mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-11 19:05:16 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6ef575dac4 | ||
|
|
5c2a1552df | ||
|
|
e0de0fdf6f | ||
|
|
8d424e039e | ||
|
|
d9b874f9d0 | ||
|
|
f56c013928 | ||
|
|
208e323035 | ||
|
|
ec7446add4 | ||
|
|
b30302b630 | ||
|
|
7aa3fac069 | ||
|
|
fd1e7a34ce | ||
|
|
ce0f21e2ff | ||
|
|
d172d060a5 | ||
|
|
2d86b94b2f | ||
|
|
d6d4084a06 | ||
|
|
16bb179e67 | ||
|
|
e08389065c | ||
|
|
80badb3b8f |
@@ -1,5 +1,28 @@
|
||||
# Changelog
|
||||
|
||||
## 0.11.4 - 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.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed Hoplite showing an error in Settings → Providers instead of discovering models in workspaces linked to a Hoplite project
|
||||
|
||||
## 0.11.3 - 2026-10-15
|
||||
|
||||
### 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
|
||||
|
||||
@@ -57,7 +57,7 @@ Paseo is an open source agentic development environment for desktop, mobile, web
|
||||
<!-- Sponsors: one cell per sponsor in the order of packages/website/src/data/sponsors.ts, then "become a sponsor" cells up to three. -->
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center" width="33%"><a href="https://hoplite.sh/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/hoplite-on-dark.svg"><img src="packages/website/public/sponsors/hoplite-on-light.svg" alt="Hoplite" height="40"></picture></a><br><sub>Cloud coding agents</sub></td>
|
||||
<td align="center" width="33%"><a href="https://hoplite.sh/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/hoplite-on-dark.svg"><img src="packages/website/public/sponsors/hoplite-on-light.svg" alt="Hoplite" height="56"></picture></a><br><sub>Cloud coding agents</sub></td>
|
||||
<td align="center" width="33%"><a href="https://paseo.sh/sponsor">Become a sponsor</a></td>
|
||||
<td align="center" width="33%"><a href="https://paseo.sh/sponsor">Become a sponsor</a></td>
|
||||
</tr>
|
||||
|
||||
@@ -58,12 +58,17 @@ So arrival sets a _target_ and the reveal rate is derived from the backlog inste
|
||||
through that hook; the web viewport once skipped it and history hosts of a live tool group went
|
||||
stale. A new field on `StreamLayoutItem` must be added to `areLayoutItemsEquivalent`, or sharing
|
||||
silently stops.
|
||||
- **Streaming cost must not grow with revealed history.** Reading older messages must not
|
||||
make the next reply progressively more expensive to display. Reuse unchanged history work
|
||||
while text arrives, and release obsolete window caches as the reader reveals more history;
|
||||
window caches must stay bounded while their source timeline remains loaded.
|
||||
|
||||
## Measuring
|
||||
|
||||
- **Smoothness (user-perceived):** `packages/app/e2e/browser/agent-stream-smoothness.spec.ts`, gated behind `PASEO_AGENT_STREAM_PERF_E2E=1`. Drives the mock provider's `bursty-stream` model and reports coefficient of variation of characters painted per frame (smoothness) plus p95 gap between visible updates (stalls). Both numbers are needed: a stalled stream is perfectly smooth.
|
||||
- **Reproducing bursty arrival:** the `bursty-stream` model in `mock-load-test-agent.ts` emits uneven runs of tokens separated by idle gaps. Burst sizes come from a seeded generator, so a run repeats exactly.
|
||||
- **Rate policy in isolation:** `computeRevealStep` in `packages/app/src/agent-stream/text-reveal.ts` is pure; `text-reveal.test.ts` covers convergence and burst flattening without a renderer.
|
||||
- **Per-delta cost on a long timeline:** `npx vitest bench --project unit src/agent-stream/stream-tick.bench.ts` from `packages/app` replays 200 deltas over a 2,000-item timeline through the pure model and layout pipeline, with the default mounted window and with history fully revealed. It measures the JS work per delta, not paint.
|
||||
|
||||
Healthy numbers (2026-08, Expo web against a local dev daemon, real Claude Haiku agent, ~8.5s samples during active streaming). Setting `TEXT_REVEAL_HORIZON_MS` to 0 makes the reveal paint on arrival, which is how the baseline column was taken:
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
+4
-1
@@ -589,7 +589,10 @@ host, kinds, and ids. Opening a cached workspace uses exact workspace and projec
|
||||
directory scan. One invalid row is deleted and returned as a miss without affecting other rows.
|
||||
An invalid directory row and its affected checkpoint cursor are repaired in one transaction, so a
|
||||
later launch cannot accept a checkpoint for a partial baseline. Directory changes and their
|
||||
checkpoint are also applied in one transaction.
|
||||
checkpoint are also applied in one transaction. Reads wait for accepted changes to reach storage,
|
||||
then retry only when a requested row changes during the read. Unrelated agent streams do not
|
||||
invalidate the read. Directory baseline replacements and host removal or renaming still invalidate
|
||||
the affected reads.
|
||||
|
||||
The cache is capped at 32 MiB and evicts whole hosts in least-recently-written order. Budget
|
||||
bookkeeping may scan opaque row sizes during a deferred write, never during host registry startup or
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
import { test, expect } from "../support/fixtures";
|
||||
import { awaitAssistantMessage } from "../support/helpers/agent-stream";
|
||||
import { startRunningMockAgent } from "../support/helpers/composer";
|
||||
import { startRunningMockAgent, submitMessage } from "../support/helpers/composer";
|
||||
import {
|
||||
seedLongMockAgentTimeline,
|
||||
openAgentTimeline,
|
||||
scrollTimelineUntilOlderHistoryIsReachable,
|
||||
scrollTimelineToNewestLoadedEdge,
|
||||
expectTimelinePromptVisible,
|
||||
} from "../support/helpers/timeline-pagination";
|
||||
import {
|
||||
sampleStreamFrames,
|
||||
summarizeStreamSmoothness,
|
||||
@@ -102,6 +109,40 @@ agentStreamPerfDescribe("Agent stream smoothness", () => {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps streaming work bounded after revealing older history", async ({ page }, testInfo) => {
|
||||
test.setTimeout(120_000);
|
||||
await page.addInitScript(() => {
|
||||
Reflect.set(globalThis, "__PASEO_RENDER_PROFILE_ENABLED__", true);
|
||||
});
|
||||
const agent = await seedLongMockAgentTimeline({ turns: 80, liveTurns: "thirty-minute-stream" });
|
||||
try {
|
||||
await openAgentTimeline(page, agent);
|
||||
await expect(page.getByRole("textbox", { name: "Message agent..." }).first()).toBeVisible();
|
||||
await scrollTimelineUntilOlderHistoryIsReachable(page, agent.oldestPrompt);
|
||||
await expectTimelinePromptVisible(page, agent.oldestPrompt);
|
||||
await scrollTimelineToNewestLoadedEdge(page);
|
||||
await submitMessage(page, "Stream a long answer after reading older messages.");
|
||||
await awaitAssistantMessage(page);
|
||||
|
||||
for (let sample = 0; sample < 3; sample += 1) {
|
||||
await page.evaluate(() => globalThis.__PASEO_RESET_RENDER_PROFILE__?.());
|
||||
const frames = await sampleStreamFrames(page, { sampleWindowMs: SAMPLE_WINDOW_MS });
|
||||
const smoothness = summarizeStreamSmoothness(frames, SAMPLE_WINDOW_MS);
|
||||
const react = summarizeReactCommits(await readStreamReactCommits(page));
|
||||
await testInfo.attach(`revealed-history-stream-${sample}`, {
|
||||
body: JSON.stringify({ smoothness, react }, null, 2),
|
||||
contentType: "application/json",
|
||||
});
|
||||
console.log(`[perf] Revealed history stream: ${JSON.stringify({ smoothness, react })}`);
|
||||
expect(smoothness.growthFrames).toBeGreaterThan(20);
|
||||
expect(react.count).toBeGreaterThan(20);
|
||||
expect(react.actualDurationP95Ms).toBeLessThan(REACT_COMMIT_P95_BUDGET_MS);
|
||||
}
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
async function readStreamReactCommits(
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { expect, test, type Page } from "../support/fixtures";
|
||||
import {
|
||||
composerLocator,
|
||||
blurComposerInput,
|
||||
composerLocator,
|
||||
enterComposerFullscreen,
|
||||
exitComposerFullscreen,
|
||||
expectComposerDraft,
|
||||
@@ -25,6 +25,100 @@ import {
|
||||
swipeOpenMobileAgentSidebar,
|
||||
swipeOpenMobileExplorer,
|
||||
} from "../support/helpers/sidebar";
|
||||
import { readScrollMetrics } from "../support/helpers/agent-bottom-anchor";
|
||||
import {
|
||||
expectTimelinePromptPositionPreserved,
|
||||
rememberTimelinePromptPosition,
|
||||
seedLongMockAgentTimeline,
|
||||
waitForTimelineGeometryToSettle,
|
||||
} from "../support/helpers/timeline-pagination";
|
||||
|
||||
test("clicking chat text or background focuses the feed for keyboard paging", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
const agent = await seedLongMockAgentTimeline({ turns: 8 });
|
||||
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
const composer = composerLocator(page);
|
||||
const feed = page.getByTestId("agent-chat-scroll").filter({ visible: true });
|
||||
await composer.fill("Keep this draft");
|
||||
await feed.getByText(agent.newestPrompt, { exact: true }).click();
|
||||
await expect(feed).toBeFocused();
|
||||
|
||||
const beforePaging = await readScrollMetrics(page);
|
||||
expect(beforePaging.offsetY).toBeGreaterThan(beforePaging.viewportHeight);
|
||||
await page.keyboard.press("PageUp");
|
||||
await expect
|
||||
.poll(async () => (await readScrollMetrics(page)).offsetY)
|
||||
.toBeLessThan(beforePaging.offsetY - beforePaging.viewportHeight / 2);
|
||||
await page.screenshot({ path: testInfo.outputPath("chat-keyboard-paging.png") });
|
||||
await page.keyboard.press("PageDown");
|
||||
await expect
|
||||
.poll(async () => (await readScrollMetrics(page)).distanceFromBottom)
|
||||
.toBeLessThanOrEqual(2);
|
||||
|
||||
await composer.click();
|
||||
await expectComposerFocused(page);
|
||||
await feed.click({ position: { x: 2, y: 40 } });
|
||||
await expect(feed).toBeFocused();
|
||||
await page.keyboard.press("PageUp");
|
||||
await expect
|
||||
.poll(async () => (await readScrollMetrics(page)).distanceFromBottom)
|
||||
.toBeGreaterThan(beforePaging.viewportHeight / 2);
|
||||
await waitForTimelineGeometryToSettle(page);
|
||||
const readingPrompt = agent.prompts[4];
|
||||
await expect(feed.getByText(readingPrompt, { exact: true })).toBeInViewport();
|
||||
const readingPosition = await rememberTimelinePromptPosition(page, readingPrompt);
|
||||
await agent.client.sendAgentMessage(agent.agentId, "emit 2 coalesced agent stream updates");
|
||||
await agent.client.waitForFinish(agent.agentId, 15_000);
|
||||
// The daemon finishing does not mean its response has reached the browser.
|
||||
await expect(feed.getByText(/stress-update-1/)).toHaveCount(1);
|
||||
await waitForTimelineGeometryToSettle(page);
|
||||
await expectTimelinePromptPositionPreserved(page, readingPosition);
|
||||
await expectComposerDraft(page, "Keep this draft");
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("focusing the feed preserves assistant text selection and code copy controls", async ({
|
||||
page,
|
||||
context,
|
||||
}) => {
|
||||
const sentence = "Select this assistant sentence.";
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "chat-focus-selection-",
|
||||
title: "Chat focus selection",
|
||||
initialPrompt: "Render text and code.",
|
||||
featureValues: {
|
||||
mockAssistantResponse: `${sentence}\n\n\`\`\`bash\necho example\n\`\`\``,
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
|
||||
await agent.client.waitForFinish(agent.agentId, 15_000);
|
||||
await openAgentRoute(page, agent);
|
||||
await composerLocator(page).fill("Keep this draft");
|
||||
|
||||
const feed = page.getByTestId("agent-chat-scroll").filter({ visible: true });
|
||||
await feed.getByText(sentence, { exact: true }).click({ clickCount: 3 });
|
||||
await expect(feed).toBeFocused();
|
||||
expect(await page.evaluate(() => window.getSelection()?.toString().trim())).toBe(sentence);
|
||||
await page.keyboard.press("ControlOrMeta+c");
|
||||
expect((await page.evaluate(() => navigator.clipboard.readText())).trim()).toBe(sentence);
|
||||
|
||||
const code = feed.locator('[data-paseo-markdown-language="bash"]');
|
||||
await code.hover();
|
||||
await code.locator("[data-paseo-markdown-ignore]").click();
|
||||
await expect(feed).not.toBeFocused();
|
||||
expect(await page.evaluate(() => navigator.clipboard.readText())).toBe("echo example");
|
||||
await expectComposerDraft(page, "Keep this draft");
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("submitting a message leaves the composer ready for the next message", async ({ page }) => {
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import path from "node:path";
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import { expect, test, type Page } from "../support/fixtures";
|
||||
import { gotoAppShell, openSettings } from "../support/helpers/app";
|
||||
import {
|
||||
closeModelPicker,
|
||||
drillIntoProvider,
|
||||
openModelPicker,
|
||||
} from "../support/helpers/agent-profiles";
|
||||
import { expectComposerVisible, expectComposerFocused } from "../support/helpers/composer";
|
||||
import { connectDaemonClient } from "../support/helpers/daemon-client-loader";
|
||||
import { clickNewChat, gotoWorkspace } from "../support/helpers/launcher";
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
import { openSettingsHost, openSettingsHostSection } from "../support/helpers/settings";
|
||||
|
||||
// Use an existing repository linked to the signed-in user's Hoplite project.
|
||||
const cwd = process.env.E2E_HOPLITE_CWD ?? path.resolve(__dirname, "../../../..");
|
||||
|
||||
test.use({
|
||||
viewport: { width: 1440, height: 1000 },
|
||||
e2eDaemonConfig: { version: 1, agents: { providers: { hoplite: { enabled: true } } } },
|
||||
});
|
||||
|
||||
async function openHopliteSettings(page: Page): Promise<void> {
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
await openSettingsHost(page, getServerId());
|
||||
await openSettingsHostSection(page, getServerId(), "providers");
|
||||
await page.getByRole("button", { name: "Hoplite provider details", exact: true }).click();
|
||||
}
|
||||
|
||||
async function expectEmptyGlobalCatalog(page: Page, client: DaemonClient): Promise<void> {
|
||||
const models = await client.listProviderModels("hoplite");
|
||||
expect(models.error).toBeNull();
|
||||
expect(models.models).toEqual([]);
|
||||
const snapshot = await client.getProvidersSnapshot();
|
||||
expect(snapshot.entries.find((entry) => entry.provider === "hoplite")).toMatchObject({
|
||||
status: "ready",
|
||||
models: [],
|
||||
});
|
||||
await expect(page.getByText("No models detected", { exact: true })).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: "Retry", exact: true })).toHaveCount(0);
|
||||
}
|
||||
|
||||
async function refreshGlobalCatalog(page: Page): Promise<void> {
|
||||
await page.getByRole("button", { name: "Refresh", exact: true }).click();
|
||||
await expect(page.getByRole("button", { name: "Refresh", exact: true })).toBeEnabled({
|
||||
timeout: 120_000,
|
||||
});
|
||||
}
|
||||
|
||||
async function openWorkspaceModels(page: Page, workspaceId: string): Promise<void> {
|
||||
await gotoWorkspace(page, workspaceId);
|
||||
await clickNewChat(page);
|
||||
await expectComposerVisible(page);
|
||||
await expectComposerFocused(page);
|
||||
await openModelPicker(page);
|
||||
await page.getByTestId("sheet-header-back").click();
|
||||
await drillIntoProvider(page, "hoplite");
|
||||
}
|
||||
|
||||
test("real Hoplite has an empty global catalog and discovers models in its linked workspace", async ({
|
||||
page,
|
||||
e2eWorkerClient,
|
||||
}, testInfo) => {
|
||||
test.setTimeout(180_000);
|
||||
const client = await connectDaemonClient<DaemonClient>({ clientIdPrefix: "hoplite-discovery" });
|
||||
const created = await e2eWorkerClient.createWorkspace({
|
||||
source: { kind: "directory", path: cwd },
|
||||
title: "Hoplite discovery QA",
|
||||
});
|
||||
expect(created.error).toBeNull();
|
||||
const workspace = created.workspace!;
|
||||
try {
|
||||
await test.step("global settings succeed with no models, including refresh", async () => {
|
||||
await openHopliteSettings(page);
|
||||
await expectEmptyGlobalCatalog(page, client);
|
||||
await refreshGlobalCatalog(page);
|
||||
await expectEmptyGlobalCatalog(page, client);
|
||||
await page.screenshot({ path: testInfo.outputPath("hoplite-global-empty.png") });
|
||||
});
|
||||
|
||||
await test.step("the linked workspace discovers real models", async () => {
|
||||
const models = await client.listProviderModels("hoplite", { cwd });
|
||||
expect(models.error).toBeNull();
|
||||
expect(models.models!.length).toBeGreaterThan(0);
|
||||
await testInfo.attach("workspace-models", {
|
||||
body: JSON.stringify(models, null, 2),
|
||||
contentType: "application/json",
|
||||
});
|
||||
await openWorkspaceModels(page, workspace.id);
|
||||
await expect(page.getByText(models.models![0]!.label, { exact: true }).last()).toBeVisible();
|
||||
await page.screenshot({ path: testInfo.outputPath("hoplite-workspace-models.png") });
|
||||
await closeModelPicker(page);
|
||||
});
|
||||
|
||||
await test.step("workspace discovery does not populate the global catalog", async () => {
|
||||
await openHopliteSettings(page);
|
||||
await expectEmptyGlobalCatalog(page, client);
|
||||
await refreshGlobalCatalog(page);
|
||||
await expectEmptyGlobalCatalog(page, client);
|
||||
const models = await client.listProviderModels("hoplite", { cwd });
|
||||
expect(models.error).toBeNull();
|
||||
expect(models.models!.length).toBeGreaterThan(0);
|
||||
});
|
||||
} finally {
|
||||
await client.close();
|
||||
await e2eWorkerClient.removeProject(workspace.projectId);
|
||||
}
|
||||
});
|
||||
@@ -100,6 +100,40 @@ function weeklyReport(sourceId: string, usedPct: number): UsageReportEntry {
|
||||
};
|
||||
}
|
||||
|
||||
function installReversedUsageRefresh(page: Page) {
|
||||
const initial = [weeklyReport("opencode", 31), weeklyReport("openai", 12)];
|
||||
const refreshed = [weeklyReport("openai", 22), weeklyReport("opencode", 41)];
|
||||
return installUsageReportsFixture(page, {
|
||||
lists: [(request) => (request.forceRefresh ? refreshed : initial)],
|
||||
});
|
||||
}
|
||||
|
||||
async function openUsageSummaryAtWidth(page: Page, width: number) {
|
||||
await page.setViewportSize({ width, height: 900 });
|
||||
await gotoAppShell(page);
|
||||
if (width === 390) await openCompactSidebar(page);
|
||||
await expectPinnedUsage(page, ["31% Weekly", "12% Weekly"]);
|
||||
await openUsageFromItem(page);
|
||||
}
|
||||
|
||||
async function expectUsageProviderOrder(page: Page, summary: string[]) {
|
||||
const group = page.getByTestId(`usage-host-${getServerId()}`);
|
||||
await expect(group.getByText(/^(opencode|openai) plan$/)).toHaveText([
|
||||
"opencode plan",
|
||||
"openai plan",
|
||||
]);
|
||||
await expectPinnedUsage(page, summary);
|
||||
}
|
||||
|
||||
async function refreshUsageAndWaitForReports(page: Page, usage: UsageReportsFixture) {
|
||||
const requestCount = usage.listRequests().length;
|
||||
await refreshAllUsage(page);
|
||||
await usage.waitForListRequests(requestCount + 1);
|
||||
const group = page.getByTestId(`usage-host-${getServerId()}`);
|
||||
await expect(group.getByText("41%", { exact: true })).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: "Refresh all", exact: true })).toBeEnabled();
|
||||
}
|
||||
|
||||
test.describe("usage modal", () => {
|
||||
test("opens from the sidebar on the host's reports, with no host filter for one host", async ({
|
||||
page,
|
||||
@@ -152,6 +186,21 @@ test.describe("usage modal", () => {
|
||||
await expect(group.getByTestId("usage-freshness")).toHaveCount(0);
|
||||
});
|
||||
|
||||
for (const width of [1440, 390]) {
|
||||
test(`keeps sidebar and modal provider order across a reversed refresh at width ${width}`, async ({
|
||||
page,
|
||||
}) => {
|
||||
const usage = await installReversedUsageRefresh(page);
|
||||
await openUsageSummaryAtWidth(page, width);
|
||||
await expectUsageProviderOrder(page, ["31% Weekly", "12% Weekly"]);
|
||||
await qaScreenshot(page, `usage-order-${width}-before-refresh`);
|
||||
|
||||
await refreshUsageAndWaitForReports(page, usage);
|
||||
await expectUsageProviderOrder(page, ["41% Weekly", "22% Weekly"]);
|
||||
await qaScreenshot(page, `usage-order-${width}-after-refresh`);
|
||||
});
|
||||
}
|
||||
|
||||
test("refreshes one report from its card", async ({ page }) => {
|
||||
test.setTimeout(120_000);
|
||||
const serverId = getServerId();
|
||||
|
||||
@@ -30,7 +30,7 @@ import {
|
||||
openUsageFromIcon,
|
||||
openUsageFromItem,
|
||||
pinRow,
|
||||
scrollUsage,
|
||||
scrollUsageToWindow,
|
||||
setSummaryInSidebar,
|
||||
openUsageOptions,
|
||||
showUsageAs,
|
||||
@@ -146,7 +146,9 @@ test.describe("Usage item", () => {
|
||||
compact: { viewport: COMPACT, showSidebar: openCompactSidebar },
|
||||
};
|
||||
for (const [size, { viewport, showSidebar }] of Object.entries(layouts)) {
|
||||
test(`long usage reports scroll to the final window on ${size}`, async ({ page }) => {
|
||||
test(`long usage reports scroll between their first and last windows on ${size}`, async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(120_000);
|
||||
const source = await installTallUsageSource();
|
||||
try {
|
||||
@@ -161,10 +163,10 @@ test.describe("Usage item", () => {
|
||||
await waitForSettledPosition(content);
|
||||
await expect(content.getByText("Window 20", { exact: true })).not.toBeInViewport();
|
||||
await qaScreenshot(page, `${size}-usage-scroll-top`);
|
||||
await scrollUsage(page, 5_000);
|
||||
await scrollUsageToWindow(page, "Window 20");
|
||||
await expect(content.getByText("Window 20", { exact: true })).toBeInViewport();
|
||||
await qaScreenshot(page, `${size}-usage-scroll-bottom`);
|
||||
await scrollUsage(page, -5_000);
|
||||
await scrollUsageToWindow(page, "Window 1");
|
||||
await expect(content.getByText("Window 20", { exact: true })).not.toBeInViewport();
|
||||
} finally {
|
||||
await source.cleanup();
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -544,7 +544,7 @@ async function readTimelineViewport(page: Page): Promise<TimelineViewportSnapsho
|
||||
});
|
||||
}
|
||||
|
||||
async function waitForTimelineGeometryToSettle(page: Page): Promise<void> {
|
||||
export async function waitForTimelineGeometryToSettle(page: Page): Promise<void> {
|
||||
const scroll = page.locator('[data-testid="agent-chat-scroll"]:visible').first();
|
||||
await scroll.evaluate(
|
||||
(element) =>
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -212,6 +212,14 @@ export async function scrollUsage(page: Page, deltaY: number): Promise<void> {
|
||||
await page.mouse.wheel(0, deltaY);
|
||||
}
|
||||
|
||||
/** Reach a window with the wheel even when other reports follow its card. */
|
||||
export async function scrollUsageToWindow(page: Page, label: string): Promise<void> {
|
||||
const target = await usageModal(page).getByText(label, { exact: true }).boundingBox();
|
||||
const viewport = page.viewportSize();
|
||||
if (!target || !viewport) throw new Error("Usage window must exist before scrolling to it.");
|
||||
await scrollUsage(page, target.y + target.height / 2 - viewport.height / 2);
|
||||
}
|
||||
|
||||
/** The modal's own Close button. */
|
||||
export async function closeUsage(page: Page): Promise<void> {
|
||||
await visible(page, "usage-modal").getByRole("button", { name: "Close", exact: true }).click();
|
||||
|
||||
@@ -2,6 +2,9 @@ import type { ReactNode, RefObject } from "react";
|
||||
import type { StreamItem } from "@/types/stream";
|
||||
import type { StreamViewportHandle } from "../strategy";
|
||||
|
||||
export interface MountedMessageIds {
|
||||
has(messageId: string): boolean;
|
||||
}
|
||||
export interface ChatFindProps {
|
||||
agentId: string;
|
||||
serverId: string;
|
||||
@@ -9,7 +12,7 @@ export interface ChatFindProps {
|
||||
items: StreamItem[];
|
||||
viewportRef: RefObject<StreamViewportHandle | null>;
|
||||
revealLoadedMessage(messageId: string): boolean;
|
||||
visibleMessageIds: ReadonlySet<string>;
|
||||
visibleMessageIds: MountedMessageIds;
|
||||
children: ReactNode;
|
||||
}
|
||||
export interface ChatFindExpansionProps {
|
||||
|
||||
@@ -178,7 +178,7 @@ describe("useChatOutline", () => {
|
||||
timelineEpoch,
|
||||
enabled,
|
||||
viewportRef,
|
||||
visibleMessageIds: new Set(),
|
||||
mountedHistoryMessageIds: new Set(),
|
||||
onJumpError: vi.fn(),
|
||||
}),
|
||||
{
|
||||
@@ -278,7 +278,7 @@ describe("useChatOutline", () => {
|
||||
},
|
||||
];
|
||||
const { result, rerender } = renderHook(
|
||||
({ visibleMessageIds }) =>
|
||||
({ mountedHistoryMessageIds }) =>
|
||||
useChatOutline({
|
||||
agentId: "agent-1",
|
||||
serverId: "server-1",
|
||||
@@ -288,10 +288,10 @@ describe("useChatOutline", () => {
|
||||
enabled: true,
|
||||
viewportRef,
|
||||
onJumpError: vi.fn(),
|
||||
visibleMessageIds,
|
||||
mountedHistoryMessageIds,
|
||||
revealLoadedMessage,
|
||||
}),
|
||||
{ initialProps: { visibleMessageIds: new Set<string>() } },
|
||||
{ initialProps: { mountedHistoryMessageIds: new Set<string>() } },
|
||||
);
|
||||
|
||||
await waitFor(() => expect(result.current.prompts).toHaveLength(1));
|
||||
@@ -299,7 +299,7 @@ describe("useChatOutline", () => {
|
||||
expect(revealLoadedMessage).toHaveBeenCalledWith("older-prompt");
|
||||
expect(scrollToMessage).not.toHaveBeenCalled();
|
||||
|
||||
rerender({ visibleMessageIds: new Set(["older-prompt"]) });
|
||||
rerender({ mountedHistoryMessageIds: new Set(["older-prompt"]) });
|
||||
await waitFor(() => expect(scrollToMessage).toHaveBeenCalledWith("older-prompt"));
|
||||
});
|
||||
|
||||
@@ -327,7 +327,7 @@ describe("useChatOutline", () => {
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1 },
|
||||
};
|
||||
const { result, rerender } = renderHook(
|
||||
({ tail, visibleMessageIds }) =>
|
||||
({ tail, mountedHistoryMessageIds }) =>
|
||||
useChatOutline({
|
||||
agentId: "agent-1",
|
||||
serverId: "server-1",
|
||||
@@ -337,13 +337,13 @@ describe("useChatOutline", () => {
|
||||
enabled: true,
|
||||
viewportRef,
|
||||
onJumpError: vi.fn(),
|
||||
visibleMessageIds,
|
||||
mountedHistoryMessageIds,
|
||||
revealLoadedMessage,
|
||||
}),
|
||||
{
|
||||
initialProps: {
|
||||
tail: [] as (typeof fetchedPrompt)[],
|
||||
visibleMessageIds: new Set<string>(),
|
||||
mountedHistoryMessageIds: new Set<string>(),
|
||||
},
|
||||
},
|
||||
);
|
||||
@@ -352,11 +352,11 @@ describe("useChatOutline", () => {
|
||||
act(() => result.current.jumpToPrompt(1));
|
||||
await waitFor(() => expect(runtime.fetchAgentTimeline).toHaveBeenCalledOnce());
|
||||
|
||||
rerender({ tail: [fetchedPrompt], visibleMessageIds: new Set<string>() });
|
||||
rerender({ tail: [fetchedPrompt], mountedHistoryMessageIds: new Set<string>() });
|
||||
await waitFor(() => expect(revealLoadedMessage).toHaveBeenCalledWith(fetchedPrompt.id));
|
||||
expect(scrollToMessage).not.toHaveBeenCalled();
|
||||
|
||||
rerender({ tail: [fetchedPrompt], visibleMessageIds: new Set([fetchedPrompt.id]) });
|
||||
rerender({ tail: [fetchedPrompt], mountedHistoryMessageIds: new Set([fetchedPrompt.id]) });
|
||||
await waitFor(() => expect(scrollToMessage).toHaveBeenCalledOnce());
|
||||
expect(scrollToMessage).toHaveBeenCalledWith(fetchedPrompt.id);
|
||||
await act(async () => fetch.resolve());
|
||||
@@ -392,7 +392,7 @@ describe("useChatOutline", () => {
|
||||
enabled: true,
|
||||
viewportRef: { current: viewport },
|
||||
onJumpError: vi.fn(),
|
||||
visibleMessageIds: new Set([livePrompt.id]),
|
||||
mountedHistoryMessageIds: new Set<string>(),
|
||||
revealLoadedMessage,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";
|
||||
import { useEffect, useMemo, useRef, useState, type RefObject } from "react";
|
||||
import type { AgentTimelinePromptIndexPayload } from "@getpaseo/client/internal/daemon-client";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { useStableEvent } from "@/hooks/use-stable-event";
|
||||
@@ -33,7 +33,8 @@ export interface UseChatOutlineInput {
|
||||
enabled: boolean;
|
||||
viewportRef: RefObject<StreamViewportHandle | null>;
|
||||
onJumpError: () => void;
|
||||
visibleMessageIds?: ReadonlySet<string>;
|
||||
// Message ids of the history the viewport has mounted. Live head messages are always mounted.
|
||||
mountedHistoryMessageIds?: ReadonlySet<string>;
|
||||
revealLoadedMessage?: (messageId: string) => boolean;
|
||||
}
|
||||
|
||||
@@ -44,6 +45,24 @@ export interface ChatOutline {
|
||||
reportReadingPosition: (seq: number | null) => void;
|
||||
}
|
||||
|
||||
function latestPromptSeqIn(items: StreamItem[], timelineEpoch: string | null): number {
|
||||
let latest = -1;
|
||||
for (const item of items) {
|
||||
if (item.kind === "user_message" && item.timelineCursor?.epoch === timelineEpoch) {
|
||||
latest = Math.max(latest, item.timelineCursor.seq);
|
||||
}
|
||||
}
|
||||
return latest;
|
||||
}
|
||||
|
||||
function findLoadedItem(
|
||||
tail: StreamItem[],
|
||||
head: StreamItem[],
|
||||
predicate: (item: StreamItem) => boolean,
|
||||
): StreamItem | undefined {
|
||||
return tail.find(predicate) ?? head.find(predicate);
|
||||
}
|
||||
|
||||
export function useChatOutline({
|
||||
agentId,
|
||||
serverId,
|
||||
@@ -53,7 +72,7 @@ export function useChatOutline({
|
||||
enabled,
|
||||
viewportRef,
|
||||
onJumpError,
|
||||
visibleMessageIds,
|
||||
mountedHistoryMessageIds,
|
||||
revealLoadedMessage,
|
||||
}: UseChatOutlineInput): ChatOutline {
|
||||
const [index, setIndex] = useState<AgentTimelinePromptIndexPayload | null>(null);
|
||||
@@ -62,18 +81,19 @@ export function useChatOutline({
|
||||
const readingSeqRef = useRef<number | null>(null);
|
||||
const nextJumpRequestIdRef = useRef(0);
|
||||
const nextIndexRequestIdRef = useRef(0);
|
||||
const loadedItems = useMemo(() => [...tail, ...(head ?? NO_STREAM_ITEMS)], [head, tail]);
|
||||
// A disabled outline (every native viewport) must not pay for the timeline per delta.
|
||||
const loadedTail = enabled ? tail : NO_STREAM_ITEMS;
|
||||
const loadedHead = enabled ? (head ?? NO_STREAM_ITEMS) : NO_STREAM_ITEMS;
|
||||
const prompts = enabled ? (index?.prompts ?? NO_PROMPTS) : NO_PROMPTS;
|
||||
|
||||
// The viewed timeline already owns live delivery and reconnect catch-up. Its complete
|
||||
// loaded items (including rows outside the mounted window) invalidate the prompt index.
|
||||
const latestPromptSeq = loadedItems.reduce(
|
||||
(latest, item) =>
|
||||
item.kind === "user_message" && item.timelineCursor?.epoch === timelineEpoch
|
||||
? Math.max(latest, item.timelineCursor.seq)
|
||||
: latest,
|
||||
-1,
|
||||
// Only the head changes per streamed delta, so the tail's contribution is memoized.
|
||||
const tailPromptSeq = useMemo(
|
||||
() => latestPromptSeqIn(loadedTail, timelineEpoch),
|
||||
[loadedTail, timelineEpoch],
|
||||
);
|
||||
const latestPromptSeq = Math.max(tailPromptSeq, latestPromptSeqIn(loadedHead, timelineEpoch));
|
||||
|
||||
useEffect(() => setIndex(null), [agentId, enabled, serverId, timelineEpoch]);
|
||||
|
||||
@@ -135,10 +155,18 @@ export function useChatOutline({
|
||||
|
||||
useEffect(() => {
|
||||
if (pendingJump === null) return;
|
||||
const target = loadedItems.find((item) => item.timelineCursor?.seq === pendingJump.seq);
|
||||
const target = findLoadedItem(
|
||||
loadedTail,
|
||||
loadedHead,
|
||||
(item) => item.timelineCursor?.seq === pendingJump.seq,
|
||||
);
|
||||
if (target) {
|
||||
if (pendingJump.hasScrolled) return;
|
||||
if (visibleMessageIds?.has(target.id) === false) {
|
||||
const isMounted =
|
||||
mountedHistoryMessageIds === undefined ||
|
||||
mountedHistoryMessageIds.has(target.id) ||
|
||||
loadedHead.includes(target);
|
||||
if (!isMounted) {
|
||||
revealLoadedMessage?.(target.id);
|
||||
return;
|
||||
}
|
||||
@@ -150,40 +178,48 @@ export function useChatOutline({
|
||||
return;
|
||||
}
|
||||
if (pendingJump.fetchSettled) setPendingJump(null);
|
||||
}, [loadedItems, pendingJump, revealLoadedMessage, viewportRef, visibleMessageIds]);
|
||||
}, [
|
||||
loadedHead,
|
||||
loadedTail,
|
||||
mountedHistoryMessageIds,
|
||||
pendingJump,
|
||||
revealLoadedMessage,
|
||||
viewportRef,
|
||||
]);
|
||||
|
||||
const jumpToPrompt = useCallback(
|
||||
(seq: number) => {
|
||||
nextJumpRequestIdRef.current += 1;
|
||||
setPendingJump(null);
|
||||
const loaded = loadedItems.find((item) => item.timelineCursor?.seq === seq);
|
||||
if (loaded) {
|
||||
if (revealLoadedMessage?.(loaded.id)) {
|
||||
const requestId = nextJumpRequestIdRef.current;
|
||||
setPendingJump({ requestId, seq, fetchSettled: true, hasScrolled: false });
|
||||
return;
|
||||
}
|
||||
viewportRef.current?.scrollToMessage?.(loaded.id);
|
||||
const jumpToPrompt = useStableEvent((seq: number) => {
|
||||
nextJumpRequestIdRef.current += 1;
|
||||
setPendingJump(null);
|
||||
const loaded = findLoadedItem(
|
||||
loadedTail,
|
||||
loadedHead,
|
||||
(item) => item.timelineCursor?.seq === seq,
|
||||
);
|
||||
if (loaded) {
|
||||
if (revealLoadedMessage?.(loaded.id)) {
|
||||
const requestId = nextJumpRequestIdRef.current;
|
||||
setPendingJump({ requestId, seq, fetchSettled: true, hasScrolled: false });
|
||||
return;
|
||||
}
|
||||
if (!index) return;
|
||||
const requestId = nextJumpRequestIdRef.current;
|
||||
setPendingJump({ requestId, seq, fetchSettled: false, hasScrolled: false });
|
||||
void getHostRuntimeStore()
|
||||
.fetchAgentTimeline(serverId, agentId, planTimelinePromptJump({ epoch: index.epoch, seq }))
|
||||
.catch((error: unknown) => {
|
||||
console.warn("Failed to load a Chat outline window", error);
|
||||
onJumpError();
|
||||
})
|
||||
.finally(() => {
|
||||
setPendingJump((current) => {
|
||||
if (current?.requestId !== requestId) return current;
|
||||
return { ...current, fetchSettled: true };
|
||||
});
|
||||
viewportRef.current?.scrollToMessage?.(loaded.id);
|
||||
return;
|
||||
}
|
||||
if (!index) return;
|
||||
const requestId = nextJumpRequestIdRef.current;
|
||||
setPendingJump({ requestId, seq, fetchSettled: false, hasScrolled: false });
|
||||
void getHostRuntimeStore()
|
||||
.fetchAgentTimeline(serverId, agentId, planTimelinePromptJump({ epoch: index.epoch, seq }))
|
||||
.catch((error: unknown) => {
|
||||
console.warn("Failed to load a Chat outline window", error);
|
||||
onJumpError();
|
||||
})
|
||||
.finally(() => {
|
||||
setPendingJump((current) => {
|
||||
if (current?.requestId !== requestId) return current;
|
||||
return { ...current, fetchSettled: true };
|
||||
});
|
||||
},
|
||||
[agentId, index, loadedItems, onJumpError, revealLoadedMessage, serverId, viewportRef],
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
return { prompts, activePrompt, jumpToPrompt, reportReadingPosition };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { setFlagsFromString } from "node:v8";
|
||||
import { runInNewContext } from "node:vm";
|
||||
import { buildAgentStreamRenderModel } from "./model";
|
||||
import type { StreamItem } from "@/types/stream";
|
||||
|
||||
function revealHistory(tail: StreamItem[]): WeakRef<StreamItem[]>[] {
|
||||
const windows: WeakRef<StreamItem[]>[] = [];
|
||||
for (let start = tail.length - 20; start >= 20; start -= 20) {
|
||||
const model = buildAgentStreamRenderModel({
|
||||
tail,
|
||||
head: [],
|
||||
historyStart: start,
|
||||
platform: "web",
|
||||
isMobileBreakpoint: false,
|
||||
isTurnActive: false,
|
||||
activeTurnStartedAt: null,
|
||||
});
|
||||
windows.push(new WeakRef(model.history));
|
||||
}
|
||||
return windows;
|
||||
}
|
||||
|
||||
it("releases obsolete history windows and their source timeline", async () => {
|
||||
setFlagsFromString("--expose_gc");
|
||||
const gc = runInNewContext("gc") as () => void;
|
||||
setFlagsFromString("--no-expose_gc");
|
||||
async function collect() {
|
||||
for (let i = 0; i < 3; i++) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
gc();
|
||||
}
|
||||
}
|
||||
let tail: StreamItem[] = Array.from({ length: 1000 }, (_, i) => ({
|
||||
kind: i % 2 ? "assistant_message" : "user_message",
|
||||
id: `row-${i}`,
|
||||
text: "text",
|
||||
timestamp: new Date(1700000000000 + i * 1000),
|
||||
}));
|
||||
const windows = revealHistory(tail);
|
||||
await collect();
|
||||
expect(windows.filter((ref) => ref.deref() !== undefined)).toHaveLength(1);
|
||||
|
||||
windows.push(...revealHistory(tail));
|
||||
await collect();
|
||||
expect(windows.filter((ref) => ref.deref() !== undefined)).toHaveLength(1);
|
||||
|
||||
tail = [];
|
||||
await collect();
|
||||
expect(windows.every((ref) => ref.deref() === undefined)).toBe(true);
|
||||
});
|
||||
@@ -240,4 +240,47 @@ describe("buildAgentStreamRenderModel", () => {
|
||||
|
||||
expect(model.turnTiming.byAssistantId.size).toBe(0);
|
||||
});
|
||||
|
||||
it.each(["web", "native"] as const)(
|
||||
"reuses rendered history and timing across live-head updates inside a history window on %s",
|
||||
(platform) => {
|
||||
const at = (seed: number) => new Date(Date.UTC(2026, 0, 1, 0, 0, seed));
|
||||
const tail: StreamItem[] = [];
|
||||
for (let index = 0; index < 40; index += 1) {
|
||||
tail.push(
|
||||
{ ...userMessage(`u${index}`, 0), timestamp: at(index * 2) },
|
||||
{ ...assistantMessage(`a${index}`, 0), timestamp: at(index * 2 + 1) },
|
||||
);
|
||||
}
|
||||
const live = (text: string): StreamItem => ({
|
||||
kind: "assistant_message",
|
||||
id: "live",
|
||||
text,
|
||||
timestamp: at(81),
|
||||
});
|
||||
const build = (head: StreamItem[]) =>
|
||||
buildAgentStreamRenderModel({
|
||||
isTurnActive: true,
|
||||
activeTurnStartedAt: tail.at(-2)?.timestamp ?? null,
|
||||
tail,
|
||||
head,
|
||||
platform,
|
||||
isMobileBreakpoint: false,
|
||||
historyStart: 60,
|
||||
});
|
||||
|
||||
const first = build([live("live")]);
|
||||
const second = build([live("live grows")]);
|
||||
|
||||
expect(second.history).toBe(first.history);
|
||||
expect(second.segments.historyMounted).toBe(first.segments.historyMounted);
|
||||
expect(second.turnTiming.byAssistantId).toBe(first.turnTiming.byAssistantId);
|
||||
expect(first.history).toHaveLength(20);
|
||||
expect(first.turnTiming.byAssistantId.has("a29")).toBe(false);
|
||||
expect(first.turnTiming.byAssistantId.get("a38")).toEqual({
|
||||
completedAt: tail[77]?.timestamp,
|
||||
durationMs: 1000,
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -53,11 +53,29 @@ const splitHistoryCache = new WeakMap<
|
||||
StreamItem[],
|
||||
Map<string, Pick<AgentStreamRenderModel, "history" | "segments">>
|
||||
>();
|
||||
const turnTimingCache = new WeakMap<
|
||||
// A streamed delta rebuilds the model with the same tail. Everything below is keyed on
|
||||
// the rendered tail's identity, so the slice has to be reused, not recomputed.
|
||||
const renderedTailCache = new WeakMap<
|
||||
StreamItem[],
|
||||
WeakMap<StreamItem[], Map<string, StreamTurnTiming>>
|
||||
{ historyStart: number; rendered: StreamItem[] }
|
||||
>();
|
||||
|
||||
function getRenderedTail(tail: StreamItem[], historyStart: number | undefined): StreamItem[] {
|
||||
if (!historyStart) {
|
||||
renderedTailCache.delete(tail);
|
||||
return tail;
|
||||
}
|
||||
const cached = renderedTailCache.get(tail);
|
||||
if (cached?.historyStart === historyStart) {
|
||||
return cached.rendered;
|
||||
}
|
||||
const rendered = tail.slice(historyStart);
|
||||
// Revealing older history replaces the previous window, allowing its arrays and
|
||||
// downstream layouts to be collected while the unchanged source tail stays alive.
|
||||
renderedTailCache.set(tail, { historyStart, rendered });
|
||||
return rendered;
|
||||
}
|
||||
|
||||
function getOrderedItems(params: {
|
||||
cache: WeakMap<StreamItem[], Map<string, StreamItem[]>>;
|
||||
source: StreamItem[];
|
||||
@@ -129,32 +147,6 @@ function splitOrderedTail(params: {
|
||||
return split;
|
||||
}
|
||||
|
||||
function getTurnTiming(params: {
|
||||
isTurnActive: boolean;
|
||||
activeTurnStartedAt: Date | null;
|
||||
tail: StreamItem[];
|
||||
head: StreamItem[];
|
||||
}): StreamTurnTiming {
|
||||
let cachedByHead = turnTimingCache.get(params.tail);
|
||||
if (!cachedByHead) {
|
||||
cachedByHead = new WeakMap();
|
||||
turnTimingCache.set(params.tail, cachedByHead);
|
||||
}
|
||||
let cachedByActivity = cachedByHead.get(params.head);
|
||||
if (!cachedByActivity) {
|
||||
cachedByActivity = new Map();
|
||||
cachedByHead.set(params.head, cachedByActivity);
|
||||
}
|
||||
const activityKey = `${params.isTurnActive}:${params.activeTurnStartedAt?.getTime() ?? "none"}`;
|
||||
const cached = cachedByActivity.get(activityKey);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
const timing = deriveStreamTurnTiming(params);
|
||||
cachedByActivity.set(activityKey, timing);
|
||||
return timing;
|
||||
}
|
||||
|
||||
export function buildAgentStreamRenderModel(
|
||||
input: BuildAgentStreamRenderModelInput,
|
||||
): AgentStreamRenderModel {
|
||||
@@ -163,7 +155,7 @@ export function buildAgentStreamRenderModel(
|
||||
isMobileBreakpoint: input.isMobileBreakpoint,
|
||||
});
|
||||
const orderingCacheKey = `${input.platform}:${input.isMobileBreakpoint}`;
|
||||
const renderedTail = input.historyStart ? input.tail.slice(input.historyStart) : input.tail;
|
||||
const renderedTail = getRenderedTail(input.tail, input.historyStart);
|
||||
const orderedTail = getOrderedItems({
|
||||
cache: orderedTailCache,
|
||||
source: renderedTail,
|
||||
@@ -189,7 +181,7 @@ export function buildAgentStreamRenderModel(
|
||||
platform: input.platform,
|
||||
isMobileBreakpoint: input.isMobileBreakpoint,
|
||||
});
|
||||
const turnTiming = getTurnTiming({
|
||||
const turnTiming = deriveStreamTurnTiming({
|
||||
isTurnActive: input.isTurnActive,
|
||||
activeTurnStartedAt: input.activeTurnStartedAt,
|
||||
tail: renderedTail,
|
||||
|
||||
@@ -1298,6 +1298,8 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
<div style={viewportStyle} data-window-content>
|
||||
<div
|
||||
ref={handleScrollContainerRef}
|
||||
// Let clicks focus the feed for browser keyboard scrolling without adding a Tab stop.
|
||||
tabIndex={-1}
|
||||
data-testid="agent-chat-scroll"
|
||||
data-overlay-scrollbar={scrollEnabled && !isMobileBreakpoint ? "true" : undefined}
|
||||
id={`agent-chat-scroll-${shouldUseVirtualizer ? "web-dom-virtualized" : "web-dom-scroll"}`}
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import { bench, describe } from "vitest";
|
||||
import type { StreamItem, ToolCallItem } from "@/types/stream";
|
||||
import {
|
||||
prepareToolCallHistory,
|
||||
projectToolCallDetailLevel,
|
||||
} from "@/tool-calls/detail-level/projection";
|
||||
import { findMountedWindowStart, getMountedRecentStreamItems } from "./history-window";
|
||||
import { layoutStream } from "./layout";
|
||||
import { buildAgentStreamRenderModel } from "./model";
|
||||
import { resolveStreamRenderStrategy } from "./strategy-resolver";
|
||||
|
||||
// One coalesced delta replaces the stream head. This is the pure work AgentStreamView
|
||||
// does per delta on a long timeline, without React:
|
||||
// npx vitest bench --project unit src/agent-stream/stream-tick.bench.ts
|
||||
|
||||
const TIMELINE_ITEMS = 2_000;
|
||||
const TICKS = 200;
|
||||
|
||||
function timestamp(seed: number): Date {
|
||||
return new Date(1_700_000_000_000 + seed * 1000);
|
||||
}
|
||||
|
||||
function toolCall(id: string, seed: number): ToolCallItem {
|
||||
return {
|
||||
kind: "tool_call",
|
||||
id,
|
||||
timestamp: timestamp(seed),
|
||||
payload: {
|
||||
source: "agent",
|
||||
data: {
|
||||
provider: "claude",
|
||||
callId: id,
|
||||
name: "shell",
|
||||
status: "completed",
|
||||
error: null,
|
||||
detail: { type: "shell", command: id },
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function buildTimeline(count: number): StreamItem[] {
|
||||
const items: StreamItem[] = [];
|
||||
let seed = 0;
|
||||
while (items.length < count) {
|
||||
const turn = items.length;
|
||||
items.push({
|
||||
kind: "user_message",
|
||||
id: `u${turn}`,
|
||||
text: "prompt",
|
||||
timestamp: timestamp(seed++),
|
||||
});
|
||||
items.push(toolCall(`t${turn}a`, seed++));
|
||||
items.push(toolCall(`t${turn}b`, seed++));
|
||||
items.push({
|
||||
kind: "assistant_message",
|
||||
id: `a${turn}`,
|
||||
text: "answer",
|
||||
timestamp: timestamp(seed++),
|
||||
});
|
||||
}
|
||||
return items.slice(0, count);
|
||||
}
|
||||
|
||||
function buildHeads(base: StreamItem[], ticks: number): StreamItem[][] {
|
||||
let text = "";
|
||||
const heads: StreamItem[][] = [];
|
||||
for (let tick = 0; tick < ticks; tick += 1) {
|
||||
text += "token ";
|
||||
heads.push([
|
||||
{
|
||||
kind: "assistant_message",
|
||||
id: "live",
|
||||
text,
|
||||
timestamp: timestamp(base.length + tick),
|
||||
},
|
||||
]);
|
||||
}
|
||||
return heads;
|
||||
}
|
||||
|
||||
function runTicks(input: { tail: StreamItem[]; historyStart: number; heads: StreamItem[][] }) {
|
||||
const { tail, historyStart, heads } = input;
|
||||
const strategy = resolveStreamRenderStrategy({ platform: "web", isMobileBreakpoint: false });
|
||||
const prepared = prepareToolCallHistory("overview", tail);
|
||||
const boundaryId = tail[historyStart]?.id ?? null;
|
||||
const activeTurnStartedAt = tail.at(-1)?.timestamp ?? null;
|
||||
for (const head of heads) {
|
||||
const projected = projectToolCallDetailLevel({
|
||||
level: "overview",
|
||||
tail,
|
||||
head,
|
||||
preparedHistory: prepared,
|
||||
isTurnActive: true,
|
||||
});
|
||||
const boundaryIndex = boundaryId
|
||||
? projected.tail.findIndex((item) => item.id === boundaryId)
|
||||
: -1;
|
||||
const model = buildAgentStreamRenderModel({
|
||||
isTurnActive: true,
|
||||
activeTurnStartedAt,
|
||||
tail: projected.tail,
|
||||
head: projected.head,
|
||||
platform: "web",
|
||||
isMobileBreakpoint: false,
|
||||
historyStart: boundaryIndex >= 0 ? boundaryIndex : historyStart,
|
||||
});
|
||||
layoutStream({
|
||||
strategy,
|
||||
isTurnActive: true,
|
||||
history: model.history,
|
||||
liveHead: model.segments.liveHead,
|
||||
timingByAssistantId: model.turnTiming.byAssistantId,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const tail = buildTimeline(TIMELINE_ITEMS);
|
||||
const heads = buildHeads(tail, TICKS);
|
||||
const defaultWindowStart = findMountedWindowStart({
|
||||
items: tail,
|
||||
minMountedCount: getMountedRecentStreamItems(),
|
||||
});
|
||||
|
||||
describe(`${TICKS} streamed deltas over a ${TIMELINE_ITEMS}-item timeline`, () => {
|
||||
bench("default mounted window (recent items only)", () => {
|
||||
runTicks({ tail, historyStart: defaultWindowStart, heads });
|
||||
});
|
||||
bench("history fully revealed (scrolled to top)", () => {
|
||||
runTicks({ tail, historyStart: 0, heads });
|
||||
});
|
||||
});
|
||||
@@ -70,10 +70,11 @@ export function useStreamHistoryWindow(input: {
|
||||
boundaryItemId: initialBoundaryItemId,
|
||||
initialized: items.length > 0,
|
||||
}));
|
||||
const boundaryIndex =
|
||||
window.agentId === agentId && window.boundaryItemId !== null
|
||||
? items.findIndex((item) => item.id === window.boundaryItemId)
|
||||
: -1;
|
||||
const boundaryItemId = window.agentId === agentId ? window.boundaryItemId : null;
|
||||
const boundaryIndex = useMemo(
|
||||
() => (boundaryItemId === null ? -1 : items.findIndex((item) => item.id === boundaryItemId)),
|
||||
[boundaryItemId, items],
|
||||
);
|
||||
let start = initialStart;
|
||||
if (window.agentId === agentId && window.initialized) {
|
||||
if (window.boundaryItemId === null) {
|
||||
|
||||
@@ -607,16 +607,21 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
toast?.error(t("agentStream.historyLoadFailed"));
|
||||
}, [t, toast]);
|
||||
// Chat find and the chat outline address messages, and an assistant message is a
|
||||
// group of block rows, so this is a set of message ids and never of row ids.
|
||||
const visibleMessageIds = useMemo(
|
||||
() =>
|
||||
new Set(
|
||||
[...baseRenderModel.history, ...baseRenderModel.segments.liveHead].map(
|
||||
getStreamItemMessageId,
|
||||
),
|
||||
),
|
||||
[baseRenderModel.history, baseRenderModel.segments.liveHead],
|
||||
// group of block rows, so these hold message ids and never row ids. Only the head
|
||||
// changes per streamed delta, so the history set is keyed on mounted history alone.
|
||||
const mountedHistoryMessageIds = useMemo(
|
||||
() => new Set(baseRenderModel.history.map(getStreamItemMessageId)),
|
||||
[baseRenderModel.history],
|
||||
);
|
||||
const mountedMessageIds = useMemo(() => {
|
||||
const liveHeadMessageIds = new Set(
|
||||
baseRenderModel.segments.liveHead.map(getStreamItemMessageId),
|
||||
);
|
||||
return {
|
||||
has: (messageId: string) =>
|
||||
mountedHistoryMessageIds.has(messageId) || liveHeadMessageIds.has(messageId),
|
||||
};
|
||||
}, [baseRenderModel.segments.liveHead, mountedHistoryMessageIds]);
|
||||
const chatOutline = useChatOutline({
|
||||
agentId,
|
||||
serverId: resolvedServerId,
|
||||
@@ -626,7 +631,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
enabled: supportsChatOutline && chatOutlineEnabled,
|
||||
viewportRef,
|
||||
onJumpError: handleTimelineHistoryLoadError,
|
||||
visibleMessageIds,
|
||||
mountedHistoryMessageIds,
|
||||
revealLoadedMessage: revealLoadedHistory,
|
||||
});
|
||||
|
||||
@@ -1105,7 +1110,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
items={findItems}
|
||||
viewportRef={viewportRef}
|
||||
revealLoadedMessage={revealLoadedHistory}
|
||||
visibleMessageIds={visibleMessageIds}
|
||||
visibleMessageIds={mountedMessageIds}
|
||||
>
|
||||
<ToolCallSheetProvider>
|
||||
<AssistantSelectionCopySurface style={stylesheet.container}>
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -17,6 +17,14 @@ export function getActiveMessageSubmissions(
|
||||
);
|
||||
}
|
||||
|
||||
export function hasActiveMessageSubmission(
|
||||
submissions: readonly MessageSubmissionRecord[] | null | undefined,
|
||||
): boolean {
|
||||
return (submissions ?? EMPTY_MESSAGE_SUBMISSIONS).some(
|
||||
(submission) => !submission.providerAcknowledged,
|
||||
);
|
||||
}
|
||||
|
||||
export function getSendingClientMessageIds(
|
||||
submissions: readonly MessageSubmissionRecord[] | null | undefined,
|
||||
): string[] {
|
||||
|
||||
@@ -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]: {
|
||||
|
||||
@@ -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: "غير قادر على تثبيت الموفر",
|
||||
},
|
||||
|
||||
@@ -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",
|
||||
},
|
||||
|
||||
@@ -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",
|
||||
},
|
||||
|
||||
@@ -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",
|
||||
},
|
||||
|
||||
@@ -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: "プロバイダーをインストールできません",
|
||||
},
|
||||
|
||||
@@ -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: "프로바이더를 설치할 수 없습니다",
|
||||
},
|
||||
|
||||
@@ -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",
|
||||
},
|
||||
|
||||
@@ -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: "Не удалось установить провайдера",
|
||||
},
|
||||
|
||||
@@ -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",
|
||||
},
|
||||
|
||||
@@ -4,6 +4,7 @@ import { keyboardEventToComboString } from "./shortcut-string";
|
||||
import {
|
||||
buildKeyboardShortcutHelpSections,
|
||||
buildEffectiveBindings,
|
||||
normalizeCapturedShortcutCombo,
|
||||
getBindingIdForAction,
|
||||
getDefaultKeysForAction,
|
||||
getWorkspaceIndexJumpModifierKey,
|
||||
@@ -823,9 +824,9 @@ describe("keyboard-shortcut help sections", () => {
|
||||
expect(rowChord({}, "show-shortcuts")).toEqual([["?"]]);
|
||||
});
|
||||
|
||||
it("replaces the default-only wildcard when the index jump is rebound", () => {
|
||||
it("keeps the digit range readable when the index jump is rebound", () => {
|
||||
expect(rowChord({ [MAC_INDEX_BINDING]: "Ctrl+Digit" }, "workspace-jump-index")).toEqual([
|
||||
["ctrl", "Digit"],
|
||||
["ctrl", "1-9"],
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -1347,3 +1348,45 @@ describe("direct new-tab target shortcuts", () => {
|
||||
).toEqual([["ctrl", "shift", "H"]]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("number-group shortcut capture", () => {
|
||||
const tabBindingId = "workspace-tab-navigate-index-cmd-alt-digit-mac-desktop";
|
||||
it.each([
|
||||
{ id: tabBindingId, action: "workspace.tab.navigate.index", row: "workspace-tab-jump-index" },
|
||||
{
|
||||
id: "workspace-navigate-index-cmd-digit-mac",
|
||||
action: "workspace.navigate.index",
|
||||
row: "workspace-jump-index",
|
||||
},
|
||||
])("captures Ctrl+1 as the entire number group for $row", ({ id, action, row }) => {
|
||||
const combo = normalizeCapturedShortcutCombo(id, "Ctrl+1");
|
||||
expect(combo).toBe("Ctrl+Digit");
|
||||
const overrides = { [id]: combo };
|
||||
const bindings = buildEffectiveBindings(overrides);
|
||||
for (let index = 1; index <= 9; index++) {
|
||||
const result = resolveShortcut({
|
||||
event: { key: String(index), code: `Digit${index}`, ctrlKey: true },
|
||||
context: { isMac: true, isDesktop: true, focusScope: "message-input" },
|
||||
bindings,
|
||||
});
|
||||
expect(result.match?.action).toBe(action);
|
||||
expect(result.match?.payload).toEqual({ index });
|
||||
}
|
||||
expect(resolveShortcutKeysForAction(row, overrides, { isMac: true, isDesktop: true })).toEqual([
|
||||
["ctrl", "1-9"],
|
||||
]);
|
||||
expect(
|
||||
resolveShortcut({
|
||||
event: { key: "0", code: "Digit0", ctrlKey: true },
|
||||
context: { isMac: true, isDesktop: true },
|
||||
bindings,
|
||||
}).match,
|
||||
).toBeNull();
|
||||
});
|
||||
it("preserves literal numbers for non-index actions and existing nonnumeric combos", () => {
|
||||
expect(normalizeCapturedShortcutCombo("show-shortcuts", "Ctrl+1")).toBe("Ctrl+1");
|
||||
expect(normalizeCapturedShortcutCombo(tabBindingId, "Ctrl+K")).toBe("Ctrl+K");
|
||||
expect(normalizeCapturedShortcutCombo(tabBindingId, "Ctrl+0")).toBe("Ctrl+0");
|
||||
expect(normalizeCapturedShortcutCombo(tabBindingId, "Ctrl+9")).toBe("Ctrl+Digit");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1210,6 +1210,13 @@ export const DEFAULT_BINDINGS: readonly ParsedShortcutBinding[] =
|
||||
|
||||
export type ShortcutOverrides = Record<string, string | null>;
|
||||
|
||||
/** Keep number-group actions bound to all nine indices when recording a new modifier. */
|
||||
export function normalizeCapturedShortcutCombo(bindingId: string, combo: string): string {
|
||||
const binding = DEFAULT_BINDINGS.find((candidate) => candidate.id === bindingId);
|
||||
if (binding?.payload?.type !== "index") return combo;
|
||||
return combo.replace(/(^|\+)[1-9]$/, "$1Digit");
|
||||
}
|
||||
|
||||
export function buildEffectiveBindings(overrides: ShortcutOverrides): ParsedShortcutBinding[] {
|
||||
return DEFAULT_BINDINGS.map(function (binding) {
|
||||
const override = overrides[binding.id];
|
||||
|
||||
@@ -192,6 +192,7 @@ const MODIFIER_CODES = new Set([
|
||||
* override on a named key renders as a raw code — `ARROWLEFT`, not `←`.
|
||||
*/
|
||||
const DISPLAY_KEY_ALIASES: Record<string, string> = {
|
||||
Digit: "1-9",
|
||||
ArrowLeft: "Left",
|
||||
ArrowRight: "Right",
|
||||
ArrowUp: "Up",
|
||||
|
||||
@@ -301,6 +301,19 @@ describe("ReplicaCache", () => {
|
||||
expect(storage.rows.size).toBe(0);
|
||||
});
|
||||
|
||||
it("preserves background visibility when restoring a cached workspace", async () => {
|
||||
const storage = new MemoryStorage();
|
||||
const writer = createCache(storage);
|
||||
const original = directory();
|
||||
original.workspaces.get("workspace-1")!.background = true;
|
||||
commitDirectory(writer, SERVER_ID, original);
|
||||
await writer.flush();
|
||||
|
||||
const reader = createCache(storage);
|
||||
const restored = await reader.readDirectory(SERVER_ID);
|
||||
expect(restored.workspaces.get("workspace-1")?.background).toBe(true);
|
||||
});
|
||||
|
||||
it("round-trips explicit directory and timeline commits", async () => {
|
||||
const storage = new MemoryStorage();
|
||||
const writer = createCache(storage);
|
||||
@@ -464,6 +477,19 @@ describe("ReplicaCache", () => {
|
||||
expect((await cache.readDirectory(SERVER_ID)).projects.size).toBe(0);
|
||||
});
|
||||
|
||||
it("does not return an accepted agent that storage rejected", async () => {
|
||||
const storage = new MemoryStorage();
|
||||
const cache = createCache(storage);
|
||||
storage.persistentWriteFailure = new Error("disk unavailable");
|
||||
commitDirectory(cache, SERVER_ID, directory());
|
||||
await cache.flush();
|
||||
|
||||
const result = await cache.readAgent(SERVER_ID, "agent-1");
|
||||
|
||||
expect(storage.rows.size).toBe(0);
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it("fails closed when an accepted deletion cannot be persisted before a read", async () => {
|
||||
const storage = new MemoryStorage();
|
||||
const cache = createCache(storage);
|
||||
@@ -504,6 +530,25 @@ describe("ReplicaCache", () => {
|
||||
expect((await cache.readWorkspace(SERVER_ID, "workspace-1"))?.workspace.id).toBe("workspace-1");
|
||||
});
|
||||
|
||||
it("discards an in-flight read across host removal and reactivation", async () => {
|
||||
const storage = new MemoryStorage();
|
||||
const cache = createCache(storage);
|
||||
commitDirectory(cache, SERVER_ID, directory());
|
||||
await cache.flush();
|
||||
const started = deferred();
|
||||
const release = deferred();
|
||||
storage.onRead = started.resolve;
|
||||
storage.readGate = release.promise;
|
||||
|
||||
const reading = cache.readAgent(SERVER_ID, "agent-1");
|
||||
await started.promise;
|
||||
cache.setHosts([]);
|
||||
cache.setHosts([SERVER_ID]);
|
||||
release.resolve();
|
||||
|
||||
expect(await reading).toBeUndefined();
|
||||
});
|
||||
|
||||
it("discards a durable read when the host changes while it is in flight", async () => {
|
||||
const storage = new MemoryStorage();
|
||||
const cache = createCache(storage);
|
||||
@@ -522,6 +567,36 @@ describe("ReplicaCache", () => {
|
||||
expect(await reading).toBeUndefined();
|
||||
});
|
||||
|
||||
it("retries a timeline read when that same timeline changes in flight", async () => {
|
||||
const storage = new MemoryStorage();
|
||||
const cache = createCache(storage);
|
||||
cache.commitTimeline(SERVER_ID, "agent-1", timeline("Old"));
|
||||
await cache.flush();
|
||||
storage.onRead = () => {
|
||||
storage.onRead = null;
|
||||
cache.commitTimeline(SERVER_ID, "agent-1", timeline("New"));
|
||||
};
|
||||
|
||||
expect((await cache.readTimeline(SERVER_ID, "agent-1"))?.items).toEqual([timelineItem("New")]);
|
||||
expect(storage.reads).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("discards a requested row removed by a directory baseline replacement in flight", async () => {
|
||||
const storage = new MemoryStorage();
|
||||
const cache = createCache(storage);
|
||||
commitDirectory(cache, SERVER_ID, directory());
|
||||
await cache.flush();
|
||||
const replacement = directory();
|
||||
replacement.agents.clear();
|
||||
storage.onRead = () => {
|
||||
storage.onRead = null;
|
||||
cache.replaceDirectoryBaseline(SERVER_ID, replacement);
|
||||
};
|
||||
|
||||
expect(await cache.readAgent(SERVER_ID, "agent-1")).toBeUndefined();
|
||||
expect(storage.reads).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("never reads a timeline older than an accepted deferred replacement", async () => {
|
||||
const storage = new MemoryStorage();
|
||||
const cache = createCache(storage);
|
||||
@@ -796,7 +871,7 @@ describe("ReplicaCache", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("retries a timeline read invalidated by a concurrent directory commit", async () => {
|
||||
it("reads a persisted timeline across a concurrent directory commit", async () => {
|
||||
const storage = new MemoryStorage();
|
||||
const cache = createCache(storage);
|
||||
cache.commitTimeline(SERVER_ID, "agent-1", timeline("Persisted timeline"));
|
||||
@@ -858,6 +933,90 @@ describe("ReplicaCache", () => {
|
||||
|
||||
expect(storage.cleanups).toBe(1);
|
||||
});
|
||||
|
||||
describe.each(["timeline", "directory"] as const)(
|
||||
"while another agent streams %s updates",
|
||||
(kind) => {
|
||||
async function streamingCache() {
|
||||
const storage = new MemoryStorage();
|
||||
const cache = createCache(storage);
|
||||
commitDirectory(cache, SERVER_ID, directory());
|
||||
cache.commitTimeline(SERVER_ID, "agent-1", timeline());
|
||||
await cache.flush();
|
||||
const readsBefore = storage.reads.length;
|
||||
const writesBefore = storage.writes;
|
||||
let chunks = 0;
|
||||
storage.onRead = () => {
|
||||
if (chunks >= 200) return;
|
||||
chunks += 1;
|
||||
if (kind === "timeline") {
|
||||
cache.commitTimeline(SERVER_ID, "agent-2", {
|
||||
...timeline(`chunk ${chunks}`),
|
||||
agentId: "agent-2",
|
||||
});
|
||||
} else {
|
||||
cache.commitDirectoryMutations(
|
||||
SERVER_ID,
|
||||
[{ type: "upsert", kind: "agent", id: "agent-2", value: agent("agent-2") }],
|
||||
{ agents: { generation: "g", afterSeq: 12 + chunks } },
|
||||
);
|
||||
}
|
||||
};
|
||||
return {
|
||||
cache,
|
||||
expectReads: (count: number, writes = 0) => {
|
||||
expect(storage.reads.length - readsBefore).toBe(count);
|
||||
expect(storage.writes - writesBefore).toBe(writes);
|
||||
expect(chunks).toBe(count);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
it("reads another cached agent without waiting for the stream to stop", async () => {
|
||||
const { cache, expectReads } = await streamingCache();
|
||||
|
||||
expect((await cache.readAgent(SERVER_ID, "agent-1"))?.title).toBe("Cached agent");
|
||||
expectReads(1);
|
||||
await cache.flush();
|
||||
});
|
||||
|
||||
it("reads another cached workspace without waiting for the stream to stop", async () => {
|
||||
const { cache, expectReads } = await streamingCache();
|
||||
|
||||
expect((await cache.readWorkspace(SERVER_ID, "workspace-1"))?.workspace.name).toBe("main");
|
||||
expectReads(2, 1);
|
||||
await cache.flush();
|
||||
});
|
||||
|
||||
it("reads another cached timeline without waiting for the stream to stop", async () => {
|
||||
const { cache, expectReads } = await streamingCache();
|
||||
|
||||
expect(await cache.readTimeline(SERVER_ID, "agent-1")).toEqual(timeline());
|
||||
expectReads(1);
|
||||
await cache.flush();
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("reads the directory after persisting a pending baseline replacement", async () => {
|
||||
const storage = new MemoryStorage();
|
||||
const cache = createCache(storage);
|
||||
commitDirectory(cache, SERVER_ID, directory());
|
||||
cache.commitTimeline(SERVER_ID, "agent-1", timeline());
|
||||
await cache.flush();
|
||||
const replacement = directory({ agents: { generation: "g2", afterSeq: 1 } });
|
||||
replacement.projects.clear();
|
||||
replacement.agents.set("agent-2", agent("agent-2"));
|
||||
cache.replaceDirectoryBaseline(SERVER_ID, replacement);
|
||||
|
||||
const read = await cache.readDirectory(SERVER_ID);
|
||||
|
||||
expect([...read.agents.keys()].sort()).toEqual(["agent-1", "agent-2"]);
|
||||
expect(read.projects.size).toBe(0);
|
||||
expect(read.checkpoint).toEqual({ agents: { generation: "g2", afterSeq: 1 } });
|
||||
expect(await cache.readTimeline(SERVER_ID, "agent-1")).toEqual(timeline());
|
||||
expect(storage.writes).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
it("retains semantic agent messages across disk-cache reconstruction", async () => {
|
||||
|
||||
@@ -880,9 +880,24 @@ function directoryEntityForRow(row: ReplicaRow): keyof DirectoryCheckpoint | und
|
||||
return undefined;
|
||||
}
|
||||
|
||||
interface ReplicaRead {
|
||||
serverId: string;
|
||||
kinds: readonly ReplicaRowKind[];
|
||||
ids?: readonly string[];
|
||||
invalidated: boolean;
|
||||
}
|
||||
|
||||
function matchesReplicaRead(read: ReplicaRead, row: ReplicaRowKey): boolean {
|
||||
return (
|
||||
read.serverId === row.serverId &&
|
||||
read.kinds.includes(row.kind) &&
|
||||
(!read.ids || read.ids.includes(row.id))
|
||||
);
|
||||
}
|
||||
|
||||
export class ReplicaCache {
|
||||
private readonly activeServerIds = new Set<string>();
|
||||
private readonly hostRevisions = new Map<string, number>();
|
||||
private readonly activeReads = new Set<ReplicaRead>();
|
||||
private readonly storedRows = new Map<string, Map<string, ReplicaRow>>();
|
||||
private readonly hostBytes = new Map<string, number>();
|
||||
private readonly hostWriteOrder = new Map<string, true>();
|
||||
@@ -1004,10 +1019,22 @@ export class ReplicaCache {
|
||||
// accepted commits to land. A store that rejects them will keep rejecting them: fail closed
|
||||
// rather than re-attempt the write on every pass. A write rejected for another host leaves
|
||||
// this host's stored rows readable.
|
||||
if (!(await this.syncPending()) && this.hasPendingHostChanges(serverId)) return [];
|
||||
const revision = this.hostRevisions.get(serverId) ?? 0;
|
||||
const rows = await this.rowStore.read(serverId, kinds, ids);
|
||||
if (this.canReadHostRevision(serverId, revision)) return rows;
|
||||
const read: ReplicaRead = { serverId, kinds, ids, invalidated: false };
|
||||
this.activeReads.add(read);
|
||||
try {
|
||||
if (!(await this.syncPending()) && this.hasPendingHostChanges(serverId)) return [];
|
||||
if (read.invalidated || this.hasPendingReadChanges(read)) continue;
|
||||
const rows = await this.rowStore.read(serverId, kinds, ids);
|
||||
if (
|
||||
this.activeServerIds.has(serverId) &&
|
||||
!read.invalidated &&
|
||||
!this.hasPendingReadChanges(read)
|
||||
) {
|
||||
return rows;
|
||||
}
|
||||
} finally {
|
||||
this.activeReads.delete(read);
|
||||
}
|
||||
}
|
||||
return [];
|
||||
} catch {
|
||||
@@ -1092,7 +1119,6 @@ export class ReplicaCache {
|
||||
): void {
|
||||
if (!this.activeServerIds.has(serverId)) return;
|
||||
if (this.invalidatedHosts.has(serverId)) return;
|
||||
this.advanceHostRevision(serverId);
|
||||
for (const mutation of mutations) {
|
||||
if (mutation.type === "delete") {
|
||||
this.queueEntityDelete(serverId, mutation.kind, mutation.id);
|
||||
@@ -1118,7 +1144,7 @@ export class ReplicaCache {
|
||||
|
||||
replaceDirectoryBaseline(serverId: string, directory: CachedDirectory): void {
|
||||
if (!this.activeServerIds.has(serverId)) return;
|
||||
this.advanceHostRevision(serverId);
|
||||
this.invalidateHostReads(serverId, ["agent", "workspace", "project", "checkpoint"]);
|
||||
// Replacing the directory must not discard independently accepted timeline changes.
|
||||
for (const [key, row] of this.pendingUpserts) {
|
||||
if (row.serverId === serverId && row.kind !== "timeline") this.pendingUpserts.delete(key);
|
||||
@@ -1150,7 +1176,6 @@ export class ReplicaCache {
|
||||
commitTimeline(serverId: string, agentId: string, timeline: CachedTimeline): void {
|
||||
if (!this.activeServerIds.has(serverId)) return;
|
||||
if (timeline.agentId !== agentId) throw new Error("Timeline cache key does not match payload");
|
||||
this.advanceHostRevision(serverId);
|
||||
this.queueUpsert({ serverId, kind: "timeline", id: agentId, value: timeline });
|
||||
this.schedulePersist();
|
||||
}
|
||||
@@ -1159,7 +1184,7 @@ export class ReplicaCache {
|
||||
const next = new Set(serverIds);
|
||||
const removed = [...this.activeServerIds].filter((serverId) => !next.has(serverId));
|
||||
const added = [...next].filter((serverId) => !this.activeServerIds.has(serverId));
|
||||
for (const serverId of [...removed, ...added]) this.advanceHostRevision(serverId);
|
||||
for (const serverId of [...removed, ...added]) this.invalidateHostReads(serverId);
|
||||
this.activeServerIds.clear();
|
||||
for (const serverId of next) this.activeServerIds.add(serverId);
|
||||
for (const serverId of removed) {
|
||||
@@ -1171,8 +1196,8 @@ export class ReplicaCache {
|
||||
}
|
||||
|
||||
reconcileServerId(oldServerId: string, newServerId: string): void {
|
||||
this.advanceHostRevision(oldServerId);
|
||||
this.advanceHostRevision(newServerId);
|
||||
this.invalidateHostReads(oldServerId);
|
||||
this.invalidateHostReads(newServerId);
|
||||
const rows = this.storedRows.get(oldServerId);
|
||||
if (rows) {
|
||||
const newRows = this.storedRows.get(newServerId) ?? new Map<string, ReplicaRow>();
|
||||
@@ -1250,12 +1275,14 @@ export class ReplicaCache {
|
||||
}
|
||||
|
||||
private queueUpsert(row: StructuredReplicaUpsert): void {
|
||||
this.invalidateRowReads(row);
|
||||
const key = pendingRowKey(row);
|
||||
this.pendingDeletes.delete(key);
|
||||
this.pendingUpserts.set(key, row);
|
||||
}
|
||||
|
||||
private queueDelete(key: ReplicaRowKey): void {
|
||||
this.invalidateRowReads(key);
|
||||
const pendingKey = pendingRowKey(key);
|
||||
this.pendingUpserts.delete(pendingKey);
|
||||
this.pendingDeletes.set(pendingKey, key);
|
||||
@@ -1267,14 +1294,36 @@ export class ReplicaCache {
|
||||
);
|
||||
}
|
||||
|
||||
private canReadHostRevision(serverId: string, revision: number): boolean {
|
||||
private hasPendingReadChanges(read: ReplicaRead): boolean {
|
||||
if (
|
||||
this.pendingBaselines.has(read.serverId) &&
|
||||
read.kinds.some((kind) => kind !== "timeline")
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
return (
|
||||
this.activeServerIds.has(serverId) &&
|
||||
(this.hostRevisions.get(serverId) ?? 0) === revision &&
|
||||
!this.hasPendingHostChanges(serverId)
|
||||
[...this.pendingUpserts.values()].some((row) => matchesReplicaRead(read, row)) ||
|
||||
[...this.pendingDeletes.values()].some((row) => matchesReplicaRead(read, row))
|
||||
);
|
||||
}
|
||||
|
||||
private invalidateRowReads(row: ReplicaRowKey): void {
|
||||
for (const read of this.activeReads) {
|
||||
if (matchesReplicaRead(read, row)) read.invalidated = true;
|
||||
}
|
||||
}
|
||||
|
||||
private invalidateHostReads(serverId: string, kinds?: readonly ReplicaRowKind[]): void {
|
||||
for (const read of this.activeReads) {
|
||||
if (
|
||||
read.serverId === serverId &&
|
||||
(!kinds || kinds.some((kind) => read.kinds.includes(kind)))
|
||||
) {
|
||||
read.invalidated = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private hasPendingHostChanges(serverId: string): boolean {
|
||||
if (this.pendingBaselines.has(serverId)) return true;
|
||||
for (const row of this.pendingUpserts.values()) {
|
||||
@@ -1286,10 +1335,6 @@ export class ReplicaCache {
|
||||
return false;
|
||||
}
|
||||
|
||||
private advanceHostRevision(serverId: string): void {
|
||||
this.hostRevisions.set(serverId, (this.hostRevisions.get(serverId) ?? 0) + 1);
|
||||
}
|
||||
|
||||
private drainPendingChanges(): PendingReplicaChanges {
|
||||
const changes = {
|
||||
upserts: [...this.pendingUpserts.values()],
|
||||
|
||||
@@ -19,6 +19,7 @@ import { useKeyboardShortcutOverrides } from "@/hooks/use-keyboard-shortcut-over
|
||||
import {
|
||||
buildKeyboardShortcutHelpSections,
|
||||
getBindingIdForAction,
|
||||
normalizeCapturedShortcutCombo,
|
||||
getDefaultKeysForAction,
|
||||
resolveShortcutKeysForAction,
|
||||
type KeyboardShortcutHelpRow,
|
||||
@@ -389,7 +390,8 @@ export function KeyboardShortcutsSection() {
|
||||
}
|
||||
|
||||
setHeldModifiers(null);
|
||||
setCapturedCombos((current) => [...current, comboString]);
|
||||
const capturedCombo = normalizeCapturedShortcutCombo(capturingBindingId!, comboString);
|
||||
setCapturedCombos((current) => [...current, capturedCombo]);
|
||||
}
|
||||
|
||||
window.addEventListener("keydown", handleKeyDown, true);
|
||||
|
||||
@@ -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 (
|
||||
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
import {
|
||||
acceptMessageSubmission,
|
||||
beginMessageSubmission,
|
||||
getActiveMessageSubmissions,
|
||||
hasActiveMessageSubmission,
|
||||
observeMessageSubmissionCanonical,
|
||||
rejectMessageSubmission,
|
||||
type MessageSubmissionRecord,
|
||||
@@ -348,7 +348,7 @@ export function selectAgentTurnPresentation(
|
||||
session?.agents.get(agentId)?.turn ??
|
||||
session?.agentDetails.get(agentId)?.turn ??
|
||||
TURN_LIVENESS_IDLE,
|
||||
getActiveMessageSubmissions(session?.messageSubmissions.get(agentId)).length > 0,
|
||||
hasActiveMessageSubmission(session?.messageSubmissions.get(agentId)),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -12,11 +12,11 @@ function user(id: string, timestamp: Date): StreamItem {
|
||||
};
|
||||
}
|
||||
|
||||
function assistant(id: string, timestamp: Date): StreamItem {
|
||||
function assistant(id: string, timestamp: Date, text = id): StreamItem {
|
||||
return {
|
||||
kind: "assistant_message",
|
||||
id,
|
||||
text: id,
|
||||
text,
|
||||
timestamp,
|
||||
};
|
||||
}
|
||||
@@ -125,4 +125,97 @@ describe("deriveStreamTurnTiming", () => {
|
||||
durationMs: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the timing map identity while a streamed delta grows the live head", () => {
|
||||
const tail = [
|
||||
user("u1", new Date("2026-05-15T00:00:00.000Z")),
|
||||
assistant("a1", new Date("2026-05-15T00:00:07.000Z")),
|
||||
user("u2", new Date("2026-05-15T00:01:00.000Z")),
|
||||
];
|
||||
const derive = (text: string, at: string) =>
|
||||
deriveStreamTurnTiming({
|
||||
isTurnActive: true,
|
||||
activeTurnStartedAt: tail[2]?.timestamp ?? null,
|
||||
tail,
|
||||
head: [assistant("a2", new Date(at), text)],
|
||||
});
|
||||
|
||||
const first = derive("one", "2026-05-15T00:01:04.000Z");
|
||||
const second = derive("one two", "2026-05-15T00:01:05.000Z");
|
||||
|
||||
assert.equal(second.byAssistantId, first.byAssistantId);
|
||||
assert.deepEqual(first.byAssistantId.get("a1"), {
|
||||
completedAt: tail[1]?.timestamp,
|
||||
durationMs: 7000,
|
||||
});
|
||||
assert.equal(first.byAssistantId.has("a2"), false);
|
||||
});
|
||||
|
||||
it("keeps the timing map identity when the head closed the tail's open turn", () => {
|
||||
const lastTailAt = new Date("2026-05-15T00:00:07.000Z");
|
||||
const tail = [user("u1", new Date("2026-05-15T00:00:00.000Z")), assistant("a1", lastTailAt)];
|
||||
const derive = (text: string, at: string) =>
|
||||
deriveStreamTurnTiming({
|
||||
isTurnActive: true,
|
||||
activeTurnStartedAt: null,
|
||||
tail,
|
||||
head: [
|
||||
user("u2", new Date("2026-05-15T00:01:00.000Z")),
|
||||
assistant("a2", new Date(at), text),
|
||||
],
|
||||
});
|
||||
|
||||
const first = derive("one", "2026-05-15T00:01:04.000Z");
|
||||
const second = derive("one two", "2026-05-15T00:01:05.000Z");
|
||||
|
||||
assert.equal(second.byAssistantId, first.byAssistantId);
|
||||
assert.deepEqual(first.byAssistantId.get("a1"), {
|
||||
completedAt: lastTailAt,
|
||||
durationMs: 7000,
|
||||
});
|
||||
});
|
||||
|
||||
it("produces a new timing map when the streamed turn completes", () => {
|
||||
const tail = [user("u1", new Date("2026-05-15T00:00:00.000Z"))];
|
||||
const completedAt = new Date("2026-05-15T00:00:09.000Z");
|
||||
const head = [assistant("a1", completedAt)];
|
||||
|
||||
const active = deriveStreamTurnTiming({
|
||||
isTurnActive: true,
|
||||
activeTurnStartedAt: tail[0]?.timestamp ?? null,
|
||||
tail,
|
||||
head,
|
||||
});
|
||||
const completed = deriveStreamTurnTiming({
|
||||
isTurnActive: false,
|
||||
activeTurnStartedAt: null,
|
||||
tail,
|
||||
head,
|
||||
});
|
||||
|
||||
assert.notEqual(completed.byAssistantId, active.byAssistantId);
|
||||
assert.equal(active.byAssistantId.has("a1"), false);
|
||||
assert.deepEqual(completed.byAssistantId.get("a1"), { completedAt, durationMs: 9000 });
|
||||
});
|
||||
|
||||
it("derives fresh timing when the tail itself changes", () => {
|
||||
const firstTail = [
|
||||
user("u1", new Date("2026-05-15T00:00:00.000Z")),
|
||||
assistant("a1", new Date("2026-05-15T00:00:07.000Z")),
|
||||
user("u2", new Date("2026-05-15T00:01:00.000Z")),
|
||||
];
|
||||
const secondTail = [...firstTail, assistant("a2", new Date("2026-05-15T00:01:03.000Z"))];
|
||||
const derive = (tail: StreamItem[]) =>
|
||||
deriveStreamTurnTiming({ isTurnActive: false, activeTurnStartedAt: null, tail, head: [] });
|
||||
|
||||
const first = derive(firstTail);
|
||||
const second = derive(secondTail);
|
||||
|
||||
assert.notEqual(second.byAssistantId, first.byAssistantId);
|
||||
assert.equal(first.byAssistantId.has("a2"), false);
|
||||
assert.deepEqual(second.byAssistantId.get("a2"), {
|
||||
completedAt: secondTail[3]?.timestamp,
|
||||
durationMs: 3000,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -11,61 +11,135 @@ export interface StreamTurnTiming {
|
||||
runningStartedAt: Date | null;
|
||||
}
|
||||
|
||||
interface OpenTurn {
|
||||
userAt: Date | null;
|
||||
lastItemAt: Date | null;
|
||||
assistantIds: readonly string[];
|
||||
previousItem: StreamItem | null;
|
||||
}
|
||||
|
||||
interface HeadTurnTiming {
|
||||
additions: Map<string, TurnTiming>;
|
||||
byAssistantId: Map<string, TurnTiming>;
|
||||
}
|
||||
|
||||
interface TailTurnTiming {
|
||||
completed: Map<string, TurnTiming>;
|
||||
openTurn: OpenTurn;
|
||||
lastHead: HeadTurnTiming | null;
|
||||
}
|
||||
|
||||
const EMPTY_OPEN_TURN: OpenTurn = {
|
||||
userAt: null,
|
||||
lastItemAt: null,
|
||||
assistantIds: [],
|
||||
previousItem: null,
|
||||
};
|
||||
|
||||
function closeTurn(turn: OpenTurn, into: Map<string, TurnTiming>): void {
|
||||
if (!turn.lastItemAt || turn.assistantIds.length === 0) {
|
||||
return;
|
||||
}
|
||||
const timing: TurnTiming = {
|
||||
completedAt: turn.lastItemAt,
|
||||
durationMs: turn.userAt ? Math.max(0, turn.lastItemAt.getTime() - turn.userAt.getTime()) : null,
|
||||
};
|
||||
for (const id of turn.assistantIds) {
|
||||
into.set(id, timing);
|
||||
}
|
||||
}
|
||||
|
||||
function walkTurns(
|
||||
items: readonly StreamItem[],
|
||||
from: OpenTurn,
|
||||
into: Map<string, TurnTiming>,
|
||||
): OpenTurn {
|
||||
let userAt = from.userAt;
|
||||
let lastItemAt = from.lastItemAt;
|
||||
let assistantIds = [...from.assistantIds];
|
||||
let previousItem = from.previousItem;
|
||||
for (const item of items) {
|
||||
if (startsNewTurn(item, previousItem)) {
|
||||
closeTurn({ userAt, lastItemAt, assistantIds, previousItem }, into);
|
||||
userAt = item.kind === "user_message" ? item.timestamp : null;
|
||||
lastItemAt = null;
|
||||
assistantIds = [];
|
||||
}
|
||||
lastItemAt = item.timestamp;
|
||||
if (item.kind === "assistant_message") {
|
||||
assistantIds.push(item.id);
|
||||
}
|
||||
previousItem = item;
|
||||
}
|
||||
return { userAt, lastItemAt, assistantIds, previousItem };
|
||||
}
|
||||
|
||||
function areTimingsEqual(a: Map<string, TurnTiming>, b: Map<string, TurnTiming>): boolean {
|
||||
if (a.size !== b.size) {
|
||||
return false;
|
||||
}
|
||||
for (const [id, timing] of a) {
|
||||
const other = b.get(id);
|
||||
if (
|
||||
!other ||
|
||||
other.completedAt.getTime() !== timing.completedAt.getTime() ||
|
||||
other.durationMs !== timing.durationMs
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// The tail walk is cached by array identity so a streamed delta, which only replaces the
|
||||
// head, walks the head from the carried open turn. The returned Map keeps its identity
|
||||
// while the head adds no completed turn, so memos keyed on it do not miss per tick.
|
||||
const tailTurnTimingCache = new WeakMap<StreamItem[], TailTurnTiming>();
|
||||
|
||||
function getTailTurnTiming(tail: StreamItem[]): TailTurnTiming {
|
||||
const cached = tailTurnTimingCache.get(tail);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
const completed = new Map<string, TurnTiming>();
|
||||
const openTurn = walkTurns(tail, EMPTY_OPEN_TURN, completed);
|
||||
const timing: TailTurnTiming = { completed, openTurn, lastHead: null };
|
||||
tailTurnTimingCache.set(tail, timing);
|
||||
return timing;
|
||||
}
|
||||
|
||||
function resolveByAssistantId(
|
||||
tail: TailTurnTiming,
|
||||
additions: Map<string, TurnTiming>,
|
||||
): Map<string, TurnTiming> {
|
||||
if (additions.size === 0) {
|
||||
return tail.completed;
|
||||
}
|
||||
if (tail.lastHead && areTimingsEqual(tail.lastHead.additions, additions)) {
|
||||
return tail.lastHead.byAssistantId;
|
||||
}
|
||||
const byAssistantId = new Map(tail.completed);
|
||||
for (const [id, timing] of additions) {
|
||||
byAssistantId.set(id, timing);
|
||||
}
|
||||
tail.lastHead = { additions, byAssistantId };
|
||||
return byAssistantId;
|
||||
}
|
||||
|
||||
export function deriveStreamTurnTiming(params: {
|
||||
isTurnActive: boolean;
|
||||
activeTurnStartedAt: Date | null;
|
||||
tail: StreamItem[];
|
||||
head: StreamItem[];
|
||||
}): StreamTurnTiming {
|
||||
const byAssistantId = new Map<string, TurnTiming>();
|
||||
let currentUserAt: Date | null = null;
|
||||
let currentLastItemAt: Date | null = null;
|
||||
let currentAssistantIds: string[] = [];
|
||||
let previousItem: StreamItem | null = null;
|
||||
|
||||
const flushCompletedTurn = () => {
|
||||
if (!currentLastItemAt || currentAssistantIds.length === 0) {
|
||||
return;
|
||||
}
|
||||
const timing: TurnTiming = {
|
||||
completedAt: currentLastItemAt,
|
||||
durationMs: currentUserAt
|
||||
? Math.max(0, currentLastItemAt.getTime() - currentUserAt.getTime())
|
||||
: null,
|
||||
};
|
||||
for (const id of currentAssistantIds) {
|
||||
byAssistantId.set(id, timing);
|
||||
}
|
||||
};
|
||||
|
||||
const visitItem = (item: StreamItem) => {
|
||||
if (startsNewTurn(item, previousItem)) {
|
||||
flushCompletedTurn();
|
||||
currentUserAt = item.kind === "user_message" ? item.timestamp : null;
|
||||
currentLastItemAt = null;
|
||||
currentAssistantIds = [];
|
||||
}
|
||||
currentLastItemAt = item.timestamp;
|
||||
if (item.kind === "assistant_message") {
|
||||
currentAssistantIds.push(item.id);
|
||||
}
|
||||
previousItem = item;
|
||||
};
|
||||
|
||||
for (const item of params.tail) {
|
||||
visitItem(item);
|
||||
}
|
||||
for (const item of params.head) {
|
||||
visitItem(item);
|
||||
}
|
||||
|
||||
const runningStartedAt = params.isTurnActive ? params.activeTurnStartedAt : null;
|
||||
const tail = getTailTurnTiming(params.tail);
|
||||
const additions = new Map<string, TurnTiming>();
|
||||
const openTurn = walkTurns(params.head, tail.openTurn, additions);
|
||||
if (!params.isTurnActive) {
|
||||
flushCompletedTurn();
|
||||
closeTurn(openTurn, additions);
|
||||
}
|
||||
|
||||
return {
|
||||
byAssistantId,
|
||||
runningStartedAt,
|
||||
byAssistantId: resolveByAssistantId(tail, additions),
|
||||
runningStartedAt: params.isTurnActive ? params.activeTurnStartedAt : null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -257,6 +257,22 @@ describe("settleReports", () => {
|
||||
expect(settleReports([refreshed, beta], [alpha, beta])).toEqual([refreshed, beta]);
|
||||
});
|
||||
|
||||
it("keeps the displayed order when providers finish a refresh in reverse order", () => {
|
||||
const refreshed = entry({ sourceId: "alpha", planLabel: "New" });
|
||||
const streamed = upsertReport(upsertReport([alpha, beta], beta), refreshed);
|
||||
expect(settleReports(streamed, [beta, refreshed])).toEqual([refreshed, beta]);
|
||||
});
|
||||
|
||||
it("drops missing reports and appends new ones without moving surviving reports", () => {
|
||||
const gamma = entry({ sourceId: "gamma" });
|
||||
const delta = entry({ sourceId: "delta" });
|
||||
expect(settleReports([alpha, beta, gamma], [delta, gamma, alpha])).toEqual([
|
||||
alpha,
|
||||
gamma,
|
||||
delta,
|
||||
]);
|
||||
});
|
||||
|
||||
it("takes the finished list as is when nothing was shown yet", () => {
|
||||
expect(settleReports(undefined, [alpha, beta])).toEqual([alpha, beta]);
|
||||
});
|
||||
|
||||
@@ -82,17 +82,24 @@ export function upsertReport(
|
||||
}
|
||||
|
||||
/**
|
||||
* The list a finished request leaves: its reports, dropping any the host no longer has, except
|
||||
* that a copy on screen fetched after the request's copy stays.
|
||||
* Keep displayed reports in place: the finished list is in fetch-completion order, which can
|
||||
* change on every refresh. Drop missing reports, append new ones, and keep newer fetched copies.
|
||||
*/
|
||||
export function settleReports(
|
||||
shown: readonly UsageReportEntry[] | undefined,
|
||||
finished: readonly UsageReportEntry[],
|
||||
): UsageReportEntry[] {
|
||||
return finished.map((report) => {
|
||||
const copy = shown?.find((entry) => entry.id === report.id);
|
||||
return copy ? laterFetched(copy, report) : report;
|
||||
});
|
||||
const remaining = new Map(finished.map((report) => [report.id, report]));
|
||||
const settled: UsageReportEntry[] = [];
|
||||
for (const report of shown ?? []) {
|
||||
const arriving = remaining.get(report.id);
|
||||
if (!arriving) {
|
||||
continue;
|
||||
}
|
||||
settled.push(laterFetched(report, arriving));
|
||||
remaining.delete(report.id);
|
||||
}
|
||||
return [...settled, ...remaining.values()];
|
||||
}
|
||||
|
||||
export interface UsageQueryState {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { clickNewChat, gotoWorkspace } from "../../app/e2e/support/helpers/launcher";
|
||||
import { clickSettingsBackToWorkspace } from "../../app/e2e/support/helpers/settings";
|
||||
import type { Page } from "@playwright/test";
|
||||
import { test, expect } from "../../app/e2e/support/fixtures";
|
||||
import { gotoAppShell, openSettings } from "../../app/e2e/support/helpers/app";
|
||||
@@ -213,3 +215,49 @@ for (const { platform, keys, label, firstCombo, secondCombo } of [
|
||||
await expectInterruptShortcut(page, label);
|
||||
});
|
||||
}
|
||||
|
||||
async function rebindTabNumbers(page: Page) {
|
||||
await captureShortcut(page, "Jump to tab", "workspace-tab-jump-index", "Control+1");
|
||||
await page.getByRole("button", { name: "Done", exact: true }).click();
|
||||
}
|
||||
|
||||
async function expectTabNumberRange(page: Page) {
|
||||
const row = page.getByText("Jump to tab", { exact: true }).locator("..");
|
||||
await expect(row.getByText("⌃1-9", { exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
async function openTwoDraftTabs(page: Page, workspaceId: string) {
|
||||
await installDesktopBridge(page);
|
||||
await gotoWorkspace(page, workspaceId);
|
||||
await clickNewChat(page);
|
||||
await clickNewChat(page);
|
||||
await expect(
|
||||
page.locator('[data-testid^="workspace-tab-draft_"]').filter({ visible: true }),
|
||||
).toHaveCount(2);
|
||||
await openSettings(page);
|
||||
await openSettingsSection(page, "shortcuts");
|
||||
}
|
||||
|
||||
async function expectTabNumberNavigation(page: Page) {
|
||||
const tabs = page.locator('[data-testid^="workspace-tab-draft_"]').filter({ visible: true });
|
||||
await page.keyboard.press("Control+1");
|
||||
await expect(tabs.nth(0)).toHaveAttribute("aria-selected", "true");
|
||||
await page.keyboard.press("Control+2");
|
||||
await expect(tabs.nth(1)).toHaveAttribute("aria-selected", "true");
|
||||
}
|
||||
|
||||
test("rebinding Jump to tab preserves the number group after reload", async ({
|
||||
page,
|
||||
withWorkspace,
|
||||
}) => {
|
||||
const workspace = await withWorkspace({ prefix: "tab-number-rebind-" });
|
||||
await openTwoDraftTabs(page, workspace.workspaceId);
|
||||
await rebindTabNumbers(page);
|
||||
await clickSettingsBackToWorkspace(page);
|
||||
await expectTabNumberNavigation(page);
|
||||
await page.reload();
|
||||
await expectTabNumberNavigation(page);
|
||||
await openSettings(page);
|
||||
await openSettingsSection(page, "shortcuts");
|
||||
await expectTabNumberRange(page);
|
||||
});
|
||||
|
||||
@@ -127,7 +127,7 @@ function inspectChatDragExclusions(scroll: Element) {
|
||||
const headerRect = header.getBoundingClientRect();
|
||||
const headerY = headerRect.top + headerRect.height / 2;
|
||||
const content = scroll.firstElementChild;
|
||||
const focusScope = scroll.closest("[tabindex]");
|
||||
const focusScope = scroll.closest("[data-window-content]")?.parentElement?.closest("[tabindex]");
|
||||
if (!content || !focusScope) throw new Error("Expected chat content and its focus scope");
|
||||
const contentRect = content.getBoundingClientRect();
|
||||
const chatX = (contentRect.left + contentRect.right) / 2;
|
||||
|
||||
@@ -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,
|
||||
@@ -545,8 +547,13 @@ class AcpRuntime {
|
||||
return sessionCapabilities;
|
||||
}
|
||||
|
||||
async discover(cwd = process.cwd()): Promise<ProviderCatalog> {
|
||||
const response = await this.call(this.connection.newSession({ cwd, mcpServers: [] }));
|
||||
async discover(cwd?: string): Promise<ProviderCatalog> {
|
||||
if (cwd === undefined && this.options.options.acpOptions?.workspaceOnlyCatalog) {
|
||||
return { models: [], modes: [] };
|
||||
}
|
||||
const response = await this.call(
|
||||
this.connection.newSession({ cwd: cwd ?? process.cwd(), mcpServers: [] }),
|
||||
);
|
||||
this.nativeSessionId = response.sessionId;
|
||||
this.modes = response.modes;
|
||||
this.configOptions = response.configOptions ?? [];
|
||||
@@ -595,10 +602,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 +620,8 @@ class AcpRuntime {
|
||||
});
|
||||
return undefined;
|
||||
},
|
||||
(error): void => {
|
||||
async (error): Promise<void> => {
|
||||
await this.drainNotifications();
|
||||
this.fallbackChunkIds.clear();
|
||||
this.terminalizeTransientItems("failed");
|
||||
this.emit({
|
||||
@@ -1027,9 +1038,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 +1095,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 +1406,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 +1436,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);
|
||||
}
|
||||
|
||||
@@ -272,6 +272,39 @@ lines.on("line", (line) => {
|
||||
}
|
||||
});
|
||||
|
||||
it("still reports initialization failures for workspace-only global discovery", async () => {
|
||||
let unavailable = false;
|
||||
const { connector } = connectorHarness({
|
||||
handleRequest(instance, request) {
|
||||
if (unavailable && request.method === "initialize") {
|
||||
instance.reject(request, "Bridge unavailable");
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
});
|
||||
const registration = runAcpProvider({
|
||||
id: "workspace-acp",
|
||||
label: "Workspace ACP",
|
||||
connector,
|
||||
acpOptions: { workspaceOnlyCatalog: true },
|
||||
});
|
||||
const connection = await registration.connect({ versions: [1], capabilities: [] });
|
||||
const events: ProviderEvent[] = [];
|
||||
connection.onEvent((event) => events.push(event));
|
||||
try {
|
||||
unavailable = true;
|
||||
await connection.send({ type: "catalog", requestId: "global" });
|
||||
expect(await waitForEvent(events, (event) => event.type === "request.failed")).toMatchObject({
|
||||
requestId: "global",
|
||||
error: { message: expect.stringContaining("Bridge unavailable") },
|
||||
});
|
||||
expect(events.some((event) => event.type === "catalog")).toBe(false);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects connection cleanly when the ACP executable does not exist", async () => {
|
||||
const registration = runAcpProvider({
|
||||
id: "missing-acp",
|
||||
@@ -619,6 +652,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 = [
|
||||
|
||||
@@ -44,6 +44,8 @@ export type AcpConnector = () => AcpStream | Promise<AcpStream>;
|
||||
export interface AcpOptions {
|
||||
protocol?: "auto" | "v1";
|
||||
startupTimeoutMs?: number;
|
||||
/** Global discovery initializes ACP but returns an empty catalog without opening a session. */
|
||||
workspaceOnlyCatalog?: boolean;
|
||||
waitForInitialCommands?: boolean;
|
||||
initialCommandsTimeoutMs?: number;
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -89,7 +89,7 @@
|
||||
"speech:transcribe:local": "tsx scripts/transcribe-local-wav.ts",
|
||||
"test": "npm run test:unit && npm run test:integration",
|
||||
"test:unit": "vitest run --fileParallelism --exclude \"**/*.e2e.test.ts\"",
|
||||
"test:integration": "vitest run --maxWorkers=1 src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts && vitest run --maxWorkers=1 src/server/daemon-e2e/git-operations.e2e.test.ts -t \"merges into\" && vitest run --maxWorkers=1 src/server/session.create-agent-worktree-autoarchive.e2e.test.ts -t \"creates a worktree and auto-archives both\" && vitest run --maxWorkers=1 src/server/agent/providers/opencode-bridge.local.e2e.test.ts -t \"versioned runtime\" && vitest run --maxWorkers=1 src/server/daemon-e2e/relay-transport.e2e.test.ts -t \"oversized attachments\"",
|
||||
"test:integration": "vitest run --maxWorkers=1 src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts && vitest run --maxWorkers=1 src/server/daemon-e2e/git-operations.e2e.test.ts -t \"merges into\" && vitest run --maxWorkers=1 src/server/session.create-agent-worktree-autoarchive.e2e.test.ts -t \"creates a worktree and auto-archives both\" && vitest run --maxWorkers=1 src/server/agent/providers/opencode-bridge.local.e2e.test.ts -t \"versioned runtime\" && vitest run --maxWorkers=1 src/server/daemon-e2e/relay-transport.e2e.test.ts -t \"oversized attachments\"",
|
||||
"test:hub-cli-contract": "vitest run --maxWorkers=1 src/server/hub/hub-cli-contract.test.ts",
|
||||
"test:integration:all": "npm run test:e2e",
|
||||
"test:integration:real": "vitest run real.e2e.test.ts",
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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. */
|
||||
|
||||
+48
@@ -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,44 @@
|
||||
// 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" && request.params.cwd !== process.env.HOPLITE_TEST_CWD) {
|
||||
send({
|
||||
id: request.id,
|
||||
error: { code: -32602, message: "No Hoplite project for this directory" },
|
||||
});
|
||||
return;
|
||||
}
|
||||
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,133 @@ 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, HOPLITE_TEST_CWD: root },
|
||||
},
|
||||
},
|
||||
});
|
||||
const globalModels = await client.listProviderModels("hoplite");
|
||||
expect(globalModels.error).toBeNull();
|
||||
expect(globalModels.models).toEqual([]);
|
||||
await expect
|
||||
.poll(
|
||||
async () =>
|
||||
(await client.getProvidersSnapshot()).entries.find(
|
||||
(entry) => entry.provider === "hoplite",
|
||||
)?.status,
|
||||
)
|
||||
.toBe("ready");
|
||||
const workspaceModels = await client.listProviderModels("hoplite", { cwd: root });
|
||||
expect(workspaceModels.error).toBeNull();
|
||||
expect(workspaceModels.models.map((model) => model.id)).toEqual(["fixture-model"]);
|
||||
await client.refreshProvidersSnapshot({ providers: ["hoplite"] });
|
||||
expect((await client.listProviderModels("hoplite")).models).toEqual([]);
|
||||
expect(
|
||||
(await client.listProviderModels("hoplite", { cwd: root })).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.
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { existsSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { expect, onTestFinished, test } from "vitest";
|
||||
@@ -18,6 +19,7 @@ function createGitRepoWithBranch(): { repoDir: string; tempRoot: string } {
|
||||
const tempRoot = mkdtempSync(path.join(tmpdir(), "workspace-create-worktree-source-"));
|
||||
const repoDir = path.join(tempRoot, "repo");
|
||||
execFileSync("git", ["init", "-b", "main", repoDir], { stdio: "pipe" });
|
||||
execFileSync("git", ["config", "core.autocrlf", "false"], { cwd: repoDir, stdio: "pipe" });
|
||||
execFileSync("git", ["config", "user.email", "test@getpaseo.local"], {
|
||||
cwd: repoDir,
|
||||
stdio: "pipe",
|
||||
@@ -60,10 +62,134 @@ test("workspace.create worktree source forwards action=checkout + refName into t
|
||||
} finally {
|
||||
await client.close().catch(() => undefined);
|
||||
await daemon.close();
|
||||
rmSync(tempRoot, { recursive: true, force: true });
|
||||
await rm(tempRoot, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
||||
}
|
||||
}, 180000);
|
||||
|
||||
test.each([false, true])(
|
||||
"workspace.create opens worktree.terminals (setup service: %s)",
|
||||
async (withSetupService) => {
|
||||
const daemon = await createTestPaseoDaemon();
|
||||
const { repoDir, tempRoot } = createGitRepoWithBranch();
|
||||
writeFileSync(
|
||||
path.join(repoDir, "paseo.json"),
|
||||
JSON.stringify({
|
||||
worktree: {
|
||||
...(withSetupService
|
||||
? {
|
||||
// Launch the Windows service asynchronously so it outlives
|
||||
// the setup command instead of holding setup open.
|
||||
setup:
|
||||
process.platform === "win32"
|
||||
? "Start-Process -FilePath node -ArgumentList 'setup.cjs','serve' -WorkingDirectory (Get-Location).Path -WindowStyle Hidden; while (!(Test-Path setup-pid.txt)) { Start-Sleep -Milliseconds 25 }"
|
||||
: "node setup.cjs",
|
||||
}
|
||||
: {}),
|
||||
terminals: [
|
||||
{ name: "preview", command: "echo paseo-auto-terminal >> terminal-marker.txt" },
|
||||
],
|
||||
},
|
||||
}),
|
||||
);
|
||||
writeFileSync(
|
||||
path.join(repoDir, "setup.cjs"),
|
||||
`
|
||||
const fs = require("node:fs");
|
||||
if (process.argv[2] === "serve") {
|
||||
require("node:net").createServer().listen(Number(process.env.PASEO_WORKTREE_PORT), "127.0.0.1", () => {
|
||||
fs.writeFileSync("setup-pid.txt", String(process.pid));
|
||||
process.send?.("ready");
|
||||
});
|
||||
} else {
|
||||
const child = require("node:child_process").spawn(process.execPath, [__filename, "serve"], {
|
||||
detached: true,
|
||||
stdio: ["ignore", "ignore", "ignore", "ipc"],
|
||||
});
|
||||
child.once("message", () => { child.disconnect(); child.unref(); });
|
||||
}
|
||||
`,
|
||||
);
|
||||
execFileSync("git", ["add", "paseo.json", "setup.cjs"], { cwd: repoDir, stdio: "pipe" });
|
||||
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "add paseo.json"], {
|
||||
cwd: repoDir,
|
||||
stdio: "pipe",
|
||||
});
|
||||
const client = new DaemonClient({
|
||||
url: `ws://127.0.0.1:${daemon.port}/ws`,
|
||||
appVersion: "0.1.82",
|
||||
});
|
||||
|
||||
let workspaceCwd: string | undefined;
|
||||
try {
|
||||
await client.connect();
|
||||
|
||||
// This is the request the New Workspace screen sends: the workspace is
|
||||
// created on its own, with no agent in the same request.
|
||||
const result = await client.createWorkspace({
|
||||
source: {
|
||||
kind: "worktree",
|
||||
cwd: repoDir,
|
||||
action: "branch-off",
|
||||
branchName: "feature/auto-terminals",
|
||||
worktreeSlug: "feature-auto-terminals",
|
||||
baseBranch: "main",
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.error).toBeNull();
|
||||
const workspace = result.workspace;
|
||||
if (!workspace) {
|
||||
throw new Error("Expected a created workspace");
|
||||
}
|
||||
|
||||
workspaceCwd = workspace.workspaceDirectory;
|
||||
if (withSetupService) {
|
||||
await expect
|
||||
.poll(() => existsSync(path.join(workspaceCwd!, "setup-pid.txt")), { timeout: 30000 })
|
||||
.toBe(true);
|
||||
}
|
||||
await expect
|
||||
.poll(async () => (await client.fetchWorkspaceSetupStatus(workspace.id)).snapshot, {
|
||||
timeout: 30000,
|
||||
})
|
||||
.toMatchObject({ status: "completed", error: null });
|
||||
await expect
|
||||
.poll(
|
||||
async () =>
|
||||
(
|
||||
await client.listTerminals(workspace.workspaceDirectory, undefined, {
|
||||
workspaceId: workspace.id,
|
||||
})
|
||||
).terminals.map((terminal) => terminal.name),
|
||||
{ timeout: 30000 },
|
||||
)
|
||||
.toContain("preview");
|
||||
await expect
|
||||
.poll(
|
||||
() => {
|
||||
const marker = path.join(workspaceCwd!, "terminal-marker.txt");
|
||||
return existsSync(marker) ? readFileSync(marker, "utf8").trim() : null;
|
||||
},
|
||||
{ timeout: 10000 },
|
||||
)
|
||||
.toBe("paseo-auto-terminal");
|
||||
expect(
|
||||
(await client.listTerminals(workspaceCwd, undefined, { workspaceId: workspace.id }))
|
||||
.terminals,
|
||||
).toHaveLength(1);
|
||||
} finally {
|
||||
const pidFile = workspaceCwd && path.join(workspaceCwd, "setup-pid.txt");
|
||||
if (pidFile && existsSync(pidFile)) {
|
||||
process.kill(Number(readFileSync(pidFile, "utf8")));
|
||||
}
|
||||
await client.close().catch(() => undefined);
|
||||
await daemon.close();
|
||||
await rm(tempRoot, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
||||
}
|
||||
},
|
||||
180000,
|
||||
);
|
||||
|
||||
test("existing branch changes remain visible after archive and restore", async () => {
|
||||
const daemon = await createTestPaseoDaemon();
|
||||
const { repoDir, tempRoot } = createGitRepoWithBranch();
|
||||
@@ -74,7 +200,7 @@ test("existing branch changes remain visible after archive and restore", async (
|
||||
onTestFinished(async () => {
|
||||
await client.close().catch(() => undefined);
|
||||
await daemon.close();
|
||||
rmSync(tempRoot, { recursive: true, force: true });
|
||||
await rm(tempRoot, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
||||
});
|
||||
runGit(repoDir, "switch", "feature/existing-branch");
|
||||
commitFile(repoDir, "feature.txt", "feature change\n");
|
||||
@@ -134,7 +260,7 @@ test("workspace.create keeps a branch-off name separate from its worktree slug",
|
||||
} finally {
|
||||
await client.close().catch(() => undefined);
|
||||
await daemon.close();
|
||||
rmSync(tempRoot, { recursive: true, force: true });
|
||||
await rm(tempRoot, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
||||
}
|
||||
}, 180000);
|
||||
|
||||
@@ -168,7 +294,7 @@ test("workspace.create accepts a Git-valid branch-off name outside Paseo slug sy
|
||||
} finally {
|
||||
await client.close().catch(() => undefined);
|
||||
await daemon.close();
|
||||
rmSync(tempRoot, { recursive: true, force: true });
|
||||
await rm(tempRoot, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
||||
}
|
||||
}, 180000);
|
||||
|
||||
@@ -210,7 +336,7 @@ test("workspace.create always creates a new worktree when the slug is already oc
|
||||
} finally {
|
||||
await client.close().catch(() => undefined);
|
||||
await daemon.close();
|
||||
rmSync(tempRoot, { recursive: true, force: true });
|
||||
await rm(tempRoot, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
||||
}
|
||||
}, 180000);
|
||||
|
||||
@@ -255,7 +381,7 @@ test("workspace.create suffixes past an occupied detached worktree", async () =>
|
||||
} finally {
|
||||
await client.close().catch(() => undefined);
|
||||
await daemon.close();
|
||||
rmSync(tempRoot, { recursive: true, force: true });
|
||||
await rm(tempRoot, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
||||
}
|
||||
}, 180000);
|
||||
|
||||
@@ -297,7 +423,7 @@ test("workspace.create suffixes an occupied checkout branch", async () => {
|
||||
} finally {
|
||||
await client.close().catch(() => undefined);
|
||||
await daemon.close();
|
||||
rmSync(tempRoot, { recursive: true, force: true });
|
||||
await rm(tempRoot, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
||||
}
|
||||
}, 180000);
|
||||
|
||||
@@ -340,7 +466,7 @@ async function createRestorableWorkspace(baseRef: string) {
|
||||
onTestFinished(async () => {
|
||||
await client.close().catch(() => undefined);
|
||||
await daemon.close();
|
||||
rmSync(tempRoot, { recursive: true, force: true });
|
||||
await rm(tempRoot, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
||||
});
|
||||
createDivergentBases(repoDir);
|
||||
await client.connect();
|
||||
|
||||
@@ -593,13 +593,10 @@ export async function runWorktreeAutoTerminals(options: {
|
||||
workspaceId: string;
|
||||
worktree: WorktreeConfig;
|
||||
workspaceCwd: string;
|
||||
runtimeEnv: WorktreeRuntimeEnv;
|
||||
terminalManager: TerminalManager | null;
|
||||
logger?: Logger;
|
||||
}): Promise<void> {
|
||||
const runtimeEnv = await resolveWorktreeRuntimeEnv({
|
||||
worktreePath: options.worktree.worktreePath,
|
||||
branchName: options.worktree.branchName,
|
||||
});
|
||||
await runWorktreeTerminalBootstrap(
|
||||
{
|
||||
agentId: options.workspaceId,
|
||||
@@ -610,7 +607,7 @@ export async function runWorktreeAutoTerminals(options: {
|
||||
appendTimelineItem: async () => true,
|
||||
logger: options.logger,
|
||||
},
|
||||
runtimeEnv,
|
||||
options.runtimeEnv,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -817,7 +817,6 @@ export async function handleWorkspaceSetupRunRequest(
|
||||
slug: basename(worktree.worktreePath),
|
||||
worktreePath: worktree.worktreePath,
|
||||
workspaceCwd: workspace.cwd,
|
||||
runAutoTerminals: true,
|
||||
},
|
||||
signal,
|
||||
),
|
||||
@@ -857,7 +856,6 @@ export async function runWorktreeSetupInBackground(
|
||||
slug: string;
|
||||
worktreePath: string;
|
||||
workspaceCwd?: string;
|
||||
runAutoTerminals?: boolean;
|
||||
},
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> {
|
||||
@@ -898,18 +896,18 @@ export async function runWorktreeSetupInBackground(
|
||||
} else {
|
||||
const workspaceCwd = options.workspaceCwd ?? worktree.worktreePath;
|
||||
const setupCommands = getWorktreeSetupCommands(workspaceCwd);
|
||||
const runtimeEnv = await resolveWorktreeRuntimeEnv({
|
||||
worktreePath: worktree.worktreePath,
|
||||
branchName: worktree.branchName,
|
||||
repoRootPath: options.repoRoot,
|
||||
});
|
||||
dependencies.terminalManager?.registerCwdEnv({
|
||||
cwd: workspaceCwd,
|
||||
env: runtimeEnv,
|
||||
});
|
||||
if (setupCommands.length === 0) {
|
||||
emitSetupProgress("completed", null);
|
||||
} else {
|
||||
const runtimeEnv = await resolveWorktreeRuntimeEnv({
|
||||
worktreePath: worktree.worktreePath,
|
||||
branchName: worktree.branchName,
|
||||
repoRootPath: options.repoRoot,
|
||||
});
|
||||
dependencies.terminalManager?.registerCwdEnv({
|
||||
cwd: workspaceCwd,
|
||||
env: runtimeEnv,
|
||||
});
|
||||
setupResults = await runWorktreeSetupCommands({
|
||||
worktreePath: workspaceCwd,
|
||||
branchName: worktree.branchName,
|
||||
@@ -924,15 +922,14 @@ export async function runWorktreeSetupInBackground(
|
||||
});
|
||||
emitSetupProgress("completed", null);
|
||||
}
|
||||
if (options.runAutoTerminals) {
|
||||
await runWorktreeAutoTerminals({
|
||||
workspaceId,
|
||||
worktree,
|
||||
workspaceCwd,
|
||||
terminalManager: dependencies.terminalManager,
|
||||
logger: dependencies.sessionLogger,
|
||||
});
|
||||
}
|
||||
await runWorktreeAutoTerminals({
|
||||
workspaceId,
|
||||
worktree,
|
||||
workspaceCwd,
|
||||
runtimeEnv,
|
||||
terminalManager: dependencies.terminalManager,
|
||||
logger: dependencies.sessionLogger,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof WorktreeSetupError) {
|
||||
|
||||
@@ -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/**"],
|
||||
},
|
||||
});
|
||||
|
||||
@@ -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 |
@@ -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,18 @@
|
||||
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"],
|
||||
acpOptions: { workspaceOnlyCatalog: true },
|
||||
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();
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user