mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-25 17:55:18 +00:00
Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cd4a72587f | ||
|
|
40b9fd4b3c | ||
|
|
79bbd80ba6 | ||
|
|
5d918a12d2 | ||
|
|
8ce42b4da7 | ||
|
|
2c639b0be0 | ||
|
|
8446b53ff0 | ||
|
|
1c7dea109a |
@@ -56,7 +56,6 @@ sdk:
|
||||
- "packages/plugin/**"
|
||||
- "plugin-examples/**"
|
||||
- "public-docs/plugins/**"
|
||||
- "skills/paseo-plugin/**"
|
||||
- "packages/client/**"
|
||||
- "packages/highlight/**"
|
||||
- "packages/protocol/**"
|
||||
|
||||
@@ -87,6 +87,10 @@ jobs:
|
||||
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.quality != 'false') }}
|
||||
run: npx --yes lockfile-lint --path package-lock.json --type npm --allowed-hosts npm --validate-https --validate-integrity
|
||||
|
||||
- name: Verify dependency signatures
|
||||
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.quality != 'false') }}
|
||||
run: npm audit signatures
|
||||
|
||||
- name: Lint
|
||||
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.quality != 'false') }}
|
||||
run: npm run lint
|
||||
|
||||
@@ -54,7 +54,6 @@ At the start of non-trivial work, list `docs/` and skim anything relevant to the
|
||||
| [docs/permissions.md](docs/permissions.md) | Semantic daemon permissions, principals, credentials, pairing invitations, and Hub authority |
|
||||
| [docs/terminal-performance.md](docs/terminal-performance.md) | Terminal latency pipeline, coalescing/backpressure invariants, benchmark + perf spec usage |
|
||||
| [docs/terminal-rendering.md](docs/terminal-rendering.md) | Native terminal view: xterm owns the grid, cluster placement, emoji widths, mixed-direction limits, render regression |
|
||||
| [docs/timeline-sync.md](docs/timeline-sync.md) | Owned agent history, rewind retirements, live stream vs authoritative fetch, paged catch-up, client replica |
|
||||
| [docs/agent-stream-performance.md](docs/agent-stream-performance.md) | Assistant text pipeline — coalescing window, paced reveal, why arrival lumps are smoothed at render |
|
||||
| [docs/agent-stream-disclosure.md](docs/agent-stream-disclosure.md) | Expand/collapse in the chat timeline — hold contract, native anchor sequence, frame spacing, render-window cost |
|
||||
| [docs/markdown-renderer.md](docs/markdown-renderer.md) | Shared Markdown engine, the vendored library fork, native selection, links, images and library constraints |
|
||||
|
||||
@@ -39,8 +39,8 @@ An unarchived agent may be `closed` without being deleted or archived. Closing r
|
||||
processes and subscriptions while retaining its Paseo identity, persistence handle, timeline,
|
||||
workspace, labels, title, usage, attention, timestamps, and parent relationship. Opening or prompting
|
||||
the agent runs through `ensureAgentLoaded()`, which resumes the durable provider session under the
|
||||
same Paseo agent ID. Resume does not read provider history when the agent already has a timeline;
|
||||
see [owned history](timeline-sync.md#owned-history).
|
||||
same Paseo agent ID. Provider history is not appended again when the canonical timeline is already
|
||||
primed.
|
||||
|
||||
Reload releases the old runtime before resuming its durable session: an idle provider process can
|
||||
still own an exclusive writer. A close failure retains that runtime for cleanup and blocks the
|
||||
@@ -256,8 +256,7 @@ lifecycle is separate from public workspace visibility and is not a public creat
|
||||
Archive is a **soft delete**: the agent record stays on disk with `archivedAt` set, the runtime is closed, and the agent disappears from active lists. Archive is **global** — it lives on the server and propagates to every connected client.
|
||||
|
||||
Archive sets `archivedAt`, invokes the provider's native archive hook, and cascades to managed
|
||||
children. The timeline and the provider children stay, so an archived chat reads them without its
|
||||
provider; deleting the agent removes them.
|
||||
children.
|
||||
|
||||
`create_agent_request` can opt an agent into `autoArchive`. In that mode the daemon archives the agent after the first terminal turn event (`turn_completed`, `turn_failed`, or `turn_canceled`). When the agent owns an isolated workspace, auto-archive archives that workspace too; the managed worktree is removed when its final workspace reference is gone.
|
||||
|
||||
@@ -353,8 +352,6 @@ Workspace status is an aggregate activity signal computed **per `workspaceId`**.
|
||||
|
||||
Running provider-native subagents contribute `running` to the workspace owned by their parent agent. Their completed, failed, and canceled states stay in the parent's subagents track.
|
||||
|
||||
Only the parent's current runtime makes a provider child running. A child's stored status is the last report about it, and that report can come from provider history or from a runtime an earlier daemon ran, so a stored `running` child does not make the workspace running or keep the parent's runtime alive. It counts again once the live session reports it running. Closing a runtime cancels the children that runtime reported running; children it never reported keep their stored status.
|
||||
|
||||
A finished or failed workspace can be marked unread after it has been reviewed. The daemon restores
|
||||
attention on its newest eligible workspace-root agent, `error` for an agent whose lifecycle is
|
||||
`error` and `finished` otherwise, without sending a new notification. Opening a workspace restores
|
||||
|
||||
@@ -94,7 +94,6 @@ workspace for a directory clears it. The store lives in memory and resets on dae
|
||||
| `server/directory-sync/` | Daemon-global latest-state sequences for projects, workspaces, and agents |
|
||||
| `server/workspace-labels/` | Host-local label catalog, assignment mutations, and explicit subscriptions |
|
||||
| `server/agent/agent-manager.ts` | Agent lifecycle state machine, timeline tracking, subscriber management |
|
||||
| `server/agent/timeline/` | Owned agent history, provider children, rewind retirements, behind a backend |
|
||||
| `server/agent/agent-storage.ts` | File-backed JSON persistence at `$PASEO_HOME/agents/` |
|
||||
| `server/agent/tools/` | Transport-neutral catalog for workspaces, agents, permissions, and automation |
|
||||
| `server/agent/mcp-server.ts` | Thin MCP adapter that registers the Paseo tool catalog with the MCP SDK |
|
||||
@@ -403,7 +402,7 @@ initializing → idle ⇄ running
|
||||
client-side dedup; the default fetch page is 200 items.
|
||||
- Timeline row `timestamp` values are canonical daemon-owned timestamps. Providers may supply original replay timestamps, but clients must not guess timestamp trust or hide time UI based on local clock heuristics.
|
||||
- Events stream to connected clients in real time; correctness is backed by authoritative timeline fetches and paged-to-completion catch-up.
|
||||
- Agent state persists to `$PASEO_HOME/agents/{cwd-with-dashes}/{agent-id}.json`. That storage path is derived from `cwd`, not from workspace id. Timeline rows persist in the daemon database, `$PASEO_HOME/paseo.db`. They are the transcript authority after the first import of provider history. See [owned history](timeline-sync.md#owned-history).
|
||||
- Agent state persists to `$PASEO_HOME/agents/{cwd-with-dashes}/{agent-id}.json`. Timeline rows are runtime memory; provider history is the durable transcript authority and resumed agents rebuild from it. That storage path is derived from `cwd`, not from workspace id.
|
||||
|
||||
## Right-sidebar boundary: directory-backed vs workspace-owned
|
||||
|
||||
@@ -479,7 +478,6 @@ Providers that can accept native tool definitions should set `supportsNativePase
|
||||
```
|
||||
$PASEO_HOME/
|
||||
├── agents/{cwd-with-dashes}/{agent-id}.json # Agent record
|
||||
├── paseo.db # Daemon database (SQLite): agent timelines
|
||||
├── projects/projects.json # Project registry
|
||||
├── projects/workspaces.json # Workspace registry
|
||||
├── projects/icons/ # Custom project icon images
|
||||
|
||||
+1
-41
@@ -34,7 +34,7 @@ Workspace archive runs lifecycle teardown from the exact `cwd` but removes only
|
||||
`worktreeRoot` after its last active reference disappears. Worktree recovery recreates that backing
|
||||
checkout from `mainRepoRoot`, then restores the relative path from `worktreeRoot` to `cwd`.
|
||||
|
||||
Paseo persists most stores as JSON files, and agent timelines in the [daemon database](#daemon-database). JSON data is validated at runtime with Zod schemas. Most JSON stores write atomically (write to temp file, then rename); a few still use plain `writeFile` — see each section. JSON stores have no schema-versioning/migration framework — schemas rely on optional fields with defaults for forward compatibility, with a small amount of inline normalization in `persisted-config.ts` for legacy provider/speech entries.
|
||||
Paseo uses **file-based JSON persistence** instead of a traditional database. All data is validated at runtime with Zod schemas. Most stores write atomically (write to temp file, then rename); a few still use plain `writeFile` — see each section. There is no schema-versioning/migration framework — schemas rely on optional fields with defaults for forward compatibility, with a small amount of inline normalization in `persisted-config.ts` for legacy provider/speech entries.
|
||||
|
||||
All server-side stores live under `$PASEO_HOME` (defaults to `~/.paseo`).
|
||||
|
||||
@@ -53,7 +53,6 @@ $PASEO_HOME/
|
||||
├── daemon-keypair.json # E2EE keypair for relay (mode 0600)
|
||||
├── paseo.pid # Daemon PID lock file
|
||||
├── local-credential # Per-run local client credential (mode 0600)
|
||||
├── paseo.db # Daemon database (SQLite, with -wal and -shm files)
|
||||
├── daemon.log # Default log file (path configurable)
|
||||
├── agents/
|
||||
│ └── {sanitized-cwd}/
|
||||
@@ -182,45 +181,6 @@ Terminal activity contributes to the workspace status bucket **per `workspaceId`
|
||||
|
||||
---
|
||||
|
||||
## Daemon database
|
||||
|
||||
`$PASEO_HOME/paseo.db` is one SQLite file that the daemon opens at startup with `node:sqlite`
|
||||
(`packages/server/src/server/database/`). Agent timelines are its only store today. Each store is a
|
||||
`SchemaModule`: its own table-name prefix and an append-only list of migrations.
|
||||
|
||||
- **Migrations.** Startup runs every module's pending migrations in one transaction, so a failed
|
||||
migration leaves the file as it was. `schema_versions` records each module's version and
|
||||
`min_reader_version`. Mark a migration `breaking` when an older daemon cannot read the result,
|
||||
for example a dropped or renamed column. An older daemon then refuses to start with
|
||||
`DatabaseSchemaTooNewError`. Additive migrations leave older daemons working, and they ignore
|
||||
modules they do not know. This matters because the app and the daemon update separately, and a
|
||||
user can run an older daemon on the same `$PASEO_HOME`.
|
||||
- **Failure.** A file that SQLite cannot open stops the daemon with `DatabaseOpenError`, which
|
||||
names the path. The daemon does not delete or recreate the file.
|
||||
- **Access.** The file holds every prompt and reply, so the daemon sets it and its `-wal` and `-shm`
|
||||
files to mode `0600` on every open. SQLite gives the WAL files it creates the mode of the database
|
||||
file.
|
||||
- **Durability.** The database uses WAL with `synchronous = NORMAL`. A power loss can drop the
|
||||
last commits but does not corrupt the file.
|
||||
- **Checkpoints.** A checkpoint syncs the file to disk and takes up to 100 ms. SQLite's
|
||||
auto-checkpoint runs it on the committing thread, which stalled the event loop during streaming.
|
||||
The daemon turns it off and checkpoints from a worker thread with its own connection. If the
|
||||
worker exits, the daemon turns auto-checkpoint back on.
|
||||
- **Transactions.** `write` and `read` callbacks are synchronous, so a transaction never spans an
|
||||
`await` and transactions never interleave.
|
||||
- **Node.** `node:sqlite` needs Node 22.16 or later. Node 22 prints an experimental warning once,
|
||||
when the daemon opens the database.
|
||||
|
||||
### Agent timelines
|
||||
|
||||
`AgentTimeline` owns each agent's history, and its SQLite backend stores the projected rows, the
|
||||
source ranges, retirements, the open rewind, and provider children in `timeline_*` tables. The text
|
||||
of a streamed assistant or reasoning message is stored as one chunk per source event, beside its
|
||||
row, so a chunk never rewrites the message. An earlier file store rewrote the whole transcript on
|
||||
every update. See [owned history](timeline-sync.md#owned-history).
|
||||
|
||||
---
|
||||
|
||||
## 2. Daemon Configuration
|
||||
|
||||
**Path:** `$PASEO_HOME/config.json`
|
||||
|
||||
+6
-6
@@ -575,9 +575,8 @@ where the overrides apply; workspace scripts still find the binary through the r
|
||||
|
||||
## Dependency signature audit
|
||||
|
||||
The [pre-release dependency checks](release.md#pre-release-dependency-checks) include
|
||||
`npm audit signatures`. The command verifies registry signatures and, for packages published
|
||||
with provenance, fetches
|
||||
The `quality` CI job runs `npm audit signatures`. It verifies every lockfile package's registry
|
||||
signature and, for packages published with provenance, fetches
|
||||
`/-/npm/v1/attestations/<name>@<version>` from the registry. Cloudflare caches that document
|
||||
for a year. An edge that cached it in the seconds before the registry attached the publish
|
||||
attestation keeps serving a document with only the provenance bundle, and npm fails with:
|
||||
@@ -588,10 +587,11 @@ npm error <name>@<version> has attestations but no corresponding public key(s) c
|
||||
```
|
||||
|
||||
The same package's registry signature verified a moment earlier with the same keys, so the
|
||||
key list is intact. The failure names one package and depends on which Cloudflare edge serves
|
||||
the cached attestation.
|
||||
key list is intact. The failure names one package, repeats only for that package, and depends
|
||||
on the Azure region the runner landed in, because each region maps to one Cloudflare colo. A
|
||||
rerun passes only by landing elsewhere.
|
||||
|
||||
To confirm, fetch the URL from several regions and compare `content-length`, the `cf-ray` colo
|
||||
To confirm, fetch the URL from several runners and compare `content-length`, the `cf-ray` colo
|
||||
suffix, and the number of `attestations` entries (#7730 has the probe). To fix, remove or
|
||||
replace that version in the lockfile. If the dependent’s range cannot be changed, pin a clean
|
||||
version in root `overrides`. Report the URL to npm so they purge it.
|
||||
|
||||
@@ -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".
|
||||
- **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).
|
||||
- **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.
|
||||
- **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.
|
||||
|
||||
@@ -883,13 +883,6 @@ its Zod schema, and mounts the component inside the normal plugin runtime and er
|
||||
optional output `id` distinguishes several stable replacements from the same source item; its output
|
||||
index is the default.
|
||||
|
||||
Each replacement keeps a reference to the source row (`source` on the projected stream item), and
|
||||
turn logic reads a replaced reply through it. A reply split into several cards stays one reply: turn
|
||||
folding keeps every card visible, and the turn footer hangs under the last card, copies the original
|
||||
reply text once, forks at its message, and shows its duration and stats. Read the reply with
|
||||
`getAssistantReply` (`packages/app/src/types/stream.ts`) instead of checking `kind ===
|
||||
"assistant_message"`.
|
||||
|
||||
Transformers run synchronously and must be deterministic. When several transformers match, the
|
||||
first one that returns a result owns that source item. Plugin and registration ordering is stable.
|
||||
See `plugin-examples/timeline-items` for the complete contract.
|
||||
|
||||
+11
-33
@@ -17,7 +17,6 @@ A release has exactly two steps. The agent does the first, the user authorizes t
|
||||
run `npm run release:prep:<mode>` to create the `chore(release): cut <version>` commit without a tag
|
||||
- push the `release/vX.Y.Z` or `release/vX.Y.Z-beta.N` branch and confirm its `CI` and
|
||||
`Desktop Packages` runs pass (never wait on `main` CI)
|
||||
- run the [pre-release dependency checks](#pre-release-dependency-checks) on the release commit
|
||||
|
||||
**Go-ahead** (user says "go ahead"):
|
||||
|
||||
@@ -108,7 +107,6 @@ An explicit user instruction can select another base.
|
||||
`CI` (all 21 jobs) and `Desktop Packages` (Linux user-namespace smoke) in their own concurrency
|
||||
groups, isolated from `main` traffic. Never wait on `main` CI, because `main` cancels in-progress
|
||||
runs on every merge. Wait for both runs on the release branch commit to pass before shipping.
|
||||
Complete the [pre-release dependency checks](#pre-release-dependency-checks) on that commit.
|
||||
Pushing a `release/**` branch without a `v*` tag triggers no publish workflows.
|
||||
6. After go-ahead, run `npm run release:ship` (stable) or `npm run release:ship:beta` (beta). This
|
||||
publishes to npm and pushes the `v*` tag on the already-verified commit. Because the release
|
||||
@@ -128,9 +126,7 @@ shipping while `0.13.3-beta.2` soaks. Never republish or reuse a shipped version
|
||||
as the next unused patch beta, `0.13.4-beta.1`, from the tested beta tag. No `version:all:*` mode
|
||||
computes that from a prerelease, so run `npm run release:check`, bump with
|
||||
`npm version 0.13.4-beta.1 --include-workspace-root --no-git-tag-version && git commit -m "chore(release): cut 0.13.4-beta.1"`,
|
||||
push the release branch for `CI` and `Desktop Packages`, and complete the
|
||||
[pre-release dependency checks](#pre-release-dependency-checks) before shipping with
|
||||
`npm run release:ship:beta`.
|
||||
push the release branch for `CI` and `Desktop Packages`, then ship with `npm run release:ship:beta`.
|
||||
Record the tested beta tag as its source so its soak still counts for the unchanged content.
|
||||
|
||||
## Release inventory
|
||||
@@ -238,7 +234,6 @@ npm run release:prep:minor
|
||||
|
||||
# 2. Push the release branch and wait for CI + Desktop Packages on this commit.
|
||||
git push -u origin HEAD
|
||||
# Complete the pre-release dependency checks on this commit.
|
||||
|
||||
# 3. After go-ahead and green release-branch checks: publish npm and push the tag.
|
||||
npm run release:ship
|
||||
@@ -274,8 +269,7 @@ npm run release:check # Typecheck, build, dry-run pack
|
||||
npm run version:all:patch
|
||||
npm run version:all:minor
|
||||
git push -u origin HEAD # Trigger CI + Desktop Packages on release/vX.Y.Z
|
||||
# Wait for CI and Desktop Packages and complete the pre-release dependency checks.
|
||||
# After go-ahead:
|
||||
# Wait for CI and Desktop Packages on this branch to pass, then after go-ahead:
|
||||
npm run release:publish # Publish to npm (idempotent, with propagation + beta dist-tag sync)
|
||||
npm run release:push # Create tag vX.Y.Z on HEAD and push (triggers release workflows)
|
||||
```
|
||||
@@ -292,7 +286,6 @@ npm run release:prep:beta:next # Cut X.Y.Z-beta.2, beta.3, ...
|
||||
|
||||
# 2. Push the release branch and wait for CI + Desktop Packages to pass:
|
||||
git push -u origin HEAD
|
||||
# Complete the pre-release dependency checks on this commit.
|
||||
|
||||
# 3. After go-ahead:
|
||||
npm run release:ship:beta
|
||||
@@ -300,8 +293,7 @@ npm run release:ship:beta
|
||||
# Later, after soak, promote on release/vX.Y.Z:
|
||||
npm run release:prep:promote
|
||||
git push -u origin HEAD
|
||||
# Wait for CI + Desktop Packages and complete the pre-release dependency checks.
|
||||
# After go-ahead:
|
||||
# Wait for CI + Desktop Packages to pass, then after go-ahead:
|
||||
npm run release:ship
|
||||
```
|
||||
|
||||
@@ -337,21 +329,22 @@ Drafts do not appear in GitHub's releases feed. Updater clients continue to see
|
||||
|
||||
### Default behavior
|
||||
|
||||
Follow the [standard stable release procedure](#standard-release-stable). The tag push starts
|
||||
the desktop release workflow, which sets a 36-hour rollout when it publishes the release.
|
||||
`npm run release:prep:patch` or `npm run release:prep:minor` → push release branch → green checks → `npm run release:ship` → tag push → 36h ramp. No extra action needed.
|
||||
|
||||
The `rollout_hours` input on `desktop-release.yml` is **only read on `workflow_dispatch`** — tag-push runs always default to 36. To get any other rollout duration on a fresh release, use the post-publish flip below.
|
||||
|
||||
### Instant-admit release (rollout_hours=0)
|
||||
|
||||
Follow the [standard stable release procedure](#standard-release-stable). Wait for Desktop
|
||||
Release to publish, then update the manifests to admit everyone immediately.
|
||||
Tag-push runs from `npm run release:ship` always stamp 36 hours. To admit everyone immediately (hotfix, doc-only change, a release you want out fast), ship the release normally, wait for it to publish, then flip the manifests:
|
||||
|
||||
```bash
|
||||
# 1. Wait for Desktop Release to publish the GitHub Release.
|
||||
# 1. Ship the verified release branch (36h ramp from tag push).
|
||||
npm run release:ship
|
||||
|
||||
# 2. Wait for Desktop Release to publish the GitHub Release.
|
||||
gh run watch <desktop-release-run-id> --exit-status
|
||||
|
||||
# 2. Flip the published manifests to instant admit.
|
||||
# 3. Flip the published manifests to instant admit.
|
||||
gh workflow run desktop-rollout.yml \
|
||||
-f tag=v0.1.64 \
|
||||
-f rollout_hours=0
|
||||
@@ -397,8 +390,7 @@ gh workflow run desktop-release.yml \
|
||||
-f rollout_hours=6
|
||||
```
|
||||
|
||||
For a fresh release with a custom ramp, follow the [instant-admit procedure](#instant-admit-release-rollout_hours0)
|
||||
and set `rollout_hours` to your chosen duration.
|
||||
This does **not** apply to fresh releases shipped via `npm run release:ship` — tag-push runs always stamp 36. For a fresh release with a custom ramp, ship normally and then dispatch `desktop-rollout.yml` (same pattern as the instant-admit flow above, with your chosen `rollout_hours`).
|
||||
|
||||
### Releasing during an active rollout
|
||||
|
||||
@@ -867,18 +859,6 @@ Bullets within each section (Added, Changed, Fixed) follow this order:
|
||||
2. **Quality-of-life improvements** — polish, performance, smoother interactions.
|
||||
3. **Internal/infra changes last** — only include if they have a tangible user benefit (e.g. "faster startup" is user-facing even if the fix was internal).
|
||||
|
||||
## Pre-release dependency checks
|
||||
|
||||
Run these checks from the repository root on the release commit before shipping a beta or stable release.
|
||||
Use Linux x64 so the audit includes the platform-specific dependencies that the CI job checked.
|
||||
|
||||
1. Review changes to dependency versions, download URLs, and integrity hashes in `git diff <previous-release-tag> HEAD -- package-lock.json`.
|
||||
2. Install the exact dependencies from the release lockfile with `npm ci`.
|
||||
3. Run `npm audit signatures`. Investigate failures before shipping. See [Dependency signature audit](development.md#dependency-signature-audit) for help.
|
||||
|
||||
Checking signatures and reviewing the lockfile diff reduce the risk of shipping compromised dependencies.
|
||||
These checks help prevent supply-chain attacks from reaching users through Paseo.
|
||||
|
||||
## Pre-release sanity check
|
||||
|
||||
Before cutting a **stable** release, the release agent reviews the diff as a last line of defence against shipping bugs. Skip this for betas — the beta itself is the smoke test, and gating each beta on a code review defeats the point of using betas as fast release candidates.
|
||||
@@ -906,7 +886,6 @@ Every entry covers `previous stable release → release source`: first beta, lat
|
||||
- [ ] Fold this beta into the series' single `CHANGELOG.md` entry (heading `## X.Y.Z-beta.N - YYYY-MM-DD`, previous stable → release source), review it against the changelog policy, get approval, and commit it with its [`CHANGELOG.zh-CN.md` translation](#changelog-translations) before running `release:prep:*`
|
||||
- [ ] The diff from the previous stable to the resolved release source is classified as patch or minor, with the target version and rationale approved
|
||||
- [ ] `npm run release:prep:beta:patch`, `release:prep:beta:minor`, or `release:prep:beta:next` created the version commit on `release/vX.Y.Z-beta.N` without a tag, and the pushed branch passed `CI` and `Desktop Packages` before shipping (never relying on `main` CI)
|
||||
- [ ] Complete the [pre-release dependency checks](#pre-release-dependency-checks) on the release commit
|
||||
- [ ] After go-ahead, `npm run release:ship:beta` published npm and pushed the `vX.Y.Z-beta.N` tag without triggering a second CI run
|
||||
- [ ] npm shows the version under the `beta` dist-tag, not `latest`
|
||||
- [ ] The GitHub prerelease was published only after the three beta manifests were uploaded, and it has the changelog body and every expected macOS, Linux, Windows, and Android APK asset
|
||||
@@ -930,7 +909,6 @@ Every entry covers `previous stable release → release source`: first beta, lat
|
||||
- [ ] Verify the changelog heading follows strict `## X.Y.Z - YYYY-MM-DD` format
|
||||
- [ ] Ensure local format, lint, and typecheck pass and the working tree is clean before running `release:prep:*`
|
||||
- [ ] `npm run release:prep:patch`, `release:prep:minor`, or `release:prep:promote` created the version commit on `release/vX.Y.Z` without a tag, and the pushed branch passed `CI` and `Desktop Packages` before shipping (never relying on `main` CI)
|
||||
- [ ] Complete the [pre-release dependency checks](#pre-release-dependency-checks) on the release commit
|
||||
- [ ] After go-ahead, `npm run release:ship` published npm, updated dist-tags, and pushed the `vX.Y.Z` tag without triggering a second CI run
|
||||
- [ ] `latest` resolves to the new stable, and `beta` resolves to it too unless an active newer beta holds `beta`
|
||||
- [ ] The GitHub Release was published only after the three stable manifests were uploaded, and it has the changelog body and every expected macOS, Linux, Windows, and Android APK asset
|
||||
|
||||
+11
-68
@@ -5,9 +5,15 @@ Agent chat delivery has two paths:
|
||||
1. **Live stream** — `agent_stream` WebSocket messages for immediacy. These may be delta-shaped lifecycle updates.
|
||||
2. **Authoritative history** — `fetch_agent_timeline_request` for correctness. This always returns full projected timeline items, never lifecycle deltas.
|
||||
|
||||
Pagination bounds each read, not total resident history. Streaming overhead must remain
|
||||
proportional to the retained transcript. Cumulative text snapshots must be released after their
|
||||
deltas have been consumed.
|
||||
The daemon retains projected items in memory. Each source event advances the stream sequence,
|
||||
then replaces the previous tool state or merges into the current text item. Intermediate payloads
|
||||
are never retained for history or catch-up. Provider history is the durable transcript authority
|
||||
and rebuilds the projection when an agent resumes.
|
||||
|
||||
Pagination bounds each read, not total resident history. Active and idle agents retain their
|
||||
projected transcript; archive releases it and later history reads rebuild it from the provider.
|
||||
Streaming overhead must remain proportional to the retained transcript. Cumulative text snapshots
|
||||
must be released after their deltas have been consumed.
|
||||
|
||||
The invariants are:
|
||||
|
||||
@@ -26,50 +32,6 @@ bounded item is used for runtime timeline rows and live stream events. Provider
|
||||
applies the same rule so reopening an agent cannot restore an oversized payload. Fetches apply it
|
||||
again to assistant and reasoning rows the projection merges from many chunks.
|
||||
|
||||
## Owned history
|
||||
|
||||
The daemon owns each agent's history in `AgentTimeline`
|
||||
(`packages/server/src/server/agent/timeline/`): one ordered history per agent, with each provider
|
||||
child's descriptor and history in a child scope of the same agent. Each source event advances the
|
||||
stream sequence, then replaces the previous tool state or merges into the current text item.
|
||||
Intermediate payloads are never retained for history or catch-up.
|
||||
|
||||
History is append-only: rewind, import, reload and archive never delete or rewrite a row. Only
|
||||
deleting the agent, or a provider removing one of its own children, deletes history.
|
||||
|
||||
- **Rewind** retires a range of rows. They leave the conversation and stay stored, in the same
|
||||
epoch. See [Rewind retires rows](#rewind-retires-rows).
|
||||
- **Provider history** is imported only into an agent that has no history. After that, resume
|
||||
does not read it. Reload agent and Unarchive require the provider history to start with the
|
||||
same prompt IDs and text in order. They then append whole new turns, starting at the next
|
||||
prompt. Existing replies, including partial replies, stay as recorded. If the prompts differ,
|
||||
for example because the provider stored expanded attachment text, the chat stays unchanged and
|
||||
Paseo reports a mismatch. A provider child Paseo already holds, listed or retired, is never imported again.
|
||||
- **Archive and reload** keep the history and the provider children. An archived chat reads them
|
||||
without its provider. Opening a stored agent that has no provider session to resume starts its
|
||||
first session on the same history.
|
||||
- **Delete** removes the agent's history and every child's, retired ones included, before the
|
||||
agent record. If the history cannot be removed, the request fails and the agent stays listed. The
|
||||
user can keep using it and delete it again.
|
||||
|
||||
`epoch` is the stored history's identity, minted once when the history is created.
|
||||
|
||||
`AgentTimeline` serializes every operation of one agent, child scopes included, and keeps its
|
||||
state in an `AgentTimelineBackend`: the sequence, the rows and retirements, prompt identities, the
|
||||
open rewind, and the children. The backend contract suite is `agent-timeline.test.ts`, run over
|
||||
`TIMELINE_CONTRACT_BACKENDS` in `timeline/testing.ts`. The daemon uses the SQLite backend in the
|
||||
[daemon database](data-model.md#daemon-database). History, retirements, the open rewind, and
|
||||
provider children survive a daemon restart in the same epoch, so clients keep their cursors. A
|
||||
closed or archived agent holds no history in memory. Each fetch reads the page from the database
|
||||
and starts no provider. An internal agent, such as the one that writes a commit message, keeps its
|
||||
history in a memory backend instead, so it leaves nothing on disk. The memory backend also serves
|
||||
tests.
|
||||
|
||||
An open rewind is stored with the history. Resuming an agent whose history holds one settles it
|
||||
before the agent takes prompts: a recorded provider cut is committed, and an unknown outcome is
|
||||
judged from the resumed provider history. When that history proves nothing, the rewind stays open
|
||||
and the agent refuses prompts with the unknown-outcome error.
|
||||
|
||||
## Presence is not delivery
|
||||
|
||||
Client heartbeat reports presence:
|
||||
@@ -206,7 +168,7 @@ or retry backoff. This cannot keep a mobile socket alive after the operating sys
|
||||
bookkeeping without replacing timeline arrays, preserving an upward-scrolled viewport.
|
||||
- When the page overlaps or is adjacent to the local end cursor, only projected items newer than
|
||||
that cursor are applied. Already-covered rows are not replayed.
|
||||
- A true middle gap or epoch change atomically replaces stale canonical history with the
|
||||
- A true middle gap, epoch change, or rewind atomically replaces stale canonical history with the
|
||||
latest tail. The replacement reconciles positioned live rows beyond its coverage and unresolved
|
||||
local submissions; it never retains two discontiguous canonical ranges.
|
||||
|
||||
@@ -219,24 +181,6 @@ history replay. The pending approval UI can hide that tool from presentation, bu
|
||||
must retain its position. Creating a new history card on rejection places it after the prompt that
|
||||
rejected it; changing steer-event ordering would also put new assistant output before that prompt.
|
||||
|
||||
## Rewind retires rows
|
||||
|
||||
A conversation rewind commits a retirement `{ seq, retireFromSeq }`: active rows anchored in
|
||||
`[retireFromSeq, seq)` leave the conversation, and `seq` is the retirement's own position in the
|
||||
sequence. The provider children spawned by retired tool calls, and their descendants, are retired
|
||||
in the same commit. They leave the listing, keep their history, and drop late provider events.
|
||||
|
||||
Clients learn of a retirement live through `agent.timeline.rewind`, and on pages through
|
||||
`retirements`, which lists the retirements whose `seq` lies inside the page's span. The client
|
||||
drops the rows it holds in that range; rows without a timeline position are unechoed local sends
|
||||
and stay. Retired ranges and the retirement's `seq` count as covered, so forward cursors advance
|
||||
through them. Tail, before and prompt-jump pages are served from active rows, so one served before
|
||||
a retirement the client already applied is stale and is refetched (`viewed-timeline-sync.ts`).
|
||||
|
||||
Clients without `timeline_rewind_operations` cannot drop retired rows. For them the session derives
|
||||
a wire epoch that changes with each retirement, so they take the destructive replacement they
|
||||
always took on rewind. The shim is tagged `COMPAT(timelineRewindOperations)`.
|
||||
|
||||
## Provider child history
|
||||
|
||||
Child transcripts use the same projected-page reconciliation as the main conversation. The client
|
||||
@@ -401,7 +345,7 @@ the draft-create handoff is the one boundary that also permits the legacy canoni
|
||||
arrived first. Generic reducers and consumers do not reimplement message identity matching.
|
||||
|
||||
Ordinary bootstrap, same-epoch reset, and catch-up replacement preserve unmatched locally submitted
|
||||
rows because a provider may never echo them. A known epoch change replaces history and
|
||||
rows because a provider may never echo them. A known epoch change or rewind replaces history and
|
||||
drops acknowledged local rows omitted by the new canonical epoch; every transaction not yet
|
||||
acknowledged by the provider, and no other local row, crosses that destructive boundary. A cold
|
||||
reset without an existing epoch is destructive because the client has no continuity anchor.
|
||||
@@ -417,7 +361,6 @@ canonical assistant prefix, it stays in the head lane. No row may be returned in
|
||||
|
||||
## Relevant code
|
||||
|
||||
- Server owned history: `packages/server/src/server/agent/timeline/`
|
||||
- Server live stream forwarding: `packages/server/src/server/session.ts`
|
||||
- App sync planning: `packages/app/src/timeline/timeline-sync-plan.ts`
|
||||
- App viewed-agent synchronization: `packages/app/src/timeline/viewed-timeline-sync.ts`
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
sha256-IAhKhkolW4xvFvMaAEFdhYvPAhTm2azsqbGMKCKL3q0=
|
||||
sha256-TAVzJzziWDAapQkG4TLkLzOlodkdFNKSl3y/Tm9HB28=
|
||||
|
||||
Generated
+1
-20
@@ -45,9 +45,6 @@
|
||||
"react-dom": "19.2.3",
|
||||
"typescript": "^5.9.3",
|
||||
"ws": "^8.20.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@0no-co/graphql.web": {
|
||||
@@ -39722,9 +39719,6 @@
|
||||
"typescript": "^5.2.2",
|
||||
"vitest": "^4.1.6",
|
||||
"zx": "^8.8.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
},
|
||||
"packages/cli/node_modules/@vitest/expect": {
|
||||
@@ -40652,7 +40646,7 @@
|
||||
"@playwright/test": "^1.56.1",
|
||||
"@types/express": "^4.17.20",
|
||||
"@types/markdown-it": "^14.2.0",
|
||||
"@types/node": "^22.16.0",
|
||||
"@types/node": "^20.9.0",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@types/uuid": "^9.0.7",
|
||||
"@types/ws": "^8.5.8",
|
||||
@@ -40660,9 +40654,6 @@
|
||||
"cross-env": "^10.1.0",
|
||||
"tsx": "^4.6.0",
|
||||
"vitest": "^4.1.6"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
},
|
||||
"packages/server/node_modules/@esbuild/aix-ppc64": {
|
||||
@@ -41110,16 +41101,6 @@
|
||||
"@types/mdurl": "^2"
|
||||
}
|
||||
},
|
||||
"packages/server/node_modules/@types/node": {
|
||||
"version": "22.20.5",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz",
|
||||
"integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"undici-types": "~6.21.0"
|
||||
}
|
||||
},
|
||||
"packages/server/node_modules/@vitest/expect": {
|
||||
"version": "4.1.6",
|
||||
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.6.tgz",
|
||||
|
||||
@@ -169,8 +169,5 @@
|
||||
"tiny-async-pool": {
|
||||
"semver@^5": "5.7.2"
|
||||
}
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,13 +13,6 @@ import {
|
||||
import { expectNearBottom, scrollChatAwayFromBottom } from "../support/helpers/agent-bottom-anchor";
|
||||
import { holdRewindCompletion } from "../support/helpers/agent-timeline-gate";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
import { userScrollsTimelineToHistoryStart } from "../support/helpers/timeline-pagination";
|
||||
import {
|
||||
closeWorkspaceAgentTab,
|
||||
fetchAgentArchivedAt,
|
||||
primeAdditionalPage,
|
||||
resetSeededPageState,
|
||||
} from "../support/helpers/archive-tab";
|
||||
|
||||
async function completeSubmittedTurn(
|
||||
page: Page,
|
||||
@@ -55,102 +48,26 @@ async function expectTurnCompletesNormally(
|
||||
await expectAgentIdle(page);
|
||||
}
|
||||
|
||||
async function openAgentOnAnotherClient(
|
||||
page: Page,
|
||||
agent: Awaited<ReturnType<typeof seedMockAgentWorkspace>>,
|
||||
): Promise<void> {
|
||||
await primeAdditionalPage(page);
|
||||
await resetSeededPageState(page);
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
}
|
||||
|
||||
/** The prompts the chat shows, in order, each exactly once. */
|
||||
async function expectPrompts(page: Page, prompts: string[]): Promise<void> {
|
||||
const messages = page.getByTestId("user-message");
|
||||
await expect(messages).toHaveCount(prompts.length);
|
||||
await expect(messages).toContainText(prompts);
|
||||
}
|
||||
|
||||
async function reloadAgentFromTabMenu(page: Page, agentId: string): Promise<void> {
|
||||
const tabId = `workspace-tab-agent_${agentId}`;
|
||||
await page.getByTestId(tabId).filter({ visible: true }).first().click({ button: "right" });
|
||||
await page.getByTestId(`workspace-tab-context-agent_${agentId}-reload-agent`).click();
|
||||
}
|
||||
|
||||
async function archiveAgentByClosingTab(
|
||||
page: Page,
|
||||
agent: Awaited<ReturnType<typeof seedMockAgentWorkspace>>,
|
||||
): Promise<void> {
|
||||
await closeWorkspaceAgentTab(page, agent.agentId);
|
||||
await expect.poll(() => fetchAgentArchivedAt(agent.client, agent.agentId)).not.toBeNull();
|
||||
}
|
||||
|
||||
async function unarchiveAgent(page: Page): Promise<void> {
|
||||
await page.getByRole("button", { name: "Unarchive", exact: true }).click();
|
||||
await expect(page.getByText("This agent is archived", { exact: true })).toHaveCount(0, {
|
||||
timeout: 30_000,
|
||||
});
|
||||
}
|
||||
|
||||
async function expectToast(page: Page, message: string): Promise<void> {
|
||||
await expect(page.getByTestId("app-toast-message")).toHaveText(message, { timeout: 30_000 });
|
||||
}
|
||||
|
||||
// The mock provider's resumed session holds no history, so it never matches what Paseo shows.
|
||||
const UNSYNCED_RELOAD =
|
||||
"Reloaded agent, but the provider's history doesn't match this chat, so it wasn't synced";
|
||||
|
||||
/** The prompts of the whole conversation, after scrolling up through its older pages. */
|
||||
async function expectConversationPrompts(page: Page, prompts: string[]): Promise<void> {
|
||||
const messages = page.getByTestId("user-message");
|
||||
await expect
|
||||
.poll(async () => {
|
||||
await userScrollsTimelineToHistoryStart(page);
|
||||
return await messages.count();
|
||||
})
|
||||
.toBe(prompts.length);
|
||||
await expect(messages).toContainText(prompts);
|
||||
}
|
||||
|
||||
// A row React remounts loses this attribute; one that stays mounted keeps it.
|
||||
async function markMounted(row: Locator): Promise<void> {
|
||||
await row.evaluate((element) => element.setAttribute("data-e2e-mounted", "before-rewind"));
|
||||
}
|
||||
|
||||
async function expectStillMounted(row: Locator): Promise<void> {
|
||||
await expect(row).toHaveAttribute("data-e2e-mounted", "before-rewind");
|
||||
}
|
||||
|
||||
test.describe("Agent message rewind", () => {
|
||||
test("rewinds a prompt in place on every open client and keeps a human draft", async ({
|
||||
test("rewinds a submitted prompt without replaying history and preserves a human draft", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(150_000);
|
||||
test.setTimeout(90_000);
|
||||
const retainedPrompt = "Keep this completed turn after rewind.";
|
||||
const rewoundPrompt = "Remove this completed turn after rewind.";
|
||||
const nextPrompt = "Continue after the rewind.";
|
||||
const preservedDraft = "Keep this human draft after rewind.";
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "message-rewind-roundtrip-",
|
||||
title: "Message rewind roundtrip",
|
||||
model: "ten-second-stream",
|
||||
});
|
||||
const otherClient = await page.context().newPage();
|
||||
|
||||
try {
|
||||
const rewindCompletion = await holdRewindCompletion(page, agent.agentId);
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
const retainedMessage = await completeSubmittedTurn(page, agent, retainedPrompt);
|
||||
await completeSubmittedTurn(page, agent, retainedPrompt);
|
||||
const userMessage = await completeSubmittedTurn(page, agent, rewoundPrompt);
|
||||
|
||||
await test.step("a second client opens the same chat", async () => {
|
||||
await openAgentOnAnotherClient(otherClient, agent);
|
||||
await expectPrompts(otherClient, [retainedPrompt, rewoundPrompt]);
|
||||
});
|
||||
|
||||
await markMounted(retainedMessage);
|
||||
await scrollChatAwayFromBottom(page, {
|
||||
deltaY: -900,
|
||||
minDistanceFromBottom: 300,
|
||||
@@ -159,92 +76,19 @@ test.describe("Agent message rewind", () => {
|
||||
await blurComposerInput(page);
|
||||
rewindCompletion.clearTimelineStreamCount();
|
||||
|
||||
await test.step("the rewind stays pending until the daemon answers", async () => {
|
||||
const rewind = rewindConversation(page, userMessage, rewoundPrompt);
|
||||
await rewindCompletion.waitForDelayedResponse();
|
||||
await expect(page.getByTestId("rewind-menu-conversation")).toBeDisabled();
|
||||
expect(rewindCompletion.timelineStreamCount()).toBe(0);
|
||||
rewindCompletion.release();
|
||||
await rewind;
|
||||
});
|
||||
const rewind = rewindConversation(page, userMessage, rewoundPrompt);
|
||||
await rewindCompletion.waitForDelayedResponse();
|
||||
await expect(page.getByTestId("rewind-menu-conversation")).toBeDisabled();
|
||||
expect(rewindCompletion.timelineStreamCount()).toBe(0);
|
||||
rewindCompletion.release();
|
||||
await rewind;
|
||||
|
||||
await test.step("the rewound turn leaves without reloading the chat", async () => {
|
||||
await expectPrompts(page, [retainedPrompt]);
|
||||
await expectStillMounted(retainedMessage);
|
||||
expect(rewindCompletion.timelineFetchCount()).toBe(0);
|
||||
await expectComposerDraft(page, preservedDraft);
|
||||
await expectComposerNotFocused(page);
|
||||
await expectNearBottom(page);
|
||||
await expectPrompts(otherClient, [retainedPrompt]);
|
||||
});
|
||||
|
||||
await test.step("the next prompt appears once on both clients", async () => {
|
||||
await completeSubmittedTurn(otherClient, agent, nextPrompt);
|
||||
await expectPrompts(otherClient, [retainedPrompt, nextPrompt]);
|
||||
await expectPrompts(page, [retainedPrompt, nextPrompt]);
|
||||
});
|
||||
|
||||
await test.step("a reconnecting client loads the rewound conversation", async () => {
|
||||
await otherClient.reload();
|
||||
await expectPrompts(otherClient, [retainedPrompt, nextPrompt]);
|
||||
});
|
||||
} finally {
|
||||
await otherClient.close();
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps the rewound conversation through Reload agent, archive and unarchive", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(150_000);
|
||||
const keptPrompt = "Keep this turn through reload and archive.";
|
||||
const rewoundPrompt = "Rewind this turn before reloading.";
|
||||
const nextPrompt = "Continue after the rewind, then reload.";
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "message-rewind-reload-archive-",
|
||||
title: "Message rewind reload archive",
|
||||
model: "ten-second-stream",
|
||||
});
|
||||
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
await completeSubmittedTurn(page, agent, keptPrompt);
|
||||
const rewound = await completeSubmittedTurn(page, agent, rewoundPrompt);
|
||||
await rewindConversation(page, rewound, rewoundPrompt);
|
||||
await expectPrompts(page, [keptPrompt]);
|
||||
await completeSubmittedTurn(page, agent, nextPrompt);
|
||||
await expectPrompts(page, [keptPrompt, nextPrompt]);
|
||||
|
||||
await test.step("Reload agent keeps the chat and says the provider's history was not synced", async () => {
|
||||
await reloadAgentFromTabMenu(page, agent.agentId);
|
||||
await expectToast(page, UNSYNCED_RELOAD);
|
||||
await expectPrompts(page, [keptPrompt, nextPrompt]);
|
||||
await expectComposerVisible(page);
|
||||
});
|
||||
|
||||
await test.step("the archived chat shows the rewound conversation", async () => {
|
||||
await archiveAgentByClosingTab(page, agent);
|
||||
await openAgentRoute(page, agent);
|
||||
await expect(page.getByText("This agent is archived", { exact: true })).toBeVisible({
|
||||
timeout: 30_000,
|
||||
});
|
||||
await expectConversationPrompts(page, [keptPrompt, nextPrompt]);
|
||||
});
|
||||
|
||||
await test.step("unarchiving keeps the rewound conversation", async () => {
|
||||
await unarchiveAgent(page);
|
||||
await expectToast(page, UNSYNCED_RELOAD);
|
||||
await expectComposerVisible(page);
|
||||
await expectConversationPrompts(page, [keptPrompt, nextPrompt]);
|
||||
});
|
||||
|
||||
await test.step("a reconnecting client loads the same conversation", async () => {
|
||||
await page.reload();
|
||||
await expectComposerVisible(page);
|
||||
await expectConversationPrompts(page, [keptPrompt, nextPrompt]);
|
||||
});
|
||||
await expect(page.getByTestId("user-message").filter({ hasText: rewoundPrompt })).toHaveCount(
|
||||
0,
|
||||
);
|
||||
await expectComposerDraft(page, preservedDraft);
|
||||
await expectComposerNotFocused(page);
|
||||
await expectNearBottom(page);
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
|
||||
@@ -2,10 +2,8 @@ import { expect, test } from "../support/fixtures";
|
||||
import {
|
||||
applyProfileFromPicker,
|
||||
closeModelPicker,
|
||||
expectAgentProfileNameDraft,
|
||||
expectComposerDoesNotName,
|
||||
expectAgentProfilesEmptyPrompt,
|
||||
expectHostAgentProfiles,
|
||||
expectProfileEditTooltip,
|
||||
expectComposerMode,
|
||||
expectCreateProfileFromModelRow,
|
||||
@@ -16,11 +14,8 @@ import {
|
||||
expectProfileReachableByScrolling,
|
||||
expectProfileSearchResult,
|
||||
expectProfileVisibleForProvider,
|
||||
fillAgentProfileName,
|
||||
openEditProfileFromModelRow,
|
||||
openModelPicker,
|
||||
openAgentProfilesFromEmptyPrompt,
|
||||
removeOpenModalAgentProfileWithConfirm,
|
||||
searchModelPicker,
|
||||
seedAgentProfiles,
|
||||
selectModelRow,
|
||||
@@ -151,10 +146,10 @@ test.describe("Agent profiles in the model picker", () => {
|
||||
await openModelPicker(page);
|
||||
await expectModelRowProfileActionBesideRow(page, oneMinute);
|
||||
await expectCreateProfileFromModelRow(page, oneMinute);
|
||||
await expectComposerModel(page, oneMinute.modelLabel);
|
||||
await openModelPicker(page);
|
||||
await selectModelRow(page, { provider: "mock", modelId: "ten-second-stream" });
|
||||
await expectComposerModel(page, "Ten second stream");
|
||||
await openModelPicker(page);
|
||||
await selectModelRow(page, oneMinute);
|
||||
await expectComposerModel(page, oneMinute.modelLabel);
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
await seed.restore();
|
||||
@@ -239,44 +234,4 @@ test.describe("Agent profiles in the model picker", () => {
|
||||
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,32 +1,19 @@
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import { test } from "../support/fixtures";
|
||||
import {
|
||||
browserBackWithConfirm,
|
||||
browserHistoryJumpWithConfirm,
|
||||
createAgentProfile,
|
||||
createAgentProfileFromEmptyState,
|
||||
duplicateOpenAgentProfileWithConfirm,
|
||||
editAgentProfile,
|
||||
expectAgentProfile,
|
||||
expectAgentProfileForm,
|
||||
expectAgentProfileNameDraft,
|
||||
expectAgentProfileNotesDraft,
|
||||
expectAgentProfileOrder,
|
||||
expectAgentProfileTagsGone,
|
||||
expectHostAgentProfiles,
|
||||
expectNoAgentProfiles,
|
||||
fillAgentProfileName,
|
||||
fillAgentProfileNotes,
|
||||
moveAgentProfileUp,
|
||||
openAgentProfileEditor,
|
||||
openAgentProfileSettings,
|
||||
openCompactAgentProfileSettings,
|
||||
openCreateAgentProfileEditor,
|
||||
removeAgentProfile,
|
||||
saveOpenAgentProfile,
|
||||
seedAgentProfiles,
|
||||
stageLegacyFavoritesForHostMigration,
|
||||
switchSettingsSectionWithConfirm,
|
||||
toggleAgentProfileCustomize,
|
||||
} from "../support/helpers/agent-profiles";
|
||||
|
||||
const MOCK_PROVIDER_LABEL = "Mock Load Test";
|
||||
@@ -138,252 +125,4 @@ test.describe("Agent profiles settings", () => {
|
||||
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();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
closeRelayPairing,
|
||||
emptyHome,
|
||||
loadingScreen,
|
||||
openTailscaleDocsFromSetup,
|
||||
expectTailscaleSwitchDisabled,
|
||||
paseoToolsSwitch,
|
||||
pickTheme,
|
||||
projectSuggestion,
|
||||
@@ -403,12 +403,10 @@ test("setup choices carry over to Settings and the phone step pairs over relay",
|
||||
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 page.screenshot({ path: testInfo.outputPath("5-phone.png") });
|
||||
expect(await openTailscaleDocsFromSetup(page)).toBe(
|
||||
"https://paseo.sh/docs/connectivity#tailscale",
|
||||
);
|
||||
await expectTailscaleSwitchDisabled(page);
|
||||
const pairing = await openRelayPairingFromSetup(page);
|
||||
await expect(pairing.getByText("Enable relay?", { exact: true })).toBeVisible();
|
||||
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 { startTailscaleTestDaemon } from "../support/helpers/tailscale-daemon";
|
||||
import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon";
|
||||
import {
|
||||
expectPairingOffer,
|
||||
cancelTailscaleTurnOff,
|
||||
confirmTailscaleTurnOff,
|
||||
connectThroughTailscale,
|
||||
disableTailscale,
|
||||
enableTailscale,
|
||||
expectTailscaleAddress,
|
||||
expectTailscaleRowLoadsOn,
|
||||
openSetupMobileStep,
|
||||
slowConnectionToHost,
|
||||
expectTailscaleUpdateRequired,
|
||||
expectCompletePairingQr,
|
||||
expectRelayConsent,
|
||||
openPairDeviceModal,
|
||||
@@ -37,3 +54,59 @@ test("keeps the pairing QR code inside its compact tile", async ({ page }, testI
|
||||
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,25 +372,6 @@ test.describe("Plugin sidebar items", () => {
|
||||
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 }) => {
|
||||
await page.setViewportSize(WIDE);
|
||||
await gotoWorkspace(page, workspaceId);
|
||||
|
||||
@@ -1,12 +1,6 @@
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import {
|
||||
expectChatHistoryAttachment,
|
||||
forkMostRecentAssistantTurnToNewTab,
|
||||
observeForkAttachment,
|
||||
} from "../support/helpers/assistant-fork";
|
||||
import { test } from "../support/fixtures";
|
||||
import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate";
|
||||
import {
|
||||
ASSISTANT_TEXT,
|
||||
withTimelinePlugin,
|
||||
viewInlineThinkingExample,
|
||||
requestPluginTimeline,
|
||||
@@ -61,24 +55,3 @@ test("inline-thinking example renders a streamed thought through host UI", async
|
||||
}, info) => {
|
||||
await viewInlineThinkingExample(page, info);
|
||||
});
|
||||
|
||||
test("plugin-transformed assistant reply keeps copy, fork, and turn duration in its footer", async ({
|
||||
page,
|
||||
}, info) => {
|
||||
const forkAttachment = observeForkAttachment(page);
|
||||
await withTimelinePlugin(page, info, "assistant", async (agent) => {
|
||||
await requestPluginTimeline(agent);
|
||||
await agent.client.waitForFinish(agent.agentId, 30_000);
|
||||
await expectWholeCompletedCard(page);
|
||||
|
||||
const footer = page.getByTestId("turn-footer").last();
|
||||
await expect(footer).toBeVisible();
|
||||
await expect(footer.getByRole("button", { name: "Copy turn" })).toBeVisible();
|
||||
await expect(footer.getByRole("button", { name: "Fork chat from here" })).toBeVisible();
|
||||
await expect(footer.getByText(/^Worked for /)).toBeVisible();
|
||||
|
||||
await forkMostRecentAssistantTurnToNewTab(page);
|
||||
await expectChatHistoryAttachment(page);
|
||||
expect(await forkAttachment.waitForText()).toContain(ASSISTANT_TEXT);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -235,7 +235,7 @@ test.describe("Rewind sheet", () => {
|
||||
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
|
||||
await expect(userMessage(page, secondPrompt)).toHaveCount(0);
|
||||
await expect(page.getByText("Cycle 1", { exact: true })).toHaveCount(0);
|
||||
await expectUserMessageCount(page, 0);
|
||||
await expectUserMessageCount(page, 1);
|
||||
await expectComposerDraft(page, firstPrompt);
|
||||
await expectComposerFocused(page);
|
||||
|
||||
@@ -243,7 +243,7 @@ test.describe("Rewind sheet", () => {
|
||||
await expectUserMessageVisible(page, replacementPrompt);
|
||||
await expect(userMessage(page, secondPrompt)).toHaveCount(0);
|
||||
await expect(page.getByText("Cycle 1", { exact: true })).toHaveCount(0);
|
||||
await expectUserMessageCount(page, 1);
|
||||
await expectUserMessageCount(page, 2);
|
||||
|
||||
await fillComposerDraft(page, "");
|
||||
await composerLocator(page).evaluate((element) => element.blur());
|
||||
@@ -254,19 +254,7 @@ test.describe("Rewind sheet", () => {
|
||||
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
|
||||
await expectComposerDraft(page, "");
|
||||
await expectComposerNotFocused(page);
|
||||
await expectUserMessageCount(page, 1);
|
||||
|
||||
const preservedDraft = "Keep this human draft after rewind.";
|
||||
await fillComposerDraft(page, preservedDraft);
|
||||
await composerLocator(page).evaluate((element) => element.blur());
|
||||
await userMessage(page, replacementPrompt).hover();
|
||||
await page.getByTestId("rewind-menu-trigger").last().click();
|
||||
await expect(page.getByTestId("rewind-menu-content")).toBeVisible();
|
||||
await selectRewindOption(page, "Rewind files");
|
||||
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
|
||||
await expectComposerDraft(page, preservedDraft);
|
||||
await expectComposerNotFocused(page);
|
||||
await expectUserMessageCount(page, 1);
|
||||
await expectUserMessageCount(page, 2);
|
||||
|
||||
await fillComposerDraft(page, "");
|
||||
await composerLocator(page).evaluate((element) => element.blur());
|
||||
@@ -277,7 +265,7 @@ test.describe("Rewind sheet", () => {
|
||||
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
|
||||
await expectComposerDraft(page, replacementPrompt);
|
||||
await expectComposerFocused(page);
|
||||
await expectUserMessageCount(page, 0);
|
||||
await expectUserMessageCount(page, 1);
|
||||
} finally {
|
||||
await session.cleanup();
|
||||
}
|
||||
|
||||
@@ -15,8 +15,8 @@ press "id=\"model-provider-${PROVIDER_ID}\""
|
||||
wait "id=\"compact-model-list\"" 3000
|
||||
# The row's profile action sits inside Android's independent scroll viewport.
|
||||
press "id=\"model-create-profile-${PROVIDER_ID}-${PROFILE_MODEL_ID}\""
|
||||
wait "id=\"model-profile-created-toast\"" 5000
|
||||
# Undo removes the created profile after selecting the model and closing the picker.
|
||||
press "id=\"model-profile-created-undo\""
|
||||
wait "id=\"combined-model-selector\"" 3000
|
||||
wait "text=\"Add agent profile\"" 5000
|
||||
# Closing the form keeps the remembered model: the tap did not also select the row.
|
||||
back
|
||||
wait "id=\"combined-model-selector\" label=\"Select model (${MODEL_LABEL})\"" 3000
|
||||
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>
|
||||
import assert from "node:assert/strict";
|
||||
import { execFileSync } from "node:child_process";
|
||||
@@ -13,11 +13,7 @@ function ad(...args) {
|
||||
});
|
||||
}
|
||||
|
||||
ad(
|
||||
"press",
|
||||
'label="Pair a device, Scan a QR code or copy a link to connect your phone to this host"',
|
||||
"--settle",
|
||||
);
|
||||
ad("press", 'label="Relay"', "--settle");
|
||||
ad("wait", "text", "Pairing QR code", "10000");
|
||||
const { data } = JSON.parse(ad("snapshot", "-i", "--json"));
|
||||
const sheet = data.nodes.find((node) => node.label === "Bottom Sheet");
|
||||
|
||||
@@ -142,22 +142,8 @@ export async function openAgentProfileSettings(page: Page): Promise<void> {
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
await openSettingsHost(page, serverId);
|
||||
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 });
|
||||
}
|
||||
|
||||
/** 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 page.getByRole("button", { name: "Agents", exact: true }).click();
|
||||
await expectAppRoute(page, buildSettingsHostSectionRoute(serverId, "agents"));
|
||||
await expect(page.getByTestId("agent-profiles-card")).toBeVisible({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
@@ -170,9 +156,7 @@ export async function expectNoAgentProfiles(page: Page): Promise<void> {
|
||||
// ─── Settings: the profile list ────────────────────────────────────────────
|
||||
|
||||
export function agentProfileRow(page: Page, name: string): Locator {
|
||||
return page
|
||||
.locator('[data-testid^="agent-profile-row-"]')
|
||||
.filter({ has: page.getByText(name, { exact: true }) });
|
||||
return page.locator('[data-testid^="agent-profile-row-"]').filter({ hasText: name });
|
||||
}
|
||||
|
||||
export async function expectAgentProfile(
|
||||
@@ -181,9 +165,7 @@ export async function expectAgentProfile(
|
||||
): Promise<void> {
|
||||
const row = agentProfileRow(page, expected.name);
|
||||
await expect(row).toBeVisible({ timeout: 30_000 });
|
||||
for (const tag of expected.tags) {
|
||||
await expect(row).toContainText(tag);
|
||||
}
|
||||
await expect(row.getByText(expected.tags.join(" · "), { exact: true })).toBeVisible();
|
||||
if (expected.notes !== undefined) {
|
||||
await expect(row.getByText(expected.notes, { exact: true })).toBeVisible();
|
||||
}
|
||||
@@ -195,7 +177,7 @@ export async function expectAgentProfileTagsGone(
|
||||
): Promise<void> {
|
||||
const row = agentProfileRow(page, input.name);
|
||||
for (const tag of input.tags) {
|
||||
await expect(row).not.toContainText(tag);
|
||||
await expect(row.getByText(tag, { exact: true })).toHaveCount(0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -214,22 +196,12 @@ export async function expectAgentProfileOrder(page: Page, names: string[]): Prom
|
||||
.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> {
|
||||
await openRowActionMenu(page, name);
|
||||
await page.getByRole("menuitem", { name: "Move up", exact: true }).click();
|
||||
await agentProfileRow(page, name).getByRole("button", { name: "Move up", exact: true }).click();
|
||||
}
|
||||
|
||||
export async function moveAgentProfileDown(page: Page, name: string): Promise<void> {
|
||||
await openRowActionMenu(page, name);
|
||||
await page.getByRole("menuitem", { name: "Move down", exact: true }).click();
|
||||
await agentProfileRow(page, name).getByRole("button", { name: "Move down", exact: true }).click();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -243,13 +215,12 @@ export async function removeAgentProfile(page: Page, name: string): Promise<void
|
||||
await dialog.accept();
|
||||
return message;
|
||||
});
|
||||
await openRowActionMenu(page, name);
|
||||
await page.getByRole("menuitem", { name: "Remove", exact: true }).click();
|
||||
await agentProfileRow(page, name).getByRole("button", { name: "Remove", exact: true }).click();
|
||||
expect(await dialogMessage).toContain(`Remove "${name}"?`);
|
||||
await expect(agentProfileRow(page, name)).toHaveCount(0, { timeout: 30_000 });
|
||||
}
|
||||
|
||||
// ─── Settings: the inspector drawer / edit sheet ───────────────────────────
|
||||
// ─── Settings: the edit modal ──────────────────────────────────────────────
|
||||
|
||||
export interface AgentProfileDraft {
|
||||
name?: string;
|
||||
@@ -260,96 +231,62 @@ export interface AgentProfileDraft {
|
||||
notes?: string;
|
||||
}
|
||||
|
||||
function editSurface(page: Page): Locator {
|
||||
return page.locator(
|
||||
'[data-testid="agent-profile-drawer"], [data-testid="agent-profile-edit-modal"]',
|
||||
);
|
||||
function editModal(page: Page): Locator {
|
||||
return page.getByTestId("agent-profile-edit-modal");
|
||||
}
|
||||
|
||||
async function chooseSelectFieldOption(
|
||||
page: Page,
|
||||
input: { field: "model" | "mode" | "thinking"; option: string },
|
||||
input: { field: "provider" | "model" | "mode" | "thinking"; option: string },
|
||||
): Promise<void> {
|
||||
await editSurface(page).getByTestId(`agent-profile-${input.field}-trigger`).click();
|
||||
await editModal(page).getByTestId(`agent-profile-${input.field}-trigger`).click();
|
||||
const option = page
|
||||
.getByTestId("combobox-desktop-container")
|
||||
.getByRole("button", { name: input.option, exact: true });
|
||||
await expect(option).toBeVisible({ timeout: 30_000 });
|
||||
await option.click();
|
||||
await expect(
|
||||
page.getByRole("button", { name: `${capitalize(input.field)} (${input.option})` }),
|
||||
).toBeVisible({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
async function ensureCustomizeExpanded(surface: Locator): Promise<void> {
|
||||
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();
|
||||
}
|
||||
function capitalize(value: string): string {
|
||||
return value.charAt(0).toUpperCase() + value.slice(1);
|
||||
}
|
||||
|
||||
async function fillAgentProfileForm(page: Page, draft: AgentProfileDraft): Promise<void> {
|
||||
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 });
|
||||
}
|
||||
const modal = editModal(page);
|
||||
if (draft.name !== undefined) {
|
||||
await surface.getByRole("textbox", { name: "Name", exact: true }).fill(draft.name);
|
||||
await modal.getByRole("textbox", { name: "Name", exact: true }).fill(draft.name);
|
||||
}
|
||||
if (draft.thinking !== undefined || draft.mode !== undefined || draft.notes !== undefined) {
|
||||
await ensureCustomizeExpanded(surface);
|
||||
// Provider first: it resets every provider-scoped field below it.
|
||||
if (draft.provider !== undefined) {
|
||||
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) {
|
||||
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) {
|
||||
await surface.getByRole("textbox", { name: "When to use", exact: true }).fill(draft.notes);
|
||||
await modal.getByRole("textbox", { name: "When to use", exact: true }).fill(draft.notes);
|
||||
}
|
||||
}
|
||||
|
||||
async function saveAgentProfile(page: Page): Promise<void> {
|
||||
await page.getByTestId("agent-profile-save-button").click();
|
||||
await expect(editSurface(page)).toHaveCount(0, { timeout: 30_000 });
|
||||
await editModal(page).getByRole("button", { name: "Save", exact: true }).click();
|
||||
await expect(editModal(page)).toHaveCount(0, { timeout: 30_000 });
|
||||
}
|
||||
|
||||
export async function createAgentProfile(page: Page, draft: AgentProfileDraft): Promise<void> {
|
||||
await page.getByTestId("agent-profiles-add-button").click();
|
||||
await expect(editSurface(page)).toBeVisible({ timeout: 30_000 });
|
||||
await page.getByRole("button", { name: "Add agent profile", exact: true }).click();
|
||||
await expect(editModal(page)).toBeVisible({ timeout: 30_000 });
|
||||
await fillAgentProfileForm(page, draft);
|
||||
await saveAgentProfile(page);
|
||||
}
|
||||
@@ -362,7 +299,7 @@ export async function createAgentProfileFromEmptyState(
|
||||
.getByTestId("agent-profiles-card")
|
||||
.getByRole("button", { name: "New profile", exact: true })
|
||||
.click();
|
||||
await expect(editSurface(page)).toBeVisible({ timeout: 30_000 });
|
||||
await expect(editModal(page)).toBeVisible({ timeout: 30_000 });
|
||||
await fillAgentProfileForm(page, draft);
|
||||
await saveAgentProfile(page);
|
||||
}
|
||||
@@ -372,183 +309,46 @@ export async function editAgentProfile(
|
||||
name: string,
|
||||
changes: AgentProfileDraft,
|
||||
): Promise<void> {
|
||||
await agentProfileRow(page, name).click();
|
||||
await expect(editSurface(page)).toBeVisible({ timeout: 30_000 });
|
||||
await agentProfileRow(page, name)
|
||||
.getByRole("button", { name: "Edit profile", exact: true })
|
||||
.click();
|
||||
await expect(editModal(page)).toBeVisible({ timeout: 30_000 });
|
||||
await fillAgentProfileForm(page, changes);
|
||||
await saveAgentProfile(page);
|
||||
}
|
||||
|
||||
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. */
|
||||
/** Opens the modal for a profile purely to read back what it stored. */
|
||||
export async function expectAgentProfileForm(
|
||||
page: Page,
|
||||
name: string,
|
||||
expected: { provider?: string; model?: string; mode?: string; notes?: string },
|
||||
): Promise<void> {
|
||||
await agentProfileRow(page, name).click();
|
||||
const surface = editSurface(page);
|
||||
await expect(surface).toBeVisible({ timeout: 30_000 });
|
||||
await expect(surface.getByRole("textbox", { name: "Name", exact: true })).toHaveValue(name);
|
||||
const notesHint = surface.getByTestId("agent-profile-notes-field-hint");
|
||||
await expect(notesHint).toHaveText("Tells agents when to pick this profile");
|
||||
await agentProfileRow(page, name)
|
||||
.getByRole("button", { name: "Edit profile", exact: true })
|
||||
.click();
|
||||
const modal = editModal(page);
|
||||
await expect(modal).toBeVisible({ timeout: 30_000 });
|
||||
await expect(modal.getByRole("textbox", { name: "Name", exact: true })).toHaveValue(name);
|
||||
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(
|
||||
"1",
|
||||
);
|
||||
if (expected.model) {
|
||||
await expect(surface.getByTestId("agent-profile-model-trigger")).toContainText(expected.model);
|
||||
} else if (expected.provider) {
|
||||
await expect(surface.getByTestId("agent-profile-model-trigger")).toContainText(
|
||||
expected.provider,
|
||||
);
|
||||
for (const [field, value] of Object.entries(expected)) {
|
||||
if (field === "notes") {
|
||||
await expect(modal.getByRole("textbox", { name: "When to use", exact: true })).toHaveValue(
|
||||
value,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
await expect(
|
||||
modal.getByRole("button", { name: `${capitalize(field)} (${value})` }),
|
||||
).toBeVisible({ timeout: 30_000 });
|
||||
}
|
||||
if (expected.provider) {
|
||||
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 });
|
||||
await modal.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
await expect(editModal(page)).toHaveCount(0, { timeout: 30_000 });
|
||||
}
|
||||
|
||||
// ─── The model picker ──────────────────────────────────────────────────────
|
||||
@@ -735,10 +535,7 @@ export async function expectModelRowProfileActionBesideRow(
|
||||
await expect(row.getByRole("button")).toHaveCount(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
/** The hover-revealed plus on an unprofiled model row opens a seeded profile form. */
|
||||
export async function expectCreateProfileFromModelRow(
|
||||
page: Page,
|
||||
input: { provider: string; modelId: string; modelLabel: string },
|
||||
@@ -751,14 +548,14 @@ export async function expectCreateProfileFromModelRow(
|
||||
await modelRow(page, input).hover();
|
||||
await expect(action).toHaveCSS("pointer-events", "auto");
|
||||
await action.click();
|
||||
|
||||
const toast = page.getByTestId("model-profile-created-toast");
|
||||
await expect(toast).toBeVisible({ timeout: 30_000 });
|
||||
await expect(toast).toContainText(input.modelLabel);
|
||||
|
||||
// Undo removes the newly saved profile from the toast.
|
||||
await toast.getByTestId("model-profile-created-undo").click();
|
||||
await expect(toast).toHaveCount(0, { timeout: 30_000 });
|
||||
const modal = editModal(page);
|
||||
await expect(modal).toBeVisible({ timeout: 30_000 });
|
||||
await expect(modal.getByRole("textbox", { name: "Name", exact: true })).toHaveValue(
|
||||
input.modelLabel,
|
||||
);
|
||||
await expect(modal.getByRole("button", { name: `Model (${input.modelLabel})` })).toBeVisible();
|
||||
await modal.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
await expect(modal).toHaveCount(0, { timeout: 30_000 });
|
||||
}
|
||||
|
||||
export async function selectModelRow(
|
||||
|
||||
@@ -31,8 +31,6 @@ export interface RewindCompletionGate {
|
||||
clearTimelineStreamCount(): void;
|
||||
release(): void;
|
||||
timelineStreamCount(): number;
|
||||
/** Timeline reads this page sent since the last clear. */
|
||||
timelineFetchCount(): number;
|
||||
waitForDelayedResponse(): Promise<void>;
|
||||
}
|
||||
|
||||
@@ -188,20 +186,12 @@ export async function holdDaemonHydration(page: Page): Promise<DaemonHydrationGa
|
||||
};
|
||||
}
|
||||
|
||||
// The rewind response and the timeline change it causes; the change removes the rewound row too.
|
||||
const REWIND_COMPLETION_MESSAGES = new Set([
|
||||
"agent.rewind.response",
|
||||
"agent.timeline.rewind",
|
||||
"agent.timeline.replacement",
|
||||
]);
|
||||
|
||||
export async function holdRewindCompletion(
|
||||
page: Page,
|
||||
agentId: string,
|
||||
): Promise<RewindCompletionGate> {
|
||||
let released = false;
|
||||
let timelineStreamCount = 0;
|
||||
let timelineFetchCount = 0;
|
||||
const delayedForwards: Array<() => void> = [];
|
||||
let resolveDelayedResponse: (() => void) | null = null;
|
||||
const delayedResponse = new Promise<void>((resolve) => {
|
||||
@@ -210,16 +200,7 @@ export async function holdRewindCompletion(
|
||||
|
||||
await page.routeWebSocket(daemonWsRoutePattern(), (ws) => {
|
||||
const server = ws.connectToServer();
|
||||
ws.onMessage((message) => {
|
||||
const sessionMessage = getSessionMessage(message);
|
||||
if (
|
||||
sessionMessage?.type === "fetch_agent_timeline_request" &&
|
||||
sessionMessage.agentId === agentId
|
||||
) {
|
||||
timelineFetchCount += 1;
|
||||
}
|
||||
server.send(message);
|
||||
});
|
||||
ws.onMessage((message) => server.send(message));
|
||||
server.onMessage((message) => {
|
||||
const sessionMessage = getSessionMessage(message);
|
||||
const payload = sessionMessage ? getPayload(sessionMessage) : null;
|
||||
@@ -235,11 +216,11 @@ export async function holdRewindCompletion(
|
||||
}
|
||||
if (
|
||||
!released &&
|
||||
sessionMessage &&
|
||||
REWIND_COMPLETION_MESSAGES.has(String(sessionMessage.type)) &&
|
||||
(sessionMessage?.type === "agent.rewind.response" ||
|
||||
sessionMessage?.type === "agent.timeline.replacement") &&
|
||||
payload?.agentId === agentId
|
||||
) {
|
||||
// The rewind also signals completion and removes the rewound row/menu.
|
||||
// The replacement also signals completion and removes the rewound row/menu.
|
||||
// Hold it with the response so the pending-state assertion observes a pending rewind.
|
||||
delayedForwards.push(() => ws.send(message));
|
||||
if (sessionMessage.type === "agent.rewind.response") resolveDelayedResponse?.();
|
||||
@@ -252,7 +233,6 @@ export async function holdRewindCompletion(
|
||||
return {
|
||||
clearTimelineStreamCount() {
|
||||
timelineStreamCount = 0;
|
||||
timelineFetchCount = 0;
|
||||
},
|
||||
release() {
|
||||
released = true;
|
||||
@@ -261,7 +241,6 @@ export async function holdRewindCompletion(
|
||||
}
|
||||
},
|
||||
timelineStreamCount: () => timelineStreamCount,
|
||||
timelineFetchCount: () => timelineFetchCount,
|
||||
waitForDelayedResponse: () => delayedResponse,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { promisify } from "node:util";
|
||||
import { once } from "node:events";
|
||||
import {
|
||||
spawn,
|
||||
execFile,
|
||||
@@ -11,6 +12,7 @@ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import net from "node:net";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { WebSocket } from "ws";
|
||||
import { withDisabledE2ESpeechEnv } from "./speech-env";
|
||||
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
|
||||
* enough: the port is released before the daemon binds it, and whatever takes
|
||||
* 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(
|
||||
port: number,
|
||||
child: ChildProcess,
|
||||
identity: { serverId: string; paseoHome: string },
|
||||
published: boolean,
|
||||
): Promise<void> {
|
||||
const deadline = Date.now() + 90_000;
|
||||
let lastError: unknown = null;
|
||||
@@ -82,7 +86,10 @@ async function waitForServer(
|
||||
}
|
||||
try {
|
||||
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}`);
|
||||
} catch (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
|
||||
* on a password-protected daemon; the daemon accepts the local credential it
|
||||
@@ -246,7 +259,7 @@ export async function startIsolatedHostDaemon(
|
||||
});
|
||||
|
||||
try {
|
||||
await waitForServer(port, spawned, { serverId, paseoHome });
|
||||
await waitForServer(port, spawned, { serverId, paseoHome }, Boolean(publishedPackageRoot));
|
||||
return spawned;
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
|
||||
@@ -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. */
|
||||
export async function openRelayPairingFromSetup(page: Page): Promise<Locator> {
|
||||
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();
|
||||
return pairing;
|
||||
}
|
||||
@@ -171,20 +171,9 @@ export async function closeRelayPairing(pairing: Locator): Promise<void> {
|
||||
await expect(pairing).toHaveCount(0);
|
||||
}
|
||||
|
||||
/** Clicks the Phone step's Tailscale row and returns the docs page it opened. */
|
||||
export async function openTailscaleDocsFromSetup(page: Page): Promise<string> {
|
||||
await page
|
||||
.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 async function expectTailscaleSwitchDisabled(page: Page): Promise<void> {
|
||||
const setup = setupModal(page);
|
||||
await expect(setup.getByRole("switch", { name: "Tailscale", exact: true })).toBeDisabled();
|
||||
}
|
||||
|
||||
export interface SetupHost {
|
||||
|
||||
@@ -9,6 +9,8 @@ import {
|
||||
selectSettingsHost,
|
||||
} from "./settings";
|
||||
import { expectAppRoute } from "./route-assertions";
|
||||
import { wsRoutePatternForPort } from "./daemon-port";
|
||||
import { goToSetupStep, showSetupAgainFromSettings } from "./onboarding";
|
||||
import { buildSettingsHostSectionRoute } from "@/utils/host-routes";
|
||||
|
||||
interface PairingHostInput {
|
||||
@@ -60,9 +62,33 @@ export async function prepareLocalPairingHost(
|
||||
await preparePairingHost(page, daemon, additionalHosts);
|
||||
}
|
||||
|
||||
type PairingHost =
|
||||
| Pick<IsolatedHostDaemon, "serverId" | "port">
|
||||
| Pick<OutdatedDaemon, "serverId" | "endpoint">;
|
||||
|
||||
export async function preparePairingHost(
|
||||
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[] = [],
|
||||
): Promise<void> {
|
||||
await seedSavedSettingsHosts(page, [
|
||||
@@ -74,20 +100,271 @@ export async function preparePairingHost(
|
||||
...additionalHosts,
|
||||
]);
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
await openSettingsHost(page, daemon.serverId);
|
||||
await expect(page.getByTestId("host-page-pair-device-row")).toHaveCount(0);
|
||||
await openSettingsHostSection(page, daemon.serverId, "pair-device");
|
||||
await expect(page.getByTestId("host-page-pair-device-row")).toBeVisible();
|
||||
}
|
||||
|
||||
export async function enableTailscale(page: Page): Promise<void> {
|
||||
const toggle = page.getByRole("switch", { name: "Tailscale", exact: true });
|
||||
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> {
|
||||
await page.getByRole("button", { name: /Pair a device/ }).click();
|
||||
await expect(page.getByTestId("host-page-pair-device-card")).toBeVisible();
|
||||
await page.getByRole("button", { name: "Relay", exact: true }).click();
|
||||
await expect(page.getByTestId("devices-relay-pairing")).toBeVisible();
|
||||
}
|
||||
|
||||
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(/end-to-end encrypted/)).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> {
|
||||
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> {
|
||||
@@ -124,10 +401,10 @@ export async function expectPairingOffer(page: Page): Promise<void> {
|
||||
|
||||
export async function closePairDeviceModal(page: Page): Promise<void> {
|
||||
await page
|
||||
.getByTestId("host-page-pair-device-card")
|
||||
.getByTestId("devices-relay-pairing")
|
||||
.getByRole("button", { name: "Close", 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 reloadAndOpenPairDevice(page: Page): Promise<void> {
|
||||
@@ -145,7 +422,7 @@ export async function enableRelayAndExpectFailure(
|
||||
expectedError = "Relay is controlled by a daemon launch override",
|
||||
): Promise<void> {
|
||||
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("button", { name: "Retry", exact: true })).toBeEnabled();
|
||||
await expect(modal.getByRole("textbox", { name: "Pairing link" })).toHaveCount(0);
|
||||
@@ -155,7 +432,7 @@ export async function retryRelayAndExpectFailure(
|
||||
page: Page,
|
||||
expectedError = "Relay is controlled by a daemon launch override",
|
||||
): 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 expect(modal.getByRole("alert")).toContainText(expectedError);
|
||||
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> {
|
||||
const modal = page.getByTestId("host-page-pair-device-card");
|
||||
const modal = page.getByTestId("devices-relay-pairing");
|
||||
await expect(
|
||||
modal.getByText("Update the host to enable relay from Paseo Desktop."),
|
||||
).toBeVisible();
|
||||
@@ -195,15 +472,15 @@ export function observePairingOfferRequests(page: Page, daemon: OutdatedDaemon):
|
||||
}
|
||||
|
||||
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("button", { name: "Retry", exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
export async function switchPairDeviceToHost(page: Page, serverId: string): Promise<void> {
|
||||
await selectSettingsHost(page, serverId);
|
||||
await expectAppRoute(page, buildSettingsHostSectionRoute(serverId, "pair-device"));
|
||||
await expect(page.getByTestId("host-page-pair-device-row")).toBeVisible();
|
||||
await expectAppRoute(page, buildSettingsHostSectionRoute(serverId, "devices"));
|
||||
await expect(page.getByTestId("devices-relay")).toBeVisible();
|
||||
}
|
||||
|
||||
export async function openRelaySecurityDocs(page: Page): Promise<void> {
|
||||
|
||||
@@ -66,7 +66,7 @@ export type SettingsSection = keyof typeof SECTION_LABELS;
|
||||
type HostSection =
|
||||
| "projects"
|
||||
| "connections"
|
||||
| "pair-device"
|
||||
| "devices"
|
||||
| "agents"
|
||||
| "metadata"
|
||||
| "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;
|
||||
}
|
||||
}
|
||||
@@ -1,76 +1,11 @@
|
||||
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 { useCallback, useMemo, useState, type ReactElement } from "react";
|
||||
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 { generateAgentProfileId } from "./internal/profile-id";
|
||||
import {
|
||||
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} />;
|
||||
}
|
||||
import type { AgentProfileSeed, AgentProfileValue } from "./internal/profile-form-model";
|
||||
import { useAgentProfiles } from "./internal/use-agent-profiles";
|
||||
|
||||
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. */
|
||||
openCreateFromModel: (seed: AgentProfileSeed) => void;
|
||||
/** Open the edit form for one profile. */
|
||||
@@ -88,78 +23,8 @@ type EditorRequest =
|
||||
* never see `saveProfiles` or construct profile records themselves.
|
||||
*/
|
||||
export function useAgentProfileEditor(serverId: string | null): AgentProfileEditorControls {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const { profiles, mutateProfiles } = useAgentProfiles(serverId);
|
||||
const { entries } = useProvidersSnapshot(serverId, { cwd: null });
|
||||
const { profiles, saveProfiles } = useAgentProfiles(serverId);
|
||||
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) => {
|
||||
setRequest({ mode: "create", seed });
|
||||
@@ -180,59 +45,15 @@ export function useAgentProfileEditor(serverId: string | null): AgentProfileEdit
|
||||
|
||||
const handleSave = useCallback(
|
||||
async (value: AgentProfileValue) => {
|
||||
const savedRequest = request;
|
||||
const editing = savedRequest?.mode === "edit" ? savedRequest.profile : undefined;
|
||||
const written = await mutateProfiles((current) =>
|
||||
editing
|
||||
? current.map((entry) => (entry.id === editing.id ? { id: entry.id, ...value } : entry))
|
||||
: [...current, { id: generateAgentProfileId(), ...value }],
|
||||
);
|
||||
if (!written) {
|
||||
return;
|
||||
}
|
||||
setRequest((current) => (current === savedRequest ? null : current));
|
||||
const current = profiles ?? [];
|
||||
const editing = request?.mode === "edit" ? request.profile : undefined;
|
||||
const next: AgentProfile[] = editing
|
||||
? current.map((entry) => (entry.id === editing.id ? { id: entry.id, ...value } : entry))
|
||||
: [...current, { id: generateAgentProfileId(), ...value }];
|
||||
await saveProfiles(next);
|
||||
setRequest(null);
|
||||
},
|
||||
[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],
|
||||
[profiles, request, saveProfiles],
|
||||
);
|
||||
|
||||
const element = useMemo(
|
||||
@@ -245,34 +66,13 @@ export function useAgentProfileEditor(serverId: string | null): AgentProfileEdit
|
||||
{...(request?.mode === "create" && request.seed ? { seed: request.seed } : {})}
|
||||
onClose={close}
|
||||
onSave={handleSave}
|
||||
onRemove={handleRemove}
|
||||
/>
|
||||
),
|
||||
[close, handleRemove, handleSave, request, serverId],
|
||||
[close, handleSave, request, serverId],
|
||||
);
|
||||
|
||||
return useMemo(
|
||||
() => ({ quickCreateFromModel, undoCreate, openCreateFromModel, openEdit, element }),
|
||||
[element, openCreateFromModel, openEdit, quickCreateFromModel, undoCreate],
|
||||
() => ({ openCreateFromModel, openEdit, element }),
|
||||
[openCreateFromModel, openEdit, element],
|
||||
);
|
||||
}
|
||||
|
||||
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,7 +27,4 @@ export {
|
||||
type DraftAgentProfileControls,
|
||||
} from "./internal/use-agent-profile-picker";
|
||||
export { AgentProfileGlyph } from "./internal/agent-profile-glyph";
|
||||
export {
|
||||
AgentProfilesPage,
|
||||
type AgentProfilesBeforeLeaveGuard,
|
||||
} from "./settings/agent-profiles-section";
|
||||
export { AgentProfilesSection } from "./settings/agent-profiles-section";
|
||||
|
||||
@@ -31,7 +31,6 @@ import {
|
||||
TestTube,
|
||||
Wrench,
|
||||
} from "lucide-react-native";
|
||||
import { useProviderIcon } from "@/components/provider-icons";
|
||||
import { identityForeground } from "@/styles/identity-colors";
|
||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||
import {
|
||||
@@ -109,57 +108,21 @@ export function agentProfileColorMapping(
|
||||
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 roster, model picker,
|
||||
* 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.
|
||||
* How a profile is drawn everywhere it appears — settings list, model picker,
|
||||
* and the picker grid's own cells. One component so the three can't drift.
|
||||
*/
|
||||
export function AgentProfileGlyph({
|
||||
icon,
|
||||
color,
|
||||
provider,
|
||||
serverId,
|
||||
size = ICON_SIZE.md,
|
||||
}: {
|
||||
icon?: string | undefined;
|
||||
color?: string | undefined;
|
||||
provider?: string | undefined;
|
||||
serverId?: string | null | undefined;
|
||||
size?: number;
|
||||
}) {
|
||||
const iconKey = resolveAgentProfileIconKey(icon);
|
||||
const mapping = COLOR_MAPPINGS[resolveAgentProfileColor(color)];
|
||||
if (iconKey) {
|
||||
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} />;
|
||||
const Icon = iconKey ? THEMED_ICONS[iconKey] : ThemedDefaultIcon;
|
||||
return <Icon size={size} uniProps={mapping} />;
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
buildControlsRequestKey,
|
||||
buildInstantAgentProfile,
|
||||
openAgentProfileForm,
|
||||
type AgentProfileFormModel,
|
||||
} from "./profile-form-model";
|
||||
@@ -71,10 +70,6 @@ function optionValues(options: readonly { value: string }[]): string[] {
|
||||
return options.map((option) => option.value);
|
||||
}
|
||||
|
||||
function optionIds(options: readonly { id: string }[]): string[] {
|
||||
return options.map((option) => option.id);
|
||||
}
|
||||
|
||||
const FAST = {
|
||||
controls: [{ type: "toggle" as const, key: "fast_mode", label: "Fast" }],
|
||||
options: { fast_mode: false },
|
||||
@@ -533,71 +528,16 @@ describe("openAgentProfileForm", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps previous provider controls mounted while another model's answer is pending to prevent layout jank", () => {
|
||||
it("draws no controls for the previous model while another model's answer is pending", () => {
|
||||
const model = openWithCatalog({ mode: "create" });
|
||||
selectClaude(model);
|
||||
model.applyControls(model.getState().controlsRequestKey ?? "", WEB_SEARCH_CONTROLS);
|
||||
|
||||
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([]);
|
||||
});
|
||||
|
||||
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", () => {
|
||||
const model = toggledOnOpus();
|
||||
expect(model.getState().submitValue?.options).toEqual({ fast_mode: true });
|
||||
@@ -703,36 +643,6 @@ describe("openAgentProfileForm", () => {
|
||||
expect(notifications).toBe(1);
|
||||
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", () => {
|
||||
@@ -747,55 +657,3 @@ 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,16 +41,6 @@ export interface AgentProfileFormOption {
|
||||
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
|
||||
* mode always seeds from the stored `profile` and ignores this.
|
||||
@@ -65,8 +55,6 @@ export interface AgentProfileFormSnapshot {
|
||||
mode: "create" | "edit";
|
||||
profile?: AgentProfile;
|
||||
seed?: AgentProfileSeed;
|
||||
/** Optional cached host catalog so the first render is already hydrated without a layout flash. */
|
||||
entries?: readonly ProviderSnapshotEntry[];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -109,7 +97,6 @@ export interface AgentProfileFormState {
|
||||
optionEdits: ProviderOptions;
|
||||
|
||||
providerOptions: AgentProfileFormOption[];
|
||||
unifiedModelOptions: AgentProfileUnifiedModelOption[];
|
||||
modelOptions: AgentProfileFormOption[];
|
||||
modeOptions: AgentProfileFormOption[];
|
||||
thinkingOptions: AgentProfileFormOption[];
|
||||
@@ -128,14 +115,10 @@ export interface AgentProfileFormState {
|
||||
|
||||
catalogResolution: AgentProfileResolutionStatus;
|
||||
controlsResolution: AgentProfileResolutionStatus;
|
||||
controlsPending: boolean;
|
||||
controlsRequest: AgentProfileControlsRequest | null;
|
||||
controlsRequestKey: string | null;
|
||||
|
||||
disclosure: AgentProfileFormDisclosure;
|
||||
isDirty: boolean;
|
||||
/** Monotonic counter incremented on every user edit that changes the draft. */
|
||||
draftRevision: number;
|
||||
isSubmitting: boolean;
|
||||
submitError: string | null;
|
||||
canSubmit: boolean;
|
||||
@@ -159,11 +142,6 @@ export interface AgentProfileFormModel {
|
||||
setAppearance: (value: { icon: string; color: string }) => void;
|
||||
setNotes: (value: string) => 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;
|
||||
setMode: (modeId: string, display: AgentProfileFormDisplay | null) => void;
|
||||
setThinking: (thinkingOptionId: string, display: AgentProfileFormDisplay | null) => void;
|
||||
@@ -246,53 +224,6 @@ 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[] {
|
||||
return models.map((model) =>
|
||||
formOption({
|
||||
@@ -454,28 +385,6 @@ export function buildControlsRequestKey(
|
||||
: 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 {
|
||||
const name = state.name.trim();
|
||||
const notes = state.notes.trim();
|
||||
@@ -537,7 +446,6 @@ function buildInitialState(snapshot: AgentProfileFormSnapshot): AgentProfileForm
|
||||
options: { ...profile.options },
|
||||
optionEdits: {},
|
||||
providerOptions: [],
|
||||
unifiedModelOptions: [],
|
||||
modelOptions: [],
|
||||
modeOptions: [],
|
||||
thinkingOptions: [],
|
||||
@@ -551,7 +459,6 @@ function buildInitialState(snapshot: AgentProfileFormSnapshot): AgentProfileForm
|
||||
thinkingDisplay: seedDisplay(profile.thinkingOptionId),
|
||||
catalogResolution: "idle",
|
||||
controlsResolution: "idle",
|
||||
controlsPending: false,
|
||||
controlsRequest: null,
|
||||
controlsRequestKey: null,
|
||||
disclosure: {
|
||||
@@ -560,8 +467,6 @@ function buildInitialState(snapshot: AgentProfileFormSnapshot): AgentProfileForm
|
||||
showThinkingField: false,
|
||||
showControlsField: false,
|
||||
},
|
||||
isDirty: false,
|
||||
draftRevision: 0,
|
||||
isSubmitting: false,
|
||||
submitError: null,
|
||||
canSubmit: false,
|
||||
@@ -569,118 +474,17 @@ 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 {
|
||||
let entries: readonly ProviderSnapshotEntry[] = snapshot.entries ? [...snapshot.entries] : [];
|
||||
let catalogResolution: AgentProfileResolutionStatus = snapshot.entries ? "complete" : "idle";
|
||||
let entries: readonly ProviderSnapshotEntry[] = [];
|
||||
let catalogResolution: AgentProfileResolutionStatus = "idle";
|
||||
let resolvedControlsKey: string | null = null;
|
||||
let resolvedScopeKey: string | null = null;
|
||||
let resolvedProvider: string | null = null;
|
||||
let resolvedControls: AgentOptionControl[] = [];
|
||||
let resolvedOptions: ProviderOptions = {};
|
||||
let drawnKeys: ReadonlySet<string> = new Set();
|
||||
let answeredKeys: ReadonlySet<string> = new Set();
|
||||
let listeners = new Set<() => void>();
|
||||
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 {
|
||||
const models = resolveModels(entries, incoming.provider);
|
||||
@@ -698,21 +502,24 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
|
||||
const controlsRequest = buildControlsRequest(next);
|
||||
const controlsRequestKey = buildControlsRequestKey(controlsRequest);
|
||||
const controlsScopeKey = buildControlsScopeKey(controlsRequest);
|
||||
const { controls, controlOptions, controlsResolution } = resolveControlsSlice({
|
||||
next,
|
||||
controlsRequestKey,
|
||||
controlsScopeKey,
|
||||
resolvedControlsKey,
|
||||
resolvedScopeKey,
|
||||
resolvedProvider,
|
||||
resolvedControls,
|
||||
resolvedOptions,
|
||||
});
|
||||
const featuresAreCurrent =
|
||||
controlsRequestKey !== null && controlsRequestKey === resolvedControlsKey;
|
||||
// A toggle changes only the options, so the controls stay up while the daemon answers and the
|
||||
// toggle shows over the last answer. A change of provider, model, mode or thinking draws none
|
||||
// until its own answer arrives.
|
||||
const controlsApply = controlsScopeKey !== null && controlsScopeKey === resolvedScopeKey;
|
||||
const controls = controlsApply ? resolvedControls : [];
|
||||
let controlOptions: ProviderOptions = next.options;
|
||||
if (controlsApply) {
|
||||
controlOptions = featuresAreCurrent
|
||||
? resolvedOptions
|
||||
: { ...resolvedOptions, ...next.optionEdits };
|
||||
}
|
||||
const controlsResolution = resolveControlsStatus(controlsRequestKey, featuresAreCurrent);
|
||||
|
||||
const withOptions: AgentProfileFormState = {
|
||||
...next,
|
||||
providerOptions: buildProviderOptions(entries),
|
||||
unifiedModelOptions: buildUnifiedModelOptions(entries),
|
||||
modelOptions: buildModelOptions(models),
|
||||
modeOptions: buildModeOptions(modes),
|
||||
thinkingOptions: buildThinkingOptions(thinking),
|
||||
@@ -731,16 +538,21 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
|
||||
modeDisplay: refineDisplay(
|
||||
next.modeDisplay,
|
||||
next.modeId,
|
||||
resolveModeLabel(modes, next.modeId),
|
||||
(() => {
|
||||
const mode = modes.find((entry) => entry.id === next.modeId);
|
||||
return mode ? formatAgentModeLabel(mode) : null;
|
||||
})(),
|
||||
),
|
||||
thinkingDisplay: refineDisplay(
|
||||
next.thinkingDisplay,
|
||||
next.thinkingOptionId,
|
||||
resolveThinkingLabel(thinking, next.thinkingOptionId),
|
||||
(() => {
|
||||
const option = thinking.find((entry) => entry.id === next.thinkingOptionId);
|
||||
return option ? formatThinkingOptionLabel(option) : null;
|
||||
})(),
|
||||
),
|
||||
catalogResolution,
|
||||
controlsResolution,
|
||||
controlsPending: controlsResolution === "pending",
|
||||
controlsRequest,
|
||||
controlsRequestKey,
|
||||
};
|
||||
@@ -760,40 +572,16 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
|
||||
withOptions.provider.length > 0 &&
|
||||
!withOptions.isSubmitting;
|
||||
const resolved: AgentProfileFormState = { ...withOptions, disclosure, canSubmit };
|
||||
const submitValue = canSubmit ? buildSubmitValue(resolved) : null;
|
||||
const isDirty =
|
||||
baselineFingerprint.length > 0 && formDraftFingerprint(resolved) !== baselineFingerprint;
|
||||
return { ...resolved, isDirty, draftRevision, submitValue };
|
||||
return { ...resolved, submitValue: canSubmit ? buildSubmitValue(resolved) : null };
|
||||
}
|
||||
|
||||
let state: AgentProfileFormState = derive(buildInitialState(snapshot));
|
||||
baselineFingerprint = formDraftFingerprint(state);
|
||||
|
||||
function publish(
|
||||
mutate: (current: AgentProfileFormState) => AgentProfileFormState,
|
||||
options?: { userEdit?: boolean },
|
||||
): void {
|
||||
function publish(mutate: (current: AgentProfileFormState) => AgentProfileFormState): void {
|
||||
if (closed) {
|
||||
return;
|
||||
}
|
||||
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;
|
||||
state = derive(mutate(state));
|
||||
for (const listener of listeners) {
|
||||
listener();
|
||||
}
|
||||
@@ -822,7 +610,6 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
|
||||
}
|
||||
resolvedControlsKey = requestKey;
|
||||
resolvedScopeKey = buildControlsScopeKey(state.controlsRequest);
|
||||
resolvedProvider = state.provider || null;
|
||||
resolvedControls = [...resolved.controls];
|
||||
resolvedOptions = resolved.options;
|
||||
answeredKeys = new Set(resolved.controls.map((control) => control.key));
|
||||
@@ -835,149 +622,66 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
|
||||
}
|
||||
resolvedControlsKey = requestKey;
|
||||
resolvedScopeKey = buildControlsScopeKey(state.controlsRequest);
|
||||
resolvedProvider = state.provider || null;
|
||||
resolvedControls = [];
|
||||
resolvedOptions = {};
|
||||
publish((current) => current);
|
||||
},
|
||||
setName: (value) =>
|
||||
publish(
|
||||
(current) => {
|
||||
if (value !== autoSuggestedName) {
|
||||
autoSuggestedName = null;
|
||||
}
|
||||
return { ...current, name: value };
|
||||
},
|
||||
{ userEdit: true },
|
||||
),
|
||||
setName: (value) => publish((current) => ({ ...current, name: value })),
|
||||
setAppearance: (value) =>
|
||||
publish((current) => ({ ...current, icon: value.icon, color: value.color }), {
|
||||
userEdit: true,
|
||||
}),
|
||||
setNotes: (value) => publish((current) => ({ ...current, notes: value }), { userEdit: true }),
|
||||
publish((current) => ({ ...current, icon: value.icon, color: value.color })),
|
||||
setNotes: (value) => publish((current) => ({ ...current, notes: value })),
|
||||
setProvider: (providerId, display) =>
|
||||
publish(
|
||||
(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.
|
||||
// Clearing them is enough — `derive` seeds the new provider's defaults.
|
||||
drawnKeys = new Set();
|
||||
answeredKeys = new Set();
|
||||
resolvedProvider = null;
|
||||
resolvedScopeKey = null;
|
||||
resolvedControlsKey = null;
|
||||
resolvedControls = [];
|
||||
resolvedOptions = {};
|
||||
return {
|
||||
...current,
|
||||
provider: providerId,
|
||||
providerDisplay: display,
|
||||
modelId: "",
|
||||
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) =>
|
||||
publish(
|
||||
(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.
|
||||
const nextThinking = resolveThinkingOptions(entries, current.provider, modelId);
|
||||
const keepsThinking =
|
||||
current.thinkingOptionId.length > 0 &&
|
||||
nextThinking.some((option) => option.id === current.thinkingOptionId);
|
||||
return {
|
||||
...current,
|
||||
modelId,
|
||||
modelDisplay: display,
|
||||
thinkingOptionId: keepsThinking ? current.thinkingOptionId : "",
|
||||
thinkingDisplay: keepsThinking ? current.thinkingDisplay : null,
|
||||
};
|
||||
},
|
||||
{ userEdit: true },
|
||||
),
|
||||
setMode: (modeId, display) =>
|
||||
publish((current) => ({ ...current, modeId, modeDisplay: display }), { userEdit: true }),
|
||||
setThinking: (thinkingOptionId, display) =>
|
||||
publish((current) => ({ ...current, thinkingOptionId, thinkingDisplay: display }), {
|
||||
userEdit: true,
|
||||
}),
|
||||
setOption: (key, value) =>
|
||||
publish(
|
||||
(current) => ({
|
||||
publish((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.
|
||||
// Clearing them is enough — `derive` seeds the new provider's defaults.
|
||||
drawnKeys = new Set();
|
||||
answeredKeys = new Set();
|
||||
return {
|
||||
...current,
|
||||
optionEdits: { ...current.optionEdits, [key]: value },
|
||||
}),
|
||||
{ userEdit: true },
|
||||
),
|
||||
provider: providerId,
|
||||
providerDisplay: display,
|
||||
modelId: "",
|
||||
modelDisplay: null,
|
||||
modeId: "",
|
||||
modeDisplay: null,
|
||||
thinkingOptionId: "",
|
||||
thinkingDisplay: null,
|
||||
options: {},
|
||||
optionEdits: {},
|
||||
};
|
||||
}),
|
||||
setModel: (modelId, display) =>
|
||||
publish((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.
|
||||
const nextThinking = resolveThinkingOptions(entries, current.provider, modelId);
|
||||
const keepsThinking =
|
||||
current.thinkingOptionId.length > 0 &&
|
||||
nextThinking.some((option) => option.id === current.thinkingOptionId);
|
||||
return {
|
||||
...current,
|
||||
modelId,
|
||||
modelDisplay: display,
|
||||
thinkingOptionId: keepsThinking ? current.thinkingOptionId : "",
|
||||
thinkingDisplay: keepsThinking ? current.thinkingDisplay : null,
|
||||
};
|
||||
}),
|
||||
setMode: (modeId, display) =>
|
||||
publish((current) => ({ ...current, modeId, modeDisplay: display })),
|
||||
setThinking: (thinkingOptionId, display) =>
|
||||
publish((current) => ({ ...current, thinkingOptionId, thinkingDisplay: display })),
|
||||
setOption: (key, value) =>
|
||||
publish((current) => ({
|
||||
...current,
|
||||
optionEdits: { ...current.optionEdits, [key]: value },
|
||||
})),
|
||||
setSubmitting: (value) => publish((current) => ({ ...current, isSubmitting: value })),
|
||||
setSubmitError: (value) => publish((current) => ({ ...current, submitError: value })),
|
||||
};
|
||||
|
||||
@@ -1,83 +0,0 @@
|
||||
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,55 +7,6 @@ export interface AgentProfileTag {
|
||||
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(
|
||||
entries: readonly ProviderSnapshotEntry[],
|
||||
provider: string,
|
||||
|
||||
@@ -1,171 +0,0 @@
|
||||
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")]);
|
||||
});
|
||||
});
|
||||
@@ -1,65 +0,0 @@
|
||||
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,21 +1,8 @@
|
||||
import { useCallback, useMemo } from "react";
|
||||
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 { useCallback } from "react";
|
||||
import type { AgentProfile } from "@getpaseo/protocol/messages";
|
||||
import { useDaemonConfig } from "@/hooks/use-daemon-config";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { supportsAgentProfiles } from "./capabilities";
|
||||
import {
|
||||
createAgentProfileWriteQueue,
|
||||
removeAgentProfileById,
|
||||
type AgentProfileListUpdater,
|
||||
} from "./profile-write-queue";
|
||||
|
||||
const sharedProfileWriteQueue = createAgentProfileWriteQueue();
|
||||
|
||||
export { removeAgentProfileById };
|
||||
export type { AgentProfileListUpdater };
|
||||
|
||||
export interface UseAgentProfilesResult {
|
||||
/** `null` until the daemon config has arrived. */
|
||||
@@ -24,56 +11,24 @@ export interface UseAgentProfilesResult {
|
||||
isSupported: boolean;
|
||||
/** Writes the whole list; there is no per-profile RPC. */
|
||||
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 {
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
const { config, patchConfig } = useDaemonConfig(serverId);
|
||||
const queryKey = useMemo(() => daemonConfigQueryKey(serverId), [serverId]);
|
||||
const isSupported = useSessionStore((state) => {
|
||||
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(
|
||||
async (next: AgentProfile[]) => {
|
||||
await mutateProfiles(() => next);
|
||||
await patchConfig({ agentProfiles: next });
|
||||
},
|
||||
[mutateProfiles],
|
||||
[patchConfig],
|
||||
);
|
||||
|
||||
return {
|
||||
profiles: config ? (config.agentProfiles ?? []) : null,
|
||||
isSupported,
|
||||
saveProfiles,
|
||||
mutateProfiles,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,20 +1,14 @@
|
||||
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 { useEffect, useState, useSyncExternalStore } from "react";
|
||||
import {
|
||||
openAgentProfileForm,
|
||||
type AgentProfileFormModel,
|
||||
type AgentProfileFormSnapshot,
|
||||
type AgentProfileFormState,
|
||||
type AgentProfileSeed,
|
||||
type AgentProfileValue,
|
||||
} from "./profile-form-model";
|
||||
import { useAgentProfileFormCatalog, useAgentProfileFormControls } from "./use-profile-form-inputs";
|
||||
|
||||
/**
|
||||
* One model per mount. The sheet or drawer host keys its session on mode + profile id,
|
||||
* so create and edit never share an instance and reopening always starts from the record.
|
||||
* One model per mount. The modal keys its body on mode + profile id, so create
|
||||
* and edit never share an instance and reopening always starts from the record.
|
||||
*/
|
||||
export function useAgentProfileFormModel(
|
||||
snapshot: AgentProfileFormSnapshot,
|
||||
@@ -33,78 +27,3 @@ export function useAgentProfileFormModel(
|
||||
export function useAgentProfileFormState(model: AgentProfileFormModel): AgentProfileFormState {
|
||||
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,19 +1,16 @@
|
||||
import { useCallback, useMemo, useRef, useState, type ReactElement } from "react";
|
||||
import { View, type PressableStateCallbackType } from "react-native";
|
||||
import { Pressable, View, type PressableStateCallbackType } from "react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { TFunction } from "i18next";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { Check, ChevronDown } from "lucide-react-native";
|
||||
import { Combobox, type ComboboxOption } from "@/components/ui/combobox";
|
||||
import {
|
||||
bySizing,
|
||||
createControlGeometry,
|
||||
resolveControlInteractionStyles,
|
||||
TOUCH_TARGET,
|
||||
type ControlSize,
|
||||
} from "@/components/ui/control-geometry";
|
||||
import { mutedIconColorMapping } from "@/components/ui/icon-color";
|
||||
import { PressHighlight } from "@/components/ui/press-highlight";
|
||||
import { Field } from "@/components/ui/form-field";
|
||||
import { identityForeground } from "@/styles/identity-colors";
|
||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||
import { AgentProfileGlyph } from "../internal/agent-profile-glyph";
|
||||
@@ -40,6 +37,7 @@ const EMPTY_COMBOBOX_OPTIONS: ComboboxOption[] = [];
|
||||
const ThemedChevronDown = withUnistyles(ChevronDown);
|
||||
const ThemedCheck = withUnistyles(Check);
|
||||
|
||||
const foregroundMutedMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
|
||||
const onIdentityMapping = (theme: Theme) => ({ color: theme.colors.background });
|
||||
|
||||
/**
|
||||
@@ -58,43 +56,39 @@ function IconCell({
|
||||
iconKey,
|
||||
selected,
|
||||
color,
|
||||
provider,
|
||||
serverId,
|
||||
onSelect,
|
||||
}: {
|
||||
iconKey: AgentProfileIconKey | null;
|
||||
selected: boolean;
|
||||
color: AgentProfileColor;
|
||||
provider?: string;
|
||||
serverId?: string | null;
|
||||
onSelect: (iconKey: AgentProfileIconKey | null) => void;
|
||||
}) {
|
||||
const handlePress = useCallback(() => onSelect(iconKey), [iconKey, onSelect]);
|
||||
const accessibilityState = useMemo(() => ({ selected }), [selected]);
|
||||
const cellStyle = useCallback(
|
||||
({ hovered }: PressableStateCallbackType & { hovered?: boolean }) => [
|
||||
({ hovered, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [
|
||||
styles.cell,
|
||||
Boolean(hovered) && styles.cellHovered,
|
||||
pressed && styles.cellPressed,
|
||||
selected && styles.cellSelected,
|
||||
],
|
||||
[selected],
|
||||
);
|
||||
return (
|
||||
<PressHighlight
|
||||
<Pressable
|
||||
onPress={handlePress}
|
||||
style={cellStyle}
|
||||
highlightStyle={styles.cellPressed}
|
||||
accessibilityRole="button"
|
||||
accessibilityState={accessibilityState}
|
||||
accessibilityLabel={iconKey ?? "default"}
|
||||
testID={`agent-profile-icon-cell-${iconKey ?? "default"}`}
|
||||
>
|
||||
<AgentProfileGlyph
|
||||
{...(iconKey ? { icon: iconKey } : { provider, serverId })}
|
||||
{...(iconKey ? { icon: iconKey } : {})}
|
||||
color={color}
|
||||
size={ICON_SIZE.lg}
|
||||
/>
|
||||
</PressHighlight>
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -110,54 +104,58 @@ function ColorCell({
|
||||
const { t } = useTranslation();
|
||||
const handlePress = useCallback(() => onSelect(color), [color, onSelect]);
|
||||
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 (
|
||||
<PressHighlight
|
||||
<Pressable
|
||||
onPress={handlePress}
|
||||
style={styles.colorCell}
|
||||
highlightStyle={styles.cellPressed}
|
||||
style={cellStyle}
|
||||
accessibilityRole="button"
|
||||
accessibilityState={accessibilityState}
|
||||
accessibilityLabel={colorLabel(t, color)}
|
||||
testID={`agent-profile-color-cell-${color}`}
|
||||
>
|
||||
<View style={[styles.swatch, color === "none" ? styles.swatchNone : identitySwatch(color)]}>
|
||||
<View style={swatchStyle}>
|
||||
{selected ? (
|
||||
<ThemedCheck
|
||||
size={ICON_SIZE.sm}
|
||||
uniProps={color === "none" ? mutedIconColorMapping : onIdentityMapping}
|
||||
uniProps={color === "none" ? foregroundMutedMapping : onIdentityMapping}
|
||||
/>
|
||||
) : null}
|
||||
</View>
|
||||
</PressHighlight>
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Compact clickable icon+color tile that opens the appearance popover without
|
||||
* requiring a separate labeled field box. Used inline beside the Name input
|
||||
* and in the inspector drawer header.
|
||||
* Icon and colour in one popover rather than two fields: the pair is a single
|
||||
* visual decision, and picking them apart means never seeing the result until
|
||||
* both are closed. The grid redraws in the chosen colour as you switch colours,
|
||||
* so the swatch row sits above it.
|
||||
*/
|
||||
export function AgentProfileIconButton({
|
||||
export function AgentProfileAppearanceField({
|
||||
label,
|
||||
icon,
|
||||
color,
|
||||
provider,
|
||||
serverId,
|
||||
onChange,
|
||||
size = "md",
|
||||
variant = "field",
|
||||
disabled = false,
|
||||
testID,
|
||||
triggerTestID,
|
||||
}: {
|
||||
label: string;
|
||||
icon: string;
|
||||
color: string;
|
||||
provider?: string;
|
||||
serverId?: string | null;
|
||||
onChange: (next: { icon: string; color: string }) => void;
|
||||
size?: ControlSize;
|
||||
variant?: "field" | "hero";
|
||||
disabled?: boolean;
|
||||
testID?: string;
|
||||
triggerTestID?: string;
|
||||
}): ReactElement {
|
||||
const { t } = useTranslation();
|
||||
@@ -190,10 +188,8 @@ export function AgentProfileIconButton({
|
||||
const triggerStyle = useCallback(
|
||||
({ hovered, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [
|
||||
styles.trigger,
|
||||
variant === "hero" && styles.triggerHero,
|
||||
variant !== "hero" && size === "sm" && styles.triggerSm,
|
||||
variant !== "hero" && size !== "sm" && styles.triggerMd,
|
||||
variant === "field" && styles.triggerIconOnly,
|
||||
size === "sm" ? styles.triggerSm : styles.triggerMd,
|
||||
styles.triggerIconOnly,
|
||||
resolveControlInteractionStyles(
|
||||
{
|
||||
controlRest: styles.controlRest,
|
||||
@@ -204,36 +200,29 @@ export function AgentProfileIconButton({
|
||||
{ hovered: Boolean(hovered), active: pressed || open, disabled },
|
||||
),
|
||||
],
|
||||
[disabled, open, size, variant],
|
||||
[disabled, open, size],
|
||||
);
|
||||
|
||||
const header = useMemo(() => ({ title: label }), [label]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Field label={label} testID={testID}>
|
||||
<View ref={anchorRef} collapsable={false}>
|
||||
<PressHighlight
|
||||
<Pressable
|
||||
onPress={handleTriggerPress}
|
||||
disabled={disabled}
|
||||
style={triggerStyle}
|
||||
highlightStyle={styles.triggerPressed}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={`${label} (${colorLabel(t, selectedColor)})`}
|
||||
testID={triggerTestID}
|
||||
>
|
||||
<AgentProfileGlyph
|
||||
{...(selectedIcon ? { icon: selectedIcon } : { provider, serverId })}
|
||||
{...(selectedIcon ? { icon: selectedIcon } : {})}
|
||||
color={selectedColor}
|
||||
size={variant === "hero" ? ICON_SIZE.lg : ICON_SIZE.md}
|
||||
size={ICON_SIZE.md}
|
||||
/>
|
||||
{variant === "hero" ? (
|
||||
<View style={styles.heroCaretBadge}>
|
||||
<ThemedChevronDown size={ICON_SIZE.xs} uniProps={mutedIconColorMapping} />
|
||||
</View>
|
||||
) : (
|
||||
<ThemedChevronDown size={ICON_SIZE.xs} uniProps={mutedIconColorMapping} />
|
||||
)}
|
||||
</PressHighlight>
|
||||
<ThemedChevronDown size={ICON_SIZE.sm} uniProps={foregroundMutedMapping} />
|
||||
</Pressable>
|
||||
</View>
|
||||
<Combobox
|
||||
options={EMPTY_COMBOBOX_OPTIONS}
|
||||
@@ -262,8 +251,6 @@ export function AgentProfileIconButton({
|
||||
iconKey={null}
|
||||
selected={selectedIcon === null}
|
||||
color={selectedColor}
|
||||
provider={provider}
|
||||
serverId={serverId}
|
||||
onSelect={handleIconSelect}
|
||||
/>
|
||||
{AGENT_PROFILE_ICON_KEYS.map((key) => (
|
||||
@@ -278,7 +265,7 @@ export function AgentProfileIconButton({
|
||||
</View>
|
||||
</View>
|
||||
</Combobox>
|
||||
</>
|
||||
</Field>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -292,8 +279,6 @@ function identitySwatch(color: Exclude<AgentProfileColor, "none">) {
|
||||
return styles[IDENTITY_SWATCH_STYLE_KEYS[color]];
|
||||
}
|
||||
|
||||
const HERO_BUTTON_SIZE = bySizing({ touch: TOUCH_TARGET, pointer: 40 });
|
||||
|
||||
const styles = StyleSheet.create((theme) => {
|
||||
const geometry = createControlGeometry(theme);
|
||||
|
||||
@@ -307,29 +292,6 @@ const styles = StyleSheet.create((theme) => {
|
||||
},
|
||||
triggerSm: { ...geometry.fieldControlSm },
|
||||
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
|
||||
// a chevron, so it keeps the shared height and drops the text-sized inset.
|
||||
triggerIconOnly: {
|
||||
@@ -377,7 +339,7 @@ const styles = StyleSheet.create((theme) => {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
},
|
||||
cellPressed: {
|
||||
opacity: theme.opacity[50],
|
||||
opacity: 0.7,
|
||||
},
|
||||
cellSelected: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
|
||||
@@ -1,503 +0,0 @@
|
||||
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,16 +1,36 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactElement } from "react";
|
||||
import { View } from "react-native";
|
||||
import { Text, View } from "react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
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 { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import type { AgentProfileSeed, AgentProfileValue } from "../internal/profile-form-model";
|
||||
import { type ControlSize } from "@/components/ui/control-geometry";
|
||||
import { Field, FormTextInput } from "@/components/ui/form-field";
|
||||
import {
|
||||
useAgentProfileFormSession,
|
||||
type AgentProfileFormSession,
|
||||
SelectField,
|
||||
type SelectFieldDisplay,
|
||||
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";
|
||||
import { AgentProfileFormFields } from "./agent-profile-form-fields";
|
||||
|
||||
export interface AgentProfileEditModalProps {
|
||||
serverId: string;
|
||||
@@ -18,15 +38,16 @@ export interface AgentProfileEditModalProps {
|
||||
mode: "create" | "edit";
|
||||
profile?: AgentProfile;
|
||||
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;
|
||||
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 {
|
||||
if (props.mode === "edit") {
|
||||
return `edit:${props.profile?.id ?? ""}`;
|
||||
@@ -36,11 +57,7 @@ function openKey(props: AgentProfileEditModalProps): string {
|
||||
|
||||
/**
|
||||
* Create and edit never share a mounted instance: the body is keyed on mode plus
|
||||
* 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.
|
||||
* profile id, so every open constructs a form model seeded from that record.
|
||||
*/
|
||||
export function AgentProfileEditModal(props: AgentProfileEditModalProps): ReactElement | null {
|
||||
const [renderedProps, setRenderedProps] = useState<AgentProfileEditModalProps | null>(() =>
|
||||
@@ -84,24 +101,10 @@ export function AgentProfileEditModal(props: AgentProfileEditModalProps): ReactE
|
||||
return null;
|
||||
}
|
||||
|
||||
const activeProps = props.visible ? props : renderedProps;
|
||||
|
||||
if (activeProps.session) {
|
||||
return (
|
||||
<AgentProfileEditModalContent
|
||||
{...activeProps}
|
||||
session={activeProps.session}
|
||||
visible={sheetVisible}
|
||||
onClose={requestClose}
|
||||
onDismiss={handleDismiss}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<StandaloneAgentProfileEditModal
|
||||
key={openKey(activeProps)}
|
||||
{...activeProps}
|
||||
<OpenAgentProfileEditModal
|
||||
key={openKey(renderedProps)}
|
||||
{...renderedProps}
|
||||
visible={sheetVisible}
|
||||
onClose={requestClose}
|
||||
onDismiss={handleDismiss}
|
||||
@@ -109,36 +112,36 @@ export function AgentProfileEditModal(props: AgentProfileEditModalProps): ReactE
|
||||
);
|
||||
}
|
||||
|
||||
function StandaloneAgentProfileEditModal(
|
||||
props: AgentProfileEditModalProps & { onDismiss: () => void },
|
||||
): ReactElement {
|
||||
const session = useAgentProfileFormSession({
|
||||
serverId: props.serverId,
|
||||
mode: props.mode,
|
||||
profile: props.profile,
|
||||
seed: props.seed,
|
||||
onSave: props.onSave,
|
||||
onSaved: props.onClose,
|
||||
});
|
||||
return <AgentProfileEditModalContent {...props} session={session} />;
|
||||
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 AgentProfileEditModalContent({
|
||||
function OpenAgentProfileEditModal({
|
||||
serverId,
|
||||
visible,
|
||||
mode,
|
||||
profile,
|
||||
session,
|
||||
collapsibleDefaults,
|
||||
seed,
|
||||
onClose,
|
||||
onDismiss,
|
||||
onRemove,
|
||||
}: AgentProfileEditModalProps & {
|
||||
session: AgentProfileFormSession;
|
||||
onDismiss: () => void;
|
||||
}): ReactElement {
|
||||
onSave,
|
||||
}: AgentProfileEditModalProps & { onDismiss: () => void }): ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const { model, state, save } = session;
|
||||
const controlSize: ControlSize = "md";
|
||||
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>(
|
||||
() => ({
|
||||
@@ -150,9 +153,59 @@ function AgentProfileEditModalContent({
|
||||
[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(() => {
|
||||
void save();
|
||||
}, [save]);
|
||||
void handleSave();
|
||||
}, [handleSave]);
|
||||
|
||||
const handleCancel = useCallback(() => {
|
||||
if (state.isSubmitting) {
|
||||
@@ -161,31 +214,170 @@ function AgentProfileEditModalContent({
|
||||
onClose();
|
||||
}, [onClose, state.isSubmitting]);
|
||||
|
||||
const handleRemove = useCallback(() => {
|
||||
if (!profile || !onRemove) {
|
||||
return;
|
||||
}
|
||||
onRemove(profile.id);
|
||||
}, [onRemove, profile]);
|
||||
|
||||
const footer = useMemo(
|
||||
() => (
|
||||
<View style={styles.footer}>
|
||||
<View style={styles.footerStart}>
|
||||
{mode === "edit" && profile && onRemove ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
onPress={handleRemove}
|
||||
return (
|
||||
<AdaptiveModalSheet
|
||||
visible={visible}
|
||||
header={sheetHeader}
|
||||
onClose={handleCancel}
|
||||
onDismiss={onDismiss}
|
||||
desktopMaxWidth={520}
|
||||
testID="agent-profile-edit-modal"
|
||||
>
|
||||
<View style={styles.body}>
|
||||
<View style={styles.nameRow}>
|
||||
<View style={styles.iconField}>
|
||||
<AgentProfileAppearanceField
|
||||
label={t("settings.host.agentProfiles.iconLabel")}
|
||||
icon={state.icon}
|
||||
color={state.color}
|
||||
onChange={handleAppearanceChange}
|
||||
disabled={state.isSubmitting}
|
||||
testID="agent-profile-modal-remove-button"
|
||||
size={controlSize}
|
||||
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"
|
||||
>
|
||||
{t("settings.host.agentProfiles.remove")}
|
||||
</Button>
|
||||
) : null}
|
||||
<FormTextInput
|
||||
initialValue={seed?.name ?? profile?.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"
|
||||
/>
|
||||
</Field>
|
||||
</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
|
||||
variant="secondary"
|
||||
style={styles.actionButton}
|
||||
onPress={handleCancel}
|
||||
disabled={state.isSubmitting}
|
||||
testID="agent-profile-cancel-button"
|
||||
@@ -194,65 +386,177 @@ function AgentProfileEditModalContent({
|
||||
</Button>
|
||||
<Button
|
||||
variant="default"
|
||||
style={styles.actionButton}
|
||||
onPress={handleSavePress}
|
||||
disabled={!state.canSubmit}
|
||||
loading={state.isSubmitting}
|
||||
testID="agent-profile-save-button"
|
||||
>
|
||||
{t("settings.host.agentProfiles.save")}
|
||||
{state.isSubmitting
|
||||
? t("settings.host.agentProfiles.saving")
|
||||
: t("settings.host.agentProfiles.save")}
|
||||
</Button>
|
||||
</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>
|
||||
);
|
||||
}
|
||||
|
||||
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) => ({
|
||||
footer: {
|
||||
body: {
|
||||
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,
|
||||
},
|
||||
featureCard: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
borderRadius: theme.borderRadius.md,
|
||||
borderWidth: 1,
|
||||
borderColor: theme.colors.border,
|
||||
paddingHorizontal: theme.spacing[3],
|
||||
},
|
||||
featureRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
gap: theme.spacing[2],
|
||||
gap: theme.spacing[3],
|
||||
paddingVertical: theme.spacing[3],
|
||||
},
|
||||
footerStart: {
|
||||
featureRowBorder: {
|
||||
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",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
marginTop: theme.spacing[2],
|
||||
},
|
||||
footerEnd: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
actionButton: {
|
||||
flex: 1,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -1,567 +0,0 @@
|
||||
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,342 +1,57 @@
|
||||
import { useCallback, useMemo, useState, type ReactElement } from "react";
|
||||
import { useCallback, useMemo, type ReactElement } from "react";
|
||||
import { Text, View } from "react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
ArrowDown,
|
||||
ArrowUp,
|
||||
ArrowUpToLine,
|
||||
ChevronRight,
|
||||
Copy,
|
||||
GripVertical,
|
||||
MoreVertical,
|
||||
Pencil,
|
||||
Trash2,
|
||||
} from "lucide-react-native";
|
||||
import { ArrowDown, ArrowUp, FileText, Pencil, Trash2 } from "lucide-react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentProfile } from "@getpaseo/protocol/messages";
|
||||
import { DraggableListHandle } from "@/components/draggable-list";
|
||||
import { useOpenKebabMenuVisibility } from "@/components/sidebar/use-open-kebab-menu-visibility";
|
||||
import { bySizing, 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 { Button } from "@/components/ui/button";
|
||||
import { settingsStyles } from "@/styles/settings";
|
||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||
import { AgentProfileGlyph } from "../internal/agent-profile-glyph";
|
||||
import { buildAgentProfileRosterSummary } from "../internal/profile-summary";
|
||||
import { buildAgentProfileTags } 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_GRIP_WIDTH = bySizing({ touch: 28, pointer: 20 });
|
||||
export const ROSTER_TRAILING_WIDTH = bySizing({ touch: TOUCH_TARGET + 14, pointer: 42 });
|
||||
|
||||
const ROW_MIN_HEIGHT = bySizing({ touch: TOUCH_TARGET + 16, pointer: 56 });
|
||||
const GRIP_HANDLE_HEIGHT = bySizing({ touch: TOUCH_TARGET, pointer: 28 });
|
||||
|
||||
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 ThemedArrowDown = withUnistyles(ArrowDown);
|
||||
const ThemedArrowUpToLine = withUnistyles(ArrowUpToLine);
|
||||
const ThemedPencil = withUnistyles(Pencil);
|
||||
const ThemedTrash2 = withUnistyles(Trash2);
|
||||
const ThemedFileText = withUnistyles(FileText);
|
||||
|
||||
const destructiveIconColorMapping = (theme: Theme) => ({ color: theme.colors.destructive });
|
||||
const mutedColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
|
||||
const destructiveColorMapping = (theme: Theme) => ({ color: theme.colors.destructive });
|
||||
|
||||
const editMenuIcon = <ThemedPencil size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />;
|
||||
const duplicateMenuIcon = <ThemedCopy size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />;
|
||||
const moveUpMenuIcon = <ThemedArrowUp size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />;
|
||||
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;
|
||||
const moveUpIcon = <ThemedArrowUp size={ICON_SIZE.sm} uniProps={mutedColorMapping} />;
|
||||
const moveDownIcon = <ThemedArrowDown size={ICON_SIZE.sm} uniProps={mutedColorMapping} />;
|
||||
const editIcon = <ThemedPencil size={ICON_SIZE.sm} uniProps={mutedColorMapping} />;
|
||||
const removeIcon = <ThemedTrash2 size={ICON_SIZE.sm} uniProps={destructiveColorMapping} />;
|
||||
|
||||
export interface AgentProfileRowProps {
|
||||
serverId: string;
|
||||
profile: AgentProfile;
|
||||
entries: readonly ProviderSnapshotEntry[] | undefined;
|
||||
isFirst: 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;
|
||||
onDuplicate: (id: string) => void;
|
||||
onRemove: (id: string) => void;
|
||||
onMoveUp: (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={ICON_SIZE.sm} 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>
|
||||
<View style={styles.stackedSpecLine}>
|
||||
<AgentProfileGlyph
|
||||
provider={profile.provider}
|
||||
serverId={serverId}
|
||||
size={ICON_SIZE.xs}
|
||||
/>
|
||||
<Text style={styles.stackedSpecText} numberOfLines={1}>
|
||||
{fullSummary}
|
||||
</Text>
|
||||
</View>
|
||||
{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({
|
||||
serverId,
|
||||
profile,
|
||||
entries,
|
||||
isFirst,
|
||||
isLast,
|
||||
selected = false,
|
||||
dragging = false,
|
||||
compactLayout = false,
|
||||
reorderable = true,
|
||||
onEdit,
|
||||
onDuplicate,
|
||||
onRemove,
|
||||
onMoveUp,
|
||||
onMoveDown,
|
||||
onMoveToTop,
|
||||
}: AgentProfileRowProps): ReactElement {
|
||||
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 handleDuplicate = useCallback(() => onDuplicate(profile.id), [onDuplicate, profile.id]);
|
||||
const handleRemove = useCallback(() => onRemove(profile.id), [onRemove, profile.id]);
|
||||
const handleMoveUp = useCallback(() => onMoveUp(profile.id), [onMoveUp, profile.id]);
|
||||
const handleMoveDown = useCallback(() => onMoveDown(profile.id), [onMoveDown, profile.id]);
|
||||
const handleMoveToTop = useCallback(() => onMoveToTop(profile.id), [onMoveToTop, profile.id]);
|
||||
|
||||
const formatFeatureCount = useCallback(
|
||||
(count: number) =>
|
||||
@@ -345,276 +60,125 @@ export function AgentProfileRow({
|
||||
: t("settings.host.agentProfiles.featureCount", { count }),
|
||||
[t],
|
||||
);
|
||||
|
||||
const rosterSummary = useMemo(
|
||||
() => buildAgentProfileRosterSummary({ profile, entries, formatFeatureCount }),
|
||||
const tags = useMemo(
|
||||
() => buildAgentProfileTags({ profile, entries, formatFeatureCount }),
|
||||
[entries, formatFeatureCount, profile],
|
||||
);
|
||||
const fullSummary = useMemo(
|
||||
() => rosterSummary.allTags.map((tag) => tag.label).join(" · "),
|
||||
[rosterSummary.allTags],
|
||||
);
|
||||
const runtimeSubline = useMemo(
|
||||
() => rosterSummary.runtimeDetails.join(" · "),
|
||||
[rosterSummary.runtimeDetails],
|
||||
);
|
||||
const summary = useMemo(() => tags.map((tag) => tag.label).join(" · "), [tags]);
|
||||
|
||||
const isStacked = compactLayout || isCompactFormFactor;
|
||||
|
||||
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 gripVisibilityStyle = useMemo(
|
||||
() => [styles.gripSlot, !showRowAffordances && styles.affordanceHidden],
|
||||
[showRowAffordances],
|
||||
);
|
||||
const kebabVisibilityStyle = useMemo(
|
||||
() => [styles.kebabSlot, !showRowAffordances && styles.affordanceHidden],
|
||||
[showRowAffordances],
|
||||
const rowStyle = useMemo(
|
||||
() => [settingsStyles.row, isFirst ? null : settingsStyles.rowBorder, styles.row],
|
||||
[isFirst],
|
||||
);
|
||||
|
||||
return (
|
||||
<View
|
||||
style={rowContainerStyle}
|
||||
onPointerEnter={handlePointerEnter}
|
||||
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}
|
||||
|
||||
{reorderable ? (
|
||||
<View style={gripVisibilityStyle} pointerEvents={showRowAffordances ? "auto" : "none"}>
|
||||
<DraggableListHandle
|
||||
accessibilityLabel={t("settings.host.agentProfiles.reorderProfile", {
|
||||
name: profile.name,
|
||||
})}
|
||||
style={styles.gripHandle}
|
||||
testID={`agent-profile-drag-${profile.id}`}
|
||||
>
|
||||
<ThemedGripVertical size={ICON_SIZE.sm} uniProps={extraMutedIconColorMapping} />
|
||||
</DraggableListHandle>
|
||||
<View style={rowStyle} testID={`agent-profile-row-${profile.id}`}>
|
||||
<View style={styles.rowMain}>
|
||||
<View style={styles.iconWrapper}>
|
||||
<AgentProfileGlyph icon={profile.icon} color={profile.color} size={ICON_SIZE.md} />
|
||||
</View>
|
||||
) : (
|
||||
<View style={isStacked ? styles.gripSpacerCompact : styles.gripSlot} />
|
||||
)}
|
||||
|
||||
<AgentProfileRowContent
|
||||
serverId={serverId}
|
||||
profile={profile}
|
||||
modelLabel={rosterSummary.modelLabel}
|
||||
providerLabel={rosterSummary.providerLabel}
|
||||
runtimeSubline={runtimeSubline}
|
||||
fullSummary={fullSummary}
|
||||
isStacked={isStacked}
|
||||
/>
|
||||
|
||||
<View style={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 style={[styles.chevron, styles.passThrough]} {...HIDDEN_FROM_ASSISTIVE_TECH}>
|
||||
<ThemedChevronRight
|
||||
size={ICON_SIZE.sm}
|
||||
uniProps={isHovered || selected ? foregroundIconColorMapping : mutedIconColorMapping}
|
||||
/>
|
||||
<View style={settingsStyles.rowContent}>
|
||||
<View style={styles.titleLine}>
|
||||
<Text style={settingsStyles.rowTitle} numberOfLines={1}>
|
||||
{profile.name}
|
||||
</Text>
|
||||
<Text style={styles.summary} numberOfLines={1}>
|
||||
{summary}
|
||||
</Text>
|
||||
</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>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
row: {
|
||||
position: "relative",
|
||||
flexDirection: "row",
|
||||
gap: theme.spacing[2],
|
||||
minHeight: 56,
|
||||
alignItems: "center",
|
||||
minHeight: ROW_MIN_HEIGHT,
|
||||
paddingVertical: theme.spacing[3],
|
||||
paddingLeft: theme.spacing[2],
|
||||
paddingRight: theme.spacing[4],
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
rowHovered: {
|
||||
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",
|
||||
},
|
||||
gripSlot: {
|
||||
width: ROSTER_GRIP_WIDTH,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
flexShrink: 0,
|
||||
},
|
||||
gripSpacerCompact: {
|
||||
width: theme.spacing[2],
|
||||
flexShrink: 0,
|
||||
},
|
||||
gripHandle: {
|
||||
width: ROSTER_GRIP_WIDTH,
|
||||
height: GRIP_HANDLE_HEIGHT,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
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: {
|
||||
rowMain: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[4],
|
||||
},
|
||||
colProfile: {
|
||||
width: ROSTER_COL_PROFILE_WIDTH,
|
||||
flexShrink: 0,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
minWidth: 0,
|
||||
},
|
||||
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],
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
stackedContent: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
gap: theme.spacing[0.5],
|
||||
},
|
||||
stackedSpecLine: {
|
||||
flexDirection: "row",
|
||||
iconWrapper: {
|
||||
width: theme.iconSize.md,
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[1.5],
|
||||
justifyContent: "center",
|
||||
marginTop: 1,
|
||||
},
|
||||
titleLine: {
|
||||
flexDirection: "row",
|
||||
alignItems: "baseline",
|
||||
gap: theme.spacing[2],
|
||||
minWidth: 0,
|
||||
},
|
||||
stackedSpecText: {
|
||||
summary: {
|
||||
flexShrink: 1,
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
},
|
||||
stackedNotesText: {
|
||||
color: theme.colors.foregroundExtraMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
marginTop: theme.spacing[0.5],
|
||||
notes: {
|
||||
flexDirection: "row",
|
||||
alignItems: "flex-start",
|
||||
gap: theme.spacing[1],
|
||||
marginTop: theme.spacing[1],
|
||||
},
|
||||
trailing: {
|
||||
width: ROSTER_TRAILING_WIDTH,
|
||||
notesText: {
|
||||
flex: 1,
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
},
|
||||
rowActions: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "flex-end",
|
||||
gap: theme.spacing[1],
|
||||
flexShrink: 0,
|
||||
},
|
||||
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
@@ -56,7 +56,6 @@ export function ChatFind({
|
||||
agentId,
|
||||
serverId,
|
||||
epoch,
|
||||
rewindSeq,
|
||||
items,
|
||||
viewportRef,
|
||||
revealLoadedMessage,
|
||||
@@ -96,8 +95,8 @@ export function ChatFind({
|
||||
);
|
||||
const state = useSyncExternalStore(model.subscribe, model.getSnapshot, model.getSnapshot);
|
||||
useEffect(() => {
|
||||
model.updateHistory(epoch, items, rewindSeq);
|
||||
}, [model, epoch, items, rewindSeq]);
|
||||
model.updateHistory(epoch, items);
|
||||
}, [model, epoch, items]);
|
||||
useEffect(() => () => model.close(), [model]);
|
||||
useEffect(() => {
|
||||
if (!active) model.close();
|
||||
|
||||
@@ -18,7 +18,7 @@ function message(seq: number, text = "target"): StreamItem {
|
||||
kind: "assistant_message",
|
||||
text,
|
||||
timestamp: new Date(0),
|
||||
timelineCursor: { epoch: "epoch", seq, anchorSeq: seq },
|
||||
timelineCursor: { epoch: "epoch", seq },
|
||||
};
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ it("loads an older location and searches a response merged across suppressed tas
|
||||
source.map((item, index) => ({
|
||||
event: { type: "timeline" as const, provider: "claude" as const, item },
|
||||
timestamp: new Date(0),
|
||||
timelineCursor: { epoch: "epoch", seq: index + 1, anchorSeq: index + 1 },
|
||||
timelineCursor: { epoch: "epoch", seq: index + 1 },
|
||||
})),
|
||||
{ source: "canonical" },
|
||||
);
|
||||
@@ -55,7 +55,7 @@ it("loads an older location and searches a response merged across suppressed tas
|
||||
},
|
||||
async load(_epoch, seq) {
|
||||
loaded.push(seq);
|
||||
model.updateHistory("epoch", history, null);
|
||||
model.updateHistory("epoch", history);
|
||||
},
|
||||
async reveal(_id, _query, occurrence) {
|
||||
revealed.push(occurrence);
|
||||
@@ -64,7 +64,7 @@ it("loads an older location and searches a response merged across suppressed tas
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [], null);
|
||||
model.updateHistory("epoch", []);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
@@ -99,7 +99,7 @@ it("skips a source-only candidate and highlights a displayed match", async () =>
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.updateHistory("epoch", [message(1), message(2)]);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().selectedItemId).toBe("row-2");
|
||||
@@ -129,7 +129,7 @@ it("ignores replies after closing and does not navigate", async () => {
|
||||
},
|
||||
clear() {},
|
||||
});
|
||||
model.updateHistory("epoch", [message(1)], null);
|
||||
model.updateHistory("epoch", [message(1)]);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => calls).toEqual(["search"]);
|
||||
@@ -155,7 +155,7 @@ it("retains a failed search for retry and distinguishes failure from zero matche
|
||||
};
|
||||
const model = new ChatFindModel(operations);
|
||||
try {
|
||||
model.updateHistory("epoch", [], null);
|
||||
model.updateHistory("epoch", []);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("error");
|
||||
@@ -185,7 +185,7 @@ it("reports a failed timeline load as a connection failure", async () => {
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [], null);
|
||||
model.updateHistory("epoch", []);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("error");
|
||||
@@ -207,160 +207,24 @@ it("reports a search result that outlived its epoch as a changed history", async
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1)], null);
|
||||
model.updateHistory("epoch", [message(1)]);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
model.updateHistory("epoch-2", [message(1)], null);
|
||||
model.updateHistory("epoch-2", [message(1)]);
|
||||
expect(model.getSnapshot()).toMatchObject({ phase: "error", failure: "historyChanged" });
|
||||
} finally {
|
||||
model.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("reports results that a rewind took messages from as a changed history", async () => {
|
||||
const model = new ChatFindModel({
|
||||
async search() {
|
||||
return response([{ seq: 2, role: "assistant" }]);
|
||||
},
|
||||
async load() {},
|
||||
async reveal() {
|
||||
return { count: 1, occurrence: 0 };
|
||||
},
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
expect(model.getSnapshot()).toMatchObject({ selectedItemId: "row-2", count: 1 });
|
||||
// Another client rewinds the turn holding the match; the epoch stays.
|
||||
model.updateHistory("epoch", [message(1)], 3);
|
||||
expect(model.getSnapshot()).toMatchObject({
|
||||
phase: "error",
|
||||
failure: "historyChanged",
|
||||
selectedItemId: null,
|
||||
});
|
||||
} finally {
|
||||
model.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("stops a search still receiving pages when a rewind lands between them", async () => {
|
||||
let pages = 0;
|
||||
let releaseSecondPage!: () => void;
|
||||
const secondPage = new Promise<void>((resolve) => {
|
||||
releaseSecondPage = resolve;
|
||||
});
|
||||
const model = new ChatFindModel({
|
||||
async search(_query, cursor) {
|
||||
pages += 1;
|
||||
if (cursor === undefined)
|
||||
return { ...response([{ seq: 2, role: "assistant" }]), nextCursor: 2 };
|
||||
await secondPage;
|
||||
return response([{ seq: 1, role: "assistant" }]);
|
||||
},
|
||||
async load() {},
|
||||
async reveal() {
|
||||
return { count: 1, occurrence: 0 };
|
||||
},
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => pages).toBe(2);
|
||||
model.updateHistory("epoch", [message(1)], 3);
|
||||
releaseSecondPage();
|
||||
await expect.poll(() => model.getSnapshot().failure).toBe("historyChanged");
|
||||
expect(model.getSnapshot()).toMatchObject({ phase: "error", selectedItemId: null });
|
||||
} finally {
|
||||
model.close();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
["Next", "next"],
|
||||
["Previous", "previous"],
|
||||
] as const)("reports a rewind after %s as a changed history", async (_label, step) => {
|
||||
const model = new ChatFindModel({
|
||||
async search() {
|
||||
return response([
|
||||
{ seq: 1, role: "assistant" },
|
||||
{ seq: 2, role: "assistant" },
|
||||
]);
|
||||
},
|
||||
async load() {},
|
||||
async reveal() {
|
||||
return { count: 1, occurrence: 0 };
|
||||
},
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
model[step]();
|
||||
await expect.poll(() => model.getSnapshot().selectedItemId).toBe("row-2");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
model.updateHistory("epoch", [message(1)], 3);
|
||||
expect(model.getSnapshot()).toMatchObject({
|
||||
phase: "error",
|
||||
failure: "historyChanged",
|
||||
selectedItemId: null,
|
||||
});
|
||||
} finally {
|
||||
model.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("stops a pending Next when a rewind lands before it reveals", async () => {
|
||||
let reveals = 0;
|
||||
let revealSecond!: () => void;
|
||||
const secondReveal = new Promise<void>((resolve) => {
|
||||
revealSecond = resolve;
|
||||
});
|
||||
const model = new ChatFindModel({
|
||||
async search() {
|
||||
return response([
|
||||
{ seq: 1, role: "assistant" },
|
||||
{ seq: 2, role: "assistant" },
|
||||
]);
|
||||
},
|
||||
async load() {},
|
||||
async reveal() {
|
||||
reveals += 1;
|
||||
if (reveals > 1) await secondReveal;
|
||||
return { count: 1, occurrence: 0 };
|
||||
},
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
model.next();
|
||||
await expect.poll(() => reveals).toBe(2);
|
||||
model.updateHistory("epoch", [message(1)], 3);
|
||||
revealSecond();
|
||||
await expect.poll(() => model.getSnapshot().failure).toBe("historyChanged");
|
||||
expect(model.getSnapshot()).toMatchObject({ phase: "error", selectedItemId: null });
|
||||
} finally {
|
||||
model.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("can load a search location before the initial chat history has arrived", async () => {
|
||||
const model = new ChatFindModel({
|
||||
async search() {
|
||||
return response([{ seq: 1, role: "assistant" }]);
|
||||
},
|
||||
async load() {
|
||||
model.updateHistory("epoch", [message(1)], null);
|
||||
model.updateHistory("epoch", [message(1)]);
|
||||
},
|
||||
async reveal() {
|
||||
return { count: 1, occurrence: 0 };
|
||||
@@ -368,7 +232,7 @@ it("can load a search location before the initial chat history has arrived", asy
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory(null, [], null);
|
||||
model.updateHistory(null, []);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
@@ -396,7 +260,7 @@ it("reports the position across the whole chat and corrects it with rendered cou
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.updateHistory("epoch", [message(1), message(2)]);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
@@ -433,7 +297,7 @@ it("counts one match per message from a host that reports no counts", async () =
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.updateHistory("epoch", [message(1), message(2)]);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
|
||||
@@ -76,10 +76,6 @@ export class ChatFindModel {
|
||||
private items: StreamItem[] = [];
|
||||
private epoch: string | null = null;
|
||||
private resultEpoch: string | null = null;
|
||||
/** The latest rewind applied to the history. A rewind keeps the epoch and retires messages. */
|
||||
private rewindSeq: number | null = null;
|
||||
/** The latest rewind when the current result set's search started; undefined until a search starts. */
|
||||
private searchedRewindSeq: number | null | undefined = undefined;
|
||||
private locations: Location[] = [];
|
||||
private resolved = new Map<Location, Target>();
|
||||
private current = -1;
|
||||
@@ -117,7 +113,6 @@ export class ChatFindModel {
|
||||
this.cancel();
|
||||
this.locations = [];
|
||||
this.resultEpoch = null;
|
||||
this.searchedRewindSeq = undefined;
|
||||
this.resolved.clear();
|
||||
this.current = -1;
|
||||
this.inMessage = { occurrence: 0, count: 0 };
|
||||
@@ -149,7 +144,6 @@ export class ChatFindModel {
|
||||
});
|
||||
}
|
||||
private async search(signal: AbortSignal) {
|
||||
this.searchedRewindSeq = this.rewindSeq;
|
||||
try {
|
||||
let cursor: number | undefined;
|
||||
do {
|
||||
@@ -174,14 +168,15 @@ export class ChatFindModel {
|
||||
this.fail(error, signal);
|
||||
}
|
||||
}
|
||||
/** `rewindSeq` is the sequence number of the latest rewind applied to this history. */
|
||||
updateHistory(epoch: string | null, items: StreamItem[], rewindSeq: number | null) {
|
||||
const replaced = this.resultEpoch !== null && epoch !== null && epoch !== this.resultEpoch;
|
||||
const rewound = this.searchedRewindSeq !== undefined && rewindSeq !== this.searchedRewindSeq;
|
||||
if ((replaced || rewound) && this.state.open) {
|
||||
updateHistory(epoch: string | null, items: StreamItem[]) {
|
||||
if (
|
||||
this.resultEpoch !== null &&
|
||||
epoch !== null &&
|
||||
epoch !== this.resultEpoch &&
|
||||
this.state.open
|
||||
) {
|
||||
this.fail(new ChatFindFailureError("historyChanged"), this.abort.signal);
|
||||
}
|
||||
this.rewindSeq = rewindSeq;
|
||||
this.epoch = epoch;
|
||||
this.items = items;
|
||||
this.historyListeners.forEach((listener) => listener());
|
||||
|
||||
@@ -9,8 +9,6 @@ export interface ChatFindProps {
|
||||
agentId: string;
|
||||
serverId: string;
|
||||
epoch: string | null;
|
||||
/** The sequence number of the latest rewind applied to this history, if any. */
|
||||
rewindSeq: number | null;
|
||||
items: StreamItem[];
|
||||
viewportRef: RefObject<StreamViewportHandle | null>;
|
||||
revealLoadedMessage(messageId: string): boolean;
|
||||
|
||||
@@ -139,7 +139,7 @@ describe("useChatOutline", () => {
|
||||
kind: "user_message",
|
||||
text: "live prompt",
|
||||
timestamp: new Date(seq),
|
||||
timelineCursor: { epoch: "epoch-1", seq, anchorSeq: seq },
|
||||
timelineCursor: { epoch: "epoch-1", seq },
|
||||
});
|
||||
rerender({ tail: [loadedPrompt(2)] });
|
||||
await waitFor(() => expect(runtime.listAgentTimelinePrompts).toHaveBeenCalledTimes(2));
|
||||
@@ -198,7 +198,7 @@ describe("useChatOutline", () => {
|
||||
kind: "assistant_message",
|
||||
text: "chunk",
|
||||
timestamp: new Date(),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
||||
},
|
||||
],
|
||||
timelineEpoch: "epoch-1",
|
||||
@@ -219,7 +219,7 @@ describe("useChatOutline", () => {
|
||||
kind: "user_message",
|
||||
text: "Replaced conversation",
|
||||
timestamp: new Date(2),
|
||||
timelineCursor: { epoch: "epoch-2", seq: 1, anchorSeq: 1 },
|
||||
timelineCursor: { epoch: "epoch-2", seq: 1 },
|
||||
},
|
||||
],
|
||||
timelineEpoch: "epoch-2",
|
||||
@@ -275,7 +275,7 @@ describe("useChatOutline", () => {
|
||||
kind: "user_message" as const,
|
||||
text: "prompt",
|
||||
timestamp: new Date(1),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1 },
|
||||
},
|
||||
];
|
||||
const { result, rerender } = renderHook(
|
||||
@@ -326,7 +326,7 @@ describe("useChatOutline", () => {
|
||||
kind: "user_message" as const,
|
||||
text: "prompt",
|
||||
timestamp: new Date(1),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1 },
|
||||
};
|
||||
const { result, rerender } = renderHook(
|
||||
({ tail, mountedHistoryMessageIds }) =>
|
||||
@@ -381,7 +381,7 @@ describe("useChatOutline", () => {
|
||||
kind: "user_message" as const,
|
||||
text: "prompt",
|
||||
timestamp: new Date(2),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
||||
};
|
||||
const revealLoadedMessage = vi.fn();
|
||||
revealLoadedMessage.mockReturnValue(false);
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { TurnTiming } from "@/timeline/turn-time";
|
||||
import type { TimelineItemTransform } from "@/plugins/timeline";
|
||||
import { projectPluginTimelineItems } from "@/plugins/timeline/projection";
|
||||
import type { StreamItem } from "@/types/stream";
|
||||
import {
|
||||
orderHeadForStreamRenderStrategy,
|
||||
@@ -580,40 +578,4 @@ describe("layoutStream", () => {
|
||||
expect(footerOwners(layout)).toEqual([]);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["web", "android"] as const)(
|
||||
"attaches the turn footer to the final card of a plugin-split reply on %s",
|
||||
(platform) => {
|
||||
const metrics = [{ label: "Model", value: "opus" }];
|
||||
const first = { ...assistantMessage("a1", 2), turnMetrics: [{ label: "Steps", value: "1" }] };
|
||||
const latest = { ...assistantMessage("a2", 4), turnMetrics: metrics };
|
||||
const splitIntoCards: TimelineItemTransform = ({ item, sourceId }) =>
|
||||
item.type !== "assistant_message"
|
||||
? undefined
|
||||
: ["text", "card"].map((part) => ({
|
||||
type: "plugin",
|
||||
id: `${sourceId}/${part}`,
|
||||
pluginId: "genui",
|
||||
kind: `genui-${part}`,
|
||||
version: 1,
|
||||
data: {},
|
||||
}));
|
||||
const tail = projectPluginTimelineItems(
|
||||
[userMessage("u1", 1), first, userMessage("u2", 3), latest],
|
||||
splitIntoCards,
|
||||
);
|
||||
|
||||
const layout = layoutFor({
|
||||
platform,
|
||||
tail,
|
||||
timingIds: ["genui/a1/card", "genui/a2/card"],
|
||||
});
|
||||
|
||||
expect(footerOwners(layout)).toEqual(["genui/a1/card", "genui/a2/card"]);
|
||||
expect(findLayoutItem(layout, "genui/a1/card").completedFooter?.turnMetrics).toBe(
|
||||
first.turnMetrics,
|
||||
);
|
||||
expect(layout.auxiliaryTurnFooter?.turnMetrics).toBe(metrics);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { AgentMetric } from "@getpaseo/protocol/agent-types";
|
||||
import type { TurnTiming } from "@/timeline/turn-time";
|
||||
import { getAssistantReply, type StreamItem } from "@/types/stream";
|
||||
import type { StreamItem } from "@/types/stream";
|
||||
import { getAssistantMessageSpacing, getGapBetweenStreamItems } from "./spacing";
|
||||
import type { StreamFrameChildOrder, StreamStrategy } from "./strategy";
|
||||
import { continuesResponse, continuesTurn, isResponseBoundary } from "./turn-membership";
|
||||
@@ -72,9 +72,9 @@ function createTurnFooterHost(input: {
|
||||
timingByItemId: Map<string, TurnTiming>;
|
||||
}): TurnFooterHost {
|
||||
const turnMetrics =
|
||||
input.item.kind === "tool_call"
|
||||
input.item.kind === "assistant_message" || input.item.kind === "tool_call"
|
||||
? input.item.turnMetrics
|
||||
: getAssistantReply(input.item)?.turnMetrics;
|
||||
: undefined;
|
||||
return {
|
||||
itemId: input.item.id,
|
||||
items: input.items,
|
||||
@@ -109,7 +109,7 @@ function findTurnFooterSource(input: {
|
||||
if (!item || (laterItem && !continuesResponse(item, laterItem))) {
|
||||
return toolFallback;
|
||||
}
|
||||
if (getAssistantReply(item)) {
|
||||
if (item.kind === "assistant_message") {
|
||||
return { item, items, index };
|
||||
}
|
||||
laterItem = item;
|
||||
|
||||
@@ -320,7 +320,7 @@ describe("stream presentation through installed plugins", () => {
|
||||
const source = harness.source();
|
||||
const live = source.head[0];
|
||||
if (live?.kind !== "assistant_message") throw new Error("Expected a live assistant message");
|
||||
const canonical = { ...live, timelineCursor: { epoch: "epoch-1", seq: 42, anchorSeq: 42 } };
|
||||
const canonical = { ...live, timelineCursor: { epoch: "epoch-1", seq: 42 } };
|
||||
const present = createStreamPresentation();
|
||||
present({ ...presentationOptions, tail: [], head: [live], transform: undefined });
|
||||
const repointed = rows(
|
||||
@@ -330,7 +330,7 @@ describe("stream presentation through installed plugins", () => {
|
||||
{
|
||||
id: streamed[0]!.id,
|
||||
text: "Streamed answer",
|
||||
timelineCursor: { epoch: "epoch-1", seq: 42, anchorSeq: 42 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 42 },
|
||||
},
|
||||
]);
|
||||
});
|
||||
@@ -517,7 +517,7 @@ describe("timeline presentation", () => {
|
||||
messageId: "provider-message",
|
||||
clientMessageId: "client-message",
|
||||
turnId: "turn-1",
|
||||
timelineCursor: { epoch: "epoch", seq: 12, anchorSeq: 12 },
|
||||
timelineCursor: { epoch: "epoch", seq: 12 },
|
||||
});
|
||||
const presentMessage = () =>
|
||||
present({
|
||||
|
||||
@@ -28,11 +28,7 @@ function userMessage(id: string, text: string, seed: number): StreamItem {
|
||||
};
|
||||
}
|
||||
|
||||
function assistantMessage(
|
||||
id: string,
|
||||
text: string,
|
||||
seed: number,
|
||||
): Extract<StreamItem, { kind: "assistant_message" }> {
|
||||
function assistantMessage(id: string, text: string, seed: number): StreamItem {
|
||||
return {
|
||||
kind: "assistant_message",
|
||||
id,
|
||||
@@ -247,38 +243,4 @@ describe("layout strategy edges", () => {
|
||||
"content-then-footer",
|
||||
);
|
||||
});
|
||||
|
||||
it.each(PLATFORMS)("copies a reply split into plugin cards once on %s", (platform) => {
|
||||
const strategy = strategyFor(platform);
|
||||
const splitReply = assistantMessage("a2", 'Summary\n\n```ui\nCard("Hi", [])\n```', 3);
|
||||
const card = (part: string): StreamItem => ({
|
||||
kind: "plugin",
|
||||
id: `genui/a2/${part}`,
|
||||
source: splitReply,
|
||||
timestamp: splitReply.timestamp,
|
||||
pluginId: "genui",
|
||||
pluginItemId: `a2/${part}`,
|
||||
itemKind: `genui-${part}`,
|
||||
version: 1,
|
||||
data: {},
|
||||
});
|
||||
const items = orderTailForStreamRenderStrategy({
|
||||
strategy,
|
||||
streamItems: [
|
||||
userMessage("u1", "prompt", 1),
|
||||
assistantMessage("a1", "Before card", 2),
|
||||
card("text"),
|
||||
card("card"),
|
||||
],
|
||||
});
|
||||
const startIndex = items.findIndex((item) => item.id === "genui/a2/card");
|
||||
|
||||
expect(
|
||||
collectAssistantResponseContentForStreamRenderStrategy({
|
||||
strategy,
|
||||
items,
|
||||
startIndex,
|
||||
}),
|
||||
).toBe(`Before card\n\n${splitReply.text}`);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { ComponentType, ReactElement, ReactNode, RefObject } from "react";
|
||||
import type { StyleProp, ViewStyle } from "react-native";
|
||||
import { getAssistantReply, type StreamItem } from "@/types/stream";
|
||||
import type { StreamItem } from "@/types/stream";
|
||||
import type { ReadingRowReplacements } from "./reading-anchor";
|
||||
import { continuesResponse } from "./turn-membership";
|
||||
import type { StreamHistoryBoundary, StreamRenderSegments } from "./model";
|
||||
@@ -185,7 +185,6 @@ export function createStreamStrategy(config: StreamStrategyConfig): StreamStrate
|
||||
},
|
||||
collectAssistantResponseContent: (items, startIndex) => {
|
||||
const messages: string[] = [];
|
||||
const seenReplies = new Set<StreamItem>();
|
||||
let laterItem: StreamItem | null = null;
|
||||
for (
|
||||
let index = startIndex;
|
||||
@@ -196,11 +195,8 @@ export function createStreamStrategy(config: StreamStrategyConfig): StreamStrate
|
||||
if (!currentItem || (laterItem && !continuesResponse(currentItem, laterItem))) {
|
||||
break;
|
||||
}
|
||||
// A transformer can split one reply into several cards; copy the reply once.
|
||||
const reply = getAssistantReply(currentItem);
|
||||
if (reply && !seenReplies.has(reply)) {
|
||||
seenReplies.add(reply);
|
||||
messages.push(reply.text);
|
||||
if (currentItem.kind === "assistant_message") {
|
||||
messages.push(currentItem.text);
|
||||
}
|
||||
laterItem = currentItem;
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
|
||||
it("forks a failed assistant turn from its Paseo timeline cursor without a provider message id", () => {
|
||||
const failedTurn = {
|
||||
...assistantMessage("assistant-error", 2),
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42 },
|
||||
};
|
||||
|
||||
expect(
|
||||
@@ -50,7 +50,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
|
||||
it("includes the provider message id with a supported timeline cursor", () => {
|
||||
const selected = {
|
||||
...assistantMessage("assistant-1", 2, "msg-assistant-1"),
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42 },
|
||||
};
|
||||
|
||||
expect(
|
||||
@@ -68,7 +68,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
|
||||
it("falls back to the provider message id when timeline cursors are unsupported", () => {
|
||||
const selected = {
|
||||
...assistantMessage("assistant-1", 2, "msg-assistant-1"),
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42 },
|
||||
};
|
||||
|
||||
expect(
|
||||
@@ -112,63 +112,4 @@ describe("resolveAssistantTurnForkBoundary", () => {
|
||||
}),
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it("resolves a fork boundary from the reply a plugin card replaced", () => {
|
||||
const reply = {
|
||||
...assistantMessage("assistant-1", 2, "msg-assistant-1"),
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
|
||||
};
|
||||
const card: StreamItem = {
|
||||
kind: "plugin",
|
||||
id: "genui/assistant-1/1",
|
||||
source: reply,
|
||||
timelineCursor: reply.timelineCursor,
|
||||
timestamp: reply.timestamp,
|
||||
pluginId: "genui",
|
||||
pluginItemId: "assistant-1/1",
|
||||
itemKind: "genui-block",
|
||||
version: 1,
|
||||
data: {},
|
||||
};
|
||||
|
||||
expect(
|
||||
resolveAssistantTurnForkBoundary({
|
||||
items: [userMessage("user-1", 1), card],
|
||||
startIndex: 1,
|
||||
supportsTimelineCursor: true,
|
||||
}),
|
||||
).toEqual({
|
||||
boundaryCursor: { epoch: "timeline-1", seq: 42 },
|
||||
boundaryMessageId: "msg-assistant-1",
|
||||
});
|
||||
expect(
|
||||
resolveAssistantTurnForkBoundary({
|
||||
items: [userMessage("user-1", 1), card],
|
||||
startIndex: 1,
|
||||
supportsTimelineCursor: false,
|
||||
}),
|
||||
).toEqual({ boundaryMessageId: "msg-assistant-1" });
|
||||
});
|
||||
|
||||
it("ignores plugin cards that did not replace a reply", () => {
|
||||
const appended: StreamItem = {
|
||||
kind: "plugin",
|
||||
id: "plugin/card-1",
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
|
||||
timestamp: timestamp(2),
|
||||
pluginId: "plugin",
|
||||
pluginItemId: "card-1",
|
||||
itemKind: "card",
|
||||
version: 1,
|
||||
data: {},
|
||||
};
|
||||
|
||||
expect(
|
||||
resolveAssistantTurnForkBoundary({
|
||||
items: [userMessage("user-1", 1), appended],
|
||||
startIndex: 1,
|
||||
supportsTimelineCursor: true,
|
||||
}),
|
||||
).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,13 +1,7 @@
|
||||
import { getAssistantReply, type StreamItem } from "@/types/stream";
|
||||
|
||||
/** The daemon's timeline cursor; the row's anchor stays in the client. */
|
||||
interface TimelineBoundaryCursor {
|
||||
epoch: string;
|
||||
seq: number;
|
||||
}
|
||||
import type { StreamItem, TimelinePosition } from "@/types/stream";
|
||||
|
||||
export type AssistantTurnForkBoundary =
|
||||
| { boundaryCursor: TimelineBoundaryCursor; boundaryMessageId?: string }
|
||||
| { boundaryCursor: TimelinePosition; boundaryMessageId?: string }
|
||||
| { boundaryCursor?: undefined; boundaryMessageId: string };
|
||||
|
||||
export function resolveAssistantTurnForkBoundary(input: {
|
||||
@@ -15,15 +9,15 @@ export function resolveAssistantTurnForkBoundary(input: {
|
||||
startIndex: number;
|
||||
supportsTimelineCursor: boolean;
|
||||
}): AssistantTurnForkBoundary | undefined {
|
||||
const reply = getAssistantReply(input.items[input.startIndex]);
|
||||
if (!reply) {
|
||||
const item = input.items[input.startIndex];
|
||||
if (item?.kind !== "assistant_message") {
|
||||
return undefined;
|
||||
}
|
||||
if (input.supportsTimelineCursor && reply.timelineCursor) {
|
||||
if (input.supportsTimelineCursor && item.timelineCursor) {
|
||||
return {
|
||||
boundaryCursor: { epoch: reply.timelineCursor.epoch, seq: reply.timelineCursor.seq },
|
||||
...(reply.messageId ? { boundaryMessageId: reply.messageId } : {}),
|
||||
boundaryCursor: item.timelineCursor,
|
||||
...(item.messageId ? { boundaryMessageId: item.messageId } : {}),
|
||||
};
|
||||
}
|
||||
return reply.messageId ? { boundaryMessageId: reply.messageId } : undefined;
|
||||
return item.messageId ? { boundaryMessageId: item.messageId } : undefined;
|
||||
}
|
||||
|
||||
@@ -16,7 +16,8 @@ function pluginReply(sourceId: string, part = "0"): StreamItem {
|
||||
return {
|
||||
kind: "plugin",
|
||||
id: `math/${sourceId}/${part}`,
|
||||
source: reply(sourceId),
|
||||
sourceId,
|
||||
sourceKind: "assistant_message",
|
||||
timestamp: at,
|
||||
pluginId: "math",
|
||||
pluginItemId: `${sourceId}/${part}`,
|
||||
@@ -98,10 +99,10 @@ describe("collapseTurns", () => {
|
||||
expect(result.hostIdByFoldedMessageId.get("intermediate")).toBe("prompt");
|
||||
});
|
||||
|
||||
it.each([undefined, thought("card"), shell("card")])(
|
||||
"does not treat a plugin row replacing %o as a reply",
|
||||
(source) => {
|
||||
const card = { ...pluginReply("card"), source };
|
||||
it.each([undefined, "thought", "tool_call"] as const)(
|
||||
"does not treat a plugin row with source kind %s as a reply",
|
||||
(sourceKind) => {
|
||||
const card = { ...pluginReply("card"), sourceKind };
|
||||
const items = [user("prompt"), shell("call"), card];
|
||||
expect(collapse(items).tail).toEqual(items);
|
||||
expect(collapse(items).summaryRowsByHostId.size).toBe(0);
|
||||
@@ -139,7 +140,7 @@ describe("collapseTurns", () => {
|
||||
it("stands at its host's timeline position, taking a new row when that position lands", () => {
|
||||
const live = collapse([user("u1"), shell("c1"), reply("r1")]);
|
||||
expect(live.summaryRowsByHostId.get("u1")).not.toHaveProperty("timelineCursor");
|
||||
const cursor = { epoch: "epoch-1", seq: 7, anchorSeq: 7 };
|
||||
const cursor = { epoch: "epoch-1", seq: 7 };
|
||||
const placed = [{ ...user("u1"), timelineCursor: cursor }, shell("c1"), reply("r1")];
|
||||
const canonical = collapse(placed, { previousSummaryRowsByHostId: live.summaryRowsByHostId });
|
||||
expect(canonical.summaryRowsByHostId.get("u1")).not.toBe(live.summaryRowsByHostId.get("u1"));
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { isTurnBoundary, isTurnTrigger } from "../turn-membership";
|
||||
import {
|
||||
getStreamItemMessageId,
|
||||
getAssistantReply,
|
||||
type StreamItem,
|
||||
type ThoughtItem,
|
||||
type TimelinePosition,
|
||||
@@ -104,15 +103,22 @@ function staysVisibleWhenCollapsed(item: StreamItem): boolean {
|
||||
return isTurnTrigger(item) || item.kind === "compaction";
|
||||
}
|
||||
|
||||
function isAssistantReply(item: StreamItem): boolean {
|
||||
return (
|
||||
item.kind === "assistant_message" ||
|
||||
(item.kind === "plugin" && item.sourceKind === "assistant_message")
|
||||
);
|
||||
}
|
||||
|
||||
function findLastReplyIndex(tail: StreamItem[], start: number, end: number): number {
|
||||
for (let index = end - 1; index >= start; index -= 1) {
|
||||
const item = tail[index]!;
|
||||
if (!getAssistantReply(item)) continue;
|
||||
if (!isAssistantReply(item)) continue;
|
||||
const messageId = getStreamItemMessageId(item);
|
||||
// A transformer can split one reply into several cards; keep the whole reply visible.
|
||||
while (index > start) {
|
||||
const previous = tail[index - 1]!;
|
||||
if (!getAssistantReply(previous) || getStreamItemMessageId(previous) !== messageId) break;
|
||||
if (!isAssistantReply(previous) || getStreamItemMessageId(previous) !== messageId) break;
|
||||
index -= 1;
|
||||
}
|
||||
return index;
|
||||
@@ -150,7 +156,7 @@ export function collapseTurns(input: CollapseTurnsInput): TurnCollapse {
|
||||
}
|
||||
const folded = tail.slice(runStart, replyIndex);
|
||||
const tools = summarizeTurn(folded, input.getGroupedCalls);
|
||||
if (!hasWork(tools) && !folded.some((item) => getAssistantReply(item))) {
|
||||
if (!hasWork(tools) && !folded.some(isAssistantReply)) {
|
||||
output.push(...tail.slice(runStart, runEnd));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -150,44 +150,3 @@ describe("turn stats", () => {
|
||||
expect(host.getBoundingClientRect().height).toBe(without);
|
||||
});
|
||||
});
|
||||
|
||||
const projectedReply: StreamItem = {
|
||||
kind: "plugin",
|
||||
id: "genui/reply/1",
|
||||
source: {
|
||||
kind: "assistant_message",
|
||||
id: "reply",
|
||||
messageId: "provider-reply-1",
|
||||
text: 'Done.\n\n```ui\nCard("Summary", [])\n```',
|
||||
timelineCursor: { epoch: "e1", seq: 5, anchorSeq: 5 },
|
||||
timestamp: FRIDAY_NIGHT,
|
||||
},
|
||||
timelineCursor: { epoch: "e1", seq: 5, anchorSeq: 5 },
|
||||
timestamp: FRIDAY_NIGHT,
|
||||
pluginId: "genui",
|
||||
pluginItemId: "reply/1",
|
||||
itemKind: "genui-block",
|
||||
version: 1,
|
||||
data: {},
|
||||
};
|
||||
|
||||
it("renders copy, fork, and duration for a plugin-projected assistant reply", () => {
|
||||
const onFork = vi.fn();
|
||||
|
||||
act(() =>
|
||||
root.render(
|
||||
<CompletedTurnFooterRow
|
||||
strategy={createNativeStreamStrategy()}
|
||||
items={[projectedReply]}
|
||||
timing={COMPLETED_TIMING}
|
||||
startIndex={0}
|
||||
supportsTimelineCursor={true}
|
||||
onForkAssistantTurn={onFork}
|
||||
/>,
|
||||
),
|
||||
);
|
||||
|
||||
expect(host.querySelector('[aria-label="Copy turn"]')).not.toBeNull();
|
||||
expect(host.querySelector('[aria-label="Fork chat from here"]')).not.toBeNull();
|
||||
expect(host.textContent).toContain("Worked for 26s");
|
||||
});
|
||||
|
||||
@@ -4,7 +4,7 @@ import { View } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { SPACING, type Theme } from "@/styles/theme";
|
||||
import type { TurnTiming } from "@/timeline/turn-time";
|
||||
import { getAssistantReply, type StreamItem } from "@/types/stream";
|
||||
import type { StreamItem } from "@/types/stream";
|
||||
import {
|
||||
collectAssistantResponseContentForStreamRenderStrategy,
|
||||
type StreamStrategy,
|
||||
@@ -208,7 +208,7 @@ function CompletedTurnFooter({
|
||||
return (
|
||||
<View style={stylesheet.turnFooterSlot}>
|
||||
<AssistantTurnFooter
|
||||
getContent={getAssistantReply(items[startIndex]) ? getContent : undefined}
|
||||
getContent={items[startIndex]?.kind === "assistant_message" ? getContent : undefined}
|
||||
completedAt={timing?.completedAt}
|
||||
durationMs={timing?.durationMs}
|
||||
onFork={boundary && onForkAssistantTurn ? handleFork : undefined}
|
||||
|
||||
@@ -408,10 +408,6 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
const timelineEpoch = useSessionStore(
|
||||
(state) => state.sessions[resolvedServerId]?.agentTimelineCursor.get(agentId)?.epoch ?? null,
|
||||
);
|
||||
const timelineRewindSeq = useSessionStore((state) => {
|
||||
const rewind = state.sessions[resolvedServerId]?.agentTimelineLatestRewind.get(agentId);
|
||||
return rewind && rewind.epoch === timelineEpoch ? rewind.seq : null;
|
||||
});
|
||||
const isTimelineDetached = useSessionStore(
|
||||
(state) => state.sessions[resolvedServerId]?.agentTimelineHasNewer.get(agentId) === true,
|
||||
);
|
||||
@@ -1170,7 +1166,6 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
agentId={agentId}
|
||||
serverId={resolvedServerId}
|
||||
epoch={timelineEpoch}
|
||||
rewindSeq={timelineRewindSeq}
|
||||
items={findItems}
|
||||
viewportRef={viewportRef}
|
||||
revealLoadedMessage={revealLoadedMessage}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { useLocalSearchParams } from "expo-router";
|
||||
import { Redirect, useLocalSearchParams } from "expo-router";
|
||||
import { useMemo } from "react";
|
||||
import { HostRouteBootstrapBoundary } from "@/components/host-route-bootstrap-boundary";
|
||||
import SettingsScreen from "@/screens/settings-screen";
|
||||
import { normalizeHostSectionSlug } from "@/utils/host-routes";
|
||||
import { buildSettingsHostSectionRoute, normalizeHostSectionSlug } from "@/utils/host-routes";
|
||||
|
||||
export default function SettingsHostSectionRoute() {
|
||||
const params = useLocalSearchParams<{ serverId?: string; hostSection?: string }>();
|
||||
@@ -11,6 +11,10 @@ export default function SettingsHostSectionRoute() {
|
||||
const section = normalizeHostSectionSlug(rawSection) ?? "connections";
|
||||
const view = useMemo(() => ({ kind: "host" as const, serverId, section }), [serverId, section]);
|
||||
|
||||
if (rawSection === "pair-device" && serverId) {
|
||||
return <Redirect href={buildSettingsHostSectionRoute(serverId, "devices")} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<HostRouteBootstrapBoundary>
|
||||
<SettingsScreen view={view} />
|
||||
|
||||
@@ -7,7 +7,6 @@ import { FOOTER_HEIGHT } from "@/constants/layout";
|
||||
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
|
||||
import { KeyboardTranslateView } from "@/keyboard/shift";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useToast } from "@/contexts/toast-context";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import { toErrorMessage } from "@/utils/error-messages";
|
||||
|
||||
@@ -20,7 +19,6 @@ export function ArchivedAgentCallout({ serverId, agentId }: ArchivedAgentCallout
|
||||
const { t } = useTranslation();
|
||||
const client = useHostRuntimeClient(serverId);
|
||||
const isConnected = useHostRuntimeIsConnected(serverId);
|
||||
const toast = useToast();
|
||||
const [isUnarchiving, setIsUnarchiving] = useState(false);
|
||||
const [unarchiveError, setUnarchiveError] = useState<string | null>(null);
|
||||
|
||||
@@ -29,15 +27,12 @@ export function ArchivedAgentCallout({ serverId, agentId }: ArchivedAgentCallout
|
||||
setIsUnarchiving(true);
|
||||
setUnarchiveError(null);
|
||||
try {
|
||||
const refreshed = await client.refreshAgent(agentId);
|
||||
if (refreshed.historyDiverged) {
|
||||
toast.show(t("workspace.tabs.toasts.reloadedAgentHistoryDiverged"), { variant: "warning" });
|
||||
}
|
||||
await client.refreshAgent(agentId);
|
||||
} catch (error) {
|
||||
setUnarchiveError(toErrorMessage(error));
|
||||
setIsUnarchiving(false);
|
||||
}
|
||||
}, [client, isConnected, isUnarchiving, agentId, toast, t]);
|
||||
}, [client, isConnected, isUnarchiving, agentId]);
|
||||
|
||||
return (
|
||||
<KeyboardTranslateView style={styles.container}>
|
||||
|
||||
@@ -3,7 +3,7 @@ import { Pressable, Text, View, type PressableStateCallbackType } from "react-na
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import type { AgentProvider } from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentProfile, AgentProfilePicker, AgentProfileSeed } from "@/agent-profiles";
|
||||
import type { AgentProfilePicker, AgentProfileSeed } from "@/agent-profiles";
|
||||
import { ComboboxTrigger } from "@/components/ui/combobox-trigger";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { Combobox, type ComboboxOption, type ComboboxProps } from "@/components/ui/combobox";
|
||||
@@ -40,7 +40,7 @@ interface CombinedModelSelectorProps {
|
||||
profiles?: AgentProfilePicker | null;
|
||||
onApplyProfile?: (profileId: string) => void;
|
||||
onEditProfiles?: () => void;
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => void;
|
||||
onEditProfile?: (profileId: string) => void;
|
||||
renderTrigger?: (input: {
|
||||
selectedModelLabel: string;
|
||||
@@ -195,17 +195,12 @@ export function CombinedModelSelector({
|
||||
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(
|
||||
(seed: AgentProfileSeed) => {
|
||||
if (seed.modelId) {
|
||||
onSelect(seed.provider, seed.modelId);
|
||||
}
|
||||
handleOpenChange(false);
|
||||
void onCreateProfile?.(seed);
|
||||
onCreateProfile?.(seed);
|
||||
},
|
||||
[handleOpenChange, onCreateProfile, onSelect],
|
||||
[handleOpenChange, onCreateProfile],
|
||||
);
|
||||
|
||||
const handleEditProfile = useCallback(
|
||||
|
||||
@@ -31,7 +31,6 @@ import {
|
||||
import type { AgentProvider } from "@getpaseo/protocol/agent-types";
|
||||
import {
|
||||
AgentProfileGlyph,
|
||||
type AgentProfile,
|
||||
type AgentProfilePicker,
|
||||
type AgentProfilePickerRow as AgentProfilePickerRowModel,
|
||||
type AgentProfileSeed,
|
||||
@@ -222,7 +221,7 @@ interface ModelBrowserProps {
|
||||
/** Applying a profile resolves the pick and dismisses, exactly like a model row. */
|
||||
onApplyProfile?: (profileId: string) => void;
|
||||
onEditProfiles?: () => void;
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => void;
|
||||
onEditProfile?: (profileId: string) => void;
|
||||
onRetryProvider?: (provider: AgentProvider) => void;
|
||||
isRetryingProvider?: boolean;
|
||||
@@ -696,7 +695,7 @@ function ModelRow({
|
||||
showProviderLabel?: boolean;
|
||||
onPress: () => void;
|
||||
profiledRows: AgentProfilePickerRowModel[];
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => void;
|
||||
onEditProfile?: (profileId: string) => void;
|
||||
onEditProfiles?: () => void;
|
||||
}) {
|
||||
@@ -759,13 +758,7 @@ function ModelRow({
|
||||
label={t("modelSelector.editProfileLabel", { name: primary.name })}
|
||||
testID={`model-edit-profile-${row.provider}-${row.modelId}`}
|
||||
>
|
||||
<AgentProfileGlyph
|
||||
icon={primary.icon}
|
||||
color={primary.color}
|
||||
provider={primary.provider}
|
||||
serverId={serverId}
|
||||
size={ICON_SIZE.xs}
|
||||
/>
|
||||
<AgentProfileGlyph icon={primary.icon} color={primary.color} size={ICON_SIZE.xs} />
|
||||
</ModelRowProfileAction>
|
||||
);
|
||||
}
|
||||
@@ -779,13 +772,7 @@ function ModelRow({
|
||||
label={t("modelSelector.editProfilesCount", { count: profiledRows.length })}
|
||||
testID={`model-edit-profiles-${row.provider}-${row.modelId}`}
|
||||
>
|
||||
<AgentProfileGlyph
|
||||
icon={primary.icon}
|
||||
color={primary.color}
|
||||
provider={primary.provider}
|
||||
serverId={serverId}
|
||||
size={ICON_SIZE.xs}
|
||||
/>
|
||||
<AgentProfileGlyph icon={primary.icon} color={primary.color} size={ICON_SIZE.xs} />
|
||||
</ModelRowProfileAction>
|
||||
);
|
||||
}, [
|
||||
@@ -800,7 +787,6 @@ function ModelRow({
|
||||
profiledRows,
|
||||
row.modelId,
|
||||
row.provider,
|
||||
serverId,
|
||||
t,
|
||||
]);
|
||||
|
||||
@@ -875,7 +861,7 @@ function SelectableModelRow({
|
||||
showProviderLabel?: boolean;
|
||||
onSelect: (provider: string, modelId: string) => void;
|
||||
profiledRows: AgentProfilePickerRowModel[];
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => void;
|
||||
onEditProfile?: (profileId: string) => void;
|
||||
onEditProfiles?: () => void;
|
||||
}) {
|
||||
@@ -899,25 +885,15 @@ function SelectableModelRow({
|
||||
|
||||
function AgentProfilePickerRowView({
|
||||
row,
|
||||
serverId,
|
||||
onApply,
|
||||
}: {
|
||||
row: AgentProfilePickerRowModel;
|
||||
serverId: string | null;
|
||||
onApply: (profileId: string) => void;
|
||||
}) {
|
||||
const handlePress = useCallback(() => onApply(row.id), [onApply, row.id]);
|
||||
const leadingSlot = useMemo(
|
||||
() => (
|
||||
<AgentProfileGlyph
|
||||
icon={row.icon}
|
||||
color={row.color}
|
||||
provider={row.provider}
|
||||
serverId={serverId}
|
||||
size={ICON_SIZE.sm}
|
||||
/>
|
||||
),
|
||||
[row.color, row.icon, row.provider, serverId],
|
||||
() => <AgentProfileGlyph icon={row.icon} color={row.color} size={ICON_SIZE.sm} />,
|
||||
[row.color, row.icon],
|
||||
);
|
||||
return (
|
||||
<ModelBrowserRow
|
||||
@@ -938,12 +914,10 @@ function AgentProfilePickerRowView({
|
||||
*/
|
||||
function AgentProfilesPickerSection({
|
||||
rows,
|
||||
serverId,
|
||||
onApplyProfile,
|
||||
onEditProfiles,
|
||||
}: {
|
||||
rows: AgentProfilePickerRowModel[];
|
||||
serverId: string | null;
|
||||
onApplyProfile?: (profileId: string) => void;
|
||||
onEditProfiles?: () => void;
|
||||
}) {
|
||||
@@ -963,12 +937,7 @@ function AgentProfilesPickerSection({
|
||||
) : null}
|
||||
</View>
|
||||
{rows.map((row) => (
|
||||
<AgentProfilePickerRowView
|
||||
key={row.id}
|
||||
row={row}
|
||||
serverId={serverId}
|
||||
onApply={handleApply}
|
||||
/>
|
||||
<AgentProfilePickerRowView key={row.id} row={row} onApply={handleApply} />
|
||||
))}
|
||||
</View>
|
||||
);
|
||||
@@ -997,12 +966,10 @@ function CreateAgentProfileRow({ onPress }: { onPress: () => void }) {
|
||||
|
||||
function AgentProfilesPickerContent({
|
||||
rows,
|
||||
serverId,
|
||||
onApplyProfile,
|
||||
onEditProfiles,
|
||||
}: {
|
||||
rows: AgentProfilePickerRowModel[];
|
||||
serverId: string | null;
|
||||
onApplyProfile?: (profileId: string) => void;
|
||||
onEditProfiles?: () => void;
|
||||
}) {
|
||||
@@ -1012,7 +979,6 @@ function AgentProfilesPickerContent({
|
||||
return (
|
||||
<AgentProfilesPickerSection
|
||||
rows={rows}
|
||||
serverId={serverId}
|
||||
onApplyProfile={onApplyProfile}
|
||||
onEditProfiles={onEditProfiles}
|
||||
/>
|
||||
@@ -1025,13 +991,11 @@ function AgentProfilesPickerContent({
|
||||
*/
|
||||
function ProfileSearchResultsHeader({
|
||||
rows,
|
||||
serverId,
|
||||
hasModelRows,
|
||||
onApplyProfile,
|
||||
onEditProfiles,
|
||||
}: {
|
||||
rows: AgentProfilePickerRowModel[];
|
||||
serverId: string | null;
|
||||
hasModelRows: boolean;
|
||||
onApplyProfile?: (profileId: string) => void;
|
||||
onEditProfiles?: () => void;
|
||||
@@ -1041,7 +1005,6 @@ function ProfileSearchResultsHeader({
|
||||
<View>
|
||||
<AgentProfilesPickerSection
|
||||
rows={rows}
|
||||
serverId={serverId}
|
||||
onApplyProfile={onApplyProfile}
|
||||
onEditProfiles={onEditProfiles}
|
||||
/>
|
||||
@@ -1244,7 +1207,7 @@ function ModelRowList({
|
||||
header?: React.ReactElement;
|
||||
scrolling: "sheet" | "independent";
|
||||
profiledLookup: Map<string, AgentProfilePickerRowModel[]>;
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => void;
|
||||
onEditProfile?: (profileId: string) => void;
|
||||
onEditProfiles?: () => void;
|
||||
}) {
|
||||
@@ -1373,7 +1336,7 @@ function ProviderModelBrowserContent({
|
||||
onSelect: (provider: string, modelId: string) => void;
|
||||
onApplyProfile?: (profileId: string) => void;
|
||||
onEditProfiles?: () => void;
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => void;
|
||||
onEditProfile?: (profileId: string) => void;
|
||||
profiledLookup: Map<string, AgentProfilePickerRowModel[]>;
|
||||
showProfilesSection?: boolean;
|
||||
@@ -1400,7 +1363,6 @@ function ProviderModelBrowserContent({
|
||||
return (
|
||||
<AgentProfilesPickerContent
|
||||
rows={providerProfileRows}
|
||||
serverId={serverId}
|
||||
onApplyProfile={onApplyProfile}
|
||||
onEditProfiles={onEditProfiles}
|
||||
/>
|
||||
@@ -1409,7 +1371,6 @@ function ProviderModelBrowserContent({
|
||||
return matchedProfileRows.length > 0 ? (
|
||||
<ProfileSearchResultsHeader
|
||||
rows={matchedProfileRows}
|
||||
serverId={serverId}
|
||||
hasModelRows={visibleRows.length > 0}
|
||||
onApplyProfile={onApplyProfile}
|
||||
onEditProfiles={onEditProfiles}
|
||||
@@ -1422,7 +1383,6 @@ function ProviderModelBrowserContent({
|
||||
onEditProfiles,
|
||||
profiles,
|
||||
providerProfileRows,
|
||||
serverId,
|
||||
showProfilesSection,
|
||||
visibleRows.length,
|
||||
]);
|
||||
@@ -1525,13 +1485,12 @@ function ModelBrowserContent({
|
||||
allView.kind === "searchResults" && allView.profiles.length > 0 ? (
|
||||
<ProfileSearchResultsHeader
|
||||
rows={allView.profiles}
|
||||
serverId={serverId}
|
||||
hasModelRows={allView.rows.length > 0}
|
||||
onApplyProfile={onApplyProfile}
|
||||
onEditProfiles={onEditProfiles}
|
||||
/>
|
||||
) : undefined,
|
||||
[allView, onApplyProfile, onEditProfiles, serverId],
|
||||
[allView, onApplyProfile, onEditProfiles],
|
||||
);
|
||||
|
||||
if (view.kind === "provider") {
|
||||
@@ -1593,7 +1552,6 @@ function ModelBrowserContent({
|
||||
{showProfilesSection && profiles ? (
|
||||
<AgentProfilesPickerContent
|
||||
rows={profiles.rows}
|
||||
serverId={serverId}
|
||||
onApplyProfile={onApplyProfile}
|
||||
onEditProfiles={onEditProfiles}
|
||||
/>
|
||||
|
||||
@@ -9,7 +9,6 @@ import { useRewindComposerRestore } from "./composer-restore";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { shouldRestoreComposerForRewindMode } from "./rewind-mode";
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import { hostSupportsFeature } from "@/runtime/host-features";
|
||||
|
||||
interface UseRewindAgentMutationInput {
|
||||
serverId?: string;
|
||||
@@ -43,16 +42,7 @@ export function useRewindAgentMutation(input: UseRewindAgentMutationInput): {
|
||||
throw new Error(t("common.errors.daemonClientUnavailable"));
|
||||
}
|
||||
await input.client.rewindAgent(input.agentId, input.messageId, mode);
|
||||
// COMPAT(timelineRewindOperations): added in v0.14.1, remove after 2027-05-10. A daemon with
|
||||
// the feature delivers the rewind on the live timeline; an older one replaced the timeline
|
||||
// and this client has to read it again.
|
||||
const appliesLive =
|
||||
input.serverId !== undefined &&
|
||||
hostSupportsFeature(
|
||||
useSessionStore.getState().sessions[input.serverId]?.serverInfo,
|
||||
"timelineRewindOperations",
|
||||
);
|
||||
if (mode !== "files" && !appliesLive) {
|
||||
if (mode !== "files") {
|
||||
const cursor = input.serverId
|
||||
? useSessionStore
|
||||
.getState()
|
||||
|
||||
@@ -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 { StyleSheet } from "react-native-unistyles";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { settingsStyles } from "@/styles/settings";
|
||||
import { NestedSettingsRows } from "./row-density";
|
||||
import { SettingsRowChildren } from "./row-children";
|
||||
import { SettingsRowHeader } from "./row-header";
|
||||
|
||||
interface SettingsCollapsibleRowProps {
|
||||
@@ -48,27 +46,7 @@ export function SettingsCollapsibleRow({
|
||||
webAccessibilityProps={webExpandedProps}
|
||||
testID={testID ? `${testID}-toggle` : undefined}
|
||||
/>
|
||||
{expanded ? (
|
||||
<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}
|
||||
{expanded ? <SettingsRowChildren>{children}</SettingsRowChildren> : null}
|
||||
</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 { settingsStyles } from "@/styles/settings";
|
||||
import { ControlSizeProvider } from "@/components/ui/control-size";
|
||||
import { ExternalLink, type ExternalLinkProps } from "@/components/ui/external-link";
|
||||
import { useSettingsRowLayout } from "./row-density";
|
||||
import { SettingsRowTitle } from "./row-label";
|
||||
export { SettingsRowChildren } from "./row-children";
|
||||
export { SettingsGroup } from "./headings/settings-group";
|
||||
export { SettingsSection } from "./headings/settings-section";
|
||||
export { SettingsCollapsibleRow } from "./collapsible-row";
|
||||
@@ -36,11 +39,16 @@ export { SettingsBackLink, SettingsDetailHeader } from "./detail-header";
|
||||
export { SettingsInfoTip } from "./headings/settings-info-tip";
|
||||
export { MenuSettingsRows } from "./row-density";
|
||||
|
||||
/** What app screens can add to a plugin-facing row: an accessory beside the label, such as an info tip. */
|
||||
/**
|
||||
* 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 {
|
||||
labelAccessory?: ReactNode;
|
||||
/** An icon before the label, such as the thing the row is about. */
|
||||
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 {
|
||||
@@ -67,6 +75,7 @@ export function SettingsRow({
|
||||
leading,
|
||||
labelAccessory,
|
||||
hint,
|
||||
link,
|
||||
error,
|
||||
children,
|
||||
testID,
|
||||
@@ -74,20 +83,17 @@ export function SettingsRow({
|
||||
const compact = useIsCompactFormFactor();
|
||||
const layout = useSettingsRowLayout();
|
||||
const rowStyle = useMemo(() => [layout.row, compact && styles.compactRow], [compact, layout]);
|
||||
const accessoryTitleStyle = useMemo(() => [layout.title, styles.accessoryLabel], [layout]);
|
||||
return (
|
||||
<View style={rowStyle} testID={testID}>
|
||||
{leading ? <View style={styles.leading}>{leading}</View> : null}
|
||||
<View style={styles.label}>
|
||||
{labelAccessory ? (
|
||||
<View style={styles.labelRow}>
|
||||
<Text style={accessoryTitleStyle}>{label}</Text>
|
||||
{labelAccessory}
|
||||
</View>
|
||||
) : (
|
||||
<Text style={layout.title}>{label}</Text>
|
||||
)}
|
||||
<SettingsRowTitle label={label} accessory={labelAccessory} />
|
||||
{typeof hint === "string" ? <Text style={layout.hint}>{hint}</Text> : hint}
|
||||
{link ? (
|
||||
<View style={styles.link}>
|
||||
<ExternalLink {...link} />
|
||||
</View>
|
||||
) : null}
|
||||
{error ? (
|
||||
<Text accessibilityRole="alert" style={settingsStyles.rowError}>
|
||||
{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 (
|
||||
<SettingsRow {...row}>
|
||||
<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 (
|
||||
<SettingsRow {...row}>
|
||||
<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.
|
||||
leading: { marginRight: theme.spacing[3], alignItems: "center", justifyContent: "center" },
|
||||
label: { flexGrow: 1, flexShrink: 1, flexBasis: 160, marginRight: theme.spacing[3] },
|
||||
labelRow: {
|
||||
flexDirection: "row",
|
||||
flexWrap: "wrap",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
accessoryLabel: { flexShrink: 1, minWidth: 0 },
|
||||
link: { alignItems: "flex-start", marginTop: theme.spacing[1] },
|
||||
control: { flexShrink: 1, maxWidth: "100%" },
|
||||
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,
|
||||
},
|
||||
}));
|
||||
@@ -11,6 +11,7 @@ import { SkeletonPulse, useSkeletonPulse } from "@/components/ui/skeleton";
|
||||
import { settingsStyles } from "@/styles/settings";
|
||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||
import { useSettingsRowLayout, type SettingsRowLayout } from "./row-density";
|
||||
import { SettingsRowTitle } from "./row-label";
|
||||
|
||||
const ThemedChevron = withUnistyles(ChevronRight);
|
||||
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
|
||||
@@ -114,9 +115,8 @@ export function SettingsRowHeader({
|
||||
</View>
|
||||
) : null}
|
||||
<View style={[settingsStyles.rowContent, styles.passThrough]}>
|
||||
<View style={labelAccessory ? styles.labelRow : undefined} {...HIDDEN_FROM_ASSISTIVE_TECH}>
|
||||
<Text style={layout.title}>{label}</Text>
|
||||
{labelAccessory}
|
||||
<View {...HIDDEN_FROM_ASSISTIVE_TECH}>
|
||||
<SettingsRowTitle label={label} accessory={labelAccessory} />
|
||||
</View>
|
||||
{hintStatus ? (
|
||||
<RowHintLine hint={hint} status={hintStatus} hintStyle={layout.hint} />
|
||||
@@ -256,7 +256,6 @@ const styles = StyleSheet.create((theme) => ({
|
||||
borderRadius: theme.borderRadius.sm,
|
||||
backgroundColor: theme.colors.surface2,
|
||||
},
|
||||
labelRow: { flexDirection: "row", alignItems: "center", gap: theme.spacing[2] },
|
||||
summary: {
|
||||
flexShrink: 1,
|
||||
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] },
|
||||
}));
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useCallback, useMemo } from "react";
|
||||
import {
|
||||
Pressable,
|
||||
View,
|
||||
type GestureResponderEvent,
|
||||
type StyleProp,
|
||||
type ViewStyle,
|
||||
@@ -19,7 +20,11 @@ import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
|
||||
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;
|
||||
disabled?: boolean;
|
||||
accessibilityLabel?: string;
|
||||
@@ -109,7 +114,7 @@ export function Switch({
|
||||
const handlePress = useCallback(
|
||||
(event: GestureResponderEvent) => {
|
||||
event.stopPropagation();
|
||||
if (disabled) return;
|
||||
if (disabled || value === null) return;
|
||||
onValueChange?.(!value);
|
||||
},
|
||||
[disabled, onValueChange, value],
|
||||
@@ -119,7 +124,10 @@ export function Switch({
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
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(
|
||||
() => [
|
||||
styles.switchControl,
|
||||
@@ -134,6 +142,12 @@ export function Switch({
|
||||
],
|
||||
[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 (
|
||||
<Pressable
|
||||
|
||||
@@ -96,7 +96,6 @@ import {
|
||||
import {
|
||||
useAgentProfileEditor,
|
||||
useAgentProfilePicker,
|
||||
type AgentProfile,
|
||||
type AgentProfileApplyTarget,
|
||||
type AgentProfileEditorControls,
|
||||
type AgentProfilePicker,
|
||||
@@ -128,7 +127,7 @@ interface ControlledAgentControlsProps {
|
||||
agentProfiles?: AgentProfilePicker | null;
|
||||
onApplyAgentProfile?: (profileId: string) => void;
|
||||
onEditAgentProfiles?: () => void;
|
||||
onCreateAgentProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
|
||||
onCreateAgentProfile?: (seed: AgentProfileSeed) => void;
|
||||
onEditAgentProfile?: (profileId: string) => void;
|
||||
optionControls?: ComposerOptionControls;
|
||||
onDropdownClose?: () => void;
|
||||
@@ -270,7 +269,7 @@ function useEditAgentProfilesNavigation(
|
||||
): (() => void) | undefined {
|
||||
const handleEdit = useCallback(() => {
|
||||
if (!serverId) return;
|
||||
router.push(buildSettingsHostSectionRoute(serverId, "agent-profiles"));
|
||||
router.push(buildSettingsHostSectionRoute(serverId, "agents"));
|
||||
}, [serverId]);
|
||||
return serverId && isSupported ? handleEdit : undefined;
|
||||
}
|
||||
@@ -279,14 +278,14 @@ function resolveAgentProfileEditorActions(
|
||||
isSupported: boolean,
|
||||
editor: AgentProfileEditorControls,
|
||||
): {
|
||||
create?: (seed: AgentProfileSeed) => Promise<AgentProfile | null>;
|
||||
create?: (seed: AgentProfileSeed) => void;
|
||||
edit?: (profileId: string) => void;
|
||||
} {
|
||||
if (!isSupported) {
|
||||
return {};
|
||||
}
|
||||
return {
|
||||
create: editor.quickCreateFromModel,
|
||||
create: editor.openCreateFromModel,
|
||||
edit: editor.openEdit,
|
||||
};
|
||||
}
|
||||
@@ -733,7 +732,7 @@ interface AgentControlsContentProps {
|
||||
featureItems: ComposerControlItem[];
|
||||
onApplyAgentProfile?: (profileId: string) => void;
|
||||
onEditAgentProfiles?: () => void;
|
||||
onCreateAgentProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
|
||||
onCreateAgentProfile?: (seed: AgentProfileSeed) => void;
|
||||
onEditAgentProfile?: (profileId: string) => void;
|
||||
onDropdownClose?: () => void;
|
||||
onModelSelectorOpen?: () => void;
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
} from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import type { AgentProvider } from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentProfile, AgentProfilePicker, AgentProfileSeed } from "@/agent-profiles";
|
||||
import type { AgentProfilePicker, AgentProfileSeed } from "@/agent-profiles";
|
||||
import { AdaptiveModalSheet } from "@/components/adaptive-modal-sheet";
|
||||
import type { ContextBridge } from "@/components/ui/isolated-bottom-sheet-modal";
|
||||
import { ComboboxTrigger } from "@/components/ui/combobox-trigger";
|
||||
@@ -56,7 +56,7 @@ interface CompactModelSheetProps {
|
||||
profiles?: AgentProfilePicker | null;
|
||||
onApplyProfile?: (profileId: string) => void;
|
||||
onEditProfiles?: () => void;
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => void;
|
||||
onEditProfile?: (profileId: string) => void;
|
||||
onOpen?: () => void;
|
||||
onClose?: () => void;
|
||||
@@ -74,9 +74,8 @@ interface CompactModelSheetProps {
|
||||
}
|
||||
|
||||
function resolveModelSheetProfileActions(
|
||||
onCreateProfile: ((seed: AgentProfileSeed) => Promise<AgentProfile | null> | void) | undefined,
|
||||
onCreateProfile: ((seed: AgentProfileSeed) => void) | undefined,
|
||||
onEditProfile: ((profileId: string) => void) | undefined,
|
||||
onSelect: (provider: string, modelId: string) => void,
|
||||
close: () => void,
|
||||
): {
|
||||
create?: (seed: AgentProfileSeed) => void;
|
||||
@@ -85,11 +84,8 @@ function resolveModelSheetProfileActions(
|
||||
return {
|
||||
create: onCreateProfile
|
||||
? (seed: AgentProfileSeed) => {
|
||||
if (seed.modelId) {
|
||||
onSelect(seed.provider, seed.modelId);
|
||||
}
|
||||
close();
|
||||
void onCreateProfile(seed);
|
||||
onCreateProfile(seed);
|
||||
}
|
||||
: undefined,
|
||||
edit: onEditProfile
|
||||
@@ -285,12 +281,7 @@ export function CompactModelSheet({
|
||||
onEditProfiles?.();
|
||||
}, [close, onEditProfiles]);
|
||||
|
||||
const profileActions = resolveModelSheetProfileActions(
|
||||
onCreateProfile,
|
||||
onEditProfile,
|
||||
onSelect,
|
||||
close,
|
||||
);
|
||||
const profileActions = resolveModelSheetProfileActions(onCreateProfile, onEditProfile, close);
|
||||
|
||||
const toggle = useCallback(() => {
|
||||
if (isOpen) {
|
||||
|
||||
@@ -385,16 +385,6 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
|
||||
console.warn("[Session] timeline replacement refresh failed", { serverId, error });
|
||||
});
|
||||
};
|
||||
const onRewind = (message: SessionOutboundMessage) => {
|
||||
if (message.type !== "agent.timeline.rewind") return;
|
||||
const { agentId, epoch, seq, retireFromSeq } = message.payload;
|
||||
sync.applyStreamEvent(agentId, {
|
||||
event: { type: "rewind", retireFromSeq },
|
||||
seq,
|
||||
epoch,
|
||||
timestamp: new Date(),
|
||||
});
|
||||
};
|
||||
const sync = getHostRuntimeStore().createViewedTimelineOwner(serverId, {
|
||||
canCheckFreshness: () =>
|
||||
client.getLastServerInfoMessage()?.features?.timelineFreshnessCheck === true,
|
||||
@@ -405,7 +395,6 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
|
||||
update: (message) => {
|
||||
if (message.type === "agent_stream") onStream(message);
|
||||
else if (message.type === "agent.timeline.replacement") onReplacement(message);
|
||||
else if (message.type === "agent.timeline.rewind") onRewind(message);
|
||||
},
|
||||
});
|
||||
return observation;
|
||||
|
||||
@@ -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 { useTranslation } from "react-i18next";
|
||||
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 {
|
||||
serverId: string;
|
||||
+1
-1
@@ -23,7 +23,7 @@ import {
|
||||
|
||||
const RELAY_DOCS_URL = "https://paseo.sh/docs/security";
|
||||
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 ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -166,7 +166,7 @@ describe("ensureAgentIsInitialized", () => {
|
||||
kind: "assistant_message",
|
||||
id: "canonical-item",
|
||||
text: "Canonical before restart",
|
||||
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 12 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 12 },
|
||||
timestamp: new Date("2026-07-27T10:00:00.000Z"),
|
||||
},
|
||||
],
|
||||
|
||||
@@ -741,8 +741,6 @@ export const ar: TranslationResources = {
|
||||
resumeCommandUnavailable: "أمر الاستئناف غير متوفر",
|
||||
reloadingAgent: "وكيل إعادة التحميل...",
|
||||
reloadedAgent: "وكيل إعادة تحميل",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"تمت إعادة تحميل الوكيل، لكن سجل المزوّد لا يطابق هذه المحادثة، لذا لم تتم مزامنته",
|
||||
failedToReloadAgent: "فشل في إعادة تحميل الوكيل",
|
||||
failedToCloseAgent: "فشل في إغلاق الوكيل",
|
||||
},
|
||||
@@ -1784,12 +1782,6 @@ export const ar: TranslationResources = {
|
||||
"يتيح لك تطبيق الجوال الأصلي كامل الميزات التحكم في أي كمبيوتر يعمل عليه Paseo من هاتفك",
|
||||
appStore: "App Store",
|
||||
googlePlay: "Google Play",
|
||||
connectTitle: "اختر طريقة الاتصال",
|
||||
connectDocs: "الوثائق",
|
||||
openConnectDocs: "افتح وثائق الاتصال",
|
||||
recommended: "موصى به",
|
||||
relay: { title: "التتابع", hint: "مشفّر من طرف إلى طرف، امسح رمز QR" },
|
||||
tailscale: { title: "Tailscale", hint: "يتطلب بعض الإعداد" },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -1816,9 +1808,6 @@ export const ar: TranslationResources = {
|
||||
editProfilesLabel: "تحرير ملفات الوكيل",
|
||||
createProfile: "إنشاء ملف شخصي",
|
||||
createProfileFromModel: "إنشاء ملف شخصي من هذا النموذج",
|
||||
profileSaved: 'تم حفظ "{{name}}"',
|
||||
undo: "تراجع",
|
||||
undoProfileSave: "التراجع عن حفظ الملف الشخصي",
|
||||
editProfileLabel: "تحرير {{name}}",
|
||||
editProfilesCount: "تحرير الملفات الشخصية ({{count}})",
|
||||
modelCount: "{{count}} نموذج",
|
||||
@@ -1868,6 +1857,32 @@ export const ar: TranslationResources = {
|
||||
hostDisconnected: "Host غير متصل",
|
||||
},
|
||||
},
|
||||
devices: {
|
||||
title: "الأجهزة",
|
||||
waysToConnect: "طرق الاتصال",
|
||||
docs: "الوثائق",
|
||||
docsAccessibility: "افتح وثائق الاتصال",
|
||||
recommended: "موصى به",
|
||||
relay: { title: "التتابع", hint: "مشفّر من طرف إلى طرف، امسح رمز QR" },
|
||||
tailscale: {
|
||||
hint: "اتصال مباشر عبر شبكة tailnet الخاصة بك، أدخل عنوانًا",
|
||||
unavailable: "Tailscale لا يعمل على هذا المضيف",
|
||||
install: "احصل على Tailscale",
|
||||
waiting: "في انتظار بدء Tailscale على هذا المضيف",
|
||||
alwaysOn: "مفعّل دائمًا، لأن هذا المضيف يقبل اتصالات Tailscale بالفعل",
|
||||
socket: "متوقف، لأن هذا المضيف يستمع على مقبس محلي",
|
||||
launch: "يتحكم فيه الأمر الذي يشغّل هذا المضيف",
|
||||
update: "حدّث هذا المضيف لاستخدام Tailscale",
|
||||
updateDocs: "طريقة التحديث",
|
||||
address: "على هاتف متصل بـ Tailscale، أضف مضيفًا بهذا العنوان",
|
||||
statusError: "تعذّر التحقق من Tailscale",
|
||||
turnOnError: "تعذّر تشغيل Tailscale",
|
||||
turnOffError: "تعذّر إيقاف Tailscale",
|
||||
confirmTitle: "إيقاف Tailscale؟",
|
||||
confirmMessage: "هذا الجهاز متصل عبر Tailscale وسيفقد اتصاله بالمضيف.",
|
||||
confirmAction: "إيقاف",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "كلمة المرور لـ {{host}}",
|
||||
@@ -2435,7 +2450,6 @@ export const ar: TranslationResources = {
|
||||
projects: "المشاريع",
|
||||
connections: "اتصالات",
|
||||
agents: "Agents",
|
||||
agentProfiles: "ملفات الوكيل",
|
||||
metadata: "البيانات الوصفية",
|
||||
voice: "الصوت",
|
||||
workspaces: "Workspaces",
|
||||
@@ -2922,9 +2936,7 @@ export const ar: TranslationResources = {
|
||||
timeout: "نفذ الوقت",
|
||||
},
|
||||
pairDevices: {
|
||||
title: "إقران الأجهزة",
|
||||
rowTitle: "إقران جهاز",
|
||||
rowHint: "امسح رمز QR ضوئيًا أو انسخ رابطًا لتوصيل هاتفك بهذا المضيف",
|
||||
},
|
||||
skills: {
|
||||
...en.settings.host.skills,
|
||||
@@ -3063,31 +3075,6 @@ export const ar: TranslationResources = {
|
||||
removeConfirmMessage: 'إزالة "{{name}}"؟',
|
||||
moveUp: "نقل لأعلى",
|
||||
moveDown: "نقل لأسفل",
|
||||
searchPlaceholder: "ابحث عن الملفات",
|
||||
clearSearch: "مسح البحث",
|
||||
noSearchMatches: 'لا توجد ملفات تطابق "{{query}}"',
|
||||
noRoutingNote: "بدون ملاحظة",
|
||||
duplicate: "تكرار",
|
||||
copyName: "{{name}} (نسخة)",
|
||||
moveToTop: "نقل إلى الأعلى",
|
||||
profileActions: "إجراءات {{name}}",
|
||||
reorderProfile: "إعادة ترتيب {{name}}",
|
||||
previousProfile: "الملف السابق",
|
||||
nextProfile: "الملف التالي",
|
||||
chooseModelPlaceholder: "اختر نموذجًا",
|
||||
searchModelsPlaceholder: "ابحث عن النماذج",
|
||||
chooseModelSubtitle: "اختر نموذجًا",
|
||||
customizeSettings: "تخصيص الإعدادات",
|
||||
addRoutingNoteShort: "إضافة ملاحظة",
|
||||
providerOptionsLabel: "خيارات {{provider}}",
|
||||
discardTitle: "تجاهل التغييرات؟",
|
||||
discardMessage: "لديك تغييرات غير محفوظة في هذا الملف.",
|
||||
discardConfirm: "تجاهل",
|
||||
columns: {
|
||||
profile: "الملف",
|
||||
runtime: "النموذج والتشغيل",
|
||||
whenToUse: "متى يُستخدم",
|
||||
},
|
||||
},
|
||||
daemon: {
|
||||
rename: {
|
||||
|
||||
@@ -740,8 +740,6 @@ export const en = {
|
||||
resumeCommandUnavailable: "Resume command not available",
|
||||
reloadingAgent: "Reloading agent...",
|
||||
reloadedAgent: "Reloaded agent",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"Reloaded agent, but the provider's history doesn't match this chat, so it wasn't synced",
|
||||
failedToReloadAgent: "Failed to reload agent",
|
||||
failedToCloseAgent: "Failed to close agent",
|
||||
},
|
||||
@@ -1813,12 +1811,6 @@ export const en = {
|
||||
"The fully featured native mobile app allows you to control any Paseo computer from your phone",
|
||||
appStore: "App Store",
|
||||
googlePlay: "Google Play",
|
||||
connectTitle: "Choose how to connect",
|
||||
connectDocs: "Docs",
|
||||
openConnectDocs: "Open connectivity documentation",
|
||||
recommended: "Recommended",
|
||||
relay: { title: "Relay", hint: "End-to-end encrypted, scan a QR code" },
|
||||
tailscale: { title: "Tailscale", hint: "Requires some setup" },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -1845,9 +1837,6 @@ export const en = {
|
||||
editProfilesLabel: "Edit agent profiles",
|
||||
createProfile: "Create profile",
|
||||
createProfileFromModel: "Create profile from this model",
|
||||
profileSaved: 'Saved "{{name}}"',
|
||||
undo: "Undo",
|
||||
undoProfileSave: "Undo saving profile",
|
||||
editProfileLabel: "Edit {{name}}",
|
||||
editProfilesCount: "Edit profiles ({{count}})",
|
||||
modelCount: "{{count}} model",
|
||||
@@ -1897,6 +1886,33 @@ export const en = {
|
||||
hostDisconnected: "Host is not connected",
|
||||
},
|
||||
},
|
||||
devices: {
|
||||
title: "Devices",
|
||||
waysToConnect: "Ways to connect",
|
||||
docs: "Docs",
|
||||
docsAccessibility: "Open connectivity documentation",
|
||||
recommended: "Recommended",
|
||||
relay: { title: "Relay", hint: "End-to-end encrypted, scan a QR code" },
|
||||
tailscale: {
|
||||
hint: "Direct over your tailnet, enter an address",
|
||||
unavailable: "Tailscale is not running on this host",
|
||||
install: "Get Tailscale",
|
||||
waiting: "Waiting for Tailscale to start on this host",
|
||||
alwaysOn: "Always on, because this host already accepts Tailscale connections",
|
||||
socket: "Off, because this host listens on a local socket",
|
||||
launch: "Controlled by the command that starts this host",
|
||||
update: "Update this host to use Tailscale",
|
||||
updateDocs: "How to update",
|
||||
address: "On a phone with Tailscale, add a host at this address",
|
||||
statusError: "Could not check Tailscale",
|
||||
turnOnError: "Could not turn on Tailscale",
|
||||
turnOffError: "Could not turn off Tailscale",
|
||||
confirmTitle: "Turn off Tailscale?",
|
||||
confirmMessage:
|
||||
"This device is connected through Tailscale and will lose its connection to the host.",
|
||||
confirmAction: "Turn off",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "Password for {{host}}",
|
||||
@@ -2466,7 +2482,6 @@ export const en = {
|
||||
projects: "Projects",
|
||||
connections: "Connections",
|
||||
agents: "Agents",
|
||||
agentProfiles: "Agent profiles",
|
||||
metadata: "Metadata",
|
||||
voice: "Voice",
|
||||
workspaces: "Workspaces",
|
||||
@@ -3017,9 +3032,7 @@ export const en = {
|
||||
timeout: "Timeout",
|
||||
},
|
||||
pairDevices: {
|
||||
title: "Pair devices",
|
||||
rowTitle: "Pair a device",
|
||||
rowHint: "Scan a QR code or copy a link to connect your phone to this host",
|
||||
},
|
||||
skills: {
|
||||
sectionTitle: "Orchestration skills",
|
||||
@@ -3153,7 +3166,7 @@ export const en = {
|
||||
featureCountOne: "{{count}} feature",
|
||||
notesLabel: "When to use",
|
||||
notesPlaceholder: "Use for UI work — components, layout and design tokens.",
|
||||
notesHint: "Tells agents when to pick this profile",
|
||||
notesHint: "Helps agents choose this profile when starting another agent.",
|
||||
save: "Save",
|
||||
saving: "Saving...",
|
||||
remove: "Remove",
|
||||
@@ -3161,31 +3174,6 @@ export const en = {
|
||||
removeConfirmMessage: 'Remove "{{name}}"?',
|
||||
moveUp: "Move up",
|
||||
moveDown: "Move down",
|
||||
searchPlaceholder: "Search profiles",
|
||||
clearSearch: "Clear search",
|
||||
noSearchMatches: 'No profiles match "{{query}}"',
|
||||
noRoutingNote: "No note",
|
||||
duplicate: "Duplicate",
|
||||
copyName: "{{name}} (copy)",
|
||||
moveToTop: "Move to top",
|
||||
profileActions: "Actions for {{name}}",
|
||||
reorderProfile: "Reorder {{name}}",
|
||||
previousProfile: "Previous profile",
|
||||
nextProfile: "Next profile",
|
||||
chooseModelPlaceholder: "Select a model",
|
||||
searchModelsPlaceholder: "Search models",
|
||||
chooseModelSubtitle: "Select a model",
|
||||
customizeSettings: "Customize settings",
|
||||
addRoutingNoteShort: "Add a note",
|
||||
providerOptionsLabel: "{{provider}} options",
|
||||
discardTitle: "Discard changes?",
|
||||
discardMessage: "You have unsaved changes to this profile.",
|
||||
discardConfirm: "Discard",
|
||||
columns: {
|
||||
profile: "Profile",
|
||||
runtime: "Model & runtime",
|
||||
whenToUse: "When to use",
|
||||
},
|
||||
},
|
||||
daemon: {
|
||||
rename: {
|
||||
|
||||
@@ -748,8 +748,6 @@ export const es: TranslationResources = {
|
||||
resumeCommandUnavailable: "Comando de reanudación no disponible",
|
||||
reloadingAgent: "Agente de recarga...",
|
||||
reloadedAgent: "Agente recargado",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"Agente recargado, pero el historial del proveedor no coincide con este chat, así que no se sincronizó",
|
||||
failedToReloadAgent: "No se pudo recargar el agente",
|
||||
failedToCloseAgent: "No se pudo cerrar el agente",
|
||||
},
|
||||
@@ -1832,12 +1830,6 @@ export const es: TranslationResources = {
|
||||
"La app móvil nativa completa te permite controlar cualquier ordenador con Paseo desde tu teléfono",
|
||||
appStore: "App Store",
|
||||
googlePlay: "Google Play",
|
||||
connectTitle: "Elige cómo conectarte",
|
||||
connectDocs: "Docs",
|
||||
openConnectDocs: "Abrir la documentación de conectividad",
|
||||
recommended: "Recomendado",
|
||||
relay: { title: "Relé", hint: "Cifrado de extremo a extremo, escanea un código QR" },
|
||||
tailscale: { title: "Tailscale", hint: "Requiere algo de configuración" },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -1864,9 +1856,6 @@ export const es: TranslationResources = {
|
||||
editProfilesLabel: "Editar perfiles de agente",
|
||||
createProfile: "Crear perfil",
|
||||
createProfileFromModel: "Crear perfil desde este modelo",
|
||||
profileSaved: 'Guardado "{{name}}"',
|
||||
undo: "Deshacer",
|
||||
undoProfileSave: "Deshacer perfil guardado",
|
||||
editProfileLabel: "Editar {{name}}",
|
||||
editProfilesCount: "Editar perfiles ({{count}})",
|
||||
modelCount: "{{count}} modelo",
|
||||
@@ -1916,6 +1905,33 @@ export const es: TranslationResources = {
|
||||
hostDisconnected: "Hostno está conectado",
|
||||
},
|
||||
},
|
||||
devices: {
|
||||
title: "Dispositivos",
|
||||
waysToConnect: "Formas de conectarse",
|
||||
docs: "Docs",
|
||||
docsAccessibility: "Abrir la documentación de conectividad",
|
||||
recommended: "Recomendado",
|
||||
relay: { title: "Relé", hint: "Cifrado de extremo a extremo, escanea un código QR" },
|
||||
tailscale: {
|
||||
hint: "Conexión directa por tu tailnet, introduce una dirección",
|
||||
unavailable: "Tailscale no se está ejecutando en este host",
|
||||
install: "Obtener Tailscale",
|
||||
waiting: "Esperando a que Tailscale se inicie en este host",
|
||||
alwaysOn: "Siempre activado, porque este host ya acepta conexiones de Tailscale",
|
||||
socket: "Desactivado, porque este host escucha en un socket local",
|
||||
launch: "Lo controla el comando que inicia este host",
|
||||
update: "Actualiza este host para usar Tailscale",
|
||||
updateDocs: "Cómo actualizar",
|
||||
address: "En un teléfono con Tailscale, añade un host con esta dirección",
|
||||
statusError: "No se pudo comprobar Tailscale",
|
||||
turnOnError: "No se pudo activar Tailscale",
|
||||
turnOffError: "No se pudo desactivar Tailscale",
|
||||
confirmTitle: "¿Desactivar Tailscale?",
|
||||
confirmMessage:
|
||||
"Este dispositivo está conectado mediante Tailscale y perderá la conexión con el host.",
|
||||
confirmAction: "Desactivar",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "Contraseña de {{host}}",
|
||||
@@ -2449,7 +2465,6 @@ export const es: TranslationResources = {
|
||||
projects: "Proyectos",
|
||||
connections: "Conexiones",
|
||||
agents: "Agents",
|
||||
agentProfiles: "Perfiles de agente",
|
||||
metadata: "Metadatos",
|
||||
voice: "Voz",
|
||||
workspaces: "Workspaces",
|
||||
@@ -2946,9 +2961,7 @@ export const es: TranslationResources = {
|
||||
timeout: "Se acabó el tiempo",
|
||||
},
|
||||
pairDevices: {
|
||||
title: "Emparejar dispositivos",
|
||||
rowTitle: "Emparejar un dispositivo",
|
||||
rowHint: "Escanee un códigoQRo copie un enlace para conectar su teléfono a este host",
|
||||
},
|
||||
skills: {
|
||||
...en.settings.host.skills,
|
||||
@@ -3089,31 +3102,6 @@ export const es: TranslationResources = {
|
||||
removeConfirmMessage: '¿Eliminar "{{name}}"?',
|
||||
moveUp: "Mover hacia arriba",
|
||||
moveDown: "Mover hacia abajo",
|
||||
searchPlaceholder: "Buscar perfiles",
|
||||
clearSearch: "Limpiar búsqueda",
|
||||
noSearchMatches: 'Ningún perfil coincide con "{{query}}"',
|
||||
noRoutingNote: "Sin nota",
|
||||
duplicate: "Duplicar",
|
||||
copyName: "{{name}} (copia)",
|
||||
moveToTop: "Mover al principio",
|
||||
profileActions: "Acciones para {{name}}",
|
||||
reorderProfile: "Reordenar {{name}}",
|
||||
previousProfile: "Perfil anterior",
|
||||
nextProfile: "Perfil siguiente",
|
||||
chooseModelPlaceholder: "Seleccionar un modelo",
|
||||
searchModelsPlaceholder: "Buscar modelos",
|
||||
chooseModelSubtitle: "Seleccionar un modelo",
|
||||
customizeSettings: "Personalizar ajustes",
|
||||
addRoutingNoteShort: "Añadir una nota",
|
||||
providerOptionsLabel: "Opciones de {{provider}}",
|
||||
discardTitle: "¿Descartar cambios?",
|
||||
discardMessage: "Tienes cambios sin guardar en este perfil.",
|
||||
discardConfirm: "Descartar",
|
||||
columns: {
|
||||
profile: "Perfil",
|
||||
runtime: "Modelo y ejecución",
|
||||
whenToUse: "Cuándo usarlo",
|
||||
},
|
||||
},
|
||||
daemon: {
|
||||
rename: {
|
||||
|
||||
@@ -748,8 +748,6 @@ export const fr: TranslationResources = {
|
||||
resumeCommandUnavailable: "Commande de reprise indisponible",
|
||||
reloadingAgent: "Rechargement de l’agent…",
|
||||
reloadedAgent: "Agent rechargé",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"Agent rechargé, mais l’historique du fournisseur ne correspond pas à cette conversation, il n’a donc pas été synchronisé",
|
||||
failedToReloadAgent: "Impossible de recharger l’agent",
|
||||
failedToCloseAgent: "Impossible de fermer l’agent",
|
||||
},
|
||||
@@ -1830,12 +1828,6 @@ export const fr: TranslationResources = {
|
||||
"L'application mobile native complète vous permet de contrôler n'importe quel ordinateur Paseo depuis votre téléphone",
|
||||
appStore: "App Store",
|
||||
googlePlay: "Google Play",
|
||||
connectTitle: "Choisissez comment vous connecter",
|
||||
connectDocs: "Docs",
|
||||
openConnectDocs: "Ouvrir la documentation sur la connectivité",
|
||||
recommended: "Recommandé",
|
||||
relay: { title: "Relais", hint: "Chiffré de bout en bout, scannez un QR code" },
|
||||
tailscale: { title: "Tailscale", hint: "Demande un peu de configuration" },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -1862,9 +1854,6 @@ export const fr: TranslationResources = {
|
||||
editProfilesLabel: "Modifier les profils d’agent",
|
||||
createProfile: "Créer un profil",
|
||||
createProfileFromModel: "Créer un profil à partir de ce modèle",
|
||||
profileSaved: "« {{name}} » enregistré",
|
||||
undo: "Annuler",
|
||||
undoProfileSave: "Annuler l’enregistrement du profil",
|
||||
editProfileLabel: "Modifier {{name}}",
|
||||
editProfilesCount: "Modifier les profils ({{count}})",
|
||||
modelCount: "{{count}} modèle",
|
||||
@@ -1914,6 +1903,32 @@ export const fr: TranslationResources = {
|
||||
hostDisconnected: "L’hôte n’est pas connecté",
|
||||
},
|
||||
},
|
||||
devices: {
|
||||
title: "Appareils",
|
||||
waysToConnect: "Moyens de connexion",
|
||||
docs: "Docs",
|
||||
docsAccessibility: "Ouvrir la documentation sur la connectivité",
|
||||
recommended: "Recommandé",
|
||||
relay: { title: "Relais", hint: "Chiffré de bout en bout, scannez un QR code" },
|
||||
tailscale: {
|
||||
hint: "Connexion directe via votre tailnet, saisissez une adresse",
|
||||
unavailable: "Tailscale ne fonctionne pas sur cet hôte",
|
||||
install: "Obtenir Tailscale",
|
||||
waiting: "En attente du démarrage de Tailscale sur cet hôte",
|
||||
alwaysOn: "Toujours activé, car cet hôte accepte déjà les connexions Tailscale",
|
||||
socket: "Désactivé, car cet hôte écoute sur un socket local",
|
||||
launch: "Contrôlé par la commande qui démarre cet hôte",
|
||||
update: "Mettez cet hôte à jour pour utiliser Tailscale",
|
||||
updateDocs: "Comment mettre à jour",
|
||||
address: "Sur un téléphone avec Tailscale, ajoutez un hôte à cette adresse",
|
||||
statusError: "Impossible de vérifier Tailscale",
|
||||
turnOnError: "Impossible d’activer Tailscale",
|
||||
turnOffError: "Impossible de désactiver Tailscale",
|
||||
confirmTitle: "Désactiver Tailscale ?",
|
||||
confirmMessage: "Cet appareil est connecté via Tailscale et perdra sa connexion à l’hôte.",
|
||||
confirmAction: "Désactiver",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "Mot de passe pour {{host}}",
|
||||
@@ -2449,7 +2464,6 @@ export const fr: TranslationResources = {
|
||||
projects: "Projets",
|
||||
connections: "Connexions",
|
||||
agents: "Agents",
|
||||
agentProfiles: "Profils d’agent",
|
||||
metadata: "Métadonnées",
|
||||
voice: "Voix",
|
||||
workspaces: "Espaces de travail",
|
||||
@@ -2948,9 +2962,7 @@ export const fr: TranslationResources = {
|
||||
timeout: "Délai dépassé",
|
||||
},
|
||||
pairDevices: {
|
||||
title: "Associer des appareils",
|
||||
rowTitle: "Associer un appareil",
|
||||
rowHint: "Scannez un QR code ou copiez un lien pour connecter votre téléphone à cet hôte",
|
||||
},
|
||||
skills: {
|
||||
...en.settings.host.skills,
|
||||
@@ -3093,31 +3105,6 @@ export const fr: TranslationResources = {
|
||||
removeConfirmMessage: "Supprimer « {{name}} » ?",
|
||||
moveUp: "Monter",
|
||||
moveDown: "Descendre",
|
||||
searchPlaceholder: "Rechercher des profils",
|
||||
clearSearch: "Effacer la recherche",
|
||||
noSearchMatches: "Aucun profil ne correspond à « {{query}} »",
|
||||
noRoutingNote: "Aucune note",
|
||||
duplicate: "Dupliquer",
|
||||
copyName: "{{name}} (copie)",
|
||||
moveToTop: "Placer en haut",
|
||||
profileActions: "Actions pour {{name}}",
|
||||
reorderProfile: "Réorganiser {{name}}",
|
||||
previousProfile: "Profil précédent",
|
||||
nextProfile: "Profil suivant",
|
||||
chooseModelPlaceholder: "Sélectionner un modèle",
|
||||
searchModelsPlaceholder: "Rechercher des modèles",
|
||||
chooseModelSubtitle: "Sélectionner un modèle",
|
||||
customizeSettings: "Personnaliser les réglages",
|
||||
addRoutingNoteShort: "Ajouter une note",
|
||||
providerOptionsLabel: "Options {{provider}}",
|
||||
discardTitle: "Ignorer les modifications ?",
|
||||
discardMessage: "Vous avez des modifications non enregistrées pour ce profil.",
|
||||
discardConfirm: "Ignorer",
|
||||
columns: {
|
||||
profile: "Profil",
|
||||
runtime: "Modèle et exécution",
|
||||
whenToUse: "Quand l’utiliser",
|
||||
},
|
||||
},
|
||||
daemon: {
|
||||
rename: {
|
||||
|
||||
@@ -748,8 +748,6 @@ export const ja: TranslationResources = {
|
||||
resumeCommandUnavailable: "再開コマンドが利用できません",
|
||||
reloadingAgent: "エージェントを再読み込み中...",
|
||||
reloadedAgent: "エージェントを再読み込みしました",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"エージェントを再読み込みしましたが、プロバイダーの履歴がこのチャットと一致しないため同期しませんでした",
|
||||
failedToReloadAgent: "エージェントの再読み込みに失敗しました",
|
||||
failedToCloseAgent: "エージェントを閉じられませんでした",
|
||||
},
|
||||
@@ -1804,12 +1802,6 @@ export const ja: TranslationResources = {
|
||||
"フル機能のネイティブモバイルアプリで、スマートフォンからどの Paseo コンピューターでも操作できます",
|
||||
appStore: "App Store",
|
||||
googlePlay: "Google Play",
|
||||
connectTitle: "接続方法を選択",
|
||||
connectDocs: "ドキュメント",
|
||||
openConnectDocs: "接続のドキュメントを開く",
|
||||
recommended: "おすすめ",
|
||||
relay: { title: "リレー", hint: "エンドツーエンド暗号化、QR コードをスキャン" },
|
||||
tailscale: { title: "Tailscale", hint: "少し設定が必要です" },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -1836,9 +1828,6 @@ export const ja: TranslationResources = {
|
||||
editProfilesLabel: "エージェントプロファイルを編集",
|
||||
createProfile: "プロファイルを作成",
|
||||
createProfileFromModel: "このモデルからプロファイルを作成",
|
||||
profileSaved: "「{{name}}」を保存しました",
|
||||
undo: "元に戻す",
|
||||
undoProfileSave: "プロファイル保存を取り消す",
|
||||
editProfileLabel: "{{name}}を編集",
|
||||
editProfilesCount: "プロファイルを編集({{count}})",
|
||||
modelCount: "{{count}}つのモデル",
|
||||
@@ -1888,6 +1877,32 @@ export const ja: TranslationResources = {
|
||||
hostDisconnected: "ホストが接続されていません",
|
||||
},
|
||||
},
|
||||
devices: {
|
||||
title: "デバイス",
|
||||
waysToConnect: "接続方法",
|
||||
docs: "ドキュメント",
|
||||
docsAccessibility: "接続のドキュメントを開く",
|
||||
recommended: "おすすめ",
|
||||
relay: { title: "リレー", hint: "エンドツーエンド暗号化、QR コードをスキャン" },
|
||||
tailscale: {
|
||||
hint: "tailnet 経由で直接接続、アドレスを入力",
|
||||
unavailable: "このホストで Tailscale が動作していません",
|
||||
install: "Tailscale を入手",
|
||||
waiting: "このホストで Tailscale が起動するのを待っています",
|
||||
alwaysOn: "常にオン。このホストはすでに Tailscale からの接続を受け付けています",
|
||||
socket: "オフ。このホストはローカルソケットで待ち受けています",
|
||||
launch: "このホストを起動するコマンドで制御されています",
|
||||
update: "Tailscale を使うにはこのホストを更新してください",
|
||||
updateDocs: "更新方法",
|
||||
address: "Tailscale を使うスマートフォンで、このアドレスのホストを追加してください",
|
||||
statusError: "Tailscale を確認できませんでした",
|
||||
turnOnError: "Tailscale をオンにできませんでした",
|
||||
turnOffError: "Tailscale をオフにできませんでした",
|
||||
confirmTitle: "Tailscale をオフにしますか?",
|
||||
confirmMessage: "このデバイスは Tailscale 経由で接続しているため、ホストとの接続が切れます。",
|
||||
confirmAction: "オフにする",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "{{host}} のパスワード",
|
||||
@@ -2423,7 +2438,6 @@ export const ja: TranslationResources = {
|
||||
projects: "プロジェクト",
|
||||
connections: "接続",
|
||||
agents: "エージェント",
|
||||
agentProfiles: "エージェントプロファイル",
|
||||
metadata: "メタデータ",
|
||||
voice: "音声",
|
||||
workspaces: "ワークスペース",
|
||||
@@ -2914,9 +2928,7 @@ export const ja: TranslationResources = {
|
||||
timeout: "タイムアウト",
|
||||
},
|
||||
pairDevices: {
|
||||
title: "デバイスをペアリング",
|
||||
rowTitle: "デバイスをペアリング",
|
||||
rowHint: "QRコードをスキャンするかリンクをコピーしてスマートフォンをこのホストに接続",
|
||||
},
|
||||
skills: {
|
||||
...en.settings.host.skills,
|
||||
@@ -3058,31 +3070,6 @@ export const ja: TranslationResources = {
|
||||
removeConfirmMessage: '"{{name}}"を削除しますか?',
|
||||
moveUp: "上に移動",
|
||||
moveDown: "下に移動",
|
||||
searchPlaceholder: "プロファイルを検索",
|
||||
clearSearch: "検索をクリア",
|
||||
noSearchMatches: "「{{query}}」に一致するプロファイルはありません",
|
||||
noRoutingNote: "メモなし",
|
||||
duplicate: "複製",
|
||||
copyName: "{{name}}(コピー)",
|
||||
moveToTop: "一番上に移動",
|
||||
profileActions: "{{name}} の操作",
|
||||
reorderProfile: "{{name}} を並べ替え",
|
||||
previousProfile: "前のプロファイル",
|
||||
nextProfile: "次のプロファイル",
|
||||
chooseModelPlaceholder: "モデルを選択",
|
||||
searchModelsPlaceholder: "モデルを検索",
|
||||
chooseModelSubtitle: "モデルを選択",
|
||||
customizeSettings: "設定をカスタマイズ",
|
||||
addRoutingNoteShort: "メモを追加",
|
||||
providerOptionsLabel: "{{provider}} オプション",
|
||||
discardTitle: "変更を破棄しますか?",
|
||||
discardMessage: "このプロファイルに未保存の変更があります。",
|
||||
discardConfirm: "破棄",
|
||||
columns: {
|
||||
profile: "プロファイル",
|
||||
runtime: "モデルと実行",
|
||||
whenToUse: "使用場面",
|
||||
},
|
||||
},
|
||||
daemon: {
|
||||
rename: {
|
||||
|
||||
@@ -743,8 +743,6 @@ export const ko: TranslationResources = {
|
||||
resumeCommandUnavailable: "재개 명령을 사용할 수 없습니다",
|
||||
reloadingAgent: "에이전트 다시 로드 중...",
|
||||
reloadedAgent: "에이전트를 다시 로드했습니다",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"에이전트를 다시 로드했지만 제공자 기록이 이 채팅과 일치하지 않아 동기화하지 않았습니다",
|
||||
failedToReloadAgent: "에이전트를 다시 로드하지 못했습니다",
|
||||
failedToCloseAgent: "에이전트를 닫지 못했습니다",
|
||||
},
|
||||
@@ -1795,12 +1793,6 @@ export const ko: TranslationResources = {
|
||||
"모든 기능을 갖춘 네이티브 모바일 앱으로 휴대폰에서 어떤 Paseo 컴퓨터든 제어할 수 있습니다",
|
||||
appStore: "App Store",
|
||||
googlePlay: "Google Play",
|
||||
connectTitle: "연결 방법 선택",
|
||||
connectDocs: "문서",
|
||||
openConnectDocs: "연결 문서 열기",
|
||||
recommended: "권장",
|
||||
relay: { title: "릴레이", hint: "엔드투엔드 암호화, QR 코드를 스캔하세요" },
|
||||
tailscale: { title: "Tailscale", hint: "약간의 설정이 필요합니다" },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -1827,9 +1819,6 @@ export const ko: TranslationResources = {
|
||||
editProfilesLabel: "에이전트 프로필 편집",
|
||||
createProfile: "프로필 만들기",
|
||||
createProfileFromModel: "이 모델에서 프로필 만들기",
|
||||
profileSaved: '"{{name}}" 저장됨',
|
||||
undo: "실행 취소",
|
||||
undoProfileSave: "프로필 저장 취소",
|
||||
editProfileLabel: "{{name}} 편집",
|
||||
editProfilesCount: "프로필 편집 ({{count}})",
|
||||
modelCount: "모델 {{count}}개",
|
||||
@@ -1879,6 +1868,32 @@ export const ko: TranslationResources = {
|
||||
hostDisconnected: "호스트가 연결되어 있지 않습니다",
|
||||
},
|
||||
},
|
||||
devices: {
|
||||
title: "기기",
|
||||
waysToConnect: "연결 방법",
|
||||
docs: "문서",
|
||||
docsAccessibility: "연결 문서 열기",
|
||||
recommended: "권장",
|
||||
relay: { title: "릴레이", hint: "엔드투엔드 암호화, QR 코드를 스캔하세요" },
|
||||
tailscale: {
|
||||
hint: "tailnet으로 직접 연결, 주소 입력",
|
||||
unavailable: "이 호스트에서 Tailscale이 실행 중이 아닙니다",
|
||||
install: "Tailscale 받기",
|
||||
waiting: "이 호스트에서 Tailscale이 시작되기를 기다리는 중",
|
||||
alwaysOn: "항상 켜짐. 이 호스트가 이미 Tailscale 연결을 받고 있습니다",
|
||||
socket: "꺼짐. 이 호스트가 로컬 소켓에서 수신 대기 중입니다",
|
||||
launch: "이 호스트를 시작하는 명령이 제어합니다",
|
||||
update: "Tailscale을 사용하려면 이 호스트를 업데이트하세요",
|
||||
updateDocs: "업데이트 방법",
|
||||
address: "Tailscale을 사용하는 휴대전화에서 이 주소로 호스트를 추가하세요",
|
||||
statusError: "Tailscale을 확인하지 못했습니다",
|
||||
turnOnError: "Tailscale을 켜지 못했습니다",
|
||||
turnOffError: "Tailscale을 끄지 못했습니다",
|
||||
confirmTitle: "Tailscale을 끌까요?",
|
||||
confirmMessage: "이 기기는 Tailscale로 연결되어 있어 호스트와의 연결이 끊깁니다.",
|
||||
confirmAction: "끄기",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "{{host}}의 비밀번호",
|
||||
@@ -2410,7 +2425,6 @@ export const ko: TranslationResources = {
|
||||
projects: "프로젝트",
|
||||
connections: "연결",
|
||||
agents: "에이전트",
|
||||
agentProfiles: "에이전트 프로필",
|
||||
metadata: "메타데이터",
|
||||
voice: "음성",
|
||||
workspaces: "워크스페이스",
|
||||
@@ -2900,9 +2914,7 @@ export const ko: TranslationResources = {
|
||||
timeout: "시간 초과",
|
||||
},
|
||||
pairDevices: {
|
||||
title: "기기 페어링",
|
||||
rowTitle: "기기 페어링",
|
||||
rowHint: "QR 코드를 스캔하거나 링크를 복사하여 휴대폰을 이 호스트에 연결하세요",
|
||||
},
|
||||
skills: {
|
||||
...en.settings.host.skills,
|
||||
@@ -3042,31 +3054,6 @@ export const ko: TranslationResources = {
|
||||
removeConfirmMessage: '"{{name}}"을(를) 제거할까요?',
|
||||
moveUp: "위로 이동",
|
||||
moveDown: "아래로 이동",
|
||||
searchPlaceholder: "프로필 검색",
|
||||
clearSearch: "검색 지우기",
|
||||
noSearchMatches: '"{{query}}"와 일치하는 프로필이 없습니다',
|
||||
noRoutingNote: "메모 없음",
|
||||
duplicate: "복제",
|
||||
copyName: "{{name}} (사본)",
|
||||
moveToTop: "맨 위로 이동",
|
||||
profileActions: "{{name}} 작업",
|
||||
reorderProfile: "{{name}} 순서 변경",
|
||||
previousProfile: "이전 프로필",
|
||||
nextProfile: "다음 프로필",
|
||||
chooseModelPlaceholder: "모델 선택",
|
||||
searchModelsPlaceholder: "모델 검색",
|
||||
chooseModelSubtitle: "모델 선택",
|
||||
customizeSettings: "설정 사용자 지정",
|
||||
addRoutingNoteShort: "메모 추가",
|
||||
providerOptionsLabel: "{{provider}} 옵션",
|
||||
discardTitle: "변경 사항을 버리시겠습니까?",
|
||||
discardMessage: "이 프로필에 저장되지 않은 변경 사항이 있습니다.",
|
||||
discardConfirm: "버리기",
|
||||
columns: {
|
||||
profile: "프로필",
|
||||
runtime: "모델 및 런타임",
|
||||
whenToUse: "사용 시기",
|
||||
},
|
||||
},
|
||||
daemon: {
|
||||
rename: {
|
||||
|
||||
@@ -746,8 +746,6 @@ export const ptBR: TranslationResources = {
|
||||
resumeCommandUnavailable: "Comando de retomada indisponível",
|
||||
reloadingAgent: "Recarregando agente...",
|
||||
reloadedAgent: "Agente recarregado",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"Agente recarregado, mas o histórico do provedor não corresponde a este chat, então não foi sincronizado",
|
||||
failedToReloadAgent: "Falha ao recarregar agente",
|
||||
failedToCloseAgent: "Falha ao fechar agente",
|
||||
},
|
||||
@@ -1817,12 +1815,6 @@ export const ptBR: TranslationResources = {
|
||||
"O app móvel nativo completo permite controlar qualquer computador com Paseo pelo seu celular",
|
||||
appStore: "App Store",
|
||||
googlePlay: "Google Play",
|
||||
connectTitle: "Escolha como se conectar",
|
||||
connectDocs: "Docs",
|
||||
openConnectDocs: "Abrir documentação de conectividade",
|
||||
recommended: "Recomendado",
|
||||
relay: { title: "Relay", hint: "Criptografia de ponta a ponta, escaneie um código QR" },
|
||||
tailscale: { title: "Tailscale", hint: "Requer alguma configuração" },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -1849,9 +1841,6 @@ export const ptBR: TranslationResources = {
|
||||
editProfilesLabel: "Editar perfis de agente",
|
||||
createProfile: "Criar perfil",
|
||||
createProfileFromModel: "Criar perfil a partir deste modelo",
|
||||
profileSaved: 'Salvo "{{name}}"',
|
||||
undo: "Desfazer",
|
||||
undoProfileSave: "Desfazer salvamento do perfil",
|
||||
editProfileLabel: "Editar {{name}}",
|
||||
editProfilesCount: "Editar perfis ({{count}})",
|
||||
modelCount: "{{count}} modelo",
|
||||
@@ -1901,6 +1890,33 @@ export const ptBR: TranslationResources = {
|
||||
hostDisconnected: "Host não está conectado",
|
||||
},
|
||||
},
|
||||
devices: {
|
||||
title: "Dispositivos",
|
||||
waysToConnect: "Formas de conexão",
|
||||
docs: "Docs",
|
||||
docsAccessibility: "Abrir documentação de conectividade",
|
||||
recommended: "Recomendado",
|
||||
relay: { title: "Relay", hint: "Criptografia de ponta a ponta, escaneie um código QR" },
|
||||
tailscale: {
|
||||
hint: "Conexão direta pela sua tailnet, digite um endereço",
|
||||
unavailable: "O Tailscale não está em execução neste host",
|
||||
install: "Baixar o Tailscale",
|
||||
waiting: "Aguardando o Tailscale iniciar neste host",
|
||||
alwaysOn: "Sempre ativado, porque este host já aceita conexões do Tailscale",
|
||||
socket: "Desativado, porque este host escuta em um socket local",
|
||||
launch: "Controlado pelo comando que inicia este host",
|
||||
update: "Atualize este host para usar o Tailscale",
|
||||
updateDocs: "Como atualizar",
|
||||
address: "Em um celular com Tailscale, adicione um host com este endereço",
|
||||
statusError: "Não foi possível verificar o Tailscale",
|
||||
turnOnError: "Não foi possível ativar o Tailscale",
|
||||
turnOffError: "Não foi possível desativar o Tailscale",
|
||||
confirmTitle: "Desativar o Tailscale?",
|
||||
confirmMessage:
|
||||
"Este dispositivo está conectado pelo Tailscale e perderá a conexão com o host.",
|
||||
confirmAction: "Desativar",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "Senha de {{host}}",
|
||||
@@ -2434,7 +2450,6 @@ export const ptBR: TranslationResources = {
|
||||
projects: "Projetos",
|
||||
connections: "Conexões",
|
||||
agents: "Agentes",
|
||||
agentProfiles: "Perfis de agente",
|
||||
metadata: "Metadados",
|
||||
voice: "Voz",
|
||||
workspaces: "Workspaces",
|
||||
@@ -2927,9 +2942,7 @@ export const ptBR: TranslationResources = {
|
||||
timeout: "Timeout",
|
||||
},
|
||||
pairDevices: {
|
||||
title: "Parear dispositivos",
|
||||
rowTitle: "Parear um dispositivo",
|
||||
rowHint: "Escaneie um QR code ou copie um link para conectar seu celular a este host",
|
||||
},
|
||||
skills: {
|
||||
...en.settings.host.skills,
|
||||
@@ -3071,31 +3084,6 @@ export const ptBR: TranslationResources = {
|
||||
removeConfirmMessage: 'Remover "{{name}}"?',
|
||||
moveUp: "Mover para cima",
|
||||
moveDown: "Mover para baixo",
|
||||
searchPlaceholder: "Buscar perfis",
|
||||
clearSearch: "Limpar busca",
|
||||
noSearchMatches: 'Nenhum perfil corresponde a "{{query}}"',
|
||||
noRoutingNote: "Sem nota",
|
||||
duplicate: "Duplicar",
|
||||
copyName: "{{name}} (cópia)",
|
||||
moveToTop: "Mover para o topo",
|
||||
profileActions: "Ações para {{name}}",
|
||||
reorderProfile: "Reordenar {{name}}",
|
||||
previousProfile: "Perfil anterior",
|
||||
nextProfile: "Próximo perfil",
|
||||
chooseModelPlaceholder: "Selecionar um modelo",
|
||||
searchModelsPlaceholder: "Buscar modelos",
|
||||
chooseModelSubtitle: "Selecionar um modelo",
|
||||
customizeSettings: "Personalizar configurações",
|
||||
addRoutingNoteShort: "Adicionar uma nota",
|
||||
providerOptionsLabel: "Opções de {{provider}}",
|
||||
discardTitle: "Descartar alterações?",
|
||||
discardMessage: "Você tem alterações não salvas neste perfil.",
|
||||
discardConfirm: "Descartar",
|
||||
columns: {
|
||||
profile: "Perfil",
|
||||
runtime: "Modelo e execução",
|
||||
whenToUse: "Quando usar",
|
||||
},
|
||||
},
|
||||
daemon: {
|
||||
rename: {
|
||||
|
||||
@@ -749,8 +749,6 @@ export const ru: TranslationResources = {
|
||||
resumeCommandUnavailable: "Команда возобновления недоступна",
|
||||
reloadingAgent: "Перезагрузка агента...",
|
||||
reloadedAgent: "Агент перезагружен",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"Агент перезагружен, но история провайдера не совпадает с этим чатом, поэтому она не синхронизирована",
|
||||
failedToReloadAgent: "Не удалось перезагрузить агента",
|
||||
failedToCloseAgent: "Не удалось закрыть агента",
|
||||
},
|
||||
@@ -1817,12 +1815,6 @@ export const ru: TranslationResources = {
|
||||
"Полнофункциональное нативное мобильное приложение позволяет управлять любым компьютером с Paseo с телефона",
|
||||
appStore: "App Store",
|
||||
googlePlay: "Google Play",
|
||||
connectTitle: "Выберите способ подключения",
|
||||
connectDocs: "Документация",
|
||||
openConnectDocs: "Открыть документацию по подключению",
|
||||
recommended: "Рекомендуется",
|
||||
relay: { title: "Ретранслятор", hint: "Сквозное шифрование, отсканируйте QR-код" },
|
||||
tailscale: { title: "Tailscale", hint: "Требует небольшой настройки" },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -1849,9 +1841,6 @@ export const ru: TranslationResources = {
|
||||
editProfilesLabel: "Изменить профили агентов",
|
||||
createProfile: "Создать профиль",
|
||||
createProfileFromModel: "Создать профиль из этой модели",
|
||||
profileSaved: "Сохранено: «{{name}}»",
|
||||
undo: "Отменить",
|
||||
undoProfileSave: "Отменить сохранение профиля",
|
||||
editProfileLabel: "Изменить {{name}}",
|
||||
editProfilesCount: "Изменить профили ({{count}})",
|
||||
modelCount: "{{count}} модель",
|
||||
@@ -1901,6 +1890,32 @@ export const ru: TranslationResources = {
|
||||
hostDisconnected: "Хост не подключён",
|
||||
},
|
||||
},
|
||||
devices: {
|
||||
title: "Устройства",
|
||||
waysToConnect: "Способы подключения",
|
||||
docs: "Документация",
|
||||
docsAccessibility: "Открыть документацию по подключению",
|
||||
recommended: "Рекомендуется",
|
||||
relay: { title: "Ретранслятор", hint: "Сквозное шифрование, отсканируйте QR-код" },
|
||||
tailscale: {
|
||||
hint: "Прямое подключение через ваш tailnet, по адресу",
|
||||
unavailable: "Tailscale не запущен на этом хосте",
|
||||
install: "Скачать Tailscale",
|
||||
waiting: "Ожидаем запуска Tailscale на этом хосте",
|
||||
alwaysOn: "Всегда включено, так как хост уже принимает подключения Tailscale",
|
||||
socket: "Выключено, так как хост слушает локальный сокет",
|
||||
launch: "Управляется командой, которая запускает этот хост",
|
||||
update: "Обновите этот хост, чтобы использовать Tailscale",
|
||||
updateDocs: "Как обновить",
|
||||
address: "На телефоне с Tailscale добавьте хост с этим адресом",
|
||||
statusError: "Не удалось проверить Tailscale",
|
||||
turnOnError: "Не удалось включить Tailscale",
|
||||
turnOffError: "Не удалось выключить Tailscale",
|
||||
confirmTitle: "Выключить Tailscale?",
|
||||
confirmMessage: "Это устройство подключено через Tailscale и потеряет соединение с хостом.",
|
||||
confirmAction: "Выключить",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "Пароль для {{host}}",
|
||||
@@ -2436,7 +2451,6 @@ export const ru: TranslationResources = {
|
||||
projects: "Проекты",
|
||||
connections: "Подключения",
|
||||
agents: "Агенты",
|
||||
agentProfiles: "Профили агентов",
|
||||
metadata: "Метаданные",
|
||||
voice: "Голос",
|
||||
workspaces: "Рабочие пространства",
|
||||
@@ -2935,10 +2949,7 @@ export const ru: TranslationResources = {
|
||||
timeout: "Время ожидания истекло",
|
||||
},
|
||||
pairDevices: {
|
||||
title: "Подключение устройств",
|
||||
rowTitle: "Подключить устройство",
|
||||
rowHint:
|
||||
"Отсканируйте QR-код или скопируйте ссылку, чтобы подключить телефон к этому хосту.",
|
||||
},
|
||||
skills: {
|
||||
sectionTitle: "Навыки оркестрации",
|
||||
@@ -3082,31 +3093,6 @@ export const ru: TranslationResources = {
|
||||
removeConfirmMessage: "Удалить «{{name}}»?",
|
||||
moveUp: "Переместить вверх",
|
||||
moveDown: "Переместить вниз",
|
||||
searchPlaceholder: "Поиск профилей",
|
||||
clearSearch: "Очистить поиск",
|
||||
noSearchMatches: "Нет профилей по запросу «{{query}}»",
|
||||
noRoutingNote: "Без заметки",
|
||||
duplicate: "Дублировать",
|
||||
copyName: "{{name}} (копия)",
|
||||
moveToTop: "В начало списка",
|
||||
profileActions: "Действия для {{name}}",
|
||||
reorderProfile: "Изменить порядок {{name}}",
|
||||
previousProfile: "Предыдущий профиль",
|
||||
nextProfile: "Следующий профиль",
|
||||
chooseModelPlaceholder: "Выберите модель",
|
||||
searchModelsPlaceholder: "Поиск моделей",
|
||||
chooseModelSubtitle: "Выберите модель",
|
||||
customizeSettings: "Настроить параметры",
|
||||
addRoutingNoteShort: "Добавить заметку",
|
||||
providerOptionsLabel: "Параметры {{provider}}",
|
||||
discardTitle: "Отменить изменения?",
|
||||
discardMessage: "В этом профиле есть несохранённые изменения.",
|
||||
discardConfirm: "Отменить",
|
||||
columns: {
|
||||
profile: "Профиль",
|
||||
runtime: "Модель и запуск",
|
||||
whenToUse: "Когда использовать",
|
||||
},
|
||||
},
|
||||
daemon: {
|
||||
rename: {
|
||||
|
||||
@@ -741,8 +741,6 @@ export const zhCN: TranslationResources = {
|
||||
resumeCommandUnavailable: "恢复命令不可用",
|
||||
reloadingAgent: "正在重新加载 Agent...",
|
||||
reloadedAgent: "已重新加载 Agent",
|
||||
reloadedAgentHistoryDiverged:
|
||||
"已重新加载 Agent,但提供方的历史记录与此对话不一致,因此未同步",
|
||||
failedToReloadAgent: "重新加载 Agent 失败",
|
||||
failedToCloseAgent: "关闭 Agent 失败",
|
||||
},
|
||||
@@ -1766,12 +1764,6 @@ export const zhCN: TranslationResources = {
|
||||
description: "功能完整的原生移动应用让你可以在手机上控制任意一台 Paseo 电脑",
|
||||
appStore: "App Store",
|
||||
googlePlay: "Google Play",
|
||||
connectTitle: "选择连接方式",
|
||||
connectDocs: "文档",
|
||||
openConnectDocs: "打开连接文档",
|
||||
recommended: "推荐",
|
||||
relay: { title: "中继", hint: "端到端加密,扫描二维码" },
|
||||
tailscale: { title: "Tailscale", hint: "需要一些设置" },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -1798,9 +1790,6 @@ export const zhCN: TranslationResources = {
|
||||
editProfilesLabel: "编辑智能体配置文件",
|
||||
createProfile: "创建配置文件",
|
||||
createProfileFromModel: "从此模型创建配置文件",
|
||||
profileSaved: "已保存“{{name}}”",
|
||||
undo: "撤销",
|
||||
undoProfileSave: "撤销保存配置文件",
|
||||
editProfileLabel: "编辑 {{name}}",
|
||||
editProfilesCount: "编辑配置文件 ({{count}})",
|
||||
modelCount: "{{count}} 个模型",
|
||||
@@ -1850,6 +1839,32 @@ export const zhCN: TranslationResources = {
|
||||
hostDisconnected: "Host 未连接",
|
||||
},
|
||||
},
|
||||
devices: {
|
||||
title: "设备",
|
||||
waysToConnect: "连接方式",
|
||||
docs: "文档",
|
||||
docsAccessibility: "打开连接文档",
|
||||
recommended: "推荐",
|
||||
relay: { title: "中继", hint: "端到端加密,扫描二维码" },
|
||||
tailscale: {
|
||||
hint: "通过你的 tailnet 直连,输入地址即可",
|
||||
unavailable: "此主机未运行 Tailscale",
|
||||
install: "获取 Tailscale",
|
||||
waiting: "正在等待此主机上的 Tailscale 启动",
|
||||
alwaysOn: "始终开启,因为此主机已接受 Tailscale 连接",
|
||||
socket: "已关闭,因为此主机监听的是本地套接字",
|
||||
launch: "由启动此主机的命令控制",
|
||||
update: "更新此主机以使用 Tailscale",
|
||||
updateDocs: "如何更新",
|
||||
address: "在已连接 Tailscale 的手机上,用此地址添加主机",
|
||||
statusError: "无法检查 Tailscale",
|
||||
turnOnError: "无法开启 Tailscale",
|
||||
turnOffError: "无法关闭 Tailscale",
|
||||
confirmTitle: "关闭 Tailscale?",
|
||||
confirmMessage: "此设备通过 Tailscale 连接,关闭后将与主机断开连接。",
|
||||
confirmAction: "关闭",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "{{host}} 的密码",
|
||||
@@ -2376,7 +2391,6 @@ export const zhCN: TranslationResources = {
|
||||
projects: "项目",
|
||||
connections: "连接",
|
||||
agents: "Agents",
|
||||
agentProfiles: "智能体配置文件",
|
||||
metadata: "元数据",
|
||||
voice: "语音",
|
||||
workspaces: "Workspaces",
|
||||
@@ -2856,9 +2870,7 @@ export const zhCN: TranslationResources = {
|
||||
timeout: "超时",
|
||||
},
|
||||
pairDevices: {
|
||||
title: "配对设备",
|
||||
rowTitle: "配对设备",
|
||||
rowHint: "扫描二维码或复制链接,将手机连接到这个 Host",
|
||||
},
|
||||
skills: {
|
||||
...en.settings.host.skills,
|
||||
@@ -2997,31 +3009,6 @@ export const zhCN: TranslationResources = {
|
||||
removeConfirmMessage: "移除「{{name}}」?",
|
||||
moveUp: "上移",
|
||||
moveDown: "下移",
|
||||
searchPlaceholder: "搜索配置文件",
|
||||
clearSearch: "清除搜索",
|
||||
noSearchMatches: "没有匹配“{{query}}”的配置文件",
|
||||
noRoutingNote: "无说明",
|
||||
duplicate: "复制",
|
||||
copyName: "{{name}}(副本)",
|
||||
moveToTop: "移至顶部",
|
||||
profileActions: "{{name}} 的操作",
|
||||
reorderProfile: "调整 {{name}} 顺序",
|
||||
previousProfile: "上一个配置文件",
|
||||
nextProfile: "下一个配置文件",
|
||||
chooseModelPlaceholder: "选择模型",
|
||||
searchModelsPlaceholder: "搜索模型",
|
||||
chooseModelSubtitle: "选择模型",
|
||||
customizeSettings: "自定义设置",
|
||||
addRoutingNoteShort: "添加说明",
|
||||
providerOptionsLabel: "{{provider}} 选项",
|
||||
discardTitle: "放弃更改?",
|
||||
discardMessage: "此配置文件有未保存的更改。",
|
||||
discardConfirm: "放弃",
|
||||
columns: {
|
||||
profile: "配置文件",
|
||||
runtime: "模型与运行时",
|
||||
whenToUse: "适用场景",
|
||||
},
|
||||
},
|
||||
daemon: {
|
||||
rename: {
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
export interface RouteLeaveGuard {
|
||||
isDirty: () => boolean;
|
||||
confirmDiscard: () => Promise<boolean>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Installs the web browser history (`popstate`) guard before Expo Router mounts
|
||||
* its own `popstate` listener. No-op on native, where React Navigation's
|
||||
* `beforeRemove` owns swipe-back and hardware Back interception.
|
||||
*/
|
||||
export function installRouteLeavePopStateGuard(): void {
|
||||
// Native platforms handle back navigation through React Navigation's beforeRemove event.
|
||||
}
|
||||
|
||||
/** Registers the active screen's leave guard for browser Back/Forward interception. */
|
||||
export function registerRouteLeaveGuard(_guard: RouteLeaveGuard | null): () => void {
|
||||
return () => {};
|
||||
}
|
||||
@@ -1,268 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
createWebPopStateGuard,
|
||||
type PopStateStorageLike,
|
||||
type PopStateWindowLike,
|
||||
} from "./index.web";
|
||||
|
||||
interface FakeHistoryEntry {
|
||||
state: unknown;
|
||||
path: string;
|
||||
}
|
||||
|
||||
function createMemoryStorage(): PopStateStorageLike {
|
||||
const store = new Map<string, string>();
|
||||
return {
|
||||
getItem: (key) => store.get(key) ?? null,
|
||||
setItem: (key, value) => {
|
||||
store.set(key, value);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function createFakeWindow(
|
||||
initialEntries: FakeHistoryEntry[],
|
||||
options?: { index?: number; sessionStorage?: PopStateStorageLike },
|
||||
) {
|
||||
let entries: FakeHistoryEntry[] = [...initialEntries];
|
||||
let index = options?.index ?? entries.length - 1;
|
||||
const listeners: Array<(event: PopStateEvent) => void> = [];
|
||||
|
||||
const current = () => entries[index] ?? { state: null, path: "/" };
|
||||
|
||||
const dispatchPopState = (state: unknown) => {
|
||||
let stopped = false;
|
||||
const event = {
|
||||
state,
|
||||
stopImmediatePropagation() {
|
||||
stopped = true;
|
||||
},
|
||||
} as unknown as PopStateEvent;
|
||||
for (const listener of listeners.slice()) {
|
||||
if (stopped) {
|
||||
break;
|
||||
}
|
||||
listener(event);
|
||||
}
|
||||
return { stopped };
|
||||
};
|
||||
|
||||
const win: PopStateWindowLike = {
|
||||
...(options?.sessionStorage ? { sessionStorage: options.sessionStorage } : {}),
|
||||
history: {
|
||||
get state() {
|
||||
return current().state;
|
||||
},
|
||||
pushState(state, _unused, url) {
|
||||
const path = typeof url === "string" ? url : String(url ?? "/");
|
||||
entries = entries.slice(0, index + 1);
|
||||
entries.push({ state, path });
|
||||
index = entries.length - 1;
|
||||
},
|
||||
replaceState(state, _unused, url) {
|
||||
const path = typeof url === "string" ? url : String(url ?? "/");
|
||||
entries[index] = { state, path };
|
||||
},
|
||||
go(delta = 0) {
|
||||
const nextIndex = index + delta;
|
||||
if (nextIndex < 0 || nextIndex >= entries.length || nextIndex === index) {
|
||||
return;
|
||||
}
|
||||
index = nextIndex;
|
||||
dispatchPopState(current().state);
|
||||
},
|
||||
},
|
||||
addEventListener(_type, listener) {
|
||||
listeners.push(listener);
|
||||
},
|
||||
removeEventListener(_type, listener) {
|
||||
const idx = listeners.indexOf(listener);
|
||||
if (idx >= 0) {
|
||||
listeners.splice(idx, 1);
|
||||
}
|
||||
},
|
||||
dispatchEvent(event) {
|
||||
const popEvent = event as PopStateEvent;
|
||||
dispatchPopState(popEvent.state);
|
||||
return true;
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
win,
|
||||
getPath: () => current().path,
|
||||
getEntries: () => entries.map((entry) => entry.path),
|
||||
getIndex: () => index,
|
||||
simulateHistoryJump: (delta: number) => {
|
||||
const nextIndex = index + delta;
|
||||
index = Math.max(0, Math.min(entries.length - 1, nextIndex));
|
||||
return dispatchPopState(current().state);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("createWebPopStateGuard", () => {
|
||||
it("preserves intervening history entries when canceling a two-step Back jump", async () => {
|
||||
const fake = createFakeWindow([{ state: { id: "id-0" }, path: "/open-project" }], {
|
||||
sessionStorage: createMemoryStorage(),
|
||||
});
|
||||
const guard = createWebPopStateGuard(fake.win);
|
||||
guard.install();
|
||||
|
||||
const routerSeenPaths: string[] = [];
|
||||
fake.win.addEventListener("popstate", () => {
|
||||
routerSeenPaths.push(fake.getPath());
|
||||
});
|
||||
|
||||
fake.win.history.pushState({ id: "id-1" }, "", "/settings");
|
||||
fake.win.history.pushState({ id: "id-2" }, "", "/settings/hosts/srv/agent-profiles");
|
||||
|
||||
let dirty = true;
|
||||
guard.register({
|
||||
isDirty: () => dirty,
|
||||
confirmDiscard: async () => false,
|
||||
});
|
||||
|
||||
// Jump straight from Agent profiles back two entries to Open project and cancel.
|
||||
const { stopped } = fake.simulateHistoryJump(-2);
|
||||
await Promise.resolve();
|
||||
|
||||
expect(stopped).toBe(true);
|
||||
expect(routerSeenPaths).toEqual([]);
|
||||
expect(fake.getPath()).toBe("/settings/hosts/srv/agent-profiles");
|
||||
expect(fake.getEntries()).toEqual([
|
||||
"/open-project",
|
||||
"/settings",
|
||||
"/settings/hosts/srv/agent-profiles",
|
||||
]);
|
||||
expect(fake.getIndex()).toBe(2);
|
||||
|
||||
// After closing the editor, a normal one-step Back still reaches Settings.
|
||||
dirty = false;
|
||||
fake.simulateHistoryJump(-1);
|
||||
expect(fake.getPath()).toBe("/settings");
|
||||
expect(routerSeenPaths).toEqual(["/settings"]);
|
||||
});
|
||||
|
||||
it("restores the editor URL on a two-step Back jump after a reload (with sessionStorage)", async () => {
|
||||
const storage = createMemoryStorage();
|
||||
const beforeReload = createFakeWindow([{ state: { id: "id-0" }, path: "/open-project" }], {
|
||||
sessionStorage: storage,
|
||||
});
|
||||
const firstGuard = createWebPopStateGuard(beforeReload.win);
|
||||
firstGuard.install();
|
||||
beforeReload.win.history.pushState({ id: "id-1" }, "", "/settings");
|
||||
beforeReload.win.history.pushState({ id: "id-2" }, "", "/settings/hosts/srv/agent-profiles");
|
||||
firstGuard.dispose();
|
||||
|
||||
// Simulate reload on Agent profiles with the same browser history and tab sessionStorage.
|
||||
const afterReload = createFakeWindow(
|
||||
[
|
||||
{ state: { id: "id-0" }, path: "/open-project" },
|
||||
{ state: { id: "id-1" }, path: "/settings" },
|
||||
{ state: { id: "id-2" }, path: "/settings/hosts/srv/agent-profiles" },
|
||||
],
|
||||
{ index: 2, sessionStorage: storage },
|
||||
);
|
||||
const guard = createWebPopStateGuard(afterReload.win);
|
||||
guard.install();
|
||||
guard.register({
|
||||
isDirty: () => true,
|
||||
confirmDiscard: async () => false,
|
||||
});
|
||||
|
||||
afterReload.simulateHistoryJump(-2);
|
||||
await Promise.resolve();
|
||||
|
||||
expect(afterReload.getPath()).toBe("/settings/hosts/srv/agent-profiles");
|
||||
expect(afterReload.getIndex()).toBe(2);
|
||||
});
|
||||
|
||||
it("steps back to the exact editor entry after a reload even without sessionStorage", async () => {
|
||||
const afterReload = createFakeWindow(
|
||||
[
|
||||
{ state: { id: "id-0" }, path: "/open-project" },
|
||||
{ state: { id: "id-1" }, path: "/settings" },
|
||||
{ state: { id: "id-2" }, path: "/settings/hosts/srv/agent-profiles" },
|
||||
],
|
||||
{ index: 2 },
|
||||
);
|
||||
const guard = createWebPopStateGuard(afterReload.win);
|
||||
guard.install();
|
||||
|
||||
const routerSeenPaths: string[] = [];
|
||||
afterReload.win.addEventListener("popstate", () => {
|
||||
routerSeenPaths.push(afterReload.getPath());
|
||||
});
|
||||
|
||||
guard.register({
|
||||
isDirty: () => true,
|
||||
confirmDiscard: async () => false,
|
||||
});
|
||||
|
||||
afterReload.simulateHistoryJump(-2);
|
||||
await Promise.resolve();
|
||||
|
||||
expect(routerSeenPaths).toEqual([]);
|
||||
expect(afterReload.getPath()).toBe("/settings/hosts/srv/agent-profiles");
|
||||
expect(afterReload.getIndex()).toBe(2);
|
||||
});
|
||||
|
||||
it("reaches the exact two-step destination when confirming a multi-step Back jump", async () => {
|
||||
const fake = createFakeWindow([{ state: { id: "id-0" }, path: "/open-project" }], {
|
||||
sessionStorage: createMemoryStorage(),
|
||||
});
|
||||
const guard = createWebPopStateGuard(fake.win);
|
||||
guard.install();
|
||||
|
||||
const routerSeenPaths: string[] = [];
|
||||
fake.win.addEventListener("popstate", () => {
|
||||
routerSeenPaths.push(fake.getPath());
|
||||
});
|
||||
|
||||
fake.win.history.pushState({ id: "id-1" }, "", "/settings");
|
||||
fake.win.history.pushState({ id: "id-2" }, "", "/settings/hosts/srv/agent-profiles");
|
||||
|
||||
let dirty = true;
|
||||
guard.register({
|
||||
isDirty: () => dirty,
|
||||
confirmDiscard: async () => {
|
||||
dirty = false;
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
fake.simulateHistoryJump(-2);
|
||||
await Promise.resolve();
|
||||
|
||||
expect(routerSeenPaths).toEqual(["/open-project"]);
|
||||
expect(fake.getPath()).toBe("/open-project");
|
||||
expect(fake.getIndex()).toBe(0);
|
||||
});
|
||||
|
||||
it("passes browser Back straight through when the guard is not dirty", () => {
|
||||
const fake = createFakeWindow([{ state: { id: "id-0" }, path: "/open-project" }]);
|
||||
const guard = createWebPopStateGuard(fake.win);
|
||||
guard.install();
|
||||
|
||||
let routerSawPopState = 0;
|
||||
fake.win.addEventListener("popstate", () => {
|
||||
routerSawPopState += 1;
|
||||
});
|
||||
|
||||
fake.win.history.pushState({ id: "id-1" }, "", "/settings/hosts/srv/agent-profiles");
|
||||
|
||||
guard.register({
|
||||
isDirty: () => false,
|
||||
confirmDiscard: async () => {
|
||||
throw new Error("should not prompt when clean");
|
||||
},
|
||||
});
|
||||
|
||||
const { stopped } = fake.simulateHistoryJump(-1);
|
||||
|
||||
expect(stopped).toBe(false);
|
||||
expect(routerSawPopState).toBe(1);
|
||||
expect(fake.getPath()).toBe("/open-project");
|
||||
});
|
||||
});
|
||||
@@ -1,307 +0,0 @@
|
||||
import type { RouteLeaveGuard } from "./index";
|
||||
|
||||
export type { RouteLeaveGuard } from "./index";
|
||||
|
||||
const HISTORY_STORAGE_KEY = "@paseo:route-leave-history:v1";
|
||||
const MAX_REVERT_STEPS = 20;
|
||||
const REVERT_TIMEOUT_MS = 400;
|
||||
|
||||
export interface PopStateStorageLike {
|
||||
getItem(key: string): string | null;
|
||||
setItem(key: string, value: string): void;
|
||||
}
|
||||
|
||||
export interface PopStateWindowLike {
|
||||
history: {
|
||||
readonly state: unknown;
|
||||
pushState(data: unknown, unused: string, url?: string | URL | null): void;
|
||||
replaceState(data: unknown, unused: string, url?: string | URL | null): void;
|
||||
go(delta?: number): void;
|
||||
};
|
||||
sessionStorage?: PopStateStorageLike;
|
||||
addEventListener(type: "popstate", listener: (event: PopStateEvent) => void): void;
|
||||
removeEventListener(type: "popstate", listener: (event: PopStateEvent) => void): void;
|
||||
dispatchEvent(event: Event): boolean;
|
||||
}
|
||||
|
||||
export interface WebPopStateGuardController {
|
||||
install(): void;
|
||||
register(guard: RouteLeaveGuard | null): () => void;
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
function readHistoryStateId(state: unknown): string | null {
|
||||
if (typeof state === "object" && state !== null && "id" in state) {
|
||||
const id = (state as { id?: unknown }).id;
|
||||
return typeof id === "string" && id.length > 0 ? id : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function createPopStateEvent(state: unknown): PopStateEvent {
|
||||
if (typeof PopStateEvent === "function") {
|
||||
return new PopStateEvent("popstate", { state });
|
||||
}
|
||||
const event = new Event("popstate") as PopStateEvent;
|
||||
Object.defineProperty(event, "state", { value: state });
|
||||
return event;
|
||||
}
|
||||
|
||||
function loadStoredEntryIds(storage: PopStateStorageLike | undefined): Array<string | null> | null {
|
||||
if (!storage) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const raw = storage.getItem(HISTORY_STORAGE_KEY);
|
||||
if (!raw) {
|
||||
return null;
|
||||
}
|
||||
const parsed: unknown = JSON.parse(raw);
|
||||
if (!Array.isArray(parsed)) {
|
||||
return null;
|
||||
}
|
||||
if (!parsed.every((item) => item === null || typeof item === "string")) {
|
||||
return null;
|
||||
}
|
||||
return parsed as Array<string | null>;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function persistEntryIds(
|
||||
storage: PopStateStorageLike | undefined,
|
||||
entryIds: readonly (string | null)[],
|
||||
): void {
|
||||
if (!storage) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
storage.setItem(HISTORY_STORAGE_KEY, JSON.stringify(entryIds));
|
||||
} catch {
|
||||
// Ignore storage quota or private-mode restrictions; fallback stepping still works.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Intercepts browser Back/Forward (`popstate`) before Expo Router's
|
||||
* `createMemoryHistory` listener runs.
|
||||
*
|
||||
* Tracks the ordered history entry IDs written by Expo Router (persisted in
|
||||
* `sessionStorage` so reloads keep the tab's full index). Canceling any
|
||||
* traversal reverts via `history.go(delta)` without calling `pushState` or
|
||||
* truncating intervening entries — and verifies it landed back on the saved
|
||||
* entry ID (stepping forward if pre-reload history was unknown). Confirming
|
||||
* replays `popstate` at the browser's exact selected destination.
|
||||
*/
|
||||
export function createWebPopStateGuard(win: PopStateWindowLike): WebPopStateGuardController {
|
||||
let installed = false;
|
||||
let activeGuard: RouteLeaveGuard | null = null;
|
||||
let confirmInFlight = false;
|
||||
let isReverting = false;
|
||||
let revertingTargetId: string | null = null;
|
||||
let revertStepDirection: 1 | -1 = 1;
|
||||
let revertStepsRemaining = 0;
|
||||
let isReplaying = false;
|
||||
let revertResetTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let entryIds: Array<string | null> = [];
|
||||
let currentIdx = 0;
|
||||
|
||||
let origPushState: PopStateWindowLike["history"]["pushState"] | null = null;
|
||||
let origReplaceState: PopStateWindowLike["history"]["replaceState"] | null = null;
|
||||
|
||||
const clearRevertState = () => {
|
||||
isReverting = false;
|
||||
revertingTargetId = null;
|
||||
revertStepsRemaining = 0;
|
||||
if (revertResetTimer !== null) {
|
||||
clearTimeout(revertResetTimer);
|
||||
revertResetTimer = null;
|
||||
}
|
||||
};
|
||||
|
||||
const armRevertTimer = () => {
|
||||
if (revertResetTimer !== null) {
|
||||
clearTimeout(revertResetTimer);
|
||||
}
|
||||
revertResetTimer = setTimeout(() => {
|
||||
clearRevertState();
|
||||
}, REVERT_TIMEOUT_MS);
|
||||
};
|
||||
|
||||
const revertToSavedEntry = (savedId: string | null, returnDelta: number) => {
|
||||
isReverting = true;
|
||||
revertingTargetId = savedId;
|
||||
revertStepDirection = returnDelta >= 0 ? 1 : -1;
|
||||
revertStepsRemaining = MAX_REVERT_STEPS;
|
||||
armRevertTimer();
|
||||
win.history.go(returnDelta);
|
||||
};
|
||||
|
||||
const resolveTargetIndex = (state: unknown): number => {
|
||||
const targetId = readHistoryStateId(state);
|
||||
if (!targetId) {
|
||||
return -1;
|
||||
}
|
||||
return entryIds.indexOf(targetId);
|
||||
};
|
||||
|
||||
const handleRevertPopState = (event: PopStateEvent) => {
|
||||
event.stopImmediatePropagation();
|
||||
const landedId = readHistoryStateId(event.state);
|
||||
if (revertingTargetId !== null && landedId !== revertingTargetId && revertStepsRemaining > 0) {
|
||||
revertStepsRemaining -= 1;
|
||||
armRevertTimer();
|
||||
win.history.go(revertStepDirection);
|
||||
return;
|
||||
}
|
||||
const landedIdx = resolveTargetIndex(event.state);
|
||||
if (landedIdx >= 0) {
|
||||
currentIdx = landedIdx;
|
||||
}
|
||||
clearRevertState();
|
||||
};
|
||||
|
||||
const handlePopState = (event: PopStateEvent) => {
|
||||
if (isReverting) {
|
||||
handleRevertPopState(event);
|
||||
return;
|
||||
}
|
||||
|
||||
const targetIdx = resolveTargetIndex(event.state);
|
||||
|
||||
if (isReplaying) {
|
||||
isReplaying = false;
|
||||
if (targetIdx >= 0) {
|
||||
currentIdx = targetIdx;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const guard = activeGuard;
|
||||
if (!guard?.isDirty()) {
|
||||
if (targetIdx >= 0) {
|
||||
currentIdx = targetIdx;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
event.stopImmediatePropagation();
|
||||
const savedId = entryIds[currentIdx] ?? null;
|
||||
const returnDelta = targetIdx >= 0 ? currentIdx - targetIdx : 1;
|
||||
|
||||
if (confirmInFlight) {
|
||||
if (returnDelta !== 0) {
|
||||
revertToSavedEntry(savedId, returnDelta);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
confirmInFlight = true;
|
||||
const confirmAndResolve = async () => {
|
||||
try {
|
||||
const confirmed = await guard.confirmDiscard();
|
||||
if (confirmed) {
|
||||
isReplaying = true;
|
||||
win.dispatchEvent(createPopStateEvent(event.state));
|
||||
} else if (returnDelta !== 0) {
|
||||
revertToSavedEntry(savedId, returnDelta);
|
||||
}
|
||||
} finally {
|
||||
confirmInFlight = false;
|
||||
}
|
||||
};
|
||||
void confirmAndResolve();
|
||||
};
|
||||
|
||||
return {
|
||||
install() {
|
||||
if (installed) {
|
||||
return;
|
||||
}
|
||||
installed = true;
|
||||
const initialId = readHistoryStateId(win.history.state);
|
||||
const stored = loadStoredEntryIds(win.sessionStorage);
|
||||
const storedIdx = stored && initialId ? stored.indexOf(initialId) : -1;
|
||||
if (stored && storedIdx >= 0) {
|
||||
entryIds = stored;
|
||||
currentIdx = storedIdx;
|
||||
} else {
|
||||
entryIds = [initialId];
|
||||
currentIdx = 0;
|
||||
persistEntryIds(win.sessionStorage, entryIds);
|
||||
}
|
||||
|
||||
origPushState = win.history.pushState;
|
||||
origReplaceState = win.history.replaceState;
|
||||
|
||||
win.history.pushState = (data, unused, url) => {
|
||||
origPushState?.call(win.history, data, unused, url);
|
||||
entryIds = entryIds.slice(0, currentIdx + 1);
|
||||
entryIds.push(readHistoryStateId(data));
|
||||
currentIdx = entryIds.length - 1;
|
||||
persistEntryIds(win.sessionStorage, entryIds);
|
||||
};
|
||||
|
||||
win.history.replaceState = (data, unused, url) => {
|
||||
origReplaceState?.call(win.history, data, unused, url);
|
||||
entryIds[currentIdx] = readHistoryStateId(data);
|
||||
persistEntryIds(win.sessionStorage, entryIds);
|
||||
};
|
||||
|
||||
win.addEventListener("popstate", handlePopState);
|
||||
},
|
||||
register(guard) {
|
||||
activeGuard = guard;
|
||||
return () => {
|
||||
if (activeGuard === guard) {
|
||||
activeGuard = null;
|
||||
}
|
||||
};
|
||||
},
|
||||
dispose() {
|
||||
if (!installed) {
|
||||
return;
|
||||
}
|
||||
installed = false;
|
||||
activeGuard = null;
|
||||
confirmInFlight = false;
|
||||
isReplaying = false;
|
||||
clearRevertState();
|
||||
win.removeEventListener("popstate", handlePopState);
|
||||
if (origPushState) {
|
||||
win.history.pushState = origPushState;
|
||||
origPushState = null;
|
||||
}
|
||||
if (origReplaceState) {
|
||||
win.history.replaceState = origReplaceState;
|
||||
origReplaceState = null;
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
let sharedController: WebPopStateGuardController | null = null;
|
||||
|
||||
function getSharedController(): WebPopStateGuardController | null {
|
||||
if (typeof window === "undefined") {
|
||||
return null;
|
||||
}
|
||||
if (!sharedController) {
|
||||
sharedController = createWebPopStateGuard(window);
|
||||
}
|
||||
return sharedController;
|
||||
}
|
||||
|
||||
export function installRouteLeavePopStateGuard(): void {
|
||||
getSharedController()?.install();
|
||||
}
|
||||
|
||||
export function registerRouteLeaveGuard(guard: RouteLeaveGuard | null): () => void {
|
||||
const controller = getSharedController();
|
||||
if (!controller) {
|
||||
return () => {};
|
||||
}
|
||||
controller.install();
|
||||
return controller.register(guard);
|
||||
}
|
||||
@@ -1,17 +1,11 @@
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { useCallback } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { View } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { AppleIcon } from "@/components/icons/apple-icon";
|
||||
import { GooglePlayIcon } from "@/components/icons/google-play-icon";
|
||||
import { SettingsCard, SettingsDetailRow, SettingsSection } from "@/components/settings";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { StatusBadge } from "@/components/ui/status-badge";
|
||||
import { PairDeviceModal } from "@/desktop/components/pair-device-modal";
|
||||
import {
|
||||
CONNECTIVITY_DOCS_URL,
|
||||
TAILSCALE_DOCS_URL,
|
||||
} from "@/desktop/components/pair-device-section";
|
||||
import { WaysToConnect } from "@/devices";
|
||||
import { ICON_SIZE } from "@/styles/theme";
|
||||
import { openExternalUrl } from "@/utils/open-external-url";
|
||||
|
||||
@@ -26,33 +20,11 @@ function openUrl(url: string) {
|
||||
void openExternalUrl(url).catch(console.error);
|
||||
}
|
||||
|
||||
/** Get the app, then connect it: the relay pairs in a modal, Tailscale is a docs page away. */
|
||||
/** Get the app, then connect it the same ways the host's Devices settings offer. */
|
||||
export function PhoneStep({ serverId }: { serverId: string }) {
|
||||
const { t } = useTranslation();
|
||||
const [isPairing, setIsPairing] = useState(false);
|
||||
const openAppStore = useCallback(() => openUrl(APP_STORE_URL), []);
|
||||
const openPlayStore = useCallback(() => openUrl(PLAY_STORE_URL), []);
|
||||
const openTailscaleDocs = useCallback(() => openUrl(TAILSCALE_DOCS_URL), []);
|
||||
const openPairing = useCallback(() => setIsPairing(true), []);
|
||||
const closePairing = useCallback(() => setIsPairing(false), []);
|
||||
const recommendedBadge = useMemo(
|
||||
() => (
|
||||
<StatusBadge
|
||||
size="xs"
|
||||
variant="success"
|
||||
label={t("onboarding.setup.steps.phone.recommended")}
|
||||
/>
|
||||
),
|
||||
[t],
|
||||
);
|
||||
const docsLink = useMemo(
|
||||
() => ({
|
||||
href: CONNECTIVITY_DOCS_URL,
|
||||
label: t("onboarding.setup.steps.phone.connectDocs"),
|
||||
accessibilityLabel: t("onboarding.setup.steps.phone.openConnectDocs"),
|
||||
}),
|
||||
[t],
|
||||
);
|
||||
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
@@ -64,31 +36,7 @@ export function PhoneStep({ serverId }: { serverId: string }) {
|
||||
{t("onboarding.setup.steps.phone.googlePlay")}
|
||||
</Button>
|
||||
</View>
|
||||
<SettingsSection title={t("onboarding.setup.steps.phone.connectTitle")} link={docsLink}>
|
||||
<SettingsCard>
|
||||
<SettingsDetailRow
|
||||
label={t("onboarding.setup.steps.phone.relay.title")}
|
||||
labelAccessory={recommendedBadge}
|
||||
hint={t("onboarding.setup.steps.phone.relay.hint")}
|
||||
onPress={openPairing}
|
||||
testID="onboarding-phone-relay"
|
||||
/>
|
||||
<SettingsDetailRow
|
||||
label={t("onboarding.setup.steps.phone.tailscale.title")}
|
||||
hint={t("onboarding.setup.steps.phone.tailscale.hint")}
|
||||
summary={t("onboarding.setup.steps.phone.connectDocs")}
|
||||
onPress={openTailscaleDocs}
|
||||
external
|
||||
testID="onboarding-phone-tailscale"
|
||||
/>
|
||||
</SettingsCard>
|
||||
</SettingsSection>
|
||||
<PairDeviceModal
|
||||
serverId={serverId}
|
||||
visible={isPairing}
|
||||
onClose={closePairing}
|
||||
testID="onboarding-pair-device-card"
|
||||
/>
|
||||
<WaysToConnect serverId={serverId} />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user