mirror of
https://github.com/getpaseo/paseo.git
synced 2026-12-01 04:36:26 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1bfa3c3ecd | ||
|
|
97628dfd13 | ||
|
|
25441b1845 | ||
|
|
e1bb1f8ff1 | ||
|
|
20354c13b9 | ||
|
|
f3e59c1c86 | ||
|
|
ce5b60a9e6 | ||
|
|
59a5724460 | ||
|
|
e713f5acf7 | ||
|
|
a271074716 | ||
|
|
c026b27639 | ||
|
|
526aa3133e | ||
|
|
b08a0bc6ce | ||
|
|
d7404733f6 | ||
|
|
0d215ecf29 | ||
|
|
df45627da5 | ||
|
|
5343d72939 | ||
|
|
990721e134 | ||
|
|
b1677e58d8 | ||
|
|
08298dcc10 | ||
|
|
cafb42560c | ||
|
|
6655aa77b3 | ||
|
|
291d54fa71 | ||
|
|
ddb15230b3 | ||
|
|
9dc533fcd2 | ||
|
|
0ee4a57981 | ||
|
|
aa957c9ca9 | ||
|
|
a96a4d61f1 | ||
|
|
6916ceee47 | ||
|
|
635df88fa6 | ||
|
|
552690e45c | ||
|
|
9815d68f3b | ||
|
|
59377767c7 | ||
|
|
67612b36f3 | ||
|
|
01227a73a4 | ||
|
|
12a6f07939 | ||
|
|
34d38a82d2 | ||
|
|
d71d9b37c6 | ||
|
|
eae885fba4 | ||
|
|
6ec8941943 | ||
|
|
dbeb181f03 |
@@ -1,2 +0,0 @@
|
||||
packages/app/gpui/package-lock.json linguist-generated
|
||||
packages/app/gpui/desktop/Cargo.lock linguist-generated
|
||||
@@ -1,6 +1,6 @@
|
||||
# Pull-request checks are routed by the behavior they prove. Package consumers
|
||||
# do not inherit their dependencies' test suites; main and manual runs execute
|
||||
# every contract regardless of these paths.
|
||||
# do not inherit their dependencies' test suites, except where noted below; main
|
||||
# and manual runs execute every contract regardless of these paths.
|
||||
routing:
|
||||
- ".github/ci-paths.yml"
|
||||
|
||||
@@ -60,6 +60,7 @@ sdk:
|
||||
- "packages/client/**"
|
||||
- "packages/highlight/**"
|
||||
- "packages/protocol/**"
|
||||
- "packages/workflows/**"
|
||||
|
||||
browser:
|
||||
- "packages/server/src/server/agent/provider-snapshot-manager.ts"
|
||||
@@ -87,5 +88,9 @@ browser:
|
||||
relay:
|
||||
- "packages/relay/**"
|
||||
|
||||
# cli-tests is also a daemon end-to-end suite: it drives a real daemon, built-in
|
||||
# plugins included, so daemon changes run it too.
|
||||
cli:
|
||||
- "packages/cli/**"
|
||||
- "packages/server/**"
|
||||
- "plugins/**"
|
||||
|
||||
@@ -8,13 +8,14 @@ on:
|
||||
merge_group:
|
||||
workflow_dispatch:
|
||||
|
||||
# A newer push to the same ref cancels the run still in progress, main included.
|
||||
# A full run costs about 200 runner-minutes against the org's 20 concurrent
|
||||
# jobs, and a superseded main run only answers a question the newer commit
|
||||
# answers again.
|
||||
# A newer push cancels the run still in progress on every ref except main,
|
||||
# because a full run costs about 200 runner-minutes against the org's 20
|
||||
# concurrent jobs. A main run finishes: cancelling it mid-flight leaves CANCELLED
|
||||
# checks that paint the commit red. Each ref has one run in progress and one
|
||||
# pending, so a newer push replaces a pending main run before it starts any job.
|
||||
concurrency:
|
||||
group: ci-${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
|
||||
|
||||
env:
|
||||
# CI does not use the CUDA execution provider, and the onnxruntime-node
|
||||
@@ -127,6 +128,14 @@ jobs:
|
||||
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
|
||||
run: npm run test --workspace=@getpaseo/highlight
|
||||
|
||||
- name: Build workflows package
|
||||
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
|
||||
run: npm run build:workflows
|
||||
|
||||
- name: Run workflows tests
|
||||
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
|
||||
run: npm run test --workspace=@getpaseo/workflows
|
||||
|
||||
- name: Typecheck client examples
|
||||
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
|
||||
run: npm run typecheck:examples --workspace=@getpaseo/client
|
||||
@@ -174,6 +183,9 @@ jobs:
|
||||
- name: Verify dependency patch recovery
|
||||
run: node --test scripts/postinstall-patches.test.mjs
|
||||
|
||||
- name: Verify daemon runtime trace contract
|
||||
run: node --test scripts/trace-daemon.test.mjs
|
||||
|
||||
- name: Build server stack
|
||||
run: npm run build:server
|
||||
|
||||
@@ -213,6 +225,15 @@ jobs:
|
||||
- name: Verify website mockups
|
||||
run: npm run test:e2e --workspace=@getpaseo/website
|
||||
|
||||
- name: Upload website test artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
if: failure()
|
||||
with:
|
||||
name: website-playwright-results
|
||||
path: packages/website/test-results/
|
||||
if-no-files-found: ignore
|
||||
retention-days: 7
|
||||
|
||||
- name: Verify public package contents
|
||||
run: |
|
||||
npm pack --dry-run --ignore-scripts --workspace=@getpaseo/protocol
|
||||
|
||||
@@ -13,9 +13,11 @@ on:
|
||||
- ".github/workflows/desktop-packages.yml"
|
||||
workflow_dispatch:
|
||||
|
||||
# A main run finishes. A run cancelled mid-flight leaves CANCELLED checks that
|
||||
# paint the commit red.
|
||||
concurrency:
|
||||
group: desktop-packages-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
@@ -28,9 +28,11 @@ on:
|
||||
- "false"
|
||||
- "true"
|
||||
|
||||
# main, tag and publish runs finish. A run cancelled mid-flight leaves CANCELLED
|
||||
# checks that paint a main commit red.
|
||||
concurrency:
|
||||
group: docker-${{ github.workflow }}-${{ github.event_name == 'workflow_dispatch' && inputs.publish == 'true' && format('publish-{0}', inputs.paseo_version || github.run_id) || github.ref }}
|
||||
cancel-in-progress: ${{ !startsWith(github.ref, 'refs/tags/') && !(github.event_name == 'workflow_dispatch' && inputs.publish == 'true') }}
|
||||
cancel-in-progress: ${{ github.ref != 'refs/heads/main' && !startsWith(github.ref, 'refs/tags/') && !(github.event_name == 'workflow_dispatch' && inputs.publish == 'true') }}
|
||||
|
||||
env:
|
||||
REGISTRY: ghcr.io
|
||||
|
||||
@@ -3,8 +3,37 @@ name: Nix
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
# Prove the real Nix package and daemon smoke before merge when Nix, CLI,
|
||||
# server, or daemon packaging inputs change.
|
||||
pull_request:
|
||||
paths:
|
||||
- "nix/**"
|
||||
- "flake.nix"
|
||||
- "flake.lock"
|
||||
- "package.json"
|
||||
- "package-lock.json"
|
||||
- "packages/protocol/**"
|
||||
- "packages/client/**"
|
||||
- "packages/highlight/**"
|
||||
- "packages/plugin/**"
|
||||
- "packages/server/**"
|
||||
- "packages/relay/**"
|
||||
- "packages/cli/**"
|
||||
- "packages/desktop/**"
|
||||
- "plugins/**"
|
||||
- "skills/**"
|
||||
- "scripts/trace-daemon.mjs"
|
||||
- "scripts/is-main-module.mjs"
|
||||
- "scripts/build-daemon-web-ui.mjs"
|
||||
- "scripts/update-nix.sh"
|
||||
- "scripts/fix-lockfile.mjs"
|
||||
- ".github/workflows/nix.yml"
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: nix-${{ github.ref }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
@@ -102,6 +131,7 @@ jobs:
|
||||
run: nix build .#desktop -o result-desktop
|
||||
|
||||
build-desktop-darwin:
|
||||
if: ${{ github.event_name != 'pull_request' }}
|
||||
runs-on: macos-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
@@ -99,5 +99,3 @@ app.json
|
||||
|
||||
# Project-local Serena configuration and memories.
|
||||
.serena/
|
||||
|
||||
!packages/app/gpui/app.json
|
||||
|
||||
+18
-11
@@ -198,17 +198,24 @@ outstanding intent. A crash after successful dispatch but before removal commits
|
||||
notification. Clean shutdown can also flush an already queued callback while retaining its intent,
|
||||
so that callback can repeat after restart. This is an at-least-once wakeup, without turn attribution or exactly-once delivery.
|
||||
|
||||
A turn end is not always a settled child. When the child ends its turn with work that will start its
|
||||
next turn by itself, the caller gets one `message` notice ("ended its turn but is still working") and
|
||||
the subscription keeps following the child. That work is a running turn, queued messages, a pending
|
||||
provider wake-up (`AgentSession.hasPendingWakeup`: Claude background tasks, task notifications, and
|
||||
one-shot wake-ups), or the child's own outstanding finish subscriptions as a caller. Heartbeats,
|
||||
recurring crons, change-request watches, and other daemon background items never count: they are
|
||||
external triggers, not work the caller is waiting for. While following, turn ends and work changes stay
|
||||
silent until nothing is pending, which sends `finished` and removes the subscription. `followingSince`
|
||||
is stored before the notice is sent, so restarts resume following without repeating it, and following
|
||||
ends after 24 hours with an "is still working" notice. Remote children and providers without the probe
|
||||
report their first turn end as `finished`.
|
||||
A turn end is not always a settled child. A child can end its turn with work that will start its next
|
||||
turn by itself: a running turn, queued messages, a pending provider wake-up
|
||||
(`AgentSession.hasPendingWakeup`: Claude background tasks, task notifications, and one-shot
|
||||
wake-ups), or the child's own outstanding finish subscriptions as a caller. Heartbeats, recurring
|
||||
crons, change-request watches, and other daemon background items never count: they are external
|
||||
triggers, not work the caller is waiting for.
|
||||
|
||||
Every turn end reports `finished` at once. When work is still pending, the notice names it and the
|
||||
subscription follows the child: each later turn end reports `finished` again, and the child settling
|
||||
with nothing pending sends a final `finished` and removes the subscription, even when the work
|
||||
drains without another turn. Reporting at once keeps a long-lived task, such as a dev server, from
|
||||
leaving the caller without the child's reply. Following is what lets the caller hear the reply a
|
||||
background task wakes up later ([#6346](https://github.com/getpaseo/paseo/issues/6346)). A work change
|
||||
that leaves work pending sends nothing. Errors, permission requests, and closes report as they
|
||||
happen. `followingSince` is stored when following starts, so a restart keeps following instead of
|
||||
waiting for another turn end. After 24 hours of following, the caller gets a final `finished` with
|
||||
the child's last reply and the subscription ends. Remote children and providers without the probe
|
||||
report their first turn end as a settled `finished`.
|
||||
|
||||
Permission requests are notification checkpoints, not the end of that subscription. The caller is notified again after a permission response when the child finishes, errors, or requests another permission.
|
||||
The permission notification includes the normalized request plus the child and request IDs, so the caller can inspect it and respond without fetching agent status.
|
||||
|
||||
@@ -329,7 +329,7 @@ messages or transfers.
|
||||
### Compatibility rules
|
||||
|
||||
- WebSocket schemas are append-only. Add fields, do not remove fields, and never make optional fields required.
|
||||
- New wire enum values must be gated at serialization with `session.supports(CLIENT_CAPS.someCapability)`.
|
||||
- New wire enum values must be gated at serialization with `session.supports(CLIENT_CAPS.someCapability)`. An older reader skips an unknown value inside a list; gate it anyway when the old client must see something.
|
||||
- Capabilities belong to the physical source socket. `session.supports(...)` reads the requesting or observing source at the domain projection boundary; one socket must not borrow a sibling's capabilities.
|
||||
|
||||
Example: adding a new enum value
|
||||
@@ -337,7 +337,7 @@ Example: adding a new enum value
|
||||
```ts
|
||||
// 1. Add CLIENT_CAPS.newThing = "new_thing"
|
||||
// 2. Let new clients advertise it in WS hello
|
||||
// 3. Keep the shared producer schema strict
|
||||
// 3. Add the value to the shared schema; no catch-all branch
|
||||
// 4. Gate the new emitted value: session.supports(CLIENT_CAPS.newThing) ? "new_value" : "old_value"
|
||||
```
|
||||
|
||||
|
||||
@@ -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
@@ -205,10 +205,9 @@ docker build \
|
||||
.
|
||||
```
|
||||
|
||||
The Docker workflow builds the image on pull requests and on `main` as a
|
||||
non-publishing check. Stable `vX.Y.Z` tag pushes publish
|
||||
`ghcr.io/getpaseo/paseo:X.Y.Z` and `ghcr.io/getpaseo/paseo:latest`. Beta tags
|
||||
publish only the exact prerelease tag, such as
|
||||
The Docker workflow builds the image on `main` as a non-publishing check.
|
||||
Stable `vX.Y.Z` tag pushes publish `ghcr.io/getpaseo/paseo:X.Y.Z` and
|
||||
`ghcr.io/getpaseo/paseo:latest`. Beta tags publish only the exact prerelease tag, such as
|
||||
`ghcr.io/getpaseo/paseo:0.1.102-beta.1`, and do not update `latest`.
|
||||
|
||||
To replace a Docker image in place without rebuilding desktop, APK, or EAS
|
||||
|
||||
+21
-5
@@ -301,9 +301,10 @@ translation scope is React context and does not cross it (Gotcha 7). It returns:
|
||||
height with it; never animate height per frame.
|
||||
|
||||
Do not measure an anchor with `measureInWindow` and correct it by the keyboard
|
||||
shift. On iOS the translate view uses the native driver, and `measureInWindow`
|
||||
includes its transform only when the view happened to re-render since the
|
||||
keyboard moved. Both results were observed, so any correction double-lifts the
|
||||
shift. On iOS the translate view uses the native driver, which moves the view
|
||||
without updating the shadow tree. The translate view commits the resting lift to
|
||||
the shadow tree once the keyboard settles, so `measureInWindow` includes the lift
|
||||
at rest and misses it while the keyboard moves. Any correction double-lifts the
|
||||
popover or leaves it behind the keyboard. `measureAtRest` measures through
|
||||
Fabric's transform-free `measureLayout` instead. Re-measure when `isMoving`
|
||||
settles; the composer's resting position changes as the draft grows.
|
||||
@@ -315,8 +316,8 @@ the anchor's rect against the layer and commits the placement with `flushSync`,
|
||||
which runs after layout and before paint. On native a Reanimated frame callback
|
||||
reads only the anchor's height on the UI thread and holds its bottom edge at
|
||||
the rest measurement. A height carries no transform. On iOS the absolute
|
||||
position does not reliably include one: the keyboard lift runs on the native
|
||||
driver and reaches the shadow tree only when the view re-renders. The
|
||||
position does not include one while the keyboard moves: the lift runs on the
|
||||
native driver and reaches the shadow tree only at rest. The
|
||||
fixed-bottom model is wrong for the centered New workspace composer on tablets,
|
||||
which grows around its middle, and for width or x changes. The popover is off
|
||||
there by half the growth, or by the old width, until the next rest measurement.
|
||||
@@ -324,6 +325,21 @@ Keep the portal's `KeyboardTranslateView` host-sized with
|
||||
`pointerEvents="box-none"` and position the popover inside it, so the popover
|
||||
moves without leaving its parent's bounds (Gotcha 1).
|
||||
|
||||
The resting commit also keeps touches working. Pressability measures a
|
||||
`Pressable`'s press region in the shadow tree. If the region stays at the
|
||||
unlifted position, a tap that drifts a few points leaves it and the press is
|
||||
dropped. This hit every control in the dock: Send, attach, and the model selector.
|
||||
|
||||
`Combobox` positions its native popover with floating-ui against the window, and
|
||||
the software keyboard covers part of the window. It adds the settled keyboard
|
||||
height (`useSettledKeyboardHeight`) to its bottom collision padding. The height
|
||||
changes on `keyboardDidShow` and `keyboardDidHide`, at the end of the move. The new
|
||||
padding re-measures the anchor on the next frame, when the resting lift is in the
|
||||
shadow tree, so the popover follows an anchor that rides the keyboard.
|
||||
Opening the model picker moves focus to its search input, and the keyboard hides
|
||||
and shows again on the way. A height that changes at `keyboardWillShow` instead
|
||||
measures the trigger before it lifts and leaves the popover over the keyboard.
|
||||
|
||||
The provider also reconciles iOS from the controller's native `onEnd` event.
|
||||
The controller's stock iOS shared values update at move start and during an
|
||||
interactive move, but not at the terminal event, so JS contention can otherwise
|
||||
|
||||
@@ -127,7 +127,10 @@ With a Codex draft selected, set `_SCENARIO=growth` on a 402pt-wide iPhone to
|
||||
check live wrapping, shrinking, the 12pt anchor gap, and command insertion. Set
|
||||
`_SCENARIO=previews` on an SE-sized iPhone to check long and short descriptions
|
||||
under an eight-line draft, selection with the keyboard shown and hidden, and
|
||||
file mentions. These scenarios only need `_SERVER_ID` and `_WORKSPACE_ID`;
|
||||
file mentions. Set `_SCENARIO=controls` to tap the attach button and the model
|
||||
selector with a 3pt drag while the keyboard is open, then check that a wide
|
||||
layout's model popover clears both the trigger and the keyboard. Run it on an
|
||||
iPhone and on the iPhone Duo unfolded. These scenarios only need `_SERVER_ID` and `_WORKSPACE_ID`;
|
||||
`_UDID` selects an exact simulator and `_ARTIFACTS_DIR` overrides the output path.
|
||||
|
||||
The Android sidebar scroll-retention flow requires a connected host with enough
|
||||
|
||||
@@ -639,6 +639,12 @@ effective configuration and execution environment, or
|
||||
`undefined` for target-specific caching. Ignore `force` when choosing identity. Existing providers
|
||||
need no change. See [catalogue ownership](providers.md#provider-snapshot-refresh-contract).
|
||||
|
||||
Both sides of the provider protocol ignore fields they do not know. A list element of an unknown
|
||||
kind, such as a prompt content block, a command kind, or a timeline item, is dropped and the rest of
|
||||
the input or event is kept. The daemon drops an event of a kind it does not know and keeps the
|
||||
connection open. Paseo supplies the SDK at runtime, so both sides read with the daemon's parser. An
|
||||
input the provider must act on still needs a connection capability, as `session.launch_wrap` does.
|
||||
|
||||
`send()` resolves after acceptance. Publish operation completion, prompt disposition, turn state,
|
||||
configuration, permissions, persistence, and complete timeline snapshots through `onEvent()`.
|
||||
Route messages, structured commands, steering, and command side effects through `session.prompt`.
|
||||
|
||||
@@ -17,6 +17,9 @@ A schema change must not break parsing in either direction. An old app still par
|
||||
- A field you stop sending stays accepted. You stop writing it, you don't stop reading it.
|
||||
- Wire schemas are pure structural declarations. No `.transform()`, `.catch()`, or `.preprocess()` on WebSocket message schemas — normalization happens in an explicit pass after validation. The reason is in [protocol-validation.md](protocol-validation.md): inbound validators are generated, and the generator only compiles pure schemas.
|
||||
- Plain `z.union()` is forbidden when every branch shares a literal tag. Use `z.discriminatedUnion()`.
|
||||
- Wire objects ignore keys they do not know. Never put `.strict()` or `z.strictObject` on a schema that reads another process's data. `packages/protocol/tests/validation/evolvability.test.ts` audits every app↔daemon schema. Strict objects belong to local files that should reject typos, such as the `config.json` copies in `packages/server/src/server/persisted-config.ts`. The browser automation request is the one wire exception: it rejects legacy tab targeting so a request cannot run against the wrong tab.
|
||||
- An unknown variant inside a list costs one element. Readers parse through `safeParseSkippingUnknownVariants` (`packages/protocol/src/validation/unknown-variants.ts`): an unrecognized tag or enum value inside an array drops that element and keeps the message. Outside an array the read fails with `unknownVariant: true` and the reader drops that one message. Schemas stay closed, so consumer `switch`es stay exhaustive. Pruning reaches a list only through objects, arrays, and discriminated unions; a list under a plain `z.union()` branch or a record value is not pruned.
|
||||
- Skipping is not support. When an old reader must see something for the feature to make sense, gate the new value at serialization ([architecture](architecture.md#compatibility-rules)).
|
||||
- `.default()` belongs on primitive leaves only, never on item schemas inside large arrays or big inbound containers.
|
||||
|
||||
Two questions to ask before you commit a schema change:
|
||||
|
||||
@@ -6,7 +6,7 @@ The reason is mobile performance. A captured 353 KB provider snapshot cost about
|
||||
|
||||
## Runtime Path
|
||||
|
||||
`packages/protocol/src/validation/ws-outbound.ts` is the shipped boundary. It validates the envelope with a generated validator that checks only each session message's `type` tag, then runs the generated validator for that one message type and returns the validated data. Issue paths from the message validator, including nested union branches, are prefixed with `message`, so callers see the same issues as when one validator covered the whole envelope. It does not normalize, repair, or re-validate the generated result.
|
||||
`packages/protocol/src/validation/ws-outbound.ts` is the shipped boundary. It validates the envelope with a generated validator that checks only each session message's `type` tag, then runs the generated validator for that one message type and returns the validated data. Issue paths from the message validator, including nested union branches, are prefixed with `message`, so callers see the same issues as when one validator covered the whole envelope. It does not normalize or repair the generated result. When the only failures are unknown variants inside lists, the boundary removes those elements and validates once more ([protocol-compatibility](protocol-compatibility.md#the-protocol-contract-always-compatible)). The reader classifies failures from the issue list, so it behaves the same over the generated validator and Zod, and a valid message pays nothing extra.
|
||||
|
||||
Keep one generated function per message type. zod-aot inlines every nested schema into the function it compiles, so compiling `WSOutboundMessageSchema` as a whole produced one 11 MB function. On V8 (daemon clients, plugin hosts, the CLI, and Electron), the Maglev tier compiled that function once it was hot, allocating about 800 MB and stalling for seconds, and compiled it again after each deoptimization. Hermes has no JIT, so mobile never showed it. `packages/protocol/tests/validation/ws-outbound.test.ts` fails if a generated function grows past 1 MB.
|
||||
|
||||
|
||||
+4
-3
@@ -118,8 +118,9 @@ An explicit user instruction can select another base.
|
||||
`chore(release): cut <version>` without a tag.
|
||||
5. Push the release branch (`git push -u origin HEAD`). Pushing any `release/**` branch triggers
|
||||
`CI` (all 21 jobs) and `Desktop Packages` (Linux user-namespace smoke) in their own concurrency
|
||||
groups, isolated from `main` traffic. Never wait on `main` CI, because `main` cancels in-progress
|
||||
runs on every merge. Wait for both runs on the release branch commit to pass before shipping.
|
||||
groups, isolated from `main` traffic. Never wait on `main` CI, because `main` runs queue behind
|
||||
each other and a newer merge replaces the pending one.
|
||||
Wait for both runs on the release branch commit to pass before shipping.
|
||||
Complete the [pre-release dependency checks](#pre-release-dependency-checks) on that commit.
|
||||
Pushing a `release/**` branch without a `v*` tag triggers no publish workflows.
|
||||
6. After go-ahead, push the tag first with `npm run release:push` so remote builds start right away.
|
||||
@@ -278,7 +279,7 @@ The tag push triggers `Desktop Release`, `Android APK Release`, `Docker`, `Relea
|
||||
|
||||
Confirm that `npm view @getpaseo/cli dist-tags` shows `latest` at the shipped version, and `beta` at the shipped version or an active newer beta, before considering the stable release complete.
|
||||
|
||||
The Docker workflow builds images from the checked-out source tree on `main` as non-publishing checks (cancelling superseded `main` runs). Stable `vX.Y.Z` tag pushes publish `ghcr.io/getpaseo/paseo:X.Y.Z` and `ghcr.io/getpaseo/paseo:latest`; beta `vX.Y.Z-beta.N` tag pushes publish only `ghcr.io/getpaseo/paseo:X.Y.Z-beta.N` and never move `latest`.
|
||||
The Docker workflow builds images from the checked-out source tree on `main` as non-publishing checks (a running check finishes, and a newer merge replaces the pending one). Stable `vX.Y.Z` tag pushes publish `ghcr.io/getpaseo/paseo:X.Y.Z` and `ghcr.io/getpaseo/paseo:latest`; beta `vX.Y.Z-beta.N` tag pushes publish only `ghcr.io/getpaseo/paseo:X.Y.Z-beta.N` and never move `latest`.
|
||||
|
||||
The production relay is the Elixir service in [getpaseo/paseo-relay](https://github.com/getpaseo/paseo-relay), with its own deployment process. Paseo releases and pushes to this repository do not deploy it. The Cloudflare relay code and workflow in this repository are legacy and are not used in production.
|
||||
|
||||
|
||||
+1
-1
@@ -200,7 +200,7 @@ Test suites in this repo are heavy. Running them in bulk freezes the machine, es
|
||||
|
||||
## Pull-request test routing
|
||||
|
||||
PR checks are routed by the behavior each suite proves, using `.github/ci-paths.yml`. A package does not inherit every test suite of its runtime consumers: app changes do not run CLI or Electron-wrapper tests, and protocol changes do not run every package that imports the protocol. Cross-package static compatibility belongs to `typecheck`; full integration coverage runs after merge on main and in manual CI runs.
|
||||
PR checks are routed by the behavior each suite proves, using `.github/ci-paths.yml`. A package does not inherit every test suite of its runtime consumers: app changes do not run CLI or Electron-wrapper tests, and protocol changes do not run every package that imports the protocol. The CLI E2E tests are the exception: they drive a real daemon, so changes to the server or built-in plugins run them too. Cross-package static compatibility belongs to `typecheck`; full integration coverage runs after merge on main and in manual CI runs.
|
||||
|
||||
Required matrix legs are declared as statically named jobs. Their shared steps use YAML anchors, while job-level `if` conditions let GitHub report an unaffected leg as genuinely skipped without allocating a runner or losing the exact required-check name.
|
||||
|
||||
|
||||
+24
-8
@@ -330,19 +330,35 @@ that starts or accepts them. Received messages retain sender attribution, while
|
||||
notifications remain visible events. Collapse, timing and locally mounted history share
|
||||
these boundaries.
|
||||
|
||||
Agent-message XML belongs to the daemon's `agent/agent-messages` boundary. Prompt delivery encodes
|
||||
Agent-message markup belongs to the daemon's `agent/agent-messages` boundary. Prompt delivery encodes
|
||||
provenance; acceptance, provider echoes, import, and replay share its projection. The delivery ID is
|
||||
also the projected call ID, so a provider echo cannot create a second row. Sender IDs are opaque and
|
||||
do not imply local ownership or authorization. Capture the sender title at delivery: archived or
|
||||
removed senders must remain understandable without a live directory lookup.
|
||||
|
||||
The optional `agentMessage` payload carries event, sender, and delivered text. Shared client
|
||||
presentation (`protocol/paseo-tool-presentation`) owns its heading and expanded details, next to the
|
||||
labels for every Paseo MCP tool. The daemon
|
||||
must not construct UI labels or prepend sender labels to the semantic message body. The existing
|
||||
`tool_call` / `plain_text` envelope is a compatibility adapter: older clients still parse the row and
|
||||
expand its body. New clients use the typed payload, never infer the event from a tool name or parse
|
||||
XML. Stream reduction and disk-cache serialization preserve the payload without rendering it.
|
||||
Each delivered message keeps its text first and ends with a `<paseo-message … length="N"/>` marker.
|
||||
Text at character 0 stays the sender's, so a provider still reads a slash command there, and bodies
|
||||
are never escaped. `length` bounds the text before the marker, so marker syntax inside a body cannot
|
||||
split it, and a batch splits back into rows by reading markers from the end. A person's prompt gets a
|
||||
marker only when it shares a provider turn with other deliveries or contains `<paseo-message` or
|
||||
`<paseo-system`. Transcripts written before markers open with a `<paseo-system>` envelope; the
|
||||
projection still reads those (`COMPAT(leadingPaseoSystemEnvelope)`).
|
||||
|
||||
The daemon decides whether a delivery is a message or a tool call, and clients render what it sends:
|
||||
|
||||
- A person's text is a `user_message`.
|
||||
- A peer message is an `agent_message` tool call whose `agentMessage` carries sender and text. The
|
||||
wire has no sender on `user_message`, so clients present it as a "Sent by" bubble.
|
||||
- Lifecycle notifications (`agent_finished`, `agent_errored`, `agent_needs_permission`,
|
||||
`agent_closed`), schedule fires (`heartbeat`), and change-request updates
|
||||
are plain tool calls. `plain_text` detail carries the sender in `label`, the body in `text`, and
|
||||
the icon. Clients render the heading from the tool name, so no notification event reaches them.
|
||||
|
||||
`isTimelineTurnTrigger` (`packages/protocol/src/timeline-turn.ts`) lists the delivered tool names that
|
||||
start a turn. Add a name there when the daemon projects a new delivery. Rows that older daemons stored
|
||||
with notification `agentMessage` metadata are rewritten to the plain call at presentation
|
||||
(`COMPAT(agentNotificationMetadata)`). Stream reduction and disk-cache serialization preserve the
|
||||
payload without rendering it.
|
||||
|
||||
The compatibility boundary for older daemons is snapshot normalization: running/idle status becomes an
|
||||
anonymous active turn or idle state once, and downstream code consumes the same activity shape. The app
|
||||
|
||||
@@ -73,6 +73,17 @@
|
||||
"entry": ["src/index.ts", "src/**/*.test.ts"],
|
||||
"project": ["src/**/*.ts"]
|
||||
},
|
||||
"packages/workflows": {
|
||||
"entry": [
|
||||
"src/index.ts",
|
||||
"src/ir.ts",
|
||||
"src/dsl.ts",
|
||||
"src/yaml.ts",
|
||||
"src/testing.ts",
|
||||
"test/**/*.test.ts"
|
||||
],
|
||||
"project": ["src/**/*.ts", "test/**/*.ts"]
|
||||
},
|
||||
"packages/expo-two-way-audio": {
|
||||
"entry": ["src/index.ts"],
|
||||
"project": ["src/**/*.ts"]
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
sha256-aal9eR571blWuL7CZt1LR+KfA4QPJ0ivVl/GSTWy93o=
|
||||
sha256-34bUBmRmjekbUSp93597GLTmSWKt23TCHaK3ViXG+iU=
|
||||
|
||||
Generated
+20
-3
@@ -16,6 +16,7 @@
|
||||
"packages/highlight",
|
||||
"packages/plugin",
|
||||
"packages/protocol",
|
||||
"packages/workflows",
|
||||
"packages/client",
|
||||
"packages/server",
|
||||
"packages/app",
|
||||
@@ -6709,6 +6710,10 @@
|
||||
"resolved": "packages/website",
|
||||
"link": true
|
||||
},
|
||||
"node_modules/@getpaseo/workflows": {
|
||||
"resolved": "packages/workflows",
|
||||
"link": true
|
||||
},
|
||||
"node_modules/@gorhom/bottom-sheet": {
|
||||
"version": "5.2.14",
|
||||
"resolved": "https://registry.npmjs.org/@gorhom/bottom-sheet/-/bottom-sheet-5.2.14.tgz",
|
||||
@@ -14924,7 +14929,6 @@
|
||||
"version": "8.11.0",
|
||||
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.11.0.tgz",
|
||||
"integrity": "sha512-wGgprdCvMalC0BztXvitD2hC04YffAvtsUn93JbGXYLAtCUO4xd17mCCZQxUOItiBwZvJScWo8NIvQMQ71rdpg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^3.1.1",
|
||||
@@ -31398,7 +31402,6 @@
|
||||
"version": "2.3.1",
|
||||
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
|
||||
"integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
@@ -36228,7 +36231,6 @@
|
||||
"version": "4.4.1",
|
||||
"resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz",
|
||||
"integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==",
|
||||
"dev": true,
|
||||
"license": "BSD-2-Clause",
|
||||
"dependencies": {
|
||||
"punycode": "^2.1.0"
|
||||
@@ -43159,6 +43161,21 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"packages/workflows": {
|
||||
"name": "@getpaseo/workflows",
|
||||
"version": "0.1.0",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"ajv": "^8.11.0",
|
||||
"js-yaml": "^4.1.1",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.9.0",
|
||||
"typescript": "^5.9.3",
|
||||
"vitest": "^4.1.6"
|
||||
}
|
||||
},
|
||||
"plugins": {
|
||||
"name": "@getpaseo/builtin-plugins",
|
||||
"version": "0.18.1",
|
||||
|
||||
+4
-5
@@ -27,6 +27,7 @@
|
||||
"packages/highlight",
|
||||
"packages/plugin",
|
||||
"packages/protocol",
|
||||
"packages/workflows",
|
||||
"packages/client",
|
||||
"packages/server",
|
||||
"packages/app",
|
||||
@@ -60,6 +61,8 @@
|
||||
"build:relay:clean": "npm run build:clean --workspace=@getpaseo/relay",
|
||||
"build:protocol": "npm run build --workspace=@getpaseo/protocol",
|
||||
"build:protocol:clean": "npm run build:clean --workspace=@getpaseo/protocol",
|
||||
"build:workflows": "npm run build --workspace=@getpaseo/workflows",
|
||||
"build:workflows:clean": "npm run build:clean --workspace=@getpaseo/workflows",
|
||||
"build:client": "npm run build --workspace=@getpaseo/client",
|
||||
"build:client:clean": "npm run build:protocol:clean && npm run build:clean --workspace=@getpaseo/client",
|
||||
"build:server-deps": "npm run build:client && concurrently --kill-others-on-fail --names highlight,plugin,relay --prefix-colors yellow,green,blue \"npm run build:highlight\" \"npm run build:plugin\" \"npm run build:relay\"",
|
||||
@@ -126,11 +129,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,16 @@ test.describe("Agent profiles in the model picker", () => {
|
||||
await expectComposerMode(page, "Load test");
|
||||
});
|
||||
|
||||
await test.step("the sole provider opens directly", async () => {
|
||||
await test.step("the single-provider picker lists Profiles above the agent's models without a rail", async () => {
|
||||
await openModelPicker(page);
|
||||
await expect(page.getByTestId("model-search-input").first()).toBeVisible();
|
||||
await expect(page.getByTestId("sheet-header-back")).toHaveCount(0);
|
||||
await expect(page.locator('[data-testid^="model-provider-"]')).toHaveCount(0);
|
||||
await expectProfileVisibleForProvider(page, {
|
||||
await expect(page.getByTestId("model-search-input").first()).toBeFocused();
|
||||
await expect(page.getByTestId("model-picker-rail")).toHaveCount(0);
|
||||
await expectModelRowSelected(page, { provider: "mock", modelId: "ten-second-stream" });
|
||||
await expectPickerProfile(page, {
|
||||
name: PROFILE.name,
|
||||
summary: PROFILE_SUMMARY,
|
||||
});
|
||||
await expectProfileEditIsPencilOnly(page);
|
||||
await expectProfileEditTooltip(page);
|
||||
await expectProfilesEditLink(page);
|
||||
});
|
||||
|
||||
await test.step("applying it writes its model and mode into the composer", async () => {
|
||||
@@ -115,14 +113,13 @@ test.describe("Agent profiles in the model picker", () => {
|
||||
await expectComposerDoesNotName(page, PROFILE.name);
|
||||
});
|
||||
|
||||
await test.step("reopening returns directly to the provider models", async () => {
|
||||
await test.step("reopening returns to the provider models with the new model checked", async () => {
|
||||
await openModelPicker(page);
|
||||
await expect(page.getByTestId("model-search-input").first()).toBeVisible();
|
||||
await expectProfileVisibleForProvider(page, {
|
||||
await expectModelRowSelected(page, { provider: "mock", modelId: "one-minute-stream" });
|
||||
await expectPickerProfile(page, {
|
||||
name: PROFILE.name,
|
||||
summary: PROFILE_SUMMARY,
|
||||
});
|
||||
await expectModelRowSelected(page, { provider: "mock", modelId: "one-minute-stream" });
|
||||
await closeModelPicker(page);
|
||||
});
|
||||
} finally {
|
||||
|
||||
@@ -0,0 +1,559 @@
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import { connectDaemonClient } from "../support/helpers/daemon-client-loader";
|
||||
import {
|
||||
beginTextReveal,
|
||||
retargetTextReveal,
|
||||
visibleRevealedText,
|
||||
} from "../../src/agent-stream/text-reveal";
|
||||
import type { Page } from "@playwright/test";
|
||||
import { test, expect } from "../support/fixtures";
|
||||
import { expectComposerVisible } from "../support/helpers/composer";
|
||||
import { scrollChatAwayFromBottom } from "../support/helpers/agent-bottom-anchor";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
|
||||
test.use({
|
||||
e2eDaemonConfig: {
|
||||
version: 1,
|
||||
agents: {
|
||||
providers: Object.fromEntries(
|
||||
[
|
||||
"claude",
|
||||
"codex",
|
||||
"copilot",
|
||||
"opencode",
|
||||
"pi",
|
||||
"omp",
|
||||
"antigravity",
|
||||
"hoplite",
|
||||
"muse",
|
||||
].map((id) => [id, { enabled: false }]),
|
||||
),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
interface ClosingFenceFrameSample {
|
||||
text: string;
|
||||
codeBlockHeights: number[];
|
||||
codeBlockTexts: string[];
|
||||
messageHeights: number[];
|
||||
partialFenceLines: string[];
|
||||
}
|
||||
|
||||
interface ClosingFenceFrameReport {
|
||||
finished: boolean;
|
||||
samples: ClosingFenceFrameSample[];
|
||||
}
|
||||
|
||||
async function sampleClosingFenceFrames(page: Page): Promise<ClosingFenceFrameReport> {
|
||||
return await page.evaluate(async () => {
|
||||
const samples: ClosingFenceFrameSample[] = [];
|
||||
let finished = false;
|
||||
|
||||
await new Promise<void>((resolve) => {
|
||||
const tick = () => {
|
||||
const messages = Array.from(
|
||||
document.querySelectorAll<HTMLElement>('[data-testid="assistant-message"]'),
|
||||
);
|
||||
const text = messages.map((message) => message.textContent ?? "").join("");
|
||||
const sample: ClosingFenceFrameSample = {
|
||||
text,
|
||||
codeBlockHeights: [],
|
||||
codeBlockTexts: [],
|
||||
messageHeights: messages.map((message) =>
|
||||
Math.round(message.getBoundingClientRect().height),
|
||||
),
|
||||
partialFenceLines: [],
|
||||
};
|
||||
|
||||
for (const message of messages) {
|
||||
for (const block of message.querySelectorAll<HTMLElement>(
|
||||
'pre, [data-paseo-markdown-tag="pre"]',
|
||||
)) {
|
||||
const code = block.querySelector<HTMLElement>('code, [data-paseo-markdown-tag="code"]');
|
||||
const codeText = code?.textContent ?? block.textContent ?? "";
|
||||
sample.codeBlockTexts.push(codeText.trimEnd());
|
||||
// Opening fence prefixes render as prose; closing artifacts live inside code blocks.
|
||||
for (const line of codeText.split(/\r?\n/)) {
|
||||
if (/^\s*`{1,2}\s*$/.test(line)) sample.partialFenceLines.push(line);
|
||||
}
|
||||
sample.codeBlockHeights.push(Math.round(block.getBoundingClientRect().height));
|
||||
}
|
||||
}
|
||||
|
||||
samples.push(sample);
|
||||
|
||||
finished = text.includes("Both blocks are closed.");
|
||||
if (finished) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
requestAnimationFrame(tick);
|
||||
};
|
||||
requestAnimationFrame(tick);
|
||||
});
|
||||
|
||||
return { finished, samples };
|
||||
});
|
||||
}
|
||||
|
||||
const FIRST_PAUSE_TEXT = "Here is the first snippet:const answer = 42;\nconsole.log(answer);";
|
||||
const SECOND_PAUSE_TEXT = `${FIRST_PAUSE_TEXT}And a second one:echo done`;
|
||||
|
||||
for (const { label, html } of [
|
||||
{ label: "semantic", html: "<pre><code>const answer = 42;\n`\n``</code></pre>" },
|
||||
{
|
||||
label: "annotated",
|
||||
html: '<div data-paseo-markdown-tag="pre"><span data-paseo-markdown-tag="code">const answer = 42;\n`\n``</span><button>Copy</button></div>',
|
||||
},
|
||||
{
|
||||
label: "annotated semantic",
|
||||
html: '<pre data-paseo-markdown-tag="pre"><code data-paseo-markdown-tag="code">const answer = 42;\n`\n``</code></pre>',
|
||||
},
|
||||
]) {
|
||||
test(`samples ${label} code block DOM without duplicate blocks or controls`, async ({ page }) => {
|
||||
await page.setContent(
|
||||
`<div data-testid="assistant-message">${html}<p>Both blocks are closed.</p></div>`,
|
||||
);
|
||||
const report = await sampleClosingFenceFrames(page);
|
||||
const sample = report.samples.at(-1)!;
|
||||
expect(report.finished).toBe(true);
|
||||
expect(sample.codeBlockTexts).toEqual(["const answer = 42;\n`\n``"]);
|
||||
expect(sample.partialFenceLines).toEqual(["`", "``"]);
|
||||
expect(sample.codeBlockHeights).toHaveLength(1);
|
||||
expect(sample.codeBlockHeights[0]).toBeGreaterThan(0);
|
||||
});
|
||||
}
|
||||
|
||||
function closingFencePauseSamples(
|
||||
samples: readonly ClosingFenceFrameSample[],
|
||||
pauseText: string,
|
||||
): ClosingFenceFrameSample[] {
|
||||
return samples.filter((sample) => sample.text === pauseText);
|
||||
}
|
||||
|
||||
function expectStableGeometry(
|
||||
samples: readonly ClosingFenceFrameSample[],
|
||||
expectedCodeBlockTexts: readonly string[],
|
||||
): void {
|
||||
expect(samples.length, "the paused text state should be sampled").toBeGreaterThan(0);
|
||||
expect(
|
||||
samples.every(
|
||||
(sample) => JSON.stringify(sample.codeBlockTexts) === JSON.stringify(expectedCodeBlockTexts),
|
||||
),
|
||||
"the sampled code should contain only the authored lines",
|
||||
).toBe(true);
|
||||
const geometries = new Set(
|
||||
samples.map((sample) => JSON.stringify([sample.messageHeights, sample.codeBlockHeights])),
|
||||
);
|
||||
expect(
|
||||
geometries.size,
|
||||
"message and code block geometry should stay fixed during the pause",
|
||||
).toBe(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* A closing fence that is still being typed must not be painted as code.
|
||||
*
|
||||
* The mock reply closes each code block in two arrivals: one backtick, a pause,
|
||||
* then the other two. Painted, that first backtick is a line of code that
|
||||
* vanishes when the fence completes, so the block grows and shrinks and every
|
||||
* row below it moves twice. Each pause is sampled and its text geometry checked.
|
||||
*/
|
||||
test("does not paint a closing fence while it is still being typed", async ({ page }, testInfo) => {
|
||||
test.setTimeout(90_000);
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "closing-fence-",
|
||||
title: "Closing fence",
|
||||
model: "e2e-fast-stream",
|
||||
});
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
const reportPromise = sampleClosingFenceFrames(page);
|
||||
await agent.client.sendAgentMessage(
|
||||
agent.agentId,
|
||||
"Stream a code block with a split closing fence.",
|
||||
);
|
||||
const report = await reportPromise;
|
||||
|
||||
await testInfo.attach("closing-fence-frames", {
|
||||
body: JSON.stringify(report, null, 2),
|
||||
contentType: "application/json",
|
||||
});
|
||||
expect(report.finished, "the reply should finish streaming").toBe(true);
|
||||
expect(
|
||||
report.samples.flatMap((sample) => sample.partialFenceLines),
|
||||
"no frame, including transitions outside the pause windows, may show a partial fence inside code",
|
||||
).toEqual([]);
|
||||
const firstPauseSamples = closingFencePauseSamples(report.samples, FIRST_PAUSE_TEXT);
|
||||
const secondPauseSamples = closingFencePauseSamples(report.samples, SECOND_PAUSE_TEXT);
|
||||
expectStableGeometry(firstPauseSamples, ["const answer = 42;\nconsole.log(answer);"]);
|
||||
expectStableGeometry(secondPauseSamples, [
|
||||
"const answer = 42;\nconsole.log(answer);",
|
||||
"echo done",
|
||||
]);
|
||||
expect(secondPauseSamples[0]?.codeBlockHeights[0]).toBe(
|
||||
firstPauseSamples[0]?.codeBlockHeights[0],
|
||||
);
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("excludes each revealed character of the next paragraph from both pauses", () => {
|
||||
for (const [pauseText, paragraph] of [
|
||||
[FIRST_PAUSE_TEXT, "And a second one:"],
|
||||
[SECOND_PAUSE_TEXT, "Both blocks are closed."],
|
||||
]) {
|
||||
const state = retargetTextReveal(beginTextReveal(pauseText), pauseText + paragraph);
|
||||
const samples = Array.from({ length: paragraph.length + 1 }, (_, index) => ({
|
||||
text: visibleRevealedText({ ...state, revealed: pauseText.length + index }),
|
||||
codeBlockHeights: [],
|
||||
codeBlockTexts: [],
|
||||
messageHeights: [index],
|
||||
partialFenceLines: [],
|
||||
}));
|
||||
expect(closingFencePauseSamples(samples, pauseText)).toEqual([samples[0]]);
|
||||
}
|
||||
});
|
||||
|
||||
for (const { label, markdown, expectedCode, expectedPartialFenceLines } of [
|
||||
{
|
||||
label: "opening prefixes in prose",
|
||||
markdown: "And a second one:\n\n`\n\n``\n\nBoth blocks are closed.",
|
||||
expectedCode: [],
|
||||
expectedPartialFenceLines: [],
|
||||
},
|
||||
{
|
||||
label: "partial fences inside rendered code",
|
||||
markdown: "```ts\nconst answer = 42;\n`\n``\n```\n\nBoth blocks are closed.",
|
||||
expectedCode: ["const answer = 42;\n`\n``"],
|
||||
expectedPartialFenceLines: ["`", "``"],
|
||||
},
|
||||
]) {
|
||||
test(`samples ${label} in the correct container`, async ({ page }, testInfo) => {
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "fence-sample-container-",
|
||||
title: "Fence sample container",
|
||||
featureValues: { mockAssistantResponse: markdown },
|
||||
});
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
const reportPromise = sampleClosingFenceFrames(page);
|
||||
await agent.client.sendAgentMessage(agent.agentId, "Show the fence sampling fixture.");
|
||||
const report = await reportPromise;
|
||||
await testInfo.attach("fence-container-frames", {
|
||||
body: JSON.stringify(report, null, 2),
|
||||
contentType: "application/json",
|
||||
});
|
||||
expect(report.finished).toBe(true);
|
||||
const messageText = await page.getByTestId("assistant-message").innerText();
|
||||
const messageLines = messageText.split(/\r?\n/);
|
||||
const messageFenceLines = messageLines.filter((line) => /^\s*`{1,2}\s*$/.test(line));
|
||||
expect(messageFenceLines).toEqual(["`", "``"]);
|
||||
const finalSample = report.samples.at(-1);
|
||||
expect(finalSample?.codeBlockTexts).toEqual(expectedCode);
|
||||
expect(finalSample?.partialFenceLines).toEqual(expectedPartialFenceLines);
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test("shows the complete reasoning after a streamed turn finishes", async ({ page }, testInfo) => {
|
||||
test.setTimeout(90_000);
|
||||
await page.setViewportSize({ width: 1280, height: 900 });
|
||||
await page.addInitScript(() => {
|
||||
localStorage.setItem(
|
||||
"@paseo:app-settings",
|
||||
JSON.stringify({ toolCallDetailLevel: "detailed", autoExpandReasoning: true }),
|
||||
);
|
||||
});
|
||||
const reasoning =
|
||||
"Need to find the scroll container, the layout effect that watches for new messages, and any gesture handler that might fight with programmatic scrolling. Probably a ref on the FlatList plus a near-bottom threshold.";
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "finished-reasoning-",
|
||||
title: "Finished reasoning",
|
||||
model: "ten-second-stream",
|
||||
});
|
||||
const historyClient = await connectDaemonClient<
|
||||
Pick<DaemonClient, "connect" | "close" | "fetchAgentTimeline">
|
||||
>({ clientIdPrefix: "finished-reasoning-history" });
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
await agent.client.sendAgentMessage(
|
||||
agent.agentId,
|
||||
"Stream briefly to check finished reasoning.",
|
||||
);
|
||||
await agent.client.waitForFinish(agent.agentId, 30_000);
|
||||
const history = await historyClient.fetchAgentTimeline(agent.agentId, { limit: 500 });
|
||||
const thoughts = history.entries
|
||||
.map((entry) => entry.item)
|
||||
.filter((item) => item.type === "reasoning");
|
||||
await testInfo.attach("canonical-reasoning", {
|
||||
body: JSON.stringify(thoughts, null, 2),
|
||||
contentType: "application/json",
|
||||
});
|
||||
expect(thoughts[0]?.text).toBe(reasoning);
|
||||
const expectedCounts = new Map<string, number>();
|
||||
for (const thought of thoughts)
|
||||
expectedCounts.set(thought.text, (expectedCounts.get(thought.text) ?? 0) + 1);
|
||||
const rendered = page.getByText(reasoning, { exact: true });
|
||||
for (const [text, count] of expectedCounts)
|
||||
await expect(page.getByText(text, { exact: true })).toHaveCount(count);
|
||||
await expect(rendered.first()).toBeVisible();
|
||||
await testInfo.attach("finished-reasoning", {
|
||||
body: await page.screenshot(),
|
||||
contentType: "image/png",
|
||||
});
|
||||
await page.reload();
|
||||
for (const [text, count] of expectedCounts)
|
||||
await expect(page.getByText(text, { exact: true })).toHaveCount(count);
|
||||
await expect(rendered.first()).toBeVisible();
|
||||
} catch (error) {
|
||||
await testInfo.attach("reasoning-before-cleanup", {
|
||||
body: await page.screenshot(),
|
||||
contentType: "image/png",
|
||||
});
|
||||
throw error;
|
||||
} finally {
|
||||
await historyClient.close();
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("records equal-input long-reply rendering metrics", async ({ page }, testInfo) => {
|
||||
test.setTimeout(120_000);
|
||||
await page.setViewportSize({ width: 1280, height: 900 });
|
||||
const markdown =
|
||||
Array.from({ length: 15 }, (_, index) =>
|
||||
[
|
||||
"### Block " + index,
|
||||
"",
|
||||
"\x60\x60\x60ts",
|
||||
...Array.from(
|
||||
{ length: 12 },
|
||||
(_value, line) => "const value_" + index + "_" + line + " = " + (index * 12 + line) + ";",
|
||||
),
|
||||
"\x60\x60\x60",
|
||||
"",
|
||||
].join("\n"),
|
||||
).join("\n") + "\nEqual-input stream complete.";
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "equal-input-long-reply-",
|
||||
title: "Equal-input long reply",
|
||||
featureValues: {
|
||||
mockStreamingAssistantResponse: markdown,
|
||||
mockStreamingAssistantIntervalMs: 5,
|
||||
},
|
||||
});
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
const session = await page.context().newCDPSession(page);
|
||||
await session.send("Performance.enable");
|
||||
const before = await session.send("Performance.getMetrics");
|
||||
const sampler = await page.evaluateHandle(() => {
|
||||
const state = {
|
||||
frames: [] as number[],
|
||||
longTasks: [] as number[],
|
||||
running: true,
|
||||
last: performance.now(),
|
||||
};
|
||||
const observer = new PerformanceObserver((list) => {
|
||||
state.longTasks.push(...list.getEntries().map((entry) => entry.duration));
|
||||
});
|
||||
observer.observe({ type: "longtask", buffered: false });
|
||||
const tick = (now: number) => {
|
||||
state.frames.push(now - state.last);
|
||||
state.last = now;
|
||||
if (state.running) requestAnimationFrame(tick);
|
||||
};
|
||||
requestAnimationFrame(tick);
|
||||
return { state, observer };
|
||||
});
|
||||
await agent.client.sendAgentMessage(agent.agentId, "Render the fixed fifteen-block fixture.");
|
||||
await agent.client.waitForFinish(agent.agentId, 60_000);
|
||||
const message = page.getByTestId("assistant-message").last();
|
||||
await expect(message).toContainText("Equal-input stream complete.", { timeout: 30_000 });
|
||||
const blocks = message.locator('pre, [data-paseo-markdown-tag="pre"]');
|
||||
await expect(blocks).toHaveCount(15);
|
||||
for (let index = 0; index < 15; index++) {
|
||||
await expect(blocks.nth(index)).toContainText(
|
||||
"const value_" + index + "_11 = " + (index * 12 + 11) + ";",
|
||||
);
|
||||
}
|
||||
const samples = await sampler.evaluate(({ state, observer }) => {
|
||||
state.running = false;
|
||||
state.longTasks.push(...observer.takeRecords().map((entry) => entry.duration));
|
||||
observer.disconnect();
|
||||
return state;
|
||||
});
|
||||
const after = await session.send("Performance.getMetrics");
|
||||
const frames = [...samples.frames].sort((a, b) => a - b);
|
||||
await testInfo.attach("equal-input-rendering", {
|
||||
body: JSON.stringify(
|
||||
{
|
||||
markdown,
|
||||
viewport: page.viewportSize(),
|
||||
intervalMs: 5,
|
||||
frameCount: frames.length,
|
||||
frameP95Ms: frames[Math.floor(frames.length * 0.95)],
|
||||
maxFrameMs: frames.at(-1),
|
||||
longTasksMs: samples.longTasks,
|
||||
before: before.metrics,
|
||||
after: after.metrics,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
contentType: "application/json",
|
||||
});
|
||||
await sampler.dispose();
|
||||
await session.detach();
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("manually expands complete reasoning after leaving output following", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
test.setTimeout(90_000);
|
||||
await page.setViewportSize({ width: 1280, height: 900 });
|
||||
await page.addInitScript(() => {
|
||||
localStorage.setItem(
|
||||
"@paseo:app-settings",
|
||||
JSON.stringify({ chatDisplay: "full", autoExpandReasoning: false }),
|
||||
);
|
||||
});
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "manual-finished-reasoning-",
|
||||
title: "Manual finished reasoning",
|
||||
model: "ten-second-stream",
|
||||
});
|
||||
const historyClient = await connectDaemonClient<
|
||||
Pick<DaemonClient, "connect" | "close" | "fetchAgentTimeline">
|
||||
>({ clientIdPrefix: "manual-finished-reasoning-history" });
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
await agent.client.sendAgentMessage(
|
||||
agent.agentId,
|
||||
"Stream briefly to check finished reasoning.",
|
||||
);
|
||||
const finished = await agent.client.waitForFinish(agent.agentId, 30_000);
|
||||
expect(finished.status).toBe("idle");
|
||||
await testInfo.attach("manual-completed-turn", {
|
||||
body: JSON.stringify(finished),
|
||||
contentType: "application/json",
|
||||
});
|
||||
const history = await historyClient.fetchAgentTimeline(agent.agentId, { limit: 500 });
|
||||
const thoughts = history.entries
|
||||
.map((entry) => entry.item)
|
||||
.filter((item) => item.type === "reasoning");
|
||||
expect(thoughts.length).toBeGreaterThan(0);
|
||||
expect(thoughts.every((thought) => thought.text.length > 0)).toBe(true);
|
||||
const expectedCounts = new Map<string, number>();
|
||||
for (const thought of thoughts)
|
||||
expectedCounts.set(thought.text, (expectedCounts.get(thought.text) ?? 0) + 1);
|
||||
await testInfo.attach("manual-canonical-reasoning", {
|
||||
body: JSON.stringify(thoughts, null, 2),
|
||||
contentType: "application/json",
|
||||
});
|
||||
const pointerCapture = await page.evaluateHandle(() => {
|
||||
const events: {
|
||||
type: string;
|
||||
timestamp: number;
|
||||
tag: string;
|
||||
label: string;
|
||||
scrollTop: number | null;
|
||||
}[] = [];
|
||||
const observe = (event: Event) => {
|
||||
const target = event.target;
|
||||
if (!(target instanceof HTMLElement)) return;
|
||||
const scroll = document.querySelector<HTMLElement>('[data-testid="agent-chat-scroll"]');
|
||||
events.push({
|
||||
type: event.type,
|
||||
timestamp: event.timeStamp,
|
||||
tag: target.tagName,
|
||||
label: target.textContent?.slice(0, 80) ?? "",
|
||||
scrollTop: scroll?.scrollTop ?? null,
|
||||
});
|
||||
};
|
||||
for (const type of ["pointerdown", "pointerup", "wheel"])
|
||||
document.addEventListener(type, observe, true);
|
||||
return {
|
||||
events,
|
||||
stop: () => {
|
||||
for (const type of ["pointerdown", "pointerup", "wheel"])
|
||||
document.removeEventListener(type, observe, true);
|
||||
},
|
||||
};
|
||||
});
|
||||
const badges = page.getByTestId("tool-call-badge").filter({ hasText: "Thinking" });
|
||||
await expect(badges).toHaveCount(thoughts.length);
|
||||
// Locator scrolling alone leaves output-following armed, so pointer-down can
|
||||
// snap the feed to its tail before pointer-up reaches the Thinking control.
|
||||
await scrollChatAwayFromBottom(page, { deltaY: -600, minDistanceFromBottom: 100 });
|
||||
for (let index = 0; index < thoughts.length; index++) {
|
||||
await badges
|
||||
.nth(index)
|
||||
.getByRole("button", { name: "Thinking", exact: true })
|
||||
.first()
|
||||
.click();
|
||||
await expect(
|
||||
badges.nth(index).getByText(thoughts[index].text, { exact: true }),
|
||||
).toBeVisible();
|
||||
}
|
||||
for (const [text, count] of expectedCounts)
|
||||
await expect(page.getByText(text, { exact: true })).toHaveCount(count);
|
||||
const first = badges.first();
|
||||
await first.getByRole("button", { name: "Thinking", exact: true }).first().click();
|
||||
await expect(first.getByText(thoughts[0].text, { exact: true })).not.toBeVisible();
|
||||
await first.getByRole("button", { name: "Thinking", exact: true }).first().click();
|
||||
await expect(first.getByText(thoughts[0].text, { exact: true })).toBeVisible();
|
||||
for (const [text, count] of expectedCounts)
|
||||
await expect(page.getByText(text, { exact: true })).toHaveCount(count);
|
||||
await testInfo.attach("manual-expanded-reasoning", {
|
||||
body: await page.screenshot(),
|
||||
contentType: "image/png",
|
||||
});
|
||||
const pointerEvents = await pointerCapture.evaluate(({ events, stop }) => {
|
||||
stop();
|
||||
return events;
|
||||
});
|
||||
await pointerCapture.dispose();
|
||||
await testInfo.attach("manual-pointer-events", {
|
||||
body: JSON.stringify(pointerEvents, null, 2),
|
||||
contentType: "application/json",
|
||||
});
|
||||
await page.reload();
|
||||
await expect(badges).toHaveCount(thoughts.length);
|
||||
await scrollChatAwayFromBottom(page, { deltaY: -600, minDistanceFromBottom: 100 });
|
||||
for (let index = 0; index < thoughts.length; index++) {
|
||||
await badges
|
||||
.nth(index)
|
||||
.getByRole("button", { name: "Thinking", exact: true })
|
||||
.first()
|
||||
.click();
|
||||
await expect(
|
||||
badges.nth(index).getByText(thoughts[index].text, { exact: true }),
|
||||
).toBeVisible();
|
||||
}
|
||||
for (const [text, count] of expectedCounts)
|
||||
await expect(page.getByText(text, { exact: true })).toHaveCount(count);
|
||||
} catch (error) {
|
||||
await testInfo.attach("manual-before-cleanup", {
|
||||
body: await page.screenshot(),
|
||||
contentType: "image/png",
|
||||
});
|
||||
throw error;
|
||||
} finally {
|
||||
await historyClient.close();
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
@@ -84,17 +84,14 @@ async function openModelSelector(page: Page) {
|
||||
await expect(page.getByTestId("agent-controls-settings-list")).toBeVisible({ timeout: 10_000 });
|
||||
}
|
||||
|
||||
async function dismissStackedModelPickerWithBackdrop(page: Page) {
|
||||
await page
|
||||
.getByTestId("agent-controls-settings-list")
|
||||
.getByRole("button", { name: /Select model/ })
|
||||
.click();
|
||||
await expect(page.getByTestId("agent-controls-model-browser-sheet")).toBeInViewport();
|
||||
await page.mouse.click(MOBILE_VIEWPORT.width / 2, 24);
|
||||
// In CI, Gorhom retains the dismissed sheet below the viewport.
|
||||
// Dismissal is complete when it leaves the displayed surface.
|
||||
await expect(page.getByTestId("agent-controls-model-browser-sheet")).not.toBeInViewport();
|
||||
await expect(page.getByTestId("agent-controls-model-sheet")).toBeVisible();
|
||||
async function openModelPage(page: Page) {
|
||||
await page.getByTestId("agent-controls-model").click();
|
||||
await expect(page.getByTestId("mobile-model-page")).toBeVisible();
|
||||
await expect(page.getByTestId("agent-controls-settings-list")).toHaveCount(0);
|
||||
}
|
||||
|
||||
async function returnHomeWithBack(page: Page) {
|
||||
await page.getByTestId("sheet-header-back").click();
|
||||
await expect(page.getByTestId("agent-controls-settings-list")).toBeVisible();
|
||||
}
|
||||
|
||||
@@ -113,7 +110,7 @@ async function openAndCloseModelSelectorTwice(page: Page) {
|
||||
}
|
||||
|
||||
test.describe("mobile bottom sheet reopen", () => {
|
||||
test("sheets reopen and model search returns to configuration", async ({ page }) => {
|
||||
test("sheets reopen and a model pick returns to Home", async ({ page }) => {
|
||||
const session = await openMockAgentAtMobileBreakpoint(page);
|
||||
try {
|
||||
await test.step("tab switcher opens, closes, and reopens", async () => {
|
||||
@@ -124,24 +121,28 @@ test.describe("mobile bottom sheet reopen", () => {
|
||||
await openAndCloseModelSelectorTwice(page);
|
||||
});
|
||||
|
||||
await test.step("model search returns to configuration", async () => {
|
||||
await test.step("the Model page swaps in place and Back returns to Home", async () => {
|
||||
await openModelSelector(page);
|
||||
const sheet = page.getByTestId("agent-controls-model-sheet");
|
||||
await openModelPage(page);
|
||||
await returnHomeWithBack(page);
|
||||
await expect(sheet).toBeVisible();
|
||||
});
|
||||
|
||||
await dismissStackedModelPickerWithBackdrop(page);
|
||||
|
||||
await page.getByTestId("model-search-all-input").click();
|
||||
await test.step("a model found by search returns to Home with that model", async () => {
|
||||
await openModelPage(page);
|
||||
const search = page.getByTestId("model-search-all-input");
|
||||
await expect(search).not.toBeFocused();
|
||||
await search.click();
|
||||
await search.fill("Ten second");
|
||||
const model = page.getByRole("button", { name: /^Ten second stream/ });
|
||||
await expect(model).toBeVisible({
|
||||
timeout: 10_000,
|
||||
});
|
||||
await expect(model).toBeVisible({ timeout: 10_000 });
|
||||
|
||||
await model.click();
|
||||
|
||||
await expect(sheet).toBeVisible();
|
||||
await expect(page.getByTestId("agent-controls-model-sheet")).toBeVisible();
|
||||
await expect(page.getByTestId("agent-controls-settings-list")).toBeVisible();
|
||||
await expect(page.getByTestId("agent-controls-model")).toContainText("Ten second stream");
|
||||
await expect(page.getByTestId("agent-controls-model-browser-sheet")).not.toBeInViewport();
|
||||
});
|
||||
} finally {
|
||||
await session.cleanup();
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import {
|
||||
expectBuiltinPluginSettings,
|
||||
openBuiltinPluginSettings,
|
||||
test,
|
||||
} from "../support/helpers/builtin-plugin-settings";
|
||||
|
||||
test("a built-in plugin's settings link opens its screen", async ({
|
||||
page,
|
||||
builtinSettingsHost,
|
||||
}) => {
|
||||
await openBuiltinPluginSettings(page, builtinSettingsHost);
|
||||
await expectBuiltinPluginSettings(page);
|
||||
});
|
||||
@@ -30,7 +30,14 @@ test.use({
|
||||
const ACTIVE_SPEED_COLOR = "rgb(251, 191, 36)";
|
||||
const NORMAL_SPEED_COLOR = "rgb(113, 113, 122)";
|
||||
|
||||
const COMPACT_SPEED_CONTROL = "agent-feature-service_tier";
|
||||
const COMPACT_SPEED_SECTION = `${COMPACT_SPEED_CONTROL}-section`;
|
||||
|
||||
async function openSpeedSelector(page: Page): Promise<void> {
|
||||
const compactSection = page.getByTestId(COMPACT_SPEED_SECTION);
|
||||
if (await compactSection.isVisible().catch(() => false)) {
|
||||
return;
|
||||
}
|
||||
const speed = page.getByRole("button", { name: /^(Select speed|Speed: .+)$/ });
|
||||
const features = page.getByRole("button", { name: "Open agent features", exact: true });
|
||||
const modelSettings = page.getByRole("button", { name: /^Select model \(/ });
|
||||
@@ -39,7 +46,12 @@ async function openSpeedSelector(page: Page): Promise<void> {
|
||||
});
|
||||
if (!(await speed.isVisible())) {
|
||||
if (await features.isVisible()) await features.click();
|
||||
else await modelSettings.click();
|
||||
else {
|
||||
await modelSettings.click();
|
||||
await expect(compactSection).toBeVisible({ timeout: 30_000 });
|
||||
await expect(compactSection.getByText("Normal", { exact: true })).toBeVisible();
|
||||
return;
|
||||
}
|
||||
}
|
||||
await expect(speed).toBeVisible({ timeout: 30_000 });
|
||||
await speed.click();
|
||||
@@ -47,6 +59,13 @@ async function openSpeedSelector(page: Page): Promise<void> {
|
||||
}
|
||||
|
||||
async function selectSpeed(page: Page, label: string): Promise<void> {
|
||||
const compactSection = page.getByTestId(COMPACT_SPEED_SECTION);
|
||||
if (await compactSection.isVisible().catch(() => false)) {
|
||||
const pill = compactSection.getByRole("button", { name: label, exact: true });
|
||||
await pill.click();
|
||||
await expect(pill).toHaveAttribute("aria-selected", "true");
|
||||
return;
|
||||
}
|
||||
await page.getByRole("button", { name: label, exact: true }).last().click();
|
||||
const toolbarTrigger = page.getByRole("button", { name: `Speed: ${label}`, exact: true });
|
||||
const sheetTrigger = page.getByRole("button", { name: "Select speed", exact: true });
|
||||
@@ -56,6 +75,11 @@ async function selectSpeed(page: Page, label: string): Promise<void> {
|
||||
}
|
||||
|
||||
async function expectSpeedIconColor(page: Page, color: string): Promise<void> {
|
||||
const compactSection = page.getByTestId(COMPACT_SPEED_SECTION);
|
||||
if (await compactSection.isVisible().catch(() => false)) {
|
||||
await expect(compactSection.locator("svg").first()).toHaveCSS("stroke", color);
|
||||
return;
|
||||
}
|
||||
const trigger = page
|
||||
.getByRole("button", { name: /^(Speed: .+|Select speed)$/ })
|
||||
.filter({ visible: true });
|
||||
|
||||
@@ -387,7 +387,10 @@ test.describe("Composer model and effort shortcuts", () => {
|
||||
const effortLabel = page.getByTestId("combined-model-selector-thinking-label");
|
||||
await expect(effortLabel).toHaveText("Medium");
|
||||
await toggleModelPickerFromComposer(page);
|
||||
await expectModelPickerClosesFromSearch(page);
|
||||
const drawerModelRow = page.getByTestId("agent-controls-model");
|
||||
await expect(drawerModelRow).toBeVisible();
|
||||
await page.keyboard.press(`${SHORTCUT_MOD}+Slash`);
|
||||
await expect(drawerModelRow).toBeHidden();
|
||||
await cycleComposerEffort(page);
|
||||
await expect(effortLabel).toHaveText("High");
|
||||
});
|
||||
|
||||
@@ -233,6 +233,63 @@ test("opening an agent focuses the composer when a mouse drives the UI", async (
|
||||
}
|
||||
});
|
||||
|
||||
/** The composer frame's border colour once its border-color transition has finished. */
|
||||
async function readSettledFrameBorder(page: Page): Promise<string> {
|
||||
return composerLocator(page).evaluate(async (input) => {
|
||||
let frame = input.parentElement;
|
||||
while (frame && parseFloat(getComputedStyle(frame).borderTopWidth) < 1) {
|
||||
frame = frame.parentElement;
|
||||
}
|
||||
if (!frame) throw new Error("Composer frame has no border");
|
||||
while (frame.getAnimations().length > 0) {
|
||||
await new Promise((resolve) => requestAnimationFrame(resolve));
|
||||
}
|
||||
return getComputedStyle(frame).borderTopColor;
|
||||
});
|
||||
}
|
||||
|
||||
// `borderAccent` at rest, `surface4` while focused: greys in both themes, never the accent.
|
||||
const FRAME_BORDERS = {
|
||||
dark: { rest: "rgb(47, 53, 52)", focus: "rgb(89, 91, 91)" },
|
||||
light: { rest: "rgb(236, 236, 241)", focus: "rgb(212, 212, 216)" },
|
||||
} as const;
|
||||
|
||||
for (const colorScheme of ["dark", "light"] as const) {
|
||||
test(`the composer frame takes a neutral border on focus in the ${colorScheme} theme`, async ({
|
||||
page,
|
||||
}) => {
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "composer-frame-focus-",
|
||||
title: "Composer frame focus",
|
||||
});
|
||||
const borders = FRAME_BORDERS[colorScheme];
|
||||
|
||||
try {
|
||||
await page.emulateMedia({ colorScheme });
|
||||
await openAgentRoute(page, agent);
|
||||
const composer = composerLocator(page);
|
||||
await expectComposerVisible(page);
|
||||
await page.mouse.move(0, 0);
|
||||
await blurComposerInput(page);
|
||||
expect(await readSettledFrameBorder(page)).toBe(borders.rest);
|
||||
|
||||
await composer.click();
|
||||
await page.mouse.move(0, 0);
|
||||
await expectComposerFocused(page);
|
||||
expect(await readSettledFrameBorder(page)).toBe(borders.focus);
|
||||
|
||||
await blurComposerInput(page);
|
||||
expect(await readSettledFrameBorder(page)).toBe(borders.rest);
|
||||
|
||||
// Hover alone leaves the frame at rest, so the border only ever means focus.
|
||||
await composer.hover();
|
||||
expect(await readSettledFrameBorder(page)).toBe(borders.rest);
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function waitForAnimationFrames(page: Page, count: number): Promise<void> {
|
||||
await page.evaluate(async (frames) => {
|
||||
for (let frame = 0; frame < frames; frame += 1) {
|
||||
|
||||
@@ -753,6 +753,10 @@ test.describe("CodeMirror workspace file editing", () => {
|
||||
const imagePath = path.join(workspace.repoPath, "pixel.png");
|
||||
await writeFile(markdownPath, "# First heading\n", "utf8");
|
||||
await writeFile(imagePath, RED_PIXEL);
|
||||
await writeFile(
|
||||
path.join(workspace.repoPath, "shape.svg"),
|
||||
await readFile(path.resolve(__dirname, "../mobile/fixtures/native-preview.svg")),
|
||||
);
|
||||
await workspace.navigateTo();
|
||||
await openWorkspaceFile(page, "notes.md");
|
||||
|
||||
@@ -800,6 +804,11 @@ test.describe("CodeMirror workspace file editing", () => {
|
||||
const initialSource = await image.getAttribute("src");
|
||||
await writeFile(imagePath, BLUE_PIXEL);
|
||||
await expect.poll(() => image.getAttribute("src")).not.toBe(initialSource);
|
||||
|
||||
await openWorkspaceFile(page, "shape.svg");
|
||||
await expect(imageCanvas).toBeVisible();
|
||||
await expect(image).toBeVisible();
|
||||
await expect(image).toHaveJSProperty("naturalWidth", 240);
|
||||
});
|
||||
|
||||
test("renders local relative images inside Markdown preview", async ({ page, withWorkspace }) => {
|
||||
|
||||
@@ -3,9 +3,11 @@ import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import { test, expect, type Page } from "../support/fixtures";
|
||||
import { connectDaemonClient } from "../support/helpers/daemon-client-loader";
|
||||
import {
|
||||
clearModelSearchWithEscape,
|
||||
clickModelRowWhileProviderOpens,
|
||||
closeModelPicker,
|
||||
expectModelListScrollKeepsSearchFocused,
|
||||
expectSearchProfilesAtTop,
|
||||
expectModelSearchEmptyState,
|
||||
expectModelPickerHeight,
|
||||
expectModelPickerWidth,
|
||||
@@ -19,8 +21,14 @@ import {
|
||||
seedModelProvider,
|
||||
expectSearchResultsVirtualized,
|
||||
} from "../support/helpers/agent-profiles";
|
||||
import { expectComposerVisible } from "../support/helpers/composer";
|
||||
import {
|
||||
blurComposerInput,
|
||||
expectComposerFocused,
|
||||
expectComposerVisible,
|
||||
} from "../support/helpers/composer";
|
||||
import { openGlobalNewWorkspaceComposer } from "../support/helpers/new-workspace";
|
||||
import { clickNewChat, clickNewTerminal, gotoWorkspace } from "../support/helpers/launcher";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
import { seedWorkspace } from "../support/helpers/seed-client";
|
||||
|
||||
const MOCK_PROVIDER_LABEL = "Mock Load Test";
|
||||
@@ -56,9 +64,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 +105,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 +114,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 +145,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 +196,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 +211,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 +221,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 +267,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 +286,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 +294,77 @@ test.describe("Cross-provider model search", () => {
|
||||
await clickModelRowWhileProviderOpens(page, {
|
||||
provider: "mock",
|
||||
modelLabel: "One minute stream",
|
||||
otherProvider: STUDIO.id,
|
||||
});
|
||||
await expect(viewport).toHaveCount(0);
|
||||
await expect(trigger).toContainText("One minute stream");
|
||||
await expectComposerFocused(page);
|
||||
});
|
||||
|
||||
await test.step("Enter on the active profile row applies it", async () => {
|
||||
await openModelPicker(page);
|
||||
await page.keyboard.press("ArrowLeft");
|
||||
for (let step = 0; step < 10; step += 1) {
|
||||
if ((await profilesRailRow.getAttribute("data-active")) === "true") break;
|
||||
await page.keyboard.press("ArrowUp");
|
||||
}
|
||||
await page.keyboard.press("ArrowRight");
|
||||
await expect(profileRow).toHaveAttribute("data-active", "true");
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(viewport).toHaveCount(0);
|
||||
await expect(trigger).toContainText("Ten second stream");
|
||||
await expectComposerFocused(page);
|
||||
});
|
||||
|
||||
await test.step("folded compact sheet also supports Enter on the active profile row", async () => {
|
||||
await test.step("the compact drawer surfaces collapsed Profiles above Model on Home and keeps provider headers stable on collapse", async () => {
|
||||
await page.setViewportSize({ width: 390, height: 800 });
|
||||
await page.getByTestId("combined-model-selector").filter({ visible: true }).first().click();
|
||||
const profilesToggle = page.getByTestId("agent-controls-profiles");
|
||||
const modelRowButton = page.getByTestId("agent-controls-model");
|
||||
await expect(profilesToggle).toBeVisible();
|
||||
await expect(page.getByTestId("agent-controls-profiles-list")).toHaveCount(0);
|
||||
const profilesBox = await profilesToggle.boundingBox();
|
||||
const modelBox = await modelRowButton.boundingBox();
|
||||
expect(profilesBox && modelBox && profilesBox.y < modelBox.y).toBe(true);
|
||||
|
||||
// Open Model: Profiles is extracted onto Home, and provider headers keep exact geometry when collapsed.
|
||||
await modelRowButton.click();
|
||||
await expect(page.getByTestId("compact-model-list")).toBeVisible();
|
||||
await expect(page.getByTestId("model-picker-rail-profiles")).toHaveCount(0);
|
||||
const expandedHeader = page.locator('[data-testid^="model-provider-section-"]').first();
|
||||
const expandedBox = await expandedHeader.boundingBox();
|
||||
const expandedProviderId = (await expandedHeader.getAttribute("data-testid"))?.replace(
|
||||
"model-provider-section-",
|
||||
"",
|
||||
);
|
||||
await expandedHeader.click();
|
||||
await expect(page.getByTestId("compact-model-list")).toHaveCount(0);
|
||||
const collapsedHeader = page.getByTestId(`model-provider-${expandedProviderId}`);
|
||||
const collapsedBox = await collapsedHeader.boundingBox();
|
||||
expect(expandedBox && collapsedBox).toBeTruthy();
|
||||
expect(Math.abs(expandedBox!.y - collapsedBox!.y)).toBeLessThanOrEqual(1);
|
||||
expect(Math.abs(expandedBox!.height - collapsedBox!.height)).toBeLessThanOrEqual(1);
|
||||
|
||||
// Search dock matches the collapsed provider card's outer rails, height, and text rail.
|
||||
const searchContainer = page.getByTestId("model-search-all-input-container");
|
||||
const searchInput = page.getByTestId("model-search-all-input");
|
||||
const searchBox = await searchContainer.boundingBox();
|
||||
const searchInputBox = await searchInput.boundingBox();
|
||||
const collapsedCardBox = await readCollapsedCardGeometry(collapsedHeader);
|
||||
expect(searchBox && searchInputBox && collapsedCardBox).toBeTruthy();
|
||||
expect(Math.abs(searchBox!.x - collapsedCardBox!.cardX)).toBeLessThanOrEqual(1);
|
||||
expect(Math.abs(searchBox!.width - collapsedCardBox!.cardWidth)).toBeLessThanOrEqual(1);
|
||||
expect(Math.abs(searchBox!.height - collapsedCardBox!.cardHeight)).toBeLessThanOrEqual(1);
|
||||
expect(Math.abs(searchInputBox!.x - collapsedCardBox!.labelX)).toBeLessThanOrEqual(2);
|
||||
|
||||
// Return Home, expand Profiles in place, and apply the profile.
|
||||
await page.getByTestId("sheet-header-back").click();
|
||||
await profilesToggle.click();
|
||||
const sheetProfileRow = page.getByTestId("model-profile-row-agent_profile_e2e_arrows");
|
||||
await expect(sheetProfileRow).toBeVisible();
|
||||
await expect(sheetProfileRow).toHaveAttribute("data-active", "true");
|
||||
await page.keyboard.press("Enter");
|
||||
await sheetProfileRow.click();
|
||||
await expect(sheetProfileRow).toHaveCount(0);
|
||||
await expect(page.getByTestId("agent-controls-model-sheet")).not.toBeInViewport();
|
||||
});
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
@@ -293,8 +372,230 @@ test.describe("Cross-provider model search", () => {
|
||||
await provider.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("choosing a model restores composer focus in workspace drafts and New Workspace", async ({
|
||||
page,
|
||||
}) => {
|
||||
const provider = await seedModelProvider(STUDIO);
|
||||
const workspace = await seedWorkspace({ repoPrefix: "model-picker-focus-" });
|
||||
|
||||
try {
|
||||
await test.step("clicking a model after blurring the workspace draft returns focus to the composer", async () => {
|
||||
await gotoWorkspace(page, workspace.workspaceId);
|
||||
await clickNewChat(page);
|
||||
await expectComposerVisible(page);
|
||||
await blurComposerInput(page);
|
||||
await openModelPicker(page);
|
||||
const viewport = page.getByTestId("combobox-desktop-container");
|
||||
await viewport.getByTestId(`model-provider-${STUDIO.id}`).click();
|
||||
await viewport.getByTestId(`model-row-${STUDIO.id}-studio-deep`).click();
|
||||
await expect(viewport).toHaveCount(0);
|
||||
await expectComposerFocused(page);
|
||||
});
|
||||
|
||||
await test.step("clicking a model on the New Workspace screen returns focus to the composer", async () => {
|
||||
await openGlobalNewWorkspaceComposer(page);
|
||||
await expectComposerVisible(page);
|
||||
await blurComposerInput(page);
|
||||
await openModelPicker(page);
|
||||
const viewport = page.getByTestId("combobox-desktop-container");
|
||||
await viewport.getByTestId(`model-provider-${STUDIO.id}`).click();
|
||||
await viewport.getByTestId(`model-row-${STUDIO.id}-studio-fast`).click();
|
||||
await expect(viewport).toHaveCount(0);
|
||||
await expectComposerFocused(page);
|
||||
});
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
await provider.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("reopening a deep selected model lands at its scroll offset on the first paint on desktop and mobile", async ({
|
||||
page,
|
||||
}) => {
|
||||
const provider = await seedModelProvider(LARGE_CATALOG);
|
||||
const workspace = await seedWorkspace({ repoPrefix: "model-picker-initial-scroll-" });
|
||||
|
||||
try {
|
||||
await gotoWorkspace(page, workspace.workspaceId);
|
||||
await clickNewChat(page);
|
||||
await expectComposerVisible(page);
|
||||
|
||||
// Select a model deep in the 200-item catalog.
|
||||
await openModelPicker(page);
|
||||
await searchAllModels(page, "bulk model 80");
|
||||
await page
|
||||
.getByTestId("combobox-desktop-container")
|
||||
.getByTestId(`model-row-${LARGE_CATALOG.id}-bulk-80`)
|
||||
.click();
|
||||
await expect(page.getByTestId("combobox-desktop-container")).toHaveCount(0);
|
||||
|
||||
await test.step("desktop opens directly at the selected row without flashing scrollTop 0", async () => {
|
||||
await startScrollSampling(page, "model-picker-model-list");
|
||||
await page.getByTestId("combined-model-selector").filter({ visible: true }).first().click();
|
||||
const samples = await readScrollSamples(page, "model-picker-model-list");
|
||||
expect(samples[0]).toBeGreaterThan(0);
|
||||
await expect(
|
||||
page
|
||||
.getByTestId("combobox-desktop-container")
|
||||
.getByTestId(`model-row-${LARGE_CATALOG.id}-bulk-80`),
|
||||
).toBeInViewport();
|
||||
await closeModelPicker(page);
|
||||
});
|
||||
|
||||
await test.step("mobile opens directly at the selected row without flashing scrollTop 0", async () => {
|
||||
await page.setViewportSize({ width: 390, height: 800 });
|
||||
await page.getByTestId("combined-model-selector").filter({ visible: true }).first().click();
|
||||
await expect(page.getByTestId("agent-controls-model")).toBeVisible();
|
||||
await startScrollSampling(page, "compact-model-list");
|
||||
await page.getByTestId("agent-controls-model").click();
|
||||
const samples = await readScrollSamples(page, "compact-model-list");
|
||||
expect(samples[0]).toBeGreaterThan(0);
|
||||
const listBox = await page.getByTestId("compact-model-list").boundingBox();
|
||||
const rowBox = await page
|
||||
.getByTestId(`model-row-${LARGE_CATALOG.id}-bulk-80`)
|
||||
.boundingBox();
|
||||
expect(listBox && rowBox).toBeTruthy();
|
||||
expect(rowBox!.y).toBeGreaterThanOrEqual(listBox!.y - 1);
|
||||
expect(rowBox!.y + rowBox!.height).toBeLessThanOrEqual(listBox!.y + listBox!.height + 1);
|
||||
});
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
await provider.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("compact single-provider picker keeps its header fixed and scrolls to the last model row", async ({
|
||||
page,
|
||||
}) => {
|
||||
const extraModels = Array.from({ length: 24 }, (_, index) => ({
|
||||
id: `extra-scroll-${String(index).padStart(2, "0")}`,
|
||||
label: `Extra scroll model ${String(index).padStart(2, "0")}`,
|
||||
description: `Extra row ${index}`,
|
||||
}));
|
||||
const client = await connectDaemonClient<DaemonClient>({
|
||||
clientIdPrefix: "single-provider-scroll",
|
||||
});
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "single-provider-scroll-",
|
||||
title: "Single provider scroll",
|
||||
model: "ten-second-stream",
|
||||
modeId: "load-test",
|
||||
});
|
||||
|
||||
try {
|
||||
await client.patchDaemonConfig({
|
||||
providers: {
|
||||
mock: {
|
||||
additionalModels: extraModels,
|
||||
},
|
||||
},
|
||||
});
|
||||
await page.setViewportSize({ width: 390, height: 800 });
|
||||
await openAgentRoute(page, workspace);
|
||||
await expectComposerVisible(page);
|
||||
await page.getByTestId("combined-model-selector").filter({ visible: true }).first().click();
|
||||
await expect(page.getByTestId("agent-controls-model")).toBeVisible();
|
||||
await page.getByTestId("agent-controls-model").click();
|
||||
|
||||
const list = page.getByTestId("compact-model-list");
|
||||
await expect(list).toBeVisible();
|
||||
const header = page.getByTestId("model-provider-section-mock");
|
||||
await expect(header).toBeVisible();
|
||||
const headerBox = await header.boundingBox();
|
||||
expect(headerBox).toBeTruthy();
|
||||
expect(headerBox!.height).toBeGreaterThanOrEqual(16);
|
||||
|
||||
// Scroll to the bottom of the lone provider's list and confirm the final row is fully in view.
|
||||
await list.evaluate((node) => {
|
||||
node.scrollTop = node.scrollHeight;
|
||||
});
|
||||
const lastRow = page.getByTestId("model-row-mock-extra-scroll-23");
|
||||
await expect(lastRow).toBeVisible();
|
||||
const listBox = await list.boundingBox();
|
||||
const lastRowBox = await lastRow.boundingBox();
|
||||
expect(listBox && lastRowBox).toBeTruthy();
|
||||
expect(lastRowBox!.y + lastRowBox!.height).toBeLessThanOrEqual(
|
||||
listBox!.y + listBox!.height + 1,
|
||||
);
|
||||
await lastRow.click();
|
||||
await expect(page.getByTestId("agent-controls-model")).toContainText("Extra scroll model 23");
|
||||
} finally {
|
||||
await client
|
||||
.patchDaemonConfig({
|
||||
providers: {
|
||||
mock: {
|
||||
additionalModels: [],
|
||||
},
|
||||
},
|
||||
})
|
||||
.catch(() => undefined);
|
||||
await client.close().catch(() => undefined);
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
async function readCollapsedCardGeometry(collapsedHeader: ReturnType<Page["getByTestId"]>) {
|
||||
return collapsedHeader.evaluate((node) => {
|
||||
// Walk up from the press overlay to the SettingsCard container (2px taller for borders).
|
||||
const header = node.parentElement;
|
||||
const card = header?.parentElement?.parentElement;
|
||||
const rect = card?.getBoundingClientRect();
|
||||
const label = header?.querySelector('[dir="auto"]');
|
||||
const labelRect = label?.getBoundingClientRect();
|
||||
return rect && labelRect
|
||||
? {
|
||||
cardX: rect.x,
|
||||
cardWidth: rect.width,
|
||||
cardHeight: rect.height,
|
||||
labelX: labelRect.x,
|
||||
}
|
||||
: null;
|
||||
});
|
||||
}
|
||||
|
||||
async function startScrollSampling(page: Page, listTestId: string): Promise<void> {
|
||||
await page.evaluate((testId) => {
|
||||
const samples: number[] = [];
|
||||
const win = window as unknown as {
|
||||
__scrollSamples?: number[];
|
||||
__scrollObserver?: MutationObserver;
|
||||
};
|
||||
win.__scrollObserver?.disconnect();
|
||||
win.__scrollSamples = samples;
|
||||
const capture = (el: Element) => {
|
||||
samples.push(el.scrollTop);
|
||||
let remaining = 4;
|
||||
const tick = () => {
|
||||
const current = document.querySelector(`[data-testid="${testId}"]`);
|
||||
if (current) samples.push(current.scrollTop);
|
||||
remaining -= 1;
|
||||
if (remaining > 0) requestAnimationFrame(tick);
|
||||
};
|
||||
requestAnimationFrame(tick);
|
||||
};
|
||||
const observer = new MutationObserver(() => {
|
||||
const el = document.querySelector(`[data-testid="${testId}"]`);
|
||||
if (!el) return;
|
||||
observer.disconnect();
|
||||
capture(el);
|
||||
});
|
||||
win.__scrollObserver = observer;
|
||||
observer.observe(document.body, { childList: true, subtree: true });
|
||||
}, listTestId);
|
||||
}
|
||||
|
||||
async function readScrollSamples(page: Page, listTestId: string): Promise<number[]> {
|
||||
await expect(page.getByTestId(listTestId)).toBeVisible({ timeout: 10_000 });
|
||||
const readSamples = () =>
|
||||
page.evaluate(
|
||||
() => (window as unknown as { __scrollSamples?: number[] }).__scrollSamples ?? [],
|
||||
);
|
||||
await expect.poll(async () => (await readSamples()).length).toBeGreaterThanOrEqual(2);
|
||||
return readSamples();
|
||||
}
|
||||
|
||||
async function setRuntimeCatalog(client: DaemonClient, count: number, cwd: string) {
|
||||
await client.patchDaemonConfig({
|
||||
providers: {
|
||||
@@ -332,7 +633,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(() =>
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { BuiltinPluginLoader } from "../../../../server/src/server/plugins/builtin/index.js";
|
||||
import { createTestPaseoDaemon } from "../../../../server/src/server/test-utils/paseo-daemon.js";
|
||||
import { DaemonClient } from "../../../../server/src/server/test-utils/daemon-client.js";
|
||||
import assert from "node:assert/strict";
|
||||
import pino from "pino";
|
||||
|
||||
const [, , root, origin, paseoHomeRoot, daemonVersion] = process.argv;
|
||||
|
||||
const daemon = await createTestPaseoDaemon({
|
||||
corsAllowedOrigins: [origin!],
|
||||
paseoHomeRoot,
|
||||
daemonVersion,
|
||||
logger: pino({ level: "error" }),
|
||||
builtinPlugins: new BuiltinPluginLoader(root, ["builtin-settings"]),
|
||||
});
|
||||
const client = new DaemonClient({
|
||||
appVersion: daemonVersion,
|
||||
url: `ws://127.0.0.1:${daemon.port}/ws`,
|
||||
});
|
||||
|
||||
try {
|
||||
await client.connect();
|
||||
const plugin = (await client.getPluginCatalog()).find(({ id }) => id === "builtin-settings");
|
||||
assert.ok(plugin?.clientBundle, JSON.stringify(await client.getPluginLogs("builtin-settings")));
|
||||
assert.deepEqual(await client.listPlugins(), []);
|
||||
process.send!({ serverId: client.getLastServerInfoMessage()!.serverId, port: daemon.port });
|
||||
await new Promise<void>((resolve) => {
|
||||
process.once("disconnect", resolve);
|
||||
process.once("SIGTERM", resolve);
|
||||
});
|
||||
} finally {
|
||||
await client.close();
|
||||
await daemon.close();
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
# Native SVG preview regression
|
||||
|
||||
Copy `../fixtures/native-preview.svg`, `../fixtures/native-preview-viewbox.svg`, and
|
||||
`../../../assets/images/icon.png` into a workspace on a test daemon. In the Android
|
||||
or iOS app, connect to that daemon, open the workspace's Files tab, and tap
|
||||
`native-preview.svg`. The SVG should show a yellow circle on a green rectangle.
|
||||
|
||||
With that preview open, run:
|
||||
|
||||
```sh
|
||||
agent-device test packages/app/e2e/mobile/agent-device/native-svg-preview.android.ad \
|
||||
--metro-port <port> --artifacts-dir .artifacts/svg-preview
|
||||
```
|
||||
|
||||
Run it again with `native-preview-viewbox.svg` open to cover SVG dimensions
|
||||
inferred from `viewBox`, then with the PNG open to check raster images. Close and
|
||||
reopen the SVG and rerun to cover cached file previews. Use English app language
|
||||
for the zoom button selectors. The scripts are discovered by `npm run test:e2e:mobile`; the iOS counterpart is
|
||||
`native-svg-preview.ios.ad`. They reopen the installed app with its current
|
||||
preview and leave the daemon connection unchanged.
|
||||
|
||||
Before the fix the SVG remains blank and the canvas wait fails. The PNG passes.
|
||||
The replay checks successful native dimension decoding and zoom/reset controls;
|
||||
visually verify the circle and rectangle as well.
|
||||
@@ -0,0 +1,11 @@
|
||||
context platform=android timeout=60000 retries=0
|
||||
env APP_ID=sh.paseo.debug
|
||||
|
||||
open "${APP_ID}"
|
||||
wait "id=\"image-file-preview-canvas\"" 10000
|
||||
wait "role=button label=\"Zoom in\"" 10000
|
||||
press "role=button label=\"Zoom in\""
|
||||
wait "role=button label=\"Reset view\" enabled=true" 10000
|
||||
press "role=button label=\"Reset view\""
|
||||
wait "role=button label=\"Reset view\" enabled=false" 10000
|
||||
close
|
||||
@@ -0,0 +1,11 @@
|
||||
context platform=ios timeout=60000 retries=0
|
||||
env APP_ID=sh.paseo.debug
|
||||
|
||||
open "${APP_ID}"
|
||||
wait "id=\"image-file-preview-canvas\"" 10000
|
||||
wait "role=button label=\"Zoom in\"" 10000
|
||||
press "role=button label=\"Zoom in\""
|
||||
wait "role=button label=\"Reset view\" enabled=true" 10000
|
||||
press "role=button label=\"Reset view\""
|
||||
wait "role=button label=\"Reset view\" enabled=false" 10000
|
||||
close
|
||||
@@ -317,6 +317,80 @@ async function runBoundedPreview() {
|
||||
await runCase("preview", "files", fileCase);
|
||||
}
|
||||
|
||||
// A finger drifts a few points during a tap, so tap the composer's controls with a
|
||||
// short drag while the keyboard is open. The model picker must open, and on a wide
|
||||
// layout its popover must end above the keyboard.
|
||||
function dragTap(rect) {
|
||||
ad(
|
||||
"gesture",
|
||||
"pan",
|
||||
String(Math.round(rect.x + rect.width / 2)),
|
||||
String(Math.round(rect.y + rect.height / 2)),
|
||||
"0",
|
||||
"3",
|
||||
"120",
|
||||
);
|
||||
}
|
||||
|
||||
// Waits until the keyboard is shown and the node with `id` stops moving.
|
||||
async function settledWithKeyboard(name, id) {
|
||||
let previousTop;
|
||||
return waitFor(name, (snap) => {
|
||||
const node = nodeById(snap, id);
|
||||
if (!node || !keyboardShown(snap)) return false;
|
||||
const stable = node.rect.y === previousTop;
|
||||
previousTop = node.rect.y;
|
||||
return stable;
|
||||
});
|
||||
}
|
||||
|
||||
const keyboardTop = (snap) =>
|
||||
snap.data.nodes.find((node) => node.type === "Keyboard" && node.rect).rect.y;
|
||||
|
||||
async function runControlTaps() {
|
||||
await clearInput("controls");
|
||||
const attach = nodeById(
|
||||
await settledWithKeyboard("controls-attach-before", "message-input-root"),
|
||||
"message-input-attach-button",
|
||||
);
|
||||
dragTap(attach.rect);
|
||||
// Wide layouts show the attachment menu as a popover and phones as a sheet; both list the items.
|
||||
await waitFor("controls-attach-menu", (snap) =>
|
||||
Boolean(nodeById(snap, "message-input-attachment-menu-item-file")),
|
||||
);
|
||||
process.stdout.write("PASS drag tap on attach opened the attachment menu\n");
|
||||
// The open menu hides the composer from accessibility. Its backdrop covers the top-left corner.
|
||||
ad("press", "20", "120");
|
||||
await waitFor("controls-attach-closed", (snap) => Boolean(nodeById(snap, "message-input-root")));
|
||||
await clearInput("controls-model");
|
||||
|
||||
const trigger = nodeById(
|
||||
await settledWithKeyboard("controls-model-before", "message-input-root"),
|
||||
"combined-model-selector",
|
||||
);
|
||||
dragTap(trigger.rect);
|
||||
const sheetOpen = (snap) =>
|
||||
snap.data.nodes.some((node) => node.type === "Button" && node.label === "Close");
|
||||
const opened = await waitFor(
|
||||
"controls-model-picker",
|
||||
(snap) => Boolean(nodeById(snap, "combobox-desktop-container")) || sheetOpen(snap),
|
||||
);
|
||||
process.stdout.write("PASS drag tap on the model selector opened the picker\n");
|
||||
if (!nodeById(opened, "combobox-desktop-container")) return;
|
||||
const settled = await settledWithKeyboard("controls-model-popover", "combobox-desktop-container");
|
||||
const frame = nodeById(settled, "combobox-desktop-container").rect;
|
||||
const bottom = frame.y + frame.height;
|
||||
const covered = frame.y < trigger.rect.y + trigger.rect.height && bottom > trigger.rect.y;
|
||||
if (covered || bottom > keyboardTop(settled) + 1) {
|
||||
throw new Error(
|
||||
`Model popover spans ${Math.round(frame.y)}-${Math.round(bottom)}; it must clear the trigger at ${Math.round(trigger.rect.y)} and the keyboard at ${Math.round(keyboardTop(settled))}`,
|
||||
);
|
||||
}
|
||||
process.stdout.write(
|
||||
`PASS model popover ${Math.round(frame.y)}-${Math.round(bottom)} clears the trigger and the keyboard\n`,
|
||||
);
|
||||
}
|
||||
|
||||
if (scenario !== "all") {
|
||||
ad(
|
||||
"open",
|
||||
@@ -328,6 +402,7 @@ if (scenario !== "all") {
|
||||
await waitFor("draft", (snap) => Boolean(nodeById(snap, "message-input-root")), 60_000);
|
||||
if (scenario === "growth") await runLiveGrowth();
|
||||
else if (scenario === "previews") await runBoundedPreview();
|
||||
else if (scenario === "controls") await runControlTaps();
|
||||
else throw new Error(`Unknown scenario: ${scenario}`);
|
||||
process.stdout.write(`Composer ${scenario} regression passed. Artifacts: ${artifactsDir}\n`);
|
||||
process.exit(0);
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 240 160"><rect width="240" height="160" fill="#08a040"/><circle cx="120" cy="80" r="50" fill="#ffcc00"/></svg>
|
||||
|
After Width: | Height: | Size: 164 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="240" height="160" viewBox="0 0 240 160"><rect width="240" height="160" fill="#08a040"/><circle cx="120" cy="80" r="50" fill="#ffcc00"/></svg>
|
||||
|
After Width: | Height: | Size: 188 B |
@@ -587,7 +587,12 @@ export async function openModelPicker(page: Page): Promise<void> {
|
||||
await expect(pickerViewport(page)).toBeVisible({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
/** Escape clears a typed query first; the next Escape closes the picker. */
|
||||
export async function closeModelPicker(page: Page): Promise<void> {
|
||||
const search = pickerViewport(page).getByTestId("model-search-input");
|
||||
if ((await search.count()) > 0 && (await search.inputValue()) !== "") {
|
||||
await clearModelSearchWithEscape(page);
|
||||
}
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(pickerViewport(page)).toHaveCount(0, { timeout: 30_000 });
|
||||
}
|
||||
@@ -598,70 +603,44 @@ export function profilePickerRow(page: Page, name: string): Locator {
|
||||
.filter({ hasText: name });
|
||||
}
|
||||
|
||||
/**
|
||||
* Profiles are pinned above the provider list, so "pinned" is an ordering claim:
|
||||
* the profile row's top edge sits above every provider row's.
|
||||
*/
|
||||
export async function expectProfilePinnedAboveProviders(
|
||||
page: Page,
|
||||
input: { name: string; summary: string },
|
||||
): Promise<void> {
|
||||
const viewport = pickerViewport(page);
|
||||
await expect(viewport.getByText("Profiles", { exact: true })).toBeVisible({ timeout: 30_000 });
|
||||
const row = profilePickerRow(page, input.name);
|
||||
await expect(row).toBeVisible({ timeout: 30_000 });
|
||||
await expect(row.getByText(input.summary, { exact: true })).toBeVisible();
|
||||
|
||||
const profileTop = await boxTop(row);
|
||||
const providerRows = viewport.locator('[data-testid^="model-provider-"]');
|
||||
await expect(providerRows.first()).toBeVisible();
|
||||
const providerCount = await providerRows.count();
|
||||
for (let index = 0; index < providerCount; index += 1) {
|
||||
expect(profileTop).toBeLessThan(await boxTop(providerRows.nth(index)));
|
||||
/** Multi-provider desktop keeps profiles behind the rail; single-pane lists them inline. */
|
||||
export async function openPickerProfiles(page: Page): Promise<void> {
|
||||
const rail = pickerViewport(page).getByTestId("model-picker-rail-profiles");
|
||||
if (await rail.isVisible().catch(() => false)) {
|
||||
await rail.click();
|
||||
}
|
||||
}
|
||||
|
||||
export async function expectProfileVisibleForProvider(
|
||||
export async function expectPickerProfile(
|
||||
page: Page,
|
||||
input: { name: string; summary: string },
|
||||
): Promise<void> {
|
||||
const viewport = pickerViewport(page);
|
||||
await expect(viewport.getByText("Profiles", { exact: true })).toBeVisible({ timeout: 30_000 });
|
||||
await openPickerProfiles(page);
|
||||
const row = profilePickerRow(page, input.name);
|
||||
await expect(row).toBeVisible({ timeout: 30_000 });
|
||||
await expect(row.getByText(input.summary, { exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
export async function expectProfileEditIsPencilOnly(page: Page): Promise<void> {
|
||||
const viewport = pickerViewport(page);
|
||||
await expect(
|
||||
viewport.getByRole("button", { name: "Edit agent profiles", exact: true }),
|
||||
).toBeVisible();
|
||||
await expect(viewport.getByText("Edit", { exact: true })).toHaveCount(0);
|
||||
}
|
||||
|
||||
export async function expectAgentProfilesEmptyPrompt(page: Page): Promise<void> {
|
||||
const viewport = pickerViewport(page);
|
||||
await expect(viewport.getByText("Profiles", { exact: true })).toHaveCount(0);
|
||||
await expect(
|
||||
viewport.getByRole("button", { name: "Edit agent profiles", exact: true }),
|
||||
).toHaveCount(0);
|
||||
await expect(viewport.getByRole("button", { name: "Create profile", exact: true })).toBeVisible({
|
||||
timeout: 30_000,
|
||||
});
|
||||
}
|
||||
|
||||
export async function expectProfileEditTooltip(page: Page): Promise<void> {
|
||||
export async function expectProfilesEditLink(page: Page): Promise<void> {
|
||||
const edit = pickerViewport(page).getByRole("button", {
|
||||
name: "Edit agent profiles",
|
||||
exact: true,
|
||||
});
|
||||
await edit.hover();
|
||||
await expect(page.getByText("Edit agent profiles", { exact: true })).toBeVisible();
|
||||
await expect(edit).toBeVisible();
|
||||
await expect(edit).toHaveText("");
|
||||
await expect(edit.locator("svg")).toBeVisible();
|
||||
}
|
||||
|
||||
/** With no profiles, the Profiles entry offers to create one instead of listing any. */
|
||||
export async function expectAgentProfilesEmptyPrompt(page: Page): Promise<void> {
|
||||
await openPickerProfiles(page);
|
||||
const viewport = pickerViewport(page);
|
||||
await expect(viewport.locator('[data-testid^="model-profile-row-"]')).toHaveCount(0);
|
||||
await expect(viewport.getByTestId("model-profiles-empty")).toBeVisible({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
export async function openAgentProfilesFromEmptyPrompt(page: Page): Promise<void> {
|
||||
await pickerViewport(page).getByRole("button", { name: "Create profile", exact: true }).click();
|
||||
await pickerViewport(page).getByTestId("model-profiles-empty").click();
|
||||
await expect(page.getByTestId("agent-profiles-card")).toBeVisible({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
@@ -709,25 +688,17 @@ export async function expectProfileReachableByScrolling(page: Page, name: string
|
||||
}
|
||||
|
||||
export async function applyProfileFromPicker(page: Page, name: string): Promise<void> {
|
||||
await profilePickerRow(page, name).click();
|
||||
const row = profilePickerRow(page, name);
|
||||
if (!(await row.isVisible().catch(() => false))) {
|
||||
const profilesRail = pickerViewport(page).getByTestId("model-picker-rail-profiles");
|
||||
if (await profilesRail.isVisible().catch(() => false)) {
|
||||
await profilesRail.click();
|
||||
}
|
||||
}
|
||||
await row.click();
|
||||
await expect(pickerViewport(page)).toHaveCount(0, { timeout: 30_000 });
|
||||
}
|
||||
|
||||
/**
|
||||
* Applying a profile materializes it and forgets it: nothing in the root view
|
||||
* claims selection. Model rows do carry `aria-selected`, so a count of zero here
|
||||
* is the absence of a checkmark, not the absence of the attribute everywhere.
|
||||
*/
|
||||
export async function expectNothingSelectedInPickerRoot(page: Page): Promise<void> {
|
||||
await expect(pickerViewport(page).locator("[aria-selected]")).toHaveCount(0);
|
||||
}
|
||||
|
||||
export async function expectAgentProfilesEditShortcut(page: Page): Promise<void> {
|
||||
await expect(
|
||||
pickerViewport(page).getByRole("button", { name: "Edit agent profiles", exact: true }),
|
||||
).toBeVisible({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
export async function drillIntoProvider(page: Page, providerId: string): Promise<void> {
|
||||
await pickerViewport(page).getByTestId(`model-provider-${providerId}`).click();
|
||||
}
|
||||
@@ -798,13 +769,13 @@ export async function selectModelRow(
|
||||
*/
|
||||
export async function clickModelRowWhileProviderOpens(
|
||||
page: Page,
|
||||
input: { provider: string; modelLabel: string },
|
||||
input: { provider: string; modelLabel: string; otherProvider: string },
|
||||
): Promise<void> {
|
||||
const viewport = pickerViewport(page);
|
||||
await drillIntoProvider(page, input.provider);
|
||||
const rowBox = await viewport.getByText(input.modelLabel, { exact: true }).boundingBox();
|
||||
if (!rowBox) throw new Error(`Model row ${input.modelLabel} has no box`);
|
||||
await viewport.getByRole("button", { name: "Back", exact: true }).click();
|
||||
await drillIntoProvider(page, input.otherProvider);
|
||||
|
||||
const cdp = await page.context().newCDPSession(page);
|
||||
await cdp.send("Emulation.setCPUThrottlingRate", { rate: 10 });
|
||||
@@ -822,7 +793,7 @@ export async function clickModelRowWhileProviderOpens(
|
||||
/** Scrolling a provider's model list with the wheel leaves typing and Enter in the search field. */
|
||||
export async function expectModelListScrollKeepsSearchFocused(page: Page): Promise<void> {
|
||||
const search = pickerViewport(page).getByTestId("model-search-input");
|
||||
const list = pickerViewport(page).getByTestId("compact-model-list");
|
||||
const list = pickerViewport(page).getByTestId("model-picker-model-list");
|
||||
await expect(search).toBeFocused();
|
||||
await list.hover();
|
||||
await page.mouse.wheel(0, 200);
|
||||
@@ -833,11 +804,18 @@ export async function expectModelListScrollKeepsSearchFocused(page: Page): Promi
|
||||
// ─── Cross-provider model search ───────────────────────────────────────────
|
||||
|
||||
export async function searchAllModels(page: Page, query: string): Promise<void> {
|
||||
const input = page.getByTestId("model-search-all-input");
|
||||
const input = pickerViewport(page).getByTestId("model-search-input");
|
||||
await expect(input).toBeVisible({ timeout: 30_000 });
|
||||
await input.fill(query);
|
||||
}
|
||||
|
||||
/** Search results open at the top, with the Profiles heading above the first matching profile. */
|
||||
export async function expectSearchProfilesAtTop(page: Page, profileId: string): Promise<void> {
|
||||
const list = pickerViewport(page).getByTestId("model-picker-model-list");
|
||||
await expect(list.getByText("Profiles", { exact: true })).toBeInViewport({ ratio: 1 });
|
||||
await expect(list.getByTestId(`model-profile-row-${profileId}`)).toBeInViewport({ ratio: 1 });
|
||||
}
|
||||
|
||||
export async function expectModelSearchResult(
|
||||
page: Page,
|
||||
expected: { provider: string; modelId: string; providerLabel: string; modelLabel: string },
|
||||
@@ -856,11 +834,19 @@ function escapeForRegex(value: string): string {
|
||||
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
}
|
||||
|
||||
/** Search results replace the whole root view, pinned profiles included. */
|
||||
/** Search results replace both panes, the Profiles list included. */
|
||||
export async function expectPinnedProfilesHidden(page: Page): Promise<void> {
|
||||
await expect(pickerViewport(page).locator('[data-testid^="model-profile-row-"]')).toHaveCount(0);
|
||||
}
|
||||
|
||||
export async function clearModelSearchWithEscape(page: Page): Promise<void> {
|
||||
const search = pickerViewport(page).getByTestId("model-search-input");
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(search).toHaveValue("");
|
||||
await expect(search).toBeFocused();
|
||||
await expect(pickerViewport(page)).toBeVisible();
|
||||
}
|
||||
|
||||
export async function expectModelSearchEmptyState(page: Page, query: string): Promise<void> {
|
||||
const empty = page.getByTestId("model-search-empty");
|
||||
await expect(empty).toBeVisible({ timeout: 30_000 });
|
||||
|
||||
@@ -362,8 +362,8 @@ export const selectModel = async (page: Page, model: string) => {
|
||||
// Type to search/filter models
|
||||
await searchInput.fill(normalizedModel);
|
||||
|
||||
const dialog = page.getByRole("dialog");
|
||||
const exactOption = dialog
|
||||
const viewport = page.getByTestId("combobox-desktop-container").or(page.getByRole("dialog"));
|
||||
const exactOption = viewport
|
||||
.getByText(new RegExp(`^${escapeRegex(normalizedModel)}$`, "i"))
|
||||
.first();
|
||||
const exactVisible = await exactOption.isVisible().catch(() => false);
|
||||
@@ -375,8 +375,10 @@ export const selectModel = async (page: Page, model: string) => {
|
||||
await searchInput.press("Enter");
|
||||
}
|
||||
|
||||
// Wait for dropdown to close
|
||||
if (await searchInput.isVisible().catch(() => false)) {
|
||||
// Wait for dropdown to close; when a query has no match, the first Escape clears the query
|
||||
// and the second closes the picker.
|
||||
for (let attempt = 0; attempt < 2; attempt += 1) {
|
||||
if (!(await searchInput.isVisible().catch(() => false))) break;
|
||||
await page.keyboard.press("Escape").catch(() => undefined);
|
||||
}
|
||||
await expect(searchInput).not.toBeVisible({ timeout: 5000 });
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { once } from "node:events";
|
||||
import { spawnTsx, killProcessTree } from "./spawn-node";
|
||||
import appPackage from "../../../package.json";
|
||||
import { expect, test as base, type Page } from "../fixtures";
|
||||
import { gotoAppShell } from "./app";
|
||||
import { addConnectedHostAndReload } from "./hosts";
|
||||
import { pluginRequirements } from "./plugin-fixture";
|
||||
|
||||
const pluginId = "builtin-settings";
|
||||
const screenId = "general";
|
||||
const settingsText = "Built-in settings body";
|
||||
|
||||
export const test = base.extend<{ builtinSettingsHost: { serverId: string; port: number } }>({
|
||||
builtinSettingsHost: async ({ baseURL }, provide, testInfo) => {
|
||||
const root = testInfo.outputPath("builtin-plugins");
|
||||
const directory = path.join(root, pluginId);
|
||||
await mkdir(directory, { recursive: true });
|
||||
await writeFile(
|
||||
path.join(directory, "paseo-plugin.json"),
|
||||
JSON.stringify({ id: pluginId, requirements: pluginRequirements }),
|
||||
);
|
||||
await writeFile(
|
||||
path.join(directory, "index.client.tsx"),
|
||||
`import React from "react";
|
||||
import { Text } from "react-native";
|
||||
|
||||
export default function contribute(client) {
|
||||
client.addSettingsScreen({
|
||||
id: "${screenId}",
|
||||
title: "General",
|
||||
icon: "SlidersHorizontal",
|
||||
Component: () => <Text>${settingsText}</Text>,
|
||||
});
|
||||
return () => {};
|
||||
}`,
|
||||
);
|
||||
await writeFile(
|
||||
path.join(directory, "index.server.ts"),
|
||||
"export default function contribute() { return () => {}; }",
|
||||
);
|
||||
const daemon = spawnTsx(
|
||||
path.resolve(__dirname, "../../fixtures/builtin-settings/daemon.mts"),
|
||||
[root, new URL(baseURL!).origin, testInfo.outputPath("daemon"), appPackage.version],
|
||||
{ stdio: ["ignore", "inherit", "inherit", "ipc"] },
|
||||
);
|
||||
try {
|
||||
const [host] = await Promise.race([
|
||||
once(daemon, "message") as Promise<[{ serverId: string; port: number }]>,
|
||||
once(daemon, "exit").then(([code]) => {
|
||||
throw new Error(`Built-in settings daemon exited with code ${code}`);
|
||||
}),
|
||||
]);
|
||||
await provide(host);
|
||||
} finally {
|
||||
await killProcessTree(daemon);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
export async function openBuiltinPluginSettings(
|
||||
page: Page,
|
||||
host: { serverId: string; port: number },
|
||||
) {
|
||||
await gotoAppShell(page);
|
||||
await addConnectedHostAndReload(page, {
|
||||
...host,
|
||||
label: "Built-in settings host",
|
||||
destination: `/settings/hosts/${host.serverId}/plugins/${pluginId}/${screenId}`,
|
||||
});
|
||||
}
|
||||
|
||||
export async function expectBuiltinPluginSettings(page: Page) {
|
||||
await expect(page.getByText(settingsText, { exact: true })).toBeVisible();
|
||||
await expect(page.getByRole("switch", { name: /: Disable$/ })).toHaveCount(0);
|
||||
}
|
||||
@@ -76,15 +76,24 @@ export async function addOfflineHostsAndReload(
|
||||
|
||||
export async function addConnectedHostAndReload(
|
||||
page: Page,
|
||||
input: { serverId: string; label: string; port: number; primaryLabel?: string },
|
||||
input: {
|
||||
serverId: string;
|
||||
label: string;
|
||||
port: number;
|
||||
primaryLabel?: string;
|
||||
destination?: string;
|
||||
},
|
||||
): Promise<void> {
|
||||
await addConnectedHostsAndReload(page, [input], { primaryLabel: input.primaryLabel });
|
||||
await addConnectedHostsAndReload(page, [input], {
|
||||
primaryLabel: input.primaryLabel,
|
||||
destination: input.destination,
|
||||
});
|
||||
}
|
||||
|
||||
export async function addConnectedHostsAndReload(
|
||||
page: Page,
|
||||
inputs: Array<{ serverId: string; label: string; port: number }>,
|
||||
options?: { primaryLabel?: string },
|
||||
options?: { primaryLabel?: string; destination?: string },
|
||||
): Promise<void> {
|
||||
const connectedHosts = inputs.map((input) =>
|
||||
buildSeededHost({
|
||||
@@ -123,7 +132,8 @@ export async function addConnectedHostsAndReload(
|
||||
},
|
||||
);
|
||||
|
||||
await page.reload();
|
||||
if (options?.destination) await page.goto(options.destination);
|
||||
else await page.reload();
|
||||
}
|
||||
|
||||
export async function waitForConnectedHost(
|
||||
|
||||
@@ -17,7 +17,6 @@ export async function chooseModel(page: Page, provider: string, label: string) {
|
||||
export async function reselectModel(page: Page, provider: string, label: string) {
|
||||
await expectRememberedModel(page, label);
|
||||
await openModelPicker(page);
|
||||
await page.getByRole("dialog").getByRole("button", { name: "Back", exact: true }).click();
|
||||
await selectProviderModel(page, provider, label);
|
||||
}
|
||||
|
||||
|
||||
@@ -44,9 +44,8 @@ async function expectProviderIcon(surface: Locator, paths: string[]): Promise<vo
|
||||
|
||||
async function selectPluginModel(page: Page): Promise<void> {
|
||||
await openModelPicker(page);
|
||||
await page.getByRole("button", { name: "Back", exact: true }).click();
|
||||
await page.getByText("Direct provider example", { exact: true }).click();
|
||||
await page.getByText("Example 1", { exact: true }).click();
|
||||
await page.getByTestId("model-provider-direct-example").click();
|
||||
await page.getByTestId("model-row-direct-example-example-1").click();
|
||||
await expect(page.getByRole("button", { name: MODEL_LABEL, exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
|
||||
@@ -463,16 +463,15 @@ export async function delegateFleetThroughMcp() {
|
||||
direction: "tail",
|
||||
limit: 100,
|
||||
});
|
||||
return timeline.entries
|
||||
.flatMap(({ item }) =>
|
||||
item.type === "tool_call" && item.agentMessage ? [item.agentMessage] : [],
|
||||
)
|
||||
.filter(
|
||||
(message) =>
|
||||
message.event === "finished" &&
|
||||
message.sender.id === child.agentId &&
|
||||
message.text.includes(`Server: ${child.serverId}`),
|
||||
).length;
|
||||
return timeline.entries.filter(
|
||||
({ item }) =>
|
||||
item.type === "tool_call" &&
|
||||
item.name === "agent_finished" &&
|
||||
item.detail.type === "plain_text" &&
|
||||
item.detail.label === child.title &&
|
||||
item.detail.text?.includes(child.agentId) &&
|
||||
item.detail.text.includes(`Server: ${child.serverId}`),
|
||||
).length;
|
||||
})
|
||||
.toBe(1);
|
||||
},
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
node_modules/
|
||||
desktop/build/
|
||||
desktop/autolink/
|
||||
@@ -1,3 +0,0 @@
|
||||
workspaces=false
|
||||
legacy-peer-deps=true
|
||||
install-links=true
|
||||
@@ -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;
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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();
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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());
|
||||
@@ -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() {}
|
||||
@@ -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";
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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),
|
||||
};
|
||||
@@ -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 +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);
|
||||
@@ -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" }]],
|
||||
};
|
||||
};
|
||||
@@ -1,4 +0,0 @@
|
||||
build/
|
||||
.cache/
|
||||
autolink/
|
||||
target/
|
||||
Generated
-8785
File diff suppressed because it is too large
Load Diff
@@ -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.
|
||||
@@ -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())
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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");
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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(¶ms).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"}])
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
@@ -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,
|
||||
);
|
||||
@@ -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.");
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
Generated
-6737
File diff suppressed because it is too large
Load Diff
@@ -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"
|
||||
}
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
/// <reference types="@react-native-gpui/core/types" />
|
||||
// Added by react-native-gpui. Do not edit: it is regenerated.
|
||||
@@ -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")),
|
||||
};
|
||||
@@ -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?$/,
|
||||
);
|
||||
@@ -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);
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user