Compare commits

..
Author SHA1 Message Date
paseo-bot[bot] a6b5db65ed test(app): reproduce failed workspace status overwritten by creation 2026-10-15 20:09:01 +02:00
Mohamed Boudra fd1e7a34ce docs(changelog): welcome Hoplite as first sponsor in 0.11.3 2026-10-15 19:06:24 +02:00
Mohamed Boudra ce0f21e2ff docs(changelog): 0.11.3
Cherry-picked from ed53a7193 on release/0.11.3-hoplite (tag v0.11.3).
2026-10-15 18:58:16 +02:00
paseo-bot[bot] d172d060a5 server: keep streamed OpenCode v2 chunks from holding their whole message (#6262)
Each streamed text or reasoning chunk was cut from the accumulated
message with slice, which can share the source string's storage. The
timeline store keeps every chunk, so a 128 KB reasoning part retained
about 128 MB: every chunk held the full message as it stood when the
chunk arrived. Long OpenCode v2 reasoning streams exhausted the daemon
worker's heap.

The timeline now emits an independent copy of each suffix, so retained
memory follows the length of the text.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-10-15 18:28:07 +02:00
Mohamed Boudra 2d86b94b2f Refine provider catalog buttons and show Add errors as toasts (#7030)
* fix(app): refine provider catalog actions and error feedback

Use compact row tiles and the shared error toast so failed Add actions remain visible while browsing the catalog. Point Hoplite installation instructions at the CLI install section.

* test(app): supply toast context in provider settings tests

Import the toast API independently of its renderer so the provider section only depends on the context it consumes.
2026-10-15 22:45:12 +07:00
Mohamed Boudra d6d4084a06 docs(plugins): make registry publishing requirements actionable (#6996)
* docs(plugins): explain registry publishing requirements

* docs(plugins): trim publishing guidance to author tasks
2026-10-15 21:38:38 +07:00
Mohamed BoudraandOdin Glynn-Martin 16bb179e67 feat(providers): add opt-in Hoplite and searchable provider grid (#6953)
Preserve the bundled Hoplite ACP adapter and provisioning transformer, activate it only after Add, and provide a searchable provider grid. Restore the contributor's original icon without the copyright mark.

Co-authored-by: Odin Glynn-Martin <odin.glynn@icloud.com>
2026-10-15 21:25:23 +07:00
Mohamed Boudra e08389065c fix(plugins): allow protocol type imports without local dependencies (#7023)
Protocol contracts are available through the SDK peer dependency during development, but clean Git installs lack that dependency tree. Accept erased protocol type imports while retaining runtime dependency resolution and SDK ownership checks.
2026-10-15 21:13:00 +07:00
paseo-bot[bot]andGrant Ammons 80badb3b8f fix(opencode): answer multi-select v2 questions from the question card (#6149)
Closes #6135

Co-authored-by: Grant Ammons <grant@grant.dev>
2026-10-15 15:15:19 +02:00
71f575e16a Keep malformed Claude question answers retryable (#6936)
* fix: reject a question permission that would deliver no answer

Answering an `AskUserQuestion` permission in any shape but
`updatedInput.answers` keyed by one of its questions resolves as `allow` and
delivers nothing. The waiting agent is told "The user did not answer the
questions." — an affirmative falsehood rather than silence, so neither side can
see that anything failed. The responder sees success; the agent believes the
human declined and acts on that.

The field it is most natural to reach for cannot work. `selectedActionId` is
`z.string().optional()` with no membership check, and is read only for `plan`
kinds; a question advertises `actions: undefined`, so there is no action id to
name in the first place.

It is also unrecoverable. `respondToPermission` deletes the request from
`pendingPermissions` on entry, so the malformed answer consumes it and the retry
fails with "No pending permission request". The guard runs before that delete,
and `AgentManager` drops its own copy only once the call resolves, so both maps
survive the throw and the request stays answerable.

The answer contract is per provider, so the guard is in the Claude provider
rather than in `AgentManager`. Claude keeps an answer only when its key is a
question's full text or its header and its value is a non-empty string; Codex's
`mapCodexQuestionResponseByHeader` reads headers only and deliberately selects
each question's first option when nothing maps, which a shared guard would have
rejected; OpenCode reads headers only as well.

`resolveClaudeAskUserQuestionAnswers` is extracted from
`normalizeClaudeAskUserQuestionUpdatedInput` with no change in behaviour, and
both it and the guard now use it. So "would this deliver anything" is answered
by the code that does the delivering, rather than by a second copy of its rule —
which matters more than it looks, because that rule has two details easy to
restate wrongly: `readNonEmptyString` tests `value.trim()` for emptiness but
returns the *original* string, so a question named `" Which colour? "` is keyed
by that padding; and an empty `updatedInput.questions` array is a list that wins
over the request's own questions and maps nothing, not an absent one.

Verified on a live daemon over the MCP `respond_to_permission` path against a
seat whose question text is literally `" Which colour? "`: `selectedActionId`,
the trimmed key, an empty echoed question list and a numeric answer are each
rejected with the request still pending, and
`{"answers":{" Which colour? ":"Ochre"}}` then reaches the agent.

One known limit: the WebSocket path (`session.ts handleAgentPermissionResponse`)
catches the throw and emits an `activity_log` error rather than failing the
call, because a permission response is modelled as a notification. So
`paseo permit allow` still prints `allowed` and exits 0 for a rejected shape.
The destructive half is closed on every path — the request survives and the
agent is never told a falsehood — but closing the reporting half needs a
protocol change.

* test(claude): cover the question-answer-required retry path

A non-deliverable answer to an AskUserQuestion permission is rejected, but
the pending request survives it: a corrected retry against the same request
id is accepted, and the waiting agent receives the answer.

Mutation testing on a fork found that the existing suite does not pin this
ordering — moving the deliverability check to run after the request is
deleted from pendingPermissions still leaves every existing test green. This
test reds against that change.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: Thomas Van <minhthong@gmail.com>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: paseo-bot <paseo-bot@users.noreply.github.com>
2026-10-15 14:21:03 +02:00
72 changed files with 2008 additions and 438 deletions
+17
View File
@@ -1,5 +1,22 @@
# Changelog
## 0.11.3 - 2026-10-15
[Hoplite](https://hoplite.sh) joins Paseo as our first sponsor through the company sponsorship program. Hoplite builds cloud coding agents that turn tasks from GitHub, Linear, Slack and more into pull requests. Thank you to the Hoplite team for supporting Paseo.
### Added
- Added Hoplite as an opt-in provider in the ACP provider catalog ([#6953](https://github.com/getpaseo/paseo/pull/6953) by [@odinglyn0](https://github.com/odinglyn0))
- Added search to the Add provider catalog ([#6953](https://github.com/getpaseo/paseo/pull/6953), [#7030](https://github.com/getpaseo/paseo/pull/7030))
### Changed
- Changed Add provider failures to show as a toast ([#7030](https://github.com/getpaseo/paseo/pull/7030))
### Fixed
- Fixed Remove being offered for plugin providers such as Antigravity and Muse Code ([#6568](https://github.com/getpaseo/paseo/pull/6568) by [@Ctrl-Creeper](https://github.com/Ctrl-Creeper))
## 0.11.2 - 2026-10-09
### Fixed
+1 -1
View File
@@ -484,7 +484,7 @@ The [Agent Client Protocol (ACP)](https://agentclientprotocol.com) is an open st
ACP agents communicate over JSON-RPC 2.0 on stdio. Paseo spawns the agent process and talks to it through stdin/stdout.
Paseo also ships an in-app ACP provider catalog for common agents, including CodeWhale, Cursor, DeepAgents, DimCode, Gemini CLI, Hermes, Qwen Code, and Kimi Code. Catalog entries create the same `extends: "acp"` provider config shown below.
Paseo also ships an in-app ACP provider catalog for common agents, including CodeWhale, Cursor, DeepAgents, DimCode, Gemini CLI, Hermes, Qwen Code, and Kimi Code. Most catalog entries create the same `extends: "acp"` provider config shown below. Hoplite activates its [bundled provider](plugins.md#built-in-plugins) instead.
### Adding a generic ACP provider
+6
View File
@@ -107,6 +107,12 @@ absent from the installed plugin list and source configuration; their client bun
appear in the plugin catalog. Editing one in development requires a daemon restart.
Directory, Git, and npm installs cannot use a built-in ID.
A provider registration with `requiresConfiguration: true` participates only while its ID exists
under `agents.providers`. Hoplite uses this for catalog opt-in. Add writes `{ "enabled": true }`
without `extends`, so it selects the bundled adapter. Remove deletes the config entry; setting
`enabled: false` keeps the entry. The bundled JavaScript still loads at startup, but an absent
provider does not enter executable resolution or catalog discovery.
Provider plugins use separate installation and provider IDs. `muse-provider` registers the
selectable `muse` provider (Muse Code) and a usage source. Its `status({ launch })` reports
availability and a diagnostic after the daemon resolves the executable. Configure command,
@@ -1,13 +1,24 @@
import { test } from "../support/fixtures";
import {
closeModelPicker,
openModelPicker,
seedAgentProfiles,
} from "../support/helpers/agent-profiles";
import { expectComposerVisible } from "../support/helpers/composer";
import { clickNewChat, gotoWorkspace } from "../support/helpers/launcher";
import { seedWorkspace } from "../support/helpers/seed-client";
import { writeFile } from "node:fs/promises";
import { expect, test } from "../support/fixtures";
import { gotoAppShell, openSettings } from "../support/helpers/app";
import { connectDaemonClient } from "../support/helpers/daemon-client-loader";
import { getServerId } from "../support/helpers/server-id";
import {
expectProviderInstalledInSettings,
findAcpCatalogProvider,
installAcpCatalogProvider,
openAddProviderArea,
openSettingsHost,
openSettingsHostSection,
seedSavedSettingsHosts,
} from "../support/helpers/settings";
const ACP_PROVIDER = {
@@ -16,8 +27,13 @@ const ACP_PROVIDER = {
};
interface ProviderCatalogDaemonClient {
getLastServerInfoMessage(): {
features?: { hopliteProvider?: boolean; plugins?: boolean };
} | null;
connect(): Promise<void>;
close(): Promise<void>;
getDaemonConfig(): Promise<{ config: { providers?: Record<string, unknown> } }>;
getProvidersSnapshot(): Promise<{ entries: Array<{ provider: string }> }>;
patchDaemonConfig(config: { removeProviders?: string[] }): Promise<unknown>;
}
@@ -41,3 +57,124 @@ test.describe("ACP provider catalog", () => {
}
});
});
for (const theme of ["light", "dark"] as const) {
test(`adds Hoplite from the catalog in ${theme} theme`, async ({ page }, testInfo) => {
const client = await connectDaemonClient<ProviderCatalogDaemonClient>({
clientIdPrefix: "hoplite-catalog-e2e",
});
try {
expect(client.getLastServerInfoMessage()?.features?.hopliteProvider).toBe(true);
await client.patchDaemonConfig({ removeProviders: ["hoplite"] });
expect(
(await client.getProvidersSnapshot()).entries.some((entry) => entry.provider === "hoplite"),
).toBe(false);
await page.addInitScript((value) => {
localStorage.setItem("@paseo:app-settings", JSON.stringify({ theme: value }));
}, theme);
await gotoAppShell(page);
await openSettings(page);
await openSettingsHost(page, getServerId());
await openSettingsHostSection(page, getServerId(), "providers");
await expect(
page.getByRole("button", { name: "Hoplite provider details", exact: true }),
).toHaveCount(0);
await openAddProviderArea(page);
await findAcpCatalogProvider(page, "Hoplite");
await page.screenshot({ path: testInfo.outputPath(`hoplite-catalog-${theme}.png`) });
await installAcpCatalogProvider(page, "Hoplite");
await expectProviderInstalledInSettings(page, "Hoplite");
await page.screenshot({ path: testInfo.outputPath(`hoplite-installed-${theme}.png`) });
expect((await client.getDaemonConfig()).config.providers?.hoplite).toEqual({ enabled: true });
await writeFile(
testInfo.outputPath(`hoplite-added-${theme}.json`),
JSON.stringify(await client.getProvidersSnapshot(), null, 2),
);
await removeHoplite(page);
await expect(
page.getByRole("button", { name: "Hoplite provider details", exact: true }),
).toHaveCount(0);
expect((await client.getDaemonConfig()).config.providers?.hoplite).toBeUndefined();
expect(
(await client.getProvidersSnapshot()).entries.some((entry) => entry.provider === "hoplite"),
).toBe(false);
await writeFile(
testInfo.outputPath(`hoplite-removed-${theme}.json`),
JSON.stringify(await client.getProvidersSnapshot(), null, 2),
);
await openAddProviderArea(page);
await findAcpCatalogProvider(page, "Hoplite");
await page.screenshot({ path: testInfo.outputPath(`hoplite-removed-${theme}.png`) });
await installAcpCatalogProvider(page, "Hoplite");
await expectProviderInstalledInSettings(page, "Hoplite");
} finally {
await client.patchDaemonConfig({ removeProviders: ["hoplite"] }).catch(() => undefined);
await client.close().catch(() => undefined);
}
});
}
async function removeHoplite(page: import("@playwright/test").Page): Promise<void> {
await page.getByTestId("provider-actions-hoplite").click();
page.once("dialog", (dialog) => {
void dialog.accept();
});
await page.getByTestId("provider-remove-hoplite").click();
}
test("unsupported host asks for an update without writing Hoplite config", async ({
page,
outdatedDaemon,
}, testInfo) => {
const client = await connectDaemonClient<ProviderCatalogDaemonClient>({
clientIdPrefix: "hoplite-unsupported",
port: Number(new URL(`http://${outdatedDaemon.endpoint}`).port),
});
try {
expect(client.getLastServerInfoMessage()?.features?.plugins).toBe(true);
expect(client.getLastServerInfoMessage()?.features?.hopliteProvider).toBe(false);
const before = await client.getDaemonConfig();
await seedSavedSettingsHosts(page, [outdatedDaemon]);
await page.reload();
await openSettings(page);
await openSettingsHost(page, outdatedDaemon.serverId);
await openSettingsHostSection(page, outdatedDaemon.serverId, "providers");
await openAddProviderArea(page);
await page.getByRole("button", { name: "Add Hoplite", exact: true }).click();
const errorToast = page.getByTestId("app-toast-message");
await expect(errorToast).toHaveText("Update the host to add Hoplite.");
await expect(errorToast).toBeInViewport();
expect((await client.getDaemonConfig()).config).toEqual(before.config);
await expect(
page.getByRole("button", { name: "Hoplite provider details", exact: true }),
).toHaveCount(0);
await page.screenshot({ path: testInfo.outputPath("hoplite-update-host.png") });
} finally {
await client.close();
}
});
test("model selector excludes Hoplite before opt-in", async ({ page }, testInfo) => {
const client = await connectDaemonClient<ProviderCatalogDaemonClient>({
clientIdPrefix: "hoplite-picker",
});
const profiles = await seedAgentProfiles([
{ id: "hoplite-picker-anchor", name: "Picker anchor", provider: "mock" },
]);
const workspace = await seedWorkspace({ repoPrefix: "hoplite-picker-" });
try {
await client.patchDaemonConfig({ removeProviders: ["hoplite"] });
await gotoWorkspace(page, workspace.workspaceId);
await clickNewChat(page);
await expectComposerVisible(page);
await openModelPicker(page);
await expect(page.getByTestId("model-provider-mock")).toBeVisible();
await expect(page.getByTestId("model-provider-hoplite")).toHaveCount(0);
await page.screenshot({ path: testInfo.outputPath("hoplite-model-selector-absent.png") });
await closeModelPicker(page);
} finally {
await workspace.cleanup();
await profiles.restore();
await client.close();
}
});
@@ -133,6 +133,58 @@ test("scroll detector accounts for delayed wheel input and growth below the new
).toHaveLength(1);
});
test("scroll detector follows the entered image through resize and virtual offset correction", () => {
for (const height of [225, 1632]) {
const before: ScrollFrame = {
at: 1000,
scrollTop: 2208,
scrollHeight: 5000,
viewportHeight: 516,
virtualized: true,
loading: false,
rows: [
{ id: "image", top: -704, height: 560 },
{ id: "caption", top: -144, height: 100 },
{ id: "old-reader", top: -44, height: 127 },
],
anchor: "old-reader",
wheelTotal: 0,
lastWheelAt: 0,
inputFinishedAt: null,
imageLoads: 0,
mounted: 3,
unmounted: 0,
};
const resize = height - 560;
const after: ScrollFrame = {
...before,
at: 1060,
// The virtualizer corrects 110px of estimates while the wheel moves 160px.
scrollTop: 1938,
scrollHeight: 5000 + resize - 110,
wheelTotal: 160,
lastWheelAt: 1020,
imageLoads: 1,
rows: [
{ id: "image", top: -544, height },
{ id: "caption", top: 16 + resize, height: 100 },
{ id: "old-reader", top: 116 + resize, height: 127 },
],
};
expect(findScrollJumps([before, after])).toEqual([]);
// Resizing must not excuse additional viewport movement.
expect(
findScrollJumps([
before,
{
...after,
rows: after.rows.map((row) => ({ id: row.id, height: row.height, top: row.top + 100 })),
},
]),
).toHaveLength(1);
}
});
for (const cadence of scrollCadences) {
test(`varied timeline preserves reading position during ${cadence.name} upward scrolling`, async ({
page,
@@ -0,0 +1,117 @@
import { mkdirSync, rmSync, writeFileSync } from "node:fs";
import path from "node:path";
import type { Page } from "@playwright/test";
import { test, expect } from "../support/fixtures";
import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate";
import { seedWorkspace } from "../support/helpers/seed-client";
import { gotoWorkspace } from "../support/helpers/launcher";
import { waitForSidebarHydration } from "../support/helpers/workspace-ui";
import {
openGlobalNewWorkspaceComposer,
submitNewWorkspacePrompt,
} from "../support/helpers/new-workspace";
import { chooseModel, startWithoutRememberedModel } from "../support/helpers/model-memory";
import { selectSidebarStatusGrouping } from "../support/helpers/sidebar";
// Diagnostic reproduction for #7043. Keep provider state inside the checkout.
const piAgentDirectory = path.resolve(__dirname, "../../../../.diagnose-7043-pi-agent");
test.use({
e2eDaemonConfig: {
version: 1,
agents: {
providers: {
pi: { models: [{ id: "anthropic/claude-sonnet-4-5", label: "Claude Sonnet 4.5" }] },
},
},
},
e2eDaemonEnvironment: {
PI_CODING_AGENT_DIR: piAgentDirectory,
ANTHROPIC_API_KEY: "",
OPENAI_API_KEY: "",
OPENROUTER_API_KEY: "",
},
});
test.beforeAll(() => {
mkdirSync(piAgentDirectory, { recursive: true });
writeFileSync(path.join(piAgentDirectory, "auth.json"), "{}\n");
});
test.afterAll(() => rmSync(piAgentDirectory, { recursive: true, force: true }));
interface WorkspaceFrame {
type: string;
status?: string;
phase?: string;
}
function recordWorkspaceFrames(page: Page): WorkspaceFrame[] {
const frames: WorkspaceFrame[] = [];
page.on("websocket", (socket) =>
socket.on("framereceived", ({ payload }) => {
const envelope = JSON.parse(String(payload));
const message = envelope.message ?? envelope;
if (
message.type === "workspace_update" ||
message.type === "workspace.create.response" ||
message.type === "workspace.create.update"
) {
frames.push({
type: message.type,
status: message.payload?.workspace?.status,
phase: message.payload?.phase,
});
}
}),
);
return frames;
}
async function startFailedPiWorkspace(page: Page): Promise<void> {
await waitForSidebarHydration(page);
await selectSidebarStatusGrouping(page);
await openGlobalNewWorkspaceComposer(page);
await chooseModel(page, "pi", "Claude Sonnet 4.5");
await submitNewWorkspacePrompt(page, "Reply OK.");
}
async function expectFailedWorkspaceOutsideWorking(page: Page): Promise<void> {
await expect(page.getByText(/No API key found/).first()).toBeVisible({ timeout: 60_000 });
await expect(page.getByText("Worked for 0s", { exact: true }).first()).toBeVisible();
await expect(page.getByLabel("Working group", { exact: true })).not.toBeVisible();
await expect(page.getByLabel("Failed group", { exact: true })).toBeVisible();
}
for (const lateResponse of [false, true]) {
test(`failed first Pi turn leaves Working with ${lateResponse ? "creation response last" : "ordinary delivery"}`, async ({
page,
}) => {
test.setTimeout(120_000);
const workspace = await seedWorkspace({ repoPrefix: "failed-workspace-status-" });
const frames = recordWorkspaceFrames(page);
const gate = await installDaemonWebSocketGate(page);
try {
await startWithoutRememberedModel(page);
await gotoWorkspace(page, workspace.workspaceId);
if (lateResponse) gate.holdNextServerMessage("workspace.create.response");
await startFailedPiWorkspace(page);
if (lateResponse) {
await gate.waitForHeldServerMessage("workspace.create.response");
// Adapted timing: deliver the real response after both real failure updates.
await expect
.poll(
() =>
frames.filter(
(frame) => frame.type === "workspace_update" && frame.status === "failed",
).length,
)
.toBeGreaterThanOrEqual(2);
gate.releaseHeldServerMessage("workspace.create.response");
}
await expectFailedWorkspaceOutsideWorking(page);
} finally {
console.log("WORKSPACE FRAMES", JSON.stringify(frames));
await page.screenshot({ path: test.info().outputPath("failed-sidebar.png") });
await workspace.cleanup();
}
});
}
+1 -1
View File
@@ -370,7 +370,7 @@ export async function findAcpCatalogProvider(page: Page, providerName: string):
export async function installAcpCatalogProvider(page: Page, providerName: string): Promise<void> {
await findAcpCatalogProvider(page, providerName);
await page.getByRole("button", { name: "Add", exact: true }).click();
await page.getByRole("button", { name: `Add ${providerName}`, exact: true }).click();
}
export async function expectProviderInstalledInSettings(
@@ -297,11 +297,7 @@ export function findScrollJumps(frames: ScrollFrame[]) {
// Follow that intended row, not text now below the image.
const recent = frames.findLast((frame) => frame.at <= previous.at - 100);
const wheelBudget = current.wheelTotal - (recent?.wheelTotal ?? 0);
const frameScroll = Math.max(0, previous.scrollTop - current.scrollTop);
const availableScroll = Math.min(frameScroll, wheelBudget, previous.scrollTop);
const readingLine = 8 - availableScroll;
const currentRows = new Map(current.rows.map((row) => [row.id, row]));
const intendedRow = previous.rows.find((row) => row.top + row.height > readingLine);
const anchor = previous.anchor;
const before = currentRows.has(anchor)
? previous.rows.find((row) => row.id === anchor)!
@@ -316,25 +312,33 @@ export function findScrollJumps(frames: ScrollFrame[]) {
// A busy main thread can deliver wheel movement hundreds of milliseconds
// after its event. Only assert idle stability after the driver stops input.
const idle = current.inputFinishedAt !== null && previous.at - current.inputFinishedAt > 250;
// Wheel events can precede their scroll update, or include input already
// applied in earlier frames. Locate the reader with this frame's scroll,
// bounded by recent input. Growth below it can move the old anchor without
// moving the reading line.
const readerFollowsInput =
intendedRow &&
currentRows.has(intendedRow.id) &&
Math.abs(currentRows.get(intendedRow.id)!.top - intendedRow.top - availableScroll) <= 32;
const enteredRowGrowth = readerFollowsInput
// scrollTop also includes virtualizer estimate corrections. Locate the row
// entered by wheel input from its viewport movement instead. Its old height
// identifies the reader before a simultaneous image resize takes effect.
const intendedRow = previous.rows.find((row) => {
const next = currentRows.get(row.id);
if (!next || idle || wheelBudget <= 0) return false;
const travel = next.top - row.top;
return (
travel >= -8 &&
travel <= Math.min(wheelBudget, previous.scrollTop) + 32 &&
(next.top <= 8 || current.scrollTop === 0) &&
next.top + row.height > 8
);
});
const enteredRowResize = intendedRow
? previous.rows.reduce((growth, row) => {
if (row.top < intendedRow.top || row.top >= before.top) return growth;
const height = currentRows.get(row.id)?.height ?? row.height;
return growth + Math.max(0, height - row.height);
return growth + height - row.height;
}, 0)
: 0;
const excessForward = movement > wheelBudget + enteredRowGrowth + 32;
const readingMovement = movement - enteredRowResize;
const excessForward = readingMovement > wheelBudget + 32;
// Upward wheel input moves the same text DOWN the viewport. A negative move
// is a reversal, independent of legitimate scrollTop compensation on prepend.
if (movement >= -8 && (!idle || Math.abs(movement) <= 8) && !excessForward) return [];
if (readingMovement >= -8 && (!idle || Math.abs(readingMovement) <= 8) && !excessForward)
return [];
return [
{
frame: index,
@@ -48,6 +48,8 @@ export const ACP_PROVIDER_ICON_SVGS = {
goose:
'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24">\n <path fill="currentColor" d="M20.9093 19.3861L19.5185 18.2413C18.7624 17.619 18.1189 16.8713 17.6157 16.0313C16.9205 14.8706 15.9599 13.8912 14.8133 13.1735L14.2533 12.8475C14.0614 12.7141 13.9276 12.5062 13.9086 12.2716C13.8963 12.1204 13.9326 11.9852 14.0171 11.8662C14.3087 11.4553 15.896 9.74698 16.1722 9.51845C16.528 9.22442 16.9243 8.97987 17.2921 8.69986C17.3443 8.66 17.3968 8.62035 17.4485 8.57989C17.4503 8.57808 17.4529 8.57668 17.4545 8.57508C17.5725 8.48195 17.6838 8.383 17.7724 8.26563C18.2036 7.76631 18.195 7.3443 18.195 7.3443C18.195 7.3443 18.1954 7.3439 18.1956 7.3437C18.1497 7.23133 17.9847 6.88163 17.6492 6.71759C17.9458 6.71178 18.2805 6.82294 18.4323 6.97156C18.6148 6.68534 18.7328 6.49967 18.9162 6.18762C18.9599 6.11352 18.9831 5.97652 18.8996 5.89981C18.8996 5.89981 18.8992 5.89981 18.8988 5.89981C18.8988 5.89981 18.8988 5.8994 18.8988 5.899C18.8972 5.8974 18.8952 5.8962 18.8936 5.8946C18.892 5.893 18.891 5.89119 18.8892 5.88939C18.8892 5.88939 18.8888 5.88939 18.8884 5.88939C18.8884 5.88939 18.8884 5.88899 18.8884 5.88859C18.885 5.88518 18.8812 5.88258 18.8776 5.87938C18.8754 5.87717 18.8736 5.87457 18.8716 5.87217C18.8692 5.87016 18.8665 5.86836 18.8643 5.86616C18.8609 5.86275 18.8587 5.85855 18.8551 5.85534C18.8551 5.85534 18.8545 5.85514 18.8543 5.85534C18.8543 5.85534 18.8543 5.85494 18.8543 5.85454C18.8527 5.85294 18.8507 5.85174 18.8491 5.85013C18.8475 5.84853 18.8463 5.84653 18.8447 5.84493C18.8447 5.84493 18.8441 5.84473 18.8439 5.84493C18.8439 5.84493 18.8439 5.84453 18.8439 5.84413C18.7672 5.7606 18.6302 5.78384 18.5561 5.8275C18.1503 6.06625 17.7555 6.32322 17.3996 6.54855C17.3996 6.54855 16.9778 6.53973 16.4783 6.97116C16.3607 7.05989 16.2618 7.17125 16.1688 7.28902C16.167 7.29082 16.1654 7.29322 16.164 7.29503C16.1234 7.3465 16.0837 7.39898 16.0441 7.45145C15.7639 7.81939 15.5195 8.21556 15.2255 8.57128C14.9971 8.84768 13.2887 10.4348 12.8777 10.7264C12.7587 10.8109 12.6237 10.8474 12.4723 10.835C12.2379 10.8161 12.0298 10.6821 11.8965 10.4903L11.5704 9.93024C10.8527 8.78318 9.87332 7.82299 8.71264 7.12778C7.87262 6.62466 7.12514 5.98092 6.50264 5.22503L5.35778 3.83421C5.3013 3.76571 5.19314 3.77693 5.15268 3.85585C5.02249 4.10941 4.77393 4.64479 4.58346 5.36483C4.57885 5.38186 4.58286 5.39988 4.59407 5.4135C4.83082 5.69952 5.37901 6.32983 6.03196 6.863C6.07742 6.90005 6.04017 6.97336 5.98369 6.95774C5.42047 6.80432 4.87288 6.55796 4.46308 6.34805C4.42964 6.33103 4.38918 6.35226 4.38437 6.38951C4.32068 6.89985 4.30425 7.46027 4.37155 8.05112C4.37355 8.07035 4.38577 8.08697 4.4036 8.09479C4.87088 8.29808 5.61816 8.59311 6.40269 8.78078C6.45958 8.7944 6.45777 8.87632 6.40029 8.88733C5.78941 9.0023 5.14968 9.02794 4.62973 9.02113C4.59327 9.02073 4.56643 9.05518 4.57625 9.09023C4.6806 9.45896 4.822 9.8339 5.00847 10.2115C5.08559 10.3811 5.16951 10.5475 5.25944 10.7104C5.27486 10.7382 5.3047 10.7548 5.33655 10.7534C5.76577 10.7324 6.28452 10.6871 6.80608 10.595C6.89501 10.5794 6.94268 10.6964 6.86757 10.7466C6.51345 10.9834 6.13571 11.1873 5.7844 11.3551C5.73733 11.3777 5.72211 11.4378 5.75315 11.4797C5.96186 11.7625 6.19139 12.0301 6.44075 12.2794C6.44075 12.2794 7.66853 13.5441 7.70198 13.6432C8.41841 12.9096 9.59612 12.0964 10.8966 11.3864C9.15488 12.8036 8.18387 13.8499 7.69517 14.4444L7.35447 14.9225C7.17742 15.1708 7.02379 15.4346 6.89541 15.7112C6.46579 16.6356 5.75756 18.5051 5.75756 18.5051C5.70328 18.6515 5.74754 18.7959 5.84168 18.89C5.84388 18.8922 5.84609 18.8944 5.84849 18.8964C5.85069 18.8986 5.8527 18.901 5.8549 18.9032C5.94924 18.9976 6.09345 19.0416 6.23986 18.9874C6.23986 18.9874 8.10897 18.2791 9.03371 17.8495C9.31031 17.7211 9.57429 17.5673 9.82245 17.3905L10.349 17.0153C10.6278 16.8166 11.0096 16.8483 11.2517 17.0904L12.4655 18.3042C12.7148 18.5535 12.9824 18.7831 13.2652 18.9918C13.3073 19.0226 13.3672 19.0076 13.3898 18.9605C13.5579 18.6094 13.7618 18.2313 13.9983 17.8774C14.0486 17.8022 14.1657 17.8501 14.1499 17.9388C14.0576 18.4606 14.0127 18.9794 13.9915 19.4084C13.9899 19.44 14.0067 19.4701 14.0345 19.4855C14.1972 19.5756 14.3636 19.6595 14.5335 19.7364C14.911 19.9229 15.2862 20.0645 15.6547 20.1687C15.6897 20.1785 15.7242 20.1516 15.7238 20.1152C15.7168 19.595 15.7424 18.9553 15.8576 18.3446C15.8684 18.2869 15.9503 18.2851 15.9641 18.3422C16.1516 19.127 16.4466 19.8742 16.6501 20.3413C16.6579 20.3591 16.6744 20.3712 16.6938 20.3734C17.2847 20.4407 17.8451 20.4242 18.3554 20.3606C18.3929 20.3559 18.4141 20.3155 18.3969 20.2818C18.187 19.872 17.9406 19.3241 17.7872 18.7612C17.7718 18.7046 17.8449 18.6675 17.8819 18.713C18.4151 19.3659 19.0454 19.9141 19.3314 20.1508C19.345 20.1621 19.3633 20.1659 19.3801 20.1615C20.1003 19.9712 20.6357 19.7226 20.8891 19.5922C20.968 19.5518 20.9792 19.4436 20.9107 19.3871L20.9093 19.3861Z"/>\n</svg>\n',
grok: '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 1024 1024" fill="none">\n <path fill="currentColor" d="M395.479 633.828L735.91 381.105C752.599 368.715 776.454 373.548 784.406 392.792C826.26 494.285 807.561 616.253 724.288 699.996C641.016 783.739 525.151 802.104 419.247 760.277L303.556 814.143C469.49 928.202 670.987 899.995 796.901 773.282C896.776 672.843 927.708 535.937 898.785 412.476L899.047 412.739C857.105 231.37 909.358 158.874 1016.4 10.6326C1018.93 7.11771 1021.47 3.60279 1024 0L883.144 141.651V141.212L395.392 633.916"/>\n <path fill="currentColor" d="M325.226 695.251C206.128 580.84 226.662 403.776 328.285 301.668C403.431 226.097 526.549 195.254 634.026 240.596L749.454 186.994C728.657 171.88 702.007 155.623 671.424 144.2C533.19 86.9942 367.693 115.465 255.323 228.382C147.234 337.081 113.244 504.215 171.613 646.833C215.216 753.423 143.739 828.818 71.7385 904.916C46.2237 931.893 20.6216 958.87 0 987.429L325.139 695.339"/>\n</svg>\n',
hoplite:
'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="1.394 1.679 8.494 7.828" fill="currentColor"><path d="M8.237 7.813C8.276 7.789 8.327 7.796 8.358 7.83L9.741 9.346C9.797 9.407 9.754 9.506 9.671 9.507H8.977C8.924 9.507 8.881 9.463 8.881 9.41V9.125C8.881 9.089 8.861 9.057 8.83 9.04L7.589 8.379C7.524 8.344 7.521 8.251 7.584 8.212L8.237 7.813ZM3.944 1.679C4.502 1.679 5.052 1.82 5.54 2.09L5.962 2.323C6.024 2.358 6.029 2.446 5.97 2.486L5.091 3.09C5.065 3.108 5.05 3.137 5.05 3.169V3.495C5.05 3.529 5.032 3.561 5.003 3.578L4.68 3.769C4.594 3.82 4.498 3.722 4.549 3.637L4.592 3.566C4.63 3.502 4.584 3.421 4.51 3.421H4.028C3.925 3.421 3.894 3.562 3.989 3.604L4.377 3.775C4.448 3.806 4.455 3.904 4.389 3.944L3.77 4.323C3.755 4.332 3.737 4.337 3.72 4.337H3.361C3.309 4.337 3.268 4.379 3.268 4.431C3.268 4.484 3.309 4.526 3.361 4.526H3.779C3.797 4.526 3.814 4.521 3.829 4.513L7.599 2.272C8.135 1.954 8.815 2.008 9.294 2.407C9.307 2.418 9.314 2.434 9.314 2.451V2.729C9.315 2.812 9.413 2.856 9.475 2.8L9.728 2.57C9.789 2.514 9.888 2.558 9.888 2.641V5.812C9.888 5.865 9.845 5.908 9.792 5.908H9.359C9.331 5.908 9.303 5.895 9.285 5.873L8.374 4.773C8.337 4.728 8.268 4.728 8.229 4.771L7.468 5.625C7.429 5.669 7.438 5.737 7.487 5.769L9.038 6.776C9.098 6.815 9.096 6.903 9.035 6.939L6.618 8.363C6.556 8.4 6.478 8.358 6.474 8.286L6.439 7.633C6.437 7.578 6.48 7.532 6.535 7.532H6.925C6.948 7.532 6.971 7.523 6.988 7.508L7.211 7.31C7.276 7.252 7.236 7.144 7.148 7.142L5.991 7.118H1.49C1.437 7.118 1.394 7.075 1.394 7.022V3.308C1.394 3.255 1.437 3.212 1.49 3.212H2.544C2.597 3.212 2.64 3.169 2.64 3.116V2.969C2.64 2.916 2.597 2.873 2.544 2.873H1.461C1.366 2.873 1.329 2.75 1.408 2.697L2.134 2.221C2.672 1.867 3.301 1.679 3.944 1.679Z"/></svg>\n',
junie:
'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 40 40" fill="none">\n <path d="M25 15H35V16.75C35 29 30.5001 35 16.5001 35H15V25H16.5001C22.6251 25 25 22.875 25 16.75V15Z" fill="currentColor"/>\n <rect x="5" y="15" width="10" height="10" fill="currentColor"/>\n <rect x="15" y="5" width="10" height="10" fill="currentColor"/>\n</svg>\n',
kilo: '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 40 40">\n <path fill="currentColor" d="M27.9998324,34.6666921h6.6666279v5.3333023h-8.3809037l-3.6190266-3.6190266v-8.3809037h5.3333023v6.6666279ZM39.9997627,26.2857884l-3.6190266-3.6190266h-8.3809037v5.3333023h6.6666279v6.6666279h5.3333023v-8.3809037ZM17.3332326,22.6667578h-5.3333023v5.3333023h5.3333023v-5.3333023ZM0,36.3809638l3.6190266,3.6190266h13.714206v-5.3333023H5.3333023v-11.9999302H0v13.714206ZM33.9600959,11.9999247V3.619021L30.3410693-.0000056h-7.6745392v5.3333023h5.9602634v6.6666279h-5.9602634v5.3333023h17.3332326v-5.3333023h-6.0396668ZM5.3333023,0H0v17.3332326h5.3333023v-5.9999651h6.6666279v5.9999651h5.3333023v-5.9999651l-5.3333023-5.3333023h-6.6666279V0ZM17.3332326,0h-5.3333023v5.9999651h5.3333023V0Z"/>\n</svg>\n',
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="1.394 1.679 8.494 7.828" fill="currentColor"><path d="M8.237 7.813C8.276 7.789 8.327 7.796 8.358 7.83L9.741 9.346C9.797 9.407 9.754 9.506 9.671 9.507H8.977C8.924 9.507 8.881 9.463 8.881 9.41V9.125C8.881 9.089 8.861 9.057 8.83 9.04L7.589 8.379C7.524 8.344 7.521 8.251 7.584 8.212L8.237 7.813ZM3.944 1.679C4.502 1.679 5.052 1.82 5.54 2.09L5.962 2.323C6.024 2.358 6.029 2.446 5.97 2.486L5.091 3.09C5.065 3.108 5.05 3.137 5.05 3.169V3.495C5.05 3.529 5.032 3.561 5.003 3.578L4.68 3.769C4.594 3.82 4.498 3.722 4.549 3.637L4.592 3.566C4.63 3.502 4.584 3.421 4.51 3.421H4.028C3.925 3.421 3.894 3.562 3.989 3.604L4.377 3.775C4.448 3.806 4.455 3.904 4.389 3.944L3.77 4.323C3.755 4.332 3.737 4.337 3.72 4.337H3.361C3.309 4.337 3.268 4.379 3.268 4.431C3.268 4.484 3.309 4.526 3.361 4.526H3.779C3.797 4.526 3.814 4.521 3.829 4.513L7.599 2.272C8.135 1.954 8.815 2.008 9.294 2.407C9.307 2.418 9.314 2.434 9.314 2.451V2.729C9.315 2.812 9.413 2.856 9.475 2.8L9.728 2.57C9.789 2.514 9.888 2.558 9.888 2.641V5.812C9.888 5.865 9.845 5.908 9.792 5.908H9.359C9.331 5.908 9.303 5.895 9.285 5.873L8.374 4.773C8.337 4.728 8.268 4.728 8.229 4.771L7.468 5.625C7.429 5.669 7.438 5.737 7.487 5.769L9.038 6.776C9.098 6.815 9.096 6.903 9.035 6.939L6.618 8.363C6.556 8.4 6.478 8.358 6.474 8.286L6.439 7.633C6.437 7.578 6.48 7.532 6.535 7.532H6.925C6.948 7.532 6.971 7.523 6.988 7.508L7.211 7.31C7.276 7.252 7.236 7.144 7.148 7.142L5.991 7.118H1.49C1.437 7.118 1.394 7.075 1.394 7.022V3.308C1.394 3.255 1.437 3.212 1.49 3.212H2.544C2.597 3.212 2.64 3.169 2.64 3.116V2.969C2.64 2.916 2.597 2.873 2.544 2.873H1.461C1.366 2.873 1.329 2.75 1.408 2.697L2.134 2.221C2.672 1.867 3.301 1.679 3.944 1.679Z"/></svg>

After

Width:  |  Height:  |  Size: 1.7 KiB

@@ -1,19 +1,21 @@
import { useCallback, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { Pressable, Text, View } from "react-native";
import { Text, View, type LayoutChangeEvent } from "react-native";
import { SvgXml } from "react-native-svg";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { ExternalLink, PackagePlus, Search } from "lucide-react-native";
import { PackagePlus } from "lucide-react-native";
import { Button } from "@/components/ui/button";
import { isWeb } from "@/constants/platform";
import { ExternalLink } from "@/components/ui/external-link";
import { SearchField } from "@/components/ui/search-field";
import { StatusBadge } from "@/components/ui/status-badge";
import { rankProviderCatalog } from "@/components/provider-catalog-search";
import {
useAcpProviderCatalog,
type AcpProviderCatalogItem,
} from "@/hooks/use-acp-provider-catalog";
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
import type { Theme } from "@/styles/theme";
import { openExternalUrl } from "@/utils/open-external-url";
import { EditingTextInput as TextInput } from "@/components/ui/text-input";
import { SPACING, type Theme } from "@/styles/theme";
import { settingsStyles } from "@/styles/settings";
interface ProviderCatalogListProps {
serverId: string;
@@ -21,52 +23,43 @@ interface ProviderCatalogListProps {
onInstall: (entry: AcpProviderCatalogItem) => Promise<void> | void;
}
const SEARCH_ICON_SIZE = 16;
const PROVIDER_FALLBACK_ICON_SIZE = 20;
const PROVIDER_REMOTE_ICON_SIZE = 24;
const TILE_GAP = SPACING[3];
/** Narrowest tile that keeps the icon, type badge, install link, and Add on one row. */
const MIN_TILE_WIDTH = 300;
const MAX_COLUMNS = 4;
const ThemedPackagePlus = withUnistyles(PackagePlus);
const ThemedSvgXml = withUnistyles(SvgXml);
const ThemedSearch = withUnistyles(Search);
const ThemedExternalLink = withUnistyles(ExternalLink);
const ThemedTextInput = withUnistyles(TextInput, (theme) => ({
placeholderTextColor: theme.colors.foregroundMuted,
}));
const foregroundColorMapping = (theme: Theme) => ({ color: theme.colors.foreground });
const foregroundMutedColorMapping = (theme: Theme) => ({
color: theme.colors.foregroundMuted,
});
function matchesSearch(entry: AcpProviderCatalogItem, query: string): boolean {
const normalized = query.trim().toLowerCase();
if (!normalized) return true;
return [entry.title, entry.id, entry.description].some((value) =>
value.toLowerCase().includes(normalized),
);
function columnCountForWidth(width: number): number {
const fits = Math.floor((width + TILE_GAP) / (MIN_TILE_WIDTH + TILE_GAP));
return Math.min(MAX_COLUMNS, Math.max(1, fits));
}
interface CatalogRowProps {
interface CatalogTileProps {
entry: AcpProviderCatalogItem;
/** `undefined` until the grid is measured, or in a single column; the tile fills the row. */
width: number | undefined;
installing: boolean;
onInstall: (entry: AcpProviderCatalogItem) => void;
}
function CatalogRow({ entry, installing, onInstall }: CatalogRowProps) {
function CatalogTile({ entry, width, installing, onInstall }: CatalogTileProps) {
const { t } = useTranslation();
const actionLabel = installing
? t("providerCatalog.actions.adding")
: t("providerCatalog.actions.add");
const handleInstall = useCallback(() => {
onInstall(entry);
}, [entry, onInstall]);
const handleOpenInstallLink = useCallback(() => {
void openExternalUrl(entry.installLink);
}, [entry.installLink]);
const tileStyle = useMemo(
() => [settingsStyles.card, styles.tile, width === undefined ? styles.tileFull : { width }],
[width],
);
return (
<View style={styles.row}>
<View style={tileStyle} testID={`provider-catalog-tile-${entry.id}`}>
<View style={styles.iconFrame}>
{entry.iconSvg ? (
<ThemedSvgXml
@@ -79,42 +72,33 @@ function CatalogRow({ entry, installing, onInstall }: CatalogRowProps) {
<ThemedPackagePlus size={PROVIDER_FALLBACK_ICON_SIZE} uniProps={foregroundColorMapping} />
)}
</View>
<View style={styles.textColumn}>
<View style={styles.titleRow}>
<Text style={styles.name} numberOfLines={1}>
{entry.title}
</Text>
<Text style={styles.version} numberOfLines={1}>
{entry.version}
</Text>
</View>
<Text style={styles.description} numberOfLines={1}>
{entry.description || entry.id}
<View style={styles.details}>
<Text style={styles.name} numberOfLines={1}>
{entry.title}
</Text>
<Pressable
accessibilityRole="link"
accessibilityLabel={t("providerCatalog.actions.installInstructionsFor", {
provider: entry.title,
})}
onPress={handleOpenInstallLink}
style={styles.installLink}
>
<Text style={styles.installLinkText} numberOfLines={1}>
{t("providerCatalog.actions.installInstructions")}
</Text>
<ThemedExternalLink size={12} uniProps={foregroundMutedColorMapping} />
</Pressable>
<View style={styles.metaRow}>
{/* The catalog is the ACP registry, so every entry it offers is an ACP provider. */}
<StatusBadge label={t("providerCatalog.types.acp")} size="xs" />
<ExternalLink
href={entry.installLink}
label={t("providerCatalog.actions.installInstructions")}
accessibilityLabel={t("providerCatalog.actions.installInstructionsFor", {
provider: entry.title,
})}
/>
</View>
</View>
<Button
size="sm"
variant="default"
size="xs"
variant="outline"
disabled={installing}
loading={installing}
onPress={handleInstall}
style={styles.actionButton}
accessibilityLabel={t("providerCatalog.actions.addProvider", { provider: entry.title })}
style={styles.addButton}
testID={`install-provider-${entry.id}`}
>
{actionLabel}
{installing ? t("providerCatalog.actions.adding") : t("providerCatalog.actions.add")}
</Button>
</View>
);
@@ -129,6 +113,7 @@ export function ProviderCatalogList({
const { entries: catalogEntries } = useAcpProviderCatalog();
const { entries: providerEntries } = useProvidersSnapshot(serverId);
const [search, setSearch] = useState("");
const [gridWidth, setGridWidth] = useState<number | null>(null);
const installedIds = useMemo(
() => new Set(providerEntries?.map((entry) => entry.provider) ?? []),
@@ -137,41 +122,48 @@ export function ProviderCatalogList({
const availableEntries = useMemo(
() =>
catalogEntries
.filter((entry) => !installedIds.has(entry.id))
.filter((entry) => matchesSearch(entry, search)),
rankProviderCatalog(
catalogEntries.filter((entry) => !installedIds.has(entry.id)),
search,
),
[catalogEntries, installedIds, search],
);
const handleGridLayout = useCallback((event: LayoutChangeEvent) => {
setGridWidth(event.nativeEvent.layout.width);
}, []);
const tileWidth = useMemo(() => {
if (gridWidth === null) return undefined;
const columns = columnCountForWidth(gridWidth);
if (columns === 1) return undefined;
return Math.floor((gridWidth - TILE_GAP * (columns - 1)) / columns);
}, [gridWidth]);
return (
<View>
<View style={styles.searchField}>
<View style={styles.searchIcon}>
<ThemedSearch size={SEARCH_ICON_SIZE} uniProps={foregroundMutedColorMapping} />
</View>
<ThemedTextInput
testID="provider-catalog-search"
initialValue={search}
<View style={styles.searchRail}>
<SearchField
value={search}
onChangeText={setSearch}
accessibilityLabel={t("providerCatalog.search")}
placeholder={t("providerCatalog.search")}
// @ts-expect-error - outlineStyle is web-only
style={[styles.searchInput, isWeb && { outlineStyle: "none" }]}
autoCapitalize="none"
autoCorrect={false}
clearAccessibilityLabel={t("providerCatalog.clearSearch")}
testID="provider-catalog-search"
clearTestID="provider-catalog-search-clear"
/>
</View>
{availableEntries.length === 0 ? (
<View style={styles.stateBox}>
<View style={[settingsStyles.card, styles.stateBox]}>
<Text style={styles.stateText}>{t("providerCatalog.noProviders")}</Text>
</View>
) : (
<View style={styles.list}>
<View style={styles.grid} onLayout={handleGridLayout}>
{availableEntries.map((entry) => (
<CatalogRow
<CatalogTile
key={entry.id}
entry={entry}
width={tileWidth}
installing={installingProviderId === entry.id}
onInstall={onInstall}
/>
@@ -183,101 +175,56 @@ export function ProviderCatalogList({
}
const styles = StyleSheet.create((theme) => ({
searchField: {
searchRail: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
backgroundColor: theme.colors.surface2,
borderRadius: theme.borderRadius.lg,
borderWidth: 1,
borderColor: theme.colors.border,
paddingHorizontal: theme.spacing[3],
marginBottom: theme.spacing[3],
},
searchIcon: {
width: 18,
alignItems: "center",
grid: {
flexDirection: "row",
flexWrap: "wrap",
gap: TILE_GAP,
},
searchInput: {
flex: 1,
minWidth: 0,
paddingVertical: theme.spacing[3],
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
},
list: {
borderRadius: theme.borderRadius.lg,
borderWidth: 1,
borderColor: theme.colors.border,
overflow: "hidden",
},
row: {
tile: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[3],
padding: theme.spacing[3],
borderBottomWidth: 1,
borderBottomColor: theme.colors.border,
},
tileFull: {
width: "100%",
},
details: {
flex: 1,
minWidth: 0,
gap: theme.spacing[1],
},
iconFrame: {
flexShrink: 0,
width: 36,
height: 36,
borderRadius: theme.borderRadius.md,
backgroundColor: theme.colors.surface2,
alignItems: "center",
justifyContent: "center",
},
addButton: {
flexShrink: 0,
},
textColumn: {
flex: 1,
minWidth: 0,
gap: theme.spacing[1],
},
titleRow: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
minWidth: 0,
},
name: {
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
fontWeight: theme.fontWeight.medium,
flexShrink: 1,
fontWeight: theme.fontWeight.normal,
},
version: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
flexShrink: 0,
},
description: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
},
installLink: {
alignSelf: "flex-start",
metaRow: {
flexDirection: "row",
flexWrap: "wrap",
alignItems: "center",
gap: theme.spacing[1],
maxWidth: "100%",
},
installLinkText: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
},
actionButton: {
width: 92,
flexShrink: 0,
gap: theme.spacing[2],
},
stateBox: {
minHeight: 96,
borderRadius: theme.borderRadius.lg,
borderWidth: 1,
borderColor: theme.colors.border,
backgroundColor: theme.colors.surface1,
alignItems: "center",
justifyContent: "center",
gap: theme.spacing[3],
padding: theme.spacing[4],
},
stateText: {
@@ -0,0 +1,45 @@
import { describe, expect, it } from "vitest";
import { rankProviderCatalog } from "./provider-catalog-search";
const entries = [
{ id: "kiro-cli", title: "Kiro CLI" },
{ id: "goose", title: "goose" },
{ id: "kimi", title: "Kimi Code CLI" },
{ id: "gemini", title: "Gemini CLI" },
{ id: "qwen-code", title: "Qwen Code" },
{ id: "codex-acp", title: "Codex" },
];
function titles(list: { title: string }[]): string[] {
return list.map((entry) => entry.title);
}
describe("rankProviderCatalog", () => {
it("lists every provider alphabetically by name without a query", () => {
expect(titles(rankProviderCatalog(entries, " "))).toEqual([
"Codex",
"Gemini CLI",
"goose",
"Kimi Code CLI",
"Kiro CLI",
"Qwen Code",
]);
});
it("ranks the strongest match first and drops providers that do not match", () => {
expect(titles(rankProviderCatalog(entries, "cod"))).toEqual([
"Codex",
"Kimi Code CLI",
"Qwen Code",
]);
});
it("matches in-word subsequences and multiple tokens like the other pickers", () => {
expect(titles(rankProviderCatalog(entries, "gmni"))).toEqual(["Gemini CLI"]);
expect(titles(rankProviderCatalog(entries, "qw cod"))).toEqual(["Qwen Code"]);
});
it("matches the provider id", () => {
expect(titles(rankProviderCatalog(entries, "kiro-cli"))).toEqual(["Kiro CLI"]);
});
});
@@ -0,0 +1,34 @@
import {
compareMatchScores,
scoreTextFields,
type MatchScore,
} from "@getpaseo/protocol/search/text-match";
export interface SearchableCatalogEntry {
id: string;
title: string;
}
function compareTitles(a: SearchableCatalogEntry, b: SearchableCatalogEntry): number {
return a.title.localeCompare(b.title, undefined, { sensitivity: "base" });
}
/**
* Orders the Add provider catalog. Without a query the list is alphabetical by
* name. With a query it uses the pickers' ranked matcher over the fields the
* tile shows (name and id), best match first, ties alphabetical.
*/
export function rankProviderCatalog<T extends SearchableCatalogEntry>(
entries: readonly T[],
query: string,
): T[] {
if (!query.trim()) return [...entries].sort(compareTitles);
const scored: { entry: T; score: MatchScore }[] = [];
for (const entry of entries) {
const score = scoreTextFields(query, [entry.title, entry.id]);
if (score) scored.push({ entry, score });
}
scored.sort((a, b) => compareMatchScores(a.score, b.score) || compareTitles(a.entry, b.entry));
return scored.map(({ entry }) => entry);
}
@@ -8,6 +8,7 @@ export interface AcpProviderCatalogEntry {
iconSvg: string | null;
installLink: string;
command: readonly [string, ...string[]];
bundledProvider?: boolean;
env?: Readonly<Record<string, string>>;
params?: Readonly<Record<string, unknown>>;
}
@@ -238,6 +239,16 @@ const CATALOG_DATA = [
installLink: "https://hermes-agent.nousresearch.com/docs/user-guide/features/acp",
command: ["hermes", "acp"],
},
{
id: "hoplite",
bundledProvider: true,
title: "Hoplite",
description: "Cloud coding agent through the local hoplite acp bridge",
version: "manual",
iconId: "hoplite",
installLink: "https://hoplite.sh/docs/cli#install",
command: ["hoplite", "acp"],
},
{
id: "junie",
title: "Junie",
@@ -389,6 +400,7 @@ export const ACP_PROVIDER_CATALOG: AcpProviderCatalogEntry[] = CATALOG_DATA.map(
version: entry.version,
installLink: entry.installLink,
command: entry.command,
bundledProvider: "bundledProvider" in entry ? entry.bundledProvider : undefined,
env: "env" in entry ? entry.env : undefined,
params: "params" in entry ? entry.params : undefined,
iconSvg: entry.iconId ? (ACP_PROVIDER_ICON_SVGS[entry.iconId] ?? null) : null,
@@ -44,6 +44,7 @@ describe("ACP provider catalog", () => {
expect(findProvider("codewhale").command).toEqual(["codewhale", "serve", "--acp"]);
expect(findProvider("devin").command).toEqual(["devin", "acp"]);
expect(findProvider("goose").command).toEqual(["goose", "acp"]);
expect(findProvider("hoplite").command).toEqual(["hoplite", "acp"]);
expect(findProvider("junie").command).toEqual(["junie", "--acp", "true"]);
expect(findProvider("kiro").command).toEqual(["kiro-cli", "acp"]);
expect(findProvider("poolside").command).toEqual(["pool", "acp"]);
@@ -59,6 +60,32 @@ describe("ACP provider catalog", () => {
expect(findProvider("minimax-code").iconSvg).toContain("<svg");
});
it("offers Hoplite through its local ACP bridge with the Hoplite mark", () => {
expect(findProvider("hoplite")).toMatchObject({
title: "Hoplite",
command: ["hoplite", "acp"],
installLink: "https://hoplite.sh/docs/cli#install",
});
expect(buildAcpProviderConfigPatch(findProvider("hoplite"), true)).toEqual({
providers: {
hoplite: { enabled: true },
},
});
const ids = getAcpProviderCatalog().map((entry) => entry.id);
expect(ids.indexOf("hermes")).toBeLessThan(ids.indexOf("hoplite"));
expect(ids.indexOf("hoplite")).toBeLessThan(ids.indexOf("junie"));
expect(findProvider("hoplite").iconSvg).toContain('fill="currentColor"');
});
it.each([undefined, false])(
"rejects unsupported bundled Hoplite before producing a patch (%s)",
(supported) => {
expect(() => buildAcpProviderConfigPatch(findProvider("hoplite"), supported)).toThrow(
"Update the host to add Hoplite.",
);
},
);
it("maps a catalog entry to the daemon provider config patch", () => {
expect(buildAcpProviderConfigPatch(findProvider("amp-acp"))).toEqual({
providers: {
@@ -10,7 +10,13 @@ export function getAcpProviderCatalog(): AcpProviderCatalogItem[] {
export function buildAcpProviderConfigPatch(
entry: AcpProviderCatalogItem,
supportsHopliteProvider = false,
): MutableDaemonConfigPatch {
if (entry.bundledProvider) {
// COMPAT(hopliteProvider): added after v0.11.2, remove after 2027-04-15 once host floor includes the bundled adapter.
if (!supportsHopliteProvider) throw new Error("Update the host to add Hoplite.");
return { providers: { [entry.id]: { enabled: true } } };
}
return {
providers: {
[entry.id]: {
+5
View File
@@ -1657,14 +1657,19 @@ export const ar: TranslationResources = {
title: "إضافة مزود",
search: "مقدمي البحث",
noProviders: "لم يتم العثور على مقدمي الخدمات",
clearSearch: "مسح البحث",
actions: {
add: "يضيف",
addProvider: "إضافة {{provider}}",
adding: "إضافة",
installed: "تم التثبيت",
cancel: "يلغي",
installInstructions: "تعليمات التثبيت",
installInstructionsFor: "تعليمات تثبيت{{provider}}",
},
types: {
acp: "ACP",
},
errors: {
unableToInstall: "غير قادر على تثبيت الموفر",
},
+5
View File
@@ -1682,14 +1682,19 @@ export const en = {
title: "Add provider",
search: "Search providers",
noProviders: "No providers found",
clearSearch: "Clear search",
actions: {
add: "Add",
addProvider: "Add {{provider}}",
adding: "Adding",
installed: "Installed",
cancel: "Cancel",
installInstructions: "Install instructions",
installInstructionsFor: "{{provider}} install instructions",
},
types: {
acp: "ACP",
},
errors: {
unableToInstall: "Unable to install provider",
},
+5
View File
@@ -1703,14 +1703,19 @@ export const es: TranslationResources = {
title: "Agregar proveedor",
search: "Proveedores de búsqueda",
noProviders: "No se encontraron proveedores",
clearSearch: "Borrar búsqueda",
actions: {
add: "Agregar",
addProvider: "Añadir {{provider}}",
adding: "Añadiendo",
installed: "Instalado",
cancel: "Cancelar",
installInstructions: "Instrucciones de instalación",
installInstructionsFor: "Instrucciones de instalación de{{provider}}",
},
types: {
acp: "ACP",
},
errors: {
unableToInstall: "No se puede instalar el proveedor",
},
+5
View File
@@ -1699,14 +1699,19 @@ export const fr: TranslationResources = {
title: "Ajouter un fournisseur",
search: "Rechercher des fournisseurs",
noProviders: "Aucun fournisseur trouvé",
clearSearch: "Effacer la recherche",
actions: {
add: "Ajouter",
addProvider: "Ajouter {{provider}}",
adding: "Ajout…",
installed: "Installé",
cancel: "Annuler",
installInstructions: "Instructions d’installation",
installInstructionsFor: "Instructions d’installation de {{provider}}",
},
types: {
acp: "ACP",
},
errors: {
unableToInstall: "Impossible d’installer le fournisseur",
},
+5
View File
@@ -1674,14 +1674,19 @@ export const ja: TranslationResources = {
title: "プロバイダーを追加",
search: "プロバイダーを検索",
noProviders: "プロバイダーが見つかりません",
clearSearch: "検索をクリア",
actions: {
add: "追加",
addProvider: "{{provider}} を追加",
adding: "追加中",
installed: "インストール済み",
cancel: "キャンセル",
installInstructions: "インストール手順",
installInstructionsFor: "{{provider}}のインストール手順",
},
types: {
acp: "ACP",
},
errors: {
unableToInstall: "プロバイダーをインストールできません",
},
+5
View File
@@ -1667,14 +1667,19 @@ export const ko: TranslationResources = {
title: "프로바이더 추가",
search: "프로바이더 검색",
noProviders: "프로바이더를 찾을 수 없습니다",
clearSearch: "검색 지우기",
actions: {
add: "추가",
addProvider: "{{provider}} 추가",
adding: "추가 중",
installed: "설치됨",
cancel: "취소",
installInstructions: "설치 안내",
installInstructionsFor: "{{provider}} 설치 안내",
},
types: {
acp: "ACP",
},
errors: {
unableToInstall: "프로바이더를 설치할 수 없습니다",
},
+5
View File
@@ -1688,14 +1688,19 @@ export const ptBR: TranslationResources = {
title: "Adicionar provedor",
search: "Buscar provedores",
noProviders: "Nenhum provedor encontrado",
clearSearch: "Limpar pesquisa",
actions: {
add: "Adicionar",
addProvider: "Adicionar {{provider}}",
adding: "Adicionando",
installed: "Instalado",
cancel: "Cancelar",
installInstructions: "Instruções de instalação",
installInstructionsFor: "Instruções de instalação de {{provider}}",
},
types: {
acp: "ACP",
},
errors: {
unableToInstall: "Não foi possível instalar provedor",
},
+5
View File
@@ -1686,14 +1686,19 @@ export const ru: TranslationResources = {
title: "Добавить провайдера",
search: "Поиск провайдеров",
noProviders: "Провайдеры не найдены",
clearSearch: "Очистить поиск",
actions: {
add: "Добавить",
addProvider: "Добавить {{provider}}",
adding: "Добавление",
installed: "Установлено",
cancel: "Отмена",
installInstructions: "Инструкции по установке",
installInstructionsFor: "Инструкции по установке {{provider}}",
},
types: {
acp: "ACP",
},
errors: {
unableToInstall: "Не удалось установить провайдера",
},
+5
View File
@@ -1640,14 +1640,19 @@ export const zhCN: TranslationResources = {
title: "添加 provider",
search: "搜索 providers",
noProviders: "未找到 providers",
clearSearch: "清除搜索",
actions: {
add: "添加",
addProvider: "添加 {{provider}}",
adding: "正在添加",
installed: "已安装",
cancel: "取消",
installInstructions: "安装说明",
installInstructionsFor: "{{provider}} 安装说明",
},
types: {
acp: "ACP",
},
errors: {
unableToInstall: "无法安装 provider",
},
@@ -230,3 +230,22 @@ it("does not restore a targeted cached workspace while its archive is pending",
store.clearSession(serverId);
}
});
it("keeps the failed first turn out of Working when the creation response arrives last", () => {
const serverId = "failed-first-turn-creation";
const store = useSessionStore.getState();
store.initializeSession(serverId, null as unknown as DaemonClient);
try {
const replica = new WorkspaceDirectoryReplica(serverId);
const descriptor = workspace("failed-first-turn");
replica.applyDelta({ kind: "upsert", workspace: { ...descriptor, status: "running" } });
replica.applyDelta({ kind: "upsert", workspace: { ...descriptor, status: "failed" } });
// The new-workspace screen turns its older creation response into a running snapshot.
replica.acceptWorkspaces([normalizeWorkspaceDescriptor({ ...descriptor, status: "running" })]);
expect(
useSessionStore.getState().sessions[serverId]?.workspaces.get(descriptor.id)?.status,
).toBe("failed");
} finally {
store.clearSession(serverId);
}
});
@@ -6,6 +6,7 @@ import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types";
import type { MutableDaemonConfig } from "@getpaseo/protocol/messages";
import { ToastApiProvider } from "@/contexts/toast-api-context";
const { theme, snapshotState, configState, patchConfigMock, openProviderSettingsMock } = vi.hoisted(
() => ({
@@ -281,6 +282,12 @@ vi.mock("@/utils/confirm-dialog", () => ({
import { ProvidersSection } from "./providers-section";
function unexpectedToast(): never {
throw new Error("Provider row interactions should not display a toast");
}
const toastApi = { show: unexpectedToast, copied: unexpectedToast, error: unexpectedToast };
const claudeEntry: ProviderSnapshotEntry = {
provider: "claude",
status: "ready",
@@ -366,7 +373,11 @@ describe("ProvidersSection", () => {
function render(): void {
act(() => {
root?.render(<ProvidersSection serverId="server-1" />);
root?.render(
<ToastApiProvider api={toastApi}>
<ProvidersSection serverId="server-1" />
</ToastApiProvider>,
);
});
}
@@ -11,6 +11,7 @@ import {
} from "react-native";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import { useIsCompactFormFactor } from "@/constants/layout";
import { useToast } from "@/contexts/toast-api-context";
import { settingsStyles } from "@/styles/settings";
import { useHostRuntimeIsConnected } from "@/runtime/host-runtime";
import { useHostFeature } from "@/runtime/host-features";
@@ -19,6 +20,7 @@ import { useDaemonConfig } from "@/hooks/use-daemon-config";
import { buildProviderDefinitions } from "@/utils/provider-definitions";
import {
buildAcpProviderConfigPatch,
getAcpProviderCatalog,
type AcpProviderCatalogItem,
} from "@/hooks/use-acp-provider-catalog";
import { ProviderCatalogList } from "@/components/provider-catalog-list";
@@ -325,7 +327,9 @@ export interface ProvidersSectionProps {
export function ProvidersSection({ serverId }: ProvidersSectionProps) {
const { t } = useTranslation();
const toast = useToast();
const isConnected = useHostRuntimeIsConnected(serverId);
const supportsHopliteProvider = useHostFeature(serverId, "hopliteProvider");
const supportsProviderRemoval = useHostFeature(serverId, "providerRemoval");
const { entries, isLoading, refresh } = useProvidersSnapshot(serverId);
const { config, patchConfig } = useDaemonConfig(serverId);
@@ -338,9 +342,16 @@ export function ProvidersSection({ serverId }: ProvidersSectionProps) {
const providerDefinitions = useMemo(() => buildProviderDefinitions(entries), [entries]);
const hasServer = serverId.length > 0;
/** Custom providers are deletable only when config.json holds their `extends` definition. */
/** Config owns derived providers and opt-in bundled catalog providers. */
const isConfigOwnedProvider = useCallback(
(providerId: string) => Boolean(config?.providers?.[providerId]?.extends),
(providerId: string) =>
Boolean(
config?.providers?.[providerId] &&
(config.providers[providerId].extends ||
getAcpProviderCatalog().some(
(entry) => entry.id === providerId && entry.bundledProvider,
)),
),
[config],
);
@@ -405,18 +416,15 @@ export function ProvidersSection({ serverId }: ProvidersSectionProps) {
if (installingProviderId) return;
setInstallingProviderId(entry.id);
try {
await patchConfig(buildAcpProviderConfigPatch(entry));
await patchConfig(buildAcpProviderConfigPatch(entry, supportsHopliteProvider));
await refresh([entry.id]);
} catch (error) {
Alert.alert(
t("settings.providers.addErrorTitle"),
error instanceof Error ? error.message : String(error),
);
toast.error(error instanceof Error ? error.message : String(error));
} finally {
setInstallingProviderId((current) => (current === entry.id ? null : current));
}
},
[installingProviderId, patchConfig, refresh, t],
[installingProviderId, patchConfig, refresh, supportsHopliteProvider, toast],
);
return (
@@ -359,6 +359,8 @@ class AcpRuntime {
private emit: (event: ProviderEvent) => void;
private readonly messages = new Map<string, string>();
private readonly toolCalls = new Map<string, AcpToolCallSnapshot>();
// Running tool rows published by transformers; the turn's terminal closes any left open.
private readonly vendorToolCalls = new Map<string, ToolCallTimelineItem>();
private readonly pendingCompactions = new Set<string>();
private readonly permissions = new Map<
string,
@@ -595,10 +597,13 @@ class AcpRuntime {
turnId,
state: "started",
});
// The SDK dispatches notifications without awaiting them, so the prompt response can resolve
// while earlier session updates are still queued. Apply them before the turn ends.
const settled = this.call(
this.connection.prompt({ sessionId: this.nativeSessionId, prompt }),
).then(
(response): void => {
async (response): Promise<void> => {
await this.drainNotifications();
const state = response.stopReason === "cancelled" ? "canceled" : "completed";
this.fallbackChunkIds.clear();
this.terminalizeTransientItems(state);
@@ -610,7 +615,8 @@ class AcpRuntime {
});
return undefined;
},
(error): void => {
async (error): Promise<void> => {
await this.drainNotifications();
this.fallbackChunkIds.clear();
this.terminalizeTransientItems("failed");
this.emit({
@@ -1027,9 +1033,17 @@ class AcpRuntime {
this.emit({
type: "timeline.item",
sessionId: this.options.boundarySessionId,
item: toolTimelineItem(completed),
item: terminalToolItem(toolTimelineItem(snapshot), state),
});
}
for (const item of this.vendorToolCalls.values()) {
this.emit({
type: "timeline.item",
sessionId: this.options.boundarySessionId,
item: terminalToolItem(item, state),
});
}
this.vendorToolCalls.clear();
for (const id of this.pendingCompactions) {
this.emit({
type: "timeline.item",
@@ -1076,6 +1090,10 @@ class AcpRuntime {
if (this.configTransaction) this.stagedTransformerConfig = update.config;
else this.emitConfigSnapshot(update.config);
} else if (update.type === "timeline") {
if (update.item.type === "tool_call") {
if (update.item.status === "running") this.vendorToolCalls.set(update.item.id, update.item);
else this.vendorToolCalls.delete(update.item.id);
}
this.emit({
type: "timeline.item",
sessionId: this.options.boundarySessionId,
@@ -1383,7 +1401,9 @@ function configValues(
return Object.fromEntries(options.map((option) => [option.id, option.currentValue]));
}
function toolTimelineItem(snapshot: AcpToolCallSnapshot): ProviderTimelineItem {
type ToolCallTimelineItem = Extract<ProviderTimelineItem, { type: "tool_call" }>;
function toolTimelineItem(snapshot: AcpToolCallSnapshot): ToolCallTimelineItem {
const input = jsonRecord(snapshot.input);
const isEdit = snapshot.kind === "edit" || snapshot.name?.toLowerCase().includes("edit") === true;
const detail = isEdit
@@ -1411,6 +1431,18 @@ function toolTimelineItem(snapshot: AcpToolCallSnapshot): ProviderTimelineItem {
return { ...base, status, error: null };
}
// A row the turn left open ends with the turn. The wire contract requires a non-null error on a
// failed tool call, so a canceled turn cancels its rows instead of failing them.
function terminalToolItem(
item: ToolCallTimelineItem,
state: "completed" | "failed" | "canceled",
): ToolCallTimelineItem {
if (state === "failed") {
return { ...item, status: "failed", error: item.error ?? { message: "Turn failed" } };
}
return { ...item, status: state, error: null };
}
function jsonValue(value: unknown) {
return z.json().parse(value);
}
+140
View File
@@ -619,6 +619,146 @@ lines.on("line", (line) => {
await connection.close();
});
it.each([
["end_turn", "completed", "completed"],
["cancelled", "canceled", "canceled"],
] as const)(
"closes a transformer's running tool row when the turn ends with %s",
async (stopReason, turnState, rowStatus) => {
const harness = connectorHarness({
handleMessage(instance, message) {
if (!("method" in message) || !("id" in message)) return false;
if (message.method !== "session/prompt") return false;
instance.notify("vendor/phase", { id: "phase-1", label: "Preparing" });
instance.respond(message as AcpRequestMessage, { stopReason });
return true;
},
});
const registration = runAcpProvider({
id: "vendor-row-acp",
label: "Vendor row ACP",
connector: harness.connector,
transformers: [
{
notification(notification) {
if (notification.method !== "vendor/phase") return null;
return {
type: "timeline",
item: {
type: "tool_call",
id: "phase-1",
callId: "phase-1",
name: "Vendor phase",
detail: { type: "plain_text", label: "Preparing" },
status: "running",
error: null,
},
};
},
},
],
});
const connection = await registration.connect({
versions: [1],
capabilities: ["prompt.message"],
});
const events: ProviderEvent[] = [];
connection.onEvent((event) => events.push(event));
await connection.send(openInput());
await waitForEvent(events, (event) => event.type === "session.ready");
await connection.send({
type: "session.prompt",
sessionId: "session-1",
prompt: {
clientMessageId: "first",
delivery: "auto",
input: { type: "message", content: [{ type: "text", text: "first" }] },
},
});
await waitForEvent(
events,
(event) => event.type === "session.turn" && event.state === turnState,
);
const rows = events.flatMap((event) =>
event.type === "timeline.item" && event.item.id === "phase-1" ? [event.item] : [],
);
expect(rows.map((row) => row.type === "tool_call" && row.status)).toEqual([
"running",
rowStatus,
]);
const closed = events.findIndex(
(event) =>
event.type === "timeline.item" &&
event.item.id === "phase-1" &&
event.item.type === "tool_call" &&
event.item.status === rowStatus,
);
const terminal = events.findIndex(
(event) => event.type === "session.turn" && event.state === turnState,
);
expect(closed).toBeLessThan(terminal);
// The wire contract only accepts a failed tool call with a non-null error.
expect(rows.at(-1)).toMatchObject({ error: null });
await connection.close();
},
);
it("cancels an in-progress ACP tool call with the canceled turn instead of failing it without an error", async () => {
const harness = connectorHarness({
handleMessage(instance, message) {
if (!("method" in message) || !("id" in message)) return false;
if (message.method !== "session/prompt") return false;
instance.notify("session/update", {
sessionId: "connector-session",
update: {
sessionUpdate: "tool_call",
toolCallId: "tool-1",
title: "Run tests",
kind: "execute",
status: "in_progress",
},
});
instance.respond(message as AcpRequestMessage, { stopReason: "cancelled" });
return true;
},
});
const registration = runAcpProvider({
id: "cancel-tool-acp",
label: "Cancel tool ACP",
connector: harness.connector,
});
const connection = await registration.connect({
versions: [1],
capabilities: ["prompt.message"],
});
const events: ProviderEvent[] = [];
connection.onEvent((event) => events.push(event));
await connection.send(openInput());
await waitForEvent(events, (event) => event.type === "session.ready");
await connection.send({
type: "session.prompt",
sessionId: "session-1",
prompt: {
clientMessageId: "first",
delivery: "auto",
input: { type: "message", content: [{ type: "text", text: "first" }] },
},
});
await waitForEvent(
events,
(event) => event.type === "session.turn" && event.state === "canceled",
);
const rows = events.flatMap((event) =>
event.type === "timeline.item" && event.item.id === "tool-1" ? [event.item] : [],
);
expect(rows.at(-1)).toMatchObject({ type: "tool_call", status: "canceled", error: null });
await connection.close();
});
it("serializes configuration mutations", async () => {
let releaseMutation: (() => void) | null = null;
const configOptions = [
+2
View File
@@ -26,6 +26,8 @@ export const PROVIDER_CAPABILITIES = [
export type ProviderCapability = (typeof PROVIDER_CAPABILITIES)[number];
export interface ProviderRegistration {
/** Activate only while agents.providers contains this provider ID, independently of enabled. */
requiresConfiguration?: boolean;
/** Equal keys share discovery within this provider. Include effective configuration and execution environment. */
getCatalogCacheKey?(options: ProviderCatalogOptions): Promise<string | undefined>;
/** Default executable and arguments; the daemon resolves overrides before status/connect. */
@@ -812,3 +812,14 @@ describe("checkout PR schemas", () => {
});
});
});
test.each([undefined, false, true])(
"accepts optional Hoplite capability (%s)",
(hopliteProvider) => {
const features = hopliteProvider === undefined ? {} : { hopliteProvider };
expect(
ServerInfoStatusPayloadSchema.parse({ status: "server_info", serverId: "test", features })
.features,
).toEqual(features);
},
);
+2
View File
@@ -3710,6 +3710,8 @@ export const ServerInfoStatusPayloadSchema = z
commitBaseClassification: z.boolean().optional(),
// COMPAT(providerRemoval): added in v0.1.105, drop the gate when floor >= v0.1.105.
providerRemoval: z.boolean().optional(),
// COMPAT(hopliteProvider): added after v0.11.2, remove after 2027-04-15 once host floor includes the bundled adapter.
hopliteProvider: z.boolean().optional(),
// COMPAT(importSessionWorkspaceTarget): added in v0.1.110, remove gate after 2027-01-16.
importSessionWorkspaceTarget: z.boolean().optional(),
// COMPAT(importSessionSearch): added in v0.8.0, remove gate after 2027-03-02.
@@ -31,6 +31,7 @@ export const ACP_PROVIDER_ICON_NAMES = [
"glm-acp-agent",
"goose",
"grok",
"hoplite",
"junie",
"kilo",
"kimi",
@@ -1,25 +0,0 @@
import { describe, expect, it } from "vitest";
import { TerminalInputModeTracker } from "./terminal-input-mode";
import { encodeTerminalKeyInput } from "./terminal-key-input";
describe("Modified Enter negotiation", () => {
it("answers a keyboard query split immediately after ESC", () => {
const tracker = new TerminalInputModeTracker();
tracker.feed("\x1b");
expect(tracker.feed("[?u").responses).toEqual(["\x1b[?0u"]);
});
it("recognizes modified Enter after a program enables modifyOtherKeys level 2", () => {
const tracker = new TerminalInputModeTracker();
tracker.feed("\x1b[>4;2m");
expect(tracker.supportsModifiedEnter()).toBe(true);
});
it("distinguishes Shift+Enter from Enter after modifyOtherKeys negotiation", () => {
const tracker = new TerminalInputModeTracker();
tracker.feed("\x1b[>4;2m");
const options = { inputMode: tracker.getState() };
expect(encodeTerminalKeyInput({ key: "Enter", shift: true }, options)).toBe("\x1b[27;2;13~");
expect(encodeTerminalKeyInput({ key: "Enter" }, options)).toBe("\r");
});
});
@@ -1121,3 +1121,50 @@ describe("plugin provider launch and status", () => {
},
);
});
test("config-required plugin membership is independent of enablement and other providers", async () => {
const logger = createTestLogger();
const plugins = new PluginAgentClientRegistry(logger);
const harness = createProviderHarness();
let connections = 0;
let probes = 0;
plugins.replace([
{
...harness.registration,
requiresConfiguration: true,
async status() {
probes++;
return { available: true };
},
async connect(request) {
connections++;
return harness.registration.connect(request);
},
},
]);
const build = (providerOverrides = {}) =>
buildProviderRegistry(logger, {
pluginProviders: plugins.definitions(),
providerOverrides,
});
try {
const before = build();
expect(before["plugin-direct"]).toBeUndefined();
expect({ probes, connections }).toEqual({ probes: 0, connections: 0 });
const added = build({ "plugin-direct": {} });
expect(added["plugin-direct"].enabled).toBe(true);
const client = added["plugin-direct"].createClient(logger);
expect(await client.isAvailable()).toBe(true);
const catalog = await client.fetchCatalog({ scope: "global" });
expect(catalog.models.map((model) => model.id)).toEqual(["plugin-model"]);
expect({ probes, connections }).toEqual({ probes: 1, connections: 1 });
const disabled = build({ "plugin-direct": { enabled: false } });
expect(disabled["plugin-direct"].enabled).toBe(false);
expect(Object.keys(build())).toEqual(Object.keys(before));
for (const id of Object.keys(before)) {
expect(added[id].enabled).toBe(before[id].enabled);
}
} finally {
await plugins.shutdown();
}
});
@@ -885,6 +885,7 @@ function createPluginProviderDefinition(
label: registration.label,
description: registration.description ?? `Plugin provider ${registration.label}`,
iconSvg: registration.icon,
requiresConfiguration: registration.requiresConfiguration,
defaultModeId: null,
modes: [],
supportsExactMcpPreapproval: true,
@@ -97,6 +97,7 @@ export interface ProviderDefinition extends AgentProviderDefinition {
/** Provider metadata and an unconfigured factory; the registry owns override application. */
export interface RegisteredProviderDefinition extends AgentProviderDefinition {
requiresConfiguration?: boolean;
iconSvg?: string;
supportsExactMcpPreapproval: boolean;
createClient: (logger: Logger, runtimeSettings?: ProviderRuntimeSettings) => AgentClient;
@@ -925,6 +926,8 @@ export function buildProviderRegistry(
throw new Error(`Plugin provider '${provider}' conflicts with a built-in provider`);
}
const override = providerOverrides[provider];
if (definition.requiresConfiguration && !override) continue;
if (override?.extends) {
logger.warn({ provider }, "Plugin provider shadowed by configured provider");
continue;
@@ -348,6 +348,10 @@ export class ProviderSnapshotManager {
return Object.prototype.hasOwnProperty.call(this.generation.definitions, provider);
}
supportsConfigRequiredProvider(provider: AgentProvider): boolean {
return this.pluginProviders.definitions()[provider]?.requiresConfiguration === true;
}
getProviderLabel(provider: AgentProvider): string {
return this.generation.definitions[provider]?.label ?? provider;
}
@@ -203,24 +203,26 @@ function stripClaudeAskUserQuestionUiMetadata(input: AgentMetadata): AgentMetada
};
}
export function normalizeClaudeAskUserQuestionUpdatedInput(
/**
* The answers this response will actually deliver, keyed by full question text,
* or null when there is no question list and answers map to work from.
*
* Shared by the normalizer and by the check that rejects an undeliverable
* answer, so the two can never disagree about what "deliverable" means.
*/
function resolveClaudeAskUserQuestionAnswers(
updatedInput: AgentMetadata | undefined,
fallbackInput: AgentMetadata | undefined,
): AgentMetadata {
): Record<string, string> | null {
const fallback = isMetadata(fallbackInput) ? fallbackInput : {};
const base = isMetadata(updatedInput) ? updatedInput : {};
// Paseo's shared question UI serializes answers by question header, but Claude's
// AskUserQuestion tool expects answer keys to match the full question text. Merge
// the original request payload back in so provider callbacks that only return
// `{ answers }` still satisfy Claude's full tool input schema.
const merged = stripClaudeAskUserQuestionUiMetadata({ ...fallback, ...base });
const questions =
(Array.isArray(base.questions) ? base.questions : null) ??
(Array.isArray(fallback.questions) ? fallback.questions : null);
const answers = isMetadata(base.answers) ? base.answers : null;
if (!questions || !answers) {
return merged;
return null;
}
const normalizedAnswers: Record<string, string> = {};
@@ -244,7 +246,23 @@ export function normalizeClaudeAskUserQuestionUpdatedInput(
}
}
if (Object.keys(normalizedAnswers).length === 0) {
return normalizedAnswers;
}
export function normalizeClaudeAskUserQuestionUpdatedInput(
updatedInput: AgentMetadata | undefined,
fallbackInput: AgentMetadata | undefined,
): AgentMetadata {
const fallback = isMetadata(fallbackInput) ? fallbackInput : {};
const base = isMetadata(updatedInput) ? updatedInput : {};
// Paseo's shared question UI serializes answers by question header, but Claude's
// AskUserQuestion tool expects answer keys to match the full question text. Merge
// the original request payload back in so provider callbacks that only return
// `{ answers }` still satisfy Claude's full tool input schema.
const merged = stripClaudeAskUserQuestionUiMetadata({ ...fallback, ...base });
const normalizedAnswers = resolveClaudeAskUserQuestionAnswers(updatedInput, fallbackInput);
if (!normalizedAnswers || Object.keys(normalizedAnswers).length === 0) {
return merged;
}
@@ -254,6 +272,32 @@ export function normalizeClaudeAskUserQuestionUpdatedInput(
};
}
class ClaudeQuestionAnswerRequiredError extends Error {
readonly code = "question_answer_required" as const;
constructor(readonly requestId: string) {
super(
`Permission request '${requestId}' requires updatedInput.answers keyed by a ` +
`question's full text or header, with a non-empty string value. ` +
`The request is still pending; retry with that shape.`,
);
this.name = "ClaudeQuestionAnswerRequiredError";
}
}
function assertClaudeQuestionAnswerDeliverable(
request: AgentPermissionRequest,
response: AgentPermissionResponse,
): void {
if (request.kind !== "question" || response.behavior !== "allow") {
return;
}
const answers = resolveClaudeAskUserQuestionAnswers(response.updatedInput, request.input);
if (!answers || Object.keys(answers).length === 0) {
throw new ClaudeQuestionAnswerRequiredError(request.id);
}
}
function isObjectRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
@@ -2734,6 +2778,12 @@ class ClaudeAgentSession implements AgentSession {
if (!pending) {
throw new Error(`No pending permission request with id '${requestId}'`);
}
// Before the delete below, so a rejected answer leaves the request pending
// and answerable rather than consuming it for nothing. AgentManager only
// drops its own copy once this resolves, so both maps survive the throw.
assertClaudeQuestionAnswerDeliverable(pending.request, response);
this.pendingPermissions.delete(requestId);
pending.cleanup?.();
@@ -0,0 +1,164 @@
import { describe, expect, test } from "vitest";
import type { CanUseTool, Query, SDKMessage } from "@anthropic-ai/claude-agent-sdk";
import { ClaudeAgentClient } from "./agent.js";
import type { ClaudeQueryFactory } from "./query.js";
import type { AgentPermissionResponse } from "../../agent-sdk-types.js";
import { createTestLogger } from "../../../../test-utils/test-logger.js";
// The SDK dependency receives the same permission callback as a real Claude process.
// Keep its stream open until close; permission state belongs entirely to the session.
function createSdkFake() {
let canUseTool: CanUseTool | undefined;
let finish!: () => void;
const finished = new Promise<void>((resolve) => {
finish = resolve;
});
const queryFactory: ClaudeQueryFactory = ({ options }) => {
canUseTool = options.canUseTool;
return {
close: finish,
return: async () => {
finish();
return { value: undefined, done: true };
},
[Symbol.asyncIterator]() {
return {
next: async (): Promise<IteratorResult<SDKMessage, void>> => {
await finished;
return { value: undefined, done: true };
},
};
},
} as Query;
};
return {
queryFactory,
ask: (input: Record<string, unknown>) => {
if (!canUseTool) throw new Error("SDK permission callback was not configured");
return canUseTool("AskUserQuestion", input, {
signal: new AbortController().signal,
toolUseID: "question-tool-call",
});
},
};
}
const questionInput = {
questions: [{ question: "Which colour?", header: "Colour", options: [], multiSelect: false }],
};
const invalidResponses: Array<[string, AgentPermissionResponse]> = [
["selectedActionId", { behavior: "allow", selectedActionId: "Viridian" }],
["missing answers", { behavior: "allow", updatedInput: {} }],
["unknown question", { behavior: "allow", updatedInput: { answers: { Hue: "Viridian" } } }],
["blank answer", { behavior: "allow", updatedInput: { answers: { Colour: " " } } }],
["non-string answer", { behavior: "allow", updatedInput: { answers: { Colour: 1 } } }],
[
"empty echoed questions",
{ behavior: "allow", updatedInput: { questions: [], answers: { Colour: "Viridian" } } },
],
];
describe("Claude question permission responses", () => {
test.each(invalidResponses)(
"rejects %s and delivers a corrected retry",
async (_label, response) => {
const sdk = createSdkFake();
const session = await new ClaudeAgentClient({
logger: createTestLogger(),
queryFactory: sdk.queryFactory,
resolveBinary: async () => "/test/claude/bin",
}).createSession({ provider: "claude", cwd: process.cwd(), modeId: "default" });
try {
await session.startTurn("Ask which colour");
const answer = sdk.ask(questionInput);
void answer.catch(() => undefined);
const request = session.getPendingPermissions()[0]!;
expect(request.kind).toBe("question");
await expect(session.respondToPermission(request.id, response)).rejects.toMatchObject({
code: "question_answer_required",
requestId: request.id,
});
expect(session.getPendingPermissions()).toEqual([request]);
await session.respondToPermission(request.id, {
behavior: "allow",
updatedInput: { answers: { Colour: "Viridian" } },
});
await expect(answer).resolves.toMatchObject({
behavior: "allow",
updatedInput: { answers: { "Which colour?": "Viridian" } },
});
expect(session.getPendingPermissions()).toEqual([]);
} finally {
await session.close();
}
},
);
test.each([
["header", questionInput, { Colour: "Viridian" }, { "Which colour?": "Viridian" }],
["question text", questionInput, { "Which colour?": "Ochre" }, { "Which colour?": "Ochre" }],
[
"padded question text",
{ questions: [{ question: " Which colour? ", header: " Colour " }] },
{ " Which colour? ": "Ochre" },
{ " Which colour? ": "Ochre" },
],
[
"padded header",
{ questions: [{ question: " Which colour? ", header: " Colour " }] },
{ " Colour ": "Viridian" },
{ " Which colour? ": "Viridian" },
],
[
"partial answer",
{ questions: [...questionInput.questions, { question: "Ship it?", header: "Ship" }] },
{ Ship: "Yes" },
{ "Ship it?": "Yes" },
],
])("delivers answers keyed by %s", async (_label, input, answers, expected) => {
const sdk = createSdkFake();
const session = await new ClaudeAgentClient({
logger: createTestLogger(),
queryFactory: sdk.queryFactory,
resolveBinary: async () => "/test/claude/bin",
}).createSession({ provider: "claude", cwd: process.cwd(), modeId: "default" });
try {
await session.startTurn("Ask which colour");
const answer = sdk.ask(input);
void answer.catch(() => undefined);
const request = session.getPendingPermissions()[0]!;
await session.respondToPermission(request.id, {
behavior: "allow",
updatedInput: { answers },
});
await expect(answer).resolves.toMatchObject({
behavior: "allow",
updatedInput: { answers: expected },
});
expect(session.getPendingPermissions()).toEqual([]);
} finally {
await session.close();
}
});
test("allows denying a question without answers", async () => {
const sdk = createSdkFake();
const session = await new ClaudeAgentClient({
logger: createTestLogger(),
queryFactory: sdk.queryFactory,
resolveBinary: async () => "/test/claude/bin",
}).createSession({ provider: "claude", cwd: process.cwd(), modeId: "default" });
try {
await session.startTurn("Ask which colour");
const answer = sdk.ask(questionInput);
void answer.catch(() => undefined);
const request = session.getPendingPermissions()[0]!;
await session.respondToPermission(request.id, { behavior: "deny", message: "No answer" });
await expect(answer).resolves.toMatchObject({ behavior: "deny", message: "No answer" });
expect(session.getPendingPermissions()).toEqual([]);
} finally {
await session.close();
}
});
});
@@ -3,6 +3,7 @@ import type {
AgentPermissionResponse,
AgentProvider,
} from "../../agent-sdk-types.js";
import { splitMultiSelectAnswer } from "../question-card-answer.js";
import type { OmpAgentMessage, OmpRuntimeEvent } from "./rpc-types.js";
type UiRequest = Extract<OmpRuntimeEvent, { type: "extension_ui_request" }>;
@@ -176,21 +177,7 @@ function selectedAnswer(
return labels.includes(answer)
? { selected: [answer], custom: null }
: { selected: [], custom: answer };
// The shared question UI sends a comma-joined answer in click order. Consume
// exact option labels from the front; any remaining text is the Other answer.
let remaining = answer;
const selected: string[] = [];
while (remaining.length > 0) {
const label = labels
.filter((candidate) => !selected.includes(candidate))
.sort((left, right) => right.length - left.length)
.find((candidate) => remaining === candidate || remaining.startsWith(`${candidate}, `));
if (!label) break;
selected.push(label);
remaining = remaining === label ? "" : remaining.slice(label.length + 2);
}
return { selected, custom: remaining || null };
return splitMultiSelectAnswer(answer, labels);
}
/** Owns OMP question mapping and the ask tool's multi-RPC answer sequence. */
@@ -0,0 +1,48 @@
import { TimelineProjection } from "../../../timeline-projection.js";
import { V2Timeline } from "../v2/timeline.js";
// Streams one reasoning part through the timeline into the daemon's projection and
// prints the bytes still held once the part is complete.
const mode = process.argv[2];
const chunks = Number(process.argv[3]);
if (mode !== "delta" && mode !== "snapshot") throw new Error("Mode must be delta or snapshot");
if (!global.gc) throw new Error("Run with --expose-gc");
global.gc();
const before = process.memoryUsage().heapUsed;
const timeline = new V2Timeline();
const projection = new TimelineProjection();
const part = { assistantMessageID: "answer", type: "reasoning" as const, ordinal: 0 };
timeline.startPart(part);
let text = "";
for (let index = 0; index < chunks; index++) {
const delta = `chunk-${index}:`.padEnd(64, String.fromCharCode(65 + (index % 26)));
text += delta;
const event =
mode === "delta"
? timeline.delta({ ...part, delta })
: timeline.messages([
{
id: "answer",
type: "assistant",
agent: "build",
model: { providerID: "test", id: "model" },
time: { created: 2 },
content: [{ type: "reasoning", text }],
},
])[0];
if (event?.type !== "timeline") throw new Error("Expected a timeline event");
projection.append({
seq: index + 1,
timestamp: "2026-10-01T00:00:00.000Z",
turnId: "turn",
item: event.item,
});
}
global.gc();
const retainedBytes = process.memoryUsage().heapUsed - before;
const [row] = projection.getRows();
if (row?.item.type !== "reasoning" || row.item.text !== text) {
throw new Error("Projection lost the streamed text");
}
process.stdout.write(String(retainedBytes));
@@ -109,7 +109,7 @@ describe("OpenCode v2 question tool", () => {
{ value: "Explore", label: "Explore", description: "Map the codebase" },
{ value: "Fix a bug", label: "Fix a bug", description: "Track down a bug" },
],
multiple: false,
multiSelect: false,
allowOther: true,
},
],
@@ -129,6 +129,99 @@ describe("OpenCode v2 question tool", () => {
await session.close();
}
});
test("answers a multi-select question with the checked options and a typed answer", async () => {
const harness = new V2Harness();
harness.api.session.form.list = async () => [
{
id: "question",
sessionID: "session",
title: "Questions",
fields: [
{
key: "q0",
title: "Fixes",
description: "Which fixes should I make?",
type: "multiselect",
options: [
{ value: "delete", label: "Delete both" },
{ value: "delete-and-fix", label: "Delete both, fix code" },
{ value: "email", label: "Email the user" },
],
custom: true,
},
],
},
];
const answers: Parameters<V2Api["session"]["form"]["reply"]>[0][] = [];
harness.api.session.form.reply = async (input) => {
answers.push(input);
};
const client = new OpenCodeV2AgentClient({
logger: createTestLogger(),
runtime: harness.runtime,
});
const session = await client.createSession({ provider: "opencode", cwd: "/tmp/project" });
try {
const [request] = session.getPendingPermissions();
expect(request.input).toMatchObject({ questions: [{ header: "Fixes", multiSelect: true }] });
await session.respondToPermission("question", {
behavior: "allow",
updatedInput: {
answers: { Fixes: "Delete both, fix code, Email the user, Also check the logs" },
},
});
expect(answers).toEqual([
{
sessionID: "session",
formID: "question",
answer: { q0: ["delete-and-fix", "email", "Also check the logs"] },
},
]);
expect(session.getPendingPermissions()).toHaveLength(0);
} finally {
await session.close();
}
});
test("rejects typed text on a multi-select question that has no typed answer", async () => {
const harness = new V2Harness();
harness.api.session.form.list = async () => [
{
id: "question",
sessionID: "session",
title: "Questions",
fields: [
{
key: "q0",
title: "Fixes",
type: "multiselect",
options: [{ value: "delete", label: "Delete both" }],
},
],
},
];
const answers: Parameters<V2Api["session"]["form"]["reply"]>[0][] = [];
harness.api.session.form.reply = async (input) => {
answers.push(input);
};
const client = new OpenCodeV2AgentClient({
logger: createTestLogger(),
runtime: harness.runtime,
});
const session = await client.createSession({ provider: "opencode", cwd: "/tmp/project" });
try {
await expect(
session.respondToPermission("question", {
behavior: "allow",
updatedInput: { answers: { Fixes: "Delete both, Something else" } },
}),
).rejects.toThrow("Invalid answer for OpenCode question q0");
expect(answers).toEqual([]);
} finally {
await session.close();
}
});
});
describe("OpenCode v2 permission routing", () => {
@@ -7,6 +7,7 @@ import type {
AgentSessionConfig,
AgentStreamEvent,
} from "../../../agent-sdk-types.js";
import { splitMultiSelectAnswer } from "../../question-card-answer.js";
export class SessionPermissions {
private readonly pending = new Map<string, AgentPermissionRequest>();
@@ -109,7 +110,7 @@ export class SessionPermissions {
header: field.title ?? field.key,
question: field.description ?? field.title ?? field.key,
options: "options" in field ? field.options : undefined,
multiple: field.type === "multiselect",
multiSelect: field.type === "multiselect",
allowOther: "custom" in field && field.custom === true,
})),
},
@@ -143,8 +144,8 @@ function formAnswer(field: FormInfo["fields"][number], value: unknown): FormValu
);
};
if (field.type === "multiselect") {
if (Array.isArray(value) && value.every((item: unknown) => typeof item === "string"))
return value.map(labelValue);
const selected = multiSelectAnswer(field, value);
if (selected) return selected.map(labelValue);
} else if (field.type === "string" && typeof value === "string") {
return labelValue(value);
} else if (field.type === "boolean") {
@@ -162,3 +163,17 @@ function formAnswer(field: FormInfo["fields"][number], value: unknown): FormValu
}
throw new Error(`Invalid answer for OpenCode question ${field.key}`);
}
type MultiSelectField = Extract<FormInfo["fields"][number], { type: "multiselect" }>;
function multiSelectAnswer(field: MultiSelectField, value: unknown): string[] | undefined {
if (Array.isArray(value) && value.every((item: unknown) => typeof item === "string"))
return value;
if (typeof value !== "string") return undefined;
const { selected, custom } = splitMultiSelectAnswer(
value,
field.options.map((option) => option.label),
);
if (custom === null) return selected;
return field.custom === true ? [...selected, custom] : undefined;
}
@@ -1,4 +1,6 @@
import type { SessionMessageAssistant } from "@opencode/client";
import { execFileSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { expect, test } from "vitest";
import { V2Timeline } from "./timeline.js";
@@ -95,3 +97,38 @@ test("a tool's image output is shown as an image, not as base64 in the tool outp
]);
expect(timeline.messages([screenshot])).toEqual([]);
});
test("a surrogate pair split across deltas streams back intact", () => {
const timeline = new V2Timeline();
const part = { assistantMessageID: "answer", type: "text" as const, ordinal: 0 };
timeline.startPart(part);
const chunks = ["a\uD83D", "\uDE00b"].map((delta) => {
const event = timeline.delta({ ...part, delta });
return event?.type === "timeline" && event.item.type === "assistant_message"
? event.item.text
: null;
});
expect(chunks).toEqual(["a\uD83D", "\uDE00b"]);
expect(chunks.join("")).toBe("a😀b");
});
function retainedBytesAfterStreaming(mode: "delta" | "snapshot", chunks: number): number {
const fixture = fileURLToPath(
new URL("../test-utils/v2-streamed-text-memory.ts", import.meta.url),
);
const output = execFileSync(
process.execPath,
["--expose-gc", "--import", "tsx", fixture, mode, String(chunks)],
{ encoding: "utf8" },
);
return Number(output);
}
test.each(["delta", "snapshot"] as const)(
"a long %s-streamed part holds memory in proportion to its text",
(mode) => {
const chunks = 2000;
const textBytes = chunks * 64;
expect(retainedBytesAfterStreaming(mode, chunks)).toBeLessThan(textBytes * 32);
},
);
@@ -12,6 +12,13 @@ function textPartKey(messageID: string, part: "text" | "reasoning", ordinal: num
return `${messageID}:${part}:${ordinal}`;
}
// A `slice` can share its source's storage, so every streamed chunk kept by the timeline
// store would hold the whole text it was cut from. Copying the UTF-16 code units makes
// the chunk independent; UTF-8 would corrupt a surrogate pair split across chunks.
function detachedSuffix(text: string, start: number): string {
return Buffer.from(text.slice(start), "utf16le").toString("utf16le");
}
// Text and reasoning each number parts from zero, independent of snapshot position.
export class V2Timeline {
private readonly content = new Map<string, string>();
@@ -40,7 +47,7 @@ export class V2Timeline {
if (!text.startsWith(emitted))
throw new Error("OpenCode changed previously emitted message content");
this.content.set(key, text);
const suffix = text.slice(emitted.length);
const suffix = detachedSuffix(text, emitted.length);
const item: AgentTimelineItem =
event.type === "text"
? { type: "assistant_message", text: suffix, messageId: event.assistantMessageID }
@@ -143,7 +150,7 @@ export class V2Timeline {
if (!part.text.startsWith(previous))
throw new Error("OpenCode changed previously emitted message content");
this.content.set(key, part.text);
const suffix = part.text.slice(previous.length);
const suffix = detachedSuffix(part.text, previous.length);
if (part.type === "text")
push({ type: "assistant_message", text: suffix, messageId: messageID });
else push({ type: "reasoning", text: suffix });
@@ -0,0 +1,32 @@
import { describe, expect, test } from "vitest";
import { splitMultiSelectAnswer } from "./question-card-answer.js";
describe("splitMultiSelectAnswer", () => {
const labels = ["Delete both", "Delete both, fix code", "Email the user"];
test("splits checked labels in click order", () => {
expect(splitMultiSelectAnswer("Email the user, Delete both", labels)).toEqual({
selected: ["Email the user", "Delete both"],
custom: null,
});
});
test("keeps a label that contains a comma as one selection", () => {
expect(splitMultiSelectAnswer("Delete both, fix code, Email the user", labels)).toEqual({
selected: ["Delete both, fix code", "Email the user"],
custom: null,
});
});
test("returns trailing text as the typed answer", () => {
expect(splitMultiSelectAnswer("Delete both, Also check the logs", labels)).toEqual({
selected: ["Delete both"],
custom: "Also check the logs",
});
expect(splitMultiSelectAnswer("Only typed text", labels)).toEqual({
selected: [],
custom: "Only typed text",
});
});
});
@@ -0,0 +1,23 @@
/**
* The shared question card sends a multi-select answer as one string: the checked option
* labels in click order, then any typed answer, joined with ", ". Consume exact option
* labels from the front, longest first so a label containing ", " wins over its prefix;
* any remaining text is the typed answer.
*/
export function splitMultiSelectAnswer(
answer: string,
labels: string[],
): { selected: string[]; custom: string | null } {
let remaining = answer;
const selected: string[] = [];
while (remaining.length > 0) {
const label = labels
.filter((candidate) => !selected.includes(candidate))
.sort((left, right) => right.length - left.length)
.find((candidate) => remaining === candidate || remaining.startsWith(`${candidate}, `));
if (!label) break;
selected.push(label);
remaining = remaining === label ? "" : remaining.slice(label.length + 2);
}
return { selected, custom: remaining || null };
}
@@ -0,0 +1,37 @@
// Local ACP peer for the bundled Hoplite adapter; no Hoplite service or credentials.
const fs = require("node:fs");
const readline = require("node:readline");
fs.appendFileSync(process.env.HOPLITE_TEST_RECORD, "launch\n");
const configOptions = [
{
id: "model",
category: "model",
type: "select",
name: "Model",
currentValue: "fixture-model",
options: [{ value: "fixture-model", name: "Fixture model" }],
},
];
const send = (message) =>
process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\n");
readline.createInterface({ input: process.stdin }).on("line", (line) => {
const request = JSON.parse(line);
if (request.id === undefined) return;
let result = {};
if (request.method === "initialize")
result = { protocolVersion: 1, agentCapabilities: {}, authMethods: [] };
if (request.method === "session/new")
result = {
sessionId: "hoplite-fixture",
configOptions,
};
if (request.method === "session/set_config_option") result = { configOptions };
if (request.method === "session/prompt") {
send({
method: "_hoplite/run_phase",
params: { runId: "fixture-run", phase: "provisioning", label: "Preparing fixture workspace" },
});
result = { stopReason: "end_turn" };
}
send({ id: request.id, result });
});
@@ -1,7 +1,8 @@
import { describe, test, expect } from "vitest";
import { mkdtemp, rm } from "node:fs/promises";
import { mkdtemp, rm, readFile, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { loadConfig } from "../config.js";
import { findExecutable } from "../../executable-resolution/executable-resolution.js";
import { BuiltinPluginLoader } from "../plugins/builtin/index.js";
import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js";
@@ -162,3 +163,125 @@ test("Antigravity creates an agent and answers a prompt with real agy", async ({
await rm(cwd, { recursive: true, force: true });
}
}, 120000);
test("bundled Hoplite requires a config entry and removal survives restart", async () => {
const root = await mkdtemp(path.join(os.tmpdir(), "paseo-hoplite-optin-"));
const record = path.join(root, "launches.txt");
await writeFile(record, "");
const options = {
paseoHomeRoot: root,
cleanup: false,
mcpEnabled: false,
builtinPlugins: new BuiltinPluginLoader(undefined, [
"hoplite-provider",
"antigravity-provider",
]),
};
let daemon = await createTestPaseoDaemon(options);
const connect = async () => {
const client = new DaemonClient({
url: `ws://127.0.0.1:${daemon.port}/ws`,
appVersion: "0.11.2",
});
await client.connect();
await client.fetchAgents({ subscribe: {} });
return client;
};
let client = await connect();
try {
const before = await client.getProvidersSnapshot();
expect(before.entries.some((entry) => entry.provider === "hoplite")).toBe(false);
expect(before.entries.some((entry) => entry.provider === "antigravity")).toBe(true);
expect(await readFile(record, "utf8")).toBe("");
await client.patchDaemonConfig({
providers: {
hoplite: {
enabled: true,
command: [process.execPath, path.resolve(import.meta.dirname, "hoplite-fixture.cjs")],
env: { HOPLITE_TEST_RECORD: record },
},
},
});
await expect
.poll(
async () =>
(await client.getProvidersSnapshot()).entries.find(
(entry) => entry.provider === "hoplite",
)?.status,
)
.toBe("ready");
expect((await client.listProviderModels("hoplite")).models.map((model) => model.id)).toEqual([
"fixture-model",
]);
const agent = await client.createAgent({
provider: "hoplite",
cwd: root,
model: "fixture-model",
});
await client.sendMessage(agent.id, "Exercise the contributor transformer");
await client.waitForFinish(agent.id, 10000);
const timeline = await client.fetchAgentTimeline(agent.id, { limit: 100 });
expect(timeline.entries.map((entry) => entry.item)).toContainEqual(
expect.objectContaining({
type: "tool_call",
name: "Hoplite workspace",
status: "completed",
}),
);
await client.archiveAgent(agent.id);
expect(await readFile(record, "utf8")).toContain("launch");
await client.patchDaemonConfig({ providers: { hoplite: { enabled: false } } });
expect(
(await client.getProvidersSnapshot()).entries.find((entry) => entry.provider === "hoplite")
?.enabled,
).toBe(false);
await client.close();
await daemon.close();
daemon = await createTestPaseoDaemon({
...options,
staticDir: daemon.staticDir,
providerOverrides: loadConfig(daemon.paseoHome, { env: {} }).providerOverrides,
});
client = await connect();
expect(
(await client.getProvidersSnapshot()).entries.find((entry) => entry.provider === "hoplite")
?.enabled,
).toBe(false);
await client.patchDaemonConfig({ removeProviders: ["hoplite"] });
expect(
(await client.getProvidersSnapshot()).entries.some((entry) => entry.provider === "hoplite"),
).toBe(false);
expect((await client.getDaemonConfig()).config.providers?.hoplite).toBeUndefined();
const persisted = JSON.parse(
await readFile(path.join(daemon.paseoHome, "config.json"), "utf8"),
);
expect(persisted.agents?.providers?.hoplite).toBeUndefined();
const launchesAfterRemoval = await readFile(record, "utf8");
await client.close();
await daemon.close();
daemon = await createTestPaseoDaemon({
...options,
staticDir: daemon.staticDir,
providerOverrides: loadConfig(daemon.paseoHome, { env: {} }).providerOverrides,
});
client = await connect();
const restarted = await client.getProvidersSnapshot();
expect(restarted.entries.some((entry) => entry.provider === "hoplite")).toBe(false);
expect(restarted.entries.map((entry) => entry.provider)).toEqual(
before.entries.map((entry) => entry.provider),
);
expect(await readFile(record, "utf8")).toBe(launchesAfterRemoval);
await client.patchDaemonConfig({ providers: { hoplite: { enabled: false } } });
expect(
(await client.getProvidersSnapshot()).entries.find((entry) => entry.provider === "hoplite")
?.enabled,
).toBe(false);
} finally {
await client.close();
await daemon.close();
await rm(root, { recursive: true, force: true });
await rm(daemon.staticDir, { recursive: true, force: true });
}
}, 60000);
@@ -9,6 +9,7 @@ export const builtinPlugins = [
"copilot-usage-source",
"cursor-usage-source",
"grok-usage-source",
"hoplite-provider",
"kimi-usage-source",
"minimax-usage-source",
"muse-provider",
@@ -138,6 +138,51 @@ async function createRootAlias(directory: string): Promise<string> {
}
describe("plugin runtime entries", () => {
it.each([
'import type { AgentTimelineItem, ToolCallDetail } from "@getpaseo/protocol/agent-types"; export type Detail = ToolCallDetail; export type Item = AgentTimelineItem;',
'import { type AgentTimelineItem } from "@getpaseo/protocol/agent-types"; export type Item = AgentTimelineItem;',
'export type { AgentTimelineItem } from "@getpaseo/protocol/agent-types";',
'export type Item = import("@getpaseo/protocol/agent-types").AgentTimelineItem;',
'export type { AgentAttachment } from "@getpaseo/protocol/messages";',
])("compiles protocol types without local dependencies: %s", async (typeSource) => {
const entries = await createSplitPlugin();
await writeFile(
path.join(entries.directory, "shared", "labels.ts"),
`${typeSource}\nexport const clientLabel = "Client contribution"; export const serverLabel = "Server contribution";`,
);
const result = await compilePlugin(entries);
expect(result.clientBundle).toContain("Client contribution");
expect(result.serverBundle).toContain("Server contribution");
expect(result.clientBundle).not.toContain("@getpaseo/protocol");
expect(result.serverBundle).not.toContain("@getpaseo/protocol");
});
it("still requires local dependencies for protocol runtime imports", async () => {
const entries = await createSplitPlugin();
await writeFile(
entries.server,
'import { TOOL_CALL_ICON_NAMES } from "@getpaseo/protocol/agent-types"; export default () => TOOL_CALL_ICON_NAMES;',
);
await expect(compilePlugin(entries)).rejects.toThrow(
'Could not resolve "@getpaseo/protocol/agent-types"',
);
});
it("still rejects missing third-party type dependencies", async () => {
const entries = await createSplitPlugin();
await writeFile(
entries.client,
'import type { Item } from "missing-types"; export default (item: Item) => item;',
);
await expect(compilePlugin(entries)).rejects.toThrow(
'Could not resolve type dependency "missing-types"',
);
});
it.each([
"react",
"react/jsx-runtime",
@@ -245,6 +245,10 @@ function createRuntimeBoundaryPlugin(target: PluginBuildTarget, pluginDirectory:
runtimeSpecifierError(packageSpecifier, owner, file) ??
lexicalBoundaryError(specifier, path.dirname(file), pluginDirectory, owner);
if (error) return error;
// Protocol types are shared host contracts, also exposed by the SDK's peer
// dependency during development. Erased imports need no plugin-local install;
// runtime imports still go through normal dependency resolution below.
if (typeOnly && specifier.startsWith("@getpaseo/protocol/")) continue;
// Host modules have separately enforced SDK boundaries and need no local installation.
if (
(PLUGIN_SDK_SPECIFIERS as readonly string[]).includes(specifier) ||
@@ -629,6 +629,7 @@ export class PluginService {
label: provider.label,
description: provider.description,
command: provider.command,
requiresConfiguration: provider.requiresConfiguration,
status: provider.hasStatus
? (request) => {
if (!this.runtime.getProviderStatus)
@@ -14,6 +14,7 @@ import {
import { z } from "zod";
export interface PluginProviderMetadata {
requiresConfiguration?: boolean;
hasCatalogCacheKey?: boolean;
hasStatus?: boolean;
command?: readonly [string, ...string[]];
@@ -112,6 +113,7 @@ const providerMetadataSchema = z
label: z.string().min(1),
description: z.string().optional(),
iconPath: z.string().optional(),
requiresConfiguration: z.boolean().optional(),
hasCatalogCacheKey: z.boolean().optional(),
hasStatus: z.boolean().optional(),
command: z.tuple([z.string().min(1)], z.string()).optional(),
@@ -158,6 +158,7 @@ export function createPluginWorker(options: {
label: provider.label,
description: provider.description,
iconPath: provider.icon,
requiresConfiguration: provider.requiresConfiguration,
hasCatalogCacheKey: provider.getCatalogCacheKey !== undefined,
hasStatus: provider.status !== undefined,
command: provider.command,
@@ -240,6 +240,7 @@ export function createProviderSnapshotManagerStub(): {
const off = vi.fn();
const destroy = vi.fn<ProviderSnapshotManager["destroy"]>();
const stub = {
supportsConfigRequiredProvider: () => false,
getSnapshot,
refreshSnapshotForCwd,
refreshSettingsSnapshot,
@@ -1141,6 +1141,7 @@ describe("relay external socket reconnect behavior", () => {
expect(serverInfo.features?.stableProjectIdentity).toBe(true);
expect(serverInfo.features?.canonicalSubmittedPrompts).toBe(true);
expect(serverInfo.features?.providersSnapshotCwd).toBe(true);
expect(serverInfo.features?.hopliteProvider).toBe(false);
expect(serverInfo.features?.pluginLogs).toBe(true);
expect(serverInfo.features?.workspaceMarkUnread).toBe(true);
expect(serverInfo.features?.["terminal-input-mode-replay"]).toBe(true);
@@ -1915,6 +1915,7 @@ export class VoiceAssistantWebSocketServer {
commitBaseClassification: true,
// COMPAT(providerRemoval): added in v0.1.105, drop the gate when floor >= v0.1.105.
providerRemoval: true,
hopliteProvider: this.providerSnapshotManager.supportsConfigRequiredProvider("hoplite"),
// COMPAT(importSessionWorkspaceTarget): added in v0.1.110, remove gate after 2027-01-16.
importSessionWorkspaceTarget: true,
// COMPAT(importSessionSearch): added in v0.7.3, remove gate after 2027-03-02.
+3 -3
View File
@@ -19,9 +19,9 @@ export default defineConfig({
setupFiles: [path.resolve(__dirname, "./src/test-utils/vitest-setup.ts")],
pool: "forks",
fileParallelism: false,
// Windows runners intermittently starve subprocess-heavy Git tests at the
// default worker count, leaving child processes alive past their deadlines.
maxWorkers: process.platform === "win32" ? 2 : undefined,
// Even two concurrent Git-heavy suites can exhaust Windows test deadlines.
// Run files serially so their subprocesses do not compete across suites.
maxWorkers: process.platform === "win32" ? 1 : undefined,
exclude: ["**/node_modules/**", "**/dist/**", "**/.claude/**", "**/.dev/**"],
},
});
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="1.394 1.679 8.494 7.828" fill="currentColor"><path d="M8.237 7.813C8.276 7.789 8.327 7.796 8.358 7.83L9.741 9.346C9.797 9.407 9.754 9.506 9.671 9.507H8.977C8.924 9.507 8.881 9.463 8.881 9.41V9.125C8.881 9.089 8.861 9.057 8.83 9.04L7.589 8.379C7.524 8.344 7.521 8.251 7.584 8.212L8.237 7.813ZM3.944 1.679C4.502 1.679 5.052 1.82 5.54 2.09L5.962 2.323C6.024 2.358 6.029 2.446 5.97 2.486L5.091 3.09C5.065 3.108 5.05 3.137 5.05 3.169V3.495C5.05 3.529 5.032 3.561 5.003 3.578L4.68 3.769C4.594 3.82 4.498 3.722 4.549 3.637L4.592 3.566C4.63 3.502 4.584 3.421 4.51 3.421H4.028C3.925 3.421 3.894 3.562 3.989 3.604L4.377 3.775C4.448 3.806 4.455 3.904 4.389 3.944L3.77 4.323C3.755 4.332 3.737 4.337 3.72 4.337H3.361C3.309 4.337 3.268 4.379 3.268 4.431C3.268 4.484 3.309 4.526 3.361 4.526H3.779C3.797 4.526 3.814 4.521 3.829 4.513L7.599 2.272C8.135 1.954 8.815 2.008 9.294 2.407C9.307 2.418 9.314 2.434 9.314 2.451V2.729C9.315 2.812 9.413 2.856 9.475 2.8L9.728 2.57C9.789 2.514 9.888 2.558 9.888 2.641V5.812C9.888 5.865 9.845 5.908 9.792 5.908H9.359C9.331 5.908 9.303 5.895 9.285 5.873L8.374 4.773C8.337 4.728 8.268 4.728 8.229 4.771L7.468 5.625C7.429 5.669 7.438 5.737 7.487 5.769L9.038 6.776C9.098 6.815 9.096 6.903 9.035 6.939L6.618 8.363C6.556 8.4 6.478 8.358 6.474 8.286L6.439 7.633C6.437 7.578 6.48 7.532 6.535 7.532H6.925C6.948 7.532 6.971 7.523 6.988 7.508L7.211 7.31C7.276 7.252 7.236 7.144 7.148 7.142L5.991 7.118H1.49C1.437 7.118 1.394 7.075 1.394 7.022V3.308C1.394 3.255 1.437 3.212 1.49 3.212H2.544C2.597 3.212 2.64 3.169 2.64 3.116V2.969C2.64 2.916 2.597 2.873 2.544 2.873H1.461C1.366 2.873 1.329 2.75 1.408 2.697L2.134 2.221C2.672 1.867 3.301 1.679 3.944 1.679Z"/></svg>

After

Width:  |  Height:  |  Size: 1.7 KiB

+7
View File
@@ -0,0 +1,7 @@
import type { PluginServerContext } from "@getpaseo/plugin/server";
import { createHopliteProvider } from "./server/provider.js";
export default function contribute(server: PluginServerContext) {
server.registerProvider(createHopliteProvider());
return () => {};
}
@@ -0,0 +1 @@
{ "id": "hoplite-provider", "requirements": { "paseo": ">=0.11.0" } }
@@ -0,0 +1,17 @@
import { runAcpProvider } from "@getpaseo/plugin/server/acp";
import type { ProviderRegistration } from "@getpaseo/plugin/server/provider";
import { runPhaseTransformer } from "./run-phase.js";
export function createHopliteProvider(): ProviderRegistration {
return {
requiresConfiguration: true,
...runAcpProvider({
id: "hoplite",
label: "Hoplite",
description: "Hoplite's coding agent through the local `hoplite acp` bridge",
icon: "icon.svg",
command: ["hoplite", "acp"],
transformers: [runPhaseTransformer],
}),
};
}
@@ -0,0 +1,74 @@
import { describe, expect, it } from "vitest";
import { runPhaseTransformer } from "./run-phase.js";
const context = { sessionId: "session-1" };
// Frames captured from `hoplite acp` 3.0.0.
function runPhase(phase: string | null, label: string | null) {
return {
method: "_hoplite/run_phase",
params: {
sessionId: "thr_c75d39f7d7624256af918eeee2f4941b",
runId: "run_eb213b97bd3147afb2927fbc27f87180",
phase,
label,
startedAt: phase === null ? null : "2026-10-04T17:51:46.311Z",
},
};
}
describe("runPhaseTransformer", () => {
it("shows a provisioning phase as one running workspace item per run", () => {
const update = runPhaseTransformer.notification?.(
runPhase("fetching_repository", "Cloning repository"),
context,
);
expect(update).toEqual({
type: "timeline",
item: {
type: "tool_call",
id: "hoplite-run-phase:run_eb213b97bd3147afb2927fbc27f87180",
callId: "hoplite-run-phase:run_eb213b97bd3147afb2927fbc27f87180",
name: "Hoplite workspace",
detail: { type: "plain_text", label: "Cloning repository", icon: "wrench" },
status: "running",
error: null,
},
});
});
it("completes the same item when the run leaves provisioning", () => {
const update = runPhaseTransformer.notification?.(runPhase(null, null), context);
expect(update).toMatchObject({
type: "timeline",
item: {
id: "hoplite-run-phase:run_eb213b97bd3147afb2927fbc27f87180",
status: "completed",
detail: { label: "Workspace ready" },
},
});
});
it("falls back to the phase name when Hoplite sends no label", () => {
const update = runPhaseTransformer.notification?.(
runPhase("configuring_workspace", null),
context,
);
expect(update).toMatchObject({ item: { detail: { label: "configuring_workspace" } } });
});
it("ignores other vendor notifications and malformed phases", () => {
expect(
runPhaseTransformer.notification?.({ method: "_hoplite/other", params: {} }, context),
).toBeNull();
expect(
runPhaseTransformer.notification?.(
{ method: "_hoplite/run_phase", params: { phase: "x" } },
context,
),
).toBeNull();
});
});
@@ -0,0 +1,39 @@
import type { AcpTransformer } from "@getpaseo/plugin/server/acp";
import { z } from "zod";
// Hoplite provisions a cloud workspace before the first agent output of a run and reports each
// step as `_hoplite/run_phase`. A null phase ends provisioning for that run.
const runPhaseSchema = z.object({
runId: z.string().min(1),
phase: z.string().nullable(),
label: z.string().nullable(),
});
const RUN_PHASE_METHOD = "_hoplite/run_phase";
export const runPhaseTransformer: AcpTransformer = {
notification(notification) {
if (notification.method !== RUN_PHASE_METHOD) return null;
const params = runPhaseSchema.safeParse(notification.params);
if (!params.success) return null;
const { runId, phase, label } = params.data;
const id = `hoplite-run-phase:${runId}`;
const running = phase !== null;
return {
type: "timeline",
item: {
type: "tool_call",
id,
callId: id,
name: "Hoplite workspace",
detail: {
type: "plain_text",
label: running ? (label ?? phase) : "Workspace ready",
icon: "wrench",
},
status: running ? "running" : "completed",
error: null,
},
};
},
};
+9 -6
View File
@@ -228,11 +228,12 @@ The output includes each script's lifecycle and supervised terminal ID. Services
Create and manage trusted plugins on a daemon:
```bash
paseo plugin init /absolute/path/to/plugin
paseo plugin install /absolute/path/to/plugin
paseo plugin add owner/repository
paseo plugin init ./plugin
paseo plugin install ./plugin
paseo plugin add owner/slug
paseo plugin add git:owner/repository
paseo plugin add https://gitlab.com/group/repository.git --ref main
paseo plugin add owner/monorepo:plugins/review
paseo plugin add git:owner/monorepo:plugins/review
paseo plugin ls [id]
paseo plugin update my-plugin
paseo plugin update --all
@@ -243,8 +244,10 @@ paseo plugin enable my-plugin
paseo plugin remove my-plugin
```
GitHub shorthand checks an existing host directory first. Append `:<directory>` for a plugin in a
monorepo. `paseo plugin ls [id]` does not contact the remote. `paseo plugin logs <id>` returns the
Bare `owner/slug` installs a reviewed registry listing. Use `git:owner/repository` for GitHub
source, or `./plugin` for a local directory. Append `:<directory>` for a plugin in a monorepo.
`paseo plugin ls [id]` does not contact the remote. `paseo plugin logs <id>` returns the
plugin's recent daemon-side stdout and stderr. Add `--json` for structured entries, or run
`paseo --host <target> plugin logs <id>` for another daemon. See the
[Plugin reference](/docs/plugins/reference) for installation, trust, lifecycle, and log-retention
+4 -5
View File
@@ -10,12 +10,11 @@ category: Getting started
These projects are related to Paseo and built by the community.
## Plugin directory
## Plugins
[paseo.cafe](https://paseo.cafe) is a community-run directory of Paseo plugins. Listings are generated
from each plugin's public repository, so it is the fastest way to see what people are building and to
publish your own. It is independent of the Paseo project and nothing on it is reviewed or endorsed by
us, so read a plugin's source before installing it.
Browse the [plugin registry](/plugins) for reviewed community plugins. To share your own, follow
[Publish a plugin](/docs/plugins/publishing) for package preparation and submission.
Plugins run unsandboxed; read their listing and source before installing.
## Tools and integrations
+218 -189
View File
@@ -1,6 +1,6 @@
---
title: Publish a plugin
description: Share a Paseo plugin on npm, through a private registry, or from a Git repository.
description: Prepare, publish and submit a Paseo plugin to the reviewed registry.
nav: Publishing
order: 45
category: Plugins
@@ -8,111 +8,241 @@ category: Plugins
# Publish a plugin
Publish your plugin so other people can install and use it in Paseo. Start with a working
[plugin project](/docs/plugins), then choose where to share it:
Start with a working [plugin project](/docs/plugins). Prepare its listing, publish it on npm
or push it to GitHub, then submit it to the registry. After approval, users install the reviewed
version with `paseo plugin add owner/slug`.
- [Plugin registry](#plugin-registry): share a reviewed artifact users install by `owner/slug`.
- [npm](#publish-on-npm): publish a package on the public npm registry.
- [GitHub or Git](#share-through-github-or-git): let users install from a repository.
1. Prepare your [listing page](#your-listing-page) and, for a visual plugin, an
[interface image](#icons-and-screenshots).
2. [Publish on npm](#publish-on-npm) or [share through Git](#share-through-github-or-git).
3. [Submit to the plugin registry](#plugin-registry).
For a private plugin, use [direct Git installation](#share-through-github-or-git) or
[private npm packages](#private-npm-packages).
## Your listing page
You can submit without `OVERVIEW.md`; the reviewer creates a listing page from your README and
verified behavior. To maintain the page yourself, put `OVERVIEW.md` beside `paseo-plugin.json`
and include it in the published package. The scaffold already includes it in `files`.
Your shipped overview replaces the reviewer-written page.
Explain these points in order, using headings only when they help:
1. What the plugin does.
2. How it works, when that is not obvious.
3. Setup: settings, accounts, tokens, external tools, supported operating systems and Paseo versions.
4. Useful capabilities, settings, data access, permissions and limitations.
Describe where data goes, including prompts and tool results sent to agent providers. Local storage
does not mean data stays on the host. If the plugin downloads or installs software while running,
explain what it installs and its source, and require explicit user confirmation before the download.
This applies to activation and connection tests too; declining must leave the software uninstalled.
Use plain factual language and sentence case. Omit marketing, unsupported claims, badges,
changelogs, contributing and license sections, and implementation details that do not help someone
choose the plugin. The listing already provides plugin installation instructions.
The publication validator rejects `paseo plugin add`, `npm install` and `npm i` anywhere in an
overview, including development or setup examples. Link to your README for those commands.
Also supply a one-sentence description: use `package.json`'s `description` for npm or the manifest's
`description` for Git. The reviewer can fill in a missing description in the registry.
## Icons and screenshots
Themes, panels and other visual plugin interfaces need at least one image showing the current
interface. Use sample data and hide private details. An icon alone does not meet this requirement;
plugins without their own visual interface do not need screenshots.
Declare local images in `paseo-plugin.json` before publishing:
```json
{
"id": "review-tools",
"name": "Review tools",
"description": "Reviews changes before merge",
"icon": "assets/icon.png",
"media": ["assets/screenshot.png"],
"requirements": { "paseo": ">=0.11.0" }
}
```
Create the referenced files and include `assets/` in `package.json`'s `files` list for npm.
Paths are relative to the manifest, use forward slashes and stay inside the plugin directory.
These metadata fields require Paseo 0.11.0 or later.
| Field | Listing behavior |
| ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name` | Optional display name; defaults to a humanized plugin ID. |
| `icon` | Optional package-relative PNG. Provider registration icons have a separate [SVG contract](/docs/plugins/reference#providers). |
| `media` | Package-relative paths or public HTTPS URLs. Images: PNG, JPG, JPEG, WebP or GIF. Videos: MP4 or WebM. The first image is the card thumbnail; videos supplement it. |
Public media URLs need a supported file extension, matched case-insensitively, and must return
HTTP 200 with the corresponding image or video content type. SVG and extensionless attachment
URLs are not accepted as registry media.
Instead of declaring `media`, you can supply suitable public image URLs in the submission or
review PR. The reviewer can add them to the listing without a new plugin release.
## Publish on npm
### 1. Set package identity
Use an npm scope you can publish to and authenticate with `npm login`. From your plugin directory,
replace `@acme` and the repository below with your own values:
```bash
npm pkg set name=@acme/paseo-review version=1.0.0
npm pkg delete private
npm pkg set repository.type=git repository.url=git+https://github.com/acme/paseo-review.git
```
The current registry tooling requires a GitHub repository for npm listing ownership, supplied
through `package.json` or npm provenance. Set `repository` to your public source repository so
pinning can determine the listing owner. Provenance itself is optional; if present, its repository
must match the package's repository. A matching source checkout is not required for artifact review.
### 2. Lock installed dependencies
Keep Paseo's host libraries and type-only dependencies in `devDependencies`. Add other runtime
libraries to `dependencies`. For registry submission, every installed dependency tree needs a lock
with exact versions, resolved sources and integrity, including transitive dependencies.
For an npm package with installed runtime dependencies, update its lock without running lifecycle
scripts, then create the publishable lock:
```bash
npm install --package-lock-only --ignore-scripts
npm shrinkwrap
```
`npm shrinkwrap` converts `package-lock.json` into `npm-shrinkwrap.json`. npm publishes the shrinkwrap
at the package root; it does not publish `package-lock.json`. A repository-only lock or exact direct
version does not lock the dependency tree installed by your users.
Plugins using only host libraries and development dependencies need no runtime lock unless a
preparation command installs those dependencies. You can also bundle a library and remove the
runtime dependency declaration. See [preparation and additional setup](#plugins-with-a-build-step)
if your plugin installs a separate tree.
### 3. Check the package and publish
Generate any required files before checking the package; the dry run skips packing scripts.
```bash
npm run typecheck
npm pack --dry-run --ignore-scripts
```
Check the file list contains `paseo-plugin.json`, at least one runtime entry, every imported local
module, any overview and assets you declared, and the shrinkwrap when required. Repository-only import aliases
and files outside the package do not reach users. The scaffold includes the entries and `client/`,
`server/` and `shared/`; add other asset directories to `files`.
Confirm any declared preparation command succeeds with the Node/npm versions you support;
an out-of-sync or incompatible lockfile still blocks installation.
Publish the checked version:
```bash
npm publish --access public
```
On a test daemon, install that exact published version and exercise its contributions:
```bash
paseo plugin install npm:@acme/paseo-review@1.0.0
paseo plugin ls
```
Require `running` with no error, then [submit the package](#plugin-registry).
## Share through GitHub or Git
For the public registry, push your plugin to a public GitHub repository. Include its manifest,
runtime entries, imported files and listing assets. Git tags and commits are optional at submission;
provide one to select a revision, or the reviewer resolves `main`.
If preparation installs runtime npm dependencies, commit a synchronized `package-lock.json` and
add this command to `paseo-plugin.json`:
```json
{
"build": [["npm", "ci", "--omit=dev", "--ignore-scripts"]]
}
```
`npm ci` consumes the committed lock and fails if it disagrees with `package.json`. `--omit=dev`
excludes development tools and `--ignore-scripts` suppresses dependency lifecycle scripts.
The daemon needs npm on its command path. Plugins using only host libraries need no preparation
command. See [preparation](#plugins-with-a-build-step) for generated files or explicit scripts.
Users can install directly from Git without a registry listing:
```bash
paseo plugin add git:acme/paseo-review
paseo plugin add git:acme/monorepo:plugins/review
```
Use `--ref` to select a branch, tag or commit for the initial installation. Direct installation
also supports private repositories and other Git hosts when the daemon has access; see
[plugin sources](/docs/plugins/reference#plugin-sources). Registry submission accepts public
GitHub sources and public npm packages.
## Plugin registry
Browse published plugins at [paseo.sh/plugins](https://paseo.sh/plugins).
Users install the reviewed artifact with:
Open the [submission form](https://github.com/getpaseo/plugins/issues/new?template=submit-plugin.yml).
Use the form so the issue receives the submission label that starts intake.
1. Use your plugin's name as the title.
2. In **Source**, enter the public npm package name or page, or the GitHub repository/folder URL.
Include the version or Git reference if you want a specific release reviewed. npm defaults to
`latest`. Registry IDs and local directories are not submission sources.
3. Select the categories that fit. Include any interface-image URLs in the issue description.
The bot opens a review PR. The reviewer inspects the artifact and dependencies without running
plugin code, completes the listing and records the exact approved version or commit. Publication
requires the [review policy](https://github.com/getpaseo/plugins/blob/main/REVIEW.md), including
locked installation inputs and appropriate data access, even when automated validation passes.
If a change is requested, reply on the review PR with the corrected version/revision or requested
image URL. The reviewer updates the pin and listing. Intake service errors retry automatically;
missing images or an overview do not prevent opening the review PR.
After approval and publication, users install your listing with:
```bash
paseo plugin add owner/slug
```
Publish your artifact through npm or Git, then follow the
[registry submission guide](https://github.com/getpaseo/plugins) to submit it for review.
Registry installations and updates use the approved revision and plugin path.
Direct Git installs use explicit `git:owner/repository` shorthand or a full Git URL.
npm releases receive automatic update PRs. Submit Git updates manually with the desired revision.
Existing registry installations use approved pins; direct npm/Git installs follow their own update
rules in the [source reference](/docs/plugins/reference#plugin-sources).
## Publish on npm
## Plugins with a build step
The scaffold prepares the package files and development dependencies. You choose the package name
and release version.
Paseo compiles TypeScript, so an ordinary plugin needs no separate publication build.
Keep generated modules in their runtime directory and host-provided modules external.
### 1. Set your package name and version
Paseo suppresses npm lifecycle scripts during package acquisition. Commands explicitly declared in
manifest `build` still run, including scripts they invoke. Explain the purpose of those commands
and keep their inputs locked and inspectable. Remove Git-only dependency-install commands from
npm manifests when npm already installs the production dependencies.
From the plugin directory, set your package details and allow publication. Replace `@acme` with your npm scope:
Later setup that installs another dependency tree needs its own complete lock, even if your plugin
has a development lockfile. For npm setup, ship the runtime manifest and lock together and use
`npm ci`. For Python setup, ship a requirements file containing exact versions and SHA-256 hashes
for all transitive packages, then install it with:
```bash
npm pkg set name=@acme/paseo-review version=1.0.0
npm pkg delete private
python -m pip install --require-hashes -r requirements-documents.txt
```
### 2. Check and publish
This command rejects unpinned or unhashed dependencies. Runtime installation also needs the
[confirmation and disclosure](#your-listing-page) described above.
```bash
npm run typecheck
npm pack --dry-run
npm publish --access public
```
Check the pack output includes any assets you added to the project.
### 3. Test the published plugin
On a daemon host with npm available:
```bash
paseo plugin install npm:@acme/paseo-review@1.0.0
```
Users can also paste `npm:@acme/paseo-review` into **Settings → Plugins → Plugin source**.
:::example[Package configuration]
The scaffold includes this `files` list in `package.json`:
```json
{
"files": [
"paseo-plugin.json",
"OVERVIEW.md",
"index.client.ts",
"index.client.tsx",
"index.server.ts",
"index.server.tsx",
"client/",
"server/",
"shared/"
]
}
```
- Add any assets stored outside these directories to `files`.
- Keep the scaffold's SDK and host libraries in `devDependencies`.
- Add other runtime libraries with `npm install <package>`. Paseo installs their dependencies too.
- The npm package name identifies the source. The manifest's `id` identifies the installed plugin.
See the [project reference](/docs/plugins/reference#project-files) for entry points and runtime boundaries.
:::
### Plugins with a build step
Paseo compiles TypeScript. An ordinary plugin needs no separate build before publication.
If your plugin generates files, include the generated output in the package.
**Installation scripts do not run automatically.** If a dependency needs host-specific setup,
declare a [preparation command](/docs/plugins/reference#cli-reference).
:::example[Generated files and dependencies]
- Generate code and assets before running `npm publish`.
- Keep generated JavaScript in its runtime directory and import it from the TypeScript entry.
- Include generated assets in `files`.
- Keep host-provided modules external when producing your own bundle.
- Remove Git-only dependency-install commands from the published manifest; npm installation already
installs production dependencies.
Paseo skips npm lifecycle scripts during installation, including dependency scripts. For example,
a native dependency that needs rebuilding requires an explicit preparation command.
:::
## Private npm packages
:::example[Publish a private package with GitHub Packages]
@@ -151,104 +281,3 @@ Paseo uses the host's npm registry settings and credentials for installation and
In the app, enter only the source identifier.
:::
## Icons and screenshots
Declare your display name, icon, screenshots, and demo videos in `paseo-plugin.json`:
```json
{
"id": "review-tools",
"name": "Review tools",
"description": "Reviews changes before merge",
"icon": "assets/icon.png",
"media": ["assets/screenshot.png", "https://example.com/review-demo.mp4"],
"requirements": { "paseo": ">=0.11.0" }
}
```
All three fields are optional. `name` gives the registry and website a display name without
changing the installation ID. When omitted, the registry falls back to a humanized ID.
Registry and website display requires the registry builder to read these fields from the pinned
manifest. That update is a separate follow-up; until it lands, these fields are exposed only
through the daemon's installed-plugin list.
`icon` must point to a PNG inside the plugin package. `media` accepts paths to images and videos
inside the package or HTTPS URLs, in display order. Paths are relative to the manifest; use
forward slashes and keep them inside the package. See the [manifest reference](/docs/plugins/reference#project-files)
for validation rules.
Commit local assets alongside the manifest at the pinned revision. For npm, add their directory
(for example, `assets/`) to `package.json`'s `files` list and verify it with `npm pack --dry-run`.
The scaffold documents these fields in its manifest's `$comment`; add your display name and
assets before publishing.
Manifests using these fields fail to install on daemons before 0.11.0. Set
`requirements.paseo` to `>=0.11.0` or a narrower supported range.
## Your listing page
Write `OVERVIEW.md` beside `paseo-plugin.json` for the plugin page inside Paseo.
It helps someone decide whether to install your plugin; the install command is already at
the top of that page. A README assumes a GitHub audience and carries installation
instructions, technical details, and badges. Long, AI-generated READMEs make people read
past that material to understand what a plugin does.
`OVERVIEW.md` is required to list your plugin in the registry. Commit it beside
`paseo-plugin.json` in the source repository at the pinned commit. The registry resolves it
relative to the manifest, under `pluginPath` for monorepos. Include it in the published npm
package too; the scaffold's `files` list includes it. Replace the scaffold's guidance comment
with useful facts before publishing.
The repository overview takes precedence over a registry import stopgap. Online validation
fails when the pinned commit has no `OVERVIEW.md`, except for unchanged imported records
that already carry `plugins/<owner>/<slug>.md` in the registry repository. Every version bump
requires a repository overview and removes the stopgap in the same PR. A bump without the
repository overview fails validation. README files do not supply the overview.
Author overviews and registry stopgaps follow the same content contract, in this order.
Choose headings only when they help; length follows complexity. A theme needs one paragraph.
1. Explain what the plugin is and does in plain terms first.
2. Explain how it works only when that is not obvious.
3. Explain setup when needed: settings, accounts, tokens, providers, external tools, or other
plugins. Include applicable daemon version and operating system requirements. Setup
guidance is allowed; installation instructions are not.
4. Explain capabilities and settings worth understanding, what each option does, what the
plugin reads or sends and where, permissions, and known limits.
Use sentence case and plain factual language, with no em dashes. Omit installation commands,
badges, changelog, contributing or license sections, marketing, and unsupported claims.
Avoid implementation filler such as empty cleanup functions, catalogs of theme-token fields,
or lists of absent features. Keep only what helps someone choose the plugin.
If your plugin is an unchanged imported record, you can propose an author-written overview
to replace the registry stopgap. Do not add import credit to your own `OVERVIEW.md`.
## Share through GitHub or Git
Push the plugin project to a repository. Users can install it with:
```bash
paseo plugin add git:acme/paseo-review
```
For another Git host:
```bash
paseo plugin install git:https://git.example.com/acme/paseo-review.git
```
If your plugin has runtime npm dependencies, commit `package-lock.json` and add a preparation
command to `paseo-plugin.json`:
```json
{
"build": [["npm", "ci", "--omit=dev"]]
}
```
- `npm ci` installs the versions in the committed lockfile.
- `--omit=dev` excludes development tools.
- npm must be available on the daemon host.
Plugins that only use Paseo's host libraries need no preparation command.
+7 -4
View File
@@ -63,7 +63,9 @@ The required root manifest is `paseo-plugin.json`:
| `build` | No | Preparation commands, described in the CLI reference. |
Paths are relative to `paseo-plugin.json`, use forward slashes, and cannot contain `..`
segments. See [icons and screenshots](/docs/plugins/publishing#icons-and-screenshots) for an example.
segments. Registry listings for visual plugins require an interface image even though `media` is
optional in the runtime manifest. See [icons and screenshots](/docs/plugins/publishing#icons-and-screenshots)
for accepted formats and listing requirements.
Paseo validates the references without opening local assets or fetching URLs.
Unknown top-level fields are ignored. Known fields still validate, and unknown keys inside
@@ -2137,7 +2139,7 @@ export default function contribute(server: PluginServerContext) {
Inputs and outputs are validated on both sides. RPC names start with a lowercase letter and contain lowercase letters, numbers, dots, hyphens, or underscores. `useRpc()` returns a typed async function. Use TanStack Query for request state, caching, and mutations.
Backend handlers receive the same `PaseoApi` as `{ paseo }`. Their connection belongs to the subprocess and closes when the plugin stops. It does not subscribe to timelines or catalog events until plugin code subscribes. Follow the [SDK event contract](../../sdk/events.md) for cleanup and timeline replacements. Backend code can use Node APIs and dependencies installed in the plugin directory.
Backend handlers receive the same `PaseoApi` as `{ paseo }`. Their connection belongs to the subprocess and closes when the plugin stops. It does not subscribe to timelines or catalog events until plugin code subscribes. Follow the [SDK event contract](/docs/sdk/events) for cleanup and timeline replacements. Backend code can use Node APIs and dependencies installed in the plugin directory.
## Debug backend output
@@ -2351,8 +2353,9 @@ keeps the complete dependency tree and `package-lock.json` when activating it. T
package and lockfile provide its current version and artifact integrity. A version, tag, or range
chooses content for this installation only.
For package contents, dependencies, preparation, and private registries, see
[Publish a plugin](/docs/plugins/publishing).
The installed lockfile records what this installation resolved. Authors submitting npm plugins
with runtime dependencies must also ship the [publication lock](/docs/plugins/publishing#2-lock-installed-dependencies).
For package contents, preparation and submission, see [Publish a plugin](/docs/plugins/publishing).
A failed download, dependency installation, manifest check, preparation command, compilation, or
activation discards the candidate. Other installed plugins keep running. Removing an npm plugin
+16
View File
@@ -85,6 +85,7 @@ Pick any of these from the in-app provider catalog. Each entry is a one-click in
- [goose](https://block.github.io/goose/), Block's local open-source AI agent.
- [Grok](https://docs.x.ai/build/overview), xAI's Grok Build agentic coding CLI.
- [Hermes Agent](https://hermes-agent.nousresearch.com/docs/user-guide/features/acp), Nous Research's self-improving agent.
- [Hoplite](#hoplite), cloud coding agent through its local ACP bridge.
- [Junie](https://junie.jetbrains.com/docs/junie-cli-acp.html), JetBrains' coding agent.
- [Kilo Code](https://kilo.ai/docs/code-with-ai/platforms/cli), open-source coding agent.
- [Kimi Code CLI](https://github.com/MoonshotAI/kimi-code), Moonshot AI's coding assistant.
@@ -100,3 +101,18 @@ Pick any of these from the in-app provider catalog. Each entry is a one-click in
- [VT Code](https://github.com/vinhnx/VTCode/blob/main/docs/guides/zed-acp.md), open-source multi-provider coding agent.
The in-app catalog is the canonical, version-pinned source. Anything not listed here can still be added manually, see [Custom providers](/docs/custom-providers).
### Hoplite
Install the [Hoplite CLI](https://hoplite.sh/docs/cli) on your daemon host and run
`hoplite login`. In **Settings → Hosts → your host → Providers**, find **Hoplite**
in the catalog and choose **Add**. Paseo launches `hoplite acp` through the generic ACP adapter.
Hoplite runs the agent in a cloud workspace. Open a repository linked to a Hoplite project,
or set `agents.providers.hoplite.env.HOPLITE_PROJECT_ID` to use one project everywhere.
Without a linked repository or pinned project, discovery reports `No Hoplite project`.
Your local files and Paseo's loopback MCP tools are not available in that cloud workspace.
See [Hoplite's ACP guide](https://hoplite.sh/docs/cli/acp) for authentication and project setup.
Use a [command override](/docs/custom-providers) if `hoplite` is outside your daemon's PATH;
keep `acp` in the arguments.