Compare commits

...
Author SHA1 Message Date
Mohamed Boudra fa6df8a959 fix(app): keep the composer's remembered provider in its picker
The picker leaves out providers that aren't installed, except the one
holding the picker's current choice. The schedule form and metadata page
passed that choice; the new-agent composer didn't, so a remembered
provider not installed on this host vanished from the picker and the
trigger read "Select model" with no reason given. The builder now requires
every caller to say what its current choice is, or null.
2026-11-14 14:41:27 +01:00
Mohamed Boudra ec179aa01e fix(app): don't leave a re-added provider's sheet stuck on Removing...
The setup step and the model picker's gear keep a provider's sheet
mounted after it closes, keyed by provider. A finished removal stayed
set in that sheet, so adding the same provider back reopened it with
Remove spinning and disabled. A finished removal now ends when the host
lists the provider again.
2026-11-14 14:24:04 +01:00
Mohamed Boudra 0563654cb0 fix(app): show progress on the provider page's in-flight buttons
Remove, Add model and the diagnostic re-run now show their work on the
pressed control, like the page's Refresh and Update: a spinner, no
further presses and, on a labelled button, "Removing..." or "Adding...".

Remove kept its label and only disabled itself, and the page went blank
mid-removal: the daemon publishes the provider list without the removed
provider before it answers the config patch, so the body had nothing to
show and each frame's title fell back to the raw id. The removal now
keeps the entry the user confirmed, and one hook feeds the frame's title
and the body, so both keep showing the provider until the page closes.
The in-flight state also starts after confirmation, not while the
dialog is open.

The diagnostic sheet's header icon buttons had lost the base branch's
spinner and dimming; SheetHeaderIconButton now takes loading and
disabled, the way Button does.
2026-11-14 14:12:14 +01:00
Mohamed Boudra 6ead9a9e0b fix(app): show the not-found notice when a provider is removed elsewhere
The page hid the notice for any provider it had shown before, to cover its own Remove. A removal from another client, the CLI or a plugin then left the page blank with no way to tell why. The page now owns its Remove: while that runs and once it succeeds the body shows nothing, and any other absence says the provider isn't on this host.

