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
192 changed files with 15783 additions and 1358 deletions
+1
View File
@@ -60,6 +60,7 @@ sdk:
- "packages/client/**"
- "packages/highlight/**"
- "packages/protocol/**"
- "packages/workflows/**"
browser:
- "packages/server/src/server/agent/provider-snapshot-manager.ts"
+8
View File
@@ -128,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
+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
+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.
+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\"",
@@ -85,13 +85,10 @@ test.describe("Agent profiles in the model picker", () => {
await expectComposerMode(page, "Load test");
});
await test.step("the picker opens on the agent's provider with Profiles beside it", 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()).toBeFocused();
await expect(page.getByTestId("model-provider-mock")).toHaveAttribute(
"data-active",
"true",
);
await expect(page.getByTestId("model-picker-rail")).toHaveCount(0);
await expectModelRowSelected(page, { provider: "mock", modelId: "ten-second-stream" });
await expectPickerProfile(page, {
name: PROFILE.name,
@@ -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);
});
+40 -34
View File
@@ -248,41 +248,47 @@ async function readSettledFrameBorder(page: Page): Promise<string> {
});
}
test("the composer frame shows hover and focus", async ({ page }) => {
const agent = await seedMockAgentWorkspace({
repoPrefix: "composer-frame-focus-",
title: "Composer frame focus",
// `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();
}
});
try {
await openAgentRoute(page, agent);
const composer = composerLocator(page);
await expectComposerVisible(page);
await page.mouse.move(0, 0);
await blurComposerInput(page);
const rest = await readSettledFrameBorder(page);
await composer.hover();
const hover = await readSettledFrameBorder(page);
expect(hover).not.toBe(rest);
await composer.click();
await page.mouse.move(0, 0);
await expectComposerFocused(page);
const focus = await readSettledFrameBorder(page);
expect(focus).not.toBe(rest);
expect(focus).not.toBe(hover);
await composer.hover();
expect(await readSettledFrameBorder(page)).toBe(focus);
await page.mouse.move(0, 0);
await blurComposerInput(page);
expect(await readSettledFrameBorder(page)).toBe(rest);
} finally {
await agent.cleanup();
}
});
}
async function waitForAnimationFrames(page: Page, count: number): Promise<void> {
await page.evaluate(async (frames) => {
@@ -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 }) => {
@@ -28,7 +28,9 @@ import {
} 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";
@@ -315,15 +317,51 @@ test.describe("Cross-provider model search", () => {
await expectComposerFocused(page);
});
await test.step("the compact drawer puts Profiles in the Model accordion and lets all groups collapse", 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();
await expect(page.getByTestId("agent-controls-profiles")).toHaveCount(0);
await page.getByTestId("agent-controls-model").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 page.locator('[data-testid^="model-provider-section-"]').first().click();
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);
await page.getByTestId("model-picker-rail-profiles").click();
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 sheetProfileRow.click();
@@ -373,8 +411,193 @@ test.describe("Cross-provider model search", () => {
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: {
@@ -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);
});
});
@@ -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);
}
@@ -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
@@ -603,9 +603,12 @@ export function profilePickerRow(page: Page, name: string): Locator {
.filter({ hasText: name });
}
/** Desktop keeps profiles behind the rail's Profiles entry, beside the providers. */
/** Multi-provider desktop keeps profiles behind the rail; single-pane lists them inline. */
export async function openPickerProfiles(page: Page): Promise<void> {
await pickerViewport(page).getByTestId("model-picker-rail-profiles").click();
const rail = pickerViewport(page).getByTestId("model-picker-rail-profiles");
if (await rail.isVisible().catch(() => false)) {
await rail.click();
}
}
export async function expectPickerProfile(
@@ -624,7 +627,8 @@ export async function expectProfilesEditLink(page: Page): Promise<void> {
exact: true,
});
await expect(edit).toBeVisible();
await expect(edit).toHaveText("Edit");
await expect(edit).toHaveText("");
await expect(edit.locator("svg")).toBeVisible();
}
/** With no profiles, the Profiles entry offers to create one instead of listing any. */
@@ -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(
@@ -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 },
);
@@ -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);
},
@@ -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;
@@ -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);
@@ -14,6 +14,7 @@ import {
import { ModelProviderGlyph, useSelectedModelLabels } from "@/components/model-browser";
import { DesktopModelPicker, type ModelPickerActions } from "@/components/model-browser-panes";
import {
getSheetSearchFooterStyle,
MobileModelPageView,
SheetSearchDock,
useMobileModelPage,
@@ -313,6 +314,7 @@ function CompactCombinedModelSelector({
snapPoints={SHEET_SNAP_POINTS}
scrollable={false}
footer={footer}
footerContainerStyle={getSheetSearchFooterStyle()}
keyboard={keyboard}
contentStyle={styles.sheetBody}
testID="model-selector-sheet"
@@ -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],
@@ -134,17 +134,15 @@ describe("mobile model page", () => {
providerId: section.providerId,
status: section.status,
expanded: section.expanded,
shown: section.shown,
total: section.total,
}
: section,
),
).toEqual([
{ providerId: "claude", status: "ready", expanded: true, shown: 4, total: 19 },
{ providerId: "codex", status: "ready", expanded: false, shown: 2, total: 2 },
{ providerId: "opencode", status: "loading", expanded: false, shown: 0, total: 0 },
{ providerId: "pi", status: "ready", expanded: false, shown: 2, total: 4 },
{ providerId: "copilot", status: "error", expanded: false, shown: 0, total: 0 },
{ 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 },
]);
});
@@ -154,12 +152,26 @@ describe("mobile model page", () => {
expect(projection.sections[0]).toEqual({
kind: "profiles",
key: MODEL_PICKER_PROFILES_RAIL_KEY,
count: 2,
expanded: false,
});
expect(projection.sections.find((section) => section.expanded)?.key).toBe("claude");
});
it("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),
@@ -1,24 +1,27 @@
import {
createModelPickerState,
MODEL_PICKER_PROFILES_RAIL_KEY,
orderProvidersForPicker,
projectModelPicker,
type ModelPickerInput,
type ModelPickerListItem,
type ModelPickerPane,
type ModelPickerState,
} from "@/components/model-browser-panes-view";
import type { NavigableProfileRow } from "@/components/model-browser-view";
import { partitionProviderModels } from "@/provider-selection/model-curation";
import {
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: Profiles (when the surface offers them) and one section per provider,
* stacked as an accordion. At most one section is open at a time, and tapping the open section
* collapses it so every group can sit closed. A query replaces the accordion with ranked results
* across profiles and every provider, folded models included.
* 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 to the desktop picker's projection so both form factors order, fold, rank and
* search the same way.
* 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> {
@@ -26,6 +29,8 @@ export interface MobileModelPageInput<TProfile extends NavigableProfileRow = Nav
/** `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;
}
@@ -46,7 +51,6 @@ export type MobileModelPageAction =
export interface MobileProfilesSection {
kind: "profiles";
key: typeof MODEL_PICKER_PROFILES_RAIL_KEY;
count: number;
expanded: boolean;
}
@@ -56,11 +60,6 @@ export interface MobileProviderSection {
providerId: string;
label: string;
status: "ready" | "loading" | "error";
/** Models listed before the fold. */
shown: number;
total: number;
/** Some models sit behind a fold, so `shown` and `total` differ in meaning. */
folds: boolean;
expanded: boolean;
}
@@ -75,11 +74,11 @@ export type MobileModelPageProjection<TProfile extends NavigableProfileRow = Nav
| {
kind: "browse";
sections: MobileModelSection[];
/** False for a lone provider without profiles: its models are the page, with no header above them. */
/** 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 the list scrolls into view. */
/** The selected model's row in the open list, which opens already in view. */
selectedIndex: number | null;
}
| {
@@ -97,7 +96,7 @@ export function createMobileModelPageState<TProfile extends NavigableProfileRow>
): MobileModelPageState {
return {
query: "",
expandedKey: createModelPickerState(toPickerInput(input)).railKey,
expandedKey: resolveInitialExpandedKey(input),
foldOverrides: {},
};
}
@@ -122,42 +121,47 @@ export function reduceMobileModelPage(
}
}
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" };
const picker = projectModelPicker<TProfile>(toPickerInput(input), toPickerState(state));
const { pane } = picker;
if (pane.kind === "noMatches") return { kind: "noMatches", query: pane.query };
if (pane.kind === "search") {
return { kind: "search", profiles: pane.profiles, models: pane.models, items: pane.items };
}
const sections: MobileModelSection[] = [];
if (picker.layout === "twoPane") {
for (const item of picker.rail) {
if (item.kind === "profiles") {
sections.push({
kind: "profiles",
key: item.key,
count: item.count,
expanded: false,
});
} else {
const provider = input.providers.find((entry) => entry.id === item.providerId);
if (provider) sections.push(toProviderSection(provider, false));
}
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,
};
}
} else {
const provider = input.providers.find((entry) => entry.id === picker.railKey);
if (provider) sections.push(toProviderSection(provider, true));
}
const sections = buildSections(input);
const showSectionHeaders = sections.length > 1;
const expandedKey = showSectionHeaders && state.expandedKey === null ? null : picker.railKey;
const expandedKey = resolveExpandedKey(sections, state.expandedKey, showSectionHeaders);
for (const section of sections) {
section.expanded = section.key === expandedKey;
}
const body = expandedKey === null ? null : pane;
const body = expandedKey === null ? null : buildSectionBody(input, state, expandedKey);
return {
kind: "browse",
sections,
@@ -167,6 +171,81 @@ export function projectMobileModelPage<TProfile extends NavigableProfileRow>(
};
}
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>,
@@ -200,33 +279,17 @@ function toPickerState(state: MobileModelPageState): ModelPickerState {
};
}
function toProviderSection(
provider: ProviderSelectorProvider,
expanded: boolean,
): MobileProviderSection {
const base = {
kind: "provider" as const,
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,
expanded,
};
const selection = provider.modelSelection;
if (selection.kind !== "models") {
return {
...base,
status: selection.kind === "loading" ? "loading" : "error",
shown: 0,
total: 0,
folds: false,
};
}
const partition = partitionProviderModels(selection.rows, provider.shownModels, "");
return {
...base,
status: "ready",
shown: partition.primary.length,
total: selection.rows.length,
folds: partition.foldKind !== null,
status,
expanded: false,
};
}
+366 -290
View File
@@ -1,14 +1,14 @@
import { useCallback, useMemo, useRef, useState, type ReactNode } from "react";
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, ChevronUp, Layers, Pencil } from "lucide-react-native";
import { AlertTriangle, ChevronDown, Layers } from "lucide-react-native";
import type { AgentProfilePickerRow } from "@/agent-profiles";
import {
IndependentScrollBoundary,
MODEL_PICKER_ROW_HEIGHT,
ModelBrowserLoadingState,
ModelBrowserNoProviders,
ModelBrowserRow,
ModelBrowserSectionHeading,
ModelProviderGlyph,
ModelSearchNoMatches,
@@ -16,12 +16,14 @@ import {
} 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,
@@ -30,41 +32,39 @@ import {
type MobileModelPageInput,
type MobileModelPageProjection,
type MobileModelSection,
type MobileProfilesSection,
type MobileProviderSection,
} from "@/components/mobile-model-page-view";
import { SettingsCard } from "@/components/settings";
import { Button } from "@/components/ui/button";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { PressHighlight } from "@/components/ui/press-highlight";
import {
FlatList as SheetFlatList,
ScrollView as SheetScrollView,
} from "@/components/ui/scroll-view";
import { useInitialFlatListScroll } from "@/components/ui/scroll-reveal";
import { SearchField } from "@/components/ui/search-field";
import { useRevealActiveFlatListRow } from "@/components/ui/scroll-reveal";
import { isNative } from "@/constants/platform";
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 of one fixed height, about five rows, that
* scrolls on its own. Opening another section, unfolding older models or loading never moves the
* sections below it, so they stay where the thumb left them.
* 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 EXPANDED_A11Y_STATE = { expanded: true };
const SECTION_HEADER_HEIGHT = 44;
const ThemedAlertTriangle = withUnistyles(AlertTriangle);
const ThemedChevronDown = withUnistyles(ChevronDown);
const ThemedChevronUp = withUnistyles(ChevronUp);
const ThemedLayers = withUnistyles(Layers);
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
const foregroundMapping = (theme: Theme) => ({ color: theme.colors.foreground });
const foregroundMutedMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
// React Native Web blurs the focused input on every scroll in "on-drag" mode.
const KEYBOARD_DISMISS_MODE = isNative ? "on-drag" : "none";
@@ -86,6 +86,7 @@ export function useMobileModelPage(input: {
providers: readonly ProviderSelectorProvider[];
profiles?: readonly AgentProfilePickerRow[] | null;
canCreateProfile?: boolean;
showProfilesSection?: boolean;
selectedProvider: string;
selectedModel: string;
}): MobileModelPage {
@@ -93,12 +94,20 @@ export function useMobileModelPage(input: {
providers,
profiles = null,
canCreateProfile = false,
showProfilesSection = true,
selectedProvider,
selectedModel,
} = input;
const pageInput = useMemo<MobileModelPageInput<AgentProfilePickerRow>>(
() => ({ providers, profiles, canCreateProfile, selectedProvider, selectedModel }),
[canCreateProfile, profiles, providers, selectedModel, selectedProvider],
() => ({
providers,
profiles,
canCreateProfile,
showProfilesSection,
selectedProvider,
selectedModel,
}),
[canCreateProfile, profiles, providers, selectedModel, selectedProvider, showProfilesSection],
);
const inputRef = useRef(pageInput);
inputRef.current = pageInput;
@@ -150,6 +159,7 @@ export function SheetSearchDock({
placeholder={placeholder}
clearAccessibilityLabel={t("providerCatalog.clearSearch")}
fullWidth
variant="card"
testID={testID}
clearTestID={testID ? `${testID}-clear` : undefined}
/>
@@ -255,6 +265,21 @@ export function MobileModelPageView({
),
[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 (
@@ -288,12 +313,8 @@ export function MobileModelPageView({
);
}
if (!projection.showSectionHeaders) {
const section = projection.sections[0];
return (
<View style={styles.page} testID="mobile-model-page">
{section?.kind === "provider" ? (
<ExpandedProviderHeader section={section} serverId={serverId} />
) : null}
<SheetListCard header={singleProviderHeader} testID="mobile-model-page">
{projection.body ? (
<SectionBody
body={projection.body}
@@ -304,7 +325,7 @@ export function MobileModelPageView({
isRetryingProvider={actions.isRetryingProvider}
/>
) : null}
</View>
</SheetListCard>
);
}
return (
@@ -321,8 +342,8 @@ export function MobileModelPageView({
<AccordionSectionCard
key={section.key}
section={section}
body={projection.body}
selectedIndex={projection.selectedIndex}
body={section.expanded ? projection.body : null}
selectedIndex={section.expanded ? projection.selectedIndex : null}
serverId={serverId}
actions={actions}
renderItem={renderItem}
@@ -334,6 +355,92 @@ export function MobileModelPageView({
);
}
/**
* 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,
@@ -351,29 +458,27 @@ function AccordionSectionCard({
renderItem: ModelItemRenderer;
onToggle: (action: MobileModelPageAction) => void;
}) {
if (!section.expanded) {
return (
<SettingsCard>
{section.kind === "profiles" ? (
<CollapsedProfilesRow section={section} onToggle={onToggle} />
) : (
<CollapsedProviderRow section={section} serverId={serverId} onToggle={onToggle} />
)}
</SettingsCard>
);
}
const handleToggle = useCallback(
() => onToggle({ kind: "toggleSection", key: section.key }),
[onToggle, section.key],
);
return (
<SettingsCard>
{section.kind === "profiles" ? (
<ExpandedProfilesHeader
section={section}
<ProfilesSectionHeader
expanded={section.expanded}
onEditProfiles={actions.onEditProfiles}
onToggle={onToggle}
onToggle={handleToggle}
/>
) : (
<ExpandedProviderHeader section={section} serverId={serverId} onToggle={onToggle} />
<ProviderSectionHeader
section={section}
serverId={serverId}
collapsible
onToggle={handleToggle}
/>
)}
{body ? (
{section.expanded && body ? (
<SectionBody
body={body}
selectedIndex={selectedIndex}
@@ -389,12 +494,25 @@ function AccordionSectionCard({
/**
* 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.
* with the list, then the list scrolls inside it while its optional header stays fixed.
*/
function SheetListCard({ children }: { children: ReactNode }) {
function SheetListCard({
header,
children,
testID,
}: {
header?: ReactNode;
children: ReactNode;
testID?: string;
}) {
return (
<View style={styles.listCardPage}>
<SettingsCard shrink>{children}</SettingsCard>
<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>
);
}
@@ -409,269 +527,166 @@ function getSearchEntryKey(entry: SearchEntry): string {
return entry.key;
}
function useSectionSummary(section: MobileProviderSection): string {
const { t } = useTranslation();
if (section.folds) {
return t("modelSelector.shownOfTotal", { shown: section.shown, total: section.total });
}
return String(section.total);
function computeBoundedListHeight(itemCount: number): number {
return Math.min(
Math.max(itemCount, 1) * MODEL_PICKER_ROW_HEIGHT + LIST_CONTENT.paddingBottom,
MOBILE_EXPANDED_PROVIDER_HEIGHT,
);
}
function ExpandedSectionHeader({
/**
* One header component shared across collapsed and expanded states so toggling never shifts the
* icon, label, or chevron.
*/
function CollapsibleSectionHeader({
leading,
title,
summary,
expanded,
trailing,
onCollapse,
onToggle,
testID,
}: {
leading: ReactNode;
title: string;
summary: string | null;
expanded: boolean;
trailing?: ReactNode;
onCollapse?: () => void;
onToggle?: () => void;
testID: string;
}) {
const titleContent = (
<>
<View style={styles.glyph}>{leading}</View>
<Text style={styles.expandedTitle} numberOfLines={1}>
{title}
{summary !== null ? <Text style={styles.summary}>{` · ${summary}`}</Text> : null}
</Text>
</>
const accessibilityState = useMemo(() => ({ expanded }), [expanded]);
const webExpandedProps = useMemo(
() => (isWeb ? ({ "aria-expanded": expanded } as const) : null),
[expanded],
);
if (!onCollapse) {
return (
<View style={styles.expandedHeader} testID={testID}>
<View style={styles.expandedTrigger}>{titleContent}</View>
{trailing}
</View>
);
}
return (
<View style={styles.expandedHeader}>
<PressHighlight
onPress={onCollapse}
accessibilityRole="button"
accessibilityState={EXPANDED_A11Y_STATE}
style={styles.expandedTrigger}
testID={testID}
>
{titleContent}
</PressHighlight>
<View style={styles.expandedTrailing}>
{trailing}
<View style={styles.sectionHeader}>
{onToggle ? (
<PressHighlight
onPress={onCollapse}
hitSlop={8}
{...webExpandedProps}
onPress={onToggle}
accessibilityRole="button"
accessibilityLabel={title}
accessibilityState={EXPANDED_A11Y_STATE}
style={styles.collapseChevron}
>
<ThemedChevronUp size={ICON_SIZE.sm} uniProps={foregroundMutedMapping} />
</PressHighlight>
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 ExpandedProfilesHeader({
section,
function ProfilesSectionHeader({
expanded,
onEditProfiles,
onToggle,
}: {
section: MobileProfilesSection;
expanded: boolean;
onEditProfiles?: () => void;
onToggle: (action: MobileModelPageAction) => void;
onToggle: () => void;
}) {
const { t } = useTranslation();
const handleCollapse = useCallback(
() => onToggle({ kind: "toggleSection", key: section.key }),
[onToggle, section.key],
);
const leading = useMemo(
() => <ThemedLayers size={ICON_SIZE.sm} uniProps={foregroundMapping} />,
[],
);
const trailing = useMemo(
() =>
onEditProfiles ? (
<Button
variant="ghost"
size="sm"
leftIcon={Pencil}
onPress={onEditProfiles}
accessibilityLabel={t("modelSelector.editProfilesLabel")}
testID="model-profiles-edit"
/>
) : null,
[onEditProfiles, t],
);
return (
<ExpandedSectionHeader
leading={leading}
title={t("modelSelector.profiles")}
summary={String(section.count)}
trailing={trailing}
onCollapse={handleCollapse}
testID="model-profiles-section"
/>
);
}
function CollapsedProfilesRow({
section,
onToggle,
}: {
section: MobileProfilesSection;
onToggle: (action: MobileModelPageAction) => void;
}) {
const { t } = useTranslation();
const handlePress = useCallback(
() => onToggle({ kind: "toggleSection", key: section.key }),
[onToggle, section.key],
);
const leadingSlot = useMemo(
() => <ThemedLayers size={ICON_SIZE.sm} uniProps={foregroundMutedMapping} />,
[],
);
const trailingSlot = useMemo(
() => (
<View style={styles.collapsedTrailing}>
<Text style={styles.summary}>{section.count}</Text>
<ThemedChevronDown size={ICON_SIZE.sm} uniProps={foregroundMutedMapping} />
</View>
),
[section.count],
);
return (
<ModelBrowserRow
label={t("modelSelector.profiles")}
leadingSlot={leadingSlot}
trailingSlot={trailingSlot}
spacing="provider"
onPress={handlePress}
testID="model-picker-rail-profiles"
/>
);
}
function ExpandedProviderHeader({
section,
serverId,
onToggle,
}: {
section: MobileProviderSection;
serverId: string | null;
onToggle?: (action: MobileModelPageAction) => void;
}) {
const summary = useSectionSummary(section);
const handleCollapse = useCallback(
() => onToggle?.({ kind: "toggleSection", key: section.key }),
[onToggle, section.key],
);
const leading = useMemo(
() => (
<ModelProviderGlyph
provider={section.providerId}
serverId={serverId}
size={ICON_SIZE.sm}
tone="foreground"
/>
),
[section.providerId, serverId],
);
const trailing = useMemo(
() =>
serverId ? (
<CustomizeProviderButton
serverId={serverId}
providerId={section.providerId}
providerLabel={section.label}
/>
) : null,
[section.label, section.providerId, serverId],
() => (expanded && onEditProfiles ? <EditProfilesButton onPress={onEditProfiles} /> : null),
[expanded, onEditProfiles],
);
return (
<ExpandedSectionHeader
<CollapsibleSectionHeader
leading={leading}
title={section.label}
summary={section.status === "ready" ? summary : null}
title={t("modelSelector.profiles")}
expanded={expanded}
trailing={trailing}
onCollapse={onToggle ? handleCollapse : undefined}
testID={`model-provider-section-${section.providerId}`}
onToggle={onToggle}
testID={expanded ? "model-profiles-section" : "model-picker-rail-profiles"}
/>
);
}
function CollapsedProviderRow({
function ProviderSectionHeader({
section,
serverId,
collapsible,
onToggle,
}: {
section: MobileProviderSection;
serverId: string | null;
onToggle: (action: MobileModelPageAction) => void;
collapsible: boolean;
onToggle?: () => void;
}) {
const summary = useSectionSummary(section);
const handlePress = useCallback(
() => onToggle({ kind: "toggleSection", key: section.key }),
[onToggle, section.key],
);
const leadingSlot = useMemo(
const leading = useMemo(
() => (
<ModelProviderGlyph provider={section.providerId} serverId={serverId} size={ICON_SIZE.sm} />
),
[section.providerId, serverId],
);
const trailingSlot = useMemo(
() => (
<View style={styles.collapsedTrailing}>
<CollapsedStatus section={section} summary={summary} />
<ThemedChevronDown size={ICON_SIZE.sm} uniProps={foregroundMutedMapping} />
</View>
),
[section, summary],
);
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 (
<ModelBrowserRow
label={section.label}
leadingSlot={leadingSlot}
trailingSlot={trailingSlot}
spacing="provider"
onPress={handlePress}
testID={`model-provider-${section.providerId}`}
<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}`
}
/>
);
}
function CollapsedStatus({
section,
summary,
}: {
section: MobileProviderSection;
summary: string;
}) {
if (section.status === "loading") {
return (
<View style={styles.spinner}>
<ThemedLoadingSpinner size="small" uniProps={foregroundMutedMapping} />
</View>
);
}
if (section.status === "error") {
return <ThemedAlertTriangle size={ICON_SIZE.sm} uniProps={foregroundMutedMapping} />;
}
return <Text style={styles.summary}>{summary}</Text>;
}
type ModelItemRenderer = ({
item,
}: {
item: ModelPickerListItem<AgentProfilePickerRow>;
}) => React.ReactElement;
}) => ReactElement;
function SectionBody({
body,
@@ -689,7 +704,7 @@ function SectionBody({
onRetryProvider: ModelPickerActions["onRetryProvider"];
isRetryingProvider: boolean;
}) {
const frameStyle = fill ? styles.page : styles.fixedViewport;
const frameStyle = fill ? styles.fillState : styles.fixedViewport;
if (body.kind === "providerLoading") {
return (
<View style={[frameStyle, styles.centered]}>
@@ -710,58 +725,91 @@ function SectionBody({
);
}
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 at its top or at the selected model.
// 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>;
}
/** Opens with the selected model in view, such as an older model behind the opened fold. */
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);
// Waits for the first visible rows, so a selection already in view never scrolls the list.
const reveal = useRevealActiveFlatListRow({
const { initialScrollIndex, contentOffset } = useInitialFlatListScroll({
listRef,
selectedIndex,
itemCount: items.length,
activeIndex: selectedIndex,
waitForViewable: true,
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 (
<FlatList
<ListComponent
ref={listRef}
data={items}
renderItem={renderItem}
keyExtractor={getItemKey}
style={fill ? styles.page : styles.fixedViewport}
getItemLayout={getModelItemLayout}
initialScrollIndex={initialScrollIndex}
contentOffset={contentOffset}
style={boxStyle}
contentContainerStyle={LIST_CONTENT}
keyboardShouldPersistTaps="handled"
keyboardDismissMode={KEYBOARD_DISMISS_MODE}
showsVerticalScrollIndicator
nestedScrollEnabled
onScrollToIndexFailed={reveal.onScrollToIndexFailed}
onViewableItemsChanged={reveal.onViewableItemsChanged}
viewabilityConfig={reveal.viewabilityConfig}
onContentSizeChange={reveal.onContentSizeChange}
onLayout={reveal.onLayout}
testID="compact-model-list"
nestedScrollEnabled={!fill}
testID={testID}
/>
);
}
@@ -778,62 +826,77 @@ const styles = StyleSheet.create((theme) => ({
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],
},
expandedHeader: {
minHeight: 44,
flexDirection: "row",
alignItems: "center",
// The model rows' leading rail (ModelBrowserRow), so the section glyph sits above theirs.
paddingLeft: isNative ? theme.spacing[6] : theme.spacing[3],
paddingRight: isNative ? theme.spacing[6] : theme.spacing[3],
},
expandedTrigger: {
flex: 1,
minWidth: 0,
minHeight: 44,
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] },
},
expandedTrailing: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[1],
sectionHeaderPress: {
...StyleSheet.absoluteFill,
},
collapseChevron: {
minWidth: 24,
minHeight: 44,
alignItems: "center",
justifyContent: "center",
sectionHeaderPressed: {
backgroundColor: theme.colors.surface2,
},
passThrough: {
pointerEvents: "none",
},
boxNone: {
pointerEvents: "box-none",
},
glyph: {
width: 16,
alignItems: "center",
justifyContent: "center",
},
expandedTitle: {
sectionTitleWrap: {
flex: 1,
minWidth: 0,
},
sectionTitle: {
fontSize: theme.fontSize.base,
fontWeight: theme.fontWeight.medium,
fontWeight: theme.fontWeight.normal,
color: theme.colors.foreground,
},
summary: {
fontSize: theme.fontSize.sm,
fontWeight: theme.fontWeight.normal,
color: theme.colors.foregroundMuted,
fontVariant: ["tabular-nums"],
},
collapsedTrailing: {
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 }],
},
@@ -841,6 +904,9 @@ const styles = StyleSheet.create((theme) => ({
height: MOBILE_EXPANDED_PROVIDER_HEIGHT,
flexGrow: 0,
},
boundedViewport: {
flexGrow: 0,
},
centered: {
alignItems: "center",
justifyContent: "center",
@@ -849,4 +915,14 @@ const styles = StyleSheet.create((theme) => ({
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;
}
@@ -152,20 +152,84 @@ describe("model picker layout", () => {
expect(resolveModelPickerLayout(input({ profiles: null }))).toBe("twoPane");
});
it("uses two panes for one provider with profiles", () => {
expect(resolveModelPickerLayout(input({ providers: [claude] }))).toBe("twoPane");
});
it("keeps two panes for one provider on a surface that offers profiles but has none", () => {
expect(resolveModelPickerLayout(input({ providers: [claude], profiles: [] }))).toBe("twoPane");
});
it("drops the rail for one provider on a surface without profiles", () => {
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);
@@ -198,12 +262,6 @@ describe("model picker rail", () => {
});
});
it("counts profiles and the models each provider shows first", () => {
const { projection } = open(input());
const counts = Object.fromEntries(projection.rail.map((item) => [item.key, item.count]));
expect(counts).toMatchObject({ profiles: 2, claude: 4, codex: 2, pi: 2 });
});
it("omits the Profiles row when the surface shows no profiles", () => {
const { projection } = open(input({ profiles: null }));
expect(projection.rail.map((item) => item.key)).not.toContain(MODEL_PICKER_PROFILES_RAIL_KEY);
@@ -244,9 +302,6 @@ describe("model picker provider pane", () => {
kind: "provider",
providerId: "claude",
label: "Claude",
shown: 4,
total: 19,
foldKind: "older",
});
expect(modelIds(projection)).toEqual(claudeCurrent);
expect(projection.pane.items.at(-1)).toMatchObject({
@@ -286,7 +341,6 @@ describe("model picker provider pane", () => {
const state = reduceModelPicker(open(pickerInput).state, { kind: "selectRail", railKey: "pi" });
const projection = projectModelPicker(pickerInput, state);
expect(modelIds(projection)).toEqual(["anthropic/opus", "openai/gpt-5"]);
expect(projection.pane).toMatchObject({ shown: 2, total: 4, foldKind: "all" });
expect(projection.pane.items.at(-1)).toMatchObject({ kind: "fold", foldKind: "all", count: 2 });
});
@@ -297,7 +351,7 @@ describe("model picker provider pane", () => {
railKey: "codex",
});
const projection = projectModelPicker(pickerInput, state);
expect(projection.pane).toMatchObject({ kind: "provider", foldKind: null });
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",
@@ -65,14 +65,13 @@ export type ModelPickerAction =
| { kind: "toggleFold"; providerId: string; expanded: boolean };
export type ModelPickerRailItem =
| { kind: "profiles"; key: typeof MODEL_PICKER_PROFILES_RAIL_KEY; count: number }
| { kind: "profiles"; key: typeof MODEL_PICKER_PROFILES_RAIL_KEY }
| {
kind: "provider";
key: string;
providerId: string;
label: string;
status: "ready" | "loading" | "error";
count: number;
/** The first errored provider after ready ones; the rail draws a divider above it. */
startsErrorGroup: boolean;
};
@@ -101,13 +100,29 @@ export type ModelPickerPane<TProfile extends NavigableProfileRow = NavigableProf
kind: "provider";
providerId: string;
label: string;
shown: number;
total: number;
foldKind: ModelFoldKind;
/** 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: "providerLoading"; providerId: string; label: string; items: [] }
| { kind: "providerError"; providerId: string; label: string; message: string; items: [] }
| { kind: "profiles"; items: ModelPickerListItem<TProfile>[] }
| {
kind: "search";
@@ -138,22 +153,31 @@ export function modelPickerFoldKey(providerId: string): string {
return `fold:${providerId}`;
}
/** Two panes whenever there is a rail to choose from: several providers, or a surface that offers
* profiles (even none yet, so the rail keeps the create-profile entry). */
/** 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 || input.profiles !== null ? "twoPane" : "singlePane";
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, folded ones included.
* 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 rowCount = provider ? countAllRows(provider) : 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 + rowCount * LIST_ROW_HEIGHT,
SINGLE_PANE_CHROME_HEIGHT + (providerRows + profileRows) * LIST_ROW_HEIGHT,
SINGLE_PANE_MIN_HEIGHT,
TWO_PANE_HEIGHT,
);
@@ -198,7 +222,7 @@ export function projectModelPicker<TProfile extends NavigableProfileRow>(
const normalizedQuery = normalizeQuery(state.query);
const pane = normalizedQuery
? buildSearchPane(input, normalizedQuery, state.query.trim())
: buildBrowsePane(input, state, railKey);
: buildBrowsePane(input, state, layout, railKey);
const focus: ModelPickerFocus =
layout === "twoPane" && !normalizedQuery && state.focus === "rail" ? "rail" : "list";
return {
@@ -357,23 +381,31 @@ function resolveRailKey(
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 providerItems = input.providers.map((provider) => buildProviderRailItem(input, provider));
const working = providerItems.filter((item) => item.status !== "error");
const errored = providerItems.filter((item) => item.status === "error");
const firstErrored = errored[0];
if (firstErrored && working.length > 0) firstErrored.startsErrorGroup = true;
const ordered = [...working, ...errored];
if (input.profiles === null) return ordered;
return [
{ kind: "profiles", key: MODEL_PICKER_PROFILES_RAIL_KEY, count: input.profiles.length },
...ordered,
];
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(
input: ModelPickerInput,
provider: ProviderSelectorProvider,
startsErrorGroup: boolean,
): Extract<ModelPickerRailItem, { kind: "provider" }> {
const selection = provider.modelSelection;
const base = {
@@ -381,16 +413,17 @@ function buildProviderRailItem(
key: provider.id,
providerId: provider.id,
label: provider.label,
startsErrorGroup: false,
startsErrorGroup,
};
if (selection.kind === "loading") return { ...base, status: "loading", count: 0 };
if (selection.kind === "error") return { ...base, status: "error", count: 0 };
return { ...base, status: "ready", count: partitionFor(input, provider).primary.length };
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) {
@@ -398,9 +431,19 @@ function buildBrowsePane<TProfile extends NavigableProfileRow>(
}
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, items: [] };
return {
kind: "providerLoading",
providerId: provider.id,
label: provider.label,
profiles: singlePaneProfiles,
items: singlePaneProfiles,
};
}
if (selection.kind === "error") {
return {
@@ -408,18 +451,45 @@ function buildBrowsePane<TProfile extends NavigableProfileRow>(
providerId: provider.id,
label: provider.label,
message: selection.message,
items: [],
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,
shown: partition.primary.length,
total: selection.rows.length,
foldKind: partition.foldKind,
items: buildProviderItems(provider.id, partition, state),
profiles: [],
models: providerModels,
items: providerModels,
};
}
@@ -5,6 +5,7 @@ import {
useReducer,
useRef,
useState,
type ReactElement,
type ReactNode,
type RefObject,
} from "react";
@@ -33,6 +34,8 @@ import {
type SheetKeyboard,
} from "@/components/adaptive-modal-sheet";
import {
MODEL_PICKER_HEADING_HEIGHT,
MODEL_PICKER_ROW_HEIGHT,
ModelBrowserLoadingState,
ModelBrowserRow,
ModelBrowserSectionHeading,
@@ -60,7 +63,11 @@ import { groupProfilesByProviderModel } from "@/components/model-browser-view";
import { Button } from "@/components/ui/button";
import { Combobox, type ComboboxDesktopPlacement } from "@/components/ui/combobox";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { useRevealActiveFlatListRow, useRevealActiveItem } from "@/components/ui/scroll-reveal";
import {
useInitialFlatListScroll,
useRevealActiveFlatListRow,
useRevealActiveItem,
} from "@/components/ui/scroll-reveal";
import type { EditingTextInputHandle } from "@/components/ui/text-input";
import type { KeyboardInputEvent } from "@/keyboard";
import { useCurrentOverlayLayer } from "@/lib/overlay-root";
@@ -165,6 +172,7 @@ export function DesktopModelPicker({
>
<ModelPickerBody
input={input}
pickerHeight={height}
serverId={serverId}
keyboardHandlerRef={keyboardHandlerRef}
{...actions}
@@ -176,11 +184,13 @@ export function DesktopModelPicker({
/** Mounted only while the popover is open, so every open starts from the current selection. */
function ModelPickerBody({
input,
pickerHeight,
serverId,
keyboardHandlerRef,
...actions
}: ModelPickerActions & {
input: ModelPickerInput<AgentProfilePickerRow>;
pickerHeight: number;
serverId: string | null;
keyboardHandlerRef: RefObject<KeyboardHandler | null>;
}) {
@@ -308,6 +318,7 @@ function ModelPickerBody({
body = (
<ListPane
projection={projection}
pickerHeight={pickerHeight}
query={state.query}
serverId={serverId}
input={input}
@@ -322,6 +333,7 @@ function ModelPickerBody({
<Rail projection={projection} serverId={serverId} onSelectRail={handleSelectRail} />
<ListPane
projection={projection}
pickerHeight={pickerHeight}
query={state.query}
serverId={serverId}
input={input}
@@ -444,6 +456,9 @@ function RailRow({
);
}
const INLINE_HEADER_HEIGHT = 56;
const PANE_HEADER_HEIGHT = 36;
function RailRowStatus({ item }: { item: ModelPickerRailItem }) {
if (item.kind === "provider" && item.status === "loading") {
return (
@@ -455,14 +470,30 @@ function RailRowStatus({ item }: { item: ModelPickerRailItem }) {
if (item.kind === "provider" && item.status === "error") {
return <ThemedAlertTriangle size={ICON_SIZE.xs} uniProps={foregroundMutedMapping} />;
}
return <Text style={styles.count}>{item.count}</Text>;
return null;
}
type ListEntry =
| { kind: "heading"; key: string; title: string }
| {
kind: "heading";
key: string;
title: string;
action?:
| { kind: "editProfiles" }
| { kind: "customizeProvider"; providerId: string; providerLabel: string };
}
| { kind: "item"; key: string; item: ModelPickerListItem<AgentProfilePickerRow> };
/** Search results carry section headings between their groups; every other pane is a flat list. */
function paneHasInlineProfiles(pane: ModelPickerPane<AgentProfilePickerRow>): boolean {
return (
(pane.kind === "provider" ||
pane.kind === "providerLoading" ||
pane.kind === "providerError") &&
pane.profiles.length > 0
);
}
/** Search results and single-pane profiles+models carry section headings; every other pane is flat. */
function useListEntries(pane: ModelPickerPane<AgentProfilePickerRow>): ListEntry[] {
const { t } = useTranslation();
return useMemo(() => {
@@ -471,6 +502,35 @@ function useListEntries(pane: ModelPickerPane<AgentProfilePickerRow>): ListEntry
key: item.key,
item,
});
if (paneHasInlineProfiles(pane)) {
if (
pane.kind !== "provider" &&
pane.kind !== "providerLoading" &&
pane.kind !== "providerError"
) {
return [];
}
return [
{
kind: "heading",
key: "heading:profiles",
title: t("modelSelector.profiles"),
action: { kind: "editProfiles" },
},
...pane.profiles.map(toEntry),
{
kind: "heading",
key: `heading:provider:${pane.providerId}`,
title: pane.label,
action: {
kind: "customizeProvider",
providerId: pane.providerId,
providerLabel: pane.label,
},
},
...(pane.kind === "provider" ? pane.models.map(toEntry) : []),
];
}
if (pane.kind !== "search") return pane.items.map(toEntry);
const entries: ListEntry[] = [];
if (pane.profiles.length > 0) {
@@ -489,6 +549,22 @@ function useListEntries(pane: ModelPickerPane<AgentProfilePickerRow>): ListEntry
}, [pane, t]);
}
function computeEntryLayout(entries: readonly ListEntry[]): {
lengths: number[];
offsets: number[];
} {
const lengths: number[] = [];
const offsets: number[] = [];
let offset = 0;
for (const entry of entries) {
const length = entry.kind === "heading" ? MODEL_PICKER_HEADING_HEIGHT : MODEL_PICKER_ROW_HEIGHT;
lengths.push(length);
offsets.push(offset);
offset += length;
}
return { lengths, offsets };
}
/** The first row reveals as the list top, so a section heading above it stays in view. */
function resolveRevealTarget(entries: readonly ListEntry[], activeKey: string | null) {
if (!activeKey) return null;
@@ -501,8 +577,15 @@ function getListEntryKey(entry: ListEntry): string {
return entry.key;
}
function paneShowsHeader(pane: ModelPickerPane<AgentProfilePickerRow>): boolean {
if (pane.kind === "search" || pane.kind === "noMatches") return false;
if (paneHasInlineProfiles(pane)) return false;
return true;
}
function ListPane({
projection,
pickerHeight,
query,
input,
serverId,
@@ -511,6 +594,7 @@ function ListPane({
actions,
}: {
projection: ModelPickerProjection<AgentProfilePickerRow>;
pickerHeight: number;
/** Each query is a new result list, which opens at its top. */
query: string;
input: ModelPickerInput<AgentProfilePickerRow>;
@@ -521,23 +605,41 @@ function ListPane({
}) {
const { pane, activeKey } = projection;
const entries = useListEntries(pane);
const listRef = useRef<FlatList<ListEntry>>(null);
const reveal = useRevealActiveFlatListRow({
listRef,
itemCount: entries.length,
activeIndex: resolveRevealTarget(entries, activeKey),
listKey: `${pane.kind}:${projection.railKey}:${query}`,
});
const profiledLookup = useMemo(
() => groupProfilesByProviderModel(input.profiles ?? []),
[input.profiles],
);
const inSearch = pane.kind === "search";
const { selectedProvider, selectedModel } = input;
const hasPaneHeader = paneShowsHeader(pane);
const visibleCount = Math.max(
1,
Math.floor(
(pickerHeight - INLINE_HEADER_HEIGHT - (hasPaneHeader ? PANE_HEADER_HEIGHT : 0)) /
MODEL_PICKER_ROW_HEIGHT,
),
);
// Keyed per browse pane so switching providers in the rail opens at the new provider's initial
// scroll position instead of flashing the previous provider's scroll offset for a frame.
const paneListKey = inSearch ? "search" : `${pane.kind}:${projection.railKey}`;
const renderEntry = useCallback(
({ item: entry }: { item: ListEntry }) => {
if (entry.kind === "heading") return <ModelBrowserSectionHeading title={entry.title} />;
if (entry.kind === "heading") {
let headingAction: ReactNode = null;
if (entry.action?.kind === "editProfiles" && actions.onEditProfiles) {
headingAction = <EditProfilesButton onPress={actions.onEditProfiles} />;
} else if (entry.action?.kind === "customizeProvider" && serverId) {
headingAction = (
<CustomizeProviderButton
serverId={serverId}
providerId={entry.action.providerId}
providerLabel={entry.action.providerLabel}
/>
);
}
return <ModelBrowserSectionHeading title={entry.title} action={headingAction} />;
}
const { item } = entry;
return (
<ModelPickerItemRow
@@ -570,33 +672,102 @@ function ListPane({
],
);
const inlineStateFooter = useMemo(
() => (entries.length > 0 ? <PaneState pane={pane} actions={actions} /> : null),
[actions, entries.length, pane],
);
return (
<View style={styles.listPane} testID="model-picker-list">
<ListPaneHeader pane={pane} serverId={serverId} onEditProfiles={actions.onEditProfiles} />
<PaneState pane={pane} actions={actions} />
{entries.length > 0 ? (
<FlatList
ref={listRef}
data={entries}
extraData={activeKey}
renderItem={renderEntry}
keyExtractor={getListEntryKey}
onScrollToIndexFailed={reveal.onScrollToIndexFailed}
onViewableItemsChanged={reveal.onViewableItemsChanged}
viewabilityConfig={reveal.viewabilityConfig}
onContentSizeChange={reveal.onContentSizeChange}
onLayout={reveal.onLayout}
style={styles.scroll}
contentContainerStyle={styles.listContent}
keyboardShouldPersistTaps="handled"
showsVerticalScrollIndicator={false}
testID="model-picker-model-list"
<PaneFlatList
key={paneListKey}
entries={entries}
activeKey={activeKey}
listKey={inSearch ? query : paneListKey}
visibleCount={visibleCount}
renderEntry={renderEntry}
listFooter={inlineStateFooter}
/>
) : null}
) : (
<PaneState pane={pane} actions={actions} />
)}
</View>
);
}
function PaneFlatList({
entries,
activeKey,
listKey,
visibleCount,
renderEntry,
listFooter,
}: {
entries: ListEntry[];
activeKey: string | null;
listKey: string;
visibleCount: number;
renderEntry: ({ item }: { item: ListEntry }) => React.ReactElement;
listFooter?: ReactElement | null;
}) {
const listRef = useRef<FlatList<ListEntry>>(null);
const entryLayout = useMemo(() => computeEntryLayout(entries), [entries]);
const getItemLayout = useCallback(
(_data: ArrayLike<ListEntry> | null | undefined, index: number) => ({
length: entryLayout.lengths[index] ?? MODEL_PICKER_ROW_HEIGHT,
offset: entryLayout.offsets[index] ?? index * MODEL_PICKER_ROW_HEIGHT,
index,
}),
[entryLayout],
);
const offsetForIndex = useCallback(
(index: number) => entryLayout.offsets[index] ?? index * MODEL_PICKER_ROW_HEIGHT,
[entryLayout],
);
const revealTarget = resolveRevealTarget(entries, activeKey);
const { initialScrollIndex, contentOffset, initialVisibleRange } = useInitialFlatListScroll({
listRef,
selectedIndex: typeof revealTarget === "number" ? revealTarget : null,
itemCount: entries.length,
visibleCount,
offsetForIndex,
});
const reveal = useRevealActiveFlatListRow({
listRef,
itemCount: entries.length,
activeIndex: revealTarget,
initialVisibleRange,
listKey,
});
return (
<FlatList
ref={listRef}
data={entries}
extraData={activeKey}
renderItem={renderEntry}
keyExtractor={getListEntryKey}
getItemLayout={getItemLayout}
initialScrollIndex={initialScrollIndex}
contentOffset={contentOffset}
ListFooterComponent={listFooter}
onScrollToIndexFailed={reveal.onScrollToIndexFailed}
onViewableItemsChanged={reveal.onViewableItemsChanged}
viewabilityConfig={reveal.viewabilityConfig}
onContentSizeChange={reveal.onContentSizeChange}
onLayout={reveal.onLayout}
style={styles.scroll}
contentContainerStyle={styles.listContent}
keyboardShouldPersistTaps="handled"
showsVerticalScrollIndicator={false}
testID="model-picker-model-list"
/>
);
}
function ListPaneHeader({
pane,
serverId,
@@ -607,36 +778,22 @@ function ListPaneHeader({
onEditProfiles?: () => void;
}) {
const { t } = useTranslation();
if (pane.kind === "search" || pane.kind === "noMatches") return null;
if (!paneShowsHeader(pane)) return null;
if (pane.kind === "profiles") {
return (
<View style={styles.paneHeader}>
<Text style={styles.paneTitle} numberOfLines={1}>
{t("modelSelector.profiles")}
</Text>
{onEditProfiles ? (
<Button
variant="ghost"
size="sm"
onPress={onEditProfiles}
accessibilityLabel={t("modelSelector.editProfilesLabel")}
testID="model-profiles-edit"
>
{t("modelSelector.editProfiles")}
</Button>
) : null}
{onEditProfiles ? <EditProfilesButton onPress={onEditProfiles} /> : null}
</View>
);
}
const summary =
pane.kind === "provider" && pane.foldKind !== null
? t("modelSelector.shownOfTotal", { shown: pane.shown, total: pane.total })
: null;
if (pane.kind === "search" || pane.kind === "noMatches") return null;
return (
<View style={styles.paneHeader}>
<Text style={styles.paneTitle} numberOfLines={1}>
{pane.label}
{summary ? <Text style={styles.paneSummary}>{` · ${summary}`}</Text> : null}
</Text>
{serverId ? (
<CustomizeProviderButton
@@ -649,6 +806,20 @@ function ListPaneHeader({
);
}
export function EditProfilesButton({ onPress }: { onPress: () => void }) {
const { t } = useTranslation();
return (
<Button
variant="ghost"
size="sm"
leftIcon={Pencil}
onPress={onPress}
accessibilityLabel={t("modelSelector.editProfilesLabel")}
testID="model-profiles-edit"
/>
);
}
export function CustomizeProviderButton({
serverId,
providerId,
@@ -861,11 +1032,6 @@ const styles = StyleSheet.create((theme) => ({
railSpinner: {
transform: [{ scale: 0.7 }],
},
count: {
fontSize: theme.fontSize.sm,
color: theme.colors.foregroundMuted,
fontVariant: ["tabular-nums"],
},
listPane: {
flex: 1,
minWidth: 0,
@@ -878,7 +1044,7 @@ const styles = StyleSheet.create((theme) => ({
paddingBottom: theme.spacing[2],
},
paneHeader: {
height: 36,
height: PANE_HEADER_HEIGHT,
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
@@ -892,8 +1058,4 @@ const styles = StyleSheet.create((theme) => ({
fontWeight: theme.fontWeight.medium,
color: theme.colors.foreground,
},
paneSummary: {
fontWeight: theme.fontWeight.normal,
color: theme.colors.foregroundMuted,
},
}));
+15 -12
View File
@@ -101,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);
@@ -2036,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",
@@ -2067,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,
},
@@ -2088,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,
@@ -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]);
}
+3 -15
View File
@@ -56,25 +56,13 @@ interface AppSettingsRowProps extends Omit<SettingsRowProps, "hint">, AppRowExtr
hint?: ReactNode;
}
/** Lets a card and its rows shrink below their content, so a list inside can scroll. */
const SHRINK = { flexShrink: 1, minHeight: 0 } as const;
export function SettingsCard({
children,
testID,
shrink = false,
}: {
children: ReactNode;
testID?: string;
/** The card shrinks to fit a parent with a bounded height, and a list inside it scrolls. */
shrink?: boolean;
}) {
export function SettingsCard({ children, testID }: { children: ReactNode; testID?: string }) {
return (
<View style={[settingsStyles.card, shrink && SHRINK]} testID={testID}>
<View style={settingsStyles.card} testID={testID}>
{Children.toArray(children).map((child, index) => (
<View
key={isValidElement(child) ? child.key : index}
style={[index ? settingsStyles.rowBorder : undefined, shrink && SHRINK]}
style={index ? settingsStyles.rowBorder : undefined}
>
{child}
</View>
@@ -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"),
);
});
});
@@ -141,6 +141,7 @@ export function SettingsRowHeader({
hovered={hovered}
summary={summary}
summaryLeading={summaryLeading}
titleStyle={layout.title}
/>
{external || disabled ? null : (
<View style={chevronStyle} {...HIDDEN_FROM_ASSISTIVE_TECH}>
@@ -167,14 +168,17 @@ function RowTrailing({
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. */}
@@ -183,7 +187,7 @@ function RowTrailing({
<View style={styles.summaryLeading}>{summaryLeading}</View>
) : null}
{!external && summary ? (
<Text style={styles.summary} numberOfLines={1}>
<Text style={summaryStyle} numberOfLines={1}>
{summary}
</Text>
) : null}
@@ -315,7 +319,6 @@ const styles = StyleSheet.create((theme) => ({
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,
+23 -5
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,
@@ -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({
@@ -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%",
},
@@ -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`}
+8 -3
View File
@@ -191,7 +191,11 @@ interface FakeSendCall {
}
function createFakeSendClient(
options: { rejection?: Error; beforeRejection?: (call: FakeSendCall) => void } = {},
options: {
rejection?: Error;
beforeRejection?: (call: FakeSendCall) => void;
uploadedImageAttachments?: boolean;
} = {},
): ComposerSendClient & {
calls: FakeSendCall[];
uploadCalls: Array<{ fileName: string; mimeType: string; bytes: Uint8Array }>;
@@ -201,6 +205,9 @@ function createFakeSendClient(
return {
calls,
uploadCalls,
getLastServerInfoMessage: () => ({
features: { uploadedImageAttachments: options.uploadedImageAttachments ?? true },
}),
sendAgentMessage: async (agentId, text, opts) => {
const call = { agentId, text, options: opts };
calls.push(call);
@@ -1097,7 +1104,6 @@ describe("file upload preparation", () => {
const sent: string[] = [];
const upload = uploadFileAttachments({
client: {
sendAgentMessage: async () => {},
uploadFile: async (file) => {
sent.push(file.fileName);
expect(file.bytes).toEqual(new Uint8Array([1, 2]));
@@ -1137,7 +1143,6 @@ describe("file upload preparation", () => {
await expect(
uploadFileAttachments({
client: {
sendAgentMessage: async () => {},
uploadFile: async () => {
sends++;
throw new Error("unexpected send");
+11 -6
View File
@@ -1,5 +1,5 @@
import type { SelectedFile } from "@/attachments/selected-file";
import { uploadImageAttachments } from "@/attachments/service";
import { prepareImageAttachmentsForSend } from "@/attachments/service";
import { FILE_UPLOAD_MAX_BYTES } from "@/attachments/upload-limit";
import type {
ActiveTurnBehavior,
@@ -65,6 +65,7 @@ export interface ComposerSendClient {
file: UploadedFileAttachment | null;
error: string | null;
}>;
getLastServerInfoMessage: () => { features?: { uploadedImageAttachments?: boolean } } | null;
}
export interface ComposerCancelClient {
@@ -121,7 +122,7 @@ export async function pickAndPersistImages(input: {
}
export async function uploadFileAttachments(input: {
client: ComposerSendClient;
client: Pick<ComposerSendClient, "uploadFile">;
files: SelectedFile[];
}): Promise<Extract<ComposerAttachment, { kind: "file" }>[]> {
const result: Extract<ComposerAttachment, { kind: "file" }>[] = [];
@@ -213,13 +214,17 @@ export async function dispatchComposerAgentMessage(
});
input.submission.begin(input.agentId, userMessage);
try {
const uploadedImageAttachments = input.uploadImages
? await input.uploadImages(wirePayload.images)
: await uploadImageAttachments({ client: input.client, images: wirePayload.images });
const imagePayload = input.uploadImages
? { attachments: await input.uploadImages(wirePayload.images) }
: await prepareImageAttachmentsForSend({
client: input.client,
images: wirePayload.images,
});
await input.client.sendAgentMessage(input.agentId, input.text, {
messageId: clientMessageId,
...(input.activeTurnBehavior ? { activeTurnBehavior: input.activeTurnBehavior } : {}),
attachments: [...wirePayload.attachments, ...(uploadedImageAttachments ?? [])],
...(imagePayload.images ? { images: imagePayload.images } : {}),
attachments: [...wirePayload.attachments, ...(imagePayload.attachments ?? [])],
});
input.submission.accept(input.agentId, clientMessageId);
} catch (error) {
@@ -12,6 +12,8 @@ import {
import { ModelProviderGlyph } from "@/components/model-browser";
import type { ModelPickerActions } from "@/components/model-browser-panes";
import {
CollapsibleProfilesCard,
getSheetSearchFooterStyle,
MobileModelPageView,
SheetSearchDock,
useMobileModelPage,
@@ -86,6 +88,7 @@ export function AgentSettingsDrawer({
}: AgentSettingsDrawerProps) {
const { t } = useTranslation();
const [page, setPage] = useState<AgentSheetPage>(AGENT_SHEET_HOME);
const [profilesExpanded, setProfilesExpanded] = useState(false);
// Select pages search with this; the Model page keeps its own.
const [pageQuery, setPageQuery] = useState("");
const [pageSearchKey, setPageSearchKey] = useState(0);
@@ -93,10 +96,16 @@ export function AgentSettingsDrawer({
providers,
profiles: profiles?.rows ?? null,
canCreateProfile: Boolean(onEditProfiles),
// Profiles lives directly on Agent settings Home above Model; unified search still covers it.
showProfilesSection: false,
selectedProvider,
selectedModel,
});
const toggleProfiles = useCallback(() => {
setProfilesExpanded((expanded) => !expanded);
}, []);
const goTo = useCallback((next: AgentSheetPage) => {
Keyboard.dismiss();
setPageQuery("");
@@ -116,6 +125,7 @@ export function AgentSettingsDrawer({
const close = useCallback(() => {
Keyboard.dismiss();
setPage(AGENT_SHEET_HOME);
setProfilesExpanded(false);
setPageQuery("");
modelPage.reset();
onClose();
@@ -262,15 +272,39 @@ export function AgentSettingsDrawer({
const topCard = useMemo(
() => (
<AgentSheetTopCard
selectedProvider={selectedProvider}
serverId={serverId}
selectedModelLabel={selectedModelLabel}
disabled={disabled}
onOpenModel={openModel}
/>
<View style={styles.topStack}>
{profiles !== null ? (
<CollapsibleProfilesCard
profiles={profiles.rows}
expanded={profilesExpanded}
onToggle={toggleProfiles}
serverId={serverId}
onApplyProfile={handleApplyProfile}
onEditProfiles={onEditProfiles ? handleEditProfiles : undefined}
/>
) : null}
<AgentSheetTopCard
selectedProvider={selectedProvider}
serverId={serverId}
selectedModelLabel={selectedModelLabel}
disabled={disabled}
onOpenModel={openModel}
/>
</View>
),
[disabled, openModel, selectedModelLabel, selectedProvider, serverId],
[
disabled,
handleApplyProfile,
handleEditProfiles,
onEditProfiles,
openModel,
profiles,
profilesExpanded,
selectedModelLabel,
selectedProvider,
serverId,
toggleProfiles,
],
);
let body: ReactNode;
@@ -319,6 +353,7 @@ export function AgentSettingsDrawer({
snapPoints={SNAP_POINTS}
scrollable={false}
footer={footer}
footerContainerStyle={getSheetSearchFooterStyle()}
keyboard={keyboard}
contentStyle={styles.sheetBody}
contextBridge={contextBridge}
@@ -410,13 +445,16 @@ function SelectSearchDock({
);
}
const styles = StyleSheet.create(() => ({
const styles = StyleSheet.create((theme) => ({
sheetBody: {
paddingHorizontal: 0,
paddingTop: 0,
paddingBottom: 0,
gap: 0,
},
topStack: {
gap: theme.spacing[3],
},
page: {
flex: 1,
minHeight: 0,
@@ -660,7 +660,7 @@ const styles = StyleSheet.create((theme) => ({
sliderValue: {
marginLeft: theme.spacing[3],
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
fontSize: theme.fontSize.base,
},
radioRow: {
minHeight: 44,
@@ -4,14 +4,22 @@ import type { AttachmentMetadata, AttachmentStore } from "@/attachments/types";
import { __setAttachmentStoreForTests } from "@/attachments/store";
import { requestWorkspaceDraftAgent } from "./create-agent-request";
function createFakeStore(bytesById: Record<string, Uint8Array>): AttachmentStore {
function createFakeStore(
bytesById: Record<string, Uint8Array>,
options: { allowEncodeBase64?: boolean } = {},
): AttachmentStore {
return {
storageType: "web-indexeddb",
async save() {
throw new Error("not used");
},
async encodeBase64() {
throw new Error("encodeBase64 must not be called when uploading images");
async encodeBase64({ attachment }) {
if (!options.allowEncodeBase64) {
throw new Error("encodeBase64 must not be called when uploading images");
}
const bytes = bytesById[attachment.id];
if (!bytes) throw new Error(`missing ${attachment.id}`);
return Buffer.from(bytes).toString("base64");
},
async readBytes({ attachment }) {
const bytes = bytesById[attachment.id];
@@ -54,7 +62,11 @@ describe("requestWorkspaceDraftAgent", () => {
id: "agent-new",
...input,
}));
const client = { uploadFile, createAgent } as unknown as DaemonClient;
const client = {
uploadFile,
createAgent,
getLastServerInfoMessage: () => ({ features: { uploadedImageAttachments: true } }),
} as unknown as DaemonClient;
const images: AttachmentMetadata[] = [
{
@@ -110,4 +122,50 @@ describe("requestWorkspaceDraftAgent", () => {
},
]);
});
it("falls back to inline base64 images when the daemon does not advertise uploadedImageAttachments", async () => {
const photoBytes = new Uint8Array([9, 8, 7, 6]);
__setAttachmentStoreForTests(
createFakeStore({ imgLegacy: photoBytes }, { allowEncodeBase64: true }),
);
const uploadFile = vi.fn(async () => {
throw new Error("uploadFile must not be called against legacy daemons");
});
const createAgent = vi.fn(async (input: Record<string, unknown>) => ({
id: "agent-legacy",
...input,
}));
const client = {
uploadFile,
createAgent,
getLastServerInfoMessage: () => ({ features: {} }),
} as unknown as DaemonClient;
await requestWorkspaceDraftAgent(client, {
workspaceId: "ws-legacy",
config: { provider: "claude", cwd: "/repo" },
text: "Inspect legacy photo",
clientMessageId: "draft:legacy-image",
images: [
{
id: "imgLegacy",
mimeType: "image/png",
storageType: "web-indexeddb",
storageKey: "imgLegacy",
fileName: "legacy.png",
byteSize: photoBytes.byteLength,
createdAt: 1,
},
],
});
expect(uploadFile).not.toHaveBeenCalled();
expect(createAgent).toHaveBeenCalledTimes(1);
const createCall = createAgent.mock.calls[0]?.[0] as Record<string, unknown>;
expect(createCall.attachments).toBeUndefined();
expect(createCall.images).toEqual([
{ data: Buffer.from(photoBytes).toString("base64"), mimeType: "image/png" },
]);
});
});
@@ -1,7 +1,7 @@
import type { AgentSessionConfig } from "@getpaseo/protocol/agent-types";
import type { AgentSnapshotPayload, CreateAgentRequestMessage } from "@getpaseo/protocol/messages";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import { uploadImageAttachments } from "@/attachments/service";
import { prepareImageAttachmentsForSend } from "@/attachments/service";
import type { AttachmentMetadata } from "@/attachments/types";
export interface WorkspaceDraftAgentRequest {
@@ -21,13 +21,14 @@ export async function requestWorkspaceDraftAgent(
client: DaemonClient,
request: WorkspaceDraftAgentRequest,
): Promise<AgentSnapshotPayload> {
const uploadedImageAttachments = await uploadImageAttachments({ client, images: request.images });
const mergedAttachments = [...(request.attachments ?? []), ...(uploadedImageAttachments ?? [])];
const imagePayload = await prepareImageAttachmentsForSend({ client, images: request.images });
const mergedAttachments = [...(request.attachments ?? []), ...(imagePayload.attachments ?? [])];
return await client.createAgent({
config: request.config,
workspaceId: request.workspaceId,
clientMessageId: request.clientMessageId,
...(request.text ? { initialPrompt: request.text } : {}),
...(imagePayload.images ? { images: imagePayload.images } : {}),
...(mergedAttachments.length > 0 ? { attachments: mergedAttachments } : {}),
});
}
@@ -22,7 +22,7 @@ import { useCreateFlowStore } from "@/stores/create-flow-store";
import type { Agent } from "@/stores/session-store";
import { useWorkspaceFields } from "@/stores/session-store-hooks";
import { useWorkspaceDraftSubmissionStore } from "@/stores/workspace-draft-submission-store";
import { uploadImageAttachments } from "@/attachments/service";
import { prepareImageAttachmentsForSend } from "@/attachments/service";
import { shouldAutoFocusWorkspaceDraftComposer } from "@/screens/workspace/workspace-draft-pane-focus";
import {
resolveDraftWorkingDirectory,
@@ -190,14 +190,15 @@ async function submitDraftCreateRequest(input: {
});
const attachmentsArray = Array.isArray(attachments) ? attachments : [];
const uploadedImageAttachments = await uploadImageAttachments({ client, images });
const mergedAttachments = [...attachmentsArray, ...(uploadedImageAttachments ?? [])];
const imagePayload = await prepareImageAttachmentsForSend({ client, images });
const mergedAttachments = [...attachmentsArray, ...(imagePayload.attachments ?? [])];
const request = {
config,
workspaceId,
initialPrompt: text,
clientMessageId: attempt.clientMessageId,
...(Object.keys(composerState.metadata).length > 0 ? { metadata: composerState.metadata } : {}),
...(imagePayload.images ? { images: imagePayload.images } : {}),
...(mergedAttachments.length > 0 ? { attachments: mergedAttachments } : {}),
};
const result = await client.createAgent({
+6 -23
View File
@@ -110,7 +110,6 @@ import {
applyDictationTranscript,
computeCanStartDictation,
resolveAlternateSendAction,
resolveComposerFramePhase,
resolveComposerSurfacePresentation,
resolveComposerSurfaceText,
resolveMessageInputEnterAction,
@@ -1369,8 +1368,6 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
const dictationToggleKeys = useShortcutKeys("dictation-toggle");
const focusInputKeys = useShortcutKeys("focus-message-input");
const [isInputFocused, setIsInputFocused] = useState(false);
// Only the frame's pointer events set it, so hover stays a web thing; see docs/hover.md.
const [isInputHovered, setIsInputHovered] = useState(false);
useKeyboardFocusSurface("message-input", isInputFocused && isPaneFocused);
// Web text is DOM-owned between deferred draft publications. The action button only needs
// this boundary, so publish empty/non-empty transitions without rerendering for every key.
@@ -2041,30 +2038,22 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
void handleStopRealtimeVoice();
}, [handleStopRealtimeVoice]);
const handleInputWrapperPointerEnter = useCallback(() => setIsInputHovered(true), []);
const handleInputWrapperPointerLeave = useCallback(() => setIsInputHovered(false), []);
const framePhase = resolveComposerFramePhase({
hovered: isInputHovered,
focused: isInputFocused,
readOnly,
disabled,
});
const showFocusBorder = isInputFocused && !readOnly && !disabled;
const inputWrapperCombinedStyle = useMemo(
() => [
styles.inputWrapper,
Platform.OS !== "ios" && isCompact && !isFullscreen && styles.inputWrapperCompact,
readOnly && styles.inputWrapperReadOnly,
framePhase === "hover" && styles.inputWrapperHovered,
framePhase === "active" && styles.inputWrapperFocused,
showFocusBorder && styles.inputWrapperFocused,
inputWrapperStyle,
{ opacity: surfacePresentation.input.opacity },
],
[
framePhase,
inputWrapperStyle,
isCompact,
isFullscreen,
readOnly,
showFocusBorder,
surfacePresentation.input.opacity,
],
);
@@ -2414,8 +2403,6 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
onExit={exitFullscreen}
inputWrapperRef={inputWrapperRef}
inputWrapperStyle={inputWrapperCombinedStyle}
onInputWrapperPointerEnter={handleInputWrapperPointerEnter}
onInputWrapperPointerLeave={handleInputWrapperPointerLeave}
inputPointerEvents={surfacePresentation.input.pointerEvents}
attachmentSlot={attachmentSlot}
showFullscreenButton={shouldShowFullscreenControl(
@@ -2470,14 +2457,10 @@ const styles = StyleSheet.create((theme: Theme) => ({
inputWrapperReadOnly: {
borderStyle: "dotted",
},
// The rest border is already the `borderAccent` that `controlHover` gives other inputs, so
// hover steps up one surface; focus takes the accent, like their focus ring. Colour only:
// the border width stays put, so the frame never shifts under the pointer.
inputWrapperHovered: {
borderColor: theme.colors.surface4,
},
// A neutral step up from the resting `borderAccent`, never the accent. There is no hover
// step: `surface3` is fainter than the resting border in the pure black theme.
inputWrapperFocused: {
borderColor: theme.colors.accent,
borderColor: theme.colors.surface4,
},
// The band the fullscreen glyph sits in is the input's own padding, so a tap
// anywhere in it (under the glyph, or where the glyph would be) is a tap on the
@@ -37,8 +37,6 @@ export function ComposerInputPresentation({
onExit,
inputWrapperRef,
inputWrapperStyle,
onInputWrapperPointerEnter,
onInputWrapperPointerLeave,
inputPointerEvents,
attachmentSlot,
showFullscreenButton,
@@ -55,9 +53,6 @@ export function ComposerInputPresentation({
onExit: () => void;
inputWrapperRef: Ref<View>;
inputWrapperStyle: ViewProps["style"];
/** Hover tracking for the frame's border; the frame is a plain View, per docs/hover.md. */
onInputWrapperPointerEnter: () => void;
onInputWrapperPointerLeave: () => void;
inputPointerEvents: ViewProps["pointerEvents"];
attachmentSlot: ReactNode;
showFullscreenButton: boolean;
@@ -112,8 +107,6 @@ export function ComposerInputPresentation({
ref={inputWrapperRef}
style={fullscreen ? styles.fullscreenInputWrapper : inputWrapperStyle}
pointerEvents={inputPointerEvents}
onPointerEnter={onInputWrapperPointerEnter}
onPointerLeave={onInputWrapperPointerLeave}
>
{fullscreen ? null : attachmentSlot}
<View style={fullscreen ? styles.fullscreenTextSurface : styles.inlineTextSurface}>
@@ -4,7 +4,6 @@ import {
computeCanStartDictation,
type MessageInputEnterContext,
resolveActiveSendBehavior,
resolveComposerFramePhase,
resolveComposerSurfacePresentation,
resolveComposerSurfaceText,
resolveGlyphRailOffset,
@@ -615,23 +614,3 @@ describe("fullscreen glyph rail", () => {
expect(offset + inkInset).toBeCloseTo(0);
});
});
describe("composer frame phase", () => {
const rest = { hovered: false, focused: false, readOnly: false, disabled: false };
it("shows the focus border while the editor has focus, hovered or not", () => {
expect(resolveComposerFramePhase({ ...rest, focused: true })).toBe("active");
expect(resolveComposerFramePhase({ ...rest, focused: true, hovered: true })).toBe("active");
});
it("shows the hover border only while the pointer is over an unfocused frame", () => {
expect(resolveComposerFramePhase({ ...rest, hovered: true })).toBe("hover");
expect(resolveComposerFramePhase(rest)).toBe("rest");
});
it("keeps a read-only or disabled frame at rest", () => {
const engaged = { ...rest, hovered: true, focused: true };
expect(resolveComposerFramePhase({ ...engaged, readOnly: true })).toBe("rest");
expect(resolveComposerFramePhase({ ...engaged, disabled: true })).toBe("rest");
});
});
-21
View File
@@ -3,10 +3,6 @@ import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import type { ActiveTurnBehavior } from "@getpaseo/protocol/messages";
import type { MessagePayload, TextReplacement } from "@/composer/types";
import type { MessageInputKeyboardActionKind } from "@/keyboard/actions";
import {
getControlInteractionPhase,
type ControlInteractionPhase,
} from "@/components/ui/control-geometry";
export type SendBehavior = ActiveTurnBehavior | "queue";
@@ -250,23 +246,6 @@ export function resolveGlyphRailOffset(input: {
return -inkInset;
}
/**
* The composer frame follows the phases of the app's other inputs: focus wins over hover, and
* a frame you can't type into (read-only, disabled) stays at rest.
*/
export function resolveComposerFramePhase(input: {
hovered: boolean;
focused: boolean;
readOnly: boolean;
disabled: boolean;
}): ControlInteractionPhase {
return getControlInteractionPhase({
hovered: input.hovered,
focused: input.focused,
disabled: input.readOnly || input.disabled,
});
}
export function resolveComposerSurfaceText(
liveText: string,
replacement: TextReplacement,
+3 -1
View File
@@ -1889,7 +1889,6 @@ export const ar: TranslationResources = {
searchPlaceholder: "نماذج البحث...",
openProviderSettings: "افتح إعدادات{{provider}}",
searchModelsAndProfilesPlaceholder: "البحث في النماذج والملفات الشخصية...",
shownOfTotal: "{{shown}} معروضة من {{total}}",
olderModels: "نماذج أقدم ({{count}})",
allModels: "كل النماذج ({{count}})",
olderTag: "أقدم",
@@ -2184,6 +2183,9 @@ export const ar: TranslationResources = {
archiveFinishedRetry: "إعادة المحاولة ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "تعذّر عرض هذه اللوحة",
},
draft: {
newAgent: "وكيل جديد",
creatingAgent: "وكيل الخلق",
+3 -1
View File
@@ -1918,7 +1918,6 @@ export const en = {
searchPlaceholder: "Search models...",
openProviderSettings: "Open {{provider}} settings",
searchModelsAndProfilesPlaceholder: "Search models and profiles...",
shownOfTotal: "{{shown}} shown of {{total}}",
olderModels: "Older models ({{count}})",
allModels: "All models ({{count}})",
olderTag: "Older",
@@ -2214,6 +2213,9 @@ export const en = {
archiveFinishedRetry: "Retry ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "Unable to show this panel",
},
draft: {
newAgent: "New Agent",
creatingAgent: "Creating agent",
+3 -1
View File
@@ -1939,7 +1939,6 @@ export const es: TranslationResources = {
searchPlaceholder: "Buscar modelos...",
openProviderSettings: "Abrir configuración de{{provider}}",
searchModelsAndProfilesPlaceholder: "Buscar modelos y perfiles...",
shownOfTotal: "{{shown}} visibles de {{total}}",
olderModels: "Modelos anteriores ({{count}})",
allModels: "Todos los modelos ({{count}})",
olderTag: "Anterior",
@@ -2240,6 +2239,9 @@ export const es: TranslationResources = {
archiveFinishedRetry: "Reintentar ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "No se puede mostrar este panel",
},
draft: {
newAgent: "Nuevo agente",
creatingAgent: "Agente creador",
+3 -1
View File
@@ -1937,7 +1937,6 @@ export const fr: TranslationResources = {
searchPlaceholder: "Rechercher des modèles…",
openProviderSettings: "Ouvrir les paramètres de {{provider}}",
searchModelsAndProfilesPlaceholder: "Rechercher des modèles et des profils…",
shownOfTotal: "{{shown}} affichés sur {{total}}",
olderModels: "Modèles plus anciens ({{count}})",
allModels: "Tous les modèles ({{count}})",
olderTag: "Ancien",
@@ -2237,6 +2236,9 @@ export const fr: TranslationResources = {
archiveFinishedRetry: "Réessayer ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "Impossible d'afficher ce panneau",
},
draft: {
newAgent: "Nouvel agent",
creatingAgent: "Création de l’agent",
+3 -1
View File
@@ -1910,7 +1910,6 @@ export const ja: TranslationResources = {
searchPlaceholder: "モデルを検索...",
openProviderSettings: "{{provider}}の設定を開く",
searchModelsAndProfilesPlaceholder: "モデルとプロファイルを検索...",
shownOfTotal: "{{total}} 件中 {{shown}} 件を表示",
olderModels: "以前のモデル ({{count}})",
allModels: "すべてのモデル ({{count}})",
olderTag: "以前",
@@ -2207,6 +2206,9 @@ export const ja: TranslationResources = {
archiveFinishedRetry: "再試行 ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "このパネルを表示できません",
},
draft: {
newAgent: "新しいエージェント",
creatingAgent: "エージェントを作成中",
+3 -1
View File
@@ -1901,7 +1901,6 @@ export const ko: TranslationResources = {
searchPlaceholder: "모델 검색...",
openProviderSettings: "{{provider}} 설정 열기",
searchModelsAndProfilesPlaceholder: "모델 및 프로필 검색...",
shownOfTotal: "{{total}}개 중 {{shown}}개 표시",
olderModels: "이전 모델 ({{count}})",
allModels: "모든 모델 ({{count}})",
olderTag: "이전",
@@ -2196,6 +2195,9 @@ export const ko: TranslationResources = {
archiveFinishedRetry: "다시 시도 ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "이 패널을 표시할 수 없습니다",
},
draft: {
newAgent: "새 에이전트",
creatingAgent: "에이전트 생성 중",
+3 -1
View File
@@ -1923,7 +1923,6 @@ export const ptBR: TranslationResources = {
searchPlaceholder: "Buscar modelos...",
openProviderSettings: "Abrir configurações de {{provider}}",
searchModelsAndProfilesPlaceholder: "Buscar modelos e perfis...",
shownOfTotal: "{{shown}} de {{total}} exibidos",
olderModels: "Modelos anteriores ({{count}})",
allModels: "Todos os modelos ({{count}})",
olderTag: "Anterior",
@@ -2224,6 +2223,9 @@ export const ptBR: TranslationResources = {
archiveFinishedRetry: "Tentar novamente ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "Não foi possível exibir este painel",
},
draft: {
newAgent: "Novo Agente",
creatingAgent: "Criando agente",
+3 -1
View File
@@ -1923,7 +1923,6 @@ export const ru: TranslationResources = {
searchPlaceholder: "Поиск моделей...",
openProviderSettings: "Открыть настройки {{provider}}",
searchModelsAndProfilesPlaceholder: "Поиск моделей и профилей...",
shownOfTotal: "Показано {{shown}} из {{total}}",
olderModels: "Старые модели ({{count}})",
allModels: "Все модели ({{count}})",
olderTag: "Старая",
@@ -2224,6 +2223,9 @@ export const ru: TranslationResources = {
archiveFinishedRetry: "Повторить ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "Не удалось показать эту панель",
},
draft: {
newAgent: "Новый агент",
creatingAgent: "Создание агента",
+3 -1
View File
@@ -1871,7 +1871,6 @@ export const zhCN: TranslationResources = {
searchPlaceholder: "搜索模型...",
openProviderSettings: "打开 {{provider}} 设置",
searchModelsAndProfilesPlaceholder: "搜索模型和配置文件...",
shownOfTotal: "显示 {{shown}} / {{total}}",
olderModels: "旧模型 ({{count}})",
allModels: "所有模型 ({{count}})",
olderTag: "旧版",
@@ -2161,6 +2160,9 @@ export const zhCN: TranslationResources = {
archiveFinishedRetry: "重试 ({{failed}}/{{total}})",
},
panels: {
renderError: {
title: "无法显示此面板",
},
draft: {
newAgent: "新建 Agent",
creatingAgent: "正在创建 Agent",
+1
View File
@@ -2,3 +2,4 @@ export { KeyboardShiftProvider, useKeyboardShiftStyle } from "./internal/provide
export { useKeyboardShift } from "./internal/context";
export { KeyboardTranslateView } from "./internal/translate";
export { useKeyboardAnchor } from "./internal/anchor";
export { useSettledKeyboardHeight } from "./internal/settled-height";
@@ -11,8 +11,8 @@ export function measureInWindow(element: View): Promise<WindowRect> {
/**
* The element's window rect with `frame`'s own transform left out. Whether
* `measureInWindow` includes a transform depends on the driver: Reanimated commits
* it to the shadow tree, RN's native driver commits it only when the view happens
* to re-render. Fabric's `measureLayout` and a view's `measure` origin ignore
* it to the shadow tree every frame, the iOS translate view commits it only once the
* keyboard settles. Fabric's `measureLayout` and a view's `measure` origin ignore
* transforms. The frame's parent must not move with the keyboard; the composer dock
* is the only anchor host, and its parent is the stationary dock viewport.
*/
@@ -0,0 +1,27 @@
import { useEffect, useState } from "react";
import { KeyboardController, KeyboardEvents } from "react-native-keyboard-controller";
/**
* The software keyboard's height once it has finished moving, or 0 while it is hidden.
*
* Views that ride the keyboard, like the composer, reach their final place only when the keyboard
* settles. Measure against them after this value changes, not when the keyboard starts to move.
*/
export function useSettledKeyboardHeight(): number {
const [height, setHeight] = useState(readSettledHeight);
useEffect(() => {
const subscriptions = [
KeyboardEvents.addListener("keyboardDidShow", (event) => setHeight(event.height)),
KeyboardEvents.addListener("keyboardDidHide", () => setHeight(0)),
];
setHeight(readSettledHeight());
return () => {
for (const subscription of subscriptions) subscription.remove();
};
}, []);
return height;
}
function readSettledHeight(): number {
return KeyboardController.isVisible() ? KeyboardController.state().height : 0;
}
@@ -1,9 +1,12 @@
import { useMemo, useEffect, useRef, type ReactNode } from "react";
import { useCallback, useMemo, useEffect, useRef, type ReactNode } from "react";
import { Animated, useAnimatedValue, type View, type ViewProps } from "react-native";
import { useKeyboardAnimation } from "react-native-keyboard-controller";
import { useAnimatedReaction } from "react-native-reanimated";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { KeyboardTranslationContext } from "./context";
import { scheduleOnRN } from "react-native-worklets";
import { KeyboardTranslationContext, useKeyboardShift } from "./context";
import { useKeyboardTranslationScope } from "./measure";
import { resolveKeyboardLift } from "./policy";
interface KeyboardTranslateViewProps extends ViewProps {
children: ReactNode;
@@ -73,6 +76,25 @@ export function KeyboardTranslateView({
);
const scope = useKeyboardTranslationScope(frameRef, translation);
// The native driver moves the view without telling the shadow tree, and Pressability
// measures its press region there. With a stale region, a touch that drifts a few
// points leaves it and the press is dropped. Commit the lift once the keyboard settles.
const { layoutShift, isMoving } = useKeyboardShift();
const commitRestingLift = useCallback(
(shift: number) => {
const lift = resolveKeyboardLift({ shift, ...translation });
frameRef.current?.setNativeProps({ transform: [{ translateY: -lift }] });
},
[translation],
);
useAnimatedReaction(
() => (isMoving.value ? null : layoutShift.value),
(restingShift) => {
if (restingShift !== null) scheduleOnRN(commitRestingLift, restingShift);
},
[commitRestingLift],
);
return (
<Animated.View ref={frameRef} style={[style, keyboardStyle]} {...props}>
<KeyboardTranslationContext.Provider value={scope}>
@@ -27,8 +27,12 @@ import { StatusBadge } from "@/components/ui/status-badge";
import { Switch } from "@/components/ui/switch";
import { useIsCompactFormFactor } from "@/constants/layout";
import { useToast } from "@/contexts/toast-api-context";
import { useHostRuntimeClient } from "@/runtime/host-runtime";
import { useInstalledPlugin, usePluginEvaluationError } from "@/plugins/registry";
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
import {
useInstalledPlugin,
usePluginCatalogStatus,
usePluginEvaluationError,
} from "@/plugins/registry";
import { pluginDisplayName } from "@/plugins/plugin-list";
import { PluginSettingsContent } from "@/plugins/settings";
import { usePluginActions, type PluginAction } from "./actions";
@@ -276,8 +280,6 @@ interface PluginPageModel {
error?: string;
/** Why the last update failed, while the update is still offered. The installed version keeps running. */
updateError?: string;
/** The plugin's own settings screen, shown inline. */
screenId?: string;
overview?: string;
}
@@ -301,12 +303,10 @@ function usePluginPageModel({
const directory = usePluginDirectory(serverId);
const meta = useListingMeta();
const pluginId = plugin?.id ?? "";
const installedPlugin = useInstalledPlugin(serverId, pluginId);
const evaluationError = usePluginEvaluationError(serverId, pluginId);
const pluginOperation = usePluginOperation(serverId, pluginId);
const updates = usePluginUpdates(serverId);
const text = listing ? listingText(listing, i18n.language) : undefined;
const requestedScreen = subject.kind === "installed" ? subject.screenId : undefined;
return {
name: plugin ? pluginDisplayName(plugin) : (text?.name ?? subjectId(subject)),
description: text?.description ?? plugin?.description,
@@ -316,11 +316,22 @@ function usePluginPageModel({
authorAvatar: listing && listingAuthorAvatar(listing),
error: plugin ? (evaluationError ?? plugin.error) : failedError(installOperation),
updateError: failedUpdateError(pluginOperation, updates.data, pluginId),
screenId: plugin ? (requestedScreen ?? installedPlugin?.settingsScreens[0]?.id) : undefined,
overview: detail && listingOverview(detail, i18n.language),
};
}
function usePluginPageSettings(
serverId: string,
subject: PluginPageSubject,
plugin: PluginListItem | undefined,
) {
const pluginId = subject.kind === "installed" ? subject.pluginId : (plugin?.id ?? "");
const installedPlugin = useInstalledPlugin(serverId, pluginId);
const requestedScreen = subject.kind === "installed" ? subject.screenId : undefined;
const screenId = requestedScreen ?? installedPlugin?.settingsScreens[0]?.id;
return (plugin || installedPlugin) && screenId ? { pluginId, screenId } : undefined;
}
function subjectId(subject: PluginPageSubject): string {
return subject.kind === "listing" ? subject.listingId : subject.pluginId;
}
@@ -408,6 +419,9 @@ export function PluginPage({
const { t } = useTranslation();
const compact = useIsCompactFormFactor();
const { plugin, listingId, listing, detail, loading } = useResolvedPlugin(serverId, subject);
const settings = usePluginPageSettings(serverId, subject, plugin);
const catalogStatus = usePluginCatalogStatus(serverId);
const connected = useHostRuntimeIsConnected(serverId);
const installOperation = usePluginOperation(serverId, listingId);
const model = usePluginPageModel({
serverId,
@@ -436,14 +450,20 @@ export function PluginPage({
<SettingsBackLink label={t("settings.plugins.screens.backToPlugins")} onPress={onBack} />
</View>
);
if (loading)
const waitingForSettings =
subject.kind === "installed" &&
!plugin &&
!settings &&
connected &&
catalogStatus === "loading";
if (loading || waitingForSettings)
return (
<View>
{back}
<PluginPageSkeleton />
</View>
);
if (!plugin && !listing)
if (!plugin && !listing && !settings)
return (
<Alert
size="sm"
@@ -486,6 +506,7 @@ export function PluginPage({
listing={listing}
overviewLoading={detail.isLoading}
model={model}
settings={settings}
/>
{installTarget ? (
<InstallPluginSheet serverId={serverId} target={installTarget} onClose={closeInstall} />
@@ -500,12 +521,14 @@ function PluginPageBody({
listing,
overviewLoading,
model,
settings,
}: {
serverId: string;
plugin?: PluginListItem;
listing?: PluginListing;
overviewLoading: boolean;
model: PluginPageModel;
settings?: { pluginId: string; screenId: string };
}) {
const { t } = useTranslation();
return (
@@ -523,9 +546,9 @@ function PluginPageBody({
</View>
) : null}
{listing ? <MediaStrip urls={listingImages(listing)} /> : null}
{plugin && model.screenId ? (
{settings ? (
// The plugin's settings screen brings its own sections.
<PluginSettingsContent serverId={serverId} pluginId={plugin.id} screenId={model.screenId} />
<PluginSettingsContent serverId={serverId} {...settings} />
) : null}
{model.overview || (listing && overviewLoading) ? (
<SettingsSection title={t("settings.plugins.gallery.sections.overview")}>
@@ -1,6 +1,7 @@
import React, { Component, type ErrorInfo, type ReactNode } from "react";
import type { ReactNode } from "react";
import { Text } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { RenderErrorBoundary } from "@/components/render-error-boundary";
interface SurfaceErrorBoundaryProps {
children: ReactNode;
@@ -10,42 +11,30 @@ interface SurfaceErrorBoundaryProps {
renderError?(error: string): ReactNode;
}
interface SurfaceErrorBoundaryState {
error: string | null;
export function SurfaceErrorBoundary({
children,
installation,
resetKey,
Surface,
renderError,
}: SurfaceErrorBoundaryProps) {
return (
<RenderErrorBoundary
resetKeys={[installation, resetKey, Surface]}
onError={warnSurfaceRenderFailed}
renderError={renderError ?? renderPluginFailed}
>
{children}
</RenderErrorBoundary>
);
}
export class SurfaceErrorBoundary extends Component<
SurfaceErrorBoundaryProps,
SurfaceErrorBoundaryState
> {
state: SurfaceErrorBoundaryState = { error: null };
function renderPluginFailed(error: string) {
return <Text style={styles.errorText}>Plugin failed: {error}</Text>;
}
static getDerivedStateFromError(error: unknown): SurfaceErrorBoundaryState {
return { error: error instanceof Error ? error.message : String(error) };
}
componentDidCatch(error: Error, info: ErrorInfo): void {
console.warn("[Plugins] Surface render failed", error, info.componentStack);
}
componentDidUpdate(previous: SurfaceErrorBoundaryProps): void {
if (
this.state.error &&
(previous.installation !== this.props.installation ||
previous.resetKey !== this.props.resetKey ||
previous.Surface !== this.props.Surface)
) {
this.setState({ error: null });
}
}
render() {
if (this.state.error) {
if (this.props.renderError) return this.props.renderError(this.state.error);
return <Text style={styles.errorText}>Plugin failed: {this.state.error}</Text>;
}
return this.props.children;
}
function warnSurfaceRenderFailed(error: unknown, componentStack: string | null | undefined): void {
console.warn("[Plugins] Surface render failed", error, componentStack);
}
const styles = StyleSheet.create((theme) => ({
@@ -82,6 +82,69 @@ describe("plugin timeline projection", () => {
expect(seen).toEqual(["Inspect files"]);
});
it("keeps repeated plugin output IDs distinct across source messages", () => {
const transform: TimelineItemTransform = ({ item }) => [
{
type: "plugin",
id: "part-0",
pluginId: "split",
kind: "part",
version: 1,
data: { text: item.type === "assistant_message" ? item.text : "" },
},
];
const first: StreamItem = {
kind: "assistant_message",
id: "message-1",
text: "Short",
timestamp: new Date("2026-01-01T00:00:00.000Z"),
};
const second: StreamItem = { ...first, id: "message-2", text: "A much longer reply" };
const rows = projectPluginTimelineItems([first, second], transform);
expect(new Set(rows.map((row) => row.id)).size).toBe(2);
expect(rows).toMatchObject([
{ source: { id: "message-1" }, pluginItemId: "part-0", data: { text: "Short" } },
{
source: { id: "message-2" },
pluginItemId: "part-0",
data: { text: "A much longer reply" },
},
]);
const updated = projectPluginTimelineItems(
[{ ...second, text: "Updated reply" }],
transform,
"streaming",
);
expect(updated[0].id).toBe(rows[1].id);
const completed = projectPluginTimelineItems([{ ...second, text: "Final reply" }], transform);
expect(completed[0].id).toBe(rows[1].id);
const prepended = projectPluginTimelineItems(
[{ ...first, id: "older-message" }, first, second],
transform,
);
expect(prepended.slice(1).map((row) => row.id)).toEqual(rows.map((row) => row.id));
});
it("keeps source and output ID separators unambiguous", () => {
const rows = projectPluginTimelineItems(
[
{ ...thought("First"), id: "message/a" },
{ ...thought("Second"), id: "message" },
],
({ sourceId }) => [
{
type: "plugin",
id: sourceId === "message/a" ? "b" : "a/b",
pluginId: "split",
kind: "part",
version: 1,
data: null,
},
],
);
expect(rows[0].id).not.toBe(rows[1].id);
});
it("does not expose mutable tool detail from stream state", () => {
const detail = { type: "read" as const, filePath: "/repo/original.ts" };
const source: StreamItem = {
@@ -126,8 +189,8 @@ describe("plugin timeline projection", () => {
expect(projectPluginTimelineItems([thought("First")], transform)).toMatchObject([
{
kind: "plugin",
id: "inline-thinking/thought-1/0",
source: { kind: "thought", id: "thought-1" },
pluginItemId: "thought-1/0",
data: { text: "First", phase: "streaming" },
},
]);
@@ -214,10 +277,11 @@ describe("plugin timeline projection", () => {
]);
const filtered = projectPluginTimelineItems([source], () => []);
expect(exploded.map((item) => item.id)).toEqual([
"split/thought-1/left",
"split/thought-1/right",
expect(exploded).toMatchObject([
{ source: { id: "thought-1" }, pluginItemId: "thought-1/left" },
{ source: { id: "thought-1" }, pluginItemId: "thought-1/right" },
]);
expect(new Set(exploded.map((item) => item.id)).size).toBe(2);
expect(filtered).toEqual([]);
});
@@ -254,13 +318,13 @@ describe("plugin timeline projection", () => {
expect(projected).toMatchObject([
{
kind: "plugin",
id: "genui/assistant-1/text",
pluginItemId: "assistant-1/text",
timelineCursor: { epoch: "e1", seq: 7 },
turnId: "turn-1",
},
{
kind: "plugin",
id: "genui/assistant-1/card",
pluginItemId: "assistant-1/card",
timelineCursor: { epoch: "e1", seq: 7 },
turnId: "turn-1",
},
@@ -94,7 +94,9 @@ function transformSourceItem(
return transformed.map((pluginItem) => {
const projected: PluginTimelineStreamItem = {
kind: "plugin",
id: `${pluginItem.pluginId}/${pluginItem.id}`,
// Output IDs are local to a source item. Encode each part so separators in
// source or output IDs cannot alias another replacement.
id: JSON.stringify([pluginItem.pluginId, item.id, pluginItem.id]),
source: item,
timestamp: item.timestamp,
pluginId: pluginItem.pluginId,
@@ -29,7 +29,8 @@ import {
type HostRuntimeControllerDeps,
type HostRuntimeStorage,
} from "./host-runtime";
import type { ReplicaRow, ReplicaRowStore } from "./replica-cache/row-store";
import { replicaPayloadBytes } from "./replica-cache/payload-bytes";
import type { ReplicaRow, ReplicaRowSize, ReplicaRowStore } from "./replica-cache/row-store";
import { subscriptionFixture } from "./subscription-fixture";
import { readDesktopManagedLocalCredential } from "@/desktop/daemon/local-credential";
@@ -640,12 +641,12 @@ function createMemoryReplicaRowStore(): ReplicaRowStore {
(!acceptedIds || acceptedIds.has(row.id)),
);
},
readAll: async () => {
const hosts = new Map<string, ReplicaRow[]>();
for (const row of rows.values()) {
const hostRows = hosts.get(row.serverId) ?? [];
hostRows.push(row);
hosts.set(row.serverId, hostRows);
readIndex: async () => {
const hosts = new Map<string, ReplicaRowSize[]>();
for (const { serverId, kind, id, payload } of rows.values()) {
const hostRows = hosts.get(serverId) ?? [];
hostRows.push({ serverId, kind, id, bytes: replicaPayloadBytes(payload) });
hosts.set(serverId, hostRows);
}
return [...hosts].map(([serverId, hostRows]) => ({ serverId, rows: hostRows }));
},
@@ -0,0 +1,128 @@
import { getHeapSnapshot } from "node:v8";
import { describe, expect, it } from "vitest";
import { ReplicaCache } from ".";
import { createSqliteReplicaRowStore, type ReplicaSqliteDriver } from "./row-store-sqlite";
import { createNodeSqliteDriver } from "./row-store-sqlite.test-driver";
// The SQLite store keeps rows in native memory, so any payload string left on the JS heap after a
// write or a cold start is one the cache itself holds on to.
const SERVER_ID = "cached-host";
const OTHER_SERVER_ID = "other-host";
const noLegacyCleanup = { clearLegacyCache: async () => undefined };
function openCache(driver: ReplicaSqliteDriver, maxBytes?: number): ReplicaCache {
const cache = new ReplicaCache(createSqliteReplicaRowStore(driver, 1), {
...noLegacyCleanup,
...(maxBytes ? { maxBytes } : {}),
});
cache.setHosts([SERVER_ID, OTHER_SERVER_ID]);
return cache;
}
function timeline(agentId: string, text: string) {
return {
agentId,
items: [
{
kind: "assistant_message" as const,
id: "message-1",
text,
timestamp: new Date("2026-07-18T08:02:00.000Z"),
timelineCursor: { epoch: "epoch-1", seq: 12 },
},
],
range: { epoch: "epoch-1", startSeq: 1, endSeq: 12 },
hasOlder: false,
};
}
// Built inside a function so the test keeps no reference to the transcript text once committed.
function commitLargeTimeline(cache: ReplicaCache, serverId: string, marker: string): void {
cache.commitTimeline(serverId, "agent-1", timeline("agent-1", marker + "x".repeat(1_000_000)));
}
/** Sizes of serialized payload strings, retained on the JS heap, whose text contains the marker. */
async function retainedPayloadStrings(marker: string): Promise<number[]> {
const chunks: Buffer[] = [];
// Taking a snapshot runs a full garbage collection first.
for await (const chunk of getHeapSnapshot()) chunks.push(chunk as Buffer);
const snapshot = JSON.parse(Buffer.concat(chunks).toString("utf8")) as {
snapshot: { meta: { node_fields: string[]; node_types: [string[]] } };
nodes: number[];
strings: string[];
};
const fields = snapshot.snapshot.meta.node_fields;
const types = snapshot.snapshot.meta.node_types[0];
const typeField = fields.indexOf("type");
const nameField = fields.indexOf("name");
const sizeField = fields.indexOf("self_size");
const sizes: number[] = [];
for (let base = 0; base < snapshot.nodes.length; base += fields.length) {
if (!types[snapshot.nodes[base + typeField]].includes("string")) continue;
const name = snapshot.strings[snapshot.nodes[base + nameField]];
// The transcript text itself starts with the marker; its JSON payload starts with "{".
if (name.startsWith("{") && name.includes(marker)) {
sizes.push(snapshot.nodes[base + sizeField]);
}
}
return sizes;
}
describe("ReplicaCache over SQLite", () => {
it("does not keep written payloads on the JS heap", async () => {
const marker = `written-${crypto.randomUUID()}`;
const cache = openCache(createNodeSqliteDriver());
commitLargeTimeline(cache, SERVER_ID, marker);
await cache.flush();
expect(await retainedPayloadStrings(marker)).toEqual([]);
expect((await cache.readTimeline(SERVER_ID, "agent-1"))?.items[0]).toMatchObject({
text: expect.stringMatching(new RegExp(`^${marker}x{1000000}$`)),
});
}, 60_000);
it("does not load stored payloads onto the JS heap to index a cold start", async () => {
const marker = `stored-${crypto.randomUUID()}`;
const driver = createNodeSqliteDriver();
const writer = openCache(driver);
commitLargeTimeline(writer, SERVER_ID, marker);
await writer.flush();
const cache = openCache(driver);
// The first write indexes every stored row to enforce the budget.
cache.commitTimeline(OTHER_SERVER_ID, "agent-1", timeline("agent-1", "small"));
await cache.flush();
expect(await retainedPayloadStrings(marker)).toEqual([]);
expect(await cache.readTimeline(SERVER_ID, "agent-1")).toBeDefined();
}, 60_000);
it.each([
{ budget: "exactly fits", slack: 0, evicted: false },
{ budget: "is one byte short", slack: -1, evicted: true },
])("enforces the budget in UTF-8 bytes after a cold start when it $budget", async (input) => {
const driver = createNodeSqliteDriver();
const writer = openCache(driver);
writer.commitTimeline(SERVER_ID, "agent-1", timeline("agent-1", "é😀中".repeat(500)));
writer.commitTimeline(OTHER_SERVER_ID, "agent-1", timeline("agent-1", "other"));
await writer.flush();
const storedBytes = await sumStoredPayloadBytes(driver);
const cache = openCache(driver, storedBytes + input.slack);
// Same size as the stored row, so the projected total stays at the stored total.
cache.commitTimeline(OTHER_SERVER_ID, "agent-1", timeline("agent-1", "OTHER"));
await cache.flush();
expect((await cache.readTimeline(SERVER_ID, "agent-1")) === undefined).toBe(input.evicted);
expect((await cache.readTimeline(OTHER_SERVER_ID, "agent-1"))?.items[0]).toMatchObject({
text: "OTHER",
});
});
});
async function sumStoredPayloadBytes(driver: ReplicaSqliteDriver): Promise<number> {
const connection = await driver.open();
const rows = await connection.all<{ payload: string }>("SELECT payload FROM rows");
return rows.reduce((total, row) => total + Buffer.byteLength(row.payload, "utf8"), 0);
}
@@ -7,10 +7,20 @@ import {
} from "@/stores/session-store";
import type { StreamItem } from "@/types/stream";
import { normalizeAgentSnapshot } from "@/utils/agent-snapshots";
import { createPluginWorkspaceSnapshot } from "@/plugins/client-state/snapshots";
import {
createPluginAgentSnapshot,
createPluginWorkspaceSnapshot,
} from "@/plugins/client-state/snapshots";
import { ReplicaCache } from ".";
import type { DirectoryCheckpoint } from "@/runtime/replica-cache";
import type { ReplicaHostRows, ReplicaRow, ReplicaRowChanges, ReplicaRowStore } from "./row-store";
import { replicaPayloadBytes } from "./payload-bytes";
import type {
ReplicaHostIndex,
ReplicaRow,
ReplicaRowChanges,
ReplicaRowSize,
ReplicaRowStore,
} from "./row-store";
const SERVER_ID = "cached-host";
@@ -38,8 +48,8 @@ class MemoryStorage implements ReplicaRowStore {
onRead: (() => void) | null = null;
/** Throws once a read goes past this count, so a non-terminating read loop fails the test. */
readLimit: number | null = null;
/** Awaited before the store lists every row or deletes a host, so a test can interleave there. */
beforeReadAll: (() => Promise<void>) | null = null;
/** Awaited before the store indexes every row or deletes a host, so a test can interleave there. */
beforeReadIndex: (() => Promise<void>) | null = null;
beforeDeleteHost: (() => Promise<void>) | null = null;
private key(row: Pick<ReplicaRow, "serverId" | "kind" | "id">): string {
@@ -71,13 +81,13 @@ class MemoryStorage implements ReplicaRowStore {
);
}
async readAll(): Promise<ReplicaHostRows[]> {
await this.beforeReadAll?.();
const hosts = new Map<string, ReplicaRow[]>();
for (const row of this.rows.values()) {
const rows = hosts.get(row.serverId) ?? [];
rows.push(row);
hosts.set(row.serverId, rows);
async readIndex(): Promise<ReplicaHostIndex[]> {
await this.beforeReadIndex?.();
const hosts = new Map<string, ReplicaRowSize[]>();
for (const { serverId, kind, id, payload } of this.rows.values()) {
const rows = hosts.get(serverId) ?? [];
rows.push({ serverId, kind, id, bytes: replicaPayloadBytes(payload) });
hosts.set(serverId, rows);
}
return [...hosts].map(([serverId, rows]) => ({ serverId, rows }));
}
@@ -158,6 +168,7 @@ function agent(id = "agent-1"): Agent {
persistence: null,
title: "Cached agent",
labels: {},
metadata: {},
},
SERVER_ID,
),
@@ -1139,7 +1150,7 @@ describe("ReplicaCache", () => {
).toEqual(["agent", "checkpoint", "project", "workspace"]);
});
it.each(["beforeReadAll", "beforeDeleteHost"] as const)(
it.each(["beforeReadIndex", "beforeDeleteHost"] as const)(
"stores no checkpoint for a host evicted after its update was queued (%s)",
async (pausePoint) => {
const storage = new MemoryStorage();
@@ -1433,3 +1444,40 @@ it("retains workspace metadata across replica-cache reload and invalidates pre-m
projects: checkpoint.projects,
});
});
it("restores agent metadata for plugins when the directory cache reopens", async () => {
const storage = new MemoryStorage();
const writer = createCache(storage);
const baseline = directory();
const metadata = { "plugin.waiting": { kind: "plan", at: "2026-07-18T08:02:00.000Z" } };
baseline.agents.set("agent-1", { ...agent(), metadata });
commitDirectory(writer, SERVER_ID, baseline);
await writer.flush();
const restored = await createCache(storage).readDirectory(SERVER_ID);
expect(
createPluginAgentSnapshot(restored.agents.get("agent-1")!, "workspace-1").metadata,
).toEqual(metadata);
expect(restored.checkpoint).toEqual(baseline.checkpoint);
});
it("discards the agent cursor when a pre-metadata agent row is restored", async () => {
const storage = new MemoryStorage();
const writer = createCache(storage);
const baseline = directory({
agents: { generation: "g", afterSeq: 12 },
projects: { generation: "g", afterSeq: 4 },
});
commitDirectory(writer, SERVER_ID, baseline);
await writer.flush();
const key = `${SERVER_ID}:agent:agent-1`;
const row = storage.rows.get(key)!;
const legacyPayload = JSON.parse(row.payload) as { snapshot: Record<string, unknown> };
delete legacyPayload.snapshot.metadata;
storage.rows.set(key, { ...row, payload: JSON.stringify(legacyPayload) });
const restored = await createCache(storage).readDirectory(SERVER_ID);
expect(restored.checkpoint).toEqual({ projects: baseline.checkpoint.projects });
expect(restored.agents.size).toBe(0);
});
+36 -37
View File
@@ -27,12 +27,14 @@ import {
import type { UnsettledTurn } from "@/timeline/turn-liveness";
import { normalizeAgentSnapshot } from "@/utils/agent-snapshots";
import { clearLegacyReplicaCache } from "./legacy-cleanup";
import { replicaPayloadBytes } from "./payload-bytes";
import {
REPLICA_SINGLETON_ROW_ID,
type ReplicaRow,
type ReplicaRowChanges,
type ReplicaRowKey,
type ReplicaRowKind,
type ReplicaRowSize,
type ReplicaRowStore,
} from "./row-store";
@@ -257,6 +259,8 @@ const StoredAgentSnapshotSchema = z.strictObject({
lastError: z.string().optional(),
title: z.string().nullable(),
labels: z.record(z.string(), z.string()),
// Require metadata so older rows invalidate the agent cursor and refetch from the daemon.
metadata: z.record(z.string(), z.unknown() as z.ZodType<JsonValue>),
// Optional: clients without background_agents never received a background agent to cache.
background: z.boolean().optional(),
requiresAttention: z.boolean().optional(),
@@ -705,6 +709,7 @@ function serializeAgent(agent: Agent): StoredAgent {
...(agent.lastError ? { lastError: agent.lastError } : {}),
title: agent.title,
labels: agent.labels,
metadata: agent.metadata ?? {},
...(agent.background ? { background: true } : {}),
requiresAttention: agent.requiresAttention ?? false,
backgroundWork: agent.backgroundWork,
@@ -866,31 +871,27 @@ function pendingRowKey(key: ReplicaRowKey): string {
return `${key.serverId}\u0000${rowKey(key)}`;
}
// Budget accounting runs over every stored row of a touched host on each persist. Rows are
// immutable once stored, so their size is computed once. The count itself avoids the JS Buffer
// polyfill, which materialises the whole byte array just to measure it.
const rowBytesCache = new WeakMap<ReplicaRow, number>();
// A write is sized twice, once to fit the budget and once when it is stored. Sizing walks the
// whole payload, so each written row is measured once.
const writtenRowSizes = new WeakMap<ReplicaRow, ReplicaRowSize>();
function utf8ByteLength(text: string): number {
let bytes = 0;
for (let index = 0; index < text.length; index += 1) {
const code = text.charCodeAt(index);
if (code < 0x80) bytes += 1;
else if (code < 0x800) bytes += 2;
else if (code >= 0xd800 && code <= 0xdbff) {
bytes += 4;
index += 1;
} else bytes += 3;
function rowSize(row: ReplicaRow): ReplicaRowSize {
let size = writtenRowSizes.get(row);
if (!size) {
size = {
serverId: row.serverId,
kind: row.kind,
id: row.id,
bytes: replicaPayloadBytes(row.payload),
};
writtenRowSizes.set(row, size);
}
return bytes;
return size;
}
function rowBytes(row: ReplicaRow): number {
let bytes = rowBytesCache.get(row);
if (bytes === undefined) {
bytes = utf8ByteLength(row.payload);
rowBytesCache.set(row, bytes);
}
function sumBytes(rows: Iterable<ReplicaRowSize>): number {
let bytes = 0;
for (const row of rows) bytes += row.bytes;
return bytes;
}
@@ -977,7 +978,8 @@ function matchesReplicaRead(read: ReplicaRead, row: ReplicaRowKey): boolean {
export class ReplicaCache {
private readonly activeServerIds = new Set<string>();
private readonly activeReads = new Set<ReplicaRead>();
private readonly storedRows = new Map<string, Map<string, ReplicaRow>>();
// Key and size of every stored row, by host. Payloads stay in the row store.
private readonly storedRows = new Map<string, Map<string, ReplicaRowSize>>();
private readonly hostBytes = new Map<string, number>();
private readonly hostWriteOrder = new Map<string, true>();
private pendingUpserts = new Map<string, StructuredReplicaUpsert>();
@@ -1280,13 +1282,13 @@ export class ReplicaCache {
this.invalidateHostReads(newServerId);
const rows = this.storedRows.get(oldServerId);
if (rows) {
const newRows = this.storedRows.get(newServerId) ?? new Map<string, ReplicaRow>();
const newRows = this.storedRows.get(newServerId) ?? new Map<string, ReplicaRowSize>();
this.totalBytes -=
(this.hostBytes.get(oldServerId) ?? 0) + (this.hostBytes.get(newServerId) ?? 0);
this.storedRows.delete(oldServerId);
for (const [key, row] of rows) newRows.set(key, { ...row, serverId: newServerId });
this.storedRows.set(newServerId, newRows);
const bytes = [...newRows.values()].reduce((sum, row) => sum + rowBytes(row), 0);
const bytes = sumBytes(newRows.values());
this.hostBytes.delete(oldServerId);
this.hostBytes.set(newServerId, bytes);
this.totalBytes += bytes;
@@ -1526,17 +1528,17 @@ export class ReplicaCache {
const previous = rows?.get(rowKey(key));
if (previous) {
rows?.delete(rowKey(key));
this.adjustHostBytes(key.serverId, -rowBytes(previous));
this.adjustHostBytes(key.serverId, -previous.bytes);
}
touchedServerIds.add(key.serverId);
}
for (const row of changes.upserts) {
const rows = this.storedRows.get(row.serverId) ?? new Map<string, ReplicaRow>();
const rows = this.storedRows.get(row.serverId) ?? new Map<string, ReplicaRowSize>();
const previous = rows.get(rowKey(row));
const previousBytes = previous ? rowBytes(previous) : 0;
rows.set(rowKey(row), row);
const size = rowSize(row);
rows.set(rowKey(row), size);
this.storedRows.set(row.serverId, rows);
this.adjustHostBytes(row.serverId, rowBytes(row) - previousBytes);
this.adjustHostBytes(row.serverId, size.bytes - (previous?.bytes ?? 0));
touchedServerIds.add(row.serverId);
}
for (const serverId of touchedServerIds) {
@@ -1565,7 +1567,7 @@ export class ReplicaCache {
for (const key of changes.deletes) touchedServerIds.add(key.serverId);
for (const row of changes.upserts) touchedServerIds.add(row.serverId);
const projectedRows = new Map<string, Map<string, ReplicaRow>>();
const projectedRows = new Map<string, Map<string, ReplicaRowSize>>();
const projectedBytes = new Map(this.hostBytes);
for (const serverId of touchedServerIds) {
projectedRows.set(serverId, new Map(this.storedRows.get(serverId)));
@@ -1574,13 +1576,10 @@ export class ReplicaCache {
projectedRows.get(key.serverId)?.delete(rowKey(key));
}
for (const row of changes.upserts) {
projectedRows.get(row.serverId)?.set(rowKey(row), row);
projectedRows.get(row.serverId)?.set(rowKey(row), rowSize(row));
}
for (const [serverId, rows] of projectedRows) {
projectedBytes.set(
serverId,
[...rows.values()].reduce((sum, row) => sum + rowBytes(row), 0),
);
projectedBytes.set(serverId, sumBytes(rows.values()));
}
const writeOrder = [...this.hostWriteOrder.keys()].filter(
@@ -1653,7 +1652,7 @@ export class ReplicaCache {
}
private ensureStoredIndex(): Promise<void> {
this.storedIndexPromise ??= this.rowStore.readAll().then(async (hosts) => {
this.storedIndexPromise ??= this.rowStore.readIndex().then(async (hosts) => {
this.storedRows.clear();
this.hostBytes.clear();
this.hostWriteOrder.clear();
@@ -1664,7 +1663,7 @@ export class ReplicaCache {
continue;
}
const rows = new Map(host.rows.map((row) => [rowKey(row), row]));
const bytes = host.rows.reduce((sum, row) => sum + rowBytes(row), 0);
const bytes = sumBytes(host.rows);
this.storedRows.set(host.serverId, rows);
this.hostBytes.set(host.serverId, bytes);
this.totalBytes += bytes;
@@ -0,0 +1,15 @@
// The size the row stores report for a payload. Counting avoids the JS Buffer polyfill, which
// materialises the whole byte array just to measure it.
export function replicaPayloadBytes(payload: string): number {
let bytes = 0;
for (let index = 0; index < payload.length; index += 1) {
const code = payload.charCodeAt(index);
if (code < 0x80) bytes += 1;
else if (code < 0x800) bytes += 2;
else if (code >= 0xd800 && code <= 0xdbff) {
bytes += 4;
index += 1;
} else bytes += 3;
}
return bytes;
}
@@ -0,0 +1,37 @@
import { DatabaseSync, type SQLInputValue } from "node:sqlite";
import type { ReplicaSqliteConnection, ReplicaSqliteDriver, SqliteValue } from "./row-store-sqlite";
/** Test driver over Node's built-in SQLite. Rows live in native memory, outside the JS heap. */
export function createNodeSqliteDriver(): ReplicaSqliteDriver {
const database = new DatabaseSync(":memory:");
function connection(): ReplicaSqliteConnection {
return {
async exec(sql) {
database.exec(sql);
},
async run(sql, params = []) {
database.prepare(sql).run(...(params as SQLInputValue[]));
},
async all<Row>(sql: string, params: readonly SqliteValue[] = []) {
return database.prepare(sql).all(...(params as SQLInputValue[])) as Row[];
},
async transaction(operation) {
database.exec("BEGIN IMMEDIATE");
try {
await operation(connection());
database.exec("COMMIT");
} catch (error) {
database.exec("ROLLBACK");
throw error;
}
},
};
}
return {
async open() {
return connection();
},
};
}
@@ -1,4 +1,10 @@
import type { ReplicaHostRows, ReplicaRow, ReplicaRowChanges, ReplicaRowStore } from "./row-store";
import type {
ReplicaHostIndex,
ReplicaRow,
ReplicaRowChanges,
ReplicaRowSize,
ReplicaRowStore,
} from "./row-store";
export type SqliteValue = string | number | null;
@@ -34,6 +40,13 @@ interface StoredMeta {
value: string;
}
interface StoredRowSize {
server_id: string;
kind: ReplicaRow["kind"];
id: string;
bytes: number;
}
interface StoredRow {
server_id: string;
kind: ReplicaRow["kind"];
@@ -89,18 +102,20 @@ export function createSqliteReplicaRowStore(
}
}
async function readAll(): Promise<ReplicaHostRows[]> {
const storedRows = await getConnection().all<StoredRow>(
"SELECT server_id, kind, id, payload FROM rows ORDER BY server_id, kind, id",
async function readIndex(): Promise<ReplicaHostIndex[]> {
// The database stores text as UTF-8, so the blob length is the payload's UTF-8 size.
const storedRows = await getConnection().all<StoredRowSize>(
`SELECT server_id, kind, id, length(CAST(payload AS BLOB)) AS bytes FROM rows
ORDER BY server_id, kind, id`,
);
const hosts = new Map<string, ReplicaRow[]>();
const hosts = new Map<string, ReplicaRowSize[]>();
for (const storedRow of storedRows) {
const rows = hosts.get(storedRow.server_id) ?? [];
rows.push({
serverId: storedRow.server_id,
kind: storedRow.kind,
id: storedRow.id,
payload: storedRow.payload,
bytes: storedRow.bytes,
});
hosts.set(storedRow.server_id, rows);
}
@@ -169,5 +184,5 @@ export function createSqliteReplicaRowStore(
await getConnection().run("DELETE FROM rows");
}
return { open, read, readAll, apply, deleteHost, renameHost, clear };
return { open, read, readIndex, apply, deleteHost, renameHost, clear };
}
@@ -8,6 +8,23 @@ export interface ReplicaRowStoreHarness {
export type CreateReplicaRowStoreHarness = () => Promise<ReplicaRowStoreHarness>;
const ALL_KINDS: ReplicaRow["kind"][] = ["agent", "checkpoint", "project", "timeline", "workspace"];
interface ReplicaHostRows {
serverId: string;
rows: ReplicaRow[];
}
async function readEveryRow(store: ReplicaRowStore): Promise<ReplicaHostRows[]> {
const hosts = await store.readIndex();
return Promise.all(
hosts.map(async (host) => ({
serverId: host.serverId,
rows: await store.read(host.serverId, ALL_KINDS),
})),
);
}
function row(serverId: string, kind: ReplicaRow["kind"], id: string, payload: string): ReplicaRow {
return { serverId, kind, id, payload };
}
@@ -27,7 +44,7 @@ export function runReplicaRowStoreContract(
});
it("reads an empty store", async () => {
expect(await store.readAll()).toEqual([]);
expect(await readEveryRow(store)).toEqual([]);
});
it("round-trips opaque payloads grouped by server", async () => {
@@ -40,7 +57,7 @@ export function runReplicaRowStoreContract(
deletes: [],
});
expect(await store.readAll()).toEqual([
expect(await readEveryRow(store)).toEqual([
{
serverId: "server-a",
rows: [
@@ -81,7 +98,7 @@ export function runReplicaRowStoreContract(
deletes: [],
});
expect(await store.readAll()).toEqual([
expect(await readEveryRow(store)).toEqual([
{
serverId: "server-a",
rows: [row("server-a", "agent", "agent-1", "new")],
@@ -102,7 +119,7 @@ export function runReplicaRowStoreContract(
deletes: [{ serverId: "server-a", kind: "agent", id: "same-id" }],
});
expect(await store.readAll()).toEqual([
expect(await readEveryRow(store)).toEqual([
{
serverId: "server-a",
rows: [row("server-a", "workspace", "same-id", "workspace")],
@@ -122,7 +139,7 @@ export function runReplicaRowStoreContract(
deletes: [],
}),
).rejects.toBeInstanceOf(Error);
expect(await store.readAll()).toEqual([]);
expect(await readEveryRow(store)).toEqual([]);
});
it("deletes every row belonging to one host", async () => {
@@ -137,7 +154,7 @@ export function runReplicaRowStoreContract(
await store.deleteHost("server-a");
expect(await store.readAll()).toEqual([
expect(await readEveryRow(store)).toEqual([
{ serverId: "server-b", rows: [row("server-b", "agent", "agent-2", "b")] },
]);
});
@@ -155,7 +172,7 @@ export function runReplicaRowStoreContract(
await store.renameHost("temporary", "canonical");
expect(await store.readAll()).toEqual([
expect(await readEveryRow(store)).toEqual([
{
serverId: "canonical",
rows: [
@@ -178,7 +195,67 @@ export function runReplicaRowStoreContract(
await store.clear();
expect(await store.readAll()).toEqual([]);
expect(await readEveryRow(store)).toEqual([]);
});
it("indexes every row by key and UTF-8 payload size, without payloads", async () => {
await store.apply({
upserts: [
row("server-b", "checkpoint", "singleton", '{"cursor":2}'),
row("server-a", "timeline", "agent-1", "é😀中a"),
row("server-a", "agent", "agent-1", "ascii"),
],
deletes: [],
});
expect(await store.readIndex()).toEqual([
{
serverId: "server-a",
rows: [
{ serverId: "server-a", kind: "agent", id: "agent-1", bytes: 5 },
{ serverId: "server-a", kind: "timeline", id: "agent-1", bytes: 10 },
],
},
{
serverId: "server-b",
rows: [{ serverId: "server-b", kind: "checkpoint", id: "singleton", bytes: 12 }],
},
]);
});
it("keeps indexed sizes in step with overwrites, deletes, directory writes, and renames", async () => {
await store.apply({
upserts: [
row("temporary", "agent", "agent-1", "x".repeat(40)),
row("temporary", "timeline", "agent-1", "short"),
],
deletes: [],
});
await store.apply(
{
upserts: [
row("temporary", "agent", "agent-1", "ü".repeat(3)),
row("temporary", "checkpoint", "singleton", '{"a":1}'),
],
deletes: [{ serverId: "temporary", kind: "timeline", id: "agent-1" }],
},
{ directoryBaselines: new Set(["temporary"]) },
);
await store.renameHost("temporary", "canonical");
expect(await store.readIndex()).toEqual([
{
serverId: "canonical",
rows: [
{ serverId: "canonical", kind: "agent", id: "agent-1", bytes: 6 },
{ serverId: "canonical", kind: "checkpoint", id: "singleton", bytes: 7 },
],
},
]);
expect(await store.read("canonical", ["agent", "checkpoint"])).toEqual([
row("canonical", "agent", "agent-1", "ü".repeat(3)),
row("canonical", "checkpoint", "singleton", '{"a":1}'),
]);
});
it("wipes cached rows when the schema version changes on open", async () => {
@@ -189,7 +266,7 @@ export function runReplicaRowStoreContract(
const upgradedStore = await harness.openWithSchemaVersion(2);
expect(await upgradedStore.readAll()).toEqual([]);
expect(await readEveryRow(upgradedStore)).toEqual([]);
});
});
}

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