diff --git a/CHANGELOG.md b/CHANGELOG.md index 0e2b24ac5c..cbd1d0551d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/README.md b/README.md index 91310cd7c7..1f6df3c3e4 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,7 @@ Paseo is an open source agentic development environment for desktop, mobile, web - + diff --git a/docs/agent-stream-performance.md b/docs/agent-stream-performance.md index c7aac17f81..ec506ee99b 100644 --- a/docs/agent-stream-performance.md +++ b/docs/agent-stream-performance.md @@ -43,6 +43,10 @@ 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. ## Native parsing cost @@ -55,6 +59,7 @@ Completion restores one native text view per Mermaid-delimited segment, so selec - **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: diff --git a/docs/android.md b/docs/android.md index f04ce945bb..75908a8ae2 100644 --- a/docs/android.md +++ b/docs/android.md @@ -124,7 +124,9 @@ This is the Android counterpart of the iOS local-simulator flow in [development. Android focus and selection visibility requests must not reposition inverted timelines. The `modules/paseo-scroll` package keeps React Native's scroll manager interface and returns zero for -child-reveal scroll calculations when the vertical scale is inverted. Dragging and explicit scroll +child-reveal scroll calculations when the view's transform matrix inverts the vertical axis. React +Native's Android list uses `scale: -1`, which decomposes into a 180-degree rotation with positive +`scaleY`; checking the scale property alone misses it. Dragging and explicit scroll commands still work; non-inverted scroll views keep Android's default behavior. Register this package before React Native's core package through its Expo config plugin. Normal diff --git a/docs/custom-providers.md b/docs/custom-providers.md index efc5fdf24f..a6c6cefbdc 100644 --- a/docs/custom-providers.md +++ b/docs/custom-providers.md @@ -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 diff --git a/docs/data-model.md b/docs/data-model.md index 25a214b11c..1b578bb6d8 100644 --- a/docs/data-model.md +++ b/docs/data-model.md @@ -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 diff --git a/docs/floating-panels.md b/docs/floating-panels.md index 1af71ac4c9..c183dc6615 100644 --- a/docs/floating-panels.md +++ b/docs/floating-panels.md @@ -204,10 +204,11 @@ still-mounted content, paints its own surface under the safe areas, and turns the surface translation off. The composer's single tree keeps the editing surface at the same position in both modes, so the mounted editor, its native buffer, selection, and focus survive the toggle and Send's clear always reaches -the live input. The one remount left is a viewport crossing the compact -breakpoint: the app shell swaps its gesture wrapper and the workspace screen +the live input. A viewport crossing the compact breakpoint still remounts it: +the app shell swaps its gesture wrapper and the workspace screen mounts tabs in different trees, so every screen below remounts. The draft owner -restores the text and the editing session restores the caret and focus intent. +restores the text and the editing session restores the caret. Focus restoration +is limited to mouse-driven UIs, using the same fine-pointer policy as autofocus. New workspace keys its sessions by draft in the app-level store for the same reason. The centered form honors fullscreen by style alone: no centering, no translation, setup fields hidden, slot filling the stationary viewport. The @@ -217,14 +218,12 @@ sheet suspends pane focus, and the composer gives up input from the moment the user asks for the compact agent list or explorer, before the panel's motion settles. Pane focus itself stays put under those panels: the agent panel reads it as "the user is in this chat" for attention clearing, and opening the agent -list must not clear the attention it shows. Focus restoration follows pane -focus, not the active composer. The editor keeps its focus intent only across -a blur that lands while its pane is not the user's (a retained tab hidden, a -sheet over it) and refocuses when the pane comes back. A blur while the pane is -theirs drops the intent in every layout mode, and the keyboard the compact -panels dismiss when they settle is such a blur, so closing the agent list or -explorer never reopens the keyboard. Keying restoration on the active composer -made that dismiss look like a hidden-tab blur and refocused on close. +list must not clear the attention it shows. On mouse-driven UIs, focus restoration +follows pane focus, not the active composer. Keying it on the active composer +made sidebar dismissal look like a hidden-tab blur and refocused on close. +Native and touch-web navigation must not replay old editor focus, including +when blur arrives after pane deactivation or the editor unmounts before blur. +Fullscreen toggles keep the editor mounted and need no focus restoration. The band beside the inline editor where the fullscreen glyph sits is the input's own right padding, so a tap anywhere in it focuses the editor whether or not the glyph shows. On web the slot is a fixed box over the visible viewport, which is diff --git a/docs/plugins.md b/docs/plugins.md index 866c74128e..4e1985ea81 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -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, diff --git a/packages/app/e2e/browser/acp-provider-catalog.spec.ts b/packages/app/e2e/browser/acp-provider-catalog.spec.ts index a0d94e5c02..ceca7489e3 100644 --- a/packages/app/e2e/browser/acp-provider-catalog.spec.ts +++ b/packages/app/e2e/browser/acp-provider-catalog.spec.ts @@ -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; close(): Promise; + getDaemonConfig(): Promise<{ config: { providers?: Record } }>; + getProvidersSnapshot(): Promise<{ entries: Array<{ provider: string }> }>; patchDaemonConfig(config: { removeProviders?: string[] }): Promise; } @@ -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({ + 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 { + 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({ + 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({ + 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(); + } +}); diff --git a/packages/app/e2e/browser/add-project-flow.spec.ts b/packages/app/e2e/browser/add-project-flow.spec.ts index 9fd7f9413d..f66b963d5f 100644 --- a/packages/app/e2e/browser/add-project-flow.spec.ts +++ b/packages/app/e2e/browser/add-project-flow.spec.ts @@ -1,6 +1,6 @@ import { randomUUID } from "node:crypto"; -import { mkdtemp, rm, stat } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { mkdir, mkdtemp, rm, stat } from "node:fs/promises"; +import { homedir, tmpdir } from "node:os"; import path from "node:path"; import { test, expect } from "../support/fixtures"; import { @@ -12,12 +12,15 @@ import { chooseAddProjectMethod, expectAddProjectPage, expectNewWorkspaceForAddedProject, + expectAddProjectResultVisible, + navigateAddProjectResults, openAddProjectFlow, openAddProjectHostSelection, } from "../support/helpers/add-project-flow"; import { gotoAppShell } from "../support/helpers/app"; import { addConnectedHostAndReload, + addConnectedHostsAndReload, addOfflineHostAndReload, waitForConnectedHost, } from "../support/helpers/hosts"; @@ -214,6 +217,60 @@ test.describe("Add Project command-center flow", () => { }); }); + test("filtered hosts keep the keyboard-selected row visible", async ({ page }) => { + const hosts: IsolatedHostDaemon[] = []; + try { + for (let index = 1; index <= 3; index += 1) { + hosts.push(await startIsolatedHostDaemon(`scroll-host-${index}`)); + } + await page.setViewportSize({ width: 1280, height: 360 }); + await gotoAppShell(page); + await addConnectedHostsAndReload( + page, + hosts.map((host, index) => ({ + serverId: host.serverId, + port: host.port, + label: index < 2 ? `Fleet 0${index + 1}` : "Other host", + })), + { primaryLabel: "Fleet 00" }, + ); + for (const host of hosts) { + await waitForConnectedHost(page, { + serverId: host.serverId, + endpoint: `localhost:${host.port}`, + }); + } + await openAddProjectHostSelection(page); + await expect( + addProjectFlow(page).getByRole("button").filter({ hasText: "Other host" }), + ).toBeVisible(); + + await addProjectFlowInput(page).fill("Fleet"); + await expect(addProjectFlowHost(page, hosts[2]!.serverId)).toHaveCount(0); + await navigateAddProjectResults(page, "ArrowDown", 2); + await expectAddProjectResultVisible(page, "Fleet 02"); + + // Filtering out the first host moves retained rows to new positions. + await addProjectFlowInput(page).fill("scroll-host"); + await expect(addProjectFlowHost(page, getServerId())).toHaveCount(0); + await expectAddProjectResultVisible(page, "Fleet 01"); + await navigateAddProjectResults(page, "ArrowDown", 2); + await expectAddProjectResultVisible(page, "Other host"); + await navigateAddProjectResults(page, "ArrowDown", 1); + await expectAddProjectResultVisible(page, "Fleet 01"); + + await addProjectFlowInput(page).fill("Fleet"); + await expectAddProjectResultVisible(page, "Fleet 00"); + await navigateAddProjectResults(page, "ArrowDown", 2); + await expectAddProjectResultVisible(page, "Fleet 02"); + await page.keyboard.press("Enter"); + await expectAddProjectPage(page, "method"); + await expect(addProjectFlow(page)).toContainText("Fleet 02"); + } finally { + await Promise.all(hosts.map((host) => host.close())); + } + }); + test("keyboard directory search adds the selected Project", async ({ page, projectPickerFixture, @@ -241,6 +298,59 @@ test.describe("Add Project command-center flow", () => { await expectProjectHasNoWorkspaces(projectId); }); + test("keyboard navigation keeps the selected row inside the visible results", async ({ + page, + }) => { + const parentDirectory = await mkdtemp(path.join(homedir(), "paseo-e2e-scroll-")); + const rowPath = (index: number) => + path.join(parentDirectory, `scroll-probe-${String(index).padStart(2, "0")}`); + let projectId: string | null = null; + try { + await Promise.all(Array.from({ length: 16 }, (_, index) => mkdir(rowPath(index)))); + await gotoAppShell(page); + await openAddProjectFlow(page); + await chooseAddProjectMethod(page, "directory-search"); + await addProjectFlowInput(page).fill(path.basename(parentDirectory)); + const results = page.getByTestId("add-project-flow-results"); + await expect(results.getByRole("button", { name: /scroll-probe-/ })).toHaveCount(16, { + timeout: 30_000, + }); + + await navigateAddProjectResults(page, "ArrowDown", 12); + await expectAddProjectResultVisible(page, rowPath(11)); + await navigateAddProjectResults(page, "ArrowUp", 12); + await expectAddProjectResultVisible(page, parentDirectory); + await navigateAddProjectResults(page, "ArrowUp", 1); + await expectAddProjectResultVisible(page, rowPath(15)); + await navigateAddProjectResults(page, "ArrowDown", 1); + await expectAddProjectResultVisible(page, parentDirectory); + + await navigateAddProjectResults(page, "ArrowDown", 12); + await expectAddProjectResultVisible(page, rowPath(11)); + await addProjectFlowInput(page).fill(`${path.basename(parentDirectory)}probe`); + await expect(results.getByRole("button")).toHaveCount(16); + await expectAddProjectResultVisible(page, rowPath(0)); + await navigateAddProjectResults(page, "ArrowDown", 12); + await expectAddProjectResultVisible(page, rowPath(12)); + await addProjectFlowInput(page).fill(path.basename(parentDirectory)); + await expect(results.getByRole("button")).toHaveCount(17); + await expectAddProjectResultVisible(page, parentDirectory); + await navigateAddProjectResults(page, "ArrowDown", 12); + await expectAddProjectResultVisible(page, rowPath(11)); + await page.keyboard.press("Enter"); + projectId = await expectOpenedProject(page, "scroll-probe-11"); + await expectNewWorkspaceForAddedProject(page, { + serverId: getServerId(), + projectId, + projectName: "scroll-probe-11", + projectPath: rowPath(11), + }); + } finally { + if (projectId) await removeCreatedProject(rowPath(11), projectId); + await rm(parentDirectory, { recursive: true, force: true }); + } + }); + test("a complete repository URL remains selectable without a GitHub search result", async ({ page, }) => { diff --git a/packages/app/e2e/browser/agent-stream-smoothness.spec.ts b/packages/app/e2e/browser/agent-stream-smoothness.spec.ts index 74069d3561..0146582755 100644 --- a/packages/app/e2e/browser/agent-stream-smoothness.spec.ts +++ b/packages/app/e2e/browser/agent-stream-smoothness.spec.ts @@ -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( diff --git a/packages/app/e2e/browser/agent-timeline-scroll-smoothness.spec.ts b/packages/app/e2e/browser/agent-timeline-scroll-smoothness.spec.ts index d5dd99e43f..04286b85d3 100644 --- a/packages/app/e2e/browser/agent-timeline-scroll-smoothness.spec.ts +++ b/packages/app/e2e/browser/agent-timeline-scroll-smoothness.spec.ts @@ -135,6 +135,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, diff --git a/packages/app/e2e/browser/bottom-sheet-reopen.spec.ts b/packages/app/e2e/browser/bottom-sheet-reopen.spec.ts index 89ee10af22..bc65ae65de 100644 --- a/packages/app/e2e/browser/bottom-sheet-reopen.spec.ts +++ b/packages/app/e2e/browser/bottom-sheet-reopen.spec.ts @@ -89,9 +89,11 @@ async function dismissStackedModelPickerWithBackdrop(page: Page) { .getByTestId("agent-controls-settings-list") .getByRole("button", { name: /Select model/ }) .click(); - await expect(page.getByTestId("agent-controls-model-browser-sheet")).toBeVisible(); + await expect(page.getByTestId("agent-controls-model-browser-sheet")).toBeInViewport(); await page.mouse.click(MOBILE_VIEWPORT.width / 2, 24); - await expect(page.getByTestId("agent-controls-model-browser-sheet")).not.toBeVisible(); + // In CI, Gorhom retains the dismissed sheet below the viewport. + // Dismissal is complete when it leaves the displayed surface. + await expect(page.getByTestId("agent-controls-model-browser-sheet")).not.toBeInViewport(); await expect(page.getByTestId("agent-controls-model-sheet")).toBeVisible(); await expect(page.getByTestId("agent-controls-settings-list")).toBeVisible(); } @@ -139,7 +141,7 @@ test.describe("mobile bottom sheet reopen", () => { await expect(sheet).toBeVisible(); await expect(page.getByTestId("agent-controls-settings-list")).toBeVisible(); await expect(page.getByTestId("agent-controls-model")).toContainText("Ten second stream"); - await expect(page.getByTestId("agent-controls-model-browser-sheet")).not.toBeVisible(); + await expect(page.getByTestId("agent-controls-model-browser-sheet")).not.toBeInViewport(); }); } finally { await session.cleanup(); diff --git a/packages/app/e2e/browser/compact-workspace-header.spec.ts b/packages/app/e2e/browser/compact-workspace-header.spec.ts index c245d2ae10..be26dbb8d1 100644 --- a/packages/app/e2e/browser/compact-workspace-header.spec.ts +++ b/packages/app/e2e/browser/compact-workspace-header.spec.ts @@ -3,6 +3,18 @@ import { test, expect } from "../support/fixtures"; import { seedWorkspace } from "../support/helpers/seed-client"; import { openAgentRoute } from "../support/helpers/mock-agent"; import { getServerId } from "../support/helpers/server-id"; +import { expectOpenTabCount } from "../support/helpers/sheet"; +import { + closeCompactWorkspaceMenu, + goBackInMenu, + menuRow, + openCompactWorkspaceMenu, + openRunningScriptPage, + openScriptsPage, + runScriptFromScriptsPage, + scriptRow, + scriptsMenuRow, +} from "../support/helpers/compact-workspace-scripts"; const labels = { long: { @@ -38,11 +50,13 @@ async function openNamedWorkspace(page: Page, names: typeof labels.long) { } async function expectHeaderContentsFit(page: Page, info: TestInfo, long: boolean) { + const menu = page.getByTestId("menu-button").filter({ visible: true }); const title = page.getByTestId("workspace-header-title"); const project = page.getByTestId("workspace-header-subtitle"); const badge = page.getByTestId(`host-badge-${getServerId()}`).filter({ visible: true }); const trigger = page.getByRole("button", { name: /Switch tabs/ }); const measure = async () => ({ + menu: await menu.boundingBox(), title: await title.boundingBox(), project: await project.boundingBox(), badge: await badge.boundingBox(), @@ -54,23 +68,21 @@ async function expectHeaderContentsFit(page: Page, info: TestInfo, long: boolean await page.screenshot({ path: info.outputPath("header.png") }); await expect(async () => { const bounds = await measure(); + expect(bounds.menu).not.toBeNull(); expect(bounds.title).not.toBeNull(); expect(bounds.project).not.toBeNull(); expect(bounds.badge).not.toBeNull(); expect(bounds.icon).not.toBeNull(); expect(bounds.trigger).not.toBeNull(); - // Approved geometry: 12px outside margin, 46px leading island, 8px title gap. - expect(bounds.title!.x).toBe(66); + // The labels sit between the menu button and the actions without overlapping either. + expect(bounds.title!.x).toBeGreaterThan(bounds.menu!.x + bounds.menu!.width); expect(bounds.project!.x).toBe(bounds.title!.x); - expect(bounds.trigger!.width).toBe(32); - expect(bounds.trigger!.height).toBe(32); - // The action frame starts 7px inside its island; preserve the 8px gap before it. - const contentRight = bounds.trigger!.x - 15; for (const box of [bounds.title!, bounds.project!, bounds.badge!, bounds.icon!]) { - expect(box.x + box.width).toBeLessThanOrEqual(contentRight + 1); + expect(box.x + box.width).toBeLessThan(bounds.trigger!.x); } expect(bounds.project!.width).toBeGreaterThan(20); - expect(bounds.icon!.width).toBe(12); + // Long labels truncate instead of squeezing the host icon. + expect(bounds.icon!.width).toBe(bounds.icon!.height); expect(bounds.badge!.x).toBeGreaterThan(bounds.project!.x + bounds.project!.width); expect(bounds.titleTruncated).toBe(long); expect(bounds.projectTruncated).toBe(long); @@ -94,3 +106,87 @@ for (const width of [320, 390]) { }); } } + +const KEEP_ALIVE = 'node -e "setInterval(() => {}, 1000)"'; +const WEB_SERVER = + "node -e \"require('http').createServer((q, r) => r.end('ok')).listen(process.env.PASEO_PORT)\""; + +async function openWorkspaceWithScripts(page: Page) { + const workspace = await seedWorkspace({ + repoPrefix: "compact-scripts-", + repo: { + paseoConfig: { + scripts: { + lint: { type: "script", command: KEEP_ALIVE }, + web: { type: "service", command: WEB_SERVER }, + }, + }, + }, + }); + try { + const agent = await workspace.client.createAgent({ + provider: "mock", + cwd: workspace.repoPath, + workspaceId: workspace.workspaceId, + title: "Scripts menu check", + modeId: "load-test", + model: "e2e-fast-stream", + }); + await openAgentRoute(page, { workspaceId: workspace.workspaceId, agentId: agent.id }); + return workspace; + } catch (error) { + await workspace.cleanup(); + throw error; + } +} + +test("compact header menu runs, shows, and stops workspace scripts", async ({ page }) => { + await page.setViewportSize({ width: 390, height: 844 }); + const workspace = await openWorkspaceWithScripts(page); + try { + await expectOpenTabCount(page, 1); + + await test.step("nothing running: the Scripts row has no value", async () => { + await openCompactWorkspaceMenu(page); + await expect(scriptsMenuRow(page)).toHaveAccessibleName("Scripts"); + await closeCompactWorkspaceMenu(page); + }); + + await test.step("a stopped script runs from the Scripts page into a terminal tab", async () => { + await runScriptFromScriptsPage(page, "lint"); + await expectOpenTabCount(page, 2); + await openCompactWorkspaceMenu(page); + await expect(scriptsMenuRow(page)).toHaveAccessibleName(/^Scripts\s*lint$/); + await closeCompactWorkspaceMenu(page); + }); + + await test.step("two running scripts are counted on the root row", async () => { + await runScriptFromScriptsPage(page, "web"); + await expectOpenTabCount(page, 3); + await openCompactWorkspaceMenu(page); + await expect(scriptsMenuRow(page)).toHaveAccessibleName(/^Scripts\s*2 running$/); + await closeCompactWorkspaceMenu(page); + }); + + await test.step("stopping a script keeps its page open in the stopped state", async () => { + await openRunningScriptPage(page, "web"); + await expect(menuRow(page, "View service")).toBeVisible(); + await menuRow(page, "Stop").click(); + await expect(menuRow(page, "Run")).toBeVisible({ timeout: 15_000 }); + await expect(menuRow(page, "Stop")).toHaveCount(0); + + await goBackInMenu(page); + await expect(scriptRow(page, "web")).toHaveAccessibleName(/^web\s*exit \d+$/); + await expect(scriptRow(page, "lint")).toHaveAccessibleName(/^lint\s*Running$/); + await closeCompactWorkspaceMenu(page); + }); + + await test.step("the root row names the one script still running", async () => { + await openScriptsPage(page); + await goBackInMenu(page); + await expect(scriptsMenuRow(page)).toHaveAccessibleName(/^Scripts\s*lint$/); + }); + } finally { + await workspace.cleanup(); + } +}); diff --git a/packages/app/e2e/browser/composer-focus.spec.ts b/packages/app/e2e/browser/composer-focus.spec.ts index cbc710a94a..c81624ff7d 100644 --- a/packages/app/e2e/browser/composer-focus.spec.ts +++ b/packages/app/e2e/browser/composer-focus.spec.ts @@ -1,7 +1,7 @@ import { expect, test, type Page } from "../support/fixtures"; import { - composerLocator, blurComposerInput, + composerLocator, enterComposerFullscreen, exitComposerFullscreen, expectComposerDraft, @@ -15,6 +15,9 @@ import { typeIntoFocusedComposer, } from "../support/helpers/composer"; import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent"; +import { createMockIdleAgent, openWorkspaceWithAgents } from "../support/helpers/archive-tab"; +import { seedWorkspace } from "../support/helpers/seed-client"; +import { switchComposerTabWithKeyboard } from "../support/helpers/composer"; import { closeMobileAgentSidebar, closeMobileExplorer, @@ -25,6 +28,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({ @@ -73,6 +170,59 @@ test.describe("touch screen wide enough for the desktop layout", () => { // composer there raises the on-screen keyboard over the conversation. test.use({ viewport: { width: 1024, height: 768 }, isMobile: true, hasTouch: true }); + test("remounting an inline composer does not restore focus on touch", async ({ page }) => { + const agent = await seedMockAgentWorkspace({ + repoPrefix: "composer-touch-remount-", + title: "Touch remount", + }); + try { + await openAgentRoute(page, agent); + await composerLocator(page).fill("Keep this draft through resize"); + await expectComposerFocused(page); + await resizeComposerViewport(page, "portrait"); + await expectComposerDraft(page, "Keep this draft through resize"); + await expectComposerNotFocused(page); + await composerLocator(page).tap(); + await expectComposerFocused(page); + } finally { + await agent.cleanup(); + } + }); + + test("returning to an inactive inline composer does not restore focus on touch", async ({ + page, + }) => { + const workspace = await seedWorkspace({ repoPrefix: "composer-touch-retained-" }); + try { + const first = await createMockIdleAgent(workspace.client, { + cwd: workspace.repoPath, + workspaceId: workspace.workspaceId, + title: "First touch chat", + }); + const second = await createMockIdleAgent(workspace.client, { + cwd: workspace.repoPath, + workspaceId: workspace.workspaceId, + title: "Second touch chat", + }); + await openWorkspaceWithAgents(page, [first, second]); + await composerLocator(page).fill("Keep this touch draft"); + await expectComposerFocused(page); + // An external keyboard changes tabs without a pointer click blurring the + // editor first. The device still has a touch-primary focus policy. + await switchComposerTabWithKeyboard(page, "previous"); + await expectComposerDraft(page, ""); + await switchComposerTabWithKeyboard(page, "next"); + await expectComposerDraft(page, "Keep this touch draft"); + await expectComposerNotFocused(page); + await composerLocator(page).tap(); + await expectComposerFocused(page); + await typeIntoFocusedComposer(page, " after return"); + await expectComposerDraft(page, "Keep this touch draft after return"); + } finally { + await workspace.cleanup(); + } + }); + test("opening an agent leaves the composer unfocused", async ({ page }) => { const agent = await seedMockAgentWorkspace({ repoPrefix: "composer-focus-touch-", diff --git a/packages/app/e2e/browser/hoplite-model-discovery.real.spec.ts b/packages/app/e2e/browser/hoplite-model-discovery.real.spec.ts new file mode 100644 index 0000000000..60e13b70a6 --- /dev/null +++ b/packages/app/e2e/browser/hoplite-model-discovery.real.spec.ts @@ -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 { + 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 { + 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 { + 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 { + 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({ 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); + } +}); diff --git a/packages/app/e2e/browser/plugin-popover.spec.ts b/packages/app/e2e/browser/plugin-popover.spec.ts new file mode 100644 index 0000000000..8ce3b35513 --- /dev/null +++ b/packages/app/e2e/browser/plugin-popover.spec.ts @@ -0,0 +1,47 @@ +import { expect, test, type Page } from "../support/fixtures"; +import { composerLocator, submitMessageWithButton } from "../support/helpers/composer"; +import { seedMockAgentWorkspace, openAgentRoute } from "../support/helpers/mock-agent"; +import { withPopoverTimelinePlugin } from "../support/helpers/plugin-timeline"; + +async function openPreviewWhileTyping(page: Page): Promise { + await composerLocator(page).focus(); + await page.getByRole("button", { name: "Hover plugin preview", exact: true }).hover(); + await expect(page.getByRole("dialog", { name: "Plugin preview" })).toBeVisible(); + await expect(composerLocator(page)).toBeFocused(); +} + +async function dismissPreview(page: Page): Promise { + await page.keyboard.press("Escape"); + await expect(page.getByRole("dialog", { name: "Plugin preview" })).not.toBeVisible(); +} + +test("Escape dismisses a plugin preview before interrupting the agent", async ({ page }) => { + test.setTimeout(120_000); + const agent = await seedMockAgentWorkspace({ + repoPrefix: "plugin-popover-", + title: "Plugin preview keyboard regression", + model: "e2e-fast-stream", + }); + try { + await withPopoverTimelinePlugin(async () => { + await openAgentRoute(page, agent); + await submitMessageWithButton(page, "Show the plugin preview."); + await agent.client.waitForFinish(agent.agentId, 30_000); + await expect(page.getByRole("button", { name: "Hover plugin preview" })).toBeVisible(); + await submitMessageWithButton(page, "withhold synthetic user message until interrupted"); + const stop = page.getByRole("button", { name: "Stop agent", exact: true }); + await expect(stop).toBeVisible(); + + await openPreviewWhileTyping(page); + await dismissPreview(page); + await expect(stop).toBeVisible(); + await expect(composerLocator(page)).toBeFocused(); + + await page.keyboard.press("Escape"); + await expect(stop).not.toBeVisible(); + await agent.client.waitForFinish(agent.agentId, 15_000); + }); + } finally { + await agent.cleanup(); + } +}); diff --git a/packages/app/e2e/browser/usage-modal.spec.ts b/packages/app/e2e/browser/usage-modal.spec.ts index 6f546078bf..a923971d09 100644 --- a/packages/app/e2e/browser/usage-modal.spec.ts +++ b/packages/app/e2e/browser/usage-modal.spec.ts @@ -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(); diff --git a/packages/app/e2e/browser/usage-sidebar-item.spec.ts b/packages/app/e2e/browser/usage-sidebar-item.spec.ts index fb738b3cb5..27fac6691c 100644 --- a/packages/app/e2e/browser/usage-sidebar-item.spec.ts +++ b/packages/app/e2e/browser/usage-sidebar-item.spec.ts @@ -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(); diff --git a/packages/app/e2e/mobile/agent-device/native-compact-workspace-scripts-preconditions.md b/packages/app/e2e/mobile/agent-device/native-compact-workspace-scripts-preconditions.md new file mode 100644 index 0000000000..56dbd6355e --- /dev/null +++ b/packages/app/e2e/mobile/agent-device/native-compact-workspace-scripts-preconditions.md @@ -0,0 +1,15 @@ +# Native compact workspace scripts flow + +`native-compact-workspace-scripts.android.ad` covers live script status in the compact ⋯ → Scripts sheet when nothing else keeps the host directory live. Start on a phone with a workspace open, the sidebar closed, and no agent tab selected. A viewed agent tab or the open sidebar hides the failure, because either one keeps the directory subscribed. + +The workspace's `paseo.json` needs a long-running plain script, stopped before the run. `SCRIPT` defaults to `worker`: + +```json +{ "scripts": { "worker": { "command": "node -e \"setInterval(() => {}, 1000)\"" } } } +``` + +The flow starts the script, checks that Stop flips its page to Run, runs it again, and checks that Restart brings it back to running with no other interaction. It ends with the script stopped and the sheet dismissed, so it can be replayed. + +```sh +agent-device replay packages/app/e2e/mobile/agent-device/native-compact-workspace-scripts.android.ad --platform android --serial emulator-5590 --metro-port 8137 +``` diff --git a/packages/app/e2e/mobile/agent-device/native-compact-workspace-scripts.android.ad b/packages/app/e2e/mobile/agent-device/native-compact-workspace-scripts.android.ad new file mode 100644 index 0000000000..7a24b7ee8b --- /dev/null +++ b/packages/app/e2e/mobile/agent-device/native-compact-workspace-scripts.android.ad @@ -0,0 +1,45 @@ +context platform=android timeout=120000 retries=0 +env APP_ID=sh.paseo.debug +env SCRIPT=worker + +open "${APP_ID}" +wait "id=\"workspace-header-menu-trigger\"" 45000 +wait stable 1000 15000 +press "id=\"workspace-header-menu-trigger\"" +wait "id=\"workspace-header-scripts\"" 10000 +press "id=\"workspace-header-scripts\"" +wait "id=\"workspace-scripts-row-${SCRIPT}\"" 10000 +press "id=\"workspace-scripts-row-${SCRIPT}\"" +wait stable 1000 15000 +wait "id=\"workspace-header-menu-trigger\"" 10000 +press "id=\"workspace-header-menu-trigger\"" +wait "id=\"workspace-header-scripts\"" 10000 +press "id=\"workspace-header-scripts\"" +wait "text" "Running" 10000 +press "id=\"workspace-scripts-row-${SCRIPT}\"" +wait "id=\"workspace-script-${SCRIPT}-stop\"" 10000 +press "id=\"workspace-script-${SCRIPT}-stop\"" +wait "id=\"workspace-script-${SCRIPT}-run\"" 10000 +press "id=\"workspace-script-${SCRIPT}-run\"" +wait stable 1000 15000 +wait "id=\"workspace-header-menu-trigger\"" 10000 +press "id=\"workspace-header-menu-trigger\"" +wait "id=\"workspace-header-scripts\"" 10000 +press "id=\"workspace-header-scripts\"" +wait "text" "Running" 10000 +press "id=\"workspace-scripts-row-${SCRIPT}\"" +wait "id=\"workspace-script-${SCRIPT}-restart\"" 10000 +press "id=\"workspace-script-${SCRIPT}-restart\"" +wait stable 1000 15000 +wait "id=\"workspace-header-menu-trigger\"" 10000 +press "id=\"workspace-header-menu-trigger\"" +wait "id=\"workspace-header-scripts\"" 10000 +press "id=\"workspace-header-scripts\"" +wait "text" "Running" 15000 +press "id=\"workspace-scripts-row-${SCRIPT}\"" +wait "id=\"workspace-script-${SCRIPT}-stop\"" 10000 +press "id=\"workspace-script-${SCRIPT}-stop\"" +wait "id=\"workspace-script-${SCRIPT}-run\"" 10000 +back +wait stable 1000 15000 +close diff --git a/packages/app/e2e/support/helpers/add-project-flow.ts b/packages/app/e2e/support/helpers/add-project-flow.ts index bb88264d37..666469540e 100644 --- a/packages/app/e2e/support/helpers/add-project-flow.ts +++ b/packages/app/e2e/support/helpers/add-project-flow.ts @@ -90,3 +90,26 @@ export async function expectNewWorkspaceForAddedProject( { timeout: 30_000 }, ); } + +export async function navigateAddProjectResults( + page: Page, + key: "ArrowDown" | "ArrowUp", + count: number, +): Promise { + for (let index = 0; index < count; index += 1) await page.keyboard.press(key); +} + +export async function expectAddProjectResultVisible(page: Page, text: string): Promise { + const results = page.getByTestId("add-project-flow-results"); + const row = results.getByRole("button").filter({ has: page.getByText(text, { exact: true }) }); + await expect + .poll(async () => { + const viewport = await results.boundingBox(); + const bounds = await row.boundingBox(); + if (!viewport || !bounds) return false; + return ( + bounds.y >= viewport.y - 1 && bounds.y + bounds.height <= viewport.y + viewport.height + 1 + ); + }) + .toBe(true); +} diff --git a/packages/app/e2e/support/helpers/compact-workspace-scripts.ts b/packages/app/e2e/support/helpers/compact-workspace-scripts.ts new file mode 100644 index 0000000000..b01a527bc6 --- /dev/null +++ b/packages/app/e2e/support/helpers/compact-workspace-scripts.ts @@ -0,0 +1,61 @@ +import { expect, type Locator, type Page } from "@playwright/test"; + +/** The compact ⋯ sheet. Its trigger shares "Workspace actions" with the sidebar row kebabs. */ +export function compactWorkspaceMenu(page: Page): Locator { + return page.getByTestId("workspace-header-menu-content"); +} + +export async function openCompactWorkspaceMenu(page: Page): Promise { + await page.getByTestId("workspace-header-menu-trigger").click(); + await expect(compactWorkspaceMenu(page)).toBeVisible({ timeout: 10_000 }); +} + +export function menuRow(page: Page, name: string | RegExp): Locator { + return compactWorkspaceMenu(page).getByRole("menuitem", { name }); +} + +/** The root row that leads to the Scripts page; its accessible name carries its value. */ +export function scriptsMenuRow(page: Page): Locator { + return menuRow(page, /^Scripts/); +} + +/** A row on the Scripts page. A running script's name is followed by "Running". */ +export function scriptRow(page: Page, scriptName: string): Locator { + return menuRow(page, new RegExp(`^${scriptName}`)); +} + +export async function openScriptsPage(page: Page): Promise { + await openCompactWorkspaceMenu(page); + await scriptsMenuRow(page).click(); + await expect(scriptsMenuRow(page)).toHaveCount(0); + await expect(backButton(page)).toBeVisible(); +} + +export async function openRunningScriptPage(page: Page, scriptName: string): Promise { + await openScriptsPage(page); + await scriptRow(page, scriptName).click(); + await expect(menuRow(page, "Stop")).toBeVisible(); +} + +/** Taps a stopped script on the Scripts page, which runs it and closes the sheet. */ +export async function runScriptFromScriptsPage(page: Page, scriptName: string): Promise { + await openScriptsPage(page); + await scriptRow(page, scriptName).click(); + await expect(compactWorkspaceMenu(page)).toBeHidden({ timeout: 10_000 }); +} + +export async function goBackInMenu(page: Page): Promise { + await backButton(page).click(); +} + +export async function closeCompactWorkspaceMenu(page: Page): Promise { + await page + .getByRole("button", { name: "Bottom sheet backdrop" }) + .first() + .click({ position: { x: 12, y: 12 } }); + await expect(compactWorkspaceMenu(page)).toBeHidden({ timeout: 10_000 }); +} + +function backButton(page: Page): Locator { + return compactWorkspaceMenu(page).getByRole("button", { name: "Back" }); +} diff --git a/packages/app/e2e/support/helpers/plugin-timeline.ts b/packages/app/e2e/support/helpers/plugin-timeline.ts index 8ad7e0a632..8b0f680e2d 100644 --- a/packages/app/e2e/support/helpers/plugin-timeline.ts +++ b/packages/app/e2e/support/helpers/plugin-timeline.ts @@ -231,3 +231,46 @@ export async function attachPromptTimelineEvidence(page: Page, info: TestInfo): contentType: "image/png", }); } + +const POPOVER_CLIENT_SOURCE = `import React, { useEffect, useRef } from "react"; +import { z } from "zod"; + +function Preview() { + const panel = useRef(null); + useEffect(() => { + const close = (event) => { + if (event.key === "Escape" && panel.current.matches(":popover-open")) { + panel.current.hidePopover(); + } + }; + document.addEventListener("keydown", close, true); + return () => document.removeEventListener("keydown", close, true); + }, []); + return
+ +
Plugin hover preview
+
; +} + +export default function contribute(client) { + client.addTimelineTransformer({ + id: "preview", query: { itemType: "user_message" }, + transform({ item }) { + if (item.text !== "Show the plugin preview.") return; + return { items: [{ type: "plugin", kind: "preview", version: 1, data: {} }] }; + }, + }); + client.addTimelineRenderer({ + kind: "preview", version: 1, schema: z.object({}), Component: Preview, + }); + return () => {}; +}`; + +/** Installs a timeline preview that owns Escape through the DOM Popover API. */ +export async function withPopoverTimelinePlugin(run: () => Promise): Promise { + await withDirectoryPlugin({ + pluginId: "timeline-popover-e2e", + source: POPOVER_CLIENT_SOURCE, + run, + }); +} diff --git a/packages/app/e2e/support/helpers/settings.ts b/packages/app/e2e/support/helpers/settings.ts index 1702f7fe44..6b810e6d13 100644 --- a/packages/app/e2e/support/helpers/settings.ts +++ b/packages/app/e2e/support/helpers/settings.ts @@ -370,7 +370,7 @@ export async function findAcpCatalogProvider(page: Page, providerName: string): export async function installAcpCatalogProvider(page: Page, providerName: string): Promise { 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( diff --git a/packages/app/e2e/support/helpers/timeline-pagination.ts b/packages/app/e2e/support/helpers/timeline-pagination.ts index 7dd3dca8d7..52027df956 100644 --- a/packages/app/e2e/support/helpers/timeline-pagination.ts +++ b/packages/app/e2e/support/helpers/timeline-pagination.ts @@ -544,7 +544,7 @@ async function readTimelineViewport(page: Page): Promise { +export async function waitForTimelineGeometryToSettle(page: Page): Promise { const scroll = page.locator('[data-testid="agent-chat-scroll"]:visible').first(); await scroll.evaluate( (element) => diff --git a/packages/app/e2e/support/helpers/timeline-scroll-smoothness.ts b/packages/app/e2e/support/helpers/timeline-scroll-smoothness.ts index 60db71b25e..41f8cf3279 100644 --- a/packages/app/e2e/support/helpers/timeline-scroll-smoothness.ts +++ b/packages/app/e2e/support/helpers/timeline-scroll-smoothness.ts @@ -412,11 +412,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)! @@ -431,25 +427,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, diff --git a/packages/app/e2e/support/helpers/usage-sidebar-item.ts b/packages/app/e2e/support/helpers/usage-sidebar-item.ts index 8cc3c07a00..95c6a4d689 100644 --- a/packages/app/e2e/support/helpers/usage-sidebar-item.ts +++ b/packages/app/e2e/support/helpers/usage-sidebar-item.ts @@ -212,6 +212,14 @@ export async function scrollUsage(page: Page, deltaY: number): Promise { 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 { + 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 { await visible(page, "usage-modal").getByRole("button", { name: "Close", exact: true }).click(); diff --git a/packages/app/modules/paseo-scroll/android/src/androidTest/java/sh/paseo/scroll/ScrollSelectionTest.kt b/packages/app/modules/paseo-scroll/android/src/androidTest/java/sh/paseo/scroll/ScrollSelectionTest.kt index 3c446d140b..c7007776ba 100644 --- a/packages/app/modules/paseo-scroll/android/src/androidTest/java/sh/paseo/scroll/ScrollSelectionTest.kt +++ b/packages/app/modules/paseo-scroll/android/src/androidTest/java/sh/paseo/scroll/ScrollSelectionTest.kt @@ -8,11 +8,12 @@ import android.widget.FrameLayout import android.widget.TextView import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry +import com.facebook.react.bridge.BridgeReactContext import com.facebook.react.bridge.JavaOnlyArray import com.facebook.react.bridge.JavaOnlyMap -import com.facebook.react.uimanager.ReactStylesDiffMap -import com.facebook.react.bridge.BridgeReactContext import com.facebook.react.soloader.OpenSourceMergedSoMapping +import com.facebook.react.uimanager.DisplayMetricsHolder +import com.facebook.react.uimanager.ReactStylesDiffMap import com.facebook.react.uimanager.ThemedReactContext import com.facebook.react.views.scroll.ReactScrollView import com.facebook.react.views.scroll.ReactScrollViewManager @@ -50,34 +51,29 @@ class ScrollSelectionTest { assertNotEquals(before, scroll.scrollY) } - @Test fun directVerticalMirroringKeepsSelectionStill() = withScroll(inverted = false) { scroll, text -> - scroll.scaleY = -1f + @Test fun verticalScaleStillKeepsFocusAndSelectionInPlace() = withScroll(inverted = true, transform = "scaleY") { scroll, text -> val before = scroll.scrollY + assertTrue(text.requestFocus()) text.requestRectangleOnScreen(Rect(0, 0, 80, 40), true) assertEquals(before, scroll.scrollY) } - @Test fun horizontalMirroringStillRevealsSelectedText() = withScroll(inverted = false) { scroll, text -> - scroll.scaleX = -1f + @Test fun horizontalScaleStillRevealsSelectedText() = withScroll(inverted = true, transform = "scaleX") { scroll, text -> val before = scroll.scrollY text.requestRectangleOnScreen(Rect(0, 0, 80, 40), true) assertNotEquals(before, scroll.scrollY) } - private fun withScroll(inverted: Boolean, check: (ReactScrollView, TextView) -> Unit) { + private fun withScroll(inverted: Boolean, transform: String = "scale", check: (ReactScrollView, TextView) -> Unit) { val instrumentation = InstrumentationRegistry.getInstrumentation() instrumentation.runOnMainSync { val appContext = instrumentation.targetContext + DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(appContext) SoLoader.init(appContext, OpenSourceMergedSoMapping) - com.facebook.react.uimanager.DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(appContext) val reactContext = BridgeReactContext(appContext) val context = ThemedReactContext(reactContext, appContext) val manager = PaseoScrollPackage().createViewManager(reactContext, ReactScrollViewManager.REACT_CLASS) as ReactScrollViewManager val scroll = manager.createViewInstance(context) - // Exercise VirtualizedList's Android transform through RN's real decomposition. - if (inverted) manager.updateProperties(scroll, ReactStylesDiffMap(JavaOnlyMap.of( - "transform", JavaOnlyArray.of(JavaOnlyMap.of("scale", -1.0)) - ))) val content = FrameLayout(context) val text = TextView(context).apply { setText("Selectable timeline text", TextView.BufferType.SPANNABLE) @@ -89,6 +85,13 @@ class ScrollSelectionTest { content.layout(0, 0, 300, 2000) scroll.measure(exact(300), exact(300)) scroll.layout(0, 0, 300, 300) + // Apply RN's actual Android inversion through the manager's transform decomposition. + val transforms = JavaOnlyArray.of(JavaOnlyMap.of(transform, if (inverted) -1.0 else 1.0)) + manager.updateProperties(scroll, ReactStylesDiffMap(JavaOnlyMap.of("transform", transforms))) + if (inverted && transform == "scale") { + assertEquals(1f, scroll.scaleY, 0f) + assertEquals(180f, kotlin.math.abs(scroll.rotation), 0f) + } scroll.scrollTo(0, 400) check(scroll, text) } diff --git a/packages/app/modules/paseo-scroll/android/src/main/java/sh/paseo/scroll/PaseoScrollPackage.kt b/packages/app/modules/paseo-scroll/android/src/main/java/sh/paseo/scroll/PaseoScrollPackage.kt index 51dc57db5f..71ff179cb1 100644 --- a/packages/app/modules/paseo-scroll/android/src/main/java/sh/paseo/scroll/PaseoScrollPackage.kt +++ b/packages/app/modules/paseo-scroll/android/src/main/java/sh/paseo/scroll/PaseoScrollPackage.kt @@ -30,13 +30,13 @@ private class PaseoScrollViewManager : ReactScrollViewManager() { private class PaseoScrollView(context: ThemedReactContext) : ReactScrollView(context) { private val transformValues = FloatArray(9) - // Android VirtualizedList uses scale: -1, which RN decomposes into a 180-degree - // rotation with positive scaleY. Inspect the composed transform so both that - // inversion and a direct scaleY: -1 suppress untransformed visibility requests. - // Keep focus/selection bookkeeping; gestures and explicit commands still scroll. + // Both RN focus handling and Android selection visibility requests use this calculation. + // Its coordinates ignore inversion. Keep focus/selection bookkeeping, but leave timeline + // movement to user gestures and explicit scroll commands. override fun computeScrollDeltaToGetChildRectOnScreen(rect: Rect): Int { + // RN's Android scale: -1 becomes a 180-degree rotation with positive scaleY. matrix.getValues(transformValues) - return if (transformValues[Matrix.MSCALE_Y] < 0) 0 - else super.computeScrollDeltaToGetChildRectOnScreen(rect) + if (transformValues[Matrix.MSCALE_Y] < 0) return 0 + return super.computeScrollDeltaToGetChildRectOnScreen(rect) } } diff --git a/packages/app/src/agent-stream/chat-find/types.ts b/packages/app/src/agent-stream/chat-find/types.ts index cce58be96e..4fdf543a5e 100644 --- a/packages/app/src/agent-stream/chat-find/types.ts +++ b/packages/app/src/agent-stream/chat-find/types.ts @@ -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; revealLoadedMessage(messageId: string): boolean; - visibleMessageIds: ReadonlySet; + visibleMessageIds: MountedMessageIds; children: ReactNode; } export interface ChatFindExpansionProps { diff --git a/packages/app/src/agent-stream/chat-outline/use-chat-outline.test.tsx b/packages/app/src/agent-stream/chat-outline/use-chat-outline.test.tsx index 4b2139fef6..bd5a73ce94 100644 --- a/packages/app/src/agent-stream/chat-outline/use-chat-outline.test.tsx +++ b/packages/app/src/agent-stream/chat-outline/use-chat-outline.test.tsx @@ -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() } }, + { initialProps: { mountedHistoryMessageIds: new Set() } }, ); 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(), + mountedHistoryMessageIds: new Set(), }, }, ); @@ -352,11 +352,11 @@ describe("useChatOutline", () => { act(() => result.current.jumpToPrompt(1)); await waitFor(() => expect(runtime.fetchAgentTimeline).toHaveBeenCalledOnce()); - rerender({ tail: [fetchedPrompt], visibleMessageIds: new Set() }); + rerender({ tail: [fetchedPrompt], mountedHistoryMessageIds: new Set() }); 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(), revealLoadedMessage, }), ); diff --git a/packages/app/src/agent-stream/chat-outline/use-chat-outline.ts b/packages/app/src/agent-stream/chat-outline/use-chat-outline.ts index 015b883d21..cfdb26b2a5 100644 --- a/packages/app/src/agent-stream/chat-outline/use-chat-outline.ts +++ b/packages/app/src/agent-stream/chat-outline/use-chat-outline.ts @@ -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; onJumpError: () => void; - visibleMessageIds?: ReadonlySet; + // Message ids of the history the viewport has mounted. Live head messages are always mounted. + mountedHistoryMessageIds?: ReadonlySet; 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(null); @@ -62,18 +81,19 @@ export function useChatOutline({ const readingSeqRef = useRef(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 }; } diff --git a/packages/app/src/agent-stream/model-retention.test.ts b/packages/app/src/agent-stream/model-retention.test.ts new file mode 100644 index 0000000000..c82b29d301 --- /dev/null +++ b/packages/app/src/agent-stream/model-retention.test.ts @@ -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[] { + const windows: WeakRef[] = []; + 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); +}); diff --git a/packages/app/src/agent-stream/model.test.ts b/packages/app/src/agent-stream/model.test.ts index e29792ab02..dec4c489b9 100644 --- a/packages/app/src/agent-stream/model.test.ts +++ b/packages/app/src/agent-stream/model.test.ts @@ -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, + }); + }, + ); }); diff --git a/packages/app/src/agent-stream/model.ts b/packages/app/src/agent-stream/model.ts index 89eb73a7be..92f8be7141 100644 --- a/packages/app/src/agent-stream/model.ts +++ b/packages/app/src/agent-stream/model.ts @@ -53,11 +53,29 @@ const splitHistoryCache = new WeakMap< StreamItem[], Map> >(); -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> + { 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>; 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, diff --git a/packages/app/src/agent-stream/strategy-web.tsx b/packages/app/src/agent-stream/strategy-web.tsx index d66c80e049..97490c2a17 100644 --- a/packages/app/src/agent-stream/strategy-web.tsx +++ b/packages/app/src/agent-stream/strategy-web.tsx @@ -1308,6 +1308,8 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
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 }); + }); +}); diff --git a/packages/app/src/agent-stream/use-stream-history-window.ts b/packages/app/src/agent-stream/use-stream-history-window.ts index 42168f052d..9874158dcc 100644 --- a/packages/app/src/agent-stream/use-stream-history-window.ts +++ b/packages/app/src/agent-stream/use-stream-history-window.ts @@ -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) { diff --git a/packages/app/src/agent-stream/view.tsx b/packages/app/src/agent-stream/view.tsx index aa398c4b52..cd7aa42b70 100644 --- a/packages/app/src/agent-stream/view.tsx +++ b/packages/app/src/agent-stream/view.tsx @@ -596,16 +596,21 @@ const AgentStreamViewComponent = forwardRef - 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, @@ -615,7 +620,7 @@ const AgentStreamViewComponent = forwardRef diff --git a/packages/app/src/assets/acp-provider-icons.ts b/packages/app/src/assets/acp-provider-icons.ts index 65f123cb3d..cebb4ca76d 100644 --- a/packages/app/src/assets/acp-provider-icons.ts +++ b/packages/app/src/assets/acp-provider-icons.ts @@ -48,6 +48,8 @@ export const ACP_PROVIDER_ICON_SVGS = { goose: '\n \n\n', grok: '\n \n \n\n', + hoplite: + '\n', junie: '\n \n \n \n\n', kilo: '\n \n\n', diff --git a/packages/app/src/assets/acp-provider-icons/hoplite.svg b/packages/app/src/assets/acp-provider-icons/hoplite.svg new file mode 100644 index 0000000000..4d9c443429 --- /dev/null +++ b/packages/app/src/assets/acp-provider-icons/hoplite.svg @@ -0,0 +1 @@ + diff --git a/packages/app/src/components/add-project-flow.tsx b/packages/app/src/components/add-project-flow.tsx index d874a73618..c331f237c5 100644 --- a/packages/app/src/components/add-project-flow.tsx +++ b/packages/app/src/components/add-project-flow.tsx @@ -19,6 +19,7 @@ import { useRef, useState, type ComponentType, + type RefObject, } from "react"; import { Modal, @@ -71,6 +72,7 @@ import { type ProjectPickerOption, } from "@/components/project-picker-options"; import { Shortcut } from "@/components/ui/shortcut"; +import { useRevealActiveItem } from "@/components/ui/scroll-reveal"; import { useKeyboardShortcutsAvailable } from "@/keyboard/availability"; import { getIsElectronRuntime } from "@/constants/layout"; import { isNative, isWeb } from "@/constants/platform"; @@ -252,7 +254,17 @@ function pathTestId(path: string): string { return `add-project-flow-path-${encodeURIComponent(path)}`; } -function FlowRow({ option, active }: { option: FlowRowOption; active: boolean }) { +function FlowRow({ + option, + active, + activeItemRef, + onRowLayout, +}: { + option: FlowRowOption; + active: boolean; + activeItemRef: RefObject; + onRowLayout: () => void; +}) { const accessibilityState = useMemo( () => ({ disabled: option.disabled === true, selected: active }), [active, option.disabled], @@ -270,6 +282,8 @@ function FlowRow({ option, active }: { option: FlowRowOption; active: boolean }) accessibilityRole="button" accessibilityState={accessibilityState} disabled={option.disabled} + ref={active ? activeItemRef : undefined} + onLayout={active ? onRowLayout : undefined} onPress={option.select} style={rowStyle} testID={option.testID} @@ -384,6 +398,7 @@ export function AddProjectFlow({ request, onClose }: AddProjectFlowProps) { ); const setHasHydratedWorkspaces = useSessionStore((store) => store.setHasHydratedWorkspaces); const inputRef = useRef(null); + const resultsRef = useRef(null); const submissionInFlightRef = useRef(false); const browseInFlightRef = useRef(false); const query = page.kind === "new-directory-name" || page.kind === "method" ? "" : page.query; @@ -715,6 +730,13 @@ export function AddProjectFlow({ request, onClose }: AddProjectFlowProps) { ]); const activeIndex = rows.length === 0 ? 0 : Math.min(page.activeIndex, rows.length - 1); + const rowListKey = useMemo(() => rows.map((row) => row.id).join("\u0000"), [rows]); + const { activeItemRef, contentRef, onItemLayout, onViewportLayout, onScroll } = + useRevealActiveItem({ + activeIndex, + listKey: rowListKey, + scrollRef: resultsRef, + }); const createDirectory = useCallback(async () => { if (page.kind !== "new-directory-name" || !client) return; const name = page.name.trim(); @@ -905,53 +927,64 @@ export function AddProjectFlow({ request, onClose }: AddProjectFlowProps) { ) : null} - {preview ? ( - - {shortenPath(preview)} - - ) : null} - {isSubmitting ? ( - - {progressText(page)} - - ) : null} - {!isSubmitting && page.error ? ( - - {page.error} - - ) : null} - {!isSubmitting && queryError ? ( - - {queryError} - - ) : null} - {!isSubmitting && loading ? ( - - Loading... - - ) : null} - {!isSubmitting && - (!loading || page.kind === "github-search") && - (!queryError || page.kind === "github-search") - ? rows.map((option, index) => ( - - )) - : null} - {!isSubmitting && - !loading && - !queryError && - rows.length === 0 && - page.kind !== "new-directory-name" ? ( - - {emptyText(page, host ?? null)} - - ) : null} + + {preview ? ( + + {shortenPath(preview)} + + ) : null} + {isSubmitting ? ( + + {progressText(page)} + + ) : null} + {!isSubmitting && page.error ? ( + + {page.error} + + ) : null} + {!isSubmitting && queryError ? ( + + {queryError} + + ) : null} + {!isSubmitting && loading ? ( + + Loading... + + ) : null} + {!isSubmitting && + (!loading || page.kind === "github-search") && + (!queryError || page.kind === "github-search") + ? rows.map((option, index) => ( + + )) + : null} + {!isSubmitting && + !loading && + !queryError && + rows.length === 0 && + page.kind !== "new-directory-name" ? ( + + {emptyText(page, host ?? null)} + + ) : null} + diff --git a/packages/app/src/components/floating-header/index.tsx b/packages/app/src/components/floating-header/index.tsx index b18a8731b0..6e4cd525f1 100644 --- a/packages/app/src/components/floating-header/index.tsx +++ b/packages/app/src/components/floating-header/index.tsx @@ -1,11 +1,12 @@ -import { useCallback, useId, useState, type ReactNode } from "react"; +import { useCallback, useState, type ReactNode } from "react"; import { View, type LayoutChangeEvent } from "react-native"; -import Svg, { Defs, LinearGradient as SvgLinearGradient, Rect, Stop } from "react-native-svg"; -import { StyleSheet, withUnistyles } from "react-native-unistyles"; -import type { Theme } from "@/styles/theme"; +import { StyleSheet } from "react-native-unistyles"; +import { EdgeFade } from "@/components/ui/edge-fade"; /** How far the fade runs past the header's bottom edge, so content dissolves instead of clipping. */ -const FADE_OVERHANG = 24; +const FADE_OVERHANG = 48; +/** Share of the fade that stays opaque, so the header's title and icons keep contrast. */ +const FADE_SOLID_FRACTION = 0.57; interface FloatingHeaderLayoutProps { header: ReactNode; @@ -29,51 +30,22 @@ export function FloatingHeaderLayout({ header, floating, children }: FloatingHea {floating ? null : header} {children(floating ? headerHeight : 0)} {floating ? ( - - - {header} + + + + {header} + ) : null} ); } -function FloatingHeaderFadeSvg({ gradientId, color }: { gradientId: string; color: string }) { - return ( - - - - {/* Vary opacity rather than interpolating toward `transparent`, which crosses black in - some engines and leaves a grey fringe. */} - - - - - - - - - ); -} - -const ThemedFloatingHeaderFadeSvg = withUnistyles(FloatingHeaderFadeSvg); -const workspaceSurfaceColorMapping = (theme: Theme) => ({ - color: theme.colors.surfaceWorkspace, -}); - -function FloatingHeaderFade() { - // React-generated ids contain characters that are invalid inside SVG fragment references. - const gradientId = `floating-header-fade-${useId().replace(/[^a-zA-Z0-9_-]/g, "")}`; - return ( - - - - ); -} - const styles = StyleSheet.create({ root: { flex: 1, @@ -88,12 +60,14 @@ const styles = StyleSheet.create({ top: 0, left: 0, right: 0, + // The fade's tail lives inside the overlay so Android does not clip it. + paddingBottom: FADE_OVERHANG, }, fade: { position: "absolute", top: 0, left: 0, right: 0, - bottom: -FADE_OVERHANG, + bottom: 0, }, }); diff --git a/packages/app/src/components/headers/compact-header.tsx b/packages/app/src/components/headers/compact-header.tsx index aa66580fce..6ed2bddcbe 100644 --- a/packages/app/src/components/headers/compact-header.tsx +++ b/packages/app/src/components/headers/compact-header.tsx @@ -17,7 +17,6 @@ import type { ShortcutKey } from "@/utils/format-shortcut"; const ThemedArrowLeft = withUnistyles(ArrowLeft); -const ISLAND_PADDING = 7; const NO_SHORTCUT: ShortcutKey[] = []; interface CompactHeaderProps { @@ -37,8 +36,9 @@ interface CompactHeaderProps { /** * The phone header: the navigation button and the screen's actions sit in islands, with the title - * left-aligned between them. It has no background of its own, so it reads the same in flow and floating - * over content (see `FloatingHeaderLayout`). Its height matches the old flat header, so anything + * left-aligned between them. Neither the header nor its islands draw a background, so it reads the + * same in flow and floating over content (see `FloatingHeaderLayout`, whose fade gives the icons + * contrast). Its height matches the old flat header, so anything * offset by the header height still lines up. */ export function CompactHeader({ @@ -90,7 +90,11 @@ function CompactHeaderTitle({ return ( <> {title ? ( - + {title} ) : null} @@ -146,10 +150,6 @@ const styles = StyleSheet.create((theme) => ({ island: { flexDirection: "row", alignItems: "center", - padding: ISLAND_PADDING, - borderRadius: theme.borderRadius.full, - backgroundColor: theme.colors.surface2, - ...theme.shadow.sm, }, title: { fontSize: theme.fontSize.base, @@ -157,6 +157,13 @@ const styles = StyleSheet.create((theme) => ({ color: theme.colors.foreground, textAlign: "left", }, + // A title without a subtitle has the header to itself, so it reads one step larger. + singleLineTitle: { + fontSize: theme.fontSize.lg, + fontWeight: theme.fontWeight.medium, + color: theme.colors.foreground, + textAlign: "left", + }, titleSkeleton: { width: 140, maxWidth: "100%", diff --git a/packages/app/src/components/provider-catalog-list.tsx b/packages/app/src/components/provider-catalog-list.tsx index 4f996fdd40..3e75765919 100644 --- a/packages/app/src/components/provider-catalog-list.tsx +++ b/packages/app/src/components/provider-catalog-list.tsx @@ -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; } -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 ( - + {entry.iconSvg ? ( )} - - - - {entry.title} - - - {entry.version} - - - - {entry.description || entry.id} + + + {entry.title} - - - {t("providerCatalog.actions.installInstructions")} - - - + + {/* The catalog is the ACP registry, so every entry it offers is an ACP provider. */} + + + ); @@ -129,6 +113,7 @@ export function ProviderCatalogList({ const { entries: catalogEntries } = useAcpProviderCatalog(); const { entries: providerEntries } = useProvidersSnapshot(serverId); const [search, setSearch] = useState(""); + const [gridWidth, setGridWidth] = useState(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 ( - - - - - + {availableEntries.length === 0 ? ( - + {t("providerCatalog.noProviders")} ) : ( - + {availableEntries.map((entry) => ( - @@ -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: { diff --git a/packages/app/src/components/provider-catalog-search.test.ts b/packages/app/src/components/provider-catalog-search.test.ts new file mode 100644 index 0000000000..4079d79602 --- /dev/null +++ b/packages/app/src/components/provider-catalog-search.test.ts @@ -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"]); + }); +}); diff --git a/packages/app/src/components/provider-catalog-search.ts b/packages/app/src/components/provider-catalog-search.ts new file mode 100644 index 0000000000..23303c868f --- /dev/null +++ b/packages/app/src/components/provider-catalog-search.ts @@ -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( + 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); +} diff --git a/packages/app/src/components/ui/autocomplete-utils.test.ts b/packages/app/src/components/ui/autocomplete-utils.test.ts index dd67c23b57..ecf046a8aa 100644 --- a/packages/app/src/components/ui/autocomplete-utils.test.ts +++ b/packages/app/src/components/ui/autocomplete-utils.test.ts @@ -1,10 +1,6 @@ import { describe, expect, it } from "vitest"; -import { - getAutocompleteFallbackIndex, - getAutocompleteScrollOffset, - orderAutocompleteOptions, -} from "./autocomplete-utils"; +import { getAutocompleteFallbackIndex, orderAutocompleteOptions } from "./autocomplete-utils"; const OPTIONS = ["alpha", "beta", "gamma"]; @@ -28,27 +24,3 @@ describe("getAutocompleteFallbackIndex", () => { expect(getAutocompleteFallbackIndex(3, "below-input")).toBe(0); }); }); - -describe("getAutocompleteScrollOffset", () => { - it("scrolls up when the active item is above the viewport", () => { - expect( - getAutocompleteScrollOffset({ - currentOffset: 120, - viewportHeight: 80, - itemTop: 90, - itemHeight: 20, - }), - ).toBe(90); - }); - - it("scrolls down when the active item is below the viewport", () => { - expect( - getAutocompleteScrollOffset({ - currentOffset: 0, - viewportHeight: 100, - itemTop: 150, - itemHeight: 24, - }), - ).toBe(74); - }); -}); diff --git a/packages/app/src/components/ui/autocomplete-utils.ts b/packages/app/src/components/ui/autocomplete-utils.ts index f8250856df..175cf6b62d 100644 --- a/packages/app/src/components/ui/autocomplete-utils.ts +++ b/packages/app/src/components/ui/autocomplete-utils.ts @@ -29,28 +29,3 @@ export function getAutocompleteNextIndex(args: { }): number { return getNextActiveIndex(args); } - -export function getAutocompleteScrollOffset(args: { - currentOffset: number; - viewportHeight: number; - itemTop: number; - itemHeight: number; -}): number { - if (args.viewportHeight <= 0) { - return args.currentOffset; - } - - const itemBottom = args.itemTop + args.itemHeight; - const viewportTop = args.currentOffset; - const viewportBottom = args.currentOffset + args.viewportHeight; - - if (args.itemTop < viewportTop) { - return Math.max(0, args.itemTop); - } - - if (itemBottom > viewportBottom) { - return Math.max(0, itemBottom - args.viewportHeight); - } - - return args.currentOffset; -} diff --git a/packages/app/src/components/ui/autocomplete.tsx b/packages/app/src/components/ui/autocomplete.tsx index cc684f8b41..7b5b99b316 100644 --- a/packages/app/src/components/ui/autocomplete.tsx +++ b/packages/app/src/components/ui/autocomplete.tsx @@ -13,7 +13,7 @@ import { StyleSheet, useUnistyles } from "react-native-unistyles"; import { useTranslation } from "react-i18next"; import { File, Folder } from "lucide-react-native"; import type { Theme } from "@/styles/theme"; -import { getAutocompleteScrollOffset } from "./autocomplete-utils"; +import { getScrollOffsetToRevealItem } from "./scroll-reveal"; export interface AutocompleteOption { id: string; @@ -146,7 +146,7 @@ export function Autocomplete({ return; } - const nextOffset = getAutocompleteScrollOffset({ + const nextOffset = getScrollOffsetToRevealItem({ currentOffset: scrollOffsetRef.current, viewportHeight: viewportHeightRef.current, itemTop: layout.top, diff --git a/packages/app/src/components/ui/edge-fade.tsx b/packages/app/src/components/ui/edge-fade.tsx new file mode 100644 index 0000000000..de404aeed8 --- /dev/null +++ b/packages/app/src/components/ui/edge-fade.tsx @@ -0,0 +1,72 @@ +import { useId } from "react"; +import { View, type StyleProp, type ViewStyle } from "react-native"; +import Svg, { Defs, LinearGradient as SvgLinearGradient, Rect, Stop } from "react-native-svg"; +import { withUnistyles } from "react-native-unistyles"; +import type { Theme } from "@/styles/theme"; + +type EdgeFadeBackdrop = "surface0" | "surfaceWorkspace"; + +const backdropColorMappings: Record { color: string }> = { + surface0: (theme) => ({ color: theme.colors.surface0 }), + surfaceWorkspace: (theme) => ({ color: theme.colors.surfaceWorkspace }), +}; + +interface EdgeFadeSvgProps { + gradientId: string; + color: string; + edge: "top" | "bottom"; + solidFraction: number; +} + +function EdgeFadeSvg({ gradientId, color, edge, solidFraction }: EdgeFadeSvgProps) { + const fromTop = edge === "top"; + return ( + + + + {/* Vary opacity rather than interpolating toward `transparent`, which crosses black in + some engines and leaves a grey fringe. Keep it to three stops: Android rendered a + four-stop version far more transparent than its stops specify. */} + + + + + + + + ); +} + +const ThemedEdgeFadeSvg = withUnistyles(EdgeFadeSvg); + +interface EdgeFadeProps { + /** The solid edge; content dissolves moving away from it. */ + edge: "top" | "bottom"; + /** Share of the fade, measured from the solid edge, that stays fully opaque. */ + solidFraction: number; + backdrop: EdgeFadeBackdrop; + /** Position and size. Keep the fade inside its parent: Android clips overhanging children. */ + style: StyleProp; +} + +/** Dissolves content into the surface behind chrome that floats over it. */ +export function EdgeFade({ edge, solidFraction, backdrop, style }: EdgeFadeProps) { + // React-generated ids contain characters that are invalid inside SVG fragment references. + const gradientId = `edge-fade-${useId().replace(/[^a-zA-Z0-9_-]/g, "")}`; + return ( + + + + ); +} diff --git a/packages/app/src/components/ui/scroll-reveal.test.ts b/packages/app/src/components/ui/scroll-reveal.test.ts new file mode 100644 index 0000000000..b793b2f46b --- /dev/null +++ b/packages/app/src/components/ui/scroll-reveal.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, it } from "vitest"; +import { getScrollOffsetToRevealItem } from "./scroll-reveal"; + +describe("getScrollOffsetToRevealItem", () => { + it("keeps the offset when the item is already inside the viewport", () => { + expect( + getScrollOffsetToRevealItem({ + currentOffset: 40, + viewportHeight: 200, + itemTop: 100, + itemHeight: 40, + }), + ).toBe(40); + }); + + it("scrolls up to the item top when the item is above the viewport", () => { + expect( + getScrollOffsetToRevealItem({ + currentOffset: 300, + viewportHeight: 200, + itemTop: 240, + itemHeight: 40, + }), + ).toBe(240); + }); + + it("scrolls down just far enough to reveal the item bottom", () => { + expect( + getScrollOffsetToRevealItem({ + currentOffset: 0, + viewportHeight: 200, + itemTop: 380, + itemHeight: 40, + }), + ).toBe(220); + }); + + it("stays put before the viewport has been measured", () => { + expect( + getScrollOffsetToRevealItem({ + currentOffset: 120, + viewportHeight: 0, + itemTop: 400, + itemHeight: 40, + }), + ).toBe(120); + }); +}); diff --git a/packages/app/src/components/ui/scroll-reveal.ts b/packages/app/src/components/ui/scroll-reveal.ts new file mode 100644 index 0000000000..50194c3ac8 --- /dev/null +++ b/packages/app/src/components/ui/scroll-reveal.ts @@ -0,0 +1,110 @@ +import { useCallback, useLayoutEffect, useRef, type RefObject } from "react"; +import type { + LayoutChangeEvent, + NativeScrollEvent, + NativeSyntheticEvent, + ScrollView, + View, +} from "react-native"; + +export function getScrollOffsetToRevealItem(args: { + currentOffset: number; + viewportHeight: number; + itemTop: number; + itemHeight: number; +}): number { + if (args.viewportHeight <= 0) { + return args.currentOffset; + } + + const itemBottom = args.itemTop + args.itemHeight; + const viewportTop = args.currentOffset; + const viewportBottom = args.currentOffset + args.viewportHeight; + + if (args.itemTop < viewportTop) { + return Math.max(0, args.itemTop); + } + + if (itemBottom > viewportBottom) { + return Math.max(0, itemBottom - args.viewportHeight); + } + + return args.currentOffset; +} + +export interface RevealActiveItemHandlers { + activeItemRef: RefObject; + contentRef: RefObject; + onItemLayout: () => void; + onViewportLayout: (event: LayoutChangeEvent) => void; + onScroll: (event: NativeSyntheticEvent) => void; +} + +/** + * Reveals the keyboard-selected row using its current position in the scroll + * content. Measuring on selection/list changes also covers retained rows that + * move or keep their size without emitting another onLayout event on web. + * A list replacement resets to the top only when selection restarts there. + * Bottom-anchored lists share only getScrollOffsetToRevealItem. + */ +export function useRevealActiveItem(options: { + activeIndex: number; + listKey: string; + scrollRef: RefObject; +}): RevealActiveItemHandlers { + const { activeIndex, listKey, scrollRef } = options; + const activeItemRef = useRef(null); + const contentRef = useRef(null); + const viewportHeightRef = useRef(0); + const offsetRef = useRef(0); + const measurementRef = useRef(0); + + const reveal = useCallback(() => { + const request = ++measurementRef.current; + const item = activeItemRef.current; + const scroll = scrollRef.current; + const content = contentRef.current; + if (!item || !scroll || !content) return; + + item.measureLayout(content, (_left, top, _width, height) => { + if (request !== measurementRef.current || activeItemRef.current !== item) return; + const nextOffset = getScrollOffsetToRevealItem({ + currentOffset: offsetRef.current, + viewportHeight: viewportHeightRef.current, + itemTop: top, + itemHeight: height, + }); + if (Math.abs(nextOffset - offsetRef.current) < 1) return; + offsetRef.current = nextOffset; + scroll.scrollTo({ y: nextOffset, animated: false }); + }); + }, [scrollRef]); + + const prevListKeyRef = useRef(listKey); + useLayoutEffect(() => { + if (prevListKeyRef.current !== listKey && activeIndex === 0) { + offsetRef.current = 0; + scrollRef.current?.scrollTo({ y: 0, animated: false }); + } + prevListKeyRef.current = listKey; + reveal(); + return () => { + // Measurements are asynchronous; a previous selection must not scroll us. + measurementRef.current += 1; + }; + }, [activeIndex, listKey, reveal, scrollRef]); + + const onViewportLayout = useCallback( + (event: LayoutChangeEvent) => { + viewportHeightRef.current = event.nativeEvent.layout.height; + reveal(); + }, + [reveal], + ); + + const onScroll = useCallback((event: NativeSyntheticEvent) => { + offsetRef.current = event.nativeEvent.contentOffset.y; + }, []); + + return { activeItemRef, contentRef, onItemLayout: reveal, onViewportLayout, onScroll }; +} diff --git a/packages/app/src/composer/input/input.tsx b/packages/app/src/composer/input/input.tsx index 7346095d5b..c6c267a38f 100644 --- a/packages/app/src/composer/input/input.tsx +++ b/packages/app/src/composer/input/input.tsx @@ -28,6 +28,7 @@ import { useTranslation } from "react-i18next"; import { ICON_SIZE, type Theme } from "@/styles/theme"; import { ArrowUp, Mic, MicOff, CornerDownLeft, Plus, Square } from "lucide-react-native"; import { useDictation } from "@/hooks/use-dictation"; +import { hasFinePointer } from "@/hooks/use-fine-pointer"; import { DictationOverlay } from "@/components/dictation-controls"; import { RealtimeVoiceOverlay } from "@/components/realtime-voice-overlay"; import type { DaemonClient } from "@getpaseo/client/internal/daemon-client"; @@ -1289,12 +1290,14 @@ export const MessageInput = forwardRef( webTextareaRef.current = element; setWebTextArea(element); }, []); - // Focus intent outlives a blur only while the pane is not the user's pane (a retained - // tab hidden, a sheet over it); the pane coming back restores focus. A blur while the - // pane is theirs drops it, whatever the layout mode: the user dismissed the keyboard, - // or a compact overlay panel did on their behalf, and nothing later refocuses. + // Only mouse-driven UIs restore editing focus on navigation. Touch users return + // to the conversation; replaying old focus would reopen their software keyboard. + // Read pointer capability when restoring, without making a pointer change itself + // a focus trigger. useLayoutEffect(() => { - if (isPaneFocused && focusIntentRef.current) textInputRef.current?.focus(); + if (isPaneFocused && focusIntentRef.current && hasFinePointer()) { + textInputRef.current?.focus(); + } }, [isPaneFocused]); // The compact and desktop screens mount the editor in different trees, so a // viewport that crosses the breakpoint remounts it. The draft owner brings the @@ -1311,7 +1314,7 @@ export const MessageInput = forwardRef( retainedSelectionRef.current = retained.selection; selectionRef.current = selection; textInputRef.current?.setSelection(selection); - if (retained.focused) { + if (retained.focused && hasFinePointer()) { focusIntentRef.current = true; if (paneFocusedRef.current) textInputRef.current?.focus(); } @@ -1818,6 +1821,7 @@ export const MessageInput = forwardRef( }, [onFocusChange]); const handleInputBlur = useCallback(() => { + // A blur in the active pane is a dismissal; only hiding the pane preserves intent. if (paneFocusedRef.current) focusIntentRef.current = false; isInputFocusedRef.current = false; setIsInputFocused(false); @@ -1858,11 +1862,12 @@ export const MessageInput = forwardRef( const inputWrapperCombinedStyle = useMemo( () => [ styles.inputWrapper, + isCompact && !isFullscreen && styles.inputWrapperCompact, readOnly && styles.inputWrapperReadOnly, inputWrapperStyle, { opacity: surfacePresentation.input.opacity }, ], - [inputWrapperStyle, readOnly, surfacePresentation.input.opacity], + [inputWrapperStyle, isCompact, isFullscreen, readOnly, surfacePresentation.input.opacity], ); // `withUnistyles` maps this component's `style` into a `.hash > *` child // rule, which ties on specificity with react-native-web's own @@ -2219,6 +2224,10 @@ const styles = StyleSheet.create((theme: Theme) => ({ } : {}), }, + // Lifts the composer off the chat it sits under on phones. + inputWrapperCompact: { + boxShadow: "0px 4px 16px rgba(0, 0, 0, 0.2)", + }, // Dotted says "this surface is the same box, but there is nothing to type // into it" without swapping the border colour, which reads as an error state. inputWrapperReadOnly: { diff --git a/packages/app/src/composer/keyboard-scope.tsx b/packages/app/src/composer/keyboard-scope.tsx index 20b57dde28..f8087bf420 100644 --- a/packages/app/src/composer/keyboard-scope.tsx +++ b/packages/app/src/composer/keyboard-scope.tsx @@ -8,10 +8,8 @@ import { interface ComposerKeyboardScopeValue { /** - * The pane this composer sits in is the user's pane. Focus restoration follows it: - * the editor keeps its focus intent across blurs that happen while the pane is not - * the user's (a retained tab hidden, a sheet over it) and brings focus back when - * the pane is theirs again. + * The pane this composer sits in is the user's pane. Mouse-driven focus + * restoration follows it; touch navigation does not restore editor focus. */ isPaneFocused: boolean; /** diff --git a/packages/app/src/composer/submission/model.ts b/packages/app/src/composer/submission/model.ts index 26febae04f..67301bd5ff 100644 --- a/packages/app/src/composer/submission/model.ts +++ b/packages/app/src/composer/submission/model.ts @@ -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[] { diff --git a/packages/app/src/data/acp-provider-catalog.ts b/packages/app/src/data/acp-provider-catalog.ts index 1fdb1c6f5d..1bd32db53d 100644 --- a/packages/app/src/data/acp-provider-catalog.ts +++ b/packages/app/src/data/acp-provider-catalog.ts @@ -8,6 +8,7 @@ export interface AcpProviderCatalogEntry { iconSvg: string | null; installLink: string; command: readonly [string, ...string[]]; + bundledProvider?: boolean; env?: Readonly>; params?: Readonly>; } @@ -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, diff --git a/packages/app/src/hooks/use-acp-provider-catalog.test.ts b/packages/app/src/hooks/use-acp-provider-catalog.test.ts index 63e360aba0..201c17c022 100644 --- a/packages/app/src/hooks/use-acp-provider-catalog.test.ts +++ b/packages/app/src/hooks/use-acp-provider-catalog.test.ts @@ -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(" { + 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: { diff --git a/packages/app/src/hooks/use-acp-provider-catalog.ts b/packages/app/src/hooks/use-acp-provider-catalog.ts index 92f9ca07e2..f20c31caf2 100644 --- a/packages/app/src/hooks/use-acp-provider-catalog.ts +++ b/packages/app/src/hooks/use-acp-provider-catalog.ts @@ -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]: { diff --git a/packages/app/src/hooks/use-keyboard-shortcuts.ts b/packages/app/src/hooks/use-keyboard-shortcuts.ts index d723b5be04..6f332b0a98 100644 --- a/packages/app/src/hooks/use-keyboard-shortcuts.ts +++ b/packages/app/src/hooks/use-keyboard-shortcuts.ts @@ -40,7 +40,7 @@ import { navigateToLastWorkspace, useActiveWorkspaceSelection, } from "@/stores/navigation-active-workspace-store"; -import { dispatchTopWebOverlayKeyDown } from "@/lib/overlay-root"; +import { dispatchTopWebOverlayKeyDown, keyBelongsToDomPopover } from "@/lib/overlay-root"; export function useKeyboardShortcuts({ enabled, @@ -321,6 +321,10 @@ export function useKeyboardShortcuts({ return; } + if (keyBelongsToDomPopover(event)) { + return; + } + // During IME composition, Enter confirms the candidate selection and must // not route through global shortcuts like message send. if (isImeComposingKeyboardEvent(event)) { diff --git a/packages/app/src/i18n/resources/ar.ts b/packages/app/src/i18n/resources/ar.ts index 87cacb2f82..5e09ac5957 100644 --- a/packages/app/src/i18n/resources/ar.ts +++ b/packages/app/src/i18n/resources/ar.ts @@ -729,6 +729,7 @@ export const ar: TranslationResources = { header: { actions: { workspaceActions: "إجراءات Workspace", + workspaceActionsUnhealthy: "إجراءات Workspace، توجد خدمة غير سليمة", newAgent: "وكيل جديد", newTerminal: "محطة جديدة", newBrowser: "علامة تبويب متصفح جديدة", @@ -776,6 +777,8 @@ export const ar: TranslationResources = { exitCode: "الخروج من{{code}}", startFailed: "فشل بدء تشغيل{{scriptName}}", stopFailed: "فشل إيقاف{{scriptName}}", + running: "قيد التشغيل", + runningCount: "{{count}} قيد التشغيل", }, }, tree: { @@ -1657,14 +1660,19 @@ export const ar: TranslationResources = { title: "إضافة مزود", search: "مقدمي البحث", noProviders: "لم يتم العثور على مقدمي الخدمات", + clearSearch: "مسح البحث", actions: { add: "يضيف", + addProvider: "إضافة {{provider}}", adding: "إضافة", installed: "تم التثبيت", cancel: "يلغي", installInstructions: "تعليمات التثبيت", installInstructionsFor: "تعليمات تثبيت{{provider}}", }, + types: { + acp: "ACP", + }, errors: { unableToInstall: "غير قادر على تثبيت الموفر", }, diff --git a/packages/app/src/i18n/resources/en.ts b/packages/app/src/i18n/resources/en.ts index f9779a6d55..8c6a870580 100644 --- a/packages/app/src/i18n/resources/en.ts +++ b/packages/app/src/i18n/resources/en.ts @@ -724,6 +724,7 @@ export const en = { header: { actions: { workspaceActions: "Workspace actions", + workspaceActionsUnhealthy: "Workspace actions, a service is unhealthy", newAgent: "New agent", newTerminal: "New terminal", newBrowser: "New browser tab", @@ -771,6 +772,8 @@ export const en = { exitCode: "exit {{code}}", startFailed: "Failed to start {{scriptName}}", stopFailed: "Failed to stop {{scriptName}}", + running: "Running", + runningCount: "{{count}} running", }, }, tree: { @@ -1682,14 +1685,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", }, diff --git a/packages/app/src/i18n/resources/es.ts b/packages/app/src/i18n/resources/es.ts index 190b36d08d..62667ba9f9 100644 --- a/packages/app/src/i18n/resources/es.ts +++ b/packages/app/src/i18n/resources/es.ts @@ -736,6 +736,7 @@ export const es: TranslationResources = { header: { actions: { workspaceActions: "AccionesWorkspace", + workspaceActionsUnhealthy: "Acciones del workspace, hay un servicio con problemas", newAgent: "Nuevo agente", newTerminal: "Nueva terminal", newBrowser: "Nueva pestaña del navegador", @@ -784,6 +785,8 @@ export const es: TranslationResources = { exitCode: "salir de{{code}}", startFailed: "No se pudo iniciar{{scriptName}}", stopFailed: "No se pudo detener{{scriptName}}", + running: "En ejecución", + runningCount: "{{count}} en ejecución", }, }, tree: { @@ -1703,14 +1706,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", }, diff --git a/packages/app/src/i18n/resources/fr.ts b/packages/app/src/i18n/resources/fr.ts index 6cfe15b1be..8e70ece6da 100644 --- a/packages/app/src/i18n/resources/fr.ts +++ b/packages/app/src/i18n/resources/fr.ts @@ -735,6 +735,8 @@ export const fr: TranslationResources = { header: { actions: { workspaceActions: "Actions de l’espace de travail", + workspaceActionsUnhealthy: + "Actions de l’espace de travail, un service est en mauvaise santé", newAgent: "Nouvel agent", newTerminal: "Nouveau terminal", newBrowser: "Nouvel onglet de navigateur", @@ -783,6 +785,8 @@ export const fr: TranslationResources = { exitCode: "sortie {{code}}", startFailed: "Impossible de démarrer {{scriptName}}", stopFailed: "Impossible d’arrêter {{scriptName}}", + running: "En cours", + runningCount: "{{count}} en cours", }, }, tree: { @@ -1699,14 +1703,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", }, diff --git a/packages/app/src/i18n/resources/ja.ts b/packages/app/src/i18n/resources/ja.ts index cb37dde381..d7b08a9c84 100644 --- a/packages/app/src/i18n/resources/ja.ts +++ b/packages/app/src/i18n/resources/ja.ts @@ -733,6 +733,7 @@ export const ja: TranslationResources = { header: { actions: { workspaceActions: "ワークスペースアクション", + workspaceActionsUnhealthy: "ワークスペースアクション、異常なサービスがあります", newAgent: "新しいエージェント", newTerminal: "新しいターミナル", newBrowser: "新しいブラウザタブ", @@ -780,6 +781,8 @@ export const ja: TranslationResources = { exitCode: "終了コード: {{code}}", startFailed: "{{scriptName}}の起動に失敗しました", stopFailed: "{{scriptName}}の停止に失敗しました", + running: "実行中", + runningCount: "{{count}} 件実行中", }, }, tree: { @@ -1674,14 +1677,19 @@ export const ja: TranslationResources = { title: "プロバイダーを追加", search: "プロバイダーを検索", noProviders: "プロバイダーが見つかりません", + clearSearch: "検索をクリア", actions: { add: "追加", + addProvider: "{{provider}} を追加", adding: "追加中", installed: "インストール済み", cancel: "キャンセル", installInstructions: "インストール手順", installInstructionsFor: "{{provider}}のインストール手順", }, + types: { + acp: "ACP", + }, errors: { unableToInstall: "プロバイダーをインストールできません", }, diff --git a/packages/app/src/i18n/resources/ko.ts b/packages/app/src/i18n/resources/ko.ts index 418490d395..c82240f0c4 100644 --- a/packages/app/src/i18n/resources/ko.ts +++ b/packages/app/src/i18n/resources/ko.ts @@ -729,6 +729,7 @@ export const ko: TranslationResources = { header: { actions: { workspaceActions: "워크스페이스 작업", + workspaceActionsUnhealthy: "워크스페이스 작업, 비정상 서비스가 있습니다", newAgent: "새 에이전트", newTerminal: "새 터미널", newBrowser: "새 브라우저 탭", @@ -776,6 +777,8 @@ export const ko: TranslationResources = { exitCode: "종료 {{code}}", startFailed: "{{scriptName}}을(를) 시작하지 못했습니다", stopFailed: "{{scriptName}}를 중지하지 못했습니다.", + running: "실행 중", + runningCount: "{{count}}개 실행 중", }, }, tree: { @@ -1667,14 +1670,19 @@ export const ko: TranslationResources = { title: "프로바이더 추가", search: "프로바이더 검색", noProviders: "프로바이더를 찾을 수 없습니다", + clearSearch: "검색 지우기", actions: { add: "추가", + addProvider: "{{provider}} 추가", adding: "추가 중", installed: "설치됨", cancel: "취소", installInstructions: "설치 안내", installInstructionsFor: "{{provider}} 설치 안내", }, + types: { + acp: "ACP", + }, errors: { unableToInstall: "프로바이더를 설치할 수 없습니다", }, diff --git a/packages/app/src/i18n/resources/pt-BR.ts b/packages/app/src/i18n/resources/pt-BR.ts index b2fe479b74..622c13e798 100644 --- a/packages/app/src/i18n/resources/pt-BR.ts +++ b/packages/app/src/i18n/resources/pt-BR.ts @@ -733,6 +733,7 @@ export const ptBR: TranslationResources = { header: { actions: { workspaceActions: "Ações do workspace", + workspaceActionsUnhealthy: "Ações do workspace, há um serviço com problema", newAgent: "Novo agente", newTerminal: "Novo terminal", newBrowser: "Nova aba de navegador", @@ -780,6 +781,8 @@ export const ptBR: TranslationResources = { exitCode: "saída {{code}}", startFailed: "Falha ao iniciar {{scriptName}}", stopFailed: "Falha ao parar {{scriptName}}", + running: "Em execução", + runningCount: "{{count}} em execução", }, }, tree: { @@ -1688,14 +1691,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", }, diff --git a/packages/app/src/i18n/resources/ru.ts b/packages/app/src/i18n/resources/ru.ts index 086cd51c01..733596de39 100644 --- a/packages/app/src/i18n/resources/ru.ts +++ b/packages/app/src/i18n/resources/ru.ts @@ -736,6 +736,7 @@ export const ru: TranslationResources = { header: { actions: { workspaceActions: "Действия с рабочим пространством", + workspaceActionsUnhealthy: "Действия с рабочим пространством, есть неисправный сервис", newAgent: "Новый агент", newTerminal: "Новый терминал", newBrowser: "Новая вкладка браузера", @@ -784,6 +785,8 @@ export const ru: TranslationResources = { exitCode: "Код выхода: {{code}}", startFailed: "Не удалось запустить скрипт {{scriptName}}", stopFailed: "Не удалось остановить скрипт {{scriptName}}", + running: "Запущен", + runningCount: "Запущено: {{count}}", }, }, tree: { @@ -1686,14 +1689,19 @@ export const ru: TranslationResources = { title: "Добавить провайдера", search: "Поиск провайдеров", noProviders: "Провайдеры не найдены", + clearSearch: "Очистить поиск", actions: { add: "Добавить", + addProvider: "Добавить {{provider}}", adding: "Добавление", installed: "Установлено", cancel: "Отмена", installInstructions: "Инструкции по установке", installInstructionsFor: "Инструкции по установке {{provider}}", }, + types: { + acp: "ACP", + }, errors: { unableToInstall: "Не удалось установить провайдера", }, diff --git a/packages/app/src/i18n/resources/zh-CN.ts b/packages/app/src/i18n/resources/zh-CN.ts index 16dc24b3a5..c8627ca769 100644 --- a/packages/app/src/i18n/resources/zh-CN.ts +++ b/packages/app/src/i18n/resources/zh-CN.ts @@ -725,6 +725,7 @@ export const zhCN: TranslationResources = { header: { actions: { workspaceActions: "Workspace 操作", + workspaceActionsUnhealthy: "Workspace 操作,有服务异常", newAgent: "新建 Agent", newTerminal: "新建 Terminal", newBrowser: "新建浏览器标签", @@ -772,6 +773,8 @@ export const zhCN: TranslationResources = { exitCode: "exit {{code}}", startFailed: "启动 {{scriptName}} 失败", stopFailed: "停止 {{scriptName}} 失败", + running: "运行中", + runningCount: "{{count}} 个运行中", }, }, tree: { @@ -1640,14 +1643,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", }, diff --git a/packages/app/src/keyboard/keyboard-shortcuts.test.ts b/packages/app/src/keyboard/keyboard-shortcuts.test.ts index 571474643b..9e56ef66cd 100644 --- a/packages/app/src/keyboard/keyboard-shortcuts.test.ts +++ b/packages/app/src/keyboard/keyboard-shortcuts.test.ts @@ -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"); + }); +}); diff --git a/packages/app/src/keyboard/keyboard-shortcuts.ts b/packages/app/src/keyboard/keyboard-shortcuts.ts index 54d2b59cdb..a009008b85 100644 --- a/packages/app/src/keyboard/keyboard-shortcuts.ts +++ b/packages/app/src/keyboard/keyboard-shortcuts.ts @@ -1210,6 +1210,13 @@ export const DEFAULT_BINDINGS: readonly ParsedShortcutBinding[] = export type ShortcutOverrides = Record; +/** 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]; diff --git a/packages/app/src/keyboard/shortcut-string.ts b/packages/app/src/keyboard/shortcut-string.ts index 8b632befbd..6b80009633 100644 --- a/packages/app/src/keyboard/shortcut-string.ts +++ b/packages/app/src/keyboard/shortcut-string.ts @@ -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 = { + Digit: "1-9", ArrowLeft: "Left", ArrowRight: "Right", ArrowUp: "Up", diff --git a/packages/app/src/lib/overlay-root.browser.test.tsx b/packages/app/src/lib/overlay-root.browser.test.tsx index a21403dd8d..bd20d2aeeb 100644 --- a/packages/app/src/lib/overlay-root.browser.test.tsx +++ b/packages/app/src/lib/overlay-root.browser.test.tsx @@ -2,7 +2,11 @@ import React, { type RefCallback } from "react"; import { flushSync } from "react-dom"; import { createRoot, type Root } from "react-dom/client"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; -import { useWebOverlayRegistration } from "./overlay-root"; +import { + hasOpenDomPopover, + keyBelongsToDomPopover, + useWebOverlayRegistration, +} from "./overlay-root"; function nextFrame(): Promise { return new Promise((resolve) => requestAnimationFrame(() => resolve())); @@ -68,3 +72,35 @@ describe("useWebOverlayRegistration in the browser", () => { expect(openerFocusCalls).toBe(1); }); }); + +describe("hasOpenDomPopover", () => { + afterEach(() => { + document.body.replaceChildren(); + }); + + it("is true only while a popover is shown", () => { + const panel = document.createElement("div"); + panel.setAttribute("popover", "manual"); + document.body.append(panel); + expect(hasOpenDomPopover()).toBe(false); + panel.showPopover(); + expect(hasOpenDomPopover()).toBe(true); + panel.hidePopover(); + expect(hasOpenDomPopover()).toBe(false); + }); +}); + +describe("Escape with a plugin popover open", () => { + afterEach(() => { + document.body.replaceChildren(); + }); + + it("leaves other keys to the shortcuts while a popover is open", () => { + const panel = document.createElement("div"); + panel.setAttribute("popover", "manual"); + document.body.append(panel); + panel.showPopover(); + expect(keyBelongsToDomPopover({ key: "Enter" })).toBe(false); + expect(keyBelongsToDomPopover({ key: "Escape" })).toBe(true); + }); +}); diff --git a/packages/app/src/lib/overlay-root.ts b/packages/app/src/lib/overlay-root.ts index 9ffd81725f..d1ab0b9787 100644 --- a/packages/app/src/lib/overlay-root.ts +++ b/packages/app/src/lib/overlay-root.ts @@ -112,6 +112,31 @@ export function hasActiveWebOverlay(): boolean { return getTopWebOverlay() !== undefined; } +/** + * True while an element shown with the Popover API is open. Such a layer + * floats above the app like a registered overlay but lives outside the + * registry: plugins draw their panels this way, since they cannot register. + */ +export function hasOpenDomPopover(): boolean { + if (typeof document === "undefined") return false; + try { + return document.querySelector(":popover-open") !== null; + } catch { + // An engine without the Popover API rejects the selector, and has none open. + return false; + } +} + +/** + * Whether a key belongs to an open popover rather than to the app's shortcuts. + * An open popover (a plugin's panel) is the top layer and closes on its own + * Escape listener, which runs after the shortcut engine's capture listener: + * Escape must not also interrupt the running agent. + */ +export function keyBelongsToDomPopover(event: Pick): boolean { + return event.key === "Escape" && hasOpenDomPopover(); +} + function getFocusableElements(scope: HTMLElement): HTMLElement[] { const selector = [ "a[href]", diff --git a/packages/app/src/runtime/directory-sync/index.test.ts b/packages/app/src/runtime/directory-sync/index.test.ts index 5a247590d5..2dea552239 100644 --- a/packages/app/src/runtime/directory-sync/index.test.ts +++ b/packages/app/src/runtime/directory-sync/index.test.ts @@ -31,6 +31,7 @@ import { subscriptionFixture } from "../subscription-fixture"; type WorkspaceFetchResult = Awaited>; type ProjectListResult = Awaited>; type AgentFetchResult = Awaited>; +type WorkspaceScriptsResult = Awaited>; class FakeDirectoryClient { supportsBackgroundWorkspaces(): boolean { @@ -181,6 +182,14 @@ class FakeDirectoryClient { }; } + listWorkspaceScriptsCalls = 0; + workspaceScripts: WorkspaceScriptsResult["scripts"] = []; + + async listWorkspaceScripts(workspaceId: string): Promise { + this.listWorkspaceScriptsCalls += 1; + return { requestId: "scripts", workspaceId, scripts: this.workspaceScripts, error: null }; + } + getLastServerInfoMessage() { return this.supportsWorkspaceLabels ? { features: { workspaceLabels: true } } : null; } @@ -482,6 +491,52 @@ describe("DirectorySync session readiness", () => { directory.dispose(); }); + it("keeps a workspace's script status live without demanding the directory", async () => { + const serverId = "script-status-demand"; + const { client, directory } = createDirectory(serverId); + useSessionStore.getState().initializeSession(serverId, client as unknown as DaemonClient, 1); + const workspace = normalizeWorkspaceDescriptor({ + ...createWorkspaceEntry("workspace-1"), + scripts: [], + }); + directory.acceptWorkspaces([workspace]); + const script = { + scriptName: "worker", + type: "script" as const, + hostname: "worker.paseo.localhost", + port: null, + proxyUrl: null, + lifecycle: "running" as const, + health: null, + exitCode: null, + terminalId: "terminal-1", + }; + const lifecycle = () => + useSessionStore.getState().sessions[serverId]?.workspaces.get(workspace.id)?.scripts[0] + ?.lifecycle; + client.workspaceScripts = [script]; + const source = {}; + + directory.setScriptStatusDemand(source, workspace.id); + + await expect.poll(lifecycle).toBe("running"); + client.emit({ + type: "script_status_update", + payload: { workspaceId: workspace.id, scripts: [{ ...script, lifecycle: "stopped" }] }, + }); + expect(lifecycle()).toBe("stopped"); + expect(client.fetchAgentsCalls).toBe(0); + expect(client.fetchWorkspacesCalls).toBe(0); + + directory.setScriptStatusDemand(source, null); + client.emit({ + type: "script_status_update", + payload: { workspaceId: workspace.id, scripts: [script] }, + }); + expect(lifecycle()).toBe("stopped"); + directory.dispose(); + }); + it("subscribes to live agent updates when the directory is demanded", async () => { const serverId = "demanded-directory-subscription"; const { client, directory } = createDirectory(serverId); diff --git a/packages/app/src/runtime/directory-sync/index.ts b/packages/app/src/runtime/directory-sync/index.ts index 6589914825..28b217fea6 100644 --- a/packages/app/src/runtime/directory-sync/index.ts +++ b/packages/app/src/runtime/directory-sync/index.ts @@ -150,6 +150,7 @@ export class DirectorySync { private agentSubscription: OwnedSubscription | null = null; private workspaceSubscription: OwnedSubscription | null = null; private eventSubscription: ReturnType | null = null; + private scriptStatusSubscription: ReturnType | null = null; private readonly abortSessionWaits = new Set<() => void>(); private cacheLoad: Promise | null = null; private cacheAccepted = false; @@ -157,6 +158,7 @@ export class DirectorySync { private workspaceRevision = 0; private readonly routeDemandIds = new Set(); private readonly fullDemandSources = new Set(); + private readonly scriptStatusDemand = new Map(); private demandRefresh: Promise | null = null; private satisfiedDemandSource: DirectorySourceToken | null = null; private cursors: DirectoryCheckpoint = {}; @@ -189,10 +191,12 @@ export class DirectorySync { } this.flushAbortedTransactions(); this.releaseSubscriptions(); + this.releaseScriptStatusEvents(); workspaceLabels.disconnect(this.serverId); this.connection = connection; this.abortPendingSessionWaits(); if (!connection.client || connection.status !== "online") return true; + if (this.scriptStatusDemand.size > 0) this.observeScriptStatusEvents(); // Reattach labels here because route-only demand can satisfy the epoch before full demand requests them. void this.connectWorkspaceLabels().catch(() => undefined); if (this.hasDemand()) void this.requestDemandRefresh().catch(() => undefined); @@ -226,10 +230,32 @@ export class DirectorySync { } } + /** + * Keeps one workspace's script status live without demanding the directory: a + * script_status_update subscription, plus one scripts fetch to cover what changed before it. + */ + setScriptStatusDemand(source: object, workspaceId: string | null): void { + if (!workspaceId) { + this.scriptStatusDemand.delete(source); + if (!this.wantsScriptStatus()) this.releaseScriptStatusEvents(); + return; + } + this.scriptStatusDemand.set(source, workspaceId); + if (!this.getOnlineConnection()) return; + // A new subscription fetches every demanded workspace once its snapshot lands. + if (!this.scriptStatusSubscription) this.observeScriptStatusEvents(); + else + void this.scriptStatusSubscription.ready + .then(() => this.fetchScriptStatus(workspaceId)) + .catch(() => undefined); + } + dispose(): void { this.flushAbortedTransactions(); this.abortPendingSessionWaits(); + this.scriptStatusDemand.clear(); this.releaseSubscriptions(); + this.releaseScriptStatusEvents(); this.fullDemandSources.clear(); this.routeDemandIds.clear(); workspaceLabels.disconnect(this.serverId); @@ -247,6 +273,12 @@ export class DirectorySync { this.workspaceSubscription = null; this.eventSubscription = null; this.satisfiedDemandSource = null; + if (!this.wantsScriptStatus()) this.releaseScriptStatusEvents(); + } + + private releaseScriptStatusEvents(): void { + void this.scriptStatusSubscription?.release().catch(() => undefined); + this.scriptStatusSubscription = null; } private receiveAgentDelta(source: DirectorySourceToken, delta: AgentDirectoryDelta): void { @@ -276,22 +308,51 @@ export class DirectorySync { private observeDirectoryEvents(): void { if (this.eventSubscription) return; const { client, source } = this.requireOnline(); - this.eventSubscription = client.observeEvents(["project.update", "script_status_update"]); + this.eventSubscription = client.observeEvents(["project.update"]); this.eventSubscription.subscribe({ snapshot: () => {}, update: (message) => { if (!this.isCurrent(client, source)) return; if (message.type === "project.update") this.receiveWorkspaceDelta(source, message.payload); - if (message.type === "script_status_update") - this.receiveWorkspaceDelta(source, { kind: "script_status", update: message.payload }); }, }); } + // Script status has its own subscription so a workspace screen can hold it without the directory. + private observeScriptStatusEvents(): void { + if (this.scriptStatusSubscription) return; + const { client, source } = this.requireOnline(); + this.scriptStatusSubscription = client.observeEvents(["script_status_update"]); + this.scriptStatusSubscription.subscribe({ + snapshot: () => { + for (const workspaceId of new Set(this.scriptStatusDemand.values())) + void this.fetchScriptStatus(workspaceId).catch(() => undefined); + }, + update: (message) => { + if (!this.isCurrent(client, source) || message.type !== "script_status_update") return; + this.receiveWorkspaceDelta(source, { kind: "script_status", update: message.payload }); + }, + }); + } + + private async fetchScriptStatus(workspaceId: string): Promise { + const { client, source } = this.requireOnline(); + const result = await client.listWorkspaceScripts(workspaceId); + if (!this.isCurrent(client, source) || result.error || !result.scripts) return; + this.receiveWorkspaceDelta(source, { + kind: "script_status", + update: { workspaceId, scripts: result.scripts }, + }); + } + private hasDemand(): boolean { return this.fullDemandSources.size > 0 || this.routeDemandIds.size > 0; } + private wantsScriptStatus(): boolean { + return this.hasDemand() || this.scriptStatusDemand.size > 0; + } + private requestDemandRefresh(force = false): Promise { if (this.demandRefresh) return this.demandRefresh; if (!this.hasDemand()) return Promise.resolve(); @@ -299,6 +360,7 @@ export class DirectorySync { return this.fullDemandSources.size > 0 ? this.loadCachedDirectory() : Promise.resolve(); } this.observeDirectoryEvents(); + this.observeScriptStatusEvents(); const source = this.connection.source; if ( !force && diff --git a/packages/app/src/runtime/host-runtime.ts b/packages/app/src/runtime/host-runtime.ts index 2ecbe60448..55298ce5a1 100644 --- a/packages/app/src/runtime/host-runtime.ts +++ b/packages/app/src/runtime/host-runtime.ts @@ -2606,6 +2606,14 @@ export class HostRuntimeStore { return () => directory.setDemand(source, false); } + acquireScriptStatusDemand(serverId: string, workspaceId: string): () => void { + const directory = this.directorySyncByServer.get(serverId); + if (!directory) return () => undefined; + const source = {}; + directory.setScriptStatusDemand(source, workspaceId); + return () => directory.setScriptStatusDemand(source, null); + } + async prepareAgentRoute(serverId: string, agentId: string): Promise { const directory = this.directorySyncByServer.get(serverId); if (!directory) throw new Error(`Unknown host runtime for serverId ${serverId}`); diff --git a/packages/app/src/runtime/replica-cache/index.test.ts b/packages/app/src/runtime/replica-cache/index.test.ts index 76e9e66464..15adc841fb 100644 --- a/packages/app/src/runtime/replica-cache/index.test.ts +++ b/packages/app/src/runtime/replica-cache/index.test.ts @@ -464,6 +464,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 +517,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 +554,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 +858,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 +920,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 () => { diff --git a/packages/app/src/runtime/replica-cache/index.ts b/packages/app/src/runtime/replica-cache/index.ts index 3fc8458551..94937d4dc5 100644 --- a/packages/app/src/runtime/replica-cache/index.ts +++ b/packages/app/src/runtime/replica-cache/index.ts @@ -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(); - private readonly hostRevisions = new Map(); + private readonly activeReads = new Set(); private readonly storedRows = new Map>(); private readonly hostBytes = new Map(); private readonly hostWriteOrder = new Map(); @@ -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(); @@ -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()], diff --git a/packages/app/src/screens/settings-screen.tsx b/packages/app/src/screens/settings-screen.tsx index 925607a858..3950c0778e 100644 --- a/packages/app/src/screens/settings-screen.tsx +++ b/packages/app/src/screens/settings-screen.tsx @@ -120,6 +120,7 @@ import { MetadataGenerationPage } from "@/screens/settings/metadata-generation-p import ProjectsScreen from "@/screens/projects-screen"; import ProjectSettingsScreen from "@/screens/project-settings-screen"; import { SETTINGS_DESKTOP_SIDEBAR_WIDTH, useIsCompactFormFactor } from "@/constants/layout"; +import { densityIconBox, densityIconSize } from "@/styles/density"; import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon"; import { type EnableBuiltInDaemonOption, @@ -758,7 +759,7 @@ function SidebarSectionButton({ isSelected, onSelect, }: SidebarSectionButtonProps) { - const { theme } = useUnistyles(); + const { theme, rt } = useUnistyles(); const handlePress = useCallback(() => { onSelect(itemId); }, [onSelect, itemId]); @@ -775,7 +776,7 @@ function SidebarSectionButton({ style={isSelected ? selectedSidebarItemStyle : sidebarItemStyle} > @@ -801,7 +802,7 @@ function SidebarHostSectionButton({ isSelected, onSelect, }: SidebarHostSectionButtonProps) { - const { theme } = useUnistyles(); + const { theme, rt } = useUnistyles(); const handlePress = useCallback(() => { onSelect(itemId); }, [onSelect, itemId]); @@ -819,7 +820,7 @@ function SidebarHostSectionButton({ style={isSelected ? selectedSidebarItemStyle : sidebarItemStyle} > @@ -912,6 +913,16 @@ function HostPicker({ ); } +/** A labelled group of sidebar rows. On compact layouts the rows sit together in one island. */ +function SidebarGroup({ label, children }: { label?: string; children: ReactNode }) { + return ( + + {label ? {label} : null} + {children} + + ); +} + interface SettingsSidebarProps { view: SettingsView; onSelectSection: (section: SettingsSectionSlug) => void; @@ -933,7 +944,7 @@ function SettingsSidebar({ activeHostServerId, layout, }: SettingsSidebarProps) { - const { theme } = useUnistyles(); + const { theme, rt } = useUnistyles(); const { t } = useTranslation(); const hosts = useHosts(); const localServerId = useLocalDaemonServerId(); @@ -960,8 +971,7 @@ function SettingsSidebar({ const sidebarBody = ( <> - - {t("settings.groups.app")} + {items.map((item) => ( ))} - + {hasHosts ? ( - - {t("settings.groups.host")} + ))} - + ) : ( - + @@ -1021,7 +1030,7 @@ function SettingsSidebar({ style={sidebarItemStyle} > @@ -1030,7 +1039,7 @@ function SettingsSidebar({ ) : null} - + )} ); @@ -1572,26 +1581,33 @@ const sidebarStyles = StyleSheet.create((theme) => ({ paddingVertical: theme.spacing[2], paddingHorizontal: theme.spacing[2], }, - list: { + // Compact values draw each group as an island of tiles; desktop keeps a plain list. + group: { paddingVertical: theme.spacing[2], paddingHorizontal: theme.spacing[2], - gap: theme.spacing[0.5], + gap: { xs: theme.spacing[1], md: theme.spacing[0.5] }, }, groupLabel: { fontSize: theme.fontSize.base, fontWeight: theme.fontWeight.normal, color: theme.colors.foregroundExtraMuted, - paddingHorizontal: theme.spacing[2], + paddingHorizontal: { xs: theme.spacing[4], md: theme.spacing[2] }, paddingVertical: theme.spacing[1], }, + island: { + gap: { xs: 2, md: theme.spacing[0.5] }, + borderRadius: { xs: theme.borderRadius["2xl"], md: 0 }, + overflow: "hidden", + }, item: { flexDirection: "row", alignItems: "center", - gap: theme.spacing[2], - minHeight: 28, + gap: { xs: theme.spacing[3], md: theme.spacing[2] }, + minHeight: { xs: 52, md: 28 }, paddingVertical: theme.spacing[1], - paddingHorizontal: theme.spacing[2], - borderRadius: theme.borderRadius.lg, + paddingHorizontal: { xs: theme.spacing[4], md: theme.spacing[2] }, + borderRadius: { xs: 0, md: theme.borderRadius.lg }, + backgroundColor: { xs: theme.colors.surface1, md: "transparent" }, }, itemHovered: { backgroundColor: theme.colors.surfaceSidebarHover, @@ -1600,7 +1616,7 @@ const sidebarStyles = StyleSheet.create((theme) => ({ backgroundColor: theme.colors.surfaceSidebarHover, }, label: { - fontSize: theme.fontSize.base, + fontSize: { xs: theme.fontSize.lg, md: theme.fontSize.base }, color: theme.colors.foregroundMuted, fontWeight: theme.fontWeight.normal, flex: 1, @@ -1608,11 +1624,12 @@ const sidebarStyles = StyleSheet.create((theme) => ({ pickerTrigger: { flexDirection: "row", alignItems: "center", - gap: theme.spacing[2], - minHeight: 28, + gap: { xs: theme.spacing[3], md: theme.spacing[2] }, + minHeight: { xs: 52, md: 28 }, paddingVertical: theme.spacing[1], - paddingHorizontal: theme.spacing[2], - borderRadius: theme.borderRadius.lg, + paddingHorizontal: { xs: theme.spacing[4], md: theme.spacing[2] }, + borderRadius: { xs: 0, md: theme.borderRadius.lg }, + backgroundColor: { xs: theme.colors.surface1, md: "transparent" }, }, pickerTriggerHovered: { backgroundColor: theme.colors.surfaceSidebarHover, @@ -1620,14 +1637,14 @@ const sidebarStyles = StyleSheet.create((theme) => ({ pickerTriggerLabel: { flex: 1, minWidth: 0, - fontSize: theme.fontSize.base, + fontSize: { xs: theme.fontSize.lg, md: theme.fontSize.base }, color: theme.colors.foreground, fontWeight: theme.fontWeight.normal, }, // Match the setting items' icon footprint so the host label aligns with them. pickerTriggerDot: { - width: theme.iconSize.md, - height: theme.iconSize.md, + width: densityIconBox("md"), + height: densityIconBox("md"), alignItems: "center", justifyContent: "center", }, diff --git a/packages/app/src/screens/settings/keyboard-shortcuts-section.tsx b/packages/app/src/screens/settings/keyboard-shortcuts-section.tsx index 3798a5f9bd..8a8c4b42b9 100644 --- a/packages/app/src/screens/settings/keyboard-shortcuts-section.tsx +++ b/packages/app/src/screens/settings/keyboard-shortcuts-section.tsx @@ -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); diff --git a/packages/app/src/screens/settings/providers-section.test.tsx b/packages/app/src/screens/settings/providers-section.test.tsx index 77aaa4d8ec..0a702ae641 100644 --- a/packages/app/src/screens/settings/providers-section.test.tsx +++ b/packages/app/src/screens/settings/providers-section.test.tsx @@ -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(); + root?.render( + + + , + ); }); } diff --git a/packages/app/src/screens/settings/providers-section.tsx b/packages/app/src/screens/settings/providers-section.tsx index 4fb0a43278..72234b7602 100644 --- a/packages/app/src/screens/settings/providers-section.tsx +++ b/packages/app/src/screens/settings/providers-section.tsx @@ -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 ( diff --git a/packages/app/src/screens/workspace/scripts/index.ts b/packages/app/src/screens/workspace/scripts/index.ts new file mode 100644 index 0000000000..efff482e80 --- /dev/null +++ b/packages/app/src/screens/workspace/scripts/index.ts @@ -0,0 +1,10 @@ +/** + * Workspace scripts: the desktop header popover, and the pages the compact header menu carries. + * Both share one set of actions and one reading of script status. + */ +export { WorkspaceScriptsButton } from "./workspace-scripts-button"; +export { + useWorkspaceScriptsMenuPages, + type UseWorkspaceScriptsMenuPagesInput, + type WorkspaceScriptsMenuPages, +} from "./workspace-scripts-menu-pages"; diff --git a/packages/app/src/screens/workspace/scripts/script-marks.tsx b/packages/app/src/screens/workspace/scripts/script-marks.tsx new file mode 100644 index 0000000000..ae4f9a9edb --- /dev/null +++ b/packages/app/src/screens/workspace/scripts/script-marks.tsx @@ -0,0 +1,78 @@ +import type { ReactElement } from "react"; +import { Text, View } from "react-native"; +import { Globe, SquareTerminal } from "lucide-react-native"; +import { StyleSheet, withUnistyles } from "react-native-unistyles"; +import { useTranslation } from "react-i18next"; +import type { WorkspaceDescriptor } from "@/stores/session-store"; +import type { WorkspaceScriptLinkKind } from "@/utils/workspace-script-links"; +import { scriptStatus, scriptToneColorMapping } from "./script-status"; + +const ThemedGlobe = withUnistyles(Globe); +const ThemedSquareTerminal = withUnistyles(SquareTerminal); + +/** A globe for a service, a terminal for a plain script, in the colour of what it is doing. */ +export function ScriptIcon({ + script, + size, +}: { + script: WorkspaceDescriptor["scripts"][number]; + size: number; +}): ReactElement { + const Icon = script.type === "service" ? ThemedGlobe : ThemedSquareTerminal; + return ( + + ); +} + +export function ExitCodeBadge({ code }: { code: number }): ReactElement { + const { t } = useTranslation(); + const exitTextStyle = + code === 0 ? styles.exitBadgeText : [styles.exitBadgeText, styles.exitBadgeTextError]; + return ( + + {t("workspace.scripts.states.exitCode", { code })} + + ); +} + +/** The label of a URL route, as the user picks between them. */ +export function routeLabelKey( + kind: WorkspaceScriptLinkKind, +): + | "workspace.scripts.routes.public" + | "workspace.scripts.routes.paseo" + | "workspace.scripts.routes.direct" { + switch (kind) { + case "public": + return "workspace.scripts.routes.public"; + case "paseo": + return "workspace.scripts.routes.paseo"; + case "direct": + return "workspace.scripts.routes.direct"; + } +} + +const styles = StyleSheet.create((theme) => ({ + scriptIcon: { + flexShrink: 0, + }, + exitBadge: { + paddingHorizontal: theme.spacing[1.5], + paddingVertical: 1, + borderRadius: 2, + backgroundColor: theme.colors.surface2, + }, + exitBadgeText: { + fontSize: 10, + lineHeight: 12, + fontWeight: theme.fontWeight.medium, + color: theme.colors.foregroundMuted, + }, + exitBadgeTextError: { + color: theme.colors.statusDanger, + }, +})); diff --git a/packages/app/src/screens/workspace/scripts/script-status.test.ts b/packages/app/src/screens/workspace/scripts/script-status.test.ts new file mode 100644 index 0000000000..7ca5dc81b3 --- /dev/null +++ b/packages/app/src/screens/workspace/scripts/script-status.test.ts @@ -0,0 +1,89 @@ +import { describe, expect, it } from "vitest"; +import type { WorkspaceScriptPayload } from "@getpaseo/protocol/messages"; +import { scriptStatus, summarizeScripts } from "./script-status"; + +function service( + scriptName: string, + state: Pick, +): WorkspaceScriptPayload { + return { ...script(scriptName, state.lifecycle), type: "service", health: state.health }; +} + +function script( + scriptName: string, + lifecycle: WorkspaceScriptPayload["lifecycle"], +): WorkspaceScriptPayload { + return { + scriptName, + type: "script", + hostname: scriptName, + port: null, + proxyUrl: null, + lifecycle, + health: null, + exitCode: null, + terminalId: null, + }; +} + +describe("scriptStatus", () => { + it("colours services by their health and plain scripts by whether they run", () => { + expect(scriptStatus(script("lint", "stopped"))).toBe("idle"); + expect(scriptStatus(script("lint", "running"))).toBe("running"); + expect(scriptStatus(service("web", { lifecycle: "stopped", health: "unhealthy" }))).toBe( + "idle", + ); + expect(scriptStatus(service("web", { lifecycle: "running", health: null }))).toBe("running"); + expect(scriptStatus(service("web", { lifecycle: "running", health: "healthy" }))).toBe( + "healthy", + ); + expect(scriptStatus(service("web", { lifecycle: "running", health: "unhealthy" }))).toBe( + "unhealthy", + ); + }); +}); + +describe("summarizeScripts", () => { + it("is idle with nothing running when nothing runs", () => { + expect(summarizeScripts([])).toEqual({ tone: "idle", running: [] }); + expect(summarizeScripts([script("lint", "stopped")])).toEqual({ tone: "idle", running: [] }); + }); + + it("lists the running scripts by name", () => { + expect( + summarizeScripts([ + script("lint", "stopped"), + service("web", { lifecycle: "running", health: null }), + ]), + ).toEqual({ tone: "running", running: ["web"] }); + }); + + it("is unhealthy when any running service is", () => { + expect( + summarizeScripts([ + service("web", { lifecycle: "running", health: "healthy" }), + service("api", { lifecycle: "running", health: "unhealthy" }), + ]), + ).toEqual({ tone: "unhealthy", running: ["web", "api"] }); + }); + + it("is healthy only when every running service reports healthy", () => { + expect( + summarizeScripts([ + script("lint", "running"), + service("web", { lifecycle: "running", health: "healthy" }), + service("api", { lifecycle: "stopped", health: "unhealthy" }), + ]), + ).toEqual({ tone: "healthy", running: ["lint", "web"] }); + expect( + summarizeScripts([ + service("web", { lifecycle: "running", health: "healthy" }), + service("api", { lifecycle: "running", health: null }), + ]), + ).toEqual({ tone: "running", running: ["web", "api"] }); + expect(summarizeScripts([script("lint", "running")])).toEqual({ + tone: "running", + running: ["lint"], + }); + }); +}); diff --git a/packages/app/src/screens/workspace/scripts/script-status.ts b/packages/app/src/screens/workspace/scripts/script-status.ts new file mode 100644 index 0000000000..ff7398dda4 --- /dev/null +++ b/packages/app/src/screens/workspace/scripts/script-status.ts @@ -0,0 +1,63 @@ +import type { WorkspaceScriptPayload } from "@getpaseo/protocol/messages"; +import type { Theme } from "@/styles/theme"; + +/** + * What a script, or a set of them, is doing, as the one colour its ▶ or row icon is drawn in. + * + * Health is a service's own report, so it only colours running services. A plain script that is + * running is just running. + */ +export type ScriptTone = "idle" | "running" | "healthy" | "unhealthy"; + +export interface ScriptsSummary { + tone: ScriptTone; + /** Names of the running scripts, in the order the workspace lists them. */ + running: string[]; +} + +export function scriptStatus(script: WorkspaceScriptPayload): ScriptTone { + if (script.lifecycle !== "running") return "idle"; + if (script.type !== "service") return "running"; + if (script.health === "healthy") return "healthy"; + if (script.health === "unhealthy") return "unhealthy"; + return "running"; +} + +/** + * One unhealthy service makes the whole set unhealthy. The set reads healthy only when every + * running service says so; a service that has not reported yet keeps it at plain running. + */ +export function summarizeScripts(scripts: readonly WorkspaceScriptPayload[]): ScriptsSummary { + const running = scripts.filter((script) => script.lifecycle === "running"); + if (running.length === 0) return { tone: "idle", running: [] }; + return { tone: aggregateTone(running), running: running.map((script) => script.scriptName) }; +} + +function aggregateTone(running: readonly WorkspaceScriptPayload[]): ScriptTone { + const serviceTones = running + .filter((script) => script.type === "service") + .map((script) => scriptStatus(script)); + if (serviceTones.includes("unhealthy")) return "unhealthy"; + if (serviceTones.length > 0 && serviceTones.every((tone) => tone === "healthy")) { + return "healthy"; + } + return "running"; +} + +const idleColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted }); +const runningColorMapping = (theme: Theme) => ({ color: theme.colors.palette.blue[500] }); +const healthyColorMapping = (theme: Theme) => ({ color: theme.colors.palette.green[500] }); +const unhealthyColorMapping = (theme: Theme) => ({ color: theme.colors.palette.red[500] }); + +export function scriptToneColorMapping(tone: ScriptTone): (theme: Theme) => { color: string } { + switch (tone) { + case "idle": + return idleColorMapping; + case "running": + return runningColorMapping; + case "healthy": + return healthyColorMapping; + case "unhealthy": + return unhealthyColorMapping; + } +} diff --git a/packages/app/src/screens/workspace/scripts/use-workspace-script-actions.ts b/packages/app/src/screens/workspace/scripts/use-workspace-script-actions.ts new file mode 100644 index 0000000000..fb7809990f --- /dev/null +++ b/packages/app/src/screens/workspace/scripts/use-workspace-script-actions.ts @@ -0,0 +1,191 @@ +import { useCallback, useEffect, useMemo, useRef } from "react"; +import * as Clipboard from "expo-clipboard"; +import { useMutation } from "@tanstack/react-query"; +import { useTranslation } from "react-i18next"; +import type { WorkspaceDescriptor } from "@/stores/session-store"; +import { useSessionStore } from "@/stores/session-store"; +import { useHostRuntimeSnapshot } from "@/runtime/host-runtime"; +import { useToast } from "@/contexts/toast-context"; +import { + resolveWorkspaceScriptLink, + type WorkspaceScriptLinkKind, + type WorkspaceScriptLinkTarget, +} from "@/utils/workspace-script-links"; +import { useWorkspaceServiceRoutePreferencesStore } from "@/workspace-service-routes/store"; + +type WorkspaceScript = WorkspaceDescriptor["scripts"][number]; + +export interface WorkspaceScriptLinks { + /** The URL this host's route preference picks, or null when the script serves none. */ + selected: WorkspaceScriptLinkTarget | null; + targets: WorkspaceScriptLinkTarget[]; +} + +export interface WorkspaceScriptActions { + start: (scriptName: string) => void; + stop: (scriptName: string) => void; + /** Stops the script, then starts it again once the daemon reports it stopped. */ + restart: (scriptName: string) => void; + copyUrl: (target: WorkspaceScriptLinkTarget) => void; + selectRoute: (kind: WorkspaceScriptLinkKind) => void; + resolveLinks: (script: WorkspaceScript) => WorkspaceScriptLinks; + isStartPending: boolean; + isStopPending: boolean; +} + +export interface UseWorkspaceScriptActionsInput { + serverId: string; + workspaceId: string; + scripts: WorkspaceDescriptor["scripts"]; + onScriptTerminalStarted?: (terminalId: string) => void; +} + +/** + * Run, stop, restart and URL handling for a workspace's scripts, shared by every surface that + * lists them. + * + * A restart outlives the press that asked for it — the second half waits for the daemon to + * report the script stopped — so mount this with whatever owns the menu, not inside a menu page + * that unmounts when the menu closes. + */ +export function useWorkspaceScriptActions({ + serverId, + workspaceId, + scripts, + onScriptTerminalStarted, +}: UseWorkspaceScriptActionsInput): WorkspaceScriptActions { + const { t } = useTranslation(); + const toast = useToast(); + const client = useSessionStore((state) => state.sessions[serverId]?.client ?? null); + const activeConnection = useHostRuntimeSnapshot(serverId)?.activeConnection ?? null; + const preferredRouteKind = useWorkspaceServiceRoutePreferencesStore( + (state) => state.byServerId[serverId] ?? null, + ); + const setPreferredRoute = useWorkspaceServiceRoutePreferencesStore( + (state) => state.setPreferredRoute, + ); + const pendingRestartRef = useRef>(new Set()); + + const startScriptMutation = useMutation({ + mutationFn: async (scriptName: string) => { + if (!client) { + throw new Error(t("common.errors.daemonClientUnavailable")); + } + const result = await client.startWorkspaceScript(workspaceId, scriptName); + if (result.error) { + throw new Error(result.error); + } + return result; + }, + onError: (error, scriptName) => { + toast.show( + error instanceof Error + ? error.message + : t("workspace.scripts.states.startFailed", { scriptName }), + { + variant: "error", + }, + ); + }, + onSuccess: (result) => { + if (result.terminalId) { + onScriptTerminalStarted?.(result.terminalId); + } + }, + }); + const startScript = startScriptMutation.mutate; + + const stopScriptMutation = useMutation({ + mutationFn: async (scriptName: string) => { + if (!client) { + throw new Error(t("common.errors.daemonClientUnavailable")); + } + const terminalId = scripts.find((s) => s.scriptName === scriptName)?.terminalId; + if (!terminalId) { + throw new Error(t("workspace.scripts.states.stopFailed", { scriptName })); + } + const result = await client.killTerminal(terminalId); + if (!result.success) { + throw new Error(t("workspace.scripts.states.stopFailed", { scriptName })); + } + }, + onError: (error, scriptName) => { + pendingRestartRef.current.delete(scriptName); + toast.show( + error instanceof Error + ? error.message + : t("workspace.scripts.states.stopFailed", { scriptName }), + { + variant: "error", + }, + ); + }, + }); + const stopScript = stopScriptMutation.mutate; + + // Restart = kill the script terminal, then start again once the daemon + // reports the script as stopped (it tears the runtime entry down on exit). + useEffect(() => { + const pending = pendingRestartRef.current; + if (pending.size === 0) return; + for (const script of scripts) { + if (!pending.has(script.scriptName) || script.lifecycle === "running") continue; + pending.delete(script.scriptName); + startScript(script.scriptName); + } + }, [scripts, startScript]); + + const restart = useCallback( + (scriptName: string) => { + pendingRestartRef.current.add(scriptName); + stopScript(scriptName); + }, + [stopScript], + ); + + const copyUrl = useCallback( + (target: WorkspaceScriptLinkTarget) => { + void Clipboard.setStringAsync(target.url); + toast.copied(target.label); + }, + [toast], + ); + + const selectRoute = useCallback( + (kind: WorkspaceScriptLinkKind) => setPreferredRoute(serverId, kind), + [serverId, setPreferredRoute], + ); + + const resolveLinks = useCallback( + (script: WorkspaceScript): WorkspaceScriptLinks => { + const link = resolveWorkspaceScriptLink({ script, activeConnection }); + const selected = + link.targets.find((target) => target.kind === preferredRouteKind) ?? link.primary; + return { selected, targets: link.targets }; + }, + [activeConnection, preferredRouteKind], + ); + + return useMemo( + () => ({ + start: startScript, + stop: stopScript, + restart, + copyUrl, + selectRoute, + resolveLinks, + isStartPending: startScriptMutation.isPending, + isStopPending: stopScriptMutation.isPending, + }), + [ + startScript, + stopScript, + restart, + copyUrl, + selectRoute, + resolveLinks, + startScriptMutation.isPending, + stopScriptMutation.isPending, + ], + ); +} diff --git a/packages/app/src/screens/workspace/workspace-scripts-button.test.tsx b/packages/app/src/screens/workspace/scripts/workspace-scripts-button.test.tsx similarity index 96% rename from packages/app/src/screens/workspace/workspace-scripts-button.test.tsx rename to packages/app/src/screens/workspace/scripts/workspace-scripts-button.test.tsx index 82e0132cd3..290f424e97 100644 --- a/packages/app/src/screens/workspace/workspace-scripts-button.test.tsx +++ b/packages/app/src/screens/workspace/scripts/workspace-scripts-button.test.tsx @@ -8,7 +8,7 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import type { WorkspaceScriptPayload } from "@getpaseo/protocol/messages"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { createRoot } from "react-dom/client"; -import { WorkspaceScriptsButton } from "@/screens/workspace/workspace-scripts-button"; +import { WorkspaceScriptsButton } from "./workspace-scripts-button"; void testI18n; @@ -235,7 +235,6 @@ const LIVE_TERMINAL_IDS: string[] = ["terminal-script-1"]; interface RenderScriptsOptions { hideLabels?: boolean; - presentation?: "split" | "ghost"; } function renderScripts( @@ -264,7 +263,6 @@ function renderScripts( scripts={nextScripts} liveTerminalIds={LIVE_TERMINAL_IDS} hideLabels={options.hideLabels} - presentation={options.presentation} /> ); @@ -431,17 +429,6 @@ describe("WorkspaceScriptsButton", () => { ); }); - it("removes the trigger caret in ghost presentation", () => { - current = renderScripts([script({ scriptName: "dev" })], { - hideLabels: true, - presentation: "ghost", - }); - - const trigger = document.querySelector('[data-testid="workspace-scripts-button"]'); - expect(trigger?.querySelector('[data-icon="Play"]')?.getAttribute("data-size")).toBe("16"); - expect(trigger?.querySelector('[data-icon="ChevronDown"]')).toBeNull(); - }); - it("keeps the trigger caret in split presentation", () => { current = renderScripts([script({ scriptName: "dev" })]); diff --git a/packages/app/src/screens/workspace/workspace-scripts-button.tsx b/packages/app/src/screens/workspace/scripts/workspace-scripts-button.tsx similarity index 63% rename from packages/app/src/screens/workspace/workspace-scripts-button.tsx rename to packages/app/src/screens/workspace/scripts/workspace-scripts-button.tsx index 59ddd9a0fb..3a1c472518 100644 --- a/packages/app/src/screens/workspace/workspace-scripts-button.tsx +++ b/packages/app/src/screens/workspace/scripts/workspace-scripts-button.tsx @@ -1,13 +1,10 @@ -import { useCallback, useEffect, useMemo, useRef, type ReactElement } from "react"; +import { useCallback, useMemo, type ReactElement } from "react"; import type { GestureResponderEvent } from "react-native"; import { Pressable, Text, View } from "react-native"; -import * as Clipboard from "expo-clipboard"; -import { useMutation } from "@tanstack/react-query"; import { ChevronDown, Copy, Eye, - Globe, Play, RotateCw, Square, @@ -16,8 +13,6 @@ import { import { StyleSheet, withUnistyles } from "react-native-unistyles"; import { useTranslation } from "react-i18next"; import type { WorkspaceDescriptor } from "@/stores/session-store"; -import { useSessionStore } from "@/stores/session-store"; -import { useHostRuntimeSnapshot } from "@/runtime/host-runtime"; import { DropdownMenu, DropdownMenuContent, @@ -27,17 +22,20 @@ import { } from "@/components/ui/dropdown-menu"; import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; import { MENU_ITEM_HEIGHT } from "@/components/ui/menu/menu-geometry"; -import { useToast } from "@/contexts/toast-context"; import { openServiceUrl } from "@/utils/open-service-url"; -import { - resolveWorkspaceScriptLink, - type WorkspaceScriptLinkKind, - type WorkspaceScriptLinkTarget, +import type { + WorkspaceScriptLinkKind, + WorkspaceScriptLinkTarget, } from "@/utils/workspace-script-links"; import type { Theme } from "@/styles/theme"; -import { useWorkspaceServiceRoutePreferencesStore } from "@/workspace-service-routes/store"; import { buttonControlHeight, HEADER_CONTROL_HEIGHT } from "@/components/ui/control-geometry"; import { extraMutedIconColorMapping } from "@/components/ui/icon-color"; +import { ExitCodeBadge, routeLabelKey, ScriptIcon } from "./script-marks"; +import { scriptToneColorMapping } from "./script-status"; +import { + useWorkspaceScriptActions, + type WorkspaceScriptActions, +} from "./use-workspace-script-actions"; type RowActionIcon = "copy" | "open" | "restart" | "start" | "stop" | "terminal"; @@ -50,37 +48,23 @@ interface WorkspaceScriptsButtonProps { onViewTerminal?: (terminalId: string) => void; onOpenUrlInBrowserTab?: (url: string) => void; hideLabels?: boolean; - presentation?: "split" | "ghost"; } const ThemedPlay = withUnistyles(Play); const ThemedSquareTerminal = withUnistyles(SquareTerminal); -const ThemedGlobe = withUnistyles(Globe); const ThemedChevronDown = withUnistyles(ChevronDown); const ThemedEye = withUnistyles(Eye); const ThemedCopy = withUnistyles(Copy); const ThemedRotateCw = withUnistyles(RotateCw); const ThemedSquare = withUnistyles(Square); -const GHOST_TRIGGER_ICON_SIZE = 16; - const foregroundColorMapping = (theme: Theme) => ({ color: theme.colors.foreground, }); const mutedColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted, }); -const blueColorMapping = (theme: Theme) => ({ - color: theme.colors.palette.blue[500], -}); -const greenColorMapping = (theme: Theme) => ({ - color: theme.colors.palette.green[500], -}); -const redColorMapping = (theme: Theme) => ({ - color: theme.colors.palette.red[500], -}); const playFillTransparent = { fill: "transparent" }; -const ghostPlayStroke = { strokeWidth: 1.5 }; interface ScriptRowActionButtonProps { accessibilityLabel: string; @@ -163,23 +147,7 @@ interface ServiceLinkRowProps { targets: WorkspaceScriptLinkTarget[]; scriptName: string; onSelectKind: (kind: WorkspaceScriptLinkKind) => void; - onCopy: (url: string, label: string) => void; -} - -function routeLabelKey( - kind: WorkspaceScriptLinkKind, -): - | "workspace.scripts.routes.public" - | "workspace.scripts.routes.paseo" - | "workspace.scripts.routes.direct" { - switch (kind) { - case "public": - return "workspace.scripts.routes.public"; - case "paseo": - return "workspace.scripts.routes.paseo"; - case "direct": - return "workspace.scripts.routes.direct"; - } + onCopy: (target: WorkspaceScriptLinkTarget) => void; } function ServiceRouteOption({ @@ -298,12 +266,12 @@ function ServiceLinkRow({ }: ServiceLinkRowProps): ReactElement { const { t } = useTranslation(); const closeMenu = useDropdownMenuClose(); - const { label, url } = selectedTarget; + const { label } = selectedTarget; const handleCopy = useCallback(() => { closeMenu(); - onCopy(url, label); - }, [url, label, onCopy, closeMenu]); + onCopy(selectedTarget); + }, [selectedTarget, onCopy, closeMenu]); return ( @@ -333,84 +301,29 @@ function ServiceLinkRow({ ); } -function ExitCodeBadge({ code }: { code: number }): ReactElement { - const { t } = useTranslation(); - const exitTextStyle = - code === 0 ? styles.exitBadgeText : [styles.exitBadgeText, styles.exitBadgeTextError]; - return ( - - {t("workspace.scripts.states.exitCode", { code })} - - ); -} - interface ScriptRowProps { script: WorkspaceDescriptor["scripts"][number]; liveTerminalIdSet: Set; - activeConnection: ReturnType extends infer R - ? R extends { activeConnection: infer A } - ? A - : null - : null; - isStartPending: boolean; - isStopPending: boolean; - onStartScript: (scriptName: string) => void; - onStopScript: (scriptName: string) => void; - onRestartScript: (scriptName: string) => void; - onCopyUrl: (url: string, label: string) => void; - preferredRouteKind: WorkspaceScriptLinkKind | null; - onSelectRouteKind: (kind: WorkspaceScriptLinkKind) => void; + actions: WorkspaceScriptActions; onViewTerminal?: (terminalId: string) => void; onOpenUrlInBrowserTab?: (url: string) => void; } -function resolveScriptIconColorMapping(args: { - script: WorkspaceDescriptor["scripts"][number]; - isService: boolean; - isRunning: boolean; -}): (theme: Theme) => { color: string } { - const { script, isService, isRunning } = args; - if (isService) { - if (isRunning && script.health === "healthy") return greenColorMapping; - if (isRunning && script.health === "unhealthy") return redColorMapping; - if (isRunning) return blueColorMapping; - return mutedColorMapping; - } - if (isRunning) return blueColorMapping; - return mutedColorMapping; -} - function ScriptRow({ script, liveTerminalIdSet, - activeConnection, - isStartPending, - isStopPending, - onStartScript, - onStopScript, - onRestartScript, - onCopyUrl, - preferredRouteKind, - onSelectRouteKind, + actions, onViewTerminal, onOpenUrlInBrowserTab, }: ScriptRowProps): ReactElement { const { t } = useTranslation(); const isRunning = script.lifecycle === "running"; - const isService = (script.type ?? "service") === "service"; const exitCode = script.exitCode ?? null; - const serviceLink = resolveWorkspaceScriptLink({ script, activeConnection }); - const selectedLink = - isService && isRunning - ? (serviceLink.targets.find((target) => target.kind === preferredRouteKind) ?? - serviceLink.primary) - : null; + const { selected: selectedLink, targets: linkTargets } = actions.resolveLinks(script); const liveTerminalId = script.terminalId && liveTerminalIdSet.has(script.terminalId) ? script.terminalId : null; - - const iconColorMapping = resolveScriptIconColorMapping({ script, isService, isRunning }); - const ScriptIcon = isService ? ThemedGlobe : ThemedSquareTerminal; const showExitBadge = !isRunning && exitCode !== null; + const { start, stop, restart } = actions; const closeMenu = useDropdownMenuClose(); const handleOpenService = useCallback(() => { @@ -424,16 +337,16 @@ function ScriptRow({ }, [liveTerminalId, onViewTerminal]); const handleRun = useCallback(() => { - onStartScript(script.scriptName); - }, [onStartScript, script.scriptName]); + start(script.scriptName); + }, [start, script.scriptName]); const handleStop = useCallback(() => { - onStopScript(script.scriptName); - }, [onStopScript, script.scriptName]); + stop(script.scriptName); + }, [stop, script.scriptName]); const handleRestart = useCallback(() => { - onRestartScript(script.scriptName); - }, [onRestartScript, script.scriptName]); + restart(script.scriptName); + }, [restart, script.scriptName]); const scriptNameStyle = useMemo( () => (isRunning ? [styles.scriptName, styles.scriptNameActive] : styles.scriptName), @@ -471,7 +384,7 @@ function ScriptRow({ scriptName: script.scriptName, })} testID={`workspace-scripts-stop-${script.scriptName}`} - disabled={isStopPending} + disabled={actions.isStopPending} icon="stop" onPress={handleStop} tooltipLabel={t("workspace.scripts.actions.stop")} @@ -482,7 +395,7 @@ function ScriptRow({ scriptName: script.scriptName, })} testID={`workspace-scripts-start-${script.scriptName}`} - disabled={isStartPending} + disabled={actions.isStartPending} icon="start" onPress={handleRun} tooltipLabel={t("workspace.scripts.actions.run")} @@ -497,7 +410,7 @@ function ScriptRow({ })} > - + {script.scriptName} @@ -511,7 +424,7 @@ function ScriptRow({ scriptName: script.scriptName, })} testID={`workspace-scripts-restart-${script.scriptName}`} - disabled={isStopPending} + disabled={actions.isStopPending} icon="restart" onPress={handleRestart} tooltipLabel={t("workspace.scripts.actions.restart")} @@ -523,10 +436,10 @@ function ScriptRow({ ) : null} @@ -543,142 +456,35 @@ export function WorkspaceScriptsButton({ onViewTerminal, onOpenUrlInBrowserTab, hideLabels, - presentation = "split", }: WorkspaceScriptsButtonProps): ReactElement | null { const { t } = useTranslation(); - const toast = useToast(); - const client = useSessionStore((state) => state.sessions[serverId]?.client ?? null); - const activeConnection = useHostRuntimeSnapshot(serverId)?.activeConnection ?? null; - const preferredRouteKind = useWorkspaceServiceRoutePreferencesStore( - (state) => state.byServerId[serverId] ?? null, - ); - const setPreferredRoute = useWorkspaceServiceRoutePreferencesStore( - (state) => state.setPreferredRoute, - ); + const actions = useWorkspaceScriptActions({ + serverId, + workspaceId, + scripts, + onScriptTerminalStarted, + }); const liveTerminalIdSet = useMemo(() => new Set(liveTerminalIds), [liveTerminalIds]); - const pendingRestartRef = useRef>(new Set()); - - const startScriptMutation = useMutation({ - mutationFn: async (scriptName: string) => { - if (!client) { - throw new Error(t("common.errors.daemonClientUnavailable")); - } - const result = await client.startWorkspaceScript(workspaceId, scriptName); - if (result.error) { - throw new Error(result.error); - } - return result; - }, - onError: (error, scriptName) => { - toast.show( - error instanceof Error - ? error.message - : t("workspace.scripts.states.startFailed", { scriptName }), - { - variant: "error", - }, - ); - }, - onSuccess: (result) => { - if (result.terminalId) { - onScriptTerminalStarted?.(result.terminalId); - } - }, - }); - const startScript = startScriptMutation.mutate; - - const stopScriptMutation = useMutation({ - mutationFn: async (scriptName: string) => { - if (!client) { - throw new Error(t("common.errors.daemonClientUnavailable")); - } - const terminalId = scripts.find((s) => s.scriptName === scriptName)?.terminalId; - if (!terminalId) { - throw new Error(t("workspace.scripts.states.stopFailed", { scriptName })); - } - const result = await client.killTerminal(terminalId); - if (!result.success) { - throw new Error(t("workspace.scripts.states.stopFailed", { scriptName })); - } - }, - onError: (error, scriptName) => { - pendingRestartRef.current.delete(scriptName); - toast.show( - error instanceof Error - ? error.message - : t("workspace.scripts.states.stopFailed", { scriptName }), - { - variant: "error", - }, - ); - }, - }); - - // Restart = kill the script terminal, then start again once the daemon - // reports the script as stopped (it tears the runtime entry down on exit). - useEffect(() => { - const pending = pendingRestartRef.current; - if (pending.size === 0) return; - for (const script of scripts) { - if (!pending.has(script.scriptName) || script.lifecycle === "running") continue; - pending.delete(script.scriptName); - startScript(script.scriptName); - } - }, [scripts, startScript]); const triggerStyle = useCallback( ({ hovered, pressed, open }: { hovered: boolean; pressed: boolean; open: boolean }) => [ - presentation === "ghost" ? styles.ghostButton : styles.splitButtonPrimary, - (hovered || pressed || open) && - (presentation === "ghost" ? styles.ghostButtonHovered : styles.splitButtonPrimaryHovered), + styles.splitButtonPrimary, + (hovered || pressed || open) && styles.splitButtonPrimaryHovered, ], - [presentation], - ); - - const handleStartScript = useCallback( - (scriptName: string) => startScriptMutation.mutate(scriptName), - [startScriptMutation], - ); - - const handleStopScript = useCallback( - (scriptName: string) => stopScriptMutation.mutate(scriptName), - [stopScriptMutation], - ); - - const handleRestartScript = useCallback( - (scriptName: string) => { - pendingRestartRef.current.add(scriptName); - stopScriptMutation.mutate(scriptName); - }, - [stopScriptMutation], - ); - - const handleCopyUrl = useCallback( - (url: string, label: string) => { - void Clipboard.setStringAsync(url); - toast.copied(label); - }, - [toast], - ); - - const handleSelectRouteKind = useCallback( - (kind: WorkspaceScriptLinkKind) => setPreferredRoute(serverId, kind), - [serverId, setPreferredRoute], + [], ); if (scripts.length === 0) { return null; } + // The trigger only says whether anything runs; health is for the rows inside. const hasAnyRunning = scripts.some((s) => s.lifecycle === "running"); - const triggerPlayMapping = hasAnyRunning ? blueColorMapping : mutedColorMapping; - const triggerIconSize = presentation === "ghost" ? GHOST_TRIGGER_ICON_SIZE : 14; - const triggerPlayProps = - presentation === "ghost" ? { ...playFillTransparent, ...ghostPlayStroke } : playFillTransparent; + const triggerPlayMapping = scriptToneColorMapping(hasAnyRunning ? "running" : "idle"); return ( - + - + {!hideLabels && ( {t("workspace.scripts.title")} )} - {presentation === "split" ? ( - - ) : null} + @@ -750,21 +542,6 @@ const styles = StyleSheet.create((theme) => ({ borderColor: theme.colors.borderAccent, overflow: "hidden", }, - ghostButtonFrame: { - flexDirection: "row", - alignItems: "stretch", - }, - ghostButton: { - width: theme.spacing[8], - height: theme.spacing[8], - padding: 0, - borderRadius: theme.borderRadius.lg, - alignItems: "center", - justifyContent: "center", - }, - ghostButtonHovered: { - backgroundColor: theme.colors.surface2, - }, splitButtonPrimary: { paddingHorizontal: { xs: theme.spacing[3], @@ -798,9 +575,6 @@ const styles = StyleSheet.create((theme) => ({ paddingHorizontal: theme.spacing[3], minHeight: MENU_ITEM_HEIGHT, }, - scriptIcon: { - flexShrink: 0, - }, scriptName: { fontSize: theme.fontSize.base, fontWeight: theme.fontWeight.normal, @@ -844,21 +618,6 @@ const styles = StyleSheet.create((theme) => ({ hostLabelActive: { color: theme.colors.foreground, }, - exitBadge: { - paddingHorizontal: theme.spacing[1.5], - paddingVertical: 1, - borderRadius: 2, - backgroundColor: theme.colors.surface2, - }, - exitBadgeText: { - fontSize: 10, - lineHeight: 12, - fontWeight: theme.fontWeight.medium, - color: theme.colors.foregroundMuted, - }, - exitBadgeTextError: { - color: theme.colors.palette.red[300], - }, iconActionButton: { padding: 2, }, diff --git a/packages/app/src/screens/workspace/scripts/workspace-scripts-menu-pages.tsx b/packages/app/src/screens/workspace/scripts/workspace-scripts-menu-pages.tsx new file mode 100644 index 0000000000..3d14d9faff --- /dev/null +++ b/packages/app/src/screens/workspace/scripts/workspace-scripts-menu-pages.tsx @@ -0,0 +1,416 @@ +import { useCallback, useMemo, type ReactElement } from "react"; +import { View } from "react-native"; +import { Copy, Eye, Play, RotateCw, Square, SquareTerminal } from "lucide-react-native"; +import { StyleSheet, withUnistyles } from "react-native-unistyles"; +import { useTranslation } from "react-i18next"; +import { + DropdownMenuItem, + DropdownMenuSeparator, + DropdownMenuSubTrigger, + type MenuPageDefinition, +} from "@/components/ui/dropdown-menu"; +import type { WorkspaceDescriptor } from "@/stores/session-store"; +import type { Theme } from "@/styles/theme"; +import { openServiceUrl } from "@/utils/open-service-url"; +import type { + WorkspaceScriptLinkKind, + WorkspaceScriptLinkTarget, +} from "@/utils/workspace-script-links"; +import { ExitCodeBadge, routeLabelKey, ScriptIcon } from "./script-marks"; +import { scriptToneColorMapping, summarizeScripts, type ScriptsSummary } from "./script-status"; +import { + useWorkspaceScriptActions, + type WorkspaceScriptActions, +} from "./use-workspace-script-actions"; + +type WorkspaceScript = WorkspaceDescriptor["scripts"][number]; + +const ThemedPlay = withUnistyles(Play); +const ThemedEye = withUnistyles(Eye); +const ThemedSquareTerminal = withUnistyles(SquareTerminal); +const ThemedCopy = withUnistyles(Copy); +const ThemedRotateCw = withUnistyles(RotateCw); +const ThemedSquare = withUnistyles(Square); + +const mutedColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted }); +const playFillTransparent = { fill: "transparent" }; + +const ROW_ICON_SIZE = 16; +const TRAILING_ICON_SIZE = 14; + +const OPEN_SERVICE_ICON = ; +const VIEW_TERMINAL_ICON = ( + +); +const COPY_URL_ICON = ; +const RESTART_ICON = ; +const STOP_ICON = ; +const RUN_ICON = ( + +); + +const SCRIPTS_PAGE_ID = "workspace-scripts"; + +function scriptPageId(scriptName: string): string { + return `${SCRIPTS_PAGE_ID}/${scriptName}`; +} + +export interface UseWorkspaceScriptsMenuPagesInput { + serverId: string; + workspaceId: string; + scripts: WorkspaceDescriptor["scripts"]; + liveTerminalIds: readonly string[]; + onScriptTerminalStarted: (terminalId: string) => void; + onViewTerminal: (terminalId: string) => void; + onOpenUrlInBrowserTab: (url: string) => void; +} + +export interface WorkspaceScriptsMenuPages { + /** The root row that leads to the scripts page. Null when the workspace has no scripts. */ + trigger: ReactElement | null; + pages: MenuPageDefinition[]; + /** A running service reports unhealthy, so the menu's own trigger should say so. */ + needsAttention: boolean; +} + +/** + * Workspace scripts as pages of a sheet menu: a Scripts row on the root, a page listing every + * script, and one page per script. + * + * Every script gets a page whether or not it runs, so stopping one from its own page flips that + * page to its stopped state instead of pulling it out from under the user. + * + * The actions live here rather than in a page, so call this from whatever owns the menu: a restart + * finishes after the sheet has closed. + */ +export function useWorkspaceScriptsMenuPages({ + serverId, + workspaceId, + scripts, + liveTerminalIds, + onScriptTerminalStarted, + onViewTerminal, + onOpenUrlInBrowserTab, +}: UseWorkspaceScriptsMenuPagesInput): WorkspaceScriptsMenuPages { + const { t } = useTranslation(); + const actions = useWorkspaceScriptActions({ + serverId, + workspaceId, + scripts, + onScriptTerminalStarted, + }); + const summary = useMemo(() => summarizeScripts(scripts), [scripts]); + + const trigger = useMemo( + () => (scripts.length === 0 ? null : ), + [scripts.length, summary], + ); + + const pages = useMemo(() => { + if (scripts.length === 0) return []; + const liveTerminalIdSet = new Set(liveTerminalIds); + return [ + { + id: SCRIPTS_PAGE_ID, + title: t("workspace.scripts.title"), + content: , + }, + ...scripts.map((script) => ({ + id: scriptPageId(script.scriptName), + title: script.scriptName, + content: ( + + ), + })), + ]; + }, [actions, liveTerminalIds, onOpenUrlInBrowserTab, onViewTerminal, scripts, t]); + + return { trigger, pages, needsAttention: summary.tone === "unhealthy" }; +} + +/** The root row: ▶ in the colour of the whole set, and what is running as its value. */ +function ScriptsMenuTrigger({ summary }: { summary: ScriptsSummary }): ReactElement { + const { t } = useTranslation(); + const leading = useMemo( + () => ( + + ), + [summary.tone], + ); + const [onlyRunning] = summary.running; + const value = + summary.running.length > 1 + ? t("workspace.scripts.states.runningCount", { count: summary.running.length }) + : onlyRunning; + return ( + + {t("workspace.scripts.title")} + + ); +} + +function ScriptsPage({ + scripts, + actions, +}: { + scripts: WorkspaceDescriptor["scripts"]; + actions: WorkspaceScriptActions; +}): ReactElement { + return ( + <> + {scripts.map((script) => + script.lifecycle === "running" ? ( + + ) : ( + + ), + )} + + ); +} + +function RunningScriptRow({ script }: { script: WorkspaceScript }): ReactElement { + const { t } = useTranslation(); + const leading = useMemo(() => , [script]); + return ( + + {script.scriptName} + + ); +} + +/** Pressing a stopped script runs it. Starting opens its terminal tab, so the sheet closes. */ +function StoppedScriptRow({ + script, + actions, +}: { + script: WorkspaceScript; + actions: WorkspaceScriptActions; +}): ReactElement { + const { start } = actions; + const handleSelect = useCallback(() => start(script.scriptName), [start, script.scriptName]); + const exitCode = script.exitCode ?? null; + const leading = useMemo(() => , [script]); + const trailing = useMemo( + () => ( + + {exitCode === null ? null : } + + + ), + [exitCode], + ); + return ( + + {script.scriptName} + + ); +} + +interface ScriptPageProps { + script: WorkspaceScript; + actions: WorkspaceScriptActions; + liveTerminalId: string | null; + onViewTerminal: (terminalId: string) => void; + onOpenUrlInBrowserTab: (url: string) => void; +} + +function ScriptPage(props: ScriptPageProps): ReactElement { + return props.script.lifecycle === "running" ? ( + + ) : ( + + ); +} + +/** + * Rows that open something — the service, the terminal, the clipboard toast — close the sheet. + * Stop and the URL choice stay: the page is where their result shows. + */ +function RunningScriptPage({ + script, + actions, + liveTerminalId, + onViewTerminal, + onOpenUrlInBrowserTab, +}: ScriptPageProps): ReactElement { + const { t } = useTranslation(); + const { scriptName } = script; + const { selected, targets } = actions.resolveLinks(script); + const { stop, restart, copyUrl, selectRoute } = actions; + + const handleOpenService = useCallback(() => { + if (!selected) return; + void openServiceUrl(selected.url, { openInApp: onOpenUrlInBrowserTab }); + }, [selected, onOpenUrlInBrowserTab]); + const handleViewTerminal = useCallback(() => { + if (liveTerminalId) onViewTerminal(liveTerminalId); + }, [liveTerminalId, onViewTerminal]); + const handleCopyUrl = useCallback(() => { + if (selected) copyUrl(selected); + }, [selected, copyUrl]); + const handleRestart = useCallback(() => restart(scriptName), [restart, scriptName]); + const handleStop = useCallback(() => stop(scriptName), [stop, scriptName]); + + return ( + <> + {selected ? ( + + {t("workspace.scripts.actions.openService")} + + ) : null} + {liveTerminalId ? ( + + {t("workspace.scripts.actions.view")} + + ) : null} + {selected ? ( + + {t("workspace.scripts.actions.copyUrl")} + + ) : null} + + {t("workspace.scripts.actions.restart")} + + + {t("workspace.scripts.actions.stop")} + + {selected && targets.length > 1 ? ( + <> + + {targets.map((target) => ( + + ))} + + ) : null} + + ); +} + +/** A pick-one URL route. Choosing one keeps the page open so the check moves under the thumb. */ +function ServiceRouteOption({ + scriptName, + target, + selected, + onSelect, +}: { + scriptName: string; + target: WorkspaceScriptLinkTarget; + selected: boolean; + onSelect: (kind: WorkspaceScriptLinkKind) => void; +}): ReactElement { + const { t } = useTranslation(); + const handleSelect = useCallback(() => onSelect(target.kind), [onSelect, target.kind]); + return ( + + {t(routeLabelKey(target.kind))} + + ); +} + +function StoppedScriptPage({ + script, + actions, +}: { + script: WorkspaceScript; + actions: WorkspaceScriptActions; +}): ReactElement { + const { t } = useTranslation(); + const { start } = actions; + const handleRun = useCallback(() => start(script.scriptName), [start, script.scriptName]); + const exitCode = script.exitCode ?? null; + const trailing = useMemo( + () => (exitCode === null ? null : ), + [exitCode], + ); + return ( + + {t("workspace.scripts.actions.run")} + + ); +} + +const styles = StyleSheet.create((theme) => ({ + trailing: { + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[1.5], + }, +})); diff --git a/packages/app/src/screens/workspace/workspace-header-menu.tsx b/packages/app/src/screens/workspace/workspace-header-menu.tsx index 2fb7176e10..74a95c7548 100644 --- a/packages/app/src/screens/workspace/workspace-header-menu.tsx +++ b/packages/app/src/screens/workspace/workspace-header-menu.tsx @@ -27,6 +27,10 @@ import { } from "@getpaseo/protocol/terminal-profiles"; import { buildSettingsHostSectionRoute } from "@/utils/host-routes"; import type { Theme } from "@/styles/theme"; +import { + useWorkspaceScriptsMenuPages, + type UseWorkspaceScriptsMenuPagesInput, +} from "@/screens/workspace/scripts"; const ThemedEllipsis = withUnistyles(Ellipsis); const ThemedCopy = withUnistyles(Copy); @@ -49,6 +53,16 @@ function WorkspaceHeaderMenuTriggerIcon() { ); } +/** The ⋯ with a dot on it, for when something inside the menu needs looking at. */ +function WorkspaceHeaderMenuAttentionTriggerIcon() { + return ( + + + + + ); +} + /** * The compact header buttons draw at 32pt, under the 44pt touch minimum, and sit flush against * each other — so the slop can only grow vertically. Widening it would put two buttons' slop over @@ -192,6 +206,7 @@ function HeaderMenuProfileItem({ export interface WorkspaceHeaderMenuMobileProps extends WorkspaceHeaderWorkspaceActions { normalizedServerId: string; + scripts: UseWorkspaceScriptsMenuPagesInput; showCreateBrowserTab: boolean; createTerminalDisabled: boolean; onCreateTerminalWithProfile: (profile: TerminalProfile) => void; @@ -201,9 +216,13 @@ export interface WorkspaceHeaderMenuMobileProps extends WorkspaceHeaderWorkspace /** * Compact layouts have no tab strip. New agent and New terminal sit in the tab switcher's footer; * the rarer launches stay here alongside the workspace actions. + * + * The header has no room for a scripts button either, so scripts are a page of this menu, and the + * ⋯ carries a dot while a running service is unhealthy. */ export function WorkspaceHeaderMenuMobile({ normalizedServerId, + scripts, showCreateBrowserTab, createTerminalDisabled, onCreateTerminalWithProfile, @@ -222,6 +241,7 @@ export function WorkspaceHeaderMenuMobile({ const handleEditProfiles = useCallback(() => { router.push(buildSettingsHostSectionRoute(normalizedServerId, "terminals") as Href); }, [normalizedServerId, router]); + const scriptsMenu = useWorkspaceScriptsMenuPages(scripts); return ( @@ -230,16 +250,26 @@ export function WorkspaceHeaderMenuMobile({ style={triggerStyle} hitSlop={COMPACT_HEADER_BUTTON_HIT_SLOP} accessibilityRole="button" - accessibilityLabel={t("workspace.header.actions.workspaceActions")} + accessibilityLabel={ + scriptsMenu.needsAttention + ? t("workspace.header.actions.workspaceActionsUnhealthy") + : t("workspace.header.actions.workspaceActions") + } > - + {scriptsMenu.needsAttention ? ( + + ) : ( + + )} + {scriptsMenu.trigger} {showCreateBrowserTab ? ( ({ headerMenuProfileIconWrapper: { width: 16, height: 16, }, -}); + // Same red as the Scripts row's unhealthy ▶, so the dot and the row it leads to agree. + attentionDot: { + position: "absolute", + top: -1, + right: -2, + width: ATTENTION_DOT_SIZE, + height: ATTENTION_DOT_SIZE, + borderRadius: theme.borderRadius.full, + backgroundColor: theme.colors.palette.red[500], + }, +})); diff --git a/packages/app/src/screens/workspace/workspace-screen.tsx b/packages/app/src/screens/workspace/workspace-screen.tsx index 90a46d9e06..0872c0dc92 100644 --- a/packages/app/src/screens/workspace/workspace-screen.tsx +++ b/packages/app/src/screens/workspace/workspace-screen.tsx @@ -48,7 +48,7 @@ import { SplitContainer } from "@/components/split-container"; import { RetainedPanel } from "@/components/retained-panel"; import { WorkspaceActions } from "@/git/workspace-actions"; import { WorkspaceOpenInEditorButton } from "@/workspace/open-in-editor/button"; -import { WorkspaceScriptsButton } from "@/screens/workspace/workspace-scripts-button"; +import { WorkspaceScriptsButton } from "@/screens/workspace/scripts"; import { ImportSessionSheet } from "@/components/import-session-sheet"; import { useNavigateToImportedAgent } from "@/hooks/use-import-session"; import { useToast } from "@/contexts/toast-context"; @@ -1027,6 +1027,15 @@ function WorkspaceScreenContent({ .prepareWorkspaceRoute(normalizedServerId, normalizedWorkspaceId) .catch(() => undefined); }, [normalizedServerId, normalizedWorkspaceId, workspaceDescriptor]); + // The focused workspace keeps its script status live even when no sidebar or viewed agent + // timeline demands the directory. Retained, hidden workspaces release it. + useEffect(() => { + if (!isRouteFocused || !normalizedServerId || !normalizedWorkspaceId) return; + return getHostRuntimeStore().acquireScriptStatusDemand( + normalizedServerId, + normalizedWorkspaceId, + ); + }, [isRouteFocused, normalizedServerId, normalizedWorkspaceId]); const workspaceScripts = getWorkspaceScripts(workspaceDescriptor); const { handleRetryHost, handleManageHost, handleDismissMissingWorkspace } = useWorkspaceRouteActions(normalizedServerId); @@ -3374,6 +3383,26 @@ function WorkspaceScreenContent({ isWorkspaceHeaderSubtitleDistinct, ], ); + const compactHeaderScripts = useMemo( + () => ({ + serverId: normalizedServerId, + workspaceId: normalizedWorkspaceId, + scripts: workspaceScripts, + liveTerminalIds, + onScriptTerminalStarted: handleScriptTerminalStarted, + onViewTerminal: handleViewScriptTerminal, + onOpenUrlInBrowserTab: handleOpenUrlInBrowserTab, + }), + [ + normalizedServerId, + normalizedWorkspaceId, + workspaceScripts, + liveTerminalIds, + handleScriptTerminalStarted, + handleViewScriptTerminal, + handleOpenUrlInBrowserTab, + ], + ); const compactWorkspaceHeader = useMemo( () => isMobile ? ( @@ -3409,6 +3438,7 @@ function WorkspaceScreenContent({ /> 0, + hasActiveMessageSubmission(session?.messageSubmissions.get(agentId)), ); } diff --git a/packages/app/src/timeline/turn-time.test.ts b/packages/app/src/timeline/turn-time.test.ts index 35dacf397b..3ce6942301 100644 --- a/packages/app/src/timeline/turn-time.test.ts +++ b/packages/app/src/timeline/turn-time.test.ts @@ -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, + }); + }); }); diff --git a/packages/app/src/timeline/turn-time.ts b/packages/app/src/timeline/turn-time.ts index 4542962af4..c47a6983cd 100644 --- a/packages/app/src/timeline/turn-time.ts +++ b/packages/app/src/timeline/turn-time.ts @@ -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; + byAssistantId: Map; +} + +interface TailTurnTiming { + completed: Map; + openTurn: OpenTurn; + lastHead: HeadTurnTiming | null; +} + +const EMPTY_OPEN_TURN: OpenTurn = { + userAt: null, + lastItemAt: null, + assistantIds: [], + previousItem: null, +}; + +function closeTurn(turn: OpenTurn, into: Map): 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, +): 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, b: Map): 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(); + +function getTailTurnTiming(tail: StreamItem[]): TailTurnTiming { + const cached = tailTurnTimingCache.get(tail); + if (cached) { + return cached; + } + const completed = new Map(); + 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, +): Map { + 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(); - 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(); + 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, }; } diff --git a/packages/app/src/usage/model.test.ts b/packages/app/src/usage/model.test.ts index ad293bb23e..a2c493619d 100644 --- a/packages/app/src/usage/model.test.ts +++ b/packages/app/src/usage/model.test.ts @@ -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]); }); diff --git a/packages/app/src/usage/model.ts b/packages/app/src/usage/model.ts index a32da7ea4d..ed8a39163a 100644 --- a/packages/app/src/usage/model.ts +++ b/packages/app/src/usage/model.ts @@ -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 { diff --git a/packages/desktop/e2e/keyboard-shortcut-unassign.spec.ts b/packages/desktop/e2e/keyboard-shortcut-unassign.spec.ts index 1d0b829f67..b7063b4565 100644 --- a/packages/desktop/e2e/keyboard-shortcut-unassign.spec.ts +++ b/packages/desktop/e2e/keyboard-shortcut-unassign.spec.ts @@ -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); +}); diff --git a/packages/desktop/e2e/workspace-restart.spec.ts b/packages/desktop/e2e/workspace-restart.spec.ts index 4ee1655242..67bc8408ea 100644 --- a/packages/desktop/e2e/workspace-restart.spec.ts +++ b/packages/desktop/e2e/workspace-restart.spec.ts @@ -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; diff --git a/packages/plugin/src/server/acp-internal/connection.ts b/packages/plugin/src/server/acp-internal/connection.ts index fc78d2a8c4..05403594cf 100644 --- a/packages/plugin/src/server/acp-internal/connection.ts +++ b/packages/plugin/src/server/acp-internal/connection.ts @@ -359,6 +359,8 @@ class AcpRuntime { private emit: (event: ProviderEvent) => void; private readonly messages = new Map(); private readonly toolCalls = new Map(); + // Running tool rows published by transformers; the turn's terminal closes any left open. + private readonly vendorToolCalls = new Map(); private readonly pendingCompactions = new Set(); private readonly permissions = new Map< string, @@ -545,8 +547,13 @@ class AcpRuntime { return sessionCapabilities; } - async discover(cwd = process.cwd()): Promise { - const response = await this.call(this.connection.newSession({ cwd, mcpServers: [] })); + async discover(cwd?: string): Promise { + 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 => { + 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 => { + 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; + +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); } diff --git a/packages/plugin/src/server/acp.test.ts b/packages/plugin/src/server/acp.test.ts index a62b2f2c48..40c8019439 100644 --- a/packages/plugin/src/server/acp.test.ts +++ b/packages/plugin/src/server/acp.test.ts @@ -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 = [ diff --git a/packages/plugin/src/server/acp.ts b/packages/plugin/src/server/acp.ts index 533453f15e..826bc23235 100644 --- a/packages/plugin/src/server/acp.ts +++ b/packages/plugin/src/server/acp.ts @@ -44,6 +44,8 @@ export type AcpConnector = () => AcpStream | Promise; 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; } diff --git a/packages/plugin/src/server/provider.ts b/packages/plugin/src/server/provider.ts index 33b49ab447..1646e8473b 100644 --- a/packages/plugin/src/server/provider.ts +++ b/packages/plugin/src/server/provider.ts @@ -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; /** Default executable and arguments; the daemon resolves overrides before status/connect. */ diff --git a/packages/protocol/src/messages.checkout-pr-schema.test.ts b/packages/protocol/src/messages.checkout-pr-schema.test.ts index cf15e47962..3966d6eb71 100644 --- a/packages/protocol/src/messages.checkout-pr-schema.test.ts +++ b/packages/protocol/src/messages.checkout-pr-schema.test.ts @@ -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); + }, +); diff --git a/packages/protocol/src/messages.ts b/packages/protocol/src/messages.ts index fefc104279..c8fe60ff67 100644 --- a/packages/protocol/src/messages.ts +++ b/packages/protocol/src/messages.ts @@ -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. diff --git a/packages/protocol/src/provider-icon-names.ts b/packages/protocol/src/provider-icon-names.ts index 6265b631c3..4ca8ea44e3 100644 --- a/packages/protocol/src/provider-icon-names.ts +++ b/packages/protocol/src/provider-icon-names.ts @@ -31,6 +31,7 @@ export const ACP_PROVIDER_ICON_NAMES = [ "glm-acp-agent", "goose", "grok", + "hoplite", "junie", "kilo", "kimi", diff --git a/packages/server/package.json b/packages/server/package.json index a69a2c3c2a..6e5e2448a2 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -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", diff --git a/packages/server/scripts/transcribe-local-wav.test.ts b/packages/server/scripts/transcribe-local-wav.test.ts new file mode 100644 index 0000000000..703025e2c5 --- /dev/null +++ b/packages/server/scripts/transcribe-local-wav.test.ts @@ -0,0 +1,40 @@ +import { spawnSync } from "node:child_process"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +import { afterEach, describe, expect, test } from "vitest"; + +const tempDirs: string[] = []; + +afterEach(() => { + for (const dir of tempDirs.splice(0)) { + rmSync(dir, { recursive: true, force: true }); + } +}); + +describe("transcribe-local-wav CLI", () => { + test("initializes the complete speech provider configuration", () => { + const modelsDir = mkdtempSync(path.join(tmpdir(), "paseo-transcribe-local-")); + tempDirs.push(modelsDir); + const missingWav = path.join(modelsDir, "missing.wav"); + const scriptPath = fileURLToPath(new URL("./transcribe-local-wav.ts", import.meta.url)); + + const result = spawnSync( + process.execPath, + ["--import", "tsx", scriptPath, missingWav, "--models-dir", modelsDir], + { + encoding: "utf8", + timeout: 15_000, + }, + ); + + expect(result.error).toBeUndefined(); + expect(result.status).not.toBe(0); + // The worker client is lazy, so reaching the missing WAV proves provider initialization completed first. + expect(result.stderr).toContain("ENOENT"); + expect(result.stderr).toContain(missingWav); + expect(result.stderr).not.toContain("Cannot read properties of undefined"); + }); +}); diff --git a/packages/server/scripts/transcribe-local-wav.ts b/packages/server/scripts/transcribe-local-wav.ts index 0b323df029..a9cb10b7a2 100644 --- a/packages/server/scripts/transcribe-local-wav.ts +++ b/packages/server/scripts/transcribe-local-wav.ts @@ -120,6 +120,7 @@ async function main(): Promise { const providers: RequestedSpeechProviders = { dictationStt: { provider: "local", explicit: true }, + voiceTurnDetection: { provider: "local", explicit: false, enabled: false }, voiceStt: { provider: "local", explicit: true }, // Not used here, but required by the shared runtime config shape. voiceTts: { provider: "openai", explicit: false }, diff --git a/packages/server/src/server/agent/plugin-provider.test.ts b/packages/server/src/server/agent/plugin-provider.test.ts index 8b894a7765..ae8ed805d7 100644 --- a/packages/server/src/server/agent/plugin-provider.test.ts +++ b/packages/server/src/server/agent/plugin-provider.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(); + } +}); diff --git a/packages/server/src/server/agent/plugin-provider.ts b/packages/server/src/server/agent/plugin-provider.ts index 58bddd07b6..e575ff0d45 100644 --- a/packages/server/src/server/agent/plugin-provider.ts +++ b/packages/server/src/server/agent/plugin-provider.ts @@ -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, diff --git a/packages/server/src/server/agent/provider-registry.ts b/packages/server/src/server/agent/provider-registry.ts index 2698a3b2ac..9f85e4d37f 100644 --- a/packages/server/src/server/agent/provider-registry.ts +++ b/packages/server/src/server/agent/provider-registry.ts @@ -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; diff --git a/packages/server/src/server/agent/provider-snapshot-manager.ts b/packages/server/src/server/agent/provider-snapshot-manager.ts index 82acd13e1f..b10a4f8e02 100644 --- a/packages/server/src/server/agent/provider-snapshot-manager.ts +++ b/packages/server/src/server/agent/provider-snapshot-manager.ts @@ -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; } diff --git a/packages/server/src/server/agent/providers/opencode/test-utils/v2-streamed-text-memory.ts b/packages/server/src/server/agent/providers/opencode/test-utils/v2-streamed-text-memory.ts new file mode 100644 index 0000000000..d9d254d9de --- /dev/null +++ b/packages/server/src/server/agent/providers/opencode/test-utils/v2-streamed-text-memory.ts @@ -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)); diff --git a/packages/server/src/server/agent/providers/opencode/v2/timeline.test.ts b/packages/server/src/server/agent/providers/opencode/v2/timeline.test.ts index 9189f5d3c5..82236de2b8 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/timeline.test.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/timeline.test.ts @@ -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); + }, +); diff --git a/packages/server/src/server/agent/providers/opencode/v2/timeline.ts b/packages/server/src/server/agent/providers/opencode/v2/timeline.ts index c58316df9e..0fdd6f9f40 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/timeline.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/timeline.ts @@ -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(); @@ -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 }); diff --git a/packages/server/src/server/daemon-e2e/hoplite-fixture.cjs b/packages/server/src/server/daemon-e2e/hoplite-fixture.cjs new file mode 100644 index 0000000000..542c2cf2ba --- /dev/null +++ b/packages/server/src/server/daemon-e2e/hoplite-fixture.cjs @@ -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 }); +}); diff --git a/packages/server/src/server/daemon-e2e/models.e2e.test.ts b/packages/server/src/server/daemon-e2e/models.e2e.test.ts index b9293d8c3e..cfa420654b 100644 --- a/packages/server/src/server/daemon-e2e/models.e2e.test.ts +++ b/packages/server/src/server/daemon-e2e/models.e2e.test.ts @@ -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); diff --git a/packages/server/src/server/plugins/builtin/index.ts b/packages/server/src/server/plugins/builtin/index.ts index c14c027853..cf6ffe9eee 100644 --- a/packages/server/src/server/plugins/builtin/index.ts +++ b/packages/server/src/server/plugins/builtin/index.ts @@ -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", diff --git a/packages/server/src/server/plugins/compiler.test.ts b/packages/server/src/server/plugins/compiler.test.ts index facba48fdb..fc86f85db3 100644 --- a/packages/server/src/server/plugins/compiler.test.ts +++ b/packages/server/src/server/plugins/compiler.test.ts @@ -138,6 +138,51 @@ async function createRootAlias(directory: string): Promise { } 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", diff --git a/packages/server/src/server/plugins/compiler.ts b/packages/server/src/server/plugins/compiler.ts index 15df395d06..b48449bb50 100644 --- a/packages/server/src/server/plugins/compiler.ts +++ b/packages/server/src/server/plugins/compiler.ts @@ -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) || diff --git a/packages/server/src/server/plugins/index.ts b/packages/server/src/server/plugins/index.ts index 6c4af29e62..a5ecea8097 100644 --- a/packages/server/src/server/plugins/index.ts +++ b/packages/server/src/server/plugins/index.ts @@ -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) diff --git a/packages/server/src/server/plugins/plugin-process-protocol.ts b/packages/server/src/server/plugins/plugin-process-protocol.ts index e959780389..b3f363cb29 100644 --- a/packages/server/src/server/plugins/plugin-process-protocol.ts +++ b/packages/server/src/server/plugins/plugin-process-protocol.ts @@ -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(), diff --git a/packages/server/src/server/plugins/plugin-process.ts b/packages/server/src/server/plugins/plugin-process.ts index 3f11926d7d..5e6efa1925 100644 --- a/packages/server/src/server/plugins/plugin-process.ts +++ b/packages/server/src/server/plugins/plugin-process.ts @@ -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, diff --git a/packages/server/src/server/test-utils/session-stubs.ts b/packages/server/src/server/test-utils/session-stubs.ts index 50c0ee3c76..c5cf271ad3 100644 --- a/packages/server/src/server/test-utils/session-stubs.ts +++ b/packages/server/src/server/test-utils/session-stubs.ts @@ -240,6 +240,7 @@ export function createProviderSnapshotManagerStub(): { const off = vi.fn(); const destroy = vi.fn(); const stub = { + supportsConfigRequiredProvider: () => false, getSnapshot, refreshSnapshotForCwd, refreshSettingsSnapshot, diff --git a/packages/server/src/server/websocket-server.relay-reconnect.test.ts b/packages/server/src/server/websocket-server.relay-reconnect.test.ts index 25acb9946b..10694a6ebe 100644 --- a/packages/server/src/server/websocket-server.relay-reconnect.test.ts +++ b/packages/server/src/server/websocket-server.relay-reconnect.test.ts @@ -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); diff --git a/packages/server/src/server/websocket-server.ts b/packages/server/src/server/websocket-server.ts index 5e93681a66..e833a07ce3 100644 --- a/packages/server/src/server/websocket-server.ts +++ b/packages/server/src/server/websocket-server.ts @@ -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. diff --git a/packages/server/src/server/workspace-create-worktree-source.e2e.test.ts b/packages/server/src/server/workspace-create-worktree-source.e2e.test.ts index b377c22374..69c1da2efc 100644 --- a/packages/server/src/server/workspace-create-worktree-source.e2e.test.ts +++ b/packages/server/src/server/workspace-create-worktree-source.e2e.test.ts @@ -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(); diff --git a/packages/server/src/server/worktree-bootstrap.ts b/packages/server/src/server/worktree-bootstrap.ts index 8e69908f59..4bd49b1c2d 100644 --- a/packages/server/src/server/worktree-bootstrap.ts +++ b/packages/server/src/server/worktree-bootstrap.ts @@ -593,13 +593,10 @@ export async function runWorktreeAutoTerminals(options: { workspaceId: string; worktree: WorktreeConfig; workspaceCwd: string; + runtimeEnv: WorktreeRuntimeEnv; terminalManager: TerminalManager | null; logger?: Logger; }): Promise { - 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, ); } diff --git a/packages/server/src/server/worktree-session.ts b/packages/server/src/server/worktree-session.ts index cdb0119b64..82f0113bd5 100644 --- a/packages/server/src/server/worktree-session.ts +++ b/packages/server/src/server/worktree-session.ts @@ -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 { @@ -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) { diff --git a/packages/server/vitest.config.ts b/packages/server/vitest.config.ts index 4b25764445..c80345c79e 100644 --- a/packages/server/vitest.config.ts +++ b/packages/server/vitest.config.ts @@ -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/**"], }, }); diff --git a/plugins/hoplite-provider/icon.svg b/plugins/hoplite-provider/icon.svg new file mode 100644 index 0000000000..ed585a9083 --- /dev/null +++ b/plugins/hoplite-provider/icon.svg @@ -0,0 +1 @@ + diff --git a/plugins/hoplite-provider/index.server.ts b/plugins/hoplite-provider/index.server.ts new file mode 100644 index 0000000000..4c101df470 --- /dev/null +++ b/plugins/hoplite-provider/index.server.ts @@ -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 () => {}; +} diff --git a/plugins/hoplite-provider/paseo-plugin.json b/plugins/hoplite-provider/paseo-plugin.json new file mode 100644 index 0000000000..138cf83ad6 --- /dev/null +++ b/plugins/hoplite-provider/paseo-plugin.json @@ -0,0 +1 @@ +{ "id": "hoplite-provider", "requirements": { "paseo": ">=0.11.0" } } diff --git a/plugins/hoplite-provider/server/provider.ts b/plugins/hoplite-provider/server/provider.ts new file mode 100644 index 0000000000..cb362052ea --- /dev/null +++ b/plugins/hoplite-provider/server/provider.ts @@ -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], + }), + }; +} diff --git a/plugins/hoplite-provider/server/run-phase.test.ts b/plugins/hoplite-provider/server/run-phase.test.ts new file mode 100644 index 0000000000..5526f386c6 --- /dev/null +++ b/plugins/hoplite-provider/server/run-phase.test.ts @@ -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(); + }); +}); diff --git a/plugins/hoplite-provider/server/run-phase.ts b/plugins/hoplite-provider/server/run-phase.ts new file mode 100644 index 0000000000..767ee0447d --- /dev/null +++ b/plugins/hoplite-provider/server/run-phase.ts @@ -0,0 +1,39 @@ +import type { AcpTransformer } from "@getpaseo/plugin/server/acp"; +import { z } from "zod"; + +// Hoplite provisions a cloud workspace before the first agent output of a run and reports each +// step as `_hoplite/run_phase`. A null phase ends provisioning for that run. +const runPhaseSchema = z.object({ + runId: z.string().min(1), + phase: z.string().nullable(), + label: z.string().nullable(), +}); + +const RUN_PHASE_METHOD = "_hoplite/run_phase"; + +export const runPhaseTransformer: AcpTransformer = { + notification(notification) { + if (notification.method !== RUN_PHASE_METHOD) return null; + const params = runPhaseSchema.safeParse(notification.params); + if (!params.success) return null; + const { runId, phase, label } = params.data; + const id = `hoplite-run-phase:${runId}`; + const running = phase !== null; + return { + type: "timeline", + item: { + type: "tool_call", + id, + callId: id, + name: "Hoplite workspace", + detail: { + type: "plain_text", + label: running ? (label ?? phase) : "Workspace ready", + icon: "wrench", + }, + status: running ? "running" : "completed", + error: null, + }, + }; + }, +}; diff --git a/public-docs/cli.md b/public-docs/cli.md index 1c348960b3..48f37e89de 100644 --- a/public-docs/cli.md +++ b/public-docs/cli.md @@ -228,11 +228,12 @@ The output includes each script's lifecycle and supervised terminal ID. Services Create and manage trusted plugins on a daemon: ```bash -paseo plugin init /absolute/path/to/plugin -paseo plugin install /absolute/path/to/plugin -paseo plugin add owner/repository +paseo plugin init ./plugin +paseo plugin install ./plugin +paseo plugin add owner/slug +paseo plugin add git:owner/repository paseo plugin add https://gitlab.com/group/repository.git --ref main -paseo plugin add owner/monorepo:plugins/review +paseo plugin add git:owner/monorepo:plugins/review paseo plugin ls [id] paseo plugin update my-plugin paseo plugin update --all @@ -243,8 +244,10 @@ paseo plugin enable my-plugin paseo plugin remove my-plugin ``` -GitHub shorthand checks an existing host directory first. Append `:` for a plugin in a -monorepo. `paseo plugin ls [id]` does not contact the remote. `paseo plugin logs ` returns the +Bare `owner/slug` installs a reviewed registry listing. Use `git:owner/repository` for GitHub +source, or `./plugin` for a local directory. Append `:` for a plugin in a monorepo. + +`paseo plugin ls [id]` does not contact the remote. `paseo plugin logs ` returns the plugin's recent daemon-side stdout and stderr. Add `--json` for structured entries, or run `paseo --host plugin logs ` for another daemon. See the [Plugin reference](/docs/plugins/reference) for installation, trust, lifecycle, and log-retention diff --git a/public-docs/community.md b/public-docs/community.md index 33ba212056..f18815990d 100644 --- a/public-docs/community.md +++ b/public-docs/community.md @@ -10,12 +10,11 @@ category: Getting started These projects are related to Paseo and built by the community. -## Plugin directory +## Plugins -[paseo.cafe](https://paseo.cafe) is a community-run directory of Paseo plugins. Listings are generated -from each plugin's public repository, so it is the fastest way to see what people are building and to -publish your own. It is independent of the Paseo project and nothing on it is reviewed or endorsed by -us, so read a plugin's source before installing it. +Browse the [plugin registry](/plugins) for reviewed community plugins. To share your own, follow +[Publish a plugin](/docs/plugins/publishing) for package preparation and submission. +Plugins run unsandboxed; read their listing and source before installing. ## Tools and integrations diff --git a/public-docs/plugins/publishing.md b/public-docs/plugins/publishing.md index 16cde2389a..f925d0f1d4 100644 --- a/public-docs/plugins/publishing.md +++ b/public-docs/plugins/publishing.md @@ -1,6 +1,6 @@ --- title: Publish a plugin -description: Share a Paseo plugin on npm, through a private registry, or from a Git repository. +description: Prepare, publish and submit a Paseo plugin to the reviewed registry. nav: Publishing order: 45 category: Plugins @@ -8,111 +8,241 @@ category: Plugins # Publish a plugin -Publish your plugin so other people can install and use it in Paseo. Start with a working -[plugin project](/docs/plugins), then choose where to share it: +Start with a working [plugin project](/docs/plugins). Prepare its listing, publish it on npm +or push it to GitHub, then submit it to the registry. After approval, users install the reviewed +version with `paseo plugin add owner/slug`. -- [Plugin registry](#plugin-registry): share a reviewed artifact users install by `owner/slug`. -- [npm](#publish-on-npm): publish a package on the public npm registry. -- [GitHub or Git](#share-through-github-or-git): let users install from a repository. +1. Prepare your [listing page](#your-listing-page) and, for a visual plugin, an + [interface image](#icons-and-screenshots). +2. [Publish on npm](#publish-on-npm) or [share through Git](#share-through-github-or-git). +3. [Submit to the plugin registry](#plugin-registry). + +For a private plugin, use [direct Git installation](#share-through-github-or-git) or +[private npm packages](#private-npm-packages). + +## Your listing page + +You can submit without `OVERVIEW.md`; the reviewer creates a listing page from your README and +verified behavior. To maintain the page yourself, put `OVERVIEW.md` beside `paseo-plugin.json` +and include it in the published package. The scaffold already includes it in `files`. +Your shipped overview replaces the reviewer-written page. + +Explain these points in order, using headings only when they help: + +1. What the plugin does. +2. How it works, when that is not obvious. +3. Setup: settings, accounts, tokens, external tools, supported operating systems and Paseo versions. +4. Useful capabilities, settings, data access, permissions and limitations. + +Describe where data goes, including prompts and tool results sent to agent providers. Local storage +does not mean data stays on the host. If the plugin downloads or installs software while running, +explain what it installs and its source, and require explicit user confirmation before the download. +This applies to activation and connection tests too; declining must leave the software uninstalled. + +Use plain factual language and sentence case. Omit marketing, unsupported claims, badges, +changelogs, contributing and license sections, and implementation details that do not help someone +choose the plugin. The listing already provides plugin installation instructions. + +The publication validator rejects `paseo plugin add`, `npm install` and `npm i` anywhere in an +overview, including development or setup examples. Link to your README for those commands. + +Also supply a one-sentence description: use `package.json`'s `description` for npm or the manifest's +`description` for Git. The reviewer can fill in a missing description in the registry. + +## Icons and screenshots + +Themes, panels and other visual plugin interfaces need at least one image showing the current +interface. Use sample data and hide private details. An icon alone does not meet this requirement; +plugins without their own visual interface do not need screenshots. + +Declare local images in `paseo-plugin.json` before publishing: + +```json +{ + "id": "review-tools", + "name": "Review tools", + "description": "Reviews changes before merge", + "icon": "assets/icon.png", + "media": ["assets/screenshot.png"], + "requirements": { "paseo": ">=0.11.0" } +} +``` + +Create the referenced files and include `assets/` in `package.json`'s `files` list for npm. +Paths are relative to the manifest, use forward slashes and stay inside the plugin directory. +These metadata fields require Paseo 0.11.0 or later. + +| Field | Listing behavior | +| ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `name` | Optional display name; defaults to a humanized plugin ID. | +| `icon` | Optional package-relative PNG. Provider registration icons have a separate [SVG contract](/docs/plugins/reference#providers). | +| `media` | Package-relative paths or public HTTPS URLs. Images: PNG, JPG, JPEG, WebP or GIF. Videos: MP4 or WebM. The first image is the card thumbnail; videos supplement it. | + +Public media URLs need a supported file extension, matched case-insensitively, and must return +HTTP 200 with the corresponding image or video content type. SVG and extensionless attachment +URLs are not accepted as registry media. + +Instead of declaring `media`, you can supply suitable public image URLs in the submission or +review PR. The reviewer can add them to the listing without a new plugin release. + +## Publish on npm + +### 1. Set package identity + +Use an npm scope you can publish to and authenticate with `npm login`. From your plugin directory, +replace `@acme` and the repository below with your own values: + +```bash +npm pkg set name=@acme/paseo-review version=1.0.0 +npm pkg delete private +npm pkg set repository.type=git repository.url=git+https://github.com/acme/paseo-review.git +``` + +The current registry tooling requires a GitHub repository for npm listing ownership, supplied +through `package.json` or npm provenance. Set `repository` to your public source repository so +pinning can determine the listing owner. Provenance itself is optional; if present, its repository +must match the package's repository. A matching source checkout is not required for artifact review. + +### 2. Lock installed dependencies + +Keep Paseo's host libraries and type-only dependencies in `devDependencies`. Add other runtime +libraries to `dependencies`. For registry submission, every installed dependency tree needs a lock +with exact versions, resolved sources and integrity, including transitive dependencies. + +For an npm package with installed runtime dependencies, update its lock without running lifecycle +scripts, then create the publishable lock: + +```bash +npm install --package-lock-only --ignore-scripts +npm shrinkwrap +``` + +`npm shrinkwrap` converts `package-lock.json` into `npm-shrinkwrap.json`. npm publishes the shrinkwrap +at the package root; it does not publish `package-lock.json`. A repository-only lock or exact direct +version does not lock the dependency tree installed by your users. + +Plugins using only host libraries and development dependencies need no runtime lock unless a +preparation command installs those dependencies. You can also bundle a library and remove the +runtime dependency declaration. See [preparation and additional setup](#plugins-with-a-build-step) +if your plugin installs a separate tree. + +### 3. Check the package and publish + +Generate any required files before checking the package; the dry run skips packing scripts. + +```bash +npm run typecheck +npm pack --dry-run --ignore-scripts +``` + +Check the file list contains `paseo-plugin.json`, at least one runtime entry, every imported local +module, any overview and assets you declared, and the shrinkwrap when required. Repository-only import aliases +and files outside the package do not reach users. The scaffold includes the entries and `client/`, +`server/` and `shared/`; add other asset directories to `files`. + +Confirm any declared preparation command succeeds with the Node/npm versions you support; +an out-of-sync or incompatible lockfile still blocks installation. + +Publish the checked version: + +```bash +npm publish --access public +``` + +On a test daemon, install that exact published version and exercise its contributions: + +```bash +paseo plugin install npm:@acme/paseo-review@1.0.0 +paseo plugin ls +``` + +Require `running` with no error, then [submit the package](#plugin-registry). + +## Share through GitHub or Git + +For the public registry, push your plugin to a public GitHub repository. Include its manifest, +runtime entries, imported files and listing assets. Git tags and commits are optional at submission; +provide one to select a revision, or the reviewer resolves `main`. + +If preparation installs runtime npm dependencies, commit a synchronized `package-lock.json` and +add this command to `paseo-plugin.json`: + +```json +{ + "build": [["npm", "ci", "--omit=dev", "--ignore-scripts"]] +} +``` + +`npm ci` consumes the committed lock and fails if it disagrees with `package.json`. `--omit=dev` +excludes development tools and `--ignore-scripts` suppresses dependency lifecycle scripts. +The daemon needs npm on its command path. Plugins using only host libraries need no preparation +command. See [preparation](#plugins-with-a-build-step) for generated files or explicit scripts. + +Users can install directly from Git without a registry listing: + +```bash +paseo plugin add git:acme/paseo-review +paseo plugin add git:acme/monorepo:plugins/review +``` + +Use `--ref` to select a branch, tag or commit for the initial installation. Direct installation +also supports private repositories and other Git hosts when the daemon has access; see +[plugin sources](/docs/plugins/reference#plugin-sources). Registry submission accepts public +GitHub sources and public npm packages. ## Plugin registry -Browse published plugins at [paseo.sh/plugins](https://paseo.sh/plugins). -Users install the reviewed artifact with: +Open the [submission form](https://github.com/getpaseo/plugins/issues/new?template=submit-plugin.yml). +Use the form so the issue receives the submission label that starts intake. + +1. Use your plugin's name as the title. +2. In **Source**, enter the public npm package name or page, or the GitHub repository/folder URL. + Include the version or Git reference if you want a specific release reviewed. npm defaults to + `latest`. Registry IDs and local directories are not submission sources. +3. Select the categories that fit. Include any interface-image URLs in the issue description. + +The bot opens a review PR. The reviewer inspects the artifact and dependencies without running +plugin code, completes the listing and records the exact approved version or commit. Publication +requires the [review policy](https://github.com/getpaseo/plugins/blob/main/REVIEW.md), including +locked installation inputs and appropriate data access, even when automated validation passes. + +If a change is requested, reply on the review PR with the corrected version/revision or requested +image URL. The reviewer updates the pin and listing. Intake service errors retry automatically; +missing images or an overview do not prevent opening the review PR. + +After approval and publication, users install your listing with: ```bash paseo plugin add owner/slug ``` -Publish your artifact through npm or Git, then follow the -[registry submission guide](https://github.com/getpaseo/plugins) to submit it for review. -Registry installations and updates use the approved revision and plugin path. -Direct Git installs use explicit `git:owner/repository` shorthand or a full Git URL. +npm releases receive automatic update PRs. Submit Git updates manually with the desired revision. +Existing registry installations use approved pins; direct npm/Git installs follow their own update +rules in the [source reference](/docs/plugins/reference#plugin-sources). -## Publish on npm +## Plugins with a build step -The scaffold prepares the package files and development dependencies. You choose the package name -and release version. +Paseo compiles TypeScript, so an ordinary plugin needs no separate publication build. +Keep generated modules in their runtime directory and host-provided modules external. -### 1. Set your package name and version +Paseo suppresses npm lifecycle scripts during package acquisition. Commands explicitly declared in +manifest `build` still run, including scripts they invoke. Explain the purpose of those commands +and keep their inputs locked and inspectable. Remove Git-only dependency-install commands from +npm manifests when npm already installs the production dependencies. -From the plugin directory, set your package details and allow publication. Replace `@acme` with your npm scope: +Later setup that installs another dependency tree needs its own complete lock, even if your plugin +has a development lockfile. For npm setup, ship the runtime manifest and lock together and use +`npm ci`. For Python setup, ship a requirements file containing exact versions and SHA-256 hashes +for all transitive packages, then install it with: ```bash -npm pkg set name=@acme/paseo-review version=1.0.0 -npm pkg delete private +python -m pip install --require-hashes -r requirements-documents.txt ``` -### 2. Check and publish +This command rejects unpinned or unhashed dependencies. Runtime installation also needs the +[confirmation and disclosure](#your-listing-page) described above. -```bash -npm run typecheck -npm pack --dry-run -npm publish --access public -``` - -Check the pack output includes any assets you added to the project. - -### 3. Test the published plugin - -On a daemon host with npm available: - -```bash -paseo plugin install npm:@acme/paseo-review@1.0.0 -``` - -Users can also paste `npm:@acme/paseo-review` into **Settings → Plugins → Plugin source**. - -:::example[Package configuration] - -The scaffold includes this `files` list in `package.json`: - -```json -{ - "files": [ - "paseo-plugin.json", - "OVERVIEW.md", - "index.client.ts", - "index.client.tsx", - "index.server.ts", - "index.server.tsx", - "client/", - "server/", - "shared/" - ] -} -``` - -- Add any assets stored outside these directories to `files`. -- Keep the scaffold's SDK and host libraries in `devDependencies`. -- Add other runtime libraries with `npm install `. Paseo installs their dependencies too. -- The npm package name identifies the source. The manifest's `id` identifies the installed plugin. - -See the [project reference](/docs/plugins/reference#project-files) for entry points and runtime boundaries. - -::: - -### Plugins with a build step - -Paseo compiles TypeScript. An ordinary plugin needs no separate build before publication. -If your plugin generates files, include the generated output in the package. - -**Installation scripts do not run automatically.** If a dependency needs host-specific setup, -declare a [preparation command](/docs/plugins/reference#cli-reference). - -:::example[Generated files and dependencies] - -- Generate code and assets before running `npm publish`. -- Keep generated JavaScript in its runtime directory and import it from the TypeScript entry. -- Include generated assets in `files`. -- Keep host-provided modules external when producing your own bundle. -- Remove Git-only dependency-install commands from the published manifest; npm installation already - installs production dependencies. - -Paseo skips npm lifecycle scripts during installation, including dependency scripts. For example, -a native dependency that needs rebuilding requires an explicit preparation command. - -::: +## Private npm packages :::example[Publish a private package with GitHub Packages] @@ -151,104 +281,3 @@ Paseo uses the host's npm registry settings and credentials for installation and In the app, enter only the source identifier. ::: - -## Icons and screenshots - -Declare your display name, icon, screenshots, and demo videos in `paseo-plugin.json`: - -```json -{ - "id": "review-tools", - "name": "Review tools", - "description": "Reviews changes before merge", - "icon": "assets/icon.png", - "media": ["assets/screenshot.png", "https://example.com/review-demo.mp4"], - "requirements": { "paseo": ">=0.11.0" } -} -``` - -All three fields are optional. `name` gives the registry and website a display name without -changing the installation ID. When omitted, the registry falls back to a humanized ID. -Registry and website display requires the registry builder to read these fields from the pinned -manifest. That update is a separate follow-up; until it lands, these fields are exposed only -through the daemon's installed-plugin list. -`icon` must point to a PNG inside the plugin package. `media` accepts paths to images and videos -inside the package or HTTPS URLs, in display order. Paths are relative to the manifest; use -forward slashes and keep them inside the package. See the [manifest reference](/docs/plugins/reference#project-files) -for validation rules. - -Commit local assets alongside the manifest at the pinned revision. For npm, add their directory -(for example, `assets/`) to `package.json`'s `files` list and verify it with `npm pack --dry-run`. -The scaffold documents these fields in its manifest's `$comment`; add your display name and -assets before publishing. - -Manifests using these fields fail to install on daemons before 0.11.0. Set -`requirements.paseo` to `>=0.11.0` or a narrower supported range. - -## Your listing page - -Write `OVERVIEW.md` beside `paseo-plugin.json` for the plugin page inside Paseo. -It helps someone decide whether to install your plugin; the install command is already at -the top of that page. A README assumes a GitHub audience and carries installation -instructions, technical details, and badges. Long, AI-generated READMEs make people read -past that material to understand what a plugin does. - -`OVERVIEW.md` is required to list your plugin in the registry. Commit it beside -`paseo-plugin.json` in the source repository at the pinned commit. The registry resolves it -relative to the manifest, under `pluginPath` for monorepos. Include it in the published npm -package too; the scaffold's `files` list includes it. Replace the scaffold's guidance comment -with useful facts before publishing. - -The repository overview takes precedence over a registry import stopgap. Online validation -fails when the pinned commit has no `OVERVIEW.md`, except for unchanged imported records -that already carry `plugins//.md` in the registry repository. Every version bump -requires a repository overview and removes the stopgap in the same PR. A bump without the -repository overview fails validation. README files do not supply the overview. - -Author overviews and registry stopgaps follow the same content contract, in this order. -Choose headings only when they help; length follows complexity. A theme needs one paragraph. - -1. Explain what the plugin is and does in plain terms first. -2. Explain how it works only when that is not obvious. -3. Explain setup when needed: settings, accounts, tokens, providers, external tools, or other - plugins. Include applicable daemon version and operating system requirements. Setup - guidance is allowed; installation instructions are not. -4. Explain capabilities and settings worth understanding, what each option does, what the - plugin reads or sends and where, permissions, and known limits. - -Use sentence case and plain factual language, with no em dashes. Omit installation commands, -badges, changelog, contributing or license sections, marketing, and unsupported claims. -Avoid implementation filler such as empty cleanup functions, catalogs of theme-token fields, -or lists of absent features. Keep only what helps someone choose the plugin. - -If your plugin is an unchanged imported record, you can propose an author-written overview -to replace the registry stopgap. Do not add import credit to your own `OVERVIEW.md`. - -## Share through GitHub or Git - -Push the plugin project to a repository. Users can install it with: - -```bash -paseo plugin add git:acme/paseo-review -``` - -For another Git host: - -```bash -paseo plugin install git:https://git.example.com/acme/paseo-review.git -``` - -If your plugin has runtime npm dependencies, commit `package-lock.json` and add a preparation -command to `paseo-plugin.json`: - -```json -{ - "build": [["npm", "ci", "--omit=dev"]] -} -``` - -- `npm ci` installs the versions in the committed lockfile. -- `--omit=dev` excludes development tools. -- npm must be available on the daemon host. - -Plugins that only use Paseo's host libraries need no preparation command. diff --git a/public-docs/plugins/reference.md b/public-docs/plugins/reference.md index 04c88bdf1a..409bb3f5a6 100644 --- a/public-docs/plugins/reference.md +++ b/public-docs/plugins/reference.md @@ -63,7 +63,9 @@ The required root manifest is `paseo-plugin.json`: | `build` | No | Preparation commands, described in the CLI reference. | Paths are relative to `paseo-plugin.json`, use forward slashes, and cannot contain `..` -segments. See [icons and screenshots](/docs/plugins/publishing#icons-and-screenshots) for an example. +segments. Registry listings for visual plugins require an interface image even though `media` is +optional in the runtime manifest. See [icons and screenshots](/docs/plugins/publishing#icons-and-screenshots) +for accepted formats and listing requirements. Paseo validates the references without opening local assets or fetching URLs. Unknown top-level fields are ignored. Known fields still validate, and unknown keys inside @@ -2137,7 +2139,7 @@ export default function contribute(server: PluginServerContext) { Inputs and outputs are validated on both sides. RPC names start with a lowercase letter and contain lowercase letters, numbers, dots, hyphens, or underscores. `useRpc()` returns a typed async function. Use TanStack Query for request state, caching, and mutations. -Backend handlers receive the same `PaseoApi` as `{ paseo }`. Their connection belongs to the subprocess and closes when the plugin stops. It does not subscribe to timelines or catalog events until plugin code subscribes. Follow the [SDK event contract](../../sdk/events.md) for cleanup and timeline replacements. Backend code can use Node APIs and dependencies installed in the plugin directory. +Backend handlers receive the same `PaseoApi` as `{ paseo }`. Their connection belongs to the subprocess and closes when the plugin stops. It does not subscribe to timelines or catalog events until plugin code subscribes. Follow the [SDK event contract](/docs/sdk/events) for cleanup and timeline replacements. Backend code can use Node APIs and dependencies installed in the plugin directory. ## Debug backend output @@ -2351,8 +2353,9 @@ keeps the complete dependency tree and `package-lock.json` when activating it. T package and lockfile provide its current version and artifact integrity. A version, tag, or range chooses content for this installation only. -For package contents, dependencies, preparation, and private registries, see -[Publish a plugin](/docs/plugins/publishing). +The installed lockfile records what this installation resolved. Authors submitting npm plugins +with runtime dependencies must also ship the [publication lock](/docs/plugins/publishing#2-lock-installed-dependencies). +For package contents, preparation and submission, see [Publish a plugin](/docs/plugins/publishing). A failed download, dependency installation, manifest check, preparation command, compilation, or activation discards the candidate. Other installed plugins keep running. Removing an npm plugin diff --git a/public-docs/supported-providers.md b/public-docs/supported-providers.md index f2b1370b68..1aa981ba29 100644 --- a/public-docs/supported-providers.md +++ b/public-docs/supported-providers.md @@ -85,6 +85,7 @@ Pick any of these from the in-app provider catalog. Each entry is a one-click in - [goose](https://block.github.io/goose/), Block's local open-source AI agent. - [Grok](https://docs.x.ai/build/overview), xAI's Grok Build agentic coding CLI. - [Hermes Agent](https://hermes-agent.nousresearch.com/docs/user-guide/features/acp), Nous Research's self-improving agent. +- [Hoplite](#hoplite), cloud coding agent through its local ACP bridge. - [Junie](https://junie.jetbrains.com/docs/junie-cli-acp.html), JetBrains' coding agent. - [Kilo Code](https://kilo.ai/docs/code-with-ai/platforms/cli), open-source coding agent. - [Kimi Code CLI](https://github.com/MoonshotAI/kimi-code), Moonshot AI's coding assistant. @@ -100,3 +101,18 @@ Pick any of these from the in-app provider catalog. Each entry is a one-click in - [VT Code](https://github.com/vinhnx/VTCode/blob/main/docs/guides/zed-acp.md), open-source multi-provider coding agent. The in-app catalog is the canonical, version-pinned source. Anything not listed here can still be added manually, see [Custom providers](/docs/custom-providers). + +### Hoplite + +Install the [Hoplite CLI](https://hoplite.sh/docs/cli) on your daemon host and run +`hoplite login`. In **Settings → Hosts → your host → Providers**, find **Hoplite** +in the catalog and choose **Add**. Paseo launches `hoplite acp` through the generic ACP adapter. + +Hoplite runs the agent in a cloud workspace. Open a repository linked to a Hoplite project, +or set `agents.providers.hoplite.env.HOPLITE_PROJECT_ID` to use one project everywhere. +Without a linked repository or pinned project, discovery reports `No Hoplite project`. +Your local files and Paseo's loopback MCP tools are not available in that cloud workspace. + +See [Hoplite's ACP guide](https://hoplite.sh/docs/cli/acp) for authentication and project setup. +Use a [command override](/docs/custom-providers) if `hoplite` is outside your daemon's PATH; +keep `acp` in the arguments.
Hoplite
Cloud coding agents
Hoplite
Cloud coding agents
Become a sponsor Become a sponsor