mirror of
https://github.com/getpaseo/paseo.git
synced 2026-12-01 04:36:26 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
555391d8b5 | ||
|
|
08298dcc10 | ||
|
|
cafb42560c | ||
|
|
6655aa77b3 | ||
|
|
291d54fa71 | ||
|
|
ddb15230b3 | ||
|
|
9dc533fcd2 | ||
|
|
0ee4a57981 | ||
|
|
aa957c9ca9 | ||
|
|
a96a4d61f1 | ||
|
|
6916ceee47 | ||
|
|
635df88fa6 | ||
|
|
552690e45c | ||
|
|
9815d68f3b | ||
|
|
59377767c7 | ||
|
|
67612b36f3 | ||
|
|
01227a73a4 | ||
|
|
12a6f07939 | ||
|
|
34d38a82d2 | ||
|
|
d71d9b37c6 | ||
|
|
eae885fba4 | ||
|
|
6ec8941943 | ||
|
|
dbeb181f03 |
@@ -1,6 +1,6 @@
|
||||
# Pull-request checks are routed by the behavior they prove. Package consumers
|
||||
# do not inherit their dependencies' test suites; main and manual runs execute
|
||||
# every contract regardless of these paths.
|
||||
# do not inherit their dependencies' test suites, except where noted below; main
|
||||
# and manual runs execute every contract regardless of these paths.
|
||||
routing:
|
||||
- ".github/ci-paths.yml"
|
||||
|
||||
@@ -87,5 +87,9 @@ browser:
|
||||
relay:
|
||||
- "packages/relay/**"
|
||||
|
||||
# cli-tests is also a daemon end-to-end suite: it drives a real daemon, built-in
|
||||
# plugins included, so daemon changes run it too.
|
||||
cli:
|
||||
- "packages/cli/**"
|
||||
- "packages/server/**"
|
||||
- "plugins/**"
|
||||
|
||||
@@ -8,13 +8,14 @@ on:
|
||||
merge_group:
|
||||
workflow_dispatch:
|
||||
|
||||
# A newer push to the same ref cancels the run still in progress, main included.
|
||||
# A full run costs about 200 runner-minutes against the org's 20 concurrent
|
||||
# jobs, and a superseded main run only answers a question the newer commit
|
||||
# answers again.
|
||||
# A newer push cancels the run still in progress on every ref except main,
|
||||
# because a full run costs about 200 runner-minutes against the org's 20
|
||||
# concurrent jobs. A main run finishes: cancelling it mid-flight leaves CANCELLED
|
||||
# checks that paint the commit red. Each ref has one run in progress and one
|
||||
# pending, so a newer push replaces a pending main run before it starts any job.
|
||||
concurrency:
|
||||
group: ci-${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
|
||||
|
||||
env:
|
||||
# CI does not use the CUDA execution provider, and the onnxruntime-node
|
||||
@@ -174,6 +175,9 @@ jobs:
|
||||
- name: Verify dependency patch recovery
|
||||
run: node --test scripts/postinstall-patches.test.mjs
|
||||
|
||||
- name: Verify daemon runtime trace contract
|
||||
run: node --test scripts/trace-daemon.test.mjs
|
||||
|
||||
- name: Build server stack
|
||||
run: npm run build:server
|
||||
|
||||
@@ -213,6 +217,15 @@ jobs:
|
||||
- name: Verify website mockups
|
||||
run: npm run test:e2e --workspace=@getpaseo/website
|
||||
|
||||
- name: Upload website test artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
if: failure()
|
||||
with:
|
||||
name: website-playwright-results
|
||||
path: packages/website/test-results/
|
||||
if-no-files-found: ignore
|
||||
retention-days: 7
|
||||
|
||||
- name: Verify public package contents
|
||||
run: |
|
||||
npm pack --dry-run --ignore-scripts --workspace=@getpaseo/protocol
|
||||
|
||||
@@ -13,9 +13,11 @@ on:
|
||||
- ".github/workflows/desktop-packages.yml"
|
||||
workflow_dispatch:
|
||||
|
||||
# A main run finishes. A run cancelled mid-flight leaves CANCELLED checks that
|
||||
# paint the commit red.
|
||||
concurrency:
|
||||
group: desktop-packages-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
@@ -28,9 +28,11 @@ on:
|
||||
- "false"
|
||||
- "true"
|
||||
|
||||
# main, tag and publish runs finish. A run cancelled mid-flight leaves CANCELLED
|
||||
# checks that paint a main commit red.
|
||||
concurrency:
|
||||
group: docker-${{ github.workflow }}-${{ github.event_name == 'workflow_dispatch' && inputs.publish == 'true' && format('publish-{0}', inputs.paseo_version || github.run_id) || github.ref }}
|
||||
cancel-in-progress: ${{ !startsWith(github.ref, 'refs/tags/') && !(github.event_name == 'workflow_dispatch' && inputs.publish == 'true') }}
|
||||
cancel-in-progress: ${{ github.ref != 'refs/heads/main' && !startsWith(github.ref, 'refs/tags/') && !(github.event_name == 'workflow_dispatch' && inputs.publish == 'true') }}
|
||||
|
||||
env:
|
||||
REGISTRY: ghcr.io
|
||||
|
||||
@@ -3,8 +3,37 @@ name: Nix
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
# Prove the real Nix package and daemon smoke before merge when Nix, CLI,
|
||||
# server, or daemon packaging inputs change.
|
||||
pull_request:
|
||||
paths:
|
||||
- "nix/**"
|
||||
- "flake.nix"
|
||||
- "flake.lock"
|
||||
- "package.json"
|
||||
- "package-lock.json"
|
||||
- "packages/protocol/**"
|
||||
- "packages/client/**"
|
||||
- "packages/highlight/**"
|
||||
- "packages/plugin/**"
|
||||
- "packages/server/**"
|
||||
- "packages/relay/**"
|
||||
- "packages/cli/**"
|
||||
- "packages/desktop/**"
|
||||
- "plugins/**"
|
||||
- "skills/**"
|
||||
- "scripts/trace-daemon.mjs"
|
||||
- "scripts/is-main-module.mjs"
|
||||
- "scripts/build-daemon-web-ui.mjs"
|
||||
- "scripts/update-nix.sh"
|
||||
- "scripts/fix-lockfile.mjs"
|
||||
- ".github/workflows/nix.yml"
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: nix-${{ github.ref }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
@@ -102,6 +131,7 @@ jobs:
|
||||
run: nix build .#desktop -o result-desktop
|
||||
|
||||
build-desktop-darwin:
|
||||
if: ${{ github.event_name != 'pull_request' }}
|
||||
runs-on: macos-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
+18
-11
@@ -198,17 +198,24 @@ outstanding intent. A crash after successful dispatch but before removal commits
|
||||
notification. Clean shutdown can also flush an already queued callback while retaining its intent,
|
||||
so that callback can repeat after restart. This is an at-least-once wakeup, without turn attribution or exactly-once delivery.
|
||||
|
||||
A turn end is not always a settled child. When the child ends its turn with work that will start its
|
||||
next turn by itself, the caller gets one `message` notice ("ended its turn but is still working") and
|
||||
the subscription keeps following the child. That work is a running turn, queued messages, a pending
|
||||
provider wake-up (`AgentSession.hasPendingWakeup`: Claude background tasks, task notifications, and
|
||||
one-shot wake-ups), or the child's own outstanding finish subscriptions as a caller. Heartbeats,
|
||||
recurring crons, change-request watches, and other daemon background items never count: they are
|
||||
external triggers, not work the caller is waiting for. While following, turn ends and work changes stay
|
||||
silent until nothing is pending, which sends `finished` and removes the subscription. `followingSince`
|
||||
is stored before the notice is sent, so restarts resume following without repeating it, and following
|
||||
ends after 24 hours with an "is still working" notice. Remote children and providers without the probe
|
||||
report their first turn end as `finished`.
|
||||
A turn end is not always a settled child. A child can end its turn with work that will start its next
|
||||
turn by itself: a running turn, queued messages, a pending provider wake-up
|
||||
(`AgentSession.hasPendingWakeup`: Claude background tasks, task notifications, and one-shot
|
||||
wake-ups), or the child's own outstanding finish subscriptions as a caller. Heartbeats, recurring
|
||||
crons, change-request watches, and other daemon background items never count: they are external
|
||||
triggers, not work the caller is waiting for.
|
||||
|
||||
Every turn end reports `finished` at once. When work is still pending, the notice names it and the
|
||||
subscription follows the child: each later turn end reports `finished` again, and the child settling
|
||||
with nothing pending sends a final `finished` and removes the subscription, even when the work
|
||||
drains without another turn. Reporting at once keeps a long-lived task, such as a dev server, from
|
||||
leaving the caller without the child's reply. Following is what lets the caller hear the reply a
|
||||
background task wakes up later ([#6346](https://github.com/getpaseo/paseo/issues/6346)). A work change
|
||||
that leaves work pending sends nothing. Errors, permission requests, and closes report as they
|
||||
happen. `followingSince` is stored when following starts, so a restart keeps following instead of
|
||||
waiting for another turn end. After 24 hours of following, the caller gets a final `finished` with
|
||||
the child's last reply and the subscription ends. Remote children and providers without the probe
|
||||
report their first turn end as a settled `finished`.
|
||||
|
||||
Permission requests are notification checkpoints, not the end of that subscription. The caller is notified again after a permission response when the child finishes, errors, or requests another permission.
|
||||
The permission notification includes the normalized request plus the child and request IDs, so the caller can inspect it and respond without fetching agent status.
|
||||
|
||||
+3
-4
@@ -205,10 +205,9 @@ docker build \
|
||||
.
|
||||
```
|
||||
|
||||
The Docker workflow builds the image on pull requests and on `main` as a
|
||||
non-publishing check. Stable `vX.Y.Z` tag pushes publish
|
||||
`ghcr.io/getpaseo/paseo:X.Y.Z` and `ghcr.io/getpaseo/paseo:latest`. Beta tags
|
||||
publish only the exact prerelease tag, such as
|
||||
The Docker workflow builds the image on `main` as a non-publishing check.
|
||||
Stable `vX.Y.Z` tag pushes publish `ghcr.io/getpaseo/paseo:X.Y.Z` and
|
||||
`ghcr.io/getpaseo/paseo:latest`. Beta tags publish only the exact prerelease tag, such as
|
||||
`ghcr.io/getpaseo/paseo:0.1.102-beta.1`, and do not update `latest`.
|
||||
|
||||
To replace a Docker image in place without rebuilding desktop, APK, or EAS
|
||||
|
||||
+4
-3
@@ -118,8 +118,9 @@ An explicit user instruction can select another base.
|
||||
`chore(release): cut <version>` without a tag.
|
||||
5. Push the release branch (`git push -u origin HEAD`). Pushing any `release/**` branch triggers
|
||||
`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.
|
||||
groups, isolated from `main` traffic. Never wait on `main` CI, because `main` runs queue behind
|
||||
each other and a newer merge replaces the pending one.
|
||||
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, push the tag first with `npm run release:push` so remote builds start right away.
|
||||
@@ -278,7 +279,7 @@ The tag push triggers `Desktop Release`, `Android APK Release`, `Docker`, `Relea
|
||||
|
||||
Confirm that `npm view @getpaseo/cli dist-tags` shows `latest` at the shipped version, and `beta` at the shipped version or an active newer beta, before considering the stable release complete.
|
||||
|
||||
The Docker workflow builds images from the checked-out source tree on `main` as non-publishing checks (cancelling superseded `main` runs). Stable `vX.Y.Z` tag pushes publish `ghcr.io/getpaseo/paseo:X.Y.Z` and `ghcr.io/getpaseo/paseo:latest`; beta `vX.Y.Z-beta.N` tag pushes publish only `ghcr.io/getpaseo/paseo:X.Y.Z-beta.N` and never move `latest`.
|
||||
The Docker workflow builds images from the checked-out source tree on `main` as non-publishing checks (a running check finishes, and a newer merge replaces the pending one). Stable `vX.Y.Z` tag pushes publish `ghcr.io/getpaseo/paseo:X.Y.Z` and `ghcr.io/getpaseo/paseo:latest`; beta `vX.Y.Z-beta.N` tag pushes publish only `ghcr.io/getpaseo/paseo:X.Y.Z-beta.N` and never move `latest`.
|
||||
|
||||
The production relay is the Elixir service in [getpaseo/paseo-relay](https://github.com/getpaseo/paseo-relay), with its own deployment process. Paseo releases and pushes to this repository do not deploy it. The Cloudflare relay code and workflow in this repository are legacy and are not used in production.
|
||||
|
||||
|
||||
+1
-1
@@ -200,7 +200,7 @@ Test suites in this repo are heavy. Running them in bulk freezes the machine, es
|
||||
|
||||
## Pull-request test routing
|
||||
|
||||
PR checks are routed by the behavior each suite proves, using `.github/ci-paths.yml`. A package does not inherit every test suite of its runtime consumers: app changes do not run CLI or Electron-wrapper tests, and protocol changes do not run every package that imports the protocol. Cross-package static compatibility belongs to `typecheck`; full integration coverage runs after merge on main and in manual CI runs.
|
||||
PR checks are routed by the behavior each suite proves, using `.github/ci-paths.yml`. A package does not inherit every test suite of its runtime consumers: app changes do not run CLI or Electron-wrapper tests, and protocol changes do not run every package that imports the protocol. The CLI E2E tests are the exception: they drive a real daemon, so changes to the server or built-in plugins run them too. Cross-package static compatibility belongs to `typecheck`; full integration coverage runs after merge on main and in manual CI runs.
|
||||
|
||||
Required matrix legs are declared as statically named jobs. Their shared steps use YAML anchors, while job-level `if` conditions let GitHub report an unaffected leg as genuinely skipped without allocating a runner or losing the exact required-check name.
|
||||
|
||||
|
||||
+24
-8
@@ -330,19 +330,35 @@ that starts or accepts them. Received messages retain sender attribution, while
|
||||
notifications remain visible events. Collapse, timing and locally mounted history share
|
||||
these boundaries.
|
||||
|
||||
Agent-message XML belongs to the daemon's `agent/agent-messages` boundary. Prompt delivery encodes
|
||||
Agent-message markup belongs to the daemon's `agent/agent-messages` boundary. Prompt delivery encodes
|
||||
provenance; acceptance, provider echoes, import, and replay share its projection. The delivery ID is
|
||||
also the projected call ID, so a provider echo cannot create a second row. Sender IDs are opaque and
|
||||
do not imply local ownership or authorization. Capture the sender title at delivery: archived or
|
||||
removed senders must remain understandable without a live directory lookup.
|
||||
|
||||
The optional `agentMessage` payload carries event, sender, and delivered text. Shared client
|
||||
presentation (`protocol/paseo-tool-presentation`) owns its heading and expanded details, next to the
|
||||
labels for every Paseo MCP tool. The daemon
|
||||
must not construct UI labels or prepend sender labels to the semantic message body. The existing
|
||||
`tool_call` / `plain_text` envelope is a compatibility adapter: older clients still parse the row and
|
||||
expand its body. New clients use the typed payload, never infer the event from a tool name or parse
|
||||
XML. Stream reduction and disk-cache serialization preserve the payload without rendering it.
|
||||
Each delivered message keeps its text first and ends with a `<paseo-message … length="N"/>` marker.
|
||||
Text at character 0 stays the sender's, so a provider still reads a slash command there, and bodies
|
||||
are never escaped. `length` bounds the text before the marker, so marker syntax inside a body cannot
|
||||
split it, and a batch splits back into rows by reading markers from the end. A person's prompt gets a
|
||||
marker only when it shares a provider turn with other deliveries or contains `<paseo-message` or
|
||||
`<paseo-system`. Transcripts written before markers open with a `<paseo-system>` envelope; the
|
||||
projection still reads those (`COMPAT(leadingPaseoSystemEnvelope)`).
|
||||
|
||||
The daemon decides whether a delivery is a message or a tool call, and clients render what it sends:
|
||||
|
||||
- A person's text is a `user_message`.
|
||||
- A peer message is an `agent_message` tool call whose `agentMessage` carries sender and text. The
|
||||
wire has no sender on `user_message`, so clients present it as a "Sent by" bubble.
|
||||
- Lifecycle notifications (`agent_finished`, `agent_errored`, `agent_needs_permission`,
|
||||
`agent_closed`), schedule fires (`heartbeat`), and change-request updates
|
||||
are plain tool calls. `plain_text` detail carries the sender in `label`, the body in `text`, and
|
||||
the icon. Clients render the heading from the tool name, so no notification event reaches them.
|
||||
|
||||
`isTimelineTurnTrigger` (`packages/protocol/src/timeline-turn.ts`) lists the delivered tool names that
|
||||
start a turn. Add a name there when the daemon projects a new delivery. Rows that older daemons stored
|
||||
with notification `agentMessage` metadata are rewritten to the plain call at presentation
|
||||
(`COMPAT(agentNotificationMetadata)`). Stream reduction and disk-cache serialization preserve the
|
||||
payload without rendering it.
|
||||
|
||||
The compatibility boundary for older daemons is snapshot normalization: running/idle status becomes an
|
||||
anonymous active turn or idle state once, and downstream code consumes the same activity shape. The app
|
||||
|
||||
@@ -6,16 +6,15 @@ import {
|
||||
expectComposerDoesNotName,
|
||||
expectAgentProfilesEmptyPrompt,
|
||||
expectHostAgentProfiles,
|
||||
expectProfileEditTooltip,
|
||||
expectComposerMode,
|
||||
expectCreateProfileFromModelRow,
|
||||
expectComposerModel,
|
||||
expectModelRowProfileActionBesideRow,
|
||||
expectModelRowSelected,
|
||||
expectProfileEditIsPencilOnly,
|
||||
expectProfileReachableByScrolling,
|
||||
expectProfileSearchResult,
|
||||
expectProfileVisibleForProvider,
|
||||
expectPickerProfile,
|
||||
expectProfilesEditLink,
|
||||
fillAgentProfileName,
|
||||
openEditProfileFromModelRow,
|
||||
openModelPicker,
|
||||
@@ -86,17 +85,19 @@ test.describe("Agent profiles in the model picker", () => {
|
||||
await expectComposerMode(page, "Load test");
|
||||
});
|
||||
|
||||
await test.step("the sole provider opens directly", async () => {
|
||||
await test.step("the picker opens on the agent's provider with Profiles beside it", async () => {
|
||||
await openModelPicker(page);
|
||||
await expect(page.getByTestId("model-search-input").first()).toBeVisible();
|
||||
await expect(page.getByTestId("sheet-header-back")).toHaveCount(0);
|
||||
await expect(page.locator('[data-testid^="model-provider-"]')).toHaveCount(0);
|
||||
await expectProfileVisibleForProvider(page, {
|
||||
await expect(page.getByTestId("model-search-input").first()).toBeFocused();
|
||||
await expect(page.getByTestId("model-provider-mock")).toHaveAttribute(
|
||||
"data-active",
|
||||
"true",
|
||||
);
|
||||
await expectModelRowSelected(page, { provider: "mock", modelId: "ten-second-stream" });
|
||||
await expectPickerProfile(page, {
|
||||
name: PROFILE.name,
|
||||
summary: PROFILE_SUMMARY,
|
||||
});
|
||||
await expectProfileEditIsPencilOnly(page);
|
||||
await expectProfileEditTooltip(page);
|
||||
await expectProfilesEditLink(page);
|
||||
});
|
||||
|
||||
await test.step("applying it writes its model and mode into the composer", async () => {
|
||||
@@ -115,14 +116,13 @@ test.describe("Agent profiles in the model picker", () => {
|
||||
await expectComposerDoesNotName(page, PROFILE.name);
|
||||
});
|
||||
|
||||
await test.step("reopening returns directly to the provider models", async () => {
|
||||
await test.step("reopening returns to the provider models with the new model checked", async () => {
|
||||
await openModelPicker(page);
|
||||
await expect(page.getByTestId("model-search-input").first()).toBeVisible();
|
||||
await expectProfileVisibleForProvider(page, {
|
||||
await expectModelRowSelected(page, { provider: "mock", modelId: "one-minute-stream" });
|
||||
await expectPickerProfile(page, {
|
||||
name: PROFILE.name,
|
||||
summary: PROFILE_SUMMARY,
|
||||
});
|
||||
await expectModelRowSelected(page, { provider: "mock", modelId: "one-minute-stream" });
|
||||
await closeModelPicker(page);
|
||||
});
|
||||
} finally {
|
||||
|
||||
@@ -0,0 +1,559 @@
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import { connectDaemonClient } from "../support/helpers/daemon-client-loader";
|
||||
import {
|
||||
beginTextReveal,
|
||||
retargetTextReveal,
|
||||
visibleRevealedText,
|
||||
} from "../../src/agent-stream/text-reveal";
|
||||
import type { Page } from "@playwright/test";
|
||||
import { test, expect } from "../support/fixtures";
|
||||
import { expectComposerVisible } from "../support/helpers/composer";
|
||||
import { scrollChatAwayFromBottom } from "../support/helpers/agent-bottom-anchor";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
|
||||
test.use({
|
||||
e2eDaemonConfig: {
|
||||
version: 1,
|
||||
agents: {
|
||||
providers: Object.fromEntries(
|
||||
[
|
||||
"claude",
|
||||
"codex",
|
||||
"copilot",
|
||||
"opencode",
|
||||
"pi",
|
||||
"omp",
|
||||
"antigravity",
|
||||
"hoplite",
|
||||
"muse",
|
||||
].map((id) => [id, { enabled: false }]),
|
||||
),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
interface ClosingFenceFrameSample {
|
||||
text: string;
|
||||
codeBlockHeights: number[];
|
||||
codeBlockTexts: string[];
|
||||
messageHeights: number[];
|
||||
partialFenceLines: string[];
|
||||
}
|
||||
|
||||
interface ClosingFenceFrameReport {
|
||||
finished: boolean;
|
||||
samples: ClosingFenceFrameSample[];
|
||||
}
|
||||
|
||||
async function sampleClosingFenceFrames(page: Page): Promise<ClosingFenceFrameReport> {
|
||||
return await page.evaluate(async () => {
|
||||
const samples: ClosingFenceFrameSample[] = [];
|
||||
let finished = false;
|
||||
|
||||
await new Promise<void>((resolve) => {
|
||||
const tick = () => {
|
||||
const messages = Array.from(
|
||||
document.querySelectorAll<HTMLElement>('[data-testid="assistant-message"]'),
|
||||
);
|
||||
const text = messages.map((message) => message.textContent ?? "").join("");
|
||||
const sample: ClosingFenceFrameSample = {
|
||||
text,
|
||||
codeBlockHeights: [],
|
||||
codeBlockTexts: [],
|
||||
messageHeights: messages.map((message) =>
|
||||
Math.round(message.getBoundingClientRect().height),
|
||||
),
|
||||
partialFenceLines: [],
|
||||
};
|
||||
|
||||
for (const message of messages) {
|
||||
for (const block of message.querySelectorAll<HTMLElement>(
|
||||
'pre, [data-paseo-markdown-tag="pre"]',
|
||||
)) {
|
||||
const code = block.querySelector<HTMLElement>('code, [data-paseo-markdown-tag="code"]');
|
||||
const codeText = code?.textContent ?? block.textContent ?? "";
|
||||
sample.codeBlockTexts.push(codeText.trimEnd());
|
||||
// Opening fence prefixes render as prose; closing artifacts live inside code blocks.
|
||||
for (const line of codeText.split(/\r?\n/)) {
|
||||
if (/^\s*`{1,2}\s*$/.test(line)) sample.partialFenceLines.push(line);
|
||||
}
|
||||
sample.codeBlockHeights.push(Math.round(block.getBoundingClientRect().height));
|
||||
}
|
||||
}
|
||||
|
||||
samples.push(sample);
|
||||
|
||||
finished = text.includes("Both blocks are closed.");
|
||||
if (finished) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
requestAnimationFrame(tick);
|
||||
};
|
||||
requestAnimationFrame(tick);
|
||||
});
|
||||
|
||||
return { finished, samples };
|
||||
});
|
||||
}
|
||||
|
||||
const FIRST_PAUSE_TEXT = "Here is the first snippet:const answer = 42;\nconsole.log(answer);";
|
||||
const SECOND_PAUSE_TEXT = `${FIRST_PAUSE_TEXT}And a second one:echo done`;
|
||||
|
||||
for (const { label, html } of [
|
||||
{ label: "semantic", html: "<pre><code>const answer = 42;\n`\n``</code></pre>" },
|
||||
{
|
||||
label: "annotated",
|
||||
html: '<div data-paseo-markdown-tag="pre"><span data-paseo-markdown-tag="code">const answer = 42;\n`\n``</span><button>Copy</button></div>',
|
||||
},
|
||||
{
|
||||
label: "annotated semantic",
|
||||
html: '<pre data-paseo-markdown-tag="pre"><code data-paseo-markdown-tag="code">const answer = 42;\n`\n``</code></pre>',
|
||||
},
|
||||
]) {
|
||||
test(`samples ${label} code block DOM without duplicate blocks or controls`, async ({ page }) => {
|
||||
await page.setContent(
|
||||
`<div data-testid="assistant-message">${html}<p>Both blocks are closed.</p></div>`,
|
||||
);
|
||||
const report = await sampleClosingFenceFrames(page);
|
||||
const sample = report.samples.at(-1)!;
|
||||
expect(report.finished).toBe(true);
|
||||
expect(sample.codeBlockTexts).toEqual(["const answer = 42;\n`\n``"]);
|
||||
expect(sample.partialFenceLines).toEqual(["`", "``"]);
|
||||
expect(sample.codeBlockHeights).toHaveLength(1);
|
||||
expect(sample.codeBlockHeights[0]).toBeGreaterThan(0);
|
||||
});
|
||||
}
|
||||
|
||||
function closingFencePauseSamples(
|
||||
samples: readonly ClosingFenceFrameSample[],
|
||||
pauseText: string,
|
||||
): ClosingFenceFrameSample[] {
|
||||
return samples.filter((sample) => sample.text === pauseText);
|
||||
}
|
||||
|
||||
function expectStableGeometry(
|
||||
samples: readonly ClosingFenceFrameSample[],
|
||||
expectedCodeBlockTexts: readonly string[],
|
||||
): void {
|
||||
expect(samples.length, "the paused text state should be sampled").toBeGreaterThan(0);
|
||||
expect(
|
||||
samples.every(
|
||||
(sample) => JSON.stringify(sample.codeBlockTexts) === JSON.stringify(expectedCodeBlockTexts),
|
||||
),
|
||||
"the sampled code should contain only the authored lines",
|
||||
).toBe(true);
|
||||
const geometries = new Set(
|
||||
samples.map((sample) => JSON.stringify([sample.messageHeights, sample.codeBlockHeights])),
|
||||
);
|
||||
expect(
|
||||
geometries.size,
|
||||
"message and code block geometry should stay fixed during the pause",
|
||||
).toBe(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* A closing fence that is still being typed must not be painted as code.
|
||||
*
|
||||
* The mock reply closes each code block in two arrivals: one backtick, a pause,
|
||||
* then the other two. Painted, that first backtick is a line of code that
|
||||
* vanishes when the fence completes, so the block grows and shrinks and every
|
||||
* row below it moves twice. Each pause is sampled and its text geometry checked.
|
||||
*/
|
||||
test("does not paint a closing fence while it is still being typed", async ({ page }, testInfo) => {
|
||||
test.setTimeout(90_000);
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "closing-fence-",
|
||||
title: "Closing fence",
|
||||
model: "e2e-fast-stream",
|
||||
});
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
const reportPromise = sampleClosingFenceFrames(page);
|
||||
await agent.client.sendAgentMessage(
|
||||
agent.agentId,
|
||||
"Stream a code block with a split closing fence.",
|
||||
);
|
||||
const report = await reportPromise;
|
||||
|
||||
await testInfo.attach("closing-fence-frames", {
|
||||
body: JSON.stringify(report, null, 2),
|
||||
contentType: "application/json",
|
||||
});
|
||||
expect(report.finished, "the reply should finish streaming").toBe(true);
|
||||
expect(
|
||||
report.samples.flatMap((sample) => sample.partialFenceLines),
|
||||
"no frame, including transitions outside the pause windows, may show a partial fence inside code",
|
||||
).toEqual([]);
|
||||
const firstPauseSamples = closingFencePauseSamples(report.samples, FIRST_PAUSE_TEXT);
|
||||
const secondPauseSamples = closingFencePauseSamples(report.samples, SECOND_PAUSE_TEXT);
|
||||
expectStableGeometry(firstPauseSamples, ["const answer = 42;\nconsole.log(answer);"]);
|
||||
expectStableGeometry(secondPauseSamples, [
|
||||
"const answer = 42;\nconsole.log(answer);",
|
||||
"echo done",
|
||||
]);
|
||||
expect(secondPauseSamples[0]?.codeBlockHeights[0]).toBe(
|
||||
firstPauseSamples[0]?.codeBlockHeights[0],
|
||||
);
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("excludes each revealed character of the next paragraph from both pauses", () => {
|
||||
for (const [pauseText, paragraph] of [
|
||||
[FIRST_PAUSE_TEXT, "And a second one:"],
|
||||
[SECOND_PAUSE_TEXT, "Both blocks are closed."],
|
||||
]) {
|
||||
const state = retargetTextReveal(beginTextReveal(pauseText), pauseText + paragraph);
|
||||
const samples = Array.from({ length: paragraph.length + 1 }, (_, index) => ({
|
||||
text: visibleRevealedText({ ...state, revealed: pauseText.length + index }),
|
||||
codeBlockHeights: [],
|
||||
codeBlockTexts: [],
|
||||
messageHeights: [index],
|
||||
partialFenceLines: [],
|
||||
}));
|
||||
expect(closingFencePauseSamples(samples, pauseText)).toEqual([samples[0]]);
|
||||
}
|
||||
});
|
||||
|
||||
for (const { label, markdown, expectedCode, expectedPartialFenceLines } of [
|
||||
{
|
||||
label: "opening prefixes in prose",
|
||||
markdown: "And a second one:\n\n`\n\n``\n\nBoth blocks are closed.",
|
||||
expectedCode: [],
|
||||
expectedPartialFenceLines: [],
|
||||
},
|
||||
{
|
||||
label: "partial fences inside rendered code",
|
||||
markdown: "```ts\nconst answer = 42;\n`\n``\n```\n\nBoth blocks are closed.",
|
||||
expectedCode: ["const answer = 42;\n`\n``"],
|
||||
expectedPartialFenceLines: ["`", "``"],
|
||||
},
|
||||
]) {
|
||||
test(`samples ${label} in the correct container`, async ({ page }, testInfo) => {
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "fence-sample-container-",
|
||||
title: "Fence sample container",
|
||||
featureValues: { mockAssistantResponse: markdown },
|
||||
});
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
const reportPromise = sampleClosingFenceFrames(page);
|
||||
await agent.client.sendAgentMessage(agent.agentId, "Show the fence sampling fixture.");
|
||||
const report = await reportPromise;
|
||||
await testInfo.attach("fence-container-frames", {
|
||||
body: JSON.stringify(report, null, 2),
|
||||
contentType: "application/json",
|
||||
});
|
||||
expect(report.finished).toBe(true);
|
||||
const messageText = await page.getByTestId("assistant-message").innerText();
|
||||
const messageLines = messageText.split(/\r?\n/);
|
||||
const messageFenceLines = messageLines.filter((line) => /^\s*`{1,2}\s*$/.test(line));
|
||||
expect(messageFenceLines).toEqual(["`", "``"]);
|
||||
const finalSample = report.samples.at(-1);
|
||||
expect(finalSample?.codeBlockTexts).toEqual(expectedCode);
|
||||
expect(finalSample?.partialFenceLines).toEqual(expectedPartialFenceLines);
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test("shows the complete reasoning after a streamed turn finishes", async ({ page }, testInfo) => {
|
||||
test.setTimeout(90_000);
|
||||
await page.setViewportSize({ width: 1280, height: 900 });
|
||||
await page.addInitScript(() => {
|
||||
localStorage.setItem(
|
||||
"@paseo:app-settings",
|
||||
JSON.stringify({ toolCallDetailLevel: "detailed", autoExpandReasoning: true }),
|
||||
);
|
||||
});
|
||||
const reasoning =
|
||||
"Need to find the scroll container, the layout effect that watches for new messages, and any gesture handler that might fight with programmatic scrolling. Probably a ref on the FlatList plus a near-bottom threshold.";
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "finished-reasoning-",
|
||||
title: "Finished reasoning",
|
||||
model: "ten-second-stream",
|
||||
});
|
||||
const historyClient = await connectDaemonClient<
|
||||
Pick<DaemonClient, "connect" | "close" | "fetchAgentTimeline">
|
||||
>({ clientIdPrefix: "finished-reasoning-history" });
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
await agent.client.sendAgentMessage(
|
||||
agent.agentId,
|
||||
"Stream briefly to check finished reasoning.",
|
||||
);
|
||||
await agent.client.waitForFinish(agent.agentId, 30_000);
|
||||
const history = await historyClient.fetchAgentTimeline(agent.agentId, { limit: 500 });
|
||||
const thoughts = history.entries
|
||||
.map((entry) => entry.item)
|
||||
.filter((item) => item.type === "reasoning");
|
||||
await testInfo.attach("canonical-reasoning", {
|
||||
body: JSON.stringify(thoughts, null, 2),
|
||||
contentType: "application/json",
|
||||
});
|
||||
expect(thoughts[0]?.text).toBe(reasoning);
|
||||
const expectedCounts = new Map<string, number>();
|
||||
for (const thought of thoughts)
|
||||
expectedCounts.set(thought.text, (expectedCounts.get(thought.text) ?? 0) + 1);
|
||||
const rendered = page.getByText(reasoning, { exact: true });
|
||||
for (const [text, count] of expectedCounts)
|
||||
await expect(page.getByText(text, { exact: true })).toHaveCount(count);
|
||||
await expect(rendered.first()).toBeVisible();
|
||||
await testInfo.attach("finished-reasoning", {
|
||||
body: await page.screenshot(),
|
||||
contentType: "image/png",
|
||||
});
|
||||
await page.reload();
|
||||
for (const [text, count] of expectedCounts)
|
||||
await expect(page.getByText(text, { exact: true })).toHaveCount(count);
|
||||
await expect(rendered.first()).toBeVisible();
|
||||
} catch (error) {
|
||||
await testInfo.attach("reasoning-before-cleanup", {
|
||||
body: await page.screenshot(),
|
||||
contentType: "image/png",
|
||||
});
|
||||
throw error;
|
||||
} finally {
|
||||
await historyClient.close();
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("records equal-input long-reply rendering metrics", async ({ page }, testInfo) => {
|
||||
test.setTimeout(120_000);
|
||||
await page.setViewportSize({ width: 1280, height: 900 });
|
||||
const markdown =
|
||||
Array.from({ length: 15 }, (_, index) =>
|
||||
[
|
||||
"### Block " + index,
|
||||
"",
|
||||
"\x60\x60\x60ts",
|
||||
...Array.from(
|
||||
{ length: 12 },
|
||||
(_value, line) => "const value_" + index + "_" + line + " = " + (index * 12 + line) + ";",
|
||||
),
|
||||
"\x60\x60\x60",
|
||||
"",
|
||||
].join("\n"),
|
||||
).join("\n") + "\nEqual-input stream complete.";
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "equal-input-long-reply-",
|
||||
title: "Equal-input long reply",
|
||||
featureValues: {
|
||||
mockStreamingAssistantResponse: markdown,
|
||||
mockStreamingAssistantIntervalMs: 5,
|
||||
},
|
||||
});
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
const session = await page.context().newCDPSession(page);
|
||||
await session.send("Performance.enable");
|
||||
const before = await session.send("Performance.getMetrics");
|
||||
const sampler = await page.evaluateHandle(() => {
|
||||
const state = {
|
||||
frames: [] as number[],
|
||||
longTasks: [] as number[],
|
||||
running: true,
|
||||
last: performance.now(),
|
||||
};
|
||||
const observer = new PerformanceObserver((list) => {
|
||||
state.longTasks.push(...list.getEntries().map((entry) => entry.duration));
|
||||
});
|
||||
observer.observe({ type: "longtask", buffered: false });
|
||||
const tick = (now: number) => {
|
||||
state.frames.push(now - state.last);
|
||||
state.last = now;
|
||||
if (state.running) requestAnimationFrame(tick);
|
||||
};
|
||||
requestAnimationFrame(tick);
|
||||
return { state, observer };
|
||||
});
|
||||
await agent.client.sendAgentMessage(agent.agentId, "Render the fixed fifteen-block fixture.");
|
||||
await agent.client.waitForFinish(agent.agentId, 60_000);
|
||||
const message = page.getByTestId("assistant-message").last();
|
||||
await expect(message).toContainText("Equal-input stream complete.", { timeout: 30_000 });
|
||||
const blocks = message.locator('pre, [data-paseo-markdown-tag="pre"]');
|
||||
await expect(blocks).toHaveCount(15);
|
||||
for (let index = 0; index < 15; index++) {
|
||||
await expect(blocks.nth(index)).toContainText(
|
||||
"const value_" + index + "_11 = " + (index * 12 + 11) + ";",
|
||||
);
|
||||
}
|
||||
const samples = await sampler.evaluate(({ state, observer }) => {
|
||||
state.running = false;
|
||||
state.longTasks.push(...observer.takeRecords().map((entry) => entry.duration));
|
||||
observer.disconnect();
|
||||
return state;
|
||||
});
|
||||
const after = await session.send("Performance.getMetrics");
|
||||
const frames = [...samples.frames].sort((a, b) => a - b);
|
||||
await testInfo.attach("equal-input-rendering", {
|
||||
body: JSON.stringify(
|
||||
{
|
||||
markdown,
|
||||
viewport: page.viewportSize(),
|
||||
intervalMs: 5,
|
||||
frameCount: frames.length,
|
||||
frameP95Ms: frames[Math.floor(frames.length * 0.95)],
|
||||
maxFrameMs: frames.at(-1),
|
||||
longTasksMs: samples.longTasks,
|
||||
before: before.metrics,
|
||||
after: after.metrics,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
contentType: "application/json",
|
||||
});
|
||||
await sampler.dispose();
|
||||
await session.detach();
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("manually expands complete reasoning after leaving output following", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
test.setTimeout(90_000);
|
||||
await page.setViewportSize({ width: 1280, height: 900 });
|
||||
await page.addInitScript(() => {
|
||||
localStorage.setItem(
|
||||
"@paseo:app-settings",
|
||||
JSON.stringify({ chatDisplay: "full", autoExpandReasoning: false }),
|
||||
);
|
||||
});
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "manual-finished-reasoning-",
|
||||
title: "Manual finished reasoning",
|
||||
model: "ten-second-stream",
|
||||
});
|
||||
const historyClient = await connectDaemonClient<
|
||||
Pick<DaemonClient, "connect" | "close" | "fetchAgentTimeline">
|
||||
>({ clientIdPrefix: "manual-finished-reasoning-history" });
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
await agent.client.sendAgentMessage(
|
||||
agent.agentId,
|
||||
"Stream briefly to check finished reasoning.",
|
||||
);
|
||||
const finished = await agent.client.waitForFinish(agent.agentId, 30_000);
|
||||
expect(finished.status).toBe("idle");
|
||||
await testInfo.attach("manual-completed-turn", {
|
||||
body: JSON.stringify(finished),
|
||||
contentType: "application/json",
|
||||
});
|
||||
const history = await historyClient.fetchAgentTimeline(agent.agentId, { limit: 500 });
|
||||
const thoughts = history.entries
|
||||
.map((entry) => entry.item)
|
||||
.filter((item) => item.type === "reasoning");
|
||||
expect(thoughts.length).toBeGreaterThan(0);
|
||||
expect(thoughts.every((thought) => thought.text.length > 0)).toBe(true);
|
||||
const expectedCounts = new Map<string, number>();
|
||||
for (const thought of thoughts)
|
||||
expectedCounts.set(thought.text, (expectedCounts.get(thought.text) ?? 0) + 1);
|
||||
await testInfo.attach("manual-canonical-reasoning", {
|
||||
body: JSON.stringify(thoughts, null, 2),
|
||||
contentType: "application/json",
|
||||
});
|
||||
const pointerCapture = await page.evaluateHandle(() => {
|
||||
const events: {
|
||||
type: string;
|
||||
timestamp: number;
|
||||
tag: string;
|
||||
label: string;
|
||||
scrollTop: number | null;
|
||||
}[] = [];
|
||||
const observe = (event: Event) => {
|
||||
const target = event.target;
|
||||
if (!(target instanceof HTMLElement)) return;
|
||||
const scroll = document.querySelector<HTMLElement>('[data-testid="agent-chat-scroll"]');
|
||||
events.push({
|
||||
type: event.type,
|
||||
timestamp: event.timeStamp,
|
||||
tag: target.tagName,
|
||||
label: target.textContent?.slice(0, 80) ?? "",
|
||||
scrollTop: scroll?.scrollTop ?? null,
|
||||
});
|
||||
};
|
||||
for (const type of ["pointerdown", "pointerup", "wheel"])
|
||||
document.addEventListener(type, observe, true);
|
||||
return {
|
||||
events,
|
||||
stop: () => {
|
||||
for (const type of ["pointerdown", "pointerup", "wheel"])
|
||||
document.removeEventListener(type, observe, true);
|
||||
},
|
||||
};
|
||||
});
|
||||
const badges = page.getByTestId("tool-call-badge").filter({ hasText: "Thinking" });
|
||||
await expect(badges).toHaveCount(thoughts.length);
|
||||
// Locator scrolling alone leaves output-following armed, so pointer-down can
|
||||
// snap the feed to its tail before pointer-up reaches the Thinking control.
|
||||
await scrollChatAwayFromBottom(page, { deltaY: -600, minDistanceFromBottom: 100 });
|
||||
for (let index = 0; index < thoughts.length; index++) {
|
||||
await badges
|
||||
.nth(index)
|
||||
.getByRole("button", { name: "Thinking", exact: true })
|
||||
.first()
|
||||
.click();
|
||||
await expect(
|
||||
badges.nth(index).getByText(thoughts[index].text, { exact: true }),
|
||||
).toBeVisible();
|
||||
}
|
||||
for (const [text, count] of expectedCounts)
|
||||
await expect(page.getByText(text, { exact: true })).toHaveCount(count);
|
||||
const first = badges.first();
|
||||
await first.getByRole("button", { name: "Thinking", exact: true }).first().click();
|
||||
await expect(first.getByText(thoughts[0].text, { exact: true })).not.toBeVisible();
|
||||
await first.getByRole("button", { name: "Thinking", exact: true }).first().click();
|
||||
await expect(first.getByText(thoughts[0].text, { exact: true })).toBeVisible();
|
||||
for (const [text, count] of expectedCounts)
|
||||
await expect(page.getByText(text, { exact: true })).toHaveCount(count);
|
||||
await testInfo.attach("manual-expanded-reasoning", {
|
||||
body: await page.screenshot(),
|
||||
contentType: "image/png",
|
||||
});
|
||||
const pointerEvents = await pointerCapture.evaluate(({ events, stop }) => {
|
||||
stop();
|
||||
return events;
|
||||
});
|
||||
await pointerCapture.dispose();
|
||||
await testInfo.attach("manual-pointer-events", {
|
||||
body: JSON.stringify(pointerEvents, null, 2),
|
||||
contentType: "application/json",
|
||||
});
|
||||
await page.reload();
|
||||
await expect(badges).toHaveCount(thoughts.length);
|
||||
await scrollChatAwayFromBottom(page, { deltaY: -600, minDistanceFromBottom: 100 });
|
||||
for (let index = 0; index < thoughts.length; index++) {
|
||||
await badges
|
||||
.nth(index)
|
||||
.getByRole("button", { name: "Thinking", exact: true })
|
||||
.first()
|
||||
.click();
|
||||
await expect(
|
||||
badges.nth(index).getByText(thoughts[index].text, { exact: true }),
|
||||
).toBeVisible();
|
||||
}
|
||||
for (const [text, count] of expectedCounts)
|
||||
await expect(page.getByText(text, { exact: true })).toHaveCount(count);
|
||||
} catch (error) {
|
||||
await testInfo.attach("manual-before-cleanup", {
|
||||
body: await page.screenshot(),
|
||||
contentType: "image/png",
|
||||
});
|
||||
throw error;
|
||||
} finally {
|
||||
await historyClient.close();
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
@@ -84,17 +84,14 @@ async function openModelSelector(page: Page) {
|
||||
await expect(page.getByTestId("agent-controls-settings-list")).toBeVisible({ timeout: 10_000 });
|
||||
}
|
||||
|
||||
async function dismissStackedModelPickerWithBackdrop(page: Page) {
|
||||
await page
|
||||
.getByTestId("agent-controls-settings-list")
|
||||
.getByRole("button", { name: /Select model/ })
|
||||
.click();
|
||||
await expect(page.getByTestId("agent-controls-model-browser-sheet")).toBeInViewport();
|
||||
await page.mouse.click(MOBILE_VIEWPORT.width / 2, 24);
|
||||
// In CI, Gorhom retains the dismissed sheet below the viewport.
|
||||
// Dismissal is complete when it leaves the displayed surface.
|
||||
await expect(page.getByTestId("agent-controls-model-browser-sheet")).not.toBeInViewport();
|
||||
await expect(page.getByTestId("agent-controls-model-sheet")).toBeVisible();
|
||||
async function openModelPage(page: Page) {
|
||||
await page.getByTestId("agent-controls-model").click();
|
||||
await expect(page.getByTestId("mobile-model-page")).toBeVisible();
|
||||
await expect(page.getByTestId("agent-controls-settings-list")).toHaveCount(0);
|
||||
}
|
||||
|
||||
async function returnHomeWithBack(page: Page) {
|
||||
await page.getByTestId("sheet-header-back").click();
|
||||
await expect(page.getByTestId("agent-controls-settings-list")).toBeVisible();
|
||||
}
|
||||
|
||||
@@ -113,7 +110,7 @@ async function openAndCloseModelSelectorTwice(page: Page) {
|
||||
}
|
||||
|
||||
test.describe("mobile bottom sheet reopen", () => {
|
||||
test("sheets reopen and model search returns to configuration", async ({ page }) => {
|
||||
test("sheets reopen and a model pick returns to Home", async ({ page }) => {
|
||||
const session = await openMockAgentAtMobileBreakpoint(page);
|
||||
try {
|
||||
await test.step("tab switcher opens, closes, and reopens", async () => {
|
||||
@@ -124,24 +121,28 @@ test.describe("mobile bottom sheet reopen", () => {
|
||||
await openAndCloseModelSelectorTwice(page);
|
||||
});
|
||||
|
||||
await test.step("model search returns to configuration", async () => {
|
||||
await test.step("the Model page swaps in place and Back returns to Home", async () => {
|
||||
await openModelSelector(page);
|
||||
const sheet = page.getByTestId("agent-controls-model-sheet");
|
||||
await openModelPage(page);
|
||||
await returnHomeWithBack(page);
|
||||
await expect(sheet).toBeVisible();
|
||||
});
|
||||
|
||||
await dismissStackedModelPickerWithBackdrop(page);
|
||||
|
||||
await page.getByTestId("model-search-all-input").click();
|
||||
await test.step("a model found by search returns to Home with that model", async () => {
|
||||
await openModelPage(page);
|
||||
const search = page.getByTestId("model-search-all-input");
|
||||
await expect(search).not.toBeFocused();
|
||||
await search.click();
|
||||
await search.fill("Ten second");
|
||||
const model = page.getByRole("button", { name: /^Ten second stream/ });
|
||||
await expect(model).toBeVisible({
|
||||
timeout: 10_000,
|
||||
});
|
||||
await expect(model).toBeVisible({ timeout: 10_000 });
|
||||
|
||||
await model.click();
|
||||
|
||||
await expect(sheet).toBeVisible();
|
||||
await expect(page.getByTestId("agent-controls-model-sheet")).toBeVisible();
|
||||
await expect(page.getByTestId("agent-controls-settings-list")).toBeVisible();
|
||||
await expect(page.getByTestId("agent-controls-model")).toContainText("Ten second stream");
|
||||
await expect(page.getByTestId("agent-controls-model-browser-sheet")).not.toBeInViewport();
|
||||
});
|
||||
} finally {
|
||||
await session.cleanup();
|
||||
|
||||
@@ -30,7 +30,14 @@ test.use({
|
||||
const ACTIVE_SPEED_COLOR = "rgb(251, 191, 36)";
|
||||
const NORMAL_SPEED_COLOR = "rgb(113, 113, 122)";
|
||||
|
||||
const COMPACT_SPEED_CONTROL = "agent-feature-service_tier";
|
||||
const COMPACT_SPEED_SECTION = `${COMPACT_SPEED_CONTROL}-section`;
|
||||
|
||||
async function openSpeedSelector(page: Page): Promise<void> {
|
||||
const compactSection = page.getByTestId(COMPACT_SPEED_SECTION);
|
||||
if (await compactSection.isVisible().catch(() => false)) {
|
||||
return;
|
||||
}
|
||||
const speed = page.getByRole("button", { name: /^(Select speed|Speed: .+)$/ });
|
||||
const features = page.getByRole("button", { name: "Open agent features", exact: true });
|
||||
const modelSettings = page.getByRole("button", { name: /^Select model \(/ });
|
||||
@@ -39,7 +46,12 @@ async function openSpeedSelector(page: Page): Promise<void> {
|
||||
});
|
||||
if (!(await speed.isVisible())) {
|
||||
if (await features.isVisible()) await features.click();
|
||||
else await modelSettings.click();
|
||||
else {
|
||||
await modelSettings.click();
|
||||
await expect(compactSection).toBeVisible({ timeout: 30_000 });
|
||||
await expect(compactSection.getByText("Normal", { exact: true })).toBeVisible();
|
||||
return;
|
||||
}
|
||||
}
|
||||
await expect(speed).toBeVisible({ timeout: 30_000 });
|
||||
await speed.click();
|
||||
@@ -47,6 +59,13 @@ async function openSpeedSelector(page: Page): Promise<void> {
|
||||
}
|
||||
|
||||
async function selectSpeed(page: Page, label: string): Promise<void> {
|
||||
const compactSection = page.getByTestId(COMPACT_SPEED_SECTION);
|
||||
if (await compactSection.isVisible().catch(() => false)) {
|
||||
const pill = compactSection.getByRole("button", { name: label, exact: true });
|
||||
await pill.click();
|
||||
await expect(pill).toHaveAttribute("aria-selected", "true");
|
||||
return;
|
||||
}
|
||||
await page.getByRole("button", { name: label, exact: true }).last().click();
|
||||
const toolbarTrigger = page.getByRole("button", { name: `Speed: ${label}`, exact: true });
|
||||
const sheetTrigger = page.getByRole("button", { name: "Select speed", exact: true });
|
||||
@@ -56,6 +75,11 @@ async function selectSpeed(page: Page, label: string): Promise<void> {
|
||||
}
|
||||
|
||||
async function expectSpeedIconColor(page: Page, color: string): Promise<void> {
|
||||
const compactSection = page.getByTestId(COMPACT_SPEED_SECTION);
|
||||
if (await compactSection.isVisible().catch(() => false)) {
|
||||
await expect(compactSection.locator("svg").first()).toHaveCSS("stroke", color);
|
||||
return;
|
||||
}
|
||||
const trigger = page
|
||||
.getByRole("button", { name: /^(Speed: .+|Select speed)$/ })
|
||||
.filter({ visible: true });
|
||||
|
||||
@@ -387,7 +387,10 @@ test.describe("Composer model and effort shortcuts", () => {
|
||||
const effortLabel = page.getByTestId("combined-model-selector-thinking-label");
|
||||
await expect(effortLabel).toHaveText("Medium");
|
||||
await toggleModelPickerFromComposer(page);
|
||||
await expectModelPickerClosesFromSearch(page);
|
||||
const drawerModelRow = page.getByTestId("agent-controls-model");
|
||||
await expect(drawerModelRow).toBeVisible();
|
||||
await page.keyboard.press(`${SHORTCUT_MOD}+Slash`);
|
||||
await expect(drawerModelRow).toBeHidden();
|
||||
await cycleComposerEffort(page);
|
||||
await expect(effortLabel).toHaveText("High");
|
||||
});
|
||||
|
||||
@@ -233,6 +233,57 @@ test("opening an agent focuses the composer when a mouse drives the UI", async (
|
||||
}
|
||||
});
|
||||
|
||||
/** The composer frame's border colour once its border-color transition has finished. */
|
||||
async function readSettledFrameBorder(page: Page): Promise<string> {
|
||||
return composerLocator(page).evaluate(async (input) => {
|
||||
let frame = input.parentElement;
|
||||
while (frame && parseFloat(getComputedStyle(frame).borderTopWidth) < 1) {
|
||||
frame = frame.parentElement;
|
||||
}
|
||||
if (!frame) throw new Error("Composer frame has no border");
|
||||
while (frame.getAnimations().length > 0) {
|
||||
await new Promise((resolve) => requestAnimationFrame(resolve));
|
||||
}
|
||||
return getComputedStyle(frame).borderTopColor;
|
||||
});
|
||||
}
|
||||
|
||||
test("the composer frame shows hover and focus", async ({ page }) => {
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "composer-frame-focus-",
|
||||
title: "Composer frame focus",
|
||||
});
|
||||
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
const composer = composerLocator(page);
|
||||
await expectComposerVisible(page);
|
||||
await page.mouse.move(0, 0);
|
||||
await blurComposerInput(page);
|
||||
const rest = await readSettledFrameBorder(page);
|
||||
|
||||
await composer.hover();
|
||||
const hover = await readSettledFrameBorder(page);
|
||||
expect(hover).not.toBe(rest);
|
||||
|
||||
await composer.click();
|
||||
await page.mouse.move(0, 0);
|
||||
await expectComposerFocused(page);
|
||||
const focus = await readSettledFrameBorder(page);
|
||||
expect(focus).not.toBe(rest);
|
||||
expect(focus).not.toBe(hover);
|
||||
|
||||
await composer.hover();
|
||||
expect(await readSettledFrameBorder(page)).toBe(focus);
|
||||
|
||||
await page.mouse.move(0, 0);
|
||||
await blurComposerInput(page);
|
||||
expect(await readSettledFrameBorder(page)).toBe(rest);
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
async function waitForAnimationFrames(page: Page, count: number): Promise<void> {
|
||||
await page.evaluate(async (frames) => {
|
||||
for (let frame = 0; frame < frames; frame += 1) {
|
||||
|
||||
@@ -3,9 +3,11 @@ import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import { test, expect, type Page } from "../support/fixtures";
|
||||
import { connectDaemonClient } from "../support/helpers/daemon-client-loader";
|
||||
import {
|
||||
clearModelSearchWithEscape,
|
||||
clickModelRowWhileProviderOpens,
|
||||
closeModelPicker,
|
||||
expectModelListScrollKeepsSearchFocused,
|
||||
expectSearchProfilesAtTop,
|
||||
expectModelSearchEmptyState,
|
||||
expectModelPickerHeight,
|
||||
expectModelPickerWidth,
|
||||
@@ -19,7 +21,12 @@ import {
|
||||
seedModelProvider,
|
||||
expectSearchResultsVirtualized,
|
||||
} from "../support/helpers/agent-profiles";
|
||||
import { expectComposerVisible } from "../support/helpers/composer";
|
||||
import {
|
||||
blurComposerInput,
|
||||
expectComposerFocused,
|
||||
expectComposerVisible,
|
||||
} from "../support/helpers/composer";
|
||||
import { openGlobalNewWorkspaceComposer } from "../support/helpers/new-workspace";
|
||||
import { clickNewChat, clickNewTerminal, gotoWorkspace } from "../support/helpers/launcher";
|
||||
import { seedWorkspace } from "../support/helpers/seed-client";
|
||||
|
||||
@@ -56,9 +63,7 @@ const LARGE_CATALOG = {
|
||||
};
|
||||
|
||||
test.describe("Cross-provider model search", () => {
|
||||
test("one query over the picker root reaches every provider and names each result's provider", async ({
|
||||
page,
|
||||
}) => {
|
||||
test("one query reaches every provider and names each result's provider", async ({ page }) => {
|
||||
const provider = await seedModelProvider(STUDIO);
|
||||
const profile = await seedAgentProfiles([ROOT_VIEW_PROFILE]);
|
||||
const workspace = await seedWorkspace({ repoPrefix: "model-search-providers-" });
|
||||
@@ -99,7 +104,7 @@ test.describe("Cross-provider model search", () => {
|
||||
});
|
||||
});
|
||||
|
||||
await test.step("results replace the pinned profiles", async () => {
|
||||
await test.step("results replace the Profiles list", async () => {
|
||||
await expectPinnedProfilesHidden(page);
|
||||
});
|
||||
|
||||
@@ -108,6 +113,10 @@ test.describe("Cross-provider model search", () => {
|
||||
await test.step("a query with no matches repeats the query back", async () => {
|
||||
await searchAllModels(page, "zzz");
|
||||
await expectModelSearchEmptyState(page, "zzz");
|
||||
});
|
||||
|
||||
await test.step("Escape clears the query before it closes the picker", async () => {
|
||||
await clearModelSearchWithEscape(page);
|
||||
await closeModelPicker(page);
|
||||
});
|
||||
} finally {
|
||||
@@ -135,16 +144,23 @@ test.describe("Cross-provider model search", () => {
|
||||
const restingHeight = await readModelPickerHeight(page);
|
||||
const restingWidth = await readModelPickerWidth(page);
|
||||
|
||||
await test.step("a broad query renders only the visible result window", async () => {
|
||||
await test.step("a broad query renders only the visible result window and scrolls without leaving search", async () => {
|
||||
await searchAllModels(page, "bulk model");
|
||||
await expectSearchResultsVirtualized(page, {
|
||||
provider: LARGE_CATALOG.id,
|
||||
total: LARGE_CATALOG_SIZE,
|
||||
});
|
||||
await expectModelListScrollKeepsSearchFocused(page);
|
||||
await expectModelPickerHeight(page, restingHeight);
|
||||
await expectModelPickerWidth(page, restingWidth);
|
||||
});
|
||||
|
||||
await test.step("a new query opens at the top, with the Profiles heading above the matching profile", async () => {
|
||||
// "search" matches the profile's name and every bulk model's description.
|
||||
await searchAllModels(page, "search");
|
||||
await expectSearchProfilesAtTop(page, ROOT_VIEW_PROFILE.id);
|
||||
});
|
||||
|
||||
await test.step("narrowing to one result does not resize the picker", async () => {
|
||||
await searchAllModels(page, "bulk model 199");
|
||||
await expectModelSearchResult(page, {
|
||||
@@ -179,7 +195,7 @@ test.describe("Cross-provider model search", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("arrow keys navigate profiles, providers, models, and search results in the composer", async ({
|
||||
test("arrow keys move between the rail, the model list, and search results in the composer", async ({
|
||||
page,
|
||||
}) => {
|
||||
const provider = await seedModelProvider(STUDIO);
|
||||
@@ -194,7 +210,7 @@ test.describe("Cross-provider model search", () => {
|
||||
const workspace = await seedWorkspace({ repoPrefix: "model-picker-arrows-" });
|
||||
|
||||
try {
|
||||
await test.step("open the composer model picker on the root view", async () => {
|
||||
await test.step("open the composer model picker", async () => {
|
||||
await gotoWorkspace(page, workspace.workspaceId);
|
||||
await clickNewChat(page);
|
||||
await expectComposerVisible(page);
|
||||
@@ -204,32 +220,42 @@ test.describe("Cross-provider model search", () => {
|
||||
const viewport = page.getByTestId("combobox-desktop-container");
|
||||
const trigger = page.getByTestId("combined-model-selector").filter({ visible: true }).first();
|
||||
const profileRow = viewport.getByTestId("model-profile-row-agent_profile_e2e_arrows");
|
||||
const profilesRailRow = viewport.getByTestId("model-picker-rail-profiles");
|
||||
const studioProviderRow = viewport.getByTestId(`model-provider-${STUDIO.id}`);
|
||||
|
||||
await test.step("move from profiles to providers, drill in with ArrowRight, and go back with ArrowLeft", async () => {
|
||||
await expect(profileRow).toHaveAttribute("data-active", "true");
|
||||
// Root view keeps aria-selected absent while keyboard-active uses data-active.
|
||||
await expect(viewport.locator("[aria-selected]")).toHaveCount(0);
|
||||
await test.step("ArrowLeft moves to the rail, ArrowDown opens each entry, ArrowRight enters its list", async () => {
|
||||
await page.keyboard.press("ArrowLeft");
|
||||
// The rail opens what it lands on, so ArrowUp from any provider reaches Profiles.
|
||||
for (let step = 0; step < 10; step += 1) {
|
||||
if ((await profilesRailRow.getAttribute("data-active")) === "true") break;
|
||||
await page.keyboard.press("ArrowUp");
|
||||
}
|
||||
await expect(profilesRailRow).toHaveAttribute("data-active", "true");
|
||||
await expect(profileRow).toBeVisible();
|
||||
|
||||
// Step down until Mock Studio is active (provider order can vary across environments).
|
||||
// Step down until Mock Studio is open (provider order can vary across environments).
|
||||
for (let step = 0; step < 10; step += 1) {
|
||||
if ((await studioProviderRow.getAttribute("data-active")) === "true") break;
|
||||
await page.keyboard.press("ArrowDown");
|
||||
}
|
||||
await expect(studioProviderRow).toHaveAttribute("data-active", "true");
|
||||
|
||||
await page.keyboard.press("ArrowRight");
|
||||
await expect(viewport.getByTestId(`model-row-${STUDIO.id}-studio-fast`)).toBeVisible();
|
||||
|
||||
await page.keyboard.press("ArrowRight");
|
||||
await expect(viewport.getByTestId(`model-row-${STUDIO.id}-studio-fast`)).toHaveAttribute(
|
||||
"data-active",
|
||||
"true",
|
||||
);
|
||||
await page.keyboard.press("ArrowLeft");
|
||||
await expect(studioProviderRow).toHaveAttribute("data-active", "true");
|
||||
await expect(
|
||||
viewport.locator('[data-testid^="model-row-"][data-active="true"]'),
|
||||
).toHaveCount(0);
|
||||
});
|
||||
|
||||
await test.step("Enter drills into the active provider and ArrowDown + Enter selects a model", async () => {
|
||||
await test.step("Enter moves from the rail into the list and ArrowDown + Enter selects a model", async () => {
|
||||
await page.keyboard.press("Enter");
|
||||
const deepRow = viewport.getByTestId(`model-row-${STUDIO.id}-studio-deep`);
|
||||
await expect(deepRow).toBeVisible();
|
||||
await expectModelListScrollKeepsSearchFocused(page);
|
||||
|
||||
for (let step = 0; step < 5; step += 1) {
|
||||
if ((await deepRow.getAttribute("data-active")) === "true") break;
|
||||
@@ -240,6 +266,7 @@ test.describe("Cross-provider model search", () => {
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(viewport).toHaveCount(0);
|
||||
await expect(trigger).toContainText("Studio deep think");
|
||||
await expectComposerFocused(page);
|
||||
});
|
||||
|
||||
await test.step("typing filters results while arrow keys select across search matches", async () => {
|
||||
@@ -258,6 +285,7 @@ test.describe("Cross-provider model search", () => {
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(viewport).toHaveCount(0);
|
||||
await expect(trigger).toContainText("Ten second stream");
|
||||
await expectComposerFocused(page);
|
||||
});
|
||||
|
||||
await test.step("a press on a model row selects it while the provider list is still opening", async () => {
|
||||
@@ -265,27 +293,42 @@ test.describe("Cross-provider model search", () => {
|
||||
await clickModelRowWhileProviderOpens(page, {
|
||||
provider: "mock",
|
||||
modelLabel: "One minute stream",
|
||||
otherProvider: STUDIO.id,
|
||||
});
|
||||
await expect(viewport).toHaveCount(0);
|
||||
await expect(trigger).toContainText("One minute stream");
|
||||
await expectComposerFocused(page);
|
||||
});
|
||||
|
||||
await test.step("Enter on the active profile row applies it", async () => {
|
||||
await openModelPicker(page);
|
||||
await page.keyboard.press("ArrowLeft");
|
||||
for (let step = 0; step < 10; step += 1) {
|
||||
if ((await profilesRailRow.getAttribute("data-active")) === "true") break;
|
||||
await page.keyboard.press("ArrowUp");
|
||||
}
|
||||
await page.keyboard.press("ArrowRight");
|
||||
await expect(profileRow).toHaveAttribute("data-active", "true");
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(viewport).toHaveCount(0);
|
||||
await expect(trigger).toContainText("Ten second stream");
|
||||
await expectComposerFocused(page);
|
||||
});
|
||||
|
||||
await test.step("folded compact sheet also supports Enter on the active profile row", async () => {
|
||||
await test.step("the compact drawer puts Profiles in the Model accordion and lets all groups collapse", async () => {
|
||||
await page.setViewportSize({ width: 390, height: 800 });
|
||||
await page.getByTestId("combined-model-selector").filter({ visible: true }).first().click();
|
||||
await expect(page.getByTestId("agent-controls-profiles")).toHaveCount(0);
|
||||
await page.getByTestId("agent-controls-model").click();
|
||||
await expect(page.getByTestId("compact-model-list")).toBeVisible();
|
||||
await page.locator('[data-testid^="model-provider-section-"]').first().click();
|
||||
await expect(page.getByTestId("compact-model-list")).toHaveCount(0);
|
||||
await page.getByTestId("model-picker-rail-profiles").click();
|
||||
const sheetProfileRow = page.getByTestId("model-profile-row-agent_profile_e2e_arrows");
|
||||
await expect(sheetProfileRow).toBeVisible();
|
||||
await expect(sheetProfileRow).toHaveAttribute("data-active", "true");
|
||||
await page.keyboard.press("Enter");
|
||||
await sheetProfileRow.click();
|
||||
await expect(sheetProfileRow).toHaveCount(0);
|
||||
await expect(page.getByTestId("agent-controls-model-sheet")).not.toBeInViewport();
|
||||
});
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
@@ -293,6 +336,43 @@ test.describe("Cross-provider model search", () => {
|
||||
await provider.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("choosing a model restores composer focus in workspace drafts and New Workspace", async ({
|
||||
page,
|
||||
}) => {
|
||||
const provider = await seedModelProvider(STUDIO);
|
||||
const workspace = await seedWorkspace({ repoPrefix: "model-picker-focus-" });
|
||||
|
||||
try {
|
||||
await test.step("clicking a model after blurring the workspace draft returns focus to the composer", async () => {
|
||||
await gotoWorkspace(page, workspace.workspaceId);
|
||||
await clickNewChat(page);
|
||||
await expectComposerVisible(page);
|
||||
await blurComposerInput(page);
|
||||
await openModelPicker(page);
|
||||
const viewport = page.getByTestId("combobox-desktop-container");
|
||||
await viewport.getByTestId(`model-provider-${STUDIO.id}`).click();
|
||||
await viewport.getByTestId(`model-row-${STUDIO.id}-studio-deep`).click();
|
||||
await expect(viewport).toHaveCount(0);
|
||||
await expectComposerFocused(page);
|
||||
});
|
||||
|
||||
await test.step("clicking a model on the New Workspace screen returns focus to the composer", async () => {
|
||||
await openGlobalNewWorkspaceComposer(page);
|
||||
await expectComposerVisible(page);
|
||||
await blurComposerInput(page);
|
||||
await openModelPicker(page);
|
||||
const viewport = page.getByTestId("combobox-desktop-container");
|
||||
await viewport.getByTestId(`model-provider-${STUDIO.id}`).click();
|
||||
await viewport.getByTestId(`model-row-${STUDIO.id}-studio-fast`).click();
|
||||
await expect(viewport).toHaveCount(0);
|
||||
await expectComposerFocused(page);
|
||||
});
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
await provider.restore();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
async function setRuntimeCatalog(client: DaemonClient, count: number, cwd: string) {
|
||||
@@ -332,7 +412,6 @@ async function reloadSavedDraft(page: Page) {
|
||||
}
|
||||
async function expectOneCatalogChoice(page: Page, label: string) {
|
||||
await openModelPicker(page);
|
||||
await page.getByRole("button", { name: "Back", exact: true }).click();
|
||||
await searchAllModels(page, label);
|
||||
await expect(page.getByTestId("model-row-gemini-gemini-3.5-flash")).toHaveCount(1);
|
||||
await closeModelPicker(page);
|
||||
|
||||
@@ -34,7 +34,6 @@ async function rememberModel(page: Page) {
|
||||
|
||||
async function expectRecoveredModelInPicker(page: Page) {
|
||||
await openModelPicker(page);
|
||||
await page.getByRole("dialog").getByRole("button", { name: "Back", exact: true }).click();
|
||||
await drillIntoProvider(page, PROVIDER);
|
||||
await expect(
|
||||
page.getByTestId("combobox-desktop-container").getByText(LABEL, { exact: true }),
|
||||
|
||||
@@ -26,16 +26,14 @@ async function openProviderSettingsFromModelSelector(page: Page) {
|
||||
const configuration = page.getByTestId("agent-controls-model-sheet");
|
||||
await expect(configuration).toBeVisible({ timeout: 10_000 });
|
||||
await page.getByTestId("agent-controls-model").click();
|
||||
|
||||
const modelBrowser = page.getByTestId("agent-controls-model-browser-sheet");
|
||||
await expect(modelBrowser).toBeVisible({ timeout: 10_000 });
|
||||
await expect(page.getByTestId("mobile-model-page")).toBeVisible({ timeout: 10_000 });
|
||||
|
||||
await page.getByRole("button", { name: /Open .* settings/ }).click();
|
||||
await expect(page.getByTestId("provider-settings-sheet")).toBeVisible({ timeout: 10_000 });
|
||||
}
|
||||
|
||||
async function expectModelBrowserVisible(page: Page) {
|
||||
await expect(page.getByTestId("agent-controls-model-browser-sheet")).toBeVisible({
|
||||
async function expectModelPageVisible(page: Page) {
|
||||
await expect(page.getByTestId("mobile-model-page")).toBeVisible({
|
||||
timeout: 10_000,
|
||||
});
|
||||
await expect(page.getByRole("button", { name: /Open .* settings/ })).toBeVisible();
|
||||
@@ -187,7 +185,7 @@ test.describe("provider settings overlay stack", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("provider settings and children close back through the model browser to configuration", async ({
|
||||
test("provider settings and children close back to the Model page, then Back reaches Home", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(180_000);
|
||||
@@ -199,17 +197,15 @@ test.describe("provider settings overlay stack", () => {
|
||||
await exerciseProviderSettingsStack(page);
|
||||
await closeSheetByHeaderButton(page, "provider-settings-sheet");
|
||||
|
||||
await expectModelBrowserVisible(page);
|
||||
await expectModelPageVisible(page);
|
||||
await page.getByRole("button", { name: /Open .* settings/ }).click();
|
||||
await expect(page.getByTestId("provider-settings-sheet")).toBeVisible({ timeout: 10_000 });
|
||||
await exerciseProviderSettingsStack(page);
|
||||
await closeSheetByHeaderButton(page, "provider-settings-sheet");
|
||||
|
||||
await expectModelBrowserVisible(page);
|
||||
await closeTopSheet(page);
|
||||
await expect(page.getByTestId("agent-controls-model-browser-sheet")).not.toBeVisible({
|
||||
timeout: 10_000,
|
||||
});
|
||||
await expectModelPageVisible(page);
|
||||
await page.getByTestId("sheet-header-back").click();
|
||||
await expect(page.getByTestId("mobile-model-page")).toHaveCount(0);
|
||||
await expect(page.getByTestId("agent-controls-settings-list")).toBeVisible();
|
||||
await closeTopSheet(page);
|
||||
} finally {
|
||||
@@ -226,8 +222,6 @@ async function openTimedOutProvider(page: Page, workspaceId: string, width: numb
|
||||
await page.getByRole("button", { name: /Select model/ }).click();
|
||||
if (width < 600) {
|
||||
await page.getByTestId("agent-controls-model").click();
|
||||
} else {
|
||||
await page.getByRole("button", { name: "Back", exact: true }).click();
|
||||
}
|
||||
await page.getByTestId("model-provider-picker-timeout").click();
|
||||
await expect(page.getByText(/Timed out refreshing Pi timeout/)).toBeVisible();
|
||||
|
||||
@@ -13,8 +13,12 @@ import { test, expect } from "../support/fixtures";
|
||||
import { expectComposerVisible } from "../support/helpers/composer";
|
||||
import { withDirectoryPlugin } from "../support/helpers/plugin-timeline";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
import { getE2EDaemonPort } from "../support/helpers/daemon-port";
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
||||
|
||||
test.use({
|
||||
e2eInjectPaseoTools: true,
|
||||
e2eDaemonConfig: {
|
||||
version: 1,
|
||||
agents: {
|
||||
@@ -290,6 +294,89 @@ test("received messages show their sender and open that agent", async ({ page })
|
||||
}
|
||||
});
|
||||
|
||||
/** Calls a Paseo MCP tool as `callerAgentId`, the way that agent's provider would. */
|
||||
async function callPaseoToolAs(
|
||||
callerAgentId: string,
|
||||
name: string,
|
||||
args: Record<string, unknown>,
|
||||
): Promise<Record<string, unknown>> {
|
||||
const mcp = new Client({ name: "turn-collapse-e2e", version: "1" });
|
||||
await mcp.connect(
|
||||
new StreamableHTTPClientTransport(
|
||||
new URL(`http://127.0.0.1:${getE2EDaemonPort()}/mcp/agents?callerAgentId=${callerAgentId}`),
|
||||
),
|
||||
);
|
||||
try {
|
||||
const response = await mcp.callTool({ name, arguments: args });
|
||||
expect(response, name).not.toMatchObject({ isError: true });
|
||||
return response.structuredContent as Record<string, unknown>;
|
||||
} finally {
|
||||
await mcp.close();
|
||||
}
|
||||
}
|
||||
|
||||
test("a delegated child reports each turn end as a compact tool call until its own delegate is done", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
const frames: string[] = [];
|
||||
page.on("websocket", (socket) => {
|
||||
socket.on("framereceived", ({ payload }) => {
|
||||
if (typeof payload === "string") frames.push(payload);
|
||||
});
|
||||
});
|
||||
const childNoticeFrames = () => frames.filter((frame) => frame.includes('"label":"Child"'));
|
||||
const parent = await seedMockAgentWorkspace({ repoPrefix: "child-notices-", title: "Lead" });
|
||||
try {
|
||||
await openAgentRoute(page, parent);
|
||||
await expectComposerVisible(page);
|
||||
const child = await callPaseoToolAs(parent.agentId, "create_agent", {
|
||||
workspaceId: parent.workspaceId,
|
||||
title: "Child",
|
||||
provider: "mock/e2e-fast-stream",
|
||||
settings: { modeId: "load-test" },
|
||||
initialPrompt: "Delegate the slow part",
|
||||
});
|
||||
const childId = String(child.agentId);
|
||||
// The child's own delegate outlives the child's first turn.
|
||||
const grandchild = await callPaseoToolAs(childId, "create_agent", {
|
||||
workspaceId: parent.workspaceId,
|
||||
title: "Grandchild",
|
||||
provider: "mock/ten-second-stream",
|
||||
settings: { modeId: "load-test" },
|
||||
initialPrompt: "Take your time",
|
||||
});
|
||||
const notices = page.getByRole("button", { name: /^Agent .*Child/ });
|
||||
const finished = page.getByRole("button", { name: /^Agent finished.*Child/ });
|
||||
|
||||
// The child ended its turn while waiting on its delegate: the parent hears it now.
|
||||
await expect(finished).toHaveCount(1, { timeout: 30_000 });
|
||||
const delegate = await parent.client.waitForAgentUpsert(String(grandchild.agentId), () => true);
|
||||
expect(delegate.status, "the delegate must still be running").toBe("running");
|
||||
expect(
|
||||
childNoticeFrames().some((frame) => frame.includes("It still has agents it is waiting on.")),
|
||||
).toBe(true);
|
||||
|
||||
// The delegate reports to the child, and the child's settled turn reaches the parent.
|
||||
await expect(finished).toHaveCount(2, { timeout: 60_000 });
|
||||
await expect(notices).toHaveCount(2);
|
||||
await expect(page.getByText(/still working/i)).toHaveCount(0);
|
||||
await expect(page.getByText(/Sent by/)).toHaveCount(0);
|
||||
await expect(page.getByText(/<agent-response>/)).toHaveCount(0);
|
||||
await finished.last().scrollIntoViewIfNeeded();
|
||||
await page.screenshot({ path: testInfo.outputPath("child-notices.png") });
|
||||
// Notification events stay on the daemon: clients get only plain tool calls.
|
||||
expect(frames.filter((frame) => frame.includes('"agentMessage"'))).toEqual([]);
|
||||
expect(childNoticeFrames().some((frame) => frame.includes('"name":"agent_finished"'))).toBe(
|
||||
true,
|
||||
);
|
||||
expect(childNoticeFrames().filter((frame) => /"name":"agent_(?!finished)/.test(frame))).toEqual(
|
||||
[],
|
||||
);
|
||||
} finally {
|
||||
await parent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("long sender attribution stays on one line in compact chat", async ({ page }, testInfo) => {
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await page.addInitScript(() =>
|
||||
|
||||
@@ -587,7 +587,12 @@ export async function openModelPicker(page: Page): Promise<void> {
|
||||
await expect(pickerViewport(page)).toBeVisible({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
/** Escape clears a typed query first; the next Escape closes the picker. */
|
||||
export async function closeModelPicker(page: Page): Promise<void> {
|
||||
const search = pickerViewport(page).getByTestId("model-search-input");
|
||||
if ((await search.count()) > 0 && (await search.inputValue()) !== "") {
|
||||
await clearModelSearchWithEscape(page);
|
||||
}
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(pickerViewport(page)).toHaveCount(0, { timeout: 30_000 });
|
||||
}
|
||||
@@ -598,70 +603,40 @@ export function profilePickerRow(page: Page, name: string): Locator {
|
||||
.filter({ hasText: name });
|
||||
}
|
||||
|
||||
/**
|
||||
* Profiles are pinned above the provider list, so "pinned" is an ordering claim:
|
||||
* the profile row's top edge sits above every provider row's.
|
||||
*/
|
||||
export async function expectProfilePinnedAboveProviders(
|
||||
page: Page,
|
||||
input: { name: string; summary: string },
|
||||
): Promise<void> {
|
||||
const viewport = pickerViewport(page);
|
||||
await expect(viewport.getByText("Profiles", { exact: true })).toBeVisible({ timeout: 30_000 });
|
||||
const row = profilePickerRow(page, input.name);
|
||||
await expect(row).toBeVisible({ timeout: 30_000 });
|
||||
await expect(row.getByText(input.summary, { exact: true })).toBeVisible();
|
||||
|
||||
const profileTop = await boxTop(row);
|
||||
const providerRows = viewport.locator('[data-testid^="model-provider-"]');
|
||||
await expect(providerRows.first()).toBeVisible();
|
||||
const providerCount = await providerRows.count();
|
||||
for (let index = 0; index < providerCount; index += 1) {
|
||||
expect(profileTop).toBeLessThan(await boxTop(providerRows.nth(index)));
|
||||
}
|
||||
/** Desktop keeps profiles behind the rail's Profiles entry, beside the providers. */
|
||||
export async function openPickerProfiles(page: Page): Promise<void> {
|
||||
await pickerViewport(page).getByTestId("model-picker-rail-profiles").click();
|
||||
}
|
||||
|
||||
export async function expectProfileVisibleForProvider(
|
||||
export async function expectPickerProfile(
|
||||
page: Page,
|
||||
input: { name: string; summary: string },
|
||||
): Promise<void> {
|
||||
const viewport = pickerViewport(page);
|
||||
await expect(viewport.getByText("Profiles", { exact: true })).toBeVisible({ timeout: 30_000 });
|
||||
await openPickerProfiles(page);
|
||||
const row = profilePickerRow(page, input.name);
|
||||
await expect(row).toBeVisible({ timeout: 30_000 });
|
||||
await expect(row.getByText(input.summary, { exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
export async function expectProfileEditIsPencilOnly(page: Page): Promise<void> {
|
||||
const viewport = pickerViewport(page);
|
||||
await expect(
|
||||
viewport.getByRole("button", { name: "Edit agent profiles", exact: true }),
|
||||
).toBeVisible();
|
||||
await expect(viewport.getByText("Edit", { exact: true })).toHaveCount(0);
|
||||
}
|
||||
|
||||
export async function expectAgentProfilesEmptyPrompt(page: Page): Promise<void> {
|
||||
const viewport = pickerViewport(page);
|
||||
await expect(viewport.getByText("Profiles", { exact: true })).toHaveCount(0);
|
||||
await expect(
|
||||
viewport.getByRole("button", { name: "Edit agent profiles", exact: true }),
|
||||
).toHaveCount(0);
|
||||
await expect(viewport.getByRole("button", { name: "Create profile", exact: true })).toBeVisible({
|
||||
timeout: 30_000,
|
||||
});
|
||||
}
|
||||
|
||||
export async function expectProfileEditTooltip(page: Page): Promise<void> {
|
||||
export async function expectProfilesEditLink(page: Page): Promise<void> {
|
||||
const edit = pickerViewport(page).getByRole("button", {
|
||||
name: "Edit agent profiles",
|
||||
exact: true,
|
||||
});
|
||||
await edit.hover();
|
||||
await expect(page.getByText("Edit agent profiles", { exact: true })).toBeVisible();
|
||||
await expect(edit).toBeVisible();
|
||||
await expect(edit).toHaveText("Edit");
|
||||
}
|
||||
|
||||
/** With no profiles, the Profiles entry offers to create one instead of listing any. */
|
||||
export async function expectAgentProfilesEmptyPrompt(page: Page): Promise<void> {
|
||||
await openPickerProfiles(page);
|
||||
const viewport = pickerViewport(page);
|
||||
await expect(viewport.locator('[data-testid^="model-profile-row-"]')).toHaveCount(0);
|
||||
await expect(viewport.getByTestId("model-profiles-empty")).toBeVisible({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
export async function openAgentProfilesFromEmptyPrompt(page: Page): Promise<void> {
|
||||
await pickerViewport(page).getByRole("button", { name: "Create profile", exact: true }).click();
|
||||
await pickerViewport(page).getByTestId("model-profiles-empty").click();
|
||||
await expect(page.getByTestId("agent-profiles-card")).toBeVisible({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
@@ -709,25 +684,17 @@ export async function expectProfileReachableByScrolling(page: Page, name: string
|
||||
}
|
||||
|
||||
export async function applyProfileFromPicker(page: Page, name: string): Promise<void> {
|
||||
await profilePickerRow(page, name).click();
|
||||
const row = profilePickerRow(page, name);
|
||||
if (!(await row.isVisible().catch(() => false))) {
|
||||
const profilesRail = pickerViewport(page).getByTestId("model-picker-rail-profiles");
|
||||
if (await profilesRail.isVisible().catch(() => false)) {
|
||||
await profilesRail.click();
|
||||
}
|
||||
}
|
||||
await row.click();
|
||||
await expect(pickerViewport(page)).toHaveCount(0, { timeout: 30_000 });
|
||||
}
|
||||
|
||||
/**
|
||||
* Applying a profile materializes it and forgets it: nothing in the root view
|
||||
* claims selection. Model rows do carry `aria-selected`, so a count of zero here
|
||||
* is the absence of a checkmark, not the absence of the attribute everywhere.
|
||||
*/
|
||||
export async function expectNothingSelectedInPickerRoot(page: Page): Promise<void> {
|
||||
await expect(pickerViewport(page).locator("[aria-selected]")).toHaveCount(0);
|
||||
}
|
||||
|
||||
export async function expectAgentProfilesEditShortcut(page: Page): Promise<void> {
|
||||
await expect(
|
||||
pickerViewport(page).getByRole("button", { name: "Edit agent profiles", exact: true }),
|
||||
).toBeVisible({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
export async function drillIntoProvider(page: Page, providerId: string): Promise<void> {
|
||||
await pickerViewport(page).getByTestId(`model-provider-${providerId}`).click();
|
||||
}
|
||||
@@ -798,13 +765,13 @@ export async function selectModelRow(
|
||||
*/
|
||||
export async function clickModelRowWhileProviderOpens(
|
||||
page: Page,
|
||||
input: { provider: string; modelLabel: string },
|
||||
input: { provider: string; modelLabel: string; otherProvider: string },
|
||||
): Promise<void> {
|
||||
const viewport = pickerViewport(page);
|
||||
await drillIntoProvider(page, input.provider);
|
||||
const rowBox = await viewport.getByText(input.modelLabel, { exact: true }).boundingBox();
|
||||
if (!rowBox) throw new Error(`Model row ${input.modelLabel} has no box`);
|
||||
await viewport.getByRole("button", { name: "Back", exact: true }).click();
|
||||
await drillIntoProvider(page, input.otherProvider);
|
||||
|
||||
const cdp = await page.context().newCDPSession(page);
|
||||
await cdp.send("Emulation.setCPUThrottlingRate", { rate: 10 });
|
||||
@@ -822,7 +789,7 @@ export async function clickModelRowWhileProviderOpens(
|
||||
/** Scrolling a provider's model list with the wheel leaves typing and Enter in the search field. */
|
||||
export async function expectModelListScrollKeepsSearchFocused(page: Page): Promise<void> {
|
||||
const search = pickerViewport(page).getByTestId("model-search-input");
|
||||
const list = pickerViewport(page).getByTestId("compact-model-list");
|
||||
const list = pickerViewport(page).getByTestId("model-picker-model-list");
|
||||
await expect(search).toBeFocused();
|
||||
await list.hover();
|
||||
await page.mouse.wheel(0, 200);
|
||||
@@ -833,11 +800,18 @@ export async function expectModelListScrollKeepsSearchFocused(page: Page): Promi
|
||||
// ─── Cross-provider model search ───────────────────────────────────────────
|
||||
|
||||
export async function searchAllModels(page: Page, query: string): Promise<void> {
|
||||
const input = page.getByTestId("model-search-all-input");
|
||||
const input = pickerViewport(page).getByTestId("model-search-input");
|
||||
await expect(input).toBeVisible({ timeout: 30_000 });
|
||||
await input.fill(query);
|
||||
}
|
||||
|
||||
/** Search results open at the top, with the Profiles heading above the first matching profile. */
|
||||
export async function expectSearchProfilesAtTop(page: Page, profileId: string): Promise<void> {
|
||||
const list = pickerViewport(page).getByTestId("model-picker-model-list");
|
||||
await expect(list.getByText("Profiles", { exact: true })).toBeInViewport({ ratio: 1 });
|
||||
await expect(list.getByTestId(`model-profile-row-${profileId}`)).toBeInViewport({ ratio: 1 });
|
||||
}
|
||||
|
||||
export async function expectModelSearchResult(
|
||||
page: Page,
|
||||
expected: { provider: string; modelId: string; providerLabel: string; modelLabel: string },
|
||||
@@ -856,11 +830,19 @@ function escapeForRegex(value: string): string {
|
||||
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
}
|
||||
|
||||
/** Search results replace the whole root view, pinned profiles included. */
|
||||
/** Search results replace both panes, the Profiles list included. */
|
||||
export async function expectPinnedProfilesHidden(page: Page): Promise<void> {
|
||||
await expect(pickerViewport(page).locator('[data-testid^="model-profile-row-"]')).toHaveCount(0);
|
||||
}
|
||||
|
||||
export async function clearModelSearchWithEscape(page: Page): Promise<void> {
|
||||
const search = pickerViewport(page).getByTestId("model-search-input");
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(search).toHaveValue("");
|
||||
await expect(search).toBeFocused();
|
||||
await expect(pickerViewport(page)).toBeVisible();
|
||||
}
|
||||
|
||||
export async function expectModelSearchEmptyState(page: Page, query: string): Promise<void> {
|
||||
const empty = page.getByTestId("model-search-empty");
|
||||
await expect(empty).toBeVisible({ timeout: 30_000 });
|
||||
|
||||
@@ -362,8 +362,8 @@ export const selectModel = async (page: Page, model: string) => {
|
||||
// Type to search/filter models
|
||||
await searchInput.fill(normalizedModel);
|
||||
|
||||
const dialog = page.getByRole("dialog");
|
||||
const exactOption = dialog
|
||||
const viewport = page.getByTestId("combobox-desktop-container").or(page.getByRole("dialog"));
|
||||
const exactOption = viewport
|
||||
.getByText(new RegExp(`^${escapeRegex(normalizedModel)}$`, "i"))
|
||||
.first();
|
||||
const exactVisible = await exactOption.isVisible().catch(() => false);
|
||||
@@ -375,8 +375,10 @@ export const selectModel = async (page: Page, model: string) => {
|
||||
await searchInput.press("Enter");
|
||||
}
|
||||
|
||||
// Wait for dropdown to close
|
||||
if (await searchInput.isVisible().catch(() => false)) {
|
||||
// Wait for dropdown to close; when a query has no match, the first Escape clears the query
|
||||
// and the second closes the picker.
|
||||
for (let attempt = 0; attempt < 2; attempt += 1) {
|
||||
if (!(await searchInput.isVisible().catch(() => false))) break;
|
||||
await page.keyboard.press("Escape").catch(() => undefined);
|
||||
}
|
||||
await expect(searchInput).not.toBeVisible({ timeout: 5000 });
|
||||
|
||||
@@ -17,7 +17,6 @@ export async function chooseModel(page: Page, provider: string, label: string) {
|
||||
export async function reselectModel(page: Page, provider: string, label: string) {
|
||||
await expectRememberedModel(page, label);
|
||||
await openModelPicker(page);
|
||||
await page.getByRole("dialog").getByRole("button", { name: "Back", exact: true }).click();
|
||||
await selectProviderModel(page, provider, label);
|
||||
}
|
||||
|
||||
|
||||
@@ -44,9 +44,8 @@ async function expectProviderIcon(surface: Locator, paths: string[]): Promise<vo
|
||||
|
||||
async function selectPluginModel(page: Page): Promise<void> {
|
||||
await openModelPicker(page);
|
||||
await page.getByRole("button", { name: "Back", exact: true }).click();
|
||||
await page.getByText("Direct provider example", { exact: true }).click();
|
||||
await page.getByText("Example 1", { exact: true }).click();
|
||||
await page.getByTestId("model-provider-direct-example").click();
|
||||
await page.getByTestId("model-row-direct-example-example-1").click();
|
||||
await expect(page.getByRole("button", { name: MODEL_LABEL, exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
|
||||
@@ -463,16 +463,15 @@ export async function delegateFleetThroughMcp() {
|
||||
direction: "tail",
|
||||
limit: 100,
|
||||
});
|
||||
return timeline.entries
|
||||
.flatMap(({ item }) =>
|
||||
item.type === "tool_call" && item.agentMessage ? [item.agentMessage] : [],
|
||||
)
|
||||
.filter(
|
||||
(message) =>
|
||||
message.event === "finished" &&
|
||||
message.sender.id === child.agentId &&
|
||||
message.text.includes(`Server: ${child.serverId}`),
|
||||
).length;
|
||||
return timeline.entries.filter(
|
||||
({ item }) =>
|
||||
item.type === "tool_call" &&
|
||||
item.name === "agent_finished" &&
|
||||
item.detail.type === "plain_text" &&
|
||||
item.detail.label === child.title &&
|
||||
item.detail.text?.includes(child.agentId) &&
|
||||
item.detail.text.includes(`Server: ${child.serverId}`),
|
||||
).length;
|
||||
})
|
||||
.toBe(1);
|
||||
},
|
||||
|
||||
@@ -783,6 +783,56 @@ it("presents received agent messages as attributed bubbles with the original tur
|
||||
});
|
||||
});
|
||||
|
||||
it("presents a finished notification as a compact tool call, not a received message", () => {
|
||||
const call = toolCall("notice", "agent_finished");
|
||||
if (call.payload.source !== "agent") throw new Error("Expected agent tool");
|
||||
call.payload.data.detail = {
|
||||
type: "plain_text",
|
||||
label: "Child",
|
||||
text: "Agent child (Child) finished.",
|
||||
icon: "bot",
|
||||
};
|
||||
const result = createStreamPresentation()({
|
||||
...presentationOptions,
|
||||
transform: undefined,
|
||||
tail: [call],
|
||||
head: [],
|
||||
});
|
||||
expect(result.tail).toEqual([call]);
|
||||
});
|
||||
|
||||
// COMPAT(agentNotificationMetadata): rows from daemons that sent notification metadata.
|
||||
it("presents a legacy notification as the plain tool call current daemons send", () => {
|
||||
const call = toolCall("legacy", "agent_message");
|
||||
if (call.payload.source !== "agent") throw new Error("Expected agent tool");
|
||||
call.turnId = "turn";
|
||||
call.payload.data.detail = { type: "plain_text", text: "Done", icon: "bot" };
|
||||
call.payload.data.agentMessage = {
|
||||
event: "finished",
|
||||
sender: { id: "child", title: "Child" },
|
||||
text: "Done",
|
||||
};
|
||||
const result = createStreamPresentation()({
|
||||
...presentationOptions,
|
||||
transform: undefined,
|
||||
tail: [call],
|
||||
head: [],
|
||||
});
|
||||
expect(result.tail).toHaveLength(1);
|
||||
const [presented] = result.tail;
|
||||
if (presented?.kind !== "tool_call" || presented.payload.source !== "agent")
|
||||
throw new Error("Expected agent tool");
|
||||
expect(presented).toMatchObject({ id: call.id, turnId: "turn" });
|
||||
expect(presented.payload.data).toEqual({
|
||||
provider: "codex",
|
||||
callId: "legacy",
|
||||
name: "agent_finished",
|
||||
status: "completed",
|
||||
error: null,
|
||||
detail: { type: "plain_text", label: "Child", text: "Done", icon: "bot" },
|
||||
});
|
||||
});
|
||||
|
||||
it("does not reopen the previous turn while a new run waits for its first row", () => {
|
||||
const timestamp = new Date();
|
||||
const tail: StreamItem[] = [
|
||||
|
||||
@@ -9,7 +9,14 @@ import {
|
||||
type ToolCallDetailLevel,
|
||||
type ToolCallDetailProjection,
|
||||
} from "@/tool-calls/detail-level/projection";
|
||||
import type { StreamItem, UserMessageItem } from "@/types/stream";
|
||||
import type { AgentMessage } from "@getpaseo/protocol/agent-message";
|
||||
import { legacyAgentNotificationToolCall } from "@getpaseo/protocol/paseo-tool-presentation/index";
|
||||
import {
|
||||
isAgentToolCallItem,
|
||||
type AgentToolCallItem,
|
||||
type StreamItem,
|
||||
type UserMessageItem,
|
||||
} from "@/types/stream";
|
||||
import { collapseTurns, type TurnCollapse } from "./turn-collapse/model";
|
||||
import type { ReadingRowReplacements } from "./reading-anchor";
|
||||
|
||||
@@ -56,6 +63,7 @@ const NO_COLLAPSED_TURNS: StreamPresentation["turns"] = collapseTurns({
|
||||
/** Source messages reach plugins before display projection. */
|
||||
export function createStreamPresentation() {
|
||||
const userMessageCache = new WeakMap<UserMessageItem, UserMessageItem>();
|
||||
const legacyNotificationCache = new WeakMap<AgentToolCallItem, AgentToolCallItem>();
|
||||
|
||||
function presentUserMessage(item: UserMessageItem): UserMessageItem {
|
||||
const cached = userMessageCache.get(item);
|
||||
@@ -72,6 +80,19 @@ export function createStreamPresentation() {
|
||||
return projected;
|
||||
}
|
||||
|
||||
// COMPAT(agentNotificationMetadata): added in v0.18.1, remove after 2027-06-01.
|
||||
function presentLegacyNotification(item: AgentToolCallItem, message: AgentMessage): StreamItem {
|
||||
const cached = legacyNotificationCache.get(item);
|
||||
if (cached) return cached;
|
||||
const { agentMessage: _legacy, ...data } = item.payload.data;
|
||||
const presented: AgentToolCallItem = {
|
||||
...item,
|
||||
payload: { source: "agent", data: { ...data, ...legacyAgentNotificationToolCall(message) } },
|
||||
};
|
||||
legacyNotificationCache.set(item, presented);
|
||||
return presented;
|
||||
}
|
||||
|
||||
let historySource: StreamItem[] | undefined;
|
||||
let historyTransform: TimelineItemTransform | undefined;
|
||||
let historyRows: StreamItem[] = [];
|
||||
@@ -86,7 +107,7 @@ export function createStreamPresentation() {
|
||||
let collapsed: TurnCollapse | undefined;
|
||||
|
||||
function presentRows(item: StreamItem): StreamItem[] {
|
||||
if (item.kind === "tool_call" && item.payload.source === "agent") {
|
||||
if (isAgentToolCallItem(item)) {
|
||||
const message = item.payload.data.agentMessage;
|
||||
if (message?.event === "message") {
|
||||
return [
|
||||
@@ -101,6 +122,7 @@ export function createStreamPresentation() {
|
||||
},
|
||||
];
|
||||
}
|
||||
if (message) return [presentLegacyNotification(item, message)];
|
||||
}
|
||||
return [item.kind === "user_message" ? presentUserMessage(item) : item];
|
||||
}
|
||||
|
||||
@@ -22,10 +22,35 @@ function row(index: number, height = ROW_HEIGHT): Extract<StreamItem, { kind: "u
|
||||
};
|
||||
}
|
||||
|
||||
function assistantRow(
|
||||
index: number,
|
||||
height = ROW_HEIGHT,
|
||||
): Extract<StreamItem, { kind: "assistant_message" }> {
|
||||
return {
|
||||
kind: "assistant_message",
|
||||
id: `assistant-${index}`,
|
||||
text: String(height),
|
||||
timestamp: new Date(`2026-04-20T00:00:${String(index % 60).padStart(2, "0")}.000Z`),
|
||||
};
|
||||
}
|
||||
|
||||
function thoughtRow(index: number, height = ROW_HEIGHT): Extract<StreamItem, { kind: "thought" }> {
|
||||
return {
|
||||
kind: "thought",
|
||||
id: `thought-${index}`,
|
||||
text: String(height),
|
||||
status: "ready",
|
||||
timestamp: new Date(`2026-04-20T00:00:${String(index % 60).padStart(2, "0")}.000Z`),
|
||||
};
|
||||
}
|
||||
|
||||
const rowStyleByHeight = new Map<number, { height: number }>();
|
||||
|
||||
function renderRow(item: StreamItem) {
|
||||
const height = item.kind === "user_message" ? Number(item.text) : ROW_HEIGHT;
|
||||
const height =
|
||||
item.kind === "user_message" || item.kind === "assistant_message" || item.kind === "thought"
|
||||
? Number(item.text)
|
||||
: ROW_HEIGHT;
|
||||
let style = rowStyleByHeight.get(height);
|
||||
if (!style) {
|
||||
style = { height };
|
||||
@@ -57,18 +82,30 @@ type OlderHistoryInput = Pick<
|
||||
interface MountTimelineOptions {
|
||||
olderHistory?: OlderHistoryInput;
|
||||
isMobileBreakpoint?: boolean;
|
||||
historyVirtualized?: StreamItem[];
|
||||
viewportHeight?: number;
|
||||
}
|
||||
|
||||
function mountTimeline(
|
||||
historyMounted: StreamItem[],
|
||||
{ olderHistory, isMobileBreakpoint = true }: MountTimelineOptions = {},
|
||||
{
|
||||
olderHistory,
|
||||
isMobileBreakpoint = true,
|
||||
historyVirtualized = [],
|
||||
viewportHeight = VIEWPORT_HEIGHT,
|
||||
}: MountTimelineOptions = {},
|
||||
) {
|
||||
host.style.height = `${viewportHeight}px`;
|
||||
const strategy = createWebStreamStrategy({ isMobileBreakpoint });
|
||||
const viewportRef = React.createRef<StreamViewportHandle>();
|
||||
const input: StreamRenderInput = {
|
||||
let currentInput: StreamRenderInput = {
|
||||
agentId: "agent",
|
||||
segments: { historyVirtualized: [], historyMounted, liveHead: [] },
|
||||
boundary: { hasVirtualizedHistory: false, hasMountedHistory: true, hasLiveHead: false },
|
||||
segments: { historyVirtualized, historyMounted, liveHead: [] },
|
||||
boundary: {
|
||||
hasVirtualizedHistory: historyVirtualized.length > 0,
|
||||
hasMountedHistory: historyMounted.length > 0,
|
||||
hasLiveHead: false,
|
||||
},
|
||||
renderers: {
|
||||
renderHistoryVirtualizedRow: renderRow,
|
||||
renderHistoryMountedRow: renderRow,
|
||||
@@ -91,8 +128,23 @@ function mountTimeline(
|
||||
contentMaxWidth: DEFAULT_CONTENT_MAX_WIDTH,
|
||||
...olderHistory,
|
||||
};
|
||||
const render = (segments: Partial<StreamRenderInput["segments"]>) =>
|
||||
root.render(strategy.render({ ...input, segments: { ...input.segments, ...segments } }));
|
||||
const render = (
|
||||
segments: Partial<StreamRenderInput["segments"]>,
|
||||
overrides: Partial<Omit<StreamRenderInput, "segments">> = {},
|
||||
) => {
|
||||
const nextSegments = { ...currentInput.segments, ...segments };
|
||||
currentInput = {
|
||||
...currentInput,
|
||||
...overrides,
|
||||
segments: nextSegments,
|
||||
boundary: {
|
||||
hasVirtualizedHistory: nextSegments.historyVirtualized.length > 0,
|
||||
hasMountedHistory: nextSegments.historyMounted.length > 0,
|
||||
hasLiveHead: nextSegments.liveHead.length > 0,
|
||||
},
|
||||
};
|
||||
root.render(strategy.render(currentInput));
|
||||
};
|
||||
act(() => render({}));
|
||||
|
||||
const scrollContainer = host.querySelector<HTMLElement>('[data-testid="agent-chat-scroll"]');
|
||||
@@ -104,7 +156,10 @@ function mountTimeline(
|
||||
};
|
||||
|
||||
return {
|
||||
render: (segments: Partial<StreamRenderInput["segments"]>) => act(() => render(segments)),
|
||||
render: (
|
||||
segments: Partial<StreamRenderInput["segments"]>,
|
||||
overrides?: Partial<Omit<StreamRenderInput, "segments">>,
|
||||
) => act(() => render(segments, overrides)),
|
||||
hold: (rowId: string, apply: () => void, triggerEdge: DisclosureTriggerEdge = "top") =>
|
||||
act(() => viewportRef.current!.holdRow(rowId, apply, triggerEdge)),
|
||||
rowTop: (id: string) =>
|
||||
@@ -129,9 +184,9 @@ function mountTimeline(
|
||||
scrollContainer.dispatchEvent(new Event("scroll"));
|
||||
}),
|
||||
// Resize observers and the hold's settle run on animation frames.
|
||||
settle: () =>
|
||||
settle: (frames = 4) =>
|
||||
act(async () => {
|
||||
for (let frame = 0; frame < 4; frame += 1) {
|
||||
for (let frame = 0; frame < frames; frame += 1) {
|
||||
await new Promise((resolve) => requestAnimationFrame(resolve));
|
||||
}
|
||||
}),
|
||||
@@ -310,3 +365,148 @@ describe("web history start", () => {
|
||||
expect(olderHistoryLoads).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("web virtualizer reconcile stability", () => {
|
||||
it("settles without nested update loops when virtualized rows grow far past estimates above a mounted anchor", async () => {
|
||||
const mounted = Array.from({ length: 10 }, (_, index) => row(500 + index));
|
||||
const timeline = mountTimeline(mounted, { viewportHeight: 200 });
|
||||
await timeline.settle();
|
||||
timeline.scrollUp(200);
|
||||
await timeline.settle();
|
||||
const readingTop = timeline.rowTop("message-500");
|
||||
|
||||
const virtualized = Array.from({ length: 500 }, (_, index) => thoughtRow(index, 800));
|
||||
timeline.render({ historyVirtualized: virtualized, historyMounted: mounted });
|
||||
await timeline.settle();
|
||||
|
||||
expect(timeline.rowTop("message-500")).toBe(readingTop);
|
||||
expect(timeline.rowBottom("thought-499")).toBe(readingTop);
|
||||
});
|
||||
|
||||
it("does not overflow React update depth via reconcileReadingPosition when growing virtualized rows reach the start on desktop", async () => {
|
||||
const mounted = Array.from({ length: 10 }, (_, index) => row(400 + index));
|
||||
const timeline = mountTimeline(mounted, {
|
||||
viewportHeight: 200,
|
||||
isMobileBreakpoint: false,
|
||||
});
|
||||
await timeline.settle();
|
||||
timeline.scrollUp(200);
|
||||
await timeline.settle();
|
||||
const readingTop = timeline.rowTop("message-400");
|
||||
|
||||
const virtualized = Array.from({ length: 170 }, (_, index) => thoughtRow(index, 800));
|
||||
timeline.render({ historyVirtualized: virtualized, historyMounted: mounted });
|
||||
await timeline.settle();
|
||||
|
||||
expect(timeline.rowTop("message-400")).toBe(readingTop);
|
||||
expect(timeline.rowBottom("thought-169")).toBe(readingTop);
|
||||
});
|
||||
|
||||
it("does not runaway-loop when unmeasured virtualized rows shrink near the bottom of a long chat", async () => {
|
||||
const virtualized = Array.from({ length: 2000 }, (_, index) => assistantRow(index, 20));
|
||||
const mounted = Array.from({ length: 10 }, (_, index) => row(2000 + index, 40));
|
||||
const timeline = mountTimeline(mounted, {
|
||||
historyVirtualized: virtualized,
|
||||
viewportHeight: 600,
|
||||
});
|
||||
await timeline.settle(10);
|
||||
timeline.scrollUp(120);
|
||||
await timeline.settle(10);
|
||||
|
||||
const readingTop = timeline.rowTop("message-2000");
|
||||
timeline.render({}, { contentMaxWidth: 360 });
|
||||
await timeline.settle(10);
|
||||
|
||||
expect(timeline.rowTop("message-2000")).toBe(readingTop);
|
||||
expect(timeline.rowBottom("assistant-1999")).toBe(readingTop);
|
||||
expect(timeline.rowTop("assistant-1990")).toBe(readingTop - 200);
|
||||
});
|
||||
|
||||
it("keeps a mounted anchor near the bottom when prepended virtualized rows shrink below estimate", async () => {
|
||||
const mounted = Array.from({ length: 10 }, (_, index) => row(40 + index, 40));
|
||||
const timeline = mountTimeline(mounted, { viewportHeight: 200 });
|
||||
await timeline.settle();
|
||||
timeline.scrollUp(60);
|
||||
await timeline.settle();
|
||||
const readingTop = timeline.rowTop("message-44");
|
||||
|
||||
const virtualized = Array.from({ length: 40 }, (_, index) => assistantRow(index, 40));
|
||||
timeline.render({ historyVirtualized: virtualized, historyMounted: mounted });
|
||||
await timeline.settle();
|
||||
|
||||
expect(timeline.rowTop("message-44")).toBe(readingTop);
|
||||
expect(timeline.rowBottom("assistant-39")).toBe(timeline.rowTop("message-40"));
|
||||
});
|
||||
|
||||
it("settles across frames without hitting React update depth limits for hundreds of tiny virtualized rows", async () => {
|
||||
const mounted = Array.from({ length: 4 }, (_, index) => row(800 + index, 40));
|
||||
const virtualized = Array.from({ length: 800 }, (_, index) => assistantRow(index, 2));
|
||||
const timeline = mountTimeline(mounted, {
|
||||
historyVirtualized: virtualized,
|
||||
viewportHeight: 1200,
|
||||
});
|
||||
await timeline.settle(16);
|
||||
expect(timeline.distanceFromEnd()).toBeLessThanOrEqual(1);
|
||||
|
||||
const readingTop = timeline.rowTop("message-800");
|
||||
timeline.hold("message-800", () => timeline.render({}, { contentMaxWidth: 360 }));
|
||||
await timeline.settle(16);
|
||||
|
||||
expect(timeline.rowTop("message-800")).toBe(readingTop);
|
||||
expect(timeline.rowBottom("assistant-799")).toBe(readingTop);
|
||||
expect(timeline.rowTop("assistant-700")).toBe(readingTop - 200);
|
||||
});
|
||||
|
||||
it("resumes following when a layout commit precedes the scroll event at the bottom", async () => {
|
||||
const mounted = Array.from({ length: 10 }, (_, index) => row(index, 40));
|
||||
const timeline = mountTimeline(mounted, { viewportHeight: 200 });
|
||||
await timeline.settle();
|
||||
timeline.scrollUp(120);
|
||||
await timeline.settle();
|
||||
|
||||
timeline.scrollTo(1000);
|
||||
timeline.render({ historyMounted: [...mounted] });
|
||||
await timeline.settle();
|
||||
|
||||
timeline.render({ liveHead: [row(10, 40)] });
|
||||
await timeline.settle();
|
||||
|
||||
expect(timeline.distanceFromEnd()).toBe(0);
|
||||
});
|
||||
|
||||
it("mounts the top of a newly virtualized block when all history fits in the viewport", async () => {
|
||||
const timeline = mountTimeline([row(99, 40)], {
|
||||
viewportHeight: 1200,
|
||||
isMobileBreakpoint: false,
|
||||
});
|
||||
await timeline.settle();
|
||||
|
||||
timeline.render({
|
||||
historyVirtualized: Array.from({ length: 24 }, (_, index) => thoughtRow(index, 40)),
|
||||
});
|
||||
await timeline.settle();
|
||||
|
||||
expect(timeline.scrollTop()).toBe(0);
|
||||
expect(timeline.rowTop("thought-0")).toBe(48);
|
||||
expect(timeline.rowTop("message-99")).toBe(48 + 24 * 40);
|
||||
});
|
||||
|
||||
it("mounts the top of a newly virtualized block when a mounted row shrinks in the same commit", async () => {
|
||||
const timeline = mountTimeline([row(99, 1100)], {
|
||||
viewportHeight: 1200,
|
||||
isMobileBreakpoint: false,
|
||||
});
|
||||
await timeline.settle();
|
||||
expect(timeline.scrollTop()).toBe(0);
|
||||
|
||||
timeline.render({
|
||||
historyVirtualized: Array.from({ length: 24 }, (_, index) => thoughtRow(index, 40)),
|
||||
historyMounted: [row(99, 40)],
|
||||
});
|
||||
await timeline.settle();
|
||||
|
||||
expect(timeline.scrollTop()).toBe(0);
|
||||
expect(timeline.rowTop("message-99")).toBe(1008);
|
||||
expect(timeline.rowTop("thought-0")).toBe(48);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -57,8 +57,10 @@ const AUTO_SCROLL_RESUME_THRESHOLD_PX = 1;
|
||||
const HISTORY_START_SETTLE_FRAMES = 2;
|
||||
const HISTORY_START_SLOT_HEIGHT_PX = 32;
|
||||
const CONTENT_PADDING_TOP_PX = 16;
|
||||
const CONTENT_PADDING_BOTTOM_PX = 16;
|
||||
const UPWARD_INPUT_EVIDENCE_TIMEOUT_MS = 100;
|
||||
const VIRTUALIZER_SCROLL_MARGIN_PX = HISTORY_START_SLOT_HEIGHT_PX + CONTENT_PADDING_TOP_PX;
|
||||
const MAX_SYNC_LAYOUT_PASSES = 16;
|
||||
|
||||
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
|
||||
const foregroundMutedColorMapping = (theme: Theme) => ({
|
||||
@@ -118,6 +120,127 @@ function isScrollContainerMeasurable(
|
||||
return scrollContainer.clientHeight > 0 && scrollContainer.scrollHeight > 0;
|
||||
}
|
||||
|
||||
function getUnclampedScrollTop(
|
||||
scrollContainer: Pick<HTMLElement, "scrollTop" | "clientHeight" | "scrollHeight">,
|
||||
lastKnownScrollTop: number,
|
||||
): number {
|
||||
if (!isScrollContainerMeasurable(scrollContainer)) {
|
||||
return scrollContainer.scrollTop;
|
||||
}
|
||||
const maxScrollTop = Math.max(0, scrollContainer.scrollHeight - scrollContainer.clientHeight);
|
||||
const isBrowserClamped =
|
||||
maxScrollTop < lastKnownScrollTop - 0.5 &&
|
||||
Math.abs(scrollContainer.scrollTop - maxScrollTop) <= 1;
|
||||
return isBrowserClamped ? lastKnownScrollTop : scrollContainer.scrollTop;
|
||||
}
|
||||
|
||||
interface MountedRowOffset {
|
||||
topWithoutVirtual: number;
|
||||
height: number;
|
||||
mountedIndex: number;
|
||||
}
|
||||
|
||||
interface MountedRowSnapshot {
|
||||
firstRowId: string | null;
|
||||
offsets: Map<string, MountedRowOffset>;
|
||||
}
|
||||
|
||||
function findNonVirtualizedRowIndex(
|
||||
segments: Pick<StreamRenderInput["segments"], "historyMounted" | "liveHead">,
|
||||
rowId: string,
|
||||
): number {
|
||||
const mountedIndex = segments.historyMounted.findIndex((row) => row.id === rowId);
|
||||
if (mountedIndex >= 0) {
|
||||
return mountedIndex;
|
||||
}
|
||||
const liveHeadIndex = segments.liveHead.findIndex((row) => row.id === rowId);
|
||||
return liveHeadIndex >= 0 ? segments.historyMounted.length + liveHeadIndex : -1;
|
||||
}
|
||||
|
||||
interface CommittedLayoutMetrics {
|
||||
hasCommittedFlowHeight: boolean;
|
||||
virtualSpacerHeight: number;
|
||||
nonVirtualFlowHeight: number;
|
||||
nonVirtualRowCount: number;
|
||||
}
|
||||
|
||||
interface ProjectRangeOffsetInput {
|
||||
container: HTMLElement;
|
||||
virtualizer: Virtualizer<HTMLElement, Element>;
|
||||
followOutput: boolean;
|
||||
isJumpSettling: boolean;
|
||||
lastClampedBaselineScrollTop: number;
|
||||
committedLayoutMetrics: CommittedLayoutMetrics;
|
||||
anchorId: string | null;
|
||||
anchorIndex: number;
|
||||
segments: Pick<StreamRenderInput["segments"], "historyMounted" | "liveHead">;
|
||||
mountedSnapshot: MountedRowSnapshot;
|
||||
readingAnchor: ReturnType<typeof createReadingAnchor>;
|
||||
readingRowReplacements: StreamRenderInput["readingRowReplacements"];
|
||||
}
|
||||
|
||||
function projectRangeOffset(input: ProjectRangeOffsetInput): number {
|
||||
const { container, virtualizer } = input;
|
||||
if (input.isJumpSettling) {
|
||||
return container.scrollTop;
|
||||
}
|
||||
const baseScrollTop = getUnclampedScrollTop(container, input.lastClampedBaselineScrollTop);
|
||||
if (input.followOutput && isScrollContainerMeasurable(container)) {
|
||||
const { committedLayoutMetrics } = input;
|
||||
const currentNonVirtualRowCount =
|
||||
input.segments.historyMounted.length + input.segments.liveHead.length;
|
||||
if (
|
||||
!committedLayoutMetrics.hasCommittedFlowHeight ||
|
||||
currentNonVirtualRowCount < committedLayoutMetrics.nonVirtualRowCount
|
||||
) {
|
||||
return baseScrollTop;
|
||||
}
|
||||
const projectedFlowHeight =
|
||||
committedLayoutMetrics.nonVirtualFlowHeight + virtualizer.getTotalSize();
|
||||
return Math.max(0, projectedFlowHeight - container.clientHeight);
|
||||
}
|
||||
if (input.anchorIndex >= 0) {
|
||||
const measurement = virtualizer.measurementsCache[input.anchorIndex];
|
||||
if (!measurement) {
|
||||
return baseScrollTop;
|
||||
}
|
||||
return input.readingAnchor.project(
|
||||
baseScrollTop,
|
||||
{
|
||||
id: String(measurement.key),
|
||||
top: measurement.start,
|
||||
height: measurement.size,
|
||||
},
|
||||
input.readingRowReplacements,
|
||||
);
|
||||
}
|
||||
if (!input.anchorId) {
|
||||
return baseScrollTop;
|
||||
}
|
||||
const mountedAnchor = input.mountedSnapshot.offsets.get(input.anchorId);
|
||||
if (!mountedAnchor) {
|
||||
return baseScrollTop;
|
||||
}
|
||||
const currentMountedIndex = findNonVirtualizedRowIndex(input.segments, input.anchorId);
|
||||
const currentFirstMountedId =
|
||||
input.segments.historyMounted[0]?.id ?? input.segments.liveHead[0]?.id ?? null;
|
||||
if (
|
||||
currentMountedIndex !== mountedAnchor.mountedIndex ||
|
||||
currentFirstMountedId !== input.mountedSnapshot.firstRowId
|
||||
) {
|
||||
return baseScrollTop;
|
||||
}
|
||||
return input.readingAnchor.project(
|
||||
baseScrollTop,
|
||||
{
|
||||
id: input.anchorId,
|
||||
top: mountedAnchor.topWithoutVirtual + virtualizer.getTotalSize(),
|
||||
height: mountedAnchor.height,
|
||||
},
|
||||
input.readingRowReplacements,
|
||||
);
|
||||
}
|
||||
|
||||
function isEditableEventTarget(target: EventTarget | null): boolean {
|
||||
if (!(target instanceof Element)) {
|
||||
return false;
|
||||
@@ -330,6 +453,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
const isActive = useRetainedPanelActive();
|
||||
const { t } = useTranslation();
|
||||
const rowsHostRef = useRef<HTMLDivElement | null>(null);
|
||||
const virtualSpacerRef = useRef<HTMLDivElement | null>(null);
|
||||
const auxiliaryRef = useRef<HTMLDivElement | null>(null);
|
||||
const isActiveRef = useRef(isActive);
|
||||
const scrollContainerRef = useRef<HTMLElement | null>(null);
|
||||
@@ -341,6 +465,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
contentRef.current = node;
|
||||
}, []);
|
||||
const [followOutput, setFollowOutputr] = useState(true);
|
||||
const [rangeProjectionEpoch, setRangeProjectionEpoch] = useState(0);
|
||||
const followOutputRef = useRef(followOutput);
|
||||
const setFollowOutput = (value: boolean) => {
|
||||
followOutputRef.current = value;
|
||||
@@ -348,6 +473,10 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
return value;
|
||||
};
|
||||
const lastKnownScrollTopRef = useRef(0);
|
||||
const lastClampedBaselineScrollTopRef = useRef(0);
|
||||
const segmentsRef = useRef(segments);
|
||||
segmentsRef.current = segments;
|
||||
const isJumpSettlingRef = useRef<() => boolean>(() => false);
|
||||
const mouseScrollGestureRef = useRef<
|
||||
| { kind: "scrollbar"; pointerId: number }
|
||||
| {
|
||||
@@ -363,9 +492,23 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
const lastTouchClientYRef = useRef<number | null>(null);
|
||||
const pendingAutoScrollFrameRef = useRef<number | null>(null);
|
||||
const pendingAutoScrollTimeoutRef = useRef<number | null>(null);
|
||||
const deferredLayoutFrameRef = useRef<number | null>(null);
|
||||
const lastProjectedRangeOffsetRef = useRef<number | null>(null);
|
||||
const syncLayoutPassesRef = useRef(0);
|
||||
const syncLayoutResetScheduledRef = useRef(false);
|
||||
const historyStartReadyRef = useRef(false);
|
||||
const readingAnchor = useMemo(createReadingAnchor, []);
|
||||
const measuredRowHeights = useRef(new Map<string, { width: number; height: number }>());
|
||||
const mountedRowSnapshotRef = useRef<MountedRowSnapshot>({
|
||||
firstRowId: null,
|
||||
offsets: new Map(),
|
||||
});
|
||||
const committedLayoutMetricsRef = useRef<CommittedLayoutMetrics>({
|
||||
hasCommittedFlowHeight: false,
|
||||
virtualSpacerHeight: 0,
|
||||
nonVirtualFlowHeight: 0,
|
||||
nonVirtualRowCount: 0,
|
||||
});
|
||||
const historyStartSettleSchedulerRef = useRef<HistoryStartSettleScheduler | null>(null);
|
||||
const lastActiveFollowOutputLayoutRef = useRef<ActiveFollowOutputLayout | null>(null);
|
||||
const lastObservedViewportGeometryRef = useRef<ObservedViewportGeometry | null>(null);
|
||||
@@ -404,38 +547,50 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
const rowVirtualizerRef = useRef<Virtualizer<HTMLElement, Element> | null>(null);
|
||||
const rangeExtractor = useCallback(
|
||||
(range: VirtualRange): number[] => {
|
||||
const anchorIndex = segments.historyVirtualized.findIndex(
|
||||
(row) => row.id === readingAnchor.getRowId(props.readingRowReplacements),
|
||||
);
|
||||
// Busts TanStack's getVirtualIndexes memo when a post-commit check detects a stale projection.
|
||||
void rangeProjectionEpoch;
|
||||
const anchorId = readingAnchor.getRowId(props.readingRowReplacements);
|
||||
const anchorIndex = anchorId
|
||||
? segments.historyVirtualized.findIndex((row) => row.id === anchorId)
|
||||
: -1;
|
||||
const container = scrollContainerRef.current;
|
||||
// TanStack has computed the new measurements before calling the extractor.
|
||||
// Select against the pending anchor correction, before mounting any rows at
|
||||
// the stale pre-prepend offset. The DOM correction still belongs to commit.
|
||||
const virtualizer = rowVirtualizerRef.current!;
|
||||
const measurement = virtualizer.measurementsCache[anchorIndex];
|
||||
const correctedOffset =
|
||||
container && measurement
|
||||
? readingAnchor.project(
|
||||
container.scrollTop,
|
||||
{
|
||||
id: String(measurement.key),
|
||||
top: measurement.start,
|
||||
height: measurement.size,
|
||||
},
|
||||
props.readingRowReplacements,
|
||||
)
|
||||
: container?.scrollTop;
|
||||
const virtualizerOffset = virtualizer.scrollOffset ?? 0;
|
||||
const correctedOffset = container
|
||||
? projectRangeOffset({
|
||||
container,
|
||||
virtualizer,
|
||||
followOutput: followOutputRef.current,
|
||||
isJumpSettling: isJumpSettlingRef.current(),
|
||||
lastClampedBaselineScrollTop: lastClampedBaselineScrollTopRef.current,
|
||||
committedLayoutMetrics: committedLayoutMetricsRef.current,
|
||||
anchorId,
|
||||
anchorIndex,
|
||||
segments: segmentsRef.current,
|
||||
mountedSnapshot: mountedRowSnapshotRef.current,
|
||||
readingAnchor,
|
||||
readingRowReplacements: props.readingRowReplacements,
|
||||
})
|
||||
: undefined;
|
||||
let visibleRange = range;
|
||||
let projectedRangeOffset: number | null = null;
|
||||
if (
|
||||
container &&
|
||||
correctedOffset !== undefined &&
|
||||
Math.abs(correctedOffset - container.scrollTop) > 0.5
|
||||
Math.abs(correctedOffset - virtualizerOffset) > 0.5
|
||||
) {
|
||||
const first = virtualizer.getVirtualItemForOffset(correctedOffset);
|
||||
const last = virtualizer.getVirtualItemForOffset(correctedOffset + container.clientHeight);
|
||||
if (first && last)
|
||||
const projectedOffset = Math.max(0, correctedOffset);
|
||||
const first = virtualizer.getVirtualItemForOffset(projectedOffset);
|
||||
const last = virtualizer.getVirtualItemForOffset(projectedOffset + container.clientHeight);
|
||||
if (first && last) {
|
||||
visibleRange = { ...range, startIndex: first.index, endIndex: last.index };
|
||||
projectedRangeOffset = projectedOffset;
|
||||
}
|
||||
}
|
||||
lastProjectedRangeOffsetRef.current = projectedRangeOffset;
|
||||
return [
|
||||
...new Set([
|
||||
...defaultRangeExtractor(visibleRange),
|
||||
@@ -444,7 +599,13 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
]),
|
||||
].sort((left, right) => left - right);
|
||||
},
|
||||
[chatFindRowIndexes, readingAnchor, segments.historyVirtualized, props.readingRowReplacements],
|
||||
[
|
||||
chatFindRowIndexes,
|
||||
rangeProjectionEpoch,
|
||||
readingAnchor,
|
||||
segments.historyVirtualized,
|
||||
props.readingRowReplacements,
|
||||
],
|
||||
);
|
||||
const virtualOffsetListener = useRef<((offset: number, scrolling: boolean) => void) | null>(null);
|
||||
const observeVirtualOffset = useCallback<typeof observeElementOffset>((instance, onOffset) => {
|
||||
@@ -563,8 +724,10 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
"[data-history-row-id][data-index]",
|
||||
) ?? []) {
|
||||
const index = Number(element.dataset.index);
|
||||
const measurement = rowVirtualizer.measurementsCache[index];
|
||||
if (!measurement) continue;
|
||||
const height = measureVirtualElement(element, undefined, rowVirtualizer);
|
||||
if (rowVirtualizer.measurementsCache[index]?.size === height) continue;
|
||||
if (measurement.size === height) continue;
|
||||
rowVirtualizer.resizeItem(index, height);
|
||||
resized = true;
|
||||
}
|
||||
@@ -593,6 +756,22 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
);
|
||||
useEffect(() => () => virtualRowObserver.disconnect(), [virtualRowObserver]);
|
||||
|
||||
const cancelDeferredLayoutPass = useCallback(() => {
|
||||
const pendingFrame = deferredLayoutFrameRef.current;
|
||||
if (pendingFrame !== null) {
|
||||
deferredLayoutFrameRef.current = null;
|
||||
window.cancelAnimationFrame(pendingFrame);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
cancelDeferredLayoutPass();
|
||||
syncLayoutPassesRef.current = 0;
|
||||
},
|
||||
[cancelDeferredLayoutPass],
|
||||
);
|
||||
|
||||
const cancelPendingStickToBottom = useCallback(() => {
|
||||
const pendingFrame = pendingAutoScrollFrameRef.current;
|
||||
if (pendingFrame !== null) {
|
||||
@@ -638,11 +817,20 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
return;
|
||||
}
|
||||
cancelPendingStickToBottom();
|
||||
cancelDeferredLayoutPass();
|
||||
lastProjectedRangeOffsetRef.current = null;
|
||||
syncLayoutPassesRef.current = 0;
|
||||
historyStartSettleSchedulerRef.current?.cancel();
|
||||
clearMouseScrollGesture();
|
||||
clearUpwardInputEvidence();
|
||||
lastTouchClientYRef.current = null;
|
||||
}, [cancelPendingStickToBottom, clearMouseScrollGesture, clearUpwardInputEvidence, isActive]);
|
||||
}, [
|
||||
cancelDeferredLayoutPass,
|
||||
cancelPendingStickToBottom,
|
||||
clearMouseScrollGesture,
|
||||
clearUpwardInputEvidence,
|
||||
isActive,
|
||||
]);
|
||||
|
||||
const scrollMessagesToBottom = useCallback(
|
||||
(behavior: ScrollBehaviorLike = "auto") => {
|
||||
@@ -659,6 +847,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
}
|
||||
scrollElementToBottom(scrollContainer, behavior);
|
||||
lastKnownScrollTopRef.current = scrollContainer.scrollTop;
|
||||
lastClampedBaselineScrollTopRef.current = scrollContainer.scrollTop;
|
||||
syncNearBottom(scrollContainer, onNearBottomChange);
|
||||
evaluateHistoryStart();
|
||||
},
|
||||
@@ -731,6 +920,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
setFollowOutput,
|
||||
onNearBottomChange,
|
||||
});
|
||||
isJumpSettlingRef.current = isJumpSettling;
|
||||
|
||||
// Row tops in content coordinates, which survive scrolling.
|
||||
const measureRows = useStableEvent(() => {
|
||||
@@ -740,14 +930,89 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
const viewportTop = container.getBoundingClientRect().top;
|
||||
const scrollTop = container.scrollTop;
|
||||
const width = readContentWidth() ?? 0;
|
||||
return Array.from(content.querySelectorAll<HTMLElement>("[data-history-row-id]"), (element) => {
|
||||
const bounds = element.getBoundingClientRect();
|
||||
const id = element.dataset.historyRowId!;
|
||||
measuredRowHeights.current.set(id, { width, height: bounds.height });
|
||||
return { id, top: bounds.top - viewportTop + scrollTop, height: bounds.height };
|
||||
const virtualSpacerHeight = virtualSpacerRef.current?.getBoundingClientRect().height ?? 0;
|
||||
const rowsHostHeight = rowsHostRef.current?.getBoundingClientRect().height ?? 0;
|
||||
const auxiliaryHeight = auxiliaryRef.current?.getBoundingClientRect().height ?? 0;
|
||||
const shouldTrackMountedOffsets = !followOutputRef.current;
|
||||
const mountedOffsets = mountedRowSnapshotRef.current.offsets;
|
||||
mountedOffsets.clear();
|
||||
let firstRowId: string | null = null;
|
||||
let mountedIndex = 0;
|
||||
const rows = Array.from(
|
||||
content.querySelectorAll<HTMLElement>("[data-history-row-id]"),
|
||||
(element) => {
|
||||
const bounds = element.getBoundingClientRect();
|
||||
const id = element.dataset.historyRowId!;
|
||||
const top = bounds.top - viewportTop + scrollTop;
|
||||
measuredRowHeights.current.set(id, { width, height: bounds.height });
|
||||
if (!element.hasAttribute("data-index")) {
|
||||
if (shouldTrackMountedOffsets) {
|
||||
if (firstRowId === null) {
|
||||
firstRowId = id;
|
||||
}
|
||||
mountedOffsets.set(id, {
|
||||
topWithoutVirtual: top - virtualSpacerHeight,
|
||||
height: bounds.height,
|
||||
mountedIndex,
|
||||
});
|
||||
}
|
||||
mountedIndex += 1;
|
||||
}
|
||||
return { id, top, height: bounds.height };
|
||||
},
|
||||
);
|
||||
mountedRowSnapshotRef.current.firstRowId = firstRowId;
|
||||
committedLayoutMetricsRef.current = {
|
||||
hasCommittedFlowHeight: true,
|
||||
virtualSpacerHeight,
|
||||
nonVirtualFlowHeight:
|
||||
VIRTUALIZER_SCROLL_MARGIN_PX +
|
||||
Math.max(0, rowsHostHeight - virtualSpacerHeight) +
|
||||
auxiliaryHeight +
|
||||
CONTENT_PADDING_BOTTOM_PX,
|
||||
nonVirtualRowCount: mountedIndex,
|
||||
};
|
||||
return rows;
|
||||
});
|
||||
|
||||
const scheduleDeferredLayoutPass = useStableEvent(() => {
|
||||
if (deferredLayoutFrameRef.current !== null || !isActiveRef.current) {
|
||||
return;
|
||||
}
|
||||
deferredLayoutFrameRef.current = window.requestAnimationFrame(() => {
|
||||
deferredLayoutFrameRef.current = null;
|
||||
syncLayoutPassesRef.current = 0;
|
||||
if (!isActiveRef.current) {
|
||||
return;
|
||||
}
|
||||
if (measureVirtualizedRows()) {
|
||||
return;
|
||||
}
|
||||
reconcileReadingPosition();
|
||||
if (followOutputRef.current && scrollContainerRef.current) {
|
||||
reconcileProjectedRange(scrollContainerRef.current);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const reconcileProjectedRange = useStableEvent((container: HTMLElement): boolean => {
|
||||
const projectedOffset = lastProjectedRangeOffsetRef.current;
|
||||
if (projectedOffset === null) {
|
||||
return false;
|
||||
}
|
||||
if (Math.abs(container.scrollTop - projectedOffset) <= 0.5) {
|
||||
lastProjectedRangeOffsetRef.current = null;
|
||||
return false;
|
||||
}
|
||||
if (syncLayoutPassesRef.current >= MAX_SYNC_LAYOUT_PASSES) {
|
||||
scheduleDeferredLayoutPass();
|
||||
return true;
|
||||
}
|
||||
lastProjectedRangeOffsetRef.current = null;
|
||||
setRangeProjectionEpoch((value) => value + 1);
|
||||
return true;
|
||||
});
|
||||
|
||||
const reconcileReadingPosition = useStableEvent(() => {
|
||||
const container = scrollContainerRef.current;
|
||||
if (!isActiveRef.current || !container) return;
|
||||
@@ -755,8 +1020,11 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
if (!rows) return;
|
||||
const shouldAnchor = !followOutputRef.current && !isJumpSettling();
|
||||
if (!shouldAnchor) readingAnchor.reset();
|
||||
const anchorScrollTop = shouldAnchor
|
||||
? getUnclampedScrollTop(container, lastClampedBaselineScrollTopRef.current)
|
||||
: container.scrollTop;
|
||||
const correctedTop = readingAnchor.reconcile(
|
||||
container.scrollTop,
|
||||
anchorScrollTop,
|
||||
rows,
|
||||
false,
|
||||
props.readingRowReplacements,
|
||||
@@ -768,9 +1036,20 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
if (Math.abs(correctedTop - container.scrollTop) > 0.5) {
|
||||
container.scrollTop = correctedTop;
|
||||
lastKnownScrollTopRef.current = container.scrollTop;
|
||||
}
|
||||
lastClampedBaselineScrollTopRef.current = container.scrollTop;
|
||||
const virtualizerOffset = rowVirtualizer.scrollOffset ?? 0;
|
||||
if (virtualOffsetListener.current && Math.abs(container.scrollTop - virtualizerOffset) > 0.5) {
|
||||
if (syncLayoutPassesRef.current >= MAX_SYNC_LAYOUT_PASSES) {
|
||||
scheduleDeferredLayoutPass();
|
||||
return;
|
||||
}
|
||||
// The DOM scroll event arrives later. Fill the corrected virtual range in
|
||||
// this layout so the reader does not get a frame containing only the pin.
|
||||
virtualOffsetListener.current?.(container.scrollTop, false);
|
||||
virtualOffsetListener.current(container.scrollTop, false);
|
||||
}
|
||||
if (reconcileProjectedRange(container)) {
|
||||
return;
|
||||
}
|
||||
// A disclosure that closes back to the end of the list rejoins the output.
|
||||
if (disclosurePendingRef.current) {
|
||||
@@ -782,17 +1061,38 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
// Apply row positions and their scroll correction in the same paint, including
|
||||
// the ordinary-to-virtualized handoff and measurements of newly mounted rows.
|
||||
useLayoutEffect(() => {
|
||||
if (!isActive) {
|
||||
cancelDeferredLayoutPass();
|
||||
lastProjectedRangeOffsetRef.current = null;
|
||||
syncLayoutPassesRef.current = 0;
|
||||
return;
|
||||
}
|
||||
if (syncLayoutPassesRef.current >= MAX_SYNC_LAYOUT_PASSES) {
|
||||
scheduleDeferredLayoutPass();
|
||||
return;
|
||||
}
|
||||
syncLayoutPassesRef.current += 1;
|
||||
if (!syncLayoutResetScheduledRef.current) {
|
||||
syncLayoutResetScheduledRef.current = true;
|
||||
queueMicrotask(() => {
|
||||
syncLayoutResetScheduledRef.current = false;
|
||||
syncLayoutPassesRef.current = 0;
|
||||
});
|
||||
}
|
||||
// Commit positions for every resized row before accepting reading geometry.
|
||||
// Child layout can change during this commit, ahead of ResizeObserver delivery.
|
||||
if (!isActive || measureVirtualizedRows()) return;
|
||||
if (measureVirtualizedRows()) return;
|
||||
cancelDeferredLayoutPass();
|
||||
reconcileReadingPosition();
|
||||
}, [
|
||||
cancelDeferredLayoutPass,
|
||||
contentWidth,
|
||||
isActive,
|
||||
segments,
|
||||
virtualRows,
|
||||
measureVirtualizedRows,
|
||||
reconcileReadingPosition,
|
||||
scheduleDeferredLayoutPass,
|
||||
]);
|
||||
|
||||
const stopFollowingOutputFromUserIntent = useStableEvent(() => {
|
||||
@@ -832,6 +1132,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
}
|
||||
|
||||
lastKnownScrollTopRef.current = currentScrollTop;
|
||||
lastClampedBaselineScrollTopRef.current = currentScrollTop;
|
||||
if (!followOutputRef.current && !isJumpSettling() && (scrolledUp || scrolledDown)) {
|
||||
readingAnchor.scroll(currentScrollTop);
|
||||
}
|
||||
@@ -925,11 +1226,15 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
if (!followOutputRef.current || resumedUnchangedLayout) return;
|
||||
cancelPendingStickToBottom();
|
||||
scrollMessagesToBottom("auto");
|
||||
if (scrollContainerRef.current) {
|
||||
reconcileProjectedRange(scrollContainerRef.current);
|
||||
}
|
||||
}, [
|
||||
activationKey,
|
||||
cancelPendingStickToBottom,
|
||||
isActive,
|
||||
isActivationReady,
|
||||
reconcileProjectedRange,
|
||||
renderLiveAuxiliary,
|
||||
scrollMessagesToBottom,
|
||||
segments.historyMounted,
|
||||
@@ -997,7 +1302,9 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
} else {
|
||||
lastObservedViewportGeometryRef.current = nextGeometry;
|
||||
}
|
||||
reconcileReadingPosition();
|
||||
if (deferredLayoutFrameRef.current === null) {
|
||||
reconcileReadingPosition();
|
||||
}
|
||||
if (isHistoryStartSettling()) {
|
||||
scheduleHistoryStartPrependSettle();
|
||||
}
|
||||
@@ -1208,6 +1515,9 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
setFollowOutput(false);
|
||||
const row = measureRows()?.find((candidate) => candidate.id === rowId);
|
||||
const scrollTop = scrollContainerRef.current?.scrollTop;
|
||||
if (scrollTop !== undefined) {
|
||||
lastClampedBaselineScrollTopRef.current = scrollTop;
|
||||
}
|
||||
if (row && scrollTop !== undefined) readingAnchor.pin(row, triggerEdge, scrollTop);
|
||||
disclosurePendingRef.current = true;
|
||||
apply();
|
||||
@@ -1243,7 +1553,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
flexDirection: "column",
|
||||
minHeight: "100%",
|
||||
paddingTop: CONTENT_PADDING_TOP_PX,
|
||||
paddingBottom: 16,
|
||||
paddingBottom: CONTENT_PADDING_BOTTOM_PX,
|
||||
paddingLeft,
|
||||
paddingRight,
|
||||
boxSizing: "border-box",
|
||||
@@ -1375,7 +1685,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
<div ref={handleContentRef} style={contentContainerStyle}>
|
||||
{historyStartSlot}
|
||||
<div ref={rowsHostRef} style={streamRowsHostStyle}>
|
||||
<div style={virtualRowsContainerStyle} />
|
||||
<div ref={virtualSpacerRef} style={virtualRowsContainerStyle} />
|
||||
{[
|
||||
...virtualRows.map((virtualRow) => {
|
||||
const item = segments.historyVirtualized[virtualRow.index];
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
TEXT_REVEAL_FRAME_INTERVAL_MS,
|
||||
TEXT_REVEAL_HORIZON_MS,
|
||||
visibleRevealedText,
|
||||
withholdPartialClosingFence,
|
||||
} from "./text-reveal";
|
||||
|
||||
describe("computeRevealStep", () => {
|
||||
@@ -275,3 +276,127 @@ describe("trailing fragments from arrival boundaries", () => {
|
||||
expect(visibleRevealedText(beginTextReveal(prose), { streaming: true })).toBe(prose);
|
||||
});
|
||||
});
|
||||
|
||||
describe("a closing fence still being typed", () => {
|
||||
const code = "Intro\n\n```ts\nconst a = 1;\n";
|
||||
|
||||
it("holds back one or two backticks that can only become the closing fence", () => {
|
||||
expect(withholdPartialClosingFence(`${code}\``)).toBe(code);
|
||||
expect(withholdPartialClosingFence(`${code}\`\``)).toBe(code);
|
||||
expect(withholdPartialClosingFence(`${code} \`\``)).toBe(code);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ char: "`", length: 3, whitespace: " " },
|
||||
{ char: "`", length: 3, whitespace: "\t" },
|
||||
{ char: "`", length: 4, whitespace: " " },
|
||||
{ char: "`", length: 4, whitespace: "\t" },
|
||||
{ char: "~", length: 3, whitespace: " " },
|
||||
{ char: "~", length: 3, whitespace: "\t" },
|
||||
{ char: "~", length: 5, whitespace: " " },
|
||||
{ char: "~", length: 5, whitespace: "\t" },
|
||||
])(
|
||||
"paints real code after whitespace ends a $length $char run ($whitespace)",
|
||||
({ char, length, whitespace }) => {
|
||||
const prefix = `${char.repeat(length)}\ncode\n`;
|
||||
const run = char.repeat(length - 1);
|
||||
expect(withholdPartialClosingFence(prefix + run)).toBe(prefix);
|
||||
const text = prefix + run + whitespace;
|
||||
expect(withholdPartialClosingFence(text)).toBe(text);
|
||||
expect(visibleRevealedText(beginTextReveal(text), { streaming: true })).toBe(text);
|
||||
},
|
||||
);
|
||||
|
||||
it("paints the fence once it closes the block", () => {
|
||||
expect(withholdPartialClosingFence(`${code}\`\`\``)).toBe(`${code}\`\`\``);
|
||||
expect(withholdPartialClosingFence(`${code}\`\`\`\n\nAfter`)).toBe(`${code}\`\`\`\n\nAfter`);
|
||||
});
|
||||
|
||||
it("needs a run as long as the opener and of the same character", () => {
|
||||
const long = "````md\nInside\n";
|
||||
expect(withholdPartialClosingFence(`${long}\`\`\``)).toBe(long);
|
||||
expect(withholdPartialClosingFence(`${long}\`\`\`\``)).toBe(`${long}\`\`\`\``);
|
||||
const tilde = "~~~\ncode\n";
|
||||
expect(withholdPartialClosingFence(`${tilde}~~`)).toBe(tilde);
|
||||
expect(withholdPartialClosingFence(`${tilde}\``)).toBe(`${tilde}\``);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ lineEnding: "LF", newline: "\n", closer: "```" },
|
||||
{ lineEnding: "CRLF", newline: "\r\n", closer: "```" },
|
||||
{ lineEnding: "LF", newline: "\n", closer: "``` \t" },
|
||||
{ lineEnding: "CRLF", newline: "\r\n", closer: "``` \t" },
|
||||
])(
|
||||
"recognizes completed closers before a tilde block with $lineEnding ($closer)",
|
||||
({ newline, closer }) => {
|
||||
const backtickBlock = ["Intro", "```ts", "const a = 1;", closer, ""].join(newline);
|
||||
const tildeBlock = backtickBlock + ["~~~md", "code", ""].join(newline);
|
||||
|
||||
expect(withholdPartialClosingFence(tildeBlock + "~~")).toBe(tildeBlock);
|
||||
expect(withholdPartialClosingFence(tildeBlock + "~~~")).toBe(tildeBlock + "~~~");
|
||||
expect(withholdPartialClosingFence(tildeBlock + "~~ not a closer")).toBe(
|
||||
tildeBlock + "~~ not a closer",
|
||||
);
|
||||
|
||||
const closedTildeBlock = tildeBlock + "~~~" + newline;
|
||||
expect(withholdPartialClosingFence(closedTildeBlock + "`")).toBe(closedTildeBlock + "`");
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
{ marker: "-", fence: "```", newline: "\n" },
|
||||
{ marker: "1.", fence: "~~~", newline: "\n" },
|
||||
{ marker: "-", fence: "~~~", newline: "\r\n" },
|
||||
{ marker: "1.", fence: "```", newline: "\r\n" },
|
||||
])(
|
||||
"keeps prose after a closed $marker list fence ($fence, $newline)",
|
||||
({ marker, fence, newline }) => {
|
||||
const indent = " ".repeat(marker.length + 1);
|
||||
const closed = [`${marker} ${fence}`, `${indent}code`, `${indent}${fence}`, "", ""].join(
|
||||
newline,
|
||||
);
|
||||
const prose = closed + fence[0];
|
||||
expect(withholdPartialClosingFence(prose)).toBe(prose);
|
||||
expect(visibleRevealedText(beginTextReveal(prose), { streaming: true })).toBe(prose);
|
||||
const open = [`${marker} ${fence}`, `${indent}code`, ""].join(newline);
|
||||
expect(withholdPartialClosingFence(open + indent + fence[0])).toBe(open);
|
||||
},
|
||||
);
|
||||
|
||||
it("does not take an indented code block's fence for a top-level opener", () => {
|
||||
const text = " code\n ```\n\n`";
|
||||
expect(withholdPartialClosingFence(text)).toBe(text);
|
||||
});
|
||||
|
||||
it("leaves backticks alone outside a code block", () => {
|
||||
expect(withholdPartialClosingFence("Prose\n`")).toBe("Prose\n`");
|
||||
const closed = "```\na\n```\n";
|
||||
expect(withholdPartialClosingFence(`${closed}\``)).toBe(`${closed}\``);
|
||||
expect(withholdPartialClosingFence("`` inline ``\n`")).toBe("`` inline ``\n`");
|
||||
});
|
||||
|
||||
it("leaves a code line that only starts with backticks alone", () => {
|
||||
expect(withholdPartialClosingFence(`${code}\`x`)).toBe(`${code}\`x`);
|
||||
});
|
||||
|
||||
it("never paints a lone backtick line while a paced reveal crosses the closing fence", () => {
|
||||
const full = `${code}\`\`\`\n\nAfter the block.`;
|
||||
let state = retargetTextReveal(beginTextReveal(code), full);
|
||||
const painted: string[] = [];
|
||||
for (let frame = 0; frame < 120 && !isTextRevealSettled(state); frame += 1) {
|
||||
state = advanceTextReveal(state, 16, 1_000);
|
||||
painted.push(visibleRevealedText(state, { streaming: true }));
|
||||
}
|
||||
expect(painted.at(-1)).toBe(full);
|
||||
for (const text of painted) {
|
||||
expect(full.startsWith(text)).toBe(true);
|
||||
expect(text.endsWith("\n`") || text.endsWith("\n``")).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("holds the fence back when an arrival ends inside it, and paints it once the turn ends", () => {
|
||||
const state = beginTextReveal(`${code}\``);
|
||||
expect(visibleRevealedText(state, { streaming: true })).toBe(code);
|
||||
expect(visibleRevealedText(state, { streaming: false })).toBe(`${code}\``);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { createMarkdownParser } from "@/utils/markdown-parser";
|
||||
|
||||
/**
|
||||
* Paced reveal for streaming assistant text.
|
||||
*
|
||||
@@ -207,6 +209,41 @@ function trimIncompleteTrailingCluster(text: string): string {
|
||||
return text;
|
||||
}
|
||||
|
||||
// Only parse block context when the current line can still become a closer.
|
||||
const UNFINISHED_FENCE_RUN = /^ {0,3}(`+|~+)$/;
|
||||
const fenceParser = createMarkdownParser({ linkify: false }).disable("inline");
|
||||
|
||||
/**
|
||||
* Hold back the closing fence of a code block while it is still being typed.
|
||||
*
|
||||
* Inside an open fence, a last line holding one or two backticks is code until
|
||||
* the third one arrives and closes the block. Painted, it adds a line of code
|
||||
* that vanishes a frame later, so the block grows and shrinks and every row
|
||||
* below it shifts twice. A paced reveal hands out these prefixes one character
|
||||
* at a time, and an arrival boundary can end on one too. The line waits until it
|
||||
* either closes the block or turns out to be code.
|
||||
*/
|
||||
export function withholdPartialClosingFence(text: string): string {
|
||||
const lineStart = text.lastIndexOf("\n") + 1;
|
||||
if (lineStart === 0) return text;
|
||||
const run = UNFINISHED_FENCE_RUN.exec(text.slice(lineStart))?.[1];
|
||||
if (!run) return text;
|
||||
// Source maps include container boundaries: a list closer must not become a
|
||||
// new top-level opener, and a fence-looking line in indented code is not one.
|
||||
const lastLine = text.split("\n").length - 1;
|
||||
const open = fenceParser
|
||||
.parse(text, {})
|
||||
.findLast(
|
||||
(token) =>
|
||||
token.type === "fence" &&
|
||||
token.map !== null &&
|
||||
token.map[0] < lastLine &&
|
||||
token.map[1] === lastLine + 1,
|
||||
);
|
||||
if (!open || open.markup[0] !== run[0] || run.length >= open.markup.length) return text;
|
||||
return text.slice(0, lineStart);
|
||||
}
|
||||
|
||||
/** Number of regional indicators at the end of `text`. A flag is a pair. */
|
||||
function countTrailingRegionalIndicators(text: string): number {
|
||||
let count = 0;
|
||||
@@ -234,7 +271,12 @@ export function visibleRevealedText(
|
||||
options?: { streaming?: boolean },
|
||||
): string {
|
||||
if (state.revealed >= state.target.length) {
|
||||
return options?.streaming ? trimIncompleteTrailingCluster(state.target) : state.target;
|
||||
return options?.streaming
|
||||
? withholdPartialClosingFence(trimIncompleteTrailingCluster(state.target))
|
||||
: state.target;
|
||||
}
|
||||
return state.target.slice(0, clampToSafeRevealBoundary(state.target, state.revealed));
|
||||
// More text is already here, so a partial fence at the cut is certainly unfinished.
|
||||
return withholdPartialClosingFence(
|
||||
state.target.slice(0, clampToSafeRevealBoundary(state.target, state.revealed)),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -162,11 +162,12 @@ describe("collapseTurns", () => {
|
||||
create.payload.data.detail = { type: "unknown", input: { title: "Side fix" }, output: null };
|
||||
const finished = shell("finished");
|
||||
if (finished.payload.source !== "agent") throw new Error("Expected agent tool");
|
||||
finished.payload.data.name = "agent_notification";
|
||||
finished.payload.data.agentMessage = {
|
||||
event: "finished",
|
||||
sender: { id: "worker", title: "PR helper" },
|
||||
finished.payload.data.name = "agent_finished";
|
||||
finished.payload.data.detail = {
|
||||
type: "plain_text",
|
||||
label: "PR helper",
|
||||
text: "Finished",
|
||||
icon: "bot",
|
||||
};
|
||||
const items: StreamItem[] = [
|
||||
user("u1"),
|
||||
|
||||
@@ -77,11 +77,8 @@ describe("canonical turn membership", () => {
|
||||
delete trigger.turnId;
|
||||
expect(continuesTurn(previous, trigger)).toBe(false);
|
||||
trigger.payload.data.name = "agent_message";
|
||||
trigger.payload.data.agentMessage = {
|
||||
event: "finished",
|
||||
sender: { id: "worker" },
|
||||
text: "Done",
|
||||
};
|
||||
expect(continuesTurn(previous, trigger)).toBe(false);
|
||||
trigger.payload.data.name = "agent_finished";
|
||||
expect(continuesTurn(previous, trigger)).toBe(false);
|
||||
});
|
||||
|
||||
|
||||
@@ -827,7 +827,6 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
cwd={context.cwd}
|
||||
serverId={resolvedServerId}
|
||||
metadata={data.metadata}
|
||||
agentMessage={data.agentMessage}
|
||||
isLastInSequence={isLastInSequence}
|
||||
onOpenFilePath={handleToolCallOpenFile}
|
||||
standalone={options.standalone}
|
||||
|
||||
@@ -624,8 +624,8 @@ export interface AdaptiveModalSheetProps {
|
||||
/** Re-establishes caller-owned contexts inside the native or compact sheet portal. */
|
||||
contextBridge?: ContextBridge | null;
|
||||
/**
|
||||
* Keys the body handles while the sheet is the top overlay, such as list navigation. Escape
|
||||
* always closes the sheet. Return true from `onKeyDown` to claim the key.
|
||||
* Keys the body handles while the sheet is the top overlay, such as list navigation. Return true
|
||||
* from `onKeyDown` to claim the key. Escape closes the sheet unless the body lists it and claims it.
|
||||
*/
|
||||
keyboard?: SheetKeyboard;
|
||||
}
|
||||
@@ -783,12 +783,18 @@ export function AdaptiveModalSheet({
|
||||
}
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
// A body that lists Escape among its keys undoes its own step first, such as a page that
|
||||
// returns to the one before it; Escape closes the sheet when the body has nothing to undo.
|
||||
if (keyboard?.keys.includes("Escape") && keyboard.onKeyDown(event)) return true;
|
||||
onClose();
|
||||
return true;
|
||||
},
|
||||
[keyboard, onClose],
|
||||
);
|
||||
const overlayKeys = useMemo(() => ["Escape", ...(keyboard?.keys ?? [])], [keyboard?.keys]);
|
||||
const overlayKeys = useMemo(
|
||||
() => ["Escape", ...(keyboard?.keys ?? []).filter((key) => key !== "Escape")],
|
||||
[keyboard?.keys],
|
||||
);
|
||||
const setOverlayScope = useOverlayRegistration({
|
||||
keys: overlayKeys,
|
||||
active: visible,
|
||||
|
||||
@@ -1,18 +1,26 @@
|
||||
import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
|
||||
import { Pressable, Text, View, type PressableStateCallbackType } from "react-native";
|
||||
import { useCallback, useMemo, useRef, useState, type ReactNode, type RefObject } from "react";
|
||||
import { Keyboard, Pressable, Text, View, type PressableStateCallbackType } from "react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import type { AgentProvider } from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentProfile, 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";
|
||||
import { ModelBrowser, ModelProviderGlyph, useModelBrowser } from "@/components/model-browser";
|
||||
import { resolveModelBrowserScrolling } from "@/components/model-browser-view";
|
||||
import type { ComboboxProps } from "@/components/ui/combobox";
|
||||
import {
|
||||
AdaptiveModalSheet,
|
||||
type SheetHeader,
|
||||
type SheetKeyboard,
|
||||
} from "@/components/adaptive-modal-sheet";
|
||||
import { ModelProviderGlyph, useSelectedModelLabels } from "@/components/model-browser";
|
||||
import { DesktopModelPicker, type ModelPickerActions } from "@/components/model-browser-panes";
|
||||
import {
|
||||
MobileModelPageView,
|
||||
SheetSearchDock,
|
||||
useMobileModelPage,
|
||||
} from "@/components/mobile-model-page";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { isNative, isWeb } from "@/constants/platform";
|
||||
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
|
||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||
import { ICON_SIZE } from "@/styles/theme";
|
||||
import {
|
||||
TOOLBAR_GLYPH_SIZES,
|
||||
toolbarContentSlot,
|
||||
@@ -21,15 +29,9 @@ import {
|
||||
|
||||
import { useKeyboardToggle, type KeyboardToggleAction } from "@/hooks/use-keyboard-toggle";
|
||||
|
||||
const EMPTY_COMBOBOX_OPTIONS: ComboboxOption[] = [];
|
||||
const DEFAULT_TRIGGER_DECORATION = { showCaret: true, tooltip: undefined };
|
||||
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
|
||||
|
||||
const foregroundMutedMapping = (theme: Theme) => ({
|
||||
color: theme.colors.foregroundMuted,
|
||||
});
|
||||
|
||||
function noop() {}
|
||||
const SHEET_SNAP_POINTS = ["80%", "90%"];
|
||||
const ESCAPE_KEYS = ["Escape"] as const;
|
||||
|
||||
interface CombinedModelSelectorProps {
|
||||
providers: ProviderSelectorProvider[];
|
||||
@@ -58,7 +60,6 @@ interface CombinedModelSelectorProps {
|
||||
disabled?: boolean;
|
||||
serverId?: string | null;
|
||||
desktopPlacement?: ComboboxProps["desktopPlacement"];
|
||||
desktopMinWidth?: number;
|
||||
/**
|
||||
* Render the custom trigger as a full-width form field: the outer Pressable
|
||||
* becomes a transparent passthrough that stretches its child edge-to-edge and
|
||||
@@ -75,7 +76,17 @@ interface CombinedModelSelectorProps {
|
||||
};
|
||||
}
|
||||
|
||||
export function CombinedModelSelector({
|
||||
export function CombinedModelSelector(props: CombinedModelSelectorProps) {
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
// One frame per form factor: a sheet that drills into providers, or a two-pane popover.
|
||||
return isCompact ? (
|
||||
<CompactCombinedModelSelector {...props} />
|
||||
) : (
|
||||
<DesktopCombinedModelSelector {...props} />
|
||||
);
|
||||
}
|
||||
|
||||
function DesktopCombinedModelSelector({
|
||||
providers,
|
||||
selectedProvider,
|
||||
selectedModel,
|
||||
@@ -95,60 +106,127 @@ export function CombinedModelSelector({
|
||||
disabled = false,
|
||||
serverId = null,
|
||||
desktopPlacement,
|
||||
desktopMinWidth,
|
||||
triggerFill = false,
|
||||
toolbar,
|
||||
}: CombinedModelSelectorProps) {
|
||||
const anchorRef = useRef<View>(null);
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const labels = useSelectedModelLabels({ providers, selectedProvider, selectedModel, isLoading });
|
||||
|
||||
const handleOpenChange = useCallback(
|
||||
(open: boolean) => {
|
||||
setIsOpen(open);
|
||||
if (open) onOpen?.();
|
||||
else onClose?.();
|
||||
},
|
||||
[onClose, onOpen],
|
||||
);
|
||||
const handleTriggerPress = useCallback(() => {
|
||||
handleOpenChange(!isOpen);
|
||||
}, [handleOpenChange, isOpen]);
|
||||
const actions = useModelSelectorActions({
|
||||
onOpenChange: handleOpenChange,
|
||||
onSelect,
|
||||
onApplyProfile,
|
||||
onEditProfiles,
|
||||
onCreateProfile,
|
||||
onEditProfile,
|
||||
});
|
||||
|
||||
useKeyboardToggle({
|
||||
action: toggleAction,
|
||||
disabled,
|
||||
open: isOpen,
|
||||
// The search field holds focus for as long as the popover is open.
|
||||
searchFocused: isOpen,
|
||||
onToggle: handleTriggerPress,
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<ModelSelectorTrigger
|
||||
anchorRef={anchorRef}
|
||||
isOpen={isOpen}
|
||||
disabled={disabled}
|
||||
onPress={handleTriggerPress}
|
||||
labels={labels}
|
||||
selectedProvider={selectedProvider}
|
||||
serverId={serverId}
|
||||
renderTrigger={renderTrigger}
|
||||
triggerFill={triggerFill}
|
||||
toolbar={toolbar}
|
||||
/>
|
||||
<DesktopModelPicker
|
||||
open={isOpen}
|
||||
onOpenChange={handleOpenChange}
|
||||
anchorRef={anchorRef}
|
||||
desktopPlacement={desktopPlacement}
|
||||
providers={providers}
|
||||
selectedProvider={selectedProvider}
|
||||
selectedModel={selectedModel}
|
||||
profiles={profiles}
|
||||
serverId={serverId}
|
||||
onSelect={actions.handleSelect}
|
||||
onApplyProfile={actions.handleApplyProfile}
|
||||
onEditProfiles={onEditProfiles ? actions.handleEditProfiles : undefined}
|
||||
onCreateProfile={onCreateProfile ? actions.handleCreateProfile : undefined}
|
||||
onEditProfile={onEditProfile ? actions.handleEditProfile : undefined}
|
||||
onRetryProvider={onRetryProvider}
|
||||
isRetryingProvider={isRetryingProvider}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function CompactCombinedModelSelector({
|
||||
providers,
|
||||
selectedProvider,
|
||||
selectedModel,
|
||||
onSelect,
|
||||
isLoading,
|
||||
profiles = null,
|
||||
onApplyProfile,
|
||||
onEditProfiles,
|
||||
onCreateProfile,
|
||||
onEditProfile,
|
||||
renderTrigger,
|
||||
toggleAction,
|
||||
onOpen,
|
||||
onClose,
|
||||
onRetryProvider,
|
||||
isRetryingProvider = false,
|
||||
disabled = false,
|
||||
serverId = null,
|
||||
triggerFill = false,
|
||||
toolbar,
|
||||
}: CombinedModelSelectorProps) {
|
||||
const { t } = useTranslation();
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
const modelBrowserScrolling = resolveModelBrowserScrolling({ isNative, isCompact });
|
||||
const anchorRef = useRef<View>(null);
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [isContentReady, setIsContentReady] = useState(isWeb);
|
||||
const browser = useModelBrowser({
|
||||
const labels = useSelectedModelLabels({ providers, selectedProvider, selectedModel, isLoading });
|
||||
const page = useMobileModelPage({
|
||||
providers,
|
||||
profiles: profiles?.rows ?? null,
|
||||
canCreateProfile: Boolean(onEditProfiles),
|
||||
selectedProvider,
|
||||
selectedModel,
|
||||
isLoading,
|
||||
profiles,
|
||||
serverId,
|
||||
});
|
||||
const { prepareToOpen, reset } = browser;
|
||||
const { reset, clearQuery } = page;
|
||||
|
||||
const handleOpenChange = useCallback(
|
||||
(open: boolean) => {
|
||||
setIsOpen(open);
|
||||
if (open) {
|
||||
prepareToOpen();
|
||||
reset();
|
||||
onOpen?.();
|
||||
return;
|
||||
}
|
||||
reset();
|
||||
Keyboard.dismiss();
|
||||
onClose?.();
|
||||
},
|
||||
[onClose, onOpen, prepareToOpen, reset],
|
||||
[onClose, onOpen, reset],
|
||||
);
|
||||
|
||||
const handleSelect = useCallback(
|
||||
(provider: string, modelId: string) => {
|
||||
onSelect(provider, modelId);
|
||||
handleOpenChange(false);
|
||||
},
|
||||
[handleOpenChange, onSelect],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (isWeb) return () => {};
|
||||
if (!isOpen) {
|
||||
setIsContentReady(false);
|
||||
return () => {};
|
||||
}
|
||||
const frame = requestAnimationFrame(() => {
|
||||
setIsContentReady(true);
|
||||
});
|
||||
return () => cancelAnimationFrame(frame);
|
||||
}, [isOpen]);
|
||||
|
||||
const handleClose = useCallback(() => handleOpenChange(false), [handleOpenChange]);
|
||||
const handleTriggerPress = useCallback(() => {
|
||||
handleOpenChange(!isOpen);
|
||||
}, [handleOpenChange, isOpen]);
|
||||
@@ -157,10 +235,184 @@ export function CombinedModelSelector({
|
||||
action: toggleAction,
|
||||
disabled,
|
||||
open: isOpen,
|
||||
searchFocused: browser.isSearchFocused,
|
||||
searchFocused: false,
|
||||
onToggle: handleTriggerPress,
|
||||
});
|
||||
|
||||
const actions = useModelSelectorActions({
|
||||
onOpenChange: handleOpenChange,
|
||||
onSelect,
|
||||
onApplyProfile,
|
||||
onEditProfiles,
|
||||
onCreateProfile,
|
||||
onEditProfile,
|
||||
});
|
||||
const pickerActions = useMemo<ModelPickerActions>(
|
||||
() => ({
|
||||
onSelect: actions.handleSelect,
|
||||
onApplyProfile: actions.handleApplyProfile,
|
||||
onEditProfiles: onEditProfiles ? actions.handleEditProfiles : undefined,
|
||||
onCreateProfile: onCreateProfile ? actions.handleCreateProfile : undefined,
|
||||
onEditProfile: onEditProfile ? actions.handleEditProfile : undefined,
|
||||
onRetryProvider,
|
||||
isRetryingProvider,
|
||||
}),
|
||||
[actions, isRetryingProvider, onCreateProfile, onEditProfile, onEditProfiles, onRetryProvider],
|
||||
);
|
||||
|
||||
// Escape clears the search first, then closes the sheet.
|
||||
const query = page.query;
|
||||
const keyboard = useMemo<SheetKeyboard>(
|
||||
() => ({
|
||||
keys: ESCAPE_KEYS,
|
||||
onKeyDown: (event) => {
|
||||
if (event.key !== "Escape" || query.trim().length === 0) return false;
|
||||
clearQuery();
|
||||
return true;
|
||||
},
|
||||
}),
|
||||
[clearQuery, query],
|
||||
);
|
||||
const header = useMemo<SheetHeader>(() => ({ title: t("modelSelector.selectModel") }), [t]);
|
||||
const footer = useMemo(() => {
|
||||
let placeholder = t("modelSelector.searchPlaceholder");
|
||||
if (profiles && profiles.rows.length > 0) {
|
||||
placeholder = t("modelSelector.searchModelsAndProfilesPlaceholder");
|
||||
} else if (providers.length > 1) {
|
||||
placeholder = t("modelSelector.searchAllPlaceholder");
|
||||
}
|
||||
return (
|
||||
<SheetSearchDock
|
||||
query={page.query}
|
||||
searchKey={page.searchKey}
|
||||
onChangeText={page.setQuery}
|
||||
placeholder={placeholder}
|
||||
testID="model-search-all-input"
|
||||
/>
|
||||
);
|
||||
}, [page.query, page.searchKey, page.setQuery, profiles, providers.length, t]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<ModelSelectorTrigger
|
||||
anchorRef={anchorRef}
|
||||
isOpen={isOpen}
|
||||
disabled={disabled}
|
||||
onPress={handleTriggerPress}
|
||||
labels={labels}
|
||||
selectedProvider={selectedProvider}
|
||||
serverId={serverId}
|
||||
renderTrigger={renderTrigger}
|
||||
triggerFill={triggerFill}
|
||||
toolbar={toolbar}
|
||||
/>
|
||||
<AdaptiveModalSheet
|
||||
header={header}
|
||||
visible={isOpen}
|
||||
onClose={handleClose}
|
||||
snapPoints={SHEET_SNAP_POINTS}
|
||||
scrollable={false}
|
||||
footer={footer}
|
||||
keyboard={keyboard}
|
||||
contentStyle={styles.sheetBody}
|
||||
testID="model-selector-sheet"
|
||||
>
|
||||
<MobileModelPageView
|
||||
page={page}
|
||||
selectedProvider={selectedProvider}
|
||||
selectedModel={selectedModel}
|
||||
serverId={serverId}
|
||||
profiles={profiles?.rows ?? null}
|
||||
actions={pickerActions}
|
||||
/>
|
||||
</AdaptiveModalSheet>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Every pick resolves the selector and closes it. A 1-tap `+` saves the profile, selects its model
|
||||
* immediately, and closes the picker; useAgentProfileEditor surfaces a toast with Edit and Undo.
|
||||
*/
|
||||
function useModelSelectorActions({
|
||||
onOpenChange,
|
||||
onSelect,
|
||||
onApplyProfile,
|
||||
onEditProfiles,
|
||||
onCreateProfile,
|
||||
onEditProfile,
|
||||
}: Pick<
|
||||
CombinedModelSelectorProps,
|
||||
"onSelect" | "onApplyProfile" | "onEditProfiles" | "onCreateProfile" | "onEditProfile"
|
||||
> & { onOpenChange: (open: boolean) => void }) {
|
||||
const handleSelect = useCallback(
|
||||
(provider: string, modelId: string) => {
|
||||
onSelect(provider, modelId);
|
||||
onOpenChange(false);
|
||||
},
|
||||
[onOpenChange, onSelect],
|
||||
);
|
||||
const handleApplyProfile = useCallback(
|
||||
(profileId: string) => {
|
||||
onApplyProfile?.(profileId);
|
||||
onOpenChange(false);
|
||||
},
|
||||
[onApplyProfile, onOpenChange],
|
||||
);
|
||||
const handleEditProfiles = useCallback(() => {
|
||||
onOpenChange(false);
|
||||
onEditProfiles?.();
|
||||
}, [onEditProfiles, onOpenChange]);
|
||||
const handleCreateProfile = useCallback(
|
||||
(seed: AgentProfileSeed) => {
|
||||
if (seed.modelId) {
|
||||
onSelect(seed.provider, seed.modelId);
|
||||
}
|
||||
onOpenChange(false);
|
||||
void onCreateProfile?.(seed);
|
||||
},
|
||||
[onCreateProfile, onOpenChange, onSelect],
|
||||
);
|
||||
const handleEditProfile = useCallback(
|
||||
(profileId: string) => {
|
||||
onOpenChange(false);
|
||||
onEditProfile?.(profileId);
|
||||
},
|
||||
[onEditProfile, onOpenChange],
|
||||
);
|
||||
return {
|
||||
handleSelect,
|
||||
handleApplyProfile,
|
||||
handleEditProfiles,
|
||||
handleCreateProfile,
|
||||
handleEditProfile,
|
||||
};
|
||||
}
|
||||
|
||||
function ModelSelectorTrigger({
|
||||
anchorRef,
|
||||
isOpen,
|
||||
disabled,
|
||||
onPress,
|
||||
labels,
|
||||
selectedProvider,
|
||||
serverId,
|
||||
renderTrigger,
|
||||
triggerFill,
|
||||
toolbar,
|
||||
}: {
|
||||
anchorRef: RefObject<View | null>;
|
||||
isOpen: boolean;
|
||||
disabled: boolean;
|
||||
onPress: () => void;
|
||||
labels: { selectedModelLabel: string; triggerLabel: string };
|
||||
selectedProvider: string;
|
||||
serverId: string | null;
|
||||
renderTrigger: CombinedModelSelectorProps["renderTrigger"];
|
||||
triggerFill: boolean;
|
||||
toolbar: CombinedModelSelectorProps["toolbar"];
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const triggerStyle = useCallback(
|
||||
({ pressed, hovered }: PressableStateCallbackType & { hovered?: boolean }) => {
|
||||
if (triggerFill) {
|
||||
@@ -181,145 +433,73 @@ export function CombinedModelSelector({
|
||||
},
|
||||
[disabled, isOpen, renderTrigger, triggerFill],
|
||||
);
|
||||
|
||||
const handleApplyProfile = useCallback(
|
||||
(profileId: string) => {
|
||||
onApplyProfile?.(profileId);
|
||||
handleOpenChange(false);
|
||||
},
|
||||
[handleOpenChange, onApplyProfile],
|
||||
);
|
||||
|
||||
const handleEditProfiles = useCallback(() => {
|
||||
handleOpenChange(false);
|
||||
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);
|
||||
},
|
||||
[handleOpenChange, onCreateProfile, onSelect],
|
||||
);
|
||||
|
||||
const handleEditProfile = useCallback(
|
||||
(profileId: string) => {
|
||||
handleOpenChange(false);
|
||||
onEditProfile?.(profileId);
|
||||
},
|
||||
[handleOpenChange, onEditProfile],
|
||||
);
|
||||
|
||||
const selectorBody = isContentReady ? (
|
||||
<ModelBrowser
|
||||
state={browser}
|
||||
onSelect={handleSelect}
|
||||
onApplyProfile={handleApplyProfile}
|
||||
onEditProfiles={onEditProfiles ? handleEditProfiles : undefined}
|
||||
onCreateProfile={onCreateProfile ? handleCreateProfile : undefined}
|
||||
onEditProfile={onEditProfile ? handleEditProfile : undefined}
|
||||
onRetryProvider={onRetryProvider}
|
||||
isRetryingProvider={isRetryingProvider}
|
||||
scrolling={modelBrowserScrolling}
|
||||
/>
|
||||
) : (
|
||||
<View style={styles.sheetLoadingState}>
|
||||
<ThemedLoadingSpinner size={ICON_SIZE.sm} uniProps={foregroundMutedMapping} />
|
||||
<Text style={styles.sheetLoadingText}>{t("modelSelector.loadingSelector")}</Text>
|
||||
</View>
|
||||
);
|
||||
|
||||
const accessibilityLabel = t("modelSelector.selectedModel", {
|
||||
model: labels.selectedModelLabel,
|
||||
});
|
||||
const { showCaret, tooltip } = toolbar ?? DEFAULT_TRIGGER_DECORATION;
|
||||
|
||||
return (
|
||||
<>
|
||||
{renderTrigger ? (
|
||||
<Pressable
|
||||
ref={anchorRef}
|
||||
collapsable={false}
|
||||
disabled={disabled}
|
||||
onPress={handleTriggerPress}
|
||||
style={triggerStyle}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={t("modelSelector.selectedModel", {
|
||||
model: browser.selectedModelLabel,
|
||||
})}
|
||||
testID="combined-model-selector"
|
||||
>
|
||||
{({ pressed, hovered }: PressableStateCallbackType & { hovered?: boolean }) =>
|
||||
renderTrigger({
|
||||
selectedModelLabel: browser.triggerLabel,
|
||||
onPress: handleTriggerPress,
|
||||
disabled,
|
||||
isOpen,
|
||||
hovered: Boolean(hovered),
|
||||
pressed,
|
||||
})
|
||||
}
|
||||
</Pressable>
|
||||
) : (
|
||||
<ComboboxTrigger
|
||||
ref={anchorRef}
|
||||
collapsable={false}
|
||||
disabled={disabled}
|
||||
onPress={handleTriggerPress}
|
||||
style={triggerStyle}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={t("modelSelector.selectedModel", {
|
||||
model: browser.selectedModelLabel,
|
||||
})}
|
||||
testID="combined-model-selector"
|
||||
chevron={showCaret === false ? null : undefined}
|
||||
tooltip={tooltip}
|
||||
>
|
||||
{selectedProvider.trim().length > 0 ? (
|
||||
<View style={toolbar ? styles.toolbarGlyph : styles.glyph}>
|
||||
<ModelProviderGlyph
|
||||
provider={selectedProvider}
|
||||
serverId={serverId}
|
||||
size={toolbar?.glyph.size ?? ICON_SIZE.md}
|
||||
strokeWidth={toolbar?.glyph.strokeWidth}
|
||||
tone={toolbar?.glyph.tone}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
<Text style={styles.triggerText} numberOfLines={1} ellipsizeMode="tail">
|
||||
{browser.triggerLabel}
|
||||
</Text>
|
||||
</ComboboxTrigger>
|
||||
)}
|
||||
<Combobox
|
||||
options={EMPTY_COMBOBOX_OPTIONS}
|
||||
value=""
|
||||
onSelect={noop}
|
||||
open={isOpen}
|
||||
onOpenChange={handleOpenChange}
|
||||
anchorRef={anchorRef}
|
||||
desktopPlacement={desktopPlacement}
|
||||
desktopMinWidth={desktopMinWidth}
|
||||
desktopLockWidth
|
||||
desktopFixedHeight={browser.desktopFixedHeight}
|
||||
desktopChildrenScrollEnabled={false}
|
||||
header={browser.header}
|
||||
keyboard={browser.keyboard}
|
||||
mobileChildrenScrollEnabled={!browser.isProviderView || !isNative}
|
||||
mobileChildrenContentContainerStyle={styles.mobileBrowserContent}
|
||||
if (renderTrigger) {
|
||||
return (
|
||||
<Pressable
|
||||
ref={anchorRef}
|
||||
collapsable={false}
|
||||
disabled={disabled}
|
||||
onPress={onPress}
|
||||
style={triggerStyle}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={accessibilityLabel}
|
||||
testID="combined-model-selector"
|
||||
>
|
||||
{selectorBody}
|
||||
</Combobox>
|
||||
</>
|
||||
{({ pressed, hovered }: PressableStateCallbackType & { hovered?: boolean }) =>
|
||||
renderTrigger({
|
||||
selectedModelLabel: labels.triggerLabel,
|
||||
onPress,
|
||||
disabled,
|
||||
isOpen,
|
||||
hovered: Boolean(hovered),
|
||||
pressed,
|
||||
})
|
||||
}
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<ComboboxTrigger
|
||||
ref={anchorRef}
|
||||
collapsable={false}
|
||||
disabled={disabled}
|
||||
onPress={onPress}
|
||||
style={triggerStyle}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={accessibilityLabel}
|
||||
testID="combined-model-selector"
|
||||
chevron={showCaret === false ? null : undefined}
|
||||
tooltip={tooltip}
|
||||
>
|
||||
{selectedProvider.trim().length > 0 ? (
|
||||
<View style={toolbar ? styles.toolbarGlyph : styles.glyph}>
|
||||
<ModelProviderGlyph
|
||||
provider={selectedProvider}
|
||||
serverId={serverId}
|
||||
size={toolbar?.glyph.size ?? ICON_SIZE.md}
|
||||
strokeWidth={toolbar?.glyph.strokeWidth}
|
||||
tone={toolbar?.glyph.tone}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
<Text style={styles.triggerText} numberOfLines={1} ellipsizeMode="tail">
|
||||
{labels.triggerLabel}
|
||||
</Text>
|
||||
</ComboboxTrigger>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
mobileBrowserContent: {
|
||||
sheetBody: {
|
||||
paddingHorizontal: 0,
|
||||
paddingTop: 0,
|
||||
paddingBottom: 0,
|
||||
gap: 0,
|
||||
},
|
||||
trigger: {
|
||||
minWidth: 0,
|
||||
@@ -371,14 +551,4 @@ const styles = StyleSheet.create((theme) => ({
|
||||
backgroundColor: "transparent",
|
||||
borderRadius: 0,
|
||||
},
|
||||
sheetLoadingState: {
|
||||
minHeight: 160,
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
sheetLoadingText: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.base,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -2331,7 +2331,6 @@ function areExpandableBadgePropsEqual(previous: ExpandableBadgeProps, next: Expa
|
||||
}
|
||||
|
||||
interface ToolCallProps {
|
||||
agentMessage?: AgentMessage;
|
||||
serverId?: string;
|
||||
toolName: string;
|
||||
args?: unknown;
|
||||
@@ -2354,7 +2353,6 @@ interface ToolCallProps {
|
||||
}
|
||||
|
||||
export const ToolCall = memo(function ToolCall({
|
||||
agentMessage,
|
||||
serverId,
|
||||
toolName,
|
||||
args,
|
||||
@@ -2403,7 +2401,6 @@ export const ToolCall = memo(function ToolCall({
|
||||
const presentation = useMemo(
|
||||
() =>
|
||||
buildToolCallPresentation({
|
||||
agentMessage,
|
||||
toolName,
|
||||
status,
|
||||
error: error ?? null,
|
||||
@@ -2413,7 +2410,7 @@ export const ToolCall = memo(function ToolCall({
|
||||
targetAgentTitle,
|
||||
resolveIcon: resolveToolCallIcon,
|
||||
}),
|
||||
[toolName, status, error, effectiveDetail, metadata, cwd, agentMessage, targetAgentTitle],
|
||||
[toolName, status, error, effectiveDetail, metadata, cwd, targetAgentTitle],
|
||||
);
|
||||
const handleOpenFile = useMemo(() => {
|
||||
const openFilePath = presentation.openFilePath;
|
||||
@@ -2524,7 +2521,6 @@ export const ToolCall = memo(function ToolCall({
|
||||
function areToolCallPropsEqual(previous: ToolCallProps, next: ToolCallProps) {
|
||||
if (previous.toolName !== next.toolName) return false;
|
||||
if (previous.serverId !== next.serverId) return false;
|
||||
if (previous.agentMessage !== next.agentMessage) return false;
|
||||
if (previous.args !== next.args) return false;
|
||||
if (previous.result !== next.result) return false;
|
||||
if (previous.error !== next.error) return false;
|
||||
|
||||
@@ -0,0 +1,364 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { MODEL_PICKER_PROFILES_RAIL_KEY } from "@/components/model-browser-panes-view";
|
||||
import type { NavigableProfileRow } from "@/components/model-browser-view";
|
||||
import type {
|
||||
ProviderSelectionModelRow,
|
||||
ProviderSelectorProvider,
|
||||
} from "@/provider-selection/provider-selection";
|
||||
import {
|
||||
createMobileModelPageState,
|
||||
projectMobileModelPage,
|
||||
reduceMobileModelPage,
|
||||
type MobileModelPageInput,
|
||||
type MobileModelPageProjection,
|
||||
} from "./mobile-model-page-view";
|
||||
|
||||
function row(
|
||||
providerId: string,
|
||||
providerLabel: string,
|
||||
modelId: string,
|
||||
options: { legacy?: boolean } = {},
|
||||
): ProviderSelectionModelRow {
|
||||
return {
|
||||
favoriteKey: `${providerId}:${modelId}`,
|
||||
provider: providerId,
|
||||
providerLabel,
|
||||
modelId,
|
||||
modelLabel: modelId,
|
||||
...(options.legacy ? { legacy: true } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
const profile = (
|
||||
id: string,
|
||||
name: string,
|
||||
summary: string,
|
||||
provider: string,
|
||||
): NavigableProfileRow => ({
|
||||
id,
|
||||
name,
|
||||
summary,
|
||||
provider,
|
||||
});
|
||||
const reviewer = profile("reviewer", "Reviewer", "Claude · Opus 5.5 · Plan", "claude");
|
||||
const fixer = profile("fixer", "Bug fixer", "Codex · GPT-5.4", "codex");
|
||||
|
||||
const claudeOlder = Array.from({ length: 15 }, (_, index) => `claude-older-${index + 1}`);
|
||||
const claude: ProviderSelectorProvider = {
|
||||
id: "claude",
|
||||
label: "Claude",
|
||||
modelSelection: {
|
||||
kind: "models",
|
||||
rows: [
|
||||
...["opus-5.5", "fable-5.2", "sonnet-5.5", "haiku-5.5"].map((id) =>
|
||||
row("claude", "Claude", id),
|
||||
),
|
||||
...claudeOlder.map((id) => row("claude", "Claude", id, { legacy: true })),
|
||||
],
|
||||
},
|
||||
};
|
||||
const copilot: ProviderSelectorProvider = {
|
||||
id: "copilot",
|
||||
label: "Copilot",
|
||||
modelSelection: { kind: "error", message: "Not signed in" },
|
||||
};
|
||||
const codex: ProviderSelectorProvider = {
|
||||
id: "codex",
|
||||
label: "Codex",
|
||||
modelSelection: {
|
||||
kind: "models",
|
||||
rows: [row("codex", "Codex", "gpt-5.4"), row("codex", "Codex", "gpt-5.4-mini")],
|
||||
},
|
||||
};
|
||||
const opencode: ProviderSelectorProvider = {
|
||||
id: "opencode",
|
||||
label: "OpenCode",
|
||||
modelSelection: { kind: "loading" },
|
||||
};
|
||||
const pi: ProviderSelectorProvider = {
|
||||
id: "pi",
|
||||
label: "Pi",
|
||||
shownModels: ["anthropic/opus-5.5", "openai/gpt-5.4"],
|
||||
modelSelection: {
|
||||
kind: "models",
|
||||
rows: [
|
||||
row("pi", "Pi", "anthropic/opus-5.5"),
|
||||
row("pi", "Pi", "openai/gpt-5.4"),
|
||||
row("pi", "Pi", "openai/gpt-5.4-mini"),
|
||||
row("pi", "Pi", "anthropic/opus-4.6"),
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const input: MobileModelPageInput = {
|
||||
providers: [claude, copilot, codex, opencode, pi],
|
||||
profiles: null,
|
||||
canCreateProfile: false,
|
||||
selectedProvider: "claude",
|
||||
selectedModel: "opus-5.5",
|
||||
};
|
||||
|
||||
const inputWithProfiles: MobileModelPageInput = {
|
||||
...input,
|
||||
profiles: [reviewer, fixer],
|
||||
canCreateProfile: true,
|
||||
};
|
||||
|
||||
function project(
|
||||
actions: Parameters<typeof reduceMobileModelPage>[1][] = [],
|
||||
pageInput: MobileModelPageInput = input,
|
||||
): MobileModelPageProjection {
|
||||
const state = actions.reduce(reduceMobileModelPage, createMobileModelPageState(pageInput));
|
||||
return projectMobileModelPage(pageInput, state);
|
||||
}
|
||||
|
||||
function browse(projection: MobileModelPageProjection) {
|
||||
if (projection.kind !== "browse") throw new Error(`expected browse, got ${projection.kind}`);
|
||||
return projection;
|
||||
}
|
||||
|
||||
function bodyKeys(projection: MobileModelPageProjection): string[] {
|
||||
const { body } = browse(projection);
|
||||
if (!body) throw new Error("expected an expanded section body, got null");
|
||||
return body.items.map((item) => item.key);
|
||||
}
|
||||
|
||||
describe("mobile model page", () => {
|
||||
it("opens with the selected provider expanded and the others as rows, errors last", () => {
|
||||
const projection = browse(project());
|
||||
expect(projection.showSectionHeaders).toBe(true);
|
||||
expect(
|
||||
projection.sections.map((section) =>
|
||||
section.kind === "provider"
|
||||
? {
|
||||
providerId: section.providerId,
|
||||
status: section.status,
|
||||
expanded: section.expanded,
|
||||
shown: section.shown,
|
||||
total: section.total,
|
||||
}
|
||||
: section,
|
||||
),
|
||||
).toEqual([
|
||||
{ providerId: "claude", status: "ready", expanded: true, shown: 4, total: 19 },
|
||||
{ providerId: "codex", status: "ready", expanded: false, shown: 2, total: 2 },
|
||||
{ providerId: "opencode", status: "loading", expanded: false, shown: 0, total: 0 },
|
||||
{ providerId: "pi", status: "ready", expanded: false, shown: 2, total: 4 },
|
||||
{ providerId: "copilot", status: "error", expanded: false, shown: 0, total: 0 },
|
||||
]);
|
||||
});
|
||||
|
||||
it("places Profiles as the first collapsible category when the surface offers profiles", () => {
|
||||
const projection = browse(project([], inputWithProfiles));
|
||||
expect(projection.showSectionHeaders).toBe(true);
|
||||
expect(projection.sections[0]).toEqual({
|
||||
kind: "profiles",
|
||||
key: MODEL_PICKER_PROFILES_RAIL_KEY,
|
||||
count: 2,
|
||||
expanded: false,
|
||||
});
|
||||
expect(projection.sections.find((section) => section.expanded)?.key).toBe("claude");
|
||||
});
|
||||
|
||||
it("expands Profiles to list saved profiles, or Create profile when there are none", () => {
|
||||
const expanded = browse(
|
||||
project([{ kind: "toggleSection", key: MODEL_PICKER_PROFILES_RAIL_KEY }], inputWithProfiles),
|
||||
);
|
||||
expect(expanded.sections.filter((section) => section.expanded)).toMatchObject([
|
||||
{ kind: "profiles", key: MODEL_PICKER_PROFILES_RAIL_KEY },
|
||||
]);
|
||||
expect(expanded.body).toEqual({
|
||||
kind: "profiles",
|
||||
items: [
|
||||
{ kind: "profile", key: "profile:reviewer", profile: reviewer },
|
||||
{ kind: "profile", key: "profile:fixer", profile: fixer },
|
||||
],
|
||||
});
|
||||
|
||||
const emptyCreate = browse(
|
||||
project([{ kind: "toggleSection", key: MODEL_PICKER_PROFILES_RAIL_KEY }], {
|
||||
...inputWithProfiles,
|
||||
profiles: [],
|
||||
canCreateProfile: true,
|
||||
}),
|
||||
);
|
||||
expect(emptyCreate.body).toEqual({
|
||||
kind: "profiles",
|
||||
items: [{ kind: "createProfile", key: "create-profile" }],
|
||||
});
|
||||
});
|
||||
|
||||
it("collapses the open section when tapped again so every group can be collapsed", () => {
|
||||
const collapsedProvider = browse(
|
||||
project([{ kind: "toggleSection", key: "claude" }], inputWithProfiles),
|
||||
);
|
||||
expect(collapsedProvider.sections.every((section) => !section.expanded)).toBe(true);
|
||||
expect(collapsedProvider.body).toBeNull();
|
||||
expect(collapsedProvider.selectedIndex).toBeNull();
|
||||
|
||||
const collapsedProfiles = browse(
|
||||
project(
|
||||
[
|
||||
{ kind: "toggleSection", key: MODEL_PICKER_PROFILES_RAIL_KEY },
|
||||
{ kind: "toggleSection", key: MODEL_PICKER_PROFILES_RAIL_KEY },
|
||||
],
|
||||
inputWithProfiles,
|
||||
),
|
||||
);
|
||||
expect(collapsedProfiles.sections.every((section) => !section.expanded)).toBe(true);
|
||||
expect(collapsedProfiles.body).toBeNull();
|
||||
});
|
||||
|
||||
it("lists the expanded provider's shown models above a closed fold", () => {
|
||||
expect(bodyKeys(project())).toEqual([
|
||||
"model:claude:opus-5.5",
|
||||
"model:claude:fable-5.2",
|
||||
"model:claude:sonnet-5.5",
|
||||
"model:claude:haiku-5.5",
|
||||
"fold:claude",
|
||||
]);
|
||||
});
|
||||
|
||||
it("opens the fold to list the models behind it", () => {
|
||||
const keys = bodyKeys(project([{ kind: "toggleFold", providerId: "claude", expanded: true }]));
|
||||
expect(keys).toHaveLength(4 + 1 + 15);
|
||||
expect(keys[5]).toBe("model:claude:claude-older-1");
|
||||
});
|
||||
|
||||
it("expands one section at a time", () => {
|
||||
const projection = browse(project([{ kind: "toggleSection", key: "pi" }]));
|
||||
expect(projection.sections.filter((section) => section.expanded)).toMatchObject([
|
||||
{ kind: "provider", providerId: "pi" },
|
||||
]);
|
||||
expect(bodyKeys(projection)).toEqual([
|
||||
"model:pi:anthropic/opus-5.5",
|
||||
"model:pi:openai/gpt-5.4",
|
||||
"fold:pi",
|
||||
]);
|
||||
});
|
||||
|
||||
it("opens the fold when the selected model sits behind it", () => {
|
||||
const keys = bodyKeys(
|
||||
project([], { ...input, selectedProvider: "claude", selectedModel: "claude-older-3" }),
|
||||
);
|
||||
expect(keys).toContain("model:claude:claude-older-3");
|
||||
});
|
||||
|
||||
it("points the open list at the selected model, so a folded pick is in view on reopen", () => {
|
||||
const folded = browse(
|
||||
project([], { ...input, selectedProvider: "claude", selectedModel: "claude-older-3" }),
|
||||
);
|
||||
expect(
|
||||
folded.body?.kind === "provider" && folded.body.items[folded.selectedIndex ?? -1]?.key,
|
||||
).toBe("model:claude:claude-older-3");
|
||||
expect(browse(project()).selectedIndex).toBe(0);
|
||||
expect(browse(project([{ kind: "toggleSection", key: "codex" }])).selectedIndex).toBeNull();
|
||||
});
|
||||
|
||||
it("shows a loading or errored provider's state in its section", () => {
|
||||
expect(browse(project([{ kind: "toggleSection", key: "opencode" }])).body).toMatchObject({
|
||||
kind: "providerLoading",
|
||||
providerId: "opencode",
|
||||
});
|
||||
expect(browse(project([{ kind: "toggleSection", key: "copilot" }])).body).toMatchObject({
|
||||
kind: "providerError",
|
||||
providerId: "copilot",
|
||||
message: "Not signed in",
|
||||
});
|
||||
});
|
||||
|
||||
it("expands the first ready provider when the selected one is not listed and there are no profiles", () => {
|
||||
const projection = browse(project([], { ...input, selectedProvider: "", selectedModel: "" }));
|
||||
expect(projection.sections.find((section) => section.expanded)?.key).toBe("claude");
|
||||
});
|
||||
|
||||
it("lists a lone provider's models without section headers when profiles are absent, and with headers when profiles exist", () => {
|
||||
const loneWithoutProfiles = browse(
|
||||
project([], {
|
||||
providers: [codex],
|
||||
profiles: null,
|
||||
canCreateProfile: false,
|
||||
selectedProvider: "codex",
|
||||
selectedModel: "gpt-5.4",
|
||||
}),
|
||||
);
|
||||
expect(loneWithoutProfiles.showSectionHeaders).toBe(false);
|
||||
expect(bodyKeys(loneWithoutProfiles)).toEqual([
|
||||
"model:codex:gpt-5.4",
|
||||
"model:codex:gpt-5.4-mini",
|
||||
]);
|
||||
|
||||
const loneWithProfiles = browse(
|
||||
project([], {
|
||||
providers: [codex],
|
||||
profiles: [],
|
||||
canCreateProfile: true,
|
||||
selectedProvider: "codex",
|
||||
selectedModel: "gpt-5.4",
|
||||
}),
|
||||
);
|
||||
expect(loneWithProfiles.showSectionHeaders).toBe(true);
|
||||
expect(loneWithProfiles.sections.map((section) => section.key)).toEqual([
|
||||
MODEL_PICKER_PROFILES_RAIL_KEY,
|
||||
"codex",
|
||||
]);
|
||||
});
|
||||
|
||||
it("searches profiles and every provider, shown models before folded ones", () => {
|
||||
const projection = project([{ kind: "query", query: "opus" }], inputWithProfiles);
|
||||
expect(projection.kind).toBe("search");
|
||||
if (projection.kind !== "search") return;
|
||||
expect(projection.profiles.map((item) => item.key)).toEqual(["profile:reviewer"]);
|
||||
expect(
|
||||
projection.models.map((item) => (item.kind === "model" ? [item.key, item.tag] : [item.key])),
|
||||
).toEqual([
|
||||
["model:claude:opus-5.5", null],
|
||||
["model:pi:anthropic/opus-5.5", null],
|
||||
["model:pi:anthropic/opus-4.6", "all"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("finds folded models that only match behind the fold", () => {
|
||||
const projection = project([{ kind: "query", query: "older-12" }]);
|
||||
expect(projection).toMatchObject({
|
||||
kind: "search",
|
||||
items: [{ key: "model:claude:claude-older-12", tag: "older" }],
|
||||
});
|
||||
});
|
||||
|
||||
it("returns to the expanded or all-collapsed state when the search clears", () => {
|
||||
const expandedAgain = project([
|
||||
{ kind: "toggleSection", key: "pi" },
|
||||
{ kind: "query", query: "opus" },
|
||||
{ kind: "query", query: "" },
|
||||
]);
|
||||
expect(browse(expandedAgain).sections.find((section) => section.expanded)?.key).toBe("pi");
|
||||
|
||||
const stillCollapsed = project([
|
||||
{ kind: "toggleSection", key: "claude" },
|
||||
{ kind: "query", query: "opus" },
|
||||
{ kind: "query", query: "" },
|
||||
]);
|
||||
expect(browse(stillCollapsed).body).toBeNull();
|
||||
expect(browse(stillCollapsed).sections.every((section) => !section.expanded)).toBe(true);
|
||||
});
|
||||
|
||||
it("says when the host lists no providers, as it does before the first provider snapshot", () => {
|
||||
const empty: MobileModelPageInput = {
|
||||
providers: [],
|
||||
profiles: null,
|
||||
canCreateProfile: false,
|
||||
selectedProvider: "",
|
||||
selectedModel: "",
|
||||
};
|
||||
expect(project([], empty)).toEqual({ kind: "noProviders" });
|
||||
expect(project([{ kind: "query", query: "opus" }], empty)).toEqual({ kind: "noProviders" });
|
||||
});
|
||||
|
||||
it("says when nothing matches", () => {
|
||||
expect(project([{ kind: "query", query: " zzz " }])).toEqual({
|
||||
kind: "noMatches",
|
||||
query: "zzz",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,232 @@
|
||||
import {
|
||||
createModelPickerState,
|
||||
MODEL_PICKER_PROFILES_RAIL_KEY,
|
||||
projectModelPicker,
|
||||
type ModelPickerInput,
|
||||
type ModelPickerListItem,
|
||||
type ModelPickerPane,
|
||||
type ModelPickerState,
|
||||
} from "@/components/model-browser-panes-view";
|
||||
import type { NavigableProfileRow } from "@/components/model-browser-view";
|
||||
import { partitionProviderModels } from "@/provider-selection/model-curation";
|
||||
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
|
||||
|
||||
/**
|
||||
* The compact model picker: Profiles (when the surface offers them) and one section per provider,
|
||||
* stacked as an accordion. At most one section is open at a time, and tapping the open section
|
||||
* collapses it so every group can sit closed. A query replaces the accordion with ranked results
|
||||
* across profiles and every provider, folded models included.
|
||||
*
|
||||
* It delegates to the desktop picker's projection so both form factors order, fold, rank and
|
||||
* search the same way.
|
||||
*/
|
||||
|
||||
export interface MobileModelPageInput<TProfile extends NavigableProfileRow = NavigableProfileRow> {
|
||||
providers: readonly ProviderSelectorProvider[];
|
||||
/** `null` when the surface offers no profiles. */
|
||||
profiles: readonly TProfile[] | null;
|
||||
canCreateProfile: boolean;
|
||||
selectedProvider: string;
|
||||
selectedModel: string;
|
||||
}
|
||||
|
||||
export interface MobileModelPageState {
|
||||
query: string;
|
||||
/** The open section (`MODEL_PICKER_PROFILES_RAIL_KEY` or a provider id), or `null` when all are collapsed. */
|
||||
expandedKey: string | null;
|
||||
/** Folds the user opened or closed, by provider. Others follow the partition's default. */
|
||||
foldOverrides: Readonly<Record<string, boolean>>;
|
||||
}
|
||||
|
||||
export type MobileModelPageAction =
|
||||
| { kind: "query"; query: string }
|
||||
| { kind: "toggleSection"; key: string }
|
||||
| { kind: "toggleFold"; providerId: string; expanded: boolean };
|
||||
|
||||
export interface MobileProfilesSection {
|
||||
kind: "profiles";
|
||||
key: typeof MODEL_PICKER_PROFILES_RAIL_KEY;
|
||||
count: number;
|
||||
expanded: boolean;
|
||||
}
|
||||
|
||||
export interface MobileProviderSection {
|
||||
kind: "provider";
|
||||
key: string;
|
||||
providerId: string;
|
||||
label: string;
|
||||
status: "ready" | "loading" | "error";
|
||||
/** Models listed before the fold. */
|
||||
shown: number;
|
||||
total: number;
|
||||
/** Some models sit behind a fold, so `shown` and `total` differ in meaning. */
|
||||
folds: boolean;
|
||||
expanded: boolean;
|
||||
}
|
||||
|
||||
export type MobileModelSection = MobileProfilesSection | MobileProviderSection;
|
||||
|
||||
export type MobileModelBody<TProfile extends NavigableProfileRow = NavigableProfileRow> = Extract<
|
||||
ModelPickerPane<TProfile>,
|
||||
{ kind: "profiles" | "provider" | "providerLoading" | "providerError" }
|
||||
>;
|
||||
|
||||
export type MobileModelPageProjection<TProfile extends NavigableProfileRow = NavigableProfileRow> =
|
||||
| {
|
||||
kind: "browse";
|
||||
sections: MobileModelSection[];
|
||||
/** False for a lone provider without profiles: its models are the page, with no header above them. */
|
||||
showSectionHeaders: boolean;
|
||||
/** What the open section lists, or `null` when every section is collapsed. */
|
||||
body: MobileModelBody<TProfile> | null;
|
||||
/** The selected model's row in the open list, which the list scrolls into view. */
|
||||
selectedIndex: number | null;
|
||||
}
|
||||
| {
|
||||
kind: "search";
|
||||
profiles: ModelPickerListItem<TProfile>[];
|
||||
models: ModelPickerListItem<TProfile>[];
|
||||
items: ModelPickerListItem<TProfile>[];
|
||||
}
|
||||
| { kind: "noMatches"; query: string }
|
||||
/** The host lists no providers, which is also the state before its first provider snapshot. */
|
||||
| { kind: "noProviders" };
|
||||
|
||||
export function createMobileModelPageState<TProfile extends NavigableProfileRow>(
|
||||
input: MobileModelPageInput<TProfile>,
|
||||
): MobileModelPageState {
|
||||
return {
|
||||
query: "",
|
||||
expandedKey: createModelPickerState(toPickerInput(input)).railKey,
|
||||
foldOverrides: {},
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceMobileModelPage(
|
||||
state: MobileModelPageState,
|
||||
action: MobileModelPageAction,
|
||||
): MobileModelPageState {
|
||||
switch (action.kind) {
|
||||
case "query":
|
||||
return { ...state, query: action.query };
|
||||
case "toggleSection":
|
||||
return {
|
||||
...state,
|
||||
expandedKey: state.expandedKey === action.key ? null : action.key,
|
||||
};
|
||||
case "toggleFold":
|
||||
return {
|
||||
...state,
|
||||
foldOverrides: { ...state.foldOverrides, [action.providerId]: action.expanded },
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function projectMobileModelPage<TProfile extends NavigableProfileRow>(
|
||||
input: MobileModelPageInput<TProfile>,
|
||||
state: MobileModelPageState,
|
||||
): MobileModelPageProjection<TProfile> {
|
||||
if (input.providers.length === 0) return { kind: "noProviders" };
|
||||
const picker = projectModelPicker<TProfile>(toPickerInput(input), toPickerState(state));
|
||||
const { pane } = picker;
|
||||
if (pane.kind === "noMatches") return { kind: "noMatches", query: pane.query };
|
||||
if (pane.kind === "search") {
|
||||
return { kind: "search", profiles: pane.profiles, models: pane.models, items: pane.items };
|
||||
}
|
||||
const sections: MobileModelSection[] = [];
|
||||
if (picker.layout === "twoPane") {
|
||||
for (const item of picker.rail) {
|
||||
if (item.kind === "profiles") {
|
||||
sections.push({
|
||||
kind: "profiles",
|
||||
key: item.key,
|
||||
count: item.count,
|
||||
expanded: false,
|
||||
});
|
||||
} else {
|
||||
const provider = input.providers.find((entry) => entry.id === item.providerId);
|
||||
if (provider) sections.push(toProviderSection(provider, false));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const provider = input.providers.find((entry) => entry.id === picker.railKey);
|
||||
if (provider) sections.push(toProviderSection(provider, true));
|
||||
}
|
||||
const showSectionHeaders = sections.length > 1;
|
||||
const expandedKey = showSectionHeaders && state.expandedKey === null ? null : picker.railKey;
|
||||
for (const section of sections) {
|
||||
section.expanded = section.key === expandedKey;
|
||||
}
|
||||
const body = expandedKey === null ? null : pane;
|
||||
return {
|
||||
kind: "browse",
|
||||
sections,
|
||||
showSectionHeaders,
|
||||
body,
|
||||
selectedIndex: body ? findSelectedIndex(body, input) : null,
|
||||
};
|
||||
}
|
||||
|
||||
function findSelectedIndex<TProfile extends NavigableProfileRow>(
|
||||
body: MobileModelBody<TProfile>,
|
||||
input: MobileModelPageInput<TProfile>,
|
||||
): number | null {
|
||||
if (body.kind !== "provider" || body.providerId !== input.selectedProvider) return null;
|
||||
const index = body.items.findIndex(
|
||||
(item) => item.kind === "model" && item.row.modelId === input.selectedModel,
|
||||
);
|
||||
return index >= 0 ? index : null;
|
||||
}
|
||||
|
||||
function toPickerInput<TProfile extends NavigableProfileRow>(
|
||||
input: MobileModelPageInput<TProfile>,
|
||||
): ModelPickerInput<TProfile> {
|
||||
return {
|
||||
providers: input.providers,
|
||||
profiles: input.profiles,
|
||||
canCreateProfile: input.canCreateProfile,
|
||||
selectedProvider: input.selectedProvider,
|
||||
selectedModel: input.selectedModel,
|
||||
};
|
||||
}
|
||||
|
||||
function toPickerState(state: MobileModelPageState): ModelPickerState {
|
||||
return {
|
||||
query: state.query,
|
||||
railKey: state.expandedKey ?? "",
|
||||
focus: "list",
|
||||
activeKey: null,
|
||||
foldOverrides: state.foldOverrides,
|
||||
};
|
||||
}
|
||||
|
||||
function toProviderSection(
|
||||
provider: ProviderSelectorProvider,
|
||||
expanded: boolean,
|
||||
): MobileProviderSection {
|
||||
const base = {
|
||||
kind: "provider" as const,
|
||||
key: provider.id,
|
||||
providerId: provider.id,
|
||||
label: provider.label,
|
||||
expanded,
|
||||
};
|
||||
const selection = provider.modelSelection;
|
||||
if (selection.kind !== "models") {
|
||||
return {
|
||||
...base,
|
||||
status: selection.kind === "loading" ? "loading" : "error",
|
||||
shown: 0,
|
||||
total: 0,
|
||||
folds: false,
|
||||
};
|
||||
}
|
||||
const partition = partitionProviderModels(selection.rows, provider.shownModels, "");
|
||||
return {
|
||||
...base,
|
||||
status: "ready",
|
||||
shown: partition.primary.length,
|
||||
total: selection.rows.length,
|
||||
folds: partition.foldKind !== null,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,852 @@
|
||||
import { useCallback, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { FlatList, Text, View } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { AlertTriangle, ChevronDown, ChevronUp, Layers, Pencil } from "lucide-react-native";
|
||||
import type { AgentProfilePickerRow } from "@/agent-profiles";
|
||||
import {
|
||||
IndependentScrollBoundary,
|
||||
ModelBrowserLoadingState,
|
||||
ModelBrowserNoProviders,
|
||||
ModelBrowserRow,
|
||||
ModelBrowserSectionHeading,
|
||||
ModelProviderGlyph,
|
||||
ModelSearchNoMatches,
|
||||
ProviderErrorEmptyState,
|
||||
} from "@/components/model-browser";
|
||||
import {
|
||||
CustomizeProviderButton,
|
||||
ModelPickerItemRow,
|
||||
type ModelPickerActions,
|
||||
} from "@/components/model-browser-panes";
|
||||
import type { ModelPickerListItem } from "@/components/model-browser-panes-view";
|
||||
import { groupProfilesByProviderModel } from "@/components/model-browser-view";
|
||||
import {
|
||||
createMobileModelPageState,
|
||||
projectMobileModelPage,
|
||||
reduceMobileModelPage,
|
||||
type MobileModelBody,
|
||||
type MobileModelPageAction,
|
||||
type MobileModelPageInput,
|
||||
type MobileModelPageProjection,
|
||||
type MobileModelSection,
|
||||
type MobileProfilesSection,
|
||||
type MobileProviderSection,
|
||||
} from "@/components/mobile-model-page-view";
|
||||
import { SettingsCard } from "@/components/settings";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { PressHighlight } from "@/components/ui/press-highlight";
|
||||
import {
|
||||
FlatList as SheetFlatList,
|
||||
ScrollView as SheetScrollView,
|
||||
} from "@/components/ui/scroll-view";
|
||||
import { SearchField } from "@/components/ui/search-field";
|
||||
import { useRevealActiveFlatListRow } from "@/components/ui/scroll-reveal";
|
||||
import { isNative } from "@/constants/platform";
|
||||
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
|
||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||
|
||||
/**
|
||||
* The open accordion section lists its rows in a box of one fixed height, about five rows, that
|
||||
* scrolls on its own. Opening another section, unfolding older models or loading never moves the
|
||||
* sections below it, so they stay where the thumb left them.
|
||||
*/
|
||||
export const MOBILE_EXPANDED_PROVIDER_HEIGHT = 220;
|
||||
|
||||
/** Theme-free: the sheet scrollers drop a themed contentContainerStyle on web (docs/unistyles.md). */
|
||||
const LIST_CONTENT = { paddingBottom: 4 };
|
||||
const SHEET_LIST_CARD_LIST = { flexGrow: 0, flexShrink: 1, minHeight: 0 };
|
||||
const EXPANDED_A11Y_STATE = { expanded: true };
|
||||
|
||||
const ThemedAlertTriangle = withUnistyles(AlertTriangle);
|
||||
const ThemedChevronDown = withUnistyles(ChevronDown);
|
||||
const ThemedChevronUp = withUnistyles(ChevronUp);
|
||||
const ThemedLayers = withUnistyles(Layers);
|
||||
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
|
||||
const foregroundMapping = (theme: Theme) => ({ color: theme.colors.foreground });
|
||||
const foregroundMutedMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
|
||||
// React Native Web blurs the focused input on every scroll in "on-drag" mode.
|
||||
const KEYBOARD_DISMISS_MODE = isNative ? "on-drag" : "none";
|
||||
const NO_PROFILES: AgentProfilePickerRow[] = [];
|
||||
|
||||
export interface MobileModelPage {
|
||||
projection: MobileModelPageProjection<AgentProfilePickerRow>;
|
||||
query: string;
|
||||
/** Changes when the search is cleared from outside the field, so the field remounts empty. */
|
||||
searchKey: number;
|
||||
setQuery: (query: string) => void;
|
||||
clearQuery: () => void;
|
||||
dispatch: (action: MobileModelPageAction) => void;
|
||||
/** Starts over from the current selection: its provider open, no search. */
|
||||
reset: () => void;
|
||||
}
|
||||
|
||||
export function useMobileModelPage(input: {
|
||||
providers: readonly ProviderSelectorProvider[];
|
||||
profiles?: readonly AgentProfilePickerRow[] | null;
|
||||
canCreateProfile?: boolean;
|
||||
selectedProvider: string;
|
||||
selectedModel: string;
|
||||
}): MobileModelPage {
|
||||
const {
|
||||
providers,
|
||||
profiles = null,
|
||||
canCreateProfile = false,
|
||||
selectedProvider,
|
||||
selectedModel,
|
||||
} = input;
|
||||
const pageInput = useMemo<MobileModelPageInput<AgentProfilePickerRow>>(
|
||||
() => ({ providers, profiles, canCreateProfile, selectedProvider, selectedModel }),
|
||||
[canCreateProfile, profiles, providers, selectedModel, selectedProvider],
|
||||
);
|
||||
const inputRef = useRef(pageInput);
|
||||
inputRef.current = pageInput;
|
||||
const [state, setState] = useState(() => createMobileModelPageState(pageInput));
|
||||
const [searchKey, setSearchKey] = useState(0);
|
||||
const projection = useMemo(() => projectMobileModelPage(pageInput, state), [pageInput, state]);
|
||||
const dispatch = useCallback((action: MobileModelPageAction) => {
|
||||
setState((current) => reduceMobileModelPage(current, action));
|
||||
}, []);
|
||||
const setQuery = useCallback((query: string) => dispatch({ kind: "query", query }), [dispatch]);
|
||||
const clearQuery = useCallback(() => {
|
||||
dispatch({ kind: "query", query: "" });
|
||||
setSearchKey((key) => key + 1);
|
||||
}, [dispatch]);
|
||||
const reset = useCallback(() => {
|
||||
setState(createMobileModelPageState(inputRef.current));
|
||||
setSearchKey((key) => key + 1);
|
||||
}, []);
|
||||
return useMemo(
|
||||
() => ({ projection, query: state.query, searchKey, setQuery, clearQuery, dispatch, reset }),
|
||||
[clearQuery, dispatch, projection, reset, searchKey, setQuery, state.query],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The search that sits at the bottom of a compact sheet page, in reach of the thumb. It never takes
|
||||
* focus by itself, so the keyboard stays down until the user taps it.
|
||||
*/
|
||||
export function SheetSearchDock({
|
||||
query,
|
||||
searchKey,
|
||||
onChangeText,
|
||||
placeholder,
|
||||
testID,
|
||||
}: {
|
||||
query: string;
|
||||
searchKey: number;
|
||||
onChangeText: (query: string) => void;
|
||||
placeholder: string;
|
||||
testID?: string;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<View style={styles.dock}>
|
||||
<SearchField
|
||||
key={searchKey}
|
||||
value={query}
|
||||
onChangeText={onChangeText}
|
||||
placeholder={placeholder}
|
||||
clearAccessibilityLabel={t("providerCatalog.clearSearch")}
|
||||
fullWidth
|
||||
testID={testID}
|
||||
clearTestID={testID ? `${testID}-clear` : undefined}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export interface MobileModelPageViewProps {
|
||||
page: MobileModelPage;
|
||||
/** Keep this object stable across renders; the list re-renders its rows when it changes. */
|
||||
actions: ModelPickerActions;
|
||||
selectedProvider: string;
|
||||
selectedModel: string;
|
||||
serverId: string | null;
|
||||
/** Profiles whose model a row names, for the row's profile action. */
|
||||
profiles?: readonly AgentProfilePickerRow[] | null;
|
||||
}
|
||||
|
||||
type SearchEntry =
|
||||
| { kind: "heading"; key: string; title: string }
|
||||
| { kind: "item"; key: string; item: ModelPickerListItem<AgentProfilePickerRow> };
|
||||
|
||||
/** The compact model picker's body; its search is a `SheetSearchDock` in the sheet's footer. */
|
||||
export function MobileModelPageView({
|
||||
page,
|
||||
selectedProvider,
|
||||
selectedModel,
|
||||
serverId,
|
||||
profiles,
|
||||
actions,
|
||||
}: MobileModelPageViewProps) {
|
||||
const { t } = useTranslation();
|
||||
const { projection, dispatch } = page;
|
||||
const profiledLookup = useMemo(
|
||||
() => groupProfilesByProviderModel(profiles ?? NO_PROFILES),
|
||||
[profiles],
|
||||
);
|
||||
const handleToggleFold = useCallback(
|
||||
(item: Extract<ModelPickerListItem, { kind: "fold" }>) =>
|
||||
dispatch({ kind: "toggleFold", providerId: item.providerId, expanded: !item.expanded }),
|
||||
[dispatch],
|
||||
);
|
||||
const renderItem = useCallback(
|
||||
({ item }: { item: ModelPickerListItem<AgentProfilePickerRow> }) => (
|
||||
<ModelPickerItemRow
|
||||
item={item}
|
||||
active={false}
|
||||
selected={
|
||||
item.kind === "model" &&
|
||||
item.row.provider === selectedProvider &&
|
||||
item.row.modelId === selectedModel
|
||||
}
|
||||
inSearch={projection.kind === "search"}
|
||||
serverId={serverId}
|
||||
profiledLookup={profiledLookup}
|
||||
onToggleFold={handleToggleFold}
|
||||
onActivate={noop}
|
||||
actions={actions}
|
||||
/>
|
||||
),
|
||||
[
|
||||
actions,
|
||||
handleToggleFold,
|
||||
profiledLookup,
|
||||
projection.kind,
|
||||
selectedModel,
|
||||
selectedProvider,
|
||||
serverId,
|
||||
],
|
||||
);
|
||||
const searchEntries = useMemo<SearchEntry[]>(() => {
|
||||
if (projection.kind !== "search") return [];
|
||||
const toEntry = (item: ModelPickerListItem<AgentProfilePickerRow>): SearchEntry => ({
|
||||
kind: "item",
|
||||
key: item.key,
|
||||
item,
|
||||
});
|
||||
const entries: SearchEntry[] = [];
|
||||
if (projection.profiles.length > 0) {
|
||||
entries.push({
|
||||
kind: "heading",
|
||||
key: "heading:profiles",
|
||||
title: t("modelSelector.profiles"),
|
||||
});
|
||||
entries.push(...projection.profiles.map(toEntry));
|
||||
if (projection.models.length > 0) {
|
||||
entries.push({
|
||||
kind: "heading",
|
||||
key: "heading:models",
|
||||
title: t("modelSelector.models"),
|
||||
});
|
||||
}
|
||||
}
|
||||
entries.push(...projection.models.map(toEntry));
|
||||
return entries;
|
||||
}, [projection, t]);
|
||||
const renderSearchEntry = useCallback(
|
||||
({ item }: { item: SearchEntry }) =>
|
||||
item.kind === "heading" ? (
|
||||
<ModelBrowserSectionHeading title={item.title} />
|
||||
) : (
|
||||
renderItem({ item: item.item })
|
||||
),
|
||||
[renderItem],
|
||||
);
|
||||
|
||||
if (projection.kind === "noProviders") {
|
||||
return (
|
||||
<View style={styles.page}>
|
||||
<ModelBrowserNoProviders />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
if (projection.kind === "noMatches") {
|
||||
return (
|
||||
<View style={styles.page}>
|
||||
<ModelSearchNoMatches query={projection.query} />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
if (projection.kind === "search") {
|
||||
return (
|
||||
<SheetListCard>
|
||||
<SheetFlatList
|
||||
data={searchEntries}
|
||||
renderItem={renderSearchEntry}
|
||||
keyExtractor={getSearchEntryKey}
|
||||
style={SHEET_LIST_CARD_LIST}
|
||||
contentContainerStyle={LIST_CONTENT}
|
||||
keyboardShouldPersistTaps="handled"
|
||||
keyboardDismissMode={KEYBOARD_DISMISS_MODE}
|
||||
showsVerticalScrollIndicator={false}
|
||||
testID="mobile-model-search-results"
|
||||
/>
|
||||
</SheetListCard>
|
||||
);
|
||||
}
|
||||
if (!projection.showSectionHeaders) {
|
||||
const section = projection.sections[0];
|
||||
return (
|
||||
<View style={styles.page} testID="mobile-model-page">
|
||||
{section?.kind === "provider" ? (
|
||||
<ExpandedProviderHeader section={section} serverId={serverId} />
|
||||
) : null}
|
||||
{projection.body ? (
|
||||
<SectionBody
|
||||
body={projection.body}
|
||||
selectedIndex={projection.selectedIndex}
|
||||
renderItem={renderItem}
|
||||
fill
|
||||
onRetryProvider={actions.onRetryProvider}
|
||||
isRetryingProvider={actions.isRetryingProvider}
|
||||
/>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<SheetScrollView
|
||||
style={styles.page}
|
||||
keyboardShouldPersistTaps="handled"
|
||||
keyboardDismissMode={KEYBOARD_DISMISS_MODE}
|
||||
showsVerticalScrollIndicator={false}
|
||||
testID="mobile-model-page"
|
||||
>
|
||||
{/* Themed insets sit on a View: the sheet scroller drops a themed contentContainerStyle on web. */}
|
||||
<View style={styles.sections}>
|
||||
{projection.sections.map((section) => (
|
||||
<AccordionSectionCard
|
||||
key={section.key}
|
||||
section={section}
|
||||
body={projection.body}
|
||||
selectedIndex={projection.selectedIndex}
|
||||
serverId={serverId}
|
||||
actions={actions}
|
||||
renderItem={renderItem}
|
||||
onToggle={dispatch}
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
</SheetScrollView>
|
||||
);
|
||||
}
|
||||
|
||||
function AccordionSectionCard({
|
||||
section,
|
||||
body,
|
||||
selectedIndex,
|
||||
serverId,
|
||||
actions,
|
||||
renderItem,
|
||||
onToggle,
|
||||
}: {
|
||||
section: MobileModelSection;
|
||||
body: MobileModelBody<AgentProfilePickerRow> | null;
|
||||
selectedIndex: number | null;
|
||||
serverId: string | null;
|
||||
actions: ModelPickerActions;
|
||||
renderItem: ModelItemRenderer;
|
||||
onToggle: (action: MobileModelPageAction) => void;
|
||||
}) {
|
||||
if (!section.expanded) {
|
||||
return (
|
||||
<SettingsCard>
|
||||
{section.kind === "profiles" ? (
|
||||
<CollapsedProfilesRow section={section} onToggle={onToggle} />
|
||||
) : (
|
||||
<CollapsedProviderRow section={section} serverId={serverId} onToggle={onToggle} />
|
||||
)}
|
||||
</SettingsCard>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<SettingsCard>
|
||||
{section.kind === "profiles" ? (
|
||||
<ExpandedProfilesHeader
|
||||
section={section}
|
||||
onEditProfiles={actions.onEditProfiles}
|
||||
onToggle={onToggle}
|
||||
/>
|
||||
) : (
|
||||
<ExpandedProviderHeader section={section} serverId={serverId} onToggle={onToggle} />
|
||||
)}
|
||||
{body ? (
|
||||
<SectionBody
|
||||
body={body}
|
||||
selectedIndex={selectedIndex}
|
||||
renderItem={renderItem}
|
||||
fill={false}
|
||||
onRetryProvider={actions.onRetryProvider}
|
||||
isRetryingProvider={actions.isRetryingProvider}
|
||||
/>
|
||||
) : null}
|
||||
</SettingsCard>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* An inset card holding one sheet list, on the same rail as the browse sections' cards. It grows
|
||||
* with the list, then the list scrolls inside it.
|
||||
*/
|
||||
function SheetListCard({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<View style={styles.listCardPage}>
|
||||
<SettingsCard shrink>{children}</SettingsCard>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function noop() {}
|
||||
|
||||
function getItemKey(item: ModelPickerListItem<AgentProfilePickerRow>): string {
|
||||
return item.key;
|
||||
}
|
||||
|
||||
function getSearchEntryKey(entry: SearchEntry): string {
|
||||
return entry.key;
|
||||
}
|
||||
|
||||
function useSectionSummary(section: MobileProviderSection): string {
|
||||
const { t } = useTranslation();
|
||||
if (section.folds) {
|
||||
return t("modelSelector.shownOfTotal", { shown: section.shown, total: section.total });
|
||||
}
|
||||
return String(section.total);
|
||||
}
|
||||
|
||||
function ExpandedSectionHeader({
|
||||
leading,
|
||||
title,
|
||||
summary,
|
||||
trailing,
|
||||
onCollapse,
|
||||
testID,
|
||||
}: {
|
||||
leading: ReactNode;
|
||||
title: string;
|
||||
summary: string | null;
|
||||
trailing?: ReactNode;
|
||||
onCollapse?: () => void;
|
||||
testID: string;
|
||||
}) {
|
||||
const titleContent = (
|
||||
<>
|
||||
<View style={styles.glyph}>{leading}</View>
|
||||
<Text style={styles.expandedTitle} numberOfLines={1}>
|
||||
{title}
|
||||
{summary !== null ? <Text style={styles.summary}>{` · ${summary}`}</Text> : null}
|
||||
</Text>
|
||||
</>
|
||||
);
|
||||
if (!onCollapse) {
|
||||
return (
|
||||
<View style={styles.expandedHeader} testID={testID}>
|
||||
<View style={styles.expandedTrigger}>{titleContent}</View>
|
||||
{trailing}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<View style={styles.expandedHeader}>
|
||||
<PressHighlight
|
||||
onPress={onCollapse}
|
||||
accessibilityRole="button"
|
||||
accessibilityState={EXPANDED_A11Y_STATE}
|
||||
style={styles.expandedTrigger}
|
||||
testID={testID}
|
||||
>
|
||||
{titleContent}
|
||||
</PressHighlight>
|
||||
<View style={styles.expandedTrailing}>
|
||||
{trailing}
|
||||
<PressHighlight
|
||||
onPress={onCollapse}
|
||||
hitSlop={8}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={title}
|
||||
accessibilityState={EXPANDED_A11Y_STATE}
|
||||
style={styles.collapseChevron}
|
||||
>
|
||||
<ThemedChevronUp size={ICON_SIZE.sm} uniProps={foregroundMutedMapping} />
|
||||
</PressHighlight>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function ExpandedProfilesHeader({
|
||||
section,
|
||||
onEditProfiles,
|
||||
onToggle,
|
||||
}: {
|
||||
section: MobileProfilesSection;
|
||||
onEditProfiles?: () => void;
|
||||
onToggle: (action: MobileModelPageAction) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const handleCollapse = useCallback(
|
||||
() => onToggle({ kind: "toggleSection", key: section.key }),
|
||||
[onToggle, section.key],
|
||||
);
|
||||
const leading = useMemo(
|
||||
() => <ThemedLayers size={ICON_SIZE.sm} uniProps={foregroundMapping} />,
|
||||
[],
|
||||
);
|
||||
const trailing = useMemo(
|
||||
() =>
|
||||
onEditProfiles ? (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
leftIcon={Pencil}
|
||||
onPress={onEditProfiles}
|
||||
accessibilityLabel={t("modelSelector.editProfilesLabel")}
|
||||
testID="model-profiles-edit"
|
||||
/>
|
||||
) : null,
|
||||
[onEditProfiles, t],
|
||||
);
|
||||
return (
|
||||
<ExpandedSectionHeader
|
||||
leading={leading}
|
||||
title={t("modelSelector.profiles")}
|
||||
summary={String(section.count)}
|
||||
trailing={trailing}
|
||||
onCollapse={handleCollapse}
|
||||
testID="model-profiles-section"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CollapsedProfilesRow({
|
||||
section,
|
||||
onToggle,
|
||||
}: {
|
||||
section: MobileProfilesSection;
|
||||
onToggle: (action: MobileModelPageAction) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const handlePress = useCallback(
|
||||
() => onToggle({ kind: "toggleSection", key: section.key }),
|
||||
[onToggle, section.key],
|
||||
);
|
||||
const leadingSlot = useMemo(
|
||||
() => <ThemedLayers size={ICON_SIZE.sm} uniProps={foregroundMutedMapping} />,
|
||||
[],
|
||||
);
|
||||
const trailingSlot = useMemo(
|
||||
() => (
|
||||
<View style={styles.collapsedTrailing}>
|
||||
<Text style={styles.summary}>{section.count}</Text>
|
||||
<ThemedChevronDown size={ICON_SIZE.sm} uniProps={foregroundMutedMapping} />
|
||||
</View>
|
||||
),
|
||||
[section.count],
|
||||
);
|
||||
return (
|
||||
<ModelBrowserRow
|
||||
label={t("modelSelector.profiles")}
|
||||
leadingSlot={leadingSlot}
|
||||
trailingSlot={trailingSlot}
|
||||
spacing="provider"
|
||||
onPress={handlePress}
|
||||
testID="model-picker-rail-profiles"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function ExpandedProviderHeader({
|
||||
section,
|
||||
serverId,
|
||||
onToggle,
|
||||
}: {
|
||||
section: MobileProviderSection;
|
||||
serverId: string | null;
|
||||
onToggle?: (action: MobileModelPageAction) => void;
|
||||
}) {
|
||||
const summary = useSectionSummary(section);
|
||||
const handleCollapse = useCallback(
|
||||
() => onToggle?.({ kind: "toggleSection", key: section.key }),
|
||||
[onToggle, section.key],
|
||||
);
|
||||
const leading = useMemo(
|
||||
() => (
|
||||
<ModelProviderGlyph
|
||||
provider={section.providerId}
|
||||
serverId={serverId}
|
||||
size={ICON_SIZE.sm}
|
||||
tone="foreground"
|
||||
/>
|
||||
),
|
||||
[section.providerId, serverId],
|
||||
);
|
||||
const trailing = useMemo(
|
||||
() =>
|
||||
serverId ? (
|
||||
<CustomizeProviderButton
|
||||
serverId={serverId}
|
||||
providerId={section.providerId}
|
||||
providerLabel={section.label}
|
||||
/>
|
||||
) : null,
|
||||
[section.label, section.providerId, serverId],
|
||||
);
|
||||
return (
|
||||
<ExpandedSectionHeader
|
||||
leading={leading}
|
||||
title={section.label}
|
||||
summary={section.status === "ready" ? summary : null}
|
||||
trailing={trailing}
|
||||
onCollapse={onToggle ? handleCollapse : undefined}
|
||||
testID={`model-provider-section-${section.providerId}`}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CollapsedProviderRow({
|
||||
section,
|
||||
serverId,
|
||||
onToggle,
|
||||
}: {
|
||||
section: MobileProviderSection;
|
||||
serverId: string | null;
|
||||
onToggle: (action: MobileModelPageAction) => void;
|
||||
}) {
|
||||
const summary = useSectionSummary(section);
|
||||
const handlePress = useCallback(
|
||||
() => onToggle({ kind: "toggleSection", key: section.key }),
|
||||
[onToggle, section.key],
|
||||
);
|
||||
const leadingSlot = useMemo(
|
||||
() => (
|
||||
<ModelProviderGlyph provider={section.providerId} serverId={serverId} size={ICON_SIZE.sm} />
|
||||
),
|
||||
[section.providerId, serverId],
|
||||
);
|
||||
const trailingSlot = useMemo(
|
||||
() => (
|
||||
<View style={styles.collapsedTrailing}>
|
||||
<CollapsedStatus section={section} summary={summary} />
|
||||
<ThemedChevronDown size={ICON_SIZE.sm} uniProps={foregroundMutedMapping} />
|
||||
</View>
|
||||
),
|
||||
[section, summary],
|
||||
);
|
||||
return (
|
||||
<ModelBrowserRow
|
||||
label={section.label}
|
||||
leadingSlot={leadingSlot}
|
||||
trailingSlot={trailingSlot}
|
||||
spacing="provider"
|
||||
onPress={handlePress}
|
||||
testID={`model-provider-${section.providerId}`}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CollapsedStatus({
|
||||
section,
|
||||
summary,
|
||||
}: {
|
||||
section: MobileProviderSection;
|
||||
summary: string;
|
||||
}) {
|
||||
if (section.status === "loading") {
|
||||
return (
|
||||
<View style={styles.spinner}>
|
||||
<ThemedLoadingSpinner size="small" uniProps={foregroundMutedMapping} />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
if (section.status === "error") {
|
||||
return <ThemedAlertTriangle size={ICON_SIZE.sm} uniProps={foregroundMutedMapping} />;
|
||||
}
|
||||
return <Text style={styles.summary}>{summary}</Text>;
|
||||
}
|
||||
|
||||
type ModelItemRenderer = ({
|
||||
item,
|
||||
}: {
|
||||
item: ModelPickerListItem<AgentProfilePickerRow>;
|
||||
}) => React.ReactElement;
|
||||
|
||||
function SectionBody({
|
||||
body,
|
||||
selectedIndex,
|
||||
renderItem,
|
||||
fill,
|
||||
onRetryProvider,
|
||||
isRetryingProvider,
|
||||
}: {
|
||||
body: MobileModelBody<AgentProfilePickerRow>;
|
||||
selectedIndex: number | null;
|
||||
renderItem: ModelItemRenderer;
|
||||
/** A lone provider's list fills the page; an open section keeps its fixed height. */
|
||||
fill: boolean;
|
||||
onRetryProvider: ModelPickerActions["onRetryProvider"];
|
||||
isRetryingProvider: boolean;
|
||||
}) {
|
||||
const frameStyle = fill ? styles.page : styles.fixedViewport;
|
||||
if (body.kind === "providerLoading") {
|
||||
return (
|
||||
<View style={[frameStyle, styles.centered]}>
|
||||
<ModelBrowserLoadingState />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
if (body.kind === "providerError") {
|
||||
return (
|
||||
<View style={[frameStyle, styles.centered]}>
|
||||
<ProviderErrorEmptyState
|
||||
providerId={body.providerId}
|
||||
message={body.message}
|
||||
onRetryProvider={onRetryProvider}
|
||||
isRetryingProvider={isRetryingProvider}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
const listKey = body.kind === "profiles" ? "profiles" : body.providerId;
|
||||
const list = (
|
||||
<SectionItemList
|
||||
// Each section is a new list, which opens at its top or at the selected model.
|
||||
key={listKey}
|
||||
items={body.items}
|
||||
selectedIndex={selectedIndex}
|
||||
renderItem={renderItem}
|
||||
fill={fill}
|
||||
/>
|
||||
);
|
||||
// The lone provider's list is the page's only scroller; a fixed box scrolls inside the page's.
|
||||
return fill ? list : <IndependentScrollBoundary>{list}</IndependentScrollBoundary>;
|
||||
}
|
||||
|
||||
/** Opens with the selected model in view, such as an older model behind the opened fold. */
|
||||
function SectionItemList({
|
||||
items,
|
||||
selectedIndex,
|
||||
renderItem,
|
||||
fill,
|
||||
}: {
|
||||
items: ModelPickerListItem<AgentProfilePickerRow>[];
|
||||
selectedIndex: number | null;
|
||||
renderItem: ModelItemRenderer;
|
||||
fill: boolean;
|
||||
}) {
|
||||
const listRef = useRef<FlatList<ModelPickerListItem<AgentProfilePickerRow>>>(null);
|
||||
// Waits for the first visible rows, so a selection already in view never scrolls the list.
|
||||
const reveal = useRevealActiveFlatListRow({
|
||||
listRef,
|
||||
itemCount: items.length,
|
||||
activeIndex: selectedIndex,
|
||||
waitForViewable: true,
|
||||
});
|
||||
return (
|
||||
<FlatList
|
||||
ref={listRef}
|
||||
data={items}
|
||||
renderItem={renderItem}
|
||||
keyExtractor={getItemKey}
|
||||
style={fill ? styles.page : styles.fixedViewport}
|
||||
contentContainerStyle={LIST_CONTENT}
|
||||
keyboardShouldPersistTaps="handled"
|
||||
keyboardDismissMode={KEYBOARD_DISMISS_MODE}
|
||||
showsVerticalScrollIndicator
|
||||
nestedScrollEnabled
|
||||
onScrollToIndexFailed={reveal.onScrollToIndexFailed}
|
||||
onViewableItemsChanged={reveal.onViewableItemsChanged}
|
||||
viewabilityConfig={reveal.viewabilityConfig}
|
||||
onContentSizeChange={reveal.onContentSizeChange}
|
||||
onLayout={reveal.onLayout}
|
||||
testID="compact-model-list"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
page: {
|
||||
flex: 1,
|
||||
minHeight: 0,
|
||||
},
|
||||
listCardPage: {
|
||||
flex: 1,
|
||||
minHeight: 0,
|
||||
paddingHorizontal: theme.spacing[4],
|
||||
paddingTop: theme.spacing[2],
|
||||
paddingBottom: theme.spacing[2],
|
||||
},
|
||||
sections: {
|
||||
paddingHorizontal: theme.spacing[4],
|
||||
paddingTop: theme.spacing[2],
|
||||
paddingBottom: theme.spacing[4],
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
expandedHeader: {
|
||||
minHeight: 44,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
// The model rows' leading rail (ModelBrowserRow), so the section glyph sits above theirs.
|
||||
paddingLeft: isNative ? theme.spacing[6] : theme.spacing[3],
|
||||
paddingRight: isNative ? theme.spacing[6] : theme.spacing[3],
|
||||
},
|
||||
expandedTrigger: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
minHeight: 44,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
expandedTrailing: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[1],
|
||||
},
|
||||
collapseChevron: {
|
||||
minWidth: 24,
|
||||
minHeight: 44,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
glyph: {
|
||||
width: 16,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
expandedTitle: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
fontSize: theme.fontSize.base,
|
||||
fontWeight: theme.fontWeight.medium,
|
||||
color: theme.colors.foreground,
|
||||
},
|
||||
summary: {
|
||||
fontSize: theme.fontSize.sm,
|
||||
fontWeight: theme.fontWeight.normal,
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontVariant: ["tabular-nums"],
|
||||
},
|
||||
collapsedTrailing: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
spinner: {
|
||||
transform: [{ scale: 0.7 }],
|
||||
},
|
||||
fixedViewport: {
|
||||
height: MOBILE_EXPANDED_PROVIDER_HEIGHT,
|
||||
flexGrow: 0,
|
||||
},
|
||||
centered: {
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
dock: {
|
||||
flex: 1,
|
||||
flexDirection: "row",
|
||||
},
|
||||
}));
|
||||
@@ -0,0 +1,578 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type {
|
||||
ProviderSelectionModelRow,
|
||||
ProviderSelectorProvider,
|
||||
} from "@/provider-selection/provider-selection";
|
||||
import {
|
||||
MODEL_PICKER_PROFILES_RAIL_KEY,
|
||||
createModelPickerState,
|
||||
projectModelPicker,
|
||||
reduceModelPicker,
|
||||
resolveModelPickerHeight,
|
||||
resolveModelPickerKey,
|
||||
resolveModelPickerLayout,
|
||||
type ModelPickerInput,
|
||||
type ModelPickerKeyResult,
|
||||
type ModelPickerListItem,
|
||||
type ModelPickerProjection,
|
||||
type ModelPickerState,
|
||||
} from "./model-browser-panes-view";
|
||||
|
||||
interface Profile {
|
||||
id: string;
|
||||
provider: string;
|
||||
modelId: string;
|
||||
name: string;
|
||||
summary: string;
|
||||
}
|
||||
|
||||
function row(
|
||||
providerId: string,
|
||||
providerLabel: string,
|
||||
modelId: string,
|
||||
options: { legacy?: boolean; label?: string } = {},
|
||||
): ProviderSelectionModelRow {
|
||||
return {
|
||||
favoriteKey: `${providerId}:${modelId}`,
|
||||
provider: providerId,
|
||||
providerLabel,
|
||||
modelId,
|
||||
modelLabel: options.label ?? modelId,
|
||||
description: `${modelId} description`,
|
||||
...(options.legacy ? { legacy: true } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
const claudeCurrent = ["opus-5.5", "fable-5.2", "sonnet-5.5", "haiku-5.5"];
|
||||
const claudeOlder = Array.from({ length: 15 }, (_, index) => `claude-older-${index + 1}`);
|
||||
const claude: ProviderSelectorProvider = {
|
||||
id: "claude",
|
||||
label: "Claude",
|
||||
modelSelection: {
|
||||
kind: "models",
|
||||
rows: [
|
||||
...claudeCurrent.map((id) => row("claude", "Claude", id)),
|
||||
...claudeOlder.map((id) => row("claude", "Claude", id, { legacy: true })),
|
||||
],
|
||||
},
|
||||
};
|
||||
const codex: ProviderSelectorProvider = {
|
||||
id: "codex",
|
||||
label: "Codex",
|
||||
modelSelection: {
|
||||
kind: "models",
|
||||
rows: [row("codex", "Codex", "gpt-5.4"), row("codex", "Codex", "gpt-5.4-mini")],
|
||||
},
|
||||
};
|
||||
const pi: ProviderSelectorProvider = {
|
||||
id: "pi",
|
||||
label: "Pi",
|
||||
shownModels: ["anthropic/opus", "openai/gpt-5"],
|
||||
modelSelection: {
|
||||
kind: "models",
|
||||
rows: [
|
||||
row("pi", "Pi", "anthropic/opus"),
|
||||
row("pi", "Pi", "openai/gpt-5"),
|
||||
row("pi", "Pi", "openai/gpt-5.4"),
|
||||
row("pi", "Pi", "google/gemini"),
|
||||
],
|
||||
},
|
||||
};
|
||||
const copilot: ProviderSelectorProvider = {
|
||||
id: "copilot",
|
||||
label: "Copilot",
|
||||
modelSelection: { kind: "error", message: "Not signed in" },
|
||||
};
|
||||
const opencode: ProviderSelectorProvider = {
|
||||
id: "opencode",
|
||||
label: "OpenCode",
|
||||
modelSelection: { kind: "loading" },
|
||||
};
|
||||
|
||||
const profiles: Profile[] = [
|
||||
{
|
||||
id: "deep-review",
|
||||
provider: "codex",
|
||||
modelId: "gpt-5.4",
|
||||
name: "Codex 5.4 Deep Review",
|
||||
summary: "Codex · GPT-5.4 · High",
|
||||
},
|
||||
{
|
||||
id: "quick",
|
||||
provider: "claude",
|
||||
modelId: "haiku-5.5",
|
||||
name: "Quick fixes",
|
||||
summary: "Claude · Haiku 5.5",
|
||||
},
|
||||
];
|
||||
|
||||
function input(overrides: Partial<ModelPickerInput<Profile>> = {}): ModelPickerInput<Profile> {
|
||||
return {
|
||||
providers: [claude, copilot, codex, opencode, pi],
|
||||
profiles,
|
||||
canCreateProfile: true,
|
||||
selectedProvider: "claude",
|
||||
selectedModel: "opus-5.5",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function open(pickerInput: ModelPickerInput<Profile>) {
|
||||
const state = createModelPickerState(pickerInput);
|
||||
return { state, projection: projectModelPicker(pickerInput, state) };
|
||||
}
|
||||
|
||||
function keys(items: readonly ModelPickerListItem<Profile>[]): string[] {
|
||||
return items.map((item) => item.key);
|
||||
}
|
||||
|
||||
function modelIds(projection: ModelPickerProjection<Profile>): string[] {
|
||||
return projection.pane.items.flatMap((item) => (item.kind === "model" ? [item.row.modelId] : []));
|
||||
}
|
||||
|
||||
function press(
|
||||
pickerInput: ModelPickerInput<Profile>,
|
||||
state: ModelPickerState,
|
||||
key: string,
|
||||
options: { focusedControlOwnsEnter?: boolean; shiftKey?: boolean; metaKey?: boolean } = {},
|
||||
): ModelPickerKeyResult {
|
||||
return resolveModelPickerKey(pickerInput, state, {
|
||||
event: { key, shiftKey: options.shiftKey, metaKey: options.metaKey },
|
||||
focusedControlOwnsEnter: options.focusedControlOwnsEnter ?? false,
|
||||
});
|
||||
}
|
||||
|
||||
function nextState(result: ModelPickerKeyResult): ModelPickerState {
|
||||
if (result?.kind !== "state") throw new Error(`expected a state change, got ${result?.kind}`);
|
||||
return result.state;
|
||||
}
|
||||
|
||||
describe("model picker layout", () => {
|
||||
it("uses two panes for several providers", () => {
|
||||
expect(resolveModelPickerLayout(input({ profiles: null }))).toBe("twoPane");
|
||||
});
|
||||
|
||||
it("uses two panes for one provider with profiles", () => {
|
||||
expect(resolveModelPickerLayout(input({ providers: [claude] }))).toBe("twoPane");
|
||||
});
|
||||
|
||||
it("keeps two panes for one provider on a surface that offers profiles but has none", () => {
|
||||
expect(resolveModelPickerLayout(input({ providers: [claude], profiles: [] }))).toBe("twoPane");
|
||||
});
|
||||
|
||||
it("drops the rail for one provider on a surface without profiles", () => {
|
||||
expect(resolveModelPickerLayout(input({ providers: [claude], profiles: null }))).toBe(
|
||||
"singlePane",
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps a fixed two-pane height whatever the content", () => {
|
||||
const tall = resolveModelPickerHeight(input());
|
||||
expect(resolveModelPickerHeight(input({ providers: [codex, pi] }))).toBe(tall);
|
||||
});
|
||||
|
||||
it("sizes the single pane from every row, folded or not, so expanding never resizes it", () => {
|
||||
const small = resolveModelPickerHeight(input({ providers: [codex], profiles: null }));
|
||||
const large = resolveModelPickerHeight(input({ providers: [claude], profiles: null }));
|
||||
expect(small).toBeLessThan(large);
|
||||
expect(large).toBe(resolveModelPickerHeight(input()));
|
||||
});
|
||||
});
|
||||
|
||||
describe("model picker rail", () => {
|
||||
it("lists Profiles, then ready providers, then errored providers after a divider", () => {
|
||||
const { projection } = open(input());
|
||||
expect(projection.rail.map((item) => item.key)).toEqual([
|
||||
MODEL_PICKER_PROFILES_RAIL_KEY,
|
||||
"claude",
|
||||
"codex",
|
||||
"opencode",
|
||||
"pi",
|
||||
"copilot",
|
||||
]);
|
||||
const copilotItem = projection.rail.find((item) => item.key === "copilot");
|
||||
expect(copilotItem).toMatchObject({
|
||||
kind: "provider",
|
||||
status: "error",
|
||||
startsErrorGroup: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("counts profiles and the models each provider shows first", () => {
|
||||
const { projection } = open(input());
|
||||
const counts = Object.fromEntries(projection.rail.map((item) => [item.key, item.count]));
|
||||
expect(counts).toMatchObject({ profiles: 2, claude: 4, codex: 2, pi: 2 });
|
||||
});
|
||||
|
||||
it("omits the Profiles row when the surface shows no profiles", () => {
|
||||
const { projection } = open(input({ profiles: null }));
|
||||
expect(projection.rail.map((item) => item.key)).not.toContain(MODEL_PICKER_PROFILES_RAIL_KEY);
|
||||
});
|
||||
|
||||
it("has no rail in the single-pane layout", () => {
|
||||
const { projection } = open(input({ providers: [claude], profiles: null }));
|
||||
expect(projection.rail).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("model picker initial selection", () => {
|
||||
it("opens on the selected provider with its model active", () => {
|
||||
const { projection } = open(input());
|
||||
expect(projection.railKey).toBe("claude");
|
||||
expect(projection.focus).toBe("list");
|
||||
expect(projection.activeKey).toBe("model:claude:opus-5.5");
|
||||
});
|
||||
|
||||
it("opens on Profiles when nothing is selected and profiles exist", () => {
|
||||
const { projection } = open(input({ selectedProvider: "", selectedModel: "" }));
|
||||
expect(projection.railKey).toBe(MODEL_PICKER_PROFILES_RAIL_KEY);
|
||||
expect(projection.pane.kind).toBe("profiles");
|
||||
});
|
||||
|
||||
it("opens on the first ready provider when nothing is selected and there are no profiles", () => {
|
||||
const { projection } = open(
|
||||
input({ providers: [copilot, opencode, codex], profiles: null, selectedProvider: "" }),
|
||||
);
|
||||
expect(projection.railKey).toBe("codex");
|
||||
});
|
||||
});
|
||||
|
||||
describe("model picker provider pane", () => {
|
||||
it("shows the current Claude models and folds the 15 older ones", () => {
|
||||
const { projection } = open(input());
|
||||
expect(projection.pane).toMatchObject({
|
||||
kind: "provider",
|
||||
providerId: "claude",
|
||||
label: "Claude",
|
||||
shown: 4,
|
||||
total: 19,
|
||||
foldKind: "older",
|
||||
});
|
||||
expect(modelIds(projection)).toEqual(claudeCurrent);
|
||||
expect(projection.pane.items.at(-1)).toMatchObject({
|
||||
kind: "fold",
|
||||
foldKind: "older",
|
||||
count: 15,
|
||||
expanded: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("opens the fold when the selected model is folded", () => {
|
||||
const { projection } = open(input({ selectedModel: "claude-older-3" }));
|
||||
expect(projection.pane.items[4]).toMatchObject({ kind: "fold", expanded: true });
|
||||
expect(modelIds(projection)).toEqual([...claudeCurrent, ...claudeOlder]);
|
||||
expect(projection.activeKey).toBe("model:claude:claude-older-3");
|
||||
});
|
||||
|
||||
it("toggles the fold in place", () => {
|
||||
const pickerInput = input();
|
||||
const { state } = open(pickerInput);
|
||||
const expanded = reduceModelPicker(state, {
|
||||
kind: "toggleFold",
|
||||
providerId: "claude",
|
||||
expanded: true,
|
||||
});
|
||||
expect(modelIds(projectModelPicker(pickerInput, expanded))).toHaveLength(19);
|
||||
const collapsed = reduceModelPicker(expanded, {
|
||||
kind: "toggleFold",
|
||||
providerId: "claude",
|
||||
expanded: false,
|
||||
});
|
||||
expect(modelIds(projectModelPicker(pickerInput, collapsed))).toEqual(claudeCurrent);
|
||||
});
|
||||
|
||||
it("shows the picked models first and folds the rest behind All models", () => {
|
||||
const pickerInput = input();
|
||||
const state = reduceModelPicker(open(pickerInput).state, { kind: "selectRail", railKey: "pi" });
|
||||
const projection = projectModelPicker(pickerInput, state);
|
||||
expect(modelIds(projection)).toEqual(["anthropic/opus", "openai/gpt-5"]);
|
||||
expect(projection.pane).toMatchObject({ shown: 2, total: 4, foldKind: "all" });
|
||||
expect(projection.pane.items.at(-1)).toMatchObject({ kind: "fold", foldKind: "all", count: 2 });
|
||||
});
|
||||
|
||||
it("shows every model without a fold when nothing is folded", () => {
|
||||
const pickerInput = input();
|
||||
const state = reduceModelPicker(open(pickerInput).state, {
|
||||
kind: "selectRail",
|
||||
railKey: "codex",
|
||||
});
|
||||
const projection = projectModelPicker(pickerInput, state);
|
||||
expect(projection.pane).toMatchObject({ kind: "provider", foldKind: null });
|
||||
expect(keys(projection.pane.items)).toEqual([
|
||||
"model:codex:gpt-5.4",
|
||||
"model:codex:gpt-5.4-mini",
|
||||
]);
|
||||
expect(projection.activeKey).toBe("model:codex:gpt-5.4");
|
||||
});
|
||||
|
||||
it("shows loading and error states for providers without models", () => {
|
||||
const pickerInput = input();
|
||||
const loading = reduceModelPicker(open(pickerInput).state, {
|
||||
kind: "selectRail",
|
||||
railKey: "opencode",
|
||||
});
|
||||
expect(projectModelPicker(pickerInput, loading).pane).toMatchObject({
|
||||
kind: "providerLoading",
|
||||
items: [],
|
||||
});
|
||||
const errored = reduceModelPicker(loading, { kind: "selectRail", railKey: "copilot" });
|
||||
expect(projectModelPicker(pickerInput, errored).pane).toMatchObject({
|
||||
kind: "providerError",
|
||||
providerId: "copilot",
|
||||
message: "Not signed in",
|
||||
items: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("lists profiles on the Profiles pane, or offers to create one", () => {
|
||||
const pickerInput = input();
|
||||
const state = reduceModelPicker(open(pickerInput).state, {
|
||||
kind: "selectRail",
|
||||
railKey: MODEL_PICKER_PROFILES_RAIL_KEY,
|
||||
});
|
||||
expect(keys(projectModelPicker(pickerInput, state).pane.items)).toEqual([
|
||||
"profile:deep-review",
|
||||
"profile:quick",
|
||||
]);
|
||||
const empty = input({ profiles: [] });
|
||||
expect(
|
||||
keys(
|
||||
projectModelPicker(
|
||||
empty,
|
||||
reduceModelPicker(createModelPickerState(empty), {
|
||||
kind: "selectRail",
|
||||
railKey: MODEL_PICKER_PROFILES_RAIL_KEY,
|
||||
}),
|
||||
).pane.items,
|
||||
),
|
||||
).toEqual(["create-profile"]);
|
||||
});
|
||||
|
||||
it("falls back to the first rail row when the open provider disappears", () => {
|
||||
const pickerInput = input();
|
||||
const state = reduceModelPicker(open(pickerInput).state, { kind: "selectRail", railKey: "pi" });
|
||||
const projection = projectModelPicker(input({ providers: [claude, codex] }), state);
|
||||
expect(projection.railKey).toBe(MODEL_PICKER_PROFILES_RAIL_KEY);
|
||||
});
|
||||
|
||||
it("keeps folding in the single-pane layout", () => {
|
||||
const { projection } = open(input({ providers: [claude], profiles: null }));
|
||||
expect(projection.layout).toBe("singlePane");
|
||||
expect(modelIds(projection)).toEqual(claudeCurrent);
|
||||
expect(projection.pane.items.at(-1)).toMatchObject({ kind: "fold", count: 15 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("model picker search", () => {
|
||||
function search(query: string, overrides: Partial<ModelPickerInput<Profile>> = {}) {
|
||||
const pickerInput = input(overrides);
|
||||
const state = reduceModelPicker(createModelPickerState(pickerInput), { kind: "query", query });
|
||||
return projectModelPicker(pickerInput, state);
|
||||
}
|
||||
|
||||
it("matches profiles and models across every provider, folded ones included", () => {
|
||||
const projection = search("5.4");
|
||||
expect(projection.pane.kind).toBe("search");
|
||||
expect(keys(projection.pane.items)).toEqual([
|
||||
"profile:deep-review",
|
||||
"model:codex:gpt-5.4",
|
||||
"model:codex:gpt-5.4-mini",
|
||||
"model:pi:openai/gpt-5.4",
|
||||
]);
|
||||
expect(projection.activeKey).toBe("profile:deep-review");
|
||||
});
|
||||
|
||||
it("tags models that browse would fold", () => {
|
||||
const projection = search("older-1");
|
||||
const tags = projection.pane.items.flatMap((item) => (item.kind === "model" ? [item.tag] : []));
|
||||
expect(tags.length).toBeGreaterThan(0);
|
||||
expect(new Set(tags)).toEqual(new Set(["older"]));
|
||||
const piFolded = search("gemini").pane.items[0];
|
||||
expect(piFolded).toMatchObject({ kind: "model", tag: "all" });
|
||||
const shown = search("gpt-5.4-mini").pane.items[0];
|
||||
expect(shown).toMatchObject({ kind: "model", tag: null });
|
||||
});
|
||||
|
||||
it("ranks primary matches ahead of folded ones", () => {
|
||||
const opus: ProviderSelectorProvider = {
|
||||
id: "anthropic",
|
||||
label: "Anthropic",
|
||||
modelSelection: {
|
||||
kind: "models",
|
||||
rows: [
|
||||
row("anthropic", "Anthropic", "opus-5.5", { label: "Opus 5.5" }),
|
||||
row("anthropic", "Anthropic", "opus-4.6", { label: "Opus 4.6", legacy: true }),
|
||||
row("anthropic", "Anthropic", "opus-5", { label: "Opus 5", legacy: true }),
|
||||
],
|
||||
},
|
||||
};
|
||||
const overrides = { providers: [opus], profiles: null };
|
||||
expect(keys(search("opus", overrides).pane.items)).toEqual([
|
||||
"model:anthropic:opus-5.5",
|
||||
"model:anthropic:opus-4.6",
|
||||
"model:anthropic:opus-5",
|
||||
]);
|
||||
expect(keys(search("4.6", overrides).pane.items)).toEqual(["model:anthropic:opus-4.6"]);
|
||||
});
|
||||
|
||||
it("ranks a close folded match ahead of a loose shown one", () => {
|
||||
const anthropic: ProviderSelectorProvider = {
|
||||
id: "anthropic",
|
||||
label: "Anthropic",
|
||||
modelSelection: {
|
||||
kind: "models",
|
||||
rows: [
|
||||
row("anthropic", "Anthropic", "opus-5.5", { label: "Opus 5.5" }),
|
||||
row("anthropic", "Anthropic", "opus-4.6", { label: "Opus 4.6", legacy: true }),
|
||||
],
|
||||
},
|
||||
};
|
||||
// Nothing curated, so every row is shown, and "opus" only matches these scattered across
|
||||
// the id.
|
||||
const openrouter: ProviderSelectorProvider = {
|
||||
id: "openrouter",
|
||||
label: "OpenRouter",
|
||||
modelSelection: {
|
||||
kind: "models",
|
||||
rows: [
|
||||
row("openrouter", "OpenRouter", "openrouter/mistralai/codestral-2508", {
|
||||
label: "Codestral 2508",
|
||||
}),
|
||||
row("openrouter", "OpenRouter", "openrouter/anthropic/claude-sonnet-4.6", {
|
||||
label: "Claude Sonnet 4.6",
|
||||
}),
|
||||
],
|
||||
},
|
||||
};
|
||||
const overrides = { providers: [openrouter, anthropic], profiles: null };
|
||||
expect(keys(search("opus", overrides).pane.items).slice(0, 2)).toEqual([
|
||||
"model:anthropic:opus-5.5",
|
||||
"model:anthropic:opus-4.6",
|
||||
]);
|
||||
expect(keys(search("opus 4.6", overrides).pane.items)[0]).toBe("model:anthropic:opus-4.6");
|
||||
});
|
||||
|
||||
it("searches only models when the surface shows no profiles", () => {
|
||||
expect(keys(search("deep review", { profiles: null }).pane.items)).toEqual([]);
|
||||
});
|
||||
|
||||
it("reports no matches", () => {
|
||||
expect(search("zzzz").pane).toMatchObject({ kind: "noMatches", items: [] });
|
||||
});
|
||||
|
||||
it("ignores surrounding whitespace and returns to browse when cleared", () => {
|
||||
expect(search(" ").pane.kind).toBe("provider");
|
||||
});
|
||||
});
|
||||
|
||||
describe("model picker keyboard", () => {
|
||||
it("moves through the list with the arrow keys and wraps", () => {
|
||||
const pickerInput = input();
|
||||
let state = open(pickerInput).state;
|
||||
state = nextState(press(pickerInput, state, "ArrowDown"));
|
||||
expect(projectModelPicker(pickerInput, state).activeKey).toBe("model:claude:fable-5.2");
|
||||
state = nextState(press(pickerInput, state, "ArrowUp"));
|
||||
state = nextState(press(pickerInput, state, "ArrowUp"));
|
||||
expect(projectModelPicker(pickerInput, state).activeKey).toBe("fold:claude");
|
||||
});
|
||||
|
||||
it("selects the active model on Enter", () => {
|
||||
const pickerInput = input();
|
||||
const state = nextState(press(pickerInput, open(pickerInput).state, "ArrowDown"));
|
||||
expect(press(pickerInput, state, "Enter")).toEqual({
|
||||
kind: "selectModel",
|
||||
provider: "claude",
|
||||
modelId: "fable-5.2",
|
||||
});
|
||||
});
|
||||
|
||||
it("toggles the fold on Enter and keeps it active", () => {
|
||||
const pickerInput = input();
|
||||
const onFold = nextState(press(pickerInput, open(pickerInput).state, "ArrowUp"));
|
||||
const expanded = nextState(press(pickerInput, onFold, "Enter"));
|
||||
const projection = projectModelPicker(pickerInput, expanded);
|
||||
expect(modelIds(projection)).toHaveLength(19);
|
||||
expect(projection.activeKey).toBe("fold:claude");
|
||||
});
|
||||
|
||||
it("moves to the rail with ArrowLeft and switches providers with the arrow keys", () => {
|
||||
const pickerInput = input();
|
||||
let state = nextState(press(pickerInput, open(pickerInput).state, "ArrowLeft"));
|
||||
let projection = projectModelPicker(pickerInput, state);
|
||||
expect(projection.focus).toBe("rail");
|
||||
expect(projection.activeKey).toBeNull();
|
||||
state = nextState(press(pickerInput, state, "ArrowDown"));
|
||||
projection = projectModelPicker(pickerInput, state);
|
||||
expect(projection.railKey).toBe("codex");
|
||||
expect(projection.pane).toMatchObject({ kind: "provider", providerId: "codex" });
|
||||
state = nextState(press(pickerInput, state, "ArrowRight"));
|
||||
projection = projectModelPicker(pickerInput, state);
|
||||
expect(projection.focus).toBe("list");
|
||||
expect(projection.activeKey).toBe("model:codex:gpt-5.4");
|
||||
});
|
||||
|
||||
it("enters the list on Enter from the rail", () => {
|
||||
const pickerInput = input();
|
||||
const onRail = nextState(press(pickerInput, open(pickerInput).state, "ArrowLeft"));
|
||||
expect(
|
||||
projectModelPicker(pickerInput, nextState(press(pickerInput, onRail, "Enter"))).focus,
|
||||
).toBe("list");
|
||||
});
|
||||
|
||||
it("does not enter an empty pane from the rail", () => {
|
||||
const pickerInput = input();
|
||||
let state = reduceModelPicker(open(pickerInput).state, {
|
||||
kind: "selectRail",
|
||||
railKey: "copilot",
|
||||
});
|
||||
state = nextState(press(pickerInput, state, "ArrowLeft"));
|
||||
expect(press(pickerInput, state, "ArrowRight")).toBeNull();
|
||||
});
|
||||
|
||||
it("leaves Left and Right to the caret while searching", () => {
|
||||
const pickerInput = input();
|
||||
const state = reduceModelPicker(open(pickerInput).state, { kind: "query", query: "gpt" });
|
||||
expect(press(pickerInput, state, "ArrowLeft")).toBeNull();
|
||||
expect(press(pickerInput, state, "ArrowRight")).toBeNull();
|
||||
});
|
||||
|
||||
it("ignores Left and Right in the single-pane layout", () => {
|
||||
const pickerInput = input({ providers: [claude], profiles: null });
|
||||
expect(press(pickerInput, open(pickerInput).state, "ArrowLeft")).toBeNull();
|
||||
});
|
||||
|
||||
it("applies a profile from search results on Enter", () => {
|
||||
const pickerInput = input();
|
||||
const state = reduceModelPicker(open(pickerInput).state, { kind: "query", query: "deep" });
|
||||
expect(press(pickerInput, state, "Enter")).toEqual({
|
||||
kind: "applyProfile",
|
||||
profileId: "deep-review",
|
||||
});
|
||||
});
|
||||
|
||||
it("offers profile creation on Enter", () => {
|
||||
const pickerInput = input({ profiles: [], selectedProvider: "" });
|
||||
let state = reduceModelPicker(createModelPickerState(pickerInput), {
|
||||
kind: "selectRail",
|
||||
railKey: MODEL_PICKER_PROFILES_RAIL_KEY,
|
||||
});
|
||||
state = reduceModelPicker(state, { kind: "activate", key: "create-profile" });
|
||||
expect(press(pickerInput, state, "Enter")).toEqual({ kind: "createProfile" });
|
||||
});
|
||||
|
||||
it("clears a search on Escape, then lets Escape close the picker", () => {
|
||||
const pickerInput = input();
|
||||
const searching = reduceModelPicker(open(pickerInput).state, { kind: "query", query: "gpt" });
|
||||
const cleared = nextState(press(pickerInput, searching, "Escape"));
|
||||
expect(cleared.query).toBe("");
|
||||
expect(projectModelPicker(pickerInput, cleared).pane.kind).toBe("provider");
|
||||
expect(press(pickerInput, cleared, "Escape")).toBeNull();
|
||||
});
|
||||
|
||||
it("leaves Enter to a focused button and modified keys to the app", () => {
|
||||
const pickerInput = input();
|
||||
const { state } = open(pickerInput);
|
||||
expect(press(pickerInput, state, "Enter", { focusedControlOwnsEnter: true })).toBeNull();
|
||||
expect(press(pickerInput, state, "ArrowDown", { metaKey: true })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,543 @@
|
||||
import { compareMatchScores, type MatchScore } from "@getpaseo/protocol/search/text-match";
|
||||
import { getNextActiveIndex } from "@/components/ui/combobox-keyboard";
|
||||
import {
|
||||
MODEL_BROWSER_CREATE_PROFILE_KEY,
|
||||
filterAndRankProfileRows,
|
||||
modelBrowserModelKey,
|
||||
modelBrowserProfileKey,
|
||||
type ModelBrowserKeyEvent,
|
||||
type NavigableProfileRow,
|
||||
} from "@/components/model-browser-view";
|
||||
import {
|
||||
partitionProviderModels,
|
||||
type ModelFoldKind,
|
||||
type ProviderModelPartition,
|
||||
} from "@/provider-selection/model-curation";
|
||||
import {
|
||||
scoreModelRow,
|
||||
type ProviderSelectionModelRow,
|
||||
type ProviderSelectorProvider,
|
||||
} from "@/provider-selection/provider-selection";
|
||||
|
||||
/**
|
||||
* The desktop model picker: a rail of Profiles and providers beside the open entry's list, or a
|
||||
* single list when there is only one provider to show. A query replaces both panes with ranked
|
||||
* results from every provider, folded models included.
|
||||
*
|
||||
* Everything the picker shows and every key it handles is derived here, so the view only renders
|
||||
* the projection and sends the user's actions back through `reduceModelPicker`.
|
||||
*/
|
||||
|
||||
export const MODEL_PICKER_PROFILES_RAIL_KEY = "profiles";
|
||||
|
||||
const TWO_PANE_HEIGHT = 392;
|
||||
const SINGLE_PANE_MIN_HEIGHT = 220;
|
||||
const SINGLE_PANE_CHROME_HEIGHT = 96;
|
||||
const LIST_ROW_HEIGHT = 36;
|
||||
|
||||
export type ModelPickerLayout = "twoPane" | "singlePane";
|
||||
export type ModelPickerFocus = "rail" | "list";
|
||||
|
||||
export interface ModelPickerInput<TProfile extends NavigableProfileRow = NavigableProfileRow> {
|
||||
providers: readonly ProviderSelectorProvider[];
|
||||
/** `null` when the surface offers no profiles. */
|
||||
profiles: readonly TProfile[] | null;
|
||||
canCreateProfile: boolean;
|
||||
selectedProvider: string;
|
||||
selectedModel: string;
|
||||
}
|
||||
|
||||
export interface ModelPickerState {
|
||||
query: string;
|
||||
/** The open rail entry: `MODEL_PICKER_PROFILES_RAIL_KEY` or a provider id. */
|
||||
railKey: string;
|
||||
focus: ModelPickerFocus;
|
||||
/** The row the user moved to. `null` falls back to the selected model or the first row. */
|
||||
activeKey: string | null;
|
||||
/** Folds the user opened or closed, by provider. Others follow the partition's default. */
|
||||
foldOverrides: Readonly<Record<string, boolean>>;
|
||||
}
|
||||
|
||||
export type ModelPickerAction =
|
||||
| { kind: "query"; query: string }
|
||||
| { kind: "selectRail"; railKey: string }
|
||||
| { kind: "activate"; key: string }
|
||||
| { kind: "toggleFold"; providerId: string; expanded: boolean };
|
||||
|
||||
export type ModelPickerRailItem =
|
||||
| { kind: "profiles"; key: typeof MODEL_PICKER_PROFILES_RAIL_KEY; count: number }
|
||||
| {
|
||||
kind: "provider";
|
||||
key: string;
|
||||
providerId: string;
|
||||
label: string;
|
||||
status: "ready" | "loading" | "error";
|
||||
count: number;
|
||||
/** The first errored provider after ready ones; the rail draws a divider above it. */
|
||||
startsErrorGroup: boolean;
|
||||
};
|
||||
|
||||
export type ModelPickerListItem<TProfile extends NavigableProfileRow = NavigableProfileRow> =
|
||||
| {
|
||||
kind: "model";
|
||||
key: string;
|
||||
row: ProviderSelectionModelRow;
|
||||
/** Search only: the fold this model sits behind while browsing. */
|
||||
tag: ModelFoldKind;
|
||||
}
|
||||
| {
|
||||
kind: "fold";
|
||||
key: string;
|
||||
providerId: string;
|
||||
foldKind: "older" | "all";
|
||||
count: number;
|
||||
expanded: boolean;
|
||||
}
|
||||
| { kind: "profile"; key: string; profile: TProfile }
|
||||
| { kind: "createProfile"; key: typeof MODEL_BROWSER_CREATE_PROFILE_KEY };
|
||||
|
||||
export type ModelPickerPane<TProfile extends NavigableProfileRow = NavigableProfileRow> =
|
||||
| {
|
||||
kind: "provider";
|
||||
providerId: string;
|
||||
label: string;
|
||||
shown: number;
|
||||
total: number;
|
||||
foldKind: ModelFoldKind;
|
||||
items: ModelPickerListItem<TProfile>[];
|
||||
}
|
||||
| { kind: "providerLoading"; providerId: string; label: string; items: [] }
|
||||
| { kind: "providerError"; providerId: string; label: string; message: string; items: [] }
|
||||
| { kind: "profiles"; items: ModelPickerListItem<TProfile>[] }
|
||||
| {
|
||||
kind: "search";
|
||||
profiles: ModelPickerListItem<TProfile>[];
|
||||
models: ModelPickerListItem<TProfile>[];
|
||||
items: ModelPickerListItem<TProfile>[];
|
||||
}
|
||||
| { kind: "noMatches"; query: string; items: [] };
|
||||
|
||||
export interface ModelPickerProjection<TProfile extends NavigableProfileRow = NavigableProfileRow> {
|
||||
layout: ModelPickerLayout;
|
||||
rail: ModelPickerRailItem[];
|
||||
railKey: string;
|
||||
focus: ModelPickerFocus;
|
||||
pane: ModelPickerPane<TProfile>;
|
||||
/** The highlighted list row; `null` while the rail has focus. */
|
||||
activeKey: string | null;
|
||||
}
|
||||
|
||||
export type ModelPickerKeyResult =
|
||||
| { kind: "state"; state: ModelPickerState }
|
||||
| { kind: "selectModel"; provider: string; modelId: string }
|
||||
| { kind: "applyProfile"; profileId: string }
|
||||
| { kind: "createProfile" }
|
||||
| null;
|
||||
|
||||
export function modelPickerFoldKey(providerId: string): string {
|
||||
return `fold:${providerId}`;
|
||||
}
|
||||
|
||||
/** Two panes whenever there is a rail to choose from: several providers, or a surface that offers
|
||||
* profiles (even none yet, so the rail keeps the create-profile entry). */
|
||||
export function resolveModelPickerLayout(input: ModelPickerInput): ModelPickerLayout {
|
||||
return input.providers.length > 1 || input.profiles !== null ? "twoPane" : "singlePane";
|
||||
}
|
||||
|
||||
/**
|
||||
* The popover keeps one height for its whole life, so switching providers, opening a fold, or
|
||||
* searching never moves it. A single pane sizes to all its rows, folded ones included.
|
||||
*/
|
||||
export function resolveModelPickerHeight(input: ModelPickerInput): number {
|
||||
if (resolveModelPickerLayout(input) === "twoPane") return TWO_PANE_HEIGHT;
|
||||
const provider = input.providers[0];
|
||||
const rowCount = provider ? countAllRows(provider) : 0;
|
||||
return clamp(
|
||||
SINGLE_PANE_CHROME_HEIGHT + rowCount * LIST_ROW_HEIGHT,
|
||||
SINGLE_PANE_MIN_HEIGHT,
|
||||
TWO_PANE_HEIGHT,
|
||||
);
|
||||
}
|
||||
|
||||
export function createModelPickerState(input: ModelPickerInput): ModelPickerState {
|
||||
return {
|
||||
query: "",
|
||||
railKey: resolveInitialRailKey(input),
|
||||
focus: "list",
|
||||
activeKey: null,
|
||||
foldOverrides: {},
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceModelPicker(
|
||||
state: ModelPickerState,
|
||||
action: ModelPickerAction,
|
||||
): ModelPickerState {
|
||||
switch (action.kind) {
|
||||
case "query":
|
||||
return { ...state, query: action.query, activeKey: null };
|
||||
case "selectRail":
|
||||
return { ...state, railKey: action.railKey, activeKey: null };
|
||||
case "activate":
|
||||
return { ...state, activeKey: action.key, focus: "list" };
|
||||
case "toggleFold":
|
||||
return {
|
||||
...state,
|
||||
foldOverrides: { ...state.foldOverrides, [action.providerId]: action.expanded },
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function projectModelPicker<TProfile extends NavigableProfileRow>(
|
||||
input: ModelPickerInput<TProfile>,
|
||||
state: ModelPickerState,
|
||||
): ModelPickerProjection<TProfile> {
|
||||
const layout = resolveModelPickerLayout(input);
|
||||
const rail = layout === "twoPane" ? buildRail(input) : [];
|
||||
const railKey = resolveRailKey(input, state, layout, rail);
|
||||
const normalizedQuery = normalizeQuery(state.query);
|
||||
const pane = normalizedQuery
|
||||
? buildSearchPane(input, normalizedQuery, state.query.trim())
|
||||
: buildBrowsePane(input, state, railKey);
|
||||
const focus: ModelPickerFocus =
|
||||
layout === "twoPane" && !normalizedQuery && state.focus === "rail" ? "rail" : "list";
|
||||
return {
|
||||
layout,
|
||||
rail,
|
||||
railKey,
|
||||
focus,
|
||||
pane,
|
||||
activeKey: focus === "list" ? resolveActiveKey(input, state, pane) : null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves a keydown into the next state or a pick, or `null` when the key belongs to text editing,
|
||||
* a focused button, or the host (an unclaimed Escape closes the picker).
|
||||
*/
|
||||
export function resolveModelPickerKey<TProfile extends NavigableProfileRow>(
|
||||
input: ModelPickerInput<TProfile>,
|
||||
state: ModelPickerState,
|
||||
options: { event: ModelBrowserKeyEvent; focusedControlOwnsEnter: boolean },
|
||||
): ModelPickerKeyResult {
|
||||
const { event } = options;
|
||||
if (event.metaKey || event.ctrlKey || event.altKey) return null;
|
||||
const projection = projectModelPicker(input, state);
|
||||
|
||||
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
|
||||
return moveActive(projection, state, event.key);
|
||||
}
|
||||
if (event.shiftKey) return null;
|
||||
|
||||
if (event.key === "Escape") {
|
||||
return state.query.length > 0
|
||||
? { kind: "state", state: reduceModelPicker(state, { kind: "query", query: "" }) }
|
||||
: null;
|
||||
}
|
||||
|
||||
if (event.key === "Enter") {
|
||||
if (options.focusedControlOwnsEnter) return null;
|
||||
if (projection.focus === "rail") return enterList(projection, state);
|
||||
return activateItem(projection, state);
|
||||
}
|
||||
|
||||
const browsingTwoPanes = projection.layout === "twoPane" && state.query.trim().length === 0;
|
||||
if (!browsingTwoPanes) return null;
|
||||
if (event.key === "ArrowRight" && projection.focus === "rail") {
|
||||
return enterList(projection, state);
|
||||
}
|
||||
if (event.key === "ArrowLeft" && projection.focus === "list") {
|
||||
return { kind: "state", state: { ...state, focus: "rail", activeKey: null } };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function moveActive(
|
||||
projection: ModelPickerProjection,
|
||||
state: ModelPickerState,
|
||||
key: "ArrowDown" | "ArrowUp",
|
||||
): ModelPickerKeyResult {
|
||||
if (projection.focus === "rail") {
|
||||
const nextKey = stepKey(
|
||||
projection.rail.map((item) => item.key),
|
||||
projection.railKey,
|
||||
key,
|
||||
);
|
||||
return nextKey
|
||||
? { kind: "state", state: reduceModelPicker(state, { kind: "selectRail", railKey: nextKey }) }
|
||||
: null;
|
||||
}
|
||||
const nextKey = stepKey(
|
||||
projection.pane.items.map((item) => item.key),
|
||||
projection.activeKey,
|
||||
key,
|
||||
);
|
||||
return nextKey
|
||||
? { kind: "state", state: reduceModelPicker(state, { kind: "activate", key: nextKey }) }
|
||||
: null;
|
||||
}
|
||||
|
||||
function enterList(
|
||||
projection: ModelPickerProjection,
|
||||
state: ModelPickerState,
|
||||
): ModelPickerKeyResult {
|
||||
if (projection.pane.items.length === 0) return null;
|
||||
return { kind: "state", state: { ...state, focus: "list", activeKey: null } };
|
||||
}
|
||||
|
||||
function activateItem(
|
||||
projection: ModelPickerProjection,
|
||||
state: ModelPickerState,
|
||||
): ModelPickerKeyResult {
|
||||
const item = projection.pane.items.find((entry) => entry.key === projection.activeKey);
|
||||
if (!item) return null;
|
||||
switch (item.kind) {
|
||||
case "model":
|
||||
return { kind: "selectModel", provider: item.row.provider, modelId: item.row.modelId };
|
||||
case "profile":
|
||||
return { kind: "applyProfile", profileId: item.profile.id };
|
||||
case "createProfile":
|
||||
return { kind: "createProfile" };
|
||||
case "fold":
|
||||
return {
|
||||
kind: "state",
|
||||
state: reduceModelPicker(
|
||||
{ ...state, activeKey: item.key },
|
||||
{ kind: "toggleFold", providerId: item.providerId, expanded: !item.expanded },
|
||||
),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function stepKey(
|
||||
keys: readonly string[],
|
||||
currentKey: string | null,
|
||||
key: "ArrowDown" | "ArrowUp",
|
||||
): string | null {
|
||||
const currentIndex = currentKey ? keys.indexOf(currentKey) : -1;
|
||||
const nextIndex = getNextActiveIndex({ currentIndex, itemCount: keys.length, key });
|
||||
return nextIndex >= 0 ? (keys[nextIndex] ?? null) : null;
|
||||
}
|
||||
|
||||
function resolveActiveKey(
|
||||
input: ModelPickerInput,
|
||||
state: ModelPickerState,
|
||||
pane: ModelPickerPane,
|
||||
): string | null {
|
||||
const { items } = pane;
|
||||
if (items.length === 0) return null;
|
||||
if (state.activeKey && items.some((item) => item.key === state.activeKey)) {
|
||||
return state.activeKey;
|
||||
}
|
||||
if (pane.kind === "provider") {
|
||||
const selectedKey = modelBrowserModelKey(`${input.selectedProvider}:${input.selectedModel}`);
|
||||
if (items.some((item) => item.key === selectedKey)) return selectedKey;
|
||||
}
|
||||
return items[0].key;
|
||||
}
|
||||
|
||||
function resolveInitialRailKey(input: ModelPickerInput): string {
|
||||
const selected = input.providers.find((provider) => provider.id === input.selectedProvider);
|
||||
if (selected) return selected.id;
|
||||
if (resolveModelPickerLayout(input) === "twoPane" && (input.profiles?.length ?? 0) > 0) {
|
||||
return MODEL_PICKER_PROFILES_RAIL_KEY;
|
||||
}
|
||||
const ready = input.providers.find((provider) => provider.modelSelection.kind === "models");
|
||||
return (ready ?? input.providers[0])?.id ?? MODEL_PICKER_PROFILES_RAIL_KEY;
|
||||
}
|
||||
|
||||
function resolveRailKey(
|
||||
input: ModelPickerInput,
|
||||
state: ModelPickerState,
|
||||
layout: ModelPickerLayout,
|
||||
rail: readonly ModelPickerRailItem[],
|
||||
): string {
|
||||
if (layout === "singlePane") return input.providers[0]?.id ?? MODEL_PICKER_PROFILES_RAIL_KEY;
|
||||
if (rail.some((item) => item.key === state.railKey)) return state.railKey;
|
||||
return rail[0]?.key ?? MODEL_PICKER_PROFILES_RAIL_KEY;
|
||||
}
|
||||
|
||||
function buildRail(input: ModelPickerInput): ModelPickerRailItem[] {
|
||||
const providerItems = input.providers.map((provider) => buildProviderRailItem(input, provider));
|
||||
const working = providerItems.filter((item) => item.status !== "error");
|
||||
const errored = providerItems.filter((item) => item.status === "error");
|
||||
const firstErrored = errored[0];
|
||||
if (firstErrored && working.length > 0) firstErrored.startsErrorGroup = true;
|
||||
const ordered = [...working, ...errored];
|
||||
if (input.profiles === null) return ordered;
|
||||
return [
|
||||
{ kind: "profiles", key: MODEL_PICKER_PROFILES_RAIL_KEY, count: input.profiles.length },
|
||||
...ordered,
|
||||
];
|
||||
}
|
||||
|
||||
function buildProviderRailItem(
|
||||
input: ModelPickerInput,
|
||||
provider: ProviderSelectorProvider,
|
||||
): Extract<ModelPickerRailItem, { kind: "provider" }> {
|
||||
const selection = provider.modelSelection;
|
||||
const base = {
|
||||
kind: "provider" as const,
|
||||
key: provider.id,
|
||||
providerId: provider.id,
|
||||
label: provider.label,
|
||||
startsErrorGroup: false,
|
||||
};
|
||||
if (selection.kind === "loading") return { ...base, status: "loading", count: 0 };
|
||||
if (selection.kind === "error") return { ...base, status: "error", count: 0 };
|
||||
return { ...base, status: "ready", count: partitionFor(input, provider).primary.length };
|
||||
}
|
||||
|
||||
function buildBrowsePane<TProfile extends NavigableProfileRow>(
|
||||
input: ModelPickerInput<TProfile>,
|
||||
state: ModelPickerState,
|
||||
railKey: string,
|
||||
): ModelPickerPane<TProfile> {
|
||||
if (railKey === MODEL_PICKER_PROFILES_RAIL_KEY) {
|
||||
return { kind: "profiles", items: buildProfileItems(input) };
|
||||
}
|
||||
const provider = input.providers.find((entry) => entry.id === railKey);
|
||||
if (!provider) return { kind: "profiles", items: buildProfileItems(input) };
|
||||
const selection = provider.modelSelection;
|
||||
if (selection.kind === "loading") {
|
||||
return { kind: "providerLoading", providerId: provider.id, label: provider.label, items: [] };
|
||||
}
|
||||
if (selection.kind === "error") {
|
||||
return {
|
||||
kind: "providerError",
|
||||
providerId: provider.id,
|
||||
label: provider.label,
|
||||
message: selection.message,
|
||||
items: [],
|
||||
};
|
||||
}
|
||||
const partition = partitionFor(input, provider);
|
||||
return {
|
||||
kind: "provider",
|
||||
providerId: provider.id,
|
||||
label: provider.label,
|
||||
shown: partition.primary.length,
|
||||
total: selection.rows.length,
|
||||
foldKind: partition.foldKind,
|
||||
items: buildProviderItems(provider.id, partition, state),
|
||||
};
|
||||
}
|
||||
|
||||
function buildProviderItems<TProfile extends NavigableProfileRow>(
|
||||
providerId: string,
|
||||
partition: ProviderModelPartition,
|
||||
state: ModelPickerState,
|
||||
): ModelPickerListItem<TProfile>[] {
|
||||
const primary = partition.primary.map((row) => toModelItem<TProfile>(row, null));
|
||||
if (partition.foldKind === null) return primary;
|
||||
const expanded = state.foldOverrides[providerId] ?? partition.defaultExpanded;
|
||||
const fold: ModelPickerListItem<TProfile> = {
|
||||
kind: "fold",
|
||||
key: modelPickerFoldKey(providerId),
|
||||
providerId,
|
||||
foldKind: partition.foldKind,
|
||||
count: partition.folded.length,
|
||||
expanded,
|
||||
};
|
||||
const folded = expanded ? partition.folded.map((row) => toModelItem<TProfile>(row, null)) : [];
|
||||
return [...primary, fold, ...folded];
|
||||
}
|
||||
|
||||
function buildProfileItems<TProfile extends NavigableProfileRow>(
|
||||
input: ModelPickerInput<TProfile>,
|
||||
): ModelPickerListItem<TProfile>[] {
|
||||
const profiles = input.profiles ?? [];
|
||||
if (profiles.length === 0) {
|
||||
return input.canCreateProfile
|
||||
? [{ kind: "createProfile", key: MODEL_BROWSER_CREATE_PROFILE_KEY }]
|
||||
: [];
|
||||
}
|
||||
return profiles.map((profile) => toProfileItem(profile));
|
||||
}
|
||||
|
||||
function buildSearchPane<TProfile extends NavigableProfileRow>(
|
||||
input: ModelPickerInput<TProfile>,
|
||||
normalizedQuery: string,
|
||||
displayQuery: string,
|
||||
): ModelPickerPane<TProfile> {
|
||||
const profiles = filterAndRankProfileRows(input.profiles ?? [], normalizedQuery).map((profile) =>
|
||||
toProfileItem(profile),
|
||||
);
|
||||
const candidates: SearchCandidate[] = [];
|
||||
for (const provider of input.providers) {
|
||||
if (provider.modelSelection.kind !== "models") continue;
|
||||
const partition = partitionFor(input, provider);
|
||||
for (const row of partition.primary) candidates.push({ row, tag: null });
|
||||
for (const row of partition.folded) candidates.push({ row, tag: partition.foldKind });
|
||||
}
|
||||
const models = rankSearchMatches(candidates, normalizedQuery).map(({ row, tag }) =>
|
||||
toModelItem<TProfile>(row, tag),
|
||||
);
|
||||
if (profiles.length === 0 && models.length === 0) {
|
||||
return { kind: "noMatches", query: displayQuery, items: [] };
|
||||
}
|
||||
return { kind: "search", profiles, models, items: [...profiles, ...models] };
|
||||
}
|
||||
|
||||
interface SearchCandidate {
|
||||
row: ProviderSelectionModelRow;
|
||||
tag: ModelFoldKind;
|
||||
}
|
||||
|
||||
// The closer match wins wherever the model sits, so "opus 4.6" finds the folded Opus 4.6 before
|
||||
// a shown model that only scatters "opus" across its id. Equal matches put shown models first,
|
||||
// so "opus" leads with the current Opus.
|
||||
function rankSearchMatches(
|
||||
candidates: SearchCandidate[],
|
||||
normalizedQuery: string,
|
||||
): SearchCandidate[] {
|
||||
const matches: (SearchCandidate & { score: MatchScore })[] = [];
|
||||
for (const candidate of candidates) {
|
||||
const score = scoreModelRow(candidate.row, normalizedQuery);
|
||||
if (score) matches.push({ ...candidate, score });
|
||||
}
|
||||
matches.sort(
|
||||
(a, b) =>
|
||||
compareMatchScores(a.score, b.score) ||
|
||||
Number(a.tag !== null) - Number(b.tag !== null) ||
|
||||
a.row.modelLabel.localeCompare(b.row.modelLabel),
|
||||
);
|
||||
return matches;
|
||||
}
|
||||
|
||||
function partitionFor(
|
||||
input: ModelPickerInput,
|
||||
provider: ProviderSelectorProvider,
|
||||
): ProviderModelPartition {
|
||||
const rows = provider.modelSelection.kind === "models" ? provider.modelSelection.rows : [];
|
||||
const selectedModel = provider.id === input.selectedProvider ? input.selectedModel : "";
|
||||
return partitionProviderModels(rows, provider.shownModels, selectedModel);
|
||||
}
|
||||
|
||||
function countAllRows(provider: ProviderSelectorProvider): number {
|
||||
if (provider.modelSelection.kind !== "models") return 0;
|
||||
const partition = partitionProviderModels(provider.modelSelection.rows, provider.shownModels, "");
|
||||
const foldRow = partition.foldKind === null ? 0 : 1;
|
||||
return provider.modelSelection.rows.length + foldRow;
|
||||
}
|
||||
|
||||
function toModelItem<TProfile extends NavigableProfileRow>(
|
||||
row: ProviderSelectionModelRow,
|
||||
tag: ModelFoldKind,
|
||||
): ModelPickerListItem<TProfile> {
|
||||
return { kind: "model", key: modelBrowserModelKey(row.favoriteKey), row, tag };
|
||||
}
|
||||
|
||||
function toProfileItem<TProfile extends NavigableProfileRow>(
|
||||
profile: TProfile,
|
||||
): ModelPickerListItem<TProfile> {
|
||||
return { kind: "profile", key: modelBrowserProfileKey(profile.id), profile };
|
||||
}
|
||||
|
||||
function normalizeQuery(value: string): string {
|
||||
return value.trim().toLowerCase();
|
||||
}
|
||||
|
||||
function clamp(value: number, min: number, max: number): number {
|
||||
return Math.min(Math.max(value, min), max);
|
||||
}
|
||||
@@ -0,0 +1,899 @@
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useReducer,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
type RefObject,
|
||||
} from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { FlatList, ScrollView, Text, View } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import {
|
||||
AlertTriangle,
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
Layers,
|
||||
Pencil,
|
||||
Plus,
|
||||
} from "lucide-react-native";
|
||||
import type { AgentProvider } from "@getpaseo/protocol/agent-types";
|
||||
import {
|
||||
AgentProfileGlyph,
|
||||
type AgentProfile,
|
||||
type AgentProfilePicker,
|
||||
type AgentProfilePickerRow,
|
||||
type AgentProfileSeed,
|
||||
} from "@/agent-profiles";
|
||||
import {
|
||||
InlineHeaderView,
|
||||
type SheetHeader,
|
||||
type SheetKeyboard,
|
||||
} from "@/components/adaptive-modal-sheet";
|
||||
import {
|
||||
ModelBrowserLoadingState,
|
||||
ModelBrowserRow,
|
||||
ModelBrowserSectionHeading,
|
||||
ModelProviderGlyph,
|
||||
ModelRow,
|
||||
ModelSearchNoMatches,
|
||||
ProviderErrorEmptyState,
|
||||
} from "@/components/model-browser";
|
||||
import { focusedModelBrowserControlOwnsEnter } from "@/components/model-browser-focus";
|
||||
import {
|
||||
createModelPickerState,
|
||||
projectModelPicker,
|
||||
reduceModelPicker,
|
||||
resolveModelPickerHeight,
|
||||
resolveModelPickerKey,
|
||||
resolveModelPickerLayout,
|
||||
type ModelPickerAction,
|
||||
type ModelPickerInput,
|
||||
type ModelPickerListItem,
|
||||
type ModelPickerPane,
|
||||
type ModelPickerProjection,
|
||||
type ModelPickerRailItem,
|
||||
} from "@/components/model-browser-panes-view";
|
||||
import { groupProfilesByProviderModel } from "@/components/model-browser-view";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Combobox, type ComboboxDesktopPlacement } from "@/components/ui/combobox";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { useRevealActiveFlatListRow, useRevealActiveItem } from "@/components/ui/scroll-reveal";
|
||||
import type { EditingTextInputHandle } from "@/components/ui/text-input";
|
||||
import type { KeyboardInputEvent } from "@/keyboard";
|
||||
import { useCurrentOverlayLayer } from "@/lib/overlay-root";
|
||||
import type { ModelFoldKind } from "@/provider-selection/model-curation";
|
||||
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
|
||||
import { useProviderSettingsStore } from "@/stores/provider-settings-store";
|
||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||
|
||||
const TWO_PANE_WIDTH = 560;
|
||||
const SINGLE_PANE_WIDTH = 360;
|
||||
const RAIL_WIDTH = 192;
|
||||
const PICKER_KEYS = ["ArrowDown", "ArrowUp", "ArrowLeft", "ArrowRight", "Enter"] as const;
|
||||
const NO_OPTIONS: never[] = [];
|
||||
|
||||
const ThemedAlertTriangle = withUnistyles(AlertTriangle);
|
||||
const ThemedChevronDown = withUnistyles(ChevronDown);
|
||||
const ThemedChevronRight = withUnistyles(ChevronRight);
|
||||
const ThemedLayers = withUnistyles(Layers);
|
||||
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
|
||||
const ThemedPlus = withUnistyles(Plus);
|
||||
|
||||
const foregroundMutedMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
|
||||
|
||||
function noop() {}
|
||||
|
||||
type KeyboardHandler = (event: KeyboardInputEvent) => boolean;
|
||||
|
||||
export interface ModelPickerActions {
|
||||
onSelect: (provider: string, modelId: string) => void;
|
||||
onApplyProfile?: (profileId: string) => void;
|
||||
onEditProfiles?: () => void;
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
|
||||
onEditProfile?: (profileId: string) => void;
|
||||
onRetryProvider?: (provider: AgentProvider) => void;
|
||||
isRetryingProvider: boolean;
|
||||
}
|
||||
|
||||
export interface DesktopModelPickerProps extends ModelPickerActions {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
anchorRef: RefObject<View | null>;
|
||||
desktopPlacement?: ComboboxDesktopPlacement;
|
||||
providers: ProviderSelectorProvider[];
|
||||
selectedProvider: string;
|
||||
selectedModel: string;
|
||||
profiles: AgentProfilePicker | null;
|
||||
serverId: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The model picker on wide layouts: a rail of Profiles and providers beside the open entry's
|
||||
* models, or one list when there is a single provider and no profiles. The popover keeps one size
|
||||
* for as long as it is open.
|
||||
*/
|
||||
export function DesktopModelPicker({
|
||||
open,
|
||||
onOpenChange,
|
||||
anchorRef,
|
||||
desktopPlacement,
|
||||
providers,
|
||||
selectedProvider,
|
||||
selectedModel,
|
||||
profiles,
|
||||
serverId,
|
||||
...actions
|
||||
}: DesktopModelPickerProps) {
|
||||
const input = useMemo<ModelPickerInput<AgentProfilePickerRow>>(
|
||||
() => ({
|
||||
providers,
|
||||
profiles: profiles?.rows ?? null,
|
||||
canCreateProfile: Boolean(actions.onEditProfiles),
|
||||
selectedProvider,
|
||||
selectedModel,
|
||||
}),
|
||||
[actions.onEditProfiles, profiles, providers, selectedModel, selectedProvider],
|
||||
);
|
||||
const layout = resolveModelPickerLayout(input);
|
||||
const height = useMemo(() => resolveModelPickerHeight(input), [input]);
|
||||
const keyboardHandlerRef = useRef<KeyboardHandler | null>(null);
|
||||
const keyboard = useMemo<SheetKeyboard>(
|
||||
() => ({
|
||||
keys: PICKER_KEYS,
|
||||
onKeyDown: (event) => keyboardHandlerRef.current?.(event) ?? false,
|
||||
}),
|
||||
[],
|
||||
);
|
||||
|
||||
return (
|
||||
<Combobox
|
||||
options={NO_OPTIONS}
|
||||
value=""
|
||||
onSelect={noop}
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
anchorRef={anchorRef}
|
||||
desktopPlacement={desktopPlacement}
|
||||
desktopMinWidth={layout === "twoPane" ? TWO_PANE_WIDTH : SINGLE_PANE_WIDTH}
|
||||
desktopLockWidth
|
||||
desktopFixedHeight={height}
|
||||
desktopChildrenScrollEnabled={false}
|
||||
keyboard={keyboard}
|
||||
>
|
||||
<ModelPickerBody
|
||||
input={input}
|
||||
serverId={serverId}
|
||||
keyboardHandlerRef={keyboardHandlerRef}
|
||||
{...actions}
|
||||
/>
|
||||
</Combobox>
|
||||
);
|
||||
}
|
||||
|
||||
/** Mounted only while the popover is open, so every open starts from the current selection. */
|
||||
function ModelPickerBody({
|
||||
input,
|
||||
serverId,
|
||||
keyboardHandlerRef,
|
||||
...actions
|
||||
}: ModelPickerActions & {
|
||||
input: ModelPickerInput<AgentProfilePickerRow>;
|
||||
serverId: string | null;
|
||||
keyboardHandlerRef: RefObject<KeyboardHandler | null>;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const { onSelect, onApplyProfile, onEditProfiles, onCreateProfile, onEditProfile } = actions;
|
||||
const { onRetryProvider, isRetryingProvider } = actions;
|
||||
const stableActions = useMemo<ModelPickerActions>(
|
||||
() => ({
|
||||
onSelect,
|
||||
onApplyProfile,
|
||||
onEditProfiles,
|
||||
onCreateProfile,
|
||||
onEditProfile,
|
||||
onRetryProvider,
|
||||
isRetryingProvider,
|
||||
}),
|
||||
[
|
||||
isRetryingProvider,
|
||||
onApplyProfile,
|
||||
onCreateProfile,
|
||||
onEditProfile,
|
||||
onEditProfiles,
|
||||
onRetryProvider,
|
||||
onSelect,
|
||||
],
|
||||
);
|
||||
const [state, setState] = useState(() => createModelPickerState(input));
|
||||
const [searchResetKey, bumpSearchResetKey] = useReducer((key: number) => key + 1, 0);
|
||||
const searchInputRef = useRef<EditingTextInputHandle | null>(null);
|
||||
const projection = useMemo(() => projectModelPicker(input, state), [input, state]);
|
||||
|
||||
const focusSearch = useCallback(() => {
|
||||
searchInputRef.current?.focus();
|
||||
}, []);
|
||||
const dispatch = useCallback((action: ModelPickerAction) => {
|
||||
setState((current) => reduceModelPicker(current, action));
|
||||
}, []);
|
||||
|
||||
const handleKeyDown = useCallback(
|
||||
(event: KeyboardInputEvent): boolean => {
|
||||
const result = resolveModelPickerKey(input, state, {
|
||||
event,
|
||||
focusedControlOwnsEnter: focusedModelBrowserControlOwnsEnter(),
|
||||
});
|
||||
if (!result) return false;
|
||||
switch (result.kind) {
|
||||
case "state":
|
||||
if (result.state.query !== state.query) bumpSearchResetKey();
|
||||
setState(result.state);
|
||||
focusSearch();
|
||||
return true;
|
||||
case "selectModel":
|
||||
actions.onSelect(result.provider, result.modelId);
|
||||
return true;
|
||||
case "applyProfile":
|
||||
if (!actions.onApplyProfile) return false;
|
||||
actions.onApplyProfile(result.profileId);
|
||||
return true;
|
||||
case "createProfile":
|
||||
if (!actions.onEditProfiles) return false;
|
||||
actions.onEditProfiles();
|
||||
return true;
|
||||
}
|
||||
},
|
||||
[actions, focusSearch, input, state],
|
||||
);
|
||||
const handleKeyDownRef = useRef(handleKeyDown);
|
||||
handleKeyDownRef.current = handleKeyDown;
|
||||
useEffect(() => {
|
||||
keyboardHandlerRef.current = (event) => handleKeyDownRef.current(event);
|
||||
return () => {
|
||||
keyboardHandlerRef.current = null;
|
||||
};
|
||||
}, [keyboardHandlerRef]);
|
||||
|
||||
const header = useMemo<SheetHeader>(
|
||||
() => ({
|
||||
title: t("modelSelector.models"),
|
||||
search: {
|
||||
onChange: (query) => dispatch({ kind: "query", query }),
|
||||
placeholder:
|
||||
input.profiles && input.profiles.length > 0
|
||||
? t("modelSelector.searchModelsAndProfilesPlaceholder")
|
||||
: t("modelSelector.searchPlaceholder"),
|
||||
autoFocus: true,
|
||||
resetKey: searchResetKey,
|
||||
inputRef: searchInputRef,
|
||||
testID: "model-search-input",
|
||||
},
|
||||
}),
|
||||
[dispatch, input.profiles, searchResetKey, t],
|
||||
);
|
||||
|
||||
const handleSelectRail = useCallback(
|
||||
(railKey: string) => {
|
||||
setState((current) => ({
|
||||
...reduceModelPicker(current, { kind: "selectRail", railKey }),
|
||||
focus: "list",
|
||||
}));
|
||||
focusSearch();
|
||||
},
|
||||
[focusSearch],
|
||||
);
|
||||
const handleToggleFold = useCallback(
|
||||
(item: Extract<ModelPickerListItem, { kind: "fold" }>) => {
|
||||
setState((current) =>
|
||||
reduceModelPicker(reduceModelPicker(current, { kind: "activate", key: item.key }), {
|
||||
kind: "toggleFold",
|
||||
providerId: item.providerId,
|
||||
expanded: !item.expanded,
|
||||
}),
|
||||
);
|
||||
focusSearch();
|
||||
},
|
||||
[focusSearch],
|
||||
);
|
||||
const handleActivate = useCallback(
|
||||
(key: string) => dispatch({ kind: "activate", key }),
|
||||
[dispatch],
|
||||
);
|
||||
|
||||
const isSearching = projection.pane.kind === "search" || projection.pane.kind === "noMatches";
|
||||
let body: ReactNode;
|
||||
if (isSearching || projection.layout === "singlePane") {
|
||||
body = (
|
||||
<ListPane
|
||||
projection={projection}
|
||||
query={state.query}
|
||||
serverId={serverId}
|
||||
input={input}
|
||||
onToggleFold={handleToggleFold}
|
||||
onActivate={handleActivate}
|
||||
actions={stableActions}
|
||||
/>
|
||||
);
|
||||
} else {
|
||||
body = (
|
||||
<View style={styles.panes}>
|
||||
<Rail projection={projection} serverId={serverId} onSelectRail={handleSelectRail} />
|
||||
<ListPane
|
||||
projection={projection}
|
||||
query={state.query}
|
||||
serverId={serverId}
|
||||
input={input}
|
||||
onToggleFold={handleToggleFold}
|
||||
onActivate={handleActivate}
|
||||
actions={stableActions}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={styles.root} testID="model-picker">
|
||||
<InlineHeaderView header={header} />
|
||||
{body}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function Rail({
|
||||
projection,
|
||||
serverId,
|
||||
onSelectRail,
|
||||
}: {
|
||||
projection: ModelPickerProjection<AgentProfilePickerRow>;
|
||||
serverId: string | null;
|
||||
onSelectRail: (railKey: string) => void;
|
||||
}) {
|
||||
const scrollRef = useRef<ScrollView>(null);
|
||||
const reveal = useRevealActiveItem({
|
||||
activeIndex: projection.rail.findIndex((item) => item.key === projection.railKey),
|
||||
listKey: "rail",
|
||||
scrollRef,
|
||||
});
|
||||
return (
|
||||
<View style={styles.rail} testID="model-picker-rail">
|
||||
<ScrollView
|
||||
ref={scrollRef}
|
||||
style={styles.scroll}
|
||||
contentContainerStyle={styles.railContent}
|
||||
onLayout={reveal.onViewportLayout}
|
||||
onScroll={reveal.onScroll}
|
||||
scrollEventThrottle={16}
|
||||
keyboardShouldPersistTaps="handled"
|
||||
showsVerticalScrollIndicator={false}
|
||||
>
|
||||
<View ref={reveal.contentRef} collapsable={false}>
|
||||
{projection.rail.map((item) => (
|
||||
<View key={item.key}>
|
||||
{item.kind === "provider" && item.startsErrorGroup ? (
|
||||
<View style={styles.railDivider} />
|
||||
) : null}
|
||||
<RailRow
|
||||
item={item}
|
||||
serverId={serverId}
|
||||
selected={item.key === projection.railKey}
|
||||
focused={projection.focus === "rail"}
|
||||
activeItemRef={reveal.activeItemRef}
|
||||
onActiveLayout={reveal.onItemLayout}
|
||||
onSelect={onSelectRail}
|
||||
/>
|
||||
{item.kind === "profiles" ? <View style={styles.railDivider} /> : null}
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
</ScrollView>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function RailRow({
|
||||
item,
|
||||
serverId,
|
||||
selected,
|
||||
focused,
|
||||
activeItemRef,
|
||||
onActiveLayout,
|
||||
onSelect,
|
||||
}: {
|
||||
item: ModelPickerRailItem;
|
||||
serverId: string | null;
|
||||
selected: boolean;
|
||||
focused: boolean;
|
||||
activeItemRef: RefObject<View | null>;
|
||||
onActiveLayout: () => void;
|
||||
onSelect: (railKey: string) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const handlePress = useCallback(() => onSelect(item.key), [item.key, onSelect]);
|
||||
const providerId = item.kind === "provider" ? item.providerId : null;
|
||||
const leadingSlot = useMemo(
|
||||
() =>
|
||||
providerId === null ? (
|
||||
<ThemedLayers size={ICON_SIZE.sm} uniProps={foregroundMutedMapping} />
|
||||
) : (
|
||||
<ModelProviderGlyph provider={providerId} serverId={serverId} size={ICON_SIZE.sm} />
|
||||
),
|
||||
[providerId, serverId],
|
||||
);
|
||||
const trailingSlot = useMemo(() => <RailRowStatus item={item} />, [item]);
|
||||
return (
|
||||
<ModelBrowserRow
|
||||
label={item.kind === "profiles" ? t("modelSelector.profiles") : item.label}
|
||||
labelMuted={item.kind === "provider" && item.status === "error"}
|
||||
leadingSlot={leadingSlot}
|
||||
trailingSlot={trailingSlot}
|
||||
// The open entry stays highlighted while the list has focus, like a list+detail sidebar.
|
||||
active={selected}
|
||||
tone={focused ? "elevated" : "default"}
|
||||
spacing="provider"
|
||||
activeItemRef={activeItemRef}
|
||||
onActiveLayout={onActiveLayout}
|
||||
onPress={handlePress}
|
||||
testID={
|
||||
item.kind === "profiles"
|
||||
? "model-picker-rail-profiles"
|
||||
: `model-provider-${item.providerId}`
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function RailRowStatus({ item }: { item: ModelPickerRailItem }) {
|
||||
if (item.kind === "provider" && item.status === "loading") {
|
||||
return (
|
||||
<View style={styles.railSpinner}>
|
||||
<ThemedLoadingSpinner size={ICON_SIZE.sm} uniProps={foregroundMutedMapping} />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
if (item.kind === "provider" && item.status === "error") {
|
||||
return <ThemedAlertTriangle size={ICON_SIZE.xs} uniProps={foregroundMutedMapping} />;
|
||||
}
|
||||
return <Text style={styles.count}>{item.count}</Text>;
|
||||
}
|
||||
|
||||
type ListEntry =
|
||||
| { kind: "heading"; key: string; title: string }
|
||||
| { kind: "item"; key: string; item: ModelPickerListItem<AgentProfilePickerRow> };
|
||||
|
||||
/** Search results carry section headings between their groups; every other pane is a flat list. */
|
||||
function useListEntries(pane: ModelPickerPane<AgentProfilePickerRow>): ListEntry[] {
|
||||
const { t } = useTranslation();
|
||||
return useMemo(() => {
|
||||
const toEntry = (item: ModelPickerListItem<AgentProfilePickerRow>): ListEntry => ({
|
||||
kind: "item",
|
||||
key: item.key,
|
||||
item,
|
||||
});
|
||||
if (pane.kind !== "search") return pane.items.map(toEntry);
|
||||
const entries: ListEntry[] = [];
|
||||
if (pane.profiles.length > 0) {
|
||||
entries.push({
|
||||
kind: "heading",
|
||||
key: "heading:profiles",
|
||||
title: t("modelSelector.profiles"),
|
||||
});
|
||||
entries.push(...pane.profiles.map(toEntry));
|
||||
if (pane.models.length > 0) {
|
||||
entries.push({ kind: "heading", key: "heading:models", title: t("modelSelector.models") });
|
||||
}
|
||||
}
|
||||
entries.push(...pane.models.map(toEntry));
|
||||
return entries;
|
||||
}, [pane, t]);
|
||||
}
|
||||
|
||||
/** The first row reveals as the list top, so a section heading above it stays in view. */
|
||||
function resolveRevealTarget(entries: readonly ListEntry[], activeKey: string | null) {
|
||||
if (!activeKey) return null;
|
||||
const index = entries.findIndex((entry) => entry.key === activeKey);
|
||||
const firstItem = entries.findIndex((entry) => entry.kind === "item");
|
||||
return index === firstItem ? "top" : index;
|
||||
}
|
||||
|
||||
function getListEntryKey(entry: ListEntry): string {
|
||||
return entry.key;
|
||||
}
|
||||
|
||||
function ListPane({
|
||||
projection,
|
||||
query,
|
||||
input,
|
||||
serverId,
|
||||
onToggleFold,
|
||||
onActivate,
|
||||
actions,
|
||||
}: {
|
||||
projection: ModelPickerProjection<AgentProfilePickerRow>;
|
||||
/** Each query is a new result list, which opens at its top. */
|
||||
query: string;
|
||||
input: ModelPickerInput<AgentProfilePickerRow>;
|
||||
serverId: string | null;
|
||||
onToggleFold: (item: Extract<ModelPickerListItem, { kind: "fold" }>) => void;
|
||||
onActivate: (key: string) => void;
|
||||
actions: ModelPickerActions;
|
||||
}) {
|
||||
const { pane, activeKey } = projection;
|
||||
const entries = useListEntries(pane);
|
||||
const listRef = useRef<FlatList<ListEntry>>(null);
|
||||
const reveal = useRevealActiveFlatListRow({
|
||||
listRef,
|
||||
itemCount: entries.length,
|
||||
activeIndex: resolveRevealTarget(entries, activeKey),
|
||||
listKey: `${pane.kind}:${projection.railKey}:${query}`,
|
||||
});
|
||||
const profiledLookup = useMemo(
|
||||
() => groupProfilesByProviderModel(input.profiles ?? []),
|
||||
[input.profiles],
|
||||
);
|
||||
const inSearch = pane.kind === "search";
|
||||
const { selectedProvider, selectedModel } = input;
|
||||
|
||||
const renderEntry = useCallback(
|
||||
({ item: entry }: { item: ListEntry }) => {
|
||||
if (entry.kind === "heading") return <ModelBrowserSectionHeading title={entry.title} />;
|
||||
const { item } = entry;
|
||||
return (
|
||||
<ModelPickerItemRow
|
||||
item={item}
|
||||
active={item.key === activeKey}
|
||||
selected={
|
||||
item.kind === "model" &&
|
||||
item.row.provider === selectedProvider &&
|
||||
item.row.modelId === selectedModel
|
||||
}
|
||||
inSearch={inSearch}
|
||||
serverId={serverId}
|
||||
profiledLookup={profiledLookup}
|
||||
onToggleFold={onToggleFold}
|
||||
onActivate={onActivate}
|
||||
actions={actions}
|
||||
/>
|
||||
);
|
||||
},
|
||||
[
|
||||
actions,
|
||||
activeKey,
|
||||
inSearch,
|
||||
onActivate,
|
||||
onToggleFold,
|
||||
profiledLookup,
|
||||
selectedModel,
|
||||
selectedProvider,
|
||||
serverId,
|
||||
],
|
||||
);
|
||||
|
||||
return (
|
||||
<View style={styles.listPane} testID="model-picker-list">
|
||||
<ListPaneHeader pane={pane} serverId={serverId} onEditProfiles={actions.onEditProfiles} />
|
||||
<PaneState pane={pane} actions={actions} />
|
||||
{entries.length > 0 ? (
|
||||
<FlatList
|
||||
ref={listRef}
|
||||
data={entries}
|
||||
extraData={activeKey}
|
||||
renderItem={renderEntry}
|
||||
keyExtractor={getListEntryKey}
|
||||
onScrollToIndexFailed={reveal.onScrollToIndexFailed}
|
||||
onViewableItemsChanged={reveal.onViewableItemsChanged}
|
||||
viewabilityConfig={reveal.viewabilityConfig}
|
||||
onContentSizeChange={reveal.onContentSizeChange}
|
||||
onLayout={reveal.onLayout}
|
||||
style={styles.scroll}
|
||||
contentContainerStyle={styles.listContent}
|
||||
keyboardShouldPersistTaps="handled"
|
||||
showsVerticalScrollIndicator={false}
|
||||
testID="model-picker-model-list"
|
||||
/>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function ListPaneHeader({
|
||||
pane,
|
||||
serverId,
|
||||
onEditProfiles,
|
||||
}: {
|
||||
pane: ModelPickerPane<AgentProfilePickerRow>;
|
||||
serverId: string | null;
|
||||
onEditProfiles?: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
if (pane.kind === "search" || pane.kind === "noMatches") return null;
|
||||
if (pane.kind === "profiles") {
|
||||
return (
|
||||
<View style={styles.paneHeader}>
|
||||
<Text style={styles.paneTitle} numberOfLines={1}>
|
||||
{t("modelSelector.profiles")}
|
||||
</Text>
|
||||
{onEditProfiles ? (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onPress={onEditProfiles}
|
||||
accessibilityLabel={t("modelSelector.editProfilesLabel")}
|
||||
testID="model-profiles-edit"
|
||||
>
|
||||
{t("modelSelector.editProfiles")}
|
||||
</Button>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
const summary =
|
||||
pane.kind === "provider" && pane.foldKind !== null
|
||||
? t("modelSelector.shownOfTotal", { shown: pane.shown, total: pane.total })
|
||||
: null;
|
||||
return (
|
||||
<View style={styles.paneHeader}>
|
||||
<Text style={styles.paneTitle} numberOfLines={1}>
|
||||
{pane.label}
|
||||
{summary ? <Text style={styles.paneSummary}>{` · ${summary}`}</Text> : null}
|
||||
</Text>
|
||||
{serverId ? (
|
||||
<CustomizeProviderButton
|
||||
serverId={serverId}
|
||||
providerId={pane.providerId}
|
||||
providerLabel={pane.label}
|
||||
/>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export function CustomizeProviderButton({
|
||||
serverId,
|
||||
providerId,
|
||||
providerLabel,
|
||||
}: {
|
||||
serverId: string;
|
||||
providerId: string;
|
||||
providerLabel: string;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const overlayParentLayer = useCurrentOverlayLayer();
|
||||
const handlePress = useCallback(() => {
|
||||
useProviderSettingsStore
|
||||
.getState()
|
||||
.open({ serverId, provider: providerId, overlayParentLayer });
|
||||
}, [overlayParentLayer, providerId, serverId]);
|
||||
return (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
leftIcon={Pencil}
|
||||
onPress={handlePress}
|
||||
accessibilityLabel={t("modelSelector.openProviderSettings", { provider: providerLabel })}
|
||||
testID={`selector-header-settings-${providerId}`}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function PaneState({
|
||||
pane,
|
||||
actions,
|
||||
}: {
|
||||
pane: ModelPickerPane<AgentProfilePickerRow>;
|
||||
actions: ModelPickerActions;
|
||||
}) {
|
||||
const { onRetryProvider, isRetryingProvider } = actions;
|
||||
if (pane.kind === "providerLoading") return <ModelBrowserLoadingState />;
|
||||
if (pane.kind === "providerError") {
|
||||
return (
|
||||
<ProviderErrorEmptyState
|
||||
providerId={pane.providerId}
|
||||
message={pane.message}
|
||||
onRetryProvider={onRetryProvider}
|
||||
isRetryingProvider={isRetryingProvider}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (pane.kind === "noMatches") return <ModelSearchNoMatches query={pane.query} />;
|
||||
return null;
|
||||
}
|
||||
|
||||
function useFoldTag(tag: ModelFoldKind): string | undefined {
|
||||
const { t } = useTranslation();
|
||||
if (tag === "older") return t("modelSelector.olderTag");
|
||||
if (tag === "all") return t("modelSelector.allModelsTag");
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** One row of a picker list: a model, a fold, a profile, or the create-profile entry. */
|
||||
export function ModelPickerItemRow({
|
||||
item,
|
||||
active,
|
||||
selected,
|
||||
inSearch,
|
||||
serverId,
|
||||
profiledLookup,
|
||||
onToggleFold,
|
||||
onActivate,
|
||||
actions,
|
||||
}: {
|
||||
item: ModelPickerListItem<AgentProfilePickerRow>;
|
||||
active: boolean;
|
||||
selected: boolean;
|
||||
inSearch: boolean;
|
||||
serverId: string | null;
|
||||
profiledLookup: Map<string, AgentProfilePickerRow[]>;
|
||||
onToggleFold: (item: Extract<ModelPickerListItem, { kind: "fold" }>) => void;
|
||||
onActivate: (key: string) => void;
|
||||
actions: ModelPickerActions;
|
||||
}) {
|
||||
const { onSelect, onApplyProfile, onEditProfiles, onCreateProfile, onEditProfile } = actions;
|
||||
const { t } = useTranslation();
|
||||
const tag = useFoldTag(item.kind === "model" ? item.tag : null);
|
||||
const leadingSlot = useMemo(() => {
|
||||
switch (item.kind) {
|
||||
case "profile":
|
||||
return (
|
||||
<AgentProfileGlyph
|
||||
icon={item.profile.icon}
|
||||
color={item.profile.color}
|
||||
provider={item.profile.provider}
|
||||
serverId={serverId}
|
||||
size={ICON_SIZE.sm}
|
||||
/>
|
||||
);
|
||||
case "createProfile":
|
||||
return <ThemedPlus size={ICON_SIZE.sm} uniProps={foregroundMutedMapping} />;
|
||||
case "fold": {
|
||||
const Chevron = item.expanded ? ThemedChevronDown : ThemedChevronRight;
|
||||
return <Chevron size={ICON_SIZE.sm} uniProps={foregroundMutedMapping} />;
|
||||
}
|
||||
case "model":
|
||||
return null;
|
||||
}
|
||||
}, [item, serverId]);
|
||||
const handleFocus = useCallback(() => onActivate(item.key), [item.key, onActivate]);
|
||||
const handlePress = useCallback(() => {
|
||||
switch (item.kind) {
|
||||
case "model":
|
||||
onSelect(item.row.provider, item.row.modelId);
|
||||
return;
|
||||
case "profile":
|
||||
onApplyProfile?.(item.profile.id);
|
||||
return;
|
||||
case "createProfile":
|
||||
onEditProfiles?.();
|
||||
return;
|
||||
case "fold":
|
||||
onToggleFold(item);
|
||||
}
|
||||
}, [item, onApplyProfile, onEditProfiles, onSelect, onToggleFold]);
|
||||
|
||||
if (item.kind === "model") {
|
||||
return (
|
||||
<ModelRow
|
||||
row={item.row}
|
||||
serverId={serverId}
|
||||
isSelected={selected}
|
||||
isActive={active}
|
||||
showProviderLabel={inSearch}
|
||||
tag={tag}
|
||||
onPress={handlePress}
|
||||
onFocus={handleFocus}
|
||||
profiledRows={profiledLookup.get(`${item.row.provider}:${item.row.modelId}`) ?? []}
|
||||
onCreateProfile={onCreateProfile}
|
||||
onEditProfile={onEditProfile}
|
||||
onEditProfiles={onEditProfiles}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (item.kind === "profile") {
|
||||
return (
|
||||
<ModelBrowserRow
|
||||
label={item.profile.name}
|
||||
description={item.profile.summary}
|
||||
active={active}
|
||||
onPress={handlePress}
|
||||
onFocus={handleFocus}
|
||||
leadingSlot={leadingSlot}
|
||||
testID={`model-profile-row-${item.profile.id}`}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (item.kind === "createProfile") {
|
||||
return (
|
||||
<ModelBrowserRow
|
||||
label={t("modelSelector.createProfile")}
|
||||
labelMuted
|
||||
active={active}
|
||||
onPress={handlePress}
|
||||
onFocus={handleFocus}
|
||||
leadingSlot={leadingSlot}
|
||||
testID="model-profiles-empty"
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<ModelBrowserRow
|
||||
label={t(
|
||||
item.foldKind === "older" ? "modelSelector.olderModels" : "modelSelector.allModels",
|
||||
{
|
||||
count: item.count,
|
||||
},
|
||||
)}
|
||||
labelMuted
|
||||
active={active}
|
||||
onPress={handlePress}
|
||||
onFocus={handleFocus}
|
||||
leadingSlot={leadingSlot}
|
||||
testID={`model-fold-${item.providerId}`}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
root: {
|
||||
flex: 1,
|
||||
minHeight: 0,
|
||||
},
|
||||
panes: {
|
||||
flex: 1,
|
||||
minHeight: 0,
|
||||
flexDirection: "row",
|
||||
},
|
||||
rail: {
|
||||
width: RAIL_WIDTH,
|
||||
flexShrink: 0,
|
||||
borderRightWidth: 1,
|
||||
borderRightColor: theme.colors.border,
|
||||
},
|
||||
railContent: {
|
||||
paddingVertical: theme.spacing[1],
|
||||
},
|
||||
railDivider: {
|
||||
height: 1,
|
||||
marginVertical: theme.spacing[1],
|
||||
marginHorizontal: theme.spacing[3],
|
||||
backgroundColor: theme.colors.border,
|
||||
},
|
||||
railSpinner: {
|
||||
transform: [{ scale: 0.7 }],
|
||||
},
|
||||
count: {
|
||||
fontSize: theme.fontSize.sm,
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontVariant: ["tabular-nums"],
|
||||
},
|
||||
listPane: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
minHeight: 0,
|
||||
},
|
||||
scroll: {
|
||||
flex: 1,
|
||||
},
|
||||
listContent: {
|
||||
paddingBottom: theme.spacing[2],
|
||||
},
|
||||
paneHeader: {
|
||||
height: 36,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
paddingLeft: theme.spacing[3],
|
||||
paddingRight: theme.spacing[1],
|
||||
},
|
||||
paneTitle: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
fontSize: theme.fontSize.sm,
|
||||
fontWeight: theme.fontWeight.medium,
|
||||
color: theme.colors.foreground,
|
||||
},
|
||||
paneSummary: {
|
||||
fontWeight: theme.fontWeight.normal,
|
||||
color: theme.colors.foregroundMuted,
|
||||
},
|
||||
}));
|
||||
@@ -17,7 +17,6 @@ import {
|
||||
resolveModelBrowserKeyCommand,
|
||||
resolveModelBrowserNavItems,
|
||||
resolveModelBrowserProjection,
|
||||
resolveModelBrowserScrolling,
|
||||
} from "./model-browser-view";
|
||||
|
||||
function provider(
|
||||
@@ -48,20 +47,6 @@ function modelRow(
|
||||
};
|
||||
}
|
||||
|
||||
describe("model browser scrolling", () => {
|
||||
it("participates in native compact bottom-sheet scrolling", () => {
|
||||
expect(resolveModelBrowserScrolling({ isNative: true, isCompact: true })).toBe("sheet");
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ platform: "native wide", isNative: true, isCompact: false },
|
||||
{ platform: "compact web", isNative: false, isCompact: true },
|
||||
{ platform: "wide web", isNative: false, isCompact: false },
|
||||
])("owns scrolling on $platform surfaces", ({ isNative, isCompact }) => {
|
||||
expect(resolveModelBrowserScrolling({ isNative, isCompact })).toBe("independent");
|
||||
});
|
||||
});
|
||||
|
||||
describe("model browser initial view", () => {
|
||||
const codex = provider("codex", "Codex");
|
||||
const pi = provider("pi", "Pi");
|
||||
@@ -169,36 +154,17 @@ describe("model browser all view", () => {
|
||||
providers,
|
||||
profiles: [],
|
||||
normalizedQuery: "",
|
||||
isSearchFocused: false,
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "browse",
|
||||
});
|
||||
});
|
||||
|
||||
it("shows every searchable model as soon as empty search receives focus", () => {
|
||||
const view = resolveModelBrowserAllView({
|
||||
providers,
|
||||
profiles: [],
|
||||
normalizedQuery: "",
|
||||
isSearchFocused: true,
|
||||
});
|
||||
|
||||
expect(view.kind).toBe("searchResults");
|
||||
expect(view.kind === "searchResults" ? view.rows.map((row) => row.favoriteKey) : []).toEqual([
|
||||
"claude:opus-5",
|
||||
"claude:sonnet-4.6",
|
||||
"copilot:claude-opus-5",
|
||||
"codex:gpt-5.4",
|
||||
]);
|
||||
});
|
||||
|
||||
it("ranks the same model label across every provider that offers it", () => {
|
||||
const view = resolveModelBrowserAllView({
|
||||
providers,
|
||||
profiles: [],
|
||||
normalizedQuery: "opus",
|
||||
isSearchFocused: true,
|
||||
});
|
||||
|
||||
expect(view.kind).toBe("searchResults");
|
||||
@@ -213,7 +179,6 @@ describe("model browser all view", () => {
|
||||
providers,
|
||||
profiles: [],
|
||||
normalizedQuery: "codex",
|
||||
isSearchFocused: true,
|
||||
});
|
||||
|
||||
expect(view.kind === "searchResults" ? view.rows.map((row) => row.modelId) : []).toEqual([
|
||||
@@ -227,7 +192,6 @@ describe("model browser all view", () => {
|
||||
providers,
|
||||
profiles: [],
|
||||
normalizedQuery: "zzzz",
|
||||
isSearchFocused: true,
|
||||
}),
|
||||
).toEqual({ kind: "noSearchMatches" });
|
||||
});
|
||||
@@ -249,7 +213,6 @@ describe("model browser all view", () => {
|
||||
providers: [loading, failed],
|
||||
profiles: [],
|
||||
normalizedQuery: "opus",
|
||||
isSearchFocused: true,
|
||||
}),
|
||||
).toEqual({ kind: "noSearchMatches" });
|
||||
});
|
||||
@@ -268,7 +231,6 @@ describe("model browser profile search", () => {
|
||||
providers: [claude],
|
||||
profiles,
|
||||
normalizedQuery: "review",
|
||||
isSearchFocused: true,
|
||||
});
|
||||
|
||||
expect(view).toEqual({ kind: "searchResults", profiles: [reviewer], rows: [] });
|
||||
@@ -279,7 +241,6 @@ describe("model browser profile search", () => {
|
||||
providers: [claude],
|
||||
profiles,
|
||||
normalizedQuery: "opus",
|
||||
isSearchFocused: true,
|
||||
});
|
||||
|
||||
expect(view.kind === "searchResults" ? view.profiles : []).toEqual([reviewer]);
|
||||
@@ -319,11 +280,8 @@ describe("model browser keyboard navigation", () => {
|
||||
view: { kind: "all" },
|
||||
providers,
|
||||
profiles,
|
||||
showProfilesSection: true,
|
||||
canCreateProfileRow: true,
|
||||
normalizedQuery: "",
|
||||
isSearchFocused: false,
|
||||
hasCustomRootBrowseContent: false,
|
||||
});
|
||||
|
||||
expect(items.map((item) => item.key)).toEqual([
|
||||
@@ -339,11 +297,8 @@ describe("model browser keyboard navigation", () => {
|
||||
view: { kind: "all" },
|
||||
providers,
|
||||
profiles: [],
|
||||
showProfilesSection: true,
|
||||
canCreateProfileRow: true,
|
||||
normalizedQuery: "",
|
||||
isSearchFocused: false,
|
||||
hasCustomRootBrowseContent: false,
|
||||
});
|
||||
|
||||
expect(items.map((item) => item.key)).toEqual([
|
||||
@@ -353,34 +308,13 @@ describe("model browser keyboard navigation", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("omits providers when custom root browse content replaces them", () => {
|
||||
const items = resolveModelBrowserNavItems({
|
||||
view: { kind: "all" },
|
||||
providers,
|
||||
profiles,
|
||||
showProfilesSection: true,
|
||||
canCreateProfileRow: true,
|
||||
normalizedQuery: "",
|
||||
isSearchFocused: false,
|
||||
hasCustomRootBrowseContent: true,
|
||||
});
|
||||
|
||||
expect(items.map((item) => item.key)).toEqual([
|
||||
modelBrowserProfileKey("reviewer"),
|
||||
modelBrowserProfileKey("quick"),
|
||||
]);
|
||||
});
|
||||
|
||||
it("orders matching profiles before matching models with model indexes in search results", () => {
|
||||
const items = resolveModelBrowserNavItems({
|
||||
view: { kind: "all" },
|
||||
providers,
|
||||
profiles,
|
||||
showProfilesSection: true,
|
||||
canCreateProfileRow: true,
|
||||
normalizedQuery: "opus",
|
||||
isSearchFocused: true,
|
||||
hasCustomRootBrowseContent: false,
|
||||
});
|
||||
|
||||
expect(items).toEqual([
|
||||
@@ -400,11 +334,8 @@ describe("model browser keyboard navigation", () => {
|
||||
view: { kind: "provider", providerId: "claude", providerLabel: "Claude Code" },
|
||||
providers,
|
||||
profiles,
|
||||
showProfilesSection: true,
|
||||
canCreateProfileRow: true,
|
||||
normalizedQuery: "",
|
||||
isSearchFocused: false,
|
||||
hasCustomRootBrowseContent: false,
|
||||
});
|
||||
|
||||
expect(items.map((item) => item.key)).toEqual([
|
||||
@@ -417,11 +348,8 @@ describe("model browser keyboard navigation", () => {
|
||||
view: { kind: "provider", providerId: "pi", providerLabel: "Pi" },
|
||||
providers: [{ id: "pi", label: "Pi", modelSelection: { kind: "loading" } }],
|
||||
profiles: null,
|
||||
showProfilesSection: false,
|
||||
canCreateProfileRow: false,
|
||||
normalizedQuery: "",
|
||||
isSearchFocused: false,
|
||||
hasCustomRootBrowseContent: false,
|
||||
});
|
||||
expect(loadingItems).toEqual([]);
|
||||
});
|
||||
@@ -432,11 +360,8 @@ describe("model browser keyboard navigation", () => {
|
||||
view,
|
||||
providers,
|
||||
profiles,
|
||||
showProfilesSection: true,
|
||||
canCreateProfileRow: false,
|
||||
normalizedQuery: "",
|
||||
isSearchFocused: false,
|
||||
hasCustomRootBrowseContent: false,
|
||||
});
|
||||
|
||||
expect(
|
||||
@@ -467,11 +392,8 @@ describe("model browser keyboard navigation", () => {
|
||||
view: { kind: "all" },
|
||||
providers,
|
||||
profiles,
|
||||
showProfilesSection: true,
|
||||
canCreateProfileRow: false,
|
||||
normalizedQuery: "",
|
||||
isSearchFocused: false,
|
||||
hasCustomRootBrowseContent: false,
|
||||
});
|
||||
|
||||
expect(
|
||||
@@ -492,11 +414,8 @@ describe("model browser keyboard navigation", () => {
|
||||
view: { kind: "all" },
|
||||
providers,
|
||||
profiles,
|
||||
showProfilesSection: true,
|
||||
canCreateProfileRow: false,
|
||||
normalizedQuery: "",
|
||||
isSearchFocused: false,
|
||||
hasCustomRootBrowseContent: false,
|
||||
});
|
||||
|
||||
expect(
|
||||
@@ -535,11 +454,8 @@ describe("model browser keyboard navigation", () => {
|
||||
view: { kind: "all" },
|
||||
providers,
|
||||
profiles,
|
||||
showProfilesSection: true,
|
||||
canCreateProfileRow: true,
|
||||
normalizedQuery: "",
|
||||
isSearchFocused: false,
|
||||
hasCustomRootBrowseContent: false,
|
||||
});
|
||||
expect(browse.kind).toBe("browse");
|
||||
if (browse.kind === "browse") {
|
||||
@@ -559,11 +475,8 @@ describe("model browser keyboard navigation", () => {
|
||||
view: { kind: "provider", providerId: "claude", providerLabel: "Claude Code" },
|
||||
providers,
|
||||
profiles,
|
||||
showProfilesSection: true,
|
||||
canCreateProfileRow: true,
|
||||
normalizedQuery: "opus",
|
||||
isSearchFocused: true,
|
||||
hasCustomRootBrowseContent: false,
|
||||
});
|
||||
expect(providerSearch.kind).toBe("modelList");
|
||||
if (providerSearch.kind === "modelList") {
|
||||
@@ -585,11 +498,8 @@ describe("model browser keyboard navigation", () => {
|
||||
view: { kind: "provider", providerId: "pi", providerLabel: "Pi" },
|
||||
providers: [{ id: "pi", label: "Pi", modelSelection: { kind: "error", message: "boom" } }],
|
||||
profiles: null,
|
||||
showProfilesSection: false,
|
||||
canCreateProfileRow: false,
|
||||
normalizedQuery: "",
|
||||
isSearchFocused: false,
|
||||
hasCustomRootBrowseContent: false,
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "providerError",
|
||||
@@ -603,11 +513,8 @@ describe("model browser keyboard navigation", () => {
|
||||
view: { kind: "all" },
|
||||
providers,
|
||||
profiles,
|
||||
showProfilesSection: true,
|
||||
canCreateProfileRow: true,
|
||||
normalizedQuery: "zzzz",
|
||||
isSearchFocused: true,
|
||||
hasCustomRootBrowseContent: false,
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "noSearchMatches",
|
||||
@@ -620,11 +527,8 @@ describe("model browser keyboard navigation", () => {
|
||||
view: { kind: "all" },
|
||||
providers,
|
||||
profiles: [reviewer],
|
||||
showProfilesSection: true,
|
||||
canCreateProfileRow: false,
|
||||
normalizedQuery: "",
|
||||
isSearchFocused: false,
|
||||
hasCustomRootBrowseContent: false,
|
||||
});
|
||||
|
||||
expect(
|
||||
@@ -649,11 +553,8 @@ describe("model browser keyboard navigation", () => {
|
||||
view: { kind: "all" },
|
||||
providers,
|
||||
profiles: [reviewer],
|
||||
showProfilesSection: true,
|
||||
canCreateProfileRow: false,
|
||||
normalizedQuery: "",
|
||||
isSearchFocused: false,
|
||||
hasCustomRootBrowseContent: false,
|
||||
});
|
||||
|
||||
expect(
|
||||
|
||||
@@ -12,16 +12,6 @@ export type ModelBrowserView =
|
||||
| { kind: "all" }
|
||||
| { kind: "provider"; providerId: string; providerLabel: string };
|
||||
|
||||
export function resolveModelBrowserScrolling({
|
||||
isNative,
|
||||
isCompact,
|
||||
}: {
|
||||
isNative: boolean;
|
||||
isCompact: boolean;
|
||||
}): "sheet" | "independent" {
|
||||
return isNative && isCompact ? "sheet" : "independent";
|
||||
}
|
||||
|
||||
/** A profile's model reference; used to match profiles back to model rows. */
|
||||
export interface ModelProfileRef {
|
||||
provider: string;
|
||||
@@ -83,19 +73,15 @@ export function resolveModelBrowserAllView<T extends SearchableProfileRow>({
|
||||
providers,
|
||||
profiles,
|
||||
normalizedQuery,
|
||||
isSearchFocused,
|
||||
}: {
|
||||
providers: ProviderSelectorProvider[];
|
||||
/** Profiles the search may offer; empty when the surface shows none. */
|
||||
profiles: readonly T[];
|
||||
normalizedQuery: string;
|
||||
isSearchFocused: boolean;
|
||||
}): ModelBrowserAllView<T> {
|
||||
if (!normalizedQuery && !isSearchFocused) {
|
||||
if (!normalizedQuery) {
|
||||
return { kind: "browse" };
|
||||
}
|
||||
const allRows = getAllProviderModelRows(providers);
|
||||
const rows = normalizedQuery ? filterAndRankModelRows(allRows, normalizedQuery) : allRows;
|
||||
const rows = filterAndRankModelRows(getAllProviderModelRows(providers), normalizedQuery);
|
||||
const matchedProfiles = filterAndRankProfileRows(profiles, normalizedQuery);
|
||||
if (rows.length === 0 && matchedProfiles.length === 0) {
|
||||
return { kind: "noSearchMatches" };
|
||||
@@ -206,11 +192,8 @@ export interface ModelBrowserProjectionInput<
|
||||
view: ModelBrowserView;
|
||||
providers: ProviderSelectorProvider[];
|
||||
profiles: readonly TProfile[] | null;
|
||||
showProfilesSection: boolean;
|
||||
canCreateProfileRow: boolean;
|
||||
normalizedQuery: string;
|
||||
isSearchFocused: boolean;
|
||||
hasCustomRootBrowseContent: boolean;
|
||||
}
|
||||
|
||||
function toProfileNavItems(rows: readonly NavigableProfileRow[]): ModelBrowserNavItem[] {
|
||||
@@ -233,30 +216,27 @@ function profileSectionToNavItems<TProfile extends NavigableProfileRow>(
|
||||
|
||||
function resolveBrowseProfileSection<TProfile extends NavigableProfileRow>(
|
||||
rows: readonly TProfile[] | null,
|
||||
showProfilesSection: boolean,
|
||||
canCreateProfileRow: boolean,
|
||||
): ModelBrowserProfileSection<TProfile> {
|
||||
if (!showProfilesSection || rows === null) return { kind: "none" };
|
||||
if (rows === null) return { kind: "none" };
|
||||
if (rows.length > 0) return { kind: "profiles", rows: [...rows] };
|
||||
return canCreateProfileRow ? { kind: "createProfile" } : { kind: "none" };
|
||||
}
|
||||
|
||||
function resolveProviderProfileSection<TProfile extends NavigableProfileRow>({
|
||||
providerProfiles,
|
||||
showProfilesSection,
|
||||
canCreateProfileRow,
|
||||
normalizedQuery,
|
||||
hasModelRows,
|
||||
}: {
|
||||
providerProfiles: readonly TProfile[] | null;
|
||||
showProfilesSection: boolean;
|
||||
canCreateProfileRow: boolean;
|
||||
normalizedQuery: string;
|
||||
hasModelRows: boolean;
|
||||
}): ModelBrowserProfileSection<TProfile> {
|
||||
if (!showProfilesSection || providerProfiles === null) return { kind: "none" };
|
||||
if (providerProfiles === null) return { kind: "none" };
|
||||
if (normalizedQuery.length === 0) {
|
||||
return resolveBrowseProfileSection(providerProfiles, true, canCreateProfileRow);
|
||||
return resolveBrowseProfileSection(providerProfiles, canCreateProfileRow);
|
||||
}
|
||||
const matched = filterAndRankProfileRows(providerProfiles, normalizedQuery);
|
||||
return matched.length > 0
|
||||
@@ -287,14 +267,12 @@ function resolveProviderProjection<TProfile extends NavigableProfileRow>({
|
||||
providerId,
|
||||
providers,
|
||||
profiles,
|
||||
showProfilesSection,
|
||||
canCreateProfileRow,
|
||||
normalizedQuery,
|
||||
}: {
|
||||
providerId: string;
|
||||
providers: ProviderSelectorProvider[];
|
||||
profiles: readonly TProfile[] | null;
|
||||
showProfilesSection: boolean;
|
||||
canCreateProfileRow: boolean;
|
||||
normalizedQuery: string;
|
||||
}): ModelBrowserProjection<TProfile> {
|
||||
@@ -315,7 +293,6 @@ function resolveProviderProjection<TProfile extends NavigableProfileRow>({
|
||||
profiles !== null ? profiles.filter((row) => row.provider === providerId) : null;
|
||||
const profileSection = resolveProviderProfileSection({
|
||||
providerProfiles,
|
||||
showProfilesSection,
|
||||
canCreateProfileRow,
|
||||
normalizedQuery,
|
||||
hasModelRows: modelRows.length > 0,
|
||||
@@ -346,7 +323,6 @@ export function resolveModelBrowserProjection<TProfile extends NavigableProfileR
|
||||
providerId: input.view.providerId,
|
||||
providers: input.providers,
|
||||
profiles: input.profiles,
|
||||
showProfilesSection: input.showProfilesSection,
|
||||
canCreateProfileRow: input.canCreateProfileRow,
|
||||
normalizedQuery: input.normalizedQuery,
|
||||
});
|
||||
@@ -354,9 +330,8 @@ export function resolveModelBrowserProjection<TProfile extends NavigableProfileR
|
||||
|
||||
const allView = resolveModelBrowserAllView({
|
||||
providers: input.providers,
|
||||
profiles: input.showProfilesSection && input.profiles ? input.profiles : [],
|
||||
profiles: input.profiles ?? [],
|
||||
normalizedQuery: input.normalizedQuery,
|
||||
isSearchFocused: input.isSearchFocused,
|
||||
});
|
||||
|
||||
if (allView.kind === "noSearchMatches") {
|
||||
@@ -381,25 +356,15 @@ export function resolveModelBrowserProjection<TProfile extends NavigableProfileR
|
||||
};
|
||||
}
|
||||
|
||||
const profileSection = resolveBrowseProfileSection(
|
||||
input.profiles,
|
||||
input.showProfilesSection,
|
||||
input.canCreateProfileRow,
|
||||
);
|
||||
const visibleProviders = input.hasCustomRootBrowseContent ? [] : input.providers;
|
||||
const hasResults =
|
||||
input.profiles !== null || input.providers.length > 0 || input.hasCustomRootBrowseContent;
|
||||
const profileSection = resolveBrowseProfileSection(input.profiles, input.canCreateProfileRow);
|
||||
|
||||
return {
|
||||
kind: "browse",
|
||||
profileSection,
|
||||
providers: visibleProviders,
|
||||
showProvidersHeading: input.showProfilesSection && input.profiles !== null,
|
||||
isEmpty: !hasResults,
|
||||
navItems: [
|
||||
...profileSectionToNavItems(profileSection),
|
||||
...toProviderNavItems(visibleProviders),
|
||||
],
|
||||
providers: input.providers,
|
||||
showProvidersHeading: input.profiles !== null,
|
||||
isEmpty: input.profiles === null && input.providers.length === 0,
|
||||
navItems: [...profileSectionToNavItems(profileSection), ...toProviderNavItems(input.providers)],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -27,10 +27,6 @@ import {
|
||||
type StyleProp,
|
||||
type ViewStyle,
|
||||
} from "react-native";
|
||||
import {
|
||||
FlatList as SheetFlatList,
|
||||
ScrollView as SheetScrollView,
|
||||
} from "@/components/ui/scroll-view";
|
||||
import { Gesture, GestureDetector } from "react-native-gesture-handler";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import {
|
||||
@@ -280,23 +276,15 @@ interface ModelBrowserProps {
|
||||
onEditProfile?: (profileId: string) => void;
|
||||
onRetryProvider?: (provider: AgentProvider) => void;
|
||||
isRetryingProvider?: boolean;
|
||||
scrolling?: "sheet" | "independent";
|
||||
/** Empty focused search shows all model rows instead of the browse root. */
|
||||
searchAllOnFocus?: boolean;
|
||||
/** Replaces provider rows only while the all-provider search is empty. */
|
||||
rootBrowseContent?: React.ReactNode;
|
||||
/** Hide the pinned Profiles section while still using rows for model matching. */
|
||||
showProfilesSection?: boolean;
|
||||
}
|
||||
|
||||
interface ModelBrowserContentProps extends Omit<ModelBrowserProps, "state" | "scrolling"> {
|
||||
interface ModelBrowserContentProps extends Omit<ModelBrowserProps, "state"> {
|
||||
serverId: string | null;
|
||||
view: ModelBrowserView;
|
||||
providers: ProviderSelectorProvider[];
|
||||
selectedProvider: string;
|
||||
selectedModel: string;
|
||||
searchQuery: string;
|
||||
isSearchFocused: boolean;
|
||||
profiles: AgentProfilePicker | null;
|
||||
explicitActiveKey: string | null;
|
||||
preferredActiveKey: string | null;
|
||||
@@ -305,9 +293,6 @@ interface ModelBrowserContentProps extends Omit<ModelBrowserProps, "state" | "sc
|
||||
registerKeyboardHandler: (handler: ((event: KeyboardInputEvent) => boolean) | null) => void;
|
||||
onShowAll: (fromProviderId?: string) => void;
|
||||
onDrillDown: (providerId: string, providerLabel: string) => void;
|
||||
scrolling: "sheet" | "independent";
|
||||
searchAllOnFocus: boolean;
|
||||
rootBrowseContent?: React.ReactNode;
|
||||
}
|
||||
|
||||
type ProviderGlyphTone = "muted" | "foreground";
|
||||
@@ -361,6 +346,38 @@ function resolveDesktopFixedHeight(
|
||||
);
|
||||
}
|
||||
|
||||
/** The selected model's full label and the shorter one a trigger shows. */
|
||||
export function useSelectedModelLabels({
|
||||
providers,
|
||||
selectedProvider,
|
||||
selectedModel,
|
||||
isLoading,
|
||||
}: {
|
||||
providers: ProviderSelectorProvider[];
|
||||
selectedProvider: string;
|
||||
selectedModel: string;
|
||||
isLoading: boolean;
|
||||
}): { selectedModelLabel: string; triggerLabel: string } {
|
||||
const { t } = useTranslation();
|
||||
const selectedModelLabel = useMemo(
|
||||
() =>
|
||||
resolveSelectedModelLabel({
|
||||
providers,
|
||||
selectedProvider,
|
||||
selectedModel,
|
||||
isLoading,
|
||||
}),
|
||||
[isLoading, providers, selectedModel, selectedProvider],
|
||||
);
|
||||
const triggerLabel = useMemo(() => {
|
||||
const isPlaceholder =
|
||||
selectedModelLabel === t("modelSelector.loading") ||
|
||||
selectedModelLabel === t("modelSelector.selectModel");
|
||||
return isPlaceholder ? selectedModelLabel : buildSelectedTriggerLabel(selectedModelLabel);
|
||||
}, [selectedModelLabel, t]);
|
||||
return { selectedModelLabel, triggerLabel };
|
||||
}
|
||||
|
||||
export function useModelBrowser({
|
||||
providers,
|
||||
selectedProvider,
|
||||
@@ -520,23 +537,12 @@ export function useModelBrowser({
|
||||
view,
|
||||
]);
|
||||
|
||||
const selectedModelLabel = useMemo(
|
||||
() =>
|
||||
resolveSelectedModelLabel({
|
||||
providers,
|
||||
selectedProvider,
|
||||
selectedModel,
|
||||
isLoading,
|
||||
}),
|
||||
[isLoading, providers, selectedModel, selectedProvider],
|
||||
);
|
||||
|
||||
const triggerLabel = useMemo(() => {
|
||||
const isPlaceholder =
|
||||
selectedModelLabel === t("modelSelector.loading") ||
|
||||
selectedModelLabel === t("modelSelector.selectModel");
|
||||
return isPlaceholder ? selectedModelLabel : buildSelectedTriggerLabel(selectedModelLabel);
|
||||
}, [selectedModelLabel, t]);
|
||||
const { selectedModelLabel, triggerLabel } = useSelectedModelLabels({
|
||||
providers,
|
||||
selectedProvider,
|
||||
selectedModel,
|
||||
isLoading,
|
||||
});
|
||||
|
||||
const desktopFixedHeight = useMemo(
|
||||
() => resolveDesktopFixedHeight(view, providers),
|
||||
@@ -701,9 +707,9 @@ function ModelBrowserPressable({
|
||||
);
|
||||
}
|
||||
|
||||
type ModelBrowserRowTone = "default" | "elevated" | "drillDown";
|
||||
export type ModelBrowserRowTone = "default" | "elevated" | "drillDown";
|
||||
|
||||
function ModelBrowserRow({
|
||||
export function ModelBrowserRow({
|
||||
label,
|
||||
description,
|
||||
leadingSlot,
|
||||
@@ -835,14 +841,17 @@ function ModelRowProfileAction({
|
||||
);
|
||||
}
|
||||
|
||||
function ModelRow({
|
||||
export function ModelRow({
|
||||
row,
|
||||
serverId,
|
||||
isSelected,
|
||||
isActive = false,
|
||||
showProviderLabel = false,
|
||||
tag,
|
||||
onPress,
|
||||
onFocus,
|
||||
activeItemRef,
|
||||
onActiveLayout,
|
||||
profiledRows,
|
||||
onCreateProfile,
|
||||
onEditProfile,
|
||||
@@ -853,8 +862,12 @@ function ModelRow({
|
||||
isSelected: boolean;
|
||||
isActive?: boolean;
|
||||
showProviderLabel?: boolean;
|
||||
/** A short note beside the label, such as the fold a search result comes from. */
|
||||
tag?: string;
|
||||
onPress: () => void;
|
||||
onFocus?: () => void;
|
||||
activeItemRef?: RefObject<View | null>;
|
||||
onActiveLayout?: () => void;
|
||||
profiledRows: AgentProfilePickerRowModel[];
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
|
||||
onEditProfile?: (profileId: string) => void;
|
||||
@@ -986,6 +999,8 @@ function ModelRow({
|
||||
accessibilitySelected={isSelected}
|
||||
navRow
|
||||
active={isActive}
|
||||
rowRef={isActive ? activeItemRef : undefined}
|
||||
onLayout={isActive ? onActiveLayout : undefined}
|
||||
testID={`model-row-${row.provider}-${row.modelId}`}
|
||||
>
|
||||
<View style={styles.browserRowContent}>
|
||||
@@ -994,6 +1009,13 @@ function ModelRow({
|
||||
<Text numberOfLines={1} style={styles.browserRowLabel}>
|
||||
{row.modelLabel}
|
||||
</Text>
|
||||
{tag ? (
|
||||
<View style={styles.browserRowTag}>
|
||||
<Text numberOfLines={1} style={styles.browserRowTagText}>
|
||||
{tag}
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
{description ? (
|
||||
<Text numberOfLines={1} style={styles.browserRowDescription}>
|
||||
{description}
|
||||
@@ -1355,7 +1377,7 @@ function GroupedProviderRows({
|
||||
);
|
||||
}
|
||||
|
||||
function IndependentScrollBoundary({ children }: { children: React.ReactElement }) {
|
||||
export function IndependentScrollBoundary({ children }: { children: React.ReactElement }) {
|
||||
// Prevent the parent sheet from cancelling Android's native scroll when the
|
||||
// finger crosses this viewport; receiving ACTION_UP is what preserves fling.
|
||||
const nativeScrollGesture = useMemo(
|
||||
@@ -1498,7 +1520,6 @@ function ModelRowList({
|
||||
onSelect,
|
||||
showProviderLabel = false,
|
||||
header,
|
||||
scrolling,
|
||||
profiledLookup,
|
||||
onCreateProfile,
|
||||
onEditProfile,
|
||||
@@ -1514,13 +1535,11 @@ function ModelRowList({
|
||||
onSelect: (provider: string, modelId: string) => void;
|
||||
showProviderLabel?: boolean;
|
||||
header?: React.ReactElement;
|
||||
scrolling: "sheet" | "independent";
|
||||
profiledLookup: Map<string, AgentProfilePickerRowModel[]>;
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
|
||||
onEditProfile?: (profileId: string) => void;
|
||||
onEditProfiles?: () => void;
|
||||
}) {
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
const { activeKey } = useContext(ModelBrowserNavContext);
|
||||
const renderItem = useCallback(
|
||||
({ item }: { item: ProviderSelectionModelRow }) => (
|
||||
@@ -1548,49 +1567,20 @@ function ModelRowList({
|
||||
showProviderLabel,
|
||||
],
|
||||
);
|
||||
const keyExtractor = useCallback((row: ProviderSelectionModelRow) => row.favoriteKey, []);
|
||||
|
||||
if (scrolling === "independent") {
|
||||
return (
|
||||
<IndependentModelList
|
||||
rows={rows}
|
||||
renderItem={renderItem}
|
||||
header={header}
|
||||
activeKey={activeKey}
|
||||
activeModelIndex={activeModelIndex}
|
||||
hasActiveHeaderItem={hasActiveHeaderItem}
|
||||
shouldRevealActive={shouldRevealActive}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (isCompact && isNative) {
|
||||
return (
|
||||
<SheetFlatList
|
||||
data={rows}
|
||||
extraData={activeKey}
|
||||
renderItem={renderItem}
|
||||
ListHeaderComponent={header}
|
||||
keyExtractor={keyExtractor}
|
||||
style={styles.virtualizedModelList}
|
||||
keyboardShouldPersistTaps="handled"
|
||||
showsVerticalScrollIndicator={false}
|
||||
contentContainerStyle={styles.virtualizedModelListContent}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View>
|
||||
{header}
|
||||
{rows.map((row) => (
|
||||
<View key={row.favoriteKey}>{renderItem({ item: row })}</View>
|
||||
))}
|
||||
</View>
|
||||
<IndependentModelList
|
||||
rows={rows}
|
||||
renderItem={renderItem}
|
||||
header={header}
|
||||
activeKey={activeKey}
|
||||
activeModelIndex={activeModelIndex}
|
||||
hasActiveHeaderItem={hasActiveHeaderItem}
|
||||
shouldRevealActive={shouldRevealActive}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function ProviderErrorEmptyState({
|
||||
export function ProviderErrorEmptyState({
|
||||
providerId,
|
||||
message,
|
||||
onRetryProvider,
|
||||
@@ -1618,6 +1608,54 @@ function ProviderErrorEmptyState({
|
||||
);
|
||||
}
|
||||
|
||||
export function ModelBrowserLoadingState() {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<View style={styles.emptyState}>
|
||||
<View style={styles.rowSpinner}>
|
||||
<ThemedLoadingSpinner size={ICON_SIZE.sm} uniProps={foregroundMutedMapping} />
|
||||
</View>
|
||||
<Text style={styles.emptyStateText}>{t("modelSelector.loadingShort")}</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export function ModelBrowserNoProviders() {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<View style={styles.emptyState} testID="model-browser-no-providers">
|
||||
<ThemedAlertTriangle size={ICON_SIZE.md} uniProps={foregroundMutedMapping} />
|
||||
<Text style={styles.emptyStateText}>{t("providerSelection.readiness.noProviders")}</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export function ModelSearchNoMatches({ query }: { query: string }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<View style={styles.emptyState} testID="model-search-empty">
|
||||
<ThemedSearch size={ICON_SIZE.md} uniProps={foregroundMutedMapping} />
|
||||
<Text style={styles.emptyStateText}>{t("modelSelector.noMatchesForQuery", { query })}</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
/** A muted label above a group of rows, with an optional action on its right. */
|
||||
export function ModelBrowserSectionHeading({
|
||||
title,
|
||||
action,
|
||||
}: {
|
||||
title: string;
|
||||
action?: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<View style={styles.sectionHeading}>
|
||||
<Text style={styles.sectionHeadingText}>{title}</Text>
|
||||
{action ? <View style={styles.sectionHeadingAction}>{action}</View> : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function ModelSearchEmptyState() {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
@@ -1714,8 +1752,6 @@ function ModelBrowserBrowseView({
|
||||
projection,
|
||||
activeNavIndex,
|
||||
listKey,
|
||||
rootBrowseContent,
|
||||
scrolling,
|
||||
onApplyProfile,
|
||||
onEditProfiles,
|
||||
onDrillDown,
|
||||
@@ -1724,8 +1760,6 @@ function ModelBrowserBrowseView({
|
||||
projection: Extract<ModelBrowserProjection<AgentProfilePickerRowModel>, { kind: "browse" }>;
|
||||
activeNavIndex: number;
|
||||
listKey: string;
|
||||
rootBrowseContent?: React.ReactNode;
|
||||
scrolling: "sheet" | "independent";
|
||||
onApplyProfile?: (profileId: string) => void;
|
||||
onEditProfiles?: () => void;
|
||||
onDrillDown: (providerId: string, providerLabel: string) => void;
|
||||
@@ -1757,27 +1791,26 @@ function ModelBrowserBrowseView({
|
||||
onApplyProfile={onApplyProfile}
|
||||
onEditProfiles={onEditProfiles}
|
||||
/>
|
||||
{rootBrowseContent ??
|
||||
(projection.providers.length > 0 ? (
|
||||
<View>
|
||||
{projection.showProvidersHeading ? (
|
||||
<View style={styles.sectionHeading}>
|
||||
<Text style={styles.sectionHeadingText}>{t("modelSelector.providers")}</Text>
|
||||
</View>
|
||||
) : null}
|
||||
<GroupedProviderRows
|
||||
providers={projection.providers}
|
||||
serverId={serverId}
|
||||
onDrillDown={onDrillDown}
|
||||
/>
|
||||
</View>
|
||||
) : null)}
|
||||
{projection.providers.length > 0 ? (
|
||||
<View>
|
||||
{projection.showProvidersHeading ? (
|
||||
<View style={styles.sectionHeading}>
|
||||
<Text style={styles.sectionHeadingText}>{t("modelSelector.providers")}</Text>
|
||||
</View>
|
||||
) : null}
|
||||
<GroupedProviderRows
|
||||
providers={projection.providers}
|
||||
serverId={serverId}
|
||||
onDrillDown={onDrillDown}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
{projection.isEmpty ? <ModelSearchEmptyState /> : null}
|
||||
</View>
|
||||
</ModelBrowserNavContext.Provider>
|
||||
);
|
||||
|
||||
return scrolling === "independent" ? (
|
||||
return (
|
||||
<IndependentProviderList
|
||||
scrollRef={browseScrollRef}
|
||||
onLayout={browseReveal.onViewportLayout}
|
||||
@@ -1785,24 +1818,6 @@ function ModelBrowserBrowseView({
|
||||
>
|
||||
{allProvidersContent}
|
||||
</IndependentProviderList>
|
||||
) : (
|
||||
<SheetScrollView
|
||||
ref={browseScrollRef}
|
||||
style={styles.virtualizedModelList}
|
||||
contentContainerStyle={[
|
||||
styles.virtualizedModelListContent,
|
||||
styles.virtualizedProviderListContent,
|
||||
]}
|
||||
onLayout={browseReveal.onViewportLayout}
|
||||
onScroll={browseReveal.onScroll}
|
||||
scrollEventThrottle={16}
|
||||
keyboardShouldPersistTaps="handled"
|
||||
keyboardDismissMode={MODEL_LIST_KEYBOARD_DISMISS_MODE}
|
||||
showsVerticalScrollIndicator={false}
|
||||
testID="compact-provider-list"
|
||||
>
|
||||
{allProvidersContent}
|
||||
</SheetScrollView>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1813,7 +1828,6 @@ function ModelBrowserContent({
|
||||
selectedProvider,
|
||||
selectedModel,
|
||||
searchQuery,
|
||||
isSearchFocused,
|
||||
profiles,
|
||||
explicitActiveKey,
|
||||
preferredActiveKey,
|
||||
@@ -1829,12 +1843,7 @@ function ModelBrowserContent({
|
||||
onDrillDown,
|
||||
onRetryProvider,
|
||||
isRetryingProvider = false,
|
||||
scrolling,
|
||||
searchAllOnFocus,
|
||||
rootBrowseContent,
|
||||
showProfilesSection = true,
|
||||
}: ModelBrowserContentProps) {
|
||||
const { t } = useTranslation();
|
||||
const hasHardwareKeyboard = useHardwareKeyboardPresent();
|
||||
const normalizedQuery = useMemo(() => normalizeSearchQuery(searchQuery), [searchQuery]);
|
||||
const profiledLookup = useMemo(
|
||||
@@ -1847,23 +1856,10 @@ function ModelBrowserContent({
|
||||
view,
|
||||
providers,
|
||||
profiles: profiles?.rows ?? null,
|
||||
showProfilesSection,
|
||||
canCreateProfileRow: Boolean(onEditProfiles),
|
||||
normalizedQuery,
|
||||
isSearchFocused: searchAllOnFocus && isSearchFocused,
|
||||
hasCustomRootBrowseContent: rootBrowseContent != null,
|
||||
}),
|
||||
[
|
||||
isSearchFocused,
|
||||
normalizedQuery,
|
||||
onEditProfiles,
|
||||
profiles,
|
||||
providers,
|
||||
rootBrowseContent,
|
||||
searchAllOnFocus,
|
||||
showProfilesSection,
|
||||
view,
|
||||
],
|
||||
[normalizedQuery, onEditProfiles, profiles, providers, view],
|
||||
);
|
||||
const { navItems } = projection;
|
||||
const activeKey = useMemo(
|
||||
@@ -1940,14 +1936,7 @@ function ModelBrowserContent({
|
||||
|
||||
let content: React.ReactNode;
|
||||
if (projection.kind === "providerLoading") {
|
||||
content = (
|
||||
<View style={styles.emptyState}>
|
||||
<View style={styles.rowSpinner}>
|
||||
<ThemedLoadingSpinner size={ICON_SIZE.sm} uniProps={foregroundMutedMapping} />
|
||||
</View>
|
||||
<Text style={styles.emptyStateText}>{t("modelSelector.loadingShort")}</Text>
|
||||
</View>
|
||||
);
|
||||
content = <ModelBrowserLoadingState />;
|
||||
} else if (projection.kind === "providerError") {
|
||||
content = (
|
||||
<ProviderErrorEmptyState
|
||||
@@ -1960,14 +1949,7 @@ function ModelBrowserContent({
|
||||
} else if (projection.kind === "empty") {
|
||||
content = <ModelSearchEmptyState />;
|
||||
} else if (projection.kind === "noSearchMatches") {
|
||||
content = (
|
||||
<View style={styles.emptyState} testID="model-search-empty">
|
||||
<ThemedSearch size={ICON_SIZE.md} uniProps={foregroundMutedMapping} />
|
||||
<Text style={styles.emptyStateText}>
|
||||
{t("modelSelector.noMatchesForQuery", { query: searchQuery.trim() })}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
content = <ModelSearchNoMatches query={searchQuery.trim()} />;
|
||||
} else if (projection.kind === "modelList") {
|
||||
content = (
|
||||
<ModelRowList
|
||||
@@ -1981,7 +1963,6 @@ function ModelBrowserContent({
|
||||
onSelect={onSelect}
|
||||
showProviderLabel={projection.showProviderLabel}
|
||||
header={listHeader}
|
||||
scrolling={scrolling}
|
||||
profiledLookup={profiledLookup}
|
||||
onCreateProfile={onCreateProfile}
|
||||
onEditProfile={onEditProfile}
|
||||
@@ -1995,8 +1976,6 @@ function ModelBrowserContent({
|
||||
projection={projection}
|
||||
activeNavIndex={activeNavIndex}
|
||||
listKey={browseListKey}
|
||||
rootBrowseContent={rootBrowseContent}
|
||||
scrolling={scrolling}
|
||||
onApplyProfile={onApplyProfile}
|
||||
onEditProfiles={onEditProfiles}
|
||||
onDrillDown={onDrillDown}
|
||||
@@ -2018,10 +1997,6 @@ export function ModelBrowser({
|
||||
onEditProfile,
|
||||
onRetryProvider,
|
||||
isRetryingProvider = false,
|
||||
scrolling = "sheet",
|
||||
searchAllOnFocus = false,
|
||||
rootBrowseContent,
|
||||
showProfilesSection,
|
||||
}: ModelBrowserProps) {
|
||||
return (
|
||||
<ModelBrowserContent
|
||||
@@ -2031,7 +2006,6 @@ export function ModelBrowser({
|
||||
selectedProvider={state.selectedProvider}
|
||||
selectedModel={state.selectedModel}
|
||||
searchQuery={state.searchQuery}
|
||||
isSearchFocused={state.isSearchFocused}
|
||||
profiles={state.profiles}
|
||||
explicitActiveKey={state.explicitActiveKey}
|
||||
preferredActiveKey={state.preferredActiveKey}
|
||||
@@ -2047,10 +2021,6 @@ export function ModelBrowser({
|
||||
onDrillDown={state.drillDown}
|
||||
onRetryProvider={onRetryProvider}
|
||||
isRetryingProvider={isRetryingProvider}
|
||||
scrolling={scrolling}
|
||||
searchAllOnFocus={searchAllOnFocus}
|
||||
rootBrowseContent={rootBrowseContent}
|
||||
showProfilesSection={showProfilesSection}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -2144,6 +2114,17 @@ const styles = StyleSheet.create((theme) => ({
|
||||
color: theme.colors.foregroundMuted,
|
||||
flexShrink: 0,
|
||||
},
|
||||
browserRowTag: {
|
||||
alignSelf: "center",
|
||||
flexShrink: 0,
|
||||
paddingHorizontal: theme.spacing[1],
|
||||
borderRadius: theme.borderRadius.base,
|
||||
backgroundColor: theme.colors.surface2,
|
||||
},
|
||||
browserRowTagText: {
|
||||
fontSize: theme.fontSize.sm,
|
||||
color: theme.colors.foregroundMuted,
|
||||
},
|
||||
browserRowDescription: {
|
||||
fontSize: theme.fontSize.sm,
|
||||
color: theme.colors.foregroundMuted,
|
||||
|
||||
@@ -13,6 +13,8 @@ interface SettingsDetailRowProps {
|
||||
hintStatus?: SettingsRowHintStatus;
|
||||
/** What the detail is set to, so the row says it without being opened. */
|
||||
summary?: string;
|
||||
/** An icon drawn directly before the summary text. */
|
||||
summaryLeading?: ReactNode;
|
||||
onPress: () => void;
|
||||
/** A row that cannot be opened keeps its summary and drops the chevron. */
|
||||
disabled?: boolean;
|
||||
|
||||
@@ -9,6 +9,8 @@ import { settingsStyles } from "@/styles/settings";
|
||||
|
||||
interface SettingsSectionProps {
|
||||
title: string;
|
||||
/** An icon before the section title. */
|
||||
leading?: ReactNode;
|
||||
/**
|
||||
* What this section is for. Renders as an info tooltip on the header; a
|
||||
* paragraph between the header and the card is wrong (docs/design.md §7).
|
||||
@@ -38,6 +40,7 @@ interface SettingsSectionProps {
|
||||
*/
|
||||
export function SettingsSection({
|
||||
title,
|
||||
leading,
|
||||
info,
|
||||
link,
|
||||
trailing,
|
||||
@@ -54,6 +57,7 @@ export function SettingsSection({
|
||||
<View style={sectionStyle} testID={testID}>
|
||||
<View style={styles.header}>
|
||||
<View style={styles.titleRow}>
|
||||
{leading}
|
||||
<Text style={settingsStyles.sectionHeaderTitle}>{title}</Text>
|
||||
{info ? (
|
||||
<SettingsInfoTip
|
||||
|
||||
@@ -56,13 +56,25 @@ interface AppSettingsRowProps extends Omit<SettingsRowProps, "hint">, AppRowExtr
|
||||
hint?: ReactNode;
|
||||
}
|
||||
|
||||
export function SettingsCard({ children, testID }: { children: ReactNode; testID?: string }) {
|
||||
/** Lets a card and its rows shrink below their content, so a list inside can scroll. */
|
||||
const SHRINK = { flexShrink: 1, minHeight: 0 } as const;
|
||||
|
||||
export function SettingsCard({
|
||||
children,
|
||||
testID,
|
||||
shrink = false,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
testID?: string;
|
||||
/** The card shrinks to fit a parent with a bounded height, and a list inside it scrolls. */
|
||||
shrink?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<View style={settingsStyles.card} testID={testID}>
|
||||
<View style={[settingsStyles.card, shrink && SHRINK]} testID={testID}>
|
||||
{Children.toArray(children).map((child, index) => (
|
||||
<View
|
||||
key={isValidElement(child) ? child.key : index}
|
||||
style={index ? settingsStyles.rowBorder : undefined}
|
||||
style={[index ? settingsStyles.rowBorder : undefined, shrink && SHRINK]}
|
||||
>
|
||||
{child}
|
||||
</View>
|
||||
|
||||
@@ -34,6 +34,8 @@ export interface SettingsRowHeaderProps {
|
||||
hintStatus?: SettingsRowHintStatus;
|
||||
/** A short status shown before the chevron. */
|
||||
summary?: string;
|
||||
/** An icon drawn directly before the summary text, such as a provider glyph beside a model name. */
|
||||
summaryLeading?: ReactNode;
|
||||
onPress: () => void;
|
||||
disabled?: boolean;
|
||||
/** Turns the chevron down, for a row whose children are revealed in place. */
|
||||
@@ -72,6 +74,7 @@ export function SettingsRowHeader({
|
||||
hint,
|
||||
hintStatus,
|
||||
summary,
|
||||
summaryLeading,
|
||||
onPress,
|
||||
disabled,
|
||||
expanded = false,
|
||||
@@ -132,7 +135,13 @@ export function SettingsRowHeader({
|
||||
<ControlSizeProvider size={layout.controlSize}>{control}</ControlSizeProvider>
|
||||
</View>
|
||||
) : null}
|
||||
<RowTrailing hinted={hinted} external={external} hovered={hovered} summary={summary} />
|
||||
<RowTrailing
|
||||
hinted={hinted}
|
||||
external={external}
|
||||
hovered={hovered}
|
||||
summary={summary}
|
||||
summaryLeading={summaryLeading}
|
||||
/>
|
||||
{external || disabled ? null : (
|
||||
<View style={chevronStyle} {...HIDDEN_FROM_ASSISTIVE_TECH}>
|
||||
<ThemedChevron
|
||||
@@ -157,17 +166,22 @@ function RowTrailing({
|
||||
external,
|
||||
hovered,
|
||||
summary,
|
||||
summaryLeading,
|
||||
}: {
|
||||
hinted: boolean;
|
||||
external: boolean;
|
||||
hovered: boolean;
|
||||
summary: string | undefined;
|
||||
summaryLeading: ReactNode;
|
||||
}) {
|
||||
const style = hinted ? styles.hintedTrailing : styles.labelTrailing;
|
||||
return (
|
||||
<View style={[style, styles.passThrough]} {...HIDDEN_FROM_ASSISTIVE_TECH}>
|
||||
{/* Drawn the same as a section header's docs link, so the two read as one thing. */}
|
||||
{external ? <ExternalLinkLabel hovered={hovered}>{summary}</ExternalLinkLabel> : null}
|
||||
{!external && summaryLeading && summary ? (
|
||||
<View style={styles.summaryLeading}>{summaryLeading}</View>
|
||||
) : null}
|
||||
{!external && summary ? (
|
||||
<Text style={styles.summary} numberOfLines={1}>
|
||||
{summary}
|
||||
@@ -293,6 +307,11 @@ const styles = StyleSheet.create((theme) => ({
|
||||
borderRadius: theme.borderRadius.sm,
|
||||
backgroundColor: theme.colors.surface2,
|
||||
},
|
||||
summaryLeading: {
|
||||
marginRight: theme.spacing[1.5],
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
summary: {
|
||||
flexShrink: 1,
|
||||
color: theme.colors.foregroundMuted,
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
import { Check } from "lucide-react-native";
|
||||
import { useCallback, useMemo, type ReactNode } from "react";
|
||||
import { View, type StyleProp, type ViewStyle } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import { PressHighlight } from "./press-highlight";
|
||||
|
||||
const ThemedCheck = withUnistyles(Check);
|
||||
const checkedIconMapping = (theme: Theme) => ({ color: theme.colors.accentForeground });
|
||||
|
||||
/** The checkbox glyph. A row that toggles it is a `CheckboxRow`. */
|
||||
export function Checkbox({ checked }: { checked: boolean }) {
|
||||
return (
|
||||
<View style={checked ? styles.boxChecked : styles.box}>
|
||||
{checked ? <ThemedCheck size={14} uniProps={checkedIconMapping} /> : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
interface HoverState {
|
||||
hovered?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* A row that toggles a checkbox: the whole row is the hit area, it announces its checked state,
|
||||
* and Space toggles it on web. The caller lays out the row and passes what follows the box.
|
||||
*/
|
||||
export function CheckboxRow({
|
||||
checked,
|
||||
onToggle,
|
||||
accessibilityLabel,
|
||||
disabled = false,
|
||||
style,
|
||||
testID,
|
||||
children,
|
||||
}: {
|
||||
checked: boolean;
|
||||
onToggle: () => void;
|
||||
accessibilityLabel: string;
|
||||
disabled?: boolean;
|
||||
style?: StyleProp<ViewStyle>;
|
||||
testID?: string;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const accessibilityState = useMemo(() => ({ checked, disabled }), [checked, disabled]);
|
||||
const rowStyle = useCallback(
|
||||
({ hovered }: HoverState) => [style, hovered && !disabled ? styles.hovered : null],
|
||||
[disabled, style],
|
||||
);
|
||||
const keyProps = useMemo(() => {
|
||||
if (!isWeb || disabled) return {};
|
||||
return {
|
||||
// React Native Web's Pressable activates Space only for role="button", not checkbox.
|
||||
onKeyDown: (event: { key?: string; preventDefault?: () => void }) => {
|
||||
if (event.key === " " || event.key === "Spacebar") {
|
||||
event.preventDefault?.();
|
||||
onToggle();
|
||||
}
|
||||
},
|
||||
};
|
||||
}, [disabled, onToggle]);
|
||||
|
||||
return (
|
||||
<PressHighlight
|
||||
style={rowStyle}
|
||||
highlightStyle={styles.pressed}
|
||||
onPress={onToggle}
|
||||
disabled={disabled}
|
||||
accessibilityRole="checkbox"
|
||||
accessibilityLabel={accessibilityLabel}
|
||||
accessibilityState={accessibilityState}
|
||||
aria-checked={checked}
|
||||
testID={testID}
|
||||
{...keyProps}
|
||||
>
|
||||
<Checkbox checked={checked} />
|
||||
{children}
|
||||
</PressHighlight>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
box: {
|
||||
width: 18,
|
||||
height: 18,
|
||||
flexShrink: 0,
|
||||
borderRadius: theme.borderRadius.sm,
|
||||
borderWidth: 1,
|
||||
borderColor: theme.colors.border,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
boxChecked: {
|
||||
width: 18,
|
||||
height: 18,
|
||||
flexShrink: 0,
|
||||
borderRadius: theme.borderRadius.sm,
|
||||
borderWidth: 1,
|
||||
borderColor: theme.colors.accent,
|
||||
backgroundColor: theme.colors.accent,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
hovered: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
},
|
||||
pressed: {
|
||||
backgroundColor: theme.colors.surface3,
|
||||
},
|
||||
}));
|
||||
@@ -149,8 +149,8 @@ export interface ComboboxProps {
|
||||
/** Where focus goes when the picker closes. Defaults to whatever had focus when it opened. */
|
||||
restoreFocusRef?: React.RefObject<unknown>;
|
||||
/**
|
||||
* Keys custom `children` handle while the combobox is the top overlay. Escape always
|
||||
* closes the combobox. Return true from `onKeyDown` to claim the key.
|
||||
* Keys custom `children` handle while the combobox is the top overlay. Return true from
|
||||
* `onKeyDown` to claim the key. Escape closes the combobox unless `onKeyDown` claims it.
|
||||
*/
|
||||
keyboard?: SheetKeyboard;
|
||||
children?: ReactNode;
|
||||
@@ -1735,12 +1735,13 @@ export function Combobox({
|
||||
const handleOverlayKeyDown = useCallback(
|
||||
(event: KeyboardInputEvent) => {
|
||||
if (keyboard) {
|
||||
if (event.key === "Escape") {
|
||||
// The children get first refusal on Escape, so a search can clear before the picker closes.
|
||||
if (event.key === "Escape" && !keyboard.onKeyDown(event)) {
|
||||
event.preventDefault();
|
||||
handleClose();
|
||||
return true;
|
||||
}
|
||||
if (!keyboard.onKeyDown(event)) return false;
|
||||
if (event.key !== "Escape" && !keyboard.onKeyDown(event)) return false;
|
||||
event.preventDefault();
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -153,7 +153,7 @@ const styles = StyleSheet.create((theme) => ({
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
padding: 0,
|
||||
height: 20,
|
||||
minHeight: 20,
|
||||
// The browser's focus ring would sit inside the field's own focus border.
|
||||
// `outlineWidth` is typed on ViewStyle since RN 0.81 and is a no-op on
|
||||
// native, so this needs neither a cast nor a platform branch.
|
||||
|
||||
@@ -31,6 +31,8 @@ interface SegmentedControlProps<T extends string> {
|
||||
hideLabels?: boolean;
|
||||
/** Share the container's width equally between the segments, for a control that heads a surface. */
|
||||
fill?: boolean;
|
||||
/** Let the segments run onto more lines when they do not fit on one. */
|
||||
wrap?: boolean;
|
||||
style?: StyleProp<ViewStyle>;
|
||||
testID?: string;
|
||||
}
|
||||
@@ -57,6 +59,7 @@ export function SegmentedControl<T extends string>({
|
||||
size: sizeProp,
|
||||
hideLabels = false,
|
||||
fill = false,
|
||||
wrap = false,
|
||||
style,
|
||||
testID,
|
||||
}: SegmentedControlProps<T>) {
|
||||
@@ -72,8 +75,8 @@ export function SegmentedControl<T extends string>({
|
||||
const iconSize = controlIconSize[size];
|
||||
|
||||
const containerStyle = useMemo(
|
||||
() => [styles.container, containerSizeStyle, style],
|
||||
[containerSizeStyle, style],
|
||||
() => [styles.container, containerSizeStyle, wrap && styles.containerWrap, style],
|
||||
[containerSizeStyle, style, wrap],
|
||||
);
|
||||
|
||||
return (
|
||||
@@ -191,6 +194,9 @@ const styles = StyleSheet.create((theme) => {
|
||||
backgroundColor: "transparent",
|
||||
gap: theme.spacing[1],
|
||||
},
|
||||
containerWrap: {
|
||||
flexWrap: "wrap",
|
||||
},
|
||||
containerSm: {
|
||||
...geometry.segmentedContainerSm,
|
||||
},
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { resolveSliderFraction, resolveSliderIndexFromX } from "./stepped-slider-math";
|
||||
|
||||
describe("stepped slider math", () => {
|
||||
it("computes normalized stop positions across the track", () => {
|
||||
expect(resolveSliderFraction(0, 5)).toBe(0);
|
||||
expect(resolveSliderFraction(2, 5)).toBe(0.5);
|
||||
expect(resolveSliderFraction(4, 5)).toBe(1);
|
||||
expect(resolveSliderFraction(-1, 5)).toBe(0);
|
||||
expect(resolveSliderFraction(9, 5)).toBe(1);
|
||||
expect(resolveSliderFraction(0, 1)).toBe(0);
|
||||
});
|
||||
|
||||
it("snaps drag positions to the nearest stop and clamps out-of-bounds drags", () => {
|
||||
expect(resolveSliderIndexFromX(-20, 200, 5)).toBe(0);
|
||||
expect(resolveSliderIndexFromX(0, 200, 5)).toBe(0);
|
||||
expect(resolveSliderIndexFromX(24, 200, 5)).toBe(0);
|
||||
expect(resolveSliderIndexFromX(26, 200, 5)).toBe(1);
|
||||
expect(resolveSliderIndexFromX(100, 200, 5)).toBe(2);
|
||||
expect(resolveSliderIndexFromX(190, 200, 5)).toBe(4);
|
||||
expect(resolveSliderIndexFromX(260, 200, 5)).toBe(4);
|
||||
expect(resolveSliderIndexFromX(50, 0, 5)).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* Pure geometry for `SteppedSlider`: maps between discrete stop indices and normalized track
|
||||
* positions so tap targets, pan scrubbing, and visual stops agree to the pixel.
|
||||
*/
|
||||
|
||||
export function resolveSliderFraction(index: number, count: number): number {
|
||||
if (count <= 1) return 0;
|
||||
return clamp(index, 0, count - 1) / (count - 1);
|
||||
}
|
||||
|
||||
export function resolveSliderIndexFromX(x: number, trackWidth: number, count: number): number {
|
||||
if (count <= 1 || trackWidth <= 0) return 0;
|
||||
const fraction = clamp(x / trackWidth, 0, 1);
|
||||
return Math.round(fraction * (count - 1));
|
||||
}
|
||||
|
||||
function clamp(value: number, min: number, max: number): number {
|
||||
return Math.min(Math.max(value, min), max);
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
import { useCallback, useMemo, useRef, useState } from "react";
|
||||
import { Pressable, Text, View, type LayoutChangeEvent } from "react-native";
|
||||
import { Gesture, GestureDetector } from "react-native-gesture-handler";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { isNative } from "@/constants/platform";
|
||||
import { resolveSliderFraction, resolveSliderIndexFromX } from "./stepped-slider-math";
|
||||
|
||||
const TRACK_HEIGHT = 28;
|
||||
const TRACK_INSET = 2;
|
||||
const THUMB_SIZE = TRACK_HEIGHT - TRACK_INSET * 2;
|
||||
const THUMB_RADIUS = THUMB_SIZE / 2;
|
||||
/** Matches `TRACK_HEIGHT / 2` so the circular thumb stays concentric with the capsule and fill caps. */
|
||||
const TRAVEL_EDGE = TRACK_INSET + THUMB_RADIUS;
|
||||
const DOT_SIZE = 6;
|
||||
const DOT_RADIUS = DOT_SIZE / 2;
|
||||
|
||||
export interface SteppedSliderOption<T extends string> {
|
||||
value: T;
|
||||
label: string;
|
||||
testID?: string;
|
||||
}
|
||||
|
||||
interface SteppedSliderProps<T extends string> {
|
||||
options: readonly SteppedSliderOption<T>[];
|
||||
value: T | null;
|
||||
onValueChange: (value: T) => void;
|
||||
/** Fires while scrubbing so a header label can preview the stop before release. */
|
||||
onPreviewChange?: (value: T | null) => void;
|
||||
disabled?: boolean;
|
||||
accessibilityLabel?: string;
|
||||
testID?: string;
|
||||
}
|
||||
|
||||
function triggerSelectionHaptic() {
|
||||
if (!isNative) return;
|
||||
void Haptics.selectionAsync().catch(() => {});
|
||||
}
|
||||
|
||||
/**
|
||||
* A thick capsule slider with discrete stop dots, matching Paseo's Switch proportions. Tapping any
|
||||
* stop picks it immediately; dragging horizontally scrubs across stops without blocking vertical
|
||||
* sheet scrolling.
|
||||
*/
|
||||
export function SteppedSlider<T extends string>({
|
||||
options,
|
||||
value,
|
||||
onValueChange,
|
||||
onPreviewChange,
|
||||
disabled = false,
|
||||
accessibilityLabel,
|
||||
testID,
|
||||
}: SteppedSliderProps<T>) {
|
||||
const travelWidthRef = useRef(0);
|
||||
const [scrubIndex, setScrubIndex] = useState<number | null>(null);
|
||||
const scrubIndexRef = useRef<number | null>(null);
|
||||
|
||||
const selectedIndex = Math.max(
|
||||
0,
|
||||
options.findIndex((option) => option.value === value),
|
||||
);
|
||||
const activeIndex = scrubIndex ?? selectedIndex;
|
||||
const fraction = resolveSliderFraction(activeIndex, options.length);
|
||||
|
||||
const handleTravelLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
travelWidthRef.current = event.nativeEvent.layout.width;
|
||||
}, []);
|
||||
|
||||
const updateScrubFromX = useCallback(
|
||||
(x: number) => {
|
||||
const nextIndex = resolveSliderIndexFromX(
|
||||
x - TRAVEL_EDGE,
|
||||
travelWidthRef.current,
|
||||
options.length,
|
||||
);
|
||||
if (nextIndex === scrubIndexRef.current) return;
|
||||
scrubIndexRef.current = nextIndex;
|
||||
setScrubIndex(nextIndex);
|
||||
const option = options[nextIndex];
|
||||
if (option) {
|
||||
onPreviewChange?.(option.value);
|
||||
triggerSelectionHaptic();
|
||||
}
|
||||
},
|
||||
[onPreviewChange, options],
|
||||
);
|
||||
|
||||
const commitScrub = useCallback(() => {
|
||||
const finalIndex = scrubIndexRef.current;
|
||||
scrubIndexRef.current = null;
|
||||
setScrubIndex(null);
|
||||
onPreviewChange?.(null);
|
||||
if (finalIndex === null) return;
|
||||
const option = options[finalIndex];
|
||||
if (option && option.value !== value) {
|
||||
onValueChange(option.value);
|
||||
}
|
||||
}, [onPreviewChange, onValueChange, options, value]);
|
||||
|
||||
const cancelScrub = useCallback(() => {
|
||||
scrubIndexRef.current = null;
|
||||
setScrubIndex(null);
|
||||
onPreviewChange?.(null);
|
||||
}, [onPreviewChange]);
|
||||
|
||||
const panGesture = useMemo(
|
||||
() =>
|
||||
Gesture.Pan()
|
||||
.enabled(!disabled && options.length > 1)
|
||||
.activeOffsetX([-6, 6])
|
||||
.failOffsetY([-12, 12])
|
||||
.runOnJS(true)
|
||||
.onBegin((event) => {
|
||||
updateScrubFromX(event.x);
|
||||
})
|
||||
.onUpdate((event) => {
|
||||
updateScrubFromX(event.x);
|
||||
})
|
||||
.onEnd(() => {
|
||||
commitScrub();
|
||||
})
|
||||
.onFinalize((_, success) => {
|
||||
if (!success) cancelScrub();
|
||||
}),
|
||||
[cancelScrub, commitScrub, disabled, options.length, updateScrubFromX],
|
||||
);
|
||||
|
||||
const handleSelectOption = useCallback(
|
||||
(optionValue: T) => {
|
||||
if (disabled || optionValue === value) return;
|
||||
triggerSelectionHaptic();
|
||||
onValueChange(optionValue);
|
||||
},
|
||||
[disabled, onValueChange, value],
|
||||
);
|
||||
|
||||
const containerStyle = useMemo(() => [styles.container, disabled && styles.disabled], [disabled]);
|
||||
const fillAnchorStyle = useMemo(
|
||||
() => [styles.fillAnchor, { width: `${fraction * 100}%` as const }],
|
||||
[fraction],
|
||||
);
|
||||
const thumbStyle = useMemo(
|
||||
() => [styles.thumb, { left: `${fraction * 100}%` as const }],
|
||||
[fraction],
|
||||
);
|
||||
|
||||
const firstOption = options[0];
|
||||
const lastOption = options[options.length - 1];
|
||||
|
||||
return (
|
||||
<View style={containerStyle} accessibilityLabel={accessibilityLabel} testID={testID}>
|
||||
<GestureDetector gesture={panGesture}>
|
||||
<View style={styles.trackBand}>
|
||||
<View style={styles.capsule}>
|
||||
<View style={styles.travelArea} onLayout={handleTravelLayout} pointerEvents="none">
|
||||
{activeIndex > 0 ? (
|
||||
<View style={fillAnchorStyle}>
|
||||
<View style={styles.trackFill} />
|
||||
</View>
|
||||
) : null}
|
||||
{options.map((option, index) => (
|
||||
<StopDot
|
||||
key={option.value}
|
||||
fraction={resolveSliderFraction(index, options.length)}
|
||||
filled={index < activeIndex}
|
||||
/>
|
||||
))}
|
||||
<View style={thumbStyle} />
|
||||
</View>
|
||||
</View>
|
||||
<View style={styles.hitRow}>
|
||||
{options.map((option, index) => (
|
||||
<StopHitTarget
|
||||
key={option.value}
|
||||
option={option}
|
||||
selected={index === activeIndex}
|
||||
disabled={disabled}
|
||||
onSelect={handleSelectOption}
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
</GestureDetector>
|
||||
{firstOption && lastOption && firstOption.value !== lastOption.value ? (
|
||||
<View style={styles.endpoints} pointerEvents="none">
|
||||
<Text style={styles.endpointLabel} numberOfLines={1}>
|
||||
{firstOption.label}
|
||||
</Text>
|
||||
<Text style={styles.endpointLabel} numberOfLines={1}>
|
||||
{lastOption.label}
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function StopDot({ fraction, filled }: { fraction: number; filled: boolean }) {
|
||||
const style = useMemo(
|
||||
() => [
|
||||
styles.dot,
|
||||
filled ? styles.dotFilled : styles.dotIdle,
|
||||
{ left: `${fraction * 100}%` as const },
|
||||
],
|
||||
[filled, fraction],
|
||||
);
|
||||
return <View style={style} pointerEvents="none" />;
|
||||
}
|
||||
|
||||
function StopHitTarget<T extends string>({
|
||||
option,
|
||||
selected,
|
||||
disabled,
|
||||
onSelect,
|
||||
}: {
|
||||
option: SteppedSliderOption<T>;
|
||||
selected: boolean;
|
||||
disabled: boolean;
|
||||
onSelect: (value: T) => void;
|
||||
}) {
|
||||
const handlePress = useCallback(() => onSelect(option.value), [onSelect, option.value]);
|
||||
const accessibilityState = useMemo(() => ({ selected, disabled }), [disabled, selected]);
|
||||
return (
|
||||
<Pressable
|
||||
onPress={handlePress}
|
||||
disabled={disabled}
|
||||
accessibilityRole="radio"
|
||||
accessibilityLabel={option.label}
|
||||
accessibilityState={accessibilityState}
|
||||
aria-selected={selected}
|
||||
style={styles.hitTarget}
|
||||
testID={option.testID}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
container: {
|
||||
gap: theme.spacing[1],
|
||||
},
|
||||
disabled: {
|
||||
opacity: theme.opacity[50],
|
||||
},
|
||||
trackBand: {
|
||||
height: 36,
|
||||
justifyContent: "center",
|
||||
},
|
||||
capsule: {
|
||||
height: TRACK_HEIGHT,
|
||||
borderRadius: TRACK_HEIGHT / 2,
|
||||
backgroundColor: theme.colors.surface3,
|
||||
overflow: "hidden",
|
||||
paddingHorizontal: TRAVEL_EDGE,
|
||||
},
|
||||
travelArea: {
|
||||
flex: 1,
|
||||
justifyContent: "center",
|
||||
},
|
||||
fillAnchor: {
|
||||
position: "absolute",
|
||||
left: 0,
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
},
|
||||
trackFill: {
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
left: -TRAVEL_EDGE,
|
||||
right: -TRAVEL_EDGE,
|
||||
borderRadius: TRACK_HEIGHT / 2,
|
||||
backgroundColor: theme.colors.accent,
|
||||
},
|
||||
dot: {
|
||||
position: "absolute",
|
||||
width: DOT_SIZE,
|
||||
height: DOT_SIZE,
|
||||
borderRadius: DOT_RADIUS,
|
||||
marginLeft: -DOT_RADIUS,
|
||||
},
|
||||
dotFilled: {
|
||||
backgroundColor: theme.colors.accentForeground,
|
||||
opacity: 0.5,
|
||||
},
|
||||
dotIdle: {
|
||||
backgroundColor: theme.colors.foregroundExtraMuted,
|
||||
opacity: 0.75,
|
||||
},
|
||||
thumb: {
|
||||
position: "absolute",
|
||||
width: THUMB_SIZE,
|
||||
height: THUMB_SIZE,
|
||||
borderRadius: THUMB_RADIUS,
|
||||
marginLeft: -THUMB_RADIUS,
|
||||
backgroundColor: theme.colors.palette.white,
|
||||
shadowColor: "rgba(0, 0, 0, 0.25)",
|
||||
shadowOffset: { width: 0, height: 1 },
|
||||
shadowRadius: 2,
|
||||
shadowOpacity: 1,
|
||||
elevation: 2,
|
||||
},
|
||||
hitRow: {
|
||||
position: "absolute",
|
||||
left: 0,
|
||||
right: 0,
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
flexDirection: "row",
|
||||
},
|
||||
hitTarget: {
|
||||
flex: 1,
|
||||
height: "100%",
|
||||
},
|
||||
endpoints: {
|
||||
flexDirection: "row",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center",
|
||||
paddingHorizontal: 2,
|
||||
},
|
||||
endpointLabel: {
|
||||
fontSize: theme.fontSize.sm,
|
||||
color: theme.colors.foregroundMuted,
|
||||
},
|
||||
}));
|
||||
@@ -0,0 +1,424 @@
|
||||
import { useCallback, useMemo, useState, type ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Keyboard, View } 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 {
|
||||
AdaptiveModalSheet,
|
||||
type SheetHeader,
|
||||
type SheetKeyboard,
|
||||
} from "@/components/adaptive-modal-sheet";
|
||||
import { ModelProviderGlyph } from "@/components/model-browser";
|
||||
import type { ModelPickerActions } from "@/components/model-browser-panes";
|
||||
import {
|
||||
MobileModelPageView,
|
||||
SheetSearchDock,
|
||||
useMobileModelPage,
|
||||
} from "@/components/mobile-model-page";
|
||||
import { SettingsCard, SettingsDetailRow } from "@/components/settings";
|
||||
import type { ContextBridge } from "@/components/ui/isolated-bottom-sheet-modal";
|
||||
import type { KeyboardInputEvent } from "@/keyboard";
|
||||
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
|
||||
import { ICON_SIZE } from "@/styles/theme";
|
||||
import { AGENT_SHEET_HOME, resolveAgentSheetEscape, type AgentSheetPage } from "./model-sheet-flow";
|
||||
import {
|
||||
AgentSheetHome,
|
||||
AgentSheetSelectPage,
|
||||
selectPageIsSearchable,
|
||||
selectPageTitle,
|
||||
type AgentSheetControls,
|
||||
} from "./sheet-home";
|
||||
|
||||
const SNAP_POINTS = ["80%", "90%"];
|
||||
const ESCAPE_KEYS = ["Escape"] as const;
|
||||
|
||||
export interface AgentSettingsDrawerProps {
|
||||
visible: boolean;
|
||||
onClose: () => void;
|
||||
contextBridge: ContextBridge | null;
|
||||
providers: readonly ProviderSelectorProvider[];
|
||||
selectedProvider: string;
|
||||
selectedModel: string;
|
||||
selectedModelLabel: string;
|
||||
canSwitchProvider: boolean;
|
||||
serverId: string | null;
|
||||
disabled: boolean;
|
||||
controls: AgentSheetControls;
|
||||
/** Drawn below the controls on Home. */
|
||||
pluginItems: ReactNode;
|
||||
profiles: AgentProfilePicker | null;
|
||||
onSelect: (provider: string, modelId: string) => void;
|
||||
onApplyProfile?: (profileId: string) => void;
|
||||
onEditProfiles?: () => void;
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
|
||||
onEditProfile?: (profileId: string) => void;
|
||||
onRetryProvider?: (provider: AgentProvider) => void;
|
||||
isRetryingProvider: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* The compact agent settings: one drawer whose page changes in place. Home lays out every control;
|
||||
* Model (which also holds Profiles) and a long select each take the drawer over with a way back
|
||||
* to Home.
|
||||
*/
|
||||
export function AgentSettingsDrawer({
|
||||
visible,
|
||||
onClose,
|
||||
contextBridge,
|
||||
providers,
|
||||
selectedProvider,
|
||||
selectedModel,
|
||||
selectedModelLabel,
|
||||
canSwitchProvider,
|
||||
serverId,
|
||||
disabled,
|
||||
controls,
|
||||
pluginItems,
|
||||
profiles,
|
||||
onSelect,
|
||||
onApplyProfile,
|
||||
onEditProfiles,
|
||||
onCreateProfile,
|
||||
onEditProfile,
|
||||
onRetryProvider,
|
||||
isRetryingProvider,
|
||||
}: AgentSettingsDrawerProps) {
|
||||
const { t } = useTranslation();
|
||||
const [page, setPage] = useState<AgentSheetPage>(AGENT_SHEET_HOME);
|
||||
// Select pages search with this; the Model page keeps its own.
|
||||
const [pageQuery, setPageQuery] = useState("");
|
||||
const [pageSearchKey, setPageSearchKey] = useState(0);
|
||||
const modelPage = useMobileModelPage({
|
||||
providers,
|
||||
profiles: profiles?.rows ?? null,
|
||||
canCreateProfile: Boolean(onEditProfiles),
|
||||
selectedProvider,
|
||||
selectedModel,
|
||||
});
|
||||
|
||||
const goTo = useCallback((next: AgentSheetPage) => {
|
||||
Keyboard.dismiss();
|
||||
setPageQuery("");
|
||||
setPageSearchKey((key) => key + 1);
|
||||
setPage(next);
|
||||
}, []);
|
||||
const goHome = useCallback(() => goTo(AGENT_SHEET_HOME), [goTo]);
|
||||
const openModel = useCallback(() => {
|
||||
modelPage.reset();
|
||||
goTo({ kind: "model" });
|
||||
}, [goTo, modelPage]);
|
||||
const openSelect = useCallback(
|
||||
(controlId: string) => goTo({ kind: "select", controlId }),
|
||||
[goTo],
|
||||
);
|
||||
|
||||
const close = useCallback(() => {
|
||||
Keyboard.dismiss();
|
||||
setPage(AGENT_SHEET_HOME);
|
||||
setPageQuery("");
|
||||
modelPage.reset();
|
||||
onClose();
|
||||
}, [modelPage, onClose]);
|
||||
|
||||
const clearPageQuery = useCallback(() => {
|
||||
setPageQuery("");
|
||||
setPageSearchKey((key) => key + 1);
|
||||
}, []);
|
||||
|
||||
const keyboard = useMemo<SheetKeyboard>(
|
||||
() => ({
|
||||
keys: ESCAPE_KEYS,
|
||||
onKeyDown: (event: KeyboardInputEvent) => {
|
||||
if (event.key !== "Escape") return false;
|
||||
const query = page.kind === "model" ? modelPage.query : pageQuery;
|
||||
const step = resolveAgentSheetEscape({ page, query });
|
||||
if (step === "close") return false;
|
||||
if (step === "home") goHome();
|
||||
else if (page.kind === "model") modelPage.clearQuery();
|
||||
else clearPageQuery();
|
||||
return true;
|
||||
},
|
||||
}),
|
||||
[clearPageQuery, goHome, modelPage, page, pageQuery],
|
||||
);
|
||||
|
||||
const handlePickModel = useCallback(
|
||||
(provider: string, modelId: string) => {
|
||||
onSelect(provider, modelId);
|
||||
goHome();
|
||||
},
|
||||
[goHome, onSelect],
|
||||
);
|
||||
const handleApplyProfile = useCallback(
|
||||
(profileId: string) => {
|
||||
onApplyProfile?.(profileId);
|
||||
close();
|
||||
},
|
||||
[close, onApplyProfile],
|
||||
);
|
||||
const handleEditProfiles = useCallback(() => {
|
||||
close();
|
||||
onEditProfiles?.();
|
||||
}, [close, onEditProfiles]);
|
||||
const handleCreateProfile = useCallback(
|
||||
(seed: AgentProfileSeed) => {
|
||||
if (seed.modelId) onSelect(seed.provider, seed.modelId);
|
||||
close();
|
||||
void onCreateProfile?.(seed);
|
||||
},
|
||||
[close, onCreateProfile, onSelect],
|
||||
);
|
||||
const handleEditProfile = useCallback(
|
||||
(profileId: string) => {
|
||||
close();
|
||||
onEditProfile?.(profileId);
|
||||
},
|
||||
[close, onEditProfile],
|
||||
);
|
||||
const pickerActions = useMemo<ModelPickerActions>(
|
||||
() => ({
|
||||
onSelect: handlePickModel,
|
||||
onApplyProfile: handleApplyProfile,
|
||||
onEditProfiles: onEditProfiles ? handleEditProfiles : undefined,
|
||||
onCreateProfile: onCreateProfile ? handleCreateProfile : undefined,
|
||||
onEditProfile: onEditProfile ? handleEditProfile : undefined,
|
||||
onRetryProvider,
|
||||
isRetryingProvider,
|
||||
}),
|
||||
[
|
||||
handleApplyProfile,
|
||||
handleCreateProfile,
|
||||
handleEditProfile,
|
||||
handleEditProfiles,
|
||||
handlePickModel,
|
||||
isRetryingProvider,
|
||||
onCreateProfile,
|
||||
onEditProfile,
|
||||
onEditProfiles,
|
||||
onRetryProvider,
|
||||
],
|
||||
);
|
||||
|
||||
const header = useMemo<SheetHeader>(() => {
|
||||
const back = { onPress: goHome };
|
||||
switch (page.kind) {
|
||||
case "home":
|
||||
return { title: t("agentControls.sheet.title") };
|
||||
case "model":
|
||||
return { title: t("modelSelector.model"), back };
|
||||
case "select":
|
||||
return {
|
||||
title: selectPageTitle(page.controlId, controls, t("agentControls.mode.title")),
|
||||
back,
|
||||
};
|
||||
}
|
||||
}, [controls, goHome, page, t]);
|
||||
|
||||
const footer = useMemo(() => {
|
||||
switch (page.kind) {
|
||||
case "home":
|
||||
return null;
|
||||
case "model": {
|
||||
let placeholder = t("modelSelector.searchPlaceholder");
|
||||
if (profiles && profiles.rows.length > 0) {
|
||||
placeholder = t("modelSelector.searchModelsAndProfilesPlaceholder");
|
||||
} else if (canSwitchProvider) {
|
||||
placeholder = t("modelSelector.searchAllPlaceholder");
|
||||
}
|
||||
return (
|
||||
<SheetSearchDock
|
||||
query={modelPage.query}
|
||||
searchKey={modelPage.searchKey}
|
||||
onChangeText={modelPage.setQuery}
|
||||
placeholder={placeholder}
|
||||
testID="model-search-all-input"
|
||||
/>
|
||||
);
|
||||
}
|
||||
case "select":
|
||||
return selectPageIsSearchable(page.controlId, controls) ? (
|
||||
<SelectSearchDock
|
||||
controlId={page.controlId}
|
||||
controls={controls}
|
||||
query={pageQuery}
|
||||
searchKey={pageSearchKey}
|
||||
onChangeText={setPageQuery}
|
||||
/>
|
||||
) : null;
|
||||
}
|
||||
}, [
|
||||
canSwitchProvider,
|
||||
controls,
|
||||
modelPage.query,
|
||||
modelPage.searchKey,
|
||||
modelPage.setQuery,
|
||||
page,
|
||||
pageQuery,
|
||||
pageSearchKey,
|
||||
profiles,
|
||||
t,
|
||||
]);
|
||||
|
||||
const topCard = useMemo(
|
||||
() => (
|
||||
<AgentSheetTopCard
|
||||
selectedProvider={selectedProvider}
|
||||
serverId={serverId}
|
||||
selectedModelLabel={selectedModelLabel}
|
||||
disabled={disabled}
|
||||
onOpenModel={openModel}
|
||||
/>
|
||||
),
|
||||
[disabled, openModel, selectedModelLabel, selectedProvider, serverId],
|
||||
);
|
||||
|
||||
let body: ReactNode;
|
||||
switch (page.kind) {
|
||||
case "home":
|
||||
body = (
|
||||
<AgentSheetHome
|
||||
controls={controls}
|
||||
disabled={disabled}
|
||||
topCard={topCard}
|
||||
footer={pluginItems}
|
||||
onOpenSelect={openSelect}
|
||||
/>
|
||||
);
|
||||
break;
|
||||
case "model":
|
||||
body = (
|
||||
<MobileModelPageView
|
||||
page={modelPage}
|
||||
selectedProvider={selectedProvider}
|
||||
selectedModel={selectedModel}
|
||||
serverId={serverId}
|
||||
profiles={profiles?.rows ?? null}
|
||||
actions={pickerActions}
|
||||
/>
|
||||
);
|
||||
break;
|
||||
case "select":
|
||||
body = (
|
||||
<AgentSheetSelectPage
|
||||
controlId={page.controlId}
|
||||
controls={controls}
|
||||
query={pageQuery}
|
||||
disabled={disabled}
|
||||
onPicked={goHome}
|
||||
/>
|
||||
);
|
||||
break;
|
||||
}
|
||||
|
||||
return (
|
||||
<AdaptiveModalSheet
|
||||
header={header}
|
||||
visible={visible}
|
||||
onClose={close}
|
||||
snapPoints={SNAP_POINTS}
|
||||
scrollable={false}
|
||||
footer={footer}
|
||||
keyboard={keyboard}
|
||||
contentStyle={styles.sheetBody}
|
||||
contextBridge={contextBridge}
|
||||
testID="agent-controls-model-sheet"
|
||||
>
|
||||
{/* Keyed by page, so each page opens at its top. */}
|
||||
<View key={pageKey(page)} style={styles.page}>
|
||||
{body}
|
||||
</View>
|
||||
</AdaptiveModalSheet>
|
||||
);
|
||||
}
|
||||
|
||||
/** The Model row that heads Home. */
|
||||
function AgentSheetTopCard({
|
||||
selectedProvider,
|
||||
serverId,
|
||||
selectedModelLabel,
|
||||
disabled,
|
||||
onOpenModel,
|
||||
}: {
|
||||
selectedProvider: string;
|
||||
serverId: string | null;
|
||||
selectedModelLabel: string;
|
||||
disabled: boolean;
|
||||
onOpenModel: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const hasProvider = selectedProvider.trim().length > 0;
|
||||
const summaryLeading = useMemo(
|
||||
() =>
|
||||
hasProvider ? (
|
||||
<ModelProviderGlyph provider={selectedProvider} serverId={serverId} size={ICON_SIZE.sm} />
|
||||
) : undefined,
|
||||
[hasProvider, selectedProvider, serverId],
|
||||
);
|
||||
return (
|
||||
<SettingsCard>
|
||||
<SettingsDetailRow
|
||||
label={t("modelSelector.model")}
|
||||
summary={selectedModelLabel}
|
||||
summaryLeading={summaryLeading}
|
||||
onPress={onOpenModel}
|
||||
disabled={disabled}
|
||||
accessibilityLabel={t("modelSelector.selectedModel", { model: selectedModelLabel })}
|
||||
testID="agent-controls-model"
|
||||
/>
|
||||
</SettingsCard>
|
||||
);
|
||||
}
|
||||
|
||||
function pageKey(page: AgentSheetPage): string {
|
||||
return page.kind === "select" ? `select:${page.controlId}` : page.kind;
|
||||
}
|
||||
|
||||
function SelectSearchDock({
|
||||
controlId,
|
||||
controls,
|
||||
query,
|
||||
searchKey,
|
||||
onChangeText,
|
||||
}: {
|
||||
controlId: string;
|
||||
controls: AgentSheetControls;
|
||||
query: string;
|
||||
searchKey: number;
|
||||
onChangeText: (query: string) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const item = [...controls.thinkingItems, ...controls.featureItems].find(
|
||||
(candidate) => candidate.id === controlId,
|
||||
);
|
||||
const onSearchQueryChange = item?.type === "select" ? item.onSearchQueryChange : undefined;
|
||||
const handleChange = useCallback(
|
||||
(next: string) => {
|
||||
onChangeText(next);
|
||||
onSearchQueryChange?.(next);
|
||||
},
|
||||
[onChangeText, onSearchQueryChange],
|
||||
);
|
||||
return (
|
||||
<SheetSearchDock
|
||||
query={query}
|
||||
searchKey={searchKey}
|
||||
onChangeText={handleChange}
|
||||
placeholder={item ? t("common.actions.search") : t("agentControls.mode.searchPlaceholder")}
|
||||
testID="agent-controls-select-search"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create(() => ({
|
||||
sheetBody: {
|
||||
paddingHorizontal: 0,
|
||||
paddingTop: 0,
|
||||
paddingBottom: 0,
|
||||
gap: 0,
|
||||
},
|
||||
page: {
|
||||
flex: 1,
|
||||
minHeight: 0,
|
||||
},
|
||||
}));
|
||||
@@ -192,7 +192,7 @@ function listProps(select: SelectItem | null) {
|
||||
|
||||
// A command that returns a promise keeps the control pending until it settles, and a failure
|
||||
// reaches the user the way a built-in live control's does.
|
||||
function usePendingRun() {
|
||||
export function usePendingRun() {
|
||||
const toast = useToast();
|
||||
const [pending, setPending] = useState(false);
|
||||
const run = useCallback(
|
||||
@@ -305,6 +305,13 @@ export function ComposerControl({
|
||||
);
|
||||
}
|
||||
|
||||
/** A control's icon in its highlight colour, muted when it has none. */
|
||||
export function ComposerControlIcon({ item, size }: { item: ComposerControlItem; size: number }) {
|
||||
const Icon = item.icon;
|
||||
const color = item.highlight ? styles[item.highlight].color : styles.fieldIcon.color;
|
||||
return <Icon size={size} color={color} />;
|
||||
}
|
||||
|
||||
/** Where a list opens on desktop; the sheet has its own presentation. */
|
||||
const DESKTOP_PLACEMENT = {
|
||||
toolbar: "top-start",
|
||||
|
||||
@@ -26,6 +26,7 @@ import { resolveProviderDefinition } from "@/utils/provider-definitions";
|
||||
import { mergeProviderPreferences, useFormPreferences } from "@/hooks/use-form-preferences";
|
||||
import {
|
||||
AgentModeControl,
|
||||
useAgentModeCycleShortcut,
|
||||
useLiveAgentModeControl,
|
||||
type AgentModeControlValue,
|
||||
} from "@/composer/agent-controls/mode-control";
|
||||
@@ -82,6 +83,7 @@ import {
|
||||
useModelPickerShortcut,
|
||||
} from "@/composer/agent-controls/control-items";
|
||||
import { CompactModelSheet } from "@/composer/agent-controls/model-sheet";
|
||||
import type { AgentSheetControls } from "@/composer/agent-controls/sheet-home";
|
||||
import { useComposerSheetBridge } from "@/composer/agent-controls/sheet-bridge";
|
||||
import { draftComposerAgent } from "@/composer/draft/composer-agent";
|
||||
import { agentComposer } from "@/composer/agent-composer";
|
||||
@@ -462,6 +464,7 @@ function ControlledAgentControls({
|
||||
const { fontScale } = useWindowDimensions();
|
||||
const [activeSheet, setActiveSheet] = useState<ActiveSheet>(null);
|
||||
const [openSelector, setOpenSelector] = useState<string | null>(null);
|
||||
useAgentModeCycleShortcut(modeControl);
|
||||
// A compact composer always folds its controls into the model sheet; the width budget only
|
||||
// decides whether the model keeps its label.
|
||||
const minimumDensity: ComposerControlDensity = isCompact ? "compact" : "full";
|
||||
@@ -836,7 +839,6 @@ function DesktopAgentControlsContent(props: DesktopAgentControlsContentProps) {
|
||||
isRetryingProvider={isRetryingModelProvider}
|
||||
serverId={modelSelectorServerId}
|
||||
desktopPlacement="top-start"
|
||||
desktopMinWidth={360}
|
||||
toolbar={modelToolbar}
|
||||
/>
|
||||
</View>
|
||||
@@ -941,27 +943,13 @@ function SheetAgentControlsContent(props: SheetAgentControlsContentProps) {
|
||||
canSwitchProvider,
|
||||
} = props;
|
||||
|
||||
const sheetControls = (
|
||||
<View style={styles.combinedSheetControls} testID="agent-controls-combined-sheet-controls">
|
||||
<ComposerControls
|
||||
items={thinkingItems}
|
||||
surface="sheet"
|
||||
disabled={disabled}
|
||||
openId={openSelector}
|
||||
onOpenIdChange={handleSheetOpenChange}
|
||||
/>
|
||||
|
||||
{modeControl ? <AgentModeControl {...modeControl} surface="sheet" /> : null}
|
||||
|
||||
<ComposerControls
|
||||
items={featureItems}
|
||||
surface="sheet"
|
||||
disabled={disabled}
|
||||
openId={openSelector}
|
||||
onOpenIdChange={handleSheetOpenChange}
|
||||
/>
|
||||
<PluginComposerItems serverId={modelSelectorServerId} surface="sheet" />
|
||||
</View>
|
||||
const sheetControls = useMemo<AgentSheetControls>(
|
||||
() => ({ thinkingItems, featureItems, modeControl: modeControl ?? null }),
|
||||
[featureItems, modeControl, thinkingItems],
|
||||
);
|
||||
const pluginItems = useMemo(
|
||||
() => <PluginComposerItems serverId={modelSelectorServerId} surface="sheet" />,
|
||||
[modelSelectorServerId],
|
||||
);
|
||||
|
||||
return canSelectModel ? (
|
||||
@@ -988,9 +976,11 @@ function SheetAgentControlsContent(props: SheetAgentControlsContentProps) {
|
||||
glyphs={glyphs}
|
||||
showLabels={showLabels}
|
||||
canSwitchProvider={canSwitchProvider}
|
||||
>
|
||||
{sheetControls}
|
||||
</CompactModelSheet>
|
||||
controls={sheetControls}
|
||||
pluginItems={pluginItems}
|
||||
openControlId={openSelector}
|
||||
onOpenControlIdChange={handleSheetOpenChange}
|
||||
/>
|
||||
) : null;
|
||||
}
|
||||
|
||||
@@ -1553,7 +1543,4 @@ const styles = StyleSheet.create((theme) => ({
|
||||
backgroundColor: "transparent",
|
||||
borderRadius: theme.borderRadius.full,
|
||||
},
|
||||
combinedSheetControls: {
|
||||
gap: theme.spacing[1],
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import React, { useMemo } from "react";
|
||||
import { act, cleanup, render } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { AgentMode } from "@getpaseo/protocol/agent-types";
|
||||
import { ComposerKeyboardScopeProvider } from "@/composer/keyboard-scope";
|
||||
import {
|
||||
KeyboardActionDispatcherProvider,
|
||||
useKeyboardActionDispatcher,
|
||||
} from "@/keyboard/keyboard-action-dispatcher-context";
|
||||
import { useAgentModeCycleShortcut, type AgentModeControlValue } from "./mode-control";
|
||||
|
||||
beforeEach(() => vi.stubGlobal("React", React));
|
||||
afterEach(cleanup);
|
||||
|
||||
const MODES: AgentMode[] = [
|
||||
{ id: "default", label: "Default" },
|
||||
{ id: "plan", label: "Plan" },
|
||||
{ id: "bypass", label: "Bypass" },
|
||||
];
|
||||
|
||||
let dispatcher: ReturnType<typeof useKeyboardActionDispatcher> | null = null;
|
||||
|
||||
// A composer's controls with no Mode control mounted, as a compact composer renders them while
|
||||
// its settings drawer is closed.
|
||||
function ComposerControlsProbe({
|
||||
selectedModeId,
|
||||
onSelectMode,
|
||||
}: {
|
||||
selectedModeId: string;
|
||||
onSelectMode: (modeId: string) => void;
|
||||
}) {
|
||||
dispatcher = useKeyboardActionDispatcher();
|
||||
const modeControl = useMemo<AgentModeControlValue>(
|
||||
() => ({
|
||||
provider: "claude",
|
||||
providerDefinitions: [],
|
||||
modeOptions: MODES,
|
||||
selectedModeId,
|
||||
onSelectMode,
|
||||
}),
|
||||
[onSelectMode, selectedModeId],
|
||||
);
|
||||
useAgentModeCycleShortcut(modeControl);
|
||||
return null;
|
||||
}
|
||||
|
||||
function renderComposer(input: { selectedModeId: string; isActiveComposer?: boolean }) {
|
||||
const onSelectMode = vi.fn();
|
||||
render(
|
||||
<KeyboardActionDispatcherProvider>
|
||||
<ComposerKeyboardScopeProvider
|
||||
isPaneFocused
|
||||
isActiveComposer={input.isActiveComposer ?? true}
|
||||
isCommandCenterTarget
|
||||
>
|
||||
<ComposerControlsProbe selectedModeId={input.selectedModeId} onSelectMode={onSelectMode} />
|
||||
</ComposerKeyboardScopeProvider>
|
||||
</KeyboardActionDispatcherProvider>,
|
||||
);
|
||||
return onSelectMode;
|
||||
}
|
||||
|
||||
function cycleMode(): boolean {
|
||||
if (!dispatcher) throw new Error("The dispatcher is not mounted");
|
||||
let handled = false;
|
||||
act(() => {
|
||||
handled = dispatcher!.dispatch({ id: "message-input.mode-cycle", scope: "message-input" });
|
||||
});
|
||||
return handled;
|
||||
}
|
||||
|
||||
describe("useAgentModeCycleShortcut", () => {
|
||||
it("cycles to the next mode without a Mode control on screen", () => {
|
||||
const onSelectMode = renderComposer({ selectedModeId: "plan" });
|
||||
expect(cycleMode()).toBe(true);
|
||||
expect(onSelectMode).toHaveBeenCalledWith("bypass");
|
||||
});
|
||||
|
||||
it("leaves the shortcut to the composer that takes input", () => {
|
||||
const onSelectMode = renderComposer({ selectedModeId: "plan", isActiveComposer: false });
|
||||
expect(cycleMode()).toBe(false);
|
||||
expect(onSelectMode).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -90,7 +90,6 @@ export function AgentModeControl({
|
||||
const { isActiveComposer } = useComposerKeyboardScope();
|
||||
const cycleShortcutKeys = useShortcutKeys("cycle-agent-mode");
|
||||
const anchorRef = useRef<View>(null);
|
||||
const keyboardHandlerIdRef = useRef(`mode-control:${Math.random().toString(36).slice(2)}`);
|
||||
const openRef = useRef(false);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
@@ -135,26 +134,6 @@ export function AgentModeControl({
|
||||
[onSelectMode, handleOpenChange],
|
||||
);
|
||||
|
||||
const handleKeyboardAction = useCallback(
|
||||
(action: KeyboardActionDefinition): boolean => {
|
||||
if (action.id !== "message-input.mode-cycle") return false;
|
||||
if (disabled || !isActiveComposer) return false;
|
||||
const nextModeId = resolveNextAgentModeId({ modeOptions, selectedMode: selectedModeId });
|
||||
if (!nextModeId) return false;
|
||||
onSelectMode(nextModeId);
|
||||
return true;
|
||||
},
|
||||
[disabled, isActiveComposer, modeOptions, onSelectMode, selectedModeId],
|
||||
);
|
||||
|
||||
useKeyboardActionHandler({
|
||||
handlerId: keyboardHandlerIdRef.current,
|
||||
actions: ["message-input.mode-cycle"],
|
||||
enabled: isActiveComposer && !disabled && modeOptions.length > 1,
|
||||
priority: 200,
|
||||
handle: handleKeyboardAction,
|
||||
});
|
||||
|
||||
const renderOption = useCallback(
|
||||
(args: {
|
||||
option: ComboboxOption;
|
||||
@@ -234,6 +213,41 @@ export function AgentModeControl({
|
||||
|
||||
const EMPTY_MODES: AgentMode[] = [];
|
||||
|
||||
/**
|
||||
* Cycles the agent's mode on the mode-cycle shortcut. The composer's controls mount it once,
|
||||
* whatever the layout: a compact composer folds Mode into its settings drawer, and a phone or
|
||||
* narrow window can still have a keyboard.
|
||||
*/
|
||||
export function useAgentModeCycleShortcut(modeControl: AgentModeControlValue | null | undefined) {
|
||||
const { isActiveComposer } = useComposerKeyboardScope();
|
||||
const handlerIdRef = useRef(`mode-cycle:${Math.random().toString(36).slice(2)}`);
|
||||
const modeOptions = modeControl?.modeOptions ?? EMPTY_MODES;
|
||||
const enabled =
|
||||
isActiveComposer && modeControl != null && !modeControl.disabled && modeOptions.length > 1;
|
||||
|
||||
const handle = useCallback(
|
||||
(action: KeyboardActionDefinition): boolean => {
|
||||
if (action.id !== "message-input.mode-cycle" || !enabled || !modeControl) return false;
|
||||
const nextModeId = resolveNextAgentModeId({
|
||||
modeOptions,
|
||||
selectedMode: modeControl.selectedModeId,
|
||||
});
|
||||
if (!nextModeId) return false;
|
||||
modeControl.onSelectMode(nextModeId);
|
||||
return true;
|
||||
},
|
||||
[enabled, modeControl, modeOptions],
|
||||
);
|
||||
|
||||
useKeyboardActionHandler({
|
||||
handlerId: handlerIdRef.current,
|
||||
actions: ["message-input.mode-cycle"],
|
||||
enabled,
|
||||
priority: 200,
|
||||
handle,
|
||||
});
|
||||
}
|
||||
|
||||
function compareAvailableModes(a: AgentMode[], b: AgentMode[]): boolean {
|
||||
return a === b || JSON.stringify(a) === JSON.stringify(b);
|
||||
}
|
||||
|
||||
@@ -1,42 +1,19 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
|
||||
import { resolveModelSheetOpening } from "./model-sheet-flow";
|
||||
import { AGENT_SHEET_HOME, resolveAgentSheetEscape } from "./model-sheet-flow";
|
||||
|
||||
function provider(id: string, label: string): ProviderSelectorProvider {
|
||||
return { id, label, modelSelection: { kind: "models", rows: [] } };
|
||||
}
|
||||
|
||||
const codex = provider("codex", "Codex");
|
||||
const claude = provider("claude", "Claude Code");
|
||||
|
||||
describe("model sheet opening", () => {
|
||||
it("starts drafts at providers even when only one provider is available", () => {
|
||||
expect(
|
||||
resolveModelSheetOpening({
|
||||
canSwitchProvider: true,
|
||||
providers: [codex],
|
||||
selectedProvider: "codex",
|
||||
}),
|
||||
).toEqual({ kind: "all" });
|
||||
describe("agent settings sheet Escape", () => {
|
||||
it("clears a search before it leaves the page", () => {
|
||||
expect(resolveAgentSheetEscape({ page: { kind: "model" }, query: "opus" })).toBe("clearQuery");
|
||||
});
|
||||
|
||||
it("opens a running agent directly at its fixed provider", () => {
|
||||
it("returns from a page to home", () => {
|
||||
expect(resolveAgentSheetEscape({ page: { kind: "model" }, query: "" })).toBe("home");
|
||||
expect(
|
||||
resolveModelSheetOpening({
|
||||
canSwitchProvider: false,
|
||||
providers: [claude, codex],
|
||||
selectedProvider: "codex",
|
||||
}),
|
||||
).toEqual({ kind: "provider", providerId: "codex", providerLabel: "Codex" });
|
||||
resolveAgentSheetEscape({ page: { kind: "select", controlId: "feature-branch" }, query: "" }),
|
||||
).toBe("home");
|
||||
});
|
||||
|
||||
it("falls back to the only provider while live state catches up", () => {
|
||||
expect(
|
||||
resolveModelSheetOpening({
|
||||
canSwitchProvider: false,
|
||||
providers: [codex],
|
||||
selectedProvider: "",
|
||||
}),
|
||||
).toEqual({ kind: "provider", providerId: "codex", providerLabel: "Codex" });
|
||||
it("closes the sheet from home", () => {
|
||||
expect(resolveAgentSheetEscape({ page: AGENT_SHEET_HOME, query: "" })).toBe("close");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,19 +1,22 @@
|
||||
import type { ModelBrowserView } from "@/components/model-browser-view";
|
||||
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
|
||||
/**
|
||||
* The pages of the compact agent settings sheet. One sheet swaps its page in place; nothing stacks
|
||||
* a second sheet over it.
|
||||
*/
|
||||
export type AgentSheetPage =
|
||||
| { kind: "home" }
|
||||
| { kind: "model" }
|
||||
/** A select too long to scan on home, by control id; `mode` is the agent's mode. */
|
||||
| { kind: "select"; controlId: string };
|
||||
|
||||
export function resolveModelSheetOpening({
|
||||
canSwitchProvider,
|
||||
providers,
|
||||
selectedProvider,
|
||||
}: {
|
||||
canSwitchProvider: boolean;
|
||||
providers: ProviderSelectorProvider[];
|
||||
selectedProvider: string;
|
||||
}): ModelBrowserView {
|
||||
if (canSwitchProvider) return { kind: "all" };
|
||||
export const AGENT_SHEET_HOME: AgentSheetPage = { kind: "home" };
|
||||
|
||||
const provider = providers.find((entry) => entry.id === selectedProvider) ?? providers[0] ?? null;
|
||||
return provider
|
||||
? { kind: "provider", providerId: provider.id, providerLabel: provider.label }
|
||||
: { kind: "all" };
|
||||
export type AgentSheetEscape = "clearQuery" | "home" | "close";
|
||||
|
||||
/** Escape undoes one step: the search, then the page, then the sheet. */
|
||||
export function resolveAgentSheetEscape(input: {
|
||||
page: AgentSheetPage;
|
||||
query: string;
|
||||
}): AgentSheetEscape {
|
||||
if (input.page.kind === "home") return "close";
|
||||
return input.query.trim().length > 0 ? "clearQuery" : "home";
|
||||
}
|
||||
|
||||
@@ -17,14 +17,11 @@ import { ComboboxTrigger } from "@/components/ui/combobox-trigger";
|
||||
import { TailEllipsisText } from "@/components/ui/tail-ellipsis-text";
|
||||
import { useProviderIcon } from "@/components/provider-icons";
|
||||
import { ModelBrowser, useModelBrowser } from "@/components/model-browser";
|
||||
import { resolveModelBrowserScrolling } from "@/components/model-browser-view";
|
||||
import { AgentControlTrigger } from "@/composer/agent-controls/control";
|
||||
import { ComposerToolbarGlyph } from "@/composer/agent-controls/glyph";
|
||||
import { resolveModelTriggerLabels } from "@/composer/agent-controls/layout";
|
||||
import { resolveModelSheetOpening } from "@/composer/agent-controls/model-sheet-flow";
|
||||
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { isNative, isWeb } from "@/constants/platform";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { readMeasuredWidth } from "@/hooks/use-container-width";
|
||||
import {
|
||||
toolbarContentSlot,
|
||||
@@ -35,10 +32,14 @@ import { getAgentControlHintKey, shortModelLabel } from "./utils";
|
||||
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
|
||||
import { useKeyboardToggle } from "@/hooks/use-keyboard-toggle";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { ControlTooltipHint } from "./composer-control";
|
||||
import { ComposerControls, ControlTooltipHint } from "./composer-control";
|
||||
import { useModelPickerShortcut } from "./control-items";
|
||||
import { AgentSettingsDrawer } from "./agent-settings-drawer";
|
||||
import { AgentModeControl } from "./mode-control";
|
||||
import type { AgentSheetControls } from "./sheet-home";
|
||||
|
||||
const SNAP_POINTS = ["80%", "90%"];
|
||||
// The dialog's model list scrolls inside its fixed viewport, apart from the controls below it.
|
||||
const MODEL_LIST_TOP_INSET = 4;
|
||||
const MODEL_ROW_STRIDE = 44;
|
||||
const MODEL_VIEWPORT_VISIBLE_ROWS = 4.5;
|
||||
@@ -70,7 +71,12 @@ interface CompactModelSheetProps {
|
||||
canSwitchProvider: boolean;
|
||||
/** Carries the composer's contexts into the sheets, which draw away from it. */
|
||||
contextBridge?: ContextBridge | null;
|
||||
children: ReactNode;
|
||||
controls: AgentSheetControls;
|
||||
/** Plugin controls, drawn after the agent's own. */
|
||||
pluginItems: ReactNode;
|
||||
/** The control whose list is open, in the narrow-pane dialog. */
|
||||
openControlId: string | null;
|
||||
onOpenControlIdChange: (id: string | null) => void;
|
||||
}
|
||||
|
||||
function resolveModelSheetProfileActions(
|
||||
@@ -161,16 +167,14 @@ export function CompactModelSheet({
|
||||
showLabels,
|
||||
canSwitchProvider,
|
||||
contextBridge = null,
|
||||
children,
|
||||
controls,
|
||||
pluginItems,
|
||||
openControlId,
|
||||
onOpenControlIdChange,
|
||||
}: CompactModelSheetProps) {
|
||||
const { t } = useTranslation();
|
||||
const usesBottomSheet = useIsCompactFormFactor();
|
||||
const modelBrowserScrolling = resolveModelBrowserScrolling({
|
||||
isNative,
|
||||
isCompact: usesBottomSheet,
|
||||
});
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [isModelBrowserOpen, setIsModelBrowserOpen] = useState(false);
|
||||
const availableProviders = useMemo(() => {
|
||||
if (canSwitchProvider) return providers;
|
||||
const fixedProvider =
|
||||
@@ -186,31 +190,8 @@ export function CompactModelSheet({
|
||||
profiles,
|
||||
serverId,
|
||||
});
|
||||
const modelBrowser = useModelBrowser({
|
||||
providers: availableProviders,
|
||||
selectedProvider,
|
||||
selectedModel,
|
||||
isLoading,
|
||||
autoFocusSearch: isWeb && !usesBottomSheet,
|
||||
profiles,
|
||||
serverId,
|
||||
});
|
||||
const ModelIcon = useProviderIcon(selectedProvider, serverId);
|
||||
const hasSelectedProvider = selectedProvider.trim().length > 0;
|
||||
const rootHeader = useMemo(
|
||||
() => ({
|
||||
...rootBrowser.header,
|
||||
title: t("modelSelector.selectModel"),
|
||||
search:
|
||||
rootBrowser.header.search && !canSwitchProvider
|
||||
? {
|
||||
...rootBrowser.header.search,
|
||||
placeholder: t("modelSelector.searchPlaceholder"),
|
||||
}
|
||||
: rootBrowser.header.search,
|
||||
}),
|
||||
[canSwitchProvider, rootBrowser.header, t],
|
||||
);
|
||||
|
||||
const open = useCallback(() => {
|
||||
Keyboard.dismiss();
|
||||
@@ -220,77 +201,10 @@ export function CompactModelSheet({
|
||||
}, [onOpen, rootBrowser]);
|
||||
|
||||
const close = useCallback(() => {
|
||||
setIsModelBrowserOpen(false);
|
||||
setIsOpen(false);
|
||||
rootBrowser.reset();
|
||||
modelBrowser.reset();
|
||||
onClose?.();
|
||||
}, [modelBrowser, onClose, rootBrowser]);
|
||||
|
||||
const handleSearchSelect = useCallback(
|
||||
(provider: string, modelId: string) => {
|
||||
onSelect(provider, modelId);
|
||||
Keyboard.dismiss();
|
||||
rootBrowser.showAll();
|
||||
},
|
||||
[onSelect, rootBrowser],
|
||||
);
|
||||
|
||||
const openModelBrowser = useCallback(() => {
|
||||
Keyboard.dismiss();
|
||||
const destination = resolveModelSheetOpening({
|
||||
canSwitchProvider,
|
||||
providers: availableProviders,
|
||||
selectedProvider,
|
||||
});
|
||||
if (destination.kind === "all") {
|
||||
modelBrowser.showAll();
|
||||
} else {
|
||||
modelBrowser.drillDown(destination.providerId, destination.providerLabel);
|
||||
}
|
||||
setIsModelBrowserOpen(true);
|
||||
}, [availableProviders, canSwitchProvider, modelBrowser, selectedProvider]);
|
||||
|
||||
const closeModelBrowser = useCallback(() => {
|
||||
setIsModelBrowserOpen(false);
|
||||
modelBrowser.reset();
|
||||
}, [modelBrowser]);
|
||||
|
||||
const handleBrowserSelect = useCallback(
|
||||
(provider: string, modelId: string) => {
|
||||
onSelect(provider, modelId);
|
||||
closeModelBrowser();
|
||||
},
|
||||
[closeModelBrowser, onSelect],
|
||||
);
|
||||
|
||||
const handleDesktopSelect = useCallback(
|
||||
(provider: string, modelId: string) => {
|
||||
onSelect(provider, modelId);
|
||||
close();
|
||||
},
|
||||
[close, onSelect],
|
||||
);
|
||||
|
||||
const handleApplyProfile = useCallback(
|
||||
(profileId: string) => {
|
||||
onApplyProfile?.(profileId);
|
||||
close();
|
||||
},
|
||||
[close, onApplyProfile],
|
||||
);
|
||||
|
||||
const handleEditProfiles = useCallback(() => {
|
||||
close();
|
||||
onEditProfiles?.();
|
||||
}, [close, onEditProfiles]);
|
||||
|
||||
const profileActions = resolveModelSheetProfileActions(
|
||||
onCreateProfile,
|
||||
onEditProfile,
|
||||
onSelect,
|
||||
close,
|
||||
);
|
||||
}, [onClose, rootBrowser]);
|
||||
|
||||
const toggle = useCallback(() => {
|
||||
if (isOpen) {
|
||||
@@ -300,29 +214,6 @@ export function CompactModelSheet({
|
||||
open();
|
||||
}, [close, isOpen, open]);
|
||||
|
||||
const mobileRootContent = useMemo(
|
||||
() => (
|
||||
<View style={styles.mobileRootContent} testID="agent-controls-settings-list">
|
||||
<View style={styles.controlsContent}>
|
||||
<AgentControlTrigger
|
||||
icon={ModelIcon}
|
||||
surface="sheet"
|
||||
label={t("modelSelector.model")}
|
||||
value={rootBrowser.selectedModelLabel}
|
||||
disabled={disabled}
|
||||
onPress={openModelBrowser}
|
||||
accessibilityLabel={t("modelSelector.selectedModel", {
|
||||
model: rootBrowser.selectedModelLabel,
|
||||
})}
|
||||
testID="agent-controls-model"
|
||||
/>
|
||||
{children}
|
||||
</View>
|
||||
</View>
|
||||
),
|
||||
[ModelIcon, children, disabled, openModelBrowser, rootBrowser.selectedModelLabel, t],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<ModelSheetTrigger
|
||||
@@ -332,7 +223,7 @@ export function CompactModelSheet({
|
||||
glyphs={glyphs}
|
||||
iconOnly={!showLabels && hasSelectedProvider}
|
||||
isOpen={isOpen}
|
||||
searchFocused={rootBrowser.isSearchFocused || modelBrowser.isSearchFocused}
|
||||
searchFocused={rootBrowser.isSearchFocused}
|
||||
disabled={disabled}
|
||||
onPress={toggle}
|
||||
accessibilityLabel={t("modelSelector.selectedModel", {
|
||||
@@ -341,90 +232,195 @@ export function CompactModelSheet({
|
||||
effortKeys={effortKeys}
|
||||
/>
|
||||
|
||||
<AdaptiveModalSheet
|
||||
header={rootHeader}
|
||||
visible={isOpen}
|
||||
onClose={close}
|
||||
snapPoints={SNAP_POINTS}
|
||||
scrollable={false}
|
||||
keyboard={rootBrowser.keyboard}
|
||||
contentStyle={styles.sheetBody}
|
||||
contextBridge={contextBridge}
|
||||
testID="agent-controls-model-sheet"
|
||||
>
|
||||
<View
|
||||
style={[
|
||||
styles.modelViewport,
|
||||
usesBottomSheet ? styles.flexibleModelViewport : styles.fixedModelViewport,
|
||||
]}
|
||||
testID="agent-controls-model-viewport"
|
||||
>
|
||||
<ModelBrowser
|
||||
state={rootBrowser}
|
||||
onSelect={usesBottomSheet ? handleSearchSelect : handleDesktopSelect}
|
||||
onApplyProfile={handleApplyProfile}
|
||||
onEditProfiles={onEditProfiles ? handleEditProfiles : undefined}
|
||||
onCreateProfile={profileActions.create}
|
||||
onEditProfile={profileActions.edit}
|
||||
onRetryProvider={onRetryProvider}
|
||||
isRetryingProvider={isRetryingProvider}
|
||||
scrolling={modelBrowserScrolling}
|
||||
searchAllOnFocus={usesBottomSheet}
|
||||
rootBrowseContent={usesBottomSheet ? mobileRootContent : undefined}
|
||||
/>
|
||||
</View>
|
||||
{!usesBottomSheet ? (
|
||||
<>
|
||||
<View style={styles.modelViewportDivider} />
|
||||
<ScrollView
|
||||
style={styles.controlsScroll}
|
||||
contentContainerStyle={styles.controlsContent}
|
||||
keyboardShouldPersistTaps="handled"
|
||||
showsVerticalScrollIndicator={false}
|
||||
testID="agent-controls-settings-list"
|
||||
>
|
||||
{children}
|
||||
</ScrollView>
|
||||
</>
|
||||
) : null}
|
||||
</AdaptiveModalSheet>
|
||||
|
||||
{usesBottomSheet ? (
|
||||
<AdaptiveModalSheet
|
||||
header={modelBrowser.header}
|
||||
visible={isModelBrowserOpen}
|
||||
onClose={closeModelBrowser}
|
||||
snapPoints={SNAP_POINTS}
|
||||
scrollable={false}
|
||||
presentation="push"
|
||||
keyboard={modelBrowser.keyboard}
|
||||
contentStyle={styles.sheetBody}
|
||||
<AgentSettingsDrawer
|
||||
visible={isOpen}
|
||||
onClose={close}
|
||||
contextBridge={contextBridge}
|
||||
testID="agent-controls-model-browser-sheet"
|
||||
>
|
||||
<View
|
||||
style={[styles.modelViewport, styles.flexibleModelViewport]}
|
||||
testID="agent-controls-model-browser-viewport"
|
||||
>
|
||||
<ModelBrowser
|
||||
state={modelBrowser}
|
||||
onSelect={handleBrowserSelect}
|
||||
onEditProfiles={onEditProfiles ? handleEditProfiles : undefined}
|
||||
onCreateProfile={profileActions.create}
|
||||
onEditProfile={profileActions.edit}
|
||||
onRetryProvider={onRetryProvider}
|
||||
isRetryingProvider={isRetryingProvider}
|
||||
scrolling={modelBrowserScrolling}
|
||||
searchAllOnFocus
|
||||
showProfilesSection={false}
|
||||
/>
|
||||
</View>
|
||||
</AdaptiveModalSheet>
|
||||
) : null}
|
||||
providers={availableProviders}
|
||||
selectedProvider={selectedProvider}
|
||||
selectedModel={selectedModel}
|
||||
selectedModelLabel={rootBrowser.selectedModelLabel}
|
||||
canSwitchProvider={canSwitchProvider}
|
||||
serverId={serverId}
|
||||
disabled={disabled}
|
||||
controls={controls}
|
||||
pluginItems={pluginItems}
|
||||
profiles={profiles}
|
||||
onSelect={onSelect}
|
||||
onApplyProfile={onApplyProfile}
|
||||
onEditProfiles={onEditProfiles}
|
||||
onCreateProfile={onCreateProfile}
|
||||
onEditProfile={onEditProfile}
|
||||
onRetryProvider={onRetryProvider}
|
||||
isRetryingProvider={isRetryingProvider}
|
||||
/>
|
||||
) : (
|
||||
<NarrowPaneModelDialog
|
||||
visible={isOpen}
|
||||
onClose={close}
|
||||
contextBridge={contextBridge}
|
||||
browser={rootBrowser}
|
||||
canSwitchProvider={canSwitchProvider}
|
||||
disabled={disabled}
|
||||
controls={controls}
|
||||
pluginItems={pluginItems}
|
||||
openControlId={openControlId}
|
||||
onOpenControlIdChange={onOpenControlIdChange}
|
||||
onSelect={onSelect}
|
||||
onApplyProfile={onApplyProfile}
|
||||
onEditProfiles={onEditProfiles}
|
||||
onCreateProfile={onCreateProfile}
|
||||
onEditProfile={onEditProfile}
|
||||
onRetryProvider={onRetryProvider}
|
||||
isRetryingProvider={isRetryingProvider}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A narrow composer pane in a wide window: the model browser above the agent's controls, in one
|
||||
* dialog.
|
||||
*/
|
||||
function NarrowPaneModelDialog({
|
||||
visible,
|
||||
onClose,
|
||||
contextBridge,
|
||||
browser,
|
||||
canSwitchProvider,
|
||||
disabled,
|
||||
controls,
|
||||
pluginItems,
|
||||
openControlId,
|
||||
onOpenControlIdChange,
|
||||
onSelect,
|
||||
onApplyProfile,
|
||||
onEditProfiles,
|
||||
onCreateProfile,
|
||||
onEditProfile,
|
||||
onRetryProvider,
|
||||
isRetryingProvider,
|
||||
}: {
|
||||
visible: boolean;
|
||||
onClose: () => void;
|
||||
contextBridge: ContextBridge | null;
|
||||
browser: ReturnType<typeof useModelBrowser>;
|
||||
canSwitchProvider: boolean;
|
||||
disabled: boolean;
|
||||
controls: AgentSheetControls;
|
||||
pluginItems: ReactNode;
|
||||
openControlId: string | null;
|
||||
onOpenControlIdChange: (id: string | null) => void;
|
||||
onSelect: (provider: string, modelId: string) => void;
|
||||
onApplyProfile?: (profileId: string) => void;
|
||||
onEditProfiles?: () => void;
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
|
||||
onEditProfile?: (profileId: string) => void;
|
||||
onRetryProvider?: (provider: AgentProvider) => void;
|
||||
isRetryingProvider: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const header = useMemo(
|
||||
() => ({
|
||||
...browser.header,
|
||||
title: t("modelSelector.selectModel"),
|
||||
search:
|
||||
browser.header.search && !canSwitchProvider
|
||||
? {
|
||||
...browser.header.search,
|
||||
placeholder: t("modelSelector.searchPlaceholder"),
|
||||
}
|
||||
: browser.header.search,
|
||||
}),
|
||||
[canSwitchProvider, browser.header, t],
|
||||
);
|
||||
const handleSelect = useCallback(
|
||||
(provider: string, modelId: string) => {
|
||||
onSelect(provider, modelId);
|
||||
onClose();
|
||||
},
|
||||
[onClose, onSelect],
|
||||
);
|
||||
const handleApplyProfile = useCallback(
|
||||
(profileId: string) => {
|
||||
onApplyProfile?.(profileId);
|
||||
onClose();
|
||||
},
|
||||
[onClose, onApplyProfile],
|
||||
);
|
||||
const handleEditProfiles = useCallback(() => {
|
||||
onClose();
|
||||
onEditProfiles?.();
|
||||
}, [onClose, onEditProfiles]);
|
||||
const profileActions = resolveModelSheetProfileActions(
|
||||
onCreateProfile,
|
||||
onEditProfile,
|
||||
onSelect,
|
||||
onClose,
|
||||
);
|
||||
|
||||
return (
|
||||
<AdaptiveModalSheet
|
||||
header={header}
|
||||
visible={visible}
|
||||
onClose={onClose}
|
||||
snapPoints={SNAP_POINTS}
|
||||
scrollable={false}
|
||||
keyboard={browser.keyboard}
|
||||
contentStyle={styles.sheetBody}
|
||||
contextBridge={contextBridge}
|
||||
testID="agent-controls-model-sheet"
|
||||
>
|
||||
<View
|
||||
style={[styles.modelViewport, styles.fixedModelViewport]}
|
||||
testID="agent-controls-model-viewport"
|
||||
>
|
||||
<ModelBrowser
|
||||
state={browser}
|
||||
onSelect={handleSelect}
|
||||
onApplyProfile={handleApplyProfile}
|
||||
onEditProfiles={onEditProfiles ? handleEditProfiles : undefined}
|
||||
onCreateProfile={profileActions.create}
|
||||
onEditProfile={profileActions.edit}
|
||||
onRetryProvider={onRetryProvider}
|
||||
isRetryingProvider={isRetryingProvider}
|
||||
/>
|
||||
</View>
|
||||
<View style={styles.modelViewportDivider} />
|
||||
<ScrollView
|
||||
style={styles.controlsScroll}
|
||||
contentContainerStyle={styles.controlsContent}
|
||||
keyboardShouldPersistTaps="handled"
|
||||
showsVerticalScrollIndicator={false}
|
||||
testID="agent-controls-settings-list"
|
||||
>
|
||||
<View style={styles.combinedControls} testID="agent-controls-combined-sheet-controls">
|
||||
<ComposerControls
|
||||
items={controls.thinkingItems}
|
||||
surface="sheet"
|
||||
disabled={disabled}
|
||||
openId={openControlId}
|
||||
onOpenIdChange={onOpenControlIdChange}
|
||||
/>
|
||||
{controls.modeControl ? (
|
||||
<AgentModeControl {...controls.modeControl} surface="sheet" />
|
||||
) : null}
|
||||
<ComposerControls
|
||||
items={controls.featureItems}
|
||||
surface="sheet"
|
||||
disabled={disabled}
|
||||
openId={openControlId}
|
||||
onOpenIdChange={onOpenControlIdChange}
|
||||
/>
|
||||
{pluginItems}
|
||||
</View>
|
||||
</ScrollView>
|
||||
</AdaptiveModalSheet>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The folded model control in the toolbar: the provider glyph, then the model and thinking
|
||||
* labels for as long as they fit.
|
||||
@@ -660,10 +656,6 @@ const styles = StyleSheet.create((theme) => ({
|
||||
overflow: "hidden",
|
||||
backgroundColor: theme.colors.surfaceSidebar,
|
||||
},
|
||||
flexibleModelViewport: {
|
||||
flex: 1,
|
||||
minHeight: 0,
|
||||
},
|
||||
fixedModelViewport: {
|
||||
height: FIXED_MODEL_VIEWPORT_HEIGHT,
|
||||
minHeight: FIXED_MODEL_VIEWPORT_HEIGHT,
|
||||
@@ -677,15 +669,13 @@ const styles = StyleSheet.create((theme) => ({
|
||||
flex: 1,
|
||||
minHeight: 0,
|
||||
},
|
||||
mobileRootContent: {
|
||||
backgroundColor: theme.colors.surfaceSidebar,
|
||||
borderTopWidth: 1,
|
||||
borderTopColor: theme.colors.border,
|
||||
},
|
||||
controlsContent: {
|
||||
paddingHorizontal: theme.spacing[2],
|
||||
paddingTop: theme.spacing[3],
|
||||
paddingBottom: theme.spacing[3],
|
||||
gap: theme.spacing[1],
|
||||
},
|
||||
combinedControls: {
|
||||
gap: theme.spacing[1],
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { Brain } from "lucide-react-native";
|
||||
import type { ComposerControlChoice, ComposerControlItem } from "./composer-control";
|
||||
import {
|
||||
classifySheetControl,
|
||||
isOrderedThinkingRange,
|
||||
layoutSheetHome,
|
||||
} from "./sheet-control-layout";
|
||||
|
||||
function noop() {}
|
||||
|
||||
function choices(...labels: string[]): ComposerControlChoice[] {
|
||||
return labels.map((label) => ({ value: label.toLowerCase(), label }));
|
||||
}
|
||||
|
||||
function select(
|
||||
id: string,
|
||||
options: {
|
||||
choices: ComposerControlChoice[];
|
||||
searchable?: boolean;
|
||||
remoteSearch?: boolean;
|
||||
},
|
||||
): ComposerControlItem {
|
||||
return {
|
||||
id,
|
||||
type: "select",
|
||||
title: id,
|
||||
icon: Brain,
|
||||
value: options.choices[0]?.value ?? null,
|
||||
onChange: noop,
|
||||
...options,
|
||||
};
|
||||
}
|
||||
|
||||
function toggle(id: string): ComposerControlItem {
|
||||
return { id, type: "toggle", title: id, icon: Brain, value: false, onChange: noop };
|
||||
}
|
||||
|
||||
function action(id: string): ComposerControlItem {
|
||||
return { id, type: "action", title: id, icon: Brain, onPress: noop };
|
||||
}
|
||||
|
||||
const claudeThinking = select("thinking", {
|
||||
choices: choices("Off", "Low", "Medium", "High", "Extra High", "Max"),
|
||||
});
|
||||
|
||||
describe("isOrderedThinkingRange", () => {
|
||||
it("recognizes standard effort scales across providers (including 8-stop OMP)", () => {
|
||||
expect(isOrderedThinkingRange(choices("Low", "Medium", "High", "Extra high", "Max"))).toBe(
|
||||
true,
|
||||
);
|
||||
expect(
|
||||
isOrderedThinkingRange(choices("None", "Minimal", "Low", "Medium", "High", "XHigh")),
|
||||
).toBe(true);
|
||||
expect(
|
||||
isOrderedThinkingRange(
|
||||
choices("Auto", "Off", "Minimal", "Low", "Medium", "High", "XHigh", "Max"),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("recognizes numeric thinking budgets", () => {
|
||||
expect(isOrderedThinkingRange(choices("Off", "1k", "4k", "16k", "32k"))).toBe(true);
|
||||
expect(isOrderedThinkingRange(choices("0", "1024", "4096", "16384"))).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects binary, unordered, or custom non-range thinking options", () => {
|
||||
expect(isOrderedThinkingRange(choices("Off", "On"))).toBe(false);
|
||||
expect(isOrderedThinkingRange(choices("High", "Low", "Medium"))).toBe(false);
|
||||
expect(isOrderedThinkingRange(choices("Bespoke", "Fast CoT", "Tree Search"))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("classifySheetControl", () => {
|
||||
it("draws a toggle as a switch row", () => {
|
||||
expect(classifySheetControl(toggle("fast"))).toBe("switch");
|
||||
});
|
||||
|
||||
it("draws an action as a row", () => {
|
||||
expect(classifySheetControl(action("open"))).toBe("action");
|
||||
});
|
||||
|
||||
it("draws an ordered thinking range as a slider, even with eight stops", () => {
|
||||
expect(classifySheetControl(claudeThinking)).toBe("slider");
|
||||
expect(
|
||||
classifySheetControl(
|
||||
select("thinking", {
|
||||
choices: choices("Auto", "Off", "Minimal", "Low", "Medium", "High", "XHigh", "Max"),
|
||||
}),
|
||||
),
|
||||
).toBe("slider");
|
||||
});
|
||||
|
||||
it("falls back to pills for binary or non-range thinking choices and short selects", () => {
|
||||
expect(classifySheetControl(select("thinking", { choices: choices("Off", "On") }))).toBe(
|
||||
"pills",
|
||||
);
|
||||
expect(
|
||||
classifySheetControl(select("thinking", { choices: choices("Bespoke", "Fast", "Deep") })),
|
||||
).toBe("pills");
|
||||
expect(
|
||||
classifySheetControl(select("speed", { choices: choices("Low", "Medium", "High") })),
|
||||
).toBe("pills");
|
||||
});
|
||||
|
||||
it("draws a select as a radio list once a label is too long for a pill", () => {
|
||||
expect(
|
||||
classifySheetControl(select("mode", { choices: choices("Default", "Accept file edits") })),
|
||||
).toBe("radioList");
|
||||
});
|
||||
|
||||
it("draws a select as a radio list when any choice has a description", () => {
|
||||
expect(
|
||||
classifySheetControl(
|
||||
select("speed", {
|
||||
choices: [
|
||||
{ value: "normal", label: "Normal" },
|
||||
{ value: "fast", label: "Fast", description: "Costs more" },
|
||||
],
|
||||
}),
|
||||
),
|
||||
).toBe("radioList");
|
||||
});
|
||||
|
||||
it("keeps seven choices inline and moves an eighth to its own page", () => {
|
||||
const seven = choices("A", "B", "C", "D", "E", "F", "G");
|
||||
expect(classifySheetControl(select("seven", { choices: seven }))).toBe("pills");
|
||||
expect(classifySheetControl(select("eight", { choices: [...seven, ...choices("H")] }))).toBe(
|
||||
"subpage",
|
||||
);
|
||||
});
|
||||
|
||||
it("moves a searchable select to its own page whatever its size", () => {
|
||||
expect(
|
||||
classifySheetControl(select("branch", { choices: choices("main"), searchable: true })),
|
||||
).toBe("subpage");
|
||||
expect(
|
||||
classifySheetControl(select("issue", { choices: choices("one"), remoteSearch: true })),
|
||||
).toBe("subpage");
|
||||
});
|
||||
});
|
||||
|
||||
describe("layoutSheetHome", () => {
|
||||
it("orders thinking slider, then inline selects, then one card of rows, then mode", () => {
|
||||
const speed = select("speed", { choices: choices("Normal", "Flex", "Fast", "Ultrafast") });
|
||||
const blocks = layoutSheetHome({
|
||||
thinkingItems: [claudeThinking],
|
||||
featureItems: [toggle("plan"), speed, action("review")],
|
||||
modeChoiceCount: 3,
|
||||
});
|
||||
expect(blocks.map((block) => block.kind)).toEqual(["slider", "pills", "rows", "mode"]);
|
||||
expect(blocks[2]).toMatchObject({
|
||||
kind: "rows",
|
||||
rows: [
|
||||
{ layout: "switch", item: { id: "plan" } },
|
||||
{ layout: "action", item: { id: "review" } },
|
||||
],
|
||||
});
|
||||
expect(blocks[3]).toEqual({ kind: "mode", layout: "radioList" });
|
||||
});
|
||||
|
||||
it("puts a select that needs its own page in the card of rows", () => {
|
||||
const branch = select("branch", { choices: choices("main"), searchable: true });
|
||||
expect(
|
||||
layoutSheetHome({ thinkingItems: [], featureItems: [branch], modeChoiceCount: 0 }),
|
||||
).toEqual([{ kind: "rows", rows: [{ layout: "subpage", item: branch }] }]);
|
||||
});
|
||||
|
||||
it("moves a long mode list to its own page", () => {
|
||||
expect(layoutSheetHome({ thinkingItems: [], featureItems: [], modeChoiceCount: 8 })).toEqual([
|
||||
{ kind: "mode", layout: "subpage" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,159 @@
|
||||
import type { ComposerControlChoice, ComposerControlItem } from "./composer-control";
|
||||
|
||||
/**
|
||||
* How a control draws on the agent settings sheet's home page. Everything a phone can set in one
|
||||
* tap stays on the page; only a list too long or too open-ended to scan moves to a page of its own.
|
||||
*/
|
||||
export type SheetControlLayout = "switch" | "action" | "slider" | "pills" | "radioList" | "subpage";
|
||||
|
||||
type SelectItem = Extract<ComposerControlItem, { type: "select" }>;
|
||||
|
||||
/** More choices than this read as a list to search, not a set to scan. */
|
||||
const MAX_INLINE_CHOICES = 7;
|
||||
/** A longer label wraps a pill row into a ragged block; a list reads better. */
|
||||
const MAX_PILL_LABEL_LENGTH = 12;
|
||||
/** Ordered thinking scales can span up to 8 stops (e.g. Auto, Off, Minimal..Max). */
|
||||
const MIN_SLIDER_CHOICES = 3;
|
||||
const MAX_SLIDER_CHOICES = 8;
|
||||
|
||||
const THINKING_LEVEL_RANKS: Readonly<Record<string, number>> = {
|
||||
auto: 0,
|
||||
none: 1,
|
||||
off: 1,
|
||||
disabled: 1,
|
||||
minimal: 2,
|
||||
min: 2,
|
||||
light: 2,
|
||||
low: 3,
|
||||
medium: 4,
|
||||
med: 4,
|
||||
balanced: 4,
|
||||
normal: 4,
|
||||
default: 4,
|
||||
high: 5,
|
||||
deep: 5,
|
||||
xhigh: 6,
|
||||
extrahigh: 6,
|
||||
veryhigh: 6,
|
||||
max: 7,
|
||||
maximum: 7,
|
||||
extreme: 7,
|
||||
ultra: 7,
|
||||
};
|
||||
|
||||
const NUMERIC_BUDGET_PATTERN = /^(\d+(?:\.\d+)?)(k|m)?$/;
|
||||
|
||||
function normalizeRankToken(raw: string): string {
|
||||
return raw
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[\s_-]+/g, "");
|
||||
}
|
||||
|
||||
function resolveEffortRank(choice: ComposerControlChoice): number | null {
|
||||
return (
|
||||
THINKING_LEVEL_RANKS[normalizeRankToken(choice.value)] ??
|
||||
THINKING_LEVEL_RANKS[normalizeRankToken(choice.label)] ??
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
function resolveNumericBudget(raw: string): number | null {
|
||||
const token = normalizeRankToken(raw)
|
||||
.replace(/tokens?$/i, "")
|
||||
.replace(/,/g, "");
|
||||
if (token === "off" || token === "none" || token === "disabled") return 0;
|
||||
const match = NUMERIC_BUDGET_PATTERN.exec(token);
|
||||
if (!match) return null;
|
||||
const base = Number(match[1]);
|
||||
if (!Number.isFinite(base)) return null;
|
||||
if (match[2] === "k") return base * 1_000;
|
||||
if (match[2] === "m") return base * 1_000_000;
|
||||
return base;
|
||||
}
|
||||
|
||||
function isStrictlyIncreasing(values: readonly (number | null)[]): boolean {
|
||||
let prev = -Infinity;
|
||||
for (const value of values) {
|
||||
if (value === null || value <= prev) return false;
|
||||
prev = value;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** True when a thinking select's choices form a recognized, strictly increasing scale. */
|
||||
export function isOrderedThinkingRange(choices: readonly ComposerControlChoice[]): boolean {
|
||||
if (choices.length < MIN_SLIDER_CHOICES || choices.length > MAX_SLIDER_CHOICES) return false;
|
||||
if (choices.some((choice) => Boolean(choice.description))) return false;
|
||||
if (isStrictlyIncreasing(choices.map(resolveEffortRank))) return true;
|
||||
return isStrictlyIncreasing(
|
||||
choices.map(
|
||||
(choice) => resolveNumericBudget(choice.value) ?? resolveNumericBudget(choice.label),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export function classifySheetControl(control: ComposerControlItem): SheetControlLayout {
|
||||
if (control.type === "toggle") return "switch";
|
||||
if (control.type === "action") return "action";
|
||||
if (control.searchable || control.remoteSearch) {
|
||||
return "subpage";
|
||||
}
|
||||
if (control.id === "thinking" && isOrderedThinkingRange(control.choices)) {
|
||||
return "slider";
|
||||
}
|
||||
if (control.choices.length > MAX_INLINE_CHOICES) {
|
||||
return "subpage";
|
||||
}
|
||||
const fitsPills = control.choices.every(
|
||||
(choice) => !choice.description && choice.label.length <= MAX_PILL_LABEL_LENGTH,
|
||||
);
|
||||
return fitsPills ? "pills" : "radioList";
|
||||
}
|
||||
|
||||
export interface SheetHomeRow {
|
||||
layout: Extract<SheetControlLayout, "switch" | "action" | "subpage">;
|
||||
item: ComposerControlItem;
|
||||
}
|
||||
|
||||
export type SheetHomeBlock =
|
||||
| { kind: "slider"; item: SelectItem }
|
||||
| { kind: "pills"; item: SelectItem }
|
||||
| { kind: "radioList"; item: SelectItem }
|
||||
| { kind: "rows"; rows: SheetHomeRow[] }
|
||||
| { kind: "mode"; layout: "radioList" | "subpage" };
|
||||
|
||||
/**
|
||||
* The home page, top to bottom: thinking, the selects that fit inline, one card holding every
|
||||
* switch, action and row that opens a page, then mode. Mode is a list with icons, so it never
|
||||
* becomes pills.
|
||||
*/
|
||||
export function layoutSheetHome(input: {
|
||||
thinkingItems: readonly ComposerControlItem[];
|
||||
featureItems: readonly ComposerControlItem[];
|
||||
/** 0 when the agent has no modes. */
|
||||
modeChoiceCount: number;
|
||||
}): SheetHomeBlock[] {
|
||||
const inline: SheetHomeBlock[] = [];
|
||||
const rows: SheetHomeRow[] = [];
|
||||
for (const item of [...input.thinkingItems, ...input.featureItems]) {
|
||||
const layout = classifySheetControl(item);
|
||||
if (
|
||||
item.type === "select" &&
|
||||
(layout === "slider" || layout === "pills" || layout === "radioList")
|
||||
) {
|
||||
inline.push({ kind: layout, item });
|
||||
} else if (layout !== "slider" && layout !== "pills" && layout !== "radioList") {
|
||||
rows.push({ layout, item });
|
||||
}
|
||||
}
|
||||
const blocks: SheetHomeBlock[] = [...inline];
|
||||
if (rows.length > 0) blocks.push({ kind: "rows", rows });
|
||||
if (input.modeChoiceCount > 0) {
|
||||
blocks.push({
|
||||
kind: "mode",
|
||||
layout: input.modeChoiceCount > MAX_INLINE_CHOICES ? "subpage" : "radioList",
|
||||
});
|
||||
}
|
||||
return blocks;
|
||||
}
|
||||
@@ -0,0 +1,719 @@
|
||||
import { useCallback, useMemo, useState, type ReactElement, type ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Text, View, type PressableStateCallbackType } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { Check } from "lucide-react-native";
|
||||
import { getModeVisuals, type AgentProviderDefinition } from "@getpaseo/protocol/provider-manifest";
|
||||
import type { AgentMode } from "@getpaseo/protocol/agent-types";
|
||||
import { getAgentModeOptionIcon } from "@/agent-controls/icons";
|
||||
import { formatAgentModeLabel } from "@/agent-controls/labels";
|
||||
import {
|
||||
SettingsCard,
|
||||
SettingsDetailRow,
|
||||
SettingsSection,
|
||||
SettingsSwitch,
|
||||
} from "@/components/settings";
|
||||
import type { ComboboxOption } from "@/components/ui/combobox";
|
||||
import { foregroundIconColorMapping } from "@/components/ui/icon-color";
|
||||
import { PressHighlight } from "@/components/ui/press-highlight";
|
||||
import { ScrollView as SheetScrollView } from "@/components/ui/scroll-view";
|
||||
import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control";
|
||||
import { SteppedSlider, type SteppedSliderOption } from "@/components/ui/stepped-slider";
|
||||
import { isNative } from "@/constants/platform";
|
||||
import { ICON_SIZE } from "@/styles/theme";
|
||||
import {
|
||||
ComposerControlIcon,
|
||||
usePendingRun,
|
||||
type ComposerControlChoice,
|
||||
type ComposerControlItem,
|
||||
} from "./composer-control";
|
||||
import type { AgentModeControlValue } from "./mode-control";
|
||||
import { layoutSheetHome, type SheetHomeBlock, type SheetHomeRow } from "./sheet-control-layout";
|
||||
|
||||
const ThemedCheck = withUnistyles(Check);
|
||||
const KEYBOARD_DISMISS_MODE = isNative ? "on-drag" : "none";
|
||||
|
||||
/** The controls the agent settings sheet draws on its Home page, by kind. */
|
||||
export interface AgentSheetControls {
|
||||
thinkingItems: readonly ComposerControlItem[];
|
||||
featureItems: readonly ComposerControlItem[];
|
||||
modeControl: AgentModeControlValue | null;
|
||||
}
|
||||
|
||||
/** The select page id of the agent's mode, beside the ids of the composer controls. */
|
||||
export const AGENT_SHEET_MODE_CONTROL_ID = "mode";
|
||||
|
||||
type SelectItem = Extract<ComposerControlItem, { type: "select" }>;
|
||||
|
||||
/**
|
||||
* Home: the Model row, then every control laid out in place: short choices as pills,
|
||||
* longer ones as a radio list, switches and actions as rows. Only a list too long to scan opens
|
||||
* a page of its own.
|
||||
*/
|
||||
export function AgentSheetHome({
|
||||
controls,
|
||||
disabled,
|
||||
topCard,
|
||||
footer,
|
||||
onOpenSelect,
|
||||
}: {
|
||||
controls: AgentSheetControls;
|
||||
disabled: boolean;
|
||||
/** The Model row. */
|
||||
topCard: ReactNode;
|
||||
/** Drawn after the controls, such as plugin items. */
|
||||
footer?: ReactNode;
|
||||
onOpenSelect: (controlId: string) => void;
|
||||
}) {
|
||||
const { thinkingItems, featureItems, modeControl } = controls;
|
||||
const blocks = useMemo(
|
||||
() =>
|
||||
layoutSheetHome({
|
||||
thinkingItems,
|
||||
featureItems,
|
||||
modeChoiceCount: modeControl?.modeOptions.length ?? 0,
|
||||
}),
|
||||
[featureItems, modeControl?.modeOptions.length, thinkingItems],
|
||||
);
|
||||
return (
|
||||
<SheetScrollView
|
||||
style={styles.page}
|
||||
keyboardShouldPersistTaps="handled"
|
||||
keyboardDismissMode={KEYBOARD_DISMISS_MODE}
|
||||
showsVerticalScrollIndicator={false}
|
||||
testID="agent-controls-settings-list"
|
||||
>
|
||||
{/* Themed insets sit on a View: the sheet scroller drops a themed contentContainerStyle on web. */}
|
||||
<View style={styles.content}>
|
||||
<View style={styles.block}>{topCard}</View>
|
||||
{blocks.map((block) => (
|
||||
<HomeBlock
|
||||
key={blockKey(block)}
|
||||
block={block}
|
||||
modeControl={modeControl}
|
||||
disabled={disabled}
|
||||
onOpenSelect={onOpenSelect}
|
||||
/>
|
||||
))}
|
||||
{footer}
|
||||
</View>
|
||||
</SheetScrollView>
|
||||
);
|
||||
}
|
||||
|
||||
function blockKey(block: SheetHomeBlock): string {
|
||||
switch (block.kind) {
|
||||
case "slider":
|
||||
case "pills":
|
||||
case "radioList":
|
||||
return `${block.kind}:${block.item.id}`;
|
||||
case "rows":
|
||||
return "rows";
|
||||
case "mode":
|
||||
return "mode";
|
||||
}
|
||||
}
|
||||
|
||||
function HomeBlock({
|
||||
block,
|
||||
modeControl,
|
||||
disabled,
|
||||
onOpenSelect,
|
||||
}: {
|
||||
block: SheetHomeBlock;
|
||||
modeControl: AgentModeControlValue | null;
|
||||
disabled: boolean;
|
||||
onOpenSelect: (controlId: string) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const sectionLeading = useMemo(
|
||||
() =>
|
||||
block.kind === "pills" || block.kind === "radioList" ? (
|
||||
<ComposerControlIcon item={block.item} size={ICON_SIZE.sm} />
|
||||
) : undefined,
|
||||
[block],
|
||||
);
|
||||
switch (block.kind) {
|
||||
case "slider":
|
||||
return (
|
||||
<View style={styles.block}>
|
||||
<SettingsCard>
|
||||
<SliderControl item={block.item} disabled={disabled} />
|
||||
</SettingsCard>
|
||||
</View>
|
||||
);
|
||||
case "pills":
|
||||
return (
|
||||
<SettingsSection
|
||||
title={block.item.title}
|
||||
leading={sectionLeading}
|
||||
flush
|
||||
style={styles.block}
|
||||
testID={block.item.testID ? `${block.item.testID}-section` : undefined}
|
||||
>
|
||||
<SettingsCard>
|
||||
<PillsControl item={block.item} disabled={disabled} />
|
||||
</SettingsCard>
|
||||
</SettingsSection>
|
||||
);
|
||||
case "radioList":
|
||||
return (
|
||||
<SettingsSection
|
||||
title={block.item.title}
|
||||
leading={sectionLeading}
|
||||
flush
|
||||
style={styles.block}
|
||||
testID={block.item.testID ? `${block.item.testID}-section` : undefined}
|
||||
>
|
||||
<SettingsCard testID={block.item.testID}>
|
||||
{block.item.choices.map((choice) => (
|
||||
<SelectChoiceRow
|
||||
key={choice.value}
|
||||
item={block.item}
|
||||
choice={choice}
|
||||
disabled={disabled}
|
||||
/>
|
||||
))}
|
||||
</SettingsCard>
|
||||
</SettingsSection>
|
||||
);
|
||||
case "rows":
|
||||
return (
|
||||
<View style={styles.block}>
|
||||
<SettingsCard>
|
||||
{block.rows.map((row) => (
|
||||
<ControlRow
|
||||
key={row.item.id}
|
||||
row={row}
|
||||
disabled={disabled}
|
||||
onOpenSelect={onOpenSelect}
|
||||
/>
|
||||
))}
|
||||
</SettingsCard>
|
||||
</View>
|
||||
);
|
||||
case "mode":
|
||||
if (!modeControl) return null;
|
||||
if (block.layout === "subpage") {
|
||||
return (
|
||||
<View style={styles.block}>
|
||||
<SettingsCard>
|
||||
<ModeSummaryRow modeControl={modeControl} onOpenSelect={onOpenSelect} />
|
||||
</SettingsCard>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<SettingsSection title={t("agentControls.mode.title")} flush style={styles.block}>
|
||||
<SettingsCard testID="mode-control">
|
||||
{modeControl.modeOptions.map((mode) => (
|
||||
<ModeRadioRow key={mode.id} mode={mode} modeControl={modeControl} />
|
||||
))}
|
||||
</SettingsCard>
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function SliderControl({ item, disabled }: { item: SelectItem; disabled: boolean }) {
|
||||
const { pending, run } = usePendingRun();
|
||||
const [previewValue, setPreviewValue] = useState<string | null>(null);
|
||||
const options = useMemo<SteppedSliderOption<string>[]>(
|
||||
() =>
|
||||
item.choices.map((choice) => ({
|
||||
value: choice.value,
|
||||
label: choice.label,
|
||||
testID: item.testID ? `${item.testID}-${choice.value}` : undefined,
|
||||
})),
|
||||
[item.choices, item.testID],
|
||||
);
|
||||
const handleChange = useCallback((value: string) => run(() => item.onChange(value)), [item, run]);
|
||||
const displayedValue = previewValue ?? item.value;
|
||||
const displayedLabel =
|
||||
item.choices.find((choice) => choice.value === displayedValue)?.label ??
|
||||
item.valueLabel ??
|
||||
item.title;
|
||||
|
||||
return (
|
||||
<View style={styles.sliderCard}>
|
||||
<View style={styles.sliderHeader}>
|
||||
<View style={styles.sliderLeading}>
|
||||
<ComposerControlIcon item={item} size={ICON_SIZE.md} />
|
||||
</View>
|
||||
<Text style={styles.sliderTitle} numberOfLines={1}>
|
||||
{item.title}
|
||||
</Text>
|
||||
<Text style={styles.sliderValue} numberOfLines={1}>
|
||||
{displayedLabel}
|
||||
</Text>
|
||||
</View>
|
||||
<SteppedSlider
|
||||
options={options}
|
||||
value={item.value}
|
||||
onValueChange={handleChange}
|
||||
onPreviewChange={setPreviewValue}
|
||||
disabled={disabled || pending}
|
||||
accessibilityLabel={item.accessibilityLabel ?? item.title}
|
||||
testID={item.testID}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function PillsControl({ item, disabled }: { item: SelectItem; disabled: boolean }) {
|
||||
const { pending, run } = usePendingRun();
|
||||
const options = useMemo<SegmentedControlOption<string>[]>(
|
||||
() =>
|
||||
item.choices.map((choice) => ({
|
||||
value: choice.value,
|
||||
label: choice.label,
|
||||
disabled: disabled || pending,
|
||||
testID: item.testID ? `${item.testID}-${choice.value}` : undefined,
|
||||
})),
|
||||
[disabled, item.choices, item.testID, pending],
|
||||
);
|
||||
const handleChange = useCallback((value: string) => run(() => item.onChange(value)), [item, run]);
|
||||
return (
|
||||
<View style={styles.pills}>
|
||||
<SegmentedControl
|
||||
options={options}
|
||||
value={item.value}
|
||||
onValueChange={handleChange}
|
||||
wrap
|
||||
testID={item.testID}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function ControlRow({
|
||||
row,
|
||||
disabled,
|
||||
onOpenSelect,
|
||||
}: {
|
||||
row: SheetHomeRow;
|
||||
disabled: boolean;
|
||||
onOpenSelect: (controlId: string) => void;
|
||||
}) {
|
||||
const { item } = row;
|
||||
const { pending, run } = usePendingRun();
|
||||
const leading = useMemo(() => <ComposerControlIcon item={item} size={ICON_SIZE.md} />, [item]);
|
||||
const handleToggle = useCallback(
|
||||
(value: boolean) => {
|
||||
if (item.type === "toggle") run(() => item.onChange(value));
|
||||
},
|
||||
[item, run],
|
||||
);
|
||||
const handlePress = useCallback(() => {
|
||||
if (item.type === "action") run(item.onPress);
|
||||
else onOpenSelect(item.id);
|
||||
}, [item, onOpenSelect, run]);
|
||||
|
||||
if (item.type === "toggle") {
|
||||
return (
|
||||
<SettingsSwitch
|
||||
label={item.title}
|
||||
leading={leading}
|
||||
value={item.value}
|
||||
onValueChange={handleToggle}
|
||||
disabled={disabled || pending}
|
||||
testID={item.testID}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<SettingsDetailRow
|
||||
label={item.title}
|
||||
leading={leading}
|
||||
summary={item.type === "select" ? selectValueLabel(item) : undefined}
|
||||
onPress={handlePress}
|
||||
disabled={disabled || pending}
|
||||
accessibilityLabel={item.accessibilityLabel}
|
||||
testID={item.testID}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function selectValueLabel(item: SelectItem): string {
|
||||
return (
|
||||
item.choices.find((choice) => choice.value === item.value)?.label ??
|
||||
item.valueLabel ??
|
||||
item.title
|
||||
);
|
||||
}
|
||||
|
||||
/** One choice of a select, picked in place. */
|
||||
export function SelectChoiceRow({
|
||||
item,
|
||||
choice,
|
||||
disabled,
|
||||
onPicked,
|
||||
}: {
|
||||
item: SelectItem;
|
||||
choice: ComposerControlChoice;
|
||||
disabled: boolean;
|
||||
onPicked?: () => void;
|
||||
}): ReactElement {
|
||||
const { pending, run } = usePendingRun();
|
||||
const option = useMemo<ComboboxOption>(
|
||||
() => ({ id: choice.value, label: choice.label, description: choice.description }),
|
||||
[choice],
|
||||
);
|
||||
const selected = option.id === (item.value ?? "");
|
||||
const handlePress = useCallback(() => {
|
||||
run(() => item.onChange(option.id));
|
||||
onPicked?.();
|
||||
}, [item, onPicked, option.id, run]);
|
||||
if (item.renderOption) {
|
||||
return item.renderOption({ option, selected, active: false, onPress: handlePress });
|
||||
}
|
||||
return (
|
||||
<SheetRadioRow
|
||||
label={option.label}
|
||||
hint={option.description}
|
||||
selected={selected}
|
||||
disabled={disabled || pending}
|
||||
onPress={handlePress}
|
||||
testID={item.testID ? `${item.testID}-${option.id}` : undefined}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function ModeSummaryRow({
|
||||
modeControl,
|
||||
onOpenSelect,
|
||||
}: {
|
||||
modeControl: AgentModeControlValue;
|
||||
onOpenSelect: (controlId: string) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const selected = findSelectedMode(modeControl);
|
||||
const Icon = selected
|
||||
? getAgentModeOptionIcon(modeControl.provider, selected.id, modeControl.providerDefinitions)
|
||||
: undefined;
|
||||
const leading = useMemo(
|
||||
() => (Icon ? <Icon size={ICON_SIZE.md} color={styles.iconMuted.color} /> : undefined),
|
||||
[Icon],
|
||||
);
|
||||
const handlePress = useCallback(() => onOpenSelect(AGENT_SHEET_MODE_CONTROL_ID), [onOpenSelect]);
|
||||
return (
|
||||
<SettingsDetailRow
|
||||
label={t("agentControls.mode.title")}
|
||||
leading={leading}
|
||||
summary={selected ? formatAgentModeLabel(selected) : undefined}
|
||||
onPress={handlePress}
|
||||
disabled={modeControl.disabled}
|
||||
testID="mode-control"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function findSelectedMode(modeControl: AgentModeControlValue): AgentMode | null {
|
||||
return (
|
||||
modeControl.modeOptions.find((mode) => mode.id === modeControl.selectedModeId) ??
|
||||
modeControl.modeOptions[0] ??
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
/** A mode that runs tools without asking reads in the warning colour, so it is never picked by accident. */
|
||||
function isUnattendedMode(
|
||||
mode: AgentMode,
|
||||
provider: string,
|
||||
providerDefinitions: AgentProviderDefinition[],
|
||||
): boolean {
|
||||
const tier = getModeVisuals(provider, mode.id, providerDefinitions)?.colorTier ?? mode.colorTier;
|
||||
return tier === "dangerous";
|
||||
}
|
||||
|
||||
/** One of the agent's modes, picked in place. */
|
||||
export function ModeRadioRow({
|
||||
mode,
|
||||
modeControl,
|
||||
onPicked,
|
||||
}: {
|
||||
mode: AgentMode;
|
||||
modeControl: AgentModeControlValue;
|
||||
onPicked?: () => void;
|
||||
}) {
|
||||
const { provider, providerDefinitions, onSelectMode } = modeControl;
|
||||
const selected = findSelectedMode(modeControl)?.id === mode.id;
|
||||
const warning = isUnattendedMode(mode, provider, providerDefinitions);
|
||||
const Icon = getAgentModeOptionIcon(provider, mode.id, providerDefinitions);
|
||||
const leading = useMemo(
|
||||
() =>
|
||||
Icon ? (
|
||||
<Icon
|
||||
size={ICON_SIZE.md}
|
||||
color={warning ? styles.iconWarning.color : styles.iconMuted.color}
|
||||
/>
|
||||
) : undefined,
|
||||
[Icon, warning],
|
||||
);
|
||||
const handlePress = useCallback(() => {
|
||||
onSelectMode(mode.id);
|
||||
onPicked?.();
|
||||
}, [mode.id, onPicked, onSelectMode]);
|
||||
return (
|
||||
<SheetRadioRow
|
||||
label={formatAgentModeLabel(mode)}
|
||||
leading={leading}
|
||||
tone={warning ? "warning" : "default"}
|
||||
selected={selected}
|
||||
disabled={modeControl.disabled === true}
|
||||
onPress={handlePress}
|
||||
testID={`mode-option-${mode.id}`}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/** A row of a settings card that picks one of several values; the picked one carries a check. */
|
||||
function SheetRadioRow({
|
||||
label,
|
||||
hint,
|
||||
leading,
|
||||
tone = "default",
|
||||
selected,
|
||||
disabled,
|
||||
onPress,
|
||||
testID,
|
||||
}: {
|
||||
label: string;
|
||||
hint?: string;
|
||||
leading?: ReactNode;
|
||||
tone?: "default" | "warning";
|
||||
selected: boolean;
|
||||
disabled: boolean;
|
||||
onPress: () => void;
|
||||
testID?: string;
|
||||
}) {
|
||||
const accessibilityState = useMemo(() => ({ checked: selected, disabled }), [disabled, selected]);
|
||||
const rowStyle = useCallback(
|
||||
({ hovered }: PressableStateCallbackType & { hovered?: boolean }) => [
|
||||
styles.radioRow,
|
||||
Boolean(hovered) && !disabled && styles.radioRowHovered,
|
||||
disabled && styles.radioRowDisabled,
|
||||
],
|
||||
[disabled],
|
||||
);
|
||||
return (
|
||||
<PressHighlight
|
||||
accessibilityRole="radio"
|
||||
accessibilityLabel={label}
|
||||
accessibilityState={accessibilityState}
|
||||
aria-checked={selected}
|
||||
disabled={disabled}
|
||||
onPress={onPress}
|
||||
style={rowStyle}
|
||||
highlightStyle={styles.radioRowPressed}
|
||||
testID={testID}
|
||||
>
|
||||
{leading ? <View style={styles.radioLeading}>{leading}</View> : null}
|
||||
<View style={styles.radioLabel}>
|
||||
<Text
|
||||
style={[styles.radioTitle, tone === "warning" && styles.radioTitleWarning]}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{label}
|
||||
</Text>
|
||||
{hint ? (
|
||||
<Text style={styles.radioHint} numberOfLines={2}>
|
||||
{hint}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
<View style={styles.checkSlot}>
|
||||
{selected ? (
|
||||
<ThemedCheck size={ICON_SIZE.sm} uniProps={foregroundIconColorMapping} />
|
||||
) : null}
|
||||
</View>
|
||||
</PressHighlight>
|
||||
);
|
||||
}
|
||||
|
||||
/** A page that lists one select's choices, or the agent's modes, for a list too long for Home. */
|
||||
export function AgentSheetSelectPage({
|
||||
controlId,
|
||||
controls,
|
||||
query,
|
||||
disabled,
|
||||
onPicked,
|
||||
}: {
|
||||
controlId: string;
|
||||
controls: AgentSheetControls;
|
||||
query: string;
|
||||
disabled: boolean;
|
||||
onPicked: () => void;
|
||||
}) {
|
||||
const { modeControl } = controls;
|
||||
const item = useMemo(
|
||||
() =>
|
||||
[...controls.thinkingItems, ...controls.featureItems].find(
|
||||
(candidate): candidate is SelectItem =>
|
||||
candidate.id === controlId && candidate.type === "select",
|
||||
) ?? null,
|
||||
[controlId, controls.featureItems, controls.thinkingItems],
|
||||
);
|
||||
const normalizedQuery = query.trim().toLowerCase();
|
||||
let rows: ReactNode = null;
|
||||
if (controlId === AGENT_SHEET_MODE_CONTROL_ID && modeControl) {
|
||||
rows = modeControl.modeOptions
|
||||
.filter((mode) => formatAgentModeLabel(mode).toLowerCase().includes(normalizedQuery))
|
||||
.map((mode) => (
|
||||
<ModeRadioRow key={mode.id} mode={mode} modeControl={modeControl} onPicked={onPicked} />
|
||||
));
|
||||
} else if (item) {
|
||||
const choices =
|
||||
item.remoteSearch || !normalizedQuery
|
||||
? item.choices
|
||||
: item.choices.filter((choice) => choice.label.toLowerCase().includes(normalizedQuery));
|
||||
rows = choices.map((choice) => (
|
||||
<SelectChoiceRow
|
||||
key={choice.value}
|
||||
item={item}
|
||||
choice={choice}
|
||||
disabled={disabled}
|
||||
onPicked={onPicked}
|
||||
/>
|
||||
));
|
||||
}
|
||||
const empty = !rows || (Array.isArray(rows) && rows.length === 0);
|
||||
return (
|
||||
<SheetScrollView
|
||||
style={styles.page}
|
||||
keyboardShouldPersistTaps="handled"
|
||||
keyboardDismissMode={KEYBOARD_DISMISS_MODE}
|
||||
showsVerticalScrollIndicator={false}
|
||||
testID="agent-controls-select-page"
|
||||
>
|
||||
<View style={styles.content}>
|
||||
{empty ? (
|
||||
<Text style={styles.empty}>{item?.emptyText ?? ""}</Text>
|
||||
) : (
|
||||
<SettingsCard>{rows}</SettingsCard>
|
||||
)}
|
||||
</View>
|
||||
</SheetScrollView>
|
||||
);
|
||||
}
|
||||
|
||||
/** Whether a select page offers a search: the mode list and searchable selects do. */
|
||||
export function selectPageIsSearchable(controlId: string, controls: AgentSheetControls): boolean {
|
||||
if (controlId === AGENT_SHEET_MODE_CONTROL_ID) return true;
|
||||
const item = [...controls.thinkingItems, ...controls.featureItems].find(
|
||||
(candidate) => candidate.id === controlId,
|
||||
);
|
||||
return item?.type === "select" && (item.searchable === true || item.remoteSearch === true);
|
||||
}
|
||||
|
||||
/** The title of a select page. */
|
||||
export function selectPageTitle(
|
||||
controlId: string,
|
||||
controls: AgentSheetControls,
|
||||
modeTitle: string,
|
||||
): string {
|
||||
if (controlId === AGENT_SHEET_MODE_CONTROL_ID) return modeTitle;
|
||||
return (
|
||||
[...controls.thinkingItems, ...controls.featureItems].find(
|
||||
(candidate) => candidate.id === controlId,
|
||||
)?.title ?? ""
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
page: {
|
||||
flex: 1,
|
||||
minHeight: 0,
|
||||
},
|
||||
content: {
|
||||
paddingHorizontal: theme.spacing[4],
|
||||
paddingTop: theme.spacing[2],
|
||||
paddingBottom: theme.spacing[6],
|
||||
},
|
||||
block: {
|
||||
marginBottom: theme.spacing[4],
|
||||
},
|
||||
pills: {
|
||||
padding: theme.spacing[2],
|
||||
},
|
||||
sliderCard: {
|
||||
paddingHorizontal: theme.spacing[4],
|
||||
paddingTop: theme.spacing[3],
|
||||
paddingBottom: theme.spacing[3],
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
sliderHeader: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
},
|
||||
sliderLeading: {
|
||||
marginRight: theme.spacing[3],
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
sliderTitle: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.base,
|
||||
},
|
||||
sliderValue: {
|
||||
marginLeft: theme.spacing[3],
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
},
|
||||
radioRow: {
|
||||
minHeight: 44,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
paddingHorizontal: theme.spacing[4],
|
||||
paddingVertical: theme.spacing[2],
|
||||
},
|
||||
radioRowHovered: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
},
|
||||
radioRowPressed: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
},
|
||||
radioRowDisabled: {
|
||||
opacity: theme.opacity[50],
|
||||
},
|
||||
radioLeading: {
|
||||
marginRight: theme.spacing[3],
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
radioLabel: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
},
|
||||
radioTitle: {
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.base,
|
||||
},
|
||||
radioTitleWarning: {
|
||||
color: theme.colors.statusWarning,
|
||||
},
|
||||
radioHint: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
marginTop: theme.spacing[1],
|
||||
},
|
||||
checkSlot: {
|
||||
width: ICON_SIZE.sm,
|
||||
marginLeft: theme.spacing[3],
|
||||
alignItems: "center",
|
||||
},
|
||||
iconMuted: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
},
|
||||
iconWarning: {
|
||||
color: theme.colors.statusWarning,
|
||||
},
|
||||
empty: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
textAlign: "center",
|
||||
paddingVertical: theme.spacing[6],
|
||||
},
|
||||
}));
|
||||
@@ -155,6 +155,39 @@ describe("resolveAgentModelSelection", () => {
|
||||
expect(selection.selectedThinkingId).toBe("high");
|
||||
});
|
||||
|
||||
it("lists and selects the agent's thinking level when the model does not list it", () => {
|
||||
const selection = resolveAgentModelSelection({
|
||||
models: [
|
||||
{
|
||||
id: "opus",
|
||||
provider: "claude",
|
||||
label: "opus",
|
||||
thinkingOptions: [
|
||||
{ id: "low", label: "Low" },
|
||||
{ id: "medium", label: "Medium" },
|
||||
{ id: "high", label: "High", isDefault: true },
|
||||
{ id: "max", label: "Max" },
|
||||
],
|
||||
defaultThinkingOptionId: "high",
|
||||
},
|
||||
],
|
||||
runtimeModelId: "opus",
|
||||
configuredModelId: "opus",
|
||||
runtimeThinkingOptionId: null,
|
||||
explicitThinkingOptionId: "xhigh",
|
||||
});
|
||||
|
||||
expect(selection.selectedThinkingId).toBe("xhigh");
|
||||
expect(selection.displayThinking).toBe("Extra high");
|
||||
expect(selection.thinkingOptions?.map((option) => option.id)).toEqual([
|
||||
"low",
|
||||
"medium",
|
||||
"high",
|
||||
"max",
|
||||
"xhigh",
|
||||
]);
|
||||
});
|
||||
|
||||
it("formats raw thinking labels in the selected model display", () => {
|
||||
const selection = resolveAgentModelSelection({
|
||||
models: [
|
||||
|
||||
@@ -130,6 +130,21 @@ function resolveEffectiveThinking(
|
||||
return selectedThinking ?? thinkingOptions?.[0] ?? null;
|
||||
}
|
||||
|
||||
// The agent runs on its level even when the model's list leaves it out. The level joins the
|
||||
// list, so the controls show and check it and none of them falls back to the first option.
|
||||
function includeResolvedThinkingOption(
|
||||
thinkingOptions: ThinkingOption[] | null,
|
||||
resolvedThinkingId: string | null,
|
||||
): ThinkingOption[] | null {
|
||||
if (!thinkingOptions || thinkingOptions.length === 0 || !resolvedThinkingId) {
|
||||
return thinkingOptions;
|
||||
}
|
||||
if (thinkingOptions.some((option) => option.id === resolvedThinkingId)) {
|
||||
return thinkingOptions;
|
||||
}
|
||||
return [...thinkingOptions, { id: resolvedThinkingId, label: resolvedThinkingId }];
|
||||
}
|
||||
|
||||
function resolveModelDisplay(
|
||||
selectedModel: AgentModelDefinition | null,
|
||||
preferredModelId: string | null,
|
||||
@@ -192,12 +207,15 @@ export function resolveAgentModelSelection(input: {
|
||||
i18n.t("agentControls.model.unknown"),
|
||||
);
|
||||
|
||||
const thinkingOptions = selectedModel?.thinkingOptions ?? null;
|
||||
const resolvedThinkingId = resolveThinkingId(
|
||||
runtimeThinkingOptionId,
|
||||
explicitThinkingOptionId,
|
||||
selectedModel,
|
||||
);
|
||||
const thinkingOptions = includeResolvedThinkingOption(
|
||||
selectedModel?.thinkingOptions ?? null,
|
||||
resolvedThinkingId,
|
||||
);
|
||||
const effectiveThinking = resolveEffectiveThinking(thinkingOptions, resolvedThinkingId);
|
||||
const selectedThinkingId = effectiveThinking?.id ?? resolvedThinkingId;
|
||||
const displayThinking = resolveThinkingDisplay(
|
||||
|
||||
@@ -329,6 +329,7 @@ function renderLeftContent(args: RenderLeftContentArgs): ReactElement | null {
|
||||
return (
|
||||
<DraftAgentControls
|
||||
{...agentControls}
|
||||
onDropdownClose={agentControls.onDropdownClose ?? focusInput}
|
||||
draftId={agentId}
|
||||
serverId={serverId}
|
||||
isCompactLayout={isCompactLayout}
|
||||
|
||||
@@ -110,6 +110,7 @@ import {
|
||||
applyDictationTranscript,
|
||||
computeCanStartDictation,
|
||||
resolveAlternateSendAction,
|
||||
resolveComposerFramePhase,
|
||||
resolveComposerSurfacePresentation,
|
||||
resolveComposerSurfaceText,
|
||||
resolveMessageInputEnterAction,
|
||||
@@ -1368,6 +1369,8 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
const dictationToggleKeys = useShortcutKeys("dictation-toggle");
|
||||
const focusInputKeys = useShortcutKeys("focus-message-input");
|
||||
const [isInputFocused, setIsInputFocused] = useState(false);
|
||||
// Only the frame's pointer events set it, so hover stays a web thing; see docs/hover.md.
|
||||
const [isInputHovered, setIsInputHovered] = useState(false);
|
||||
useKeyboardFocusSurface("message-input", isInputFocused && isPaneFocused);
|
||||
// Web text is DOM-owned between deferred draft publications. The action button only needs
|
||||
// this boundary, so publish empty/non-empty transitions without rerendering for every key.
|
||||
@@ -2038,15 +2041,32 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
void handleStopRealtimeVoice();
|
||||
}, [handleStopRealtimeVoice]);
|
||||
|
||||
const handleInputWrapperPointerEnter = useCallback(() => setIsInputHovered(true), []);
|
||||
const handleInputWrapperPointerLeave = useCallback(() => setIsInputHovered(false), []);
|
||||
const framePhase = resolveComposerFramePhase({
|
||||
hovered: isInputHovered,
|
||||
focused: isInputFocused,
|
||||
readOnly,
|
||||
disabled,
|
||||
});
|
||||
const inputWrapperCombinedStyle = useMemo(
|
||||
() => [
|
||||
styles.inputWrapper,
|
||||
Platform.OS !== "ios" && isCompact && !isFullscreen && styles.inputWrapperCompact,
|
||||
readOnly && styles.inputWrapperReadOnly,
|
||||
framePhase === "hover" && styles.inputWrapperHovered,
|
||||
framePhase === "active" && styles.inputWrapperFocused,
|
||||
inputWrapperStyle,
|
||||
{ opacity: surfacePresentation.input.opacity },
|
||||
],
|
||||
[inputWrapperStyle, isCompact, isFullscreen, readOnly, surfacePresentation.input.opacity],
|
||||
[
|
||||
framePhase,
|
||||
inputWrapperStyle,
|
||||
isCompact,
|
||||
isFullscreen,
|
||||
readOnly,
|
||||
surfacePresentation.input.opacity,
|
||||
],
|
||||
);
|
||||
// `withUnistyles` maps this component's `style` into a `.hash > *` child
|
||||
// rule, which ties on specificity with react-native-web's own
|
||||
@@ -2394,6 +2414,8 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
onExit={exitFullscreen}
|
||||
inputWrapperRef={inputWrapperRef}
|
||||
inputWrapperStyle={inputWrapperCombinedStyle}
|
||||
onInputWrapperPointerEnter={handleInputWrapperPointerEnter}
|
||||
onInputWrapperPointerLeave={handleInputWrapperPointerLeave}
|
||||
inputPointerEvents={surfacePresentation.input.pointerEvents}
|
||||
attachmentSlot={attachmentSlot}
|
||||
showFullscreenButton={shouldShowFullscreenControl(
|
||||
@@ -2448,6 +2470,15 @@ const styles = StyleSheet.create((theme: Theme) => ({
|
||||
inputWrapperReadOnly: {
|
||||
borderStyle: "dotted",
|
||||
},
|
||||
// The rest border is already the `borderAccent` that `controlHover` gives other inputs, so
|
||||
// hover steps up one surface; focus takes the accent, like their focus ring. Colour only:
|
||||
// the border width stays put, so the frame never shifts under the pointer.
|
||||
inputWrapperHovered: {
|
||||
borderColor: theme.colors.surface4,
|
||||
},
|
||||
inputWrapperFocused: {
|
||||
borderColor: theme.colors.accent,
|
||||
},
|
||||
// The band the fullscreen glyph sits in is the input's own padding, so a tap
|
||||
// anywhere in it (under the glyph, or where the glyph would be) is a tap on the
|
||||
// editor: it focuses, shows the keyboard, and places the caret. Reserved whether
|
||||
|
||||
@@ -37,6 +37,8 @@ export function ComposerInputPresentation({
|
||||
onExit,
|
||||
inputWrapperRef,
|
||||
inputWrapperStyle,
|
||||
onInputWrapperPointerEnter,
|
||||
onInputWrapperPointerLeave,
|
||||
inputPointerEvents,
|
||||
attachmentSlot,
|
||||
showFullscreenButton,
|
||||
@@ -53,6 +55,9 @@ export function ComposerInputPresentation({
|
||||
onExit: () => void;
|
||||
inputWrapperRef: Ref<View>;
|
||||
inputWrapperStyle: ViewProps["style"];
|
||||
/** Hover tracking for the frame's border; the frame is a plain View, per docs/hover.md. */
|
||||
onInputWrapperPointerEnter: () => void;
|
||||
onInputWrapperPointerLeave: () => void;
|
||||
inputPointerEvents: ViewProps["pointerEvents"];
|
||||
attachmentSlot: ReactNode;
|
||||
showFullscreenButton: boolean;
|
||||
@@ -107,6 +112,8 @@ export function ComposerInputPresentation({
|
||||
ref={inputWrapperRef}
|
||||
style={fullscreen ? styles.fullscreenInputWrapper : inputWrapperStyle}
|
||||
pointerEvents={inputPointerEvents}
|
||||
onPointerEnter={onInputWrapperPointerEnter}
|
||||
onPointerLeave={onInputWrapperPointerLeave}
|
||||
>
|
||||
{fullscreen ? null : attachmentSlot}
|
||||
<View style={fullscreen ? styles.fullscreenTextSurface : styles.inlineTextSurface}>
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
computeCanStartDictation,
|
||||
type MessageInputEnterContext,
|
||||
resolveActiveSendBehavior,
|
||||
resolveComposerFramePhase,
|
||||
resolveComposerSurfacePresentation,
|
||||
resolveComposerSurfaceText,
|
||||
resolveGlyphRailOffset,
|
||||
@@ -614,3 +615,23 @@ describe("fullscreen glyph rail", () => {
|
||||
expect(offset + inkInset).toBeCloseTo(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("composer frame phase", () => {
|
||||
const rest = { hovered: false, focused: false, readOnly: false, disabled: false };
|
||||
|
||||
it("shows the focus border while the editor has focus, hovered or not", () => {
|
||||
expect(resolveComposerFramePhase({ ...rest, focused: true })).toBe("active");
|
||||
expect(resolveComposerFramePhase({ ...rest, focused: true, hovered: true })).toBe("active");
|
||||
});
|
||||
|
||||
it("shows the hover border only while the pointer is over an unfocused frame", () => {
|
||||
expect(resolveComposerFramePhase({ ...rest, hovered: true })).toBe("hover");
|
||||
expect(resolveComposerFramePhase(rest)).toBe("rest");
|
||||
});
|
||||
|
||||
it("keeps a read-only or disabled frame at rest", () => {
|
||||
const engaged = { ...rest, hovered: true, focused: true };
|
||||
expect(resolveComposerFramePhase({ ...engaged, readOnly: true })).toBe("rest");
|
||||
expect(resolveComposerFramePhase({ ...engaged, disabled: true })).toBe("rest");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,6 +3,10 @@ import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { ActiveTurnBehavior } from "@getpaseo/protocol/messages";
|
||||
import type { MessagePayload, TextReplacement } from "@/composer/types";
|
||||
import type { MessageInputKeyboardActionKind } from "@/keyboard/actions";
|
||||
import {
|
||||
getControlInteractionPhase,
|
||||
type ControlInteractionPhase,
|
||||
} from "@/components/ui/control-geometry";
|
||||
|
||||
export type SendBehavior = ActiveTurnBehavior | "queue";
|
||||
|
||||
@@ -246,6 +250,23 @@ export function resolveGlyphRailOffset(input: {
|
||||
return -inkInset;
|
||||
}
|
||||
|
||||
/**
|
||||
* The composer frame follows the phases of the app's other inputs: focus wins over hover, and
|
||||
* a frame you can't type into (read-only, disabled) stays at rest.
|
||||
*/
|
||||
export function resolveComposerFramePhase(input: {
|
||||
hovered: boolean;
|
||||
focused: boolean;
|
||||
readOnly: boolean;
|
||||
disabled: boolean;
|
||||
}): ControlInteractionPhase {
|
||||
return getControlInteractionPhase({
|
||||
hovered: input.hovered,
|
||||
focused: input.focused,
|
||||
disabled: input.readOnly || input.disabled,
|
||||
});
|
||||
}
|
||||
|
||||
export function resolveComposerSurfaceText(
|
||||
liveText: string,
|
||||
replacement: TextReplacement,
|
||||
|
||||
@@ -2,9 +2,9 @@ import { useCallback, useMemo, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Text, View } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { Check } from "lucide-react-native";
|
||||
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { CheckboxRow } from "@/components/ui/checkbox";
|
||||
import { PressHighlight } from "@/components/ui/press-highlight";
|
||||
import { PluginIconView } from "@/plugins/icons";
|
||||
import { settingsStyles } from "@/styles/settings";
|
||||
@@ -14,9 +14,7 @@ import type { FilePanelPickerState } from "./model";
|
||||
import { useFilePanelChoiceSnapshot, type FilePanelChoice } from "./hook";
|
||||
import { filePanelIcon, filePanelOptionLabel, filePanelPickerTitle } from "./presentation";
|
||||
|
||||
const ThemedCheck = withUnistyles(Check);
|
||||
const ThemedPanelIcon = withUnistyles(PluginIconView);
|
||||
const checkedIconMapping = (theme: Theme) => ({ color: theme.colors.accentForeground });
|
||||
const mutedIconMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
|
||||
|
||||
/** The first-open question for a file with several panels, over the panel already showing. */
|
||||
@@ -97,10 +95,14 @@ function PickerBody({
|
||||
))}
|
||||
</View>
|
||||
<CheckboxRow
|
||||
label={t("panels.file.filePanels.dontAskAgain")}
|
||||
accessibilityLabel={t("panels.file.filePanels.dontAskAgain")}
|
||||
checked={picker.remember}
|
||||
onToggle={onToggleRemember}
|
||||
/>
|
||||
style={styles.checkboxRow}
|
||||
testID="file-panel-picker-remember"
|
||||
>
|
||||
<Text style={settingsStyles.rowTitle}>{t("panels.file.filePanels.dontAskAgain")}</Text>
|
||||
</CheckboxRow>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -144,34 +146,6 @@ function PanelRadioRow({
|
||||
);
|
||||
}
|
||||
|
||||
function CheckboxRow({
|
||||
label,
|
||||
checked,
|
||||
onToggle,
|
||||
}: {
|
||||
label: string;
|
||||
checked: boolean;
|
||||
onToggle: () => void;
|
||||
}) {
|
||||
const accessibilityState = useMemo(() => ({ checked }), [checked]);
|
||||
return (
|
||||
<PressHighlight
|
||||
style={styles.checkboxRow}
|
||||
onPress={onToggle}
|
||||
accessibilityRole="checkbox"
|
||||
accessibilityLabel={label}
|
||||
accessibilityState={accessibilityState}
|
||||
aria-checked={checked}
|
||||
testID="file-panel-picker-remember"
|
||||
>
|
||||
<View style={checked ? styles.checkboxChecked : styles.checkbox}>
|
||||
{checked ? <ThemedCheck size={14} uniProps={checkedIconMapping} /> : null}
|
||||
</View>
|
||||
<Text style={settingsStyles.rowTitle}>{label}</Text>
|
||||
</PressHighlight>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
footerButton: {
|
||||
flex: 1,
|
||||
@@ -211,23 +185,4 @@ const styles = StyleSheet.create((theme) => ({
|
||||
paddingVertical: theme.spacing[2],
|
||||
paddingHorizontal: theme.spacing[4],
|
||||
},
|
||||
checkbox: {
|
||||
width: 18,
|
||||
height: 18,
|
||||
borderRadius: theme.borderRadius.sm,
|
||||
borderWidth: 1,
|
||||
borderColor: theme.colors.border,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
checkboxChecked: {
|
||||
width: 18,
|
||||
height: 18,
|
||||
borderRadius: theme.borderRadius.sm,
|
||||
borderWidth: 1,
|
||||
borderColor: theme.colors.accent,
|
||||
backgroundColor: theme.colors.accent,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
retargetTextReveal,
|
||||
type TextRevealState,
|
||||
visibleRevealedText,
|
||||
withholdPartialClosingFence,
|
||||
} from "@/agent-stream/text-reveal";
|
||||
export type MarkdownPhase = "streaming" | "complete";
|
||||
|
||||
@@ -81,7 +82,9 @@ export function useRevealedText(text: string, phase: MarkdownPhase): string {
|
||||
};
|
||||
}, [text, pacingSupported, phase]);
|
||||
|
||||
return pacingSupported
|
||||
? visibleRevealedText(stateRef.current, { streaming: phase === "streaming" })
|
||||
: text;
|
||||
if (pacingSupported) {
|
||||
return visibleRevealedText(stateRef.current, { streaming: phase === "streaming" });
|
||||
}
|
||||
// Painted whole as it arrives, an arrival can still end inside a closing fence.
|
||||
return phase === "streaming" ? withholdPartialClosingFence(text) : text;
|
||||
}
|
||||
|
||||
@@ -244,6 +244,9 @@ export const ar: TranslationResources = {
|
||||
searchPlaceholder: "أوضاع البحث...",
|
||||
selectWithValue: "حدد وضع الوكيل ({{value}})",
|
||||
},
|
||||
sheet: {
|
||||
title: "إعدادات الوكيل",
|
||||
},
|
||||
hints: {
|
||||
thinking: "وضع التفكير",
|
||||
model: "تغيير النموذج",
|
||||
@@ -1885,6 +1888,12 @@ export const ar: TranslationResources = {
|
||||
searchAllPlaceholder: "ابحث في كل النماذج...",
|
||||
searchPlaceholder: "نماذج البحث...",
|
||||
openProviderSettings: "افتح إعدادات{{provider}}",
|
||||
searchModelsAndProfilesPlaceholder: "البحث في النماذج والملفات الشخصية...",
|
||||
shownOfTotal: "{{shown}} معروضة من {{total}}",
|
||||
olderModels: "نماذج أقدم ({{count}})",
|
||||
allModels: "كل النماذج ({{count}})",
|
||||
olderTag: "أقدم",
|
||||
allModelsTag: "كل النماذج",
|
||||
},
|
||||
providerCatalog: {
|
||||
title: "إضافة مزود",
|
||||
@@ -3392,6 +3401,13 @@ export const ar: TranslationResources = {
|
||||
retrying: "جارٍ إعادة المحاولة...",
|
||||
noSearchMatches: "لا توجد نماذج تطابق بحثك",
|
||||
noneDetected: "لم يتم اكتشاف أي نماذج",
|
||||
shownInfo: "تظهر النماذج المحددة أولاً في أدوات الاختيار. يظل البحث يجد البقية.",
|
||||
shownCount: "المعروضة ({{count}})",
|
||||
allShown: "كل النماذج معروضة",
|
||||
resetShown: "إعادة تعيين",
|
||||
resetShownLabel: "عرض كل النماذج في أدوات الاختيار",
|
||||
shownReset: "عرض كل النماذج",
|
||||
failedToSaveShown: "تعذر حفظ النماذج المعروضة",
|
||||
noCustom: "لا توجد نماذج مخصصة",
|
||||
title: "النماذج",
|
||||
custom: "نماذج مخصصة",
|
||||
|
||||
@@ -242,6 +242,9 @@ export const en = {
|
||||
searchPlaceholder: "Search modes...",
|
||||
selectWithValue: "Select agent mode ({{value}})",
|
||||
},
|
||||
sheet: {
|
||||
title: "Agent settings",
|
||||
},
|
||||
hints: {
|
||||
thinking: "Thinking mode",
|
||||
model: "Change model",
|
||||
@@ -1914,6 +1917,12 @@ export const en = {
|
||||
searchAllPlaceholder: "Search all models...",
|
||||
searchPlaceholder: "Search models...",
|
||||
openProviderSettings: "Open {{provider}} settings",
|
||||
searchModelsAndProfilesPlaceholder: "Search models and profiles...",
|
||||
shownOfTotal: "{{shown}} shown of {{total}}",
|
||||
olderModels: "Older models ({{count}})",
|
||||
allModels: "All models ({{count}})",
|
||||
olderTag: "Older",
|
||||
allModelsTag: "All models",
|
||||
},
|
||||
providerCatalog: {
|
||||
title: "Add provider",
|
||||
@@ -3493,6 +3502,13 @@ export const en = {
|
||||
retrying: "Retrying...",
|
||||
noSearchMatches: "No models match your search",
|
||||
noneDetected: "No models detected",
|
||||
shownInfo: "Checked models show first in pickers. Search still finds the rest.",
|
||||
shownCount: "Shown ({{count}})",
|
||||
allShown: "All models shown",
|
||||
resetShown: "Reset",
|
||||
resetShownLabel: "Show all models in pickers",
|
||||
shownReset: "Showing all models",
|
||||
failedToSaveShown: "Couldn't save shown models",
|
||||
noCustom: "No custom models",
|
||||
title: "Models",
|
||||
custom: "Custom models",
|
||||
|
||||
@@ -246,6 +246,9 @@ export const es: TranslationResources = {
|
||||
searchPlaceholder: "Modos de búsqueda...",
|
||||
selectWithValue: "Seleccione el modo de agente ({{value}})",
|
||||
},
|
||||
sheet: {
|
||||
title: "Ajustes del agente",
|
||||
},
|
||||
hints: {
|
||||
thinking: "Modo de pensamiento",
|
||||
model: "Cambiar modelo",
|
||||
@@ -1935,6 +1938,12 @@ export const es: TranslationResources = {
|
||||
searchAllPlaceholder: "Buscar en todos los modelos...",
|
||||
searchPlaceholder: "Buscar modelos...",
|
||||
openProviderSettings: "Abrir configuración de{{provider}}",
|
||||
searchModelsAndProfilesPlaceholder: "Buscar modelos y perfiles...",
|
||||
shownOfTotal: "{{shown}} visibles de {{total}}",
|
||||
olderModels: "Modelos anteriores ({{count}})",
|
||||
allModels: "Todos los modelos ({{count}})",
|
||||
olderTag: "Anterior",
|
||||
allModelsTag: "Todos los modelos",
|
||||
},
|
||||
providerCatalog: {
|
||||
title: "Agregar proveedor",
|
||||
@@ -3429,6 +3438,14 @@ export const es: TranslationResources = {
|
||||
retrying: "Reintentando...",
|
||||
noSearchMatches: "Ningún modelo coincide con tu búsqueda",
|
||||
noneDetected: "No se detectaron modelos",
|
||||
shownInfo:
|
||||
"Los modelos marcados aparecen primero en los selectores. La búsqueda sigue encontrando el resto.",
|
||||
shownCount: "Visibles ({{count}})",
|
||||
allShown: "Todos los modelos visibles",
|
||||
resetShown: "Restablecer",
|
||||
resetShownLabel: "Mostrar todos los modelos en los selectores",
|
||||
shownReset: "Mostrando todos los modelos",
|
||||
failedToSaveShown: "No se pudieron guardar los modelos visibles",
|
||||
noCustom: "No hay modelos personalizados",
|
||||
title: "Modelos",
|
||||
custom: "Modelos personalizados",
|
||||
|
||||
@@ -247,6 +247,9 @@ export const fr: TranslationResources = {
|
||||
searchPlaceholder: "Rechercher un mode…",
|
||||
selectWithValue: "Choisir le mode de l’agent ({{value}})",
|
||||
},
|
||||
sheet: {
|
||||
title: "Réglages de l'agent",
|
||||
},
|
||||
hints: {
|
||||
thinking: "Mode de réflexion",
|
||||
model: "Changer de modèle",
|
||||
@@ -1933,6 +1936,12 @@ export const fr: TranslationResources = {
|
||||
searchAllPlaceholder: "Rechercher dans tous les modèles…",
|
||||
searchPlaceholder: "Rechercher des modèles…",
|
||||
openProviderSettings: "Ouvrir les paramètres de {{provider}}",
|
||||
searchModelsAndProfilesPlaceholder: "Rechercher des modèles et des profils…",
|
||||
shownOfTotal: "{{shown}} affichés sur {{total}}",
|
||||
olderModels: "Modèles plus anciens ({{count}})",
|
||||
allModels: "Tous les modèles ({{count}})",
|
||||
olderTag: "Ancien",
|
||||
allModelsTag: "Tous les modèles",
|
||||
},
|
||||
providerCatalog: {
|
||||
title: "Ajouter un fournisseur",
|
||||
@@ -3436,6 +3445,14 @@ export const fr: TranslationResources = {
|
||||
retrying: "Nouvelle tentative…",
|
||||
noSearchMatches: "Aucun modèle ne correspond à votre recherche",
|
||||
noneDetected: "Aucun modèle détecté",
|
||||
shownInfo:
|
||||
"Les modèles cochés apparaissent en premier dans les sélecteurs. La recherche trouve toujours les autres.",
|
||||
shownCount: "Affichés ({{count}})",
|
||||
allShown: "Tous les modèles affichés",
|
||||
resetShown: "Réinitialiser",
|
||||
resetShownLabel: "Afficher tous les modèles dans les sélecteurs",
|
||||
shownReset: "Tous les modèles sont affichés",
|
||||
failedToSaveShown: "Impossible d'enregistrer les modèles affichés",
|
||||
noCustom: "Aucun modèle personnalisé",
|
||||
title: "Modèles",
|
||||
custom: "Modèles personnalisés",
|
||||
|
||||
@@ -246,6 +246,9 @@ export const ja: TranslationResources = {
|
||||
searchPlaceholder: "モードを検索...",
|
||||
selectWithValue: "エージェントモードを選択({{value}})",
|
||||
},
|
||||
sheet: {
|
||||
title: "エージェント設定",
|
||||
},
|
||||
hints: {
|
||||
thinking: "思考モード",
|
||||
model: "モデルを変更",
|
||||
@@ -1906,6 +1909,12 @@ export const ja: TranslationResources = {
|
||||
searchAllPlaceholder: "すべてのモデルを検索...",
|
||||
searchPlaceholder: "モデルを検索...",
|
||||
openProviderSettings: "{{provider}}の設定を開く",
|
||||
searchModelsAndProfilesPlaceholder: "モデルとプロファイルを検索...",
|
||||
shownOfTotal: "{{total}} 件中 {{shown}} 件を表示",
|
||||
olderModels: "以前のモデル ({{count}})",
|
||||
allModels: "すべてのモデル ({{count}})",
|
||||
olderTag: "以前",
|
||||
allModelsTag: "すべてのモデル",
|
||||
},
|
||||
providerCatalog: {
|
||||
title: "プロバイダーを追加",
|
||||
@@ -3392,6 +3401,13 @@ export const ja: TranslationResources = {
|
||||
retrying: "再試行中...",
|
||||
noSearchMatches: "検索に一致するモデルがありません",
|
||||
noneDetected: "モデルが検出されませんでした",
|
||||
shownInfo: "チェックしたモデルが選択肢の先頭に表示されます。残りも検索で見つかります。",
|
||||
shownCount: "表示中 ({{count}})",
|
||||
allShown: "すべてのモデルを表示中",
|
||||
resetShown: "リセット",
|
||||
resetShownLabel: "選択肢にすべてのモデルを表示",
|
||||
shownReset: "すべてのモデルを表示しています",
|
||||
failedToSaveShown: "表示するモデルを保存できませんでした",
|
||||
noCustom: "カスタムモデルはありません",
|
||||
title: "モデル",
|
||||
custom: "カスタムモデル",
|
||||
|
||||
@@ -244,6 +244,9 @@ export const ko: TranslationResources = {
|
||||
searchPlaceholder: "모드 검색...",
|
||||
selectWithValue: "에이전트 모드 선택 ({{value}})",
|
||||
},
|
||||
sheet: {
|
||||
title: "에이전트 설정",
|
||||
},
|
||||
hints: {
|
||||
thinking: "사고 모드",
|
||||
model: "모델 변경",
|
||||
@@ -1897,6 +1900,12 @@ export const ko: TranslationResources = {
|
||||
searchAllPlaceholder: "모든 모델 검색...",
|
||||
searchPlaceholder: "모델 검색...",
|
||||
openProviderSettings: "{{provider}} 설정 열기",
|
||||
searchModelsAndProfilesPlaceholder: "모델 및 프로필 검색...",
|
||||
shownOfTotal: "{{total}}개 중 {{shown}}개 표시",
|
||||
olderModels: "이전 모델 ({{count}})",
|
||||
allModels: "모든 모델 ({{count}})",
|
||||
olderTag: "이전",
|
||||
allModelsTag: "모든 모델",
|
||||
},
|
||||
providerCatalog: {
|
||||
title: "프로바이더 추가",
|
||||
@@ -3375,6 +3384,13 @@ export const ko: TranslationResources = {
|
||||
retrying: "다시 시도 중...",
|
||||
noSearchMatches: "검색과 일치하는 모델이 없습니다",
|
||||
noneDetected: "감지된 모델이 없습니다",
|
||||
shownInfo: "선택한 모델이 선택기에 먼저 표시됩니다. 나머지는 검색으로 찾을 수 있습니다.",
|
||||
shownCount: "표시됨 ({{count}})",
|
||||
allShown: "모든 모델 표시됨",
|
||||
resetShown: "재설정",
|
||||
resetShownLabel: "선택기에 모든 모델 표시",
|
||||
shownReset: "모든 모델을 표시합니다",
|
||||
failedToSaveShown: "표시할 모델을 저장하지 못했습니다",
|
||||
noCustom: "사용자 지정 모델 없음",
|
||||
title: "모델",
|
||||
custom: "사용자 지정 모델",
|
||||
|
||||
@@ -245,6 +245,9 @@ export const ptBR: TranslationResources = {
|
||||
searchPlaceholder: "Buscar modos...",
|
||||
selectWithValue: "Selecionar modo do agente ({{value}})",
|
||||
},
|
||||
sheet: {
|
||||
title: "Configurações do agente",
|
||||
},
|
||||
hints: {
|
||||
thinking: "Modo de raciocínio",
|
||||
model: "Alterar modelo",
|
||||
@@ -1919,6 +1922,12 @@ export const ptBR: TranslationResources = {
|
||||
searchAllPlaceholder: "Buscar em todos os modelos...",
|
||||
searchPlaceholder: "Buscar modelos...",
|
||||
openProviderSettings: "Abrir configurações de {{provider}}",
|
||||
searchModelsAndProfilesPlaceholder: "Buscar modelos e perfis...",
|
||||
shownOfTotal: "{{shown}} de {{total}} exibidos",
|
||||
olderModels: "Modelos anteriores ({{count}})",
|
||||
allModels: "Todos os modelos ({{count}})",
|
||||
olderTag: "Anterior",
|
||||
allModelsTag: "Todos os modelos",
|
||||
},
|
||||
providerCatalog: {
|
||||
title: "Adicionar provedor",
|
||||
@@ -3410,6 +3419,14 @@ export const ptBR: TranslationResources = {
|
||||
retrying: "Tentando novamente...",
|
||||
noSearchMatches: "Nenhum modelo corresponde à sua busca",
|
||||
noneDetected: "Nenhum modelo detectado",
|
||||
shownInfo:
|
||||
"Os modelos marcados aparecem primeiro nos seletores. A busca ainda encontra o restante.",
|
||||
shownCount: "Exibidos ({{count}})",
|
||||
allShown: "Todos os modelos exibidos",
|
||||
resetShown: "Redefinir",
|
||||
resetShownLabel: "Exibir todos os modelos nos seletores",
|
||||
shownReset: "Exibindo todos os modelos",
|
||||
failedToSaveShown: "Não foi possível salvar os modelos exibidos",
|
||||
noCustom: "Nenhum modelo personalizado",
|
||||
title: "Modelos",
|
||||
custom: "Modelos personalizados",
|
||||
|
||||
@@ -246,6 +246,9 @@ export const ru: TranslationResources = {
|
||||
searchPlaceholder: "Поиск режимов...",
|
||||
selectWithValue: "Выбрать режим агента ({{value}})",
|
||||
},
|
||||
sheet: {
|
||||
title: "Настройки агента",
|
||||
},
|
||||
hints: {
|
||||
thinking: "Режим рассуждений",
|
||||
model: "Изменить модель",
|
||||
@@ -1919,6 +1922,12 @@ export const ru: TranslationResources = {
|
||||
searchAllPlaceholder: "Поиск по всем моделям...",
|
||||
searchPlaceholder: "Поиск моделей...",
|
||||
openProviderSettings: "Открыть настройки {{provider}}",
|
||||
searchModelsAndProfilesPlaceholder: "Поиск моделей и профилей...",
|
||||
shownOfTotal: "Показано {{shown}} из {{total}}",
|
||||
olderModels: "Старые модели ({{count}})",
|
||||
allModels: "Все модели ({{count}})",
|
||||
olderTag: "Старая",
|
||||
allModelsTag: "Все модели",
|
||||
},
|
||||
providerCatalog: {
|
||||
title: "Добавить провайдера",
|
||||
@@ -3419,6 +3428,14 @@ export const ru: TranslationResources = {
|
||||
retrying: "Повторная попытка...",
|
||||
noSearchMatches: "Ни одна модель не соответствует вашему запросу",
|
||||
noneDetected: "Модели не обнаружены",
|
||||
shownInfo:
|
||||
"Отмеченные модели показываются первыми в списках выбора. Поиск по-прежнему находит остальные.",
|
||||
shownCount: "Показаны ({{count}})",
|
||||
allShown: "Показаны все модели",
|
||||
resetShown: "Сбросить",
|
||||
resetShownLabel: "Показывать все модели в списках выбора",
|
||||
shownReset: "Показаны все модели",
|
||||
failedToSaveShown: "Не удалось сохранить показываемые модели",
|
||||
noCustom: "Нет пользовательских моделей",
|
||||
title: "Модели",
|
||||
custom: "Пользовательские модели",
|
||||
|
||||
@@ -244,6 +244,9 @@ export const zhCN: TranslationResources = {
|
||||
searchPlaceholder: "搜索 modes...",
|
||||
selectWithValue: "选择 Agent mode({{value}})",
|
||||
},
|
||||
sheet: {
|
||||
title: "智能体设置",
|
||||
},
|
||||
hints: {
|
||||
thinking: "Thinking mode",
|
||||
model: "切换 Model",
|
||||
@@ -1867,6 +1870,12 @@ export const zhCN: TranslationResources = {
|
||||
searchAllPlaceholder: "搜索所有模型...",
|
||||
searchPlaceholder: "搜索模型...",
|
||||
openProviderSettings: "打开 {{provider}} 设置",
|
||||
searchModelsAndProfilesPlaceholder: "搜索模型和配置文件...",
|
||||
shownOfTotal: "显示 {{shown}} / {{total}}",
|
||||
olderModels: "旧模型 ({{count}})",
|
||||
allModels: "所有模型 ({{count}})",
|
||||
olderTag: "旧版",
|
||||
allModelsTag: "所有模型",
|
||||
},
|
||||
providerCatalog: {
|
||||
title: "添加 provider",
|
||||
@@ -3319,6 +3328,13 @@ export const zhCN: TranslationResources = {
|
||||
retrying: "正在重试...",
|
||||
noSearchMatches: "没有匹配搜索的 Model",
|
||||
noneDetected: "未检测到 Model",
|
||||
shownInfo: "勾选的 Model 会优先显示在选择器中。其余 Model 仍可搜索。",
|
||||
shownCount: "已显示 ({{count}})",
|
||||
allShown: "显示全部 Model",
|
||||
resetShown: "重置",
|
||||
resetShownLabel: "在选择器中显示全部 Model",
|
||||
shownReset: "正在显示全部 Model",
|
||||
failedToSaveShown: "无法保存显示的 Model",
|
||||
noCustom: "没有自定义模型",
|
||||
title: "Models",
|
||||
custom: "自定义 Models",
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { partitionProviderModels } from "./model-curation";
|
||||
import type { ProviderSelectionModelRow } from "./provider-selection";
|
||||
|
||||
function row(modelId: string, options: { legacy?: boolean } = {}): ProviderSelectionModelRow {
|
||||
return {
|
||||
favoriteKey: `pi:${modelId}`,
|
||||
provider: "pi",
|
||||
providerLabel: "Pi",
|
||||
modelId,
|
||||
modelLabel: modelId,
|
||||
...(options.legacy ? { legacy: true } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function ids(rows: readonly ProviderSelectionModelRow[]): string[] {
|
||||
return rows.map((candidate) => candidate.modelId);
|
||||
}
|
||||
|
||||
describe("partitionProviderModels", () => {
|
||||
const rows = [row("a"), row("b"), row("c", { legacy: true }), row("d", { legacy: true })];
|
||||
|
||||
it("shows picked models first in their picked order and folds the rest", () => {
|
||||
const partition = partitionProviderModels(rows, ["d", "a"], "a");
|
||||
expect(ids(partition.primary)).toEqual(["d", "a"]);
|
||||
expect(ids(partition.folded)).toEqual(["b", "c"]);
|
||||
expect(partition.foldKind).toBe("all");
|
||||
expect(partition.defaultExpanded).toBe(false);
|
||||
});
|
||||
|
||||
it("ignores picked models the catalog no longer has", () => {
|
||||
const partition = partitionProviderModels(rows, ["gone", "b"], "");
|
||||
expect(ids(partition.primary)).toEqual(["b"]);
|
||||
expect(ids(partition.folded)).toEqual(["a", "c", "d"]);
|
||||
});
|
||||
|
||||
it("falls back to folding older models when every picked model is gone", () => {
|
||||
const partition = partitionProviderModels(rows, ["gone"], "");
|
||||
expect(ids(partition.primary)).toEqual(["a", "b"]);
|
||||
expect(ids(partition.folded)).toEqual(["c", "d"]);
|
||||
expect(partition.foldKind).toBe("older");
|
||||
});
|
||||
|
||||
it("folds older models when nothing is picked", () => {
|
||||
const partition = partitionProviderModels(rows, undefined, "");
|
||||
expect(ids(partition.primary)).toEqual(["a", "b"]);
|
||||
expect(ids(partition.folded)).toEqual(["c", "d"]);
|
||||
expect(partition.foldKind).toBe("older");
|
||||
});
|
||||
|
||||
it("shows every model when all of them are older", () => {
|
||||
const allLegacy = [row("c", { legacy: true }), row("d", { legacy: true })];
|
||||
const partition = partitionProviderModels(allLegacy, [], "");
|
||||
expect(ids(partition.primary)).toEqual(["c", "d"]);
|
||||
expect(partition.folded).toEqual([]);
|
||||
expect(partition.foldKind).toBeNull();
|
||||
});
|
||||
|
||||
it("shows every model when none is older or picked", () => {
|
||||
const partition = partitionProviderModels([row("a"), row("b")], undefined, "a");
|
||||
expect(ids(partition.primary)).toEqual(["a", "b"]);
|
||||
expect(partition.foldKind).toBeNull();
|
||||
expect(partition.defaultExpanded).toBe(false);
|
||||
});
|
||||
|
||||
it("has nothing to fold when every model is picked", () => {
|
||||
const partition = partitionProviderModels([row("a"), row("b")], ["b", "a"], "a");
|
||||
expect(ids(partition.primary)).toEqual(["b", "a"]);
|
||||
expect(partition.folded).toEqual([]);
|
||||
expect(partition.foldKind).toBeNull();
|
||||
});
|
||||
|
||||
it("opens the fold when the selected model is inside it", () => {
|
||||
expect(partitionProviderModels(rows, undefined, "c").defaultExpanded).toBe(true);
|
||||
expect(partitionProviderModels(rows, ["a"], "b").defaultExpanded).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
import type { ProviderSelectionModelRow } from "./provider-selection";
|
||||
|
||||
/**
|
||||
* Why models sit behind the fold: `all` folds what the user did not pick in
|
||||
* Settings, `older` folds previous releases. `null` means nothing is folded.
|
||||
*/
|
||||
export type ModelFoldKind = "all" | "older" | null;
|
||||
|
||||
export interface ProviderModelPartition {
|
||||
primary: ProviderSelectionModelRow[];
|
||||
folded: ProviderSelectionModelRow[];
|
||||
foldKind: ModelFoldKind;
|
||||
/** The selected model is folded, so the picker opens the fold to show it. */
|
||||
defaultExpanded: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits one provider's models into the rows a picker shows and the rows it folds.
|
||||
* Picked models win; otherwise previous releases fold behind the current ones.
|
||||
* The primary list is never empty while the provider has models.
|
||||
*/
|
||||
export function partitionProviderModels(
|
||||
rows: readonly ProviderSelectionModelRow[],
|
||||
shownModels: readonly string[] | undefined,
|
||||
selectedModelId: string,
|
||||
): ProviderModelPartition {
|
||||
const picked = pickShownRows(rows, shownModels);
|
||||
if (picked.length > 0) {
|
||||
const pickedIds = new Set(picked.map((row) => row.modelId));
|
||||
return withFold(
|
||||
picked,
|
||||
rows.filter((row) => !pickedIds.has(row.modelId)),
|
||||
"all",
|
||||
selectedModelId,
|
||||
);
|
||||
}
|
||||
|
||||
const current = rows.filter((row) => row.legacy !== true);
|
||||
if (current.length > 0 && current.length < rows.length) {
|
||||
return withFold(
|
||||
current,
|
||||
rows.filter((row) => row.legacy === true),
|
||||
"older",
|
||||
selectedModelId,
|
||||
);
|
||||
}
|
||||
|
||||
return withFold([...rows], [], null, selectedModelId);
|
||||
}
|
||||
|
||||
function pickShownRows(
|
||||
rows: readonly ProviderSelectionModelRow[],
|
||||
shownModels: readonly string[] | undefined,
|
||||
): ProviderSelectionModelRow[] {
|
||||
if (!shownModels || shownModels.length === 0) return [];
|
||||
const rowsById = new Map(rows.map((row) => [row.modelId, row]));
|
||||
return shownModels.flatMap((modelId) => {
|
||||
const row = rowsById.get(modelId);
|
||||
return row ? [row] : [];
|
||||
});
|
||||
}
|
||||
|
||||
function withFold(
|
||||
primary: ProviderSelectionModelRow[],
|
||||
folded: ProviderSelectionModelRow[],
|
||||
foldKind: ModelFoldKind,
|
||||
selectedModelId: string,
|
||||
): ProviderModelPartition {
|
||||
if (folded.length === 0) {
|
||||
return { primary, folded, foldKind: null, defaultExpanded: false };
|
||||
}
|
||||
return {
|
||||
primary,
|
||||
folded,
|
||||
foldKind,
|
||||
defaultExpanded: folded.some((row) => row.modelId === selectedModelId),
|
||||
};
|
||||
}
|
||||
@@ -23,6 +23,8 @@ export interface ProviderSelectionModelRow {
|
||||
modelLabel: string;
|
||||
description?: string;
|
||||
isDefault?: boolean;
|
||||
/** A previous release, folded behind the current models. */
|
||||
legacy?: boolean;
|
||||
}
|
||||
|
||||
function buildModelRowKey(provider: string, modelId: string): string {
|
||||
@@ -38,6 +40,8 @@ export interface ProviderSelectorProvider {
|
||||
id: string;
|
||||
label: string;
|
||||
modelSelection: ProviderModelSelection;
|
||||
/** User-picked model IDs, in display order. Absent means the user picked none. */
|
||||
shownModels?: readonly string[];
|
||||
}
|
||||
|
||||
export interface ProviderSelectionState {
|
||||
@@ -67,6 +71,7 @@ function buildModelRows(
|
||||
modelLabel: model.label,
|
||||
description: model.description ?? model.id,
|
||||
isDefault: model.isDefault,
|
||||
...(model.legacy ? { legacy: true } : {}),
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -153,6 +158,7 @@ export function buildSelectorProvider(
|
||||
id: entry.provider,
|
||||
label,
|
||||
modelSelection: buildEntryModelSelection(entry, label, isConnected),
|
||||
...(entry.shownModels ? { shownModels: entry.shownModels } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -11,13 +11,16 @@ import {
|
||||
AdaptiveTextInput,
|
||||
type SheetHeader,
|
||||
} from "@/components/adaptive-modal-sheet";
|
||||
import { SettingsSection } from "@/components/settings";
|
||||
import { SettingsRow, SettingsSection } from "@/components/settings";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { CheckboxRow } from "@/components/ui/checkbox";
|
||||
import { bySizing, TOUCH_TARGET } from "@/components/ui/control-geometry";
|
||||
import { ToolbarButton, paneContentToolbarIconSize } from "@/components/ui/pane-content-toolbar";
|
||||
import { SearchField } from "@/components/ui/search-field";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { useDaemonConfig } from "@/hooks/use-daemon-config";
|
||||
import { useHostFeature } from "@/runtime/host-features";
|
||||
import { CODE_SURFACE_DATASET } from "@/styles/code-surface";
|
||||
import { settingsStyles } from "@/styles/settings";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
@@ -27,6 +30,8 @@ import {
|
||||
} from "./discovered-models";
|
||||
import type { ProviderEntry } from "./provider-config";
|
||||
import { ProviderRefreshButton, useCheckedLabel, type ProviderRefresh } from "./provider-refresh";
|
||||
import { arrangeShownFirst, countShownModels } from "./shown-models";
|
||||
import { useShownModelsEditor, type ShownModelsEditor } from "./use-shown-models";
|
||||
|
||||
const ThemedTrash = withUnistyles(Trash2);
|
||||
const destructiveColorMapping = (theme: Theme) => ({ color: theme.colors.destructive });
|
||||
@@ -88,9 +93,27 @@ export function ProviderModels({
|
||||
|
||||
// Search shows only beside the provider's own models; a query typed then must not hide custom ones.
|
||||
const q = discovered ? query.trim() : "";
|
||||
|
||||
// COMPAT(providerShownModels): added in v0.18.1, remove gate after 2027-05-28.
|
||||
const curationSupported = useHostFeature(serverId, "providerShownModels");
|
||||
const curating = discovered && curationSupported && config !== null;
|
||||
const shownEditor = useShownModelsEditor({ provider, config, patchConfig });
|
||||
// Shown models list first, but a check never moves a row under the pointer: the order is taken
|
||||
// when the page opens, a search ends, or the list is reset, and holds while the user checks.
|
||||
const arrangementKey = `${q === "" ? "browse" : "search"}:${curating}:${shownEditor.revision}`;
|
||||
const [arrangement, setArrangement] = useState({
|
||||
key: arrangementKey,
|
||||
shownModels: shownEditor.shownModels,
|
||||
});
|
||||
if (arrangement.key !== arrangementKey) {
|
||||
setArrangement({ key: arrangementKey, shownModels: shownEditor.shownModels });
|
||||
}
|
||||
const filteredDiscovered = useMemo(
|
||||
() => rankModels(discoveredModels, q, (m) => [m.label, m.id, m.description ?? ""]),
|
||||
[discoveredModels, q],
|
||||
() =>
|
||||
q === "" && curating
|
||||
? arrangeShownFirst(discoveredModels, arrangement.shownModels)
|
||||
: rankModels(discoveredModels, q, (m) => [m.label, m.id, m.description ?? ""]),
|
||||
[arrangement.shownModels, curating, discoveredModels, q],
|
||||
);
|
||||
const filteredCustom = useMemo(
|
||||
() => rankModels(additionalModels, q, (m) => [m.label, m.id]),
|
||||
@@ -151,9 +174,19 @@ export function ProviderModels({
|
||||
} else if (filteredDiscovered.length === 0) {
|
||||
discoveredBody = <MutedRow>{t("settings.providers.models.noSearchMatches")}</MutedRow>;
|
||||
} else {
|
||||
discoveredBody = filteredDiscovered.map((model, index) => (
|
||||
<DiscoveredModelRow key={model.id} model={model} first={index === 0} />
|
||||
));
|
||||
discoveredBody = filteredDiscovered.map((model, index) =>
|
||||
curating ? (
|
||||
<ShownModelRow
|
||||
key={model.id}
|
||||
model={model}
|
||||
first={index === 0}
|
||||
checked={shownEditor.shownModels.includes(model.id)}
|
||||
onToggle={shownEditor.toggle}
|
||||
/>
|
||||
) : (
|
||||
<DiscoveredModelRow key={model.id} model={model} first={index === 0} />
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
let customBody: React.ReactNode;
|
||||
@@ -176,7 +209,11 @@ export function ProviderModels({
|
||||
return (
|
||||
<View testID="provider-models">
|
||||
{discovered ? (
|
||||
<SettingsSection title={t("settings.providers.models.title")} trailing={discoveredTrailing}>
|
||||
<SettingsSection
|
||||
title={t("settings.providers.models.title")}
|
||||
trailing={discoveredTrailing}
|
||||
info={curating ? t("settings.providers.models.shownInfo") : undefined}
|
||||
>
|
||||
<View style={styles.searchRow}>
|
||||
<SearchField
|
||||
value={query}
|
||||
@@ -188,11 +225,17 @@ export function ProviderModels({
|
||||
/>
|
||||
</View>
|
||||
<View style={settingsStyles.card}>
|
||||
{curating && discoveredModels.length > 0 ? (
|
||||
<ShownModelsBar
|
||||
count={countShownModels(discoveredModels, shownEditor.shownModels)}
|
||||
onReset={shownEditor.reset}
|
||||
/>
|
||||
) : null}
|
||||
{/* A provider can report hundreds of models; the rest of the page stays in reach. */}
|
||||
<ScrollView
|
||||
style={styles.discoveredList}
|
||||
// Android scrolls a ScrollView nested in the page or the sheet only with this flag.
|
||||
nestedScrollEnabled
|
||||
style={[styles.discoveredList, curating && settingsStyles.rowBorder]}
|
||||
testID="provider-discovered-models"
|
||||
>
|
||||
{discoveredBody}
|
||||
@@ -241,6 +284,65 @@ function MutedRow({ children }: { children: string }) {
|
||||
function DiscoveredModelRow({ model, first }: { model: AgentModelDefinition; first: boolean }) {
|
||||
return (
|
||||
<View style={[styles.modelRow, !first && settingsStyles.rowBorder]}>
|
||||
<ModelRowText model={model} />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
/** How many models pickers show first, and the way back to showing all of them. */
|
||||
function ShownModelsBar({ count, onReset }: { count: number; onReset: () => void }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<SettingsRow
|
||||
label={
|
||||
count > 0
|
||||
? t("settings.providers.models.shownCount", { count })
|
||||
: t("settings.providers.models.allShown")
|
||||
}
|
||||
testID="provider-shown-models-bar"
|
||||
>
|
||||
{/* Always drawn, so the first check does not move the list below. */}
|
||||
<Button
|
||||
variant="secondary"
|
||||
onPress={onReset}
|
||||
disabled={count === 0}
|
||||
accessibilityLabel={t("settings.providers.models.resetShownLabel")}
|
||||
testID="provider-shown-models-reset"
|
||||
>
|
||||
{t("settings.providers.models.resetShown")}
|
||||
</Button>
|
||||
</SettingsRow>
|
||||
);
|
||||
}
|
||||
|
||||
function ShownModelRow({
|
||||
model,
|
||||
first,
|
||||
checked,
|
||||
onToggle,
|
||||
}: {
|
||||
model: AgentModelDefinition;
|
||||
first: boolean;
|
||||
checked: boolean;
|
||||
onToggle: ShownModelsEditor["toggle"];
|
||||
}) {
|
||||
const handleToggle = useCallback(() => onToggle(model.id), [model.id, onToggle]);
|
||||
return (
|
||||
<CheckboxRow
|
||||
checked={checked}
|
||||
onToggle={handleToggle}
|
||||
accessibilityLabel={model.label}
|
||||
style={[styles.modelRow, styles.shownModelRow, !first && settingsStyles.rowBorder]}
|
||||
testID={`provider-shown-model-${model.id}`}
|
||||
>
|
||||
<ModelRowText model={model} />
|
||||
</CheckboxRow>
|
||||
);
|
||||
}
|
||||
|
||||
function ModelRowText({ model }: { model: AgentModelDefinition }) {
|
||||
return (
|
||||
<>
|
||||
<Text style={styles.modelTitle} numberOfLines={1}>
|
||||
{model.label}
|
||||
</Text>
|
||||
@@ -252,7 +354,7 @@ function DiscoveredModelRow({ model, first }: { model: AgentModelDefinition; fir
|
||||
{model.description}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -416,6 +518,10 @@ const styles = StyleSheet.create((theme) => ({
|
||||
paddingHorizontal: theme.spacing[4],
|
||||
gap: theme.spacing[3],
|
||||
},
|
||||
// A touch-sized hit area; the row's text keeps its rails.
|
||||
shownModelRow: {
|
||||
minHeight: bySizing({ touch: TOUCH_TARGET, pointer: 0 }),
|
||||
},
|
||||
modelTitle: {
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.base,
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { arrangeShownFirst, countShownModels, toggleShownModel } from "./shown-models";
|
||||
|
||||
const models = [{ id: "a" }, { id: "b" }, { id: "c" }, { id: "d" }];
|
||||
|
||||
describe("toggleShownModel", () => {
|
||||
it("adds a model after the ones already picked, in the order the user checks them", () => {
|
||||
expect(toggleShownModel(["c"], "a")).toEqual(["c", "a"]);
|
||||
});
|
||||
|
||||
it("removes a picked model and keeps the rest in order", () => {
|
||||
expect(toggleShownModel(["c", "a", "d"], "a")).toEqual(["c", "d"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("arrangeShownFirst", () => {
|
||||
it("lists picked models first in picked order, then the rest in catalog order", () => {
|
||||
expect(arrangeShownFirst(models, ["d", "b"]).map((model) => model.id)).toEqual([
|
||||
"d",
|
||||
"b",
|
||||
"a",
|
||||
"c",
|
||||
]);
|
||||
});
|
||||
|
||||
it("skips picked models the catalog no longer has", () => {
|
||||
expect(arrangeShownFirst(models, ["gone", "c"]).map((model) => model.id)).toEqual([
|
||||
"c",
|
||||
"a",
|
||||
"b",
|
||||
"d",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("countShownModels", () => {
|
||||
it("counts only picked models the catalog still has", () => {
|
||||
expect(countShownModels(models, ["gone", "c", "a"])).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
interface IdentifiedModel {
|
||||
id: string;
|
||||
}
|
||||
|
||||
/** Checking a model adds it after the ones already picked; unchecking removes it. */
|
||||
export function toggleShownModel(shownModels: readonly string[], modelId: string): string[] {
|
||||
return shownModels.includes(modelId)
|
||||
? shownModels.filter((id) => id !== modelId)
|
||||
: [...shownModels, modelId];
|
||||
}
|
||||
|
||||
/** Picked models first, in the order the user picked them, then the rest in catalog order. */
|
||||
export function arrangeShownFirst<T extends IdentifiedModel>(
|
||||
models: readonly T[],
|
||||
shownModels: readonly string[],
|
||||
): T[] {
|
||||
const modelsById = new Map(models.map((model) => [model.id, model]));
|
||||
const shown = shownModels.flatMap((id) => {
|
||||
const model = modelsById.get(id);
|
||||
return model ? [model] : [];
|
||||
});
|
||||
const shownIds = new Set(shown.map((model) => model.id));
|
||||
return [...shown, ...models.filter((model) => !shownIds.has(model.id))];
|
||||
}
|
||||
|
||||
/** Picked models the catalog still reports; a removed model no longer counts as shown. */
|
||||
export function countShownModels(
|
||||
models: readonly IdentifiedModel[],
|
||||
shownModels: readonly string[],
|
||||
): number {
|
||||
const ids = new Set(models.map((model) => model.id));
|
||||
return shownModels.filter((id) => ids.has(id)).length;
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import { useCallback, useMemo, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Text, View } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import type { MutableDaemonConfig, MutableDaemonConfigPatch } from "@getpaseo/protocol/messages";
|
||||
import type { DismissToast } from "@/components/toast-host";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useToast } from "@/contexts/toast-context";
|
||||
import { toggleShownModel } from "./shown-models";
|
||||
|
||||
const RESET_UNDO_WINDOW_MS = 6000;
|
||||
|
||||
export interface ShownModelsEditor {
|
||||
/** The models pickers show first, including a change still being saved. */
|
||||
shownModels: readonly string[];
|
||||
toggle: (modelId: string) => void;
|
||||
reset: () => void;
|
||||
/** Changes when the list is replaced as a whole (reset, undo), so the page can re-sort it. */
|
||||
revision: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Edits one provider's shown models. A check shows at once and is saved in the background; a
|
||||
* failed save puts the last saved list back and says so. Reset can be undone from its toast.
|
||||
*/
|
||||
export function useShownModelsEditor(input: {
|
||||
provider: string;
|
||||
config: MutableDaemonConfig | null;
|
||||
patchConfig: (patch: MutableDaemonConfigPatch) => Promise<unknown>;
|
||||
}): ShownModelsEditor {
|
||||
const { provider, config, patchConfig } = input;
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
// The list being saved. Each save sends the whole list, so the latest one wins.
|
||||
const [pending, setPending] = useState<readonly string[] | null>(null);
|
||||
const [revision, setRevision] = useState(0);
|
||||
const saved = config?.providers?.[provider]?.shownModels;
|
||||
const shownModels = useMemo(() => pending ?? saved ?? [], [pending, saved]);
|
||||
|
||||
const save = useCallback(
|
||||
(next: readonly string[]) => {
|
||||
setPending(next);
|
||||
const settle = () => setPending((current) => (current === next ? null : current));
|
||||
void patchConfig({ providers: { [provider]: { shownModels: [...next] } } }).then(
|
||||
settle,
|
||||
(error: unknown) => {
|
||||
settle();
|
||||
toast.error(
|
||||
error instanceof Error && error.message
|
||||
? error.message
|
||||
: t("settings.providers.models.failedToSaveShown"),
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
[patchConfig, provider, t, toast],
|
||||
);
|
||||
|
||||
const toggle = useCallback(
|
||||
(modelId: string) => save(toggleShownModel(shownModels, modelId)),
|
||||
[save, shownModels],
|
||||
);
|
||||
|
||||
const dismissResetToast = useRef<DismissToast>(() => {});
|
||||
const restore = useCallback(
|
||||
(previous: readonly string[]) => {
|
||||
dismissResetToast.current();
|
||||
save(previous);
|
||||
setRevision((value) => value + 1);
|
||||
},
|
||||
[save],
|
||||
);
|
||||
|
||||
const reset = useCallback(() => {
|
||||
save([]);
|
||||
setRevision((value) => value + 1);
|
||||
dismissResetToast.current = toast.show(
|
||||
<ShownResetToast previous={shownModels} onUndo={restore} />,
|
||||
{ layout: "action", durationMs: RESET_UNDO_WINDOW_MS, testID: "provider-shown-reset-toast" },
|
||||
);
|
||||
}, [restore, save, shownModels, toast]);
|
||||
|
||||
return { shownModels, toggle, reset, revision };
|
||||
}
|
||||
|
||||
function ShownResetToast(props: {
|
||||
previous: readonly string[];
|
||||
onUndo: (previous: readonly string[]) => void;
|
||||
}) {
|
||||
const { previous, onUndo } = props;
|
||||
const { t } = useTranslation();
|
||||
const undo = useCallback(() => onUndo(previous), [onUndo, previous]);
|
||||
return (
|
||||
<View style={styles.row}>
|
||||
<Text style={styles.message}>{t("settings.providers.models.shownReset")}</Text>
|
||||
<Button size="sm" onPress={undo} testID="provider-shown-reset-undo">
|
||||
{t("modelSelector.undo")}
|
||||
</Button>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
row: {
|
||||
flexDirection: "row",
|
||||
flexWrap: "wrap",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[3],
|
||||
},
|
||||
message: {
|
||||
flexShrink: 1,
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.base,
|
||||
},
|
||||
}));
|
||||
@@ -282,7 +282,6 @@ function MetadataModelSelectionRows({
|
||||
disabled={isSaving}
|
||||
serverId={serverId}
|
||||
desktopPlacement="bottom-start"
|
||||
desktopMinWidth={360}
|
||||
/>
|
||||
</SettingsRow>
|
||||
</View>
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import type { AgentMessage } from "@getpaseo/protocol/agent-message";
|
||||
import type { ToolCallDetail } from "@getpaseo/protocol/agent-types";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { buildToolCallPresentation, type ToolCallPresentationIcon } from "./presentation";
|
||||
|
||||
const fakeIcons = {
|
||||
paseo: (() => null) as ToolCallPresentationIcon,
|
||||
bot: (() => null) as ToolCallPresentationIcon,
|
||||
brain: (() => null) as ToolCallPresentationIcon,
|
||||
eye: (() => null) as ToolCallPresentationIcon,
|
||||
wrench: (() => null) as ToolCallPresentationIcon,
|
||||
@@ -14,10 +13,9 @@ const fakeIcons = {
|
||||
function fakeResolveIcon(
|
||||
toolName: string,
|
||||
detail: ToolCallDetail | undefined,
|
||||
agentMessage: AgentMessage | undefined,
|
||||
): ToolCallPresentationIcon {
|
||||
if (agentMessage) {
|
||||
return fakeIcons.paseo;
|
||||
if (detail?.type === "plain_text" && detail.icon === "bot") {
|
||||
return fakeIcons.bot;
|
||||
}
|
||||
if (detail?.type === "plan") {
|
||||
return fakeIcons.brain;
|
||||
@@ -118,46 +116,29 @@ describe("tool-call presentation", () => {
|
||||
});
|
||||
|
||||
it.each([
|
||||
["message", "Message received"],
|
||||
["finished", "Agent finished"],
|
||||
["errored", "Agent errored"],
|
||||
["permission-required", "Agent needs permission"],
|
||||
["closed", "Agent closed"],
|
||||
] as const)(
|
||||
"presents %s with a fixed label, the sender as context, and the Paseo icon",
|
||||
(event, heading) => {
|
||||
const presentation = buildToolCallPresentation({
|
||||
toolName: "internal_name_should_not_be_visible",
|
||||
status: "completed",
|
||||
error: null,
|
||||
detail: { type: "plain_text", label: "legacy summary", text: "legacy body", icon: "bot" },
|
||||
agentMessage: {
|
||||
event,
|
||||
sender: { id: "server::sender", title: "QA messenger" },
|
||||
text: "The delivered message.",
|
||||
},
|
||||
resolveIcon: fakeResolveIcon,
|
||||
});
|
||||
expect(presentation.displayName).toBe(heading);
|
||||
expect(presentation.summary).toBe("QA messenger");
|
||||
expect(presentation.icon).toBe(fakeIcons.paseo);
|
||||
expect(presentation.detail).toEqual({
|
||||
type: "plain_text",
|
||||
text: "From agent: server::sender\n\nThe delivered message.",
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("uses an opaque sender ID when no title is available", () => {
|
||||
["agent_finished", "Agent finished"],
|
||||
["agent_errored", "Agent errored"],
|
||||
["agent_needs_permission", "Agent needs permission"],
|
||||
["agent_closed", "Agent closed"],
|
||||
] as const)("presents the %s notification from its plain-text detail", (toolName, heading) => {
|
||||
const detail = {
|
||||
type: "plain_text" as const,
|
||||
label: "QA messenger",
|
||||
text: "The delivered notification.",
|
||||
icon: "bot" as const,
|
||||
};
|
||||
const presentation = buildToolCallPresentation({
|
||||
toolName: "agent_message",
|
||||
toolName,
|
||||
status: "completed",
|
||||
error: null,
|
||||
agentMessage: { event: "message", sender: { id: "remote::worker" }, text: "Hello" },
|
||||
detail,
|
||||
resolveIcon: fakeResolveIcon,
|
||||
});
|
||||
expect(presentation.displayName).toBe("Message received");
|
||||
expect(presentation.summary).toBe("remote::worker");
|
||||
expect(presentation.displayName).toBe(heading);
|
||||
expect(presentation.summary).toBe("QA messenger");
|
||||
expect(presentation.icon).toBe(fakeIcons.bot);
|
||||
expect(presentation.detail).toEqual(detail);
|
||||
expect(presentation.canOpenDetails).toBe(true);
|
||||
});
|
||||
|
||||
it("shows the target agent title as context for Paseo agent tools", () => {
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import type { AgentMessage } from "@getpaseo/protocol/agent-message";
|
||||
import { buildAgentMessageDisplay } from "@getpaseo/protocol/paseo-tool-presentation/index";
|
||||
import type { PlanOutcome } from "@/components/plan-card";
|
||||
import type { ComponentType } from "react";
|
||||
import type { ToolCallDetail } from "@getpaseo/protocol/agent-types";
|
||||
@@ -15,7 +13,6 @@ type ToolCallStatus = "executing" | "running" | "completed" | "failed" | "cancel
|
||||
export type ToolCallPresentationIcon = ComponentType<{ size?: number; color?: string }>;
|
||||
|
||||
interface BuildToolCallPresentationInput {
|
||||
agentMessage?: AgentMessage;
|
||||
toolName: string;
|
||||
status: ToolCallStatus;
|
||||
error: unknown;
|
||||
@@ -43,7 +40,6 @@ export interface ToolCallPresentation {
|
||||
export type ToolCallIconResolver = (
|
||||
toolName: string,
|
||||
detail: ToolCallDetail | undefined,
|
||||
agentMessage: AgentMessage | undefined,
|
||||
) => ToolCallPresentationIcon;
|
||||
|
||||
function displayStatus(status: ToolCallStatus): ToolCallDisplayInput["status"] {
|
||||
@@ -57,13 +53,10 @@ function displayDetail(detail: ToolCallDetail | undefined): ToolCallDetail {
|
||||
export function buildToolCallPresentation(
|
||||
input: BuildToolCallPresentationInput,
|
||||
): ToolCallPresentation {
|
||||
const detail = input.agentMessage
|
||||
? buildAgentMessageDisplay(input.agentMessage).detail
|
||||
: input.detail;
|
||||
const detail = input.detail;
|
||||
const detailForDisplay = displayDetail(detail);
|
||||
const displayModel = buildToolCallDisplayModel({
|
||||
name: input.toolName,
|
||||
agentMessage: input.agentMessage,
|
||||
status: displayStatus(input.status),
|
||||
error: input.error ?? null,
|
||||
detail: detailForDisplay,
|
||||
@@ -83,7 +76,7 @@ export function buildToolCallPresentation(
|
||||
displayName: displayModel.displayName,
|
||||
summary: displayModel.summary,
|
||||
errorText: displayModel.errorText,
|
||||
icon: input.resolveIcon(input.toolName, detail, input.agentMessage),
|
||||
icon: input.resolveIcon(input.toolName, detail),
|
||||
isLoadingDetails,
|
||||
hasDetails,
|
||||
canOpenDetails: hasDetails || isLoadingDetails,
|
||||
|
||||
@@ -54,13 +54,9 @@ describe("resolveToolCallIconName", () => {
|
||||
expect(icon).toBe("wrench");
|
||||
});
|
||||
|
||||
it("uses the Paseo icon for agent messages despite the legacy bot detail icon", () => {
|
||||
const icon = resolveToolCallIconName(
|
||||
"agent_message",
|
||||
{ type: "plain_text", text: "Done.", icon: "bot" },
|
||||
{ event: "finished", sender: { id: "agt_1" }, text: "Done." },
|
||||
);
|
||||
|
||||
expect(icon).toBe("paseo");
|
||||
it("uses the plain-text icon a daemon notification names", () => {
|
||||
expect(
|
||||
resolveToolCallIconName("agent_finished", { type: "plain_text", text: "Done.", icon: "bot" }),
|
||||
).toBe("bot");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import type { AgentMessage } from "@getpaseo/protocol/agent-message";
|
||||
import type { ToolCallDetail, ToolCallIconName } from "@getpaseo/protocol/agent-types";
|
||||
import { isPaseoToolName } from "@getpaseo/protocol/tool-name-normalization";
|
||||
|
||||
@@ -18,15 +17,7 @@ const TOOL_DETAIL_ICON_NAMES: Record<ToolCallDetail["type"], ToolCallIcon> = {
|
||||
unknown: "wrench",
|
||||
};
|
||||
|
||||
export function resolveToolCallIconName(
|
||||
toolName: string,
|
||||
detail?: ToolCallDetail,
|
||||
agentMessage?: AgentMessage,
|
||||
): ToolCallIcon {
|
||||
// Agent messages are Paseo deliveries; the wire detail's legacy "bot" icon is for old clients.
|
||||
if (agentMessage) {
|
||||
return "paseo";
|
||||
}
|
||||
export function resolveToolCallIconName(toolName: string, detail?: ToolCallDetail): ToolCallIcon {
|
||||
const lowerName = toolName.trim().toLowerCase();
|
||||
|
||||
if (detail?.type === "plain_text" && detail.icon) {
|
||||
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
SquareTerminal,
|
||||
Wrench,
|
||||
} from "lucide-react-native";
|
||||
import type { AgentMessage } from "@getpaseo/protocol/agent-message";
|
||||
import type { ToolCallDetail } from "@getpaseo/protocol/agent-types";
|
||||
import { PaseoLogo } from "@/components/icons/paseo-logo";
|
||||
import { resolveToolCallIconName, type ToolCallIcon } from "./tool-call-icon-name";
|
||||
@@ -37,7 +36,6 @@ export function componentForToolCallIcon(name: ToolCallIcon): ToolCallIconCompon
|
||||
export function resolveToolCallIcon(
|
||||
toolName: string,
|
||||
detail?: ToolCallDetail,
|
||||
agentMessage?: AgentMessage,
|
||||
): ToolCallIconComponent {
|
||||
return componentForToolCallIcon(resolveToolCallIconName(toolName, detail, agentMessage));
|
||||
return componentForToolCallIcon(resolveToolCallIconName(toolName, detail));
|
||||
}
|
||||
|
||||
@@ -41,9 +41,12 @@ export function createScheduleCommand(): Command {
|
||||
.option("--expires-in <duration>", "Time to live for the schedule"),
|
||||
).action(withOutput(runCreateCommand));
|
||||
|
||||
addJsonAndDaemonHostOptions(schedule.command("ls").description("List schedules")).action(
|
||||
withOutput(runLsCommand),
|
||||
);
|
||||
addJsonAndDaemonHostOptions(
|
||||
schedule
|
||||
.command("ls")
|
||||
.description("List new-agent schedules")
|
||||
.option("--all", "Include schedules targeting existing agents"),
|
||||
).action(withOutput(runLsCommand));
|
||||
|
||||
addJsonAndDaemonHostOptions(
|
||||
schedule.command("inspect").description("Inspect a schedule").argument("<id>", "Schedule ID"),
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user