Compare commits

...
18 Commits
Author SHA1 Message Date
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
110 changed files with 4941 additions and 1253 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
@@ -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 });
}
});
@@ -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],
);
}
@@ -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");
});
});
@@ -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: [
{
@@ -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",
},
}));
+42 -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",
@@ -798,10 +838,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; });
+20
View File
@@ -39,6 +39,7 @@ import type {
PluginSidebarItemContribution,
PluginWorkspacePanelContribution,
PluginWorkspaceRowBadgeItemContribution,
PluginComposerPillItemContribution,
} from "./types";
import type { ComponentType } from "react";
import { parsePluginIcon, parseSerializablePluginIcon } from "./icons";
@@ -164,6 +165,7 @@ export function runPluginClientBundle(
workspaceRowBadgeItems: [],
filePanels: [],
composerItems: [],
composerPillItems: [],
newWorkspaceItems: [],
workspacePanels: [],
commandCenterItems: [],
@@ -184,6 +186,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>();
@@ -322,6 +325,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))
@@ -690,6 +709,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;
+62 -4
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,9 +84,7 @@ 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) {
if (!workspaceId) throw new Error("No active workspace");
@@ -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: [],
+4
View File
@@ -14,6 +14,7 @@ import type {
PluginComposerItemContribution,
PluginNewWorkspaceItemContribution,
PluginComposerPillContribution as SDKPluginComposerPillContribution,
PluginComposerPillItemContribution as SDKPluginComposerPillItemContribution,
PluginSidebarContribution as SDKPluginSidebarContribution,
PluginSidebarViewContribution,
PluginSidebarItemContribution as SDKPluginSidebarItemContribution,
@@ -33,6 +34,7 @@ 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 =
@@ -63,6 +65,7 @@ export interface EvaluatedPlugin {
workspaceRowBadgeItems: PluginWorkspaceRowBadgeItemContribution[];
filePanels: PluginFilePanelContribution[];
composerItems: PluginComposerItemContribution[];
composerPillItems: PluginComposerPillItemContribution[];
newWorkspaceItems: PluginNewWorkspaceItemContribution[];
workspacePanels: EvaluatedPluginWorkspacePanelContribution[];
commandCenterItems: PluginCommandCenterItemContribution[];
@@ -99,6 +102,7 @@ export type {
PluginComposerItemContribution,
PluginNewWorkspaceItemContribution,
PluginComposerPillContribution,
PluginComposerPillItemContribution,
PluginSidebarContribution,
PluginSidebarItemContribution,
PluginWorkspaceRowBadgeItemContribution,
@@ -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);
@@ -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),
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,
};
}
@@ -1,12 +1,12 @@
import { usePublishPanelInstanceAttributes } from "@/panels/panel-instance-attributes";
import { getComponentMountKey, usePanelTab } from "@/panels/panel-instance-attributes";
import type {
PluginAgentPanelProps,
PluginHostProps,
PluginWorkspacePanelProps,
PluginTab,
} from "@getpaseo/plugin/client";
import type { PluginTheme } from "@getpaseo/plugin";
import { CircleAlert } from "lucide-react-native";
import { useMemo, 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,12 +18,15 @@ import { useSessionStore } from "@/stores/session-store";
import { useWorkspaceExists } from "@/stores/session-store-hooks";
import type { Theme } from "@/styles/theme";
import { normalizeWorkspaceOpaqueId } from "@/utils/workspace-identity";
import type { PluginWorkspaceTabTarget } from "@/workspace-tabs/model";
import { usePluginHostNavigation } from "../host-navigation";
import { usePluginOpenScreen } from "../navigation";
import { toPluginTheme } from "../theme";
import { pluginIconComponent } from "../icons";
import { useInstalledPlugin } from "../registry";
import { PluginInstallationProvider } from "../installation-provider";
import { SurfaceErrorBoundary } from "../surface-error-boundary";
import type { EvaluatedPluginWorkspacePanelContribution } from "../types";
import { resolvePluginWorkspacePanel } from "./resolution";
import { resolvePluginPlatform } from "../platform";
@@ -31,22 +34,72 @@ const pluginThemeMapping = (theme: Theme) => ({
theme: toPluginTheme(theme),
});
function PluginPanelBody({ theme }: { theme: PluginTheme }) {
const {
serverId,
const EMPTY_WORKSPACE_PARAMS = {} as const;
function MountedPluginPanel({
contribution,
target,
theme,
host,
layout,
navigation,
openScreen,
workspaceId,
revision,
}: {
contribution: EvaluatedPluginWorkspacePanelContribution;
target: PluginWorkspaceTabTarget;
theme: PluginTheme;
host: PluginHostProps["host"];
layout: PluginHostProps["layout"];
navigation: PluginWorkspacePanelProps["navigation"];
openScreen: PluginWorkspacePanelProps["openScreen"];
workspaceId: string;
revision: number;
}) {
const tab = usePanelTab();
const agentId = target.context === "agent" ? target.agentId : null;
const agentParams = useMemo(() => (agentId ? { agentId } : null), [agentId]);
if (contribution.context === "workspace") {
const props: PluginWorkspacePanelProps = {
// COMPAT(pluginPanelFlatProps): added in v0.13.0, remove after 2027-04-23
context: "workspace",
params: EMPTY_WORKSPACE_PARAMS,
revision,
tab,
theme,
host,
layout,
navigation,
openScreen,
workspaceId,
};
const Component = contribution.Component;
return <Component {...props} />;
}
invariant(agentParams && agentId, "PluginAgentPanel requires agent target");
const props: PluginAgentPanelProps = {
// COMPAT(pluginPanelFlatProps): added in v0.13.0, remove after 2027-04-23
context: "agent",
params: agentParams,
revision,
tab,
theme,
host,
layout,
navigation,
openScreen,
workspaceId,
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],
);
// COMPAT(pluginPanelFlatProps): added in v0.13.0, remove after 2027-04-23
agentId,
};
const Component = contribution.Component;
return <Component {...props} />;
}
function PluginPanelBody({ theme }: { theme: PluginTheme }) {
const { serverId, workspaceId, target, panelRevision } = usePaneContext();
invariant(target.kind === "plugin", "PluginPanel requires plugin target");
const plugin = useInstalledPlugin(serverId, target.pluginId);
const contribution = resolvePluginWorkspacePanel(plugin, target);
@@ -67,6 +120,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 +128,30 @@ 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 || target.context !== "agent")) {
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}>
<MountedPluginPanel
key={getComponentMountKey(contribution.Component)}
contribution={contribution}
target={target}
theme={theme}
host={host}
layout={layout}
navigation={navigation}
openScreen={openScreen}
workspaceId={workspaceId}
revision={panelRevision ?? 0}
/>
</PluginInstallationProvider>
</SurfaceErrorBoundary>
);
}
@@ -27,6 +27,7 @@ function installed(): InstalledPlugin {
workspaceRowBadgeItems: [],
filePanels: [],
composerItems: [],
composerPillItems: [],
newWorkspaceItems: [],
workspacePanels: [
{
@@ -1,5 +1,5 @@
import { workspaceTabSwitcherPopoverLayout } from "../workspace-tab-layout";
import { memo, useCallback, useMemo, useRef, useState } 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,
@@ -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();
+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);
}
+89 -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 });
@@ -1096,3 +1124,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([]);
});
});
+24
View File
@@ -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;
@@ -185,6 +205,8 @@ export interface PluginTab {
readonly id: string;
/** Shows the tab's unsaved dot and asks before closing. */
setModified(modified: boolean): void;
/** Overrides this tab's title while mounted. Pass null or empty string to reset to the static panel title. */
setTitle(title: string | null): void;
/** Opaque persisted JSON. Undefined until written; the panel validates it. */
readonly state: unknown;
setState(state: JsonValue): void;
@@ -195,6 +217,7 @@ export interface PluginPanelProps<Params> extends PluginNavigableHostProps {
readonly params: Readonly<Params>;
revision: number;
tab: PluginTab;
openScreen(input: PluginOpenScreenInput): void;
}
export interface PluginWorkspacePanelParams {}
export interface PluginAgentPanelParams {
@@ -268,6 +291,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;
+2
View File
@@ -19,6 +19,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;
+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. */
@@ -273,8 +273,8 @@ export class MemoryTimelineBackend implements AgentTimelineBackend {
return state.projection.getLastItem(state.nextSeq - 1);
}
lastAssistantMessage(scope: TimelineScope): string | null {
return this.requireState(scope).projection.getLastAssistantMessage();
lastAssistantMessage(scope: TimelineScope, turnId?: string): string | null {
return this.requireState(scope).projection.getLastAssistantMessage(turnId);
}
private describe(state: MemoryTimelineState): TimelineHead {
@@ -494,13 +494,15 @@ export class SqliteTimelineBackend implements AgentTimelineBackend {
});
}
lastAssistantMessage(scope: TimelineScope): string | null {
lastAssistantMessage(scope: TimelineScope, turnId?: string): string | null {
return this.database.read((sql) => {
const { id } = requireScope(sql, scope);
const last = sql.get<{ seq_start: number }>(
`SELECT seq_start FROM timeline_rows WHERE ${ACTIVE} ` +
"AND item_type = 'assistant_message' ORDER BY seq_start DESC LIMIT 1",
id,
"AND item_type = 'assistant_message' " +
(turnId === undefined ? "" : "AND turn_id = ? ") +
"ORDER BY seq_start DESC LIMIT 1",
...(turnId === undefined ? [id] : [id, turnId]),
);
if (!last) return null;
const records = sql.iterate<Pick<RowRecord, "item_type" | "row">>(
@@ -198,7 +198,7 @@ export class DeferredTimelineBackend implements AgentTimelineBackend {
lastItem(scope: TimelineScope): Promise<AgentTimelineItem | null> {
return this.defer(() => this.inner.lastItem(scope));
}
lastAssistantMessage(scope: TimelineScope): Promise<string | null> {
return this.defer(() => this.inner.lastAssistantMessage(scope));
lastAssistantMessage(scope: TimelineScope, turnId?: string): Promise<string | null> {
return this.defer(() => this.inner.lastAssistantMessage(scope, turnId));
}
}
@@ -230,40 +230,37 @@ function parseEncryptedJson(sharedKey: Uint8Array, text: string): unknown {
return JSON.parse(plaintext);
}
async function getAvailablePort(): Promise<number> {
// Wrangler binds the port itself (`--port 0`) and reports it once it listens.
// Reserving a free port first and passing it in races other test files that
// bind ports between the reservation and wrangler's bind.
async function waitForRelayListening(relay: ChildProcess, timeout = 60000): Promise<number> {
return await new Promise((resolve, reject) => {
const server = net.createServer();
server.once("error", reject);
server.listen(0, "127.0.0.1", () => {
const address = server.address();
if (!address || typeof address === "string") {
server.close(() => reject(new Error("Failed to acquire port")));
return;
}
server.close(() => resolve(address.port));
});
const output: string[] = [];
const cleanup = () => {
clearTimeout(timer);
relay.stdout?.off("data", onData);
relay.stderr?.off("data", onData);
relay.off("exit", onExit);
};
const fail = (reason: string) => {
cleanup();
reject(new Error(`${reason}. Recent output:\n${output.slice(-20).join("")}`));
};
const onData = (data: Buffer) => {
output.push(data.toString());
const ready = /Ready on http:\/\/127\.0\.0\.1:(\d+)\r?\n/.exec(output.join(""));
if (!ready) return;
cleanup();
resolve(Number(ready[1]));
};
const onExit = (code: number | null) => fail(`Local relay exited with code ${code}`);
const timer = setTimeout(() => fail(`Local relay did not listen within ${timeout}ms`), timeout);
relay.stdout?.on("data", onData);
relay.stderr?.on("data", onData);
relay.once("exit", onExit);
});
}
async function waitForServer(port: number, timeout = 15000): Promise<void> {
const start = Date.now();
while (Date.now() - start < timeout) {
try {
await new Promise<void>((resolve, reject) => {
const socket = net.connect(port, "127.0.0.1", () => {
socket.end();
resolve();
});
socket.on("error", reject);
});
return;
} catch {
await new Promise((r) => setTimeout(r, 100));
}
}
throw new Error(`Server did not start on port ${port} within ${timeout}ms`);
}
async function waitForRelayWebSocketReady(port: number, timeout = 60000): Promise<void> {
const start = Date.now();
while (Date.now() - start < timeout) {
@@ -333,7 +330,6 @@ async function waitForCapturedLog(
await waitForRelayWebSocketReady(relayPort, 60000);
return;
}
relayPort = options.port ?? (await getAvailablePort());
const relayDir = path.resolve(process.cwd(), "../relay");
const relayArgs = [
"wrangler",
@@ -342,7 +338,7 @@ async function waitForCapturedLog(
"--ip",
"127.0.0.1",
"--port",
String(relayPort),
String(options.port ?? 0),
"--live-reload=false",
"--show-interactive-dev-session=false",
];
@@ -386,7 +382,7 @@ async function waitForCapturedLog(
}
});
await waitForServer(relayPort, 30000);
relayPort = await waitForRelayListening(relayProcess);
await waitForRelayWebSocketReady(relayPort, 60000);
};
@@ -394,6 +390,7 @@ async function waitForCapturedLog(
if (!relayProcess) return;
const process = relayProcess;
relayProcess = null;
if (process.exitCode !== null || process.signalCode !== null) return;
const exited = once(process, "exit");
process.kill("SIGTERM");
await withTimeout(exited, 10000, "Local relay did not stop");
@@ -1,6 +1,10 @@
import { MockLoadTestAgentClient } from "./agent/providers/mock-load-test-agent.js";
import {
MockLoadTestAgentClient,
MockLoadTestAgentSession,
} from "./agent/providers/mock-load-test-agent.js";
import { createPaseoApi } from "@getpaseo/client";
import type { AgentManager } from "./agent/agent-manager.js";
import type { AgentStreamEvent } from "./agent/agent-sdk-types.js";
import { AgentStorage } from "./agent/agent-storage.js";
import { createTestLogger } from "../test-utils/test-logger.js";
import { execFileSync } from "node:child_process";
@@ -1386,6 +1390,124 @@ test("dictation failure belongs only to its requesting source and releases speec
}
});
test("a tool-only turn uses the generic finish notification", async () => {
const daemon = await createTestPaseoDaemon({ mcpEnabled: false });
const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
const bodies: string[] = [];
const unsubscribe = client.onAgentAttentionRequired((event) => {
if (event.reason === "finished" && event.notification) bodies.push(event.notification.body);
});
try {
await client.connect();
await client.observeEvents(["agent_attention_required"], { notifications: true }).ready;
const agent = await client.createAgent({
provider: "claude",
cwd: daemon.staticDir,
modeId: "bypassPermissions",
});
await client.sendMessage(agent.id, "Respond with exactly: Previous report is ready.");
await expect.poll(() => bodies).toEqual(["Previous report is ready."]);
await client.clearAgentAttention(agent.id);
await client.sendMessage(agent.id, "Run echo hello without replying");
await expect.poll(() => bodies.length).toBe(2);
expect(bodies[1]).toBe("Finished working.");
} finally {
unsubscribe();
await client.close();
await daemon.close();
}
});
test("background finish notifications preview only the completed turn", async () => {
class BackgroundSession extends MockLoadTestAgentSession {
private readonly subscribers = new Set<Parameters<MockLoadTestAgentSession["subscribe"]>[0]>();
model: string | undefined;
override subscribe(callback: Parameters<MockLoadTestAgentSession["subscribe"]>[0]) {
const unsubscribe = super.subscribe(callback);
this.subscribers.add(callback);
return () => {
this.subscribers.delete(callback);
unsubscribe();
};
}
override async getRuntimeInfo() {
const info = await super.getRuntimeInfo();
return { ...info, model: this.model ?? info.model };
}
publish(event: AgentStreamEvent) {
for (const subscriber of this.subscribers) subscriber(event);
}
}
class BackgroundClient extends MockLoadTestAgentClient {
session!: BackgroundSession;
override async createSession(config: Parameters<MockLoadTestAgentClient["createSession"]>[0]) {
this.session = new BackgroundSession({ config, sessionId: "background-notifications" });
return this.session;
}
}
const provider = new BackgroundClient();
const daemon = await createTestPaseoDaemon({
mcpEnabled: false,
isDev: true,
agentClients: { mock: provider },
});
const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
const bodies: string[] = [];
const unsubscribe = client.onAgentAttentionRequired((event) => {
if (event.reason === "finished" && event.notification) bodies.push(event.notification.body);
});
try {
await client.connect();
await client.observeEvents(["agent_attention_required"], { notifications: true }).ready;
const agent = await client.createAgent({ provider: "mock", cwd: daemon.staticDir });
for (const [turnId, reply, model, expectedBody] of [
["first", "Previous report is ready.", undefined, "Previous report is ready."],
["silent", undefined, undefined, "Finished working."],
["latest", "The new report is ready.", "changed-model", "The new report is ready."],
] as const) {
const index = bodies.length;
const session = provider.session;
session.publish({ type: "turn_started", provider: "mock", turnId });
await expect
.poll(async () => (await client.fetchAgent(agent.id))?.agent.status)
.toBe("running");
if (reply) {
session.publish({
type: "timeline",
provider: "mock",
turnId,
item: { type: "assistant_message", text: reply },
});
}
session.model = model;
session.publish({
type: "turn_completed",
provider: "mock",
turnId,
usage: { inputTokens: 1, outputTokens: 1 },
});
await expect.poll(() => bodies.length).toBe(index + 1);
expect(bodies[index]).toBe(expectedBody);
await client.clearAgentAttention(agent.id);
}
} finally {
unsubscribe();
await client.close();
await daemon.close();
}
});
test("a legacy socket cannot borrow a modern sibling's directory observation", async () => {
const daemon = await createTestPaseoDaemon({ mcpEnabled: false });
const admin = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws`, appVersion: "0.8.0" });
@@ -1,6 +1,8 @@
import { mkdir, rename, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { existsSync, readFileSync } from "node:fs";
import { createServer } from "node:http";
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
import { spawn } from "node:child_process";
import { once } from "node:events";
import { tmpdir } from "node:os";
import path from "node:path";
import { pathToFileURL } from "node:url";
@@ -36,6 +38,66 @@ async function commitAll(repository: string, message: string): Promise<string> {
return stdout.trim();
}
async function serveGitHttp({
request,
response,
root,
}: {
request: IncomingMessage;
response: ServerResponse;
root: string;
}) {
const url = new URL(request.url!, "http://localhost");
const chunks: Buffer[] = [];
for await (const chunk of request) chunks.push(chunk as Buffer);
const body = Buffer.concat(chunks);
const child = spawn("git", ["http-backend"], {
env: {
...process.env,
GIT_PROJECT_ROOT: root,
GIT_HTTP_EXPORT_ALL: "1",
PATH_INFO: url.pathname,
QUERY_STRING: url.search.slice(1),
REQUEST_METHOD: request.method,
CONTENT_TYPE: request.headers["content-type"],
CONTENT_LENGTH: String(body.length),
HTTP_GIT_PROTOCOL: request.headers["git-protocol"] as string | undefined,
},
});
const closed = once(child, "close");
child.stdin.end(body);
const output: Buffer[] = [];
for await (const chunk of child.stdout) output.push(chunk as Buffer);
const [code] = await closed;
const data = Buffer.concat(output);
const end = data.indexOf("\r\n\r\n");
if (code !== 0 || end < 0) throw new Error("git http-backend failed");
for (const line of data.subarray(0, end).toString().split("\r\n")) {
const colon = line.indexOf(":");
if (colon < 0) continue;
const name = line.slice(0, colon);
const value = line.slice(colon + 1).trim();
if (name.toLowerCase() === "status") response.statusCode = Number(value.slice(0, 3));
else response.setHeader(name, value);
}
response.end(data.subarray(end + 4));
}
function createGitFixtureServer({ root, posts }: { root: string; posts: string[] }) {
return createServer((request, response) => {
if (
request.headers.authorization !==
`Basic ${Buffer.from("fixture:fake-secret").toString("base64")}`
) {
response.writeHead(401, { "WWW-Authenticate": 'Basic realm="fixture"' }).end();
return;
}
const url = new URL(request.url!, "http://localhost");
if (request.method === "POST") posts.push(url.pathname);
void serveGitHttp({ request, response, root }).catch(() => response.writeHead(500).end());
});
}
/** Points https://github.com/fixture/repository.git at a local repository for the callback. */
async function withGitHubFixture(repository: string, run: () => Promise<void>): Promise<void> {
const overlay = {
@@ -120,6 +182,128 @@ describe("managed Git plugin sources", () => {
});
}, 30_000);
it("downloads only the files of the installed commit, not every blob in history", async () => {
const repository = await createRepository();
// A file that exists only in history, like screenshots a plugin repository later dropped.
await writeFile(path.join(repository, "history-only.bin"), "x".repeat(256 * 1024));
await commitAll(repository, "add a large asset");
const { stdout: historyBlob } = await runGitCommand(["rev-parse", "HEAD:history-only.bin"], {
cwd: repository,
});
await rm(path.join(repository, "history-only.bin"));
await commitAll(repository, "drop the asset");
await runGitCommand(["config", "uploadpack.allowFilter", "true"], { cwd: repository });
await runGitCommand(["config", "uploadpack.allowAnySHA1InWant", "true"], { cwd: repository });
const home = await mkdtemp(path.join(tmpdir(), "paseo-plugin-git-home-"));
roots.push(home);
const sources = new ManagedPluginSources(home);
let candidate = await sources.prepareInstall({
source: `git:${pathToFileURL(repository).href}`,
});
candidate = await sources.place("managed-example", candidate);
expect(await readFile(path.join(candidate.directory, "index.server.ts"), "utf8")).toContain(
"export default",
);
const { stdout: checkoutRoot } = await runGitCommand(["rev-parse", "--show-toplevel"], {
cwd: candidate.directory,
});
const { stdout: missing } = await runGitCommand(
["rev-list", "--objects", "--all", "--missing=print"],
{ cwd: checkoutRoot.trim() },
);
expect(missing.split("\n")).toContain(`?${historyBlob.trim()}`);
}, 30_000);
it("fetches filtered checkout blobs for credentialed Git installs and updates", async () => {
const repository = await createRepository();
const root = await mkdtemp(path.join(tmpdir(), "paseo-plugin-smart-http-"));
roots.push(root);
await runGitCommand(["clone", "--bare", repository, "plugin.git"], { cwd: root });
const bare = path.join(root, "plugin.git");
await runGitCommand(["--git-dir", bare, "config", "uploadpack.allowFilter", "true"], {
cwd: root,
});
const posts: string[] = [];
const server = createGitFixtureServer({ root, posts });
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const address = server.address();
if (!address || typeof address === "string") throw new Error("Expected HTTP port");
const home = await mkdtemp(path.join(tmpdir(), "paseo-plugin-credential-filter-"));
roots.push(home);
const previous = process.env.GIT_CONFIG_PARAMETERS;
process.env.GIT_CONFIG_PARAMETERS = [previous, "'credential.helper='"]
.filter(Boolean)
.join(" ");
try {
const remote = `http://fixture:fake-secret@127.0.0.1:${address.port}/plugin.git`;
const sources = new ManagedPluginSources(home);
let candidate = await sources.prepareInstall({ source: remote });
candidate = await sources.place("managed-example", candidate);
sources.commit("managed-example", candidate.record);
expect(await readFile(path.join(candidate.directory, "index.server.ts"), "utf8")).toContain(
"export default",
);
expect(posts.length).toBeGreaterThanOrEqual(2);
expect(new Set(posts)).toEqual(new Set(["/plugin.git/git-upload-pack"]));
const installFetches = posts.length;
const config = await readFile(path.join(candidate.directory, ".git", "config"), "utf8");
expect(config).not.toMatch(/fixture:fake-secret/);
expect(config).toContain("https://paseo.invalid/plugin.git");
expect(config).toContain("partialclonefilter = blob:none");
await writeFile(
path.join(repository, "index.server.ts"),
"export default () => 'updated';\n",
);
const revision = await commitAll(repository, "update");
await runGitCommand(["push", bare, "main"], { cwd: repository });
const preview = await sources.preview("managed-example", candidate.directory);
expect(preview.target).toEqual({ kind: "git", commit: revision });
const updated = await sources.prepareUpdate(preview.proposal!, candidate.directory);
expect(await readFile(path.join(updated.directory, "index.server.ts"), "utf8")).toContain(
"updated",
);
expect(posts.length - installFetches).toBeGreaterThanOrEqual(2);
} finally {
if (previous === undefined) delete process.env.GIT_CONFIG_PARAMETERS;
else process.env.GIT_CONFIG_PARAMETERS = previous;
server.closeAllConnections();
await new Promise<void>((resolve) => server.close(() => resolve()));
}
}, 30_000);
it("rejects updating to a reviewed commit after the remote amends it away", async () => {
const repository = await createRepository();
const home = await mkdtemp(path.join(tmpdir(), "paseo-plugin-git-home-"));
roots.push(home);
const remote = pathToFileURL(repository).href;
const sources = new ManagedPluginSources(home);
let candidate = await sources.prepareInstall({ source: `git:${remote}` });
candidate = await sources.place("managed-example", candidate);
sources.commit("managed-example", candidate.record);
await writeFile(path.join(repository, "index.server.ts"), "export default () => 'v2';\n");
await commitAll(repository, "update v2");
const preview = await sources.preview("managed-example", candidate.directory);
expect(preview.outcome).toBe("update");
// Rewriting the commit without running gc leaves the unreferenced commit in the remote's
// object store; revision resolution must not lazily fetch commits absent from remote refs.
await writeFile(
path.join(repository, "index.server.ts"),
"export default () => 'v2-amended';\n",
);
await runGitCommand(["add", "-A"], { cwd: repository });
await runGitCommand(["commit", "--amend", "-m", "update v2 amended"], { cwd: repository });
await expect(sources.prepareUpdate(preview.proposal!, candidate.directory)).rejects.toThrow(
/Git command failed/,
);
}, 30_000);
it("offers current default HEAD after installing a tag", async () => {
const repository = await createRepository();
const home = await mkdtemp(path.join(tmpdir(), "paseo-plugin-git-home-"));
@@ -194,7 +194,7 @@ export class ManagedPluginSources {
const commit = await resolveRequestedRef(sourceRoot, input.ref);
if (target?.kind === "git" && commit !== target.commit)
throw new Error("Git target changed since review");
await checkout(sourceRoot, commit);
await checkout({ checkoutRoot: sourceRoot, commit, remote });
record = { kind: "git", remote };
}
const directory = path.resolve(sourceRoot, pluginPath);
@@ -502,7 +502,7 @@ function assertPluginPath(checkoutRoot: string, directory: string): void {
}
}
async function clone(remote: string, checkoutRoot: string): Promise<void> {
function gitRemote(remote: string) {
const publicRemote = redactRemoteCredentials(remote);
const cloneRemote = publicRemote === remote ? remote : "https://paseo.invalid/plugin.git";
const envOverlay =
@@ -514,12 +514,23 @@ async function clone(remote: string, checkoutRoot: string): Promise<void> {
GIT_CONFIG_KEY_0: `url.${remote}.insteadOf`,
GIT_CONFIG_VALUE_0: cloneRemote,
};
return { cloneRemote, envOverlay };
}
async function clone(remote: string, checkoutRoot: string): Promise<void> {
const { cloneRemote, envOverlay } = gitRemote(remote);
try {
await runGitCommand(["clone", "--no-checkout", "--", cloneRemote, checkoutRoot], {
cwd: path.dirname(checkoutRoot),
envOverlay,
timeout: GIT_TIMEOUT_MS,
});
// A blobless clone keeps every commit and ref for revision lookups, and checkout fetches
// only the files of the chosen commit. A full clone of a plugin repository with large
// assets in its history can outlast GIT_TIMEOUT_MS on an ordinary connection.
await runGitCommand(
["clone", "--no-checkout", "--filter=blob:none", "--", cloneRemote, checkoutRoot],
{
cwd: path.dirname(checkoutRoot),
envOverlay,
timeout: GIT_TIMEOUT_MS,
},
);
} catch (error) {
throw redactRemoteError(error, remote);
}
@@ -545,17 +556,30 @@ function redactRemoteError(error: unknown, remote: string): Error {
return new Error(message);
}
async function checkout(checkoutRoot: string, commit: string): Promise<void> {
await runGitCommand(["checkout", "--detach", commit], {
cwd: checkoutRoot,
envOverlay: GIT_ENV,
timeout: GIT_TIMEOUT_MS,
});
await runGitCommand(["submodule", "update", "--init", "--recursive"], {
cwd: checkoutRoot,
envOverlay: GIT_ENV,
timeout: GIT_TIMEOUT_MS,
});
async function checkout({
checkoutRoot,
commit,
remote,
}: {
checkoutRoot: string;
commit: string;
remote: string;
}): Promise<void> {
const { envOverlay } = gitRemote(remote);
try {
await runGitCommand(["checkout", "--detach", commit], {
cwd: checkoutRoot,
envOverlay,
timeout: GIT_TIMEOUT_MS,
});
await runGitCommand(["submodule", "update", "--init", "--recursive"], {
cwd: checkoutRoot,
envOverlay,
timeout: GIT_TIMEOUT_MS,
});
} catch (error) {
throw redactRemoteError(error, remote);
}
}
async function resolveRequestedRef(
@@ -576,17 +600,7 @@ async function resolveRequestedRef(
async function resolveRemoteCommit(remote: string, cwd: string, ref?: string): Promise<string> {
if (ref?.startsWith("-")) throw new Error("Plugin Git ref cannot start with '-'");
if (ref && /^[0-9a-f]{40,64}$/.test(ref)) return ref;
const publicRemote = redactRemoteCredentials(remote);
const cloneRemote = publicRemote === remote ? remote : "https://paseo.invalid/plugin.git";
const envOverlay =
cloneRemote === remote
? GIT_ENV
: {
...GIT_ENV,
GIT_CONFIG_COUNT: "1",
GIT_CONFIG_KEY_0: `url.${remote}.insteadOf`,
GIT_CONFIG_VALUE_0: cloneRemote,
};
const { cloneRemote, envOverlay } = gitRemote(remote);
try {
const names = ref
? [`refs/heads/${ref}`, `refs/tags/${ref}^{}`, `refs/tags/${ref}`, ref]
@@ -636,7 +650,12 @@ async function refExists(cwd: string, ref: string): Promise<boolean> {
}
async function revParse(cwd: string, ref: string): Promise<string> {
const { stdout } = await runGitCommand(["rev-parse", "--verify", ref], { cwd });
// Blobless clones register a promisor remote; keep revision lookups local so rev-parse
// does not lazily fetch unadvertised commits or bypass credentialed remote rewriting.
const { stdout } = await runGitCommand(["rev-parse", "--verify", ref], {
cwd,
envOverlay: { ...GIT_ENV, GIT_NO_LAZY_FETCH: "1" },
});
return stdout.trim();
}
@@ -880,24 +880,26 @@ class FakeAgentSession implements AgentSession {
}
}
const assistantText = this.buildAssistantText(textPrompt);
const assistantChunkA: AgentStreamEvent = {
type: "timeline",
provider: this.providerName,
item: { type: "assistant_message", text: assistantText.slice(0, 6) },
};
await this.appendHistoryEvent(assistantChunkA);
this.notifySubscribers(assistantChunkA);
const assistantChunkBText = assistantText.slice(6);
if (assistantChunkBText.length > 0) {
const assistantChunkB: AgentStreamEvent = {
if (textPrompt !== "Run echo hello without replying") {
const assistantText = this.buildAssistantText(textPrompt);
const assistantChunkA: AgentStreamEvent = {
type: "timeline",
provider: this.providerName,
item: { type: "assistant_message", text: assistantChunkBText },
item: { type: "assistant_message", text: assistantText.slice(0, 6) },
};
await this.appendHistoryEvent(assistantChunkB);
this.notifySubscribers(assistantChunkB);
await this.appendHistoryEvent(assistantChunkA);
this.notifySubscribers(assistantChunkA);
const assistantChunkBText = assistantText.slice(6);
if (assistantChunkBText.length > 0) {
const assistantChunkB: AgentStreamEvent = {
type: "timeline",
provider: this.providerName,
item: { type: "assistant_message", text: assistantChunkBText },
};
await this.appendHistoryEvent(assistantChunkB);
this.notifySubscribers(assistantChunkB);
}
}
await this.beforeTurnComplete?.(prompt);
@@ -1,3 +1,4 @@
import type { AgentAttentionEvent } from "./agent/agent-manager.js";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
@@ -58,13 +59,7 @@ import { VoiceAssistantWebSocketServer } from "./websocket-server.js";
interface WebSocketServerInternals {
sessions: Map<unknown, unknown>;
broadcastAgentAttention(params: {
agentId: string;
reason: string;
preview?: string;
providerId?: string;
timestamp?: string;
}): Promise<void>;
broadcastAgentAttention(params: AgentAttentionEvent): Promise<void>;
}
function createLogger() {
@@ -288,6 +283,7 @@ describe("VoiceAssistantWebSocketServer notification payloads", () => {
agentId: "agent-1",
provider: "claude",
reason: "finished",
finishedTurnId: "turn-1",
attentionTimestamp: new Date(),
});
@@ -303,7 +299,7 @@ describe("VoiceAssistantWebSocketServer notification payloads", () => {
},
},
]);
expect(getLastAssistantMessage).toHaveBeenCalledWith("agent-1");
expect(getLastAssistantMessage).toHaveBeenCalledWith("agent-1", "turn-1");
});
it("sends push notifications regardless of UI label presence", async () => {
@@ -323,11 +319,12 @@ describe("VoiceAssistantWebSocketServer notification payloads", () => {
agentId: "agent-2",
provider: "claude",
reason: "finished",
finishedTurnId: "turn-2",
attentionTimestamp: new Date(),
});
expect(pushNotifications.sent).toHaveLength(1);
expect(getLastAssistantMessage).toHaveBeenCalledWith("agent-2");
expect(getLastAssistantMessage).toHaveBeenCalledWith("agent-2", "turn-2");
});
it("routes a hidden stale focused browser tab's notification to the present Electron web client", async () => {
+10 -9
View File
@@ -48,7 +48,11 @@ import { getCachedHostMachineKind } from "./host-machine-kind.js";
import { getHostName } from "./host-name.js";
import { randomUUID } from "node:crypto";
import { monitorEventLoopDelay } from "node:perf_hooks";
import type { AgentManager, AgentMetricsSnapshot } from "./agent/agent-manager.js";
import type {
AgentAttentionEvent,
AgentManager,
AgentMetricsSnapshot,
} from "./agent/agent-manager.js";
import type { AgentStorage } from "./agent/agent-storage.js";
import type { DownloadTokenStore } from "./file-download/token-store.js";
import type { TerminalManager } from "../terminal/terminal-manager.js";
@@ -108,7 +112,6 @@ function resolveAgentMessageQueueStore(
return store ?? createMemoryAgentMessageQueueStore();
}
import type { HubExecutionAgents } from "./hub/daemon-executions.js";
import type { AgentProvider } from "./agent/agent-sdk-types.js";
import { ProviderSnapshotManager } from "./agent/provider-snapshot-manager.js";
import { attachMutableProviderConfigOwner } from "./agent/mutable-provider-config-owner.js";
import type {
@@ -3641,12 +3644,7 @@ export class VoiceAssistantWebSocketServer {
};
}
private async broadcastAgentAttention(params: {
agentId: string;
provider: AgentProvider;
reason: "finished" | "error" | "permission";
attentionTimestamp: Date | null;
}): Promise<void> {
private async broadcastAgentAttention(params: AgentAttentionEvent): Promise<void> {
const agent = this.agentManager.getAgent(params.agentId);
if (!agent?.workspaceId) {
return;
@@ -3674,7 +3672,10 @@ export class VoiceAssistantWebSocketServer {
);
const allStates = notificationEntries.map((e) => e.state);
const nowMs = Date.now();
const assistantMessage = await this.agentManager.getLastAssistantMessage(params.agentId);
const assistantMessage =
params.reason === "finished" && params.finishedTurnId !== undefined
? await this.agentManager.getLastAssistantMessage(params.agentId, params.finishedTurnId)
: null;
const notification = buildAgentAttentionNotificationPayload({
reason: params.reason,
serverId: this.serverId,
@@ -2,8 +2,9 @@ import { createWorkspaceRuntimeStore } from "./workspace-runtime-store/index.js"
import { execFileSync } from "node:child_process";
import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve as resolvePath } from "node:path";
import { basename, join, resolve as resolvePath } from "node:path";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { createGiteaService, TeaCommandError } from "../services/gitea-service.js";
import { createGitHubService } from "../services/github-service.js";
import type { CurrentPullRequestStatus, ForgeService } from "../services/forge-service.js";
import { defaultForgeRegistry } from "../services/forge-registry.js";
@@ -1297,6 +1298,7 @@ describe("WorkspaceGitServiceImpl primitive refresh entrypoint", () => {
headRef: "feature",
headSha: "1111111111111111111111111111111111111111",
reason: "self-heal-forge-pr-status",
pollRemoteUrl: "https://forge-self-heal.test/acme/repo.git",
});
expect(listener).toHaveBeenCalledWith(
expect.objectContaining({
@@ -1316,6 +1318,168 @@ describe("WorkspaceGitServiceImpl primitive refresh entrypoint", () => {
}
});
test.each(["healthy", "retry-after", "cli-error"] as const)(
"Forgejo self-heal shares repository reads and host cooldowns (%s)",
async (scenario) => {
const host = "forgejo-status.test";
const origin = `https://${host}`;
const worktree = (branch: string) => join(REPO_CWD, branch);
const branches = ["one", "two", "three"] as const;
const repoFor = (cwd: string) =>
["four", "five"].includes(basename(cwd)) ? "other" : "repo";
const remoteFor = (cwd: string) => `${origin}/acme/${repoFor(cwd)}.git`;
const reads: string[] = [];
const statusRequests: string[] = [];
let rejectionSent = false;
let revision = 1;
const pull = (
repo: string,
branch: string,
number: number,
state: string,
merged = false,
) => ({
number,
html_url: `${origin}/acme/${repo}/pulls/${number}`,
title: `${branch} v${revision}`,
state,
merged,
head: { ref: branch, sha: String(number).repeat(40) },
base: { ref: "main" },
});
const forge = createGiteaService({
resolveTeaPath: async () => "/fake/tea",
resolveRemoteUrl: async (cwd) => remoteFor(cwd),
now: () => Date.now(),
runner: async (args, { cwd }) => {
const repo = repoFor(cwd);
const endpoint = args.at(-1) ?? "";
const includesHeaders = args.includes("-i");
const cliList = args[0] === "pr" && args[1] === "list";
const open = cliList || endpoint.includes("state=open");
const terminal = endpoint.includes("state=all");
const json = (data: unknown) => ({
stdout: (includesHeaders ? "HTTP/1.1 200 OK\r\n\r\n" : "") + JSON.stringify(data),
stderr: "",
});
if (includesHeaders || cliList || terminal) statusRequests.push(endpoint);
if (!open && !terminal) {
if (endpoint.includes("/commits/"))
return json({ state: "", statuses: [], total_count: 0 });
if (endpoint.includes("/actions/")) return json({ workflow_runs: [], total_count: 0 });
return json({ full_name: `acme/${repo}`, default_branch: "main" });
}
reads.push(`${repo}:${open ? "open" : "terminal"}`);
if (scenario !== "healthy" && !rejectionSent) {
rejectionSent = true;
if (scenario === "retry-after" && includesHeaders) {
return {
stdout: "{}",
stderr:
"agent-vault: routing HTTP/HTTPS through MITM proxy (<agent-vault-proxy>:14322)\n" +
"agent-vault: agent-vault connected. Starting /usr/bin/env...\n\n" +
"HTTP/1.1 429 Too Many Requests\r\nRetry-After: 19\r\n\r\n",
};
}
throw new TeaCommandError({ args, cwd, exitCode: 1, stderr: "Too Many Requests" });
}
if (terminal)
return json([pull(repo, "two", 2, "closed", true), pull(repo, "three", 3, "closed")]);
if (repo === "other")
return json([pull(repo, "four", 4, "open"), pull(repo, "five", 5, "open")]);
const item = pull(repo, "one", 1, "open");
return json(
cliList
? [
{
index: "1",
state: "open",
title: item.title,
url: item.html_url,
head: item.head.ref,
},
]
: [item],
);
},
});
const unregister = defaultForgeRegistry.register("forgejo-status-test", {
createService: () => forge,
matchesHost: (candidate) => candidate === host,
});
const service = createService({
getCheckoutSnapshotFacts: async (cwd) =>
createCheckoutFacts(cwd, {
currentBranch: basename(cwd),
remoteUrl: remoteFor(cwd),
pullRequestLookupTarget: { headRef: basename(cwd) },
}),
getCheckoutStatus: async (cwd) =>
createCheckoutStatus(cwd, { currentBranch: basename(cwd), remoteUrl: remoteFor(cwd) }),
});
const statuses = new Map<string, WorkspaceGitRuntimeSnapshot["forge"]["pullRequest"]>();
const observe = (branch: string) =>
service.registerWorkspace({ cwd: worktree(branch) }, (snapshot) => {
statuses.set(branch, snapshot.forge.pullRequest);
});
const expectStatuses = (version: number) => {
expect(
branches.map((branch) => [statuses.get(branch)?.state, statuses.get(branch)?.title]),
).toEqual([
["open", `one v${version}`],
["merged", `two v${version}`],
["closed", `three v${version}`],
]);
};
try {
branches.forEach(observe);
if (scenario !== "healthy") {
const cooldownMs = scenario === "retry-after" ? 19_000 : 60_000;
await vi.advanceTimersByTimeAsync(cooldownMs - 1);
observe("four");
await vi.advanceTimersByTimeAsync(1);
observe("five");
await vi.advanceTimersByTimeAsync(119_999);
expect(reads).toEqual(["repo:open"]);
expect(statusRequests).toHaveLength(1);
await vi.advanceTimersByTimeAsync(1);
expect(reads).toEqual(["repo:open", "other:open"]);
expect(statuses.get("five")?.title).toBe("five v1");
await vi.advanceTimersByTimeAsync(120_000);
expect(reads).toEqual([
"repo:open",
"other:open",
"repo:open",
"repo:terminal",
"other:open",
]);
expect(statuses.get("four")?.title).toBe("four v1");
} else {
await vi.advanceTimersByTimeAsync(120_000);
expect(reads).toEqual(["repo:open", "repo:terminal"]);
}
expectStatuses(1);
reads.length = 0;
revision = 2;
await vi.advanceTimersByTimeAsync(120_000);
expect(reads).toEqual(
scenario === "healthy"
? ["repo:open", "repo:terminal"]
: ["repo:open", "repo:terminal", "other:open"],
);
expectStatuses(2);
} finally {
service.dispose();
unregister();
}
},
);
test("generic forge self-heal uses the fast poll window while checks are pending", async () => {
const forge = {
...createGitHubServiceStub(),
@@ -3425,6 +3425,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
cwd: target.cwd,
...pollTarget,
reason: "self-heal-forge-pr-status",
pollRemoteUrl: target.latestGit?.remoteUrl ?? undefined,
});
if (!closed && this.isActiveObservedWorkspaceTarget(target)) {
latestStatus = status;
@@ -442,6 +442,8 @@ export interface CurrentPullRequestLookup {
headRef: string;
headSha?: string;
headRepositoryOwner?: string;
/** Repository remote already resolved by workspace status polling. */
pollRemoteUrl?: string;
/** Local branch name when it differs from the PR source ref. */
currentBranch?: string;
}
@@ -363,7 +363,7 @@ function isSubmittedGiteaReview(review: GiteaReview): boolean {
return state !== "PENDING" && state !== "REQUEST_REVIEW";
}
function parseTeaHttpStreams(
export function parseTeaHttpStreams(
stdout: string,
stderr: string,
): {
@@ -375,7 +375,9 @@ function parseTeaHttpStreams(
if (fromStdout.status !== null) {
return fromStdout;
}
const fromStderr = parseCliHttpResponse(stderr);
// Proxy startup diagnostics can precede Tea's HTTP headers on stderr.
const statusLine = stderr.search(/^HTTP\/\d(?:\.\d)?[ \t]+\d{3}\b/m);
const fromStderr = parseCliHttpResponse(statusLine === -1 ? stderr : stderr.slice(statusLine));
if (fromStderr.status !== null) {
return { status: fromStderr.status, headers: fromStderr.headers, body: stdout.trim() };
}
@@ -470,6 +470,60 @@ describe("createGiteaService getReferenceRepository", () => {
});
describe("createGiteaService", () => {
it("shares Actions tasks across concurrent open PR status polls", async () => {
const repo = "repos/example-user/sample-repo";
const pulls = [1, 2, 3].map((number) => {
const pull = currentPullRequestApi({
number,
state: "open",
headRef: `feature-${number}`,
headSha: String(number).repeat(40),
});
pull.title = `Feature ${number}`;
return pull;
});
const tasks = pulls.map((pull) => ({
id: pull.number,
name: pull.title,
head_sha: pull.head.sha,
status: "success",
}));
const { service, calls } = makeService((args) => {
const endpoint = args.at(-1);
const json = (body: unknown) => ok(`HTTP/1.1 200 OK\r\n\r\n${JSON.stringify(body)}`);
if (endpoint === `${repo}/pulls?state=open&limit=50&page=1`) return json(pulls);
if (endpoint?.startsWith(`${repo}/commits/`)) {
return json({ state: "", statuses: [], total_count: 0 });
}
if (endpoint === `${repo}/actions/tasks?limit=50&page=1`) {
return json({ total_count: tasks.length, workflow_runs: tasks });
}
throw new Error(`unexpected call: ${args.join(" ")}`);
});
const statuses = await Promise.all(
pulls.map((pull) =>
service.getCurrentPullRequestStatus({
cwd: `/worktrees/${pull.head.ref}`,
headRef: pull.head.ref,
pollRemoteUrl: "https://gitea.com/example-user/sample-repo.git",
reason: "self-heal-forge-pr-status",
}),
),
);
expect(statuses).toMatchObject(
pulls.map((pull) => ({ title: pull.title, checks: [{ name: pull.title }] })),
);
expect(calls.map((args) => args.at(-1)).sort()).toEqual(
[
`${repo}/pulls?state=open&limit=50&page=1`,
`${repo}/actions/tasks?limit=50&page=1`,
...pulls.map((pull) => `${repo}/commits/${pull.head.sha}/status`),
].sort(),
);
});
it("maps a tea pr list item to the neutral current PR status by head branch", async () => {
const { service, calls } = makeService((args) => {
if (args[0] === "pr" && args[1] === "list")
+192 -77
View File
@@ -78,7 +78,8 @@ import {
type GiteaCombinedCommitStatus,
type GiteaCommitStatus,
} from "./gitea-checks.js";
import { createGiteaChangeRequestSource } from "./gitea-change-requests.js";
import { createGiteaChangeRequestSource, parseTeaHttpStreams } from "./gitea-change-requests.js";
import { ChangeRequestRateLimitError, parseRetryAfterMs } from "./change-request-poller.js";
import { isGiteaStatusFacts, type GiteaStatusFacts } from "./gitea-facts.js";
const TEA_ENV = {
@@ -111,6 +112,8 @@ const ISSUE_LIST_FIELDS = "index,state,author,url,title,body,labels,comments,cre
const CURRENT_PR_LOOKUP_PAGE_SIZE = 50;
const CURRENT_PR_OPEN_LOOKUP_MAX_PAGES = 4;
// Cover shortly staggered worktree polls without carrying data into the next poll cycle.
const CURRENT_PR_LIST_SHARE_MS = 15_000;
const TIMELINE_PAGE_SIZE = 50;
const TIMELINE_MAX_PAGES_PER_BUCKET = 4;
@@ -141,6 +144,17 @@ export interface TeaCommandRunnerOptions {
executablePath?: string;
}
interface TeaStatusReadOptions extends TeaCommandRunnerOptions {
statusHost?: string;
statusRepositoryKey?: string;
}
interface CurrentPullRequestCheckRead extends TeaStatusReadOptions {
repoOwner: string;
repoName: string;
sha: string;
}
export interface TeaCommandResult {
stdout: string;
stderr: string;
@@ -992,14 +1006,14 @@ function classifyGiteaTimelineErrorKind(stderr: string): PullRequestTimelineErro
}
/**
* Re-throw only tea auth / CLI-missing failures, letting every other error be
* swallowed by a best-effort caller. Background status polling wraps its checks
* load in its own catch, so this stays invisible there; on the explicit,
* user-triggered check-details path it lets an expired token surface the real
* remediation instead of a misleading "check not found".
* Keep rate limits and auth failures visible through optional check reads.
*/
function rethrowTeaAuthFailure(error: unknown): void {
if (error instanceof TeaAuthenticationError || error instanceof TeaCliMissingError) {
function rethrowTeaCheckReadFailure(error: unknown): void {
if (
error instanceof ChangeRequestRateLimitError ||
error instanceof TeaAuthenticationError ||
error instanceof TeaCliMissingError
) {
throw error;
}
}
@@ -1235,6 +1249,8 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
const resolveRemoteUrl = options.resolveRemoteUrl ?? defaultResolveRemoteUrl;
const resolveCurrentBranch = options.resolveCurrentBranch ?? defaultResolveCurrentBranch;
const now = options.now ?? Date.now;
const statusPausedUntilByHost = new Map<string, number>();
const sharedStatusReads = new Map<string, { result: Promise<string>; expiresAt: number }>();
const currentPrHeadShaCache = new Map<string, { sha: string; expiresAt: number }>();
async function runRaw(
@@ -1252,9 +1268,81 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
}
}
async function run(args: string[], runOptions: TeaCommandRunnerOptions): Promise<string> {
const result = await runRaw(args, runOptions);
return result.stdout.trim();
function assertStatusHostAvailable(host: string): void {
const resetAtMs = statusPausedUntilByHost.get(host);
if (resetAtMs === undefined) return;
if (resetAtMs > now()) throw new ChangeRequestRateLimitError({ host, resetAtMs });
statusPausedUntilByHost.delete(host);
}
function pauseStatusHost(host: string, headers: ReadonlyMap<string, string>): never {
const resetAtMs = Math.max(
statusPausedUntilByHost.get(host) ?? 0,
parseRetryAfterMs(headers, now(), { forceOnMissing: true })!,
);
statusPausedUntilByHost.set(host, resetAtMs);
throw new ChangeRequestRateLimitError({ host, resetAtMs });
}
async function runStatusRead(
args: string[],
runOptions: TeaCommandRunnerOptions,
host: string,
): Promise<string> {
const readArgs = args[0] === "api" ? ["api", "-i", ...args.slice(1)] : args;
const result = await runRaw(readArgs, runOptions).catch((error: unknown) => {
if (error instanceof TeaCommandError) {
const response = parseTeaHttpStreams(error.stdout ?? "", error.stderr);
if (response.status === 429 || /\bToo Many Requests\b/i.test(error.stderr)) {
pauseStatusHost(host, response.headers);
}
}
throw error;
});
const response = parseTeaHttpStreams(result.stdout, result.stderr);
if (response.status === 429) pauseStatusHost(host, response.headers);
if (response.status !== null && (response.status < 200 || response.status >= 300)) {
throw new TeaCommandError({
args: readArgs,
cwd: runOptions.cwd,
exitCode: 0,
stderr: `Gitea API returned HTTP ${response.status}`,
});
}
assertStatusHostAvailable(host);
return response.body;
}
async function run(args: string[], runOptions: TeaStatusReadOptions): Promise<string> {
const { statusHost, statusRepositoryKey, ...commandOptions } = runOptions;
if (!statusHost) {
return (await runRaw(args, commandOptions)).stdout.trim();
}
assertStatusHostAvailable(statusHost);
if (!statusRepositoryKey) return runStatusRead(args, commandOptions, statusHost);
// Share repository reads, then let each caller select its own branch.
const key = JSON.stringify([statusRepositoryKey, args]);
const nowMs = now();
for (const [readKey, read] of sharedStatusReads) {
if (read.expiresAt <= nowMs) sharedStatusReads.delete(readKey);
}
const shared = sharedStatusReads.get(key);
if (shared) return shared.result;
const read = {
result: runStatusRead(args, commandOptions, statusHost),
expiresAt: Infinity,
};
sharedStatusReads.set(key, read);
try {
const result = await read.result;
read.expiresAt = now() + CURRENT_PR_LIST_SHARE_MS;
return result;
} catch (error) {
sharedStatusReads.delete(key);
throw error;
}
}
const changeRequests = createGiteaChangeRequestSource({
@@ -1284,7 +1372,7 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
async function runJsonArray<T>(
args: string[],
runOptions: TeaCommandRunnerOptions,
runOptions: TeaStatusReadOptions,
itemSchema: z.ZodType<T>,
): Promise<T[]> {
const stdout = await run(args, runOptions);
@@ -1296,7 +1384,7 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
async function runJson<T>(
args: string[],
runOptions: TeaCommandRunnerOptions,
runOptions: TeaStatusReadOptions,
schema: z.ZodType<T>,
): Promise<T> {
const stdout = await run(args, runOptions);
@@ -1435,12 +1523,20 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
async function loadCurrentPullRequestStatus(
input: CurrentPullRequestLookup,
): Promise<CurrentPullRequestStatus | null> {
const match = await findCurrentPullRequestForHeadRef(input);
const location = input.pollRemoteUrl ? parseGitRemoteLocation(input.pollRemoteUrl) : null;
const statusRead = {
cwd: input.cwd,
statusHost: location?.host,
statusRepositoryKey: location
? JSON.stringify([location.host, location.port, location.path])
: undefined,
};
const match = await findCurrentPullRequestForHeadRef(input, location, statusRead);
if (!match) {
return null;
}
const status = toCurrentPullRequestStatus(match);
return loadCurrentPullRequestChecks(input.cwd, match, status);
return loadCurrentPullRequestChecks(match, status, statusRead);
}
async function resolveCurrentRepoIdentity(
@@ -1470,10 +1566,20 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
async function findCurrentPullRequestForHeadRef(
input: CurrentPullRequestLookup,
location?: ReturnType<typeof parseGitRemoteLocation>,
statusRead: TeaStatusReadOptions = { cwd: input.cwd },
): Promise<GiteaPrListItem | null> {
const repoIdentity = await resolveCurrentRepoIdentity(input.cwd);
const repoIdentity = location
? parseGitHubRemoteIdentity(location.path)
: await resolveCurrentRepoIdentity(input.cwd);
const repoPath = repositoryApiPath(repoIdentity);
const expectedHeadOwner = repoIdentity?.owner ?? null;
const openMatch = await findOpenPullRequestForHeadRef(input, expectedHeadOwner);
const openMatch = await findOpenPullRequestForHeadRef(
input.headRef,
expectedHeadOwner,
repoPath,
statusRead,
);
if (openMatch) {
return openMatch;
}
@@ -1481,13 +1587,12 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
// tea discovers repository context from any configured git remote, while
// the default remote resolver reads origin only. Preserve that broader
// discovery for repositories whose primary remote has another name.
const repoPath = repositoryApiPath(repoIdentity);
const recentItems = await runJsonArray(
[
"api",
`${repoPath}/pulls?state=all&sort=recentupdate&page=1&limit=${CURRENT_PR_LOOKUP_PAGE_SIZE}`,
],
{ cwd: input.cwd },
statusRead,
GiteaCurrentPullRequestApiSchema,
);
const candidates = recentItems.filter((item) => {
@@ -1518,7 +1623,14 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
candidates[0] ??
null;
if (match && mapGiteaState(match.state) !== "open") {
const repository = await readRepository(input.cwd, repoPath).catch(() => null);
const repository = await runJson(
["api", repoPath],
statusRead,
GiteaRepositoryApiSchema,
).catch((error: unknown) => {
if (error instanceof ChangeRequestRateLimitError) throw error;
return null;
});
if (isOnDefaultBranch(input, repository?.default_branch)) {
return null;
}
@@ -1527,23 +1639,30 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
}
async function findOpenPullRequestForHeadRef(
input: {
cwd: string;
headRef: string;
headSha?: string;
},
headRef: string,
expectedHeadOwner: string | null,
repoPath: string,
statusRead: TeaStatusReadOptions,
): Promise<GiteaPrListItem | null> {
for (let page = 1; page <= CURRENT_PR_OPEN_LOOKUP_MAX_PAGES; page += 1) {
const items = await listPullRequestItems({
cwd: input.cwd,
state: "open",
limit: CURRENT_PR_LOOKUP_PAGE_SIZE,
page,
});
const match = items.find((item) =>
matchesCurrentHeadRef(item, input.headRef, expectedHeadOwner),
);
const items = statusRead.statusHost
? (
await runJsonArray(
[
"api",
`${repoPath}/pulls?state=open&limit=${CURRENT_PR_LOOKUP_PAGE_SIZE}&page=${page}`,
],
statusRead,
GiteaCurrentPullRequestApiSchema,
)
).map(currentPullRequestApiToListItem)
: await listPullRequestItems({
cwd: statusRead.cwd,
state: "open",
limit: CURRENT_PR_LOOKUP_PAGE_SIZE,
page,
});
const match = items.find((item) => matchesCurrentHeadRef(item, headRef, expectedHeadOwner));
if (match) {
return match;
}
@@ -1555,28 +1674,32 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
}
async function loadCurrentPullRequestChecks(
cwd: string,
item: GiteaPrListItem,
status: CurrentPullRequestStatus,
statusRead: TeaStatusReadOptions,
): Promise<CurrentPullRequestStatus> {
const number = parseGiteaInt(item.index);
if (number === null || !status.repoOwner || !status.repoName) {
return status;
}
try {
const pr = await runJson(
["pr", String(number), "-o", "json"],
{ cwd },
GiteaPullRequestViewSchema,
);
if (!pr.headSha) {
const sha =
(statusRead.statusHost ? item.headSha : undefined) ??
(
await runJson(
["pr", String(number), "-o", "json"],
{ cwd: statusRead.cwd, statusHost: statusRead.statusHost },
GiteaPullRequestViewSchema,
)
).headSha;
if (!sha) {
return status;
}
const checksInput = {
cwd,
...statusRead,
repoOwner: status.repoOwner,
repoName: status.repoName,
sha: pr.headSha,
sha,
};
const [combined, actionTasks] = await Promise.all([
loadCombinedCommitStatusBestEffort(checksInput),
@@ -1588,42 +1711,37 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
actionTasks,
);
return applyGiteaChecks(
{ ...status, headSha: pr.headSha },
{ ...status, headSha: sha },
combined,
actionTasks,
actionRequiredRunIds,
);
} catch {
} catch (error) {
if (error instanceof ChangeRequestRateLimitError) throw error;
return status;
}
}
async function loadCombinedCommitStatusBestEffort(input: {
cwd: string;
repoOwner: string;
repoName: string;
sha: string;
}): Promise<GiteaCombinedCommitStatus> {
async function loadCombinedCommitStatusBestEffort(
input: CurrentPullRequestCheckRead,
): Promise<GiteaCombinedCommitStatus> {
try {
return await loadCombinedCommitStatus(input);
} catch (error) {
rethrowTeaAuthFailure(error);
rethrowTeaCheckReadFailure(error);
return { state: "", statuses: [], total_count: 0 };
}
}
async function loadCombinedCommitStatus(input: {
cwd: string;
repoOwner: string;
repoName: string;
sha: string;
}): Promise<GiteaCombinedCommitStatus> {
async function loadCombinedCommitStatus(
input: CurrentPullRequestCheckRead,
): Promise<GiteaCombinedCommitStatus> {
const owner = encodeURIComponent(input.repoOwner);
const repo = encodeURIComponent(input.repoName);
const sha = encodeURIComponent(input.sha);
return runJson(
["api", `repos/${owner}/${repo}/commits/${sha}/status`],
{ cwd: input.cwd },
{ cwd: input.cwd, statusHost: input.statusHost },
GiteaCombinedCommitStatusSchema,
);
}
@@ -1633,7 +1751,7 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
// (waiting run, no tasks, pending shadows). Skipping the fetch otherwise keeps
// the common running/finished path at two requests.
async function loadActionRequiredRunIdsBestEffort(
input: { cwd: string; repoOwner: string; repoName: string; sha: string },
input: CurrentPullRequestCheckRead,
combined: GiteaCombinedCommitStatus,
actionTasks: GiteaActionTask[],
): Promise<ReadonlySet<number>> {
@@ -1656,30 +1774,27 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
const runs = await loadGiteaActionPages(input, "runs", `head_sha=${sha}`);
return deriveGiteaActionRequiredRunIds(runs, input.sha);
} catch (error) {
rethrowTeaAuthFailure(error);
rethrowTeaCheckReadFailure(error);
return new Set();
}
}
async function loadActionTasksBestEffort(input: {
cwd: string;
repoOwner: string;
repoName: string;
sha: string;
}): Promise<GiteaActionTask[]> {
async function loadActionTasksBestEffort(
input: CurrentPullRequestCheckRead,
): Promise<GiteaActionTask[]> {
try {
const tasks = await loadActionTasks(input);
const matchingTasks = tasks.filter((task) => task.head_sha === input.sha);
const latestTasks = latestGiteaActionTasksByWorkflow(matchingTasks);
return await enrichActionTaskApprovalsBestEffort(input, latestTasks);
} catch (error) {
rethrowTeaAuthFailure(error);
rethrowTeaCheckReadFailure(error);
return [];
}
}
async function enrichActionTaskApprovalsBestEffort(
input: { cwd: string; repoOwner: string; repoName: string; sha: string },
input: CurrentPullRequestCheckRead,
tasks: GiteaActionTask[],
): Promise<GiteaActionTask[]> {
if (!tasks.some((task) => task.status.toLowerCase() === "blocked")) return tasks;
@@ -1703,7 +1818,7 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
: task,
);
} catch (error) {
rethrowTeaAuthFailure(error);
rethrowTeaCheckReadFailure(error);
return tasks;
}
}
@@ -1715,7 +1830,7 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
// until total_count is exhausted, a page comes back empty, or the bounded
// max-pages cap is hit. SHA matches need not be contiguous across pages.
async function loadGiteaActionPages(
input: { cwd: string; repoOwner: string; repoName: string },
input: CurrentPullRequestCheckRead,
endpoint: "tasks" | "runs",
query?: string,
): Promise<unknown[]> {
@@ -1730,7 +1845,11 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
"api",
`repos/${owner}/${repo}/actions/${endpoint}?${queryPrefix}limit=${GITEA_ACTION_PAGE_LIMIT}&page=${page}`,
],
{ cwd: input.cwd },
{
cwd: input.cwd,
statusHost: input.statusHost,
statusRepositoryKey: endpoint === "tasks" ? input.statusRepositoryKey : undefined,
},
GiteaActionsListResponseSchema,
);
if (response.workflow_runs.length === 0) break;
@@ -1741,11 +1860,7 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
return items;
}
async function loadActionTasks(input: {
cwd: string;
repoOwner: string;
repoName: string;
}): Promise<GiteaActionTask[]> {
async function loadActionTasks(input: CurrentPullRequestCheckRead): Promise<GiteaActionTask[]> {
return parseGiteaActionTasks(await loadGiteaActionPages(input, "tasks"));
}
@@ -26,7 +26,7 @@ import {
rmSync,
writeFileSync,
} from "node:fs";
import { delimiter, join } from "node:path";
import { basename, delimiter, join } from "node:path";
import { tmpdir } from "node:os";
import pino from "pino";
import {
@@ -1667,25 +1667,53 @@ async function startManagerWithWorkerProtocol(
}
}
// Whether the program still accepts connections on its socket. Unlike its pid, which Windows
// hands to another process as soon as the program ends and records without a birth time, the
// socket closes with the program and nothing else answers on it.
async function programListens(socketPath: string): Promise<boolean> {
return await new Promise((resolve) => {
const socket = createConnection(socketPath);
socket.once("connect", () => {
socket.destroy();
resolve(true);
});
socket.once("error", () => resolve(false));
});
}
// A terminal running an idle program in a worker that reports `protocolVersion`, left running
// after its daemon lets go (stop --keep-terminals).
// after its daemon lets go (stop --keep-terminals). The program listens on `programSocket`.
async function leaveWorkerWithTerminal(
paseoHome: string,
protocolVersion: number,
): Promise<{ terminalId: string; programPid: number; workerPid: number; cwd: string }> {
): Promise<{
terminalId: string;
programPid: number;
programSocket: string;
workerPid: number;
cwd: string;
}> {
const cwd = mkdtempSync(join(tmpdir(), "worker-terminal-manager-protocol-"));
temporaryDirs.push(cwd);
const programSocket =
process.platform === "win32"
? `\\\\.\\pipe\\paseo-test-program-${basename(cwd)}`
: join(cwd, "program.sock");
const previous = await startManagerWithWorkerProtocol(paseoHome, protocolVersion);
const session = await previous.createTerminal({
workspaceId: "ws-protocol",
cwd,
...nodeTerminalCommand("setInterval(() => {}, 1000);"),
...nodeTerminalCommand(
`require("node:net").createServer().listen(${JSON.stringify(programSocket)}); setInterval(() => {}, 1000);`,
),
});
await waitForCondition(() => programListens(programSocket), 10000);
const [record] = await workerRecords(paseoHome);
await previous.detach();
return {
terminalId: session.id,
programPid: (await recordedTerminalPids(paseoHome)).get(session.id)!,
programSocket,
workerPid: record!.pid,
cwd,
};
@@ -1697,24 +1725,14 @@ it.each([1, 4, 5])(
const paseoHome = createTemporaryHome();
const old = await leaveWorkerWithTerminal(paseoHome, version);
const [record] = await workerRecords(paseoHome);
const program = record!.terminals.find((entry) => entry.id === old.terminalId)!;
const inspector = createTerminalWorkerProcessInspector();
manager = await startRealWorkerManager({ paseoHome });
expect(await readUnconfirmedTerminalCleanup(paseoHome)).toEqual([]);
// Startup launches a replacement worker after cleanup. Either old PID may already
// belong to another process, so verify that the recorded birth identities are gone.
// Startup launches a replacement worker after cleanup. The program's PID may already
// belong to another process, so its own socket is what proves it gone.
await waitForCondition(() => !isProcessAlive(record!.pid), 10000);
await expect
.poll(
async () =>
!isProcessAlive(program.pid) ||
classifyTerminalProgramProcess(program, await inspector.inspect(program.pid)).status ===
"unrelated",
{ timeout: 10000 },
)
.toBe(true);
await expect.poll(() => programListens(old.programSocket), { timeout: 10000 }).toBe(false);
expect(manager.getTerminal(old.terminalId)).toBeUndefined();
const workers = await workerRecords(paseoHome);
expect(workers).toHaveLength(1);
-99
View File
@@ -1,4 +1,3 @@
import copy from "../src/i18n/resources/en.json" with { type: "json" };
import { expect, test, waitForHydration, type Page } from "./fixtures";
async function openHub(page: Page, width = 1024) {
@@ -28,45 +27,6 @@ async function readPreviewOnFocus(page: Page) {
});
}
async function useLargerText(page: Page, size = "125%") {
await page.addStyleTag({ content: `html { font-size: ${size}; }` });
}
async function expectSourceLabelFits(page: Page, name: string, text = name) {
const label = page.getByRole("tab", { name }).getByText(text, { exact: true });
await expect(label).toBeVisible();
expect(await label.evaluate((element) => element.scrollWidth <= element.clientWidth)).toBe(true);
}
async function expectPreviewRowsFit(page: Page, source: string, ...rows: string[]) {
const name = new RegExp(`^${source}`);
await page.getByRole("tab", { name }).click();
const preview = page.getByRole("tabpanel", { name });
await preview.scrollIntoViewIfNeeded();
for (const row of rows) {
const text = preview.getByText(row, { exact: true }).filter({ visible: true });
await expect(text.first()).toBeVisible();
for (const match of await text.all()) {
await expect
.poll(() =>
match.evaluate((element) => {
const frame = element.closest('[role="img"]')!.getBoundingClientRect();
const range = document.createRange();
range.selectNodeContents(element);
return Array.from(range.getClientRects()).every(
(rect) =>
rect.left >= frame.left - 1 &&
rect.right <= frame.right + 1 &&
rect.top >= frame.top - 1 &&
rect.bottom <= frame.bottom + 1,
);
}),
)
.toBe(true);
}
}
}
async function focusProSeatHelp(page: Page) {
// Hydration scrolls the window back to the top, which would carry the tooltip off screen.
await waitForHydration(page);
@@ -79,15 +39,6 @@ async function focusProSeatHelp(page: Page) {
return pro.getByRole("tooltip");
}
test("Hub fits a viewport narrower than its page frame", async ({ page }) => {
await openHub(page);
const { contentWidth, viewportWidth } = await page.evaluate(() => ({
contentWidth: document.documentElement.scrollWidth,
viewportWidth: document.documentElement.clientWidth,
}));
expect(contentWidth).toBeLessThanOrEqual(viewportWidth);
});
for (const width of [320, 768, 1024]) {
test(`the complete Pro seat explanation is visible on keyboard focus at ${width}px`, async ({
page,
@@ -115,53 +66,3 @@ test("keyboard focus enters the selected preview with its current content", asyn
await expect(page.getByRole("tabpanel", { name: /^GitHub/ })).toBeFocused();
expect((await atFocus.jsonValue()).label).toMatch(/^GitHub issue/);
});
test("source names fit on a narrow phone", async ({ page }) => {
await openHub(page, 320);
await expectSourceLabelFits(page, "Schedules");
await expectSourceLabelFits(page, "Webhooks");
});
test("source names remain readable with larger text on a phone", async ({ page }) => {
await openHub(page, 375);
await useLargerText(page);
for (const name of ["GitHub", "Discord", "Schedules", "Webhooks"]) {
await expectSourceLabelFits(page, name);
}
});
test("desktop source descriptions fit with larger text", async ({ page }) => {
await openHub(page, 1280);
await useLargerText(page);
for (const { name, description } of Object.values(copy.hub.sources)) {
await expectSourceLabelFits(page, name, description);
}
});
test("Hub previews have room for their final rows with larger text", async ({ page }) => {
await page.emulateMedia({ reducedMotion: "reduce" });
await openHub(page, 1280);
await useLargerText(page);
await waitForHydration(page);
await expectPreviewRowsFit(page, "GitHub", "Open in Paseo");
await expectPreviewRowsFit(page, "Discord", "Message #engineering");
});
test("preview results fit on a narrow phone with larger text", async ({ page }) => {
await page.emulateMedia({ reducedMotion: "reduce" });
await openHub(page, 320);
await useLargerText(page);
await waitForHydration(page);
await expectPreviewRowsFit(page, "Discord", "Fix stale worktrees", "getpaseo/paseo#2825");
await expectPreviewRowsFit(page, "Schedules", "tests passed");
});
test("Hub previews keep their rows visible with twice the default font size", async ({ page }) => {
await page.emulateMedia({ reducedMotion: "reduce" });
await openHub(page, 320);
await useLargerText(page, "200%");
await waitForHydration(page);
await expectPreviewRowsFit(page, "Slack", "Open in Paseo");
await expectPreviewRowsFit(page, "Linear", "PAS-418");
await expectPreviewRowsFit(page, "Discord", "tests passed", "Message #engineering");
});

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