Compare commits

...
Author SHA1 Message Date
Mohamed Boudra 2e646303b6 chore(gpui): bump runtime packages to paseo-4 2026-11-28 19:44:55 +01:00
Mohamed Boudra 122041acd4 test(gpui): check pointer control height within one device pixel
Query display scaleFactor from the test driver so pointer control height assertions handle non-integer DPI snapping (such as 1.9167 on Linux Xvfb).
2026-11-28 19:10:27 +01:00
Mohamed Boudra 8e5cab31ec refactor(app): export resource budget values and move sizing to presentation
Replace usesMobileResourceBudget with per-target budget limits (workspaceDeckRetentionLimit, sourceFileBudgets, deferModelSelectorMount) so callers read values directly and GPUI can tune its retention limit independently. Move initial font defaults and composer minimum height into presentation, and export plain values without resolve helpers from .gpui.ts owners.
2026-11-28 19:10:27 +01:00
Mohamed Boudra 5ef07a0335 test(gpui): verify Enter submit and workspace retention in native harness
Exercise multiline Shift+Enter newline insertion, Enter message submission, and retained workspace TextInput state across workspace switches in native.test.ts.
2026-11-28 19:10:27 +01:00
Mohamed Boudra d17ca42d1f fix(app): disable touch press delay, holds, and haptics on GPUI
Add a touch-timing owner and press-highlight.gpui.tsx so GPUI gets immediate press highlights and skips touch-hold delays and haptics on composer alternate send, draggable lists, and sidebar long-press interactions.
2026-11-28 19:10:26 +01:00
Mohamed Boudra b2b862b1ea fix(app): use desktop presentation defaults on GPUI
Add a presentation capabilities owner with a GPUI override so GPUI matches desktop inline rename, popover spacing, and non-sheet modal/browser presentation while keeping iOS, Android, web, and Electron unchanged.
2026-11-28 19:10:26 +01:00
Mohamed Boudra 8aaa01ad07 fix(app): give GPUI desktop resource budgets
Add a resource-budget owner with a GPUI override so mounted workspace retention, source highlight budgets, model selector mount deferral, font defaults, and composer minimum input height use desktop values on GPUI without altering iOS, Android, web, or Electron.
2026-11-28 19:10:26 +01:00
Mohamed Boudra 1887eb5220 fix(app): answer hardware keyboard presence and conventions on GPUI
Add GPUI hardware keyboard presence and convention files, expose hasSoftwareKeyboard from keyboard, and move composer Enter/hint/autofocus/blur, model browser autofocus/dismiss, terminal virtual key bar/paste/copy/insets, and panel keyboard dismiss onto the keyboard owner.
2026-11-28 19:10:26 +01:00
Mohamed Boudra 3576503027 fix(app): wire ResizeHandle fine-pointer branch for non-web GPUI
Use the pointer capability owner in ResizeHandle without calling DOM pointer capture or document/window APIs when running on GPUI. iOS, Android, web, and Electron keep their exact behavior.
2026-11-28 19:10:26 +01:00
Mohamed Boudra aeebea8d3d style(gpui): format desktop Cargo.toml 2026-11-28 19:10:20 +01:00
Mohamed Boudra b57648b196 chore(gpui): bump runtime packages to paseo-3 2026-11-28 17:46:32 +01:00
Mohamed Boudra 90aa1eef3f chore(gpui): install runtime packages from release tarballs
Replace the vendored react-native-gpui tree with pinned tarballs from the getpaseo/react-native-gpui paseo-2 release for the four runtime packages and seven @react-native-gpui modules, and add a --local install path for testing against a local fork checkout.
2026-11-28 16:14:04 +01:00
Mohamed Boudra 7a5be97a4c fix(gpui): report a fine pointer on GPUI so controls take pointer sizes
pointer-capabilities answers touch-primary for every non-web build, so the
GPUI desktop client took iOS touch sizes: 44 pt controls and rows instead
of 28 and 36. GPUI reports every pointer as a mouse, so its branch answers
fine pointer, no touch screen. iOS, Android and web resolve the same file
as before.
2026-11-28 16:13:35 +01:00
Mohamed Boudra 1390e83b30 fix(gpui): export RefreshControl and VirtualizedList from the Unistyles adapter
The Unistyles Babel plugin sends RefreshControl and VirtualizedList imports
from react-native to the GPUI adapter, which did not export them. History
rendered the agent list with an undefined RefreshControl and showed
Element type is invalid.
2026-11-28 16:13:35 +01:00
Mohamed Boudra 12b284335e fix(gpui): clamp enriched-markdown measurements to layoutConstraints
Forward minimum and maximum LayoutConstraints through measureMarkdown and clamp measured dimensions to Yoga bounds so stretched narrow content does not violate minimumSize.
2026-11-28 16:13:35 +01:00
Mohamed Boudra 0706cdfeb6 fix(gpui): include LayoutConstraints in enriched-markdown shadow nodes
Apple clang does not reach LayoutConstraints.h transitively, so
measureContent saw only the forward declaration and failed to compile.
2026-11-28 16:13:35 +01:00
Mohamed Boudra b2b683a5d4 test(gpui): expand markdown block checks and add release stage benchmark
Add caller-level layout and pixel assertions across every Phase 1 block type, verify regression.png rendering output, and add the standalone release stage benchmark example.
2026-11-28 16:13:35 +01:00
Mohamed Boudra 56eb19b7ca fix(gpui): match native enriched-markdown font, inline code, and code block defaults
Drop the Linux Nimbus Sans font remap so markdown resolves font families the same way as RN <Text>, fix serde renaming for isGFM, apply inline code fontScale, and add the iOS/Android code block language header and divider bar.
2026-11-28 16:13:35 +01:00
Mohamed Boudra 418e676c87 feat(gpui): add enriched-markdown desktop GPUI backend
Implements EnrichedMarkdown and EnrichedMarkdownText inside packages/react-native-enriched-markdown/desktop by reusing the shared C++ MD4C parser, link recognizer, and tree-sitter code highlighter for Fabric measurement and rendering blocks, inline styles, links, lists, highlighted code, and tables on GPUI with zero changes under packages/app/src.
2026-11-28 16:13:35 +01:00
Mohamed Boudra 35a5cd4311 gpui: dispatch onLayout for any node that sets it 2026-11-28 13:10:11 +01:00
Mohamed Boudra 1eb69a4217 feat(gpui): add .gpui.* Metro resolution rule 2026-11-28 12:38:31 +01:00
Mohamed Boudra c1f6992a6c fix(gpui): adapt press-feedback and stabilize native test after main merge 2026-11-28 12:20:46 +01:00
Mohamed Boudra 4de5e7e4df Merge remote-tracking branch 'origin/main' into gpui-ship-readiness-assessment
# Conflicts:
#	.oxfmtrc.json
#	.oxlintrc.json
#	package.json
#	packages/relay/src/e2e.test.ts
2026-11-28 11:58:16 +01:00
Mohamed Boudra d0129a4f90 chore(gpui): catch up vendored react-native-gpui to ad502d80d
Update vendor/react-native-gpui packages/{cli,codegen,core,hermes} to streetwriters/react-native-gpui@ad502d80d and modules/* to streetwriters/react-native-gpui-modules@7435b7f4d, drop upstreamed local patches, retain the remaining local patches documented in UPSTREAM, refresh packages/app/gpui dependencies and Cargo lockfile, and include the updated GPUI README rules.
2026-11-28 11:55:55 +01:00
Mohamed Boudra 291c8ad1a8 fix(gpui): stabilize macOS packaging, connections and appearance
Release terminal WebSocket clients on the JS thread so daemon retries do not exhaust descriptors or join their own IO thread. Preserve Cargo symbols and seal ad-hoc macOS bundles with a library-loading policy that works with hardened runtime.

Use rounded border decoration without changing Fabric child layout, and route desktop hover through pointer events and Pressable render props. Include native regressions and reproducible package verification.
2026-11-08 04:40:38 +01:00
Mohamed Boudra 6d247815fd test(relay): keep local E2E traffic off production upstream 2026-11-02 02:32:15 +01:00
Mohamed Boudra d785a685a0 feat(app): add an experimental native desktop target 2026-11-02 02:19:47 +01:00
Mohamed Boudra 5518c25ac5 chore(gpui): vendor the experimental native runtime 2026-11-02 02:19:36 +01:00
127 changed files with 24766 additions and 156 deletions
+2
View File
@@ -0,0 +1,2 @@
packages/app/gpui/package-lock.json linguist-generated
packages/app/gpui/desktop/Cargo.lock linguist-generated
+2
View File
@@ -99,3 +99,5 @@ app.json
# Project-local Serena configuration and memories.
.serena/
!packages/app/gpui/app.json
+7
View File
@@ -29,6 +29,13 @@ 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:
+5 -1
View File
@@ -126,7 +126,11 @@
"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"
"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"
},
"devDependencies": {
"@types/ws": "^8.5.14",
+3
View File
@@ -0,0 +1,3 @@
node_modules/
desktop/build/
desktop/autolink/
+3
View File
@@ -0,0 +1,3 @@
workspaces=false
legacy-peer-deps=true
install-links=true
+283
View File
@@ -0,0 +1,283 @@
# 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/`.
@@ -0,0 +1,73 @@
import { promises as fs, paths } from "@react-native-gpui/fs";
import Desktop from "../desktop/src/NativePaseoDesktop";
let writes = Promise.resolve();
const directory = () => `${paths.appData}/paseo-gpui/storage`;
const filename = (key) => `${directory()}/${Desktop.sha256(key)}.json`;
async function read(key) {
try {
return JSON.parse(await fs.readFile(filename(key), "utf8")).value;
} catch (error) {
if (error.code === "ENOENT") return null;
throw error;
}
}
function mutate(operation) {
const result = writes.then(operation);
writes = result.catch(() => {});
return result;
}
async function write(key, value) {
await fs.mkdir(directory(), { recursive: true });
const target = filename(key);
await fs.writeFile(`${target}.tmp`, JSON.stringify({ key, value }), "utf8");
await fs.rename(`${target}.tmp`, target);
}
async function keys() {
let entries;
try {
entries = await fs.readdir(directory());
} catch (error) {
if (error.code === "ENOENT") return [];
throw error;
}
return Promise.all(
entries
.filter((name) => name.endsWith(".json"))
.map(async (name) => JSON.parse(await fs.readFile(`${directory()}/${name}`, "utf8")).key),
);
}
const storage = {
async getItem(key) {
await writes;
return read(key);
},
setItem(key, value) {
return mutate(() => write(key, value));
},
removeItem(key) {
return mutate(() => fs.rm(filename(key), { force: true }));
},
async getAllKeys() {
await writes;
return keys();
},
async multiGet(items) {
await writes;
return Promise.all(items.map(async (key) => [key, await read(key)]));
},
multiSet(items) {
return mutate(async () => {
for (const [key, value] of items) await write(key, value);
});
},
multiRemove(items) {
return mutate(async () => {
for (const key of items) await fs.rm(filename(key), { force: true });
});
},
clear() {
return mutate(() => fs.rm(directory(), { recursive: true, force: true }));
},
};
export default storage;
+16
View File
@@ -0,0 +1,16 @@
import { TurboModuleRegistry } from "react-native";
const clipboard = TurboModuleRegistry.getEnforcing("Clipboard");
export const getStringAsync = () => clipboard.getString();
export async function setStringAsync(value) {
clipboard.setString(value);
return true;
}
export async function hasStringAsync() {
return (await getStringAsync()).length > 0;
}
export async function getImageAsync() {
throw new Error("Image clipboard is not implemented for GPUI yet");
}
export async function setImageAsync() {
throw new Error("Image clipboard is not implemented for GPUI yet");
}
+24
View File
@@ -0,0 +1,24 @@
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);
}
@@ -0,0 +1,14 @@
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,
})),
),
};
}
@@ -0,0 +1,11 @@
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();
@@ -0,0 +1,30 @@
import { Linking } from "react-native";
import { NativeModule } from "expo-modules-core/src/polyfill/CoreModule";
class DesktopLinking extends NativeModule {
initialURL = null;
subscription;
constructor() {
super();
Linking.getInitialURL()
.then((url) => {
this.initialURL = url;
if (url) this.emit("onURLReceived", { url });
return url;
})
.catch((error) => console.error("[GPUI linking]", error));
}
getLinkingURL = () => this.initialURL;
clearInitialURL() {
this.initialURL = null;
}
startObserving() {
this.subscription = Linking.addEventListener("url", (event) =>
this.emit("onURLReceived", event),
);
}
stopObserving() {
this.subscription?.remove();
}
}
export default new DesktopLinking();
+129
View File
@@ -0,0 +1,129 @@
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();
},
};
}
@@ -0,0 +1,8 @@
// 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.");
},
};
@@ -0,0 +1,28 @@
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",
})),
),
};
}
@@ -0,0 +1,5 @@
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);
}
@@ -0,0 +1,23 @@
/* oxlint-disable import/no-unassigned-import -- Exercise the actual GPUI Intl implementation. */
import "@formatjs/intl-datetimeformat/polyfill-force.js";
import "@formatjs/intl-datetimeformat/locale-data/en.js";
import "@formatjs/intl-datetimeformat/add-all-tz.js";
import { afterEach, expect, test } from "vitest";
import { setDefaultTimeZone } from "./intl-timezone";
afterEach(() => setDefaultTimeZone("UTC"));
test.each([
["GMT", "UTC"],
["gmt", "UTC"],
["UTC", "UTC"],
["Europe/Berlin", "Europe/Berlin"],
["US/Pacific", "America/Los_Angeles"],
])("initializes the system timezone %s as %s", (systemZone, expectedZone) => {
setDefaultTimeZone(systemZone);
expect(new Intl.DateTimeFormat("en").resolvedOptions().timeZone).toBe(expectedZone);
});
test("does not silently replace an invalid system timezone", () => {
expect(() => setDefaultTimeZone("Invalid/Zone")).toThrow(RangeError);
});
+17
View File
@@ -0,0 +1,17 @@
/* oxlint-disable import/no-unassigned-import -- These packages install Intl and locale data by side effect. */
// Hermes' Linux build omits Intl; install real locale algorithms before app code.
import "@formatjs/intl-getcanonicallocales/polyfill-force.js";
import "@formatjs/intl-locale/polyfill-force.js";
import "@formatjs/intl-pluralrules/polyfill-force.js";
import "@formatjs/intl-pluralrules/locale-data/en.js";
import "@formatjs/intl-numberformat/polyfill-force.js";
import "@formatjs/intl-numberformat/locale-data/en.js";
import "@formatjs/intl-datetimeformat/polyfill-force.js";
import "@formatjs/intl-datetimeformat/locale-data/en.js";
import "@formatjs/intl-datetimeformat/add-all-tz.js";
import "@formatjs/intl-displaynames/polyfill-force.js";
import "@formatjs/intl-displaynames/locale-data/en.js";
import "@formatjs/intl-segmenter/polyfill-force.js";
import Desktop from "../desktop/src/NativePaseoDesktop";
import { setDefaultTimeZone } from "./intl-timezone";
setDefaultTimeZone(Desktop.timezone());
+6
View File
@@ -0,0 +1,6 @@
// No desktop power-inhibition lease is acquired by this backend yet.
export const isAvailableAsync = async () => false;
export async function activateKeepAwakeAsync() {
throw new Error("Power inhibition is not available in the GPUI build.");
}
export async function deactivateKeepAwake() {}
+60
View File
@@ -0,0 +1,60 @@
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]);
}
@@ -0,0 +1,5 @@
import Desktop from "../desktop/src/NativePaseoDesktop";
export function getLocales() {
const languageTag = Desktop.locale().split(".")[0].replaceAll("_", "-");
return [{ languageTag, languageCode: languageTag.split("-")[0] }];
}
@@ -0,0 +1,5 @@
import { Buffer } from "buffer";
import Desktop from "../desktop/src/NativePaseoDesktop";
export function randomBytes(length) {
return Buffer.from(Desktop.randomBytes(length));
}
@@ -0,0 +1,3 @@
// GPUI's native TextInput owns text paste, selection, and IME. The mobile
// PasteInput module's image-paste extension is not available on this target.
export { TextInput as default } from "react-native";
+11
View File
@@ -0,0 +1,11 @@
import { dialog, promises } from "@react-native-gpui/fs";
// Linux exports a downloaded file through the native Save dialog.
export const isAvailableAsync = async () => true;
export async function shareAsync(uri, options = {}) {
const source = uri.replace(/^file:\/\//, "");
const destination = await dialog.save({
title: options.dialogTitle ?? "Save file",
defaultName: source.split("/").at(-1),
});
if (destination) await promises.copyFile(source, destination);
}
+37
View File
@@ -0,0 +1,37 @@
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;
}
}),
};
}
@@ -0,0 +1,28 @@
import * as RN from "react-native";
import { createUnistylesElement } from "./unistyles";
export const View = createUnistylesElement(RN.View);
export const Text = createUnistylesElement(RN.Text);
export const ScrollView = createUnistylesElement(RN.ScrollView);
export const TextInput = createUnistylesElement(RN.TextInput);
export const Pressable = createUnistylesElement(RN.Pressable);
export const Image = createUnistylesElement(RN.Image);
export const ImageBackground = createUnistylesElement(RN.ImageBackground);
export const FlatList = createUnistylesElement(RN.FlatList);
export const SectionList = createUnistylesElement(RN.SectionList);
export const TouchableOpacity = createUnistylesElement(RN.TouchableOpacity);
export const TouchableHighlight = createUnistylesElement(RN.TouchableHighlight);
export const TouchableWithoutFeedback = createUnistylesElement(RN.TouchableWithoutFeedback);
export const ActivityIndicator = createUnistylesElement(RN.ActivityIndicator);
export const KeyboardAvoidingView = createUnistylesElement(RN.KeyboardAvoidingView);
export const SafeAreaView = createUnistylesElement(RN.SafeAreaView);
export const Switch = createUnistylesElement(RN.Switch);
export const RefreshControl = createUnistylesElement(RN.RefreshControl);
export const VirtualizedList = createUnistylesElement(RN.VirtualizedList);
export const StatusBar = RN.StatusBar;
export const Animated = {
...RN.Animated,
View: createUnistylesElement(RN.Animated.View),
Text: createUnistylesElement(RN.Animated.Text),
ScrollView: createUnistylesElement(RN.Animated.ScrollView),
Image: createUnistylesElement(RN.Animated.Image),
};
+140
View File
@@ -0,0 +1,140 @@
import React, { forwardRef, useSyncExternalStore } from "react";
import * as Native from "react-native";
// GPUI has Fabric but no Nitro/Unistyles shadow-tree bindings. Keep the app's
// style factories and theme API; this backend updates subscribed React views.
const listeners = new Set();
const resolveStyle = Symbol("paseo.gpui.style");
let revision = 0;
let themes = {};
let themeName = "dark";
let adaptive = true;
let breakpoints = {};
const emit = () => {
revision += 1;
for (const listener of listeners) listener();
};
const subscribe = (listener) => {
listeners.add(listener);
return () => listeners.delete(listener);
};
const snapshot = () => revision;
const theme = () => themes[themeName];
const runtime = () => ({
themeName,
colorScheme: Native.Appearance.getColorScheme() ?? "light",
screen: Native.Dimensions.get("window"),
insets: { top: 0, bottom: 0, left: 0, right: 0, ime: 0 },
pixelRatio: Native.PixelRatio.get(),
fontScale: Native.PixelRatio.getFontScale(),
breakpoint: Object.keys(breakpoints).findLast(
(key) => breakpoints[key] <= Native.Dimensions.get("window").width,
),
});
Native.Dimensions.addEventListener("change", emit);
Native.Appearance.addChangeListener(({ colorScheme }) => {
if (adaptive && themes[colorScheme]) themeName = colorScheme;
emit();
});
function responsive(value) {
if (Array.isArray(value)) return value.map(responsive);
if (!value || typeof value !== "object") return value;
if (Object.getPrototypeOf(value) !== Object.prototype) return value;
const keys = Object.keys(value);
if (keys.length && keys.every((key) => key in breakpoints)) {
const width = Native.Dimensions.get("window").width;
const key = keys
.sort((a, b) => breakpoints[a] - breakpoints[b])
.findLast((candidate) => breakpoints[candidate] <= width);
return key === undefined ? undefined : responsive(value[key]);
}
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, responsive(item)]));
}
function materialize(style) {
if (Array.isArray(style)) return style.map(materialize);
if (style && typeof style === "object" && style[resolveStyle]) return style[resolveStyle]();
return style;
}
function styledProps(props) {
const result = { ...props };
for (const key of ["style", "contentContainerStyle"]) {
if (typeof props[key] === "function")
result[key] = (...args) => materialize(props[key](...args));
else if (props[key]) result[key] = materialize(props[key]);
}
return result;
}
export const UnistylesRuntime = {
get themeName() {
return themeName;
},
get breakpoint() {
return runtime().breakpoint;
},
get colorScheme() {
return runtime().colorScheme;
},
getTheme: theme,
setTheme(name) {
if (!themes[name]) throw new Error(`Unknown GPUI theme: ${name}`);
themeName = name;
emit();
},
updateTheme(name, update) {
themes[name] = update(themes[name]);
emit();
},
setAdaptiveThemes(value) {
adaptive = value;
if (value && themes[runtime().colorScheme]) themeName = runtime().colorScheme;
emit();
},
};
export const StyleSheet = {
...Native.StyleSheet,
configure(config) {
themes = config.themes;
breakpoints = config.breakpoints;
adaptive = config.settings?.adaptiveThemes ?? false;
themeName =
config.settings?.initialTheme ?? (adaptive ? runtime().colorScheme : Object.keys(themes)[0]);
emit();
},
create(factory) {
const evaluate = () => (typeof factory === "function" ? factory(theme(), runtime()) : factory);
const initial = evaluate();
const sheet = {};
for (const key of Object.keys(initial)) {
const wrap = (args) => {
const resolve = () => {
const value = evaluate()[key];
return responsive(typeof value === "function" ? value(...args) : value);
};
return Object.defineProperty({ ...resolve() }, resolveStyle, { value: resolve });
};
sheet[key] = typeof initial[key] === "function" ? (...args) => wrap(args) : wrap([]);
}
return sheet;
},
};
// Existing consumers retain this API; new app code should use style factories.
export function useUnistyles() {
useSyncExternalStore(subscribe, snapshot, snapshot);
return { theme: theme(), rt: runtime() };
}
export function withUnistyles(Component, mappings) {
const Wrapped = forwardRef(function GpuiThemed(props, ref) {
useSyncExternalStore(subscribe, snapshot, snapshot);
const { uniProps, ...rest } = props;
return React.createElement(Component, {
...styledProps({
...mappings?.(theme(), runtime()),
...uniProps?.(theme(), runtime()),
...rest,
}),
ref,
});
});
return Wrapped;
}
export const createUnistylesElement = withUnistyles;
+1
View File
@@ -0,0 +1 @@
{ "name": "Paseo", "displayName": "Paseo GPUI" }
@@ -0,0 +1,121 @@
/* oxlint-disable react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop -- Minimal native regression scene. */
import React, { useCallback, useState } from "react";
import { AppRegistry, Image, Pressable, ScrollView, Text, TextInput, View } from "react-native";
function AppearanceRegression() {
const [buttonHovered, setHovered] = useState(false);
const [entered, setEntered] = useState(false);
const [expanded, setExpanded] = useState(false);
const [layouts, setLayouts] = useState({});
const record = useCallback((key, event) => {
const layout = event?.nativeEvent?.layout;
const layoutKeys = layout ? Object.keys(layout).sort() : [];
setLayouts((prev) => ({
...prev,
[key]: {
count: (prev[key]?.count ?? 0) + 1,
keys: layoutKeys,
layout,
},
}));
}, []);
const onViewLayout = useCallback((e) => record("view", e), [record]);
const onTextLayout = useCallback((e) => record("text", e), [record]);
const onInputLayout = useCallback((e) => record("textInput", e), [record]);
const onImageLayout = useCallback((e) => record("image", e), [record]);
const onScrollLayout = useCallback((e) => record("scrollView", e), [record]);
return (
<View style={{ flex: 1, flexDirection: "row", backgroundColor: "white", padding: 40, gap: 40 }}>
<View style={{ gap: 24 }}>
<View
testID="rounded-border"
style={{
width: 200,
height: 100,
borderRadius: 24,
borderWidth: 4,
borderColor: "#ff0000",
backgroundColor: "#0000ff",
}}
/>
<Pressable
testID="hover-button"
onHoverIn={() => setHovered(true)}
onHoverOut={() => setHovered(false)}
style={{ width: 200, height: 60, backgroundColor: buttonHovered ? "#00ff00" : "#0000ff" }}
>
<Text>{buttonHovered ? "hover active" : "hover inactive"}</Text>
</Pressable>
<Pressable
testID="hover-render-prop"
style={({ hovered }) => ({
width: 200,
height: 60,
backgroundColor: hovered ? "#00ff00" : "#0000ff",
})}
>
{({ hovered }) => <Text>{hovered ? "render hovered" : "render idle"}</Text>}
</Pressable>
<View
testID="hover-row"
onPointerEnter={() => setEntered(true)}
onPointerLeave={() => setEntered(false)}
style={{ width: 200, height: 60, backgroundColor: entered ? "#00ff00" : "#0000ff" }}
>
<Pressable testID="nested-button" style={{ width: 100, height: 60 }}>
<Text>{entered ? "row active" : "row inactive"}</Text>
</Pressable>
</View>
<View testID="outside-hover" style={{ width: 200, height: 60 }} />
</View>
<View style={{ gap: 12, alignItems: "flex-start" }}>
<Pressable
testID="layout-resize-toggle"
onPress={() => setExpanded((value) => !value)}
style={{ width: 160, height: 32, backgroundColor: "#dddddd", justifyContent: "center" }}
>
<Text>{expanded ? "Shrink" : "Expand"}</Text>
</Pressable>
<View
testID="layout-view"
onLayout={onViewLayout}
style={{ width: expanded ? 180 : 120, height: 24, backgroundColor: "#eeeeee" }}
/>
<Text testID="layout-text" onLayout={onTextLayout}>
{expanded ? "Measure a much longer text label" : "Short label"}
</Text>
<TextInput
testID="layout-text-input"
onLayout={onInputLayout}
defaultValue="hi"
style={{ width: expanded ? 200 : 140, height: 32, borderWidth: 1 }}
/>
<Image
testID="layout-image"
onLayout={onImageLayout}
style={{ width: expanded ? 96 : 64, height: 32, backgroundColor: "#cccccc" }}
/>
<ScrollView
testID="layout-scroll"
onLayout={onScrollLayout}
style={{
flexGrow: 0,
flexShrink: 0,
width: expanded ? 210 : 150,
height: 40,
backgroundColor: "#eeeeee",
}}
>
<View style={{ width: expanded ? 210 : 150, height: 80 }} />
</ScrollView>
<Text testID="layout-results">{JSON.stringify(layouts)}</Text>
</View>
</View>
);
}
AppRegistry.registerComponent("Paseo", () => AppearanceRegression);
+7
View File
@@ -0,0 +1,7 @@
module.exports = function (api) {
api.cache(true);
return {
presets: [[require.resolve("babel-preset-expo"), { unstable_transformImportMeta: true }]],
plugins: [[require.resolve("react-native-unistyles/plugin"), { root: "../src" }]],
};
};
+4
View File
@@ -0,0 +1,4 @@
build/
.cache/
autolink/
target/
File diff suppressed because it is too large Load Diff
+63
View File
@@ -0,0 +1,63 @@
[package]
name = "react-native-gpui-paseo-gpui"
version = "0.1.0"
edition = "2021"
# Set CARGO_PROFILE_DEV_DEBUG=full to opt into full debug information.
[profile.dev]
debug = "line-tables-only"
split-debuginfo = "packed"
# Dependencies are optimized even in a dev build: GPUI rebuilds and paints the
# element tree on every frame, and they are only compiled once.
[profile.dev.package."*"]
debug = false
opt-level = 3
# The C++ bridge picks its CMake build type from this crate's opt-level, and a
# Release build of React Native has no dev server, inspector or Fast Refresh.
[profile.dev.package.rn-gpui-sys]
opt-level = 0
[profile.release]
debug = "line-tables-only"
# Cargo strips inside the linker, before dsymutil, so package-desktop preserves the
# Cargo dSYM and then strips. Full LTO: 2 MB smaller for 1.4x the build time.
strip = "none"
split-debuginfo = "packed"
lto = "fat"
codegen-units = 1
[build-dependencies]
rn-gpui-module-build = { path = "../node_modules/@react-native-gpui/core/ReactGpui/rn-gpui-module-build" }
serde_json = "1"
[features]
visual-capture = ["react-native-gpui/visual-capture"]
test-driver = ["react-native-gpui/test-driver"]
runtime-shaders = ["react-native-gpui/runtime-shaders"]
[dev-dependencies]
rn_gpui_enriched_markdown = { package = "rn-gpui-enriched-markdown", path = "../../../react-native-enriched-markdown/desktop" }
gpui = { git = "https://github.com/streetwriters/gpui-fast", rev = "1ad3cc3" }
gpui_platform = { git = "https://github.com/streetwriters/gpui-fast", rev = "1ad3cc3", features = [
"test-support",
] }
[dependencies]
serde_json = "1"
sha2 = "0.10"
rusqlite = { version = "0.38", features = ["bundled"] }
rn-gpui-module = { path = "../node_modules/@react-native-gpui/core/ReactGpui/rn-gpui-module" }
rn-gpui-autolink = { path = "autolink" }
react-native-gpui = { path = "../node_modules/@react-native-gpui/core/ReactGpui/rn-gpui" }
[patch.crates-io]
# Managed by @react-native-gpui/cli autolink; do not edit between these markers.
react-native-gpui = { path = "../node_modules/@react-native-gpui/core/ReactGpui/rn-gpui" }
rn-gpui-sys = { path = "../node_modules/@react-native-gpui/core/ReactGpui/rn-gpui-sys" }
rn-gpui-module = { path = "../node_modules/@react-native-gpui/core/ReactGpui/rn-gpui-module" }
rn-gpui-module-build = { path = "../node_modules/@react-native-gpui/core/ReactGpui/rn-gpui-module-build" }
gpui = { git = "https://github.com/streetwriters/gpui-fast", rev = "1ad3cc3" }
gpui_platform = { git = "https://github.com/streetwriters/gpui-fast", rev = "1ad3cc3" }
# End managed by autolink.
+172
View File
@@ -0,0 +1,172 @@
fn main() {
// Forwards the engine's Node-API exports out of this executable, which is
// what lets a stock `.node` addon resolve them on Windows.
//
// A DLL records every import as a name *plus the file it comes from*, and a
// node-gyp addon records "from `node.exe`" — Windows has no global symbol
// scope for it to fall back on. Node's own answer is that the host process
// exports the Node-API functions, so that is what this does: the executable
// re-exports each of the VM's `napi_*`/`node_api_*` names, forwarded to
// `hermesvm.dll`. Addons that use node-gyp's delay-load hook (the default)
// then reach this process instead of looking for `node.exe` on disk.
//
// It is a no-op on macOS and Linux, where an addon's imports resolve against
// whatever is already loaded and need no forwarding. Declare it once, before
// the module list; it does not depend on anything else in this file.
rn_gpui_module_build::forward_node_api_exports();
// App-local Rust TurboModules: list one entry per `src/Native*.ts` spec,
// for example `&["src/NativeGreeting.ts"]`. Their glue is generated into
// this crate's OUT_DIR, and main.rs registers the modules.
rn_gpui_module_build::generate(&["src/NativePaseoDesktop.ts"]);
let desktop_root = std::path::PathBuf::from(
std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set"),
);
// `app.json` names the app; `desktop/desktop.json` carries the identifier
// and everything else the packaging step needs. The loader the CLI uses is
// JavaScript, so this reads the same file directly and applies the two
// defaults it would apply.
let project_root = desktop_root
.parent()
.expect("desktop folder has a React Native project root");
let app_json_path = project_root.join("app.json");
println!("cargo:rerun-if-changed={}", app_json_path.display());
let app_json: serde_json::Value = serde_json::from_slice(
&std::fs::read(&app_json_path)
.unwrap_or_else(|error| panic!("read {}: {error}", app_json_path.display())),
)
.unwrap_or_else(|error| panic!("parse {}: {error}", app_json_path.display()));
let app_name = app_json["name"]
.as_str()
.filter(|name| !name.is_empty())
.expect("app.json must define a nonempty name");
if app_json["desktop"]
.as_object()
.is_some_and(|desktop| !desktop.is_empty())
{
panic!("move `app.json` desktop.* into `desktop/desktop.json` (see the README)");
}
let desktop_json_path = project_root.join("desktop/desktop.json");
println!("cargo:rerun-if-changed={}", desktop_json_path.display());
let desktop_json: serde_json::Value = std::fs::read(&desktop_json_path)
.ok()
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
.unwrap_or(serde_json::Value::Null);
let app_id = match desktop_json["identifier"].as_str() {
Some(identifier) if !identifier.is_empty() => identifier.to_string(),
_ => format!(
"com.example.{}",
app_name
.to_lowercase()
.chars()
.map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
.collect::<String>()
),
};
println!("cargo:rustc-env=RN_GPUI_APP_NAME={app_name}");
println!("cargo:rustc-env=RN_GPUI_APP_ID={app_id}");
// Only a debug build names the bundle it was developed against. A release
// binary must find the bundle beside its own executable, because the path
// baked in here is where this machine happened to build it — and on the
// machine the package is installed on, that path does not exist.
println!("cargo:rerun-if-env-changed=PROFILE");
if std::env::var("PROFILE").as_deref() == Ok("debug") {
println!(
"cargo:rustc-env=RN_GPUI_DEFAULT_BUNDLE={}",
desktop_root.join("build/index.bundle").display()
);
}
println!("cargo:rerun-if-env-changed=DEP_RN_GPUI_RUNTIME_RPATHS");
println!("cargo:rerun-if-env-changed=RN_GPUI_PACKAGING");
let Ok(paths) = std::env::var("DEP_RN_GPUI_RUNTIME_RPATHS") else {
return;
};
let dirs = paths.split('|').filter(|path| !path.is_empty());
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
stage_shared_libraries(dirs);
return;
}
// `RN_GPUI_PACKAGING` means this binary is about to be installed somewhere
// else, so only the relative rpaths belong in it. Keeping the absolute ones
// would let a packaged app load this build tree's libraries in preference to
// its own on the machine that built it — which hides exactly the packaging
// bugs the packaged run exists to catch.
let packaging = std::env::var("RN_GPUI_PACKAGING").is_ok();
if !packaging {
for path in dirs {
println!("cargo:rustc-link-arg=-Wl,-rpath,{path}");
}
}
emit_relocatable_rpaths(app_name);
}
/// rpaths that survive being installed somewhere else.
///
/// The absolute paths above let a development build run from this tree. A
/// packaged app is copied to another machine, where those paths do not exist,
/// so a release build also carries paths relative to the executable: the
/// layout the installers produce.
fn emit_relocatable_rpaths(app_name: &str) {
if std::env::var("PROFILE").as_deref() != Ok("release") {
return;
}
let os = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
let mut emit = |rpath: String| println!("cargo:rustc-link-arg=-Wl,-rpath,{rpath}");
match os.as_str() {
// An app bundle puts the executable in Contents/MacOS and the shipped
// libraries in Contents/Frameworks.
"macos" => emit("@executable_path/../Frameworks".into()),
// Linux installs the executable at `usr/bin` and ships its libraries
// under `usr/lib`:
// - the deb puts them in `usr/lib/<app>`;
// - an AppImage's libraries are flat in `usr/lib`, because that is the
// directory AppRun puts on the library path and the one linuxdeploy
// resolves dependencies from before the image is assembled.
// Both are covered, so one binary works in either layout.
"linux" => {
emit(format!("$ORIGIN/../lib/{app_name}"));
emit("$ORIGIN/../lib".into());
emit("$ORIGIN".into());
}
// Windows has no rpath: the DLLs are copied beside the executable.
_ => {}
}
}
/// Windows has no rpath: the loader finds a DLL next to the executable or on
/// `PATH`, so every directory the runtime reports as holding a shared library
/// (the Hermes binary directory in particular) is copied into the profile
/// directory that receives this app's executable. Without this the app builds
/// and then fails to start with "hermesvm.dll was not found".
fn stage_shared_libraries<'a>(dirs: impl Iterator<Item = &'a str>) {
let out_dir = std::path::PathBuf::from(std::env::var("OUT_DIR").expect("OUT_DIR is set"));
// <profile>/build/<package>-<hash>/out -> <profile>
let Some(profile_dir) = out_dir.ancestors().nth(3) else {
return;
};
for dir in dirs {
let Ok(entries) = std::fs::read_dir(dir) else {
continue;
};
for entry in entries.flatten() {
let source = entry.path();
let is_shared_library = source
.extension()
.and_then(|extension| extension.to_str())
.is_some_and(|extension| extension.eq_ignore_ascii_case("dll"));
if !is_shared_library {
continue;
}
let Some(name) = source.file_name() else {
continue;
};
println!("cargo:rerun-if-changed={}", source.display());
std::fs::copy(&source, profile_dir.join(name)).unwrap_or_else(|error| {
panic!("copy {} next to the executable: {error}", source.display())
});
}
}
}
+4
View File
@@ -0,0 +1,4 @@
{
"identifier": "sh.paseo.gpui",
"bundle": { "macos": { "minimumSystemVersion": "15.0" } }
}
@@ -0,0 +1,271 @@
use gpui::{
div, px, App, AppContext, Context, IntoElement, ParentElement, Render, Styled, Window,
WindowBounds, WindowOptions,
};
use react_native_gpui::DesktopAppConfig;
use rn_gpui_enriched_markdown::layout::{layout_document, LaidOutDocument};
use rn_gpui_enriched_markdown::model::MarkdownSnapshot;
use rn_gpui_enriched_markdown::render::render_document;
use std::ffi::{c_char, c_int, CStr, CString};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
extern "C" {
fn rn_gpui_markdown_bench_stages(
markdown: *const c_char,
is_gfm: bool,
style_json: *const c_char,
out_parse_ns: *mut f64,
out_highlight_ns: *mut f64,
out_serialize_ns: *mut f64,
out_json: *mut *mut c_char,
out_json_len: *mut usize,
) -> c_int;
fn rn_gpui_markdown_bench_free(ptr: *mut c_char);
}
struct BenchState {
render_doc_ns: f64,
}
struct BenchView {
doc: Arc<LaidOutDocument>,
state: Arc<Mutex<BenchState>>,
}
impl Render for BenchView {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let t0 = Instant::now();
let el = render_document(&self.doc, 1);
let elapsed_ns = t0.elapsed().as_secs_f64() * 1e9;
if let Ok(mut s) = self.state.lock() {
s.render_doc_ns = elapsed_ns;
}
div().w(px(720.0)).bg(gpui::rgb(0xffffff)).child(el)
}
}
const STYLE_JSON: &str = r##"{
"paragraph": { "fontSize": 15, "lineHeight": 21, "color": 4279900702, "marginBottom": 12 },
"h1": { "fontSize": 24, "lineHeight": 31, "fontWeight": "bold", "color": 4279900702, "marginBottom": 12 },
"h2": { "fontSize": 21, "lineHeight": 27, "fontWeight": "bold", "color": 4279900702, "marginBottom": 12 },
"h3": { "fontSize": 18, "lineHeight": 23, "fontWeight": "bold", "color": 4279900702, "marginBottom": 12 },
"list": { "fontSize": 15, "lineHeight": 21, "color": 4279900702, "bulletColor": 4285624698, "markerColor": 4285624698, "gapWidth": 7, "itemSpacing": 4, "marginLeft": 20, "marginBottom": 12 },
"blockquote": { "fontSize": 15, "lineHeight": 21, "color": 4279900702, "backgroundColor": 4294638330, "borderColor": 4293190887, "borderWidth": 3, "padding": 12, "gapWidth": 8, "marginBottom": 12 },
"link": { "color": 4280523094, "underline": false },
"code": { "fontFamily": "monospace", "fontScale": 0.8, "color": 4279900702, "backgroundColor": 4294243573 },
"codeBlock": {
"fontFamily": "monospace", "fontSize": 12, "lineHeight": 21, "color": 4279900702,
"backgroundColor": 4294243573, "borderColor": 4293190887, "borderRadius": 8, "padding": 12, "marginBottom": 12,
"syntaxColors": {
"keyword": 4294933362, "string": 4289058559, "comment": 4287337630, "number": 4286169343,
"type": 4294944343, "function": 4291995903, "operatorColor": 4294933362, "punctuation": 4286495103
}
},
"table": {
"fontSize": 15, "lineHeight": 21, "color": 4279900702,
"headerBackgroundColor": 4294243573, "headerTextColor": 4279900702,
"rowEvenBackgroundColor": 4294967295, "rowOddBackgroundColor": 4294638330,
"borderColor": 4293190887, "marginBottom": 12
}
}"##;
fn build_realistic_reply(target_bytes: usize) -> String {
let section_prose = "\n## Module Analysis and Data Flow\n\n\
The renderer translates snapshots from `packages/react-native-enriched-markdown/cpp/GpuiMarkdownBridge.cpp` into \
**GPUI elements** with *inline styles* and links such as [protocol docs](https://paseo.sh/docs/protocol). \
When a streaming token arrives, React commits the updated `markdown` string and re-measures the node.\n\n\
- Preserves AST structure for headings, paragraphs, emphasis, and `inline_code`\n\
- Highlights fenced code blocks using Tree-sitter grammars\n\
- Lays out GFM tables with measured column widths\n";
let section_code = "\n```ts\n\
export interface StreamDelta {\n\
readonly messageId: string;\n\
readonly seq: number;\n\
readonly chunk: string;\n\
}\n\n\
export function applyDelta(acc: Map<string, string>, delta: StreamDelta): string {\n\
const prev = acc.get(delta.messageId) ?? \"\";\n\
const next = prev + delta.chunk;\n\
acc.set(delta.messageId, next);\n\
return next;\n\
}\n\
```\n";
let section_table = "\n| Stage | Input | Output | Owner |\n\
| --- | --- | --- | --- |\n\
| Parse | Markdown UTF-8 | MD4C AST | C++ |\n\
| Highlight | Code lines | Token ranges | Tree-sitter |\n\
| Serialize | AST + Style | JSON string | folly::toJson |\n\
| Deserialize | JSON string | MarkdownSnapshot | serde_json |\n\
| Layout | Snapshot + width | LaidOutDocument | layout.rs |\n\
| Paint | LaidOutDocument | GPUI scene | render.rs + gpui |\n";
let mut out = String::from("# Architecture Overview\n\nStreaming reply benchmark fixture with realistic prose, code blocks, lists, and a table.\n");
out.push_str(section_table);
let mut i = 0usize;
while out.len() < target_bytes {
out.push_str(section_prose);
if i % 2 == 0 {
out.push_str(section_code);
}
if i % 5 == 4 && out.len() + section_table.len() < target_bytes {
out.push_str(section_table);
}
i += 1;
}
out
}
fn median_ms(samples: &mut [f64]) -> f64 {
samples.sort_by(|a, b| a.total_cmp(b));
let mid = samples.len() / 2;
if samples.len() % 2 == 0 {
((samples[mid - 1] + samples[mid]) * 0.5) / 1e6
} else {
samples[mid] / 1e6
}
}
fn mean_ms(samples: &[f64]) -> f64 {
let sum: f64 = samples.iter().sum();
(sum / samples.len() as f64) / 1e6
}
fn run_bench_on_app(cx: &mut App) {
let bench_state = Arc::new(Mutex::new(BenchState { render_doc_ns: 0.0 }));
let bench_state_init = bench_state.clone();
let window = cx
.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(gpui::Bounds::centered(
None,
gpui::size(px(800.0), px(1200.0)),
cx,
))),
..Default::default()
},
|_, cx| {
cx.new(|_| BenchView {
doc: Arc::new(LaidOutDocument::default()),
state: bench_state_init,
})
},
)
.unwrap();
let _ = cx.update_window(window.into(), |_, window, cx| {
window.draw(cx).clear(cx);
});
let style_c = CString::new(STYLE_JSON).unwrap();
for &(label, target_bytes, iters) in &[
("5 KB", 5 * 1024usize, 25usize),
("20 KB", 20 * 1024usize, 15usize),
("100 KB", 100 * 1024usize, 7usize),
] {
let base = build_realistic_reply(target_bytes);
let actual_bytes = base.len();
let mut parse_s = Vec::with_capacity(iters);
let mut hl_s = Vec::with_capacity(iters);
let mut ser_s = Vec::with_capacity(iters);
let mut deser_s = Vec::with_capacity(iters);
let mut layout_s = Vec::with_capacity(iters);
let mut paint_s = Vec::with_capacity(iters);
let mut build_el_s = Vec::with_capacity(iters);
for step in 0..=iters {
let md = if step == 0 {
base.clone()
} else {
format!("{base}\nStreamed token chunk #{step}.")
};
let md_c = CString::new(md).unwrap();
let mut parse_ns = 0.0f64;
let mut hl_ns = 0.0f64;
let mut ser_ns = 0.0f64;
let mut out_ptr: *mut c_char = std::ptr::null_mut();
let mut out_len: usize = 0;
let rc = unsafe {
rn_gpui_markdown_bench_stages(
md_c.as_ptr(),
true,
style_c.as_ptr(),
&mut parse_ns,
&mut hl_ns,
&mut ser_ns,
&mut out_ptr,
&mut out_len,
)
};
assert_eq!(rc, 0, "C++ bench failed");
let json = unsafe { CStr::from_ptr(out_ptr) }
.to_str()
.unwrap()
.to_owned();
unsafe { rn_gpui_markdown_bench_free(out_ptr) };
let t_deser = Instant::now();
let snapshot: MarkdownSnapshot = serde_json::from_str(&json).unwrap();
let deser_ns = t_deser.elapsed().as_secs_f64() * 1e9;
let t_layout = Instant::now();
let doc = Arc::new(layout_document(&snapshot, Some(680.0)));
let layout_ns = t_layout.elapsed().as_secs_f64() * 1e9;
let mut paint_elapsed = Duration::ZERO;
let _ = window.update(cx, |v, _, cx| {
v.doc = doc.clone();
cx.notify();
});
let _ = cx.update_window(window.into(), |_, window, cx| {
let t_paint = Instant::now();
window.refresh();
window.draw(cx).clear(cx);
paint_elapsed = t_paint.elapsed();
});
let render_doc_ns = bench_state.lock().map(|s| s.render_doc_ns).unwrap_or(0.0);
if step > 0 {
parse_s.push(parse_ns);
hl_s.push(hl_ns);
ser_s.push(ser_ns);
deser_s.push(deser_ns);
layout_s.push(layout_ns);
paint_s.push(paint_elapsed.as_secs_f64() * 1e9);
build_el_s.push(render_doc_ns);
}
}
let p_med = median_ms(&mut parse_s);
let h_med = median_ms(&mut hl_s);
let s_med = median_ms(&mut ser_s);
let d_med = median_ms(&mut deser_s);
let l_med = median_ms(&mut layout_s);
let pt_med = median_ms(&mut paint_s);
let total_med = p_med + h_med + s_med + d_med + l_med + pt_med;
println!(
"SIZE={label} bytes={actual_bytes} iters={iters} | MEDIAN_MS: parse={p_med:.3} highlight={h_med:.3} serialize={s_med:.3} deserialize={d_med:.3} layout={l_med:.3} paint={pt_med:.3} (build_el={:.3}) total={total_med:.3} | MEAN_MS: parse={:.3} highlight={:.3} serialize={:.3} deserialize={:.3} layout={:.3} paint={:.3}",
median_ms(&mut build_el_s),
mean_ms(&parse_s),
mean_ms(&hl_s),
mean_ms(&ser_s),
mean_ms(&deser_s),
mean_ms(&layout_s),
mean_ms(&paint_s),
);
}
std::process::exit(0);
}
fn main() {
rn_gpui_autolink::ensure_linked();
let config =
DesktopAppConfig::from_env_with_defaults(env!("RN_GPUI_APP_NAME"), env!("RN_GPUI_APP_ID"))
.window_title("Markdown Bench")
.window_size(800.0, 1200.0)
.on_app_ready(run_bench_on_app);
react_native_gpui::run_with(config);
}
+77
View File
@@ -0,0 +1,77 @@
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;
@@ -0,0 +1,9 @@
import { TurboModuleRegistry, type TurboModule } from "react-native";
export interface Spec extends TurboModule {
sqlite(sql: string, params: string): string;
locale(): string;
timezone(): string;
sha256(text: string): string;
randomBytes(length: number): Array<number>;
}
export default TurboModuleRegistry.getEnforcing<Spec>("PaseoDesktop");
+29
View File
@@ -0,0 +1,29 @@
rn_gpui_module::include_specs!();
mod services;
fn main() {
react_native_gpui::register_module(native_paseo_desktop_module::<services::PaseoDesktop>());
rn_gpui_autolink::ensure_linked();
// A debug build knows where its own bundle is; a release build does not, and
// must not: the path would name the machine that built it. A packaged release
// app resolves the bundle beside its executable instead.
#[cfg(debug_assertions)]
if std::env::var_os("RN_GPUI_BUNDLE").is_none() {
std::env::set_var("RN_GPUI_BUNDLE", env!("RN_GPUI_DEFAULT_BUNDLE"));
}
let config = react_native_gpui::DesktopAppConfig::from_env_with_defaults(
env!("RN_GPUI_APP_NAME"),
env!("RN_GPUI_APP_ID"),
)
.window_title("Paseo GPUI")
.window_size(1024.0, 768.0)
.dev_menu(true)
.configure_window(|options| {
// GPUI window options are public: titlebar, resizability, display,
// decorations, min size, and other native window behavior.
options.is_resizable = true;
});
react_native_gpui::run_with(config);
}
+174
View File
@@ -0,0 +1,174 @@
use crate::{NativePaseoDesktopEvents, NativePaseoDesktopSpec};
use rn_gpui_module::ModuleError;
use std::io::Read;
pub struct PaseoDesktop {
database: std::sync::Mutex<Option<rusqlite::Connection>>,
}
impl PaseoDesktop {
fn database(
&self,
) -> Result<std::sync::MutexGuard<'_, Option<rusqlite::Connection>>, ModuleError> {
let mut guard = self
.database
.lock()
.map_err(|e| ModuleError::new(e.to_string()))?;
if guard.is_none() {
let base = std::env::var("XDG_DATA_HOME")
.map(std::path::PathBuf::from)
.unwrap_or_else(|_| {
std::path::PathBuf::from(std::env::var("HOME").expect("HOME is set"))
.join(".local/share")
});
let dir = base.join("paseo-gpui");
std::fs::create_dir_all(&dir).map_err(|e| ModuleError::new(e.to_string()))?;
*guard = Some(
rusqlite::Connection::open(dir.join("replica.db"))
.map_err(|e| ModuleError::new(e.to_string()))?,
);
}
Ok(guard)
}
}
impl NativePaseoDesktopSpec for PaseoDesktop {
fn new(_events: NativePaseoDesktopEvents) -> Self {
Self {
database: std::sync::Mutex::new(None),
}
}
fn sqlite(&self, sql: String, params: String) -> Result<String, ModuleError> {
let fail = |e: rusqlite::Error| ModuleError::new(e.to_string());
let db = self.database()?;
let db = db.as_ref().unwrap();
if params == "batch" {
db.execute_batch(&sql).map_err(fail)?;
return Ok("[]".into());
}
let values: Vec<serde_json::Value> =
serde_json::from_str(&params).map_err(|e| ModuleError::new(e.to_string()))?;
let values: Vec<rusqlite::types::Value> = values
.into_iter()
.map(|v| match v {
serde_json::Value::Null => rusqlite::types::Value::Null,
serde_json::Value::String(v) => rusqlite::types::Value::Text(v),
serde_json::Value::Number(v) => v
.as_i64()
.map(rusqlite::types::Value::Integer)
.unwrap_or_else(|| rusqlite::types::Value::Real(v.as_f64().unwrap())),
_ => rusqlite::types::Value::Text(v.to_string()),
})
.collect();
let mut stmt = db.prepare(&sql).map_err(fail)?;
let names: Vec<String> = stmt.column_names().into_iter().map(str::to_owned).collect();
let mut rows = stmt
.query(rusqlite::params_from_iter(values))
.map_err(fail)?;
let mut results = Vec::new();
while let Some(row) = rows.next().map_err(fail)? {
let mut object = serde_json::Map::new();
for (index, name) in names.iter().enumerate() {
let value = match row.get_ref(index).map_err(fail)? {
rusqlite::types::ValueRef::Null => serde_json::Value::Null,
rusqlite::types::ValueRef::Integer(v) => v.into(),
rusqlite::types::ValueRef::Real(v) => serde_json::json!(v),
rusqlite::types::ValueRef::Text(v) => {
String::from_utf8_lossy(v).into_owned().into()
}
rusqlite::types::ValueRef::Blob(_) => {
return Err(ModuleError::new(
"Replica store does not support blob columns",
))
}
};
object.insert(name.clone(), value);
}
results.push(object);
}
serde_json::to_string(&results).map_err(|e| ModuleError::new(e.to_string()))
}
fn timezone(&self) -> Result<String, ModuleError> {
if let Ok(zone) = std::env::var("TZ") {
if !zone.is_empty() {
return Ok(zone.trim_start_matches(':').into());
}
}
if let Ok(path) = std::fs::read_link("/etc/localtime") {
if let Some((_, zone)) = path.to_string_lossy().split_once("/zoneinfo/") {
return Ok(zone.into());
}
}
Ok(std::fs::read_to_string("/etc/timezone")
.map(|s| s.trim().into())
.unwrap_or_else(|_| "UTC".into()))
}
fn locale(&self) -> Result<String, ModuleError> {
Ok(["LC_ALL", "LC_MESSAGES", "LANG"]
.iter()
.find_map(|key| std::env::var(key).ok().filter(|v| !v.is_empty()))
.unwrap_or_else(|| "en_US.UTF-8".into()))
}
fn sha256(&self, text: String) -> Result<String, ModuleError> {
use sha2::{Digest, Sha256};
Ok(format!("{:x}", Sha256::digest(text.as_bytes())))
}
fn random_bytes(&self, length: f64) -> Result<Vec<f64>, ModuleError> {
if !length.is_finite() || length < 0.0 || length > 65536.0 || length.fract() != 0.0 {
return Err(ModuleError::new("Invalid random byte count"));
}
let mut bytes = vec![0u8; length as usize];
std::fs::File::open("/dev/urandom")
.and_then(|mut source| source.read_exact(&mut bytes))
.map_err(|error| ModuleError::new(error.to_string()))?;
Ok(bytes.into_iter().map(f64::from).collect())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn service() -> PaseoDesktop {
PaseoDesktop {
database: std::sync::Mutex::new(Some(rusqlite::Connection::open_in_memory().unwrap())),
}
}
#[test]
fn crypto_matches_sha256_and_bounds_random_requests() {
let service = service();
assert_eq!(
service.sha256("abc".into()).unwrap(),
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
);
assert_eq!(service.random_bytes(32.0).unwrap().len(), 32);
assert!(service.random_bytes(65537.0).is_err());
assert!(service.random_bytes(-1.0).is_err());
}
#[test]
fn replica_transactions_bind_values_and_roll_back() {
let service = service();
service
.sqlite(
"CREATE TABLE rows (key TEXT PRIMARY KEY, value TEXT);".into(),
"batch".into(),
)
.unwrap();
service
.sqlite(
"INSERT INTO rows VALUES (?, ?)".into(),
r#"["key","quoted ' value"]"#.into(),
)
.unwrap();
service
.sqlite(
"BEGIN IMMEDIATE; DELETE FROM rows; ROLLBACK;".into(),
"batch".into(),
)
.unwrap();
let result = service
.sqlite("SELECT key, value FROM rows".into(), "[]".into())
.unwrap();
assert_eq!(
serde_json::from_str::<serde_json::Value>(&result).unwrap(),
serde_json::json!([{"key":"key","value":"quoted ' value"}])
);
}
}
+10
View File
@@ -0,0 +1,10 @@
/* 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);
@@ -0,0 +1,401 @@
/* oxlint-disable react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop -- Minimal markdown native regression scene. */
import React, { useCallback, useState } from "react";
import { AppRegistry, Pressable, Text, View } from "react-native";
import { EnrichedMarkdownText } from "react-native-enriched-markdown";
const BASE_MARKDOWN = `# Phase 1 Heading
## Subhead \`code\`
**bold**, *italic*, ~~struck~~, [docs](https://example.com/guide).
> Blockquote note
- Bullet one
- Bullet two
1. Ordered one
2. Ordered two
- [x] Done task
- [ ] Open task
\`\`\`ts
const n: number = 42;
function hi(s: string): string {
return \`Hi \${s}\`;
}
\`\`\`
| Component | Status |
| --- | --- |
| Parser | Ready |`;
const STREAM_APPEND = `
### Streamed
Appended **live** and [next](https://example.com/streamed).`;
const MARKDOWN_STYLE = {
paragraph: {
fontSize: 13,
lineHeight: 17,
color: "#111827",
marginBottom: 4,
},
h1: {
fontSize: 19,
lineHeight: 23,
fontWeight: "700",
color: "#0f172a",
marginBottom: 4,
},
h2: {
fontSize: 16,
lineHeight: 20,
fontWeight: "600",
color: "#1e293b",
marginTop: 2,
marginBottom: 4,
},
h3: {
fontSize: 14,
lineHeight: 18,
fontWeight: "600",
color: "#1e293b",
marginTop: 2,
marginBottom: 2,
},
h5: {
fontSize: 13,
lineHeight: 17,
fontWeight: "600",
color: "#334155",
marginBottom: 2,
},
strong: { fontWeight: "700" },
em: { fontStyle: "italic" },
strikethrough: { textDecorationLine: "line-through", color: "#64748b" },
code: {
fontFamily: "monospace",
fontScale: 0.85,
color: "#0f172a",
backgroundColor: "#e2e8f0",
},
link: {
color: "#2563eb",
underline: true,
},
list: {
fontSize: 13,
lineHeight: 17,
color: "#111827",
bulletColor: "#475569",
markerColor: "#475569",
bulletSize: 5,
gapWidth: 6,
marginLeft: 14,
itemSpacing: 1,
marginBottom: 4,
},
taskList: {
checkedColor: "#2563eb",
borderColor: "#475569",
checkmarkColor: "#ffffff",
checkedTextColor: "#64748b",
checkedStrikethrough: true,
checkboxSize: 13,
},
blockquote: {
fontSize: 13,
lineHeight: 17,
color: "#1e293b",
backgroundColor: "#eff6ff",
borderColor: "#2563eb",
borderWidth: 4,
padding: 6,
gapWidth: 6,
marginBottom: 4,
},
codeBlock: {
fontFamily: "monospace",
fontSize: 11,
lineHeight: 15,
color: "#e2e8f0",
backgroundColor: "#0f172a",
borderColor: "#334155",
borderWidth: 1,
borderRadius: 6,
padding: 6,
marginBottom: 4,
syntaxColors: {
keyword: "#c084fc",
string: "#86efac",
comment: "#94a3b8",
number: "#fbbf24",
type: "#38bdf8",
function: "#60a5fa",
operator: "#f472b6",
punctuation: "#cbd5e1",
},
},
table: {
fontSize: 12,
lineHeight: 16,
color: "#111827",
headerFontWeight: "700",
headerBackgroundColor: "#dbeafe",
headerTextColor: "#0f172a",
rowEvenBackgroundColor: "#ffffff",
rowOddBackgroundColor: "#f8fafc",
borderColor: "#2563eb",
borderWidth: 1,
borderRadius: 5,
cellPaddingHorizontal: 6,
cellPaddingVertical: 3,
marginBottom: 4,
},
};
function MarkdownRegression() {
const [streamed, setStreamed] = useState(false);
const [pressedLink, setPressedLink] = useState("none");
const [taskEvent, setTaskEvent] = useState("none");
const [codeEvent, setCodeEvent] = useState("none");
const [layoutText, setLayoutText] = useState("{}");
const handleLinkPress = useCallback((event) => {
setPressedLink(event?.url ?? "missing");
}, []);
const handleTaskPress = useCallback((event) => {
setTaskEvent(`${event?.index}:${event?.checked}:${event?.text}`);
}, []);
const handleCodePress = useCallback((event) => {
setCodeEvent(`${event?.language}:${String(event?.code ?? "").trim().length}`);
}, []);
const handleLayout = useCallback((event) => {
const layout = event?.nativeEvent?.layout;
if (layout) setLayoutText(JSON.stringify(layout));
}, []);
const markdown = streamed ? `${BASE_MARKDOWN}${STREAM_APPEND}` : BASE_MARKDOWN;
return (
<View
style={{ flex: 1, flexDirection: "row", padding: 8, gap: 10, backgroundColor: "#ffffff" }}
>
<View style={{ width: 320, gap: 4, backgroundColor: "#ffffff" }}>
<View style={{ flexDirection: "row", alignItems: "center", gap: 6, flexWrap: "wrap" }}>
<EnrichedMarkdownText
testID="markdown-link-target"
flavor="github"
markdown="[Open docs](https://example.com/docs)"
markdownStyle={MARKDOWN_STYLE}
onLinkPress={handleLinkPress}
allowTrailingMargin={false}
style={{ alignSelf: "flex-start" }}
/>
<Pressable
testID="markdown-stream-next"
onPress={() => setStreamed(true)}
style={{
width: 82,
height: 20,
backgroundColor: "#e2e8f0",
justifyContent: "center",
alignItems: "center",
}}
>
<Text style={{ fontSize: 12 }}>Stream Next</Text>
</Pressable>
<Text testID="pressed-link" style={{ fontSize: 11 }}>
{pressedLink}
</Text>
<Text testID="task-event" style={{ fontSize: 11 }}>
{taskEvent}
</Text>
<Text testID="code-event" style={{ fontSize: 11 }}>
{codeEvent}
</Text>
</View>
<Text testID="markdown-layout" style={{ fontSize: 10 }}>
{layoutText}
</Text>
<EnrichedMarkdownText
testID="markdown-view"
flavor="github"
markdown={markdown}
md4cFlags={{ underline: true, latexMath: true }}
markdownStyle={MARKDOWN_STYLE}
onLinkPress={handleLinkPress}
onLayout={handleLayout}
allowTrailingMargin={false}
/>
</View>
<View style={{ width: 320, gap: 3, backgroundColor: "#ffffff" }}>
<View style={{ flexDirection: "row", gap: 6, backgroundColor: "#ffffff" }}>
<View testID="probe-text-plain" style={{ backgroundColor: "#ffffff" }}>
<Text style={{ fontSize: 13, color: "#111827" }}>Sample</Text>
</View>
<View testID="probe-text-bold" style={{ backgroundColor: "#ffffff" }}>
<Text style={{ fontSize: 13, fontWeight: "700", color: "#111827" }}>Sample</Text>
</View>
<View testID="probe-text-italic" style={{ backgroundColor: "#ffffff" }}>
<Text style={{ fontSize: 13, fontStyle: "italic", color: "#111827" }}>Sample</Text>
</View>
</View>
<View style={{ flexDirection: "row", gap: 6, alignItems: "flex-start" }}>
<View testID="block-h1" style={{ width: 155, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
testID="block-h1-md"
flavor="github"
markdown="# Heading A"
markdownStyle={MARKDOWN_STYLE}
allowTrailingMargin={false}
/>
</View>
<View testID="block-h5" style={{ width: 155, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
testID="block-h5-md"
flavor="github"
markdown="##### Heading A"
markdownStyle={MARKDOWN_STYLE}
allowTrailingMargin={false}
/>
</View>
</View>
<View style={{ flexDirection: "row", gap: 6 }}>
<View testID="block-emphasis-plain" style={{ width: 155, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
flavor="github"
markdown="alpha beta gamma"
markdownStyle={MARKDOWN_STYLE}
allowTrailingMargin={false}
/>
</View>
<View testID="block-emphasis-styled" style={{ width: 155, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
flavor="github"
markdown="**alpha** *beta* ~~gamma~~"
markdownStyle={MARKDOWN_STYLE}
allowTrailingMargin={false}
/>
</View>
</View>
<View style={{ flexDirection: "row", gap: 6 }}>
<View testID="block-inline-code-plain" style={{ width: 155, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
flavor="github"
markdown="use code_val"
markdownStyle={MARKDOWN_STYLE}
allowTrailingMargin={false}
/>
</View>
<View testID="block-inline-code" style={{ width: 155, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
flavor="github"
markdown={"use `code_val`"}
markdownStyle={MARKDOWN_STYLE}
allowTrailingMargin={false}
/>
</View>
</View>
<View style={{ flexDirection: "row", gap: 6 }}>
<View testID="block-ul" style={{ width: 100, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
flavor="github"
markdown={"- One\n- Two"}
markdownStyle={MARKDOWN_STYLE}
allowTrailingMargin={false}
/>
</View>
<View testID="block-ol-1" style={{ width: 100, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
flavor="github"
markdown={"1. One\n2. Two"}
markdownStyle={MARKDOWN_STYLE}
allowTrailingMargin={false}
/>
</View>
<View testID="block-ol-8" style={{ width: 100, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
flavor="github"
markdown={"8. One\n9. Two"}
markdownStyle={MARKDOWN_STYLE}
allowTrailingMargin={false}
/>
</View>
</View>
<View style={{ flexDirection: "row", gap: 6 }}>
<View testID="block-task-checked" style={{ width: 132, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
flavor="github"
markdown="- [x] Done task"
markdownStyle={MARKDOWN_STYLE}
allowTrailingMargin={false}
/>
</View>
<View testID="block-task-unchecked" style={{ width: 132, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
flavor="github"
markdown="- [ ] Open task"
markdownStyle={MARKDOWN_STYLE}
allowTrailingMargin={false}
/>
</View>
<EnrichedMarkdownText
testID="block-task-toggle-md"
flavor="github"
markdown="- [ ] Ok"
markdownStyle={MARKDOWN_STYLE}
enableTaskListItemToggle={true}
onTaskListItemPress={handleTaskPress}
allowTrailingMargin={false}
style={{ width: 44, height: 17 }}
/>
</View>
<View testID="block-blockquote" style={{ width: 320, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
flavor="github"
markdown="> Quoted note"
markdownStyle={MARKDOWN_STYLE}
allowTrailingMargin={false}
/>
</View>
<View testID="block-code" style={{ width: 320, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
testID="block-code-md"
flavor="github"
markdown={"```ts\nconst n: number = 42;\n```"}
markdownStyle={MARKDOWN_STYLE}
onCodeBlockPress={handleCodePress}
allowTrailingMargin={false}
/>
</View>
<View testID="block-table" style={{ width: 320, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
flavor="github"
markdown={"| ColA | ColB |\n| --- | --- |\n| Left | Right |"}
markdownStyle={MARKDOWN_STYLE}
allowTrailingMargin={false}
/>
</View>
</View>
</View>
);
}
AppRegistry.registerComponent("Paseo", () => MarkdownRegression);
+341
View File
@@ -0,0 +1,341 @@
import { afterAll, beforeAll, expect, test } from "vitest";
import sharp from "sharp";
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import path from "node:path";
const endpoint = process.env.PASEO_GPUI_TEST_URL;
const token = process.env.PASEO_GPUI_TEST_TOKEN;
const markdownFixture = process.env.PASEO_GPUI_TEST_SCENE === "markdown";
const driverLogPath = process.env.PASEO_GPUI_DRIVER_LOG;
interface Node {
tag: number;
component: string;
testID: string;
text: string;
frame?: [number, number, number, number];
children?: Node[];
}
let socket: WebSocket;
let nextId = 0;
const pending = new Map<number, { resolve(value: unknown): void; reject(error: Error): void }>();
function request<T = unknown>(method: string, params: Record<string, unknown> = {}): Promise<T> {
const id = ++nextId;
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
pending.delete(id);
reject(new Error(`GPUI ${method} timed out`));
}, 15_000);
pending.set(id, {
resolve: (value) => {
clearTimeout(timer);
resolve(value as T);
},
reject: (error) => {
clearTimeout(timer);
reject(error);
},
});
socket.send(JSON.stringify({ jsonrpc: "2.0", id, method, params: { ...params, token } }));
});
}
function flatten(node: Node): Node[] {
return [node, ...(node.children ?? []).flatMap(flatten)];
}
async function nodes() {
return (await request<{ children: Node[] }>("tree")).children.flatMap(flatten);
}
async function nodeWithId(testID: string) {
await expect
.poll(async () => {
const node = (await nodes()).find((item) => item.testID === testID);
return (node?.frame?.[2] ?? 0) > 0 && (node?.frame?.[3] ?? 0) > 0;
})
.toBe(true);
return (await nodes()).find((node) => node.testID === testID)!;
}
beforeAll(async () => {
if (!endpoint) return;
if (!token) throw new Error("PASEO_GPUI_TEST_TOKEN is required");
socket = new WebSocket(endpoint);
await new Promise<void>((resolve, reject) => {
socket.addEventListener("open", () => resolve(), { once: true });
socket.addEventListener("error", () => reject(new Error("GPUI driver connection failed")), {
once: true,
});
});
socket.addEventListener("message", (event) => {
const response = JSON.parse(String(event.data));
const waiter = pending.get(response.id);
if (!waiter) return;
pending.delete(response.id);
const error = response.error ?? response.result?.error;
if (error) waiter.reject(new Error(JSON.stringify(error)));
else waiter.resolve(response.result);
});
await new Promise((r) => setTimeout(r, 800));
});
afterAll(() => socket?.close());
async function captureRaw(tag: number) {
let png: string | undefined;
await expect
.poll(
async () => {
try {
const res = await request<{ png: string }>("screenshot", { tag });
png = res.png;
return true;
} catch {
return false;
}
},
{ timeout: 10_000, interval: 100 },
)
.toBe(true);
const bytes = Buffer.from(png!, "base64");
const { data, info } = await sharp(bytes)
.removeAlpha()
.raw()
.toBuffer({ resolveWithObject: true });
return { bytes, data, width: info.width, height: info.height, channels: info.channels };
}
function diffPixelCount(
a: { data: Buffer; width: number; height: number; channels: number },
b: { data: Buffer; width: number; height: number; channels: number },
xMax = Math.min(a.width, b.width),
) {
const w = Math.min(a.width, b.width, xMax);
const h = Math.min(a.height, b.height);
let diff = 0;
for (let y = 0; y < h; y++) {
for (let x = 0; x < w; x++) {
const ia = (y * a.width + x) * a.channels;
const ib = (y * b.width + x) * b.channels;
if (
Math.abs(a.data[ia]! - b.data[ib]!) > 12 ||
Math.abs(a.data[ia + 1]! - b.data[ib + 1]!) > 12 ||
Math.abs(a.data[ia + 2]! - b.data[ib + 2]!) > 12
) {
diff++;
}
}
}
return diff;
}
function countMatchingPixels(
img: { data: Buffer; width: number; height: number; channels: number },
pred: (r: number, g: number, b: number, x: number, y: number) => boolean,
) {
let count = 0;
for (let y = 0; y < img.height; y++) {
for (let x = 0; x < img.width; x++) {
const i = (y * img.width + x) * img.channels;
if (pred(img.data[i]!, img.data[i + 1]!, img.data[i + 2]!, x, y)) {
count++;
}
}
}
return count;
}
test.skipIf(!endpoint || !markdownFixture)(
"RN <Text> bold and italic probe matches renderer font resolution",
async () => {
const plain = await captureRaw((await nodeWithId("probe-text-plain")).tag);
const bold = await captureRaw((await nodeWithId("probe-text-bold")).tag);
const italic = await captureRaw((await nodeWithId("probe-text-italic")).tag);
const boldDiff = diffPixelCount(plain, bold);
const italicDiff = diffPixelCount(plain, italic);
console.log(
`[probe-text] plain=${plain.width}x${plain.height} boldDiff=${boldDiff} italicDiff=${italicDiff}`,
);
expect(bold.width).toBeGreaterThan(20);
},
20_000,
);
test.skipIf(!endpoint || !markdownFixture)(
"EnrichedMarkdown renders every Phase 1 block type through caller interfaces and asserts regression.png",
async () => {
const view = await nodeWithId("markdown-view");
expect(view.component).toBe("EnrichedMarkdown");
expect(view.frame?.[2] ?? 0).toBeGreaterThan(200);
expect(view.frame?.[3] ?? 0).toBeGreaterThan(250);
const layoutNode = await nodeWithId("markdown-layout");
const initialLayout = JSON.parse(layoutNode.text) as { height?: number; width?: number };
expect(initialLayout.width ?? 0).toBeGreaterThan(200);
expect(initialLayout.height ?? 0).toBeGreaterThan(250);
// 1. Headings scale vertically between H1 and H5.
const h1Node = await nodeWithId("block-h1-md");
const h5Node = await nodeWithId("block-h5-md");
expect(h1Node.frame?.[3] ?? 0).toBeGreaterThan((h5Node.frame?.[3] ?? 0) + 4);
// 2. Emphasis + strikethrough visibly alter rendered ink vs plain prose.
const empPlain = await captureRaw((await nodeWithId("block-emphasis-plain")).tag);
const empStyled = await captureRaw((await nodeWithId("block-emphasis-styled")).tag);
expect(diffPixelCount(empPlain, empStyled)).toBeGreaterThan(30);
// 3. Inline code paints its #e2e8f0 pill background and keeps distinct glyph pixels.
const codePlain = await captureRaw((await nodeWithId("block-inline-code-plain")).tag);
const codeStyled = await captureRaw((await nodeWithId("block-inline-code")).tag);
const pillBg = (r: number, g: number, b: number) =>
Math.abs(r - 0xe2) <= 8 && Math.abs(g - 0xe8) <= 8 && Math.abs(b - 0xf0) <= 8 && b - r >= 6;
expect(countMatchingPixels(codePlain, pillBg)).toBeLessThan(15);
expect(countMatchingPixels(codeStyled, pillBg)).toBeGreaterThan(150);
// 4. Unordered and ordered lists paint distinct gutter markers.
const ulImg = await captureRaw((await nodeWithId("block-ul")).tag);
const ulGutterX = Math.round(ulImg.width * 0.28);
const ulGutterInk = countMatchingPixels(
ulImg,
(r, g, b, x) => x < ulGutterX && r < 140 && g < 140 && b < 140,
);
expect(ulGutterInk).toBeGreaterThan(12);
const ol1 = await captureRaw((await nodeWithId("block-ol-1")).tag);
const ol8 = await captureRaw((await nodeWithId("block-ol-8")).tag);
expect(diffPixelCount(ol1, ol8, Math.round(ol1.width * 0.3))).toBeGreaterThan(10);
// 5. Task lists paint checked vs unchecked state and toggle via caller event.
const taskChecked = await captureRaw((await nodeWithId("block-task-checked")).tag);
const taskUnchecked = await captureRaw((await nodeWithId("block-task-unchecked")).tag);
const taskGutterX = Math.round(taskChecked.width * 0.22);
const accentBlue = (r: number, g: number, b: number, x: number) =>
x < taskGutterX && b - r > 50 && r < 80;
expect(countMatchingPixels(taskChecked, accentBlue)).toBeGreaterThan(40);
expect(countMatchingPixels(taskUnchecked, accentBlue)).toBe(0);
const taskToggleNode = await nodeWithId("block-task-toggle-md");
expect(await request("click", { tag: taskToggleNode.tag })).toEqual({ clicked: true });
await expect.poll(async () => (await nodeWithId("task-event")).text).toBe("0:true:Ok");
// 6. Blockquote paints left accent bar and tinted background.
const bqImg = await captureRaw((await nodeWithId("block-blockquote")).tag);
const bqBarX = Math.max(24, Math.round(bqImg.width * 0.08));
const bqBar = countMatchingPixels(bqImg, (r, g, b, x) => x < bqBarX && b - r > 80 && r < 80);
const bqFill = countMatchingPixels(
bqImg,
(r, g, b) => Math.abs(r - 0xef) < 12 && Math.abs(g - 0xf6) < 12 && b > 240,
);
expect(bqBar).toBeGreaterThan(40);
expect(bqFill).toBeGreaterThan(400);
// 7. Code block paints dark card, TypeScript header band, syntax-highlighted tokens, and fires onCodeBlockPress.
const cbImg = await captureRaw((await nodeWithId("block-code")).tag);
const cbSplitY = Math.round(cbImg.height * 0.42);
const cbDarkBg = countMatchingPixels(cbImg, (r, g, b) => r < 30 && g < 40 && b < 70);
const cbHeaderInk = countMatchingPixels(
cbImg,
(r, g, b, _x, y) => y < cbSplitY && (r > 90 || g > 90 || b > 100),
);
const cbSyntaxColors = countMatchingPixels(
cbImg,
(r, g, b, _x, y) =>
y >= cbSplitY &&
((r > 150 && b > 200 && g < 180) || // purple keyword (#c084fc)
(b > 200 && g > 150 && r < 120) || // cyan type (#38bdf8)
(r > 200 && g > 150 && b < 110)), // amber number (#fbbf24)
);
expect(cbDarkBg).toBeGreaterThan(2000);
expect(cbHeaderInk).toBeGreaterThan(25);
expect(cbSyntaxColors).toBeGreaterThan(30);
const codeNode = await nodeWithId("block-code-md");
expect(await request("click", { tag: codeNode.tag })).toEqual({ clicked: true });
await expect.poll(async () => (await nodeWithId("code-event")).text).toBe("ts:21");
// 8. Table paints header tint and blue border.
const tableImg = await captureRaw((await nodeWithId("block-table")).tag);
const tableHeaderFill = countMatchingPixels(
tableImg,
(r, g, b) => Math.abs(r - 0xdb) < 16 && Math.abs(g - 0xea) < 16 && b > 240,
);
const tableBorderBlue = countMatchingPixels(tableImg, (r, g, b) => b - r > 80 && r < 80);
expect(tableHeaderFill).toBeGreaterThan(400);
expect(tableBorderBlue).toBeGreaterThan(100);
// 9. Capture and structurally assert regression.png for the full composite document.
const initialComposite = await captureRaw(view.tag);
const directory = path.resolve(import.meta.dirname, "../../../.artifacts/gpui/markdown");
mkdirSync(directory, { recursive: true });
writeFileSync(path.join(directory, "regression.png"), initialComposite.bytes);
expect(
countMatchingPixels(initialComposite, (r, g, b) => r < 60 && g < 60 && b < 60),
).toBeGreaterThan(1500);
expect(
countMatchingPixels(initialComposite, (r, g, b) => b - r > 60 && r < 100),
).toBeGreaterThan(300);
expect(
countMatchingPixels(
initialComposite,
(r, g, b) =>
(r > 150 && b > 200 && g < 180) ||
(g > 180 && r < 160 && b < 190) ||
(r > 200 && g > 150 && b < 110),
),
).toBeGreaterThan(80);
// Dark code card + blue header table bands must both exist in the composite screenshot.
expect(
countMatchingPixels(initialComposite, (r, g, b) => r < 25 && g < 35 && b < 60),
).toBeGreaterThan(2000);
expect(
countMatchingPixels(
initialComposite,
(r, g, b) => Math.abs(r - 0xdb) < 16 && Math.abs(g - 0xea) < 16 && b > 240,
),
).toBeGreaterThan(300);
// 10. Clicking a rendered link dispatches onLinkPress with the URL.
const linkTarget = await nodeWithId("markdown-link-target");
expect(linkTarget.frame?.[2] ?? 0).toBeGreaterThan(40);
expect(linkTarget.frame?.[3] ?? 0).toBeGreaterThan(10);
expect(await request("click", { tag: linkTarget.tag })).toEqual({ clicked: true });
await expect
.poll(async () => (await nodeWithId("pressed-link")).text)
.toBe("https://example.com/docs");
// 11. Streaming append increases layout height and paints new ink pixels in the composite screenshot.
const streamBtn = await nodeWithId("markdown-stream-next");
expect(await request("click", { tag: streamBtn.tag })).toEqual({ clicked: true });
await expect
.poll(
async () =>
(JSON.parse((await nodeWithId("markdown-layout")).text) as { height?: number }).height ??
0,
)
.toBeGreaterThan(initialLayout.height ?? 0);
await expect
.poll(async () => {
const streamedComposite = await captureRaw(view.tag);
if (streamedComposite.height <= initialComposite.height) return 0;
return countMatchingPixels(
streamedComposite,
(r, g, b, _x, y) => y >= initialComposite.height && r < 140 && g < 140 && b < 140,
);
})
.toBeGreaterThan(80);
if (driverLogPath) {
const invalidLines = readFileSync(driverLogPath, "utf8")
.split("\n")
.filter((line) => line.includes("returned an invalid measurement"));
expect(invalidLines).toEqual([]);
}
},
30_000,
);
+251
View File
@@ -0,0 +1,251 @@
import { realpathSync, statSync } from "node:fs";
import { createRequire } from "node:module";
import path from "node:path";
import { afterEach, describe, expect, test } from "vitest";
const require = createRequire(import.meta.url);
const GPUI_DIR = import.meta.dirname;
const APP_DIR = path.resolve(GPUI_DIR, "..");
interface MetroConfig {
resolver: {
sourceExts: string[];
resolveRequest: (
context: Record<string, unknown>,
moduleName: string,
platform: string | null,
) => { type: string; filePath?: string };
};
}
function createResolutionContext(
originModulePath: string,
sourceExts: string[],
preferNativePlatform: boolean,
resolverModule: { resolve: (...args: unknown[]) => unknown },
) {
const fileSystemLookup = (candidatePath: string) => {
try {
const stats = statSync(candidatePath);
if (stats.isFile() || stats.isDirectory()) {
return {
exists: true,
type: stats.isFile() ? "f" : "d",
realPath: realpathSync(candidatePath),
};
}
} catch {
// Missing candidate path.
}
return { exists: false };
};
return {
allowHaste: false,
assetExts: new Set(["png", "jpg", "jpeg", "gif", "webp", "svg"]),
customResolverOptions: {},
dev: false,
disableHierarchicalLookup: false,
doesFileExist: (filePath: string) => fileSystemLookup(filePath).exists,
extraNodeModules: {},
fileSystemLookup,
getPackage: () => null,
getPackageForModule: () => null,
mainFields: ["react-native", "browser", "main"],
nodeModulesPaths: [path.join(GPUI_DIR, "node_modules"), path.join(APP_DIR, "node_modules")],
originModulePath,
preferNativePlatform,
redirectModulePath: (modulePath: string) => modulePath,
resolveAsset: () => null,
resolveHasteModule: () => null,
resolveHastePackage: () => null,
resolveRequest: resolverModule.resolve,
sourceExts,
unstable_conditionNames: ["require", "react-native"],
unstable_conditionsByPlatform: {},
unstable_enablePackageExports: false,
unstable_incrementalResolution: false,
unstable_logWarning: () => {},
};
}
function loadAppMetroConfig(webPlatform?: string) {
const previous = process.env.PASEO_WEB_PLATFORM;
if (webPlatform === undefined) delete process.env.PASEO_WEB_PLATFORM;
else process.env.PASEO_WEB_PLATFORM = webPlatform;
const configPath = path.join(APP_DIR, "metro.config.cjs");
delete require.cache[configPath];
try {
return {
config: require(configPath) as MetroConfig,
resolver: require(
require.resolve("metro-resolver", { paths: [APP_DIR, path.resolve(APP_DIR, "../..")] }),
) as { resolve: (...args: unknown[]) => unknown },
};
} finally {
if (previous === undefined) delete process.env.PASEO_WEB_PLATFORM;
else process.env.PASEO_WEB_PLATFORM = previous;
}
}
const CASES = [
{
label: "audio engine",
origin: path.join(APP_DIR, "src/audio/index.ts"),
specifier: "./audio-engine",
gpui: path.join(APP_DIR, "src/audio/audio-engine.gpui.ts"),
native: path.join(APP_DIR, "src/audio/audio-engine.native.ts"),
web: path.join(APP_DIR, "src/audio/audio-engine.web.ts"),
},
{
label: "mermaid fence host",
origin: path.join(APP_DIR, "src/components/markdown/fence/mermaid/index.tsx"),
specifier: "./host",
gpui: path.join(APP_DIR, "src/components/markdown/fence/mermaid/host.gpui.tsx"),
native: path.join(APP_DIR, "src/components/markdown/fence/mermaid/host.native.tsx"),
web: path.join(APP_DIR, "src/components/markdown/fence/mermaid/host.web.tsx"),
},
{
label: "html preview",
origin: path.join(APP_DIR, "src/file-panels/builtin.tsx"),
specifier: "./html-preview",
gpui: path.join(APP_DIR, "src/file-panels/html-preview.gpui.tsx"),
native: path.join(APP_DIR, "src/file-panels/html-preview.tsx"),
web: path.join(APP_DIR, "src/file-panels/html-preview.web.tsx"),
},
{
label: "document frame",
origin: path.join(APP_DIR, "src/plugins/react-native/ui.ts"),
specifier: "@/file-panels/document-frame",
gpui: path.join(APP_DIR, "src/file-panels/document-frame/index.gpui.tsx"),
native: path.join(APP_DIR, "src/file-panels/document-frame/index.tsx"),
web: path.join(APP_DIR, "src/file-panels/document-frame/index.web.tsx"),
},
{
label: "press feedback",
origin: path.join(APP_DIR, "modules/paseo-press-feedback/src/ui/index.tsx"),
specifier: "./feedback",
gpui: path.join(APP_DIR, "modules/paseo-press-feedback/src/ui/feedback.gpui.tsx"),
native: path.join(APP_DIR, "modules/paseo-press-feedback/src/ui/feedback.native.tsx"),
web: path.join(APP_DIR, "modules/paseo-press-feedback/src/ui/feedback.tsx"),
},
{
label: "pointer capabilities",
origin: path.join(APP_DIR, "src/components/ui/control-sizing.ts"),
specifier: "@/hooks/pointer-capabilities",
gpui: path.join(APP_DIR, "src/hooks/pointer-capabilities.gpui.ts"),
native: path.join(APP_DIR, "src/hooks/pointer-capabilities.ts"),
web: path.join(APP_DIR, "src/hooks/pointer-capabilities.ts"),
},
{
label: "keyboard presence",
origin: path.join(APP_DIR, "src/keyboard/availability.ts"),
specifier: "./internal/presence",
gpui: path.join(APP_DIR, "src/keyboard/internal/presence.gpui.ts"),
native: path.join(APP_DIR, "src/keyboard/internal/presence.ts"),
web: path.join(APP_DIR, "src/keyboard/internal/presence.web.ts"),
},
{
label: "keyboard conventions",
origin: path.join(APP_DIR, "src/keyboard/index.ts"),
specifier: "./internal/conventions",
gpui: path.join(APP_DIR, "src/keyboard/internal/conventions.gpui.ts"),
native: path.join(APP_DIR, "src/keyboard/internal/conventions.ts"),
web: path.join(APP_DIR, "src/keyboard/internal/conventions.web.ts"),
},
{
label: "resource budget",
origin: path.join(APP_DIR, "src/hooks/use-settings/storage.ts"),
specifier: "@/constants/resource-budget",
gpui: path.join(APP_DIR, "src/constants/resource-budget.gpui.ts"),
native: path.join(APP_DIR, "src/constants/resource-budget.ts"),
web: path.join(APP_DIR, "src/constants/resource-budget.ts"),
},
{
label: "presentation",
origin: path.join(APP_DIR, "src/command-center/command-center.tsx"),
specifier: "@/constants/presentation",
gpui: path.join(APP_DIR, "src/constants/presentation.gpui.ts"),
native: path.join(APP_DIR, "src/constants/presentation.ts"),
web: path.join(APP_DIR, "src/constants/presentation.ts"),
},
{
label: "touch timing",
origin: path.join(APP_DIR, "src/composer/input/input.tsx"),
specifier: "@/constants/touch-timing",
gpui: path.join(APP_DIR, "src/constants/touch-timing.gpui.ts"),
native: path.join(APP_DIR, "src/constants/touch-timing.ts"),
web: path.join(APP_DIR, "src/constants/touch-timing.ts"),
},
{
label: "press highlight",
origin: path.join(APP_DIR, "src/components/sidebar-workspace-list.tsx"),
specifier: "@/components/ui/press-highlight",
gpui: path.join(APP_DIR, "src/components/ui/press-highlight.gpui.tsx"),
native: path.join(APP_DIR, "src/components/ui/press-highlight.native.tsx"),
web: path.join(APP_DIR, "src/components/ui/press-highlight.tsx"),
},
];
afterEach(() => {
delete require.cache[path.join(APP_DIR, "metro.config.cjs")];
});
describe("GPUI Metro platform rule", () => {
test("GPUI resolves .gpui.* files ahead of .desktop, .native, and base files", () => {
const config = require(path.join(GPUI_DIR, "desktop/metro.config.js")) as MetroConfig;
const resolver = require(require.resolve("metro-resolver", { paths: [GPUI_DIR] })) as {
resolve: (...args: unknown[]) => unknown;
};
for (const item of CASES) {
const ctx = createResolutionContext(item.origin, config.resolver.sourceExts, true, resolver);
expect(
config.resolver.resolveRequest(ctx, item.specifier, "desktop").filePath,
item.label,
).toBe(item.gpui);
}
// GPUI must not pick Electron's .electron.* files as "desktop".
const browserCtx = createResolutionContext(
path.join(APP_DIR, "src/components/split-container.tsx"),
config.resolver.sourceExts,
true,
resolver,
);
expect(
config.resolver.resolveRequest(browserCtx, "@/desktop/browser/pane", "desktop").filePath,
).toBe(path.join(APP_DIR, "src/desktop/browser/pane/index.tsx"));
});
test("iOS, Android, web, and Electron never resolve .gpui.* files", () => {
const relativeCases = CASES.filter((item) => !item.specifier.startsWith("@/"));
const standard = loadAppMetroConfig();
const electron = loadAppMetroConfig("electron");
const targets = [
{ ...standard, platform: "ios", preferNative: true, expected: "native" as const },
{ ...standard, platform: "android", preferNative: true, expected: "native" as const },
{ ...standard, platform: "web", preferNative: false, expected: "web" as const },
{ ...electron, platform: "web", preferNative: false, expected: "web" as const },
];
for (const target of targets) {
for (const item of relativeCases) {
const ctx = createResolutionContext(
item.origin,
target.config.resolver.sourceExts,
target.preferNative,
target.resolver,
);
const filePath = target.config.resolver.resolveRequest(
ctx,
item.specifier,
target.platform,
).filePath;
expect(filePath, `${target.platform}: ${item.label}`).toBe(item[target.expected]);
expect(filePath).not.toContain(".gpui.");
}
}
});
});
+434
View File
@@ -0,0 +1,434 @@
import { afterAll, beforeAll, expect, test } from "vitest";
import sharp from "sharp";
import { mkdirSync, writeFileSync } from "node:fs";
import path from "node:path";
// Runs against the actual Paseo bundle in the compiled GPUI app. Start with
// RN_GPUI_TEST_DRIVER=1 and pass its loopback URL and token to this test.
const endpoint = process.env.PASEO_GPUI_TEST_URL;
const token = process.env.PASEO_GPUI_TEST_TOKEN;
const appearanceFixture = process.env.PASEO_GPUI_TEST_SCENE === "appearance";
let socket: WebSocket;
let nextId = 0;
interface Node {
tag: number;
component: string;
testID: string;
text: string;
frame?: [number, number, number, number];
children?: Node[];
}
const pending = new Map<number, { resolve(value: unknown): void; reject(error: Error): void }>();
function request<T = unknown>(method: string, params: Record<string, unknown> = {}): Promise<T> {
const id = ++nextId;
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
pending.delete(id);
reject(new Error(`GPUI ${method} timed out`));
}, 15_000);
pending.set(id, {
resolve: (value) => {
clearTimeout(timer);
resolve(value as T);
},
reject: (error) => {
clearTimeout(timer);
reject(error);
},
});
socket.send(JSON.stringify({ jsonrpc: "2.0", id, method, params: { ...params, token } }));
});
}
function flatten(node: Node): Node[] {
return [node, ...(node.children ?? []).flatMap(flatten)];
}
async function nodes() {
return (await request<{ children: Node[] }>("tree")).children.flatMap(flatten);
}
beforeAll(async () => {
if (!endpoint) return;
if (!token) throw new Error("PASEO_GPUI_TEST_TOKEN is required");
socket = new WebSocket(endpoint);
await new Promise<void>((resolve, reject) => {
socket.addEventListener("open", () => resolve(), { once: true });
socket.addEventListener("error", () => reject(new Error("GPUI driver connection failed")), {
once: true,
});
});
socket.addEventListener("message", (event) => {
const response = JSON.parse(String(event.data));
const waiter = pending.get(response.id);
if (!waiter) return;
pending.delete(response.id);
const error = response.error ?? response.result?.error;
if (error) waiter.reject(new Error(JSON.stringify(error)));
else waiter.resolve(response.result);
});
});
afterAll(() => socket?.close());
test.skipIf(!endpoint || appearanceFixture)(
"real Paseo portal passes workspace clicks and the native composer edits text",
async () => {
const workspace = (await nodes()).find((node) =>
node.testID.startsWith("sidebar-workspace-row-"),
);
expect(workspace, "connected daemon must have an existing workspace").toBeDefined();
// Regression: the upstream box-none portal hit area intercepted this click.
expect(await request("click", { tag: workspace!.tag })).toEqual({ clicked: true });
await expect
.poll(async () => (await nodes()).some((node) => node.testID === "workspace-header-title"), {
timeout: 15_000,
})
.toBe(true);
await expect
.poll(async () => (await nodes()).some((node) => node.component === "TextInput"), {
timeout: 15_000,
})
.toBe(true);
// Wait for async draft hydration (which resets an empty native TextInput once after mount).
let settledTag: number | undefined;
await expect
.poll(
async () => {
const current = (await nodes()).find((node) => node.component === "TextInput")?.tag;
const stable = current !== undefined && current === settledTag;
settledTag = current;
return stable;
},
{ timeout: 15_000, interval: 500 },
)
.toBe(true);
const input = (await nodes()).find((node) => node.component === "TextInput")!;
const original = (await request<{ text: string }>("getProps", { tag: input.tag })).text;
try {
await request("click", { tag: input.tag });
await request("press", { key: "secondary-a" });
await request("press", { key: "backspace" });
expect(
await request("type", { tag: input.tag, text: "GPUI native input regression" }),
).toEqual({ typed: true });
await expect
.poll(async () => (await request<{ text: string }>("getProps", { tag: input.tag })).text)
.toBe("GPUI native input regression");
} finally {
await request("press", { key: "secondary-a" });
await request("press", { key: "backspace" });
if (original) await request("type", { tag: input.tag, text: original });
await expect
.poll(async () => (await request<{ text: string }>("getProps", { tag: input.tag })).text)
.toBe(original);
}
},
45_000,
);
test.skipIf(!endpoint || appearanceFixture)(
"real Paseo sizes controls for a pointer, not for touch",
async () => {
// Regression: GPUI took the native touch answer, so a 28 pt pointer control rendered at 44.
const settings = await nodeWithId("sidebar-settings");
const displays = await request<Array<{ primary: boolean; scaleFactor: number }>>("displays");
const scale =
displays.find((display) => display.primary)?.scaleFactor ?? displays[0]?.scaleFactor ?? 1;
expect(settings.frame?.[3]).toBeDefined();
expect(Math.abs(settings.frame![3] - 28)).toBeLessThanOrEqual(1 / scale);
},
20_000,
);
test.skipIf(!endpoint || appearanceFixture)(
"real Paseo opens History",
async () => {
// Regression: the agent list's RefreshControl was undefined on GPUI, so History rendered
// "Element type is invalid" instead of the list. The daemon needs at least one agent.
const history = await nodeWithId("sidebar-sessions");
expect(await request("click", { tag: history.tag })).toEqual({ clicked: true });
// The list mounts after the agents load, so wait for a row, not for the search input.
await expect
.poll(
async () => {
const current = await nodes();
if (current.some((node) => node.testID === "root-error-boundary")) return "error screen";
return current.some((node) => node.testID.startsWith("agent-row-")) ? "list" : "loading";
},
{ timeout: 15_000 },
)
.toBe("list");
},
30_000,
);
async function openWorkspaceAndWaitForComposer(workspaceRow: Node): Promise<Node> {
expect(await request("click", { tag: workspaceRow.tag })).toEqual({ clicked: true });
await expect
.poll(async () => (await nodes()).some((node) => node.testID === "workspace-header-title"), {
timeout: 15_000,
})
.toBe(true);
await expect
.poll(async () => (await nodes()).some((node) => node.component === "TextInput"), {
timeout: 15_000,
})
.toBe(true);
let settledTag: number | undefined;
await expect
.poll(
async () => {
const current = (await nodes()).find((node) => node.component === "TextInput")?.tag;
const stable = current !== undefined && current === settledTag;
settledTag = current;
return stable;
},
{ timeout: 15_000, interval: 500 },
)
.toBe(true);
return (await nodes()).find((node) => node.component === "TextInput")!;
}
test.skipIf(!endpoint || appearanceFixture)(
"real Paseo submits the composer on Enter and inserts a newline on Shift+Enter",
async () => {
await expect
.poll(
async () => (await nodes()).some((n) => n.testID.startsWith("sidebar-workspace-row-")),
{
timeout: 15_000,
},
)
.toBe(true);
const workspace = (await nodes()).find((n) => n.testID.startsWith("sidebar-workspace-row-"))!;
const input = await openWorkspaceAndWaitForComposer(workspace);
await request("click", { tag: input.tag });
await request("press", { key: "secondary-a" });
await request("press", { key: "backspace" });
const marker = `GPUI Enter ${Date.now()}`;
await request("type", { tag: input.tag, text: marker });
await request("press", { key: "shift-enter" });
await request("type", { tag: input.tag, text: "line2" });
await expect
.poll(async () => (await request<{ text: string }>("getProps", { tag: input.tag })).text)
.toBe(`${marker}\nline2`);
await request("press", { key: "enter" });
await expect
.poll(
async () => {
const current = (await nodes()).find((node) => node.component === "TextInput");
if (!current) return null;
return (await request<{ text: string }>("getProps", { tag: current.tag })).text;
},
{ timeout: 15_000 },
)
.toBe("");
await expect
.poll(async () => (await nodes()).some((node) => node.text.includes(marker)), {
timeout: 15_000,
})
.toBe(true);
},
45_000,
);
test.skipIf(!endpoint || appearanceFixture)(
"real Paseo keeps the first workspace mounted when switching between two workspaces",
async () => {
await expect
.poll(
async () =>
(await nodes()).filter((n) => n.testID.startsWith("sidebar-workspace-row-")).length >= 2,
{ timeout: 15_000 },
)
.toBe(true);
const rows = (await nodes()).filter((n) => n.testID.startsWith("sidebar-workspace-row-"));
const firstInput = await openWorkspaceAndWaitForComposer(rows[0]!);
const firstTitle = (await nodes()).find((n) => n.testID === "workspace-header-title")?.text;
await request("click", { tag: firstInput.tag });
await request("press", { key: "secondary-a" });
await request("press", { key: "backspace" });
await request("type", { tag: firstInput.tag, text: "Kept across workspace switch" });
await expect
.poll(async () => (await request<{ text: string }>("getProps", { tag: firstInput.tag })).text)
.toBe("Kept across workspace switch");
try {
expect(await request("click", { tag: rows[1]!.tag })).toEqual({ clicked: true });
await expect
.poll(
async () => {
const title = (await nodes()).find((n) => n.testID === "workspace-header-title")?.text;
return title !== undefined && title !== firstTitle;
},
{ timeout: 15_000 },
)
.toBe(true);
expect(await request("click", { tag: rows[0]!.tag })).toEqual({ clicked: true });
await expect
.poll(
async () => (await nodes()).find((n) => n.testID === "workspace-header-title")?.text,
{ timeout: 15_000 },
)
.toBe(firstTitle);
// The exact Fabric node tag and draft text must survive because desktop retention keeps
// inactive workspaces mounted instead of unmounting on switch.
expect((await request<{ text: string }>("getProps", { tag: firstInput.tag })).text).toBe(
"Kept across workspace switch",
);
} finally {
await request("click", { tag: firstInput.tag });
await request("press", { key: "secondary-a" });
await request("press", { key: "backspace" });
}
},
45_000,
);
async function nodeWithId(testID: string) {
await expect.poll(async () => (await nodes()).some((node) => node.testID === testID)).toBe(true);
return (await nodes()).find((node) => node.testID === testID)!;
}
async function expectBackground(node: Node, color: number) {
await expect
.poll(
async () =>
(await request<{ backgroundColor: number }>("getProps", { tag: node.tag })).backgroundColor,
)
.toBe(color);
}
test.skipIf(!endpoint || !appearanceFixture)(
"Pressable render props receive hover state",
async () => {
const button = await nodeWithId("hover-render-prop");
const outside = await nodeWithId("outside-hover");
await request("hover", { tag: button.tag });
await expectBackground(button, 0xff00ff00);
await expect
.poll(async () => (await nodes()).some((node) => node.text === "render hovered"))
.toBe(true);
await request("hover", { tag: outside.tag });
await expectBackground(button, 0xff0000ff);
await expect
.poll(async () => (await nodes()).some((node) => node.text === "render idle"))
.toBe(true);
},
);
test.skipIf(!endpoint || !appearanceFixture)(
"rounded borders follow the background curve",
async () => {
const node = await nodeWithId("rounded-border");
const { png } = await request<{ png: string }>("screenshot", { tag: node.tag });
const bytes = Buffer.from(png, "base64");
const directory = path.resolve(import.meta.dirname, "../../../.artifacts/gpui/appearance");
mkdirSync(directory, { recursive: true });
writeFileSync(path.join(directory, "rounded-border.png"), bytes);
const { data, info } = await sharp(bytes)
.removeAlpha()
.raw()
.toBuffer({ resolveWithObject: true });
const pixel = (x: number, y: number) => {
const offset =
(Math.floor((y * info.height) / 100) * info.width + Math.floor((x * info.width) / 200)) *
info.channels;
return [...data.subarray(offset, offset + 3)];
};
// Outside the arc must be clear; the diagonal must have an actual curved
// border, not four straight rules clipped to a rounded rectangle.
expect(pixel(1, 1)).toEqual([255, 255, 255]);
expect(pixel(8, 8)).toEqual([255, 0, 0]);
expect(pixel(15, 15)).toEqual([0, 0, 255]);
expect(pixel(100, 1)).toEqual([255, 0, 0]);
expect(pixel(198, 98)).toEqual([255, 255, 255]);
},
);
test.skipIf(!endpoint || !appearanceFixture)(
"Pressable hover highlights enter and leave",
async () => {
const button = await nodeWithId("hover-button");
const outside = await nodeWithId("outside-hover");
await request("hover", { tag: button.tag });
await expectBackground(button, 0xff00ff00);
await request("hover", { tag: outside.tag });
await expectBackground(button, 0xff0000ff);
},
);
test.skipIf(!endpoint || !appearanceFixture)(
"row hover survives entering a nested Pressable",
async () => {
const row = await nodeWithId("hover-row");
const child = await nodeWithId("nested-button");
const outside = await nodeWithId("outside-hover");
await request("hover", { tag: row.tag });
await request("hover", { tag: child.tag });
await expectBackground(row, 0xff00ff00);
await request("hover", { tag: outside.tag });
await expectBackground(row, 0xff0000ff);
},
);
test.skipIf(!endpoint || !appearanceFixture)(
"onLayout fires with React Native layout shape for View, Text, TextInput, Image, and ScrollView",
async () => {
interface LayoutEntry {
count: number;
keys: string[];
layout: { x: number; y: number; width: number; height: number };
}
const readLayouts = async () => {
const node = await nodeWithId("layout-results");
return JSON.parse(node.text) as Record<string, LayoutEntry>;
};
const targets = [
["view", "layout-view"],
["text", "layout-text"],
["textInput", "layout-text-input"],
["image", "layout-image"],
["scrollView", "layout-scroll"],
] as const;
await expect
.poll(async () => Object.keys(await readLayouts()).sort())
.toEqual(targets.map(([key]) => key).sort());
const initial = await readLayouts();
const treeNodes = await nodes();
for (const [key, testID] of targets) {
const entry = initial[key];
expect(entry.count, `${key} initial onLayout count`).toBe(1);
expect(entry.keys, `${key} layout keys`).toEqual(["height", "width", "x", "y"]);
expect(entry.layout.width, `${key} width`).toBeGreaterThan(0);
expect(entry.layout.height, `${key} height`).toBeGreaterThan(0);
const treeNode = treeNodes.find((n) => n.testID === testID);
expect(treeNode?.frame, `${testID} frame`).toBeDefined();
expect(entry.layout.x).toBeCloseTo(treeNode!.frame![0], 2);
expect(entry.layout.y).toBeCloseTo(treeNode!.frame![1], 2);
expect(entry.layout.width).toBeCloseTo(treeNode!.frame![2], 2);
expect(entry.layout.height).toBeCloseTo(treeNode!.frame![3], 2);
}
const toggle = await nodeWithId("layout-resize-toggle");
expect(await request("click", { tag: toggle.tag })).toEqual({ clicked: true });
await expect
.poll(async () => {
const parsed = await readLayouts();
return targets.every(([key]) => (parsed[key]?.count ?? 0) >= 2);
})
.toBe(true);
const resized = await readLayouts();
for (const [key] of targets) {
expect(resized[key].count, `${key} resized onLayout count`).toBe(2);
expect(resized[key].layout.width, `${key} resized width`).toBeGreaterThan(
initial[key].layout.width,
);
}
},
);
+6737
View File
File diff suppressed because it is too large Load Diff
+40
View File
@@ -0,0 +1,40 @@
{
"name": "paseo-gpui",
"version": "0.0.0",
"private": true,
"dependencies": {
"@formatjs/intl-datetimeformat": "^7.9.0",
"@formatjs/intl-displaynames": "^7.4.0",
"@formatjs/intl-getcanonicallocales": "^3.3.0",
"@formatjs/intl-locale": "^5.4.1",
"@formatjs/intl-numberformat": "^9.5.0",
"@formatjs/intl-pluralrules": "^6.4.0",
"@formatjs/intl-segmenter": "^12.3.0",
"@react-native-gpui/codegen": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-4/react-native-gpui-codegen-0.87.0-alpha.2.tgz",
"@react-native-gpui/core": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-4/react-native-gpui-core-0.87.0-alpha.5.tgz",
"@react-native-gpui/fs": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-4/react-native-gpui-fs-0.0.1-alpha.1.tgz",
"@react-native-gpui/gesture-handler": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-4/react-native-gpui-gesture-handler-3.3.0-alpha.1.tgz",
"@react-native-gpui/hermes": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-4/react-native-gpui-hermes-0.87.0-alpha.1.tgz",
"@react-native-gpui/reanimated": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-4/react-native-gpui-reanimated-4.7.0-alpha.1.tgz",
"@react-native-gpui/safe-area-context": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-4/react-native-gpui-safe-area-context-5.10.0-alpha.0.tgz",
"@react-native-gpui/screens": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-4/react-native-gpui-screens-4.28.0-alpha.2.tgz",
"@react-native-gpui/svg": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-4/react-native-gpui-svg-15.15.0-alpha.1.tgz",
"@react-native-gpui/worklets": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-4/react-native-gpui-worklets-0.13.0-alpha.1.tgz",
"@react-native/assets-registry": "^0.87.1",
"react": "19.2.3",
"react-native": "0.87.1",
"react-native-gesture-handler": "3.3.0",
"react-native-reanimated": "https://github.com/ammarahm-ed/react-native-reanimated/releases/download/4.7.1-desktop.1/react-native-reanimated-4.7.1.tgz",
"react-native-safe-area-context": "5.10.1",
"react-native-screens": "4.28.0",
"react-native-svg": "15.15.5",
"react-native-worklets": "https://github.com/ammarahm-ed/react-native-reanimated/releases/download/worklets-0.13.0-desktop.1/react-native-worklets-0.13.0.tgz"
},
"devDependencies": {
"@react-native-community/cli": "20.2.0",
"@react-native-gpui/cli": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-4/react-native-gpui-cli-0.87.0-alpha.5.tgz",
"@react-native/babel-preset": "0.87.1",
"@react-native/metro-config": "0.87.1",
"typescript": "^5.8.3"
}
}
+2
View File
@@ -0,0 +1,2 @@
/// <reference types="@react-native-gpui/core/types" />
// Added by react-native-gpui. Do not edit: it is regenerated.
+22
View File
@@ -0,0 +1,22 @@
const path = require("node:path");
module.exports = {
// This target only launches desktop. RN CLI 20.2's built-in
// run-ios/run-android option lists conflict with the CLI's global verbose
// option, and this app has no native mobile projects to launch.
commands: ["build-android", "build-ios", "log-android", "log-ios", "run-android", "run-ios"].map(
(name) => ({
name,
description: `${name} is not configured for Paseo GPUI`,
func: () => {
throw new Error(`${name} is not configured for Paseo GPUI`);
},
}),
),
project: { desktop: {} },
dependencies: {
"react-native-enriched-markdown": {
root: path.resolve(__dirname, "../../react-native-enriched-markdown"),
},
},
reactNativePath: path.dirname(require.resolve("react-native/package.json")),
};
+7
View File
@@ -0,0 +1,7 @@
// Use the existing route tree. Expo's transformer normally supplies this root
// through a Babel caller field; the RN desktop transformer does not.
export const ctx = require.context(
"../src/app",
true,
/^(?:\.\/)(?!(?:(?:(?:.*\+api)|(?:\+(html|native-intent))))\.[tj]sx?$).*\.[tj]sx?$/,
);
+3
View File
@@ -0,0 +1,3 @@
[toolchain]
channel = "stable"
profile = "minimal"
@@ -0,0 +1,47 @@
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([]);
});
@@ -0,0 +1,61 @@
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}`,
);
@@ -0,0 +1,45 @@
import { AppRegistry } from "react-native";
AppRegistry.registerComponent("Paseo", () => () => null);
// The native test supplies a loopback server before loading this bundle.
const base = globalThis.__webSocketRegressionUrl;
async function connect(path, expectedCode, localClose = false) {
return new Promise((resolve, reject) => {
const socket = new WebSocket(`${base}/${path}`);
const timeout = setTimeout(() => reject(new Error(`${path}: timed out`)), 5000);
let echoed = false;
socket.addEventListener("open", () => socket.send("native websocket regression"));
socket.addEventListener("message", (event) => {
echoed = event.data === "native websocket regression";
if (localClose) socket.close(1000, "client done");
});
socket.addEventListener("close", (event) => {
clearTimeout(timeout);
if (event.code !== expectedCode || (expectedCode === 1000 && !echoed)) {
reject(new Error(`${path}: code=${event.code}, echoed=${echoed}`));
} else {
resolve();
}
});
});
}
async function run() {
// Keep retrying through the real RN WebSocket API. Before the fix, native
// clients survived terminal events and exhausted the Mac's descriptor limit.
for (const [path, code, localClose] of [
["reject", 1006, false],
["remote-close", 1000, false],
["local-close", 1000, true],
]) {
for (let attempt = 0; attempt < 128; attempt++) {
await connect(path, code, localClose);
}
console.log(`WEBSOCKET_REGRESSION_PASS ${path}`);
}
console.log("WEBSOCKET_REGRESSION_COMPLETE");
}
setTimeout(() => {
run().catch((error) => console.error(`WEBSOCKET_REGRESSION_FAIL ${error.message}`));
}, 0);
+117
View File
@@ -0,0 +1,117 @@
import { spawn, execFileSync } from "node:child_process";
import { createServer } from "node:http";
import { mkdtempSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { Server as WebSocketServer } from "ws";
import { expect, test } from "vitest";
const binary = process.env.PASEO_GPUI_TEST_BINARY;
const project = path.dirname(fileURLToPath(import.meta.url));
const root = path.resolve(project, "../../..");
function createPeer() {
const server = createServer();
const sockets = new WebSocketServer({ noServer: true });
server.on("upgrade", (request, socket, head) => {
if (request.url === "/reject") {
socket.end("HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
return;
}
sockets.handleUpgrade(request, socket, head, (websocket) => {
websocket.on("message", (message) => {
websocket.send(message.toString());
if (request.url === "/remote-close") websocket.close(1000, "server done");
});
});
});
return { server, sockets };
}
test.skipIf(!binary)(
"native WebSocket retries and peer closes release their resources",
async () => {
mkdirSync(path.join(root, ".artifacts/gpui"), { recursive: true });
const artifacts = mkdtempSync(path.join(root, ".artifacts/gpui/websocket-"));
const bundle = path.join(artifacts, "regression.bundle");
execFileSync(
process.execPath,
[
"node_modules/react-native/cli.js",
"bundle",
"--platform",
"desktop",
"--entry-file",
"websocket-regression.fixture.js",
"--config",
"desktop/metro.config.js",
"--bundle-output",
bundle,
"--dev",
"false",
"--max-workers",
"1",
],
{ cwd: project, env: { ...process.env, PASEO_RENDERER: "gpui" }, timeout: 120_000 },
);
const { server, sockets } = createPeer();
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const address = server.address();
if (!address || typeof address === "string") throw new Error("Missing server address");
writeFileSync(
bundle,
`globalThis.__webSocketRegressionUrl = "ws://127.0.0.1:${address.port}";\n${readFileSync(bundle, "utf8")}`,
);
// Match Finder's descriptor limit even when the test shell has raised it.
const app = spawn("/bin/sh", ["-c", 'ulimit -n 256; exec "$@"', "gpui-test", binary!], {
env: {
...process.env,
RN_GPUI_BUNDLE: bundle,
RN_GPUI_APP_ID: "sh.paseo.gpui.websocket-test",
XDG_DATA_HOME: path.join(artifacts, "data"),
},
stdio: ["ignore", "pipe", "pipe"],
});
let output = "";
try {
await new Promise<void>((resolve, reject) => {
const timeout = setTimeout(
() => reject(new Error(`Native retry test timed out:\n${output}`)),
60_000,
);
const collect = (chunk: Buffer) => {
output += chunk.toString();
if (output.includes("WEBSOCKET_REGRESSION_COMPLETE")) {
clearTimeout(timeout);
resolve();
} else if (output.includes("WEBSOCKET_REGRESSION_FAIL")) {
clearTimeout(timeout);
reject(new Error(output));
}
};
app.stdout.on("data", collect);
app.stderr.on("data", collect);
app.once("error", (error) => {
clearTimeout(timeout);
reject(error);
});
app.once("exit", (code, signal) => {
clearTimeout(timeout);
reject(new Error(`Native process exited (${code}, ${signal}):\n${output}`));
});
});
expect(app.exitCode).toBeNull();
expect(output).toContain("WEBSOCKET_REGRESSION_PASS reject");
expect(output).toContain("WEBSOCKET_REGRESSION_PASS remote-close");
expect(output).toContain("WEBSOCKET_REGRESSION_PASS local-close");
} finally {
writeFileSync(path.join(artifacts, "native.log"), output);
app.kill("SIGTERM");
for (const client of sockets.clients) client.terminate();
sockets.close();
server.close();
}
},
180_000,
);
@@ -0,0 +1,9 @@
import type { Ref } from "react";
export interface RowFeedbackHandle {
acknowledge(): Promise<void>;
}
export function RowFeedback(_props: { ref?: Ref<RowFeedbackHandle>; selected: boolean }) {
return null;
}
@@ -20,11 +20,11 @@ import {
getWorkspaceSelectionKey,
orderWorkspaceSelectionsForStableRender,
reconcileRetainedWorkspaceSelections,
resolveWorkspaceDeckRetentionLimit,
type RetainedWorkspaceSelection,
resolveWorkspaceDeckEntries,
shouldKeepWorkspaceDeckEntryMounted,
} from "@/screens/workspace/workspace-deck-retention";
import { workspaceDeckRetentionLimit } from "@/constants/resource-budget";
import {
decodeWorkspaceIdFromPathSegment,
parseWorkspaceOpenIntent,
@@ -35,7 +35,7 @@ import {
stripHostWorkspaceRouteEchoSearchFromBrowserUrlAfterCommit,
} from "@/utils/host-route-browser";
import { prepareWorkspaceTab } from "@/utils/prepare-workspace-tab";
import { isNative, isWeb } from "@/constants/platform";
import { isWeb } from "@/constants/platform";
import { RenderProfile } from "@/utils/render-profiler";
function getParamValue(value: string | string[] | undefined): string {
@@ -164,7 +164,7 @@ function WorkspaceDeck() {
currentEntries: retainedSelections,
activeSelection,
now: reconciliationNow,
maxMountedWorkspaces: resolveWorkspaceDeckRetentionLimit({ isNative }),
maxMountedWorkspaces: workspaceDeckRetentionLimit,
}),
[activeSelection, reconciliationNow, retainedSelections],
);
@@ -201,7 +201,7 @@ function WorkspaceDeck() {
currentEntries: current,
activeSelection,
now: Date.now(),
maxMountedWorkspaces: resolveWorkspaceDeckRetentionLimit({ isNative }),
maxMountedWorkspaces: workspaceDeckRetentionLimit,
}),
);
}, expirationDelay + 1);
@@ -0,0 +1,26 @@
import type { AudioEngine, AudioEngineCallbacks, AudioEngineOptions } from "./audio-engine-types";
// Preserve the voice model's lifecycle without loading mobile-only Expo audio
// during app startup. Requests fail explicitly until a Linux audio backend exists.
export function createAudioEngine(
_callbacks: AudioEngineCallbacks,
_options?: AudioEngineOptions,
): AudioEngine {
const unavailable = async (): Promise<never> => {
throw new Error("Voice capture and playback are not available in the GPUI build yet.");
};
return {
initialize: unavailable,
startCapture: unavailable,
play: unavailable,
async destroy() {},
async stopCapture() {},
stop() {},
clearQueue() {},
isPlaying: () => false,
isMuted: () => false,
toggleMute() {
throw new Error("Voice capture is not available in the GPUI build yet.");
},
};
}
@@ -52,6 +52,7 @@ import {
} from "@/components/ui/isolated-bottom-sheet-modal";
import { useIsCompactFormFactor } from "@/constants/layout";
import { isNative, isWeb } from "@/constants/platform";
import { usesCompactBottomSheet } from "@/constants/presentation";
import { useAggregatedAgents, type AggregatedAgent } from "@/hooks/use-aggregated-agents";
import { useProjects } from "@/hooks/use-projects";
import { useTimeAgo } from "@/hooks/use-time-ago";
@@ -914,7 +915,7 @@ export function CommandCenter() {
isCompact ? COMMAND_CENTER_LIST_METRICS.compact : COMMAND_CENTER_LIST_METRICS.desktop,
interaction,
);
const showBottomSheet = isCompact && isNative;
const showBottomSheet = isCompact && usesCompactBottomSheet;
const modalLayer = useGlobalOverlayLayer("modal", state.open);
const { sheetRef, handleSheetChange, handleSheetDismiss } = useIsolatedBottomSheetVisibility({
visible: state.open,
@@ -10,7 +10,8 @@ import { Combobox, type ComboboxOption, type ComboboxProps } from "@/components/
import { ModelBrowser, ModelProviderGlyph, useModelBrowser } from "@/components/model-browser";
import { resolveModelBrowserScrolling } from "@/components/model-browser-view";
import { useIsCompactFormFactor } from "@/constants/layout";
import { isNative, isWeb } from "@/constants/platform";
import { usesCompactBottomSheet } from "@/constants/presentation";
import { deferModelSelectorMount } from "@/constants/resource-budget";
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import {
@@ -101,10 +102,13 @@ export function CombinedModelSelector({
}: CombinedModelSelectorProps) {
const { t } = useTranslation();
const isCompact = useIsCompactFormFactor();
const modelBrowserScrolling = resolveModelBrowserScrolling({ isNative, isCompact });
const modelBrowserScrolling = resolveModelBrowserScrolling({
usesCompactBottomSheet,
isCompact,
});
const anchorRef = useRef<View>(null);
const [isOpen, setIsOpen] = useState(false);
const [isContentReady, setIsContentReady] = useState(isWeb);
const [isContentReady, setIsContentReady] = useState(!deferModelSelectorMount);
const browser = useModelBrowser({
providers,
selectedProvider,
@@ -138,7 +142,7 @@ export function CombinedModelSelector({
);
useEffect(() => {
if (isWeb) return () => {};
if (!deferModelSelectorMount) return () => {};
if (!isOpen) {
setIsContentReady(false);
return () => {};
@@ -308,7 +312,7 @@ export function CombinedModelSelector({
desktopChildrenScrollEnabled={false}
header={browser.header}
keyboard={browser.keyboard}
mobileChildrenScrollEnabled={!browser.isProviderView || !isNative}
mobileChildrenScrollEnabled={!browser.isProviderView || !usesCompactBottomSheet}
mobileChildrenContentContainerStyle={styles.mobileBrowserContent}
>
{selectorBody}
@@ -16,6 +16,7 @@ import DraggableFlatList, {
import type { GestureType } from "react-native-gesture-handler";
import { useUnistyles } from "react-native-unistyles";
import { useContentDrag } from "@/components/ui/content-drag";
import { supportsTouchHaptics } from "@/constants/touch-timing";
import { createDragHold } from "./drag-reorder/drag-hold";
import { movedItemKey } from "./drag-reorder/native-drop";
import type {
@@ -52,7 +53,7 @@ export function DraggableListHandle({ testID, style, children }: DraggableListHa
delayMs: HANDLE_HOLD_MS,
slopPx: HANDLE_HOLD_SLOP_PX,
onArm: () => {
void Haptics.selectionAsync().catch(() => {});
if (supportsTouchHaptics) void Haptics.selectionAsync().catch(() => {});
drag();
},
})
@@ -0,0 +1,17 @@
import { Text, View } from "react-native";
import { HighlightedCodeBlock } from "@/components/highlighted-code-block";
import type { MarkdownFenceRendererProps } from "./types";
export function MermaidFenceHost({ code, inheritedStyles, textStyle }: MarkdownFenceRendererProps) {
return (
<View>
<Text style={inheritedStyles}>Diagram rendering is not available in the GPUI build yet.</Text>
<HighlightedCodeBlock
code={code}
language="mermaid"
inheritedStyles={inheritedStyles}
textStyle={textStyle}
/>
</View>
);
}
+2 -2
View File
@@ -23,7 +23,7 @@ import {
import { TaskListRow } from "@/components/task-list-row";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { useIsCompactFormFactor } from "@/constants/layout";
import { isNative, isWeb } from "@/constants/platform";
import { isNative, isWeb, supportsMaskedEffects } from "@/constants/platform";
import { useRevealedText, type MarkdownPhase } from "@/hooks/use-revealed-text";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
@@ -1905,7 +1905,7 @@ function computeShimmerMetrics(input: {
// React Native Web only observes a node when onLayout exists at mount. Keep
// measuring while idle so a retained badge has dimensions when it starts loading.
const shouldMeasureWebShimmer = isWeb;
const shouldMeasureNativeShimmer = input.isLoading && isNative;
const shouldMeasureNativeShimmer = input.isLoading && isNative && supportsMaskedEffects;
const isNativeShimmer =
shouldMeasureNativeShimmer && input.labelRowWidth > 0 && input.labelRowHeight > 0;
const webShimmerSpanStartX = input.labelOffsetX;
@@ -49,16 +49,18 @@ function modelRow(
}
describe("model browser scrolling", () => {
it("participates in native compact bottom-sheet scrolling", () => {
expect(resolveModelBrowserScrolling({ isNative: true, isCompact: true })).toBe("sheet");
it("participates in compact bottom-sheet scrolling on mobile targets", () => {
expect(resolveModelBrowserScrolling({ usesCompactBottomSheet: true, isCompact: true })).toBe(
"sheet",
);
});
it.each([
{ platform: "native wide", isNative: true, isCompact: false },
{ platform: "compact web", isNative: false, isCompact: true },
{ platform: "wide web", isNative: false, isCompact: false },
])("owns scrolling on $platform surfaces", ({ isNative, isCompact }) => {
expect(resolveModelBrowserScrolling({ isNative, isCompact })).toBe("independent");
{ platform: "mobile wide", usesCompactBottomSheet: true, isCompact: false },
{ platform: "compact web/desktop", usesCompactBottomSheet: false, isCompact: true },
{ platform: "wide web/desktop", usesCompactBottomSheet: false, isCompact: false },
])("owns scrolling on $platform surfaces", ({ usesCompactBottomSheet, isCompact }) => {
expect(resolveModelBrowserScrolling({ usesCompactBottomSheet, isCompact })).toBe("independent");
});
});
@@ -13,13 +13,13 @@ export type ModelBrowserView =
| { kind: "provider"; providerId: string; providerLabel: string };
export function resolveModelBrowserScrolling({
isNative,
usesCompactBottomSheet,
isCompact,
}: {
isNative: boolean;
usesCompactBottomSheet: boolean;
isCompact: boolean;
}): "sheet" | "independent" {
return isNative && isCompact ? "sheet" : "independent";
return usesCompactBottomSheet && isCompact ? "sheet" : "independent";
}
/** A profile's model reference; used to match profiles back to model rows. */
+15 -10
View File
@@ -62,8 +62,13 @@ import type { EditingTextInputHandle } from "@/components/ui/text-input";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { useProviderIcon } from "@/components/provider-icons";
import { useIsCompactFormFactor } from "@/constants/layout";
import { isNative, isWeb } from "@/constants/platform";
import { useHardwareKeyboardPresent, type KeyboardInputEvent } from "@/keyboard";
import { isNative } from "@/constants/platform";
import { usesCompactBottomSheet, usesDesktopPopoverSpacing } from "@/constants/presentation";
import {
hasSoftwareKeyboard,
useHardwareKeyboardPresent,
type KeyboardInputEvent,
} from "@/keyboard";
import {
buildProviderQualifiedDescription,
buildSelectedTriggerLabel,
@@ -366,7 +371,7 @@ export function useModelBrowser({
selectedProvider,
selectedModel,
isLoading,
autoFocusSearch = isWeb,
autoFocusSearch = !hasSoftwareKeyboard,
profiles = null,
serverId = null,
}: ModelBrowserInput): ModelBrowserState {
@@ -1564,7 +1569,7 @@ function ModelRowList({
);
}
if (isCompact && isNative) {
if (isCompact && usesCompactBottomSheet) {
return (
<SheetFlatList
data={rows}
@@ -1631,7 +1636,7 @@ function ModelSearchEmptyState() {
// React Native Web blurs the focused input on every scroll in "on-drag" mode, including wheel
// scrolls and the scroll that reveals an arrowed-to row. That moves focus out of search, so
// typing stops and Enter lands on the header's Back button. Only a native keyboard needs it.
const MODEL_LIST_KEYBOARD_DISMISS_MODE = isNative ? "on-drag" : "none";
const MODEL_LIST_KEYBOARD_DISMISS_MODE = hasSoftwareKeyboard ? "on-drag" : "none";
interface ModelBrowserKeyboardBinding {
view: ModelBrowserView;
@@ -2070,14 +2075,14 @@ const styles = StyleSheet.create((theme) => ({
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
paddingHorizontal: isWeb ? theme.spacing[3] : theme.spacing[6],
paddingHorizontal: usesDesktopPopoverSpacing ? theme.spacing[3] : theme.spacing[6],
paddingTop: theme.spacing[2],
paddingBottom: theme.spacing[1],
},
sectionHeadingAction: {
position: "absolute",
top: theme.spacing[1],
right: isWeb ? theme.spacing[3] : theme.spacing[6],
right: usesDesktopPopoverSpacing ? theme.spacing[3] : theme.spacing[6],
},
sectionHeadingText: {
flex: 1,
@@ -2097,10 +2102,10 @@ const styles = StyleSheet.create((theme) => ({
position: "absolute",
top: 0,
bottom: 0,
right: isWeb ? theme.spacing[3] : theme.spacing[6],
right: usesDesktopPopoverSpacing ? theme.spacing[3] : theme.spacing[6],
justifyContent: "center",
},
browserModelRow: isWeb ? {} : { marginBottom: theme.spacing[1] },
browserModelRow: usesDesktopPopoverSpacing ? {} : { marginBottom: theme.spacing[1] },
browserRowHovered: {
backgroundColor: theme.colors.surface1,
},
@@ -2118,7 +2123,7 @@ const styles = StyleSheet.create((theme) => ({
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
paddingHorizontal: isWeb ? theme.spacing[3] : theme.spacing[6],
paddingHorizontal: usesDesktopPopoverSpacing ? theme.spacing[3] : theme.spacing[6],
},
browserRowLeading: {
width: 16,
@@ -1,5 +1,8 @@
import { describe, expect, it, vi } from "vitest";
import { startResizeHandleDrag } from "@/components/resize-handle-drag";
import {
resolveResizeHandleInteraction,
startResizeHandleDrag,
} from "@/components/resize-handle-drag";
describe("startResizeHandleDrag", () => {
it("previews pointer frames and commits only the final size", () => {
@@ -29,3 +32,14 @@ describe("startResizeHandleDrag", () => {
expect(commit.mock.calls[0]?.[0][1]).toBeCloseTo(0.4, 10);
});
});
describe("resolveResizeHandleInteraction", () => {
it("uses DOM pointer events only on fine-pointer web targets, gesture pan on GPUI, and touch grip on touch targets", () => {
expect(resolveResizeHandleInteraction({ finePointer: true, isWeb: true })).toBe("web-pointer");
expect(resolveResizeHandleInteraction({ finePointer: true, isWeb: false })).toBe(
"native-pointer",
);
expect(resolveResizeHandleInteraction({ finePointer: false, isWeb: false })).toBe("touch");
expect(resolveResizeHandleInteraction({ finePointer: false, isWeb: true })).toBe("touch");
});
});
@@ -7,6 +7,23 @@ interface StartResizeHandleDragInput {
commit: (sizes: number[]) => void;
}
export type ResizeHandleInteraction = "web-pointer" | "native-pointer" | "touch";
/**
* Selects how the resize bar is hit-tested and dragged: thin pointer bar with DOM events on web,
* thin pointer bar with gesture pan on GPUI, and a wide touch target with a grip pill otherwise.
*/
export function resolveResizeHandleInteraction({
finePointer,
isWeb,
}: {
finePointer: boolean;
isWeb: boolean;
}): ResizeHandleInteraction {
if (!finePointer) return "touch";
return isWeb ? "web-pointer" : "native-pointer";
}
export interface ResizeHandleDrag {
move: (deltaRatio: number) => void;
finish: () => void;
+40 -24
View File
@@ -2,7 +2,12 @@ import { useCallback, useMemo, useRef, useState } from "react";
import { View, type PointerEvent as RNPointerEvent } from "react-native";
import { Gesture, GestureDetector } from "react-native-gesture-handler";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import { startResizeHandleDrag, type ResizeHandleDrag } from "@/components/resize-handle-drag";
import {
resolveResizeHandleInteraction,
startResizeHandleDrag,
type ResizeHandleDrag,
} from "@/components/resize-handle-drag";
import { isWeb } from "@/constants/platform";
import { usePointerCapabilities } from "@/hooks/pointer-capabilities";
import {
SIDEBAR_RESIZE_ACTIVATION_OFFSET,
@@ -48,6 +53,7 @@ export function ResizeHandle({
}: ResizeHandleProps) {
const { theme } = useUnistyles();
const { finePointer } = usePointerCapabilities();
const interaction = resolveResizeHandleInteraction({ finePointer, isWeb });
const pointerStatesRef = useRef(new Map<number, PointerState>());
const touchStateRef = useRef<PointerState | null>(null);
const cursorBeforeDragRef = useRef<string | null>(null);
@@ -225,8 +231,12 @@ export function ResizeHandle({
...(direction === "horizontal"
? { left: hitAreaAlignment === "end" ? 0 : -5 }
: { top: hitAreaAlignment === "end" ? 0 : -5 }),
cursor: direction === "horizontal" ? "col-resize" : "row-resize",
touchAction: "none",
...(isWeb
? {
cursor: direction === "horizontal" ? "col-resize" : "row-resize",
touchAction: "none",
}
: {}),
} as object,
],
[direction, hitAreaAlignment],
@@ -254,6 +264,32 @@ export function ResizeHandle({
[direction, highlighted, theme.colors.foreground],
);
const ariaOrientation = direction === "horizontal" ? "vertical" : "horizontal";
const separatorHitArea =
interaction === "web-pointer" ? (
<View
role="separator"
aria-orientation={ariaOrientation}
style={hitAreaStyle}
onPointerDown={handlePointerDown}
onPointerEnter={handlePointerEnter}
onPointerLeave={handlePointerLeave}
/>
) : (
<GestureDetector gesture={touchGesture}>
<View
role="separator"
aria-orientation={ariaOrientation}
collapsable={false}
style={interaction === "native-pointer" ? hitAreaStyle : touchHitAreaStyle}
onPointerEnter={interaction === "native-pointer" ? handlePointerEnter : undefined}
onPointerLeave={interaction === "native-pointer" ? handlePointerLeave : undefined}
>
{interaction === "touch" ? <View pointerEvents="none" style={touchGripStyle} /> : null}
</View>
</GestureDetector>
);
return (
<View style={handleStyle} testID={testID}>
{highlighted && (
@@ -263,27 +299,7 @@ export function ResizeHandle({
testID={testID ? `${testID}-highlight` : undefined}
/>
)}
{finePointer ? (
<View
role="separator"
aria-orientation={direction === "horizontal" ? "vertical" : "horizontal"}
style={hitAreaStyle}
onPointerDown={handlePointerDown}
onPointerEnter={handlePointerEnter}
onPointerLeave={handlePointerLeave}
/>
) : (
<GestureDetector gesture={touchGesture}>
<View
role="separator"
aria-orientation={direction === "horizontal" ? "vertical" : "horizontal"}
collapsable={false}
style={touchHitAreaStyle}
>
<View pointerEvents="none" style={touchGripStyle} />
</View>
</GestureDetector>
)}
{separatorHitArea}
</View>
);
}
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useRef } from "react";
import type { GestureResponderEvent } from "react-native";
import * as Haptics from "expo-haptics";
import { isWeb as platformIsWeb } from "@/constants/platform";
import { supportsTouchHaptics, usesTouchLongPressHold } from "@/constants/touch-timing";
import { decideLongPressMove } from "@/utils/sidebar-gesture-arbitration";
import type { useContextMenu } from "@/components/ui/context-menu";
@@ -59,7 +59,7 @@ export function useLongPressDragInteraction(input: {
const armTimers = useCallback(() => {
clearTimers();
if (platformIsWeb || !drag) {
if (!usesTouchLongPressHold || !drag) {
return;
}
@@ -86,7 +86,7 @@ export function useLongPressDragInteraction(input: {
dragArmedRef.current = true;
dragActivatedRef.current = true;
didLongPressRef.current = true;
void Haptics.selectionAsync().catch(() => {});
if (supportsTouchHaptics) void Haptics.selectionAsync().catch(() => {});
drag();
}, DRAG_ARM_DELAY_MS);
@@ -109,7 +109,7 @@ export function useLongPressDragInteraction(input: {
if (distance > CONTEXT_MENU_STATIONARY_SLOP_PX) {
return;
}
void Haptics.selectionAsync().catch(() => {});
if (supportsTouchHaptics) void Haptics.selectionAsync().catch(() => {});
openContextMenuAtStartPoint();
}, CONTEXT_MENU_DELAY_MS);
}, [clearTimers, drag, menuController, openContextMenuAtStartPoint]);
+12 -7
View File
@@ -22,6 +22,7 @@ import {
} from "@getpaseo/protocol/terminal-input-mode";
import { useTranslation } from "react-i18next";
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
import { hasSoftwareKeyboard } from "@/keyboard";
import { useKeyboardShiftStyle } from "@/keyboard/shift";
import { useAppActivelyVisible } from "@/hooks/use-app-visible";
import { useStableEvent } from "@/hooks/use-stable-event";
@@ -89,7 +90,6 @@ import {
type TerminalResizeRequest,
} from "./terminal-resize-debouncer";
import { useIsCompactFormFactor } from "@/constants/layout";
import { isNative } from "@/constants/platform";
import { useKeyboardFocusSurface } from "@/keyboard";
import {
applyTerminalRendererReadyChange,
@@ -305,7 +305,10 @@ export function TerminalPane({
return trimmed.length > 0 ? trimmed : undefined;
}, [settings.monoFontFamily]);
const isMobile = useIsCompactFormFactor();
const showVirtualKeyBar = shouldShowTerminalVirtualKeyBar({ isNative, isCompact: isMobile });
const showVirtualKeyBar = shouldShowTerminalVirtualKeyBar({
hasSoftwareKeyboard,
isCompact: isMobile,
});
const [keyBarWidth, setKeyBarWidth] = useState(0);
const virtualKeyboardRows = resolveTerminalVirtualKeyboardRows({
isCompact: isMobile,
@@ -316,7 +319,7 @@ export function TerminalPane({
const swipeGesturesEnabled = isMobile;
const { shift: keyboardShift, style: keyboardPaddingStyle } = useKeyboardShiftStyle({
mode: "padding",
enabled: isNative || isMobile,
enabled: hasSoftwareKeyboard || isMobile,
});
const [keyboardInset, setKeyboardInset] = useState(0);
const [isKeyboardVisible, setIsKeyboardVisible] = useState(false);
@@ -608,7 +611,7 @@ export function TerminalPane({
const handleKeyboardChange = useCallback(
(nextShift: number) => {
setKeyboardInset(isNative || isMobile ? nextShift : 0);
setKeyboardInset(hasSoftwareKeyboard || isMobile ? nextShift : 0);
setIsKeyboardVisible(nextShift > 0);
pulseKeyboardRefits();
},
@@ -1180,10 +1183,10 @@ export function TerminalPane({
emulatorRef.current?.blur();
onOpenFileExplorer();
}, [swipeGesturesEnabled, onOpenFileExplorer]);
const showPasteAction = shouldShowTerminalPasteAction({ isNative });
const showPasteAction = shouldShowTerminalPasteAction({ hasSoftwareKeyboard });
const showFloatingCopyAction = shouldShowTerminalFloatingCopyAction({
hasSelection,
isNative,
hasSoftwareKeyboard,
});
const keyboardToggleIconColor = theme.colors.foregroundMuted;
@@ -1332,7 +1335,9 @@ export function TerminalPane({
<View
style={styles.keyboardRows}
onLayout={handleKeyBarLayout}
testID={isNative && !isMobile ? "terminal-virtual-keyboard-native-wide" : undefined}
testID={
hasSoftwareKeyboard && !isMobile ? "terminal-virtual-keyboard-native-wide" : undefined
}
>
{virtualKeyboardRows.map((row) => (
<View
@@ -0,0 +1 @@
export { PressHighlight } from "./press-highlight.immediate";
@@ -0,0 +1,13 @@
import { forwardRef } from "react";
import { Pressable, type View } from "react-native";
import { usePressFill } from "./press-highlight.fill";
import type { PressHighlightProps } from "./press-highlight.types";
/** Immediate press highlight without mobile touch-scroll hold delay. */
export const PressHighlight = forwardRef<View, PressHighlightProps>(function PressHighlight(
{ highlightStyle, onHighlightChange, style, onPressIn, onPressOut, ...props },
ref,
) {
const fill = usePressFill({ style, highlightStyle, onPressIn, onPressOut, onHighlightChange });
return <Pressable ref={ref} {...props} {...fill} />;
});
@@ -1,13 +1 @@
import { forwardRef } from "react";
import { Pressable } from "react-native";
import type { View } from "react-native";
import { usePressFill } from "./press-highlight.fill";
import type { PressHighlightProps } from "./press-highlight.types";
export const PressHighlight = forwardRef<View, PressHighlightProps>(function PressHighlight(
{ highlightStyle, onHighlightChange, style, onPressIn, onPressOut, ...props },
ref,
) {
const fill = usePressFill({ style, highlightStyle, onPressIn, onPressOut, onHighlightChange });
return <Pressable ref={ref} {...props} {...fill} />;
});
export { PressHighlight } from "./press-highlight.immediate";
@@ -24,7 +24,8 @@ import { resolveModelTriggerLabels } from "@/composer/agent-controls/layout";
import { resolveModelSheetOpening } from "@/composer/agent-controls/model-sheet-flow";
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
import { useIsCompactFormFactor } from "@/constants/layout";
import { isNative, isWeb } from "@/constants/platform";
import { usesCompactBottomSheet } from "@/constants/presentation";
import { hasSoftwareKeyboard } from "@/keyboard";
import { readMeasuredWidth } from "@/hooks/use-container-width";
import {
toolbarContentSlot,
@@ -166,7 +167,7 @@ export function CompactModelSheet({
const { t } = useTranslation();
const usesBottomSheet = useIsCompactFormFactor();
const modelBrowserScrolling = resolveModelBrowserScrolling({
isNative,
usesCompactBottomSheet,
isCompact: usesBottomSheet,
});
const [isOpen, setIsOpen] = useState(false);
@@ -182,7 +183,7 @@ export function CompactModelSheet({
selectedProvider,
selectedModel,
isLoading,
autoFocusSearch: isWeb && !usesBottomSheet,
autoFocusSearch: !hasSoftwareKeyboard && !usesBottomSheet,
profiles,
serverId,
});
@@ -191,7 +192,7 @@ export function CompactModelSheet({
selectedProvider,
selectedModel,
isLoading,
autoFocusSearch: isWeb && !usesBottomSheet,
autoFocusSearch: !hasSoftwareKeyboard && !usesBottomSheet,
profiles,
serverId,
});
+2 -1
View File
@@ -45,6 +45,7 @@ import {
toolbarSlot,
} from "@/components/ui/control-geometry";
import { usePanelStore, type MobilePanelView } from "@/stores/panel-store";
import { hasSoftwareKeyboard } from "@/keyboard";
import { usePointerCapabilities } from "@/hooks/pointer-capabilities";
import { useShallow } from "zustand/shallow";
import {
@@ -235,7 +236,7 @@ function resolveKeyboardPriority(isMessageInputFocused: boolean): number {
}
function resolveIsDesktopWebBreakpoint(isMobile: boolean): boolean {
return isWeb && !isMobile;
return !hasSoftwareKeyboard && !isMobile;
}
function resolveCompactLayout(override: boolean | undefined, formFactor: boolean): boolean {
+31 -12
View File
@@ -80,8 +80,11 @@ import { useIosHardwareKeyboardSubmit } from "@/hooks/use-ios-hardware-keyboard-
import { formatShortcut, type ShortcutKey } from "@/utils/format-shortcut";
import { getShortcutOs } from "@/utils/shortcut-platform";
import type { MessageInputKeyboardActionKind } from "@/keyboard/actions";
import { supportsConfigurableComposerSendKeys } from "@/keyboard";
import { isImeComposingKeyboardEvent } from "@/utils/keyboard-ime";
import { isNative, isWeb } from "@/constants/platform";
import { isWeb } from "@/constants/platform";
import { composerMinInputHeight } from "@/constants/presentation";
import { supportsTouchHaptics } from "@/constants/touch-timing";
import { useIsCompactFormFactor } from "@/constants/layout";
import { useComposerKeyboardScope } from "@/composer/keyboard-scope";
import { RenderProfile } from "@/utils/render-profiler";
@@ -239,11 +242,9 @@ export interface MessageInputRef {
getNativeElement?: () => HTMLElement | null;
}
const MIN_INPUT_HEIGHT_MOBILE = 30;
const MIN_INPUT_HEIGHT_DESKTOP = 46;
const DEFAULT_MAX_INPUT_HEIGHT = 160;
const MAX_INPUT_VIEWPORT_RATIO = 0.5;
const MIN_INPUT_HEIGHT = isWeb ? MIN_INPUT_HEIGHT_DESKTOP : MIN_INPUT_HEIGHT_MOBILE;
const MIN_INPUT_HEIGHT = composerMinInputHeight;
type WebTextInputKeyPressEvent = NativeSyntheticEvent<
TextInputKeyPressEventData & {
metaKey?: boolean;
@@ -457,6 +458,14 @@ function SendButtonContent({
);
}
function resolveComposerSubmitBehavior(
shouldSubmitOnEnter: boolean,
sendShortcut: SendShortcut,
): EditingTextInputProps["submitBehavior"] {
if (!shouldSubmitOnEnter || sendShortcut !== "enter" || isWeb) return undefined;
return "submit";
}
interface DesktopKeyPressContext {
onKeyPressCallback: ((event: ComposerKeyPressEvent) => boolean) | undefined;
input: ComposerKeyPressEvent["input"];
@@ -692,6 +701,7 @@ interface ComposerTextSurfaceProps {
editable: boolean;
scrollEnabled: boolean;
autoFocus: boolean;
submitBehavior?: EditingTextInputProps["submitBehavior"];
onKeyPress: ((event: WebTextInputKeyPressEvent) => void) | undefined;
onSelectionChange: (event: NativeSyntheticEvent<TextInputSelectionChangeEventData>) => void;
onPasteImages: ((files: readonly NativePastedFile[]) => void) | undefined;
@@ -785,6 +795,7 @@ function ComposerTextSurface(props: ComposerTextSurfaceProps): React.ReactElemen
onBlur={props.onBlur}
style={textInputStyle}
multiline
submitBehavior={props.submitBehavior}
scrollEnabled={props.scrollEnabled}
editable={props.editable}
onKeyPress={props.onKeyPress}
@@ -1861,7 +1872,7 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
});
const handleLongPressSend = useCallback(() => {
if (alternateSendAction && isNative) {
if (alternateSendAction && supportsTouchHaptics) {
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium).catch(() => {});
}
handleAlternateSendAction();
@@ -1886,12 +1897,13 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
[onSelectionChangeCallback],
);
const shouldHandleWebKeyPress = isWeb;
const shouldSubmitOnEnter = isWeb && !isCompact;
const shouldHandleKeyPress = supportsConfigurableComposerSendKeys;
const shouldSubmitOnEnter = supportsConfigurableComposerSendKeys && !isCompact;
const composerSubmitBehavior = resolveComposerSubmitBehavior(shouldSubmitOnEnter, sendShortcut);
const handleDesktopKeyPress = useCallback(
(event: WebTextInputKeyPressEvent) => {
if (!shouldHandleWebKeyPress) return;
if (!shouldHandleKeyPress) return;
handleDesktopKeyPressImpl(event, {
onKeyPressCallback,
input: getComposerInputSnapshot(
@@ -1911,7 +1923,7 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
});
},
[
shouldHandleWebKeyPress,
shouldHandleKeyPress,
onKeyPressCallback,
shouldSubmitOnEnter,
sendShortcut,
@@ -2189,14 +2201,20 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
editable={!isDictating && !isRealtimeVoiceForCurrentAgent && !disabled}
scrollEnabled={isComposerScrollEnabled}
autoFocus={false}
onKeyPress={shouldHandleWebKeyPress ? handleDesktopKeyPress : undefined}
submitBehavior={composerSubmitBehavior}
onKeyPress={shouldHandleKeyPress ? handleDesktopKeyPress : undefined}
onSelectionChange={handleSelectionChange}
onPasteImages={onPasteImages}
onPasteError={handlePasteError}
fullscreen={isFullscreen}
compact={isCompact}
onRenderedLinesChange={setRenderedLines}
focusHintVisible={!isFullscreen && isWeb && !isInputFocused && !hasLiveText}
focusHintVisible={
!isFullscreen &&
supportsConfigurableComposerSendKeys &&
!isInputFocused &&
!hasLiveText
}
focusInputKeys={focusInputKeys}
focusHintLabel={t("composer.input.focusHint", {
shortcut: focusInputKeys ? formatShortcut(focusInputKeys[0], getShortcutOs()) : "",
@@ -2220,7 +2238,8 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
isRealtimeVoiceForCurrentAgent,
disabled,
isComposerScrollEnabled,
shouldHandleWebKeyPress,
composerSubmitBehavior,
shouldHandleKeyPress,
handleDesktopKeyPress,
handleSelectionChange,
onPasteImages,
+3
View File
@@ -25,6 +25,9 @@ export const isWeb = Platform.OS === "web";
/** iOS or Android — the JS runtime is React Native. */
export const isNative = Platform.OS !== "web";
/** Platforms with an alpha-mask compositor for decorative shimmer effects. */
export const supportsMaskedEffects = ["web", "ios", "android"].includes(Platform.OS);
/** Development build/runtime — true in Metro dev bundles, false in production. */
export const isDev = Boolean((globalThis as { __DEV__?: boolean }).__DEV__);
@@ -0,0 +1,9 @@
import { FONT_SIZE } from "@/styles/theme";
export const allowsInlineWorkspaceRename = true;
export const usesCompactBottomSheet = false;
export const usesDesktopPopoverSpacing = true;
export const initialUiBaseFontSize = FONT_SIZE.base;
export const initialContentFontSize = FONT_SIZE.content;
export const usesMobileContentFontMigration = false;
export const composerMinInputHeight = 46;
@@ -0,0 +1,54 @@
import { describe, expect, it } from "vitest";
import * as gpuiPresentation from "./presentation.gpui";
describe("presentation capabilities per target", () => {
it("resolves mobile and desktop presentation answers for iOS, Android, web, and Electron", async () => {
const basePresentation = (await import(
new URL("./presentation.ts", import.meta.url).href
)) as typeof import("./presentation");
expect(
basePresentation.resolvePresentationCapabilities({ isNative: true, isWeb: false }),
).toEqual({
allowsInlineWorkspaceRename: false,
usesCompactBottomSheet: true,
usesDesktopPopoverSpacing: false,
initialUiBaseFontSize: 15,
initialContentFontSize: 16,
usesMobileContentFontMigration: true,
composerMinInputHeight: 30,
});
expect(
basePresentation.resolvePresentationCapabilities({ isNative: false, isWeb: true }),
).toEqual({
allowsInlineWorkspaceRename: true,
usesCompactBottomSheet: false,
usesDesktopPopoverSpacing: true,
initialUiBaseFontSize: 14,
initialContentFontSize: 15,
usesMobileContentFontMigration: false,
composerMinInputHeight: 46,
});
});
it("exports plain desktop presentation values on GPUI without a target resolver", () => {
expect({
allowsInlineWorkspaceRename: gpuiPresentation.allowsInlineWorkspaceRename,
usesCompactBottomSheet: gpuiPresentation.usesCompactBottomSheet,
usesDesktopPopoverSpacing: gpuiPresentation.usesDesktopPopoverSpacing,
initialUiBaseFontSize: gpuiPresentation.initialUiBaseFontSize,
initialContentFontSize: gpuiPresentation.initialContentFontSize,
usesMobileContentFontMigration: gpuiPresentation.usesMobileContentFontMigration,
composerMinInputHeight: gpuiPresentation.composerMinInputHeight,
}).toEqual({
allowsInlineWorkspaceRename: true,
usesCompactBottomSheet: false,
usesDesktopPopoverSpacing: true,
initialUiBaseFontSize: 14,
initialContentFontSize: 15,
usesMobileContentFontMigration: false,
composerMinInputHeight: 46,
});
expect("resolvePresentationCapabilities" in gpuiPresentation).toBe(false);
});
});
@@ -0,0 +1,44 @@
import { FONT_SIZE } from "@/styles/theme";
import { isNative, isWeb } from "./platform";
export interface PresentationCapabilities {
/** Wide sidebar rows rename in place instead of opening a rename modal. */
allowsInlineWorkspaceRename: boolean;
/** Compact screens present bottom sheets (`SheetFlatList` / Gorhom modal) instead of dialogs. */
usesCompactBottomSheet: boolean;
/** Popover lists use tight desktop row padding instead of touch-sheet spacing. */
usesDesktopPopoverSpacing: boolean;
/** Initial UI font size (pt) when no user preference is saved. */
initialUiBaseFontSize: number;
/** Initial chat content font size (pt) when no user preference is saved. */
initialContentFontSize: number;
/** Whether legacy 15 pt persisted content size migrates up to the mobile 16 pt default. */
usesMobileContentFontMigration: boolean;
/** Minimum multiline composer input height (pt). */
composerMinInputHeight: number;
}
export function resolvePresentationCapabilities(input: {
isNative: boolean;
isWeb: boolean;
}): PresentationCapabilities {
return {
allowsInlineWorkspaceRename: input.isWeb,
usesCompactBottomSheet: input.isNative,
usesDesktopPopoverSpacing: input.isWeb,
initialUiBaseFontSize: input.isNative ? 15 : FONT_SIZE.base,
initialContentFontSize: input.isNative ? 16 : FONT_SIZE.content,
usesMobileContentFontMigration: input.isNative,
composerMinInputHeight: input.isWeb ? 46 : 30,
};
}
const CAPABILITIES = resolvePresentationCapabilities({ isNative, isWeb });
export const allowsInlineWorkspaceRename = CAPABILITIES.allowsInlineWorkspaceRename;
export const usesCompactBottomSheet = CAPABILITIES.usesCompactBottomSheet;
export const usesDesktopPopoverSpacing = CAPABILITIES.usesDesktopPopoverSpacing;
export const initialUiBaseFontSize = CAPABILITIES.initialUiBaseFontSize;
export const initialContentFontSize = CAPABILITIES.initialContentFontSize;
export const usesMobileContentFontMigration = CAPABILITIES.usesMobileContentFontMigration;
export const composerMinInputHeight = CAPABILITIES.composerMinInputHeight;
@@ -0,0 +1,11 @@
import type { SourceFileBudgets } from "./resource-budget";
// Mounted workspace retention limit on GPUI (adjust independently while memory retention is measured).
export const workspaceDeckRetentionLimit = 10;
export const sourceFileBudgets: SourceFileBudgets = {
highlighted: 10 * 1024 * 1024,
plain: 50 * 1024 * 1024,
};
export const deferModelSelectorMount = false;
@@ -0,0 +1,34 @@
import { describe, expect, it } from "vitest";
import * as gpuiBudget from "./resource-budget.gpui";
describe("resource budget per target", () => {
it("resolves mobile and desktop resource budget limits for iOS, Android, web, and Electron", async () => {
const baseBudget = (await import(
new URL("./resource-budget.ts", import.meta.url).href
)) as typeof import("./resource-budget");
expect(baseBudget.resolveResourceBudgets({ isNative: true })).toEqual({
workspaceDeckRetentionLimit: 1,
sourceFileBudgets: { highlighted: 1024 * 1024, plain: 10 * 1024 * 1024 },
deferModelSelectorMount: true,
});
expect(baseBudget.resolveResourceBudgets({ isNative: false })).toEqual({
workspaceDeckRetentionLimit: 10,
sourceFileBudgets: { highlighted: 10 * 1024 * 1024, plain: 50 * 1024 * 1024 },
deferModelSelectorMount: false,
});
});
it("exports plain desktop-sized resource budget values on GPUI without a target resolver", () => {
expect({
workspaceDeckRetentionLimit: gpuiBudget.workspaceDeckRetentionLimit,
sourceFileBudgets: gpuiBudget.sourceFileBudgets,
deferModelSelectorMount: gpuiBudget.deferModelSelectorMount,
}).toEqual({
workspaceDeckRetentionLimit: 10,
sourceFileBudgets: { highlighted: 10 * 1024 * 1024, plain: 50 * 1024 * 1024 },
deferModelSelectorMount: false,
});
expect("resolveResourceBudgets" in gpuiBudget).toBe(false);
});
});
@@ -0,0 +1,35 @@
import { isNative } from "./platform";
export interface SourceFileBudgets {
readonly highlighted: number;
readonly plain: number;
}
export interface PlatformResourceBudgets {
readonly workspaceDeckRetentionLimit: number;
readonly sourceFileBudgets: SourceFileBudgets;
readonly deferModelSelectorMount: boolean;
}
const MOBILE_RESOURCE_BUDGETS: PlatformResourceBudgets = {
workspaceDeckRetentionLimit: 1,
sourceFileBudgets: { highlighted: 1024 * 1024, plain: 10 * 1024 * 1024 },
deferModelSelectorMount: true,
};
const WEB_RESOURCE_BUDGETS: PlatformResourceBudgets = {
workspaceDeckRetentionLimit: 10,
sourceFileBudgets: { highlighted: 10 * 1024 * 1024, plain: 50 * 1024 * 1024 },
deferModelSelectorMount: false,
};
/** Shipping-target resolver: native phones use mobile memory budgets; web and Electron use desktop budgets. */
export function resolveResourceBudgets(input: { isNative: boolean }): PlatformResourceBudgets {
return input.isNative ? MOBILE_RESOURCE_BUDGETS : WEB_RESOURCE_BUDGETS;
}
const RESOURCE_BUDGETS = resolveResourceBudgets({ isNative });
export const workspaceDeckRetentionLimit = RESOURCE_BUDGETS.workspaceDeckRetentionLimit;
export const sourceFileBudgets = RESOURCE_BUDGETS.sourceFileBudgets;
export const deferModelSelectorMount = RESOURCE_BUDGETS.deferModelSelectorMount;
@@ -0,0 +1,2 @@
export const supportsTouchHaptics = false;
export const usesTouchLongPressHold = false;
@@ -0,0 +1,27 @@
import { describe, expect, it } from "vitest";
import * as gpuiTouchTiming from "./touch-timing.gpui";
describe("touch timing per target", () => {
it("enables touch timing and haptics only on mobile touch platforms, not on web, Electron, or GPUI", async () => {
const baseTiming = (await import(
new URL("./touch-timing.ts", import.meta.url).href
)) as typeof import("./touch-timing");
expect(baseTiming.resolveTouchTiming({ isNative: true })).toEqual({
supportsTouchHaptics: true,
usesTouchLongPressHold: true,
});
expect(baseTiming.resolveTouchTiming({ isNative: false })).toEqual({
supportsTouchHaptics: false,
usesTouchLongPressHold: false,
});
expect({
supportsTouchHaptics: gpuiTouchTiming.supportsTouchHaptics,
usesTouchLongPressHold: gpuiTouchTiming.usesTouchLongPressHold,
}).toEqual({
supportsTouchHaptics: false,
usesTouchLongPressHold: false,
});
expect("resolveTouchTiming" in gpuiTouchTiming).toBe(false);
});
});
@@ -0,0 +1,20 @@
import { isNative } from "./platform";
export interface TouchTimingCapabilities {
/** Fire tactile `expo-haptics` feedback on touch interactions. */
supportsTouchHaptics: boolean;
/** Require a stationary long-press delay to arm drag or open context menus. */
usesTouchLongPressHold: boolean;
}
export function resolveTouchTiming(input: { isNative: boolean }): TouchTimingCapabilities {
return {
supportsTouchHaptics: input.isNative,
usesTouchLongPressHold: input.isNative,
};
}
const TOUCH_TIMING = resolveTouchTiming({ isNative });
export const supportsTouchHaptics = TOUCH_TIMING.supportsTouchHaptics;
export const usesTouchLongPressHold = TOUCH_TIMING.usesTouchLongPressHold;
@@ -0,0 +1,9 @@
import { Text, View } from "react-native";
export function DocumentFrame({ url: _url, testID }: { url: string; testID?: string }) {
return (
<View testID={testID}>
<Text>Document preview is not available in the GPUI build yet.</Text>
</View>
);
}
@@ -0,0 +1,36 @@
import { ScrollView, Text } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { HighlightedCodeBlock } from "@/components/highlighted-code-block";
import type { Theme } from "@/styles/theme";
const ThemedHighlightedCodeBlock = withUnistyles(HighlightedCodeBlock);
const codeBlockStyles = (theme: Theme) => ({
inheritedStyles: {
color: theme.colors.foreground,
fontFamily: theme.fontFamily.mono,
fontSize: theme.fontSize.code,
},
textStyle: {
backgroundColor: theme.colors.surface2,
padding: theme.spacing[3],
borderRadius: theme.borderRadius.lg,
},
});
export function FileHtmlPreview({ html, testID }: { html: string; testID?: string }) {
return (
<ScrollView testID={testID}>
<Text style={styles.notice}>HTML rendering is not available in GPUI. Showing source.</Text>
<ThemedHighlightedCodeBlock code={html} language="html" uniProps={codeBlockStyles} />
</ScrollView>
);
}
const styles = StyleSheet.create((theme) => ({
notice: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
marginBottom: theme.spacing[2],
},
}));
@@ -76,7 +76,7 @@ type TextFilePanelProps = PluginFilePanelProps & {
*/
export function TextFilePanel(props: TextFilePanelProps) {
const size = props.file.size;
const presentation = selectSourcePresentation({ size, platform: isWeb ? "web" : "native" });
const presentation = selectSourcePresentation({ size });
if (presentation === "unsupported") return <TooLargeTextFile size={size} />;
if (isWeb && size <= MAX_EDITABLE_BYTES) return <EditableTextFile {...props} />;
return <ReadonlyTextFile {...props} presentation={presentation} />;
@@ -11,4 +11,11 @@ describe("selectSourcePresentation", () => {
expect(selectSourcePresentation({ platform, size: budgets.plain + 1 })).toBe("unsupported");
});
}
it("defaults to the target resource budget limits when no platform override is passed", () => {
const webBudgets = SOURCE_PRESENTATION_BUDGETS.web;
expect(selectSourcePresentation({ size: webBudgets.highlighted })).toBe("highlighted");
expect(selectSourcePresentation({ size: webBudgets.highlighted + 1 })).toBe("plain");
expect(selectSourcePresentation({ size: webBudgets.plain + 1 })).toBe("unsupported");
});
});
@@ -1,6 +1,8 @@
import { resolveResourceBudgets, sourceFileBudgets } from "@/constants/resource-budget";
export const SOURCE_PRESENTATION_BUDGETS = {
web: { highlighted: 10 * 1024 * 1024, plain: 50 * 1024 * 1024 },
native: { highlighted: 1024 * 1024, plain: 10 * 1024 * 1024 },
web: resolveResourceBudgets({ isNative: false }).sourceFileBudgets,
native: resolveResourceBudgets({ isNative: true }).sourceFileBudgets,
} as const;
export type SourcePresentation = "highlighted" | "plain" | "unsupported";
@@ -8,9 +10,9 @@ export type SourcePlatform = keyof typeof SOURCE_PRESENTATION_BUDGETS;
export function selectSourcePresentation(input: {
size: number;
platform: SourcePlatform;
platform?: SourcePlatform;
}): SourcePresentation {
const budgets = SOURCE_PRESENTATION_BUDGETS[input.platform];
const budgets = input.platform ? SOURCE_PRESENTATION_BUDGETS[input.platform] : sourceFileBudgets;
if (input.size <= budgets.highlighted) return "highlighted";
if (input.size <= budgets.plain) return "plain";
return "unsupported";
@@ -0,0 +1,21 @@
import type { PointerCapabilities, PointerCapabilitiesSource } from "./pointer-capabilities";
export type { PointerCapabilities, PointerCapabilitiesSource };
// The GPUI desktop client runs in a macOS, Linux, or Windows window. The runtime reports
// every pointer as a mouse, so a fine pointer drives the UI and the answer never changes.
const GPUI_POINTER_CAPABILITIES: PointerCapabilities = { finePointer: true, touchScreen: false };
export function usePointerCapabilities(): PointerCapabilities {
return GPUI_POINTER_CAPABILITIES;
}
/** True when a mouse-like pointer drives the UI, read at call time. */
export function hasFinePointer(): boolean {
return true;
}
/** True when touch is the primary input, read at call time. */
export function hasTouchPrimaryPointer(): boolean {
return false;
}
@@ -1,5 +1,13 @@
import { describe, expect, it } from "vitest";
import { createPointerCapabilitiesSource } from "./pointer-capabilities";
import {
createNativePointerCapabilitiesSource,
createPointerCapabilitiesSource,
} from "./pointer-capabilities";
import {
hasFinePointer as hasGpuiFinePointer,
hasTouchPrimaryPointer as hasGpuiTouchPrimaryPointer,
usePointerCapabilities as useGpuiPointerCapabilities,
} from "./pointer-capabilities.gpui";
class FakeMediaQueryList {
private readonly listeners = new Set<() => void>();
@@ -105,3 +113,28 @@ describe("hasTouchPrimaryPointer", () => {
expect(createPointerCapabilitiesSource(null).hasTouchPrimaryPointer()).toBe(false);
});
});
describe("pointer capabilities per target", () => {
it("reports a coarse touch primary pointer on native iOS/Android", () => {
const nativeSource = createNativePointerCapabilitiesSource();
expect(nativeSource.getSnapshot()).toEqual({ finePointer: false, touchScreen: true });
expect(nativeSource.hasTouchPrimaryPointer()).toBe(true);
});
it("reports fine pointer without touch screen on desktop web/Electron", () => {
const desktopDisplay = createFakeDisplay({
finePointer: true,
touchScreen: false,
touchPrimaryPointer: false,
});
const desktopSource = createPointerCapabilitiesSource(desktopDisplay.matchMedia);
expect(desktopSource.getSnapshot()).toEqual({ finePointer: true, touchScreen: false });
expect(desktopSource.hasTouchPrimaryPointer()).toBe(false);
});
it("reports fine pointer without touch screen on GPUI", () => {
expect(useGpuiPointerCapabilities()).toEqual({ finePointer: true, touchScreen: false });
expect(hasGpuiFinePointer()).toBe(true);
expect(hasGpuiTouchPrimaryPointer()).toBe(false);
});
});
+11 -6
View File
@@ -62,13 +62,18 @@ function browserMatchMedia(): MatchMedia | null {
// Native builds run on iOS and Android touch screens. A paired mouse or pen is
// filtered per gesture event by its pointer type, not by this capability.
const NATIVE_POINTER_CAPABILITIES: PointerCapabilities = { finePointer: false, touchScreen: true };
const nativeSource: PointerCapabilitiesSource = {
getSnapshot: () => NATIVE_POINTER_CAPABILITIES,
subscribe: () => () => {},
hasTouchPrimaryPointer: () => true,
};
const source = isWeb ? createPointerCapabilitiesSource(browserMatchMedia()) : nativeSource;
export function createNativePointerCapabilitiesSource(): PointerCapabilitiesSource {
return {
getSnapshot: () => NATIVE_POINTER_CAPABILITIES,
subscribe: () => () => {},
hasTouchPrimaryPointer: () => true,
};
}
const source = isWeb
? createPointerCapabilitiesSource(browserMatchMedia())
: createNativePointerCapabilitiesSource();
const SERVER_SNAPSHOT: PointerCapabilities = { finePointer: false, touchScreen: false };
function getServerSnapshot(): PointerCapabilities {
+10 -4
View File
@@ -23,7 +23,11 @@ import {
isChecksHiddenByLegacyRowItem,
type SidebarRowItems,
} from "@/components/sidebar/display-preferences/row-items";
import { isNative } from "@/constants/platform";
import {
initialContentFontSize,
initialUiBaseFontSize,
usesMobileContentFontMigration,
} from "@/constants/presentation";
import {
DEFAULT_CONTENT_MAX_WIDTH,
FONT_SIZE,
@@ -63,14 +67,14 @@ export function defaultUiBaseFontSize(native: boolean): number {
return native ? 15 : FONT_SIZE.base;
}
export const DEFAULT_UI_BASE_FONT_SIZE = defaultUiBaseFontSize(isNative);
export const DEFAULT_UI_BASE_FONT_SIZE = initialUiBaseFontSize;
export const MIN_UI_BASE_FONT_SIZE = 10;
export const MAX_UI_BASE_FONT_SIZE = 21;
export function defaultContentFontSize(native: boolean): number {
return native ? 16 : FONT_SIZE.content;
}
export const DEFAULT_CONTENT_FONT_SIZE = defaultContentFontSize(isNative);
export const DEFAULT_CONTENT_FONT_SIZE = initialContentFontSize;
export const MIN_CONTENT_FONT_SIZE = 10;
export const MAX_CONTENT_FONT_SIZE = 21;
export const DEFAULT_CODE_FONT_SIZE = 12; // == FONT_SIZE.code
@@ -410,7 +414,9 @@ export async function loadAppSettingsFromStorage(deps: SettingsDeps): Promise<Ap
await writeAppSettings(deps.storage, read.stored, read.settings);
}
const { needsWrite: _needsWrite, ...stored } = read.stored;
return await migrateAppSettings(read.settings, deps.storage, stored, { native: isNative });
return await migrateAppSettings(read.settings, deps.storage, stored, {
native: usesMobileContentFontMigration,
});
} catch (error) {
console.error("[AppSettings] Failed to load settings:", error);
throw error;
@@ -1,5 +1,9 @@
import { describe, expect, it } from "vitest";
import { createHardwareKeyboardPresence } from "./internal/hardware-presence";
import * as gpuiConventions from "./internal/conventions.gpui";
import * as webConventions from "./internal/conventions.web";
import { hardwareKeyboardPresence as gpuiPresence } from "./internal/presence.gpui";
import { createWebHardwareKeyboardPresence } from "./internal/presence.web";
import { buildEffectiveBindings } from "./keyboard-shortcuts";
import { createKeyboardPipeline } from "./internal/pipeline";
import { createOverlayRegistry } from "./internal/overlays";
@@ -65,4 +69,50 @@ describe("hardware keyboard availability", () => {
expect(actions).toEqual(["command-center.toggle"]);
pipeline.dispose();
});
it("answers keyboard presence and conventions per target", async () => {
const nativeConventions = (await import(
new URL("./internal/conventions.ts", import.meta.url).href
)) as typeof gpuiConventions;
const { hardwareKeyboardPresence: nativePresence } = (await import(
new URL("./internal/presence.ts", import.meta.url).href
)) as { hardwareKeyboardPresence: typeof gpuiPresence };
expect(nativePresence.getSnapshot()).toBe(false);
expect(gpuiPresence.getSnapshot()).toBe(true);
expect(
createWebHardwareKeyboardPresence({ matches: true } as MediaQueryList, null).getSnapshot(),
).toBe(true);
expect(
createWebHardwareKeyboardPresence({ matches: false } as MediaQueryList, null).getSnapshot(),
).toBe(false);
expect({
usesDesktopBindings: nativeConventions.usesDesktopBindings,
supportsConfigurableComposerSendKeys: nativeConventions.supportsConfigurableComposerSendKeys,
hasSoftwareKeyboard: nativeConventions.hasSoftwareKeyboard,
}).toEqual({
usesDesktopBindings: true,
supportsConfigurableComposerSendKeys: false,
hasSoftwareKeyboard: true,
});
expect({
supportsConfigurableComposerSendKeys: webConventions.supportsConfigurableComposerSendKeys,
hasSoftwareKeyboard: webConventions.hasSoftwareKeyboard,
}).toEqual({
supportsConfigurableComposerSendKeys: true,
hasSoftwareKeyboard: false,
});
expect({
usesDesktopBindings: gpuiConventions.usesDesktopBindings,
supportsConfigurableComposerSendKeys: gpuiConventions.supportsConfigurableComposerSendKeys,
hasSoftwareKeyboard: gpuiConventions.hasSoftwareKeyboard,
}).toEqual({
usesDesktopBindings: true,
supportsConfigurableComposerSendKeys: true,
hasSoftwareKeyboard: false,
});
});
});
+5 -1
View File
@@ -11,7 +11,11 @@ export { hasFocusedTextInput, registerFocusedTextInput } from "./internal/focuse
export { useKeyboardFocusSurface } from "./internal/use-focus-surface";
export { subscribeHardwareKeyboard } from "./internal/sources/hardware";
export type { HardwareKeyboardEvent } from "./internal/sources/hardware";
export { usesDesktopBindings, supportsConfigurableComposerSendKeys } from "./internal/conventions";
export {
hasSoftwareKeyboard,
usesDesktopBindings,
supportsConfigurableComposerSendKeys,
} from "./internal/conventions";
export type { BrowserKeyboardPolicy } from "./internal/sources/electron-browser";
export { useHardwareKeyboardPresent } from "./availability";
export { readPressModifiers } from "./internal/press-modifiers";
@@ -0,0 +1,3 @@
export const usesDesktopBindings = true;
export const supportsConfigurableComposerSendKeys = true;
export const hasSoftwareKeyboard = false;

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