Compare commits

..
Author SHA1 Message Date
Mohamed Boudra 6c89950b2e chore(release): cut 0.17.0-beta.1 2026-11-19 14:48:37 +01:00
Mohamed Boudra fbbfcf42bc docs(changelog): prepare 0.17.0 beta 2026-11-19 14:43:29 +01:00
397 changed files with 7893 additions and 30425 deletions
-63
View File
@@ -1,63 +0,0 @@
# Brand assets
Canonical marks, lockups, and wordmark font for **Paseo** and **Paseo Hub**. These are the source assets that will replace the existing icons across the app, desktop client, website, docs, and Hub in follow-up work.
## Brand architecture
- **Paseo** (butterfly mark): the local client, daemon, CLI, SDK, and small account features (sign-in, share links, tunnels).
- **Paseo Hub** (flower mark): the software factory, team features, hosted service, and paid plans (`Hub Free`, `Hub Solo`, `Hub Team`).
- **Hub** (flower mark + `Hub`): used only where Paseo is already on screen, such as inside the Hub dashboard header.
## Specifications
### Marks
Both marks are single-line stroked paths on a `700 × 700` viewBox with `stroke-width="50"`, `stroke-linecap="round"`, and `stroke-linejoin="round"`. Both are optically centered to a `527`-unit ink footprint:
- **Paseo (`marks/paseo-*.svg`)**: refit of the hand-drawn butterfly (redraw B) with smooth curvature on the large wing and lower loop and a uniform `50` stroke width.
- **Paseo Hub (`marks/paseo-hub-*.svg`)**: five-petal looped flower (variant A) with a `12°` clockwise petal lean, sized up to match the butterfly's `527` footprint with the same `50` stroke.
Colors:
- `white` (`#FFFFFF`) for dark surfaces (`#101615`, `#101010`, `#000000`)
- `black` (`#000000`) for light surfaces
- `green` (`#20744A`) brand accent
### Lockups
All lockups (`lockups/*.svg`) share a `144`-unit height (`140`-unit flower ink height with a `2`-unit margin on all sides) so stacked lockups align cleanly:
- **Font**: Plus Jakarta Sans SemiBold (`600`), bundled in `fonts/PlusJakartaSans-SemiBold.ttf` under the SIL Open Font License 1.1 (`fonts/OFL.txt`).
- **Outlined text**: lockup SVGs outline the wordmark to `<path>` elements so they render identically everywhere without the font installed.
- **Proportions**: marks are `15%` larger against text and `20%` closer than the original website header baseline (`24 px` box, `12 px` gap, `18 px` text).
- **Optical balance**: in the `paseo` lockup, the butterfly is scaled to `94%` (`stroke-width` proportional) so `Paseo`, `Paseo Hub`, and `Hub` sit at equal visual weight when shown together.
## Files
```text
assets/brand/
build.mjs Regenerates all marks and lockups
fonts/
PlusJakartaSans-SemiBold.ttf
OFL.txt
marks/
paseo-white.svg
paseo-black.svg
paseo-green.svg
paseo-hub-white.svg
paseo-hub-black.svg
paseo-hub-green.svg
lockups/
paseo-white.svg
paseo-black.svg
paseo-hub-white.svg
paseo-hub-black.svg
hub-white.svg
hub-black.svg
```
## Regenerate
```sh
node assets/brand/build.mjs
```
File diff suppressed because one or more lines are too long
-93
View File
@@ -1,93 +0,0 @@
Copyright 2020 The Plus Jakarta Sans Project Authors (https://github.com/tokotype/PlusJakartaSans)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file not shown.
File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 7.9 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 7.9 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 11 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 14 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 14 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 11 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 5.9 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 5.9 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 6.7 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 6.7 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 6.7 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 5.9 KiB

+5 -7
View File
@@ -186,13 +186,11 @@ Terminal activity contributes to the workspace status bucket **per `workspaceId`
Single file, validated with `PersistedConfigSchema`.
`agents.skills.selection` stores the orchestration-skill preference for the daemon host, and a
missing value defaults to `{ mode: "all" }`. The daemon does not persist installed state. It
derives installed state from `~/.agents/skills`, `~/.claude/skills`, and `~/.gemini/config/skills`,
and serializes configuration and filesystem convergence through one owner. Codex and Gemini CLI
discover `~/.agents/skills`, while Antigravity discovers `~/.gemini/config/skills`. Updates retire
unchanged files from Paseo-managed copies in `~/.codex/skills` and preserve user edits and
untracked files.
`agents.skills.selection` is the daemon host's orchestration-skill preference. Missing means
`{ mode: "all" }`. Installed state is not persisted; the daemon derives it from the shared
`~/.agents/skills` and Claude skill directories and keeps config plus filesystem convergence behind
one serialized owner. Codex discovers the shared directory. Updates retire unchanged files from
Paseo-managed copies in `~/.codex/skills`, preserving user edits and untracked files.
`paseo reload` reads and validates this file once inside the daemon. That snapshot drives resolution,
classification, application, and reload bookkeeping. `DaemonConfigStore` owns applying runtime-safe
+6 -6
View File
@@ -134,7 +134,7 @@ A section or group explains itself through the `info` prop on `<SettingsSection>
Cards inside a section sit closer than sections. Rows inside a card touch — only the divider separates them. The rhythm is page → spacious; section → spacious; card → tight.
Rows have generous vertical padding: roughly 16px of content plus 16px of vertical padding for settings rows, 8–12px for sidebar list items where many rows must fit. A row that opens something (`<SettingsDetailRow>`, a collapsible row's header) is at least as tall as one holding a default control, so a list where only some of those rows carry a switch keeps one row height. Other rows take their content's height. Compressing rows below the established density to fit more on the screen is wrong. Too many rows means more cards or more sections, not smaller rows.
Rows have generous vertical padding: roughly 16px of content plus 16px of vertical padding for settings rows, 8–12px for sidebar list items where many rows must fit. Compressing rows below the established density to fit more on the screen is wrong. Too many rows means more cards or more sections, not smaller rows.
Rows revealed under a `<SettingsCollapsibleRow>` are nested rows, one step smaller than card rows: 8px of vertical padding, `fontSize.sm` text, `sm` controls, and one fixed height so rows with and without a trailing button line up. The collapsible row sets this for everything under it (`packages/app/src/components/settings/row-density.tsx`). Never pass a density to a row, and never pad or resize a nested row by hand. Settings rows that share a menu surface with menu rows, such as Usage's options, go inside `<MenuSettingsRows>`, which puts their labels on the menu rows' label rail (`menuRowContentInset`).
@@ -207,11 +207,11 @@ Terminology:
## 11. States
Loading is inline by default. `<LoadingSpinner size={14} color={foregroundMuted} />` leads the line it relates to, never trails a label: a settings row's hint takes `hintStatus="busy"` while its work runs, and `hintStatus="pending"` holds the line with a skeleton until its value is read (`packages/app/src/components/settings/row-header.tsx`). Page-level loading is a centered `<LoadingSpinner size="large">` (`packages/app/src/screens/sessions-screen.tsx:69-72`). Card-level loading is a single short line, not a spinner. In-row dropdown items use `<DropdownMenuItem status="pending" pendingLabel="Removing...">`; the menu item handles its own pending state.
Loading is inline by default. `<LoadingSpinner size={14} color={foregroundMuted} />` sits next to the thing it relates to (`packages/app/src/screens/settings/providers-section.tsx:227-231`). Page-level loading is a centered `<LoadingSpinner size="large">` (`packages/app/src/screens/sessions-screen.tsx:69-72`). Card-level loading is a single short line, not a spinner. In-row dropdown items use `<DropdownMenuItem status="pending" pendingLabel="Removing...">`; the menu item handles its own pending state.
Screen-level empty states use a centered, muted noun phrase and at most one ghost button (`packages/app/src/screens/sessions-screen.tsx`). Sidebar list empty states use a quiet bordered card with a left-aligned `sm` title, a muted `sm` description, and `sm` `<Button>` actions. Use `secondary` for the primary action and `outline` for a secondary action (`packages/app/src/components/sidebar/empty-states.tsx`). Keep both forms short and free of illustrations.
Inline errors are a single sentence in `palette.red[300]` `xs`, sitting under the field or inside the card it relates to (`packages/app/src/components/ui/form-field.tsx`). A settings row that is broken says so in its hint with `hintStatus="error"`: a red dot and the error in `statusDanger`.
Inline errors are a single sentence in `palette.red[300]` `xs`, sitting under the field or inside the card it relates to (`packages/app/src/screens/settings/providers-section.tsx:115-119`).
Page-level alerts — informational notices, success confirmations, warnings, or recoverable errors that need a small visible block on the page — use `<Alert>` (`packages/app/src/components/ui/alert.tsx`). Variants: `default`, `info`, `success`, `warning`, `error`. The chrome is quiet by design: a 1px tinted border, transparent background, a small variant-tinted icon, the title in the variant accent, the description in `foregroundMuted`. Actions go in the `children` slot as `<Button variant="outline">` — recovery actions are low-frequency and outline keeps them quiet alongside the alert's accent (`packages/app/src/screens/project-settings-screen.tsx`). One `<Alert>` at a time per region.
@@ -233,13 +233,13 @@ Changing state must not move the layout. A row that grows when its badge arrives
The row anatomy is a content column with an optional trailing slot. Inside a card the row is `settingsStyles.row`. Inside a sidebar list the row carries its own padding and `borderRadius.lg` per item (`packages/app/src/components/sidebar-workspace-list.tsx:2614-2625`).
A trailing chevron opens a detail, as a page or a sheet (`ChevronRight`, `iconSize.sm`, `foregroundMuted`). The whole row is the pressable; use `<SettingsDetailRow>`. Pair-device row (`packages/app/src/screens/settings/host-page.tsx`), provider row (`packages/app/src/provider-settings/internal/provider-row.tsx`), project row in the projects list. A fixed right chevron means navigation. An expandable row uses a trailing right chevron that rotates down when expanded (`SettingsCollapsibleRow`); pressing the row reveals its child rows in place.
Rows that drill into a detail lead with a chevron in the trailing slot (`ChevronRight`, `iconSize.sm`, `foregroundMuted`). The whole row is the `<Pressable>`. Pair-device row (`packages/app/src/screens/settings/host-page.tsx:644-668`), provider row (`packages/app/src/screens/settings/providers-section.tsx:92-132`), project row in the projects list. A fixed right chevron means navigation. An expandable row uses a trailing right chevron that rotates down when expanded (`SettingsCollapsibleRow`); pressing the row reveals its child rows in place.
Kebab menus (`<DropdownMenu>` with `<MoreVertical size={14} />` trigger) are for actions on the row, not navigation. Trigger style: `padding: 2`, `borderRadius: 4`, hover background `surface2`. Menu position: `align="end"`. Items use `<DropdownMenuItem leading={<Icon size={14} color={foregroundMuted} />} ...>`. Visibility is `isHovered || isTouchPlatform` — hover-revealed on web, always visible on native (`packages/app/src/components/sidebar-workspace-list.tsx:684-770`).
A row may carry both a chevron and a kebab when both navigation and row-level actions apply. Chevron sits at the end; kebab sits before it.
Switches and segmented controls also sit in the trailing slot. A row that both navigates and toggles passes its `<Switch>` as the `control` of `<SettingsDetailRow>`, before the chevron; the switch stops the press from reaching the row (`packages/app/src/provider-settings/internal/provider-row.tsx`). A list the user adds to ends with a muted `<SettingsAddRow>`. Sidebar items that hold a status dot, a count, and a kebab follow the same rule (`packages/app/src/components/sidebar-workspace-list.tsx`).
Switches and segmented controls also sit in the trailing slot. A row that both navigates and toggles is a `<Pressable>` with a `<Switch>` in the trailing slot — the switch calls `event.stopPropagation()` so the row press does not fire (`packages/app/src/screens/settings/providers-section.tsx:92-132`). Sidebar items that hold a status dot, a count, and a kebab follow the same rule (`packages/app/src/components/sidebar-workspace-list.tsx`).
Selected state on rows in a desktop list+detail uses `surfaceSidebarHover` as the background (`packages/app/src/screens/projects-screen.tsx`). Selected state on rows in the sidebar list uses `surface2` (`packages/app/src/components/agent-list.tsx:563-571`).
@@ -288,7 +288,7 @@ New status pills use `<StatusBadge>`. Identity, shortcut, and interactive link b
| Pattern | Reference |
| --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| List+detail (compact stack, desktop sidebar+pane) | `packages/app/src/screens/settings-screen.tsx`, `packages/app/src/screens/projects-screen.tsx` |
| Detail card+row | `packages/app/src/screens/settings/host-page.tsx`, `packages/app/src/provider-settings/internal/provider-list.tsx` |
| Detail card+row | `packages/app/src/screens/settings/host-page.tsx`, `packages/app/src/screens/settings/providers-section.tsx` |
| Section grouping inside a card list | `packages/app/src/screens/settings/settings-section.tsx` |
| Form modal (label + input fields, primary + cancel) | `packages/app/src/hosts/add-host/internal/add-host-modal.tsx`, `packages/app/src/hosts/add-host/internal/pair-link-modal.tsx`, `packages/app/src/components/project-picker-modal.tsx` |
| Destructive confirmation | `confirmDialog` invoked from `packages/app/src/screens/settings/host-page.tsx:541-547` |
-12
View File
@@ -510,18 +510,6 @@ before calling status; it exposes your diagnostic through the normal provider di
A command-backed provider without status is available when its executable resolves. Providers with
neither command nor status retain connection-based availability.
Implement optional `installation` to fill the **Installation** section of provider settings. The
bridge sends each callback as a `provider.installation.*` request carrying the launch `status`
receives plus `resolved`. `resolved: false` means the executable was not found and `command` is
the configured name, so answer `not_installed` instead of spawning it. Inspect and update-check
requests use the 30 s plugin request timeout; the daemon's 25 s update-check deadline sits below
it, so a slow check reports that deadline. `update` has no request timeout and streams output
through `provider.installation.report`. When the daemon stops waiting on any of the three, it
sends `provider.installation.cancel`, which aborts the callback's `signal`.
The rules shared with built-ins are in [providers.md](providers.md#installation-and-updates); the
author contract is in the
[public provider guide](../public-docs/plugins/providers.md#report-installation-and-updates).
A same-ID config entry without `extends` overrides the plugin's `enabled`, `command`, `env`, label,
description, and model configuration through the normal provider registry. `enabled: false` disables
selection and discovery. An entry with `extends` defines the user's own provider, shadows the plugin,
-47
View File
@@ -263,53 +263,6 @@ promise for completion: equal results, including equal discovery timestamps, emi
---
## Installation and updates
The provider list and the **Installation** section of a provider's page read `AgentClient.installation`. Built-ins set
it on the client; plugins set `ProviderRegistration.installation`, which the plugin bridge maps to
the same interface. `ProviderInstallations` in `packages/server/src/server/agent/provider-installation/`
owns deadlines, caching and the one running update per provider, so a provider only answers.
Declare only what the vendor offers:
- `installUrl` and `updateUrl` link the vendor's own install and update docs.
- `inspect` reports the version the CLI prints. Versions are opaque: Paseo shows them as written
and never parses them.
- `checkForUpdates` receives the version `inspect` reported as `installedVersion` and asks the
source the CLI's own updater reads, such as the vendor's release endpoint or the CLI's
`update --check`. Do not read the version again. Leave it out when that source is inside the binary or
depends on how the CLI was installed, which is why Copilot and OpenCode have no check. Do not
build a release lookup of your own.
- `update` runs the CLI's own update command and passes its output through, using
`runUpdateCommand`. Paseo adds no verification, signature check or rollback, so the update does
exactly what the same command does in a terminal.
The three calls are separate because they cost differently. `inspect` runs for every provider
whenever the provider list shows, because each row states its version; a provider's page shares the
row's request. It has a 20 s deadline and a 30 s cache. `checkForUpdates` usually reaches the
network. Paseo calls it only after `inspect` reports the CLI installed, and keeps a conclusive
answer for an hour while `inspect` reports the same version, so a CLI updated outside Paseo is
checked again once the 30 s inspection expires. `update` runs for minutes, streams output, and is
aborted only when the daemon stops. A failed update stays on the provider until the next refresh
of its installation, which tells every client observing the provider's updates that it is gone; a
running one is never dropped.
The update check only informs. Once `inspect` reports the CLI installed, the app offers **Update**
for a provider that declares `update`, or **Update instructions** for one that declares only
`updateUrl`, whatever the check answers and whether the provider has one. The check's answer shows
beside the action when it has one. Copilot and OpenCode have no check, so they show **Update** alone.
Write the success message for the provider's process model. A CLI that Paseo starts once per agent
uses `updatedForNewAgents()`. OpenCode agents share one server that keeps the old binary running,
so its message asks the user to restart the daemon.
`createCliInstallation()` covers a CLI that prints `--version` and updates with a subcommand. It
resolves the configured command, so a profile that extends a built-in reports and updates the CLI
that profile launches. Clients for `extends: "acp"` providers declare no installation.
Test with fake executables, as `providers/provider-update-checks.test.ts` does. Running a real
updater during development replaces the CLI on your machine.
## Usage sources
See the [public usage source reference](../public-docs/plugins/reference.md#usage-sources) for the
+1 -1
View File
@@ -1 +1 @@
sha256-T3mbzIj0+IZBS4XA+4Ab6e6LtIi8PX4Rzs4wFEWeClk=
sha256-yLTaVMgu3tc/dgngJ7RP0htJcWE0ZtQ4mouypevyv0s=
-10
View File
@@ -6651,15 +6651,6 @@
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/plus-jakarta-sans": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/plus-jakarta-sans/-/plus-jakarta-sans-5.3.0.tgz",
"integrity": "sha512-/l/4r0yyWK9JzAlmA0LiYgGgmJe/Gswt4jTJEzr5QhJfwMbvJZDmYWyW0M4X7yCK69BajMVlV/Lx8g7WDc1+sw==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@getpaseo/app": {
"resolved": "packages/app",
"link": true
@@ -41488,7 +41479,6 @@
"@cloudflare/vite-plugin": "^1.29.1",
"@cloudflare/workers-types": "^4.20260317.1",
"@fontsource-variable/geist": "^5.3.0",
"@fontsource-variable/plus-jakarta-sans": "^5.3.0",
"@getpaseo/protocol": "*",
"@tanstack/react-router": "^1.170.16",
"@tanstack/react-start": "^1.168.26",
@@ -15,8 +15,7 @@ import {
expectProviderInstalledInSettings,
findAcpCatalogProvider,
installAcpCatalogProvider,
openAddProvider,
openProviderDetail,
openAddProviderArea,
openSettingsHost,
openSettingsHostSection,
seedSavedSettingsHosts,
@@ -29,12 +28,7 @@ const ACP_PROVIDER = {
interface ProviderCatalogDaemonClient {
getLastServerInfoMessage(): {
features?: {
gooseProvider?: boolean;
fxProvider?: boolean;
hopliteProvider?: boolean;
plugins?: boolean;
};
features?: { fxProvider?: boolean; hopliteProvider?: boolean; plugins?: boolean };
} | null;
connect(): Promise<void>;
close(): Promise<void>;
@@ -53,7 +47,7 @@ test.describe("ACP provider catalog", () => {
await openSettings(page);
await openSettingsHost(page, getServerId());
await openSettingsHostSection(page, getServerId(), "providers");
await openAddProvider(page);
await openAddProviderArea(page);
await installAcpCatalogProvider(page, ACP_PROVIDER.name);
await expectProviderInstalledInSettings(page, ACP_PROVIDER.name);
@@ -75,7 +69,7 @@ test("adds fx from the catalog with only a config entry", async ({ page }, testI
await openSettings(page);
await openSettingsHost(page, getServerId());
await openSettingsHostSection(page, getServerId(), "providers");
await openAddProvider(page);
await openAddProviderArea(page);
await findAcpCatalogProvider(page, "fx");
await page.screenshot({ path: testInfo.outputPath("fx-catalog.png") });
@@ -110,7 +104,7 @@ for (const theme of ["light", "dark"] as const) {
await expect(
page.getByRole("button", { name: "Hoplite provider details", exact: true }),
).toHaveCount(0);
await openAddProvider(page);
await openAddProviderArea(page);
await findAcpCatalogProvider(page, "Hoplite");
await page.screenshot({ path: testInfo.outputPath(`hoplite-catalog-${theme}.png`) });
await installAcpCatalogProvider(page, "Hoplite");
@@ -133,7 +127,7 @@ for (const theme of ["light", "dark"] as const) {
testInfo.outputPath(`hoplite-removed-${theme}.json`),
JSON.stringify(await client.getProvidersSnapshot(), null, 2),
);
await openAddProvider(page);
await openAddProviderArea(page);
await findAcpCatalogProvider(page, "Hoplite");
await page.screenshot({ path: testInfo.outputPath(`hoplite-removed-${theme}.png`) });
await installAcpCatalogProvider(page, "Hoplite");
@@ -146,11 +140,11 @@ for (const theme of ["light", "dark"] as const) {
}
async function removeHoplite(page: import("@playwright/test").Page): Promise<void> {
await openProviderDetail(page, "Hoplite");
await page.getByTestId("provider-actions-hoplite").click();
page.once("dialog", (dialog) => {
void dialog.accept();
});
await page.getByTestId("provider-remove").click();
await page.getByTestId("provider-remove-hoplite").click();
}
test("unsupported host asks for an update without writing Hoplite config", async ({
@@ -170,7 +164,7 @@ test("unsupported host asks for an update without writing Hoplite config", async
await openSettings(page);
await openSettingsHost(page, outdatedDaemon.serverId);
await openSettingsHostSection(page, outdatedDaemon.serverId, "providers");
await openAddProvider(page);
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.");
@@ -209,47 +203,3 @@ test("model selector excludes Hoplite before opt-in", async ({ page }, testInfo)
await client.close();
}
});
test("adds bundled goose from the catalog", async ({ page }) => {
const client = await connectDaemonClient<ProviderCatalogDaemonClient>({
clientIdPrefix: "goose-catalog-e2e",
});
try {
expect(client.getLastServerInfoMessage()?.features?.gooseProvider).toBe(true);
await client.patchDaemonConfig({ removeProviders: ["goose"] });
await gotoAppShell(page);
await addGooseFromSettings(page, getServerId());
expect((await client.getDaemonConfig()).config.providers?.goose).toEqual({ enabled: true });
} finally {
await client.patchDaemonConfig({ removeProviders: ["goose"] });
await client.close();
}
});
test("adds goose through ACP on an older host", async ({ page, outdatedDaemon }) => {
const client = await connectDaemonClient<ProviderCatalogDaemonClient>({
clientIdPrefix: "goose-catalog-old-host",
port: Number(new URL(`http://${outdatedDaemon.endpoint}`).port),
});
try {
expect(client.getLastServerInfoMessage()?.features?.gooseProvider).toBe(false);
await seedSavedSettingsHosts(page, [outdatedDaemon]);
await page.reload();
await addGooseFromSettings(page, outdatedDaemon.serverId);
expect((await client.getDaemonConfig()).config.providers?.goose).toMatchObject({
extends: "acp",
command: ["goose", "acp"],
});
} finally {
await client.close();
}
});
async function addGooseFromSettings(page: import("@playwright/test").Page, serverId: string) {
await openSettings(page);
await openSettingsHost(page, serverId);
await openSettingsHostSection(page, serverId, "providers");
await openAddProvider(page);
await installAcpCatalogProvider(page, "goose");
await expectProviderInstalledInSettings(page, "goose");
}
+1 -258
View File
@@ -1598,237 +1598,6 @@ test("canvas diff replaces a selection with forward and backward drags", async (
}
});
test("canvas diff double-click selects the grapheme under the pointer, not the nearest caret", async ({
context,
page,
}) => {
const content = "call(foo bar)";
const workspace = await createWorkspaceWithExactSelectionDiff(content);
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
await useUnwrappedDiffLines(page);
await openSelectionWorkspaceChanges(page, workspace);
await dragAddedTextRange(page, {
lines: [content],
clickCount: 2,
fraction: 0.75,
start: { line: 0, offset: 3 },
end: { line: 0, offset: 3 },
});
await copyDiffSelectionWithKeyboard(page);
await expectClipboardText(page, "call");
await dragAddedTextRange(page, {
lines: [content],
clickCount: 2,
fraction: 0.1,
start: { line: 0, offset: 4 },
end: { line: 0, offset: 4 },
});
await copyDiffSelectionWithKeyboard(page);
await expectClipboardText(page, "(");
});
test("canvas diff double-click selects the clicked word and replaces an existing selection", async ({
context,
page,
}) => {
const content = "alpha bravo charlie delta";
const workspace = await createWorkspaceWithExactSelectionDiff(content);
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
await useUnwrappedDiffLines(page);
await openSelectionWorkspaceChanges(page, workspace);
await dragAddedTextRange(page, {
lines: [content],
start: { line: 0, offset: 0 },
end: { line: 0, offset: 4 },
});
await dragAddedTextRange(page, {
lines: [content],
clickCount: 2,
start: { line: 0, offset: 8 },
end: { line: 0, offset: 8 },
});
await copyDiffSelectionWithKeyboard(page);
await expectClipboardText(page, "bravo");
});
test("canvas diff double-click drag extends the selection word by word in both directions", async ({
context,
page,
}) => {
const content = "alpha bravo charlie delta";
const workspace = await createWorkspaceWithExactSelectionDiff(content);
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
await useUnwrappedDiffLines(page);
await openSelectionWorkspaceChanges(page, workspace);
for (const [start, end, expectedText] of [
[{ line: 0, offset: 8 }, { line: 0, offset: 14 }, "bravo charlie"],
[{ line: 0, offset: 14 }, { line: 0, offset: 2 }, "alpha bravo charlie"],
] as const) {
await dragAddedTextRange(page, { lines: [content], clickCount: 2, start, end });
await copyDiffSelectionWithKeyboard(page);
await expectClipboardText(page, expectedText);
}
});
test("canvas diff double-click drag extends word by word across lines and wrapped lines", async ({
context,
page,
}) => {
const lines = ["alpha bravo", "charlie delta"];
const workspace = await createWorkspaceWithExactSelectionDiff(lines.join("\n"));
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
await useUnwrappedDiffLines(page);
await openSelectionWorkspaceChanges(page, workspace);
for (const [start, end, expectedText] of [
[{ line: 0, offset: 8 }, { line: 1, offset: 10 }, "bravo\ncharlie delta"],
[{ line: 1, offset: 10 }, { line: 0, offset: 2 }, "alpha bravo\ncharlie delta"],
] as const) {
await dragAddedTextRange(page, { lines, clickCount: 2, start, end });
await copyDiffSelectionWithKeyboard(page);
await expectClipboardText(page, expectedText);
}
const wrapped = `${"alpha ".repeat(40)}bravo charlie`;
const wrappedWorkspace = await createWorkspaceWithExactSelectionDiff(wrapped);
await configureDiffPresentation(page, { layout: "unified", wrapLines: true });
await openSelectionWorkspaceChanges(page, wrappedWorkspace);
await setOpenChangesPresentation(page, { layout: "unified", wrapLines: true });
const bravoStart = 40 * "alpha ".length;
await dragAddedTextRange(page, {
lines: [wrapped],
wrapped: true,
clickCount: 2,
start: { line: 0, offset: bravoStart + 2 },
end: { line: 0, offset: bravoStart + 9 },
});
await copyDiffSelectionWithKeyboard(page);
await expectClipboardText(page, "bravo charlie");
});
test("canvas diff double-click drag keeps word selection on the split side", async ({
context,
page,
}) => {
const lines = ["RIGHT-ONE", "RIGHT-TWO"];
const workspace = await createWorkspaceWithExactSelectionDiff(lines.join("\n"));
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
await configureDiffPresentation(page, { layout: "split", wrapLines: false });
await openSelectionWorkspaceChanges(page, workspace);
await setOpenChangesPresentation(page, { layout: "split", wrapLines: false });
await dragAddedTextRange(page, {
lines,
side: "right",
clickCount: 2,
start: { line: 0, offset: 7 },
end: { line: 1, offset: 3 },
});
await page.keyboard.press("ControlOrMeta+C");
await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe("ONE\nRIGHT");
});
test("canvas diff triple-click selects the whole source line and replaces an existing selection", async ({
context,
page,
}) => {
const content = "alpha bravo";
const workspace = await createWorkspaceWithExactSelectionDiff(content);
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
await useUnwrappedDiffLines(page);
await openSelectionWorkspaceChanges(page, workspace);
await dragAddedTextRange(page, {
lines: [content],
start: { line: 0, offset: 0 },
end: { line: 0, offset: 3 },
});
await dragAddedTextRange(page, {
lines: [content],
clickCount: 3,
start: { line: 0, offset: 8 },
end: { line: 0, offset: 8 },
});
await copyDiffSelectionWithKeyboard(page);
await expectClipboardText(page, content);
});
test("canvas diff triple-click drag extends whole source lines in both directions", async ({
context,
page,
}) => {
const lines = ["alpha", "bravo", "charlie"];
const workspace = await createWorkspaceWithExactSelectionDiff(lines.join("\n"));
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
await useUnwrappedDiffLines(page);
await openSelectionWorkspaceChanges(page, workspace);
for (const [start, end] of [
[
{ line: 0, offset: 2 },
{ line: 2, offset: 3 },
],
[
{ line: 2, offset: 3 },
{ line: 0, offset: 1 },
],
] as const) {
await dragAddedTextRange(page, { lines, clickCount: 3, start, end });
await copyDiffSelectionWithKeyboard(page);
await expectClipboardText(page, "alpha\nbravo\ncharlie");
}
});
test("canvas diff triple-click selects every wrapped fragment of a source line", async ({
context,
page,
}) => {
const content = `${"alpha ".repeat(80)}omega`;
const workspace = await createWorkspaceWithExactSelectionDiff(content);
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
await configureDiffPresentation(page, { layout: "unified", wrapLines: true });
await openSelectionWorkspaceChanges(page, workspace);
await setOpenChangesPresentation(page, { layout: "unified", wrapLines: true });
await dragAddedTextRange(page, {
lines: [content],
wrapped: true,
clickCount: 3,
start: { line: 0, offset: 20 },
end: { line: 0, offset: 20 },
});
await copyDiffSelectionWithKeyboard(page);
await expectClipboardText(page, content);
});
test("canvas diff triple-click drag keeps whole source lines on the split side", async ({
context,
page,
}) => {
const lines = ["RIGHT-ONE", "RIGHT-TWO"];
const workspace = await createWorkspaceWithExactSelectionDiff(lines.join("\n"));
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
await configureDiffPresentation(page, { layout: "split", wrapLines: false });
await openSelectionWorkspaceChanges(page, workspace);
await setOpenChangesPresentation(page, { layout: "split", wrapLines: false });
await dragAddedTextRange(page, {
lines,
side: "right",
clickCount: 3,
start: { line: 1, offset: 3 },
end: { line: 0, offset: 4 },
});
await page.keyboard.press("ControlOrMeta+C");
await expect
.poll(() => page.evaluate(() => navigator.clipboard.readText()))
.toBe("RIGHT-ONE\nRIGHT-TWO");
});
test("canvas diff copies only the selected split side", async ({ context, page }) => {
const lines = ["RIGHT-ONE", "RIGHT-TWO"];
const workspace = await createWorkspaceWithExactSelectionDiff(lines.join("\n"));
@@ -2713,8 +2482,6 @@ async function dragAddedTextRange(
side?: "left" | "right";
wrapped?: boolean;
horizontalOffset?: number;
clickCount?: 1 | 2 | 3;
fraction?: number;
},
): Promise<void> {
const body = page.getByTestId("diff-file-0-body");
@@ -2753,38 +2520,14 @@ async function dragAddedTextRange(
columnLeft +
gutterWidth +
8 +
(localOffset + (input.fraction ?? 0)) * metrics.characterWidth -
localOffset * metrics.characterWidth -
(input.horizontalOffset ?? 0),
y: bounds.y + (1 + fragmentsBefore(line) + fragment + 0.5) * lineHeight,
};
};
const start = point(input.start);
const end = point(input.end);
const clickCount = input.clickCount ?? 1;
await page.mouse.move(start.x, start.y);
if (clickCount > 1) {
const isSinglePoint =
input.start.line === input.end.line && input.start.offset === input.end.offset;
if (isSinglePoint && clickCount === 2) {
await page.mouse.dblclick(start.x, start.y);
return;
}
if (isSinglePoint) {
for (let count = 1; count <= clickCount; count += 1) {
await page.mouse.down({ clickCount: count });
await page.mouse.up({ clickCount: count });
}
return;
}
for (let count = 1; count < clickCount; count += 1) {
await page.mouse.down({ clickCount: count });
await page.mouse.up({ clickCount: count });
}
await page.mouse.down({ clickCount });
await page.mouse.move(end.x, end.y, { steps: 12 });
await page.mouse.up({ clickCount });
return;
}
await page.mouse.down();
await page.mouse.move(end.x, end.y, { steps: 12 });
await page.mouse.up();
@@ -2,7 +2,7 @@ import { expect, test } from "../support/fixtures";
import { trackPromptJumpRequests } from "../support/helpers/agent-timeline-gate";
import {
clickChatOutlineRowEdge,
disableChatOutline,
disableChatOutlineFromAppearance,
expectActiveChatOutlinePrompt,
expectActiveChatOutlinePromptMovedFrom,
expectChatOutlinePreview,
@@ -314,13 +314,13 @@ test.describe("desktop chat outline", () => {
}
});
test("can be disabled from Chat settings", async ({ page }) => {
test("can be disabled from Appearance settings", async ({ page }) => {
const agent = await seedLongMockAgentTimeline({ turns: 2 });
try {
await page.setViewportSize(WIDE_VIEWPORT);
await openAgentTimeline(page, agent);
await disableChatOutline(page);
await disableChatOutlineFromAppearance(page);
await expectNoChatOutline(page);
} finally {
+41 -82
View File
@@ -1,30 +1,20 @@
import { expect, test } from "../support/fixtures";
import { test } from "../support/fixtures";
import {
chatOutlineRail,
disableChatOutline,
expectChatOutlinePrompts,
expectNoChatOutline,
} from "../support/helpers/chat-outline";
import {
chooseContentWidth,
expectColumnAtLeftGutter,
expectColumnClearOfOutline,
expectContentColumnWidth,
expectSharedHorizontalRail,
expectCustomContentWidthSetting,
expectDefaultContentWidthSetting,
openAppearanceSettings,
resetContentWidth,
setContentWidth,
} from "../support/helpers/content-width";
import { openFileExplorer, openFileFromExplorer } from "../support/helpers/file-explorer";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
const ULTRAWIDE_VIEWPORT = { width: 2560, height: 1080 };
const DESKTOP_VIEWPORT = { width: 1440, height: 900 };
const TRANSITION_VIEWPORT = { width: 1250, height: 900 };
const DEFAULT_COLUMN = { min: 800, max: 820 };
const WIDE_COLUMN = { min: 1180, max: 1200 };
const FULL_COLUMN = { min: 2000, max: ULTRAWIDE_VIEWPORT.width };
test("resizes mounted chat content and keeps timeline and composer on one rail beside the outline", async ({
test("widens chat and Markdown files to the chosen content width and resets to the default", async ({
page,
}) => {
}, testInfo) => {
test.setTimeout(120_000);
const agent = await seedMockAgentWorkspace({
repoPrefix: "content-width-",
@@ -33,78 +23,47 @@ test("resizes mounted chat content and keeps timeline and composer on one rail b
});
try {
await agent.client.waitForFinish(agent.agentId, 30_000);
await agent.client.sendAgentMessage(agent.agentId, "Write another paragraph.");
await agent.client.waitForFinish(agent.agentId, 30_000);
await page.setViewportSize(ULTRAWIDE_VIEWPORT);
await openAgentRoute(page, agent);
await expectChatOutlinePrompts(page, 2);
const reply = page.getByTestId("assistant-message").first();
const turnFooter = page.getByTestId("turn-footer").first();
const composer = page.getByTestId("message-input-root");
await expectContentColumnWidth(reply, DEFAULT_COLUMN);
await expectSharedHorizontalRail(turnFooter, composer);
const originalReply = await reply.elementHandle();
const assistantMessage = page.getByTestId("assistant-message").first();
const markdownPreview = page.getByTestId("markdown-preview-frame").first();
// In the transition band (pane ~930px >= 918px, < 820 + 120), Default clears the outline on one rail.
await page.setViewportSize(TRANSITION_VIEWPORT);
await expectColumnClearOfOutline(composer, chatOutlineRail(page));
await expectSharedHorizontalRail(turnFooter, composer);
await test.step("chat starts at the default width", async () => {
await openAgentRoute(page, agent);
await expectContentColumnWidth(assistantMessage, { max: 820 });
});
await page.setViewportSize(ULTRAWIDE_VIEWPORT);
await chooseContentWidth(page, "Wide");
await expectContentColumnWidth(reply, WIDE_COLUMN);
await expectContentColumnWidth(composer, WIDE_COLUMN);
await expectSharedHorizontalRail(turnFooter, composer);
await test.step("settings show the default without a reset", async () => {
await openAppearanceSettings(page);
await expectDefaultContentWidthSetting(page, 820);
});
// At 1440px (pane ~1120px < 1200 + 120), Wide clears the outline and keeps timeline and composer aligned.
await page.setViewportSize(DESKTOP_VIEWPORT);
await expectColumnClearOfOutline(composer, chatOutlineRail(page));
await expectSharedHorizontalRail(turnFooter, composer);
await test.step("a custom width is saved and offers a reset", async () => {
await setContentWidth(page, 1600);
await expectCustomContentWidthSetting(page, 1600);
await page.screenshot({ path: testInfo.outputPath("settings-custom-width.png") });
});
await page.setViewportSize(ULTRAWIDE_VIEWPORT);
await chooseContentWidth(page, "Full");
await expectContentColumnWidth(reply, FULL_COLUMN);
await expectContentColumnWidth(composer, FULL_COLUMN);
await expectColumnClearOfOutline(reply, chatOutlineRail(page));
await expectColumnClearOfOutline(composer, chatOutlineRail(page));
await expectSharedHorizontalRail(turnFooter, composer);
await test.step("chat and Markdown files use the custom width", async () => {
await openAgentRoute(page, agent);
await expectContentColumnWidth(assistantMessage, { min: 1200, max: 1600 });
await page.screenshot({ path: testInfo.outputPath("chat-custom-width.png") });
await disableChatOutline(page);
await expectNoChatOutline(page);
await expectColumnAtLeftGutter(page, reply);
await expectColumnAtLeftGutter(page, composer);
await expectSharedHorizontalRail(turnFooter, composer);
await openFileExplorer(page);
await openFileFromExplorer(page, "README.md");
await expectContentColumnWidth(markdownPreview, { min: 1200, max: 1600 });
await page.screenshot({ path: testInfo.outputPath("markdown-custom-width.png") });
});
await chooseContentWidth(page, "Default");
await expectContentColumnWidth(reply, DEFAULT_COLUMN);
await expectContentColumnWidth(composer, DEFAULT_COLUMN);
await expectSharedHorizontalRail(turnFooter, composer);
expect(await originalReply?.evaluate((node) => node.isConnected)).toBe(true);
} finally {
await agent.cleanup();
}
});
test("updates an open Markdown preview when the content width changes", async ({ page }) => {
const agent = await seedMockAgentWorkspace({
repoPrefix: "markdown-content-width-",
title: "Markdown content width",
});
try {
await page.setViewportSize(ULTRAWIDE_VIEWPORT);
await openAgentRoute(page, agent);
await openFileExplorer(page);
await openFileFromExplorer(page, "README.md");
const preview = page.getByTestId("markdown-preview-frame").first();
await expectContentColumnWidth(preview, DEFAULT_COLUMN);
await chooseContentWidth(page, "Wide");
await expectContentColumnWidth(preview, WIDE_COLUMN);
await chooseContentWidth(page, "Full");
await expectContentColumnWidth(preview, { min: 1500, max: ULTRAWIDE_VIEWPORT.width });
await test.step("reset returns to the default without storing it", async () => {
await openAppearanceSettings(page);
await resetContentWidth(page);
await expectDefaultContentWidthSetting(page, 820);
await openAgentRoute(page, agent);
await expectContentColumnWidth(assistantMessage, { max: 820 });
await page.screenshot({ path: testInfo.outputPath("chat-default-width.png") });
});
} finally {
await agent.cleanup();
}
@@ -1,19 +1,10 @@
import { expect, test } from "../support/fixtures";
import { gotoAppShell, openSettings } from "../support/helpers/app";
import { test } from "../support/fixtures";
import {
addCustomModel,
expectCustomModelRetained,
openCustomModels,
removeCustomModel,
removeListedCustomModel,
} from "../support/helpers/custom-models";
import { connectDaemonClient } from "../support/helpers/daemon-client-loader";
import { getServerId } from "../support/helpers/server-id";
import {
openProviderDetail,
openSettingsHost,
openSettingsHostSection,
} from "../support/helpers/settings";
const longModelId = "custom-model-with-a-long-name-".repeat(6);
const shortModelId = "custom-short";
@@ -36,52 +27,3 @@ for (const width of [1200, 390]) {
await removeCustomModel(page, shortModelId);
});
}
/** An ACP provider whose command runs but exits before it answers, so the provider fails. */
const FAILING_PROVIDER = { id: "failing-acp", name: "Failing ACP" } as const;
interface ProviderConfigClient {
connect(): Promise<void>;
close(): Promise<void>;
patchDaemonConfig(config: {
providers?: Record<string, { extends: string; label: string; command: string[] }>;
removeProviders?: string[];
}): Promise<unknown>;
}
test("adds and removes a custom model while the provider fails", async ({ page }) => {
test.setTimeout(120_000);
const client = await connectDaemonClient<ProviderConfigClient>({
clientIdPrefix: "custom-model-failing-e2e",
});
try {
await client.patchDaemonConfig({
providers: {
[FAILING_PROVIDER.id]: {
extends: "acp",
label: FAILING_PROVIDER.name,
command: ["node", "-e", "process.exit(1)"],
},
},
});
await gotoAppShell(page);
await openSettings(page);
await openSettingsHost(page, getServerId());
await openSettingsHostSection(page, getServerId(), "providers");
await openProviderDetail(page, FAILING_PROVIDER.name);
await test.step("the page leads with the failure and lists no reported models", async () => {
await expect(page.getByTestId("provider-error")).toBeVisible({ timeout: 30_000 });
await expect(page.getByText("Custom models", { exact: true })).toBeVisible();
await expect(page.getByRole("textbox", { name: "Search models" })).toHaveCount(0);
});
await addCustomModel(page, shortModelId);
await removeListedCustomModel(page, shortModelId);
} finally {
await client
.patchDaemonConfig({ removeProviders: [FAILING_PROVIDER.id] })
.catch(() => undefined);
await client.close().catch(() => undefined);
}
});
+4 -54
View File
@@ -6,7 +6,6 @@ import {
addProjectFromSetup,
continueSetup,
expectSetupStep,
expectSheetCoversSetupCard,
finishSetup,
goToSetupStep,
hostGivesAgentsPaseoTools,
@@ -24,7 +23,6 @@ import {
recordFirstLaunch,
setupModal,
setupPrimaryButton,
setupSheet,
showSetupAgainFromSettings,
skipSetup,
startSetupHost,
@@ -37,11 +35,7 @@ import {
import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate";
import { enableRelayAndExpectOffer } from "../support/helpers/pair-device";
import { seedWorkspace } from "../support/helpers/seed-client";
import {
installAcpCatalogProvider,
openAddProvider,
openSettingsHostSection,
} from "../support/helpers/settings";
import { openSettingsHostSection } from "../support/helpers/settings";
import { createTempDirectory, createTempGitRepo } from "../support/helpers/workspace";
// Midnight's muted foreground (#9a9db0), which the step description is drawn in.
@@ -65,28 +59,11 @@ test("a new user is walked through setup once", async ({ page }, testInfo) => {
await test.step("Providers shows the same provider list as Settings", async () => {
await continueSetup(page);
await expectSetupStep(page, "Your providers");
await expectSetupStep(page, "Your agents");
await expect(setupModal(page).getByTestId("host-page-providers-card")).toBeVisible();
await page.screenshot({ path: testInfo.outputPath("2-providers.png") });
});
await test.step("a provider's detail and Add provider cover the setup card and lead back to it", async () => {
await setupModal(page)
.getByRole("button", { name: "Claude provider details", exact: true })
.click();
const detail = setupSheet(page, "provider-settings-sheet");
await expectSheetCoversSetupCard(page, detail);
await detail.getByRole("button", { name: "Back to providers", exact: true }).click();
await expect(detail).toHaveCount(0);
await setupModal(page).getByTestId("provider-list-add").click();
const add = setupSheet(page, "add-provider-sheet");
await expectSheetCoversSetupCard(page, add);
await page.keyboard.press("Escape");
await expect(add).toHaveCount(0);
await expectSetupStep(page, "Your providers");
});
await test.step("with no agent history, Add project opens the regular flow and the folder shows as added", async () => {
await continueSetup(page);
await expectSetupStep(page, "Add your projects");
@@ -126,33 +103,6 @@ test("a new user is walked through setup once", async ({ page }, testInfo) => {
}
});
test("a provider removed in setup can be added back and removed again", async ({ page }) => {
test.setTimeout(180_000);
const host = await startSetupHost("re-add");
const detail = setupSheet(page, "provider-settings-sheet");
const remove = detail.getByTestId("provider-remove");
page.on("dialog", (dialog) => void dialog.accept());
try {
await openAppAsNewUser(page, host);
await continueSetup(page);
await expectSetupStep(page, "Your providers");
await openAddProvider(page);
await installAcpCatalogProvider(page, "Junie");
await remove.click();
await expect(detail).toHaveCount(0);
// Adding it back opens the same provider's sheet, which must not still be removing it.
await openAddProvider(page);
await installAcpCatalogProvider(page, "Junie");
await expect(remove).toHaveText("Remove");
await expect(remove).toBeEnabled();
} finally {
await host.close();
}
});
test("a new user goes from the loading screen straight into setup", async ({ page }) => {
const host = await startSetupHost("first-launch");
@@ -195,7 +145,7 @@ test("changing the theme keeps the setup window in place on every step", async (
for (const title of [
"Welcome to Paseo",
"Your providers",
"Your agents",
"Add your projects",
"Let agents use Paseo",
"Take your agents with you",
@@ -468,7 +418,7 @@ test("in the compact layout, Finish on Orchestration applies its switches", asyn
await openAppAsNewUser(page, host);
await step("Welcome to Paseo");
await primary("Continue").click();
await step("Your providers");
await step("Your agents");
await primary("Continue").click();
await step("Add your projects");
await primary("Continue").click();
@@ -1,22 +1,21 @@
import { ACP_PROVIDER_ICON_SVGS } from "../../src/assets/acp-provider-icons";
import { expect, test, type Page } from "../support/fixtures";
import type { Locator, TestInfo } from "@playwright/test";
import type { TestInfo } from "@playwright/test";
import { gotoAppShell, openSettings } from "../support/helpers/app";
import { getServerId } from "../support/helpers/server-id";
import {
findAcpCatalogProvider,
openAddProvider,
openAddProviderArea,
openSettingsHost,
openSettingsHostSection,
} from "../support/helpers/settings";
async function openProviderCatalog(page: Page, viewport?: { width: number; height: number }) {
async function openProviderCatalog(page: Page) {
await gotoAppShell(page);
await openSettings(page);
await openSettingsHost(page, getServerId());
await openSettingsHostSection(page, getServerId(), "providers");
if (viewport) await page.setViewportSize(viewport);
await openAddProvider(page);
await openAddProviderArea(page);
}
async function expectProviderArtwork(
@@ -26,11 +25,11 @@ async function expectProviderArtwork(
name: string,
) {
await findAcpCatalogProvider(page, name);
// Catalog rows have no semantic role of their own; scope artwork to the named provider's row.
const icon = page.getByTestId(`provider-catalog-row-${id}`).locator("svg").first();
// Catalog tiles have no semantic role; scope artwork to the named provider's tile.
const icon = page.getByTestId(`provider-catalog-tile-${id}`).locator("svg").first();
await expect(icon).toBeVisible();
// Artwork draws at the provider list's icon size, so the catalog and the list share a rail.
await expect.soft(icon).toHaveAttribute("width", "16");
// Provider artwork is 24px; the generic PackagePlus fallback is 20px.
await expect.soft(icon).toHaveAttribute("width", "24");
const expectedPaths = await page.evaluate((xml) => {
const document = new DOMParser().parseFromString(xml, "image/svg+xml");
return Array.from(document.querySelectorAll("path"), (path) => path.getAttribute("d")!);
@@ -50,20 +49,3 @@ test("#7087: the provider catalog shows Devin, Hermes, and Kiro artwork", async
await expectProviderArtwork(page, testInfo, "hermes", "Hermes");
await expectProviderArtwork(page, testInfo, "kiro", "Kiro CLI");
});
/** The space between a row's icon and its label, as drawn. */
async function gapAfterIcon(row: Locator, label: string): Promise<number> {
const icon = await row.locator("svg").first().boundingBox();
const text = await row.getByText(label, { exact: true }).boundingBox();
if (!icon || !text) throw new Error(`${label} has no icon or label on screen`);
return text.x - (icon.x + icon.width);
}
test("catalog rows keep the provider list's icon rail on a phone", async ({ page }) => {
await openProviderCatalog(page, { width: 390, height: 844 });
await findAcpCatalogProvider(page, "Kiro CLI");
const listGap = await gapAfterIcon(page.getByTestId("provider-row-claude"), "Claude");
const catalogGap = await gapAfterIcon(page.getByTestId("provider-catalog-row-kiro"), "Kiro CLI");
expect(catalogGap).toBe(listGap);
});
@@ -1,54 +0,0 @@
import { expect, test } from "../support/fixtures";
import { openCustomModels, removeCustomModel } from "../support/helpers/custom-models";
import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate";
// A pressed control shows its own progress while the daemon answers, the way Button's `loading`
// does: a spinner in place of its icon, no further presses and, on a labelled button, a
// present-participle label.
const MODEL_ID = "in-flight-model";
test.describe("provider page work in flight", () => {
test("says Adding... on the Add button while a custom model is saved", async ({ page }) => {
const gate = await installDaemonWebSocketGate(page);
await openCustomModels(page);
await page.getByRole("button", { name: "Add model", exact: true }).click();
const sheet = page.getByTestId("add-custom-model-sheet");
await page.getByPlaceholder("e.g. openai/gpt-5").fill(MODEL_ID);
gate.holdNextServerMessage("set_daemon_config_response");
await sheet.getByRole("button", { name: "Add", exact: true }).click();
await gate.waitForHeldServerMessage("set_daemon_config_response");
const adding = sheet.getByRole("button", { name: "Adding...", exact: true });
await expect(adding.getByRole("progressbar")).toBeVisible();
await expect(adding).toBeDisabled();
gate.releaseHeldServerMessage("set_daemon_config_response");
await expect(sheet).toBeHidden({ timeout: 30_000 });
await removeCustomModel(page, MODEL_ID);
});
test("shows the diagnostic report running again on its re-run button", async ({ page }) => {
const gate = await installDaemonWebSocketGate(page);
await openCustomModels(page);
await page.getByRole("button", { name: "Diagnostic report", exact: true }).click();
const sheet = page.getByTestId("provider-diagnostic-sheet");
const rerun = sheet.getByRole("button", { name: "Refresh diagnostic", exact: true });
await expect(rerun).toBeEnabled({ timeout: 30_000 });
// Copy has a report to copy once the first run is in.
await expect(sheet.getByRole("button", { name: "Copy diagnostic" })).toBeEnabled();
gate.holdNextServerMessage("provider_diagnostic_response");
await rerun.click();
await gate.waitForHeldServerMessage("provider_diagnostic_response");
const running = sheet.getByRole("button", { name: "Refreshing diagnostic", exact: true });
await expect(running.getByRole("progressbar")).toBeVisible();
await expect(running).toBeDisabled();
gate.releaseHeldServerMessage("provider_diagnostic_response");
await expect(rerun).toBeEnabled({ timeout: 30_000 });
});
});
@@ -2,16 +2,11 @@ import type { Dialog } from "@playwright/test";
import { expect, test, type Page } from "../support/fixtures";
import { gotoAppShell, openSettings } from "../support/helpers/app";
import { connectDaemonClient } from "../support/helpers/daemon-client-loader";
import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate";
import { getServerId } from "../support/helpers/server-id";
import {
expectInstallOpensGuide,
expectProviderInstalledInSettings,
expectProviderNotOnHost,
installAcpCatalogProvider,
leaveProviderDetail,
openAddProvider,
openProviderDetail,
openAddProviderArea,
openSettingsHost,
openSettingsHostSection,
} from "../support/helpers/settings";
@@ -20,8 +15,6 @@ import { copyPluginExample } from "../support/helpers/plugin-fixture";
const CUSTOM_PROVIDER = {
id: "junie",
name: "Junie",
// The Add provider catalog's guide. The CLI is not installed where these tests run.
installGuide: "https://junie.jetbrains.com/docs/junie-cli-acp.html",
} as const;
const PLUGIN_PROVIDER = {
@@ -69,39 +62,13 @@ async function clickRemoveProviderAndAcceptWarning(page: Page): Promise<Dialog>
expect(dialog.message()).toContain("This deletes the provider entry from config.json.");
void dialog.accept();
});
await page.getByTestId("provider-remove").click();
await page.getByTestId(`provider-remove-${CUSTOM_PROVIDER.id}`).click();
if (!warning) {
throw new Error("Expected a provider removal confirmation dialog, but none was shown.");
}
return warning;
}
const MISSING_NOTICE = '[data-testid="provider-detail-missing"]';
/** Records whether the page ever says its provider isn't on the host, however briefly. */
async function watchForMissingNotice(page: Page): Promise<void> {
await page.evaluate((selector) => {
const flags = window as unknown as { sawMissingNotice?: boolean };
flags.sawMissingNotice = false;
new MutationObserver(() => {
if (document.querySelector(selector)) flags.sawMissingNotice = true;
}).observe(document.body, { childList: true, subtree: true });
}, MISSING_NOTICE);
}
async function expectMissingNoticeNeverShown(page: Page): Promise<void> {
const saw = await page.evaluate(
() => (window as unknown as { sawMissingNotice?: boolean }).sawMissingNotice,
);
expect(saw).toBe(false);
}
/**
* The daemon publishes the provider list without the removed provider before it answers the config
* patch. Holding the answer keeps the page in that window.
*/
const CONFIG_RESPONSE = "set_daemon_config_response";
test.describe("provider removal", () => {
test("removes a custom provider from Settings", async ({ page }) => {
test.setTimeout(120_000);
@@ -112,42 +79,20 @@ test.describe("provider removal", () => {
try {
await removeCustomProvider(client);
const gate = await installDaemonWebSocketGate(page);
await gotoAppShell(page);
await openSettings(page);
await openSettingsHost(page, getServerId());
await openSettingsHostSection(page, getServerId(), "providers");
// A built-in provider has no Danger zone.
await openProviderDetail(page, "Claude");
await expect(page.getByTestId("provider-remove")).toHaveCount(0);
await leaveProviderDetail(page);
await openAddProvider(page);
await expect(page.getByTestId("provider-actions-claude")).toHaveCount(0);
await openAddProviderArea(page);
await installAcpCatalogProvider(page, CUSTOM_PROVIDER.name);
await expectProviderInstalledInSettings(page, CUSTOM_PROVIDER.name);
await expectProviderSource(client, "custom");
await openProviderDetail(page, CUSTOM_PROVIDER.name);
await test.step("the page points at the catalog's install guide", async () => {
await expectInstallOpensGuide(page, CUSTOM_PROVIDER.installGuide);
});
await expect(page.getByTestId("provider-remove")).toBeVisible();
await watchForMissingNotice(page);
gate.holdNextServerMessage(CONFIG_RESPONSE);
await page.getByTestId(`provider-actions-${CUSTOM_PROVIDER.id}`).click();
await expect(page.getByTestId(`provider-remove-${CUSTOM_PROVIDER.id}`)).toBeVisible();
await clickRemoveProviderAndAcceptWarning(page);
await gate.waitForHeldServerMessage(CONFIG_RESPONSE);
await expectProviderSource(client, undefined);
// Until the removal is answered, the page keeps the provider and the pressed button says so.
const removeButton = page.getByTestId("provider-remove");
await expect(removeButton).toHaveText("Removing...");
await expect(removeButton.getByRole("progressbar")).toBeVisible();
await expect(removeButton).toBeDisabled();
await expect(page.getByTestId("provider-detail-title")).toHaveText(CUSTOM_PROVIDER.name);
gate.releaseHeldServerMessage(CONFIG_RESPONSE);
// Removing leaves the provider's page for the list, without first calling it missing.
await expect(page.getByTestId("provider-list")).toBeVisible();
await expectMissingNoticeNeverShown(page);
await expect(
page.getByRole("button", {
@@ -155,33 +100,7 @@ test.describe("provider removal", () => {
exact: true,
}),
).toHaveCount(0);
} finally {
await removeCustomProvider(client).catch(() => undefined);
await client.close().catch(() => undefined);
}
});
test("says a provider removed elsewhere while its page is open isn't on this host", async ({
page,
}) => {
test.setTimeout(120_000);
const client = await connectDaemonClient<ProviderRemovalDaemonClient>({
clientIdPrefix: "provider-removal-e2e",
});
try {
await removeCustomProvider(client);
await gotoAppShell(page);
await openSettings(page);
await openSettingsHost(page, getServerId());
await openSettingsHostSection(page, getServerId(), "providers");
await openAddProvider(page);
await installAcpCatalogProvider(page, CUSTOM_PROVIDER.name);
await expectProviderInstalledInSettings(page, CUSTOM_PROVIDER.name);
await openProviderDetail(page, CUSTOM_PROVIDER.name);
await removeCustomProvider(client);
await expectProviderNotOnHost(page);
await expectProviderSource(client, undefined);
} finally {
await removeCustomProvider(client).catch(() => undefined);
await client.close().catch(() => undefined);
@@ -211,9 +130,7 @@ test.describe("provider removal", () => {
exact: true,
});
await expect(pluginProviderRow).toBeVisible();
await openProviderDetail(page, PLUGIN_PROVIDER.name);
await expect(page.getByTestId("provider-remove")).toHaveCount(0);
await leaveProviderDetail(page);
await expect(page.getByTestId(`provider-actions-${PLUGIN_PROVIDER.id}`)).toHaveCount(0);
// The provider survives a removeProviders patch pointed at it: the
// plugin, not config.json, owns the definition.
@@ -97,7 +97,7 @@ async function hasFocusWithin(locator: Locator): Promise<boolean> {
async function expectProviderSettingsVisible(page: Page) {
await expect(page.getByTestId("provider-settings-sheet")).toBeVisible({ timeout: 10_000 });
await expect(page.getByRole("button", { name: "Add model" })).toBeVisible();
await expect(page.getByRole("button", { name: "Diagnostic report" })).toBeVisible();
await expect(page.getByRole("button", { name: "Diagnostic", exact: true })).toBeVisible();
}
async function exerciseProviderSettingsStack(page: Page) {
@@ -109,7 +109,7 @@ async function exerciseProviderSettingsStack(page: Page) {
await expect(page.getByPlaceholder("e.g. openai/gpt-5")).not.toBeVisible({ timeout: 10_000 });
await expectProviderSettingsVisible(page);
await page.getByRole("button", { name: "Diagnostic report" }).click();
await page.getByRole("button", { name: "Diagnostic", exact: true }).click();
await expect(page.getByTestId("provider-diagnostic-sheet")).toBeVisible({ timeout: 10_000 });
await page.getByRole("button", { name: /Refresh diagnostic/ }).click();
await expect(page.getByTestId("provider-diagnostic-sheet")).toBeVisible({ timeout: 10_000 });
@@ -118,7 +118,7 @@ async function exerciseProviderSettingsStack(page: Page) {
await page.getByRole("button", { name: "Refresh", exact: true }).click();
await expectProviderSettingsVisible(page);
await expect(page.getByText("Checked just now", { exact: true })).toBeVisible({
await expect(page.getByText("Updated just now", { exact: true })).toBeVisible({
timeout: 30_000,
});
}
@@ -1,44 +0,0 @@
import {
backToProviderList,
expectNoUpdateFailure,
expectRowReadsVersionAndModels,
expectRowReportsUpdateFailure,
openProviderInstallation,
refreshFromOtherClient,
refreshProviderDetails,
runFailingUpdate,
test,
} from "../support/helpers/provider-update-failure";
test("a refresh clears a failed update from the provider's page and its row", async ({
providerUpdateFailure: { page, otherClient },
}) => {
await openProviderInstallation(page);
await test.step("Refresh on the page clears the failure", async () => {
await runFailingUpdate(page);
await refreshProviderDetails(page);
await expectNoUpdateFailure(page);
});
await test.step("the row in the list reads the version and models again", async () => {
await backToProviderList(page);
await expectRowReadsVersionAndModels(page);
});
await test.step("a refresh from another client clears the page", async () => {
await openProviderInstallation(page);
await runFailingUpdate(page);
await refreshFromOtherClient(otherClient);
await expectNoUpdateFailure(page);
});
await test.step("a refresh from another client clears the row on the open list", async () => {
await runFailingUpdate(page);
await backToProviderList(page);
// Without a refresh, the row still reports the failure.
await expectRowReportsUpdateFailure(page);
await refreshFromOtherClient(otherClient);
await expectRowReadsVersionAndModels(page);
});
});
@@ -15,9 +15,6 @@ import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon
import { getServerId } from "../support/helpers/server-id";
import {
expectSettingsHeader,
expectProviderNotOnHost,
expectProviderPageLoaded,
gotoProviderPage,
openSettingsHost,
openHostSection,
expectHostLabelDisplayed,
@@ -267,20 +264,6 @@ test.describe("Settings host page", () => {
});
});
test.describe("provider page from its URL", () => {
test("loads a provider's page on a cold visit", async ({ page }) => {
await gotoAppShell(page);
await gotoProviderPage(page, getServerId(), "claude");
await expectProviderPageLoaded(page, "Claude");
});
test("says a provider the host doesn't have isn't on this host", async ({ page }) => {
await gotoAppShell(page);
await gotoProviderPage(page, getServerId(), "not-a-provider");
await expectProviderNotOnHost(page);
});
});
test("restart recovery defaults off and persists opt-in and custom prompt", async ({ page }) => {
const serverId = getServerId();
await gotoAppShell(page);
+2 -2
View File
@@ -233,8 +233,8 @@ test.describe("usage modal", () => {
],
});
await gotoAppShell(page);
// Three Weekly labels overflow the summary, so it falls back to compact shorthands.
await expectPinnedUsage(page, ["31% wk", "20% wk", "12% wk"]);
// Three windows leave no room for labels in the summary, so it reads percents.
await expectPinnedUsage(page, ["31%", "20%", "12%"]);
await openUsageFromItem(page);
await expectUsageCardOrder(page, ["alpha:a", "beta:home", "beta:work"]);
@@ -40,7 +40,6 @@ import {
usageModal,
installTallUsageSource,
} from "../support/helpers/usage-sidebar-item";
import { seedDockedSidebarWidth } from "../support/helpers/sidebar-footer-overflow";
import { seedSidebarFooterPreferences } from "../support/helpers/sidebar-nav-settings";
import { waitForSettledPosition } from "../support/helpers/sheet-layout";
import { createTempGitRepo } from "../support/helpers/workspace";
@@ -578,97 +577,3 @@ test("visible usage summary requests reports on load", async ({ page }) => {
await expectPinnedUsage(page, ["31% 5h", "54% wk", "7% 5h", "12% wk"]);
expect(usage.listRequests()).toHaveLength(1);
});
test("sidebar usage falls back to period shorthands before dropping all labels", async ({
page,
}) => {
test.setTimeout(120_000);
const [claude, codex] = claudeAndCodexReports();
const fetchedAt = new Date().toISOString();
await installUsageReportsFixture(page, {
lists: [
() => [
{
...codex!,
report: {
status: "available",
windows: [
{ id: "weekly", label: "Weekly", shortLabel: "wk", summary: true, usedPct: 97 },
],
},
},
{
...claude!,
report: {
status: "available",
windows: [
{ id: "five_hour", label: "Session", shortLabel: "5h", summary: true, usedPct: 100 },
{ id: "weekly", label: "Weekly", shortLabel: "wk", summary: true, usedPct: 14 },
{
id: "weekly_model_opus",
label: "Weekly · Opus",
shortLabel: "wk Opus",
summary: true,
usedPct: 22,
},
],
},
},
{
id: "antigravity:default",
account: {},
fetchedAt,
sourceId: "antigravity",
sourceLabel: "Antigravity",
report: {
status: "available",
windows: [
{
id: "gemini-weekly",
label: "Gemini Models · Weekly",
shortLabel: "Gemini wk",
summary: true,
usedPct: 6,
},
{
id: "gemini-5h",
label: "Gemini Models · 5h",
shortLabel: "Gemini 5h",
summary: true,
usedPct: 20,
},
],
},
},
],
],
});
await seedSidebarFooterPreferences(page, [{ key: "usage", visible: true }]);
await seedDockedSidebarWidth(page, 432);
await page.setViewportSize(WIDE);
await gotoAppShell(page);
await expectPinnedUsage(page, ["6% wk", "20% 5h", "100% 5h", "14% wk", "22% wk", "97% wk"]);
const handle = page.getByTestId("left-sidebar-resize-handle");
const dragSidebarTo = async (targetX: number) => {
const box = (await handle.boundingBox())!;
await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
await page.mouse.down();
await page.mouse.move(targetX, box.y + box.height / 2, { steps: 10 });
await page.mouse.up();
};
await dragSidebarTo(600);
await expectPinnedUsage(page, [
"6% Gemini wk",
"20% Gemini 5h",
"100% 5h",
"14% wk",
"22% wk Opus",
"97% wk",
]);
await dragSidebarTo(300);
await expectPinnedUsage(page, ["6%", "20%", "100%", "14%", "22%", "97%"]);
});
@@ -22,7 +22,7 @@ type AgentSkillsClient = Pick<
"close" | "connect" | "getAgentSkillsStatus" | "saveAgentSkillsSelection"
>;
export type SkillTargetName = "agents" | "claude" | "antigravity";
export type SkillTargetName = "agents" | "claude";
export interface AgentSkillsSandbox {
available: string[];
@@ -64,7 +64,6 @@ export async function startAgentSkillsSandbox(): Promise<AgentSkillsSandbox> {
const targets = {
agents: path.join(home, ".agents", "skills"),
claude: path.join(home, ".claude", "skills"),
antigravity: path.join(home, ".gemini", "config", "skills"),
};
const codexSkillsDir = path.join(home, ".codex", "skills");
@@ -1,6 +1,6 @@
import { expect, type Locator, type Page } from "@playwright/test";
import { openSettings } from "./app";
import { clickSettingsBackToWorkspace, openSettingsSection } from "./settings";
import { openSettingsSection } from "./settings";
import { runWorkspaceActionFromCommandCenter } from "./command-center-workspace-actions";
import { seedMockAgentWorkspace, type MockAgentWorkspace } from "./mock-agent";
import { loadSessionMessageReaders } from "./new-workspace";
@@ -81,13 +81,12 @@ export async function splitCurrentPanelRight(page: Page): Promise<void> {
await runWorkspaceActionFromCommandCenter(page, "Split pane right");
}
export async function disableChatOutline(page: Page): Promise<void> {
export async function disableChatOutlineFromAppearance(page: Page): Promise<void> {
const timelineUrl = page.url();
await openSettings(page);
await openSettingsSection(page, "chat");
const outlineSwitch = page.getByRole("switch", { name: "Chat outline" });
await outlineSwitch.click();
await expect(outlineSwitch).not.toBeChecked();
await clickSettingsBackToWorkspace(page);
await page.getByRole("switch", { name: "Chat outline" }).click();
await page.goto(timelineUrl);
}
/** Parks the pointer in the middle of the transcript, clear of the rail. */
@@ -1,68 +1,63 @@
import { expect, type Locator, type Page } from "@playwright/test";
import { openSettings } from "./app";
import { clickSettingsBackToWorkspace, openSettingsSection } from "./settings";
import { openSettingsSection } from "./settings";
type ContentWidthOption = "Default" | "Wide" | "Full";
const APP_SETTINGS_KEY = "@paseo:app-settings";
function contentWidthOption(page: Page, option: ContentWidthOption): Locator {
return page
.getByTestId("content-width-options")
.getByRole("button", { name: option, exact: true });
function contentWidthInput(page: Page): Locator {
return page.getByLabel("Content width in pixels", { exact: true });
}
export async function chooseContentWidth(page: Page, option: ContentWidthOption): Promise<void> {
function resetContentWidthButton(page: Page): Locator {
return page.getByRole("button", { name: "Reset content width to default", exact: true });
}
export async function openAppearanceSettings(page: Page): Promise<void> {
await openSettings(page);
await openSettingsSection(page, "appearance");
const button = contentWidthOption(page, option);
await button.click();
await expect(button).toHaveAttribute("aria-selected", "true");
await clickSettingsBackToWorkspace(page);
}
/** Checks the rendered content width, allowing for padding inside the column. */
export async function setContentWidth(page: Page, width: number): Promise<void> {
const input = contentWidthInput(page);
await input.fill(String(width));
await input.press("Tab");
}
export async function resetContentWidth(page: Page): Promise<void> {
await resetContentWidthButton(page).click();
}
export async function expectDefaultContentWidthSetting(page: Page, width: number): Promise<void> {
await expect(contentWidthInput(page)).toHaveValue(String(width));
await expect(resetContentWidthButton(page)).toHaveCount(0);
await expect.poll(() => readStoredContentWidth(page)).toBeNull();
}
export async function expectCustomContentWidthSetting(page: Page, width: number): Promise<void> {
await expect(contentWidthInput(page)).toHaveValue(String(width));
await expect(resetContentWidthButton(page)).toBeVisible();
await expect.poll(() => readStoredContentWidth(page)).toBe(width);
}
/** Asserts the rendered width of a content-column element stays within `max` and above `min`. */
export async function expectContentColumnWidth(
element: Locator,
bounds: { min: number; max: number },
bounds: { min?: number; max: number },
): Promise<void> {
await expect(element).toBeVisible({ timeout: 30_000 });
await expect
.poll(async () => (await element.boundingBox())?.width ?? 0)
.toBeGreaterThanOrEqual(bounds.min);
await expect
.poll(async () => (await element.boundingBox())?.width ?? Infinity)
.toBeLessThanOrEqual(bounds.max);
await expect
.poll(async () => (await element.boundingBox())?.width ?? 0)
.toBeGreaterThan(bounds.min ?? 0);
}
export async function expectColumnClearOfOutline(column: Locator, outline: Locator): Promise<void> {
await expect
.poll(async () => {
const [content, rail] = await Promise.all([column.boundingBox(), outline.boundingBox()]);
return content && rail ? content.x - (rail.x + rail.width) : -1;
})
.toBeGreaterThanOrEqual(8);
}
export async function expectColumnAtLeftGutter(page: Page, column: Locator): Promise<void> {
const viewport = page.getByTestId("agent-chat-scroll");
await expect
.poll(async () => {
const [content, scroll] = await Promise.all([column.boundingBox(), viewport.boundingBox()]);
return content && scroll ? content.x - scroll.x : Infinity;
})
.toBeLessThanOrEqual(24);
}
/** Checks that two column surfaces sit on the same left and right vertical rails. */
export async function expectSharedHorizontalRail(first: Locator, second: Locator): Promise<void> {
await expect(first).toBeVisible({ timeout: 30_000 });
await expect(second).toBeVisible({ timeout: 30_000 });
await expect
.poll(async () => {
const [a, b] = await Promise.all([first.boundingBox(), second.boundingBox()]);
if (!a || !b) return Infinity;
const leftDelta = Math.abs(a.x - b.x);
const rightDelta = Math.abs(a.x + a.width - (b.x + b.width));
return Math.max(leftDelta, rightDelta);
})
.toBeLessThanOrEqual(1);
async function readStoredContentWidth(page: Page): Promise<unknown> {
return page.evaluate((key) => {
const raw = localStorage.getItem(key);
return raw === null
? undefined
: (JSON.parse(raw) as { contentMaxWidth?: unknown }).contentMaxWidth;
}, APP_SETTINGS_KEY);
}
@@ -25,12 +25,7 @@ export async function addCustomModel(page: Page, id: string): Promise<void> {
}
export async function removeCustomModel(page: Page, id: string): Promise<void> {
await searchModels(page, id);
await removeListedCustomModel(page, id);
}
/** Removes a custom model shown on the page without searching for it first. */
export async function removeListedCustomModel(page: Page, id: string): Promise<void> {
await page.getByRole("textbox", { name: "Search models" }).fill(id);
const remove = page.getByRole("button", { name: `Remove ${id}`, exact: true });
await expect(remove).toBeInViewport({ ratio: 1 });
await remove.click();
@@ -38,20 +33,8 @@ export async function removeListedCustomModel(page: Page, id: string): Promise<v
}
export async function expectCustomModelRetained(page: Page, id: string): Promise<void> {
await searchModels(page, id);
await page.getByRole("textbox", { name: "Search models" }).fill(id);
await expect(page.getByRole("button", { name: `Remove ${id}`, exact: true })).toBeInViewport({
ratio: 1,
});
}
/**
* Filters the model list and scrolls the sheet down to the custom models, since other sections push
* them below the fold at phone width. Only the section heading is scrolled into view: scrolling the
* row itself would also slide its card sideways and hide a Remove button pushed past the right edge.
*/
async function searchModels(page: Page, id: string): Promise<void> {
await page.getByRole("textbox", { name: "Search models" }).fill(id);
await page
.getByText("Custom models", { exact: true })
.evaluate((heading) => heading.scrollIntoView({ block: "start" }));
}
+1 -12
View File
@@ -86,17 +86,6 @@ export function setupModal(page: Page): Locator {
return page.getByTestId("onboarding-modal").getByRole("dialog");
}
/** A sheet opened from a setup step, which should sit exactly on the setup card. */
export function setupSheet(page: Page, testID: "provider-settings-sheet" | "add-provider-sheet") {
return page.getByTestId(testID).getByRole("dialog");
}
export async function expectSheetCoversSetupCard(page: Page, sheet: Locator): Promise<void> {
await expect(sheet).toBeVisible();
const card = await setupModal(page).boundingBox();
await expect.poll(() => sheet.boundingBox()).toEqual(card);
}
export async function expectSetupStep(page: Page, title: string): Promise<void> {
await expect(setupModal(page).getByRole("heading", { name: title, exact: true })).toBeVisible({
timeout: 60_000,
@@ -196,7 +185,7 @@ export interface SetupHost {
/**
* An isolated host whose only agent history is the Claude sessions given here, so suggestions
* never depend on the machine running the test. Its HOME is a scratch folder, so the skills setup
* installs never land in the real ~/.agents, ~/.claude, ~/.codex, or ~/.gemini/config. `withBrokenProvider` adds a
* installs never land in the real ~/.agents, ~/.claude or ~/.codex. `withBrokenProvider` adds a
* provider that cannot start.
*/
export async function startSetupHost(
@@ -106,12 +106,10 @@ export async function verifyProviderSettings({
await test.step("provider settings render the registered icon", async () => {
await openSettings(page);
await openSettingsHostSection(page, getServerId(), "providers");
// The row's button lies under its content, so the icon is in the row, beside the button.
const opener = page.getByRole("button", {
name: "Direct provider example provider details",
exact: true,
});
await expectProviderIcon(page.getByTestId(/^provider-row-/).filter({ has: opener }), iconPaths);
await expectProviderIcon(
page.getByRole("button", { name: "Direct provider example provider details", exact: true }),
iconPaths,
);
await capture(page, testInfo, "provider-settings");
await page.getByTestId("settings-back-to-workspace").click();
});
@@ -1,138 +0,0 @@
import { writeFile } from "node:fs/promises";
import path from "node:path";
import type { DaemonClient as InternalDaemonClient } from "@getpaseo/client/internal/daemon-client";
import { expect, test as base, type Page } from "../fixtures";
import { gotoAppShell, openSettings } from "./app";
import { connectDaemonClient } from "./daemon-client-loader";
import { copyPluginExample, pluginRequirements } from "./plugin-fixture";
import { getServerId } from "./server-id";
import { leaveProviderDetail, openSettingsHostSection } from "./settings";
const PLUGIN_ID = "provider-update-failure";
const PROVIDER_ID = "update-failure";
const PROVIDER_NAME = "Update failure";
const FAILURE = "The updater could not write to the install directory";
/** The direct provider example with an installation whose updater always fails. */
const SERVER_SOURCE = `import type { PluginServerContext } from "@getpaseo/plugin/server";
import { createDirectExampleProvider } from "./server/provider";
export default function contribute(server: PluginServerContext) {
server.registerProvider({
...createDirectExampleProvider(),
id: ${JSON.stringify(PROVIDER_ID)},
label: ${JSON.stringify(PROVIDER_NAME)},
installation: {
async inspect() {
return { status: "installed", version: "1.0.0" };
},
async update({ report }) {
report({ type: "stderr", text: "EACCES\\n" });
return { status: "failed", message: ${JSON.stringify(FAILURE)} };
},
},
});
return () => {};
}
`;
type ObserverClient = Pick<
InternalDaemonClient,
| "close"
| "connect"
| "getDaemonConfig"
| "inspectProviderInstallation"
| "installDirectoryPlugin"
| "patchDaemonConfig"
| "removePlugin"
>;
interface ProviderUpdateFailure {
page: Page;
/** A second client of the same host. */
otherClient: ObserverClient;
}
export const test = base.extend<{ providerUpdateFailure: ProviderUpdateFailure }>({
providerUpdateFailure: async ({ page }, provide) => {
const client = await connectDaemonClient<ObserverClient>({
clientIdPrefix: "app-e2e-provider-update-failure",
});
const plugin = await copyPluginExample("provider-direct");
try {
const previous = await client.getDaemonConfig();
await writeFile(
path.join(plugin.directory, "paseo-plugin.json"),
JSON.stringify({ id: PLUGIN_ID, requirements: pluginRequirements }),
);
await writeFile(path.join(plugin.directory, "index.server.ts"), SERVER_SOURCE);
try {
await client.patchDaemonConfig({ pluginsEnabled: true });
await client.installDirectoryPlugin(plugin.directory);
await provide({ page, otherClient: client });
} finally {
try {
await client.removePlugin(PLUGIN_ID);
} finally {
await client.patchDaemonConfig({ pluginsEnabled: previous.config.pluginsEnabled });
}
}
} finally {
await plugin.cleanup();
await client.close();
}
},
});
export async function openProviderInstallation(page: Page): Promise<void> {
await gotoAppShell(page);
await openSettings(page);
await openSettingsHostSection(page, getServerId(), "providers");
await page
.getByRole("button", { name: `${PROVIDER_NAME} provider details`, exact: true })
.click();
await expect(page.getByTestId("provider-installation-version")).toHaveText("1.0.0");
}
export async function runFailingUpdate(page: Page): Promise<void> {
await page.getByTestId("provider-update-start").click();
await expect(page.getByTestId("provider-update-status")).toHaveText("Update failed");
await expect(page.getByTestId("provider-update-message")).toHaveText(FAILURE);
}
export async function refreshProviderDetails(page: Page): Promise<void> {
await page.getByTestId("provider-refresh").click();
}
export async function backToProviderList(page: Page): Promise<void> {
await leaveProviderDetail(page);
}
function providerRow(page: Page) {
return page.getByTestId(`provider-row-${PROVIDER_ID}`);
}
/** The provider's row in the list reports the failed update, with the error dot. */
export async function expectRowReportsUpdateFailure(page: Page): Promise<void> {
const row = providerRow(page);
await expect(row).toContainText(FAILURE);
await expect(row.getByTestId("settings-row-error-dot")).toHaveCount(1);
}
/** The provider's row reads its version and model count again, with no error dot. */
export async function expectRowReadsVersionAndModels(page: Page): Promise<void> {
const row = providerRow(page);
await expect(row).toContainText("1.0.0 · 1 model");
await expect(row).not.toContainText(FAILURE);
await expect(row.getByTestId("settings-row-error-dot")).toHaveCount(0);
}
export async function refreshFromOtherClient(client: ObserverClient): Promise<void> {
const result = await client.inspectProviderInstallation(PROVIDER_ID, { refresh: true });
expect(result.error).toBeNull();
}
export async function expectNoUpdateFailure(page: Page): Promise<void> {
await expect(page.getByTestId("provider-update-run")).toHaveCount(0);
await expect(page.getByTestId("provider-installation-version")).toHaveText("1.0.0");
}
+2 -67
View File
@@ -515,8 +515,8 @@ export async function serveJson(page: Page, url: string, body: unknown): Promise
});
}
export async function openAddProvider(page: Page): Promise<void> {
await page.getByTestId("provider-list-add").click();
export async function openAddProviderArea(page: Page): Promise<void> {
await page.getByTestId("host-page-add-provider-card").scrollIntoViewIfNeeded();
await expect(page.getByRole("textbox", { name: "Search providers" })).toBeVisible();
}
@@ -528,82 +528,17 @@ export async function findAcpCatalogProvider(page: Page, providerName: string):
export async function installAcpCatalogProvider(page: Page, providerName: string): Promise<void> {
await findAcpCatalogProvider(page, providerName);
await page.getByRole("button", { name: `Add ${providerName}`, exact: true }).click();
// The sheet closes once the add is done. Adding probes the new provider, which can outlast an
// assertion's default wait.
await expect(page.getByRole("textbox", { name: "Search providers" })).toHaveCount(0, {
timeout: 60_000,
});
}
/** Adding opens the new provider's page; its row waits in the list behind it. */
export async function expectProviderInstalledInSettings(
page: Page,
providerName: string,
): Promise<void> {
await expect(page.getByTestId("provider-detail-title")).toHaveText(providerName);
await page.getByTestId("provider-detail-back").click();
await expect(
page.getByRole("button", { name: `${providerName} provider details`, exact: true }),
).toBeVisible();
}
export async function openProviderDetail(page: Page, providerName: string): Promise<void> {
await page.getByRole("button", { name: `${providerName} provider details`, exact: true }).click();
await expect(page.getByTestId("provider-detail-title")).toHaveText(providerName);
}
/** Load a provider's Settings page from its URL, as a reload or a shared link does. */
export async function gotoProviderPage(
page: Page,
serverId: string,
providerId: string,
): Promise<void> {
await page.goto(
`/settings/hosts/${encodeURIComponent(serverId)}/providers/${encodeURIComponent(providerId)}`,
);
}
export async function expectProviderPageLoaded(page: Page, providerName: string): Promise<void> {
await expect(page.getByTestId("provider-detail-title")).toHaveText(providerName, {
timeout: 30_000,
});
await expect(page.getByText("Provider status")).toBeVisible({ timeout: 30_000 });
}
export async function expectProviderNotOnHost(page: Page): Promise<void> {
await expect(page.getByText("This provider isn't on this host")).toBeVisible({
timeout: 30_000,
});
}
/**
* The provider page says the provider's CLI is missing, and Install opens the given guide. The
* guide is served locally so the test never reaches the network.
*/
export async function expectInstallOpensGuide(page: Page, guideUrl: string): Promise<void> {
const installation = page.getByTestId("provider-installation");
await expect(installation.getByText("Not installed", { exact: true })).toBeVisible({
timeout: 30_000,
});
await page.context().route(guideUrl, (route) =>
route.fulfill({
status: 200,
contentType: "text/html",
body: "<title>Install guide</title>",
}),
);
const guide = page.waitForEvent("popup");
await installation.getByRole("button", { name: "Install", exact: true }).click();
const opened = await guide;
expect(opened.url()).toBe(guideUrl);
await opened.close();
}
export async function leaveProviderDetail(page: Page): Promise<void> {
await page.getByTestId("provider-detail-back").click();
await expect(page.getByTestId("provider-list")).toBeVisible();
}
export async function expectHostNoDaemonLifecycleRow(page: Page): Promise<void> {
await expect(page.getByTestId("host-page-daemon-lifecycle-card")).toHaveCount(0);
}
@@ -1,4 +1,4 @@
import { expect, test, type Page } from "@playwright/test";
import { expect, type Page } from "@playwright/test";
import { openChangesPanel } from "./branch-switcher";
export async function restoreArchivedWorkspace(page: Page): Promise<void> {
@@ -32,11 +32,7 @@ export async function expectCommittedFile(page: Page, filename: string): Promise
}
export async function expectCommittedFileAfterReload(page: Page, filename: string): Promise<void> {
await test.step("See the committed file immediately after Restore", async () => {
await expectCommittedFile(page, filename);
});
await test.step("Reload and see the same committed file", async () => {
await page.reload();
await expectCommittedFile(page, filename);
});
await expectCommittedFile(page, filename);
await page.reload();
await expectCommittedFile(page, filename);
}
-1
View File
@@ -66,7 +66,6 @@
[role="slider"],
[role="menuitem"],
[tabindex],
[data-window-no-drag],
[contenteditable="true"] {
-webkit-app-region: no-drag !important;
}
@@ -66,23 +66,4 @@ describe("fetchAgentCommands", () => {
expect(client.calls).toEqual([{ agentId: "agent-1", draftConfig: undefined }]);
});
it("deduplicates duplicate command names from the daemon, keeping the first entry", async () => {
const client = createClient(
commandsPayload([
{ name: "goal", description: "Run until goal is finished", argumentHint: "" },
{ name: "plan", description: "Plan carefully before executing a task.", argumentHint: "" },
{ name: "plan", description: "Local plan skill description", argumentHint: "" },
{ name: "review", description: "Review changes", argumentHint: "" },
]),
);
const commands = await fetchAgentCommands({ client, agentId: "agent-1" });
expect(commands).toEqual([
{ name: "goal", description: "Run until goal is finished", argumentHint: "" },
{ name: "plan", description: "Plan carefully before executing a task.", argumentHint: "" },
{ name: "review", description: "Review changes", argumentHint: "" },
]);
});
});
+1 -13
View File
@@ -37,18 +37,6 @@ export interface AgentCommandsClient {
listCommands(options: ListAgentCommandsOptions): ReturnType<DaemonClient["listCommands"]>;
}
// COMPAT(dedupeListCommands): added in v0.17.0, remove after 2027-05-20 once daemon floor >= v0.17.0.
function dedupeSlashCommands(commands: readonly AgentSlashCommand[]): AgentSlashCommand[] {
const seen = new Set<string>();
const unique: AgentSlashCommand[] = [];
for (const command of commands) {
if (seen.has(command.name)) continue;
seen.add(command.name);
unique.push(command);
}
return unique;
}
export async function fetchAgentCommands(input: {
client: AgentCommandsClient;
agentId: string;
@@ -59,7 +47,7 @@ export async function fetchAgentCommands(input: {
draftConfig: input.draftConfig,
});
if (response.error) throw new Error(response.error);
return dedupeSlashCommands(response.commands as AgentSlashCommand[]);
return response.commands as AgentSlashCommand[];
}
interface UseAgentCommandsQueryOptions {
@@ -1,7 +0,0 @@
import { SPACING } from "@/styles/theme";
// Outline rail geometry shared between the rail overlay and the chat pane's column rail.
export const CHAT_OUTLINE_RAIL_WIDTH = 36;
export const CHAT_OUTLINE_RAIL_LEFT = SPACING[2];
export const CHAT_OUTLINE_MIN_PANEL_WIDTH = 918;
export const CHAT_OUTLINE_GUTTER_INSET = CHAT_OUTLINE_RAIL_LEFT + CHAT_OUTLINE_RAIL_WIDTH;
@@ -2,17 +2,17 @@ import { memo, useCallback, useEffect, useMemo, useState, useSyncExternalStore }
import { Pressable, Text, View, type PointerEvent as RNPointerEvent } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { useReducedMotion } from "react-native-reanimated";
import { useContainerWidthBelow } from "@/hooks/use-container-width";
import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
import { CHAT_OUTLINE_RAIL_LEFT, CHAT_OUTLINE_RAIL_WIDTH } from "./geometry";
import { createChatOutlineHoverIntent } from "./hover-intent";
import { promptTickMagnification } from "./model";
import type { ChatOutlineRailProps } from "./rail";
// Hover tracking lives on the rail and the slots, never on the Pressable inside them:
// magnifying a slot must not move the box the pointer is resting on. See docs/hover.md.
const RAIL_WIDTH = CHAT_OUTLINE_RAIL_WIDTH;
const RAIL_LEFT = CHAT_OUTLINE_RAIL_LEFT;
const RAIL_WIDTH = 36;
const SLOT_HEIGHT = 8;
const MIN_PANEL_WIDTH = 918;
const RESTING_PILL_HEIGHT = 2;
const MAGNIFIED_PILL_HEIGHT = 4;
const RESTING_PILL_WIDTH = 10;
@@ -31,6 +31,7 @@ export const ChatOutlineRail = memo(function ChatOutlineRail({
const [focusedIndex, setFocusedIndex] = useState<number | null>(null);
const activeSeq = useSyncExternalStore(activePrompt.subscribe, activePrompt.getActiveSeq);
const prefersReducedMotion = useReducedMotion();
const { onLayout, isBelow: isPanelNarrow } = useContainerWidthBelow(MIN_PANEL_WIDTH);
const hoverIntent = useMemo(
() =>
@@ -59,6 +60,9 @@ export const ChatOutlineRail = memo(function ChatOutlineRail({
);
const handlePointerLeaveRail = useCallback(() => hoverIntent.leave(), [hoverIntent]);
useEffect(() => () => hoverIntent.dispose(), [hoverIntent]);
useEffect(() => {
if (isPanelNarrow) hoverIntent.leave();
}, [hoverIntent, isPanelNarrow]);
const handleFocusChange = useCallback((index: number, focused: boolean) => {
setFocusedIndex((current) => {
if (focused) return index;
@@ -70,34 +74,40 @@ export const ChatOutlineRail = memo(function ChatOutlineRail({
// same band and the same preview once the pointer leaves.
const attentionIndex = hoveredIndex ?? focusedIndex;
if (prompts.length < 2) return null;
return (
<View
style={styles.rail}
role="tablist"
testID="chat-outline-rail"
onPointerEnter={handlePointerEnterRail}
onPointerMove={handlePointerMoveRail}
onPointerLeave={handlePointerLeaveRail}
>
{prompts.map((prompt, index) => (
<ChatOutlineTick
key={prompt.seq}
index={index}
seq={prompt.seq}
preview={prompt.preview}
label={`${index + 1} of ${prompts.length}: ${prompt.preview}`}
isActive={prompt.seq === activeSeq}
hasAttention={index === attentionIndex}
magnification={
prefersReducedMotion || attentionIndex === null
? 0
: promptTickMagnification(index - attentionIndex)
}
onHover={handlePointerEnterTick}
onFocusChange={handleFocusChange}
onJumpToPrompt={onJumpToPrompt}
/>
))}
<View style={styles.panelMeasure} pointerEvents="box-none" onLayout={onLayout}>
{isPanelNarrow ? null : (
<View
style={styles.rail}
role="tablist"
testID="chat-outline-rail"
onPointerEnter={handlePointerEnterRail}
onPointerMove={handlePointerMoveRail}
onPointerLeave={handlePointerLeaveRail}
>
{prompts.map((prompt, index) => (
<ChatOutlineTick
key={prompt.seq}
index={index}
seq={prompt.seq}
preview={prompt.preview}
label={`${index + 1} of ${prompts.length}: ${prompt.preview}`}
isActive={prompt.seq === activeSeq}
hasAttention={index === attentionIndex}
magnification={
prefersReducedMotion || attentionIndex === null
? 0
: promptTickMagnification(index - attentionIndex)
}
onHover={handlePointerEnterTick}
onFocusChange={handleFocusChange}
onJumpToPrompt={onJumpToPrompt}
/>
))}
</View>
)}
</View>
);
});
@@ -175,9 +185,13 @@ const ChatOutlineTick = memo(function ChatOutlineTick({
});
const styles = StyleSheet.create((theme) => ({
panelMeasure: {
position: "absolute",
inset: 0,
},
rail: {
position: "absolute",
left: RAIL_LEFT,
left: theme.spacing[2],
top: "10%",
bottom: "10%",
width: RAIL_WIDTH,
+6 -26
View File
@@ -40,7 +40,6 @@ import {
type HistoryStartSettleScheduler,
} from "./history-start-settle-scheduler";
import { useChatFindSelectedMessageId } from "@/agent-stream/chat-find";
import { CHAT_COLUMN_BASE_GUTTER, resolveChatColumnGutters } from "@/chat-rail/gutters";
import { useScrollToMessage } from "./use-scroll-to-message.web";
interface CreateWebStreamStrategyInput {
@@ -315,7 +314,6 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
olderHistoryProgressKey,
scrollEnabled,
contentMaxWidth,
outlineInset = 0,
isMobileBreakpoint,
} = props;
const historyVirtualized = useRevisedHistoryRows(
@@ -455,13 +453,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
unsubscribe?.();
};
}, []);
// The scroll viewport keeps its width when the reading column changes.
// Track the effective column width for cached measurements and estimates.
const readContentWidth = () => {
const available = rowsHostRef.current?.getBoundingClientRect().width;
return available ? Math.min(available, contentMaxWidth ?? available) : contentMaxWidth;
};
const contentWidth = readContentWidth();
const contentWidth = contentRef.current?.getBoundingClientRect().width;
const rowVirtualizer = useVirtualizer({
count: segments.historyVirtualized.length,
enabled: shouldUseVirtualizer,
@@ -477,9 +469,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
const row = segments.historyVirtualized[index];
const measured = row && measuredRowHeights.current.get(row.id);
if (measured && measured.width === contentWidth) return measured.height;
return row
? estimateStreamItemHeight({ item: row, contentMaxWidth: contentWidth ?? 0 })
: 120;
return row ? estimateStreamItemHeight({ item: row, contentMaxWidth }) : 120;
},
observeElementOffset: observeVirtualOffset,
rangeExtractor,
@@ -487,10 +477,6 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
overscan: 8,
});
rowVirtualizerRef.current = rowVirtualizer;
useLayoutEffect(() => {
// Discard offscreen sizes measured with the previous text wrapping.
rowVirtualizer.measure();
}, [contentMaxWidth, outlineInset, rowVirtualizer]);
// Scroll correction belongs to the viewport's committed layout. The virtualizer
// otherwise writes scrollTop before React applies its new row positions.
rowVirtualizer.shouldAdjustScrollPositionOnItemSizeChange = () => false;
@@ -736,7 +722,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
if (!container || !content) return null;
const viewportTop = container.getBoundingClientRect().top;
const scrollTop = container.scrollTop;
const width = readContentWidth() ?? 0;
const width = content.getBoundingClientRect().width;
return Array.from(content.querySelectorAll<HTMLElement>("[data-history-row-id]"), (element) => {
const bounds = element.getBoundingClientRect();
const id = element.dataset.historyRowId!;
@@ -1229,23 +1215,17 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
]);
const contentContainerStyle = useMemo((): CSSProperties => {
const gutter = isMobileBreakpoint ? 8 : CHAT_COLUMN_BASE_GUTTER;
const { paddingLeft, paddingRight } = resolveChatColumnGutters({
gutter,
outlineInset,
contentMaxWidth,
});
return {
display: "flex",
flexDirection: "column",
minHeight: "100%",
paddingTop: CONTENT_PADDING_TOP_PX,
paddingBottom: 16,
paddingLeft,
paddingRight,
paddingLeft: isMobileBreakpoint ? 8 : 16,
paddingRight: isMobileBreakpoint ? 8 : 16,
boxSizing: "border-box",
};
}, [contentMaxWidth, isMobileBreakpoint, outlineInset]);
}, [isMobileBreakpoint]);
const scrollContainerStyle = useMemo((): CSSProperties => {
const overlayScrollbarEnabled = scrollEnabled && !isMobileBreakpoint;
return {
+1 -2
View File
@@ -107,8 +107,7 @@ export interface StreamRenderInput {
baseListContentContainerStyle: StyleProp<ViewStyle>;
forwardListContentContainerStyle: StyleProp<ViewStyle>;
// The chat column's max width. The web viewport estimates unmeasured row heights with it.
contentMaxWidth: number | undefined;
outlineInset?: number;
contentMaxWidth: number;
}
export interface ResolveStreamRenderStrategyInput {
+12 -13
View File
@@ -82,7 +82,6 @@ import { renderStreamRow, type RenderStreamItem } from "./stream-row";
import { type NearBottom, useIsNearBottom, useNearBottom } from "./near-bottom";
import { ChatOutlineRail } from "@/agent-stream/chat-outline/rail";
import { useChatOutline } from "@/agent-stream/chat-outline/use-chat-outline";
import { CHAT_COLUMN_RAIL_DATASET, useChatOutlineRail } from "@/chat-rail";
import { getHostRuntimeStore } from "@/runtime/host-runtime";
import { planTimelineTailFetch } from "@/timeline/timeline-sync-plan";
import {
@@ -323,7 +322,7 @@ function ScrollToBottomButton({
);
if (isNearBottom && !isTimelineDetached) return null;
return (
<View style={containerStyle} dataSet={CHAT_COLUMN_RAIL_DATASET} pointerEvents="box-none">
<View style={containerStyle} pointerEvents="box-none">
<Animated.View entering={scrollIndicatorFadeIn} exiting={scrollIndicatorFadeOut}>
<Pressable
style={stylesheet.scrollToBottomButton}
@@ -366,6 +365,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
const { t } = useTranslation();
const autoExpandReasoning = useSettings((settings) => settings.autoExpandReasoning);
const chatDisplay = useSettings((settings) => settings.chatDisplay);
const chatOutlineEnabled = useSettings((settings) => settings.chatOutlineEnabled);
const contentMaxWidth = useSettings(resolveContentMaxWidth);
const viewportRef = useRef<StreamViewportHandle | null>(null);
const pendingClientMessageIds = useMemo(
@@ -404,6 +404,10 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
(state) =>
state.sessions[resolvedServerId]?.serverInfo?.features?.agentForkContextCursor === true,
);
const supportsChatOutline = useSessionStore(
(state) =>
state.sessions[resolvedServerId]?.serverInfo?.features?.agentTimelinePromptIndex === true,
);
const timelineEpoch = useSessionStore(
(state) => state.sessions[resolvedServerId]?.agentTimelineCursor.get(agentId)?.epoch ?? null,
);
@@ -613,15 +617,13 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
mountedHistoryMessageIds.has(messageId) || liveHeadMessageIds.has(messageId),
};
}, [baseRenderModel.segments.liveHead, mountedHistoryMessageIds]);
const outlineRail = useChatOutlineRail();
const outlineInset = outlineRail.inset;
const chatOutline = useChatOutline({
agentId,
serverId: resolvedServerId,
timelineEpoch,
tail: effectiveStreamItems,
head: effectiveStreamHead,
enabled: outlineRail.enabled,
enabled: supportsChatOutline && chatOutlineEnabled,
viewportRef,
onJumpError: handleTimelineHistoryLoadError,
mountedHistoryMessageIds,
@@ -1200,18 +1202,15 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
baseListContentContainerStyle: stylesheet.listContentContainer,
forwardListContentContainerStyle: stylesheet.forwardListContentContainer,
contentMaxWidth,
outlineInset,
})}
</UserMessageExpansionContext.Provider>
</ToolCallExpansionContext.Provider>
</MessageOuterSpacingProvider>
{outlineInset > 0 && chatOutline.prompts.length >= 2 ? (
<ChatOutlineRail
prompts={chatOutline.prompts}
activePrompt={chatOutline.activePrompt}
onJumpToPrompt={chatOutline.jumpToPrompt}
/>
) : null}
<ChatOutlineRail
prompts={chatOutline.prompts}
activePrompt={chatOutline.activePrompt}
onJumpToPrompt={chatOutline.jumpToPrompt}
/>
<ScrollToBottomButton
nearBottom={nearBottom}
isTimelineDetached={isTimelineDetached}
-1
View File
@@ -936,7 +936,6 @@ function RootStack() {
<Stack.Screen name="settings/hosts/[serverId]/plugin-directory/[owner]/[slug]" />
<Stack.Screen name="settings/hosts/[serverId]/projects/index" />
<Stack.Screen name="settings/hosts/[serverId]/projects/[projectId]" />
<Stack.Screen name="settings/hosts/[serverId]/providers/[providerId]" />
</ThemedStack>
);
}
@@ -1,24 +0,0 @@
import { useLocalSearchParams } from "expo-router";
import { useMemo } from "react";
import { HostRouteBootstrapBoundary } from "@/components/host-route-bootstrap-boundary";
import SettingsScreen from "@/screens/settings-screen";
import { normalizeProjectSettingsRouteId } from "@/utils/host-routes";
export default function SettingsHostProviderDetailRoute() {
const params = useLocalSearchParams<{
serverId?: string | string[];
providerId?: string | string[];
}>();
const serverId = normalizeProjectSettingsRouteId(params.serverId);
const providerId = normalizeProjectSettingsRouteId(params.providerId);
const view = useMemo(
() => ({ kind: "provider" as const, serverId, providerId }),
[providerId, serverId],
);
return (
<HostRouteBootstrapBoundary>
<SettingsScreen view={view} />
</HostRouteBootstrapBoundary>
);
}
+5 -8
View File
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { darkHighlightColors, resolveSyntaxColors } from "@getpaseo/highlight";
import { DEFAULT_UI_FONT_STACK, REGISTERED_THEMES, type Theme } from "@/styles/theme";
import { DEFAULT_UI_FONT_STACK, REGISTERED_THEMES } from "@/styles/theme";
import { applyAppearance, type AppearanceInput } from "./apply";
// Override the global react-native-unistyles mock (vitest.setup.ts) so that
@@ -37,7 +37,7 @@ interface FakeTheme {
"4xl": number;
};
lineHeight: { diff: number };
contentMaxWidth: Theme["contentMaxWidth"];
contentMaxWidth: number;
colors: { foreground: string; syntax: Record<string, string> };
}
@@ -105,13 +105,10 @@ describe("applyAppearance", () => {
]);
});
it.each([
[1600, "1600px"],
[undefined, "100%"],
])("uses a CSS variable-compatible width on web for %s", (contentMaxWidth, cssWidth) => {
applyAppearance(makeInput({ contentMaxWidth }));
it("patches the content max width into the theme", () => {
applyAppearance(makeInput({ contentMaxWidth: 1600 }));
expect(runCapturedUpdater().contentMaxWidth).toBe(cssWidth);
expect(runCapturedUpdater().contentMaxWidth).toBe(1600);
});
it("resolves an empty UI font family to the default stack", () => {
+3 -5
View File
@@ -5,7 +5,6 @@ import {
DEFAULT_MONO_FONT_STACK,
FONT_SIZE,
REGISTERED_THEMES,
themeContentMaxWidth,
type Theme,
} from "@/styles/theme";
import { applyRootUiFont } from "./apply-root-font";
@@ -18,7 +17,7 @@ export interface AppearanceInput {
uiBaseFontSize: number; // already clamped
contentFontSize: number; // already clamped
codeFontSize: number; // already clamped
contentMaxWidth: number | undefined; // undefined fills the available width
contentMaxWidth: number; // already clamped, default resolved
syntaxTheme: SyntaxThemeId;
}
@@ -65,7 +64,6 @@ export function applyAppearance(input: AppearanceInput): void {
const ui = input.uiFontFamily.trim() || DEFAULT_UI_FONT_STACK;
const mono = input.monoFontFamily.trim() || DEFAULT_MONO_FONT_STACK;
const diffLineHeight = Math.round(input.codeFontSize * 1.5); // couple to code size
const contentMaxWidth = themeContentMaxWidth(input.contentMaxWidth);
const activeTheme = UnistylesRuntime.themeName;
// Unistyles web emits after each registry patch. Updating the mounted theme
// first ensures subscribers receive its new numeric tokens in this render;
@@ -89,7 +87,7 @@ export function applyAppearance(input: AppearanceInput): void {
fontFamily,
fontSize,
lineHeight,
contentMaxWidth,
contentMaxWidth: input.contentMaxWidth,
colors: { ...t.colors, syntax: resolveSyntaxColors(input.syntaxTheme, t.colorScheme) },
};
}
@@ -98,7 +96,7 @@ export function applyAppearance(input: AppearanceInput): void {
fontFamily,
fontSize,
lineHeight,
contentMaxWidth,
contentMaxWidth: input.contentMaxWidth,
colors: { ...t.colors, syntax: resolveSyntaxColors(input.syntaxTheme, t.colorScheme) },
};
});
+2 -3
View File
@@ -65,7 +65,6 @@ export function AppearanceProvider({ children }: { children: ReactNode }) {
return options.find((option) => option.id === settings.pluginThemeId) ?? null;
}, [options, settings.pluginThemeId, settings.theme]);
const contentMaxWidth = resolveContentMaxWidth(settings);
useEffect(() => {
if (isLoading) return;
applyTheme({ preference: settings.theme, contributedTheme: selected });
@@ -75,7 +74,7 @@ export function AppearanceProvider({ children }: { children: ReactNode }) {
uiBaseFontSize: settings.uiBaseFontSize,
contentFontSize: settings.contentFontSize,
codeFontSize: settings.codeFontSize,
contentMaxWidth,
contentMaxWidth: resolveContentMaxWidth({ contentMaxWidth: settings.contentMaxWidth }),
syntaxTheme: settings.syntaxTheme,
});
setHasAppliedAppearance(true);
@@ -88,7 +87,7 @@ export function AppearanceProvider({ children }: { children: ReactNode }) {
settings.uiBaseFontSize,
settings.contentFontSize,
settings.codeFontSize,
contentMaxWidth,
settings.contentMaxWidth,
settings.syntaxTheme,
]);
@@ -1,77 +0,0 @@
import { describe, expect, it } from "vitest";
import { CHAT_OUTLINE_GUTTER_INSET } from "@/agent-stream/chat-outline/geometry";
import { CHAT_COLUMN_BASE_GUTTER, resolveChatColumnGutters } from "./gutters";
import {
CHAT_COLUMN_RAIL_DATASET as NATIVE_CHAT_COLUMN_RAIL_DATASET,
ChatColumnRailSurface as NativeChatColumnRailSurface,
useChatOutlineRail as useNativeChatOutlineRail,
} from "./index.native";
import { CHAT_COLUMN_RAIL_DATASET as WEB_CHAT_COLUMN_RAIL_DATASET } from "./index.web";
describe("resolveChatColumnGutters", () => {
it("uses symmetric base gutters when no outline inset is reserved", () => {
expect(
resolveChatColumnGutters({
gutter: CHAT_COLUMN_BASE_GUTTER,
outlineInset: 0,
contentMaxWidth: 820,
}),
).toEqual({ paddingLeft: 16, paddingRight: 16 });
expect(
resolveChatColumnGutters({
gutter: CHAT_COLUMN_BASE_GUTTER,
outlineInset: 0,
contentMaxWidth: undefined,
}),
).toEqual({ paddingLeft: 16, paddingRight: 16 });
});
it("reserves only the left outline gutter when content width is Full", () => {
expect(
resolveChatColumnGutters({
gutter: CHAT_COLUMN_BASE_GUTTER,
outlineInset: CHAT_OUTLINE_GUTTER_INSET,
contentMaxWidth: undefined,
}),
).toEqual({ paddingLeft: 60, paddingRight: 16 });
});
it("balances capped columns with a clamped right gutter from the remaining width", () => {
expect(
resolveChatColumnGutters({
gutter: CHAT_COLUMN_BASE_GUTTER,
outlineInset: CHAT_OUTLINE_GUTTER_INSET,
contentMaxWidth: 820,
}),
).toEqual({
paddingLeft: 60,
paddingRight: "clamp(16px, calc(100% - 880px), 60px)",
});
expect(
resolveChatColumnGutters({
gutter: CHAT_COLUMN_BASE_GUTTER,
outlineInset: CHAT_OUTLINE_GUTTER_INSET,
contentMaxWidth: 1200,
}),
).toEqual({
paddingLeft: 60,
paddingRight: "clamp(16px, calc(100% - 1260px), 60px)",
});
});
});
describe("native and web chat-rail boundaries", () => {
it("keeps native as a zero-overhead pass-through with no dataset or outline inset", () => {
const sentinel = "child";
expect(NATIVE_CHAT_COLUMN_RAIL_DATASET).toBeUndefined();
expect(useNativeChatOutlineRail()).toEqual({ enabled: false, inset: 0 });
expect(NativeChatColumnRailSurface({ serverId: "srv-1", children: sentinel })).toBe(sentinel);
});
it("tags web rail lanes with a frozen dataset reference", () => {
expect(WEB_CHAT_COLUMN_RAIL_DATASET).toEqual({ chatRailLane: "true" });
expect(Object.isFrozen(WEB_CHAT_COLUMN_RAIL_DATASET)).toBe(true);
});
});
-30
View File
@@ -1,30 +0,0 @@
import { SPACING } from "@/styles/theme";
export const CHAT_COLUMN_BASE_GUTTER = SPACING[4];
export interface ChatColumnGutters {
paddingLeft: number;
paddingRight: number | string;
}
/**
* Horizontal padding for a chat column on web.
*
* When the chat outline reserves `outlineInset` on the left, a capped column matches
* that inset on the right using only the horizontal slack left over after fitting
* `contentMaxWidth`. Default and Wide stay centered while the pane has room, shift
* smoothly away from the outline as the pane narrows, and fall back to the base gutter
* on the right when uncapped (`Full`) or tight.
*/
export function resolveChatColumnGutters(input: {
gutter: number;
outlineInset: number;
contentMaxWidth: number | undefined;
}): ChatColumnGutters {
const paddingLeft = input.gutter + input.outlineInset;
const paddingRight =
input.outlineInset > 0 && input.contentMaxWidth !== undefined
? `clamp(${input.gutter}px, calc(100% - ${paddingLeft + input.contentMaxWidth}px), ${paddingLeft}px)`
: input.gutter;
return { paddingLeft, paddingRight };
}
@@ -1,39 +0,0 @@
import type { ReactNode } from "react";
export interface ChatColumnRailSurfaceProps {
serverId: string;
children: ReactNode;
}
export interface ChatOutlineRailState {
/** Whether the chat outline feature is enabled for this pane (independent of pane width). */
readonly enabled: boolean;
/** Left gutter inset currently reserved for the outline rail (`0` or `44` on web). */
readonly inset: number;
}
const DISABLED_CHAT_OUTLINE_RAIL: ChatOutlineRailState = Object.freeze({
enabled: false,
inset: 0,
});
/**
* Marker for chat surfaces (composer, track bar, callouts) that share the pane's
* horizontal column rail. On web, an active `ChatColumnRailSurface` applies the
* pane's outline-aware gutters via CSS custom properties without re-rendering
* children. Native never reserves an outline gutter, so this is undefined.
*/
export const CHAT_COLUMN_RAIL_DATASET: Record<string, string> | undefined = undefined;
/**
* Native pass-through: the chat outline is a wide-layout web affordance, so native
* renders no wrapper view, registers no subscriptions, and reserves no outline inset.
*/
export function ChatColumnRailSurface({ children }: ChatColumnRailSurfaceProps) {
return children;
}
/** Chat outline state for this pane (always disabled with 0 inset on native). */
export function useChatOutlineRail(): ChatOutlineRailState {
return DISABLED_CHAT_OUTLINE_RAIL;
}
-7
View File
@@ -1,7 +0,0 @@
export {
CHAT_COLUMN_RAIL_DATASET,
ChatColumnRailSurface,
useChatOutlineRail,
type ChatColumnRailSurfaceProps,
type ChatOutlineRailState,
} from "./index.native";
-143
View File
@@ -1,143 +0,0 @@
import {
createContext,
useContext,
useLayoutEffect,
useMemo,
useRef,
useState,
type CSSProperties,
} from "react";
import {
CHAT_OUTLINE_GUTTER_INSET,
CHAT_OUTLINE_MIN_PANEL_WIDTH,
} from "@/agent-stream/chat-outline/geometry";
import { resolveContentMaxWidth, useSettings } from "@/hooks/use-settings";
import { useSessionStore } from "@/stores/session-store";
import { CHAT_COLUMN_BASE_GUTTER, resolveChatColumnGutters } from "./gutters";
import type { ChatColumnRailSurfaceProps, ChatOutlineRailState } from "./index";
export type { ChatColumnRailSurfaceProps, ChatOutlineRailState };
const STYLE_ID = "paseo-chat-column-rail";
// React Native Web turns `dataSet={{ chatRailLane: "true" }}` into `data-chat-rail-lane="true"`.
// When the enclosing pane reserves an outline gutter, every tagged rail consumer receives
// the same horizontal gutters in the browser's layout pass without re-rendering React subtrees
// or growing Unistyles' CSS registry.
const RAIL_RULE =
'[data-chat-rail-active="true"] [data-chat-rail-lane="true"]{padding-left:var(--paseo-chat-rail-left)!important;padding-right:var(--paseo-chat-rail-right)!important;}';
const BASE_SURFACE_STYLE: CSSProperties = {
display: "flex",
flexDirection: "column",
flex: 1,
minWidth: 0,
minHeight: 0,
};
const DISABLED_CHAT_OUTLINE_RAIL: ChatOutlineRailState = Object.freeze({
enabled: false,
inset: 0,
});
const ChatOutlineRailContext = createContext<ChatOutlineRailState>(DISABLED_CHAT_OUTLINE_RAIL);
export const CHAT_COLUMN_RAIL_DATASET: Record<string, string> | undefined = Object.freeze({
chatRailLane: "true",
});
function ensureChatColumnRailStyle(): void {
if (typeof document === "undefined") return;
if (document.getElementById(STYLE_ID)) return;
const style = document.createElement("style");
style.id = STYLE_ID;
style.textContent = RAIL_RULE;
document.head.appendChild(style);
}
function cssLength(value: number | string): string {
return typeof value === "number" ? `${value}px` : value;
}
/**
* Pane-level owner of the chat column rail on web.
*
* Measures the pane width once against `CHAT_OUTLINE_MIN_PANEL_WIDTH` (ignoring 0px
* measurements from hidden retained tabs) and publishes the resolved horizontal gutters
* via CSS custom properties to the composer, track bar, and callouts. Only the outline
* enabled flag and reserved inset (`0` or `44`) enter React context for `AgentStreamView`.
*/
export function ChatColumnRailSurface({ serverId, children }: ChatColumnRailSurfaceProps) {
const surfaceRef = useRef<HTMLDivElement | null>(null);
const [isBelow, setIsBelow] = useState(true);
const chatOutlineEnabled = useSettings((settings) => settings.chatOutlineEnabled);
const contentMaxWidth = useSettings(resolveContentMaxWidth);
const supportsChatOutline = useSessionStore(
(state) => state.sessions[serverId]?.serverInfo?.features?.agentTimelinePromptIndex === true,
);
useLayoutEffect(() => {
const node = surfaceRef.current;
if (!node) return;
const update = (width: number) => {
// Retained inactive tabs sit under `display: none` and report 0; ignore them.
if (width <= 0) return;
const next = width < CHAT_OUTLINE_MIN_PANEL_WIDTH;
setIsBelow((current) => (current === next ? current : next));
};
update(node.getBoundingClientRect().width);
if (typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver((entries) => {
const width =
entries[entries.length - 1]?.contentRect.width ?? node.getBoundingClientRect().width;
update(width);
});
observer.observe(node);
return () => observer.disconnect();
}, []);
const enabled = supportsChatOutline && chatOutlineEnabled;
const inset = enabled && !isBelow ? CHAT_OUTLINE_GUTTER_INSET : 0;
useLayoutEffect(() => {
if (inset > 0) {
ensureChatColumnRailStyle();
}
}, [inset]);
const outlineRail = useMemo<ChatOutlineRailState>(
() => (enabled ? { enabled, inset } : DISABLED_CHAT_OUTLINE_RAIL),
[enabled, inset],
);
const surfaceStyle = useMemo((): CSSProperties => {
if (inset === 0) {
return BASE_SURFACE_STYLE;
}
const gutters = resolveChatColumnGutters({
gutter: CHAT_COLUMN_BASE_GUTTER,
outlineInset: inset,
contentMaxWidth,
});
return {
...BASE_SURFACE_STYLE,
"--paseo-chat-rail-left": cssLength(gutters.paddingLeft),
"--paseo-chat-rail-right": cssLength(gutters.paddingRight),
} as CSSProperties;
}, [contentMaxWidth, inset]);
return (
<ChatOutlineRailContext.Provider value={outlineRail}>
<div
ref={surfaceRef}
style={surfaceStyle}
data-chat-rail-active={inset > 0 ? "true" : undefined}
>
{children}
</div>
</ChatOutlineRailContext.Provider>
);
}
export function useChatOutlineRail(): ChatOutlineRailState {
return useContext(ChatOutlineRailContext);
}
@@ -437,13 +437,11 @@ export function SheetHeaderSubtitle({ text, testID }: { text: string; testID?: s
export function SheetHeaderView({
header,
onClose,
showCloseButton = true,
testID,
closeTestID,
}: {
header: SheetHeader;
onClose: () => void;
showCloseButton?: boolean;
testID?: string;
closeTestID?: string;
}) {
@@ -475,14 +473,12 @@ export function SheetHeaderView({
</View>
<View style={styles.headerTrailing}>
{header.actions}
{showCloseButton ? (
<SheetHeaderIconButton
icon={X}
label={t("common.actions.close")}
onPress={onClose}
testID={closeTestID}
/>
) : null}
<SheetHeaderIconButton
icon={X}
label={t("common.actions.close")}
onPress={onClose}
testID={closeTestID}
/>
</View>
</View>
</IconButtonChromeProvider>
@@ -570,11 +566,6 @@ export interface AdaptiveModalSheetProps {
* corner, and the compact sheet closes from its handle.
*/
header?: SheetHeader;
/**
* Leave out the header's close button when `header.back` is the only way out, as for a sheet
* that stands in for a page of the surface beneath it. Escape still closes the sheet.
*/
showCloseButton?: boolean;
visible: boolean;
onClose: () => void;
onDismiss?: () => void;
@@ -605,7 +596,6 @@ export interface AdaptiveModalSheetProps {
*/
function CompactSheetBody({
header,
showCloseButton,
onClose,
testID,
footer,
@@ -616,7 +606,6 @@ function CompactSheetBody({
children,
}: {
header?: SheetHeader;
showCloseButton: boolean;
onClose: () => void;
testID?: string;
footer: ReactNode;
@@ -646,14 +635,7 @@ function CompactSheetBody({
);
return (
<SheetVisibleFrame footer={footerView}>
{header ? (
<SheetHeaderView
header={header}
onClose={onClose}
showCloseButton={showCloseButton}
testID={testID}
/>
) : null}
{header ? <SheetHeaderView header={header} onClose={onClose} testID={testID} /> : null}
<View style={[styles.compactStaticContent, bodyStyle]}>
{scrollable ? (
<ScrollView
@@ -680,7 +662,6 @@ function CompactSheetBody({
export function AdaptiveModalSheet({
header,
showCloseButton = true,
visible,
onClose,
onDismiss,
@@ -808,7 +789,6 @@ export function AdaptiveModalSheet({
<OverlayLayerProvider layer={modalLayer}>
<CompactSheetBody
header={header}
showCloseButton={showCloseButton}
onClose={onClose}
testID={testID}
footer={footerView}
@@ -828,9 +808,7 @@ export function AdaptiveModalSheet({
desktopHeight == null ? styles.desktopStaticContent : styles.compactStaticContent;
const cardInner = (
<OverlayLayerProvider layer={modalLayer}>
{header ? (
<SheetHeaderView header={header} onClose={onClose} showCloseButton={showCloseButton} />
) : null}
{header ? <SheetHeaderView header={header} onClose={onClose} /> : null}
<View style={[scrollable ? styles.desktopScrollContainer : desktopStaticStyle, bodyStyle]}>
{scrollable ? (
<ScrollView
@@ -2,7 +2,6 @@ import { useCallback, useState } from "react";
import { View, Text } from "react-native";
import { useTranslation } from "react-i18next";
import { StyleSheet } from "react-native-unistyles";
import { CHAT_COLUMN_RAIL_DATASET } from "@/chat-rail";
import { FOOTER_HEIGHT } from "@/constants/layout";
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
import { KeyboardTranslateView } from "@/keyboard/shift";
@@ -36,7 +35,7 @@ export function ArchivedAgentCallout({ serverId, agentId }: ArchivedAgentCallout
return (
<KeyboardTranslateView style={styles.container}>
<View style={styles.inputAreaContainer} dataSet={CHAT_COLUMN_RAIL_DATASET}>
<View style={styles.inputAreaContainer}>
<View style={styles.inputAreaContent}>
<View style={styles.calloutStack}>
<View style={styles.callout}>
@@ -24,9 +24,6 @@ import { isNative } from "@/constants/platform";
*/
export const WINDOW_CONTENT_DATASET = { "window-content": "" };
/** Reserves a clickable area for a control mounted outside the titlebar rail. */
export const WINDOW_NO_DRAG_DATASET = { "window-no-drag": "" };
export const titlebarDragSurfaceStyle: React.CSSProperties = {
cursor: "default",
// @ts-expect-error — WebkitAppRegion is not in CSSProperties
@@ -27,7 +27,6 @@ const NO_SHORTCUT: ShortcutKey[] = [];
interface CompactHeaderProps {
/** The leading island: the sidebar menu, or a back button. */
navigation: "menu" | "back";
inDesktopTitlebar?: boolean;
/** Back button action. Defaults to navigating back. */
onBack?: () => void;
title?: string;
@@ -50,7 +49,6 @@ interface CompactHeaderProps {
*/
export function CompactHeader({
navigation,
inDesktopTitlebar = false,
onBack,
title,
titleTestID,
@@ -60,28 +58,22 @@ export function CompactHeader({
}: CompactHeaderProps) {
const insets = useSafeAreaInsets();
const inTopBand = useTopBand() !== null;
const usesTitlebarHeight = inTopBand || inDesktopTitlebar;
const rootStyle = useMemo(
() => [
styles.root,
{
paddingTop: insets.top + (usesTitlebarHeight ? 0 : HEADER_TOP_PADDING_MOBILE),
paddingTop: insets.top + (inTopBand ? 0 : HEADER_TOP_PADDING_MOBILE),
marginLeft: insets.left,
marginRight: insets.right,
},
],
[usesTitlebarHeight, insets.top, insets.left, insets.right],
[inTopBand, insets.top, insets.left, insets.right],
);
return (
<IconButtonChromeProvider value="header-island">
<View style={rootStyle}>
<View
style={[
usesTitlebarHeight ? styles.titlebarRow : styles.row,
inDesktopTitlebar && styles.desktopTitlebarDividerSpace,
]}
>
<View style={inTopBand ? styles.topBandRow : styles.row}>
<View style={styles.island}>
{navigation === "menu" ? <SidebarMenuToggle /> : <BackButton onBack={onBack} />}
</View>
@@ -163,16 +155,12 @@ const styles = StyleSheet.create((theme) => ({
alignItems: "center",
gap: theme.spacing[2],
},
titlebarRow: {
topBandRow: {
height: HEADER_INNER_HEIGHT,
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
},
desktopTitlebarDividerSpace: {
borderBottomWidth: theme.borderWidth[1],
borderBottomColor: "transparent",
},
titleGroup: {
flex: 1,
minWidth: 0,
@@ -0,0 +1,234 @@
import { useCallback, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { Text, View, type LayoutChangeEvent } from "react-native";
import { SvgXml } from "react-native-svg";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { PackagePlus } from "lucide-react-native";
import { Button } from "@/components/ui/button";
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 { SPACING, type Theme } from "@/styles/theme";
import { settingsStyles } from "@/styles/settings";
interface ProviderCatalogListProps {
serverId: string;
installingProviderId: string | null;
onInstall: (entry: AcpProviderCatalogItem) => Promise<void> | void;
}
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 foregroundColorMapping = (theme: Theme) => ({ color: theme.colors.foreground });
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 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 CatalogTile({ entry, width, installing, onInstall }: CatalogTileProps) {
const { t } = useTranslation();
const handleInstall = useCallback(() => {
onInstall(entry);
}, [entry, onInstall]);
const tileStyle = useMemo(
() => [settingsStyles.card, styles.tile, width === undefined ? styles.tileFull : { width }],
[width],
);
return (
<View style={tileStyle} testID={`provider-catalog-tile-${entry.id}`}>
<View style={styles.iconFrame}>
{entry.iconSvg ? (
<ThemedSvgXml
xml={entry.iconSvg}
width={PROVIDER_REMOTE_ICON_SIZE}
height={PROVIDER_REMOTE_ICON_SIZE}
uniProps={foregroundColorMapping}
/>
) : (
<ThemedPackagePlus size={PROVIDER_FALLBACK_ICON_SIZE} uniProps={foregroundColorMapping} />
)}
</View>
<View style={styles.details}>
<Text style={styles.name} numberOfLines={1}>
{entry.title}
</Text>
<View style={styles.metaRow}>
{/* The catalog is the ACP registry, so every entry it offers is an ACP provider. */}
<StatusBadge label={t("providerCatalog.types.acp")} size="xs" />
<ExternalLink
href={entry.installLink}
label={t("providerCatalog.actions.installInstructions")}
accessibilityLabel={t("providerCatalog.actions.installInstructionsFor", {
provider: entry.title,
})}
/>
</View>
</View>
<Button
size="sm"
variant="outline"
disabled={installing}
loading={installing}
onPress={handleInstall}
accessibilityLabel={t("providerCatalog.actions.addProvider", { provider: entry.title })}
style={styles.addButton}
testID={`install-provider-${entry.id}`}
>
{installing ? t("providerCatalog.actions.adding") : t("providerCatalog.actions.add")}
</Button>
</View>
);
}
export function ProviderCatalogList({
serverId,
installingProviderId,
onInstall,
}: ProviderCatalogListProps) {
const { t } = useTranslation();
const { entries: catalogEntries } = useAcpProviderCatalog();
const { entries: providerEntries } = useProvidersSnapshot(serverId);
const [search, setSearch] = useState("");
const [gridWidth, setGridWidth] = useState<number | null>(null);
const installedIds = useMemo(
() => new Set(providerEntries?.map((entry) => entry.provider) ?? []),
[providerEntries],
);
const availableEntries = useMemo(
() =>
rankProviderCatalog(
catalogEntries.filter((entry) => !installedIds.has(entry.id)),
search,
),
[catalogEntries, installedIds, search],
);
const handleGridLayout = useCallback((event: LayoutChangeEvent) => {
setGridWidth(event.nativeEvent.layout.width);
}, []);
const tileWidth = useMemo(() => {
if (gridWidth === null) return undefined;
const columns = columnCountForWidth(gridWidth);
if (columns === 1) return undefined;
return Math.floor((gridWidth - TILE_GAP * (columns - 1)) / columns);
}, [gridWidth]);
return (
<View>
<View style={styles.searchRail}>
<SearchField
value={search}
onChangeText={setSearch}
placeholder={t("providerCatalog.search")}
clearAccessibilityLabel={t("providerCatalog.clearSearch")}
testID="provider-catalog-search"
clearTestID="provider-catalog-search-clear"
/>
</View>
{availableEntries.length === 0 ? (
<View style={[settingsStyles.card, styles.stateBox]}>
<Text style={styles.stateText}>{t("providerCatalog.noProviders")}</Text>
</View>
) : (
<View style={styles.grid} onLayout={handleGridLayout}>
{availableEntries.map((entry) => (
<CatalogTile
key={entry.id}
entry={entry}
width={tileWidth}
installing={installingProviderId === entry.id}
onInstall={onInstall}
/>
))}
</View>
)}
</View>
);
}
const styles = StyleSheet.create((theme) => ({
searchRail: {
flexDirection: "row",
marginBottom: theme.spacing[3],
},
grid: {
flexDirection: "row",
flexWrap: "wrap",
gap: TILE_GAP,
},
tile: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[3],
padding: theme.spacing[3],
},
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,
},
name: {
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
fontWeight: theme.fontWeight.normal,
},
metaRow: {
flexDirection: "row",
flexWrap: "wrap",
alignItems: "center",
gap: theme.spacing[2],
},
stateBox: {
minHeight: 96,
alignItems: "center",
justifyContent: "center",
padding: theme.spacing[4],
},
stateText: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.base,
},
}));
@@ -3,7 +3,7 @@ import type { AgentModelDefinition } from "@getpaseo/protocol/agent-types";
import {
resolveProviderDiscoveredModels,
type ProviderDiscoveredModelsCache,
} from "./discovered-models";
} from "./provider-diagnostic-models";
const piModel: AgentModelDefinition = {
provider: "pi",
@@ -0,0 +1,825 @@
import * as Clipboard from "expo-clipboard";
import { AlertTriangle, Copy, FileText, Plus, RotateCw, Trash2 } from "lucide-react-native";
import type { TFunction } from "i18next";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Pressable, type PressableStateCallbackType, Text, View } from "react-native";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import {
AdaptiveModalSheet,
AdaptiveTextInput,
SheetHeaderIconButton,
type SheetHeader,
} from "@/components/adaptive-modal-sheet";
import { Button } from "@/components/ui/button";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { ScrollableCodeSurface, SurfaceCard } from "@/components/ui/scrollable-code-surface";
import { useIsCompactFormFactor } from "@/constants/layout";
import { isWeb } from "@/constants/platform";
import { useToast } from "@/contexts/toast-context";
import { CODE_SURFACE_DATASET } from "@/styles/code-surface";
import { useDaemonConfig } from "@/hooks/use-daemon-config";
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
import { useTimeAgo } from "@/hooks/use-time-ago";
import { useHostRuntimeClient } from "@/runtime/host-runtime";
import { settingsStyles } from "@/styles/settings";
import { resolveProviderLabel } from "@/utils/provider-definitions";
import { compareMatchScores, scoreTextFields } from "@getpaseo/protocol/search/text-match";
import type { AgentModelDefinition, AgentProvider } from "@getpaseo/protocol/agent-types";
import type { ProviderProfileModel } from "@getpaseo/protocol/provider-config";
import {
resolveProviderDiscoveredModels,
type ProviderDiscoveredModelsCache,
} from "./provider-diagnostic-models";
interface ProviderDiagnosticSheetProps {
provider: string;
visible: boolean;
onClose: () => void;
serverId: string;
}
function rankModels<T>(items: T[], query: string, fields: (item: T) => string[]): T[] {
if (!query.trim()) return items;
const scored = items
.map((item) => ({ item, score: scoreTextFields(query, fields(item)) }))
.filter(
(entry): entry is { item: T; score: NonNullable<typeof entry.score> } => entry.score !== null,
);
scored.sort((a, b) => compareMatchScores(a.score, b.score));
return scored.map((entry) => entry.item);
}
function DiscoveredModelRow({ model }: { model: AgentModelDefinition }) {
return (
<View style={sheetStyles.modelRow}>
<Text style={sheetStyles.modelTitle} numberOfLines={1}>
{model.label}
</Text>
<Text
style={sheetStyles.monoHint}
numberOfLines={1}
selectable
dataSet={CODE_SURFACE_DATASET}
>
{model.id}
</Text>
{model.description ? (
<Text style={sheetStyles.descriptionInline} numberOfLines={1}>
{model.description}
</Text>
) : null}
</View>
);
}
function CustomModelRow({
model,
deleting,
onDelete,
}: {
model: ProviderProfileModel;
deleting: boolean;
onDelete: (modelId: string) => void;
}) {
const { t } = useTranslation();
const { theme } = useUnistyles();
const handleDelete = useCallback(() => onDelete(model.id), [model.id, onDelete]);
const deleteButtonStyle = useCallback(
({ hovered, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [
sheetStyles.iconButton,
(Boolean(hovered) || pressed) && sheetStyles.iconButtonHovered,
deleting ? sheetStyles.disabled : null,
],
[deleting],
);
return (
<View style={sheetStyles.modelRow}>
<Text style={[sheetStyles.modelTitle, sheetStyles.customModelText]} numberOfLines={1}>
{model.label}
</Text>
<Text
style={[sheetStyles.monoHint, sheetStyles.customModelText]}
numberOfLines={1}
selectable
dataSet={CODE_SURFACE_DATASET}
>
{model.id}
</Text>
<View style={sheetStyles.modelRowFiller} />
<Pressable
onPress={handleDelete}
disabled={deleting}
hitSlop={8}
style={deleteButtonStyle}
accessibilityRole="button"
accessibilityLabel={t("settings.providers.models.removeModel", { id: model.id })}
>
<Trash2 size={theme.iconSize.sm} color={theme.colors.destructive} />
</Pressable>
</View>
);
}
function SectionHeader({ title, count, hint }: { title: string; count?: number; hint?: string }) {
return (
<View style={sheetStyles.sectionHeader}>
<Text style={settingsStyles.sectionHeaderTitle}>{title}</Text>
<View style={sheetStyles.sectionHeaderMeta}>
{count !== undefined ? (
<Text style={settingsStyles.sectionHeaderTitle}>{count}</Text>
) : null}
{count !== undefined && hint ? (
<Text style={settingsStyles.sectionHeaderTitle}>·</Text>
) : null}
{hint ? <Text style={settingsStyles.sectionHeaderTitle}>{hint}</Text> : null}
</View>
</View>
);
}
function AddCustomModelSubSheet({
provider,
serverId,
visible,
onClose,
refresh,
}: {
provider: string;
serverId: string;
visible: boolean;
onClose: () => void;
refresh: (providers?: AgentProvider[]) => Promise<void>;
}) {
const { t } = useTranslation();
const { theme } = useUnistyles();
const { config, patchConfig } = useDaemonConfig(serverId);
const [input, setInput] = useState("");
const [error, setError] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
const additionalModels = useMemo(
() => config?.providers?.[provider]?.additionalModels ?? [],
[config?.providers, provider],
);
const trimmed = input.trim();
const canAdd = trimmed.length > 0 && !additionalModels.some((model) => model.id === trimmed);
useEffect(() => {
if (!visible) {
setInput("");
setError(null);
}
}, [visible]);
const handleAdd = useCallback(() => {
if (!canAdd) return;
setError(null);
setSaving(true);
void patchConfig({
providers: {
[provider]: {
additionalModels: [...additionalModels, { id: trimmed, label: trimmed }],
},
},
})
.then(() => refresh([provider]))
.then(() => onClose())
.catch((err) => {
setError(err instanceof Error ? err.message : t("settings.providers.models.failedToSave"));
})
.finally(() => setSaving(false));
}, [additionalModels, canAdd, onClose, patchConfig, provider, refresh, t, trimmed]);
const header = useMemo<SheetHeader>(
() => ({ title: t("settings.providers.models.addCustomTitle") }),
[t],
);
return (
<AdaptiveModalSheet
header={header}
visible={visible}
onClose={onClose}
desktopMaxWidth={420}
snapPoints={ADD_SNAP_POINTS}
testID="add-custom-model-sheet"
>
<View style={sheetStyles.formGroup}>
<Text style={sheetStyles.formLabel}>{t("settings.providers.models.modelId")}</Text>
<AdaptiveTextInput
initialValue={input}
resetKey={`add-custom-${visible}`}
onChangeText={setInput}
onSubmitEditing={handleAdd}
placeholder={t("settings.providers.models.modelIdPlaceholder")}
placeholderTextColor={theme.colors.foregroundMuted}
autoCapitalize="none"
autoCorrect={false}
returnKeyType="done"
// @ts-expect-error - outlineStyle is web-only
style={[sheetStyles.formInput, isWeb && { outlineStyle: "none" }]}
/>
{error ? <Text style={sheetStyles.errorText}>{error}</Text> : null}
<View style={sheetStyles.formActions}>
<Button variant="secondary" onPress={onClose} disabled={saving}>
{t("common.actions.cancel")}
</Button>
<Button variant="default" onPress={handleAdd} disabled={!canAdd || saving}>
{saving ? t("settings.providers.models.adding") : t("settings.providers.models.add")}
</Button>
</View>
</View>
</AdaptiveModalSheet>
);
}
function DiagnosticSubSheet({
provider,
serverId,
visible,
onClose,
}: {
provider: string;
serverId: string;
visible: boolean;
onClose: () => void;
}) {
const { t } = useTranslation();
const { theme } = useUnistyles();
const toast = useToast();
const client = useHostRuntimeClient(serverId);
const [diagnostic, setDiagnostic] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const fetchDiagnostic = useCallback(async () => {
if (!client) return;
setLoading(true);
try {
const result = await client.getProviderDiagnostic(provider);
setDiagnostic(result.diagnostic);
} catch (err) {
setDiagnostic(
err instanceof Error ? err.message : t("settings.providers.diagnostic.failedToFetch"),
);
} finally {
setLoading(false);
}
}, [client, provider, t]);
useEffect(() => {
if (visible) {
void fetchDiagnostic();
} else {
setDiagnostic(null);
}
}, [visible, fetchDiagnostic]);
const handleRefreshPress = useCallback(() => {
void fetchDiagnostic();
}, [fetchDiagnostic]);
const handleCopyPress = useCallback(() => {
if (!diagnostic) return;
void Clipboard.setStringAsync(diagnostic)
.then(() => toast.copied(t("settings.providers.diagnostic.copyLabel")))
.catch(() => toast.error(t("settings.providers.diagnostic.copyFailed")));
}, [diagnostic, t, toast]);
const header = useMemo<SheetHeader>(
() => ({
title: t("settings.providers.diagnostic.title"),
actions: (
<>
<SheetHeaderIconButton
icon={Copy}
label={t("settings.providers.diagnostic.copyAccessibility")}
onPress={handleCopyPress}
disabled={!diagnostic}
/>
<SheetHeaderIconButton
icon={RotateCw}
label={
loading
? t("settings.providers.diagnostic.refreshingAccessibility")
: t("settings.providers.diagnostic.refreshAccessibility")
}
onPress={handleRefreshPress}
busy={loading}
/>
</>
),
}),
[diagnostic, handleCopyPress, handleRefreshPress, loading, t],
);
let body: React.ReactNode;
if (loading && !diagnostic) {
body = (
<SurfaceCard key={visible ? "visible" : "hidden"}>
<View style={sheetStyles.codeBlockLoading}>
<LoadingSpinner size="small" color={theme.colors.foregroundMuted} />
<Text style={sheetStyles.mutedText}>{t("settings.providers.diagnostic.running")}</Text>
</View>
</SurfaceCard>
);
} else if (diagnostic) {
body = (
<ScrollableCodeSurface key={visible ? "visible" : "hidden"} maxHeight={480}>
{diagnostic}
</ScrollableCodeSurface>
);
} else {
body = (
<SurfaceCard key={visible ? "visible" : "hidden"}>
<View style={sheetStyles.codeBlockLoading}>
<Text style={sheetStyles.mutedText}>{t("settings.providers.diagnostic.none")}</Text>
</View>
</SurfaceCard>
);
}
return (
<AdaptiveModalSheet
header={header}
visible={visible}
onClose={onClose}
snapPoints={DIAGNOSTIC_SNAP_POINTS}
scrollable={false}
testID="provider-diagnostic-sheet"
>
{body}
</AdaptiveModalSheet>
);
}
interface ProviderModalBodyProps {
discoveredCount: number;
additionalCount: number;
providerSnapshotRefreshing: boolean;
providerErrorMessage: string | null;
modelsRefreshing: boolean;
searchActive: boolean;
filteredDiscovered: AgentModelDefinition[];
filteredCustom: ProviderProfileModel[];
deletingModelId: string | null;
onRefresh: () => void;
onDeleteCustom: (modelId: string) => void;
theme: { iconSize: { md: number }; colors: { foregroundMuted: string } };
}
interface ProviderSheetFooterInput {
fetchedAt: string | null;
isCompact: boolean;
modelsRefreshing: boolean;
t: TFunction;
onOpenAddSheet: () => void;
onOpenDiagSheet: () => void;
onRefreshModels: () => void;
}
function renderProviderSheetFooter({
fetchedAt,
isCompact,
modelsRefreshing,
t,
onOpenAddSheet,
onOpenDiagSheet,
onRefreshModels,
}: ProviderSheetFooterInput) {
const contentStyle = isCompact ? sheetStyles.compactFooterContent : sheetStyles.footerContent;
const actionsStyle = isCompact ? sheetStyles.compactFooterActions : sheetStyles.footerActions;
const buttonStyle = isCompact ? sheetStyles.compactFooterButton : null;
return (
<View style={contentStyle}>
{fetchedAt || !isCompact ? (
<ProviderUpdatedLabel fetchedAt={fetchedAt} isCompact={isCompact} />
) : null}
<View style={actionsStyle}>
<Button variant="secondary" leftIcon={Plus} onPress={onOpenAddSheet} style={buttonStyle}>
{t("settings.providers.models.addModel")}
</Button>
<Button
variant="secondary"
leftIcon={FileText}
onPress={onOpenDiagSheet}
style={buttonStyle}
>
{t("settings.providers.diagnostic.button")}
</Button>
<Button
variant="default"
leftIcon={modelsRefreshing ? undefined : RotateCw}
onPress={onRefreshModels}
disabled={modelsRefreshing}
style={buttonStyle}
>
{modelsRefreshing
? t("settings.providers.diagnostic.refreshing")
: t("settings.providers.diagnostic.refresh")}
</Button>
</View>
</View>
);
}
function ProviderUpdatedLabel({
fetchedAt,
isCompact,
}: {
fetchedAt: string | null;
isCompact: boolean;
}) {
const { t } = useTranslation();
const label = useTimeAgo(fetchedAt ? new Date(fetchedAt) : null);
const style = isCompact
? [sheetStyles.footerMeta, sheetStyles.compactFooterMeta]
: sheetStyles.footerMeta;
return (
<Text style={style} numberOfLines={1}>
{fetchedAt ? t("settings.providers.models.updated", { time: label }) : ""}
</Text>
);
}
function ProviderModalBody(props: ProviderModalBodyProps) {
const { t } = useTranslation();
const {
discoveredCount,
additionalCount,
providerSnapshotRefreshing,
providerErrorMessage,
modelsRefreshing,
searchActive,
filteredDiscovered,
filteredCustom,
deletingModelId,
onRefresh,
onDeleteCustom,
theme,
} = props;
if (discoveredCount === 0 && additionalCount === 0 && providerSnapshotRefreshing) {
return (
<View style={sheetStyles.emptyState}>
<LoadingSpinner size="small" color={theme.colors.foregroundMuted} />
<Text style={sheetStyles.mutedText}>{t("settings.providers.models.loading")}</Text>
</View>
);
}
if (discoveredCount === 0 && additionalCount === 0 && providerErrorMessage) {
return (
<View style={sheetStyles.emptyState}>
<AlertTriangle size={theme.iconSize.md} color={theme.colors.foregroundMuted} />
<Text style={sheetStyles.mutedText}>{providerErrorMessage}</Text>
<Button variant="default" onPress={onRefresh} disabled={modelsRefreshing}>
{modelsRefreshing
? t("settings.providers.models.retrying")
: t("settings.providers.models.retry")}
</Button>
</View>
);
}
if (filteredDiscovered.length === 0 && filteredCustom.length === 0 && searchActive) {
return (
<View style={sheetStyles.emptyState}>
<Text style={sheetStyles.mutedText}>{t("settings.providers.models.noSearchMatches")}</Text>
</View>
);
}
if (discoveredCount === 0 && additionalCount === 0) {
return (
<View style={sheetStyles.emptyState}>
<Text style={sheetStyles.mutedText}>{t("settings.providers.models.noneDetected")}</Text>
</View>
);
}
return (
<>
{filteredDiscovered.length > 0 ? (
<View style={sheetStyles.section}>
<SectionHeader
title={t("settings.providers.models.discovered")}
count={filteredDiscovered.length}
/>
<View style={settingsStyles.card}>
{filteredDiscovered.map((model) => (
<DiscoveredModelRow key={model.id} model={model} />
))}
</View>
</View>
) : null}
{filteredCustom.length > 0 ? (
<View style={sheetStyles.section}>
<SectionHeader
title={t("settings.providers.models.custom")}
count={filteredCustom.length}
/>
<View style={settingsStyles.card}>
{filteredCustom.map((model) => (
<CustomModelRow
key={model.id}
model={model}
deleting={deletingModelId === model.id}
onDelete={onDeleteCustom}
/>
))}
</View>
</View>
) : null}
</>
);
}
export function ProviderDiagnosticSheet({
provider,
visible,
onClose,
serverId,
}: ProviderDiagnosticSheetProps) {
const { t } = useTranslation();
const { theme } = useUnistyles();
const isCompact = useIsCompactFormFactor();
const { entries: snapshotEntries, refresh, isRefreshing } = useProvidersSnapshot(serverId);
const { config, patchConfig } = useDaemonConfig(serverId);
const [query, setQuery] = useState("");
const [addSheetOpen, setAddSheetOpen] = useState(false);
const [diagSheetOpen, setDiagSheetOpen] = useState(false);
const [deletingModelId, setDeletingModelId] = useState<string | null>(null);
const providerLabel = resolveProviderLabel(provider, snapshotEntries);
const providerEntry = useMemo(
() => snapshotEntries?.find((entry) => entry.provider === provider),
[snapshotEntries, provider],
);
const additionalModels = useMemo(
() => config?.providers?.[provider]?.additionalModels ?? [],
[config?.providers, provider],
);
const providerSnapshotRefreshing = providerEntry?.status === "loading";
const providerErrorMessage =
providerEntry?.status === "error"
? (providerEntry.error ?? t("settings.providers.diagnostic.unknownError"))
: null;
const modelsRefreshing = isRefreshing || providerSnapshotRefreshing;
const stableDiscoveredRef = useRef<ProviderDiscoveredModelsCache | null>(null);
const currentModels = providerEntry?.models;
const { models: discoveredModels, cache: nextDiscoveredCache } = resolveProviderDiscoveredModels({
serverId,
provider,
currentModels,
providerSnapshotRefreshing,
previousCache: stableDiscoveredRef.current,
});
stableDiscoveredRef.current = nextDiscoveredCache;
useEffect(() => {
if (!visible) {
setQuery("");
setAddSheetOpen(false);
setDiagSheetOpen(false);
}
}, [visible]);
const q = query.trim();
const filteredDiscovered = useMemo(
() => rankModels(discoveredModels, q, (m) => [m.label, m.id, m.description ?? ""]),
[discoveredModels, q],
);
const filteredCustom = useMemo(
() => rankModels(additionalModels, q, (m) => [m.label, m.id]),
[additionalModels, q],
);
const handleRefreshModels = useCallback(() => {
void refresh([provider]);
}, [provider, refresh]);
const handleOpenAddSheet = useCallback(() => setAddSheetOpen(true), []);
const handleCloseAddSheet = useCallback(() => setAddSheetOpen(false), []);
const handleOpenDiagSheet = useCallback(() => setDiagSheetOpen(true), []);
const handleCloseDiagSheet = useCallback(() => setDiagSheetOpen(false), []);
const handleDeleteCustom = useCallback(
(modelId: string) => {
setDeletingModelId(modelId);
void patchConfig({
providers: {
[provider]: {
additionalModels: additionalModels.filter((model) => model.id !== modelId),
},
},
})
.then(() => refresh([provider]))
.finally(() => {
setDeletingModelId((current) => (current === modelId ? null : current));
});
},
[additionalModels, patchConfig, provider, refresh],
);
const sheetHeader = useMemo<SheetHeader>(
() => ({
title: providerLabel,
search: {
onChange: setQuery,
placeholder: t("settings.providers.models.searchPlaceholder"),
testID: "provider-settings-search",
},
}),
[providerLabel, t],
);
return (
<>
<AdaptiveModalSheet
header={sheetHeader}
visible={visible}
onClose={onClose}
testID="provider-settings-sheet"
footer={renderProviderSheetFooter({
fetchedAt: providerEntry?.fetchedAt ?? null,
isCompact,
modelsRefreshing,
t,
onOpenAddSheet: handleOpenAddSheet,
onOpenDiagSheet: handleOpenDiagSheet,
onRefreshModels: handleRefreshModels,
})}
snapPoints={MAIN_SNAP_POINTS}
>
<ProviderModalBody
discoveredCount={discoveredModels.length}
additionalCount={additionalModels.length}
providerSnapshotRefreshing={providerSnapshotRefreshing}
providerErrorMessage={providerErrorMessage}
modelsRefreshing={modelsRefreshing}
searchActive={Boolean(q)}
filteredDiscovered={filteredDiscovered}
filteredCustom={filteredCustom}
deletingModelId={deletingModelId}
onRefresh={handleRefreshModels}
onDeleteCustom={handleDeleteCustom}
theme={theme}
/>
</AdaptiveModalSheet>
<AddCustomModelSubSheet
provider={provider}
serverId={serverId}
visible={addSheetOpen}
onClose={handleCloseAddSheet}
refresh={refresh}
/>
<DiagnosticSubSheet
provider={provider}
serverId={serverId}
visible={diagSheetOpen}
onClose={handleCloseDiagSheet}
/>
</>
);
}
const sheetStyles = StyleSheet.create((theme) => ({
mutedText: {
fontSize: theme.fontSize.base,
color: theme.colors.foregroundMuted,
},
monoHint: {
fontFamily: theme.fontFamily.mono,
fontSize: theme.fontSize.code,
color: theme.colors.foregroundMuted,
flexShrink: 0,
},
descriptionInline: {
flex: 1,
fontSize: theme.fontSize.sm,
color: theme.colors.foregroundMuted,
},
errorText: {
fontSize: theme.fontSize.sm,
color: theme.colors.destructive,
},
formInput: {
backgroundColor: theme.colors.surface2,
borderRadius: theme.borderRadius.lg,
paddingHorizontal: theme.spacing[4],
paddingVertical: theme.spacing[3],
color: theme.colors.foreground,
borderWidth: 1,
borderColor: theme.colors.border,
fontSize: theme.fontSize.base,
},
iconButton: {
width: 28,
height: 28,
flexShrink: 0,
borderRadius: theme.borderRadius.full,
alignItems: "center",
justifyContent: "center",
},
iconButtonHovered: {
backgroundColor: theme.colors.surface2,
},
disabled: {
opacity: 0.5,
},
section: {
marginBottom: theme.spacing[4],
},
sectionHeader: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
gap: theme.spacing[2],
marginBottom: theme.spacing[2],
marginLeft: theme.spacing[1],
},
sectionHeaderMeta: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[1],
},
modelRow: {
flexDirection: "row",
alignItems: "center",
paddingVertical: theme.spacing[2],
paddingHorizontal: theme.spacing[4],
gap: theme.spacing[3],
borderTopWidth: 1,
borderTopColor: theme.colors.border,
},
modelTitle: {
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
flexShrink: 0,
},
customModelText: {
flexShrink: 1,
minWidth: 0,
},
modelRowFiller: {
flex: 1,
},
emptyState: {
paddingVertical: theme.spacing[8],
alignItems: "center",
gap: theme.spacing[3],
},
footerContent: {
flex: 1,
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
gap: theme.spacing[2],
},
compactFooterContent: {
flex: 1,
gap: theme.spacing[2],
},
footerMeta: {
flex: 1,
fontSize: theme.fontSize.sm,
color: theme.colors.foregroundMuted,
},
compactFooterMeta: {
flex: 0,
},
footerActions: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
},
compactFooterActions: {
gap: theme.spacing[2],
},
compactFooterButton: {
alignSelf: "stretch",
},
formGroup: {
gap: theme.spacing[3],
},
formLabel: {
fontSize: theme.fontSize.base,
fontWeight: theme.fontWeight.medium,
color: theme.colors.foreground,
},
formActions: {
flexDirection: "row",
justifyContent: "flex-end",
gap: theme.spacing[2],
},
codeBlockLoading: {
paddingVertical: theme.spacing[4],
paddingHorizontal: theme.spacing[4],
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
},
}));
const MAIN_SNAP_POINTS = ["65%", "92%"];
const ADD_SNAP_POINTS = ["40%"];
const DIAGNOSTIC_SNAP_POINTS = ["50%", "85%"];
@@ -1,480 +0,0 @@
import React, { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { within } from "@testing-library/dom";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { i18n as testI18n } from "@/i18n/i18next";
import {
ProviderInstallationSection,
type ProviderInstallationState,
type ProviderUpdateAction,
type ProviderUpdatesState,
} from "./provider-installation-section";
// Load translations so controls expose their real accessible names.
void testI18n;
// App sources compile against the classic JSX runtime, which expects React on the global.
beforeEach(() => vi.stubGlobal("React", React));
const mounted: { root: Root; container: HTMLDivElement }[] = [];
afterEach(() => {
for (const entry of mounted.splice(0)) {
act(() => entry.root.unmount());
entry.container.remove();
}
});
const INSTALL_URL = "https://example.com/install";
const UPDATE_URL = "https://example.com/update";
function mount(
state: ProviderInstallationState,
updates: ProviderUpdatesState = { status: "hidden" },
action?: ProviderUpdateAction,
) {
const container = document.createElement("div");
document.body.appendChild(container);
const root = createRoot(container);
act(() =>
root.render(<ProviderInstallationSection state={state} updates={updates} action={action} />),
);
mounted.push({ root, container });
const view = within(container);
return {
view,
rerender: (nextUpdates: ProviderUpdatesState, nextAction?: ProviderUpdateAction) =>
act(() =>
root.render(
<ProviderInstallationSection state={state} updates={nextUpdates} action={nextAction} />,
),
),
installButton: () => view.queryByRole("button", { name: "Install" }),
installLink: () => view.queryByRole("link", { name: "Install instructions" }),
};
}
function ready(installation: ProviderInstallationState & { status: "ready" }) {
return installation;
}
describe("install link visibility", () => {
it("offers the Install button when the provider reports it is not installed", () => {
const section = mount(
ready({
status: "ready",
installation: { installUrl: INSTALL_URL, inspection: { status: "not_installed" } },
}),
);
expect(section.installButton()).not.toBeNull();
expect(section.installLink()).toBeNull();
});
it("offers a quiet install link when the installation check failed", async () => {
const section = mount(
ready({
status: "ready",
installation: {
installUrl: INSTALL_URL,
inspection: { status: "error", message: "version probe exploded" },
},
}),
);
await expect.element(section.view.getByText("version probe exploded")).toBeVisible();
expect(section.installLink()).not.toBeNull();
expect(section.installButton()).toBeNull();
});
it("offers a quiet install link for a provider that only declares where to install it", () => {
const section = mount(ready({ status: "ready", installation: { installUrl: INSTALL_URL } }));
expect(section.installLink()).not.toBeNull();
expect(section.installButton()).toBeNull();
});
it("offers no install link once the provider reports it is installed", () => {
const section = mount(
ready({
status: "ready",
installation: {
installUrl: INSTALL_URL,
inspection: { status: "installed", version: "1" },
},
}),
);
expect(section.installLink()).toBeNull();
expect(section.installButton()).toBeNull();
});
});
describe("update check", () => {
const installed = ready({
status: "ready",
installation: {
installUrl: INSTALL_URL,
updateUrl: UPDATE_URL,
inspection: { status: "installed", version: "0.165.0" },
},
});
it("shows the reported versions and message as written, with Update instructions", async () => {
const section = mount(installed, {
status: "ready",
updateCheck: {
status: "available",
versions: ["0.168.0", "nightly (unstable)"],
message: "Restart to finish",
},
});
await expect.element(section.view.getByText("Update available")).toBeVisible();
expect(
section.view.getAllByTestId("provider-updates-version").map((node) => node.textContent),
).toEqual(["0.168.0", "nightly (unstable)"]);
await expect.element(section.view.getByText("Restart to finish")).toBeVisible();
await expect
.element(section.view.getByRole("button", { name: "Update instructions" }))
.toBeVisible();
});
const inconclusive = [
{
name: "unknown",
updates: { status: "ready", updateCheck: { status: "unknown", message: "Offline" } },
},
{
name: "a thrown or timed-out check",
updates: { status: "ready", updateCheck: { status: "error", message: "Offline" } },
},
{ name: "a failed request", updates: { status: "error", message: "Offline" } },
] as const;
it.each(inconclusive)("shows $name as inconclusive, never up to date", async ({ updates }) => {
const section = mount(installed, updates);
await expect.element(section.view.getByText("Couldn't check for updates")).toBeVisible();
await expect.element(section.view.getByText("Offline")).toBeVisible();
expect(section.view.queryByText("Up to date")).toBeNull();
await expect
.element(section.view.getByRole("button", { name: "Update instructions" }))
.toBeVisible();
});
it.each(inconclusive)(
"still says $name when the provider offers no update",
async ({ updates }) => {
const section = mount(
ready({
status: "ready",
installation: { inspection: { status: "installed", version: "0.165.0" } },
}),
updates,
);
await expect.element(section.view.getByText("Couldn't check for updates")).toBeVisible();
expect(section.view.queryByRole("button")).toBeNull();
},
);
it("shows up to date only when the provider says so", async () => {
const section = mount(installed, { status: "ready", updateCheck: { status: "current" } });
await expect.element(section.view.getByText("Up to date")).toBeVisible();
});
it("shows the check's answer for a provider that offers no update", async () => {
const section = mount(
ready({
status: "ready",
installation: { inspection: { status: "installed", version: "1.4.18" } },
}),
{ status: "ready", updateCheck: { status: "current" } },
);
await expect.element(section.view.getByText("Up to date")).toBeVisible();
expect(section.view.queryByRole("button")).toBeNull();
});
it.each([
{ name: "cannot check", updates: { status: "ready", updateCheck: null } },
{ name: "is still checking", updates: { status: "loading" } },
] as const)(
"shows no Updates row while a provider that offers no update $name",
({ updates }) => {
const section = mount(
ready({
status: "ready",
installation: {
installUrl: INSTALL_URL,
inspection: { status: "installed", version: "1.0.0" },
},
}),
updates,
);
expect(section.view.queryByTestId("provider-updates")).toBeNull();
expect(section.view.getByTestId("provider-installation-version").textContent).toBe("1.0.0");
},
);
});
describe("update action", () => {
const installed = (canUpdate: boolean) =>
ready({
status: "ready",
installation: {
updateUrl: UPDATE_URL,
inspection: { status: "installed", version: "1.0.0" },
...(canUpdate ? { canUpdate: true } : {}),
},
});
const available: ProviderUpdatesState = {
status: "ready",
updateCheck: { status: "available", versions: ["2.0.0"] },
};
function action(overrides: Partial<ProviderUpdateAction> = {}) {
let starts = 0;
const value: ProviderUpdateAction = {
current: null,
starting: false,
startError: null,
start: () => {
starts += 1;
},
...overrides,
};
return { value, starts: () => starts };
}
const operation = { id: "op", startedAt: "2026-11-13T00:00:00.000Z" };
const finishedAt = "2026-11-13T00:01:00.000Z";
// The check only informs: Update and the update instructions never wait on it.
const checkStates = [
{ name: "an update is available", updates: available, says: "Update available" },
// No check answer: the row shows only its title (asserted whole below).
{
name: "the provider cannot check",
updates: { status: "ready", updateCheck: null },
says: "Updates",
},
{ name: "the check is running", updates: { status: "loading" }, says: "Checking..." },
{
name: "the check could not tell",
updates: { status: "ready", updateCheck: { status: "unknown" } },
says: "Couldn't check for updates",
},
{
name: "the check failed",
updates: { status: "error", message: "Offline" },
says: "Couldn't check for updates",
},
{
name: "the provider is up to date",
updates: { status: "ready", updateCheck: { status: "current" } },
says: "Up to date",
},
] satisfies { name: string; updates: ProviderUpdatesState; says: string }[];
it.each(checkStates)(
"offers Update when $name and the provider runs its own",
async ({ updates, says }) => {
const control = action();
const section = mount(installed(true), updates, control.value);
const button = section.view.getByRole("button", { name: "Update" });
act(() => button.click());
expect(control.starts()).toBe(1);
expect(section.view.queryByRole("button", { name: "Update instructions" })).toBeNull();
await expect.element(section.view.getByText(says, { exact: true })).toBeVisible();
},
);
it.each(checkStates)(
"offers Update instructions when $name and the provider only links its guide",
async ({ updates }) => {
const section = mount(installed(false), updates, action().value);
expect(section.view.queryByRole("button", { name: "Update" })).toBeNull();
await expect
.element(section.view.getByRole("button", { name: "Update instructions" }))
.toBeVisible();
},
);
it("shows no update status beside Update when the provider cannot check", () => {
const section = mount(installed(true), { status: "ready", updateCheck: null }, action().value);
expect(section.view.getByTestId("provider-updates").textContent).toBe("UpdatesUpdate");
});
it("shows a running update with its output so far", () => {
const section = mount(
installed(true),
available,
action({
current: {
operation: { ...operation, status: "running" },
output: [
{ type: "message", text: "Running codex update\n" },
{ type: "stdout", text: "added 1 package\n" },
],
},
}).value,
);
expect(section.view.queryByTestId("provider-update-status")).toBeNull();
expect(section.view.getByTestId("provider-update-output").textContent).toBe(
"Running codex update\nadded 1 package\n",
);
});
it("shows the provider's success message as written", () => {
const section = mount(
installed(true),
{ status: "ready", updateCheck: { status: "current" } },
action({
current: {
operation: {
...operation,
status: "succeeded",
finishedAt,
message: " Restart agents \n",
},
output: [],
},
}).value,
);
expect(section.view.getByTestId("provider-update-status").textContent).toBe("Updated");
expect(section.view.getByTestId("provider-update-message").textContent).toBe(
" Restart agents \n",
);
expect(section.view.queryByTestId("provider-update-output")).toBeNull();
});
it("shows a failure with its message, its output and the update instructions", async () => {
const section = mount(
installed(true),
available,
action({
current: {
operation: { ...operation, status: "failed", finishedAt, message: "exited with code 1" },
output: [{ type: "stderr", text: "npm error EACCES\n" }],
truncated: true,
},
}).value,
);
expect(section.view.getByTestId("provider-update-status").textContent).toBe("Update failed");
await expect.element(section.view.getByText("exited with code 1")).toBeVisible();
expect(section.view.getByTestId("provider-update-output").textContent).toBe(
"npm error EACCES\n",
);
await expect.element(section.view.getByText("Earlier output was dropped.")).toBeVisible();
await expect
.element(section.view.getByRole("link", { name: "Update instructions" }))
.toBeVisible();
await expect.element(section.view.getByRole("button", { name: "Update" })).toBeVisible();
});
// Update carries the update's progress from the tap until it settles, like every in-flight
// button in Settings. The update's row shows only its output meanwhile.
describe("progress", () => {
const runningUpdate = (output: string[] = []) => ({
operation: { ...operation, status: "running" as const },
output: output.map((text) => ({ type: "stdout" as const, text })),
});
function progress(section: ReturnType<typeof mount>) {
const indicators = section.view.queryAllByRole("progressbar");
const button = section.view.queryByTestId("provider-update-start");
return {
count: indicators.length,
inButton: indicators.every((indicator) => button?.contains(indicator) ?? false),
label: button?.textContent,
pressable: button?.getAttribute("aria-disabled") !== "true",
};
}
const updating = { count: 1, inButton: true, label: "Updating...", pressable: false };
const idle = { count: 0, inButton: true, label: "Update", pressable: true };
it("shows progress on Update alone from tap to settle", () => {
const previous = {
operation: { ...operation, status: "failed" as const, finishedAt, message: "exit 1" },
output: [{ type: "stderr" as const, text: "old failure\n" }],
};
const section = mount(installed(true), available, action({ current: previous }).value);
expect(progress(section)).toEqual(idle);
// Tapped, the host has not answered yet: the previous result gives way to the new update.
section.rerender(available, action({ current: previous, starting: true }).value);
expect(progress(section)).toEqual(updating);
expect(section.view.queryByTestId("provider-update-run")).toBeNull();
// Running before any output arrives.
section.rerender(available, action({ current: runningUpdate() }).value);
expect(progress(section)).toEqual(updating);
expect(section.view.queryByTestId("provider-update-run")).toBeNull();
section.rerender(available, action({ current: runningUpdate(["downloading\n"]) }).value);
expect(progress(section)).toEqual(updating);
expect(section.view.getByTestId("provider-update-run").textContent).toBe("downloading\n");
section.rerender(
{ status: "ready", updateCheck: { status: "current" } },
action({
current: {
...runningUpdate(["downloading\n"]),
operation: { ...operation, status: "succeeded", finishedAt },
},
}).value,
);
expect(progress(section)).toEqual(idle);
expect(section.view.getByTestId("provider-update-status").textContent).toBe("Updated");
});
it("shows progress on Update when the sheet reopens mid-update", () => {
const section = mount(
installed(true),
available,
action({ current: runningUpdate(["downloading\n"]) }).value,
);
expect(progress(section)).toEqual(updating);
expect(section.view.queryByTestId("provider-update-status")).toBeNull();
});
it.each([
{ name: "still loading", state: { status: "loading" } },
{
name: "not installed",
state: { status: "ready", installation: { inspection: { status: "not_installed" } } },
},
{
name: "failing",
state: {
status: "ready",
installation: { inspection: { status: "error", message: "--version timed out" } },
},
},
{ name: "unreachable", state: { status: "error", message: "Host disconnected" } },
] satisfies { name: string; state: ProviderInstallationState }[])(
"shows progress on Update while the installation reads as $name",
({ state }) => {
const section = mount(
state,
{ status: "hidden" },
action({ current: runningUpdate() }).value,
);
// The inspection may show its own progress beside the Version row.
const button = section.view.getByRole("button", { name: "Updating..." });
expect(button.getAttribute("aria-disabled")).toBe("true");
expect(within(button).queryAllByRole("progressbar")).toHaveLength(1);
},
);
it("returns Update to rest when the host refuses the start", () => {
const section = mount(installed(true), available, action({ starting: true }).value);
expect(progress(section)).toEqual(updating);
section.rerender(available, action({ startError: "Busy" }).value);
expect(progress(section)).toEqual(idle);
expect(section.view.getByTestId("provider-update-status").textContent).toBe("Update failed");
});
});
it("shows why the host refused to start the update", async () => {
const section = mount(
installed(true),
available,
action({ startError: "Provider codex cannot update itself" }).value,
);
expect(section.view.getByTestId("provider-update-status").textContent).toBe("Update failed");
await expect
.element(section.view.getByText("Provider codex cannot update itself"))
.toBeVisible();
});
});
@@ -1,448 +0,0 @@
import { useCallback, useRef } from "react";
import { useTranslation } from "react-i18next";
import { ScrollView, Text, View } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import type {
ProviderInstallation,
ProviderInstallationUpdate,
ProviderInstallationUpdateCheck,
} from "@getpaseo/protocol/messages";
import { Button } from "@/components/ui/button";
import { ExternalLink } from "@/components/ui/external-link";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { CODE_SURFACE_DATASET } from "@/styles/code-surface";
import { settingsStyles } from "@/styles/settings";
import type { Theme } from "@/styles/theme";
import { openExternalUrl } from "@/utils/open-external-url";
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
const foregroundMutedColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
export type ProviderInstallationState =
| { status: "unsupported" }
| { status: "loading" }
| { status: "ready"; installation: ProviderInstallation | null }
| { status: "error"; message: string };
/**
* What the provider's update check knows. `hidden` until the provider is installed. A null
* `updateCheck` means the provider cannot check; the check only informs, and never gates Update.
*/
export type ProviderUpdatesState =
| { status: "hidden" }
| { status: "loading" }
| { status: "ready"; updateCheck: ProviderInstallationUpdateCheck | null }
| { status: "error"; message: string };
/** Running the provider's own update. Absent when the host cannot report updates. */
export interface ProviderUpdateAction {
/** The provider's latest update since the host started, or null. */
current: ProviderInstallationUpdate | null;
/** The request to start an update is in flight. */
starting: boolean;
/** Why the host did not start the update. */
startError: string | null;
start(): void;
}
export function ProviderInstallationSection({
state,
updates,
action,
}: {
state: ProviderInstallationState;
updates: ProviderUpdatesState;
action?: ProviderUpdateAction;
}) {
const { t } = useTranslation();
if (state.status === "unsupported") return null;
if (
state.status === "ready" &&
!state.installation?.inspection &&
!state.installation?.installUrl
)
return null;
const installation = state.status === "ready" ? state.installation : null;
const run = action ? readUpdateRun(action) : null;
// A running update keeps its row, so Update shows its progress whatever the inspection reads
// meanwhile; the binary may be mid-replacement.
const updating = action ? isUpdating(action) : false;
return (
<View style={settingsStyles.section} testID="provider-installation">
<View style={settingsStyles.sectionHeader}>
<Text style={settingsStyles.sectionHeaderTitle}>
{t("settings.providers.installation.title")}
</Text>
</View>
<View style={settingsStyles.card}>
<InstallationRow state={state} />
{installation?.inspection?.status === "installed" || updating ? (
<UpdatesRow
updates={updates}
updateUrl={installation?.updateUrl}
action={updating || installation?.canUpdate ? action : undefined}
/>
) : null}
{run ? <UpdateRunRow run={run} updateUrl={installation?.updateUrl} /> : null}
</View>
</View>
);
}
function InstallInstructionsLink({ installUrl }: { installUrl: string }) {
const { t } = useTranslation();
return (
<ExternalLink
href={installUrl}
label={t("settings.providers.installation.installInstructions")}
testID="provider-installation-install-instructions"
/>
);
}
function InstallationRow({ state }: { state: ProviderInstallationState }) {
const { t } = useTranslation();
const installation = state.status === "ready" ? state.installation : null;
const installUrl = installation?.installUrl;
const handleInstall = useCallback(() => {
if (installUrl) void openExternalUrl(installUrl);
}, [installUrl]);
if (state.status === "loading") {
return (
<View style={settingsStyles.row}>
<Text style={settingsStyles.rowTitle}>{t("settings.providers.installation.version")}</Text>
<View style={styles.trailing}>
<ThemedLoadingSpinner size="small" uniProps={foregroundMutedColorMapping} />
<Text style={styles.value}>{t("settings.providers.installation.checking")}</Text>
</View>
</View>
);
}
const inspection = installation?.inspection;
if (inspection?.status === "not_installed") {
return (
<View style={settingsStyles.row}>
<Text style={settingsStyles.rowTitle}>
{t("settings.providers.installation.notInstalled")}
</Text>
{installUrl ? (
<Button variant="outline" onPress={handleInstall}>
{t("settings.providers.installation.install")}
</Button>
) : null}
</View>
);
}
if (inspection?.status === "installed") {
return (
<View style={settingsStyles.row}>
<Text style={settingsStyles.rowTitle}>{t("settings.providers.installation.version")}</Text>
{inspection.version ? (
<Text
style={styles.version}
numberOfLines={1}
selectable
dataSet={CODE_SURFACE_DATASET}
testID="provider-installation-version"
>
{inspection.version}
</Text>
) : (
<Text style={styles.value}>{t("settings.providers.installation.installed")}</Text>
)}
</View>
);
}
// The installed state is unknown: the check failed, or the provider only links to a guide.
let message: string | null = null;
if (state.status === "error") message = state.message;
else if (inspection?.status === "error") message = inspection.message;
if (!message) {
return installUrl ? (
<View style={settingsStyles.row}>
<InstallInstructionsLink installUrl={installUrl} />
</View>
) : null;
}
return (
<View style={settingsStyles.row}>
<View style={settingsStyles.rowContent}>
<Text style={settingsStyles.rowTitle}>{t("settings.providers.installation.failed")}</Text>
<Text style={settingsStyles.rowHint}>{message}</Text>
{installUrl ? (
<View style={styles.link}>
<InstallInstructionsLink installUrl={installUrl} />
</View>
) : null}
</View>
</View>
);
}
/**
* The update the provider offers, with what its check knows beside it. Update, or the update
* instructions, stay in place whatever the check says: an answer can be an hour old, and the
* provider's own updater reports when there is nothing newer.
*/
function UpdatesRow({
updates,
updateUrl,
action,
}: {
updates: ProviderUpdatesState;
updateUrl: string | undefined;
/** Present when the provider runs its own update. */
action: ProviderUpdateAction | undefined;
}) {
const { t } = useTranslation();
const updateCheck = updates.status === "ready" ? updates.updateCheck : null;
const offersUpdate = Boolean(action || updateUrl);
// With nothing to offer, the row waits until the check has something to say.
if (!offersUpdate && !updateCheck && updates.status !== "error") return null;
return (
<View style={[settingsStyles.row, settingsStyles.rowBorder]} testID="provider-updates">
<View style={settingsStyles.rowContent}>
<Text style={settingsStyles.rowTitle}>
{updateCheck?.status === "available"
? t("settings.providers.installation.updateAvailable")
: t("settings.providers.installation.updates")}
</Text>
<UpdateCheckSummary updates={updates} />
</View>
<UpdateButton action={action} updateUrl={updateUrl} />
</View>
);
}
function UpdateCheckSummary({ updates }: { updates: ProviderUpdatesState }) {
const { t } = useTranslation();
if (updates.status === "loading") {
return (
<View style={styles.trailing}>
<ThemedLoadingSpinner size="small" uniProps={foregroundMutedColorMapping} />
<Text style={settingsStyles.rowHint}>{t("settings.providers.installation.checking")}</Text>
</View>
);
}
if (updates.status === "hidden") return null;
const updateCheck = updates.status === "ready" ? updates.updateCheck : null;
if (updates.status === "ready" && !updateCheck) return null;
if (updateCheck?.status === "current") {
return (
<Text style={settingsStyles.rowHint} testID="provider-updates-current">
{t("settings.providers.installation.upToDate")}
</Text>
);
}
if (updateCheck?.status === "available") {
// Versions are opaque; drop repeats so each one keys its own line.
const versions = [...new Set(updateCheck.versions ?? [])];
return (
<>
{versions.map((version) => (
<Text
key={version}
style={styles.availableVersion}
selectable
dataSet={CODE_SURFACE_DATASET}
testID="provider-updates-version"
>
{version}
</Text>
))}
{updateCheck.message ? (
<Text style={settingsStyles.rowHint}>{updateCheck.message}</Text>
) : null}
</>
);
}
// A check that threw, timed out or could not tell is never shown as up to date.
const message = updates.status === "error" ? updates.message : updateCheck?.message;
return (
<>
<Text style={settingsStyles.rowHint} testID="provider-updates-unchecked">
{t("settings.providers.installation.updatesFailed")}
</Text>
{message ? <Text style={settingsStyles.rowHint}>{message}</Text> : null}
</>
);
}
function isUpdating(action: ProviderUpdateAction): boolean {
return action.starting || action.current?.operation.status === "running";
}
/**
* Update runs the provider's updater; without one, the provider's update guide opens. The button
* carries the update's progress from the tap until it settles.
*/
function UpdateButton({
action,
updateUrl,
}: {
action: ProviderUpdateAction | undefined;
updateUrl: string | undefined;
}) {
const { t } = useTranslation();
const handleOpenInstructions = useCallback(() => {
if (updateUrl) void openExternalUrl(updateUrl);
}, [updateUrl]);
if (action)
return (
<Button
variant="outline"
onPress={action.start}
loading={isUpdating(action)}
testID="provider-update-start"
>
{isUpdating(action)
? t("settings.providers.installation.updating")
: t("settings.providers.installation.update")}
</Button>
);
if (!updateUrl) return null;
return (
<Button variant="outline" onPress={handleOpenInstructions}>
{t("settings.providers.installation.updateInstructions")}
</Button>
);
}
type UpdateRun =
| { status: "running"; update: ProviderInstallationUpdate }
| { status: "succeeded" | "failed"; update: ProviderInstallationUpdate }
| { status: "refused"; message: string };
/**
* What the update's row shows, or null for nothing. While the update starts or runs, Update shows
* its progress and the row holds only the output so far. A new start clears the previous result.
*/
function readUpdateRun(action: ProviderUpdateAction): UpdateRun | null {
const update = action.current;
if (isUpdating(action)) {
return update?.operation.status === "running" && update.output.length > 0
? { status: "running", update }
: null;
}
if (action.startError) return { status: "refused", message: action.startError };
if (!update || update.operation.status === "running") return null;
return { status: update.operation.status, update };
}
function UpdateRunRow({ run, updateUrl }: { run: UpdateRun; updateUrl: string | undefined }) {
const { t } = useTranslation();
const scroll = useRef<ScrollView>(null);
const followOutput = useCallback(() => scroll.current?.scrollToEnd({ animated: false }), []);
const update = run.status === "refused" ? null : run.update;
const output = update?.output.map((entry) => entry.text).join("") ?? "";
let message: string | undefined;
if (run.status === "refused") message = run.message;
else if (run.update.operation.status !== "running") message = run.update.operation.message;
return (
<View style={[settingsStyles.row, settingsStyles.rowBorder]} testID="provider-update-run">
<View style={settingsStyles.rowContent}>
{run.status === "running" ? null : (
<Text style={settingsStyles.rowTitle} testID="provider-update-status">
{run.status === "succeeded"
? t("settings.providers.installation.updated")
: t("settings.providers.installation.updateFailed")}
</Text>
)}
{message ? (
<Text style={settingsStyles.rowHint} selectable testID="provider-update-message">
{message}
</Text>
) : null}
{output ? (
<ScrollView
ref={scroll}
style={
run.status === "running" ? styles.output : [styles.output, styles.outputAfterResult]
}
contentContainerStyle={styles.outputContent}
onContentSizeChange={followOutput}
// Android scrolls a ScrollView nested in the provider sheet only with this flag.
nestedScrollEnabled
>
{update?.truncated ? (
<Text style={styles.outputNote}>
{t("settings.providers.installation.outputTruncated")}
</Text>
) : null}
<Text
style={styles.outputText}
selectable
dataSet={CODE_SURFACE_DATASET}
testID="provider-update-output"
>
{output}
</Text>
</ScrollView>
) : null}
{(run.status === "failed" || run.status === "refused") && updateUrl ? (
<View style={styles.link}>
<ExternalLink
href={updateUrl}
label={t("settings.providers.installation.updateInstructions")}
/>
</View>
) : null}
</View>
</View>
);
}
const styles = StyleSheet.create((theme) => ({
output: {
maxHeight: 240,
borderRadius: theme.borderRadius.md,
backgroundColor: theme.colors.surface0,
},
outputAfterResult: {
marginTop: theme.spacing[2],
},
outputContent: {
padding: theme.spacing[3],
},
outputText: {
fontFamily: theme.fontFamily.mono,
fontSize: theme.fontSize.code,
lineHeight: 20,
color: theme.colors.foreground,
},
outputNote: {
marginBottom: theme.spacing[1],
fontSize: theme.fontSize.sm,
color: theme.colors.foregroundMuted,
},
trailing: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
},
value: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
},
version: {
flexShrink: 1,
marginLeft: theme.spacing[3],
fontFamily: theme.fontFamily.mono,
fontSize: theme.fontSize.code,
color: theme.colors.foregroundMuted,
},
availableVersion: {
marginTop: theme.spacing[1],
fontFamily: theme.fontFamily.mono,
fontSize: theme.fontSize.code,
color: theme.colors.foregroundMuted,
},
link: {
flexDirection: "row",
marginTop: theme.spacing[1],
},
}));
@@ -1,195 +0,0 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import type { ProviderInstallationUpdate } from "@getpaseo/protocol/messages";
import { useFetchQuery } from "@/data/query";
import { useHostFeature } from "@/runtime/host-features";
import { useHostRuntimeClient } from "@/runtime/host-runtime";
import type {
ProviderInstallationState,
ProviderUpdateAction,
ProviderUpdatesState,
} from "./provider-installation-section";
import { applyProviderUpdateProgress } from "./provider-update-progress";
export interface ProviderInstallationRead {
state: ProviderInstallationState;
updates: ProviderUpdatesState;
/** Absent when the host cannot report provider installations. */
action: ProviderUpdateAction | undefined;
/** Ask the provider again, skipping the host's caches. */
refresh: () => void;
/** A refresh is in flight. The last answers stay on screen until the new ones arrive. */
refreshing: boolean;
}
/**
* Reads a provider's installation from hosts that advertise `providerInstallation`. The update
* check is a separate request that starts once the provider reports itself installed, so the
* installed version never waits on it.
*/
export function useProviderInstallation(input: {
serverId: string;
provider: string;
visible: boolean;
}): ProviderInstallationRead {
const { serverId, provider, visible } = input;
const supported = useHostFeature(serverId, "providerInstallation");
const client = useHostRuntimeClient(serverId);
const queryClient = useQueryClient();
const { t } = useTranslation();
const enabled = supported && visible && Boolean(client);
const installationKey = ["provider-installation", serverId, provider] as const;
const updatesKey = ["provider-updates", serverId, provider] as const;
const inspect = useCallback(
async (refresh: boolean) => {
if (!client) throw new Error(t("workspace.terminal.hostDisconnected"));
const result = await client.inspectProviderInstallation(provider, { refresh });
if (result.error) throw new Error(result.error);
return result.installation;
},
[client, provider, t],
);
const checkForUpdates = useCallback(
async (refresh: boolean) => {
if (!client) throw new Error(t("workspace.terminal.hostDisconnected"));
const result = await client.checkProviderUpdates(provider, { refresh });
if (result.error) throw new Error(result.error);
return result.updateCheck;
},
[client, provider, t],
);
// The host caches both answers, so reading on every open is cheap.
const installationQuery = useFetchQuery({
queryKey: installationKey,
queryFn: () => inspect(false),
enabled,
dataShape: "value",
staleTimeMs: 0,
});
const installed = installationQuery.data?.inspection?.status === "installed";
const updatesQuery = useFetchQuery({
queryKey: updatesKey,
queryFn: () => checkForUpdates(false),
enabled: enabled && installed,
dataShape: "value",
staleTimeMs: 0,
});
// A refresh runs through the queries so its answer or its failure is what the screen shows.
// `staleTime: 0` overrides the app default so the request always goes out.
const refreshInstallation = useMutation({
mutationFn: () =>
queryClient.fetchQuery({
queryKey: installationKey,
queryFn: () => inspect(true),
staleTime: 0,
}),
});
const refreshUpdates = useMutation({
mutationFn: () =>
queryClient.fetchQuery({
queryKey: updatesKey,
queryFn: () => checkForUpdates(true),
staleTime: 0,
}),
});
// The host owns the update; this view follows it while open and catches up on reopen.
const [currentUpdate, setCurrentUpdate] = useState<ProviderInstallationUpdate | null>(null);
useEffect(() => {
if (!enabled || !client) return;
const subscription = client.observeProviderUpdates(provider);
// The update this view saw running. Its success arrives as live progress, or as the snapshot
// a reconnect delivers when the progress was missed; either way the host dropped its cached
// answers, so read the new version and update state.
let runningId: string | null = null;
const follow = (operation: ProviderInstallationUpdate["operation"] | undefined) => {
if (!operation) return;
if (operation.status === "running") {
runningId = operation.id;
return;
}
if (operation.id !== runningId) return;
runningId = null;
if (operation.status !== "succeeded") return;
void queryClient.invalidateQueries({
queryKey: ["provider-installation", serverId, provider],
});
void queryClient.invalidateQueries({ queryKey: ["provider-updates", serverId, provider] });
};
const detach = subscription.subscribe({
snapshot: (response) => {
setCurrentUpdate(response.update);
follow(response.update?.operation);
},
update: (message) => {
if (message.type === "provider.installation.update.cleared") {
const { operationId } = message.payload;
setCurrentUpdate((current) => (current?.operation.id === operationId ? null : current));
return;
}
if (message.type !== "provider.installation.update.progress") return;
setCurrentUpdate((current) => applyProviderUpdateProgress(current, message.payload));
follow(message.payload.operation);
},
error: (failure) => console.warn("Failed to observe provider updates", failure),
});
return () => {
detach();
void subscription
.release()
.catch((failure) => console.warn("Failed to release provider update observation", failure));
};
}, [client, enabled, provider, queryClient, serverId]);
const startUpdate = useMutation({
mutationFn: async () => {
if (!client) throw new Error(t("workspace.terminal.hostDisconnected"));
const result = await client.updateProvider(provider);
if (result.error) throw new Error(result.error);
return result.update;
},
onSuccess: (update) => {
if (!update) return;
// Progress for this operation may already have arrived; keep the further-along copy.
setCurrentUpdate((current) =>
current?.operation.id === update.operation.id ? current : update,
);
},
});
const { mutate: mutateStartUpdate } = startUpdate;
const start = useCallback(() => mutateStartUpdate(), [mutateStartUpdate]);
const action: ProviderUpdateAction | undefined = supported
? {
current: currentUpdate,
starting: startUpdate.isPending,
startError: startUpdate.error?.message ?? null,
start,
}
: undefined;
const { mutate: mutateInstallation } = refreshInstallation;
const { mutate: mutateUpdates } = refreshUpdates;
const refresh = useCallback(() => {
if (!supported || !client) return;
mutateInstallation();
if (installed) mutateUpdates();
}, [client, installed, mutateInstallation, mutateUpdates, supported]);
let state: ProviderInstallationState;
if (!supported) state = { status: "unsupported" };
else if (installationQuery.isPending) state = { status: "loading" };
else if (installationQuery.isError)
state = { status: "error", message: installationQuery.error.message };
else state = { status: "ready", installation: installationQuery.data ?? null };
let updates: ProviderUpdatesState;
if (!supported || !installed) updates = { status: "hidden" };
else if (updatesQuery.isPending) updates = { status: "loading" };
else if (updatesQuery.isError) updates = { status: "error", message: updatesQuery.error.message };
else updates = { status: "ready", updateCheck: updatesQuery.data ?? null };
const refreshing = refreshInstallation.isPending || refreshUpdates.isPending;
return { state, updates, action, refresh, refreshing };
}
@@ -1,5 +1,5 @@
import { useCallback } from "react";
import { ProviderDetailSheet } from "@/provider-settings";
import { ProviderDiagnosticSheet } from "@/components/provider-diagnostic-sheet";
import { OverlayLayerProvider } from "@/lib/overlay-root";
import { useProviderSettingsStore } from "@/stores/provider-settings-store";
@@ -20,7 +20,7 @@ export function ProviderSettingsHost() {
return (
<OverlayLayerProvider layer={overlayParentLayer}>
<ProviderDetailSheet
<ProviderDiagnosticSheet
key={`${serverId}:${provider}`}
provider={provider}
serverId={serverId}
@@ -1,48 +0,0 @@
import { describe, expect, it } from "vitest";
import type { ProviderInstallationUpdateProgress } from "@getpaseo/protocol/messages";
import { applyProviderUpdateProgress } from "./provider-update-progress";
const running = {
status: "running",
id: "update-1",
startedAt: "2026-11-13T00:00:00.000Z",
} as const;
function progress(...texts: string[]): ProviderInstallationUpdateProgress {
return {
provider: "codex",
operation: running,
output: texts.map((text) => ({ type: "stdout", text })),
};
}
describe("applyProviderUpdateProgress", () => {
it("appends output for the same update", () => {
const first = applyProviderUpdateProgress(null, progress("a"), { outputLimit: 10 });
const second = applyProviderUpdateProgress(first, progress("b"), { outputLimit: 10 });
expect(second.output.map((entry) => entry.text)).toEqual(["a", "b"]);
expect(second.truncated).toBeUndefined();
});
it("drops the oldest output beyond the limit and marks the update truncated", () => {
let update = applyProviderUpdateProgress(null, progress("12345"), { outputLimit: 8 });
update = applyProviderUpdateProgress(update, progress("6789"), { outputLimit: 8 });
expect(update.output.map((entry) => entry.text)).toEqual(["6789"]);
expect(update.truncated).toBe(true);
update = applyProviderUpdateProgress(update, progress("abcdefghij"), { outputLimit: 8 });
expect(update.output.map((entry) => entry.text)).toEqual(["cdefghij"]);
expect(update.truncated).toBe(true);
});
it("starts a new update empty", () => {
const first = applyProviderUpdateProgress(null, progress("123456789"), { outputLimit: 4 });
const next = applyProviderUpdateProgress(
first,
{ ...progress("x"), operation: { ...running, id: "update-2" } },
{ outputLimit: 4 },
);
expect(next.output.map((entry) => entry.text)).toEqual(["x"]);
expect(next.truncated).toBeUndefined();
});
});
@@ -1,38 +0,0 @@
import type {
ProviderInstallationUpdate,
ProviderInstallationUpdateOutput,
ProviderInstallationUpdateProgress,
} from "@getpaseo/protocol/messages";
/** Characters of update output the app keeps, matching what the daemon retains. */
export const PROVIDER_UPDATE_OUTPUT_LIMIT = 64 * 1024;
/**
* Folds a progress message into the update it belongs to; a new operation starts empty. Output
* beyond `outputLimit` characters drops oldest first and marks the update truncated, so a noisy
* updater cannot grow the screen's memory while it stays open.
*/
export function applyProviderUpdateProgress(
current: ProviderInstallationUpdate | null,
progress: ProviderInstallationUpdateProgress,
options: { outputLimit: number } = { outputLimit: PROVIDER_UPDATE_OUTPUT_LIMIT },
): ProviderInstallationUpdate {
const previous = current?.operation.id === progress.operation.id ? current : null;
const limit = options.outputLimit;
const output: ProviderInstallationUpdateOutput[] = [
...(previous?.output ?? []),
...progress.output,
];
let length = output.reduce((total, entry) => total + entry.text.length, 0);
let truncated = previous?.truncated ?? false;
while (length > limit && output.length > 1) {
length -= output.shift()!.text.length;
truncated = true;
}
const last = output.at(-1);
if (last && last.text.length > limit) {
output[output.length - 1] = { type: last.type, text: last.text.slice(-limit) };
truncated = true;
}
return { operation: progress.operation, output, ...(truncated ? { truncated: true } : {}) };
}
@@ -1,60 +0,0 @@
import { Plus } from "lucide-react-native";
import { useCallback } from "react";
import { Text, View, type PressableStateCallbackType } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { mutedIconColorMapping } from "@/components/ui/icon-color";
import { PressHighlight } from "@/components/ui/press-highlight";
import { ICON_SIZE } from "@/styles/theme";
import { useSettingsRowLayout } from "./row-density";
const ThemedPlus = withUnistyles(Plus);
type HoverState = PressableStateCallbackType & { hovered?: boolean };
/**
* The last row of a card that lists things, adding one more. Quiet, so the list reads first: a
* muted plus in the rows' leading slot and a muted label on the labels' rail.
*/
export function SettingsAddRow({
label,
onPress,
testID,
}: {
label: string;
onPress: () => void;
testID?: string;
}) {
const layout = useSettingsRowLayout();
const rowStyle = useCallback(
({ hovered, pressed }: HoverState) => [
layout.row,
styles.row,
hovered && styles.hovered,
pressed && styles.pressed,
],
[layout],
);
return (
<PressHighlight
accessibilityRole="button"
accessibilityLabel={label}
onPress={onPress}
style={rowStyle}
highlightStyle={styles.pressed}
testID={testID}
>
<View style={styles.leading}>
<ThemedPlus size={ICON_SIZE.md} uniProps={mutedIconColorMapping} />
</View>
<Text style={[layout.title, styles.label]}>{label}</Text>
</PressHighlight>
);
}
const styles = StyleSheet.create((theme) => ({
row: { justifyContent: "flex-start" },
leading: { marginRight: theme.spacing[3], alignItems: "center", justifyContent: "center" },
label: { color: theme.colors.foregroundMuted },
hovered: { backgroundColor: theme.colors.surface2 },
pressed: { backgroundColor: theme.colors.surface3 },
}));
@@ -1,86 +0,0 @@
import { ArrowLeft } from "lucide-react-native";
import type { ReactNode } from "react";
import { Text, View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { Button } from "@/components/ui/button";
/**
* "Back to …" above a settings detail page on wide layouts, where the page has no header of its
* own. The ghost button drops its padding so the arrow sits on the content's leading rail.
*/
export function SettingsBackLink({
label,
onPress,
testID,
}: {
label: string;
onPress: () => void;
testID?: string;
}) {
return (
<Button
testID={testID}
accessibilityLabel={label}
onPress={onPress}
variant="ghost"
leftIcon={ArrowLeft}
style={styles.backLink}
>
{label}
</Button>
);
}
/**
* The top of a settings detail page: "Back to …" when the page has no header of its own, then the
* icon and name the page is about, with an optional action after the name.
*/
export function SettingsDetailHeader({
back,
icon,
title,
trailing,
titleTestID,
}: {
back?: { label: string; onPress: () => void; testID?: string };
icon: ReactNode;
title: string;
trailing?: ReactNode;
titleTestID?: string;
}) {
return (
<View style={styles.header}>
{back ? <SettingsBackLink {...back} /> : null}
<View style={styles.titleRow}>
{icon}
<Text style={styles.title} numberOfLines={1} testID={titleTestID}>
{title}
</Text>
{trailing}
</View>
</View>
);
}
const styles = StyleSheet.create((theme) => ({
backLink: {
alignSelf: "flex-start",
paddingHorizontal: 0,
},
header: {
gap: theme.spacing[2],
marginBottom: theme.spacing[4],
},
titleRow: {
marginTop: theme.spacing[2],
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[3],
},
title: {
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
fontWeight: theme.fontWeight.medium,
flexShrink: 1,
},
}));
@@ -1,16 +1,12 @@
import type { ReactNode } from "react";
import { SettingsRowHeader, type SettingsRowHintStatus } from "./row-header";
import { SettingsRowHeader } from "./row-header";
interface SettingsDetailRowProps {
label: string;
/** An icon before the label, such as the thing the row opens. */
leading?: ReactNode;
/** Shown beside the label, such as a badge. */
labelAccessory?: ReactNode;
/** A line under the label saying what the row leads to. */
hint?: string;
/** Marks the hint as work under way, a fault, or a value still loading. */
hintStatus?: SettingsRowHintStatus;
/** What the detail is set to, so the row says it without being opened. */
summary?: string;
onPress: () => void;
@@ -18,10 +14,6 @@ interface SettingsDetailRowProps {
disabled?: boolean;
/** Opens a page outside the app; an outward arrow replaces the chevron. */
external?: boolean;
/** A control acting on the row's subject in place, such as a switch, before the chevron. */
control?: ReactNode;
/** Names the row for assistive tech when the label alone does not say where it leads. */
accessibilityLabel?: string;
testID?: string;
}
+1 -12
View File
@@ -30,17 +30,12 @@ export { SettingsGroup } from "./headings/settings-group";
export { SettingsSection } from "./headings/settings-section";
export { SettingsCollapsibleRow } from "./collapsible-row";
export { SettingsDetailRow } from "./detail-row";
export type { SettingsRowHintStatus } from "./row-header";
export { SettingsAddRow } from "./add-row";
export { SettingsBackLink, SettingsDetailHeader } from "./detail-header";
export { SettingsInfoTip } from "./headings/settings-info-tip";
export { MenuSettingsRows } from "./row-density";
/** What app screens can add to a plugin-facing row: an accessory beside the label, such as an info tip. */
interface AppRowExtras {
labelAccessory?: ReactNode;
/** An icon before the label, such as the thing the row is about. */
leading?: ReactNode;
}
interface AppSettingsRowProps extends Omit<SettingsRowProps, "hint">, AppRowExtras {
@@ -64,7 +59,6 @@ export function SettingsCard({ children, testID }: { children: ReactNode; testID
export function SettingsRow({
label,
leading,
labelAccessory,
hint,
error,
@@ -77,7 +71,6 @@ export function SettingsRow({
const accessoryTitleStyle = useMemo(() => [layout.title, styles.accessoryLabel], [layout]);
return (
<View style={rowStyle} testID={testID}>
{leading ? <View style={styles.leading}>{leading}</View> : null}
<View style={styles.label}>
{labelAccessory ? (
<View style={styles.labelRow}>
@@ -215,11 +208,7 @@ export function SettingsAction({ actionLabel, onPress, disabled, ...row }: Setti
}
const styles = StyleSheet.create((theme) => ({
// A control that wraps under the label gets space above it. Across the row, the leading slot and
// the label already carry their own margins, so a column gap would double them.
compactRow: { flexWrap: "wrap", rowGap: theme.spacing[3] },
// The same leading slot as `SettingsRowHeader`, so icons and labels share rails across row kinds.
leading: { marginRight: theme.spacing[3], alignItems: "center", justifyContent: "center" },
compactRow: { flexWrap: "wrap", gap: theme.spacing[3] },
label: { flexGrow: 1, flexShrink: 1, flexBasis: 160, marginRight: theme.spacing[3] },
labelRow: {
flexDirection: "row",
@@ -2,12 +2,7 @@ import React, { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, describe, expect, it } from "vitest";
import { Button } from "@/components/ui/button";
import {
SettingsCard,
SettingsCollapsibleRow,
SettingsDetailRow,
SettingsRow,
} from "@/components/settings";
import { SettingsCard, SettingsCollapsibleRow, SettingsRow } from "@/components/settings";
let root: Root | null = null;
let container: HTMLDivElement | null = null;
@@ -19,8 +14,6 @@ afterEach(() => {
container = null;
});
function openNothing() {}
function mountRows() {
container = document.createElement("div");
document.body.appendChild(container);
@@ -33,7 +26,6 @@ function mountRows() {
Download
</Button>
</SettingsRow>
<SettingsDetailRow label="Opens a page" onPress={openNothing} testID="detail-row" />
<SettingsCollapsibleRow label="Group" defaultExpanded testID="group">
<SettingsRow label="Nested with a button" testID="nested-with-button">
<Button variant="outline" testID="nested-button">
@@ -74,13 +66,6 @@ describe("settings row density", () => {
expect(heightOf("group-toggle")).toBeGreaterThan(heightOf("nested-without-button"));
});
it("keeps a row that opens something as tall as a row holding a control", () => {
mountRows();
expect(heightOf("detail-row")).toBe(heightOf("card-row"));
expect(heightOf("group-toggle")).toBe(heightOf("card-row"));
});
it("sizes nested text and controls one step below card rows", () => {
mountRows();
@@ -27,11 +27,6 @@ export function MenuSettingsRows({ children }: { children: ReactNode }) {
export interface SettingsRowLayout {
row: StyleProp<ViewStyle>;
/**
* A row as tall as one holding a control of `controlSize`, whether or not it holds one. In a menu
* it keeps the menu's row height.
*/
controlRow: StyleProp<ViewStyle>;
title: StyleProp<TextStyle>;
hint: StyleProp<TextStyle>;
/** The size of the controls in the row's trailing slot. */
@@ -43,7 +38,6 @@ function layoutFor(placement: RowPlacement): SettingsRowLayout {
case "nested":
return {
row: [settingsStyles.row, styles.nestedRow],
controlRow: [settingsStyles.row, styles.nestedRow],
title: [settingsStyles.rowTitle, styles.nestedText],
hint: [settingsStyles.rowHint, styles.nestedText],
controlSize: "sm",
@@ -51,7 +45,6 @@ function layoutFor(placement: RowPlacement): SettingsRowLayout {
case "menu":
return {
row: [settingsStyles.row, styles.menuRow],
controlRow: [settingsStyles.row, styles.menuRow],
title: settingsStyles.rowTitle,
hint: settingsStyles.rowHint,
controlSize: "md",
@@ -59,7 +52,6 @@ function layoutFor(placement: RowPlacement): SettingsRowLayout {
case "card":
return {
row: settingsStyles.row,
controlRow: [settingsStyles.row, styles.cardControlRow],
title: settingsStyles.rowTitle,
hint: settingsStyles.rowHint,
controlSize: "md",
@@ -74,9 +66,6 @@ export function useSettingsRowLayout(): SettingsRowLayout {
}
const styles = StyleSheet.create((theme) => ({
cardControlRow: {
minHeight: mapLayout(CONTROL_HEIGHTS.md, (height) => height + theme.spacing[4] * 2),
},
// Every nested row is as tall as one holding an `sm` control, so rows with and without a
// trailing button line up.
nestedRow: {
@@ -1,36 +1,25 @@
import { ChevronRight } from "lucide-react-native";
import { useCallback, useMemo, useState, type ReactNode } from "react";
import { Text, View, type AccessibilityState } from "react-native";
import { useCallback, useMemo, type ReactNode } from "react";
import { Text, View, type AccessibilityState, type PressableStateCallbackType } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { ControlSizeProvider } from "@/components/ui/control-size";
import { ExternalLinkLabel } from "@/components/ui/external-link";
import { mutedIconColorMapping } from "@/components/ui/icon-color";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { PressHighlight } from "@/components/ui/press-highlight";
import { SkeletonPulse, useSkeletonPulse } from "@/components/ui/skeleton";
import { settingsStyles } from "@/styles/settings";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import { useSettingsRowLayout, type SettingsRowLayout } from "./row-density";
import { useSettingsRowLayout } from "./row-density";
const ThemedChevron = withUnistyles(ChevronRight);
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
const hoveredIconColorMapping = (theme: Theme) => ({ color: theme.colors.foreground });
/**
* What the hint reports beyond its words: work under way (a leading spinner), a fault (a leading
* red dot and red text), or a value still loading (a placeholder the height of the line).
*/
export type SettingsRowHintStatus = "busy" | "error" | "pending";
type HoverState = PressableStateCallbackType & { hovered?: boolean };
export interface SettingsRowHeaderProps {
label: string;
/** An icon before the label, such as the thing the row opens. */
leading?: ReactNode;
/** Shown beside the label, such as a badge. */
labelAccessory?: ReactNode;
/** A line under the label saying what the row leads to. */
hint?: string;
hintStatus?: SettingsRowHintStatus;
/** A short status shown before the chevron. */
summary?: string;
onPress: () => void;
@@ -39,10 +28,6 @@ export interface SettingsRowHeaderProps {
expanded?: boolean;
/** The row leaves the app, such as to a docs page: the summary and an outward arrow are drawn as an external link in place of the chevron. */
external?: boolean;
/** A control acting on the row's subject in place, such as a switch, before the chevron. */
control?: ReactNode;
/** Names the row for assistive tech when the label alone does not say where it leads. */
accessibilityLabel?: string;
accessibilityState?: AccessibilityState;
/** Props React Native Web does not derive from `accessibilityState`, such as `aria-expanded`. */
webAccessibilityProps?: Record<string, unknown> | null;
@@ -53,209 +38,81 @@ export interface SettingsRowHeaderProps {
* The pressable line shared by settings rows that lead somewhere: a label, an optional summary and
* a trailing chevron. A collapsible row turns the chevron down; a row that opens a sheet keeps it
* pointing right.
*
* The press target is a button laid under the row's content rather than wrapped around it, so a
* control in the row is the button's sibling: a switch inside a button is invalid markup, and keys
* pressed on the switch would also press the row. Everything drawn over the button lets presses
* through to it. The label, icon and summary stay out of the accessibility tree, where the button's
* label already names the row; the hint stays readable, since it carries the row's state.
* Hover is tracked on the row itself, so it holds while the pointer is over the control.
*
* The row is as tall as one holding a control whether or not it holds one, so a list where only
* some rows carry a switch keeps one row height.
*/
export function SettingsRowHeader({
label,
leading,
labelAccessory,
hint,
hintStatus,
summary,
onPress,
disabled,
expanded = false,
external = false,
control,
accessibilityLabel,
accessibilityState,
webAccessibilityProps,
testID,
}: SettingsRowHeaderProps) {
const layout = useSettingsRowLayout();
const [pointerOver, setPointerOver] = useState(false);
const handlePointerEnter = useCallback(() => setPointerOver(true), []);
const handlePointerLeave = useCallback(() => setPointerOver(false), []);
const hovered = pointerOver && !disabled;
const rowStyle = useMemo(() => [layout.controlRow, hovered && styles.hovered], [hovered, layout]);
const rowStyle = useCallback(
({ hovered }: HoverState) => [layout.row, !disabled && hovered && styles.hovered],
[disabled, layout],
);
const chevronStyle = useMemo(
() => [styles.chevron, expanded && styles.chevronExpanded],
[expanded],
);
return (
<View
<PressHighlight
{...webAccessibilityProps}
accessibilityRole={external ? "link" : "button"}
accessibilityLabel={summary ? `${label}, ${summary}` : label}
accessibilityState={accessibilityState}
disabled={disabled}
onPress={onPress}
style={rowStyle}
onPointerEnter={handlePointerEnter}
onPointerLeave={handlePointerLeave}
highlightStyle={styles.pressed}
testID={testID}
>
<PressHighlight
{...webAccessibilityProps}
accessibilityRole={external ? "link" : "button"}
accessibilityLabel={accessibilityLabel ?? (summary ? `${label}, ${summary}` : label)}
accessibilityState={accessibilityState}
disabled={disabled}
onPress={onPress}
style={styles.pressTarget}
highlightStyle={styles.pressed}
/>
{leading ? (
<View style={[styles.leading, styles.passThrough]} {...HIDDEN_FROM_ASSISTIVE_TECH}>
{leading}
</View>
) : null}
<View style={[settingsStyles.rowContent, styles.passThrough]}>
<View style={labelAccessory ? styles.labelRow : undefined} {...HIDDEN_FROM_ASSISTIVE_TECH}>
<Text style={layout.title}>{label}</Text>
{labelAccessory}
</View>
{hintStatus ? (
<RowHintLine hint={hint} status={hintStatus} hintStyle={layout.hint} />
) : null}
{hint && !hintStatus ? <Text style={layout.hint}>{hint}</Text> : null}
</View>
{control ? (
<View style={styles.control}>
<ControlSizeProvider size={layout.controlSize}>{control}</ControlSizeProvider>
</View>
) : null}
<View style={[styles.trailing, styles.passThrough]} {...HIDDEN_FROM_ASSISTIVE_TECH}>
{external ? (
// Drawn the same as a section header's docs link, so the two read as one thing.
<ExternalLinkLabel hovered={hovered}>{summary}</ExternalLinkLabel>
) : (
<>
{summary ? (
<Text style={styles.summary} numberOfLines={1}>
{summary}
</Text>
) : null}
{disabled ? null : (
<View style={chevronStyle}>
<ThemedChevron
size={ICON_SIZE.sm}
uniProps={hovered ? hoveredIconColorMapping : mutedIconColorMapping}
/>
{({ hovered }: HoverState) => (
<>
<View style={settingsStyles.rowContent}>
{labelAccessory ? (
<View style={styles.labelRow}>
<Text style={layout.title}>{label}</Text>
{labelAccessory}
</View>
) : (
<Text style={layout.title}>{label}</Text>
)}
</>
)}
</View>
</View>
);
}
const HIDDEN_FROM_ASSISTIVE_TECH = {
accessibilityElementsHidden: true,
importantForAccessibility: "no-hide-descendants",
"aria-hidden": true,
} as const;
/**
* The hint with its status mark. The line keeps the hint's own height in every status, so a row
* does not move when its value arrives or its work starts. A long error is cut to the line; the
* row's detail says it in full.
*/
function RowHintLine({
hint,
status,
hintStyle,
}: {
hint: string | undefined;
status: SettingsRowHintStatus;
hintStyle: SettingsRowLayout["hint"];
}) {
const textStyle = useMemo(
() => [hintStyle, styles.hintText, status === "error" && styles.hintError],
[hintStyle, status],
);
if (status === "pending") {
return (
<View style={styles.hintLine}>
{/* A blank line of hint text holds the height; the placeholder sits over it. */}
<Text style={textStyle}> </Text>
<HintPlaceholder />
</View>
);
}
return (
<View style={styles.hintLine}>
{status === "busy" ? (
<ThemedLoadingSpinner size={14} uniProps={mutedIconColorMapping} />
) : (
<View style={styles.errorDot} testID="settings-row-error-dot" />
{hint ? <Text style={layout.hint}>{hint}</Text> : null}
</View>
{external ? (
// Drawn the same as a section header's docs link, so the two read as one thing.
<ExternalLinkLabel hovered={hovered}>{summary}</ExternalLinkLabel>
) : (
<>
{summary ? (
<Text style={styles.summary} numberOfLines={1}>
{summary}
</Text>
) : null}
{disabled ? null : (
<View style={chevronStyle}>
<ThemedChevron
size={ICON_SIZE.sm}
uniProps={hovered ? hoveredIconColorMapping : mutedIconColorMapping}
/>
</View>
)}
</>
)}
</>
)}
<Text style={textStyle} numberOfLines={1}>
{hint}
</Text>
</View>
</PressHighlight>
);
}
function HintPlaceholder() {
const pulse = useSkeletonPulse();
return <SkeletonPulse pulse={pulse} style={styles.hintPlaceholder} />;
}
const styles = StyleSheet.create((theme) => ({
leading: {
marginRight: theme.spacing[3],
alignItems: "center",
justifyContent: "center",
},
control: {
marginRight: theme.spacing[3],
},
// The button under the row's content; it fills the row, padding included.
pressTarget: {
...StyleSheet.absoluteFill,
},
passThrough: {
pointerEvents: "none",
},
trailing: {
flexDirection: "row",
alignItems: "center",
flexShrink: 1,
},
hintLine: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[1.5],
marginTop: theme.spacing[1],
},
// The line carries the hint's top margin, so the mark and the words share one baseline box.
hintText: {
marginTop: 0,
flexShrink: 1,
},
hintError: {
color: theme.colors.statusDanger,
},
errorDot: {
width: 8,
height: 8,
borderRadius: theme.borderRadius.full,
backgroundColor: theme.colors.statusDanger,
},
hintPlaceholder: {
position: "absolute",
left: 0,
top: theme.spacing[0.5],
bottom: theme.spacing[0.5],
width: theme.spacing[32],
borderRadius: theme.borderRadius.sm,
backgroundColor: theme.colors.surface2,
},
labelRow: { flexDirection: "row", alignItems: "center", gap: theme.spacing[2] },
summary: {
flexShrink: 1,
@@ -25,7 +25,7 @@ export interface SegmentedControlOption<T extends string> {
interface SegmentedControlProps<T extends string> {
options: SegmentedControlOption<T>[];
value: T | null;
value: T;
onValueChange: (value: T) => void;
size?: ControlSize;
hideLabels?: boolean;
@@ -112,7 +112,7 @@ function SegmentItem<T extends string>({
hideLabels: boolean;
segmentSizeStyle: StyleProp<ViewStyle>;
labelSizeStyle: StyleProp<TextStyle>;
currentValue: T | null;
currentValue: T;
onValueChange: (value: T) => void;
}) {
const labelStyle = useMemo(
@@ -16,7 +16,7 @@ import { formatThinkingOptionLabel } from "@/agent-controls/labels";
import { CombinedModelSelector } from "@/components/combined-model-selector";
import {
buildProviderSelectorProviders,
buildSelectorProvider,
buildSelectableProviderSelectorProviders,
type ProviderSelectorProvider,
} from "@/provider-selection/provider-selection";
import { filterSelectableModels } from "@/provider-selection/model-catalog";
@@ -1049,7 +1049,7 @@ export const AgentControls = memo(function AgentControls({
);
const agentModelSelectorProviders = useMemo(() => {
if (snapshotSelectedEntry) {
return [buildSelectorProvider(snapshotSelectedEntry)];
return buildSelectableProviderSelectorProviders([snapshotSelectedEntry]);
}
return buildProviderSelectorProviders({
providerDefinitions: agentProviderDefinitions,
@@ -4,7 +4,6 @@ import type { JsonValue } from "@getpaseo/protocol/agent-types";
import { Keyboard, StyleSheet as RNStyleSheet, Text, View } from "react-native";
import { useTranslation } from "react-i18next";
import { StyleSheet } from "react-native-unistyles";
import { CHAT_COLUMN_RAIL_DATASET } from "@/chat-rail";
import { useContainerWidthBelow } from "@/hooks/use-container-width";
import invariant from "tiny-invariant";
import { Composer } from "@/composer";
@@ -537,17 +536,14 @@ export function WorkspaceDraftComposer({
return (
<View style={animatedStaticStyles.inputAreaWrapper} onLayout={onInputAreaLayout}>
{formErrorMessage ? (
<View
style={styles.formErrorRow}
dataSet={isComposerFullscreen ? undefined : CHAT_COLUMN_RAIL_DATASET}
>
<View style={styles.formErrorRow}>
<View style={styles.formError}>
<Text style={styles.errorText}>{formErrorMessage}</Text>
</View>
</View>
) : null}
{importPillPress && !isComposerFullscreen ? (
<View style={styles.importPillRow} dataSet={CHAT_COLUMN_RAIL_DATASET}>
<View style={styles.importPillRow}>
<View style={styles.importPillContent}>
<ComposerImportPill onPress={importPillPress} />
</View>
+1 -5
View File
@@ -30,7 +30,6 @@ import {
} from "react";
import { useTranslation } from "react-i18next";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { CHAT_COLUMN_RAIL_DATASET } from "@/chat-rail";
import { useIsCompactFormFactor } from "@/constants/layout";
import {
controlSizingForLayout,
@@ -2576,10 +2575,7 @@ function ComposerContentImpl({
>
<AttachmentLightbox source={lightboxSource} onClose={handleLightboxClose} />
{/* Input area */}
<View
style={inputAreaContainerStyle}
dataSet={isFullscreen ? undefined : CHAT_COLUMN_RAIL_DATASET}
>
<View style={inputAreaContainerStyle}>
<View style={inputAreaContentStyle}>
{isFullscreen ? null : queueList}
{!isFullscreen && sendErrorNode}
+1 -2
View File
@@ -21,7 +21,6 @@ import {
useHorizontalScrollBoundary,
} from "@/components/ui/horizontal-scroll-boundary";
import { STATUS_RING_HALO_INSET } from "@/components/status-ring/geometry";
import { CHAT_COLUMN_RAIL_DATASET } from "@/chat-rail";
import { isWeb } from "@/constants/platform";
import { usePanelAwareHorizontalScrollGesture } from "@/mobile-panels/gestures";
import { getStatusDotColor } from "@/utils/status-dot-color";
@@ -46,7 +45,7 @@ export function ComposerTrackBar({ children }: { children: ReactNode }): ReactEl
const scrollGesture = usePanelAwareHorizontalScrollGesture();
const scrollBoundary = useHorizontalScrollBoundary();
return (
<View style={styles.bar} dataSet={CHAT_COLUMN_RAIL_DATASET} pointerEvents="box-none">
<View style={styles.bar} pointerEvents="box-none">
<View style={styles.trackViewport} pointerEvents="box-none">
<GestureDetector gesture={scrollGesture}>
<Animated.ScrollView
@@ -224,7 +224,6 @@ const CATALOG_DATA = [
},
{
id: "goose",
bundledProvider: { hostFeature: "gooseProvider" },
title: "goose",
description: "A local, extensible, open source AI agent that automates engineering tasks",
version: "1.33.1",
@@ -2,7 +2,6 @@ import type { ParsedDiffFile } from "@getpaseo/protocol/messages";
import { describe, expect, it } from "vitest";
import {
characterOffsetAtPoint,
graphemeOffsetAtPoint,
hitTestDiffDocument,
orderedSelection,
selectAllSource,
@@ -44,49 +43,6 @@ describe("diff hit testing", () => {
).toBe(combining?.end);
});
it("keeps the nearest caret for character drags but hits the grapheme under word gestures", () => {
const cell = changedCell(buildModel("call(foo)", { wrapLines: false, viewportWidth: 300 }));
const graphemes = cell.fragments[0]!.graphemes;
const lastOfWord = graphemes[3]!;
const punctuation = graphemes[4]!;
const beforeLastOfWord = graphemes
.slice(0, 3)
.reduce((width, grapheme) => width + grapheme.width, 0);
const rightHalfOfWord = beforeLastOfWord + lastOfWord.width * 0.75;
const leftHalfOfPunctuation = beforeLastOfWord + lastOfWord.width + punctuation.width * 0.1;
expect(characterOffsetAtPoint({ cell, x: rightHalfOfWord, y: 0, lineHeight: 18 })).toBe(
punctuation.start,
);
expect(graphemeOffsetAtPoint({ cell, x: rightHalfOfWord, y: 0, lineHeight: 18 })).toBe(
lastOfWord.start,
);
expect(characterOffsetAtPoint({ cell, x: leftHalfOfPunctuation, y: 0, lineHeight: 18 })).toBe(
punctuation.start,
);
expect(graphemeOffsetAtPoint({ cell, x: leftHalfOfPunctuation, y: 0, lineHeight: 18 })).toBe(
punctuation.start,
);
});
it("keeps wrapped fragment boundaries from stealing the grapheme under the pointer", () => {
const cell = changedCell(buildModel("abcdef", { viewportWidth: 90 }));
const firstFragment = cell.fragments[0]!;
expect(cell.fragments.length).toBeGreaterThan(1);
const lastGrapheme = firstFragment.graphemes.at(-1)!;
const beforeLastGrapheme = firstFragment.graphemes
.slice(0, -1)
.reduce((width, grapheme) => width + grapheme.width, 0);
const rightHalfOfLastGrapheme = beforeLastGrapheme + lastGrapheme.width * 0.75;
expect(characterOffsetAtPoint({ cell, x: rightHalfOfLastGrapheme, y: 0, lineHeight: 18 })).toBe(
firstFragment.end,
);
expect(graphemeOffsetAtPoint({ cell, x: rightHalfOfLastGrapheme, y: 0, lineHeight: 18 })).toBe(
lastGrapheme.start,
);
});
it("normalizes backwards selection and copies exact source including empty lines", () => {
const model = buildModel("", { wrapLines: false });
const cell = changedCell(model);
@@ -3,7 +3,6 @@ import type {
DiffCell,
DiffCharacterPosition,
DiffDocumentModel,
DiffFragment,
DiffHit,
DiffSelection,
} from "./types";
@@ -34,7 +33,12 @@ export function hitTestDiffDocument(input: {
localX - file.gutterWidth - CODE_LEFT_PADDING + input.horizontalOffset,
);
const textY = input.documentY - row.top;
const point = { cell, x: contentX, y: textY, lineHeight: input.model.lineHeight };
const sourceOffset = characterOffsetAtPoint({
cell,
x: contentX,
y: textY,
lineHeight: input.model.lineHeight,
});
return {
kind: "cell",
target: cell.reviewTarget,
@@ -43,9 +47,8 @@ export function hitTestDiffDocument(input: {
rowIndex: row.index,
cellIndex,
side: cell.reviewTarget?.side ?? (cellIndex === 0 ? "old" : "new"),
sourceOffset: characterOffsetAtPoint(point),
sourceOffset,
},
graphemeOffset: graphemeOffsetAtPoint(point),
};
}
@@ -55,7 +58,11 @@ export function characterOffsetAtPoint(input: {
y: number;
lineHeight: number;
}): number {
const fragment = fragmentAtPoint(input);
const fragmentIndex = Math.min(
input.cell.fragments.length - 1,
Math.max(0, Math.floor(input.y / input.lineHeight)),
);
const fragment = input.cell.fragments[fragmentIndex];
if (!fragment) return 0;
let width = 0;
for (const grapheme of fragment.graphemes) {
@@ -65,36 +72,6 @@ export function characterOffsetAtPoint(input: {
return fragment.end;
}
/** The grapheme under the pointer, unlike `characterOffsetAtPoint`, which snaps to the nearest caret. */
export function graphemeOffsetAtPoint(input: {
cell: DiffCell;
x: number;
y: number;
lineHeight: number;
}): number {
const fragment = fragmentAtPoint(input);
if (!fragment) return 0;
let width = 0;
for (const grapheme of fragment.graphemes) {
if (input.x < width + grapheme.width) return grapheme.start;
width += grapheme.width;
}
const lastGrapheme = fragment.graphemes.at(-1);
return lastGrapheme ? lastGrapheme.start : fragment.start;
}
function fragmentAtPoint(input: {
cell: DiffCell;
y: number;
lineHeight: number;
}): DiffFragment | null {
const fragmentIndex = Math.min(
input.cell.fragments.length - 1,
Math.max(0, Math.floor(input.y / input.lineHeight)),
);
return input.cell.fragments[fragmentIndex] ?? null;
}
function rowAtOffset(
rows: readonly DiffDocumentModel["rows"][number][],
start: number,
@@ -186,7 +163,7 @@ export function selectAllSource(
return first && last ? { anchor: first, focus: last } : null;
}
export function comparePosition(left: DiffCharacterPosition, right: DiffCharacterPosition): number {
function comparePosition(left: DiffCharacterPosition, right: DiffCharacterPosition): number {
return (
left.rowIndex - right.rowIndex ||
left.cellIndex - right.cellIndex ||
@@ -1,38 +1,5 @@
import { describe, expect, it } from "vitest";
import {
hasPointerDragStarted,
lineSelectionForDrag,
wordSelectionForDrag,
type LineAtPosition,
type WordAtPosition,
} from "./pointer-gesture";
import type { DiffCharacterPosition } from "./types";
function positionAt(offset: number, rowIndex = 1, cellIndex = 0): DiffCharacterPosition {
return { fileIndex: 0, rowIndex, cellIndex, side: "new", sourceOffset: offset };
}
function wordAt(
input: { offset: number; start: number; end: number },
rowIndex = 1,
cellIndex = 0,
): WordAtPosition {
return {
position: positionAt(input.offset, rowIndex, cellIndex),
word: { start: input.start, end: input.end },
};
}
function lineAt(
input: { offset: number; end: number },
rowIndex = 1,
cellIndex = 0,
): LineAtPosition {
return {
position: positionAt(input.offset, rowIndex, cellIndex),
end: input.end,
};
}
import { hasPointerDragStarted } from "./pointer-gesture";
describe("diff pointer gesture", () => {
it("classifies pointer movement as a drag without requiring a character change", () => {
@@ -59,99 +26,3 @@ describe("diff pointer gesture", () => {
).toBe(true);
});
});
describe("diff word drag selection", () => {
it("extends forward from the start of the anchor word to the end of the focus word", () => {
expect(
wordSelectionForDrag({
anchor: wordAt({ offset: 8, start: 6, end: 11 }),
focus: wordAt({ offset: 14, start: 12, end: 19 }),
}),
).toEqual({
anchor: positionAt(6),
focus: positionAt(19),
});
});
it("extends backward from the end of the anchor word to the start of the focus word", () => {
expect(
wordSelectionForDrag({
anchor: wordAt({ offset: 15, start: 13, end: 20 }),
focus: wordAt({ offset: 7, start: 6, end: 11 }),
}),
).toEqual({
anchor: positionAt(6),
focus: positionAt(20),
});
});
it("keeps the anchor word whole while the pointer stays inside it", () => {
const anchor = wordAt({ offset: 10, start: 6, end: 11 });
const expected = { anchor: positionAt(6), focus: positionAt(11) };
expect(
wordSelectionForDrag({ anchor, focus: wordAt({ offset: 7, start: 6, end: 11 }) }),
).toEqual(expected);
expect(
wordSelectionForDrag({ anchor, focus: wordAt({ offset: 9, start: 6, end: 11 }) }),
).toEqual(expected);
});
it("snaps both ends to word boundaries across rows", () => {
expect(
wordSelectionForDrag({
anchor: wordAt({ offset: 3, start: 2, end: 5 }, 1),
focus: wordAt({ offset: 2, start: 0, end: 4 }, 3),
}),
).toEqual({
anchor: positionAt(2, 1),
focus: positionAt(4, 3),
});
expect(
wordSelectionForDrag({
anchor: wordAt({ offset: 2, start: 0, end: 4 }, 3),
focus: wordAt({ offset: 3, start: 2, end: 5 }, 1),
}),
).toEqual({
anchor: positionAt(2, 1),
focus: positionAt(4, 3),
});
});
});
describe("diff line drag selection", () => {
it("selects the whole clicked source line", () => {
expect(
lineSelectionForDrag({
anchor: lineAt({ offset: 3, end: 12 }),
focus: lineAt({ offset: 3, end: 12 }),
}),
).toEqual({
anchor: positionAt(0),
focus: positionAt(12),
});
});
it("extends forward to the end of the focus line while keeping the anchor line", () => {
expect(
lineSelectionForDrag({
anchor: lineAt({ offset: 3, end: 12 }),
focus: lineAt({ offset: 1, end: 7 }, 3),
}),
).toEqual({
anchor: positionAt(0),
focus: positionAt(7, 3),
});
});
it("extends backward from the start of the focus line to the end of the anchor line", () => {
expect(
lineSelectionForDrag({
anchor: lineAt({ offset: 5, end: 9 }, 3),
focus: lineAt({ offset: 2, end: 12 }, 1),
}),
).toEqual({
anchor: positionAt(0, 1),
focus: positionAt(9, 3),
});
});
});
@@ -1,46 +1,5 @@
import { comparePosition } from "./hit-testing";
import type { DiffCharacterPosition, DiffSelection } from "./types";
import type { SourceWordRange } from "./word-boundaries";
const DRAG_THRESHOLD = 4;
export interface WordAtPosition {
position: DiffCharacterPosition;
word: SourceWordRange;
}
export interface LineAtPosition {
position: DiffCharacterPosition;
/** UTF-16 length of the canonical source line. */
end: number;
}
export function wordSelectionForDrag(input: {
anchor: WordAtPosition;
focus: WordAtPosition;
}): DiffSelection {
const isBackward = comparePosition(input.focus.position, input.anchor.position) < 0;
const start = isBackward ? input.focus : input.anchor;
const end = isBackward ? input.anchor : input.focus;
return {
anchor: { ...start.position, sourceOffset: start.word.start },
focus: { ...end.position, sourceOffset: end.word.end },
};
}
export function lineSelectionForDrag(input: {
anchor: LineAtPosition;
focus: LineAtPosition;
}): DiffSelection {
const isBackward = comparePosition(input.focus.position, input.anchor.position) < 0;
const start = isBackward ? input.focus : input.anchor;
const end = isBackward ? input.anchor : input.focus;
return {
anchor: { ...start.position, sourceOffset: 0 },
focus: { ...end.position, sourceOffset: end.end },
};
}
export function hasPointerDragStarted(input: {
startX: number;
startY: number;
@@ -35,13 +35,7 @@ import {
resolveRelayoutScrollTop,
} from "./model";
import { paintWebFileHeader, paintWebViewport } from "./paint.web";
import {
hasPointerDragStarted,
lineSelectionForDrag,
wordSelectionForDrag,
type LineAtPosition,
type WordAtPosition,
} from "./pointer-gesture";
import { hasPointerDragStarted } from "./pointer-gesture";
import {
createMeasuredAdvances,
createAdditiveAdvances,
@@ -50,8 +44,6 @@ import {
} from "./text-measurement";
import { retainDiffViewport } from "./viewport";
import type {
DiffCell,
DiffCharacterPosition,
DiffHit,
DiffFileSection,
DiffSelection,
@@ -59,7 +51,6 @@ import type {
DiffTypography,
TextMeasurer,
} from "./types";
import { wordRangeAtOffset } from "./word-boundaries";
import { useDiffDocumentWorkspaceCache } from "./workspace-cache";
const DEFAULT_MONO_STACK = "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace";
@@ -113,11 +104,6 @@ export function DiffSurface(props: DiffSurfaceProps) {
startY: number;
moved: boolean;
dismissSelectionOnClick: boolean;
granularity:
| { kind: "character" }
| { kind: "word"; anchor: WordAtPosition }
| { kind: "line"; anchor: LineAtPosition };
pointerType: string;
} | null>(null);
const frameRef = useRef<number | null>(null);
const activeHeaderPathRef = useRef<string | null>(null);
@@ -605,31 +591,6 @@ export function DiffSurface(props: DiffSurfaceProps) {
desiredTypography,
setSelection,
]);
const cellAt = useCallback((position: DiffCharacterPosition): DiffCell | null => {
const currentModel = modelRef.current;
if (!currentModel) return null;
const row = currentModel.rows[position.rowIndex];
return row?.kind === "line" ? row.cells[position.cellIndex] : null;
}, []);
const wordAt = useCallback(
(hit: Extract<DiffHit, { kind: "cell" }>): WordAtPosition | null => {
const cell = cellAt(hit.position);
if (!cell) return null;
return {
position: { ...hit.position, sourceOffset: hit.graphemeOffset },
word: wordRangeAtOffset(cell.content, hit.graphemeOffset),
};
},
[cellAt],
);
const lineAt = useCallback(
(hit: Extract<DiffHit, { kind: "cell" }>): LineAtPosition | null => {
const cell = cellAt(hit.position);
if (!cell) return null;
return { position: hit.position, end: cell.content.length };
},
[cellAt],
);
const pointerDown = useCallback(
(event: React.PointerEvent<HTMLDivElement>) => {
if (event.button !== 0) return;
@@ -641,18 +602,18 @@ export function DiffSurface(props: DiffSurfaceProps) {
)
)
return;
const dismissSelectionOnClick = selectionRef.current !== null;
if (dismissSelectionOnClick) {
setSelection(null);
}
const hit = pointHit(event);
const hadSelection = selectionRef.current !== null;
if (hadSelection) setSelection(null);
if (hit?.kind !== "cell") return;
dragRef.current = {
anchor: hit.position,
startX: event.clientX,
startY: event.clientY,
moved: false,
dismissSelectionOnClick: hadSelection,
granularity: { kind: "character" },
pointerType: event.pointerType,
dismissSelectionOnClick,
};
setSelection({ anchor: hit.position, focus: hit.position });
event.currentTarget.focus();
@@ -660,38 +621,6 @@ export function DiffSurface(props: DiffSurfaceProps) {
},
[pointHit, setSelection],
);
// The native click count honors the OS double-click setting and arrives on the
// second mousedown, after pointerdown has opened the character drag.
const mouseDown = useCallback(
(event: React.MouseEvent<HTMLDivElement>) => {
const drag = dragRef.current;
if (!drag || event.button !== 0 || event.detail < 2 || drag.pointerType === "touch") return;
const target = event.target;
if (
target instanceof Element &&
target.closest(
'[data-diff-header="true"], [data-diff-review="true"], [role="menuitem"], button, input, textarea',
)
)
return;
const hit = pointHitAt(event.clientX, event.clientY);
if (hit?.kind !== "cell") return;
if (event.detail >= 3) {
const lineAnchor = lineAt(hit);
if (!lineAnchor) return;
drag.granularity = { kind: "line", anchor: lineAnchor };
drag.dismissSelectionOnClick = false;
setSelection(lineSelectionForDrag({ anchor: lineAnchor, focus: lineAnchor }));
return;
}
const wordAnchor = wordAt(hit);
if (!wordAnchor) return;
drag.granularity = { kind: "word", anchor: wordAnchor };
drag.dismissSelectionOnClick = false;
setSelection(wordSelectionForDrag({ anchor: wordAnchor, focus: wordAnchor }));
},
[lineAt, pointHitAt, setSelection, wordAt],
);
const updateActiveHeader = useCallback(
(target: EventTarget | null) => {
const header =
@@ -705,32 +634,6 @@ export function DiffSurface(props: DiffSurfaceProps) {
},
[paintStickyHeaderPool, schedulePaint],
);
const updateHoveredAffordance = useCallback(
(hit: Extract<DiffHit, { kind: "cell" }>, clientX: number) => {
const row = modelRef.current?.rows[hit.position.rowIndex];
const file = modelRef.current?.files[hit.position.fileIndex];
const sideIndex =
row?.kind === "line" && row.cells.length === 2 && hit.position.side === "new" ? 1 : 0;
if (row && file) {
const columnWidth = viewport.width / (row.kind === "line" ? row.cells.length : 1);
const gutterBorder = sideIndex * columnWidth + file.gutterWidth;
const rootBounds = rootRef.current?.getBoundingClientRect();
const pointerX = rootBounds ? clientX - rootBounds.left : Number.NaN;
if (hit.target && Number.isFinite(pointerX)) {
hasHoveredAffordanceRef.current = true;
setHoveredAffordance({
hit,
left: gutterBorder - 12,
top: row.top - scrollTopRef.current + (modelRef.current!.lineHeight - 22) / 2,
});
return;
}
}
hasHoveredAffordanceRef.current = false;
setHoveredAffordance(null);
},
[viewport.width],
);
const pointerMove = useCallback(
(event: React.PointerEvent<HTMLDivElement>) => {
updateActiveHeader(event.target);
@@ -746,29 +649,35 @@ export function DiffSurface(props: DiffSurfaceProps) {
}
const hit = pointHit(event);
if (hit?.kind === "cell") {
updateHoveredAffordance(hit, event.clientX);
const row = modelRef.current?.rows[hit.position.rowIndex];
const file = modelRef.current?.files[hit.position.fileIndex];
const sideIndex =
row?.kind === "line" && row.cells.length === 2 && hit.position.side === "new" ? 1 : 0;
if (row && file) {
const columnWidth = viewport.width / (row.kind === "line" ? row.cells.length : 1);
const gutterBorder = sideIndex * columnWidth + file.gutterWidth;
const rootBounds = rootRef.current?.getBoundingClientRect();
const pointerX = rootBounds ? event.clientX - rootBounds.left : Number.NaN;
if (hit.target && Number.isFinite(pointerX)) {
hasHoveredAffordanceRef.current = true;
setHoveredAffordance({
hit,
left: gutterBorder - 12,
top: row.top - scrollTopRef.current + (modelRef.current!.lineHeight - 22) / 2,
});
} else {
hasHoveredAffordanceRef.current = false;
setHoveredAffordance(null);
}
}
} else {
hasHoveredAffordanceRef.current = false;
setHoveredAffordance(null);
}
if (!drag || hit?.kind !== "cell") return;
if (drag.granularity.kind === "word") {
const focusWord = wordAt(hit);
if (focusWord) {
setSelection(wordSelectionForDrag({ anchor: drag.granularity.anchor, focus: focusWord }));
}
return;
}
if (drag.granularity.kind === "line") {
const focusLine = lineAt(hit);
if (focusLine) {
setSelection(lineSelectionForDrag({ anchor: drag.granularity.anchor, focus: focusLine }));
}
return;
}
setSelection({ anchor: drag.anchor, focus: hit.position });
},
[lineAt, pointHit, setSelection, updateActiveHeader, updateHoveredAffordance, wordAt],
[pointHit, setSelection, updateActiveHeader, viewport.width],
);
const pointerUp = useCallback(
(event: React.PointerEvent<HTMLDivElement>) => {
@@ -913,7 +822,6 @@ export function DiffSurface(props: DiffSurfaceProps) {
data-overlay-scrollbar="true"
tabIndex={0}
onPointerDown={pointerDown}
onMouseDown={mouseDown}
onPointerMove={pointerMove}
onPointerUp={pointerUp}
onPointerCancel={cancelPointer}
@@ -208,8 +208,6 @@ export type DiffHit =
kind: "cell";
target: ReviewableDiffTarget | null;
position: DiffCharacterPosition;
/** The grapheme under the pointer, which word gestures select from. */
graphemeOffset: number;
};
export interface DiffSelection {
@@ -1,70 +0,0 @@
import { CharCategory, EditorState } from "@codemirror/state";
import { describe, expect, it } from "vitest";
import { wordRangeAtOffset } from "./word-boundaries";
describe("diff word boundaries", () => {
it("selects the identifier under the offset", () => {
expect(wordRangeAtOffset("alpha bravo charlie", 8)).toEqual({ start: 6, end: 11 });
});
it("selects the surrounding whitespace when the offset is inside a run of spaces", () => {
expect(wordRangeAtOffset("alpha bravo", 6)).toEqual({ start: 5, end: 8 });
});
it("selects a run of punctuation without merging it into neighboring words", () => {
expect(wordRangeAtOffset("call(foo, bar)", 4)).toEqual({ start: 4, end: 5 });
expect(wordRangeAtOffset("call(foo, bar)", 6)).toEqual({ start: 5, end: 8 });
expect(wordRangeAtOffset("fn()", 3)).toEqual({ start: 2, end: 4 });
expect(wordRangeAtOffset("foo.bar", 3)).toEqual({ start: 3, end: 4 });
expect(wordRangeAtOffset("foo.bar", 5)).toEqual({ start: 4, end: 7 });
});
it("selects the final word when the offset reaches the end of the line", () => {
expect(wordRangeAtOffset("alpha bravo", 11)).toEqual({ start: 6, end: 11 });
expect(wordRangeAtOffset("alpha bravo", 99)).toEqual({ start: 6, end: 11 });
});
it("selects the leading word when the offset is clamped at the start", () => {
expect(wordRangeAtOffset("alpha bravo", 0)).toEqual({ start: 0, end: 5 });
});
it("keeps combining sequences and emoji clusters whole", () => {
const combining = "ai\u0301b";
expect(wordRangeAtOffset(combining, 1)).toEqual({ start: 0, end: 4 });
expect(wordRangeAtOffset(combining, 2)).toEqual({ start: 0, end: 4 });
const emoji = "hi 👨‍👩‍👧‍👦 there";
const emojiStart = emoji.indexOf("👨");
expect(wordRangeAtOffset(emoji, emojiStart)).toEqual({
start: emojiStart,
end: emojiStart + "👨‍👩‍👧‍👦".length,
});
});
it("treats tabs as whitespace and returns an empty range for empty content", () => {
expect(wordRangeAtOffset("\tfoo", 0)).toEqual({ start: 0, end: 1 });
expect(wordRangeAtOffset("", 0)).toEqual({ start: 0, end: 0 });
});
it("matches CodeMirror word runs for offsets inside a word", () => {
const content = "alpha bravo charlie";
const state = EditorState.create({ doc: content });
for (const offset of [0, 2, 8, 14, 18]) {
const word = state.wordAt(offset);
expect(word).not.toBeNull();
expect(wordRangeAtOffset(content, offset)).toEqual({ start: word!.from, end: word!.to });
}
});
it("classifies leading graphemes with CodeMirror character categories", () => {
const categorize = EditorState.create({ doc: "" }).charCategorizer(0);
const clusters = ["a", "1", "_", "中", "👨‍👩‍👧‍👦", "\u0301", "\ufe0f", "\u00a0"];
for (const cluster of clusters) {
const isWord = categorize(cluster) === CharCategory.Word;
expect(wordRangeAtOffset(`${cluster}x`, 0)).toEqual({
start: 0,
end: isWord ? cluster.length + 1 : cluster.length,
});
}
});
});
@@ -1,88 +0,0 @@
import { CharCategory, EditorState } from "@codemirror/state";
import { graphemeBoundaries } from "./model";
export interface SourceWordRange {
start: number;
end: number;
}
interface SourceText {
state: EditorState;
boundaries: number[];
categorize: (cluster: string) => CharCategory;
}
// Word gestures query the same line repeatedly while dragging. Keep a bounded
// set of parsed sources instead of rebuilding an EditorState on every move.
const SOURCE_CACHE_LIMIT = 8;
const sources = new Map<string, SourceText>();
/**
* The run around `offset` that a double click selects: a word, a run of
* whitespace, or a run of punctuation. Runs never cross grapheme boundaries.
*/
export function wordRangeAtOffset(content: string, offset: number): SourceWordRange {
if (content.length === 0) return { start: 0, end: 0 };
const source = sourceText(content);
const { boundaries } = source;
const clusterIndex = clusterIndexAt(boundaries, offset);
const category = source.categorize(clusterText(content, boundaries, clusterIndex));
if (category === CharCategory.Word) {
const word = source.state.wordAt(boundaries[clusterIndex]);
if (word) return { start: word.from, end: word.to };
}
let first = clusterIndex;
while (first > 0 && categoryAt(source, content, boundaries, first - 1) === category) first -= 1;
let last = clusterIndex;
while (
last < boundaries.length - 2 &&
categoryAt(source, content, boundaries, last + 1) === category
)
last += 1;
return { start: boundaries[first], end: boundaries[last + 1] };
}
function sourceText(content: string): SourceText {
const cached = sources.get(content);
if (cached) {
sources.delete(content);
sources.set(content, cached);
return cached;
}
const state = EditorState.create({ doc: content });
const source: SourceText = {
state,
boundaries: graphemeBoundaries(content),
categorize: state.charCategorizer(0),
};
sources.set(content, source);
if (sources.size > SOURCE_CACHE_LIMIT) {
const oldest = sources.keys().next();
if (!oldest.done) sources.delete(oldest.value);
}
return source;
}
function clusterIndexAt(boundaries: readonly number[], offset: number): number {
let low = 0;
let high = boundaries.length - 2;
while (low < high) {
const middle = (low + high + 1) >>> 1;
if (boundaries[middle] <= offset) low = middle;
else high = middle - 1;
}
return low;
}
function categoryAt(
source: SourceText,
content: string,
boundaries: readonly number[],
index: number,
): CharCategory {
return source.categorize(clusterText(content, boundaries, index));
}
function clusterText(content: string, boundaries: readonly number[], index: number): string {
return content.slice(boundaries[index], boundaries[index + 1]);
}
@@ -150,21 +150,3 @@ describe("ACP provider catalog", () => {
});
});
});
it("adds bundled goose on capable hosts and uses the ACP config on older hosts", () => {
const goose = findProvider("goose");
expect(buildAcpProviderConfigPatch(goose, (feature) => feature === "gooseProvider")).toEqual({
providers: { goose: { enabled: true } },
});
expect(buildAcpProviderConfigPatch(goose)).toEqual({
providers: {
goose: {
extends: "acp",
label: "goose",
description: goose.description,
command: ["goose", "acp"],
env: {},
},
},
});
});
@@ -9,26 +9,17 @@ export function getAcpProviderCatalog(): AcpProviderCatalogItem[] {
return ACP_PROVIDER_CATALOG;
}
/** The catalog's install guide for a provider added from it, or null for any other provider. */
export function readAcpProviderInstallGuide(provider: string): string | null {
return ACP_PROVIDER_CATALOG.find((entry) => entry.id === provider)?.installLink ?? null;
}
export function buildAcpProviderConfigPatch(
entry: AcpProviderCatalogItem,
hostSupports: (feature: HostFeatureName) => boolean = () => false,
): MutableDaemonConfigPatch {
if (entry.bundledProvider) {
const feature = entry.bundledProvider.hostFeature;
if (hostSupports(feature)) {
return { providers: { [entry.id]: { enabled: true } } };
}
// COMPAT(gooseProvider): added in v0.17.0, remove after 2027-05-20 once host floor includes the bundled adapter.
// COMPAT(hopliteProvider): added after v0.11.2, remove after 2027-04-15 once host floor includes the bundled adapter.
// COMPAT(fxProvider): added after v0.15.3, remove after 2027-05-09 once host floor includes the bundled adapter.
if (feature !== "gooseProvider") {
if (!hostSupports(entry.bundledProvider.hostFeature)) {
throw new Error(`Update the host to add ${entry.title}.`);
}
return { providers: { [entry.id]: { enabled: true } } };
}
return {
providers: {

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