Compare commits

..
Author SHA1 Message Date
QSothoth 555391d8b5 fix(server): lazily probe plugin providers for session listing
PluginAgentClient.capabilities previously derived supportsSessionListing
solely from already-negotiated connection capabilities, returning false
before first connect(). Command-backed plugins with custom status() hooks
(such as Antigravity ACP and Muse) were therefore skipped by
AgentManager.listImportableSessions() right after daemon startup.

Allow unconnected, non-closed plugin clients to report
supportsSessionListing so listImportableSessions() can lazily connect on
demand. Coalesce cold listing setup so executable resolution runs once
per connection attempt, return an empty list without connecting when the
executable is missing (typed ProviderExecutableNotFoundError) or when
status() reports unavailable, surface unexpected status() failures to
providerErrors, avoid blocking shutdown on in-flight status() probes,
and fall back to negotiated capabilities once connected.

Fixes #10412

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

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

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

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

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

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

---------

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

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

Refs #8908.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Closes #7225

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

Co-authored-by: tieo <65707274+tieo@users.noreply.github.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-28 11:42:40 +00:00
303 changed files with 13683 additions and 26859 deletions
-2
View File
@@ -1,2 +0,0 @@
packages/app/gpui/package-lock.json linguist-generated
packages/app/gpui/desktop/Cargo.lock linguist-generated
+6 -2
View File
@@ -1,6 +1,6 @@
# Pull-request checks are routed by the behavior they prove. Package consumers
# do not inherit their dependencies' test suites; main and manual runs execute
# every contract regardless of these paths.
# do not inherit their dependencies' test suites, except where noted below; main
# and manual runs execute every contract regardless of these paths.
routing:
- ".github/ci-paths.yml"
@@ -87,5 +87,9 @@ browser:
relay:
- "packages/relay/**"
# cli-tests is also a daemon end-to-end suite: it drives a real daemon, built-in
# plugins included, so daemon changes run it too.
cli:
- "packages/cli/**"
- "packages/server/**"
- "plugins/**"
+18 -5
View File
@@ -8,13 +8,14 @@ on:
merge_group:
workflow_dispatch:
# A newer push to the same ref cancels the run still in progress, main included.
# A full run costs about 200 runner-minutes against the org's 20 concurrent
# jobs, and a superseded main run only answers a question the newer commit
# answers again.
# A newer push cancels the run still in progress on every ref except main,
# because a full run costs about 200 runner-minutes against the org's 20
# concurrent jobs. A main run finishes: cancelling it mid-flight leaves CANCELLED
# checks that paint the commit red. Each ref has one run in progress and one
# pending, so a newer push replaces a pending main run before it starts any job.
concurrency:
group: ci-${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
env:
# CI does not use the CUDA execution provider, and the onnxruntime-node
@@ -174,6 +175,9 @@ jobs:
- name: Verify dependency patch recovery
run: node --test scripts/postinstall-patches.test.mjs
- name: Verify daemon runtime trace contract
run: node --test scripts/trace-daemon.test.mjs
- name: Build server stack
run: npm run build:server
@@ -213,6 +217,15 @@ jobs:
- name: Verify website mockups
run: npm run test:e2e --workspace=@getpaseo/website
- name: Upload website test artifacts
uses: actions/upload-artifact@v4
if: failure()
with:
name: website-playwright-results
path: packages/website/test-results/
if-no-files-found: ignore
retention-days: 7
- name: Verify public package contents
run: |
npm pack --dry-run --ignore-scripts --workspace=@getpaseo/protocol
+3 -1
View File
@@ -13,9 +13,11 @@ on:
- ".github/workflows/desktop-packages.yml"
workflow_dispatch:
# A main run finishes. A run cancelled mid-flight leaves CANCELLED checks that
# paint the commit red.
concurrency:
group: desktop-packages-${{ github.ref }}
cancel-in-progress: true
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
permissions:
contents: read
+3 -1
View File
@@ -28,9 +28,11 @@ on:
- "false"
- "true"
# main, tag and publish runs finish. A run cancelled mid-flight leaves CANCELLED
# checks that paint a main commit red.
concurrency:
group: docker-${{ github.workflow }}-${{ github.event_name == 'workflow_dispatch' && inputs.publish == 'true' && format('publish-{0}', inputs.paseo_version || github.run_id) || github.ref }}
cancel-in-progress: ${{ !startsWith(github.ref, 'refs/tags/') && !(github.event_name == 'workflow_dispatch' && inputs.publish == 'true') }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' && !startsWith(github.ref, 'refs/tags/') && !(github.event_name == 'workflow_dispatch' && inputs.publish == 'true') }}
env:
REGISTRY: ghcr.io
+30
View File
@@ -3,8 +3,37 @@ name: Nix
on:
push:
branches: [main]
# Prove the real Nix package and daemon smoke before merge when Nix, CLI,
# server, or daemon packaging inputs change.
pull_request:
paths:
- "nix/**"
- "flake.nix"
- "flake.lock"
- "package.json"
- "package-lock.json"
- "packages/protocol/**"
- "packages/client/**"
- "packages/highlight/**"
- "packages/plugin/**"
- "packages/server/**"
- "packages/relay/**"
- "packages/cli/**"
- "packages/desktop/**"
- "plugins/**"
- "skills/**"
- "scripts/trace-daemon.mjs"
- "scripts/is-main-module.mjs"
- "scripts/build-daemon-web-ui.mjs"
- "scripts/update-nix.sh"
- "scripts/fix-lockfile.mjs"
- ".github/workflows/nix.yml"
workflow_dispatch:
concurrency:
group: nix-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
permissions:
contents: read
@@ -102,6 +131,7 @@ jobs:
run: nix build .#desktop -o result-desktop
build-desktop-darwin:
if: ${{ github.event_name != 'pull_request' }}
runs-on: macos-latest
steps:
- uses: actions/checkout@v4
-2
View File
@@ -99,5 +99,3 @@ app.json
# Project-local Serena configuration and memories.
.serena/
!packages/app/gpui/app.json
+18 -11
View File
@@ -198,17 +198,24 @@ outstanding intent. A crash after successful dispatch but before removal commits
notification. Clean shutdown can also flush an already queued callback while retaining its intent,
so that callback can repeat after restart. This is an at-least-once wakeup, without turn attribution or exactly-once delivery.
A turn end is not always a settled child. When the child ends its turn with work that will start its
next turn by itself, the caller gets one `message` notice ("ended its turn but is still working") and
the subscription keeps following the child. That work is a running turn, queued messages, a pending
provider wake-up (`AgentSession.hasPendingWakeup`: Claude background tasks, task notifications, and
one-shot wake-ups), or the child's own outstanding finish subscriptions as a caller. Heartbeats,
recurring crons, change-request watches, and other daemon background items never count: they are
external triggers, not work the caller is waiting for. While following, turn ends and work changes stay
silent until nothing is pending, which sends `finished` and removes the subscription. `followingSince`
is stored before the notice is sent, so restarts resume following without repeating it, and following
ends after 24 hours with an "is still working" notice. Remote children and providers without the probe
report their first turn end as `finished`.
A turn end is not always a settled child. A child can end its turn with work that will start its next
turn by itself: a running turn, queued messages, a pending provider wake-up
(`AgentSession.hasPendingWakeup`: Claude background tasks, task notifications, and one-shot
wake-ups), or the child's own outstanding finish subscriptions as a caller. Heartbeats, recurring
crons, change-request watches, and other daemon background items never count: they are external
triggers, not work the caller is waiting for.
Every turn end reports `finished` at once. When work is still pending, the notice names it and the
subscription follows the child: each later turn end reports `finished` again, and the child settling
with nothing pending sends a final `finished` and removes the subscription, even when the work
drains without another turn. Reporting at once keeps a long-lived task, such as a dev server, from
leaving the caller without the child's reply. Following is what lets the caller hear the reply a
background task wakes up later ([#6346](https://github.com/getpaseo/paseo/issues/6346)). A work change
that leaves work pending sends nothing. Errors, permission requests, and closes report as they
happen. `followingSince` is stored when following starts, so a restart keeps following instead of
waiting for another turn end. After 24 hours of following, the caller gets a final `finished` with
the child's last reply and the subscription ends. Remote children and providers without the probe
report their first turn end as a settled `finished`.
Permission requests are notification checkpoints, not the end of that subscription. The caller is notified again after a permission response when the child finishes, errors, or requests another permission.
The permission notification includes the normalized request plus the child and request IDs, so the caller can inspect it and respond without fetching agent status.
-7
View File
@@ -29,13 +29,6 @@ the titlebar row. Production builds leave the variable unset and show no label.
`npm run dev` is only a shorthand for `npm run dev:server`. Keep `127.0.0.1:6767` for the packaged app and production-style `~/.paseo` state.
## Experimental GPUI client
The opt-in [GPUI target](../packages/app/gpui/README.md) runs the existing React
Native app on Linux. Its contributor guide covers setup, the renderer comparison,
unsupported features, native checks, and experiments to pick up. It connects to
an already-running daemon and does not replace the Electron dev command.
## Nix desktop package
The flake exposes `packages.<system>.desktop` on Linux and macOS:
+3 -4
View File
@@ -205,10 +205,9 @@ docker build \
.
```
The Docker workflow builds the image on pull requests and on `main` as a
non-publishing check. Stable `vX.Y.Z` tag pushes publish
`ghcr.io/getpaseo/paseo:X.Y.Z` and `ghcr.io/getpaseo/paseo:latest`. Beta tags
publish only the exact prerelease tag, such as
The Docker workflow builds the image on `main` as a non-publishing check.
Stable `vX.Y.Z` tag pushes publish `ghcr.io/getpaseo/paseo:X.Y.Z` and
`ghcr.io/getpaseo/paseo:latest`. Beta tags publish only the exact prerelease tag, such as
`ghcr.io/getpaseo/paseo:0.1.102-beta.1`, and do not update `latest`.
To replace a Docker image in place without rebuilding desktop, APK, or EAS
+4 -3
View File
@@ -118,8 +118,9 @@ An explicit user instruction can select another base.
`chore(release): cut <version>` without a tag.
5. Push the release branch (`git push -u origin HEAD`). Pushing any `release/**` branch triggers
`CI` (all 21 jobs) and `Desktop Packages` (Linux user-namespace smoke) in their own concurrency
groups, isolated from `main` traffic. Never wait on `main` CI, because `main` cancels in-progress
runs on every merge. Wait for both runs on the release branch commit to pass before shipping.
groups, isolated from `main` traffic. Never wait on `main` CI, because `main` runs queue behind
each other and a newer merge replaces the pending one.
Wait for both runs on the release branch commit to pass before shipping.
Complete the [pre-release dependency checks](#pre-release-dependency-checks) on that commit.
Pushing a `release/**` branch without a `v*` tag triggers no publish workflows.
6. After go-ahead, push the tag first with `npm run release:push` so remote builds start right away.
@@ -278,7 +279,7 @@ The tag push triggers `Desktop Release`, `Android APK Release`, `Docker`, `Relea
Confirm that `npm view @getpaseo/cli dist-tags` shows `latest` at the shipped version, and `beta` at the shipped version or an active newer beta, before considering the stable release complete.
The Docker workflow builds images from the checked-out source tree on `main` as non-publishing checks (cancelling superseded `main` runs). Stable `vX.Y.Z` tag pushes publish `ghcr.io/getpaseo/paseo:X.Y.Z` and `ghcr.io/getpaseo/paseo:latest`; beta `vX.Y.Z-beta.N` tag pushes publish only `ghcr.io/getpaseo/paseo:X.Y.Z-beta.N` and never move `latest`.
The Docker workflow builds images from the checked-out source tree on `main` as non-publishing checks (a running check finishes, and a newer merge replaces the pending one). Stable `vX.Y.Z` tag pushes publish `ghcr.io/getpaseo/paseo:X.Y.Z` and `ghcr.io/getpaseo/paseo:latest`; beta `vX.Y.Z-beta.N` tag pushes publish only `ghcr.io/getpaseo/paseo:X.Y.Z-beta.N` and never move `latest`.
The production relay is the Elixir service in [getpaseo/paseo-relay](https://github.com/getpaseo/paseo-relay), with its own deployment process. Paseo releases and pushes to this repository do not deploy it. The Cloudflare relay code and workflow in this repository are legacy and are not used in production.
+1 -1
View File
@@ -200,7 +200,7 @@ Test suites in this repo are heavy. Running them in bulk freezes the machine, es
## Pull-request test routing
PR checks are routed by the behavior each suite proves, using `.github/ci-paths.yml`. A package does not inherit every test suite of its runtime consumers: app changes do not run CLI or Electron-wrapper tests, and protocol changes do not run every package that imports the protocol. Cross-package static compatibility belongs to `typecheck`; full integration coverage runs after merge on main and in manual CI runs.
PR checks are routed by the behavior each suite proves, using `.github/ci-paths.yml`. A package does not inherit every test suite of its runtime consumers: app changes do not run CLI or Electron-wrapper tests, and protocol changes do not run every package that imports the protocol. The CLI E2E tests are the exception: they drive a real daemon, so changes to the server or built-in plugins run them too. Cross-package static compatibility belongs to `typecheck`; full integration coverage runs after merge on main and in manual CI runs.
Required matrix legs are declared as statically named jobs. Their shared steps use YAML anchors, while job-level `if` conditions let GitHub report an unaffected leg as genuinely skipped without allocating a runner or losing the exact required-check name.
+24 -8
View File
@@ -330,19 +330,35 @@ that starts or accepts them. Received messages retain sender attribution, while
notifications remain visible events. Collapse, timing and locally mounted history share
these boundaries.
Agent-message XML belongs to the daemon's `agent/agent-messages` boundary. Prompt delivery encodes
Agent-message markup belongs to the daemon's `agent/agent-messages` boundary. Prompt delivery encodes
provenance; acceptance, provider echoes, import, and replay share its projection. The delivery ID is
also the projected call ID, so a provider echo cannot create a second row. Sender IDs are opaque and
do not imply local ownership or authorization. Capture the sender title at delivery: archived or
removed senders must remain understandable without a live directory lookup.
The optional `agentMessage` payload carries event, sender, and delivered text. Shared client
presentation (`protocol/paseo-tool-presentation`) owns its heading and expanded details, next to the
labels for every Paseo MCP tool. The daemon
must not construct UI labels or prepend sender labels to the semantic message body. The existing
`tool_call` / `plain_text` envelope is a compatibility adapter: older clients still parse the row and
expand its body. New clients use the typed payload, never infer the event from a tool name or parse
XML. Stream reduction and disk-cache serialization preserve the payload without rendering it.
Each delivered message keeps its text first and ends with a `<paseo-message … length="N"/>` marker.
Text at character 0 stays the sender's, so a provider still reads a slash command there, and bodies
are never escaped. `length` bounds the text before the marker, so marker syntax inside a body cannot
split it, and a batch splits back into rows by reading markers from the end. A person's prompt gets a
marker only when it shares a provider turn with other deliveries or contains `<paseo-message` or
`<paseo-system`. Transcripts written before markers open with a `<paseo-system>` envelope; the
projection still reads those (`COMPAT(leadingPaseoSystemEnvelope)`).
The daemon decides whether a delivery is a message or a tool call, and clients render what it sends:
- A person's text is a `user_message`.
- A peer message is an `agent_message` tool call whose `agentMessage` carries sender and text. The
wire has no sender on `user_message`, so clients present it as a "Sent by" bubble.
- Lifecycle notifications (`agent_finished`, `agent_errored`, `agent_needs_permission`,
`agent_closed`), schedule fires (`heartbeat`), and change-request updates
are plain tool calls. `plain_text` detail carries the sender in `label`, the body in `text`, and
the icon. Clients render the heading from the tool name, so no notification event reaches them.
`isTimelineTurnTrigger` (`packages/protocol/src/timeline-turn.ts`) lists the delivered tool names that
start a turn. Add a name there when the daemon projects a new delivery. Rows that older daemons stored
with notification `agentMessage` metadata are rewritten to the plain call at presentation
(`COMPAT(agentNotificationMetadata)`). Stream reduction and disk-cache serialization preserve the
payload without rendering it.
The compatibility boundary for older daemons is snapshot normalization: running/idle status becomes an
anonymous active turn or idle state once, and downstream code consumes the same activity shape. The app
+1 -5
View File
@@ -126,11 +126,7 @@
"release:push": "node scripts/push-current-release-tag.mjs",
"release:ship": "npm run release:push && npm run release:publish",
"release:ship:beta": "npm run release:push && npm run release:publish:beta",
"release:reconcile": "node scripts/reconcile-release.mjs",
"gpui:install": "node scripts/gpui.mjs install",
"gpui:bundle": "node scripts/gpui.mjs bundle",
"build:gpui": "node scripts/gpui.mjs build",
"dev:gpui": "node scripts/gpui.mjs run"
"release:reconcile": "node scripts/reconcile-release.mjs"
},
"devDependencies": {
"@types/ws": "^8.5.14",
@@ -6,16 +6,15 @@ import {
expectComposerDoesNotName,
expectAgentProfilesEmptyPrompt,
expectHostAgentProfiles,
expectProfileEditTooltip,
expectComposerMode,
expectCreateProfileFromModelRow,
expectComposerModel,
expectModelRowProfileActionBesideRow,
expectModelRowSelected,
expectProfileEditIsPencilOnly,
expectProfileReachableByScrolling,
expectProfileSearchResult,
expectProfileVisibleForProvider,
expectPickerProfile,
expectProfilesEditLink,
fillAgentProfileName,
openEditProfileFromModelRow,
openModelPicker,
@@ -86,17 +85,19 @@ test.describe("Agent profiles in the model picker", () => {
await expectComposerMode(page, "Load test");
});
await test.step("the sole provider opens directly", async () => {
await test.step("the picker opens on the agent's provider with Profiles beside it", async () => {
await openModelPicker(page);
await expect(page.getByTestId("model-search-input").first()).toBeVisible();
await expect(page.getByTestId("sheet-header-back")).toHaveCount(0);
await expect(page.locator('[data-testid^="model-provider-"]')).toHaveCount(0);
await expectProfileVisibleForProvider(page, {
await expect(page.getByTestId("model-search-input").first()).toBeFocused();
await expect(page.getByTestId("model-provider-mock")).toHaveAttribute(
"data-active",
"true",
);
await expectModelRowSelected(page, { provider: "mock", modelId: "ten-second-stream" });
await expectPickerProfile(page, {
name: PROFILE.name,
summary: PROFILE_SUMMARY,
});
await expectProfileEditIsPencilOnly(page);
await expectProfileEditTooltip(page);
await expectProfilesEditLink(page);
});
await test.step("applying it writes its model and mode into the composer", async () => {
@@ -115,14 +116,13 @@ test.describe("Agent profiles in the model picker", () => {
await expectComposerDoesNotName(page, PROFILE.name);
});
await test.step("reopening returns directly to the provider models", async () => {
await test.step("reopening returns to the provider models with the new model checked", async () => {
await openModelPicker(page);
await expect(page.getByTestId("model-search-input").first()).toBeVisible();
await expectProfileVisibleForProvider(page, {
await expectModelRowSelected(page, { provider: "mock", modelId: "one-minute-stream" });
await expectPickerProfile(page, {
name: PROFILE.name,
summary: PROFILE_SUMMARY,
});
await expectModelRowSelected(page, { provider: "mock", modelId: "one-minute-stream" });
await closeModelPicker(page);
});
} finally {
@@ -0,0 +1,559 @@
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import { connectDaemonClient } from "../support/helpers/daemon-client-loader";
import {
beginTextReveal,
retargetTextReveal,
visibleRevealedText,
} from "../../src/agent-stream/text-reveal";
import type { Page } from "@playwright/test";
import { test, expect } from "../support/fixtures";
import { expectComposerVisible } from "../support/helpers/composer";
import { scrollChatAwayFromBottom } from "../support/helpers/agent-bottom-anchor";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
test.use({
e2eDaemonConfig: {
version: 1,
agents: {
providers: Object.fromEntries(
[
"claude",
"codex",
"copilot",
"opencode",
"pi",
"omp",
"antigravity",
"hoplite",
"muse",
].map((id) => [id, { enabled: false }]),
),
},
},
});
interface ClosingFenceFrameSample {
text: string;
codeBlockHeights: number[];
codeBlockTexts: string[];
messageHeights: number[];
partialFenceLines: string[];
}
interface ClosingFenceFrameReport {
finished: boolean;
samples: ClosingFenceFrameSample[];
}
async function sampleClosingFenceFrames(page: Page): Promise<ClosingFenceFrameReport> {
return await page.evaluate(async () => {
const samples: ClosingFenceFrameSample[] = [];
let finished = false;
await new Promise<void>((resolve) => {
const tick = () => {
const messages = Array.from(
document.querySelectorAll<HTMLElement>('[data-testid="assistant-message"]'),
);
const text = messages.map((message) => message.textContent ?? "").join("");
const sample: ClosingFenceFrameSample = {
text,
codeBlockHeights: [],
codeBlockTexts: [],
messageHeights: messages.map((message) =>
Math.round(message.getBoundingClientRect().height),
),
partialFenceLines: [],
};
for (const message of messages) {
for (const block of message.querySelectorAll<HTMLElement>(
'pre, [data-paseo-markdown-tag="pre"]',
)) {
const code = block.querySelector<HTMLElement>('code, [data-paseo-markdown-tag="code"]');
const codeText = code?.textContent ?? block.textContent ?? "";
sample.codeBlockTexts.push(codeText.trimEnd());
// Opening fence prefixes render as prose; closing artifacts live inside code blocks.
for (const line of codeText.split(/\r?\n/)) {
if (/^\s*`{1,2}\s*$/.test(line)) sample.partialFenceLines.push(line);
}
sample.codeBlockHeights.push(Math.round(block.getBoundingClientRect().height));
}
}
samples.push(sample);
finished = text.includes("Both blocks are closed.");
if (finished) {
resolve();
return;
}
requestAnimationFrame(tick);
};
requestAnimationFrame(tick);
});
return { finished, samples };
});
}
const FIRST_PAUSE_TEXT = "Here is the first snippet:const answer = 42;\nconsole.log(answer);";
const SECOND_PAUSE_TEXT = `${FIRST_PAUSE_TEXT}And a second one:echo done`;
for (const { label, html } of [
{ label: "semantic", html: "<pre><code>const answer = 42;\n`\n``</code></pre>" },
{
label: "annotated",
html: '<div data-paseo-markdown-tag="pre"><span data-paseo-markdown-tag="code">const answer = 42;\n`\n``</span><button>Copy</button></div>',
},
{
label: "annotated semantic",
html: '<pre data-paseo-markdown-tag="pre"><code data-paseo-markdown-tag="code">const answer = 42;\n`\n``</code></pre>',
},
]) {
test(`samples ${label} code block DOM without duplicate blocks or controls`, async ({ page }) => {
await page.setContent(
`<div data-testid="assistant-message">${html}<p>Both blocks are closed.</p></div>`,
);
const report = await sampleClosingFenceFrames(page);
const sample = report.samples.at(-1)!;
expect(report.finished).toBe(true);
expect(sample.codeBlockTexts).toEqual(["const answer = 42;\n`\n``"]);
expect(sample.partialFenceLines).toEqual(["`", "``"]);
expect(sample.codeBlockHeights).toHaveLength(1);
expect(sample.codeBlockHeights[0]).toBeGreaterThan(0);
});
}
function closingFencePauseSamples(
samples: readonly ClosingFenceFrameSample[],
pauseText: string,
): ClosingFenceFrameSample[] {
return samples.filter((sample) => sample.text === pauseText);
}
function expectStableGeometry(
samples: readonly ClosingFenceFrameSample[],
expectedCodeBlockTexts: readonly string[],
): void {
expect(samples.length, "the paused text state should be sampled").toBeGreaterThan(0);
expect(
samples.every(
(sample) => JSON.stringify(sample.codeBlockTexts) === JSON.stringify(expectedCodeBlockTexts),
),
"the sampled code should contain only the authored lines",
).toBe(true);
const geometries = new Set(
samples.map((sample) => JSON.stringify([sample.messageHeights, sample.codeBlockHeights])),
);
expect(
geometries.size,
"message and code block geometry should stay fixed during the pause",
).toBe(1);
}
/**
* A closing fence that is still being typed must not be painted as code.
*
* The mock reply closes each code block in two arrivals: one backtick, a pause,
* then the other two. Painted, that first backtick is a line of code that
* vanishes when the fence completes, so the block grows and shrinks and every
* row below it moves twice. Each pause is sampled and its text geometry checked.
*/
test("does not paint a closing fence while it is still being typed", async ({ page }, testInfo) => {
test.setTimeout(90_000);
const agent = await seedMockAgentWorkspace({
repoPrefix: "closing-fence-",
title: "Closing fence",
model: "e2e-fast-stream",
});
try {
await openAgentRoute(page, agent);
await expectComposerVisible(page);
const reportPromise = sampleClosingFenceFrames(page);
await agent.client.sendAgentMessage(
agent.agentId,
"Stream a code block with a split closing fence.",
);
const report = await reportPromise;
await testInfo.attach("closing-fence-frames", {
body: JSON.stringify(report, null, 2),
contentType: "application/json",
});
expect(report.finished, "the reply should finish streaming").toBe(true);
expect(
report.samples.flatMap((sample) => sample.partialFenceLines),
"no frame, including transitions outside the pause windows, may show a partial fence inside code",
).toEqual([]);
const firstPauseSamples = closingFencePauseSamples(report.samples, FIRST_PAUSE_TEXT);
const secondPauseSamples = closingFencePauseSamples(report.samples, SECOND_PAUSE_TEXT);
expectStableGeometry(firstPauseSamples, ["const answer = 42;\nconsole.log(answer);"]);
expectStableGeometry(secondPauseSamples, [
"const answer = 42;\nconsole.log(answer);",
"echo done",
]);
expect(secondPauseSamples[0]?.codeBlockHeights[0]).toBe(
firstPauseSamples[0]?.codeBlockHeights[0],
);
} finally {
await agent.cleanup();
}
});
test("excludes each revealed character of the next paragraph from both pauses", () => {
for (const [pauseText, paragraph] of [
[FIRST_PAUSE_TEXT, "And a second one:"],
[SECOND_PAUSE_TEXT, "Both blocks are closed."],
]) {
const state = retargetTextReveal(beginTextReveal(pauseText), pauseText + paragraph);
const samples = Array.from({ length: paragraph.length + 1 }, (_, index) => ({
text: visibleRevealedText({ ...state, revealed: pauseText.length + index }),
codeBlockHeights: [],
codeBlockTexts: [],
messageHeights: [index],
partialFenceLines: [],
}));
expect(closingFencePauseSamples(samples, pauseText)).toEqual([samples[0]]);
}
});
for (const { label, markdown, expectedCode, expectedPartialFenceLines } of [
{
label: "opening prefixes in prose",
markdown: "And a second one:\n\n`\n\n``\n\nBoth blocks are closed.",
expectedCode: [],
expectedPartialFenceLines: [],
},
{
label: "partial fences inside rendered code",
markdown: "```ts\nconst answer = 42;\n`\n``\n```\n\nBoth blocks are closed.",
expectedCode: ["const answer = 42;\n`\n``"],
expectedPartialFenceLines: ["`", "``"],
},
]) {
test(`samples ${label} in the correct container`, async ({ page }, testInfo) => {
const agent = await seedMockAgentWorkspace({
repoPrefix: "fence-sample-container-",
title: "Fence sample container",
featureValues: { mockAssistantResponse: markdown },
});
try {
await openAgentRoute(page, agent);
await expectComposerVisible(page);
const reportPromise = sampleClosingFenceFrames(page);
await agent.client.sendAgentMessage(agent.agentId, "Show the fence sampling fixture.");
const report = await reportPromise;
await testInfo.attach("fence-container-frames", {
body: JSON.stringify(report, null, 2),
contentType: "application/json",
});
expect(report.finished).toBe(true);
const messageText = await page.getByTestId("assistant-message").innerText();
const messageLines = messageText.split(/\r?\n/);
const messageFenceLines = messageLines.filter((line) => /^\s*`{1,2}\s*$/.test(line));
expect(messageFenceLines).toEqual(["`", "``"]);
const finalSample = report.samples.at(-1);
expect(finalSample?.codeBlockTexts).toEqual(expectedCode);
expect(finalSample?.partialFenceLines).toEqual(expectedPartialFenceLines);
} finally {
await agent.cleanup();
}
});
}
test("shows the complete reasoning after a streamed turn finishes", async ({ page }, testInfo) => {
test.setTimeout(90_000);
await page.setViewportSize({ width: 1280, height: 900 });
await page.addInitScript(() => {
localStorage.setItem(
"@paseo:app-settings",
JSON.stringify({ toolCallDetailLevel: "detailed", autoExpandReasoning: true }),
);
});
const reasoning =
"Need to find the scroll container, the layout effect that watches for new messages, and any gesture handler that might fight with programmatic scrolling. Probably a ref on the FlatList plus a near-bottom threshold.";
const agent = await seedMockAgentWorkspace({
repoPrefix: "finished-reasoning-",
title: "Finished reasoning",
model: "ten-second-stream",
});
const historyClient = await connectDaemonClient<
Pick<DaemonClient, "connect" | "close" | "fetchAgentTimeline">
>({ clientIdPrefix: "finished-reasoning-history" });
try {
await openAgentRoute(page, agent);
await expectComposerVisible(page);
await agent.client.sendAgentMessage(
agent.agentId,
"Stream briefly to check finished reasoning.",
);
await agent.client.waitForFinish(agent.agentId, 30_000);
const history = await historyClient.fetchAgentTimeline(agent.agentId, { limit: 500 });
const thoughts = history.entries
.map((entry) => entry.item)
.filter((item) => item.type === "reasoning");
await testInfo.attach("canonical-reasoning", {
body: JSON.stringify(thoughts, null, 2),
contentType: "application/json",
});
expect(thoughts[0]?.text).toBe(reasoning);
const expectedCounts = new Map<string, number>();
for (const thought of thoughts)
expectedCounts.set(thought.text, (expectedCounts.get(thought.text) ?? 0) + 1);
const rendered = page.getByText(reasoning, { exact: true });
for (const [text, count] of expectedCounts)
await expect(page.getByText(text, { exact: true })).toHaveCount(count);
await expect(rendered.first()).toBeVisible();
await testInfo.attach("finished-reasoning", {
body: await page.screenshot(),
contentType: "image/png",
});
await page.reload();
for (const [text, count] of expectedCounts)
await expect(page.getByText(text, { exact: true })).toHaveCount(count);
await expect(rendered.first()).toBeVisible();
} catch (error) {
await testInfo.attach("reasoning-before-cleanup", {
body: await page.screenshot(),
contentType: "image/png",
});
throw error;
} finally {
await historyClient.close();
await agent.cleanup();
}
});
test("records equal-input long-reply rendering metrics", async ({ page }, testInfo) => {
test.setTimeout(120_000);
await page.setViewportSize({ width: 1280, height: 900 });
const markdown =
Array.from({ length: 15 }, (_, index) =>
[
"### Block " + index,
"",
"\x60\x60\x60ts",
...Array.from(
{ length: 12 },
(_value, line) => "const value_" + index + "_" + line + " = " + (index * 12 + line) + ";",
),
"\x60\x60\x60",
"",
].join("\n"),
).join("\n") + "\nEqual-input stream complete.";
const agent = await seedMockAgentWorkspace({
repoPrefix: "equal-input-long-reply-",
title: "Equal-input long reply",
featureValues: {
mockStreamingAssistantResponse: markdown,
mockStreamingAssistantIntervalMs: 5,
},
});
try {
await openAgentRoute(page, agent);
await expectComposerVisible(page);
const session = await page.context().newCDPSession(page);
await session.send("Performance.enable");
const before = await session.send("Performance.getMetrics");
const sampler = await page.evaluateHandle(() => {
const state = {
frames: [] as number[],
longTasks: [] as number[],
running: true,
last: performance.now(),
};
const observer = new PerformanceObserver((list) => {
state.longTasks.push(...list.getEntries().map((entry) => entry.duration));
});
observer.observe({ type: "longtask", buffered: false });
const tick = (now: number) => {
state.frames.push(now - state.last);
state.last = now;
if (state.running) requestAnimationFrame(tick);
};
requestAnimationFrame(tick);
return { state, observer };
});
await agent.client.sendAgentMessage(agent.agentId, "Render the fixed fifteen-block fixture.");
await agent.client.waitForFinish(agent.agentId, 60_000);
const message = page.getByTestId("assistant-message").last();
await expect(message).toContainText("Equal-input stream complete.", { timeout: 30_000 });
const blocks = message.locator('pre, [data-paseo-markdown-tag="pre"]');
await expect(blocks).toHaveCount(15);
for (let index = 0; index < 15; index++) {
await expect(blocks.nth(index)).toContainText(
"const value_" + index + "_11 = " + (index * 12 + 11) + ";",
);
}
const samples = await sampler.evaluate(({ state, observer }) => {
state.running = false;
state.longTasks.push(...observer.takeRecords().map((entry) => entry.duration));
observer.disconnect();
return state;
});
const after = await session.send("Performance.getMetrics");
const frames = [...samples.frames].sort((a, b) => a - b);
await testInfo.attach("equal-input-rendering", {
body: JSON.stringify(
{
markdown,
viewport: page.viewportSize(),
intervalMs: 5,
frameCount: frames.length,
frameP95Ms: frames[Math.floor(frames.length * 0.95)],
maxFrameMs: frames.at(-1),
longTasksMs: samples.longTasks,
before: before.metrics,
after: after.metrics,
},
null,
2,
),
contentType: "application/json",
});
await sampler.dispose();
await session.detach();
} finally {
await agent.cleanup();
}
});
test("manually expands complete reasoning after leaving output following", async ({
page,
}, testInfo) => {
test.setTimeout(90_000);
await page.setViewportSize({ width: 1280, height: 900 });
await page.addInitScript(() => {
localStorage.setItem(
"@paseo:app-settings",
JSON.stringify({ chatDisplay: "full", autoExpandReasoning: false }),
);
});
const agent = await seedMockAgentWorkspace({
repoPrefix: "manual-finished-reasoning-",
title: "Manual finished reasoning",
model: "ten-second-stream",
});
const historyClient = await connectDaemonClient<
Pick<DaemonClient, "connect" | "close" | "fetchAgentTimeline">
>({ clientIdPrefix: "manual-finished-reasoning-history" });
try {
await openAgentRoute(page, agent);
await expectComposerVisible(page);
await agent.client.sendAgentMessage(
agent.agentId,
"Stream briefly to check finished reasoning.",
);
const finished = await agent.client.waitForFinish(agent.agentId, 30_000);
expect(finished.status).toBe("idle");
await testInfo.attach("manual-completed-turn", {
body: JSON.stringify(finished),
contentType: "application/json",
});
const history = await historyClient.fetchAgentTimeline(agent.agentId, { limit: 500 });
const thoughts = history.entries
.map((entry) => entry.item)
.filter((item) => item.type === "reasoning");
expect(thoughts.length).toBeGreaterThan(0);
expect(thoughts.every((thought) => thought.text.length > 0)).toBe(true);
const expectedCounts = new Map<string, number>();
for (const thought of thoughts)
expectedCounts.set(thought.text, (expectedCounts.get(thought.text) ?? 0) + 1);
await testInfo.attach("manual-canonical-reasoning", {
body: JSON.stringify(thoughts, null, 2),
contentType: "application/json",
});
const pointerCapture = await page.evaluateHandle(() => {
const events: {
type: string;
timestamp: number;
tag: string;
label: string;
scrollTop: number | null;
}[] = [];
const observe = (event: Event) => {
const target = event.target;
if (!(target instanceof HTMLElement)) return;
const scroll = document.querySelector<HTMLElement>('[data-testid="agent-chat-scroll"]');
events.push({
type: event.type,
timestamp: event.timeStamp,
tag: target.tagName,
label: target.textContent?.slice(0, 80) ?? "",
scrollTop: scroll?.scrollTop ?? null,
});
};
for (const type of ["pointerdown", "pointerup", "wheel"])
document.addEventListener(type, observe, true);
return {
events,
stop: () => {
for (const type of ["pointerdown", "pointerup", "wheel"])
document.removeEventListener(type, observe, true);
},
};
});
const badges = page.getByTestId("tool-call-badge").filter({ hasText: "Thinking" });
await expect(badges).toHaveCount(thoughts.length);
// Locator scrolling alone leaves output-following armed, so pointer-down can
// snap the feed to its tail before pointer-up reaches the Thinking control.
await scrollChatAwayFromBottom(page, { deltaY: -600, minDistanceFromBottom: 100 });
for (let index = 0; index < thoughts.length; index++) {
await badges
.nth(index)
.getByRole("button", { name: "Thinking", exact: true })
.first()
.click();
await expect(
badges.nth(index).getByText(thoughts[index].text, { exact: true }),
).toBeVisible();
}
for (const [text, count] of expectedCounts)
await expect(page.getByText(text, { exact: true })).toHaveCount(count);
const first = badges.first();
await first.getByRole("button", { name: "Thinking", exact: true }).first().click();
await expect(first.getByText(thoughts[0].text, { exact: true })).not.toBeVisible();
await first.getByRole("button", { name: "Thinking", exact: true }).first().click();
await expect(first.getByText(thoughts[0].text, { exact: true })).toBeVisible();
for (const [text, count] of expectedCounts)
await expect(page.getByText(text, { exact: true })).toHaveCount(count);
await testInfo.attach("manual-expanded-reasoning", {
body: await page.screenshot(),
contentType: "image/png",
});
const pointerEvents = await pointerCapture.evaluate(({ events, stop }) => {
stop();
return events;
});
await pointerCapture.dispose();
await testInfo.attach("manual-pointer-events", {
body: JSON.stringify(pointerEvents, null, 2),
contentType: "application/json",
});
await page.reload();
await expect(badges).toHaveCount(thoughts.length);
await scrollChatAwayFromBottom(page, { deltaY: -600, minDistanceFromBottom: 100 });
for (let index = 0; index < thoughts.length; index++) {
await badges
.nth(index)
.getByRole("button", { name: "Thinking", exact: true })
.first()
.click();
await expect(
badges.nth(index).getByText(thoughts[index].text, { exact: true }),
).toBeVisible();
}
for (const [text, count] of expectedCounts)
await expect(page.getByText(text, { exact: true })).toHaveCount(count);
} catch (error) {
await testInfo.attach("manual-before-cleanup", {
body: await page.screenshot(),
contentType: "image/png",
});
throw error;
} finally {
await historyClient.close();
await agent.cleanup();
}
});
@@ -84,17 +84,14 @@ async function openModelSelector(page: Page) {
await expect(page.getByTestId("agent-controls-settings-list")).toBeVisible({ timeout: 10_000 });
}
async function dismissStackedModelPickerWithBackdrop(page: Page) {
await page
.getByTestId("agent-controls-settings-list")
.getByRole("button", { name: /Select model/ })
.click();
await expect(page.getByTestId("agent-controls-model-browser-sheet")).toBeInViewport();
await page.mouse.click(MOBILE_VIEWPORT.width / 2, 24);
// In CI, Gorhom retains the dismissed sheet below the viewport.
// Dismissal is complete when it leaves the displayed surface.
await expect(page.getByTestId("agent-controls-model-browser-sheet")).not.toBeInViewport();
await expect(page.getByTestId("agent-controls-model-sheet")).toBeVisible();
async function openModelPage(page: Page) {
await page.getByTestId("agent-controls-model").click();
await expect(page.getByTestId("mobile-model-page")).toBeVisible();
await expect(page.getByTestId("agent-controls-settings-list")).toHaveCount(0);
}
async function returnHomeWithBack(page: Page) {
await page.getByTestId("sheet-header-back").click();
await expect(page.getByTestId("agent-controls-settings-list")).toBeVisible();
}
@@ -113,7 +110,7 @@ async function openAndCloseModelSelectorTwice(page: Page) {
}
test.describe("mobile bottom sheet reopen", () => {
test("sheets reopen and model search returns to configuration", async ({ page }) => {
test("sheets reopen and a model pick returns to Home", async ({ page }) => {
const session = await openMockAgentAtMobileBreakpoint(page);
try {
await test.step("tab switcher opens, closes, and reopens", async () => {
@@ -124,24 +121,28 @@ test.describe("mobile bottom sheet reopen", () => {
await openAndCloseModelSelectorTwice(page);
});
await test.step("model search returns to configuration", async () => {
await test.step("the Model page swaps in place and Back returns to Home", async () => {
await openModelSelector(page);
const sheet = page.getByTestId("agent-controls-model-sheet");
await openModelPage(page);
await returnHomeWithBack(page);
await expect(sheet).toBeVisible();
});
await dismissStackedModelPickerWithBackdrop(page);
await page.getByTestId("model-search-all-input").click();
await test.step("a model found by search returns to Home with that model", async () => {
await openModelPage(page);
const search = page.getByTestId("model-search-all-input");
await expect(search).not.toBeFocused();
await search.click();
await search.fill("Ten second");
const model = page.getByRole("button", { name: /^Ten second stream/ });
await expect(model).toBeVisible({
timeout: 10_000,
});
await expect(model).toBeVisible({ timeout: 10_000 });
await model.click();
await expect(sheet).toBeVisible();
await expect(page.getByTestId("agent-controls-model-sheet")).toBeVisible();
await expect(page.getByTestId("agent-controls-settings-list")).toBeVisible();
await expect(page.getByTestId("agent-controls-model")).toContainText("Ten second stream");
await expect(page.getByTestId("agent-controls-model-browser-sheet")).not.toBeInViewport();
});
} finally {
await session.cleanup();
+25 -1
View File
@@ -30,7 +30,14 @@ test.use({
const ACTIVE_SPEED_COLOR = "rgb(251, 191, 36)";
const NORMAL_SPEED_COLOR = "rgb(113, 113, 122)";
const COMPACT_SPEED_CONTROL = "agent-feature-service_tier";
const COMPACT_SPEED_SECTION = `${COMPACT_SPEED_CONTROL}-section`;
async function openSpeedSelector(page: Page): Promise<void> {
const compactSection = page.getByTestId(COMPACT_SPEED_SECTION);
if (await compactSection.isVisible().catch(() => false)) {
return;
}
const speed = page.getByRole("button", { name: /^(Select speed|Speed: .+)$/ });
const features = page.getByRole("button", { name: "Open agent features", exact: true });
const modelSettings = page.getByRole("button", { name: /^Select model \(/ });
@@ -39,7 +46,12 @@ async function openSpeedSelector(page: Page): Promise<void> {
});
if (!(await speed.isVisible())) {
if (await features.isVisible()) await features.click();
else await modelSettings.click();
else {
await modelSettings.click();
await expect(compactSection).toBeVisible({ timeout: 30_000 });
await expect(compactSection.getByText("Normal", { exact: true })).toBeVisible();
return;
}
}
await expect(speed).toBeVisible({ timeout: 30_000 });
await speed.click();
@@ -47,6 +59,13 @@ async function openSpeedSelector(page: Page): Promise<void> {
}
async function selectSpeed(page: Page, label: string): Promise<void> {
const compactSection = page.getByTestId(COMPACT_SPEED_SECTION);
if (await compactSection.isVisible().catch(() => false)) {
const pill = compactSection.getByRole("button", { name: label, exact: true });
await pill.click();
await expect(pill).toHaveAttribute("aria-selected", "true");
return;
}
await page.getByRole("button", { name: label, exact: true }).last().click();
const toolbarTrigger = page.getByRole("button", { name: `Speed: ${label}`, exact: true });
const sheetTrigger = page.getByRole("button", { name: "Select speed", exact: true });
@@ -56,6 +75,11 @@ async function selectSpeed(page: Page, label: string): Promise<void> {
}
async function expectSpeedIconColor(page: Page, color: string): Promise<void> {
const compactSection = page.getByTestId(COMPACT_SPEED_SECTION);
if (await compactSection.isVisible().catch(() => false)) {
await expect(compactSection.locator("svg").first()).toHaveCSS("stroke", color);
return;
}
const trigger = page
.getByRole("button", { name: /^(Speed: .+|Select speed)$/ })
.filter({ visible: true });
@@ -387,7 +387,10 @@ test.describe("Composer model and effort shortcuts", () => {
const effortLabel = page.getByTestId("combined-model-selector-thinking-label");
await expect(effortLabel).toHaveText("Medium");
await toggleModelPickerFromComposer(page);
await expectModelPickerClosesFromSearch(page);
const drawerModelRow = page.getByTestId("agent-controls-model");
await expect(drawerModelRow).toBeVisible();
await page.keyboard.press(`${SHORTCUT_MOD}+Slash`);
await expect(drawerModelRow).toBeHidden();
await cycleComposerEffort(page);
await expect(effortLabel).toHaveText("High");
});
@@ -233,6 +233,57 @@ test("opening an agent focuses the composer when a mouse drives the UI", async (
}
});
/** The composer frame's border colour once its border-color transition has finished. */
async function readSettledFrameBorder(page: Page): Promise<string> {
return composerLocator(page).evaluate(async (input) => {
let frame = input.parentElement;
while (frame && parseFloat(getComputedStyle(frame).borderTopWidth) < 1) {
frame = frame.parentElement;
}
if (!frame) throw new Error("Composer frame has no border");
while (frame.getAnimations().length > 0) {
await new Promise((resolve) => requestAnimationFrame(resolve));
}
return getComputedStyle(frame).borderTopColor;
});
}
test("the composer frame shows hover and focus", async ({ page }) => {
const agent = await seedMockAgentWorkspace({
repoPrefix: "composer-frame-focus-",
title: "Composer frame focus",
});
try {
await openAgentRoute(page, agent);
const composer = composerLocator(page);
await expectComposerVisible(page);
await page.mouse.move(0, 0);
await blurComposerInput(page);
const rest = await readSettledFrameBorder(page);
await composer.hover();
const hover = await readSettledFrameBorder(page);
expect(hover).not.toBe(rest);
await composer.click();
await page.mouse.move(0, 0);
await expectComposerFocused(page);
const focus = await readSettledFrameBorder(page);
expect(focus).not.toBe(rest);
expect(focus).not.toBe(hover);
await composer.hover();
expect(await readSettledFrameBorder(page)).toBe(focus);
await page.mouse.move(0, 0);
await blurComposerInput(page);
expect(await readSettledFrameBorder(page)).toBe(rest);
} finally {
await agent.cleanup();
}
});
async function waitForAnimationFrames(page: Page, count: number): Promise<void> {
await page.evaluate(async (frames) => {
for (let frame = 0; frame < frames; frame += 1) {
@@ -3,9 +3,11 @@ import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import { test, expect, type Page } from "../support/fixtures";
import { connectDaemonClient } from "../support/helpers/daemon-client-loader";
import {
clearModelSearchWithEscape,
clickModelRowWhileProviderOpens,
closeModelPicker,
expectModelListScrollKeepsSearchFocused,
expectSearchProfilesAtTop,
expectModelSearchEmptyState,
expectModelPickerHeight,
expectModelPickerWidth,
@@ -19,7 +21,12 @@ import {
seedModelProvider,
expectSearchResultsVirtualized,
} from "../support/helpers/agent-profiles";
import { expectComposerVisible } from "../support/helpers/composer";
import {
blurComposerInput,
expectComposerFocused,
expectComposerVisible,
} from "../support/helpers/composer";
import { openGlobalNewWorkspaceComposer } from "../support/helpers/new-workspace";
import { clickNewChat, clickNewTerminal, gotoWorkspace } from "../support/helpers/launcher";
import { seedWorkspace } from "../support/helpers/seed-client";
@@ -56,9 +63,7 @@ const LARGE_CATALOG = {
};
test.describe("Cross-provider model search", () => {
test("one query over the picker root reaches every provider and names each result's provider", async ({
page,
}) => {
test("one query reaches every provider and names each result's provider", async ({ page }) => {
const provider = await seedModelProvider(STUDIO);
const profile = await seedAgentProfiles([ROOT_VIEW_PROFILE]);
const workspace = await seedWorkspace({ repoPrefix: "model-search-providers-" });
@@ -99,7 +104,7 @@ test.describe("Cross-provider model search", () => {
});
});
await test.step("results replace the pinned profiles", async () => {
await test.step("results replace the Profiles list", async () => {
await expectPinnedProfilesHidden(page);
});
@@ -108,6 +113,10 @@ test.describe("Cross-provider model search", () => {
await test.step("a query with no matches repeats the query back", async () => {
await searchAllModels(page, "zzz");
await expectModelSearchEmptyState(page, "zzz");
});
await test.step("Escape clears the query before it closes the picker", async () => {
await clearModelSearchWithEscape(page);
await closeModelPicker(page);
});
} finally {
@@ -135,16 +144,23 @@ test.describe("Cross-provider model search", () => {
const restingHeight = await readModelPickerHeight(page);
const restingWidth = await readModelPickerWidth(page);
await test.step("a broad query renders only the visible result window", async () => {
await test.step("a broad query renders only the visible result window and scrolls without leaving search", async () => {
await searchAllModels(page, "bulk model");
await expectSearchResultsVirtualized(page, {
provider: LARGE_CATALOG.id,
total: LARGE_CATALOG_SIZE,
});
await expectModelListScrollKeepsSearchFocused(page);
await expectModelPickerHeight(page, restingHeight);
await expectModelPickerWidth(page, restingWidth);
});
await test.step("a new query opens at the top, with the Profiles heading above the matching profile", async () => {
// "search" matches the profile's name and every bulk model's description.
await searchAllModels(page, "search");
await expectSearchProfilesAtTop(page, ROOT_VIEW_PROFILE.id);
});
await test.step("narrowing to one result does not resize the picker", async () => {
await searchAllModels(page, "bulk model 199");
await expectModelSearchResult(page, {
@@ -179,7 +195,7 @@ test.describe("Cross-provider model search", () => {
}
});
test("arrow keys navigate profiles, providers, models, and search results in the composer", async ({
test("arrow keys move between the rail, the model list, and search results in the composer", async ({
page,
}) => {
const provider = await seedModelProvider(STUDIO);
@@ -194,7 +210,7 @@ test.describe("Cross-provider model search", () => {
const workspace = await seedWorkspace({ repoPrefix: "model-picker-arrows-" });
try {
await test.step("open the composer model picker on the root view", async () => {
await test.step("open the composer model picker", async () => {
await gotoWorkspace(page, workspace.workspaceId);
await clickNewChat(page);
await expectComposerVisible(page);
@@ -204,32 +220,42 @@ test.describe("Cross-provider model search", () => {
const viewport = page.getByTestId("combobox-desktop-container");
const trigger = page.getByTestId("combined-model-selector").filter({ visible: true }).first();
const profileRow = viewport.getByTestId("model-profile-row-agent_profile_e2e_arrows");
const profilesRailRow = viewport.getByTestId("model-picker-rail-profiles");
const studioProviderRow = viewport.getByTestId(`model-provider-${STUDIO.id}`);
await test.step("move from profiles to providers, drill in with ArrowRight, and go back with ArrowLeft", async () => {
await expect(profileRow).toHaveAttribute("data-active", "true");
// Root view keeps aria-selected absent while keyboard-active uses data-active.
await expect(viewport.locator("[aria-selected]")).toHaveCount(0);
await test.step("ArrowLeft moves to the rail, ArrowDown opens each entry, ArrowRight enters its list", async () => {
await page.keyboard.press("ArrowLeft");
// The rail opens what it lands on, so ArrowUp from any provider reaches Profiles.
for (let step = 0; step < 10; step += 1) {
if ((await profilesRailRow.getAttribute("data-active")) === "true") break;
await page.keyboard.press("ArrowUp");
}
await expect(profilesRailRow).toHaveAttribute("data-active", "true");
await expect(profileRow).toBeVisible();
// Step down until Mock Studio is active (provider order can vary across environments).
// Step down until Mock Studio is open (provider order can vary across environments).
for (let step = 0; step < 10; step += 1) {
if ((await studioProviderRow.getAttribute("data-active")) === "true") break;
await page.keyboard.press("ArrowDown");
}
await expect(studioProviderRow).toHaveAttribute("data-active", "true");
await page.keyboard.press("ArrowRight");
await expect(viewport.getByTestId(`model-row-${STUDIO.id}-studio-fast`)).toBeVisible();
await page.keyboard.press("ArrowRight");
await expect(viewport.getByTestId(`model-row-${STUDIO.id}-studio-fast`)).toHaveAttribute(
"data-active",
"true",
);
await page.keyboard.press("ArrowLeft");
await expect(studioProviderRow).toHaveAttribute("data-active", "true");
await expect(
viewport.locator('[data-testid^="model-row-"][data-active="true"]'),
).toHaveCount(0);
});
await test.step("Enter drills into the active provider and ArrowDown + Enter selects a model", async () => {
await test.step("Enter moves from the rail into the list and ArrowDown + Enter selects a model", async () => {
await page.keyboard.press("Enter");
const deepRow = viewport.getByTestId(`model-row-${STUDIO.id}-studio-deep`);
await expect(deepRow).toBeVisible();
await expectModelListScrollKeepsSearchFocused(page);
for (let step = 0; step < 5; step += 1) {
if ((await deepRow.getAttribute("data-active")) === "true") break;
@@ -240,6 +266,7 @@ test.describe("Cross-provider model search", () => {
await page.keyboard.press("Enter");
await expect(viewport).toHaveCount(0);
await expect(trigger).toContainText("Studio deep think");
await expectComposerFocused(page);
});
await test.step("typing filters results while arrow keys select across search matches", async () => {
@@ -258,6 +285,7 @@ test.describe("Cross-provider model search", () => {
await page.keyboard.press("Enter");
await expect(viewport).toHaveCount(0);
await expect(trigger).toContainText("Ten second stream");
await expectComposerFocused(page);
});
await test.step("a press on a model row selects it while the provider list is still opening", async () => {
@@ -265,27 +293,42 @@ test.describe("Cross-provider model search", () => {
await clickModelRowWhileProviderOpens(page, {
provider: "mock",
modelLabel: "One minute stream",
otherProvider: STUDIO.id,
});
await expect(viewport).toHaveCount(0);
await expect(trigger).toContainText("One minute stream");
await expectComposerFocused(page);
});
await test.step("Enter on the active profile row applies it", async () => {
await openModelPicker(page);
await page.keyboard.press("ArrowLeft");
for (let step = 0; step < 10; step += 1) {
if ((await profilesRailRow.getAttribute("data-active")) === "true") break;
await page.keyboard.press("ArrowUp");
}
await page.keyboard.press("ArrowRight");
await expect(profileRow).toHaveAttribute("data-active", "true");
await page.keyboard.press("Enter");
await expect(viewport).toHaveCount(0);
await expect(trigger).toContainText("Ten second stream");
await expectComposerFocused(page);
});
await test.step("folded compact sheet also supports Enter on the active profile row", async () => {
await test.step("the compact drawer puts Profiles in the Model accordion and lets all groups collapse", async () => {
await page.setViewportSize({ width: 390, height: 800 });
await page.getByTestId("combined-model-selector").filter({ visible: true }).first().click();
await expect(page.getByTestId("agent-controls-profiles")).toHaveCount(0);
await page.getByTestId("agent-controls-model").click();
await expect(page.getByTestId("compact-model-list")).toBeVisible();
await page.locator('[data-testid^="model-provider-section-"]').first().click();
await expect(page.getByTestId("compact-model-list")).toHaveCount(0);
await page.getByTestId("model-picker-rail-profiles").click();
const sheetProfileRow = page.getByTestId("model-profile-row-agent_profile_e2e_arrows");
await expect(sheetProfileRow).toBeVisible();
await expect(sheetProfileRow).toHaveAttribute("data-active", "true");
await page.keyboard.press("Enter");
await sheetProfileRow.click();
await expect(sheetProfileRow).toHaveCount(0);
await expect(page.getByTestId("agent-controls-model-sheet")).not.toBeInViewport();
});
} finally {
await workspace.cleanup();
@@ -293,6 +336,43 @@ test.describe("Cross-provider model search", () => {
await provider.restore();
}
});
test("choosing a model restores composer focus in workspace drafts and New Workspace", async ({
page,
}) => {
const provider = await seedModelProvider(STUDIO);
const workspace = await seedWorkspace({ repoPrefix: "model-picker-focus-" });
try {
await test.step("clicking a model after blurring the workspace draft returns focus to the composer", async () => {
await gotoWorkspace(page, workspace.workspaceId);
await clickNewChat(page);
await expectComposerVisible(page);
await blurComposerInput(page);
await openModelPicker(page);
const viewport = page.getByTestId("combobox-desktop-container");
await viewport.getByTestId(`model-provider-${STUDIO.id}`).click();
await viewport.getByTestId(`model-row-${STUDIO.id}-studio-deep`).click();
await expect(viewport).toHaveCount(0);
await expectComposerFocused(page);
});
await test.step("clicking a model on the New Workspace screen returns focus to the composer", async () => {
await openGlobalNewWorkspaceComposer(page);
await expectComposerVisible(page);
await blurComposerInput(page);
await openModelPicker(page);
const viewport = page.getByTestId("combobox-desktop-container");
await viewport.getByTestId(`model-provider-${STUDIO.id}`).click();
await viewport.getByTestId(`model-row-${STUDIO.id}-studio-fast`).click();
await expect(viewport).toHaveCount(0);
await expectComposerFocused(page);
});
} finally {
await workspace.cleanup();
await provider.restore();
}
});
});
async function setRuntimeCatalog(client: DaemonClient, count: number, cwd: string) {
@@ -332,7 +412,6 @@ async function reloadSavedDraft(page: Page) {
}
async function expectOneCatalogChoice(page: Page, label: string) {
await openModelPicker(page);
await page.getByRole("button", { name: "Back", exact: true }).click();
await searchAllModels(page, label);
await expect(page.getByTestId("model-row-gemini-gemini-3.5-flash")).toHaveCount(1);
await closeModelPicker(page);
@@ -34,7 +34,6 @@ async function rememberModel(page: Page) {
async function expectRecoveredModelInPicker(page: Page) {
await openModelPicker(page);
await page.getByRole("dialog").getByRole("button", { name: "Back", exact: true }).click();
await drillIntoProvider(page, PROVIDER);
await expect(
page.getByTestId("combobox-desktop-container").getByText(LABEL, { exact: true }),
@@ -26,16 +26,14 @@ async function openProviderSettingsFromModelSelector(page: Page) {
const configuration = page.getByTestId("agent-controls-model-sheet");
await expect(configuration).toBeVisible({ timeout: 10_000 });
await page.getByTestId("agent-controls-model").click();
const modelBrowser = page.getByTestId("agent-controls-model-browser-sheet");
await expect(modelBrowser).toBeVisible({ timeout: 10_000 });
await expect(page.getByTestId("mobile-model-page")).toBeVisible({ timeout: 10_000 });
await page.getByRole("button", { name: /Open .* settings/ }).click();
await expect(page.getByTestId("provider-settings-sheet")).toBeVisible({ timeout: 10_000 });
}
async function expectModelBrowserVisible(page: Page) {
await expect(page.getByTestId("agent-controls-model-browser-sheet")).toBeVisible({
async function expectModelPageVisible(page: Page) {
await expect(page.getByTestId("mobile-model-page")).toBeVisible({
timeout: 10_000,
});
await expect(page.getByRole("button", { name: /Open .* settings/ })).toBeVisible();
@@ -187,7 +185,7 @@ test.describe("provider settings overlay stack", () => {
}
});
test("provider settings and children close back through the model browser to configuration", async ({
test("provider settings and children close back to the Model page, then Back reaches Home", async ({
page,
}) => {
test.setTimeout(180_000);
@@ -199,17 +197,15 @@ test.describe("provider settings overlay stack", () => {
await exerciseProviderSettingsStack(page);
await closeSheetByHeaderButton(page, "provider-settings-sheet");
await expectModelBrowserVisible(page);
await expectModelPageVisible(page);
await page.getByRole("button", { name: /Open .* settings/ }).click();
await expect(page.getByTestId("provider-settings-sheet")).toBeVisible({ timeout: 10_000 });
await exerciseProviderSettingsStack(page);
await closeSheetByHeaderButton(page, "provider-settings-sheet");
await expectModelBrowserVisible(page);
await closeTopSheet(page);
await expect(page.getByTestId("agent-controls-model-browser-sheet")).not.toBeVisible({
timeout: 10_000,
});
await expectModelPageVisible(page);
await page.getByTestId("sheet-header-back").click();
await expect(page.getByTestId("mobile-model-page")).toHaveCount(0);
await expect(page.getByTestId("agent-controls-settings-list")).toBeVisible();
await closeTopSheet(page);
} finally {
@@ -226,8 +222,6 @@ async function openTimedOutProvider(page: Page, workspaceId: string, width: numb
await page.getByRole("button", { name: /Select model/ }).click();
if (width < 600) {
await page.getByTestId("agent-controls-model").click();
} else {
await page.getByRole("button", { name: "Back", exact: true }).click();
}
await page.getByTestId("model-provider-picker-timeout").click();
await expect(page.getByText(/Timed out refreshing Pi timeout/)).toBeVisible();
@@ -13,8 +13,12 @@ import { test, expect } from "../support/fixtures";
import { expectComposerVisible } from "../support/helpers/composer";
import { withDirectoryPlugin } from "../support/helpers/plugin-timeline";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import { getE2EDaemonPort } from "../support/helpers/daemon-port";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
test.use({
e2eInjectPaseoTools: true,
e2eDaemonConfig: {
version: 1,
agents: {
@@ -290,6 +294,89 @@ test("received messages show their sender and open that agent", async ({ page })
}
});
/** Calls a Paseo MCP tool as `callerAgentId`, the way that agent's provider would. */
async function callPaseoToolAs(
callerAgentId: string,
name: string,
args: Record<string, unknown>,
): Promise<Record<string, unknown>> {
const mcp = new Client({ name: "turn-collapse-e2e", version: "1" });
await mcp.connect(
new StreamableHTTPClientTransport(
new URL(`http://127.0.0.1:${getE2EDaemonPort()}/mcp/agents?callerAgentId=${callerAgentId}`),
),
);
try {
const response = await mcp.callTool({ name, arguments: args });
expect(response, name).not.toMatchObject({ isError: true });
return response.structuredContent as Record<string, unknown>;
} finally {
await mcp.close();
}
}
test("a delegated child reports each turn end as a compact tool call until its own delegate is done", async ({
page,
}, testInfo) => {
const frames: string[] = [];
page.on("websocket", (socket) => {
socket.on("framereceived", ({ payload }) => {
if (typeof payload === "string") frames.push(payload);
});
});
const childNoticeFrames = () => frames.filter((frame) => frame.includes('"label":"Child"'));
const parent = await seedMockAgentWorkspace({ repoPrefix: "child-notices-", title: "Lead" });
try {
await openAgentRoute(page, parent);
await expectComposerVisible(page);
const child = await callPaseoToolAs(parent.agentId, "create_agent", {
workspaceId: parent.workspaceId,
title: "Child",
provider: "mock/e2e-fast-stream",
settings: { modeId: "load-test" },
initialPrompt: "Delegate the slow part",
});
const childId = String(child.agentId);
// The child's own delegate outlives the child's first turn.
const grandchild = await callPaseoToolAs(childId, "create_agent", {
workspaceId: parent.workspaceId,
title: "Grandchild",
provider: "mock/ten-second-stream",
settings: { modeId: "load-test" },
initialPrompt: "Take your time",
});
const notices = page.getByRole("button", { name: /^Agent .*Child/ });
const finished = page.getByRole("button", { name: /^Agent finished.*Child/ });
// The child ended its turn while waiting on its delegate: the parent hears it now.
await expect(finished).toHaveCount(1, { timeout: 30_000 });
const delegate = await parent.client.waitForAgentUpsert(String(grandchild.agentId), () => true);
expect(delegate.status, "the delegate must still be running").toBe("running");
expect(
childNoticeFrames().some((frame) => frame.includes("It still has agents it is waiting on.")),
).toBe(true);
// The delegate reports to the child, and the child's settled turn reaches the parent.
await expect(finished).toHaveCount(2, { timeout: 60_000 });
await expect(notices).toHaveCount(2);
await expect(page.getByText(/still working/i)).toHaveCount(0);
await expect(page.getByText(/Sent by/)).toHaveCount(0);
await expect(page.getByText(/<agent-response>/)).toHaveCount(0);
await finished.last().scrollIntoViewIfNeeded();
await page.screenshot({ path: testInfo.outputPath("child-notices.png") });
// Notification events stay on the daemon: clients get only plain tool calls.
expect(frames.filter((frame) => frame.includes('"agentMessage"'))).toEqual([]);
expect(childNoticeFrames().some((frame) => frame.includes('"name":"agent_finished"'))).toBe(
true,
);
expect(childNoticeFrames().filter((frame) => /"name":"agent_(?!finished)/.test(frame))).toEqual(
[],
);
} finally {
await parent.cleanup();
}
});
test("long sender attribution stays on one line in compact chat", async ({ page }, testInfo) => {
await page.setViewportSize({ width: 390, height: 844 });
await page.addInitScript(() =>
@@ -587,7 +587,12 @@ export async function openModelPicker(page: Page): Promise<void> {
await expect(pickerViewport(page)).toBeVisible({ timeout: 30_000 });
}
/** Escape clears a typed query first; the next Escape closes the picker. */
export async function closeModelPicker(page: Page): Promise<void> {
const search = pickerViewport(page).getByTestId("model-search-input");
if ((await search.count()) > 0 && (await search.inputValue()) !== "") {
await clearModelSearchWithEscape(page);
}
await page.keyboard.press("Escape");
await expect(pickerViewport(page)).toHaveCount(0, { timeout: 30_000 });
}
@@ -598,70 +603,40 @@ export function profilePickerRow(page: Page, name: string): Locator {
.filter({ hasText: name });
}
/**
* Profiles are pinned above the provider list, so "pinned" is an ordering claim:
* the profile row's top edge sits above every provider row's.
*/
export async function expectProfilePinnedAboveProviders(
page: Page,
input: { name: string; summary: string },
): Promise<void> {
const viewport = pickerViewport(page);
await expect(viewport.getByText("Profiles", { exact: true })).toBeVisible({ timeout: 30_000 });
const row = profilePickerRow(page, input.name);
await expect(row).toBeVisible({ timeout: 30_000 });
await expect(row.getByText(input.summary, { exact: true })).toBeVisible();
const profileTop = await boxTop(row);
const providerRows = viewport.locator('[data-testid^="model-provider-"]');
await expect(providerRows.first()).toBeVisible();
const providerCount = await providerRows.count();
for (let index = 0; index < providerCount; index += 1) {
expect(profileTop).toBeLessThan(await boxTop(providerRows.nth(index)));
}
/** Desktop keeps profiles behind the rail's Profiles entry, beside the providers. */
export async function openPickerProfiles(page: Page): Promise<void> {
await pickerViewport(page).getByTestId("model-picker-rail-profiles").click();
}
export async function expectProfileVisibleForProvider(
export async function expectPickerProfile(
page: Page,
input: { name: string; summary: string },
): Promise<void> {
const viewport = pickerViewport(page);
await expect(viewport.getByText("Profiles", { exact: true })).toBeVisible({ timeout: 30_000 });
await openPickerProfiles(page);
const row = profilePickerRow(page, input.name);
await expect(row).toBeVisible({ timeout: 30_000 });
await expect(row.getByText(input.summary, { exact: true })).toBeVisible();
}
export async function expectProfileEditIsPencilOnly(page: Page): Promise<void> {
const viewport = pickerViewport(page);
await expect(
viewport.getByRole("button", { name: "Edit agent profiles", exact: true }),
).toBeVisible();
await expect(viewport.getByText("Edit", { exact: true })).toHaveCount(0);
}
export async function expectAgentProfilesEmptyPrompt(page: Page): Promise<void> {
const viewport = pickerViewport(page);
await expect(viewport.getByText("Profiles", { exact: true })).toHaveCount(0);
await expect(
viewport.getByRole("button", { name: "Edit agent profiles", exact: true }),
).toHaveCount(0);
await expect(viewport.getByRole("button", { name: "Create profile", exact: true })).toBeVisible({
timeout: 30_000,
});
}
export async function expectProfileEditTooltip(page: Page): Promise<void> {
export async function expectProfilesEditLink(page: Page): Promise<void> {
const edit = pickerViewport(page).getByRole("button", {
name: "Edit agent profiles",
exact: true,
});
await edit.hover();
await expect(page.getByText("Edit agent profiles", { exact: true })).toBeVisible();
await expect(edit).toBeVisible();
await expect(edit).toHaveText("Edit");
}
/** With no profiles, the Profiles entry offers to create one instead of listing any. */
export async function expectAgentProfilesEmptyPrompt(page: Page): Promise<void> {
await openPickerProfiles(page);
const viewport = pickerViewport(page);
await expect(viewport.locator('[data-testid^="model-profile-row-"]')).toHaveCount(0);
await expect(viewport.getByTestId("model-profiles-empty")).toBeVisible({ timeout: 30_000 });
}
export async function openAgentProfilesFromEmptyPrompt(page: Page): Promise<void> {
await pickerViewport(page).getByRole("button", { name: "Create profile", exact: true }).click();
await pickerViewport(page).getByTestId("model-profiles-empty").click();
await expect(page.getByTestId("agent-profiles-card")).toBeVisible({ timeout: 30_000 });
}
@@ -709,25 +684,17 @@ export async function expectProfileReachableByScrolling(page: Page, name: string
}
export async function applyProfileFromPicker(page: Page, name: string): Promise<void> {
await profilePickerRow(page, name).click();
const row = profilePickerRow(page, name);
if (!(await row.isVisible().catch(() => false))) {
const profilesRail = pickerViewport(page).getByTestId("model-picker-rail-profiles");
if (await profilesRail.isVisible().catch(() => false)) {
await profilesRail.click();
}
}
await row.click();
await expect(pickerViewport(page)).toHaveCount(0, { timeout: 30_000 });
}
/**
* Applying a profile materializes it and forgets it: nothing in the root view
* claims selection. Model rows do carry `aria-selected`, so a count of zero here
* is the absence of a checkmark, not the absence of the attribute everywhere.
*/
export async function expectNothingSelectedInPickerRoot(page: Page): Promise<void> {
await expect(pickerViewport(page).locator("[aria-selected]")).toHaveCount(0);
}
export async function expectAgentProfilesEditShortcut(page: Page): Promise<void> {
await expect(
pickerViewport(page).getByRole("button", { name: "Edit agent profiles", exact: true }),
).toBeVisible({ timeout: 30_000 });
}
export async function drillIntoProvider(page: Page, providerId: string): Promise<void> {
await pickerViewport(page).getByTestId(`model-provider-${providerId}`).click();
}
@@ -798,13 +765,13 @@ export async function selectModelRow(
*/
export async function clickModelRowWhileProviderOpens(
page: Page,
input: { provider: string; modelLabel: string },
input: { provider: string; modelLabel: string; otherProvider: string },
): Promise<void> {
const viewport = pickerViewport(page);
await drillIntoProvider(page, input.provider);
const rowBox = await viewport.getByText(input.modelLabel, { exact: true }).boundingBox();
if (!rowBox) throw new Error(`Model row ${input.modelLabel} has no box`);
await viewport.getByRole("button", { name: "Back", exact: true }).click();
await drillIntoProvider(page, input.otherProvider);
const cdp = await page.context().newCDPSession(page);
await cdp.send("Emulation.setCPUThrottlingRate", { rate: 10 });
@@ -822,7 +789,7 @@ export async function clickModelRowWhileProviderOpens(
/** Scrolling a provider's model list with the wheel leaves typing and Enter in the search field. */
export async function expectModelListScrollKeepsSearchFocused(page: Page): Promise<void> {
const search = pickerViewport(page).getByTestId("model-search-input");
const list = pickerViewport(page).getByTestId("compact-model-list");
const list = pickerViewport(page).getByTestId("model-picker-model-list");
await expect(search).toBeFocused();
await list.hover();
await page.mouse.wheel(0, 200);
@@ -833,11 +800,18 @@ export async function expectModelListScrollKeepsSearchFocused(page: Page): Promi
// ─── Cross-provider model search ───────────────────────────────────────────
export async function searchAllModels(page: Page, query: string): Promise<void> {
const input = page.getByTestId("model-search-all-input");
const input = pickerViewport(page).getByTestId("model-search-input");
await expect(input).toBeVisible({ timeout: 30_000 });
await input.fill(query);
}
/** Search results open at the top, with the Profiles heading above the first matching profile. */
export async function expectSearchProfilesAtTop(page: Page, profileId: string): Promise<void> {
const list = pickerViewport(page).getByTestId("model-picker-model-list");
await expect(list.getByText("Profiles", { exact: true })).toBeInViewport({ ratio: 1 });
await expect(list.getByTestId(`model-profile-row-${profileId}`)).toBeInViewport({ ratio: 1 });
}
export async function expectModelSearchResult(
page: Page,
expected: { provider: string; modelId: string; providerLabel: string; modelLabel: string },
@@ -856,11 +830,19 @@ function escapeForRegex(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
/** Search results replace the whole root view, pinned profiles included. */
/** Search results replace both panes, the Profiles list included. */
export async function expectPinnedProfilesHidden(page: Page): Promise<void> {
await expect(pickerViewport(page).locator('[data-testid^="model-profile-row-"]')).toHaveCount(0);
}
export async function clearModelSearchWithEscape(page: Page): Promise<void> {
const search = pickerViewport(page).getByTestId("model-search-input");
await page.keyboard.press("Escape");
await expect(search).toHaveValue("");
await expect(search).toBeFocused();
await expect(pickerViewport(page)).toBeVisible();
}
export async function expectModelSearchEmptyState(page: Page, query: string): Promise<void> {
const empty = page.getByTestId("model-search-empty");
await expect(empty).toBeVisible({ timeout: 30_000 });
+6 -4
View File
@@ -362,8 +362,8 @@ export const selectModel = async (page: Page, model: string) => {
// Type to search/filter models
await searchInput.fill(normalizedModel);
const dialog = page.getByRole("dialog");
const exactOption = dialog
const viewport = page.getByTestId("combobox-desktop-container").or(page.getByRole("dialog"));
const exactOption = viewport
.getByText(new RegExp(`^${escapeRegex(normalizedModel)}$`, "i"))
.first();
const exactVisible = await exactOption.isVisible().catch(() => false);
@@ -375,8 +375,10 @@ export const selectModel = async (page: Page, model: string) => {
await searchInput.press("Enter");
}
// Wait for dropdown to close
if (await searchInput.isVisible().catch(() => false)) {
// Wait for dropdown to close; when a query has no match, the first Escape clears the query
// and the second closes the picker.
for (let attempt = 0; attempt < 2; attempt += 1) {
if (!(await searchInput.isVisible().catch(() => false))) break;
await page.keyboard.press("Escape").catch(() => undefined);
}
await expect(searchInput).not.toBeVisible({ timeout: 5000 });
@@ -17,7 +17,6 @@ export async function chooseModel(page: Page, provider: string, label: string) {
export async function reselectModel(page: Page, provider: string, label: string) {
await expectRememberedModel(page, label);
await openModelPicker(page);
await page.getByRole("dialog").getByRole("button", { name: "Back", exact: true }).click();
await selectProviderModel(page, provider, label);
}
@@ -44,9 +44,8 @@ async function expectProviderIcon(surface: Locator, paths: string[]): Promise<vo
async function selectPluginModel(page: Page): Promise<void> {
await openModelPicker(page);
await page.getByRole("button", { name: "Back", exact: true }).click();
await page.getByText("Direct provider example", { exact: true }).click();
await page.getByText("Example 1", { exact: true }).click();
await page.getByTestId("model-provider-direct-example").click();
await page.getByTestId("model-row-direct-example-example-1").click();
await expect(page.getByRole("button", { name: MODEL_LABEL, exact: true })).toBeVisible();
}
+9 -10
View File
@@ -463,16 +463,15 @@ export async function delegateFleetThroughMcp() {
direction: "tail",
limit: 100,
});
return timeline.entries
.flatMap(({ item }) =>
item.type === "tool_call" && item.agentMessage ? [item.agentMessage] : [],
)
.filter(
(message) =>
message.event === "finished" &&
message.sender.id === child.agentId &&
message.text.includes(`Server: ${child.serverId}`),
).length;
return timeline.entries.filter(
({ item }) =>
item.type === "tool_call" &&
item.name === "agent_finished" &&
item.detail.type === "plain_text" &&
item.detail.label === child.title &&
item.detail.text?.includes(child.agentId) &&
item.detail.text.includes(`Server: ${child.serverId}`),
).length;
})
.toBe(1);
},
-3
View File
@@ -1,3 +0,0 @@
node_modules/
desktop/build/
desktop/autolink/
-3
View File
@@ -1,3 +0,0 @@
workspaces=false
legacy-peer-deps=true
install-links=true
-283
View File
@@ -1,283 +0,0 @@
# Experimental GPUI client
Run Paseo's existing React Native app in a native GPUI window on Linux or macOS. This is
a community starting point: the real workspace UI runs, but terminal/diff
renderers and several native services still need porting. The normal desktop
build remains Electron. The native app connects to a separately running daemon.
## Run it
Start from the repository's [development setup](../../../docs/development.md).
A fresh checkout needs the root dependencies and workspace build outputs:
```sh
npm ci
npm run build:server
npm run gpui:install
EXPO_PUBLIC_LOCAL_DAEMON=localhost:6768 npm run dev:gpui
```
Use an already-running compatible daemon and replace `localhost:6768` with its
endpoint. These GPUI commands never start or restart a daemon. The address is
inlined at bundle time. The app's normal connection/authentication rules apply.
You also need Rust stable through rustup, CMake, Ninja, Clang, Linux X11/Wayland
development libraries, and Vulkan. The tested Linux x86_64 host already had
most build tools; it additionally needed `libxkbcommon-x11-dev`. A clean-machine
prerequisite check is still needed. The first native build downloads dependencies
and builds Rust/C++; allow several minutes and several GB of disk.
`dev:gpui` bundles the app, autolinks native modules, builds, and opens the window.
Restart after editing. It uses an offline production JS bundle; Fast Refresh is
not wired into this launcher. `build:gpui` builds without opening a window.
`gpui:bundle -- --dev false` only writes the JS bundle, source map, and assets to
`.artifacts/gpui/`. Bundle validation checks that the real routes are present and
that no `react-native-webview` modules were included.
## Build a macOS test DMG
On an Apple Silicon Mac, install the dependencies above plus Xcode, CMake, and
Ninja. From the repository root, after `npm run gpui:install`:
```sh
gpui_repo_root="$PWD"
cd packages/app/gpui
MACOSX_DEPLOYMENT_TARGET=15.0 NODE_OPTIONS=--max-old-space-size=6144 CARGO_BUILD_JOBS=4 \
CARGO_TARGET_DIR="$gpui_repo_root/.artifacts/gpui/macos/target" \
PASEO_RENDERER=gpui EXPO_PUBLIC_LOCAL_DAEMON=localhost:6767 \
node node_modules/react-native/cli.js package-desktop \
--target app,dmg --out "$gpui_repo_root/.artifacts/gpui/macos/dist"
```
Use the React Native CLI entry point shown here; the standalone GPUI CLI rejects
`package-desktop`. Keep one absolute `CARGO_TARGET_DIR` for both compilation and
packaging because their default target directories differ. Metro needs more than
Node's default 2 GiB heap for this app.
Keep `MACOSX_DEPLOYMENT_TARGET` aligned with `desktop/desktop.json` when building
from source; it controls both Rust and CMake's macOS API availability.
The DMG requires macOS 15 or later, matching the bundled Hermes/JSI libraries.
It contains `Paseo GPUI.app` with ad-hoc signing and the library-validation
exception required for loading ad-hoc dylibs under hardened runtime. It is not
notarized or signed with Developer ID. Copy it out of the mounted DMG before testing. Its daemon
address is fixed at bundle time, and the installer does not include a daemon.
Native terminals and diff rendering remain unsupported.
Check the installed bundle before sharing it:
```sh
node packages/app/gpui/verify-macos-package.mjs "/Applications/Paseo GPUI.app"
```
This checks the sealed signature, ad-hoc library-loading entitlement, and the
minimum macOS version of each bundled dylib. A successful launch on a Mac with
SIP disabled does not test Team ID library validation; verify the signing policy
and use a Mac with SIP enabled for distribution launch acceptance.
Namespace GUI testing needs an active remote desktop session; SSH alone can leave
GPUI waiting for a display. Use Namespace's `devbox desktop` commands before
launching the app. Keep Cargo's generated debug-symbol symlink intact when
rebuilding; the packager copies its contents alongside the installer.
## Rules for working on this target
iOS, Android, web, and macOS all run from the same app code. This target does too.
- **Change the app as little as possible.** Add what GPUI needs in GPUI-specific
code. Do not edit shared app code to make GPUI work.
- **Select GPUI code with a GPUI-specific Metro rule.** A `.gpui.ts` / `.gpui.tsx`
file sits next to the `.native` and `.web` files it stands in for.
`desktop/metro.config.js` prepends `gpui.<ext>` entries to
`resolver.sourceExts`, so Metro resolves `.gpui.*` ahead of `.desktop.`,
`.native.`, and base extensions. No other target (iOS, Android, web, or
Electron) resolves `.gpui.*`. `adapters/` holds package-level redirects only.
- **Fill the branches where it matters.** A piece the app needs and GPUI lacks,
such as markdown, selection in the chat, or diffs, gets a GPUI implementation
behind the interface the app already uses.
- **Fix the renderer, not the React code.** When something looks or behaves
wrong only on GPUI, such as the tab track, the same React code is correct on
every other platform. The defect is in [getpaseo/react-native-gpui](https://github.com/getpaseo/react-native-gpui); fix it there.
## Approach and renderer choice
```text
Existing Paseo RootApp + Expo Router + state/client/plugin code
|
React in Hermes
|
React Native Fabric
|
Rust GPUI native renderer
|
Linux GPU window
Existing Paseo client <-- WebSocket --> separately running Node daemon
```
The separate npm project is deliberate: the selected runtime uses RN 0.87.1,
while Paseo's mobile app uses RN 0.86.3. Metro redirects native dependencies to
that installation and resolves the rest from the app. This avoids changing the
mobile dependency baseline just to try another renderer. It also creates a
version-maintenance cost that needs testing before this becomes a supported target.
The choice was to preserve the existing app's RN component and library contracts:
| Candidate | Integration model | Consequence for this experiment |
| ----------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Streetwriters react-native-gpui](https://github.com/streetwriters/react-native-gpui/tree/de11aa265e6fb36c80e8a30315bce6d34a9be7d6) | React Native Fabric, Hermes, and GPUI, with ports of screens, gestures, Reanimated/worklets, safe areas, and SVG | Chosen because it lets the existing RN app reach a real Linux window with targeted adapters. These ports are still experimental. |
| [natew/react-native-gpui](https://github.com/natew/react-native-gpui/tree/b2254543357f02fdd983d0d8a584d1d1bd93f5da) | Custom React reconciler with an RN-like component surface; its README targets macOS arm64/Metal | Useful implementation reference. Running this Linux app would also require platform work and compatibility with the RN libraries it imports. |
| [GPUIX](https://github.com/remorses/gpuix) | Custom React/Solid renderer, its own JSX primitives, and Node-API native bindings; supports Bun/Node execution | Also native GPUI, with interesting packaging and specialized surfaces. Adopting it would require replacing or adapting Paseo's RN component/library contracts. It remains an alternative worth testing, not a rejected renderer. |
| Existing Electron target | RN Web inside Chromium, with the desktop host bridge | Preserves the working desktop feature set, but does not answer the experiment's question of running the app through a native renderer. |
This is an integration choice, not a performance comparison. There are no
controlled CPU, memory, startup, or frame-time results against these alternatives.
## What belongs in the change
| Area | Why it is here |
| ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `packages/app/gpui/package.json` and `package-lock.json` | Pinned tarballs from a [getpaseo/react-native-gpui](https://github.com/getpaseo/react-native-gpui/releases) release (`paseo-*`) for `@react-native-gpui/{cli,codegen,core,hermes}` and the seven `@react-native-gpui/*` modules. |
| `packages/app/gpui/desktop/Cargo.lock` | Pins Rust crates for the desktop shell (`../node_modules/@react-native-gpui/core/ReactGpui/...` path dependencies). |
| `desktop/`, `index.js`, `routes.js`, Metro/Babel config, root launcher | Register the full app, select the native runtime, compile native services, and bundle the actual route graph. The explicit route context prevents an apparently successful build with no app routes. |
| `adapters/` | Desktop implementations of npm packages used by the app, plus explicit unavailable-capability implementations for mobile packages. Limited ports, not complete replacements for Expo/Unistyles. App-module overrides live next to the shared files as `.gpui.ts` / `.gpui.tsx`. |
| Shared app edits | One capability gate for alpha-mask shimmer. GPUI shows the logo and labels without that effect. Existing web/iOS/Android paths keep their behavior. |
| Native tests and this guide | Make the working slice reproducible and give contributors bounded follow-up work. |
### Testing changes against a local fork checkout
To build Paseo against a local checkout of `getpaseo/react-native-gpui` instead of the pinned release:
```sh
npm run gpui:install -- --local /path/to/react-native-gpui
```
You can also pass the path via `PASEO_GPUI_LOCAL=/path/to/react-native-gpui npm run gpui:install`.
This installs locked dependencies and the seven `@react-native-gpui/*` modules from the release, then packs `@react-native-gpui/{cli,codegen,core,hermes}` from the local checkout into `packages/app/gpui/node_modules/@react-native-gpui/` without modifying `package.json` or `package-lock.json`. Re-run the same command after editing the fork, then rebuild (`npm run build:gpui` or `npm run dev:gpui`). Run `npm run gpui:install` without `--local` to restore the release packages.
GPUI remains a pinned Cargo git dependency. Upstream tooling downloads Hermes
and builds the C++ runtime when needed; release packaging has not been verified across all platforms.
## Working slice and limits
Verified on Linux x86_64 and macOS arm64: all 24 app routes in the bundle, connection to the
daemon, the real project/workspace sidebar, opening an existing workspace,
existing message rendering, and native composer typing/deletion. The native
regression test restores the draft and does not send a message. Rust tests cover
SHA-256/random-byte bounds and real SQLite parameter binding/transaction rollback.
The macOS build also passed draft restoration after restarting the native process.
The following are not feature-parity claims:
| Area | Current state |
| ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Styling | Adapter evaluates existing Unistyles theme/style factories and breakpoints. No Nitro shadow-tree integration. Full theme/resize behavior needs QA. |
| Storage/crypto/localization | Native filesystem + SQLite + SHA-256 + OS randomness. Intl ships English locale data and IANA time zones. The Rust service contains Linux-specific OS access. |
| Clipboard/files | Text clipboard, native file dialogs, PNG/JPEG picking, and download/export adapters exist. End-to-end dialog/transfer coverage is still missing. |
| Voice/camera/push/power inhibition | Unavailable. Requests either report the missing capability or use the app's existing unavailable-capability implementation. |
| Image conversion/image clipboard | Unavailable. The picker accepts PNG/JPEG without conversion. |
| Mermaid/HTML/document previews | Mermaid and HTML show source. Document previews report unavailable. No embedded browser backend. |
| Terminals | The mobile view expects an Expo `PaseoTerminal` component. No GPUI implementation yet. |
| Diffs | The mobile surface uses React Native Skia. No GPUI drawing backend yet. |
| Plugins | The existing loader evaluates JS and injects host React/RN. No end-to-end plugin verification on GPUI yet. |
| Other platforms | Linux x86_64 and macOS arm64 have been exercised. Windows remains unverified. |
The initial stripped development executable was about 68 MiB, with about 10 MiB
of Hermes/JSI libraries and a 21 MiB JS bundle, approximately 100 MiB uncompressed.
That measurement excludes the daemon, is not an optimized release installer, and
does not establish memory usage or a size advantage over another renderer.
## Experiments to pick up
Each experiment should preserve the real app and demonstrate a user workflow.
1. **Native terminal.** Implement a GPUI component for the existing
[`PaseoTerminalView`](../modules/paseo-terminal/index.tsx) frame contract.
Keep the JS headless xterm emulator, transport, and frame generation initially.
Verify resize/replay, keyboard/IME/paste, scrollback/selection, and the existing
Unicode corpus. [Terminal rendering](../../../docs/terminal-rendering.md)
explains why shaping must preserve xterm's cell columns.
2. **Diff surface.** Keep `src/git/diff-document`'s model and review actions;
add GPUI text measurement and painting instead of the Skia surface. Test
unified/split views, wrapping, scrolling, selection, and inline reviews on
large real diffs. The [C++ layout experiment](../modules/paseo-diff-prototype/README.md)
is a separate candidate for shared geometry; it is not a finished renderer.
3. **Plugins.** Load a small plugin into an isolated daemon, open its real screen
or workspace panel, call a plugin RPC, and reload it. Verify subscriptions and
cleanup. Track unsupported services explicitly instead of adding fake APIs.
4. **Native services and styling.** Exercise dialogs, downloads, clipboard,
persistence/restart, theme switching, resizing, and focus. Replace the narrow
adapters with complete implementations only where the app needs them.
5. **Portability and packaging.** Build on clean Linux, then macOS/Windows. Replace
Linux-only randomness/timezone access, check font/shaping and IME behavior, and
verify relocatable libraries/assets. Measure a release build and a controlled
workflow before claiming a performance or size improvement.
6. **Bundled daemon, independently.** First run the unchanged daemon under Bun
in isolation. Verify PTY/native dependencies, terminal-worker subprocesses,
provider launches, and dynamic plugins. Then compare standalone/AOT packaging
and size. This branch neither ports the daemon nor embeds it in the UI process.
A Rust/GPUI terminal or diff painter can share desktop implementation across the
upstream renderer's supported OSes. Reusing it on mobile still requires mobile
bindings and graphics integration; choosing Rust or C++ alone does not provide that.
## Verification
Run the normal checks from the root. `.gpui.ts` and `.gpui.tsx` files in
`packages/app/src` and `packages/app/modules` are checked by root `typecheck`
and `lint`, while `packages/app/gpui/adapters/` is excluded from the mobile
TypeScript project.
```sh
npm run typecheck
npm run lint
npm run format:check
```
For the native UI regression, use a daemon with an existing workspace and build
with the driver. Run the native app on an isolated display when testing on a
machine in use:
```sh
EXPO_PUBLIC_LOCAL_DAEMON=localhost:6768 npm run build:gpui -- --features test-driver,visual-capture
RN_GPUI_TEST_DRIVER=1 RN_GPUI_TEST_DRIVER_TOKEN=local-test \
RN_GPUI_DEV_MODE=0 RN_GPUI_BUNDLE="$PWD/.artifacts/gpui/paseo.bundle" \
RN_GPUI_ASSETS_DIR="$PWD/.artifacts/gpui/assets/assets" \
xvfb-run -a -s '-screen 0 2560x1600x24' \
packages/app/gpui/desktop/target/debug/react-native-gpui-paseo-gpui
```
Use the printed `RN_GPUI_TEST_DRIVER_PORT` in another shell:
```sh
PASEO_GPUI_TEST_URL=ws://127.0.0.1:PORT PASEO_GPUI_TEST_TOKEN=local-test \
npx vitest run packages/app/gpui/native.test.ts --bail=1
```
Without a driver URL the test is skipped. Put diagnostic logs/captures in
`.artifacts/gpui/`; do not commit them or publish private workspace contents as QA.
For border and hover regressions, bundle the isolated scene from `packages/app/gpui`:
```sh
PASEO_RENDERER=gpui node node_modules/react-native/cli.js bundle --platform desktop \
--entry-file appearance-regression.fixture.js --config desktop/metro.config.js \
--bundle-output ../../../.artifacts/gpui/appearance.bundle --dev false --max-workers 1
```
Launch the driver-enabled executable with `RN_GPUI_BUNDLE` pointing at that bundle.
Run `native.test.ts` from the root with the driver URL/token above and
`PASEO_GPUI_TEST_SCENE=appearance`. It checks the rendered border pixels,
Pressable hover callbacks and render props, and hover across nested controls.
No daemon is needed for this scene.
On macOS, test WebSocket cleanup against a compiled native executable:
```sh
PASEO_GPUI_TEST_BINARY="/absolute/path/to/react-native-gpui-paseo-gpui" \
npx vitest run packages/app/gpui/websocket.native.test.ts --bail=1
```
This opens an isolated native window and uses a loopback peer for 128 rejected
handshakes, 128 server closes, and 128 client closes under a 256-descriptor limit.
It needs an active display and the GPUI npm dependencies, but no Paseo daemon.
Without the executable path it is skipped. Its bundle and logs stay in `.artifacts/gpui/`.
@@ -1,73 +0,0 @@
import { promises as fs, paths } from "@react-native-gpui/fs";
import Desktop from "../desktop/src/NativePaseoDesktop";
let writes = Promise.resolve();
const directory = () => `${paths.appData}/paseo-gpui/storage`;
const filename = (key) => `${directory()}/${Desktop.sha256(key)}.json`;
async function read(key) {
try {
return JSON.parse(await fs.readFile(filename(key), "utf8")).value;
} catch (error) {
if (error.code === "ENOENT") return null;
throw error;
}
}
function mutate(operation) {
const result = writes.then(operation);
writes = result.catch(() => {});
return result;
}
async function write(key, value) {
await fs.mkdir(directory(), { recursive: true });
const target = filename(key);
await fs.writeFile(`${target}.tmp`, JSON.stringify({ key, value }), "utf8");
await fs.rename(`${target}.tmp`, target);
}
async function keys() {
let entries;
try {
entries = await fs.readdir(directory());
} catch (error) {
if (error.code === "ENOENT") return [];
throw error;
}
return Promise.all(
entries
.filter((name) => name.endsWith(".json"))
.map(async (name) => JSON.parse(await fs.readFile(`${directory()}/${name}`, "utf8")).key),
);
}
const storage = {
async getItem(key) {
await writes;
return read(key);
},
setItem(key, value) {
return mutate(() => write(key, value));
},
removeItem(key) {
return mutate(() => fs.rm(filename(key), { force: true }));
},
async getAllKeys() {
await writes;
return keys();
},
async multiGet(items) {
await writes;
return Promise.all(items.map(async (key) => [key, await read(key)]));
},
multiSet(items) {
return mutate(async () => {
for (const [key, value] of items) await write(key, value);
});
},
multiRemove(items) {
return mutate(async () => {
for (const key of items) await fs.rm(filename(key), { force: true });
});
},
clear() {
return mutate(() => fs.rm(directory(), { recursive: true, force: true }));
},
};
export default storage;
-16
View File
@@ -1,16 +0,0 @@
import { TurboModuleRegistry } from "react-native";
const clipboard = TurboModuleRegistry.getEnforcing("Clipboard");
export const getStringAsync = () => clipboard.getString();
export async function setStringAsync(value) {
clipboard.setString(value);
return true;
}
export async function hasStringAsync() {
return (await getStringAsync()).length > 0;
}
export async function getImageAsync() {
throw new Error("Image clipboard is not implemented for GPUI yet");
}
export async function setImageAsync() {
throw new Error("Image clipboard is not implemented for GPUI yet");
}
-24
View File
@@ -1,24 +0,0 @@
import Desktop from "../desktop/src/NativePaseoDesktop";
export function getRandomValues(array) {
if (
!ArrayBuffer.isView(array) ||
array instanceof DataView ||
array instanceof Float32Array ||
array instanceof Float64Array
) {
throw new TypeError("getRandomValues requires an integer typed array");
}
if (array.byteLength > 65536) throw new RangeError("Random request exceeds 65536 bytes");
new Uint8Array(array.buffer, array.byteOffset, array.byteLength).set(
Desktop.randomBytes(array.byteLength),
);
return array;
}
export function randomUUID() {
return globalThis.crypto.randomUUID();
}
export const CryptoDigestAlgorithm = { SHA256: "SHA-256" };
export async function digestStringAsync(algorithm, text) {
if (algorithm !== "SHA-256") throw new Error(`Unsupported digest algorithm: ${algorithm}`);
return Desktop.sha256(text);
}
@@ -1,14 +0,0 @@
import { dialog, promises } from "@react-native-gpui/fs";
export async function getDocumentAsync(options = {}) {
const paths = await dialog.open({ multiple: options.multiple ?? false });
return {
canceled: paths.length === 0,
assets: await Promise.all(
paths.map(async (path) => ({
uri: `file://${path}`,
name: path.split("/").at(-1),
size: (await promises.stat(path)).size,
})),
),
};
}
@@ -1,11 +0,0 @@
import {
EventEmitter,
NativeModule,
SharedObject,
SharedRef,
} from "expo-modules-core/src/polyfill/CoreModule";
export function ensureNativeModulesAreInstalled() {
if (globalThis.expo) return;
globalThis.expo = { EventEmitter, NativeModule, SharedObject, SharedRef, modules: {} };
}
ensureNativeModulesAreInstalled();
@@ -1,30 +0,0 @@
import { Linking } from "react-native";
import { NativeModule } from "expo-modules-core/src/polyfill/CoreModule";
class DesktopLinking extends NativeModule {
initialURL = null;
subscription;
constructor() {
super();
Linking.getInitialURL()
.then((url) => {
this.initialURL = url;
if (url) this.emit("onURLReceived", { url });
return url;
})
.catch((error) => console.error("[GPUI linking]", error));
}
getLinkingURL = () => this.initialURL;
clearInitialURL() {
this.initialURL = null;
}
startObserving() {
this.subscription = Linking.addEventListener("url", (event) =>
this.emit("onURLReceived", event),
);
}
stopObserving() {
this.subscription?.remove();
}
}
export default new DesktopLinking();
-129
View File
@@ -1,129 +0,0 @@
import fs, { promises, paths } from "@react-native-gpui/fs";
import { Buffer } from "buffer";
const pathOf = (value) => String(value?.uri ?? value).replace(/^file:\/\//, "");
const join = (parts) =>
parts
.map(pathOf)
.join("/")
.replace(/\/{2,}/g, "/");
export const cacheDirectory = `file://${paths.appCache}/paseo-gpui/`;
export const documentDirectory = `file://${paths.appData}/paseo-gpui/`;
export const EncodingType = { Base64: "base64", UTF8: "utf8" };
export const Paths = { cache: cacheDirectory, document: documentDirectory };
export async function getInfoAsync(uri) {
try {
const stat = await promises.stat(pathOf(uri));
return { exists: true, isDirectory: stat.isDirectory(), size: stat.size, uri };
} catch (error) {
if (error.code === "ENOENT") return { exists: false, uri };
throw error;
}
}
export const makeDirectoryAsync = (uri, options = {}) =>
promises.mkdir(pathOf(uri), { recursive: options.intermediates });
export const copyAsync = ({ from, to }) => promises.copyFile(pathOf(from), pathOf(to));
export const moveAsync = ({ from, to }) => promises.rename(pathOf(from), pathOf(to));
export const readAsStringAsync = (uri, options = {}) =>
promises.readFile(pathOf(uri), options.encoding ?? "utf8");
export const writeAsStringAsync = (uri, contents, options = {}) =>
promises.writeFile(pathOf(uri), contents, options.encoding ?? "utf8");
export const deleteAsync = (uri, options = {}) =>
promises.rm(pathOf(uri), { recursive: true, force: options.idempotent });
export const readDirectoryAsync = (uri) => promises.readdir(pathOf(uri));
export class File {
constructor(...parts) {
this.uri = `file://${join(parts)}`;
}
get name() {
return pathOf(this).split("/").at(-1);
}
get exists() {
return fs.existsSync(pathOf(this));
}
get size() {
return fs.statSync(pathOf(this)).size;
}
create({ overwrite = false, intermediates = false } = {}) {
if (intermediates)
fs.mkdirSync(pathOf(this).split("/").slice(0, -1).join("/"), { recursive: true });
fs.writeFileSync(pathOf(this), "", { flag: overwrite ? "w" : "wx" });
}
write(value) {
fs.writeFileSync(pathOf(this), value);
}
delete() {
fs.rmSync(pathOf(this));
}
async bytes() {
return promises.readFile(pathOf(this));
}
async arrayBuffer() {
const bytes = await this.bytes();
return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
}
async base64() {
return Buffer.from(await this.bytes()).toString("base64");
}
async text() {
return promises.readFile(pathOf(this), "utf8");
}
move(destination) {
fs.renameSync(pathOf(this), pathOf(destination));
this.uri = destination.uri;
}
copy(destination) {
fs.copyFileSync(pathOf(this), pathOf(destination));
}
static async downloadFileAsync(url, destination) {
const response = await fetch(url);
if (!response.ok) throw new Error(`Download failed: ${response.status}`);
const file = destination instanceof File ? destination : new File(destination);
await promises.writeFile(pathOf(file), new Uint8Array(await response.arrayBuffer()));
return file;
}
}
export class Directory {
constructor(...parts) {
this.uri = `file://${join(parts)}`;
}
get exists() {
return fs.existsSync(pathOf(this));
}
create({ intermediates = false } = {}) {
fs.mkdirSync(pathOf(this), { recursive: intermediates });
}
delete() {
fs.rmSync(pathOf(this), { recursive: true });
}
list() {
return fs
.readdirSync(pathOf(this), { withFileTypes: true })
.map((entry) =>
entry.isDirectory() ? new Directory(this, entry.name) : new File(this, entry.name),
);
}
}
export function createDownloadResumable(url, uri, options = {}, onProgress) {
const controller = new AbortController();
return {
async downloadAsync() {
const response = await fetch(url, { headers: options.headers, signal: controller.signal });
if (!response.ok) throw new Error(`Download failed: ${response.status}`);
const bytes = new Uint8Array(await response.arrayBuffer());
const target = pathOf(uri);
await promises.mkdir(target.split("/").slice(0, -1).join("/"), { recursive: true });
await promises.writeFile(`${target}.part`, bytes);
await promises.rename(`${target}.part`, target);
onProgress?.({ totalBytesWritten: bytes.length, totalBytesExpectedToWrite: bytes.length });
return {
uri,
status: response.status,
headers: Object.fromEntries(response.headers.entries()),
};
},
async cancelAsync() {
controller.abort();
},
};
}
@@ -1,8 +0,0 @@
// The GPUI picker accepts JPEG/PNG directly. Other formats require a future
// native decoder; never claim conversion succeeded for an unsupported format.
export const SaveFormat = { PNG: "png", JPEG: "jpeg", WEBP: "webp" };
export const ImageManipulator = {
manipulate() {
throw new Error("Image conversion is not available in the GPUI build; select a PNG or JPEG.");
},
};
@@ -1,28 +0,0 @@
import { dialog, promises } from "@react-native-gpui/fs";
// Desktop access is granted for each selection by the system file dialog.
export const PermissionStatus = {
GRANTED: "granted",
DENIED: "denied",
UNDETERMINED: "undetermined",
};
const permission = { status: "granted", granted: true, canAskAgain: true, expires: "never" };
export const requestMediaLibraryPermissionsAsync = async () => permission;
export const useMediaLibraryPermissions = () => [permission, requestMediaLibraryPermissionsAsync];
export const getPendingResultAsync = async () => null;
export async function launchImageLibraryAsync(options = {}) {
const paths = await dialog.open({
multiple: options.allowsMultipleSelection,
filters: [{ name: "Images", extensions: ["png", "jpg", "jpeg"] }],
});
return {
canceled: !paths.length,
assets: await Promise.all(
paths.map(async (path) => ({
uri: `file://${path}`,
fileName: path.split("/").at(-1),
fileSize: (await promises.stat(path)).size,
mimeType: /\.png$/i.test(path) ? "image/png" : "image/jpeg",
})),
),
};
}
@@ -1,5 +0,0 @@
export function setDefaultTimeZone(timeZone) {
// macOS uses the IANA alias GMT. FormatJS's timezone data omits that alias;
// normalize it at the polyfill boundary while preserving other system zones.
Intl.DateTimeFormat.__setDefaultTimeZone(timeZone.toUpperCase() === "GMT" ? "UTC" : timeZone);
}
@@ -1,23 +0,0 @@
/* oxlint-disable import/no-unassigned-import -- Exercise the actual GPUI Intl implementation. */
import "@formatjs/intl-datetimeformat/polyfill-force.js";
import "@formatjs/intl-datetimeformat/locale-data/en.js";
import "@formatjs/intl-datetimeformat/add-all-tz.js";
import { afterEach, expect, test } from "vitest";
import { setDefaultTimeZone } from "./intl-timezone";
afterEach(() => setDefaultTimeZone("UTC"));
test.each([
["GMT", "UTC"],
["gmt", "UTC"],
["UTC", "UTC"],
["Europe/Berlin", "Europe/Berlin"],
["US/Pacific", "America/Los_Angeles"],
])("initializes the system timezone %s as %s", (systemZone, expectedZone) => {
setDefaultTimeZone(systemZone);
expect(new Intl.DateTimeFormat("en").resolvedOptions().timeZone).toBe(expectedZone);
});
test("does not silently replace an invalid system timezone", () => {
expect(() => setDefaultTimeZone("Invalid/Zone")).toThrow(RangeError);
});
-17
View File
@@ -1,17 +0,0 @@
/* oxlint-disable import/no-unassigned-import -- These packages install Intl and locale data by side effect. */
// Hermes' Linux build omits Intl; install real locale algorithms before app code.
import "@formatjs/intl-getcanonicallocales/polyfill-force.js";
import "@formatjs/intl-locale/polyfill-force.js";
import "@formatjs/intl-pluralrules/polyfill-force.js";
import "@formatjs/intl-pluralrules/locale-data/en.js";
import "@formatjs/intl-numberformat/polyfill-force.js";
import "@formatjs/intl-numberformat/locale-data/en.js";
import "@formatjs/intl-datetimeformat/polyfill-force.js";
import "@formatjs/intl-datetimeformat/locale-data/en.js";
import "@formatjs/intl-datetimeformat/add-all-tz.js";
import "@formatjs/intl-displaynames/polyfill-force.js";
import "@formatjs/intl-displaynames/locale-data/en.js";
import "@formatjs/intl-segmenter/polyfill-force.js";
import Desktop from "../desktop/src/NativePaseoDesktop";
import { setDefaultTimeZone } from "./intl-timezone";
setDefaultTimeZone(Desktop.timezone());
-6
View File
@@ -1,6 +0,0 @@
// No desktop power-inhibition lease is acquired by this backend yet.
export const isAvailableAsync = async () => false;
export async function activateKeepAwakeAsync() {
throw new Error("Power inhibition is not available in the GPUI build.");
}
export async function deactivateKeepAwake() {}
-60
View File
@@ -1,60 +0,0 @@
import { useEffect } from "react";
import { Keyboard, ScrollView, useAnimatedValue } from "react-native";
import { useSharedValue } from "react-native-reanimated";
// A GPUI desktop window has no software-keyboard inset. RN still owns focus
// and physical keyboard events; the mobile layout API observes its events.
export function KeyboardProvider({ children }) {
return children;
}
export const KeyboardAwareScrollView = ScrollView;
export const KeyboardController = {
isVisible: () => Keyboard.isVisible(),
dismiss: () => Keyboard.dismiss(),
};
export const KeyboardEvents = { addListener: (...args) => Keyboard.addListener(...args) };
export function useReanimatedKeyboardAnimation() {
const height = useSharedValue(0);
const progress = useSharedValue(0);
useEffect(() => {
const shown = Keyboard.addListener("keyboardDidShow", (event) => {
height.value = -event.endCoordinates.height;
progress.value = 1;
});
const hidden = Keyboard.addListener("keyboardDidHide", () => {
height.value = 0;
progress.value = 0;
});
return () => {
shown.remove();
hidden.remove();
};
}, [height, progress]);
return { height, progress };
}
export function useKeyboardAnimation() {
const height = useAnimatedValue(0);
const progress = useAnimatedValue(0);
return { height, progress };
}
export function useGenericKeyboardHandler(handlers) {
useEffect(() => {
const subscriptions = [
Keyboard.addListener("keyboardDidShow", (event) => {
const value = {
height: event.endCoordinates.height,
progress: 1,
duration: event.duration,
};
handlers.onStart?.(value);
handlers.onEnd?.(value);
}),
Keyboard.addListener("keyboardDidHide", () => {
const value = { height: 0, progress: 0, duration: 0 };
handlers.onStart?.(value);
handlers.onEnd?.(value);
}),
];
return () => subscriptions.forEach((subscription) => subscription.remove());
}, [handlers]);
}
@@ -1,5 +0,0 @@
import Desktop from "../desktop/src/NativePaseoDesktop";
export function getLocales() {
const languageTag = Desktop.locale().split(".")[0].replaceAll("_", "-");
return [{ languageTag, languageCode: languageTag.split("-")[0] }];
}
@@ -1,5 +0,0 @@
import { Buffer } from "buffer";
import Desktop from "../desktop/src/NativePaseoDesktop";
export function randomBytes(length) {
return Buffer.from(Desktop.randomBytes(length));
}
@@ -1,3 +0,0 @@
// GPUI's native TextInput owns text paste, selection, and IME. The mobile
// PasteInput module's image-paste extension is not available on this target.
export { TextInput as default } from "react-native";
-11
View File
@@ -1,11 +0,0 @@
import { dialog, promises } from "@react-native-gpui/fs";
// Linux exports a downloaded file through the native Save dialog.
export const isAvailableAsync = async () => true;
export async function shareAsync(uri, options = {}) {
const source = uri.replace(/^file:\/\//, "");
const destination = await dialog.save({
title: options.dialogTitle ?? "Save file",
defaultName: source.split("/").at(-1),
});
if (destination) await promises.copyFile(source, destination);
}
-37
View File
@@ -1,37 +0,0 @@
import Desktop from "../desktop/src/NativePaseoDesktop";
let pending = Promise.resolve();
function enqueue(operation) {
const result = pending.then(operation);
pending = result.catch(() => {});
return result;
}
const connection = {
async execAsync(sql) {
Desktop.sqlite(sql, "batch");
},
async runAsync(sql, params = []) {
Desktop.sqlite(sql, JSON.stringify(params));
},
async getAllAsync(sql, params = []) {
return JSON.parse(Desktop.sqlite(sql, JSON.stringify(params)));
},
};
export async function openDatabaseAsync(name) {
if (name !== "paseo-replica-row-store.db") throw new Error(`Unknown GPUI database: ${name}`);
return {
execAsync: (...args) => enqueue(() => connection.execAsync(...args)),
runAsync: (...args) => enqueue(() => connection.runAsync(...args)),
getAllAsync: (...args) => enqueue(() => connection.getAllAsync(...args)),
withExclusiveTransactionAsync: (operation) =>
enqueue(async () => {
await connection.execAsync("BEGIN IMMEDIATE");
try {
await operation(connection);
await connection.execAsync("COMMIT");
} catch (error) {
await connection.execAsync("ROLLBACK");
throw error;
}
}),
};
}
@@ -1,28 +0,0 @@
import * as RN from "react-native";
import { createUnistylesElement } from "./unistyles";
export const View = createUnistylesElement(RN.View);
export const Text = createUnistylesElement(RN.Text);
export const ScrollView = createUnistylesElement(RN.ScrollView);
export const TextInput = createUnistylesElement(RN.TextInput);
export const Pressable = createUnistylesElement(RN.Pressable);
export const Image = createUnistylesElement(RN.Image);
export const ImageBackground = createUnistylesElement(RN.ImageBackground);
export const FlatList = createUnistylesElement(RN.FlatList);
export const SectionList = createUnistylesElement(RN.SectionList);
export const TouchableOpacity = createUnistylesElement(RN.TouchableOpacity);
export const TouchableHighlight = createUnistylesElement(RN.TouchableHighlight);
export const TouchableWithoutFeedback = createUnistylesElement(RN.TouchableWithoutFeedback);
export const ActivityIndicator = createUnistylesElement(RN.ActivityIndicator);
export const KeyboardAvoidingView = createUnistylesElement(RN.KeyboardAvoidingView);
export const SafeAreaView = createUnistylesElement(RN.SafeAreaView);
export const Switch = createUnistylesElement(RN.Switch);
export const RefreshControl = createUnistylesElement(RN.RefreshControl);
export const VirtualizedList = createUnistylesElement(RN.VirtualizedList);
export const StatusBar = RN.StatusBar;
export const Animated = {
...RN.Animated,
View: createUnistylesElement(RN.Animated.View),
Text: createUnistylesElement(RN.Animated.Text),
ScrollView: createUnistylesElement(RN.Animated.ScrollView),
Image: createUnistylesElement(RN.Animated.Image),
};
-140
View File
@@ -1,140 +0,0 @@
import React, { forwardRef, useSyncExternalStore } from "react";
import * as Native from "react-native";
// GPUI has Fabric but no Nitro/Unistyles shadow-tree bindings. Keep the app's
// style factories and theme API; this backend updates subscribed React views.
const listeners = new Set();
const resolveStyle = Symbol("paseo.gpui.style");
let revision = 0;
let themes = {};
let themeName = "dark";
let adaptive = true;
let breakpoints = {};
const emit = () => {
revision += 1;
for (const listener of listeners) listener();
};
const subscribe = (listener) => {
listeners.add(listener);
return () => listeners.delete(listener);
};
const snapshot = () => revision;
const theme = () => themes[themeName];
const runtime = () => ({
themeName,
colorScheme: Native.Appearance.getColorScheme() ?? "light",
screen: Native.Dimensions.get("window"),
insets: { top: 0, bottom: 0, left: 0, right: 0, ime: 0 },
pixelRatio: Native.PixelRatio.get(),
fontScale: Native.PixelRatio.getFontScale(),
breakpoint: Object.keys(breakpoints).findLast(
(key) => breakpoints[key] <= Native.Dimensions.get("window").width,
),
});
Native.Dimensions.addEventListener("change", emit);
Native.Appearance.addChangeListener(({ colorScheme }) => {
if (adaptive && themes[colorScheme]) themeName = colorScheme;
emit();
});
function responsive(value) {
if (Array.isArray(value)) return value.map(responsive);
if (!value || typeof value !== "object") return value;
if (Object.getPrototypeOf(value) !== Object.prototype) return value;
const keys = Object.keys(value);
if (keys.length && keys.every((key) => key in breakpoints)) {
const width = Native.Dimensions.get("window").width;
const key = keys
.sort((a, b) => breakpoints[a] - breakpoints[b])
.findLast((candidate) => breakpoints[candidate] <= width);
return key === undefined ? undefined : responsive(value[key]);
}
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, responsive(item)]));
}
function materialize(style) {
if (Array.isArray(style)) return style.map(materialize);
if (style && typeof style === "object" && style[resolveStyle]) return style[resolveStyle]();
return style;
}
function styledProps(props) {
const result = { ...props };
for (const key of ["style", "contentContainerStyle"]) {
if (typeof props[key] === "function")
result[key] = (...args) => materialize(props[key](...args));
else if (props[key]) result[key] = materialize(props[key]);
}
return result;
}
export const UnistylesRuntime = {
get themeName() {
return themeName;
},
get breakpoint() {
return runtime().breakpoint;
},
get colorScheme() {
return runtime().colorScheme;
},
getTheme: theme,
setTheme(name) {
if (!themes[name]) throw new Error(`Unknown GPUI theme: ${name}`);
themeName = name;
emit();
},
updateTheme(name, update) {
themes[name] = update(themes[name]);
emit();
},
setAdaptiveThemes(value) {
adaptive = value;
if (value && themes[runtime().colorScheme]) themeName = runtime().colorScheme;
emit();
},
};
export const StyleSheet = {
...Native.StyleSheet,
configure(config) {
themes = config.themes;
breakpoints = config.breakpoints;
adaptive = config.settings?.adaptiveThemes ?? false;
themeName =
config.settings?.initialTheme ?? (adaptive ? runtime().colorScheme : Object.keys(themes)[0]);
emit();
},
create(factory) {
const evaluate = () => (typeof factory === "function" ? factory(theme(), runtime()) : factory);
const initial = evaluate();
const sheet = {};
for (const key of Object.keys(initial)) {
const wrap = (args) => {
const resolve = () => {
const value = evaluate()[key];
return responsive(typeof value === "function" ? value(...args) : value);
};
return Object.defineProperty({ ...resolve() }, resolveStyle, { value: resolve });
};
sheet[key] = typeof initial[key] === "function" ? (...args) => wrap(args) : wrap([]);
}
return sheet;
},
};
// Existing consumers retain this API; new app code should use style factories.
export function useUnistyles() {
useSyncExternalStore(subscribe, snapshot, snapshot);
return { theme: theme(), rt: runtime() };
}
export function withUnistyles(Component, mappings) {
const Wrapped = forwardRef(function GpuiThemed(props, ref) {
useSyncExternalStore(subscribe, snapshot, snapshot);
const { uniProps, ...rest } = props;
return React.createElement(Component, {
...styledProps({
...mappings?.(theme(), runtime()),
...uniProps?.(theme(), runtime()),
...rest,
}),
ref,
});
});
return Wrapped;
}
export const createUnistylesElement = withUnistyles;
-1
View File
@@ -1 +0,0 @@
{ "name": "Paseo", "displayName": "Paseo GPUI" }
@@ -1,121 +0,0 @@
/* oxlint-disable react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop -- Minimal native regression scene. */
import React, { useCallback, useState } from "react";
import { AppRegistry, Image, Pressable, ScrollView, Text, TextInput, View } from "react-native";
function AppearanceRegression() {
const [buttonHovered, setHovered] = useState(false);
const [entered, setEntered] = useState(false);
const [expanded, setExpanded] = useState(false);
const [layouts, setLayouts] = useState({});
const record = useCallback((key, event) => {
const layout = event?.nativeEvent?.layout;
const layoutKeys = layout ? Object.keys(layout).sort() : [];
setLayouts((prev) => ({
...prev,
[key]: {
count: (prev[key]?.count ?? 0) + 1,
keys: layoutKeys,
layout,
},
}));
}, []);
const onViewLayout = useCallback((e) => record("view", e), [record]);
const onTextLayout = useCallback((e) => record("text", e), [record]);
const onInputLayout = useCallback((e) => record("textInput", e), [record]);
const onImageLayout = useCallback((e) => record("image", e), [record]);
const onScrollLayout = useCallback((e) => record("scrollView", e), [record]);
return (
<View style={{ flex: 1, flexDirection: "row", backgroundColor: "white", padding: 40, gap: 40 }}>
<View style={{ gap: 24 }}>
<View
testID="rounded-border"
style={{
width: 200,
height: 100,
borderRadius: 24,
borderWidth: 4,
borderColor: "#ff0000",
backgroundColor: "#0000ff",
}}
/>
<Pressable
testID="hover-button"
onHoverIn={() => setHovered(true)}
onHoverOut={() => setHovered(false)}
style={{ width: 200, height: 60, backgroundColor: buttonHovered ? "#00ff00" : "#0000ff" }}
>
<Text>{buttonHovered ? "hover active" : "hover inactive"}</Text>
</Pressable>
<Pressable
testID="hover-render-prop"
style={({ hovered }) => ({
width: 200,
height: 60,
backgroundColor: hovered ? "#00ff00" : "#0000ff",
})}
>
{({ hovered }) => <Text>{hovered ? "render hovered" : "render idle"}</Text>}
</Pressable>
<View
testID="hover-row"
onPointerEnter={() => setEntered(true)}
onPointerLeave={() => setEntered(false)}
style={{ width: 200, height: 60, backgroundColor: entered ? "#00ff00" : "#0000ff" }}
>
<Pressable testID="nested-button" style={{ width: 100, height: 60 }}>
<Text>{entered ? "row active" : "row inactive"}</Text>
</Pressable>
</View>
<View testID="outside-hover" style={{ width: 200, height: 60 }} />
</View>
<View style={{ gap: 12, alignItems: "flex-start" }}>
<Pressable
testID="layout-resize-toggle"
onPress={() => setExpanded((value) => !value)}
style={{ width: 160, height: 32, backgroundColor: "#dddddd", justifyContent: "center" }}
>
<Text>{expanded ? "Shrink" : "Expand"}</Text>
</Pressable>
<View
testID="layout-view"
onLayout={onViewLayout}
style={{ width: expanded ? 180 : 120, height: 24, backgroundColor: "#eeeeee" }}
/>
<Text testID="layout-text" onLayout={onTextLayout}>
{expanded ? "Measure a much longer text label" : "Short label"}
</Text>
<TextInput
testID="layout-text-input"
onLayout={onInputLayout}
defaultValue="hi"
style={{ width: expanded ? 200 : 140, height: 32, borderWidth: 1 }}
/>
<Image
testID="layout-image"
onLayout={onImageLayout}
style={{ width: expanded ? 96 : 64, height: 32, backgroundColor: "#cccccc" }}
/>
<ScrollView
testID="layout-scroll"
onLayout={onScrollLayout}
style={{
flexGrow: 0,
flexShrink: 0,
width: expanded ? 210 : 150,
height: 40,
backgroundColor: "#eeeeee",
}}
>
<View style={{ width: expanded ? 210 : 150, height: 80 }} />
</ScrollView>
<Text testID="layout-results">{JSON.stringify(layouts)}</Text>
</View>
</View>
);
}
AppRegistry.registerComponent("Paseo", () => AppearanceRegression);
-7
View File
@@ -1,7 +0,0 @@
module.exports = function (api) {
api.cache(true);
return {
presets: [[require.resolve("babel-preset-expo"), { unstable_transformImportMeta: true }]],
plugins: [[require.resolve("react-native-unistyles/plugin"), { root: "../src" }]],
};
};
-4
View File
@@ -1,4 +0,0 @@
build/
.cache/
autolink/
target/
File diff suppressed because it is too large Load Diff
-63
View File
@@ -1,63 +0,0 @@
[package]
name = "react-native-gpui-paseo-gpui"
version = "0.1.0"
edition = "2021"
# Set CARGO_PROFILE_DEV_DEBUG=full to opt into full debug information.
[profile.dev]
debug = "line-tables-only"
split-debuginfo = "packed"
# Dependencies are optimized even in a dev build: GPUI rebuilds and paints the
# element tree on every frame, and they are only compiled once.
[profile.dev.package."*"]
debug = false
opt-level = 3
# The C++ bridge picks its CMake build type from this crate's opt-level, and a
# Release build of React Native has no dev server, inspector or Fast Refresh.
[profile.dev.package.rn-gpui-sys]
opt-level = 0
[profile.release]
debug = "line-tables-only"
# Cargo strips inside the linker, before dsymutil, so package-desktop preserves the
# Cargo dSYM and then strips. Full LTO: 2 MB smaller for 1.4x the build time.
strip = "none"
split-debuginfo = "packed"
lto = "fat"
codegen-units = 1
[build-dependencies]
rn-gpui-module-build = { path = "../node_modules/@react-native-gpui/core/ReactGpui/rn-gpui-module-build" }
serde_json = "1"
[features]
visual-capture = ["react-native-gpui/visual-capture"]
test-driver = ["react-native-gpui/test-driver"]
runtime-shaders = ["react-native-gpui/runtime-shaders"]
[dev-dependencies]
rn_gpui_enriched_markdown = { package = "rn-gpui-enriched-markdown", path = "../../../react-native-enriched-markdown/desktop" }
gpui = { git = "https://github.com/streetwriters/gpui-fast", rev = "1ad3cc3" }
gpui_platform = { git = "https://github.com/streetwriters/gpui-fast", rev = "1ad3cc3", features = [
"test-support",
] }
[dependencies]
serde_json = "1"
sha2 = "0.10"
rusqlite = { version = "0.38", features = ["bundled"] }
rn-gpui-module = { path = "../node_modules/@react-native-gpui/core/ReactGpui/rn-gpui-module" }
rn-gpui-autolink = { path = "autolink" }
react-native-gpui = { path = "../node_modules/@react-native-gpui/core/ReactGpui/rn-gpui" }
[patch.crates-io]
# Managed by @react-native-gpui/cli autolink; do not edit between these markers.
react-native-gpui = { path = "../node_modules/@react-native-gpui/core/ReactGpui/rn-gpui" }
rn-gpui-sys = { path = "../node_modules/@react-native-gpui/core/ReactGpui/rn-gpui-sys" }
rn-gpui-module = { path = "../node_modules/@react-native-gpui/core/ReactGpui/rn-gpui-module" }
rn-gpui-module-build = { path = "../node_modules/@react-native-gpui/core/ReactGpui/rn-gpui-module-build" }
gpui = { git = "https://github.com/streetwriters/gpui-fast", rev = "1ad3cc3" }
gpui_platform = { git = "https://github.com/streetwriters/gpui-fast", rev = "1ad3cc3" }
# End managed by autolink.
-172
View File
@@ -1,172 +0,0 @@
fn main() {
// Forwards the engine's Node-API exports out of this executable, which is
// what lets a stock `.node` addon resolve them on Windows.
//
// A DLL records every import as a name *plus the file it comes from*, and a
// node-gyp addon records "from `node.exe`" — Windows has no global symbol
// scope for it to fall back on. Node's own answer is that the host process
// exports the Node-API functions, so that is what this does: the executable
// re-exports each of the VM's `napi_*`/`node_api_*` names, forwarded to
// `hermesvm.dll`. Addons that use node-gyp's delay-load hook (the default)
// then reach this process instead of looking for `node.exe` on disk.
//
// It is a no-op on macOS and Linux, where an addon's imports resolve against
// whatever is already loaded and need no forwarding. Declare it once, before
// the module list; it does not depend on anything else in this file.
rn_gpui_module_build::forward_node_api_exports();
// App-local Rust TurboModules: list one entry per `src/Native*.ts` spec,
// for example `&["src/NativeGreeting.ts"]`. Their glue is generated into
// this crate's OUT_DIR, and main.rs registers the modules.
rn_gpui_module_build::generate(&["src/NativePaseoDesktop.ts"]);
let desktop_root = std::path::PathBuf::from(
std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set"),
);
// `app.json` names the app; `desktop/desktop.json` carries the identifier
// and everything else the packaging step needs. The loader the CLI uses is
// JavaScript, so this reads the same file directly and applies the two
// defaults it would apply.
let project_root = desktop_root
.parent()
.expect("desktop folder has a React Native project root");
let app_json_path = project_root.join("app.json");
println!("cargo:rerun-if-changed={}", app_json_path.display());
let app_json: serde_json::Value = serde_json::from_slice(
&std::fs::read(&app_json_path)
.unwrap_or_else(|error| panic!("read {}: {error}", app_json_path.display())),
)
.unwrap_or_else(|error| panic!("parse {}: {error}", app_json_path.display()));
let app_name = app_json["name"]
.as_str()
.filter(|name| !name.is_empty())
.expect("app.json must define a nonempty name");
if app_json["desktop"]
.as_object()
.is_some_and(|desktop| !desktop.is_empty())
{
panic!("move `app.json` desktop.* into `desktop/desktop.json` (see the README)");
}
let desktop_json_path = project_root.join("desktop/desktop.json");
println!("cargo:rerun-if-changed={}", desktop_json_path.display());
let desktop_json: serde_json::Value = std::fs::read(&desktop_json_path)
.ok()
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
.unwrap_or(serde_json::Value::Null);
let app_id = match desktop_json["identifier"].as_str() {
Some(identifier) if !identifier.is_empty() => identifier.to_string(),
_ => format!(
"com.example.{}",
app_name
.to_lowercase()
.chars()
.map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
.collect::<String>()
),
};
println!("cargo:rustc-env=RN_GPUI_APP_NAME={app_name}");
println!("cargo:rustc-env=RN_GPUI_APP_ID={app_id}");
// Only a debug build names the bundle it was developed against. A release
// binary must find the bundle beside its own executable, because the path
// baked in here is where this machine happened to build it — and on the
// machine the package is installed on, that path does not exist.
println!("cargo:rerun-if-env-changed=PROFILE");
if std::env::var("PROFILE").as_deref() == Ok("debug") {
println!(
"cargo:rustc-env=RN_GPUI_DEFAULT_BUNDLE={}",
desktop_root.join("build/index.bundle").display()
);
}
println!("cargo:rerun-if-env-changed=DEP_RN_GPUI_RUNTIME_RPATHS");
println!("cargo:rerun-if-env-changed=RN_GPUI_PACKAGING");
let Ok(paths) = std::env::var("DEP_RN_GPUI_RUNTIME_RPATHS") else {
return;
};
let dirs = paths.split('|').filter(|path| !path.is_empty());
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
stage_shared_libraries(dirs);
return;
}
// `RN_GPUI_PACKAGING` means this binary is about to be installed somewhere
// else, so only the relative rpaths belong in it. Keeping the absolute ones
// would let a packaged app load this build tree's libraries in preference to
// its own on the machine that built it — which hides exactly the packaging
// bugs the packaged run exists to catch.
let packaging = std::env::var("RN_GPUI_PACKAGING").is_ok();
if !packaging {
for path in dirs {
println!("cargo:rustc-link-arg=-Wl,-rpath,{path}");
}
}
emit_relocatable_rpaths(app_name);
}
/// rpaths that survive being installed somewhere else.
///
/// The absolute paths above let a development build run from this tree. A
/// packaged app is copied to another machine, where those paths do not exist,
/// so a release build also carries paths relative to the executable: the
/// layout the installers produce.
fn emit_relocatable_rpaths(app_name: &str) {
if std::env::var("PROFILE").as_deref() != Ok("release") {
return;
}
let os = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
let mut emit = |rpath: String| println!("cargo:rustc-link-arg=-Wl,-rpath,{rpath}");
match os.as_str() {
// An app bundle puts the executable in Contents/MacOS and the shipped
// libraries in Contents/Frameworks.
"macos" => emit("@executable_path/../Frameworks".into()),
// Linux installs the executable at `usr/bin` and ships its libraries
// under `usr/lib`:
// - the deb puts them in `usr/lib/<app>`;
// - an AppImage's libraries are flat in `usr/lib`, because that is the
// directory AppRun puts on the library path and the one linuxdeploy
// resolves dependencies from before the image is assembled.
// Both are covered, so one binary works in either layout.
"linux" => {
emit(format!("$ORIGIN/../lib/{app_name}"));
emit("$ORIGIN/../lib".into());
emit("$ORIGIN".into());
}
// Windows has no rpath: the DLLs are copied beside the executable.
_ => {}
}
}
/// Windows has no rpath: the loader finds a DLL next to the executable or on
/// `PATH`, so every directory the runtime reports as holding a shared library
/// (the Hermes binary directory in particular) is copied into the profile
/// directory that receives this app's executable. Without this the app builds
/// and then fails to start with "hermesvm.dll was not found".
fn stage_shared_libraries<'a>(dirs: impl Iterator<Item = &'a str>) {
let out_dir = std::path::PathBuf::from(std::env::var("OUT_DIR").expect("OUT_DIR is set"));
// <profile>/build/<package>-<hash>/out -> <profile>
let Some(profile_dir) = out_dir.ancestors().nth(3) else {
return;
};
for dir in dirs {
let Ok(entries) = std::fs::read_dir(dir) else {
continue;
};
for entry in entries.flatten() {
let source = entry.path();
let is_shared_library = source
.extension()
.and_then(|extension| extension.to_str())
.is_some_and(|extension| extension.eq_ignore_ascii_case("dll"));
if !is_shared_library {
continue;
}
let Some(name) = source.file_name() else {
continue;
};
println!("cargo:rerun-if-changed={}", source.display());
std::fs::copy(&source, profile_dir.join(name)).unwrap_or_else(|error| {
panic!("copy {} next to the executable: {error}", source.display())
});
}
}
}
-4
View File
@@ -1,4 +0,0 @@
{
"identifier": "sh.paseo.gpui",
"bundle": { "macos": { "minimumSystemVersion": "15.0" } }
}
@@ -1,271 +0,0 @@
use gpui::{
div, px, App, AppContext, Context, IntoElement, ParentElement, Render, Styled, Window,
WindowBounds, WindowOptions,
};
use react_native_gpui::DesktopAppConfig;
use rn_gpui_enriched_markdown::layout::{layout_document, LaidOutDocument};
use rn_gpui_enriched_markdown::model::MarkdownSnapshot;
use rn_gpui_enriched_markdown::render::render_document;
use std::ffi::{c_char, c_int, CStr, CString};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
extern "C" {
fn rn_gpui_markdown_bench_stages(
markdown: *const c_char,
is_gfm: bool,
style_json: *const c_char,
out_parse_ns: *mut f64,
out_highlight_ns: *mut f64,
out_serialize_ns: *mut f64,
out_json: *mut *mut c_char,
out_json_len: *mut usize,
) -> c_int;
fn rn_gpui_markdown_bench_free(ptr: *mut c_char);
}
struct BenchState {
render_doc_ns: f64,
}
struct BenchView {
doc: Arc<LaidOutDocument>,
state: Arc<Mutex<BenchState>>,
}
impl Render for BenchView {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let t0 = Instant::now();
let el = render_document(&self.doc, 1);
let elapsed_ns = t0.elapsed().as_secs_f64() * 1e9;
if let Ok(mut s) = self.state.lock() {
s.render_doc_ns = elapsed_ns;
}
div().w(px(720.0)).bg(gpui::rgb(0xffffff)).child(el)
}
}
const STYLE_JSON: &str = r##"{
"paragraph": { "fontSize": 15, "lineHeight": 21, "color": 4279900702, "marginBottom": 12 },
"h1": { "fontSize": 24, "lineHeight": 31, "fontWeight": "bold", "color": 4279900702, "marginBottom": 12 },
"h2": { "fontSize": 21, "lineHeight": 27, "fontWeight": "bold", "color": 4279900702, "marginBottom": 12 },
"h3": { "fontSize": 18, "lineHeight": 23, "fontWeight": "bold", "color": 4279900702, "marginBottom": 12 },
"list": { "fontSize": 15, "lineHeight": 21, "color": 4279900702, "bulletColor": 4285624698, "markerColor": 4285624698, "gapWidth": 7, "itemSpacing": 4, "marginLeft": 20, "marginBottom": 12 },
"blockquote": { "fontSize": 15, "lineHeight": 21, "color": 4279900702, "backgroundColor": 4294638330, "borderColor": 4293190887, "borderWidth": 3, "padding": 12, "gapWidth": 8, "marginBottom": 12 },
"link": { "color": 4280523094, "underline": false },
"code": { "fontFamily": "monospace", "fontScale": 0.8, "color": 4279900702, "backgroundColor": 4294243573 },
"codeBlock": {
"fontFamily": "monospace", "fontSize": 12, "lineHeight": 21, "color": 4279900702,
"backgroundColor": 4294243573, "borderColor": 4293190887, "borderRadius": 8, "padding": 12, "marginBottom": 12,
"syntaxColors": {
"keyword": 4294933362, "string": 4289058559, "comment": 4287337630, "number": 4286169343,
"type": 4294944343, "function": 4291995903, "operatorColor": 4294933362, "punctuation": 4286495103
}
},
"table": {
"fontSize": 15, "lineHeight": 21, "color": 4279900702,
"headerBackgroundColor": 4294243573, "headerTextColor": 4279900702,
"rowEvenBackgroundColor": 4294967295, "rowOddBackgroundColor": 4294638330,
"borderColor": 4293190887, "marginBottom": 12
}
}"##;
fn build_realistic_reply(target_bytes: usize) -> String {
let section_prose = "\n## Module Analysis and Data Flow\n\n\
The renderer translates snapshots from `packages/react-native-enriched-markdown/cpp/GpuiMarkdownBridge.cpp` into \
**GPUI elements** with *inline styles* and links such as [protocol docs](https://paseo.sh/docs/protocol). \
When a streaming token arrives, React commits the updated `markdown` string and re-measures the node.\n\n\
- Preserves AST structure for headings, paragraphs, emphasis, and `inline_code`\n\
- Highlights fenced code blocks using Tree-sitter grammars\n\
- Lays out GFM tables with measured column widths\n";
let section_code = "\n```ts\n\
export interface StreamDelta {\n\
readonly messageId: string;\n\
readonly seq: number;\n\
readonly chunk: string;\n\
}\n\n\
export function applyDelta(acc: Map<string, string>, delta: StreamDelta): string {\n\
const prev = acc.get(delta.messageId) ?? \"\";\n\
const next = prev + delta.chunk;\n\
acc.set(delta.messageId, next);\n\
return next;\n\
}\n\
```\n";
let section_table = "\n| Stage | Input | Output | Owner |\n\
| --- | --- | --- | --- |\n\
| Parse | Markdown UTF-8 | MD4C AST | C++ |\n\
| Highlight | Code lines | Token ranges | Tree-sitter |\n\
| Serialize | AST + Style | JSON string | folly::toJson |\n\
| Deserialize | JSON string | MarkdownSnapshot | serde_json |\n\
| Layout | Snapshot + width | LaidOutDocument | layout.rs |\n\
| Paint | LaidOutDocument | GPUI scene | render.rs + gpui |\n";
let mut out = String::from("# Architecture Overview\n\nStreaming reply benchmark fixture with realistic prose, code blocks, lists, and a table.\n");
out.push_str(section_table);
let mut i = 0usize;
while out.len() < target_bytes {
out.push_str(section_prose);
if i % 2 == 0 {
out.push_str(section_code);
}
if i % 5 == 4 && out.len() + section_table.len() < target_bytes {
out.push_str(section_table);
}
i += 1;
}
out
}
fn median_ms(samples: &mut [f64]) -> f64 {
samples.sort_by(|a, b| a.total_cmp(b));
let mid = samples.len() / 2;
if samples.len() % 2 == 0 {
((samples[mid - 1] + samples[mid]) * 0.5) / 1e6
} else {
samples[mid] / 1e6
}
}
fn mean_ms(samples: &[f64]) -> f64 {
let sum: f64 = samples.iter().sum();
(sum / samples.len() as f64) / 1e6
}
fn run_bench_on_app(cx: &mut App) {
let bench_state = Arc::new(Mutex::new(BenchState { render_doc_ns: 0.0 }));
let bench_state_init = bench_state.clone();
let window = cx
.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(gpui::Bounds::centered(
None,
gpui::size(px(800.0), px(1200.0)),
cx,
))),
..Default::default()
},
|_, cx| {
cx.new(|_| BenchView {
doc: Arc::new(LaidOutDocument::default()),
state: bench_state_init,
})
},
)
.unwrap();
let _ = cx.update_window(window.into(), |_, window, cx| {
window.draw(cx).clear(cx);
});
let style_c = CString::new(STYLE_JSON).unwrap();
for &(label, target_bytes, iters) in &[
("5 KB", 5 * 1024usize, 25usize),
("20 KB", 20 * 1024usize, 15usize),
("100 KB", 100 * 1024usize, 7usize),
] {
let base = build_realistic_reply(target_bytes);
let actual_bytes = base.len();
let mut parse_s = Vec::with_capacity(iters);
let mut hl_s = Vec::with_capacity(iters);
let mut ser_s = Vec::with_capacity(iters);
let mut deser_s = Vec::with_capacity(iters);
let mut layout_s = Vec::with_capacity(iters);
let mut paint_s = Vec::with_capacity(iters);
let mut build_el_s = Vec::with_capacity(iters);
for step in 0..=iters {
let md = if step == 0 {
base.clone()
} else {
format!("{base}\nStreamed token chunk #{step}.")
};
let md_c = CString::new(md).unwrap();
let mut parse_ns = 0.0f64;
let mut hl_ns = 0.0f64;
let mut ser_ns = 0.0f64;
let mut out_ptr: *mut c_char = std::ptr::null_mut();
let mut out_len: usize = 0;
let rc = unsafe {
rn_gpui_markdown_bench_stages(
md_c.as_ptr(),
true,
style_c.as_ptr(),
&mut parse_ns,
&mut hl_ns,
&mut ser_ns,
&mut out_ptr,
&mut out_len,
)
};
assert_eq!(rc, 0, "C++ bench failed");
let json = unsafe { CStr::from_ptr(out_ptr) }
.to_str()
.unwrap()
.to_owned();
unsafe { rn_gpui_markdown_bench_free(out_ptr) };
let t_deser = Instant::now();
let snapshot: MarkdownSnapshot = serde_json::from_str(&json).unwrap();
let deser_ns = t_deser.elapsed().as_secs_f64() * 1e9;
let t_layout = Instant::now();
let doc = Arc::new(layout_document(&snapshot, Some(680.0)));
let layout_ns = t_layout.elapsed().as_secs_f64() * 1e9;
let mut paint_elapsed = Duration::ZERO;
let _ = window.update(cx, |v, _, cx| {
v.doc = doc.clone();
cx.notify();
});
let _ = cx.update_window(window.into(), |_, window, cx| {
let t_paint = Instant::now();
window.refresh();
window.draw(cx).clear(cx);
paint_elapsed = t_paint.elapsed();
});
let render_doc_ns = bench_state.lock().map(|s| s.render_doc_ns).unwrap_or(0.0);
if step > 0 {
parse_s.push(parse_ns);
hl_s.push(hl_ns);
ser_s.push(ser_ns);
deser_s.push(deser_ns);
layout_s.push(layout_ns);
paint_s.push(paint_elapsed.as_secs_f64() * 1e9);
build_el_s.push(render_doc_ns);
}
}
let p_med = median_ms(&mut parse_s);
let h_med = median_ms(&mut hl_s);
let s_med = median_ms(&mut ser_s);
let d_med = median_ms(&mut deser_s);
let l_med = median_ms(&mut layout_s);
let pt_med = median_ms(&mut paint_s);
let total_med = p_med + h_med + s_med + d_med + l_med + pt_med;
println!(
"SIZE={label} bytes={actual_bytes} iters={iters} | MEDIAN_MS: parse={p_med:.3} highlight={h_med:.3} serialize={s_med:.3} deserialize={d_med:.3} layout={l_med:.3} paint={pt_med:.3} (build_el={:.3}) total={total_med:.3} | MEAN_MS: parse={:.3} highlight={:.3} serialize={:.3} deserialize={:.3} layout={:.3} paint={:.3}",
median_ms(&mut build_el_s),
mean_ms(&parse_s),
mean_ms(&hl_s),
mean_ms(&ser_s),
mean_ms(&deser_s),
mean_ms(&layout_s),
mean_ms(&paint_s),
);
}
std::process::exit(0);
}
fn main() {
rn_gpui_autolink::ensure_linked();
let config =
DesktopAppConfig::from_env_with_defaults(env!("RN_GPUI_APP_NAME"), env!("RN_GPUI_APP_ID"))
.window_title("Markdown Bench")
.window_size(800.0, 1200.0)
.on_app_ready(run_bench_on_app);
react_native_gpui::run_with(config);
}
-77
View File
@@ -1,77 +0,0 @@
const path = require("node:path");
const { makeMetroConfig } = require("@react-native-gpui/core/metro.config");
const projectRoot = path.resolve(__dirname, "..");
process.env.EXPO_ROUTER_APP_ROOT = path.resolve(projectRoot, "../src/app");
const config = makeMetroConfig({ projectRoot });
const resolveRequest = config.resolver.resolveRequest;
config.watchFolders.push(path.resolve(projectRoot, "../../.."));
config.transformer.unstable_allowRequireContext = true;
config.resolver.disableHierarchicalLookup = false;
config.resolver.blockList = /[/\\]gpui[/\\]desktop[/\\](target|build|autolink)[/\\]/;
// Metro loops over sourceExts outside platform suffixes, so listing gpui.<ext>
// first selects .gpui.* ahead of .desktop, .native, and base extensions.
config.resolver.sourceExts = [
...config.resolver.sourceExts.map((ext) => `gpui.${ext}`),
...config.resolver.sourceExts,
];
const nativePackages = [
"react",
"react-native-reanimated",
"react-native-worklets",
"react-native-gesture-handler",
"react-native-screens",
"react-native-safe-area-context",
"react-native-svg",
];
const adapters = {
"expo-keep-awake": "keep-awake.js",
"expo-image-picker": "image-picker.js",
"expo-image-manipulator": "image-manipulator.js",
"expo-sharing": "sharing.js",
"expo-document-picker": "document-picker.js",
"@mattermost/react-native-paste-input": "paste-input.js",
"@react-native-async-storage/async-storage": "async-storage.js",
"expo-localization": "localization.js",
"expo-clipboard": "clipboard.js",
"expo-file-system": "file-system.js",
"expo-file-system/legacy": "file-system.js",
"react-native-keyboard-controller": "keyboard.jsx",
crypto: "node-crypto.js",
"node:crypto": "node-crypto.js",
"expo-sqlite": "sqlite.js",
"expo-crypto": "crypto.js",
"react-native-unistyles": "unistyles.js",
};
config.resolver.resolveRequest = (context, name, platform) => {
if (adapters[name]) name = path.resolve(projectRoot, "adapters", adapters[name]);
if (
name.endsWith("/ensureNativeModulesAreInstalled") &&
context.originModulePath.includes("expo-modules-core")
)
name = path.resolve(projectRoot, "adapters/expo-install.js");
if (name === "./ExpoLinking" && context.originModulePath.includes("expo-linking"))
name = path.resolve(projectRoot, "adapters/expo-linking.js");
// Linux has no Expo mobile push-token or camera provider; reuse the app's
// existing unavailable-capability implementations.
if (name === "expo-notifications")
name = path.resolve(projectRoot, "../src/fdroid/expo-notifications.ts");
if (name === "expo-camera") name = path.resolve(projectRoot, "../src/fdroid/expo-camera.tsx");
if (name === "expo-router/_ctx") name = path.resolve(projectRoot, "routes.js");
if (name === "qrcode") name = "qrcode/lib/browser.js";
if (name.startsWith("react-native-unistyles/components/native/"))
name = path.resolve(projectRoot, "adapters/unistyles-components.js");
if (name.startsWith("@/")) name = path.resolve(projectRoot, "../src", name.slice(2));
if (
name.startsWith("react-native/") ||
nativePackages.some((pkg) => name === pkg || name.startsWith(`${pkg}/`))
) {
context = {
...context,
disableHierarchicalLookup: true,
nodeModulesPaths: [path.join(projectRoot, "node_modules")],
};
}
return resolveRequest(context, name, platform);
};
module.exports = config;
@@ -1,9 +0,0 @@
import { TurboModuleRegistry, type TurboModule } from "react-native";
export interface Spec extends TurboModule {
sqlite(sql: string, params: string): string;
locale(): string;
timezone(): string;
sha256(text: string): string;
randomBytes(length: number): Array<number>;
}
export default TurboModuleRegistry.getEnforcing<Spec>("PaseoDesktop");
-29
View File
@@ -1,29 +0,0 @@
rn_gpui_module::include_specs!();
mod services;
fn main() {
react_native_gpui::register_module(native_paseo_desktop_module::<services::PaseoDesktop>());
rn_gpui_autolink::ensure_linked();
// A debug build knows where its own bundle is; a release build does not, and
// must not: the path would name the machine that built it. A packaged release
// app resolves the bundle beside its executable instead.
#[cfg(debug_assertions)]
if std::env::var_os("RN_GPUI_BUNDLE").is_none() {
std::env::set_var("RN_GPUI_BUNDLE", env!("RN_GPUI_DEFAULT_BUNDLE"));
}
let config = react_native_gpui::DesktopAppConfig::from_env_with_defaults(
env!("RN_GPUI_APP_NAME"),
env!("RN_GPUI_APP_ID"),
)
.window_title("Paseo GPUI")
.window_size(1024.0, 768.0)
.dev_menu(true)
.configure_window(|options| {
// GPUI window options are public: titlebar, resizability, display,
// decorations, min size, and other native window behavior.
options.is_resizable = true;
});
react_native_gpui::run_with(config);
}
-174
View File
@@ -1,174 +0,0 @@
use crate::{NativePaseoDesktopEvents, NativePaseoDesktopSpec};
use rn_gpui_module::ModuleError;
use std::io::Read;
pub struct PaseoDesktop {
database: std::sync::Mutex<Option<rusqlite::Connection>>,
}
impl PaseoDesktop {
fn database(
&self,
) -> Result<std::sync::MutexGuard<'_, Option<rusqlite::Connection>>, ModuleError> {
let mut guard = self
.database
.lock()
.map_err(|e| ModuleError::new(e.to_string()))?;
if guard.is_none() {
let base = std::env::var("XDG_DATA_HOME")
.map(std::path::PathBuf::from)
.unwrap_or_else(|_| {
std::path::PathBuf::from(std::env::var("HOME").expect("HOME is set"))
.join(".local/share")
});
let dir = base.join("paseo-gpui");
std::fs::create_dir_all(&dir).map_err(|e| ModuleError::new(e.to_string()))?;
*guard = Some(
rusqlite::Connection::open(dir.join("replica.db"))
.map_err(|e| ModuleError::new(e.to_string()))?,
);
}
Ok(guard)
}
}
impl NativePaseoDesktopSpec for PaseoDesktop {
fn new(_events: NativePaseoDesktopEvents) -> Self {
Self {
database: std::sync::Mutex::new(None),
}
}
fn sqlite(&self, sql: String, params: String) -> Result<String, ModuleError> {
let fail = |e: rusqlite::Error| ModuleError::new(e.to_string());
let db = self.database()?;
let db = db.as_ref().unwrap();
if params == "batch" {
db.execute_batch(&sql).map_err(fail)?;
return Ok("[]".into());
}
let values: Vec<serde_json::Value> =
serde_json::from_str(&params).map_err(|e| ModuleError::new(e.to_string()))?;
let values: Vec<rusqlite::types::Value> = values
.into_iter()
.map(|v| match v {
serde_json::Value::Null => rusqlite::types::Value::Null,
serde_json::Value::String(v) => rusqlite::types::Value::Text(v),
serde_json::Value::Number(v) => v
.as_i64()
.map(rusqlite::types::Value::Integer)
.unwrap_or_else(|| rusqlite::types::Value::Real(v.as_f64().unwrap())),
_ => rusqlite::types::Value::Text(v.to_string()),
})
.collect();
let mut stmt = db.prepare(&sql).map_err(fail)?;
let names: Vec<String> = stmt.column_names().into_iter().map(str::to_owned).collect();
let mut rows = stmt
.query(rusqlite::params_from_iter(values))
.map_err(fail)?;
let mut results = Vec::new();
while let Some(row) = rows.next().map_err(fail)? {
let mut object = serde_json::Map::new();
for (index, name) in names.iter().enumerate() {
let value = match row.get_ref(index).map_err(fail)? {
rusqlite::types::ValueRef::Null => serde_json::Value::Null,
rusqlite::types::ValueRef::Integer(v) => v.into(),
rusqlite::types::ValueRef::Real(v) => serde_json::json!(v),
rusqlite::types::ValueRef::Text(v) => {
String::from_utf8_lossy(v).into_owned().into()
}
rusqlite::types::ValueRef::Blob(_) => {
return Err(ModuleError::new(
"Replica store does not support blob columns",
))
}
};
object.insert(name.clone(), value);
}
results.push(object);
}
serde_json::to_string(&results).map_err(|e| ModuleError::new(e.to_string()))
}
fn timezone(&self) -> Result<String, ModuleError> {
if let Ok(zone) = std::env::var("TZ") {
if !zone.is_empty() {
return Ok(zone.trim_start_matches(':').into());
}
}
if let Ok(path) = std::fs::read_link("/etc/localtime") {
if let Some((_, zone)) = path.to_string_lossy().split_once("/zoneinfo/") {
return Ok(zone.into());
}
}
Ok(std::fs::read_to_string("/etc/timezone")
.map(|s| s.trim().into())
.unwrap_or_else(|_| "UTC".into()))
}
fn locale(&self) -> Result<String, ModuleError> {
Ok(["LC_ALL", "LC_MESSAGES", "LANG"]
.iter()
.find_map(|key| std::env::var(key).ok().filter(|v| !v.is_empty()))
.unwrap_or_else(|| "en_US.UTF-8".into()))
}
fn sha256(&self, text: String) -> Result<String, ModuleError> {
use sha2::{Digest, Sha256};
Ok(format!("{:x}", Sha256::digest(text.as_bytes())))
}
fn random_bytes(&self, length: f64) -> Result<Vec<f64>, ModuleError> {
if !length.is_finite() || length < 0.0 || length > 65536.0 || length.fract() != 0.0 {
return Err(ModuleError::new("Invalid random byte count"));
}
let mut bytes = vec![0u8; length as usize];
std::fs::File::open("/dev/urandom")
.and_then(|mut source| source.read_exact(&mut bytes))
.map_err(|error| ModuleError::new(error.to_string()))?;
Ok(bytes.into_iter().map(f64::from).collect())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn service() -> PaseoDesktop {
PaseoDesktop {
database: std::sync::Mutex::new(Some(rusqlite::Connection::open_in_memory().unwrap())),
}
}
#[test]
fn crypto_matches_sha256_and_bounds_random_requests() {
let service = service();
assert_eq!(
service.sha256("abc".into()).unwrap(),
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
);
assert_eq!(service.random_bytes(32.0).unwrap().len(), 32);
assert!(service.random_bytes(65537.0).is_err());
assert!(service.random_bytes(-1.0).is_err());
}
#[test]
fn replica_transactions_bind_values_and_roll_back() {
let service = service();
service
.sqlite(
"CREATE TABLE rows (key TEXT PRIMARY KEY, value TEXT);".into(),
"batch".into(),
)
.unwrap();
service
.sqlite(
"INSERT INTO rows VALUES (?, ?)".into(),
r#"["key","quoted ' value"]"#.into(),
)
.unwrap();
service
.sqlite(
"BEGIN IMMEDIATE; DELETE FROM rows; ROLLBACK;".into(),
"batch".into(),
)
.unwrap();
let result = service
.sqlite("SELECT key, value FROM rows".into(), "[]".into())
.unwrap();
assert_eq!(
serde_json::from_str::<serde_json::Value>(&result).unwrap(),
serde_json::json!([{"key":"key","value":"quoted ' value"}])
);
}
}
-10
View File
@@ -1,10 +0,0 @@
/* oxlint-disable import/no-unassigned-import -- Install globals before app modules evaluate. */
import "./adapters/intl";
import "../src/polyfills/install-early";
import "../src/styles/unistyles";
import { AppRegistry } from "react-native";
import { RootApp } from "../src/root-app";
// GPUI owns the native surface. Keep Paseo's full router and providers, while
// leaving Expo's mobile registration and WebView-based dev overlay out.
AppRegistry.registerComponent("Paseo", () => RootApp);
@@ -1,401 +0,0 @@
/* oxlint-disable react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop -- Minimal markdown native regression scene. */
import React, { useCallback, useState } from "react";
import { AppRegistry, Pressable, Text, View } from "react-native";
import { EnrichedMarkdownText } from "react-native-enriched-markdown";
const BASE_MARKDOWN = `# Phase 1 Heading
## Subhead \`code\`
**bold**, *italic*, ~~struck~~, [docs](https://example.com/guide).
> Blockquote note
- Bullet one
- Bullet two
1. Ordered one
2. Ordered two
- [x] Done task
- [ ] Open task
\`\`\`ts
const n: number = 42;
function hi(s: string): string {
return \`Hi \${s}\`;
}
\`\`\`
| Component | Status |
| --- | --- |
| Parser | Ready |`;
const STREAM_APPEND = `
### Streamed
Appended **live** and [next](https://example.com/streamed).`;
const MARKDOWN_STYLE = {
paragraph: {
fontSize: 13,
lineHeight: 17,
color: "#111827",
marginBottom: 4,
},
h1: {
fontSize: 19,
lineHeight: 23,
fontWeight: "700",
color: "#0f172a",
marginBottom: 4,
},
h2: {
fontSize: 16,
lineHeight: 20,
fontWeight: "600",
color: "#1e293b",
marginTop: 2,
marginBottom: 4,
},
h3: {
fontSize: 14,
lineHeight: 18,
fontWeight: "600",
color: "#1e293b",
marginTop: 2,
marginBottom: 2,
},
h5: {
fontSize: 13,
lineHeight: 17,
fontWeight: "600",
color: "#334155",
marginBottom: 2,
},
strong: { fontWeight: "700" },
em: { fontStyle: "italic" },
strikethrough: { textDecorationLine: "line-through", color: "#64748b" },
code: {
fontFamily: "monospace",
fontScale: 0.85,
color: "#0f172a",
backgroundColor: "#e2e8f0",
},
link: {
color: "#2563eb",
underline: true,
},
list: {
fontSize: 13,
lineHeight: 17,
color: "#111827",
bulletColor: "#475569",
markerColor: "#475569",
bulletSize: 5,
gapWidth: 6,
marginLeft: 14,
itemSpacing: 1,
marginBottom: 4,
},
taskList: {
checkedColor: "#2563eb",
borderColor: "#475569",
checkmarkColor: "#ffffff",
checkedTextColor: "#64748b",
checkedStrikethrough: true,
checkboxSize: 13,
},
blockquote: {
fontSize: 13,
lineHeight: 17,
color: "#1e293b",
backgroundColor: "#eff6ff",
borderColor: "#2563eb",
borderWidth: 4,
padding: 6,
gapWidth: 6,
marginBottom: 4,
},
codeBlock: {
fontFamily: "monospace",
fontSize: 11,
lineHeight: 15,
color: "#e2e8f0",
backgroundColor: "#0f172a",
borderColor: "#334155",
borderWidth: 1,
borderRadius: 6,
padding: 6,
marginBottom: 4,
syntaxColors: {
keyword: "#c084fc",
string: "#86efac",
comment: "#94a3b8",
number: "#fbbf24",
type: "#38bdf8",
function: "#60a5fa",
operator: "#f472b6",
punctuation: "#cbd5e1",
},
},
table: {
fontSize: 12,
lineHeight: 16,
color: "#111827",
headerFontWeight: "700",
headerBackgroundColor: "#dbeafe",
headerTextColor: "#0f172a",
rowEvenBackgroundColor: "#ffffff",
rowOddBackgroundColor: "#f8fafc",
borderColor: "#2563eb",
borderWidth: 1,
borderRadius: 5,
cellPaddingHorizontal: 6,
cellPaddingVertical: 3,
marginBottom: 4,
},
};
function MarkdownRegression() {
const [streamed, setStreamed] = useState(false);
const [pressedLink, setPressedLink] = useState("none");
const [taskEvent, setTaskEvent] = useState("none");
const [codeEvent, setCodeEvent] = useState("none");
const [layoutText, setLayoutText] = useState("{}");
const handleLinkPress = useCallback((event) => {
setPressedLink(event?.url ?? "missing");
}, []);
const handleTaskPress = useCallback((event) => {
setTaskEvent(`${event?.index}:${event?.checked}:${event?.text}`);
}, []);
const handleCodePress = useCallback((event) => {
setCodeEvent(`${event?.language}:${String(event?.code ?? "").trim().length}`);
}, []);
const handleLayout = useCallback((event) => {
const layout = event?.nativeEvent?.layout;
if (layout) setLayoutText(JSON.stringify(layout));
}, []);
const markdown = streamed ? `${BASE_MARKDOWN}${STREAM_APPEND}` : BASE_MARKDOWN;
return (
<View
style={{ flex: 1, flexDirection: "row", padding: 8, gap: 10, backgroundColor: "#ffffff" }}
>
<View style={{ width: 320, gap: 4, backgroundColor: "#ffffff" }}>
<View style={{ flexDirection: "row", alignItems: "center", gap: 6, flexWrap: "wrap" }}>
<EnrichedMarkdownText
testID="markdown-link-target"
flavor="github"
markdown="[Open docs](https://example.com/docs)"
markdownStyle={MARKDOWN_STYLE}
onLinkPress={handleLinkPress}
allowTrailingMargin={false}
style={{ alignSelf: "flex-start" }}
/>
<Pressable
testID="markdown-stream-next"
onPress={() => setStreamed(true)}
style={{
width: 82,
height: 20,
backgroundColor: "#e2e8f0",
justifyContent: "center",
alignItems: "center",
}}
>
<Text style={{ fontSize: 12 }}>Stream Next</Text>
</Pressable>
<Text testID="pressed-link" style={{ fontSize: 11 }}>
{pressedLink}
</Text>
<Text testID="task-event" style={{ fontSize: 11 }}>
{taskEvent}
</Text>
<Text testID="code-event" style={{ fontSize: 11 }}>
{codeEvent}
</Text>
</View>
<Text testID="markdown-layout" style={{ fontSize: 10 }}>
{layoutText}
</Text>
<EnrichedMarkdownText
testID="markdown-view"
flavor="github"
markdown={markdown}
md4cFlags={{ underline: true, latexMath: true }}
markdownStyle={MARKDOWN_STYLE}
onLinkPress={handleLinkPress}
onLayout={handleLayout}
allowTrailingMargin={false}
/>
</View>
<View style={{ width: 320, gap: 3, backgroundColor: "#ffffff" }}>
<View style={{ flexDirection: "row", gap: 6, backgroundColor: "#ffffff" }}>
<View testID="probe-text-plain" style={{ backgroundColor: "#ffffff" }}>
<Text style={{ fontSize: 13, color: "#111827" }}>Sample</Text>
</View>
<View testID="probe-text-bold" style={{ backgroundColor: "#ffffff" }}>
<Text style={{ fontSize: 13, fontWeight: "700", color: "#111827" }}>Sample</Text>
</View>
<View testID="probe-text-italic" style={{ backgroundColor: "#ffffff" }}>
<Text style={{ fontSize: 13, fontStyle: "italic", color: "#111827" }}>Sample</Text>
</View>
</View>
<View style={{ flexDirection: "row", gap: 6, alignItems: "flex-start" }}>
<View testID="block-h1" style={{ width: 155, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
testID="block-h1-md"
flavor="github"
markdown="# Heading A"
markdownStyle={MARKDOWN_STYLE}
allowTrailingMargin={false}
/>
</View>
<View testID="block-h5" style={{ width: 155, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
testID="block-h5-md"
flavor="github"
markdown="##### Heading A"
markdownStyle={MARKDOWN_STYLE}
allowTrailingMargin={false}
/>
</View>
</View>
<View style={{ flexDirection: "row", gap: 6 }}>
<View testID="block-emphasis-plain" style={{ width: 155, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
flavor="github"
markdown="alpha beta gamma"
markdownStyle={MARKDOWN_STYLE}
allowTrailingMargin={false}
/>
</View>
<View testID="block-emphasis-styled" style={{ width: 155, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
flavor="github"
markdown="**alpha** *beta* ~~gamma~~"
markdownStyle={MARKDOWN_STYLE}
allowTrailingMargin={false}
/>
</View>
</View>
<View style={{ flexDirection: "row", gap: 6 }}>
<View testID="block-inline-code-plain" style={{ width: 155, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
flavor="github"
markdown="use code_val"
markdownStyle={MARKDOWN_STYLE}
allowTrailingMargin={false}
/>
</View>
<View testID="block-inline-code" style={{ width: 155, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
flavor="github"
markdown={"use `code_val`"}
markdownStyle={MARKDOWN_STYLE}
allowTrailingMargin={false}
/>
</View>
</View>
<View style={{ flexDirection: "row", gap: 6 }}>
<View testID="block-ul" style={{ width: 100, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
flavor="github"
markdown={"- One\n- Two"}
markdownStyle={MARKDOWN_STYLE}
allowTrailingMargin={false}
/>
</View>
<View testID="block-ol-1" style={{ width: 100, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
flavor="github"
markdown={"1. One\n2. Two"}
markdownStyle={MARKDOWN_STYLE}
allowTrailingMargin={false}
/>
</View>
<View testID="block-ol-8" style={{ width: 100, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
flavor="github"
markdown={"8. One\n9. Two"}
markdownStyle={MARKDOWN_STYLE}
allowTrailingMargin={false}
/>
</View>
</View>
<View style={{ flexDirection: "row", gap: 6 }}>
<View testID="block-task-checked" style={{ width: 132, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
flavor="github"
markdown="- [x] Done task"
markdownStyle={MARKDOWN_STYLE}
allowTrailingMargin={false}
/>
</View>
<View testID="block-task-unchecked" style={{ width: 132, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
flavor="github"
markdown="- [ ] Open task"
markdownStyle={MARKDOWN_STYLE}
allowTrailingMargin={false}
/>
</View>
<EnrichedMarkdownText
testID="block-task-toggle-md"
flavor="github"
markdown="- [ ] Ok"
markdownStyle={MARKDOWN_STYLE}
enableTaskListItemToggle={true}
onTaskListItemPress={handleTaskPress}
allowTrailingMargin={false}
style={{ width: 44, height: 17 }}
/>
</View>
<View testID="block-blockquote" style={{ width: 320, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
flavor="github"
markdown="> Quoted note"
markdownStyle={MARKDOWN_STYLE}
allowTrailingMargin={false}
/>
</View>
<View testID="block-code" style={{ width: 320, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
testID="block-code-md"
flavor="github"
markdown={"```ts\nconst n: number = 42;\n```"}
markdownStyle={MARKDOWN_STYLE}
onCodeBlockPress={handleCodePress}
allowTrailingMargin={false}
/>
</View>
<View testID="block-table" style={{ width: 320, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
flavor="github"
markdown={"| ColA | ColB |\n| --- | --- |\n| Left | Right |"}
markdownStyle={MARKDOWN_STYLE}
allowTrailingMargin={false}
/>
</View>
</View>
</View>
);
}
AppRegistry.registerComponent("Paseo", () => MarkdownRegression);
-341
View File
@@ -1,341 +0,0 @@
import { afterAll, beforeAll, expect, test } from "vitest";
import sharp from "sharp";
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import path from "node:path";
const endpoint = process.env.PASEO_GPUI_TEST_URL;
const token = process.env.PASEO_GPUI_TEST_TOKEN;
const markdownFixture = process.env.PASEO_GPUI_TEST_SCENE === "markdown";
const driverLogPath = process.env.PASEO_GPUI_DRIVER_LOG;
interface Node {
tag: number;
component: string;
testID: string;
text: string;
frame?: [number, number, number, number];
children?: Node[];
}
let socket: WebSocket;
let nextId = 0;
const pending = new Map<number, { resolve(value: unknown): void; reject(error: Error): void }>();
function request<T = unknown>(method: string, params: Record<string, unknown> = {}): Promise<T> {
const id = ++nextId;
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
pending.delete(id);
reject(new Error(`GPUI ${method} timed out`));
}, 15_000);
pending.set(id, {
resolve: (value) => {
clearTimeout(timer);
resolve(value as T);
},
reject: (error) => {
clearTimeout(timer);
reject(error);
},
});
socket.send(JSON.stringify({ jsonrpc: "2.0", id, method, params: { ...params, token } }));
});
}
function flatten(node: Node): Node[] {
return [node, ...(node.children ?? []).flatMap(flatten)];
}
async function nodes() {
return (await request<{ children: Node[] }>("tree")).children.flatMap(flatten);
}
async function nodeWithId(testID: string) {
await expect
.poll(async () => {
const node = (await nodes()).find((item) => item.testID === testID);
return (node?.frame?.[2] ?? 0) > 0 && (node?.frame?.[3] ?? 0) > 0;
})
.toBe(true);
return (await nodes()).find((node) => node.testID === testID)!;
}
beforeAll(async () => {
if (!endpoint) return;
if (!token) throw new Error("PASEO_GPUI_TEST_TOKEN is required");
socket = new WebSocket(endpoint);
await new Promise<void>((resolve, reject) => {
socket.addEventListener("open", () => resolve(), { once: true });
socket.addEventListener("error", () => reject(new Error("GPUI driver connection failed")), {
once: true,
});
});
socket.addEventListener("message", (event) => {
const response = JSON.parse(String(event.data));
const waiter = pending.get(response.id);
if (!waiter) return;
pending.delete(response.id);
const error = response.error ?? response.result?.error;
if (error) waiter.reject(new Error(JSON.stringify(error)));
else waiter.resolve(response.result);
});
await new Promise((r) => setTimeout(r, 800));
});
afterAll(() => socket?.close());
async function captureRaw(tag: number) {
let png: string | undefined;
await expect
.poll(
async () => {
try {
const res = await request<{ png: string }>("screenshot", { tag });
png = res.png;
return true;
} catch {
return false;
}
},
{ timeout: 10_000, interval: 100 },
)
.toBe(true);
const bytes = Buffer.from(png!, "base64");
const { data, info } = await sharp(bytes)
.removeAlpha()
.raw()
.toBuffer({ resolveWithObject: true });
return { bytes, data, width: info.width, height: info.height, channels: info.channels };
}
function diffPixelCount(
a: { data: Buffer; width: number; height: number; channels: number },
b: { data: Buffer; width: number; height: number; channels: number },
xMax = Math.min(a.width, b.width),
) {
const w = Math.min(a.width, b.width, xMax);
const h = Math.min(a.height, b.height);
let diff = 0;
for (let y = 0; y < h; y++) {
for (let x = 0; x < w; x++) {
const ia = (y * a.width + x) * a.channels;
const ib = (y * b.width + x) * b.channels;
if (
Math.abs(a.data[ia]! - b.data[ib]!) > 12 ||
Math.abs(a.data[ia + 1]! - b.data[ib + 1]!) > 12 ||
Math.abs(a.data[ia + 2]! - b.data[ib + 2]!) > 12
) {
diff++;
}
}
}
return diff;
}
function countMatchingPixels(
img: { data: Buffer; width: number; height: number; channels: number },
pred: (r: number, g: number, b: number, x: number, y: number) => boolean,
) {
let count = 0;
for (let y = 0; y < img.height; y++) {
for (let x = 0; x < img.width; x++) {
const i = (y * img.width + x) * img.channels;
if (pred(img.data[i]!, img.data[i + 1]!, img.data[i + 2]!, x, y)) {
count++;
}
}
}
return count;
}
test.skipIf(!endpoint || !markdownFixture)(
"RN <Text> bold and italic probe matches renderer font resolution",
async () => {
const plain = await captureRaw((await nodeWithId("probe-text-plain")).tag);
const bold = await captureRaw((await nodeWithId("probe-text-bold")).tag);
const italic = await captureRaw((await nodeWithId("probe-text-italic")).tag);
const boldDiff = diffPixelCount(plain, bold);
const italicDiff = diffPixelCount(plain, italic);
console.log(
`[probe-text] plain=${plain.width}x${plain.height} boldDiff=${boldDiff} italicDiff=${italicDiff}`,
);
expect(bold.width).toBeGreaterThan(20);
},
20_000,
);
test.skipIf(!endpoint || !markdownFixture)(
"EnrichedMarkdown renders every Phase 1 block type through caller interfaces and asserts regression.png",
async () => {
const view = await nodeWithId("markdown-view");
expect(view.component).toBe("EnrichedMarkdown");
expect(view.frame?.[2] ?? 0).toBeGreaterThan(200);
expect(view.frame?.[3] ?? 0).toBeGreaterThan(250);
const layoutNode = await nodeWithId("markdown-layout");
const initialLayout = JSON.parse(layoutNode.text) as { height?: number; width?: number };
expect(initialLayout.width ?? 0).toBeGreaterThan(200);
expect(initialLayout.height ?? 0).toBeGreaterThan(250);
// 1. Headings scale vertically between H1 and H5.
const h1Node = await nodeWithId("block-h1-md");
const h5Node = await nodeWithId("block-h5-md");
expect(h1Node.frame?.[3] ?? 0).toBeGreaterThan((h5Node.frame?.[3] ?? 0) + 4);
// 2. Emphasis + strikethrough visibly alter rendered ink vs plain prose.
const empPlain = await captureRaw((await nodeWithId("block-emphasis-plain")).tag);
const empStyled = await captureRaw((await nodeWithId("block-emphasis-styled")).tag);
expect(diffPixelCount(empPlain, empStyled)).toBeGreaterThan(30);
// 3. Inline code paints its #e2e8f0 pill background and keeps distinct glyph pixels.
const codePlain = await captureRaw((await nodeWithId("block-inline-code-plain")).tag);
const codeStyled = await captureRaw((await nodeWithId("block-inline-code")).tag);
const pillBg = (r: number, g: number, b: number) =>
Math.abs(r - 0xe2) <= 8 && Math.abs(g - 0xe8) <= 8 && Math.abs(b - 0xf0) <= 8 && b - r >= 6;
expect(countMatchingPixels(codePlain, pillBg)).toBeLessThan(15);
expect(countMatchingPixels(codeStyled, pillBg)).toBeGreaterThan(150);
// 4. Unordered and ordered lists paint distinct gutter markers.
const ulImg = await captureRaw((await nodeWithId("block-ul")).tag);
const ulGutterX = Math.round(ulImg.width * 0.28);
const ulGutterInk = countMatchingPixels(
ulImg,
(r, g, b, x) => x < ulGutterX && r < 140 && g < 140 && b < 140,
);
expect(ulGutterInk).toBeGreaterThan(12);
const ol1 = await captureRaw((await nodeWithId("block-ol-1")).tag);
const ol8 = await captureRaw((await nodeWithId("block-ol-8")).tag);
expect(diffPixelCount(ol1, ol8, Math.round(ol1.width * 0.3))).toBeGreaterThan(10);
// 5. Task lists paint checked vs unchecked state and toggle via caller event.
const taskChecked = await captureRaw((await nodeWithId("block-task-checked")).tag);
const taskUnchecked = await captureRaw((await nodeWithId("block-task-unchecked")).tag);
const taskGutterX = Math.round(taskChecked.width * 0.22);
const accentBlue = (r: number, g: number, b: number, x: number) =>
x < taskGutterX && b - r > 50 && r < 80;
expect(countMatchingPixels(taskChecked, accentBlue)).toBeGreaterThan(40);
expect(countMatchingPixels(taskUnchecked, accentBlue)).toBe(0);
const taskToggleNode = await nodeWithId("block-task-toggle-md");
expect(await request("click", { tag: taskToggleNode.tag })).toEqual({ clicked: true });
await expect.poll(async () => (await nodeWithId("task-event")).text).toBe("0:true:Ok");
// 6. Blockquote paints left accent bar and tinted background.
const bqImg = await captureRaw((await nodeWithId("block-blockquote")).tag);
const bqBarX = Math.max(24, Math.round(bqImg.width * 0.08));
const bqBar = countMatchingPixels(bqImg, (r, g, b, x) => x < bqBarX && b - r > 80 && r < 80);
const bqFill = countMatchingPixels(
bqImg,
(r, g, b) => Math.abs(r - 0xef) < 12 && Math.abs(g - 0xf6) < 12 && b > 240,
);
expect(bqBar).toBeGreaterThan(40);
expect(bqFill).toBeGreaterThan(400);
// 7. Code block paints dark card, TypeScript header band, syntax-highlighted tokens, and fires onCodeBlockPress.
const cbImg = await captureRaw((await nodeWithId("block-code")).tag);
const cbSplitY = Math.round(cbImg.height * 0.42);
const cbDarkBg = countMatchingPixels(cbImg, (r, g, b) => r < 30 && g < 40 && b < 70);
const cbHeaderInk = countMatchingPixels(
cbImg,
(r, g, b, _x, y) => y < cbSplitY && (r > 90 || g > 90 || b > 100),
);
const cbSyntaxColors = countMatchingPixels(
cbImg,
(r, g, b, _x, y) =>
y >= cbSplitY &&
((r > 150 && b > 200 && g < 180) || // purple keyword (#c084fc)
(b > 200 && g > 150 && r < 120) || // cyan type (#38bdf8)
(r > 200 && g > 150 && b < 110)), // amber number (#fbbf24)
);
expect(cbDarkBg).toBeGreaterThan(2000);
expect(cbHeaderInk).toBeGreaterThan(25);
expect(cbSyntaxColors).toBeGreaterThan(30);
const codeNode = await nodeWithId("block-code-md");
expect(await request("click", { tag: codeNode.tag })).toEqual({ clicked: true });
await expect.poll(async () => (await nodeWithId("code-event")).text).toBe("ts:21");
// 8. Table paints header tint and blue border.
const tableImg = await captureRaw((await nodeWithId("block-table")).tag);
const tableHeaderFill = countMatchingPixels(
tableImg,
(r, g, b) => Math.abs(r - 0xdb) < 16 && Math.abs(g - 0xea) < 16 && b > 240,
);
const tableBorderBlue = countMatchingPixels(tableImg, (r, g, b) => b - r > 80 && r < 80);
expect(tableHeaderFill).toBeGreaterThan(400);
expect(tableBorderBlue).toBeGreaterThan(100);
// 9. Capture and structurally assert regression.png for the full composite document.
const initialComposite = await captureRaw(view.tag);
const directory = path.resolve(import.meta.dirname, "../../../.artifacts/gpui/markdown");
mkdirSync(directory, { recursive: true });
writeFileSync(path.join(directory, "regression.png"), initialComposite.bytes);
expect(
countMatchingPixels(initialComposite, (r, g, b) => r < 60 && g < 60 && b < 60),
).toBeGreaterThan(1500);
expect(
countMatchingPixels(initialComposite, (r, g, b) => b - r > 60 && r < 100),
).toBeGreaterThan(300);
expect(
countMatchingPixels(
initialComposite,
(r, g, b) =>
(r > 150 && b > 200 && g < 180) ||
(g > 180 && r < 160 && b < 190) ||
(r > 200 && g > 150 && b < 110),
),
).toBeGreaterThan(80);
// Dark code card + blue header table bands must both exist in the composite screenshot.
expect(
countMatchingPixels(initialComposite, (r, g, b) => r < 25 && g < 35 && b < 60),
).toBeGreaterThan(2000);
expect(
countMatchingPixels(
initialComposite,
(r, g, b) => Math.abs(r - 0xdb) < 16 && Math.abs(g - 0xea) < 16 && b > 240,
),
).toBeGreaterThan(300);
// 10. Clicking a rendered link dispatches onLinkPress with the URL.
const linkTarget = await nodeWithId("markdown-link-target");
expect(linkTarget.frame?.[2] ?? 0).toBeGreaterThan(40);
expect(linkTarget.frame?.[3] ?? 0).toBeGreaterThan(10);
expect(await request("click", { tag: linkTarget.tag })).toEqual({ clicked: true });
await expect
.poll(async () => (await nodeWithId("pressed-link")).text)
.toBe("https://example.com/docs");
// 11. Streaming append increases layout height and paints new ink pixels in the composite screenshot.
const streamBtn = await nodeWithId("markdown-stream-next");
expect(await request("click", { tag: streamBtn.tag })).toEqual({ clicked: true });
await expect
.poll(
async () =>
(JSON.parse((await nodeWithId("markdown-layout")).text) as { height?: number }).height ??
0,
)
.toBeGreaterThan(initialLayout.height ?? 0);
await expect
.poll(async () => {
const streamedComposite = await captureRaw(view.tag);
if (streamedComposite.height <= initialComposite.height) return 0;
return countMatchingPixels(
streamedComposite,
(r, g, b, _x, y) => y >= initialComposite.height && r < 140 && g < 140 && b < 140,
);
})
.toBeGreaterThan(80);
if (driverLogPath) {
const invalidLines = readFileSync(driverLogPath, "utf8")
.split("\n")
.filter((line) => line.includes("returned an invalid measurement"));
expect(invalidLines).toEqual([]);
}
},
30_000,
);
-251
View File
@@ -1,251 +0,0 @@
import { realpathSync, statSync } from "node:fs";
import { createRequire } from "node:module";
import path from "node:path";
import { afterEach, describe, expect, test } from "vitest";
const require = createRequire(import.meta.url);
const GPUI_DIR = import.meta.dirname;
const APP_DIR = path.resolve(GPUI_DIR, "..");
interface MetroConfig {
resolver: {
sourceExts: string[];
resolveRequest: (
context: Record<string, unknown>,
moduleName: string,
platform: string | null,
) => { type: string; filePath?: string };
};
}
function createResolutionContext(
originModulePath: string,
sourceExts: string[],
preferNativePlatform: boolean,
resolverModule: { resolve: (...args: unknown[]) => unknown },
) {
const fileSystemLookup = (candidatePath: string) => {
try {
const stats = statSync(candidatePath);
if (stats.isFile() || stats.isDirectory()) {
return {
exists: true,
type: stats.isFile() ? "f" : "d",
realPath: realpathSync(candidatePath),
};
}
} catch {
// Missing candidate path.
}
return { exists: false };
};
return {
allowHaste: false,
assetExts: new Set(["png", "jpg", "jpeg", "gif", "webp", "svg"]),
customResolverOptions: {},
dev: false,
disableHierarchicalLookup: false,
doesFileExist: (filePath: string) => fileSystemLookup(filePath).exists,
extraNodeModules: {},
fileSystemLookup,
getPackage: () => null,
getPackageForModule: () => null,
mainFields: ["react-native", "browser", "main"],
nodeModulesPaths: [path.join(GPUI_DIR, "node_modules"), path.join(APP_DIR, "node_modules")],
originModulePath,
preferNativePlatform,
redirectModulePath: (modulePath: string) => modulePath,
resolveAsset: () => null,
resolveHasteModule: () => null,
resolveHastePackage: () => null,
resolveRequest: resolverModule.resolve,
sourceExts,
unstable_conditionNames: ["require", "react-native"],
unstable_conditionsByPlatform: {},
unstable_enablePackageExports: false,
unstable_incrementalResolution: false,
unstable_logWarning: () => {},
};
}
function loadAppMetroConfig(webPlatform?: string) {
const previous = process.env.PASEO_WEB_PLATFORM;
if (webPlatform === undefined) delete process.env.PASEO_WEB_PLATFORM;
else process.env.PASEO_WEB_PLATFORM = webPlatform;
const configPath = path.join(APP_DIR, "metro.config.cjs");
delete require.cache[configPath];
try {
return {
config: require(configPath) as MetroConfig,
resolver: require(
require.resolve("metro-resolver", { paths: [APP_DIR, path.resolve(APP_DIR, "../..")] }),
) as { resolve: (...args: unknown[]) => unknown },
};
} finally {
if (previous === undefined) delete process.env.PASEO_WEB_PLATFORM;
else process.env.PASEO_WEB_PLATFORM = previous;
}
}
const CASES = [
{
label: "audio engine",
origin: path.join(APP_DIR, "src/audio/index.ts"),
specifier: "./audio-engine",
gpui: path.join(APP_DIR, "src/audio/audio-engine.gpui.ts"),
native: path.join(APP_DIR, "src/audio/audio-engine.native.ts"),
web: path.join(APP_DIR, "src/audio/audio-engine.web.ts"),
},
{
label: "mermaid fence host",
origin: path.join(APP_DIR, "src/components/markdown/fence/mermaid/index.tsx"),
specifier: "./host",
gpui: path.join(APP_DIR, "src/components/markdown/fence/mermaid/host.gpui.tsx"),
native: path.join(APP_DIR, "src/components/markdown/fence/mermaid/host.native.tsx"),
web: path.join(APP_DIR, "src/components/markdown/fence/mermaid/host.web.tsx"),
},
{
label: "html preview",
origin: path.join(APP_DIR, "src/file-panels/builtin.tsx"),
specifier: "./html-preview",
gpui: path.join(APP_DIR, "src/file-panels/html-preview.gpui.tsx"),
native: path.join(APP_DIR, "src/file-panels/html-preview.tsx"),
web: path.join(APP_DIR, "src/file-panels/html-preview.web.tsx"),
},
{
label: "document frame",
origin: path.join(APP_DIR, "src/plugins/react-native/ui.ts"),
specifier: "@/file-panels/document-frame",
gpui: path.join(APP_DIR, "src/file-panels/document-frame/index.gpui.tsx"),
native: path.join(APP_DIR, "src/file-panels/document-frame/index.tsx"),
web: path.join(APP_DIR, "src/file-panels/document-frame/index.web.tsx"),
},
{
label: "press feedback",
origin: path.join(APP_DIR, "modules/paseo-press-feedback/src/ui/index.tsx"),
specifier: "./feedback",
gpui: path.join(APP_DIR, "modules/paseo-press-feedback/src/ui/feedback.gpui.tsx"),
native: path.join(APP_DIR, "modules/paseo-press-feedback/src/ui/feedback.native.tsx"),
web: path.join(APP_DIR, "modules/paseo-press-feedback/src/ui/feedback.tsx"),
},
{
label: "pointer capabilities",
origin: path.join(APP_DIR, "src/components/ui/control-sizing.ts"),
specifier: "@/hooks/pointer-capabilities",
gpui: path.join(APP_DIR, "src/hooks/pointer-capabilities.gpui.ts"),
native: path.join(APP_DIR, "src/hooks/pointer-capabilities.ts"),
web: path.join(APP_DIR, "src/hooks/pointer-capabilities.ts"),
},
{
label: "keyboard presence",
origin: path.join(APP_DIR, "src/keyboard/availability.ts"),
specifier: "./internal/presence",
gpui: path.join(APP_DIR, "src/keyboard/internal/presence.gpui.ts"),
native: path.join(APP_DIR, "src/keyboard/internal/presence.ts"),
web: path.join(APP_DIR, "src/keyboard/internal/presence.web.ts"),
},
{
label: "keyboard conventions",
origin: path.join(APP_DIR, "src/keyboard/index.ts"),
specifier: "./internal/conventions",
gpui: path.join(APP_DIR, "src/keyboard/internal/conventions.gpui.ts"),
native: path.join(APP_DIR, "src/keyboard/internal/conventions.ts"),
web: path.join(APP_DIR, "src/keyboard/internal/conventions.web.ts"),
},
{
label: "resource budget",
origin: path.join(APP_DIR, "src/hooks/use-settings/storage.ts"),
specifier: "@/constants/resource-budget",
gpui: path.join(APP_DIR, "src/constants/resource-budget.gpui.ts"),
native: path.join(APP_DIR, "src/constants/resource-budget.ts"),
web: path.join(APP_DIR, "src/constants/resource-budget.ts"),
},
{
label: "presentation",
origin: path.join(APP_DIR, "src/command-center/command-center.tsx"),
specifier: "@/constants/presentation",
gpui: path.join(APP_DIR, "src/constants/presentation.gpui.ts"),
native: path.join(APP_DIR, "src/constants/presentation.ts"),
web: path.join(APP_DIR, "src/constants/presentation.ts"),
},
{
label: "touch timing",
origin: path.join(APP_DIR, "src/composer/input/input.tsx"),
specifier: "@/constants/touch-timing",
gpui: path.join(APP_DIR, "src/constants/touch-timing.gpui.ts"),
native: path.join(APP_DIR, "src/constants/touch-timing.ts"),
web: path.join(APP_DIR, "src/constants/touch-timing.ts"),
},
{
label: "press highlight",
origin: path.join(APP_DIR, "src/components/sidebar-workspace-list.tsx"),
specifier: "@/components/ui/press-highlight",
gpui: path.join(APP_DIR, "src/components/ui/press-highlight.gpui.tsx"),
native: path.join(APP_DIR, "src/components/ui/press-highlight.native.tsx"),
web: path.join(APP_DIR, "src/components/ui/press-highlight.tsx"),
},
];
afterEach(() => {
delete require.cache[path.join(APP_DIR, "metro.config.cjs")];
});
describe("GPUI Metro platform rule", () => {
test("GPUI resolves .gpui.* files ahead of .desktop, .native, and base files", () => {
const config = require(path.join(GPUI_DIR, "desktop/metro.config.js")) as MetroConfig;
const resolver = require(require.resolve("metro-resolver", { paths: [GPUI_DIR] })) as {
resolve: (...args: unknown[]) => unknown;
};
for (const item of CASES) {
const ctx = createResolutionContext(item.origin, config.resolver.sourceExts, true, resolver);
expect(
config.resolver.resolveRequest(ctx, item.specifier, "desktop").filePath,
item.label,
).toBe(item.gpui);
}
// GPUI must not pick Electron's .electron.* files as "desktop".
const browserCtx = createResolutionContext(
path.join(APP_DIR, "src/components/split-container.tsx"),
config.resolver.sourceExts,
true,
resolver,
);
expect(
config.resolver.resolveRequest(browserCtx, "@/desktop/browser/pane", "desktop").filePath,
).toBe(path.join(APP_DIR, "src/desktop/browser/pane/index.tsx"));
});
test("iOS, Android, web, and Electron never resolve .gpui.* files", () => {
const relativeCases = CASES.filter((item) => !item.specifier.startsWith("@/"));
const standard = loadAppMetroConfig();
const electron = loadAppMetroConfig("electron");
const targets = [
{ ...standard, platform: "ios", preferNative: true, expected: "native" as const },
{ ...standard, platform: "android", preferNative: true, expected: "native" as const },
{ ...standard, platform: "web", preferNative: false, expected: "web" as const },
{ ...electron, platform: "web", preferNative: false, expected: "web" as const },
];
for (const target of targets) {
for (const item of relativeCases) {
const ctx = createResolutionContext(
item.origin,
target.config.resolver.sourceExts,
target.preferNative,
target.resolver,
);
const filePath = target.config.resolver.resolveRequest(
ctx,
item.specifier,
target.platform,
).filePath;
expect(filePath, `${target.platform}: ${item.label}`).toBe(item[target.expected]);
expect(filePath).not.toContain(".gpui.");
}
}
});
});
-434
View File
@@ -1,434 +0,0 @@
import { afterAll, beforeAll, expect, test } from "vitest";
import sharp from "sharp";
import { mkdirSync, writeFileSync } from "node:fs";
import path from "node:path";
// Runs against the actual Paseo bundle in the compiled GPUI app. Start with
// RN_GPUI_TEST_DRIVER=1 and pass its loopback URL and token to this test.
const endpoint = process.env.PASEO_GPUI_TEST_URL;
const token = process.env.PASEO_GPUI_TEST_TOKEN;
const appearanceFixture = process.env.PASEO_GPUI_TEST_SCENE === "appearance";
let socket: WebSocket;
let nextId = 0;
interface Node {
tag: number;
component: string;
testID: string;
text: string;
frame?: [number, number, number, number];
children?: Node[];
}
const pending = new Map<number, { resolve(value: unknown): void; reject(error: Error): void }>();
function request<T = unknown>(method: string, params: Record<string, unknown> = {}): Promise<T> {
const id = ++nextId;
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
pending.delete(id);
reject(new Error(`GPUI ${method} timed out`));
}, 15_000);
pending.set(id, {
resolve: (value) => {
clearTimeout(timer);
resolve(value as T);
},
reject: (error) => {
clearTimeout(timer);
reject(error);
},
});
socket.send(JSON.stringify({ jsonrpc: "2.0", id, method, params: { ...params, token } }));
});
}
function flatten(node: Node): Node[] {
return [node, ...(node.children ?? []).flatMap(flatten)];
}
async function nodes() {
return (await request<{ children: Node[] }>("tree")).children.flatMap(flatten);
}
beforeAll(async () => {
if (!endpoint) return;
if (!token) throw new Error("PASEO_GPUI_TEST_TOKEN is required");
socket = new WebSocket(endpoint);
await new Promise<void>((resolve, reject) => {
socket.addEventListener("open", () => resolve(), { once: true });
socket.addEventListener("error", () => reject(new Error("GPUI driver connection failed")), {
once: true,
});
});
socket.addEventListener("message", (event) => {
const response = JSON.parse(String(event.data));
const waiter = pending.get(response.id);
if (!waiter) return;
pending.delete(response.id);
const error = response.error ?? response.result?.error;
if (error) waiter.reject(new Error(JSON.stringify(error)));
else waiter.resolve(response.result);
});
});
afterAll(() => socket?.close());
test.skipIf(!endpoint || appearanceFixture)(
"real Paseo portal passes workspace clicks and the native composer edits text",
async () => {
const workspace = (await nodes()).find((node) =>
node.testID.startsWith("sidebar-workspace-row-"),
);
expect(workspace, "connected daemon must have an existing workspace").toBeDefined();
// Regression: the upstream box-none portal hit area intercepted this click.
expect(await request("click", { tag: workspace!.tag })).toEqual({ clicked: true });
await expect
.poll(async () => (await nodes()).some((node) => node.testID === "workspace-header-title"), {
timeout: 15_000,
})
.toBe(true);
await expect
.poll(async () => (await nodes()).some((node) => node.component === "TextInput"), {
timeout: 15_000,
})
.toBe(true);
// Wait for async draft hydration (which resets an empty native TextInput once after mount).
let settledTag: number | undefined;
await expect
.poll(
async () => {
const current = (await nodes()).find((node) => node.component === "TextInput")?.tag;
const stable = current !== undefined && current === settledTag;
settledTag = current;
return stable;
},
{ timeout: 15_000, interval: 500 },
)
.toBe(true);
const input = (await nodes()).find((node) => node.component === "TextInput")!;
const original = (await request<{ text: string }>("getProps", { tag: input.tag })).text;
try {
await request("click", { tag: input.tag });
await request("press", { key: "secondary-a" });
await request("press", { key: "backspace" });
expect(
await request("type", { tag: input.tag, text: "GPUI native input regression" }),
).toEqual({ typed: true });
await expect
.poll(async () => (await request<{ text: string }>("getProps", { tag: input.tag })).text)
.toBe("GPUI native input regression");
} finally {
await request("press", { key: "secondary-a" });
await request("press", { key: "backspace" });
if (original) await request("type", { tag: input.tag, text: original });
await expect
.poll(async () => (await request<{ text: string }>("getProps", { tag: input.tag })).text)
.toBe(original);
}
},
45_000,
);
test.skipIf(!endpoint || appearanceFixture)(
"real Paseo sizes controls for a pointer, not for touch",
async () => {
// Regression: GPUI took the native touch answer, so a 28 pt pointer control rendered at 44.
const settings = await nodeWithId("sidebar-settings");
const displays = await request<Array<{ primary: boolean; scaleFactor: number }>>("displays");
const scale =
displays.find((display) => display.primary)?.scaleFactor ?? displays[0]?.scaleFactor ?? 1;
expect(settings.frame?.[3]).toBeDefined();
expect(Math.abs(settings.frame![3] - 28)).toBeLessThanOrEqual(1 / scale);
},
20_000,
);
test.skipIf(!endpoint || appearanceFixture)(
"real Paseo opens History",
async () => {
// Regression: the agent list's RefreshControl was undefined on GPUI, so History rendered
// "Element type is invalid" instead of the list. The daemon needs at least one agent.
const history = await nodeWithId("sidebar-sessions");
expect(await request("click", { tag: history.tag })).toEqual({ clicked: true });
// The list mounts after the agents load, so wait for a row, not for the search input.
await expect
.poll(
async () => {
const current = await nodes();
if (current.some((node) => node.testID === "root-error-boundary")) return "error screen";
return current.some((node) => node.testID.startsWith("agent-row-")) ? "list" : "loading";
},
{ timeout: 15_000 },
)
.toBe("list");
},
30_000,
);
async function openWorkspaceAndWaitForComposer(workspaceRow: Node): Promise<Node> {
expect(await request("click", { tag: workspaceRow.tag })).toEqual({ clicked: true });
await expect
.poll(async () => (await nodes()).some((node) => node.testID === "workspace-header-title"), {
timeout: 15_000,
})
.toBe(true);
await expect
.poll(async () => (await nodes()).some((node) => node.component === "TextInput"), {
timeout: 15_000,
})
.toBe(true);
let settledTag: number | undefined;
await expect
.poll(
async () => {
const current = (await nodes()).find((node) => node.component === "TextInput")?.tag;
const stable = current !== undefined && current === settledTag;
settledTag = current;
return stable;
},
{ timeout: 15_000, interval: 500 },
)
.toBe(true);
return (await nodes()).find((node) => node.component === "TextInput")!;
}
test.skipIf(!endpoint || appearanceFixture)(
"real Paseo submits the composer on Enter and inserts a newline on Shift+Enter",
async () => {
await expect
.poll(
async () => (await nodes()).some((n) => n.testID.startsWith("sidebar-workspace-row-")),
{
timeout: 15_000,
},
)
.toBe(true);
const workspace = (await nodes()).find((n) => n.testID.startsWith("sidebar-workspace-row-"))!;
const input = await openWorkspaceAndWaitForComposer(workspace);
await request("click", { tag: input.tag });
await request("press", { key: "secondary-a" });
await request("press", { key: "backspace" });
const marker = `GPUI Enter ${Date.now()}`;
await request("type", { tag: input.tag, text: marker });
await request("press", { key: "shift-enter" });
await request("type", { tag: input.tag, text: "line2" });
await expect
.poll(async () => (await request<{ text: string }>("getProps", { tag: input.tag })).text)
.toBe(`${marker}\nline2`);
await request("press", { key: "enter" });
await expect
.poll(
async () => {
const current = (await nodes()).find((node) => node.component === "TextInput");
if (!current) return null;
return (await request<{ text: string }>("getProps", { tag: current.tag })).text;
},
{ timeout: 15_000 },
)
.toBe("");
await expect
.poll(async () => (await nodes()).some((node) => node.text.includes(marker)), {
timeout: 15_000,
})
.toBe(true);
},
45_000,
);
test.skipIf(!endpoint || appearanceFixture)(
"real Paseo keeps the first workspace mounted when switching between two workspaces",
async () => {
await expect
.poll(
async () =>
(await nodes()).filter((n) => n.testID.startsWith("sidebar-workspace-row-")).length >= 2,
{ timeout: 15_000 },
)
.toBe(true);
const rows = (await nodes()).filter((n) => n.testID.startsWith("sidebar-workspace-row-"));
const firstInput = await openWorkspaceAndWaitForComposer(rows[0]!);
const firstTitle = (await nodes()).find((n) => n.testID === "workspace-header-title")?.text;
await request("click", { tag: firstInput.tag });
await request("press", { key: "secondary-a" });
await request("press", { key: "backspace" });
await request("type", { tag: firstInput.tag, text: "Kept across workspace switch" });
await expect
.poll(async () => (await request<{ text: string }>("getProps", { tag: firstInput.tag })).text)
.toBe("Kept across workspace switch");
try {
expect(await request("click", { tag: rows[1]!.tag })).toEqual({ clicked: true });
await expect
.poll(
async () => {
const title = (await nodes()).find((n) => n.testID === "workspace-header-title")?.text;
return title !== undefined && title !== firstTitle;
},
{ timeout: 15_000 },
)
.toBe(true);
expect(await request("click", { tag: rows[0]!.tag })).toEqual({ clicked: true });
await expect
.poll(
async () => (await nodes()).find((n) => n.testID === "workspace-header-title")?.text,
{ timeout: 15_000 },
)
.toBe(firstTitle);
// The exact Fabric node tag and draft text must survive because desktop retention keeps
// inactive workspaces mounted instead of unmounting on switch.
expect((await request<{ text: string }>("getProps", { tag: firstInput.tag })).text).toBe(
"Kept across workspace switch",
);
} finally {
await request("click", { tag: firstInput.tag });
await request("press", { key: "secondary-a" });
await request("press", { key: "backspace" });
}
},
45_000,
);
async function nodeWithId(testID: string) {
await expect.poll(async () => (await nodes()).some((node) => node.testID === testID)).toBe(true);
return (await nodes()).find((node) => node.testID === testID)!;
}
async function expectBackground(node: Node, color: number) {
await expect
.poll(
async () =>
(await request<{ backgroundColor: number }>("getProps", { tag: node.tag })).backgroundColor,
)
.toBe(color);
}
test.skipIf(!endpoint || !appearanceFixture)(
"Pressable render props receive hover state",
async () => {
const button = await nodeWithId("hover-render-prop");
const outside = await nodeWithId("outside-hover");
await request("hover", { tag: button.tag });
await expectBackground(button, 0xff00ff00);
await expect
.poll(async () => (await nodes()).some((node) => node.text === "render hovered"))
.toBe(true);
await request("hover", { tag: outside.tag });
await expectBackground(button, 0xff0000ff);
await expect
.poll(async () => (await nodes()).some((node) => node.text === "render idle"))
.toBe(true);
},
);
test.skipIf(!endpoint || !appearanceFixture)(
"rounded borders follow the background curve",
async () => {
const node = await nodeWithId("rounded-border");
const { png } = await request<{ png: string }>("screenshot", { tag: node.tag });
const bytes = Buffer.from(png, "base64");
const directory = path.resolve(import.meta.dirname, "../../../.artifacts/gpui/appearance");
mkdirSync(directory, { recursive: true });
writeFileSync(path.join(directory, "rounded-border.png"), bytes);
const { data, info } = await sharp(bytes)
.removeAlpha()
.raw()
.toBuffer({ resolveWithObject: true });
const pixel = (x: number, y: number) => {
const offset =
(Math.floor((y * info.height) / 100) * info.width + Math.floor((x * info.width) / 200)) *
info.channels;
return [...data.subarray(offset, offset + 3)];
};
// Outside the arc must be clear; the diagonal must have an actual curved
// border, not four straight rules clipped to a rounded rectangle.
expect(pixel(1, 1)).toEqual([255, 255, 255]);
expect(pixel(8, 8)).toEqual([255, 0, 0]);
expect(pixel(15, 15)).toEqual([0, 0, 255]);
expect(pixel(100, 1)).toEqual([255, 0, 0]);
expect(pixel(198, 98)).toEqual([255, 255, 255]);
},
);
test.skipIf(!endpoint || !appearanceFixture)(
"Pressable hover highlights enter and leave",
async () => {
const button = await nodeWithId("hover-button");
const outside = await nodeWithId("outside-hover");
await request("hover", { tag: button.tag });
await expectBackground(button, 0xff00ff00);
await request("hover", { tag: outside.tag });
await expectBackground(button, 0xff0000ff);
},
);
test.skipIf(!endpoint || !appearanceFixture)(
"row hover survives entering a nested Pressable",
async () => {
const row = await nodeWithId("hover-row");
const child = await nodeWithId("nested-button");
const outside = await nodeWithId("outside-hover");
await request("hover", { tag: row.tag });
await request("hover", { tag: child.tag });
await expectBackground(row, 0xff00ff00);
await request("hover", { tag: outside.tag });
await expectBackground(row, 0xff0000ff);
},
);
test.skipIf(!endpoint || !appearanceFixture)(
"onLayout fires with React Native layout shape for View, Text, TextInput, Image, and ScrollView",
async () => {
interface LayoutEntry {
count: number;
keys: string[];
layout: { x: number; y: number; width: number; height: number };
}
const readLayouts = async () => {
const node = await nodeWithId("layout-results");
return JSON.parse(node.text) as Record<string, LayoutEntry>;
};
const targets = [
["view", "layout-view"],
["text", "layout-text"],
["textInput", "layout-text-input"],
["image", "layout-image"],
["scrollView", "layout-scroll"],
] as const;
await expect
.poll(async () => Object.keys(await readLayouts()).sort())
.toEqual(targets.map(([key]) => key).sort());
const initial = await readLayouts();
const treeNodes = await nodes();
for (const [key, testID] of targets) {
const entry = initial[key];
expect(entry.count, `${key} initial onLayout count`).toBe(1);
expect(entry.keys, `${key} layout keys`).toEqual(["height", "width", "x", "y"]);
expect(entry.layout.width, `${key} width`).toBeGreaterThan(0);
expect(entry.layout.height, `${key} height`).toBeGreaterThan(0);
const treeNode = treeNodes.find((n) => n.testID === testID);
expect(treeNode?.frame, `${testID} frame`).toBeDefined();
expect(entry.layout.x).toBeCloseTo(treeNode!.frame![0], 2);
expect(entry.layout.y).toBeCloseTo(treeNode!.frame![1], 2);
expect(entry.layout.width).toBeCloseTo(treeNode!.frame![2], 2);
expect(entry.layout.height).toBeCloseTo(treeNode!.frame![3], 2);
}
const toggle = await nodeWithId("layout-resize-toggle");
expect(await request("click", { tag: toggle.tag })).toEqual({ clicked: true });
await expect
.poll(async () => {
const parsed = await readLayouts();
return targets.every(([key]) => (parsed[key]?.count ?? 0) >= 2);
})
.toBe(true);
const resized = await readLayouts();
for (const [key] of targets) {
expect(resized[key].count, `${key} resized onLayout count`).toBe(2);
expect(resized[key].layout.width, `${key} resized width`).toBeGreaterThan(
initial[key].layout.width,
);
}
},
);
-6737
View File
File diff suppressed because it is too large Load Diff
-40
View File
@@ -1,40 +0,0 @@
{
"name": "paseo-gpui",
"version": "0.0.0",
"private": true,
"dependencies": {
"@formatjs/intl-datetimeformat": "^7.9.0",
"@formatjs/intl-displaynames": "^7.4.0",
"@formatjs/intl-getcanonicallocales": "^3.3.0",
"@formatjs/intl-locale": "^5.4.1",
"@formatjs/intl-numberformat": "^9.5.0",
"@formatjs/intl-pluralrules": "^6.4.0",
"@formatjs/intl-segmenter": "^12.3.0",
"@react-native-gpui/codegen": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-4/react-native-gpui-codegen-0.87.0-alpha.2.tgz",
"@react-native-gpui/core": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-4/react-native-gpui-core-0.87.0-alpha.5.tgz",
"@react-native-gpui/fs": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-4/react-native-gpui-fs-0.0.1-alpha.1.tgz",
"@react-native-gpui/gesture-handler": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-4/react-native-gpui-gesture-handler-3.3.0-alpha.1.tgz",
"@react-native-gpui/hermes": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-4/react-native-gpui-hermes-0.87.0-alpha.1.tgz",
"@react-native-gpui/reanimated": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-4/react-native-gpui-reanimated-4.7.0-alpha.1.tgz",
"@react-native-gpui/safe-area-context": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-4/react-native-gpui-safe-area-context-5.10.0-alpha.0.tgz",
"@react-native-gpui/screens": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-4/react-native-gpui-screens-4.28.0-alpha.2.tgz",
"@react-native-gpui/svg": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-4/react-native-gpui-svg-15.15.0-alpha.1.tgz",
"@react-native-gpui/worklets": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-4/react-native-gpui-worklets-0.13.0-alpha.1.tgz",
"@react-native/assets-registry": "^0.87.1",
"react": "19.2.3",
"react-native": "0.87.1",
"react-native-gesture-handler": "3.3.0",
"react-native-reanimated": "https://github.com/ammarahm-ed/react-native-reanimated/releases/download/4.7.1-desktop.1/react-native-reanimated-4.7.1.tgz",
"react-native-safe-area-context": "5.10.1",
"react-native-screens": "4.28.0",
"react-native-svg": "15.15.5",
"react-native-worklets": "https://github.com/ammarahm-ed/react-native-reanimated/releases/download/worklets-0.13.0-desktop.1/react-native-worklets-0.13.0.tgz"
},
"devDependencies": {
"@react-native-community/cli": "20.2.0",
"@react-native-gpui/cli": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-4/react-native-gpui-cli-0.87.0-alpha.5.tgz",
"@react-native/babel-preset": "0.87.1",
"@react-native/metro-config": "0.87.1",
"typescript": "^5.8.3"
}
}
-2
View File
@@ -1,2 +0,0 @@
/// <reference types="@react-native-gpui/core/types" />
// Added by react-native-gpui. Do not edit: it is regenerated.
-22
View File
@@ -1,22 +0,0 @@
const path = require("node:path");
module.exports = {
// This target only launches desktop. RN CLI 20.2's built-in
// run-ios/run-android option lists conflict with the CLI's global verbose
// option, and this app has no native mobile projects to launch.
commands: ["build-android", "build-ios", "log-android", "log-ios", "run-android", "run-ios"].map(
(name) => ({
name,
description: `${name} is not configured for Paseo GPUI`,
func: () => {
throw new Error(`${name} is not configured for Paseo GPUI`);
},
}),
),
project: { desktop: {} },
dependencies: {
"react-native-enriched-markdown": {
root: path.resolve(__dirname, "../../react-native-enriched-markdown"),
},
},
reactNativePath: path.dirname(require.resolve("react-native/package.json")),
};
-7
View File
@@ -1,7 +0,0 @@
// Use the existing route tree. Expo's transformer normally supplies this root
// through a Babel caller field; the RN desktop transformer does not.
export const ctx = require.context(
"../src/app",
true,
/^(?:\.\/)(?!(?:(?:(?:.*\+api)|(?:\+(html|native-intent))))\.[tj]sx?$).*\.[tj]sx?$/,
);
-3
View File
@@ -1,3 +0,0 @@
[toolchain]
channel = "stable"
profile = "minimal"
@@ -1,47 +0,0 @@
import { readdirSync, readFileSync } from "node:fs";
import { createRequire } from "node:module";
import path from "node:path";
import { parse } from "@babel/parser";
import { expect, test } from "vitest";
const require = createRequire(import.meta.url);
const GPUI_DIR = import.meta.dirname;
// The Unistyles Babel plugin rewrites `import { X } from "react-native"` to
// `react-native-unistyles/components/native/X`, and the GPUI Metro config sends
// every such path to this one adapter. A component Unistyles wraps but the
// adapter does not export arrives as `undefined` and React throws
// "Element type is invalid" when it renders.
const ADAPTER = path.join(GPUI_DIR, "adapters/unistyles-components.js");
// NativeText and NativeView are reached only through
// `react-native/Libraries/...` imports, which the app does not use.
const NOT_REDIRECTED_FROM_REACT_NATIVE = new Set(["NativeText", "NativeView"]);
function unistylesWrappedComponents(): string[] {
const unistylesRoot = path.dirname(require.resolve("react-native-unistyles/package.json"));
return readdirSync(path.join(unistylesRoot, "components/native"), { withFileTypes: true })
.filter((entry) => entry.isDirectory() && !NOT_REDIRECTED_FROM_REACT_NATIVE.has(entry.name))
.map((entry) => entry.name)
.sort();
}
function adapterExports(): Set<string> {
const ast = parse(readFileSync(ADAPTER, "utf8"), { sourceType: "module" });
const names = new Set<string>();
for (const node of ast.program.body) {
if (node.type !== "ExportNamedDeclaration" || node.declaration?.type !== "VariableDeclaration")
continue;
for (const declarator of node.declaration.declarations) {
if (declarator.id.type === "Identifier") names.add(declarator.id.name);
}
}
return names;
}
test("the GPUI Unistyles adapter exports every component the Unistyles plugin redirects", () => {
const wrapped = unistylesWrappedComponents();
expect(wrapped).toContain("RefreshControl");
const exported = adapterExports();
expect(wrapped.filter((name) => !exported.has(name))).toEqual([]);
});
@@ -1,61 +0,0 @@
import assert from "node:assert/strict";
import { execFileSync, spawnSync } from "node:child_process";
import { readdirSync } from "node:fs";
import path from "node:path";
assert.equal(process.platform, "darwin", "Run package verification on macOS");
assert.ok(process.argv[2], "Pass the packaged .app path");
const app = path.resolve(process.argv[2]);
const contents = path.join(app, "Contents");
const info = JSON.parse(
execFileSync("plutil", ["-convert", "json", "-o", "-", path.join(contents, "Info.plist")]),
);
const executable = path.join(contents, "MacOS", info.CFBundleExecutable);
const frameworks = path.join(contents, "Frameworks");
const libraries = readdirSync(frameworks, { recursive: true })
.filter((name) => name.endsWith(".dylib"))
.map((name) => path.join(frameworks, name));
execFileSync("codesign", ["--verify", "--deep", "--strict", app], { stdio: "inherit" });
const signature = spawnSync("codesign", ["-dvvv", executable], { encoding: "utf8" });
assert.equal(signature.status, 0, signature.stderr);
if (
signature.stderr.includes("Signature=adhoc") &&
/flags=[^\n]*\bruntime\b/.test(signature.stderr) &&
libraries.length > 0
) {
const entitlements = execFileSync("codesign", ["-d", "--entitlements", "-", "--xml", executable]);
assert.ok(entitlements.length > 0, "Ad-hoc app has no library-validation entitlement");
const values = JSON.parse(
execFileSync("plutil", ["-convert", "json", "-o", "-", "--", "-"], {
input: entitlements,
}),
);
assert.equal(
values["com.apple.security.cs.disable-library-validation"],
true,
"Ad-hoc app cannot satisfy Team ID library validation on a Mac with SIP enabled",
);
}
function version(value) {
const parts = value.split(".").map(Number);
return (parts[0] * 256 + (parts[1] ?? 0)) * 256 + (parts[2] ?? 0);
}
assert.ok(info.LSMinimumSystemVersion, "The app must declare its minimum macOS version");
for (const binary of [executable, ...libraries]) {
const build = execFileSync("xcrun", ["vtool", "-show-build", binary], { encoding: "utf8" });
const minima = [...build.matchAll(/\bminos\s+(\d+(?:\.\d+)*)/g)].map((match) => match[1]);
assert.ok(minima.length > 0, `No macOS deployment target found in ${binary}`);
for (const minimum of minima) {
assert.ok(
version(minimum) <= version(info.LSMinimumSystemVersion),
`${path.basename(binary)} requires macOS ${minimum}, above the app's ${info.LSMinimumSystemVersion}`,
);
}
}
console.log(
`PASS: bundle signatures, ad-hoc library loading policy, and macOS deployment targets: ${app}`,
);
@@ -1,45 +0,0 @@
import { AppRegistry } from "react-native";
AppRegistry.registerComponent("Paseo", () => () => null);
// The native test supplies a loopback server before loading this bundle.
const base = globalThis.__webSocketRegressionUrl;
async function connect(path, expectedCode, localClose = false) {
return new Promise((resolve, reject) => {
const socket = new WebSocket(`${base}/${path}`);
const timeout = setTimeout(() => reject(new Error(`${path}: timed out`)), 5000);
let echoed = false;
socket.addEventListener("open", () => socket.send("native websocket regression"));
socket.addEventListener("message", (event) => {
echoed = event.data === "native websocket regression";
if (localClose) socket.close(1000, "client done");
});
socket.addEventListener("close", (event) => {
clearTimeout(timeout);
if (event.code !== expectedCode || (expectedCode === 1000 && !echoed)) {
reject(new Error(`${path}: code=${event.code}, echoed=${echoed}`));
} else {
resolve();
}
});
});
}
async function run() {
// Keep retrying through the real RN WebSocket API. Before the fix, native
// clients survived terminal events and exhausted the Mac's descriptor limit.
for (const [path, code, localClose] of [
["reject", 1006, false],
["remote-close", 1000, false],
["local-close", 1000, true],
]) {
for (let attempt = 0; attempt < 128; attempt++) {
await connect(path, code, localClose);
}
console.log(`WEBSOCKET_REGRESSION_PASS ${path}`);
}
console.log("WEBSOCKET_REGRESSION_COMPLETE");
}
setTimeout(() => {
run().catch((error) => console.error(`WEBSOCKET_REGRESSION_FAIL ${error.message}`));
}, 0);
-117
View File
@@ -1,117 +0,0 @@
import { spawn, execFileSync } from "node:child_process";
import { createServer } from "node:http";
import { mkdtempSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { Server as WebSocketServer } from "ws";
import { expect, test } from "vitest";
const binary = process.env.PASEO_GPUI_TEST_BINARY;
const project = path.dirname(fileURLToPath(import.meta.url));
const root = path.resolve(project, "../../..");
function createPeer() {
const server = createServer();
const sockets = new WebSocketServer({ noServer: true });
server.on("upgrade", (request, socket, head) => {
if (request.url === "/reject") {
socket.end("HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
return;
}
sockets.handleUpgrade(request, socket, head, (websocket) => {
websocket.on("message", (message) => {
websocket.send(message.toString());
if (request.url === "/remote-close") websocket.close(1000, "server done");
});
});
});
return { server, sockets };
}
test.skipIf(!binary)(
"native WebSocket retries and peer closes release their resources",
async () => {
mkdirSync(path.join(root, ".artifacts/gpui"), { recursive: true });
const artifacts = mkdtempSync(path.join(root, ".artifacts/gpui/websocket-"));
const bundle = path.join(artifacts, "regression.bundle");
execFileSync(
process.execPath,
[
"node_modules/react-native/cli.js",
"bundle",
"--platform",
"desktop",
"--entry-file",
"websocket-regression.fixture.js",
"--config",
"desktop/metro.config.js",
"--bundle-output",
bundle,
"--dev",
"false",
"--max-workers",
"1",
],
{ cwd: project, env: { ...process.env, PASEO_RENDERER: "gpui" }, timeout: 120_000 },
);
const { server, sockets } = createPeer();
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const address = server.address();
if (!address || typeof address === "string") throw new Error("Missing server address");
writeFileSync(
bundle,
`globalThis.__webSocketRegressionUrl = "ws://127.0.0.1:${address.port}";\n${readFileSync(bundle, "utf8")}`,
);
// Match Finder's descriptor limit even when the test shell has raised it.
const app = spawn("/bin/sh", ["-c", 'ulimit -n 256; exec "$@"', "gpui-test", binary!], {
env: {
...process.env,
RN_GPUI_BUNDLE: bundle,
RN_GPUI_APP_ID: "sh.paseo.gpui.websocket-test",
XDG_DATA_HOME: path.join(artifacts, "data"),
},
stdio: ["ignore", "pipe", "pipe"],
});
let output = "";
try {
await new Promise<void>((resolve, reject) => {
const timeout = setTimeout(
() => reject(new Error(`Native retry test timed out:\n${output}`)),
60_000,
);
const collect = (chunk: Buffer) => {
output += chunk.toString();
if (output.includes("WEBSOCKET_REGRESSION_COMPLETE")) {
clearTimeout(timeout);
resolve();
} else if (output.includes("WEBSOCKET_REGRESSION_FAIL")) {
clearTimeout(timeout);
reject(new Error(output));
}
};
app.stdout.on("data", collect);
app.stderr.on("data", collect);
app.once("error", (error) => {
clearTimeout(timeout);
reject(error);
});
app.once("exit", (code, signal) => {
clearTimeout(timeout);
reject(new Error(`Native process exited (${code}, ${signal}):\n${output}`));
});
});
expect(app.exitCode).toBeNull();
expect(output).toContain("WEBSOCKET_REGRESSION_PASS reject");
expect(output).toContain("WEBSOCKET_REGRESSION_PASS remote-close");
expect(output).toContain("WEBSOCKET_REGRESSION_PASS local-close");
} finally {
writeFileSync(path.join(artifacts, "native.log"), output);
app.kill("SIGTERM");
for (const client of sockets.clients) client.terminate();
sockets.close();
server.close();
}
},
180_000,
);
@@ -1,9 +0,0 @@
import type { Ref } from "react";
export interface RowFeedbackHandle {
acknowledge(): Promise<void>;
}
export function RowFeedback(_props: { ref?: Ref<RowFeedbackHandle>; selected: boolean }) {
return null;
}
@@ -783,6 +783,56 @@ it("presents received agent messages as attributed bubbles with the original tur
});
});
it("presents a finished notification as a compact tool call, not a received message", () => {
const call = toolCall("notice", "agent_finished");
if (call.payload.source !== "agent") throw new Error("Expected agent tool");
call.payload.data.detail = {
type: "plain_text",
label: "Child",
text: "Agent child (Child) finished.",
icon: "bot",
};
const result = createStreamPresentation()({
...presentationOptions,
transform: undefined,
tail: [call],
head: [],
});
expect(result.tail).toEqual([call]);
});
// COMPAT(agentNotificationMetadata): rows from daemons that sent notification metadata.
it("presents a legacy notification as the plain tool call current daemons send", () => {
const call = toolCall("legacy", "agent_message");
if (call.payload.source !== "agent") throw new Error("Expected agent tool");
call.turnId = "turn";
call.payload.data.detail = { type: "plain_text", text: "Done", icon: "bot" };
call.payload.data.agentMessage = {
event: "finished",
sender: { id: "child", title: "Child" },
text: "Done",
};
const result = createStreamPresentation()({
...presentationOptions,
transform: undefined,
tail: [call],
head: [],
});
expect(result.tail).toHaveLength(1);
const [presented] = result.tail;
if (presented?.kind !== "tool_call" || presented.payload.source !== "agent")
throw new Error("Expected agent tool");
expect(presented).toMatchObject({ id: call.id, turnId: "turn" });
expect(presented.payload.data).toEqual({
provider: "codex",
callId: "legacy",
name: "agent_finished",
status: "completed",
error: null,
detail: { type: "plain_text", label: "Child", text: "Done", icon: "bot" },
});
});
it("does not reopen the previous turn while a new run waits for its first row", () => {
const timestamp = new Date();
const tail: StreamItem[] = [
+24 -2
View File
@@ -9,7 +9,14 @@ import {
type ToolCallDetailLevel,
type ToolCallDetailProjection,
} from "@/tool-calls/detail-level/projection";
import type { StreamItem, UserMessageItem } from "@/types/stream";
import type { AgentMessage } from "@getpaseo/protocol/agent-message";
import { legacyAgentNotificationToolCall } from "@getpaseo/protocol/paseo-tool-presentation/index";
import {
isAgentToolCallItem,
type AgentToolCallItem,
type StreamItem,
type UserMessageItem,
} from "@/types/stream";
import { collapseTurns, type TurnCollapse } from "./turn-collapse/model";
import type { ReadingRowReplacements } from "./reading-anchor";
@@ -56,6 +63,7 @@ const NO_COLLAPSED_TURNS: StreamPresentation["turns"] = collapseTurns({
/** Source messages reach plugins before display projection. */
export function createStreamPresentation() {
const userMessageCache = new WeakMap<UserMessageItem, UserMessageItem>();
const legacyNotificationCache = new WeakMap<AgentToolCallItem, AgentToolCallItem>();
function presentUserMessage(item: UserMessageItem): UserMessageItem {
const cached = userMessageCache.get(item);
@@ -72,6 +80,19 @@ export function createStreamPresentation() {
return projected;
}
// COMPAT(agentNotificationMetadata): added in v0.18.1, remove after 2027-06-01.
function presentLegacyNotification(item: AgentToolCallItem, message: AgentMessage): StreamItem {
const cached = legacyNotificationCache.get(item);
if (cached) return cached;
const { agentMessage: _legacy, ...data } = item.payload.data;
const presented: AgentToolCallItem = {
...item,
payload: { source: "agent", data: { ...data, ...legacyAgentNotificationToolCall(message) } },
};
legacyNotificationCache.set(item, presented);
return presented;
}
let historySource: StreamItem[] | undefined;
let historyTransform: TimelineItemTransform | undefined;
let historyRows: StreamItem[] = [];
@@ -86,7 +107,7 @@ export function createStreamPresentation() {
let collapsed: TurnCollapse | undefined;
function presentRows(item: StreamItem): StreamItem[] {
if (item.kind === "tool_call" && item.payload.source === "agent") {
if (isAgentToolCallItem(item)) {
const message = item.payload.data.agentMessage;
if (message?.event === "message") {
return [
@@ -101,6 +122,7 @@ export function createStreamPresentation() {
},
];
}
if (message) return [presentLegacyNotification(item, message)];
}
return [item.kind === "user_message" ? presentUserMessage(item) : item];
}
@@ -22,10 +22,35 @@ function row(index: number, height = ROW_HEIGHT): Extract<StreamItem, { kind: "u
};
}
function assistantRow(
index: number,
height = ROW_HEIGHT,
): Extract<StreamItem, { kind: "assistant_message" }> {
return {
kind: "assistant_message",
id: `assistant-${index}`,
text: String(height),
timestamp: new Date(`2026-04-20T00:00:${String(index % 60).padStart(2, "0")}.000Z`),
};
}
function thoughtRow(index: number, height = ROW_HEIGHT): Extract<StreamItem, { kind: "thought" }> {
return {
kind: "thought",
id: `thought-${index}`,
text: String(height),
status: "ready",
timestamp: new Date(`2026-04-20T00:00:${String(index % 60).padStart(2, "0")}.000Z`),
};
}
const rowStyleByHeight = new Map<number, { height: number }>();
function renderRow(item: StreamItem) {
const height = item.kind === "user_message" ? Number(item.text) : ROW_HEIGHT;
const height =
item.kind === "user_message" || item.kind === "assistant_message" || item.kind === "thought"
? Number(item.text)
: ROW_HEIGHT;
let style = rowStyleByHeight.get(height);
if (!style) {
style = { height };
@@ -57,18 +82,30 @@ type OlderHistoryInput = Pick<
interface MountTimelineOptions {
olderHistory?: OlderHistoryInput;
isMobileBreakpoint?: boolean;
historyVirtualized?: StreamItem[];
viewportHeight?: number;
}
function mountTimeline(
historyMounted: StreamItem[],
{ olderHistory, isMobileBreakpoint = true }: MountTimelineOptions = {},
{
olderHistory,
isMobileBreakpoint = true,
historyVirtualized = [],
viewportHeight = VIEWPORT_HEIGHT,
}: MountTimelineOptions = {},
) {
host.style.height = `${viewportHeight}px`;
const strategy = createWebStreamStrategy({ isMobileBreakpoint });
const viewportRef = React.createRef<StreamViewportHandle>();
const input: StreamRenderInput = {
let currentInput: StreamRenderInput = {
agentId: "agent",
segments: { historyVirtualized: [], historyMounted, liveHead: [] },
boundary: { hasVirtualizedHistory: false, hasMountedHistory: true, hasLiveHead: false },
segments: { historyVirtualized, historyMounted, liveHead: [] },
boundary: {
hasVirtualizedHistory: historyVirtualized.length > 0,
hasMountedHistory: historyMounted.length > 0,
hasLiveHead: false,
},
renderers: {
renderHistoryVirtualizedRow: renderRow,
renderHistoryMountedRow: renderRow,
@@ -91,8 +128,23 @@ function mountTimeline(
contentMaxWidth: DEFAULT_CONTENT_MAX_WIDTH,
...olderHistory,
};
const render = (segments: Partial<StreamRenderInput["segments"]>) =>
root.render(strategy.render({ ...input, segments: { ...input.segments, ...segments } }));
const render = (
segments: Partial<StreamRenderInput["segments"]>,
overrides: Partial<Omit<StreamRenderInput, "segments">> = {},
) => {
const nextSegments = { ...currentInput.segments, ...segments };
currentInput = {
...currentInput,
...overrides,
segments: nextSegments,
boundary: {
hasVirtualizedHistory: nextSegments.historyVirtualized.length > 0,
hasMountedHistory: nextSegments.historyMounted.length > 0,
hasLiveHead: nextSegments.liveHead.length > 0,
},
};
root.render(strategy.render(currentInput));
};
act(() => render({}));
const scrollContainer = host.querySelector<HTMLElement>('[data-testid="agent-chat-scroll"]');
@@ -104,7 +156,10 @@ function mountTimeline(
};
return {
render: (segments: Partial<StreamRenderInput["segments"]>) => act(() => render(segments)),
render: (
segments: Partial<StreamRenderInput["segments"]>,
overrides?: Partial<Omit<StreamRenderInput, "segments">>,
) => act(() => render(segments, overrides)),
hold: (rowId: string, apply: () => void, triggerEdge: DisclosureTriggerEdge = "top") =>
act(() => viewportRef.current!.holdRow(rowId, apply, triggerEdge)),
rowTop: (id: string) =>
@@ -129,9 +184,9 @@ function mountTimeline(
scrollContainer.dispatchEvent(new Event("scroll"));
}),
// Resize observers and the hold's settle run on animation frames.
settle: () =>
settle: (frames = 4) =>
act(async () => {
for (let frame = 0; frame < 4; frame += 1) {
for (let frame = 0; frame < frames; frame += 1) {
await new Promise((resolve) => requestAnimationFrame(resolve));
}
}),
@@ -310,3 +365,148 @@ describe("web history start", () => {
expect(olderHistoryLoads).toBe(1);
});
});
describe("web virtualizer reconcile stability", () => {
it("settles without nested update loops when virtualized rows grow far past estimates above a mounted anchor", async () => {
const mounted = Array.from({ length: 10 }, (_, index) => row(500 + index));
const timeline = mountTimeline(mounted, { viewportHeight: 200 });
await timeline.settle();
timeline.scrollUp(200);
await timeline.settle();
const readingTop = timeline.rowTop("message-500");
const virtualized = Array.from({ length: 500 }, (_, index) => thoughtRow(index, 800));
timeline.render({ historyVirtualized: virtualized, historyMounted: mounted });
await timeline.settle();
expect(timeline.rowTop("message-500")).toBe(readingTop);
expect(timeline.rowBottom("thought-499")).toBe(readingTop);
});
it("does not overflow React update depth via reconcileReadingPosition when growing virtualized rows reach the start on desktop", async () => {
const mounted = Array.from({ length: 10 }, (_, index) => row(400 + index));
const timeline = mountTimeline(mounted, {
viewportHeight: 200,
isMobileBreakpoint: false,
});
await timeline.settle();
timeline.scrollUp(200);
await timeline.settle();
const readingTop = timeline.rowTop("message-400");
const virtualized = Array.from({ length: 170 }, (_, index) => thoughtRow(index, 800));
timeline.render({ historyVirtualized: virtualized, historyMounted: mounted });
await timeline.settle();
expect(timeline.rowTop("message-400")).toBe(readingTop);
expect(timeline.rowBottom("thought-169")).toBe(readingTop);
});
it("does not runaway-loop when unmeasured virtualized rows shrink near the bottom of a long chat", async () => {
const virtualized = Array.from({ length: 2000 }, (_, index) => assistantRow(index, 20));
const mounted = Array.from({ length: 10 }, (_, index) => row(2000 + index, 40));
const timeline = mountTimeline(mounted, {
historyVirtualized: virtualized,
viewportHeight: 600,
});
await timeline.settle(10);
timeline.scrollUp(120);
await timeline.settle(10);
const readingTop = timeline.rowTop("message-2000");
timeline.render({}, { contentMaxWidth: 360 });
await timeline.settle(10);
expect(timeline.rowTop("message-2000")).toBe(readingTop);
expect(timeline.rowBottom("assistant-1999")).toBe(readingTop);
expect(timeline.rowTop("assistant-1990")).toBe(readingTop - 200);
});
it("keeps a mounted anchor near the bottom when prepended virtualized rows shrink below estimate", async () => {
const mounted = Array.from({ length: 10 }, (_, index) => row(40 + index, 40));
const timeline = mountTimeline(mounted, { viewportHeight: 200 });
await timeline.settle();
timeline.scrollUp(60);
await timeline.settle();
const readingTop = timeline.rowTop("message-44");
const virtualized = Array.from({ length: 40 }, (_, index) => assistantRow(index, 40));
timeline.render({ historyVirtualized: virtualized, historyMounted: mounted });
await timeline.settle();
expect(timeline.rowTop("message-44")).toBe(readingTop);
expect(timeline.rowBottom("assistant-39")).toBe(timeline.rowTop("message-40"));
});
it("settles across frames without hitting React update depth limits for hundreds of tiny virtualized rows", async () => {
const mounted = Array.from({ length: 4 }, (_, index) => row(800 + index, 40));
const virtualized = Array.from({ length: 800 }, (_, index) => assistantRow(index, 2));
const timeline = mountTimeline(mounted, {
historyVirtualized: virtualized,
viewportHeight: 1200,
});
await timeline.settle(16);
expect(timeline.distanceFromEnd()).toBeLessThanOrEqual(1);
const readingTop = timeline.rowTop("message-800");
timeline.hold("message-800", () => timeline.render({}, { contentMaxWidth: 360 }));
await timeline.settle(16);
expect(timeline.rowTop("message-800")).toBe(readingTop);
expect(timeline.rowBottom("assistant-799")).toBe(readingTop);
expect(timeline.rowTop("assistant-700")).toBe(readingTop - 200);
});
it("resumes following when a layout commit precedes the scroll event at the bottom", async () => {
const mounted = Array.from({ length: 10 }, (_, index) => row(index, 40));
const timeline = mountTimeline(mounted, { viewportHeight: 200 });
await timeline.settle();
timeline.scrollUp(120);
await timeline.settle();
timeline.scrollTo(1000);
timeline.render({ historyMounted: [...mounted] });
await timeline.settle();
timeline.render({ liveHead: [row(10, 40)] });
await timeline.settle();
expect(timeline.distanceFromEnd()).toBe(0);
});
it("mounts the top of a newly virtualized block when all history fits in the viewport", async () => {
const timeline = mountTimeline([row(99, 40)], {
viewportHeight: 1200,
isMobileBreakpoint: false,
});
await timeline.settle();
timeline.render({
historyVirtualized: Array.from({ length: 24 }, (_, index) => thoughtRow(index, 40)),
});
await timeline.settle();
expect(timeline.scrollTop()).toBe(0);
expect(timeline.rowTop("thought-0")).toBe(48);
expect(timeline.rowTop("message-99")).toBe(48 + 24 * 40);
});
it("mounts the top of a newly virtualized block when a mounted row shrinks in the same commit", async () => {
const timeline = mountTimeline([row(99, 1100)], {
viewportHeight: 1200,
isMobileBreakpoint: false,
});
await timeline.settle();
expect(timeline.scrollTop()).toBe(0);
timeline.render({
historyVirtualized: Array.from({ length: 24 }, (_, index) => thoughtRow(index, 40)),
historyMounted: [row(99, 40)],
});
await timeline.settle();
expect(timeline.scrollTop()).toBe(0);
expect(timeline.rowTop("message-99")).toBe(1008);
expect(timeline.rowTop("thought-0")).toBe(48);
});
});
+344 -34
View File
@@ -57,8 +57,10 @@ const AUTO_SCROLL_RESUME_THRESHOLD_PX = 1;
const HISTORY_START_SETTLE_FRAMES = 2;
const HISTORY_START_SLOT_HEIGHT_PX = 32;
const CONTENT_PADDING_TOP_PX = 16;
const CONTENT_PADDING_BOTTOM_PX = 16;
const UPWARD_INPUT_EVIDENCE_TIMEOUT_MS = 100;
const VIRTUALIZER_SCROLL_MARGIN_PX = HISTORY_START_SLOT_HEIGHT_PX + CONTENT_PADDING_TOP_PX;
const MAX_SYNC_LAYOUT_PASSES = 16;
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
const foregroundMutedColorMapping = (theme: Theme) => ({
@@ -118,6 +120,127 @@ function isScrollContainerMeasurable(
return scrollContainer.clientHeight > 0 && scrollContainer.scrollHeight > 0;
}
function getUnclampedScrollTop(
scrollContainer: Pick<HTMLElement, "scrollTop" | "clientHeight" | "scrollHeight">,
lastKnownScrollTop: number,
): number {
if (!isScrollContainerMeasurable(scrollContainer)) {
return scrollContainer.scrollTop;
}
const maxScrollTop = Math.max(0, scrollContainer.scrollHeight - scrollContainer.clientHeight);
const isBrowserClamped =
maxScrollTop < lastKnownScrollTop - 0.5 &&
Math.abs(scrollContainer.scrollTop - maxScrollTop) <= 1;
return isBrowserClamped ? lastKnownScrollTop : scrollContainer.scrollTop;
}
interface MountedRowOffset {
topWithoutVirtual: number;
height: number;
mountedIndex: number;
}
interface MountedRowSnapshot {
firstRowId: string | null;
offsets: Map<string, MountedRowOffset>;
}
function findNonVirtualizedRowIndex(
segments: Pick<StreamRenderInput["segments"], "historyMounted" | "liveHead">,
rowId: string,
): number {
const mountedIndex = segments.historyMounted.findIndex((row) => row.id === rowId);
if (mountedIndex >= 0) {
return mountedIndex;
}
const liveHeadIndex = segments.liveHead.findIndex((row) => row.id === rowId);
return liveHeadIndex >= 0 ? segments.historyMounted.length + liveHeadIndex : -1;
}
interface CommittedLayoutMetrics {
hasCommittedFlowHeight: boolean;
virtualSpacerHeight: number;
nonVirtualFlowHeight: number;
nonVirtualRowCount: number;
}
interface ProjectRangeOffsetInput {
container: HTMLElement;
virtualizer: Virtualizer<HTMLElement, Element>;
followOutput: boolean;
isJumpSettling: boolean;
lastClampedBaselineScrollTop: number;
committedLayoutMetrics: CommittedLayoutMetrics;
anchorId: string | null;
anchorIndex: number;
segments: Pick<StreamRenderInput["segments"], "historyMounted" | "liveHead">;
mountedSnapshot: MountedRowSnapshot;
readingAnchor: ReturnType<typeof createReadingAnchor>;
readingRowReplacements: StreamRenderInput["readingRowReplacements"];
}
function projectRangeOffset(input: ProjectRangeOffsetInput): number {
const { container, virtualizer } = input;
if (input.isJumpSettling) {
return container.scrollTop;
}
const baseScrollTop = getUnclampedScrollTop(container, input.lastClampedBaselineScrollTop);
if (input.followOutput && isScrollContainerMeasurable(container)) {
const { committedLayoutMetrics } = input;
const currentNonVirtualRowCount =
input.segments.historyMounted.length + input.segments.liveHead.length;
if (
!committedLayoutMetrics.hasCommittedFlowHeight ||
currentNonVirtualRowCount < committedLayoutMetrics.nonVirtualRowCount
) {
return baseScrollTop;
}
const projectedFlowHeight =
committedLayoutMetrics.nonVirtualFlowHeight + virtualizer.getTotalSize();
return Math.max(0, projectedFlowHeight - container.clientHeight);
}
if (input.anchorIndex >= 0) {
const measurement = virtualizer.measurementsCache[input.anchorIndex];
if (!measurement) {
return baseScrollTop;
}
return input.readingAnchor.project(
baseScrollTop,
{
id: String(measurement.key),
top: measurement.start,
height: measurement.size,
},
input.readingRowReplacements,
);
}
if (!input.anchorId) {
return baseScrollTop;
}
const mountedAnchor = input.mountedSnapshot.offsets.get(input.anchorId);
if (!mountedAnchor) {
return baseScrollTop;
}
const currentMountedIndex = findNonVirtualizedRowIndex(input.segments, input.anchorId);
const currentFirstMountedId =
input.segments.historyMounted[0]?.id ?? input.segments.liveHead[0]?.id ?? null;
if (
currentMountedIndex !== mountedAnchor.mountedIndex ||
currentFirstMountedId !== input.mountedSnapshot.firstRowId
) {
return baseScrollTop;
}
return input.readingAnchor.project(
baseScrollTop,
{
id: input.anchorId,
top: mountedAnchor.topWithoutVirtual + virtualizer.getTotalSize(),
height: mountedAnchor.height,
},
input.readingRowReplacements,
);
}
function isEditableEventTarget(target: EventTarget | null): boolean {
if (!(target instanceof Element)) {
return false;
@@ -330,6 +453,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
const isActive = useRetainedPanelActive();
const { t } = useTranslation();
const rowsHostRef = useRef<HTMLDivElement | null>(null);
const virtualSpacerRef = useRef<HTMLDivElement | null>(null);
const auxiliaryRef = useRef<HTMLDivElement | null>(null);
const isActiveRef = useRef(isActive);
const scrollContainerRef = useRef<HTMLElement | null>(null);
@@ -341,6 +465,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
contentRef.current = node;
}, []);
const [followOutput, setFollowOutputr] = useState(true);
const [rangeProjectionEpoch, setRangeProjectionEpoch] = useState(0);
const followOutputRef = useRef(followOutput);
const setFollowOutput = (value: boolean) => {
followOutputRef.current = value;
@@ -348,6 +473,10 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
return value;
};
const lastKnownScrollTopRef = useRef(0);
const lastClampedBaselineScrollTopRef = useRef(0);
const segmentsRef = useRef(segments);
segmentsRef.current = segments;
const isJumpSettlingRef = useRef<() => boolean>(() => false);
const mouseScrollGestureRef = useRef<
| { kind: "scrollbar"; pointerId: number }
| {
@@ -363,9 +492,23 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
const lastTouchClientYRef = useRef<number | null>(null);
const pendingAutoScrollFrameRef = useRef<number | null>(null);
const pendingAutoScrollTimeoutRef = useRef<number | null>(null);
const deferredLayoutFrameRef = useRef<number | null>(null);
const lastProjectedRangeOffsetRef = useRef<number | null>(null);
const syncLayoutPassesRef = useRef(0);
const syncLayoutResetScheduledRef = useRef(false);
const historyStartReadyRef = useRef(false);
const readingAnchor = useMemo(createReadingAnchor, []);
const measuredRowHeights = useRef(new Map<string, { width: number; height: number }>());
const mountedRowSnapshotRef = useRef<MountedRowSnapshot>({
firstRowId: null,
offsets: new Map(),
});
const committedLayoutMetricsRef = useRef<CommittedLayoutMetrics>({
hasCommittedFlowHeight: false,
virtualSpacerHeight: 0,
nonVirtualFlowHeight: 0,
nonVirtualRowCount: 0,
});
const historyStartSettleSchedulerRef = useRef<HistoryStartSettleScheduler | null>(null);
const lastActiveFollowOutputLayoutRef = useRef<ActiveFollowOutputLayout | null>(null);
const lastObservedViewportGeometryRef = useRef<ObservedViewportGeometry | null>(null);
@@ -404,38 +547,50 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
const rowVirtualizerRef = useRef<Virtualizer<HTMLElement, Element> | null>(null);
const rangeExtractor = useCallback(
(range: VirtualRange): number[] => {
const anchorIndex = segments.historyVirtualized.findIndex(
(row) => row.id === readingAnchor.getRowId(props.readingRowReplacements),
);
// Busts TanStack's getVirtualIndexes memo when a post-commit check detects a stale projection.
void rangeProjectionEpoch;
const anchorId = readingAnchor.getRowId(props.readingRowReplacements);
const anchorIndex = anchorId
? segments.historyVirtualized.findIndex((row) => row.id === anchorId)
: -1;
const container = scrollContainerRef.current;
// TanStack has computed the new measurements before calling the extractor.
// Select against the pending anchor correction, before mounting any rows at
// the stale pre-prepend offset. The DOM correction still belongs to commit.
const virtualizer = rowVirtualizerRef.current!;
const measurement = virtualizer.measurementsCache[anchorIndex];
const correctedOffset =
container && measurement
? readingAnchor.project(
container.scrollTop,
{
id: String(measurement.key),
top: measurement.start,
height: measurement.size,
},
props.readingRowReplacements,
)
: container?.scrollTop;
const virtualizerOffset = virtualizer.scrollOffset ?? 0;
const correctedOffset = container
? projectRangeOffset({
container,
virtualizer,
followOutput: followOutputRef.current,
isJumpSettling: isJumpSettlingRef.current(),
lastClampedBaselineScrollTop: lastClampedBaselineScrollTopRef.current,
committedLayoutMetrics: committedLayoutMetricsRef.current,
anchorId,
anchorIndex,
segments: segmentsRef.current,
mountedSnapshot: mountedRowSnapshotRef.current,
readingAnchor,
readingRowReplacements: props.readingRowReplacements,
})
: undefined;
let visibleRange = range;
let projectedRangeOffset: number | null = null;
if (
container &&
correctedOffset !== undefined &&
Math.abs(correctedOffset - container.scrollTop) > 0.5
Math.abs(correctedOffset - virtualizerOffset) > 0.5
) {
const first = virtualizer.getVirtualItemForOffset(correctedOffset);
const last = virtualizer.getVirtualItemForOffset(correctedOffset + container.clientHeight);
if (first && last)
const projectedOffset = Math.max(0, correctedOffset);
const first = virtualizer.getVirtualItemForOffset(projectedOffset);
const last = virtualizer.getVirtualItemForOffset(projectedOffset + container.clientHeight);
if (first && last) {
visibleRange = { ...range, startIndex: first.index, endIndex: last.index };
projectedRangeOffset = projectedOffset;
}
}
lastProjectedRangeOffsetRef.current = projectedRangeOffset;
return [
...new Set([
...defaultRangeExtractor(visibleRange),
@@ -444,7 +599,13 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
]),
].sort((left, right) => left - right);
},
[chatFindRowIndexes, readingAnchor, segments.historyVirtualized, props.readingRowReplacements],
[
chatFindRowIndexes,
rangeProjectionEpoch,
readingAnchor,
segments.historyVirtualized,
props.readingRowReplacements,
],
);
const virtualOffsetListener = useRef<((offset: number, scrolling: boolean) => void) | null>(null);
const observeVirtualOffset = useCallback<typeof observeElementOffset>((instance, onOffset) => {
@@ -563,8 +724,10 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
"[data-history-row-id][data-index]",
) ?? []) {
const index = Number(element.dataset.index);
const measurement = rowVirtualizer.measurementsCache[index];
if (!measurement) continue;
const height = measureVirtualElement(element, undefined, rowVirtualizer);
if (rowVirtualizer.measurementsCache[index]?.size === height) continue;
if (measurement.size === height) continue;
rowVirtualizer.resizeItem(index, height);
resized = true;
}
@@ -593,6 +756,22 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
);
useEffect(() => () => virtualRowObserver.disconnect(), [virtualRowObserver]);
const cancelDeferredLayoutPass = useCallback(() => {
const pendingFrame = deferredLayoutFrameRef.current;
if (pendingFrame !== null) {
deferredLayoutFrameRef.current = null;
window.cancelAnimationFrame(pendingFrame);
}
}, []);
useEffect(
() => () => {
cancelDeferredLayoutPass();
syncLayoutPassesRef.current = 0;
},
[cancelDeferredLayoutPass],
);
const cancelPendingStickToBottom = useCallback(() => {
const pendingFrame = pendingAutoScrollFrameRef.current;
if (pendingFrame !== null) {
@@ -638,11 +817,20 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
return;
}
cancelPendingStickToBottom();
cancelDeferredLayoutPass();
lastProjectedRangeOffsetRef.current = null;
syncLayoutPassesRef.current = 0;
historyStartSettleSchedulerRef.current?.cancel();
clearMouseScrollGesture();
clearUpwardInputEvidence();
lastTouchClientYRef.current = null;
}, [cancelPendingStickToBottom, clearMouseScrollGesture, clearUpwardInputEvidence, isActive]);
}, [
cancelDeferredLayoutPass,
cancelPendingStickToBottom,
clearMouseScrollGesture,
clearUpwardInputEvidence,
isActive,
]);
const scrollMessagesToBottom = useCallback(
(behavior: ScrollBehaviorLike = "auto") => {
@@ -659,6 +847,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
}
scrollElementToBottom(scrollContainer, behavior);
lastKnownScrollTopRef.current = scrollContainer.scrollTop;
lastClampedBaselineScrollTopRef.current = scrollContainer.scrollTop;
syncNearBottom(scrollContainer, onNearBottomChange);
evaluateHistoryStart();
},
@@ -731,6 +920,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
setFollowOutput,
onNearBottomChange,
});
isJumpSettlingRef.current = isJumpSettling;
// Row tops in content coordinates, which survive scrolling.
const measureRows = useStableEvent(() => {
@@ -740,14 +930,89 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
const viewportTop = container.getBoundingClientRect().top;
const scrollTop = container.scrollTop;
const width = readContentWidth() ?? 0;
return Array.from(content.querySelectorAll<HTMLElement>("[data-history-row-id]"), (element) => {
const bounds = element.getBoundingClientRect();
const id = element.dataset.historyRowId!;
measuredRowHeights.current.set(id, { width, height: bounds.height });
return { id, top: bounds.top - viewportTop + scrollTop, height: bounds.height };
const virtualSpacerHeight = virtualSpacerRef.current?.getBoundingClientRect().height ?? 0;
const rowsHostHeight = rowsHostRef.current?.getBoundingClientRect().height ?? 0;
const auxiliaryHeight = auxiliaryRef.current?.getBoundingClientRect().height ?? 0;
const shouldTrackMountedOffsets = !followOutputRef.current;
const mountedOffsets = mountedRowSnapshotRef.current.offsets;
mountedOffsets.clear();
let firstRowId: string | null = null;
let mountedIndex = 0;
const rows = Array.from(
content.querySelectorAll<HTMLElement>("[data-history-row-id]"),
(element) => {
const bounds = element.getBoundingClientRect();
const id = element.dataset.historyRowId!;
const top = bounds.top - viewportTop + scrollTop;
measuredRowHeights.current.set(id, { width, height: bounds.height });
if (!element.hasAttribute("data-index")) {
if (shouldTrackMountedOffsets) {
if (firstRowId === null) {
firstRowId = id;
}
mountedOffsets.set(id, {
topWithoutVirtual: top - virtualSpacerHeight,
height: bounds.height,
mountedIndex,
});
}
mountedIndex += 1;
}
return { id, top, height: bounds.height };
},
);
mountedRowSnapshotRef.current.firstRowId = firstRowId;
committedLayoutMetricsRef.current = {
hasCommittedFlowHeight: true,
virtualSpacerHeight,
nonVirtualFlowHeight:
VIRTUALIZER_SCROLL_MARGIN_PX +
Math.max(0, rowsHostHeight - virtualSpacerHeight) +
auxiliaryHeight +
CONTENT_PADDING_BOTTOM_PX,
nonVirtualRowCount: mountedIndex,
};
return rows;
});
const scheduleDeferredLayoutPass = useStableEvent(() => {
if (deferredLayoutFrameRef.current !== null || !isActiveRef.current) {
return;
}
deferredLayoutFrameRef.current = window.requestAnimationFrame(() => {
deferredLayoutFrameRef.current = null;
syncLayoutPassesRef.current = 0;
if (!isActiveRef.current) {
return;
}
if (measureVirtualizedRows()) {
return;
}
reconcileReadingPosition();
if (followOutputRef.current && scrollContainerRef.current) {
reconcileProjectedRange(scrollContainerRef.current);
}
});
});
const reconcileProjectedRange = useStableEvent((container: HTMLElement): boolean => {
const projectedOffset = lastProjectedRangeOffsetRef.current;
if (projectedOffset === null) {
return false;
}
if (Math.abs(container.scrollTop - projectedOffset) <= 0.5) {
lastProjectedRangeOffsetRef.current = null;
return false;
}
if (syncLayoutPassesRef.current >= MAX_SYNC_LAYOUT_PASSES) {
scheduleDeferredLayoutPass();
return true;
}
lastProjectedRangeOffsetRef.current = null;
setRangeProjectionEpoch((value) => value + 1);
return true;
});
const reconcileReadingPosition = useStableEvent(() => {
const container = scrollContainerRef.current;
if (!isActiveRef.current || !container) return;
@@ -755,8 +1020,11 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
if (!rows) return;
const shouldAnchor = !followOutputRef.current && !isJumpSettling();
if (!shouldAnchor) readingAnchor.reset();
const anchorScrollTop = shouldAnchor
? getUnclampedScrollTop(container, lastClampedBaselineScrollTopRef.current)
: container.scrollTop;
const correctedTop = readingAnchor.reconcile(
container.scrollTop,
anchorScrollTop,
rows,
false,
props.readingRowReplacements,
@@ -768,9 +1036,20 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
if (Math.abs(correctedTop - container.scrollTop) > 0.5) {
container.scrollTop = correctedTop;
lastKnownScrollTopRef.current = container.scrollTop;
}
lastClampedBaselineScrollTopRef.current = container.scrollTop;
const virtualizerOffset = rowVirtualizer.scrollOffset ?? 0;
if (virtualOffsetListener.current && Math.abs(container.scrollTop - virtualizerOffset) > 0.5) {
if (syncLayoutPassesRef.current >= MAX_SYNC_LAYOUT_PASSES) {
scheduleDeferredLayoutPass();
return;
}
// The DOM scroll event arrives later. Fill the corrected virtual range in
// this layout so the reader does not get a frame containing only the pin.
virtualOffsetListener.current?.(container.scrollTop, false);
virtualOffsetListener.current(container.scrollTop, false);
}
if (reconcileProjectedRange(container)) {
return;
}
// A disclosure that closes back to the end of the list rejoins the output.
if (disclosurePendingRef.current) {
@@ -782,17 +1061,38 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
// Apply row positions and their scroll correction in the same paint, including
// the ordinary-to-virtualized handoff and measurements of newly mounted rows.
useLayoutEffect(() => {
if (!isActive) {
cancelDeferredLayoutPass();
lastProjectedRangeOffsetRef.current = null;
syncLayoutPassesRef.current = 0;
return;
}
if (syncLayoutPassesRef.current >= MAX_SYNC_LAYOUT_PASSES) {
scheduleDeferredLayoutPass();
return;
}
syncLayoutPassesRef.current += 1;
if (!syncLayoutResetScheduledRef.current) {
syncLayoutResetScheduledRef.current = true;
queueMicrotask(() => {
syncLayoutResetScheduledRef.current = false;
syncLayoutPassesRef.current = 0;
});
}
// Commit positions for every resized row before accepting reading geometry.
// Child layout can change during this commit, ahead of ResizeObserver delivery.
if (!isActive || measureVirtualizedRows()) return;
if (measureVirtualizedRows()) return;
cancelDeferredLayoutPass();
reconcileReadingPosition();
}, [
cancelDeferredLayoutPass,
contentWidth,
isActive,
segments,
virtualRows,
measureVirtualizedRows,
reconcileReadingPosition,
scheduleDeferredLayoutPass,
]);
const stopFollowingOutputFromUserIntent = useStableEvent(() => {
@@ -832,6 +1132,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
}
lastKnownScrollTopRef.current = currentScrollTop;
lastClampedBaselineScrollTopRef.current = currentScrollTop;
if (!followOutputRef.current && !isJumpSettling() && (scrolledUp || scrolledDown)) {
readingAnchor.scroll(currentScrollTop);
}
@@ -925,11 +1226,15 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
if (!followOutputRef.current || resumedUnchangedLayout) return;
cancelPendingStickToBottom();
scrollMessagesToBottom("auto");
if (scrollContainerRef.current) {
reconcileProjectedRange(scrollContainerRef.current);
}
}, [
activationKey,
cancelPendingStickToBottom,
isActive,
isActivationReady,
reconcileProjectedRange,
renderLiveAuxiliary,
scrollMessagesToBottom,
segments.historyMounted,
@@ -997,7 +1302,9 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
} else {
lastObservedViewportGeometryRef.current = nextGeometry;
}
reconcileReadingPosition();
if (deferredLayoutFrameRef.current === null) {
reconcileReadingPosition();
}
if (isHistoryStartSettling()) {
scheduleHistoryStartPrependSettle();
}
@@ -1208,6 +1515,9 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
setFollowOutput(false);
const row = measureRows()?.find((candidate) => candidate.id === rowId);
const scrollTop = scrollContainerRef.current?.scrollTop;
if (scrollTop !== undefined) {
lastClampedBaselineScrollTopRef.current = scrollTop;
}
if (row && scrollTop !== undefined) readingAnchor.pin(row, triggerEdge, scrollTop);
disclosurePendingRef.current = true;
apply();
@@ -1243,7 +1553,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
flexDirection: "column",
minHeight: "100%",
paddingTop: CONTENT_PADDING_TOP_PX,
paddingBottom: 16,
paddingBottom: CONTENT_PADDING_BOTTOM_PX,
paddingLeft,
paddingRight,
boxSizing: "border-box",
@@ -1375,7 +1685,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
<div ref={handleContentRef} style={contentContainerStyle}>
{historyStartSlot}
<div ref={rowsHostRef} style={streamRowsHostStyle}>
<div style={virtualRowsContainerStyle} />
<div ref={virtualSpacerRef} style={virtualRowsContainerStyle} />
{[
...virtualRows.map((virtualRow) => {
const item = segments.historyVirtualized[virtualRow.index];
@@ -12,6 +12,7 @@ import {
TEXT_REVEAL_FRAME_INTERVAL_MS,
TEXT_REVEAL_HORIZON_MS,
visibleRevealedText,
withholdPartialClosingFence,
} from "./text-reveal";
describe("computeRevealStep", () => {
@@ -275,3 +276,127 @@ describe("trailing fragments from arrival boundaries", () => {
expect(visibleRevealedText(beginTextReveal(prose), { streaming: true })).toBe(prose);
});
});
describe("a closing fence still being typed", () => {
const code = "Intro\n\n```ts\nconst a = 1;\n";
it("holds back one or two backticks that can only become the closing fence", () => {
expect(withholdPartialClosingFence(`${code}\``)).toBe(code);
expect(withholdPartialClosingFence(`${code}\`\``)).toBe(code);
expect(withholdPartialClosingFence(`${code} \`\``)).toBe(code);
});
it.each([
{ char: "`", length: 3, whitespace: " " },
{ char: "`", length: 3, whitespace: "\t" },
{ char: "`", length: 4, whitespace: " " },
{ char: "`", length: 4, whitespace: "\t" },
{ char: "~", length: 3, whitespace: " " },
{ char: "~", length: 3, whitespace: "\t" },
{ char: "~", length: 5, whitespace: " " },
{ char: "~", length: 5, whitespace: "\t" },
])(
"paints real code after whitespace ends a $length $char run ($whitespace)",
({ char, length, whitespace }) => {
const prefix = `${char.repeat(length)}\ncode\n`;
const run = char.repeat(length - 1);
expect(withholdPartialClosingFence(prefix + run)).toBe(prefix);
const text = prefix + run + whitespace;
expect(withholdPartialClosingFence(text)).toBe(text);
expect(visibleRevealedText(beginTextReveal(text), { streaming: true })).toBe(text);
},
);
it("paints the fence once it closes the block", () => {
expect(withholdPartialClosingFence(`${code}\`\`\``)).toBe(`${code}\`\`\``);
expect(withholdPartialClosingFence(`${code}\`\`\`\n\nAfter`)).toBe(`${code}\`\`\`\n\nAfter`);
});
it("needs a run as long as the opener and of the same character", () => {
const long = "````md\nInside\n";
expect(withholdPartialClosingFence(`${long}\`\`\``)).toBe(long);
expect(withholdPartialClosingFence(`${long}\`\`\`\``)).toBe(`${long}\`\`\`\``);
const tilde = "~~~\ncode\n";
expect(withholdPartialClosingFence(`${tilde}~~`)).toBe(tilde);
expect(withholdPartialClosingFence(`${tilde}\``)).toBe(`${tilde}\``);
});
it.each([
{ lineEnding: "LF", newline: "\n", closer: "```" },
{ lineEnding: "CRLF", newline: "\r\n", closer: "```" },
{ lineEnding: "LF", newline: "\n", closer: "``` \t" },
{ lineEnding: "CRLF", newline: "\r\n", closer: "``` \t" },
])(
"recognizes completed closers before a tilde block with $lineEnding ($closer)",
({ newline, closer }) => {
const backtickBlock = ["Intro", "```ts", "const a = 1;", closer, ""].join(newline);
const tildeBlock = backtickBlock + ["~~~md", "code", ""].join(newline);
expect(withholdPartialClosingFence(tildeBlock + "~~")).toBe(tildeBlock);
expect(withholdPartialClosingFence(tildeBlock + "~~~")).toBe(tildeBlock + "~~~");
expect(withholdPartialClosingFence(tildeBlock + "~~ not a closer")).toBe(
tildeBlock + "~~ not a closer",
);
const closedTildeBlock = tildeBlock + "~~~" + newline;
expect(withholdPartialClosingFence(closedTildeBlock + "`")).toBe(closedTildeBlock + "`");
},
);
it.each([
{ marker: "-", fence: "```", newline: "\n" },
{ marker: "1.", fence: "~~~", newline: "\n" },
{ marker: "-", fence: "~~~", newline: "\r\n" },
{ marker: "1.", fence: "```", newline: "\r\n" },
])(
"keeps prose after a closed $marker list fence ($fence, $newline)",
({ marker, fence, newline }) => {
const indent = " ".repeat(marker.length + 1);
const closed = [`${marker} ${fence}`, `${indent}code`, `${indent}${fence}`, "", ""].join(
newline,
);
const prose = closed + fence[0];
expect(withholdPartialClosingFence(prose)).toBe(prose);
expect(visibleRevealedText(beginTextReveal(prose), { streaming: true })).toBe(prose);
const open = [`${marker} ${fence}`, `${indent}code`, ""].join(newline);
expect(withholdPartialClosingFence(open + indent + fence[0])).toBe(open);
},
);
it("does not take an indented code block's fence for a top-level opener", () => {
const text = " code\n ```\n\n`";
expect(withholdPartialClosingFence(text)).toBe(text);
});
it("leaves backticks alone outside a code block", () => {
expect(withholdPartialClosingFence("Prose\n`")).toBe("Prose\n`");
const closed = "```\na\n```\n";
expect(withholdPartialClosingFence(`${closed}\``)).toBe(`${closed}\``);
expect(withholdPartialClosingFence("`` inline ``\n`")).toBe("`` inline ``\n`");
});
it("leaves a code line that only starts with backticks alone", () => {
expect(withholdPartialClosingFence(`${code}\`x`)).toBe(`${code}\`x`);
});
it("never paints a lone backtick line while a paced reveal crosses the closing fence", () => {
const full = `${code}\`\`\`\n\nAfter the block.`;
let state = retargetTextReveal(beginTextReveal(code), full);
const painted: string[] = [];
for (let frame = 0; frame < 120 && !isTextRevealSettled(state); frame += 1) {
state = advanceTextReveal(state, 16, 1_000);
painted.push(visibleRevealedText(state, { streaming: true }));
}
expect(painted.at(-1)).toBe(full);
for (const text of painted) {
expect(full.startsWith(text)).toBe(true);
expect(text.endsWith("\n`") || text.endsWith("\n``")).toBe(false);
}
});
it("holds the fence back when an arrival ends inside it, and paints it once the turn ends", () => {
const state = beginTextReveal(`${code}\``);
expect(visibleRevealedText(state, { streaming: true })).toBe(code);
expect(visibleRevealedText(state, { streaming: false })).toBe(`${code}\``);
});
});
+44 -2
View File
@@ -1,3 +1,5 @@
import { createMarkdownParser } from "@/utils/markdown-parser";
/**
* Paced reveal for streaming assistant text.
*
@@ -207,6 +209,41 @@ function trimIncompleteTrailingCluster(text: string): string {
return text;
}
// Only parse block context when the current line can still become a closer.
const UNFINISHED_FENCE_RUN = /^ {0,3}(`+|~+)$/;
const fenceParser = createMarkdownParser({ linkify: false }).disable("inline");
/**
* Hold back the closing fence of a code block while it is still being typed.
*
* Inside an open fence, a last line holding one or two backticks is code until
* the third one arrives and closes the block. Painted, it adds a line of code
* that vanishes a frame later, so the block grows and shrinks and every row
* below it shifts twice. A paced reveal hands out these prefixes one character
* at a time, and an arrival boundary can end on one too. The line waits until it
* either closes the block or turns out to be code.
*/
export function withholdPartialClosingFence(text: string): string {
const lineStart = text.lastIndexOf("\n") + 1;
if (lineStart === 0) return text;
const run = UNFINISHED_FENCE_RUN.exec(text.slice(lineStart))?.[1];
if (!run) return text;
// Source maps include container boundaries: a list closer must not become a
// new top-level opener, and a fence-looking line in indented code is not one.
const lastLine = text.split("\n").length - 1;
const open = fenceParser
.parse(text, {})
.findLast(
(token) =>
token.type === "fence" &&
token.map !== null &&
token.map[0] < lastLine &&
token.map[1] === lastLine + 1,
);
if (!open || open.markup[0] !== run[0] || run.length >= open.markup.length) return text;
return text.slice(0, lineStart);
}
/** Number of regional indicators at the end of `text`. A flag is a pair. */
function countTrailingRegionalIndicators(text: string): number {
let count = 0;
@@ -234,7 +271,12 @@ export function visibleRevealedText(
options?: { streaming?: boolean },
): string {
if (state.revealed >= state.target.length) {
return options?.streaming ? trimIncompleteTrailingCluster(state.target) : state.target;
return options?.streaming
? withholdPartialClosingFence(trimIncompleteTrailingCluster(state.target))
: state.target;
}
return state.target.slice(0, clampToSafeRevealBoundary(state.target, state.revealed));
// More text is already here, so a partial fence at the cut is certainly unfinished.
return withholdPartialClosingFence(
state.target.slice(0, clampToSafeRevealBoundary(state.target, state.revealed)),
);
}
@@ -162,11 +162,12 @@ describe("collapseTurns", () => {
create.payload.data.detail = { type: "unknown", input: { title: "Side fix" }, output: null };
const finished = shell("finished");
if (finished.payload.source !== "agent") throw new Error("Expected agent tool");
finished.payload.data.name = "agent_notification";
finished.payload.data.agentMessage = {
event: "finished",
sender: { id: "worker", title: "PR helper" },
finished.payload.data.name = "agent_finished";
finished.payload.data.detail = {
type: "plain_text",
label: "PR helper",
text: "Finished",
icon: "bot",
};
const items: StreamItem[] = [
user("u1"),
@@ -77,11 +77,8 @@ describe("canonical turn membership", () => {
delete trigger.turnId;
expect(continuesTurn(previous, trigger)).toBe(false);
trigger.payload.data.name = "agent_message";
trigger.payload.data.agentMessage = {
event: "finished",
sender: { id: "worker" },
text: "Done",
};
expect(continuesTurn(previous, trigger)).toBe(false);
trigger.payload.data.name = "agent_finished";
expect(continuesTurn(previous, trigger)).toBe(false);
});
-1
View File
@@ -827,7 +827,6 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
cwd={context.cwd}
serverId={resolvedServerId}
metadata={data.metadata}
agentMessage={data.agentMessage}
isLastInSequence={isLastInSequence}
onOpenFilePath={handleToolCallOpenFile}
standalone={options.standalone}
@@ -20,11 +20,11 @@ import {
getWorkspaceSelectionKey,
orderWorkspaceSelectionsForStableRender,
reconcileRetainedWorkspaceSelections,
resolveWorkspaceDeckRetentionLimit,
type RetainedWorkspaceSelection,
resolveWorkspaceDeckEntries,
shouldKeepWorkspaceDeckEntryMounted,
} from "@/screens/workspace/workspace-deck-retention";
import { workspaceDeckRetentionLimit } from "@/constants/resource-budget";
import {
decodeWorkspaceIdFromPathSegment,
parseWorkspaceOpenIntent,
@@ -35,7 +35,7 @@ import {
stripHostWorkspaceRouteEchoSearchFromBrowserUrlAfterCommit,
} from "@/utils/host-route-browser";
import { prepareWorkspaceTab } from "@/utils/prepare-workspace-tab";
import { isWeb } from "@/constants/platform";
import { isNative, isWeb } from "@/constants/platform";
import { RenderProfile } from "@/utils/render-profiler";
function getParamValue(value: string | string[] | undefined): string {
@@ -164,7 +164,7 @@ function WorkspaceDeck() {
currentEntries: retainedSelections,
activeSelection,
now: reconciliationNow,
maxMountedWorkspaces: workspaceDeckRetentionLimit,
maxMountedWorkspaces: resolveWorkspaceDeckRetentionLimit({ isNative }),
}),
[activeSelection, reconciliationNow, retainedSelections],
);
@@ -201,7 +201,7 @@ function WorkspaceDeck() {
currentEntries: current,
activeSelection,
now: Date.now(),
maxMountedWorkspaces: workspaceDeckRetentionLimit,
maxMountedWorkspaces: resolveWorkspaceDeckRetentionLimit({ isNative }),
}),
);
}, expirationDelay + 1);
@@ -1,26 +0,0 @@
import type { AudioEngine, AudioEngineCallbacks, AudioEngineOptions } from "./audio-engine-types";
// Preserve the voice model's lifecycle without loading mobile-only Expo audio
// during app startup. Requests fail explicitly until a Linux audio backend exists.
export function createAudioEngine(
_callbacks: AudioEngineCallbacks,
_options?: AudioEngineOptions,
): AudioEngine {
const unavailable = async (): Promise<never> => {
throw new Error("Voice capture and playback are not available in the GPUI build yet.");
};
return {
initialize: unavailable,
startCapture: unavailable,
play: unavailable,
async destroy() {},
async stopCapture() {},
stop() {},
clearQueue() {},
isPlaying: () => false,
isMuted: () => false,
toggleMute() {
throw new Error("Voice capture is not available in the GPUI build yet.");
},
};
}
@@ -52,7 +52,6 @@ import {
} from "@/components/ui/isolated-bottom-sheet-modal";
import { useIsCompactFormFactor } from "@/constants/layout";
import { isNative, isWeb } from "@/constants/platform";
import { usesCompactBottomSheet } from "@/constants/presentation";
import { useAggregatedAgents, type AggregatedAgent } from "@/hooks/use-aggregated-agents";
import { useProjects } from "@/hooks/use-projects";
import { useTimeAgo } from "@/hooks/use-time-ago";
@@ -915,7 +914,7 @@ export function CommandCenter() {
isCompact ? COMMAND_CENTER_LIST_METRICS.compact : COMMAND_CENTER_LIST_METRICS.desktop,
interaction,
);
const showBottomSheet = isCompact && usesCompactBottomSheet;
const showBottomSheet = isCompact && isNative;
const modalLayer = useGlobalOverlayLayer("modal", state.open);
const { sheetRef, handleSheetChange, handleSheetDismiss } = useIsolatedBottomSheetVisibility({
visible: state.open,
@@ -624,8 +624,8 @@ export interface AdaptiveModalSheetProps {
/** Re-establishes caller-owned contexts inside the native or compact sheet portal. */
contextBridge?: ContextBridge | null;
/**
* Keys the body handles while the sheet is the top overlay, such as list navigation. Escape
* always closes the sheet. Return true from `onKeyDown` to claim the key.
* Keys the body handles while the sheet is the top overlay, such as list navigation. Return true
* from `onKeyDown` to claim the key. Escape closes the sheet unless the body lists it and claims it.
*/
keyboard?: SheetKeyboard;
}
@@ -783,12 +783,18 @@ export function AdaptiveModalSheet({
}
event.preventDefault();
event.stopPropagation();
// A body that lists Escape among its keys undoes its own step first, such as a page that
// returns to the one before it; Escape closes the sheet when the body has nothing to undo.
if (keyboard?.keys.includes("Escape") && keyboard.onKeyDown(event)) return true;
onClose();
return true;
},
[keyboard, onClose],
);
const overlayKeys = useMemo(() => ["Escape", ...(keyboard?.keys ?? [])], [keyboard?.keys]);
const overlayKeys = useMemo(
() => ["Escape", ...(keyboard?.keys ?? []).filter((key) => key !== "Escape")],
[keyboard?.keys],
);
const setOverlayScope = useOverlayRegistration({
keys: overlayKeys,
active: visible,
@@ -1,19 +1,26 @@
import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
import { Pressable, Text, View, type PressableStateCallbackType } from "react-native";
import { useCallback, useMemo, useRef, useState, type ReactNode, type RefObject } from "react";
import { Keyboard, Pressable, Text, View, type PressableStateCallbackType } from "react-native";
import { useTranslation } from "react-i18next";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { StyleSheet } from "react-native-unistyles";
import type { AgentProvider } from "@getpaseo/protocol/agent-types";
import type { AgentProfile, AgentProfilePicker, AgentProfileSeed } from "@/agent-profiles";
import { ComboboxTrigger } from "@/components/ui/combobox-trigger";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { Combobox, type ComboboxOption, type ComboboxProps } from "@/components/ui/combobox";
import { ModelBrowser, ModelProviderGlyph, useModelBrowser } from "@/components/model-browser";
import { resolveModelBrowserScrolling } from "@/components/model-browser-view";
import type { ComboboxProps } from "@/components/ui/combobox";
import {
AdaptiveModalSheet,
type SheetHeader,
type SheetKeyboard,
} from "@/components/adaptive-modal-sheet";
import { ModelProviderGlyph, useSelectedModelLabels } from "@/components/model-browser";
import { DesktopModelPicker, type ModelPickerActions } from "@/components/model-browser-panes";
import {
MobileModelPageView,
SheetSearchDock,
useMobileModelPage,
} from "@/components/mobile-model-page";
import { useIsCompactFormFactor } from "@/constants/layout";
import { usesCompactBottomSheet } from "@/constants/presentation";
import { deferModelSelectorMount } from "@/constants/resource-budget";
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import { ICON_SIZE } from "@/styles/theme";
import {
TOOLBAR_GLYPH_SIZES,
toolbarContentSlot,
@@ -22,15 +29,9 @@ import {
import { useKeyboardToggle, type KeyboardToggleAction } from "@/hooks/use-keyboard-toggle";
const EMPTY_COMBOBOX_OPTIONS: ComboboxOption[] = [];
const DEFAULT_TRIGGER_DECORATION = { showCaret: true, tooltip: undefined };
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
const foregroundMutedMapping = (theme: Theme) => ({
color: theme.colors.foregroundMuted,
});
function noop() {}
const SHEET_SNAP_POINTS = ["80%", "90%"];
const ESCAPE_KEYS = ["Escape"] as const;
interface CombinedModelSelectorProps {
providers: ProviderSelectorProvider[];
@@ -59,7 +60,6 @@ interface CombinedModelSelectorProps {
disabled?: boolean;
serverId?: string | null;
desktopPlacement?: ComboboxProps["desktopPlacement"];
desktopMinWidth?: number;
/**
* Render the custom trigger as a full-width form field: the outer Pressable
* becomes a transparent passthrough that stretches its child edge-to-edge and
@@ -76,7 +76,17 @@ interface CombinedModelSelectorProps {
};
}
export function CombinedModelSelector({
export function CombinedModelSelector(props: CombinedModelSelectorProps) {
const isCompact = useIsCompactFormFactor();
// One frame per form factor: a sheet that drills into providers, or a two-pane popover.
return isCompact ? (
<CompactCombinedModelSelector {...props} />
) : (
<DesktopCombinedModelSelector {...props} />
);
}
function DesktopCombinedModelSelector({
providers,
selectedProvider,
selectedModel,
@@ -96,63 +106,127 @@ export function CombinedModelSelector({
disabled = false,
serverId = null,
desktopPlacement,
desktopMinWidth,
triggerFill = false,
toolbar,
}: CombinedModelSelectorProps) {
const anchorRef = useRef<View>(null);
const [isOpen, setIsOpen] = useState(false);
const labels = useSelectedModelLabels({ providers, selectedProvider, selectedModel, isLoading });
const handleOpenChange = useCallback(
(open: boolean) => {
setIsOpen(open);
if (open) onOpen?.();
else onClose?.();
},
[onClose, onOpen],
);
const handleTriggerPress = useCallback(() => {
handleOpenChange(!isOpen);
}, [handleOpenChange, isOpen]);
const actions = useModelSelectorActions({
onOpenChange: handleOpenChange,
onSelect,
onApplyProfile,
onEditProfiles,
onCreateProfile,
onEditProfile,
});
useKeyboardToggle({
action: toggleAction,
disabled,
open: isOpen,
// The search field holds focus for as long as the popover is open.
searchFocused: isOpen,
onToggle: handleTriggerPress,
});
return (
<>
<ModelSelectorTrigger
anchorRef={anchorRef}
isOpen={isOpen}
disabled={disabled}
onPress={handleTriggerPress}
labels={labels}
selectedProvider={selectedProvider}
serverId={serverId}
renderTrigger={renderTrigger}
triggerFill={triggerFill}
toolbar={toolbar}
/>
<DesktopModelPicker
open={isOpen}
onOpenChange={handleOpenChange}
anchorRef={anchorRef}
desktopPlacement={desktopPlacement}
providers={providers}
selectedProvider={selectedProvider}
selectedModel={selectedModel}
profiles={profiles}
serverId={serverId}
onSelect={actions.handleSelect}
onApplyProfile={actions.handleApplyProfile}
onEditProfiles={onEditProfiles ? actions.handleEditProfiles : undefined}
onCreateProfile={onCreateProfile ? actions.handleCreateProfile : undefined}
onEditProfile={onEditProfile ? actions.handleEditProfile : undefined}
onRetryProvider={onRetryProvider}
isRetryingProvider={isRetryingProvider}
/>
</>
);
}
function CompactCombinedModelSelector({
providers,
selectedProvider,
selectedModel,
onSelect,
isLoading,
profiles = null,
onApplyProfile,
onEditProfiles,
onCreateProfile,
onEditProfile,
renderTrigger,
toggleAction,
onOpen,
onClose,
onRetryProvider,
isRetryingProvider = false,
disabled = false,
serverId = null,
triggerFill = false,
toolbar,
}: CombinedModelSelectorProps) {
const { t } = useTranslation();
const isCompact = useIsCompactFormFactor();
const modelBrowserScrolling = resolveModelBrowserScrolling({
usesCompactBottomSheet,
isCompact,
});
const anchorRef = useRef<View>(null);
const [isOpen, setIsOpen] = useState(false);
const [isContentReady, setIsContentReady] = useState(!deferModelSelectorMount);
const browser = useModelBrowser({
const labels = useSelectedModelLabels({ providers, selectedProvider, selectedModel, isLoading });
const page = useMobileModelPage({
providers,
profiles: profiles?.rows ?? null,
canCreateProfile: Boolean(onEditProfiles),
selectedProvider,
selectedModel,
isLoading,
profiles,
serverId,
});
const { prepareToOpen, reset } = browser;
const { reset, clearQuery } = page;
const handleOpenChange = useCallback(
(open: boolean) => {
setIsOpen(open);
if (open) {
prepareToOpen();
reset();
onOpen?.();
return;
}
reset();
Keyboard.dismiss();
onClose?.();
},
[onClose, onOpen, prepareToOpen, reset],
[onClose, onOpen, reset],
);
const handleSelect = useCallback(
(provider: string, modelId: string) => {
onSelect(provider, modelId);
handleOpenChange(false);
},
[handleOpenChange, onSelect],
);
useEffect(() => {
if (!deferModelSelectorMount) return () => {};
if (!isOpen) {
setIsContentReady(false);
return () => {};
}
const frame = requestAnimationFrame(() => {
setIsContentReady(true);
});
return () => cancelAnimationFrame(frame);
}, [isOpen]);
const handleClose = useCallback(() => handleOpenChange(false), [handleOpenChange]);
const handleTriggerPress = useCallback(() => {
handleOpenChange(!isOpen);
}, [handleOpenChange, isOpen]);
@@ -161,10 +235,184 @@ export function CombinedModelSelector({
action: toggleAction,
disabled,
open: isOpen,
searchFocused: browser.isSearchFocused,
searchFocused: false,
onToggle: handleTriggerPress,
});
const actions = useModelSelectorActions({
onOpenChange: handleOpenChange,
onSelect,
onApplyProfile,
onEditProfiles,
onCreateProfile,
onEditProfile,
});
const pickerActions = useMemo<ModelPickerActions>(
() => ({
onSelect: actions.handleSelect,
onApplyProfile: actions.handleApplyProfile,
onEditProfiles: onEditProfiles ? actions.handleEditProfiles : undefined,
onCreateProfile: onCreateProfile ? actions.handleCreateProfile : undefined,
onEditProfile: onEditProfile ? actions.handleEditProfile : undefined,
onRetryProvider,
isRetryingProvider,
}),
[actions, isRetryingProvider, onCreateProfile, onEditProfile, onEditProfiles, onRetryProvider],
);
// Escape clears the search first, then closes the sheet.
const query = page.query;
const keyboard = useMemo<SheetKeyboard>(
() => ({
keys: ESCAPE_KEYS,
onKeyDown: (event) => {
if (event.key !== "Escape" || query.trim().length === 0) return false;
clearQuery();
return true;
},
}),
[clearQuery, query],
);
const header = useMemo<SheetHeader>(() => ({ title: t("modelSelector.selectModel") }), [t]);
const footer = useMemo(() => {
let placeholder = t("modelSelector.searchPlaceholder");
if (profiles && profiles.rows.length > 0) {
placeholder = t("modelSelector.searchModelsAndProfilesPlaceholder");
} else if (providers.length > 1) {
placeholder = t("modelSelector.searchAllPlaceholder");
}
return (
<SheetSearchDock
query={page.query}
searchKey={page.searchKey}
onChangeText={page.setQuery}
placeholder={placeholder}
testID="model-search-all-input"
/>
);
}, [page.query, page.searchKey, page.setQuery, profiles, providers.length, t]);
return (
<>
<ModelSelectorTrigger
anchorRef={anchorRef}
isOpen={isOpen}
disabled={disabled}
onPress={handleTriggerPress}
labels={labels}
selectedProvider={selectedProvider}
serverId={serverId}
renderTrigger={renderTrigger}
triggerFill={triggerFill}
toolbar={toolbar}
/>
<AdaptiveModalSheet
header={header}
visible={isOpen}
onClose={handleClose}
snapPoints={SHEET_SNAP_POINTS}
scrollable={false}
footer={footer}
keyboard={keyboard}
contentStyle={styles.sheetBody}
testID="model-selector-sheet"
>
<MobileModelPageView
page={page}
selectedProvider={selectedProvider}
selectedModel={selectedModel}
serverId={serverId}
profiles={profiles?.rows ?? null}
actions={pickerActions}
/>
</AdaptiveModalSheet>
</>
);
}
/**
* Every pick resolves the selector and closes it. A 1-tap `+` saves the profile, selects its model
* immediately, and closes the picker; useAgentProfileEditor surfaces a toast with Edit and Undo.
*/
function useModelSelectorActions({
onOpenChange,
onSelect,
onApplyProfile,
onEditProfiles,
onCreateProfile,
onEditProfile,
}: Pick<
CombinedModelSelectorProps,
"onSelect" | "onApplyProfile" | "onEditProfiles" | "onCreateProfile" | "onEditProfile"
> & { onOpenChange: (open: boolean) => void }) {
const handleSelect = useCallback(
(provider: string, modelId: string) => {
onSelect(provider, modelId);
onOpenChange(false);
},
[onOpenChange, onSelect],
);
const handleApplyProfile = useCallback(
(profileId: string) => {
onApplyProfile?.(profileId);
onOpenChange(false);
},
[onApplyProfile, onOpenChange],
);
const handleEditProfiles = useCallback(() => {
onOpenChange(false);
onEditProfiles?.();
}, [onEditProfiles, onOpenChange]);
const handleCreateProfile = useCallback(
(seed: AgentProfileSeed) => {
if (seed.modelId) {
onSelect(seed.provider, seed.modelId);
}
onOpenChange(false);
void onCreateProfile?.(seed);
},
[onCreateProfile, onOpenChange, onSelect],
);
const handleEditProfile = useCallback(
(profileId: string) => {
onOpenChange(false);
onEditProfile?.(profileId);
},
[onEditProfile, onOpenChange],
);
return {
handleSelect,
handleApplyProfile,
handleEditProfiles,
handleCreateProfile,
handleEditProfile,
};
}
function ModelSelectorTrigger({
anchorRef,
isOpen,
disabled,
onPress,
labels,
selectedProvider,
serverId,
renderTrigger,
triggerFill,
toolbar,
}: {
anchorRef: RefObject<View | null>;
isOpen: boolean;
disabled: boolean;
onPress: () => void;
labels: { selectedModelLabel: string; triggerLabel: string };
selectedProvider: string;
serverId: string | null;
renderTrigger: CombinedModelSelectorProps["renderTrigger"];
triggerFill: boolean;
toolbar: CombinedModelSelectorProps["toolbar"];
}) {
const { t } = useTranslation();
const triggerStyle = useCallback(
({ pressed, hovered }: PressableStateCallbackType & { hovered?: boolean }) => {
if (triggerFill) {
@@ -185,145 +433,73 @@ export function CombinedModelSelector({
},
[disabled, isOpen, renderTrigger, triggerFill],
);
const handleApplyProfile = useCallback(
(profileId: string) => {
onApplyProfile?.(profileId);
handleOpenChange(false);
},
[handleOpenChange, onApplyProfile],
);
const handleEditProfiles = useCallback(() => {
handleOpenChange(false);
onEditProfiles?.();
}, [handleOpenChange, onEditProfiles]);
// 1-tap `+` saves the profile, selects the model immediately, and closes the picker;
// useAgentProfileEditor surfaces a toast with Edit and Undo actions.
const handleCreateProfile = useCallback(
(seed: AgentProfileSeed) => {
if (seed.modelId) {
onSelect(seed.provider, seed.modelId);
}
handleOpenChange(false);
void onCreateProfile?.(seed);
},
[handleOpenChange, onCreateProfile, onSelect],
);
const handleEditProfile = useCallback(
(profileId: string) => {
handleOpenChange(false);
onEditProfile?.(profileId);
},
[handleOpenChange, onEditProfile],
);
const selectorBody = isContentReady ? (
<ModelBrowser
state={browser}
onSelect={handleSelect}
onApplyProfile={handleApplyProfile}
onEditProfiles={onEditProfiles ? handleEditProfiles : undefined}
onCreateProfile={onCreateProfile ? handleCreateProfile : undefined}
onEditProfile={onEditProfile ? handleEditProfile : undefined}
onRetryProvider={onRetryProvider}
isRetryingProvider={isRetryingProvider}
scrolling={modelBrowserScrolling}
/>
) : (
<View style={styles.sheetLoadingState}>
<ThemedLoadingSpinner size={ICON_SIZE.sm} uniProps={foregroundMutedMapping} />
<Text style={styles.sheetLoadingText}>{t("modelSelector.loadingSelector")}</Text>
</View>
);
const accessibilityLabel = t("modelSelector.selectedModel", {
model: labels.selectedModelLabel,
});
const { showCaret, tooltip } = toolbar ?? DEFAULT_TRIGGER_DECORATION;
return (
<>
{renderTrigger ? (
<Pressable
ref={anchorRef}
collapsable={false}
disabled={disabled}
onPress={handleTriggerPress}
style={triggerStyle}
accessibilityRole="button"
accessibilityLabel={t("modelSelector.selectedModel", {
model: browser.selectedModelLabel,
})}
testID="combined-model-selector"
>
{({ pressed, hovered }: PressableStateCallbackType & { hovered?: boolean }) =>
renderTrigger({
selectedModelLabel: browser.triggerLabel,
onPress: handleTriggerPress,
disabled,
isOpen,
hovered: Boolean(hovered),
pressed,
})
}
</Pressable>
) : (
<ComboboxTrigger
ref={anchorRef}
collapsable={false}
disabled={disabled}
onPress={handleTriggerPress}
style={triggerStyle}
accessibilityRole="button"
accessibilityLabel={t("modelSelector.selectedModel", {
model: browser.selectedModelLabel,
})}
testID="combined-model-selector"
chevron={showCaret === false ? null : undefined}
tooltip={tooltip}
>
{selectedProvider.trim().length > 0 ? (
<View style={toolbar ? styles.toolbarGlyph : styles.glyph}>
<ModelProviderGlyph
provider={selectedProvider}
serverId={serverId}
size={toolbar?.glyph.size ?? ICON_SIZE.md}
strokeWidth={toolbar?.glyph.strokeWidth}
tone={toolbar?.glyph.tone}
/>
</View>
) : null}
<Text style={styles.triggerText} numberOfLines={1} ellipsizeMode="tail">
{browser.triggerLabel}
</Text>
</ComboboxTrigger>
)}
<Combobox
options={EMPTY_COMBOBOX_OPTIONS}
value=""
onSelect={noop}
open={isOpen}
onOpenChange={handleOpenChange}
anchorRef={anchorRef}
desktopPlacement={desktopPlacement}
desktopMinWidth={desktopMinWidth}
desktopLockWidth
desktopFixedHeight={browser.desktopFixedHeight}
desktopChildrenScrollEnabled={false}
header={browser.header}
keyboard={browser.keyboard}
mobileChildrenScrollEnabled={!browser.isProviderView || !usesCompactBottomSheet}
mobileChildrenContentContainerStyle={styles.mobileBrowserContent}
if (renderTrigger) {
return (
<Pressable
ref={anchorRef}
collapsable={false}
disabled={disabled}
onPress={onPress}
style={triggerStyle}
accessibilityRole="button"
accessibilityLabel={accessibilityLabel}
testID="combined-model-selector"
>
{selectorBody}
</Combobox>
</>
{({ pressed, hovered }: PressableStateCallbackType & { hovered?: boolean }) =>
renderTrigger({
selectedModelLabel: labels.triggerLabel,
onPress,
disabled,
isOpen,
hovered: Boolean(hovered),
pressed,
})
}
</Pressable>
);
}
return (
<ComboboxTrigger
ref={anchorRef}
collapsable={false}
disabled={disabled}
onPress={onPress}
style={triggerStyle}
accessibilityRole="button"
accessibilityLabel={accessibilityLabel}
testID="combined-model-selector"
chevron={showCaret === false ? null : undefined}
tooltip={tooltip}
>
{selectedProvider.trim().length > 0 ? (
<View style={toolbar ? styles.toolbarGlyph : styles.glyph}>
<ModelProviderGlyph
provider={selectedProvider}
serverId={serverId}
size={toolbar?.glyph.size ?? ICON_SIZE.md}
strokeWidth={toolbar?.glyph.strokeWidth}
tone={toolbar?.glyph.tone}
/>
</View>
) : null}
<Text style={styles.triggerText} numberOfLines={1} ellipsizeMode="tail">
{labels.triggerLabel}
</Text>
</ComboboxTrigger>
);
}
const styles = StyleSheet.create((theme) => ({
mobileBrowserContent: {
sheetBody: {
paddingHorizontal: 0,
paddingTop: 0,
paddingBottom: 0,
gap: 0,
},
trigger: {
minWidth: 0,
@@ -375,14 +551,4 @@ const styles = StyleSheet.create((theme) => ({
backgroundColor: "transparent",
borderRadius: 0,
},
sheetLoadingState: {
minHeight: 160,
justifyContent: "center",
alignItems: "center",
gap: theme.spacing[2],
},
sheetLoadingText: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.base,
},
}));
@@ -16,7 +16,6 @@ import DraggableFlatList, {
import type { GestureType } from "react-native-gesture-handler";
import { useUnistyles } from "react-native-unistyles";
import { useContentDrag } from "@/components/ui/content-drag";
import { supportsTouchHaptics } from "@/constants/touch-timing";
import { createDragHold } from "./drag-reorder/drag-hold";
import { movedItemKey } from "./drag-reorder/native-drop";
import type {
@@ -53,7 +52,7 @@ export function DraggableListHandle({ testID, style, children }: DraggableListHa
delayMs: HANDLE_HOLD_MS,
slopPx: HANDLE_HOLD_SLOP_PX,
onArm: () => {
if (supportsTouchHaptics) void Haptics.selectionAsync().catch(() => {});
void Haptics.selectionAsync().catch(() => {});
drag();
},
})
@@ -1,17 +0,0 @@
import { Text, View } from "react-native";
import { HighlightedCodeBlock } from "@/components/highlighted-code-block";
import type { MarkdownFenceRendererProps } from "./types";
export function MermaidFenceHost({ code, inheritedStyles, textStyle }: MarkdownFenceRendererProps) {
return (
<View>
<Text style={inheritedStyles}>Diagram rendering is not available in the GPUI build yet.</Text>
<HighlightedCodeBlock
code={code}
language="mermaid"
inheritedStyles={inheritedStyles}
textStyle={textStyle}
/>
</View>
);
}
+3 -7
View File
@@ -23,7 +23,7 @@ import {
import { TaskListRow } from "@/components/task-list-row";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { useIsCompactFormFactor } from "@/constants/layout";
import { isNative, isWeb, supportsMaskedEffects } from "@/constants/platform";
import { isNative, isWeb } from "@/constants/platform";
import { useRevealedText, type MarkdownPhase } from "@/hooks/use-revealed-text";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
@@ -1905,7 +1905,7 @@ function computeShimmerMetrics(input: {
// React Native Web only observes a node when onLayout exists at mount. Keep
// measuring while idle so a retained badge has dimensions when it starts loading.
const shouldMeasureWebShimmer = isWeb;
const shouldMeasureNativeShimmer = input.isLoading && isNative && supportsMaskedEffects;
const shouldMeasureNativeShimmer = input.isLoading && isNative;
const isNativeShimmer =
shouldMeasureNativeShimmer && input.labelRowWidth > 0 && input.labelRowHeight > 0;
const webShimmerSpanStartX = input.labelOffsetX;
@@ -2331,7 +2331,6 @@ function areExpandableBadgePropsEqual(previous: ExpandableBadgeProps, next: Expa
}
interface ToolCallProps {
agentMessage?: AgentMessage;
serverId?: string;
toolName: string;
args?: unknown;
@@ -2354,7 +2353,6 @@ interface ToolCallProps {
}
export const ToolCall = memo(function ToolCall({
agentMessage,
serverId,
toolName,
args,
@@ -2403,7 +2401,6 @@ export const ToolCall = memo(function ToolCall({
const presentation = useMemo(
() =>
buildToolCallPresentation({
agentMessage,
toolName,
status,
error: error ?? null,
@@ -2413,7 +2410,7 @@ export const ToolCall = memo(function ToolCall({
targetAgentTitle,
resolveIcon: resolveToolCallIcon,
}),
[toolName, status, error, effectiveDetail, metadata, cwd, agentMessage, targetAgentTitle],
[toolName, status, error, effectiveDetail, metadata, cwd, targetAgentTitle],
);
const handleOpenFile = useMemo(() => {
const openFilePath = presentation.openFilePath;
@@ -2524,7 +2521,6 @@ export const ToolCall = memo(function ToolCall({
function areToolCallPropsEqual(previous: ToolCallProps, next: ToolCallProps) {
if (previous.toolName !== next.toolName) return false;
if (previous.serverId !== next.serverId) return false;
if (previous.agentMessage !== next.agentMessage) return false;
if (previous.args !== next.args) return false;
if (previous.result !== next.result) return false;
if (previous.error !== next.error) return false;
@@ -0,0 +1,364 @@
import { describe, expect, it } from "vitest";
import { MODEL_PICKER_PROFILES_RAIL_KEY } from "@/components/model-browser-panes-view";
import type { NavigableProfileRow } from "@/components/model-browser-view";
import type {
ProviderSelectionModelRow,
ProviderSelectorProvider,
} from "@/provider-selection/provider-selection";
import {
createMobileModelPageState,
projectMobileModelPage,
reduceMobileModelPage,
type MobileModelPageInput,
type MobileModelPageProjection,
} from "./mobile-model-page-view";
function row(
providerId: string,
providerLabel: string,
modelId: string,
options: { legacy?: boolean } = {},
): ProviderSelectionModelRow {
return {
favoriteKey: `${providerId}:${modelId}`,
provider: providerId,
providerLabel,
modelId,
modelLabel: modelId,
...(options.legacy ? { legacy: true } : {}),
};
}
const profile = (
id: string,
name: string,
summary: string,
provider: string,
): NavigableProfileRow => ({
id,
name,
summary,
provider,
});
const reviewer = profile("reviewer", "Reviewer", "Claude · Opus 5.5 · Plan", "claude");
const fixer = profile("fixer", "Bug fixer", "Codex · GPT-5.4", "codex");
const claudeOlder = Array.from({ length: 15 }, (_, index) => `claude-older-${index + 1}`);
const claude: ProviderSelectorProvider = {
id: "claude",
label: "Claude",
modelSelection: {
kind: "models",
rows: [
...["opus-5.5", "fable-5.2", "sonnet-5.5", "haiku-5.5"].map((id) =>
row("claude", "Claude", id),
),
...claudeOlder.map((id) => row("claude", "Claude", id, { legacy: true })),
],
},
};
const copilot: ProviderSelectorProvider = {
id: "copilot",
label: "Copilot",
modelSelection: { kind: "error", message: "Not signed in" },
};
const codex: ProviderSelectorProvider = {
id: "codex",
label: "Codex",
modelSelection: {
kind: "models",
rows: [row("codex", "Codex", "gpt-5.4"), row("codex", "Codex", "gpt-5.4-mini")],
},
};
const opencode: ProviderSelectorProvider = {
id: "opencode",
label: "OpenCode",
modelSelection: { kind: "loading" },
};
const pi: ProviderSelectorProvider = {
id: "pi",
label: "Pi",
shownModels: ["anthropic/opus-5.5", "openai/gpt-5.4"],
modelSelection: {
kind: "models",
rows: [
row("pi", "Pi", "anthropic/opus-5.5"),
row("pi", "Pi", "openai/gpt-5.4"),
row("pi", "Pi", "openai/gpt-5.4-mini"),
row("pi", "Pi", "anthropic/opus-4.6"),
],
},
};
const input: MobileModelPageInput = {
providers: [claude, copilot, codex, opencode, pi],
profiles: null,
canCreateProfile: false,
selectedProvider: "claude",
selectedModel: "opus-5.5",
};
const inputWithProfiles: MobileModelPageInput = {
...input,
profiles: [reviewer, fixer],
canCreateProfile: true,
};
function project(
actions: Parameters<typeof reduceMobileModelPage>[1][] = [],
pageInput: MobileModelPageInput = input,
): MobileModelPageProjection {
const state = actions.reduce(reduceMobileModelPage, createMobileModelPageState(pageInput));
return projectMobileModelPage(pageInput, state);
}
function browse(projection: MobileModelPageProjection) {
if (projection.kind !== "browse") throw new Error(`expected browse, got ${projection.kind}`);
return projection;
}
function bodyKeys(projection: MobileModelPageProjection): string[] {
const { body } = browse(projection);
if (!body) throw new Error("expected an expanded section body, got null");
return body.items.map((item) => item.key);
}
describe("mobile model page", () => {
it("opens with the selected provider expanded and the others as rows, errors last", () => {
const projection = browse(project());
expect(projection.showSectionHeaders).toBe(true);
expect(
projection.sections.map((section) =>
section.kind === "provider"
? {
providerId: section.providerId,
status: section.status,
expanded: section.expanded,
shown: section.shown,
total: section.total,
}
: section,
),
).toEqual([
{ providerId: "claude", status: "ready", expanded: true, shown: 4, total: 19 },
{ providerId: "codex", status: "ready", expanded: false, shown: 2, total: 2 },
{ providerId: "opencode", status: "loading", expanded: false, shown: 0, total: 0 },
{ providerId: "pi", status: "ready", expanded: false, shown: 2, total: 4 },
{ providerId: "copilot", status: "error", expanded: false, shown: 0, total: 0 },
]);
});
it("places Profiles as the first collapsible category when the surface offers profiles", () => {
const projection = browse(project([], inputWithProfiles));
expect(projection.showSectionHeaders).toBe(true);
expect(projection.sections[0]).toEqual({
kind: "profiles",
key: MODEL_PICKER_PROFILES_RAIL_KEY,
count: 2,
expanded: false,
});
expect(projection.sections.find((section) => section.expanded)?.key).toBe("claude");
});
it("expands Profiles to list saved profiles, or Create profile when there are none", () => {
const expanded = browse(
project([{ kind: "toggleSection", key: MODEL_PICKER_PROFILES_RAIL_KEY }], inputWithProfiles),
);
expect(expanded.sections.filter((section) => section.expanded)).toMatchObject([
{ kind: "profiles", key: MODEL_PICKER_PROFILES_RAIL_KEY },
]);
expect(expanded.body).toEqual({
kind: "profiles",
items: [
{ kind: "profile", key: "profile:reviewer", profile: reviewer },
{ kind: "profile", key: "profile:fixer", profile: fixer },
],
});
const emptyCreate = browse(
project([{ kind: "toggleSection", key: MODEL_PICKER_PROFILES_RAIL_KEY }], {
...inputWithProfiles,
profiles: [],
canCreateProfile: true,
}),
);
expect(emptyCreate.body).toEqual({
kind: "profiles",
items: [{ kind: "createProfile", key: "create-profile" }],
});
});
it("collapses the open section when tapped again so every group can be collapsed", () => {
const collapsedProvider = browse(
project([{ kind: "toggleSection", key: "claude" }], inputWithProfiles),
);
expect(collapsedProvider.sections.every((section) => !section.expanded)).toBe(true);
expect(collapsedProvider.body).toBeNull();
expect(collapsedProvider.selectedIndex).toBeNull();
const collapsedProfiles = browse(
project(
[
{ kind: "toggleSection", key: MODEL_PICKER_PROFILES_RAIL_KEY },
{ kind: "toggleSection", key: MODEL_PICKER_PROFILES_RAIL_KEY },
],
inputWithProfiles,
),
);
expect(collapsedProfiles.sections.every((section) => !section.expanded)).toBe(true);
expect(collapsedProfiles.body).toBeNull();
});
it("lists the expanded provider's shown models above a closed fold", () => {
expect(bodyKeys(project())).toEqual([
"model:claude:opus-5.5",
"model:claude:fable-5.2",
"model:claude:sonnet-5.5",
"model:claude:haiku-5.5",
"fold:claude",
]);
});
it("opens the fold to list the models behind it", () => {
const keys = bodyKeys(project([{ kind: "toggleFold", providerId: "claude", expanded: true }]));
expect(keys).toHaveLength(4 + 1 + 15);
expect(keys[5]).toBe("model:claude:claude-older-1");
});
it("expands one section at a time", () => {
const projection = browse(project([{ kind: "toggleSection", key: "pi" }]));
expect(projection.sections.filter((section) => section.expanded)).toMatchObject([
{ kind: "provider", providerId: "pi" },
]);
expect(bodyKeys(projection)).toEqual([
"model:pi:anthropic/opus-5.5",
"model:pi:openai/gpt-5.4",
"fold:pi",
]);
});
it("opens the fold when the selected model sits behind it", () => {
const keys = bodyKeys(
project([], { ...input, selectedProvider: "claude", selectedModel: "claude-older-3" }),
);
expect(keys).toContain("model:claude:claude-older-3");
});
it("points the open list at the selected model, so a folded pick is in view on reopen", () => {
const folded = browse(
project([], { ...input, selectedProvider: "claude", selectedModel: "claude-older-3" }),
);
expect(
folded.body?.kind === "provider" && folded.body.items[folded.selectedIndex ?? -1]?.key,
).toBe("model:claude:claude-older-3");
expect(browse(project()).selectedIndex).toBe(0);
expect(browse(project([{ kind: "toggleSection", key: "codex" }])).selectedIndex).toBeNull();
});
it("shows a loading or errored provider's state in its section", () => {
expect(browse(project([{ kind: "toggleSection", key: "opencode" }])).body).toMatchObject({
kind: "providerLoading",
providerId: "opencode",
});
expect(browse(project([{ kind: "toggleSection", key: "copilot" }])).body).toMatchObject({
kind: "providerError",
providerId: "copilot",
message: "Not signed in",
});
});
it("expands the first ready provider when the selected one is not listed and there are no profiles", () => {
const projection = browse(project([], { ...input, selectedProvider: "", selectedModel: "" }));
expect(projection.sections.find((section) => section.expanded)?.key).toBe("claude");
});
it("lists a lone provider's models without section headers when profiles are absent, and with headers when profiles exist", () => {
const loneWithoutProfiles = browse(
project([], {
providers: [codex],
profiles: null,
canCreateProfile: false,
selectedProvider: "codex",
selectedModel: "gpt-5.4",
}),
);
expect(loneWithoutProfiles.showSectionHeaders).toBe(false);
expect(bodyKeys(loneWithoutProfiles)).toEqual([
"model:codex:gpt-5.4",
"model:codex:gpt-5.4-mini",
]);
const loneWithProfiles = browse(
project([], {
providers: [codex],
profiles: [],
canCreateProfile: true,
selectedProvider: "codex",
selectedModel: "gpt-5.4",
}),
);
expect(loneWithProfiles.showSectionHeaders).toBe(true);
expect(loneWithProfiles.sections.map((section) => section.key)).toEqual([
MODEL_PICKER_PROFILES_RAIL_KEY,
"codex",
]);
});
it("searches profiles and every provider, shown models before folded ones", () => {
const projection = project([{ kind: "query", query: "opus" }], inputWithProfiles);
expect(projection.kind).toBe("search");
if (projection.kind !== "search") return;
expect(projection.profiles.map((item) => item.key)).toEqual(["profile:reviewer"]);
expect(
projection.models.map((item) => (item.kind === "model" ? [item.key, item.tag] : [item.key])),
).toEqual([
["model:claude:opus-5.5", null],
["model:pi:anthropic/opus-5.5", null],
["model:pi:anthropic/opus-4.6", "all"],
]);
});
it("finds folded models that only match behind the fold", () => {
const projection = project([{ kind: "query", query: "older-12" }]);
expect(projection).toMatchObject({
kind: "search",
items: [{ key: "model:claude:claude-older-12", tag: "older" }],
});
});
it("returns to the expanded or all-collapsed state when the search clears", () => {
const expandedAgain = project([
{ kind: "toggleSection", key: "pi" },
{ kind: "query", query: "opus" },
{ kind: "query", query: "" },
]);
expect(browse(expandedAgain).sections.find((section) => section.expanded)?.key).toBe("pi");
const stillCollapsed = project([
{ kind: "toggleSection", key: "claude" },
{ kind: "query", query: "opus" },
{ kind: "query", query: "" },
]);
expect(browse(stillCollapsed).body).toBeNull();
expect(browse(stillCollapsed).sections.every((section) => !section.expanded)).toBe(true);
});
it("says when the host lists no providers, as it does before the first provider snapshot", () => {
const empty: MobileModelPageInput = {
providers: [],
profiles: null,
canCreateProfile: false,
selectedProvider: "",
selectedModel: "",
};
expect(project([], empty)).toEqual({ kind: "noProviders" });
expect(project([{ kind: "query", query: "opus" }], empty)).toEqual({ kind: "noProviders" });
});
it("says when nothing matches", () => {
expect(project([{ kind: "query", query: " zzz " }])).toEqual({
kind: "noMatches",
query: "zzz",
});
});
});

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