Compare commits

...
Author SHA1 Message Date
Mohamed Boudra cbedec1ed6 fix(app): keep a panel's render error inside that panel
A render exception in any workspace panel, in the explorer or a split
pane, had no boundary between it and the root error boundary, so it
replaced the whole app with the root error screen. A workspace saved
with that panel selected took the app down again on every open.

The plugin surface boundary already contained errors for plugin
surfaces. Its error-catching core is now a shared RenderErrorBoundary,
and the panel host wraps every mounted panel in it. A failed panel
shows the error with a Retry button; the other panels, the chat, the
sidebar and workspace switching keep working. Plugin surfaces keep
their own "Plugin failed" state because their boundary sits inside the
panel and catches first.
2026-11-29 17:53:33 +01:00
Feraidoon MehriandClaude Opus 5.5 d63f0204e5 fix(cli): list pending permissions of background agents in permit ls (#10655)
permit ls read one page of fetch_agents without includeBackground, so it missed requests from background agents and from any agent past the first 200. Read every page through fetchAllAgents and include background agents when the host supports them.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 16:12:45 +00:00
paseo-bot[bot]andThomas Van 9c9c839bd0 fix(pi): keep the daemon alive when an extension prompt fails (#11329)
Observe extension result rejections before awaiting the prompt response. Callers still receive the original prompt or extension error.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Thomas Van <9481872+thomasvan@users.noreply.github.com>
2026-11-29 15:42:43 +00:00
paseo-bot[bot]andClaude Opus 5.5 0e8e3987a0 Wait for the model sheet to settle before comparing Profiles and Model (#11330)
The compact-drawer step read the Profiles and Model rows' boxes in two
calls while the bottom sheet was still sliding up, so the second read
could land above the first. Wait for the sheet to stop moving first,
with the existing sheet-layout helper.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 15:38:05 +00:00
0b1b2dd286 Keep plugin-transformed replies distinct in chat history (#8498)
* fix(app): keep chat history from crashing when two rows share an id

The chat virtualizer caches measured row sizes by key, and the key was the
row id. When two history rows had the same id, both rows wrote the same
cache entry. Each measurement pass set the size to the other row's height,
so the layout effect re-rendered without end and React aborted with
"Maximum update depth exceeded" (minified error #185).

Give each virtualized row a unique key. A repeated id gets a numeric
suffix, and the first occurrence keeps its plain id so the reading anchor
still matches it.

* fix(plugins): keep transformed replies distinct in chat history

Replacement IDs are local to their source message. Reusing a stable output
ID across replies aliased the row and virtualizer caches, reproducing a
packaged desktop React #185 crash. Scope row identity at projection and
retain the original prompt identity for navigation.

Build on the contributor regression, exercising transformed source rows
instead of assigning occurrence keys in the virtualizer.

Co-authored-by: Kevin Le <anhle12892@gmail.com>
Co-authored-by: ykurilov <110710320+ykurilov@users.noreply.github.com>

* test(plugins): verify repeated timeline IDs in a real browser

Exercise the installed plugin through the real daemon and chat viewport. Read the oldest virtualized replacement before and after reload, using actual browser row heights instead of extending the legacy JSDOM harness.

* test(app): use projected row IDs in turn footer assertions

---------

Co-authored-by: Kevin Le <anhle12892@gmail.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: ykurilov <110710320+ykurilov@users.noreply.github.com>
2026-11-29 14:42:45 +00:00
Mohamed Boudra 2c0bc525d3 perf(app): stop holding a copy of every cached transcript in renderer memory (#11322)
* perf(app): keep only row keys and sizes in the replica cache index

The replica cache kept every stored payload string in memory to enforce its
disk budget, so the renderer held a second copy of each cached transcript until
restart (#6477). Row stores now report each row's key and UTF-8 payload size
without loading payloads, and the cache budgets on those sizes alone.

* test(app): seed and read the replica cache at the app's database version
2026-11-29 20:54:01 +07:00
Mohamed Boudra 27e35a198d fix(app): close the keyboard when opening a file from the Files tree (#11320)
Since the Files tree gained a filter, its input stays focused when a match is
tapped. The preview sheet opens over the pane without taking input, so the
software keyboard covered the bottom of the file.
2026-11-29 20:23:44 +07:00
Mohamed Boudra 8b7cb47ef2 fix(app): keep Gboard suggestions and double-space period from corrupting Android terminal input (#11318)
* fix(app): keep Gboard suggestions and double-space period intact in the Android terminal

The Android terminal input connection emptied its editable after every
commit, while Gboard keeps its own copy of the committed text and edits it
by offset. On Android 14+ a suggestion pick or double-space period arrives as
replaceText(start, end, text); against the empty editable the range clamped
to [0, 0], so the insert reached the shell but the deletion was lost
(helo -> hello sent "lo ", giving "helolo ").

Keep the current shell line's IME text in the editable and diff it against
what the terminal holds, so offset edits become rubouts plus the new
suffix. Terminal keys still empty the editable; they now restart the IME
because Gboard ignores updateSelection as a signal to reload its text.

* fix(app): reset the Android terminal IME line on Gboard arrow keys

Gboard's editing-panel arrows reach the input connection as key events and move the shell cursor, but the editable kept the typed line. A later suggestion pick then sent rubouts for text the shell cursor was no longer after. Arrows now empty the editable and restart the IME like the other terminal keys.
2026-11-29 19:39:42 +07:00
Mohamed Boudra 693fa22377 fix(app): step back a page on Android Back in Agent settings (#11313)
AdaptiveModalSheet now forwards its header's back to the sheet's Android
Back handling, so Back from the Model page returns to Agent settings and
closes the sheet only from the first page.
2026-11-29 19:39:38 +07:00
Mohamed Boudra 22a318b1de fix(terminal): deliver one DEC 2031 report per theme switch (#11312)
The browser xterm (web and desktop) tracked CSI ?2031h itself and sent its
own unsolicited ESC[?997;Nn whenever its theme changed, on top of the
daemon's report. Query suppression could not catch it because no query is
involved. Every mounted viewer did this, so a background viewer that does
not own the terminal palette could also report a scheme the owner never
showed.

Turn off xterm's colorSchemeQuery extension so the daemon stays the only
DEC 2031 / DSR 996 responder, behind the existing palette ownership.

Refs #2795
2026-11-29 19:38:31 +07:00
paseo-bot[bot] 4f8fed2e2b test(app): wait for both pins before the pinned sidebar drag (#11319)
The pinned drag matched its two rows anywhere in the sidebar. Both rows
also exist in their project groups, so the test read the order while only
one pin had reached the Pinned section. The second pin then put its row on
top, and the drag moved it back down, which left the order the test read.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-29 12:36:39 +00:00
paseo-bot[bot] 97628dfd13 fix(app): open settings for built-in plugins (#11308)
The plugin page gated settings on the managed install list. Use the client catalog to resolve the contributed screen so that built-in plugins can open settings from their links.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-29 10:12:50 +00:00
paseo-bot[bot]andClaude Opus 5.5 25441b1845 test(terminal): read split PTY input in the pressure recovery fixture (#11305)
The ten-thousand-row pressure test's terminal program matched BURST and
echoed AFTER-CATCH-UP per stdin chunk. A PTY can split one input write
across reads, so the burst never ran and the pressured viewer never got
its recovery replay. Match against everything read so far.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 09:36:14 +00:00
Mohamed Boudra e1bb1f8ff1 Quieter, consistent indent guides in the file trees (#11299)
* fix(app): quiet the file tree indent guides in dark themes

The guides borrowed a text colour at half opacity, so they were bright on
dark backgrounds and their strength changed with each theme's text grey.
They now have their own colour, stepped from the sidebar background like
the hover and selected fills, so every theme draws the same weight.

* fix(app): keep tree guides visible off the sidebar

A solid color picked against the sidebar faded where trees sit on other
surfaces, such as the Jump to file sheet and workspace panes. The guide is
now translucent, calibrated to the same strength on the sidebar.
2026-11-29 16:16:38 +07:00
Mohamed Boudra 20354c13b9 Align compact model picker search dock, fix single-provider scrolling, and unify edit pencil (#11295)
* fix(app): align compact search dock, fix single-provider scroll, and unify edit pencil

- Add card-row geometry (`variant="card"`) to SearchField and align the compact
  sheet search footer inset with provider cards (`spacing[4]`) so the docked
  search bar shares outer width, height, radius, icon slot, and text rail with
  the cards above it.
- Render the lone provider's model list in `mobile-model-page.tsx` with
  `SheetFlatList` inside a fixed-header `SheetListCard` so Gorhom's bottom-sheet
  pan gesture no longer steals vertical drags on Android and users can scroll to
  the final rows; remove the unused `SettingsCard` `shrink` prop.
- Extract a shared `EditProfilesButton` (pencil icon) alongside
  `CustomizeProviderButton` so desktop and mobile Profiles and provider headers
  all use the same pencil affordance instead of mixing "Edit" text and icons.

* fix(app): read sheet search footer style at render time
2026-11-29 15:23:29 +07:00
paseo-ai[bot] f3e59c1c86 fix: update lockfile signatures and Nix hash [skip ci] 2026-11-29 08:22:21 +00:00
Mohamed Boudra ce5b60a9e6 feat(workflows): add @getpaseo/workflows durable state-machine package (Slice 1) (#11141)
* feat(workflows): add @getpaseo/workflows package foundation (Slice 1)

* fix(workflows): preserve wakes during pause and prevent signal double-delivery
2026-11-29 15:13:39 +07:00
minamorl 59a5724460 fix(cli): page agent logs over large histories (#10723) 2026-11-29 07:42:38 +00:00
Mohamed Boudra e713f5acf7 Accept newer fields and list variants instead of dropping whole messages (#11284)
* feat(protocol): let older readers accept newer wire messages

A field or variant added by a newer daemon, app, or plugin made an older
reader reject the whole message: strict objects failed on any unknown key,
and one unknown tag in a list (a timeline item, a tool detail, a prompt
content block) failed the page, the RPC, or the provider event.

Wire objects now strip unknown keys, and readers parse through
safeParseSkippingUnknownVariants: when the only failures are unknown tags or
enum values inside lists, those elements are removed and the value is
validated once more. Schemas stay closed so consumer switches stay exhaustive
and the generated validators need no catch-all branch; the reader works on
issues, so the generated validator and Zod agree. An unknown variant outside
a list still fails that one message, flagged unknownVariant.

config.json stays strict through local strict copies so typos still fail, the
browser automation request stays strict so legacy tab targeting is rejected,
and plugin hook results stay strict so a host without wrap fails closed.

* docs(plugins): plugins read the provider protocol with the host SDK
2026-11-29 13:36:13 +07:00
paseo-bot[bot] a271074716 Order the ACP probing test's reads like the daemon warm-up (#11287)
The cold-start test fired the global read and three workspace reads
together. Each read resolves the plugin launch before it binds the
shared catalogue, so on Windows a workspace read sometimes bound first.
The probe then spawned in that workspace's cwd, which the test never
creates, and every target reported spawn ENOENT.

Start the global read, wait for its probe to spawn, then add the
workspace reads, as the snapshot refresh does.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-29 06:36:02 +00:00
Mohamed Boudra c026b27639 Polish model picker stability, rails, and Agent settings profiles (#11280)
* fix(app): polish model picker stability, rails, and Agent settings profiles

Fixes post-redesign jank and surfaces profiles directly in Agent settings:

- Give model picker FlatList rows deterministic heights with getItemLayout, initialScrollIndex, iOS contentOffset, and synchronous pre-paint web scroll positioning so reopening a deep selected model or switching providers never flashes offset 0.
- Replace the swapped collapsed/expanded mobile accordion headers with one unified CollapsibleSectionHeader so toggling never shifts icons, labels, or chevrons.
- Tighten compact mobile model row horizontal padding from spacing[6] to spacing[4] so Model rows share the same rail as SettingsCard rows on Agent settings Home.
- Remove noisy model/profile counts from desktop rail rows, pane headers, and mobile section triggers while keeping counts on fold rows.
- Extract a collapsed, scrollable Profiles card onto Agent settings Home above Model (keeping unified search on the Model page) and match SettingsRowHeader trailing summary font size to its row title.
- Keep desktop single-provider pickers in the 360px single-pane layout with matching profiles above models instead of showing a two-row left rail.

* fix(app): share initial list scroll hook, apply Android contentOffset, and keep single-pane profiles on load/error

- Extract useInitialFlatListScroll in scroll-reveal.ts so desktop and mobile pickers share one implementation and apply contentOffset on both Android and iOS (ReactNestedScrollView applies pendingContentOffset during native layout before first paint, removing the 3-frame blank flash observed when re-expanding on Android API 35).
- Share orderProvidersForPicker between the desktop rail and mobile accordion sections.
- Keep single-pane profiles visible and actionable while the lone provider is loading or errored, with projection tests for both states.
2026-11-29 13:27:43 +07:00
Mohamed Boudra 526aa3133e fix(server,app): stop leaking uploadedImage metadata into plugin provider prompts (#11281)
#11137 attached daemon-internal uploadedImage metadata onto AgentPromptContentBlock
image entries so AgentManager could project user_message.images thumbnails.
Built-in providers copied only data and mimeType, but plugin-backed providers
forward content blocks verbatim into strict ProviderInputSchema validation,
causing every uploaded image sent to any plugin provider to fail with
unrecognized_keys: ["uploadedImage"].

- Remove uploadedImage from AgentPromptContentBlock and have resolveAgentPrompt
  return { prompt, uploadedImages } separately.
- Thread uploadedImages alongside prompts through create, send, queue, and steer
  paths in AgentManager, AgentMessageDelivery, and Session while stripping
  daemon-only metadata before calling provider startTurn/steerActiveTurn.
- Advertise server_info.features.uploadedImageAttachments and gate app image
  uploads on it so older daemons (through v0.18.1) keep receiving inline base64
  vision blocks instead of degrading uploaded images to file-path text.
2026-11-29 13:20:47 +07:00
Mohamed Boudra b08a0bc6ce Keep iOS composer taps and the model picker clear of the keyboard (#11276)
On iOS the composer dock rises with the keyboard through a native-driver
transform that never reaches the shadow tree. Pressability measures its
press region there, so a tap that drifted a few points left the stale
region and was dropped: Send, attach and the model selector often ignored
taps while the keyboard was open. The translate view now commits its
resting lift to the shadow tree once the keyboard settles.

On wide layouts the native model popover was placed against the whole
window and measured the trigger while the keyboard hid and reshowed for
the search field, so it opened over the keyboard. Combobox now adds the
settled keyboard height to its collision padding, which also re-measures
the trigger after the lift lands.
2026-11-29 12:32:21 +07:00
paseo-bot[bot]andlucamzanon d7404733f6 fix(claude): keep idle agents ready after a clean exit (#11273)
The daemon reported every exit between turns as lost work. Keep the
agent idle when the process exited cleanly and had no work to lose.
Preserve the order of failure and background cleanup when work was lost.

Co-authored-by: lucamzanon <luca.m.zanon@gmail.com>
2026-11-29 05:12:42 +00:00
Mohamed Boudra 0d215ecf29 fix(app): keep the composer's focus border neutral (#11272)
The focused composer frame took the theme accent, a bright green outline
around the largest control on screen. It now steps from borderAccent to
surface4, a grey, and the hover step is gone: surface3 is fainter than
the resting border in the pure black theme, and surface4 on hover would
look the same as focus.
2026-11-29 11:53:56 +07:00
paseo-bot[bot]andClaude Opus 5.5 df45627da5 fix(app): measure and draw SVG files in native image previews (#9094)
On Android and iOS, the image preview measured its file with React
Native's Image.getSize, which cannot decode SVG. The measurement
failed, the panel stayed empty, and the SVG never showed.

Measure with Expo Image's loadAsync and draw with Expo Image, which
decode SVG and raster images alike. The preview still paints nothing
until the size is known, and still appears together with its toolbar.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 04:12:37 +00:00
Mohamed Boudra 5343d72939 Avoid hydrating unrelated workspaces on single-ID and filtered lookups (#11266)
* perf(server): pre-filter workspace lookups before building descriptors

Single-workspace lookups through DaemonClient.findWorkspace (and workspaces.ref(id).refresh()) previously requested unfiltered pages of 200 workspaces, and WorkspaceDirectory.listFetchEntries hydrated descriptors and read paseo.json for every active workspace before filtering.

Pass the existing filter.query = workspaceId from DaemonClient.findWorkspace (requiring zero protocol changes and remaining compatible with older daemons) and pre-filter active persisted workspace records in WorkspaceDirectory.listFetchEntries before building descriptors or loading agent payloads. Live git branch names from workspaceRuntimeStore are resolved synchronously during pre-filtering so free-text queries preserve identical matching behavior.

* refactor(server): share workspace name resolver between descriptor builder and pre-filter

Have describeWorkspaceRecord, describeWorkspaceRecordWithGitData, and WorkspaceDirectory pre-filtering all call Session.resolveWorkspaceDescriptorName, and make resolveWorkspaceName required on WorkspaceDirectoryDeps so the pre-filter and descriptor name rules cannot drift.
2026-11-29 11:08:43 +07:00
paseo-bot[bot] 990721e134 fix(app): keep agent metadata after reload (#11265)
The agent directory cache dropped metadata while keeping the cursor. Require metadata in cached snapshots so older rows trigger the existing agent directory refresh.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-29 11:08:17 +07:00
paseo-bot[bot]andClaude Opus 5.5 b1677e58d8 Start Windows terminals when ConPTY's output worker is slow (#11238)
* fix(terminal): let a Windows terminal start when ConPTY's worker is slow

node-pty starts a worker thread for ConPTY output and waits 5 s for it
to report ready. When the message comes later, it fails the spawn and
the program exits with code -1 before it runs. On a loaded Windows CI
runner this made "delivers MCP key tokens through in-process" find no
terminal at all. Patch the wait to 30 s; a worker that fails still
reports an error at once.

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

* test(terminal): block the event loop from a check-phase callback

The old 5 s ConPTY timer now always runs before the worker's ready
message, so the test fails without the node-pty patch.

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

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 00:55:51 +00:00
08298dcc10 Show an agent's thinking level when its model does not list it (#10937)
When an agent's thinking level was missing from its model's list, the
composer button, the picker's check mark and the facts line each fell
back to the list's first option. An agent on Extra High with a Claude
settings model (Low, Medium, High, Max) showed Low. The agent's level
now joins the list the controls read, so they show and check it.

Co-authored-by: Orcun Simsek <1612171+ortschun@users.noreply.github.com>
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 22:42:58 +00:00
Fohong WangandClaude Opus 5.5 cafb42560c fix(desktop): open the Antigravity IDE instead of the agy CLI (#10893)
Open in Antigravity resolved `agy` first. agy is now the standalone
Antigravity CLI agent, so the editor never opened. Resolve the IDE's
`antigravity-ide` launcher (or the Antigravity IDE app) instead, and do
not treat Antigravity.app (com.google.antigravity), a separate app, as
the editor.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 22:42:36 +00:00
Tomblarom 6655aa77b3 Apply current plugin instructions when Claude resumes (#10917)
Rebuild the Claude system prompt on resume so plugin append changes and removals reach the next turn while keeping the conversation history.
2026-11-28 22:12:42 +00:00
Tomblarom 291d54fa71 fix(muse): send the current system prompt after resume (#10915) 2026-11-28 21:12:39 +00:00
paseo-bot[bot]andShane Su ddb15230b3 Show existing-agent schedules in CLI listings on request (#11243)
* Show how to include agent targets in schedule listings

* fix(cli): show the schedule hint in every table format

Use the renderer's output settings so the table alias includes the same hint about agent-target schedules.

Co-authored-by: Shane Su <26364206+suniceman@users.noreply.github.com>

---------

Co-authored-by: Shane Su <26364206+suniceman@users.noreply.github.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-28 20:42:37 +00:00
Matt Cowger 9dc533fcd2 fix(omp): skip skills, session, and title in catalogue sessions (#11129)
- Background catalogue refresh started full OMP sessions whose startup routing-hint calls were cancelled on close every tick (#11128).
- Pass --no-skills --no-session --no-title to fetchCatalog sessions only; agent sessions keep skills.
- Test that the flags apply to catalogue launches and not agent launches.
2026-11-28 20:13:03 +00:00
LiebeLee 0ee4a57981 fix(omp): keep the idle deadline on provider silence (#11079)
* fix(omp): keep the idle deadline on provider silence

- Honor agent_end.isTerminal: a queued continuation or async delivery no longer starts the 600 s failure clock; the final end owns the idle wait.
- Measure the deadline from the last provider event and suspend it while an extension-UI question or approval waits for the user.
- Abort the provider before failing a timed-out turn so the next prompt is not rejected with "Agent is already processing"; replace the runtime on the next prompt if the abort fails.
- Clear pending UI requests when the turn settles so idle runtime collection is not blocked.

Refs #8908.

* test(omp): prove the idle gate skips non-terminal agent_end

The first version observed getState counts, but the gate calls getState once before it blocks on the scheduler, so the assertion could pass on the old code. Count scheduler waits instead: the broken gate waits, the fixed one does not.
2026-11-28 20:12:40 +00:00
Konrad Karkosz aa957c9ca9 fix(app): show focus on the composer frame (#11097)
* fix(app): show focus on the composer frame

The composer frame kept its resting border whatever you did, so it was the
only text input that never showed hover or focus, and its 200ms
border-color transition on web never ran.

Focus now turns the frame's border the theme accent, as other inputs show
their focus ring. On web, hovering an unfocused frame raises the border to
surface4: the controlHover colour (borderAccent) is already the composer's
resting border, so reusing it would change nothing. Read-only and disabled
composers stay at rest. The phase comes from getControlInteractionPhase,
the helper the other inputs use, and hover follows docs/hover.md (pointer
events on the plain frame View).

* test(app): cover composer frame hover and focus

Reads the frame's settled border colour at rest, on hover, while focused and after blur.
2026-11-28 19:13:06 +00:00
Juns a96a4d61f1 fix(acp): do not settle deferred turn after interim reply when a background tool completes (#10924) 2026-11-28 19:12:37 +00:00
Mohamed Boudra 6916ceee47 test: fix the Claude listing heap test and the hero opening-scene race (#11204)
The Claude listing heap test capped its child at 96 MB, but most of
that budget went to loading the modules. Since prompt attachments
import the file-upload module, agent.ts also loads the protocol message
schemas, about 50 MB more. The 14 MB listing then ran out of heap on
runs where GC ran late. The test now measures what the imports retain
in a first child, then caps the listing child at that plus 64 MiB. That
is still below the 128 MiB transcript, so loading a whole history still
runs out of heap.

The opening-scene tests advanced the paused page clock once, right
after the scroll. The scene starts a few page tasks later
(IntersectionObserver, then a React render and effect). When the clock
advance ran first, the scene started on a paused clock and the request
never appeared. The tests now advance the clock in 1 s steps until the
request shows.

CI also uploads the website Playwright results when that step fails,
so the next stall has a trace.
2026-11-28 22:40:58 +07:00
Mohamed Boudra 635df88fa6 fix(ci): stop painting main commits red when packaging runs are superseded (#11200)
* fix(ci): let Docker and Desktop Packages runs on main finish

Each merge cancelled the packaging runs still going for the previous main commit, and the CANCELLED checks painted that commit red. #11192 fixed this for CI only.

* test(terminal): give slow Windows output time to reach the buffer

The test allowed 10s for 3000 console writes. Passing Windows CI runs take 0.7s to 9.5s, so a loaded runner crossed the limit. The suite allows 30s per test.
2026-11-28 21:54:26 +07:00
552690e45c fix(claude): settle advisor_tool_result blocks and redact encrypted payloads (#11202)
Co-authored-by: Lucas Vale Queiroz <142512124+LucasValeQueiroz@users.noreply.github.com>
Co-authored-by: SirisZheng <70536096+SirisZheng@users.noreply.github.com>
2026-11-28 14:42:41 +00:00
Mohamed Boudra 9815d68f3b Redesign model selection across desktop, phones, and provider settings (#11186)
* feat(providers): choose which models pickers show first

Provider settings now let you check the models pickers should list first,
with Reset and Undo. Claude's previous releases are marked legacy so
pickers can fold them; the default model is never legacy.

shownModels is overlaid on the provider snapshot at publish time instead of
living in the provider definition's configuration. Anything in that
configuration rebuilds the client and rediscovers the catalog when it
changes, which a checkbox toggle must not do. The catalog is never trimmed,
so search still finds every model.

The settings list keeps its order while you check boxes and re-sorts only
on search, reload, reset or undo, so rows never move under the pointer.
Gated on server_info.features.providerShownModels.

* feat(app): browse models in a two-pane desktop picker

On wide layouts the model picker shows a rail of Profiles and providers
beside the open provider's models. Each provider lists its chosen models
first and folds the rest under "Older models" or "All models". Search
covers every provider and profile at once, ranks shown models ahead of
folded ones, and tags folded matches. Arrow keys move between the rail
and the list, and Escape clears a query before it closes the picker.

The rail is kept on any surface that offers profiles, even with none
yet, so a one-provider host can still reach profile creation. Surfaces
without profiles and with one provider get a single 360px pane. Compact
layouts keep the existing sheet.

* feat(app): set up agents from one drawer on phones

The compact composer opened a second sheet on top of the first for the model
and each control. Phones now get one "Agent settings" drawer whose pages swap
in place: Home inlines thinking and speed pills, switches, and Mode as a radio
list (bypass modes in the warning colour); Model stacks providers as cards with
the open one in a fixed 220px box, so the others stay reachable below it, and
search sits in the thumb zone; Profiles lists saved profiles. Escape clears the
search, then returns Home, then closes. The standalone selector reuses the
Model page. Wide and desktop layouts are unchanged.

The Model page shows an empty state when the host lists no providers, which is
also the state before the first provider snapshot; the shared picker otherwise
falls back to its profiles rail and the page threw.

Themed padding sits on wrapper Views, not contentContainerStyle: the sheet
scrollers drop a themed contentContainerStyle on web.

* fix(app): finish the model picker redesign on phones and in search

- Cycle modes with the keyboard on phones again. The shortcut lived in the
  Mode control, which on phones only mounts while the settings drawer is
  open; the composer's controls now own it on every layout.
- Scroll a folded selected model into view when the phone Model page
  reopens. The fold opened, but the list stayed at the top.
- Rank search results by match strength before shown-vs-folded. Putting
  every shown row first let loose letter-order matches on uncurated
  providers bury exact matches on folded models, such as "Opus 4.6".
  Shown models still win ties.
- Drop ModelBrowser options and sheet scrolling that no caller uses, and
  let SettingsCard shrink instead of the phone list copying its style.

* feat(app): polish mobile model drawer, thinking slider, and desktop focus

- Use a pencil icon button for provider model customization instead of a text label.
- Restore composer focus after picking a model on desktop in workspace drafts and New Workspace, which previously omitted onDropdownClose on DraftAgentControls.
- Move Profiles out of the phone Home card into the Model accordion as the first collapsible category with unified profile + model search, and let every accordion section collapse.
- Render ordered thinking effort and token-budget ranges on phones as a switch-style stepped capsule slider with step dots, and restore the provider icon beside the selected model name plus control icons on inline sections.

* fix(app): fix Android bottom search dock height and update E2E picker helpers

- Give SheetSearchDock flexDirection: "row" and relax SearchField's input height from 20 to minHeight: 20. Inside a column container, SearchField's flex: 1 collapsed vertically on Android and clipped text at the bottom of the Model drawer.
- Update E2E helpers for the redesigned picker: selectPluginModel picks directly from the two-pane rail without clicking Back; applyProfileFromPicker opens the Profiles rail entry first; selectModel clears search on first Escape before closing on second; codex-speed interacts with compact Speed pills inline on Home and verifies the section header icon highlight.
2026-11-28 21:23:34 +07:00
Mohamed Boudra 59377767c7 fix(server): auto-deny unexpected permission prompts in unattended Hub runs (#11179) 2026-11-28 20:53:10 +07:00
Mohamed Boudra 67612b36f3 fix(nix): restore daemon server export in Nix trace and run Nix smoke on PRs (#11193)
* fix(nix): trace runtime edges with dynamic import and verify Nix on PRs

Bundling @getpaseo/cli in #11155 added an esbuild banner that aliases
createRequire as __paseoCliCreateRequire. @vercel/nft only follows
injected require() calls in ESM when createRequire is imported unaliased,
so scripts/trace-daemon.mjs silently dropped @getpaseo/server's exports.js
and exited 0 while the Nix daemon smoke failed at startup.

Inject runtime dependency edges with dynamic import() so nft follows them
in ESM regardless of createRequire aliasing and in CJS without changing
the parsed module type. Assert after tracing that every declared runtime
dependency target and its importer edge are present in nft's file list
before expanding additionalInputs, and run the Linux Nix build and daemon
smoke on pull requests touching Nix, CLI, server, or daemon packaging
inputs.

* fix(nix): include desktop and is-main-module in Nix PR path filter

scripts/trace-daemon.mjs imports scripts/is-main-module.mjs and the
Linux Nix build job also builds .#desktop with PASEO_TRACE_DESKTOP=1.
Include both paths in nix.yml pull_request.paths so changes to either
exercise the Nix build and trace checks before merge.
2026-11-28 20:53:05 +07:00
Mohamed Boudra 01227a73a4 fix(ci): stop painting interrupted main runs red and run CLI tests on server changes (#11192)
* fix(ci): finish main runs and run CLI tests on daemon changes

Cancelling a main run mid-flight left CANCELLED checks that painted the
commit red. Server PRs skipped cli-tests, which drive a real daemon, so two
server regressions first failed on main.

* test(plugin): let the ACP crash be reported before replay ends

The fake agent exits 20 ms after its last history chunk, and the provider
ended replay after 100 ms of silence. When Windows reported the exit later
than that, the open succeeded and the test never saw request.failed.
2026-11-28 20:50:29 +07:00
Kogeki 12a6f07939 fix(app): prevent React #185 update loops in web chat virtualizer (#11138) 2026-11-28 13:42:45 +00:00
paseo-bot[bot] 34d38a82d2 test(server): keep ACP replay open until shutdown in the reopen shutdown test (#11182)
The fake agent streams a history chunk every 20 ms, but the provider ended
replay after 100 ms without one. A runner stall longer than that ended
replay before the daemon stopped, so the reopen finished and the timeline
request resolved instead of being rejected. A 1 s quiet period keeps the
test on the path it checks: shutdown while replay is still streaming.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-28 12:54:40 +00:00
paseo-bot[bot]and3ae3ae d71d9b37c6 fix(opencode): add the Default thinking option for v2 models (#11184)
The v2 thinking picker listed only a model's explicit variants, so a user who
picked one could not go back to the model's base behaviour. List Default first,
as the v1 adapter does, and send no `variant` when it is selected.

Closes #7225

Co-authored-by: 3ae3ae <ogyshjsm@naver.com>
2026-11-28 12:42:51 +00:00
lukeandRoundRedDot eae885fba4 fix(app): hold back a closing code fence while it is still being typed (#7006)
While a reply streams, the last line of an open code block can hold one or
two backticks of the fence that will close it. Painted, they are a line of
code that disappears a moment later.

The reveal now withholds that line while the turn streams until it closes
the block or turns out to be code. Finished turns paint everything.

Co-authored-by: RoundRedDot <roundreddot@gmail.com>
2026-11-28 12:12:54 +00:00
Mohamed Boudra 6ec8941943 fix(server): report a delegated agent's turn ends as compact tool calls until it settles (#11175)
* refactor(server): let the daemon decide whether an agent message is a tool call or a message

Lifecycle notices (finished, errored, needs permission, closed, still working) now reach
clients as ordinary plain-text tool calls such as "Agent finished · Child". Only peer
send_agent_prompt messages keep the agentMessage sender so they still render as a
"Sent by" bubble. No protocol fields were added.

Delivered prompts carry a trailing <paseo-message .../> marker instead of a leading
<paseo-system> envelope, so the body (including a slash command) stays at character 0
and is no longer XML-escaped. Plain human messages get no marker unless they share a
turn with agent messages or contain marker syntax. Legacy envelopes and legacy
agentMessage notification rows keep rendering (COMPAT tagged).

* fix(server): keep a delivered message's sender when a provider trims the replayed prompt

Claude history replay trims each user prompt, so a body that started with whitespace came
back shorter than the marker's length and replayed as raw text. Drop the body's leading
whitespace before writing the marker.

* fix(server): stop waking the parent when a delegated child ends its turn but is still working

#10864 told the caller "ended its turn but is still working" whenever a child's turn ended
with work pending, and "is still working" after 24 hours of following. The caller could not
act on either notice; it only woke up to wait again. The watch now follows such a child
silently and reports once: finished when it settles, or errored, permission, and closed as
they happen. After 24 hours it reports finished with the child's last reply, so a task that
never ends cannot hold the caller forever.

The still-working event and its agent_still_working tool are gone. Transcripts with #10864's
event="message" notices replay as messages from the child, as clients showed them then.

* fix(server): report every turn end and keep following until the child settles

A child that ends its turn while it still has pending work (a background task such as
`npm run dev`, queued messages, or its own delegated agents) now reports `finished` to its
caller at once. The notice names the pending work and says the caller will hear again. The
subscription keeps following the child: each later turn end reports again, and the child
settling with nothing pending, with or without another turn, sends the final `finished`.
The 24-hour follow limit sends a final `finished` with the child's last reply.

Every notice is a plain `agent_finished` tool call. There is no still-working event.

The observation's initial wait no longer repeats a turn end the stream already reported,
which would have sent the first turn end twice.
2026-11-28 19:01:24 +07:00
paseo-bot[bot]andtieo dbeb181f03 fix(server): keep concurrent agent reloads from failing (#8369)
* fix(server): share concurrent agent refresh results

Keep a refresh in flight until provider history has been hydrated so concurrent
requests receive the same reload outcome across connections.

* fix(server): keep concurrent refreshes within their daemon

Hold reload and history hydration together across client connections, and scope
pending work to the agent manager that owns it. Exercise the real daemon with a
slow-history provider, separate managers, shared failures and subsequent retries.

Co-authored-by: tieo <65707274+tieo@users.noreply.github.com>

* fix(server): capture reload reply before publishing updates

* test(server): run concurrent refresh coverage in CI

* fix(server): preserve each refresh caller workspace recovery

---------

Co-authored-by: tieo <65707274+tieo@users.noreply.github.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-28 11:42:40 +00:00
325 changed files with 28328 additions and 2826 deletions
+7 -2
View File
@@ -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"
@@ -60,6 +60,7 @@ sdk:
- "packages/client/**"
- "packages/highlight/**"
- "packages/protocol/**"
- "packages/workflows/**"
browser:
- "packages/server/src/server/agent/provider-snapshot-manager.ts"
@@ -87,5 +88,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/**"
+26 -5
View File
@@ -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
@@ -127,6 +128,14 @@ jobs:
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
run: npm run test --workspace=@getpaseo/highlight
- name: Build workflows package
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
run: npm run build:workflows
- name: Run workflows tests
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
run: npm run test --workspace=@getpaseo/workflows
- name: Typecheck client examples
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
run: npm run typecheck:examples --workspace=@getpaseo/client
@@ -174,6 +183,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 +225,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
+3 -1
View File
@@ -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
+3 -1
View File
@@ -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
+30
View File
@@ -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
View File
@@ -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.
+2 -2
View File
@@ -329,7 +329,7 @@ messages or transfers.
### Compatibility rules
- WebSocket schemas are append-only. Add fields, do not remove fields, and never make optional fields required.
- New wire enum values must be gated at serialization with `session.supports(CLIENT_CAPS.someCapability)`.
- New wire enum values must be gated at serialization with `session.supports(CLIENT_CAPS.someCapability)`. An older reader skips an unknown value inside a list; gate it anyway when the old client must see something.
- Capabilities belong to the physical source socket. `session.supports(...)` reads the requesting or observing source at the domain projection boundary; one socket must not borrow a sibling's capabilities.
Example: adding a new enum value
@@ -337,7 +337,7 @@ Example: adding a new enum value
```ts
// 1. Add CLIENT_CAPS.newThing = "new_thing"
// 2. Let new clients advertise it in WS hello
// 3. Keep the shared producer schema strict
// 3. Add the value to the shared schema; no catch-all branch
// 4. Gate the new emitted value: session.supports(CLIENT_CAPS.newThing) ? "new_value" : "old_value"
```
+6 -1
View File
@@ -601,7 +601,12 @@ The cache is capped at 32 MiB and evicts whole hosts in least-recently-written o
eviction, only a baseline replacement stores that host's directory again. Mutations queued around
the eviction are dropped when they are written, so a checkpoint never outlives its rows. Budget
bookkeeping may scan opaque row sizes during a deferred write, never during host registry startup or
before a requested cache row can paint. The row store is not encrypted. A cached timeline can contain
before a requested cache row can paint. The cache holds only each row's key and UTF-8 payload size,
never the payload: a timeline row can be megabytes, and the renderer would hold a second copy of
every cached transcript until restart. Each store reports sizes without loading payloads. SQLite
measures the stored text, and IndexedDB records the size on the row and reads an index over it.
Opening an IndexedDB database written before that index existed drops its rows, because they would
be readable but never counted against the budget. The row store is not encrypted. A cached timeline can contain
source code, prompts, and tool output; encrypted-at-rest storage is a separate security decision.
### Saved hosts
+3 -4
View File
@@ -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
+21 -5
View File
@@ -301,9 +301,10 @@ translation scope is React context and does not cross it (Gotcha 7). It returns:
height with it; never animate height per frame.
Do not measure an anchor with `measureInWindow` and correct it by the keyboard
shift. On iOS the translate view uses the native driver, and `measureInWindow`
includes its transform only when the view happened to re-render since the
keyboard moved. Both results were observed, so any correction double-lifts the
shift. On iOS the translate view uses the native driver, which moves the view
without updating the shadow tree. The translate view commits the resting lift to
the shadow tree once the keyboard settles, so `measureInWindow` includes the lift
at rest and misses it while the keyboard moves. Any correction double-lifts the
popover or leaves it behind the keyboard. `measureAtRest` measures through
Fabric's transform-free `measureLayout` instead. Re-measure when `isMoving`
settles; the composer's resting position changes as the draft grows.
@@ -315,8 +316,8 @@ the anchor's rect against the layer and commits the placement with `flushSync`,
which runs after layout and before paint. On native a Reanimated frame callback
reads only the anchor's height on the UI thread and holds its bottom edge at
the rest measurement. A height carries no transform. On iOS the absolute
position does not reliably include one: the keyboard lift runs on the native
driver and reaches the shadow tree only when the view re-renders. The
position does not include one while the keyboard moves: the lift runs on the
native driver and reaches the shadow tree only at rest. The
fixed-bottom model is wrong for the centered New workspace composer on tablets,
which grows around its middle, and for width or x changes. The popover is off
there by half the growth, or by the old width, until the next rest measurement.
@@ -324,6 +325,21 @@ Keep the portal's `KeyboardTranslateView` host-sized with
`pointerEvents="box-none"` and position the popover inside it, so the popover
moves without leaving its parent's bounds (Gotcha 1).
The resting commit also keeps touches working. Pressability measures a
`Pressable`'s press region in the shadow tree. If the region stays at the
unlifted position, a tap that drifts a few points leaves it and the press is
dropped. This hit every control in the dock: Send, attach, and the model selector.
`Combobox` positions its native popover with floating-ui against the window, and
the software keyboard covers part of the window. It adds the settled keyboard
height (`useSettledKeyboardHeight`) to its bottom collision padding. The height
changes on `keyboardDidShow` and `keyboardDidHide`, at the end of the move. The new
padding re-measures the anchor on the next frame, when the resting lift is in the
shadow tree, so the popover follows an anchor that rides the keyboard.
Opening the model picker moves focus to its search input, and the keyboard hides
and shows again on the way. A height that changes at `keyboardWillShow` instead
measures the trigger before it lifts and leaves the popover over the keyboard.
The provider also reconciles iOS from the controller's native `onEnd` event.
The controller's stock iOS shared values update at move start and during an
interactive move, but not at the terminal event, so JS contention can otherwise
+4 -1
View File
@@ -127,7 +127,10 @@ With a Codex draft selected, set `_SCENARIO=growth` on a 402pt-wide iPhone to
check live wrapping, shrinking, the 12pt anchor gap, and command insertion. Set
`_SCENARIO=previews` on an SE-sized iPhone to check long and short descriptions
under an eight-line draft, selection with the keyboard shown and hidden, and
file mentions. These scenarios only need `_SERVER_ID` and `_WORKSPACE_ID`;
file mentions. Set `_SCENARIO=controls` to tap the attach button and the model
selector with a 3pt drag while the keyboard is open, then check that a wide
layout's model popover clears both the trigger and the keyboard. Run it on an
iPhone and on the iPhone Duo unfolded. These scenarios only need `_SERVER_ID` and `_WORKSPACE_ID`;
`_UDID` selects an exact simulator and `_ARTIFACTS_DIR` overrides the output path.
The Android sidebar scroll-retention flow requires a connected host with enough
+6
View File
@@ -639,6 +639,12 @@ effective configuration and execution environment, or
`undefined` for target-specific caching. Ignore `force` when choosing identity. Existing providers
need no change. See [catalogue ownership](providers.md#provider-snapshot-refresh-contract).
Both sides of the provider protocol ignore fields they do not know. A list element of an unknown
kind, such as a prompt content block, a command kind, or a timeline item, is dropped and the rest of
the input or event is kept. The daemon drops an event of a kind it does not know and keeps the
connection open. Paseo supplies the SDK at runtime, so both sides read with the daemon's parser. An
input the provider must act on still needs a connection capability, as `session.launch_wrap` does.
`send()` resolves after acceptance. Publish operation completion, prompt disposition, turn state,
configuration, permissions, persistence, and complete timeline snapshots through `onEvent()`.
Route messages, structured commands, steering, and command side effects through `session.prompt`.
+3
View File
@@ -17,6 +17,9 @@ A schema change must not break parsing in either direction. An old app still par
- A field you stop sending stays accepted. You stop writing it, you don't stop reading it.
- Wire schemas are pure structural declarations. No `.transform()`, `.catch()`, or `.preprocess()` on WebSocket message schemas — normalization happens in an explicit pass after validation. The reason is in [protocol-validation.md](protocol-validation.md): inbound validators are generated, and the generator only compiles pure schemas.
- Plain `z.union()` is forbidden when every branch shares a literal tag. Use `z.discriminatedUnion()`.
- Wire objects ignore keys they do not know. Never put `.strict()` or `z.strictObject` on a schema that reads another process's data. `packages/protocol/tests/validation/evolvability.test.ts` audits every app↔daemon schema. Strict objects belong to local files that should reject typos, such as the `config.json` copies in `packages/server/src/server/persisted-config.ts`. The browser automation request is the one wire exception: it rejects legacy tab targeting so a request cannot run against the wrong tab.
- An unknown variant inside a list costs one element. Readers parse through `safeParseSkippingUnknownVariants` (`packages/protocol/src/validation/unknown-variants.ts`): an unrecognized tag or enum value inside an array drops that element and keeps the message. Outside an array the read fails with `unknownVariant: true` and the reader drops that one message. Schemas stay closed, so consumer `switch`es stay exhaustive. Pruning reaches a list only through objects, arrays, and discriminated unions; a list under a plain `z.union()` branch or a record value is not pruned.
- Skipping is not support. When an old reader must see something for the feature to make sense, gate the new value at serialization ([architecture](architecture.md#compatibility-rules)).
- `.default()` belongs on primitive leaves only, never on item schemas inside large arrays or big inbound containers.
Two questions to ask before you commit a schema change:
+1 -1
View File
@@ -6,7 +6,7 @@ The reason is mobile performance. A captured 353 KB provider snapshot cost about
## Runtime Path
`packages/protocol/src/validation/ws-outbound.ts` is the shipped boundary. It validates the envelope with a generated validator that checks only each session message's `type` tag, then runs the generated validator for that one message type and returns the validated data. Issue paths from the message validator, including nested union branches, are prefixed with `message`, so callers see the same issues as when one validator covered the whole envelope. It does not normalize, repair, or re-validate the generated result.
`packages/protocol/src/validation/ws-outbound.ts` is the shipped boundary. It validates the envelope with a generated validator that checks only each session message's `type` tag, then runs the generated validator for that one message type and returns the validated data. Issue paths from the message validator, including nested union branches, are prefixed with `message`, so callers see the same issues as when one validator covered the whole envelope. It does not normalize or repair the generated result. When the only failures are unknown variants inside lists, the boundary removes those elements and validates once more ([protocol-compatibility](protocol-compatibility.md#the-protocol-contract-always-compatible)). The reader classifies failures from the issue list, so it behaves the same over the generated validator and Zod, and a valid message pays nothing extra.
Keep one generated function per message type. zod-aot inlines every nested schema into the function it compiles, so compiling `WSOutboundMessageSchema` as a whole produced one 11 MB function. On V8 (daemon clients, plugin hosts, the CLI, and Electron), the Maglev tier compiled that function once it was hot, allocating about 800 MB and stalling for seconds, and compiled it again after each deoptimization. Hermes has no JIT, so mobile never showed it. `packages/protocol/tests/validation/ws-outbound.test.ts` fails if a generated function grows past 1 MB.
+4 -3
View File
@@ -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
View File
@@ -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
View File
@@ -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
+11
View File
@@ -73,6 +73,17 @@
"entry": ["src/index.ts", "src/**/*.test.ts"],
"project": ["src/**/*.ts"]
},
"packages/workflows": {
"entry": [
"src/index.ts",
"src/ir.ts",
"src/dsl.ts",
"src/yaml.ts",
"src/testing.ts",
"test/**/*.test.ts"
],
"project": ["src/**/*.ts", "test/**/*.ts"]
},
"packages/expo-two-way-audio": {
"entry": ["src/index.ts"],
"project": ["src/**/*.ts"]
+1 -1
View File
@@ -1 +1 @@
sha256-aal9eR571blWuL7CZt1LR+KfA4QPJ0ivVl/GSTWy93o=
sha256-34bUBmRmjekbUSp93597GLTmSWKt23TCHaK3ViXG+iU=
+20 -3
View File
@@ -16,6 +16,7 @@
"packages/highlight",
"packages/plugin",
"packages/protocol",
"packages/workflows",
"packages/client",
"packages/server",
"packages/app",
@@ -6709,6 +6710,10 @@
"resolved": "packages/website",
"link": true
},
"node_modules/@getpaseo/workflows": {
"resolved": "packages/workflows",
"link": true
},
"node_modules/@gorhom/bottom-sheet": {
"version": "5.2.14",
"resolved": "https://registry.npmjs.org/@gorhom/bottom-sheet/-/bottom-sheet-5.2.14.tgz",
@@ -14924,7 +14929,6 @@
"version": "8.11.0",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.11.0.tgz",
"integrity": "sha512-wGgprdCvMalC0BztXvitD2hC04YffAvtsUn93JbGXYLAtCUO4xd17mCCZQxUOItiBwZvJScWo8NIvQMQ71rdpg==",
"dev": true,
"license": "MIT",
"dependencies": {
"fast-deep-equal": "^3.1.1",
@@ -31398,7 +31402,6 @@
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
"integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6"
@@ -36228,7 +36231,6 @@
"version": "4.4.1",
"resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz",
"integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==",
"dev": true,
"license": "BSD-2-Clause",
"dependencies": {
"punycode": "^2.1.0"
@@ -43159,6 +43161,21 @@
}
}
},
"packages/workflows": {
"name": "@getpaseo/workflows",
"version": "0.1.0",
"license": "Apache-2.0",
"dependencies": {
"ajv": "^8.11.0",
"js-yaml": "^4.1.1",
"zod": "^4.4.3"
},
"devDependencies": {
"@types/node": "^20.9.0",
"typescript": "^5.9.3",
"vitest": "^4.1.6"
}
},
"plugins": {
"name": "@getpaseo/builtin-plugins",
"version": "0.18.1",
+3
View File
@@ -27,6 +27,7 @@
"packages/highlight",
"packages/plugin",
"packages/protocol",
"packages/workflows",
"packages/client",
"packages/server",
"packages/app",
@@ -60,6 +61,8 @@
"build:relay:clean": "npm run build:clean --workspace=@getpaseo/relay",
"build:protocol": "npm run build --workspace=@getpaseo/protocol",
"build:protocol:clean": "npm run build:clean --workspace=@getpaseo/protocol",
"build:workflows": "npm run build --workspace=@getpaseo/workflows",
"build:workflows:clean": "npm run build:clean --workspace=@getpaseo/workflows",
"build:client": "npm run build --workspace=@getpaseo/client",
"build:client:clean": "npm run build:protocol:clean && npm run build:clean --workspace=@getpaseo/client",
"build:server-deps": "npm run build:client && concurrently --kill-others-on-fail --names highlight,plugin,relay --prefix-colors yellow,green,blue \"npm run build:highlight\" \"npm run build:plugin\" \"npm run build:relay\"",
@@ -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,16 @@ 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 single-provider picker lists Profiles above the agent's models without a rail", 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-picker-rail")).toHaveCount(0);
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 +113,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();
@@ -0,0 +1,13 @@
import {
expectBuiltinPluginSettings,
openBuiltinPluginSettings,
test,
} from "../support/helpers/builtin-plugin-settings";
test("a built-in plugin's settings link opens its screen", async ({
page,
builtinSettingsHost,
}) => {
await openBuiltinPluginSettings(page, builtinSettingsHost);
await expectBuiltinPluginSettings(page);
});
+25 -1
View File
@@ -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,63 @@ 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;
});
}
// `borderAccent` at rest, `surface4` while focused: greys in both themes, never the accent.
const FRAME_BORDERS = {
dark: { rest: "rgb(47, 53, 52)", focus: "rgb(89, 91, 91)" },
light: { rest: "rgb(236, 236, 241)", focus: "rgb(212, 212, 216)" },
} as const;
for (const colorScheme of ["dark", "light"] as const) {
test(`the composer frame takes a neutral border on focus in the ${colorScheme} theme`, async ({
page,
}) => {
const agent = await seedMockAgentWorkspace({
repoPrefix: "composer-frame-focus-",
title: "Composer frame focus",
});
const borders = FRAME_BORDERS[colorScheme];
try {
await page.emulateMedia({ colorScheme });
await openAgentRoute(page, agent);
const composer = composerLocator(page);
await expectComposerVisible(page);
await page.mouse.move(0, 0);
await blurComposerInput(page);
expect(await readSettledFrameBorder(page)).toBe(borders.rest);
await composer.click();
await page.mouse.move(0, 0);
await expectComposerFocused(page);
expect(await readSettledFrameBorder(page)).toBe(borders.focus);
await blurComposerInput(page);
expect(await readSettledFrameBorder(page)).toBe(borders.rest);
// Hover alone leaves the frame at rest, so the border only ever means focus.
await composer.hover();
expect(await readSettledFrameBorder(page)).toBe(borders.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) {
@@ -753,6 +753,10 @@ test.describe("CodeMirror workspace file editing", () => {
const imagePath = path.join(workspace.repoPath, "pixel.png");
await writeFile(markdownPath, "# First heading\n", "utf8");
await writeFile(imagePath, RED_PIXEL);
await writeFile(
path.join(workspace.repoPath, "shape.svg"),
await readFile(path.resolve(__dirname, "../mobile/fixtures/native-preview.svg")),
);
await workspace.navigateTo();
await openWorkspaceFile(page, "notes.md");
@@ -800,6 +804,11 @@ test.describe("CodeMirror workspace file editing", () => {
const initialSource = await image.getAttribute("src");
await writeFile(imagePath, BLUE_PIXEL);
await expect.poll(() => image.getAttribute("src")).not.toBe(initialSource);
await openWorkspaceFile(page, "shape.svg");
await expect(imageCanvas).toBeVisible();
await expect(image).toBeVisible();
await expect(image).toHaveJSProperty("naturalWidth", 240);
});
test("renders local relative images inside Markdown preview", async ({ page, withWorkspace }) => {
@@ -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,9 +21,16 @@ 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 { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import { seedWorkspace } from "../support/helpers/seed-client";
import { waitForSettledPosition } from "../support/helpers/sheet-layout";
const MOCK_PROVIDER_LABEL = "Mock Load Test";
@@ -56,9 +65,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 +106,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 +115,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 +146,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 +197,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 +212,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 +222,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 +268,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 +287,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 +295,78 @@ 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 surfaces collapsed Profiles above Model on Home and keeps provider headers stable on collapse", async () => {
await page.setViewportSize({ width: 390, height: 800 });
await page.getByTestId("combined-model-selector").filter({ visible: true }).first().click();
const profilesToggle = page.getByTestId("agent-controls-profiles");
const modelRowButton = page.getByTestId("agent-controls-model");
await expect(profilesToggle).toBeVisible();
await expect(page.getByTestId("agent-controls-profiles-list")).toHaveCount(0);
await waitForSettledPosition(profilesToggle);
const profilesBox = await profilesToggle.boundingBox();
const modelBox = await modelRowButton.boundingBox();
expect(profilesBox && modelBox && profilesBox.y < modelBox.y).toBe(true);
// Open Model: Profiles is extracted onto Home, and provider headers keep exact geometry when collapsed.
await modelRowButton.click();
await expect(page.getByTestId("compact-model-list")).toBeVisible();
await expect(page.getByTestId("model-picker-rail-profiles")).toHaveCount(0);
const expandedHeader = page.locator('[data-testid^="model-provider-section-"]').first();
const expandedBox = await expandedHeader.boundingBox();
const expandedProviderId = (await expandedHeader.getAttribute("data-testid"))?.replace(
"model-provider-section-",
"",
);
await expandedHeader.click();
await expect(page.getByTestId("compact-model-list")).toHaveCount(0);
const collapsedHeader = page.getByTestId(`model-provider-${expandedProviderId}`);
const collapsedBox = await collapsedHeader.boundingBox();
expect(expandedBox && collapsedBox).toBeTruthy();
expect(Math.abs(expandedBox!.y - collapsedBox!.y)).toBeLessThanOrEqual(1);
expect(Math.abs(expandedBox!.height - collapsedBox!.height)).toBeLessThanOrEqual(1);
// Search dock matches the collapsed provider card's outer rails, height, and text rail.
const searchContainer = page.getByTestId("model-search-all-input-container");
const searchInput = page.getByTestId("model-search-all-input");
const searchBox = await searchContainer.boundingBox();
const searchInputBox = await searchInput.boundingBox();
const collapsedCardBox = await readCollapsedCardGeometry(collapsedHeader);
expect(searchBox && searchInputBox && collapsedCardBox).toBeTruthy();
expect(Math.abs(searchBox!.x - collapsedCardBox!.cardX)).toBeLessThanOrEqual(1);
expect(Math.abs(searchBox!.width - collapsedCardBox!.cardWidth)).toBeLessThanOrEqual(1);
expect(Math.abs(searchBox!.height - collapsedCardBox!.cardHeight)).toBeLessThanOrEqual(1);
expect(Math.abs(searchInputBox!.x - collapsedCardBox!.labelX)).toBeLessThanOrEqual(2);
// Return Home, expand Profiles in place, and apply the profile.
await page.getByTestId("sheet-header-back").click();
await profilesToggle.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,8 +374,230 @@ 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();
}
});
test("reopening a deep selected model lands at its scroll offset on the first paint on desktop and mobile", async ({
page,
}) => {
const provider = await seedModelProvider(LARGE_CATALOG);
const workspace = await seedWorkspace({ repoPrefix: "model-picker-initial-scroll-" });
try {
await gotoWorkspace(page, workspace.workspaceId);
await clickNewChat(page);
await expectComposerVisible(page);
// Select a model deep in the 200-item catalog.
await openModelPicker(page);
await searchAllModels(page, "bulk model 80");
await page
.getByTestId("combobox-desktop-container")
.getByTestId(`model-row-${LARGE_CATALOG.id}-bulk-80`)
.click();
await expect(page.getByTestId("combobox-desktop-container")).toHaveCount(0);
await test.step("desktop opens directly at the selected row without flashing scrollTop 0", async () => {
await startScrollSampling(page, "model-picker-model-list");
await page.getByTestId("combined-model-selector").filter({ visible: true }).first().click();
const samples = await readScrollSamples(page, "model-picker-model-list");
expect(samples[0]).toBeGreaterThan(0);
await expect(
page
.getByTestId("combobox-desktop-container")
.getByTestId(`model-row-${LARGE_CATALOG.id}-bulk-80`),
).toBeInViewport();
await closeModelPicker(page);
});
await test.step("mobile opens directly at the selected row without flashing scrollTop 0", 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-model")).toBeVisible();
await startScrollSampling(page, "compact-model-list");
await page.getByTestId("agent-controls-model").click();
const samples = await readScrollSamples(page, "compact-model-list");
expect(samples[0]).toBeGreaterThan(0);
const listBox = await page.getByTestId("compact-model-list").boundingBox();
const rowBox = await page
.getByTestId(`model-row-${LARGE_CATALOG.id}-bulk-80`)
.boundingBox();
expect(listBox && rowBox).toBeTruthy();
expect(rowBox!.y).toBeGreaterThanOrEqual(listBox!.y - 1);
expect(rowBox!.y + rowBox!.height).toBeLessThanOrEqual(listBox!.y + listBox!.height + 1);
});
} finally {
await workspace.cleanup();
await provider.restore();
}
});
test("compact single-provider picker keeps its header fixed and scrolls to the last model row", async ({
page,
}) => {
const extraModels = Array.from({ length: 24 }, (_, index) => ({
id: `extra-scroll-${String(index).padStart(2, "0")}`,
label: `Extra scroll model ${String(index).padStart(2, "0")}`,
description: `Extra row ${index}`,
}));
const client = await connectDaemonClient<DaemonClient>({
clientIdPrefix: "single-provider-scroll",
});
const workspace = await seedMockAgentWorkspace({
repoPrefix: "single-provider-scroll-",
title: "Single provider scroll",
model: "ten-second-stream",
modeId: "load-test",
});
try {
await client.patchDaemonConfig({
providers: {
mock: {
additionalModels: extraModels,
},
},
});
await page.setViewportSize({ width: 390, height: 800 });
await openAgentRoute(page, workspace);
await expectComposerVisible(page);
await page.getByTestId("combined-model-selector").filter({ visible: true }).first().click();
await expect(page.getByTestId("agent-controls-model")).toBeVisible();
await page.getByTestId("agent-controls-model").click();
const list = page.getByTestId("compact-model-list");
await expect(list).toBeVisible();
const header = page.getByTestId("model-provider-section-mock");
await expect(header).toBeVisible();
const headerBox = await header.boundingBox();
expect(headerBox).toBeTruthy();
expect(headerBox!.height).toBeGreaterThanOrEqual(16);
// Scroll to the bottom of the lone provider's list and confirm the final row is fully in view.
await list.evaluate((node) => {
node.scrollTop = node.scrollHeight;
});
const lastRow = page.getByTestId("model-row-mock-extra-scroll-23");
await expect(lastRow).toBeVisible();
const listBox = await list.boundingBox();
const lastRowBox = await lastRow.boundingBox();
expect(listBox && lastRowBox).toBeTruthy();
expect(lastRowBox!.y + lastRowBox!.height).toBeLessThanOrEqual(
listBox!.y + listBox!.height + 1,
);
await lastRow.click();
await expect(page.getByTestId("agent-controls-model")).toContainText("Extra scroll model 23");
} finally {
await client
.patchDaemonConfig({
providers: {
mock: {
additionalModels: [],
},
},
})
.catch(() => undefined);
await client.close().catch(() => undefined);
await workspace.cleanup();
}
});
});
async function readCollapsedCardGeometry(collapsedHeader: ReturnType<Page["getByTestId"]>) {
return collapsedHeader.evaluate((node) => {
// Walk up from the press overlay to the SettingsCard container (2px taller for borders).
const header = node.parentElement;
const card = header?.parentElement?.parentElement;
const rect = card?.getBoundingClientRect();
const label = header?.querySelector('[dir="auto"]');
const labelRect = label?.getBoundingClientRect();
return rect && labelRect
? {
cardX: rect.x,
cardWidth: rect.width,
cardHeight: rect.height,
labelX: labelRect.x,
}
: null;
});
}
async function startScrollSampling(page: Page, listTestId: string): Promise<void> {
await page.evaluate((testId) => {
const samples: number[] = [];
const win = window as unknown as {
__scrollSamples?: number[];
__scrollObserver?: MutationObserver;
};
win.__scrollObserver?.disconnect();
win.__scrollSamples = samples;
const capture = (el: Element) => {
samples.push(el.scrollTop);
let remaining = 4;
const tick = () => {
const current = document.querySelector(`[data-testid="${testId}"]`);
if (current) samples.push(current.scrollTop);
remaining -= 1;
if (remaining > 0) requestAnimationFrame(tick);
};
requestAnimationFrame(tick);
};
const observer = new MutationObserver(() => {
const el = document.querySelector(`[data-testid="${testId}"]`);
if (!el) return;
observer.disconnect();
capture(el);
});
win.__scrollObserver = observer;
observer.observe(document.body, { childList: true, subtree: true });
}, listTestId);
}
async function readScrollSamples(page: Page, listTestId: string): Promise<number[]> {
await expect(page.getByTestId(listTestId)).toBeVisible({ timeout: 10_000 });
const readSamples = () =>
page.evaluate(
() => (window as unknown as { __scrollSamples?: number[] }).__scrollSamples ?? [],
);
await expect.poll(async () => (await readSamples()).length).toBeGreaterThanOrEqual(2);
return readSamples();
}
async function setRuntimeCatalog(client: DaemonClient, count: number, cwd: string) {
await client.patchDaemonConfig({
providers: {
@@ -332,7 +635,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 }),
@@ -15,6 +15,9 @@ import {
expectBothConsecutiveTools,
trackPluginChatRecovery,
reconnectPluginChat,
withRepeatedOutputTimeline,
readOldestPluginReplacement,
expectOldestPluginReplacementReadable,
} from "../support/helpers/plugin-timeline";
for (const width of [1100, 390]) {
@@ -82,3 +85,15 @@ test("plugin-transformed assistant reply keeps copy, fork, and turn duration in
expect(await forkAttachment.waitForText()).toContain(ASSISTANT_TEXT);
});
});
test("keeps older plugin replacements readable when source messages reuse local output IDs", async ({
page,
}, info) => {
await withRepeatedOutputTimeline(page, info, async () => {
await readOldestPluginReplacement(page);
await expectOldestPluginReplacementReadable(page);
await page.reload({ waitUntil: "domcontentloaded" });
await readOldestPluginReplacement(page);
await expectOldestPluginReplacementReadable(page);
});
});
@@ -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();
@@ -118,10 +118,14 @@ test("projects and pinned chats reorder while ordinary workspaces stay newest fi
await firstProject.client.setWorkspacePinned(firstProject.workspaceId, true);
await secondProject.client.setWorkspacePinned(secondProject.workspaceId, true);
const secondProjectWorkspaceTestId = `sidebar-workspace-row-${getServerId()}:${secondProject.workspaceId}`;
// Both rows also exist in their project groups, so match them only once each pin has
// moved its row into the Pinned section.
await quickDragFirstRowAfterSecond(
page.locator(
`[data-testid="${firstWorkspaceTestId}"], [data-testid="${secondProjectWorkspaceTestId}"]`,
),
page
.getByTestId("sidebar-pinned-section")
.locator(
`[data-testid="${firstWorkspaceTestId}"], [data-testid="${secondProjectWorkspaceTestId}"]`,
),
pressWorkspaceRow,
);
} finally {
@@ -392,6 +392,8 @@ test.describe("Terminal protocol queries", () => {
await terminalSurface(page).click();
await terminalSurface(page).pressSequentially("Q", { delay: 0 });
await expectTerminalOutput(lightTerminalId, "WATCH2031_DONE");
// One report per switch: a second responder would deliver each switch twice.
expect(watch2031Events(await terminalOutput(lightTerminalId))).toEqual(["1", "2"]);
await selectAppThemeInApp(page, "Dark");
await runPaletteChecks(lightTerminalId, TERMINAL_PALETTE_SCENARIOS.dark, {
@@ -428,6 +430,10 @@ test.describe("Terminal protocol queries", () => {
return capture.lines.join("").replace(/\s/g, "");
}
function watch2031Events(output: string): string[] {
return [...output.matchAll(/WATCH2031_EVENT:([12])/g)].map(([, scheme]) => scheme);
}
async function expectTerminalOutput(terminalId: string, text: string): Promise<void> {
await expect.poll(() => terminalOutput(terminalId), { timeout: 10_000 }).toContain(text);
}
@@ -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(() =>
@@ -0,0 +1,34 @@
import { BuiltinPluginLoader } from "../../../../server/src/server/plugins/builtin/index.js";
import { createTestPaseoDaemon } from "../../../../server/src/server/test-utils/paseo-daemon.js";
import { DaemonClient } from "../../../../server/src/server/test-utils/daemon-client.js";
import assert from "node:assert/strict";
import pino from "pino";
const [, , root, origin, paseoHomeRoot, daemonVersion] = process.argv;
const daemon = await createTestPaseoDaemon({
corsAllowedOrigins: [origin!],
paseoHomeRoot,
daemonVersion,
logger: pino({ level: "error" }),
builtinPlugins: new BuiltinPluginLoader(root, ["builtin-settings"]),
});
const client = new DaemonClient({
appVersion: daemonVersion,
url: `ws://127.0.0.1:${daemon.port}/ws`,
});
try {
await client.connect();
const plugin = (await client.getPluginCatalog()).find(({ id }) => id === "builtin-settings");
assert.ok(plugin?.clientBundle, JSON.stringify(await client.getPluginLogs("builtin-settings")));
assert.deepEqual(await client.listPlugins(), []);
process.send!({ serverId: client.getLastServerInfoMessage()!.serverId, port: daemon.port });
await new Promise<void>((resolve) => {
process.once("disconnect", resolve);
process.once("SIGTERM", resolve);
});
} finally {
await client.close();
await daemon.close();
}
@@ -0,0 +1,24 @@
# Native SVG preview regression
Copy `../fixtures/native-preview.svg`, `../fixtures/native-preview-viewbox.svg`, and
`../../../assets/images/icon.png` into a workspace on a test daemon. In the Android
or iOS app, connect to that daemon, open the workspace's Files tab, and tap
`native-preview.svg`. The SVG should show a yellow circle on a green rectangle.
With that preview open, run:
```sh
agent-device test packages/app/e2e/mobile/agent-device/native-svg-preview.android.ad \
--metro-port <port> --artifacts-dir .artifacts/svg-preview
```
Run it again with `native-preview-viewbox.svg` open to cover SVG dimensions
inferred from `viewBox`, then with the PNG open to check raster images. Close and
reopen the SVG and rerun to cover cached file previews. Use English app language
for the zoom button selectors. The scripts are discovered by `npm run test:e2e:mobile`; the iOS counterpart is
`native-svg-preview.ios.ad`. They reopen the installed app with its current
preview and leave the daemon connection unchanged.
Before the fix the SVG remains blank and the canvas wait fails. The PNG passes.
The replay checks successful native dimension decoding and zoom/reset controls;
visually verify the circle and rectangle as well.
@@ -0,0 +1,11 @@
context platform=android timeout=60000 retries=0
env APP_ID=sh.paseo.debug
open "${APP_ID}"
wait "id=\"image-file-preview-canvas\"" 10000
wait "role=button label=\"Zoom in\"" 10000
press "role=button label=\"Zoom in\""
wait "role=button label=\"Reset view\" enabled=true" 10000
press "role=button label=\"Reset view\""
wait "role=button label=\"Reset view\" enabled=false" 10000
close
@@ -0,0 +1,11 @@
context platform=ios timeout=60000 retries=0
env APP_ID=sh.paseo.debug
open "${APP_ID}"
wait "id=\"image-file-preview-canvas\"" 10000
wait "role=button label=\"Zoom in\"" 10000
press "role=button label=\"Zoom in\""
wait "role=button label=\"Reset view\" enabled=true" 10000
press "role=button label=\"Reset view\""
wait "role=button label=\"Reset view\" enabled=false" 10000
close
@@ -317,6 +317,80 @@ async function runBoundedPreview() {
await runCase("preview", "files", fileCase);
}
// A finger drifts a few points during a tap, so tap the composer's controls with a
// short drag while the keyboard is open. The model picker must open, and on a wide
// layout its popover must end above the keyboard.
function dragTap(rect) {
ad(
"gesture",
"pan",
String(Math.round(rect.x + rect.width / 2)),
String(Math.round(rect.y + rect.height / 2)),
"0",
"3",
"120",
);
}
// Waits until the keyboard is shown and the node with `id` stops moving.
async function settledWithKeyboard(name, id) {
let previousTop;
return waitFor(name, (snap) => {
const node = nodeById(snap, id);
if (!node || !keyboardShown(snap)) return false;
const stable = node.rect.y === previousTop;
previousTop = node.rect.y;
return stable;
});
}
const keyboardTop = (snap) =>
snap.data.nodes.find((node) => node.type === "Keyboard" && node.rect).rect.y;
async function runControlTaps() {
await clearInput("controls");
const attach = nodeById(
await settledWithKeyboard("controls-attach-before", "message-input-root"),
"message-input-attach-button",
);
dragTap(attach.rect);
// Wide layouts show the attachment menu as a popover and phones as a sheet; both list the items.
await waitFor("controls-attach-menu", (snap) =>
Boolean(nodeById(snap, "message-input-attachment-menu-item-file")),
);
process.stdout.write("PASS drag tap on attach opened the attachment menu\n");
// The open menu hides the composer from accessibility. Its backdrop covers the top-left corner.
ad("press", "20", "120");
await waitFor("controls-attach-closed", (snap) => Boolean(nodeById(snap, "message-input-root")));
await clearInput("controls-model");
const trigger = nodeById(
await settledWithKeyboard("controls-model-before", "message-input-root"),
"combined-model-selector",
);
dragTap(trigger.rect);
const sheetOpen = (snap) =>
snap.data.nodes.some((node) => node.type === "Button" && node.label === "Close");
const opened = await waitFor(
"controls-model-picker",
(snap) => Boolean(nodeById(snap, "combobox-desktop-container")) || sheetOpen(snap),
);
process.stdout.write("PASS drag tap on the model selector opened the picker\n");
if (!nodeById(opened, "combobox-desktop-container")) return;
const settled = await settledWithKeyboard("controls-model-popover", "combobox-desktop-container");
const frame = nodeById(settled, "combobox-desktop-container").rect;
const bottom = frame.y + frame.height;
const covered = frame.y < trigger.rect.y + trigger.rect.height && bottom > trigger.rect.y;
if (covered || bottom > keyboardTop(settled) + 1) {
throw new Error(
`Model popover spans ${Math.round(frame.y)}-${Math.round(bottom)}; it must clear the trigger at ${Math.round(trigger.rect.y)} and the keyboard at ${Math.round(keyboardTop(settled))}`,
);
}
process.stdout.write(
`PASS model popover ${Math.round(frame.y)}-${Math.round(bottom)} clears the trigger and the keyboard\n`,
);
}
if (scenario !== "all") {
ad(
"open",
@@ -328,6 +402,7 @@ if (scenario !== "all") {
await waitFor("draft", (snap) => Boolean(nodeById(snap, "message-input-root")), 60_000);
if (scenario === "growth") await runLiveGrowth();
else if (scenario === "previews") await runBoundedPreview();
else if (scenario === "controls") await runControlTaps();
else throw new Error(`Unknown scenario: ${scenario}`);
process.stdout.write(`Composer ${scenario} regression passed. Artifacts: ${artifactsDir}\n`);
process.exit(0);
@@ -0,0 +1,60 @@
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { setTimeout } from "node:timers/promises";
// Opening a file from the filtered Files tree must close the software keyboard.
//
// Before running, on a phone-sized device with a software keyboard enabled, open
// Explorer -> Files in a workspace where the first match for the query is a file.
// The app must already run the checkout being verified against a real daemon.
const serial = process.env.ANDROID_SERIAL ?? "emulator-5554";
const query = process.env.PASEO_FILES_FILTER_QUERY ?? "README";
function adb(...args) {
return execFileSync("adb", ["-s", serial, ...args], { encoding: "utf8", timeout: 60_000 });
}
function findNode(id) {
adb("shell", "uiautomator", "dump", "/sdcard/files-filter-keyboard.xml");
const tree = adb("exec-out", "cat", "/sdcard/files-filter-keyboard.xml");
const node = tree.match(new RegExp(`<node [^>]*resource-id="${id}"[^>]*>`))?.[0];
const bounds = node?.match(/bounds="\[(\d+),(\d+)\]\[(\d+),(\d+)\]"/);
if (!bounds) return null;
const [left, top, right, bottom] = bounds.slice(1).map(Number);
return { x: Math.round((left + right) / 2), y: Math.round((top + bottom) / 2) };
}
async function waitForNode(id) {
const deadline = Date.now() + 30_000;
while (Date.now() < deadline) {
const node = findNode(id);
if (node) return node;
await setTimeout(250);
}
throw new Error(`Timed out waiting for ${id}`);
}
function tap({ x, y }) {
adb("shell", "input", "tap", String(x), String(y));
}
async function waitForKeyboard(shown) {
let stable = 0;
const deadline = Date.now() + 10_000;
while (Date.now() < deadline) {
const state = adb("shell", "dumpsys", "input_method");
stable = /^ {2}mInputShown=true$/m.test(state) === shown ? stable + 1 : 0;
if (stable === 3) return;
await setTimeout(200);
}
assert.fail(`Keyboard did not settle at shown=${shown}`);
}
const clear = findNode("files-filter-clear");
if (clear) tap(clear);
tap(await waitForNode("files-filter-input"));
await waitForKeyboard(true);
adb("shell", "input", "text", query);
const match = await waitForNode("file-filter-row-0");
await waitForKeyboard(true); // Typing and new results leave the keyboard up.
tap(match);
await waitForNode("sheet-tab-body");
await waitForKeyboard(false);
console.log("PASS: opening a filtered file closes the keyboard");
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 240 160"><rect width="240" height="160" fill="#08a040"/><circle cx="120" cy="80" r="50" fill="#ffcc00"/></svg>

After

Width:  |  Height:  |  Size: 164 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="240" height="160" viewBox="0 0 240 160"><rect width="240" height="160" fill="#08a040"/><circle cx="120" cy="80" r="50" fill="#ffcc00"/></svg>

After

Width:  |  Height:  |  Size: 188 B

@@ -18,6 +18,9 @@ press "id=\"combined-model-selector\""
wait "id=\"model-provider-${PROVIDER_ID}\"" 10000
press "id=\"model-provider-${PROVIDER_ID}\""
wait "id=\"model-row-${PROVIDER_ID}-${MODEL_ID}\"" 3000
# Back takes the header's step to the provider list first, then dismisses the modal.
back
wait "id=\"model-provider-${PROVIDER_ID}\"" 3000
back
wait "id=\"combined-model-selector\" label=\"Select model (${MODEL_LABEL})\"" 3000
close
@@ -10,13 +10,13 @@ wait "id=\"agent-controls-model\"" 10000
gesture pan 540 790 0 960 500
wait "id=\"combined-model-selector\"" 3000
# Reopen, dismiss the nested model browser, then dismiss its restored parent.
# Android Back steps from Model back to Agent settings, then closes the sheet.
press "id=\"combined-model-selector\""
wait "id=\"agent-controls-model\"" 10000
press "id=\"agent-controls-model\""
wait stable 300 5000
gesture pan 540 790 0 960 500
wait "id=\"model-search-all-input\"" 10000
back
wait "id=\"agent-controls-model\"" 3000
gesture pan 540 790 0 960 500
back
wait "id=\"combined-model-selector\"" 3000
close
@@ -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,44 @@ 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)));
/** Multi-provider desktop keeps profiles behind the rail; single-pane lists them inline. */
export async function openPickerProfiles(page: Page): Promise<void> {
const rail = pickerViewport(page).getByTestId("model-picker-rail-profiles");
if (await rail.isVisible().catch(() => false)) {
await rail.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("");
await expect(edit.locator("svg")).toBeVisible();
}
/** 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 +688,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 +769,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 +793,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 +804,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 +834,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 });
+6 -4
View File
@@ -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 });
@@ -0,0 +1,77 @@
import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
import { once } from "node:events";
import { spawnTsx, killProcessTree } from "./spawn-node";
import appPackage from "../../../package.json";
import { expect, test as base, type Page } from "../fixtures";
import { gotoAppShell } from "./app";
import { addConnectedHostAndReload } from "./hosts";
import { pluginRequirements } from "./plugin-fixture";
const pluginId = "builtin-settings";
const screenId = "general";
const settingsText = "Built-in settings body";
export const test = base.extend<{ builtinSettingsHost: { serverId: string; port: number } }>({
builtinSettingsHost: async ({ baseURL }, provide, testInfo) => {
const root = testInfo.outputPath("builtin-plugins");
const directory = path.join(root, pluginId);
await mkdir(directory, { recursive: true });
await writeFile(
path.join(directory, "paseo-plugin.json"),
JSON.stringify({ id: pluginId, requirements: pluginRequirements }),
);
await writeFile(
path.join(directory, "index.client.tsx"),
`import React from "react";
import { Text } from "react-native";
export default function contribute(client) {
client.addSettingsScreen({
id: "${screenId}",
title: "General",
icon: "SlidersHorizontal",
Component: () => <Text>${settingsText}</Text>,
});
return () => {};
}`,
);
await writeFile(
path.join(directory, "index.server.ts"),
"export default function contribute() { return () => {}; }",
);
const daemon = spawnTsx(
path.resolve(__dirname, "../../fixtures/builtin-settings/daemon.mts"),
[root, new URL(baseURL!).origin, testInfo.outputPath("daemon"), appPackage.version],
{ stdio: ["ignore", "inherit", "inherit", "ipc"] },
);
try {
const [host] = await Promise.race([
once(daemon, "message") as Promise<[{ serverId: string; port: number }]>,
once(daemon, "exit").then(([code]) => {
throw new Error(`Built-in settings daemon exited with code ${code}`);
}),
]);
await provide(host);
} finally {
await killProcessTree(daemon);
}
},
});
export async function openBuiltinPluginSettings(
page: Page,
host: { serverId: string; port: number },
) {
await gotoAppShell(page);
await addConnectedHostAndReload(page, {
...host,
label: "Built-in settings host",
destination: `/settings/hosts/${host.serverId}/plugins/${pluginId}/${screenId}`,
});
}
export async function expectBuiltinPluginSettings(page: Page) {
await expect(page.getByText(settingsText, { exact: true })).toBeVisible();
await expect(page.getByRole("switch", { name: /: Disable$/ })).toHaveCount(0);
}
+14 -4
View File
@@ -76,15 +76,24 @@ export async function addOfflineHostsAndReload(
export async function addConnectedHostAndReload(
page: Page,
input: { serverId: string; label: string; port: number; primaryLabel?: string },
input: {
serverId: string;
label: string;
port: number;
primaryLabel?: string;
destination?: string;
},
): Promise<void> {
await addConnectedHostsAndReload(page, [input], { primaryLabel: input.primaryLabel });
await addConnectedHostsAndReload(page, [input], {
primaryLabel: input.primaryLabel,
destination: input.destination,
});
}
export async function addConnectedHostsAndReload(
page: Page,
inputs: Array<{ serverId: string; label: string; port: number }>,
options?: { primaryLabel?: string },
options?: { primaryLabel?: string; destination?: string },
): Promise<void> {
const connectedHosts = inputs.map((input) =>
buildSeededHost({
@@ -123,7 +132,8 @@ export async function addConnectedHostsAndReload(
},
);
await page.reload();
if (options?.destination) await page.goto(options.destination);
else await page.reload();
}
export async function waitForConnectedHost(
@@ -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();
}
@@ -7,6 +7,7 @@ import { connectNewWorkspaceDaemonClient } from "./new-workspace";
import { openAgentRoute, seedMockAgentWorkspace, type MockAgentWorkspace } from "./mock-agent";
import { installDaemonWebSocketGate } from "./daemon-websocket-gate";
import { expectReconnectingToastVisible } from "./workspace-ui";
import { userScrollsTimelineToHistoryStart } from "./timeline-pagination";
const PLUGIN_ID = "timeline-transform-e2e";
@@ -373,3 +374,81 @@ export async function viewInlineThinkingExample(page: Page, info: TestInfo): Pro
await example.cleanup();
}
}
/** Reuse plugin-local IDs across distinct source messages in a real virtualized chat. */
export async function withRepeatedOutputTimeline(
page: Page,
info: TestInfo,
run: () => Promise<void>,
): Promise<void> {
info.setTimeout(120_000);
const agent = await seedMockAgentWorkspace({
repoPrefix: "timeline-local-ids-",
title: "Repeated plugin output IDs",
});
try {
for (const label of ["First", "Second", "Third"]) {
await agent.client.sendAgentMessage(
agent.agentId,
`${label}: emit 1 coalesced agent stream updates`,
);
await agent.client.waitForFinish(agent.agentId, 15_000);
}
await withDirectoryPlugin({
pluginId: "timeline-local-ids",
source: `import React from "react";
import { Text, View } from "react-native";
import { z } from "zod";
function Row({ item }) {
return <View style={{ height: item.data.tall ? 120 : 24 }}>
<Text>{item.data.label}</Text>
</View>;
}
export default function contribute(client) {
client.addTimelineTransformer({
id: "local-ids", query: { itemType: "user_message" },
transform({ item }) {
const label = item.text.split(":")[0];
return { items: Array.from({ length: 60 }, (_, index) => ({
type: "plugin", id: "part-" + index, kind: "reply", version: 1,
data: { label: label + " replacement " + index, tall: label === "Second" },
})) };
},
});
client.addTimelineRenderer({
kind: "reply", version: 1,
schema: z.object({ label: z.string(), tall: z.boolean() }), Component: Row,
});
return () => {};
}`,
run: async () => {
await openAgentRoute(page, agent);
await expect(page.getByRole("textbox", { name: "Message agent..." }).first()).toBeVisible();
await run();
},
});
} finally {
await agent.cleanup();
}
}
export async function readOldestPluginReplacement(page: Page): Promise<void> {
await expect(page.getByText("Third replacement 59", { exact: true }).first()).toBeAttached();
await expect
.poll(async () => {
await userScrollsTimelineToHistoryStart(page);
return page.getByText("First replacement 0", { exact: true }).isVisible();
})
.toBe(true);
}
export async function expectOldestPluginReplacementReadable(page: Page): Promise<void> {
await expect(
page
.getByTestId("agent-chat-scroll")
.locator("[data-index]")
.getByText("First replacement 0", { exact: true }),
).toBeVisible();
await expect(page.getByRole("textbox", { name: "Message agent..." }).first()).toBeVisible();
await expect(page.getByText("Paseo ran into a problem.", { exact: true })).toHaveCount(0);
}
@@ -61,18 +61,24 @@ async function readRows(input: {
storeName: string;
}): Promise<ReplicaRowRecord[]> {
const database = await new Promise<IDBDatabase>((resolve, reject) => {
const request = indexedDB.open(input.databaseName, 1);
request.addEventListener("success", () => resolve(request.result));
request.addEventListener("error", () => reject(request.error));
});
return new Promise((resolve, reject) => {
const request = database
.transaction(input.storeName, "readonly")
.objectStore(input.storeName)
.getAll();
// The app owns the database version; open whatever version it created.
const request = indexedDB.open(input.databaseName);
request.addEventListener("success", () => resolve(request.result));
request.addEventListener("error", () => reject(request.error));
});
try {
return await new Promise((resolve, reject) => {
const request = database
.transaction(input.storeName, "readonly")
.objectStore(input.storeName)
.getAll();
request.addEventListener("success", () => resolve(request.result));
request.addEventListener("error", () => reject(request.error));
});
} finally {
// An open connection would block the app from upgrading the database.
database.close();
}
}
function assembleCache(rows: ReplicaRowRecord[]): ReplicaCacheRecord {
@@ -185,19 +191,27 @@ export async function writeReplicaCache(page: Page, value: ReplicaCacheRecord):
await page.evaluate(
async ({ databaseName, storeName, nextRows }) => {
const database = await new Promise<IDBDatabase>((resolve, reject) => {
const request = indexedDB.open(databaseName, 1);
const request = indexedDB.open(databaseName);
request.addEventListener("success", () => resolve(request.result));
request.addEventListener("error", () => reject(request.error));
});
await new Promise<void>((resolve, reject) => {
const transaction = database.transaction(storeName, "readwrite");
const store = transaction.objectStore(storeName);
store.clear();
for (const row of nextRows) store.put(row);
transaction.addEventListener("complete", () => resolve());
transaction.addEventListener("error", () => reject(transaction.error));
transaction.addEventListener("abort", () => reject(transaction.error));
});
try {
await new Promise<void>((resolve, reject) => {
const transaction = database.transaction(storeName, "readwrite");
const store = transaction.objectStore(storeName);
store.clear();
// The app budgets the cache on each row's recorded UTF-8 payload size.
const encoder = new TextEncoder();
for (const row of nextRows) {
store.put({ ...row, payloadBytes: encoder.encode(row.payload).length });
}
transaction.addEventListener("complete", () => resolve());
transaction.addEventListener("error", () => reject(transaction.error));
transaction.addEventListener("abort", () => reject(transaction.error));
});
} finally {
database.close();
}
},
{ databaseName: DATABASE_NAME, storeName: STORE_NAME, nextRows: rows },
);
+9 -10
View File
@@ -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);
},
@@ -1,11 +1,13 @@
package sh.paseo.terminal
import android.os.Build
import android.text.InputType
import android.view.KeyCharacterMap
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SdkSuppress
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
@@ -77,6 +79,15 @@ class TerminalInputConnectionTest {
}
}
/** Gboard commits each letter in its own batch edit when the editor disables suggestions. */
private fun TerminalInputConnection.typeLikeGboard(text: String) {
for (ch in text) {
beginBatchEdit()
commitText(ch.toString(), 1)
endBatchEdit()
}
}
@Test
fun editorInfoDisablesSuggestionsFullscreenAndPersonalizedLearning() {
instrumentation.runOnMainSync {
@@ -100,13 +111,8 @@ class TerminalInputConnectionTest {
@Test
fun batchedCommitTextAndSetComposingTextDoNotDoubleCharacters() {
withInputHarness { _, ic, _, terminal ->
for (ch in listOf("a", "b", "c", "d")) {
ic.beginBatchEdit()
ic.commitText(ch, 1)
ic.endBatchEdit()
}
ic.typeLikeGboard("abcd")
assertEquals("abcd", terminal.rawStream)
assertEquals("", ic.editable.toString())
// Coalesced setComposingText + finishComposingText inside one batch emits once.
ic.beginBatchEdit()
@@ -114,28 +120,96 @@ class TerminalInputConnectionTest {
ic.finishComposingText()
ic.endBatchEdit()
assertEquals("abcdef", terminal.rawStream)
assertEquals("", ic.editable.toString())
}
}
@Test
fun editorKeepsTheTypedLineUntilTerminalKeyBoundary() {
withInputHarness { _, ic, _, terminal ->
// IMEs address edits by offsets into the text they committed, so the editor must keep it.
ic.typeLikeGboard("ab")
assertEquals("ab", ic.getTextBeforeCursor(10, 0).toString())
// Enter leaves the shell line, so the editor starts the next line empty.
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER))
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER))
assertEquals("", ic.getTextBeforeCursor(10, 0).toString())
ic.typeLikeGboard("helo")
ic.beginBatchEdit()
ic.setComposingRegion(0, 4)
ic.commitText("hello ", 1)
ic.endBatchEdit()
assertEquals("ab\rhello ", terminal.applyToLine())
}
}
@Test
fun gboardArrowKeyStartsTheEditorOnAnEmptyLine() {
withInputHarness { _, ic, _, terminal ->
ic.typeLikeGboard("echo helo")
// Gboard's editing panel sends arrows as key events. The shell cursor moves, so the
// editor's copy of the line no longer matches where the next edit lands.
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_LEFT))
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_LEFT))
assertEquals("", ic.getTextBeforeCursor(10, 0).toString())
assertEquals(listOf("ArrowLeft"), terminal.keys.map { it.key })
assertEquals("echo helo", terminal.rawStream)
}
}
@Test
fun suggestionPickedThroughComposingRegionReplacesCommittedWord() {
withInputHarness { _, ic, _, terminal ->
// Gboard before Android 14 selects the committed word, then commits the suggestion.
ic.typeLikeGboard("helo")
ic.beginBatchEdit()
ic.setComposingRegion(3, 4)
ic.commitText("lo ", 1)
ic.endBatchEdit()
assertEquals("hello ", terminal.applyToLine())
}
}
@Test
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
fun gboardReplaceTextRewritesCommittedText() {
// Gboard on Android 14+ picks suggestions and applies double-space period with replaceText,
// addressing text it committed earlier. Offsets and texts below are the calls Gboard made live.
fun assertReplacement(typed: String, start: Int, end: Int, replacement: String, line: String) {
withInputHarness { _, ic, _, terminal ->
ic.typeLikeGboard(typed)
ic.beginBatchEdit()
ic.replaceText(start, end, replacement, 1, null)
ic.endBatchEdit()
assertEquals("$typed -> $replacement", line, terminal.applyToLine())
}
}
assertReplacement("helo", 3, 4, "lo ", line = "hello ")
assertReplacement("helo", 3, 4, "p ", line = "help ")
assertReplacement("echo hello", 5, 10, "jello ", line = "echo jello ")
assertReplacement("ab ", 2, 3, ". ", line = "ab. ")
}
@Test
fun backspaceWorksAcrossAllThreeImePaths() {
withInputHarness { _, ic, _, terminal ->
ic.commitText("abcd", 1)
assertEquals("abcd", terminal.applyToLine())
// Path 1: deleteSurroundingText (empty editable after commit)
// Path 1: deleteSurroundingText
ic.deleteSurroundingText(0, 0)
assertEquals("abcd", terminal.applyToLine())
ic.deleteSurroundingText(1, 0)
assertEquals("abc", terminal.applyToLine())
// Path 2: deleteSurroundingTextInCodePoints (empty editable)
// Path 2: deleteSurroundingTextInCodePoints
ic.deleteSurroundingTextInCodePoints(1, 0)
assertEquals("ab", terminal.applyToLine())
// Path 2b: deleteSurroundingTextInCodePoints on surrogate-pair emoji in composing buffer
ic.setComposingText("😀", 1)
// Path 2b: deleteSurroundingTextInCodePoints removes a surrogate-pair emoji as one code point
ic.commitText("😀", 1)
assertEquals("ab😀", terminal.applyToLine())
ic.deleteSurroundingTextInCodePoints(1, 0)
assertEquals("ab", terminal.applyToLine())
@@ -145,10 +219,16 @@ class TerminalInputConnectionTest {
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL))
assertEquals("a", terminal.applyToLine())
// Multi-char deleteSurroundingText on empty buffer
// Multi-char deleteSurroundingText
ic.commitText("xyz", 1)
ic.deleteSurroundingText(2, 0)
assertEquals("ax", terminal.applyToLine())
// After Enter the editor is empty, so Backspace still reaches text the shell already holds
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER))
ic.deleteSurroundingText(1, 0)
ic.deleteSurroundingTextInCodePoints(1, 0)
assertEquals("\r\u007f\u007f", terminal.rawStream.takeLast(3))
}
}
@@ -242,7 +322,7 @@ class TerminalInputConnectionTest {
ic.commitText("the", 1)
assertEquals("hellothe", terminal.applyToLine())
// Repeated clipboard paste of identical text works because editable clears after commit
// Repeated clipboard paste of identical text appends both copies
ic.commitText("echo ok", 1)
ic.commitText("echo ok", 1)
assertEquals("hellotheecho okecho ok", terminal.applyToLine())
@@ -22,9 +22,16 @@ internal data class TerminalKeyPayload(
/**
* Single authoritative IME + key stream for the Android native terminal.
*
* Keeps a private [SpannableStringBuilder] so Android IMEs can compose Hangul, Pinyin, and Latin
* candidates normally, diffs the editable against what was last sent to the PTY once each batch
* edit settles, and clears the editable as soon as no composing span remains.
* The private [SpannableStringBuilder] holds the text the IME has typed on the current shell line,
* committed and composing alike. IMEs keep their own copy of that text and edit it by offset:
* Gboard picks a suggestion or applies double-space period by replacing text it committed
* earlier. Once each batch edit settles, the editable is diffed against what the terminal already
* holds and only the difference is sent, as rubouts plus the new suffix.
*
* A terminal key (Enter, Tab, Escape, arrows, control and hardware characters) changes the shell
* line outside the IME, so it empties the editable and restarts the IME on the empty line.
* Keys sent to the terminal without passing through this connection do not empty it: the
* accessory bar, and the hardware arrows that `PaseoHardwareKeyboardModule` claims at window level.
*/
internal class TerminalInputConnection(
private val targetView: View,
@@ -196,6 +203,7 @@ internal class TerminalInputConnection(
KeyEvent.KEYCODE_DPAD_LEFT,
KeyEvent.KEYCODE_DPAD_RIGHT -> {
deadAccent = 0
flushAndClear()
val name = when (keyCode) {
KeyEvent.KEYCODE_DPAD_UP -> "ArrowUp"
KeyEvent.KEYCODE_DPAD_DOWN -> "ArrowDown"
@@ -342,57 +350,38 @@ internal class TerminalInputConnection(
if (diff.isNotEmpty()) {
out.append(normalizeLineEndings(diff))
}
lastSentText = currentText
val compStart = getComposingSpanStart(sharedEditable)
val compEnd = getComposingSpanEnd(sharedEditable)
val isComposing = compStart >= 0 && compEnd > compStart
if (!isComposing) {
val hadText = sharedEditable.isNotEmpty()
if (hadText || compStart >= 0) {
clearEditableSilently()
}
lastSentText = ""
if (hadText) {
// The IME just advanced its cursor for the committed text; report the reset to 0, 0.
forceUpdateSelection(0, 0, -1, -1)
} else {
notifySelectionIfChanged(0, 0, -1, -1)
}
} else {
lastSentText = currentText
val selStart = maxOf(0, Selection.getSelectionStart(sharedEditable))
val selEnd = maxOf(0, Selection.getSelectionEnd(sharedEditable))
notifySelectionIfChanged(selStart, selEnd, compStart, compEnd)
var compStart = getComposingSpanStart(sharedEditable)
var compEnd = getComposingSpanEnd(sharedEditable)
if (compStart >= 0 && compEnd <= compStart) {
// An empty composing span would make hardware arrows look like IME navigation.
removeComposingSpans(sharedEditable)
compStart = -1
compEnd = -1
}
notifySelectionIfChanged(
maxOf(0, Selection.getSelectionStart(sharedEditable)),
maxOf(0, Selection.getSelectionEnd(sharedEditable)),
compStart,
compEnd,
)
if (out.isNotEmpty()) {
onInput(out.toString())
}
}
/** Sends pending IME text, then starts the IME on an empty line before a terminal key. */
private fun flushAndClear() {
batchEditDepth = 0
val hadText = sharedEditable.isNotEmpty()
val out = StringBuilder()
if (pendingBackspaces > 0) {
repeat(pendingBackspaces) { out.append('\u007f') }
pendingBackspaces = 0
}
val currentText = sharedEditable.toString()
val diff = computeDiff(lastSentText, currentText)
if (diff.isNotEmpty()) {
out.append(normalizeLineEndings(diff))
}
if (hadText || getComposingSpanStart(sharedEditable) >= 0) {
clearEditableSilently()
}
lastSentText = ""
if (hadText || lastSelStart != 0 || lastSelEnd != 0 || lastCompStart != -1 || lastCompEnd != -1) {
forceUpdateSelection(0, 0, -1, -1)
}
if (out.isNotEmpty()) {
onInput(out.toString())
flush()
if (sharedEditable.isEmpty()) return
resetState()
// The IME still holds the old line; updateSelection alone does not make Gboard reload it.
val imm = targetView.context.getSystemService(InputMethodManager::class.java) ?: return
if (imm.isActive(targetView)) {
imm.restartInput(targetView)
}
}
@@ -411,10 +400,6 @@ internal class TerminalInputConnection(
) {
return
}
forceUpdateSelection(selStart, selEnd, compStart, compEnd)
}
private fun forceUpdateSelection(selStart: Int, selEnd: Int, compStart: Int, compEnd: Int) {
lastSelStart = selStart
lastSelEnd = selEnd
lastCompStart = compStart
+8 -7
View File
@@ -603,14 +603,15 @@ describe("layoutStream", () => {
splitIntoCards,
);
const layout = layoutFor({
platform,
tail,
timingIds: ["genui/a1/card", "genui/a2/card"],
});
const footerCardIds = tail
.filter((item) => item.kind === "plugin" && item.itemKind === "genui-card")
.map((item) => item.id);
expect(footerCardIds).toHaveLength(2);
expect(footerOwners(layout)).toEqual(["genui/a1/card", "genui/a2/card"]);
expect(findLayoutItem(layout, "genui/a1/card").completedFooter?.turnMetrics).toBe(
const layout = layoutFor({ platform, tail, timingIds: footerCardIds });
expect(footerOwners(layout)).toEqual(footerCardIds);
expect(findLayoutItem(layout, footerCardIds[0]).completedFooter?.turnMetrics).toBe(
first.turnMetrics,
);
expect(layout.auxiliaryTurnFooter?.turnMetrics).toBe(metrics);
@@ -203,7 +203,9 @@ describe("stream presentation through installed plugins", () => {
const source = rows(harness.source());
expect(source).toMatchObject([{ kind: "user_message", id: "prompt-1" }]);
expect(rendered).toMatchObject([{ kind: "plugin", id: "probe-plugin/prompt-1/0" }]);
expect(rendered).toMatchObject([
{ kind: "plugin", source: { id: "prompt-1" }, pluginItemId: "prompt-1/0" },
]);
// The chat outline jumps to the source id; the row it lands on is the plugin's.
expect(rendered.map(getStreamItemMessageId)).toEqual(["prompt-1"]);
});
@@ -611,7 +613,7 @@ it("folds work before a plugin-rendered reply and leaves the reply visible", ()
expect(result.tail.map((item) => item.id)).toEqual([
"prompt",
"turn-summary:prompt",
"probe-plugin/reply/0",
JSON.stringify(["probe-plugin", "reply", "reply/0"]),
]);
expect(pluginData(result.tail)).toEqual([{ text: "$$x^2$$", phase: "complete" }]);
});
@@ -640,7 +642,7 @@ it("keeps streaming replies native, then folds work without losing manual expans
expect(present(completed).tail.map((item) => item.id)).toEqual([
"prompt",
"turn-summary:prompt",
"probe-plugin/reply/0",
JSON.stringify(["probe-plugin", "reply", "reply/0"]),
]);
const expandedTurnHostIds = new Set(["prompt"]);
const opened = present({ ...completed, expandedTurnHostIds });
@@ -648,14 +650,16 @@ it("keeps streaming replies native, then folds work without losing manual expans
"prompt",
"turn-summary:prompt",
"tool-one",
"probe-plugin/reply/0",
JSON.stringify(["probe-plugin", "reply", "reply/0"]),
]);
expect(opened.turns.nestedItemIds.has("probe-plugin/reply/0")).toBe(false);
expect(opened.turns.nestedItemIds.has(JSON.stringify(["probe-plugin", "reply", "reply/0"]))).toBe(
false,
);
expect(present({ ...completed, expandedTurnHostIds }).tail).toEqual(opened.tail);
expect(present(completed).tail.map((item) => item.id)).toEqual([
"prompt",
"turn-summary:prompt",
"probe-plugin/reply/0",
JSON.stringify(["probe-plugin", "reply", "reply/0"]),
]);
});
@@ -679,7 +683,7 @@ it.each(["full", "collapseToolCalls"] as const)(
expect(result.tail.map((item) => item.id)).toEqual([
"prompt",
"tool-one",
"probe-plugin/reply/0",
JSON.stringify(["probe-plugin", "reply", "reply/0"]),
]);
expect(result.turns.summaryRowsByHostId.size).toBe(0);
},
@@ -783,6 +787,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[] = [
+24 -2
View File
@@ -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);
});
});
+344 -34
View File
@@ -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}\``);
});
});
+44 -2
View File
@@ -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);
});
-1
View File
@@ -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}
@@ -5,6 +5,7 @@ import {
encodeAttachmentsForSend,
garbageCollectAttachments,
persistAttachmentFromBytes,
prepareImageAttachmentsForSend,
uploadImageAttachments,
} from "./service";
@@ -220,4 +221,71 @@ describe("attachment service", () => {
},
]);
});
it("uses file.upload.request when daemon advertises uploadedImageAttachments and falls back to inline base64 images on legacy daemons", async () => {
const store = createRecordingStore();
__setAttachmentStoreForTests(store);
const attachment = createAttachment({
id: "img-compat",
fileName: "photo.jpg",
mimeType: "image/jpeg",
});
const uploadCalls: string[] = [];
const modernClient = {
getLastServerInfoMessage: () => ({ features: { uploadedImageAttachments: true } }),
uploadFile: async (input: { fileName: string; mimeType: string; bytes: Uint8Array }) => {
uploadCalls.push(input.fileName);
return {
requestId: "req-modern",
file: {
type: "uploaded_file" as const,
id: "upload_photo",
fileName: input.fileName,
mimeType: input.mimeType,
size: input.bytes.byteLength,
path: "/home/user/.paseo/uploads/upload_photo/photo.jpg",
},
error: null,
};
},
};
const modernResult = await prepareImageAttachmentsForSend({
client: modernClient,
images: [attachment],
});
expect(uploadCalls).toEqual(["photo.jpg"]);
expect(modernResult).toEqual({
attachments: [
{
type: "uploaded_file",
id: "upload_photo",
fileName: "photo.jpg",
mimeType: "image/jpeg",
size: new TextEncoder().encode("img-compat:bytes").byteLength,
path: "/home/user/.paseo/uploads/upload_photo/photo.jpg",
role: "image",
},
],
});
const legacyUploadCalls: string[] = [];
const legacyClient = {
getLastServerInfoMessage: () => ({ features: {} }),
uploadFile: async (input: { fileName: string }) => {
legacyUploadCalls.push(input.fileName);
throw new Error("uploadFile must not be called for legacy daemon image sends");
},
};
const legacyResult = await prepareImageAttachmentsForSend({
client: legacyClient,
images: [attachment],
});
expect(legacyUploadCalls).toEqual([]);
expect(legacyResult).toEqual({
images: [{ data: "img-compat:base64", mimeType: "image/jpeg" }],
});
});
});
+39 -3
View File
@@ -152,6 +152,15 @@ export interface ImageUploadClient {
}>;
}
export interface ImageSendClient extends ImageUploadClient {
getLastServerInfoMessage: () => { features?: { uploadedImageAttachments?: boolean } } | null;
}
export interface PreparedImagePayload {
images?: Array<{ data: string; mimeType: string }>;
attachments?: UploadedFileAttachment[];
}
export async function readAttachmentBytes(attachment: AttachmentMetadata): Promise<Uint8Array> {
const store = await getAttachmentStore();
return await store.readBytes({ attachment });
@@ -160,9 +169,8 @@ export async function readAttachmentBytes(attachment: AttachmentMetadata): Promi
/**
* Uploads persisted image attachments sequentially via `file.upload.request` so multi-photo
* batches drain cleanly between files instead of queueing concurrently on mobile sockets.
* Each uploaded image is marked with `role: "image"` inside `uploaded_file` so current daemons
* resolve it into a native vision block + timeline thumbnail, while older daemons (v0.1.91-v0.18.1)
* strip the unknown `role` field and still deliver the uploaded file path instead of dropping it.
* Each uploaded image is marked with `role: "image"` inside `uploaded_file` so capable daemons
* resolve it into a native vision block + timeline thumbnail.
*/
export async function uploadImageAttachments(input: {
client: ImageUploadClient;
@@ -196,6 +204,34 @@ export async function uploadImageAttachments(input: {
return uploaded;
}
/**
* Prepares image attachments for agent prompt/create RPCs.
*
* Hosts advertising `server_info.features.uploadedImageAttachments` receive sequential
* `file.upload.request` uploads tagged with `role: "image"`. Older hosts strip `role: "image"`
* and degrade the upload to plain file-path text, so they keep receiving inline base64 `images`.
*/
export async function prepareImageAttachmentsForSend(input: {
client: ImageSendClient;
images: readonly AttachmentMetadata[] | undefined;
}): Promise<PreparedImagePayload> {
if (!input.images || input.images.length === 0) {
return {};
}
// COMPAT(uploadedImageAttachments): added in v0.18.2, remove gate after 2027-06-01.
if (input.client.getLastServerInfoMessage()?.features?.uploadedImageAttachments === true) {
const attachments = await uploadImageAttachments({
client: input.client,
images: input.images,
});
return attachments ? { attachments } : {};
}
const images = await encodeAttachmentsForSend(input.images);
return images ? { images } : {};
}
export async function resolveAttachmentPreviewUrl(attachment: AttachmentMetadata): Promise<string> {
const store = await getAttachmentStore();
return await store.resolvePreviewUrl({ attachment });
@@ -60,6 +60,10 @@ export interface SheetHeaderSearch {
testID?: string;
}
/**
* One step back inside the sheet, such as from a page to the one before it. Android Back takes
* this step too, and closes the sheet only when the header has no back.
*/
export interface SheetHeaderBack {
onPress: () => void;
label?: string;
@@ -624,8 +628,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;
}
@@ -738,10 +742,17 @@ export function AdaptiveModalSheet({
}
}, [visible]);
const headerBack = header?.back?.onPress;
const handleBack = useCallback(() => {
if (!headerBack) return false;
headerBack();
return true;
}, [headerBack]);
const { sheetRef, handleSheetChange, handleSheetDismiss } = useIsolatedBottomSheetVisibility({
visible,
isEnabled: isSheet,
onClose,
onBack: handleBack,
});
const [shouldRenderWeb, setShouldRenderWeb] = useState(visible);
const [isWebClosing, setIsWebClosing] = useState(false);
@@ -783,12 +794,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,27 @@
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 {
getSheetSearchFooterStyle,
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 +30,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 +61,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 +77,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 +107,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 +236,185 @@ 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}
footerContainerStyle={getSheetSearchFooterStyle()}
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 +435,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 +553,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,
},
}));
@@ -12,6 +12,7 @@ import { useQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import {
FlatList,
Keyboard,
type LayoutChangeEvent,
ListRenderItemInfo,
Pressable,
@@ -629,6 +630,8 @@ export function FileExplorerPane({
if (!hasWorkspaceScope) {
return;
}
// The preview opens over this pane, so the filter must give up the keyboard.
Keyboard.dismiss();
onOpenFile?.(entry.path);
},
[hasWorkspaceScope, onOpenFile],
+1 -5
View File
@@ -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,376 @@
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,
}
: section,
),
).toEqual([
{ providerId: "claude", status: "ready", expanded: true },
{ providerId: "codex", status: "ready", expanded: false },
{ providerId: "opencode", status: "loading", expanded: false },
{ providerId: "pi", status: "ready", expanded: false },
{ providerId: "copilot", status: "error", expanded: false },
]);
});
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,
expanded: false,
});
expect(projection.sections.find((section) => section.expanded)?.key).toBe("claude");
});
it("omits the Profiles accordion when extracted to Home, while still searching profiles", () => {
const extractedInput: MobileModelPageInput = {
...inputWithProfiles,
showProfilesSection: false,
};
const browsed = browse(project([], extractedInput));
expect(browsed.sections.map((section) => section.key)).not.toContain(
MODEL_PICKER_PROFILES_RAIL_KEY,
);
const searched = project([{ kind: "query", query: "reviewer" }], extractedInput);
expect(searched.kind).toBe("search");
if (searched.kind !== "search") return;
expect(searched.profiles.map((item) => item.key)).toEqual(["profile:reviewer"]);
});
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,295 @@
import {
MODEL_PICKER_PROFILES_RAIL_KEY,
orderProvidersForPicker,
projectModelPicker,
type ModelPickerInput,
type ModelPickerListItem,
type ModelPickerPane,
type ModelPickerState,
} from "@/components/model-browser-panes-view";
import {
MODEL_BROWSER_CREATE_PROFILE_KEY,
modelBrowserProfileKey,
type NavigableProfileRow,
} from "@/components/model-browser-view";
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
/**
* The compact model picker: optional Profiles section 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 model folding, ordering, and search to the desktop picker's projection so both form
* factors behave identically.
*/
export interface MobileModelPageInput<TProfile extends NavigableProfileRow = NavigableProfileRow> {
providers: readonly ProviderSelectorProvider[];
/** `null` when the surface offers no profiles. */
profiles: readonly TProfile[] | null;
canCreateProfile: boolean;
/** False when Profiles is rendered outside this page (for example on Agent settings Home). */
showProfilesSection?: 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;
expanded: boolean;
}
export interface MobileProviderSection {
kind: "provider";
key: string;
providerId: string;
label: string;
status: "ready" | "loading" | "error";
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 a Profiles section: its models fill the page. */
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 opens already in 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: resolveInitialExpandedKey(input),
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 buildMobileProfileListItems<TProfile extends NavigableProfileRow>(
profiles: readonly TProfile[],
canCreateProfile: boolean,
): ModelPickerListItem<TProfile>[] {
if (profiles.length === 0) {
return canCreateProfile
? [{ kind: "createProfile", key: MODEL_BROWSER_CREATE_PROFILE_KEY }]
: [];
}
return profiles.map((profile) => ({
kind: "profile",
key: modelBrowserProfileKey(profile.id),
profile,
}));
}
export function projectMobileModelPage<TProfile extends NavigableProfileRow>(
input: MobileModelPageInput<TProfile>,
state: MobileModelPageState,
): MobileModelPageProjection<TProfile> {
if (input.providers.length === 0) return { kind: "noProviders" };
if (state.query.trim().length > 0) {
const picker = projectModelPicker<TProfile>(toPickerInput(input), toPickerState(state));
if (picker.pane.kind === "noMatches") return { kind: "noMatches", query: picker.pane.query };
if (picker.pane.kind === "search") {
return {
kind: "search",
profiles: picker.pane.profiles,
models: picker.pane.models,
items: picker.pane.items,
};
}
}
const sections = buildSections(input);
const showSectionHeaders = sections.length > 1;
const expandedKey = resolveExpandedKey(sections, state.expandedKey, showSectionHeaders);
for (const section of sections) {
section.expanded = section.key === expandedKey;
}
const body = expandedKey === null ? null : buildSectionBody(input, state, expandedKey);
return {
kind: "browse",
sections,
showSectionHeaders,
body,
selectedIndex: body ? findSelectedIndex(body, input) : null,
};
}
function resolveInitialExpandedKey<TProfile extends NavigableProfileRow>(
input: MobileModelPageInput<TProfile>,
): string {
const selected = input.providers.find((provider) => provider.id === input.selectedProvider);
if (selected) return selected.id;
if (input.showProfilesSection !== false && (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 buildSections<TProfile extends NavigableProfileRow>(
input: MobileModelPageInput<TProfile>,
): MobileModelSection[] {
const ordered: MobileModelSection[] = orderProvidersForPicker(input.providers).ordered.map(
(provider) => toProviderSection(provider),
);
if (input.showProfilesSection !== false && input.profiles !== null) {
ordered.unshift({
kind: "profiles",
key: MODEL_PICKER_PROFILES_RAIL_KEY,
expanded: false,
});
}
return ordered;
}
function resolveExpandedKey(
sections: readonly MobileModelSection[],
requestedKey: string | null,
showSectionHeaders: boolean,
): string | null {
if (showSectionHeaders && requestedKey === null) return null;
if (requestedKey !== null && sections.some((section) => section.key === requestedKey)) {
return requestedKey;
}
return sections[0]?.key ?? null;
}
function buildSectionBody<TProfile extends NavigableProfileRow>(
input: MobileModelPageInput<TProfile>,
state: MobileModelPageState,
expandedKey: string,
): MobileModelBody<TProfile> | null {
if (expandedKey === MODEL_PICKER_PROFILES_RAIL_KEY) {
return {
kind: "profiles",
items: buildMobileProfileListItems(input.profiles ?? [], input.canCreateProfile),
};
}
const provider = input.providers.find((entry) => entry.id === expandedKey);
if (!provider) return null;
// Pass only the expanded provider with profiles omitted so the shared picker projects that
// provider's own models, fold, loading, or error state cleanly.
const picker = projectModelPicker<TProfile>(
{
providers: [provider],
profiles: null,
canCreateProfile: false,
selectedProvider: input.selectedProvider,
selectedModel: input.selectedModel,
},
{
query: "",
railKey: provider.id,
focus: "list",
activeKey: null,
foldOverrides: state.foldOverrides,
},
);
if (picker.pane.kind === "search" || picker.pane.kind === "noMatches") return null;
return picker.pane;
}
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): MobileProviderSection {
const selection = provider.modelSelection;
let status: MobileProviderSection["status"] = "ready";
if (selection.kind === "loading") status = "loading";
else if (selection.kind === "error") status = "error";
return {
kind: "provider",
key: provider.id,
providerId: provider.id,
label: provider.label,
status,
expanded: false,
};
}
@@ -0,0 +1,928 @@
import { useCallback, useMemo, useRef, useState, type ReactElement, 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, Layers } from "lucide-react-native";
import type { AgentProfilePickerRow } from "@/agent-profiles";
import {
IndependentScrollBoundary,
MODEL_PICKER_ROW_HEIGHT,
ModelBrowserLoadingState,
ModelBrowserNoProviders,
ModelBrowserSectionHeading,
ModelProviderGlyph,
ModelSearchNoMatches,
ProviderErrorEmptyState,
} from "@/components/model-browser";
import {
CustomizeProviderButton,
EditProfilesButton,
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 {
buildMobileProfileListItems,
createMobileModelPageState,
projectMobileModelPage,
reduceMobileModelPage,
type MobileModelBody,
type MobileModelPageAction,
type MobileModelPageInput,
type MobileModelPageProjection,
type MobileModelSection,
type MobileProviderSection,
} from "@/components/mobile-model-page-view";
import { SettingsCard } from "@/components/settings";
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 { useInitialFlatListScroll } from "@/components/ui/scroll-reveal";
import { SearchField } from "@/components/ui/search-field";
import { isNative, isWeb } from "@/constants/platform";
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import { settingsStyles } from "@/styles/settings";
import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
/**
* The open accordion section lists its rows in a box capped at 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 SECTION_HEADER_HEIGHT = 44;
const ThemedAlertTriangle = withUnistyles(AlertTriangle);
const ThemedChevronDown = withUnistyles(ChevronDown);
const ThemedLayers = withUnistyles(Layers);
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
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;
showProfilesSection?: boolean;
selectedProvider: string;
selectedModel: string;
}): MobileModelPage {
const {
providers,
profiles = null,
canCreateProfile = false,
showProfilesSection = true,
selectedProvider,
selectedModel,
} = input;
const pageInput = useMemo<MobileModelPageInput<AgentProfilePickerRow>>(
() => ({
providers,
profiles,
canCreateProfile,
showProfilesSection,
selectedProvider,
selectedModel,
}),
[canCreateProfile, profiles, providers, selectedModel, selectedProvider, showProfilesSection],
);
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
variant="card"
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],
);
const singleProviderSection =
projection.kind === "browse" && !projection.showSectionHeaders
? projection.sections[0]
: undefined;
const singleProviderHeader = useMemo(
() =>
singleProviderSection?.kind === "provider" ? (
<ProviderSectionHeader
section={singleProviderSection}
serverId={serverId}
collapsible={false}
/>
) : undefined,
[serverId, singleProviderSection],
);
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) {
return (
<SheetListCard header={singleProviderHeader} testID="mobile-model-page">
{projection.body ? (
<SectionBody
body={projection.body}
selectedIndex={projection.selectedIndex}
renderItem={renderItem}
fill
onRetryProvider={actions.onRetryProvider}
isRetryingProvider={actions.isRetryingProvider}
/>
) : null}
</SheetListCard>
);
}
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={section.expanded ? projection.body : null}
selectedIndex={section.expanded ? projection.selectedIndex : null}
serverId={serverId}
actions={actions}
renderItem={renderItem}
onToggle={dispatch}
/>
))}
</View>
</SheetScrollView>
);
}
/**
* The collapsible Profiles card extracted onto Agent settings Home, using the same header and
* scrollable list as the Model accordion.
*/
export function CollapsibleProfilesCard({
profiles,
expanded,
onToggle,
serverId,
onApplyProfile,
onEditProfiles,
}: {
profiles: readonly AgentProfilePickerRow[];
expanded: boolean;
onToggle: () => void;
serverId: string | null;
onApplyProfile?: (profileId: string) => void;
onEditProfiles?: () => void;
}) {
const { t } = useTranslation();
const items = useMemo(
() => buildMobileProfileListItems(profiles, Boolean(onEditProfiles)),
[onEditProfiles, profiles],
);
const actions = useMemo<ModelPickerActions>(
() => ({
onSelect: noop,
onApplyProfile,
onEditProfiles,
isRetryingProvider: false,
}),
[onApplyProfile, onEditProfiles],
);
const emptyLookup = useMemo(() => new Map<string, AgentProfilePickerRow[]>(), []);
const renderItem = useCallback(
({ item }: { item: ModelPickerListItem<AgentProfilePickerRow> }) => (
<ModelPickerItemRow
item={item}
active={false}
selected={false}
inSearch={false}
serverId={serverId}
profiledLookup={emptyLookup}
onToggleFold={noop}
onActivate={noop}
actions={actions}
/>
),
[actions, emptyLookup, serverId],
);
const leading = useMemo(
() => <ThemedLayers size={ICON_SIZE.sm} uniProps={foregroundMutedMapping} />,
[],
);
const trailingAction = useMemo(
() => (expanded && onEditProfiles ? <EditProfilesButton onPress={onEditProfiles} /> : null),
[expanded, onEditProfiles],
);
const viewportHeight = computeBoundedListHeight(items.length);
return (
<SettingsCard testID="agent-controls-profiles-card">
<CollapsibleSectionHeader
leading={leading}
title={t("modelSelector.profiles")}
expanded={expanded}
trailing={trailingAction}
onToggle={onToggle}
testID="agent-controls-profiles"
/>
{expanded && items.length > 0 ? (
<IndependentScrollBoundary>
<SectionItemList
items={items}
selectedIndex={null}
renderItem={renderItem}
fill={false}
viewportHeight={viewportHeight}
testID="agent-controls-profiles-list"
/>
</IndependentScrollBoundary>
) : null}
</SettingsCard>
);
}
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;
}) {
const handleToggle = useCallback(
() => onToggle({ kind: "toggleSection", key: section.key }),
[onToggle, section.key],
);
return (
<SettingsCard>
{section.kind === "profiles" ? (
<ProfilesSectionHeader
expanded={section.expanded}
onEditProfiles={actions.onEditProfiles}
onToggle={handleToggle}
/>
) : (
<ProviderSectionHeader
section={section}
serverId={serverId}
collapsible
onToggle={handleToggle}
/>
)}
{section.expanded && 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 while its optional header stays fixed.
*/
function SheetListCard({
header,
children,
testID,
}: {
header?: ReactNode;
children: ReactNode;
testID?: string;
}) {
return (
<View style={styles.listCardPage} testID={testID}>
<View style={[settingsStyles.card, styles.listCard]}>
{header ? <View style={styles.listCardHeader}>{header}</View> : null}
<View style={[header ? settingsStyles.rowBorder : undefined, styles.listCardBody]}>
{children}
</View>
</View>
</View>
);
}
function noop() {}
function getItemKey(item: ModelPickerListItem<AgentProfilePickerRow>): string {
return item.key;
}
function getSearchEntryKey(entry: SearchEntry): string {
return entry.key;
}
function computeBoundedListHeight(itemCount: number): number {
return Math.min(
Math.max(itemCount, 1) * MODEL_PICKER_ROW_HEIGHT + LIST_CONTENT.paddingBottom,
MOBILE_EXPANDED_PROVIDER_HEIGHT,
);
}
/**
* One header component shared across collapsed and expanded states so toggling never shifts the
* icon, label, or chevron.
*/
function CollapsibleSectionHeader({
leading,
title,
expanded,
trailing,
onToggle,
testID,
}: {
leading: ReactNode;
title: string;
expanded: boolean;
trailing?: ReactNode;
onToggle?: () => void;
testID: string;
}) {
const accessibilityState = useMemo(() => ({ expanded }), [expanded]);
const webExpandedProps = useMemo(
() => (isWeb ? ({ "aria-expanded": expanded } as const) : null),
[expanded],
);
return (
<View style={styles.sectionHeader}>
{onToggle ? (
<PressHighlight
{...webExpandedProps}
onPress={onToggle}
accessibilityRole="button"
accessibilityLabel={title}
accessibilityState={accessibilityState}
style={styles.sectionHeaderPress}
highlightStyle={styles.sectionHeaderPressed}
testID={testID}
/>
) : null}
<View style={[styles.glyph, styles.passThrough]}>{leading}</View>
<View style={[styles.sectionTitleWrap, styles.passThrough]}>
<Text style={styles.sectionTitle} numberOfLines={1} testID={onToggle ? undefined : testID}>
{title}
</Text>
</View>
<View style={[styles.sectionTrailing, styles.boxNone]}>
{trailing}
{onToggle ? (
<View
style={[styles.chevronSlot, expanded && styles.chevronExpanded, styles.passThrough]}
>
<ThemedChevronDown size={ICON_SIZE.sm} uniProps={foregroundMutedMapping} />
</View>
) : null}
</View>
</View>
);
}
function ProfilesSectionHeader({
expanded,
onEditProfiles,
onToggle,
}: {
expanded: boolean;
onEditProfiles?: () => void;
onToggle: () => void;
}) {
const { t } = useTranslation();
const leading = useMemo(
() => <ThemedLayers size={ICON_SIZE.sm} uniProps={foregroundMutedMapping} />,
[],
);
const trailing = useMemo(
() => (expanded && onEditProfiles ? <EditProfilesButton onPress={onEditProfiles} /> : null),
[expanded, onEditProfiles],
);
return (
<CollapsibleSectionHeader
leading={leading}
title={t("modelSelector.profiles")}
expanded={expanded}
trailing={trailing}
onToggle={onToggle}
testID={expanded ? "model-profiles-section" : "model-picker-rail-profiles"}
/>
);
}
function ProviderSectionHeader({
section,
serverId,
collapsible,
onToggle,
}: {
section: MobileProviderSection;
serverId: string | null;
collapsible: boolean;
onToggle?: () => void;
}) {
const leading = useMemo(
() => (
<ModelProviderGlyph provider={section.providerId} serverId={serverId} size={ICON_SIZE.sm} />
),
[section.providerId, serverId],
);
const trailing = useMemo(() => {
if (section.expanded) {
return serverId ? (
<CustomizeProviderButton
serverId={serverId}
providerId={section.providerId}
providerLabel={section.label}
/>
) : null;
}
if (section.status === "loading") {
return (
<View style={[styles.spinner, styles.passThrough]}>
<ThemedLoadingSpinner size="small" uniProps={foregroundMutedMapping} />
</View>
);
}
if (section.status === "error") {
return (
<View style={styles.passThrough}>
<ThemedAlertTriangle size={ICON_SIZE.sm} uniProps={foregroundMutedMapping} />
</View>
);
}
return null;
}, [section.expanded, section.label, section.providerId, section.status, serverId]);
return (
<CollapsibleSectionHeader
leading={leading}
title={section.label}
expanded={section.expanded}
trailing={trailing}
onToggle={collapsible ? onToggle : undefined}
testID={
section.expanded
? `model-provider-section-${section.providerId}`
: `model-provider-${section.providerId}`
}
/>
);
}
type ModelItemRenderer = ({
item,
}: {
item: ModelPickerListItem<AgentProfilePickerRow>;
}) => 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.fillState : 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 viewportHeight =
body.kind === "profiles"
? computeBoundedListHeight(body.items.length)
: MOBILE_EXPANDED_PROVIDER_HEIGHT;
const list = (
<SectionItemList
// Each section is a new list, which opens directly at its top or at the selected model.
key={listKey}
items={body.items}
selectedIndex={selectedIndex}
renderItem={renderItem}
fill={fill}
viewportHeight={viewportHeight}
/>
);
// 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>;
}
function getModelItemLayout(
_data: ArrayLike<ModelPickerListItem<AgentProfilePickerRow>> | null | undefined,
index: number,
) {
return {
length: MODEL_PICKER_ROW_HEIGHT,
offset: index * MODEL_PICKER_ROW_HEIGHT,
index,
};
}
function modelItemOffset(index: number): number {
return index * MODEL_PICKER_ROW_HEIGHT;
}
/** Opens with the selected model already in view via `getItemLayout` + `initialScrollIndex`. */
function SectionItemList({
items,
selectedIndex,
renderItem,
fill,
viewportHeight,
testID = "compact-model-list",
}: {
items: ModelPickerListItem<AgentProfilePickerRow>[];
selectedIndex: number | null;
renderItem: ModelItemRenderer;
fill: boolean;
viewportHeight: number;
testID?: string;
}) {
const listRef = useRef<FlatList<ModelPickerListItem<AgentProfilePickerRow>>>(null);
const { initialScrollIndex, contentOffset } = useInitialFlatListScroll({
listRef,
selectedIndex,
itemCount: items.length,
visibleCount: Math.max(1, Math.floor(viewportHeight / MODEL_PICKER_ROW_HEIGHT)),
offsetForIndex: modelItemOffset,
});
const boxStyle = useMemo(() => {
if (fill) return SHEET_LIST_CARD_LIST;
if (viewportHeight === MOBILE_EXPANDED_PROVIDER_HEIGHT) return styles.fixedViewport;
return [styles.boundedViewport, inlineUnistylesStyle({ height: viewportHeight })];
}, [fill, viewportHeight]);
// A lone provider's list is the sheet's own scroller, so it must integrate with the bottom sheet
// gesture handler (SheetFlatList); an accordion list scrolls independently inside SheetScrollView.
const ListComponent = fill ? SheetFlatList : FlatList;
return (
<ListComponent
ref={listRef}
data={items}
renderItem={renderItem}
keyExtractor={getItemKey}
getItemLayout={getModelItemLayout}
initialScrollIndex={initialScrollIndex}
contentOffset={contentOffset}
style={boxStyle}
contentContainerStyle={LIST_CONTENT}
keyboardShouldPersistTaps="handled"
keyboardDismissMode={KEYBOARD_DISMISS_MODE}
showsVerticalScrollIndicator
nestedScrollEnabled={!fill}
testID={testID}
/>
);
}
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],
},
listCard: {
flexShrink: 1,
minHeight: 0,
},
listCardHeader: {
flexShrink: 0,
},
listCardBody: {
flexShrink: 1,
minHeight: 0,
},
fillState: {
minHeight: MOBILE_EXPANDED_PROVIDER_HEIGHT,
},
sections: {
paddingHorizontal: theme.spacing[4],
paddingTop: theme.spacing[2],
paddingBottom: theme.spacing[4],
gap: theme.spacing[2],
},
sectionHeader: {
height: SECTION_HEADER_HEIGHT,
position: "relative",
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
// Matches ModelBrowserRow's leading/trailing rail so icons and chevrons line up cleanly.
paddingHorizontal: { xs: theme.spacing[4], md: theme.spacing[3] },
},
sectionHeaderPress: {
...StyleSheet.absoluteFill,
},
sectionHeaderPressed: {
backgroundColor: theme.colors.surface2,
},
passThrough: {
pointerEvents: "none",
},
boxNone: {
pointerEvents: "box-none",
},
glyph: {
width: 16,
alignItems: "center",
justifyContent: "center",
},
sectionTitleWrap: {
flex: 1,
minWidth: 0,
},
sectionTitle: {
fontSize: theme.fontSize.base,
fontWeight: theme.fontWeight.normal,
color: theme.colors.foreground,
},
sectionTrailing: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
},
// Optical: matches SettingsRowHeader's chevron overhang so the glyph sits on the trailing rail.
chevronSlot: {
width: ICON_SIZE.sm,
height: ICON_SIZE.sm,
marginRight: -theme.spacing[1],
alignItems: "center",
justifyContent: "center",
},
chevronExpanded: {
transform: [{ rotate: "180deg" }],
},
spinner: {
transform: [{ scale: 0.7 }],
},
fixedViewport: {
height: MOBILE_EXPANDED_PROVIDER_HEIGHT,
flexGrow: 0,
},
boundedViewport: {
flexGrow: 0,
},
centered: {
alignItems: "center",
justifyContent: "center",
},
dock: {
flex: 1,
flexDirection: "row",
},
searchFooter: {
// Matches the card inset (`styles.sections` / `styles.listCardPage`) so the search box shares
// its outer left and right rails with the provider cards above it.
paddingHorizontal: theme.spacing[4],
},
}));
/** Read at render time rather than module scope (docs/unistyles.md). */
export function getSheetSearchFooterStyle() {
return styles.searchFooter;
}
@@ -0,0 +1,632 @@
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 a single pane for one provider even when the surface offers profiles", () => {
expect(resolveModelPickerLayout(input({ providers: [claude] }))).toBe("singlePane");
expect(resolveModelPickerLayout(input({ providers: [claude], profiles: [] }))).toBe(
"singlePane",
);
expect(resolveModelPickerLayout(input({ providers: [claude], profiles: null }))).toBe(
"singlePane",
);
});
it("lists matching profiles above models in a single-pane provider view", () => {
const { projection } = open(input({ providers: [claude], profiles: [profiles[1]] }));
expect(projection.layout).toBe("singlePane");
expect(projection.rail).toEqual([]);
expect(projection.pane).toMatchObject({
kind: "provider",
providerId: "claude",
label: "Claude",
});
if (projection.pane.kind !== "provider") return;
expect(keys(projection.pane.profiles)).toEqual(["profile:quick"]);
expect(keys(projection.pane.models)).toEqual([
"model:claude:opus-5.5",
"model:claude:fable-5.2",
"model:claude:sonnet-5.5",
"model:claude:haiku-5.5",
"fold:claude",
]);
expect(projection.activeKey).toBe("model:claude:opus-5.5");
});
it("keeps profiles usable in single-pane mode while the lone provider is loading or errored", () => {
const loading = open(
input({
providers: [opencode],
profiles: [profiles[0]],
selectedProvider: "opencode",
selectedModel: "",
}),
).projection;
expect(loading.layout).toBe("singlePane");
expect(loading.pane).toMatchObject({ kind: "providerLoading", providerId: "opencode" });
expect(keys(loading.pane.items)).toEqual(["profile:deep-review"]);
expect(loading.activeKey).toBe("profile:deep-review");
const errored = open(
input({
providers: [copilot],
profiles: [profiles[0]],
selectedProvider: "copilot",
selectedModel: "",
}),
).projection;
expect(errored.layout).toBe("singlePane");
expect(errored.pane).toMatchObject({ kind: "providerError", providerId: "copilot" });
expect(keys(errored.pane.items)).toEqual(["profile:deep-review"]);
expect(errored.activeKey).toBe("profile:deep-review");
});
it("includes Create profile at the end of a single-pane list when there are no profiles", () => {
const { projection } = open(
input({
providers: [codex],
profiles: [],
selectedProvider: "codex",
selectedModel: "gpt-5.4",
}),
);
expect(projection.layout).toBe("singlePane");
if (projection.pane.kind !== "provider") return;
expect(projection.pane.profiles).toEqual([]);
expect(keys(projection.pane.models)).toEqual([
"model:codex:gpt-5.4",
"model:codex:gpt-5.4-mini",
"create-profile",
]);
});
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("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",
});
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.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", providerId: "codex" });
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,613 @@
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 }
| {
kind: "provider";
key: string;
providerId: string;
label: string;
status: "ready" | "loading" | "error";
/** 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;
/** Single-pane only: profiles listed above this provider's models. */
profiles: ModelPickerListItem<TProfile>[];
/** Provider models, optional fold row, and trailing create-profile row in single-pane mode. */
models: ModelPickerListItem<TProfile>[];
items: ModelPickerListItem<TProfile>[];
}
| {
kind: "providerLoading";
providerId: string;
label: string;
/** Single-pane only: profiles kept usable while the provider catalog loads. */
profiles: ModelPickerListItem<TProfile>[];
items: ModelPickerListItem<TProfile>[];
}
| {
kind: "providerError";
providerId: string;
label: string;
message: string;
/** Single-pane only: profiles kept usable when the provider catalog fails. */
profiles: ModelPickerListItem<TProfile>[];
items: ModelPickerListItem<TProfile>[];
}
| { 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 only when there are several providers to switch between; a single provider keeps a
* compact single-pane list (with any matching profiles in a section above its models). */
export function resolveModelPickerLayout(input: ModelPickerInput): ModelPickerLayout {
return input.providers.length > 1 ? "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, profiles and folded ones included.
*/
export function resolveModelPickerHeight(input: ModelPickerInput): number {
if (resolveModelPickerLayout(input) === "twoPane") return TWO_PANE_HEIGHT;
const provider = input.providers[0];
const providerRows = provider ? countAllRows(provider) : 0;
let profileRows = 0;
if (input.profiles !== null) {
if (input.profiles.length > 0) {
// Profiles rows plus the Profiles and provider section headings.
profileRows = input.profiles.length + 2;
} else if (input.canCreateProfile) {
profileRows = 1;
}
}
return clamp(
SINGLE_PANE_CHROME_HEIGHT + (providerRows + profileRows) * 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, layout, 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;
}
/** Orders providers with working (ready/loading) ones first and errored ones last. */
export function orderProvidersForPicker(providers: readonly ProviderSelectorProvider[]): {
ordered: ProviderSelectorProvider[];
firstErroredId: string | null;
} {
const working = providers.filter((provider) => provider.modelSelection.kind !== "error");
const errored = providers.filter((provider) => provider.modelSelection.kind === "error");
return {
ordered: [...working, ...errored],
firstErroredId: working.length > 0 ? (errored[0]?.id ?? null) : null,
};
}
function buildRail(input: ModelPickerInput): ModelPickerRailItem[] {
const { ordered, firstErroredId } = orderProvidersForPicker(input.providers);
const providerItems = ordered.map((provider) =>
buildProviderRailItem(provider, provider.id === firstErroredId),
);
if (input.profiles === null) return providerItems;
return [{ kind: "profiles", key: MODEL_PICKER_PROFILES_RAIL_KEY }, ...providerItems];
}
function buildProviderRailItem(
provider: ProviderSelectorProvider,
startsErrorGroup: boolean,
): Extract<ModelPickerRailItem, { kind: "provider" }> {
const selection = provider.modelSelection;
const base = {
kind: "provider" as const,
key: provider.id,
providerId: provider.id,
label: provider.label,
startsErrorGroup,
};
if (selection.kind === "loading") return { ...base, status: "loading" };
if (selection.kind === "error") return { ...base, status: "error" };
return { ...base, status: "ready" };
}
function buildBrowsePane<TProfile extends NavigableProfileRow>(
input: ModelPickerInput<TProfile>,
state: ModelPickerState,
layout: ModelPickerLayout,
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 singlePaneProfiles: ModelPickerListItem<TProfile>[] =
layout === "singlePane" && input.profiles !== null && input.profiles.length > 0
? input.profiles.map((profile) => toProfileItem(profile))
: [];
const selection = provider.modelSelection;
if (selection.kind === "loading") {
return {
kind: "providerLoading",
providerId: provider.id,
label: provider.label,
profiles: singlePaneProfiles,
items: singlePaneProfiles,
};
}
if (selection.kind === "error") {
return {
kind: "providerError",
providerId: provider.id,
label: provider.label,
message: selection.message,
profiles: singlePaneProfiles,
items: singlePaneProfiles,
};
}
const partition = partitionFor(input, provider);
const providerModels = buildProviderItems<TProfile>(provider.id, partition, state);
if (layout === "singlePane" && input.profiles !== null) {
if (singlePaneProfiles.length > 0) {
return {
kind: "provider",
providerId: provider.id,
label: provider.label,
profiles: singlePaneProfiles,
models: providerModels,
items: [...singlePaneProfiles, ...providerModels],
};
}
if (input.canCreateProfile) {
const modelsWithCreate: ModelPickerListItem<TProfile>[] = [
...providerModels,
{ kind: "createProfile", key: MODEL_BROWSER_CREATE_PROFILE_KEY },
];
return {
kind: "provider",
providerId: provider.id,
label: provider.label,
profiles: [],
models: modelsWithCreate,
items: modelsWithCreate,
};
}
}
return {
kind: "provider",
providerId: provider.id,
label: provider.label,
profiles: [],
models: providerModels,
items: providerModels,
};
}
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);
}
File diff suppressed because it is too large Load Diff
@@ -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)],
};
}
+161 -177
View File
@@ -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 {
@@ -105,6 +101,10 @@ const DESKTOP_PROVIDER_VIEW_MAX_HEIGHT = 400;
const DESKTOP_PROVIDER_VIEW_BASE_HEIGHT = 80;
const DESKTOP_MODEL_ROW_HEIGHT = 40;
/** Fixed picker row heights so virtualized lists can mount directly at the selected row via `getItemLayout`. */
export const MODEL_PICKER_ROW_HEIGHT = isWeb ? 36 : 44;
export const MODEL_PICKER_HEADING_HEIGHT = 32;
const ThemedAlertTriangle = withUnistyles(AlertTriangle);
const ThemedCheck = withUnistyles(Check);
const ThemedChevronRight = withUnistyles(ChevronRight);
@@ -280,23 +280,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 +297,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 +350,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 +541,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 +711,9 @@ function ModelBrowserPressable({
);
}
type ModelBrowserRowTone = "default" | "elevated" | "drillDown";
export type ModelBrowserRowTone = "default" | "elevated" | "drillDown";
function ModelBrowserRow({
export function ModelBrowserRow({
label,
description,
leadingSlot,
@@ -835,14 +845,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 +866,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 +1003,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 +1013,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 +1381,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 +1524,6 @@ function ModelRowList({
onSelect,
showProviderLabel = false,
header,
scrolling,
profiledLookup,
onCreateProfile,
onEditProfile,
@@ -1514,13 +1539,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 +1571,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 +1612,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 +1756,6 @@ function ModelBrowserBrowseView({
projection,
activeNavIndex,
listKey,
rootBrowseContent,
scrolling,
onApplyProfile,
onEditProfiles,
onDrillDown,
@@ -1724,8 +1764,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 +1795,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 +1822,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 +1832,6 @@ function ModelBrowserContent({
selectedProvider,
selectedModel,
searchQuery,
isSearchFocused,
profiles,
explicitActiveKey,
preferredActiveKey,
@@ -1829,12 +1847,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 +1860,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 +1940,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 +1953,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 +1967,6 @@ function ModelBrowserContent({
onSelect={onSelect}
showProviderLabel={projection.showProviderLabel}
header={listHeader}
scrolling={scrolling}
profiledLookup={profiledLookup}
onCreateProfile={onCreateProfile}
onEditProfile={onEditProfile}
@@ -1995,8 +1980,6 @@ function ModelBrowserContent({
projection={projection}
activeNavIndex={activeNavIndex}
listKey={browseListKey}
rootBrowseContent={rootBrowseContent}
scrolling={scrolling}
onApplyProfile={onApplyProfile}
onEditProfiles={onEditProfiles}
onDrillDown={onDrillDown}
@@ -2018,10 +2001,6 @@ export function ModelBrowser({
onEditProfile,
onRetryProvider,
isRetryingProvider = false,
scrolling = "sheet",
searchAllOnFocus = false,
rootBrowseContent,
showProfilesSection,
}: ModelBrowserProps) {
return (
<ModelBrowserContent
@@ -2031,7 +2010,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 +2025,6 @@ export function ModelBrowser({
onDrillDown={state.drillDown}
onRetryProvider={onRetryProvider}
isRetryingProvider={isRetryingProvider}
scrolling={scrolling}
searchAllOnFocus={searchAllOnFocus}
rootBrowseContent={rootBrowseContent}
showProfilesSection={showProfilesSection}
/>
);
}
@@ -2066,29 +2040,28 @@ const styles = StyleSheet.create((theme) => ({
backgroundColor: theme.colors.border,
},
sectionHeading: {
position: "relative",
height: MODEL_PICKER_HEADING_HEIGHT,
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
paddingHorizontal: isWeb ? theme.spacing[3] : theme.spacing[6],
paddingTop: theme.spacing[2],
paddingBottom: theme.spacing[1],
paddingHorizontal: { xs: theme.spacing[4], md: theme.spacing[3] },
},
sectionHeadingAction: {
position: "absolute",
top: theme.spacing[1],
right: isWeb ? theme.spacing[3] : theme.spacing[6],
flexShrink: 0,
alignItems: "center",
justifyContent: "center",
},
sectionHeadingText: {
flex: 1,
minWidth: 0,
fontSize: theme.fontSize.sm,
fontWeight: theme.fontWeight.normal,
color: theme.colors.foregroundMuted,
},
browserRow: {
flexDirection: "row",
paddingVertical: theme.spacing[2],
minHeight: 36,
alignItems: "center",
height: MODEL_PICKER_ROW_HEIGHT,
},
modelRowHoverBoundary: {
position: "relative",
@@ -2097,10 +2070,10 @@ const styles = StyleSheet.create((theme) => ({
position: "absolute",
top: 0,
bottom: 0,
right: isWeb ? theme.spacing[3] : theme.spacing[6],
right: { xs: theme.spacing[4], md: theme.spacing[3] },
justifyContent: "center",
},
browserModelRow: isWeb ? {} : { marginBottom: theme.spacing[1] },
browserModelRow: {},
browserRowHovered: {
backgroundColor: theme.colors.surface1,
},
@@ -2118,7 +2091,7 @@ const styles = StyleSheet.create((theme) => ({
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
paddingHorizontal: isWeb ? theme.spacing[3] : theme.spacing[6],
paddingHorizontal: { xs: theme.spacing[4], md: theme.spacing[3] },
},
browserRowLeading: {
width: 16,
@@ -2144,6 +2117,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,
@@ -0,0 +1,52 @@
import { Component, type ErrorInfo, type ReactNode } from "react";
interface RenderErrorBoundaryProps {
children: ReactNode;
/** A caught error is cleared when any of these values change, so new content renders. */
resetKeys: readonly unknown[];
/** The error state shown in place of the children. `retry` renders the children again. */
renderError(error: string, retry: () => void): ReactNode;
onError(error: unknown, componentStack: string | null | undefined): void;
}
interface RenderErrorBoundaryState {
error: string | null;
}
/**
* Keeps a render error inside one surface. Without it the error reaches the root boundary,
* which replaces the whole app.
*/
export class RenderErrorBoundary extends Component<
RenderErrorBoundaryProps,
RenderErrorBoundaryState
> {
state: RenderErrorBoundaryState = { error: null };
static getDerivedStateFromError(error: unknown): RenderErrorBoundaryState {
return { error: error instanceof Error ? error.message : String(error) };
}
componentDidCatch(error: unknown, info: ErrorInfo): void {
this.props.onError(error, info.componentStack);
}
componentDidUpdate(previous: RenderErrorBoundaryProps): void {
if (this.state.error !== null && resetKeysChanged(previous.resetKeys, this.props.resetKeys)) {
this.retry();
}
}
retry = (): void => {
this.setState({ error: null });
};
render() {
if (this.state.error !== null) return this.props.renderError(this.state.error, this.retry);
return this.props.children;
}
}
function resetKeysChanged(previous: readonly unknown[], next: readonly unknown[]): boolean {
return previous.length !== next.length || previous.some((key, index) => key !== next[index]);
}
@@ -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
@@ -151,5 +151,8 @@ describe("settings row density", () => {
const summary = textNode("short-summary", "Local").getBoundingClientRect();
// The summary's margin, the chevron and the row's padding: about 40px.
expect(row.right - summary.right).toBeLessThan(48);
expect(titleFontSize("short-summary", "Local")).toBe(
titleFontSize("short-summary", "Speech to text"),
);
});
});
@@ -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,14 @@ 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}
titleStyle={layout.title}
/>
{external || disabled ? null : (
<View style={chevronStyle} {...HIDDEN_FROM_ASSISTIVE_TECH}>
<ThemedChevron
@@ -157,19 +167,27 @@ function RowTrailing({
external,
hovered,
summary,
summaryLeading,
titleStyle,
}: {
hinted: boolean;
external: boolean;
hovered: boolean;
summary: string | undefined;
summaryLeading: ReactNode;
titleStyle: SettingsRowLayout["title"];
}) {
const style = hinted ? styles.hintedTrailing : styles.labelTrailing;
const summaryStyle = useMemo(() => [titleStyle, styles.summary], [titleStyle]);
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}>
<Text style={summaryStyle} numberOfLines={1}>
{summary}
</Text>
) : null}
@@ -293,10 +311,14 @@ 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,
fontSize: theme.fontSize.sm,
marginRight: theme.spacing[2],
},
hovered: {
@@ -89,9 +89,7 @@ const styles = StyleSheet.create((theme: Theme) => ({
top: 0,
bottom: 0,
width: INDENT_GUIDE_WIDTH,
// Translucent ink, not `border`: a solid line that colour disappears into a hovered row's fill.
backgroundColor: theme.colors.foregroundExtraMuted,
opacity: theme.opacity[50],
backgroundColor: theme.colors.treeGuide,
},
chevron: {
width: WORKSPACE_TREE_ICON_SIZE,
+111
View File
@@ -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,
},
}));
+28 -9
View File
@@ -1,4 +1,5 @@
import { useOverlayRegistration, type KeyboardInputEvent } from "@/keyboard";
import { useSettledKeyboardHeight } from "@/keyboard/shift";
import { Modal } from "@/components/ui/modal";
import {
useCallback,
@@ -149,8 +150,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;
@@ -943,19 +944,34 @@ function maybePinDesktopOptionsToBottom(
interface FloatingMiddlewareInput {
collisionPadding: number;
keyboardHeight: number;
isDesktopAboveSearch: boolean;
setAvailableSize: FloatingSizeSetters["setAvailableSize"];
setReferenceWidth: FloatingSizeSetters["setReferenceWidth"];
}
function buildFloatingMiddleware(input: FloatingMiddlewareInput) {
const { collisionPadding, isDesktopAboveSearch, setAvailableSize, setReferenceWidth } = input;
const {
collisionPadding,
keyboardHeight,
isDesktopAboveSearch,
setAvailableSize,
setReferenceWidth,
} = input;
// The native popover's boundary is the window, which the software keyboard covers. The keyboard
// height changes once the keyboard settles, so this also re-measures an anchor that rides it.
const padding = {
top: collisionPadding,
left: collisionPadding,
right: collisionPadding,
bottom: collisionPadding + keyboardHeight,
};
return [
floatingOffset(isWeb ? 5 : 4),
...(isWeb ? [] : [flip({ padding: collisionPadding })]),
...(isDesktopAboveSearch ? [] : [shift({ padding: collisionPadding })]),
...(isWeb ? [] : [flip({ padding })]),
...(isDesktopAboveSearch ? [] : [shift({ padding })]),
floatingSize({
padding: collisionPadding,
padding,
apply({ availableWidth, availableHeight, rects }) {
updateAvailableSize(setAvailableSize, availableWidth, availableHeight);
updateReferenceWidth(setReferenceWidth, rects.reference.width);
@@ -1496,16 +1512,18 @@ export function Combobox({
useResetSearchOnOpen(isOpen, setSearchQueryWithCallback, bumpSearchResetKey);
const collisionPadding = useMemo(computeCollisionPadding, []);
const keyboardHeight = useSettledKeyboardHeight();
const middleware = useMemo(
() =>
buildFloatingMiddleware({
collisionPadding,
keyboardHeight,
isDesktopAboveSearch,
setAvailableSize,
setReferenceWidth,
}),
[collisionPadding, isDesktopAboveSearch],
[collisionPadding, isDesktopAboveSearch, keyboardHeight],
);
const { refs, floatingStyles, update } = useFloating({
@@ -1735,12 +1753,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;
}
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { getScrollOffsetToRevealItem } from "./scroll-reveal";
import { getScrollOffsetToRevealItem, resolveInitialScrollIndex } from "./scroll-reveal";
describe("getScrollOffsetToRevealItem", () => {
it("keeps the offset when the item is already inside the viewport", () => {
@@ -46,3 +46,38 @@ describe("getScrollOffsetToRevealItem", () => {
).toBe(120);
});
});
describe("resolveInitialScrollIndex", () => {
it("stays at the top when the selected item is already in the first viewport", () => {
expect(resolveInitialScrollIndex({ selectedIndex: 0, itemCount: 20, visibleCount: 5 })).toBe(
undefined,
);
expect(resolveInitialScrollIndex({ selectedIndex: 4, itemCount: 20, visibleCount: 5 })).toBe(
undefined,
);
});
it("centers a deeper selected item inside the visible viewport", () => {
expect(resolveInitialScrollIndex({ selectedIndex: 9, itemCount: 236, visibleCount: 5 })).toBe(
7,
);
});
it("clamps near the end so the bottom viewport stays full", () => {
expect(resolveInitialScrollIndex({ selectedIndex: 235, itemCount: 236, visibleCount: 5 })).toBe(
231,
);
expect(resolveInitialScrollIndex({ selectedIndex: 19, itemCount: 20, visibleCount: 7 })).toBe(
13,
);
});
it("returns undefined for empty or out-of-range selections", () => {
expect(resolveInitialScrollIndex({ selectedIndex: null, itemCount: 20, visibleCount: 5 })).toBe(
undefined,
);
expect(resolveInitialScrollIndex({ selectedIndex: 5, itemCount: 3, visibleCount: 5 })).toBe(
undefined,
);
});
});
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useLayoutEffect, useRef, type RefObject } from "react";
import { useCallback, useLayoutEffect, useRef, type RefObject } from "react";
import type {
FlatList,
LayoutChangeEvent,
@@ -8,6 +8,7 @@ import type {
View,
ViewToken,
} from "react-native";
import { isNative, isWeb } from "@/constants/platform";
export function getScrollOffsetToRevealItem(args: {
currentOffset: number;
@@ -125,6 +126,88 @@ interface VisibleRange {
last: number;
}
/**
* Computes the `FlatList` `initialScrollIndex` that opens with `selectedIndex` in view without
* flashing index 0 first. Returns `undefined` when the row is already inside the first page so
* the list starts cleanly at the top.
*/
export function resolveInitialScrollIndex(args: {
selectedIndex: number | null;
itemCount: number;
visibleCount: number;
}): number | undefined {
const { selectedIndex, itemCount, visibleCount } = args;
if (
selectedIndex === null ||
selectedIndex < 0 ||
selectedIndex >= itemCount ||
visibleCount <= 0
) {
return undefined;
}
if (selectedIndex < visibleCount) {
return undefined;
}
const maxStart = Math.max(0, itemCount - visibleCount);
const centered = selectedIndex - Math.floor(visibleCount / 2);
const index = Math.min(Math.max(0, centered), maxStart);
return index > 0 ? index : undefined;
}
/**
* Opens a virtualized `FlatList` directly at `selectedIndex` without flashing index 0 first.
* Captures the mount offset once, supplies `initialScrollIndex` (and iOS `contentOffset`), and
* sets the web scroll position synchronously before first paint.
*/
export function useInitialFlatListScroll<T>(options: {
listRef: RefObject<FlatList<T> | null>;
selectedIndex: number | null;
itemCount: number;
visibleCount: number;
offsetForIndex: (index: number) => number;
}): {
initialScrollIndex: number | undefined;
contentOffset: { x: number; y: number } | undefined;
initialVisibleRange: VisibleRange;
} {
const { listRef, selectedIndex, itemCount, visibleCount, offsetForIndex } = options;
const initialMount = useRef<{
initialScrollIndex: number | undefined;
offset: number;
contentOffset: { x: number; y: number } | undefined;
initialVisibleRange: VisibleRange;
} | null>(null);
if (initialMount.current === null) {
const initialScrollIndex = resolveInitialScrollIndex({
selectedIndex,
itemCount,
visibleCount,
});
const start = initialScrollIndex ?? 0;
const offset = initialScrollIndex !== undefined ? offsetForIndex(initialScrollIndex) : 0;
initialMount.current = {
initialScrollIndex,
offset,
// Both iOS and Android ScrollViews apply contentOffset during native layout before first paint.
contentOffset: isNative && offset > 0 ? { x: 0, y: offset } : undefined,
initialVisibleRange: { first: start, last: start + Math.max(visibleCount, 1) - 1 },
};
}
const initialOffset = initialMount.current.offset;
useLayoutEffect(() => {
if (isWeb && initialOffset > 0) {
listRef.current?.scrollToOffset({ offset: initialOffset, animated: false });
}
}, [initialOffset, listRef]);
return {
initialScrollIndex: initialMount.current.initialScrollIndex,
contentOffset: initialMount.current.contentOffset,
initialVisibleRange: initialMount.current.initialVisibleRange,
};
}
function nextVisibleRangeAfterReveal(
visible: VisibleRange | null,
row: number,
@@ -147,6 +230,7 @@ export function useRevealActiveFlatListRow<T>({
activeIndex,
hasHeader = false,
waitForViewable = false,
initialVisibleRange = null,
listKey,
}: {
listRef: RefObject<FlatList<T> | null>;
@@ -154,9 +238,12 @@ export function useRevealActiveFlatListRow<T>({
activeIndex: number | "top" | null;
hasHeader?: boolean;
waitForViewable?: boolean;
/** Seeded visible window when the list mounted at an `initialScrollIndex`. */
initialVisibleRange?: VisibleRange | null;
listKey?: unknown;
}): RevealActiveFlatListHandlers<T> {
const fullyVisibleRows = useRef<VisibleRange | null>(null);
const fullyVisibleRows = useRef<VisibleRange | null>(initialVisibleRange);
const prevListKey = useRef(listKey);
const pendingReveal = useRef<number | null>(null);
const isPendingRowMeasured = useRef(true);
const itemCountRef = useRef(itemCount);
@@ -222,7 +309,11 @@ export function useRevealActiveFlatListRow<T>({
[revealPendingRow],
);
useEffect(() => {
useLayoutEffect(() => {
if (prevListKey.current !== listKey) {
prevListKey.current = listKey;
fullyVisibleRows.current = null;
}
if (activeIndex === "top") {
pendingReveal.current = null;
listRef.current?.scrollToOffset({ offset: 0, animated: false });
@@ -7,7 +7,7 @@ import {
} from "react-native";
import { Search, X } from "lucide-react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import type { Theme } from "@/styles/theme";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import {
EditingTextInput as TextInput,
type EditingTextInputHandle,
@@ -35,6 +35,11 @@ export interface SearchFieldProps {
fullWidth?: boolean;
/** `sm` heads a list in tight chrome such as a sidebar pane. */
size?: "sm" | "md";
/**
* `card` matches a compact `SettingsCard` row's height, corner radius, horizontal inset, and
* leading glyph rail so a docked sheet search aligns with the cards above it.
*/
variant?: "default" | "card";
/** Escape empties the field. Off where Escape already closes the surface around it. */
clearOnEscape?: boolean;
testID?: string;
@@ -56,6 +61,7 @@ export function SearchField({
clearAccessibilityLabel,
fullWidth = false,
size = "md",
variant = "default",
clearOnEscape = false,
testID,
clearTestID,
@@ -79,17 +85,21 @@ export function SearchField({
if (value === "" && inputRef.current?.getText()) inputRef.current.replaceText("");
}, [value]);
const small = size === "sm";
const card = variant === "card";
const leadingIcon = <ThemedSearch size={ICON_SIZE.sm} uniProps={mutedColorMapping} />;
return (
<View
testID={testID ? `${testID}-container` : undefined}
style={[
styles.field,
small && styles.fieldSmall,
card && styles.fieldCard,
fullWidth && styles.fieldFullWidth,
isFocused && styles.fieldFocused,
]}
>
<ThemedSearch size={14} uniProps={mutedColorMapping} />
{card ? <View style={styles.leadingSlot}>{leadingIcon}</View> : leadingIcon}
<ThemedTextInput
testID={testID}
ref={inputRef}
@@ -112,8 +122,9 @@ export function SearchField({
accessibilityRole="button"
accessibilityLabel={clearAccessibilityLabel}
hitSlop={8}
style={card ? styles.clearSlot : undefined}
>
<ThemedX size={14} uniProps={mutedColorMapping} />
<ThemedX size={ICON_SIZE.sm} uniProps={mutedColorMapping} />
</Pressable>
) : null}
</View>
@@ -142,6 +153,25 @@ const styles = StyleSheet.create((theme) => ({
paddingVertical: 0,
paddingHorizontal: theme.spacing[1.5],
},
fieldCard: {
// Matches a collapsed SettingsCard row: 44pt inner row height + 1px top/bottom border = 46pt.
height: 46,
paddingVertical: 0,
paddingHorizontal: { xs: theme.spacing[4], md: theme.spacing[3] },
borderRadius: theme.borderRadius.lg,
},
leadingSlot: {
width: 16,
alignItems: "center",
justifyContent: "center",
},
clearSlot: {
width: ICON_SIZE.sm,
height: ICON_SIZE.sm,
marginRight: -theme.spacing[1],
alignItems: "center",
justifyContent: "center",
},
fieldFullWidth: {
maxWidth: "100%",
},
@@ -153,7 +183,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,
},
}));
@@ -24,7 +24,7 @@ import {
import { useWorkspaceSetupStore } from "@/stores/workspace-setup-store";
import { normalizeAgentSnapshot } from "@/utils/agent-snapshots";
import { applyLegacyDaemonWorkspaceOwnership } from "@/workspace/legacy-daemon-workspaces";
import { uploadImageAttachments } from "@/attachments/service";
import { prepareImageAttachmentsForSend } from "@/attachments/service";
import { toErrorMessage } from "@/utils/error-messages";
import {
resolveComposerAttachmentSubmitFormat,
@@ -122,6 +122,7 @@ function failureMessageForCreationMethod(
function buildCreateAgentOptions({
composerState,
text,
images,
attachments,
workspaceDirectory,
workspaceId,
@@ -134,6 +135,7 @@ function buildCreateAgentOptions({
selectedSystemPrompt: string;
};
text: string;
images?: CreateAgentRequestOptions["images"];
attachments: NonNullable<CreateAgentRequestOptions["attachments"]>;
workspaceDirectory: string;
workspaceId: string;
@@ -152,6 +154,7 @@ function buildCreateAgentOptions({
? { systemPrompt: composerState.selectedSystemPrompt }
: {}),
...(text.trim() ? { initialPrompt: text.trim() } : {}),
...(images && images.length > 0 ? { images } : {}),
...(attachments.length > 0 ? { attachments } : {}),
};
}
@@ -327,19 +330,20 @@ export function WorkspaceSetupDialog() {
supportsForgeAttachments: supportsForgeSearch,
}),
});
const uploadedImageAttachments =
const imagePayload =
wirePayload.images.length > 0
? await uploadImageAttachments({
? await prepareImageAttachmentsForSend({
client: withConnectedClient(),
images: wirePayload.images,
})
: undefined;
: {};
if (!pendingWorkspaceSetup) throw new Error(t("workspaceSetup.errors.pendingRequired"));
let createdAgent: AgentSnapshotPayload | undefined;
const { workspaceId: _workspaceId, ...agentInput } = buildCreateAgentOptions({
composerState,
text,
attachments: [...wirePayload.attachments, ...(uploadedImageAttachments ?? [])],
images: imagePayload.images,
attachments: [...wirePayload.attachments, ...(imagePayload.attachments ?? [])],
workspaceDirectory: cwd,
workspaceId: "",
provider: composerState.selectedProvider,
@@ -1,16 +1,13 @@
import { Image } from "react-native";
import { Image } from "expo-image";
import type { ViewportSize } from "./geometry";
/** Resolves the image's natural size; rejects when the image cannot load or has no size. */
export function measureImage(uri: string): Promise<ViewportSize> {
return new Promise((resolve, reject) => {
Image.getSize(
uri,
(width, height) => {
if (width > 0 && height > 0) resolve({ width, height });
else reject(new Error("Image has no size"));
},
reject,
);
});
/**
* Resolves the image's natural size; rejects when the image cannot load or has no size. Decodes
* with Expo Image, the same decoder that draws the image: React Native's `Image.getSize` cannot
* decode SVG on Android or iOS.
*/
export async function measureImage(uri: string): Promise<ViewportSize> {
const { width, height } = await Image.loadAsync(uri);
if (width > 0 && height > 0) return { width, height };
throw new Error("Image has no size");
}
@@ -1,11 +1,15 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { Image, View, type StyleProp, type ViewStyle } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { Image } from "expo-image";
import { View, type StyleProp, type ViewStyle } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import type { ViewportFitOptions, ViewportSize } from "./geometry";
import { measureImage } from "./image-size";
import { ZoomableViewport } from "./index";
import type { ZoomableViewportAction } from "./types";
// Expo Image draws SVG as well as raster images; React Native's Image cannot draw SVG on native.
const ViewportImage = withUnistyles(Image);
interface ZoomableImageProps {
uri: string;
accessibilityLabel?: string;
@@ -77,12 +81,12 @@ export function ZoomableImage({
testID={testID}
wheelActivation={wheelActivation}
>
<Image
// Android fades a freshly decoded image in over 300ms; it appears with its toolbar instead.
fadeDuration={0}
<ViewportImage
// No transition, so the image appears together with its toolbar.
transition={null}
contentFit="contain"
onError={onError}
onLoad={handleLoad}
resizeMode="contain"
source={source}
style={styles.image}
testID={`${testID}-image`}

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