The removal e2e routes only the e2e daemon's socket, so the fixture's port-6767 guard stays in force.
2026-11-14 13:14:12 +01:00
Mohamed Boudra 4d740fd4dd fix(app): don't call a just-removed provider missing while its page closes
The daemon can publish the provider list without the removed provider before it answers the config patch, so the page said "This provider isn't on this host" until the answer arrived and it navigated away; in a sheet, through the exit animation as well. A page that has shown its provider now shows nothing once it leaves the list. The not-found notice is for a page that never found its provider. The removal e2e holds the config answer so it always sees that order.
2026-11-14 13:03:21 +01:00
Mohamed Boudra ddc45fe1c1 fix(app): show a provider page's loading and not-found states
A provider page opened from its URL (a reload, a cold start, a shared link) rendered its title over nothing until the host's providers arrived, and forever when the id named a provider the host doesn't have. The page body now says Loading..., that the host is offline, that the providers couldn't be read, or that the provider isn't on this host, in the same notice card the provider list uses when it is offline. The page and both sheet frames share the body.
2026-11-14 12:51:41 +01:00
Mohamed Boudra 4ed83a0ef0 refactor(app): name the provider picker's connection and saved-choice options
Callers passed a bare true to reach the saved-choice argument.
2026-11-14 12:11:38 +01:00
Mohamed Boudra 969b2938e9 test(app): wait for an added catalog provider's probe before continuing
Adding a provider opens its page only after the daemon probes it, which can outlast the default expect timeout on CI.
2026-11-14 12:04:12 +01:00
Mohamed Boudra b759977818 fix(app): keep a saved provider choice visible when it is not installed
The provider picker drops unavailable providers. A schedule or metadata-generation setting saved against such a provider then showed Select model. The picker now keeps the saved provider, labelled Unavailable, so the user sees what is set and can change it.
2026-11-14 12:04:12 +01:00
Mohamed Boudra 35acb5a914 fix(app): say Not installed for a disabled provider that is not installed
A disabled provider's snapshot status is unavailable, so the row said Disabled even when the binary was missing. The installation inspection is checked first, so Not installed wins over Disabled.
2026-11-14 12:04:11 +01:00
Mohamed Boudra 0869f6df33 fix(app): don't open a provider's page after its Add sheet was closed
Adding a provider waits for the daemon to probe it. If the user closed the sheet during that wait, the completed add still navigated to the provider's page. The add now remembers which sheet session started it and only opens the page if that session is still current.
2026-11-14 12:04:11 +01:00
Mohamed Boudra 18b19f1e78 fix(app): let screen readers read a settings row's state line
The row's button carries the row's name as its label, so only the title is hidden from assistive tech now; the hint below it (a provider's version, error or Not installed) is read again.

The Enter-on-switch test now dispatches its key events synchronously inside one act. An awaited keyboard call let the Switch's animation run a frame after the test, which Vitest reported as an unhandled error and failed the run.
2026-11-14 12:04:11 +01:00
Mohamed Boudra 37c99c12b1 test(app): find the provider page's buttons in the compact sheet
On compact layouts AdaptiveModalSheet puts its testID on the header only,
so buttons in the page body cannot be found inside it. The spec looks them
up on the page, as it did before the page moved into the sheet.
2026-11-14 11:43:25 +01:00
Mohamed Boudra bf3d6b5fe0 test(app): give the Unistyles stub the light theme's full colours
Since the stub started applying withUnistyles theme mappings, a mapping
reading a colour the stub's theme lacked crashed: the markdown styles read
colors.terminal and failed the plan card disclosure tests. The stub's
colours now start from the light theme, with its own values pinned on top.
2026-11-14 11:43:25 +01:00
Mohamed Boudra 4c072573fe fix(app): reserve a control's height only on rows that open something
The previous change gave every card row a control's minimum height and
the design doc said so, but rows built directly on settingsStyles.row
(66 uses) never got it: a single-line row was 48px or 64px depending on
which code path built it.

The minimum now belongs to SettingsRowHeader, the row with an optional
control slot, so a list where only some rows carry a switch keeps one
height. SettingsRow and hand-built rows take their content's height again,
as on the base branch, and the doc states the narrower rule.
2026-11-14 11:43:25 +01:00
Mohamed Boudra ee4c26f48e fix(app): keep a settings row's switch out of the row's button
The provider row's switch rendered inside the row's <button>. That is
invalid markup, and keys reached both: Enter on the switch toggled it and
also opened the provider's page, and Space on it opened the page without
toggling.

SettingsRowHeader now lays its press target under the row's content as a
sibling of the control. The content lets presses through to the button and
stays out of the accessibility tree, where the button's label already names
the row. Hover is tracked on the row, so it holds over the switch.
2026-11-14 11:43:24 +01:00
Mohamed Boudra 19d791777e fix(app): title a provider's Settings page like a project's
The page title and the detail header both named the provider. The screen
now titles it "Providers" and the page names the provider once, the way a
project's page does.
2026-11-14 10:56:38 +01:00
Mohamed Boudra b2a83d335f fix(app): keep a provider row's error to one line
A long or multi-line error wrapped the hint to two lines with the dot
centred between them. The row cuts it to one line; the provider's page
shows it in full.
2026-11-14 10:56:38 +01:00
Mohamed Boudra c523b3ad9b fix(app): keep settings rows one height and on one icon rail on phones
On touch layouts a switch reserves a 44px control, so in the provider list
rows with a switch stood 10px taller than "Not installed" rows without one.
Card rows now reserve a default control's height, the rule nested rows
already follow.

A compact SettingsRow wrapped with a full `gap`, which added 12px on top of
the leading slot's margin: catalog icons sat 24px from their labels instead
of 12px. The wrap only needs space between lines, so it uses `rowGap`.
2026-11-14 10:56:37 +01:00
Mohamed Boudra 4858e62270 docs: describe the provider list and pages as they are now 2026-11-14 10:26:19 +01:00
Mohamed Boudra d6efcc453b feat(app): open setup's provider pages over the setup card
The detail and Add provider sheets take the setup card's frame and a back
arrow, so they read as pages of setup instead of a sheet over it. The step
is renamed "Your providers" to match the list it shows.
2026-11-14 10:24:00 +01:00
Mohamed Boudra 2e90865134 feat(app): show each provider's version, updates and faults in the list
Each row now says how its provider is: version and model count, Update
available, a spinner while an update runs, a red dot with the error, or
Not installed / Disabled. Only a broken provider gets a dot, and a
provider that is not installed has no switch, since the model picker
already leaves it out. The kebab is gone; Remove lives on the detail.

Rows read the same installation and update queries as the detail, so
opening a provider costs no new requests. Hosts without
providerInstallation still get a correct list from the snapshot alone.

Add provider is a "+ Provider" button in the header and a muted last row;
both open one sheet with search and catalog rows, replacing the tile grid.
After Add, the new provider's detail opens.

The row is the settings kit's detail row, which gains a leading icon, a
hint status (spinner, error dot, or a held line) and a control before the
chevron. The Unistyles test stub now applies withUnistyles theme mappings,
so browser tests render components that read colours through the theme.
2026-11-14 10:17:29 +01:00
Mohamed Boudra 603c52b294 feat(app): open a provider's detail as a Settings page or a sheet
Settings → Providers now pushes a provider page, like Projects and Plugins;
the model picker gear and setup keep a sheet. Both frame one body, ordered
error, Enabled, Installation, Models, Troubleshooting, Danger zone, so the
old sheet's sticky footer and Retry button are gone. Refresh lives once, in
the Troubleshooting status row.

The page header (back link, icon, title) moves into the shared settings kit
so projects, plugins and providers line up on the same rails.
2026-11-14 10:17:29 +01:00
Mohamed Boudra 737792ad7c fix(app): leave providers that are not installed out of the model picker
An agent's own provider stays in its selector, labelled Unavailable.
2026-11-14 10:17:29 +01:00
Mohamed Boudra 3edd502aac test(server): name the provider PATH test for what it shows
The availability check that gates a Copilot spawn still looks on the daemon's
PATH, so the copy on the provider's PATH is not always the one agents launch.
2026-11-14 10:16:17 +01:00
Mohamed Boudra bd3d86749c fix(server): show and update the provider CLI its agents launch
The installation contract found the CLI on the daemon's PATH, while agents
spawn the bare command with the provider's environment. A provider whose env
sets PATH could launch one copy and show and update another, so an update
succeeded while new agents kept the old version. The CLI is now resolved with
the provider's environment.

The section test's check-state table now always names the text it expects, so
no case can skip its assertion.
2026-11-14 10:04:21 +01:00
Mohamed Boudra b152308340 fix(app): keep a running update's progress visible whatever the inspection reads
Update carries the update's progress, but its row rendered only while the inspection read
"installed". An inspection that ran during the update (on reopen or Refresh) could read loading,
not installed or failed while the binary was replaced, and the sheet then showed nothing about the
running update. The Updates row now stays while an update runs.
2026-11-14 09:39:41 +01:00
Mohamed Boudra 2bd55c5ff7 fix(app): show a provider update's progress on its Update button
The pressed button carries an action's progress everywhere else in Settings: Button's own
loading state with a present-participle label, as Browser data's Clear and Project settings'
Save do. Update now does the same, reading "Updating..." from the tap until the update settles,
and the update's row holds only the output while it runs, then the result. This replaces the
row-owned spinner from the previous commit, which no other surface uses.

The installation's in-flight labels use three dots like their siblings.
2026-11-14 09:39:41 +01:00
Mohamed Boudra f7a442f4d4 fix(app): show one progress indicator per provider update and refresh
While an update ran, the Update button and the update's row each showed a spinner. The button's
spinner also widened it, and the row's leading spinner shifted the title when the update settled.
The update's row now owns progress from the tap until the update settles: it shows the update
starting before the host answers, so the indicator never moves, and the Update button only
disables.

Refresh blanked the Installation rows while the provider was asked again, then moved "Checking…"
from the Version row to the Updates row. The rows now keep their last answers until the new ones
arrive, and the Refresh button shows the refresh until both the models and the installation are
read again.
2026-11-14 09:39:41 +01:00
Mohamed Boudra 1f79e07feb fix(app): let update output scroll inside the provider sheet on Android
The output box is a ScrollView nested in the sheet's scrolling body. Android hands the drag to the outer ScrollView unless the inner one sets nestedScrollEnabled, so only the last 240px of a long update's output was readable. The tool-call detail views set the same flag.
2026-11-14 09:39:41 +01:00
Mohamed Boudra c7f55fd13f feat(app): offer provider updates whether or not an update check answers
Update and Update instructions lived inside the row that appeared only after
checkForUpdates answered, so Copilot and OpenCode, which declare update but no
check, never offered either. A check is a convenience: the Updates row now
shows for an installed provider that offers an update, keeps Update or Update
instructions in place in every check state (none, checking, up to date,
available, couldn't check), and shows what the check knows as a hint beside
it. A provider that offers no update still shows the check's answer once it
has one. The daemon already ran update without a check; a test now says so.
2026-11-14 09:39:41 +01:00
Mohamed Boudra 7349b26b56 test(app): keep the custom model check sensitive to a Remove button pushed off the sheet
scrollIntoViewIfNeeded on the Remove button scrolled the overflow-hidden model
card sideways too, so the check passed with the long-id layout fix undone.
Scroll only the Custom models heading into view, which moves the sheet
vertically and leaves the card at scrollLeft 0. With the layout fix undone the
spec now fails at 1200px and 390px again.
2026-11-14 09:39:41 +01:00
Mohamed Boudra 0d9cf2b982 test(app): scroll custom model rows into view before checking them
The provider sheet now shows an Installation section above the model
lists. At 390x1000 the custom model row sits under the sheet footer
until scrolled. The spec checks that a long model id leaves its Remove
button reachable. It had assumed the row needed no vertical scroll.
2026-11-14 09:39:41 +01:00
Mohamed Boudra dc4379ee01 fix(muse): report the build the update check compares
Paseo reuses a cached update check while inspect reports the same
version string. Muse reported 1.4.18 but compared its build
(1.4.18-R8600.1), so a new build of the same release kept the stale
"Update available" for up to an hour. The contract docs now say to
include everything the check compares in the reported version.
2026-11-14 09:39:41 +01:00
Mohamed Boudra 8e0a18f595 fix(providers): share one update check when two clients reopen after a version change 2026-11-14 09:39:41 +01:00
Mohamed Boudra b927be1bc7 test(app): assert provider installation states are visible 2026-11-14 09:39:41 +01:00
Mohamed Boudra e755886c4f fix(providers): keep update checks within their own deadline
Tying a cached check to its version made every check wait for a fresh
inspection, which could add the 20 s inspect deadline to the 25 s check
deadline. A check now never starts an inspection. It waits on one only
when the inspection is cached or already running and the check would
reuse a cached answer. When it asks the provider, it records the version
afterwards.
2026-11-14 09:39:41 +01:00
Mohamed Boudra 857808f7c9 fix(app): refresh provider version after an update settles while disconnected
The installation and update queries were invalidated only by a live
succeeded progress event. A connection dropped mid-update delivered the
settled operation as a snapshot on reconnect, which left the old version
and Update on screen. A success the view saw running now rereads them
whether it arrives as progress or as a snapshot.
2026-11-14 09:39:41 +01:00
Mohamed Boudra ad5e76b133 fix(providers): reuse a cached update check only for the version it answered
The previous fix dropped the cached check after an inspection settled
with a new version. On reopen the app sends inspect and check together,
so the check answered from the stale entry before the inspection
settled. A cached check now records the installed version it was
computed against and is reused only when the current inspection, shared
if in flight, reports the same version.
2026-11-14 09:39:41 +01:00
Mohamed Boudra d7e8099288 docs(providers): say when Update instructions shows 2026-11-14 09:39:41 +01:00
Mohamed Boudra 27bbf5355b fix(providers): keep update checks in step with the installed version
A conclusive check is cached for an hour and was not tied to the version
it answered for. After a CLI updated outside Paseo, settings showed the
new version and still offered Update to it. When an inspection reports a
different version, the cached check is dropped. Versions are compared
for equality, so they stay opaque.

The release comparison dropped prerelease suffixes, so Codex
0.200.0-alpha.1 looked current against 0.200.0. A prerelease now comes
before the release with the same numbers. Two different prereleases of
the same release are reported as unknown.
2026-11-14 09:39:41 +01:00
Mohamed Boudra 3536689ffb fix(app): bound update output and show refresh failures in provider settings
The screen appended every progress chunk with no limit while open, so a
noisy updater grew memory and never showed the truncation note that a
reopened screen shows. Progress now folds with the daemon's 64 KiB limit.

A manual refresh stored its result and failure outside the queries the
screen reads, so a failed refresh brought back the old answer with no
warning. Refresh now runs through those queries. It passes staleTime 0
because the app's default staleTime of Infinity would otherwise answer
from the cache.

The not-connected error uses the translated string the i18n check
requires.
2026-11-14 09:39:41 +01:00
Mohamed Boudra 322c542eaf chore(protocol): mark provider installation as shipping in v0.17.0
main is on the 0.16 beta series, and a promotion ships the tested beta's
content without pulling from main, so this lands in the next minor.
2026-11-14 09:39:40 +01:00
Mohamed Boudra fa8dcb372a docs(providers): document the provider installation contract
Plugin authors get the contract in the provider guide, with a worked
example that reports a version, checks for an update and runs the CLI's
own updater, and every field, deadline and cache in the reference.
The internal provider and plugin docs record why the three callbacks are
separate, that versions are opaque, that Paseo adds no verification to
an update, and how the plugin bridge carries and cancels each request.
2026-11-14 09:39:40 +01:00
Mohamed Boudra 59ab8b8c1f feat(providers): report installation for the remaining providers
Copilot, OpenCode, Pi, Oh My Pi, Antigravity and Hoplite now show an
install link and the installed version in provider settings. Each one
declares only what its CLI offers:

- Update checks ask the source the CLI's own updater reads: Pi's
  latest-version endpoint, `omp update --check`, and Hoplite's
  latest.json. Copilot and OpenCode resolve their release inside the
  binary, so they declare no check.
- Updates run the CLI's own command: `copilot update`, `opencode
  upgrade`, `pi update --self` (leaves Pi packages alone), `omp update`.
  Antigravity and Hoplite document no self-update.

OpenCode's success message asks for a daemon restart, because all
OpenCode agents share one server that keeps running the old version.
2026-11-14 09:39:40 +01:00
Mohamed Boudra 75a1ccdcee feat(providers): run provider updates from provider settings
Providers can declare `update(context)`, and the Installation section shows an Update
button when an update is available. The daemon owns the operation: one per provider,
joined by later requests, kept in memory past client disconnects, streamed to subscribers
through an owned subscription, and aborted only when the daemon stops. The provider's
answer is the outcome; the daemon adds no verification. After success it drops the cached
inspection and update check and refreshes discovery, without restarting agents.

Codex and Claude run their own `update` subcommand and pass the output through. Muse has
no update subcommand, so it does not declare one.

Updater output is capped at 64 KiB per update so a chatty updater cannot grow daemon memory.
Starting an update requires daemon.manage because it runs commands on the host.
2026-11-14 09:39:40 +01:00
Mohamed Boudra 4b67d035ce feat(providers): show available updates in provider settings
Providers can now declare `installation.checkForUpdates`, returning
`current`, `available` with opaque `versions` and `message`, or `unknown`.
The provider decides what counts as newer; Paseo shows its answer as
written and never parses or compares versions.

The check is its own RPC, `provider.installation.check_updates`, so the
installed version never waits on a network lookup. The daemon caches a
conclusive answer for an hour and an inconclusive one for 30s, shares
in-flight calls, and deadlines the call at 25s, below the plugin RPC
timeout. A throw or timeout comes back as `error`, which the app shows as
inconclusive, never as up to date. The sheet's Refresh bypasses the cache.

Codex and Claude Code read the release source their own updaters use:
the Homebrew cask for cask installs, otherwise the GitHub latest release
for Codex and the configured `autoUpdatesChannel` for Claude Code.
`codex doctor --json` reports the same answer but scans local state and
took close to a minute, so it is not used. Muse compares its build with
the launcher's channel manifest, the same rule the launcher updates by.

The install link now shows whenever the provider declares `installUrl`
and is not reported installed: the Install button for `not_installed`, a
quieter "Install instructions" link when the check failed or the
provider only links to a guide.
2026-11-14 09:39:40 +01:00
Mohamed Boudra 5afbd0d7d3 feat(providers): show installed version and install link in provider settings
Providers can now declare `installation`: install and update links plus an
`inspect` callback that reports installed state and an opaque version string.
Built-in clients and plugin providers share one contract; plugins receive the
daemon-resolved launch with `resolved: false` when the executable is missing,
so they can report not installed instead of failing.

The daemon calls `inspect` only on the new
`provider.installation.inspect.request` RPC, never from availability probing,
discovery or session creation, so a slow version probe cannot delay agents.
Results are cached per client for 30s, deadlined at 20s, and links survive a
failed probe. The app gates the provider sheet's Installation row on
`server_info.features.providerInstallation`, so older hosts show nothing new.
2026-11-14 09:39:40 +01:00
d30aa16beb Retrying a message that failed before reaching the provider delivers it (#9580)
* fix(server): let a message rejected before dispatch be retried

A send_agent_message_request with a messageId wrote its pending receipt
before loading the agent, setting its mode, and starting the run. When one
of those steps failed, nothing reached the provider, yet every retry with
the same messageId reported agent_request_outcome_unknown.

The pending receipt is now written at the dispatch boundary: the send
awaits beforeDispatch after the agent is loaded and its mode is set, just
before the prompt is handed to a run. A failure before that point leaves
no receipt, so the retry submits the message once. Failures after it stay
ambiguous, as before.

Closes #9297

Co-authored-by: tmad4000 <1430007+tmad4000@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(server): lock that a send failing after dispatch is never resubmitted

Scope the docs/hub.md retry sentence to direct sends: agent-sourced sends
still write their receipt before queueing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(hub): scope the retry promise to failures before the run starts

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(hub): name run startup as the ambiguous boundary

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: tmad4000 <1430007+tmad4000@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 08:10:41 +00:00
Mohamed Boudra a6a37b568d fix(app): correct composer glyph and placeholder tones (#9608)
* fix(app): mute labelled toolbar glyphs to match their labels

Touch-sized composer glyphs rested at foreground while the label beside them used foregroundMuted. Use the existing label/icon glyph roles: a labelled glyph takes the muted tone, while an icon-only glyph keeps the foreground header-icon treatment from #8909.

* test(app): keep toolbar tone coverage in the browser journey

The component-level probe asserted the color prop handed to a stub icon in JSDOM, which the testing rules forbid. The real-browser journey already checks the rendered stroke and label colors for both glyph roles.

* test(app): expect the muted tone for a labelled toolbar glyph

The composer layout test still asserted the old foreground tone for the label role.

* fix(app): quiet the composer placeholder to extra muted

The empty composer painted its placeholder with surface4, a surface token, instead of a text tone. Use foregroundExtraMuted so it sits below foregroundMuted and above the background, and document the composer-specific exception.

* test(app): clean up a composer tone fixture when setup fails

The helper now releases the seeded agent and repository if navigation or the readiness check throws before the test owns cleanup.
2026-11-14 13:44:33 +07:00
Mohamed Boudra 93d21e5612 Preserve the mobile sidebar when returning from Settings (#9641)
* fix(app): preserve mobile sidebar continuity through Settings

Retain the sidebar for the Settings visit so Back resumes the original
navigation surface without a new drawer animation. Native screen appearance
owns the handoff because pathname and layout updates precede presentation.

* fix(app): keep settings navigation imports lightweight

Keep the Settings visit state accessible without loading native presentation hooks, and exercise continuity with a scrolled list and complete paint capture.
2026-11-14 13:27:02 +07:00
Mohamed Boudra caae991a0f Keep sidebar toasts and bottom scrolling stable (#9639)
* fix(app): keep sidebar toast dismissal and bottom scrolling stable

Keep the positioned toast surface mounted through its native exit so its bottom anchor cannot collapse beneath the fading card. Reserve scrollable space below the final sidebar row without changing the scroll range when a toast appears.

* fix(app): preserve toast safety across themes and sidebar groups

Keep animated positioning in static React Native styles, extend the permanent scroll clearance to status grouping, and bound recording analysis to the requested frames.

* fix(app): preserve the toast surface when content changes

Replacing upload and reconnect status toasts must update the existing surface. A per-toast key retained the old surface during its exit, duplicating messages and breaking continuity.
2026-11-14 13:26:56 +07:00
Mohamed Boudra 046ac7b339 fix(app): keep cached workspace commands available during refresh (#9642)
Branch status updates reset draft command queries and discarded usable catalogs. Invalidate them instead and share the session freshness policy so drafts refresh in the background.
2026-11-14 13:26:36 +07:00
Mohamed Boudra 6213df73dc Download files from unavailable previews (#9640)
* feat(app): download files from unavailable previews

* fix(app): download files outside the workspace
2026-11-14 13:06:42 +07:00
Mohamed Boudra 02d3a05d2b Let scrolling cancel sidebar press highlights (#9637)
* fix(app): let scrolling cancel sidebar press feedback

The independent native highlight gesture painted on finger-down before a tap was recognized and competed with Pressable for mouse clicks. Use the standard Pressable lifecycle with a short activation delay so scrolling cancels pending feedback.

* fix(app): show press feedback on the usage summary

The summary only styled hover, leaving touch presses without visual acknowledgement. Share the standard delayed press primitive and paint its pressed state before opening Usage.

* fix(app): keep floating action press feedback opaque

Press styles replace the surface background. Give floating actions a solid pressed fill rather than a translucent overlay tint, and verify held feedback and release through the standard pressable.
2026-11-14 12:13:45 +07:00
Mohamed Boudra 175f36d64a Keep foreground Codex commands out of background tasks (#9635)
* fix(codex): keep foreground commands out of background tasks

Codex lists live terminals before their initial tool call returns. Exclude commands owned by an active turn so ordinary shell calls do not flash the background-work pill, while preserving processes left running by earlier turns.

* fix(codex): preserve foreground ownership during resume

Start terminal inventory ownership before installing notification handlers so autonomous commands emitted during thread resume remain foreground until their turn settles. Use named fields for the new inventory inputs.
2026-11-14 12:13:07 +07:00
Mohamed Boudra dd2281d82c fix(app): shorten reconnecting toast text (#9636) 2026-11-14 12:12:50 +07:00
Mohamed BoudraandNathan Green 2a9395e2d1 Light plugin themes and Pure Black keep their selected and hovered rows readable (#9579)
* fix(app): derive theme states and plugin fills so light and Pure Black themes stay readable

Hover, selected, the neutral fill and tertiary text were colors a theme
picked by eye, and plugin palettes filled them by borrowing `ring` and
`border`. A light plugin theme got a dark selected row under dark text,
Pure Black's hover barely separated from its surface, and light terminal
ANSI white was white on white.

States are now fixed WCAG-contrast steps from the surface they sit on,
toward the foreground, derived in styles/derive-colors.ts. Plugin
themes derive their neutral fill and tertiary text instead of aliasing
`ring` and `border`, and may set an optional `sidebar` color. The web
focus outline follows the theme's `ring`, and light terminal white and
bright white are derived to read on the background. Tokens with no
consumers are removed.

Existing plugin themes change look with no author action, and the
composer placeholder uses foregroundMuted like every other placeholder.

Co-authored-by: Nathan Green <342098+nathansgreen@users.noreply.github.com>

* fix(app): accept alpha hex in plugin theme colors when deriving

The plugin schema accepts #rgba and #rrggbbaa, but contrast derivation parsed
only opaque hex and threw, which would crash rendering for such a theme.
Derivation now reads those colors as the opaque color they sit on.

* fix(app): keep derived plugin fills and tertiary text readable on low-contrast palettes

A fixed contrast step for the neutral fill left text on message bubbles, secondary
buttons and badges at 2.6:1 on a dark palette whose body text is 4.75:1, and the
fixed fade made Solarized Light tertiary text 1.92:1. The fill step is now bounded by
the text it carries and tertiary text has a floor. The plugin reference states the
minimum Paseo version for sidebar and that the terminal white is derived on light
themes only.

* fix(app): keep the derived neutral fill visible when a theme's own text is quiet

Bounding the fill by text contrast could reach a step of 1 or less on a palette whose
body text is under about 3:1, returning the page background itself. The step now has a
minimum.

* docs(app): state the trade-off between the neutral fill step and text contrast

Below about 3.8:1 body text the fill keeps its minimum step and text on it falls under
3:1. The comment now says so and a test pins both outcomes.

* fix(app): leave the light terminal's ANSI white as it was

ANSI white is both text and a cell background, so no single palette value is readable in
both roles; making it readable as text broke black text on white cells. That needs a
contrast rule in the terminal renderer, so light white and bright white return to their
previous values and the derivation and its test floors are removed.

* feat(plugins): make derived theme colors overridable

Sidebar passive text was derived against the page even though timestamps render on hover and selected surfaces. Derive it against the resolved state surface and let contributed themes override each derived semantic role explicitly.

---------

Co-authored-by: Nathan Green <342098+nathansgreen@users.noreply.github.com>
2026-11-14 10:35:43 +07:00
Mohamed BoudraandJosh 85ce1aa828 fix(app): preserve settings scroll through appearance changes (#9605)
Preserve settings scroll and form edits across appearance changes while refreshing numeric typography at text and input leaves. Normalize displayed font sizes explicitly after commits.

Closes #9600
Closes #6931
Closes #6915

Co-authored-by: Josh <joshuaamayer@gmail.com>
2026-11-14 10:33:50 +07:00
226 changed files with 11962 additions and 3078 deletions
+13 -11
View File
@@ -20,7 +20,7 @@ A semantic element used in three or more places is a primitive. One of a kind is
Primitives live in `packages/app/src/components/ui/` and `packages/app/src/components/headers/`. Card and row layout live in `packages/app/src/styles/settings.ts`. Section structure lives in `packages/app/src/screens/settings/settings-section.tsx`.
A pressable styled to look like a button is wrong; the button is `<Button>` (`packages/app/src/components/ui/button.tsx`). A pressable wrapping an icon is wrong; the icon action is `<ToolbarButton>` (`packages/app/src/components/ui/pane-content-toolbar.tsx`), which owns the hitbox, the rounded `interactionHighlight` fill on hover and press, the compact size, and the tooltip. Rows on a menu surface are `<MenuItem>`, or `<ComposerTrackRow>` in a track panel; other rows are `<PressHighlight>` (`packages/app/src/components/ui/press-highlight.tsx`), which flashes on native the moment a finger lands. A bare `<Text>` styled to look like a section header is wrong; the section header is `<SettingsSection>` (`packages/app/src/components/settings/headings/settings-section.tsx`). A docs link in its header is its `link` prop, which renders `Label ↗` on the title's rail; a ghost button with an arrow is wrong. A custom `Modal` for a confirmation is wrong; the confirmation is `confirmDialog` (`packages/app/src/utils/confirm-dialog.ts`). A hand-rolled overflow menu is wrong; the menu is `<DropdownMenu>` (`packages/app/src/components/ui/dropdown-menu.tsx`). A hand-rolled status pill is wrong; the pill is `<StatusBadge>` (`packages/app/src/components/ui/status-badge.tsx`). A circle pinned over a scrolling surface is wrong; the floating action is `<FloatingActionButton>` (`packages/app/src/components/ui/floating-action-button.tsx`), one per surface, and the surface reserves `FLOATING_ACTION_BUTTON_CLEARANCE` below its content so the button never traps the last row.
A pressable styled to look like a button is wrong; the button is `<Button>` (`packages/app/src/components/ui/button.tsx`). A pressable wrapping an icon is wrong; the icon action is `<ToolbarButton>` (`packages/app/src/components/ui/pane-content-toolbar.tsx`), which owns the hitbox, the rounded `interactionHighlight` fill on hover and press, the compact size, and the tooltip. Rows on a menu surface are `<MenuItem>`, or `<ComposerTrackRow>` in a track panel; other rows are `<PressHighlight>` (`packages/app/src/components/ui/press-highlight.tsx`), which uses React Native’s press lifecycle on native with a short press delay so scrolling cancels pending feedback. A bare `<Text>` styled to look like a section header is wrong; the section header is `<SettingsSection>` (`packages/app/src/components/settings/headings/settings-section.tsx`). A docs link in its header is its `link` prop, which renders `Label ↗` on the title's rail; a ghost button with an arrow is wrong. A custom `Modal` for a confirmation is wrong; the confirmation is `confirmDialog` (`packages/app/src/utils/confirm-dialog.ts`). A hand-rolled overflow menu is wrong; the menu is `<DropdownMenu>` (`packages/app/src/components/ui/dropdown-menu.tsx`). A hand-rolled status pill is wrong; the pill is `<StatusBadge>` (`packages/app/src/components/ui/status-badge.tsx`). A circle pinned over a scrolling surface is wrong; the floating action is `<FloatingActionButton>` (`packages/app/src/components/ui/floating-action-button.tsx`), one per surface, and the surface reserves `FLOATING_ACTION_BUTTON_CLEARANCE` below its content so the button never traps the last row.
Before adding a new component, read `components/ui/`. The primitive usually exists.
@@ -40,9 +40,11 @@ Weight has three tiers, applied by role:
The rule, condensed: text that _names_ a surface or a group is `medium`. Text that lives _inside_ a surface or a group is `normal`. Top-of-screen titles are `<ScreenTitle>`, which is lighter still.
Foreground is for the thing being acted on: row titles, section headings, the selected sidebar item. `foregroundMuted` is for context: hints, descriptions, secondary metadata, idle sidebar items, placeholders, status text.
Foreground is for the thing being acted on: row titles, section headings, the selected sidebar item. `foregroundMuted` is for context: hints, descriptions, secondary metadata, idle sidebar items, placeholders, status text. The composer's empty placeholder is quieter; it uses `foregroundExtraMuted`.
`foregroundExtraMuted` is reserved for passive chrome that must sit behind muted text, such as an always-visible window control. Use the solid token instead of lowering SVG opacity; per-path opacity makes overlapping icon strokes render unevenly. Interactive hover and pressed states return to `foreground`.
`foregroundExtraMuted` is reserved for passive chrome that must sit behind muted text, such as an always-visible window control, and for the composer's empty placeholder. Use the solid token instead of lowering SVG opacity; per-path opacity makes overlapping icon strokes render unevenly. Interactive hover and pressed states return to `foreground`.
A theme states places and identity; `packages/app/src/styles/derive-colors.ts` derives their relationships. Sidebar hover and selected fills step from the sidebar toward the foreground. For plugin themes, passive text on those states derives against the actual state surface; page tertiary text is a separate relationship. Explicit plugin semantic overrides take precedence over derived defaults. Built-in themes retain their chosen passive text. `packages/app/src/styles/theme-contrast.test.ts` checks the built-in and representative plugin palettes against contrast floors.
Accent is the one CTA per surface. A `<Button variant="default">` filled with `accent` appears at most once on a page. Most pages have zero — settings is mostly toggles and text, the workspace pane is mostly content, the chat composer is the input itself.
@@ -70,7 +72,7 @@ the sidebar. Apply it as `backgroundColor`; setting `opacity` on the control als
Controls come in two sizes, defined once in `control-geometry.ts`. The default is the right size almost everywhere — pages, dialogs, forms, settings rows, the setup flow — so don't pass a size. It is 32px tall where a pointer drives it and 44px where controls are touch-sized, so every touch control meets the iOS HIG's 44pt hit region. `sm` is 28px pointer and 32px touch, with `fontSize.sm` labels, and is for tight chrome only: toolbars, nested settings rows, dense inline row actions. A `size="sm"` on an ordinary page or dialog is wrong, and so is choosing a size from `useIsCompactFormFactor()`.
Dense toolbar rows, such as the composer's, are the exception to the 44pt control. Touch-sized the row is 44pt tall and each control is a 36pt circle (`TOOLBAR_DISC_SIZE`): send and stop fill it, and every other control's pressed highlight fills it, so every highlight is the same fully rounded shape. Labelled pickers are 36pt pills. A control lays out at its full highlight (`toolbarSlot`, `toolbarContentSlot`) with no gap between controls (`TOOLBAR_CONTROL_GAP`), so neighbouring highlights touch and never overlap. Toolbar glyphs match the header icons: 20pt, the app's 1.5px stroke, resting at `foreground` (`toolbarGlyphsFor`). The context ring is 18pt with a 2px stroke (`TOOLBAR_RINGS`): a circle fills its box where an outline glyph does not, and a thin circle reads lighter than a glyph at the same stroke. A disc's solid glyph, such as the stop square, stays at the `md` size (`TOOLBAR_DISC_GLYPH_SIZES`). Pointer-sized toolbars keep 28px controls, a 4px gap, and a 16pt muted glyph that brightens on hover.
Dense toolbar rows, such as the composer's, are the exception to the 44pt control. Touch-sized the row is 44pt tall and each control is a 36pt circle (`TOOLBAR_DISC_SIZE`): send and stop fill it, and every other control's pressed highlight fills it, so every highlight is the same fully rounded shape. Labelled pickers are 36pt pills. A control lays out at its full highlight (`toolbarSlot`, `toolbarContentSlot`) with no gap between controls (`TOOLBAR_CONTROL_GAP`), so neighbouring highlights touch and never overlap. Touch-sized toolbar glyphs are 20pt at the app's 1.5px stroke. An icon-only control's glyph matches the header icons and rests at `foreground`; a glyph beside a label rests at `foregroundMuted` so the two read as one quiet unit (`toolbarGlyphsFor`). The context ring is 18pt with a 2px stroke (`TOOLBAR_RINGS`): a circle fills its box where an outline glyph does not, and a thin circle reads lighter than a glyph at the same stroke. A disc's solid glyph, such as the stop square, stays at the `md` size (`TOOLBAR_DISC_GLYPH_SIZES`). Pointer-sized toolbars keep 28px controls, a 4px gap, and a 16pt muted glyph that brightens on hover.
In the composer, the first glyph's ink starts on the text column's edge, and the trailing control is always a disc, so the row does not shift as it changes between voice mode, send and stop. The disc nests into the corner, as far from the right edge as from the bottom, and touch-sized the composer's corner radius is concentric with it (`packages/app/src/composer/input/toolbar-rails.ts`). Touch-sized the disc keeps a 6pt clearance from its neighbour, because it is always painted and a pressed neighbour would merge with it. The attach button sits 2pt closer to the picker than its highlight would put it: the plus is all thin arms, so the full gap reads wide. That offset is set by eye.
@@ -130,7 +132,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. 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. 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 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.
@@ -203,11 +205,11 @@ Terminology:
## 11. States
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.
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.
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/screens/settings/providers-section.tsx:115-119`).
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`.
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.
@@ -229,13 +231,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`).
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.
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.
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 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`).
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`).
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`).
@@ -267,7 +269,7 @@ New status pills use `<StatusBadge>`. Identity, shortcut, and interactive link b
- A "Settings" CTA on a detail page. Detail pages are settings; settings is reached from the sidebar, the host entry, or a row's kebab menu.
- The word "checkout" in UI strings or identifiers. The term is "workspace".
- New color tokens or hardcoded hex outside the palette. The identity color table is the documented exception (§13), not a license.
- Placeholder text dimmed beyond `foregroundMuted`. No extra opacity, no italics, no ghost-text.
- Placeholder text dimmed beyond `foregroundMuted`, except the composer's empty placeholder, which uses `foregroundExtraMuted`. No extra opacity, no italics, no ghost-text.
- `onPointerEnter` and `onPointerLeave`. They do not fire on native iOS. Hover uses Pressable's `onHoverIn`/`onHoverOut` gated with `isHovered || isCompact || isNative`.
- Raw DOM APIs without an `isWeb` guard.
- Spacing values outside the scale. `padding: 20` and `gap: 10` are wrong.
@@ -284,7 +286,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/screens/settings/providers-section.tsx` |
| Detail card+row | `packages/app/src/screens/settings/host-page.tsx`, `packages/app/src/provider-settings/internal/provider-list.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` |
+4
View File
@@ -61,6 +61,10 @@ The daemon journals the assigned agent ID before creation. Concurrent retries sh
and a retry after a lost acknowledgement or restart returns the durable agent without creating a
workspace or starting a turn. Deleting that agent does not make its old creation key reusable.
Confirmed message delivery is also journaled, so retrying its message ID does not submit it again.
A direct send (one without `sourceAgentId`) rejected before its prompt is handed to a run, for
example because the agent could not be loaded or the requested mode could not be set, leaves no
receipt, so retrying its message ID submits it. A failure during or after run startup is treated
as an unfinished delivery.
An unfinished delivery after restart reports `agent_request_outcome_unknown`: a provider can have
accepted a prompt before the daemon recorded success, so automatic resubmission could duplicate
work. Inspect the agent before choosing a new message ID. Receipts contain identity and request
+13 -4
View File
@@ -27,9 +27,17 @@ interface MobilePanelSelection {
Every semantic target change increments `revision`. Repeating the current target is idempotent.
Compact panel selection is not persisted; a cold start begins at `agent`.
Only an overlay sidebar holds `agent-list`, and only a compact layout holds `file-explorer`. App
chrome publishes the layout (compact or wide, and the left sidebar presentation `overlay`, `dock`, or
`hidden`) to `panel-store`, which drops any target the layout does not present. A stale
An overlay sidebar holds `agent-list`, and only a compact layout holds `file-explorer`.
A compact Settings visit entered from the sidebar suspends it: the host stays mounted and
laid out on native. Its target and scroll position survive until return to the originating
workspace. Route changes and `onLayout` both precede native screen appearance, so the sidebar
stays visible until Settings emits the native navigator's `transitionEnd`. Web uses layout.
Input and activity stop during the handoff. Widening or leaving for another destination discards
the return. Commands issued while suspended settle immediately behind Settings, so explicit
agent navigation does not reveal a closing sidebar animation.
App chrome publishes the layout (compact or wide, and the left sidebar presentation `overlay`,
`dock`, `hidden`, or `suspended`) to `panel-store`, which drops any target the layout does not present. A stale
`agent-list` would reopen the overlay on the next collapse; a stale `file-explorer` after widening
would block the navigation swipe, which begins only from `agent`.
@@ -120,7 +128,8 @@ definition, no longer eligible to begin.
the overlay host fills the window.
- The overlay's backdrop covers the whole window; safe-area padding applies to the sidebar and
workspace content only. It closes by swiping back, tapping the backdrop, or picking a destination:
every sidebar destination closes the overlay before it navigates.
workspace destinations close the overlay before navigating. Settings suspends the compact
sidebar for the duration of its visit instead.
- Animated panel nodes use React Native static styles plus inline theme values. Do not attach
Unistyles-generated styles to those nodes; Unistyles and Reanimated patching the same Fabric node
has caused native crashes.
+12
View File
@@ -510,6 +510,18 @@ 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,
+44
View File
@@ -263,6 +263,50 @@ 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 or compares them.
- `checkForUpdates` asks the source the CLI's own updater reads, such as the vendor's release
endpoint or the CLI's `update --check`. 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, so the app asks only after `inspect` reports the CLI installed, and a conclusive answer
holds for an hour while `inspect` reports the same version string. Report every part of the version
the check compares, such as Muse's build, or a CLI updated outside Paseo keeps its stale answer. `update` runs for minutes, streams output, and is aborted only when the daemon
stops.
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
@@ -346,7 +346,7 @@ Gotchas:
- **Narrow the discriminated union before spreading.** `updateTheme`'s updater returns the theme union; spreading the union widens `colorScheme` to `"light" | "dark"`, which is assignable to neither concrete member. Branch on `t.colorScheme` so each branch spreads a single narrowed theme type (no `as`).
- **`lineHeight.diff` is the code/diff line-height axis** — it is coupled to the code-font-size control (≈ `codeFontSize * 1.5`). Do NOT use it for prose. Markdown body line-height scales with content size (`Math.round(theme.fontSize.content * 1.4)`); routing prose through `lineHeight.diff` clips text at small code sizes.
- **High-churn draft values** (live-while-typing in the appearance preview) bypass the theme: apply them as inline styles marked with `inlineUnistylesStyle` so per-keystroke values don't grow the `#unistyles-web` CSS registry.
- **Web numeric appearance tokens need a render; native tracked styles update in place.** On web, string tokens such as colors become CSS variables, but numeric tokens (font sizes, line heights) are baked into generated classes. `AppearanceStyleBoundary` remounts web shell chrome and explorer content to refresh those classes. Native sidebars and explorer hosts stay outside appearance keys: their gesture refs outlive detached dependents until Gesture Handler's passive cleanup, so remounting a related gesture can query an unmounted view. Their tracked native styles and existing themed leaf props update without replacing the gesture hosts or draggable lists. Parsed PR markdown uses its own `withUnistyles` style mapping.
- **Web numeric appearance tokens need a render; native tracked styles update in place.** On web, string tokens such as colors become CSS variables, but numeric tokens (font sizes, line heights) are baked into generated classes. `AppearanceStyleBoundary` remounts web shell chrome and explorer content to refresh those classes. Settings retains its screen and form; `AppearanceText` refreshes numeric text styles at the leaf, and its font fields use `withUnistyles` to refresh input styles without replacing the inputs. Native sidebars and explorer hosts stay outside appearance keys: their gesture refs outlive detached dependents until Gesture Handler's passive cleanup, so remounting a related gesture can query an unmounted view. Their tracked native styles and existing themed leaf props update without replacing the gesture hosts or draggable lists. Parsed PR markdown uses its own `withUnistyles` style mapping.
- **Appearance keys belong below native lifetime owners.** `ThemedStack` wraps screen content through `screenLayout`, preserving navigator identity; nested navigators are listed in `nestedNavigatorScreens` and own their own screen boundaries. The remaining shell surfaces retain their appearance refresh separately from native panel hosts. A key above a native stack can detach its screen container inside a FragmentManager transaction during settings hydration. Keep both navigators and retained panel gesture hosts outside those keys. `applyAppearance` patches the active theme before inactive registry entries so subscribers receive the committed values in the same update. Do not add local appearance keys or a boundary above a navigator.
- **Dynamic font tokens stay widened.** `fontFamily`, `fontSize`, and `lineHeight` on `commonTheme` are annotated `string`/`number` (not narrowed by `as const`) so the updater's return assigns; the platform default stacks live in `DEFAULT_UI_FONT_STACK` / `DEFAULT_MONO_FONT_STACK`.
@@ -15,7 +15,8 @@ import {
expectProviderInstalledInSettings,
findAcpCatalogProvider,
installAcpCatalogProvider,
openAddProviderArea,
openAddProvider,
openProviderDetail,
openSettingsHost,
openSettingsHostSection,
seedSavedSettingsHosts,
@@ -47,7 +48,7 @@ test.describe("ACP provider catalog", () => {
await openSettings(page);
await openSettingsHost(page, getServerId());
await openSettingsHostSection(page, getServerId(), "providers");
await openAddProviderArea(page);
await openAddProvider(page);
await installAcpCatalogProvider(page, ACP_PROVIDER.name);
await expectProviderInstalledInSettings(page, ACP_PROVIDER.name);
@@ -69,7 +70,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 openAddProviderArea(page);
await openAddProvider(page);
await findAcpCatalogProvider(page, "fx");
await page.screenshot({ path: testInfo.outputPath("fx-catalog.png") });
@@ -104,7 +105,7 @@ for (const theme of ["light", "dark"] as const) {
await expect(
page.getByRole("button", { name: "Hoplite provider details", exact: true }),
).toHaveCount(0);
await openAddProviderArea(page);
await openAddProvider(page);
await findAcpCatalogProvider(page, "Hoplite");
await page.screenshot({ path: testInfo.outputPath(`hoplite-catalog-${theme}.png`) });
await installAcpCatalogProvider(page, "Hoplite");
@@ -127,7 +128,7 @@ for (const theme of ["light", "dark"] as const) {
testInfo.outputPath(`hoplite-removed-${theme}.json`),
JSON.stringify(await client.getProvidersSnapshot(), null, 2),
);
await openAddProviderArea(page);
await openAddProvider(page);
await findAcpCatalogProvider(page, "Hoplite");
await page.screenshot({ path: testInfo.outputPath(`hoplite-removed-${theme}.png`) });
await installAcpCatalogProvider(page, "Hoplite");
@@ -140,11 +141,11 @@ for (const theme of ["light", "dark"] as const) {
}
async function removeHoplite(page: import("@playwright/test").Page): Promise<void> {
await page.getByTestId("provider-actions-hoplite").click();
await openProviderDetail(page, "Hoplite");
page.once("dialog", (dialog) => {
void dialog.accept();
});
await page.getByTestId("provider-remove-hoplite").click();
await page.getByTestId("provider-remove").click();
}
test("unsupported host asks for an update without writing Hoplite config", async ({
@@ -164,7 +165,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 openAddProviderArea(page);
await openAddProvider(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.");
@@ -37,7 +37,7 @@ test("keeps the selected workspace visible in Light", async ({ page }, testInfo)
await row.click();
await expect(row).toHaveAttribute("aria-selected", "true");
await expect(row).toHaveCSS("background-color", "rgb(212, 212, 216)");
await expect(row).toHaveCSS("background-color", "rgb(212, 212, 213)");
await page.screenshot({
path: testInfo.outputPath("light-selected-workspace.png"),
fullPage: true,
@@ -64,7 +64,7 @@ test("keeps the selected workspace visible in Pure black", async ({ page }, test
await row.click();
await expect(row).toHaveAttribute("aria-selected", "true");
await expect(row).toHaveCSS("background-color", "rgb(17, 17, 17)");
await expect(row).toHaveCSS("background-color", "rgb(29, 29, 29)");
await page.screenshot({
path: testInfo.outputPath("pure-black-selected-workspace.png"),
fullPage: true,
@@ -2297,13 +2297,9 @@ async function changeCodeTypographyFromSettings(
await page.getByTestId("sidebar-settings").click();
await expect(page).toHaveURL(new RegExp(`${buildSettingsSectionRoute("general")}|/settings$`));
await page.getByRole("button", { name: "Appearance" }).click();
// A committed font change remounts the screen (AppearanceStyleBoundary), and the new form starts
// from the stored size. Edit the size only in the remounted form, or the remount drops it.
const sizeField = page.getByLabel("Code font size");
await sizeField.evaluate((field) => field.setAttribute("data-e2e-before-font-family", ""));
await page.getByLabel("Code font family").fill(typography.fontFamily);
await page.getByLabel("Code font family").press("Enter");
await expect(page.locator("[data-e2e-before-font-family]")).toHaveCount(0);
await sizeField.fill(String(typography.fontSize));
await page.getByLabel("Code font size").press("Enter");
await expect(page.getByLabel("Code font family")).toHaveValue(typography.fontFamily);
@@ -0,0 +1,131 @@
import { expect, test } from "../support/fixtures";
import { composerLocator, expectComposerVisible } from "../support/helpers/composer";
import {
composerControl,
expectGlyphMatchesLabel,
expectIconOnlyGlyph,
readComposerControlTone,
readComposerPlaceholderTone,
readComposerTextTone,
} from "../support/helpers/composer-toolbar-tone";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
const THINKING = "agent-thinking-selector";
const MODE = "mode-control";
const ATTACH = "message-input-attach-button";
const COMBINED_MODEL = "combined-model-selector";
async function openSeededComposer(
page: import("@playwright/test").Page,
repoPrefix: string,
readyTestId = MODE,
) {
const agent = await seedMockAgentWorkspace({
repoPrefix,
title: "Toolbar tone",
model: "ten-second-stream",
});
try {
await openAgentRoute(page, agent);
await expectComposerVisible(page);
await expect(composerControl(page, readyTestId)).toBeVisible({ timeout: 30_000 });
return agent;
} catch (error) {
await agent.cleanup();
throw error;
}
}
test.describe("Composer toolbar glyph tone", () => {
test.describe.configure({ timeout: 180_000 });
test.describe("on a touch screen", () => {
test.use({ hasTouch: true, viewport: { width: 1024, height: 1366 } });
test("a glyph beside its label matches the label while an icon-only glyph stays foreground", async ({
page,
}) => {
const agent = await openSeededComposer(page, "composer-tone-touch-");
try {
const thinking = await readComposerControlTone(composerControl(page, THINKING));
const mode = await readComposerControlTone(composerControl(page, MODE));
const attach = await readComposerControlTone(composerControl(page, ATTACH));
expectGlyphMatchesLabel(thinking, "thinking");
expectGlyphMatchesLabel(mode, "mode");
expectIconOnlyGlyph(attach, "attach");
expect(attach.glyph, "an icon-only glyph is brighter than a labelled glyph").not.toBe(
thinking.label,
);
} finally {
await agent.cleanup();
}
});
});
test.describe("on a compact non-touch window", () => {
test.use({ hasTouch: false, viewport: { width: 590, height: 844 } });
test("the icon-only thinking glyph stays foreground and the labelled mode glyph matches its label", async ({
page,
}) => {
const agent = await openSeededComposer(page, "composer-tone-compact-");
try {
const thinking = await readComposerControlTone(composerControl(page, THINKING));
const mode = await readComposerControlTone(composerControl(page, MODE));
const attach = await readComposerControlTone(composerControl(page, ATTACH));
expectIconOnlyGlyph(thinking, "thinking");
expectGlyphMatchesLabel(mode, "mode");
expectIconOnlyGlyph(attach, "attach");
expect(thinking.glyph, "the icon-only glyphs share one tone").toBe(attach.glyph);
expect(thinking.glyph, "an icon-only glyph is brighter than a labelled glyph").not.toBe(
mode.label,
);
} finally {
await agent.cleanup();
}
});
});
test.describe("on a folded compact non-touch window", () => {
test.use({ hasTouch: false, viewport: { width: 480, height: 844 } });
test("the empty composer placeholder is quieter than its labels", async ({ page }) => {
const agent = await openSeededComposer(page, "composer-tone-placeholder-", COMBINED_MODEL);
try {
const placeholder = await readComposerPlaceholderTone(composerLocator(page));
const extraMuted = await readComposerTextTone(
composerControl(page, "combined-model-selector-thinking-label"),
);
const muted = await readComposerTextTone(
composerControl(page, "combined-model-selector-model-label"),
);
expect(placeholder, "the composer paints a placeholder").not.toBeNull();
expect(extraMuted, "the folded thinking label paints the extra-muted tone").not.toBeNull();
expect(placeholder, "the placeholder uses the extra-muted tone").toBe(extraMuted);
expect(placeholder, "the placeholder is quieter than a labelled glyph").not.toBe(muted);
} finally {
await agent.cleanup();
}
});
});
test.describe("with a wide pointer", () => {
test.use({ hasTouch: false, viewport: { width: 1280, height: 800 } });
test("a labelled glyph stays muted and matches its label", async ({ page }) => {
const agent = await openSeededComposer(page, "composer-tone-pointer-");
try {
const thinking = await readComposerControlTone(composerControl(page, THINKING));
const mode = await readComposerControlTone(composerControl(page, MODE));
expectGlyphMatchesLabel(thinking, "thinking");
expectGlyphMatchesLabel(mode, "mode");
} finally {
await agent.cleanup();
}
});
});
});
@@ -3,6 +3,7 @@ import path from "node:path";
import type { Locator } from "@playwright/test";
import { expect, test, type Page } from "../support/fixtures";
import {
downloadFileFromPreview,
expandFolder,
openFileExplorer,
openFileFromExplorer,
@@ -141,6 +142,29 @@ async function seedAgentWithFileLink(input: LinkedFile) {
}
test.describe("CodeMirror workspace file editing", () => {
test("downloads an assistant-linked binary outside the workspace", async ({ page }, testInfo) => {
const filePath = testInfo.outputPath("outside.bin");
const source = Buffer.from([0, 1, 128, 255]);
await writeFile(filePath, source);
const session = await seedMockAgentWorkspace({
repoPrefix: "outside-binary-",
title: "Outside binary",
initialPrompt: "Show the file",
featureValues: { mockAssistantResponse: `[Open binary](${filePath})` },
});
try {
await openAgentRoute(page, session);
await openAssistantMarkdownLink(page, "Open binary");
const downloaded = await downloadFileFromPreview(page);
expect(downloaded.suggestedFilename()).toBe("outside.bin");
const savedFile = testInfo.outputPath("downloaded.bin");
await downloaded.saveAs(savedFile);
expect(await readFile(savedFile)).toEqual(source);
} finally {
await session.cleanup();
}
});
test("opens explicit screenshot links and explains missing files", async ({ page }) => {
const session = await seedMockAgentWorkspace({
repoPrefix: "screenshot-markdown-link-",
@@ -2,7 +2,12 @@ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
import path from "node:path";
import { expect, type Page } from "@playwright/test";
import { test } from "../support/fixtures";
import { downloadFileFromExplorer, openFileExplorer } from "../support/helpers/file-explorer";
import {
downloadFileFromExplorer,
downloadFileFromPreview,
openFileFromExplorer,
openFileExplorer,
} from "../support/helpers/file-explorer";
import { openChangesPanel } from "../support/helpers/workspace-tabs";
import { gotoWorkspace } from "../support/helpers/launcher";
import { daemonWsRoutePattern, getE2EDaemonPort } from "../support/helpers/daemon-port";
@@ -473,3 +478,21 @@ test("downloads a file over direct TCP with its original filename and bytes", as
expect(await downloaded.failure()).toBeNull();
expect(await readFile(savedFile)).toEqual(source);
});
test("downloads an unsupported binary from its preview with original filename and bytes", async ({
page,
}, testInfo) => {
const fileName = "rapport données.bin";
const source = Buffer.from([0, 1, 2, 127, 128, 255, 10]);
await writeFile(path.join(workspace.workspaceDirectory, fileName), source);
await gotoWorkspace(page, workspace.workspaceId);
await openFileExplorer(page);
await openFileFromExplorer(page, fileName);
const downloaded = await downloadFileFromPreview(page);
expect(downloaded.suggestedFilename()).toBe(fileName);
const savedFile = testInfo.outputPath(fileName);
await downloaded.saveAs(savedFile);
expect(await downloaded.failure()).toBeNull();
expect(await readFile(savedFile)).toEqual(source);
});
+54 -4
View File
@@ -6,6 +6,7 @@ import {
addProjectFromSetup,
continueSetup,
expectSetupStep,
expectSheetCoversSetupCard,
finishSetup,
goToSetupStep,
hostGivesAgentsPaseoTools,
@@ -23,6 +24,7 @@ import {
recordFirstLaunch,
setupModal,
setupPrimaryButton,
setupSheet,
showSetupAgainFromSettings,
skipSetup,
startSetupHost,
@@ -35,7 +37,11 @@ import {
import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate";
import { enableRelayAndExpectOffer } from "../support/helpers/pair-device";
import { seedWorkspace } from "../support/helpers/seed-client";
import { openSettingsHostSection } from "../support/helpers/settings";
import {
installAcpCatalogProvider,
openAddProvider,
openSettingsHostSection,
} from "../support/helpers/settings";
import { createTempDirectory, createTempGitRepo } from "../support/helpers/workspace";
// Midnight's muted foreground (#9a9db0), which the step description is drawn in.
@@ -59,11 +65,28 @@ 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 agents");
await expectSetupStep(page, "Your providers");
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");
@@ -103,6 +126,33 @@ 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");
@@ -145,7 +195,7 @@ test("changing the theme keeps the setup window in place on every step", async (
for (const title of [
"Welcome to Paseo",
"Your agents",
"Your providers",
"Add your projects",
"Let agents use Paseo",
"Take your agents with you",
@@ -418,7 +468,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 agents");
await step("Your providers");
await primary("Continue").click();
await step("Add your projects");
await primary("Continue").click();
@@ -5,6 +5,10 @@ import path from "node:path";
import { expect, test } from "../support/fixtures";
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
import { openSettingsSection } from "../support/helpers/settings";
import { seedMockAgentWorkspace, openAgentRoute } from "../support/helpers/mock-agent";
import { getServerId } from "../support/helpers/server-id";
import { contrastRatio } from "../../src/utils/color";
import type { Locator, Page } from "@playwright/test";
const PLUGIN_ID = "plugin-theme-e2e";
@@ -40,6 +44,16 @@ const PLUGIN_SOURCE = `export default function contribute(plugin) {
ring: "#9ca0b0",
},
});
for (const [id, name, overrides] of [
["solarized-dark", "Solarized Dark", {}],
["solarized-dark-custom", "Solarized Dark Custom", { sidebarSelected: "#334455", foregroundExtraMuted: "#ddeeff" }],
]) {
plugin.addTheme({ id, name, appearance: "dark", colors: {
background: "#002b36", foreground: "#839496", raised: "#073642",
control: "#073642", border: "#073642", accent: "#268bd2",
mutedForeground: "#586e75", ring: "#93a1a1", ...overrides,
}});
}
return () => {};
}`;
@@ -47,6 +61,88 @@ const PLUGIN_SOURCE = `export default function contribute(plugin) {
// contributed palette reached the semantic tokens rather than just the swatch.
const MOCHA_MUTED_FOREGROUND = "rgb(166, 173, 200)";
const LATTE_MUTED_FOREGROUND = "rgb(108, 111, 133)";
const LATTE_RING = "rgb(156, 160, 176)";
async function selectTheme(page: Page, name: string) {
await page.goto("/settings");
await openSettingsSection(page, "appearance");
const theme = page.getByRole("radio", { name, exact: true });
await expect(theme).toBeVisible({ timeout: 30_000 });
await theme.click();
await expect(theme).toBeChecked();
}
async function expectTimestampContrast(row: Locator) {
const timestamp = row.getByTestId("sidebar-workspace-timestamp");
await expect(timestamp).toBeVisible();
const hex = (rgb: string) =>
`#${rgb
.match(/\d+/g)!
.slice(0, 3)
.map((value) => Number(value).toString(16).padStart(2, "0"))
.join("")}`;
const background = await row.evaluate((element) => getComputedStyle(element).backgroundColor);
const foreground = await timestamp.evaluate((element) => getComputedStyle(element).color);
expect(contrastRatio(hex(background), hex(foreground))).toBeGreaterThanOrEqual(2.5);
}
test("keeps plugin workspace timestamps readable on state surfaces and honors overrides", async ({
page,
}) => {
const directory = await mkdtemp(path.join(tmpdir(), "paseo-plugin-theme-state-"));
const client = await connectNewWorkspaceDaemonClient({ ownProjects: false });
const previousConfig = await client.getDaemonConfig();
const selected = await seedMockAgentWorkspace({
repoPrefix: "theme-selected-",
title: "Selected theme workspace",
});
const hovered = await seedMockAgentWorkspace({
repoPrefix: "theme-hovered-",
title: "Hovered theme workspace",
});
await writeFile(
path.join(directory, "paseo-plugin.json"),
JSON.stringify({ id: PLUGIN_ID, requirements: pluginRequirements }),
);
await writeFile(path.join(directory, "index.client.ts"), PLUGIN_SOURCE);
try {
await client.patchDaemonConfig({ pluginsEnabled: true });
await client.installDirectoryPlugin(directory);
await selectTheme(page, "Solarized Dark");
await openAgentRoute(page, selected);
const selectedRow = page.getByTestId(
`sidebar-workspace-row-${getServerId()}:${selected.workspaceId}`,
);
const hoveredRow = page.getByTestId(
`sidebar-workspace-row-${getServerId()}:${hovered.workspaceId}`,
);
await expect(selectedRow).toHaveAttribute("aria-selected", "true", { timeout: 30_000 });
await page.mouse.move(0, 0);
await expect(selectedRow).toHaveCSS("background-color", "rgb(33, 58, 66)");
await expectTimestampContrast(selectedRow);
await hoveredRow.hover();
await expect(hoveredRow).toHaveCSS("background-color", "rgb(19, 50, 60)");
await expectTimestampContrast(hoveredRow);
await selectTheme(page, "Solarized Dark Custom");
await openAgentRoute(page, selected);
await page.mouse.move(0, 0);
await expect(selectedRow).toHaveCSS("background-color", "rgb(51, 68, 85)");
await expect(selectedRow.getByTestId("sidebar-workspace-timestamp")).toHaveCSS(
"color",
"rgb(221, 238, 255)",
);
} finally {
await client.removePlugin(PLUGIN_ID).catch(() => undefined);
await client
.patchDaemonConfig({ pluginsEnabled: previousConfig.config.pluginsEnabled ?? false })
.catch(() => undefined);
await client.close();
await selected.cleanup();
await hovered.cleanup();
await rm(directory, { recursive: true, force: true });
}
});
test("applies a contributed theme and falls back when its plugin is gone", async ({
page,
@@ -83,6 +179,13 @@ test("applies a contributed theme and falls back when its plugin is gone", async
await expect(sectionTitle).toHaveCSS("color", LATTE_MUTED_FOREGROUND);
});
await test.step("keyboard focus draws the outline in the theme's ring color", async () => {
await page.getByRole("radio", { name: "Catppuccin Latte", exact: true }).click();
await page.mouse.move(0, 0);
await page.keyboard.press("Tab");
await expect(page.locator(":focus-visible").first()).toHaveCSS("outline-color", LATTE_RING);
});
await mochaItem.click();
await expect(mochaItem).toBeChecked();
await expect(sectionTitle).toHaveCSS("color", MOCHA_MUTED_FOREGROUND);
@@ -1,21 +1,22 @@
import { ACP_PROVIDER_ICON_SVGS } from "../../src/assets/acp-provider-icons";
import { expect, test, type Page } from "../support/fixtures";
import type { TestInfo } from "@playwright/test";
import type { Locator, TestInfo } from "@playwright/test";
import { gotoAppShell, openSettings } from "../support/helpers/app";
import { getServerId } from "../support/helpers/server-id";
import {
findAcpCatalogProvider,
openAddProviderArea,
openAddProvider,
openSettingsHost,
openSettingsHostSection,
} from "../support/helpers/settings";
async function openProviderCatalog(page: Page) {
async function openProviderCatalog(page: Page, viewport?: { width: number; height: number }) {
await gotoAppShell(page);
await openSettings(page);
await openSettingsHost(page, getServerId());
await openSettingsHostSection(page, getServerId(), "providers");
await openAddProviderArea(page);
if (viewport) await page.setViewportSize(viewport);
await openAddProvider(page);
}
async function expectProviderArtwork(
@@ -25,11 +26,11 @@ async function expectProviderArtwork(
name: string,
) {
await findAcpCatalogProvider(page, name);
// 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();
// 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();
await expect(icon).toBeVisible();
// Provider artwork is 24px; the generic PackagePlus fallback is 20px.
await expect.soft(icon).toHaveAttribute("width", "24");
// 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");
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")!);
@@ -49,3 +50,20 @@ 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);
});
@@ -0,0 +1,54 @@
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,11 +2,15 @@ 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 {
expectProviderInstalledInSettings,
expectProviderNotOnHost,
installAcpCatalogProvider,
openAddProviderArea,
leaveProviderDetail,
openAddProvider,
openProviderDetail,
openSettingsHost,
openSettingsHostSection,
} from "../support/helpers/settings";
@@ -62,13 +66,39 @@ 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-${CUSTOM_PROVIDER.id}`).click();
await page.getByTestId("provider-remove").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);
@@ -79,20 +109,39 @@ 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");
await expect(page.getByTestId("provider-actions-claude")).toHaveCount(0);
await openAddProviderArea(page);
// 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 installAcpCatalogProvider(page, CUSTOM_PROVIDER.name);
await expectProviderInstalledInSettings(page, CUSTOM_PROVIDER.name);
await expectProviderSource(client, "custom");
await page.getByTestId(`provider-actions-${CUSTOM_PROVIDER.id}`).click();
await expect(page.getByTestId(`provider-remove-${CUSTOM_PROVIDER.id}`)).toBeVisible();
await openProviderDetail(page, CUSTOM_PROVIDER.name);
await expect(page.getByTestId("provider-remove")).toBeVisible();
await watchForMissingNotice(page);
gate.holdNextServerMessage(CONFIG_RESPONSE);
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", {
@@ -100,7 +149,33 @@ test.describe("provider removal", () => {
exact: true,
}),
).toHaveCount(0);
await expectProviderSource(client, undefined);
} 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);
} finally {
await removeCustomProvider(client).catch(() => undefined);
await client.close().catch(() => undefined);
@@ -130,7 +205,9 @@ test.describe("provider removal", () => {
exact: true,
});
await expect(pluginProviderRow).toBeVisible();
await expect(page.getByTestId(`provider-actions-${PLUGIN_PROVIDER.id}`)).toHaveCount(0);
await openProviderDetail(page, PLUGIN_PROVIDER.name);
await expect(page.getByTestId("provider-remove")).toHaveCount(0);
await leaveProviderDetail(page);
// 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", exact: true })).toBeVisible();
await expect(page.getByRole("button", { name: "Diagnostic report" })).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", exact: true }).click();
await page.getByRole("button", { name: "Diagnostic report" }).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("Updated just now", { exact: true })).toBeVisible({
await expect(page.getByText("Checked just now", { exact: true })).toBeVisible({
timeout: 30_000,
});
}
@@ -15,6 +15,9 @@ import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon
import { getServerId } from "../support/helpers/server-id";
import {
expectSettingsHeader,
expectProviderNotOnHost,
expectProviderPageLoaded,
gotoProviderPage,
openSettingsHost,
openHostSection,
expectHostLabelDisplayed,
@@ -262,6 +265,20 @@ 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);
@@ -1,3 +1,4 @@
import { writeFile } from "node:fs/promises";
import { test, expect } from "../support/fixtures";
import {
buildHostWorkspaceRoute,
@@ -6,20 +7,31 @@ import {
buildSettingsRoute,
buildSettingsSectionRoute,
} from "@/utils/host-routes";
import { openCompactSidebar } from "../support/helpers/usage-sidebar-item";
import { gotoAppShell, openSettings } from "../support/helpers/app";
import { getE2EDaemonPort } from "../support/helpers/daemon-port";
import {
closeCompactSettings,
captureCompactSidebarReturn,
openSettingsFromCompactSidebar,
captureCompactSidebarContext,
expectCompactSidebarOpen,
closeCompactSidebar,
scrollSettingsSidebarToEnd,
revealSettingsSidebarSection,
expectSettingsSidebarScrollSettled,
scrollSettingsSidebarUp,
changeSettingsInterfaceFontSize,
selectSettingsHostSectionsRapidly,
expectSettingsSidebarScrollOffset,
scrollSettingsDetailDown,
expectSettingsDetailScrollOffset,
openSettingsSection,
changeSettingsSyntaxTheme,
revealSettingsSyntaxTheme,
expectSettingsSyntaxColorChanged,
changeSettingsTypography,
normalizeSettingsFontSizes,
changeSettingsInterfaceFontSizeKeepingSidebarPosition,
expectSettingsHeader,
openAddHostFlow,
selectHostConnectionType,
@@ -84,13 +96,32 @@ test.describe("Settings sidebar scroll position", () => {
await expectSettingsSidebarScrollOffset(page, 0);
});
test("keeps the sidebar position through interface font changes", async ({ page }) => {
test("updates appearance without losing the detail scroll or form edits", async ({ page }) => {
await gotoAppShell(page);
await openSettings(page);
await openSettingsSection(page, "appearance");
const offset = await scrollSettingsSidebarToEnd(page);
await changeSettingsInterfaceFontSize(page, 20);
await expectSettingsSidebarScrollOffset(page, offset);
const { offset, keywordColor } = await revealSettingsSyntaxTheme(page);
await changeSettingsSyntaxTheme(page, "Dracula");
await expectSettingsDetailScrollOffset(page, offset);
await expectSettingsSyntaxColorChanged(page, keywordColor);
await changeSettingsTypography(page);
});
test("shows normalized font sizes after committing out-of-range and empty values", async ({
page,
}) => {
await gotoAppShell(page);
await openSettings(page);
await openSettingsSection(page, "appearance");
await normalizeSettingsFontSizes(page);
});
test("keeps the sidebar context through interface font changes", async ({ page }) => {
await gotoAppShell(page);
await openSettings(page);
await openSettingsSection(page, "appearance");
await scrollSettingsSidebarToEnd(page);
const offset = await changeSettingsInterfaceFontSizeKeepingSidebarPosition(page, 20);
await openSettingsHostSection(page, getServerId(), "providers");
await expectSettingsSidebarScrollOffset(page, offset);
});
@@ -350,6 +381,87 @@ test.describe("Settings sidebar navigation", () => {
test.describe("Settings — compact master-detail", () => {
test.use({ viewport: { width: 390, height: 844 } });
test("returning from Settings preserves the open sidebar from the first paint", async ({
page,
withWorkspace,
}, testInfo) => {
const workspace = await withWorkspace({ prefix: "settings-sidebar-continuity-" });
for (let i = 0; i < 12; i++) await withWorkspace({ prefix: "settings-sidebar-scroll-" });
await openWorkspace(page, workspace);
await openCompactSidebar(page);
await expectCompactSidebarOpen(page);
const expectContextPreserved = await captureCompactSidebarContext(page);
const openingFrames = await captureCompactSidebarReturn(page, () =>
openSettingsFromCompactSidebar(page),
);
await writeFile(
testInfo.outputPath("sidebar-opening-frames.json"),
JSON.stringify(openingFrames, null, 2),
);
expect(openingFrames.some((frame) => frame.settingsVisible)).toBe(true);
expect(openingFrames.every((frame) => frame.sidebarVisible || frame.settingsVisible)).toBe(
true,
);
await openSettingsSection(page, "appearance");
await goBackInSettings(page);
const frames = await captureCompactSidebarReturn(page, () => closeCompactSettings(page));
await writeFile(
testInfo.outputPath("sidebar-return-frames.json"),
JSON.stringify(frames, null, 2),
);
await testInfo.attach("sidebar-return-frames", {
body: JSON.stringify(frames, null, 2),
contentType: "application/json",
});
const workspaceFrames = frames.filter((frame) => !frame.pathname.startsWith("/settings"));
expect(workspaceFrames.length).toBeGreaterThan(0);
expect(workspaceFrames.every((frame) => frame.sidebarVisible)).toBe(true);
const firstX = workspaceFrames[0]!.closeX;
expect(
workspaceFrames.every((frame) => Math.abs((frame.closeX ?? Infinity) - firstX!) < 1),
).toBe(true);
await expectCompactSidebarOpen(page);
await expectContextPreserved();
await openSettingsFromCompactSidebar(page);
const backFrames = await captureCompactSidebarReturn(page, async () => {
await page.goBack();
});
await writeFile(
testInfo.outputPath("browser-back-frames.json"),
JSON.stringify(backFrames, null, 2),
);
await testInfo.attach("browser-back-frames", {
body: JSON.stringify(backFrames, null, 2),
contentType: "application/json",
});
const backWorkspaceFrames = backFrames.filter(
(frame) => !frame.pathname.startsWith("/settings"),
);
expect(backWorkspaceFrames.length).toBeGreaterThan(0);
expect(backWorkspaceFrames.every((frame) => frame.sidebarVisible)).toBe(true);
await expectCompactSidebarOpen(page);
await closeCompactSidebar(page);
});
test("widening during Settings discards the mobile sidebar return", async ({
page,
withWorkspace,
}) => {
const workspace = await withWorkspace({ prefix: "settings-sidebar-resize-" });
await openWorkspace(page, workspace);
await openCompactSettings(page, buildHostWorkspaceRoute(getServerId(), workspace.workspaceId));
await page.setViewportSize({ width: 1000, height: 844 });
await expect(page.getByTestId("settings-detail-pane")).toBeVisible();
await page.setViewportSize({ width: 390, height: 844 });
await goBackInSettings(page);
await expectCompactSettingsList(page);
await closeCompactSettings(page);
await expect(page.getByRole("button", { name: "Close sidebar", exact: true })).toBeHidden();
await expect(
page.getByRole("button", { name: "Open menu", exact: true }).first(),
).toBeInViewport();
});
test("the compact tab switcher reopens after Settings hides its workspace", async ({ page }) => {
const workspace = await seedMockAgentWorkspace({
repoPrefix: "settings-tab-switcher-",
@@ -377,6 +489,7 @@ test.describe("Settings — compact master-detail", () => {
await expect(newAgent).toHaveCount(0);
await closeCompactSettings(page);
await closeCompactSidebar(page);
await expect(switcher).toBeVisible();
await expect(newAgent).toHaveCount(0);
await switcher.click();
@@ -29,6 +29,7 @@ import {
openCompactSidebar,
openUsageFromIcon,
openUsageFromItem,
openUsageFromItemWithPressFeedback,
pinRow,
scrollUsageToWindow,
setSummaryInSidebar,
@@ -197,7 +198,7 @@ test.describe("Usage item", () => {
});
await test.step("the summary opens the same sheet", async () => {
await openUsageFromItem(page);
await openUsageFromItemWithPressFeedback(page);
await expect(usageModal(page).getByText("Codex", { exact: true })).toBeVisible();
await expect(page).toHaveURL(startingUrl);
await qaScreenshot(page, "compact-usage-summary-sheet");
@@ -136,7 +136,7 @@ async function expectForkFailureWithoutOverlappingStatus(page: Page) {
async function observeToastReplacement(page: Page) {
const observation = await page
.getByRole("alert")
.filter({ hasText: "Reconnecting to host" })
.filter({ hasText: "Reconnecting" })
.evaluateHandle((toast) => {
const frames: Array<{ connected: boolean; opacity: number; transform: string }> = [];
let frame = 0;
@@ -3,7 +3,7 @@ env APP_ID=sh.paseo.debug
# Start with the sidebar closed. WORKSPACE_ROW is the testID of a visible,
# unselected PINNED workspace row. Ordinary workspace rows are not draggable.
# Hold past drag arming (180ms), then release.
# Hold past press feedback (130ms) and drag arming (180ms), then release.
open "${APP_ID}"
press "label=\"Open menu\""
wait "id=\"sidebar-close\"" 10000
@@ -12,7 +12,7 @@ press "id=\"sidebar-close\""
wait "label=\"Open menu\"" 5000
press "label=\"Open menu\""
wait "id=\"${WORKSPACE_ROW}\"" 10000
longpress "id=\"${WORKSPACE_ROW}\"" 250
longpress "id=\"${WORKSPACE_ROW}\"" 400
press "id=\"${WORKSPACE_ROW}\""
# A released drag must not swallow the next tap: navigation closes the sidebar.
wait "label=\"Open menu\"" 5000
@@ -0,0 +1,83 @@
// Record a sidebar toast through timeout on the 2560×1600 Android tablet.
// Pass a vertical sample line through the card's plain interior, away from text,
// icons, and Android's clipboard preview, plus the visible-to-dismissed interval:
// node .../toast-dismissal.mjs recording.mp4 sample-x start-seconds end-seconds
// This checks actual native frames; a browser layout test misses this regression.
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
const [, , recording, sampleX, start, end] = process.argv;
assert(recording && sampleX && start && end, "Pass recording, sample x, start and end seconds");
const { frames } = JSON.parse(
execFileSync(
"ffprobe",
[
"-v",
"error",
"-select_streams",
"v",
"-show_entries",
"frame=best_effort_timestamp_time",
"-of",
"json",
recording,
],
{ encoding: "utf8" },
),
);
const selectedFrames = frames
.map((frame, index) => ({ time: Number(frame.best_effort_timestamp_time), index }))
.filter(({ time }) => time >= Number(start) && time <= Number(end));
assert(selectedFrames.length > 2, "Capture at least three frames in the supplied interval");
const firstFrame = selectedFrames[0].index;
const endFrame = selectedFrames.at(-1).index + 1;
const bytesPerFrame = 800;
// Bound both output and buffer to the requested frames, even for a long recording.
const pixels = execFileSync(
"ffmpeg",
[
"-v",
"fatal",
"-i",
recording,
"-vf",
`trim=start_frame=${firstFrame}:end_frame=${endFrame},crop=2:400:${Number(sampleX)}:1100,format=gray`,
"-fps_mode",
"passthrough",
"-f",
"rawvideo",
"-",
],
{ maxBuffer: selectedFrames.length * bytesPerFrame + 1024 },
);
assert.equal(
pixels.length,
selectedFrames.length * bytesPerFrame,
"Every selected frame must be decoded",
);
const positions = [];
let disappeared = false;
for (const [index, { time }] of selectedFrames.entries()) {
const column = pixels.subarray(index * bytesPerFrame, (index + 1) * bytesPerFrame);
const runs = [];
let run = [];
for (let y = 0; y < 400; y++) {
if (column[y * 2] > 250) run.push(y);
else {
if (run.length > 40) runs.push(run);
run = [];
}
}
if (run.length > 40) runs.push(run);
runs.sort((a, b) => b.length - a.length);
if (runs.length) {
const card = runs[0];
positions.push({ time, centre: 1100 + (card[0] + card.at(-1)) / 2 });
} else if (positions.length) disappeared = true;
}
assert(positions.length > 2, "Capture at least three visible card frames");
assert(disappeared, "Recording must include the card disappearing");
const centres = positions.map(({ centre }) => centre);
const shift = Math.max(...centres) - Math.min(...centres);
console.log(JSON.stringify({ positions, maximumShiftPixels: shift }, null, 2));
assert(shift <= 2, `Toast moved ${shift}px during dismissal`);
@@ -0,0 +1,55 @@
import { expect, type Locator, type Page } from "@playwright/test";
/** The tones a composer toolbar control paints: its glyph's stroke and its label's text color. */
export interface ComposerControlTone {
/** The visible glyph's stroke, or null when the control paints no glyph. */
glyph: string | null;
/** The visible label's color, or null when the control is icon-only. */
label: string | null;
}
export function composerControl(page: Page, testId: string): Locator {
return page.getByTestId(testId).filter({ visible: true }).first();
}
/**
* Reads the colors the control actually paints. The toolbar glyph and its label are separate
* nodes, so this is the only way to tell whether they match.
*/
export async function readComposerControlTone(control: Locator): Promise<ComposerControlTone> {
return control.evaluate((element) => {
const visible = (node: Element) => node.getClientRects().length > 0;
const glyph = Array.from(element.querySelectorAll("svg")).find(visible);
const label = Array.from(element.querySelectorAll("*"))
.filter(visible)
.find((node) =>
[...node.childNodes].some(
(child) => child.nodeType === Node.TEXT_NODE && child.textContent?.trim(),
),
);
return {
glyph: glyph ? getComputedStyle(glyph).stroke : null,
label: label ? getComputedStyle(label).color : null,
};
});
}
export function expectGlyphMatchesLabel(tone: ComposerControlTone, name: string): void {
expect(tone.label, `${name} paints a label`).not.toBeNull();
expect(tone.glyph, `${name}'s glyph matches its label`).toBe(tone.label);
}
export function expectIconOnlyGlyph(tone: ComposerControlTone, name: string): void {
expect(tone.label, `${name} is icon-only`).toBeNull();
expect(tone.glyph, `${name} paints a glyph`).not.toBeNull();
}
/** The color the browser paints in a text input's placeholder. */
export async function readComposerPlaceholderTone(input: Locator): Promise<string | null> {
return input.evaluate((element) => getComputedStyle(element, "::placeholder").color);
}
/** The color the browser paints for a text node. */
export async function readComposerTextTone(text: Locator): Promise<string | null> {
return text.evaluate((element) => getComputedStyle(element).color);
}
@@ -25,7 +25,7 @@ export async function addCustomModel(page: Page, id: string): Promise<void> {
}
export async function removeCustomModel(page: Page, id: string): Promise<void> {
await page.getByRole("textbox", { name: "Search models" }).fill(id);
await searchModels(page, id);
const remove = page.getByRole("button", { name: `Remove ${id}`, exact: true });
await expect(remove).toBeInViewport({ ratio: 1 });
await remove.click();
@@ -33,8 +33,20 @@ export async function removeCustomModel(page: Page, id: string): Promise<void> {
}
export async function expectCustomModelRetained(page: Page, id: string): Promise<void> {
await page.getByRole("textbox", { name: "Search models" }).fill(id);
await searchModels(page, 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" }));
}
@@ -46,3 +46,12 @@ export async function downloadFileFromExplorer(page: Page, fileName: string): Pr
await page.getByRole("menuitem", { name: "Download", exact: true }).click();
return downloaded;
}
export async function downloadFileFromPreview(page: Page): Promise<Download> {
await expect(page.getByText("Binary preview unavailable", { exact: true })).toBeVisible();
const button = page.getByRole("button", { name: "Download", exact: true });
await expect(button).toBeVisible();
const downloaded = page.waitForEvent("download");
await button.click();
return downloaded;
}
@@ -86,6 +86,17 @@ 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,
@@ -106,10 +106,12 @@ export async function verifyProviderSettings({
await test.step("provider settings render the registered icon", async () => {
await openSettings(page);
await openSettingsHostSection(page, getServerId(), "providers");
await expectProviderIcon(
page.getByRole("button", { name: "Direct provider example provider details", exact: true }),
iconPaths,
);
// 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 capture(page, testInfo, "provider-settings");
await page.getByTestId("settings-back-to-workspace").click();
});
@@ -92,7 +92,7 @@ export async function measureRelayRestartDuringStream(input: {
agentTitle: string;
}): Promise<RelayDeploymentMeasurements> {
const { page, relay, agentTitle } = input;
const toast = page.getByRole("alert").filter({ hasText: "Reconnecting to host" });
const toast = page.getByRole("alert").filter({ hasText: "Reconnecting" });
const beforeOutage = await latestAssistantText(page);
await waitForAssistantTextToGrow(page, beforeOutage);
+260 -2
View File
@@ -106,6 +106,33 @@ export async function changeSettingsInterfaceFontSize(page: Page, size: number):
await input.fill(String(size));
await input.press("Tab");
await expect(input).toHaveValue(String(size));
await expect(
page.getByRole("navigation", { name: "Settings" }).getByText("Appearance", { exact: true }),
).toHaveCSS("font-size", `${size}px`);
}
export async function changeSettingsInterfaceFontSizeKeepingSidebarPosition(
page: Page,
size: number,
): Promise<number> {
const navigation = page.getByRole("navigation", { name: "Settings" });
const anchor = navigation.getByRole("button", { name: "About", exact: true });
const before = await anchor.evaluate((node) => ({
top: node.getBoundingClientRect().top,
height: node.getBoundingClientRect().height,
}));
await changeSettingsInterfaceFontSize(page, size);
// Larger fonts reflow rows. Preserve the visible destination, rather than its old pixel offset.
await expect
.poll(() =>
anchor.evaluate((node, top) => Math.abs(node.getBoundingClientRect().top - top), before.top),
)
.toBeLessThan(before.height);
const offset = await page
.getByTestId("settings-sidebar-scroll-body")
.evaluate((node) => node.scrollTop);
expect(offset).toBeGreaterThan(0);
return offset;
}
export async function scrollSettingsSidebarToEnd(page: Page): Promise<number> {
@@ -480,8 +507,8 @@ export async function serveJson(page: Page, url: string, body: unknown): Promise
});
}
export async function openAddProviderArea(page: Page): Promise<void> {
await page.getByTestId("host-page-add-provider-card").scrollIntoViewIfNeeded();
export async function openAddProvider(page: Page): Promise<void> {
await page.getByTestId("provider-list-add").click();
await expect(page.getByRole("textbox", { name: "Search providers" })).toBeVisible();
}
@@ -493,17 +520,59 @@ 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,
});
}
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);
}
@@ -613,3 +682,192 @@ export async function expectRestartRecoveryPrompt(page: Page, prompt: string) {
await sheet.getByRole("button", { name: "Cancel", exact: true }).click();
await expect(sheet).toHaveCount(0);
}
export async function revealSettingsSyntaxTheme(page: Page) {
await page.getByLabel(/Highlight theme:/).scrollIntoViewIfNeeded();
const offset = await page
.getByTestId("settings-detail-scroll-body")
.evaluate((node) => node.scrollTop);
expect(offset).toBeGreaterThan(0);
const keywordColor = await page
.getByRole("img", { name: "Live preview of content typography, syntax theme, and code font" })
.getByText("export", { exact: true })
.first()
.evaluate((node) => getComputedStyle(node).color);
return { offset, keywordColor };
}
export async function changeSettingsSyntaxTheme(page: Page, theme: string): Promise<void> {
await page.getByLabel(/Highlight theme:/).click();
await page.getByRole("menuitem", { name: theme, exact: true }).click();
await expect(page.getByLabel(`Highlight theme: ${theme}`, { exact: true })).toBeVisible();
}
export async function expectSettingsSyntaxColorChanged(
page: Page,
previousColor: string,
): Promise<void> {
await expect(
page
.getByRole("img", { name: "Live preview of content typography, syntax theme, and code font" })
.getByText("export", { exact: true })
.first(),
).not.toHaveCSS("color", previousColor);
}
export async function changeSettingsTypography(page: Page): Promise<void> {
const input = page.getByRole("textbox", { name: "Interface font size", exact: true });
await input.fill("18");
await input.press("Enter");
await expect(input).toHaveValue("18");
await expect(input).toHaveCSS("font-size", "18px");
await expect(page.getByText("Code size", { exact: true })).toHaveCSS("font-size", "18px");
const navigation = page.getByRole("navigation", { name: "Settings" });
await expect(navigation.getByText("Appearance", { exact: true })).toHaveCSS("font-size", "18px");
await expect(navigation.getByText("Providers", { exact: true })).toHaveCSS("font-size", "18px");
await expect(page.getByText("Dracula", { exact: true })).toHaveCSS("font-size", "18px");
const familyInput = page.getByRole("textbox", { name: "Code font family", exact: true });
await familyInput.fill("Courier New, Courier, monospace");
await familyInput.press("Enter");
const codeInput = page.getByRole("textbox", { name: "Code font size", exact: true });
await codeInput.fill("16");
await codeInput.press("Enter");
await expect(codeInput).toHaveValue("16");
const preview = page.getByRole("img", {
name: "Live preview of content typography, syntax theme, and code font",
});
await expect(preview.getByText("export", { exact: true }).first()).toHaveCSS("font-size", "16px");
await expect(preview.getByText("export", { exact: true }).first()).toHaveCSS(
"line-height",
"24px",
);
await expect(preview.getByText("export", { exact: true }).first()).toHaveCSS(
"font-family",
/Courier/,
);
const contentInput = page.getByRole("textbox", { name: "Content font size", exact: true });
await contentInput.fill("20");
await contentInput.press("Enter");
await expect(preview.getByText("Readable content and code preview", { exact: true })).toHaveCSS(
"font-size",
"20px",
);
}
export async function normalizeSettingsFontSizes(page: Page): Promise<void> {
for (const [name, minimum, maximum] of [
["Interface font size", "10", "21"],
["Content font size", "10", "21"],
["Code font size", "9", "22"],
] as const) {
const input = page.getByRole("textbox", { name, exact: true });
await input.fill("999");
await input.press("Enter");
await expect(input).toHaveValue(maximum);
// Clamp again when the saved value is already at the maximum.
await input.fill("999");
await input.press("Tab");
await expect(input).toHaveValue(maximum);
await input.fill("");
await input.press("Enter");
await expect(input).toHaveValue(maximum);
await input.fill("1");
await input.press("Enter");
await expect(input).toHaveValue(minimum);
await input.fill("1");
await input.press("Tab");
await expect(input).toHaveValue(minimum);
}
}
/** Sample actual paints, including the first workspace frame after Settings. */
export async function captureCompactSidebarReturn(page: Page, returnAction: () => Promise<void>) {
await page.evaluate(() => {
const capture = {
frames: [] as {
time: number;
pathname: string;
sidebarVisible: boolean;
settingsVisible: boolean;
closeX: number | null;
}[],
stopped: false,
};
Object.assign(window, { __sidebarFrameCapture: capture });
const start = performance.now();
function sample() {
if (capture.stopped) return;
const close = document.querySelector('[data-testid="sidebar-close"]');
capture.frames.push({
time: performance.now() - start,
pathname: location.pathname,
settingsVisible:
document
.querySelector('[data-testid="settings-sidebar"]')
?.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true }) ?? false,
sidebarVisible:
(close?.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true }) ?? false) &&
close!.getBoundingClientRect().x >= 0 &&
close!.getBoundingClientRect().right <= innerWidth,
closeX: close?.getBoundingClientRect().x ?? null,
});
requestAnimationFrame(sample);
}
requestAnimationFrame(sample);
});
await returnAction();
return page.evaluate(async () => {
const capture = (
window as typeof window & {
__sidebarFrameCapture: {
frames: {
time: number;
pathname: string;
sidebarVisible: boolean;
settingsVisible: boolean;
closeX: number | null;
}[];
stopped: boolean;
};
}
).__sidebarFrameCapture;
await new Promise<void>((resolve) => setTimeout(resolve, 1500));
capture.stopped = true;
return capture.frames;
});
}
export async function captureCompactSidebarContext(page: Page) {
const sidebar = await page.getByTestId("sidebar-project-workspace-list-scroll").elementHandle();
if (!sidebar) throw new Error("Open sidebar has no workspace list");
await expect
.poll(() => sidebar.evaluate((el) => el.scrollHeight - el.clientHeight))
.toBeGreaterThan(0);
const offset = await sidebar.evaluate((el) => {
el.scrollTop = el.scrollHeight;
return el.scrollTop;
});
expect(offset).toBeGreaterThan(0);
return async () => {
expect(await sidebar.evaluate((el) => el.isConnected)).toBe(true);
expect(await sidebar.evaluate((el) => el.scrollTop)).toBe(offset);
await sidebar.dispose();
};
}
export async function expectCompactSidebarOpen(page: Page) {
await expect(page.getByRole("button", { name: "Close sidebar", exact: true })).toBeInViewport();
}
export async function closeCompactSidebar(page: Page) {
await page.getByRole("button", { name: "Close sidebar", exact: true }).click();
await expect(
page.getByRole("button", { name: "Open menu", exact: true }).first(),
).toBeInViewport();
}
export async function openSettingsFromCompactSidebar(page: Page) {
await page.getByRole("button", { name: "Settings", exact: true }).click();
await expectAppRoute(page, buildSettingsRoute());
await expectCompactSettingsList(page);
}
@@ -200,6 +200,18 @@ export async function openUsageFromItem(page: Page): Promise<void> {
await expect(usageModal(page)).toBeVisible();
}
export async function openUsageFromItemWithPressFeedback(page: Page): Promise<void> {
const summary = page.getByRole("button", { name: /^Usage:/ });
await summary.hover();
const hoveredFill = await summary.evaluate(
(element) => getComputedStyle(element).backgroundColor,
);
await page.mouse.down();
await expect(summary).not.toHaveCSS("background-color", hoveredFill);
await page.mouse.up();
await expect(usageModal(page)).toBeVisible();
}
/** Scrolls the Usage modal's body with the mouse wheel, as a user does. */
export async function scrollUsage(page: Page, deltaY: number): Promise<void> {
const body = await usageModal(page).boundingBox();
@@ -109,18 +109,18 @@ export async function expectReconnectingToastVisible(
page: Page,
options?: { timeout?: number },
): Promise<void> {
const toast = page.getByRole("alert").filter({ hasText: "Reconnecting to host" });
const toast = page.getByRole("alert").filter({ hasText: "Reconnecting" });
await expect(toast).toBeVisible({
timeout: options?.timeout ?? 30_000,
});
await expect(toast).toHaveText("Reconnecting to host");
await expect(toast).toHaveText("Reconnecting");
}
export async function expectReconnectingToastGone(
page: Page,
options?: { timeout?: number },
): Promise<void> {
await expect(page.getByRole("alert").filter({ hasText: "Reconnecting to host" })).toHaveCount(0, {
await expect(page.getByRole("alert").filter({ hasText: "Reconnecting" })).toHaveCount(0, {
timeout: options?.timeout ?? 30_000,
});
}
+4 -2
View File
@@ -81,12 +81,14 @@
/* Suppress the browser's default focus outline — it appears on mouse
clicks and looks out of place against our themed surfaces. Keep a
themed ring for keyboard users via :focus-visible. */
themed ring for keyboard users via :focus-visible. The ring is the active
theme's `ring` color, exposed by Unistyles as a CSS variable; the fallback
only shows before the theme mounts. */
*:focus {
outline: none;
}
*:focus-visible {
outline: 2px solid #20744a;
outline: 2px solid var(--colors-ring, #20744a);
outline-offset: 2px;
}
</style>
+4 -6
View File
@@ -5,7 +5,7 @@ import equal from "fast-deep-equal";
import { normalizeWorkspacePath } from "@/utils/workspace-identity";
export const AGENT_COMMANDS_QUERY_ROOT = "agentCommands";
export const sessionCommandQueryPolicy = {
export const agentCommandQueryPolicy = {
staleTime: 600_000,
gcTime: 1_800_000,
refetchOnMount: true,
@@ -102,14 +102,12 @@ export function draftAgentCommandsQueryKey(input: {
] as const;
}
// Draft commands include project skills read from the checkout. When the checkout moves to
// another branch the cached list describes files that are gone, so it is dropped rather than
// shown while a refetch runs.
export function resetDraftAgentCommandsForCheckout(
// Refresh checkout skills after branch changes while keeping the previous catalog usable.
export function invalidateDraftAgentCommandsForCheckout(
queryClient: QueryClient,
input: { serverId: string; cwd: string },
): Promise<void> {
return queryClient.resetQueries({ queryKey: draftAgentCommandsCheckoutScope(input) });
return queryClient.invalidateQueries({ queryKey: draftAgentCommandsCheckoutScope(input) });
}
export function agentCommandsQueryKey(input: {
+36 -3
View File
@@ -2,12 +2,13 @@ import { describe, expect, it } from "vitest";
import { QueryClient, QueryObserver } from "@tanstack/react-query";
import { fetchQueryOptions } from "@/data/query";
import {
invalidateDraftAgentCommandsForCheckout,
agentCommandsQueryKey,
agentCommandsQueryRoot,
draftAgentCommandsQueryKey,
normalizeAgentCommandsCwd,
sessionAgentCommandsQueryKey,
sessionCommandQueryPolicy,
agentCommandQueryPolicy,
} from "./cache";
it("reuses fresh commands and keeps stale commands during a shared refresh and failure", async () => {
@@ -20,8 +21,8 @@ it("reuses fresh commands and keeps stale commands during a shared refresh and f
resolveRefresh = resolve;
});
const options = fetchQueryOptions({
...sessionCommandQueryPolicy,
staleTimeMs: sessionCommandQueryPolicy.staleTime,
...agentCommandQueryPolicy,
staleTimeMs: agentCommandQueryPolicy.staleTime,
dataShape: "value",
queryKey: key,
retry: false,
@@ -124,3 +125,35 @@ describe("agent command query keys", () => {
expect(agentCommandsQueryRoot("server-1")).toEqual(["agentCommands", "server-1"]);
});
});
it("retains draft commands while checkout invalidation refreshes the catalog", async () => {
const client = new QueryClient();
const key = draftAgentCommandsQueryKey({
serverId: "s",
draftConfig: { provider: "codex", cwd: "/repo" },
});
client.setQueryData(key, ["old"]);
let finish: (commands: string[]) => void = () => {};
const refresh = new Promise<string[]>((resolve) => {
finish = resolve;
});
const observer = new QueryObserver(
client,
fetchQueryOptions({
queryKey: key,
dataShape: "value",
immutableWhen: () => true,
queryFn: () => refresh,
}),
);
const unsubscribe = observer.subscribe(() => {});
const updating = invalidateDraftAgentCommandsForCheckout(client, { serverId: "s", cwd: "/repo" });
expect(observer.getCurrentResult().data).toEqual(["old"]);
expect(observer.getCurrentResult().isPending).toBe(false);
expect(observer.getCurrentResult().isFetching).toBe(true);
finish(["new"]);
await updating;
expect(observer.getCurrentResult().data).toEqual(["new"]);
unsubscribe();
client.clear();
});
+3 -4
View File
@@ -9,7 +9,7 @@ import { useShallow } from "zustand/shallow";
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
import {
agentCommandsQueryKey,
sessionCommandQueryPolicy,
agentCommandQueryPolicy,
type AgentCommandsDraftConfig,
} from "./cache";
@@ -92,9 +92,8 @@ export function useAgentCommandsQuery({
agentCommandProvider: draftConfig?.provider ?? provider,
agentCommandCwd: draftConfig?.cwd ?? cwd,
},
...(draftConfig
? { immutableWhen: () => true as const }
: { ...sessionCommandQueryPolicy, staleTimeMs: sessionCommandQueryPolicy.staleTime }),
...agentCommandQueryPolicy,
staleTimeMs: agentCommandQueryPolicy.staleTime,
subscribed: queryEnabled,
retry: 3,
retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 5000),
+58 -10
View File
@@ -87,7 +87,10 @@ import {
type StartupBlocker,
} from "@/navigation/host-runtime-bootstrap";
import { registerWorkspaceRouteNavigationRef } from "@/navigation/workspace-route-navigation";
import { useSettingsRouteEntry } from "@/navigation/settings-presentation";
import {
useSettingsRouteEntry,
useSettingsSidebarPresentation,
} from "@/navigation/settings-presentation";
import { ThemedStack } from "@/navigation/themed-stack";
import { shouldUseDesktopDaemon } from "@/desktop/daemon/desktop-daemon";
import { AgentNavigationListener } from "@/desktop/agent-navigation";
@@ -473,12 +476,16 @@ function AppContainer({ children, chromeEnabled: chromeEnabledOverride }: AppCon
viewportWidth,
}),
});
const sidebarPresentation = resolveLeftSidebarPresentation({
chromeEnabled,
isCompactLayout,
isFocusModeEnabled: isWorkspaceFocusModeEnabled,
desktopSidebarVisible,
});
const { presentation: sidebarPresentation, visible: sidebarVisible } =
useSettingsSidebarPresentation({
visible: chromeEnabled,
presentation: resolveLeftSidebarPresentation({
chromeEnabled,
isCompactLayout,
isFocusModeEnabled: isWorkspaceFocusModeEnabled,
desktopSidebarVisible,
}),
});
const applyPanelLayout = usePanelStore((state) => state.applyPanelLayout);
// Publishes the layout to the store, which owns the panel targets each layout allows.
useLayoutEffect(() => {
@@ -546,7 +553,11 @@ function AppContainer({ children, chromeEnabled: chromeEnabledOverride }: AppCon
<DesktopWindowControls />
<FloatingPanelPortalHost />
</AppearanceStyleBoundary>
{isCompactLayout ? themedSidebarChrome : null}
{isCompactLayout ? (
<CompactSidebarHost visible={sidebarVisible} interactive={chromeEnabled}>
{themedSidebarChrome}
</CompactSidebarHost>
) : null}
<AppearanceStyleBoundary>
<DownloadToast />
<RosettaCalloutSource />
@@ -584,6 +595,34 @@ function AppContainer({ children, chromeEnabled: chromeEnabledOverride }: AppCon
);
}
// Keep native scroll ranges and gesture hosts intact while Settings covers the sidebar.
function CompactSidebarHost({
visible,
interactive,
children,
}: {
visible: boolean;
interactive: boolean;
children: ReactNode;
}) {
return (
<View
collapsable={false}
style={[
layoutStyles.compactSidebarHost,
{ opacity: visible ? 1 : 0 },
// DOM descendants can override pointer-events:none.
isWeb && !visible && { display: "none" },
]}
pointerEvents={interactive ? "box-none" : "none"}
accessibilityElementsHidden={!interactive}
importantForAccessibility={interactive ? "auto" : "no-hide-descendants"}
>
{children}
</View>
);
}
function AppContainerLifetime({
children,
sidebarGesturesEnabled,
@@ -614,14 +653,18 @@ function SidebarChrome({
const isCompactLayout = useIsCompactFormFactor();
const isMobileActive = useIsMobilePanelActive("agent-list");
const overlay = presentation === "overlay";
const active = resolveSidebarActivity(presentation !== "hidden", overlay, isMobileActive);
const active = resolveSidebarActivity(
presentation !== "hidden" && presentation !== "suspended",
overlay,
isMobileActive,
);
const hardwareKeyboardPresent = useHardwareKeyboardPresent();
return (
<SidebarModelProvider
active={active}
keyboardNavigationActive={keyboardShortcutsEnabled && hardwareKeyboardPresent}
>
{mounted ? (
{mounted || presentation === "suspended" ? (
<LeftSidebar active={active} desktopOverlay={overlay && !isCompactLayout} />
) : null}
<WorkspaceShortcutTargetsSubscriber enabled={keyboardShortcutsEnabled} />
@@ -864,6 +907,8 @@ const ROOT_STACK_SCREEN_OPTIONS = {
animation: "none" as const,
};
const ROOT_STACK_NESTED_NAVIGATOR_SCREENS = ["h/[serverId]"] as const;
// Settings owns reactive typography leaves; its scroll and form state survive appearance edits.
const ROOT_STACK_SCREEN_OWNED_APPEARANCE = ["settings/[section]"] as const;
function RootStack() {
const storeReady = useStoreReady();
@@ -871,6 +916,7 @@ function RootStack() {
<ThemedStack
screenOptions={ROOT_STACK_SCREEN_OPTIONS}
nestedNavigatorScreens={ROOT_STACK_NESTED_NAVIGATOR_SCREENS}
screenOwnedAppearance={ROOT_STACK_SCREEN_OWNED_APPEARANCE}
>
<Stack.Screen name="index" />
<Stack.Protected guard={storeReady}>
@@ -888,6 +934,7 @@ function RootStack() {
<Stack.Screen name="settings/hosts/[serverId]/plugins/[pluginId]/[screenId]" />
<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>
);
}
@@ -1004,6 +1051,7 @@ export default function RootLayout() {
}
const layoutStyles = StyleSheet.create((theme) => ({
compactSidebarHost: { position: "absolute", top: 0, bottom: 0, left: 0, right: 0 },
surfaceFill: {
flex: 1,
backgroundColor: theme.colors.surface0,
@@ -0,0 +1,24 @@
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>
);
}
+3
View File
@@ -0,0 +1,3 @@
import { Text } from "react-native";
export { Text as AppearanceText };
+12
View File
@@ -0,0 +1,12 @@
import { Text as NativeText } from "react-native";
import { withUnistyles } from "react-native-unistyles";
import type { Theme } from "@/styles/theme";
// Web numeric tokens are baked into classes. Subscribe this leaf so withUnistyles
// resolves its style prop again without replacing the surrounding form or scroll view.
function typographyChanges(theme: Theme) {
void theme.fontSize;
return {};
}
export const AppearanceText = withUnistyles(NativeText, typographyChanges);
+2 -1
View File
@@ -1,6 +1,7 @@
import { AppearanceText as Text } from "@/appearance/text";
import { useCallback, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { Text, View, type PressableStateCallbackType } from "react-native";
import { View, type PressableStateCallbackType } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { PressHighlight } from "@/components/ui/press-highlight";
import { DEFAULT_THEME_PREFERENCE, useAppSettings, type AppSettings } from "@/hooks/use-settings";
@@ -23,6 +23,7 @@ import {
useIsolatedBottomSheetVisibility,
} from "@/components/ui/isolated-bottom-sheet-modal";
import { getCompactSheetSafeAreaPadding } from "@/components/adaptive-modal-sheet-layout";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { ScrollView } from "@/components/ui/scroll-view";
import { isWeb } from "@/constants/platform";
import { useKeyboardVisibility } from "@/hooks/use-keyboard-visibility";
@@ -73,6 +74,7 @@ export interface SheetHeader {
const SCROLL_CONTENT_GROW = { flexGrow: 1 };
const ABSOLUTE_FILL_STYLE = { ...StyleSheet.absoluteFill };
const NATIVE_DIALOG_SNAP_POINTS = ["100%"];
const HEADER_ICON_SIZE = 16;
const styles = StyleSheet.create((theme) => ({
nativeDialogSurface: {
@@ -137,6 +139,15 @@ const styles = StyleSheet.create((theme) => ({
padding: theme.spacing[SHEET_HEADER_CLOSE_PADDING_SCALE],
borderRadius: theme.borderRadius.lg,
},
headerIconButtonInactive: {
opacity: theme.opacity[50],
},
headerIconBox: {
width: HEADER_ICON_SIZE,
height: HEADER_ICON_SIZE,
alignItems: "center",
justifyContent: "center",
},
// Without a header the close button floats over the card's top-right corner.
floatingClose: {
position: "absolute",
@@ -345,31 +356,55 @@ function SheetContent({ style, children }: { style: StyleProp<ViewStyle>; childr
/**
* An icon action in a sheet header's trailing rail, drawn like the Close button so a header's
* actions line up with it at one size. Pass it through `SheetHeader.actions`.
* actions line up with it at one size. Pass it through `SheetHeader.actions`. Like `Button`, a
* loading action shows a spinner in place of its icon and, like a disabled one, is dimmed and
* cannot be pressed.
*/
export function SheetHeaderIconButton({
icon: Icon,
accessibilityLabel,
onPress,
loading = false,
disabled = false,
testID,
}: {
icon: LucideIcon;
accessibilityLabel: string;
onPress: () => void;
loading?: boolean;
disabled?: boolean;
testID?: string;
}) {
const { theme } = useUnistyles();
const inactive = disabled || loading;
const style = useMemo(
() => [styles.closeButton, inactive && styles.headerIconButtonInactive],
[inactive],
);
const accessibilityState = useMemo(
() => ({ disabled: inactive, busy: loading }),
[inactive, loading],
);
return (
<Pressable
accessibilityRole="button"
accessibilityLabel={accessibilityLabel}
style={styles.closeButton}
accessibilityState={accessibilityState}
disabled={inactive}
style={style}
onPress={onPress}
testID={testID}
>
{({ pressed }) => (
<Icon size={16} color={pressed ? theme.colors.foreground : theme.colors.foregroundMuted} />
)}
{({ pressed }) => {
const color = pressed ? theme.colors.foreground : theme.colors.foregroundMuted;
if (!loading) return <Icon size={HEADER_ICON_SIZE} color={color} />;
// The spinner sits in the icon's box, so the header does not move while it runs.
return (
<View style={styles.headerIconBox}>
<LoadingSpinner size={HEADER_ICON_SIZE} color={color} />
</View>
);
}}
</Pressable>
);
}
@@ -539,6 +574,11 @@ 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;
@@ -569,6 +609,7 @@ export interface AdaptiveModalSheetProps {
*/
function CompactSheetBody({
header,
showCloseButton,
onClose,
testID,
footer,
@@ -579,6 +620,7 @@ function CompactSheetBody({
children,
}: {
header?: SheetHeader;
showCloseButton: boolean;
onClose: () => void;
testID?: string;
footer: ReactNode;
@@ -608,7 +650,14 @@ function CompactSheetBody({
);
return (
<SheetVisibleFrame footer={footerView}>
{header ? <SheetHeaderView header={header} onClose={onClose} testID={testID} /> : null}
{header ? (
<SheetHeaderView
header={header}
onClose={onClose}
showCloseButton={showCloseButton}
testID={testID}
/>
) : null}
<View style={[styles.compactStaticContent, bodyStyle]}>
{scrollable ? (
<ScrollView
@@ -635,6 +684,7 @@ function CompactSheetBody({
export function AdaptiveModalSheet({
header,
showCloseButton = true,
visible,
onClose,
onDismiss,
@@ -762,6 +812,7 @@ export function AdaptiveModalSheet({
<OverlayLayerProvider layer={modalLayer}>
<CompactSheetBody
header={header}
showCloseButton={showCloseButton}
onClose={onClose}
testID={testID}
footer={footerView}
@@ -781,7 +832,9 @@ export function AdaptiveModalSheet({
desktopHeight == null ? styles.desktopStaticContent : styles.compactStaticContent;
const cardInner = (
<OverlayLayerProvider layer={modalLayer}>
{header ? <SheetHeaderView header={header} onClose={onClose} /> : null}
{header ? (
<SheetHeaderView header={header} onClose={onClose} showCloseButton={showCloseButton} />
) : null}
<View style={[scrollable ? styles.desktopScrollContainer : desktopStaticStyle, bodyStyle]}>
{scrollable ? (
<ScrollView
+13 -11
View File
@@ -1,6 +1,5 @@
import { SidebarViewSlot } from "@/plugins/sidebar-view";
import { useAddHost } from "@/hosts/add-host";
import { router } from "expo-router";
import {
CircleGauge,
FolderPlus,
@@ -85,8 +84,9 @@ import { useOwnsWindowChromeCorner, WindowChromeSafeArea } from "@/utils/desktop
import { useCloseAgentListGesture } from "@/mobile-panels/gestures";
import { useLeftPanelWidth } from "@/mobile-panels/provider";
import { MobilePanelOverlay } from "@/mobile-panels/presentation";
import { buildSettingsRoute } from "@/utils/host-routes";
import { openHostOverview } from "@/navigation/settings-navigation";
import { buildSettingsHostSectionRoute } from "@/utils/host-routes";
import { useActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store";
import { openSettingsFromSidebar } from "@/navigation/settings-navigation";
import { UsageSidebarItem, UsageSidebarRoot, useUsageSummary, useOpenSidebarUsage } from "@/usage";
import { SidebarAgentListSkeleton } from "./sidebar-agent-list-skeleton";
import { SidebarCalloutSlot } from "./sidebar-callout-slot";
@@ -157,6 +157,7 @@ export const LeftSidebar = memo(function LeftSidebar({
const { t } = useTranslation();
const insets = useSafeAreaInsets();
const isCompactLayout = useIsCompactFormFactor();
const activeWorkspace = useActiveWorkspaceSelection();
const showMobileAgent = usePanelStore((state) => state.showMobileAgent);
const {
@@ -193,25 +194,26 @@ export const LeftSidebar = memo(function LeftSidebar({
const openProjectPicker = useOpenAddProject();
const { open: openImportSession, sheet: importSessionSheet } = useImportSession();
// Each destination closes the navigation overlay first. Closing is idempotent, so a docked
// sidebar runs the same handler.
// Workspace destinations close the overlay; Settings retains it for the return journey.
const handleOpenProject = useCallback(() => {
void openProjectPicker();
}, [openProjectPicker]);
const handleSettings = useCallback(() => {
showMobileAgent();
router.push(buildSettingsRoute());
}, [showMobileAgent]);
openSettingsFromSidebar({ workspace: activeWorkspace, isCompact: isCompactLayout });
}, [activeWorkspace, isCompactLayout]);
const handleAddHost = useAddHost();
const handleOpenHostSettings = useCallback(
(serverId: string) => {
showMobileAgent();
openHostOverview(serverId);
openSettingsFromSidebar({
workspace: activeWorkspace,
isCompact: isCompactLayout,
route: buildSettingsHostSectionRoute(serverId, "host"),
});
},
[showMobileAgent],
[activeWorkspace, isCompactLayout],
);
const labels = useMemo(
@@ -1,5 +1,6 @@
import { AppearanceText as Text } from "@/appearance/text";
import { useMemo, type ReactNode } from "react";
import { Platform, ScrollView, Text, View } from "react-native";
import { Platform, ScrollView, View } from "react-native";
import { KeyboardAwareScrollView } from "react-native-keyboard-controller";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { StyleSheet } from "react-native-unistyles";
@@ -1,234 +0,0 @@
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,
},
}));
@@ -1,869 +0,0 @@
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,
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 refreshButtonStyle = useCallback(
({ hovered, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [
sheetStyles.iconButton,
(Boolean(hovered) || pressed) && sheetStyles.iconButtonHovered,
loading ? sheetStyles.disabled : null,
],
[loading],
);
const handleRefreshPress = useCallback(() => {
void fetchDiagnostic();
}, [fetchDiagnostic]);
const copyButtonStyle = useCallback(
({ hovered, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [
sheetStyles.iconButton,
(Boolean(hovered) || pressed) && Boolean(diagnostic) && sheetStyles.iconButtonHovered,
diagnostic ? null : sheetStyles.disabled,
],
[diagnostic],
);
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: (
<View style={sheetStyles.headerActions}>
<Pressable
onPress={handleCopyPress}
disabled={!diagnostic}
hitSlop={8}
style={copyButtonStyle}
accessibilityRole="button"
accessibilityLabel={t("settings.providers.diagnostic.copyAccessibility")}
>
<Copy size={theme.iconSize.sm} color={theme.colors.foregroundMuted} />
</Pressable>
<Pressable
onPress={handleRefreshPress}
disabled={loading}
hitSlop={8}
style={refreshButtonStyle}
accessibilityRole="button"
accessibilityLabel={
loading
? t("settings.providers.diagnostic.refreshingAccessibility")
: t("settings.providers.diagnostic.refreshAccessibility")
}
>
{loading ? (
<LoadingSpinner size={theme.iconSize.sm} color={theme.colors.foregroundMuted} />
) : (
<RotateCw size={theme.iconSize.sm} color={theme.colors.foregroundMuted} />
)}
</Pressable>
</View>
),
}),
[
copyButtonStyle,
diagnostic,
handleCopyPress,
handleRefreshPress,
loading,
refreshButtonStyle,
t,
theme.colors.foregroundMuted,
theme.iconSize.sm,
],
);
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,
},
headerActions: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[1],
},
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%"];
@@ -0,0 +1,480 @@
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();
});
});
@@ -0,0 +1,448 @@
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],
},
}));
@@ -0,0 +1,190 @@
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.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 { ProviderDiagnosticSheet } from "@/components/provider-diagnostic-sheet";
import { ProviderDetailSheet } from "@/provider-settings";
import { OverlayLayerProvider } from "@/lib/overlay-root";
import { useProviderSettingsStore } from "@/stores/provider-settings-store";
@@ -20,7 +20,7 @@ export function ProviderSettingsHost() {
return (
<OverlayLayerProvider layer={overlayParentLayer}>
<ProviderDiagnosticSheet
<ProviderDetailSheet
key={`${serverId}:${provider}`}
provider={provider}
serverId={serverId}
@@ -0,0 +1,48 @@
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();
});
});
@@ -0,0 +1,38 @@
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 } : {}) };
}
@@ -0,0 +1,60 @@
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 },
}));
@@ -0,0 +1,86 @@
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,12 +1,16 @@
import type { ReactNode } from "react";
import { SettingsRowHeader } from "./row-header";
import { SettingsRowHeader, type SettingsRowHintStatus } 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;
@@ -14,6 +18,10 @@ 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,5 +1,6 @@
import { AppearanceText as Text } from "@/appearance/text";
import { useMemo, type ReactNode } from "react";
import { Text, View, type StyleProp, type ViewStyle } from "react-native";
import { View, type StyleProp, type ViewStyle } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { ExternalLink, type ExternalLinkProps } from "@/components/ui/external-link";
import { SettingsInfoTip } from "./settings-info-tip";
+12 -1
View File
@@ -30,11 +30,16 @@ 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";
/** 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 {
@@ -58,6 +63,7 @@ export function SettingsCard({ children, testID }: { children: ReactNode; testID
export function SettingsRow({
label,
leading,
labelAccessory,
hint,
error,
@@ -70,6 +76,7 @@ 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}>
@@ -207,7 +214,11 @@ export function SettingsAction({ actionLabel, onPress, disabled, ...row }: Setti
}
const styles = StyleSheet.create((theme) => ({
compactRow: { flexWrap: "wrap", gap: theme.spacing[3] },
// 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" },
label: { flexGrow: 1, flexShrink: 1, flexBasis: 160, marginRight: theme.spacing[3] },
labelRow: {
flexDirection: "row",
@@ -2,7 +2,12 @@ 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, SettingsRow } from "@/components/settings";
import {
SettingsCard,
SettingsCollapsibleRow,
SettingsDetailRow,
SettingsRow,
} from "@/components/settings";
let root: Root | null = null;
let container: HTMLDivElement | null = null;
@@ -14,6 +19,8 @@ afterEach(() => {
container = null;
});
function openNothing() {}
function mountRows() {
container = document.createElement("div");
document.body.appendChild(container);
@@ -26,6 +33,7 @@ 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">
@@ -66,6 +74,13 @@ 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();
@@ -16,6 +16,8 @@ export function NestedSettingsRows({ 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. */
controlRow: StyleProp<ViewStyle>;
title: StyleProp<TextStyle>;
hint: StyleProp<TextStyle>;
/** The size of the controls in the row's trailing slot. */
@@ -30,12 +32,14 @@ export function useSettingsRowLayout(): SettingsRowLayout {
nested
? {
row: [settingsStyles.row, styles.nestedRow],
controlRow: [settingsStyles.row, styles.nestedRow],
title: [settingsStyles.rowTitle, styles.nestedText],
hint: [settingsStyles.rowHint, styles.nestedText],
controlSize: "sm",
}
: {
row: settingsStyles.row,
controlRow: [settingsStyles.row, styles.cardControlRow],
title: settingsStyles.rowTitle,
hint: settingsStyles.rowHint,
controlSize: "md",
@@ -45,6 +49,9 @@ 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,25 +1,36 @@
import { ChevronRight } from "lucide-react-native";
import { useCallback, useMemo, type ReactNode } from "react";
import { useCallback, useMemo, useState, 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 } from "./row-density";
import { useSettingsRowLayout, type SettingsRowLayout } from "./row-density";
const ThemedChevron = withUnistyles(ChevronRight);
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
const hoveredIconColorMapping = (theme: Theme) => ({ color: theme.colors.foreground });
type HoverState = PressableStateCallbackType & { hovered?: boolean };
/**
* 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";
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;
@@ -28,6 +39,10 @@ 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;
@@ -38,85 +53,216 @@ 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 rowStyle = useCallback(
({ hovered, pressed }: HoverState) => [
layout.row,
!disabled && hovered && styles.hovered,
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 pressTargetStyle = useCallback(
({ pressed }: PressableStateCallbackType) => [
styles.pressTarget,
!disabled && pressed && styles.pressed,
],
[disabled, layout],
[disabled],
);
const chevronStyle = useMemo(
() => [styles.chevron, expanded && styles.chevronExpanded],
[expanded],
);
return (
<PressHighlight
{...webAccessibilityProps}
accessibilityRole={external ? "link" : "button"}
accessibilityLabel={summary ? `${label}, ${summary}` : label}
accessibilityState={accessibilityState}
disabled={disabled}
onPress={onPress}
<View
style={rowStyle}
highlightStyle={styles.pressed}
onPointerEnter={handlePointerEnter}
onPointerLeave={handlePointerLeave}
testID={testID}
>
{({ hovered }: HoverState) => (
<>
<View style={settingsStyles.rowContent}>
{labelAccessory ? (
<View style={styles.labelRow}>
<Text style={layout.title}>{label}</Text>
{labelAccessory}
<PressHighlight
{...webAccessibilityProps}
accessibilityRole={external ? "link" : "button"}
accessibilityLabel={accessibilityLabel ?? (summary ? `${label}, ${summary}` : label)}
accessibilityState={accessibilityState}
disabled={disabled}
onPress={onPress}
style={pressTargetStyle}
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}
/>
</View>
) : (
<Text style={layout.title}>{label}</Text>
)}
{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>
)}
</>
)}
</>
)}
</PressHighlight>
</>
)}
</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} />
)}
<Text style={textStyle} numberOfLines={1}>
{hint}
</Text>
</View>
);
}
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.absoluteFillObject,
},
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,
@@ -1,8 +1,8 @@
import { PressHighlight as Pressable } from "@/components/ui/press-highlight";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import {
View,
Text,
Pressable,
ScrollView,
type GestureResponderEvent,
type PressableStateCallbackType,
@@ -674,7 +674,11 @@ function WorkspaceRowRightGroup({
{renderSlot ? (
<SidebarWorkspaceTrailingActionSlot reserveWidth={reserveSlotWidth}>
<SidebarWorkspaceTrailingActionBase presentation={trailingPresentation}>
<SidebarWorkspaceTrailingContent workspace={workspace} trailing={trailing} />
<SidebarWorkspaceTrailingContent
workspace={workspace}
trailing={trailing}
backdrop={backdrop}
/>
</SidebarWorkspaceTrailingActionBase>
<SidebarWorkspaceTrailingActionOverlay
visible={kebab.showKebab}
@@ -2588,7 +2592,9 @@ const styles = StyleSheet.create((theme) => ({
// Optical inset: aligns the visible Pinned/Workspaces glyph edge with the
// Schedules icon across the divider; their layout boxes have different insets.
paddingTop: 2,
paddingBottom: theme.spacing[4],
// Keep the last row scrollable above the sidebar toast, including a wrapped Undo row.
// This space stays present across toast changes so the scroll range never jumps.
paddingBottom: theme.spacing[24],
},
projectListContainer: {
width: "100%",
@@ -1,6 +1,7 @@
import { PressHighlight as Pressable } from "@/components/ui/press-highlight";
import { useCallback } from "react";
import { useTranslation } from "react-i18next";
import { Pressable, Text, View, type PressableStateCallbackType } from "react-native";
import { Text, View, type PressableStateCallbackType } from "react-native";
import { ChevronDown, ChevronUp } from "lucide-react-native";
import { StyleSheet } from "react-native-unistyles";
import { isWeb } from "@/constants/platform";
@@ -1,5 +1,6 @@
import { PressHighlight as Pressable } from "@/components/ui/press-highlight";
import { useCallback, useState, type ComponentType, type ReactNode, type Ref } from "react";
import { Pressable, Text, View } from "react-native";
import { Text, View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { HEADER_INNER_HEIGHT, HEADER_INNER_HEIGHT_MOBILE } from "@/constants/layout";
import { DensityIcon } from "@/components/ui/density-icon";
@@ -1,6 +1,7 @@
import { PressHighlight as Pressable } from "@/components/ui/press-highlight";
import { useMemo, type ReactNode } from "react";
import { ChevronDown, ChevronRight } from "lucide-react-native";
import { Pressable, Text, View } from "react-native";
import { Text, View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { DensityIcon } from "@/components/ui/density-icon";
import { useIsCompactFormFactor } from "@/constants/layout";
@@ -1,3 +1,4 @@
import { PressHighlight as Pressable } from "@/components/ui/press-highlight";
import {
memo,
useCallback,
@@ -11,7 +12,6 @@ import { useTranslation } from "react-i18next";
import {
View,
Text,
Pressable,
ScrollView,
type GestureResponderEvent,
type PressableStateCallbackType,
@@ -1029,7 +1029,11 @@ function StatusWorkspaceActionSlot({
return (
<SidebarWorkspaceTrailingActionSlot reserveWidth={reserveSlotWidth}>
<SidebarWorkspaceTrailingActionBase presentation={trailingPresentation}>
<SidebarWorkspaceTrailingContent workspace={workspace} trailing={trailing} />
<SidebarWorkspaceTrailingContent
workspace={workspace}
trailing={trailing}
backdrop={backdrop}
/>
</SidebarWorkspaceTrailingActionBase>
<SidebarWorkspaceTrailingActionOverlay
visible={kebab.showKebab}
@@ -1097,7 +1101,8 @@ const styles = StyleSheet.create((theme) => ({
paddingHorizontal: theme.spacing[2],
// Keep status mode's Pinned/Workspaces boundary identical to project mode.
paddingTop: 2,
paddingBottom: theme.spacing[4],
// Match project grouping: permanent room to scroll the final row above sidebar toasts.
paddingBottom: theme.spacing[24],
},
pinnedSection: {
marginBottom: theme.spacing[1],
@@ -180,6 +180,7 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
<View style={sidebarWorkspaceRowStyles.rowRight}>{children}</View>
</View>
<WorkspaceMetaRow
backdrop={backdrop}
currentBranch={workspace.currentBranch}
projectName={leadingProjectName}
hostBadge={hostBadge ?? null}
@@ -1,6 +1,7 @@
import { PressHighlight as Pressable } from "@/components/ui/press-highlight";
import { Fragment, useCallback, useState, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { Pressable, Text, View, type GestureResponderEvent } from "react-native";
import { Text, View, type GestureResponderEvent } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { ExternalLink, Folder, GitBranch, Globe } from "lucide-react-native";
import {
@@ -15,6 +16,7 @@ import { getForgePresentation, normalizeForge } from "@/git/forge";
import { openExternalUrl } from "@/utils/open-external-url";
import { useSidebarMetaPreferences } from "@/components/sidebar/display-preferences/model";
import type { Theme } from "@/styles/theme";
import type { SidebarSurfaceBackdrop } from "@/styles/surface-backdrop";
import { PullRequestStateIcon } from "@/git/pull-request-state-icon";
import {
PluginWorkspaceRowBadgeItems,
@@ -75,6 +77,7 @@ export function WorkspaceMetaRow({
serviceSummary,
labels = EMPTY_LABELS,
workspace = null,
backdrop,
}: {
currentBranch: string | null;
projectName: string | null;
@@ -84,6 +87,7 @@ export function WorkspaceMetaRow({
labels?: readonly WorkspaceLabelDefinition[];
/** The real workspace behind the row; previews leave it out and get no plugin items. */
workspace?: { serverId: string; workspaceId: string } | null;
backdrop: SidebarSurfaceBackdrop;
}) {
const { rowItems, checksDisplay } = useSidebarMetaPreferences();
const items = selectMetaRowItems({
@@ -104,7 +108,17 @@ export function WorkspaceMetaRow({
<View style={styles.row}>
{items.map((item, index) => (
<Fragment key={item.kind}>
{index > 0 ? <Text style={styles.separator}>·</Text> : null}
{index > 0 ? (
<Text
style={[
styles.separator,
backdrop === "surfaceSidebarHover" && styles.separatorHovered,
backdrop === "surfaceSidebarSelected" && styles.separatorSelected,
]}
>
·
</Text>
) : null}
<MetaItemNode item={item} hostBadge={hostBadge} leading={index === 0} />
</Fragment>
))}
@@ -362,6 +376,8 @@ const styles = StyleSheet.create((theme) => ({
lineHeight: 16,
flexShrink: 0,
},
separatorHovered: { color: theme.colors.foregroundSidebarHover },
separatorSelected: { color: theme.colors.foregroundSidebarSelected },
// Tighter than the line's own gap so a run of chips reads as one item — see `LabelsItem`.
// Shrinks at the same weight as the service name: both are arbitrary text somebody chose, so
// a crowded line takes from the two of them in proportion rather than emptying one of them.
@@ -5,6 +5,7 @@ import type { SidebarWorkspaceEntry } from "@/hooks/use-sidebar-workspaces-list"
import { useAppSettings } from "@/hooks/use-settings";
import type { SidebarWorkspaceTrailing } from "@/hooks/use-settings";
import { useCompactTimeAgo } from "@/hooks/use-time-ago";
import type { SidebarSurfaceBackdrop } from "@/styles/surface-backdrop";
export type { SidebarWorkspaceTrailing };
@@ -39,9 +40,11 @@ export function hasSidebarWorkspaceTrailing({
export function SidebarWorkspaceTrailingContent({
workspace,
trailing,
backdrop,
}: {
workspace: SidebarWorkspaceEntry;
trailing: SidebarWorkspaceTrailing;
backdrop: SidebarSurfaceBackdrop;
}) {
if (trailing === "diff" && workspace.diffStat) {
return (
@@ -49,7 +52,7 @@ export function SidebarWorkspaceTrailingContent({
);
}
if (trailing === "timestamp" && workspace.statusEnteredAt) {
return <WorkspaceTimestamp enteredAt={workspace.statusEnteredAt} />;
return <WorkspaceTimestamp enteredAt={workspace.statusEnteredAt} backdrop={backdrop} />;
}
return null;
}
@@ -59,10 +62,24 @@ export function SidebarWorkspaceTrailingContent({
* re-renders the component that owns it — keeping that component down to a single `<Text>` is
* what stops a minute tick from reaching the row, the list, or the diff stat next door.
*/
function WorkspaceTimestamp({ enteredAt }: { enteredAt: Date }) {
function WorkspaceTimestamp({
enteredAt,
backdrop,
}: {
enteredAt: Date;
backdrop: SidebarSurfaceBackdrop;
}) {
const label = useCompactTimeAgo(enteredAt);
return (
<Text style={styles.timestamp} numberOfLines={1} testID="sidebar-workspace-timestamp">
<Text
style={[
styles.timestamp,
backdrop === "surfaceSidebarHover" && styles.hovered,
backdrop === "surfaceSidebarSelected" && styles.selected,
]}
numberOfLines={1}
testID="sidebar-workspace-timestamp"
>
{label}
</Text>
);
@@ -80,4 +97,6 @@ const styles = StyleSheet.create((theme) => ({
fontWeight: theme.fontWeight.normal,
flexShrink: 0,
},
hovered: { color: theme.colors.foregroundSidebarHover },
selected: { color: theme.colors.foregroundSidebarSelected },
}));
@@ -32,4 +32,32 @@ describe("useToastHost", () => {
act(() => dismissUploading());
expect(result.current.toast?.content).toBe("Image uploaded");
});
it("ends each toast's undo opportunity once, including replacement", () => {
const { result } = renderHook(() => useToastHost());
const dismissed: string[] = [];
let dismissFirst = () => {};
let dismissSecond = () => {};
act(() => {
dismissFirst = result.current.api.show("First archive", {
onDismiss: () => dismissed.push("first"),
});
});
act(() => {
dismissSecond = result.current.api.show("Second archive", {
onDismiss: () => dismissed.push("second"),
});
});
expect(dismissed).toEqual(["first"]);
act(() => dismissFirst());
expect(result.current.toast?.content).toBe("Second archive");
expect(dismissed).toEqual(["first"]);
act(() => {
dismissSecond();
dismissSecond();
result.current.dismiss();
});
expect(result.current.toast).toBeNull();
expect(dismissed).toEqual(["first", "second"]);
});
});
+36 -33
View File
@@ -8,7 +8,7 @@ import { Platform, StyleSheet as NativeStyleSheet, Text, ToastAndroid, View } fr
import Animated, { FadeIn, FadeOut } from "react-native-reanimated";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import type { Theme } from "@/styles/theme";
import { SPACING, type Theme } from "@/styles/theme";
import { useTranslation } from "react-i18next";
import { useIsCompactFormFactor } from "@/constants/layout";
import { isWeb } from "@/constants/platform";
@@ -212,10 +212,18 @@ export function ToastViewport({
const topOffset =
placement === "app-shell" ? insets.top + headerTopPadding + headerHeight : panelClearance;
const content = (
<View
// Keep the bottom anchor and its contents together while the native exit retains the view.
const content = toast ? (
<Animated.View
entering={toastEntering}
exiting={toastExiting}
style={
placement === "sidebar" ? styles.sidebarContainer : styles.container(placement, topOffset)
placement === "sidebar"
? animatedStyles.sidebarContainer
: [
animatedStyles.container,
{ top: topOffset + (placement === "app-shell" ? SPACING[2] : SPACING[3]) },
]
}
pointerEvents="box-none"
collapsable={false}
@@ -225,20 +233,16 @@ export function ToastViewport({
pointerEvents="box-none"
collapsable={false}
>
{toast ? (
<Animated.View
entering={toastEntering}
exiting={toastExiting}
style={animatedStyles.surface}
testID={toast.testID ?? "app-toast"}
accessibilityRole="alert"
>
<ToastCard toast={toast} onPointerEnter={pauseDismiss} onPointerLeave={resumeDismiss} />
</Animated.View>
) : null}
<View
style={animatedStyles.surface}
testID={toast.testID ?? "app-toast"}
accessibilityRole="alert"
>
<ToastCard toast={toast} onPointerEnter={pauseDismiss} onPointerLeave={resumeDismiss} />
</View>
</View>
</View>
);
</Animated.View>
) : null;
if (placement === "app-shell" && isWeb && typeof document !== "undefined") {
return createPortal(content, getOverlayRoot());
@@ -294,26 +298,25 @@ function ToastCard({
}
const animatedStyles = NativeStyleSheet.create({
container: {
position: "absolute",
left: SPACING[4],
right: SPACING[4],
zIndex: OVERLAY_Z.toast,
alignItems: "center",
},
sidebarContainer: {
position: "absolute",
left: SPACING[2],
right: SPACING[2],
bottom: SPACING[2],
zIndex: OVERLAY_Z.toast,
alignItems: "center",
},
surface: { alignSelf: "center", maxWidth: "100%" },
});
const styles = StyleSheet.create((theme) => ({
container: (placement: Exclude<ToastViewportPlacement, "sidebar">, topOffset: number) => ({
position: "absolute",
left: theme.spacing[4],
right: theme.spacing[4],
top: topOffset + (placement === "app-shell" ? theme.spacing[2] : theme.spacing[3]),
zIndex: OVERLAY_Z.toast,
alignItems: "center",
}),
sidebarContainer: {
position: "absolute",
left: theme.spacing[2],
right: theme.spacing[2],
bottom: theme.spacing[2],
zIndex: OVERLAY_Z.toast,
alignItems: "center",
},
widthBoundary: {
width: "92%",
maxWidth: TOAST_MAX_WIDTH,
+2 -1
View File
@@ -1,3 +1,4 @@
import { AppearanceText as Text } from "@/appearance/text";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { useContainedControlSize } from "@/components/ui/control-size";
import {
@@ -10,7 +11,7 @@ import {
type ReactElement,
type ReactNode,
} from "react";
import { Pressable, Text, View } from "react-native";
import { Pressable, View } from "react-native";
import type {
PressableProps,
PressableStateCallbackType,
@@ -42,7 +42,7 @@ vi.mock("@/components/ui/press-highlight", () => ({
afterEach(() => vi.unstubAllGlobals());
describe("ContextMenuTrigger", () => {
it("preserves a static trigger style so the native press highlight can inherit its corners", () => {
it("preserves a static trigger style for the native pressable", () => {
vi.stubGlobal("React", React);
const rowStyle = [{ borderRadius: 8 }, { backgroundColor: "#111" }];
@@ -144,11 +144,20 @@ describe("toolbar glyphs and spacing", () => {
expect(toolbarGlyphsFor("touch").label).toEqual({
size: 20,
strokeWidth: 1.5,
tone: "foreground",
tone: "muted",
});
expect(TOOLBAR_GLYPH_SIZES.label).toEqual({ xs: 20, md: 16 });
});
it("mutes a touch glyph paired with a label while keeping an icon-only touch glyph foreground", () => {
const { icon, label } = toolbarGlyphsFor("touch");
const colors = { foreground: "#fafafa", foregroundMuted: "#a1a5a4" };
const palette = { colors } as unknown as Theme;
expect(toolbarGlyphColor(palette, label.tone)).toBe(colors.foregroundMuted);
expect(toolbarGlyphColor(palette, icon.tone)).toBe(colors.foreground);
});
it("sizes the touch context ring to the toolbar glyph's ink and keeps the pointer ring", () => {
expect(TOOLBAR_RINGS).toEqual({
touch: { size: 18, strokeWidth: 2 },
@@ -132,9 +132,10 @@ export function iconSizeFor(size: IconSize): SizingValue {
}
/**
* The glyph a toolbar control paints. Touch-sized every toolbar glyph matches the header icons:
* 20pt at the app's 1.5px stroke, resting at `foreground`. Pointer-sized it is the `md` glyph at
* the same stroke and rests muted until hovered.
* The glyph a toolbar control paints. Touch-sized every toolbar glyph is 20pt at the app's 1.5px
* stroke. An icon-only control's glyph matches the header icons and rests at `foreground`; a glyph
* paired with a label rests muted so the control reads as one quiet unit with its label.
* Pointer-sized it is the `md` glyph at the same stroke and rests muted until hovered.
*/
export type ToolbarGlyphTone = "foreground" | "muted";
@@ -160,7 +161,7 @@ const POINTER_TOOLBAR_GLYPH: ToolbarGlyph = {
const TOOLBAR_GLYPHS: Record<ControlSizing, ToolbarGlyphs> = {
touch: {
icon: { size: TOUCH_ICON_SIZE.md, strokeWidth: ICON_STROKE_WIDTH, tone: "foreground" },
label: { size: TOUCH_ICON_SIZE.md, strokeWidth: ICON_STROKE_WIDTH, tone: "foreground" },
label: { size: TOUCH_ICON_SIZE.md, strokeWidth: ICON_STROKE_WIDTH, tone: "muted" },
},
pointer: { icon: POINTER_TOOLBAR_GLYPH, label: POINTER_TOOLBAR_GLYPH },
};
@@ -1,5 +1,6 @@
import { AppearanceText as Text } from "@/appearance/text";
import { useCallback, useMemo, type ReactElement, type ReactNode } from "react";
import { Text, View } from "react-native";
import { View } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { ChevronDown } from "lucide-react-native";
import {
@@ -1,5 +1,5 @@
import { forwardRef, useMemo } from "react";
import { Text, type View } from "react-native";
import { forwardRef, useCallback, useMemo } from "react";
import { Text, type PressableStateCallbackType, type View } from "react-native";
import type { LucideIcon } from "lucide-react-native";
import { StyleSheet } from "react-native-unistyles";
import { PressHighlight } from "@/components/ui/press-highlight";
@@ -35,10 +35,11 @@ export const FloatingActionButton = forwardRef<View, FloatingActionButtonProps>(
ref,
) {
const accessibilityState = useMemo(() => ({ disabled }), [disabled]);
const buttonStyle = useMemo(
() => [
const buttonStyle = useCallback(
({ pressed }: PressableStateCallbackType) => [
styles.button,
label && styles.labeled,
pressed && styles.pressed,
disabled && styles.disabled,
{ bottom: FLOATING_ACTION_BUTTON_INSET + bottomInset },
],
@@ -53,7 +54,6 @@ export const FloatingActionButton = forwardRef<View, FloatingActionButtonProps>(
disabled={disabled}
onPress={onPress}
style={buttonStyle}
highlightStyle={styles.pressed}
testID={testID}
>
<Icon size={ICON_SIZE.lg} color={styles.glyph.color} />
@@ -86,7 +86,7 @@ const styles = StyleSheet.create((theme) => ({
label: { color: theme.colors.foreground, fontSize: theme.fontSize.base },
disabled: { opacity: theme.opacity[50] },
pressed: {
backgroundColor: theme.colors.interactionHighlight,
backgroundColor: theme.colors.surface2,
},
glyph: {
color: theme.colors.foreground,
@@ -0,0 +1,60 @@
import React from "react";
import { cleanup, fireEvent, render, waitFor } from "@testing-library/react";
import { ArrowUp } from "lucide-react-native";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import { afterEach, expect, it } from "vitest";
import { PressHighlight } from "./press-highlight.native";
import { FloatingActionButton } from "./floating-action-button";
const rowStyle = { backgroundColor: "rgb(255, 255, 255)", borderRadius: 8 };
const highlightStyle = { backgroundColor: "rgb(20, 30, 40)" };
afterEach(cleanup);
function onPress() {}
it("keeps a floating action opaque while showing its held-press feedback", async () => {
const { getByRole } = render(
<FloatingActionButton icon={ArrowUp} accessibilityLabel="Jump to file" onPress={onPress} />,
);
const button = getByRole("button", { name: "Jump to file" });
const restingFill = getComputedStyle(button).backgroundColor;
fireEvent.mouseDown(button, { button: 0 });
await waitFor(() => {
const pressedFill = getComputedStyle(button).backgroundColor;
expect(pressedFill).not.toBe(restingFill);
expect(pressedFill).toMatch(/^rgb\(/);
});
fireEvent.mouseUp(button, { button: 0 });
await waitFor(() => expect(getComputedStyle(button).backgroundColor).toBe(restingFill));
});
it("uses the pressable's pressed state for the native row fill and its existing corners", () => {
const { getByTestId, rerender } = render(
<GestureHandlerRootView>
<PressHighlight
testID="row"
testOnly_pressed
style={rowStyle}
highlightStyle={highlightStyle}
/>
</GestureHandlerRootView>,
);
expect(getComputedStyle(getByTestId("row")).backgroundColor).toBe("rgb(20, 30, 40)");
expect(getComputedStyle(getByTestId("row")).borderRadius).toBe("8px");
rerender(
<GestureHandlerRootView>
<PressHighlight
testID="row"
testOnly_pressed={false}
style={rowStyle}
highlightStyle={highlightStyle}
/>
</GestureHandlerRootView>,
);
expect(getComputedStyle(getByTestId("row")).backgroundColor).toBe("rgb(255, 255, 255)");
});
@@ -1,74 +1,21 @@
import { forwardRef, useMemo } from "react";
import { Pressable, StyleSheet, View } from "react-native";
import { Gesture, GestureDetector } from "react-native-gesture-handler";
import Animated, { useAnimatedStyle, useSharedValue } from "react-native-reanimated";
import { resolveHighlightCorners } from "./press-highlight.shape";
import { forwardRef, useCallback } from "react";
import { Pressable, type PressableStateCallbackType, type View } from "react-native";
import type { PressHighlightProps } from "./press-highlight.types";
export const PressHighlight = forwardRef<View, PressHighlightProps>(function PressHighlight(
{ children, disabled, highlightStyle, ...props },
{ highlightStyle, style, unstable_pressDelay = 130, ...props },
ref,
) {
const highlighted = useSharedValue(0);
const corners = useMemo(() => resolveHighlightCorners(props.style), [props.style]);
const animatedHighlightStyle = useAnimatedStyle(() => ({ opacity: highlighted.value }));
// This gesture owns visual acknowledgement only. Pressable remains the sole owner of
// activation, cancellation, accessibility, and the caller's drag/long-press callbacks.
const pressGesture = useMemo(
() =>
Gesture.Tap()
.enabled(disabled !== true && highlightStyle != null)
.maxDistance(8)
.shouldCancelWhenOutside(true)
.onBegin(() => {
highlighted.value = 1;
})
.onFinalize(() => {
highlighted.value = 0;
}),
[disabled, highlightStyle, highlighted],
// Give the scroll view time to claim a pan before Pressable activates its feedback.
const pressStyle = useCallback(
(state: PressableStateCallbackType) => [
typeof style === "function" ? style(state) : style,
state.pressed && highlightStyle,
],
[style, highlightStyle],
);
const highlight = highlightStyle ? (
<Animated.View pointerEvents="none" style={[styles.highlight, animatedHighlightStyle]}>
{/* Keep the themed Unistyles node separate from the node Reanimated patches. The
pressable's corners come first so `highlightStyle` can still override them. */}
<View style={[styles.highlightFill, corners, highlightStyle]} />
</Animated.View>
) : null;
const renderedChildren =
typeof children === "function" ? (
(state: Parameters<typeof children>[0]) => (
<>
{highlight}
{children(state)}
</>
)
) : (
<>
{highlight}
{children}
</>
);
const pressable = (
<Pressable ref={ref} {...props} collapsable={false} disabled={disabled}>
{renderedChildren}
</Pressable>
return (
<Pressable {...props} ref={ref} unstable_pressDelay={unstable_pressDelay} style={pressStyle} />
);
if (!highlightStyle) {
return pressable;
}
return <GestureDetector gesture={pressGesture}>{pressable}</GestureDetector>;
});
const styles = StyleSheet.create({
highlight: {
...StyleSheet.absoluteFill,
},
highlightFill: {
...StyleSheet.absoluteFill,
},
});
@@ -1,38 +0,0 @@
import { describe, expect, it } from "vitest";
import type { StyleProp, ViewStyle } from "react-native";
import { resolveHighlightCorners } from "./press-highlight.shape";
describe("resolveHighlightCorners", () => {
it("takes the radius from the pressable's own style, the way a sidebar row declares it", () => {
const row = { minHeight: 36, borderRadius: 8, backgroundColor: "#111" };
expect(resolveHighlightCorners(row)).toEqual({ borderRadius: 8 });
});
it("reads through the style array a row builds per interaction state", () => {
const row: StyleProp<ViewStyle> = [{ borderRadius: 8 }, false, { backgroundColor: "#222" }];
expect(resolveHighlightCorners(row)).toEqual({ borderRadius: 8 });
});
it("keeps the last radius when a later entry in the array reshapes the row", () => {
expect(resolveHighlightCorners([{ borderRadius: 8 }, { borderRadius: 999 }])).toEqual({
borderRadius: 999,
});
});
it("carries every corner a row sets individually", () => {
const row = { borderTopLeftRadius: 8, borderBottomRightRadius: 2, paddingLeft: 12 };
expect(resolveHighlightCorners(row)).toEqual({
borderTopLeftRadius: 8,
borderBottomRightRadius: 2,
});
});
it("returns no corners for a square row, rather than a zero it never asked for", () => {
expect(resolveHighlightCorners({ backgroundColor: "#111" })).toEqual({});
expect(resolveHighlightCorners(undefined)).toEqual({});
});
it("leaves a style resolved per press state alone", () => {
expect(resolveHighlightCorners(() => ({ borderRadius: 8 }))).toEqual({});
});
});
@@ -1,48 +0,0 @@
import { StyleSheet, type StyleProp, type ViewStyle } from "react-native";
/**
* A press highlight is drawn as an overlay inside the pressable rather than as a background on
* it, because the node Reanimated animates cannot also carry the caller's themed style. An
* overlay inherits nothing, so a rounded row gets a square flash unless the corners are copied
* across.
*
* They are copied from the row's own style, not asked for again: the row already declares its
* shape once, and a highlight that had to restate it would be a second copy free to drift. That
* leaves `highlightStyle` to mean only what the highlight is painted with.
*/
const CORNER_PROPERTIES = [
"borderRadius",
"borderTopLeftRadius",
"borderTopRightRadius",
"borderBottomLeftRadius",
"borderBottomRightRadius",
"borderStartStartRadius",
"borderStartEndRadius",
"borderEndStartRadius",
"borderEndEndRadius",
] as const;
/**
* The corner radii a pressable's own style gives its highlight. A style resolved per press state
* is left alone — its shape is not knowable before the press it describes, and every corner it
* could name is one the caller can still set through `highlightStyle`.
*/
export function resolveHighlightCorners(
style: StyleProp<ViewStyle> | ((state: never) => StyleProp<ViewStyle>) | undefined,
): ViewStyle {
if (typeof style === "function") {
return {};
}
const flattened = StyleSheet.flatten(style);
if (!flattened) {
return {};
}
const corners: ViewStyle = {};
for (const property of CORNER_PROPERTIES) {
const value = flattened[property];
if (value !== undefined) {
corners[property] = value;
}
}
return corners;
}
@@ -1,13 +1,6 @@
import type { PressableProps, StyleProp, ViewStyle } from "react-native";
export interface PressHighlightProps extends PressableProps {
/**
* What the native finger-down surface is painted with — a background colour, an opacity.
* Desktop hover remains owned by the caller.
*
* Shape is not part of it: the highlight takes its corners from the pressable's own `style`, so
* a rounded row gets a rounded flash without restating the radius. Set a corner here only to
* depart from the row's shape on purpose.
*/
/** Native pressed style. Feedback and cancellation follow Pressable's press lifecycle. */
highlightStyle?: StyleProp<ViewStyle>;
}
@@ -17,7 +17,7 @@ import { formatThinkingOptionLabel } from "@/agent-controls/labels";
import { CombinedModelSelector } from "@/components/combined-model-selector";
import {
buildProviderSelectorProviders,
buildSelectableProviderSelectorProviders,
buildSelectorProvider,
type ProviderSelectorProvider,
} from "@/provider-selection/provider-selection";
import { filterSelectableModels } from "@/provider-selection/model-catalog";
@@ -1034,7 +1034,7 @@ export const AgentControls = memo(function AgentControls({
);
const agentModelSelectorProviders = useMemo(() => {
if (snapshotSelectedEntry) {
return buildSelectableProviderSelectorProviders([snapshotSelectedEntry]);
return [buildSelectorProvider(snapshotSelectedEntry)];
}
return buildProviderSelectorProviders({
providerDefinitions: agentProviderDefinitions,
@@ -251,7 +251,7 @@ describe("composer control layout", () => {
controlSize: 36,
glyphs: {
icon: { size: 20, strokeWidth: 1.5, tone: "foreground" },
label: { size: 20, strokeWidth: 1.5, tone: "foreground" },
label: { size: 20, strokeWidth: 1.5, tone: "muted" },
},
controlGap: 0,
labelPadding: 8,
+1 -1
View File
@@ -97,7 +97,7 @@ import {
} from "@/components/ui/text-input";
const ComposerTextInput = withUnistyles(EditingTextInput, (theme) => ({
placeholderTextColor: theme.colors.surface4,
placeholderTextColor: theme.colors.foregroundExtraMuted,
}));
import {
resolveSendTooltipLabel,
+18 -1
View File
@@ -1,7 +1,8 @@
import { usePaneContext } from "@/panels/pane-context";
import { useEffect, useMemo, useState } from "react";
import { useCallback, useEffect, useMemo, useState } from "react";
import type { PluginFile, PluginTab } from "@getpaseo/plugin/client";
import { Text, View } from "react-native";
import { Download } from "lucide-react-native";
import { StyleSheet } from "react-native-unistyles";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
@@ -10,6 +11,7 @@ import { useFileHandle, useFileHandleSnapshot } from "@/file-panels/file";
import { FilePanelLoading } from "@/file-panels/loading";
import { FilePanelPicker, FilePanelView, useFilePanelChoice, type FilePanel } from "@/file-panels";
import { resolveFilePreviewReadTarget } from "@/file-explorer/preview-target";
import { useFileDownload } from "@/hooks/use-file-download";
import { useAppActivelyVisible } from "@/hooks/use-app-visible";
import { usePublishPanelInstanceAttributes } from "@/panels/panel-instance-attributes";
import { useSessionStore } from "@/stores/session-store";
@@ -24,11 +26,13 @@ import type { WorkspaceFileLocation } from "@/workspace/file-open";
*/
export function FilePane({
serverId,
workspaceId,
workspaceRoot,
location,
navigationRevision,
}: {
serverId: string;
workspaceId?: string | null;
workspaceRoot: string;
location: WorkspaceFileLocation;
navigationRevision: number;
@@ -41,6 +45,16 @@ export function FilePane({
() => (path ? resolveFilePreviewReadTarget({ path, workspaceRoot: root }) : null),
[path, root],
);
const downloadFile = useFileDownload({
serverId,
workspaceId,
workspaceRoot: target?.cwd ?? root,
});
const handleDownload = useCallback(() => {
if (target) {
downloadFile({ fileName: path.split(/[\\/]/).pop() ?? path, path: target.path });
}
}, [downloadFile, path, target]);
const absolutePath = useMemo(
() => buildAbsoluteExplorerPath({ workspaceRoot: root, entryPath: path }),
[path, root],
@@ -100,6 +114,9 @@ export function FilePane({
<>
<Text style={styles.mutedText}>{t("panels.file.binaryPreviewUnavailable")}</Text>
<Text style={styles.mutedText}>{formatFileSize(snapshot.size)}</Text>
<Button variant="outline" leftIcon={Download} onPress={handleDownload}>
{t("workspace.fileActions.download")}
</Button>
</>
);
} else {
@@ -196,7 +196,7 @@ describe("applyCheckoutStatusUpdateFromEvent", () => {
).toBe(false);
});
it("drops the checkout's cached draft slash commands when its branch changes", () => {
it("marks draft slash commands stale without clearing them when the branch changes", () => {
const queryClient = createQueryClient();
queryClient.setQueryData(
checkoutStatusQueryKey(serverId, cwd),
@@ -219,7 +219,9 @@ describe("applyCheckoutStatusUpdateFromEvent", () => {
message: checkoutStatusUpdate(checkoutStatus({ currentBranch: "main" })),
});
expect(queryClient.getQueryData(thisCheckout)).toBeUndefined();
expect(queryClient.getQueryData(thisCheckout)).toEqual([{ name: "build-paseo" }]);
expect(queryClient.getQueryState(thisCheckout)?.isInvalidated).toBe(true);
expect(queryClient.getQueryState(otherCheckout)?.isInvalidated).toBe(false);
expect(queryClient.getQueryData(otherCheckout)).toEqual([{ name: "build-paseo" }]);
});
@@ -8,7 +8,7 @@ import {
invalidatePrPaneTimelineForCheckout,
} from "@/git/query-keys";
import { type CheckoutPrStatusPayload, normalizeCheckoutPrStatusPayload } from "@/git/pr-status";
import { resetDraftAgentCommandsForCheckout } from "@/agent-commands/cache";
import { invalidateDraftAgentCommandsForCheckout } from "@/agent-commands/cache";
export type CheckoutStatusPayload = CheckoutStatusResponse["payload"];
export type { CheckoutPrStatusPayload } from "@/git/pr-status";
@@ -66,7 +66,7 @@ export function applyCheckoutStatusUpdateFromEvent({
);
queryClient.setQueryData(checkoutStatusQueryKey(serverId, payload.cwd), cachePayload);
if (previousStatus?.currentBranch !== payload.currentBranch) {
void resetDraftAgentCommandsForCheckout(queryClient, { serverId, cwd: payload.cwd });
void invalidateDraftAgentCommandsForCheckout(queryClient, { serverId, cwd: payload.cwd });
}
void queryClient.invalidateQueries({
queryKey: checkoutCommitsQueryKey(serverId, payload.cwd),
@@ -235,8 +235,12 @@ export function useAgentFormState(options: UseAgentFormStateOptions): UseAgentFo
[snapshotEntries],
);
const snapshotModelSelectorProviders = useMemo(
() => buildSelectableProviderSelectorProviders(snapshotEntries, isConnected),
[snapshotEntries, isConnected],
() =>
buildSelectableProviderSelectorProviders(snapshotEntries, {
isConnected,
selectedProvider: formState.provider || null,
}),
[snapshotEntries, isConnected, formState.provider],
);
const snapshotSelectedEntry = useMemo(
() =>
+39 -2
View File
@@ -261,7 +261,7 @@ export const ar: TranslationResources = {
states: {
notFound: "لم يتم العثور على Agent",
failedToLoad: "فشل تحميل الوكيل",
reconnecting: "جارٍ إعادة الاتصال بالمضيف",
reconnecting: "جارٍ إعادة الاتصال",
updating: "جارٍ تحديث الرسائل",
timelineSyncFailed: "تعذر تحديث سجل الوكيل.",
timelineSyncRetrying: "جارٍ إعادة المحاولة…",
@@ -1702,7 +1702,7 @@ export const ar: TranslationResources = {
},
providers: {
label: "المزوّدون",
title: "وكلاؤك",
title: "مزوّدوك",
description: "يشغّل Paseo أدوات CLI للوكلاء المثبتة على هذا الكمبيوتر",
},
projects: {
@@ -3047,6 +3047,22 @@ export const ar: TranslationResources = {
providers: {
title: "مقدمي الخدمات",
addProvider: "إضافة مزود",
list: {
add: "مزود",
updatingTo: "جارٍ التحديث إلى {{version}}...",
},
detail: {
backToProviders: "العودة إلى المزودين",
notOnHost: "هذا المزود غير موجود على هذا المضيف",
enabled: "مفعّل",
unavailableTitle: "{{name}} غير متاح",
troubleshooting: "استكشاف الأخطاء",
status: "حالة المزود",
checked: "تم الفحص {{time}}",
diagnosticReport: "تقرير التشخيص",
dangerZone: "منطقة الخطر",
removeHint: "يحذف هذا المزود من config.json",
},
providerDetails: "تفاصيل مزود{{name}}",
enableProvider: "تمكين{{name}}",
unavailable: "اتصل بهذا المضيف لرؤية مقدمي الخدمة",
@@ -3088,10 +3104,31 @@ export const ar: TranslationResources = {
retrying: "جارٍ إعادة المحاولة...",
noSearchMatches: "لا توجد نماذج تطابق بحثك",
noneDetected: "لم يتم اكتشاف أي نماذج",
noCustom: "لا توجد نماذج مخصصة",
discovered: "اكتشف",
custom: "نماذج مخصصة",
updated: "تم تحديث{{time}}",
},
installation: {
title: "التثبيت",
version: "الإصدار",
installed: "مثبّت",
notInstalled: "غير مثبّت",
install: "تثبيت",
checking: "جارٍ التحقق...",
failed: "تعذّر التحقق من التثبيت",
updates: "التحديثات",
upToDate: "محدّث",
updateAvailable: "يتوفر تحديث",
updateInstructions: "تعليمات التحديث",
update: "تحديث",
updating: "جارٍ التحديث...",
updated: "تم التحديث",
updateFailed: "فشل التحديث",
outputTruncated: "تم حذف المخرجات السابقة.",
updatesFailed: "تعذّر التحقق من التحديثات",
installInstructions: "تعليمات التثبيت",
},
diagnostic: {
title: "التشخيص",
button: "التشخيص",
+39 -2
View File
@@ -257,7 +257,7 @@ export const en = {
states: {
notFound: "Agent not found",
failedToLoad: "Failed to load agent",
reconnecting: "Reconnecting to host",
reconnecting: "Reconnecting",
updating: "Updating messages",
timelineSyncFailed: "Couldn't refresh agent history.",
timelineSyncRetrying: "Retrying…",
@@ -1728,7 +1728,7 @@ export const en = {
},
providers: {
label: "Providers",
title: "Your agents",
title: "Your providers",
description: "Paseo runs the agent CLIs already on this computer",
},
projects: {
@@ -3142,6 +3142,22 @@ export const en = {
providers: {
title: "Providers",
addProvider: "Add provider",
list: {
add: "Provider",
updatingTo: "Updating to {{version}}...",
},
detail: {
backToProviders: "Back to providers",
notOnHost: "This provider isn't on this host",
enabled: "Enabled",
unavailableTitle: "{{name}} isn't available",
troubleshooting: "Troubleshooting",
status: "Provider status",
checked: "Checked {{time}}",
diagnosticReport: "Diagnostic report",
dangerZone: "Danger zone",
removeHint: "Deletes this provider from config.json",
},
providerDetails: "{{name}} provider details",
enableProvider: "Enable {{name}}",
unavailable: "Connect to this host to see providers",
@@ -3183,10 +3199,31 @@ export const en = {
retrying: "Retrying...",
noSearchMatches: "No models match your search",
noneDetected: "No models detected",
noCustom: "No custom models",
discovered: "Discovered",
custom: "Custom models",
updated: "Updated {{time}}",
},
installation: {
title: "Installation",
version: "Version",
installed: "Installed",
notInstalled: "Not installed",
install: "Install",
checking: "Checking...",
failed: "Couldn't check this installation",
updates: "Updates",
upToDate: "Up to date",
updateAvailable: "Update available",
updateInstructions: "Update instructions",
update: "Update",
updating: "Updating...",
updated: "Updated",
updateFailed: "Update failed",
outputTruncated: "Earlier output was dropped.",
updatesFailed: "Couldn't check for updates",
installInstructions: "Install instructions",
},
diagnostic: {
title: "Diagnostic",
button: "Diagnostic",
+39 -2
View File
@@ -263,7 +263,7 @@ export const es: TranslationResources = {
states: {
notFound: "Agentno encontrado",
failedToLoad: "No se pudo cargar el agente",
reconnecting: "Reconectando al host",
reconnecting: "Reconectando",
updating: "Actualizando mensajes",
timelineSyncFailed: "No se pudo actualizar el historial del agente.",
timelineSyncRetrying: "Reintentando…",
@@ -1749,7 +1749,7 @@ export const es: TranslationResources = {
},
providers: {
label: "Proveedores",
title: "Tus agentes",
title: "Tus proveedores",
description: "Paseo usa las CLI de agentes que ya están en este ordenador",
},
projects: {
@@ -3076,6 +3076,22 @@ export const es: TranslationResources = {
providers: {
title: "Proveedores",
addProvider: "Agregar proveedor",
list: {
add: "Proveedor",
updatingTo: "Actualizando a {{version}}...",
},
detail: {
backToProviders: "Volver a proveedores",
notOnHost: "Este proveedor no está en este host",
enabled: "Activado",
unavailableTitle: "{{name}} no está disponible",
troubleshooting: "Solución de problemas",
status: "Estado del proveedor",
checked: "Comprobado {{time}}",
diagnosticReport: "Informe de diagnóstico",
dangerZone: "Zona de peligro",
removeHint: "Elimina este proveedor de config.json",
},
providerDetails: "Detalles del proveedor{{name}}",
enableProvider: "Habilitar{{name}}",
unavailable: "Conéctese a este host para ver proveedores",
@@ -3117,10 +3133,31 @@ export const es: TranslationResources = {
retrying: "Reintentando...",
noSearchMatches: "Ningún modelo coincide con tu búsqueda",
noneDetected: "No se detectaron modelos",
noCustom: "No hay modelos personalizados",
discovered: "descubierto",
custom: "Modelos personalizados",
updated: "{{time}}actualizado",
},
installation: {
title: "Instalación",
version: "Versión",
installed: "Instalado",
notInstalled: "No instalado",
install: "Instalar",
checking: "Comprobando...",
failed: "No se pudo comprobar la instalación",
updates: "Actualizaciones",
upToDate: "Actualizado",
updateAvailable: "Actualización disponible",
updateInstructions: "Instrucciones de actualización",
update: "Actualizar",
updating: "Actualizando...",
updated: "Actualizado",
updateFailed: "No se pudo actualizar",
outputTruncated: "Se descartó la salida anterior.",
updatesFailed: "No se pudo comprobar si hay actualizaciones",
installInstructions: "Instrucciones de instalación",
},
diagnostic: {
title: "Diagnóstico",
button: "Diagnóstico",
+39 -2
View File
@@ -264,7 +264,7 @@ export const fr: TranslationResources = {
states: {
notFound: "Agent introuvable",
failedToLoad: "Impossible de charger l’agent",
reconnecting: "Reconnexion à l’hôte…",
reconnecting: "Reconnexion…",
updating: "Mise à jour des messages…",
timelineSyncFailed: "Impossible d’actualiser l’historique de l’agent.",
timelineSyncRetrying: "Nouvelle tentative…",
@@ -1747,7 +1747,7 @@ export const fr: TranslationResources = {
},
providers: {
label: "Fournisseurs",
title: "Vos agents",
title: "Vos fournisseurs",
description: "Paseo utilise les CLI d'agents déjà installées sur cet ordinateur",
},
projects: {
@@ -3083,6 +3083,22 @@ export const fr: TranslationResources = {
providers: {
title: "Fournisseurs",
addProvider: "Ajouter un fournisseur",
list: {
add: "Fournisseur",
updatingTo: "Mise à jour vers {{version}}…",
},
detail: {
backToProviders: "Retour aux fournisseurs",
notOnHost: "Ce fournisseur n'est pas sur cet hôte",
enabled: "Activé",
unavailableTitle: "{{name}} n'est pas disponible",
troubleshooting: "Dépannage",
status: "État du fournisseur",
checked: "Vérifié {{time}}",
diagnosticReport: "Rapport de diagnostic",
dangerZone: "Zone de danger",
removeHint: "Supprime ce fournisseur de config.json",
},
providerDetails: "Détails du fournisseur {{name}}",
enableProvider: "Activer {{name}}",
unavailable: "Connectez-vous à cet hôte pour voir les fournisseurs",
@@ -3125,10 +3141,31 @@ export const fr: TranslationResources = {
retrying: "Nouvelle tentative…",
noSearchMatches: "Aucun modèle ne correspond à votre recherche",
noneDetected: "Aucun modèle détecté",
noCustom: "Aucun modèle personnalisé",
discovered: "Détectés",
custom: "Modèles personnalisés",
updated: "Mis à jour {{time}}",
},
installation: {
title: "Installation",
version: "Version",
installed: "Installé",
notInstalled: "Non installé",
install: "Installer",
checking: "Vérification...",
failed: "Impossible de vérifier l'installation",
updates: "Mises à jour",
upToDate: "À jour",
updateAvailable: "Mise à jour disponible",
updateInstructions: "Instructions de mise à jour",
update: "Mettre à jour",
updating: "Mise à jour...",
updated: "Mis à jour",
updateFailed: "Échec de la mise à jour",
outputTruncated: "La sortie précédente a été supprimée.",
updatesFailed: "Impossible de vérifier les mises à jour",
installInstructions: "Instructions d'installation",
},
diagnostic: {
title: "Diagnostic",
button: "Diagnostic",
+39 -2
View File
@@ -263,7 +263,7 @@ export const ja: TranslationResources = {
states: {
notFound: "エージェントが見つかりません",
failedToLoad: "エージェントの読み込みに失敗しました",
reconnecting: "ホストに再接続中",
reconnecting: "再接続中",
updating: "メッセージを更新中",
timelineSyncFailed: "エージェントの履歴を更新できませんでした。",
timelineSyncRetrying: "再試行しています…",
@@ -1720,7 +1720,7 @@ export const ja: TranslationResources = {
},
providers: {
label: "プロバイダー",
title: "エージェント",
title: "プロバイダー",
description: "Paseo はこのコンピューターにインストール済みのエージェント CLI を使います",
},
projects: {
@@ -3044,6 +3044,22 @@ export const ja: TranslationResources = {
providers: {
title: "プロバイダー",
addProvider: "プロバイダーを追加",
list: {
add: "プロバイダー",
updatingTo: "{{version}} に更新中...",
},
detail: {
backToProviders: "プロバイダーに戻る",
notOnHost: "このホストにはこのプロバイダーがありません",
enabled: "有効",
unavailableTitle: "{{name}} は利用できません",
troubleshooting: "トラブルシューティング",
status: "プロバイダーの状態",
checked: "{{time}}に確認",
diagnosticReport: "診断レポート",
dangerZone: "危険な操作",
removeHint: "このプロバイダーを config.json から削除します",
},
providerDetails: "{{name}}プロバイダーの詳細",
enableProvider: "{{name}}を有効にする",
unavailable: "プロバイダーを見るにはこのホストに接続してください",
@@ -3085,10 +3101,31 @@ export const ja: TranslationResources = {
retrying: "再試行中...",
noSearchMatches: "検索に一致するモデルがありません",
noneDetected: "モデルが検出されませんでした",
noCustom: "カスタムモデルはありません",
discovered: "検出済み",
custom: "カスタムモデル",
updated: "{{time}}に更新",
},
installation: {
title: "インストール",
version: "バージョン",
installed: "インストール済み",
notInstalled: "未インストール",
install: "インストール",
checking: "確認中...",
failed: "インストールを確認できませんでした",
updates: "アップデート",
upToDate: "最新です",
updateAvailable: "アップデートがあります",
updateInstructions: "アップデート手順",
update: "アップデート",
updating: "アップデート中...",
updated: "アップデート済み",
updateFailed: "アップデートに失敗しました",
outputTruncated: "以前の出力は破棄されました。",
updatesFailed: "アップデートを確認できませんでした",
installInstructions: "インストール手順",
},
diagnostic: {
title: "診断",
button: "診断",
+39 -2
View File
@@ -261,7 +261,7 @@ export const ko: TranslationResources = {
states: {
notFound: "에이전트를 찾을 수 없습니다",
failedToLoad: "에이전트를 불러오지 못했습니다",
reconnecting: "호스트에 다시 연결하는 중",
reconnecting: "다시 연결하는 중",
updating: "메시지 업데이트 중",
timelineSyncFailed: "에이전트 기록을 새로고침할 수 없습니다.",
timelineSyncRetrying: "재시도 중…",
@@ -1713,7 +1713,7 @@ export const ko: TranslationResources = {
},
providers: {
label: "제공자",
title: "에이전트",
title: "제공자",
description: "Paseo는 이 컴퓨터에 이미 설치된 에이전트 CLI를 사용합니다",
},
projects: {
@@ -3029,6 +3029,22 @@ export const ko: TranslationResources = {
providers: {
title: "프로바이더",
addProvider: "프로바이더 추가",
list: {
add: "프로바이더",
updatingTo: "{{version}}(으)로 업데이트 중...",
},
detail: {
backToProviders: "프로바이더로 돌아가기",
notOnHost: "이 호스트에 없는 프로바이더입니다",
enabled: "사용",
unavailableTitle: "{{name}}을(를) 사용할 수 없습니다",
troubleshooting: "문제 해결",
status: "프로바이더 상태",
checked: "{{time}} 확인됨",
diagnosticReport: "진단 보고서",
dangerZone: "위험 구역",
removeHint: "config.json에서 이 프로바이더를 삭제합니다",
},
providerDetails: "{{name}} 프로바이더 세부 정보",
enableProvider: "{{name}} 활성화",
unavailable: "프로바이더를 보려면 이 호스트에 연결하세요",
@@ -3071,10 +3087,31 @@ export const ko: TranslationResources = {
retrying: "다시 시도 중...",
noSearchMatches: "검색과 일치하는 모델이 없습니다",
noneDetected: "감지된 모델이 없습니다",
noCustom: "사용자 지정 모델 없음",
discovered: "발견됨",
custom: "사용자 지정 모델",
updated: "{{time}} 업데이트됨",
},
installation: {
title: "설치",
version: "버전",
installed: "설치됨",
notInstalled: "설치되지 않음",
install: "설치",
checking: "확인 중...",
failed: "설치를 확인할 수 없습니다",
updates: "업데이트",
upToDate: "최신 상태",
updateAvailable: "업데이트 가능",
updateInstructions: "업데이트 안내",
update: "업데이트",
updating: "업데이트 중...",
updated: "업데이트됨",
updateFailed: "업데이트 실패",
outputTruncated: "이전 출력이 삭제되었습니다.",
updatesFailed: "업데이트를 확인할 수 없습니다",
installInstructions: "설치 안내",
},
diagnostic: {
title: "진단",
button: "진단",
+39 -2
View File
@@ -262,7 +262,7 @@ export const ptBR: TranslationResources = {
states: {
notFound: "Agente não encontrado",
failedToLoad: "Falha ao carregar agente",
reconnecting: "Reconectando ao host",
reconnecting: "Reconectando",
updating: "Atualizando mensagens",
timelineSyncFailed: "Não foi possível atualizar o histórico do agente.",
timelineSyncRetrying: "Tentando novamente…",
@@ -1734,7 +1734,7 @@ export const ptBR: TranslationResources = {
},
providers: {
label: "Provedores",
title: "Seus agentes",
title: "Seus provedores",
description: "O Paseo usa as CLIs de agentes já instaladas neste computador",
},
projects: {
@@ -3057,6 +3057,22 @@ export const ptBR: TranslationResources = {
providers: {
title: "Provedores",
addProvider: "Adicionar provedor",
list: {
add: "Provedor",
updatingTo: "Atualizando para {{version}}...",
},
detail: {
backToProviders: "Voltar para provedores",
notOnHost: "Este provedor não está neste host",
enabled: "Ativado",
unavailableTitle: "{{name}} não está disponível",
troubleshooting: "Solução de problemas",
status: "Status do provedor",
checked: "Verificado {{time}}",
diagnosticReport: "Relatório de diagnóstico",
dangerZone: "Zona de perigo",
removeHint: "Exclui este provedor do config.json",
},
providerDetails: "Detalhes do provedor {{name}}",
enableProvider: "Ativar {{name}}",
unavailable: "Conecte-se a este host para ver provedores",
@@ -3098,10 +3114,31 @@ export const ptBR: TranslationResources = {
retrying: "Tentando novamente...",
noSearchMatches: "Nenhum modelo corresponde à sua busca",
noneDetected: "Nenhum modelo detectado",
noCustom: "Nenhum modelo personalizado",
discovered: "Descobertos",
custom: "Modelos personalizados",
updated: "Atualizado {{time}}",
},
installation: {
title: "Instalação",
version: "Versão",
installed: "Instalado",
notInstalled: "Não instalado",
install: "Instalar",
checking: "Verificando...",
failed: "Não foi possível verificar a instalação",
updates: "Atualizações",
upToDate: "Atualizado",
updateAvailable: "Atualização disponível",
updateInstructions: "Instruções de atualização",
update: "Atualizar",
updating: "Atualizando...",
updated: "Atualizado",
updateFailed: "Falha na atualização",
outputTruncated: "A saída anterior foi descartada.",
updatesFailed: "Não foi possível verificar atualizações",
installInstructions: "Instruções de instalação",
},
diagnostic: {
title: "Diagnóstico",
button: "Diagnóstico",
+39 -2
View File
@@ -263,7 +263,7 @@ export const ru: TranslationResources = {
states: {
notFound: "Агент не найден",
failedToLoad: "Не удалось загрузить агента",
reconnecting: "Повторное подключение к хосту",
reconnecting: "Повторное подключение",
updating: "Обновление сообщений",
timelineSyncFailed: "Не удалось обновить историю агента.",
timelineSyncRetrying: "Повторная попытка…",
@@ -1732,7 +1732,7 @@ export const ru: TranslationResources = {
},
providers: {
label: "Провайдеры",
title: "Ваши агенты",
title: "Ваши провайдеры",
description: "Paseo использует CLI агентов, уже установленные на этом компьютере",
},
projects: {
@@ -3067,6 +3067,22 @@ export const ru: TranslationResources = {
providers: {
title: "Провайдеры",
addProvider: "Добавить провайдера",
list: {
add: "Провайдер",
updatingTo: "Обновление до {{version}}...",
},
detail: {
backToProviders: "Назад к провайдерам",
notOnHost: "Этого провайдера нет на этом хосте",
enabled: "Включён",
unavailableTitle: "{{name}} недоступен",
troubleshooting: "Диагностика",
status: "Состояние провайдера",
checked: "Проверено {{time}}",
diagnosticReport: "Диагностический отчёт",
dangerZone: "Опасная зона",
removeHint: "Удаляет этого провайдера из config.json",
},
providerDetails: "Сведения о провайдере {{name}}",
enableProvider: "Включить {{name}}",
unavailable: "Подключитесь к этому хосту, чтобы увидеть провайдеров",
@@ -3109,10 +3125,31 @@ export const ru: TranslationResources = {
retrying: "Повторная попытка...",
noSearchMatches: "Ни одна модель не соответствует вашему запросу",
noneDetected: "Модели не обнаружены",
noCustom: "Нет пользовательских моделей",
discovered: "Обнаруженные модели",
custom: "Пользовательские модели",
updated: "Обновлено {{time}}",
},
installation: {
title: "Установка",
version: "Версия",
installed: "Установлено",
notInstalled: "Не установлено",
install: "Установить",
checking: "Проверка...",
failed: "Не удалось проверить установку",
updates: "Обновления",
upToDate: "Актуальная версия",
updateAvailable: "Доступно обновление",
updateInstructions: "Инструкции по обновлению",
update: "Обновить",
updating: "Обновление...",
updated: "Обновлено",
updateFailed: "Не удалось обновить",
outputTruncated: "Более ранний вывод был отброшен.",
updatesFailed: "Не удалось проверить обновления",
installInstructions: "Инструкции по установке",
},
diagnostic: {
title: "Диагностика",
button: "Диагностика",
+39 -2
View File
@@ -261,7 +261,7 @@ export const zhCN: TranslationResources = {
states: {
notFound: "未找到 Agent",
failedToLoad: "加载 Agent 失败",
reconnecting: "正在重新连接主机",
reconnecting: "正在重新连接",
updating: "正在更新消息",
timelineSyncFailed: "无法刷新代理历史记录。",
timelineSyncRetrying: "正在重试…",
@@ -1685,7 +1685,7 @@ export const zhCN: TranslationResources = {
},
providers: {
label: "提供方",
title: "你的代理",
title: "你的提供方",
description: "Paseo 使用这台电脑上已安装的代理 CLI",
},
projects: {
@@ -2976,6 +2976,22 @@ export const zhCN: TranslationResources = {
providers: {
title: "Providers",
addProvider: "添加 Provider",
list: {
add: "Provider",
updatingTo: "正在更新到 {{version}}...",
},
detail: {
backToProviders: "返回 Provider 列表",
notOnHost: "此 Host 上没有这个 Provider",
enabled: "已启用",
unavailableTitle: "{{name}} 不可用",
troubleshooting: "故障排查",
status: "Provider 状态",
checked: "{{time}}检查",
diagnosticReport: "诊断报告",
dangerZone: "危险操作",
removeHint: "从 config.json 中删除此 Provider",
},
providerDetails: "{{name}} Provider 详情",
enableProvider: "启用 {{name}}",
unavailable: "连接到这个 Host 以查看 Providers",
@@ -3017,10 +3033,31 @@ export const zhCN: TranslationResources = {
retrying: "正在重试...",
noSearchMatches: "没有匹配搜索的 Model",
noneDetected: "未检测到 Model",
noCustom: "没有自定义模型",
discovered: "已发现",
custom: "自定义 Models",
updated: "已更新 {{time}}",
},
installation: {
title: "安装",
version: "版本",
installed: "已安装",
notInstalled: "未安装",
install: "安装",
checking: "正在检查...",
failed: "无法检查安装状态",
updates: "更新",
upToDate: "已是最新",
updateAvailable: "有可用更新",
updateInstructions: "更新说明",
update: "更新",
updating: "正在更新...",
updated: "已更新",
updateFailed: "更新失败",
outputTruncated: "较早的输出已被丢弃。",
updatesFailed: "无法检查更新",
installInstructions: "安装说明",
},
diagnostic: {
title: "诊断",
button: "诊断",
@@ -305,3 +305,22 @@ describe("mobile panel ownership", () => {
});
});
});
it("lands an explicit destination while the sidebar is suspended without a slide", () => {
const state = createMobilePanelMotionState({ target: "agent-list", revision: 1 });
const result = transitionMobilePanel(state, {
type: "command",
selection: { target: "agent", revision: 2 },
immediate: true,
});
expect(result).toEqual({
immediateTarget: "agent",
state: {
target: "agent",
revision: 2,
gesture: null,
motionTarget: "agent",
settledTarget: "agent",
},
});
});
+13 -1
View File
@@ -17,6 +17,7 @@ export interface MobilePanelCommit {
export interface MobilePanelTransition {
animationTarget?: MobilePanelView;
immediateTarget?: MobilePanelView;
commit?: MobilePanelCommit;
state: MobilePanelMotionState;
}
@@ -48,7 +49,7 @@ function settleMobilePanelAtPosition(
}
export type MobilePanelEvent =
| { type: "command"; selection: MobilePanelSelection }
| { type: "command"; selection: MobilePanelSelection; immediate?: boolean }
| { type: "gesture.begin"; origin: MobilePanelView }
| {
type: "gesture.finish";
@@ -78,6 +79,17 @@ export function transitionMobilePanel(
if (event.selection.revision <= state.revision) {
return { state };
}
if (event.immediate) {
return {
immediateTarget: event.selection.target,
state: {
...event.selection,
gesture: null,
motionTarget: event.selection.target,
settledTarget: event.selection.target,
},
};
}
// An interrupted drag left the position between anchors, so it moves back even when the
// target is unchanged. Without a drag, the command adopts motion already heading there.
const continuesCurrentMotion = !state.gesture && state.motionTarget === event.selection.target;

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