mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-26 02:05:31 +00:00
Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6c237aabf1 | ||
|
|
22baf9e344 | ||
|
|
68d58c8217 | ||
|
|
e51bb7b8cd | ||
|
|
050e168974 | ||
|
|
e114e13de2 | ||
|
|
3777cc754b | ||
|
|
7708e1f084 | ||
|
|
ba45634eee | ||
|
|
5c82a2e999 | ||
|
|
60943dde1c | ||
|
|
e52bb6e3c4 | ||
|
|
307f65d8f7 | ||
|
|
163162e9f3 | ||
|
|
4a6b8ae080 | ||
|
|
465db78ab6 | ||
|
|
30a155127d |
@@ -56,6 +56,7 @@ sdk:
|
|||||||
- "packages/plugin/**"
|
- "packages/plugin/**"
|
||||||
- "plugin-examples/**"
|
- "plugin-examples/**"
|
||||||
- "public-docs/plugins/**"
|
- "public-docs/plugins/**"
|
||||||
|
- "skills/paseo-plugin/**"
|
||||||
- "packages/client/**"
|
- "packages/client/**"
|
||||||
- "packages/highlight/**"
|
- "packages/highlight/**"
|
||||||
- "packages/protocol/**"
|
- "packages/protocol/**"
|
||||||
|
|||||||
@@ -131,6 +131,29 @@ jobs:
|
|||||||
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
|
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
|
||||||
run: npm run typecheck:examples --workspace=@getpaseo/client
|
run: npm run typecheck:examples --workspace=@getpaseo/client
|
||||||
|
|
||||||
|
# Plugin process launches and launch wraps quote for cmd.exe, which only real Windows checks.
|
||||||
|
sdk-tests-windows:
|
||||||
|
name: sdk-tests (windows-latest)
|
||||||
|
needs: changes
|
||||||
|
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
|
||||||
|
runs-on: windows-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: "22"
|
||||||
|
cache: "npm"
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: node scripts/npm-retry.mjs ci
|
||||||
|
|
||||||
|
- name: Build plugin SDK
|
||||||
|
run: npm run build:relay && npm run build:client && npm run build:plugin
|
||||||
|
|
||||||
|
- name: Run plugin SDK tests
|
||||||
|
run: npm run test --workspace=@getpaseo/plugin
|
||||||
|
|
||||||
# The locked Playwright installers do not support ubuntu-latest's Ubuntu 26.04.
|
# The locked Playwright installers do not support ubuntu-latest's Ubuntu 26.04.
|
||||||
typecheck:
|
typecheck:
|
||||||
name: typecheck
|
name: typecheck
|
||||||
|
|||||||
@@ -36,6 +36,7 @@ At the start of non-trivial work, list `docs/` and skim anything relevant to the
|
|||||||
| [docs/floating-panels.md](docs/floating-panels.md) | Anchored popovers — Portal/Modal escape for Android, lifecycle gates, keyboard-shared-value, status-bar offset, the flash |
|
| [docs/floating-panels.md](docs/floating-panels.md) | Anchored popovers — Portal/Modal escape for Android, lifecycle gates, keyboard-shared-value, status-bar offset, the flash |
|
||||||
| [docs/keyboard-shortcuts.md](docs/keyboard-shortcuts.md) | The binding table, per-platform key sources, badges vs routing, iOS `UIKeyCommand` limits |
|
| [docs/keyboard-shortcuts.md](docs/keyboard-shortcuts.md) | The binding table, per-platform key sources, badges vs routing, iOS `UIKeyCommand` limits |
|
||||||
| [docs/menus.md](docs/menus.md) | The menu engine — popover vs sheet, submenu pages, hover intent, when a decision earns a submenu |
|
| [docs/menus.md](docs/menus.md) | The menu engine — popover vs sheet, submenu pages, hover intent, when a decision earns a submenu |
|
||||||
|
| [docs/drag-reorder.md](docs/drag-reorder.md) | Drag to reorder — `DraggableList` and its handle, the scroll view that must host the drag, grip placement, testing on a phone |
|
||||||
| [docs/expo-router.md](docs/expo-router.md) | Expo Router route ownership, startup restore, and native blank-screen gotchas |
|
| [docs/expo-router.md](docs/expo-router.md) | Expo Router route ownership, startup restore, and native blank-screen gotchas |
|
||||||
| [docs/notifications.md](docs/notifications.md) | Notification tap ownership, native replay and acknowledgement, startup handoff, and payload QA |
|
| [docs/notifications.md](docs/notifications.md) | Notification tap ownership, native replay and acknowledgement, startup handoff, and payload QA |
|
||||||
| [docs/file-icons.md](docs/file-icons.md) | Material icon theme integration for the file explorer |
|
| [docs/file-icons.md](docs/file-icons.md) | Material icon theme integration for the file explorer |
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
# Drag to reorder
|
||||||
|
|
||||||
|
A list the user can reorder renders through `DraggableList` from `@/components/draggable-list`. Each row puts a `DraggableListHandle` where its grip is drawn. The Usage cards (`packages/app/src/usage/list.tsx`, `packages/app/src/usage/card.tsx`) and the agent profile roster (`packages/app/src/agent-profiles/settings/`) are the reference.
|
||||||
|
|
||||||
|
| Platform | How a drag starts |
|
||||||
|
| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||||
|
| Web | dnd-kit pointer drag. With `useDragHandle`, only the handle starts it, and the handle reorders by keyboard. Without it, the whole row starts it. |
|
||||||
|
| Native | Hold the handle for 180 ms without moving more than 4 px. The list then owns the touch until the finger lifts. |
|
||||||
|
|
||||||
|
## The scroll view must host the drag
|
||||||
|
|
||||||
|
On native, the hold calls `drag()`, which calls `useContentDrag().setActive(true)` from `@/components/ui/content-drag` on the nearest scroll view. That scroll view stops scrolling until the drag ends. If no scroll view up the tree hosts content drags, `setActive` does nothing. The page scroll then takes the touch as soon as the finger moves past the touch slop, before the list's own pan activates. The row never moves, and the page scrolls instead.
|
||||||
|
|
||||||
|
These scroll views host content drags:
|
||||||
|
|
||||||
|
- `ScrollView` from `@/components/ui/scroll-view`, inside and outside a sheet.
|
||||||
|
- `PageLayout`, for a settings page or any other full page.
|
||||||
|
|
||||||
|
If you put a reorderable list in another scroll view, such as a third-party keyboard-aware one, wrap it with `withContentDrag` from `@/components/ui/content-drag`. `packages/app/src/components/page-layout/index.tsx` shows the pattern. A plain `ScrollView` from `react-native` breaks the drag.
|
||||||
|
|
||||||
|
Inside a sheet, the `ScrollView` also registers the drag gesture with the sheet, so the sheet's pan-to-close waits for it.
|
||||||
|
|
||||||
|
## Where the grip goes
|
||||||
|
|
||||||
|
The grip hangs in the row's leading padding, absolutely positioned over the full row height. The row's content keeps the same left rail as rows that cannot be reordered, and the grip does not take a column. On a pointer device the grip shows on hover, focus, or while dragging. On touch and compact layouts it always shows, because there is no hover.
|
||||||
|
|
||||||
|
## Test with a page that scrolls
|
||||||
|
|
||||||
|
A list that fits on the screen does not show the bug, because the page has nothing to scroll. Test on a phone with enough rows that the page scrolls. Then check both directions:
|
||||||
|
|
||||||
|
1. Hold the grip and drag a row past two others. The new order is saved.
|
||||||
|
2. Swipe quickly on a row body. The page scrolls and the order stays the same.
|
||||||
|
|
||||||
|
On an Android emulator, `adb shell input swipe` does not hold still long enough to arm the drag. Send `input motionevent DOWN`, wait 500 ms, then send `MOVE` events and `UP`.
|
||||||
@@ -465,7 +465,7 @@ in a tab. An overlay opened from that content and calling `useSafeAreaInsets()`
|
|||||||
gets that 0 and draws over the navigation bar.
|
gets that 0 and draws over the navigation bar.
|
||||||
|
|
||||||
- A Gorhom sheet reads the inset inside its children, which render in the app's sheet host. See
|
- A Gorhom sheet reads the inset inside its children, which render in the app's sheet host. See
|
||||||
`CompactSheetBody`, `MenuSheetScrollView` and `ComboboxSheetFrame`.
|
`SheetVisibleFrame` (used by `CompactSheetBody` and `ComboboxSheetFrame`) and `MenuSheetScrollView`.
|
||||||
- An RN `Modal` passes the call site's context straight through, so wrap its content in
|
- An RN `Modal` passes the call site's context straight through, so wrap its content in
|
||||||
`WindowSafeArea` from `@/window-layout` and read the inset below that. It provides the insets of
|
`WindowSafeArea` from `@/window-layout` and read the inset below that. It provides the insets of
|
||||||
the whole window, published by `WindowLayoutProvider`. Do not put a `SafeAreaProvider` inside the
|
the whole window, published by `WindowLayoutProvider`. Do not put a `SafeAreaProvider` inside the
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ Authoritative terminology. UI label wins. Don't invent synonyms; use what's here
|
|||||||
- **Agent** — See **Agent session**. UI still says "Agent" / "New Agent" in places, but moving toward **Agent session** as the canonical term. Code: `AgentSnapshotPayload` (`packages/protocol/src/messages.ts:608`). Forbidden: "Task", "Job", "Run".
|
- **Agent** — See **Agent session**. UI still says "Agent" / "New Agent" in places, but moving toward **Agent session** as the canonical term. Code: `AgentSnapshotPayload` (`packages/protocol/src/messages.ts:608`). Forbidden: "Task", "Job", "Run".
|
||||||
- **Daemon** — Local Paseo server process; identified by `serverId`. UI: "Daemon" (system contexts only). Code: `serverId` in `ServerInfoStatusPayloadSchema` (`packages/protocol/src/messages.ts:1936`), `DaemonClient` (`packages/client/src/daemon-client.ts`).
|
- **Daemon** — Local Paseo server process; identified by `serverId`. UI: "Daemon" (system contexts only). Code: `serverId` in `ServerInfoStatusPayloadSchema` (`packages/protocol/src/messages.ts:1936`), `DaemonClient` (`packages/client/src/daemon-client.ts`).
|
||||||
- **Host** — Client-side connection profile pointing at a daemon; bundles one or more `HostConnection`s. UI: "Host" / "Add host" / "Switch host". Code: `HostProfile` (`packages/app/src/types/host-connection.ts:37`). Forbidden: "Connection" (means `HostConnection`, not host).
|
- **Host** — Client-side connection profile pointing at a daemon; bundles one or more `HostConnection`s. UI: "Host" / "Add host" / "Switch host". Code: `HostProfile` (`packages/app/src/types/host-connection.ts:37`). Forbidden: "Connection" (means `HostConnection`, not host).
|
||||||
|
- **Device** — A computer or phone running a Paseo client. Open **Devices** in a host’s settings to connect another device.
|
||||||
- **Host badge** — The item on a sidebar workspace row's meta row naming which host that workspace lives on. Three things gate it, and they compose as a lattice rather than competing: the sidebar must span more than one host (automatic), **Show → Host** in the sidebar's display preferences must be on (global, all hosts at once), and then that host's own display mode decides _how_ it draws — **Name** / **Icon only** / **Hidden**. Name, color, and display mode are per-host, per-device, and live client-side on `HostProfile.appearance`; nothing about it reaches the daemon. Never add a fourth way to hide it. UI: the "Appearance" group on a host's settings page, and the "Show" submenu in the sidebar's display preferences. Code: `selectHostBadges` (`packages/app/src/hosts/appearance.ts`) takes the first two as its `enabled` input; `WorkspaceMetaRow` (`packages/app/src/components/sidebar/workspace-meta-row/index.tsx`) draws it. Don't confuse with **Status pill**, which reports state rather than identity.
|
- **Host badge** — The item on a sidebar workspace row's meta row naming which host that workspace lives on. Three things gate it, and they compose as a lattice rather than competing: the sidebar must span more than one host (automatic), **Show → Host** in the sidebar's display preferences must be on (global, all hosts at once), and then that host's own display mode decides _how_ it draws — **Name** / **Icon only** / **Hidden**. Name, color, and display mode are per-host, per-device, and live client-side on `HostProfile.appearance`; nothing about it reaches the daemon. Never add a fourth way to hide it. UI: the "Appearance" group on a host's settings page, and the "Show" submenu in the sidebar's display preferences. Code: `selectHostBadges` (`packages/app/src/hosts/appearance.ts`) takes the first two as its `enabled` input; `WorkspaceMetaRow` (`packages/app/src/components/sidebar/workspace-meta-row/index.tsx`) draws it. Don't confuse with **Status pill**, which reports state rather than identity.
|
||||||
- **Project host entry** — One row in a project for a single (project, daemon) pair, aggregating that daemon's workspaces in the project. Internal. Code: `ProjectHostEntry` (`packages/app/src/utils/projects.ts:11`). Don't introduce "Checkout" as a synonym.
|
- **Project host entry** — One row in a project for a single (project, daemon) pair, aggregating that daemon's workspaces in the project. Internal. Code: `ProjectHostEntry` (`packages/app/src/utils/projects.ts:11`). Don't introduce "Checkout" as a synonym.
|
||||||
- **Placement** — One workspace's stable foreign-key relationship to its project plus its git checkout snapshot. Internal. An explicit creation `projectId` is authoritative when active.
|
- **Placement** — One workspace's stable foreign-key relationship to its project plus its git checkout snapshot. Internal. An explicit creation `projectId` is authoritative when active.
|
||||||
|
|||||||
@@ -32,10 +32,11 @@ CI does not build native code or run the fork's Robolectric suites. Run `npm run
|
|||||||
|
|
||||||
Some fork changes are backports. A sync past the upstream version drops them in favour of upstream's code:
|
Some fork changes are backports. A sync past the upstream version drops them in favour of upstream's code:
|
||||||
|
|
||||||
| Fork change | Upstream | Released in |
|
| Fork change | Upstream | Released in |
|
||||||
| ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------- |
|
| ------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------- |
|
||||||
| Android measurements survive parent clones | [#924](https://github.com/software-mansion/enriched-markdown/pull/924) | after `1.2.0-nightly-20261019-926ef06f0` |
|
| Android measurements survive parent clones | [#924](https://github.com/software-mansion/enriched-markdown/pull/924) | after `1.2.0-nightly-20261019-926ef06f0` |
|
||||||
| Android nested list items start their text after their own marker | [#1015](https://github.com/software-mansion/enriched-markdown/pull/1015), [#1023](https://github.com/software-mansion/enriched-markdown/pull/1023) (Android) | `1.2.0` |
|
| Android long-press drag selection keeps parent intercept disallowed | [#1012](https://github.com/software-mansion/enriched-markdown/pull/1012) | `1.2.0` |
|
||||||
|
| Android nested list items start their text after their own marker | [#1015](https://github.com/software-mansion/enriched-markdown/pull/1015), [#1023](https://github.com/software-mansion/enriched-markdown/pull/1023) (Android) | `1.2.0` |
|
||||||
|
|
||||||
## Engine constraints
|
## Engine constraints
|
||||||
|
|
||||||
|
|||||||
+64
-2
@@ -462,8 +462,55 @@ Server entries register async handlers with `server.addHook(name, handler)`, ret
|
|||||||
function. Names follow `subject.operation.position`, ending in `before` or `after`. Waiting is a per-hook
|
function. Names follow `subject.operation.position`, ending in `before` or `after`. Waiting is a per-hook
|
||||||
registry property, independent of position. The [hooks reference](../public-docs/plugins/hooks.md)
|
registry property, independent of position. The [hooks reference](../public-docs/plugins/hooks.md)
|
||||||
owns payloads, ordering, failure behavior, and examples. `agent.create.before` edits saved
|
owns payloads, ordering, failure behavior, and examples. `agent.create.before` edits saved
|
||||||
configuration; `agent.open.before` contributes launch-only `env`, `tools`, and `mcpServers` on
|
configuration; `agent.open.before` contributes launch-only `env`, `tools`, `mcpServers`, and a
|
||||||
every open. Executable tool definitions stay in the plugin process; only metadata crosses the boundary.
|
[launch wrap](#launch-wrap) on every open. Executable tool definitions stay in the plugin process; only metadata crosses the boundary.
|
||||||
|
`packages/server/src/server/plugins/session-attachments.ts` records what each plugin contributed to
|
||||||
|
each live session. A plugin start, stop, or reload reruns only that plugin's callback per session,
|
||||||
|
swaps its tools in place, and reopens a session only when its launch would differ. A reopen closes
|
||||||
|
the provider process, so a reload must not reopen agents the plugin does not change.
|
||||||
|
|
||||||
|
### Launch wrap
|
||||||
|
|
||||||
|
An `agent.open.before` result can carry `wrap: [executable, ...args]`. The provider then starts that
|
||||||
|
session's harness as `[...wrap, command, ...args]` with the final hook env. It starts with no shell,
|
||||||
|
except Windows script launchers, which go through cmd.exe like any provider launcher
|
||||||
|
(`spawnProcess` quotes each argument). An argument with spaces stays one element. `executable` must
|
||||||
|
be an absolute path.
|
||||||
|
The wrap is never saved on the agent; every open asks the hooks again, and a plugin session reopen
|
||||||
|
reuses the wrap it opened with.
|
||||||
|
|
||||||
|
- **Support is a provider property.** The provider snapshot entry carries `launchWrap: true` when the
|
||||||
|
provider can apply a wrap. Read it in `agent.create.before` with `paseo.providers.snapshot()`; an
|
||||||
|
absent field means unsupported, which is also what a host without this feature reports. Core
|
||||||
|
providers declare it in the provider contract table in `provider-registry.ts`; every core provider
|
||||||
|
that starts a local harness declares it, and custom ACP providers and providers that extend a core
|
||||||
|
one inherit it. A plugin provider declares `ProviderRegistration.launchWrap`;
|
||||||
|
`runAcpProvider({ command })` sets it, a connector declares it itself (Muse Code does). The declaration travels with the
|
||||||
|
registration metadata, so it is in the snapshot before the provider first connects.
|
||||||
|
- **One wrap per open.** A later hook, in the same plugin or a later one, may omit the wrap or return
|
||||||
|
the same value. A different value fails the open.
|
||||||
|
- **Fail closed.** `buildLaunchContext` admits a wrapped open before any session harness starts. It
|
||||||
|
throws `LaunchWrapUnsupportedError` (`code: "launch_wrap_unsupported"`) when the provider does not
|
||||||
|
declare support, or when a plugin provider's live connection lacks `session.launch_wrap`. A host
|
||||||
|
that predates `wrap` rejects the key: the hook result schema is strict. A missing launcher fails the
|
||||||
|
spawn; nothing retries the bare command.
|
||||||
|
|
||||||
|
Once an open selects a wrap, a supported provider runs that session's harness through it or fails
|
||||||
|
before starting the harness. Every provider starts through `spawnProcess({ wrap })`, which owns the
|
||||||
|
argv and Windows launcher handling; `applyLaunchWrap` covers the launches that do not go through it
|
||||||
|
(pty terminals, MCP stdio transports, worktree commands). The wrap also covers what Paseo starts for
|
||||||
|
the session: stdio MCP servers Paseo hosts for the agent (OMP, OpenCode v2), Pi's MCP probe, and ACP
|
||||||
|
client terminals. OpenCode shares one server between sessions, so a wrapped session gets a dedicated
|
||||||
|
server instead; an explicitly configured external OpenCode server cannot be wrapped and the open
|
||||||
|
fails. The guarantee does not cover:
|
||||||
|
|
||||||
|
1. Paseo's host terminal tools (`create_terminal`, `send_terminal_keys`) run outside the wrap.
|
||||||
|
2. Work before the open hook runs unwrapped: draft command and control discovery, and the catalog
|
||||||
|
lookup during create when no model is set.
|
||||||
|
3. Host-side operations run unwrapped: availability and capability probes (the ACP connection's
|
||||||
|
initialize probe included), catalog and session listing, version and update commands, usage
|
||||||
|
queries, and Codex native archive and unarchive.
|
||||||
|
4. Losing the plugin that chose the wrap is not covered: a later open without it runs unwrapped.
|
||||||
|
|
||||||
Worktree placement is resolved before Git source planning, so a hook can change the branch and base
|
Worktree placement is resolved before Git source planning, so a hook can change the branch and base
|
||||||
without undoing fetched refs. Restores use the recorded destination and bypass creation hooks.
|
without undoing fetched refs. Restores use the recorded destination and bypass creation hooks.
|
||||||
@@ -483,6 +530,17 @@ change requests; `remove` and `restore` fall back to built-in Git when the plugi
|
|||||||
[worktree managers reference](../public-docs/plugins/reference.md#worktree-managers) and
|
[worktree managers reference](../public-docs/plugins/reference.md#worktree-managers) and
|
||||||
`plugin-examples/worktrunk`.
|
`plugin-examples/worktrunk`.
|
||||||
|
|
||||||
|
`terminal.create.before` runs in `withTerminalCreateHook`, which wraps the daemon's one terminal manager, so every creation path is covered and adopted terminals are not; callers pass an `origin` to name the source. `command.run.before` runs inside the setup and teardown runners through `commandRunHook`. Setup and archive dependencies take `lifecycle` as a required field so a new caller cannot skip the hook by omission; pass `null` only where no plugins run.
|
||||||
|
|
||||||
|
Both hooks change only `env` and a [launch wrap](#launch-wrap); `keepSelectedWrap` in the lifecycle
|
||||||
|
module applies the one-wrap rule to all three wrap hooks. The terminal wrap becomes the terminal's
|
||||||
|
`command` and `args` in `withTerminalCreateHook`, so the terminal worker protocol does not change and
|
||||||
|
no previous-version adapter is needed. A default-shell terminal resolves the shell there through
|
||||||
|
`default-terminal-shell.ts`, which stays apart from `terminal.ts` so the daemon does not load node-pty.
|
||||||
|
The wrapped shell starts without Paseo's shell integration, which is why a wrapped script does not
|
||||||
|
report command completion. A setup or teardown wrap goes in front of the
|
||||||
|
`buildStringCommandShellInvocation` argv.
|
||||||
|
|
||||||
Emit from the operation owner, not a client subscription. Provider history replay must not trigger
|
Emit from the operation owner, not a client subscription. Provider history replay must not trigger
|
||||||
live hooks. Notifications must not be awaited inside agent mutations: a handler can send a prompt
|
live hooks. Notifications must not be awaited inside agent mutations: a handler can send a prompt
|
||||||
or answer a permission through its own daemon session. Awaiting it there deadlocks that command.
|
or answer a permission through its own daemon session. Awaiting it there deadlocks that command.
|
||||||
@@ -582,6 +640,10 @@ persistence. Re-read credentials and provider-owned configuration on `session.op
|
|||||||
daemon launch from `connect` and the per-session env and MCP servers from `session.open`. There is
|
daemon launch from `connect` and the per-session env and MCP servers from `session.open`. There is
|
||||||
no provider reload input.
|
no provider reload input.
|
||||||
|
|
||||||
|
Declare `ProviderRegistration.launchWrap: true` when every session spawns its own harness and can
|
||||||
|
run it as `[...config.wrap, command, ...args]`; offer `session.launch_wrap` on the connection. See
|
||||||
|
[Launch wrap](#launch-wrap). `runAcpProvider({ command })` does both.
|
||||||
|
|
||||||
For an ACP command, register `runAcpProvider({ id, label, command })` from
|
For an ACP command, register `runAcpProvider({ id, label, command })` from
|
||||||
`@getpaseo/plugin/server/acp`. The shim builds the standard row for each ACP tool `kind`
|
`@getpaseo/plugin/server/acp`. The shim builds the standard row for each ACP tool `kind`
|
||||||
(`acp-internal/tool-call-detail.ts`). Its transformer hooks cover narrow vendor differences; do not translate the
|
(`acp-internal/tool-call-detail.ts`). Its transformer hooks cover narrow vendor differences; do not translate the
|
||||||
|
|||||||
Generated
+1
@@ -40625,6 +40625,7 @@
|
|||||||
"p-limit": "^7.3.0",
|
"p-limit": "^7.3.0",
|
||||||
"p-memoize": "^8.0.0",
|
"p-memoize": "^8.0.0",
|
||||||
"p-throttle": "^8.1.0",
|
"p-throttle": "^8.1.0",
|
||||||
|
"parse5": "^7.3.0",
|
||||||
"pino": "^10.2.0",
|
"pino": "^10.2.0",
|
||||||
"pino-pretty": "^13.1.3",
|
"pino-pretty": "^13.1.3",
|
||||||
"qrcode": "^1.5.4",
|
"qrcode": "^1.5.4",
|
||||||
|
|||||||
@@ -2,8 +2,10 @@ import { expect, test } from "../support/fixtures";
|
|||||||
import {
|
import {
|
||||||
applyProfileFromPicker,
|
applyProfileFromPicker,
|
||||||
closeModelPicker,
|
closeModelPicker,
|
||||||
|
expectAgentProfileNameDraft,
|
||||||
expectComposerDoesNotName,
|
expectComposerDoesNotName,
|
||||||
expectAgentProfilesEmptyPrompt,
|
expectAgentProfilesEmptyPrompt,
|
||||||
|
expectHostAgentProfiles,
|
||||||
expectProfileEditTooltip,
|
expectProfileEditTooltip,
|
||||||
expectComposerMode,
|
expectComposerMode,
|
||||||
expectCreateProfileFromModelRow,
|
expectCreateProfileFromModelRow,
|
||||||
@@ -14,8 +16,11 @@ import {
|
|||||||
expectProfileReachableByScrolling,
|
expectProfileReachableByScrolling,
|
||||||
expectProfileSearchResult,
|
expectProfileSearchResult,
|
||||||
expectProfileVisibleForProvider,
|
expectProfileVisibleForProvider,
|
||||||
|
fillAgentProfileName,
|
||||||
|
openEditProfileFromModelRow,
|
||||||
openModelPicker,
|
openModelPicker,
|
||||||
openAgentProfilesFromEmptyPrompt,
|
openAgentProfilesFromEmptyPrompt,
|
||||||
|
removeOpenModalAgentProfileWithConfirm,
|
||||||
searchModelPicker,
|
searchModelPicker,
|
||||||
seedAgentProfiles,
|
seedAgentProfiles,
|
||||||
selectModelRow,
|
selectModelRow,
|
||||||
@@ -146,10 +151,10 @@ test.describe("Agent profiles in the model picker", () => {
|
|||||||
await openModelPicker(page);
|
await openModelPicker(page);
|
||||||
await expectModelRowProfileActionBesideRow(page, oneMinute);
|
await expectModelRowProfileActionBesideRow(page, oneMinute);
|
||||||
await expectCreateProfileFromModelRow(page, oneMinute);
|
await expectCreateProfileFromModelRow(page, oneMinute);
|
||||||
await expectComposerModel(page, "Ten second stream");
|
|
||||||
await openModelPicker(page);
|
|
||||||
await selectModelRow(page, oneMinute);
|
|
||||||
await expectComposerModel(page, oneMinute.modelLabel);
|
await expectComposerModel(page, oneMinute.modelLabel);
|
||||||
|
await openModelPicker(page);
|
||||||
|
await selectModelRow(page, { provider: "mock", modelId: "ten-second-stream" });
|
||||||
|
await expectComposerModel(page, "Ten second stream");
|
||||||
} finally {
|
} finally {
|
||||||
await workspace.cleanup();
|
await workspace.cleanup();
|
||||||
await seed.restore();
|
await seed.restore();
|
||||||
@@ -234,4 +239,44 @@ test.describe("Agent profiles in the model picker", () => {
|
|||||||
await seed.restore();
|
await seed.restore();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("canceling Remove in the composer profile editor keeps the editor and draft open", async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
const seed = await seedAgentProfiles([PROFILE]);
|
||||||
|
const workspace = await seedMockAgentWorkspace({
|
||||||
|
repoPrefix: "agent-profiles-remove-cancel-",
|
||||||
|
title: "Agent profiles remove cancel",
|
||||||
|
model: "ten-second-stream",
|
||||||
|
modeId: "load-test",
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
await openAgentRoute(page, workspace);
|
||||||
|
await expectComposerVisible(page);
|
||||||
|
await openModelPicker(page);
|
||||||
|
await openEditProfileFromModelRow(page, {
|
||||||
|
provider: "mock",
|
||||||
|
modelId: "one-minute-stream",
|
||||||
|
});
|
||||||
|
await fillAgentProfileName(page, "Draft name");
|
||||||
|
|
||||||
|
await test.step("canceling Remove keeps the modal and draft intact", async () => {
|
||||||
|
await removeOpenModalAgentProfileWithConfirm(page, "dismiss");
|
||||||
|
await expect(page.getByTestId("agent-profile-edit-modal")).toBeVisible();
|
||||||
|
await expectAgentProfileNameDraft(page, "Draft name");
|
||||||
|
});
|
||||||
|
|
||||||
|
await test.step("confirming Remove deletes the profile and closes the modal", async () => {
|
||||||
|
await removeOpenModalAgentProfileWithConfirm(page, "accept");
|
||||||
|
await expect(page.getByTestId("agent-profile-edit-modal")).toHaveCount(0, {
|
||||||
|
timeout: 30_000,
|
||||||
|
});
|
||||||
|
await expectHostAgentProfiles([]);
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
await workspace.cleanup();
|
||||||
|
await seed.restore();
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,19 +1,32 @@
|
|||||||
import { test } from "../support/fixtures";
|
import { expect, test } from "../support/fixtures";
|
||||||
import {
|
import {
|
||||||
|
browserBackWithConfirm,
|
||||||
|
browserHistoryJumpWithConfirm,
|
||||||
createAgentProfile,
|
createAgentProfile,
|
||||||
createAgentProfileFromEmptyState,
|
createAgentProfileFromEmptyState,
|
||||||
|
duplicateOpenAgentProfileWithConfirm,
|
||||||
editAgentProfile,
|
editAgentProfile,
|
||||||
expectAgentProfile,
|
expectAgentProfile,
|
||||||
expectAgentProfileForm,
|
expectAgentProfileForm,
|
||||||
|
expectAgentProfileNameDraft,
|
||||||
|
expectAgentProfileNotesDraft,
|
||||||
expectAgentProfileOrder,
|
expectAgentProfileOrder,
|
||||||
expectAgentProfileTagsGone,
|
expectAgentProfileTagsGone,
|
||||||
expectHostAgentProfiles,
|
expectHostAgentProfiles,
|
||||||
expectNoAgentProfiles,
|
expectNoAgentProfiles,
|
||||||
|
fillAgentProfileName,
|
||||||
|
fillAgentProfileNotes,
|
||||||
moveAgentProfileUp,
|
moveAgentProfileUp,
|
||||||
|
openAgentProfileEditor,
|
||||||
openAgentProfileSettings,
|
openAgentProfileSettings,
|
||||||
|
openCompactAgentProfileSettings,
|
||||||
|
openCreateAgentProfileEditor,
|
||||||
removeAgentProfile,
|
removeAgentProfile,
|
||||||
|
saveOpenAgentProfile,
|
||||||
seedAgentProfiles,
|
seedAgentProfiles,
|
||||||
stageLegacyFavoritesForHostMigration,
|
stageLegacyFavoritesForHostMigration,
|
||||||
|
switchSettingsSectionWithConfirm,
|
||||||
|
toggleAgentProfileCustomize,
|
||||||
} from "../support/helpers/agent-profiles";
|
} from "../support/helpers/agent-profiles";
|
||||||
|
|
||||||
const MOCK_PROVIDER_LABEL = "Mock Load Test";
|
const MOCK_PROVIDER_LABEL = "Mock Load Test";
|
||||||
@@ -125,4 +138,252 @@ test.describe("Agent profiles settings", () => {
|
|||||||
await seed.restore();
|
await seed.restore();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("remounting the profile form keeps draft text across resize and collapsible toggles", async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
const seed = await seedAgentProfiles([
|
||||||
|
{
|
||||||
|
id: "agent_profile_e2e_remount",
|
||||||
|
name: "Original profile",
|
||||||
|
provider: "mock",
|
||||||
|
model: "one-minute-stream",
|
||||||
|
notes: "Original note",
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await page.setViewportSize({ width: 1680, height: 900 });
|
||||||
|
await openAgentProfileSettings(page);
|
||||||
|
|
||||||
|
await test.step("drawer-to-modal and compact resizes keep the edited name and save it", async () => {
|
||||||
|
await openAgentProfileEditor(page, "Original profile");
|
||||||
|
await expect(page.getByTestId("agent-profile-drawer")).toBeVisible();
|
||||||
|
await fillAgentProfileName(page, "Draft rename");
|
||||||
|
|
||||||
|
await page.setViewportSize({ width: 1000, height: 900 });
|
||||||
|
await expect(page.getByTestId("agent-profile-edit-modal")).toBeVisible({ timeout: 30_000 });
|
||||||
|
await expectAgentProfileNameDraft(page, "Draft rename");
|
||||||
|
|
||||||
|
await page.setViewportSize({ width: 390, height: 844 });
|
||||||
|
await expect(page.getByTestId("agent-profile-edit-modal")).toBeVisible({ timeout: 30_000 });
|
||||||
|
await expectAgentProfileNameDraft(page, "Draft rename");
|
||||||
|
|
||||||
|
await saveOpenAgentProfile(page);
|
||||||
|
await expectAgentProfile(page, {
|
||||||
|
name: "Draft rename",
|
||||||
|
tags: [MOCK_PROVIDER_LABEL, "One minute stream"],
|
||||||
|
notes: "Original note",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
await test.step("collapsing and reopening advanced settings keeps the draft note", async () => {
|
||||||
|
await page.setViewportSize({ width: 1000, height: 900 });
|
||||||
|
await openCreateAgentProfileEditor(page);
|
||||||
|
await expect(page.getByTestId("agent-profile-edit-modal")).toBeVisible({ timeout: 30_000 });
|
||||||
|
await toggleAgentProfileCustomize(page);
|
||||||
|
await fillAgentProfileNotes(page, "Draft routing note");
|
||||||
|
await toggleAgentProfileCustomize(page);
|
||||||
|
await toggleAgentProfileCustomize(page);
|
||||||
|
await expectAgentProfileNotesDraft(page, "Draft routing note");
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
await seed.restore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("duplicating while editing asks before discarding unsaved changes", async ({ page }) => {
|
||||||
|
const seed = await seedAgentProfiles([
|
||||||
|
{
|
||||||
|
id: "agent_profile_e2e_duplicate",
|
||||||
|
name: "UI work",
|
||||||
|
provider: "mock",
|
||||||
|
model: "one-minute-stream",
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await page.setViewportSize({ width: 1680, height: 900 });
|
||||||
|
await openAgentProfileSettings(page);
|
||||||
|
await openAgentProfileEditor(page, "UI work");
|
||||||
|
await expect(page.getByTestId("agent-profile-drawer")).toBeVisible();
|
||||||
|
await fillAgentProfileName(page, "Draft name");
|
||||||
|
|
||||||
|
await test.step("dismissing the prompt keeps the draft and does not create a copy", async () => {
|
||||||
|
await duplicateOpenAgentProfileWithConfirm(page, "dismiss");
|
||||||
|
await expectAgentProfileNameDraft(page, "Draft name");
|
||||||
|
await expectAgentProfileOrder(page, ["UI work"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
await test.step("accepting the prompt creates and opens the copy", async () => {
|
||||||
|
await duplicateOpenAgentProfileWithConfirm(page, "accept");
|
||||||
|
await expectAgentProfileOrder(page, ["UI work", "UI work (copy)"]);
|
||||||
|
await expectAgentProfileNameDraft(page, "UI work (copy)");
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
await seed.restore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("docked drawer allows roster search and section switches ask before discarding a draft", async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
const seed = await seedAgentProfiles([
|
||||||
|
{
|
||||||
|
id: "agent_profile_e2e_docked_1",
|
||||||
|
name: "UI work",
|
||||||
|
provider: "mock",
|
||||||
|
model: "one-minute-stream",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "agent_profile_e2e_docked_2",
|
||||||
|
name: "Deep review",
|
||||||
|
provider: "mock",
|
||||||
|
model: "five-minute-stream",
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await page.setViewportSize({ width: 1680, height: 900 });
|
||||||
|
await openAgentProfileSettings(page);
|
||||||
|
await openAgentProfileEditor(page, "UI work");
|
||||||
|
await expect(page.getByTestId("agent-profile-drawer")).toBeVisible();
|
||||||
|
|
||||||
|
await test.step("typing in roster search works while the docked drawer is open", async () => {
|
||||||
|
const searchInput = page.getByTestId("agent-profiles-search-input");
|
||||||
|
await searchInput.click();
|
||||||
|
await page.keyboard.type("Deep");
|
||||||
|
await expect(searchInput).toHaveValue("Deep");
|
||||||
|
await expect(page.getByTestId("agent-profile-drawer")).toBeVisible();
|
||||||
|
await expectAgentProfileOrder(page, ["Deep review"]);
|
||||||
|
await page.getByTestId("agent-profiles-search-clear").click();
|
||||||
|
});
|
||||||
|
|
||||||
|
await test.step("browser Back asks before discarding a draft and canceling keeps route and draft", async () => {
|
||||||
|
await fillAgentProfileName(page, "Unsaved browser back edit");
|
||||||
|
const profilesUrl = page.url();
|
||||||
|
|
||||||
|
await browserBackWithConfirm(page, "dismiss");
|
||||||
|
await expect(page).toHaveURL(profilesUrl, { timeout: 15_000 });
|
||||||
|
await expect(page.getByTestId("agent-profile-drawer")).toBeVisible();
|
||||||
|
await expectAgentProfileNameDraft(page, "Unsaved browser back edit");
|
||||||
|
});
|
||||||
|
|
||||||
|
await test.step("switching Settings sections asks before discarding an edited draft", async () => {
|
||||||
|
await fillAgentProfileName(page, "Unsaved sidebar edit");
|
||||||
|
|
||||||
|
await switchSettingsSectionWithConfirm(page, "Agents", "dismiss");
|
||||||
|
await expect(page.getByTestId("agent-profile-drawer")).toBeVisible();
|
||||||
|
await expectAgentProfileNameDraft(page, "Unsaved sidebar edit");
|
||||||
|
|
||||||
|
await switchSettingsSectionWithConfirm(page, "Agents", "accept");
|
||||||
|
await expect(page.getByTestId("agent-profile-drawer")).toHaveCount(0, { timeout: 30_000 });
|
||||||
|
await expect(page.getByTestId("settings-detail-header-title")).toHaveText("Agents");
|
||||||
|
});
|
||||||
|
|
||||||
|
await test.step("confirming browser Back leaves Agent profiles and discards the draft", async () => {
|
||||||
|
await page.getByRole("button", { name: "Agent profiles", exact: true }).click();
|
||||||
|
await expect(page.getByTestId("agent-profiles-card")).toBeVisible({ timeout: 30_000 });
|
||||||
|
await openAgentProfileEditor(page, "UI work");
|
||||||
|
await fillAgentProfileName(page, "Discard on browser back");
|
||||||
|
const profilesUrl = page.url();
|
||||||
|
|
||||||
|
await browserBackWithConfirm(page, "accept");
|
||||||
|
await expect(page).not.toHaveURL(profilesUrl, { timeout: 15_000 });
|
||||||
|
await expect(page.getByTestId("agent-profile-drawer")).toHaveCount(0, { timeout: 30_000 });
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
await seed.restore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("canceling a multi-step Back jump keeps intervening browser history and confirming reaches the destination", async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
const seed = await seedAgentProfiles([
|
||||||
|
{
|
||||||
|
id: "agent_profile_e2e_multistep",
|
||||||
|
name: "UI work",
|
||||||
|
provider: "mock",
|
||||||
|
model: "one-minute-stream",
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Narrow viewport pushes Open project -> Settings -> Agent profiles onto history.
|
||||||
|
await page.setViewportSize({ width: 390, height: 844 });
|
||||||
|
await openCompactAgentProfileSettings(page);
|
||||||
|
const profilesUrl = page.url();
|
||||||
|
|
||||||
|
await openAgentProfileEditor(page, "UI work");
|
||||||
|
await fillAgentProfileName(page, "Unsaved multi-step edit");
|
||||||
|
|
||||||
|
await test.step("canceling a two-step Back jump keeps Agent profiles, draft, and Settings in history", async () => {
|
||||||
|
await browserHistoryJumpWithConfirm(page, -2, "dismiss");
|
||||||
|
await expect(page).toHaveURL(profilesUrl, { timeout: 15_000 });
|
||||||
|
await expect(page.getByTestId("agent-profile-edit-modal")).toBeVisible();
|
||||||
|
await expectAgentProfileNameDraft(page, "Unsaved multi-step edit");
|
||||||
|
});
|
||||||
|
|
||||||
|
await test.step("canceling a two-step Back jump after reload still restores the Agent profiles URL", async () => {
|
||||||
|
await page.reload();
|
||||||
|
await expect(page.getByTestId("agent-profiles-card")).toBeVisible({ timeout: 30_000 });
|
||||||
|
await openAgentProfileEditor(page, "UI work");
|
||||||
|
await fillAgentProfileName(page, "Post-reload draft");
|
||||||
|
|
||||||
|
await browserHistoryJumpWithConfirm(page, -2, "dismiss");
|
||||||
|
await expect(page).toHaveURL(profilesUrl, { timeout: 15_000 });
|
||||||
|
await expect(page.getByTestId("agent-profile-edit-modal")).toBeVisible();
|
||||||
|
await expectAgentProfileNameDraft(page, "Post-reload draft");
|
||||||
|
});
|
||||||
|
|
||||||
|
await test.step("confirming a two-step Back jump lands directly on the selected destination", async () => {
|
||||||
|
await browserHistoryJumpWithConfirm(page, -2, "accept");
|
||||||
|
await expect(page).toHaveURL(/\/open-project/, { timeout: 15_000 });
|
||||||
|
await expect(page.getByTestId("agent-profile-edit-modal")).toHaveCount(0, {
|
||||||
|
timeout: 30_000,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
await test.step("forward navigation confirms the intervening Settings entry survived", async () => {
|
||||||
|
await page.goForward();
|
||||||
|
await expect(page).toHaveURL(/\/settings(?:\?|$)/, { timeout: 15_000 });
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
await seed.restore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("canceling an untouched provider-and-model-only profile closes without a discard prompt", async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
const seed = await seedAgentProfiles([
|
||||||
|
{
|
||||||
|
id: "legacy_favorite:mock:one-minute-stream",
|
||||||
|
name: "One minute stream",
|
||||||
|
provider: "mock",
|
||||||
|
model: "one-minute-stream",
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
let dialogTriggered = false;
|
||||||
|
const onDialog = async (dialog: { dismiss: () => Promise<void> }) => {
|
||||||
|
dialogTriggered = true;
|
||||||
|
await dialog.dismiss();
|
||||||
|
};
|
||||||
|
page.on("dialog", onDialog);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await page.setViewportSize({ width: 1680, height: 900 });
|
||||||
|
await openAgentProfileSettings(page);
|
||||||
|
await openAgentProfileEditor(page, "One minute stream");
|
||||||
|
await expect(page.getByTestId("agent-profile-drawer")).toBeVisible();
|
||||||
|
await page.getByTestId("agent-profile-cancel-button").click();
|
||||||
|
await expect(page.getByTestId("agent-profile-drawer")).toHaveCount(0, { timeout: 30_000 });
|
||||||
|
expect(dialogTriggered).toBe(false);
|
||||||
|
} finally {
|
||||||
|
page.off("dialog", onDialog);
|
||||||
|
await seed.restore();
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { expect, test } from "../support/fixtures";
|
import { expect, test } from "../support/fixtures";
|
||||||
import { gotoAppShell } from "../support/helpers/app";
|
import { gotoAppShell } from "../support/helpers/app";
|
||||||
import {
|
import {
|
||||||
|
chooseProjectWithKeyboard,
|
||||||
connectNewWorkspaceDaemonClient,
|
connectNewWorkspaceDaemonClient,
|
||||||
expectNewWorkspaceControlsEnabled,
|
expectNewWorkspaceControlsEnabled,
|
||||||
expectNewWorkspaceProjectSelected,
|
expectNewWorkspaceProjectSelected,
|
||||||
@@ -176,6 +177,33 @@ test.describe("New workspace entry points", () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("choosing a project returns focus to the composer, even when the picker was opened by clicking it", async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
const projectA: SeededWorkspace = await seedWorkspace({ repoPrefix: "entry-focus-a-" });
|
||||||
|
const projectB: SeededWorkspace = await seedWorkspace({ repoPrefix: "entry-focus-b-" });
|
||||||
|
|
||||||
|
try {
|
||||||
|
await gotoAppShell(page);
|
||||||
|
await waitForSidebarHydration(page);
|
||||||
|
await openGlobalNewWorkspaceComposer(page);
|
||||||
|
const composer = page.getByRole("textbox", { name: "Message agent..." });
|
||||||
|
|
||||||
|
await page.getByTestId("new-workspace-project-picker-trigger").click();
|
||||||
|
await chooseProjectWithKeyboard(page, projectB.projectDisplayName);
|
||||||
|
await expectNewWorkspaceProjectSelected(page, projectB.projectDisplayName);
|
||||||
|
await expect(composer).toBeFocused();
|
||||||
|
|
||||||
|
await page.keyboard.press("Control+N");
|
||||||
|
await chooseProjectWithKeyboard(page, projectA.projectDisplayName);
|
||||||
|
await expectNewWorkspaceProjectSelected(page, projectA.projectDisplayName);
|
||||||
|
await expect(composer).toBeFocused();
|
||||||
|
} finally {
|
||||||
|
await projectA.cleanup();
|
||||||
|
await projectB.cleanup();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
test("keeps the in-progress form when the remembered workspace is archived elsewhere", async ({
|
test("keeps the in-progress form when the remembered workspace is archived elsewhere", async ({
|
||||||
page,
|
page,
|
||||||
}) => {
|
}) => {
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { expect, test, type Page } from "../support/fixtures";
|
|||||||
import { gotoAppShell } from "../support/helpers/app";
|
import { gotoAppShell } from "../support/helpers/app";
|
||||||
import { waitForSidebarHydration } from "../support/helpers/workspace-ui";
|
import { waitForSidebarHydration } from "../support/helpers/workspace-ui";
|
||||||
import {
|
import {
|
||||||
|
chooseProjectWithKeyboard,
|
||||||
expectNewWorkspaceDraft,
|
expectNewWorkspaceDraft,
|
||||||
fillNewWorkspaceDraft,
|
fillNewWorkspaceDraft,
|
||||||
openNewWorkspaceComposer,
|
openNewWorkspaceComposer,
|
||||||
@@ -109,6 +110,27 @@ test.describe("New workspace: launching a terminal", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("with a profile that takes no prompt, choosing a project keeps focus on the Project field", async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
await gotoAppShell(page);
|
||||||
|
await waitForSidebarHydration(page);
|
||||||
|
await openNewWorkspaceComposer(page, {
|
||||||
|
projectKey: workspace.projectKey,
|
||||||
|
projectDisplayName: workspace.projectDisplayName,
|
||||||
|
});
|
||||||
|
await selectLaunchOption(page, BARE_PROFILE.id);
|
||||||
|
await expect(terminalPromptInput(page)).toHaveCount(0);
|
||||||
|
|
||||||
|
// The read-only command preview has nothing to type into, so the picker
|
||||||
|
// hands focus back to the field that opened it.
|
||||||
|
const projectTrigger = page.getByTestId("new-workspace-project-picker-trigger");
|
||||||
|
await projectTrigger.focus();
|
||||||
|
await page.keyboard.press("Enter");
|
||||||
|
await chooseProjectWithKeyboard(page, workspace.projectDisplayName);
|
||||||
|
await expect(projectTrigger).toBeFocused();
|
||||||
|
});
|
||||||
|
|
||||||
test("switching terminal profiles restores the prompt and its fullscreen affordance", async ({
|
test("switching terminal profiles restores the prompt and its fullscreen affordance", async ({
|
||||||
page,
|
page,
|
||||||
}) => {
|
}) => {
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ import {
|
|||||||
closeRelayPairing,
|
closeRelayPairing,
|
||||||
emptyHome,
|
emptyHome,
|
||||||
loadingScreen,
|
loadingScreen,
|
||||||
openTailscaleDocsFromSetup,
|
expectTailscaleSwitchDisabled,
|
||||||
paseoToolsSwitch,
|
paseoToolsSwitch,
|
||||||
pickTheme,
|
pickTheme,
|
||||||
projectSuggestion,
|
projectSuggestion,
|
||||||
@@ -403,12 +403,10 @@ test("setup choices carry over to Settings and the phone step pairs over relay",
|
|||||||
await continueSetup(page);
|
await continueSetup(page);
|
||||||
});
|
});
|
||||||
|
|
||||||
await test.step("Phone offers Tailscale docs and pairs over relay in its own modal", async () => {
|
await test.step("Phone shows a disabled Tailscale switch and pairs over relay", async () => {
|
||||||
await expectSetupStep(page, "Take your agents with you");
|
await expectSetupStep(page, "Take your agents with you");
|
||||||
await page.screenshot({ path: testInfo.outputPath("5-phone.png") });
|
await page.screenshot({ path: testInfo.outputPath("5-phone.png") });
|
||||||
expect(await openTailscaleDocsFromSetup(page)).toBe(
|
await expectTailscaleSwitchDisabled(page);
|
||||||
"https://paseo.sh/docs/connectivity#tailscale",
|
|
||||||
);
|
|
||||||
const pairing = await openRelayPairingFromSetup(page);
|
const pairing = await openRelayPairingFromSetup(page);
|
||||||
await expect(pairing.getByText("Enable relay?", { exact: true })).toBeVisible();
|
await expect(pairing.getByText("Enable relay?", { exact: true })).toBeVisible();
|
||||||
await enableRelayAndExpectOffer(page);
|
await enableRelayAndExpectOffer(page);
|
||||||
|
|||||||
@@ -1,7 +1,24 @@
|
|||||||
|
import { gotoAppShell, openSettings } from "../support/helpers/app";
|
||||||
|
import {
|
||||||
|
addDirectHostFromSettings,
|
||||||
|
openSettingsHostSection,
|
||||||
|
selectSettingsHost,
|
||||||
|
} from "../support/helpers/settings";
|
||||||
import { test } from "../support/fixtures";
|
import { test } from "../support/fixtures";
|
||||||
|
import { startTailscaleTestDaemon } from "../support/helpers/tailscale-daemon";
|
||||||
import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon";
|
import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon";
|
||||||
import {
|
import {
|
||||||
expectPairingOffer,
|
expectPairingOffer,
|
||||||
|
cancelTailscaleTurnOff,
|
||||||
|
confirmTailscaleTurnOff,
|
||||||
|
connectThroughTailscale,
|
||||||
|
disableTailscale,
|
||||||
|
enableTailscale,
|
||||||
|
expectTailscaleAddress,
|
||||||
|
expectTailscaleRowLoadsOn,
|
||||||
|
openSetupMobileStep,
|
||||||
|
slowConnectionToHost,
|
||||||
|
expectTailscaleUpdateRequired,
|
||||||
expectCompletePairingQr,
|
expectCompletePairingQr,
|
||||||
expectRelayConsent,
|
expectRelayConsent,
|
||||||
openPairDeviceModal,
|
openPairDeviceModal,
|
||||||
@@ -37,3 +54,59 @@ test("keeps the pairing QR code inside its compact tile", async ({ page }, testI
|
|||||||
await daemon.close();
|
await daemon.close();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("asks for a host update when Tailscale controls are unavailable", async ({ page }) => {
|
||||||
|
const daemon = await startIsolatedHostDaemon("pair-device-browser-old-host", {
|
||||||
|
publishedVersion: "0.13.0-beta.2",
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
await gotoAppShell(page);
|
||||||
|
await openSettings(page);
|
||||||
|
await addDirectHostFromSettings(page, { host: "127.0.0.1", port: daemon.port });
|
||||||
|
await selectSettingsHost(page, daemon.serverId);
|
||||||
|
await openSettingsHostSection(page, daemon.serverId, "devices");
|
||||||
|
await expectTailscaleUpdateRequired(page);
|
||||||
|
} finally {
|
||||||
|
await daemon.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("turns Tailscale on and off from Devices, asking first over Tailscale", async ({
|
||||||
|
page,
|
||||||
|
baseURL,
|
||||||
|
}, testInfo) => {
|
||||||
|
test.skip(process.platform !== "linux", "Uses a second IPv4 loopback address");
|
||||||
|
// The journey opens Devices or the setup six times, two of them over a slowed connection.
|
||||||
|
test.setTimeout(120_000);
|
||||||
|
if (!baseURL) throw new Error("Expected the app base URL");
|
||||||
|
const daemon = await startTailscaleTestDaemon(baseURL);
|
||||||
|
try {
|
||||||
|
await preparePairingHost(page, daemon);
|
||||||
|
await enableTailscale(page);
|
||||||
|
await expectTailscaleAddress(page, daemon.tailscaleAddress);
|
||||||
|
await page.screenshot({ path: testInfo.outputPath("devices.png") });
|
||||||
|
|
||||||
|
await test.step("While its status loads, the row never shows Tailscale off", async () => {
|
||||||
|
const address = daemon.tailscaleAddress;
|
||||||
|
await expectTailscaleRowLoadsOn(page, address, () => preparePairingHost(page, daemon));
|
||||||
|
await expectTailscaleRowLoadsOn(page, address, () => openSetupMobileStep(page, daemon));
|
||||||
|
const restoreSpeed = await slowConnectionToHost(page, daemon.port, 300);
|
||||||
|
await expectTailscaleRowLoadsOn(page, address, () => openSetupMobileStep(page, daemon));
|
||||||
|
await expectTailscaleRowLoadsOn(page, address, () => preparePairingHost(page, daemon));
|
||||||
|
restoreSpeed();
|
||||||
|
});
|
||||||
|
|
||||||
|
await disableTailscale(page, daemon.tailscaleAddress);
|
||||||
|
|
||||||
|
await test.step("Over Tailscale, turning it off asks first and Cancel changes nothing", async () => {
|
||||||
|
await enableTailscale(page);
|
||||||
|
await connectThroughTailscale(page, daemon);
|
||||||
|
await cancelTailscaleTurnOff(page, daemon.tailscaleAddress);
|
||||||
|
});
|
||||||
|
await test.step("Confirming turns it off and cuts this connection", async () => {
|
||||||
|
await confirmTailscaleTurnOff(page, daemon.tailscaleAddress);
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
await daemon.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|||||||
@@ -372,6 +372,25 @@ test.describe("Plugin sidebar items", () => {
|
|||||||
await expect(page.getByText("Plugin failed", { exact: false })).toHaveCount(0);
|
await expect(page.getByText("Plugin failed", { exact: false })).toHaveCount(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("a plugin screen keeps the sidebar toggle before its title", async ({ page }) => {
|
||||||
|
await page.setViewportSize(WIDE);
|
||||||
|
await gotoWorkspace(page, workspaceId);
|
||||||
|
await expect(headerRow(page, SHOWCASE_PLUGIN_ID, "deploys")).toBeVisible({ timeout: 30_000 });
|
||||||
|
await runCommand(page, "Open plugin workspaces");
|
||||||
|
await expect(screenTitle(page)).toHaveText("Workspaces");
|
||||||
|
await page.keyboard.press("ControlOrMeta+b");
|
||||||
|
await expect(page.getByTestId("sidebar-global-new-workspace")).not.toBeVisible();
|
||||||
|
|
||||||
|
await expect(visibleTestId(page, "menu-button")).toBeVisible();
|
||||||
|
const toggle = await boxOf(visibleTestId(page, "menu-button"));
|
||||||
|
const title = await boxOf(screenTitle(page));
|
||||||
|
expect(toggle.x + toggle.width).toBeLessThanOrEqual(title.x);
|
||||||
|
await qaScreenshot(page, "plugin-screen-sidebar-collapsed");
|
||||||
|
|
||||||
|
await visibleTestId(page, "menu-button").click();
|
||||||
|
await expect(page.getByTestId("sidebar-global-new-workspace")).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
test("a header row's shortcut hint presses the row", async ({ page }) => {
|
test("a header row's shortcut hint presses the row", async ({ page }) => {
|
||||||
await page.setViewportSize(WIDE);
|
await page.setViewportSize(WIDE);
|
||||||
await gotoWorkspace(page, workspaceId);
|
await gotoWorkspace(page, workspaceId);
|
||||||
|
|||||||
@@ -0,0 +1,121 @@
|
|||||||
|
import type { Locator, Page } from "@playwright/test";
|
||||||
|
import { expect, test } from "../support/fixtures";
|
||||||
|
import { gotoAppShell } from "../support/helpers/app";
|
||||||
|
import { getServerId } from "../support/helpers/server-id";
|
||||||
|
import { seedWorkspace } from "../support/helpers/seed-client";
|
||||||
|
import { selectSidebarStatusGrouping } from "../support/helpers/sidebar";
|
||||||
|
import { waitForSidebarHydration } from "../support/helpers/workspace-ui";
|
||||||
|
|
||||||
|
// Cmd on macOS, Ctrl on Windows and Linux: the platform primary modifier the app binds as `mod`.
|
||||||
|
const MOD = "ControlOrMeta";
|
||||||
|
|
||||||
|
type SeededProject = Awaited<ReturnType<typeof seedWorkspace>>;
|
||||||
|
|
||||||
|
async function seedProjectWithWorkspaces(count: number) {
|
||||||
|
const project = await seedWorkspace({ repoPrefix: "sidebar-selection-" });
|
||||||
|
const workspaceIds = [project.workspaceId];
|
||||||
|
for (let index = 1; index < count; index += 1) {
|
||||||
|
const created = await project.client.createWorkspace({
|
||||||
|
source: { kind: "directory", path: project.repoPath, projectId: project.projectId },
|
||||||
|
title: `Selection workspace ${index}`,
|
||||||
|
});
|
||||||
|
if (!created.workspace) throw new Error(created.error ?? "Failed to seed a workspace");
|
||||||
|
workspaceIds.push(created.workspace.id);
|
||||||
|
}
|
||||||
|
return { project, workspaceIds };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The seeded rows, in the order the sidebar shows them. */
|
||||||
|
async function rowsInSidebarOrder(page: Page, workspaceIds: readonly string[]) {
|
||||||
|
const testIds = workspaceIds.map((id) => `sidebar-workspace-row-${getServerId()}:${id}`);
|
||||||
|
const rows = page.locator(testIds.map((testId) => `[data-testid="${testId}"]`).join(", "));
|
||||||
|
await expect(rows).toHaveCount(workspaceIds.length);
|
||||||
|
const ordered = await rows.evaluateAll((elements) =>
|
||||||
|
elements.map((element) => element.getAttribute("data-testid") ?? ""),
|
||||||
|
);
|
||||||
|
return ordered.map((testId) => page.getByTestId(testId));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function expectChecked(rows: readonly Locator[], checked: readonly boolean[]) {
|
||||||
|
for (const [index, row] of rows.entries()) {
|
||||||
|
await expect(row).toHaveAttribute("aria-checked", String(checked[index]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function expectSelectedCount(page: Page, count: number) {
|
||||||
|
await expect(page.getByTestId("workspace-selection-count")).toHaveText(`${count} selected`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function exitSelection(page: Page) {
|
||||||
|
await page.getByTestId("workspace-selection-exit").click();
|
||||||
|
await expect(page.getByTestId("workspace-selection-toast")).toHaveCount(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Walks the Finder click matrix on four rows, starting with the first row open: a modifier click
|
||||||
|
* from normal mode selects only the clicked row, Cmd/Ctrl+click toggles, Shift+click extends and
|
||||||
|
* shrinks a range from the anchor, and plain clicks keep toggling while select mode is on.
|
||||||
|
*/
|
||||||
|
async function exerciseClickMatrix(page: Page, rows: readonly Locator[]) {
|
||||||
|
const [first, second, third, fourth] = rows;
|
||||||
|
await first.click();
|
||||||
|
await expect(first).toHaveAttribute("aria-selected", "true");
|
||||||
|
const openWorkspaceUrl = page.url();
|
||||||
|
|
||||||
|
await third.click({ modifiers: [MOD] });
|
||||||
|
await expectSelectedCount(page, 1);
|
||||||
|
await expectChecked(rows, [false, false, true, false]);
|
||||||
|
|
||||||
|
await fourth.click({ modifiers: [MOD] });
|
||||||
|
await expectChecked(rows, [false, false, true, true]);
|
||||||
|
await third.click({ modifiers: [MOD] });
|
||||||
|
await expectChecked(rows, [false, false, false, true]);
|
||||||
|
|
||||||
|
await second.click();
|
||||||
|
await expectChecked(rows, [false, true, false, true]);
|
||||||
|
expect(page.url()).toBe(openWorkspaceUrl);
|
||||||
|
await exitSelection(page);
|
||||||
|
|
||||||
|
await second.click({ modifiers: ["Shift"] });
|
||||||
|
await expectSelectedCount(page, 1);
|
||||||
|
await expectChecked(rows, [false, true, false, false]);
|
||||||
|
|
||||||
|
await fourth.click({ modifiers: ["Shift"] });
|
||||||
|
await expectChecked(rows, [false, true, true, true]);
|
||||||
|
await third.click({ modifiers: ["Shift"] });
|
||||||
|
await expectChecked(rows, [false, true, true, false]);
|
||||||
|
await first.click({ modifiers: ["Shift"] });
|
||||||
|
await expectChecked(rows, [true, true, false, false]);
|
||||||
|
|
||||||
|
await fourth.click({ modifiers: [MOD] });
|
||||||
|
await third.click({ modifiers: ["Shift"] });
|
||||||
|
await expectChecked(rows, [true, true, true, true]);
|
||||||
|
expect(page.url()).toBe(openWorkspaceUrl);
|
||||||
|
await exitSelection(page);
|
||||||
|
}
|
||||||
|
|
||||||
|
test.describe("sidebar workspace selection clicks", () => {
|
||||||
|
let seeded: { project: SeededProject; workspaceIds: string[] } | null = null;
|
||||||
|
|
||||||
|
test.afterEach(async () => {
|
||||||
|
await seeded?.project.cleanup();
|
||||||
|
seeded = null;
|
||||||
|
});
|
||||||
|
|
||||||
|
test("Cmd/Ctrl+click and Shift+click select like Finder in project grouping", async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
seeded = await seedProjectWithWorkspaces(4);
|
||||||
|
await gotoAppShell(page);
|
||||||
|
await waitForSidebarHydration(page);
|
||||||
|
await exerciseClickMatrix(page, await rowsInSidebarOrder(page, seeded.workspaceIds));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("Cmd/Ctrl+click and Shift+click select like Finder in status grouping", async ({ page }) => {
|
||||||
|
seeded = await seedProjectWithWorkspaces(4);
|
||||||
|
await gotoAppShell(page);
|
||||||
|
await waitForSidebarHydration(page);
|
||||||
|
await selectSidebarStatusGrouping(page);
|
||||||
|
await exerciseClickMatrix(page, await rowsInSidebarOrder(page, seeded.workspaceIds));
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -153,3 +153,25 @@ On iPad, replacing the field a second time appends text. For this Settings journ
|
|||||||
native clipboard Paste menu, then continue the assertions manually. Dismiss the password keyboard
|
native clipboard Paste menu, then continue the assertions manually. Dismiss the password keyboard
|
||||||
with Done to submit when the Connect button is below the keyboard. The welcome pairing regression
|
with Done to submit when the Connect button is below the keyboard. The welcome pairing regression
|
||||||
runs end to end without these adjustments.
|
runs end to end without these adjustments.
|
||||||
|
|
||||||
|
## Sheet footer keyboard safe-area clearance
|
||||||
|
|
||||||
|
`footer-keyboard.android.sh` records the **Add project** sheet on an Android device or emulator
|
||||||
|
across repeated keyboard open/dismiss transitions, then runs `assert-sheet-footer-keyboard.mjs`
|
||||||
|
over every recorded frame. Configure three-button navigation, `show_ime_with_hard_keyboard=1`, and
|
||||||
|
a visible soft keyboard (such as Gboard) on the test device before running so the script does not
|
||||||
|
mutate device settings. The assertion checks both settled positions against the navigation bar
|
||||||
|
height and fails if any frame drops the **Open project** button into the navigation bar or
|
||||||
|
overshoots above its open-keyboard position.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
ANDROID_SERIAL=emulator-5554 \
|
||||||
|
packages/app/e2e/mobile/modal-sheet/footer-keyboard.android.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
You can also validate an existing screen recording directly (optionally passing pixel tolerance and
|
||||||
|
navigation bar height in pixels):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
node packages/app/e2e/mobile/modal-sheet/assert-sheet-footer-keyboard.mjs /path/to/recording.mp4 4 96
|
||||||
|
```
|
||||||
|
|||||||
@@ -0,0 +1,173 @@
|
|||||||
|
import { execFileSync, spawnSync } from "node:child_process";
|
||||||
|
import process from "node:process";
|
||||||
|
|
||||||
|
const [, , videoPath, toleranceArg = "4", navBarHeightArg = "0"] = process.argv;
|
||||||
|
|
||||||
|
if (!videoPath) {
|
||||||
|
throw new Error(
|
||||||
|
"Usage: node assert-sheet-footer-keyboard.mjs <screenrecord.mp4> [pixel-tolerance] [nav-bar-height-px]",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const tolerance = Number(toleranceArg);
|
||||||
|
if (!Number.isFinite(tolerance) || tolerance < 0) {
|
||||||
|
throw new Error(`Invalid pixel tolerance: ${toleranceArg}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const navBarHeight = Number(navBarHeightArg);
|
||||||
|
if (!Number.isFinite(navBarHeight) || navBarHeight < 0) {
|
||||||
|
throw new Error(`Invalid navigation bar height: ${navBarHeightArg}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function probeDimensions(filePath) {
|
||||||
|
const output = execFileSync(
|
||||||
|
"ffprobe",
|
||||||
|
[
|
||||||
|
"-v",
|
||||||
|
"error",
|
||||||
|
"-select_streams",
|
||||||
|
"v:0",
|
||||||
|
"-show_entries",
|
||||||
|
"stream=width,height",
|
||||||
|
"-of",
|
||||||
|
"csv=s=x:p=0",
|
||||||
|
filePath,
|
||||||
|
],
|
||||||
|
{ encoding: "utf8" },
|
||||||
|
).trim();
|
||||||
|
const [width, height] = output.split("x").map(Number);
|
||||||
|
if (!width || !height) {
|
||||||
|
throw new Error(`Unable to read video dimensions for ${filePath}: ${output}`);
|
||||||
|
}
|
||||||
|
return { width, height };
|
||||||
|
}
|
||||||
|
|
||||||
|
function measureButtonBottomPerFrame(filePath, width, height) {
|
||||||
|
const centerX = Math.floor(width / 2);
|
||||||
|
// Decode only the 1px vertical centerline so full-rate recordings fit comfortably in memory.
|
||||||
|
const result = spawnSync(
|
||||||
|
"ffmpeg",
|
||||||
|
[
|
||||||
|
"-v",
|
||||||
|
"error",
|
||||||
|
"-i",
|
||||||
|
filePath,
|
||||||
|
"-vf",
|
||||||
|
`format=rgb24,crop=1:${height}:${centerX}:0`,
|
||||||
|
"-vsync",
|
||||||
|
"0",
|
||||||
|
"-f",
|
||||||
|
"rawvideo",
|
||||||
|
"-pix_fmt",
|
||||||
|
"rgb24",
|
||||||
|
"-",
|
||||||
|
],
|
||||||
|
{ maxBuffer: 64 * 1024 * 1024 },
|
||||||
|
);
|
||||||
|
if (result.status !== 0) {
|
||||||
|
throw new Error(`ffmpeg failed (${result.status}): ${result.stderr?.toString("utf8") ?? ""}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const buffer = result.stdout;
|
||||||
|
const frameSize = height * 3;
|
||||||
|
const frameCount = Math.floor(buffer.length / frameSize);
|
||||||
|
// Restrict vertical scan below the search field so its green focus ring is excluded.
|
||||||
|
const scanTop = Math.floor(height * 0.42);
|
||||||
|
const bottoms = [];
|
||||||
|
|
||||||
|
for (let frame = 0; frame < frameCount; frame += 1) {
|
||||||
|
const frameOffset = frame * frameSize;
|
||||||
|
let maxY = null;
|
||||||
|
for (let y = scanTop; y < height; y += 1) {
|
||||||
|
const offset = frameOffset + y * 3;
|
||||||
|
const r = buffer[offset];
|
||||||
|
const g = buffer[offset + 1];
|
||||||
|
const b = buffer[offset + 2];
|
||||||
|
// Matches the green primary "Open project" button (both enabled and disabled states).
|
||||||
|
if (g > 50 && g > r + 15 && g > b + 10) {
|
||||||
|
maxY = y;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
bottoms.push(maxY);
|
||||||
|
}
|
||||||
|
return bottoms;
|
||||||
|
}
|
||||||
|
|
||||||
|
function findSettledValue(values, minRunLength) {
|
||||||
|
let runValue = null;
|
||||||
|
let runLength = 0;
|
||||||
|
for (const value of values) {
|
||||||
|
if (value !== null && runValue !== null && Math.abs(value - runValue) <= 2) {
|
||||||
|
runLength += 1;
|
||||||
|
if (runLength >= minRunLength) return runValue;
|
||||||
|
} else {
|
||||||
|
runValue = value;
|
||||||
|
runLength = value === null ? 0 : 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { width, height } = probeDimensions(videoPath);
|
||||||
|
const bottoms = measureButtonBottomPerFrame(videoPath, width, height);
|
||||||
|
const visibleFrames = bottoms
|
||||||
|
.map((bottom, frame) => ({ frame, bottom }))
|
||||||
|
.filter((entry) => entry.bottom !== null);
|
||||||
|
|
||||||
|
if (visibleFrames.length < 10) {
|
||||||
|
throw new Error(
|
||||||
|
`Expected at least 10 frames with the Open project footer button visible, found ${visibleFrames.length}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Identify settled resting (keyboard closed, lower on screen) and open (keyboard shown, higher on
|
||||||
|
// screen) positions by finding stable runs separated by at least 200px of keyboard height.
|
||||||
|
const minBottom = Math.min(...visibleFrames.map((entry) => entry.bottom));
|
||||||
|
const maxBottom = Math.max(...visibleFrames.map((entry) => entry.bottom));
|
||||||
|
const midpoint = (minBottom + maxBottom) / 2;
|
||||||
|
|
||||||
|
const closedSettled = findSettledValue(
|
||||||
|
bottoms.map((y) => (y !== null && y > midpoint ? y : null)),
|
||||||
|
15,
|
||||||
|
);
|
||||||
|
const openSettled = findSettledValue(
|
||||||
|
bottoms.map((y) => (y !== null && y < midpoint ? y : null)),
|
||||||
|
15,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (closedSettled === null || openSettled === null || closedSettled - openSettled < 200) {
|
||||||
|
throw new Error(
|
||||||
|
`Recording did not capture settled keyboard-closed (${closedSettled}) and keyboard-open (${openSettled}) states`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const maxAllowedBottom =
|
||||||
|
navBarHeight > 0
|
||||||
|
? Math.min(closedSettled + tolerance, height - navBarHeight)
|
||||||
|
: closedSettled + tolerance;
|
||||||
|
const belowNavViolations = visibleFrames.filter((entry) => entry.bottom > maxAllowedBottom);
|
||||||
|
const overshootViolations = visibleFrames.filter((entry) => entry.bottom < openSettled - tolerance);
|
||||||
|
|
||||||
|
if (belowNavViolations.length > 0 || overshootViolations.length > 0) {
|
||||||
|
const summary = [
|
||||||
|
`Sheet footer keyboard transition jank detected in ${videoPath}:`,
|
||||||
|
` settled closed bottom=${closedSettled}px (gap=${height - closedSettled}px), settled open bottom=${openSettled}px (gap=${height - openSettled}px), maxAllowedBottom=${maxAllowedBottom}px`,
|
||||||
|
];
|
||||||
|
if (belowNavViolations.length > 0) {
|
||||||
|
const worst = Math.max(...belowNavViolations.map((entry) => entry.bottom));
|
||||||
|
summary.push(
|
||||||
|
` dropped below safe-area clearance on ${belowNavViolations.length} frames (first=f${belowNavViolations[0].frame}, last=f${belowNavViolations.at(-1).frame}, worst bottom=${worst}px, excess=+${worst - maxAllowedBottom}px)`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (overshootViolations.length > 0) {
|
||||||
|
const worst = Math.min(...overshootViolations.map((entry) => entry.bottom));
|
||||||
|
summary.push(
|
||||||
|
` overshot above open keyboard position on ${overshootViolations.length} frames (first=f${overshootViolations[0].frame}, worst bottom=${worst}px, overshoot=-${openSettled - worst}px)`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
throw new Error(summary.join("\n"));
|
||||||
|
}
|
||||||
|
|
||||||
|
process.stdout.write(
|
||||||
|
`Sheet footer stayed within bounds across ${bottoms.length} frames (${visibleFrames.length} visible): closed=${closedSettled}px, open=${openSettled}px, maxAllowed=${maxAllowedBottom}px, 0 nav-bar overlap frames, 0 overshoot frames\n`,
|
||||||
|
);
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
# Verifies that the Add project bottom sheet footer never flashes behind the Android system
|
||||||
|
# navigation bar on keyboard dismiss or overshoots upward on keyboard open.
|
||||||
|
#
|
||||||
|
# Prerequisites (configured on the test device before running):
|
||||||
|
# - Three-button navigation bar enabled (for example:
|
||||||
|
# `adb shell cmd overlay enable com.android.internal.systemui.navbar.threebutton`).
|
||||||
|
# - Software keyboard enabled when a hardware keyboard is attached (`show_ime_with_hard_keyboard=1`)
|
||||||
|
# and a visible soft keyboard (such as Gboard) selected as the active IME.
|
||||||
|
# - The Add project sheet already open with a connected host so the Open project footer button is
|
||||||
|
# visible.
|
||||||
|
# - `ffmpeg` and `ffprobe` on PATH.
|
||||||
|
|
||||||
|
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
SERIAL="${ANDROID_SERIAL:-$(adb devices | awk '/\tdevice$/ {print $1; exit}')}"
|
||||||
|
OUT_DIR="${SHEET_FOOTER_QA_DIR:-/tmp/paseo-sheet-footer-qa}"
|
||||||
|
VIDEO_PATH="$OUT_DIR/sheet-footer-keyboard.mp4"
|
||||||
|
|
||||||
|
if [ -z "$SERIAL" ]; then
|
||||||
|
echo "No Android device attached. Set ANDROID_SERIAL or start an emulator." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
mkdir -p "$OUT_DIR"
|
||||||
|
|
||||||
|
# Derive tap coordinates and 3-button navigation bar height (48dp) from the active display metrics.
|
||||||
|
SIZE_LINE="$(adb -s "$SERIAL" shell wm size | tail -n 1 | tr -d '\r')"
|
||||||
|
DIMENSIONS="${SIZE_LINE##* }"
|
||||||
|
WIDTH="${DIMENSIONS%x*}"
|
||||||
|
HEIGHT="${DIMENSIONS#*x}"
|
||||||
|
DENSITY_LINE="$(adb -s "$SERIAL" shell wm density | tail -n 1 | tr -d '\r')"
|
||||||
|
DENSITY="${DENSITY_LINE##* }"
|
||||||
|
NAV_BAR_PX="${SHEET_FOOTER_NAV_BAR_PX:-$((48 * DENSITY / 160))}"
|
||||||
|
SEARCH_X=$((WIDTH / 2))
|
||||||
|
SEARCH_Y=$((HEIGHT * 34 / 100))
|
||||||
|
|
||||||
|
adb -s "$SERIAL" shell rm -f /sdcard/sheet-footer-keyboard.mp4
|
||||||
|
adb -s "$SERIAL" shell screenrecord --time-limit 9 --bit-rate 8000000 /sdcard/sheet-footer-keyboard.mp4 &
|
||||||
|
REC_PID=$!
|
||||||
|
|
||||||
|
sleep 0.8
|
||||||
|
adb -s "$SERIAL" shell input tap "$SEARCH_X" "$SEARCH_Y"
|
||||||
|
sleep 1.8
|
||||||
|
adb -s "$SERIAL" shell input keyevent 4
|
||||||
|
sleep 1.8
|
||||||
|
adb -s "$SERIAL" shell input tap "$SEARCH_X" "$SEARCH_Y"
|
||||||
|
sleep 1.8
|
||||||
|
adb -s "$SERIAL" shell input keyevent 4
|
||||||
|
wait "$REC_PID" || true
|
||||||
|
|
||||||
|
adb -s "$SERIAL" pull /sdcard/sheet-footer-keyboard.mp4 "$VIDEO_PATH" >/dev/null
|
||||||
|
node "$SCRIPT_DIR/assert-sheet-footer-keyboard.mjs" "$VIDEO_PATH" 4 "$NAV_BAR_PX"
|
||||||
@@ -15,8 +15,8 @@ press "id=\"model-provider-${PROVIDER_ID}\""
|
|||||||
wait "id=\"compact-model-list\"" 3000
|
wait "id=\"compact-model-list\"" 3000
|
||||||
# The row's profile action sits inside Android's independent scroll viewport.
|
# The row's profile action sits inside Android's independent scroll viewport.
|
||||||
press "id=\"model-create-profile-${PROVIDER_ID}-${PROFILE_MODEL_ID}\""
|
press "id=\"model-create-profile-${PROVIDER_ID}-${PROFILE_MODEL_ID}\""
|
||||||
wait "text=\"Add agent profile\"" 5000
|
wait "id=\"model-profile-created-toast\"" 5000
|
||||||
# Closing the form keeps the remembered model: the tap did not also select the row.
|
# Undo removes the created profile after selecting the model and closing the picker.
|
||||||
back
|
press "id=\"model-profile-created-undo\""
|
||||||
wait "id=\"combined-model-selector\" label=\"Select model (${MODEL_LABEL})\"" 3000
|
wait "id=\"combined-model-selector\"" 3000
|
||||||
close
|
close
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
// Start on Settings > Host > Pair device with relay enabled in the Android app.
|
// Start on Settings > Host > Devices with relay enabled in the Android app.
|
||||||
// node packages/app/e2e/mobile/pair-device/android.mjs <agent-device-session>
|
// node packages/app/e2e/mobile/pair-device/android.mjs <agent-device-session>
|
||||||
import assert from "node:assert/strict";
|
import assert from "node:assert/strict";
|
||||||
import { execFileSync } from "node:child_process";
|
import { execFileSync } from "node:child_process";
|
||||||
@@ -13,11 +13,7 @@ function ad(...args) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
ad(
|
ad("press", 'label="Relay"', "--settle");
|
||||||
"press",
|
|
||||||
'label="Pair a device, Scan a QR code or copy a link to connect your phone to this host"',
|
|
||||||
"--settle",
|
|
||||||
);
|
|
||||||
ad("wait", "text", "Pairing QR code", "10000");
|
ad("wait", "text", "Pairing QR code", "10000");
|
||||||
const { data } = JSON.parse(ad("snapshot", "-i", "--json"));
|
const { data } = JSON.parse(ad("snapshot", "-i", "--json"));
|
||||||
const sheet = data.nodes.find((node) => node.label === "Bottom Sheet");
|
const sheet = data.nodes.find((node) => node.label === "Bottom Sheet");
|
||||||
|
|||||||
@@ -142,8 +142,22 @@ export async function openAgentProfileSettings(page: Page): Promise<void> {
|
|||||||
await gotoAppShell(page);
|
await gotoAppShell(page);
|
||||||
await openSettings(page);
|
await openSettings(page);
|
||||||
await openSettingsHost(page, serverId);
|
await openSettingsHost(page, serverId);
|
||||||
await page.getByRole("button", { name: "Agents", exact: true }).click();
|
await page.getByRole("button", { name: "Agent profiles", exact: true }).click();
|
||||||
await expectAppRoute(page, buildSettingsHostSectionRoute(serverId, "agents"));
|
await expectAppRoute(page, buildSettingsHostSectionRoute(serverId, "agent-profiles"));
|
||||||
|
await expect(page.getByTestId("agent-profiles-card")).toBeVisible({ timeout: 30_000 });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reach agent profiles on a compact viewport so Open project -> Settings -> Agent profiles are pushed. */
|
||||||
|
export async function openCompactAgentProfileSettings(page: Page): Promise<void> {
|
||||||
|
const serverId = getServerId();
|
||||||
|
await gotoAppShell(page);
|
||||||
|
await page.getByRole("button", { name: "Open menu", exact: true }).click();
|
||||||
|
const settingsButton = page.locator('[data-testid="sidebar-settings"]:visible').first();
|
||||||
|
await expect(settingsButton).toBeVisible({ timeout: 30_000 });
|
||||||
|
await settingsButton.click();
|
||||||
|
await expect(page).toHaveURL(/\/settings(?:\?|$)/, { timeout: 30_000 });
|
||||||
|
await page.getByRole("button", { name: "Agent profiles", exact: true }).click();
|
||||||
|
await expectAppRoute(page, buildSettingsHostSectionRoute(serverId, "agent-profiles"));
|
||||||
await expect(page.getByTestId("agent-profiles-card")).toBeVisible({ timeout: 30_000 });
|
await expect(page.getByTestId("agent-profiles-card")).toBeVisible({ timeout: 30_000 });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -156,7 +170,9 @@ export async function expectNoAgentProfiles(page: Page): Promise<void> {
|
|||||||
// ─── Settings: the profile list ────────────────────────────────────────────
|
// ─── Settings: the profile list ────────────────────────────────────────────
|
||||||
|
|
||||||
export function agentProfileRow(page: Page, name: string): Locator {
|
export function agentProfileRow(page: Page, name: string): Locator {
|
||||||
return page.locator('[data-testid^="agent-profile-row-"]').filter({ hasText: name });
|
return page
|
||||||
|
.locator('[data-testid^="agent-profile-row-"]')
|
||||||
|
.filter({ has: page.getByText(name, { exact: true }) });
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function expectAgentProfile(
|
export async function expectAgentProfile(
|
||||||
@@ -165,7 +181,9 @@ export async function expectAgentProfile(
|
|||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const row = agentProfileRow(page, expected.name);
|
const row = agentProfileRow(page, expected.name);
|
||||||
await expect(row).toBeVisible({ timeout: 30_000 });
|
await expect(row).toBeVisible({ timeout: 30_000 });
|
||||||
await expect(row.getByText(expected.tags.join(" · "), { exact: true })).toBeVisible();
|
for (const tag of expected.tags) {
|
||||||
|
await expect(row).toContainText(tag);
|
||||||
|
}
|
||||||
if (expected.notes !== undefined) {
|
if (expected.notes !== undefined) {
|
||||||
await expect(row.getByText(expected.notes, { exact: true })).toBeVisible();
|
await expect(row.getByText(expected.notes, { exact: true })).toBeVisible();
|
||||||
}
|
}
|
||||||
@@ -177,7 +195,7 @@ export async function expectAgentProfileTagsGone(
|
|||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const row = agentProfileRow(page, input.name);
|
const row = agentProfileRow(page, input.name);
|
||||||
for (const tag of input.tags) {
|
for (const tag of input.tags) {
|
||||||
await expect(row.getByText(tag, { exact: true })).toHaveCount(0);
|
await expect(row).not.toContainText(tag);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -196,12 +214,22 @@ export async function expectAgentProfileOrder(page: Page, names: string[]): Prom
|
|||||||
.toEqual(names);
|
.toEqual(names);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function openRowActionMenu(page: Page, name: string): Promise<void> {
|
||||||
|
const row = agentProfileRow(page, name);
|
||||||
|
await row.hover();
|
||||||
|
const trigger = row.locator('[data-testid^="agent-profile-menu-"]');
|
||||||
|
await expect(trigger).toBeVisible({ timeout: 15_000 });
|
||||||
|
await trigger.click();
|
||||||
|
}
|
||||||
|
|
||||||
export async function moveAgentProfileUp(page: Page, name: string): Promise<void> {
|
export async function moveAgentProfileUp(page: Page, name: string): Promise<void> {
|
||||||
await agentProfileRow(page, name).getByRole("button", { name: "Move up", exact: true }).click();
|
await openRowActionMenu(page, name);
|
||||||
|
await page.getByRole("menuitem", { name: "Move up", exact: true }).click();
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function moveAgentProfileDown(page: Page, name: string): Promise<void> {
|
export async function moveAgentProfileDown(page: Page, name: string): Promise<void> {
|
||||||
await agentProfileRow(page, name).getByRole("button", { name: "Move down", exact: true }).click();
|
await openRowActionMenu(page, name);
|
||||||
|
await page.getByRole("menuitem", { name: "Move down", exact: true }).click();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -215,12 +243,13 @@ export async function removeAgentProfile(page: Page, name: string): Promise<void
|
|||||||
await dialog.accept();
|
await dialog.accept();
|
||||||
return message;
|
return message;
|
||||||
});
|
});
|
||||||
await agentProfileRow(page, name).getByRole("button", { name: "Remove", exact: true }).click();
|
await openRowActionMenu(page, name);
|
||||||
|
await page.getByRole("menuitem", { name: "Remove", exact: true }).click();
|
||||||
expect(await dialogMessage).toContain(`Remove "${name}"?`);
|
expect(await dialogMessage).toContain(`Remove "${name}"?`);
|
||||||
await expect(agentProfileRow(page, name)).toHaveCount(0, { timeout: 30_000 });
|
await expect(agentProfileRow(page, name)).toHaveCount(0, { timeout: 30_000 });
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Settings: the edit modal ──────────────────────────────────────────────
|
// ─── Settings: the inspector drawer / edit sheet ───────────────────────────
|
||||||
|
|
||||||
export interface AgentProfileDraft {
|
export interface AgentProfileDraft {
|
||||||
name?: string;
|
name?: string;
|
||||||
@@ -231,62 +260,96 @@ export interface AgentProfileDraft {
|
|||||||
notes?: string;
|
notes?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
function editModal(page: Page): Locator {
|
function editSurface(page: Page): Locator {
|
||||||
return page.getByTestId("agent-profile-edit-modal");
|
return page.locator(
|
||||||
|
'[data-testid="agent-profile-drawer"], [data-testid="agent-profile-edit-modal"]',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function chooseSelectFieldOption(
|
async function chooseSelectFieldOption(
|
||||||
page: Page,
|
page: Page,
|
||||||
input: { field: "provider" | "model" | "mode" | "thinking"; option: string },
|
input: { field: "model" | "mode" | "thinking"; option: string },
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
await editModal(page).getByTestId(`agent-profile-${input.field}-trigger`).click();
|
await editSurface(page).getByTestId(`agent-profile-${input.field}-trigger`).click();
|
||||||
const option = page
|
const option = page
|
||||||
.getByTestId("combobox-desktop-container")
|
.getByTestId("combobox-desktop-container")
|
||||||
.getByRole("button", { name: input.option, exact: true });
|
.getByRole("button", { name: input.option, exact: true });
|
||||||
await expect(option).toBeVisible({ timeout: 30_000 });
|
await expect(option).toBeVisible({ timeout: 30_000 });
|
||||||
await option.click();
|
await option.click();
|
||||||
await expect(
|
|
||||||
page.getByRole("button", { name: `${capitalize(input.field)} (${input.option})` }),
|
|
||||||
).toBeVisible({ timeout: 30_000 });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function capitalize(value: string): string {
|
async function ensureCustomizeExpanded(surface: Locator): Promise<void> {
|
||||||
return value.charAt(0).toUpperCase() + value.slice(1);
|
const toggle = surface.getByTestId("agent-profile-customize-toggle");
|
||||||
|
if ((await toggle.count()) > 0 && (await toggle.isVisible())) {
|
||||||
|
await toggle.click();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function chooseProfileModel(
|
||||||
|
page: Page,
|
||||||
|
input: { provider?: string; model?: string },
|
||||||
|
): Promise<void> {
|
||||||
|
await editSurface(page).getByTestId("agent-profile-model-trigger").click();
|
||||||
|
const container = page.getByTestId("combobox-desktop-container");
|
||||||
|
await expect(container).toBeVisible({ timeout: 30_000 });
|
||||||
|
if (input.provider) {
|
||||||
|
const providerRow = container.getByRole("button", {
|
||||||
|
name: new RegExp(escapeForRegex(input.provider)),
|
||||||
|
});
|
||||||
|
if ((await providerRow.count()) > 0 && (await providerRow.first().isVisible())) {
|
||||||
|
await providerRow.first().click();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const targetLabel = input.model ?? input.provider;
|
||||||
|
if (targetLabel) {
|
||||||
|
const option = container
|
||||||
|
.getByRole("button", { name: new RegExp(escapeForRegex(targetLabel)) })
|
||||||
|
.first();
|
||||||
|
await expect(option).toBeVisible({ timeout: 30_000 });
|
||||||
|
await option.click();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function fillAgentProfileForm(page: Page, draft: AgentProfileDraft): Promise<void> {
|
async function fillAgentProfileForm(page: Page, draft: AgentProfileDraft): Promise<void> {
|
||||||
const modal = editModal(page);
|
const surface = editSurface(page);
|
||||||
|
// Model first: CombinedModelSelector sets provider + model and auto-suggests defaults.
|
||||||
|
if (draft.model !== undefined || draft.provider !== undefined) {
|
||||||
|
await chooseProfileModel(page, { provider: draft.provider, model: draft.model });
|
||||||
|
}
|
||||||
if (draft.name !== undefined) {
|
if (draft.name !== undefined) {
|
||||||
await modal.getByRole("textbox", { name: "Name", exact: true }).fill(draft.name);
|
await surface.getByRole("textbox", { name: "Name", exact: true }).fill(draft.name);
|
||||||
}
|
}
|
||||||
// Provider first: it resets every provider-scoped field below it.
|
if (draft.thinking !== undefined || draft.mode !== undefined || draft.notes !== undefined) {
|
||||||
if (draft.provider !== undefined) {
|
await ensureCustomizeExpanded(surface);
|
||||||
await chooseSelectFieldOption(page, { field: "provider", option: draft.provider });
|
|
||||||
}
|
|
||||||
// Thinking after model: thinking levels hang off the model, and switching the
|
|
||||||
// model drops a level the new one does not offer.
|
|
||||||
if (draft.model !== undefined) {
|
|
||||||
await chooseSelectFieldOption(page, { field: "model", option: draft.model });
|
|
||||||
}
|
|
||||||
if (draft.thinking !== undefined) {
|
|
||||||
await chooseSelectFieldOption(page, { field: "thinking", option: draft.thinking });
|
|
||||||
}
|
}
|
||||||
if (draft.mode !== undefined) {
|
if (draft.mode !== undefined) {
|
||||||
await chooseSelectFieldOption(page, { field: "mode", option: draft.mode });
|
await chooseSelectFieldOption(page, { field: "mode", option: draft.mode });
|
||||||
}
|
}
|
||||||
|
if (draft.thinking !== undefined) {
|
||||||
|
const thinkingContainer = surface.getByTestId("agent-profile-thinking-field");
|
||||||
|
const segmentButton = thinkingContainer.getByRole("button", {
|
||||||
|
name: draft.thinking,
|
||||||
|
exact: true,
|
||||||
|
});
|
||||||
|
if ((await segmentButton.count()) > 0) {
|
||||||
|
await segmentButton.click();
|
||||||
|
} else {
|
||||||
|
await chooseSelectFieldOption(page, { field: "thinking", option: draft.thinking });
|
||||||
|
}
|
||||||
|
}
|
||||||
if (draft.notes !== undefined) {
|
if (draft.notes !== undefined) {
|
||||||
await modal.getByRole("textbox", { name: "When to use", exact: true }).fill(draft.notes);
|
await surface.getByRole("textbox", { name: "When to use", exact: true }).fill(draft.notes);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function saveAgentProfile(page: Page): Promise<void> {
|
async function saveAgentProfile(page: Page): Promise<void> {
|
||||||
await editModal(page).getByRole("button", { name: "Save", exact: true }).click();
|
await page.getByTestId("agent-profile-save-button").click();
|
||||||
await expect(editModal(page)).toHaveCount(0, { timeout: 30_000 });
|
await expect(editSurface(page)).toHaveCount(0, { timeout: 30_000 });
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function createAgentProfile(page: Page, draft: AgentProfileDraft): Promise<void> {
|
export async function createAgentProfile(page: Page, draft: AgentProfileDraft): Promise<void> {
|
||||||
await page.getByRole("button", { name: "Add agent profile", exact: true }).click();
|
await page.getByTestId("agent-profiles-add-button").click();
|
||||||
await expect(editModal(page)).toBeVisible({ timeout: 30_000 });
|
await expect(editSurface(page)).toBeVisible({ timeout: 30_000 });
|
||||||
await fillAgentProfileForm(page, draft);
|
await fillAgentProfileForm(page, draft);
|
||||||
await saveAgentProfile(page);
|
await saveAgentProfile(page);
|
||||||
}
|
}
|
||||||
@@ -299,7 +362,7 @@ export async function createAgentProfileFromEmptyState(
|
|||||||
.getByTestId("agent-profiles-card")
|
.getByTestId("agent-profiles-card")
|
||||||
.getByRole("button", { name: "New profile", exact: true })
|
.getByRole("button", { name: "New profile", exact: true })
|
||||||
.click();
|
.click();
|
||||||
await expect(editModal(page)).toBeVisible({ timeout: 30_000 });
|
await expect(editSurface(page)).toBeVisible({ timeout: 30_000 });
|
||||||
await fillAgentProfileForm(page, draft);
|
await fillAgentProfileForm(page, draft);
|
||||||
await saveAgentProfile(page);
|
await saveAgentProfile(page);
|
||||||
}
|
}
|
||||||
@@ -309,46 +372,183 @@ export async function editAgentProfile(
|
|||||||
name: string,
|
name: string,
|
||||||
changes: AgentProfileDraft,
|
changes: AgentProfileDraft,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
await agentProfileRow(page, name)
|
await agentProfileRow(page, name).click();
|
||||||
.getByRole("button", { name: "Edit profile", exact: true })
|
await expect(editSurface(page)).toBeVisible({ timeout: 30_000 });
|
||||||
.click();
|
|
||||||
await expect(editModal(page)).toBeVisible({ timeout: 30_000 });
|
|
||||||
await fillAgentProfileForm(page, changes);
|
await fillAgentProfileForm(page, changes);
|
||||||
await saveAgentProfile(page);
|
await saveAgentProfile(page);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Opens the modal for a profile purely to read back what it stored. */
|
export async function openAgentProfileEditor(page: Page, name: string): Promise<void> {
|
||||||
|
await agentProfileRow(page, name).click();
|
||||||
|
await expect(editSurface(page)).toBeVisible({ timeout: 30_000 });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function openCreateAgentProfileEditor(page: Page): Promise<void> {
|
||||||
|
await page.getByTestId("agent-profiles-add-button").click();
|
||||||
|
await expect(editSurface(page)).toBeVisible({ timeout: 30_000 });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fillAgentProfileName(page: Page, name: string): Promise<void> {
|
||||||
|
await page.getByRole("textbox", { name: "Name", exact: true }).fill(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function expectAgentProfileNameDraft(page: Page, name: string): Promise<void> {
|
||||||
|
await expect(page.getByRole("textbox", { name: "Name", exact: true })).toHaveValue(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function toggleAgentProfileCustomize(page: Page): Promise<void> {
|
||||||
|
await page.getByTestId("agent-profile-customize-toggle").click();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fillAgentProfileNotes(page: Page, notes: string): Promise<void> {
|
||||||
|
await page.getByRole("textbox", { name: "When to use", exact: true }).fill(notes);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function expectAgentProfileNotesDraft(page: Page, notes: string): Promise<void> {
|
||||||
|
await expect(page.getByRole("textbox", { name: "When to use", exact: true })).toHaveValue(notes);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function saveOpenAgentProfile(page: Page): Promise<void> {
|
||||||
|
await saveAgentProfile(page);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function duplicateOpenAgentProfileWithConfirm(
|
||||||
|
page: Page,
|
||||||
|
decision: "accept" | "dismiss",
|
||||||
|
): Promise<void> {
|
||||||
|
const dialogMessage = page.waitForEvent("dialog").then(async (dialog) => {
|
||||||
|
const message = dialog.message();
|
||||||
|
if (decision === "accept") {
|
||||||
|
await dialog.accept();
|
||||||
|
} else {
|
||||||
|
await dialog.dismiss();
|
||||||
|
}
|
||||||
|
return message;
|
||||||
|
});
|
||||||
|
await page.getByTestId("agent-profile-drawer-more").click();
|
||||||
|
await page.getByTestId("agent-profile-drawer-duplicate").click();
|
||||||
|
expect(await dialogMessage).toMatch(/discard|unsaved/i);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function openEditProfileFromModelRow(
|
||||||
|
page: Page,
|
||||||
|
input: { provider: string; modelId: string },
|
||||||
|
): Promise<void> {
|
||||||
|
const row = modelRow(page, input);
|
||||||
|
await row.hover();
|
||||||
|
const editButton = pickerViewport(page).getByTestId(
|
||||||
|
`model-edit-profile-${input.provider}-${input.modelId}`,
|
||||||
|
);
|
||||||
|
await expect(editButton).toBeVisible({ timeout: 30_000 });
|
||||||
|
await editButton.click();
|
||||||
|
await expect(page.getByTestId("agent-profile-edit-modal")).toBeVisible({ timeout: 30_000 });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function removeOpenModalAgentProfileWithConfirm(
|
||||||
|
page: Page,
|
||||||
|
decision: "accept" | "dismiss",
|
||||||
|
): Promise<void> {
|
||||||
|
const dialogMessage = page.waitForEvent("dialog").then(async (dialog) => {
|
||||||
|
const message = dialog.message();
|
||||||
|
if (decision === "accept") {
|
||||||
|
await dialog.accept();
|
||||||
|
} else {
|
||||||
|
await dialog.dismiss();
|
||||||
|
}
|
||||||
|
return message;
|
||||||
|
});
|
||||||
|
await page.getByTestId("agent-profile-modal-remove-button").click();
|
||||||
|
expect(await dialogMessage).toMatch(/remove/i);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function switchSettingsSectionWithConfirm(
|
||||||
|
page: Page,
|
||||||
|
sectionName: string,
|
||||||
|
decision: "accept" | "dismiss",
|
||||||
|
): Promise<void> {
|
||||||
|
const dialogMessage = page.waitForEvent("dialog").then(async (dialog) => {
|
||||||
|
const message = dialog.message();
|
||||||
|
if (decision === "accept") {
|
||||||
|
await dialog.accept();
|
||||||
|
} else {
|
||||||
|
await dialog.dismiss();
|
||||||
|
}
|
||||||
|
return message;
|
||||||
|
});
|
||||||
|
await page.getByRole("button", { name: sectionName, exact: true }).click();
|
||||||
|
expect(await dialogMessage).toMatch(/discard|unsaved/i);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function browserBackWithConfirm(
|
||||||
|
page: Page,
|
||||||
|
decision: "accept" | "dismiss",
|
||||||
|
): Promise<void> {
|
||||||
|
const dialogMessage = page.waitForEvent("dialog").then(async (dialog) => {
|
||||||
|
const message = dialog.message();
|
||||||
|
if (decision === "accept") {
|
||||||
|
await dialog.accept();
|
||||||
|
} else {
|
||||||
|
await dialog.dismiss();
|
||||||
|
}
|
||||||
|
return message;
|
||||||
|
});
|
||||||
|
await page.goBack();
|
||||||
|
expect(await dialogMessage).toMatch(/discard|unsaved/i);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function browserHistoryJumpWithConfirm(
|
||||||
|
page: Page,
|
||||||
|
delta: number,
|
||||||
|
decision: "accept" | "dismiss",
|
||||||
|
): Promise<void> {
|
||||||
|
const dialogMessage = page.waitForEvent("dialog").then(async (dialog) => {
|
||||||
|
const message = dialog.message();
|
||||||
|
if (decision === "accept") {
|
||||||
|
await dialog.accept();
|
||||||
|
} else {
|
||||||
|
await dialog.dismiss();
|
||||||
|
}
|
||||||
|
return message;
|
||||||
|
});
|
||||||
|
await page.evaluate((step) => window.history.go(step), delta);
|
||||||
|
expect(await dialogMessage).toMatch(/discard|unsaved/i);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Opens the inspector for a profile purely to read back what it stored. */
|
||||||
export async function expectAgentProfileForm(
|
export async function expectAgentProfileForm(
|
||||||
page: Page,
|
page: Page,
|
||||||
name: string,
|
name: string,
|
||||||
expected: { provider?: string; model?: string; mode?: string; notes?: string },
|
expected: { provider?: string; model?: string; mode?: string; notes?: string },
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
await agentProfileRow(page, name)
|
await agentProfileRow(page, name).click();
|
||||||
.getByRole("button", { name: "Edit profile", exact: true })
|
const surface = editSurface(page);
|
||||||
.click();
|
await expect(surface).toBeVisible({ timeout: 30_000 });
|
||||||
const modal = editModal(page);
|
await expect(surface.getByRole("textbox", { name: "Name", exact: true })).toHaveValue(name);
|
||||||
await expect(modal).toBeVisible({ timeout: 30_000 });
|
const notesHint = surface.getByTestId("agent-profile-notes-field-hint");
|
||||||
await expect(modal.getByRole("textbox", { name: "Name", exact: true })).toHaveValue(name);
|
await expect(notesHint).toHaveText("Tells agents when to pick this profile");
|
||||||
const notesHint = modal.getByTestId("agent-profile-notes-field-hint");
|
|
||||||
await expect(notesHint).toHaveText(
|
|
||||||
"Helps agents choose this profile when starting another agent.",
|
|
||||||
);
|
|
||||||
expect(await notesHint.evaluate((element) => getComputedStyle(element).webkitLineClamp)).not.toBe(
|
expect(await notesHint.evaluate((element) => getComputedStyle(element).webkitLineClamp)).not.toBe(
|
||||||
"1",
|
"1",
|
||||||
);
|
);
|
||||||
for (const [field, value] of Object.entries(expected)) {
|
if (expected.model) {
|
||||||
if (field === "notes") {
|
await expect(surface.getByTestId("agent-profile-model-trigger")).toContainText(expected.model);
|
||||||
await expect(modal.getByRole("textbox", { name: "When to use", exact: true })).toHaveValue(
|
} else if (expected.provider) {
|
||||||
value,
|
await expect(surface.getByTestId("agent-profile-model-trigger")).toContainText(
|
||||||
);
|
expected.provider,
|
||||||
continue;
|
);
|
||||||
}
|
|
||||||
await expect(
|
|
||||||
modal.getByRole("button", { name: `${capitalize(field)} (${value})` }),
|
|
||||||
).toBeVisible({ timeout: 30_000 });
|
|
||||||
}
|
}
|
||||||
await modal.getByRole("button", { name: "Cancel", exact: true }).click();
|
if (expected.provider) {
|
||||||
await expect(editModal(page)).toHaveCount(0, { timeout: 30_000 });
|
await expect(surface).toContainText(expected.provider);
|
||||||
|
}
|
||||||
|
if (expected.mode) {
|
||||||
|
await expect(surface.getByTestId("agent-profile-mode-trigger")).toContainText(expected.mode);
|
||||||
|
}
|
||||||
|
if (expected.notes !== undefined) {
|
||||||
|
await expect(surface.getByRole("textbox", { name: "When to use", exact: true })).toHaveValue(
|
||||||
|
expected.notes,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
await surface.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||||
|
await expect(editSurface(page)).toHaveCount(0, { timeout: 30_000 });
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── The model picker ──────────────────────────────────────────────────────
|
// ─── The model picker ──────────────────────────────────────────────────────
|
||||||
@@ -535,7 +735,10 @@ export async function expectModelRowProfileActionBesideRow(
|
|||||||
await expect(row.getByRole("button")).toHaveCount(0);
|
await expect(row.getByRole("button")).toHaveCount(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The hover-revealed plus on an unprofiled model row opens a seeded profile form. */
|
/**
|
||||||
|
* The hover-revealed plus on an unprofiled model row saves the profile,
|
||||||
|
* selects the model immediately, closes the picker, and surfaces an Edit / Undo toast.
|
||||||
|
*/
|
||||||
export async function expectCreateProfileFromModelRow(
|
export async function expectCreateProfileFromModelRow(
|
||||||
page: Page,
|
page: Page,
|
||||||
input: { provider: string; modelId: string; modelLabel: string },
|
input: { provider: string; modelId: string; modelLabel: string },
|
||||||
@@ -548,14 +751,14 @@ export async function expectCreateProfileFromModelRow(
|
|||||||
await modelRow(page, input).hover();
|
await modelRow(page, input).hover();
|
||||||
await expect(action).toHaveCSS("pointer-events", "auto");
|
await expect(action).toHaveCSS("pointer-events", "auto");
|
||||||
await action.click();
|
await action.click();
|
||||||
const modal = editModal(page);
|
|
||||||
await expect(modal).toBeVisible({ timeout: 30_000 });
|
const toast = page.getByTestId("model-profile-created-toast");
|
||||||
await expect(modal.getByRole("textbox", { name: "Name", exact: true })).toHaveValue(
|
await expect(toast).toBeVisible({ timeout: 30_000 });
|
||||||
input.modelLabel,
|
await expect(toast).toContainText(input.modelLabel);
|
||||||
);
|
|
||||||
await expect(modal.getByRole("button", { name: `Model (${input.modelLabel})` })).toBeVisible();
|
// Undo removes the newly saved profile from the toast.
|
||||||
await modal.getByRole("button", { name: "Cancel", exact: true }).click();
|
await toast.getByTestId("model-profile-created-undo").click();
|
||||||
await expect(modal).toHaveCount(0, { timeout: 30_000 });
|
await expect(toast).toHaveCount(0, { timeout: 30_000 });
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function selectModelRow(
|
export async function selectModelRow(
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { promisify } from "node:util";
|
import { promisify } from "node:util";
|
||||||
|
import { once } from "node:events";
|
||||||
import {
|
import {
|
||||||
spawn,
|
spawn,
|
||||||
execFile,
|
execFile,
|
||||||
@@ -11,6 +12,7 @@ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
|||||||
import net from "node:net";
|
import net from "node:net";
|
||||||
import { tmpdir } from "node:os";
|
import { tmpdir } from "node:os";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
|
import { WebSocket } from "ws";
|
||||||
import { withDisabledE2ESpeechEnv } from "./speech-env";
|
import { withDisabledE2ESpeechEnv } from "./speech-env";
|
||||||
import { killProcessTree, spawnTsx } from "./spawn-node";
|
import { killProcessTree, spawnTsx } from "./spawn-node";
|
||||||
|
|
||||||
@@ -64,12 +66,14 @@ export async function getAvailableHostDaemonPort(): Promise<number> {
|
|||||||
* Resolves once this daemon answers on its port. An open TCP port is not
|
* Resolves once this daemon answers on its port. An open TCP port is not
|
||||||
* enough: the port is released before the daemon binds it, and whatever takes
|
* enough: the port is released before the daemon binds it, and whatever takes
|
||||||
* it in between also accepts connections while the daemon exits with
|
* it in between also accepts connections while the daemon exits with
|
||||||
* EADDRINUSE. Only the daemon's own status reports its server id.
|
* EADDRINUSE. Only the daemon's own status reports its server id. Published
|
||||||
|
* daemons can serve status before they accept WebSocket upgrades.
|
||||||
*/
|
*/
|
||||||
async function waitForServer(
|
async function waitForServer(
|
||||||
port: number,
|
port: number,
|
||||||
child: ChildProcess,
|
child: ChildProcess,
|
||||||
identity: { serverId: string; paseoHome: string },
|
identity: { serverId: string; paseoHome: string },
|
||||||
|
published: boolean,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const deadline = Date.now() + 90_000;
|
const deadline = Date.now() + 90_000;
|
||||||
let lastError: unknown = null;
|
let lastError: unknown = null;
|
||||||
@@ -82,7 +86,10 @@ async function waitForServer(
|
|||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const serverId = await readServerId(port, identity.paseoHome);
|
const serverId = await readServerId(port, identity.paseoHome);
|
||||||
if (serverId === identity.serverId) return;
|
if (serverId === identity.serverId) {
|
||||||
|
if (published) await checkWebSocketUpgrade(port);
|
||||||
|
return;
|
||||||
|
}
|
||||||
lastError = new Error(`Port ${port} is served by ${serverId}, not ${identity.serverId}`);
|
lastError = new Error(`Port ${port} is served by ${serverId}, not ${identity.serverId}`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
lastError = error;
|
lastError = error;
|
||||||
@@ -97,6 +104,12 @@ async function waitForServer(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function checkWebSocketUpgrade(port: number): Promise<void> {
|
||||||
|
const socket = new WebSocket(`ws://127.0.0.1:${port}/ws`, { handshakeTimeout: 1_000 });
|
||||||
|
await once(socket, "open");
|
||||||
|
socket.close();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Reads the server id from the daemon's status route. The route needs a bearer
|
* Reads the server id from the daemon's status route. The route needs a bearer
|
||||||
* on a password-protected daemon; the daemon accepts the local credential it
|
* on a password-protected daemon; the daemon accepts the local credential it
|
||||||
@@ -246,7 +259,7 @@ export async function startIsolatedHostDaemon(
|
|||||||
});
|
});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await waitForServer(port, spawned, { serverId, paseoHome });
|
await waitForServer(port, spawned, { serverId, paseoHome }, Boolean(publishedPackageRoot));
|
||||||
return spawned;
|
return spawned;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
|
|||||||
@@ -243,6 +243,14 @@ export async function openNewWorkspaceProjectPickerWithShortcut(
|
|||||||
await expect(searchInput).toBeFocused();
|
await expect(searchInput).toBeFocused();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function chooseProjectWithKeyboard(page: Page, projectName: string): Promise<void> {
|
||||||
|
const searchInput = page.getByPlaceholder("Search projects");
|
||||||
|
await expect(searchInput).toBeFocused({ timeout: 30_000 });
|
||||||
|
await page.keyboard.type(projectName);
|
||||||
|
await page.keyboard.press("Enter");
|
||||||
|
await expect(searchInput).toBeHidden({ timeout: 10_000 });
|
||||||
|
}
|
||||||
|
|
||||||
export async function expectNewWorkspaceProjectSelected(
|
export async function expectNewWorkspaceProjectSelected(
|
||||||
page: Page,
|
page: Page,
|
||||||
projectDisplayName: string,
|
projectDisplayName: string,
|
||||||
|
|||||||
@@ -161,7 +161,7 @@ export async function finishSetup(page: Page): Promise<void> {
|
|||||||
/** Opens the Phone step's Relay row: the pair device modal, over setup. */
|
/** Opens the Phone step's Relay row: the pair device modal, over setup. */
|
||||||
export async function openRelayPairingFromSetup(page: Page): Promise<Locator> {
|
export async function openRelayPairingFromSetup(page: Page): Promise<Locator> {
|
||||||
await setupModal(page).getByRole("button", { name: "Relay", exact: true }).click();
|
await setupModal(page).getByRole("button", { name: "Relay", exact: true }).click();
|
||||||
const pairing = page.getByTestId("onboarding-pair-device-card");
|
const pairing = page.getByTestId("devices-relay-pairing");
|
||||||
await expect(pairing).toBeVisible();
|
await expect(pairing).toBeVisible();
|
||||||
return pairing;
|
return pairing;
|
||||||
}
|
}
|
||||||
@@ -171,20 +171,9 @@ export async function closeRelayPairing(pairing: Locator): Promise<void> {
|
|||||||
await expect(pairing).toHaveCount(0);
|
await expect(pairing).toHaveCount(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Clicks the Phone step's Tailscale row and returns the docs page it opened. */
|
export async function expectTailscaleSwitchDisabled(page: Page): Promise<void> {
|
||||||
export async function openTailscaleDocsFromSetup(page: Page): Promise<string> {
|
const setup = setupModal(page);
|
||||||
await page
|
await expect(setup.getByRole("switch", { name: "Tailscale", exact: true })).toBeDisabled();
|
||||||
.context()
|
|
||||||
.route("https://paseo.sh/**", (route) =>
|
|
||||||
route.fulfill({ contentType: "text/html", body: "<title>Paseo docs</title>" }),
|
|
||||||
);
|
|
||||||
const popup = page.waitForEvent("popup");
|
|
||||||
await setupModal(page).getByRole("link", { name: "Tailscale, Docs", exact: true }).click();
|
|
||||||
const docs = await popup;
|
|
||||||
await docs.waitForLoadState("domcontentloaded");
|
|
||||||
const url = docs.url();
|
|
||||||
await docs.close();
|
|
||||||
return url;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SetupHost {
|
export interface SetupHost {
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ import {
|
|||||||
selectSettingsHost,
|
selectSettingsHost,
|
||||||
} from "./settings";
|
} from "./settings";
|
||||||
import { expectAppRoute } from "./route-assertions";
|
import { expectAppRoute } from "./route-assertions";
|
||||||
|
import { wsRoutePatternForPort } from "./daemon-port";
|
||||||
|
import { goToSetupStep, showSetupAgainFromSettings } from "./onboarding";
|
||||||
import { buildSettingsHostSectionRoute } from "@/utils/host-routes";
|
import { buildSettingsHostSectionRoute } from "@/utils/host-routes";
|
||||||
|
|
||||||
interface PairingHostInput {
|
interface PairingHostInput {
|
||||||
@@ -60,9 +62,33 @@ export async function prepareLocalPairingHost(
|
|||||||
await preparePairingHost(page, daemon, additionalHosts);
|
await preparePairingHost(page, daemon, additionalHosts);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type PairingHost =
|
||||||
|
| Pick<IsolatedHostDaemon, "serverId" | "port">
|
||||||
|
| Pick<OutdatedDaemon, "serverId" | "endpoint">;
|
||||||
|
|
||||||
export async function preparePairingHost(
|
export async function preparePairingHost(
|
||||||
page: Page,
|
page: Page,
|
||||||
daemon: IsolatedHostDaemon | OutdatedDaemon,
|
daemon: PairingHost,
|
||||||
|
additionalHosts: PairingHostInput[] = [],
|
||||||
|
): Promise<void> {
|
||||||
|
await openAppOnPairingHost(page, daemon, additionalHosts);
|
||||||
|
await openSettings(page);
|
||||||
|
await openSettingsHost(page, daemon.serverId);
|
||||||
|
await expect(page.getByTestId("devices-relay")).toHaveCount(0);
|
||||||
|
await openSettingsHostSection(page, daemon.serverId, "devices");
|
||||||
|
await expect(page.getByTestId("devices-relay")).toBeVisible();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Loads the app afresh with `daemon` as its first host, then opens the setup's Mobile step. */
|
||||||
|
export async function openSetupMobileStep(page: Page, daemon: PairingHost): Promise<void> {
|
||||||
|
await openAppOnPairingHost(page, daemon);
|
||||||
|
await showSetupAgainFromSettings(page);
|
||||||
|
await goToSetupStep(page, "Mobile");
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openAppOnPairingHost(
|
||||||
|
page: Page,
|
||||||
|
daemon: PairingHost,
|
||||||
additionalHosts: PairingHostInput[] = [],
|
additionalHosts: PairingHostInput[] = [],
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
await seedSavedSettingsHosts(page, [
|
await seedSavedSettingsHosts(page, [
|
||||||
@@ -74,20 +100,271 @@ export async function preparePairingHost(
|
|||||||
...additionalHosts,
|
...additionalHosts,
|
||||||
]);
|
]);
|
||||||
await gotoAppShell(page);
|
await gotoAppShell(page);
|
||||||
await openSettings(page);
|
}
|
||||||
await openSettingsHost(page, daemon.serverId);
|
|
||||||
await expect(page.getByTestId("host-page-pair-device-row")).toHaveCount(0);
|
export async function enableTailscale(page: Page): Promise<void> {
|
||||||
await openSettingsHostSection(page, daemon.serverId, "pair-device");
|
const toggle = page.getByRole("switch", { name: "Tailscale", exact: true });
|
||||||
await expect(page.getByTestId("host-page-pair-device-row")).toBeVisible();
|
await expect(toggle).toBeEnabled();
|
||||||
|
await expect(toggle).not.toBeChecked();
|
||||||
|
await toggle.click();
|
||||||
|
await expect(toggle).toBeChecked();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function expectTailscaleAddress(page: Page, address: string): Promise<void> {
|
||||||
|
const row = tailscaleAddressRow(page, address);
|
||||||
|
await expect(row).toBeVisible();
|
||||||
|
await expect(
|
||||||
|
row.getByText("On a phone with Tailscale, add a host at this address"),
|
||||||
|
).toBeVisible();
|
||||||
|
await expect(row.getByRole("button", { name: "Copy", exact: true })).toBeVisible();
|
||||||
|
const response = await fetch(`http://${address}/api/health`);
|
||||||
|
expect(response.ok).toBe(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The switch shows off as soon as it is tapped; the host stops listening when its answer lands. */
|
||||||
|
async function expectHostUnreachableAt(address: string): Promise<void> {
|
||||||
|
await expect
|
||||||
|
.poll(() =>
|
||||||
|
fetch(`http://${address}/api/health`).then(
|
||||||
|
() => "reachable",
|
||||||
|
() => "unreachable",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.toBe("unreachable");
|
||||||
|
}
|
||||||
|
|
||||||
|
function tailscaleAddressRow(page: Page, address: string) {
|
||||||
|
return page.getByTestId("devices-tailscale-address").filter({ hasText: address });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function disableTailscale(page: Page, address: string): Promise<void> {
|
||||||
|
const toggle = page.getByRole("switch", { name: "Tailscale", exact: true });
|
||||||
|
await expect(toggle).toBeEnabled();
|
||||||
|
await toggle.click();
|
||||||
|
await expect(toggle).not.toBeChecked();
|
||||||
|
await expect(tailscaleAddressRow(page, address)).toHaveCount(0);
|
||||||
|
await expectHostUnreachableAt(address);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reopens the host over its Tailscale address, as a phone on the tailnet would reach it. */
|
||||||
|
export async function connectThroughTailscale(
|
||||||
|
page: Page,
|
||||||
|
daemon: { serverId: string; tailscaleAddress: string },
|
||||||
|
): Promise<void> {
|
||||||
|
await preparePairingHost(page, { serverId: daemon.serverId, endpoint: daemon.tailscaleAddress });
|
||||||
|
await expectTailscaleAddress(page, daemon.tailscaleAddress);
|
||||||
|
}
|
||||||
|
|
||||||
|
const TURN_OFF_QUESTION =
|
||||||
|
"Turn off Tailscale?\n\nThis device is connected through Tailscale and will lose its connection to the host.";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Taps the switch off over the Tailscale connection and cancels the question. Every state the row
|
||||||
|
* commits from the tap to after Cancel must still show Tailscale on with its address: nothing
|
||||||
|
* changes until the user confirms.
|
||||||
|
*/
|
||||||
|
export async function cancelTailscaleTurnOff(page: Page, address: string): Promise<void> {
|
||||||
|
const row = await recordTailscaleRow(page);
|
||||||
|
const question = answerNextDialog(page, "dismiss");
|
||||||
|
await page.getByRole("switch", { name: "Tailscale", exact: true }).click();
|
||||||
|
expect(await question).toBe(TURN_OFF_QUESTION);
|
||||||
|
await page.waitForTimeout(500);
|
||||||
|
expect(new Set((await row()).map((state) => `${state.value} ${state.address}`))).toEqual(
|
||||||
|
new Set(["on true"]),
|
||||||
|
);
|
||||||
|
await expect(page.getByRole("switch", { name: "Tailscale", exact: true })).toBeChecked();
|
||||||
|
await expect(tailscaleAddressRow(page, address)).toBeVisible();
|
||||||
|
expect((await fetch(`http://${address}/api/health`)).ok).toBe(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Confirms turning Tailscale off over the Tailscale connection, which cuts this app off the host.
|
||||||
|
* Without the host the row shows no value at all, on or off.
|
||||||
|
*/
|
||||||
|
export async function confirmTailscaleTurnOff(page: Page, address: string): Promise<void> {
|
||||||
|
const question = answerNextDialog(page, "accept");
|
||||||
|
await page.getByRole("switch", { name: "Tailscale", exact: true }).click();
|
||||||
|
expect(await question).toBe(TURN_OFF_QUESTION);
|
||||||
|
await expect(page.getByText("Host is not connected", { exact: true })).toBeVisible();
|
||||||
|
await expect(page.getByRole("switch", { name: "Tailscale", exact: true })).toHaveCount(0);
|
||||||
|
await expectHostUnreachableAt(address);
|
||||||
|
}
|
||||||
|
|
||||||
|
function answerNextDialog(page: Page, answer: "accept" | "dismiss"): Promise<string> {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
page.once("dialog", async (dialog) => {
|
||||||
|
resolve(dialog.message());
|
||||||
|
await (answer === "accept" ? dialog.accept() : dialog.dismiss());
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
interface TailscaleRowState {
|
||||||
|
/** `none` while the row shows no value yet. */
|
||||||
|
value: "on" | "off" | "none";
|
||||||
|
address: boolean;
|
||||||
|
hint: string;
|
||||||
|
labelTop: number;
|
||||||
|
hintTop: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Records every state the Tailscale row commits, painted or not: from now on in this page, and
|
||||||
|
* from the first paint of every page load after it. Recording again starts a new record.
|
||||||
|
*/
|
||||||
|
async function recordTailscaleRow(page: Page): Promise<() => Promise<TailscaleRowState[]>> {
|
||||||
|
const record = () => {
|
||||||
|
const host = window as unknown as {
|
||||||
|
tailscaleRow?: { states: unknown[]; last: string; sample(): void };
|
||||||
|
};
|
||||||
|
if (host.tailscaleRow) {
|
||||||
|
host.tailscaleRow.states = [];
|
||||||
|
host.tailscaleRow.last = "";
|
||||||
|
host.tailscaleRow.sample();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const isVisibleText = (element: Element, text?: string) =>
|
||||||
|
element.childElementCount === 0 &&
|
||||||
|
(text === undefined
|
||||||
|
? (element.textContent ?? "").trim() !== ""
|
||||||
|
: element.textContent === text) &&
|
||||||
|
element.getBoundingClientRect().height > 0;
|
||||||
|
const readValue = (toggle: Element | null) => {
|
||||||
|
if (!toggle) return "none";
|
||||||
|
return toggle.getAttribute("aria-checked") === "true" ? "on" : "off";
|
||||||
|
};
|
||||||
|
const read = () => {
|
||||||
|
const label = [...document.querySelectorAll("div, span")].find((element) =>
|
||||||
|
isVisibleText(element, "Tailscale"),
|
||||||
|
);
|
||||||
|
if (!label) return null;
|
||||||
|
let row: Element = label;
|
||||||
|
while (row.parentElement && !(row as HTMLElement).innerText.includes("\n")) {
|
||||||
|
row = row.parentElement;
|
||||||
|
}
|
||||||
|
const hint = [...row.querySelectorAll("div, span")].find(
|
||||||
|
(element) => element !== label && isVisibleText(element),
|
||||||
|
);
|
||||||
|
const toggle = document.querySelector('[role="switch"][aria-label="Tailscale"]');
|
||||||
|
return {
|
||||||
|
value: readValue(toggle),
|
||||||
|
address: document.querySelector('[data-testid="devices-tailscale-address"]') !== null,
|
||||||
|
hint: hint?.textContent ?? "",
|
||||||
|
labelTop: Math.round(label.getBoundingClientRect().top),
|
||||||
|
hintTop: Math.round(hint?.getBoundingClientRect().top ?? -1),
|
||||||
|
};
|
||||||
|
};
|
||||||
|
const recorder = {
|
||||||
|
states: [] as unknown[],
|
||||||
|
last: "",
|
||||||
|
sample() {
|
||||||
|
const state = read();
|
||||||
|
const key = JSON.stringify(state);
|
||||||
|
if (state && key !== recorder.last) recorder.states.push(state);
|
||||||
|
recorder.last = key;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
host.tailscaleRow = recorder;
|
||||||
|
new MutationObserver(() => recorder.sample()).observe(document, {
|
||||||
|
subtree: true,
|
||||||
|
childList: true,
|
||||||
|
characterData: true,
|
||||||
|
attributes: true,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
await page.addInitScript(record);
|
||||||
|
await page.evaluate(record);
|
||||||
|
return () =>
|
||||||
|
page.evaluate(
|
||||||
|
() =>
|
||||||
|
(window as unknown as { tailscaleRow: { states: TailscaleRowState[] } }).tailscaleRow
|
||||||
|
.states,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs `open`, which first shows the Tailscale row of a host with Tailscale on, and checks the row
|
||||||
|
* from its first state to its last: it starts with no value, never shows Tailscale off, and its
|
||||||
|
* label and hint keep their text and place until it settles on, with the address below.
|
||||||
|
*/
|
||||||
|
export async function expectTailscaleRowLoadsOn(
|
||||||
|
page: Page,
|
||||||
|
address: string,
|
||||||
|
open: () => Promise<void>,
|
||||||
|
): Promise<void> {
|
||||||
|
const row = await recordTailscaleRow(page);
|
||||||
|
await open();
|
||||||
|
await expect(page.getByRole("switch", { name: "Tailscale", exact: true })).toBeChecked();
|
||||||
|
await expect(tailscaleAddressRow(page, address)).toBeVisible();
|
||||||
|
const states = await row();
|
||||||
|
expect(states[0]?.value).toBe("none");
|
||||||
|
expect(states.filter((state) => state.value === "off")).toEqual([]);
|
||||||
|
expect(
|
||||||
|
new Set(states.map(({ hint, labelTop, hintTop }) => `${hint} ${labelTop} ${hintTop}`)).size,
|
||||||
|
).toBe(1);
|
||||||
|
expect(states.at(-1)).toMatchObject({ value: "on", address: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Holds every message between the app and the host on `port` for `ms` in each direction, as on a
|
||||||
|
* slow network. The returned function brings the connection back to full speed.
|
||||||
|
*/
|
||||||
|
export async function slowConnectionToHost(
|
||||||
|
page: Page,
|
||||||
|
port: number,
|
||||||
|
ms: number,
|
||||||
|
): Promise<() => void> {
|
||||||
|
let delay = ms;
|
||||||
|
await page.routeWebSocket(wsRoutePatternForPort(String(port)), (app) => {
|
||||||
|
const host = app.connectToServer();
|
||||||
|
app.onMessage(
|
||||||
|
deliverInOrderAfter(
|
||||||
|
() => delay,
|
||||||
|
(message) => host.send(message),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
host.onMessage(
|
||||||
|
deliverInOrderAfter(
|
||||||
|
() => delay,
|
||||||
|
(message) => app.send(message),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
return () => {
|
||||||
|
delay = 0;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function deliverInOrderAfter(
|
||||||
|
delay: () => number,
|
||||||
|
deliver: (message: string | Buffer) => void,
|
||||||
|
): (message: string | Buffer) => void {
|
||||||
|
const queue: { at: number; message: string | Buffer }[] = [];
|
||||||
|
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
const flush = () => {
|
||||||
|
timer = null;
|
||||||
|
while (queue[0] && queue[0].at <= Date.now()) deliver(queue.shift()!.message);
|
||||||
|
if (queue[0]) timer = setTimeout(flush, queue[0].at - Date.now());
|
||||||
|
};
|
||||||
|
return (message) => {
|
||||||
|
queue.push({ at: Math.max(Date.now() + delay(), queue.at(-1)?.at ?? 0), message });
|
||||||
|
if (!timer) flush();
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function expectTailscaleUpdateRequired(page: Page): Promise<void> {
|
||||||
|
await expect(page.getByRole("switch", { name: "Tailscale", exact: true })).toBeDisabled();
|
||||||
|
await expect(page.getByText("Update this host to use Tailscale", { exact: true })).toBeVisible();
|
||||||
|
await expect(page.getByRole("link", { name: "How to update", exact: true })).toBeVisible();
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function openPairDeviceModal(page: Page): Promise<void> {
|
export async function openPairDeviceModal(page: Page): Promise<void> {
|
||||||
await page.getByRole("button", { name: /Pair a device/ }).click();
|
await page.getByRole("button", { name: "Relay", exact: true }).click();
|
||||||
await expect(page.getByTestId("host-page-pair-device-card")).toBeVisible();
|
await expect(page.getByTestId("devices-relay-pairing")).toBeVisible();
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function expectRelayConsent(page: Page): Promise<void> {
|
export async function expectRelayConsent(page: Page): Promise<void> {
|
||||||
const modal = page.getByTestId("host-page-pair-device-card");
|
const modal = page.getByTestId("devices-relay-pairing");
|
||||||
await expect(modal.getByText("Enable relay?", { exact: true })).toBeVisible();
|
await expect(modal.getByText("Enable relay?", { exact: true })).toBeVisible();
|
||||||
await expect(modal.getByText(/end-to-end encrypted/)).toBeVisible();
|
await expect(modal.getByText(/end-to-end encrypted/)).toBeVisible();
|
||||||
await expect(modal.getByRole("link", { name: "Read how Paseo relay works" })).toBeVisible();
|
await expect(modal.getByRole("link", { name: "Read how Paseo relay works" })).toBeVisible();
|
||||||
@@ -99,7 +376,7 @@ export async function expectRelayConsent(page: Page): Promise<void> {
|
|||||||
|
|
||||||
export async function declineRelay(page: Page): Promise<void> {
|
export async function declineRelay(page: Page): Promise<void> {
|
||||||
await page.getByRole("button", { name: "Not now", exact: true }).click();
|
await page.getByRole("button", { name: "Not now", exact: true }).click();
|
||||||
await expect(page.getByTestId("host-page-pair-device-card")).toHaveCount(0);
|
await expect(page.getByTestId("devices-relay-pairing")).toHaveCount(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function enableRelayAndExpectOffer(page: Page): Promise<void> {
|
export async function enableRelayAndExpectOffer(page: Page): Promise<void> {
|
||||||
@@ -124,10 +401,10 @@ export async function expectPairingOffer(page: Page): Promise<void> {
|
|||||||
|
|
||||||
export async function closePairDeviceModal(page: Page): Promise<void> {
|
export async function closePairDeviceModal(page: Page): Promise<void> {
|
||||||
await page
|
await page
|
||||||
.getByTestId("host-page-pair-device-card")
|
.getByTestId("devices-relay-pairing")
|
||||||
.getByRole("button", { name: "Close", exact: true })
|
.getByRole("button", { name: "Close", exact: true })
|
||||||
.click();
|
.click();
|
||||||
await expect(page.getByTestId("host-page-pair-device-card")).toHaveCount(0);
|
await expect(page.getByTestId("devices-relay-pairing")).toHaveCount(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function reloadAndOpenPairDevice(page: Page): Promise<void> {
|
export async function reloadAndOpenPairDevice(page: Page): Promise<void> {
|
||||||
@@ -145,7 +422,7 @@ export async function enableRelayAndExpectFailure(
|
|||||||
expectedError = "Relay is controlled by a daemon launch override",
|
expectedError = "Relay is controlled by a daemon launch override",
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
await page.getByRole("button", { name: "Enable relay", exact: true }).click();
|
await page.getByRole("button", { name: "Enable relay", exact: true }).click();
|
||||||
const modal = page.getByTestId("host-page-pair-device-card");
|
const modal = page.getByTestId("devices-relay-pairing");
|
||||||
await expect(modal.getByRole("alert")).toContainText(expectedError);
|
await expect(modal.getByRole("alert")).toContainText(expectedError);
|
||||||
await expect(modal.getByRole("button", { name: "Retry", exact: true })).toBeEnabled();
|
await expect(modal.getByRole("button", { name: "Retry", exact: true })).toBeEnabled();
|
||||||
await expect(modal.getByRole("textbox", { name: "Pairing link" })).toHaveCount(0);
|
await expect(modal.getByRole("textbox", { name: "Pairing link" })).toHaveCount(0);
|
||||||
@@ -155,7 +432,7 @@ export async function retryRelayAndExpectFailure(
|
|||||||
page: Page,
|
page: Page,
|
||||||
expectedError = "Relay is controlled by a daemon launch override",
|
expectedError = "Relay is controlled by a daemon launch override",
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const modal = page.getByTestId("host-page-pair-device-card");
|
const modal = page.getByTestId("devices-relay-pairing");
|
||||||
await modal.getByRole("button", { name: "Retry", exact: true }).click();
|
await modal.getByRole("button", { name: "Retry", exact: true }).click();
|
||||||
await expect(modal.getByRole("alert")).toContainText(expectedError);
|
await expect(modal.getByRole("alert")).toContainText(expectedError);
|
||||||
await expect(modal.getByRole("button", { name: "Retry", exact: true })).toBeEnabled();
|
await expect(modal.getByRole("button", { name: "Retry", exact: true })).toBeEnabled();
|
||||||
@@ -173,7 +450,7 @@ export async function openPairDeviceFromHome(page: Page): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function expectRelayUpdateRequired(page: Page): Promise<void> {
|
export async function expectRelayUpdateRequired(page: Page): Promise<void> {
|
||||||
const modal = page.getByTestId("host-page-pair-device-card");
|
const modal = page.getByTestId("devices-relay-pairing");
|
||||||
await expect(
|
await expect(
|
||||||
modal.getByText("Update the host to enable relay from Paseo Desktop."),
|
modal.getByText("Update the host to enable relay from Paseo Desktop."),
|
||||||
).toBeVisible();
|
).toBeVisible();
|
||||||
@@ -195,15 +472,15 @@ export function observePairingOfferRequests(page: Page, daemon: OutdatedDaemon):
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function expectPairingDisconnected(page: Page): Promise<void> {
|
export async function expectPairingDisconnected(page: Page): Promise<void> {
|
||||||
const modal = page.getByTestId("host-page-pair-device-card");
|
const modal = page.getByTestId("devices-relay-pairing");
|
||||||
await expect(modal.getByRole("alert")).toContainText("Host is not connected");
|
await expect(modal.getByRole("alert")).toContainText("Host is not connected");
|
||||||
await expect(modal.getByRole("button", { name: "Retry", exact: true })).toBeVisible();
|
await expect(modal.getByRole("button", { name: "Retry", exact: true })).toBeVisible();
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function switchPairDeviceToHost(page: Page, serverId: string): Promise<void> {
|
export async function switchPairDeviceToHost(page: Page, serverId: string): Promise<void> {
|
||||||
await selectSettingsHost(page, serverId);
|
await selectSettingsHost(page, serverId);
|
||||||
await expectAppRoute(page, buildSettingsHostSectionRoute(serverId, "pair-device"));
|
await expectAppRoute(page, buildSettingsHostSectionRoute(serverId, "devices"));
|
||||||
await expect(page.getByTestId("host-page-pair-device-row")).toBeVisible();
|
await expect(page.getByTestId("devices-relay")).toBeVisible();
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function openRelaySecurityDocs(page: Page): Promise<void> {
|
export async function openRelaySecurityDocs(page: Page): Promise<void> {
|
||||||
|
|||||||
@@ -66,7 +66,7 @@ export type SettingsSection = keyof typeof SECTION_LABELS;
|
|||||||
type HostSection =
|
type HostSection =
|
||||||
| "projects"
|
| "projects"
|
||||||
| "connections"
|
| "connections"
|
||||||
| "pair-device"
|
| "devices"
|
||||||
| "agents"
|
| "agents"
|
||||||
| "metadata"
|
| "metadata"
|
||||||
| "voice"
|
| "voice"
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import { once } from "node:events";
|
||||||
|
import path from "node:path";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { killProcessTree, spawnTsx } from "./spawn-node";
|
||||||
|
|
||||||
|
const readySchema = z.object({ port: z.number(), serverId: z.string() });
|
||||||
|
|
||||||
|
export async function startTailscaleTestDaemon(origin: string) {
|
||||||
|
const entrypoint = path.resolve(
|
||||||
|
__dirname,
|
||||||
|
"../../../../server/src/server/test-utils/tailscale-daemon.ts",
|
||||||
|
);
|
||||||
|
const child = spawnTsx(entrypoint, [origin], {
|
||||||
|
stdio: ["ignore", "inherit", "inherit", "ipc"],
|
||||||
|
});
|
||||||
|
const signal = AbortSignal.timeout(30_000);
|
||||||
|
try {
|
||||||
|
const ready = await Promise.race([
|
||||||
|
once(child, "message", { signal }).then(([message]) => readySchema.parse(message)),
|
||||||
|
once(child, "exit", { signal }).then(([code]) => {
|
||||||
|
throw new Error(`Tailscale test daemon exited before startup with code ${code}`);
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
return {
|
||||||
|
...ready,
|
||||||
|
tailscaleAddress: `127.0.0.2:${ready.port}`,
|
||||||
|
close: () => killProcessTree(child),
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
await killProcessTree(child);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -40,7 +40,7 @@
|
|||||||
"dev:ios": "npm --prefix ../.. run build:client && cross-env APP_VARIANT=development expo run:ios",
|
"dev:ios": "npm --prefix ../.. run build:client && cross-env APP_VARIANT=development expo run:ios",
|
||||||
"build:apk": "npm --prefix ../.. run build:apk",
|
"build:apk": "npm --prefix ../.. run build:apk",
|
||||||
"build:apk:arm64": "npm --prefix ../.. run build:apk:arm64",
|
"build:apk:arm64": "npm --prefix ../.. run build:apk:arm64",
|
||||||
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --tests '*ListRenderingTest' --tests '*TaskListInteractionTest' --tests '*ListBlockquoteMeasurementTest' --tests '*BlockquoteCopyTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
|
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --tests '*ListRenderingTest' --tests '*TaskListInteractionTest' --tests '*ListBlockquoteMeasurementTest' --tests '*BlockquoteCopyTest' --tests '*LongPressSelectionInterceptTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@codemirror/commands": "6.10.4",
|
"@codemirror/commands": "6.10.4",
|
||||||
|
|||||||
@@ -1,11 +1,76 @@
|
|||||||
import { useCallback, useMemo, useState, type ReactElement } from "react";
|
import { useCallback, useEffect, useMemo, useRef, useState, type ReactElement } from "react";
|
||||||
|
import { Text, View } from "react-native";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { StyleSheet } from "react-native-unistyles";
|
||||||
import type { AgentProfile } from "@getpaseo/protocol/messages";
|
import type { AgentProfile } from "@getpaseo/protocol/messages";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { useToast } from "@/contexts/toast-context";
|
||||||
|
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
|
||||||
|
import { confirmDialog } from "@/utils/confirm-dialog";
|
||||||
|
import { toErrorMessage } from "@/utils/error-messages";
|
||||||
import { AgentProfileEditModal } from "./settings/agent-profile-edit-modal";
|
import { AgentProfileEditModal } from "./settings/agent-profile-edit-modal";
|
||||||
import { generateAgentProfileId } from "./internal/profile-id";
|
import { generateAgentProfileId } from "./internal/profile-id";
|
||||||
import type { AgentProfileSeed, AgentProfileValue } from "./internal/profile-form-model";
|
import {
|
||||||
import { useAgentProfiles } from "./internal/use-agent-profiles";
|
buildInstantAgentProfile,
|
||||||
|
type AgentProfileSeed,
|
||||||
|
type AgentProfileValue,
|
||||||
|
} from "./internal/profile-form-model";
|
||||||
|
import { removeAgentProfileById, useAgentProfiles } from "./internal/use-agent-profiles";
|
||||||
|
|
||||||
|
const PROFILE_SAVED_TOAST_DURATION_MS = 6000;
|
||||||
|
|
||||||
|
function ProfileSavedToastContent({
|
||||||
|
name,
|
||||||
|
onEdit,
|
||||||
|
onUndo,
|
||||||
|
}: {
|
||||||
|
name: string;
|
||||||
|
onEdit: () => void;
|
||||||
|
onUndo: () => void;
|
||||||
|
}): ReactElement {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
return (
|
||||||
|
<View style={styles.toastRow}>
|
||||||
|
<Text style={styles.toastText} numberOfLines={1}>
|
||||||
|
{t("modelSelector.profileSaved", { name })}
|
||||||
|
</Text>
|
||||||
|
<View style={styles.toastActions}>
|
||||||
|
<Button
|
||||||
|
variant="secondary"
|
||||||
|
size="sm"
|
||||||
|
onPress={onEdit}
|
||||||
|
accessibilityLabel={t("modelSelector.editProfileLabel", { name })}
|
||||||
|
testID="model-profile-created-edit"
|
||||||
|
>
|
||||||
|
{t("modelSelector.editProfiles")}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onPress={onUndo}
|
||||||
|
accessibilityLabel={t("modelSelector.undoProfileSave")}
|
||||||
|
testID="model-profile-created-undo"
|
||||||
|
>
|
||||||
|
{t("modelSelector.undo")}
|
||||||
|
</Button>
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function createProfileSavedToast(input: {
|
||||||
|
name: string;
|
||||||
|
onEdit: () => void;
|
||||||
|
onUndo: () => void;
|
||||||
|
}): ReactElement {
|
||||||
|
return <ProfileSavedToastContent name={input.name} onEdit={input.onEdit} onUndo={input.onUndo} />;
|
||||||
|
}
|
||||||
|
|
||||||
export interface AgentProfileEditorControls {
|
export interface AgentProfileEditorControls {
|
||||||
|
/** Save a profile immediately from a model row with defaults and show an Edit/Undo toast. */
|
||||||
|
quickCreateFromModel: (seed: AgentProfileSeed) => Promise<AgentProfile | null>;
|
||||||
|
/** Undo an instant creation without a confirmation prompt. */
|
||||||
|
undoCreate: (profileId: string) => Promise<void>;
|
||||||
/** Open the create form pre-filled with provider, model, and suggested name. */
|
/** Open the create form pre-filled with provider, model, and suggested name. */
|
||||||
openCreateFromModel: (seed: AgentProfileSeed) => void;
|
openCreateFromModel: (seed: AgentProfileSeed) => void;
|
||||||
/** Open the edit form for one profile. */
|
/** Open the edit form for one profile. */
|
||||||
@@ -23,8 +88,78 @@ type EditorRequest =
|
|||||||
* never see `saveProfiles` or construct profile records themselves.
|
* never see `saveProfiles` or construct profile records themselves.
|
||||||
*/
|
*/
|
||||||
export function useAgentProfileEditor(serverId: string | null): AgentProfileEditorControls {
|
export function useAgentProfileEditor(serverId: string | null): AgentProfileEditorControls {
|
||||||
const { profiles, saveProfiles } = useAgentProfiles(serverId);
|
const { t } = useTranslation();
|
||||||
|
const toast = useToast();
|
||||||
|
const { profiles, mutateProfiles } = useAgentProfiles(serverId);
|
||||||
|
const { entries } = useProvidersSnapshot(serverId, { cwd: null });
|
||||||
const [request, setRequest] = useState<EditorRequest | null>(null);
|
const [request, setRequest] = useState<EditorRequest | null>(null);
|
||||||
|
const mountedRef = useRef(true);
|
||||||
|
const dismissSavedToastRef = useRef<(() => void) | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
mountedRef.current = true;
|
||||||
|
return () => {
|
||||||
|
mountedRef.current = false;
|
||||||
|
dismissSavedToastRef.current?.();
|
||||||
|
dismissSavedToastRef.current = null;
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const undoCreate = useCallback(
|
||||||
|
async (profileId: string): Promise<void> => {
|
||||||
|
try {
|
||||||
|
await mutateProfiles((current) => removeAgentProfileById(current, profileId));
|
||||||
|
} catch (error) {
|
||||||
|
toast.error(toErrorMessage(error));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[mutateProfiles, toast],
|
||||||
|
);
|
||||||
|
|
||||||
|
const quickCreateFromModel = useCallback(
|
||||||
|
async (seed: AgentProfileSeed): Promise<AgentProfile | null> => {
|
||||||
|
const value = buildInstantAgentProfile({ seed, entries });
|
||||||
|
const created: AgentProfile = { id: generateAgentProfileId(), ...value };
|
||||||
|
try {
|
||||||
|
const written = await mutateProfiles((current) => [...current, created]);
|
||||||
|
if (!written || !mountedRef.current) {
|
||||||
|
return written ? created : null;
|
||||||
|
}
|
||||||
|
dismissSavedToastRef.current?.();
|
||||||
|
let dismiss: (() => void) | null = null;
|
||||||
|
const clearToast = () => {
|
||||||
|
dismiss?.();
|
||||||
|
if (dismissSavedToastRef.current === dismiss) {
|
||||||
|
dismissSavedToastRef.current = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
dismiss = toast.show(
|
||||||
|
createProfileSavedToast({
|
||||||
|
name: created.name,
|
||||||
|
onEdit: () => {
|
||||||
|
clearToast();
|
||||||
|
setRequest({ mode: "edit", profile: created });
|
||||||
|
},
|
||||||
|
onUndo: () => {
|
||||||
|
clearToast();
|
||||||
|
void undoCreate(created.id);
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
{
|
||||||
|
variant: "success",
|
||||||
|
durationMs: PROFILE_SAVED_TOAST_DURATION_MS,
|
||||||
|
testID: "model-profile-created-toast",
|
||||||
|
},
|
||||||
|
);
|
||||||
|
dismissSavedToastRef.current = dismiss;
|
||||||
|
return created;
|
||||||
|
} catch (error) {
|
||||||
|
toast.error(toErrorMessage(error));
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[entries, mutateProfiles, toast, undoCreate],
|
||||||
|
);
|
||||||
|
|
||||||
const openCreateFromModel = useCallback((seed: AgentProfileSeed) => {
|
const openCreateFromModel = useCallback((seed: AgentProfileSeed) => {
|
||||||
setRequest({ mode: "create", seed });
|
setRequest({ mode: "create", seed });
|
||||||
@@ -45,15 +180,59 @@ export function useAgentProfileEditor(serverId: string | null): AgentProfileEdit
|
|||||||
|
|
||||||
const handleSave = useCallback(
|
const handleSave = useCallback(
|
||||||
async (value: AgentProfileValue) => {
|
async (value: AgentProfileValue) => {
|
||||||
const current = profiles ?? [];
|
const savedRequest = request;
|
||||||
const editing = request?.mode === "edit" ? request.profile : undefined;
|
const editing = savedRequest?.mode === "edit" ? savedRequest.profile : undefined;
|
||||||
const next: AgentProfile[] = editing
|
const written = await mutateProfiles((current) =>
|
||||||
? current.map((entry) => (entry.id === editing.id ? { id: entry.id, ...value } : entry))
|
editing
|
||||||
: [...current, { id: generateAgentProfileId(), ...value }];
|
? current.map((entry) => (entry.id === editing.id ? { id: entry.id, ...value } : entry))
|
||||||
await saveProfiles(next);
|
: [...current, { id: generateAgentProfileId(), ...value }],
|
||||||
setRequest(null);
|
);
|
||||||
|
if (!written) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setRequest((current) => (current === savedRequest ? null : current));
|
||||||
},
|
},
|
||||||
[profiles, request, saveProfiles],
|
[mutateProfiles, request],
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleRemove = useCallback(
|
||||||
|
(profileId: string) => {
|
||||||
|
const profile = profiles?.find((entry) => entry.id === profileId);
|
||||||
|
if (!profile) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const confirmAndRemove = async () => {
|
||||||
|
const confirmed = await confirmDialog({
|
||||||
|
title: t("settings.host.agentProfiles.removeConfirmTitle"),
|
||||||
|
message: t("settings.host.agentProfiles.removeConfirmMessage", { name: profile.name }),
|
||||||
|
confirmLabel: t("settings.host.agentProfiles.remove"),
|
||||||
|
cancelLabel: t("common.actions.cancel"),
|
||||||
|
destructive: true,
|
||||||
|
});
|
||||||
|
if (!confirmed) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const updated = await mutateProfiles((current) =>
|
||||||
|
removeAgentProfileById(current, profileId),
|
||||||
|
);
|
||||||
|
if (updated) {
|
||||||
|
setRequest((current) =>
|
||||||
|
current?.mode === "edit" && current.profile.id === profileId ? null : current,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
const detail = toErrorMessage(error);
|
||||||
|
toast.error(
|
||||||
|
detail
|
||||||
|
? `${t("common.errors.unableToSave")}: ${detail}`
|
||||||
|
: t("common.errors.unableToSave"),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
void confirmAndRemove();
|
||||||
|
},
|
||||||
|
[mutateProfiles, profiles, t, toast],
|
||||||
);
|
);
|
||||||
|
|
||||||
const element = useMemo(
|
const element = useMemo(
|
||||||
@@ -66,13 +245,34 @@ export function useAgentProfileEditor(serverId: string | null): AgentProfileEdit
|
|||||||
{...(request?.mode === "create" && request.seed ? { seed: request.seed } : {})}
|
{...(request?.mode === "create" && request.seed ? { seed: request.seed } : {})}
|
||||||
onClose={close}
|
onClose={close}
|
||||||
onSave={handleSave}
|
onSave={handleSave}
|
||||||
|
onRemove={handleRemove}
|
||||||
/>
|
/>
|
||||||
),
|
),
|
||||||
[close, handleSave, request, serverId],
|
[close, handleRemove, handleSave, request, serverId],
|
||||||
);
|
);
|
||||||
|
|
||||||
return useMemo(
|
return useMemo(
|
||||||
() => ({ openCreateFromModel, openEdit, element }),
|
() => ({ quickCreateFromModel, undoCreate, openCreateFromModel, openEdit, element }),
|
||||||
[openCreateFromModel, openEdit, element],
|
[element, openCreateFromModel, openEdit, quickCreateFromModel, undoCreate],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const styles = StyleSheet.create((theme) => ({
|
||||||
|
toastRow: {
|
||||||
|
flexDirection: "row",
|
||||||
|
alignItems: "center",
|
||||||
|
gap: theme.spacing[3],
|
||||||
|
maxWidth: "100%",
|
||||||
|
},
|
||||||
|
toastText: {
|
||||||
|
flexShrink: 1,
|
||||||
|
color: theme.colors.foreground,
|
||||||
|
fontSize: theme.fontSize.base,
|
||||||
|
},
|
||||||
|
toastActions: {
|
||||||
|
flexDirection: "row",
|
||||||
|
alignItems: "center",
|
||||||
|
gap: theme.spacing[1.5],
|
||||||
|
flexShrink: 0,
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|||||||
@@ -27,4 +27,7 @@ export {
|
|||||||
type DraftAgentProfileControls,
|
type DraftAgentProfileControls,
|
||||||
} from "./internal/use-agent-profile-picker";
|
} from "./internal/use-agent-profile-picker";
|
||||||
export { AgentProfileGlyph } from "./internal/agent-profile-glyph";
|
export { AgentProfileGlyph } from "./internal/agent-profile-glyph";
|
||||||
export { AgentProfilesSection } from "./settings/agent-profiles-section";
|
export {
|
||||||
|
AgentProfilesPage,
|
||||||
|
type AgentProfilesBeforeLeaveGuard,
|
||||||
|
} from "./settings/agent-profiles-section";
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ import {
|
|||||||
TestTube,
|
TestTube,
|
||||||
Wrench,
|
Wrench,
|
||||||
} from "lucide-react-native";
|
} from "lucide-react-native";
|
||||||
|
import { useProviderIcon } from "@/components/provider-icons";
|
||||||
import { identityForeground } from "@/styles/identity-colors";
|
import { identityForeground } from "@/styles/identity-colors";
|
||||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||||
import {
|
import {
|
||||||
@@ -108,21 +109,57 @@ export function agentProfileColorMapping(
|
|||||||
return COLOR_MAPPINGS[color];
|
return COLOR_MAPPINGS[color];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function ProviderFallbackIcon({
|
||||||
|
provider,
|
||||||
|
serverId,
|
||||||
|
size,
|
||||||
|
color = "",
|
||||||
|
}: {
|
||||||
|
provider: string;
|
||||||
|
serverId?: string | null;
|
||||||
|
size: number;
|
||||||
|
color?: string;
|
||||||
|
}) {
|
||||||
|
const Icon = useProviderIcon(provider, serverId);
|
||||||
|
return <Icon size={size} color={color} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ThemedProviderFallbackIcon = withUnistyles(ProviderFallbackIcon);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* How a profile is drawn everywhere it appears — settings list, model picker,
|
* How a profile is drawn everywhere it appears — settings roster, model picker,
|
||||||
* and the picker grid's own cells. One component so the three can't drift.
|
* drawer/sheet header, and the picker grid's own cells. When no custom icon is
|
||||||
|
* chosen and a provider is known, it falls back to that provider's mark instead
|
||||||
|
* of repeating identical generic stars across every row.
|
||||||
*/
|
*/
|
||||||
export function AgentProfileGlyph({
|
export function AgentProfileGlyph({
|
||||||
icon,
|
icon,
|
||||||
color,
|
color,
|
||||||
|
provider,
|
||||||
|
serverId,
|
||||||
size = ICON_SIZE.md,
|
size = ICON_SIZE.md,
|
||||||
}: {
|
}: {
|
||||||
icon?: string | undefined;
|
icon?: string | undefined;
|
||||||
color?: string | undefined;
|
color?: string | undefined;
|
||||||
|
provider?: string | undefined;
|
||||||
|
serverId?: string | null | undefined;
|
||||||
size?: number;
|
size?: number;
|
||||||
}) {
|
}) {
|
||||||
const iconKey = resolveAgentProfileIconKey(icon);
|
const iconKey = resolveAgentProfileIconKey(icon);
|
||||||
const mapping = COLOR_MAPPINGS[resolveAgentProfileColor(color)];
|
const mapping = COLOR_MAPPINGS[resolveAgentProfileColor(color)];
|
||||||
const Icon = iconKey ? THEMED_ICONS[iconKey] : ThemedDefaultIcon;
|
if (iconKey) {
|
||||||
return <Icon size={size} uniProps={mapping} />;
|
const Icon = THEMED_ICONS[iconKey];
|
||||||
|
return <Icon size={size} uniProps={mapping} />;
|
||||||
|
}
|
||||||
|
if (provider) {
|
||||||
|
return (
|
||||||
|
<ThemedProviderFallbackIcon
|
||||||
|
provider={provider}
|
||||||
|
serverId={serverId}
|
||||||
|
size={size}
|
||||||
|
uniProps={mapping}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return <ThemedDefaultIcon size={size} uniProps={mapping} />;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types";
|
|||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
import {
|
import {
|
||||||
buildControlsRequestKey,
|
buildControlsRequestKey,
|
||||||
|
buildInstantAgentProfile,
|
||||||
openAgentProfileForm,
|
openAgentProfileForm,
|
||||||
type AgentProfileFormModel,
|
type AgentProfileFormModel,
|
||||||
} from "./profile-form-model";
|
} from "./profile-form-model";
|
||||||
@@ -70,6 +71,10 @@ function optionValues(options: readonly { value: string }[]): string[] {
|
|||||||
return options.map((option) => option.value);
|
return options.map((option) => option.value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function optionIds(options: readonly { id: string }[]): string[] {
|
||||||
|
return options.map((option) => option.id);
|
||||||
|
}
|
||||||
|
|
||||||
const FAST = {
|
const FAST = {
|
||||||
controls: [{ type: "toggle" as const, key: "fast_mode", label: "Fast" }],
|
controls: [{ type: "toggle" as const, key: "fast_mode", label: "Fast" }],
|
||||||
options: { fast_mode: false },
|
options: { fast_mode: false },
|
||||||
@@ -528,16 +533,71 @@ describe("openAgentProfileForm", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it("draws no controls for the previous model while another model's answer is pending", () => {
|
it("keeps previous provider controls mounted while another model's answer is pending to prevent layout jank", () => {
|
||||||
const model = openWithCatalog({ mode: "create" });
|
const model = openWithCatalog({ mode: "create" });
|
||||||
selectClaude(model);
|
selectClaude(model);
|
||||||
model.applyControls(model.getState().controlsRequestKey ?? "", WEB_SEARCH_CONTROLS);
|
model.applyControls(model.getState().controlsRequestKey ?? "", WEB_SEARCH_CONTROLS);
|
||||||
|
|
||||||
model.setModel("claude-haiku-4-5", { label: "Haiku 4.5" });
|
model.setModel("claude-haiku-4-5", { label: "Haiku 4.5" });
|
||||||
|
|
||||||
|
expect(model.getState().controlsResolution).toBe("pending");
|
||||||
|
expect(model.getState().controlsPending).toBe(true);
|
||||||
|
expect(model.getState().controls).toHaveLength(1);
|
||||||
|
|
||||||
|
// Switching providers clears controls immediately so stale controls never cross providers.
|
||||||
|
model.setProvider("codex", { label: "Codex" });
|
||||||
expect(model.getState().controls).toEqual([]);
|
expect(model.getState().controls).toEqual([]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("seeds the catalog synchronously when entries are passed in the initial snapshot", () => {
|
||||||
|
const model = openAgentProfileForm({
|
||||||
|
mode: "edit",
|
||||||
|
profile: { id: "p1", name: "UI work", provider: "claude", model: "claude-opus-5" },
|
||||||
|
entries: ENTRIES,
|
||||||
|
});
|
||||||
|
const state = model.getState();
|
||||||
|
|
||||||
|
expect(state.catalogResolution).toBe("complete");
|
||||||
|
expect(state.providerDisplay).toEqual({ label: "Claude Code" });
|
||||||
|
expect(state.modelDisplay).toEqual({ label: "Opus 5" });
|
||||||
|
expect(optionIds(state.unifiedModelOptions)).toEqual([
|
||||||
|
"claude:claude-opus-5",
|
||||||
|
"claude:claude-haiku-4-5",
|
||||||
|
"codex:gpt-5.2-codex",
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("updates provider, model, and auto-suggested name together via setProviderModel", () => {
|
||||||
|
const model = openAgentProfileForm({ mode: "create", entries: ENTRIES });
|
||||||
|
|
||||||
|
model.setProviderModel("claude", "claude-opus-5", {
|
||||||
|
provider: { label: "Claude Code" },
|
||||||
|
model: { label: "Opus 5" },
|
||||||
|
});
|
||||||
|
expect(model.getState().name).toBe("Opus 5");
|
||||||
|
expect(model.getState().provider).toBe("claude");
|
||||||
|
expect(model.getState().modelId).toBe("claude-opus-5");
|
||||||
|
expect(model.getState().modeId).toBe("plan");
|
||||||
|
expect(model.getState().thinkingOptionId).toBe("think");
|
||||||
|
|
||||||
|
// Switching to another model while untouched updates the suggested name.
|
||||||
|
model.setProviderModel("codex", "gpt-5.2-codex", {
|
||||||
|
provider: { label: "Codex" },
|
||||||
|
model: { label: "GPT-5.2 Codex" },
|
||||||
|
});
|
||||||
|
expect(model.getState().name).toBe("GPT-5.2 Codex");
|
||||||
|
expect(model.getState().provider).toBe("codex");
|
||||||
|
expect(model.getState().modeId).toBe("read-only");
|
||||||
|
|
||||||
|
// Once the user types a custom name, changing model preserves it.
|
||||||
|
model.setName("My Custom Worker");
|
||||||
|
model.setProviderModel("claude", "claude-haiku-4-5", {
|
||||||
|
provider: { label: "Claude Code" },
|
||||||
|
model: { label: "Haiku 4.5" },
|
||||||
|
});
|
||||||
|
expect(model.getState().name).toBe("My Custom Worker");
|
||||||
|
});
|
||||||
|
|
||||||
it("does not save a toggle once the model that drew it is replaced by one without it", () => {
|
it("does not save a toggle once the model that drew it is replaced by one without it", () => {
|
||||||
const model = toggledOnOpus();
|
const model = toggledOnOpus();
|
||||||
expect(model.getState().submitValue?.options).toEqual({ fast_mode: true });
|
expect(model.getState().submitValue?.options).toEqual({ fast_mode: true });
|
||||||
@@ -643,6 +703,36 @@ describe("openAgentProfileForm", () => {
|
|||||||
expect(notifications).toBe(1);
|
expect(notifications).toBe(1);
|
||||||
expect(model.getState().name).toBe("a");
|
expect(model.getState().name).toBe("a");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("does not treat catalog-prefilled defaults on a minimal profile as an unsaved edit", () => {
|
||||||
|
const model = openAgentProfileForm({
|
||||||
|
mode: "edit",
|
||||||
|
profile: {
|
||||||
|
id: "legacy_favorite:claude:claude-opus-5",
|
||||||
|
name: "Opus 5",
|
||||||
|
provider: "claude",
|
||||||
|
model: "claude-opus-5",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(model.getState().isDirty).toBe(false);
|
||||||
|
|
||||||
|
// Catalog fills in default modeId ("plan") and thinkingOptionId ("think").
|
||||||
|
model.applyProviderCatalog(ENTRIES);
|
||||||
|
expect(model.getState().modeId).toBe("plan");
|
||||||
|
expect(model.getState().thinkingOptionId).toBe("think");
|
||||||
|
expect(model.getState().isDirty).toBe(false);
|
||||||
|
|
||||||
|
// User edit marks dirty and advances draftRevision; a subsequent edit advances it again.
|
||||||
|
expect(model.getState().draftRevision).toBe(0);
|
||||||
|
model.setName("Renamed");
|
||||||
|
expect(model.getState().isDirty).toBe(true);
|
||||||
|
expect(model.getState().draftRevision).toBe(1);
|
||||||
|
model.setName("Renamed again");
|
||||||
|
expect(model.getState().draftRevision).toBe(2);
|
||||||
|
model.setName("Opus 5");
|
||||||
|
expect(model.getState().isDirty).toBe(false);
|
||||||
|
expect(model.getState().draftRevision).toBe(3);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("buildControlsRequestKey", () => {
|
describe("buildControlsRequestKey", () => {
|
||||||
@@ -657,3 +747,55 @@ describe("buildControlsRequestKey", () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("buildInstantAgentProfile", () => {
|
||||||
|
it("builds a concrete profile with provider defaults from a model seed", () => {
|
||||||
|
expect(
|
||||||
|
buildInstantAgentProfile({
|
||||||
|
seed: { provider: "claude", modelId: "claude-opus-5", name: "Opus 5" },
|
||||||
|
entries: ENTRIES,
|
||||||
|
}),
|
||||||
|
).toEqual({
|
||||||
|
name: "Opus 5",
|
||||||
|
provider: "claude",
|
||||||
|
model: "claude-opus-5",
|
||||||
|
modeId: "plan",
|
||||||
|
thinkingOptionId: "think",
|
||||||
|
options: {},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps compatible preferred mode and thinking levels and ignores incompatible ones", () => {
|
||||||
|
expect(
|
||||||
|
buildInstantAgentProfile({
|
||||||
|
seed: { provider: "claude", modelId: "claude-opus-5" },
|
||||||
|
entries: ENTRIES,
|
||||||
|
preferredModeId: "accept-edits",
|
||||||
|
preferredThinkingOptionId: "think-hard",
|
||||||
|
}),
|
||||||
|
).toEqual({
|
||||||
|
name: "Opus 5",
|
||||||
|
provider: "claude",
|
||||||
|
model: "claude-opus-5",
|
||||||
|
modeId: "accept-edits",
|
||||||
|
thinkingOptionId: "think-hard",
|
||||||
|
options: {},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(
|
||||||
|
buildInstantAgentProfile({
|
||||||
|
seed: { provider: "claude", modelId: "claude-haiku-4-5" },
|
||||||
|
entries: ENTRIES,
|
||||||
|
preferredModeId: "unknown-mode",
|
||||||
|
preferredThinkingOptionId: "think-hard",
|
||||||
|
}),
|
||||||
|
).toEqual({
|
||||||
|
name: "Haiku 4.5",
|
||||||
|
provider: "claude",
|
||||||
|
model: "claude-haiku-4-5",
|
||||||
|
modeId: "plan",
|
||||||
|
thinkingOptionId: "think",
|
||||||
|
options: {},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -41,6 +41,16 @@ export interface AgentProfileFormOption {
|
|||||||
testID: string;
|
testID: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface AgentProfileUnifiedModelOption {
|
||||||
|
id: string;
|
||||||
|
provider: string;
|
||||||
|
providerLabel: string;
|
||||||
|
modelId: string;
|
||||||
|
label: string;
|
||||||
|
description?: string;
|
||||||
|
testID: string;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Pre-fill values for create mode. Only used when `mode === "create"`; edit
|
* Pre-fill values for create mode. Only used when `mode === "create"`; edit
|
||||||
* mode always seeds from the stored `profile` and ignores this.
|
* mode always seeds from the stored `profile` and ignores this.
|
||||||
@@ -55,6 +65,8 @@ export interface AgentProfileFormSnapshot {
|
|||||||
mode: "create" | "edit";
|
mode: "create" | "edit";
|
||||||
profile?: AgentProfile;
|
profile?: AgentProfile;
|
||||||
seed?: AgentProfileSeed;
|
seed?: AgentProfileSeed;
|
||||||
|
/** Optional cached host catalog so the first render is already hydrated without a layout flash. */
|
||||||
|
entries?: readonly ProviderSnapshotEntry[];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -97,6 +109,7 @@ export interface AgentProfileFormState {
|
|||||||
optionEdits: ProviderOptions;
|
optionEdits: ProviderOptions;
|
||||||
|
|
||||||
providerOptions: AgentProfileFormOption[];
|
providerOptions: AgentProfileFormOption[];
|
||||||
|
unifiedModelOptions: AgentProfileUnifiedModelOption[];
|
||||||
modelOptions: AgentProfileFormOption[];
|
modelOptions: AgentProfileFormOption[];
|
||||||
modeOptions: AgentProfileFormOption[];
|
modeOptions: AgentProfileFormOption[];
|
||||||
thinkingOptions: AgentProfileFormOption[];
|
thinkingOptions: AgentProfileFormOption[];
|
||||||
@@ -115,10 +128,14 @@ export interface AgentProfileFormState {
|
|||||||
|
|
||||||
catalogResolution: AgentProfileResolutionStatus;
|
catalogResolution: AgentProfileResolutionStatus;
|
||||||
controlsResolution: AgentProfileResolutionStatus;
|
controlsResolution: AgentProfileResolutionStatus;
|
||||||
|
controlsPending: boolean;
|
||||||
controlsRequest: AgentProfileControlsRequest | null;
|
controlsRequest: AgentProfileControlsRequest | null;
|
||||||
controlsRequestKey: string | null;
|
controlsRequestKey: string | null;
|
||||||
|
|
||||||
disclosure: AgentProfileFormDisclosure;
|
disclosure: AgentProfileFormDisclosure;
|
||||||
|
isDirty: boolean;
|
||||||
|
/** Monotonic counter incremented on every user edit that changes the draft. */
|
||||||
|
draftRevision: number;
|
||||||
isSubmitting: boolean;
|
isSubmitting: boolean;
|
||||||
submitError: string | null;
|
submitError: string | null;
|
||||||
canSubmit: boolean;
|
canSubmit: boolean;
|
||||||
@@ -142,6 +159,11 @@ export interface AgentProfileFormModel {
|
|||||||
setAppearance: (value: { icon: string; color: string }) => void;
|
setAppearance: (value: { icon: string; color: string }) => void;
|
||||||
setNotes: (value: string) => void;
|
setNotes: (value: string) => void;
|
||||||
setProvider: (providerId: string, display: AgentProfileFormDisplay) => void;
|
setProvider: (providerId: string, display: AgentProfileFormDisplay) => void;
|
||||||
|
setProviderModel: (
|
||||||
|
providerId: string,
|
||||||
|
modelId: string,
|
||||||
|
displays: { provider: AgentProfileFormDisplay; model: AgentProfileFormDisplay | null },
|
||||||
|
) => void;
|
||||||
setModel: (modelId: string, display: AgentProfileFormDisplay | null) => void;
|
setModel: (modelId: string, display: AgentProfileFormDisplay | null) => void;
|
||||||
setMode: (modeId: string, display: AgentProfileFormDisplay | null) => void;
|
setMode: (modeId: string, display: AgentProfileFormDisplay | null) => void;
|
||||||
setThinking: (thinkingOptionId: string, display: AgentProfileFormDisplay | null) => void;
|
setThinking: (thinkingOptionId: string, display: AgentProfileFormDisplay | null) => void;
|
||||||
@@ -224,6 +246,53 @@ function buildProviderOptions(entries: readonly ProviderSnapshotEntry[]): AgentP
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function formatUnifiedModelDescription(providerLabel: string, model: AgentModelDefinition): string {
|
||||||
|
if (model.description && model.description !== providerLabel) {
|
||||||
|
return `${providerLabel} · ${model.description}`;
|
||||||
|
}
|
||||||
|
if (model.id !== model.label) {
|
||||||
|
return `${providerLabel} · ${model.id}`;
|
||||||
|
}
|
||||||
|
return providerLabel;
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildUnifiedModelOptions(
|
||||||
|
entries: readonly ProviderSnapshotEntry[],
|
||||||
|
): AgentProfileUnifiedModelOption[] {
|
||||||
|
const options: AgentProfileUnifiedModelOption[] = [];
|
||||||
|
for (const entry of entries) {
|
||||||
|
if (!entry.enabled) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const providerLabel = entry.label ?? entry.provider;
|
||||||
|
const models = filterSelectableModels(entry.models ?? null) ?? [];
|
||||||
|
if (models.length === 0) {
|
||||||
|
options.push({
|
||||||
|
id: `${entry.provider}:`,
|
||||||
|
provider: entry.provider,
|
||||||
|
providerLabel,
|
||||||
|
modelId: "",
|
||||||
|
label: providerLabel,
|
||||||
|
...(entry.description ? { description: entry.description } : {}),
|
||||||
|
testID: `agent-profile-unified-model-${entry.provider}`,
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (const model of models) {
|
||||||
|
options.push({
|
||||||
|
id: `${entry.provider}:${model.id}`,
|
||||||
|
provider: entry.provider,
|
||||||
|
providerLabel,
|
||||||
|
modelId: model.id,
|
||||||
|
label: model.label,
|
||||||
|
description: formatUnifiedModelDescription(providerLabel, model),
|
||||||
|
testID: `agent-profile-unified-model-${entry.provider}-${model.id}`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return options;
|
||||||
|
}
|
||||||
|
|
||||||
function buildModelOptions(models: readonly AgentModelDefinition[]): AgentProfileFormOption[] {
|
function buildModelOptions(models: readonly AgentModelDefinition[]): AgentProfileFormOption[] {
|
||||||
return models.map((model) =>
|
return models.map((model) =>
|
||||||
formOption({
|
formOption({
|
||||||
@@ -385,6 +454,28 @@ export function buildControlsRequestKey(
|
|||||||
: scope;
|
: scope;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function stableOptionsKey(record: ProviderOptions): string {
|
||||||
|
const keys = Object.keys(record).sort();
|
||||||
|
if (keys.length === 0) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
return JSON.stringify(keys.map((key) => [key, record[key]]));
|
||||||
|
}
|
||||||
|
|
||||||
|
function formDraftFingerprint(state: AgentProfileFormState): string {
|
||||||
|
return JSON.stringify([
|
||||||
|
state.name.trim(),
|
||||||
|
state.icon,
|
||||||
|
state.color,
|
||||||
|
state.provider,
|
||||||
|
state.modelId,
|
||||||
|
state.modeId,
|
||||||
|
state.thinkingOptionId,
|
||||||
|
state.notes.trim(),
|
||||||
|
stableOptionsKey(ownOptionsOf(state)),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
function buildSubmitValue(state: AgentProfileFormState): AgentProfileValue | null {
|
function buildSubmitValue(state: AgentProfileFormState): AgentProfileValue | null {
|
||||||
const name = state.name.trim();
|
const name = state.name.trim();
|
||||||
const notes = state.notes.trim();
|
const notes = state.notes.trim();
|
||||||
@@ -446,6 +537,7 @@ function buildInitialState(snapshot: AgentProfileFormSnapshot): AgentProfileForm
|
|||||||
options: { ...profile.options },
|
options: { ...profile.options },
|
||||||
optionEdits: {},
|
optionEdits: {},
|
||||||
providerOptions: [],
|
providerOptions: [],
|
||||||
|
unifiedModelOptions: [],
|
||||||
modelOptions: [],
|
modelOptions: [],
|
||||||
modeOptions: [],
|
modeOptions: [],
|
||||||
thinkingOptions: [],
|
thinkingOptions: [],
|
||||||
@@ -459,6 +551,7 @@ function buildInitialState(snapshot: AgentProfileFormSnapshot): AgentProfileForm
|
|||||||
thinkingDisplay: seedDisplay(profile.thinkingOptionId),
|
thinkingDisplay: seedDisplay(profile.thinkingOptionId),
|
||||||
catalogResolution: "idle",
|
catalogResolution: "idle",
|
||||||
controlsResolution: "idle",
|
controlsResolution: "idle",
|
||||||
|
controlsPending: false,
|
||||||
controlsRequest: null,
|
controlsRequest: null,
|
||||||
controlsRequestKey: null,
|
controlsRequestKey: null,
|
||||||
disclosure: {
|
disclosure: {
|
||||||
@@ -467,6 +560,8 @@ function buildInitialState(snapshot: AgentProfileFormSnapshot): AgentProfileForm
|
|||||||
showThinkingField: false,
|
showThinkingField: false,
|
||||||
showControlsField: false,
|
showControlsField: false,
|
||||||
},
|
},
|
||||||
|
isDirty: false,
|
||||||
|
draftRevision: 0,
|
||||||
isSubmitting: false,
|
isSubmitting: false,
|
||||||
submitError: null,
|
submitError: null,
|
||||||
canSubmit: false,
|
canSubmit: false,
|
||||||
@@ -474,17 +569,118 @@ function buildInitialState(snapshot: AgentProfileFormSnapshot): AgentProfileForm
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function pickMatchingId(
|
||||||
|
preferred: string | null | undefined,
|
||||||
|
options: readonly { id: string }[],
|
||||||
|
fallback: string,
|
||||||
|
): string {
|
||||||
|
const trimmed = preferred?.trim() ?? "";
|
||||||
|
if (trimmed && options.some((option) => option.id === trimmed)) {
|
||||||
|
return trimmed;
|
||||||
|
}
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builds a ready-to-save profile in one tap (for composer model-row `+` creation).
|
||||||
|
* Resolves defaults from the host catalog and preserves compatible composer mode/thinking
|
||||||
|
* when provided, so the stored profile is concrete from the moment it is created.
|
||||||
|
*/
|
||||||
|
export function buildInstantAgentProfile(input: {
|
||||||
|
seed: AgentProfileSeed;
|
||||||
|
entries: readonly ProviderSnapshotEntry[] | undefined;
|
||||||
|
preferredModeId?: string | null;
|
||||||
|
preferredThinkingOptionId?: string | null;
|
||||||
|
}): AgentProfileValue {
|
||||||
|
const entries = input.entries ?? [];
|
||||||
|
const entry = findEntry(entries, input.seed.provider);
|
||||||
|
const models = resolveModels(entries, input.seed.provider);
|
||||||
|
const modes = resolveModes(entries, input.seed.provider);
|
||||||
|
const modelId = input.seed.modelId?.trim() || defaultModelId(models);
|
||||||
|
const effectiveModel = resolveEffectiveModel(models, modelId);
|
||||||
|
const matchedModel = models.find((candidate) => candidate.id === modelId);
|
||||||
|
const modeId = pickMatchingId(input.preferredModeId, modes, defaultModeId(entry, modes));
|
||||||
|
const thinkingOptionId = pickMatchingId(
|
||||||
|
input.preferredThinkingOptionId,
|
||||||
|
effectiveModel?.thinkingOptions ?? [],
|
||||||
|
defaultThinkingOptionId(effectiveModel),
|
||||||
|
);
|
||||||
|
const name =
|
||||||
|
[input.seed.name?.trim(), matchedModel?.label, modelId, entry?.label, input.seed.provider].find(
|
||||||
|
(candidate): candidate is string => Boolean(candidate),
|
||||||
|
) ?? input.seed.provider;
|
||||||
|
|
||||||
|
return {
|
||||||
|
name,
|
||||||
|
provider: input.seed.provider,
|
||||||
|
...(modelId ? { model: modelId } : {}),
|
||||||
|
...(modeId ? { modeId } : {}),
|
||||||
|
...(thinkingOptionId ? { thinkingOptionId } : {}),
|
||||||
|
options: {},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveModeLabel(modes: readonly AgentMode[], modeId: string): string | null {
|
||||||
|
const mode = modes.find((entry) => entry.id === modeId);
|
||||||
|
return mode ? formatAgentModeLabel(mode) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveThinkingLabel(options: readonly AgentSelectOption[], id: string): string | null {
|
||||||
|
const option = options.find((entry) => entry.id === id);
|
||||||
|
return option ? formatThinkingOptionLabel(option) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveControlsSlice(input: {
|
||||||
|
next: AgentProfileFormState;
|
||||||
|
controlsRequestKey: string | null;
|
||||||
|
controlsScopeKey: string | null;
|
||||||
|
resolvedControlsKey: string | null;
|
||||||
|
resolvedScopeKey: string | null;
|
||||||
|
resolvedProvider: string | null;
|
||||||
|
resolvedControls: AgentOptionControl[];
|
||||||
|
resolvedOptions: ProviderOptions;
|
||||||
|
}): {
|
||||||
|
controls: AgentOptionControl[];
|
||||||
|
controlOptions: ProviderOptions;
|
||||||
|
controlsResolution: AgentProfileResolutionStatus;
|
||||||
|
} {
|
||||||
|
const featuresAreCurrent =
|
||||||
|
input.controlsRequestKey !== null && input.controlsRequestKey === input.resolvedControlsKey;
|
||||||
|
const controlsApply =
|
||||||
|
input.controlsScopeKey !== null &&
|
||||||
|
(input.controlsScopeKey === input.resolvedScopeKey ||
|
||||||
|
(input.next.provider.length > 0 && input.next.provider === input.resolvedProvider));
|
||||||
|
const controls = controlsApply ? input.resolvedControls : [];
|
||||||
|
let controlOptions: ProviderOptions = input.next.options;
|
||||||
|
if (controlsApply) {
|
||||||
|
controlOptions = featuresAreCurrent
|
||||||
|
? input.resolvedOptions
|
||||||
|
: { ...input.resolvedOptions, ...input.next.optionEdits };
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
controls,
|
||||||
|
controlOptions,
|
||||||
|
controlsResolution: resolveControlsStatus(input.controlsRequestKey, featuresAreCurrent),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentProfileFormModel {
|
export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentProfileFormModel {
|
||||||
let entries: readonly ProviderSnapshotEntry[] = [];
|
let entries: readonly ProviderSnapshotEntry[] = snapshot.entries ? [...snapshot.entries] : [];
|
||||||
let catalogResolution: AgentProfileResolutionStatus = "idle";
|
let catalogResolution: AgentProfileResolutionStatus = snapshot.entries ? "complete" : "idle";
|
||||||
let resolvedControlsKey: string | null = null;
|
let resolvedControlsKey: string | null = null;
|
||||||
let resolvedScopeKey: string | null = null;
|
let resolvedScopeKey: string | null = null;
|
||||||
|
let resolvedProvider: string | null = null;
|
||||||
let resolvedControls: AgentOptionControl[] = [];
|
let resolvedControls: AgentOptionControl[] = [];
|
||||||
let resolvedOptions: ProviderOptions = {};
|
let resolvedOptions: ProviderOptions = {};
|
||||||
let drawnKeys: ReadonlySet<string> = new Set();
|
let drawnKeys: ReadonlySet<string> = new Set();
|
||||||
let answeredKeys: ReadonlySet<string> = new Set();
|
let answeredKeys: ReadonlySet<string> = new Set();
|
||||||
let listeners = new Set<() => void>();
|
let listeners = new Set<() => void>();
|
||||||
let closed = false;
|
let closed = false;
|
||||||
|
let hasUserEdited = false;
|
||||||
|
let draftRevision = 0;
|
||||||
|
let baselineFingerprint = "";
|
||||||
|
let autoSuggestedName: string | null =
|
||||||
|
snapshot.mode === "create" ? (snapshot.seed?.name ?? null) : null;
|
||||||
|
|
||||||
function derive(incoming: AgentProfileFormState): AgentProfileFormState {
|
function derive(incoming: AgentProfileFormState): AgentProfileFormState {
|
||||||
const models = resolveModels(entries, incoming.provider);
|
const models = resolveModels(entries, incoming.provider);
|
||||||
@@ -502,24 +698,21 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
|
|||||||
const controlsRequest = buildControlsRequest(next);
|
const controlsRequest = buildControlsRequest(next);
|
||||||
const controlsRequestKey = buildControlsRequestKey(controlsRequest);
|
const controlsRequestKey = buildControlsRequestKey(controlsRequest);
|
||||||
const controlsScopeKey = buildControlsScopeKey(controlsRequest);
|
const controlsScopeKey = buildControlsScopeKey(controlsRequest);
|
||||||
const featuresAreCurrent =
|
const { controls, controlOptions, controlsResolution } = resolveControlsSlice({
|
||||||
controlsRequestKey !== null && controlsRequestKey === resolvedControlsKey;
|
next,
|
||||||
// A toggle changes only the options, so the controls stay up while the daemon answers and the
|
controlsRequestKey,
|
||||||
// toggle shows over the last answer. A change of provider, model, mode or thinking draws none
|
controlsScopeKey,
|
||||||
// until its own answer arrives.
|
resolvedControlsKey,
|
||||||
const controlsApply = controlsScopeKey !== null && controlsScopeKey === resolvedScopeKey;
|
resolvedScopeKey,
|
||||||
const controls = controlsApply ? resolvedControls : [];
|
resolvedProvider,
|
||||||
let controlOptions: ProviderOptions = next.options;
|
resolvedControls,
|
||||||
if (controlsApply) {
|
resolvedOptions,
|
||||||
controlOptions = featuresAreCurrent
|
});
|
||||||
? resolvedOptions
|
|
||||||
: { ...resolvedOptions, ...next.optionEdits };
|
|
||||||
}
|
|
||||||
const controlsResolution = resolveControlsStatus(controlsRequestKey, featuresAreCurrent);
|
|
||||||
|
|
||||||
const withOptions: AgentProfileFormState = {
|
const withOptions: AgentProfileFormState = {
|
||||||
...next,
|
...next,
|
||||||
providerOptions: buildProviderOptions(entries),
|
providerOptions: buildProviderOptions(entries),
|
||||||
|
unifiedModelOptions: buildUnifiedModelOptions(entries),
|
||||||
modelOptions: buildModelOptions(models),
|
modelOptions: buildModelOptions(models),
|
||||||
modeOptions: buildModeOptions(modes),
|
modeOptions: buildModeOptions(modes),
|
||||||
thinkingOptions: buildThinkingOptions(thinking),
|
thinkingOptions: buildThinkingOptions(thinking),
|
||||||
@@ -538,21 +731,16 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
|
|||||||
modeDisplay: refineDisplay(
|
modeDisplay: refineDisplay(
|
||||||
next.modeDisplay,
|
next.modeDisplay,
|
||||||
next.modeId,
|
next.modeId,
|
||||||
(() => {
|
resolveModeLabel(modes, next.modeId),
|
||||||
const mode = modes.find((entry) => entry.id === next.modeId);
|
|
||||||
return mode ? formatAgentModeLabel(mode) : null;
|
|
||||||
})(),
|
|
||||||
),
|
),
|
||||||
thinkingDisplay: refineDisplay(
|
thinkingDisplay: refineDisplay(
|
||||||
next.thinkingDisplay,
|
next.thinkingDisplay,
|
||||||
next.thinkingOptionId,
|
next.thinkingOptionId,
|
||||||
(() => {
|
resolveThinkingLabel(thinking, next.thinkingOptionId),
|
||||||
const option = thinking.find((entry) => entry.id === next.thinkingOptionId);
|
|
||||||
return option ? formatThinkingOptionLabel(option) : null;
|
|
||||||
})(),
|
|
||||||
),
|
),
|
||||||
catalogResolution,
|
catalogResolution,
|
||||||
controlsResolution,
|
controlsResolution,
|
||||||
|
controlsPending: controlsResolution === "pending",
|
||||||
controlsRequest,
|
controlsRequest,
|
||||||
controlsRequestKey,
|
controlsRequestKey,
|
||||||
};
|
};
|
||||||
@@ -572,16 +760,40 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
|
|||||||
withOptions.provider.length > 0 &&
|
withOptions.provider.length > 0 &&
|
||||||
!withOptions.isSubmitting;
|
!withOptions.isSubmitting;
|
||||||
const resolved: AgentProfileFormState = { ...withOptions, disclosure, canSubmit };
|
const resolved: AgentProfileFormState = { ...withOptions, disclosure, canSubmit };
|
||||||
return { ...resolved, submitValue: canSubmit ? buildSubmitValue(resolved) : null };
|
const submitValue = canSubmit ? buildSubmitValue(resolved) : null;
|
||||||
|
const isDirty =
|
||||||
|
baselineFingerprint.length > 0 && formDraftFingerprint(resolved) !== baselineFingerprint;
|
||||||
|
return { ...resolved, isDirty, draftRevision, submitValue };
|
||||||
}
|
}
|
||||||
|
|
||||||
let state: AgentProfileFormState = derive(buildInitialState(snapshot));
|
let state: AgentProfileFormState = derive(buildInitialState(snapshot));
|
||||||
|
baselineFingerprint = formDraftFingerprint(state);
|
||||||
|
|
||||||
function publish(mutate: (current: AgentProfileFormState) => AgentProfileFormState): void {
|
function publish(
|
||||||
|
mutate: (current: AgentProfileFormState) => AgentProfileFormState,
|
||||||
|
options?: { userEdit?: boolean },
|
||||||
|
): void {
|
||||||
if (closed) {
|
if (closed) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
state = derive(mutate(state));
|
const previousFingerprint = formDraftFingerprint(state);
|
||||||
|
if (options?.userEdit) {
|
||||||
|
hasUserEdited = true;
|
||||||
|
}
|
||||||
|
let nextState = derive(mutate(state));
|
||||||
|
if (options?.userEdit && formDraftFingerprint(nextState) !== previousFingerprint) {
|
||||||
|
draftRevision += 1;
|
||||||
|
nextState = { ...nextState, draftRevision };
|
||||||
|
}
|
||||||
|
// Catalog hydration fills in missing provider defaults (e.g., default mode on a
|
||||||
|
// migrated favorite); refresh the clean baseline until the user makes an edit.
|
||||||
|
if (!hasUserEdited) {
|
||||||
|
baselineFingerprint = formDraftFingerprint(nextState);
|
||||||
|
if (nextState.isDirty) {
|
||||||
|
nextState = { ...nextState, isDirty: false };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
state = nextState;
|
||||||
for (const listener of listeners) {
|
for (const listener of listeners) {
|
||||||
listener();
|
listener();
|
||||||
}
|
}
|
||||||
@@ -610,6 +822,7 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
|
|||||||
}
|
}
|
||||||
resolvedControlsKey = requestKey;
|
resolvedControlsKey = requestKey;
|
||||||
resolvedScopeKey = buildControlsScopeKey(state.controlsRequest);
|
resolvedScopeKey = buildControlsScopeKey(state.controlsRequest);
|
||||||
|
resolvedProvider = state.provider || null;
|
||||||
resolvedControls = [...resolved.controls];
|
resolvedControls = [...resolved.controls];
|
||||||
resolvedOptions = resolved.options;
|
resolvedOptions = resolved.options;
|
||||||
answeredKeys = new Set(resolved.controls.map((control) => control.key));
|
answeredKeys = new Set(resolved.controls.map((control) => control.key));
|
||||||
@@ -622,66 +835,149 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
|
|||||||
}
|
}
|
||||||
resolvedControlsKey = requestKey;
|
resolvedControlsKey = requestKey;
|
||||||
resolvedScopeKey = buildControlsScopeKey(state.controlsRequest);
|
resolvedScopeKey = buildControlsScopeKey(state.controlsRequest);
|
||||||
|
resolvedProvider = state.provider || null;
|
||||||
resolvedControls = [];
|
resolvedControls = [];
|
||||||
resolvedOptions = {};
|
resolvedOptions = {};
|
||||||
publish((current) => current);
|
publish((current) => current);
|
||||||
},
|
},
|
||||||
setName: (value) => publish((current) => ({ ...current, name: value })),
|
setName: (value) =>
|
||||||
|
publish(
|
||||||
|
(current) => {
|
||||||
|
if (value !== autoSuggestedName) {
|
||||||
|
autoSuggestedName = null;
|
||||||
|
}
|
||||||
|
return { ...current, name: value };
|
||||||
|
},
|
||||||
|
{ userEdit: true },
|
||||||
|
),
|
||||||
setAppearance: (value) =>
|
setAppearance: (value) =>
|
||||||
publish((current) => ({ ...current, icon: value.icon, color: value.color })),
|
publish((current) => ({ ...current, icon: value.icon, color: value.color }), {
|
||||||
setNotes: (value) => publish((current) => ({ ...current, notes: value })),
|
userEdit: true,
|
||||||
|
}),
|
||||||
|
setNotes: (value) => publish((current) => ({ ...current, notes: value }), { userEdit: true }),
|
||||||
setProvider: (providerId, display) =>
|
setProvider: (providerId, display) =>
|
||||||
publish((current) => {
|
publish(
|
||||||
if (current.provider === providerId) {
|
(current) => {
|
||||||
return current;
|
if (current.provider === providerId) {
|
||||||
}
|
return current;
|
||||||
// Everything below the provider is provider-scoped: a model id, mode id,
|
}
|
||||||
// thinking id or feature id from the old provider means nothing here.
|
// Everything below the provider is provider-scoped: a model id, mode id,
|
||||||
// Clearing them is enough — `derive` seeds the new provider's defaults.
|
// thinking id or feature id from the old provider means nothing here.
|
||||||
drawnKeys = new Set();
|
// Clearing them is enough — `derive` seeds the new provider's defaults.
|
||||||
answeredKeys = new Set();
|
drawnKeys = new Set();
|
||||||
return {
|
answeredKeys = new Set();
|
||||||
...current,
|
resolvedProvider = null;
|
||||||
provider: providerId,
|
resolvedScopeKey = null;
|
||||||
providerDisplay: display,
|
resolvedControlsKey = null;
|
||||||
modelId: "",
|
resolvedControls = [];
|
||||||
modelDisplay: null,
|
resolvedOptions = {};
|
||||||
modeId: "",
|
return {
|
||||||
modeDisplay: null,
|
...current,
|
||||||
thinkingOptionId: "",
|
provider: providerId,
|
||||||
thinkingDisplay: null,
|
providerDisplay: display,
|
||||||
options: {},
|
modelId: "",
|
||||||
optionEdits: {},
|
modelDisplay: null,
|
||||||
};
|
modeId: "",
|
||||||
}),
|
modeDisplay: null,
|
||||||
|
thinkingOptionId: "",
|
||||||
|
thinkingDisplay: null,
|
||||||
|
options: {},
|
||||||
|
optionEdits: {},
|
||||||
|
};
|
||||||
|
},
|
||||||
|
{ userEdit: true },
|
||||||
|
),
|
||||||
|
setProviderModel: (providerId, modelId, displays) =>
|
||||||
|
publish(
|
||||||
|
(current) => {
|
||||||
|
const providerChanged = current.provider !== providerId;
|
||||||
|
const modelChanged = current.modelId !== modelId;
|
||||||
|
if (!providerChanged && !modelChanged) {
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
const suggested = displays.model?.label ?? displays.provider.label;
|
||||||
|
const shouldAutoName =
|
||||||
|
current.mode === "create" &&
|
||||||
|
(current.name.trim().length === 0 ||
|
||||||
|
(autoSuggestedName !== null && current.name === autoSuggestedName));
|
||||||
|
const nextName = shouldAutoName ? suggested : current.name;
|
||||||
|
if (shouldAutoName) {
|
||||||
|
autoSuggestedName = suggested;
|
||||||
|
}
|
||||||
|
if (providerChanged) {
|
||||||
|
drawnKeys = new Set();
|
||||||
|
answeredKeys = new Set();
|
||||||
|
resolvedProvider = null;
|
||||||
|
resolvedScopeKey = null;
|
||||||
|
resolvedControlsKey = null;
|
||||||
|
resolvedControls = [];
|
||||||
|
resolvedOptions = {};
|
||||||
|
return {
|
||||||
|
...current,
|
||||||
|
name: nextName,
|
||||||
|
provider: providerId,
|
||||||
|
providerDisplay: displays.provider,
|
||||||
|
modelId,
|
||||||
|
modelDisplay: displays.model,
|
||||||
|
modeId: "",
|
||||||
|
modeDisplay: null,
|
||||||
|
thinkingOptionId: "",
|
||||||
|
thinkingDisplay: null,
|
||||||
|
options: {},
|
||||||
|
optionEdits: {},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const nextThinking = resolveThinkingOptions(entries, current.provider, modelId);
|
||||||
|
const keepsThinking =
|
||||||
|
current.thinkingOptionId.length > 0 &&
|
||||||
|
nextThinking.some((option) => option.id === current.thinkingOptionId);
|
||||||
|
return {
|
||||||
|
...current,
|
||||||
|
name: nextName,
|
||||||
|
modelId,
|
||||||
|
modelDisplay: displays.model,
|
||||||
|
thinkingOptionId: keepsThinking ? current.thinkingOptionId : "",
|
||||||
|
thinkingDisplay: keepsThinking ? current.thinkingDisplay : null,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
{ userEdit: true },
|
||||||
|
),
|
||||||
setModel: (modelId, display) =>
|
setModel: (modelId, display) =>
|
||||||
publish((current) => {
|
publish(
|
||||||
if (current.modelId === modelId) {
|
(current) => {
|
||||||
return current;
|
if (current.modelId === modelId) {
|
||||||
}
|
return current;
|
||||||
// Thinking options are a property of the model, so a level the new model
|
}
|
||||||
// does not offer has to go.
|
// Thinking options are a property of the model, so a level the new model
|
||||||
const nextThinking = resolveThinkingOptions(entries, current.provider, modelId);
|
// does not offer has to go.
|
||||||
const keepsThinking =
|
const nextThinking = resolveThinkingOptions(entries, current.provider, modelId);
|
||||||
current.thinkingOptionId.length > 0 &&
|
const keepsThinking =
|
||||||
nextThinking.some((option) => option.id === current.thinkingOptionId);
|
current.thinkingOptionId.length > 0 &&
|
||||||
return {
|
nextThinking.some((option) => option.id === current.thinkingOptionId);
|
||||||
...current,
|
return {
|
||||||
modelId,
|
...current,
|
||||||
modelDisplay: display,
|
modelId,
|
||||||
thinkingOptionId: keepsThinking ? current.thinkingOptionId : "",
|
modelDisplay: display,
|
||||||
thinkingDisplay: keepsThinking ? current.thinkingDisplay : null,
|
thinkingOptionId: keepsThinking ? current.thinkingOptionId : "",
|
||||||
};
|
thinkingDisplay: keepsThinking ? current.thinkingDisplay : null,
|
||||||
}),
|
};
|
||||||
|
},
|
||||||
|
{ userEdit: true },
|
||||||
|
),
|
||||||
setMode: (modeId, display) =>
|
setMode: (modeId, display) =>
|
||||||
publish((current) => ({ ...current, modeId, modeDisplay: display })),
|
publish((current) => ({ ...current, modeId, modeDisplay: display }), { userEdit: true }),
|
||||||
setThinking: (thinkingOptionId, display) =>
|
setThinking: (thinkingOptionId, display) =>
|
||||||
publish((current) => ({ ...current, thinkingOptionId, thinkingDisplay: display })),
|
publish((current) => ({ ...current, thinkingOptionId, thinkingDisplay: display }), {
|
||||||
|
userEdit: true,
|
||||||
|
}),
|
||||||
setOption: (key, value) =>
|
setOption: (key, value) =>
|
||||||
publish((current) => ({
|
publish(
|
||||||
...current,
|
(current) => ({
|
||||||
optionEdits: { ...current.optionEdits, [key]: value },
|
...current,
|
||||||
})),
|
optionEdits: { ...current.optionEdits, [key]: value },
|
||||||
|
}),
|
||||||
|
{ userEdit: true },
|
||||||
|
),
|
||||||
setSubmitting: (value) => publish((current) => ({ ...current, isSubmitting: value })),
|
setSubmitting: (value) => publish((current) => ({ ...current, isSubmitting: value })),
|
||||||
setSubmitError: (value) => publish((current) => ({ ...current, submitError: value })),
|
setSubmitError: (value) => publish((current) => ({ ...current, submitError: value })),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,83 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types";
|
||||||
|
import type { AgentProfile } from "@getpaseo/protocol/messages";
|
||||||
|
import { buildAgentProfileRosterSummary, formatShortModelLabel } from "./profile-summary";
|
||||||
|
|
||||||
|
const formatFeatureCount = (count: number) => `${count} option${count === 1 ? "" : "s"}`;
|
||||||
|
|
||||||
|
describe("formatShortModelLabel", () => {
|
||||||
|
it("keeps plain model names intact with no prefix", () => {
|
||||||
|
expect(formatShortModelLabel("Claude Opus 4.6")).toEqual({
|
||||||
|
prefix: null,
|
||||||
|
name: "Claude Opus 4.6",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("splits slash-qualified router model ids into prefix and short name", () => {
|
||||||
|
expect(formatShortModelLabel("openrouter/moonshotai/kimi-k3.1-pro")).toEqual({
|
||||||
|
prefix: "openrouter/moonshotai/",
|
||||||
|
name: "kimi-k3.1-pro",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ignores leading or trailing slashes", () => {
|
||||||
|
expect(formatShortModelLabel("/leading")).toEqual({ prefix: null, name: "/leading" });
|
||||||
|
expect(formatShortModelLabel("trailing/")).toEqual({ prefix: null, name: "trailing/" });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("buildAgentProfileRosterSummary", () => {
|
||||||
|
const entries: ProviderSnapshotEntry[] = [
|
||||||
|
{
|
||||||
|
provider: "opencode",
|
||||||
|
status: "ready",
|
||||||
|
enabled: true,
|
||||||
|
label: "OpenCode",
|
||||||
|
models: [
|
||||||
|
{
|
||||||
|
provider: "opencode",
|
||||||
|
id: "openrouter/moonshotai/kimi-k3.1-pro",
|
||||||
|
label: "openrouter/moonshotai/kimi-k3.1-pro",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
modes: [{ id: "build", label: "Build" }],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
it("separates short model label from provider/mode/thinking/option details", () => {
|
||||||
|
const profile: AgentProfile = {
|
||||||
|
id: "p1",
|
||||||
|
name: "Kimi fast",
|
||||||
|
provider: "opencode",
|
||||||
|
model: "openrouter/moonshotai/kimi-k3.1-pro",
|
||||||
|
modeId: "build",
|
||||||
|
thinkingOptionId: "high",
|
||||||
|
options: { fast_mode: true },
|
||||||
|
};
|
||||||
|
|
||||||
|
const summary = buildAgentProfileRosterSummary({ profile, entries, formatFeatureCount });
|
||||||
|
|
||||||
|
expect(summary.providerLabel).toBe("OpenCode");
|
||||||
|
expect(summary.modelLabel).toBe("kimi-k3.1-pro");
|
||||||
|
expect(summary.modelPrefix).toBe("openrouter/moonshotai/");
|
||||||
|
expect(summary.runtimeDetails).toEqual(["OpenCode", "Build", "High", "1 option"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("falls back to stored provider id when catalog is unavailable", () => {
|
||||||
|
const profile: AgentProfile = {
|
||||||
|
id: "p2",
|
||||||
|
name: "Offline profile",
|
||||||
|
provider: "custom-agent",
|
||||||
|
};
|
||||||
|
|
||||||
|
const summary = buildAgentProfileRosterSummary({
|
||||||
|
profile,
|
||||||
|
entries: undefined,
|
||||||
|
formatFeatureCount,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(summary.providerLabel).toBe("custom-agent");
|
||||||
|
expect(summary.modelLabel).toBeNull();
|
||||||
|
expect(summary.runtimeDetails).toEqual(["custom-agent"]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -7,6 +7,55 @@ export interface AgentProfileTag {
|
|||||||
label: string;
|
label: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ShortModelLabel {
|
||||||
|
prefix: string | null;
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Splits slash-qualified routing IDs (e.g. `openrouter/moonshotai/kimi-k3.1-pro`)
|
||||||
|
* into a quiet prefix and the model's short name so dense roster rows stay readable.
|
||||||
|
*/
|
||||||
|
export function formatShortModelLabel(modelIdOrLabel: string): ShortModelLabel {
|
||||||
|
const trimmed = modelIdOrLabel.trim();
|
||||||
|
const lastSlash = trimmed.lastIndexOf("/");
|
||||||
|
if (lastSlash <= 0 || lastSlash >= trimmed.length - 1) {
|
||||||
|
return { prefix: null, name: trimmed };
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
prefix: trimmed.slice(0, lastSlash + 1),
|
||||||
|
name: trimmed.slice(lastSlash + 1),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AgentProfileRosterSummary {
|
||||||
|
providerLabel: string;
|
||||||
|
modelLabel: string | null;
|
||||||
|
modelPrefix: string | null;
|
||||||
|
runtimeDetails: string[];
|
||||||
|
allTags: AgentProfileTag[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildAgentProfileRosterSummary(input: {
|
||||||
|
profile: AgentProfile;
|
||||||
|
entries: readonly ProviderSnapshotEntry[] | undefined;
|
||||||
|
formatFeatureCount: (count: number) => string;
|
||||||
|
}): AgentProfileRosterSummary {
|
||||||
|
const allTags = buildAgentProfileTags(input);
|
||||||
|
const providerLabel =
|
||||||
|
allTags.find((tag) => tag.id === "provider")?.label ?? input.profile.provider;
|
||||||
|
const rawModel = allTags.find((tag) => tag.id === "model")?.label ?? null;
|
||||||
|
const shortModel = rawModel ? formatShortModelLabel(rawModel) : null;
|
||||||
|
const runtimeDetails = allTags.filter((tag) => tag.id !== "model").map((tag) => tag.label);
|
||||||
|
return {
|
||||||
|
providerLabel,
|
||||||
|
modelLabel: shortModel?.name ?? null,
|
||||||
|
modelPrefix: shortModel?.prefix ?? null,
|
||||||
|
runtimeDetails,
|
||||||
|
allTags,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
function findEntry(
|
function findEntry(
|
||||||
entries: readonly ProviderSnapshotEntry[],
|
entries: readonly ProviderSnapshotEntry[],
|
||||||
provider: string,
|
provider: string,
|
||||||
|
|||||||
@@ -0,0 +1,171 @@
|
|||||||
|
import type { AgentProfile } from "@getpaseo/protocol/messages";
|
||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { createAgentProfileWriteQueue } from "./profile-write-queue";
|
||||||
|
|
||||||
|
function profile(id: string, name = id): AgentProfile {
|
||||||
|
return { id, name, provider: "claude", model: "claude-opus-5" };
|
||||||
|
}
|
||||||
|
|
||||||
|
function deferred<T>() {
|
||||||
|
let resolve!: (value: T) => void;
|
||||||
|
let reject!: (reason?: unknown) => void;
|
||||||
|
const promise = new Promise<T>((res, rej) => {
|
||||||
|
resolve = res;
|
||||||
|
reject = rej;
|
||||||
|
});
|
||||||
|
return { promise, resolve, reject };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("createAgentProfileWriteQueue", () => {
|
||||||
|
it("serializes overlapping appends on the same host so both profiles persist", async () => {
|
||||||
|
const queue = createAgentProfileWriteQueue();
|
||||||
|
let stored: AgentProfile[] = [profile("p0")];
|
||||||
|
const firstGate = deferred<void>();
|
||||||
|
const writes: string[][] = [];
|
||||||
|
|
||||||
|
const write = async (next: AgentProfile[]) => {
|
||||||
|
writes.push(next.map((entry) => entry.id));
|
||||||
|
if (writes.length === 1) {
|
||||||
|
await firstGate.promise;
|
||||||
|
}
|
||||||
|
stored = next;
|
||||||
|
return stored;
|
||||||
|
};
|
||||||
|
|
||||||
|
const first = queue.enqueue("host-a", {
|
||||||
|
readCurrent: () => stored,
|
||||||
|
write,
|
||||||
|
updater: (current) => [...current, profile("p1")],
|
||||||
|
});
|
||||||
|
const second = queue.enqueue("host-a", {
|
||||||
|
readCurrent: () => stored,
|
||||||
|
write,
|
||||||
|
updater: (current) => [...current, profile("p2")],
|
||||||
|
});
|
||||||
|
|
||||||
|
// Wait a microtask so the first write is in flight before releasing it.
|
||||||
|
await Promise.resolve();
|
||||||
|
expect(writes).toEqual([["p0", "p1"]]);
|
||||||
|
|
||||||
|
firstGate.resolve();
|
||||||
|
await expect(first).resolves.toEqual([profile("p0"), profile("p1")]);
|
||||||
|
await expect(second).resolves.toEqual([profile("p0"), profile("p1"), profile("p2")]);
|
||||||
|
expect(writes).toEqual([
|
||||||
|
["p0", "p1"],
|
||||||
|
["p0", "p1", "p2"],
|
||||||
|
]);
|
||||||
|
expect(stored.map((entry) => entry.id)).toEqual(["p0", "p1", "p2"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("removes only the undone profile when Undo overlaps another in-flight save", async () => {
|
||||||
|
const queue = createAgentProfileWriteQueue();
|
||||||
|
let stored: AgentProfile[] = [profile("p0"), profile("p1")];
|
||||||
|
const saveGate = deferred<void>();
|
||||||
|
|
||||||
|
const appendSecond = queue.enqueue("host-a", {
|
||||||
|
readCurrent: () => stored,
|
||||||
|
write: async (next) => {
|
||||||
|
await saveGate.promise;
|
||||||
|
stored = next;
|
||||||
|
return stored;
|
||||||
|
},
|
||||||
|
updater: (current) => [...current, profile("p2")],
|
||||||
|
});
|
||||||
|
|
||||||
|
const undoFirst = queue.enqueue("host-a", {
|
||||||
|
readCurrent: () => stored,
|
||||||
|
write: async (next) => {
|
||||||
|
stored = next;
|
||||||
|
return stored;
|
||||||
|
},
|
||||||
|
updater: (current) => current.filter((entry) => entry.id !== "p1"),
|
||||||
|
});
|
||||||
|
|
||||||
|
saveGate.resolve();
|
||||||
|
await appendSecond;
|
||||||
|
await undoFirst;
|
||||||
|
|
||||||
|
expect(stored.map((entry) => entry.id)).toEqual(["p0", "p2"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("recovers after a rejected write so subsequent mutations still run", async () => {
|
||||||
|
const queue = createAgentProfileWriteQueue();
|
||||||
|
let stored: AgentProfile[] = [profile("p0")];
|
||||||
|
|
||||||
|
const failing = queue.enqueue("host-a", {
|
||||||
|
readCurrent: () => stored,
|
||||||
|
write: async () => {
|
||||||
|
throw new Error("network blip");
|
||||||
|
},
|
||||||
|
updater: (current) => [...current, profile("p1")],
|
||||||
|
});
|
||||||
|
|
||||||
|
const succeeding = queue.enqueue("host-a", {
|
||||||
|
readCurrent: () => stored,
|
||||||
|
write: async (next) => {
|
||||||
|
stored = next;
|
||||||
|
return stored;
|
||||||
|
},
|
||||||
|
updater: (current) => [...current, profile("p2")],
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(failing).rejects.toThrow("network blip");
|
||||||
|
await expect(succeeding).resolves.toEqual([profile("p0"), profile("p2")]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("skips writing when current profiles are unloaded or the updater returns null", async () => {
|
||||||
|
const queue = createAgentProfileWriteQueue();
|
||||||
|
let writeCalls = 0;
|
||||||
|
|
||||||
|
const unloaded = await queue.enqueue("host-a", {
|
||||||
|
readCurrent: () => null,
|
||||||
|
write: async (next) => {
|
||||||
|
writeCalls += 1;
|
||||||
|
return next;
|
||||||
|
},
|
||||||
|
updater: (current) => [...current, profile("p1")],
|
||||||
|
});
|
||||||
|
expect(unloaded).toBeNull();
|
||||||
|
|
||||||
|
const noop = await queue.enqueue("host-a", {
|
||||||
|
readCurrent: () => [profile("p0")],
|
||||||
|
write: async (next) => {
|
||||||
|
writeCalls += 1;
|
||||||
|
return next;
|
||||||
|
},
|
||||||
|
updater: () => null,
|
||||||
|
});
|
||||||
|
expect(noop).toBeNull();
|
||||||
|
expect(writeCalls).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not block writes to a different host", async () => {
|
||||||
|
const queue = createAgentProfileWriteQueue();
|
||||||
|
const hostAGate = deferred<void>();
|
||||||
|
let hostA: AgentProfile[] = [];
|
||||||
|
let hostB: AgentProfile[] = [];
|
||||||
|
|
||||||
|
const writeA = queue.enqueue("host-a", {
|
||||||
|
readCurrent: () => hostA,
|
||||||
|
write: async (next) => {
|
||||||
|
await hostAGate.promise;
|
||||||
|
hostA = next;
|
||||||
|
return hostA;
|
||||||
|
},
|
||||||
|
updater: (current) => [...current, profile("a1")],
|
||||||
|
});
|
||||||
|
|
||||||
|
const writeB = await queue.enqueue("host-b", {
|
||||||
|
readCurrent: () => hostB,
|
||||||
|
write: async (next) => {
|
||||||
|
hostB = next;
|
||||||
|
return hostB;
|
||||||
|
},
|
||||||
|
updater: (current) => [...current, profile("b1")],
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(writeB).toEqual([profile("b1")]);
|
||||||
|
hostAGate.resolve();
|
||||||
|
await expect(writeA).resolves.toEqual([profile("a1")]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
import type { AgentProfile } from "@getpaseo/protocol/messages";
|
||||||
|
|
||||||
|
export type AgentProfileListUpdater = (current: readonly AgentProfile[]) => AgentProfile[] | null;
|
||||||
|
|
||||||
|
export interface AgentProfileWriteStep {
|
||||||
|
readCurrent: () => readonly AgentProfile[] | null;
|
||||||
|
write: (next: AgentProfile[]) => Promise<AgentProfile[]>;
|
||||||
|
updater: AgentProfileListUpdater;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AgentProfileWriteQueue {
|
||||||
|
enqueue(serverId: string, step: AgentProfileWriteStep): Promise<AgentProfile[] | null>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Removes one profile by id, returning `null` if it is already absent so callers skip no-op writes. */
|
||||||
|
export function removeAgentProfileById(
|
||||||
|
current: readonly AgentProfile[],
|
||||||
|
profileId: string,
|
||||||
|
): AgentProfile[] | null {
|
||||||
|
const next = current.filter((entry) => entry.id !== profileId);
|
||||||
|
return next.length === current.length ? null : next;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runQueuedWrite(
|
||||||
|
previous: Promise<void>,
|
||||||
|
step: AgentProfileWriteStep,
|
||||||
|
): Promise<AgentProfile[] | null> {
|
||||||
|
await previous;
|
||||||
|
const current = step.readCurrent();
|
||||||
|
if (current === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const next = step.updater(current);
|
||||||
|
if (next === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return step.write(next);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Serializes profile list writes per host so overlapping mutations (rapid composer
|
||||||
|
* `+` saves, Undo while another save is in flight, split-pane composers) each compute
|
||||||
|
* their update against the result of the previous write instead of overwriting it.
|
||||||
|
*/
|
||||||
|
export function createAgentProfileWriteQueue(): AgentProfileWriteQueue {
|
||||||
|
const tails = new Map<string, Promise<void>>();
|
||||||
|
|
||||||
|
return {
|
||||||
|
enqueue(serverId, step) {
|
||||||
|
const previous = tails.get(serverId) ?? Promise.resolve();
|
||||||
|
const result = runQueuedWrite(previous, step);
|
||||||
|
const tail = result.then(
|
||||||
|
() => undefined,
|
||||||
|
() => undefined,
|
||||||
|
);
|
||||||
|
tails.set(serverId, tail);
|
||||||
|
void tail.finally(() => {
|
||||||
|
if (tails.get(serverId) === tail) {
|
||||||
|
tails.delete(serverId);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return result;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,8 +1,21 @@
|
|||||||
import { useCallback } from "react";
|
import { useCallback, useMemo } from "react";
|
||||||
import type { AgentProfile } from "@getpaseo/protocol/messages";
|
import { useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import type { AgentProfile, MutableDaemonConfig } from "@getpaseo/protocol/messages";
|
||||||
|
import { daemonConfigQueryKey } from "@/data/daemon-config";
|
||||||
import { useDaemonConfig } from "@/hooks/use-daemon-config";
|
import { useDaemonConfig } from "@/hooks/use-daemon-config";
|
||||||
import { useSessionStore } from "@/stores/session-store";
|
import { useSessionStore } from "@/stores/session-store";
|
||||||
import { supportsAgentProfiles } from "./capabilities";
|
import { supportsAgentProfiles } from "./capabilities";
|
||||||
|
import {
|
||||||
|
createAgentProfileWriteQueue,
|
||||||
|
removeAgentProfileById,
|
||||||
|
type AgentProfileListUpdater,
|
||||||
|
} from "./profile-write-queue";
|
||||||
|
|
||||||
|
const sharedProfileWriteQueue = createAgentProfileWriteQueue();
|
||||||
|
|
||||||
|
export { removeAgentProfileById };
|
||||||
|
export type { AgentProfileListUpdater };
|
||||||
|
|
||||||
export interface UseAgentProfilesResult {
|
export interface UseAgentProfilesResult {
|
||||||
/** `null` until the daemon config has arrived. */
|
/** `null` until the daemon config has arrived. */
|
||||||
@@ -11,24 +24,56 @@ export interface UseAgentProfilesResult {
|
|||||||
isSupported: boolean;
|
isSupported: boolean;
|
||||||
/** Writes the whole list; there is no per-profile RPC. */
|
/** Writes the whole list; there is no per-profile RPC. */
|
||||||
saveProfiles: (next: AgentProfile[]) => Promise<void>;
|
saveProfiles: (next: AgentProfile[]) => Promise<void>;
|
||||||
|
/**
|
||||||
|
* Applies a serialized mutation against the latest host profile list so
|
||||||
|
* overlapping writes compose instead of overwriting each other.
|
||||||
|
*/
|
||||||
|
mutateProfiles: (updater: AgentProfileListUpdater) => Promise<AgentProfile[] | null>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useAgentProfiles(serverId: string | null): UseAgentProfilesResult {
|
export function useAgentProfiles(serverId: string | null): UseAgentProfilesResult {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const queryClient = useQueryClient();
|
||||||
const { config, patchConfig } = useDaemonConfig(serverId);
|
const { config, patchConfig } = useDaemonConfig(serverId);
|
||||||
|
const queryKey = useMemo(() => daemonConfigQueryKey(serverId), [serverId]);
|
||||||
const isSupported = useSessionStore((state) => {
|
const isSupported = useSessionStore((state) => {
|
||||||
return supportsAgentProfiles(state.sessions[serverId ?? ""]?.serverInfo?.features);
|
return supportsAgentProfiles(state.sessions[serverId ?? ""]?.serverInfo?.features);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const mutateProfiles = useCallback(
|
||||||
|
async (updater: AgentProfileListUpdater): Promise<AgentProfile[] | null> => {
|
||||||
|
if (!serverId) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return sharedProfileWriteQueue.enqueue(serverId, {
|
||||||
|
readCurrent: () => {
|
||||||
|
const cached = queryClient.getQueryData<MutableDaemonConfig>(queryKey);
|
||||||
|
return cached ? (cached.agentProfiles ?? []) : null;
|
||||||
|
},
|
||||||
|
write: async (next) => {
|
||||||
|
const updated = await patchConfig({ agentProfiles: next });
|
||||||
|
if (!updated) {
|
||||||
|
throw new Error(t("workspace.terminal.hostDisconnected"));
|
||||||
|
}
|
||||||
|
return updated.agentProfiles ?? next;
|
||||||
|
},
|
||||||
|
updater,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
[patchConfig, queryClient, queryKey, serverId, t],
|
||||||
|
);
|
||||||
|
|
||||||
const saveProfiles = useCallback(
|
const saveProfiles = useCallback(
|
||||||
async (next: AgentProfile[]) => {
|
async (next: AgentProfile[]) => {
|
||||||
await patchConfig({ agentProfiles: next });
|
await mutateProfiles(() => next);
|
||||||
},
|
},
|
||||||
[patchConfig],
|
[mutateProfiles],
|
||||||
);
|
);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
profiles: config ? (config.agentProfiles ?? []) : null,
|
profiles: config ? (config.agentProfiles ?? []) : null,
|
||||||
isSupported,
|
isSupported,
|
||||||
saveProfiles,
|
saveProfiles,
|
||||||
|
mutateProfiles,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,20 @@
|
|||||||
import { useEffect, useState, useSyncExternalStore } from "react";
|
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
|
||||||
|
import type { AgentProfile } from "@getpaseo/protocol/messages";
|
||||||
|
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
|
||||||
|
import { toErrorMessage } from "@/utils/error-messages";
|
||||||
import {
|
import {
|
||||||
openAgentProfileForm,
|
openAgentProfileForm,
|
||||||
type AgentProfileFormModel,
|
type AgentProfileFormModel,
|
||||||
type AgentProfileFormSnapshot,
|
type AgentProfileFormSnapshot,
|
||||||
type AgentProfileFormState,
|
type AgentProfileFormState,
|
||||||
|
type AgentProfileSeed,
|
||||||
|
type AgentProfileValue,
|
||||||
} from "./profile-form-model";
|
} from "./profile-form-model";
|
||||||
|
import { useAgentProfileFormCatalog, useAgentProfileFormControls } from "./use-profile-form-inputs";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* One model per mount. The modal keys its body on mode + profile id, so create
|
* One model per mount. The sheet or drawer host keys its session on mode + profile id,
|
||||||
* and edit never share an instance and reopening always starts from the record.
|
* so create and edit never share an instance and reopening always starts from the record.
|
||||||
*/
|
*/
|
||||||
export function useAgentProfileFormModel(
|
export function useAgentProfileFormModel(
|
||||||
snapshot: AgentProfileFormSnapshot,
|
snapshot: AgentProfileFormSnapshot,
|
||||||
@@ -27,3 +33,78 @@ export function useAgentProfileFormModel(
|
|||||||
export function useAgentProfileFormState(model: AgentProfileFormModel): AgentProfileFormState {
|
export function useAgentProfileFormState(model: AgentProfileFormModel): AgentProfileFormState {
|
||||||
return useSyncExternalStore(model.subscribe, model.getState, model.getState);
|
return useSyncExternalStore(model.subscribe, model.getState, model.getState);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface AgentProfileFormSession {
|
||||||
|
model: AgentProfileFormModel;
|
||||||
|
state: AgentProfileFormState;
|
||||||
|
isDirty: boolean;
|
||||||
|
save: () => Promise<boolean>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shared form session used by both the desktop inspector drawer and the modal sheet.
|
||||||
|
* Lifting this above drawer/modal framing lets responsive switches preserve unsaved edits.
|
||||||
|
*/
|
||||||
|
export function useAgentProfileFormSession({
|
||||||
|
serverId,
|
||||||
|
mode,
|
||||||
|
profile,
|
||||||
|
seed,
|
||||||
|
onSave,
|
||||||
|
onSaved,
|
||||||
|
}: {
|
||||||
|
serverId: string;
|
||||||
|
mode: "create" | "edit";
|
||||||
|
profile?: AgentProfile;
|
||||||
|
seed?: AgentProfileSeed;
|
||||||
|
onSave: (value: AgentProfileValue) => Promise<void>;
|
||||||
|
onSaved: () => void;
|
||||||
|
}): AgentProfileFormSession {
|
||||||
|
const { entries } = useProvidersSnapshot(serverId, { cwd: null });
|
||||||
|
const snapshot = useMemo<AgentProfileFormSnapshot>(
|
||||||
|
() => ({
|
||||||
|
mode,
|
||||||
|
...(profile ? { profile } : {}),
|
||||||
|
...(seed ? { seed } : {}),
|
||||||
|
...(entries ? { entries } : {}),
|
||||||
|
}),
|
||||||
|
[entries, mode, profile, seed],
|
||||||
|
);
|
||||||
|
const model = useAgentProfileFormModel(snapshot);
|
||||||
|
const state = useAgentProfileFormState(model);
|
||||||
|
useAgentProfileFormCatalog({ serverId, model });
|
||||||
|
useAgentProfileFormControls({ serverId, model, state });
|
||||||
|
const mountedRef = useRef(true);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
mountedRef.current = true;
|
||||||
|
return () => {
|
||||||
|
mountedRef.current = false;
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const save = useCallback(async (): Promise<boolean> => {
|
||||||
|
const value = model.getState().submitValue;
|
||||||
|
if (!value) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
model.setSubmitError(null);
|
||||||
|
model.setSubmitting(true);
|
||||||
|
try {
|
||||||
|
await onSave(value);
|
||||||
|
// Only notify completion while this session is still active; switching profiles
|
||||||
|
// mid-save unmounts this session and must not close the next editor's draft.
|
||||||
|
if (mountedRef.current) {
|
||||||
|
onSaved();
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
} catch (error) {
|
||||||
|
model.setSubmitError(toErrorMessage(error));
|
||||||
|
return false;
|
||||||
|
} finally {
|
||||||
|
model.setSubmitting(false);
|
||||||
|
}
|
||||||
|
}, [model, onSave, onSaved]);
|
||||||
|
|
||||||
|
return useMemo(() => ({ model, state, isDirty: state.isDirty, save }), [model, save, state]);
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,16 +1,19 @@
|
|||||||
import { useCallback, useMemo, useRef, useState, type ReactElement } from "react";
|
import { useCallback, useMemo, useRef, useState, type ReactElement } from "react";
|
||||||
import { Pressable, View, type PressableStateCallbackType } from "react-native";
|
import { View, type PressableStateCallbackType } from "react-native";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import type { TFunction } from "i18next";
|
import type { TFunction } from "i18next";
|
||||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||||
import { Check, ChevronDown } from "lucide-react-native";
|
import { Check, ChevronDown } from "lucide-react-native";
|
||||||
import { Combobox, type ComboboxOption } from "@/components/ui/combobox";
|
import { Combobox, type ComboboxOption } from "@/components/ui/combobox";
|
||||||
import {
|
import {
|
||||||
|
bySizing,
|
||||||
createControlGeometry,
|
createControlGeometry,
|
||||||
resolveControlInteractionStyles,
|
resolveControlInteractionStyles,
|
||||||
|
TOUCH_TARGET,
|
||||||
type ControlSize,
|
type ControlSize,
|
||||||
} from "@/components/ui/control-geometry";
|
} from "@/components/ui/control-geometry";
|
||||||
import { Field } from "@/components/ui/form-field";
|
import { mutedIconColorMapping } from "@/components/ui/icon-color";
|
||||||
|
import { PressHighlight } from "@/components/ui/press-highlight";
|
||||||
import { identityForeground } from "@/styles/identity-colors";
|
import { identityForeground } from "@/styles/identity-colors";
|
||||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||||
import { AgentProfileGlyph } from "../internal/agent-profile-glyph";
|
import { AgentProfileGlyph } from "../internal/agent-profile-glyph";
|
||||||
@@ -37,7 +40,6 @@ const EMPTY_COMBOBOX_OPTIONS: ComboboxOption[] = [];
|
|||||||
const ThemedChevronDown = withUnistyles(ChevronDown);
|
const ThemedChevronDown = withUnistyles(ChevronDown);
|
||||||
const ThemedCheck = withUnistyles(Check);
|
const ThemedCheck = withUnistyles(Check);
|
||||||
|
|
||||||
const foregroundMutedMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
|
|
||||||
const onIdentityMapping = (theme: Theme) => ({ color: theme.colors.background });
|
const onIdentityMapping = (theme: Theme) => ({ color: theme.colors.background });
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -56,39 +58,43 @@ function IconCell({
|
|||||||
iconKey,
|
iconKey,
|
||||||
selected,
|
selected,
|
||||||
color,
|
color,
|
||||||
|
provider,
|
||||||
|
serverId,
|
||||||
onSelect,
|
onSelect,
|
||||||
}: {
|
}: {
|
||||||
iconKey: AgentProfileIconKey | null;
|
iconKey: AgentProfileIconKey | null;
|
||||||
selected: boolean;
|
selected: boolean;
|
||||||
color: AgentProfileColor;
|
color: AgentProfileColor;
|
||||||
|
provider?: string;
|
||||||
|
serverId?: string | null;
|
||||||
onSelect: (iconKey: AgentProfileIconKey | null) => void;
|
onSelect: (iconKey: AgentProfileIconKey | null) => void;
|
||||||
}) {
|
}) {
|
||||||
const handlePress = useCallback(() => onSelect(iconKey), [iconKey, onSelect]);
|
const handlePress = useCallback(() => onSelect(iconKey), [iconKey, onSelect]);
|
||||||
const accessibilityState = useMemo(() => ({ selected }), [selected]);
|
const accessibilityState = useMemo(() => ({ selected }), [selected]);
|
||||||
const cellStyle = useCallback(
|
const cellStyle = useCallback(
|
||||||
({ hovered, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [
|
({ hovered }: PressableStateCallbackType & { hovered?: boolean }) => [
|
||||||
styles.cell,
|
styles.cell,
|
||||||
Boolean(hovered) && styles.cellHovered,
|
Boolean(hovered) && styles.cellHovered,
|
||||||
pressed && styles.cellPressed,
|
|
||||||
selected && styles.cellSelected,
|
selected && styles.cellSelected,
|
||||||
],
|
],
|
||||||
[selected],
|
[selected],
|
||||||
);
|
);
|
||||||
return (
|
return (
|
||||||
<Pressable
|
<PressHighlight
|
||||||
onPress={handlePress}
|
onPress={handlePress}
|
||||||
style={cellStyle}
|
style={cellStyle}
|
||||||
|
highlightStyle={styles.cellPressed}
|
||||||
accessibilityRole="button"
|
accessibilityRole="button"
|
||||||
accessibilityState={accessibilityState}
|
accessibilityState={accessibilityState}
|
||||||
accessibilityLabel={iconKey ?? "default"}
|
accessibilityLabel={iconKey ?? "default"}
|
||||||
testID={`agent-profile-icon-cell-${iconKey ?? "default"}`}
|
testID={`agent-profile-icon-cell-${iconKey ?? "default"}`}
|
||||||
>
|
>
|
||||||
<AgentProfileGlyph
|
<AgentProfileGlyph
|
||||||
{...(iconKey ? { icon: iconKey } : {})}
|
{...(iconKey ? { icon: iconKey } : { provider, serverId })}
|
||||||
color={color}
|
color={color}
|
||||||
size={ICON_SIZE.lg}
|
size={ICON_SIZE.lg}
|
||||||
/>
|
/>
|
||||||
</Pressable>
|
</PressHighlight>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -104,58 +110,54 @@ function ColorCell({
|
|||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const handlePress = useCallback(() => onSelect(color), [color, onSelect]);
|
const handlePress = useCallback(() => onSelect(color), [color, onSelect]);
|
||||||
const accessibilityState = useMemo(() => ({ selected }), [selected]);
|
const accessibilityState = useMemo(() => ({ selected }), [selected]);
|
||||||
const swatchStyle = useMemo(
|
|
||||||
() => [styles.swatch, color === "none" ? styles.swatchNone : identitySwatch(color)],
|
|
||||||
[color],
|
|
||||||
);
|
|
||||||
const cellStyle = useCallback(
|
|
||||||
({ pressed }: PressableStateCallbackType) => [styles.colorCell, pressed && styles.cellPressed],
|
|
||||||
[],
|
|
||||||
);
|
|
||||||
return (
|
return (
|
||||||
<Pressable
|
<PressHighlight
|
||||||
onPress={handlePress}
|
onPress={handlePress}
|
||||||
style={cellStyle}
|
style={styles.colorCell}
|
||||||
|
highlightStyle={styles.cellPressed}
|
||||||
accessibilityRole="button"
|
accessibilityRole="button"
|
||||||
accessibilityState={accessibilityState}
|
accessibilityState={accessibilityState}
|
||||||
accessibilityLabel={colorLabel(t, color)}
|
accessibilityLabel={colorLabel(t, color)}
|
||||||
testID={`agent-profile-color-cell-${color}`}
|
testID={`agent-profile-color-cell-${color}`}
|
||||||
>
|
>
|
||||||
<View style={swatchStyle}>
|
<View style={[styles.swatch, color === "none" ? styles.swatchNone : identitySwatch(color)]}>
|
||||||
{selected ? (
|
{selected ? (
|
||||||
<ThemedCheck
|
<ThemedCheck
|
||||||
size={ICON_SIZE.sm}
|
size={ICON_SIZE.sm}
|
||||||
uniProps={color === "none" ? foregroundMutedMapping : onIdentityMapping}
|
uniProps={color === "none" ? mutedIconColorMapping : onIdentityMapping}
|
||||||
/>
|
/>
|
||||||
) : null}
|
) : null}
|
||||||
</View>
|
</View>
|
||||||
</Pressable>
|
</PressHighlight>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Icon and colour in one popover rather than two fields: the pair is a single
|
* Compact clickable icon+color tile that opens the appearance popover without
|
||||||
* visual decision, and picking them apart means never seeing the result until
|
* requiring a separate labeled field box. Used inline beside the Name input
|
||||||
* both are closed. The grid redraws in the chosen colour as you switch colours,
|
* and in the inspector drawer header.
|
||||||
* so the swatch row sits above it.
|
|
||||||
*/
|
*/
|
||||||
export function AgentProfileAppearanceField({
|
export function AgentProfileIconButton({
|
||||||
label,
|
label,
|
||||||
icon,
|
icon,
|
||||||
color,
|
color,
|
||||||
|
provider,
|
||||||
|
serverId,
|
||||||
onChange,
|
onChange,
|
||||||
size = "md",
|
size = "md",
|
||||||
|
variant = "field",
|
||||||
disabled = false,
|
disabled = false,
|
||||||
testID,
|
|
||||||
triggerTestID,
|
triggerTestID,
|
||||||
}: {
|
}: {
|
||||||
label: string;
|
label: string;
|
||||||
icon: string;
|
icon: string;
|
||||||
color: string;
|
color: string;
|
||||||
|
provider?: string;
|
||||||
|
serverId?: string | null;
|
||||||
onChange: (next: { icon: string; color: string }) => void;
|
onChange: (next: { icon: string; color: string }) => void;
|
||||||
size?: ControlSize;
|
size?: ControlSize;
|
||||||
|
variant?: "field" | "hero";
|
||||||
disabled?: boolean;
|
disabled?: boolean;
|
||||||
testID?: string;
|
|
||||||
triggerTestID?: string;
|
triggerTestID?: string;
|
||||||
}): ReactElement {
|
}): ReactElement {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
@@ -188,8 +190,10 @@ export function AgentProfileAppearanceField({
|
|||||||
const triggerStyle = useCallback(
|
const triggerStyle = useCallback(
|
||||||
({ hovered, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [
|
({ hovered, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [
|
||||||
styles.trigger,
|
styles.trigger,
|
||||||
size === "sm" ? styles.triggerSm : styles.triggerMd,
|
variant === "hero" && styles.triggerHero,
|
||||||
styles.triggerIconOnly,
|
variant !== "hero" && size === "sm" && styles.triggerSm,
|
||||||
|
variant !== "hero" && size !== "sm" && styles.triggerMd,
|
||||||
|
variant === "field" && styles.triggerIconOnly,
|
||||||
resolveControlInteractionStyles(
|
resolveControlInteractionStyles(
|
||||||
{
|
{
|
||||||
controlRest: styles.controlRest,
|
controlRest: styles.controlRest,
|
||||||
@@ -200,29 +204,36 @@ export function AgentProfileAppearanceField({
|
|||||||
{ hovered: Boolean(hovered), active: pressed || open, disabled },
|
{ hovered: Boolean(hovered), active: pressed || open, disabled },
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
[disabled, open, size],
|
[disabled, open, size, variant],
|
||||||
);
|
);
|
||||||
|
|
||||||
const header = useMemo(() => ({ title: label }), [label]);
|
const header = useMemo(() => ({ title: label }), [label]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Field label={label} testID={testID}>
|
<>
|
||||||
<View ref={anchorRef} collapsable={false}>
|
<View ref={anchorRef} collapsable={false}>
|
||||||
<Pressable
|
<PressHighlight
|
||||||
onPress={handleTriggerPress}
|
onPress={handleTriggerPress}
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
style={triggerStyle}
|
style={triggerStyle}
|
||||||
|
highlightStyle={styles.triggerPressed}
|
||||||
accessibilityRole="button"
|
accessibilityRole="button"
|
||||||
accessibilityLabel={`${label} (${colorLabel(t, selectedColor)})`}
|
accessibilityLabel={`${label} (${colorLabel(t, selectedColor)})`}
|
||||||
testID={triggerTestID}
|
testID={triggerTestID}
|
||||||
>
|
>
|
||||||
<AgentProfileGlyph
|
<AgentProfileGlyph
|
||||||
{...(selectedIcon ? { icon: selectedIcon } : {})}
|
{...(selectedIcon ? { icon: selectedIcon } : { provider, serverId })}
|
||||||
color={selectedColor}
|
color={selectedColor}
|
||||||
size={ICON_SIZE.md}
|
size={variant === "hero" ? ICON_SIZE.lg : ICON_SIZE.md}
|
||||||
/>
|
/>
|
||||||
<ThemedChevronDown size={ICON_SIZE.sm} uniProps={foregroundMutedMapping} />
|
{variant === "hero" ? (
|
||||||
</Pressable>
|
<View style={styles.heroCaretBadge}>
|
||||||
|
<ThemedChevronDown size={ICON_SIZE.xs} uniProps={mutedIconColorMapping} />
|
||||||
|
</View>
|
||||||
|
) : (
|
||||||
|
<ThemedChevronDown size={ICON_SIZE.xs} uniProps={mutedIconColorMapping} />
|
||||||
|
)}
|
||||||
|
</PressHighlight>
|
||||||
</View>
|
</View>
|
||||||
<Combobox
|
<Combobox
|
||||||
options={EMPTY_COMBOBOX_OPTIONS}
|
options={EMPTY_COMBOBOX_OPTIONS}
|
||||||
@@ -251,6 +262,8 @@ export function AgentProfileAppearanceField({
|
|||||||
iconKey={null}
|
iconKey={null}
|
||||||
selected={selectedIcon === null}
|
selected={selectedIcon === null}
|
||||||
color={selectedColor}
|
color={selectedColor}
|
||||||
|
provider={provider}
|
||||||
|
serverId={serverId}
|
||||||
onSelect={handleIconSelect}
|
onSelect={handleIconSelect}
|
||||||
/>
|
/>
|
||||||
{AGENT_PROFILE_ICON_KEYS.map((key) => (
|
{AGENT_PROFILE_ICON_KEYS.map((key) => (
|
||||||
@@ -265,7 +278,7 @@ export function AgentProfileAppearanceField({
|
|||||||
</View>
|
</View>
|
||||||
</View>
|
</View>
|
||||||
</Combobox>
|
</Combobox>
|
||||||
</Field>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -279,6 +292,8 @@ function identitySwatch(color: Exclude<AgentProfileColor, "none">) {
|
|||||||
return styles[IDENTITY_SWATCH_STYLE_KEYS[color]];
|
return styles[IDENTITY_SWATCH_STYLE_KEYS[color]];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const HERO_BUTTON_SIZE = bySizing({ touch: TOUCH_TARGET, pointer: 40 });
|
||||||
|
|
||||||
const styles = StyleSheet.create((theme) => {
|
const styles = StyleSheet.create((theme) => {
|
||||||
const geometry = createControlGeometry(theme);
|
const geometry = createControlGeometry(theme);
|
||||||
|
|
||||||
@@ -292,6 +307,29 @@ const styles = StyleSheet.create((theme) => {
|
|||||||
},
|
},
|
||||||
triggerSm: { ...geometry.fieldControlSm },
|
triggerSm: { ...geometry.fieldControlSm },
|
||||||
triggerMd: { ...geometry.fieldControlMd },
|
triggerMd: { ...geometry.fieldControlMd },
|
||||||
|
triggerHero: {
|
||||||
|
width: HERO_BUTTON_SIZE,
|
||||||
|
height: HERO_BUTTON_SIZE,
|
||||||
|
borderRadius: theme.borderRadius.lg,
|
||||||
|
paddingHorizontal: 0,
|
||||||
|
position: "relative",
|
||||||
|
},
|
||||||
|
triggerPressed: {
|
||||||
|
backgroundColor: theme.colors.surface3,
|
||||||
|
},
|
||||||
|
heroCaretBadge: {
|
||||||
|
position: "absolute",
|
||||||
|
right: -theme.spacing[1],
|
||||||
|
bottom: -theme.spacing[1],
|
||||||
|
width: theme.spacing[4],
|
||||||
|
height: theme.spacing[4],
|
||||||
|
borderRadius: theme.borderRadius.full,
|
||||||
|
backgroundColor: theme.colors.surface1,
|
||||||
|
borderWidth: theme.borderWidth[1],
|
||||||
|
borderColor: theme.colors.borderAccent,
|
||||||
|
alignItems: "center",
|
||||||
|
justifyContent: "center",
|
||||||
|
},
|
||||||
// The field geometry pads for a line of text. This trigger holds a glyph and
|
// The field geometry pads for a line of text. This trigger holds a glyph and
|
||||||
// a chevron, so it keeps the shared height and drops the text-sized inset.
|
// a chevron, so it keeps the shared height and drops the text-sized inset.
|
||||||
triggerIconOnly: {
|
triggerIconOnly: {
|
||||||
@@ -339,7 +377,7 @@ const styles = StyleSheet.create((theme) => {
|
|||||||
backgroundColor: theme.colors.surface2,
|
backgroundColor: theme.colors.surface2,
|
||||||
},
|
},
|
||||||
cellPressed: {
|
cellPressed: {
|
||||||
opacity: 0.7,
|
opacity: theme.opacity[50],
|
||||||
},
|
},
|
||||||
cellSelected: {
|
cellSelected: {
|
||||||
backgroundColor: theme.colors.surface2,
|
backgroundColor: theme.colors.surface2,
|
||||||
|
|||||||
@@ -0,0 +1,503 @@
|
|||||||
|
import { useCallback, useMemo, type ReactElement } from "react";
|
||||||
|
import { Text, View } from "react-native";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { ArrowDown, ArrowUp, Copy, MoreVertical, Trash2, X } from "lucide-react-native";
|
||||||
|
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||||
|
import type { AgentProfile } from "@getpaseo/protocol/messages";
|
||||||
|
import { TitlebarDragRegion } from "@/components/desktop/titlebar-drag-region";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { DismissBackdrop } from "@/components/ui/dismiss-backdrop";
|
||||||
|
import {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuSeparator,
|
||||||
|
} from "@/components/ui/dropdown-menu";
|
||||||
|
import { mutedIconColorMapping } from "@/components/ui/icon-color";
|
||||||
|
import { ToolbarButton } from "@/components/ui/pane-content-toolbar";
|
||||||
|
import { ScrollView } from "@/components/ui/scroll-view";
|
||||||
|
import { useOverlayRegistration, type KeyboardInputEvent } from "@/keyboard";
|
||||||
|
import { OverlayLayerProvider, useOverlayLayer } from "@/lib/overlay-root";
|
||||||
|
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||||
|
import { WindowChromeRegion, WindowChromeSafeArea } from "@/utils/desktop-window";
|
||||||
|
import type { AgentProfileSeed, AgentProfileValue } from "../internal/profile-form-model";
|
||||||
|
import {
|
||||||
|
useAgentProfileFormSession,
|
||||||
|
type AgentProfileFormSession,
|
||||||
|
} from "../internal/use-profile-form-model";
|
||||||
|
import { AgentProfileIconButton } from "./agent-profile-appearance-field";
|
||||||
|
import { AgentProfileFormFields } from "./agent-profile-form-fields";
|
||||||
|
|
||||||
|
export const AGENT_PROFILE_DRAWER_WIDTH = 440;
|
||||||
|
|
||||||
|
const ThemedArrowUp = withUnistyles(ArrowUp);
|
||||||
|
const ThemedArrowDown = withUnistyles(ArrowDown);
|
||||||
|
const ThemedMoreVertical = withUnistyles(MoreVertical);
|
||||||
|
const ThemedCopy = withUnistyles(Copy);
|
||||||
|
const ThemedTrash2 = withUnistyles(Trash2);
|
||||||
|
const ThemedX = withUnistyles(X);
|
||||||
|
const destructiveIconColorMapping = (theme: Theme) => ({ color: theme.colors.destructive });
|
||||||
|
|
||||||
|
const duplicateMenuIcon = <ThemedCopy size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />;
|
||||||
|
const removeMenuIcon = <ThemedTrash2 size={ICON_SIZE.sm} uniProps={destructiveIconColorMapping} />;
|
||||||
|
|
||||||
|
export interface AgentProfileDrawerProps {
|
||||||
|
serverId: string;
|
||||||
|
mode: "create" | "edit";
|
||||||
|
profile?: AgentProfile;
|
||||||
|
seed?: AgentProfileSeed;
|
||||||
|
/** Optional pre-owned session so resizing between drawer and modal preserves unsaved edits. */
|
||||||
|
session?: AgentProfileFormSession;
|
||||||
|
/** Renders as an absolute right-edge slide-over instead of reflowing the roster beside it. */
|
||||||
|
overlay?: boolean;
|
||||||
|
canStepPrev?: boolean;
|
||||||
|
canStepNext?: boolean;
|
||||||
|
onStepPrev?: () => void;
|
||||||
|
onStepNext?: () => void;
|
||||||
|
onClose: () => void;
|
||||||
|
onSave: (value: AgentProfileValue) => Promise<void>;
|
||||||
|
onDuplicate?: (profileId: string) => void;
|
||||||
|
onRemove?: (profileId: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Full-height right inspector drawer for creating and editing agent profiles.
|
||||||
|
* Pinned header + independent scroll + pinned footer prevent vertical re-centering
|
||||||
|
* when async provider options resolve.
|
||||||
|
*/
|
||||||
|
export function AgentProfileDrawer(props: AgentProfileDrawerProps): ReactElement {
|
||||||
|
if (props.session) {
|
||||||
|
return <AgentProfileDrawerContent {...props} session={props.session} />;
|
||||||
|
}
|
||||||
|
const key =
|
||||||
|
props.mode === "edit"
|
||||||
|
? `drawer-edit:${props.profile?.id ?? ""}`
|
||||||
|
: `drawer-create:${props.seed?.provider ?? ""}:${props.seed?.modelId ?? ""}`;
|
||||||
|
return <StandaloneAgentProfileDrawer key={key} {...props} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function StandaloneAgentProfileDrawer(props: AgentProfileDrawerProps): ReactElement {
|
||||||
|
const session = useAgentProfileFormSession({
|
||||||
|
serverId: props.serverId,
|
||||||
|
mode: props.mode,
|
||||||
|
profile: props.profile,
|
||||||
|
seed: props.seed,
|
||||||
|
onSave: props.onSave,
|
||||||
|
onSaved: props.onClose,
|
||||||
|
});
|
||||||
|
return <AgentProfileDrawerContent {...props} session={session} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function DrawerOverflowMenu({
|
||||||
|
profileName,
|
||||||
|
disabled,
|
||||||
|
onDuplicate,
|
||||||
|
onRemove,
|
||||||
|
}: {
|
||||||
|
profileName: string;
|
||||||
|
disabled: boolean;
|
||||||
|
onDuplicate?: () => void;
|
||||||
|
onRemove?: () => void;
|
||||||
|
}): ReactElement | null {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
if (!onDuplicate && !onRemove) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<DropdownMenu compactMode="sheet">
|
||||||
|
<ToolbarButton
|
||||||
|
kind="menu"
|
||||||
|
label={t("settings.host.agentProfiles.profileActions", { name: profileName })}
|
||||||
|
disabled={disabled}
|
||||||
|
testID="agent-profile-drawer-more"
|
||||||
|
>
|
||||||
|
<ThemedMoreVertical size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />
|
||||||
|
</ToolbarButton>
|
||||||
|
<DropdownMenuContent side="bottom" align="end" width={180}>
|
||||||
|
{onDuplicate ? (
|
||||||
|
<DropdownMenuItem
|
||||||
|
leading={duplicateMenuIcon}
|
||||||
|
onSelect={onDuplicate}
|
||||||
|
testID="agent-profile-drawer-duplicate"
|
||||||
|
>
|
||||||
|
{t("settings.host.agentProfiles.duplicate")}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
) : null}
|
||||||
|
{onDuplicate && onRemove ? <DropdownMenuSeparator /> : null}
|
||||||
|
{onRemove ? (
|
||||||
|
<DropdownMenuItem
|
||||||
|
destructive
|
||||||
|
leading={removeMenuIcon}
|
||||||
|
onSelect={onRemove}
|
||||||
|
testID="agent-profile-drawer-remove"
|
||||||
|
>
|
||||||
|
{t("settings.host.agentProfiles.remove")}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
) : null}
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function DrawerHeader({
|
||||||
|
serverId,
|
||||||
|
mode,
|
||||||
|
state,
|
||||||
|
canStepPrev,
|
||||||
|
canStepNext,
|
||||||
|
onStepPrev,
|
||||||
|
onStepNext,
|
||||||
|
onDuplicate,
|
||||||
|
onRemove,
|
||||||
|
onAppearanceChange,
|
||||||
|
onClose,
|
||||||
|
}: {
|
||||||
|
serverId: string;
|
||||||
|
mode: "create" | "edit";
|
||||||
|
state: AgentProfileFormSession["state"];
|
||||||
|
canStepPrev: boolean;
|
||||||
|
canStepNext: boolean;
|
||||||
|
onStepPrev?: () => void;
|
||||||
|
onStepNext?: () => void;
|
||||||
|
onDuplicate?: () => void;
|
||||||
|
onRemove?: () => void;
|
||||||
|
onAppearanceChange: (value: { icon: string; color: string }) => void;
|
||||||
|
onClose: () => void;
|
||||||
|
}): ReactElement {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const fallbackTitle =
|
||||||
|
mode === "edit"
|
||||||
|
? t("settings.host.agentProfiles.editProfileTitle")
|
||||||
|
: t("settings.host.agentProfiles.addProfileTitle");
|
||||||
|
const title = state.name.trim() || fallbackTitle;
|
||||||
|
const parts = [state.providerDisplay?.label, state.modelDisplay?.label].filter(Boolean);
|
||||||
|
const subtitle =
|
||||||
|
parts.length > 0 ? parts.join(" · ") : t("settings.host.agentProfiles.chooseModelPlaceholder");
|
||||||
|
const showSteppers = mode === "edit" && Boolean(onStepPrev && onStepNext);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<View style={styles.headerChrome}>
|
||||||
|
<TitlebarDragRegion />
|
||||||
|
<WindowChromeSafeArea placement="below" />
|
||||||
|
<View style={styles.header}>
|
||||||
|
<View style={styles.headerIdentity}>
|
||||||
|
<AgentProfileIconButton
|
||||||
|
label={t("settings.host.agentProfiles.iconLabel")}
|
||||||
|
icon={state.icon}
|
||||||
|
color={state.color}
|
||||||
|
provider={state.provider || undefined}
|
||||||
|
serverId={serverId}
|
||||||
|
onChange={onAppearanceChange}
|
||||||
|
variant="hero"
|
||||||
|
disabled={state.isSubmitting}
|
||||||
|
triggerTestID="agent-profile-icon-trigger"
|
||||||
|
/>
|
||||||
|
<View style={styles.headerText}>
|
||||||
|
<Text style={styles.headerTitle} numberOfLines={1} testID="agent-profile-drawer-title">
|
||||||
|
{title}
|
||||||
|
</Text>
|
||||||
|
<Text style={styles.headerSubtitle} numberOfLines={1}>
|
||||||
|
{subtitle}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
<View style={styles.headerActions}>
|
||||||
|
{showSteppers && onStepPrev && onStepNext ? (
|
||||||
|
<>
|
||||||
|
<ToolbarButton
|
||||||
|
label={t("settings.host.agentProfiles.previousProfile")}
|
||||||
|
onPress={onStepPrev}
|
||||||
|
disabled={!canStepPrev || state.isSubmitting}
|
||||||
|
testID="agent-profile-drawer-prev"
|
||||||
|
>
|
||||||
|
<ThemedArrowUp size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />
|
||||||
|
</ToolbarButton>
|
||||||
|
<ToolbarButton
|
||||||
|
label={t("settings.host.agentProfiles.nextProfile")}
|
||||||
|
onPress={onStepNext}
|
||||||
|
disabled={!canStepNext || state.isSubmitting}
|
||||||
|
testID="agent-profile-drawer-next"
|
||||||
|
>
|
||||||
|
<ThemedArrowDown size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />
|
||||||
|
</ToolbarButton>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
{mode === "edit" ? (
|
||||||
|
<DrawerOverflowMenu
|
||||||
|
profileName={title}
|
||||||
|
disabled={state.isSubmitting}
|
||||||
|
onDuplicate={onDuplicate}
|
||||||
|
onRemove={onRemove}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
<ToolbarButton
|
||||||
|
label={t("common.actions.close")}
|
||||||
|
onPress={onClose}
|
||||||
|
disabled={state.isSubmitting}
|
||||||
|
testID="agent-profile-drawer-close"
|
||||||
|
>
|
||||||
|
<ThemedX size={ICON_SIZE.md} uniProps={mutedIconColorMapping} />
|
||||||
|
</ToolbarButton>
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function DrawerFooter({
|
||||||
|
canSubmit,
|
||||||
|
isSubmitting,
|
||||||
|
onClose,
|
||||||
|
onSave,
|
||||||
|
}: {
|
||||||
|
canSubmit: boolean;
|
||||||
|
isSubmitting: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
onSave: () => void;
|
||||||
|
}): ReactElement {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
return (
|
||||||
|
<View style={styles.footer}>
|
||||||
|
<Button
|
||||||
|
variant="secondary"
|
||||||
|
onPress={onClose}
|
||||||
|
disabled={isSubmitting}
|
||||||
|
testID="agent-profile-cancel-button"
|
||||||
|
>
|
||||||
|
{t("common.actions.cancel")}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="default"
|
||||||
|
onPress={onSave}
|
||||||
|
disabled={!canSubmit}
|
||||||
|
loading={isSubmitting}
|
||||||
|
testID="agent-profile-save-button"
|
||||||
|
>
|
||||||
|
{t("settings.host.agentProfiles.save")}
|
||||||
|
</Button>
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function AgentProfileDrawerContent({
|
||||||
|
serverId,
|
||||||
|
mode,
|
||||||
|
profile,
|
||||||
|
session,
|
||||||
|
overlay = false,
|
||||||
|
canStepPrev = false,
|
||||||
|
canStepNext = false,
|
||||||
|
onStepPrev,
|
||||||
|
onStepNext,
|
||||||
|
onClose,
|
||||||
|
onDuplicate,
|
||||||
|
onRemove,
|
||||||
|
}: AgentProfileDrawerProps & { session: AgentProfileFormSession }): ReactElement {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const { model, state, save } = session;
|
||||||
|
const drawerLayer = useOverlayLayer("floating");
|
||||||
|
|
||||||
|
const handleOverlayKeyDown = useCallback(
|
||||||
|
(event: KeyboardInputEvent) => {
|
||||||
|
if (event.key !== "Escape") {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopPropagation();
|
||||||
|
if (!state.isSubmitting) {
|
||||||
|
onClose();
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
},
|
||||||
|
[onClose, state.isSubmitting],
|
||||||
|
);
|
||||||
|
|
||||||
|
const setOverlayScope = useOverlayRegistration({
|
||||||
|
keys: ["Escape"],
|
||||||
|
active: true,
|
||||||
|
layer: drawerLayer,
|
||||||
|
// Only trap focus in slide-over overlay mode; a docked drawer sits beside the
|
||||||
|
// interactive roster and must let users click and type in roster search.
|
||||||
|
manageFocus: overlay,
|
||||||
|
onKeyDown: handleOverlayKeyDown,
|
||||||
|
});
|
||||||
|
|
||||||
|
const handleAppearanceChange = useCallback(
|
||||||
|
(value: { icon: string; color: string }) => model.setAppearance(value),
|
||||||
|
[model],
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleSavePress = useCallback(() => {
|
||||||
|
void save();
|
||||||
|
}, [save]);
|
||||||
|
|
||||||
|
const handleDuplicate = useCallback(() => {
|
||||||
|
if (profile && onDuplicate) {
|
||||||
|
onDuplicate(profile.id);
|
||||||
|
}
|
||||||
|
}, [onDuplicate, profile]);
|
||||||
|
|
||||||
|
const handleRemove = useCallback(() => {
|
||||||
|
if (profile && onRemove) {
|
||||||
|
onRemove(profile.id);
|
||||||
|
}
|
||||||
|
}, [onRemove, profile]);
|
||||||
|
|
||||||
|
const handleBackdropPress = useCallback(() => {
|
||||||
|
if (!state.isSubmitting) {
|
||||||
|
onClose();
|
||||||
|
}
|
||||||
|
}, [onClose, state.isSubmitting]);
|
||||||
|
|
||||||
|
const drawerStyle = useMemo(
|
||||||
|
() => [styles.drawer, overlay && styles.drawerOverlay, overlay && { zIndex: drawerLayer }],
|
||||||
|
[drawerLayer, overlay],
|
||||||
|
);
|
||||||
|
const overlayHostStyle = useMemo(
|
||||||
|
() => [styles.overlayHost, { zIndex: drawerLayer }],
|
||||||
|
[drawerLayer],
|
||||||
|
);
|
||||||
|
|
||||||
|
const drawerPanel = (
|
||||||
|
<WindowChromeRegion corners="top-right">
|
||||||
|
<OverlayLayerProvider layer={drawerLayer}>
|
||||||
|
<View ref={setOverlayScope} style={drawerStyle} testID="agent-profile-drawer">
|
||||||
|
<DrawerHeader
|
||||||
|
serverId={serverId}
|
||||||
|
mode={mode}
|
||||||
|
state={state}
|
||||||
|
canStepPrev={canStepPrev}
|
||||||
|
canStepNext={canStepNext}
|
||||||
|
onStepPrev={onStepPrev}
|
||||||
|
onStepNext={onStepNext}
|
||||||
|
onDuplicate={profile && onDuplicate ? handleDuplicate : undefined}
|
||||||
|
onRemove={profile && onRemove ? handleRemove : undefined}
|
||||||
|
onAppearanceChange={handleAppearanceChange}
|
||||||
|
onClose={onClose}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<ScrollView style={styles.scroll} keyboardShouldPersistTaps="handled">
|
||||||
|
<View style={styles.scrollContent}>
|
||||||
|
<AgentProfileFormFields
|
||||||
|
serverId={serverId}
|
||||||
|
model={model}
|
||||||
|
state={state}
|
||||||
|
showInlineIcon={false}
|
||||||
|
collapsibleDefaults={false}
|
||||||
|
/>
|
||||||
|
</View>
|
||||||
|
</ScrollView>
|
||||||
|
|
||||||
|
<DrawerFooter
|
||||||
|
canSubmit={state.canSubmit}
|
||||||
|
isSubmitting={state.isSubmitting}
|
||||||
|
onClose={onClose}
|
||||||
|
onSave={handleSavePress}
|
||||||
|
/>
|
||||||
|
</View>
|
||||||
|
</OverlayLayerProvider>
|
||||||
|
</WindowChromeRegion>
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!overlay) {
|
||||||
|
return drawerPanel;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<View style={overlayHostStyle} pointerEvents="box-none">
|
||||||
|
<View style={styles.overlayBackdrop} pointerEvents="none" />
|
||||||
|
<DismissBackdrop label={t("common.actions.close")} onPress={handleBackdropPress} />
|
||||||
|
{drawerPanel}
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const styles = StyleSheet.create((theme) => ({
|
||||||
|
overlayHost: {
|
||||||
|
position: "absolute",
|
||||||
|
top: 0,
|
||||||
|
right: 0,
|
||||||
|
bottom: 0,
|
||||||
|
left: 0,
|
||||||
|
flexDirection: "row",
|
||||||
|
justifyContent: "flex-end",
|
||||||
|
},
|
||||||
|
overlayBackdrop: {
|
||||||
|
position: "absolute",
|
||||||
|
top: 0,
|
||||||
|
right: 0,
|
||||||
|
bottom: 0,
|
||||||
|
left: 0,
|
||||||
|
backgroundColor: theme.colors.background,
|
||||||
|
opacity: theme.opacity[50],
|
||||||
|
},
|
||||||
|
drawer: {
|
||||||
|
width: AGENT_PROFILE_DRAWER_WIDTH,
|
||||||
|
flexShrink: 0,
|
||||||
|
backgroundColor: theme.colors.surface0,
|
||||||
|
borderLeftWidth: theme.borderWidth[1],
|
||||||
|
borderLeftColor: theme.colors.borderAccent,
|
||||||
|
},
|
||||||
|
drawerOverlay: {
|
||||||
|
height: "100%",
|
||||||
|
...theme.shadow.lg,
|
||||||
|
},
|
||||||
|
headerChrome: {
|
||||||
|
position: "relative",
|
||||||
|
borderBottomWidth: theme.borderWidth[1],
|
||||||
|
borderBottomColor: theme.colors.border,
|
||||||
|
},
|
||||||
|
header: {
|
||||||
|
flexDirection: "row",
|
||||||
|
alignItems: "center",
|
||||||
|
justifyContent: "space-between",
|
||||||
|
gap: theme.spacing[3],
|
||||||
|
paddingHorizontal: theme.spacing[4],
|
||||||
|
paddingVertical: theme.spacing[4],
|
||||||
|
},
|
||||||
|
headerIdentity: {
|
||||||
|
flex: 1,
|
||||||
|
minWidth: 0,
|
||||||
|
flexDirection: "row",
|
||||||
|
alignItems: "center",
|
||||||
|
gap: theme.spacing[3],
|
||||||
|
},
|
||||||
|
headerText: {
|
||||||
|
flex: 1,
|
||||||
|
minWidth: 0,
|
||||||
|
gap: theme.spacing[0.5],
|
||||||
|
},
|
||||||
|
headerTitle: {
|
||||||
|
color: theme.colors.foreground,
|
||||||
|
fontSize: theme.fontSize.base,
|
||||||
|
fontWeight: theme.fontWeight.medium,
|
||||||
|
},
|
||||||
|
headerSubtitle: {
|
||||||
|
color: theme.colors.foregroundMuted,
|
||||||
|
fontSize: theme.fontSize.sm,
|
||||||
|
},
|
||||||
|
headerActions: {
|
||||||
|
flexDirection: "row",
|
||||||
|
alignItems: "center",
|
||||||
|
gap: theme.spacing[1],
|
||||||
|
flexShrink: 0,
|
||||||
|
},
|
||||||
|
scroll: {
|
||||||
|
flex: 1,
|
||||||
|
},
|
||||||
|
scrollContent: {
|
||||||
|
padding: theme.spacing[4],
|
||||||
|
paddingBottom: theme.spacing[8],
|
||||||
|
},
|
||||||
|
footer: {
|
||||||
|
flexDirection: "row",
|
||||||
|
alignItems: "center",
|
||||||
|
justifyContent: "flex-end",
|
||||||
|
gap: theme.spacing[2],
|
||||||
|
paddingHorizontal: theme.spacing[4],
|
||||||
|
paddingVertical: theme.spacing[3],
|
||||||
|
borderTopWidth: theme.borderWidth[1],
|
||||||
|
borderTopColor: theme.colors.border,
|
||||||
|
backgroundColor: theme.colors.surface0,
|
||||||
|
},
|
||||||
|
}));
|
||||||
@@ -1,36 +1,16 @@
|
|||||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactElement } from "react";
|
import { useCallback, useEffect, useMemo, useRef, useState, type ReactElement } from "react";
|
||||||
import { Text, View } from "react-native";
|
import { View } from "react-native";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { StyleSheet } from "react-native-unistyles";
|
import { StyleSheet } from "react-native-unistyles";
|
||||||
import type { AgentOptionControl, ProviderOptions } from "@getpaseo/protocol/agent-types";
|
|
||||||
import { readSelectOption, readToggleOption } from "@/agent-controls/option-controls";
|
|
||||||
import type { AgentProfile } from "@getpaseo/protocol/messages";
|
import type { AgentProfile } from "@getpaseo/protocol/messages";
|
||||||
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
|
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { type ControlSize } from "@/components/ui/control-geometry";
|
import type { AgentProfileSeed, AgentProfileValue } from "../internal/profile-form-model";
|
||||||
import { Field, FormTextInput } from "@/components/ui/form-field";
|
|
||||||
import {
|
import {
|
||||||
SelectField,
|
useAgentProfileFormSession,
|
||||||
type SelectFieldDisplay,
|
type AgentProfileFormSession,
|
||||||
type SelectFieldOption,
|
|
||||||
} from "@/components/ui/select-field";
|
|
||||||
import { Switch } from "@/components/ui/switch";
|
|
||||||
import { toErrorMessage } from "@/utils/error-messages";
|
|
||||||
import { AgentProfileAppearanceField } from "./agent-profile-appearance-field";
|
|
||||||
import type {
|
|
||||||
AgentProfileFormModel,
|
|
||||||
AgentProfileFormOption,
|
|
||||||
AgentProfileSeed,
|
|
||||||
AgentProfileValue,
|
|
||||||
} from "../internal/profile-form-model";
|
|
||||||
import {
|
|
||||||
useAgentProfileFormCatalog,
|
|
||||||
useAgentProfileFormControls,
|
|
||||||
} from "../internal/use-profile-form-inputs";
|
|
||||||
import {
|
|
||||||
useAgentProfileFormModel,
|
|
||||||
useAgentProfileFormState,
|
|
||||||
} from "../internal/use-profile-form-model";
|
} from "../internal/use-profile-form-model";
|
||||||
|
import { AgentProfileFormFields } from "./agent-profile-form-fields";
|
||||||
|
|
||||||
export interface AgentProfileEditModalProps {
|
export interface AgentProfileEditModalProps {
|
||||||
serverId: string;
|
serverId: string;
|
||||||
@@ -38,16 +18,15 @@ export interface AgentProfileEditModalProps {
|
|||||||
mode: "create" | "edit";
|
mode: "create" | "edit";
|
||||||
profile?: AgentProfile;
|
profile?: AgentProfile;
|
||||||
seed?: AgentProfileSeed;
|
seed?: AgentProfileSeed;
|
||||||
|
/** Optional pre-owned session so resizing between drawer and modal preserves unsaved edits. */
|
||||||
|
session?: AgentProfileFormSession;
|
||||||
|
/** Starts create mode with Mode, Thinking, Notes & Options collapsed behind a summary row. */
|
||||||
|
collapsibleDefaults?: boolean;
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
onSave: (value: AgentProfileValue) => Promise<void>;
|
onSave: (value: AgentProfileValue) => Promise<void>;
|
||||||
|
onRemove?: (profileId: string) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Only reachable before the catalog lands. Every select is seeded to a concrete
|
|
||||||
* id as soon as one exists, and none of them offer an "unset" row.
|
|
||||||
*/
|
|
||||||
const UNSET_VALUE = "";
|
|
||||||
|
|
||||||
function openKey(props: AgentProfileEditModalProps): string {
|
function openKey(props: AgentProfileEditModalProps): string {
|
||||||
if (props.mode === "edit") {
|
if (props.mode === "edit") {
|
||||||
return `edit:${props.profile?.id ?? ""}`;
|
return `edit:${props.profile?.id ?? ""}`;
|
||||||
@@ -57,7 +36,11 @@ function openKey(props: AgentProfileEditModalProps): string {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Create and edit never share a mounted instance: the body is keyed on mode plus
|
* Create and edit never share a mounted instance: the body is keyed on mode plus
|
||||||
* profile id, so every open constructs a form model seeded from that record.
|
* profile id (unless the caller lifts `session`), so every open constructs a form
|
||||||
|
* model seeded from that record.
|
||||||
|
*
|
||||||
|
* Used for editing from the composer model picker and on compact/narrow screens
|
||||||
|
* where Settings cannot host a slide-over drawer.
|
||||||
*/
|
*/
|
||||||
export function AgentProfileEditModal(props: AgentProfileEditModalProps): ReactElement | null {
|
export function AgentProfileEditModal(props: AgentProfileEditModalProps): ReactElement | null {
|
||||||
const [renderedProps, setRenderedProps] = useState<AgentProfileEditModalProps | null>(() =>
|
const [renderedProps, setRenderedProps] = useState<AgentProfileEditModalProps | null>(() =>
|
||||||
@@ -101,10 +84,24 @@ export function AgentProfileEditModal(props: AgentProfileEditModalProps): ReactE
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const activeProps = props.visible ? props : renderedProps;
|
||||||
|
|
||||||
|
if (activeProps.session) {
|
||||||
|
return (
|
||||||
|
<AgentProfileEditModalContent
|
||||||
|
{...activeProps}
|
||||||
|
session={activeProps.session}
|
||||||
|
visible={sheetVisible}
|
||||||
|
onClose={requestClose}
|
||||||
|
onDismiss={handleDismiss}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<OpenAgentProfileEditModal
|
<StandaloneAgentProfileEditModal
|
||||||
key={openKey(renderedProps)}
|
key={openKey(activeProps)}
|
||||||
{...renderedProps}
|
{...activeProps}
|
||||||
visible={sheetVisible}
|
visible={sheetVisible}
|
||||||
onClose={requestClose}
|
onClose={requestClose}
|
||||||
onDismiss={handleDismiss}
|
onDismiss={handleDismiss}
|
||||||
@@ -112,36 +109,36 @@ export function AgentProfileEditModal(props: AgentProfileEditModalProps): ReactE
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function toSelectOptions(options: AgentProfileFormOption[]): SelectFieldOption<string>[] {
|
function StandaloneAgentProfileEditModal(
|
||||||
return options.map((option) => ({
|
props: AgentProfileEditModalProps & { onDismiss: () => void },
|
||||||
id: option.id,
|
): ReactElement {
|
||||||
value: option.value,
|
const session = useAgentProfileFormSession({
|
||||||
label: option.label,
|
serverId: props.serverId,
|
||||||
...(option.description ? { description: option.description } : {}),
|
mode: props.mode,
|
||||||
testID: option.testID,
|
profile: props.profile,
|
||||||
}));
|
seed: props.seed,
|
||||||
|
onSave: props.onSave,
|
||||||
|
onSaved: props.onClose,
|
||||||
|
});
|
||||||
|
return <AgentProfileEditModalContent {...props} session={session} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
function OpenAgentProfileEditModal({
|
function AgentProfileEditModalContent({
|
||||||
serverId,
|
serverId,
|
||||||
visible,
|
visible,
|
||||||
mode,
|
mode,
|
||||||
profile,
|
profile,
|
||||||
seed,
|
session,
|
||||||
|
collapsibleDefaults,
|
||||||
onClose,
|
onClose,
|
||||||
onDismiss,
|
onDismiss,
|
||||||
onSave,
|
onRemove,
|
||||||
}: AgentProfileEditModalProps & { onDismiss: () => void }): ReactElement {
|
}: AgentProfileEditModalProps & {
|
||||||
|
session: AgentProfileFormSession;
|
||||||
|
onDismiss: () => void;
|
||||||
|
}): ReactElement {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const controlSize: ControlSize = "md";
|
const { model, state, save } = session;
|
||||||
const snapshot = useMemo(
|
|
||||||
() => ({ mode, ...(profile ? { profile } : {}), ...(seed ? { seed } : {}) }),
|
|
||||||
[mode, profile, seed],
|
|
||||||
);
|
|
||||||
const model = useAgentProfileFormModel(snapshot);
|
|
||||||
const state = useAgentProfileFormState(model);
|
|
||||||
useAgentProfileFormCatalog({ serverId, model });
|
|
||||||
useAgentProfileFormControls({ serverId, model, state });
|
|
||||||
|
|
||||||
const sheetHeader = useMemo<SheetHeader>(
|
const sheetHeader = useMemo<SheetHeader>(
|
||||||
() => ({
|
() => ({
|
||||||
@@ -153,59 +150,9 @@ function OpenAgentProfileEditModal({
|
|||||||
[mode, t],
|
[mode, t],
|
||||||
);
|
);
|
||||||
|
|
||||||
const providerOptions = useMemo(
|
|
||||||
() => toSelectOptions(state.providerOptions),
|
|
||||||
[state.providerOptions],
|
|
||||||
);
|
|
||||||
const modelOptions = useMemo(() => toSelectOptions(state.modelOptions), [state.modelOptions]);
|
|
||||||
const modeOptions = useMemo(() => toSelectOptions(state.modeOptions), [state.modeOptions]);
|
|
||||||
const thinkingOptions = useMemo(
|
|
||||||
() => toSelectOptions(state.thinkingOptions),
|
|
||||||
[state.thinkingOptions],
|
|
||||||
);
|
|
||||||
|
|
||||||
const handleAppearanceChange = useCallback(
|
|
||||||
(value: { icon: string; color: string }) => model.setAppearance(value),
|
|
||||||
[model],
|
|
||||||
);
|
|
||||||
const handleProviderChange = useCallback(
|
|
||||||
(value: string, display: SelectFieldDisplay) => model.setProvider(value, display),
|
|
||||||
[model],
|
|
||||||
);
|
|
||||||
const handleModelChange = useCallback(
|
|
||||||
(value: string, display: SelectFieldDisplay) => model.setModel(value, value ? display : null),
|
|
||||||
[model],
|
|
||||||
);
|
|
||||||
const handleModeChange = useCallback(
|
|
||||||
(value: string, display: SelectFieldDisplay) => model.setMode(value, value ? display : null),
|
|
||||||
[model],
|
|
||||||
);
|
|
||||||
const handleThinkingChange = useCallback(
|
|
||||||
(value: string, display: SelectFieldDisplay) =>
|
|
||||||
model.setThinking(value, value ? display : null),
|
|
||||||
[model],
|
|
||||||
);
|
|
||||||
|
|
||||||
const handleSave = useCallback(async () => {
|
|
||||||
const value = model.getState().submitValue;
|
|
||||||
if (!value) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
model.setSubmitError(null);
|
|
||||||
model.setSubmitting(true);
|
|
||||||
try {
|
|
||||||
await onSave(value);
|
|
||||||
onClose();
|
|
||||||
} catch (error) {
|
|
||||||
model.setSubmitError(toErrorMessage(error));
|
|
||||||
} finally {
|
|
||||||
model.setSubmitting(false);
|
|
||||||
}
|
|
||||||
}, [model, onClose, onSave]);
|
|
||||||
|
|
||||||
const handleSavePress = useCallback(() => {
|
const handleSavePress = useCallback(() => {
|
||||||
void handleSave();
|
void save();
|
||||||
}, [handleSave]);
|
}, [save]);
|
||||||
|
|
||||||
const handleCancel = useCallback(() => {
|
const handleCancel = useCallback(() => {
|
||||||
if (state.isSubmitting) {
|
if (state.isSubmitting) {
|
||||||
@@ -214,170 +161,31 @@ function OpenAgentProfileEditModal({
|
|||||||
onClose();
|
onClose();
|
||||||
}, [onClose, state.isSubmitting]);
|
}, [onClose, state.isSubmitting]);
|
||||||
|
|
||||||
return (
|
const handleRemove = useCallback(() => {
|
||||||
<AdaptiveModalSheet
|
if (!profile || !onRemove) {
|
||||||
visible={visible}
|
return;
|
||||||
header={sheetHeader}
|
}
|
||||||
onClose={handleCancel}
|
onRemove(profile.id);
|
||||||
onDismiss={onDismiss}
|
}, [onRemove, profile]);
|
||||||
desktopMaxWidth={520}
|
|
||||||
testID="agent-profile-edit-modal"
|
const footer = useMemo(
|
||||||
>
|
() => (
|
||||||
<View style={styles.body}>
|
<View style={styles.footer}>
|
||||||
<View style={styles.nameRow}>
|
<View style={styles.footerStart}>
|
||||||
<View style={styles.iconField}>
|
{mode === "edit" && profile && onRemove ? (
|
||||||
<AgentProfileAppearanceField
|
<Button
|
||||||
label={t("settings.host.agentProfiles.iconLabel")}
|
variant="outline"
|
||||||
icon={state.icon}
|
onPress={handleRemove}
|
||||||
color={state.color}
|
|
||||||
onChange={handleAppearanceChange}
|
|
||||||
disabled={state.isSubmitting}
|
disabled={state.isSubmitting}
|
||||||
size={controlSize}
|
testID="agent-profile-modal-remove-button"
|
||||||
testID="agent-profile-icon-field"
|
|
||||||
triggerTestID="agent-profile-icon-trigger"
|
|
||||||
/>
|
|
||||||
</View>
|
|
||||||
<View style={styles.nameField}>
|
|
||||||
<Field
|
|
||||||
label={t("settings.host.agentProfiles.nameLabel")}
|
|
||||||
testID="agent-profile-name-field"
|
|
||||||
>
|
>
|
||||||
<FormTextInput
|
{t("settings.host.agentProfiles.remove")}
|
||||||
initialValue={seed?.name ?? profile?.name ?? ""}
|
</Button>
|
||||||
onChangeText={model.setName}
|
) : null}
|
||||||
placeholder={t("settings.host.agentProfiles.namePlaceholder")}
|
|
||||||
autoCapitalize="none"
|
|
||||||
autoCorrect={false}
|
|
||||||
editable={!state.isSubmitting}
|
|
||||||
size={controlSize}
|
|
||||||
accessibilityLabel={t("settings.host.agentProfiles.nameLabel")}
|
|
||||||
testID="agent-profile-name-input"
|
|
||||||
/>
|
|
||||||
</Field>
|
|
||||||
</View>
|
|
||||||
</View>
|
</View>
|
||||||
|
<View style={styles.footerEnd}>
|
||||||
<SelectField
|
|
||||||
label={t("settings.host.agentProfiles.providerLabel")}
|
|
||||||
value={state.provider || null}
|
|
||||||
selectedDisplay={state.providerDisplay}
|
|
||||||
options={providerOptions}
|
|
||||||
onChange={handleProviderChange}
|
|
||||||
placeholder={t("settings.host.agentProfiles.providerPlaceholder")}
|
|
||||||
emptyText={t("settings.host.agentProfiles.noProviders")}
|
|
||||||
loading={state.catalogResolution !== "complete"}
|
|
||||||
disabled={state.isSubmitting}
|
|
||||||
searchable={providerOptions.length > 6}
|
|
||||||
title={t("settings.host.agentProfiles.providerLabel")}
|
|
||||||
size={controlSize}
|
|
||||||
testID="agent-profile-provider-field"
|
|
||||||
triggerTestID="agent-profile-provider-trigger"
|
|
||||||
/>
|
|
||||||
|
|
||||||
{state.disclosure.showModelField ? (
|
|
||||||
<SelectField
|
|
||||||
label={t("settings.host.agentProfiles.modelLabel")}
|
|
||||||
value={state.modelId || UNSET_VALUE}
|
|
||||||
selectedDisplay={state.modelDisplay}
|
|
||||||
options={modelOptions}
|
|
||||||
onChange={handleModelChange}
|
|
||||||
placeholder={t("settings.host.agentProfiles.modelLabel")}
|
|
||||||
emptyText={t("settings.host.agentProfiles.noModels")}
|
|
||||||
disabled={state.isSubmitting}
|
|
||||||
searchable={modelOptions.length > 6}
|
|
||||||
title={t("settings.host.agentProfiles.modelLabel")}
|
|
||||||
size={controlSize}
|
|
||||||
testID="agent-profile-model-field"
|
|
||||||
triggerTestID="agent-profile-model-trigger"
|
|
||||||
/>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
{state.disclosure.showModeField ? (
|
|
||||||
<SelectField
|
|
||||||
label={t("settings.host.agentProfiles.modeLabel")}
|
|
||||||
value={state.modeId || UNSET_VALUE}
|
|
||||||
selectedDisplay={state.modeDisplay}
|
|
||||||
options={modeOptions}
|
|
||||||
onChange={handleModeChange}
|
|
||||||
placeholder={t("settings.host.agentProfiles.modeLabel")}
|
|
||||||
emptyText={t("settings.host.agentProfiles.noModes")}
|
|
||||||
disabled={state.isSubmitting}
|
|
||||||
searchable={modeOptions.length > 6}
|
|
||||||
title={t("settings.host.agentProfiles.modeLabel")}
|
|
||||||
size={controlSize}
|
|
||||||
testID="agent-profile-mode-field"
|
|
||||||
triggerTestID="agent-profile-mode-trigger"
|
|
||||||
/>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
{state.disclosure.showThinkingField ? (
|
|
||||||
<SelectField
|
|
||||||
label={t("settings.host.agentProfiles.thinkingLabel")}
|
|
||||||
value={state.thinkingOptionId || UNSET_VALUE}
|
|
||||||
selectedDisplay={state.thinkingDisplay}
|
|
||||||
options={thinkingOptions}
|
|
||||||
onChange={handleThinkingChange}
|
|
||||||
placeholder={t("settings.host.agentProfiles.thinkingLabel")}
|
|
||||||
emptyText={t("settings.host.agentProfiles.noThinkingOptions")}
|
|
||||||
disabled={state.isSubmitting}
|
|
||||||
searchable={thinkingOptions.length > 6}
|
|
||||||
title={t("settings.host.agentProfiles.thinkingLabel")}
|
|
||||||
size={controlSize}
|
|
||||||
testID="agent-profile-thinking-field"
|
|
||||||
triggerTestID="agent-profile-thinking-trigger"
|
|
||||||
/>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
{state.disclosure.showControlsField ? (
|
|
||||||
<Field
|
|
||||||
label={t("settings.host.agentProfiles.featuresLabel")}
|
|
||||||
testID="agent-profile-features-field"
|
|
||||||
>
|
|
||||||
<View style={styles.featureCard} testID="agent-profile-features-card">
|
|
||||||
{state.controls.map((control, index) => (
|
|
||||||
<AgentProfileControlRow
|
|
||||||
key={control.key}
|
|
||||||
control={control}
|
|
||||||
options={state.controlOptions}
|
|
||||||
isFirst={index === 0}
|
|
||||||
disabled={state.isSubmitting}
|
|
||||||
size={controlSize}
|
|
||||||
model={model}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</View>
|
|
||||||
</Field>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
<Field
|
|
||||||
label={t("settings.host.agentProfiles.notesLabel")}
|
|
||||||
hint={t("settings.host.agentProfiles.notesHint")}
|
|
||||||
testID="agent-profile-notes-field"
|
|
||||||
>
|
|
||||||
<FormTextInput
|
|
||||||
initialValue={profile?.notes ?? ""}
|
|
||||||
onChangeText={model.setNotes}
|
|
||||||
placeholder={t("settings.host.agentProfiles.notesPlaceholder")}
|
|
||||||
multiline
|
|
||||||
numberOfLines={4}
|
|
||||||
style={styles.notesInput}
|
|
||||||
editable={!state.isSubmitting}
|
|
||||||
size={controlSize}
|
|
||||||
accessibilityLabel={t("settings.host.agentProfiles.notesLabel")}
|
|
||||||
testID="agent-profile-notes-input"
|
|
||||||
/>
|
|
||||||
</Field>
|
|
||||||
|
|
||||||
{state.submitError ? (
|
|
||||||
<Text style={styles.submitError} testID="agent-profile-submit-error">
|
|
||||||
{state.submitError}
|
|
||||||
</Text>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
<View style={styles.actions}>
|
|
||||||
<Button
|
<Button
|
||||||
variant="secondary"
|
variant="secondary"
|
||||||
style={styles.actionButton}
|
|
||||||
onPress={handleCancel}
|
onPress={handleCancel}
|
||||||
disabled={state.isSubmitting}
|
disabled={state.isSubmitting}
|
||||||
testID="agent-profile-cancel-button"
|
testID="agent-profile-cancel-button"
|
||||||
@@ -386,177 +194,65 @@ function OpenAgentProfileEditModal({
|
|||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
variant="default"
|
variant="default"
|
||||||
style={styles.actionButton}
|
|
||||||
onPress={handleSavePress}
|
onPress={handleSavePress}
|
||||||
disabled={!state.canSubmit}
|
disabled={!state.canSubmit}
|
||||||
|
loading={state.isSubmitting}
|
||||||
testID="agent-profile-save-button"
|
testID="agent-profile-save-button"
|
||||||
>
|
>
|
||||||
{state.isSubmitting
|
{t("settings.host.agentProfiles.save")}
|
||||||
? t("settings.host.agentProfiles.saving")
|
|
||||||
: t("settings.host.agentProfiles.save")}
|
|
||||||
</Button>
|
</Button>
|
||||||
</View>
|
</View>
|
||||||
</View>
|
</View>
|
||||||
|
),
|
||||||
|
[
|
||||||
|
handleCancel,
|
||||||
|
handleRemove,
|
||||||
|
handleSavePress,
|
||||||
|
mode,
|
||||||
|
onRemove,
|
||||||
|
profile,
|
||||||
|
state.canSubmit,
|
||||||
|
state.isSubmitting,
|
||||||
|
t,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AdaptiveModalSheet
|
||||||
|
visible={visible}
|
||||||
|
header={sheetHeader}
|
||||||
|
footer={footer}
|
||||||
|
onClose={handleCancel}
|
||||||
|
onDismiss={onDismiss}
|
||||||
|
desktopMaxWidth={500}
|
||||||
|
testID="agent-profile-edit-modal"
|
||||||
|
>
|
||||||
|
<AgentProfileFormFields
|
||||||
|
serverId={serverId}
|
||||||
|
model={model}
|
||||||
|
state={state}
|
||||||
|
collapsibleDefaults={collapsibleDefaults ?? mode === "create"}
|
||||||
|
/>
|
||||||
</AdaptiveModalSheet>
|
</AdaptiveModalSheet>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function AgentProfileControlRow({
|
|
||||||
control,
|
|
||||||
options,
|
|
||||||
isFirst,
|
|
||||||
disabled,
|
|
||||||
size,
|
|
||||||
model,
|
|
||||||
}: {
|
|
||||||
control: AgentOptionControl;
|
|
||||||
options: ProviderOptions;
|
|
||||||
isFirst: boolean;
|
|
||||||
disabled: boolean;
|
|
||||||
size: ControlSize;
|
|
||||||
model: AgentProfileFormModel;
|
|
||||||
}): ReactElement {
|
|
||||||
const rowStyle = useMemo(
|
|
||||||
() => [styles.featureRow, isFirst ? null : styles.featureRowBorder],
|
|
||||||
[isFirst],
|
|
||||||
);
|
|
||||||
const handleToggle = useCallback(
|
|
||||||
(value: boolean) => model.setOption(control.key, value),
|
|
||||||
[control.key, model],
|
|
||||||
);
|
|
||||||
const handleSelect = useCallback(
|
|
||||||
(value: string) => model.setOption(control.key, value),
|
|
||||||
[control.key, model],
|
|
||||||
);
|
|
||||||
const selectOptions = useMemo<SelectFieldOption<string>[]>(
|
|
||||||
() =>
|
|
||||||
control.type === "select"
|
|
||||||
? control.choices.map((choice) => ({
|
|
||||||
id: choice.value,
|
|
||||||
value: choice.value,
|
|
||||||
label: choice.label,
|
|
||||||
...(choice.description ? { description: choice.description } : {}),
|
|
||||||
testID: `agent-profile-feature-option-${control.key}-${choice.value}`,
|
|
||||||
}))
|
|
||||||
: [],
|
|
||||||
[control],
|
|
||||||
);
|
|
||||||
const selectedValue = control.type === "select" ? readSelectOption(control, options) : null;
|
|
||||||
const selectedDisplay = useMemo<SelectFieldDisplay | null>(() => {
|
|
||||||
if (control.type !== "select" || !selectedValue) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
const choice = control.choices.find((candidate) => candidate.value === selectedValue);
|
|
||||||
return { label: choice?.label ?? selectedValue };
|
|
||||||
}, [control, selectedValue]);
|
|
||||||
|
|
||||||
if (control.type === "select") {
|
|
||||||
return (
|
|
||||||
<View style={rowStyle} testID={`agent-profile-feature-row-${control.key}`}>
|
|
||||||
<SelectField
|
|
||||||
label={control.label}
|
|
||||||
value={selectedValue}
|
|
||||||
selectedDisplay={selectedDisplay}
|
|
||||||
options={selectOptions}
|
|
||||||
onChange={handleSelect}
|
|
||||||
placeholder={control.label}
|
|
||||||
emptyText={control.label}
|
|
||||||
disabled={disabled}
|
|
||||||
{...(control.description ? { hint: control.description } : {})}
|
|
||||||
title={control.label}
|
|
||||||
size={size}
|
|
||||||
testID={`agent-profile-feature-field-${control.key}`}
|
|
||||||
triggerTestID={`agent-profile-feature-trigger-${control.key}`}
|
|
||||||
/>
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<View style={rowStyle} testID={`agent-profile-feature-row-${control.key}`}>
|
|
||||||
<View style={styles.featureMeta}>
|
|
||||||
<Text style={styles.featureLabel} numberOfLines={1}>
|
|
||||||
{control.label}
|
|
||||||
</Text>
|
|
||||||
{control.description ? (
|
|
||||||
<Text style={styles.featureDescription} numberOfLines={2}>
|
|
||||||
{control.description}
|
|
||||||
</Text>
|
|
||||||
) : null}
|
|
||||||
</View>
|
|
||||||
<Switch
|
|
||||||
value={readToggleOption(control, options)}
|
|
||||||
onValueChange={handleToggle}
|
|
||||||
disabled={disabled}
|
|
||||||
accessibilityLabel={control.label}
|
|
||||||
testID={`agent-profile-feature-switch-${control.key}`}
|
|
||||||
/>
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const styles = StyleSheet.create((theme) => ({
|
const styles = StyleSheet.create((theme) => ({
|
||||||
body: {
|
footer: {
|
||||||
gap: theme.spacing[4],
|
|
||||||
paddingBottom: theme.spacing[2],
|
|
||||||
},
|
|
||||||
nameRow: {
|
|
||||||
flexDirection: "row",
|
|
||||||
alignItems: "flex-start",
|
|
||||||
gap: theme.spacing[2],
|
|
||||||
},
|
|
||||||
// No width: the trigger is a glyph and a chevron, so it sizes to them.
|
|
||||||
iconField: {
|
|
||||||
flexShrink: 0,
|
|
||||||
},
|
|
||||||
nameField: {
|
|
||||||
flex: 1,
|
flex: 1,
|
||||||
},
|
|
||||||
featureCard: {
|
|
||||||
backgroundColor: theme.colors.surface2,
|
|
||||||
borderRadius: theme.borderRadius.md,
|
|
||||||
borderWidth: 1,
|
|
||||||
borderColor: theme.colors.border,
|
|
||||||
paddingHorizontal: theme.spacing[3],
|
|
||||||
},
|
|
||||||
featureRow: {
|
|
||||||
flexDirection: "row",
|
flexDirection: "row",
|
||||||
alignItems: "center",
|
alignItems: "center",
|
||||||
justifyContent: "space-between",
|
justifyContent: "space-between",
|
||||||
gap: theme.spacing[3],
|
gap: theme.spacing[2],
|
||||||
paddingVertical: theme.spacing[3],
|
|
||||||
},
|
},
|
||||||
featureRowBorder: {
|
footerStart: {
|
||||||
borderTopWidth: 1,
|
|
||||||
borderTopColor: theme.colors.border,
|
|
||||||
},
|
|
||||||
featureMeta: {
|
|
||||||
flex: 1,
|
|
||||||
gap: theme.spacing[1],
|
|
||||||
},
|
|
||||||
featureLabel: {
|
|
||||||
color: theme.colors.foreground,
|
|
||||||
fontSize: theme.fontSize.base,
|
|
||||||
},
|
|
||||||
featureDescription: {
|
|
||||||
color: theme.colors.foregroundMuted,
|
|
||||||
fontSize: theme.fontSize.sm,
|
|
||||||
},
|
|
||||||
notesInput: {
|
|
||||||
minHeight: 88,
|
|
||||||
textAlignVertical: "top",
|
|
||||||
},
|
|
||||||
submitError: {
|
|
||||||
color: theme.colors.statusDanger,
|
|
||||||
fontSize: theme.fontSize.base,
|
|
||||||
},
|
|
||||||
actions: {
|
|
||||||
flexDirection: "row",
|
flexDirection: "row",
|
||||||
alignItems: "center",
|
alignItems: "center",
|
||||||
gap: theme.spacing[2],
|
gap: theme.spacing[2],
|
||||||
marginTop: theme.spacing[2],
|
|
||||||
},
|
},
|
||||||
actionButton: {
|
footerEnd: {
|
||||||
flex: 1,
|
flexDirection: "row",
|
||||||
|
alignItems: "center",
|
||||||
|
gap: theme.spacing[2],
|
||||||
},
|
},
|
||||||
}));
|
}));
|
||||||
|
|||||||
@@ -0,0 +1,567 @@
|
|||||||
|
import { useCallback, useMemo, useRef, type ReactElement, type ReactNode } from "react";
|
||||||
|
import { Text, View } from "react-native";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||||
|
import type {
|
||||||
|
AgentOptionControl,
|
||||||
|
AgentProvider,
|
||||||
|
ProviderOptions,
|
||||||
|
} from "@getpaseo/protocol/agent-types";
|
||||||
|
import { readSelectOption, readToggleOption } from "@/agent-controls/option-controls";
|
||||||
|
import { CombinedModelSelector } from "@/components/combined-model-selector";
|
||||||
|
import {
|
||||||
|
SettingsCard,
|
||||||
|
SettingsCollapsibleRow,
|
||||||
|
SettingsSelect,
|
||||||
|
SettingsSwitch,
|
||||||
|
} from "@/components/settings";
|
||||||
|
import type { ControlSize } from "@/components/ui/control-geometry";
|
||||||
|
import { Field, FormTextInput } from "@/components/ui/form-field";
|
||||||
|
import { mutedIconColorMapping } from "@/components/ui/icon-color";
|
||||||
|
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||||
|
import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control";
|
||||||
|
import {
|
||||||
|
SelectField,
|
||||||
|
SelectFieldTrigger,
|
||||||
|
type SelectFieldDisplay,
|
||||||
|
type SelectFieldOption,
|
||||||
|
} from "@/components/ui/select-field";
|
||||||
|
import type { EditingTextInputHandle } from "@/components/ui/text-input";
|
||||||
|
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
|
||||||
|
import { buildSelectableProviderSelectorProviders } from "@/provider-selection/provider-selection";
|
||||||
|
import { ICON_SIZE } from "@/styles/theme";
|
||||||
|
import { AgentProfileGlyph } from "../internal/agent-profile-glyph";
|
||||||
|
import type {
|
||||||
|
AgentProfileFormModel,
|
||||||
|
AgentProfileFormOption,
|
||||||
|
AgentProfileFormState,
|
||||||
|
} from "../internal/profile-form-model";
|
||||||
|
import { AgentProfileIconButton } from "./agent-profile-appearance-field";
|
||||||
|
|
||||||
|
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
|
||||||
|
|
||||||
|
const UNSET_VALUE = "";
|
||||||
|
|
||||||
|
function toSelectOptions(options: AgentProfileFormOption[]): SelectFieldOption<string>[] {
|
||||||
|
return options.map((option) => ({
|
||||||
|
id: option.id,
|
||||||
|
value: option.value,
|
||||||
|
label: option.label,
|
||||||
|
...(option.description ? { description: option.description } : {}),
|
||||||
|
testID: option.testID,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
function canUseSegmentedThinking(options: readonly AgentProfileFormOption[]): boolean {
|
||||||
|
return (
|
||||||
|
options.length >= 2 &&
|
||||||
|
options.length <= 4 &&
|
||||||
|
options.every((option) => option.label.trim().length <= 12)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AgentProfileFormFieldsProps {
|
||||||
|
serverId: string;
|
||||||
|
model: AgentProfileFormModel;
|
||||||
|
state: AgentProfileFormState;
|
||||||
|
controlSize?: ControlSize;
|
||||||
|
/** Embeds the icon+color picker beside the Name input (used in sheets; drawer places it in its hero). */
|
||||||
|
showInlineIcon?: boolean;
|
||||||
|
/** Collapses Mode, Thinking, Notes, and Options behind a SettingsCollapsibleRow until expanded. */
|
||||||
|
collapsibleDefaults?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ThinkingField({
|
||||||
|
state,
|
||||||
|
controlSize,
|
||||||
|
onSelectChange,
|
||||||
|
onSegmentChange,
|
||||||
|
}: {
|
||||||
|
state: AgentProfileFormState;
|
||||||
|
controlSize: ControlSize;
|
||||||
|
onSelectChange: (value: string, display: SelectFieldDisplay) => void;
|
||||||
|
onSegmentChange: (value: string) => void;
|
||||||
|
}): ReactElement | null {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const thinkingOptions = useMemo(
|
||||||
|
() => toSelectOptions(state.thinkingOptions),
|
||||||
|
[state.thinkingOptions],
|
||||||
|
);
|
||||||
|
const segmentedThinkingOptions = useMemo<SegmentedControlOption<string>[]>(
|
||||||
|
() =>
|
||||||
|
state.thinkingOptions.map((option) => ({
|
||||||
|
value: option.value,
|
||||||
|
label: option.label,
|
||||||
|
disabled: state.isSubmitting,
|
||||||
|
testID: option.testID,
|
||||||
|
})),
|
||||||
|
[state.isSubmitting, state.thinkingOptions],
|
||||||
|
);
|
||||||
|
if (!state.disclosure.showThinkingField) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (canUseSegmentedThinking(state.thinkingOptions)) {
|
||||||
|
return (
|
||||||
|
<Field
|
||||||
|
label={t("settings.host.agentProfiles.thinkingLabel")}
|
||||||
|
testID="agent-profile-thinking-field"
|
||||||
|
>
|
||||||
|
<SegmentedControl
|
||||||
|
options={segmentedThinkingOptions}
|
||||||
|
value={state.thinkingOptionId || null}
|
||||||
|
onValueChange={onSegmentChange}
|
||||||
|
size={controlSize}
|
||||||
|
testID="agent-profile-thinking-trigger"
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<SelectField
|
||||||
|
label={t("settings.host.agentProfiles.thinkingLabel")}
|
||||||
|
value={state.thinkingOptionId || UNSET_VALUE}
|
||||||
|
selectedDisplay={state.thinkingDisplay}
|
||||||
|
options={thinkingOptions}
|
||||||
|
onChange={onSelectChange}
|
||||||
|
placeholder={t("settings.host.agentProfiles.thinkingLabel")}
|
||||||
|
emptyText={t("settings.host.agentProfiles.noThinkingOptions")}
|
||||||
|
disabled={state.isSubmitting}
|
||||||
|
searchable={thinkingOptions.length > 6}
|
||||||
|
title={t("settings.host.agentProfiles.thinkingLabel")}
|
||||||
|
size={controlSize}
|
||||||
|
testID="agent-profile-thinking-field"
|
||||||
|
triggerTestID="agent-profile-thinking-trigger"
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function AgentProfileControlRow({
|
||||||
|
control,
|
||||||
|
options,
|
||||||
|
disabled,
|
||||||
|
model,
|
||||||
|
}: {
|
||||||
|
control: AgentOptionControl;
|
||||||
|
options: ProviderOptions;
|
||||||
|
disabled: boolean;
|
||||||
|
model: AgentProfileFormModel;
|
||||||
|
}): ReactElement {
|
||||||
|
const handleToggle = useCallback(
|
||||||
|
(value: boolean) => model.setOption(control.key, value),
|
||||||
|
[control.key, model],
|
||||||
|
);
|
||||||
|
const handleSelect = useCallback(
|
||||||
|
(value: string) => model.setOption(control.key, value),
|
||||||
|
[control.key, model],
|
||||||
|
);
|
||||||
|
const selectOptions = useMemo(
|
||||||
|
() =>
|
||||||
|
control.type === "select"
|
||||||
|
? control.choices.map((choice) => ({ label: choice.label, value: choice.value }))
|
||||||
|
: [],
|
||||||
|
[control],
|
||||||
|
);
|
||||||
|
|
||||||
|
if (control.type === "select") {
|
||||||
|
const selectedValue = readSelectOption(control, options) ?? control.choices[0]?.value ?? "";
|
||||||
|
return (
|
||||||
|
<SettingsSelect
|
||||||
|
label={control.label}
|
||||||
|
hint={control.description}
|
||||||
|
value={selectedValue}
|
||||||
|
options={selectOptions}
|
||||||
|
onValueChange={handleSelect}
|
||||||
|
disabled={disabled}
|
||||||
|
testID={`agent-profile-feature-row-${control.key}`}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<SettingsSwitch
|
||||||
|
label={control.label}
|
||||||
|
hint={control.description}
|
||||||
|
value={readToggleOption(control, options)}
|
||||||
|
onValueChange={handleToggle}
|
||||||
|
disabled={disabled}
|
||||||
|
testID={`agent-profile-feature-row-${control.key}`}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function AgentProfileAdvancedFields({
|
||||||
|
model,
|
||||||
|
state,
|
||||||
|
controlSize,
|
||||||
|
onModeChange,
|
||||||
|
onThinkingSelectChange,
|
||||||
|
onThinkingSegmentChange,
|
||||||
|
}: {
|
||||||
|
model: AgentProfileFormModel;
|
||||||
|
state: AgentProfileFormState;
|
||||||
|
controlSize: ControlSize;
|
||||||
|
onModeChange: (value: string, display: SelectFieldDisplay) => void;
|
||||||
|
onThinkingSelectChange: (value: string, display: SelectFieldDisplay) => void;
|
||||||
|
onThinkingSegmentChange: (value: string) => void;
|
||||||
|
}): ReactElement {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const modeOptions = useMemo(() => toSelectOptions(state.modeOptions), [state.modeOptions]);
|
||||||
|
const providerOptionsTitle = state.providerDisplay?.label
|
||||||
|
? t("settings.host.agentProfiles.providerOptionsLabel", {
|
||||||
|
provider: state.providerDisplay.label,
|
||||||
|
})
|
||||||
|
: t("settings.host.agentProfiles.featuresLabel");
|
||||||
|
const optionsPendingSpinner = useMemo(
|
||||||
|
() =>
|
||||||
|
state.controlsPending ? (
|
||||||
|
<ThemedLoadingSpinner size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />
|
||||||
|
) : null,
|
||||||
|
[state.controlsPending],
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{state.disclosure.showModeField ? (
|
||||||
|
<SelectField
|
||||||
|
label={t("settings.host.agentProfiles.modeLabel")}
|
||||||
|
value={state.modeId || UNSET_VALUE}
|
||||||
|
selectedDisplay={state.modeDisplay}
|
||||||
|
options={modeOptions}
|
||||||
|
onChange={onModeChange}
|
||||||
|
placeholder={t("settings.host.agentProfiles.modeLabel")}
|
||||||
|
emptyText={t("settings.host.agentProfiles.noModes")}
|
||||||
|
disabled={state.isSubmitting}
|
||||||
|
searchable={modeOptions.length > 6}
|
||||||
|
title={t("settings.host.agentProfiles.modeLabel")}
|
||||||
|
size={controlSize}
|
||||||
|
testID="agent-profile-mode-field"
|
||||||
|
triggerTestID="agent-profile-mode-trigger"
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<ThinkingField
|
||||||
|
state={state}
|
||||||
|
controlSize={controlSize}
|
||||||
|
onSelectChange={onThinkingSelectChange}
|
||||||
|
onSegmentChange={onThinkingSegmentChange}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Field
|
||||||
|
label={t("settings.host.agentProfiles.notesLabel")}
|
||||||
|
hint={t("settings.host.agentProfiles.notesHint")}
|
||||||
|
testID="agent-profile-notes-field"
|
||||||
|
>
|
||||||
|
<FormTextInput
|
||||||
|
initialValue={state.notes}
|
||||||
|
onChangeText={model.setNotes}
|
||||||
|
placeholder={t("settings.host.agentProfiles.notesPlaceholder")}
|
||||||
|
multiline
|
||||||
|
numberOfLines={3}
|
||||||
|
style={styles.notesInput}
|
||||||
|
editable={!state.isSubmitting}
|
||||||
|
size={controlSize}
|
||||||
|
accessibilityLabel={t("settings.host.agentProfiles.notesLabel")}
|
||||||
|
testID="agent-profile-notes-input"
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
{state.disclosure.showControlsField ? (
|
||||||
|
<Field
|
||||||
|
label={providerOptionsTitle}
|
||||||
|
trailing={optionsPendingSpinner}
|
||||||
|
testID="agent-profile-features-field"
|
||||||
|
>
|
||||||
|
<View style={state.controlsPending ? styles.featureCardPending : undefined}>
|
||||||
|
<SettingsCard testID="agent-profile-features-card">
|
||||||
|
{state.controls.map((control) => (
|
||||||
|
<AgentProfileControlRow
|
||||||
|
key={control.key}
|
||||||
|
control={control}
|
||||||
|
options={state.controlOptions}
|
||||||
|
disabled={state.isSubmitting || state.controlsPending}
|
||||||
|
model={model}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</SettingsCard>
|
||||||
|
</View>
|
||||||
|
</Field>
|
||||||
|
) : null}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shared profile form body used by both the desktop inspector drawer and the modal sheet.
|
||||||
|
*
|
||||||
|
* Layout order keeps inputs above async provider options: Model first (using Paseo's
|
||||||
|
* shared CombinedModelSelector), Name + icon second, Mode & Thinking, "When to use",
|
||||||
|
* and provider options last so loading options never shift controls above them.
|
||||||
|
*/
|
||||||
|
export function AgentProfileFormFields({
|
||||||
|
serverId,
|
||||||
|
model,
|
||||||
|
state,
|
||||||
|
controlSize = "md",
|
||||||
|
showInlineIcon = true,
|
||||||
|
collapsibleDefaults = false,
|
||||||
|
}: AgentProfileFormFieldsProps): ReactElement {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const nameInputRef = useRef<EditingTextInputHandle>(null);
|
||||||
|
const { entries, isLoading, isFetching, isRefreshing, refresh } = useProvidersSnapshot(serverId, {
|
||||||
|
cwd: null,
|
||||||
|
});
|
||||||
|
|
||||||
|
const modelSelectorProviders = useMemo(
|
||||||
|
() =>
|
||||||
|
buildSelectableProviderSelectorProviders(entries, {
|
||||||
|
selectedProvider: state.provider || null,
|
||||||
|
}),
|
||||||
|
[entries, state.provider],
|
||||||
|
);
|
||||||
|
|
||||||
|
const modelTriggerLeading = useMemo(
|
||||||
|
() =>
|
||||||
|
state.provider ? (
|
||||||
|
<AgentProfileGlyph provider={state.provider} serverId={serverId} size={ICON_SIZE.sm} />
|
||||||
|
) : null,
|
||||||
|
[serverId, state.provider],
|
||||||
|
);
|
||||||
|
|
||||||
|
const renderModelTrigger = useCallback(
|
||||||
|
({
|
||||||
|
selectedModelLabel,
|
||||||
|
disabled,
|
||||||
|
isOpen,
|
||||||
|
hovered,
|
||||||
|
pressed,
|
||||||
|
}: {
|
||||||
|
selectedModelLabel: string;
|
||||||
|
onPress: () => void;
|
||||||
|
disabled: boolean;
|
||||||
|
isOpen: boolean;
|
||||||
|
hovered: boolean;
|
||||||
|
pressed: boolean;
|
||||||
|
}): ReactNode => {
|
||||||
|
const displayLabel =
|
||||||
|
state.modelDisplay?.label ?? state.providerDisplay?.label ?? selectedModelLabel;
|
||||||
|
return (
|
||||||
|
<SelectFieldTrigger
|
||||||
|
label={displayLabel}
|
||||||
|
isPlaceholder={!state.provider}
|
||||||
|
placeholder={t("settings.host.agentProfiles.chooseModelPlaceholder")}
|
||||||
|
leading={modelTriggerLeading}
|
||||||
|
disabled={disabled}
|
||||||
|
active={hovered || pressed || isOpen}
|
||||||
|
size={controlSize}
|
||||||
|
testID="agent-profile-model-trigger"
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
[
|
||||||
|
controlSize,
|
||||||
|
modelTriggerLeading,
|
||||||
|
state.modelDisplay?.label,
|
||||||
|
state.provider,
|
||||||
|
state.providerDisplay?.label,
|
||||||
|
t,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleAppearanceChange = useCallback(
|
||||||
|
(value: { icon: string; color: string }) => model.setAppearance(value),
|
||||||
|
[model],
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleModelSelect = useCallback(
|
||||||
|
(provider: AgentProvider, modelId: string) => {
|
||||||
|
const previousName = model.getState().name;
|
||||||
|
const entry = entries?.find((candidate) => candidate.provider === provider);
|
||||||
|
const modelDef = entry?.models?.find((candidate) => candidate.id === modelId);
|
||||||
|
model.setProviderModel(provider, modelId, {
|
||||||
|
provider: { label: entry?.label ?? provider },
|
||||||
|
model: modelId ? { label: modelDef?.label ?? modelId } : null,
|
||||||
|
});
|
||||||
|
const suggestedName = model.getState().name;
|
||||||
|
if (suggestedName !== previousName) {
|
||||||
|
nameInputRef.current?.replaceText(suggestedName);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[entries, model],
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleRetryProvider = useCallback(
|
||||||
|
(provider: AgentProvider) => {
|
||||||
|
void refresh([provider]);
|
||||||
|
},
|
||||||
|
[refresh],
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleModeChange = useCallback(
|
||||||
|
(value: string, display: SelectFieldDisplay) => model.setMode(value, value ? display : null),
|
||||||
|
[model],
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleThinkingSelectChange = useCallback(
|
||||||
|
(value: string, display: SelectFieldDisplay) =>
|
||||||
|
model.setThinking(value, value ? display : null),
|
||||||
|
[model],
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleThinkingSegmentChange = useCallback(
|
||||||
|
(value: string) => {
|
||||||
|
const option = state.thinkingOptions.find((candidate) => candidate.value === value);
|
||||||
|
model.setThinking(value, option ? { label: option.label } : null);
|
||||||
|
},
|
||||||
|
[model, state.thinkingOptions],
|
||||||
|
);
|
||||||
|
|
||||||
|
const hasRuntimeDefaults =
|
||||||
|
state.disclosure.showModeField ||
|
||||||
|
state.disclosure.showThinkingField ||
|
||||||
|
state.disclosure.showControlsField;
|
||||||
|
|
||||||
|
const defaultsSummary = useMemo(() => {
|
||||||
|
const parts: string[] = [];
|
||||||
|
if (state.modeDisplay?.label) {
|
||||||
|
parts.push(state.modeDisplay.label);
|
||||||
|
}
|
||||||
|
if (state.thinkingDisplay?.label) {
|
||||||
|
parts.push(state.thinkingDisplay.label);
|
||||||
|
}
|
||||||
|
if (state.controls.length > 0) {
|
||||||
|
parts.push(
|
||||||
|
state.controls.length === 1
|
||||||
|
? t("settings.host.agentProfiles.featureCountOne", { count: state.controls.length })
|
||||||
|
: t("settings.host.agentProfiles.featureCount", { count: state.controls.length }),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (!state.notes.trim() && hasRuntimeDefaults) {
|
||||||
|
parts.push(t("settings.host.agentProfiles.addRoutingNoteShort"));
|
||||||
|
}
|
||||||
|
return parts.join(" · ");
|
||||||
|
}, [
|
||||||
|
hasRuntimeDefaults,
|
||||||
|
state.controls.length,
|
||||||
|
state.modeDisplay?.label,
|
||||||
|
state.notes,
|
||||||
|
state.thinkingDisplay?.label,
|
||||||
|
t,
|
||||||
|
]);
|
||||||
|
|
||||||
|
const collapsibleLabel = hasRuntimeDefaults
|
||||||
|
? t("settings.host.agentProfiles.customizeSettings")
|
||||||
|
: t("settings.host.agentProfiles.addRoutingNoteShort");
|
||||||
|
|
||||||
|
const advancedFields = (
|
||||||
|
<AgentProfileAdvancedFields
|
||||||
|
model={model}
|
||||||
|
state={state}
|
||||||
|
controlSize={controlSize}
|
||||||
|
onModeChange={handleModeChange}
|
||||||
|
onThinkingSelectChange={handleThinkingSelectChange}
|
||||||
|
onThinkingSegmentChange={handleThinkingSegmentChange}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<View style={styles.body}>
|
||||||
|
<Field label={t("settings.host.agentProfiles.modelLabel")} testID="agent-profile-model-field">
|
||||||
|
<CombinedModelSelector
|
||||||
|
providers={modelSelectorProviders}
|
||||||
|
selectedProvider={state.provider}
|
||||||
|
selectedModel={state.modelId}
|
||||||
|
onSelect={handleModelSelect}
|
||||||
|
isLoading={isLoading || isFetching}
|
||||||
|
renderTrigger={renderModelTrigger}
|
||||||
|
triggerFill
|
||||||
|
serverId={serverId}
|
||||||
|
disabled={state.isSubmitting}
|
||||||
|
onRetryProvider={handleRetryProvider}
|
||||||
|
isRetryingProvider={isRefreshing}
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
<Field label={t("settings.host.agentProfiles.nameLabel")} testID="agent-profile-name-field">
|
||||||
|
<View style={styles.nameRow}>
|
||||||
|
{showInlineIcon ? (
|
||||||
|
<AgentProfileIconButton
|
||||||
|
label={t("settings.host.agentProfiles.iconLabel")}
|
||||||
|
icon={state.icon}
|
||||||
|
color={state.color}
|
||||||
|
provider={state.provider || undefined}
|
||||||
|
serverId={serverId}
|
||||||
|
onChange={handleAppearanceChange}
|
||||||
|
disabled={state.isSubmitting}
|
||||||
|
size={controlSize}
|
||||||
|
triggerTestID="agent-profile-icon-trigger"
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
<View style={styles.nameInputWrap}>
|
||||||
|
<FormTextInput
|
||||||
|
ref={nameInputRef}
|
||||||
|
initialValue={state.name}
|
||||||
|
onChangeText={model.setName}
|
||||||
|
placeholder={t("settings.host.agentProfiles.namePlaceholder")}
|
||||||
|
autoCapitalize="none"
|
||||||
|
autoCorrect={false}
|
||||||
|
editable={!state.isSubmitting}
|
||||||
|
size={controlSize}
|
||||||
|
accessibilityLabel={t("settings.host.agentProfiles.nameLabel")}
|
||||||
|
testID="agent-profile-name-input"
|
||||||
|
/>
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
{collapsibleDefaults ? (
|
||||||
|
<SettingsCard>
|
||||||
|
<SettingsCollapsibleRow
|
||||||
|
label={collapsibleLabel}
|
||||||
|
summary={defaultsSummary || undefined}
|
||||||
|
testID="agent-profile-customize"
|
||||||
|
>
|
||||||
|
<View style={styles.collapsibleFields}>{advancedFields}</View>
|
||||||
|
</SettingsCollapsibleRow>
|
||||||
|
</SettingsCard>
|
||||||
|
) : (
|
||||||
|
advancedFields
|
||||||
|
)}
|
||||||
|
|
||||||
|
{state.submitError ? (
|
||||||
|
<Text style={styles.submitError} testID="agent-profile-submit-error">
|
||||||
|
{state.submitError}
|
||||||
|
</Text>
|
||||||
|
) : null}
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const styles = StyleSheet.create((theme) => ({
|
||||||
|
body: {
|
||||||
|
gap: theme.spacing[4],
|
||||||
|
},
|
||||||
|
nameRow: {
|
||||||
|
flexDirection: "row",
|
||||||
|
alignItems: "center",
|
||||||
|
gap: theme.spacing[2],
|
||||||
|
},
|
||||||
|
nameInputWrap: {
|
||||||
|
flex: 1,
|
||||||
|
minWidth: 0,
|
||||||
|
},
|
||||||
|
collapsibleFields: {
|
||||||
|
padding: theme.spacing[4],
|
||||||
|
gap: theme.spacing[4],
|
||||||
|
},
|
||||||
|
featureCardPending: {
|
||||||
|
opacity: theme.opacity[50],
|
||||||
|
},
|
||||||
|
notesInput: {
|
||||||
|
minHeight: theme.spacing[20],
|
||||||
|
textAlignVertical: "top",
|
||||||
|
},
|
||||||
|
submitError: {
|
||||||
|
color: theme.colors.palette.red[300],
|
||||||
|
fontSize: theme.fontSize.sm,
|
||||||
|
},
|
||||||
|
}));
|
||||||
@@ -1,57 +1,345 @@
|
|||||||
import { useCallback, useMemo, type ReactElement } from "react";
|
import { useCallback, useMemo, useState, type ReactElement } from "react";
|
||||||
import { Text, View } from "react-native";
|
import { Text, View } from "react-native";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { ArrowDown, ArrowUp, FileText, Pencil, Trash2 } from "lucide-react-native";
|
import {
|
||||||
|
ArrowDown,
|
||||||
|
ArrowUp,
|
||||||
|
ArrowUpToLine,
|
||||||
|
ChevronRight,
|
||||||
|
Copy,
|
||||||
|
GripVertical,
|
||||||
|
MoreVertical,
|
||||||
|
Pencil,
|
||||||
|
Trash2,
|
||||||
|
} from "lucide-react-native";
|
||||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||||
import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types";
|
import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types";
|
||||||
import type { AgentProfile } from "@getpaseo/protocol/messages";
|
import type { AgentProfile } from "@getpaseo/protocol/messages";
|
||||||
import { Button } from "@/components/ui/button";
|
import { DraggableListHandle } from "@/components/draggable-list";
|
||||||
|
import { useOpenKebabMenuVisibility } from "@/components/sidebar/use-open-kebab-menu-visibility";
|
||||||
|
import {
|
||||||
|
bySizing,
|
||||||
|
ICON_BUTTON_SIZES,
|
||||||
|
mapLayout,
|
||||||
|
TOUCH_TARGET,
|
||||||
|
} from "@/components/ui/control-geometry";
|
||||||
|
import {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuSeparator,
|
||||||
|
} from "@/components/ui/dropdown-menu";
|
||||||
|
import {
|
||||||
|
extraMutedIconColorMapping,
|
||||||
|
foregroundIconColorMapping,
|
||||||
|
mutedIconColorMapping,
|
||||||
|
} from "@/components/ui/icon-color";
|
||||||
|
import { ToolbarButton } from "@/components/ui/pane-content-toolbar";
|
||||||
|
import { PressHighlight } from "@/components/ui/press-highlight";
|
||||||
|
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||||
|
import { usePointerCapabilities } from "@/hooks/pointer-capabilities";
|
||||||
import { settingsStyles } from "@/styles/settings";
|
import { settingsStyles } from "@/styles/settings";
|
||||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||||
import { AgentProfileGlyph } from "../internal/agent-profile-glyph";
|
import { AgentProfileGlyph } from "../internal/agent-profile-glyph";
|
||||||
import { buildAgentProfileTags } from "../internal/profile-summary";
|
import { buildAgentProfileRosterSummary } from "../internal/profile-summary";
|
||||||
|
|
||||||
|
/** Shared column & rail geometry consumed by both RosterTableHeader and AgentProfileRow. */
|
||||||
|
export const ROSTER_COL_PROFILE_WIDTH = 184;
|
||||||
|
export const ROSTER_COL_RUNTIME_WIDTH = 248;
|
||||||
|
export const ROSTER_TRAILING_WIDTH = bySizing({ touch: TOUCH_TARGET + 14, pointer: 42 });
|
||||||
|
|
||||||
|
const ROW_MIN_HEIGHT = bySizing({ touch: TOUCH_TARGET + 16, pointer: 56 });
|
||||||
|
const KEBAB_GLYPH_SIZE = ICON_SIZE.sm;
|
||||||
|
// The kebab's hitbox is larger than its glyph; it overhangs the row so the glyph sits on the
|
||||||
|
// card's trailing rail and the hitbox does not make the row taller.
|
||||||
|
const KEBAB_HITBOX_OVERHANG = bySizing({
|
||||||
|
touch: (ICON_BUTTON_SIZES.small.touch - KEBAB_GLYPH_SIZE) / 2,
|
||||||
|
pointer: (ICON_BUTTON_SIZES.small.pointer - KEBAB_GLYPH_SIZE) / 2,
|
||||||
|
});
|
||||||
|
|
||||||
|
const ThemedGripVertical = withUnistyles(GripVertical);
|
||||||
|
const ThemedMoreVertical = withUnistyles(MoreVertical);
|
||||||
|
const ThemedChevronRight = withUnistyles(ChevronRight);
|
||||||
|
const ThemedPencil = withUnistyles(Pencil);
|
||||||
|
const ThemedCopy = withUnistyles(Copy);
|
||||||
const ThemedArrowUp = withUnistyles(ArrowUp);
|
const ThemedArrowUp = withUnistyles(ArrowUp);
|
||||||
const ThemedArrowDown = withUnistyles(ArrowDown);
|
const ThemedArrowDown = withUnistyles(ArrowDown);
|
||||||
const ThemedPencil = withUnistyles(Pencil);
|
const ThemedArrowUpToLine = withUnistyles(ArrowUpToLine);
|
||||||
const ThemedTrash2 = withUnistyles(Trash2);
|
const ThemedTrash2 = withUnistyles(Trash2);
|
||||||
const ThemedFileText = withUnistyles(FileText);
|
|
||||||
|
|
||||||
const mutedColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
|
const destructiveIconColorMapping = (theme: Theme) => ({ color: theme.colors.destructive });
|
||||||
const destructiveColorMapping = (theme: Theme) => ({ color: theme.colors.destructive });
|
|
||||||
|
|
||||||
const moveUpIcon = <ThemedArrowUp size={ICON_SIZE.sm} uniProps={mutedColorMapping} />;
|
const editMenuIcon = <ThemedPencil size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />;
|
||||||
const moveDownIcon = <ThemedArrowDown size={ICON_SIZE.sm} uniProps={mutedColorMapping} />;
|
const duplicateMenuIcon = <ThemedCopy size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />;
|
||||||
const editIcon = <ThemedPencil size={ICON_SIZE.sm} uniProps={mutedColorMapping} />;
|
const moveUpMenuIcon = <ThemedArrowUp size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />;
|
||||||
const removeIcon = <ThemedTrash2 size={ICON_SIZE.sm} uniProps={destructiveColorMapping} />;
|
const moveDownMenuIcon = <ThemedArrowDown size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />;
|
||||||
|
const moveTopMenuIcon = (
|
||||||
|
<ThemedArrowUpToLine size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />
|
||||||
|
);
|
||||||
|
const removeMenuIcon = <ThemedTrash2 size={ICON_SIZE.sm} uniProps={destructiveIconColorMapping} />;
|
||||||
|
|
||||||
|
const HIDDEN_FROM_ASSISTIVE_TECH = {
|
||||||
|
accessibilityElementsHidden: true,
|
||||||
|
importantForAccessibility: "no-hide-descendants",
|
||||||
|
"aria-hidden": true,
|
||||||
|
} as const;
|
||||||
|
|
||||||
export interface AgentProfileRowProps {
|
export interface AgentProfileRowProps {
|
||||||
|
serverId: string;
|
||||||
profile: AgentProfile;
|
profile: AgentProfile;
|
||||||
entries: readonly ProviderSnapshotEntry[] | undefined;
|
entries: readonly ProviderSnapshotEntry[] | undefined;
|
||||||
isFirst: boolean;
|
isFirst: boolean;
|
||||||
isLast: boolean;
|
isLast: boolean;
|
||||||
|
selected?: boolean;
|
||||||
|
dragging?: boolean;
|
||||||
|
/** Stacked layout when narrow or on compact form factors. */
|
||||||
|
compactLayout?: boolean;
|
||||||
|
/** Hides the drag handle when showing filtered search results while preserving the rail. */
|
||||||
|
reorderable?: boolean;
|
||||||
onEdit: (id: string) => void;
|
onEdit: (id: string) => void;
|
||||||
|
onDuplicate: (id: string) => void;
|
||||||
onRemove: (id: string) => void;
|
onRemove: (id: string) => void;
|
||||||
onMoveUp: (id: string) => void;
|
onMoveUp: (id: string) => void;
|
||||||
onMoveDown: (id: string) => void;
|
onMoveDown: (id: string) => void;
|
||||||
|
onMoveToTop: (id: string) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function AgentProfileRowMenu({
|
||||||
|
profileId,
|
||||||
|
profileName,
|
||||||
|
isFirst,
|
||||||
|
isLast,
|
||||||
|
reorderable,
|
||||||
|
menuProps,
|
||||||
|
onEdit,
|
||||||
|
onDuplicate,
|
||||||
|
onMoveUp,
|
||||||
|
onMoveDown,
|
||||||
|
onMoveToTop,
|
||||||
|
onRemove,
|
||||||
|
}: {
|
||||||
|
profileId: string;
|
||||||
|
profileName: string;
|
||||||
|
isFirst: boolean;
|
||||||
|
isLast: boolean;
|
||||||
|
reorderable: boolean;
|
||||||
|
menuProps: { open: boolean; onOpenChange: (open: boolean) => void };
|
||||||
|
onEdit: () => void;
|
||||||
|
onDuplicate: () => void;
|
||||||
|
onMoveUp: () => void;
|
||||||
|
onMoveDown: () => void;
|
||||||
|
onMoveToTop: () => void;
|
||||||
|
onRemove: () => void;
|
||||||
|
}): ReactElement {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const showReorderItems = reorderable && (!isFirst || !isLast);
|
||||||
|
return (
|
||||||
|
<DropdownMenu {...menuProps} compactMode="sheet">
|
||||||
|
<ToolbarButton
|
||||||
|
kind="menu"
|
||||||
|
label={t("settings.host.agentProfiles.profileActions", { name: profileName })}
|
||||||
|
testID={`agent-profile-menu-${profileId}`}
|
||||||
|
>
|
||||||
|
<ThemedMoreVertical size={KEBAB_GLYPH_SIZE} uniProps={mutedIconColorMapping} />
|
||||||
|
</ToolbarButton>
|
||||||
|
<DropdownMenuContent side="bottom" align="end" width={180}>
|
||||||
|
<DropdownMenuItem
|
||||||
|
leading={editMenuIcon}
|
||||||
|
onSelect={onEdit}
|
||||||
|
testID={`agent-profile-edit-${profileId}`}
|
||||||
|
>
|
||||||
|
{t("settings.host.agentProfiles.editProfile")}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem
|
||||||
|
leading={duplicateMenuIcon}
|
||||||
|
onSelect={onDuplicate}
|
||||||
|
testID={`agent-profile-duplicate-${profileId}`}
|
||||||
|
>
|
||||||
|
{t("settings.host.agentProfiles.duplicate")}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
{showReorderItems ? (
|
||||||
|
<>
|
||||||
|
<DropdownMenuSeparator />
|
||||||
|
{!isFirst ? (
|
||||||
|
<DropdownMenuItem
|
||||||
|
leading={moveUpMenuIcon}
|
||||||
|
onSelect={onMoveUp}
|
||||||
|
testID={`agent-profile-move-up-${profileId}`}
|
||||||
|
>
|
||||||
|
{t("settings.host.agentProfiles.moveUp")}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
) : null}
|
||||||
|
{!isLast ? (
|
||||||
|
<DropdownMenuItem
|
||||||
|
leading={moveDownMenuIcon}
|
||||||
|
onSelect={onMoveDown}
|
||||||
|
testID={`agent-profile-move-down-${profileId}`}
|
||||||
|
>
|
||||||
|
{t("settings.host.agentProfiles.moveDown")}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
) : null}
|
||||||
|
{!isFirst ? (
|
||||||
|
<DropdownMenuItem
|
||||||
|
leading={moveTopMenuIcon}
|
||||||
|
onSelect={onMoveToTop}
|
||||||
|
testID={`agent-profile-move-top-${profileId}`}
|
||||||
|
>
|
||||||
|
{t("settings.host.agentProfiles.moveToTop")}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
) : null}
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
<DropdownMenuSeparator />
|
||||||
|
<DropdownMenuItem
|
||||||
|
destructive
|
||||||
|
leading={removeMenuIcon}
|
||||||
|
onSelect={onRemove}
|
||||||
|
testID={`agent-profile-remove-${profileId}`}
|
||||||
|
>
|
||||||
|
{t("settings.host.agentProfiles.remove")}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function AgentProfileRowContent({
|
||||||
|
serverId,
|
||||||
|
profile,
|
||||||
|
modelLabel,
|
||||||
|
providerLabel,
|
||||||
|
runtimeSubline,
|
||||||
|
fullSummary,
|
||||||
|
isStacked,
|
||||||
|
}: {
|
||||||
|
serverId: string;
|
||||||
|
profile: AgentProfile;
|
||||||
|
modelLabel: string | null;
|
||||||
|
providerLabel: string;
|
||||||
|
runtimeSubline: string;
|
||||||
|
fullSummary: string;
|
||||||
|
isStacked: boolean;
|
||||||
|
}): ReactElement {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const iconTile = (
|
||||||
|
<View style={styles.iconTile}>
|
||||||
|
<AgentProfileGlyph
|
||||||
|
icon={profile.icon}
|
||||||
|
color={profile.color}
|
||||||
|
provider={profile.provider}
|
||||||
|
serverId={serverId}
|
||||||
|
size={ICON_SIZE.sm}
|
||||||
|
/>
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
|
||||||
|
if (isStacked) {
|
||||||
|
return (
|
||||||
|
<View style={[styles.stackedMain, styles.passThrough]}>
|
||||||
|
{iconTile}
|
||||||
|
<View style={styles.stackedContent}>
|
||||||
|
<Text style={styles.nameText} numberOfLines={1}>
|
||||||
|
{profile.name}
|
||||||
|
</Text>
|
||||||
|
<Text style={styles.stackedSpecText} numberOfLines={1}>
|
||||||
|
{fullSummary}
|
||||||
|
</Text>
|
||||||
|
{profile.notes ? (
|
||||||
|
<Text
|
||||||
|
style={styles.stackedNotesText}
|
||||||
|
numberOfLines={2}
|
||||||
|
testID={`agent-profile-notes-${profile.id}`}
|
||||||
|
>
|
||||||
|
{profile.notes}
|
||||||
|
</Text>
|
||||||
|
) : null}
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<View style={[styles.columns, styles.passThrough]}>
|
||||||
|
<View style={styles.colProfile}>
|
||||||
|
{iconTile}
|
||||||
|
<Text style={styles.nameText} numberOfLines={1}>
|
||||||
|
{profile.name}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
<View style={styles.colRuntime}>
|
||||||
|
<View style={styles.modelLine}>
|
||||||
|
<AgentProfileGlyph provider={profile.provider} serverId={serverId} size={ICON_SIZE.xs} />
|
||||||
|
<Text style={styles.modelText} numberOfLines={1}>
|
||||||
|
{modelLabel ?? providerLabel}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
<Text style={styles.runtimeSubtext} numberOfLines={1}>
|
||||||
|
{runtimeSubline}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
<View style={styles.colNotes}>
|
||||||
|
{profile.notes ? (
|
||||||
|
<Text
|
||||||
|
style={styles.notesText}
|
||||||
|
numberOfLines={2}
|
||||||
|
testID={`agent-profile-notes-${profile.id}`}
|
||||||
|
>
|
||||||
|
{profile.notes}
|
||||||
|
</Text>
|
||||||
|
) : (
|
||||||
|
<Text style={styles.notesEmptyText} numberOfLines={1}>
|
||||||
|
{t("settings.host.agentProfiles.noRoutingNote")}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Wide roster row (Profile | Model & runtime | When to use) that stacks on narrow panes.
|
||||||
|
*
|
||||||
|
* Follows docs/hover.md: hover lives on the outer plain View, tap lives on an
|
||||||
|
* underlying PressHighlight, and the kebab menu's open state is lifted via
|
||||||
|
* `useOpenKebabMenuVisibility` so losing hover never unmounts an open menu.
|
||||||
|
*/
|
||||||
export function AgentProfileRow({
|
export function AgentProfileRow({
|
||||||
|
serverId,
|
||||||
profile,
|
profile,
|
||||||
entries,
|
entries,
|
||||||
isFirst,
|
isFirst,
|
||||||
isLast,
|
isLast,
|
||||||
|
selected = false,
|
||||||
|
dragging = false,
|
||||||
|
compactLayout = false,
|
||||||
|
reorderable = true,
|
||||||
onEdit,
|
onEdit,
|
||||||
|
onDuplicate,
|
||||||
onRemove,
|
onRemove,
|
||||||
onMoveUp,
|
onMoveUp,
|
||||||
onMoveDown,
|
onMoveDown,
|
||||||
|
onMoveToTop,
|
||||||
}: AgentProfileRowProps): ReactElement {
|
}: AgentProfileRowProps): ReactElement {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
const isCompactFormFactor = useIsCompactFormFactor();
|
||||||
|
const { finePointer, touchScreen } = usePointerCapabilities();
|
||||||
|
const [isHovered, setIsHovered] = useState(false);
|
||||||
|
|
||||||
|
const alwaysShowAffordances = !finePointer || touchScreen || isCompactFormFactor;
|
||||||
|
const { showKebab, menuProps } = useOpenKebabMenuVisibility(
|
||||||
|
isHovered || dragging || alwaysShowAffordances,
|
||||||
|
);
|
||||||
|
const showRowAffordances = showKebab;
|
||||||
|
|
||||||
|
const handlePointerEnter = useCallback(() => setIsHovered(true), []);
|
||||||
|
const handlePointerLeave = useCallback(() => setIsHovered(false), []);
|
||||||
|
|
||||||
const handleEdit = useCallback(() => onEdit(profile.id), [onEdit, profile.id]);
|
const handleEdit = useCallback(() => onEdit(profile.id), [onEdit, profile.id]);
|
||||||
|
const handleDuplicate = useCallback(() => onDuplicate(profile.id), [onDuplicate, profile.id]);
|
||||||
const handleRemove = useCallback(() => onRemove(profile.id), [onRemove, profile.id]);
|
const handleRemove = useCallback(() => onRemove(profile.id), [onRemove, profile.id]);
|
||||||
const handleMoveUp = useCallback(() => onMoveUp(profile.id), [onMoveUp, profile.id]);
|
const handleMoveUp = useCallback(() => onMoveUp(profile.id), [onMoveUp, profile.id]);
|
||||||
const handleMoveDown = useCallback(() => onMoveDown(profile.id), [onMoveDown, profile.id]);
|
const handleMoveDown = useCallback(() => onMoveDown(profile.id), [onMoveDown, profile.id]);
|
||||||
|
const handleMoveToTop = useCallback(() => onMoveToTop(profile.id), [onMoveToTop, profile.id]);
|
||||||
|
|
||||||
const formatFeatureCount = useCallback(
|
const formatFeatureCount = useCallback(
|
||||||
(count: number) =>
|
(count: number) =>
|
||||||
@@ -60,125 +348,269 @@ export function AgentProfileRow({
|
|||||||
: t("settings.host.agentProfiles.featureCount", { count }),
|
: t("settings.host.agentProfiles.featureCount", { count }),
|
||||||
[t],
|
[t],
|
||||||
);
|
);
|
||||||
const tags = useMemo(
|
|
||||||
() => buildAgentProfileTags({ profile, entries, formatFeatureCount }),
|
const rosterSummary = useMemo(
|
||||||
|
() => buildAgentProfileRosterSummary({ profile, entries, formatFeatureCount }),
|
||||||
[entries, formatFeatureCount, profile],
|
[entries, formatFeatureCount, profile],
|
||||||
);
|
);
|
||||||
const summary = useMemo(() => tags.map((tag) => tag.label).join(" · "), [tags]);
|
const fullSummary = useMemo(
|
||||||
|
() => rosterSummary.allTags.map((tag) => tag.label).join(" · "),
|
||||||
|
[rosterSummary.allTags],
|
||||||
|
);
|
||||||
|
const runtimeSubline = useMemo(
|
||||||
|
() => rosterSummary.runtimeDetails.join(" · "),
|
||||||
|
[rosterSummary.runtimeDetails],
|
||||||
|
);
|
||||||
|
|
||||||
const rowStyle = useMemo(
|
const isStacked = compactLayout || isCompactFormFactor;
|
||||||
() => [settingsStyles.row, isFirst ? null : settingsStyles.rowBorder, styles.row],
|
|
||||||
[isFirst],
|
const rowContainerStyle = useMemo(
|
||||||
|
() => [
|
||||||
|
styles.row,
|
||||||
|
!isFirst && settingsStyles.rowBorder,
|
||||||
|
selected && styles.rowSelected,
|
||||||
|
(isHovered || menuProps.open) && !selected && styles.rowHovered,
|
||||||
|
dragging && styles.rowDragging,
|
||||||
|
],
|
||||||
|
[dragging, isFirst, isHovered, menuProps.open, selected],
|
||||||
|
);
|
||||||
|
|
||||||
|
const gripStyle = useMemo(
|
||||||
|
() => (showRowAffordances ? styles.grip : [styles.grip, styles.affordanceHidden]),
|
||||||
|
[showRowAffordances],
|
||||||
|
);
|
||||||
|
const kebabVisibilityStyle = useMemo(
|
||||||
|
() => [styles.kebabSlot, !showRowAffordances && styles.affordanceHidden],
|
||||||
|
[showRowAffordances],
|
||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<View style={rowStyle} testID={`agent-profile-row-${profile.id}`}>
|
<View
|
||||||
<View style={styles.rowMain}>
|
style={rowContainerStyle}
|
||||||
<View style={styles.iconWrapper}>
|
onPointerEnter={handlePointerEnter}
|
||||||
<AgentProfileGlyph icon={profile.icon} color={profile.color} size={ICON_SIZE.md} />
|
onPointerLeave={handlePointerLeave}
|
||||||
|
testID={`agent-profile-row-${profile.id}`}
|
||||||
|
>
|
||||||
|
<PressHighlight
|
||||||
|
accessibilityRole="button"
|
||||||
|
accessibilityLabel={`${profile.name}, ${fullSummary}`}
|
||||||
|
onPress={handleEdit}
|
||||||
|
style={styles.pressTarget}
|
||||||
|
highlightStyle={styles.rowPressed}
|
||||||
|
testID={`agent-profile-row-press-${profile.id}`}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{selected ? <View style={styles.selectedIndicator} pointerEvents="none" /> : null}
|
||||||
|
|
||||||
|
<AgentProfileRowContent
|
||||||
|
serverId={serverId}
|
||||||
|
profile={profile}
|
||||||
|
modelLabel={rosterSummary.modelLabel}
|
||||||
|
providerLabel={rosterSummary.providerLabel}
|
||||||
|
runtimeSubline={runtimeSubline}
|
||||||
|
fullSummary={fullSummary}
|
||||||
|
isStacked={isStacked}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* A stacked row opens on tap like the wide one; the kebab alone ends it, on the trailing rail. */}
|
||||||
|
<View style={isStacked ? styles.trailingStacked : styles.trailing}>
|
||||||
|
<View style={kebabVisibilityStyle} pointerEvents={showRowAffordances ? "auto" : "none"}>
|
||||||
|
<AgentProfileRowMenu
|
||||||
|
profileId={profile.id}
|
||||||
|
profileName={profile.name}
|
||||||
|
isFirst={isFirst}
|
||||||
|
isLast={isLast}
|
||||||
|
reorderable={reorderable}
|
||||||
|
menuProps={menuProps}
|
||||||
|
onEdit={handleEdit}
|
||||||
|
onDuplicate={handleDuplicate}
|
||||||
|
onMoveUp={handleMoveUp}
|
||||||
|
onMoveDown={handleMoveDown}
|
||||||
|
onMoveToTop={handleMoveToTop}
|
||||||
|
onRemove={handleRemove}
|
||||||
|
/>
|
||||||
</View>
|
</View>
|
||||||
<View style={settingsStyles.rowContent}>
|
{isStacked ? null : (
|
||||||
<View style={styles.titleLine}>
|
<View style={[styles.chevron, styles.passThrough]} {...HIDDEN_FROM_ASSISTIVE_TECH}>
|
||||||
<Text style={settingsStyles.rowTitle} numberOfLines={1}>
|
<ThemedChevronRight
|
||||||
{profile.name}
|
size={ICON_SIZE.sm}
|
||||||
</Text>
|
uniProps={isHovered || selected ? foregroundIconColorMapping : mutedIconColorMapping}
|
||||||
<Text style={styles.summary} numberOfLines={1}>
|
/>
|
||||||
{summary}
|
|
||||||
</Text>
|
|
||||||
</View>
|
</View>
|
||||||
{profile.notes ? (
|
)}
|
||||||
<View style={styles.notes}>
|
|
||||||
<ThemedFileText size={ICON_SIZE.xs} uniProps={mutedColorMapping} />
|
|
||||||
<Text
|
|
||||||
style={styles.notesText}
|
|
||||||
numberOfLines={2}
|
|
||||||
testID={`agent-profile-notes-${profile.id}`}
|
|
||||||
>
|
|
||||||
{profile.notes}
|
|
||||||
</Text>
|
|
||||||
</View>
|
|
||||||
) : null}
|
|
||||||
</View>
|
|
||||||
</View>
|
|
||||||
<View style={styles.rowActions}>
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
leftIcon={moveUpIcon}
|
|
||||||
onPress={handleMoveUp}
|
|
||||||
disabled={isFirst}
|
|
||||||
accessibilityLabel={t("settings.host.agentProfiles.moveUp")}
|
|
||||||
testID={`agent-profile-move-up-${profile.id}`}
|
|
||||||
/>
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
leftIcon={moveDownIcon}
|
|
||||||
onPress={handleMoveDown}
|
|
||||||
disabled={isLast}
|
|
||||||
accessibilityLabel={t("settings.host.agentProfiles.moveDown")}
|
|
||||||
testID={`agent-profile-move-down-${profile.id}`}
|
|
||||||
/>
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
leftIcon={editIcon}
|
|
||||||
onPress={handleEdit}
|
|
||||||
accessibilityLabel={t("settings.host.agentProfiles.editProfile")}
|
|
||||||
testID={`agent-profile-edit-${profile.id}`}
|
|
||||||
/>
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
leftIcon={removeIcon}
|
|
||||||
onPress={handleRemove}
|
|
||||||
accessibilityLabel={t("settings.host.agentProfiles.remove")}
|
|
||||||
testID={`agent-profile-remove-${profile.id}`}
|
|
||||||
/>
|
|
||||||
</View>
|
</View>
|
||||||
|
|
||||||
|
{reorderable ? (
|
||||||
|
<DraggableListHandle
|
||||||
|
accessibilityLabel={t("settings.host.agentProfiles.reorderProfile", {
|
||||||
|
name: profile.name,
|
||||||
|
})}
|
||||||
|
style={gripStyle}
|
||||||
|
testID={`agent-profile-drag-${profile.id}`}
|
||||||
|
>
|
||||||
|
<ThemedGripVertical size={ICON_SIZE.sm} uniProps={extraMutedIconColorMapping} />
|
||||||
|
</DraggableListHandle>
|
||||||
|
) : null}
|
||||||
</View>
|
</View>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const styles = StyleSheet.create((theme) => ({
|
const styles = StyleSheet.create((theme) => ({
|
||||||
row: {
|
row: {
|
||||||
gap: theme.spacing[2],
|
position: "relative",
|
||||||
minHeight: 56,
|
|
||||||
alignItems: "center",
|
|
||||||
paddingVertical: theme.spacing[3],
|
|
||||||
},
|
|
||||||
rowMain: {
|
|
||||||
flex: 1,
|
|
||||||
flexDirection: "row",
|
flexDirection: "row",
|
||||||
alignItems: "flex-start",
|
alignItems: "center",
|
||||||
|
minHeight: ROW_MIN_HEIGHT,
|
||||||
|
paddingVertical: theme.spacing[3],
|
||||||
|
paddingHorizontal: theme.spacing[4],
|
||||||
gap: theme.spacing[2],
|
gap: theme.spacing[2],
|
||||||
},
|
},
|
||||||
iconWrapper: {
|
rowHovered: {
|
||||||
width: theme.iconSize.md,
|
backgroundColor: theme.colors.surface2,
|
||||||
|
},
|
||||||
|
rowSelected: {
|
||||||
|
backgroundColor: theme.colors.surface3,
|
||||||
|
},
|
||||||
|
selectedIndicator: {
|
||||||
|
position: "absolute",
|
||||||
|
left: 0,
|
||||||
|
top: theme.spacing[2],
|
||||||
|
bottom: theme.spacing[2],
|
||||||
|
width: theme.borderWidth[2],
|
||||||
|
borderRadius: theme.borderRadius.full,
|
||||||
|
backgroundColor: theme.colors.accent,
|
||||||
|
},
|
||||||
|
rowPressed: {
|
||||||
|
backgroundColor: theme.colors.surface3,
|
||||||
|
},
|
||||||
|
rowDragging: {
|
||||||
|
backgroundColor: theme.colors.surface2,
|
||||||
|
},
|
||||||
|
pressTarget: {
|
||||||
|
...StyleSheet.absoluteFill,
|
||||||
|
},
|
||||||
|
passThrough: {
|
||||||
|
pointerEvents: "none",
|
||||||
|
},
|
||||||
|
// The grip hangs in the row's leading padding, as on a Usage card, so the icon tile sits on the
|
||||||
|
// card's rail with or without it and revealing it on hover moves nothing. It takes the padding's
|
||||||
|
// full height so a finger finds it.
|
||||||
|
grip: {
|
||||||
|
position: "absolute",
|
||||||
|
left: 0,
|
||||||
|
top: 0,
|
||||||
|
bottom: 0,
|
||||||
|
width: theme.spacing[4],
|
||||||
alignItems: "center",
|
alignItems: "center",
|
||||||
justifyContent: "center",
|
justifyContent: "center",
|
||||||
marginTop: 1,
|
|
||||||
},
|
},
|
||||||
titleLine: {
|
affordanceHidden: {
|
||||||
|
opacity: 0,
|
||||||
|
},
|
||||||
|
iconTile: {
|
||||||
|
width: theme.spacing[7],
|
||||||
|
height: theme.spacing[7],
|
||||||
|
borderRadius: theme.borderRadius.md,
|
||||||
|
backgroundColor: theme.colors.surface2,
|
||||||
|
alignItems: "center",
|
||||||
|
justifyContent: "center",
|
||||||
|
flexShrink: 0,
|
||||||
|
},
|
||||||
|
columns: {
|
||||||
|
flex: 1,
|
||||||
|
minWidth: 0,
|
||||||
flexDirection: "row",
|
flexDirection: "row",
|
||||||
alignItems: "baseline",
|
alignItems: "center",
|
||||||
|
gap: theme.spacing[4],
|
||||||
|
},
|
||||||
|
colProfile: {
|
||||||
|
width: ROSTER_COL_PROFILE_WIDTH,
|
||||||
|
flexShrink: 0,
|
||||||
|
flexDirection: "row",
|
||||||
|
alignItems: "center",
|
||||||
gap: theme.spacing[2],
|
gap: theme.spacing[2],
|
||||||
minWidth: 0,
|
minWidth: 0,
|
||||||
},
|
},
|
||||||
summary: {
|
colRuntime: {
|
||||||
|
width: ROSTER_COL_RUNTIME_WIDTH,
|
||||||
|
flexShrink: 0,
|
||||||
|
gap: theme.spacing[0.5],
|
||||||
|
minWidth: 0,
|
||||||
|
},
|
||||||
|
colNotes: {
|
||||||
|
flex: 1,
|
||||||
|
minWidth: 0,
|
||||||
|
},
|
||||||
|
nameText: {
|
||||||
|
flexShrink: 1,
|
||||||
|
color: theme.colors.foreground,
|
||||||
|
fontSize: theme.fontSize.base,
|
||||||
|
fontWeight: theme.fontWeight.normal,
|
||||||
|
},
|
||||||
|
modelLine: {
|
||||||
|
flexDirection: "row",
|
||||||
|
alignItems: "center",
|
||||||
|
gap: theme.spacing[1.5],
|
||||||
|
minWidth: 0,
|
||||||
|
},
|
||||||
|
modelText: {
|
||||||
|
flexShrink: 1,
|
||||||
|
color: theme.colors.foreground,
|
||||||
|
fontSize: theme.fontSize.sm,
|
||||||
|
},
|
||||||
|
runtimeSubtext: {
|
||||||
|
color: theme.colors.foregroundExtraMuted,
|
||||||
|
fontSize: theme.fontSize.sm,
|
||||||
|
},
|
||||||
|
notesText: {
|
||||||
|
color: theme.colors.foregroundMuted,
|
||||||
|
fontSize: theme.fontSize.sm,
|
||||||
|
},
|
||||||
|
notesEmptyText: {
|
||||||
|
color: theme.colors.foregroundExtraMuted,
|
||||||
|
fontSize: theme.fontSize.sm,
|
||||||
|
},
|
||||||
|
stackedMain: {
|
||||||
|
flex: 1,
|
||||||
|
minWidth: 0,
|
||||||
|
flexDirection: "row",
|
||||||
|
alignItems: "flex-start",
|
||||||
|
gap: theme.spacing[3],
|
||||||
|
},
|
||||||
|
stackedContent: {
|
||||||
|
flex: 1,
|
||||||
|
minWidth: 0,
|
||||||
|
gap: theme.spacing[0.5],
|
||||||
|
},
|
||||||
|
stackedSpecText: {
|
||||||
flexShrink: 1,
|
flexShrink: 1,
|
||||||
color: theme.colors.foregroundMuted,
|
color: theme.colors.foregroundMuted,
|
||||||
fontSize: theme.fontSize.sm,
|
fontSize: theme.fontSize.sm,
|
||||||
},
|
},
|
||||||
notes: {
|
stackedNotesText: {
|
||||||
flexDirection: "row",
|
color: theme.colors.foregroundExtraMuted,
|
||||||
alignItems: "flex-start",
|
|
||||||
gap: theme.spacing[1],
|
|
||||||
marginTop: theme.spacing[1],
|
|
||||||
},
|
|
||||||
notesText: {
|
|
||||||
flex: 1,
|
|
||||||
color: theme.colors.foregroundMuted,
|
|
||||||
fontSize: theme.fontSize.sm,
|
fontSize: theme.fontSize.sm,
|
||||||
|
marginTop: theme.spacing[0.5],
|
||||||
},
|
},
|
||||||
rowActions: {
|
trailing: {
|
||||||
|
width: ROSTER_TRAILING_WIDTH,
|
||||||
flexDirection: "row",
|
flexDirection: "row",
|
||||||
alignItems: "center",
|
alignItems: "center",
|
||||||
|
justifyContent: "flex-end",
|
||||||
|
gap: theme.spacing[1],
|
||||||
|
flexShrink: 0,
|
||||||
|
},
|
||||||
|
trailingStacked: {
|
||||||
|
flexShrink: 0,
|
||||||
|
marginRight: mapLayout(KEBAB_HITBOX_OVERHANG, (overhang) => -overhang),
|
||||||
|
marginVertical: mapLayout(KEBAB_HITBOX_OVERHANG, (overhang) => -overhang),
|
||||||
|
},
|
||||||
|
kebabSlot: {
|
||||||
|
alignItems: "center",
|
||||||
|
justifyContent: "center",
|
||||||
|
},
|
||||||
|
// Optical: matches SettingsRowHeader so the chevron sits on the card's trailing rail.
|
||||||
|
chevron: {
|
||||||
|
marginRight: -theme.spacing[1],
|
||||||
},
|
},
|
||||||
}));
|
}));
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -1,8 +1,8 @@
|
|||||||
import { useLocalSearchParams } from "expo-router";
|
import { Redirect, useLocalSearchParams } from "expo-router";
|
||||||
import { useMemo } from "react";
|
import { useMemo } from "react";
|
||||||
import { HostRouteBootstrapBoundary } from "@/components/host-route-bootstrap-boundary";
|
import { HostRouteBootstrapBoundary } from "@/components/host-route-bootstrap-boundary";
|
||||||
import SettingsScreen from "@/screens/settings-screen";
|
import SettingsScreen from "@/screens/settings-screen";
|
||||||
import { normalizeHostSectionSlug } from "@/utils/host-routes";
|
import { buildSettingsHostSectionRoute, normalizeHostSectionSlug } from "@/utils/host-routes";
|
||||||
|
|
||||||
export default function SettingsHostSectionRoute() {
|
export default function SettingsHostSectionRoute() {
|
||||||
const params = useLocalSearchParams<{ serverId?: string; hostSection?: string }>();
|
const params = useLocalSearchParams<{ serverId?: string; hostSection?: string }>();
|
||||||
@@ -11,6 +11,10 @@ export default function SettingsHostSectionRoute() {
|
|||||||
const section = normalizeHostSectionSlug(rawSection) ?? "connections";
|
const section = normalizeHostSectionSlug(rawSection) ?? "connections";
|
||||||
const view = useMemo(() => ({ kind: "host" as const, serverId, section }), [serverId, section]);
|
const view = useMemo(() => ({ kind: "host" as const, serverId, section }), [serverId, section]);
|
||||||
|
|
||||||
|
if (rawSection === "pair-device" && serverId) {
|
||||||
|
return <Redirect href={buildSettingsHostSectionRoute(serverId, "devices")} />;
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<HostRouteBootstrapBoundary>
|
<HostRouteBootstrapBoundary>
|
||||||
<SettingsScreen view={view} />
|
<SettingsScreen view={view} />
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { resolveFilePreviewReadTarget } from "@/file-explorer/preview-target";
|
||||||
|
import { resolveWorkspaceFilePaths } from "@/workspace/file-open";
|
||||||
import {
|
import {
|
||||||
classifyAssistantFileLink,
|
classifyAssistantFileLink,
|
||||||
normalizeInlinePathTarget,
|
normalizeInlinePathTarget,
|
||||||
@@ -611,3 +613,43 @@ describe("encoded filename line markers", () => {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("slash-prefixed drive links in Windows workspaces", () => {
|
||||||
|
it.each([
|
||||||
|
["/E:/demo/repo/tools/tool.vbs", "E:/demo/repo/tools/tool.vbs", undefined],
|
||||||
|
["/E:/demo/repo/docs/my%20file.md#L12", "E:/demo/repo/docs/my file.md", 12],
|
||||||
|
["/E:/demo/repo/docs/guide.md:12", "E:/demo/repo/docs/guide.md", 12],
|
||||||
|
["E:/demo/repo/tools/tool.vbs", "E:/demo/repo/tools/tool.vbs", undefined],
|
||||||
|
["file:///E:/demo/repo/tools/tool.vbs", "E:/demo/repo/tools/tool.vbs", undefined],
|
||||||
|
])("resolves %s to the workspace read target", (href, path, lineStart) => {
|
||||||
|
const workspaceRoot = "E:\\demo\\repo";
|
||||||
|
const target = parseAssistantFileLink(href, {
|
||||||
|
workspaceRoot,
|
||||||
|
decodeHref: true,
|
||||||
|
explicitLink: true,
|
||||||
|
});
|
||||||
|
expect(target).toMatchObject({ raw: href, path });
|
||||||
|
expect(target?.lineStart).toBe(lineStart);
|
||||||
|
expect(resolveFilePreviewReadTarget({ path: target!.path, workspaceRoot })).toEqual({
|
||||||
|
cwd: workspaceRoot,
|
||||||
|
path,
|
||||||
|
});
|
||||||
|
expect(resolveWorkspaceFilePaths({ path: target!.path, workspaceRoot })).toEqual({
|
||||||
|
absolutePath: path,
|
||||||
|
relativePath: path.slice("E:/demo/repo/".length),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each(["/home/demo/repo", undefined])(
|
||||||
|
"preserves POSIX paths with workspace %s",
|
||||||
|
(workspaceRoot) => {
|
||||||
|
expect(
|
||||||
|
parseAssistantFileLink("/E:/demo/repo/tools/tool.vbs", {
|
||||||
|
workspaceRoot,
|
||||||
|
decodeHref: true,
|
||||||
|
explicitLink: true,
|
||||||
|
})?.path,
|
||||||
|
).toBe("/E:/demo/repo/tools/tool.vbs");
|
||||||
|
},
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|||||||
@@ -260,7 +260,7 @@ export function parseAssistantFileLink(
|
|||||||
return fileUrlTarget;
|
return fileUrlTarget;
|
||||||
}
|
}
|
||||||
|
|
||||||
const trimmed = value?.trim();
|
const trimmed = normalizeWindowsLinkPath(value?.trim(), options.workspaceRoot);
|
||||||
if (!trimmed) {
|
if (!trimmed) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -271,7 +271,7 @@ export function parseAssistantFileLink(
|
|||||||
|
|
||||||
const inlinePathTarget = parseAssistantInlinePathLink(trimmed, options);
|
const inlinePathTarget = parseAssistantInlinePathLink(trimmed, options);
|
||||||
if (inlinePathTarget) {
|
if (inlinePathTarget) {
|
||||||
return inlinePathTarget;
|
return { ...inlinePathTarget, raw: value };
|
||||||
}
|
}
|
||||||
|
|
||||||
const windowsTarget = parseWindowsFileLink(trimmed, value, options);
|
const windowsTarget = parseWindowsFileLink(trimmed, value, options);
|
||||||
@@ -350,6 +350,14 @@ export function isFileLookingAssistantToken(value: string): boolean {
|
|||||||
return isPlausibleAssistantLocalPath(path);
|
return isPlausibleAssistantLocalPath(path);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A drive-based workspace identifies the target host's path syntax, even when
|
||||||
|
// the client runs elsewhere. Preserve the same spelling on POSIX hosts.
|
||||||
|
function normalizeWindowsLinkPath(value: string, workspaceRoot?: string): string {
|
||||||
|
return /^[A-Za-z]:[\\/]/.test(workspaceRoot?.trim() ?? "") && /^\/[A-Za-z]:[\\/]/.test(value)
|
||||||
|
? value.slice(1)
|
||||||
|
: value;
|
||||||
|
}
|
||||||
|
|
||||||
function parseWindowsFileLink(
|
function parseWindowsFileLink(
|
||||||
trimmed: string,
|
trimmed: string,
|
||||||
raw: string,
|
raw: string,
|
||||||
|
|||||||
@@ -1,48 +0,0 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
|
||||||
import { getCompactSheetSafeAreaPadding } from "@/components/adaptive-modal-sheet-layout";
|
|
||||||
|
|
||||||
describe("getCompactSheetSafeAreaPadding", () => {
|
|
||||||
it("assigns safe clearance to the footer independently of decorative padding", () => {
|
|
||||||
expect(
|
|
||||||
getCompactSheetSafeAreaPadding({
|
|
||||||
isCompact: true,
|
|
||||||
isKeyboardVisible: false,
|
|
||||||
hasFooter: true,
|
|
||||||
safeAreaBottom: 34,
|
|
||||||
}),
|
|
||||||
).toEqual({ footerPaddingBottom: 34 });
|
|
||||||
});
|
|
||||||
|
|
||||||
it("assigns safe clearance to the body only without a footer", () => {
|
|
||||||
expect(
|
|
||||||
getCompactSheetSafeAreaPadding({
|
|
||||||
isCompact: true,
|
|
||||||
isKeyboardVisible: false,
|
|
||||||
hasFooter: false,
|
|
||||||
safeAreaBottom: 34,
|
|
||||||
}),
|
|
||||||
).toEqual({ contentPaddingBottom: 34 });
|
|
||||||
});
|
|
||||||
|
|
||||||
it("does not add a safe-area band above the compact keyboard", () => {
|
|
||||||
expect(
|
|
||||||
getCompactSheetSafeAreaPadding({
|
|
||||||
isCompact: true,
|
|
||||||
isKeyboardVisible: true,
|
|
||||||
hasFooter: false,
|
|
||||||
safeAreaBottom: 34,
|
|
||||||
}),
|
|
||||||
).toEqual({});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("does not inset desktop sheets", () => {
|
|
||||||
expect(
|
|
||||||
getCompactSheetSafeAreaPadding({
|
|
||||||
isCompact: false,
|
|
||||||
isKeyboardVisible: false,
|
|
||||||
hasFooter: false,
|
|
||||||
safeAreaBottom: 34,
|
|
||||||
}),
|
|
||||||
).toEqual({});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
export interface CompactSheetSafeAreaPaddingInput {
|
|
||||||
isCompact: boolean;
|
|
||||||
isKeyboardVisible: boolean;
|
|
||||||
hasFooter: boolean;
|
|
||||||
safeAreaBottom: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface CompactSheetSafeAreaPadding {
|
|
||||||
contentPaddingBottom?: number;
|
|
||||||
footerPaddingBottom?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getCompactSheetSafeAreaPadding({
|
|
||||||
isCompact,
|
|
||||||
isKeyboardVisible,
|
|
||||||
hasFooter,
|
|
||||||
safeAreaBottom,
|
|
||||||
}: CompactSheetSafeAreaPaddingInput): CompactSheetSafeAreaPadding {
|
|
||||||
if (!isCompact || isKeyboardVisible || safeAreaBottom <= 0) {
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
|
|
||||||
if (hasFooter) {
|
|
||||||
return { footerPaddingBottom: safeAreaBottom };
|
|
||||||
}
|
|
||||||
|
|
||||||
return { contentPaddingBottom: safeAreaBottom };
|
|
||||||
}
|
|
||||||
@@ -20,12 +20,11 @@ import {
|
|||||||
IsolatedBottomSheetModal,
|
IsolatedBottomSheetModal,
|
||||||
SheetVisibleFrame,
|
SheetVisibleFrame,
|
||||||
type ContextBridge,
|
type ContextBridge,
|
||||||
|
useBottomSheetSafeAreaPaddingStyle,
|
||||||
useIsolatedBottomSheetVisibility,
|
useIsolatedBottomSheetVisibility,
|
||||||
} from "@/components/ui/isolated-bottom-sheet-modal";
|
} from "@/components/ui/isolated-bottom-sheet-modal";
|
||||||
import { getCompactSheetSafeAreaPadding } from "@/components/adaptive-modal-sheet-layout";
|
|
||||||
import { ScrollView } from "@/components/ui/scroll-view";
|
import { ScrollView } from "@/components/ui/scroll-view";
|
||||||
import { isWeb } from "@/constants/platform";
|
import { isWeb } from "@/constants/platform";
|
||||||
import { useKeyboardVisibility } from "@/hooks/use-keyboard-visibility";
|
|
||||||
import { SafeAreaInsetsContext, useSafeAreaInsets } from "react-native-safe-area-context";
|
import { SafeAreaInsetsContext, useSafeAreaInsets } from "react-native-safe-area-context";
|
||||||
import { AdaptiveTextInput } from "@/components/adaptive-text-input";
|
import { AdaptiveTextInput } from "@/components/adaptive-text-input";
|
||||||
import { useDismissibleOverlay } from "@/components/ui/overlay-dismissal";
|
import { useDismissibleOverlay } from "@/components/ui/overlay-dismissal";
|
||||||
@@ -610,8 +609,9 @@ export interface SheetKeyboard {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The compact sheet's body. It renders on the far side of the sheet's portal so it reads the
|
* The compact sheet's body. It renders on the far side of the sheet's portal so `SheetVisibleFrame`
|
||||||
* screen's bottom inset, not the one left where the sheet was opened: inside a sheet tab, none is.
|
* and `useBottomSheetSafeAreaPaddingStyle` read the screen's bottom inset, not the one left where
|
||||||
|
* the sheet was opened: inside a sheet tab, none is.
|
||||||
*/
|
*/
|
||||||
function CompactSheetBody({
|
function CompactSheetBody({
|
||||||
header,
|
header,
|
||||||
@@ -619,7 +619,6 @@ function CompactSheetBody({
|
|||||||
onClose,
|
onClose,
|
||||||
testID,
|
testID,
|
||||||
footer,
|
footer,
|
||||||
isKeyboardVisible,
|
|
||||||
scrollable,
|
scrollable,
|
||||||
bodyStyle,
|
bodyStyle,
|
||||||
contentStyle,
|
contentStyle,
|
||||||
@@ -630,32 +629,18 @@ function CompactSheetBody({
|
|||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
testID?: string;
|
testID?: string;
|
||||||
footer: ReactNode;
|
footer: ReactNode;
|
||||||
isKeyboardVisible: boolean;
|
|
||||||
scrollable: boolean;
|
scrollable: boolean;
|
||||||
bodyStyle?: StyleProp<ViewStyle>;
|
bodyStyle?: StyleProp<ViewStyle>;
|
||||||
contentStyle?: StyleProp<ViewStyle>;
|
contentStyle?: StyleProp<ViewStyle>;
|
||||||
children: ReactNode;
|
children: ReactNode;
|
||||||
}) {
|
}) {
|
||||||
const insets = useSafeAreaInsets();
|
// Safe-area clearance is owned on the UI thread in lockstep with `SheetVisibleFrame`'s keyboard
|
||||||
const { contentPaddingBottom = 0, footerPaddingBottom = 0 } = getCompactSheetSafeAreaPadding({
|
// height: `SheetVisibleFrame` pads the frame whenever a footer or non-scrollable body is shown,
|
||||||
isCompact: true,
|
// while a scrollable body without a footer pads its scroll content so items scroll behind the
|
||||||
isKeyboardVisible,
|
// system bar and still clear it at rest.
|
||||||
hasFooter: Boolean(footer),
|
const bodyClearanceStyle = useBottomSheetSafeAreaPaddingStyle(scrollable && !footer);
|
||||||
safeAreaBottom: insets.bottom,
|
|
||||||
});
|
|
||||||
// Safe-area clearance is a separate layer: it must not replace the caller's
|
|
||||||
// padding (including an explicit zero), and the footer owns it when present.
|
|
||||||
const bodyClearanceStyle = { paddingBottom: contentPaddingBottom };
|
|
||||||
const footerClearanceStyle = useMemo(
|
|
||||||
() => ({ paddingBottom: footerPaddingBottom }),
|
|
||||||
[footerPaddingBottom],
|
|
||||||
);
|
|
||||||
const footerView = useMemo(
|
|
||||||
() => (footer ? <View style={footerClearanceStyle}>{footer}</View> : null),
|
|
||||||
[footer, footerClearanceStyle],
|
|
||||||
);
|
|
||||||
return (
|
return (
|
||||||
<SheetVisibleFrame footer={footerView}>
|
<SheetVisibleFrame footer={footer} safeAreaInset={scrollable ? "footer" : "frame"}>
|
||||||
{header ? (
|
{header ? (
|
||||||
<SheetHeaderView
|
<SheetHeaderView
|
||||||
header={header}
|
header={header}
|
||||||
@@ -672,12 +657,12 @@ function CompactSheetBody({
|
|||||||
keyboardShouldPersistTaps="handled"
|
keyboardShouldPersistTaps="handled"
|
||||||
showsVerticalScrollIndicator={false}
|
showsVerticalScrollIndicator={false}
|
||||||
>
|
>
|
||||||
<View style={[styles.contentGrow, bodyClearanceStyle]}>
|
<Animated.View style={[SCROLL_CONTENT_GROW, bodyClearanceStyle]}>
|
||||||
<SheetContent style={[styles.contentGrow, contentStyle]}>{children}</SheetContent>
|
<SheetContent style={[styles.contentGrow, contentStyle]}>{children}</SheetContent>
|
||||||
</View>
|
</Animated.View>
|
||||||
</ScrollView>
|
</ScrollView>
|
||||||
) : (
|
) : (
|
||||||
<View style={[styles.compactStaticContent, bodyClearanceStyle]}>
|
<View style={styles.compactStaticContent}>
|
||||||
<SheetContent style={[styles.compactStaticContent, contentStyle]}>
|
<SheetContent style={[styles.compactStaticContent, contentStyle]}>
|
||||||
{children}
|
{children}
|
||||||
</SheetContent>
|
</SheetContent>
|
||||||
@@ -710,7 +695,6 @@ export function AdaptiveModalSheet({
|
|||||||
}: AdaptiveModalSheetProps) {
|
}: AdaptiveModalSheetProps) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const isMobile = useIsCompactFormFactor();
|
const isMobile = useIsCompactFormFactor();
|
||||||
const isKeyboardVisible = useKeyboardVisibility(visible);
|
|
||||||
const resolvedSnapPoints = useMemo(() => snapPoints ?? ["65%", "90%"], [snapPoints]);
|
const resolvedSnapPoints = useMemo(() => snapPoints ?? ["65%", "90%"], [snapPoints]);
|
||||||
const isSheet = isMobile || !isWeb;
|
const isSheet = isMobile || !isWeb;
|
||||||
// The sheet registers itself; the desktop dialog does not use it.
|
// The sheet registers itself; the desktop dialog does not use it.
|
||||||
@@ -828,7 +812,6 @@ export function AdaptiveModalSheet({
|
|||||||
onClose={onClose}
|
onClose={onClose}
|
||||||
testID={testID}
|
testID={testID}
|
||||||
footer={footerView}
|
footer={footerView}
|
||||||
isKeyboardVisible={isKeyboardVisible}
|
|
||||||
scrollable={scrollable}
|
scrollable={scrollable}
|
||||||
bodyStyle={bodyStyle}
|
bodyStyle={bodyStyle}
|
||||||
contentStyle={contentStyle}
|
contentStyle={contentStyle}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { Pressable, Text, View, type PressableStateCallbackType } from "react-na
|
|||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||||
import type { AgentProvider } from "@getpaseo/protocol/agent-types";
|
import type { AgentProvider } from "@getpaseo/protocol/agent-types";
|
||||||
import type { AgentProfilePicker, AgentProfileSeed } from "@/agent-profiles";
|
import type { AgentProfile, AgentProfilePicker, AgentProfileSeed } from "@/agent-profiles";
|
||||||
import { ComboboxTrigger } from "@/components/ui/combobox-trigger";
|
import { ComboboxTrigger } from "@/components/ui/combobox-trigger";
|
||||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||||
import { Combobox, type ComboboxOption, type ComboboxProps } from "@/components/ui/combobox";
|
import { Combobox, type ComboboxOption, type ComboboxProps } from "@/components/ui/combobox";
|
||||||
@@ -40,7 +40,7 @@ interface CombinedModelSelectorProps {
|
|||||||
profiles?: AgentProfilePicker | null;
|
profiles?: AgentProfilePicker | null;
|
||||||
onApplyProfile?: (profileId: string) => void;
|
onApplyProfile?: (profileId: string) => void;
|
||||||
onEditProfiles?: () => void;
|
onEditProfiles?: () => void;
|
||||||
onCreateProfile?: (seed: AgentProfileSeed) => void;
|
onCreateProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
|
||||||
onEditProfile?: (profileId: string) => void;
|
onEditProfile?: (profileId: string) => void;
|
||||||
renderTrigger?: (input: {
|
renderTrigger?: (input: {
|
||||||
selectedModelLabel: string;
|
selectedModelLabel: string;
|
||||||
@@ -195,12 +195,17 @@ export function CombinedModelSelector({
|
|||||||
onEditProfiles?.();
|
onEditProfiles?.();
|
||||||
}, [handleOpenChange, onEditProfiles]);
|
}, [handleOpenChange, onEditProfiles]);
|
||||||
|
|
||||||
|
// 1-tap `+` saves the profile, selects the model immediately, and closes the picker;
|
||||||
|
// useAgentProfileEditor surfaces a toast with Edit and Undo actions.
|
||||||
const handleCreateProfile = useCallback(
|
const handleCreateProfile = useCallback(
|
||||||
(seed: AgentProfileSeed) => {
|
(seed: AgentProfileSeed) => {
|
||||||
|
if (seed.modelId) {
|
||||||
|
onSelect(seed.provider, seed.modelId);
|
||||||
|
}
|
||||||
handleOpenChange(false);
|
handleOpenChange(false);
|
||||||
onCreateProfile?.(seed);
|
void onCreateProfile?.(seed);
|
||||||
},
|
},
|
||||||
[handleOpenChange, onCreateProfile],
|
[handleOpenChange, onCreateProfile, onSelect],
|
||||||
);
|
);
|
||||||
|
|
||||||
const handleEditProfile = useCallback(
|
const handleEditProfile = useCallback(
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ import DraggableFlatList, {
|
|||||||
} from "react-native-draggable-flatlist";
|
} from "react-native-draggable-flatlist";
|
||||||
import type { GestureType } from "react-native-gesture-handler";
|
import type { GestureType } from "react-native-gesture-handler";
|
||||||
import { useUnistyles } from "react-native-unistyles";
|
import { useUnistyles } from "react-native-unistyles";
|
||||||
import { useContentDrag } from "@/components/ui/scroll-view";
|
import { useContentDrag } from "@/components/ui/content-drag";
|
||||||
import { createDragHold } from "./drag-reorder/drag-hold";
|
import { createDragHold } from "./drag-reorder/drag-hold";
|
||||||
import { movedItemKey } from "./drag-reorder/native-drop";
|
import { movedItemKey } from "./drag-reorder/native-drop";
|
||||||
import type {
|
import type {
|
||||||
|
|||||||
@@ -232,6 +232,7 @@ export interface HostPickerProps {
|
|||||||
open: boolean;
|
open: boolean;
|
||||||
onOpenChange: (open: boolean) => void;
|
onOpenChange: (open: boolean) => void;
|
||||||
anchorRef: React.RefObject<View | null>;
|
anchorRef: React.RefObject<View | null>;
|
||||||
|
restoreFocusRef?: ComboboxProps["restoreFocusRef"];
|
||||||
includeAllHost?: boolean;
|
includeAllHost?: boolean;
|
||||||
includeAddHost?: boolean;
|
includeAddHost?: boolean;
|
||||||
onAddHost?: () => void;
|
onAddHost?: () => void;
|
||||||
@@ -254,6 +255,7 @@ export function HostPicker({
|
|||||||
open,
|
open,
|
||||||
onOpenChange,
|
onOpenChange,
|
||||||
anchorRef,
|
anchorRef,
|
||||||
|
restoreFocusRef,
|
||||||
includeAllHost,
|
includeAllHost,
|
||||||
includeAddHost,
|
includeAddHost,
|
||||||
onAddHost,
|
onAddHost,
|
||||||
@@ -404,6 +406,7 @@ export function HostPicker({
|
|||||||
open={open}
|
open={open}
|
||||||
onOpenChange={onOpenChange}
|
onOpenChange={onOpenChange}
|
||||||
anchorRef={anchorRef}
|
anchorRef={anchorRef}
|
||||||
|
restoreFocusRef={restoreFocusRef}
|
||||||
desktopPlacement={desktopPlacement}
|
desktopPlacement={desktopPlacement}
|
||||||
desktopMinWidth={desktopMinWidth}
|
desktopMinWidth={desktopMinWidth}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -55,6 +55,7 @@ import { HostPicker } from "@/components/hosts/host-picker";
|
|||||||
import { SidebarDisplayPreferencesMenu } from "@/components/sidebar/display-preferences/menu";
|
import { SidebarDisplayPreferencesMenu } from "@/components/sidebar/display-preferences/menu";
|
||||||
import { SidebarSeparator } from "@/components/sidebar/sidebar-separator";
|
import { SidebarSeparator } from "@/components/sidebar/sidebar-separator";
|
||||||
import { SidebarToastRegion } from "@/components/sidebar/sidebar-toast-region";
|
import { SidebarToastRegion } from "@/components/sidebar/sidebar-toast-region";
|
||||||
|
import { SidebarSelectionHost } from "@/sidebar-selection";
|
||||||
import { SidebarNavRows, useVisibleSidebarNavItems } from "@/components/sidebar/sidebar-nav-rows";
|
import { SidebarNavRows, useVisibleSidebarNavItems } from "@/components/sidebar/sidebar-nav-rows";
|
||||||
import { SidebarFooterIconHighlight } from "@/components/sidebar/sidebar-footer-icon-highlight";
|
import { SidebarFooterIconHighlight } from "@/components/sidebar/sidebar-footer-icon-highlight";
|
||||||
import { SidebarHelpMenu } from "@/components/sidebar/sidebar-help-menu";
|
import { SidebarHelpMenu } from "@/components/sidebar/sidebar-help-menu";
|
||||||
@@ -667,6 +668,7 @@ function MobileSidebar({
|
|||||||
listHeaderComponent={workspacesSectionHeaderElement}
|
listHeaderComponent={workspacesSectionHeaderElement}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
<SidebarSelectionHost active={active} workspaceEntriesByKey={workspaceEntriesByKey} />
|
||||||
</SidebarToastRegion>
|
</SidebarToastRegion>
|
||||||
</SidebarViewSlot>
|
</SidebarViewSlot>
|
||||||
|
|
||||||
@@ -922,6 +924,7 @@ function DesktopSidebar({
|
|||||||
listHeaderComponent={workspacesSectionHeaderElement}
|
listHeaderComponent={workspacesSectionHeaderElement}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
<SidebarSelectionHost active={active} workspaceEntriesByKey={workspaceEntriesByKey} />
|
||||||
</SidebarToastRegion>
|
</SidebarToastRegion>
|
||||||
</SidebarViewSlot>
|
</SidebarViewSlot>
|
||||||
|
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ import {
|
|||||||
import type { AgentProvider } from "@getpaseo/protocol/agent-types";
|
import type { AgentProvider } from "@getpaseo/protocol/agent-types";
|
||||||
import {
|
import {
|
||||||
AgentProfileGlyph,
|
AgentProfileGlyph,
|
||||||
|
type AgentProfile,
|
||||||
type AgentProfilePicker,
|
type AgentProfilePicker,
|
||||||
type AgentProfilePickerRow as AgentProfilePickerRowModel,
|
type AgentProfilePickerRow as AgentProfilePickerRowModel,
|
||||||
type AgentProfileSeed,
|
type AgentProfileSeed,
|
||||||
@@ -221,7 +222,7 @@ interface ModelBrowserProps {
|
|||||||
/** Applying a profile resolves the pick and dismisses, exactly like a model row. */
|
/** Applying a profile resolves the pick and dismisses, exactly like a model row. */
|
||||||
onApplyProfile?: (profileId: string) => void;
|
onApplyProfile?: (profileId: string) => void;
|
||||||
onEditProfiles?: () => void;
|
onEditProfiles?: () => void;
|
||||||
onCreateProfile?: (seed: AgentProfileSeed) => void;
|
onCreateProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
|
||||||
onEditProfile?: (profileId: string) => void;
|
onEditProfile?: (profileId: string) => void;
|
||||||
onRetryProvider?: (provider: AgentProvider) => void;
|
onRetryProvider?: (provider: AgentProvider) => void;
|
||||||
isRetryingProvider?: boolean;
|
isRetryingProvider?: boolean;
|
||||||
@@ -695,7 +696,7 @@ function ModelRow({
|
|||||||
showProviderLabel?: boolean;
|
showProviderLabel?: boolean;
|
||||||
onPress: () => void;
|
onPress: () => void;
|
||||||
profiledRows: AgentProfilePickerRowModel[];
|
profiledRows: AgentProfilePickerRowModel[];
|
||||||
onCreateProfile?: (seed: AgentProfileSeed) => void;
|
onCreateProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
|
||||||
onEditProfile?: (profileId: string) => void;
|
onEditProfile?: (profileId: string) => void;
|
||||||
onEditProfiles?: () => void;
|
onEditProfiles?: () => void;
|
||||||
}) {
|
}) {
|
||||||
@@ -758,7 +759,13 @@ function ModelRow({
|
|||||||
label={t("modelSelector.editProfileLabel", { name: primary.name })}
|
label={t("modelSelector.editProfileLabel", { name: primary.name })}
|
||||||
testID={`model-edit-profile-${row.provider}-${row.modelId}`}
|
testID={`model-edit-profile-${row.provider}-${row.modelId}`}
|
||||||
>
|
>
|
||||||
<AgentProfileGlyph icon={primary.icon} color={primary.color} size={ICON_SIZE.xs} />
|
<AgentProfileGlyph
|
||||||
|
icon={primary.icon}
|
||||||
|
color={primary.color}
|
||||||
|
provider={primary.provider}
|
||||||
|
serverId={serverId}
|
||||||
|
size={ICON_SIZE.xs}
|
||||||
|
/>
|
||||||
</ModelRowProfileAction>
|
</ModelRowProfileAction>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -772,7 +779,13 @@ function ModelRow({
|
|||||||
label={t("modelSelector.editProfilesCount", { count: profiledRows.length })}
|
label={t("modelSelector.editProfilesCount", { count: profiledRows.length })}
|
||||||
testID={`model-edit-profiles-${row.provider}-${row.modelId}`}
|
testID={`model-edit-profiles-${row.provider}-${row.modelId}`}
|
||||||
>
|
>
|
||||||
<AgentProfileGlyph icon={primary.icon} color={primary.color} size={ICON_SIZE.xs} />
|
<AgentProfileGlyph
|
||||||
|
icon={primary.icon}
|
||||||
|
color={primary.color}
|
||||||
|
provider={primary.provider}
|
||||||
|
serverId={serverId}
|
||||||
|
size={ICON_SIZE.xs}
|
||||||
|
/>
|
||||||
</ModelRowProfileAction>
|
</ModelRowProfileAction>
|
||||||
);
|
);
|
||||||
}, [
|
}, [
|
||||||
@@ -787,6 +800,7 @@ function ModelRow({
|
|||||||
profiledRows,
|
profiledRows,
|
||||||
row.modelId,
|
row.modelId,
|
||||||
row.provider,
|
row.provider,
|
||||||
|
serverId,
|
||||||
t,
|
t,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -861,7 +875,7 @@ function SelectableModelRow({
|
|||||||
showProviderLabel?: boolean;
|
showProviderLabel?: boolean;
|
||||||
onSelect: (provider: string, modelId: string) => void;
|
onSelect: (provider: string, modelId: string) => void;
|
||||||
profiledRows: AgentProfilePickerRowModel[];
|
profiledRows: AgentProfilePickerRowModel[];
|
||||||
onCreateProfile?: (seed: AgentProfileSeed) => void;
|
onCreateProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
|
||||||
onEditProfile?: (profileId: string) => void;
|
onEditProfile?: (profileId: string) => void;
|
||||||
onEditProfiles?: () => void;
|
onEditProfiles?: () => void;
|
||||||
}) {
|
}) {
|
||||||
@@ -885,15 +899,25 @@ function SelectableModelRow({
|
|||||||
|
|
||||||
function AgentProfilePickerRowView({
|
function AgentProfilePickerRowView({
|
||||||
row,
|
row,
|
||||||
|
serverId,
|
||||||
onApply,
|
onApply,
|
||||||
}: {
|
}: {
|
||||||
row: AgentProfilePickerRowModel;
|
row: AgentProfilePickerRowModel;
|
||||||
|
serverId: string | null;
|
||||||
onApply: (profileId: string) => void;
|
onApply: (profileId: string) => void;
|
||||||
}) {
|
}) {
|
||||||
const handlePress = useCallback(() => onApply(row.id), [onApply, row.id]);
|
const handlePress = useCallback(() => onApply(row.id), [onApply, row.id]);
|
||||||
const leadingSlot = useMemo(
|
const leadingSlot = useMemo(
|
||||||
() => <AgentProfileGlyph icon={row.icon} color={row.color} size={ICON_SIZE.sm} />,
|
() => (
|
||||||
[row.color, row.icon],
|
<AgentProfileGlyph
|
||||||
|
icon={row.icon}
|
||||||
|
color={row.color}
|
||||||
|
provider={row.provider}
|
||||||
|
serverId={serverId}
|
||||||
|
size={ICON_SIZE.sm}
|
||||||
|
/>
|
||||||
|
),
|
||||||
|
[row.color, row.icon, row.provider, serverId],
|
||||||
);
|
);
|
||||||
return (
|
return (
|
||||||
<ModelBrowserRow
|
<ModelBrowserRow
|
||||||
@@ -914,10 +938,12 @@ function AgentProfilePickerRowView({
|
|||||||
*/
|
*/
|
||||||
function AgentProfilesPickerSection({
|
function AgentProfilesPickerSection({
|
||||||
rows,
|
rows,
|
||||||
|
serverId,
|
||||||
onApplyProfile,
|
onApplyProfile,
|
||||||
onEditProfiles,
|
onEditProfiles,
|
||||||
}: {
|
}: {
|
||||||
rows: AgentProfilePickerRowModel[];
|
rows: AgentProfilePickerRowModel[];
|
||||||
|
serverId: string | null;
|
||||||
onApplyProfile?: (profileId: string) => void;
|
onApplyProfile?: (profileId: string) => void;
|
||||||
onEditProfiles?: () => void;
|
onEditProfiles?: () => void;
|
||||||
}) {
|
}) {
|
||||||
@@ -937,7 +963,12 @@ function AgentProfilesPickerSection({
|
|||||||
) : null}
|
) : null}
|
||||||
</View>
|
</View>
|
||||||
{rows.map((row) => (
|
{rows.map((row) => (
|
||||||
<AgentProfilePickerRowView key={row.id} row={row} onApply={handleApply} />
|
<AgentProfilePickerRowView
|
||||||
|
key={row.id}
|
||||||
|
row={row}
|
||||||
|
serverId={serverId}
|
||||||
|
onApply={handleApply}
|
||||||
|
/>
|
||||||
))}
|
))}
|
||||||
</View>
|
</View>
|
||||||
);
|
);
|
||||||
@@ -966,10 +997,12 @@ function CreateAgentProfileRow({ onPress }: { onPress: () => void }) {
|
|||||||
|
|
||||||
function AgentProfilesPickerContent({
|
function AgentProfilesPickerContent({
|
||||||
rows,
|
rows,
|
||||||
|
serverId,
|
||||||
onApplyProfile,
|
onApplyProfile,
|
||||||
onEditProfiles,
|
onEditProfiles,
|
||||||
}: {
|
}: {
|
||||||
rows: AgentProfilePickerRowModel[];
|
rows: AgentProfilePickerRowModel[];
|
||||||
|
serverId: string | null;
|
||||||
onApplyProfile?: (profileId: string) => void;
|
onApplyProfile?: (profileId: string) => void;
|
||||||
onEditProfiles?: () => void;
|
onEditProfiles?: () => void;
|
||||||
}) {
|
}) {
|
||||||
@@ -979,6 +1012,7 @@ function AgentProfilesPickerContent({
|
|||||||
return (
|
return (
|
||||||
<AgentProfilesPickerSection
|
<AgentProfilesPickerSection
|
||||||
rows={rows}
|
rows={rows}
|
||||||
|
serverId={serverId}
|
||||||
onApplyProfile={onApplyProfile}
|
onApplyProfile={onApplyProfile}
|
||||||
onEditProfiles={onEditProfiles}
|
onEditProfiles={onEditProfiles}
|
||||||
/>
|
/>
|
||||||
@@ -991,11 +1025,13 @@ function AgentProfilesPickerContent({
|
|||||||
*/
|
*/
|
||||||
function ProfileSearchResultsHeader({
|
function ProfileSearchResultsHeader({
|
||||||
rows,
|
rows,
|
||||||
|
serverId,
|
||||||
hasModelRows,
|
hasModelRows,
|
||||||
onApplyProfile,
|
onApplyProfile,
|
||||||
onEditProfiles,
|
onEditProfiles,
|
||||||
}: {
|
}: {
|
||||||
rows: AgentProfilePickerRowModel[];
|
rows: AgentProfilePickerRowModel[];
|
||||||
|
serverId: string | null;
|
||||||
hasModelRows: boolean;
|
hasModelRows: boolean;
|
||||||
onApplyProfile?: (profileId: string) => void;
|
onApplyProfile?: (profileId: string) => void;
|
||||||
onEditProfiles?: () => void;
|
onEditProfiles?: () => void;
|
||||||
@@ -1005,6 +1041,7 @@ function ProfileSearchResultsHeader({
|
|||||||
<View>
|
<View>
|
||||||
<AgentProfilesPickerSection
|
<AgentProfilesPickerSection
|
||||||
rows={rows}
|
rows={rows}
|
||||||
|
serverId={serverId}
|
||||||
onApplyProfile={onApplyProfile}
|
onApplyProfile={onApplyProfile}
|
||||||
onEditProfiles={onEditProfiles}
|
onEditProfiles={onEditProfiles}
|
||||||
/>
|
/>
|
||||||
@@ -1207,7 +1244,7 @@ function ModelRowList({
|
|||||||
header?: React.ReactElement;
|
header?: React.ReactElement;
|
||||||
scrolling: "sheet" | "independent";
|
scrolling: "sheet" | "independent";
|
||||||
profiledLookup: Map<string, AgentProfilePickerRowModel[]>;
|
profiledLookup: Map<string, AgentProfilePickerRowModel[]>;
|
||||||
onCreateProfile?: (seed: AgentProfileSeed) => void;
|
onCreateProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
|
||||||
onEditProfile?: (profileId: string) => void;
|
onEditProfile?: (profileId: string) => void;
|
||||||
onEditProfiles?: () => void;
|
onEditProfiles?: () => void;
|
||||||
}) {
|
}) {
|
||||||
@@ -1336,7 +1373,7 @@ function ProviderModelBrowserContent({
|
|||||||
onSelect: (provider: string, modelId: string) => void;
|
onSelect: (provider: string, modelId: string) => void;
|
||||||
onApplyProfile?: (profileId: string) => void;
|
onApplyProfile?: (profileId: string) => void;
|
||||||
onEditProfiles?: () => void;
|
onEditProfiles?: () => void;
|
||||||
onCreateProfile?: (seed: AgentProfileSeed) => void;
|
onCreateProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
|
||||||
onEditProfile?: (profileId: string) => void;
|
onEditProfile?: (profileId: string) => void;
|
||||||
profiledLookup: Map<string, AgentProfilePickerRowModel[]>;
|
profiledLookup: Map<string, AgentProfilePickerRowModel[]>;
|
||||||
showProfilesSection?: boolean;
|
showProfilesSection?: boolean;
|
||||||
@@ -1363,6 +1400,7 @@ function ProviderModelBrowserContent({
|
|||||||
return (
|
return (
|
||||||
<AgentProfilesPickerContent
|
<AgentProfilesPickerContent
|
||||||
rows={providerProfileRows}
|
rows={providerProfileRows}
|
||||||
|
serverId={serverId}
|
||||||
onApplyProfile={onApplyProfile}
|
onApplyProfile={onApplyProfile}
|
||||||
onEditProfiles={onEditProfiles}
|
onEditProfiles={onEditProfiles}
|
||||||
/>
|
/>
|
||||||
@@ -1371,6 +1409,7 @@ function ProviderModelBrowserContent({
|
|||||||
return matchedProfileRows.length > 0 ? (
|
return matchedProfileRows.length > 0 ? (
|
||||||
<ProfileSearchResultsHeader
|
<ProfileSearchResultsHeader
|
||||||
rows={matchedProfileRows}
|
rows={matchedProfileRows}
|
||||||
|
serverId={serverId}
|
||||||
hasModelRows={visibleRows.length > 0}
|
hasModelRows={visibleRows.length > 0}
|
||||||
onApplyProfile={onApplyProfile}
|
onApplyProfile={onApplyProfile}
|
||||||
onEditProfiles={onEditProfiles}
|
onEditProfiles={onEditProfiles}
|
||||||
@@ -1383,6 +1422,7 @@ function ProviderModelBrowserContent({
|
|||||||
onEditProfiles,
|
onEditProfiles,
|
||||||
profiles,
|
profiles,
|
||||||
providerProfileRows,
|
providerProfileRows,
|
||||||
|
serverId,
|
||||||
showProfilesSection,
|
showProfilesSection,
|
||||||
visibleRows.length,
|
visibleRows.length,
|
||||||
]);
|
]);
|
||||||
@@ -1485,12 +1525,13 @@ function ModelBrowserContent({
|
|||||||
allView.kind === "searchResults" && allView.profiles.length > 0 ? (
|
allView.kind === "searchResults" && allView.profiles.length > 0 ? (
|
||||||
<ProfileSearchResultsHeader
|
<ProfileSearchResultsHeader
|
||||||
rows={allView.profiles}
|
rows={allView.profiles}
|
||||||
|
serverId={serverId}
|
||||||
hasModelRows={allView.rows.length > 0}
|
hasModelRows={allView.rows.length > 0}
|
||||||
onApplyProfile={onApplyProfile}
|
onApplyProfile={onApplyProfile}
|
||||||
onEditProfiles={onEditProfiles}
|
onEditProfiles={onEditProfiles}
|
||||||
/>
|
/>
|
||||||
) : undefined,
|
) : undefined,
|
||||||
[allView, onApplyProfile, onEditProfiles],
|
[allView, onApplyProfile, onEditProfiles, serverId],
|
||||||
);
|
);
|
||||||
|
|
||||||
if (view.kind === "provider") {
|
if (view.kind === "provider") {
|
||||||
@@ -1552,6 +1593,7 @@ function ModelBrowserContent({
|
|||||||
{showProfilesSection && profiles ? (
|
{showProfilesSection && profiles ? (
|
||||||
<AgentProfilesPickerContent
|
<AgentProfilesPickerContent
|
||||||
rows={profiles.rows}
|
rows={profiles.rows}
|
||||||
|
serverId={serverId}
|
||||||
onApplyProfile={onApplyProfile}
|
onApplyProfile={onApplyProfile}
|
||||||
onEditProfiles={onEditProfiles}
|
onEditProfiles={onEditProfiles}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -8,10 +8,15 @@ import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
|||||||
import { BackHeader } from "@/components/headers/back-header";
|
import { BackHeader } from "@/components/headers/back-header";
|
||||||
import { MenuHeader } from "@/components/headers/menu-header";
|
import { MenuHeader } from "@/components/headers/menu-header";
|
||||||
import { PressHighlight } from "@/components/ui/press-highlight";
|
import { PressHighlight } from "@/components/ui/press-highlight";
|
||||||
|
import { withContentDrag } from "@/components/ui/content-drag";
|
||||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||||
import { ICON_SIZE, SPACING, type Theme } from "@/styles/theme";
|
import { ICON_SIZE, SPACING, type Theme } from "@/styles/theme";
|
||||||
|
|
||||||
const PageScrollView = Platform.OS === "android" ? KeyboardAwareScrollView : ScrollView;
|
// Rows on a page drag to reorder, so the page stops scrolling while a drag holds the touch.
|
||||||
|
const PageScrollView =
|
||||||
|
Platform.OS === "android"
|
||||||
|
? withContentDrag(KeyboardAwareScrollView)
|
||||||
|
: withContentDrag(ScrollView);
|
||||||
|
|
||||||
interface PageLayoutProps {
|
interface PageLayoutProps {
|
||||||
title?: string;
|
title?: string;
|
||||||
|
|||||||
@@ -1,9 +1,7 @@
|
|||||||
import { Children, isValidElement, useCallback, useMemo, useState, type ReactNode } from "react";
|
import { useCallback, useMemo, useState, type ReactNode } from "react";
|
||||||
import { View } from "react-native";
|
import { View } from "react-native";
|
||||||
import { StyleSheet } from "react-native-unistyles";
|
|
||||||
import { isWeb } from "@/constants/platform";
|
import { isWeb } from "@/constants/platform";
|
||||||
import { settingsStyles } from "@/styles/settings";
|
import { SettingsRowChildren } from "./row-children";
|
||||||
import { NestedSettingsRows } from "./row-density";
|
|
||||||
import { SettingsRowHeader } from "./row-header";
|
import { SettingsRowHeader } from "./row-header";
|
||||||
|
|
||||||
interface SettingsCollapsibleRowProps {
|
interface SettingsCollapsibleRowProps {
|
||||||
@@ -48,27 +46,7 @@ export function SettingsCollapsibleRow({
|
|||||||
webAccessibilityProps={webExpandedProps}
|
webAccessibilityProps={webExpandedProps}
|
||||||
testID={testID ? `${testID}-toggle` : undefined}
|
testID={testID ? `${testID}-toggle` : undefined}
|
||||||
/>
|
/>
|
||||||
{expanded ? (
|
{expanded ? <SettingsRowChildren>{children}</SettingsRowChildren> : null}
|
||||||
<View style={styles.children}>
|
|
||||||
<NestedSettingsRows>
|
|
||||||
{Children.toArray(children).map((child, index) => (
|
|
||||||
<View
|
|
||||||
key={isValidElement(child) ? child.key : index}
|
|
||||||
style={settingsStyles.rowBorder}
|
|
||||||
>
|
|
||||||
{child}
|
|
||||||
</View>
|
|
||||||
))}
|
|
||||||
</NestedSettingsRows>
|
|
||||||
</View>
|
|
||||||
) : null}
|
|
||||||
</View>
|
</View>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const styles = StyleSheet.create((theme) => ({
|
|
||||||
// The revealed rows keep the card's rails; the tint is what groups them under their header.
|
|
||||||
children: {
|
|
||||||
backgroundColor: theme.colors.surface0,
|
|
||||||
},
|
|
||||||
}));
|
|
||||||
|
|||||||
@@ -25,7 +25,10 @@ import { DropdownTrigger } from "@/components/ui/dropdown-trigger";
|
|||||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||||
import { settingsStyles } from "@/styles/settings";
|
import { settingsStyles } from "@/styles/settings";
|
||||||
import { ControlSizeProvider } from "@/components/ui/control-size";
|
import { ControlSizeProvider } from "@/components/ui/control-size";
|
||||||
|
import { ExternalLink, type ExternalLinkProps } from "@/components/ui/external-link";
|
||||||
import { useSettingsRowLayout } from "./row-density";
|
import { useSettingsRowLayout } from "./row-density";
|
||||||
|
import { SettingsRowTitle } from "./row-label";
|
||||||
|
export { SettingsRowChildren } from "./row-children";
|
||||||
export { SettingsGroup } from "./headings/settings-group";
|
export { SettingsGroup } from "./headings/settings-group";
|
||||||
export { SettingsSection } from "./headings/settings-section";
|
export { SettingsSection } from "./headings/settings-section";
|
||||||
export { SettingsCollapsibleRow } from "./collapsible-row";
|
export { SettingsCollapsibleRow } from "./collapsible-row";
|
||||||
@@ -36,11 +39,16 @@ export { SettingsBackLink, SettingsDetailHeader } from "./detail-header";
|
|||||||
export { SettingsInfoTip } from "./headings/settings-info-tip";
|
export { SettingsInfoTip } from "./headings/settings-info-tip";
|
||||||
export { MenuSettingsRows } from "./row-density";
|
export { MenuSettingsRows } from "./row-density";
|
||||||
|
|
||||||
/** What app screens can add to a plugin-facing row: an accessory beside the label, such as an info tip. */
|
/**
|
||||||
|
* What app screens can add to a plugin-facing row: an accessory beside the label, such as an info
|
||||||
|
* tip, an icon before the label, and a link to a page outside the app under the hint.
|
||||||
|
*/
|
||||||
interface AppRowExtras {
|
interface AppRowExtras {
|
||||||
labelAccessory?: ReactNode;
|
labelAccessory?: ReactNode;
|
||||||
/** An icon before the label, such as the thing the row is about. */
|
/** An icon before the label, such as the thing the row is about. */
|
||||||
leading?: ReactNode;
|
leading?: ReactNode;
|
||||||
|
/** A page outside the app that helps with this row, drawn under the hint as "Label ↗". */
|
||||||
|
link?: Pick<ExternalLinkProps, "href" | "label" | "accessibilityLabel">;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface AppSettingsRowProps extends Omit<SettingsRowProps, "hint">, AppRowExtras {
|
interface AppSettingsRowProps extends Omit<SettingsRowProps, "hint">, AppRowExtras {
|
||||||
@@ -67,6 +75,7 @@ export function SettingsRow({
|
|||||||
leading,
|
leading,
|
||||||
labelAccessory,
|
labelAccessory,
|
||||||
hint,
|
hint,
|
||||||
|
link,
|
||||||
error,
|
error,
|
||||||
children,
|
children,
|
||||||
testID,
|
testID,
|
||||||
@@ -74,20 +83,17 @@ export function SettingsRow({
|
|||||||
const compact = useIsCompactFormFactor();
|
const compact = useIsCompactFormFactor();
|
||||||
const layout = useSettingsRowLayout();
|
const layout = useSettingsRowLayout();
|
||||||
const rowStyle = useMemo(() => [layout.row, compact && styles.compactRow], [compact, layout]);
|
const rowStyle = useMemo(() => [layout.row, compact && styles.compactRow], [compact, layout]);
|
||||||
const accessoryTitleStyle = useMemo(() => [layout.title, styles.accessoryLabel], [layout]);
|
|
||||||
return (
|
return (
|
||||||
<View style={rowStyle} testID={testID}>
|
<View style={rowStyle} testID={testID}>
|
||||||
{leading ? <View style={styles.leading}>{leading}</View> : null}
|
{leading ? <View style={styles.leading}>{leading}</View> : null}
|
||||||
<View style={styles.label}>
|
<View style={styles.label}>
|
||||||
{labelAccessory ? (
|
<SettingsRowTitle label={label} accessory={labelAccessory} />
|
||||||
<View style={styles.labelRow}>
|
|
||||||
<Text style={accessoryTitleStyle}>{label}</Text>
|
|
||||||
{labelAccessory}
|
|
||||||
</View>
|
|
||||||
) : (
|
|
||||||
<Text style={layout.title}>{label}</Text>
|
|
||||||
)}
|
|
||||||
{typeof hint === "string" ? <Text style={layout.hint}>{hint}</Text> : hint}
|
{typeof hint === "string" ? <Text style={layout.hint}>{hint}</Text> : hint}
|
||||||
|
{link ? (
|
||||||
|
<View style={styles.link}>
|
||||||
|
<ExternalLink {...link} />
|
||||||
|
</View>
|
||||||
|
) : null}
|
||||||
{error ? (
|
{error ? (
|
||||||
<Text accessibilityRole="alert" style={settingsStyles.rowError}>
|
<Text accessibilityRole="alert" style={settingsStyles.rowError}>
|
||||||
{error}
|
{error}
|
||||||
@@ -103,7 +109,15 @@ export function SettingsRow({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function SettingsSwitch({ value, onValueChange, disabled, ...row }: SettingsSwitchProps) {
|
/** A switch row. App screens may pass `null` while the value is not known yet; see `Switch`. */
|
||||||
|
export function SettingsSwitch({
|
||||||
|
value,
|
||||||
|
onValueChange,
|
||||||
|
disabled,
|
||||||
|
...row
|
||||||
|
}: Omit<SettingsSwitchProps, "onValueChange" | "value"> &
|
||||||
|
Partial<Pick<SettingsSwitchProps, "onValueChange">> &
|
||||||
|
AppRowExtras & { value: boolean | null }) {
|
||||||
return (
|
return (
|
||||||
<SettingsRow {...row}>
|
<SettingsRow {...row}>
|
||||||
<Switch
|
<Switch
|
||||||
@@ -204,7 +218,12 @@ export function SettingsInput({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function SettingsAction({ actionLabel, onPress, disabled, ...row }: SettingsActionProps) {
|
export function SettingsAction({
|
||||||
|
actionLabel,
|
||||||
|
onPress,
|
||||||
|
disabled,
|
||||||
|
...row
|
||||||
|
}: SettingsActionProps & AppRowExtras) {
|
||||||
return (
|
return (
|
||||||
<SettingsRow {...row}>
|
<SettingsRow {...row}>
|
||||||
<Button variant="outline" onPress={onPress} disabled={disabled}>
|
<Button variant="outline" onPress={onPress} disabled={disabled}>
|
||||||
@@ -221,13 +240,7 @@ const styles = StyleSheet.create((theme) => ({
|
|||||||
// The same leading slot as `SettingsRowHeader`, so icons and labels share rails across row kinds.
|
// The same leading slot as `SettingsRowHeader`, so icons and labels share rails across row kinds.
|
||||||
leading: { marginRight: theme.spacing[3], alignItems: "center", justifyContent: "center" },
|
leading: { marginRight: theme.spacing[3], alignItems: "center", justifyContent: "center" },
|
||||||
label: { flexGrow: 1, flexShrink: 1, flexBasis: 160, marginRight: theme.spacing[3] },
|
label: { flexGrow: 1, flexShrink: 1, flexBasis: 160, marginRight: theme.spacing[3] },
|
||||||
labelRow: {
|
link: { alignItems: "flex-start", marginTop: theme.spacing[1] },
|
||||||
flexDirection: "row",
|
|
||||||
flexWrap: "wrap",
|
|
||||||
alignItems: "center",
|
|
||||||
gap: theme.spacing[2],
|
|
||||||
},
|
|
||||||
accessoryLabel: { flexShrink: 1, minWidth: 0 },
|
|
||||||
control: { flexShrink: 1, maxWidth: "100%" },
|
control: { flexShrink: 1, maxWidth: "100%" },
|
||||||
input: { minWidth: 180 },
|
input: { minWidth: 180 },
|
||||||
}));
|
}));
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import { Children, isValidElement, type ReactNode } from "react";
|
||||||
|
import { View } from "react-native";
|
||||||
|
import { StyleSheet } from "react-native-unistyles";
|
||||||
|
import { settingsStyles } from "@/styles/settings";
|
||||||
|
import { NestedSettingsRows } from "./row-density";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rows that belong to the row above them, such as the rows an expanded row reveals or the details
|
||||||
|
* a switch turns on. They sit in the same card on a tinted band, laid out as nested rows.
|
||||||
|
*/
|
||||||
|
export function SettingsRowChildren({ children }: { children: ReactNode }) {
|
||||||
|
return (
|
||||||
|
<View style={styles.band}>
|
||||||
|
<NestedSettingsRows>
|
||||||
|
{Children.toArray(children).map((child, index) => (
|
||||||
|
<View key={isValidElement(child) ? child.key : index} style={settingsStyles.rowBorder}>
|
||||||
|
{child}
|
||||||
|
</View>
|
||||||
|
))}
|
||||||
|
</NestedSettingsRows>
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const styles = StyleSheet.create((theme) => ({
|
||||||
|
// The rows keep the card's rails; the tint is what groups them under the row above.
|
||||||
|
band: {
|
||||||
|
backgroundColor: theme.colors.surface0,
|
||||||
|
},
|
||||||
|
}));
|
||||||
@@ -66,12 +66,16 @@ function heightOf(testID: string): number {
|
|||||||
return element(testID).getBoundingClientRect().height;
|
return element(testID).getBoundingClientRect().height;
|
||||||
}
|
}
|
||||||
|
|
||||||
function titleFontSize(rowTestID: string, label: string): number {
|
function textNode(rowTestID: string, text: string): HTMLElement {
|
||||||
const title = [...element(rowTestID).querySelectorAll("div")].find(
|
const found = [...element(rowTestID).querySelectorAll("div")].find(
|
||||||
(node) => node.textContent === label && node.children.length === 0,
|
(node) => node.textContent === text && node.children.length === 0,
|
||||||
);
|
);
|
||||||
if (!title) throw new Error(`No title ${label}`);
|
if (!found) throw new Error(`No text ${text}`);
|
||||||
return Number.parseFloat(getComputedStyle(title).fontSize);
|
return found;
|
||||||
|
}
|
||||||
|
|
||||||
|
function titleFontSize(rowTestID: string, label: string): number {
|
||||||
|
return Number.parseFloat(getComputedStyle(textNode(rowTestID, label)).fontSize);
|
||||||
}
|
}
|
||||||
|
|
||||||
describe("settings row density", () => {
|
describe("settings row density", () => {
|
||||||
@@ -100,4 +104,52 @@ describe("settings row density", () => {
|
|||||||
titleFontSize("card-row", "Card row"),
|
titleFontSize("card-row", "Card row"),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("keeps a row with a long summary one line tall on a phone-width card", () => {
|
||||||
|
container = document.createElement("div");
|
||||||
|
// A 393pt phone less the sheet's side padding.
|
||||||
|
container.style.width = "360px";
|
||||||
|
document.body.appendChild(container);
|
||||||
|
root = createRoot(container);
|
||||||
|
act(() =>
|
||||||
|
root?.render(
|
||||||
|
<SettingsCard>
|
||||||
|
<SettingsRow label="Text only" testID="text-row" />
|
||||||
|
<SettingsCollapsibleRow
|
||||||
|
label="Customize settings"
|
||||||
|
summary="Auto mode · Medium · 2 features · Add a note for when to use it"
|
||||||
|
testID="long-summary"
|
||||||
|
>
|
||||||
|
<SettingsRow label="Nested" />
|
||||||
|
</SettingsCollapsibleRow>
|
||||||
|
</SettingsCard>,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(heightOf("long-summary-toggle")).toBe(heightOf("text-row"));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps a short summary beside the chevron on a wide card", () => {
|
||||||
|
container = document.createElement("div");
|
||||||
|
container.style.width = "680px";
|
||||||
|
document.body.appendChild(container);
|
||||||
|
root = createRoot(container);
|
||||||
|
act(() =>
|
||||||
|
root?.render(
|
||||||
|
<SettingsCard>
|
||||||
|
<SettingsDetailRow
|
||||||
|
label="Speech to text"
|
||||||
|
summary="Local"
|
||||||
|
onPress={openNothing}
|
||||||
|
testID="short-summary"
|
||||||
|
/>
|
||||||
|
</SettingsCard>,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
const row = element("short-summary").getBoundingClientRect();
|
||||||
|
const summary = textNode("short-summary", "Local").getBoundingClientRect();
|
||||||
|
// The summary's margin, the chevron and the row's padding: about 40px.
|
||||||
|
expect(row.right - summary.right).toBeLessThan(48);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import { SkeletonPulse, useSkeletonPulse } from "@/components/ui/skeleton";
|
|||||||
import { settingsStyles } from "@/styles/settings";
|
import { settingsStyles } from "@/styles/settings";
|
||||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||||
import { useSettingsRowLayout, type SettingsRowLayout } from "./row-density";
|
import { useSettingsRowLayout, type SettingsRowLayout } from "./row-density";
|
||||||
|
import { SettingsRowTitle } from "./row-label";
|
||||||
|
|
||||||
const ThemedChevron = withUnistyles(ChevronRight);
|
const ThemedChevron = withUnistyles(ChevronRight);
|
||||||
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
|
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
|
||||||
@@ -88,9 +89,13 @@ export function SettingsRowHeader({
|
|||||||
const hovered = pointerOver && !disabled;
|
const hovered = pointerOver && !disabled;
|
||||||
const rowStyle = useMemo(() => [layout.row, hovered && styles.hovered], [hovered, layout]);
|
const rowStyle = useMemo(() => [layout.row, hovered && styles.hovered], [hovered, layout]);
|
||||||
const chevronStyle = useMemo(
|
const chevronStyle = useMemo(
|
||||||
() => [styles.chevron, expanded && styles.chevronExpanded],
|
() => [styles.chevron, expanded && styles.chevronExpanded, styles.passThrough],
|
||||||
[expanded],
|
[expanded],
|
||||||
);
|
);
|
||||||
|
// A hint can be a sentence, so a hinted row gives the room to the label column and caps the
|
||||||
|
// summary. A label alone keeps its one-line width and the summary truncates in what is left.
|
||||||
|
const hinted = Boolean(hint || hintStatus);
|
||||||
|
const contentStyle = hinted ? settingsStyles.rowContent : styles.labelContent;
|
||||||
return (
|
return (
|
||||||
<View
|
<View
|
||||||
style={rowStyle}
|
style={rowStyle}
|
||||||
@@ -113,10 +118,9 @@ export function SettingsRowHeader({
|
|||||||
{leading}
|
{leading}
|
||||||
</View>
|
</View>
|
||||||
) : null}
|
) : null}
|
||||||
<View style={[settingsStyles.rowContent, styles.passThrough]}>
|
<View style={[contentStyle, styles.passThrough]}>
|
||||||
<View style={labelAccessory ? styles.labelRow : undefined} {...HIDDEN_FROM_ASSISTIVE_TECH}>
|
<View {...HIDDEN_FROM_ASSISTIVE_TECH}>
|
||||||
<Text style={layout.title}>{label}</Text>
|
<SettingsRowTitle label={label} accessory={labelAccessory} />
|
||||||
{labelAccessory}
|
|
||||||
</View>
|
</View>
|
||||||
{hintStatus ? (
|
{hintStatus ? (
|
||||||
<RowHintLine hint={hint} status={hintStatus} hintStyle={layout.hint} />
|
<RowHintLine hint={hint} status={hintStatus} hintStyle={layout.hint} />
|
||||||
@@ -128,28 +132,15 @@ export function SettingsRowHeader({
|
|||||||
<ControlSizeProvider size={layout.controlSize}>{control}</ControlSizeProvider>
|
<ControlSizeProvider size={layout.controlSize}>{control}</ControlSizeProvider>
|
||||||
</View>
|
</View>
|
||||||
) : null}
|
) : null}
|
||||||
<View style={[styles.trailing, styles.passThrough]} {...HIDDEN_FROM_ASSISTIVE_TECH}>
|
<RowTrailing hinted={hinted} external={external} hovered={hovered} summary={summary} />
|
||||||
{external ? (
|
{external || disabled ? null : (
|
||||||
// Drawn the same as a section header's docs link, so the two read as one thing.
|
<View style={chevronStyle} {...HIDDEN_FROM_ASSISTIVE_TECH}>
|
||||||
<ExternalLinkLabel hovered={hovered}>{summary}</ExternalLinkLabel>
|
<ThemedChevron
|
||||||
) : (
|
size={ICON_SIZE.sm}
|
||||||
<>
|
uniProps={hovered ? hoveredIconColorMapping : mutedIconColorMapping}
|
||||||
{summary ? (
|
/>
|
||||||
<Text style={styles.summary} numberOfLines={1}>
|
</View>
|
||||||
{summary}
|
)}
|
||||||
</Text>
|
|
||||||
) : null}
|
|
||||||
{disabled ? null : (
|
|
||||||
<View style={chevronStyle}>
|
|
||||||
<ThemedChevron
|
|
||||||
size={ICON_SIZE.sm}
|
|
||||||
uniProps={hovered ? hoveredIconColorMapping : mutedIconColorMapping}
|
|
||||||
/>
|
|
||||||
</View>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</View>
|
|
||||||
</View>
|
</View>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -160,6 +151,32 @@ const HIDDEN_FROM_ASSISTIVE_TECH = {
|
|||||||
"aria-hidden": true,
|
"aria-hidden": true,
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
|
/** The summary before the chevron, or the external link label in its place. */
|
||||||
|
function RowTrailing({
|
||||||
|
hinted,
|
||||||
|
external,
|
||||||
|
hovered,
|
||||||
|
summary,
|
||||||
|
}: {
|
||||||
|
hinted: boolean;
|
||||||
|
external: boolean;
|
||||||
|
hovered: boolean;
|
||||||
|
summary: string | undefined;
|
||||||
|
}) {
|
||||||
|
const style = hinted ? styles.hintedTrailing : styles.labelTrailing;
|
||||||
|
return (
|
||||||
|
<View style={[style, styles.passThrough]} {...HIDDEN_FROM_ASSISTIVE_TECH}>
|
||||||
|
{/* Drawn the same as a section header's docs link, so the two read as one thing. */}
|
||||||
|
{external ? <ExternalLinkLabel hovered={hovered}>{summary}</ExternalLinkLabel> : null}
|
||||||
|
{!external && summary ? (
|
||||||
|
<Text style={styles.summary} numberOfLines={1}>
|
||||||
|
{summary}
|
||||||
|
</Text>
|
||||||
|
) : null}
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The hint with its status mark. The line keeps the hint's own height in every status, so a row
|
* 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
|
* does not move when its value arrives or its work starts. A long error is cut to the line; the
|
||||||
@@ -222,10 +239,30 @@ const styles = StyleSheet.create((theme) => ({
|
|||||||
passThrough: {
|
passThrough: {
|
||||||
pointerEvents: "none",
|
pointerEvents: "none",
|
||||||
},
|
},
|
||||||
trailing: {
|
// The label keeps its one-line width and takes the free space; the summary truncates in what is
|
||||||
|
// left. Any shrink, even a fraction of a pixel, would wrap the label, so it does not shrink. The
|
||||||
|
// cap lets a long label wrap before it pushes the chevron off the row. Past the cap, the auto
|
||||||
|
// margin takes the rest of the row, so the control, summary and chevron stay together at the end.
|
||||||
|
labelContent: {
|
||||||
|
flexGrow: 1,
|
||||||
|
flexShrink: 0,
|
||||||
|
maxWidth: "75%",
|
||||||
|
paddingRight: theme.spacing[3],
|
||||||
|
marginRight: "auto",
|
||||||
|
},
|
||||||
|
labelTrailing: {
|
||||||
flexDirection: "row",
|
flexDirection: "row",
|
||||||
alignItems: "center",
|
alignItems: "center",
|
||||||
flexShrink: 1,
|
flexShrink: 1,
|
||||||
|
minWidth: 0,
|
||||||
|
},
|
||||||
|
// A hinted row's column grows from zero width, so an unbounded summary would squeeze it to
|
||||||
|
// nothing and wrap the label one glyph per line. The summary keeps at most half the row.
|
||||||
|
hintedTrailing: {
|
||||||
|
flexDirection: "row",
|
||||||
|
alignItems: "center",
|
||||||
|
flexShrink: 1,
|
||||||
|
maxWidth: "50%",
|
||||||
},
|
},
|
||||||
hintLine: {
|
hintLine: {
|
||||||
flexDirection: "row",
|
flexDirection: "row",
|
||||||
@@ -256,7 +293,6 @@ const styles = StyleSheet.create((theme) => ({
|
|||||||
borderRadius: theme.borderRadius.sm,
|
borderRadius: theme.borderRadius.sm,
|
||||||
backgroundColor: theme.colors.surface2,
|
backgroundColor: theme.colors.surface2,
|
||||||
},
|
},
|
||||||
labelRow: { flexDirection: "row", alignItems: "center", gap: theme.spacing[2] },
|
|
||||||
summary: {
|
summary: {
|
||||||
flexShrink: 1,
|
flexShrink: 1,
|
||||||
color: theme.colors.foregroundMuted,
|
color: theme.colors.foregroundMuted,
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import { useMemo, type ReactNode } from "react";
|
||||||
|
import { Text, View } from "react-native";
|
||||||
|
import { StyleSheet } from "react-native-unistyles";
|
||||||
|
import { useSettingsRowLayout } from "./row-density";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A row's label line: the label, and beside it an accessory such as a badge or an info tip. Rows
|
||||||
|
* with inline controls and rows that lead somewhere both draw it, so their labels and hints keep
|
||||||
|
* the same distances whether or not a row carries an accessory.
|
||||||
|
*/
|
||||||
|
export function SettingsRowTitle({ label, accessory }: { label: string; accessory?: ReactNode }) {
|
||||||
|
const layout = useSettingsRowLayout();
|
||||||
|
const titleStyle = useMemo(() => [layout.title, styles.title], [layout]);
|
||||||
|
if (!accessory) return <Text style={layout.title}>{label}</Text>;
|
||||||
|
return (
|
||||||
|
<View style={styles.line}>
|
||||||
|
<Text style={titleStyle}>{label}</Text>
|
||||||
|
<View style={styles.accessory}>{accessory}</View>
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const styles = StyleSheet.create((theme) => ({
|
||||||
|
line: {
|
||||||
|
flexDirection: "row",
|
||||||
|
flexWrap: "wrap",
|
||||||
|
alignItems: "center",
|
||||||
|
gap: theme.spacing[2],
|
||||||
|
},
|
||||||
|
title: { flexShrink: 1, minWidth: 0 },
|
||||||
|
// An accessory is taller than the label's line. It hangs into the row's padding instead, so the
|
||||||
|
// label and hint keep the distances of a row without one.
|
||||||
|
accessory: { marginVertical: -theme.spacing[1] },
|
||||||
|
}));
|
||||||
@@ -101,7 +101,17 @@ import {
|
|||||||
import { useLongPressDragInteraction } from "@/components/sidebar/use-long-press-drag-interaction";
|
import { useLongPressDragInteraction } from "@/components/sidebar/use-long-press-drag-interaction";
|
||||||
import { SidebarSectionHeader } from "@/components/sidebar/sidebar-section-header";
|
import { SidebarSectionHeader } from "@/components/sidebar/sidebar-section-header";
|
||||||
import { SidebarGroupToggleRow } from "@/components/sidebar/sidebar-group-toggle-row";
|
import { SidebarGroupToggleRow } from "@/components/sidebar/sidebar-group-toggle-row";
|
||||||
import { createWorkspaceVisibilityPolicy } from "@/components/sidebar/sidebar-group-visibility";
|
import {
|
||||||
|
createWorkspaceVisibilityPolicy,
|
||||||
|
selectSidebarGroupVisibility,
|
||||||
|
} from "@/components/sidebar/sidebar-group-visibility";
|
||||||
|
import {
|
||||||
|
registerSidebarVisibleWorkspaceKeysReader,
|
||||||
|
useIsSidebarSelectionMode,
|
||||||
|
useIsWorkspaceBulkSelected,
|
||||||
|
useSidebarSelectionStore,
|
||||||
|
useWorkspaceSelectionPress,
|
||||||
|
} from "@/sidebar-selection";
|
||||||
import { useLimitedSidebarGroup } from "@/components/sidebar/use-limited-sidebar-group";
|
import { useLimitedSidebarGroup } from "@/components/sidebar/use-limited-sidebar-group";
|
||||||
import {
|
import {
|
||||||
SidebarWorkspaceRowFrame,
|
SidebarWorkspaceRowFrame,
|
||||||
@@ -284,6 +294,7 @@ interface WorkspaceRowInnerProps {
|
|||||||
archiveLabel?: string;
|
archiveLabel?: string;
|
||||||
archiveStatus?: "idle" | "pending" | "success";
|
archiveStatus?: "idle" | "pending" | "success";
|
||||||
archivePendingLabel?: string;
|
archivePendingLabel?: string;
|
||||||
|
onSelectWorkspace?: () => void;
|
||||||
onArchive?: () => void;
|
onArchive?: () => void;
|
||||||
onCopyBranchName?: () => void;
|
onCopyBranchName?: () => void;
|
||||||
onCopyPath?: () => void;
|
onCopyPath?: () => void;
|
||||||
@@ -607,12 +618,14 @@ function WorkspaceRowRightGroup({
|
|||||||
isHovered,
|
isHovered,
|
||||||
isTouchPlatform,
|
isTouchPlatform,
|
||||||
isCreating,
|
isCreating,
|
||||||
|
isSelectionMode,
|
||||||
showShortcutBadge,
|
showShortcutBadge,
|
||||||
shortcutNumber,
|
shortcutNumber,
|
||||||
archiveLabel,
|
archiveLabel,
|
||||||
archiveStatus,
|
archiveStatus,
|
||||||
archivePendingLabel,
|
archivePendingLabel,
|
||||||
archiveShortcutKeys,
|
archiveShortcutKeys,
|
||||||
|
onSelectWorkspace,
|
||||||
onArchive,
|
onArchive,
|
||||||
onMarkAsRead,
|
onMarkAsRead,
|
||||||
onMarkAsUnread,
|
onMarkAsUnread,
|
||||||
@@ -627,12 +640,14 @@ function WorkspaceRowRightGroup({
|
|||||||
isHovered: boolean;
|
isHovered: boolean;
|
||||||
isTouchPlatform: boolean;
|
isTouchPlatform: boolean;
|
||||||
isCreating: boolean;
|
isCreating: boolean;
|
||||||
|
isSelectionMode: boolean;
|
||||||
showShortcutBadge: boolean;
|
showShortcutBadge: boolean;
|
||||||
shortcutNumber: number | null;
|
shortcutNumber: number | null;
|
||||||
archiveLabel?: string;
|
archiveLabel?: string;
|
||||||
archiveStatus?: "idle" | "pending" | "success";
|
archiveStatus?: "idle" | "pending" | "success";
|
||||||
archivePendingLabel?: string;
|
archivePendingLabel?: string;
|
||||||
archiveShortcutKeys?: ShortcutKey[][] | null;
|
archiveShortcutKeys?: ShortcutKey[][] | null;
|
||||||
|
onSelectWorkspace?: () => void;
|
||||||
onArchive?: () => void;
|
onArchive?: () => void;
|
||||||
onMarkAsRead?: () => void;
|
onMarkAsRead?: () => void;
|
||||||
onMarkAsUnread?: () => void;
|
onMarkAsUnread?: () => void;
|
||||||
@@ -660,6 +675,7 @@ function WorkspaceRowRightGroup({
|
|||||||
isHovered,
|
isHovered,
|
||||||
isTouchPlatform,
|
isTouchPlatform,
|
||||||
showShortcut,
|
showShortcut,
|
||||||
|
isSelectionMode,
|
||||||
});
|
});
|
||||||
const kebab = useOpenKebabMenuVisibility(showKebabInSlot);
|
const kebab = useOpenKebabMenuVisibility(showKebabInSlot);
|
||||||
|
|
||||||
@@ -695,6 +711,7 @@ function WorkspaceRowRightGroup({
|
|||||||
onRename={onRename}
|
onRename={onRename}
|
||||||
onMarkAsRead={onMarkAsRead}
|
onMarkAsRead={onMarkAsRead}
|
||||||
onMarkAsUnread={onMarkAsUnread}
|
onMarkAsUnread={onMarkAsUnread}
|
||||||
|
onSelectWorkspace={onSelectWorkspace}
|
||||||
onArchive={onArchive}
|
onArchive={onArchive}
|
||||||
archiveLabel={archiveLabel}
|
archiveLabel={archiveLabel}
|
||||||
archiveStatus={archiveStatus}
|
archiveStatus={archiveStatus}
|
||||||
@@ -1065,6 +1082,7 @@ function WorkspaceRowInner({
|
|||||||
archiveLabel,
|
archiveLabel,
|
||||||
archiveStatus = "idle",
|
archiveStatus = "idle",
|
||||||
archivePendingLabel,
|
archivePendingLabel,
|
||||||
|
onSelectWorkspace,
|
||||||
onArchive,
|
onArchive,
|
||||||
onCopyBranchName,
|
onCopyBranchName,
|
||||||
onCopyPath,
|
onCopyPath,
|
||||||
@@ -1079,6 +1097,8 @@ function WorkspaceRowInner({
|
|||||||
}: WorkspaceRowInnerProps) {
|
}: WorkspaceRowInnerProps) {
|
||||||
const isCompact = useIsCompactFormFactor();
|
const isCompact = useIsCompactFormFactor();
|
||||||
const [isHighlighted, setIsHighlighted] = useState(false);
|
const [isHighlighted, setIsHighlighted] = useState(false);
|
||||||
|
const isSelectionMode = useIsSidebarSelectionMode();
|
||||||
|
const isBulkSelected = useIsWorkspaceBulkSelected(workspace.workspaceKey);
|
||||||
const isTouchPlatform = platformIsNative || isCompact;
|
const isTouchPlatform = platformIsNative || isCompact;
|
||||||
const interaction = useLongPressDragInteraction({
|
const interaction = useLongPressDragInteraction({
|
||||||
drag,
|
drag,
|
||||||
@@ -1091,30 +1111,51 @@ function WorkspaceRowInner({
|
|||||||
...dragAttributes
|
...dragAttributes
|
||||||
} = dragHandleProps?.attributes ?? {};
|
} = dragHandleProps?.attributes ?? {};
|
||||||
|
|
||||||
const { onPress: handlePress, feedback } = useWorkspaceRowPress({
|
const { onPress: handleNavigatePress, feedback } = useWorkspaceRowPress({
|
||||||
didLongPressRef: interaction.didLongPressRef,
|
didLongPressRef: interaction.didLongPressRef,
|
||||||
onPress,
|
onPress,
|
||||||
selected,
|
selected,
|
||||||
});
|
});
|
||||||
|
|
||||||
const accessibilityState = useMemo(() => ({ selected }), [selected]);
|
const { onPress: handleRowPress, onPressIn: handleRowPressIn } = useWorkspaceSelectionPress({
|
||||||
|
workspaceKey: workspace.workspaceKey,
|
||||||
|
onNavigate: handleNavigatePress,
|
||||||
|
onPressIn: interaction.handlePressIn,
|
||||||
|
});
|
||||||
|
|
||||||
|
const rowSelected = isSelectionMode ? isBulkSelected : selected;
|
||||||
|
const accessibilityState = useMemo(
|
||||||
|
() => (isSelectionMode ? { checked: isBulkSelected } : { selected }),
|
||||||
|
[isSelectionMode, isBulkSelected, selected],
|
||||||
|
);
|
||||||
const isEditingTitle = titleEditor !== null;
|
const isEditingTitle = titleEditor !== null;
|
||||||
|
const disableDrag = isEditingTitle || isSelectionMode;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<SidebarWorkspaceRowFrame
|
<SidebarWorkspaceRowFrame
|
||||||
workspace={workspace}
|
workspace={workspace}
|
||||||
isDragging={isDragging}
|
isDragging={isDragging}
|
||||||
isEditingTitle={isEditingTitle}
|
isEditingTitle={isEditingTitle}
|
||||||
|
isSelectionMode={isSelectionMode}
|
||||||
>
|
>
|
||||||
{({ isHovered, contextMenuOpen, onContextMenuOpenChange, hoverHandlers }) => {
|
{({ isHovered, contextMenuOpen, onContextMenuOpenChange, hoverHandlers }) => {
|
||||||
const isDesktop = !isTouchPlatform;
|
const isDesktop = !isTouchPlatform;
|
||||||
const serviceSummary = isDesktop ? selectWorkspaceServiceSummary(workspace.scripts) : null;
|
const serviceSummary = isDesktop ? selectWorkspaceServiceSummary(workspace.scripts) : null;
|
||||||
const workspaceRowStyle = getProjectWorkspaceRowStyle({ isDragging, selected, isHovered });
|
const workspaceRowStyle = getProjectWorkspaceRowStyle({
|
||||||
const backdrop = getSidebarRowBackdrop({ isDragging, isHighlighted, selected, isHovered });
|
isDragging,
|
||||||
|
selected: rowSelected,
|
||||||
|
isHovered,
|
||||||
|
});
|
||||||
|
const backdrop = getSidebarRowBackdrop({
|
||||||
|
isDragging,
|
||||||
|
isHighlighted,
|
||||||
|
selected: rowSelected,
|
||||||
|
isHovered,
|
||||||
|
});
|
||||||
return (
|
return (
|
||||||
<View
|
<View
|
||||||
{...dragAttributes}
|
{...dragAttributes}
|
||||||
{...(isEditingTitle ? null : dragHandleProps?.listeners)}
|
{...(disableDrag ? null : dragHandleProps?.listeners)}
|
||||||
ref={dragHandleProps?.setActivatorNodeRef as unknown as Ref<View>}
|
ref={dragHandleProps?.setActivatorNodeRef as unknown as Ref<View>}
|
||||||
style={styles.workspaceRowContainer}
|
style={styles.workspaceRowContainer}
|
||||||
{...hoverHandlers}
|
{...hoverHandlers}
|
||||||
@@ -1131,6 +1172,7 @@ function WorkspaceRowInner({
|
|||||||
onRename={onRename}
|
onRename={onRename}
|
||||||
onMarkAsRead={onMarkAsRead}
|
onMarkAsRead={onMarkAsRead}
|
||||||
onMarkAsUnread={onMarkAsUnread}
|
onMarkAsUnread={onMarkAsUnread}
|
||||||
|
onSelectWorkspace={onSelectWorkspace}
|
||||||
onArchive={onArchive}
|
onArchive={onArchive}
|
||||||
archiveLabel={archiveLabel}
|
archiveLabel={archiveLabel}
|
||||||
archiveStatus={archiveStatus}
|
archiveStatus={archiveStatus}
|
||||||
@@ -1140,17 +1182,18 @@ function WorkspaceRowInner({
|
|||||||
onTogglePin={onTogglePin}
|
onTogglePin={onTogglePin}
|
||||||
openInFileManagerPath={workspace.workspaceDirectory}
|
openInFileManagerPath={workspace.workspaceDirectory}
|
||||||
disabled={isArchiving}
|
disabled={isArchiving}
|
||||||
enabled={!isEditingTitle}
|
enabled={!isEditingTitle && !isSelectionMode}
|
||||||
aria-selected={selected}
|
aria-selected={isSelectionMode ? undefined : selected}
|
||||||
accessibilityRole="button"
|
aria-checked={isSelectionMode ? isBulkSelected : undefined}
|
||||||
|
accessibilityRole={isSelectionMode ? "checkbox" : "button"}
|
||||||
accessibilityState={accessibilityState}
|
accessibilityState={accessibilityState}
|
||||||
style={workspaceRowStyle}
|
style={workspaceRowStyle}
|
||||||
highlightStyle={isEditingTitle ? undefined : styles.workspaceRowPressed}
|
highlightStyle={isEditingTitle ? undefined : styles.workspaceRowPressed}
|
||||||
onHighlightChange={setIsHighlighted}
|
onHighlightChange={setIsHighlighted}
|
||||||
onPressIn={isEditingTitle ? undefined : interaction.handlePressIn}
|
onPressIn={isEditingTitle ? undefined : handleRowPressIn}
|
||||||
onTouchMove={isEditingTitle ? undefined : interaction.handleTouchMove}
|
onTouchMove={disableDrag ? undefined : interaction.handleTouchMove}
|
||||||
onPressOut={isEditingTitle ? undefined : interaction.handlePressOut}
|
onPressOut={disableDrag ? undefined : interaction.handlePressOut}
|
||||||
onPress={isEditingTitle ? undefined : handlePress}
|
onPress={isEditingTitle ? undefined : handleRowPress}
|
||||||
testID={`sidebar-workspace-row-${workspace.workspaceKey}`}
|
testID={`sidebar-workspace-row-${workspace.workspaceKey}`}
|
||||||
>
|
>
|
||||||
<SidebarWorkspaceRowContent
|
<SidebarWorkspaceRowContent
|
||||||
@@ -1163,6 +1206,8 @@ function WorkspaceRowInner({
|
|||||||
isHovered={isHovered}
|
isHovered={isHovered}
|
||||||
isLoading={isArchiving || isCreating}
|
isLoading={isArchiving || isCreating}
|
||||||
isCreating={isCreating}
|
isCreating={isCreating}
|
||||||
|
isSelectionMode={isSelectionMode}
|
||||||
|
isBulkSelected={isBulkSelected}
|
||||||
shortcutNumber={shortcutNumber}
|
shortcutNumber={shortcutNumber}
|
||||||
showShortcutBadge={showShortcutBadge}
|
showShortcutBadge={showShortcutBadge}
|
||||||
reserveIdleStatusIndicatorSpace={reserveIdleStatusIndicatorSpace}
|
reserveIdleStatusIndicatorSpace={reserveIdleStatusIndicatorSpace}
|
||||||
@@ -1174,12 +1219,14 @@ function WorkspaceRowInner({
|
|||||||
isHovered={isHovered}
|
isHovered={isHovered}
|
||||||
isTouchPlatform={isTouchPlatform}
|
isTouchPlatform={isTouchPlatform}
|
||||||
isCreating={isCreating}
|
isCreating={isCreating}
|
||||||
|
isSelectionMode={isSelectionMode}
|
||||||
showShortcutBadge={showShortcutBadge}
|
showShortcutBadge={showShortcutBadge}
|
||||||
shortcutNumber={shortcutNumber}
|
shortcutNumber={shortcutNumber}
|
||||||
archiveLabel={archiveLabel}
|
archiveLabel={archiveLabel}
|
||||||
archiveStatus={archiveStatus}
|
archiveStatus={archiveStatus}
|
||||||
archivePendingLabel={archivePendingLabel}
|
archivePendingLabel={archivePendingLabel}
|
||||||
archiveShortcutKeys={archiveShortcutKeys}
|
archiveShortcutKeys={archiveShortcutKeys}
|
||||||
|
onSelectWorkspace={onSelectWorkspace}
|
||||||
onArchive={onArchive}
|
onArchive={onArchive}
|
||||||
onCopyBranchName={onCopyBranchName}
|
onCopyBranchName={onCopyBranchName}
|
||||||
onCopyPath={onCopyPath}
|
onCopyPath={onCopyPath}
|
||||||
@@ -1265,6 +1312,10 @@ function WorkspaceRowWithMenu({
|
|||||||
archiveController.archive();
|
archiveController.archive();
|
||||||
}, [archiveController, isArchiving]);
|
}, [archiveController, isArchiving]);
|
||||||
|
|
||||||
|
const handleSelectWorkspace = useCallback(() => {
|
||||||
|
useSidebarSelectionStore.getState().enter(workspace.workspaceKey);
|
||||||
|
}, [workspace.workspaceKey]);
|
||||||
|
|
||||||
const clipboard = useWorkspaceClipboardActions();
|
const clipboard = useWorkspaceClipboardActions();
|
||||||
const handleCopyPath = useCallback(() => {
|
const handleCopyPath = useCallback(() => {
|
||||||
clipboard.copyPath(workspace);
|
clipboard.copyPath(workspace);
|
||||||
@@ -1317,6 +1368,7 @@ function WorkspaceRowWithMenu({
|
|||||||
archiveLabel={t("sidebar.workspace.actions.archive")}
|
archiveLabel={t("sidebar.workspace.actions.archive")}
|
||||||
archiveStatus={isArchiving ? "pending" : "idle"}
|
archiveStatus={isArchiving ? "pending" : "idle"}
|
||||||
archivePendingLabel={t("sidebar.workspace.actions.archiving")}
|
archivePendingLabel={t("sidebar.workspace.actions.archiving")}
|
||||||
|
onSelectWorkspace={handleSelectWorkspace}
|
||||||
onArchive={handleArchive}
|
onArchive={handleArchive}
|
||||||
onCopyBranchName={canCopyBranchName ? handleCopyBranchName : undefined}
|
onCopyBranchName={canCopyBranchName ? handleCopyBranchName : undefined}
|
||||||
onCopyPath={handleCopyPath}
|
onCopyPath={handleCopyPath}
|
||||||
@@ -2199,6 +2251,62 @@ function ProjectModeList({
|
|||||||
selection: selectionEnabled ? activeWorkspaceSelection : null,
|
selection: selectionEnabled ? activeWorkspaceSelection : null,
|
||||||
expanded: pinnedChatsExpanded,
|
expanded: pinnedChatsExpanded,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const visibleOrderInputRef = useRef({
|
||||||
|
pinnedCollapsed,
|
||||||
|
leadingPinnedChat,
|
||||||
|
visiblePinnedChats,
|
||||||
|
unpinnedProjects,
|
||||||
|
collapsedProjectKeys,
|
||||||
|
expandedProjectKeys,
|
||||||
|
selectionEnabled,
|
||||||
|
activeWorkspaceSelection,
|
||||||
|
workspaceEntriesByKey,
|
||||||
|
});
|
||||||
|
visibleOrderInputRef.current = {
|
||||||
|
pinnedCollapsed,
|
||||||
|
leadingPinnedChat,
|
||||||
|
visiblePinnedChats,
|
||||||
|
unpinnedProjects,
|
||||||
|
collapsedProjectKeys,
|
||||||
|
expandedProjectKeys,
|
||||||
|
selectionEnabled,
|
||||||
|
activeWorkspaceSelection,
|
||||||
|
workspaceEntriesByKey,
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
return registerSidebarVisibleWorkspaceKeysReader(() => {
|
||||||
|
const current = visibleOrderInputRef.current;
|
||||||
|
const keys: string[] = [];
|
||||||
|
if (!current.pinnedCollapsed) {
|
||||||
|
if (current.leadingPinnedChat) keys.push(current.leadingPinnedChat.workspaceKey);
|
||||||
|
for (const item of current.visiblePinnedChats) {
|
||||||
|
keys.push(item.workspaceKey);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const policy = createWorkspaceVisibilityPolicy<SidebarWorkspacePlacement>(
|
||||||
|
current.workspaceEntriesByKey,
|
||||||
|
);
|
||||||
|
const selection = current.selectionEnabled ? current.activeWorkspaceSelection : null;
|
||||||
|
for (const project of current.unpinnedProjects) {
|
||||||
|
if (current.collapsedProjectKeys.has(project.viewKey) || project.workspaces.length === 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const { leadingItem, visibleItems } = selectSidebarGroupVisibility({
|
||||||
|
items: project.workspaces,
|
||||||
|
selection,
|
||||||
|
expanded: current.expandedProjectKeys.has(project.viewKey),
|
||||||
|
policy,
|
||||||
|
});
|
||||||
|
if (leadingItem) keys.push(leadingItem.workspaceKey);
|
||||||
|
for (const item of visibleItems) {
|
||||||
|
keys.push(item.workspaceKey);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return keys;
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
const nativeScrollGestureProps = useMemo(
|
const nativeScrollGestureProps = useMemo(
|
||||||
() =>
|
() =>
|
||||||
parentGestureRef
|
parentGestureRef
|
||||||
|
|||||||
@@ -3,7 +3,9 @@ import { PressHighlight as Pressable } from "@/components/ui/press-highlight";
|
|||||||
import {
|
import {
|
||||||
memo,
|
memo,
|
||||||
useCallback,
|
useCallback,
|
||||||
|
useEffect,
|
||||||
useMemo,
|
useMemo,
|
||||||
|
useRef,
|
||||||
useState,
|
useState,
|
||||||
type MutableRefObject,
|
type MutableRefObject,
|
||||||
type ReactNode,
|
type ReactNode,
|
||||||
@@ -69,7 +71,15 @@ import {
|
|||||||
} from "@/components/sidebar/sidebar-workspace-menu";
|
} from "@/components/sidebar/sidebar-workspace-menu";
|
||||||
import { SidebarSectionHeader } from "@/components/sidebar/sidebar-section-header";
|
import { SidebarSectionHeader } from "@/components/sidebar/sidebar-section-header";
|
||||||
import { SidebarGroupToggleRow } from "@/components/sidebar/sidebar-group-toggle-row";
|
import { SidebarGroupToggleRow } from "@/components/sidebar/sidebar-group-toggle-row";
|
||||||
|
import { selectSidebarGroupVisibility } from "@/components/sidebar/sidebar-group-visibility";
|
||||||
import { useLimitedSidebarGroup } from "@/components/sidebar/use-limited-sidebar-group";
|
import { useLimitedSidebarGroup } from "@/components/sidebar/use-limited-sidebar-group";
|
||||||
|
import {
|
||||||
|
registerSidebarVisibleWorkspaceKeysReader,
|
||||||
|
useIsSidebarSelectionMode,
|
||||||
|
useIsWorkspaceBulkSelected,
|
||||||
|
useSidebarSelectionStore,
|
||||||
|
useWorkspaceSelectionPress,
|
||||||
|
} from "@/sidebar-selection";
|
||||||
import type { ToggleSidebarWorkspacePin } from "@/hooks/use-sidebar-workspace-pin";
|
import type { ToggleSidebarWorkspacePin } from "@/hooks/use-sidebar-workspace-pin";
|
||||||
import { DraggableList, type DraggableRenderItemInfo } from "@/components/draggable-list";
|
import { DraggableList, type DraggableRenderItemInfo } from "@/components/draggable-list";
|
||||||
import type { DraggableListDragHandleProps } from "@/components/draggable-list.types";
|
import type { DraggableListDragHandleProps } from "@/components/draggable-list.types";
|
||||||
@@ -154,6 +164,14 @@ export function SidebarStatusWorkspaceList({
|
|||||||
() => setPinnedWorkspacesExpanded((current) => !current),
|
() => setPinnedWorkspacesExpanded((current) => !current),
|
||||||
[],
|
[],
|
||||||
);
|
);
|
||||||
|
const [expandedGroupKeys, setExpandedGroupKeys] = useState<ReadonlySet<string>>(() => new Set());
|
||||||
|
const toggleGroupWorkspacesExpanded = useCallback((groupKey: string) => {
|
||||||
|
setExpandedGroupKeys((current) => {
|
||||||
|
const next = new Set(current);
|
||||||
|
if (!next.delete(groupKey)) next.add(groupKey);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
const {
|
const {
|
||||||
leadingItem: leadingPinnedWorkspace,
|
leadingItem: leadingPinnedWorkspace,
|
||||||
visibleItems: visiblePinnedWorkspaces,
|
visibleItems: visiblePinnedWorkspaces,
|
||||||
@@ -164,6 +182,56 @@ export function SidebarStatusWorkspaceList({
|
|||||||
expanded: pinnedWorkspacesExpanded,
|
expanded: pinnedWorkspacesExpanded,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const visibleOrderInputRef = useRef({
|
||||||
|
pinnedCollapsed,
|
||||||
|
leadingPinnedWorkspace,
|
||||||
|
visiblePinnedWorkspaces,
|
||||||
|
groups,
|
||||||
|
collapsedWorkspaceGroupKeys,
|
||||||
|
expandedGroupKeys,
|
||||||
|
activeWorkspaceSelection,
|
||||||
|
});
|
||||||
|
visibleOrderInputRef.current = {
|
||||||
|
pinnedCollapsed,
|
||||||
|
leadingPinnedWorkspace,
|
||||||
|
visiblePinnedWorkspaces,
|
||||||
|
groups,
|
||||||
|
collapsedWorkspaceGroupKeys,
|
||||||
|
expandedGroupKeys,
|
||||||
|
activeWorkspaceSelection,
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
return registerSidebarVisibleWorkspaceKeysReader(() => {
|
||||||
|
const current = visibleOrderInputRef.current;
|
||||||
|
const keys: string[] = [];
|
||||||
|
if (!current.pinnedCollapsed) {
|
||||||
|
if (current.leadingPinnedWorkspace) {
|
||||||
|
keys.push(current.leadingPinnedWorkspace.workspaceKey);
|
||||||
|
}
|
||||||
|
for (const item of current.visiblePinnedWorkspaces) {
|
||||||
|
keys.push(item.workspaceKey);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const group of current.groups) {
|
||||||
|
if (current.collapsedWorkspaceGroupKeys.has(group.key) || group.rows.length === 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const { leadingItem, visibleItems } = selectSidebarGroupVisibility({
|
||||||
|
items: group.rows,
|
||||||
|
selection: current.activeWorkspaceSelection,
|
||||||
|
expanded: current.expandedGroupKeys.has(group.key),
|
||||||
|
policy: STATUS_GROUP_VISIBILITY,
|
||||||
|
});
|
||||||
|
if (leadingItem) keys.push(leadingItem.workspaceKey);
|
||||||
|
for (const item of visibleItems) {
|
||||||
|
keys.push(item.workspaceKey);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return keys;
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
const statusShortcutIndex = showShortcutBadges
|
const statusShortcutIndex = showShortcutBadges
|
||||||
? shortcutIndexByWorkspaceKey
|
? shortcutIndexByWorkspaceKey
|
||||||
: EMPTY_SHORTCUT_INDEX;
|
: EMPTY_SHORTCUT_INDEX;
|
||||||
@@ -262,6 +330,8 @@ export function SidebarStatusWorkspaceList({
|
|||||||
<StatusGroupList
|
<StatusGroupList
|
||||||
groups={groups}
|
groups={groups}
|
||||||
collapsedWorkspaceGroupKeys={collapsedWorkspaceGroupKeys}
|
collapsedWorkspaceGroupKeys={collapsedWorkspaceGroupKeys}
|
||||||
|
expandedGroupKeys={expandedGroupKeys}
|
||||||
|
onToggleGroupWorkspacesExpanded={toggleGroupWorkspacesExpanded}
|
||||||
projectIconByProjectViewKey={projectIconByProjectViewKey}
|
projectIconByProjectViewKey={projectIconByProjectViewKey}
|
||||||
shortcutIndex={statusShortcutIndex}
|
shortcutIndex={statusShortcutIndex}
|
||||||
showShortcutBadges={showShortcutBadges}
|
showShortcutBadges={showShortcutBadges}
|
||||||
@@ -303,6 +373,8 @@ export function SidebarStatusWorkspaceList({
|
|||||||
function StatusGroupList({
|
function StatusGroupList({
|
||||||
groups,
|
groups,
|
||||||
collapsedWorkspaceGroupKeys,
|
collapsedWorkspaceGroupKeys,
|
||||||
|
expandedGroupKeys,
|
||||||
|
onToggleGroupWorkspacesExpanded,
|
||||||
projectIconByProjectViewKey,
|
projectIconByProjectViewKey,
|
||||||
shortcutIndex,
|
shortcutIndex,
|
||||||
showShortcutBadges,
|
showShortcutBadges,
|
||||||
@@ -313,6 +385,8 @@ function StatusGroupList({
|
|||||||
}: {
|
}: {
|
||||||
groups: SidebarWorkspaceGroup[];
|
groups: SidebarWorkspaceGroup[];
|
||||||
collapsedWorkspaceGroupKeys: ReadonlySet<string>;
|
collapsedWorkspaceGroupKeys: ReadonlySet<string>;
|
||||||
|
expandedGroupKeys: ReadonlySet<string>;
|
||||||
|
onToggleGroupWorkspacesExpanded: (groupKey: string) => void;
|
||||||
projectIconByProjectViewKey: ReadonlyMap<string, string | null>;
|
projectIconByProjectViewKey: ReadonlyMap<string, string | null>;
|
||||||
shortcutIndex: Map<string, number>;
|
shortcutIndex: Map<string, number>;
|
||||||
showShortcutBadges: boolean;
|
showShortcutBadges: boolean;
|
||||||
@@ -328,6 +402,8 @@ function StatusGroupList({
|
|||||||
key={group.key}
|
key={group.key}
|
||||||
group={group}
|
group={group}
|
||||||
collapsed={collapsedWorkspaceGroupKeys.has(group.key)}
|
collapsed={collapsedWorkspaceGroupKeys.has(group.key)}
|
||||||
|
workspacesExpanded={expandedGroupKeys.has(group.key)}
|
||||||
|
onToggleWorkspacesExpanded={onToggleGroupWorkspacesExpanded}
|
||||||
projectIconByProjectViewKey={projectIconByProjectViewKey}
|
projectIconByProjectViewKey={projectIconByProjectViewKey}
|
||||||
shortcutIndex={shortcutIndex}
|
shortcutIndex={shortcutIndex}
|
||||||
showShortcutBadges={showShortcutBadges}
|
showShortcutBadges={showShortcutBadges}
|
||||||
@@ -349,6 +425,8 @@ const STATUS_GROUP_VISIBILITY = {
|
|||||||
function StatusGroupRows({
|
function StatusGroupRows({
|
||||||
group,
|
group,
|
||||||
collapsed,
|
collapsed,
|
||||||
|
workspacesExpanded,
|
||||||
|
onToggleWorkspacesExpanded,
|
||||||
projectIconByProjectViewKey,
|
projectIconByProjectViewKey,
|
||||||
shortcutIndex,
|
shortcutIndex,
|
||||||
showShortcutBadges,
|
showShortcutBadges,
|
||||||
@@ -359,6 +437,8 @@ function StatusGroupRows({
|
|||||||
}: {
|
}: {
|
||||||
group: SidebarWorkspaceGroup;
|
group: SidebarWorkspaceGroup;
|
||||||
collapsed: boolean;
|
collapsed: boolean;
|
||||||
|
workspacesExpanded: boolean;
|
||||||
|
onToggleWorkspacesExpanded: (groupKey: string) => void;
|
||||||
projectIconByProjectViewKey: ReadonlyMap<string, string | null>;
|
projectIconByProjectViewKey: ReadonlyMap<string, string | null>;
|
||||||
shortcutIndex: Map<string, number>;
|
shortcutIndex: Map<string, number>;
|
||||||
showShortcutBadges: boolean;
|
showShortcutBadges: boolean;
|
||||||
@@ -368,10 +448,9 @@ function StatusGroupRows({
|
|||||||
onToggleWorkspacePin: ToggleSidebarWorkspacePin;
|
onToggleWorkspacePin: ToggleSidebarWorkspacePin;
|
||||||
}) {
|
}) {
|
||||||
const activeWorkspaceSelection = useActiveWorkspaceSelection();
|
const activeWorkspaceSelection = useActiveWorkspaceSelection();
|
||||||
const [workspacesExpanded, setWorkspacesExpanded] = useState(false);
|
|
||||||
const toggleWorkspacesExpanded = useCallback(
|
const toggleWorkspacesExpanded = useCallback(
|
||||||
() => setWorkspacesExpanded((current) => !current),
|
() => onToggleWorkspacesExpanded(group.key),
|
||||||
[],
|
[group.key, onToggleWorkspacesExpanded],
|
||||||
);
|
);
|
||||||
const {
|
const {
|
||||||
leadingItem: leadingWorkspace,
|
leadingItem: leadingWorkspace,
|
||||||
@@ -669,6 +748,10 @@ function StatusWorkspaceRowWithMenu({
|
|||||||
archiveController.archive();
|
archiveController.archive();
|
||||||
}, [archiveController, isArchiving]);
|
}, [archiveController, isArchiving]);
|
||||||
|
|
||||||
|
const handleSelectWorkspace = useCallback(() => {
|
||||||
|
useSidebarSelectionStore.getState().enter(workspace.workspaceKey);
|
||||||
|
}, [workspace.workspaceKey]);
|
||||||
|
|
||||||
const clipboard = useWorkspaceClipboardActions();
|
const clipboard = useWorkspaceClipboardActions();
|
||||||
const handleCopyPath = useCallback(() => {
|
const handleCopyPath = useCallback(() => {
|
||||||
clipboard.copyPath(workspace);
|
clipboard.copyPath(workspace);
|
||||||
@@ -716,6 +799,7 @@ function StatusWorkspaceRowWithMenu({
|
|||||||
archiveLabel={t("sidebar.workspace.actions.archive")}
|
archiveLabel={t("sidebar.workspace.actions.archive")}
|
||||||
archiveStatus={isArchiving ? "pending" : "idle"}
|
archiveStatus={isArchiving ? "pending" : "idle"}
|
||||||
archivePendingLabel={t("sidebar.workspace.actions.archiving")}
|
archivePendingLabel={t("sidebar.workspace.actions.archiving")}
|
||||||
|
onSelectWorkspace={handleSelectWorkspace}
|
||||||
onArchive={handleArchive}
|
onArchive={handleArchive}
|
||||||
onCopyBranchName={workspace.projectKind === "git" ? handleCopyBranchName : undefined}
|
onCopyBranchName={workspace.projectKind === "git" ? handleCopyBranchName : undefined}
|
||||||
onCopyPath={handleCopyPath}
|
onCopyPath={handleCopyPath}
|
||||||
@@ -750,6 +834,7 @@ interface StatusWorkspaceRowInnerProps {
|
|||||||
archiveLabel?: string;
|
archiveLabel?: string;
|
||||||
archiveStatus?: "idle" | "pending" | "success";
|
archiveStatus?: "idle" | "pending" | "success";
|
||||||
archivePendingLabel?: string;
|
archivePendingLabel?: string;
|
||||||
|
onSelectWorkspace?: () => void;
|
||||||
onArchive?: () => void;
|
onArchive?: () => void;
|
||||||
onCopyBranchName?: () => void;
|
onCopyBranchName?: () => void;
|
||||||
onCopyPath?: () => void;
|
onCopyPath?: () => void;
|
||||||
@@ -799,6 +884,7 @@ function StatusWorkspaceRowInnerContent({
|
|||||||
archiveLabel,
|
archiveLabel,
|
||||||
archiveStatus = "idle",
|
archiveStatus = "idle",
|
||||||
archivePendingLabel,
|
archivePendingLabel,
|
||||||
|
onSelectWorkspace,
|
||||||
onArchive,
|
onArchive,
|
||||||
onCopyBranchName,
|
onCopyBranchName,
|
||||||
onCopyPath,
|
onCopyPath,
|
||||||
@@ -820,6 +906,8 @@ function StatusWorkspaceRowInnerContent({
|
|||||||
const isCompact = useIsCompactFormFactor();
|
const isCompact = useIsCompactFormFactor();
|
||||||
const isTouchPlatform = platformIsNative || isCompact;
|
const isTouchPlatform = platformIsNative || isCompact;
|
||||||
const [isHighlighted, setIsHighlighted] = useState(false);
|
const [isHighlighted, setIsHighlighted] = useState(false);
|
||||||
|
const isSelectionMode = useIsSidebarSelectionMode();
|
||||||
|
const isBulkSelected = useIsWorkspaceBulkSelected(workspace.workspaceKey);
|
||||||
const trailing = useSidebarWorkspaceTrailing();
|
const trailing = useSidebarWorkspaceTrailing();
|
||||||
const {
|
const {
|
||||||
role: _dragRole,
|
role: _dragRole,
|
||||||
@@ -831,23 +919,35 @@ function StatusWorkspaceRowInnerContent({
|
|||||||
const isDesktop = !isTouchPlatform;
|
const isDesktop = !isTouchPlatform;
|
||||||
const serviceSummary = isDesktop ? selectWorkspaceServiceSummary(workspace.scripts) : null;
|
const serviceSummary = isDesktop ? selectWorkspaceServiceSummary(workspace.scripts) : null;
|
||||||
|
|
||||||
const accessibilityState = useMemo(() => ({ selected }), [selected]);
|
const rowSelected = isSelectionMode ? isBulkSelected : selected;
|
||||||
|
const accessibilityState = useMemo(
|
||||||
|
() => (isSelectionMode ? { checked: isBulkSelected } : { selected }),
|
||||||
|
[isSelectionMode, isBulkSelected, selected],
|
||||||
|
);
|
||||||
const isEditingTitle = titleEditor !== null;
|
const isEditingTitle = titleEditor !== null;
|
||||||
|
const disableDrag = isEditingTitle || isSelectionMode;
|
||||||
const didLongPressRef = dragInteraction?.didLongPressRef;
|
const didLongPressRef = dragInteraction?.didLongPressRef;
|
||||||
const startDragPress = dragInteraction?.handlePressIn;
|
const startDragPress = dragInteraction?.handlePressIn;
|
||||||
const moveDragPress = dragInteraction?.handleTouchMove;
|
const moveDragPress = dragInteraction?.handleTouchMove;
|
||||||
const endDragPress = dragInteraction?.handlePressOut;
|
const endDragPress = dragInteraction?.handlePressOut;
|
||||||
const { onPress: handlePress, feedback } = useWorkspaceRowPress({
|
const { onPress: handleNavigatePress, feedback } = useWorkspaceRowPress({
|
||||||
didLongPressRef,
|
didLongPressRef,
|
||||||
onPress,
|
onPress,
|
||||||
selected,
|
selected,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const { onPress: handleRowPress, onPressIn: handleRowPressIn } = useWorkspaceSelectionPress({
|
||||||
|
workspaceKey: workspace.workspaceKey,
|
||||||
|
onNavigate: handleNavigatePress,
|
||||||
|
onPressIn: startDragPress,
|
||||||
|
});
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<SidebarWorkspaceRowFrame
|
<SidebarWorkspaceRowFrame
|
||||||
workspace={workspace}
|
workspace={workspace}
|
||||||
isDragging={isDragging}
|
isDragging={isDragging}
|
||||||
isEditingTitle={isEditingTitle}
|
isEditingTitle={isEditingTitle}
|
||||||
|
isSelectionMode={isSelectionMode}
|
||||||
>
|
>
|
||||||
{({ isHovered, contextMenuOpen, onContextMenuOpenChange, hoverHandlers }) => {
|
{({ isHovered, contextMenuOpen, onContextMenuOpenChange, hoverHandlers }) => {
|
||||||
const showShortcut = showShortcutBadge && shortcutNumber !== null;
|
const showShortcut = showShortcutBadge && shortcutNumber !== null;
|
||||||
@@ -865,18 +965,24 @@ function StatusWorkspaceRowInnerContent({
|
|||||||
isHovered,
|
isHovered,
|
||||||
isTouchPlatform,
|
isTouchPlatform,
|
||||||
showShortcut,
|
showShortcut,
|
||||||
|
isSelectionMode,
|
||||||
});
|
});
|
||||||
const workspaceRowStyle = getStatusWorkspaceRowStyle({
|
const workspaceRowStyle = getStatusWorkspaceRowStyle({
|
||||||
selected,
|
selected: rowSelected,
|
||||||
isHovered,
|
isHovered,
|
||||||
inStatusGroup,
|
inStatusGroup,
|
||||||
isDragging,
|
isDragging,
|
||||||
});
|
});
|
||||||
const backdrop = getSidebarRowBackdrop({ isDragging, isHighlighted, selected, isHovered });
|
const backdrop = getSidebarRowBackdrop({
|
||||||
|
isDragging,
|
||||||
|
isHighlighted,
|
||||||
|
selected: rowSelected,
|
||||||
|
isHovered,
|
||||||
|
});
|
||||||
return (
|
return (
|
||||||
<View
|
<View
|
||||||
{...dragAttributes}
|
{...dragAttributes}
|
||||||
{...(isEditingTitle ? null : dragHandleProps?.listeners)}
|
{...(disableDrag ? null : dragHandleProps?.listeners)}
|
||||||
ref={dragHandleProps?.setActivatorNodeRef as unknown as Ref<View>}
|
ref={dragHandleProps?.setActivatorNodeRef as unknown as Ref<View>}
|
||||||
style={styles.workspaceRowContainer}
|
style={styles.workspaceRowContainer}
|
||||||
{...hoverHandlers}
|
{...hoverHandlers}
|
||||||
@@ -894,6 +1000,7 @@ function StatusWorkspaceRowInnerContent({
|
|||||||
onRename={onRename}
|
onRename={onRename}
|
||||||
onMarkAsRead={onMarkAsRead}
|
onMarkAsRead={onMarkAsRead}
|
||||||
onMarkAsUnread={onMarkAsUnread}
|
onMarkAsUnread={onMarkAsUnread}
|
||||||
|
onSelectWorkspace={onSelectWorkspace}
|
||||||
onArchive={onArchive}
|
onArchive={onArchive}
|
||||||
archiveLabel={archiveLabel}
|
archiveLabel={archiveLabel}
|
||||||
archiveStatus={archiveStatus}
|
archiveStatus={archiveStatus}
|
||||||
@@ -903,16 +1010,18 @@ function StatusWorkspaceRowInnerContent({
|
|||||||
onTogglePin={onTogglePin}
|
onTogglePin={onTogglePin}
|
||||||
openInFileManagerPath={workspace.workspaceDirectory}
|
openInFileManagerPath={workspace.workspaceDirectory}
|
||||||
disabled={isArchiving}
|
disabled={isArchiving}
|
||||||
enabled={!isEditingTitle}
|
enabled={!isEditingTitle && !isSelectionMode}
|
||||||
accessibilityRole="button"
|
aria-selected={isSelectionMode ? undefined : selected}
|
||||||
|
aria-checked={isSelectionMode ? isBulkSelected : undefined}
|
||||||
|
accessibilityRole={isSelectionMode ? "checkbox" : "button"}
|
||||||
accessibilityState={accessibilityState}
|
accessibilityState={accessibilityState}
|
||||||
style={workspaceRowStyle}
|
style={workspaceRowStyle}
|
||||||
highlightStyle={isEditingTitle ? undefined : styles.workspaceRowPressed}
|
highlightStyle={isEditingTitle ? undefined : styles.workspaceRowPressed}
|
||||||
onHighlightChange={setIsHighlighted}
|
onHighlightChange={setIsHighlighted}
|
||||||
onPressIn={isEditingTitle ? undefined : startDragPress}
|
onPressIn={isEditingTitle ? undefined : handleRowPressIn}
|
||||||
onTouchMove={isEditingTitle ? undefined : moveDragPress}
|
onTouchMove={disableDrag ? undefined : moveDragPress}
|
||||||
onPressOut={isEditingTitle ? undefined : endDragPress}
|
onPressOut={disableDrag ? undefined : endDragPress}
|
||||||
onPress={isEditingTitle ? undefined : handlePress}
|
onPress={isEditingTitle ? undefined : handleRowPress}
|
||||||
testID={`sidebar-workspace-row-${workspace.workspaceKey}`}
|
testID={`sidebar-workspace-row-${workspace.workspaceKey}`}
|
||||||
>
|
>
|
||||||
<SidebarWorkspaceRowContent
|
<SidebarWorkspaceRowContent
|
||||||
@@ -924,6 +1033,8 @@ function StatusWorkspaceRowInnerContent({
|
|||||||
backdrop={backdrop}
|
backdrop={backdrop}
|
||||||
isHovered={isHovered}
|
isHovered={isHovered}
|
||||||
isLoading={isArchiving}
|
isLoading={isArchiving}
|
||||||
|
isSelectionMode={isSelectionMode}
|
||||||
|
isBulkSelected={isBulkSelected}
|
||||||
shortcutNumber={shortcutNumber}
|
shortcutNumber={shortcutNumber}
|
||||||
showShortcutBadge={showShortcutBadge}
|
showShortcutBadge={showShortcutBadge}
|
||||||
reserveIdleStatusIndicatorSpace={reserveIdleStatusIndicatorSpace}
|
reserveIdleStatusIndicatorSpace={reserveIdleStatusIndicatorSpace}
|
||||||
@@ -946,6 +1057,7 @@ function StatusWorkspaceRowInnerContent({
|
|||||||
onRename={onRename}
|
onRename={onRename}
|
||||||
onMarkAsRead={onMarkAsRead}
|
onMarkAsRead={onMarkAsRead}
|
||||||
onMarkAsUnread={onMarkAsUnread}
|
onMarkAsUnread={onMarkAsUnread}
|
||||||
|
onSelectWorkspace={onSelectWorkspace}
|
||||||
onArchive={onArchive}
|
onArchive={onArchive}
|
||||||
archiveLabel={archiveLabel}
|
archiveLabel={archiveLabel}
|
||||||
archiveStatus={archiveStatus}
|
archiveStatus={archiveStatus}
|
||||||
@@ -979,6 +1091,7 @@ function StatusWorkspaceActionSlot({
|
|||||||
onRename,
|
onRename,
|
||||||
onMarkAsRead,
|
onMarkAsRead,
|
||||||
onMarkAsUnread,
|
onMarkAsUnread,
|
||||||
|
onSelectWorkspace,
|
||||||
onArchive,
|
onArchive,
|
||||||
archiveLabel,
|
archiveLabel,
|
||||||
archiveStatus,
|
archiveStatus,
|
||||||
@@ -1000,6 +1113,7 @@ function StatusWorkspaceActionSlot({
|
|||||||
onRename?: () => void;
|
onRename?: () => void;
|
||||||
onMarkAsRead?: () => void;
|
onMarkAsRead?: () => void;
|
||||||
onMarkAsUnread?: () => void;
|
onMarkAsUnread?: () => void;
|
||||||
|
onSelectWorkspace?: () => void;
|
||||||
onArchive?: () => void;
|
onArchive?: () => void;
|
||||||
archiveLabel?: string;
|
archiveLabel?: string;
|
||||||
archiveStatus?: "idle" | "pending" | "success";
|
archiveStatus?: "idle" | "pending" | "success";
|
||||||
@@ -1034,6 +1148,7 @@ function StatusWorkspaceActionSlot({
|
|||||||
onRename={onRename}
|
onRename={onRename}
|
||||||
onMarkAsRead={onMarkAsRead}
|
onMarkAsRead={onMarkAsRead}
|
||||||
onMarkAsUnread={onMarkAsUnread}
|
onMarkAsUnread={onMarkAsUnread}
|
||||||
|
onSelectWorkspace={onSelectWorkspace}
|
||||||
onArchive={onArchive}
|
onArchive={onArchive}
|
||||||
archiveLabel={archiveLabel}
|
archiveLabel={archiveLabel}
|
||||||
archiveStatus={archiveStatus}
|
archiveStatus={archiveStatus}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import {
|
|||||||
useEffect,
|
useEffect,
|
||||||
useMemo,
|
useMemo,
|
||||||
useRef,
|
useRef,
|
||||||
|
useState,
|
||||||
type ReactNode,
|
type ReactNode,
|
||||||
} from "react";
|
} from "react";
|
||||||
import { View } from "react-native";
|
import { View } from "react-native";
|
||||||
@@ -15,7 +16,13 @@ import Animated, {
|
|||||||
type SharedValue,
|
type SharedValue,
|
||||||
} from "react-native-reanimated";
|
} from "react-native-reanimated";
|
||||||
import { StyleSheet } from "react-native-unistyles";
|
import { StyleSheet } from "react-native-unistyles";
|
||||||
import { TOAST_FADE_MS, ToastViewport, useToastHost, type ToastApi } from "@/components/toast-host";
|
import {
|
||||||
|
TOAST_FADE_MS,
|
||||||
|
ToastViewport,
|
||||||
|
useToastHost,
|
||||||
|
type ToastApi,
|
||||||
|
type ToastState,
|
||||||
|
} from "@/components/toast-host";
|
||||||
import { ToastApiProvider, useToast } from "@/contexts/toast-context";
|
import { ToastApiProvider, useToast } from "@/contexts/toast-context";
|
||||||
|
|
||||||
interface SidebarToastCoverage {
|
interface SidebarToastCoverage {
|
||||||
@@ -25,6 +32,10 @@ interface SidebarToastCoverage {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const SidebarToastCoverageContext = createContext<SidebarToastCoverage | null>(null);
|
const SidebarToastCoverageContext = createContext<SidebarToastCoverage | null>(null);
|
||||||
|
const SidebarPersistentToastContext = createContext<((toast: ToastState | null) => void) | null>(
|
||||||
|
null,
|
||||||
|
);
|
||||||
|
const SidebarAppToastContext = createContext<ToastApi | null>(null);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Shows toasts raised by the sidebar's list over its bottom edge, just above the footer.
|
* Shows toasts raised by the sidebar's list over its bottom edge, just above the footer.
|
||||||
@@ -36,9 +47,10 @@ const SidebarToastCoverageContext = createContext<SidebarToastCoverage | null>(n
|
|||||||
export function SidebarToastRegion({ active, children }: { active: boolean; children: ReactNode }) {
|
export function SidebarToastRegion({ active, children }: { active: boolean; children: ReactNode }) {
|
||||||
const appToast = useToast();
|
const appToast = useToast();
|
||||||
const { api: sidebarToast, toast, dismiss } = useToastHost();
|
const { api: sidebarToast, toast, dismiss } = useToastHost();
|
||||||
|
const [persistentToast, setPersistentToast] = useState<ToastState | null>(null);
|
||||||
const activeRef = useRef(active);
|
const activeRef = useRef(active);
|
||||||
const coverageHeight = useSharedValue(0);
|
const coverageHeight = useSharedValue(0);
|
||||||
const toastVisible = toast !== null;
|
const toastVisible = toast !== null || persistentToast !== null;
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
activeRef.current = active;
|
activeRef.current = active;
|
||||||
@@ -72,19 +84,48 @@ export function SidebarToastRegion({ active, children }: { active: boolean; chil
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<View style={styles.region}>
|
<View style={styles.region}>
|
||||||
<SidebarToastCoverageContext.Provider value={coverage}>
|
<ToastApiProvider api={api}>
|
||||||
<ToastApiProvider api={api}>{children}</ToastApiProvider>
|
<SidebarAppToastContext.Provider value={appToast}>
|
||||||
</SidebarToastCoverageContext.Provider>
|
<SidebarPersistentToastContext.Provider value={setPersistentToast}>
|
||||||
<ToastViewport
|
<SidebarToastCoverageContext.Provider value={coverage}>
|
||||||
toast={toast}
|
{children}
|
||||||
onDismiss={dismiss}
|
</SidebarToastCoverageContext.Provider>
|
||||||
placement="sidebar"
|
</SidebarPersistentToastContext.Provider>
|
||||||
onBottomCoverageChange={handleCoverageChange}
|
</SidebarAppToastContext.Provider>
|
||||||
/>
|
<ToastViewport
|
||||||
|
toast={toast}
|
||||||
|
persistentToast={persistentToast}
|
||||||
|
onDismiss={dismiss}
|
||||||
|
placement="sidebar"
|
||||||
|
onBottomCoverageChange={handleCoverageChange}
|
||||||
|
/>
|
||||||
|
</ToastApiProvider>
|
||||||
</View>
|
</View>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Returns the enclosing app-level toast API so sidebar callers can report errors without displacing an active sidebar undo toast. */
|
||||||
|
export function useSidebarAppToast(): ToastApi {
|
||||||
|
const fallbackToast = useToast();
|
||||||
|
return useContext(SidebarAppToastContext) ?? fallbackToast;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Displays a persistent toast in the enclosing `SidebarToastRegion`, stacked below any active
|
||||||
|
* transient toast so controls stay reachable while a previous toast is up.
|
||||||
|
*/
|
||||||
|
export function useSidebarPersistentToast(toast: ToastState | null): void {
|
||||||
|
const setPersistentToast = useContext(SidebarPersistentToastContext);
|
||||||
|
useEffect(() => {
|
||||||
|
setPersistentToast?.(toast);
|
||||||
|
}, [setPersistentToast, toast]);
|
||||||
|
useEffect(() => {
|
||||||
|
return () => {
|
||||||
|
setPersistentToast?.(null);
|
||||||
|
};
|
||||||
|
}, [setPersistentToast]);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Space at the end of a sidebar list that matches the toast covering it, so the last row can
|
* Space at the end of a sidebar list that matches the toast covering it, so the last row can
|
||||||
* scroll clear of the toast. It sits below every row, so growing it moves nothing. It shrinks
|
* scroll clear of the toast. It sits below every row, so growing it moves nothing. It shrinks
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
import { useMemo, type ComponentProps, type PropsWithChildren, type ReactNode } from "react";
|
import { useMemo, type ComponentProps, type PropsWithChildren, type ReactNode } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import type { PressableStateCallbackType } from "react-native";
|
import type { GestureResponderEvent, PressableStateCallbackType } from "react-native";
|
||||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||||
import {
|
import {
|
||||||
Archive,
|
Archive,
|
||||||
|
CheckSquare,
|
||||||
Circle,
|
Circle,
|
||||||
CircleCheck,
|
CircleCheck,
|
||||||
Copy,
|
Copy,
|
||||||
@@ -56,6 +57,7 @@ const foregroundMutedColorMapping = (theme: Theme) => ({
|
|||||||
const ThemedMoreVertical = withUnistyles(MoreVertical);
|
const ThemedMoreVertical = withUnistyles(MoreVertical);
|
||||||
const ThemedCopy = withUnistyles(Copy);
|
const ThemedCopy = withUnistyles(Copy);
|
||||||
const ThemedArchive = withUnistyles(Archive);
|
const ThemedArchive = withUnistyles(Archive);
|
||||||
|
const ThemedCheckSquare = withUnistyles(CheckSquare);
|
||||||
const ThemedCircle = withUnistyles(Circle);
|
const ThemedCircle = withUnistyles(Circle);
|
||||||
const ThemedPencil = withUnistyles(Pencil);
|
const ThemedPencil = withUnistyles(Pencil);
|
||||||
const ThemedCircleCheck = withUnistyles(CircleCheck);
|
const ThemedCircleCheck = withUnistyles(CircleCheck);
|
||||||
@@ -69,6 +71,7 @@ const markAsReadLeadingIcon = (
|
|||||||
<ThemedCircleCheck size={14} uniProps={foregroundMutedColorMapping} />
|
<ThemedCircleCheck size={14} uniProps={foregroundMutedColorMapping} />
|
||||||
);
|
);
|
||||||
const markAsUnreadLeadingIcon = <ThemedCircle size={14} uniProps={foregroundMutedColorMapping} />;
|
const markAsUnreadLeadingIcon = <ThemedCircle size={14} uniProps={foregroundMutedColorMapping} />;
|
||||||
|
const selectLeadingIcon = <ThemedCheckSquare size={14} uniProps={foregroundMutedColorMapping} />;
|
||||||
const archiveLeadingIcon = <ThemedArchive size={14} uniProps={foregroundMutedColorMapping} />;
|
const archiveLeadingIcon = <ThemedArchive size={14} uniProps={foregroundMutedColorMapping} />;
|
||||||
const pinLeadingIcon = <ThemedPin size={14} uniProps={foregroundMutedColorMapping} />;
|
const pinLeadingIcon = <ThemedPin size={14} uniProps={foregroundMutedColorMapping} />;
|
||||||
const unpinLeadingIcon = <ThemedPinOff size={14} uniProps={foregroundMutedColorMapping} />;
|
const unpinLeadingIcon = <ThemedPinOff size={14} uniProps={foregroundMutedColorMapping} />;
|
||||||
@@ -124,6 +127,7 @@ export interface SidebarWorkspaceMenuProps {
|
|||||||
onRename?: () => void;
|
onRename?: () => void;
|
||||||
onMarkAsRead?: () => void;
|
onMarkAsRead?: () => void;
|
||||||
onMarkAsUnread?: () => void;
|
onMarkAsUnread?: () => void;
|
||||||
|
onSelectWorkspace?: () => void;
|
||||||
onArchive: () => void;
|
onArchive: () => void;
|
||||||
archiveLabel?: string;
|
archiveLabel?: string;
|
||||||
archiveStatus?: "idle" | "pending" | "success";
|
archiveStatus?: "idle" | "pending" | "success";
|
||||||
@@ -172,6 +176,7 @@ function SidebarWorkspaceMenuItems({
|
|||||||
onRename,
|
onRename,
|
||||||
onMarkAsRead,
|
onMarkAsRead,
|
||||||
onMarkAsUnread,
|
onMarkAsUnread,
|
||||||
|
onSelectWorkspace,
|
||||||
onArchive,
|
onArchive,
|
||||||
archiveLabel,
|
archiveLabel,
|
||||||
archiveStatus,
|
archiveStatus,
|
||||||
@@ -267,6 +272,16 @@ function SidebarWorkspaceMenuItems({
|
|||||||
path={openInFileManagerPath}
|
path={openInFileManagerPath}
|
||||||
testID={`sidebar-workspace-menu-open-folder-${workspaceKey}`}
|
testID={`sidebar-workspace-menu-open-folder-${workspaceKey}`}
|
||||||
/>
|
/>
|
||||||
|
{onSelectWorkspace ? (
|
||||||
|
<WorkspaceMenuItem
|
||||||
|
surface={surface}
|
||||||
|
testID={`sidebar-workspace-menu-select-${workspaceKey}`}
|
||||||
|
leading={selectLeadingIcon}
|
||||||
|
onSelect={onSelectWorkspace}
|
||||||
|
>
|
||||||
|
{t("sidebar.workspace.actions.select")}
|
||||||
|
</WorkspaceMenuItem>
|
||||||
|
) : null}
|
||||||
{onArchive ? (
|
{onArchive ? (
|
||||||
<WorkspaceMenuItem
|
<WorkspaceMenuItem
|
||||||
surface={surface}
|
surface={surface}
|
||||||
@@ -294,6 +309,7 @@ export function SidebarWorkspaceMenu({
|
|||||||
onRename,
|
onRename,
|
||||||
onMarkAsRead,
|
onMarkAsRead,
|
||||||
onMarkAsUnread,
|
onMarkAsUnread,
|
||||||
|
onSelectWorkspace,
|
||||||
onArchive,
|
onArchive,
|
||||||
archiveLabel,
|
archiveLabel,
|
||||||
archiveStatus,
|
archiveStatus,
|
||||||
@@ -340,6 +356,7 @@ export function SidebarWorkspaceMenu({
|
|||||||
onRename={onRename}
|
onRename={onRename}
|
||||||
onMarkAsRead={onMarkAsRead}
|
onMarkAsRead={onMarkAsRead}
|
||||||
onMarkAsUnread={onMarkAsUnread}
|
onMarkAsUnread={onMarkAsUnread}
|
||||||
|
onSelectWorkspace={onSelectWorkspace}
|
||||||
onArchive={onArchive}
|
onArchive={onArchive}
|
||||||
archiveLabel={archiveLabel}
|
archiveLabel={archiveLabel}
|
||||||
archiveStatus={archiveStatus}
|
archiveStatus={archiveStatus}
|
||||||
@@ -373,6 +390,7 @@ export function SidebarWorkspaceContextMenu({
|
|||||||
onRename,
|
onRename,
|
||||||
onMarkAsRead,
|
onMarkAsRead,
|
||||||
onMarkAsUnread,
|
onMarkAsUnread,
|
||||||
|
onSelectWorkspace,
|
||||||
onArchive,
|
onArchive,
|
||||||
archiveLabel,
|
archiveLabel,
|
||||||
archiveStatus,
|
archiveStatus,
|
||||||
@@ -426,11 +444,37 @@ export function SidebarWorkspaceContextMenu({
|
|||||||
[workspace],
|
[workspace],
|
||||||
);
|
);
|
||||||
const pages = useWorkspaceLabelMenuPages(workspaceTarget);
|
const pages = useWorkspaceLabelMenuPages(workspaceTarget);
|
||||||
|
const checkboxSpaceKeyProps = useMemo(() => {
|
||||||
|
if (!isWeb || triggerProps.accessibilityRole !== "checkbox" || !triggerProps.onPress) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
const onPress = triggerProps.onPress;
|
||||||
|
return {
|
||||||
|
// React Native Web's Pressable activates Space only for role="button", not checkbox.
|
||||||
|
onKeyDown: (event: {
|
||||||
|
key?: string;
|
||||||
|
repeat?: boolean;
|
||||||
|
target?: unknown;
|
||||||
|
currentTarget?: unknown;
|
||||||
|
preventDefault?: () => void;
|
||||||
|
}) => {
|
||||||
|
if (triggerProps.disabled) return;
|
||||||
|
if (event.target !== event.currentTarget) return;
|
||||||
|
if (event.key === " " || event.key === "Spacebar") {
|
||||||
|
event.preventDefault?.();
|
||||||
|
if (!event.repeat) {
|
||||||
|
onPress(event as unknown as GestureResponderEvent);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}, [triggerProps.accessibilityRole, triggerProps.disabled, triggerProps.onPress]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ContextMenu open={contextMenuOpen} onOpenChange={onContextMenuOpenChange}>
|
<ContextMenu open={contextMenuOpen} onOpenChange={onContextMenuOpenChange}>
|
||||||
<ContextMenuTrigger
|
<ContextMenuTrigger
|
||||||
{...triggerProps}
|
{...triggerProps}
|
||||||
|
{...checkboxSpaceKeyProps}
|
||||||
enabledOnMobile={false}
|
enabledOnMobile={false}
|
||||||
accessibilityLabel={accessibilityLabel ?? rowAccessibilityLabel}
|
accessibilityLabel={accessibilityLabel ?? rowAccessibilityLabel}
|
||||||
highlightStyle={highlightStyle}
|
highlightStyle={highlightStyle}
|
||||||
@@ -454,6 +498,7 @@ export function SidebarWorkspaceContextMenu({
|
|||||||
onRename={onRename}
|
onRename={onRename}
|
||||||
onMarkAsRead={onMarkAsRead}
|
onMarkAsRead={onMarkAsRead}
|
||||||
onMarkAsUnread={onMarkAsUnread}
|
onMarkAsUnread={onMarkAsUnread}
|
||||||
|
onSelectWorkspace={onSelectWorkspace}
|
||||||
onArchive={onArchive}
|
onArchive={onArchive}
|
||||||
archiveLabel={archiveLabel}
|
archiveLabel={archiveLabel}
|
||||||
archiveStatus={archiveStatus}
|
archiveStatus={archiveStatus}
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import { memo, useMemo, useCallback, useState, type ReactNode } from "react";
|
import { memo, useMemo, useCallback, useState, type ReactNode } from "react";
|
||||||
import { Text, View, type ViewStyle } from "react-native";
|
import { Text, View, type ViewStyle } from "react-native";
|
||||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||||
import { CircleAlert, Folder, FolderGit2, Monitor } from "lucide-react-native";
|
import { Check, CircleAlert, Folder, FolderGit2, Monitor } from "lucide-react-native";
|
||||||
|
import { bySizing } from "@/components/ui/control-geometry";
|
||||||
import { ProjectStatusIndicator } from "@/components/sidebar/project-leading-visual";
|
import { ProjectStatusIndicator } from "@/components/sidebar/project-leading-visual";
|
||||||
import type { SidebarSurfaceBackdrop } from "@/styles/surface-backdrop";
|
import type { SidebarSurfaceBackdrop } from "@/styles/surface-backdrop";
|
||||||
import {
|
import {
|
||||||
@@ -40,19 +41,26 @@ const needsInputColorMapping = (theme: Theme) => ({
|
|||||||
color: theme.colors.surface0,
|
color: theme.colors.surface0,
|
||||||
fill: getStatusDotColor({ theme, bucket: "needs_input" }) ?? undefined,
|
fill: getStatusDotColor({ theme, bucket: "needs_input" }) ?? undefined,
|
||||||
});
|
});
|
||||||
|
const checkedIconMapping = (theme: Theme) => ({
|
||||||
|
color: theme.colors.accentForeground,
|
||||||
|
});
|
||||||
|
|
||||||
|
const ThemedCheck = withUnistyles(Check);
|
||||||
const ThemedCircleAlert = withUnistyles(CircleAlert);
|
const ThemedCircleAlert = withUnistyles(CircleAlert);
|
||||||
|
|
||||||
export function SidebarWorkspaceRowFrame({
|
export function SidebarWorkspaceRowFrame({
|
||||||
workspace,
|
workspace,
|
||||||
isDragging = false,
|
isDragging = false,
|
||||||
isEditingTitle = false,
|
isEditingTitle = false,
|
||||||
|
isSelectionMode = false,
|
||||||
children,
|
children,
|
||||||
}: {
|
}: {
|
||||||
workspace: SidebarWorkspaceEntry;
|
workspace: SidebarWorkspaceEntry;
|
||||||
isDragging?: boolean;
|
isDragging?: boolean;
|
||||||
/** Hover would fade the kebab in over the title being edited and open the hover card. */
|
/** Hover would fade the kebab in over the title being edited and open the hover card. */
|
||||||
isEditingTitle?: boolean;
|
isEditingTitle?: boolean;
|
||||||
|
/** Hover cards would cover neighbouring rows while the user clicks through a selection. */
|
||||||
|
isSelectionMode?: boolean;
|
||||||
children: (input: {
|
children: (input: {
|
||||||
isHovered: boolean;
|
isHovered: boolean;
|
||||||
contextMenuOpen: boolean;
|
contextMenuOpen: boolean;
|
||||||
@@ -80,7 +88,7 @@ export function SidebarWorkspaceRowFrame({
|
|||||||
workspace={workspace}
|
workspace={workspace}
|
||||||
prHint={workspace.prHint}
|
prHint={workspace.prHint}
|
||||||
isDragging={isDragging}
|
isDragging={isDragging}
|
||||||
disabled={contextMenuOpen || isEditingTitle}
|
disabled={contextMenuOpen || isEditingTitle || isSelectionMode}
|
||||||
>
|
>
|
||||||
{children({
|
{children({
|
||||||
isHovered: isHovered && !contextMenuOpen && !isDragging && !isEditingTitle,
|
isHovered: isHovered && !contextMenuOpen && !isDragging && !isEditingTitle,
|
||||||
@@ -102,6 +110,8 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
|
|||||||
isHovered,
|
isHovered,
|
||||||
isLoading,
|
isLoading,
|
||||||
isCreating = false,
|
isCreating = false,
|
||||||
|
isSelectionMode = false,
|
||||||
|
isBulkSelected = false,
|
||||||
shortcutNumber = null,
|
shortcutNumber = null,
|
||||||
showShortcutBadge = false,
|
showShortcutBadge = false,
|
||||||
reserveIdleStatusIndicatorSpace = true,
|
reserveIdleStatusIndicatorSpace = true,
|
||||||
@@ -119,6 +129,8 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
|
|||||||
isHovered: boolean;
|
isHovered: boolean;
|
||||||
isLoading: boolean;
|
isLoading: boolean;
|
||||||
isCreating?: boolean;
|
isCreating?: boolean;
|
||||||
|
isSelectionMode?: boolean;
|
||||||
|
isBulkSelected?: boolean;
|
||||||
shortcutNumber?: number | null;
|
shortcutNumber?: number | null;
|
||||||
showShortcutBadge?: boolean;
|
showShortcutBadge?: boolean;
|
||||||
/** Keep the empty leading slot when the workspace has no active status. */
|
/** Keep the empty leading slot when the workspace has no active status. */
|
||||||
@@ -137,33 +149,44 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
|
|||||||
const workspaceBranchTextStyle = useMemo(
|
const workspaceBranchTextStyle = useMemo(
|
||||||
() => [
|
() => [
|
||||||
styles.workspaceBranchText,
|
styles.workspaceBranchText,
|
||||||
isHovered && styles.workspaceBranchTextHovered,
|
(isHovered || isBulkSelected) && styles.workspaceBranchTextHovered,
|
||||||
isCreating && styles.workspaceBranchTextCreating,
|
isCreating && styles.workspaceBranchTextCreating,
|
||||||
],
|
],
|
||||||
[isHovered, isCreating],
|
[isHovered, isBulkSelected, isCreating],
|
||||||
);
|
);
|
||||||
|
|
||||||
|
let leadingVisual: ReactNode;
|
||||||
|
if (isSelectionMode) {
|
||||||
|
leadingVisual = (
|
||||||
|
<WorkspaceSelectionCheckbox checked={isBulkSelected} workspaceKey={workspace.workspaceKey} />
|
||||||
|
);
|
||||||
|
} else if (leadingProjectName) {
|
||||||
|
leadingVisual = (
|
||||||
|
<ProjectStatusIndicator
|
||||||
|
iconDataUri={leadingProjectIconDataUri}
|
||||||
|
displayName={leadingProjectName}
|
||||||
|
projectViewKey={workspace.projectViewKey}
|
||||||
|
statusBucket={workspace.statusBucket}
|
||||||
|
backdrop={backdrop}
|
||||||
|
loading={isLoading}
|
||||||
|
testID={`sidebar-row-project-icon-${workspace.workspaceKey}`}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
leadingVisual = (
|
||||||
|
<WorkspaceStatusIndicator
|
||||||
|
bucket={workspace.statusBucket}
|
||||||
|
workspaceKind={workspace.workspaceKind}
|
||||||
|
loading={isLoading}
|
||||||
|
reserveIdleSpace={reserveIdleStatusIndicatorSpace}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<View style={styles.workspaceRowContent}>
|
<View style={styles.workspaceRowContent}>
|
||||||
<View style={styles.workspaceRowMain}>
|
<View style={styles.workspaceRowMain}>
|
||||||
{leadingProjectName ? (
|
{leadingVisual}
|
||||||
<ProjectStatusIndicator
|
|
||||||
iconDataUri={leadingProjectIconDataUri}
|
|
||||||
displayName={leadingProjectName}
|
|
||||||
projectViewKey={workspace.projectViewKey}
|
|
||||||
statusBucket={workspace.statusBucket}
|
|
||||||
backdrop={backdrop}
|
|
||||||
loading={isLoading}
|
|
||||||
testID={`sidebar-row-project-icon-${workspace.workspaceKey}`}
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<WorkspaceStatusIndicator
|
|
||||||
bucket={workspace.statusBucket}
|
|
||||||
workspaceKind={workspace.workspaceKind}
|
|
||||||
loading={isLoading}
|
|
||||||
reserveIdleSpace={reserveIdleStatusIndicatorSpace}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
<View style={styles.workspaceContentColumn}>
|
<View style={styles.workspaceContentColumn}>
|
||||||
<View style={styles.workspaceTitleRow}>
|
<View style={styles.workspaceTitleRow}>
|
||||||
{titleEditor ? (
|
{titleEditor ? (
|
||||||
@@ -191,7 +214,7 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
|
|||||||
/>
|
/>
|
||||||
</View>
|
</View>
|
||||||
</View>
|
</View>
|
||||||
{showShortcutBadge && shortcutNumber !== null ? (
|
{!isSelectionMode && showShortcutBadge && shortcutNumber !== null ? (
|
||||||
<View style={styles.shortcutBadgeOverlay} pointerEvents="none">
|
<View style={styles.shortcutBadgeOverlay} pointerEvents="none">
|
||||||
<SidebarWorkspaceShortcutBadge number={shortcutNumber} />
|
<SidebarWorkspaceShortcutBadge number={shortcutNumber} />
|
||||||
</View>
|
</View>
|
||||||
@@ -200,6 +223,22 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
function WorkspaceSelectionCheckbox({
|
||||||
|
checked,
|
||||||
|
workspaceKey,
|
||||||
|
}: {
|
||||||
|
checked: boolean;
|
||||||
|
workspaceKey: string;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<View style={styles.workspaceStatusDot} testID={`sidebar-workspace-checkbox-${workspaceKey}`}>
|
||||||
|
<View style={checked ? styles.selectionCheckboxChecked : styles.selectionCheckbox}>
|
||||||
|
{checked ? <ThemedCheck size={11} strokeWidth={2.5} uniProps={checkedIconMapping} /> : null}
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function WorkspaceStatusIndicator({
|
function WorkspaceStatusIndicator({
|
||||||
bucket,
|
bucket,
|
||||||
workspaceKind,
|
workspaceKind,
|
||||||
@@ -382,6 +421,7 @@ export function resolveTrailingActionVisibility({
|
|||||||
isHovered,
|
isHovered,
|
||||||
isTouchPlatform,
|
isTouchPlatform,
|
||||||
showShortcut,
|
showShortcut,
|
||||||
|
isSelectionMode = false,
|
||||||
}: {
|
}: {
|
||||||
workspace: SidebarWorkspaceEntry;
|
workspace: SidebarWorkspaceEntry;
|
||||||
trailing: SidebarWorkspaceTrailing;
|
trailing: SidebarWorkspaceTrailing;
|
||||||
@@ -389,6 +429,7 @@ export function resolveTrailingActionVisibility({
|
|||||||
isHovered: boolean;
|
isHovered: boolean;
|
||||||
isTouchPlatform: boolean;
|
isTouchPlatform: boolean;
|
||||||
showShortcut: boolean;
|
showShortcut: boolean;
|
||||||
|
isSelectionMode?: boolean;
|
||||||
}): {
|
}): {
|
||||||
trailingPresentation: SidebarWorkspaceTrailingPresentation;
|
trailingPresentation: SidebarWorkspaceTrailingPresentation;
|
||||||
showKebab: boolean;
|
showKebab: boolean;
|
||||||
@@ -398,10 +439,11 @@ export function resolveTrailingActionVisibility({
|
|||||||
reserveSlotWidth: boolean;
|
reserveSlotWidth: boolean;
|
||||||
} {
|
} {
|
||||||
const hasTrailing = hasSidebarWorkspaceTrailing({ workspace, trailing });
|
const hasTrailing = hasSidebarWorkspaceTrailing({ workspace, trailing });
|
||||||
const showKebab = Boolean(hasArchiveAction && (isHovered || isTouchPlatform)) && !showShortcut;
|
const allowRowActions = hasArchiveAction && !isSelectionMode;
|
||||||
|
const showKebab = Boolean(allowRowActions && (isHovered || isTouchPlatform)) && !showShortcut;
|
||||||
// Touch permanently replaces the stats with the menu. Only temporary shortcut hints
|
// Touch permanently replaces the stats with the menu. Only temporary shortcut hints
|
||||||
// conceal content while retaining its width, so desktop rows do not shift.
|
// conceal content while retaining its width, so desktop rows do not shift.
|
||||||
const hasContent = hasTrailing && !(hasArchiveAction && isTouchPlatform);
|
const hasContent = hasTrailing && !(allowRowActions && isTouchPlatform);
|
||||||
let trailingPresentation: SidebarWorkspaceTrailingPresentation = "absent";
|
let trailingPresentation: SidebarWorkspaceTrailingPresentation = "absent";
|
||||||
if (hasContent) trailingPresentation = showShortcut ? "hidden" : "visible";
|
if (hasContent) trailingPresentation = showShortcut ? "hidden" : "visible";
|
||||||
return {
|
return {
|
||||||
@@ -414,12 +456,12 @@ export function resolveTrailingActionVisibility({
|
|||||||
// row — over an unhovered one the gradient fades to the wrong color. That is also why
|
// row — over an unhovered one the gradient fades to the wrong color. That is also why
|
||||||
// touch, which shows the kebab without ever hovering, never gets one.
|
// touch, which shows the kebab without ever hovering, never gets one.
|
||||||
showScrim: showKebab && isHovered,
|
showScrim: showKebab && isHovered,
|
||||||
renderSlot: hasArchiveAction || hasTrailing,
|
renderSlot: allowRowActions || hasTrailing,
|
||||||
// The slot only holds width for something that permanently sits in it. Trailing content
|
// The slot only holds width for something that permanently sits in it. Trailing content
|
||||||
// does; the kebab only does on touch, where there is no hover for it to appear on and so
|
// does; the kebab only does on touch, where there is no hover for it to appear on and so
|
||||||
// no scrim to let it overlay the title. Everywhere else the width goes back to the title
|
// no scrim to let it overlay the title. Everywhere else the width goes back to the title
|
||||||
// and the kebab fades in over its tail.
|
// and the kebab fades in over its tail.
|
||||||
reserveSlotWidth: hasContent || (hasArchiveAction && isTouchPlatform),
|
reserveSlotWidth: hasContent || (allowRowActions && isTouchPlatform),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -536,6 +578,25 @@ const styles = StyleSheet.create((theme) => ({
|
|||||||
alignItems: "center",
|
alignItems: "center",
|
||||||
justifyContent: "center",
|
justifyContent: "center",
|
||||||
},
|
},
|
||||||
|
selectionCheckbox: {
|
||||||
|
width: bySizing({ touch: 18, pointer: 15 }),
|
||||||
|
height: bySizing({ touch: 18, pointer: 15 }),
|
||||||
|
borderRadius: theme.borderRadius.sm,
|
||||||
|
borderWidth: 1.5,
|
||||||
|
borderColor: theme.colors.borderAccent,
|
||||||
|
alignItems: "center",
|
||||||
|
justifyContent: "center",
|
||||||
|
},
|
||||||
|
selectionCheckboxChecked: {
|
||||||
|
width: bySizing({ touch: 18, pointer: 15 }),
|
||||||
|
height: bySizing({ touch: 18, pointer: 15 }),
|
||||||
|
borderRadius: theme.borderRadius.sm,
|
||||||
|
borderWidth: 1.5,
|
||||||
|
borderColor: theme.colors.accent,
|
||||||
|
backgroundColor: theme.colors.accent,
|
||||||
|
alignItems: "center",
|
||||||
|
justifyContent: "center",
|
||||||
|
},
|
||||||
statusDotOverlay: {
|
statusDotOverlay: {
|
||||||
position: "absolute",
|
position: "absolute",
|
||||||
right: 0,
|
right: 0,
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import Animated, { FadeIn, FadeOut } from "react-native-reanimated";
|
|||||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||||
import { SPACING, type Theme } from "@/styles/theme";
|
import { SPACING, type Theme } from "@/styles/theme";
|
||||||
|
import { CONTROL_HEIGHTS, mapLayout } from "@/components/ui/control-geometry";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||||
import { isWeb } from "@/constants/platform";
|
import { isWeb } from "@/constants/platform";
|
||||||
@@ -28,10 +29,16 @@ import {
|
|||||||
} from "@/constants/layout";
|
} from "@/constants/layout";
|
||||||
|
|
||||||
export type ToastVariant = "default" | "info" | "success" | "warning" | "error";
|
export type ToastVariant = "default" | "info" | "success" | "warning" | "error";
|
||||||
|
/**
|
||||||
|
* `action` tightens vertical and trailing insets around `size="sm"` pill controls and uses a
|
||||||
|
* concentric corner radius (`controlHeight / 2 + inset`) so buttons nest evenly in the shell.
|
||||||
|
*/
|
||||||
|
export type ToastLayout = "default" | "action";
|
||||||
|
|
||||||
export interface ToastShowOptions {
|
export interface ToastShowOptions {
|
||||||
icon?: ReactNode;
|
icon?: ReactNode;
|
||||||
variant?: ToastVariant;
|
variant?: ToastVariant;
|
||||||
|
layout?: ToastLayout;
|
||||||
durationMs?: number | null;
|
durationMs?: number | null;
|
||||||
nativeAndroid?: boolean;
|
nativeAndroid?: boolean;
|
||||||
testID?: string;
|
testID?: string;
|
||||||
@@ -45,6 +52,7 @@ export interface ToastState {
|
|||||||
nativeMessage: string | null;
|
nativeMessage: string | null;
|
||||||
icon?: ReactNode;
|
icon?: ReactNode;
|
||||||
variant: ToastVariant;
|
variant: ToastVariant;
|
||||||
|
layout?: ToastLayout;
|
||||||
durationMs: number | null;
|
durationMs: number | null;
|
||||||
testID?: string;
|
testID?: string;
|
||||||
onDismiss?: () => void;
|
onDismiss?: () => void;
|
||||||
@@ -73,6 +81,11 @@ const TOAST_MAX_WIDTH = 480;
|
|||||||
/** How long a toast takes to fade in or out. */
|
/** How long a toast takes to fade in or out. */
|
||||||
export const TOAST_FADE_MS = 140;
|
export const TOAST_FADE_MS = 140;
|
||||||
const SIDEBAR_TOAST_INSET = SPACING[2];
|
const SIDEBAR_TOAST_INSET = SPACING[2];
|
||||||
|
const ACTION_TOAST_INSET = SPACING[1.5];
|
||||||
|
const ACTION_TOAST_RADIUS = mapLayout(
|
||||||
|
CONTROL_HEIGHTS.sm,
|
||||||
|
(height) => height / 2 + ACTION_TOAST_INSET,
|
||||||
|
);
|
||||||
const toastEntering = FadeIn.duration(TOAST_FADE_MS);
|
const toastEntering = FadeIn.duration(TOAST_FADE_MS);
|
||||||
const toastExiting = FadeOut.duration(TOAST_FADE_MS);
|
const toastExiting = FadeOut.duration(TOAST_FADE_MS);
|
||||||
const ThemedCheckCircle = withUnistyles(CheckCircle2);
|
const ThemedCheckCircle = withUnistyles(CheckCircle2);
|
||||||
@@ -136,6 +149,7 @@ export function useToastHost(): {
|
|||||||
nativeMessage,
|
nativeMessage,
|
||||||
icon: options?.icon,
|
icon: options?.icon,
|
||||||
variant,
|
variant,
|
||||||
|
layout: options?.layout,
|
||||||
durationMs,
|
durationMs,
|
||||||
testID: options?.testID,
|
testID: options?.testID,
|
||||||
onDismiss: options?.onDismiss,
|
onDismiss: options?.onDismiss,
|
||||||
@@ -163,11 +177,14 @@ export function useToastHost(): {
|
|||||||
|
|
||||||
export function ToastViewport({
|
export function ToastViewport({
|
||||||
toast,
|
toast,
|
||||||
|
persistentToast = null,
|
||||||
onDismiss,
|
onDismiss,
|
||||||
placement = "app-shell",
|
placement = "app-shell",
|
||||||
onBottomCoverageChange,
|
onBottomCoverageChange,
|
||||||
}: {
|
}: {
|
||||||
toast: ToastState | null;
|
toast: ToastState | null;
|
||||||
|
/** Sidebar placement: persistent bar (such as select mode) that stays visible below transient toasts. */
|
||||||
|
persistentToast?: ToastState | null;
|
||||||
/** Called with the ID of the toast that timed out. */
|
/** Called with the ID of the toast that timed out. */
|
||||||
onDismiss: (id: number) => void;
|
onDismiss: (id: number) => void;
|
||||||
placement?: ToastViewportPlacement;
|
placement?: ToastViewportPlacement;
|
||||||
@@ -232,7 +249,10 @@ export function ToastViewport({
|
|||||||
|
|
||||||
const handleSidebarLayout = useCallback(
|
const handleSidebarLayout = useCallback(
|
||||||
(event: LayoutChangeEvent) => {
|
(event: LayoutChangeEvent) => {
|
||||||
onBottomCoverageChange?.(event.nativeEvent.layout.height + SIDEBAR_TOAST_INSET);
|
const height = event.nativeEvent.layout.height;
|
||||||
|
if (height > 0) {
|
||||||
|
onBottomCoverageChange?.(height + SIDEBAR_TOAST_INSET);
|
||||||
|
}
|
||||||
},
|
},
|
||||||
[onBottomCoverageChange],
|
[onBottomCoverageChange],
|
||||||
);
|
);
|
||||||
@@ -243,28 +263,41 @@ export function ToastViewport({
|
|||||||
const topOffset =
|
const topOffset =
|
||||||
placement === "app-shell" ? insets.top + headerTopPadding + headerHeight : panelClearance;
|
placement === "app-shell" ? insets.top + headerTopPadding + headerHeight : panelClearance;
|
||||||
|
|
||||||
|
if (placement === "sidebar") {
|
||||||
|
return (
|
||||||
|
<View
|
||||||
|
style={animatedStyles.sidebarContainer}
|
||||||
|
pointerEvents="box-none"
|
||||||
|
collapsable={false}
|
||||||
|
onLayout={handleSidebarLayout}
|
||||||
|
>
|
||||||
|
<SidebarToastSlot
|
||||||
|
toast={toast}
|
||||||
|
onPointerEnter={pauseDismiss}
|
||||||
|
onPointerLeave={resumeDismiss}
|
||||||
|
/>
|
||||||
|
<SidebarToastSlot
|
||||||
|
toast={persistentToast}
|
||||||
|
onPointerEnter={noopDismiss}
|
||||||
|
onPointerLeave={noopDismiss}
|
||||||
|
/>
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// Keep the bottom anchor and its contents together while the native exit retains the view.
|
// Keep the bottom anchor and its contents together while the native exit retains the view.
|
||||||
const content = toast ? (
|
const content = toast ? (
|
||||||
<Animated.View
|
<Animated.View
|
||||||
entering={toastEntering}
|
entering={toastEntering}
|
||||||
exiting={toastExiting}
|
exiting={toastExiting}
|
||||||
style={
|
style={[
|
||||||
placement === "sidebar"
|
animatedStyles.container,
|
||||||
? animatedStyles.sidebarContainer
|
{ top: topOffset + (placement === "app-shell" ? SPACING[2] : SPACING[3]) },
|
||||||
: [
|
]}
|
||||||
animatedStyles.container,
|
|
||||||
{ top: topOffset + (placement === "app-shell" ? SPACING[2] : SPACING[3]) },
|
|
||||||
]
|
|
||||||
}
|
|
||||||
pointerEvents="box-none"
|
pointerEvents="box-none"
|
||||||
collapsable={false}
|
collapsable={false}
|
||||||
onLayout={placement === "sidebar" ? handleSidebarLayout : undefined}
|
|
||||||
>
|
>
|
||||||
<View
|
<View style={styles.widthBoundary} pointerEvents="box-none" collapsable={false}>
|
||||||
style={placement === "sidebar" ? styles.sidebarWidthBoundary : styles.widthBoundary}
|
|
||||||
pointerEvents="box-none"
|
|
||||||
collapsable={false}
|
|
||||||
>
|
|
||||||
<View
|
<View
|
||||||
style={animatedStyles.surface}
|
style={animatedStyles.surface}
|
||||||
testID={toast.testID ?? "app-toast"}
|
testID={toast.testID ?? "app-toast"}
|
||||||
@@ -283,6 +316,35 @@ export function ToastViewport({
|
|||||||
return placement === "panel" ? <FloatingHeaderOverlay>{content}</FloatingHeaderOverlay> : content;
|
return placement === "panel" ? <FloatingHeaderOverlay>{content}</FloatingHeaderOverlay> : content;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function SidebarToastSlot({
|
||||||
|
toast,
|
||||||
|
onPointerEnter,
|
||||||
|
onPointerLeave,
|
||||||
|
}: {
|
||||||
|
toast: ToastState | null;
|
||||||
|
onPointerEnter: () => void;
|
||||||
|
onPointerLeave: () => void;
|
||||||
|
}) {
|
||||||
|
if (!toast) return null;
|
||||||
|
return (
|
||||||
|
<Animated.View
|
||||||
|
entering={toastEntering}
|
||||||
|
exiting={toastExiting}
|
||||||
|
style={styles.sidebarWidthBoundary}
|
||||||
|
pointerEvents="box-none"
|
||||||
|
collapsable={false}
|
||||||
|
>
|
||||||
|
<View
|
||||||
|
style={animatedStyles.surface}
|
||||||
|
testID={toast.testID ?? "app-toast"}
|
||||||
|
accessibilityRole="alert"
|
||||||
|
>
|
||||||
|
<ToastCard toast={toast} onPointerEnter={onPointerEnter} onPointerLeave={onPointerLeave} />
|
||||||
|
</View>
|
||||||
|
</Animated.View>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function ToastCard({
|
function ToastCard({
|
||||||
toast,
|
toast,
|
||||||
onPointerEnter,
|
onPointerEnter,
|
||||||
@@ -310,6 +372,7 @@ function ToastCard({
|
|||||||
onPointerLeave={onPointerLeave}
|
onPointerLeave={onPointerLeave}
|
||||||
style={[
|
style={[
|
||||||
styles.toast,
|
styles.toast,
|
||||||
|
toast.layout === "action" ? styles.toastAction : null,
|
||||||
toast.variant === "info" ? styles.toastInfo : null,
|
toast.variant === "info" ? styles.toastInfo : null,
|
||||||
toast.variant === "warning" ? styles.toastWarning : null,
|
toast.variant === "warning" ? styles.toastWarning : null,
|
||||||
toast.variant === "error" ? styles.toastError : null,
|
toast.variant === "error" ? styles.toastError : null,
|
||||||
@@ -344,6 +407,7 @@ const animatedStyles = NativeStyleSheet.create({
|
|||||||
bottom: SIDEBAR_TOAST_INSET,
|
bottom: SIDEBAR_TOAST_INSET,
|
||||||
zIndex: OVERLAY_Z.toast,
|
zIndex: OVERLAY_Z.toast,
|
||||||
alignItems: "center",
|
alignItems: "center",
|
||||||
|
gap: SIDEBAR_TOAST_INSET,
|
||||||
},
|
},
|
||||||
surface: { alignSelf: "center", maxWidth: "100%" },
|
surface: { alignSelf: "center", maxWidth: "100%" },
|
||||||
});
|
});
|
||||||
@@ -372,6 +436,12 @@ const styles = StyleSheet.create((theme) => ({
|
|||||||
paddingHorizontal: theme.spacing[3],
|
paddingHorizontal: theme.spacing[3],
|
||||||
...theme.shadow.md,
|
...theme.shadow.md,
|
||||||
},
|
},
|
||||||
|
toastAction: {
|
||||||
|
borderRadius: ACTION_TOAST_RADIUS,
|
||||||
|
paddingVertical: theme.spacing[1.5],
|
||||||
|
paddingLeft: theme.spacing[3.5],
|
||||||
|
paddingRight: theme.spacing[1.5],
|
||||||
|
},
|
||||||
toastInfo: {
|
toastInfo: {
|
||||||
borderColor: theme.colors.palette.blue[300],
|
borderColor: theme.colors.palette.blue[300],
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -25,7 +25,6 @@ import {
|
|||||||
} from "react-native";
|
} from "react-native";
|
||||||
import { createPortal } from "react-dom";
|
import { createPortal } from "react-dom";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
|
||||||
import type { EditingTextInputHandle } from "@/components/ui/text-input";
|
import type { EditingTextInputHandle } from "@/components/ui/text-input";
|
||||||
import { StyleSheet, useUnistyles } from "react-native-unistyles";
|
import { StyleSheet, useUnistyles } from "react-native-unistyles";
|
||||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||||
@@ -146,6 +145,8 @@ export interface ComboboxProps {
|
|||||||
/** When true, selecting an option does not close the picker (multi-select mode). */
|
/** When true, selecting an option does not close the picker (multi-select mode). */
|
||||||
keepOpenOnSelect?: boolean;
|
keepOpenOnSelect?: boolean;
|
||||||
anchorRef: React.RefObject<View | null>;
|
anchorRef: React.RefObject<View | null>;
|
||||||
|
/** Where focus goes when the picker closes. Defaults to whatever had focus when it opened. */
|
||||||
|
restoreFocusRef?: React.RefObject<unknown>;
|
||||||
children?: ReactNode;
|
children?: ReactNode;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1138,31 +1139,22 @@ function MobileComboboxSheet(props: MobileBodyProps): ReactElement {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Rendered on the far side of the sheet's portal so it clears the screen's bottom inset, not the
|
* Rendered on the far side of the sheet's portal so `SheetVisibleFrame` clears the screen's
|
||||||
* one left where the combobox was opened: inside a sheet tab, none is.
|
* bottom inset in lockstep with the keyboard, not the inset left where the combobox was opened.
|
||||||
*/
|
*/
|
||||||
function ComboboxSheetFrame({ footer, children }: { footer?: ReactNode; children: ReactNode }) {
|
function ComboboxSheetFrame({ footer, children }: { footer?: ReactNode; children: ReactNode }) {
|
||||||
const { bottom: safeAreaBottom } = useSafeAreaInsets();
|
|
||||||
const frameStyle = useMemo(
|
|
||||||
() => [styles.mobileSheetFrame, { paddingBottom: footer ? 0 : safeAreaBottom }],
|
|
||||||
[footer, safeAreaBottom],
|
|
||||||
);
|
|
||||||
const footerStyle = useMemo(
|
|
||||||
() => [styles.footer, { paddingBottom: safeAreaBottom }],
|
|
||||||
[safeAreaBottom],
|
|
||||||
);
|
|
||||||
const footerView = useMemo(
|
const footerView = useMemo(
|
||||||
() =>
|
() =>
|
||||||
footer ? (
|
footer ? (
|
||||||
<View style={footerStyle} dataSet={FOOTER_DATASET}>
|
<View style={styles.footer} dataSet={FOOTER_DATASET}>
|
||||||
{footer}
|
{footer}
|
||||||
</View>
|
</View>
|
||||||
) : undefined,
|
) : undefined,
|
||||||
[footer, footerStyle],
|
[footer],
|
||||||
);
|
);
|
||||||
return (
|
return (
|
||||||
<SheetVisibleFrame footer={footerView}>
|
<SheetVisibleFrame footer={footerView} safeAreaInset="frame">
|
||||||
<View style={frameStyle}>{children}</View>
|
<View style={styles.mobileSheetFrame}>{children}</View>
|
||||||
</SheetVisibleFrame>
|
</SheetVisibleFrame>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1437,6 +1429,7 @@ export function Combobox({
|
|||||||
footer,
|
footer,
|
||||||
keepOpenOnSelect = false,
|
keepOpenOnSelect = false,
|
||||||
anchorRef,
|
anchorRef,
|
||||||
|
restoreFocusRef,
|
||||||
children,
|
children,
|
||||||
}: ComboboxProps): ReactElement | null {
|
}: ComboboxProps): ReactElement | null {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
@@ -1728,6 +1721,7 @@ export function Combobox({
|
|||||||
layer: floatingLayer,
|
layer: floatingLayer,
|
||||||
keys: ["Escape", "Enter", "ArrowUp", "ArrowDown"],
|
keys: ["Escape", "Enter", "ArrowUp", "ArrowDown"],
|
||||||
onKeyDown: (event) => (isDesktopKey(event.key) ? handleDesktopKey(event.key, event) : false),
|
onKeyDown: (event) => (isDesktopKey(event.key) ? handleDesktopKey(event.key, event) : false),
|
||||||
|
restoreFocusRef,
|
||||||
});
|
});
|
||||||
|
|
||||||
const effectiveSearchPlaceholder = searchPlaceholder ?? resolvedPlaceholder;
|
const effectiveSearchPlaceholder = searchPlaceholder ?? resolvedPlaceholder;
|
||||||
|
|||||||
@@ -0,0 +1,106 @@
|
|||||||
|
import React, { act, Children, useCallback, type ReactNode } from "react";
|
||||||
|
import { createRoot, type Root } from "react-dom/client";
|
||||||
|
import { afterEach, describe, expect, it } from "vitest";
|
||||||
|
import { useContentDrag, withContentDrag } from "./content-drag";
|
||||||
|
|
||||||
|
let root: Root | null = null;
|
||||||
|
let container: HTMLDivElement | null = null;
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
act(() => root?.unmount());
|
||||||
|
container?.remove();
|
||||||
|
root = null;
|
||||||
|
container = null;
|
||||||
|
});
|
||||||
|
|
||||||
|
interface FakeScrollProps {
|
||||||
|
scrollEnabled?: boolean;
|
||||||
|
children?: ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Stands in for a scroll view: it reports the props a native scroll view would act on. */
|
||||||
|
function FakeScroll({ scrollEnabled, children }: FakeScrollProps) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-testid="scroll"
|
||||||
|
data-scroll-enabled={String(scrollEnabled)}
|
||||||
|
data-child-count={Children.toArray(children).length}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const DragHostScroll = withContentDrag<FakeScrollProps, unknown>(FakeScroll);
|
||||||
|
|
||||||
|
/** A row that holds a drag the way a draggable list does: active from press until release. */
|
||||||
|
function DragRow() {
|
||||||
|
const { setActive } = useContentDrag();
|
||||||
|
const arm = useCallback(() => setActive(true), [setActive]);
|
||||||
|
const release = useCallback(() => setActive(false), [setActive]);
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<button type="button" data-testid="arm" onClick={arm} />
|
||||||
|
<button type="button" data-testid="release" onClick={release} />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function mount(node: React.ReactElement) {
|
||||||
|
container = document.createElement("div");
|
||||||
|
document.body.appendChild(container);
|
||||||
|
root = createRoot(container);
|
||||||
|
act(() => root?.render(node));
|
||||||
|
}
|
||||||
|
|
||||||
|
function scroll(): HTMLElement {
|
||||||
|
const found = document.querySelector('[data-testid="scroll"]');
|
||||||
|
if (!(found instanceof HTMLElement)) throw new Error("No scroll view rendered");
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
|
||||||
|
function press(testID: string) {
|
||||||
|
const button = document.querySelector(`[data-testid="${testID}"]`);
|
||||||
|
if (!(button instanceof HTMLElement)) throw new Error(`No ${testID}`);
|
||||||
|
act(() => button.click());
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("withContentDrag", () => {
|
||||||
|
it("stops the scroll while a child drag holds the touch, and resumes after", () => {
|
||||||
|
mount(
|
||||||
|
<DragHostScroll>
|
||||||
|
<DragRow />
|
||||||
|
</DragHostScroll>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(scroll().dataset.scrollEnabled).toBe("true");
|
||||||
|
press("arm");
|
||||||
|
expect(scroll().dataset.scrollEnabled).toBe("false");
|
||||||
|
press("release");
|
||||||
|
expect(scroll().dataset.scrollEnabled).toBe("true");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps a scroll view the caller disabled disabled after the drag", () => {
|
||||||
|
mount(
|
||||||
|
<DragHostScroll scrollEnabled={false}>
|
||||||
|
<DragRow />
|
||||||
|
</DragHostScroll>,
|
||||||
|
);
|
||||||
|
|
||||||
|
press("arm");
|
||||||
|
press("release");
|
||||||
|
expect(scroll().dataset.scrollEnabled).toBe("false");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("passes the children through as given, so sticky header indices still count them", () => {
|
||||||
|
mount(
|
||||||
|
<DragHostScroll>
|
||||||
|
<div>Intro</div>
|
||||||
|
<div>Section header</div>
|
||||||
|
<DragRow />
|
||||||
|
</DragHostScroll>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(scroll().dataset.childCount).toBe("3");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
import {
|
||||||
|
createContext,
|
||||||
|
forwardRef,
|
||||||
|
useContext,
|
||||||
|
useMemo,
|
||||||
|
useState,
|
||||||
|
type ComponentType,
|
||||||
|
type Ref,
|
||||||
|
} from "react";
|
||||||
|
import type { AttachSheetContentDrag } from "./bottom-sheet-scope";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What a child that drags inside a scroll view needs to keep the touch: `setActive(true)` stops
|
||||||
|
* the scroll until the drag ends, so the scroll view cannot take the finger once the drag has
|
||||||
|
* armed. Inside a sheet the child also registers its drag gesture through `attach` so the sheet's
|
||||||
|
* pan waits for it; outside a sheet there is no `attach`. Outside any scroll view that hosts
|
||||||
|
* content drags, `setActive` does nothing.
|
||||||
|
*/
|
||||||
|
export interface ContentDrag {
|
||||||
|
attach: AttachSheetContentDrag | undefined;
|
||||||
|
setActive: (active: boolean) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ContentDragContext = createContext<ContentDrag | null>(null);
|
||||||
|
|
||||||
|
const NO_CONTENT_DRAG: ContentDrag = { attach: undefined, setActive: () => {} };
|
||||||
|
|
||||||
|
export function useContentDrag(): ContentDrag {
|
||||||
|
return useContext(ContentDragContext) ?? NO_CONTENT_DRAG;
|
||||||
|
}
|
||||||
|
|
||||||
|
function useNoAttach(): AttachSheetContentDrag | undefined {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Makes a scroll view host content drags: it stops scrolling while a child drag is active. Without
|
||||||
|
* it, a vertical drag in a row of a scrolling page is taken by the page scroll once the finger
|
||||||
|
* moves past the touch slop, before the row's drag gesture can activate. A sheet's scroll view
|
||||||
|
* passes `useAttach` so its children can also register their gesture with the sheet.
|
||||||
|
*
|
||||||
|
* The context wraps the scroll view rather than its content, so the scroll view receives its
|
||||||
|
* children as given: `stickyHeaderIndices` counts them.
|
||||||
|
*/
|
||||||
|
export function withContentDrag<P extends { scrollEnabled?: boolean }, T>(
|
||||||
|
Scroll: ComponentType<P & { ref?: Ref<T> }>,
|
||||||
|
useAttach: () => AttachSheetContentDrag | undefined = useNoAttach,
|
||||||
|
) {
|
||||||
|
return forwardRef<T, P>(function ContentDragScrollView(props, ref) {
|
||||||
|
const attach = useAttach();
|
||||||
|
const [dragging, setDragging] = useState(false);
|
||||||
|
const contentDrag = useMemo(() => ({ attach, setActive: setDragging }), [attach]);
|
||||||
|
// Overriding one prop of `P` keeps it a `P`; TypeScript cannot prove that for a generic.
|
||||||
|
const scrollProps = {
|
||||||
|
...props,
|
||||||
|
scrollEnabled: !dragging && props.scrollEnabled !== false,
|
||||||
|
} as P;
|
||||||
|
return (
|
||||||
|
<ContentDragContext.Provider value={contentDrag}>
|
||||||
|
<Scroll {...scrollProps} ref={ref} />
|
||||||
|
</ContentDragContext.Provider>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -150,17 +150,17 @@ export function ContextMenuTrigger({
|
|||||||
);
|
);
|
||||||
|
|
||||||
const propsOnLongPress = props.onLongPress;
|
const propsOnLongPress = props.onLongPress;
|
||||||
const handleLongPress = useCallback(
|
const handleNativeLongPress = useCallback(
|
||||||
(event: GestureResponderEvent) => {
|
(event: GestureResponderEvent) => {
|
||||||
if (isWeb) {
|
|
||||||
propsOnLongPress?.(event);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
openAtEvent(event);
|
openAtEvent(event);
|
||||||
propsOnLongPress?.(event);
|
propsOnLongPress?.(event);
|
||||||
},
|
},
|
||||||
[propsOnLongPress, openAtEvent],
|
[propsOnLongPress, openAtEvent],
|
||||||
);
|
);
|
||||||
|
// The web menu opens on right-click, not long press. Any onLongPress makes react-native-web cancel
|
||||||
|
// the click that ends a held press, and only a later press-in clears that, which Ctrl+click never
|
||||||
|
// gets. So on web, pass the caller's onLongPress through and nothing else.
|
||||||
|
const handleLongPress = isWeb ? propsOnLongPress : handleNativeLongPress;
|
||||||
|
|
||||||
const handleContextMenu = useCallback(
|
const handleContextMenu = useCallback(
|
||||||
(event: unknown) => {
|
(event: unknown) => {
|
||||||
|
|||||||
@@ -212,6 +212,6 @@ export function useIsolatedBottomSheetVisibility({
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export { SheetVisibleFrame } from "./visible-frame";
|
export { SheetVisibleFrame, useBottomSheetSafeAreaPaddingStyle } from "./visible-frame";
|
||||||
export { systemBackPress } from "./back-press";
|
export { systemBackPress } from "./back-press";
|
||||||
export { SheetHostScope } from "./host-scope";
|
export { SheetHostScope } from "./host-scope";
|
||||||
|
|||||||
+118
-1
@@ -1,5 +1,8 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
import { getBottomSheetVisibleContentHeight } from "./visible-frame-layout";
|
import {
|
||||||
|
getBottomSheetSafeAreaPaddingBottom,
|
||||||
|
getBottomSheetVisibleContentHeight,
|
||||||
|
} from "./visible-frame-layout";
|
||||||
|
|
||||||
describe("getBottomSheetVisibleContentHeight", () => {
|
describe("getBottomSheetVisibleContentHeight", () => {
|
||||||
it("stops subtracting the retained keyboard height after the keyboard hides", () => {
|
it("stops subtracting the retained keyboard height after the keyboard hides", () => {
|
||||||
@@ -13,6 +16,120 @@ describe("getBottomSheetVisibleContentHeight", () => {
|
|||||||
expect(getBottomSheetVisibleContentHeight({ ...layout, isKeyboardVisible: true })).toBe(418);
|
expect(getBottomSheetVisibleContentHeight({ ...layout, isKeyboardVisible: true })).toBe(418);
|
||||||
expect(getBottomSheetVisibleContentHeight({ ...layout, isKeyboardVisible: false })).toBe(762);
|
expect(getBottomSheetVisibleContentHeight({ ...layout, isKeyboardVisible: false })).toBe(762);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("ignores non-positive keyboard heights", () => {
|
||||||
|
const layout = {
|
||||||
|
containerHeight: 874,
|
||||||
|
contentPosition: 88,
|
||||||
|
handleHeight: 24,
|
||||||
|
keyboardHeight: -10,
|
||||||
|
isKeyboardVisible: true,
|
||||||
|
};
|
||||||
|
|
||||||
|
expect(getBottomSheetVisibleContentHeight(layout)).toBe(762);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("getBottomSheetSafeAreaPaddingBottom", () => {
|
||||||
|
it("keeps full safe-area clearance while the keyboard is hidden, even with retained keyboard height", () => {
|
||||||
|
expect(
|
||||||
|
getBottomSheetSafeAreaPaddingBottom({
|
||||||
|
keyboardHeight: 344,
|
||||||
|
isKeyboardVisible: false,
|
||||||
|
safeAreaBottom: 48,
|
||||||
|
}),
|
||||||
|
).toBe(48);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps full safe-area clearance during Gorhom's first-open frame before heightWithinContainer is populated", () => {
|
||||||
|
expect(
|
||||||
|
getBottomSheetSafeAreaPaddingBottom({
|
||||||
|
keyboardHeight: 0,
|
||||||
|
isKeyboardVisible: true,
|
||||||
|
safeAreaBottom: 48,
|
||||||
|
}),
|
||||||
|
).toBe(48);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("drops safe-area clearance to 0 when the keyboard height covers the bottom safe area", () => {
|
||||||
|
expect(
|
||||||
|
getBottomSheetSafeAreaPaddingBottom({
|
||||||
|
keyboardHeight: 344,
|
||||||
|
isKeyboardVisible: true,
|
||||||
|
safeAreaBottom: 48,
|
||||||
|
}),
|
||||||
|
).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("preserves remaining safe-area clearance when keyboard height is smaller than the bottom inset", () => {
|
||||||
|
expect(
|
||||||
|
getBottomSheetSafeAreaPaddingBottom({
|
||||||
|
keyboardHeight: 20,
|
||||||
|
isKeyboardVisible: true,
|
||||||
|
safeAreaBottom: 48,
|
||||||
|
}),
|
||||||
|
).toBe(28);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns 0 when there is no bottom safe-area inset", () => {
|
||||||
|
expect(
|
||||||
|
getBottomSheetSafeAreaPaddingBottom({
|
||||||
|
keyboardHeight: 0,
|
||||||
|
isKeyboardVisible: false,
|
||||||
|
safeAreaBottom: 0,
|
||||||
|
}),
|
||||||
|
).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("holds the invariant that visible frame height + paddingBottom never places the footer inside the bottom safe area across keyboard open/close transitions", () => {
|
||||||
|
const containerHeight = 1608;
|
||||||
|
const contentPosition = 161;
|
||||||
|
const handleHeight = 48;
|
||||||
|
const safeAreaBottom = 96;
|
||||||
|
const restingContentBottom = containerHeight - safeAreaBottom;
|
||||||
|
|
||||||
|
// Sequence matching real Android/iOS Gorhom keyboard transitions:
|
||||||
|
// 1. Resting closed
|
||||||
|
// 2. First open intermediate state (status=SHOWN before heightWithinContainer updates)
|
||||||
|
// 3. Open settled (heightWithinContainer = 598)
|
||||||
|
// 4. Close (status=HIDDEN while heightWithinContainer retains 598)
|
||||||
|
// 5. Partial accessory bar (heightWithinContainer = 40 < safeAreaBottom)
|
||||||
|
const transitions = [
|
||||||
|
{ isKeyboardVisible: false, keyboardHeight: 0, expectedContentBottom: restingContentBottom },
|
||||||
|
{ isKeyboardVisible: true, keyboardHeight: 0, expectedContentBottom: restingContentBottom },
|
||||||
|
{
|
||||||
|
isKeyboardVisible: true,
|
||||||
|
keyboardHeight: 598,
|
||||||
|
expectedContentBottom: containerHeight - 598,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
isKeyboardVisible: false,
|
||||||
|
keyboardHeight: 598,
|
||||||
|
expectedContentBottom: restingContentBottom,
|
||||||
|
},
|
||||||
|
{ isKeyboardVisible: true, keyboardHeight: 40, expectedContentBottom: restingContentBottom },
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const step of transitions) {
|
||||||
|
const height = getBottomSheetVisibleContentHeight({
|
||||||
|
containerHeight,
|
||||||
|
contentPosition,
|
||||||
|
handleHeight,
|
||||||
|
keyboardHeight: step.keyboardHeight,
|
||||||
|
isKeyboardVisible: step.isKeyboardVisible,
|
||||||
|
});
|
||||||
|
const paddingBottom = getBottomSheetSafeAreaPaddingBottom({
|
||||||
|
keyboardHeight: step.keyboardHeight,
|
||||||
|
isKeyboardVisible: step.isKeyboardVisible,
|
||||||
|
safeAreaBottom,
|
||||||
|
});
|
||||||
|
// Inside a border-box frame at `contentPosition + handleHeight`, the bottom of the footer
|
||||||
|
// sits at `contentPosition + handleHeight + height - paddingBottom`.
|
||||||
|
const footerBottomY = contentPosition + handleHeight + height - paddingBottom;
|
||||||
|
expect(footerBottomY).toBe(step.expectedContentBottom);
|
||||||
|
expect(footerBottomY).toBeLessThanOrEqual(restingContentBottom);
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// Below the lowest snap the frame must travel with the sheet, not shrink to the screen edge.
|
// Below the lowest snap the frame must travel with the sheet, not shrink to the screen edge.
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
interface BottomSheetVisibleContentHeightInput {
|
export interface BottomSheetVisibleContentHeightInput {
|
||||||
containerHeight: number;
|
containerHeight: number;
|
||||||
contentPosition: number;
|
contentPosition: number;
|
||||||
lowestDetentPosition?: number;
|
lowestDetentPosition?: number;
|
||||||
@@ -7,6 +7,28 @@ interface BottomSheetVisibleContentHeightInput {
|
|||||||
isKeyboardVisible: boolean;
|
isKeyboardVisible: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface BottomSheetSafeAreaPaddingInput {
|
||||||
|
keyboardHeight: number;
|
||||||
|
isKeyboardVisible: boolean;
|
||||||
|
safeAreaBottom: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Effective keyboard height inside the sheet container.
|
||||||
|
*
|
||||||
|
* Gorhom retains `heightWithinContainer` after the keyboard hides, and on first show `status`
|
||||||
|
* flips to `SHOWN` before its reaction writes `heightWithinContainer`. Treating both states as 0
|
||||||
|
* keeps frame height and safe-area clearance in lockstep.
|
||||||
|
*/
|
||||||
|
export function getBottomSheetEffectiveKeyboardHeight(
|
||||||
|
keyboardHeight: number,
|
||||||
|
isKeyboardVisible: boolean,
|
||||||
|
): number {
|
||||||
|
"worklet";
|
||||||
|
if (!isKeyboardVisible || keyboardHeight <= 0) return 0;
|
||||||
|
return keyboardHeight;
|
||||||
|
}
|
||||||
|
|
||||||
export function getBottomSheetVisibleContentHeight({
|
export function getBottomSheetVisibleContentHeight({
|
||||||
containerHeight,
|
containerHeight,
|
||||||
contentPosition,
|
contentPosition,
|
||||||
@@ -18,8 +40,29 @@ export function getBottomSheetVisibleContentHeight({
|
|||||||
"worklet";
|
"worklet";
|
||||||
if (containerHeight < 0 || handleHeight < 0) return 0;
|
if (containerHeight < 0 || handleHeight < 0) return 0;
|
||||||
const position = Math.min(contentPosition, lowestDetentPosition ?? contentPosition);
|
const position = Math.min(contentPosition, lowestDetentPosition ?? contentPosition);
|
||||||
return Math.max(
|
const effectiveKeyboardHeight = getBottomSheetEffectiveKeyboardHeight(
|
||||||
0,
|
keyboardHeight,
|
||||||
containerHeight - position - handleHeight - (isKeyboardVisible ? keyboardHeight : 0),
|
isKeyboardVisible,
|
||||||
);
|
);
|
||||||
|
return Math.max(0, containerHeight - position - handleHeight - effectiveKeyboardHeight);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bottom safe-area clearance derived from the same keyboard inset subtracted from
|
||||||
|
* `SheetVisibleFrame`'s height so both update in one UI-thread commit.
|
||||||
|
*
|
||||||
|
* Invariant: `effectiveKeyboardHeight + paddingBottom >= safeAreaBottom`.
|
||||||
|
*/
|
||||||
|
export function getBottomSheetSafeAreaPaddingBottom({
|
||||||
|
keyboardHeight,
|
||||||
|
isKeyboardVisible,
|
||||||
|
safeAreaBottom,
|
||||||
|
}: BottomSheetSafeAreaPaddingInput): number {
|
||||||
|
"worklet";
|
||||||
|
if (safeAreaBottom <= 0) return 0;
|
||||||
|
const effectiveKeyboardHeight = getBottomSheetEffectiveKeyboardHeight(
|
||||||
|
keyboardHeight,
|
||||||
|
isKeyboardVisible,
|
||||||
|
);
|
||||||
|
return Math.max(0, safeAreaBottom - effectiveKeyboardHeight);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,21 +2,63 @@ import type { ReactNode } from "react";
|
|||||||
import { View, StyleSheet } from "react-native";
|
import { View, StyleSheet } from "react-native";
|
||||||
import { KEYBOARD_STATUS, useBottomSheetInternal } from "@gorhom/bottom-sheet";
|
import { KEYBOARD_STATUS, useBottomSheetInternal } from "@gorhom/bottom-sheet";
|
||||||
import Animated, { useAnimatedStyle } from "react-native-reanimated";
|
import Animated, { useAnimatedStyle } from "react-native-reanimated";
|
||||||
import { getBottomSheetVisibleContentHeight } from "./visible-frame-layout";
|
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||||
|
import {
|
||||||
|
getBottomSheetSafeAreaPaddingBottom,
|
||||||
|
getBottomSheetVisibleContentHeight,
|
||||||
|
} from "./visible-frame-layout";
|
||||||
|
|
||||||
/** Fixed-detent sheet content. The footer shares the sheet's translation below its lowest snap. */
|
/**
|
||||||
|
* UI-thread bottom safe-area padding synchronized with Gorhom's keyboard state.
|
||||||
|
* Use this for scrollable sheet bodies without a footer so content scrolls behind the system
|
||||||
|
* navigation bar while still clearing it at rest and dropping the padding in lockstep with
|
||||||
|
* `SheetVisibleFrame` when the keyboard opens or closes.
|
||||||
|
*/
|
||||||
|
export function useBottomSheetSafeAreaPaddingStyle(enabled = true) {
|
||||||
|
const { bottom: safeAreaBottom } = useSafeAreaInsets();
|
||||||
|
const { animatedKeyboardState } = useBottomSheetInternal();
|
||||||
|
return useAnimatedStyle(() => {
|
||||||
|
const keyboard = animatedKeyboardState.get();
|
||||||
|
return {
|
||||||
|
paddingBottom: enabled
|
||||||
|
? getBottomSheetSafeAreaPaddingBottom({
|
||||||
|
keyboardHeight: keyboard.heightWithinContainer,
|
||||||
|
isKeyboardVisible: keyboard.status === KEYBOARD_STATUS.SHOWN,
|
||||||
|
safeAreaBottom,
|
||||||
|
})
|
||||||
|
: 0,
|
||||||
|
};
|
||||||
|
}, [animatedKeyboardState, enabled, safeAreaBottom]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fixed-detent sheet content. The footer shares the sheet's translation below its lowest snap,
|
||||||
|
* and frame height + bottom safe-area clearance update together in one UI-thread commit so the
|
||||||
|
* footer never flashes behind the system navigation bar on keyboard show/hide.
|
||||||
|
*/
|
||||||
export function SheetVisibleFrame({
|
export function SheetVisibleFrame({
|
||||||
children,
|
children,
|
||||||
footer,
|
footer,
|
||||||
|
safeAreaInset = "footer",
|
||||||
}: {
|
}: {
|
||||||
children: ReactNode;
|
children: ReactNode;
|
||||||
footer?: ReactNode;
|
footer?: ReactNode;
|
||||||
|
/**
|
||||||
|
* Where bottom safe-area clearance is applied:
|
||||||
|
* - `"footer"` (default): pads the frame whenever `footer` is present.
|
||||||
|
* - `"frame"`: always pads the frame, with or without a footer.
|
||||||
|
* - `"none"`: caller owns safe-area clearance.
|
||||||
|
*/
|
||||||
|
safeAreaInset?: "footer" | "frame" | "none";
|
||||||
}) {
|
}) {
|
||||||
|
const { bottom: safeAreaBottom } = useSafeAreaInsets();
|
||||||
const { animatedDetentsState, animatedKeyboardState, animatedLayoutState, animatedPosition } =
|
const { animatedDetentsState, animatedKeyboardState, animatedLayoutState, animatedPosition } =
|
||||||
useBottomSheetInternal();
|
useBottomSheetInternal();
|
||||||
|
const padFrame = safeAreaInset === "frame" || (safeAreaInset === "footer" && Boolean(footer));
|
||||||
const visibleStyle = useAnimatedStyle(() => {
|
const visibleStyle = useAnimatedStyle(() => {
|
||||||
const { containerHeight, handleHeight } = animatedLayoutState.get();
|
const { containerHeight, handleHeight } = animatedLayoutState.get();
|
||||||
const keyboard = animatedKeyboardState.get();
|
const keyboard = animatedKeyboardState.get();
|
||||||
|
const isKeyboardVisible = keyboard.status === KEYBOARD_STATUS.SHOWN;
|
||||||
return {
|
return {
|
||||||
height: getBottomSheetVisibleContentHeight({
|
height: getBottomSheetVisibleContentHeight({
|
||||||
containerHeight,
|
containerHeight,
|
||||||
@@ -24,10 +66,24 @@ export function SheetVisibleFrame({
|
|||||||
contentPosition: animatedPosition.get(),
|
contentPosition: animatedPosition.get(),
|
||||||
lowestDetentPosition: animatedDetentsState.get().detents?.[0],
|
lowestDetentPosition: animatedDetentsState.get().detents?.[0],
|
||||||
keyboardHeight: keyboard.heightWithinContainer,
|
keyboardHeight: keyboard.heightWithinContainer,
|
||||||
isKeyboardVisible: keyboard.status === KEYBOARD_STATUS.SHOWN,
|
isKeyboardVisible,
|
||||||
}),
|
}),
|
||||||
|
paddingBottom: padFrame
|
||||||
|
? getBottomSheetSafeAreaPaddingBottom({
|
||||||
|
keyboardHeight: keyboard.heightWithinContainer,
|
||||||
|
isKeyboardVisible,
|
||||||
|
safeAreaBottom,
|
||||||
|
})
|
||||||
|
: 0,
|
||||||
};
|
};
|
||||||
}, [animatedDetentsState, animatedKeyboardState, animatedLayoutState, animatedPosition]);
|
}, [
|
||||||
|
animatedDetentsState,
|
||||||
|
animatedKeyboardState,
|
||||||
|
animatedLayoutState,
|
||||||
|
animatedPosition,
|
||||||
|
padFrame,
|
||||||
|
safeAreaBottom,
|
||||||
|
]);
|
||||||
return (
|
return (
|
||||||
<Animated.View style={[styles.frame, visibleStyle]}>
|
<Animated.View style={[styles.frame, visibleStyle]}>
|
||||||
<View style={styles.body}>{children}</View>
|
<View style={styles.body}>{children}</View>
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { createContext, forwardRef, useContext, useMemo, useState, type Ref } from "react";
|
import { forwardRef, type Ref } from "react";
|
||||||
import {
|
import {
|
||||||
ScrollView as NativeScrollView,
|
ScrollView as NativeScrollView,
|
||||||
FlatList as NativeFlatList,
|
FlatList as NativeFlatList,
|
||||||
@@ -12,15 +12,13 @@ import {
|
|||||||
type NativeViewGestureHandlerProps,
|
type NativeViewGestureHandlerProps,
|
||||||
} from "react-native-gesture-handler";
|
} from "react-native-gesture-handler";
|
||||||
import { isNative } from "@/constants/platform";
|
import { isNative } from "@/constants/platform";
|
||||||
import {
|
import { useAttachSheetContentDrag, useIsInsideBottomSheet } from "./bottom-sheet-scope";
|
||||||
useAttachSheetContentDrag,
|
import { withContentDrag } from "./content-drag";
|
||||||
useIsInsideBottomSheet,
|
|
||||||
type AttachSheetContentDrag,
|
|
||||||
} from "./bottom-sheet-scope";
|
|
||||||
|
|
||||||
// Both libraries forward to the RN FlatList instance. Their published ref types
|
// Both libraries forward to the RN FlatList and ScrollView instances. Their published ref types
|
||||||
// disagree about getScrollResponder (Gorhom) and include the component function
|
// disagree about getScrollResponder (Gorhom) and include the component function
|
||||||
// in the instance intersection (RNGH); keep that type discrepancy at this boundary.
|
// in the instance intersection (RNGH); keep that type discrepancy at this boundary.
|
||||||
|
const SheetScroll = BottomSheetScrollView as unknown as typeof NativeScrollView;
|
||||||
const SheetFlatList = BottomSheetFlatList as unknown as typeof NativeFlatList;
|
const SheetFlatList = BottomSheetFlatList as unknown as typeof NativeFlatList;
|
||||||
const HorizontalFlatList = GestureFlatList as unknown as <Item>(
|
const HorizontalFlatList = GestureFlatList as unknown as <Item>(
|
||||||
props: FlatListProps<Item> & NativeViewGestureHandlerProps & { ref?: Ref<NativeFlatList<Item>> },
|
props: FlatListProps<Item> & NativeViewGestureHandlerProps & { ref?: Ref<NativeFlatList<Item>> },
|
||||||
@@ -30,7 +28,7 @@ const HorizontalFlatList = GestureFlatList as unknown as <Item>(
|
|||||||
export const ScrollView = forwardRef<NativeScrollView, ScrollViewProps>(
|
export const ScrollView = forwardRef<NativeScrollView, ScrollViewProps>(
|
||||||
function ScrollView(props, ref) {
|
function ScrollView(props, ref) {
|
||||||
const inSheet = useIsInsideBottomSheet();
|
const inSheet = useIsInsideBottomSheet();
|
||||||
if (!inSheet) return <NativeScrollView {...props} ref={ref} />;
|
if (!inSheet) return <PageScrollView {...props} ref={ref} />;
|
||||||
if (props.horizontal) {
|
if (props.horizontal) {
|
||||||
return isNative ? (
|
return isNative ? (
|
||||||
<GestureScrollView {...props} ref={ref} disallowInterruption />
|
<GestureScrollView {...props} ref={ref} disallowInterruption />
|
||||||
@@ -42,42 +40,11 @@ export const ScrollView = forwardRef<NativeScrollView, ScrollViewProps>(
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
/**
|
const PageScrollView = withContentDrag<ScrollViewProps, NativeScrollView>(NativeScrollView);
|
||||||
* What a child that drags inside a sheet needs to keep the touch: it registers its drag gesture
|
|
||||||
* through `attach` so the sheet's pan waits for it, and `setActive(true)` stops the sheet's
|
|
||||||
* scroll until the drag ends. Outside a sheet scroll there is no `attach` and `setActive` does
|
|
||||||
* nothing.
|
|
||||||
*/
|
|
||||||
export interface ContentDrag {
|
|
||||||
attach: AttachSheetContentDrag | undefined;
|
|
||||||
setActive: (active: boolean) => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
const ContentDragContext = createContext<ContentDrag | null>(null);
|
const SheetScrollView = withContentDrag<ScrollViewProps, NativeScrollView>(
|
||||||
|
SheetScroll,
|
||||||
const NO_CONTENT_DRAG: ContentDrag = { attach: undefined, setActive: () => {} };
|
useAttachSheetContentDrag,
|
||||||
|
|
||||||
export function useContentDrag(): ContentDrag {
|
|
||||||
return useContext(ContentDragContext) ?? NO_CONTENT_DRAG;
|
|
||||||
}
|
|
||||||
|
|
||||||
const SheetScrollView = forwardRef<NativeScrollView, ScrollViewProps>(
|
|
||||||
function SheetScrollView(props, ref) {
|
|
||||||
const attach = useAttachSheetContentDrag();
|
|
||||||
const [dragging, setDragging] = useState(false);
|
|
||||||
const contentDrag = useMemo(() => ({ attach, setActive: setDragging }), [attach]);
|
|
||||||
return (
|
|
||||||
<BottomSheetScrollView
|
|
||||||
{...props}
|
|
||||||
scrollEnabled={!dragging && props.scrollEnabled !== false}
|
|
||||||
ref={ref}
|
|
||||||
>
|
|
||||||
<ContentDragContext.Provider value={contentDrag}>
|
|
||||||
{props.children}
|
|
||||||
</ContentDragContext.Provider>
|
|
||||||
</BottomSheetScrollView>
|
|
||||||
);
|
|
||||||
},
|
|
||||||
);
|
);
|
||||||
|
|
||||||
function SheetAwareFlatList<Item>(props: FlatListProps<Item>, ref: Ref<NativeFlatList<Item>>) {
|
function SheetAwareFlatList<Item>(props: FlatListProps<Item>, ref: Ref<NativeFlatList<Item>>) {
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { useCallback, useMemo } from "react";
|
import { useCallback, useMemo } from "react";
|
||||||
import {
|
import {
|
||||||
Pressable,
|
Pressable,
|
||||||
|
View,
|
||||||
type GestureResponderEvent,
|
type GestureResponderEvent,
|
||||||
type StyleProp,
|
type StyleProp,
|
||||||
type ViewStyle,
|
type ViewStyle,
|
||||||
@@ -19,7 +20,11 @@ import { useIsCompactFormFactor } from "@/constants/layout";
|
|||||||
import type { Theme } from "@/styles/theme";
|
import type { Theme } from "@/styles/theme";
|
||||||
|
|
||||||
interface SwitchProps {
|
interface SwitchProps {
|
||||||
value: boolean;
|
/**
|
||||||
|
* `null` while the value is not known yet, such as while it loads from a host. The switch's space
|
||||||
|
* stays reserved and empty, so the switch takes it when the value arrives and nothing moves.
|
||||||
|
*/
|
||||||
|
value: boolean | null;
|
||||||
onValueChange?: (value: boolean) => void;
|
onValueChange?: (value: boolean) => void;
|
||||||
disabled?: boolean;
|
disabled?: boolean;
|
||||||
accessibilityLabel?: string;
|
accessibilityLabel?: string;
|
||||||
@@ -109,7 +114,7 @@ export function Switch({
|
|||||||
const handlePress = useCallback(
|
const handlePress = useCallback(
|
||||||
(event: GestureResponderEvent) => {
|
(event: GestureResponderEvent) => {
|
||||||
event.stopPropagation();
|
event.stopPropagation();
|
||||||
if (disabled) return;
|
if (disabled || value === null) return;
|
||||||
onValueChange?.(!value);
|
onValueChange?.(!value);
|
||||||
},
|
},
|
||||||
[disabled, onValueChange, value],
|
[disabled, onValueChange, value],
|
||||||
@@ -119,7 +124,10 @@ export function Switch({
|
|||||||
const isCompact = useIsCompactFormFactor();
|
const isCompact = useIsCompactFormFactor();
|
||||||
const geometry = useMemo(() => switchGeometryForLayout(size, isCompact), [size, isCompact]);
|
const geometry = useMemo(() => switchGeometryForLayout(size, isCompact), [size, isCompact]);
|
||||||
|
|
||||||
const accessibilityState = useMemo(() => ({ checked: value, disabled }), [value, disabled]);
|
const accessibilityState = useMemo(
|
||||||
|
() => ({ checked: value === true, disabled }),
|
||||||
|
[value, disabled],
|
||||||
|
);
|
||||||
const pressableStyle = useMemo(
|
const pressableStyle = useMemo(
|
||||||
() => [
|
() => [
|
||||||
styles.switchControl,
|
styles.switchControl,
|
||||||
@@ -134,6 +142,12 @@ export function Switch({
|
|||||||
],
|
],
|
||||||
[disabled, geometry.hitHeight, geometry.trackHeight, style],
|
[disabled, geometry.hitHeight, geometry.trackHeight, style],
|
||||||
);
|
);
|
||||||
|
const unknownStyle = useMemo(
|
||||||
|
() => [{ width: geometry.trackWidth, minHeight: geometry.trackHeight }, style],
|
||||||
|
[geometry.trackWidth, geometry.trackHeight, style],
|
||||||
|
);
|
||||||
|
|
||||||
|
if (value === null) return <View style={unknownStyle} testID={testID} />;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Pressable
|
<Pressable
|
||||||
|
|||||||
@@ -96,6 +96,7 @@ import {
|
|||||||
import {
|
import {
|
||||||
useAgentProfileEditor,
|
useAgentProfileEditor,
|
||||||
useAgentProfilePicker,
|
useAgentProfilePicker,
|
||||||
|
type AgentProfile,
|
||||||
type AgentProfileApplyTarget,
|
type AgentProfileApplyTarget,
|
||||||
type AgentProfileEditorControls,
|
type AgentProfileEditorControls,
|
||||||
type AgentProfilePicker,
|
type AgentProfilePicker,
|
||||||
@@ -127,7 +128,7 @@ interface ControlledAgentControlsProps {
|
|||||||
agentProfiles?: AgentProfilePicker | null;
|
agentProfiles?: AgentProfilePicker | null;
|
||||||
onApplyAgentProfile?: (profileId: string) => void;
|
onApplyAgentProfile?: (profileId: string) => void;
|
||||||
onEditAgentProfiles?: () => void;
|
onEditAgentProfiles?: () => void;
|
||||||
onCreateAgentProfile?: (seed: AgentProfileSeed) => void;
|
onCreateAgentProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
|
||||||
onEditAgentProfile?: (profileId: string) => void;
|
onEditAgentProfile?: (profileId: string) => void;
|
||||||
optionControls?: ComposerOptionControls;
|
optionControls?: ComposerOptionControls;
|
||||||
onDropdownClose?: () => void;
|
onDropdownClose?: () => void;
|
||||||
@@ -269,7 +270,7 @@ function useEditAgentProfilesNavigation(
|
|||||||
): (() => void) | undefined {
|
): (() => void) | undefined {
|
||||||
const handleEdit = useCallback(() => {
|
const handleEdit = useCallback(() => {
|
||||||
if (!serverId) return;
|
if (!serverId) return;
|
||||||
router.push(buildSettingsHostSectionRoute(serverId, "agents"));
|
router.push(buildSettingsHostSectionRoute(serverId, "agent-profiles"));
|
||||||
}, [serverId]);
|
}, [serverId]);
|
||||||
return serverId && isSupported ? handleEdit : undefined;
|
return serverId && isSupported ? handleEdit : undefined;
|
||||||
}
|
}
|
||||||
@@ -278,14 +279,14 @@ function resolveAgentProfileEditorActions(
|
|||||||
isSupported: boolean,
|
isSupported: boolean,
|
||||||
editor: AgentProfileEditorControls,
|
editor: AgentProfileEditorControls,
|
||||||
): {
|
): {
|
||||||
create?: (seed: AgentProfileSeed) => void;
|
create?: (seed: AgentProfileSeed) => Promise<AgentProfile | null>;
|
||||||
edit?: (profileId: string) => void;
|
edit?: (profileId: string) => void;
|
||||||
} {
|
} {
|
||||||
if (!isSupported) {
|
if (!isSupported) {
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
create: editor.openCreateFromModel,
|
create: editor.quickCreateFromModel,
|
||||||
edit: editor.openEdit,
|
edit: editor.openEdit,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -732,7 +733,7 @@ interface AgentControlsContentProps {
|
|||||||
featureItems: ComposerControlItem[];
|
featureItems: ComposerControlItem[];
|
||||||
onApplyAgentProfile?: (profileId: string) => void;
|
onApplyAgentProfile?: (profileId: string) => void;
|
||||||
onEditAgentProfiles?: () => void;
|
onEditAgentProfiles?: () => void;
|
||||||
onCreateAgentProfile?: (seed: AgentProfileSeed) => void;
|
onCreateAgentProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
|
||||||
onEditAgentProfile?: (profileId: string) => void;
|
onEditAgentProfile?: (profileId: string) => void;
|
||||||
onDropdownClose?: () => void;
|
onDropdownClose?: () => void;
|
||||||
onModelSelectorOpen?: () => void;
|
onModelSelectorOpen?: () => void;
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import {
|
|||||||
} from "react-native";
|
} from "react-native";
|
||||||
import { StyleSheet } from "react-native-unistyles";
|
import { StyleSheet } from "react-native-unistyles";
|
||||||
import type { AgentProvider } from "@getpaseo/protocol/agent-types";
|
import type { AgentProvider } from "@getpaseo/protocol/agent-types";
|
||||||
import type { AgentProfilePicker, AgentProfileSeed } from "@/agent-profiles";
|
import type { AgentProfile, AgentProfilePicker, AgentProfileSeed } from "@/agent-profiles";
|
||||||
import { AdaptiveModalSheet } from "@/components/adaptive-modal-sheet";
|
import { AdaptiveModalSheet } from "@/components/adaptive-modal-sheet";
|
||||||
import type { ContextBridge } from "@/components/ui/isolated-bottom-sheet-modal";
|
import type { ContextBridge } from "@/components/ui/isolated-bottom-sheet-modal";
|
||||||
import { ComboboxTrigger } from "@/components/ui/combobox-trigger";
|
import { ComboboxTrigger } from "@/components/ui/combobox-trigger";
|
||||||
@@ -56,7 +56,7 @@ interface CompactModelSheetProps {
|
|||||||
profiles?: AgentProfilePicker | null;
|
profiles?: AgentProfilePicker | null;
|
||||||
onApplyProfile?: (profileId: string) => void;
|
onApplyProfile?: (profileId: string) => void;
|
||||||
onEditProfiles?: () => void;
|
onEditProfiles?: () => void;
|
||||||
onCreateProfile?: (seed: AgentProfileSeed) => void;
|
onCreateProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
|
||||||
onEditProfile?: (profileId: string) => void;
|
onEditProfile?: (profileId: string) => void;
|
||||||
onOpen?: () => void;
|
onOpen?: () => void;
|
||||||
onClose?: () => void;
|
onClose?: () => void;
|
||||||
@@ -74,8 +74,9 @@ interface CompactModelSheetProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function resolveModelSheetProfileActions(
|
function resolveModelSheetProfileActions(
|
||||||
onCreateProfile: ((seed: AgentProfileSeed) => void) | undefined,
|
onCreateProfile: ((seed: AgentProfileSeed) => Promise<AgentProfile | null> | void) | undefined,
|
||||||
onEditProfile: ((profileId: string) => void) | undefined,
|
onEditProfile: ((profileId: string) => void) | undefined,
|
||||||
|
onSelect: (provider: string, modelId: string) => void,
|
||||||
close: () => void,
|
close: () => void,
|
||||||
): {
|
): {
|
||||||
create?: (seed: AgentProfileSeed) => void;
|
create?: (seed: AgentProfileSeed) => void;
|
||||||
@@ -84,8 +85,11 @@ function resolveModelSheetProfileActions(
|
|||||||
return {
|
return {
|
||||||
create: onCreateProfile
|
create: onCreateProfile
|
||||||
? (seed: AgentProfileSeed) => {
|
? (seed: AgentProfileSeed) => {
|
||||||
|
if (seed.modelId) {
|
||||||
|
onSelect(seed.provider, seed.modelId);
|
||||||
|
}
|
||||||
close();
|
close();
|
||||||
onCreateProfile(seed);
|
void onCreateProfile(seed);
|
||||||
}
|
}
|
||||||
: undefined,
|
: undefined,
|
||||||
edit: onEditProfile
|
edit: onEditProfile
|
||||||
@@ -281,7 +285,12 @@ export function CompactModelSheet({
|
|||||||
onEditProfiles?.();
|
onEditProfiles?.();
|
||||||
}, [close, onEditProfiles]);
|
}, [close, onEditProfiles]);
|
||||||
|
|
||||||
const profileActions = resolveModelSheetProfileActions(onCreateProfile, onEditProfile, close);
|
const profileActions = resolveModelSheetProfileActions(
|
||||||
|
onCreateProfile,
|
||||||
|
onEditProfile,
|
||||||
|
onSelect,
|
||||||
|
close,
|
||||||
|
);
|
||||||
|
|
||||||
const toggle = useCallback(() => {
|
const toggle = useCallback(() => {
|
||||||
if (isOpen) {
|
if (isOpen) {
|
||||||
|
|||||||
@@ -11,13 +11,8 @@ import { i18n } from "@/i18n/i18next";
|
|||||||
|
|
||||||
const DESKTOP_SETTINGS_QUERY_KEY = ["desktop-settings"] as const;
|
const DESKTOP_SETTINGS_QUERY_KEY = ["desktop-settings"] as const;
|
||||||
|
|
||||||
export type DesktopUpdateMode = "automatic" | "notify" | "off";
|
|
||||||
|
|
||||||
export interface DesktopSettings {
|
export interface DesktopSettings {
|
||||||
releaseChannel: ReleaseChannel;
|
releaseChannel: ReleaseChannel;
|
||||||
updates: {
|
|
||||||
mode: DesktopUpdateMode;
|
|
||||||
};
|
|
||||||
notifications: {
|
notifications: {
|
||||||
playSound: boolean;
|
playSound: boolean;
|
||||||
};
|
};
|
||||||
@@ -29,16 +24,12 @@ export interface DesktopSettings {
|
|||||||
|
|
||||||
export interface DesktopSettingsPatch {
|
export interface DesktopSettingsPatch {
|
||||||
releaseChannel?: ReleaseChannel;
|
releaseChannel?: ReleaseChannel;
|
||||||
updates?: Partial<DesktopSettings["updates"]>;
|
|
||||||
notifications?: Partial<DesktopSettings["notifications"]>;
|
notifications?: Partial<DesktopSettings["notifications"]>;
|
||||||
daemon?: Partial<DesktopSettings["daemon"]>;
|
daemon?: Partial<DesktopSettings["daemon"]>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
|
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
|
||||||
releaseChannel: "stable",
|
releaseChannel: "stable",
|
||||||
updates: {
|
|
||||||
mode: "automatic",
|
|
||||||
},
|
|
||||||
notifications: {
|
notifications: {
|
||||||
playSound: true,
|
playSound: true,
|
||||||
},
|
},
|
||||||
@@ -158,24 +149,13 @@ export async function migrateLegacyDesktopSettings(input: {
|
|||||||
await invokeDesktopCommand("migrate_legacy_desktop_settings", input);
|
await invokeDesktopCommand("migrate_legacy_desktop_settings", input);
|
||||||
}
|
}
|
||||||
|
|
||||||
function parseUpdateMode(value: unknown): DesktopUpdateMode {
|
|
||||||
if (value === "automatic" || value === "notify" || value === "off") {
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
return DEFAULT_DESKTOP_SETTINGS.updates.mode;
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseDesktopSettings(raw: unknown): DesktopSettings {
|
function parseDesktopSettings(raw: unknown): DesktopSettings {
|
||||||
const record = isRecord(raw) ? raw : {};
|
const record = isRecord(raw) ? raw : {};
|
||||||
const updates = isRecord(record.updates) ? record.updates : {};
|
|
||||||
const notifications = isRecord(record.notifications) ? record.notifications : {};
|
const notifications = isRecord(record.notifications) ? record.notifications : {};
|
||||||
const daemon = isRecord(record.daemon) ? record.daemon : {};
|
const daemon = isRecord(record.daemon) ? record.daemon : {};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
releaseChannel: record.releaseChannel === "beta" ? "beta" : "stable",
|
releaseChannel: record.releaseChannel === "beta" ? "beta" : "stable",
|
||||||
updates: {
|
|
||||||
mode: parseUpdateMode(updates.mode),
|
|
||||||
},
|
|
||||||
notifications: {
|
notifications: {
|
||||||
playSound:
|
playSound:
|
||||||
typeof notifications.playSound === "boolean"
|
typeof notifications.playSound === "boolean"
|
||||||
@@ -201,10 +181,6 @@ function mergeDesktopSettings(
|
|||||||
): DesktopSettings {
|
): DesktopSettings {
|
||||||
return {
|
return {
|
||||||
releaseChannel: updates.releaseChannel ?? current.releaseChannel,
|
releaseChannel: updates.releaseChannel ?? current.releaseChannel,
|
||||||
updates: {
|
|
||||||
...current.updates,
|
|
||||||
...updates.updates,
|
|
||||||
},
|
|
||||||
notifications: {
|
notifications: {
|
||||||
...current.notifications,
|
...current.notifications,
|
||||||
...updates.notifications,
|
...updates.notifications,
|
||||||
@@ -219,7 +195,6 @@ function mergeDesktopSettings(
|
|||||||
function normalizePatch(updates: DesktopSettingsPatch): Record<string, unknown> {
|
function normalizePatch(updates: DesktopSettingsPatch): Record<string, unknown> {
|
||||||
return {
|
return {
|
||||||
...(updates.releaseChannel ? { releaseChannel: updates.releaseChannel } : {}),
|
...(updates.releaseChannel ? { releaseChannel: updates.releaseChannel } : {}),
|
||||||
...(updates.updates ? { updates: updates.updates } : {}),
|
|
||||||
...(updates.notifications ? { notifications: updates.notifications } : {}),
|
...(updates.notifications ? { notifications: updates.notifications } : {}),
|
||||||
...(updates.daemon ? { daemon: updates.daemon } : {}),
|
...(updates.daemon ? { daemon: updates.daemon } : {}),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -128,43 +128,6 @@ describe("desktop app updater — check", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it("reports 'available' when an update is available to download without auto-downloading", async () => {
|
|
||||||
const { updater, port } = createUpdater({ now: () => 42 });
|
|
||||||
port.nextCheckResult(
|
|
||||||
buildFakeCheckResult({
|
|
||||||
hasUpdate: true,
|
|
||||||
readyToInstall: false,
|
|
||||||
downloading: false,
|
|
||||||
latestVersion: "1.2.3",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await updater.checkForUpdates({ releaseChannel: "stable" });
|
|
||||||
|
|
||||||
expect(updater.getSnapshot()).toMatchObject({
|
|
||||||
status: "available",
|
|
||||||
availableUpdate: { latestVersion: "1.2.3", readyToInstall: false, downloading: false },
|
|
||||||
lastCheckedAt: 42,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("tracks download progress updates and clears them once install completes", async () => {
|
|
||||||
const { updater, port } = createUpdater();
|
|
||||||
port.nextInstallResult(buildFakeInstallResult({ installed: true }));
|
|
||||||
|
|
||||||
updater.setDownloadProgress({
|
|
||||||
version: "1.2.3",
|
|
||||||
percent: 42.4,
|
|
||||||
transferred: 42,
|
|
||||||
total: 100,
|
|
||||||
bytesPerSecond: 10,
|
|
||||||
});
|
|
||||||
expect(updater.getSnapshot().downloadProgress?.percent).toBe(42.4);
|
|
||||||
|
|
||||||
await updater.installUpdate({ releaseChannel: "stable" });
|
|
||||||
expect(updater.getSnapshot().downloadProgress).toBeNull();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("reports 'up-to-date' when the check resolves with no update", async () => {
|
it("reports 'up-to-date' when the check resolves with no update", async () => {
|
||||||
const { updater, port } = createUpdater();
|
const { updater, port } = createUpdater();
|
||||||
port.nextCheckResult(buildFakeCheckResult({ hasUpdate: false, readyToInstall: false }));
|
port.nextCheckResult(buildFakeCheckResult({ hasUpdate: false, readyToInstall: false }));
|
||||||
@@ -377,55 +340,6 @@ describe("desktop app updater — install", () => {
|
|||||||
expect(updater.getSnapshot().status).toBe("up-to-date");
|
expect(updater.getSnapshot().status).toBe("up-to-date");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("moves to 'error' instead of 'up-to-date' when the install returns an errorMessage", async () => {
|
|
||||||
const { updater, port } = createUpdater();
|
|
||||||
port.nextInstallResult(
|
|
||||||
buildFakeInstallResult({
|
|
||||||
installed: false,
|
|
||||||
message: "Update failed: ECONNRESET",
|
|
||||||
errorMessage: "ECONNRESET",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await updater.installUpdate({ releaseChannel: "stable" });
|
|
||||||
|
|
||||||
expect(updater.getSnapshot()).toMatchObject({
|
|
||||||
status: "error",
|
|
||||||
errorMessage: "ECONNRESET",
|
|
||||||
downloadProgress: null,
|
|
||||||
isInstalling: false,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("ignores duplicate install requests and silent checks while an install is in progress", async () => {
|
|
||||||
const { updater, port } = createUpdater();
|
|
||||||
let resolveInstall!: (result: ReturnType<typeof buildFakeInstallResult>) => void;
|
|
||||||
port.installDesktopAppUpdate = async (input) => {
|
|
||||||
port.recordedInstalls.push(input);
|
|
||||||
return new Promise((resolve) => {
|
|
||||||
resolveInstall = resolve;
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const firstInstall = updater.installUpdate({ releaseChannel: "stable" });
|
|
||||||
const secondInstall = await updater.installUpdate({ releaseChannel: "stable" });
|
|
||||||
const silentCheck = await updater.checkForUpdates({
|
|
||||||
releaseChannel: "stable",
|
|
||||||
intent: "automatic",
|
|
||||||
silent: true,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(secondInstall).toBeNull();
|
|
||||||
expect(silentCheck).toBeNull();
|
|
||||||
expect(port.recordedInstalls).toHaveLength(1);
|
|
||||||
expect(port.recordedChecks).toHaveLength(0);
|
|
||||||
expect(updater.getSnapshot().status).toBe("installing");
|
|
||||||
|
|
||||||
resolveInstall(buildFakeInstallResult({ installed: true }));
|
|
||||||
await firstInstall;
|
|
||||||
expect(updater.getSnapshot().status).toBe("installed");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("reports the install error and moves to 'error' when the install throws", async () => {
|
it("reports the install error and moves to 'error' when the install throws", async () => {
|
||||||
const { updater, port, reportedInstallErrors } = createUpdater();
|
const { updater, port, reportedInstallErrors } = createUpdater();
|
||||||
const error = new Error("install failed");
|
const error = new Error("install failed");
|
||||||
@@ -548,47 +462,6 @@ describe("formatStatusText", () => {
|
|||||||
).toBe("Restart now");
|
).toBe("Restart now");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("formats download-available and live download progress status text", () => {
|
|
||||||
expect(
|
|
||||||
formatStatusText({
|
|
||||||
status: "available",
|
|
||||||
availableUpdate: buildFakeCheckResult({
|
|
||||||
hasUpdate: true,
|
|
||||||
readyToInstall: false,
|
|
||||||
downloading: false,
|
|
||||||
latestVersion: "1.2.3",
|
|
||||||
}),
|
|
||||||
installMessage: null,
|
|
||||||
lastCheckedAt: 42,
|
|
||||||
formatVersion,
|
|
||||||
formatLastCheckedAt,
|
|
||||||
}),
|
|
||||||
).toBe("Update available: v1.2.3. Last checked at time-42.");
|
|
||||||
|
|
||||||
expect(
|
|
||||||
formatStatusText({
|
|
||||||
status: "installing",
|
|
||||||
availableUpdate: buildFakeCheckResult({
|
|
||||||
hasUpdate: true,
|
|
||||||
readyToInstall: false,
|
|
||||||
downloading: false,
|
|
||||||
latestVersion: "1.2.3",
|
|
||||||
}),
|
|
||||||
downloadProgress: {
|
|
||||||
version: "1.2.3",
|
|
||||||
percent: 64.6,
|
|
||||||
transferred: 65,
|
|
||||||
total: 100,
|
|
||||||
bytesPerSecond: 10,
|
|
||||||
},
|
|
||||||
installMessage: null,
|
|
||||||
lastCheckedAt: null,
|
|
||||||
formatVersion,
|
|
||||||
formatLastCheckedAt,
|
|
||||||
}),
|
|
||||||
).toBe("Downloading v1.2.3... 65%");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("uses the active app language for local status wrappers", async () => {
|
it("uses the active app language for local status wrappers", async () => {
|
||||||
await i18n.changeLanguage("zh-CN");
|
await i18n.changeLanguage("zh-CN");
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import type {
|
import type {
|
||||||
DesktopAppUpdateCheckResult,
|
DesktopAppUpdateCheckResult,
|
||||||
DesktopAppUpdateCheckIntent,
|
DesktopAppUpdateCheckIntent,
|
||||||
DesktopAppUpdateDownloadProgress,
|
|
||||||
DesktopAppUpdateInstallResult,
|
DesktopAppUpdateInstallResult,
|
||||||
DesktopReleaseChannel,
|
DesktopReleaseChannel,
|
||||||
} from "@/desktop/updates/desktop-updates";
|
} from "@/desktop/updates/desktop-updates";
|
||||||
@@ -22,7 +21,6 @@ export const PENDING_RECHECK_MS = 10_000;
|
|||||||
export interface DesktopAppUpdaterSnapshot {
|
export interface DesktopAppUpdaterSnapshot {
|
||||||
status: DesktopAppUpdateStatus;
|
status: DesktopAppUpdateStatus;
|
||||||
availableUpdate: DesktopAppUpdateCheckResult | null;
|
availableUpdate: DesktopAppUpdateCheckResult | null;
|
||||||
downloadProgress: DesktopAppUpdateDownloadProgress | null;
|
|
||||||
errorMessage: string | null;
|
errorMessage: string | null;
|
||||||
installMessage: string | null;
|
installMessage: string | null;
|
||||||
lastCheckedAt: number | null;
|
lastCheckedAt: number | null;
|
||||||
@@ -55,7 +53,6 @@ export interface DesktopAppUpdaterDeps {
|
|||||||
export interface DesktopAppUpdater {
|
export interface DesktopAppUpdater {
|
||||||
getSnapshot(): DesktopAppUpdaterSnapshot;
|
getSnapshot(): DesktopAppUpdaterSnapshot;
|
||||||
subscribe(listener: () => void): () => void;
|
subscribe(listener: () => void): () => void;
|
||||||
setDownloadProgress(progress: DesktopAppUpdateDownloadProgress | null): void;
|
|
||||||
checkForUpdates(options?: {
|
checkForUpdates(options?: {
|
||||||
releaseChannel: DesktopReleaseChannel;
|
releaseChannel: DesktopReleaseChannel;
|
||||||
intent?: DesktopAppUpdateCheckIntent;
|
intent?: DesktopAppUpdateCheckIntent;
|
||||||
@@ -69,7 +66,6 @@ export interface DesktopAppUpdater {
|
|||||||
interface InternalState {
|
interface InternalState {
|
||||||
status: DesktopAppUpdateStatus;
|
status: DesktopAppUpdateStatus;
|
||||||
availableUpdate: DesktopAppUpdateCheckResult | null;
|
availableUpdate: DesktopAppUpdateCheckResult | null;
|
||||||
downloadProgress: DesktopAppUpdateDownloadProgress | null;
|
|
||||||
errorMessage: string | null;
|
errorMessage: string | null;
|
||||||
installMessage: string | null;
|
installMessage: string | null;
|
||||||
lastCheckedAt: number | null;
|
lastCheckedAt: number | null;
|
||||||
@@ -80,7 +76,6 @@ interface InternalState {
|
|||||||
const INITIAL_STATE: InternalState = {
|
const INITIAL_STATE: InternalState = {
|
||||||
status: "idle",
|
status: "idle",
|
||||||
availableUpdate: null,
|
availableUpdate: null,
|
||||||
downloadProgress: null,
|
|
||||||
errorMessage: null,
|
errorMessage: null,
|
||||||
installMessage: null,
|
installMessage: null,
|
||||||
lastCheckedAt: null,
|
lastCheckedAt: null,
|
||||||
@@ -92,7 +87,6 @@ function buildSnapshot(state: InternalState): DesktopAppUpdaterSnapshot {
|
|||||||
return {
|
return {
|
||||||
status: state.status,
|
status: state.status,
|
||||||
availableUpdate: state.availableUpdate,
|
availableUpdate: state.availableUpdate,
|
||||||
downloadProgress: state.downloadProgress,
|
|
||||||
errorMessage: state.errorMessage,
|
errorMessage: state.errorMessage,
|
||||||
installMessage: state.installMessage,
|
installMessage: state.installMessage,
|
||||||
lastCheckedAt: state.lastCheckedAt,
|
lastCheckedAt: state.lastCheckedAt,
|
||||||
@@ -108,113 +102,9 @@ function getErrorMessage(error: unknown): string {
|
|||||||
return String(error);
|
return String(error);
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatInstallingStatusText(input: {
|
|
||||||
availableUpdate: DesktopAppUpdateCheckResult | null;
|
|
||||||
downloadProgress: DesktopAppUpdateDownloadProgress | null;
|
|
||||||
formatVersion: (version: string | null | undefined) => string;
|
|
||||||
}): string {
|
|
||||||
const { availableUpdate, downloadProgress, formatVersion } = input;
|
|
||||||
if (downloadProgress == null) {
|
|
||||||
return i18n.t("desktop.updates.status.installing");
|
|
||||||
}
|
|
||||||
const percent = Math.round(downloadProgress.percent);
|
|
||||||
const version = downloadProgress.version ?? availableUpdate?.latestVersion;
|
|
||||||
if (version) {
|
|
||||||
return i18n.t("desktop.updates.status.downloadingVersionProgress", {
|
|
||||||
version: formatVersion(version),
|
|
||||||
percent,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return i18n.t("desktop.updates.status.downloadingProgress", { percent });
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatPendingStatusText(input: {
|
|
||||||
availableUpdate: DesktopAppUpdateCheckResult | null;
|
|
||||||
downloadProgress: DesktopAppUpdateDownloadProgress | null;
|
|
||||||
lastCheckedAt: number | null;
|
|
||||||
formatVersion: (version: string | null | undefined) => string;
|
|
||||||
formatLastCheckedAt: (timestamp: number) => string;
|
|
||||||
}): string {
|
|
||||||
const { availableUpdate, downloadProgress, lastCheckedAt, formatVersion, formatLastCheckedAt } =
|
|
||||||
input;
|
|
||||||
const time = lastCheckedAt != null ? formatLastCheckedAt(lastCheckedAt) : undefined;
|
|
||||||
if (availableUpdate?.latestVersion) {
|
|
||||||
const version = formatVersion(availableUpdate.latestVersion);
|
|
||||||
if (downloadProgress != null) {
|
|
||||||
return i18n.t(
|
|
||||||
time !== undefined
|
|
||||||
? "desktop.updates.status.pendingWithVersionProgressAndLastChecked"
|
|
||||||
: "desktop.updates.status.pendingWithVersionProgress",
|
|
||||||
{ version, percent: Math.round(downloadProgress.percent), time },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return i18n.t(
|
|
||||||
time !== undefined
|
|
||||||
? "desktop.updates.status.pendingWithVersionAndLastChecked"
|
|
||||||
: "desktop.updates.status.pendingWithVersion",
|
|
||||||
{ version, time },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (time !== undefined) {
|
|
||||||
return i18n.t("desktop.updates.status.pendingWithLastChecked", { time });
|
|
||||||
}
|
|
||||||
return i18n.t("desktop.updates.status.pending");
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatAvailableStatusText(input: {
|
|
||||||
availableUpdate: DesktopAppUpdateCheckResult | null;
|
|
||||||
lastCheckedAt: number | null;
|
|
||||||
formatVersion: (version: string | null | undefined) => string;
|
|
||||||
formatLastCheckedAt: (timestamp: number) => string;
|
|
||||||
}): string {
|
|
||||||
const { availableUpdate, lastCheckedAt, formatVersion, formatLastCheckedAt } = input;
|
|
||||||
const time = lastCheckedAt != null ? formatLastCheckedAt(lastCheckedAt) : undefined;
|
|
||||||
const isDownloadRequired =
|
|
||||||
availableUpdate?.hasUpdate === true && availableUpdate.readyToInstall === false;
|
|
||||||
if (availableUpdate?.latestVersion) {
|
|
||||||
const version = formatVersion(availableUpdate.latestVersion);
|
|
||||||
if (isDownloadRequired) {
|
|
||||||
return i18n.t(
|
|
||||||
time !== undefined
|
|
||||||
? "desktop.updates.status.downloadAvailableWithVersionAndLastChecked"
|
|
||||||
: "desktop.updates.status.downloadAvailableWithVersion",
|
|
||||||
{ version, time },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return i18n.t(
|
|
||||||
time !== undefined
|
|
||||||
? "desktop.updates.status.availableWithVersionAndLastChecked"
|
|
||||||
: "desktop.updates.status.availableWithVersion",
|
|
||||||
{ version, time },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (isDownloadRequired) {
|
|
||||||
return time !== undefined
|
|
||||||
? i18n.t("desktop.updates.status.downloadAvailableWithLastChecked", { time })
|
|
||||||
: i18n.t("desktop.updates.status.downloadAvailable");
|
|
||||||
}
|
|
||||||
return time !== undefined
|
|
||||||
? i18n.t("desktop.updates.status.availableWithLastChecked", { time })
|
|
||||||
: i18n.t("desktop.updates.status.available");
|
|
||||||
}
|
|
||||||
|
|
||||||
function resolveCheckOutcome(result: DesktopAppUpdateCheckResult): {
|
|
||||||
status: DesktopAppUpdateStatus;
|
|
||||||
availableUpdate: DesktopAppUpdateCheckResult | null;
|
|
||||||
} {
|
|
||||||
if (result.readyToInstall || (result.hasUpdate && !result.downloading)) {
|
|
||||||
return { status: "available", availableUpdate: result };
|
|
||||||
}
|
|
||||||
if (result.hasUpdate) {
|
|
||||||
return { status: "pending", availableUpdate: result };
|
|
||||||
}
|
|
||||||
return { status: "up-to-date", availableUpdate: null };
|
|
||||||
}
|
|
||||||
|
|
||||||
export function formatStatusText(input: {
|
export function formatStatusText(input: {
|
||||||
status: DesktopAppUpdateStatus;
|
status: DesktopAppUpdateStatus;
|
||||||
availableUpdate: DesktopAppUpdateCheckResult | null;
|
availableUpdate: DesktopAppUpdateCheckResult | null;
|
||||||
downloadProgress?: DesktopAppUpdateDownloadProgress | null;
|
|
||||||
installMessage: string | null;
|
installMessage: string | null;
|
||||||
lastCheckedAt: number | null;
|
lastCheckedAt: number | null;
|
||||||
formatVersion: (version: string | null | undefined) => string;
|
formatVersion: (version: string | null | undefined) => string;
|
||||||
@@ -223,45 +113,79 @@ export function formatStatusText(input: {
|
|||||||
const {
|
const {
|
||||||
status,
|
status,
|
||||||
availableUpdate,
|
availableUpdate,
|
||||||
downloadProgress = null,
|
|
||||||
installMessage,
|
installMessage,
|
||||||
lastCheckedAt,
|
lastCheckedAt,
|
||||||
formatVersion,
|
formatVersion,
|
||||||
formatLastCheckedAt,
|
formatLastCheckedAt,
|
||||||
} = input;
|
} = input;
|
||||||
|
|
||||||
if (status === "checking") return i18n.t("desktop.updates.status.checking");
|
if (status === "checking") {
|
||||||
|
return i18n.t("desktop.updates.status.checking");
|
||||||
|
}
|
||||||
|
|
||||||
if (status === "installing") {
|
if (status === "installing") {
|
||||||
return formatInstallingStatusText({ availableUpdate, downloadProgress, formatVersion });
|
return i18n.t("desktop.updates.status.installing");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (status === "up-to-date") {
|
if (status === "up-to-date") {
|
||||||
return lastCheckedAt != null
|
if (lastCheckedAt != null) {
|
||||||
? i18n.t("desktop.updates.status.upToDateWithLastChecked", {
|
return i18n.t("desktop.updates.status.upToDateWithLastChecked", {
|
||||||
time: formatLastCheckedAt(lastCheckedAt),
|
time: formatLastCheckedAt(lastCheckedAt),
|
||||||
})
|
});
|
||||||
: i18n.t("desktop.updates.status.upToDate");
|
}
|
||||||
|
return i18n.t("desktop.updates.status.upToDate");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (status === "pending") {
|
if (status === "pending") {
|
||||||
return formatPendingStatusText({
|
if (availableUpdate?.latestVersion) {
|
||||||
availableUpdate,
|
return i18n.t(
|
||||||
downloadProgress,
|
lastCheckedAt != null
|
||||||
lastCheckedAt,
|
? "desktop.updates.status.pendingWithVersionAndLastChecked"
|
||||||
formatVersion,
|
: "desktop.updates.status.pendingWithVersion",
|
||||||
formatLastCheckedAt,
|
{
|
||||||
});
|
version: formatVersion(availableUpdate.latestVersion),
|
||||||
|
time: lastCheckedAt != null ? formatLastCheckedAt(lastCheckedAt) : undefined,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (lastCheckedAt != null) {
|
||||||
|
return i18n.t("desktop.updates.status.pendingWithLastChecked", {
|
||||||
|
time: formatLastCheckedAt(lastCheckedAt),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return i18n.t("desktop.updates.status.pending");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (status === "available") {
|
if (status === "available") {
|
||||||
return formatAvailableStatusText({
|
if (availableUpdate?.latestVersion) {
|
||||||
availableUpdate,
|
return i18n.t(
|
||||||
lastCheckedAt,
|
lastCheckedAt != null
|
||||||
formatVersion,
|
? "desktop.updates.status.availableWithVersionAndLastChecked"
|
||||||
formatLastCheckedAt,
|
: "desktop.updates.status.availableWithVersion",
|
||||||
});
|
{
|
||||||
|
version: formatVersion(availableUpdate.latestVersion),
|
||||||
|
time: lastCheckedAt != null ? formatLastCheckedAt(lastCheckedAt) : undefined,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (lastCheckedAt != null) {
|
||||||
|
return i18n.t("desktop.updates.status.availableWithLastChecked", {
|
||||||
|
time: formatLastCheckedAt(lastCheckedAt),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return i18n.t("desktop.updates.status.available");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (status === "installed") {
|
if (status === "installed") {
|
||||||
return installMessage ?? i18n.t("desktop.updates.status.installed");
|
return installMessage ?? i18n.t("desktop.updates.status.installed");
|
||||||
}
|
}
|
||||||
if (status === "error") return i18n.t("desktop.updates.status.failed");
|
|
||||||
|
if (status === "error") {
|
||||||
|
return i18n.t("desktop.updates.status.failed");
|
||||||
|
}
|
||||||
|
|
||||||
return i18n.t("desktop.updates.status.idle");
|
return i18n.t("desktop.updates.status.idle");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -278,16 +202,6 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function setDownloadProgress(progress: DesktopAppUpdateDownloadProgress | null): void {
|
|
||||||
if (progress === null && state.downloadProgress === null) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
commit({
|
|
||||||
...state,
|
|
||||||
downloadProgress: progress,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async function checkForUpdates(options?: {
|
async function checkForUpdates(options?: {
|
||||||
releaseChannel: DesktopReleaseChannel;
|
releaseChannel: DesktopReleaseChannel;
|
||||||
intent?: DesktopAppUpdateCheckIntent;
|
intent?: DesktopAppUpdateCheckIntent;
|
||||||
@@ -297,7 +211,7 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
const { releaseChannel, intent = "manual", silent = false } = options;
|
const { releaseChannel, intent = "manual", silent = false } = options;
|
||||||
if (silent && (state.status === "checking" || state.isInstalling)) {
|
if (silent && state.status === "checking") {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -327,7 +241,6 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
|||||||
...state,
|
...state,
|
||||||
status: "error",
|
status: "error",
|
||||||
availableUpdate: null,
|
availableUpdate: null,
|
||||||
downloadProgress: null,
|
|
||||||
errorMessage: result.errorMessage,
|
errorMessage: result.errorMessage,
|
||||||
installMessage: null,
|
installMessage: null,
|
||||||
lastCheckedAt: nextLastCheckedAt,
|
lastCheckedAt: nextLastCheckedAt,
|
||||||
@@ -335,13 +248,24 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
const outcome = resolveCheckOutcome(result);
|
let nextStatus: DesktopAppUpdateStatus;
|
||||||
|
let nextAvailable: DesktopAppUpdateCheckResult | null;
|
||||||
|
|
||||||
|
if (result.readyToInstall) {
|
||||||
|
nextStatus = "available";
|
||||||
|
nextAvailable = result;
|
||||||
|
} else if (result.hasUpdate) {
|
||||||
|
nextStatus = "pending";
|
||||||
|
nextAvailable = result;
|
||||||
|
} else {
|
||||||
|
nextStatus = "up-to-date";
|
||||||
|
nextAvailable = null;
|
||||||
|
}
|
||||||
|
|
||||||
commit({
|
commit({
|
||||||
...state,
|
...state,
|
||||||
status: outcome.status,
|
status: nextStatus,
|
||||||
availableUpdate: outcome.availableUpdate,
|
availableUpdate: nextAvailable,
|
||||||
downloadProgress: outcome.status === "pending" ? state.downloadProgress : null,
|
|
||||||
errorMessage: null,
|
errorMessage: null,
|
||||||
installMessage: null,
|
installMessage: null,
|
||||||
lastCheckedAt: nextLastCheckedAt,
|
lastCheckedAt: nextLastCheckedAt,
|
||||||
@@ -360,7 +284,6 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
|||||||
commit({
|
commit({
|
||||||
...state,
|
...state,
|
||||||
status: "error",
|
status: "error",
|
||||||
downloadProgress: null,
|
|
||||||
errorMessage: message,
|
errorMessage: message,
|
||||||
lastCheckedAt: intent === "manual" ? deps.now() : state.lastCheckedAt,
|
lastCheckedAt: intent === "manual" ? deps.now() : state.lastCheckedAt,
|
||||||
});
|
});
|
||||||
@@ -372,10 +295,6 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
|||||||
async function installUpdate(options: {
|
async function installUpdate(options: {
|
||||||
releaseChannel: DesktopReleaseChannel;
|
releaseChannel: DesktopReleaseChannel;
|
||||||
}): Promise<DesktopAppUpdateInstallResult | null> {
|
}): Promise<DesktopAppUpdateInstallResult | null> {
|
||||||
if (state.isInstalling) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
commit({
|
commit({
|
||||||
...state,
|
...state,
|
||||||
status: "installing",
|
status: "installing",
|
||||||
@@ -388,23 +307,10 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
|||||||
releaseChannel: options.releaseChannel,
|
releaseChannel: options.releaseChannel,
|
||||||
});
|
});
|
||||||
const nextLastCheckedAt = deps.now();
|
const nextLastCheckedAt = deps.now();
|
||||||
if (!result.installed && result.errorMessage) {
|
|
||||||
commit({
|
|
||||||
...state,
|
|
||||||
status: "error",
|
|
||||||
downloadProgress: null,
|
|
||||||
errorMessage: result.errorMessage,
|
|
||||||
installMessage: null,
|
|
||||||
lastCheckedAt: nextLastCheckedAt,
|
|
||||||
isInstalling: false,
|
|
||||||
});
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
commit({
|
commit({
|
||||||
...state,
|
...state,
|
||||||
status: result.installed ? "installed" : "up-to-date",
|
status: result.installed ? "installed" : "up-to-date",
|
||||||
availableUpdate: null,
|
availableUpdate: null,
|
||||||
downloadProgress: null,
|
|
||||||
installMessage: result.message,
|
installMessage: result.message,
|
||||||
lastCheckedAt: nextLastCheckedAt,
|
lastCheckedAt: nextLastCheckedAt,
|
||||||
isInstalling: false,
|
isInstalling: false,
|
||||||
@@ -420,7 +326,6 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
|||||||
commit({
|
commit({
|
||||||
...state,
|
...state,
|
||||||
status: "error",
|
status: "error",
|
||||||
downloadProgress: null,
|
|
||||||
errorMessage: message,
|
errorMessage: message,
|
||||||
isInstalling: false,
|
isInstalling: false,
|
||||||
});
|
});
|
||||||
@@ -436,7 +341,6 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
|||||||
listeners.delete(listener);
|
listeners.delete(listener);
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
setDownloadProgress,
|
|
||||||
checkForUpdates,
|
checkForUpdates,
|
||||||
installUpdate,
|
installUpdate,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,21 +1,11 @@
|
|||||||
import { isElectronRuntime } from "@/desktop/host";
|
import { isElectronRuntime } from "@/desktop/host";
|
||||||
import { listenToDesktopEvent, type DesktopEventUnlisten } from "@/desktop/electron/events";
|
|
||||||
import { invokeDesktopCommand } from "@/desktop/electron/invoke";
|
import { invokeDesktopCommand } from "@/desktop/electron/invoke";
|
||||||
import { isWeb } from "@/constants/platform";
|
import { isWeb } from "@/constants/platform";
|
||||||
import { i18n } from "@/i18n/i18next";
|
import { i18n } from "@/i18n/i18next";
|
||||||
|
|
||||||
export interface DesktopAppUpdateDownloadProgress {
|
|
||||||
version: string | null;
|
|
||||||
percent: number;
|
|
||||||
transferred: number;
|
|
||||||
total: number;
|
|
||||||
bytesPerSecond: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface DesktopAppUpdateCheckResult {
|
export interface DesktopAppUpdateCheckResult {
|
||||||
hasUpdate: boolean;
|
hasUpdate: boolean;
|
||||||
readyToInstall: boolean;
|
readyToInstall: boolean;
|
||||||
downloading: boolean;
|
|
||||||
currentVersion: string | null;
|
currentVersion: string | null;
|
||||||
latestVersion: string | null;
|
latestVersion: string | null;
|
||||||
body: string | null;
|
body: string | null;
|
||||||
@@ -27,7 +17,6 @@ export interface DesktopAppUpdateInstallResult {
|
|||||||
installed: boolean;
|
installed: boolean;
|
||||||
version: string | null;
|
version: string | null;
|
||||||
message: string;
|
message: string;
|
||||||
errorMessage?: string | null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface DesktopRuntimeInfo {
|
export interface DesktopRuntimeInfo {
|
||||||
@@ -126,13 +115,9 @@ export async function checkDesktopAppUpdate({
|
|||||||
throw new Error("Unexpected response while checking desktop updates.");
|
throw new Error("Unexpected response while checking desktop updates.");
|
||||||
}
|
}
|
||||||
|
|
||||||
const hasUpdate = result.hasUpdate === true;
|
|
||||||
const readyToInstall = result.readyToInstall === true;
|
|
||||||
return {
|
return {
|
||||||
hasUpdate,
|
hasUpdate: result.hasUpdate === true,
|
||||||
readyToInstall,
|
readyToInstall: result.readyToInstall === true,
|
||||||
downloading:
|
|
||||||
typeof result.downloading === "boolean" ? result.downloading : hasUpdate && !readyToInstall,
|
|
||||||
currentVersion: toStringOrNull(result.currentVersion),
|
currentVersion: toStringOrNull(result.currentVersion),
|
||||||
latestVersion: toStringOrNull(result.latestVersion),
|
latestVersion: toStringOrNull(result.latestVersion),
|
||||||
body: toStringOrNull(result.body),
|
body: toStringOrNull(result.body),
|
||||||
@@ -141,36 +126,6 @@ export async function checkDesktopAppUpdate({
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function parseDesktopAppUpdateDownloadProgress(
|
|
||||||
raw: unknown,
|
|
||||||
): DesktopAppUpdateDownloadProgress | null {
|
|
||||||
if (!isRecord(raw)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
const percent = toNumberOr(Number.NaN, raw.percent);
|
|
||||||
if (!Number.isFinite(percent)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
version: toStringOrNull(raw.version),
|
|
||||||
percent: Math.max(0, Math.min(100, percent)),
|
|
||||||
transferred: toNumberOr(0, raw.transferred),
|
|
||||||
total: toNumberOr(0, raw.total),
|
|
||||||
bytesPerSecond: toNumberOr(0, raw.bytesPerSecond),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function subscribeDesktopAppUpdateDownloadProgress(
|
|
||||||
handler: (progress: DesktopAppUpdateDownloadProgress | null) => void,
|
|
||||||
): Promise<DesktopEventUnlisten> {
|
|
||||||
if (!shouldShowDesktopUpdateSection()) {
|
|
||||||
return () => {};
|
|
||||||
}
|
|
||||||
return listenToDesktopEvent<unknown>("app-update-download-progress", (payload) => {
|
|
||||||
handler(payload === null ? null : parseDesktopAppUpdateDownloadProgress(payload));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function installDesktopAppUpdate({
|
export async function installDesktopAppUpdate({
|
||||||
releaseChannel,
|
releaseChannel,
|
||||||
}: {
|
}: {
|
||||||
@@ -181,12 +136,10 @@ export async function installDesktopAppUpdate({
|
|||||||
throw new Error("Unexpected response while installing desktop update.");
|
throw new Error("Unexpected response while installing desktop update.");
|
||||||
}
|
}
|
||||||
|
|
||||||
const errorMessage = toStringOrNull(result.errorMessage);
|
|
||||||
return {
|
return {
|
||||||
installed: result.installed === true,
|
installed: result.installed === true,
|
||||||
version: toStringOrNull(result.version),
|
version: toStringOrNull(result.version),
|
||||||
message: toStringOrNull(result.message) ?? i18n.t("desktop.updates.status.installed"),
|
message: toStringOrNull(result.message) ?? i18n.t("desktop.updates.status.installed"),
|
||||||
...(errorMessage ? { errorMessage } : {}),
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -76,50 +76,6 @@ describe("resolveUpdateCalloutDescriptor", () => {
|
|||||||
expect(descriptor?.dismissalKey).toBe("desktop-update:installing:1.2.3");
|
expect(descriptor?.dismissalKey).toBe("desktop-update:installing:1.2.3");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("labels the callout as Download when the update has not been downloaded yet", () => {
|
|
||||||
const descriptor = resolveUpdateCalloutDescriptor(
|
|
||||||
input({ availableUpdate: { latestVersion: "1.2.3", readyToInstall: false } }),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(descriptor?.title).toBe("Update available");
|
|
||||||
expect(descriptor?.body).toEqual({
|
|
||||||
kind: "available",
|
|
||||||
versionLabel: "v1.2.3",
|
|
||||||
readyToInstall: false,
|
|
||||||
});
|
|
||||||
expect(descriptor?.actions).toEqual([
|
|
||||||
{ role: "changelog", label: "What's new" },
|
|
||||||
{ role: "install", label: "Download", variant: "primary", disabled: false },
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("shows download progress while downloading an update", () => {
|
|
||||||
const descriptor = resolveUpdateCalloutDescriptor(
|
|
||||||
input({
|
|
||||||
status: "installing",
|
|
||||||
isInstalling: true,
|
|
||||||
downloadProgress: {
|
|
||||||
version: "1.2.3",
|
|
||||||
percent: 42.2,
|
|
||||||
transferred: 42,
|
|
||||||
total: 100,
|
|
||||||
bytesPerSecond: 10,
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(descriptor?.title).toBe("Downloading update");
|
|
||||||
expect(descriptor?.body).toEqual({
|
|
||||||
kind: "downloading",
|
|
||||||
versionLabel: "v1.2.3",
|
|
||||||
percent: 42,
|
|
||||||
});
|
|
||||||
expect(descriptor?.actions).toEqual([
|
|
||||||
{ role: "changelog", label: "What's new" },
|
|
||||||
{ role: "install", label: "Downloading...", variant: "primary", disabled: true },
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("shows a retry action and surfaces the error message on error", () => {
|
it("shows a retry action and surfaces the error message on error", () => {
|
||||||
const descriptor = resolveUpdateCalloutDescriptor(
|
const descriptor = resolveUpdateCalloutDescriptor(
|
||||||
input({ status: "error", errorMessage: "Download failed", availableUpdate: null }),
|
input({ status: "error", errorMessage: "Download failed", availableUpdate: null }),
|
||||||
|
|||||||
@@ -1,10 +1,8 @@
|
|||||||
import type { DesktopAppUpdateStatus } from "@/desktop/updates/use-desktop-app-updater";
|
import type { DesktopAppUpdateStatus } from "@/desktop/updates/use-desktop-app-updater";
|
||||||
import type { DesktopAppUpdateDownloadProgress } from "@/desktop/updates/desktop-updates";
|
|
||||||
import { i18n } from "@/i18n/i18next";
|
import { i18n } from "@/i18n/i18next";
|
||||||
|
|
||||||
export type UpdateCalloutBody =
|
export type UpdateCalloutBody =
|
||||||
| { kind: "available"; versionLabel: string | null; readyToInstall?: boolean }
|
| { kind: "available"; versionLabel: string | null }
|
||||||
| { kind: "downloading"; versionLabel: string | null; percent: number }
|
|
||||||
| { kind: "installing" }
|
| { kind: "installing" }
|
||||||
| { kind: "error"; message: string };
|
| { kind: "error"; message: string };
|
||||||
|
|
||||||
@@ -33,8 +31,7 @@ export interface ResolveUpdateCalloutInput {
|
|||||||
isDesktopApp: boolean;
|
isDesktopApp: boolean;
|
||||||
status: DesktopAppUpdateStatus;
|
status: DesktopAppUpdateStatus;
|
||||||
isInstalling: boolean;
|
isInstalling: boolean;
|
||||||
availableUpdate: { latestVersion?: string | null; readyToInstall?: boolean } | null;
|
availableUpdate: { latestVersion?: string | null } | null;
|
||||||
downloadProgress?: DesktopAppUpdateDownloadProgress | null;
|
|
||||||
errorMessage: string | null;
|
errorMessage: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -43,59 +40,6 @@ function formatVersionLabel(latestVersion: string | null | undefined): string |
|
|||||||
return `v${latestVersion.replace(/^v/i, "")}`;
|
return `v${latestVersion.replace(/^v/i, "")}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function resolveCalloutPresentation(input: {
|
|
||||||
isError: boolean;
|
|
||||||
isInstalling: boolean;
|
|
||||||
readyToInstall: boolean;
|
|
||||||
latestVersion: string | null;
|
|
||||||
downloadProgress: DesktopAppUpdateDownloadProgress | null | undefined;
|
|
||||||
errorMessage: string | null;
|
|
||||||
}): { title: string; body: UpdateCalloutBody } {
|
|
||||||
if (input.isInstalling && input.downloadProgress != null) {
|
|
||||||
return {
|
|
||||||
title: i18n.t("desktop.updates.callout.downloadingTitle"),
|
|
||||||
body: {
|
|
||||||
kind: "downloading",
|
|
||||||
versionLabel: formatVersionLabel(input.latestVersion),
|
|
||||||
percent: Math.round(input.downloadProgress.percent),
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
if (input.isInstalling) {
|
|
||||||
return {
|
|
||||||
title: i18n.t("desktop.updates.callout.installingTitle"),
|
|
||||||
body: { kind: "installing" },
|
|
||||||
};
|
|
||||||
}
|
|
||||||
if (input.isError) {
|
|
||||||
return {
|
|
||||||
title: i18n.t("desktop.updates.callout.failedTitle"),
|
|
||||||
body: {
|
|
||||||
kind: "error",
|
|
||||||
message: input.errorMessage ?? i18n.t("desktop.updates.callout.genericError"),
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
const versionLabel = formatVersionLabel(input.latestVersion);
|
|
||||||
return {
|
|
||||||
title: i18n.t("desktop.updates.callout.availableTitle"),
|
|
||||||
body: input.readyToInstall
|
|
||||||
? { kind: "available", versionLabel }
|
|
||||||
: { kind: "available", versionLabel, readyToInstall: false },
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function resolveInstallActionLabel(input: {
|
|
||||||
isDownloading: boolean;
|
|
||||||
isInstalling: boolean;
|
|
||||||
readyToInstall: boolean;
|
|
||||||
}): string {
|
|
||||||
if (input.isDownloading) return i18n.t("desktop.updates.callout.downloadingAction");
|
|
||||||
if (input.isInstalling) return i18n.t("desktop.updates.callout.installingAction");
|
|
||||||
if (input.readyToInstall) return i18n.t("desktop.updates.callout.installAndRestart");
|
|
||||||
return i18n.t("desktop.updates.callout.downloadAndRestart");
|
|
||||||
}
|
|
||||||
|
|
||||||
export function resolveUpdateCalloutDescriptor(
|
export function resolveUpdateCalloutDescriptor(
|
||||||
input: ResolveUpdateCalloutInput,
|
input: ResolveUpdateCalloutInput,
|
||||||
): UpdateCalloutDescriptor | null {
|
): UpdateCalloutDescriptor | null {
|
||||||
@@ -106,22 +50,26 @@ export function resolveUpdateCalloutDescriptor(
|
|||||||
|
|
||||||
const isError = input.status === "error";
|
const isError = input.status === "error";
|
||||||
const isInstalling = input.isInstalling;
|
const isInstalling = input.isInstalling;
|
||||||
const isDownloading = isInstalling && input.downloadProgress != null;
|
|
||||||
const isAvailable = !isInstalling && !isError;
|
const isAvailable = !isInstalling && !isError;
|
||||||
const readyToInstall = input.availableUpdate?.readyToInstall !== false;
|
|
||||||
|
|
||||||
const latestVersion =
|
const latestVersion = input.availableUpdate?.latestVersion ?? null;
|
||||||
input.availableUpdate?.latestVersion ?? input.downloadProgress?.version ?? null;
|
|
||||||
const dismissalKey = `desktop-update:${input.status}:${latestVersion ?? "unknown"}`;
|
const dismissalKey = `desktop-update:${input.status}:${latestVersion ?? "unknown"}`;
|
||||||
|
|
||||||
const { title, body } = resolveCalloutPresentation({
|
let title: string;
|
||||||
isError,
|
let body: UpdateCalloutBody;
|
||||||
isInstalling,
|
if (isInstalling) {
|
||||||
readyToInstall,
|
title = i18n.t("desktop.updates.callout.installingTitle");
|
||||||
latestVersion,
|
body = { kind: "installing" };
|
||||||
downloadProgress: input.downloadProgress,
|
} else if (isError) {
|
||||||
errorMessage: input.errorMessage,
|
title = i18n.t("desktop.updates.callout.failedTitle");
|
||||||
});
|
body = {
|
||||||
|
kind: "error",
|
||||||
|
message: input.errorMessage ?? i18n.t("desktop.updates.callout.genericError"),
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
title = i18n.t("desktop.updates.callout.availableTitle");
|
||||||
|
body = { kind: "available", versionLabel: formatVersionLabel(latestVersion) };
|
||||||
|
}
|
||||||
|
|
||||||
const actions: UpdateCalloutActionDescriptor[] = [
|
const actions: UpdateCalloutActionDescriptor[] = [
|
||||||
{ role: "changelog", label: i18n.t("desktop.updates.callout.whatsNew") },
|
{ role: "changelog", label: i18n.t("desktop.updates.callout.whatsNew") },
|
||||||
@@ -131,7 +79,9 @@ export function resolveUpdateCalloutDescriptor(
|
|||||||
} else {
|
} else {
|
||||||
actions.push({
|
actions.push({
|
||||||
role: "install",
|
role: "install",
|
||||||
label: resolveInstallActionLabel({ isDownloading, isInstalling, readyToInstall }),
|
label: isInstalling
|
||||||
|
? i18n.t("desktop.updates.callout.installingAction")
|
||||||
|
: i18n.t("desktop.updates.callout.installAndRestart"),
|
||||||
variant: "primary",
|
variant: "primary",
|
||||||
disabled: isInstalling,
|
disabled: isInstalling,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -34,12 +34,9 @@ type InstallOutcome =
|
|||||||
function buildCheckResult(
|
function buildCheckResult(
|
||||||
overrides: Partial<DesktopAppUpdateCheckResult> = {},
|
overrides: Partial<DesktopAppUpdateCheckResult> = {},
|
||||||
): DesktopAppUpdateCheckResult {
|
): DesktopAppUpdateCheckResult {
|
||||||
const hasUpdate = overrides.hasUpdate ?? false;
|
|
||||||
const readyToInstall = overrides.readyToInstall ?? false;
|
|
||||||
return {
|
return {
|
||||||
hasUpdate,
|
hasUpdate: false,
|
||||||
readyToInstall,
|
readyToInstall: false,
|
||||||
downloading: overrides.downloading ?? (hasUpdate && !readyToInstall),
|
|
||||||
currentVersion: null,
|
currentVersion: null,
|
||||||
latestVersion: null,
|
latestVersion: null,
|
||||||
body: null,
|
body: null,
|
||||||
|
|||||||
@@ -1,8 +1,7 @@
|
|||||||
import { Gift } from "lucide-react-native";
|
import { Gift } from "lucide-react-native";
|
||||||
import { type ReactNode, useEffect, useMemo, useRef } from "react";
|
import { type ReactNode, useEffect, useRef } from "react";
|
||||||
import { View } from "react-native";
|
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { StyleSheet, useUnistyles } from "react-native-unistyles";
|
import { useUnistyles } from "react-native-unistyles";
|
||||||
import {
|
import {
|
||||||
type SidebarCalloutAction,
|
type SidebarCalloutAction,
|
||||||
SidebarCalloutDescriptionText,
|
SidebarCalloutDescriptionText,
|
||||||
@@ -20,24 +19,9 @@ import { openChangelog } from "@/changelog";
|
|||||||
const CHECK_INTERVAL_MS = 30 * 60 * 1000;
|
const CHECK_INTERVAL_MS = 30 * 60 * 1000;
|
||||||
|
|
||||||
function renderBody(body: UpdateCalloutBody, t: ReturnType<typeof useTranslation>["t"]): ReactNode {
|
function renderBody(body: UpdateCalloutBody, t: ReturnType<typeof useTranslation>["t"]): ReactNode {
|
||||||
if (body.kind === "downloading") {
|
|
||||||
return (
|
|
||||||
<UpdateDownloadingDescription
|
|
||||||
versionLabel={body.versionLabel ?? undefined}
|
|
||||||
percent={body.percent}
|
|
||||||
t={t}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (body.kind === "installing") return t("desktop.updates.callout.installingDescription");
|
if (body.kind === "installing") return t("desktop.updates.callout.installingDescription");
|
||||||
if (body.kind === "error") return body.message;
|
if (body.kind === "error") return body.message;
|
||||||
return (
|
return <UpdateAvailableDescription versionLabel={body.versionLabel ?? undefined} t={t} />;
|
||||||
<UpdateAvailableDescription
|
|
||||||
versionLabel={body.versionLabel ?? undefined}
|
|
||||||
readyToInstall={body.readyToInstall !== false}
|
|
||||||
t={t}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function materializeActions(
|
function materializeActions(
|
||||||
@@ -58,11 +42,8 @@ export function UpdateCalloutSource() {
|
|||||||
const { theme } = useUnistyles();
|
const { theme } = useUnistyles();
|
||||||
const {
|
const {
|
||||||
isDesktopApp,
|
isDesktopApp,
|
||||||
updateMode,
|
|
||||||
isLoadingSettings,
|
|
||||||
status,
|
status,
|
||||||
availableUpdate,
|
availableUpdate,
|
||||||
downloadProgress,
|
|
||||||
errorMessage,
|
errorMessage,
|
||||||
checkForUpdates,
|
checkForUpdates,
|
||||||
installUpdate,
|
installUpdate,
|
||||||
@@ -77,7 +58,7 @@ export function UpdateCalloutSource() {
|
|||||||
void checkForUpdates();
|
void checkForUpdates();
|
||||||
});
|
});
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isDesktopApp || isLoadingSettings || updateMode === "off") return;
|
if (!isDesktopApp) return;
|
||||||
|
|
||||||
void checkForUpdates({ intent: "automatic", silent: true });
|
void checkForUpdates({ intent: "automatic", silent: true });
|
||||||
|
|
||||||
@@ -90,7 +71,7 @@ export function UpdateCalloutSource() {
|
|||||||
clearInterval(intervalRef.current);
|
clearInterval(intervalRef.current);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}, [isDesktopApp, isLoadingSettings, updateMode, checkForUpdates]);
|
}, [isDesktopApp, checkForUpdates]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const descriptor = resolveUpdateCalloutDescriptor({
|
const descriptor = resolveUpdateCalloutDescriptor({
|
||||||
@@ -98,7 +79,6 @@ export function UpdateCalloutSource() {
|
|||||||
status,
|
status,
|
||||||
isInstalling,
|
isInstalling,
|
||||||
availableUpdate,
|
availableUpdate,
|
||||||
downloadProgress,
|
|
||||||
errorMessage,
|
errorMessage,
|
||||||
});
|
});
|
||||||
if (!descriptor) return;
|
if (!descriptor) return;
|
||||||
@@ -123,7 +103,6 @@ export function UpdateCalloutSource() {
|
|||||||
}, [
|
}, [
|
||||||
availableUpdate,
|
availableUpdate,
|
||||||
callouts,
|
callouts,
|
||||||
downloadProgress,
|
|
||||||
errorMessage,
|
errorMessage,
|
||||||
install,
|
install,
|
||||||
isDesktopApp,
|
isDesktopApp,
|
||||||
@@ -138,94 +117,23 @@ export function UpdateCalloutSource() {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatAvailableSummary(
|
|
||||||
t: ReturnType<typeof useTranslation>["t"],
|
|
||||||
versionLabel: string | undefined,
|
|
||||||
readyToInstall: boolean,
|
|
||||||
): string {
|
|
||||||
if (readyToInstall) {
|
|
||||||
return versionLabel
|
|
||||||
? t("desktop.updates.callout.versionReady", { version: versionLabel })
|
|
||||||
: t("desktop.updates.callout.newVersionReady");
|
|
||||||
}
|
|
||||||
return versionLabel
|
|
||||||
? t("desktop.updates.callout.versionAvailable", { version: versionLabel })
|
|
||||||
: t("desktop.updates.callout.newVersionAvailable");
|
|
||||||
}
|
|
||||||
|
|
||||||
function UpdateAvailableDescription({
|
function UpdateAvailableDescription({
|
||||||
versionLabel,
|
versionLabel,
|
||||||
readyToInstall,
|
|
||||||
t,
|
t,
|
||||||
}: {
|
}: {
|
||||||
versionLabel?: string;
|
versionLabel?: string;
|
||||||
readyToInstall: boolean;
|
|
||||||
t: ReturnType<typeof useTranslation>["t"];
|
t: ReturnType<typeof useTranslation>["t"];
|
||||||
}) {
|
}) {
|
||||||
const summary = formatAvailableSummary(t, versionLabel, readyToInstall);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<SidebarCalloutDescriptionText>{summary}</SidebarCalloutDescriptionText>
|
<SidebarCalloutDescriptionText>
|
||||||
|
{versionLabel
|
||||||
|
? t("desktop.updates.callout.versionReady", { version: versionLabel })
|
||||||
|
: t("desktop.updates.callout.newVersionReady")}
|
||||||
|
</SidebarCalloutDescriptionText>
|
||||||
<SidebarCalloutDescriptionText>
|
<SidebarCalloutDescriptionText>
|
||||||
{t("desktop.updates.callout.restartWarning")}
|
{t("desktop.updates.callout.restartWarning")}
|
||||||
</SidebarCalloutDescriptionText>
|
</SidebarCalloutDescriptionText>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function UpdateDownloadingDescription({
|
|
||||||
versionLabel,
|
|
||||||
percent,
|
|
||||||
t,
|
|
||||||
}: {
|
|
||||||
versionLabel?: string;
|
|
||||||
percent: number;
|
|
||||||
t: ReturnType<typeof useTranslation>["t"];
|
|
||||||
}) {
|
|
||||||
const clampedPercent = Math.max(0, Math.min(100, percent));
|
|
||||||
const accessibilityValue = useMemo(
|
|
||||||
() => ({ min: 0, max: 100, now: clampedPercent }),
|
|
||||||
[clampedPercent],
|
|
||||||
);
|
|
||||||
const progressFillStyle = useMemo(
|
|
||||||
() => [styles.progressFill, { width: `${clampedPercent}%` as const }],
|
|
||||||
[clampedPercent],
|
|
||||||
);
|
|
||||||
return (
|
|
||||||
<View style={styles.progressContainer}>
|
|
||||||
<SidebarCalloutDescriptionText>
|
|
||||||
{versionLabel
|
|
||||||
? t("desktop.updates.callout.downloadingVersionDescription", {
|
|
||||||
version: versionLabel,
|
|
||||||
percent: clampedPercent,
|
|
||||||
})
|
|
||||||
: t("desktop.updates.callout.downloadingDescription", { percent: clampedPercent })}
|
|
||||||
</SidebarCalloutDescriptionText>
|
|
||||||
<View
|
|
||||||
style={styles.progressTrack}
|
|
||||||
accessibilityRole="progressbar"
|
|
||||||
accessibilityValue={accessibilityValue}
|
|
||||||
>
|
|
||||||
<View style={progressFillStyle} />
|
|
||||||
</View>
|
|
||||||
</View>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const styles = StyleSheet.create((theme) => ({
|
|
||||||
progressContainer: {
|
|
||||||
gap: theme.spacing[2],
|
|
||||||
},
|
|
||||||
progressTrack: {
|
|
||||||
height: 4,
|
|
||||||
borderRadius: theme.borderRadius.full,
|
|
||||||
backgroundColor: theme.colors.surface3,
|
|
||||||
overflow: "hidden",
|
|
||||||
},
|
|
||||||
progressFill: {
|
|
||||||
height: "100%",
|
|
||||||
borderRadius: theme.borderRadius.full,
|
|
||||||
backgroundColor: theme.colors.accent,
|
|
||||||
},
|
|
||||||
}));
|
|
||||||
|
|||||||
@@ -1,94 +1,30 @@
|
|||||||
import { useCallback, useEffect, useSyncExternalStore } from "react";
|
import { useCallback, useEffect, useMemo, useSyncExternalStore } from "react";
|
||||||
import {
|
import {
|
||||||
checkDesktopAppUpdate,
|
checkDesktopAppUpdate,
|
||||||
formatVersionWithPrefix,
|
formatVersionWithPrefix,
|
||||||
installDesktopAppUpdate,
|
installDesktopAppUpdate,
|
||||||
shouldShowDesktopUpdateSection,
|
shouldShowDesktopUpdateSection,
|
||||||
subscribeDesktopAppUpdateDownloadProgress,
|
|
||||||
type DesktopAppUpdateCheckResult,
|
type DesktopAppUpdateCheckResult,
|
||||||
type DesktopAppUpdateCheckIntent,
|
type DesktopAppUpdateCheckIntent,
|
||||||
type DesktopAppUpdateDownloadProgress,
|
|
||||||
type DesktopAppUpdateInstallResult,
|
type DesktopAppUpdateInstallResult,
|
||||||
} from "@/desktop/updates/desktop-updates";
|
} from "@/desktop/updates/desktop-updates";
|
||||||
import { useDesktopSettings, type DesktopUpdateMode } from "@/desktop/settings/desktop-settings";
|
import { useDesktopSettings } from "@/desktop/settings/desktop-settings";
|
||||||
import { useDesktopIpcErrorReporter } from "@/desktop/hooks/desktop-ipc-error";
|
import { useDesktopIpcErrorReporter } from "@/desktop/hooks/desktop-ipc-error";
|
||||||
import {
|
import {
|
||||||
PENDING_RECHECK_MS,
|
PENDING_RECHECK_MS,
|
||||||
createDesktopAppUpdater,
|
createDesktopAppUpdater,
|
||||||
formatStatusText,
|
formatStatusText,
|
||||||
type DesktopAppUpdater,
|
|
||||||
type DesktopAppUpdaterErrorReport,
|
|
||||||
type DesktopAppUpdateStatus,
|
type DesktopAppUpdateStatus,
|
||||||
} from "@/desktop/updates/desktop-app-updater";
|
} from "@/desktop/updates/desktop-app-updater";
|
||||||
import { formatMessageTimestamp } from "@/utils/time";
|
import { formatMessageTimestamp } from "@/utils/time";
|
||||||
|
|
||||||
export type { DesktopAppUpdateStatus };
|
export type { DesktopAppUpdateStatus };
|
||||||
|
|
||||||
let activeInstallErrorReporter: ((report: DesktopAppUpdaterErrorReport) => void) | null = null;
|
|
||||||
let sharedDesktopAppUpdater: DesktopAppUpdater | null = null;
|
|
||||||
let progressSubscriptionCount = 0;
|
|
||||||
let progressUnsubscribe: (() => void) | null = null;
|
|
||||||
|
|
||||||
function getSharedDesktopAppUpdater(): DesktopAppUpdater {
|
|
||||||
if (!sharedDesktopAppUpdater) {
|
|
||||||
sharedDesktopAppUpdater = createDesktopAppUpdater({
|
|
||||||
port: {
|
|
||||||
checkDesktopAppUpdate,
|
|
||||||
installDesktopAppUpdate,
|
|
||||||
},
|
|
||||||
now: () => Date.now(),
|
|
||||||
reportInstallError: (report) => {
|
|
||||||
activeInstallErrorReporter?.(report);
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return sharedDesktopAppUpdater;
|
|
||||||
}
|
|
||||||
|
|
||||||
function retainDownloadProgressSubscription(updater: DesktopAppUpdater): () => void {
|
|
||||||
progressSubscriptionCount += 1;
|
|
||||||
if (progressSubscriptionCount === 1) {
|
|
||||||
let active = true;
|
|
||||||
const teardown = () => {
|
|
||||||
active = false;
|
|
||||||
};
|
|
||||||
progressUnsubscribe = teardown;
|
|
||||||
void subscribeDesktopAppUpdateDownloadProgress((progress) => {
|
|
||||||
if (active) {
|
|
||||||
updater.setDownloadProgress(progress);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.then((cleanup) => {
|
|
||||||
if (active) {
|
|
||||||
progressUnsubscribe = () => {
|
|
||||||
active = false;
|
|
||||||
cleanup();
|
|
||||||
};
|
|
||||||
} else {
|
|
||||||
cleanup();
|
|
||||||
}
|
|
||||||
return undefined;
|
|
||||||
})
|
|
||||||
.catch(() => undefined);
|
|
||||||
}
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
progressSubscriptionCount = Math.max(0, progressSubscriptionCount - 1);
|
|
||||||
if (progressSubscriptionCount === 0) {
|
|
||||||
progressUnsubscribe?.();
|
|
||||||
progressUnsubscribe = null;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface UseDesktopAppUpdaterReturn {
|
export interface UseDesktopAppUpdaterReturn {
|
||||||
isDesktopApp: boolean;
|
isDesktopApp: boolean;
|
||||||
updateMode: DesktopUpdateMode;
|
|
||||||
isLoadingSettings: boolean;
|
|
||||||
status: DesktopAppUpdateStatus;
|
status: DesktopAppUpdateStatus;
|
||||||
statusText: string;
|
statusText: string;
|
||||||
availableUpdate: DesktopAppUpdateCheckResult | null;
|
availableUpdate: DesktopAppUpdateCheckResult | null;
|
||||||
downloadProgress: DesktopAppUpdateDownloadProgress | null;
|
|
||||||
errorMessage: string | null;
|
errorMessage: string | null;
|
||||||
lastCheckedAt: number | null;
|
lastCheckedAt: number | null;
|
||||||
isChecking: boolean;
|
isChecking: boolean;
|
||||||
@@ -102,15 +38,22 @@ export interface UseDesktopAppUpdaterReturn {
|
|||||||
|
|
||||||
export function useDesktopAppUpdater(): UseDesktopAppUpdaterReturn {
|
export function useDesktopAppUpdater(): UseDesktopAppUpdaterReturn {
|
||||||
const isDesktopApp = shouldShowDesktopUpdateSection();
|
const isDesktopApp = shouldShowDesktopUpdateSection();
|
||||||
const { settings: desktopSettings, isLoading: isLoadingSettings } = useDesktopSettings();
|
const { settings: desktopSettings } = useDesktopSettings();
|
||||||
const releaseChannel = desktopSettings.releaseChannel;
|
const releaseChannel = desktopSettings.releaseChannel;
|
||||||
const updateMode = desktopSettings.updates.mode;
|
|
||||||
const reportError = useDesktopIpcErrorReporter();
|
const reportError = useDesktopIpcErrorReporter();
|
||||||
const updater = getSharedDesktopAppUpdater();
|
|
||||||
|
|
||||||
useEffect(() => {
|
const updater = useMemo(
|
||||||
activeInstallErrorReporter = reportError;
|
() =>
|
||||||
}, [reportError]);
|
createDesktopAppUpdater({
|
||||||
|
port: {
|
||||||
|
checkDesktopAppUpdate,
|
||||||
|
installDesktopAppUpdate,
|
||||||
|
},
|
||||||
|
now: () => Date.now(),
|
||||||
|
reportInstallError: reportError,
|
||||||
|
}),
|
||||||
|
[reportError],
|
||||||
|
);
|
||||||
|
|
||||||
const snapshot = useSyncExternalStore(
|
const snapshot = useSyncExternalStore(
|
||||||
updater.subscribe,
|
updater.subscribe,
|
||||||
@@ -141,20 +84,13 @@ export function useDesktopAppUpdater(): UseDesktopAppUpdaterReturn {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isDesktopApp) {
|
if (!isDesktopApp) {
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
return retainDownloadProgressSubscription(updater);
|
|
||||||
}, [isDesktopApp, updater]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!isDesktopApp || isLoadingSettings || updateMode === "off") {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
void checkForUpdates({ intent: "automatic", silent: true });
|
void checkForUpdates({ intent: "automatic", silent: true });
|
||||||
}, [checkForUpdates, isDesktopApp, isLoadingSettings, updateMode]);
|
}, [checkForUpdates, isDesktopApp]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isDesktopApp || snapshot.status !== "pending" || updateMode === "off") {
|
if (!isDesktopApp || snapshot.status !== "pending") {
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -165,24 +101,20 @@ export function useDesktopAppUpdater(): UseDesktopAppUpdaterReturn {
|
|||||||
return () => {
|
return () => {
|
||||||
clearInterval(intervalId);
|
clearInterval(intervalId);
|
||||||
};
|
};
|
||||||
}, [checkForUpdates, isDesktopApp, snapshot.status, updateMode]);
|
}, [checkForUpdates, isDesktopApp, snapshot.status]);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
isDesktopApp,
|
isDesktopApp,
|
||||||
updateMode,
|
|
||||||
isLoadingSettings,
|
|
||||||
status: snapshot.status,
|
status: snapshot.status,
|
||||||
statusText: formatStatusText({
|
statusText: formatStatusText({
|
||||||
status: snapshot.status,
|
status: snapshot.status,
|
||||||
availableUpdate: snapshot.availableUpdate,
|
availableUpdate: snapshot.availableUpdate,
|
||||||
downloadProgress: snapshot.downloadProgress,
|
|
||||||
installMessage: snapshot.installMessage,
|
installMessage: snapshot.installMessage,
|
||||||
lastCheckedAt: snapshot.lastCheckedAt,
|
lastCheckedAt: snapshot.lastCheckedAt,
|
||||||
formatVersion: formatVersionWithPrefix,
|
formatVersion: formatVersionWithPrefix,
|
||||||
formatLastCheckedAt: (timestamp) => formatMessageTimestamp(new Date(timestamp)),
|
formatLastCheckedAt: (timestamp) => formatMessageTimestamp(new Date(timestamp)),
|
||||||
}),
|
}),
|
||||||
availableUpdate: snapshot.availableUpdate,
|
availableUpdate: snapshot.availableUpdate,
|
||||||
downloadProgress: snapshot.downloadProgress,
|
|
||||||
errorMessage: snapshot.errorMessage,
|
errorMessage: snapshot.errorMessage,
|
||||||
lastCheckedAt: snapshot.lastCheckedAt,
|
lastCheckedAt: snapshot.lastCheckedAt,
|
||||||
isChecking: snapshot.isChecking,
|
isChecking: snapshot.isChecking,
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
export { PairDeviceModal } from "./pair-device-modal";
|
||||||
|
export { WaysToConnect } from "./ways-to-connect";
|
||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
import { useMemo } from "react";
|
import { useMemo } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
|
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
|
||||||
import { PairDeviceSection } from "@/desktop/components/pair-device-section";
|
import { PairDeviceSection } from "@/devices/pair-device-section";
|
||||||
|
|
||||||
export interface PairDeviceModalProps {
|
export interface PairDeviceModalProps {
|
||||||
serverId: string;
|
serverId: string;
|
||||||
+1
-1
@@ -23,7 +23,7 @@ import {
|
|||||||
|
|
||||||
const RELAY_DOCS_URL = "https://paseo.sh/docs/security";
|
const RELAY_DOCS_URL = "https://paseo.sh/docs/security";
|
||||||
export const CONNECTIVITY_DOCS_URL = "https://paseo.sh/docs/connectivity";
|
export const CONNECTIVITY_DOCS_URL = "https://paseo.sh/docs/connectivity";
|
||||||
export const TAILSCALE_DOCS_URL = `${CONNECTIVITY_DOCS_URL}#tailscale`;
|
const TAILSCALE_DOCS_URL = `${CONNECTIVITY_DOCS_URL}#tailscale`;
|
||||||
const FLEX_ONE_STYLE = { flex: 1 } as const;
|
const FLEX_ONE_STYLE = { flex: 1 } as const;
|
||||||
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
|
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
|
||||||
const ThemedShieldCheck = withUnistyles(ShieldCheck);
|
const ThemedShieldCheck = withUnistyles(ShieldCheck);
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import type { TailscaleStatus } from "@getpaseo/protocol/messages";
|
||||||
|
import { i18n } from "@/i18n/i18next";
|
||||||
|
import { describeTailscale } from "./tailscale-hint";
|
||||||
|
|
||||||
|
// Statuses as the host reports them; see `createDaemonListeners` in the server's listeners.ts.
|
||||||
|
const off: TailscaleStatus = { ip: "100.101.102.103", address: null, state: "off" };
|
||||||
|
|
||||||
|
describe("the Tailscale row's hint", () => {
|
||||||
|
it("says why Tailscale stays off when the host listens on a socket", () => {
|
||||||
|
const socketHint = "Off, because this host listens on a local socket";
|
||||||
|
expect(describeTailscale({ ...off, lockedBy: "main", mainIsSocket: true }, i18n.t)).toBe(
|
||||||
|
socketHint,
|
||||||
|
);
|
||||||
|
expect(describeTailscale({ ...off, lockedBy: "launch", mainIsSocket: true }, i18n.t)).toBe(
|
||||||
|
socketHint,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps the hint of every other state", () => {
|
||||||
|
const hint = (status: TailscaleStatus) => describeTailscale(status, i18n.t);
|
||||||
|
expect(hint(off)).toBe("Direct over your tailnet, enter an address");
|
||||||
|
expect(hint({ ip: null, address: null, state: "unavailable", lockedBy: "launch" })).toBe(
|
||||||
|
"Tailscale is not running on this host",
|
||||||
|
);
|
||||||
|
expect(hint({ ...off, state: "waiting", address: "100.101.102.103:6767" })).toBe(
|
||||||
|
"Waiting for Tailscale to start on this host",
|
||||||
|
);
|
||||||
|
expect(hint({ ...off, state: "on", address: "100.101.102.103:6767", lockedBy: "main" })).toBe(
|
||||||
|
"Always on, because this host already accepts Tailscale connections",
|
||||||
|
);
|
||||||
|
expect(hint({ ...off, lockedBy: "launch" })).toBe(
|
||||||
|
"Controlled by the command that starts this host",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import type { TailscaleStatus } from "@getpaseo/protocol/messages";
|
||||||
|
import type { TFunction } from "i18next";
|
||||||
|
|
||||||
|
/** The line under the Tailscale label for each state the host reports, most specific first. */
|
||||||
|
export function describeTailscale(status: TailscaleStatus, t: TFunction): string {
|
||||||
|
if (status.state === "unavailable") return t("devices.tailscale.unavailable");
|
||||||
|
if (status.state === "waiting") return t("devices.tailscale.waiting");
|
||||||
|
// A socket is why Tailscale cannot be on, even when the launch command also fixes the address.
|
||||||
|
if (status.mainIsSocket) return t("devices.tailscale.socket");
|
||||||
|
if (status.lockedBy === "launch") return t("devices.tailscale.launch");
|
||||||
|
if (status.lockedBy === "main") return t("devices.tailscale.alwaysOn");
|
||||||
|
return t("devices.tailscale.hint");
|
||||||
|
}
|
||||||
@@ -0,0 +1,202 @@
|
|||||||
|
import { useCallback, useMemo } from "react";
|
||||||
|
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { SettingsAction, SettingsRowChildren, SettingsSwitch } from "@/components/settings";
|
||||||
|
import { useToast } from "@/contexts/toast-context";
|
||||||
|
import { useFetchQuery } from "@/data/query";
|
||||||
|
import { useHostRuntimeClient, useHostRuntimeSnapshot } from "@/runtime/host-runtime";
|
||||||
|
import { useSessionStore } from "@/stores/session-store";
|
||||||
|
import { confirmDialog } from "@/utils/confirm-dialog";
|
||||||
|
import { copyToClipboard } from "@/utils/copy-to-clipboard";
|
||||||
|
import { describeTailscale } from "./tailscale-hint";
|
||||||
|
|
||||||
|
const UPDATES_DOCS_URL = "https://paseo.sh/docs/updates";
|
||||||
|
const TAILSCALE_DOWNLOAD_URL = "https://tailscale.com/download";
|
||||||
|
// A product name, the same in every language.
|
||||||
|
const LABEL = "Tailscale";
|
||||||
|
|
||||||
|
type HostClient = NonNullable<ReturnType<typeof useHostRuntimeClient>>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Turns Tailscale on or off for a host and shows the address a phone on the tailnet adds. Renders
|
||||||
|
* as a row inside a `SettingsCard`; when Tailscale is on, the address is a nested row under it.
|
||||||
|
*/
|
||||||
|
export function TailscaleRow({ serverId }: { serverId: string }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const client = useHostRuntimeClient(serverId);
|
||||||
|
const connection = useHostRuntimeSnapshot(serverId)?.connectionStatus;
|
||||||
|
const serverInfo = useSessionStore((state) => state.sessions[serverId]?.serverInfo);
|
||||||
|
const updateLink = useMemo(
|
||||||
|
() => ({ href: UPDATES_DOCS_URL, label: t("devices.tailscale.updateDocs") }),
|
||||||
|
[t],
|
||||||
|
);
|
||||||
|
// COMPAT(tailscale): added in v0.16.0, remove after 2027-05-25 once daemon floor >= v0.16.0.
|
||||||
|
if (serverInfo && serverInfo.features?.tailscale !== true) {
|
||||||
|
return (
|
||||||
|
<SettingsSwitch
|
||||||
|
label={LABEL}
|
||||||
|
hint={t("devices.tailscale.update")}
|
||||||
|
link={updateLink}
|
||||||
|
value={false}
|
||||||
|
disabled
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (client && connection === "online" && serverInfo) {
|
||||||
|
return <TailscaleControl serverId={serverId} client={client} />;
|
||||||
|
}
|
||||||
|
// Without the host the row shows no value: the switch's space stays empty. A host the app has
|
||||||
|
// reached before keeps its server info, so while the app retries it still reads as disconnected.
|
||||||
|
const lost = connection === "offline" || connection === "error" || Boolean(serverInfo);
|
||||||
|
return (
|
||||||
|
<SettingsSwitch
|
||||||
|
label={LABEL}
|
||||||
|
hint={t(lost ? "workspace.terminal.hostDisconnected" : "devices.tailscale.hint")}
|
||||||
|
value={null}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function TailscaleControl({ serverId, client }: { serverId: string; client: HostClient }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const tailscale = useTailscale(serverId, client);
|
||||||
|
const { status } = tailscale;
|
||||||
|
const installLink = useMemo(
|
||||||
|
() => ({ href: TAILSCALE_DOWNLOAD_URL, label: t("devices.tailscale.install") }),
|
||||||
|
[t],
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<SettingsSwitch
|
||||||
|
label={LABEL}
|
||||||
|
hint={status ? describeTailscale(status, t) : t("devices.tailscale.hint")}
|
||||||
|
link={status?.state === "unavailable" ? installLink : undefined}
|
||||||
|
error={tailscale.error}
|
||||||
|
value={tailscale.value}
|
||||||
|
disabled={!status || status.state === "unavailable" || Boolean(status.lockedBy)}
|
||||||
|
onValueChange={tailscale.setEnabled}
|
||||||
|
/>
|
||||||
|
{tailscale.address ? <TailscaleAddress address={tailscale.address} /> : null}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function TailscaleAddress({ address }: { address: string }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const toast = useToast();
|
||||||
|
const copy = useCallback(() => {
|
||||||
|
void copyToClipboard(address)
|
||||||
|
.then(() => toast.copied())
|
||||||
|
.catch(() => toast.error(t("common.errors.error")));
|
||||||
|
}, [address, t, toast]);
|
||||||
|
return (
|
||||||
|
<SettingsRowChildren>
|
||||||
|
<SettingsAction
|
||||||
|
label={address}
|
||||||
|
hint={t("devices.tailscale.address")}
|
||||||
|
actionLabel={t("common.actions.copy")}
|
||||||
|
onPress={copy}
|
||||||
|
testID="devices-tailscale-address"
|
||||||
|
/>
|
||||||
|
</SettingsRowChildren>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface TailscaleChange {
|
||||||
|
enabled: boolean;
|
||||||
|
confirmed: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The host's Tailscale state and the one way to change it. While a change is in flight the switch
|
||||||
|
* already shows where it is going, so a tap answers at once; the host's answer then settles it.
|
||||||
|
* Turning Tailscale off over the connection it would cut asks first, and nothing changes on screen
|
||||||
|
* until the user confirms.
|
||||||
|
*/
|
||||||
|
function useTailscale(serverId: string, client: HostClient) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const queryKey = useMemo(() => ["tailscale-status", serverId], [serverId]);
|
||||||
|
|
||||||
|
const query = useFetchQuery({
|
||||||
|
queryKey,
|
||||||
|
queryFn: async () => {
|
||||||
|
const { tailscale } = await client.getDaemonStatus({ includeProviders: false });
|
||||||
|
if (!tailscale) throw new Error("Host did not report Tailscale status");
|
||||||
|
return tailscale;
|
||||||
|
},
|
||||||
|
// Tailscale can come up after the host does; polling moves "waiting" to "on" on its own.
|
||||||
|
refetchInterval: 2_000,
|
||||||
|
staleTimeMs: 0,
|
||||||
|
dataShape: "value",
|
||||||
|
});
|
||||||
|
|
||||||
|
const change = useMutation({
|
||||||
|
mutationFn: async ({ enabled, confirmed }: TailscaleChange) => {
|
||||||
|
await queryClient.cancelQueries({ queryKey });
|
||||||
|
return client.setTailscaleEnabled(enabled, confirmed);
|
||||||
|
},
|
||||||
|
onSuccess: (result) => queryClient.setQueryData(queryKey, result.tailscale),
|
||||||
|
});
|
||||||
|
|
||||||
|
const status = query.data;
|
||||||
|
const pending = change.isPending ? change.variables.enabled : undefined;
|
||||||
|
const on = status?.state === "on" || status?.state === "waiting";
|
||||||
|
// Not known until the host first answers.
|
||||||
|
const value = pending ?? (status ? on : null);
|
||||||
|
|
||||||
|
const { mutate } = change;
|
||||||
|
const confirmTurnOff = useCallback(
|
||||||
|
() =>
|
||||||
|
confirmDialog({
|
||||||
|
title: t("devices.tailscale.confirmTitle"),
|
||||||
|
message: t("devices.tailscale.confirmMessage"),
|
||||||
|
confirmLabel: t("devices.tailscale.confirmAction"),
|
||||||
|
cancelLabel: t("common.actions.cancel"),
|
||||||
|
destructive: true,
|
||||||
|
}),
|
||||||
|
[t],
|
||||||
|
);
|
||||||
|
const turnOffConfirmed = useCallback(async () => {
|
||||||
|
if (await confirmTurnOff()) mutate({ enabled: false, confirmed: true });
|
||||||
|
}, [confirmTurnOff, mutate]);
|
||||||
|
const disconnects = status?.disconnectsCurrentConnection === true;
|
||||||
|
const setEnabled = useCallback(
|
||||||
|
(enabled: boolean) => {
|
||||||
|
if (!enabled && disconnects) {
|
||||||
|
void turnOffConfirmed();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
mutate(
|
||||||
|
{ enabled, confirmed: false },
|
||||||
|
{
|
||||||
|
// The status was stale: the host would cut this connection after all. Its answer has
|
||||||
|
// already put the row back to on, so the question is asked over what is true.
|
||||||
|
onSuccess: (result) => {
|
||||||
|
if (result.confirmationRequired) void turnOffConfirmed();
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
},
|
||||||
|
[disconnects, mutate, turnOffConfirmed],
|
||||||
|
);
|
||||||
|
|
||||||
|
let error: string | undefined;
|
||||||
|
if (change.isError) {
|
||||||
|
error = t(
|
||||||
|
change.variables.enabled ? "devices.tailscale.turnOnError" : "devices.tailscale.turnOffError",
|
||||||
|
);
|
||||||
|
} else if (query.isError && !status) {
|
||||||
|
error = t("devices.tailscale.statusError");
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
status,
|
||||||
|
value,
|
||||||
|
error,
|
||||||
|
// A tap is ignored until the host answers the one before it.
|
||||||
|
setEnabled: change.isPending ? undefined : setEnabled,
|
||||||
|
address: status?.state === "on" && value ? status.address : null,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import { useCallback, useMemo, useState } from "react";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { SettingsCard, SettingsDetailRow, SettingsSection } from "@/components/settings";
|
||||||
|
import { StatusBadge } from "@/components/ui/status-badge";
|
||||||
|
import { PairDeviceModal } from "./pair-device-modal";
|
||||||
|
import { CONNECTIVITY_DOCS_URL } from "./pair-device-section";
|
||||||
|
import { TailscaleRow } from "./tailscale-row";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The ways another device can connect to a host: Relay, which pairs through a QR code in a sheet,
|
||||||
|
* and Tailscale, a switch and an address. Settings and the setup's phone step show this same block.
|
||||||
|
*/
|
||||||
|
export function WaysToConnect({ serverId }: { serverId: string }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [pairing, setPairing] = useState(false);
|
||||||
|
const openPairing = useCallback(() => setPairing(true), []);
|
||||||
|
const closePairing = useCallback(() => setPairing(false), []);
|
||||||
|
const recommended = useMemo(
|
||||||
|
() => <StatusBadge size="xs" variant="success" label={t("devices.recommended")} />,
|
||||||
|
[t],
|
||||||
|
);
|
||||||
|
const docsLink = useMemo(
|
||||||
|
() => ({
|
||||||
|
href: CONNECTIVITY_DOCS_URL,
|
||||||
|
label: t("devices.docs"),
|
||||||
|
accessibilityLabel: t("devices.docsAccessibility"),
|
||||||
|
}),
|
||||||
|
[t],
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<SettingsSection title={t("devices.waysToConnect")} link={docsLink}>
|
||||||
|
<SettingsCard>
|
||||||
|
<SettingsDetailRow
|
||||||
|
label={t("devices.relay.title")}
|
||||||
|
labelAccessory={recommended}
|
||||||
|
hint={t("devices.relay.hint")}
|
||||||
|
onPress={openPairing}
|
||||||
|
testID="devices-relay"
|
||||||
|
/>
|
||||||
|
<TailscaleRow serverId={serverId} />
|
||||||
|
</SettingsCard>
|
||||||
|
<PairDeviceModal
|
||||||
|
serverId={serverId}
|
||||||
|
visible={pairing}
|
||||||
|
onClose={closePairing}
|
||||||
|
testID="devices-relay-pairing"
|
||||||
|
/>
|
||||||
|
</SettingsSection>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -146,3 +146,41 @@ export async function confirmRiskyWorktreeArchive(
|
|||||||
destructive: true,
|
destructive: true,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function confirmRiskyBulkWorktreeArchive(
|
||||||
|
input: {
|
||||||
|
totalCount: number;
|
||||||
|
riskyWorkspaces: readonly WorktreeArchiveConfirmationInput[];
|
||||||
|
},
|
||||||
|
labels: WorktreeArchiveWarningLabels = DEFAULT_WORKTREE_ARCHIVE_WARNING_LABELS,
|
||||||
|
): Promise<boolean> {
|
||||||
|
const lines: string[] = [];
|
||||||
|
let singleRisky: WorktreeArchiveConfirmationInput | null = null;
|
||||||
|
for (const workspace of input.riskyWorkspaces) {
|
||||||
|
const reasons = buildWorktreeArchiveRiskReasons(workspace, labels);
|
||||||
|
if (reasons.length === 0) continue;
|
||||||
|
singleRisky = workspace;
|
||||||
|
lines.push(
|
||||||
|
i18n.t("workspace.git.actions.archiveWarning.bulkWorkspaceReason", {
|
||||||
|
workspaceName: workspace.workspaceName,
|
||||||
|
reason: reasons.join(", "),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (lines.length === 0) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (input.totalCount === 1 && singleRisky) {
|
||||||
|
return await confirmRiskyWorktreeArchive(singleRisky, labels);
|
||||||
|
}
|
||||||
|
|
||||||
|
return await confirmDialog({
|
||||||
|
title: i18n.t("workspace.git.actions.archiveWarning.bulkTitle", {
|
||||||
|
count: input.totalCount,
|
||||||
|
}),
|
||||||
|
message: lines.join("\n"),
|
||||||
|
confirmLabel: labels.confirm,
|
||||||
|
cancelLabel: labels.cancel,
|
||||||
|
destructive: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user