Compare commits

...
Author SHA1 Message Date
Mohamed Boudra cdec809d91 fix(plugins): store idempotent parsed panel params to keep generated defaults aligned with identity 2026-12-04 15:11:25 +01:00
Mohamed Boudra 89d7895fa2 chore(plugins): remove unused EMPTY_WORKSPACE_PARAMS after rebase 2026-12-04 15:04:08 +01:00
Mohamed Boudra 40ccec39c1 fix(plugins): cache parsed panel params per contribution and target 2026-12-04 14:59:55 +01:00
Mohamed Boudra c4d1348be4 fix(plugins): evaluate panel param transforms once and preserve surface errors 2026-12-04 14:59:55 +01:00
Mohamed Boudra 54e4c15912 fix(plugins): isolate launcher panel errors and tighten test selectors 2026-12-04 14:59:22 +01:00
Mohamed Boudra b7c877129d fix(plugins): validate restored panel params against current schema 2026-12-04 14:59:22 +01:00
Mohamed Boudra abbbecc8a3 feat(plugins): add author-defined params and identity to workspace and agent panels
Lets plugin panels declare an optional Zod params schema and identity(params) coalescing function while preserving tab.state across in-place params updates and revision bumps.
2026-12-04 14:59:01 +01:00
Mohamed Boudra 3484943a7e feat(plugin): add setTitle to PluginTab (#12020)
* feat(plugin): add setTitle to PluginTab

Allow mounted workspace, agent, and file panels to override their tab title at runtime via tab.setTitle(title) and reset back to the static descriptor title on null, empty/whitespace, unmount, reload, or unavailability.

* fix(app): preserve mount-effect tab title and modified state

* fix(app): reset file panel attributes on reload and render error

* test(app): add composerPillItems to navigation test plugin fixture
2026-12-04 20:57:22 +07:00
Mohamed Boudra 55bba06161 feat(plugins): expose openScreen on panel and screen props (#12021)
* feat(plugins): expose openScreen on panel and screen props

Adds top-level openScreen({ screenId, params? }) to PluginPanelProps (covering workspace, agent, and file panels) and PluginScreenProps, matching sidebar items and popovers. Built-in file panels share BuiltinFilePanelProps without plugin-owned navigation capabilities.

* docs(plugins): document app version guidance for panel/screen openScreen

* refactor(plugins): use object params in screen navigation and ports in unit tests
2026-12-04 20:27:18 +07:00
Mohamed Boudra 4863e7e761 feat(plugins): add declarative addComposerPillItem, ComposerPill, and fix button store updates (#12019)
* feat(plugins): add addComposerPillItem, ComposerPill, and fix button store updates

* fix(plugins): encode submenu page IDs and anchor fallback composer popovers

* docs(plugins): add addComposerPillItem to migration guide and dedupe buttonPageId test
2026-12-04 20:26:12 +07:00
Mohamed Boudra ad9073dc8a test(e2e): hold all running agent updates until release in consecutive turns spec (#12034)
Since PR #12011 moved lastUserMessageAt updates and emitState(agent) to the SQLite user_message commit callback, submitting a follow-up prompt emits a second agent_update(status: running) after the initial running snapshot.

holdNextAgentUpdate() cleared its pending hold after the first match, letting that second running snapshot reach the browser before turn_started or send_agent_message_response were released and causing turn-working-elapsed to mount early.

Add holdAgentUpdates/releaseHeldAgentUpdates to hold every matching agent_update until explicitly released in arrival order, preserving all release-order assertions in agent-consecutive-turns.spec.ts.
2026-12-04 20:26:06 +07:00
paseo-bot[bot]andClaude Opus 5.5 35f0ff6ff1 Stop the relay E2E from losing its port to a parallel test (#12017)
* test(relay): let wrangler pick the relay port in the relay E2E

The relay E2E reserved a free port, closed it, then started wrangler on it.
Test files run three at a time, and another file could bind the port in
between: workerd failed with "Address already in use" and the test failed
with "Local relay did not stop". Wrangler now binds port 0 itself and the
test reads the port from its "Ready on" line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(relay): read the relay port from a complete line, keep startup errors

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 12:00:40 +00:00
paseo-bot[bot] b31565fbf7 fix(terminal): paste once on Linux middle-click (#12025)
Mouse tracking sends the click to the terminal application, while Chromium also pastes the primary selection on release. Suppress the native paste when the application owns the press, and leave the terminal paste available for the shell or forced selection.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-04 10:43:42 +00:00
paseo-bot[bot] 8302319f54 Keep old replies out of finish notifications (#12014)
* fix(server): keep old replies out of finish notifications

A tool-only turn can finish without producing a reply. Scope the preview to the completed turn so the notification uses the existing generic body when that turn has no reply.

* fix(server): keep background finish previews through runtime refresh

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-04 10:43:19 +00:00
babo-jeongukandClaude Opus 5.5 8b0c22ca31 fix(server): persist the last user message time once a submitted prompt is recorded (#12011)
Since the timeline moved to async SQLite commits, a prompt submitted through
Paseo set lastUserMessageAt in the commit callback without emitting state.
The stored record and the live agent_state kept the previous prompt's time
until the next state change, and a daemon crash in that window left the
record stale after restart.

Set lastUserMessageAt and emit state at the timeline commit point for every
user_message, and drop the two caller-side copies of that rule.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 10:42:59 +00:00
TheCouchCommanderandCodex 26175ed408 Coalesce Gitea and Forgejo PR status polling and honor rate limits (#12004)
* Coalesce Gitea PR status polling and honor rate limits

* Honor Forgejo proxy backoff and share Actions task reads

---------

Co-authored-by: Codex <codex@localhost>
2026-12-04 09:13:03 +00:00
paseo-bot[bot] 41e21d8d5f fix(desktop): keep the workspace aligned when editing chat drafts (#11983)
Anchor the top resize strip to the titlebar edge so titlebar padding cannot create horizontal overflow. Cover Page Down in the packaged desktop smoke test.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-04 08:42:53 +00:00
paseo-bot[bot] 5700dc3ea1 Keep Android image previews sharp when zooming (#11989)
* fix(app): keep Android image previews sharp when zooming

Android decodes the image to the fitted layout size by default. A pinch scales that bitmap, so details lost during decoding cannot come back. Preserve the source resolution in the zoomable image viewer.

* Keep Android zoom detail within the native bitmap limit

* Remove the obsolete Git object in the plugin update test

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-04 08:13:02 +00:00
Mohamed Boudra aabb5764d3 ci(website): isolate website tests from typecheck and clean up E2E specs (#11992)
* ci(website): isolate website tests from typecheck and clean up E2E specs

Website Playwright runs were bundled into the required typecheck job, so WebKit downloads and website timing failures blocked unrelated PRs. Moving website unit and E2E runs into a dedicated website-tests job keeps typecheck focused on build and type verification.

Also remove layout/geometry assertions and fake-clock mockup animation tests from packages/website/e2e, keeping interactive user journeys and placement-specific checks, and align Playwright CI workers and retries with the app and desktop suites.

* ci(website): include README sponsor tables in website path filter
2026-12-04 15:12:47 +07:00
Mohamed Boudra 4fe15a6918 fix(plugins): keep Git plugin revision lookup local in blobless clones (#11999)
Switching Git plugin clones to --filter=blob:none registered a promisor remote in the cloned repository, causing rev-parse to lazily fetch unadvertised or amended-away commits from origin (without GIT_ENV or credential rewrites) instead of failing revision verification. Set GIT_NO_LAZY_FETCH=1 on revParse so revision lookups stay strictly against the cloned refs and commit graph while checkout continues fetching blobs on demand. Also route managed-source.ts changes through the browser CI path filter.
2026-12-04 14:35:36 +07:00
Mohamed Boudra 32a5dd8bad test(e2e): approve AgentChat client plugins in browser specs (#11986)
Both AgentChat browser specs (#9602) were merged without calling approveClientPluginsInUi after per-host client plugin execution approval (#11717) landed, causing all 7 tests to time out waiting for the unapproved plugin's sidebar button.
2026-12-04 13:32:30 +07:00
paseo-bot[bot] 70f374f269 fix(desktop): save the stop-on-quit migration (#11984)
Desktop applied the reset in memory on every launch until another setting was saved. Save the reset and its marker together so the settings file reflects the quit policy after the first launch.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-04 06:13:38 +00:00
e31ee658c2 Avoid downloading old files when installing Git plugins (#11980)
* perf(server): clone Git plugin sources without history blobs

- Use blobless clone filter when fetching Git plugin sources to improve install performance
- Add POSIX test verification for blobless git operations

Co-authored-by: RoundRedDot <roundreddot@gmail.com>

* fix(server): preserve credentials during filtered plugin checkout

Co-authored-by: RoundRedDot <roundreddot@gmail.com>

* Merge remote-tracking branch 'origin/main' into fix/plugin-blobless-auth-review

# Conflicts:
#	packages/server/src/server/plugins/managed-source.posix.test.ts

Co-authored-by: RoundRedDot <roundreddot@gmail.com>

* refactor(server): use named Git checkout arguments

Co-authored-by: RoundRedDot <roundreddot@gmail.com>

* Name the bare Git fixture explicitly

Co-authored-by: luke <luopeihuan@gmail.com>

---------

Co-authored-by: luke <luopeihuan@gmail.com>
Co-authored-by: RoundRedDot <roundreddot@gmail.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-04 06:12:59 +00:00
paseo-bot[bot] acde63e614 test(terminal): prove an obsolete worker's program gone by its socket, not its pid (#11967)
On Windows the inspector reports no birth times, so the hard-cut test
could only prove the program gone by its pid not answering. Windows
reuses a freed pid at once, so a busy runner could keep the pid alive
under another process for the whole 10 s wait. The program now listens
on a socket of its own, and the test waits for that socket to close.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-04 06:00:53 +00:00
paseo-bot[bot] 25d9ed2985 fix(app): collapse turns with plugin-rendered work (#11974)
Calculate the summary from the work each card represents so a completed turn folds when a plugin renders its tools and reasoning.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-04 05:12:58 +00:00
128 changed files with 7248 additions and 1420 deletions
+11 -1
View File
@@ -72,7 +72,7 @@ browser:
- "packages/server/src/server/agent/providers/codex-app-server-agent.ts"
- "packages/server/src/server/agent/providers/claude/agent.ts"
- "packages/server/src/server/agent/plugin-provider.ts"
- "packages/server/src/server/plugins/{index,plugin-process,plugin-process-protocol,runtime}.ts"
- "packages/server/src/server/plugins/{index,managed-source,plugin-process,plugin-process-protocol,runtime}.ts"
- "packages/server/src/executable-resolution/**"
- "packages/plugin/src/server/provider.ts"
- "packages/app/src/!(desktop)/**"
@@ -88,6 +88,16 @@ browser:
relay:
- "packages/relay/**"
website:
- "packages/website/**"
- "packages/protocol/**"
- "public-docs/**"
- "CHANGELOG.md"
- "CHANGELOG.zh-CN.md"
- "README*.md"
- "assets/brand/**"
- "packages/app/assets/images/editor-apps/finder.png"
# cli-tests is also a daemon end-to-end suite: it drives a real daemon, built-in
# plugins and the plugin runtime included, so their changes run it too.
cli:
+32 -10
View File
@@ -43,6 +43,7 @@ jobs:
browser: ${{ steps.filter.outputs.browser }}
relay: ${{ steps.filter.outputs.relay }}
cli: ${{ steps.filter.outputs.cli }}
website: ${{ steps.filter.outputs.website }}
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
with:
@@ -163,12 +164,11 @@ jobs:
- name: Run plugin SDK tests
run: npm run test --workspace=@getpaseo/plugin
# The locked Playwright installers do not support ubuntu-latest's Ubuntu 26.04.
typecheck:
name: typecheck
needs: changes
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.quality != 'false') }}
runs-on: ubuntu-24.04
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@@ -195,6 +195,32 @@ jobs:
- name: Typecheck all packages
run: npm run typecheck
- name: Verify public package contents
run: |
npm pack --dry-run --ignore-scripts --workspace=@getpaseo/protocol
npm pack --dry-run --ignore-scripts --workspace=@getpaseo/client
npm pack --dry-run --ignore-scripts --workspace=@getpaseo/server
# The locked Playwright installers do not support ubuntu-latest's Ubuntu 26.04.
website-tests:
name: website-tests
needs: changes
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.website != 'false') }}
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: "22"
cache: "npm"
- name: Install dependencies
run: node scripts/npm-retry.mjs ci
- name: Build protocol
run: npm run build:protocol
- name: Run website tests
run: npx vitest run packages/website/src --bail=1
@@ -222,7 +248,7 @@ jobs:
cp "${archive_debs[@]}" ~/website-browser-debs/
fi
- name: Verify website mockups
- name: Run website E2E tests
run: npm run test:e2e --workspace=@getpaseo/website
- name: Upload website test artifacts
@@ -230,16 +256,12 @@ jobs:
if: failure()
with:
name: website-playwright-results
path: packages/website/test-results/
path: |
packages/website/test-results/
packages/website/playwright-report/
if-no-files-found: ignore
retention-days: 7
- name: Verify public package contents
run: |
npm pack --dry-run --ignore-scripts --workspace=@getpaseo/protocol
npm pack --dry-run --ignore-scripts --workspace=@getpaseo/client
npm pack --dry-run --ignore-scripts --workspace=@getpaseo/server
server-tests-ubuntu:
name: server-tests (ubuntu-latest)
needs: changes
+5 -3
View File
@@ -433,7 +433,9 @@ query cache. Explicit SDK targets follow the [host API contract](../public-docs/
Workspace panels, Command Center items, and client slash commands are client contributions. The
daemon transports their compiled bundle without interpreting placement or callbacks. Panel props
contain workspace and agent IDs. Required-selector hooks read normalized client state synchronously
carry `workspaceId`, validated read-only `params` (with host-enforced `agentId` on agent panels),
`revision`, and `tab`; optional `identity(params)` sets the coalescing key on the persisted
`plugin` target. Required-selector hooks read normalized client state synchronously
and use shallow equality, so a panel does not subscribe to fields it does not render. Command
callbacks materialize their snapshots only when invoked. Contribution discovery and panel opening
never fetch active context through plugin RPC. Snapshot DTOs are deeply readonly and frozen at
@@ -442,8 +444,8 @@ runtime so plugin code cannot mutate normalized app state or a memoized selectio
current installed-plugin catalog. A missing contribution renders unavailable inside the tab.
Panels declare `locations: ["workspace", "explorer"]` to opt into Explorer hosting; omission means
workspace only. Location controls hosting, not context. An agent panel target keeps its `agentId`
when moved between hosts. Explorer configuration can create workspace-context panels and remove
existing agent-context instances, but it cannot create an agent panel without an agent-aware command.
and `params` when moved between hosts. UI launchers only offer workspace-context panels whose
`params` schema accepts `{}`.
`AgentChat` renders the agent tab's own chain (`AgentPanelContent` in
`packages/app/src/panels/agent-panel.tsx`) through `packages/app/src/agent-embed`. The chain takes
@@ -745,7 +745,8 @@ async function recordDelayedRunningTransition(
const prompt = "Second prompt keeps streaming.";
gate.holdNextAgentStreamEvent("turn_started");
gate.holdNextAgentUpdate(agent.agentId, "running");
// Hold every running snapshot until release so the prompt-commit emitState does not leak early.
gate.holdAgentUpdates(agent.agentId, "running");
gate.holdNextServerMessage("send_agent_message_response");
gate.setAgentStreamSuppressed(true);
await recordTurnFrames(page, prompt);
@@ -773,7 +774,7 @@ async function recordDelayedRunningTransition(
await expect(page.getByTestId("turn-working-elapsed")).toBeVisible();
gate.releaseHeldServerMessage("send_agent_message_response");
responseReleased = true;
gate.releaseHeldAgentUpdate(agent.agentId, "running");
gate.releaseHeldAgentUpdates(agent.agentId, "running");
snapshotReleased = true;
} else if (releaseOrder === "response-before-turn") {
gate.releaseHeldServerMessage("send_agent_message_response");
@@ -782,13 +783,13 @@ async function recordDelayedRunningTransition(
gate.releaseHeldAgentStreamEvent("turn_started");
turnReleased = true;
await expect(page.getByTestId("turn-working-elapsed")).toBeVisible();
gate.releaseHeldAgentUpdate(agent.agentId, "running");
gate.releaseHeldAgentUpdates(agent.agentId, "running");
snapshotReleased = true;
} else {
gate.releaseHeldServerMessage("send_agent_message_response");
responseReleased = true;
await recordPaintsFor(page, 80);
gate.releaseHeldAgentUpdate(agent.agentId, "running");
gate.releaseHeldAgentUpdates(agent.agentId, "running");
snapshotReleased = true;
await expect(page.getByTestId("turn-working-elapsed")).toBeVisible();
gate.releaseHeldAgentStreamEvent("turn_started");
@@ -804,7 +805,7 @@ async function recordDelayedRunningTransition(
return { frames, checkpoints };
} finally {
if (!turnReleased) gate.releaseHeldAgentStreamEvent("turn_started");
if (!snapshotReleased) gate.releaseHeldAgentUpdate(agent.agentId, "running");
if (!snapshotReleased) gate.releaseHeldAgentUpdates(agent.agentId, "running");
if (!responseReleased) gate.releaseHeldServerMessage("send_agent_message_response");
gate.setAgentStreamSuppressed(false);
}
@@ -10,6 +10,7 @@ import {
type MockAgentWorkspace,
} 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 = "agent-chat-focus-e2e";
@@ -135,6 +136,7 @@ async function withEmbeds(
await client.patchDaemonConfig({ pluginsEnabled: true });
await client.installDirectoryPlugin(directory);
await gotoAppShell(page);
await approveClientPluginsInUi(page, [PLUGIN_ID]);
await page.getByRole("button", { name: SCREEN_TITLE, exact: true }).click();
const embed = (agentId: string) => page.getByTestId(`embed-${agentId}`);
for (const agent of agents) {
@@ -2,6 +2,7 @@ import { expect, test, type Page } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
import { approveClientPluginsInUi } from "../support/helpers/plugin-execution-approval";
import { copyPluginExample } from "../support/helpers/plugin-fixture";
const PLUGIN_ID = "agent-chat-example";
@@ -14,6 +15,7 @@ function embed(page: Page) {
async function openAgentInEmbed(page: Page): Promise<void> {
await gotoAppShell(page);
await approveClientPluginsInUi(page, [PLUGIN_ID]);
await page.getByRole("button", { name: "Agents", exact: true }).click();
await page
.getByTestId("example-agent-list")
@@ -0,0 +1,350 @@
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import type { Locator, Page } from "@playwright/test";
import { expect, test } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { openCommandCenter } from "../support/helpers/command-center";
import { buildAgentRoute } from "../support/helpers/mock-agent";
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
import { approveClientPluginsInUi } from "../support/helpers/plugin-execution-approval";
import { pluginRequirements } from "../support/helpers/plugin-fixture";
import { seedWorkspace } from "../support/helpers/seed-client";
const PLUGIN_ID = "composer-pill-items-e2e";
const WIDE = { width: 1440, height: 900 };
const COMPACT = { width: 390, height: 844 };
function pluginSource(workspaceId: string, agentId: string): string {
return `import React from "react";
import { Pressable, Text, View } from "react-native";
import { useWorkspace } from "@getpaseo/plugin/client";
import { ComposerPill } from "@getpaseo/plugin/client/ui";
function InboxScreen({ theme, params }) {
return (
<View style={{ flex: 1, padding: 24, gap: 8 }}>
<Text style={{ color: theme.colors.foreground }}>Inbox screen for {params.agentId}</Text>
</View>
);
}
function InboxPopover({ theme, layout, close, openScreen }) {
const workspaceName = useWorkspace(${JSON.stringify(workspaceId)}, (w) => w.name);
return (
<View style={{ gap: 10 }}>
<Text style={{ color: theme.colors.foreground, fontSize: 16 }}>Inbox decisions</Text>
<Text style={{ color: theme.colors.foregroundMuted }}>Workspace: {workspaceName}</Text>
<Text style={{ color: theme.colors.foregroundMuted }}>
Presentation: {layout.compact ? "compact" : "wide"}
</Text>
<Pressable
accessibilityRole="button"
accessibilityLabel="Open inbox screen"
onPress={() => openScreen({ screenId: "inbox", params: { agentId: ${JSON.stringify(agentId)} } })}
>
<Text style={{ color: theme.colors.foreground }}>Open screen</Text>
</Pressable>
<Pressable
accessibilityRole="button"
accessibilityLabel="Close inbox popover"
onPress={close}
>
<Text style={{ color: theme.colors.foreground }}>Done</Text>
</Pressable>
</View>
);
}
function LivePopover({ theme, close }) {
return (
<View style={{ gap: 8 }}>
<Text style={{ color: theme.colors.foreground }}>Live popover content</Text>
<Pressable
accessibilityRole="button"
accessibilityLabel="Trigger live update"
onPress={() => updateLivePopover?.()}
>
<Text style={{ color: theme.colors.foreground }}>Update</Text>
</Pressable>
<Pressable
accessibilityRole="button"
accessibilityLabel="Close live popover"
onPress={close}
>
<Text style={{ color: theme.colors.foreground }}>Close</Text>
</Pressable>
</View>
);
}
let updateLivePopover = null;
function QuietPill({ workspaceId }) {
const name = useWorkspace(workspaceId, (w) => w.name);
if (name !== "Show quiet pill") return null;
return <ComposerPill icon="Sparkles" label="Quiet" onPress={() => {}} />;
}
let finishAction = () => {};
let actionAttempts = 0;
function ActionPill() {
const [checks, setChecks] = React.useState(0);
return (
<ComposerPill
icon="Play"
label={checks === 0 ? "Run check" : "Checks · " + checks}
title="Run check action"
onPress={async () => {
actionAttempts += 1;
if (actionAttempts === 1) throw new Error("Action check failed");
await new Promise((resolve) => {
finishAction = resolve;
});
setChecks((n) => n + 1);
}}
/>
);
}
function InboxPill({ openPopover }) {
return (
<ComposerPill
icon="Inbox"
label="2 decisions"
onPress={() => openPopover(InboxPopover)}
/>
);
}
export default function contribute(client) {
const workspaceId = ${JSON.stringify(workspaceId)};
const agentId = ${JSON.stringify(agentId)};
client.addScreen({ id: "inbox", title: "Inbox Screen", Component: InboxScreen });
const removeQuiet = client.addComposerPillItem({ id: "quiet", title: "Quiet", Component: QuietPill });
const removeAction = client.addComposerPillItem({ id: "action", title: "Run check", Component: ActionPill });
const removeInbox = client.addComposerPillItem({ id: "inbox", title: "Inbox decisions", Component: InboxPill });
const live = client.addComposerPill({
id: "live-popover",
workspaceId,
agentId,
button: {
title: "Live popover",
icon: "Eye",
label: "Live",
behavior: { kind: "popover", Content: LivePopover },
},
});
const dynamicMenu = client.addComposerPill({
id: "dynamic-menu",
workspaceId,
agentId,
button: {
title: "Dynamic menu",
icon: "List",
label: "Decisions",
behavior: {
kind: "menu",
items: [
{
kind: "item",
id: "D42",
title: "Decision D42",
behavior: {
kind: "action",
onPress() {
dynamicMenu.update({ label: "Picked D42" });
},
},
},
],
},
},
});
client.addCommandCenterItem({
id: "finish-check",
title: "Finish check action",
icon: "Check",
context: "workspace",
onSelect: () => finishAction(),
});
updateLivePopover = () =>
live.update({
label: "Live · 2",
behavior: { kind: "popover", Content: LivePopover },
});
return () => {
finishAction();
removeQuiet();
removeAction();
removeInbox();
live.remove();
dynamicMenu.remove();
};
}
`;
}
async function runCommand(page: Page, title: string) {
const panel = await openCommandCenter(page);
await panel.getByTestId("command-center-input").fill(title);
await panel.getByRole("button", { name: title, exact: true }).click();
await expect(panel).not.toBeVisible();
}
async function expectStill(subject: Locator) {
let previous: Buffer | null = null;
await expect
.poll(
async () => {
const current = await subject.screenshot();
const still = previous !== null && current.equals(previous);
previous = current;
return still;
},
{ intervals: [150] },
)
.toBe(true);
}
async function qaScreenshot(page: Page, name: string) {
const directory = process.env.PASEO_QA_SCREENSHOT_DIR;
if (!directory) return;
await page.waitForTimeout(300);
await page.screenshot({ path: path.join(directory, `${name}.png`) });
}
test("declarative addComposerPillItem + ComposerPill and imperative pill fixes work end-to-end", async ({
page,
}) => {
test.setTimeout(180_000);
const workspace = await seedWorkspace({ repoPrefix: "composer-pill-items-" });
const agent = await workspace.client.createAgent({
provider: "mock",
cwd: workspace.repoPath,
workspaceId: workspace.workspaceId,
title: "Declarative composer pills",
model: "e2e-fast-stream",
modeId: "load-test",
});
const client = await connectNewWorkspaceDaemonClient({ ownProjects: false });
const config = await client.getDaemonConfig();
const directory = await mkdtemp(path.join(tmpdir(), "paseo-pill-items-"));
try {
await writeFile(
path.join(directory, "paseo-plugin.json"),
JSON.stringify({ id: PLUGIN_ID, requirements: pluginRequirements }),
);
await writeFile(
path.join(directory, "index.client.tsx"),
pluginSource(workspace.workspaceId, agent.id),
);
await client.patchDaemonConfig({ pluginsEnabled: true });
await client.installDirectoryPlugin(directory);
await page.setViewportSize(WIDE);
await gotoAppShell(page);
await approveClientPluginsInUi(page, [PLUGIN_ID]);
await page.goto(buildAgentRoute(workspace.workspaceId, agent.id));
const actionPill = page.getByRole("button", { name: "Run check action", exact: true });
const inboxPill = page.getByRole("button", { name: "2 decisions", exact: true });
await expect(actionPill).toBeVisible();
await expect(inboxPill).toBeVisible();
await test.step("null items leave no empty gap in the composer track", async () => {
await expect(page.getByRole("button", { name: "Quiet", exact: true })).toHaveCount(0);
const actionBox = (await actionPill.boundingBox())!;
const inboxBox = (await inboxPill.boundingBox())!;
expect(Math.abs(actionBox.y - inboxBox.y)).toBeLessThan(2);
expect(actionBox.height).toBeGreaterThanOrEqual(32);
expect(inboxBox.height).toBeGreaterThanOrEqual(32);
// 4px track gap between adjacent pills with no empty wrapper gap in between.
expect(inboxBox.x - (actionBox.x + actionBox.width)).toBeLessThanOrEqual(8);
await qaScreenshot(page, "01-desktop-track");
});
await test.step("ComposerPill shows error toast on rejection, enters pending busy state, and recovers", async () => {
await actionPill.click();
await expect(page.getByText("Action check failed", { exact: true })).toBeVisible();
await expect(actionPill).toBeEnabled();
await actionPill.click();
await expect(actionPill).toBeDisabled();
await expect(actionPill).toHaveAttribute("aria-busy", "true");
await qaScreenshot(page, "02-desktop-pill-pending");
await runCommand(page, "Finish check action");
await expect(actionPill).toBeEnabled();
await expect(actionPill).toContainText("Checks · 1");
});
await test.step("openPopover anchors above the pill on desktop, dismisses cleanly, and openScreen navigates", async () => {
await inboxPill.click();
const popoverTitle = page.getByText("Inbox decisions", { exact: true });
await expect(popoverTitle).toBeInViewport();
await expect(page.getByText("Presentation: wide", { exact: true })).toBeVisible();
await expectStill(popoverTitle);
const pillBox = (await inboxPill.boundingBox())!;
const popoverBox = (await page
.getByTestId(`plugin-composer-pill-${PLUGIN_ID}-inbox-popover`)
.boundingBox())!;
expect(popoverBox.y + popoverBox.height).toBeLessThanOrEqual(pillBox.y + 1);
expect(Math.abs(popoverBox.x - pillBox.x)).toBeLessThan(80);
await qaScreenshot(page, "03-desktop-popover");
await page.keyboard.press("Escape");
await expect(popoverTitle).toHaveCount(0);
await inboxPill.click();
await expect(popoverTitle).toBeVisible();
await page.getByRole("button", { name: "Open inbox screen", exact: true }).click();
await expect(popoverTitle).toHaveCount(0);
await expect(page.getByText(`Inbox screen for ${agent.id}`, { exact: true })).toBeVisible();
await page.getByTestId("plugin-surface-close").click();
await expect(inboxPill).toBeVisible();
});
await test.step("imperative PluginButtonStore fixes: same-Content popover stays open on update and dynamic menu IDs work", async () => {
const livePill = page.getByRole("button", { name: "Live popover", exact: true });
await livePill.click();
await expect(page.getByText("Live popover content", { exact: true })).toBeVisible();
await page.getByRole("button", { name: "Trigger live update", exact: true }).click();
await expect(livePill).toContainText("Live · 2");
await expect(page.getByText("Live popover content", { exact: true })).toBeVisible();
await page.getByRole("button", { name: "Close live popover", exact: true }).click();
await expect(page.getByText("Live popover content", { exact: true })).toHaveCount(0);
const menuPill = page.getByRole("button", { name: "Dynamic menu", exact: true });
await menuPill.click();
await page.getByRole("menuitem", { name: "Decision D42", exact: true }).click();
await expect(menuPill).toContainText("Picked D42");
});
await test.step("on compact layouts openPopover renders a bottom sheet and dismisses cleanly", async () => {
await page.setViewportSize(COMPACT);
await expect(inboxPill).toBeVisible();
await inboxPill.click();
const compactLabel = page.getByText("Presentation: compact", { exact: true });
await expect(compactLabel).toBeInViewport();
const sheetBox = (await compactLabel.boundingBox())!;
expect(sheetBox.y).toBeGreaterThan(COMPACT.height / 2);
await qaScreenshot(page, "04-compact-sheet");
await page.getByRole("button", { name: "Close inbox popover", exact: true }).click();
await expect(compactLabel).toHaveCount(0);
});
} finally {
await client.removePlugin(PLUGIN_ID).catch(() => undefined);
await client.patchDaemonConfig({ pluginsEnabled: config.config.pluginsEnabled });
await client.close();
await rm(directory, { recursive: true, force: true });
await workspace.cleanup();
}
});
@@ -27,7 +27,10 @@ import {
} from "@getpaseo/plugin/client";
import { useQueryClient } from "@tanstack/react-query";
import { DocumentFrame, Loading } from "@getpaseo/plugin/client/ui";
function Pdf({ file, workspaceId }) {
function FileDetailsScreen({ params }) {
return <View><Text>File screen: {params.file}</Text></View>;
}
function Pdf({ file, workspaceId, openScreen }) {
usePaseo();
useQueryClient();
const workspace = useWorkspace(workspaceId, value => ({ id: value.id }));
@@ -44,6 +47,9 @@ function Pdf({ file, workspaceId }) {
<Text>Path {file.path}</Text>
<Text>Bytes {bytes.bytes.length}; URL bytes {urlBytes}</Text>
<Text>Workspace {workspace?.id}</Text>
<Pressable accessibilityRole="button" onPress={() => openScreen({ screenId: "details", params: { file: file.name } })}>
<Text>Open screen from file panel</Text>
</Pressable>
<DocumentFrame url={href} testID="plugin-pdf-frame" />
</View>;
}
@@ -69,6 +75,7 @@ function Markdown({ file, tab }) {
</View>;
}
export default function contribute(client) {
client.addScreen({ id: "details", title: "File details", Component: FileDetailsScreen });
client.addFilePanel({ id: "pdf", title: "PDF", icon: "FileText",
files: { extensions: ["pdf", "txt"] }, Component: Pdf });
client.addFilePanel({ id: "markdown", title: "Plugin Markdown", icon: "FileText",
@@ -92,6 +99,16 @@ async function associateMarkdownWithPlugin(page: Page) {
async function editMarkdownThroughPlugin(page: Page) {
await page.getByRole("button", { name: "Edit Markdown through plugin", exact: true }).click();
}
async function openFileDetailsScreenFromPanel(page: Page, name: string) {
await page.getByRole("button", { name: "Open screen from file panel", exact: true }).click();
await expect(page).toHaveURL(
new RegExp(`/plugin/${PLUGIN_ID}/surface/details\\?param\\.file=${encodeURIComponent(name)}$`),
);
await expect(page.getByText(`File screen: ${name}`, { exact: true })).toBeVisible();
await page.getByTestId("plugin-surface-close").click();
await expect(page.getByText(`PDF plugin: ${name}`, { exact: true })).toBeVisible();
}
/** Opens the tab with Paseo's Markdown panel from "Open with…" and shows its Source view. */
async function openBuiltinMarkdownSource(page: Page, name: string) {
await page.getByTestId(`workspace-tab-file_${name}`).first().click({ button: "right" });
@@ -152,6 +169,7 @@ test("directory plugins render PDF bytes and write Markdown through the file han
const pdfScreenshot = testInfo.outputPath("plugin-pdf-web.png");
await page.screenshot({ path: pdfScreenshot });
await testInfo.attach("plugin-pdf-web", { path: pdfScreenshot, contentType: "image/png" });
await openFileDetailsScreenFromPanel(page, "report.pdf");
// A plugin panel claiming a text file competes with Source, so Paseo asks over the plugin.
await openWorkspaceFile(page, "bytes.txt");
@@ -690,16 +690,20 @@ async function updateGitPlugin(page: Page, repository: string) {
async function failUpdateFromPluginPage(page: Page, repository: string) {
await publishGitPluginChange(repository, "Git plugin v3");
await page.reload();
const update = page.getByTestId("plugin-update").filter({ visible: true });
await expect(update).toHaveText("Update");
// Rewriting the commit the page checked leaves its update pointing at a commit the remote no
// longer serves. The next check offers the rewritten commit.
const update = page.getByRole("button", { name: "Update", exact: true });
await expect(update).toBeVisible();
// Remove the advertised commit from the fixture. A file:// remote can still serve an
// amended-away commit by SHA while its object remains in the repository.
execFileSync("git", ["commit", "--amend", "-m", "Git plugin v3, amended"], {
cwd: repository,
stdio: "ignore",
});
execFileSync("git", ["-c", "gc.reflogExpireUnreachable=now", "gc", "--prune=now"], {
cwd: repository,
stdio: "ignore",
});
await update.click();
await expect(update).toHaveText("Retry");
await expect(page.getByRole("button", { name: "Retry", exact: true })).toBeVisible();
await expect(page.getByText(/Git command failed/)).toBeVisible();
}
@@ -0,0 +1,288 @@
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import type { Locator, TestInfo } from "@playwright/test";
import { expect, test, type Page } from "../support/fixtures";
import { openCommandCenter } from "../support/helpers/command-center";
import { openFileExplorer, openFileFromExplorer } from "../support/helpers/file-explorer";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
import { approveClientPluginsInUi } from "../support/helpers/plugin-execution-approval";
import { pluginRequirements } from "../support/helpers/plugin-fixture";
const PLUGIN_ID = "tab-set-title-e2e";
const WIDE = { width: 1440, height: 900 };
const CLIENT_SOURCE = `import React from "react";
import { Pressable, Text, View } from "react-native";
import type {
PluginAgentPanelProps,
PluginClientContext,
PluginFilePanelProps,
PluginWorkspacePanelProps,
} from "@getpaseo/plugin/client";
function TitleControls({
prefix,
nextTitle,
tab,
}: {
prefix: string;
nextTitle: string;
tab: PluginWorkspacePanelProps["tab"];
}) {
return (
<View style={{ padding: 16, gap: 8 }}>
<Text>{prefix} panel</Text>
<Pressable
accessibilityRole="button"
onPress={() => tab.setTitle(" " + nextTitle + " ")}
>
<Text>Set {prefix} title</Text>
</Pressable>
<Pressable
accessibilityRole="button"
onPress={() => tab.setTitle(" ")}
>
<Text>Whitespace {prefix} title</Text>
</Pressable>
<Pressable
accessibilityRole="button"
onPress={() => tab.setTitle(null)}
>
<Text>Reset {prefix} title</Text>
</Pressable>
</View>
);
}
function StatusPanel({ tab }: PluginWorkspacePanelProps) {
return <TitleControls prefix="status" nextTitle="Status (3)" tab={tab} />;
}
function ExplorerStatusPanel({ tab }: PluginWorkspacePanelProps) {
return <TitleControls prefix="explorer" nextTitle="Explorer (7)" tab={tab} />;
}
function InspectorPanel({ tab }: PluginAgentPanelProps) {
return <TitleControls prefix="agent" nextTitle="Inspector: live" tab={tab} />;
}
function NotesTxtPanel({ tab }: PluginFilePanelProps) {
return <TitleControls prefix="file" nextTitle="Readout" tab={tab} />;
}
export default function contribute(client: PluginClientContext) {
client.addWorkspacePanel({
id: "status",
title: "Status",
icon: "PanelsTopLeft",
locations: ["workspace", "explorer"],
Component: StatusPanel,
});
client.addWorkspacePanel({
id: "explorer-status",
title: "Explorer status",
icon: "PanelsTopLeft",
locations: ["workspace", "explorer"],
Component: ExplorerStatusPanel,
});
client.addAgentPanel({
id: "inspector",
title: "Inspector",
icon: "Scan",
locations: ["workspace", "explorer"],
Component: InspectorPanel,
});
client.addFilePanel({
id: "txt-viewer",
title: "Custom TXT",
icon: "FileText",
files: { extensions: ["txt"] },
Component: NotesTxtPanel,
});
client.addCommandCenterItem({
id: "open-status",
title: "Open status panel",
icon: "PanelsTopLeft",
context: "workspace",
onSelect({ workspaceLayout }) {
workspaceLayout.open({ panelId: "status" });
},
});
client.addCommandCenterItem({
id: "open-explorer-status",
title: "Open explorer status panel",
icon: "PanelsTopLeft",
context: "workspace",
onSelect({ workspaceLayout }) {
workspaceLayout.open({ panelId: "explorer-status" }, { placement: { type: "explorer" } });
},
});
client.addCommandCenterItem({
id: "open-inspector",
title: "Open inspector panel",
icon: "Scan",
context: "agent",
onSelect({ workspaceLayout, agent }) {
workspaceLayout.open({ panelId: "inspector", params: { agentId: agent.id } });
},
});
return () => {};
}
`;
async function runCommand(page: Page, title: string): Promise<void> {
const panel = await openCommandCenter(page);
await panel.getByTestId("command-center-input").fill(title);
await panel.getByRole("button", { name: title, exact: true }).click();
await expect(panel).not.toBeVisible();
}
function mainPane(page: Page): Locator {
return page.locator('[data-testid^="workspace-pane-"]').filter({ visible: true }).first();
}
function explorer(page: Page): Locator {
return page.getByTestId("workspace-explorer-sidebar");
}
function tabChip(scope: Locator, idPart: string): Locator {
return scope
.locator(
`[data-testid^="workspace-tab-"][data-testid*="${idPart}"]:not([data-testid^="workspace-tab-tooltip"]):not([data-testid^="workspace-tab-modified"])`,
)
.first();
}
async function capture(page: Page, testInfo: TestInfo, name: string): Promise<void> {
const screenshot = testInfo.outputPath(`${name}.png`);
await page.screenshot({ path: screenshot });
await testInfo.attach(name, { path: screenshot, contentType: "image/png" });
}
test("PluginTab.setTitle updates and resets tab labels in main pane, Explorer, agent, and file panels", async ({
page,
}, testInfo) => {
test.setTimeout(180_000);
const directory = await mkdtemp(path.join(tmpdir(), "paseo-plugin-tab-set-title-"));
const workspace = await seedMockAgentWorkspace({
repoPrefix: "plugin-tab-set-title-",
title: "Tab Title Agent",
repo: {
files: [{ path: "notes.txt", content: "Sample notes\n" }],
},
});
const client = await connectNewWorkspaceDaemonClient({ ownProjects: false });
const previousConfig = await client.getDaemonConfig();
await writeFile(
path.join(directory, "paseo-plugin.json"),
JSON.stringify({ id: PLUGIN_ID, requirements: pluginRequirements }),
);
await writeFile(path.join(directory, "index.client.tsx"), CLIENT_SOURCE);
try {
await client.patchDaemonConfig({ pluginsEnabled: true });
await client.installDirectoryPlugin(directory);
await page.setViewportSize(WIDE);
await openAgentRoute(page, {
workspaceId: workspace.workspaceId,
agentId: workspace.agentId,
});
await approveClientPluginsInUi(page, [PLUGIN_ID]);
await test.step("main pane workspace panel sets, trims, clears, and resets title + tooltip", async () => {
await runCommand(page, "Open status panel");
const tab = tabChip(mainPane(page), "_status");
await expect(tab).toContainText("Status");
await expect(tab).toHaveAttribute("aria-label", "Status");
await page.getByRole("button", { name: "Set status title", exact: true }).click();
await expect(tab).toContainText("Status (3)");
await expect(tab).toHaveAttribute("aria-label", "Status (3)");
await expect.poll(() => page.title()).toBe("Status (3)");
await tab.hover();
await expect(page.getByText("Status (3)").last()).toBeVisible();
await capture(page, testInfo, "main-pane-title-override");
await page.getByRole("button", { name: "Whitespace status title", exact: true }).click();
await expect(tab).toContainText("Status");
await expect(tab).toHaveAttribute("aria-label", "Status");
await page.getByRole("button", { name: "Set status title", exact: true }).click();
await expect(tab).toContainText("Status (3)");
await page.getByRole("button", { name: "Reset status title", exact: true }).click();
await expect(tab).toContainText("Status");
await expect.poll(() => page.title()).toBe("Status");
});
await test.step("Explorer workspace panel sets and resets title", async () => {
await runCommand(page, "Open explorer status panel");
const explorerTab = tabChip(explorer(page), "explorer-status");
await expect(explorerTab).toContainText("Explorer status");
await expect(explorerTab).toHaveAttribute("aria-label", "Explorer status");
await page.getByRole("button", { name: "Set explorer title", exact: true }).click();
await expect(explorerTab).toContainText("Explorer (7)");
await expect(explorerTab).toHaveAttribute("aria-label", "Explorer (7)");
await capture(page, testInfo, "explorer-title-override");
await page.getByRole("button", { name: "Reset explorer title", exact: true }).click();
await expect(explorerTab).toContainText("Explorer status");
await expect(explorerTab).toHaveAttribute("aria-label", "Explorer status");
});
await test.step("agent panel sets and resets title", async () => {
await mainPane(page).getByTestId(`workspace-tab-agent_${workspace.agentId}`).click();
await runCommand(page, "Open inspector panel");
const agentTab = tabChip(mainPane(page), "inspector");
await expect(agentTab).toContainText("Inspector");
await page.getByRole("button", { name: "Set agent title", exact: true }).click();
await expect(agentTab).toContainText("Inspector: live");
await page.getByRole("button", { name: "Reset agent title", exact: true }).click();
await expect(agentTab).toContainText("Inspector");
});
await test.step("file panel sets and resets title", async () => {
await openFileExplorer(page);
await openFileFromExplorer(page, "notes.txt");
await expect(page.getByText("Open .txt files with", { exact: true })).toBeVisible();
await page.keyboard.press("Escape");
await expect(page.getByText("Open .txt files with", { exact: true })).toBeHidden();
const fileTab = mainPane(page).getByTestId("workspace-tab-file_notes.txt");
await expect(fileTab).toContainText("notes.txt");
await page.getByRole("button", { name: "Set file title", exact: true }).click();
await expect(fileTab).toContainText("Readout");
await expect(fileTab).toHaveAttribute("aria-label", "Readout");
await page.getByRole("button", { name: "Reset file title", exact: true }).click();
await expect(fileTab).toContainText("notes.txt");
await expect(fileTab).toHaveAttribute("aria-label", "notes.txt");
});
await test.step("removing the plugin clears active title override to Plugin unavailable", async () => {
await tabChip(mainPane(page), "_status").click();
await page.getByRole("button", { name: "Set status title", exact: true }).click();
const tab = tabChip(mainPane(page), "_status");
await expect(tab).toContainText("Status (3)");
await client.removePlugin(PLUGIN_ID);
await expect(tab).toContainText("Plugin unavailable", { timeout: 30_000 });
await expect(tab).toHaveAttribute("aria-label", "This plugin panel is unavailable");
});
} finally {
await client.removePlugin(PLUGIN_ID).catch(() => undefined);
await client
.patchDaemonConfig({ pluginsEnabled: previousConfig.config.pluginsEnabled ?? false })
.catch(() => undefined);
await client.close().catch(() => undefined);
await workspace.cleanup().catch(() => undefined);
await rm(directory, { recursive: true, force: true });
}
});
@@ -326,3 +326,286 @@ test("a file a plugin opens in another workspace waits there on a phone", async
});
});
});
const PARAMS_AND_IDENTITY_ENTRY = `import {
type PluginClientContext,
type PluginWorkspacePanelProps,
useTabState,
useWorkspaceLayout,
} from "@getpaseo/plugin/client";
import { Pressable, Text, View } from "react-native";
import { z } from "zod";
const decisionParams = z.object({ decisionId: z.string() });
const decisionStateSchema = z.object({ note: z.string() });
function DecisionsPanel({
params,
revision,
tab,
theme,
}: PluginWorkspacePanelProps<z.infer<typeof decisionParams>>) {
const [state, setState] = useTabState(tab, decisionStateSchema, { note: "initial" });
return (
<View style={{ flex: 1, padding: 16, gap: 8 }}>
<Text style={{ color: theme.colors.foreground }}>
{\`decision:\${params.decisionId}|rev:\${revision}|state:\${state.note}\`}
</Text>
<Pressable
accessibilityRole="button"
onPress={() => setState({ note: "pinned" })}
>
<Text style={{ color: theme.colors.foreground }}>Pin decision state</Text>
</Pressable>
</View>
);
}
const prParams = z.object({
prNumber: z.number(),
commentId: z.string().optional(),
});
function PrPanel({
workspaceId,
params,
revision,
theme,
}: PluginWorkspacePanelProps<z.infer<typeof prParams>>) {
const readBack = useWorkspaceLayout(workspaceId, (layout) => {
const found = layout.tabs.find((entry) => entry.panelId === "workspace-layout/pr" && entry.params.prNumber === params.prNumber);
return found ? JSON.stringify(found.params) : "missing";
});
return (
<View style={{ flex: 1, padding: 16, gap: 8 }}>
<Text style={{ color: theme.colors.foreground }}>
{\`pr:\${params.prNumber}|comment:\${params.commentId ?? "none"}|rev:\${revision}\`}
</Text>
<Text style={{ color: theme.colors.foregroundMuted }}>
{\`readback:\${params.prNumber}:\${readBack}\`}
</Text>
</View>
);
}
function StaticPanel({ theme }: PluginWorkspacePanelProps) {
return (
<View style={{ flex: 1, padding: 16 }}>
<Text style={{ color: theme.colors.foreground }}>Static parameterless panel</Text>
</View>
);
}
export default function contribute(client: PluginClientContext) {
client.addWorkspacePanel({
id: "decisions",
title: "Decisions",
icon: "ListChecks",
locations: ["explorer"],
params: decisionParams,
Component: DecisionsPanel,
});
client.addWorkspacePanel({
id: "pr",
title: "PR",
icon: "GitPullRequest",
params: prParams,
identity: (p) => String(p.prNumber),
Component: PrPanel,
});
client.addWorkspacePanel({
id: "static",
title: "Static",
icon: "Square",
locations: ["workspace", "explorer"],
Component: StaticPanel,
});
client.addCommandCenterItem({
id: "open-decision-d1",
title: "Open decision D1",
icon: "ListChecks",
context: "workspace",
onSelect({ workspaceLayout }) {
workspaceLayout.open({ panelId: "decisions", params: { decisionId: "D1" } });
},
});
client.addCommandCenterItem({
id: "open-decision-d2",
title: "Open decision D2",
icon: "ListChecks",
context: "workspace",
onSelect({ workspaceLayout }) {
workspaceLayout.open({ panelId: "decisions", params: { decisionId: "D2" } });
},
});
client.addCommandCenterItem({
id: "open-pr-1a",
title: "Open PR 1 comment a",
icon: "GitPullRequest",
context: "workspace",
onSelect({ workspaceLayout }) {
workspaceLayout.open({ panelId: "pr", params: { prNumber: 1, commentId: "a" } });
},
});
client.addCommandCenterItem({
id: "open-pr-2x",
title: "Open PR 2 comment x",
icon: "GitPullRequest",
context: "workspace",
onSelect({ workspaceLayout }) {
workspaceLayout.open({ panelId: "pr", params: { prNumber: 2, commentId: "x" } });
},
});
client.addCommandCenterItem({
id: "open-pr-1b",
title: "Open PR 1 comment b",
icon: "GitPullRequest",
context: "workspace",
onSelect({ workspaceLayout }) {
workspaceLayout.open({ panelId: "pr", params: { prNumber: 1, commentId: "b" } });
},
});
return () => {};
}
`;
async function expectNewTabLauncherPanelAvailability(
page: Page,
input: { present: readonly string[]; absent: readonly string[] },
): Promise<void> {
await mainPanes(page).first().getByTestId("workspace-new-tab-button").click();
const menu = page.getByTestId("workspace-new-tab-menu").filter({ visible: true });
for (const label of input.present) {
await expect(menu.getByText(label, { exact: true })).toBeVisible();
}
for (const label of input.absent) {
await expect(menu.getByText(label, { exact: true })).toHaveCount(0);
}
await page.keyboard.press("Escape");
}
async function expectDecisionsPanel(
page: Page,
input: { tabs: number; decisionId: string; revision: number; stateNote: string },
): Promise<void> {
await expect(
explorer(page)
.getByTestId("workspace-tabs-row")
.getByRole("button", { name: "Decisions", exact: true }),
).toHaveCount(input.tabs);
await expect(
explorer(page).getByText(
`decision:${input.decisionId}|rev:${input.revision}|state:${input.stateNote}`,
{ exact: true },
),
).toBeVisible();
}
async function pinDecisionState(page: Page): Promise<void> {
await explorer(page).getByRole("button", { name: "Pin decision state" }).click();
}
async function expectPrPanel(
page: Page,
input: {
tabs: number;
prNumber: number;
commentId: string;
revision: number;
persistedParams?: { prNumber: number; commentId: string };
},
): Promise<void> {
await expect(
mainPanes(page)
.first()
.getByTestId("workspace-tabs-row")
.getByRole("button", { name: "PR", exact: true }),
).toHaveCount(input.tabs);
await expect(
page.getByText(`pr:${input.prNumber}|comment:${input.commentId}|rev:${input.revision}`, {
exact: true,
}),
).toBeVisible();
if (input.persistedParams) {
await expect(
page.getByText(`readback:${input.prNumber}:${JSON.stringify(input.persistedParams)}`, {
exact: true,
}),
).toBeVisible();
}
}
test("reused Explorer panels and keyed workspace panels deliver params, identity, revision, and tab state", async ({
page,
}) => {
test.setTimeout(180_000);
const example = await copyPluginExample("workspace-layout");
await writeFile(path.join(example.directory, "index.client.tsx"), PARAMS_AND_IDENTITY_ENTRY);
const workspace = await seedMockAgentWorkspace({
repoPrefix: "plugin-params-identity-",
title: AGENT_TITLE,
repo: { files: REPO_FILES },
});
try {
await withPluginInstalled(example.directory, async () => {
await page.setViewportSize(WIDE);
await openAgentRoute(page, workspace);
await approveClientPluginsInUi(page, ["workspace-layout"]);
await test.step("parameterless launcher hides panels with required params and keeps parameterless ones", async () => {
await expectNewTabLauncherPanelAvailability(page, {
present: ["Static"],
absent: ["PR", "Decisions"],
});
});
await test.step("reused Explorer panel updates params in place, bumps revision, and preserves tab.state", async () => {
await runCommand(page, "Open decision D1");
await expectDecisionsPanel(page, {
tabs: 1,
decisionId: "D1",
revision: 1,
stateNote: "initial",
});
await pinDecisionState(page);
await expectDecisionsPanel(page, {
tabs: 1,
decisionId: "D1",
revision: 1,
stateNote: "pinned",
});
await runCommand(page, "Open decision D2");
await expectDecisionsPanel(page, {
tabs: 1,
decisionId: "D2",
revision: 2,
stateNote: "pinned",
});
});
await test.step("keyed panel opens separate tabs per identity key and updates hint params on reveal", async () => {
await runCommand(page, "Open PR 1 comment a");
await expectPrPanel(page, { tabs: 1, prNumber: 1, commentId: "a", revision: 1 });
await runCommand(page, "Open PR 2 comment x");
await expectPrPanel(page, { tabs: 2, prNumber: 2, commentId: "x", revision: 1 });
await runCommand(page, "Open PR 1 comment b");
await expectPrPanel(page, {
tabs: 2,
prNumber: 1,
commentId: "b",
revision: 2,
persistedParams: { prNumber: 1, commentId: "b" },
});
});
});
} finally {
await workspace.cleanup();
await example.cleanup();
}
});
@@ -42,17 +42,40 @@ import { useAgent, useWorkspace, openExternalUrl } from "@getpaseo/plugin/client
import { ExternalLink } from "@getpaseo/plugin/client/ui";
import { recordComposerOpen } from "./shared/rpc";
function WorkspacePanel({ workspaceId, host, layout }) {
function WorkspacePanel({ workspaceId, host, layout, openScreen }) {
const workspace = useWorkspace(workspaceId, (value) => ({ id: value.id }));
const renderCount = useRef(0);
renderCount.current += 1;
return <View><Text>Workspace bridge {workspace?.id}</Text><Text>Workspace renders {renderCount.current}</Text><Text>Host {host.id}</Text><Text>Layout {layout.compact ? "compact" : "wide"}</Text></View>;
return <View>
<Text>Workspace bridge {workspace?.id}</Text>
<Text>Workspace renders {renderCount.current}</Text>
<Text>Host {host.id}</Text>
<Text>Layout {layout.compact ? "compact" : "wide"}</Text>
<Pressable accessibilityRole="button" onPress={() => openScreen({ screenId: "details", params: { source: "workspace-panel", item: workspaceId } })}><Text>Open screen from workspace panel</Text></Pressable>
</View>;
}
function AgentPanel({ workspaceId, agentId, host, layout }) {
function AgentPanel({ workspaceId, agentId, host, layout, openScreen }) {
const workspace = useWorkspace(workspaceId, (value) => ({ id: value.id }));
const agent = useAgent(agentId, (value) => ({ id: value.id }));
return <View><Text>Agent bridge {agent?.id}</Text><Text>Workspace {workspace?.id}</Text><Text>Host {host.id}</Text><Text>Layout {layout.compact ? "compact" : "wide"}</Text></View>;
return <View>
<Text>Agent bridge {agent?.id}</Text>
<Text>Workspace {workspace?.id}</Text>
<Text>Host {host.id}</Text>
<Text>Layout {layout.compact ? "compact" : "wide"}</Text>
<Pressable accessibilityRole="button" onPress={() => openScreen({ screenId: "details", params: { source: "agent-panel", item: agentId } })}><Text>Open screen from agent panel</Text></Pressable>
</View>;
}
function DetailsScreen({ params, openScreen }) {
return <View>
<Text>{"Details screen: " + params.source + " / " + params.item}</Text>
<Pressable accessibilityRole="button" onPress={() => openScreen({ screenId: "chained", params: { from: params.source ?? "" } })}><Text>Open chained screen</Text></Pressable>
</View>;
}
function ChainedScreen({ params }) {
return <View><Text>{"Chained screen from " + params.from}</Text></View>;
}
function DirectCollisionSurface({ navigation }) {
@@ -127,6 +150,8 @@ function contributeClient(client) {
}
export default function contribute(client) {
client.addScreen({ id: "details", title: (params) => "Details: " + (params.source ?? ""), Component: DetailsScreen });
client.addScreen({ id: "chained", title: "Chained", Component: ChainedScreen });
client.addSurface("collision", DirectCollisionSurface);
client.addSurface("sidebar-destination", SidebarCollisionSurface);
client.addSidebarItem({ id: "collision", title: "Collision sidebar", icon: "Blocks", surface: "sidebar-destination" });
@@ -252,6 +277,34 @@ async function openCompactSidebar(page: Page): Promise<void> {
await expect(page.getByTestId("sidebar-search")).toBeVisible();
}
async function openPluginScreenFromButton(
page: Page,
input: {
buttonName: string;
screenId: string;
params: Record<string, string>;
expectedText: string;
},
): Promise<void> {
await page.getByRole("button", { name: input.buttonName, exact: true }).click();
const query = Object.entries(input.params)
.map(([key, value]) => `${encodeURIComponent(`param.${key}`)}=${encodeURIComponent(value)}`)
.join("&");
await expect(page).toHaveURL(
new RegExp(`/plugin/${PLUGIN_ID}/surface/${input.screenId}\\?${query.replaceAll(".", "\\.")}$`),
);
await expect(page.getByText(input.expectedText, { exact: true })).toBeVisible();
}
async function closeTopPluginScreen(
page: Page,
options: { compact?: boolean; expectedText: string },
): Promise<void> {
const testId = options.compact ? "header-back-button" : "plugin-surface-close";
await page.getByTestId(testId).filter({ visible: true }).last().click();
await expect(page.getByText(options.expectedText, { exact: true })).toBeVisible();
}
async function capture(page: Page, testInfo: TestInfo, name: string): Promise<void> {
const screenshot = testInfo.outputPath(`${name}.png`);
await page.screenshot({ path: screenshot });
@@ -338,6 +391,24 @@ test.describe("plugin workspace panels and Command Center", () => {
await expect(page.getByText(`Host ${getServerId()}`, { exact: true })).toBeVisible();
await expect(page.getByText("Layout wide", { exact: true })).toBeVisible();
await capture(page, testInfo, "plugin-workspace-panel-wide");
await openPluginScreenFromButton(page, {
buttonName: "Open screen from workspace panel",
screenId: "details",
params: { source: "workspace-panel", item: primary.workspaceId },
expectedText: `Details screen: workspace-panel / ${primary.workspaceId}`,
});
await openPluginScreenFromButton(page, {
buttonName: "Open chained screen",
screenId: "chained",
params: { from: "workspace-panel" },
expectedText: "Chained screen from workspace-panel",
});
await closeTopPluginScreen(page, {
expectedText: `Details screen: workspace-panel / ${primary.workspaceId}`,
});
await closeTopPluginScreen(page, {
expectedText: `Workspace bridge ${primary.workspaceId}`,
});
});
await test.step("plugin links open browser tabs and in-app browsing is unavailable", async () => {
@@ -475,6 +546,16 @@ test.describe("plugin workspace panels and Command Center", () => {
).toBeVisible();
await expect(page.getByText(`Host ${getServerId()}`, { exact: true })).toBeVisible();
await expect(page.getByText("Layout compact", { exact: true })).toBeVisible();
await openPluginScreenFromButton(page, {
buttonName: "Open screen from agent panel",
screenId: "details",
params: { source: "agent-panel", item: agent.id },
expectedText: `Details screen: agent-panel / ${agent.id}`,
});
await closeTopPluginScreen(page, {
compact: true,
expectedText: `Agent bridge ${agent.id}`,
});
});
await test.step("removing the active plugin renders the panel unavailable", async () => {
@@ -0,0 +1,59 @@
import assert from "node:assert/strict";
import { readFileSync, writeFileSync } from "node:fs";
import { PNG } from "pngjs";
// Generate resolution-chart.png in an Android test workspace with the "fixture" command.
// Open it from Files on a 1080 x 2400 emulator, pinch out by 4x at (540, 1250),
// then pass the zoomed screenshot from adb exec-out screencap -p to the "check" command.
// Generate a 6,000 x 5,000 PNG with "fixture-large" to exercise Android's bitmap size
// limit. Open it from Files at fit and pass the screenshot to the same "check" command.
// Pass the width and height from Expo Image's onLoad event to "check-decode" on an
// emulator with the default 100 MiB canvas limit.
const [command, path, height] = process.argv.slice(2);
assert.ok(
path && ["fixture", "fixture-large", "check", "check-decode"].includes(command),
"Use fixture <png>, fixture-large <png>, check <png>, or check-decode <width> <height>",
);
if (command === "check-decode") {
const width = Number(path);
const decodedHeight = Number(height);
assert.ok(width > 0 && decodedHeight > 0, "Provide the positive decoded dimensions");
assert.ok(
width * decodedHeight * 4 <= 100 * 1024 * 1024,
`Decoded bitmap exceeds 100 MiB at ${width} × ${decodedHeight}`,
);
} else if (command === "fixture" || command === "fixture-large") {
const size =
command === "fixture-large" ? { width: 6000, height: 5000 } : { width: 4000, height: 3000 };
const chart = new PNG(size);
const stripeWidth = command === "fixture-large" ? 240 : 3;
for (let x = 0; x < chart.width; x++) {
const shade = Math.floor(x / stripeWidth) % 2 === 0 ? 0 : 255;
chart.data.set([shade, shade, shade, 255], x * 4);
}
for (let y = 1; y < chart.height; y++) {
chart.data.copy(chart.data, y * chart.width * 4, 0, chart.width * 4);
}
writeFileSync(path, PNG.sync.write(chart));
} else {
const screenshot = PNG.sync.read(readFileSync(path));
assert.equal(screenshot.width, 1080, "Use a 1080 x 2400 emulator");
assert.equal(screenshot.height, 2400, "Use a 1080 x 2400 emulator");
// The center of each stripe should be nearly black or white. Antialiased edges
// may stay gray, so sample a wide span and allow for those pixels.
const row = 1200;
let dark = 0;
let light = 0;
for (let x = 340; x < 740; x++) {
const shade = screenshot.data[(row * screenshot.width + x) * 4];
if (shade < 35) dark++;
if (shade > 220) light++;
}
assert.ok(
dark >= 80 && light >= 80,
`Fine stripes lost contrast (${dark} dark, ${light} light pixels)`,
);
}
@@ -55,6 +55,7 @@ interface HeldServerMessage {
interface PendingServerMessageHold {
matches: (message: ClientRequest | null) => boolean;
blockAgentStreamFollowers?: boolean;
keepHolding?: boolean;
}
function readSessionMessage(message: string | Buffer): ClientRequest | null {
@@ -412,7 +413,7 @@ export async function installDaemonWebSocketGate(page: Page, options: { port?: n
);
if (!matchedHold) return suppressed;
const [key, hold] = matchedHold;
pendingServerMessageHolds.delete(key);
if (!hold.keepHolding) pendingServerMessageHolds.delete(key);
heldServerMessages.push({
browser: input.browser,
message: input.message,
@@ -550,6 +551,23 @@ export async function installDaemonWebSocketGate(page: Page, options: { port?: n
});
});
const sendHeldServerMessage = (heldServerMessage: HeldServerMessage): void => {
heldServerMessage.browser.send(heldServerMessage.message);
for (const follower of heldServerMessage.agentStreamFollowers) {
heldServerMessage.browser.send(follower);
}
};
const releaseFirstHeldMessage = (
predicate: (message: HeldServerMessage) => boolean,
errorMessage: string,
): void => {
const index = heldServerMessages.findIndex(predicate);
const [heldServerMessage] = index >= 0 ? heldServerMessages.splice(index, 1) : [];
if (!heldServerMessage) throw new Error(errorMessage);
sendHeldServerMessage(heldServerMessage);
};
return {
waitForFileSubscription(path: string): Promise<void> {
if (subscribedFilePaths.has(path)) return Promise.resolve();
@@ -661,6 +679,13 @@ export async function installDaemonWebSocketGate(page: Page, options: { port?: n
matches: (message) => matchesAgentUpdate(message, heldAgentUpdate),
});
},
holdAgentUpdates(agentId: string, status: string): void {
const heldAgentUpdate = { agentId, status };
pendingServerMessageHolds.set(agentUpdateKey(agentId, status), {
matches: (message) => matchesAgentUpdate(message, heldAgentUpdate),
keepHolding: true,
});
},
holdNextAgentStreamEvent(type: string): void {
pendingServerMessageHolds.set(agentStreamEventKey(type), {
matches: (message) => readAgentStreamEventType(message) === type,
@@ -690,13 +715,10 @@ export async function installDaemonWebSocketGate(page: Page, options: { port?: n
},
releaseHeldServerMessage(type?: string): void {
const key = type ? serverMessageKey(type) : null;
const index = heldServerMessages.findIndex((message) => key === null || message.key === key);
const [heldServerMessage] = index >= 0 ? heldServerMessages.splice(index, 1) : [];
if (!heldServerMessage) throw new Error("No held server message to release");
heldServerMessage.browser.send(heldServerMessage.message);
for (const follower of heldServerMessage.agentStreamFollowers) {
heldServerMessage.browser.send(follower);
}
releaseFirstHeldMessage(
(message) => key === null || message.key === key,
"No held server message to release",
);
},
async waitForHeldAgentUpdate(agentId: string, status: string): Promise<void> {
const key = agentUpdateKey(agentId, status);
@@ -706,12 +728,20 @@ export async function installDaemonWebSocketGate(page: Page, options: { port?: n
},
releaseHeldAgentUpdate(agentId: string, status: string): void {
const key = agentUpdateKey(agentId, status);
const index = heldServerMessages.findIndex((message) => message.key === key);
const [heldServerMessage] = index >= 0 ? heldServerMessages.splice(index, 1) : [];
if (!heldServerMessage) throw new Error("No held agent update to release");
heldServerMessage.browser.send(heldServerMessage.message);
for (const follower of heldServerMessage.agentStreamFollowers) {
heldServerMessage.browser.send(follower);
releaseFirstHeldMessage((message) => message.key === key, "No held agent update to release");
},
releaseHeldAgentUpdates(agentId: string, status: string): void {
const key = agentUpdateKey(agentId, status);
pendingServerMessageHolds.delete(key);
const matching: HeldServerMessage[] = [];
for (let index = heldServerMessages.length - 1; index >= 0; index -= 1) {
if (heldServerMessages[index]?.key === key) {
matching.unshift(...heldServerMessages.splice(index, 1));
}
}
if (matching.length === 0) throw new Error("No held agent update to release");
for (const heldServerMessage of matching) {
sendHeldServerMessage(heldServerMessage);
}
},
async waitForHeldAgentStreamEvent(type: string): Promise<void> {
@@ -722,13 +752,10 @@ export async function installDaemonWebSocketGate(page: Page, options: { port?: n
},
releaseHeldAgentStreamEvent(type: string): void {
const key = agentStreamEventKey(type);
const index = heldServerMessages.findIndex((message) => message.key === key);
const [heldServerMessage] = index >= 0 ? heldServerMessages.splice(index, 1) : [];
if (!heldServerMessage) throw new Error("No held agent stream event to release");
heldServerMessage.browser.send(heldServerMessage.message);
for (const follower of heldServerMessage.agentStreamFollowers) {
heldServerMessage.browser.send(follower);
}
releaseFirstHeldMessage(
(message) => message.key === key,
"No held agent stream event to release",
);
},
async waitForHeldAgentStreamItem(type: string): Promise<void> {
const key = agentStreamItemKey(type);
@@ -738,13 +765,10 @@ export async function installDaemonWebSocketGate(page: Page, options: { port?: n
},
releaseHeldAgentStreamItem(type: string): void {
const key = agentStreamItemKey(type);
const index = heldServerMessages.findIndex((message) => message.key === key);
const [heldServerMessage] = index >= 0 ? heldServerMessages.splice(index, 1) : [];
if (!heldServerMessage) throw new Error("No held agent stream item to release");
heldServerMessage.browser.send(heldServerMessage.message);
for (const follower of heldServerMessage.agentStreamFollowers) {
heldServerMessage.browser.send(follower);
}
releaseFirstHeldMessage(
(message) => message.key === key,
"No held agent stream item to release",
);
},
requestTimelineTail(agentId: string): void {
if (!latestServer) throw new Error("No daemon WebSocket is connected");
@@ -948,3 +948,46 @@ it.each([false, true])(
expect(opened.groupsByHostId.size).toBe(0);
},
);
it("folds a completed turn whose plugin replaces every tool and reasoning row", () => {
const present = createStreamPresentation();
const timestamp = new Date();
const tail: StreamItem[] = [
{ kind: "user_message", id: "prompt", text: "Work", timestamp },
{ kind: "thought", id: "reasoning", text: "Plan", status: "ready", timestamp },
toolCall("one", "Bash"),
{ kind: "assistant_message", id: "reply", text: "Done", timestamp },
];
const toolPlugin = installedTransform(installProbe("tool_call"));
const reasoningPlugin = installedTransform(installProbe("reasoning"));
const input = {
...presentationOptions,
tail,
head: [],
display: "collapseTurns" as const,
isTurnActive: false,
};
const transform: TimelineItemTransform = (item) =>
toolPlugin(item)?.flatMap((card) => [card, { ...card, id: `${card.id}/detail` }]) ??
reasoningPlugin(item);
const control = present({ ...input, transform: undefined });
expect(control.tail.map((item) => item.kind)).toEqual([
"user_message",
"turn_summary",
"assistant_message",
]);
const closed = present({ ...input, transform });
expect(closed.tail.map((item) => item.kind)).toEqual(control.tail.map((item) => item.kind));
expect(closed.turns.summaryRowsByHostId.get("prompt")?.tools).toEqual(
control.turns.summaryRowsByHostId.get("prompt")?.tools,
);
const opened = present({ ...input, transform, expandedTurnHostIds: new Set(["prompt"]) });
expect(opened.tail.map((item) => item.kind)).toEqual([
"user_message",
"turn_summary",
"plugin",
"plugin",
"plugin",
"assistant_message",
]);
});
@@ -45,9 +45,14 @@ function summarizeTurn(
getGroupedCalls: CollapseTurnsInput["getGroupedCalls"],
): OverviewSummary {
const calls: (ToolCallItem | ThoughtItem)[] = [];
const countedSources = new Set<string>();
for (const item of items) {
if ((item.kind === "tool_call" || item.kind === "thought") && !isTurnTrigger(item))
calls.push(...(getGroupedCalls(item.id) ?? [item]));
const source = item.kind === "plugin" ? item.source : item;
if (!source || (source.kind !== "tool_call" && source.kind !== "thought")) continue;
if (isTurnTrigger(source) || countedSources.has(source.id)) continue;
// One source tool call can render as several plugin cards.
countedSources.add(source.id);
calls.push(...(getGroupedCalls(source.id) ?? [source]));
}
return summarizeToolCalls(calls);
}
@@ -46,6 +46,7 @@ const DRAG_OVERLAY_STYLE: React.CSSProperties = {
const TOP_RESIZER_STYLE: React.CSSProperties = {
position: "absolute",
top: 0,
left: 0,
width: "100%",
height: 4,
// @ts-expect-error — WebkitAppRegion is not in CSSProperties
@@ -1,7 +1,6 @@
import { useCallback, type ReactNode, type RefObject } from "react";
import type { View } from "react-native";
import { MenuRoot, useMenuContext } from "@/components/ui/menu";
import { PluginPopoverSurface } from "@/plugins/popover";
import type { ReactNode } from "react";
import { MenuRoot } from "@/components/ui/menu";
import { PluginPopoverSurface, usePluginPopoverAnchor } from "@/plugins/popover";
import type { SidebarSection } from "@/sidebar-nav/model";
/**
@@ -26,41 +25,7 @@ export function SidebarPopoverRoot({
);
}
function assignRef(ref: RefObject<View | null>, node: View | null) {
Object.assign(ref, { current: node });
}
/**
* Where the popover anchors. `anchorTo` moves it to an element, such as the row just pressed;
* `offerAnchor` sets it only when nothing is anchored; `releaseAnchor` drops an element that is
* going away; `anchorToFallback` covers an item that anchored nothing.
*/
export function useSidebarPopoverAnchor(name: string): {
anchorTo: (node: View | null) => void;
offerAnchor: (node: View | null) => void;
releaseAnchor: (node: View | null) => void;
anchorToFallback: (fallback: RefObject<View | null>) => void;
} {
const { triggerRef } = useMenuContext(name);
const anchorTo = useCallback((node: View | null) => assignRef(triggerRef, node), [triggerRef]);
const offerAnchor = useCallback(
(node: View | null) => {
if (!triggerRef.current) assignRef(triggerRef, node);
},
[triggerRef],
);
const releaseAnchor = useCallback(
(node: View | null) => {
if (triggerRef.current === node) assignRef(triggerRef, null);
},
[triggerRef],
);
const anchorToFallback = useCallback(
(fallback: RefObject<View | null>) => offerAnchor(fallback.current),
[offerAnchor],
);
return { anchorTo, offerAnchor, releaseAnchor, anchorToFallback };
}
export const useSidebarPopoverAnchor = usePluginPopoverAnchor;
const PLACEMENT = {
header: { side: "right", align: "start" },
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { Image } from "expo-image";
import { View, type StyleProp, type ViewStyle } from "react-native";
import { Platform, View, type StyleProp, type ViewStyle } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import type { ViewportFitOptions, ViewportSize } from "./geometry";
import { measureImage } from "./image-size";
@@ -84,7 +84,9 @@ export function ZoomableImage({
<ViewportImage
// No transition, so the image appears together with its toolbar.
transition={null}
contentFit="contain"
// The viewport already fits the image's aspect ratio. On Android, fill selects
// Expo Image's bitmap size cap while preserving detail below that cap for zoom.
contentFit={Platform.OS === "android" ? "fill" : "contain"}
onError={onError}
onLoad={handleLoad}
source={source}
+16 -3
View File
@@ -1,4 +1,11 @@
import { useCallback, useMemo, useState, type ReactElement, type ReactNode } from "react";
import {
useCallback,
useMemo,
useState,
type ReactElement,
type ReactNode,
type RefObject,
} from "react";
import { Pressable, Text, View } from "react-native";
import { GestureDetector } from "react-native-gesture-handler";
import Animated from "react-native-reanimated";
@@ -42,12 +49,18 @@ import { COMPOSER_PILL_CLEARANCE, composerPillStyles } from "./pill-styles";
* or without pills: that keeps the final footer clear, and pills that come and go every turn do not
* move the transcript.
*/
export function ComposerTrackBar({ children }: { children: ReactNode }): ReactElement {
export function ComposerTrackBar({
children,
trackViewportRef,
}: {
children: ReactNode;
trackViewportRef?: RefObject<View | null>;
}): ReactElement {
const scrollGesture = usePanelAwareHorizontalScrollGesture();
const scrollBoundary = useHorizontalScrollBoundary();
return (
<View style={styles.bar} dataSet={CHAT_COLUMN_RAIL_DATASET} pointerEvents="box-none">
<View style={styles.trackViewport} pointerEvents="box-none">
<View ref={trackViewportRef} style={styles.trackViewport} pointerEvents="box-none">
<GestureDetector gesture={scrollGesture}>
<Animated.ScrollView
testID="composer-track-scroll"
+9 -38
View File
@@ -1,6 +1,4 @@
import { usePaneContext } from "@/panels/pane-context";
import { useCallback, useEffect, useMemo, useState } from "react";
import type { PluginFile, PluginTab } from "@getpaseo/plugin/client";
import { useCallback, useMemo } from "react";
import { Text, View } from "react-native";
import { Download } from "lucide-react-native";
import { StyleSheet } from "react-native-unistyles";
@@ -9,11 +7,11 @@ import { Button } from "@/components/ui/button";
import { useRetainedPanelActive } from "@/components/retained-panel";
import { useFileHandle, useFileHandleSnapshot } from "@/file-panels/file";
import { FilePanelLoading } from "@/file-panels/loading";
import { FilePanelPicker, FilePanelView, useFilePanelChoice, type FilePanel } from "@/file-panels";
import { FilePanelPicker, FilePanelView, useFilePanelChoice } from "@/file-panels";
import { resolveFilePreviewReadTarget } from "@/file-explorer/preview-target";
import { useFileDownload } from "@/hooks/use-file-download";
import { useAppActivelyVisible } from "@/hooks/use-app-visible";
import { usePublishPanelInstanceAttributes } from "@/panels/panel-instance-attributes";
import { getComponentMountKey } from "@/panels/panel-instance-attributes";
import { useHostRuntimeConnectionStatus } from "@/runtime/host-runtime";
import { buildAbsoluteExplorerPath } from "@/utils/explorer-paths";
import { formatFileSize } from "@/utils/format-file-size";
@@ -79,8 +77,6 @@ export function FilePane({
presentable: isActive,
lineNavigation: location.lineStart ? navigationRevision : null,
});
const [modified, setModified] = useState(false);
usePublishPanelInstanceAttributes({ modified, suspendPendingSave: handle?.holdWrites });
const panelLocation = useMemo(
() => ({
lineStart: location.lineStart,
@@ -121,16 +117,19 @@ export function FilePane({
</>
);
} else {
const panelMountKey = panel.builtin
? `${panel.id}:${targetKey}`
: `${panel.id}:${targetKey}:${getComponentMountKey(panel.contribution.Component)}`;
return (
<View style={styles.container} testID="workspace-file-pane">
<FilePanelPicker choice={choice} />
<MountedFilePanel
key={`${panel.id}:${targetKey}`}
<FilePanelView
key={panelMountKey}
panel={panel}
file={handle.file}
params={panelLocation}
revision={navigationRevision}
onModifiedChange={setModified}
suspendPendingSave={handle.holdWrites}
/>
</View>
);
@@ -142,34 +141,6 @@ export function FilePane({
);
}
/** One panel mount. Its tab reports unsaved changes until the panel unmounts. */
function MountedFilePanel({
panel,
file,
params,
revision,
onModifiedChange,
}: {
panel: FilePanel;
file: PluginFile;
params: { path: string; lineStart?: number; lineEnd?: number };
revision: number;
onModifiedChange: (modified: boolean) => void;
}) {
const { tabId, state, setCurrentTabState } = usePaneContext();
const tab = useMemo<PluginTab>(
() => ({
id: tabId,
setModified: onModifiedChange,
state,
setState: setCurrentTabState,
}),
[tabId, onModifiedChange, state, setCurrentTabState],
);
useEffect(() => () => onModifiedChange(false), [onModifiedChange]);
return <FilePanelView panel={panel} file={file} tab={tab} params={params} revision={revision} />;
}
const styles = StyleSheet.create((theme) => ({
container: {
flex: 1,
+7 -6
View File
@@ -1,4 +1,5 @@
import { useWorkspace, useFileUrl, type PluginFilePanelProps } from "@getpaseo/plugin/client";
import { useWorkspace, useFileUrl } from "@getpaseo/plugin/client";
import type { BuiltinFilePanelProps } from "./panels";
import { useCallback, useState } from "react";
import { ScrollView, Text, View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
@@ -11,17 +12,17 @@ import { TextFilePanel, type TextFilePreviewProps } from "./source/panel";
import type { RenderingFilePanel, SourceFilePanel } from "./catalog";
/** Source: the text file panel with no Preview, for text files no other built-in panel claims. */
function SourcePanel(props: PluginFilePanelProps) {
function SourcePanel(props: BuiltinFilePanelProps) {
return <TextFilePanel {...props} />;
}
/** Markdown: the text file panel with the rendered document as its Preview. */
function MarkdownPanel(props: PluginFilePanelProps) {
function MarkdownPanel(props: BuiltinFilePanelProps) {
return <TextFilePanel {...props} preview={MarkdownPreview} />;
}
/** HTML: the text file panel with the sandboxed page as its Preview. */
function HtmlPanel(props: PluginFilePanelProps) {
function HtmlPanel(props: BuiltinFilePanelProps) {
return <TextFilePanel {...props} preview={HtmlPreview} />;
}
@@ -58,7 +59,7 @@ function HtmlPreview({ text }: TextFilePreviewProps) {
);
}
function ImagePanel({ file }: PluginFilePanelProps) {
function ImagePanel({ file }: BuiltinFilePanelProps) {
const url = useFileUrl(file);
if (url.status === "loading") return <FilePanelLoading />;
if (url.status === "error") return <FilePanelError message={url.error.message} />;
@@ -83,7 +84,7 @@ const components = {
export function BuiltinFilePanelView({
panel,
...props
}: PluginFilePanelProps & { panel: RenderingFilePanel | SourceFilePanel }) {
}: BuiltinFilePanelProps & { panel: RenderingFilePanel | SourceFilePanel }) {
const Component = components[panel.id];
return <Component {...props} />;
}
+4
View File
@@ -1,8 +1,12 @@
import { useMemo } from "react";
import type { PluginFilePanelProps } from "@getpaseo/plugin/client";
import { useInstalledPlugins } from "@/plugins/registry";
import type { PluginFilePanelContribution, InstalledPlugin } from "@/plugins/types";
import { filePanelCatalog, type RenderingFilePanel, type SourceFilePanel } from "./catalog";
/** Props shared by built-in file panels; excludes plugin-owned capabilities such as `openScreen`. */
export type BuiltinFilePanelProps = Omit<PluginFilePanelProps, "openScreen">;
export interface PluginFilePanel {
id: string;
builtin: false;
+30 -3
View File
@@ -1,18 +1,45 @@
import type { PluginFilePanelProps } from "@getpaseo/plugin/client";
import { usePanelTab } from "@/panels/panel-instance-attributes";
import { PluginInstallationProvider } from "@/plugins/installation-provider";
import { usePluginOpenScreen } from "@/plugins/navigation";
import { SurfaceErrorBoundary } from "@/plugins/surface-error-boundary";
import type { PluginFilePanel } from "./panels";
import type { BuiltinFilePanelProps, PluginFilePanel } from "./panels";
type PluginFilePanelHostProps = Omit<BuiltinFilePanelProps, "tab"> & {
panel: PluginFilePanel;
suspendPendingSave?: () => () => void;
};
function MountedPluginFilePanel({
panel,
suspendPendingSave,
...props
}: Omit<PluginFilePanelProps, "tab"> & {
panel: PluginFilePanel;
suspendPendingSave?: () => () => void;
}) {
const tab = usePanelTab({ suspendPendingSave });
const Component = panel.contribution.Component;
return <Component {...props} tab={tab} />;
}
export function PluginFilePanelHost({
panel,
suspendPendingSave,
...props
}: PluginFilePanelProps & { panel: PluginFilePanel }) {
}: PluginFilePanelHostProps) {
const { plugin, contribution } = panel;
const openScreen = usePluginOpenScreen(plugin);
const Component = contribution.Component;
return (
<SurfaceErrorBoundary installation={plugin} Surface={Component} key={panel.id}>
<PluginInstallationProvider plugin={plugin}>
<Component {...props} />
<MountedPluginFilePanel
{...props}
openScreen={openScreen}
panel={panel}
suspendPendingSave={suspendPendingSave}
/>
</PluginInstallationProvider>
</SurfaceErrorBoundary>
);
@@ -8,11 +8,8 @@ import {
type ComponentType,
type ReactNode,
} from "react";
import {
useFileText,
type PluginFilePanelProps,
type PluginFilePanelParams,
} from "@getpaseo/plugin/client";
import { useFileText, type PluginFilePanelParams } from "@getpaseo/plugin/client";
import type { BuiltinFilePanelProps } from "../panels";
import { Text, View } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { useTranslation } from "react-i18next";
@@ -56,12 +53,12 @@ const MAX_EDITABLE_BYTES = 1024 * 1024;
/** A rendered view of the file's text: the panel's Preview, shown instead of its source. */
export interface TextFilePreviewProps {
text: string;
params: PluginFilePanelProps["params"];
params: BuiltinFilePanelProps["params"];
workspaceId: string;
host: PluginFilePanelProps["host"];
host: BuiltinFilePanelProps["host"];
}
type TextFilePanelProps = PluginFilePanelProps & {
type TextFilePanelProps = BuiltinFilePanelProps & {
/** The panel's Preview; with one, the toolbar switches between Preview and Source. */
preview?: ComponentType<TextFilePreviewProps>;
};
+34 -6
View File
@@ -6,19 +6,40 @@ import type { PluginTheme } from "@getpaseo/plugin";
import { withUnistyles } from "react-native-unistyles";
import { useIsCompactFormFactor } from "@/constants/layout";
import { usePaneContext } from "@/panels/pane-context";
import { usePanelTab } from "@/panels/panel-instance-attributes";
import { useHosts } from "@/runtime/host-runtime";
import { usePluginHostNavigation } from "@/plugins/host-navigation";
import { resolvePluginPlatform } from "@/plugins/platform";
import { toPluginTheme } from "@/plugins/theme";
import type { Theme } from "@/styles/theme";
import type { FilePanel } from "./panels";
import type { BuiltinFilePanelProps, FilePanel } from "./panels";
import type { RenderingFilePanel, SourceFilePanel } from "./catalog";
import { BuiltinFilePanelView } from "./builtin";
import { PluginFilePanelHost } from "./plugin-host";
type Props = Pick<PluginFilePanelProps, "file" | "tab" | "params" | "revision"> & {
type Props = Pick<PluginFilePanelProps, "file" | "params" | "revision"> & {
panel: FilePanel;
suspendPendingSave?: () => () => void;
};
function FilePanelHost({ panel, theme, ...input }: Props & { theme: PluginTheme }) {
function BuiltinFilePanelHost({
panel,
suspendPendingSave,
...props
}: Omit<BuiltinFilePanelProps, "tab"> & {
panel: RenderingFilePanel | SourceFilePanel;
suspendPendingSave?: () => () => void;
}) {
const tab = usePanelTab({ suspendPendingSave });
return <BuiltinFilePanelView {...props} tab={tab} panel={panel} />;
}
function FilePanelHost({
panel,
suspendPendingSave,
theme,
...input
}: Props & { theme: PluginTheme }) {
const { workspaceId, serverId } = usePaneContext();
const compact = useIsCompactFormFactor();
const hosts = useHosts();
@@ -27,14 +48,21 @@ function FilePanelHost({ panel, theme, ...input }: Props & { theme: PluginTheme
const layout = useMemo(() => ({ compact, platform: resolvePluginPlatform() }), [compact]);
const stateSource = useMemo(() => createPluginClientStateSource(serverId), [serverId]);
const navigation = usePluginHostNavigation(serverId);
const props: PluginFilePanelProps = { ...input, workspaceId, theme, host, layout, navigation };
const props: Omit<BuiltinFilePanelProps, "tab"> = {
...input,
workspaceId,
theme,
host,
layout,
navigation,
};
if (panel.builtin)
return (
<PluginClientStateProvider source={stateSource}>
<BuiltinFilePanelView {...props} panel={panel} />
<BuiltinFilePanelHost {...props} panel={panel} suspendPendingSave={suspendPendingSave} />
</PluginClientStateProvider>
);
return <PluginFilePanelHost {...props} panel={panel} />;
return <PluginFilePanelHost {...props} panel={panel} suspendPendingSave={suspendPendingSave} />;
}
const ThemedHost = withUnistyles(FilePanelHost);
const themeMapping = (theme: Theme) => ({ theme: toPluginTheme(theme) });
+11 -3
View File
@@ -1,5 +1,6 @@
import type { AgentAddress } from "@getpaseo/protocol/addresses";
import { memo, useCallback, useMemo, type ReactElement } from "react";
import { memo, useCallback, useMemo, useRef, type ReactElement } from "react";
import type { View } from "react-native";
import { BackgroundWorkTrack, createHostBackgroundWorkModel } from "@/background-work";
import { WorkspaceDiffStatPill } from "@/composer/diff-stat-pill";
import { AgentTaskList } from "@/composer/task-list";
@@ -7,7 +8,7 @@ import { ComposerTrackBar } from "@/composer/tracks";
import { useIsCompactFormFactor } from "@/constants/layout";
import { usePaneContext } from "@/panels/pane-context";
import { useSettings } from "@/hooks/use-settings";
import { PluginComposerPills } from "@/plugins";
import { PluginComposerPillItems, PluginComposerPills } from "@/plugins";
import { useSessionStore } from "@/stores/session-store";
import {
useArchiveFinishedSubagents,
@@ -108,6 +109,7 @@ export const AgentTracks = memo(function AgentTracks({
[openSubagentTarget],
);
const sheetTabFor = useSubagentSheetTab(workspaceKey, tabId);
const trackViewportRef = useRef<View | null>(null);
const handleOpenChanges = useCallback(() => {
if (!workspaceKey) {
return;
@@ -120,7 +122,7 @@ export const AgentTracks = memo(function AgentTracks({
}, [isCompact, openInSidePane, workspaceKey]);
return (
<ComposerTrackBar>
<ComposerTrackBar trackViewportRef={trackViewportRef}>
<BackgroundWorkTrack model={backgroundModel} count={backgroundWorkCount} />
{parentAgentId ? <ParentAgentPill serverId={serverId} parentAgentId={parentAgentId} /> : null}
<AgentTaskList tasks={tasks} />
@@ -135,6 +137,12 @@ export const AgentTracks = memo(function AgentTracks({
archiveFinishedStatus={archiveFinishedSubagents.status}
onDetachSubagent={canDetachSubagents ? detachSubagent : undefined}
/>
<PluginComposerPillItems
serverId={serverId}
workspaceId={workspaceId}
agentId={agentId}
fallbackAnchorRef={trackViewportRef}
/>
<PluginComposerPills
serverId={serverId}
workspaceId={workspaceId}
@@ -32,4 +32,45 @@ describe("panel instance attributes", () => {
expect(notifications).toBe(2);
unsubscribe();
});
test("stores trimmed title overrides independently of modified and clears on empty or whitespace", () => {
const first = { serverId: "server", workspaceId: "one", tabId: "tab-title" };
const second = { serverId: "server", workspaceId: "two", tabId: "tab-title" };
setPanelInstanceAttributes(first, { modified: false, title: " Review (3) " });
expect(getPanelInstanceAttributes(first)).toEqual({
modified: false,
title: "Review (3)",
});
expect(getPanelInstanceAttributes(second)).toEqual({ modified: false });
setPanelInstanceAttributes(first, { modified: true, title: "Review (3)" });
expect(getPanelInstanceAttributes(first)).toEqual({
modified: true,
title: "Review (3)",
});
setPanelInstanceAttributes(first, { modified: true, title: " " });
expect(getPanelInstanceAttributes(first)).toEqual({ modified: true });
setPanelInstanceAttributes(first, { modified: false, title: "" });
expect(getPanelInstanceAttributes(first)).toEqual({ modified: false });
});
test("notifies subscribers only when normalized title changes", () => {
const identity = { serverId: "server", workspaceId: "workspace", tabId: "title-observed" };
let notifications = 0;
const unsubscribe = subscribePanelInstanceAttributes(identity, () => {
notifications += 1;
});
setPanelInstanceAttributes(identity, { modified: false, title: " " });
setPanelInstanceAttributes(identity, { modified: false, title: " Custom " });
setPanelInstanceAttributes(identity, { modified: false, title: "Custom" });
setPanelInstanceAttributes(identity, { modified: false, title: "" });
expect(notifications).toBe(2);
unsubscribe();
});
});
@@ -1,4 +1,5 @@
import { useCallback, useEffect, useMemo, useSyncExternalStore } from "react";
import type { PluginTab } from "@getpaseo/plugin/client";
import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from "react";
import { usePaneContext } from "@/panels/pane-context";
import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model";
@@ -10,6 +11,7 @@ export interface PanelInstanceIdentity {
export interface PanelInstanceAttributes {
modified: boolean;
title?: string;
suspendPendingSave?: () => () => void;
}
@@ -19,6 +21,23 @@ const listenersByPanel = new Map<string, Set<() => void>>();
const allListeners = new Set<() => void>();
let attributesRevision = 0;
export function normalizePanelTitle(title: string | null | undefined): string | undefined {
const trimmed = title?.trim();
return trimmed ? trimmed : undefined;
}
function normalizePanelAttributes(attributes: PanelInstanceAttributes): PanelInstanceAttributes {
const title = normalizePanelTitle(attributes.title);
const next: PanelInstanceAttributes = { modified: attributes.modified };
if (title !== undefined) {
next.title = title;
}
if (attributes.modified && attributes.suspendPendingSave !== undefined) {
next.suspendPendingSave = attributes.suspendPendingSave;
}
return next;
}
function buildWorkspacePanelKey(workspaceKey: string, tabId: string): string {
return `${workspaceKey}:${tabId}`;
}
@@ -47,13 +66,15 @@ export function setPanelInstanceAttributes(
): void {
const key = buildPanelInstanceKey(identity);
const previous = attributesByPanel.get(key) ?? DEFAULT_ATTRIBUTES;
const next = normalizePanelAttributes(attributes);
if (
previous.modified === attributes.modified &&
previous.suspendPendingSave === attributes.suspendPendingSave
previous.modified === next.modified &&
previous.title === next.title &&
previous.suspendPendingSave === next.suspendPendingSave
) {
return;
}
if (attributes.modified) attributesByPanel.set(key, attributes);
if (next.modified || next.title !== undefined) attributesByPanel.set(key, next);
else attributesByPanel.delete(key);
attributesRevision += 1;
for (const listener of listenersByPanel.get(key) ?? []) listener();
@@ -127,10 +148,49 @@ export function usePanelInstanceAttributes({
export function usePublishPanelInstanceAttributes(attributes: PanelInstanceAttributes): void {
const { serverId, workspaceId, tabId } = usePaneContext();
const modified = attributes.modified;
const title = normalizePanelTitle(attributes.title);
const suspendPendingSave = attributes.suspendPendingSave;
useEffect(() => {
const identity = { serverId, workspaceId, tabId };
setPanelInstanceAttributes(identity, { modified, suspendPendingSave });
setPanelInstanceAttributes(identity, { modified, title, suspendPendingSave });
return () => setPanelInstanceAttributes(identity, DEFAULT_ATTRIBUTES);
}, [modified, serverId, suspendPendingSave, tabId, workspaceId]);
}, [modified, serverId, suspendPendingSave, tabId, title, workspaceId]);
}
const componentMountKeys = new WeakMap<object, number>();
let nextComponentMountKey = 1;
/** Returns a stable numeric React key for a component function/object identity. */
export function getComponentMountKey(component: object): number {
let key = componentMountKeys.get(component);
if (key === undefined) {
key = nextComponentMountKey++;
componentMountKeys.set(component, key);
}
return key;
}
/** Publishes tab state (`modified` and `title`) for the current pane tab and resets it on unmount. */
export function usePanelTab(options?: { suspendPendingSave?: () => () => void }): PluginTab {
const { tabId, state, setCurrentTabState } = usePaneContext();
const [modified, setModified] = useState(false);
const [title, setTitleState] = useState<string | undefined>(undefined);
const setTitle = useCallback((nextTitle: string | null) => {
setTitleState(normalizePanelTitle(nextTitle));
}, []);
usePublishPanelInstanceAttributes({
modified,
title,
suspendPendingSave: options?.suspendPendingSave,
});
return useMemo<PluginTab>(
() => ({
id: tabId,
setModified,
setTitle,
state,
setState: setCurrentTabState,
}),
[setCurrentTabState, setTitle, state, tabId],
);
}
@@ -50,5 +50,60 @@ describe("panel manifest", () => {
expect(panelResourceKey({ kind: "file", path: "src/a.ts" })).not.toBe(
panelResourceKey({ kind: "file", path: "src/b.ts" }),
);
expect(
panelResourceKey({
kind: "plugin",
pluginId: "review",
panelId: "decisions",
context: "workspace",
params: { decisionId: "D1" },
}),
).toBe(
panelResourceKey({
kind: "plugin",
pluginId: "review",
panelId: "decisions",
context: "workspace",
params: { decisionId: "D2" },
}),
);
expect(
panelResourceKey({
kind: "plugin",
pluginId: "review",
panelId: "pr",
context: "workspace",
params: { prNumber: 1, commentId: "a" },
identityKey: "1",
}),
).toBe(
panelResourceKey({
kind: "plugin",
pluginId: "review",
panelId: "pr",
context: "workspace",
params: { prNumber: 1, commentId: "b" },
identityKey: "1",
}),
);
expect(
panelResourceKey({
kind: "plugin",
pluginId: "review",
panelId: "pr",
context: "workspace",
params: { prNumber: 1 },
identityKey: "1",
}),
).not.toBe(
panelResourceKey({
kind: "plugin",
pluginId: "review",
panelId: "pr",
context: "workspace",
params: { prNumber: 2 },
identityKey: "2",
}),
);
});
});
+7 -3
View File
@@ -280,10 +280,14 @@ const manifests = {
singleton: false,
oneTabPerInstance: false,
compactSheet: null,
resourceKey: (target) =>
target.context === "agent"
resourceKey: (target) => {
if (target.identityKey !== undefined) {
return `${target.pluginId}:${target.panelId}:keyed:${target.context}:${target.identityKey}`;
}
return target.context === "agent"
? `${target.pluginId}:${target.panelId}:agent:${target.agentId}`
: `${target.pluginId}:${target.panelId}:workspace`,
: `${target.pluginId}:${target.panelId}:workspace`;
},
// Plugin panels are named by their registration, not by this kind.
public: null,
},
@@ -0,0 +1,579 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { PortalProvider } from "@gorhom/portal";
import { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import React from "react";
import { createRoot, type Root } from "react-dom/client";
import { Text, View } from "react-native";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { page } from "vitest/browser";
import { i18n } from "@/i18n/i18next";
import { getFilePanelChoice } from "@/file-panels/choice/registry";
import { filePanelRegistration } from "@/panels/file-panel";
import { PaneFocusProvider, PaneProvider, type PaneContextValue } from "@/panels/pane-context";
import { registerPanel } from "@/panels/panel-registry";
import { pluginExecutionApprovals } from "@/plugins/execution-approval";
import { pluginRegistry } from "@/plugins/registry";
import { pluginPanelRegistration } from "@/plugins/workspace-panels/panel";
import {
getHostRuntimeStore,
type HostRuntimeController,
type HostRuntimeSnapshot,
} from "@/runtime/host-runtime";
import { RetainedPanelActivity } from "@/components/retained-panel";
import {
WorkspaceTabPresentationResolver,
type WorkspaceTabPresentation,
} from "@/screens/workspace/workspace-tab-presentation";
import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-types";
import { useSessionStore, type Agent, type WorkspaceDescriptor } from "@/stores/session-store";
import { useWorkspaceLayoutStore } from "@/stores/workspace-layout-store";
import { seedSessionHosts, seedSessionWorkspaces } from "@/test/seed-session";
void i18n;
registerPanel(pluginPanelRegistration);
registerPanel(filePanelRegistration);
const SERVER_ID = "tab-title-server";
const WORKSPACE_ID = "tab-title-workspace";
const AGENT_ID = "tab-title-agent";
const PLUGIN_ID = "tab-title-plugin";
const noop = () => {};
const FOCUS_VALUE = {
isWorkspaceFocused: true,
isPaneFocused: true,
isInteractive: true,
focusPane: noop,
} as const;
const WORKSPACE_TAB: WorkspaceTabDescriptor = {
key: "plugin-ws-1",
tabId: "plugin-ws-1",
kind: "plugin",
target: {
kind: "plugin",
pluginId: PLUGIN_ID,
panelId: "overview",
context: "workspace",
},
};
const AGENT_TAB: WorkspaceTabDescriptor = {
key: "plugin-agent-1",
tabId: "plugin-agent-1",
kind: "plugin",
target: {
kind: "plugin",
pluginId: PLUGIN_ID,
panelId: "inspector",
context: "agent",
agentId: AGENT_ID,
},
};
const FILE_TAB: WorkspaceTabDescriptor = {
key: "file-txt-1",
tabId: "file-txt-1",
kind: "file",
target: {
kind: "file",
path: "docs/notes.txt",
},
};
const MOUNT_TAB: WorkspaceTabDescriptor = {
key: "plugin-mount-1",
tabId: "plugin-mount-1",
kind: "plugin",
target: {
kind: "plugin",
pluginId: PLUGIN_ID,
panelId: "mount-effect",
context: "workspace",
},
};
function setHostRuntimeClient(serverId: string, client: DaemonClient | null) {
const controllers = (
getHostRuntimeStore() as unknown as {
controllers: Map<string, HostRuntimeController>;
}
).controllers;
const controller = controllers.get(serverId);
if (!controller) throw new Error(`Host runtime controller for ${serverId} was not initialized`);
(
controller as unknown as {
updateSnapshot: (
patch: Partial<Omit<HostRuntimeSnapshot, "serverId" | "clientGeneration">>,
) => void;
}
).updateSnapshot({ client });
}
function createFakeClient() {
const client = new DaemonClient({
url: "ws://127.0.0.1:1",
clientId: "plugin-tab-title-test",
reconnect: { enabled: false },
});
Object.assign(client, {
observeEvents: () => ({
ready: Promise.resolve({ subscriptionId: "events" }),
subscribe: () => noop,
release: async () => undefined,
}),
readFile: async (_cwd: string, path: string) => ({
path,
content: "hello from file",
encoding: "utf-8",
kind: "text",
mime: "text/plain",
size: 15,
modifiedAt: "2026-12-04T00:00:00.000Z",
revision: "rev-1",
}),
subscribeFile: async () => ({
initial: {
status: "ready",
kind: "text",
mimeType: "text/plain",
size: 15,
modifiedAt: "2026-12-04T00:00:00.000Z",
revision: "rev-1",
},
unsubscribe: async () => undefined,
}),
});
return client;
}
function workspaceDescriptor(): WorkspaceDescriptor {
return {
createdAt: null,
lastUserMessageAt: null,
id: WORKSPACE_ID,
projectId: "project-1",
projectDisplayName: "project",
projectRootPath: "/repo",
workspaceDirectory: "/repo",
projectKind: "git",
workspaceKind: "local_checkout",
name: "main",
status: "done",
diffStat: null,
scripts: [],
statusEnteredAt: null,
archivingAt: null,
};
}
function agentDescriptor(): Agent {
return {
serverId: SERVER_ID,
id: AGENT_ID,
workspaceId: WORKSPACE_ID,
provider: "codex",
status: "idle",
createdAt: new Date("2026-12-04T00:00:00.000Z"),
updatedAt: new Date("2026-12-04T00:00:00.000Z"),
lastUserMessageAt: null,
lastActivityAt: new Date("2026-12-04T00:00:00.000Z"),
capabilities: {
supportsStreaming: true,
supportsSessionPersistence: true,
supportsDynamicModes: true,
supportsMcpServers: true,
supportsReasoningStream: true,
supportsToolInvocations: true,
},
currentModeId: null,
availableModes: [],
pendingPermissions: [],
persistence: null,
title: "Test Agent",
cwd: "/repo",
model: null,
parentAgentId: null,
labels: {},
archivedAt: null,
turn: { phase: "idle", cancellationRequestId: null },
};
}
function buildBundle(versionLabel: string): string {
return `(function(require) {
var React = require("react");
var RN = require("react-native");
function Controls(props) {
var prefix = props.prefix;
var _useState = React.useState(false);
var crashed = _useState[0];
var setCrashed = _useState[1];
if (crashed) throw new Error(prefix + " crashed");
return React.createElement(
RN.View,
null,
React.createElement(RN.Text, null, "${versionLabel}"),
React.createElement(
RN.Pressable,
{
accessibilityRole: "button",
onPress: function() { props.tab.setTitle(" " + prefix + " Override "); },
},
React.createElement(RN.Text, null, "Set " + prefix + " title")
),
React.createElement(
RN.Pressable,
{
accessibilityRole: "button",
onPress: function() { props.tab.setTitle(" "); },
},
React.createElement(RN.Text, null, "Whitespace " + prefix + " title")
),
React.createElement(
RN.Pressable,
{
accessibilityRole: "button",
onPress: function() { props.tab.setTitle(null); },
},
React.createElement(RN.Text, null, "Reset " + prefix + " title")
),
React.createElement(
RN.Pressable,
{
accessibilityRole: "button",
onPress: function() { setCrashed(true); },
},
React.createElement(RN.Text, null, "Crash " + prefix + " panel")
)
);
}
return {
default: function(client) {
client.addWorkspacePanel({
id: "overview",
title: "Overview",
icon: "PanelsTopLeft",
locations: ["workspace", "explorer"],
Component: function(props) {
return React.createElement(Controls, { tab: props.tab, prefix: "workspace" });
},
});
client.addAgentPanel({
id: "inspector",
title: "Inspector",
icon: "Scan",
locations: ["workspace", "explorer"],
Component: function(props) {
return React.createElement(Controls, { tab: props.tab, prefix: "agent" });
},
});
client.addFilePanel({
id: "txt-viewer",
title: "Custom TXT",
icon: "FileText",
files: { extensions: ["txt"] },
Component: function(props) {
return React.createElement(Controls, { tab: props.tab, prefix: "file" });
},
});
client.addWorkspacePanel({
id: "mount-effect",
title: "Static Mount",
icon: "PanelsTopLeft",
Component: function(props) {
React.useEffect(function() {
if ("${versionLabel}" === "v1") {
props.tab.setTitle("Mounted title");
props.tab.setModified(true);
} else if ("${versionLabel}" === "v3") {
props.tab.setTitle("Mounted v3");
}
}, []);
return React.createElement(RN.Text, null, "mount-${versionLabel}");
},
});
return function() {};
}
};
})`;
}
function installTestPlugin(client: DaemonClient, versionLabel = "v1") {
pluginExecutionApprovals.setDecision(SERVER_ID, PLUGIN_ID, "approved");
pluginRegistry.installCatalog(
SERVER_ID,
[
{
id: PLUGIN_ID,
requirements: { paseo: ">=0.8.0" },
clientBundle: buildBundle(versionLabel),
},
],
{ client, audio: { play: async () => 0 } },
);
}
function PresentationProbe({ tab }: { tab: WorkspaceTabDescriptor }) {
return (
<WorkspaceTabPresentationResolver tab={tab} serverId={SERVER_ID} workspaceId={WORKSPACE_ID}>
{(presentation: WorkspaceTabPresentation) => (
<View>
<Text testID="probe-label">{presentation.label}</Text>
<Text testID="probe-tooltip">{presentation.tooltip}</Text>
<Text testID="probe-modified">{String(presentation.modified)}</Text>
</View>
)}
</WorkspaceTabPresentationResolver>
);
}
function makePaneContext(tab: WorkspaceTabDescriptor): PaneContextValue {
return {
serverId: SERVER_ID,
workspaceId: WORKSPACE_ID,
host: "main",
tabId: tab.tabId,
target: tab.target,
openTab: noop,
openPreferredTarget: noop,
closeCurrentTab: noop,
retargetCurrentTab: noop,
setCurrentTabState: noop,
openFileInWorkspace: noop,
openImportSheet: noop,
};
}
describe("PluginTab.setTitle browser integration", () => {
let hostElement: HTMLElement;
let root: Root;
let client: DaemonClient;
beforeEach(async () => {
vi.stubGlobal("React", React);
hostElement = document.createElement("div");
document.body.appendChild(hostElement);
root = createRoot(hostElement);
await vi.waitFor(() => expect(useWorkspaceLayoutStore.persist.hasHydrated()).toBe(true));
useSessionStore.setState((state) => ({ ...state, sessions: {} }));
client = createFakeClient();
seedSessionHosts([SERVER_ID]);
await vi.waitFor(() =>
expect(useSessionStore.getState().sessions[SERVER_ID]?.hasRestoredCachedDirectory).toBe(true),
);
setHostRuntimeClient(SERVER_ID, client);
useSessionStore.getState().updateSessionClient(SERVER_ID, client);
seedSessionWorkspaces(SERVER_ID, new Map([[WORKSPACE_ID, workspaceDescriptor()]]));
useSessionStore.getState().setAgents(SERVER_ID, new Map([[AGENT_ID, agentDescriptor()]]));
installTestPlugin(client, "v1");
});
afterEach(() => {
root.unmount();
hostElement.remove();
pluginRegistry.removeHost(SERVER_ID);
pluginExecutionApprovals.clearHost(SERVER_ID);
seedSessionHosts([]);
});
it("updates, trims, clears, and resets workspace panel title on unmount, reload, and removal", async () => {
const PluginPanel = pluginPanelRegistration.component;
const paneContext = makePaneContext(WORKSPACE_TAB);
const renderHarness = (mountPanel: boolean) => {
root.render(
<PortalProvider>
<PresentationProbe tab={WORKSPACE_TAB} />
{mountPanel ? (
<PaneProvider value={paneContext}>
<PaneFocusProvider value={FOCUS_VALUE}>
<PluginPanel />
</PaneFocusProvider>
</PaneProvider>
) : null}
</PortalProvider>,
);
};
renderHarness(true);
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("Overview");
await expect.element(page.getByTestId("probe-tooltip")).toHaveTextContent("Overview");
await page.getByRole("button", { name: "Set workspace title", exact: true }).click();
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("workspace Override");
await expect.element(page.getByTestId("probe-tooltip")).toHaveTextContent("workspace Override");
await expect.element(page.getByTestId("probe-modified")).toHaveTextContent("false");
await page.getByRole("button", { name: "Whitespace workspace title", exact: true }).click();
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("Overview");
await page.getByRole("button", { name: "Set workspace title", exact: true }).click();
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("workspace Override");
// Plugin reload resets mounted tab title override back to the static title.
installTestPlugin(client, "v2");
await expect.element(page.getByText("v2")).toBeVisible();
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("Overview");
// Reset via null.
await page.getByRole("button", { name: "Set workspace title", exact: true }).click();
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("workspace Override");
await page.getByRole("button", { name: "Reset workspace title", exact: true }).click();
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("Overview");
// Unmount resets override back to static title.
await page.getByRole("button", { name: "Set workspace title", exact: true }).click();
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("workspace Override");
renderHarness(false);
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("Overview");
// Becoming unavailable (removing plugin) unmounts inner surface and clears override.
renderHarness(true);
await page.getByRole("button", { name: "Set workspace title", exact: true }).click();
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("workspace Override");
pluginRegistry.removeHost(SERVER_ID);
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("Plugin unavailable");
await expect
.element(page.getByTestId("probe-tooltip"))
.toHaveTextContent("This plugin panel is unavailable");
});
it("updates, resets, and clears agent panel title when agent disappears or panel unmounts", async () => {
const PluginPanel = pluginPanelRegistration.component;
const paneContext = makePaneContext(AGENT_TAB);
root.render(
<PortalProvider>
<PresentationProbe tab={AGENT_TAB} />
<PaneProvider value={paneContext}>
<PaneFocusProvider value={FOCUS_VALUE}>
<PluginPanel />
</PaneFocusProvider>
</PaneProvider>
</PortalProvider>,
);
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("Inspector");
await page.getByRole("button", { name: "Set agent title", exact: true }).click();
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("agent Override");
await expect.element(page.getByTestId("probe-tooltip")).toHaveTextContent("agent Override");
await page.getByRole("button", { name: "Reset agent title", exact: true }).click();
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("Inspector");
// Removing the agent unmounts the plugin body and clears the override.
await page.getByRole("button", { name: "Set agent title", exact: true }).click();
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("agent Override");
useSessionStore.getState().setAgents(SERVER_ID, new Map());
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("Inspector");
});
it("updates, resets, and clears file panel title on panel switch and unmount", async () => {
const FilePanel = filePanelRegistration.component;
const paneContext = makePaneContext(FILE_TAB);
const testQueryClient = new QueryClient();
const renderFile = (mountPanel: boolean) => {
root.render(
<QueryClientProvider client={testQueryClient}>
<PortalProvider>
<PresentationProbe tab={FILE_TAB} />
{mountPanel ? (
<PaneProvider value={paneContext}>
<PaneFocusProvider value={FOCUS_VALUE}>
<RetainedPanelActivity active>
<FilePanel />
</RetainedPanelActivity>
</PaneFocusProvider>
</PaneProvider>
) : null}
</PortalProvider>
</QueryClientProvider>,
);
};
renderFile(true);
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("notes.txt");
await expect.element(page.getByTestId("probe-tooltip")).toHaveTextContent("docs/notes.txt");
await expect.element(page.getByText("Open .txt files with")).toBeVisible();
getFilePanelChoice({
serverId: SERVER_ID,
workspaceId: WORKSPACE_ID,
tabId: FILE_TAB.tabId,
})?.dismissPicker();
await page.getByRole("button", { name: "Set file title", exact: true }).click();
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("file Override");
await expect.element(page.getByTestId("probe-tooltip")).toHaveTextContent("file Override");
await page.getByRole("button", { name: "Reset file title", exact: true }).click();
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("notes.txt");
await expect.element(page.getByTestId("probe-tooltip")).toHaveTextContent("docs/notes.txt");
// Reloading the file plugin clears the active title override.
await page.getByRole("button", { name: "Set file title", exact: true }).click();
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("file Override");
installTestPlugin(client, "v2");
await expect.element(page.getByText("v2")).toBeVisible();
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("notes.txt");
// A render error inside the file plugin surface clears the title override too.
await page.getByRole("button", { name: "Set file title", exact: true }).click();
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("file Override");
await page.getByRole("button", { name: "Crash file panel", exact: true }).click();
await expect.element(page.getByText("Plugin failed: file crashed")).toBeVisible();
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("notes.txt");
// Re-install to recover from error boundary, then switch the active file panel.
installTestPlugin(client, "v3");
await expect.element(page.getByText("v3")).toBeVisible();
await page.getByRole("button", { name: "Set file title", exact: true }).click();
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("file Override");
getFilePanelChoice({
serverId: SERVER_ID,
workspaceId: WORKSPACE_ID,
tabId: FILE_TAB.tabId,
})?.openWith("builtin:source");
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("notes.txt");
await expect.element(page.getByTestId("probe-tooltip")).toHaveTextContent("docs/notes.txt");
// Unmounting clears any override.
renderFile(false);
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("notes.txt");
});
it("preserves title and modified set in a mount effect and resets on reload", async () => {
const PluginPanel = pluginPanelRegistration.component;
const paneContext = makePaneContext(MOUNT_TAB);
root.render(
<PortalProvider>
<PresentationProbe tab={MOUNT_TAB} />
<PaneProvider value={paneContext}>
<PaneFocusProvider value={FOCUS_VALUE}>
<PluginPanel />
</PaneFocusProvider>
</PaneProvider>
</PortalProvider>,
);
await expect.element(page.getByText("mount-v1")).toBeVisible();
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("Mounted title");
await expect.element(page.getByTestId("probe-modified")).toHaveTextContent("true");
// Reloading to v2 (which does not call setTitle/setModified) clears both back to static defaults.
installTestPlugin(client, "v2");
await expect.element(page.getByText("mount-v2")).toBeVisible();
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("Static Mount");
await expect.element(page.getByTestId("probe-modified")).toHaveTextContent("false");
// Reloading to v3 (which calls setTitle in its mount effect) applies the new mount title.
installTestPlugin(client, "v3");
await expect.element(page.getByText("mount-v3")).toBeVisible();
await expect.element(page.getByTestId("probe-label")).toHaveTextContent("Mounted v3");
await expect.element(page.getByTestId("probe-modified")).toHaveTextContent("false");
});
});
+54 -15
View File
@@ -10,22 +10,67 @@ import type {
} from "@getpaseo/plugin/client";
import type { PluginClientStateSource } from "@getpaseo/plugin/client/host";
import { resolvePluginPanelOpenLocation } from "./workspace-panels/locations";
import { buildPluginPanelTarget } from "./workspace-panels/resolution";
import { parsePluginOpenScreenInput } from "./surface-contribution";
import type { InstalledPlugin } from "./types";
import { pluginWorkspaceLayoutSource } from "./workspace-layout";
export interface PluginPanelOpenPayload {
params?: Record<string, string | number>;
identityKey?: string;
}
export interface PluginNavigation {
openSettings(pluginId: string, screenId: string): void;
openSurface(pluginId: string, surfaceId: string, params?: PluginScreenParams): void;
openWorkspacePanel(pluginId: string, panelId: string, location: PluginPanelLocation): void;
openWorkspacePanel(
pluginId: string,
panelId: string,
location: PluginPanelLocation,
resolved?: PluginPanelOpenPayload,
): void;
openAgentPanel(
pluginId: string,
panelId: string,
agentId: string,
location: PluginPanelLocation,
resolved?: PluginPanelOpenPayload,
): void;
}
export function openPluginPanelFromLegacyCommand(input: {
plugin: InstalledPlugin;
navigation: PluginNavigation;
panelId: string;
agentId?: string;
options?: { location?: PluginPanelLocation };
}): void {
const { plugin, navigation, panelId, agentId, options } = input;
const panel = plugin.workspacePanels.find(
(candidate) =>
candidate.id === panelId && (agentId !== undefined || candidate.context === "workspace"),
);
if (!panel) throw new Error(`Workspace panel is unavailable: ${panelId}`);
const location = resolvePluginPanelOpenLocation(panel, options?.location);
const rawParams = panel.context === "agent" ? { agentId } : {};
const target = buildPluginPanelTarget(plugin.id, panel, rawParams);
if (!target) {
throw new Error(`Panel "${plugin.id}/${panelId}" does not accept these params`);
}
const resolved: PluginPanelOpenPayload | undefined =
target.params !== undefined || target.identityKey !== undefined
? {
...(target.params !== undefined ? { params: target.params } : {}),
...(target.identityKey !== undefined ? { identityKey: target.identityKey } : {}),
}
: undefined;
if (target.context === "workspace") {
navigation.openWorkspacePanel(plugin.id, panelId, location, resolved);
return;
}
navigation.openAgentPanel(plugin.id, panelId, target.agentId, location, resolved);
}
export function createPluginCapabilities(
plugin: InstalledPlugin,
navigation: PluginNavigation,
@@ -67,14 +112,13 @@ export function createPluginAgentActionContext(input: {
agent,
workspaceLayout: pluginWorkspaceLayoutSource(plugin).layout(workspace.id),
openPanel(panelId, options) {
const panel = plugin.workspacePanels.find((candidate) => candidate.id === panelId);
if (!panel) throw new Error(`Workspace panel is unavailable: ${panelId}`);
const location = resolvePluginPanelOpenLocation(panel, options?.location);
if (panel.context === "workspace") {
navigation.openWorkspacePanel(plugin.id, panelId, location);
return;
}
navigation.openAgentPanel(plugin.id, panelId, agent.id, location);
openPluginPanelFromLegacyCommand({
plugin,
navigation,
panelId,
agentId: agent.id,
options,
});
},
};
}
@@ -94,12 +138,7 @@ export function createPluginWorkspaceActionContext(input: {
workspace,
workspaceLayout: pluginWorkspaceLayoutSource(plugin).layout(workspace.id),
openPanel(panelId, options) {
const panel = plugin.workspacePanels.find(
(candidate) => candidate.id === panelId && candidate.context === "workspace",
);
if (!panel) throw new Error(`Workspace panel is unavailable: ${panelId}`);
const location = resolvePluginPanelOpenLocation(panel, options?.location);
navigation.openWorkspacePanel(plugin.id, panelId, location);
openPluginPanelFromLegacyCommand({ plugin, navigation, panelId, options });
},
};
}
@@ -5,6 +5,7 @@ import { describe, expect, it } from "vitest";
import type { PluginButton } from "@getpaseo/plugin/client";
import type { InstalledPlugin } from "../types";
import { PluginButtonStore, buttonMatches } from "./model";
import { buttonPageId } from "./validation";
function installation(): InstalledPlugin {
return {
@@ -29,6 +30,7 @@ function installation(): InstalledPlugin {
workspaceRowBadgeItems: [],
filePanels: [],
composerItems: [],
composerPillItems: [],
newWorkspaceItems: [],
workspacePanels: [],
commandCenterItems: [],
@@ -262,3 +264,163 @@ it("keeps the previous descriptor after rejecting an invalid update", () => {
registration.remove();
plugin.i18n.dispose();
});
it("keeps an open popover open when update keeps the same popover Content reference, and closes on Content, kind, visible, or disabled change", () => {
const buttons = store();
const plugin = installation();
const FirstPopover = () => null;
const SecondPopover = () => null;
const registration = buttons.addComposerPill(plugin, {
id: "inbox",
workspaceId: "workspace",
agentId: "agent",
button: {
title: "Inbox",
icon: "Scan",
label: "1 decision",
behavior: { kind: "popover", Content: FirstPopover },
},
});
const key = buttons.getSnapshot()[0].key;
buttons.setOpen(key, true);
expect(buttons.getSnapshot()[0].open).toBe(true);
registration.update({
label: "2 decisions",
behavior: { kind: "popover", Content: FirstPopover },
});
expect(buttons.getSnapshot()[0].open).toBe(true);
expect(buttons.getSnapshot()[0].button.label).toBe("2 decisions");
registration.update({
behavior: { kind: "popover", Content: SecondPopover },
});
expect(buttons.getSnapshot()[0].open).toBe(false);
buttons.setOpen(key, true);
registration.update({ disabled: true, behavior: { kind: "popover", Content: SecondPopover } });
expect(buttons.getSnapshot()[0].open).toBe(false);
registration.update({ disabled: false });
buttons.setOpen(key, true);
registration.update({ visible: false, behavior: { kind: "popover", Content: SecondPopover } });
expect(buttons.getSnapshot()[0].open).toBe(false);
registration.update({ visible: true });
buttons.setOpen(key, true);
registration.update({ behavior: { kind: "action", onPress() {} } });
expect(buttons.getSnapshot()[0].open).toBe(false);
registration.remove();
plugin.i18n.dispose();
});
it("accepts non-empty trimmed unique menu entry IDs while keeping top-level button IDs kebab-case", async () => {
const buttons = store();
const plugin = installation();
expect(() =>
buttons.addComposerPill(plugin, {
id: "D42",
workspaceId: "workspace",
agentId: "agent",
button: button(),
}),
).toThrow("Invalid plugin button id: D42");
const pressed: string[] = [];
const registration = buttons.addComposerPill(plugin, {
id: "inbox",
workspaceId: "workspace",
agentId: "agent",
button: {
title: "Inbox",
icon: "Scan",
behavior: {
kind: "menu",
items: [
{
kind: "item",
id: " D42 ",
title: "Decision 42",
behavior: { kind: "action", onPress: () => void pressed.push("D42") },
},
{ kind: "separator", id: "sep_123e4567-e89b-12d3-a456-426614174000" },
{
kind: "item",
id: "550e8400-e29b-41d4-a716-446655440000",
title: "Decision UUID",
behavior: { kind: "action", onPress: () => void pressed.push("uuid") },
},
],
},
},
});
const entry = buttons.getSnapshot()[0];
expect(entry.button.behavior).toMatchObject({
kind: "menu",
items: [
{ kind: "item", id: "D42" },
{ kind: "separator", id: "sep_123e4567-e89b-12d3-a456-426614174000" },
{ kind: "item", id: "550e8400-e29b-41d4-a716-446655440000" },
],
});
await buttons.run(entry.key, ["D42"]);
await buttons.run(entry.key, ["550e8400-e29b-41d4-a716-446655440000"]);
expect(pressed).toEqual(["D42", "uuid"]);
expect(() =>
registration.update({
behavior: {
kind: "menu",
items: [
{
kind: "item",
id: " ",
title: "Blank",
behavior: { kind: "action", onPress() {} },
},
],
},
}),
).toThrow();
expect(() =>
registration.update({
behavior: {
kind: "menu",
items: [
{
kind: "item",
id: "D42",
title: "First",
behavior: { kind: "action", onPress() {} },
},
{
kind: "item",
id: " D42 ",
title: "Duplicate",
behavior: { kind: "action", onPress() {} },
},
],
},
}),
).toThrow("Duplicate plugin button menu item: D42");
expect(() =>
registration.update({
behavior: {
kind: "menu",
items: [{ kind: "separator", id: "" }],
},
}),
).toThrow();
registration.remove();
plugin.i18n.dispose();
});
it("serializes submenu page IDs without collisions when entry IDs contain slashes", () => {
expect(buttonPageId(1, ["a/b"])).not.toBe(buttonPageId(1, ["a", "b"]));
expect(buttonPageId(1, ["D42"])).toBe("plugin-button/1/D42");
});
+6 -1
View File
@@ -123,7 +123,12 @@ export class PluginButtonStore {
const nextSource = { ...sourceButton, ...patch };
const button = validateButton(nextSource, this.validation, installation.i18n.resolve);
sourceButton = nextSource;
const close = !button.visible || button.disabled || patch.behavior !== undefined;
const keepsOpenPopover =
entry.button.behavior.kind === "popover" &&
button.behavior.kind === "popover" &&
entry.button.behavior.Content === button.behavior.Content;
const close =
!button.visible || button.disabled || (patch.behavior !== undefined && !keepsOpenPopover);
this.replace(key, { button, open: close ? false : entry.open });
},
remove: () => {
+21 -4
View File
@@ -19,6 +19,22 @@ export function requireButtonId(value: string): string {
return value;
}
/** Submenu page IDs joined on `/` must encode segments so arbitrary menu IDs (e.g. `a/b`) stay unique. */
export function buttonPageId(key: number, path: readonly string[]): string {
return ["plugin-button", String(key), ...path.map((segment) => encodeURIComponent(segment))].join(
"/",
);
}
function requireMenuEntryId(value: string): string {
if (typeof value !== "string") {
throw new Error(`Invalid plugin button menu item id: ${String(value)}`);
}
const id = value.trim();
if (!id) throw new Error(`Invalid plugin button menu item id: ${value}`);
return id;
}
function optionalBoolean(value: boolean | undefined, fallback: boolean): boolean {
if (value === undefined) return fallback;
if (typeof value !== "boolean")
@@ -61,13 +77,14 @@ function validateBehavior(
return {
kind: "menu",
items: behavior.items.map((item) => {
requireButtonId(item.id);
if (ids.has(item.id)) throw new Error(`Duplicate plugin button menu item: ${item.id}`);
ids.add(item.id);
if (item.kind === "separator") return { ...item };
const id = requireMenuEntryId(item.id);
if (ids.has(id)) throw new Error(`Duplicate plugin button menu item: ${id}`);
ids.add(id);
if (item.kind === "separator") return { ...item, id };
if (item.kind !== "item") throw new Error("Invalid plugin button menu entry");
return {
...item,
id,
icon: item.icon === undefined ? undefined : validation.parseIcon(item.icon),
title: requireText(item.title, "menu item title", resolve),
visible: optionalBoolean(item.visible, true),
+4 -8
View File
@@ -1,6 +1,7 @@
import type {
ResolvedPluginButtonBehavior as PluginButtonBehavior,
ResolvedPluginButtonMenuEntry as PluginButtonMenuEntry,
import {
buttonPageId,
type ResolvedPluginButtonBehavior as PluginButtonBehavior,
type ResolvedPluginButtonMenuEntry as PluginButtonMenuEntry,
} from "./validation";
import type { PluginButtonIcon, PluginHostProps } from "@getpaseo/plugin/client";
import type { PluginTheme } from "@getpaseo/plugin";
@@ -210,11 +211,6 @@ function ButtonSurfaceBody({
);
}
// Prefixed so plugin pages can share a surface with the host's own pages.
function buttonPageId(key: number, path: readonly string[]): string {
return ["plugin-button", key, ...path].join("/");
}
type RenderButtonPage = (behavior: PluginButtonBehavior, path: readonly string[]) => ReactNode;
/** A page for every menu and popover item below `behavior`, depth first. */
@@ -110,6 +110,7 @@ function plugin(onAgentSelect: AgentCommandItem["onSelect"]): InstalledPlugin {
workspaceRowBadgeItems: [],
filePanels: [],
composerItems: [],
composerPillItems: [],
newWorkspaceItems: [],
workspacePanels: [
{
@@ -2,9 +2,12 @@ import type { PluginClientStateSource } from "@getpaseo/plugin/client/host";
import type { CommandCenterContribution } from "@/command-center/contributions";
import { getCommandCenterIcon } from "@/command-center/icon";
import { pluginIconComponent } from "../icons";
import { resolvePluginPanelOpenLocation } from "../workspace-panels/locations";
import type { InstalledPlugin } from "../types";
import { createPluginCapabilities, type PluginNavigation } from "../actions";
import {
createPluginCapabilities,
openPluginPanelFromLegacyCommand,
type PluginNavigation,
} from "../actions";
import { pluginWorkspaceLayoutSource } from "../workspace-layout";
export interface PluginCommandCenterSource {
@@ -43,12 +46,12 @@ export function buildPluginCommandCenterContributions(
workspace,
workspaceLayout,
openPanel(panelId, options) {
const panel = plugin.workspacePanels.find(
(candidate) => candidate.id === panelId && candidate.context === "workspace",
);
if (!panel) throw new Error(`Workspace panel is unavailable: ${panelId}`);
const location = resolvePluginPanelOpenLocation(panel, options?.location);
source.navigation.openWorkspacePanel(plugin.id, panelId, location);
openPluginPanelFromLegacyCommand({
plugin,
navigation: source.navigation,
panelId,
options,
});
},
});
return;
@@ -62,14 +65,13 @@ export function buildPluginCommandCenterContributions(
agent,
workspaceLayout,
openPanel(panelId, options) {
const panel = plugin.workspacePanels.find((candidate) => candidate.id === panelId);
if (!panel) throw new Error(`Workspace panel is unavailable: ${panelId}`);
const location = resolvePluginPanelOpenLocation(panel, options?.location);
if (panel.context === "workspace") {
source.navigation.openWorkspacePanel(plugin.id, panelId, location);
return;
}
source.navigation.openAgentPanel(plugin.id, panelId, agent.id, location);
openPluginPanelFromLegacyCommand({
plugin,
navigation: source.navigation,
panelId,
agentId: agent.id,
options,
});
},
});
} catch (error) {
@@ -36,6 +36,7 @@ function installed(): InstalledPlugin {
sidebarViews: [],
filePanels: [],
composerItems: [],
composerPillItems: [],
newWorkspaceItems: [],
workspaceRowBadgeItems: [],
workspacePanels: [],
@@ -46,6 +46,7 @@ function plugin(): InstalledPlugin {
sidebarViews: [],
filePanels: [],
composerItems: [],
composerPillItems: [],
newWorkspaceItems: [],
workspaceRowBadgeItems: [],
workspacePanels: [],
@@ -0,0 +1,21 @@
import { createContext, useContext } from "react";
import type { View } from "react-native";
/** What the host tells `ComposerPill` about the composer pill item it renders in. */
export interface ComposerPillItemFrame {
title: string;
testID: string;
popoverOpen: boolean;
isAnchoredTo: (node: View | null) => boolean;
/** A pill calls this before its `onPress`, so a popover that press opens anchors to it. */
anchorTo: (node: View | null) => void;
/** Pills offer themselves on mount, so a popover opened without a press anchors to a pill. */
offerAnchor: (node: View | null) => void;
releaseAnchor: (node: View | null) => void;
}
export const ComposerPillItemFrameContext = createContext<ComposerPillItemFrame | null>(null);
export function useComposerPillItemFrame(): ComposerPillItemFrame | null {
return useContext(ComposerPillItemFrameContext);
}
@@ -0,0 +1,472 @@
import React, {
act,
useCallback,
useEffect,
useMemo,
useRef,
useState,
type ReactNode,
} from "react";
import { createRoot, type Root } from "react-dom/client";
import { Pressable, Text, View, type ViewStyle } from "react-native";
import { createPaseoApi } from "@getpaseo/client";
import { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import { QueryClient } from "@tanstack/react-query";
import { router } from "expo-router";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { page } from "vitest/browser";
import {
useWorkspace,
type PluginComposerPillItemProps,
type PluginPopoverProps,
} from "@getpaseo/plugin/client";
import { PluginTranslationRuntime } from "@getpaseo/plugin/client/host";
import type { ToastApi } from "@/components/toast-host";
import { ToastApiProvider } from "@/contexts/toast-api-context";
import { useSessionStore } from "@/stores/session-store";
import { seedSessionWorkspaces } from "@/test/seed-session";
import { connectedPluginHosts } from "../client-state/connected-hosts";
import { workspace as workspaceFixture } from "../client-state/fixtures";
import { pluginRegistry } from "../registry";
import type { InstalledPlugin } from "../types";
import { ComposerPill, PluginComposerPillItems } from "./index";
// App sources compile against the classic JSX runtime, which expects React on the global.
beforeEach(() => vi.stubGlobal("React", React));
const noop = () => {};
const explodeSync = () => {
throw new Error("Sync boom");
};
const rowStyle: ViewStyle = { flexDirection: "row" };
const popoverContainerStyle: ViewStyle = { gap: 8 };
const anchoredWrapperStyle: ViewStyle = { position: "absolute", top: 700, left: 40 };
interface Mounted {
root: Root;
container: HTMLDivElement;
}
const mounted: Mounted[] = [];
function mount(node: ReactNode, toast: ToastApi): HTMLDivElement {
const container = document.createElement("div");
document.body.appendChild(container);
const root = createRoot(container);
act(() => root.render(<ToastApiProvider api={toast}>{node}</ToastApiProvider>));
mounted.push({ root, container });
return container;
}
function makePlugin(
composerPillItems: InstalledPlugin["composerPillItems"],
overrides: Partial<InstalledPlugin> = {},
): InstalledPlugin {
return {
lifetime: new AbortController(),
locale: "en",
i18n: new PluginTranslationRuntime({ getLocale: () => "en", subscribe: () => () => {} }),
id: "inbox-plugin",
serverId: "host-a",
clientBundle: "bundle",
queryClient: new QueryClient(),
paseo: createPaseoApi(
new DaemonClient({
url: "ws://127.0.0.1:1",
clientId: "composer-pill-items-test",
reconnect: { enabled: false },
}),
),
invoke: async () => undefined,
subscribe: () => {
throw new Error("Subscriptions are not used here");
},
cleanup: () => undefined,
settingsScreens: [],
surfaces: [{ id: "details", title: "Details", Component: () => null }],
sidebarViews: [],
sidebarItems: { header: [], footer: [] },
legacySidebarItems: [],
workspaceRowBadgeItems: [],
filePanels: [],
composerItems: [],
composerPillItems,
newWorkspaceItems: [],
workspacePanels: [],
commandCenterItems: [],
clientSlashCommands: [],
attachmentSources: [],
themes: [],
timelineTransformers: [],
timelineRenderers: [],
notificationOpenHandlers: [],
...overrides,
};
}
function setInstalledPlugins(plugins: InstalledPlugin[]) {
vi.spyOn(pluginRegistry, "getSnapshot").mockReturnValue(plugins);
vi.spyOn(pluginRegistry, "subscribe").mockImplementation(() => () => {});
}
function makeToast(): { toast: ToastApi; errors: string[] } {
const errors: string[] = [];
const toast = {
show: vi.fn(),
error: vi.fn((message: string) => {
errors.push(message);
}),
} as unknown as ToastApi;
return { toast, errors };
}
afterEach(() => {
for (const entry of mounted.splice(0)) {
act(() => entry.root.unmount());
entry.container.remove();
}
vi.restoreAllMocks();
});
describe("PluginComposerPillItems & ComposerPill", () => {
beforeEach(async () => {
await page.viewport(1280, 900);
});
it("mounts per (workspaceId, agentId), passes host props, and returns null cleanly with no wrapper gap", () => {
const seen: { workspaceId: string; agentId: string }[] = [];
const plugin = makePlugin([
{
id: "quiet",
title: "Quiet",
Component({ workspaceId, agentId }: PluginComposerPillItemProps) {
seen.push({ workspaceId, agentId });
return null;
},
},
{
id: "active",
title: "Active pill",
Component({ workspaceId, agentId }: PluginComposerPillItemProps) {
return <ComposerPill icon="Inbox" label={`${workspaceId}:${agentId}`} onPress={noop} />;
},
},
]);
setInstalledPlugins([plugin]);
const { toast } = makeToast();
function Harness() {
const [agentId, setAgentId] = useState("agent-1");
const switchToAgent2 = useCallback(() => setAgentId("agent-2"), []);
return (
<>
<Pressable
accessibilityRole="button"
accessibilityLabel="Switch agent"
onPress={switchToAgent2}
>
<Text>Switch</Text>
</Pressable>
<View testID="track-row" style={rowStyle}>
<PluginComposerPillItems serverId="host-a" workspaceId="ws-1" agentId={agentId} />
</View>
</>
);
}
const container = mount(<Harness />, toast);
const trackRow = container.querySelector('[data-testid="track-row"]')!;
// Only the active pill renders a child node; the null item adds no wrapper View.
expect(trackRow.children).toHaveLength(1);
expect(seen).toEqual([{ workspaceId: "ws-1", agentId: "agent-1" }]);
expect(trackRow.textContent).toBe("ws-1:agent-1");
const switchButton = container.querySelector('[aria-label="Switch agent"]') as HTMLElement;
act(() => switchButton.click());
expect(seen).toEqual([
{ workspaceId: "ws-1", agentId: "agent-1" },
{ workspaceId: "ws-1", agentId: "agent-2" },
]);
expect(trackRow.textContent).toBe("ws-1:agent-2");
});
it("isolates throwing items behind SurfaceErrorBoundary while siblings remain visible", () => {
vi.spyOn(console, "warn").mockImplementation(() => {});
const plugin = makePlugin([
{
id: "broken",
title: "Broken",
Component() {
throw new Error("pill exploded");
},
},
{
id: "healthy",
title: "Healthy",
Component() {
return <ComposerPill icon="Check" label="Healthy" onPress={noop} />;
},
},
]);
setInstalledPlugins([plugin]);
const { toast } = makeToast();
const container = mount(
<View testID="track-row" style={rowStyle}>
<PluginComposerPillItems serverId="host-a" workspaceId="ws-1" agentId="agent-1" />
</View>,
toast,
);
const trackRow = container.querySelector('[data-testid="track-row"]')!;
expect(trackRow.children).toHaveLength(1);
expect(trackRow.textContent).toBe("Healthy");
});
it("handles pending-promise busy state, prevents double presses, reports errors in toast, and allows retry", async () => {
let finish = () => {};
let attempt = 0;
const plugin = makePlugin([
{
id: "run",
title: "Run check",
Component() {
const handleRunPress = useCallback(() => {
attempt += 1;
if (attempt === 1) return Promise.reject(new Error("Check failed"));
return new Promise<void>((resolve) => {
finish = resolve;
});
}, []);
return (
<ComposerPill
icon="Play"
label="Run"
title="Run check tooltip"
onPress={handleRunPress}
/>
);
},
},
]);
setInstalledPlugins([plugin]);
const { toast, errors } = makeToast();
const container = mount(
<PluginComposerPillItems serverId="host-a" workspaceId="ws-1" agentId="agent-1" />,
toast,
);
const pill = container.querySelector(
'[data-testid="plugin-composer-pill-inbox-plugin-run"]',
) as HTMLElement;
expect(pill).toBeTruthy();
expect(pill.getAttribute("aria-label")).toBe("Run check tooltip");
// First attempt rejects -> error toast shown, pill recovers for retry.
await act(async () => {
pill.click();
});
expect(errors).toEqual(["Check failed"]);
expect(pill.getAttribute("aria-disabled")).not.toBe("true");
// Second attempt stays pending -> blocks repeated press until settled.
act(() => {
pill.click();
});
expect(pill.getAttribute("aria-disabled")).toBe("true");
expect(pill.getAttribute("aria-busy")).toBe("true");
act(() => {
pill.click();
});
expect(attempt).toBe(2);
await act(async () => {
finish();
});
expect(pill.getAttribute("aria-disabled")).not.toBe("true");
expect(pill.getAttribute("aria-busy")).not.toBe("true");
});
it("anchors openPopover above the pill on desktop, provides plugin environment, and navigates via openScreen", async () => {
const pushSpy = vi.spyOn(router, "push").mockImplementation(() => {});
vi.spyOn(connectedPluginHosts, "getSnapshot").mockReturnValue(["host-a"]);
useSessionStore.getState().initializeSession("host-a", null);
seedSessionWorkspaces(
"host-a",
new Map([["ws-1", { ...workspaceFixture, id: "ws-1", name: "My Workspace" }]]),
);
function PopoverBody({ theme, close, openScreen }: PluginPopoverProps) {
// Reads from PluginInstallationProvider inside the portal.
const workspace = useWorkspace("ws-1", (entry) => entry.name);
const titleStyle = useMemo(
() => ({ color: theme.colors.foreground }),
[theme.colors.foreground],
);
const handleOpenDetails = useCallback(
() => openScreen({ screenId: "details", params: { tab: "inbox" } }),
[openScreen],
);
return (
<View style={popoverContainerStyle}>
<Text testID="popover-title" style={titleStyle}>
Inbox popover ({workspace ?? "no-ws"})
</Text>
<Pressable
accessibilityRole="button"
accessibilityLabel="Open details screen"
onPress={handleOpenDetails}
>
<Text>Open screen</Text>
</Pressable>
<Pressable accessibilityRole="button" accessibilityLabel="Close popover" onPress={close}>
<Text>Close</Text>
</Pressable>
</View>
);
}
const plugin = makePlugin([
{
id: "inbox",
title: "Inbox",
Component({ openPopover }: PluginComposerPillItemProps) {
const handleOpenPopover = useCallback(() => openPopover(PopoverBody), [openPopover]);
return <ComposerPill icon="Inbox" label="2 decisions" onPress={handleOpenPopover} />;
},
},
]);
setInstalledPlugins([plugin]);
const { toast } = makeToast();
const container = mount(
<View style={anchoredWrapperStyle}>
<PluginComposerPillItems serverId="host-a" workspaceId="ws-1" agentId="agent-1" />
</View>,
toast,
);
const pill = container.querySelector(
'[data-testid="plugin-composer-pill-inbox-plugin-inbox"]',
) as HTMLElement;
act(() => pill.click());
await expect
.poll(() => document.querySelector('[data-testid="popover-title"]')?.textContent)
.toBe("Inbox popover (My Workspace)");
const pillRect = pill.getBoundingClientRect();
const popoverSurface = document.querySelector(
'[data-testid="plugin-composer-pill-inbox-plugin-inbox-popover"]',
) as HTMLElement;
expect(popoverSurface).toBeTruthy();
await expect
.poll(() => popoverSurface.getBoundingClientRect().bottom <= pillRect.top + 1)
.toBe(true);
// Clicking openScreen from inside the popover closes it and navigates.
const openScreenBtn = document.querySelector(
'[aria-label="Open details screen"]',
) as HTMLElement;
act(() => openScreenBtn.click());
expect(pushSpy).toHaveBeenCalledTimes(1);
expect(String(pushSpy.mock.calls[0]?.[0])).toContain(
"/h/host-a/plugin/inbox-plugin/surface/details",
);
await expect.poll(() => document.querySelector('[data-testid="popover-title"]')).toBeNull();
});
it("ignores presses when disabled and reports synchronous throws in toast", () => {
let pressed = 0;
const plugin = makePlugin([
{
id: "disabled-pill",
title: "Disabled",
Component() {
const incrementPressed = useCallback(() => {
pressed += 1;
}, []);
return <ComposerPill icon="Check" label="Locked" disabled onPress={incrementPressed} />;
},
},
{
id: "throws-sync",
title: "Throws",
Component() {
return <ComposerPill icon="Check" label="Explode" onPress={explodeSync} />;
},
},
]);
setInstalledPlugins([plugin]);
const { toast, errors } = makeToast();
const container = mount(
<PluginComposerPillItems serverId="host-a" workspaceId="ws-1" agentId="agent-1" />,
toast,
);
const disabledPill = container.querySelector(
'[data-testid="plugin-composer-pill-inbox-plugin-disabled-pill"]',
) as HTMLElement;
expect(disabledPill.getAttribute("aria-disabled")).toBe("true");
act(() => disabledPill.click());
expect(pressed).toBe(0);
const syncPill = container.querySelector(
'[data-testid="plugin-composer-pill-inbox-plugin-throws-sync"]',
) as HTMLElement;
act(() => syncPill.click());
expect(errors).toEqual(["Sync boom"]);
});
it("anchors openPopover above fallbackAnchorRef when an item opens without a mounted ComposerPill", async () => {
function FallbackPopoverBody() {
return <Text testID="fallback-popover-body">Opened from effect</Text>;
}
const plugin = makePlugin([
{
id: "effect-only",
title: "Effect only",
Component({ openPopover }: PluginComposerPillItemProps) {
useEffect(() => {
openPopover(FallbackPopoverBody);
}, [openPopover]);
return null;
},
},
]);
setInstalledPlugins([plugin]);
const { toast } = makeToast();
function FallbackHarness() {
const fallbackAnchorRef = useRef<View | null>(null);
return (
<View ref={fallbackAnchorRef} testID="fallback-anchor" style={anchoredWrapperStyle}>
<PluginComposerPillItems
serverId="host-a"
workspaceId="ws-1"
agentId="agent-1"
fallbackAnchorRef={fallbackAnchorRef}
/>
</View>
);
}
const container = mount(<FallbackHarness />, toast);
const anchor = container.querySelector('[data-testid="fallback-anchor"]') as HTMLElement;
await expect
.poll(() => document.querySelector('[data-testid="fallback-popover-body"]')?.textContent)
.toBe("Opened from effect");
const popoverSurface = document.querySelector(
'[data-testid="plugin-composer-pill-inbox-plugin-effect-only-popover"]',
) as HTMLElement;
expect(popoverSurface).toBeTruthy();
await expect
.poll(
() =>
popoverSurface.getBoundingClientRect().bottom <= anchor.getBoundingClientRect().top + 1,
)
.toBe(true);
});
});
@@ -0,0 +1,234 @@
import type { PluginTheme } from "@getpaseo/plugin";
import type {
PluginComposerPillItemProps,
PluginHostProps,
PluginOpenScreenInput,
PluginPopoverProps,
} from "@getpaseo/plugin/client";
import { router } from "expo-router";
import { useCallback, useMemo, useState, type ComponentType, type RefObject } from "react";
import type { View } from "react-native";
import { withUnistyles } from "react-native-unistyles";
import { MenuRoot } from "@/components/ui/menu";
import { pluginScreensHostKey, rememberPluginContributionHost } from "../contribution-host";
import { pluginThemeMapping, renderNothing, usePluginItemHost } from "../item-host";
import {
PluginEnvironmentProvider,
PluginPopoverContent,
PluginPopoverSurface,
usePluginPopoverAnchor,
type PluginEnvironment,
} from "../popover";
import { useInstalledPlugins } from "../registry";
import { buildPluginSurfaceRoute } from "../routes";
import { parsePluginOpenScreenInput } from "../surface-contribution";
import { SurfaceErrorBoundary } from "../surface-error-boundary";
import type { InstalledPlugin, PluginComposerPillItemContribution } from "../types";
import { ComposerPillItemFrameContext, type ComposerPillItemFrame } from "./frame";
export { ComposerPill } from "./kit";
type PopoverContent = ComponentType<PluginPopoverProps>;
interface ComposerPillItemTarget {
plugin: InstalledPlugin;
item: PluginComposerPillItemContribution;
}
/**
* Declarative composer pill items for one visible agent tab. Each item mounts behind its own error
* boundary and plugin environment with no wrapper views, so returning `null` leaves no gap.
*/
export function PluginComposerPillItems({
serverId,
workspaceId,
agentId,
fallbackAnchorRef,
}: {
serverId: string;
workspaceId: string;
agentId: string;
fallbackAnchorRef?: RefObject<View | null>;
}) {
const installed = useInstalledPlugins();
const targets = useMemo<ComposerPillItemTarget[]>(
() =>
installed
.filter((plugin) => plugin.serverId === serverId)
.flatMap((plugin) => plugin.composerPillItems.map((item) => ({ plugin, item }))),
[installed, serverId],
);
return targets.map(({ plugin, item }) => (
<ThemedComposerPillItemHost
key={`${plugin.id}/${item.id}:${workspaceId}:${agentId}`}
plugin={plugin}
item={item}
workspaceId={workspaceId}
agentId={agentId}
fallbackAnchorRef={fallbackAnchorRef}
uniProps={pluginThemeMapping}
/>
));
}
function ComposerPillItemHost({
plugin,
item,
workspaceId,
agentId,
fallbackAnchorRef,
theme,
}: {
plugin: InstalledPlugin;
item: PluginComposerPillItemContribution;
workspaceId: string;
agentId: string;
fallbackAnchorRef?: RefObject<View | null>;
theme: PluginTheme;
}) {
const { environment, props: hostProps } = usePluginItemHost(plugin, theme);
// The content outlives `open` so the surface can play its exit and native sheet teardown.
const [popover, setPopover] = useState<PopoverContent | null>(null);
const [popoverOpen, setPopoverOpen] = useState(false);
const showPopover = useCallback((content: PopoverContent | null) => {
// A function passed to a state setter is an updater, so wrap the component.
if (content) setPopover(() => content);
setPopoverOpen(content !== null);
}, []);
const handleOpenChange = useCallback((open: boolean) => {
if (!open) setPopoverOpen(false);
}, []);
return (
<SurfaceErrorBoundary
installation={plugin}
Surface={item.Component}
renderError={renderNothing}
>
<PluginEnvironmentProvider environment={environment}>
<MenuRoot compactMode="sheet" open={popoverOpen} onOpenChange={handleOpenChange}>
<ComposerPillItemContent
plugin={plugin}
item={item}
workspaceId={workspaceId}
agentId={agentId}
fallbackAnchorRef={fallbackAnchorRef}
hostProps={hostProps}
environment={environment}
popover={popover}
popoverOpen={popoverOpen}
showPopover={showPopover}
/>
</MenuRoot>
</PluginEnvironmentProvider>
</SurfaceErrorBoundary>
);
}
const ThemedComposerPillItemHost = withUnistyles(ComposerPillItemHost);
function ComposerPillItemContent({
plugin,
item,
workspaceId,
agentId,
fallbackAnchorRef,
hostProps,
environment,
popover,
popoverOpen,
showPopover,
}: {
plugin: InstalledPlugin;
item: PluginComposerPillItemContribution;
workspaceId: string;
agentId: string;
fallbackAnchorRef?: RefObject<View | null>;
hostProps: PluginHostProps;
environment: PluginEnvironment;
popover: PopoverContent | null;
popoverOpen: boolean;
showPopover: (content: PopoverContent | null) => void;
}) {
const { triggerRef, anchorTo, offerAnchor, releaseAnchor, anchorToFallback } =
usePluginPopoverAnchor("PluginComposerPillItem");
const title = plugin.i18n.resolve(item.title, plugin.locale);
const testID = `plugin-composer-pill-${plugin.id}-${item.id}`;
const openScreen = useCallback(
(input: PluginOpenScreenInput) => {
const { screenId, params } = parsePluginOpenScreenInput(plugin, input);
rememberPluginContributionHost(pluginScreensHostKey(plugin.id), plugin.serverId);
showPopover(null);
router.push(
buildPluginSurfaceRoute(
plugin.serverId,
plugin.id,
{ kind: "surface", id: screenId },
params,
),
);
},
[plugin, showPopover],
);
const openPopover = useCallback(
(Content: PopoverContent) => {
if (fallbackAnchorRef) anchorToFallback(fallbackAnchorRef);
showPopover(Content);
},
[anchorToFallback, fallbackAnchorRef, showPopover],
);
const close = useCallback(() => showPopover(null), [showPopover]);
const isAnchoredTo = useCallback(
(node: View | null) => triggerRef.current === node,
[triggerRef],
);
const frame = useMemo<ComposerPillItemFrame>(
() => ({
title,
testID,
popoverOpen,
isAnchoredTo,
anchorTo,
offerAnchor,
releaseAnchor,
}),
[anchorTo, isAnchoredTo, offerAnchor, popoverOpen, releaseAnchor, testID, title],
);
const itemProps = useMemo<PluginComposerPillItemProps>(
() => ({ ...hostProps, workspaceId, agentId, openScreen, openPopover }),
[agentId, hostProps, openPopover, openScreen, workspaceId],
);
const Item = item.Component;
const Popover = popover;
return (
<ComposerPillItemFrameContext.Provider value={frame}>
<Item {...itemProps} />
{Popover ? (
<PluginPopoverSurface
sheetTitle={title}
side="top"
align="start"
offset={12}
testID={`${testID}-popover`}
>
<SurfaceErrorBoundary installation={plugin} Surface={Popover}>
<PluginEnvironmentProvider environment={environment}>
<PluginPopoverContent>
<Popover {...hostProps} close={close} openScreen={openScreen} />
</PluginPopoverContent>
</PluginEnvironmentProvider>
</SurfaceErrorBoundary>
</PluginPopoverSurface>
) : null}
</ComposerPillItemFrameContext.Provider>
);
}
@@ -0,0 +1,171 @@
import type { ComposerPillProps } from "@getpaseo/plugin/client/ui";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Text, View } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { PressHighlight } from "@/components/ui/press-highlight";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { composerPillStyles } from "@/composer/pill-styles";
import { useToast } from "@/contexts/toast-api-context";
import type { Theme } from "@/styles/theme";
import { toErrorMessage } from "@/utils/error-messages";
import { parsePluginIcon, PluginIconView } from "../icons";
import { useComposerPillItemFrame } from "./frame";
const ThemedPluginIconView = withUnistyles(PluginIconView);
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
const mutedIconMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
function isPromiseLike(value: unknown): value is PromiseLike<unknown> {
return (
(typeof value === "object" || typeof value === "function") &&
value !== null &&
"then" in value &&
typeof (value as { then?: unknown }).then === "function"
);
}
/**
* A pill above an agent's composer. Matches Paseo's composer pill chrome, pending-promise state,
* and error toast handling while anchoring any popover opened by `openPopover` to the pressed pill.
*/
export function ComposerPill({ icon, label, title, disabled = false, onPress }: ComposerPillProps) {
const frame = useComposerPillItemFrame();
const toast = useToast();
const pillRef = useRef<View | null>(null);
const mountedRef = useRef(true);
const pendingRef = useRef(false);
const [pending, setPending] = useState(false);
useEffect(() => {
mountedRef.current = true;
return () => {
mountedRef.current = false;
};
}, []);
const offerAnchor = frame?.offerAnchor;
const releaseAnchor = frame?.releaseAnchor;
useEffect(() => {
const node = pillRef.current;
offerAnchor?.(node);
return () => {
releaseAnchor?.(node);
};
}, [offerAnchor, releaseAnchor]);
// Parsed at render, not registration, so an invalid icon throws to the item's boundary.
const parsedIcon = useMemo(() => parsePluginIcon("Composer pill", icon), [icon]);
const tooltipText = title?.trim() || undefined;
const accessibleLabel = tooltipText ?? (label.trim() || frame?.title || undefined);
const isDisabled = disabled || pending;
const isActive = Boolean(frame?.popoverOpen && frame.isAnchoredTo(pillRef.current));
const [hovered, setHovered] = useState(false);
const handleHoverIn = useCallback(() => setHovered(true), []);
const handleHoverOut = useCallback(() => setHovered(false), []);
const pillStyle = useMemo(
() => [
composerPillStyles.body,
styles.button,
((hovered && !isDisabled) || isActive) && composerPillStyles.bodyActive,
isDisabled && styles.disabled,
],
[hovered, isActive, isDisabled],
);
const handlePress = useCallback(() => {
if (disabled || pendingRef.current) return;
frame?.anchorTo(pillRef.current);
try {
const result = onPress();
if (!isPromiseLike(result)) return;
pendingRef.current = true;
setPending(true);
void Promise.resolve(result)
.catch((error: unknown) => {
toast.error(toErrorMessage(error));
})
.finally(() => {
pendingRef.current = false;
if (mountedRef.current) setPending(false);
});
} catch (error: unknown) {
toast.error(toErrorMessage(error));
}
}, [disabled, frame, onPress, toast]);
const accessibilityState = useMemo(
() => ({ busy: pending, disabled: isDisabled }),
[isDisabled, pending],
);
const trigger = (
<PressHighlight
ref={pillRef}
collapsable={false}
testID={frame?.testID}
accessibilityRole="button"
accessibilityLabel={accessibleLabel}
accessibilityState={accessibilityState}
aria-busy={pending}
disabled={isDisabled}
onPress={handlePress}
onHoverIn={handleHoverIn}
onHoverOut={handleHoverOut}
style={pillStyle}
highlightStyle={composerPillStyles.bodyActive}
>
{pending ? (
<View style={styles.icon}>
<ThemedLoadingSpinner size={14} uniProps={mutedIconMapping} />
</View>
) : (
<View
style={styles.icon}
accessible={false}
accessibilityElementsHidden
importantForAccessibility="no-hide-descendants"
>
<ThemedPluginIconView icon={parsedIcon} size={14} uniProps={mutedIconMapping} />
</View>
)}
{label ? (
<Text numberOfLines={1} style={styles.label}>
{label}
</Text>
) : null}
</PressHighlight>
);
if (!tooltipText) return trigger;
return (
<Tooltip enabledOnMobile={false}>
<TooltipTrigger asChild>{trigger}</TooltipTrigger>
<TooltipContent>
<Text style={styles.tooltipLabel}>{tooltipText}</Text>
</TooltipContent>
</Tooltip>
);
}
const styles = StyleSheet.create((theme) => ({
button: { flexShrink: 1, minWidth: 0, maxWidth: 160 },
disabled: { opacity: theme.opacity[50] },
tooltipLabel: { fontSize: theme.fontSize.sm, color: theme.colors.foreground },
label: {
fontSize: theme.fontSize.sm,
color: theme.colors.foregroundMuted,
flexShrink: 1,
},
icon: {
width: 16,
height: 16,
alignItems: "center",
justifyContent: "center",
flexShrink: 0,
overflow: "hidden",
pointerEvents: "none",
},
}));
+78 -2
View File
@@ -111,6 +111,7 @@ describe("evaluatePluginClientBundle", () => {
plugin.addSidebarHeaderItem({ id: "main", title: "Main", Component }),
plugin.addSidebarFooterItem({ id: "status", title: "Status", Component }),
plugin.addWorkspaceRowBadgeItem({ id: "status", title: "Status", icon: "Blocks", Component }),
plugin.addComposerPillItem({ id: "pill-item", title: "Pill", Component }),
plugin.addWorkspacePanel({ id: "panel", title: "Panel", icon: "Blocks", context: "workspace", Component }),
plugin.addCommandCenterItem({ id: "command", title: "Command", icon: "Blocks", context: "global", onSelect() {} }),
plugin.addSlashCommand({ name: "review", description: "Review", argumentHint: "", context: "workspace", onSubmit() {} }),
@@ -144,6 +145,7 @@ describe("evaluatePluginClientBundle", () => {
plugin.sidebarItems.header,
plugin.sidebarItems.footer,
plugin.workspaceRowBadgeItems,
plugin.composerPillItems,
plugin.workspacePanels,
plugin.commandCenterItems,
plugin.clientSlashCommands,
@@ -166,6 +168,7 @@ describe("evaluatePluginClientBundle", () => {
plugin.sidebarItems.header,
plugin.sidebarItems.footer,
plugin.workspaceRowBadgeItems,
plugin.composerPillItems,
plugin.workspacePanels,
plugin.commandCenterItems,
plugin.clientSlashCommands,
@@ -335,6 +338,43 @@ describe("evaluatePluginClientBundle", () => {
).toThrow("Workspace row badge item status is not a component");
});
it("collects composer pill items, releases ids on removal, and rejects invalid or duplicate ones", () => {
const plugin = evaluatePluginClientBundle(
"example",
bundle(`
const Item = require("react").memo(function Item() { return null; });
const remove = plugin.addComposerPillItem({ id: "inbox", title: " Inbox ", Component: Item });
remove();
plugin.addComposerPillItem({ id: "inbox", title: " Inbox ", Component: Item });
`),
);
expect(plugin.composerPillItems.map(({ id, title }) => ({ id, title }))).toEqual([
{ id: "inbox", title: "Inbox" },
]);
const item = (fields: string) =>
bundle(`function Item() { return null; } plugin.addComposerPillItem({ ${fields} });`);
expect(() =>
evaluatePluginClientBundle(
"example",
bundle(`
function Item() { return null; }
plugin.addComposerPillItem({ id: "inbox", title: "One", Component: Item });
plugin.addComposerPillItem({ id: "inbox", title: "Two", Component: Item });
`),
),
).toThrow("Duplicate composer pill item: inbox");
expect(() =>
evaluatePluginClientBundle("example", item(`id: "Inbox", title: "Inbox", Component: Item`)),
).toThrow("Invalid composer pill item id: Inbox");
expect(() =>
evaluatePluginClientBundle("example", item(`id: "inbox", title: " ", Component: Item`)),
).toThrow("Composer pill item inbox has no title");
expect(() =>
evaluatePluginClientBundle("example", item(`id: "inbox", title: "Inbox", Component: "Item"`)),
).toThrow("Composer pill item inbox is not a component");
});
it("expands the addSurface and addSidebarItem aliases to a screen and a legacy header item", () => {
const plugin = evaluatePluginClientBundle(
"example",
@@ -475,6 +515,42 @@ describe("evaluatePluginClientBundle", () => {
]);
});
it("collects params schema and identity on workspace and agent panels and rejects invalid values", () => {
const plugin = evaluatePluginClientBundle(
"panels",
bundle(`
const { z } = require("zod");
const Component = () => null;
const schema = z.object({ prNumber: z.number() });
const identity = (p) => String(p.prNumber);
plugin.addWorkspacePanel({ id: "pr", title: "PR", icon: "File", params: schema, identity, Component });
plugin.addAgentPanel({ id: "review", title: "Review", icon: "File", params: schema, identity, Component });
`),
);
expect(plugin.workspacePanels[0]?.paramsSchema).toBeDefined();
expect(plugin.workspacePanels[0]?.identity).toBeTypeOf("function");
expect(plugin.workspacePanels[1]?.paramsSchema).toBeDefined();
expect(plugin.workspacePanels[1]?.identity).toBeTypeOf("function");
expect(() =>
evaluatePluginClientBundle(
"panels",
bundle(`
plugin.addWorkspacePanel({ id: "bad-schema", title: "Bad", icon: "File", params: {}, Component: () => null });
`),
),
).toThrow("Workspace panel bad-schema has invalid params schema");
expect(() =>
evaluatePluginClientBundle(
"panels",
bundle(`
plugin.addWorkspacePanel({ id: "bad-identity", title: "Bad", icon: "File", identity: "nope", Component: () => null });
`),
),
).toThrow("Workspace panel bad-identity has invalid identity function");
});
it("registers inline SVG and component icons", () => {
const svg = '<svg viewBox="0 0 24 24"><path fill="currentColor" d="M4 4h16v16H4z" /></svg>';
const plugin = evaluatePluginClientBundle(
@@ -798,10 +874,10 @@ describe("evaluatePluginClientBundle", () => {
const plugin = evaluatePluginClientBundle(
"example",
`(function(require) {
const { Icon, ProviderIcon, Modal, useToast, SettingsSection, SidebarRow, StreamedText } = require("@getpaseo/plugin/client/ui");
const { Icon, ProviderIcon, Modal, useToast, SettingsSection, SidebarRow, ComposerPill, StreamedText } = require("@getpaseo/plugin/client/ui");
const module = { exports: {} };
module.exports.default = function(plugin) {
if (typeof Icon !== "function" || typeof ProviderIcon !== "function" || typeof Modal !== "function" || typeof Modal.Content !== "function" || typeof useToast !== "function" || typeof SettingsSection !== "function" || typeof SidebarRow !== "function" || typeof StreamedText !== "function") {
if (typeof Icon !== "function" || typeof ProviderIcon !== "function" || typeof Modal !== "function" || typeof Modal.Content !== "function" || typeof useToast !== "function" || typeof SettingsSection !== "function" || typeof SidebarRow !== "function" || typeof ComposerPill !== "function" || typeof StreamedText !== "function") {
throw new Error("React Native plugin UI is incomplete");
}
plugin.addSurface("main", function Surface() { return null; });
+81 -15
View File
@@ -17,6 +17,7 @@ import { type PluginCleanup } from "@getpaseo/plugin";
import {
type PluginClientContext,
type PluginAgentPanelContribution,
type PluginPanelParamsSchema,
type PluginWorkspacePanelContribution as WorkspacePanelInput,
type PluginScreenProps,
type PluginScreenTitle,
@@ -39,6 +40,7 @@ import type {
PluginSidebarItemContribution,
PluginWorkspacePanelContribution,
PluginWorkspaceRowBadgeItemContribution,
PluginComposerPillItemContribution,
} from "./types";
import type { ComponentType } from "react";
import { parsePluginIcon, parseSerializablePluginIcon } from "./icons";
@@ -164,6 +166,7 @@ export function runPluginClientBundle(
workspaceRowBadgeItems: [],
filePanels: [],
composerItems: [],
composerPillItems: [],
newWorkspaceItems: [],
workspacePanels: [],
commandCenterItems: [],
@@ -184,6 +187,7 @@ export function runPluginClientBundle(
const workspaceRowItemIds = new Set<string>();
const filePanelIds = new Set<string>();
const composerItemIds = new Set<string>();
const composerPillItemIds = new Set<string>();
const newWorkspaceItemIds = new Set<string>();
const workspacePanelIds = new Set<string>();
const commandCenterItemIds = new Set<string>();
@@ -252,7 +256,14 @@ export function runPluginClientBundle(
() => ids.delete(normalizedId),
);
}
function registerPanel(contribution: PluginWorkspacePanelContribution): PluginCleanup {
type EvaluatedPanelRegistrationInput =
| (Omit<Extract<PluginWorkspacePanelContribution, { context: "workspace" }>, "paramsSchema"> & {
params?: PluginPanelParamsSchema;
})
| (Omit<Extract<PluginWorkspacePanelContribution, { context: "agent" }>, "paramsSchema"> & {
params?: PluginPanelParamsSchema;
});
function registerPanel(contribution: EvaluatedPanelRegistrationInput): PluginCleanup {
const normalizedId = requireId(contribution.id, "workspace panel id");
if (workspacePanelIds.has(normalizedId)) {
throw new Error(`Duplicate workspace panel: ${normalizedId}`);
@@ -263,18 +274,42 @@ export function runPluginClientBundle(
if (typeof contribution.Component !== "function") {
throw new Error(`Workspace panel ${normalizedId} is not a component`);
}
let paramsSchema: PluginPanelParamsSchema | undefined;
if (contribution.params !== undefined) {
if (!contribution.params || typeof contribution.params.safeParse !== "function") {
throw new Error(`Workspace panel ${normalizedId} has invalid params schema`);
}
paramsSchema = contribution.params;
}
if (contribution.identity !== undefined && typeof contribution.identity !== "function") {
throw new Error(`Workspace panel ${normalizedId} has invalid identity function`);
}
const locations = normalizePanelLocations(normalizedId, contribution.locations);
workspacePanelIds.add(normalizedId);
return register(
collector.workspacePanels,
{
...contribution,
id: normalizedId,
title,
icon,
locations,
},
() => workspacePanelIds.delete(normalizedId),
const evaluated: EvaluatedPlugin["workspacePanels"][number] =
contribution.context === "agent"
? {
id: normalizedId,
title,
icon,
context: "agent",
locations,
...(paramsSchema ? { paramsSchema } : {}),
...(contribution.identity ? { identity: contribution.identity } : {}),
Component: contribution.Component,
}
: {
id: normalizedId,
title,
icon,
context: "workspace",
locations,
...(paramsSchema ? { paramsSchema } : {}),
...(contribution.identity ? { identity: contribution.identity } : {}),
Component: contribution.Component,
};
return register(collector.workspacePanels, evaluated, () =>
workspacePanelIds.delete(normalizedId),
);
}
const pluginContext: PluginClientContext = {
@@ -322,6 +357,22 @@ export function runPluginClientBundle(
() => composerItemIds.delete(normalizedId),
);
},
addComposerPillItem(contribution: PluginComposerPillItemContribution) {
const itemId = requireId(contribution.id, "composer pill item id");
if (composerPillItemIds.has(itemId))
throw new Error(`Duplicate composer pill item: ${itemId}`);
const title = normalizePluginText(contribution.title);
if (!title) throw new Error(`Composer pill item ${itemId} has no title`);
if (!isComponentType(contribution.Component)) {
throw new Error(`Composer pill item ${itemId} is not a component`);
}
composerPillItemIds.add(itemId);
return register(
collector.composerPillItems,
{ id: itemId, title, Component: contribution.Component },
() => composerPillItemIds.delete(itemId),
);
},
addNewWorkspaceItem(contribution) {
const normalizedId = requireId(contribution.id, "New workspace item id");
if (newWorkspaceItemIds.has(normalizedId))
@@ -441,17 +492,31 @@ export function runPluginClientBundle(
() => filePanelIds.delete(panelId),
);
},
addAgentPanel(contribution: PluginAgentPanelContribution<PluginText>) {
return registerPanel({ ...contribution, context: "agent" });
addAgentPanel(
contribution:
| PluginAgentPanelContribution<PluginText, PluginPanelParamsSchema>
| PluginAgentPanelContribution<PluginText>,
) {
return registerPanel({
...contribution,
context: "agent",
} as Parameters<typeof registerPanel>[0]);
},
addWorkspacePanel(input: WorkspacePanelInput<PluginText>) {
addWorkspacePanel(
input:
| WorkspacePanelInput<PluginText, PluginPanelParamsSchema>
| WorkspacePanelInput<PluginText>,
) {
// COMPAT(pluginAgentPanelAlias): added in v0.13.0, remove after 2027-04-23
if (input.context === "agent") return pluginContext.addAgentPanel(input);
// COMPAT(pluginPanelFlatProps): added in v0.13.0, remove after 2027-04-23
if (input.context !== undefined && input.context !== "workspace") {
throw new Error(`Workspace panel ${input.id} has invalid context`);
}
return registerPanel({ ...input, context: "workspace" });
return registerPanel({
...input,
context: "workspace",
} as Parameters<typeof registerPanel>[0]);
},
addCommandCenterItem(contribution: PluginCommandCenterItemContribution) {
const normalizedId = requireId(contribution.id, "Command Center item id");
@@ -690,6 +755,7 @@ export function runPluginClientBundle(
workspaceRowBadgeItems: collector.workspaceRowBadgeItems,
filePanels: collector.filePanels,
composerItems: collector.composerItems,
composerPillItems: collector.composerPillItems,
newWorkspaceItems: collector.newWorkspaceItems,
workspacePanels: collector.workspacePanels as EvaluatedPlugin["workspacePanels"],
commandCenterItems: collector.commandCenterItems,
+1
View File
@@ -61,6 +61,7 @@ function makePlugin(serverId: string): InstalledPlugin {
workspaceRowBadgeItems: [],
filePanels: [],
composerItems: [],
composerPillItems: [],
newWorkspaceItems: [],
workspacePanels: [],
commandCenterItems: [],
+1
View File
@@ -4,3 +4,4 @@ export { PluginSurfaceScreen } from "./surface-screen";
export { usePluginAttachmentPicker } from "./attachments/picker";
export { PluginResourceAttachmentPill } from "./attachments/pill";
export { PluginComposerPills, PluginHeaderButtons, usePluginWorkspaceMenu } from "./buttons/view";
export { PluginComposerPillItems } from "./composer-pill-items";
@@ -63,6 +63,7 @@ function installation(invoked: string[]): InstalledPlugin {
workspaceRowBadgeItems: [],
filePanels: [],
composerItems: [],
composerPillItems: [],
newWorkspaceItems: [],
workspacePanels: [],
commandCenterItems: [],
+136
View File
@@ -0,0 +1,136 @@
import type {
PluginAgentPanelProps,
PluginFilePanelProps,
PluginOpenScreenInput,
PluginScreenProps,
PluginWorkspacePanelProps,
} from "@getpaseo/plugin/client";
import { PluginTranslationRuntime } from "@getpaseo/plugin/client/host";
import { QueryClient } from "@tanstack/react-query";
import { describe, expect, it } from "vitest";
import type { BuiltinFilePanelProps } from "@/file-panels/panels";
import { openPluginScreen } from "./navigation";
import type { InstalledPlugin } from "./types";
function createTestPlugin(screenIds: readonly string[]): InstalledPlugin {
return {
id: "review",
serverId: "host-a",
clientBundle: "",
lifetime: new AbortController(),
locale: "en",
i18n: new PluginTranslationRuntime({ getLocale: () => "en", subscribe: () => () => {} }),
queryClient: new QueryClient(),
paseo: {} as InstalledPlugin["paseo"],
invoke: async () => undefined,
subscribe: () => {
throw new Error("Subscriptions are not used here");
},
cleanup: () => undefined,
settingsScreens: [],
surfaces: screenIds.map((id) => ({ id, title: id, Component: () => null })),
sidebarViews: [],
sidebarItems: { header: [], footer: [] },
legacySidebarItems: [],
workspaceRowBadgeItems: [],
filePanels: [],
composerItems: [],
composerPillItems: [],
newWorkspaceItems: [],
workspacePanels: [],
commandCenterItems: [],
clientSlashCommands: [],
attachmentSources: [],
themes: [],
timelineTransformers: [],
timelineRenderers: [],
notificationOpenHandlers: [],
};
}
describe("openPluginScreen", () => {
it("validates screen input, runs beforeNavigate, remembers the host, and pushes the route", () => {
const plugin = createTestPlugin(["main", "details"]);
const events: string[] = [];
openPluginScreen({
plugin,
screen: { screenId: "details", params: { itemId: "42", tab: "diff" } },
beforeNavigate: () => events.push("beforeNavigate"),
rememberHost: (contributionId, serverId) =>
events.push(`remember:${contributionId}:${serverId}`),
navigate: (route) => events.push(`navigate:${route}`),
});
expect(events).toEqual([
"beforeNavigate",
"remember:review/screens:host-a",
"navigate:/h/host-a/plugin/review/surface/details?param.itemId=42&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;
+81 -8
View File
@@ -1,11 +1,71 @@
import { buildPluginSettingsRoute } from "./settings/routes";
import { router } from "expo-router";
import type { PluginPanelLocation } from "@getpaseo/plugin/client";
import { useCallback } from "react";
import type {
PluginOpenScreenInput,
PluginPanelLocation,
PluginScreenParams,
} from "@getpaseo/plugin/client";
import { navigateToWorkspace } from "@/stores/navigation-active-workspace-store";
import { useWorkspaceLayoutStore } from "@/stores/workspace-layout-store";
import { pluginScreensHostKey, rememberPluginContributionHost } from "./contribution-host";
import { buildPluginSurfaceRoute } from "./routes";
import { parsePluginOpenScreenInput } from "./surface-contribution";
import type { InstalledPlugin } from "./types";
import type { PluginNavigation } from "./actions";
function pushPluginScreenRoute(input: {
serverId: string;
pluginId: string;
screenId: string;
params?: PluginScreenParams;
navigate?: (route: string) => void;
rememberHost?: (contributionId: string, serverId: string) => void;
}): void {
const {
serverId,
pluginId,
screenId,
params,
navigate = router.push,
rememberHost = rememberPluginContributionHost,
} = input;
rememberHost(pluginScreensHostKey(pluginId), serverId);
navigate(buildPluginSurfaceRoute(serverId, pluginId, { kind: "surface", id: screenId }, params));
}
export function openPluginScreen(input: {
plugin: InstalledPlugin;
screen: PluginOpenScreenInput;
beforeNavigate?: () => void;
navigate?: (route: string) => void;
rememberHost?: (contributionId: string, serverId: string) => void;
}): void {
const { plugin, screen, beforeNavigate, navigate, rememberHost } = input;
const { screenId, params } = parsePluginOpenScreenInput(plugin, screen);
beforeNavigate?.();
pushPluginScreenRoute({
serverId: plugin.serverId,
pluginId: plugin.id,
screenId,
params,
navigate,
rememberHost,
});
}
export function usePluginOpenScreen(
plugin: InstalledPlugin | null,
): (input: PluginOpenScreenInput) => void {
return useCallback(
(screen: PluginOpenScreenInput) => {
if (!plugin) throw new Error("Plugin is unavailable");
openPluginScreen({ plugin, screen });
},
[plugin],
);
}
export function createPluginNavigation(input: {
serverId: string;
workspaceId: string | null;
@@ -24,25 +84,38 @@ export function createPluginNavigation(input: {
router.push(buildPluginSettingsRoute(serverId, pluginId, screenId));
},
openSurface(pluginId, surfaceId, params) {
router.push(
buildPluginSurfaceRoute(serverId, pluginId, { kind: "surface", id: surfaceId }, params),
);
pushPluginScreenRoute({ serverId, pluginId, screenId: surfaceId, params });
},
openWorkspacePanel(pluginId, panelId, location) {
openWorkspacePanel(pluginId, panelId, location, resolved) {
if (!workspaceId) throw new Error("No active workspace");
navigateToWorkspace({
serverId,
workspaceId,
target: { kind: "plugin", pluginId, panelId, context: "workspace" },
target: {
kind: "plugin",
pluginId,
panelId,
context: "workspace",
...(resolved?.params !== undefined ? { params: resolved.params } : {}),
...(resolved?.identityKey !== undefined ? { identityKey: resolved.identityKey } : {}),
},
placement: placement(location),
});
},
openAgentPanel(pluginId, panelId, agentId, location) {
openAgentPanel(pluginId, panelId, agentId, location, resolved) {
if (!workspaceId) throw new Error("No active workspace");
navigateToWorkspace({
serverId,
workspaceId,
target: { kind: "plugin", pluginId, panelId, context: "agent", agentId },
target: {
kind: "plugin",
pluginId,
panelId,
context: "agent",
agentId,
...(resolved?.params !== undefined ? { params: resolved.params } : {}),
...(resolved?.identityKey !== undefined ? { identityKey: resolved.identityKey } : {}),
},
placement: placement(location),
});
},
@@ -89,6 +89,7 @@ function makeInstalledPlugin(input: {
workspaceRowBadgeItems: [],
filePanels: [],
composerItems: [],
composerPillItems: [],
newWorkspaceItems: [],
workspacePanels: [],
commandCenterItems: [],
+39 -2
View File
@@ -1,7 +1,7 @@
import type { ReactNode } from "react";
import { useCallback, type ReactNode, type RefObject } from "react";
import { View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { MenuSurface, type MenuSurfaceProps } from "@/components/ui/menu";
import { MenuSurface, useMenuContext, type MenuSurfaceProps } from "@/components/ui/menu";
import { ToastApiProvider, type useToast } from "@/contexts/toast-context";
import type { createPluginClientStateSource } from "./client-state/source";
import { PluginInstallationProvider } from "./installation-provider";
@@ -53,6 +53,43 @@ export function PluginPopoverContent({ children }: { children: ReactNode }) {
return <View style={styles.content}>{children}</View>;
}
function assignRef(ref: RefObject<View | null>, node: View | null) {
Object.assign(ref, { current: node });
}
/**
* Shared popover anchor plumbing for declarative plugin item slots (`SidebarRow`, `ComposerPill`).
* `anchorTo` moves the anchor to the pressed element; `offerAnchor` sets it only when nothing is
* anchored; `releaseAnchor` drops a departing element; `anchorToFallback` covers items with none.
*/
export function usePluginPopoverAnchor(name: string): {
triggerRef: RefObject<View | null>;
anchorTo: (node: View | null) => void;
offerAnchor: (node: View | null) => void;
releaseAnchor: (node: View | null) => void;
anchorToFallback: (fallback: RefObject<View | null>) => void;
} {
const { triggerRef } = useMenuContext(name);
const anchorTo = useCallback((node: View | null) => assignRef(triggerRef, node), [triggerRef]);
const offerAnchor = useCallback(
(node: View | null) => {
if (!triggerRef.current) assignRef(triggerRef, node);
},
[triggerRef],
);
const releaseAnchor = useCallback(
(node: View | null) => {
if (triggerRef.current === node) assignRef(triggerRef, null);
},
[triggerRef],
);
const anchorToFallback = useCallback(
(fallback: RefObject<View | null>) => offerAnchor(fallback.current),
[offerAnchor],
);
return { triggerRef, anchorTo, offerAnchor, releaseAnchor, anchorToFallback };
}
const styles = StyleSheet.create((theme) => ({
content: { padding: theme.spacing[3], gap: theme.spacing[2] },
}));
@@ -156,6 +156,7 @@ function createInstalledPlugin(serverId: string): InstalledPlugin {
workspaceRowBadgeItems: [],
filePanels: [],
composerItems: [],
composerPillItems: [],
newWorkspaceItems: [],
workspacePanels: [],
commandCenterItems: [],
@@ -11,6 +11,7 @@ export {
export { ExternalLink } from "@/components/ui/external-link";
export { SidebarRow, SidebarSeparator } from "@/plugins/sidebar-items/kit";
export { ComposerPill } from "@/plugins/composer-pill-items/kit";
export { WorkspaceRowBadge } from "@/plugins/workspace-row-badge-items/kit";
export { DocumentFrame } from "@/file-panels/document-frame";
+1
View File
@@ -233,6 +233,7 @@ export class PluginRegistry {
workspaceRowBadgeItems: [],
filePanels: [],
composerItems: [],
composerPillItems: [],
newWorkspaceItems: [],
workspacePanels: [],
commandCenterItems: [],
@@ -40,6 +40,7 @@ function installed(
workspaceRowBadgeItems: [],
filePanels: [],
composerItems: [],
composerPillItems: [],
newWorkspaceItems: [],
workspacePanels: [],
commandCenterItems: [],
@@ -6,7 +6,7 @@ import type {
PluginSidebarItemProps,
} from "@getpaseo/plugin/client";
import type { PluginTheme } from "@getpaseo/plugin";
import { router, useGlobalSearchParams, usePathname } from "expo-router";
import { useGlobalSearchParams, usePathname } from "expo-router";
import { useCallback, useMemo, useState, type ComponentType, type RefObject } from "react";
import { type View } from "react-native";
import { withUnistyles } from "react-native-unistyles";
@@ -20,19 +20,19 @@ import { useToast } from "@/contexts/toast-context";
import { useHostRuntimeClient, useHosts } from "@/runtime/host-runtime";
import type { Theme } from "@/styles/theme";
import { createPluginClientStateSource } from "../client-state/source";
import { pluginScreensHostKey, rememberPluginContributionHost } from "../contribution-host";
import { openPluginScreen } from "../navigation";
import {
PluginEnvironmentProvider,
PluginPopoverContent,
type PluginEnvironment,
} from "../popover";
import { buildPluginSurfaceRoute, hostIdFromPathname } from "../routes";
import { hostIdFromPathname } from "../routes";
import {
selectPluginSidebarTarget,
type PluginSidebarGroup,
type PluginSidebarTarget,
} from "../sidebar-groups";
import { currentPluginScreen, parsePluginOpenScreenInput } from "../surface-contribution";
import { currentPluginScreen } from "../surface-contribution";
import { SurfaceErrorBoundary } from "../surface-error-boundary";
import { toPluginTheme } from "../theme";
import type { PluginSidebarSection } from "../types";
@@ -178,19 +178,15 @@ function SidebarItemContent({
[compact, hostLabel, plugin.serverId, theme],
);
const openScreen = useCallback(
(input: PluginOpenScreenInput) => {
const { screenId, params } = parsePluginOpenScreenInput(plugin, input);
rememberPluginContributionHost(pluginScreensHostKey(plugin.id), plugin.serverId);
showPopover(null);
onBeforeNavigate?.();
router.push(
buildPluginSurfaceRoute(
plugin.serverId,
plugin.id,
{ kind: "surface", id: screenId },
params,
),
);
(screen: PluginOpenScreenInput) => {
openPluginScreen({
plugin,
screen,
beforeNavigate() {
showPopover(null);
onBeforeNavigate?.();
},
});
},
[onBeforeNavigate, plugin, showPopover],
);
@@ -59,6 +59,7 @@ function installation(
})),
filePanels: [],
composerItems: [],
composerPillItems: [],
newWorkspaceItems: [],
workspacePanels: [],
commandCenterItems: [],
+10 -1
View File
@@ -25,6 +25,7 @@ import {
import type { Theme } from "@/styles/theme";
import type { ShortcutKey } from "@/utils/format-shortcut";
import { usePluginHostNavigation } from "./host-navigation";
import { usePluginOpenScreen } from "./navigation";
import { PluginIconView } from "./icons";
import { toPluginTheme } from "./theme";
import { pluginExecutionApprovals, usePluginExecutionDecision } from "./execution-approval";
@@ -123,9 +124,17 @@ function SurfaceRenderer({
theme: PluginTheme;
}) {
const navigation = usePluginHostNavigation(host.id);
const openScreen = usePluginOpenScreen(plugin);
return (
<PluginInstallationProvider plugin={plugin}>
<Surface theme={theme} host={host} layout={layout} navigation={navigation} params={params} />
<Surface
theme={theme}
host={host}
layout={layout}
navigation={navigation}
params={params}
openScreen={openScreen}
/>
</PluginInstallationProvider>
);
}
+1
View File
@@ -73,6 +73,7 @@ function installed(serverId: string, themes: PluginThemeContribution[]): Install
workspaceRowBadgeItems: [],
filePanels: [],
composerItems: [],
composerPillItems: [],
newWorkspaceItems: [],
workspacePanels: [],
commandCenterItems: [],
@@ -30,6 +30,7 @@ function plugin(input: {
workspaceRowBadgeItems: [],
filePanels: [],
composerItems: [],
composerPillItems: [],
newWorkspaceItems: [],
workspacePanels: [],
commandCenterItems: [],
+32 -6
View File
@@ -8,12 +8,15 @@ import type {
PluginThemeContribution as SDKPluginThemeContribution,
} from "@getpaseo/plugin";
import type {
PluginAgentPanelParams,
PluginAgentPanelProps,
PluginFilePanelContribution as SDKPluginFilePanelContribution,
PluginCommandCenterItemContribution as SDKPluginCommandCenterItemContribution,
PluginClientSlashCommandContribution as SDKPluginClientSlashCommandContribution,
PluginComposerItemContribution,
PluginNewWorkspaceItemContribution,
PluginComposerPillContribution as SDKPluginComposerPillContribution,
PluginComposerPillItemContribution as SDKPluginComposerPillItemContribution,
PluginSidebarContribution as SDKPluginSidebarContribution,
PluginSidebarViewContribution,
PluginSidebarItemContribution as SDKPluginSidebarItemContribution,
@@ -23,9 +26,13 @@ import type {
PluginTimelineRendererContribution,
PluginTimelineTransformerContribution,
PluginNotificationOpenHandler,
PluginIcon,
PluginPanelLocation,
PluginWorkspacePanelContribution as SDKPluginWorkspacePanelContribution,
PluginPanelParamsSchema,
PluginPanelTargetParams,
PluginWorkspacePanelProps,
} from "@getpaseo/plugin/client";
import type { ComponentType } from "react";
type PluginFilePanelContribution = SDKPluginFilePanelContribution<PluginText>;
type PluginAttachmentSourceContribution = SDKPluginAttachmentSourceContribution<PluginText>;
@@ -33,16 +40,34 @@ type PluginThemeContribution = SDKPluginThemeContribution<PluginText>;
type PluginCommandCenterItemContribution = SDKPluginCommandCenterItemContribution<PluginText>;
type PluginClientSlashCommandContribution = SDKPluginClientSlashCommandContribution<PluginText>;
type PluginComposerPillContribution = SDKPluginComposerPillContribution<PluginText>;
type PluginComposerPillItemContribution = SDKPluginComposerPillItemContribution<PluginText>;
type PluginSidebarContribution = SDKPluginSidebarContribution<PluginText>;
type PluginSidebarItemContribution = SDKPluginSidebarItemContribution<PluginText>;
type PluginWorkspaceRowBadgeItemContribution =
SDKPluginWorkspaceRowBadgeItemContribution<PluginText>;
type PluginScreenContribution = SDKPluginScreenContribution<PluginText>;
type PluginSettingsScreenContribution = SDKPluginSettingsScreenContribution<PluginText>;
type WorkspacePanelInput = SDKPluginWorkspacePanelContribution<PluginText>;
type PluginWorkspacePanelContribution =
| (Extract<WorkspacePanelInput, { context?: "workspace" }> & { context: "workspace" })
| Extract<WorkspacePanelInput, { context: "agent" }>;
export type PluginWorkspacePanelContribution =
| {
id: string;
title: PluginText;
icon: PluginIcon;
context: "workspace";
locations?: readonly PluginPanelLocation[];
paramsSchema?: PluginPanelParamsSchema;
identity?: (params: PluginPanelTargetParams) => string;
Component: ComponentType<PluginWorkspacePanelProps<PluginPanelTargetParams>>;
}
| {
id: string;
title: PluginText;
icon: PluginIcon;
context: "agent";
locations?: readonly PluginPanelLocation[];
paramsSchema?: PluginPanelParamsSchema;
identity?: (params: PluginAgentPanelParams & PluginPanelTargetParams) => string;
Component: ComponentType<PluginAgentPanelProps<PluginPanelTargetParams>>;
};
export type PluginSidebarSection = "header" | "footer";
@@ -63,6 +88,7 @@ export interface EvaluatedPlugin {
workspaceRowBadgeItems: PluginWorkspaceRowBadgeItemContribution[];
filePanels: PluginFilePanelContribution[];
composerItems: PluginComposerItemContribution[];
composerPillItems: PluginComposerPillItemContribution[];
newWorkspaceItems: PluginNewWorkspaceItemContribution[];
workspacePanels: EvaluatedPluginWorkspacePanelContribution[];
commandCenterItems: PluginCommandCenterItemContribution[];
@@ -99,6 +125,7 @@ export type {
PluginComposerItemContribution,
PluginNewWorkspaceItemContribution,
PluginComposerPillContribution,
PluginComposerPillItemContribution,
PluginSidebarContribution,
PluginSidebarItemContribution,
PluginWorkspaceRowBadgeItemContribution,
@@ -108,5 +135,4 @@ export type {
PluginTimelineRendererContribution,
PluginTimelineTransformerContribution,
PluginNotificationOpenHandler,
PluginWorkspacePanelContribution,
};
@@ -71,7 +71,7 @@ function bundle(id: string, register: string) {
return {
id,
requirements: { paseo: ">=0.8.0" },
clientBundle: `(function() { return { default: function(plugin) {
clientBundle: `(function(require) { return { default: function(plugin) {
const Component = function() { return null; };
${register}
return function() {};
@@ -344,6 +344,30 @@ describe("reading the layout", () => {
expect(events).toHaveLength(2);
});
it("reflects dynamic tab title overrides and resets to static title when cleared", () => {
const layout = handle();
const { tabId } = layout.open({ panelId: "overview" });
const events: unknown[] = [];
const unsubscribe = layout.subscribe((event) => events.push(event));
expect(tab(layout, tabId).title).toBe("overview");
setPanelInstanceAttributes(
{ serverId: SERVER_ID, workspaceId: WORKSPACE_ID, tabId },
{ modified: false, title: "Overview (3)" },
);
expect(tab(layout, tabId).title).toBe("Overview (3)");
expect(events).toEqual([{ type: "changed" }]);
setPanelInstanceAttributes(
{ serverId: SERVER_ID, workspaceId: WORKSPACE_ID, tabId },
{ modified: false },
);
expect(tab(layout, tabId).title).toBe("overview");
expect(events).toHaveLength(2);
unsubscribe();
});
it("hands out one handle per workspace", () => {
expect(handle()).toBe(handle());
expect(handle().workspaceId).toBe(WORKSPACE_ID);
@@ -1081,3 +1105,181 @@ describe("reaching the handle outside a panel", () => {
expect(events).toHaveLength(heard);
});
});
describe("author-defined panel params and identity", () => {
const PARAMETERIZED_PANELS = `
const { z } = require("zod");
plugin.addWorkspacePanel({
id: "decisions",
title: "Decisions",
icon: "Square",
locations: ["explorer"],
params: z.object({ decisionId: z.string() }),
Component,
});
plugin.addWorkspacePanel({
id: "pr",
title: "PR",
icon: "Square",
params: z.object({ prNumber: z.number(), commentId: z.string().optional() }),
identity: (p) => String(p.prNumber),
Component,
});
plugin.addWorkspacePanel({
id: "nested-bad",
title: "NestedBad",
icon: "Square",
params: z.object({ nested: z.object({ a: z.string() }) }),
Component,
});
plugin.addWorkspacePanel({
id: "bool-bad",
title: "BoolBad",
icon: "Square",
params: z.object({ flag: z.boolean() }),
Component,
});
plugin.addAgentPanel({
id: "agent-pr",
title: "Agent PR",
icon: "Square",
params: z.object({ prNumber: z.number(), commentId: z.string().optional() }),
identity: (p) => \`\${p.agentId}:\${p.prNumber}\`,
Component,
});
`;
beforeEach(() => {
install(PARAMETERIZED_PANELS);
});
it("reuses a single tab when identity is omitted and updates params in place", () => {
const layout = handle();
const first = layout.open({ panelId: "decisions", params: { decisionId: "D1" } });
expect(tab(layout, first.tabId).params).toEqual({ decisionId: "D1" });
expect(
useWorkspaceLayoutStore.getState().panelRevisionByWorkspace[WORKSPACE_KEY]?.[first.tabId],
).toBe(1);
const second = layout.open({ panelId: "decisions", params: { decisionId: "D2" } });
expect(second).toEqual(first);
expect(layout.get().tabs.filter((open) => open.panelId === "review/decisions")).toHaveLength(1);
expect(tab(layout, first.tabId).params).toEqual({ decisionId: "D2" });
expect(
useWorkspaceLayoutStore.getState().panelRevisionByWorkspace[WORKSPACE_KEY]?.[first.tabId],
).toBe(2);
const background = layout.open(
{ panelId: "decisions", params: { decisionId: "D3" } },
{ intent: "background" },
);
expect(background).toEqual(first);
expect(tab(layout, first.tabId).params).toEqual({ decisionId: "D3" });
expect(
useWorkspaceLayoutStore.getState().panelRevisionByWorkspace[WORKSPACE_KEY]?.[first.tabId],
).toBe(3);
});
it("coalesces keyed tabs by identity(params) and opens separate tabs for distinct keys", () => {
const layout = handle();
const pr1 = layout.open({ panelId: "pr", params: { prNumber: 1, commentId: "a" } });
expect(tab(layout, pr1.tabId).params).toEqual({ prNumber: 1, commentId: "a" });
const pr1Updated = layout.open({ panelId: "pr", params: { prNumber: 1, commentId: "b" } });
expect(pr1Updated).toEqual(pr1);
expect(tab(layout, pr1.tabId).params).toEqual({ prNumber: 1, commentId: "b" });
expect(
useWorkspaceLayoutStore.getState().panelRevisionByWorkspace[WORKSPACE_KEY]?.[pr1.tabId],
).toBe(2);
const pr2 = layout.open({ panelId: "pr", params: { prNumber: 2, commentId: "a" } });
expect(pr2.tabId).not.toBe(pr1.tabId);
expect(layout.get().tabs.filter((open) => open.panelId === "review/pr")).toHaveLength(2);
expect(tab(layout, pr1.tabId).params).toEqual({ prNumber: 1, commentId: "b" });
expect(tab(layout, pr2.tabId).params).toEqual({ prNumber: 2, commentId: "a" });
const pr1Duplicate = layout.open(
{ panelId: "pr", params: { prNumber: 1, commentId: "c" } },
{ intent: "new" },
);
expect(pr1Duplicate.tabId).not.toBe(pr1.tabId);
expect(tab(layout, pr1Duplicate.tabId).params).toEqual({ prNumber: 1, commentId: "c" });
});
it("supports extra params and identity on agent panels alongside required agentId", () => {
const layout = handle();
const first = layout.open({
panelId: "agent-pr",
params: { agentId: "a1", prNumber: 10, commentId: "c1" },
});
expect(tab(layout, first.tabId).params).toEqual({
agentId: "a1",
prNumber: 10,
commentId: "c1",
});
const updated = layout.open({
panelId: "agent-pr",
params: { agentId: "a1", prNumber: 10, commentId: "c2" },
});
expect(updated).toEqual(first);
expect(tab(layout, first.tabId).params).toEqual({
agentId: "a1",
prNumber: 10,
commentId: "c2",
});
const other = layout.open({
panelId: "agent-pr",
params: { agentId: "a1", prNumber: 11 },
});
expect(other.tabId).not.toBe(first.tabId);
expect(tab(layout, other.tabId).params).toEqual({ agentId: "a1", prNumber: 11 });
});
it("rejects invalid, missing, non-flat, or non-primitive params cleanly", () => {
const layout = handle();
const before = layout.get();
for (const target of [
{ panelId: "decisions" },
{ panelId: "decisions", params: { decisionId: 42 } },
{ panelId: "pr", params: { prNumber: "1" } },
{ panelId: "pr", params: { prNumber: Number.NaN } },
{
panelId: "nested-bad",
params: { nested: { a: "x" } } as unknown as PluginPanelTarget["params"],
},
{ panelId: "bool-bad", params: { flag: true } as unknown as PluginPanelTarget["params"] },
{ panelId: "agent-pr", params: { prNumber: 1 } },
{ panelId: "agent-pr", params: { agentId: " ", prNumber: 1 } },
] satisfies PluginPanelTarget[]) {
expect(() => layout.open(target)).toThrow("does not accept these params");
}
expect(layout.get()).toBe(before);
});
it("caches parsed params and keeps generated defaults aligned with identity across reads and reveals", () => {
install(`
const { z } = require("zod");
let count = 0;
plugin.addWorkspacePanel({
id: "generated-default",
title: "Generated",
icon: "Square",
params: z.object({ token: z.string().default(() => String(++count)) }),
identity: (p) => p.token,
Component,
});
`);
const layout = handle();
const opened = layout.open({ panelId: "generated-default" });
const first = layout.get();
const second = layout.get();
expect(second).toBe(first);
expect(tab(layout, opened.tabId).params).toEqual({ token: "1" });
expect(layout.open({ panelId: "generated-default", params: { token: "1" } }).tabId).toBe(
opened.tabId,
);
});
});
@@ -163,7 +163,7 @@ function resolveDestination(
): Destination {
const locations = panelLocations(workspace.serverId, target);
const explorerPaneId = readExplorerPaneId(workspace);
const { panelId } = describePanel(target);
const { panelId } = describePanel(workspace.serverId, target);
// The Explorer is never the focused pane, so a panel that cannot be in a main pane goes there.
const wantsExplorer =
@@ -4,20 +4,23 @@ import type {
PluginPanelTarget,
PluginPanelTargetParams,
} from "@getpaseo/plugin/client";
import { z } from "zod";
import {
findPublicPanel,
panelPublicReference,
type PanelOpenRequest,
} from "@/panels/panel-manifest";
import { panelTargetSupportsHost } from "@/plugins/workspace-panels/locations";
import {
buildPluginPanelTarget,
describePluginPanelParams,
parseRegisteredPluginPanelParams,
resolvePluginWorkspacePanel,
} from "@/plugins/workspace-panels/resolution";
import { normalizeWorkspaceTabTarget } from "@/workspace-tabs/identity";
import type { PluginWorkspaceTabTarget, WorkspaceTabTarget } from "@/workspace-tabs/model";
import type { WorkspaceTabTarget } from "@/workspace-tabs/model";
import { pluginRegistry } from "../../registry";
const PASEO_NAMESPACE = "paseo";
const workspacePanelParams = z.strictObject({});
const agentPanelParams = z.strictObject({ agentId: z.string().trim().min(1) });
export interface ResolvedPanel extends PanelOpenRequest {
/** Always qualified. */
@@ -45,14 +48,42 @@ export function resolvePanel(
return { ...request, panelId };
}
export function describePanel(target: WorkspaceTabTarget): {
export function describePanel(
serverId: string,
target: WorkspaceTabTarget,
): {
panelId: string;
params: PluginPanelTargetParams;
} {
if (target.kind !== "plugin") return panelPublicReference(target);
const plugin =
pluginRegistry
.getSnapshot()
.find((candidate) => candidate.serverId === serverId && candidate.id === target.pluginId) ??
null;
const contribution = resolvePluginWorkspacePanel(plugin, target);
if (contribution) {
try {
const parsed = parseRegisteredPluginPanelParams(contribution, target);
if (parsed.ok) {
return {
panelId: `${target.pluginId}/${target.panelId}`,
params:
parsed.context === "agent"
? { ...parsed.params, agentId: parsed.agentId }
: parsed.params,
};
}
} catch (error) {
console.warn(
`[WorkspaceLayout] Failed to parse params for "${target.pluginId}/${target.panelId}":`,
error,
);
}
}
return {
panelId: `${target.pluginId}/${target.panelId}`,
params: target.context === "agent" ? { agentId: target.agentId } : {},
params: describePluginPanelParams(target),
};
}
@@ -86,16 +117,8 @@ function resolvePluginPanel(
?.workspacePanels.find((candidate) => candidate.id === panelId);
if (!panel) throw notRegistered(qualified);
const base = { kind: "plugin", pluginId, panelId } as const;
let target: PluginWorkspaceTabTarget;
if (panel.context === "agent") {
const parsed = agentPanelParams.safeParse(params);
if (!parsed.success) throw rejectedParams(qualified);
target = { ...base, context: "agent", agentId: parsed.data.agentId };
} else {
if (!workspacePanelParams.safeParse(params).success) throw rejectedParams(qualified);
target = { ...base, context: "workspace" };
}
const target = buildPluginPanelTarget(pluginId, panel, params);
if (!target) throw rejectedParams(qualified);
const normalized = normalizeWorkspaceTabTarget(target);
if (!normalized) throw notRegistered(qualified);
return { target: normalized };
@@ -82,12 +82,13 @@ function toPane(pane: SplitPane, kind: PluginPane["kind"]): PluginPane {
}
function toTab(workspace: Workspace, { tab, paneId }: OpenTab): PluginLayoutTab {
const attributes = getWorkspacePanelAttributes(workspace.key, tab.tabId);
return {
id: tab.tabId,
paneId,
...describePanel(tab.target),
...describePanel(workspace.serverId, tab.target),
locations: panelLocations(workspace.serverId, tab.target),
title: readTabTitle({ ...workspace, target: tab.target }),
modified: getWorkspacePanelAttributes(workspace.key, tab.tabId).modified,
title: attributes.title ?? readTabTitle({ ...workspace, target: tab.target }),
modified: attributes.modified,
};
}
@@ -0,0 +1,469 @@
/**
* @vitest-environment jsdom
*/
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import React, { act, useMemo } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { PaneProvider } from "@/panels/pane-context";
import { useSessionStore, type Agent, type WorkspaceDescriptor } from "@/stores/session-store";
import { collectAllTabs, useWorkspaceLayoutStore } from "@/stores/workspace-layout-store";
import { seedSessionHosts, seedSessionWorkspaces } from "@/test/seed-session";
import { pluginExecutionApprovals } from "../execution-approval";
import { pluginRegistry } from "../registry";
import { pluginWorkspaceLayoutSource } from "../workspace-layout";
import { pluginPanelRegistration } from "./panel";
const SERVER_ID = "server-panel-test";
const WORKSPACE_ID = "workspace-panel-test";
const WORKSPACE_KEY = `${SERVER_ID}:${WORKSPACE_ID}`;
function createWorkspaceDescriptor(): WorkspaceDescriptor {
return {
createdAt: null,
lastUserMessageAt: null,
id: WORKSPACE_ID,
projectId: "project-1",
projectDisplayName: "project",
projectRootPath: "/repo",
workspaceDirectory: "/repo",
projectKind: "git",
workspaceKind: "local_checkout",
name: "main",
status: "done",
diffStat: null,
scripts: [],
statusEnteredAt: null,
archivingAt: null,
};
}
function createAgent(id: string): Agent {
return {
serverId: SERVER_ID,
id,
workspaceId: WORKSPACE_ID,
provider: "codex",
status: "idle",
createdAt: new Date("2026-04-01T03:00:00.000Z"),
updatedAt: new Date("2026-04-01T03:00:00.000Z"),
lastUserMessageAt: null,
lastActivityAt: new Date("2026-04-01T03:00:00.000Z"),
capabilities: {
supportsStreaming: true,
supportsSessionPersistence: true,
supportsDynamicModes: true,
supportsMcpServers: true,
supportsReasoningStream: true,
supportsToolInvocations: true,
},
currentModeId: null,
availableModes: [],
pendingPermissions: [],
persistence: null,
title: "Test agent",
cwd: "/repo",
model: null,
parentAgentId: null,
labels: {},
archivedAt: null,
turn: { phase: "idle", cancellationRequestId: null },
};
}
const fakeDaemon = {
observeEvents: () => ({
ready: Promise.resolve({ subscriptionId: "events" }),
subscribe: () => () => undefined,
release: async () => undefined,
}),
} as unknown as DaemonClient;
vi.mock("@/runtime/host-runtime", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/runtime/host-runtime")>();
return {
...actual,
useHostRuntimeClient: () => fakeDaemon,
};
});
function installPluginWithBundle(bundleCode: string) {
pluginExecutionApprovals.setDecision(SERVER_ID, "test-plugin", "approved");
pluginRegistry.installCatalog(
SERVER_ID,
[
{
id: "test-plugin",
requirements: { paseo: ">=0.8.0" },
clientBundle: bundleCode,
},
],
{ client: fakeDaemon, audio: { play: async () => 0 } },
);
const plugin = pluginRegistry.getSnapshot().find((p) => p.id === "test-plugin");
if (!plugin) throw new Error("Failed to install test-plugin");
return plugin;
}
describe("PluginPanel params, identity, revision, and tab.state delivery", () => {
const roots: Root[] = [];
const containers: HTMLElement[] = [];
beforeEach(async () => {
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
await vi.waitFor(() => expect(useWorkspaceLayoutStore.persist.hasHydrated()).toBe(true));
useSessionStore.setState((state) => ({ ...state, sessions: {} }));
useWorkspaceLayoutStore.setState({
layoutMode: "split-panes",
sheetsByWorkspace: {},
layoutByWorkspace: {},
splitSizesByWorkspace: {},
explorerSidebarPaneIdByWorkspace: {},
sidePaneIdByWorkspace: {},
hiddenAgentIdsByWorkspace: {},
pinnedAgentIdsByWorkspace: {},
focusRestorationByWorkspace: {},
panelRevisionByWorkspace: {},
});
seedSessionHosts([SERVER_ID]);
await vi.waitFor(() =>
expect(useSessionStore.getState().sessions[SERVER_ID]?.hasRestoredCachedDirectory).toBe(true),
);
useSessionStore.getState().updateSessionClient(SERVER_ID, fakeDaemon);
seedSessionWorkspaces(SERVER_ID, new Map([[WORKSPACE_ID, createWorkspaceDescriptor()]]));
});
afterEach(() => {
for (const root of roots.splice(0)) act(() => root.unmount());
for (const container of containers.splice(0)) container.remove();
pluginRegistry.removeHost(SERVER_ID);
pluginExecutionApprovals.clearHost(SERVER_ID);
seedSessionHosts([]);
vi.unstubAllGlobals();
});
function mountTab(tabId: string) {
const container = document.createElement("div");
containers.push(container);
document.body.appendChild(container);
const root = createRoot(container);
roots.push(root);
function Harness({ activeTabId }: { activeTabId: string }) {
const layout = useWorkspaceLayoutStore((s) => s.layoutByWorkspace[WORKSPACE_KEY]);
const revision = useWorkspaceLayoutStore(
(s) => s.panelRevisionByWorkspace[WORKSPACE_KEY]?.[activeTabId] ?? 0,
);
const tab = layout
? collectAllTabs(layout.root).find((candidate) => candidate.tabId === activeTabId)
: undefined;
const PanelComponent = pluginPanelRegistration.component;
const paneValue = useMemo(
() =>
tab
? {
serverId: SERVER_ID,
workspaceId: WORKSPACE_ID,
host: "main" as const,
tabId: tab.tabId,
target: tab.target,
state: tab.state,
panelRevision: revision,
openTab: () => {},
openPreferredTarget: () => {},
closeCurrentTab: () => {},
retargetCurrentTab: () => {},
setCurrentTabState: (nextState: unknown) =>
useWorkspaceLayoutStore
.getState()
.setTabState(WORKSPACE_KEY, tab.tabId, nextState as never),
openFileInWorkspace: () => {},
openImportSheet: () => {},
}
: null,
[tab, revision],
);
if (!paneValue) return null;
return (
<PaneProvider value={paneValue}>
<PanelComponent />
</PaneProvider>
);
}
const render = async () => {
await act(async () => {
root.render(<Harness activeTabId={tabId} />);
});
};
return { container, render };
}
it("delivers updated params, bumps revision, and preserves tab.state when reusing a tab", async () => {
const plugin = installPluginWithBundle(`(function(require) {
const React = require("react");
const { Text, Pressable } = require("react-native");
const { z } = require("zod");
const { useTabState } = require("@getpaseo/plugin/client");
const stateSchema = z.object({ note: z.string() });
function DecisionPanel({ params, revision, tab }) {
const [localCount, setLocalCount] = React.useState(0);
const [tabState, setTabState] = useTabState(tab, stateSchema, { note: "initial" });
return React.createElement(
React.Fragment,
null,
React.createElement(Text, { testID: "output" }, \`\${params.decisionId}|\${revision}|\${tabState.note}|\${localCount}\`),
React.createElement(Pressable, {
testID: "save-state",
onPress: () => {
setLocalCount((n) => n + 1);
setTabState({ note: "saved-note" });
},
})
);
}
return { default: function(client) {
client.addWorkspacePanel({
id: "decision",
title: "Decision",
icon: "File",
params: z.object({ decisionId: z.string() }),
Component: DecisionPanel,
});
return function() {};
}};
})`);
const layout = pluginWorkspaceLayoutSource(plugin).layout(WORKSPACE_ID);
const first = layout.open({ panelId: "decision", params: { decisionId: "D1" } });
const mounted = mountTab(first.tabId);
await mounted.render();
expect(mounted.container.textContent).toBe("D1|1|initial|0");
// Persist tab state and local state on the mounted instance.
const button = mounted.container.querySelector('[data-testid="save-state"]');
expect(button).toBeInstanceOf(HTMLElement);
await act(async () => {
(button as HTMLElement).click();
});
expect(mounted.container.textContent).toBe("D1|1|saved-note|1");
await act(async () => {
layout.open({ panelId: "decision", params: { decisionId: "D2" } });
});
expect(mounted.container.textContent).toBe("D2|2|saved-note|1");
});
it("delivers host-enforced agentId alongside extra params on addAgentPanel", async () => {
useSessionStore.getState().setAgents(SERVER_ID, new Map([["a1", createAgent("a1")]]));
const plugin = installPluginWithBundle(`(function(require) {
const React = require("react");
const { Text } = require("react-native");
const { z } = require("zod");
function AgentPrPanel({ params, revision }) {
return React.createElement(Text, null, \`\${params.agentId}|\${params.prNumber}|\${params.commentId ?? "none"}|\${revision}\`);
}
return { default: function(client) {
client.addAgentPanel({
id: "agent-pr",
title: "Agent PR",
icon: "File",
params: z.object({ prNumber: z.number(), commentId: z.string().optional() }),
identity: (p) => \`\${p.agentId}:\${p.prNumber}\`,
Component: AgentPrPanel,
});
return function() {};
}};
})`);
const layout = pluginWorkspaceLayoutSource(plugin).layout(WORKSPACE_ID);
const opened = layout.open({
panelId: "agent-pr",
params: { agentId: "a1", prNumber: 7, commentId: "c1" },
});
const mounted = mountTab(opened.tabId);
await mounted.render();
expect(mounted.container.textContent).toBe("a1|7|c1|1");
await act(async () => {
layout.open({
panelId: "agent-pr",
params: { agentId: "a1", prNumber: 7, commentId: "c2" },
});
});
expect(mounted.container.textContent).toBe("a1|7|c2|2");
});
it("shows unavailable when a restored tab target fails the current params schema", async () => {
const plugin = installPluginWithBundle(`(function(require) {
const React = require("react");
const { Text } = require("react-native");
return { default: function(client) {
client.addWorkspacePanel({
id: "decision",
title: "Decision",
icon: "File",
Component: () => React.createElement(Text, null, "v1-ok"),
});
return function() {};
}};
})`);
const layout = pluginWorkspaceLayoutSource(plugin).layout(WORKSPACE_ID);
const opened = layout.open({ panelId: "decision" });
const mounted = mountTab(opened.tabId);
await mounted.render();
expect(mounted.container.textContent).toBe("v1-ok");
// Simulate upgrading the plugin to require `decisionId: z.string()` while the old tab remains in layout.
await act(async () => {
installPluginWithBundle(`(function(require) {
const React = require("react");
const { Text } = require("react-native");
const { z } = require("zod");
return { default: function(client) {
client.addWorkspacePanel({
id: "decision",
title: "Decision",
icon: "File",
params: z.object({ decisionId: z.string() }),
Component: ({ params }) => React.createElement(Text, null, params.decisionId.toUpperCase()),
});
return function() {};
}};
})`);
});
expect(mounted.container.textContent).toBe("This plugin panel is unavailable.");
});
it("validates and applies schema defaults when rendering a restored tab target", async () => {
const plugin = installPluginWithBundle(`(function(require) {
const React = require("react");
const { Text } = require("react-native");
return { default: function(client) {
client.addWorkspacePanel({
id: "decision",
title: "Decision",
icon: "File",
Component: () => React.createElement(Text, null, "v1-ok"),
});
return function() {};
}};
})`);
const layout = pluginWorkspaceLayoutSource(plugin).layout(WORKSPACE_ID);
const opened = layout.open({ panelId: "decision" });
const mounted = mountTab(opened.tabId);
await mounted.render();
expect(mounted.container.textContent).toBe("v1-ok");
await act(async () => {
installPluginWithBundle(`(function(require) {
const React = require("react");
const { Text } = require("react-native");
const { z } = require("zod");
return { default: function(client) {
client.addWorkspacePanel({
id: "decision",
title: "Decision",
icon: "File",
params: z.object({ filter: z.string().default("open") }),
Component: ({ params }) => React.createElement(Text, null, params.filter),
});
return function() {};
}};
})`);
});
expect(mounted.container.textContent).toBe("open");
});
it("renders transforming params schemas once on open without rejecting output values", async () => {
const plugin = installPluginWithBundle(`(function(require) {
const React = require("react");
const { Text } = require("react-native");
const { z } = require("zod");
return { default: function(client) {
client.addWorkspacePanel({
id: "transform-pr",
title: "Transform PR",
icon: "File",
params: z.object({
prNumber: z.string().transform(Number),
label: z.string().transform((value) => value + "!"),
}),
identity: (p) => String(p.prNumber),
Component: ({ params, revision }) =>
React.createElement(Text, null, \`\${typeof params.prNumber}:\${params.prNumber}|\${params.label}|\${revision}\`),
});
return function() {};
}};
})`);
const layout = pluginWorkspaceLayoutSource(plugin).layout(WORKSPACE_ID);
const opened = layout.open({
panelId: "transform-pr",
params: { prNumber: "42", label: "hi" },
});
const mounted = mountTab(opened.tabId);
await mounted.render();
expect(mounted.container.textContent).toBe("number:42|hi!|1");
expect(layout.get().tabs.find((tab) => tab.id === opened.tabId)?.params).toEqual({
prNumber: 42,
label: "hi!",
});
await act(async () => {
layout.open({
panelId: "transform-pr",
params: { prNumber: "042", label: "yo" },
});
});
expect(mounted.container.textContent).toBe("number:42|yo!|2");
});
it("reports unexpected params transform errors through SurfaceErrorBoundary", async () => {
const plugin = installPluginWithBundle(`(function(require) {
const React = require("react");
const { Text } = require("react-native");
return { default: function(client) {
client.addWorkspacePanel({
id: "decision",
title: "Decision",
icon: "File",
Component: () => React.createElement(Text, null, "v1-ok"),
});
return function() {};
}};
})`);
const layout = pluginWorkspaceLayoutSource(plugin).layout(WORKSPACE_ID);
const opened = layout.open({ panelId: "decision" });
const mounted = mountTab(opened.tabId);
await mounted.render();
expect(mounted.container.textContent).toBe("v1-ok");
await act(async () => {
installPluginWithBundle(`(function(require) {
const React = require("react");
const { Text } = require("react-native");
const { z } = require("zod");
return { default: function(client) {
client.addWorkspacePanel({
id: "decision",
title: "Decision",
icon: "File",
params: z.object({}).transform(() => {
throw new Error("transform boom");
}),
Component: () => React.createElement(Text, null, "never"),
});
return function() {};
}};
})`);
});
expect(mounted.container.textContent).toBe("Plugin failed: transform boom");
});
});
@@ -1,12 +1,13 @@
import { usePublishPanelInstanceAttributes } from "@/panels/panel-instance-attributes";
import { getComponentMountKey, usePanelTab } from "@/panels/panel-instance-attributes";
import type {
PluginAgentPanelProps,
PluginHostProps,
PluginPanelTargetParams,
PluginWorkspacePanelProps,
PluginTab,
} from "@getpaseo/plugin/client";
import type { PluginTheme } from "@getpaseo/plugin";
import { CircleAlert } from "lucide-react-native";
import { useMemo, useState } from "react";
import { useMemo } from "react";
import { Text, View } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import invariant from "tiny-invariant";
@@ -18,35 +19,146 @@ import { useSessionStore } from "@/stores/session-store";
import { useWorkspaceExists } from "@/stores/session-store-hooks";
import type { Theme } from "@/styles/theme";
import { normalizeWorkspaceOpaqueId } from "@/utils/workspace-identity";
import type { PluginWorkspaceTabTarget } from "@/workspace-tabs/model";
import { usePluginHostNavigation } from "../host-navigation";
import { usePluginOpenScreen } from "../navigation";
import { toPluginTheme } from "../theme";
import { pluginIconComponent } from "../icons";
import { useInstalledPlugin } from "../registry";
import { PluginInstallationProvider } from "../installation-provider";
import { SurfaceErrorBoundary } from "../surface-error-boundary";
import { resolvePluginWorkspacePanel } from "./resolution";
import type { EvaluatedPluginWorkspacePanelContribution } from "../types";
import {
parseRegisteredPluginPanelParams,
resolvePluginWorkspacePanel,
type ParsedPluginPanelParams,
} from "./resolution";
import { resolvePluginPlatform } from "../platform";
const pluginThemeMapping = (theme: Theme) => ({
theme: toPluginTheme(theme),
});
function PluginPanelBody({ theme }: { theme: PluginTheme }) {
const {
serverId,
workspaceId,
tabId,
target,
state: tabState,
setCurrentTabState,
panelRevision,
} = usePaneContext();
const [modified, setModified] = useState(false);
usePublishPanelInstanceAttributes({ modified });
const tab = useMemo<PluginTab>(
() => ({ id: tabId, state: tabState, setState: setCurrentTabState, setModified }),
[tabId, tabState, setCurrentTabState],
function MountedPluginPanel({
contribution,
parsed,
theme,
host,
layout,
navigation,
openScreen,
workspaceId,
revision,
}: {
contribution: EvaluatedPluginWorkspacePanelContribution;
parsed: Extract<ParsedPluginPanelParams, { ok: true }>;
theme: PluginTheme;
host: PluginHostProps["host"];
layout: PluginHostProps["layout"];
navigation: PluginWorkspacePanelProps["navigation"];
openScreen: PluginWorkspacePanelProps["openScreen"];
workspaceId: string;
revision: number;
}) {
const tab = usePanelTab();
const workspaceParams = useMemo<PluginPanelTargetParams>(
() => Object.freeze({ ...parsed.params }),
[parsed.params],
);
const agentParams = useMemo(
() =>
parsed.context === "agent"
? Object.freeze({ ...parsed.params, agentId: parsed.agentId })
: null,
[parsed],
);
if (contribution.context === "workspace") {
const props: PluginWorkspacePanelProps<PluginPanelTargetParams> = {
// COMPAT(pluginPanelFlatProps): added in v0.13.0, remove after 2027-04-23
context: "workspace",
params: workspaceParams,
revision,
tab,
theme,
host,
layout,
navigation,
openScreen,
workspaceId,
};
const Component = contribution.Component;
return <Component {...props} />;
}
invariant(parsed.context === "agent" && agentParams, "PluginAgentPanel requires agent target");
const props: PluginAgentPanelProps<PluginPanelTargetParams> = {
// COMPAT(pluginPanelFlatProps): added in v0.13.0, remove after 2027-04-23
context: "agent",
params: agentParams,
revision,
tab,
theme,
host,
layout,
navigation,
openScreen,
workspaceId,
// COMPAT(pluginPanelFlatProps): added in v0.13.0, remove after 2027-04-23
agentId: parsed.agentId,
};
const Component = contribution.Component;
return <Component {...props} />;
}
function ValidatedPluginPanel({
contribution,
target,
theme,
host,
layout,
navigation,
openScreen,
workspaceId,
revision,
}: {
contribution: EvaluatedPluginWorkspacePanelContribution;
target: Extract<PluginWorkspaceTabTarget, { kind: "plugin" }>;
theme: PluginTheme;
host: PluginHostProps["host"];
layout: PluginHostProps["layout"];
navigation: PluginWorkspacePanelProps["navigation"];
openScreen: PluginWorkspacePanelProps["openScreen"];
workspaceId: string;
revision: number;
}) {
const parsed = useMemo(
() => parseRegisteredPluginPanelParams(contribution, target),
[contribution, target],
);
if (!parsed.ok) {
return <PluginPanelUnavailable />;
}
return (
<MountedPluginPanel
key={getComponentMountKey(contribution.Component)}
contribution={contribution}
parsed={parsed}
theme={theme}
host={host}
layout={layout}
navigation={navigation}
openScreen={openScreen}
workspaceId={workspaceId}
revision={revision}
/>
);
}
function PluginPanelBody({ theme }: { theme: PluginTheme }) {
const { serverId, workspaceId, target, panelRevision } = usePaneContext();
invariant(target.kind === "plugin", "PluginPanel requires plugin target");
const plugin = useInstalledPlugin(serverId, target.pluginId);
const contribution = resolvePluginWorkspacePanel(plugin, target);
@@ -67,6 +179,7 @@ function PluginPanelBody({ theme }: { theme: PluginTheme }) {
const host = useMemo(() => ({ id: serverId, label: hostLabel }), [hostLabel, serverId]);
const layout = useMemo(() => ({ compact, platform: resolvePluginPlatform() }), [compact]);
const navigation = usePluginHostNavigation(serverId);
const openScreen = usePluginOpenScreen(plugin);
if (!plugin || !contribution || !workspaceExists) {
return <PluginPanelUnavailable />;
@@ -74,54 +187,29 @@ function PluginPanelBody({ theme }: { theme: PluginTheme }) {
if (!client) {
return <PluginPanelUnavailable message="Plugin host is offline." />;
}
let panel;
let Surface: unknown;
if (contribution.context === "workspace") {
const props: PluginWorkspacePanelProps = {
// COMPAT(pluginPanelFlatProps): added in v0.13.0, remove after 2027-04-23
context: "workspace",
params: {},
revision: panelRevision ?? 0,
tab,
theme,
host,
layout,
navigation,
workspaceId,
};
const Component = contribution.Component;
Surface = Component;
panel = <Component {...props} />;
} else if (agentExists && target.context === "agent") {
const props: PluginAgentPanelProps = {
// COMPAT(pluginPanelFlatProps): added in v0.13.0, remove after 2027-04-23
context: "agent",
params: { agentId: target.agentId },
revision: panelRevision ?? 0,
tab,
theme,
host,
layout,
navigation,
workspaceId,
// COMPAT(pluginPanelFlatProps): added in v0.13.0, remove after 2027-04-23
agentId: target.agentId,
};
const Component = contribution.Component;
Surface = Component;
panel = <Component {...props} />;
} else {
if (contribution.context === "agent" && !agentExists) {
return <PluginPanelUnavailable />;
}
return (
<SurfaceErrorBoundary
installation={plugin}
Surface={Surface}
Surface={contribution.Component}
key={`${serverId}/${target.pluginId}/${target.panelId}/${target.context}`}
>
<PluginInstallationProvider plugin={plugin}>{panel}</PluginInstallationProvider>
<PluginInstallationProvider plugin={plugin}>
<ValidatedPluginPanel
contribution={contribution}
target={target}
theme={theme}
host={host}
layout={layout}
navigation={navigation}
openScreen={openScreen}
workspaceId={workspaceId}
revision={panelRevision ?? 0}
/>
</PluginInstallationProvider>
</SurfaceErrorBoundary>
);
}
@@ -27,6 +27,7 @@ function installed(): InstalledPlugin {
workspaceRowBadgeItems: [],
filePanels: [],
composerItems: [],
composerPillItems: [],
newWorkspaceItems: [],
workspacePanels: [
{
@@ -1,7 +1,11 @@
import type { EvaluatedPluginWorkspacePanelContribution } from "../types";
import type { InstalledPlugin } from "../types";
import type { PluginPanelParamsSchema, PluginPanelTargetParams } from "@getpaseo/plugin/client";
import { z } from "zod";
import type { EvaluatedPluginWorkspacePanelContribution, InstalledPlugin } from "../types";
import type { PluginWorkspaceTabTarget } from "@/workspace-tabs/model";
const EMPTY_PARAMS_SCHEMA = z.strictObject({});
const AGENT_ID_SCHEMA = z.string().trim().min(1);
export function resolvePluginWorkspacePanel(
plugin: InstalledPlugin | null,
target: PluginWorkspaceTabTarget,
@@ -12,3 +16,213 @@ export function resolvePluginWorkspacePanel(
) ?? null
);
}
export type ParsedPluginPanelParams =
| { ok: false }
| { ok: true; context: "workspace"; params: Record<string, string | number> }
| { ok: true; context: "agent"; agentId: string; params: Record<string, string | number> };
/**
* Validates `rawParams` against `panel`'s schema (plus required `agentId` for agent panels),
* rejects non-flat or non-primitive inputs and outputs, and evaluates `panel.identity(params)`
* on the parsed output. Stores parsed output when the schema is idempotent on it (preserving
* defaults and generated values across renders and identity checks), falling back to caller input
* for non-idempotent transforms so transforms only apply once. Returns `null` when rejected.
*/
export function buildPluginPanelTarget(
pluginId: string,
panel: EvaluatedPluginWorkspacePanelContribution,
rawParams: unknown,
): PluginWorkspaceTabTarget | null {
if (!rawParams || typeof rawParams !== "object" || Array.isArray(rawParams)) {
return null;
}
const input = rawParams as Record<string, unknown>;
const isAgent = panel.context === "agent";
const schema = panel.paramsSchema ?? EMPTY_PARAMS_SCHEMA;
let agentId: string | undefined;
let schemaInput: Record<string, unknown> = input;
if (isAgent) {
const parsedAgentId = AGENT_ID_SCHEMA.safeParse(input.agentId);
if (!parsedAgentId.success) return null;
agentId = parsedAgentId.data;
const { agentId: _agentId, ...extraInput } = input;
schemaInput = extraInput;
}
const storedInput = extractFlatPrimitiveParams(schemaInput, isAgent);
if (!storedInput) return null;
const parsed = schema.safeParse(schemaInput);
if (!parsed.success) return null;
const parsedOutput = extractFlatPrimitiveParams(parsed.data, isAgent);
if (!parsedOutput) return null;
const qualifiedId = `${pluginId}/${panel.id}`;
const storedParams = selectStoredPanelParams(schema, storedInput, parsedOutput, isAgent);
if (panel.context === "agent" && agentId !== undefined) {
const identityKey = evaluateIdentityKey(
qualifiedId,
panel.identity,
Object.freeze({ ...parsedOutput, agentId }),
);
return {
kind: "plugin",
pluginId,
panelId: panel.id,
context: "agent",
agentId,
...(Object.keys(storedParams).length > 0 ? { params: storedParams } : {}),
...(identityKey !== undefined ? { identityKey } : {}),
};
}
const identityKey = evaluateIdentityKey(
qualifiedId,
panel.context === "workspace" ? panel.identity : undefined,
Object.freeze({ ...parsedOutput }),
);
return {
kind: "plugin",
pluginId,
panelId: panel.id,
context: "workspace",
...(Object.keys(storedParams).length > 0 ? { params: storedParams } : {}),
...(identityKey !== undefined ? { identityKey } : {}),
};
}
const parsedPanelParamsCache = new WeakMap<
EvaluatedPluginWorkspacePanelContribution,
WeakMap<PluginWorkspaceTabTarget, ParsedPluginPanelParams>
>();
/**
* Validates stored params on `target` against `panel`'s current schema once per
* `(panel, target)` pair and caches the result so repeated layout reads stay stable.
* Unexpected callback exceptions inside schema transforms are not swallowed.
*/
export function parseRegisteredPluginPanelParams(
panel: EvaluatedPluginWorkspacePanelContribution,
target: PluginWorkspaceTabTarget,
): ParsedPluginPanelParams {
let byTarget = parsedPanelParamsCache.get(panel);
const cached = byTarget?.get(target);
if (cached) return cached;
const computed = computeRegisteredPluginPanelParams(panel, target);
if (!byTarget) {
byTarget = new WeakMap();
parsedPanelParamsCache.set(panel, byTarget);
}
byTarget.set(target, computed);
return computed;
}
function computeRegisteredPluginPanelParams(
panel: EvaluatedPluginWorkspacePanelContribution,
target: PluginWorkspaceTabTarget,
): ParsedPluginPanelParams {
if (target.context !== panel.context) return Object.freeze({ ok: false });
const schema = panel.paramsSchema ?? EMPTY_PARAMS_SCHEMA;
if (panel.context === "agent" && target.context === "agent") {
const parsedAgentId = AGENT_ID_SCHEMA.safeParse(target.agentId);
if (!parsedAgentId.success) return Object.freeze({ ok: false });
const parsed = schema.safeParse(target.params ?? {});
if (!parsed.success) return Object.freeze({ ok: false });
const params = extractFlatPrimitiveParams(parsed.data, true);
if (!params) return Object.freeze({ ok: false });
return Object.freeze({
ok: true,
context: "agent",
agentId: parsedAgentId.data,
params: Object.freeze(params),
});
}
const parsed = schema.safeParse(target.params ?? {});
if (!parsed.success) return Object.freeze({ ok: false });
const params = extractFlatPrimitiveParams(parsed.data, false);
if (!params) return Object.freeze({ ok: false });
return Object.freeze({
ok: true,
context: "workspace",
params: Object.freeze(params),
});
}
/**
* Resolves a workspace panel target with `{}` for parameterless UI launchers.
* Returns `null` for agent panels or panels whose `params` schema rejects `{}`.
*/
export function resolveParameterlessPluginPanelTarget(
pluginId: string,
panel: EvaluatedPluginWorkspacePanelContribution,
): PluginWorkspaceTabTarget | null {
if (panel.context !== "workspace") return null;
return buildPluginPanelTarget(pluginId, panel, {});
}
export function describePluginPanelParams(
target: PluginWorkspaceTabTarget,
): PluginPanelTargetParams {
if (target.context === "agent") {
return { ...target.params, agentId: target.agentId };
}
return { ...target.params };
}
function extractFlatPrimitiveParams(
value: unknown,
omitAgentId: boolean,
): Record<string, string | number> | null {
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
const cleaned: Record<string, string | number> = {};
for (const [key, entry] of Object.entries(value)) {
if (omitAgentId && key === "agentId") continue;
if (entry === undefined) continue;
if (typeof entry === "string") {
cleaned[key] = entry;
continue;
}
if (typeof entry === "number" && Number.isFinite(entry)) {
cleaned[key] = entry;
continue;
}
return null;
}
return cleaned;
}
function selectStoredPanelParams(
schema: PluginPanelParamsSchema,
storedInput: Record<string, string | number>,
parsedOutput: Record<string, string | number>,
omitAgentId: boolean,
): Record<string, string | number> {
const reparsed = schema.safeParse(parsedOutput);
if (!reparsed.success) return storedInput;
const normalized = extractFlatPrimitiveParams(reparsed.data, omitAgentId);
if (!normalized) return storedInput;
return flatParamsEqual(normalized, parsedOutput) ? parsedOutput : storedInput;
}
function flatParamsEqual(
left: Record<string, string | number>,
right: Record<string, string | number>,
): boolean {
const leftKeys = Object.keys(left);
if (leftKeys.length !== Object.keys(right).length) return false;
return leftKeys.every((key) => Object.is(left[key], right[key]));
}
function evaluateIdentityKey<Params>(
qualifiedPanelId: string,
identity: ((params: Params) => string) | undefined,
params: Params,
): string | undefined {
if (!identity) return undefined;
const key = identity(params);
if (typeof key !== "string") {
throw new Error(`Panel "${qualifiedPanelId}" identity must return a string`);
}
return key;
}
@@ -1,5 +1,5 @@
import { workspaceTabSwitcherPopoverLayout } from "../workspace-tab-layout";
import { memo, useCallback, useMemo, useRef, useState } from "react";
import { memo, useCallback, useMemo, useRef, useState, type ReactElement } from "react";
import { Keyboard, Pressable, Text, View } from "react-native";
import { useTranslation } from "react-i18next";
import { SquarePen, SquareTerminal } from "lucide-react-native";
@@ -12,11 +12,12 @@ import {
WorkspaceTabOptionRow,
type WorkspaceTabPresentation,
} from "@/screens/workspace/workspace-tab-presentation";
import { useFilePanelOpenWithMenu } from "@/file-panels";
import { useFilePanelOpenWithMenu, type FilePanelOpenWithMenu } from "@/file-panels";
import { useFileTabMenu } from "@/screens/workspace/use-file-tab-menu";
import { MobileTabTrailingAccessory } from "@/screens/workspace/workspace-tab-trailing-accessory";
import {
buildWorkspaceTabMenuEntries,
type WorkspaceTabMenuEntry,
type WorkspaceTabMenuLabels,
} from "@/screens/workspace/workspace-tab-menu";
import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-types";
@@ -145,6 +146,52 @@ interface MobileWorkspaceTabSwitcherProps {
onCloseOtherTabs: (tabId: string) => Promise<void> | void;
}
function MobileWorkspaceTabOptionRow({
presentation,
selected,
active,
onPress,
menuTestIDBase,
fallbackLabel,
menuEntries,
openWith,
fileMenu,
}: {
presentation: WorkspaceTabPresentation;
selected: boolean;
active: boolean;
onPress: () => void;
menuTestIDBase: string;
fallbackLabel: string;
menuEntries: WorkspaceTabMenuEntry[];
openWith: FilePanelOpenWithMenu;
fileMenu: ReactElement | null;
}) {
const presentationLabel =
presentation.titleState === "loading" ? fallbackLabel : presentation.label;
const trailingAccessory = useMemo(
() => (
<MobileTabTrailingAccessory
menuTestIDBase={menuTestIDBase}
presentationLabel={presentationLabel}
menuEntries={menuEntries}
openWith={openWith}
fileMenu={fileMenu}
/>
),
[fileMenu, menuEntries, menuTestIDBase, openWith, presentationLabel],
);
return (
<WorkspaceTabOptionRow
presentation={presentation}
selected={selected}
active={active}
onPress={onPress}
trailingAccessory={trailingAccessory}
/>
);
}
function MobileWorkspaceTabOption({
tab,
tabIndex,
@@ -247,30 +294,21 @@ function MobileWorkspaceTabOption({
testIDBase: menuTestIDBase,
onRevealInFiles: onDismissSwitcher,
});
const trailingAccessory = useMemo(
() => (
<MobileTabTrailingAccessory
const renderPresentation = useCallback(
(presentation: WorkspaceTabPresentation) => (
<MobileWorkspaceTabOptionRow
presentation={presentation}
selected={selected}
active={active}
onPress={onPress}
menuTestIDBase={menuTestIDBase}
presentationLabel={fallbackLabel}
fallbackLabel={fallbackLabel}
menuEntries={menuEntries}
openWith={openWith}
fileMenu={fileMenu}
/>
),
[menuTestIDBase, fallbackLabel, menuEntries, openWith, fileMenu],
);
const renderPresentation = useCallback(
(presentation: WorkspaceTabPresentation) => (
<WorkspaceTabOptionRow
presentation={presentation}
selected={selected}
active={active}
onPress={onPress}
trailingAccessory={trailingAccessory}
/>
),
[selected, active, onPress, trailingAccessory],
[selected, active, onPress, menuTestIDBase, fallbackLabel, menuEntries, openWith, fileMenu],
);
return (
@@ -14,6 +14,7 @@ import {
import { DropdownMenu, DropdownMenuContent } from "@/components/ui/dropdown-menu";
import type { PanelIconProps } from "@/panels/panel-registry";
import { getPanelRegistration } from "@/panels/panel-registry";
import { usePanelInstanceAttributes } from "@/panels/panel-instance-attributes";
import { useViewedAgent } from "@/timeline/use-viewed-agent";
import { useWorkspaceDirectory } from "@/stores/session-store-hooks";
import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-types";
@@ -72,6 +73,12 @@ export function SheetPane({ sheet, onClose, onBack, opener = null, isTop }: Shee
workspaceId: host.workspaceId,
tabId: tab.tabId,
});
const attributes = usePanelInstanceAttributes({
serverId: host.serverId,
workspaceId: host.workspaceId,
tabId: tab.tabId,
});
const title = attributes.title ?? descriptor.label;
const openTabInFront = useWorkspaceLayoutStore((state) => state.openTabInFront);
const { workspaceKey } = host;
@@ -82,7 +89,7 @@ export function SheetPane({ sheet, onClose, onBack, opener = null, isTop }: Shee
const filePath = tab.target.kind === "file" ? tab.target.path : null;
const header = useMemo<SheetHeader>(
() => ({
title: descriptor.label,
title,
leading: <ThemedPanelIcon icon={descriptor.icon} size={16} />,
back: onBack ? { onPress: onBack } : undefined,
// The sheet is for looking; the full-screen glyph takes the tab out of the sheet and into
@@ -101,16 +108,7 @@ export function SheetPane({ sheet, onClose, onBack, opener = null, isTop }: Shee
</>
),
}),
[
descriptor.icon,
descriptor.label,
filePath,
handleOpenAsTab,
onBack,
onClose,
sheet.policy.openAsTab,
t,
],
[descriptor.icon, title, filePath, handleOpenAsTab, onBack, onClose, sheet.policy.openAsTab, t],
);
const tabDescriptor = useMemo<WorkspaceTabDescriptor>(
@@ -146,7 +144,7 @@ export function SheetPane({ sheet, onClose, onBack, opener = null, isTop }: Shee
<SheetBottomInset
style={styles.body}
role="dialog"
aria-label={descriptor.label}
aria-label={title}
testID="sheet-tab-body"
>
<WorkspacePaneContent
@@ -82,14 +82,16 @@ function WorkspaceTabPresentationResolverInner({
(state) => draftKey !== null && hasUnsavedDraft(state, draftKey),
);
const modified = attributes.modified || draftModified;
const label = attributes.title ?? descriptor.label;
const tooltip = attributes.title ?? descriptor.tooltip;
const presentation = useMemo(
() => ({
key: tab.key,
kind: tab.kind,
label: descriptor.label,
label,
subtitle: descriptor.subtitle,
tooltip: descriptor.tooltip,
tooltip,
modified,
showCloseButton: registration.showCloseButton,
titleState: descriptor.titleState,
@@ -98,8 +100,8 @@ function WorkspaceTabPresentationResolverInner({
}),
[
descriptor.icon,
descriptor.label,
descriptor.tooltip,
label,
tooltip,
descriptor.statusBucket,
descriptor.subtitle,
descriptor.titleState,
@@ -276,3 +276,119 @@ it.each([1, 2])(
expect(visible).toEqual(["agent-a"]);
},
);
it("hydrates legacy plugin tabs without params or identityKey and round-trips parameterized plugin tabs", async () => {
const workspaceKey = "server:workspace";
const values = new Map([
[
"workspace-layout-state",
JSON.stringify({
version: 2,
state: {
layoutByWorkspace: {
[workspaceKey]: {
root: {
kind: "pane",
pane: {
id: "main",
tabIds: ["plugin_workspace_6_review_8_overview"],
focusedTabId: "plugin_workspace_6_review_8_overview",
tabs: [
{
tabId: "plugin_workspace_6_review_8_overview",
target: {
kind: "plugin",
pluginId: "review",
panelId: "overview",
context: "workspace",
},
createdAt: 1,
},
],
},
},
focusedPaneId: "main",
},
},
},
}),
],
]);
const storage: StateStorage = {
getItem: (name) => values.get(name) ?? null,
setItem: (name, value) => {
values.set(name, value);
},
removeItem: (name) => {
values.delete(name);
},
};
const store = createWorkspaceLayoutStore(undefined, storage);
await store.persist.rehydrate();
expect(collectAllTabs(store.getState().layoutByWorkspace[workspaceKey].root)[0]?.target).toEqual({
kind: "plugin",
pluginId: "review",
panelId: "overview",
context: "workspace",
});
store.getState().openTab({
workspaceKey,
target: {
kind: "plugin",
pluginId: "review",
panelId: "pr",
context: "workspace",
params: { prNumber: 42, commentId: "c1" },
identityKey: "42",
},
intent: "reveal",
});
store.getState().openTab({
workspaceKey,
target: {
kind: "plugin",
pluginId: "review",
panelId: "notes",
context: "agent",
agentId: "agent-1",
params: { line: 9 },
identityKey: "agent-1:9",
},
intent: "reveal",
});
const restored = createWorkspaceLayoutStore(undefined, storage);
await restored.persist.rehydrate();
expect(
collectAllTabs(restored.getState().layoutByWorkspace[workspaceKey].root).map(
(tab) => tab.target,
),
).toEqual(
expect.arrayContaining([
{
kind: "plugin",
pluginId: "review",
panelId: "overview",
context: "workspace",
},
{
kind: "plugin",
pluginId: "review",
panelId: "pr",
context: "workspace",
params: { prNumber: 42, commentId: "c1" },
identityKey: "42",
},
{
kind: "plugin",
pluginId: "review",
panelId: "notes",
context: "agent",
agentId: "agent-1",
params: { line: 9 },
identityKey: "agent-1:9",
},
]),
);
});
@@ -62,6 +62,8 @@ const WorkspaceTabTargetStorageSchema = z.discriminatedUnion("kind", [
pluginId: z.string(),
panelId: z.string(),
context: z.literal("workspace"),
params: z.record(z.string(), z.union([z.string(), z.number()])).optional(),
identityKey: z.string().optional(),
}),
z.strictObject({
kind: z.literal("plugin"),
@@ -69,6 +71,8 @@ const WorkspaceTabTargetStorageSchema = z.discriminatedUnion("kind", [
panelId: z.string(),
context: z.literal("agent"),
agentId: z.string(),
params: z.record(z.string(), z.union([z.string(), z.number()])).optional(),
identityKey: z.string().optional(),
}),
]),
]);
@@ -475,6 +475,47 @@ describe("terminal emulator runtime in a real browser", () => {
expect(mounted.inputs).toEqual(["legacy renderer paste"]);
});
it.skipIf(!navigator.platform.includes("Linux")).each([
{
mode: "mouse tracking",
sequence: "\x1b[?1000h\x1b[?1006h",
shiftKey: false,
reportsMouse: true,
},
{ mode: "shell", sequence: "", shiftKey: false, reportsMouse: false },
{
mode: "forced selection",
sequence: "\x1b[?1000h\x1b[?1006h",
shiftKey: true,
reportsMouse: false,
},
])(
"routes a middle click in $mode to one input path",
async ({ sequence, shiftKey, reportsMouse }) => {
const mounted = createTerminalHost({ width: 720, height: 360 });
await new Promise<void>((resolve) =>
mounted.runtime.write({ data: terminalOutput(sequence + "ready"), onCommitted: resolve }),
);
const screen = mounted.host.querySelector(".xterm-screen")!;
const bounds = screen.getBoundingClientRect();
const mouse = {
button: 1,
bubbles: true,
cancelable: true,
shiftKey,
clientX: bounds.x + 2,
clientY: bounds.y + 2,
};
screen.dispatchEvent(new MouseEvent("mousedown", { ...mouse, buttons: 4 }));
const release = new MouseEvent("mouseup", mouse);
screen.dispatchEvent(release);
expect(mounted.inputs).toEqual(reportsMouse ? ["\x1b[<1;1;1M", "\x1b[<1;1;1m"] : []);
expect(release.defaultPrevented).toBe(reportsMouse);
},
);
it("pastes clipboard text on Ctrl+V without reading the clipboard image", async () => {
const mounted = createTerminalHost({ width: 720, height: 360, isMac: false });
await waitFor({ predicate: () => mounted.sizes.length > 0 });
@@ -124,6 +124,7 @@ interface TerminalEmulatorRuntimeDisposables {
clearFitTimeouts: () => void;
removeFontListeners: () => void;
removeFilePasteListener: () => void;
removeMiddleClickListeners: () => void;
removeUserInputListeners: () => void;
restoreDocumentStyles: () => void;
restoreViewportStyles: () => void;
@@ -782,6 +783,26 @@ export class TerminalEmulatorRuntime {
};
input.host.addEventListener("paste", filePasteHandler, true);
// Chromium pastes the Linux primary selection on middle-button release.
// If xterm sent the press to the PTY, the application owns that gesture.
let middlePressReported = false;
const recordMiddlePress = (event: MouseEvent): void => {
if (event.button === 1) {
middlePressReported = !event.shiftKey && terminal.modes.mouseTrackingMode !== "none";
}
};
const cancelReportedMiddleRelease = (event: MouseEvent): void => {
if (event.button === 1 && middlePressReported) {
middlePressReported = false;
event.preventDefault();
}
};
const terminalElement = terminal.element;
if (navigator.platform.includes("Linux")) {
terminalElement?.addEventListener("mousedown", recordMiddlePress, true);
terminalElement?.addEventListener("mouseup", cancelReportedMiddleRelease, true);
}
const resizeObserver = new ResizeObserver(() => {
fitAndEmitResize({ shouldClaim: false });
});
@@ -864,6 +885,10 @@ export class TerminalEmulatorRuntime {
removeFilePasteListener: () => {
input.host.removeEventListener("paste", filePasteHandler, true);
},
removeMiddleClickListeners: () => {
terminalElement?.removeEventListener("mousedown", recordMiddlePress, true);
terminalElement?.removeEventListener("mouseup", cancelReportedMiddleRelease, true);
},
removeUserInputListeners: () => {
for (const type of USER_INPUT_EVENT_TYPES) {
input.host.removeEventListener(type, recordUserInputEvent, true);
@@ -899,6 +924,7 @@ export class TerminalEmulatorRuntime {
disposables.clearFitTimeouts();
disposables.removeFontListeners();
disposables.removeFilePasteListener();
disposables.removeMiddleClickListeners();
disposables.removeUserInputListeners();
disposables.disposeFitAddon();
disposables.disposeWebglAddon();
@@ -195,4 +195,60 @@ describe("plugin panel tab identity", () => {
expect(workspace).toBe("plugin_workspace_6_review_7_details");
expect(agent).toBe("plugin_agent_6_review_7_details_7_agent-1");
});
it("preserves legacy targets without params or identityKey and distinguishes keyed targets", () => {
const legacy = normalizeWorkspaceTabTarget({
kind: "plugin",
pluginId: "review",
panelId: "details",
context: "workspace",
});
expect(legacy).toEqual({
kind: "plugin",
pluginId: "review",
panelId: "details",
context: "workspace",
});
const pr1a = normalizeWorkspaceTabTarget({
kind: "plugin",
pluginId: "review",
panelId: "pr",
context: "workspace",
params: { prNumber: 1, commentId: "a" },
identityKey: "1",
});
const pr1b = normalizeWorkspaceTabTarget({
kind: "plugin",
pluginId: "review",
panelId: "pr",
context: "workspace",
params: { prNumber: 1, commentId: "b" },
identityKey: "1",
});
const pr2 = normalizeWorkspaceTabTarget({
kind: "plugin",
pluginId: "review",
panelId: "pr",
context: "workspace",
params: { prNumber: 2, commentId: "a" },
identityKey: "2",
});
expect(pr1a).toEqual({
kind: "plugin",
pluginId: "review",
panelId: "pr",
context: "workspace",
params: { prNumber: 1, commentId: "a" },
identityKey: "1",
});
expect(pr1a && pr1b && workspaceTabTargetsEqual(pr1a, pr1b)).toBe(false);
expect(pr1a && pr2 && buildDeterministicWorkspaceTabId(pr1a)).not.toBe(
pr2 && buildDeterministicWorkspaceTabId(pr2),
);
expect(pr1a && pr1b && buildDeterministicWorkspaceTabId(pr1a)).toBe(
pr1b && buildDeterministicWorkspaceTabId(pr1b),
);
});
});
+60 -9
View File
@@ -120,17 +120,29 @@ export function workspaceTabTargetsEqual(
return left.terminalId === right.terminalId;
}
if (left.kind === "plugin" && right.kind === "plugin") {
return (
left.pluginId === right.pluginId &&
left.panelId === right.panelId &&
left.context === right.context &&
(left.context === "workspace" ||
(right.context === "agent" && left.agentId === right.agentId))
);
return pluginTabTargetsEqual(left, right);
}
return secondaryWorkspaceTabTargetsEqual(left, right);
}
function pluginTabTargetsEqual(
left: Extract<WorkspaceTabTarget, { kind: "plugin" }>,
right: Extract<WorkspaceTabTarget, { kind: "plugin" }>,
): boolean {
if (
left.pluginId !== right.pluginId ||
left.panelId !== right.panelId ||
left.context !== right.context ||
left.identityKey !== right.identityKey
) {
return false;
}
if (left.context === "agent" && right.context === "agent" && left.agentId !== right.agentId) {
return false;
}
return recordsShallowEqual(left.params ?? {}, right.params ?? {});
}
function secondaryWorkspaceTabTargetsEqual(
left: WorkspaceTabTarget,
right: WorkspaceTabTarget,
@@ -229,6 +241,9 @@ export function buildDeterministicWorkspaceTabId(target: WorkspaceTabTarget): st
}
if (target.kind === "plugin") {
const identity = `${target.pluginId.length}_${target.pluginId}_${target.panelId.length}_${target.panelId}`;
if (target.identityKey !== undefined) {
return `plugin_key_${target.context}_${identity}_${target.identityKey.length}_${target.identityKey}`;
}
return target.context === "workspace"
? `plugin_workspace_${identity}`
: `plugin_agent_${identity}_${target.agentId.length}_${target.agentId}`;
@@ -236,17 +251,53 @@ export function buildDeterministicWorkspaceTabId(target: WorkspaceTabTarget): st
return `file_${target.path}`;
}
function normalizePluginTargetParams(
value: unknown,
omitAgentId: boolean,
): Record<string, string | number> | undefined {
if (!isPlainRecord(value)) return undefined;
const cleaned: Record<string, string | number> = {};
let hasKeys = false;
for (const [key, entry] of Object.entries(value)) {
if (omitAgentId && key === "agentId") continue;
if (typeof entry === "string" || (typeof entry === "number" && Number.isFinite(entry))) {
cleaned[key] = entry;
hasKeys = true;
}
}
return hasKeys ? cleaned : undefined;
}
function normalizePluginTabTarget(
value: Extract<WorkspaceTabTarget, { kind: "plugin" }>,
): WorkspaceTabTarget | null {
const pluginId = trimNonEmpty(value.pluginId);
const panelId = trimNonEmpty(value.panelId);
if (!pluginId || !panelId) return null;
const identityKey = typeof value.identityKey === "string" ? value.identityKey : undefined;
if (value.context === "workspace") {
return { kind: "plugin", pluginId, panelId, context: "workspace" };
const params = normalizePluginTargetParams(value.params, false);
return {
kind: "plugin",
pluginId,
panelId,
context: "workspace",
...(params ? { params } : {}),
...(identityKey !== undefined ? { identityKey } : {}),
};
}
const agentId = trimNonEmpty(value.agentId);
return agentId ? { kind: "plugin", pluginId, panelId, context: "agent", agentId } : null;
if (!agentId) return null;
const params = normalizePluginTargetParams(value.params, true);
return {
kind: "plugin",
pluginId,
panelId,
context: "agent",
agentId,
...(params ? { params } : {}),
...(identityKey !== undefined ? { identityKey } : {}),
};
}
function trimNonEmpty(value: string | null | undefined): string | null {
@@ -0,0 +1,108 @@
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { pluginExecutionApprovals } from "@/plugins/execution-approval";
import { pluginRegistry } from "@/plugins/registry";
import type { NewTabSelection } from "@/workspace-tabs/new-tab";
import { buildPluginWorkspaceTabLaunchItems } from "./index";
const SERVER_ID = "server-launcher";
const fakeDaemon = {
observeEvents: () => ({
ready: Promise.resolve({ subscriptionId: "events" }),
subscribe: () => () => undefined,
release: async () => undefined,
}),
} as unknown as DaemonClient;
describe("buildPluginWorkspaceTabLaunchItems", () => {
beforeEach(() => {
pluginExecutionApprovals.setDecision(SERVER_ID, "launcher-plugin", "approved");
pluginRegistry.installCatalog(
SERVER_ID,
[
{
id: "launcher-plugin",
requirements: { paseo: ">=0.8.0" },
clientBundle: `(function(require) {
const { z } = require("zod");
const Component = () => null;
return { default: function(client) {
client.addWorkspacePanel({
id: "no-params",
title: "No Params",
icon: "File",
Component,
});
client.addWorkspacePanel({
id: "optional-params",
title: "Optional Params",
icon: "File",
params: z.object({ filter: z.string().default("open") }),
identity: (p) => p.filter,
Component,
});
client.addWorkspacePanel({
id: "required-params",
title: "Required Params",
icon: "File",
params: z.object({ prNumber: z.number() }),
identity: (p) => String(p.prNumber),
Component,
});
client.addWorkspacePanel({
id: "broken-identity",
title: "Broken Identity",
icon: "File",
identity: () => {
throw new Error("identity boom");
},
Component,
});
return function() {};
}};
})`,
},
],
{ client: fakeDaemon, audio: { play: async () => 0 } },
);
});
afterEach(() => {
pluginRegistry.removeHost(SERVER_ID);
pluginExecutionApprovals.clearHost(SERVER_ID);
vi.restoreAllMocks();
});
it("excludes panels whose schema rejects {} and isolates throwing panels", () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
const launched: NewTabSelection[] = [];
const items = buildPluginWorkspaceTabLaunchItems({
plugins: pluginRegistry.getSnapshot(),
serverId: SERVER_ID,
host: "main",
launchSelection: (selection) => () => launched.push(selection),
});
expect(items.map((item) => item.id)).toEqual([
"plugin:launcher-plugin:no-params",
"plugin:launcher-plugin:optional-params",
]);
expect(warn).toHaveBeenCalledTimes(1);
items[1]?.launch({ kind: "open" });
expect(launched).toEqual([
{
kind: "target",
target: {
kind: "plugin",
pluginId: "launcher-plugin",
panelId: "optional-params",
context: "workspace",
params: { filter: "open" },
identityKey: "open",
},
},
]);
});
});
@@ -14,7 +14,9 @@ import { useIsCompactFormFactor } from "@/constants/layout";
import { useDaemonConfig } from "@/hooks/use-daemon-config";
import { pluginIconComponent } from "@/plugins/icons";
import { useInstalledPlugins } from "@/plugins/registry";
import type { InstalledPlugin } from "@/plugins/types";
import { pluginPanelSupportsLocation } from "@/plugins/workspace-panels/locations";
import { resolveParameterlessPluginPanelTarget } from "@/plugins/workspace-panels/resolution";
import { buildSettingsHostSectionRoute } from "@/utils/host-routes";
import type { NewTabSelection } from "@/workspace-tabs/new-tab";
import type { WorkspaceTabTarget } from "@/workspace-tabs/model";
@@ -197,27 +199,12 @@ export function useWorkspaceTabLaunchCatalog(input: {
return item.hidden || !panelSupportsHost(item.panelKind, host) ? [] : [item];
});
const pluginItems: WorkspaceTabLaunchItem[] = [];
for (const plugin of plugins) {
if (plugin.serverId !== serverId) continue;
for (const panel of plugin.workspacePanels) {
if (panel.context !== "workspace") continue;
const location = host === "explorer" ? "explorer" : "workspace";
if (!pluginPanelSupportsLocation(panel, location)) continue;
const selection: NewTabSelection = {
kind: "target",
target: { kind: "plugin", pluginId: plugin.id, panelId: panel.id, context: "workspace" },
};
pluginItems.push({
id: `plugin:${plugin.id}:${panel.id}`,
label: plugin.i18n.resolve(panel.title, plugin.locale),
Icon: pluginIconComponent(panel.icon),
disabled: false,
panelKind: "plugin",
launch: launchSelection(selection),
});
}
}
const pluginItems = buildPluginWorkspaceTabLaunchItems({
plugins,
serverId,
host,
launchSelection,
});
const profiles = resolveTerminalProfiles(config?.terminalProfiles);
const groups: WorkspaceTabLaunchGroup[] = [{ id: "tabs", label: null, items: tabItems }];
@@ -266,4 +253,48 @@ export function useWorkspaceTabLaunchCatalog(input: {
]);
}
/**
* Builds launcher items for parameterless workspace panels registered on `serverId`,
* skipping panels whose `params` schema rejects `{}` and isolating any throwing panel.
*/
export function buildPluginWorkspaceTabLaunchItems(input: {
plugins: readonly InstalledPlugin[];
serverId: string;
host: PaneHost;
launchSelection: (
selection: NewTabSelection,
) => (destination: WorkspaceTabLaunchDestination) => void;
}): WorkspaceTabLaunchItem[] {
const location = input.host === "explorer" ? "explorer" : "workspace";
const pluginItems: WorkspaceTabLaunchItem[] = [];
for (const plugin of input.plugins) {
if (plugin.serverId !== input.serverId) continue;
for (const panel of plugin.workspacePanels) {
if (!pluginPanelSupportsLocation(panel, location)) continue;
try {
const target = resolveParameterlessPluginPanelTarget(plugin.id, panel);
if (!target) continue;
const selection: NewTabSelection = {
kind: "target",
target,
};
pluginItems.push({
id: `plugin:${plugin.id}:${panel.id}`,
label: plugin.i18n.resolve(panel.title, plugin.locale),
Icon: pluginIconComponent(panel.icon),
disabled: false,
panelKind: "plugin",
launch: input.launchSelection(selection),
});
} catch (error) {
console.warn(
`[WorkspaceTabLauncher] Skipping plugin panel "${plugin.id}/${panel.id}" launcher item:`,
error,
);
}
}
}
return pluginItems;
}
export { getBuiltInLaunchOrder } from "./internal/catalog";
+4
View File
@@ -24,6 +24,8 @@ export type PluginWorkspaceTabTarget =
pluginId: string;
panelId: string;
context: "workspace";
params?: Record<string, string | number>;
identityKey?: string;
}
| {
kind: "plugin";
@@ -31,6 +33,8 @@ export type PluginWorkspaceTabTarget =
panelId: string;
context: "agent";
agentId: string;
params?: Record<string, string | number>;
identityKey?: string;
};
export type WorkspaceTabTarget =
+22 -1
View File
@@ -1215,6 +1215,27 @@ async function stopCliDaemon({ appPath, env }) {
});
}
async function expectPageDownKeepsWorkspaceAligned(page) {
const composer = page.getByRole("textbox", { name: "Message agent..." });
const newTab = page.getByRole("button", { name: "New tab", exact: true });
await composer.fill("Keep the workspace in place");
await composer.press("ArrowLeft");
const before = await newTab.boundingBox();
assert.ok(before, "Workspace tab controls are visible before Page Down");
await composer.press("PageDown");
await page.evaluate(
() =>
new Promise((resolve) => {
requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
}),
);
const after = await newTab.boundingBox();
assert.ok(after, "Workspace tab controls are visible after Page Down");
assert.equal(after.x, before.x, "Page Down in the chat draft keeps the workspace aligned");
}
async function openSmokeWorkspace({ appPath, env, page, daemonHome }) {
const projectPath = path.join(daemonHome, "sandbox-smoke-project");
fs.mkdirSync(projectPath);
@@ -1242,7 +1263,7 @@ async function openSmokeWorkspace({ appPath, env, page, daemonHome }) {
await page.getByRole("button", { name: "Sandbox smoke workspace", exact: true }).click();
await page.waitForURL((url) => url.pathname.endsWith(`/workspace/${workspace.workspaceId}`));
await page.getByRole("button", { name: "Agent", exact: true }).click();
await page.getByRole("textbox", { name: "Message agent..." }).click();
await expectPageDownKeepsWorkspaceAligned(page);
console.log(`Packaged desktop smoke: renderer opened workspace ${workspace.workspaceId}`);
}
@@ -239,7 +239,7 @@ describe("desktop-settings", () => {
expect(persisted.settings.daemon.manageBuiltInDaemon).toBe(false);
});
it("does not rewrite existing settings while reading them", async () => {
it("does not rewrite migrated settings while reading them", async () => {
const userDataPath = await createTempUserDataDir();
directories.add(userDataPath);
const raw = JSON.stringify({
@@ -253,6 +253,7 @@ describe("desktop-settings", () => {
},
migrations: {
legacyRendererSettingsImported: false,
daemonStopOnQuitDefaultApplied: true,
},
});
await writeFile(settingsFilePath(userDataPath), raw);
@@ -265,7 +266,7 @@ describe("desktop-settings", () => {
expect(persisted).toBe(raw);
});
it("resets the pre-existing keep-running default so the daemon stops with the app", async () => {
it("persists the stop-on-quit migration on the first read", async () => {
const userDataPath = await createTempUserDataDir();
directories.add(userDataPath);
await writeFile(
@@ -276,7 +277,7 @@ describe("desktop-settings", () => {
releaseChannel: "stable",
daemon: { manageBuiltInDaemon: true, keepRunningAfterQuit: true },
},
migrations: { legacyRendererSettingsImported: true },
futureSetting: { value: 7 },
}),
);
const store = createDesktopSettingsStore({ userDataPath });
@@ -284,6 +285,12 @@ describe("desktop-settings", () => {
const settings = await store.get();
expect(settings.daemon.keepRunningAfterQuit).toBe(false);
const persisted = JSON.parse(await readFile(settingsFilePath(userDataPath), "utf8"));
expect(persisted).toMatchObject({
settings: { daemon: { manageBuiltInDaemon: true, keepRunningAfterQuit: false } },
migrations: { daemonStopOnQuitDefaultApplied: true },
futureSetting: { value: 7 },
});
});
it("keeps an explicit keep-running choice across restarts", async () => {
@@ -238,12 +238,9 @@ function hasLegacyRendererOwnedPatch(patch: DesktopSettingsPatch): boolean {
return patch.releaseChannel !== undefined || patch.daemon?.manageBuiltInDaemon !== undefined;
}
function coerceDocument(input: unknown): PersistedDesktopSettingsDocument {
const document = PersistedDocumentSchema.parse(input);
if (document.migrations.daemonStopOnQuitDefaultApplied) {
return document;
}
function applyDaemonStopOnQuitDefault(
document: PersistedDesktopSettingsDocument,
): PersistedDesktopSettingsDocument {
return {
...document,
settings: {
@@ -283,45 +280,39 @@ export function createDesktopSettingsStore({
cachedDocument = document;
}
async function loadDocumentUnlocked(): Promise<PersistedDesktopSettingsDocument> {
async function loadDocumentUnlocked({
recoverUnreadable = false,
} = {}): Promise<PersistedDesktopSettingsDocument> {
if (cachedDocument) {
return cachedDocument;
}
let raw: string;
let document: PersistedDesktopSettingsDocument;
try {
raw = await readFile(filePath, "utf8");
const raw = await readFile(filePath, "utf8");
document = PersistedDocumentSchema.parse(JSON.parse(raw));
} catch (error) {
if (!isNodeError(error) || error.code !== "ENOENT") {
if (!recoverUnreadable && (!isNodeError(error) || error.code !== "ENOENT")) {
throw error;
}
const document = buildDefaultDocument();
await writeDocument(document);
return document;
const defaults = buildDefaultDocument();
await writeDocument(defaults);
return defaults;
}
const document = coerceDocument(JSON.parse(raw));
if (!document.migrations.daemonStopOnQuitDefaultApplied) {
const migrated = applyDaemonStopOnQuitDefault(document);
await writeDocument(migrated);
return migrated;
}
cachedDocument = document;
return document;
}
async function initializeLegacyRendererMigrationUnlocked(): Promise<PersistedDesktopSettingsDocument> {
try {
return await loadDocumentUnlocked();
} catch {
const document = buildDefaultDocument();
await writeDocument(document);
return document;
}
}
return {
async get(): Promise<DesktopSettings> {
const document = await enqueueOperation(async () => {
if (cachedDocument) {
return cachedDocument;
}
return loadDocumentUnlocked();
});
const document = await enqueueOperation(() => loadDocumentUnlocked());
return toDesktopSettings(document.settings);
},
@@ -346,7 +337,7 @@ export function createDesktopSettingsStore({
async migrateLegacyRendererSettings(legacySettings: unknown): Promise<DesktopSettings> {
return enqueueOperation(async () => {
const current = await initializeLegacyRendererMigrationUnlocked();
const current = await loadDocumentUnlocked({ recoverUnreadable: true });
if (current.migrations.legacyRendererSettingsImported) {
return toDesktopSettings(current.settings);
}
+211 -5
View File
@@ -199,22 +199,50 @@ describe("plugin panel SDK boundary", () => {
it("accepts uniform params and persisted tab state alongside 0.12 panels", () => {
expect(
typeErrors(`
import { type PluginClientContext, type PluginFilePanelProps, type PluginWorkspacePanelProps, type PluginAgentPanelProps, type PluginTab, useTabState } from "@getpaseo/plugin/client";
import { type PluginClientContext, type PluginFilePanelProps, type PluginOpenScreenInput, type PluginScreenProps, type PluginWorkspacePanelProps, type PluginAgentPanelProps, type PluginTab, useTabState } from "@getpaseo/plugin/client";
import { z } from "zod";
function FilePanel({ params, revision, tab, file }: PluginFilePanelProps) {
function FilePanel({ params, revision, tab, file, openScreen }: PluginFilePanelProps) {
const [state, setState] = useTabState(tab, z.object({ view: z.enum(["preview", "source"]) }), { view: "preview" });
setState({ view: "source" });
tab.setTitle("Custom file title");
tab.setTitle(null);
// @ts-expect-error title override must be a string or null
tab.setTitle(undefined);
// @ts-expect-error title override must be a string or null
tab.setTitle(123);
tab.setState({ nested: [true, null, 3] });
const input: PluginOpenScreenInput = { screenId: "details", params: { path: file.path } };
openScreen(input);
openScreen({ screenId: "details" });
// @ts-expect-error openScreen takes { screenId, params? }
openScreen("details");
// @ts-expect-error only JSON state crosses the host boundary
tab.setState(() => {});
// @ts-expect-error params belong to the opener
params.path = "other";
return null;
}
function OldWorkspace({ context, workspaceId }: PluginWorkspacePanelProps) { return null; }
function OldAgent({ context, workspaceId, agentId }: PluginAgentPanelProps) { return null; }
function Agent({ params }: PluginAgentPanelProps) { params.agentId.toUpperCase(); return null; }
function OldWorkspace({ context, workspaceId, openScreen }: PluginWorkspacePanelProps) {
openScreen({ screenId: "details", params: { workspaceId } });
return null;
}
function OldAgent({ context, workspaceId, agentId, openScreen }: PluginAgentPanelProps) {
openScreen({ screenId: "details", params: { agentId } });
return null;
}
function Agent({ params, openScreen }: PluginAgentPanelProps) {
params.agentId.toUpperCase();
openScreen({ screenId: "details", params: { agentId: params.agentId } });
return null;
}
function Screen({ params, openScreen }: PluginScreenProps) {
openScreen({ screenId: "other", params: { from: params.from ?? "screen" } });
// @ts-expect-error screen params must be strings
openScreen({ screenId: "other", params: { count: 1 } });
return null;
}
function contribute(client: PluginClientContext) {
client.addScreen({ id: "details", title: "Details", Component: Screen });
client.addWorkspacePanel({ id: "old-workspace", title: "Old", icon: "File", context: "workspace", Component: OldWorkspace });
client.addWorkspacePanel({ id: "old-agent", title: "Old", icon: "File", context: "agent", Component: OldAgent });
client.addWorkspacePanel({ id: "workspace", title: "Workspace", icon: "File", Component: OldWorkspace });
@@ -223,6 +251,128 @@ describe("plugin panel SDK boundary", () => {
`),
).toEqual([]);
});
it("infers author-defined params and identity on workspace and agent panels", () => {
expect(
typeErrors(`
import {
type PluginAgentPanelProps,
type PluginClientContext,
type PluginPanelTargetParams,
type PluginWorkspacePanelProps,
} from "@getpaseo/plugin/client";
import { z } from "zod";
const prSchema = z.object({ prNumber: z.number(), commentId: z.string().optional() });
function ExternalPrPanel({ params, revision }: PluginWorkspacePanelProps<z.infer<typeof prSchema>>) {
const pr: number = params.prNumber;
const comment: string | undefined = params.commentId;
const rev: number = revision;
// @ts-expect-error params are read-only
params.prNumber = 2;
void rev;
void comment;
return null;
}
function ExternalAgentReview({ params }: PluginAgentPanelProps<{ file: string; line?: number }>) {
const agentId: string = params.agentId;
const file: string = params.file;
const line: number | undefined = params.line;
// @ts-expect-error params are read-only
params.agentId = "other";
void agentId;
void file;
void line;
return null;
}
function MismatchedWorkspace({ params }: PluginWorkspacePanelProps<{ wrong: string }>) {
void params.wrong;
return null;
}
function contribute(client: PluginClientContext) {
const targetParams: PluginPanelTargetParams = { a: "x", b: 1, c: undefined };
void targetParams;
client.addWorkspacePanel({
id: "pr",
title: "PR",
icon: "GitPullRequest",
params: prSchema,
identity: (p) => String(p.prNumber),
Component: ({ params, revision, tab }) => {
const n: number = params.prNumber;
const c: string | undefined = params.commentId;
const r: number = revision;
void tab.id;
void n;
void c;
void r;
return null;
},
});
client.addWorkspacePanel({
id: "pr-external",
title: "PR",
icon: "GitPullRequest",
params: prSchema,
Component: ExternalPrPanel,
});
client.addAgentPanel({
id: "agent-review",
title: "Review",
icon: "Scan",
params: z.object({ file: z.string(), line: z.number().optional() }),
identity: (p) => \`\${p.agentId}:\${p.file}\`,
Component: ({ params }) => {
const agentId: string = params.agentId;
const file: string = params.file;
const line: number | undefined = params.line;
void agentId;
void file;
void line;
return null;
},
});
client.addAgentPanel({
id: "agent-review-external",
title: "Review",
icon: "Scan",
params: z.object({ file: z.string(), line: z.number().optional() }),
Component: ExternalAgentReview,
});
client.addWorkspacePanel({
id: "nested-bad",
title: "Bad",
icon: "File",
// @ts-expect-error params values must be flat string | number | undefined
params: z.object({ nested: z.object({ a: z.string() }) }),
Component: () => null,
});
client.addAgentPanel({
id: "bool-bad",
title: "Bad",
icon: "File",
// @ts-expect-error params values must be flat string | number | undefined
params: z.object({ flag: z.boolean() }),
Component: () => null,
});
client.addWorkspacePanel({
id: "mismatched-schema",
title: "Bad",
icon: "File",
params: prSchema,
// @ts-expect-error Component params must match the registered params schema
Component: MismatchedWorkspace,
});
client.addWorkspacePanel({
id: "missing-schema",
title: "Bad",
icon: "File",
// @ts-expect-error cannot require custom params without registering a params schema
Component: MismatchedWorkspace,
});
}
`),
).toEqual([]);
});
});
describe("plugin workspace layout SDK boundary", () => {
@@ -1096,3 +1246,59 @@ describe("agent chat SDK boundary", () => {
).toEqual([]);
});
});
describe("composer pill item SDK boundary", () => {
it("types addComposerPillItem, PluginComposerPillItemProps, and ComposerPill", () => {
expect(
typeErrors(`
import type {
PluginClientContext,
PluginComposerPillItemContribution,
PluginComposerPillItemProps,
PluginPopoverProps,
} from "@getpaseo/plugin/client";
import { ComposerPill, type ComposerPillProps } from "@getpaseo/plugin/client/ui";
import { Text } from "react-native";
function Details({ theme, close, openScreen }: PluginPopoverProps) {
openScreen({ screenId: "main", params: { from: "pill" } });
close();
return <Text style={{ color: theme.colors.foreground }}>Details</Text>;
}
function InboxPill({ workspaceId, agentId, openPopover, openScreen }: PluginComposerPillItemProps) {
const props: ComposerPillProps = {
icon: "Inbox",
label: \`\${workspaceId}:\${agentId}\`,
title: "Open inbox",
disabled: false,
async onPress() {
openPopover(Details);
},
};
if (workspaceId === "hidden") return null;
if (workspaceId === "screen") {
return <ComposerPill icon="ExternalLink" label="Screen" onPress={() => openScreen({ screenId: "main" })} />;
}
return <ComposerPill {...props} />;
}
export default function contribute(client: PluginClientContext) {
const contribution: PluginComposerPillItemContribution = {
id: "inbox",
title: "Inbox",
Component: InboxPill,
};
const remove: () => void = client.addComposerPillItem(contribution);
// @ts-expect-error title is required on composer pill item contribution
client.addComposerPillItem({ id: "missing-title", Component: InboxPill });
// @ts-expect-error label is required on ComposerPill
void (<ComposerPill icon="Inbox" onPress={() => {}} />);
// @ts-expect-error onPress is required on ComposerPill
void (<ComposerPill icon="Inbox" label="Inbox" />);
return remove;
}
`),
).toEqual([]);
});
});
+151 -18
View File
@@ -5,7 +5,7 @@ import type { PluginPaseoApi } from "./reference-api.js";
import type { AgentTimelineItem, JsonValue } from "@getpaseo/protocol/agent-types";
import type { ZodType, input as ZodInput, output as ZodOutput } from "zod";
import type { PluginFile } from "./file.js";
import type { PluginWorkspaceLayout } from "./workspace-layout.js";
import type { PluginPanelTargetParams, PluginWorkspaceLayout } from "./workspace-layout.js";
import type {
PluginComposer,
PluginComposerItemContribution,
@@ -95,6 +95,7 @@ export interface PluginSurfaceProps extends PluginNavigableHostProps {}
export interface PluginScreenProps extends PluginSurfaceProps {
/** The params the screen was opened with; `{}` when none. */
params: PluginScreenParams;
openScreen(input: PluginOpenScreenInput): void;
}
export interface PluginPopoverProps extends PluginHostProps {
@@ -102,6 +103,25 @@ export interface PluginPopoverProps extends PluginHostProps {
openScreen(input: PluginOpenScreenInput): void;
}
export interface PluginComposerPillItemProps extends PluginHostProps {
workspaceId: string;
agentId: string;
openScreen(input: PluginOpenScreenInput): void;
/** Anchored to the pill on wide layouts; a bottom sheet on compact layouts. */
openPopover(Content: ComponentType<PluginPopoverProps>): void;
}
/**
* A pill above an agent's composer, mounted for visible agent tabs on the plugin's host.
* Render `ComposerPill` from `@getpaseo/plugin/client/ui`, or `null` when there is nothing to show.
*/
export interface PluginComposerPillItemContribution<Text extends PluginText = string> {
id: string;
/** Default accessible label and compact sheet title for ComposerPill. */
title: Text;
Component: ComponentType<PluginComposerPillItemProps>;
}
export interface PluginSidebarItemProps extends PluginHostProps {
/** This plugin's screen open on this item's host, with its params, else null. */
currentScreen: PluginScreenLocation | null;
@@ -180,22 +200,51 @@ interface PluginWorkspacePanelBase<Text extends PluginText = string> {
locations?: readonly PluginPanelLocation[];
}
/**
* Per-tab handle passed to every panel component.
*
* `tab.state` is strictly panel-owned, opaque persisted JSON (unlike `params`, which are sent by
* whoever opens or retargets the tab). `tab.state` is never passed to `workspaceLayout.open(...)`
* and is preserved across in-place `params` updates, `revision` bumps, and app reloads.
*/
export interface PluginTab {
/** This tab in its workspace's layout, as `useWorkspaceLayout` reads and arranges it. */
readonly id: string;
/** Shows the tab's unsaved dot and asks before closing. */
setModified(modified: boolean): void;
/** Opaque persisted JSON. Undefined until written; the panel validates it. */
/** Overrides this tab's title while mounted. Pass null or empty string to reset to the static panel title. */
setTitle(title: string | null): void;
/**
* Panel-owned persisted JSON state for this tab instance.
* Undefined until the panel calls `setState`; validate it with `useTabState`.
*/
readonly state: unknown;
/** Replaces this tab's persisted UI state. Callers of `workspaceLayout.open` cannot set it. */
setState(state: JsonValue): void;
}
/**
* Props delivered to every workspace, agent, and file panel component.
*
* - **`params`**: caller-sent, read-only inputs and retargeting hints validated by the panel's
* schema (with host-enforced `agentId` on agent panels).
* - **`revision`**: increments every time `workspaceLayout.open` delivers or re-sends `params` to
* this tab (via `"reveal"` or `"background"`), even when `params` values did not change.
* - **`tab`**: handle for panel-owned persisted UI state (`tab.state` / `tab.setState`), dirty
* status (`tab.setModified`), and layout tab ID (`tab.id`).
*/
export interface PluginPanelProps<Params> extends PluginNavigableHostProps {
workspaceId: string;
/** Caller-sent, read-only inputs and retargeting hints for what this tab should show. */
readonly params: Readonly<Params>;
/** Increments on each `workspaceLayout.open` targeting this tab so repeated hints are observable. */
revision: number;
/** Per-tab handle for panel-owned persisted UI state and unsaved-work status. */
tab: PluginTab;
openScreen(input: PluginOpenScreenInput): void;
}
/** Zod schema accepted by `addWorkspacePanel` and `addAgentPanel` for flat primitive `params`. */
export type PluginPanelParamsSchema = ZodType<PluginPanelTargetParams>;
export interface PluginWorkspacePanelParams {}
export interface PluginAgentPanelParams {
readonly agentId: string;
@@ -205,12 +254,16 @@ export interface PluginFilePanelParams {
readonly lineStart?: number;
readonly lineEnd?: number;
}
export interface PluginWorkspacePanelProps extends PluginPanelProps<PluginWorkspacePanelParams> {
export interface PluginWorkspacePanelProps<
Params = PluginWorkspacePanelParams,
> extends PluginPanelProps<Params> {
// COMPAT(pluginPanelFlatProps): added in v0.13.0, remove after 2027-04-23
/** @deprecated Use the panel registration to select the context. */
context: "workspace";
}
export interface PluginAgentPanelProps extends PluginPanelProps<PluginAgentPanelParams> {
export interface PluginAgentPanelProps<
Params = PluginWorkspacePanelParams,
> extends PluginPanelProps<PluginAgentPanelParams & Params> {
// COMPAT(pluginPanelFlatProps): added in v0.13.0, remove after 2027-04-23
/** @deprecated Use the panel registration to select the context. */
context: "agent";
@@ -253,10 +306,40 @@ export interface PluginClientContext extends PluginCommandCapabilities, PluginCl
addSidebarView(contribution: PluginSidebarViewContribution<PluginText>): PluginCleanup;
addSidebarHeaderItem(contribution: PluginSidebarItemContribution<PluginText>): PluginCleanup;
addSidebarFooterItem(contribution: PluginSidebarItemContribution<PluginText>): PluginCleanup;
/**
* Registers an agent-scoped workspace panel.
*
* - **`params`**: optional Zod schema for extra flat `string | number | undefined` fields
* alongside required, host-enforced `agentId: string`. When omitted, `params` is `{ agentId }`.
* - **`identity(params)`**: optional tab-coalescing key over `{ agentId, ...extra }`. Omit to
* keep one tab per `agentId`; return a key so tabs with different keys open separately while
* same-key opens update `params` in place, bump `revision`, and preserve `tab.state`.
*/
addAgentPanel<Schema extends PluginPanelParamsSchema>(
contribution: PluginAgentPanelContribution<PluginText, Schema>,
): PluginCleanup;
/**
* Registers an agent-scoped workspace panel receiving `{ agentId }` in `params`.
*/
addAgentPanel(contribution: PluginAgentPanelContribution<PluginText>): PluginCleanup;
addWorkspaceRowBadgeItem(
contribution: PluginWorkspaceRowBadgeItemContribution<PluginText>,
): PluginCleanup;
/**
* Registers a workspace-scoped panel.
*
* - **`params`**: optional Zod schema for caller-sent, read-only flat `string | number | undefined`
* inputs/hints. Panels whose schema rejects `{}` are omitted from parameterless UI tab launchers.
* - **`identity(params)`**: optional tab-coalescing key. Omit to keep one tab per workspace;
* provide a key so tabs with different keys open separately while same-key opens update
* `params` in place, bump `revision`, and preserve `tab.state`.
*/
addWorkspacePanel<Schema extends PluginPanelParamsSchema>(
contribution: PluginWorkspacePanelContribution<PluginText, Schema>,
): PluginCleanup;
/**
* Registers a workspace-scoped panel receiving `{}` in `params`.
*/
addWorkspacePanel(contribution: PluginWorkspacePanelContribution<PluginText>): PluginCleanup;
addCommandCenterItem(
contribution: PluginCommandCenterItemContribution<PluginText>,
@@ -268,6 +351,7 @@ export interface PluginClientContext extends PluginCommandCapabilities, PluginCl
addComposerPill(
contribution: PluginComposerPillContribution<PluginText>,
): PluginButtonRegistration<PluginText>;
addComposerPillItem(contribution: PluginComposerPillItemContribution<PluginText>): PluginCleanup;
addAttachmentSource(contribution: PluginAttachmentSourceContribution<PluginText>): PluginCleanup;
addComposerItem(contribution: PluginComposerItemContribution): PluginCleanup;
addNewWorkspaceItem(contribution: PluginNewWorkspaceItemContribution): PluginCleanup;
@@ -305,25 +389,74 @@ export interface PluginClientContext extends PluginCommandCapabilities, PluginCl
export type PluginClientContribution = (client: PluginClientContext) => PluginCleanup;
export type PluginWorkspacePanelContribution<Text extends PluginText = string> =
| (PluginWorkspacePanelBase<Text> & {
export type PluginWorkspacePanelContribution<
Text extends PluginText = string,
Schema extends PluginPanelParamsSchema | undefined = undefined,
> = [Schema] extends [PluginPanelParamsSchema]
? PluginWorkspacePanelBase<Text> & {
// COMPAT(pluginPanelFlatProps): added in v0.13.0, remove after 2027-04-23
/** @deprecated Omit context. */
context?: "workspace";
Component: ComponentType<PluginWorkspacePanelProps>;
})
| (PluginWorkspacePanelBase<Text> & {
// COMPAT(pluginAgentPanelAlias): added in v0.13.0, remove after 2027-04-23
/** @deprecated Register with `addAgentPanel`. */
context: "agent";
Component: ComponentType<PluginAgentPanelProps>;
});
/**
* Zod schema validating caller-sent `params` (`Record<string, string | number | undefined>`).
* Panels that reject `{}` are not offered in parameterless UI tab launchers.
*/
params: Schema;
/**
* Maps validated `params` to a tab-coalescing key. Omit to keep one tab per workspace; any
* param excluded from the key acts as a retargeting hint that updates `params` and bumps
* `revision` in place while preserving `tab.state`.
*/
identity?: (params: Readonly<ZodOutput<Schema>>) => string;
Component: ComponentType<PluginWorkspacePanelProps<ZodOutput<Schema>>>;
}
:
| (PluginWorkspacePanelBase<Text> & {
// COMPAT(pluginPanelFlatProps): added in v0.13.0, remove after 2027-04-23
/** @deprecated Omit context. */
context?: "workspace";
params?: undefined;
/**
* Maps `params` (`{}`) to a tab-coalescing key. Omit to keep one tab per workspace.
*/
identity?: (params: Readonly<PluginWorkspacePanelParams>) => string;
Component: ComponentType<PluginWorkspacePanelProps>;
})
| (PluginWorkspacePanelBase<Text> & {
// COMPAT(pluginAgentPanelAlias): added in v0.13.0, remove after 2027-04-23
/** @deprecated Register with `addAgentPanel`. */
context: "agent";
params?: undefined;
identity?: undefined;
Component: ComponentType<PluginAgentPanelProps>;
});
export interface PluginAgentPanelContribution<
export type PluginAgentPanelContribution<
Text extends PluginText = string,
> extends PluginWorkspacePanelBase<Text> {
Component: ComponentType<PluginAgentPanelProps>;
}
Schema extends PluginPanelParamsSchema | undefined = undefined,
> = [Schema] extends [PluginPanelParamsSchema]
? PluginWorkspacePanelBase<Text> & {
/**
* Zod schema for extra caller-sent `params` (`Record<string, string | number | undefined>`)
* alongside host-enforced `agentId: string`.
*/
params: Schema;
/**
* Maps validated `params` (including `agentId`) to a tab-coalescing key. Omit to keep one
* tab per `agentId`; any param excluded from the key acts as a retargeting hint that updates
* `params` and bumps `revision` in place while preserving `tab.state`.
*/
identity?: (params: Readonly<PluginAgentPanelParams & ZodOutput<Schema>>) => string;
Component: ComponentType<PluginAgentPanelProps<ZodOutput<Schema>>>;
}
: PluginWorkspacePanelBase<Text> & {
params?: undefined;
/**
* Maps `params` (`{ agentId }`) to a tab-coalescing key. Omit to keep one tab per `agentId`.
*/
identity?: (params: Readonly<PluginAgentPanelParams>) => string;
Component: ComponentType<PluginAgentPanelProps>;
};
export interface PluginSettingsScreenContribution<Text extends PluginText = string> {
id: string;
+3
View File
@@ -3,6 +3,7 @@ export type {
PluginHostNavigationActions,
PluginTab,
PluginPanelProps,
PluginPanelParamsSchema,
PluginWorkspacePanelParams,
PluginAgentPanelParams,
PluginFilePanelParams,
@@ -19,6 +20,8 @@ export type {
PluginSidebarViewProps,
PluginSidebarViewContribution,
PluginSidebarItemContribution,
PluginComposerPillItemProps,
PluginComposerPillItemContribution,
PluginWorkspaceRowBadgeItemProps,
PluginWorkspaceRowBadgeItemContribution,
PluginIcon,
+12
View File
@@ -189,6 +189,18 @@ export interface WorkspaceRowBadgeProps {
/** One item on a sidebar workspace row's meta line. Render it from a workspace row badge item's `Component`. */
export declare const WorkspaceRowBadge: ComponentType<WorkspaceRowBadgeProps>;
export interface ComposerPillProps {
/** A Lucide icon name, inline SVG, or a component. */
icon: PluginIcon;
label: string;
/** Accessible label and tooltip. Defaults to `label`. */
title?: string;
disabled?: boolean;
onPress(): void | Promise<void>;
}
/** A pill above an agent's composer. Render it from a composer pill item's `Component`. */
export declare const ComposerPill: ComponentType<ComposerPillProps>;
/** Paseo's loading state. Fills the panel; the panel decides when to show it. */
export declare const Loading: ComponentType;
@@ -15,12 +15,13 @@ export interface PluginWorkspaceLayout {
readonly workspaceId: string;
/**
* Opens a registered panel. With the default intent, `reveal`, an open tab of the same panel and
* identity is focused where it is and gets the params again with a new `revision`; `placement`
* decides where a tab that is not open yet goes.
* Opens a registered panel. With `intent: "reveal"` (default) or `"background"`, an open tab with
* the same panel and `identity` key is reused: its `params` are updated in place and its
* `revision` is incremented while preserving `tab.state`. `placement` decides where a new tab goes.
*
* Throws for a panel that is not registered, params the panel rejects, a placement the panel does
* not allow, or a pane that does not exist.
* Throws for a panel that is not registered, `params` that fail the panel's schema or are not a
* flat record of `string | number | undefined` values, a placement the panel does not allow, or a
* pane that does not exist.
*/
open(target: PluginPanelTarget, options?: PluginOpenTabOptions): PluginTabLocation;
/** Does nothing when no tab has this id. */
@@ -87,7 +88,7 @@ export interface PluginLayoutTab {
readonly paneId: string | null;
/** Always qualified: `paseo/file`, `my-plugin/review`. */
readonly panelId: string;
/** The params that identify what the tab shows. */
/** Read-only caller-supplied params and hints stored on this tab (undefined fields omitted). */
readonly params: PluginPanelTargetParams;
/** Where this tab's panel may live, from its registration. */
readonly locations: readonly PluginPanelLocation[];
@@ -112,7 +113,11 @@ export interface PluginPanelTarget {
params?: PluginPanelTargetParams;
}
export type PluginPanelTargetParams = Readonly<Record<string, string | number>>;
/**
* Flat, primitive caller-supplied params for opening a panel.
* Values must be `string`, finite `number`, or `undefined` so tab targets persist cleanly.
*/
export type PluginPanelTargetParams = Readonly<Record<string, string | number | undefined>>;
/**
* Where a tab goes. On phones and touch tablets, which have no splits, `pane`, `beside` and `split`
+4 -3
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 PluginButtonMenuEntry } from "@getpaseo/plugin/client";
import { defineTranslations, type PluginText, type PluginFilePanelContribution, type PluginClientContext, type PluginScreenContribution, type PluginWorkspacePanelContribution, type PluginSettingsScreenContribution, type PluginSidebarItemContribution, type PluginSidebarContribution, type PluginCommandCenterItemContribution, type PluginClientSlashCommandContribution, type PluginButton, type PluginHeaderButtonContribution, type PluginComposerPillContribution, type PluginComposerPillItemContribution, type PluginButtonMenuEntry } from "@getpaseo/plugin/client";
import { z } from "zod";
import { defineAttachmentSource, type PluginThemeContribution, type PluginAttachmentSourceContribution } from "@getpaseo/plugin";
const messages = defineTranslations({ resources: { en: { title: "Notes" } } });
@@ -130,10 +130,10 @@ it("keeps historical string descriptor helpers while accepting translated regist
function historicalScreen(screen: PluginScreenContribution) {
return typeof screen.title === "function" ? screen.title({}).trim() : screen.title.trim();
}
function historicalLabels(filePanel: PluginFilePanelContribution, panel: PluginWorkspacePanelContribution, settings: PluginSettingsScreenContribution, sidebar: PluginSidebarItemContribution, legacy: PluginSidebarContribution, command: PluginCommandCenterItemContribution, slash: PluginClientSlashCommandContribution, button: PluginButton, header: PluginHeaderButtonContribution, pill: PluginComposerPillContribution, menu: PluginButtonMenuEntry, theme: PluginThemeContribution, source: PluginAttachmentSourceContribution) {
function historicalLabels(filePanel: PluginFilePanelContribution, panel: PluginWorkspacePanelContribution, settings: PluginSettingsScreenContribution, sidebar: PluginSidebarItemContribution, legacy: PluginSidebarContribution, command: PluginCommandCenterItemContribution, slash: PluginClientSlashCommandContribution, button: PluginButton, header: PluginHeaderButtonContribution, pill: PluginComposerPillContribution, pillItem: PluginComposerPillItemContribution, menu: PluginButtonMenuEntry, theme: PluginThemeContribution, source: PluginAttachmentSourceContribution) {
filePanel.title.trim(); panel.title.trim(); settings.title.trim(); sidebar.title.trim(); legacy.title.trim(); command.title.trim();
slash.description.trim(); slash.argumentHint.trim(); button.title.trim(); button.label?.trim();
header.button.title.trim(); pill.button.title.trim(); if (menu.kind === "item") menu.title.trim();
header.button.title.trim(); pill.button.title.trim(); pillItem.title.trim(); if (menu.kind === "item") menu.title.trim();
theme.name.trim(); source.title.trim(); source.pickerTitle.trim(); source.searchPlaceholder.trim();
}
function contribute(client: PluginClientContext) {
@@ -145,6 +145,7 @@ it("keeps historical string descriptor helpers while accepting translated regist
const translated: PluginScreenContribution<PluginText> = { id: "typed", title: messages.message("title"), Component };
client.addScreen(translated);
client.addSidebarHeaderItem({ id: "notes", title: messages.message("title"), Component });
client.addComposerPillItem({ id: "notes", title: messages.message("title"), Component });
client.addFilePanel({ id: "notes", title: messages.message("title"), icon: "File", files: { extensions: ["notes"] }, Component });
client.addSettingsScreen({ id: "notes", title: messages.message("title"), icon: "File", Component });
client.addWorkspacePanel({ id: "notes", title: messages.message("title"), icon: "File", context: "workspace", Component });
@@ -2393,6 +2393,50 @@ async function createControlledInterruptFixture(options: {
};
}
test("a recorded submitted prompt persists and publishes its time while the turn runs", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-submitted-prompt-time-"));
const session = new ControlledInterruptSession(
{ provider: "codex", cwd: workdir },
"turn-submitted-prompt-time",
async () => undefined,
);
const client = new (class extends TestAgentClient {
override async createSession(): Promise<AgentSession> {
return session;
}
})();
const storage = new AgentStorage(join(workdir, "agents"), logger);
const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger });
const states: ManagedAgent[] = [];
manager.subscribe(
(event) => {
if (event.type === "agent_state") states.push(event.agent);
},
{ replayState: false },
);
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
workspaceId: undefined,
});
try {
const run = manager.streamAgent(agent.id, "keep working", {
clientMessageId: "submitted-prompt",
});
void drainAsyncGenerator(run).catch(() => undefined);
await manager.waitForAgentRunStart(agent.id);
await manager.flush();
const live = manager.getAgent(agent.id);
expect(live?.lifecycle).toBe("running");
const recordedAt = live?.lastUserMessageAt;
expect(recordedAt).toBeInstanceOf(Date);
expect((await storage.get(agent.id))?.lastUserMessageAt).toBe(recordedAt?.toISOString());
expect(states.at(-1)?.lastUserMessageAt).toEqual(recordedAt);
} finally {
await manager.closeAgent(agent.id);
rmSync(workdir, { recursive: true, force: true });
}
});
class HeldRuntimeInfoSession extends TestAgentSession {
private readonly runtimeInfoRequested = deferred<void>();
private readonly runtimeInfoAllowed = deferred<void>();
@@ -503,13 +503,16 @@ export interface ManagedImportableSessionsResult {
providerErrors: ImportableSessionProviderError[];
}
export type AgentAttentionCallback = (params: {
export interface AgentAttentionEvent {
agentId: string;
provider: AgentProvider;
reason: "finished" | "error" | "permission";
finishedTurnId?: string;
/** When the agent's current unread attention started; null when the agent is read. */
attentionTimestamp: Date | null;
}) => void;
}
export type AgentAttentionCallback = (event: AgentAttentionEvent) => void;
export type AgentArchivedCallback = (agentId: string) => Promise<void> | void;
@@ -5118,7 +5121,7 @@ export class AgentManager {
);
if (!shouldHoldBusyForReplacement) {
this.touchUpdatedAt(mutableAgent);
this.emitState(mutableAgent);
this.emitState(mutableAgent, { finishedTurnId: turnId });
}
}
@@ -5957,12 +5960,12 @@ export class AgentManager {
});
}
async getLastAssistantMessage(agentId: string): Promise<string | null> {
async getLastAssistantMessage(agentId: string, turnId?: string): Promise<string | null> {
const scope: TimelineScope = { agentId };
if (!(await this.timeline.describe(scope))) {
return null;
}
return await this.timeline.lastAssistantMessage(scope);
return await this.timeline.lastAssistantMessage(scope, turnId);
}
private getLastAssistantMessageFromTimeline(
@@ -7025,20 +7028,18 @@ export class AgentManager {
flags,
});
if (!options?.fromHistory) {
if (isTurnTerminalEvent(event)) {
this.runs.settleTerminalRun(agent.id, eventTurnId);
if (isForegroundEvent) {
this.finalizeForegroundTurn(agent, eventTurnId);
} else if (terminalDisposition !== "stale" && !agent.activeForegroundTurnId) {
// Publish autonomous readiness only after the tracked run has settled.
this.emitState(agent);
}
}
if (flags.shouldDispatchEvent) {
this.dispatchStream(agent.id, event, { timestamp: new Date().toISOString() });
}
if (isTurnTerminalEvent(event)) {
this.finalizeStreamTurn({
agent,
event,
options,
isForegroundEvent,
eventTurnId,
terminalDisposition,
});
}
if (!options?.fromHistory && flags.shouldDispatchEvent) {
this.dispatchStream(agent.id, event, { timestamp: new Date().toISOString() });
}
this.traceHandleStreamEventEnd(agent, event, eventTurnId, flags);
@@ -7046,6 +7047,31 @@ export class AgentManager {
return flags.shouldNotifyWaiters;
}
private finalizeStreamTurn(params: Omit<StreamEventDispatch, "flags">): void {
const { agent, event, options, isForegroundEvent, eventTurnId, terminalDisposition } = params;
// Keep the idle transition next to its state emission. A runtime refresh during the
// timeline write must not publish the finish before we can supply its turn ID.
if (
event.type === "turn_completed" &&
terminalDisposition !== "stale" &&
!isForegroundEvent &&
!agent.activeForegroundTurnId &&
agent.lifecycle !== "idle" &&
!agent.pendingReplacement
) {
(agent as ActiveManagedAgent).lifecycle = agent.historySaveError ? "error" : "idle";
}
if (options?.fromHistory) return;
this.runs.settleTerminalRun(agent.id, eventTurnId);
if (isForegroundEvent) {
this.finalizeForegroundTurn(agent, eventTurnId);
} else if (terminalDisposition !== "stale" && !agent.activeForegroundTurnId) {
// Publish autonomous readiness only after the tracked run has settled.
this.emitState(agent, { finishedTurnId: eventTurnId });
}
}
private traceHandleStreamEventStart(
agent: ActiveManagedAgent,
event: AgentStreamEvent,
@@ -7137,8 +7163,8 @@ export class AgentManager {
/**
* Applies the event by type, then stamps a completed turn's metrics, returning the event as
* stamped. Handlers change the agent's state before they write, so a terminal event whose
* record fails to write still ends the turn; the failure is logged.
* stamped. A live terminal event still ends the turn when its record fails to write.
* In that case, the failure is logged.
*/
private async recordStreamEvent(params: StreamEventDispatch): Promise<AgentStreamEvent> {
const { agent, options, eventTurnId, terminalDisposition } = params;
@@ -7211,7 +7237,6 @@ export class AgentManager {
agent,
event,
eventTurnId,
isForegroundEvent,
terminalDisposition,
});
return undefined;
@@ -7287,10 +7312,6 @@ export class AgentManager {
}
await this.recordAndDispatchTimelineItem(agent.id, item, event.provider, event.turnId);
if (item.type === "user_message") {
agent.lastUserMessageAt = new Date();
this.emitState(agent);
}
flags.shouldNotifyWaiters = true;
}
}
@@ -7303,10 +7324,9 @@ export class AgentManager {
agent: ActiveManagedAgent;
event: Extract<AgentStreamEvent, { type: "turn_completed" }>;
eventTurnId: string | undefined;
isForegroundEvent: boolean;
terminalDisposition: ActiveTurnTerminalDisposition;
}): void {
const { agent, event, eventTurnId, isForegroundEvent, terminalDisposition } = params;
const { agent, event, eventTurnId, terminalDisposition } = params;
this.logger.trace(
{
agentId: agent.id,
@@ -7326,14 +7346,6 @@ export class AgentManager {
// data accumulated during streaming isn't lost when the provider omits
// it from the completion event.
agent.lastError = agent.historySaveError;
if (
!isForegroundEvent &&
!agent.activeForegroundTurnId &&
agent.lifecycle !== "idle" &&
!agent.pendingReplacement
) {
(agent as ActiveManagedAgent).lifecycle = agent.historySaveError ? "error" : "idle";
}
void this.refreshRuntimeInfo(agent);
}
@@ -7590,6 +7602,13 @@ export class AgentManager {
options?.onRecorded?.();
this.publishTimelineEvent(agentId, event, commit);
if (options?.notifyWaiters) this.notifyForegroundTurnWaiters(agentId, event);
if (item.type === "user_message") {
const agent = this.agents.get(agentId);
if (agent) {
agent.lastUserMessageAt = new Date();
this.emitState(agent);
}
}
if (
item.type === "tool_call" &&
item.status === "completed" &&
@@ -7754,7 +7773,6 @@ export class AgentManager {
...(options?.rejected ? { rejected: true } : {}),
onRecorded: () => {
this.touchUpdatedAt(agent);
if (item.type === "user_message") agent.lastUserMessageAt = new Date();
},
});
}
@@ -7837,9 +7855,12 @@ export class AgentManager {
return parts.join("\n\n");
}
private emitState(agent: ManagedAgent, options?: { persist?: boolean }): void {
private emitState(
agent: ManagedAgent,
options?: { persist?: boolean; finishedTurnId?: string },
): void {
// Keep attention as an edge-triggered unread signal, not a level signal.
this.checkAndSetAttention(agent);
this.checkAndSetAttention(agent, options?.finishedTurnId);
if (options?.persist !== false) {
this.enqueueBackgroundPersist(agent);
}
@@ -7872,7 +7893,7 @@ export class AgentManager {
}
}
private checkAndSetAttention(agent: ManagedAgent): void {
private checkAndSetAttention(agent: ManagedAgent, finishedTurnId?: string): void {
const previousStatus = this.previousStatuses.get(agent.id);
const currentStatus = agent.lifecycle;
@@ -7892,7 +7913,7 @@ export class AgentManager {
if (agent.attention.requiresAttention) {
// The unread finish stays the same; the notifier knows whether the user was told about it.
if (finished && agent.attention.attentionReason === "finished") {
this.broadcastAgentAttention(agent, "finished");
this.broadcastAgentAttention(agent, "finished", finishedTurnId);
}
return;
}
@@ -7903,7 +7924,7 @@ export class AgentManager {
attentionReason: "finished",
attentionTimestamp: new Date(),
};
this.broadcastAgentAttention(agent, "finished");
this.broadcastAgentAttention(agent, "finished", finishedTurnId);
}
}
@@ -7985,6 +8006,7 @@ export class AgentManager {
private broadcastAgentAttention(
agent: ManagedAgent,
reason: "finished" | "error" | "permission",
finishedTurnId?: string,
): void {
if (isDelegatedAgent(agent)) {
return;
@@ -7994,6 +8016,7 @@ export class AgentManager {
agentId: agent.id,
provider: agent.provider,
reason,
...(finishedTurnId === undefined ? {} : { finishedTurnId }),
attentionTimestamp: agent.attention.requiresAttention
? agent.attention.attentionTimestamp
: null,
@@ -14,9 +14,18 @@ export function continuesAssistantMessage(previous: MessageRow, next: MessageRow
);
}
export function lastAssistantMessageText(rows: readonly MessageRow[]): string | null {
export function lastAssistantMessageText(
rows: readonly MessageRow[],
turnId?: string,
): string | null {
function* newestFirst() {
for (let index = rows.length - 1; index >= 0; index--) yield rows[index];
const start =
turnId === undefined
? rows.length - 1
: rows.findLastIndex(
(row) => row.turnId === turnId && row.item.type === "assistant_message",
);
for (let index = start; index >= 0; index--) yield rows[index];
}
return readLastAssistantMessage(newestFirst());
}
@@ -813,8 +813,8 @@ export class TimelineProjection {
return last?.endSeq === seq && last.rowIndex >= 0 ? this.rows[last.rowIndex].item : null;
}
getLastAssistantMessage(): string | null {
return lastAssistantMessageText(this.rows);
getLastAssistantMessage(turnId?: string): string | null {
return lastAssistantMessageText(this.rows, turnId);
}
enrichSubmittedUserMessage(
@@ -212,6 +212,21 @@ describe.each(
expect(await timeline.lastAssistantMessage(root("a"))).toBe("Bye");
});
it("reads assistant text only from the requested turn", async () => {
const timeline = createTimeline();
const scope = root("a");
await timeline.create(scope);
await timeline.append(scope, [
{ turnId: "first", item: { type: "assistant_message", text: "Earlier reply" } },
{ turnId: "silent", item: { type: "user_message", text: "Run without replying" } },
{ turnId: "latest", item: { type: "assistant_message", text: "New reply" } },
]);
expect(await timeline.lastAssistantMessage(scope, "first")).toBe("Earlier reply");
expect(await timeline.lastAssistantMessage(scope, "silent")).toBeNull();
expect(await timeline.lastAssistantMessage(scope, "latest")).toBe("New reply");
});
it.each([
{
scenario: "the same reply",
@@ -450,8 +450,8 @@ export class AgentTimeline {
* The newest assistant reply, with its streamed chunks joined in order. Notifications within
* an identified reply can sit between its chunks. Null when there is no assistant message.
*/
lastAssistantMessage(scope: TimelineScope): Promise<string | null> {
return this.run(scope, () => this.backendFor(scope).lastAssistantMessage(scope));
lastAssistantMessage(scope: TimelineScope, turnId?: string): Promise<string | null> {
return this.run(scope, () => this.backendFor(scope).lastAssistantMessage(scope, turnId));
}
/**
@@ -214,7 +214,7 @@ export interface AgentTimelineBackend {
readRows(scope: TimelineScope): MaybePromise<ProjectedTimelineRow[]>;
lastItem(scope: TimelineScope): MaybePromise<AgentTimelineItem | null>;
/** The trailing run of assistant messages joined, skipping later non-assistant rows. */
lastAssistantMessage(scope: TimelineScope): MaybePromise<string | null>;
lastAssistantMessage(scope: TimelineScope, turnId?: string): MaybePromise<string | null>;
}
/** The scope has no history: it was never created, or it was deleted. */

Some files were not shown because too many files have changed in this diff Show More