mirror of
https://github.com/getpaseo/paseo.git
synced 2026-12-06 15:16:03 +00:00
Compare commits
34
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6e1f985ba5 | ||
|
|
200066ffe3 | ||
|
|
c5caa9a009 | ||
|
|
d69527bbe5 | ||
|
|
99045250d0 | ||
|
|
7f07d3e028 | ||
|
|
9e8bce0789 | ||
|
|
4d2a997d57 | ||
|
|
a6ac88ebe0 | ||
|
|
baacb7aaac | ||
|
|
de1b414c25 | ||
|
|
99b55930c5 | ||
|
|
880c040287 | ||
|
|
7f94f5662c | ||
|
|
1704ba4fbb | ||
|
|
a5c32c5944 | ||
|
|
922c682a30 | ||
|
|
6da4247646 | ||
|
|
60b3f42cd5 | ||
|
|
530ccef5b5 | ||
|
|
5d53876495 | ||
|
|
757b1b89a0 | ||
|
|
72c873564a | ||
|
|
cc44ecaa09 | ||
|
|
5da532efc1 | ||
|
|
08edc6edec | ||
|
|
b181573dae | ||
|
|
1437dedd95 | ||
|
|
fa8c29f9c8 | ||
|
|
10c0f9ce0e | ||
|
|
3572c40232 | ||
|
|
8514a14d8f | ||
|
|
94164a28e2 | ||
|
|
7e93dde3af |
@@ -0,0 +1,2 @@
|
||||
packages/app/gpui/package-lock.json linguist-generated
|
||||
packages/app/gpui/desktop/Cargo.lock linguist-generated
|
||||
@@ -62,6 +62,13 @@ sdk:
|
||||
- "packages/protocol/**"
|
||||
- "packages/workflows/**"
|
||||
|
||||
nix_hash:
|
||||
- "package-lock.json"
|
||||
- "nix/**"
|
||||
- "flake.lock"
|
||||
- "scripts/fix-lockfile.mjs"
|
||||
- "scripts/update-nix.sh"
|
||||
|
||||
browser:
|
||||
- "packages/server/src/server/agent/provider-snapshot-manager.ts"
|
||||
- "packages/server/src/server/session/provider/provider-catalog-session.ts"
|
||||
|
||||
@@ -47,6 +47,7 @@ jobs:
|
||||
relay: ${{ steps.filter.outputs.relay }}
|
||||
cli: ${{ steps.filter.outputs.cli }}
|
||||
website: ${{ steps.filter.outputs.website }}
|
||||
nix_hash: ${{ steps.filter.outputs.nix_hash }}
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||
with:
|
||||
@@ -68,7 +69,7 @@ jobs:
|
||||
quality:
|
||||
name: quality
|
||||
needs: changes
|
||||
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.format != 'false' || needs.changes.outputs.quality != 'false' || needs.changes.outputs.relay != 'false' || needs.changes.outputs.sdk != 'false') }}
|
||||
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.format != 'false' || needs.changes.outputs.quality != 'false' || needs.changes.outputs.relay != 'false' || needs.changes.outputs.sdk != 'false' || needs.changes.outputs.nix_hash != 'false') }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
@@ -144,6 +145,16 @@ jobs:
|
||||
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
|
||||
run: npm run typecheck:examples --workspace=@getpaseo/client
|
||||
|
||||
- name: Install Nix
|
||||
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.nix_hash != 'false') }}
|
||||
uses: cachix/install-nix-action@3dc140bfc76c49fbd4dd958429132e3746bcb086 # v31
|
||||
with:
|
||||
nix_path: nixpkgs=channel:nixos-unstable
|
||||
|
||||
- name: Verify Nix npm-deps hash
|
||||
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.nix_hash != 'false') }}
|
||||
run: ./scripts/update-nix.sh --check
|
||||
|
||||
# Plugin process launches and launch wraps quote for cmd.exe, which only real Windows checks.
|
||||
sdk-tests-windows:
|
||||
name: sdk-tests (windows-latest)
|
||||
|
||||
@@ -0,0 +1,469 @@
|
||||
name: GPUI Experimental
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
platform:
|
||||
description: "Platform(s) to build."
|
||||
required: false
|
||||
default: "all"
|
||||
type: choice
|
||||
options:
|
||||
- all
|
||||
- macos
|
||||
- linux
|
||||
publish:
|
||||
description: "Publish built artifacts as a timestamped gpui-experimental prerelease."
|
||||
required: false
|
||||
default: "true"
|
||||
type: choice
|
||||
options:
|
||||
- "true"
|
||||
- "false"
|
||||
|
||||
concurrency:
|
||||
group: gpui-experimental-${{ github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
env:
|
||||
ONNXRUNTIME_NODE_INSTALL: skip
|
||||
NPM_CONFIG_AUDIT: "false"
|
||||
NPM_CONFIG_FUND: "false"
|
||||
RN_GPUI_JS_ENGINE: v8
|
||||
|
||||
jobs:
|
||||
build-macos:
|
||||
name: gpui-experimental (macos-latest, arm64)
|
||||
if: ${{ inputs.platform == 'all' || inputs.platform == 'macos' }}
|
||||
runs-on: macos-latest
|
||||
timeout-minutes: 60
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: "npm"
|
||||
|
||||
- name: Setup Rust toolchain
|
||||
run: |
|
||||
rustup toolchain install stable --profile minimal --no-self-update
|
||||
rustup default stable
|
||||
|
||||
- name: Cache Cargo and GPUI target
|
||||
uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
~/.cargo/git
|
||||
.artifacts/gpui/macos/target
|
||||
.artifacts/gpui/macos/native-deps
|
||||
key: gpui-nightly-cargo-v2-macos26-arm64-${{ hashFiles('packages/app/gpui/desktop/Cargo.lock', 'packages/app/gpui/package-lock.json') }}
|
||||
restore-keys: |
|
||||
gpui-nightly-cargo-v2-macos26-arm64-
|
||||
|
||||
- name: Clear restored CMake cache before configure
|
||||
run: find .artifacts/gpui/macos/target -name CMakeCache.txt -delete 2>/dev/null || true
|
||||
|
||||
- name: Install macOS build tools
|
||||
run: command -v ninja >/dev/null || brew install ninja
|
||||
|
||||
- name: Install JS dependencies and build app dependencies
|
||||
run: |
|
||||
node scripts/npm-retry.mjs ci
|
||||
npm run build:app-deps
|
||||
|
||||
- name: Install GPUI dependencies and verify V8
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
npm run gpui:install
|
||||
node packages/app/gpui/node_modules/@react-native-gpui/v8/scripts/fetch-binaries.mjs --verify
|
||||
|
||||
- name: Build macOS GPUI app bundle
|
||||
env:
|
||||
MACOSX_DEPLOYMENT_TARGET: "15.0"
|
||||
NODE_OPTIONS: --max-old-space-size=6144
|
||||
CARGO_BUILD_JOBS: "4"
|
||||
PASEO_RENDERER: gpui
|
||||
RN_GPUI_NATIVE_DEPS_CACHE: ${{ github.workspace }}/.artifacts/gpui/macos/native-deps
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
repo_root="$PWD"
|
||||
cd packages/app/gpui
|
||||
CARGO_TARGET_DIR="$repo_root/.artifacts/gpui/macos/target" \
|
||||
node node_modules/react-native/cli.js package-desktop \
|
||||
--target app --out "$repo_root/.artifacts/gpui/macos/dist"
|
||||
|
||||
- name: Check Apple signing secrets
|
||||
id: signing_secrets
|
||||
env:
|
||||
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
|
||||
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
|
||||
APPLE_ID: ${{ secrets.APPLE_ID }}
|
||||
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
run: |
|
||||
if [[ -n "$APPLE_CERTIFICATE" && -n "$APPLE_CERTIFICATE_PASSWORD" && -n "$APPLE_ID" && -n "$APPLE_PASSWORD" && -n "$APPLE_TEAM_ID" ]]; then
|
||||
echo "enabled=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "enabled=false" >> "$GITHUB_OUTPUT"
|
||||
echo "::notice::Apple signing secrets are not configured; packaging ad-hoc signed macOS build without notarization."
|
||||
fi
|
||||
|
||||
- name: Sign, verify, notarize, and package macOS DMG
|
||||
if: steps.signing_secrets.outputs.enabled == 'true'
|
||||
env:
|
||||
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
|
||||
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
|
||||
APPLE_ID: ${{ secrets.APPLE_ID }}
|
||||
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
repo_root="$PWD"
|
||||
app_path="$repo_root/.artifacts/gpui/macos/dist/Paseo GPUI.app"
|
||||
test -d "$app_path"
|
||||
|
||||
node scripts/gpui.mjs apply-macos-icon "$app_path"
|
||||
|
||||
keychain_path="$RUNNER_TEMP/gpui-signing.keychain-db"
|
||||
keychain_password="$(openssl rand -hex 24)"
|
||||
cert_path="$RUNNER_TEMP/apple-cert.p12"
|
||||
|
||||
node -e '
|
||||
const fs = require("node:fs");
|
||||
const raw = (process.env.APPLE_CERTIFICATE || "").trim().replace(/^data:[^,]*,/, "");
|
||||
fs.writeFileSync(process.argv[1], Buffer.from(raw, "base64"));
|
||||
' "$cert_path"
|
||||
|
||||
security create-keychain -p "$keychain_password" "$keychain_path"
|
||||
security set-keychain-settings -lut 21600 "$keychain_path"
|
||||
security unlock-keychain -p "$keychain_password" "$keychain_path"
|
||||
security import "$cert_path" -P "$APPLE_CERTIFICATE_PASSWORD" -A -t cert -f pkcs12 -k "$keychain_path"
|
||||
rm -f "$cert_path"
|
||||
security list-keychains -d user -s "$keychain_path" login.keychain-db
|
||||
security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$keychain_password" "$keychain_path"
|
||||
|
||||
sign_identity="$(security find-identity -v -p codesigning "$keychain_path" | sed -n 's/.*"\(Developer ID Application:[^"]*\)".*/\1/p' | head -n 1)"
|
||||
if [[ -z "$sign_identity" ]]; then
|
||||
echo "::error::No Developer ID Application certificate found in imported keychain."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
while IFS= read -r -d '' bin; do
|
||||
codesign --force --sign "$sign_identity" --timestamp --options runtime "$bin"
|
||||
done < <(find "$app_path/Contents" -type f \( -name '*.dylib' -o -name '*.so' -o -name '*.node' \) -print0)
|
||||
|
||||
codesign --force --sign "$sign_identity" --timestamp --options runtime \
|
||||
--entitlements packages/app/gpui/desktop/entitlements.mac.plist \
|
||||
"$app_path"
|
||||
|
||||
node --test packages/app/gpui/verify-macos-package.test.mjs
|
||||
node packages/app/gpui/verify-macos-package.mjs "$app_path" --require-asset-catalog
|
||||
codesign -d --entitlements :- "$app_path" 2>&1 | grep -q "com.apple.security.cs.allow-jit"
|
||||
|
||||
export PASEO_REAL_XCRUN="$(command -v xcrun)"
|
||||
xcrun_bin="$(mktemp -d)"
|
||||
trap 'rm -rf "$xcrun_bin"' EXIT
|
||||
cp scripts/macos-xcrun-retry.sh "$xcrun_bin/xcrun"
|
||||
chmod +x "$xcrun_bin/xcrun"
|
||||
export PATH="$xcrun_bin:$PATH"
|
||||
|
||||
app_notarize_zip="$RUNNER_TEMP/paseo-gpui-app-notarize.zip"
|
||||
ditto -c -k --keepParent "$app_path" "$app_notarize_zip"
|
||||
xcrun notarytool submit "$app_notarize_zip" \
|
||||
--apple-id "$APPLE_ID" \
|
||||
--password "$APPLE_PASSWORD" \
|
||||
--team-id "$APPLE_TEAM_ID" \
|
||||
--wait
|
||||
rm -f "$app_notarize_zip"
|
||||
xcrun stapler staple "$app_path"
|
||||
spctl --assess --type execute -v "$app_path"
|
||||
|
||||
out_dir="$RUNNER_TEMP/gpui-experimental-macos-arm64"
|
||||
rm -rf "$out_dir"
|
||||
node scripts/gpui.mjs package-macos-dmg "$app_path" "$out_dir"
|
||||
|
||||
dmg_path="$out_dir/Paseo-GPUI-experimental-macos-arm64.dmg"
|
||||
codesign --force --sign "$sign_identity" --timestamp "$dmg_path"
|
||||
xcrun notarytool submit "$dmg_path" \
|
||||
--apple-id "$APPLE_ID" \
|
||||
--password "$APPLE_PASSWORD" \
|
||||
--team-id "$APPLE_TEAM_ID" \
|
||||
--wait
|
||||
xcrun stapler staple "$dmg_path"
|
||||
xcrun stapler validate "$dmg_path"
|
||||
|
||||
- name: Verify and package unsigned macOS DMG (fork fallback)
|
||||
if: steps.signing_secrets.outputs.enabled != 'true'
|
||||
run: |
|
||||
set -euo pipefail
|
||||
repo_root="$PWD"
|
||||
app_path="$repo_root/.artifacts/gpui/macos/dist/Paseo GPUI.app"
|
||||
test -d "$app_path"
|
||||
node scripts/gpui.mjs apply-macos-icon "$app_path" --adhoc-resign
|
||||
node --test packages/app/gpui/verify-macos-package.test.mjs
|
||||
node packages/app/gpui/verify-macos-package.mjs "$app_path" --require-asset-catalog
|
||||
codesign -d --entitlements :- "$app_path" 2>&1 | grep -q "com.apple.security.cs.allow-jit"
|
||||
|
||||
out_dir="$RUNNER_TEMP/gpui-experimental-macos-arm64"
|
||||
rm -rf "$out_dir"
|
||||
node scripts/gpui.mjs package-macos-dmg "$app_path" "$out_dir"
|
||||
|
||||
- name: Clean up temporary Apple signing keychain
|
||||
if: always()
|
||||
run: |
|
||||
rm -f "$RUNNER_TEMP/apple-cert.p12" "$RUNNER_TEMP/paseo-gpui-app-notarize.zip"
|
||||
if [[ -f "$RUNNER_TEMP/gpui-signing.keychain-db" ]]; then
|
||||
security delete-keychain "$RUNNER_TEMP/gpui-signing.keychain-db" || true
|
||||
fi
|
||||
|
||||
- name: Generate macOS checksums
|
||||
run: node scripts/release-checksums.mjs "${{ runner.temp }}/gpui-experimental-macos-arm64" "SHA256SUMS-gpui-experimental-macos-arm64.txt"
|
||||
|
||||
- name: Upload macOS experimental artifact
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: gpui-experimental-macos-arm64
|
||||
path: ${{ runner.temp }}/gpui-experimental-macos-arm64
|
||||
retention-days: 7
|
||||
|
||||
build-linux:
|
||||
name: gpui-experimental (ubuntu-24.04, x64)
|
||||
if: ${{ inputs.platform == 'all' || inputs.platform == 'linux' }}
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 60
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: "npm"
|
||||
|
||||
- name: Setup Rust toolchain
|
||||
run: |
|
||||
rustup toolchain install stable --profile minimal --no-self-update
|
||||
rustup default stable
|
||||
|
||||
- name: Cache Cargo and GPUI target
|
||||
uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
~/.cargo/git
|
||||
.artifacts/gpui/linux/target
|
||||
.artifacts/gpui/linux/native-deps
|
||||
key: gpui-nightly-cargo-v2-linux-x64-${{ hashFiles('packages/app/gpui/desktop/Cargo.lock', 'packages/app/gpui/package-lock.json') }}
|
||||
restore-keys: |
|
||||
gpui-nightly-cargo-v2-linux-x64-
|
||||
|
||||
- name: Clear restored CMake cache before configure
|
||||
run: find .artifacts/gpui/linux/target -name CMakeCache.txt -delete 2>/dev/null || true
|
||||
|
||||
- name: Install Linux GPUI build dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y \
|
||||
build-essential \
|
||||
clang \
|
||||
cmake \
|
||||
ninja-build \
|
||||
pkg-config \
|
||||
libssl-dev \
|
||||
libfontconfig-dev \
|
||||
libfreetype-dev \
|
||||
libvulkan-dev \
|
||||
libwayland-dev \
|
||||
libx11-xcb-dev \
|
||||
libxcb1-dev \
|
||||
libxcb-render0-dev \
|
||||
libxcb-shape0-dev \
|
||||
libxcb-shm0-dev \
|
||||
libxcb-xfixes0-dev \
|
||||
libxkbcommon-dev \
|
||||
libxkbcommon-x11-dev
|
||||
|
||||
- name: Install JS dependencies and build app dependencies
|
||||
run: |
|
||||
node scripts/npm-retry.mjs ci
|
||||
npm run build:app-deps
|
||||
|
||||
- name: Install GPUI dependencies and verify V8
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
npm run gpui:install
|
||||
node packages/app/gpui/node_modules/@react-native-gpui/v8/scripts/fetch-binaries.mjs --verify
|
||||
|
||||
- name: Verify icon packaging helpers
|
||||
run: node --test packages/app/gpui/verify-macos-package.test.mjs
|
||||
|
||||
- name: Build, package, and smoke-check Linux x64 GPUI archive
|
||||
env:
|
||||
CARGO_BUILD_JOBS: "4"
|
||||
CARGO_TARGET_DIR: ${{ github.workspace }}/.artifacts/gpui/linux/target
|
||||
PASEO_RENDERER: gpui
|
||||
RN_GPUI_NATIVE_DEPS_CACHE: ${{ github.workspace }}/.artifacts/gpui/linux/native-deps
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: node scripts/gpui.mjs package-linux --out "${{ runner.temp }}/gpui-experimental-linux-x64"
|
||||
|
||||
- name: Generate Linux checksums
|
||||
run: node scripts/release-checksums.mjs "${{ runner.temp }}/gpui-experimental-linux-x64" "SHA256SUMS-gpui-experimental-linux-x64.txt"
|
||||
|
||||
- name: Upload Linux experimental artifact
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: gpui-experimental-linux-x64
|
||||
path: ${{ runner.temp }}/gpui-experimental-linux-x64
|
||||
retention-days: 7
|
||||
|
||||
publish:
|
||||
name: Publish gpui-experimental prerelease
|
||||
needs: [build-macos, build-linux]
|
||||
if: ${{ !cancelled() && inputs.publish != 'false' && needs.build-macos.result == 'success' && needs.build-linux.result == 'success' }}
|
||||
concurrency:
|
||||
group: gpui-experimental-release
|
||||
cancel-in-progress: false
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
with:
|
||||
sparse-checkout: scripts
|
||||
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
with:
|
||||
node-version: "22"
|
||||
|
||||
- name: Download built experimental artifacts
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
|
||||
with:
|
||||
pattern: gpui-experimental-*
|
||||
path: ${{ runner.temp }}/experimental-assets
|
||||
merge-multiple: true
|
||||
|
||||
- name: Publish gpui-experimental prerelease
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
assets_dir="${RUNNER_TEMP}/experimental-assets"
|
||||
notes_file="${RUNNER_TEMP}/gpui-experimental-notes.md"
|
||||
now_utc="$(date -u +'%d-%m-%Y-%H%M|%d-%m-%Y %H:%M|%Y-%m-%d %H:%M UTC')"
|
||||
IFS='|' read -r tag_timestamp title_timestamp build_date <<< "$now_utc"
|
||||
short_sha="$(printf '%s' "${GITHUB_SHA}" | cut -c1-9)"
|
||||
tag="gpui-experimental-${tag_timestamp}"
|
||||
release_title="Paseo GPUI Experimental ${title_timestamp} UTC"
|
||||
|
||||
rm -f "${assets_dir}/SHA256SUMS-gpui-experimental.txt"
|
||||
if compgen -G "${assets_dir}/SHA256SUMS-gpui-experimental-*.txt" > /dev/null; then
|
||||
cat "${assets_dir}"/SHA256SUMS-gpui-experimental-*.txt > "${assets_dir}/SHA256SUMS-gpui-experimental.txt"
|
||||
rm -f "${assets_dir}"/SHA256SUMS-gpui-experimental-*.txt
|
||||
fi
|
||||
|
||||
expected_assets=()
|
||||
for file in "${assets_dir}"/*; do
|
||||
[[ -f "$file" && "$file" != *.yml ]] || continue
|
||||
expected_assets+=("$(basename "$file")")
|
||||
done
|
||||
if [[ ${#expected_assets[@]} -eq 0 ]]; then
|
||||
echo "::error::No release artifacts found in ${assets_dir}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
{
|
||||
echo "This build is the native desktop app for Paseo. It runs on GPUI instead of Electron."
|
||||
echo ""
|
||||
echo "It is under heavy development and is not ready for daily use. It is not a Paseo beta."
|
||||
echo ""
|
||||
echo "If you want to use Paseo normally, download the [latest release](https://github.com/getpaseo/paseo/releases/latest)."
|
||||
echo ""
|
||||
echo "This app connects to a running Paseo daemon. It does not bundle the daemon."
|
||||
echo ""
|
||||
echo "- Commit: \`${GITHUB_SHA}\` (\`${short_sha}\`)"
|
||||
echo "- Built: \`${build_date}\`"
|
||||
echo ""
|
||||
echo "### SHA-256 Checksums"
|
||||
echo ""
|
||||
echo '```'
|
||||
if [[ -f "${assets_dir}/SHA256SUMS-gpui-experimental.txt" ]]; then
|
||||
cat "${assets_dir}/SHA256SUMS-gpui-experimental.txt"
|
||||
else
|
||||
echo "(no checksums generated)"
|
||||
fi
|
||||
echo '```'
|
||||
} > "${notes_file}"
|
||||
|
||||
repo="${{ github.repository }}"
|
||||
staging_tag="gpui-experimental-stage-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}"
|
||||
staging_id=""
|
||||
created_tag=""
|
||||
cleanup_staging() {
|
||||
local ec=$?
|
||||
set +e
|
||||
if [[ -n "$staging_id" ]]; then
|
||||
gh api "repos/${repo}/releases/${staging_id}" -X DELETE > /dev/null 2>&1 || true
|
||||
fi
|
||||
if [[ -n "$created_tag" ]]; then
|
||||
gh api "repos/${repo}/git/refs/tags/${created_tag}" -X DELETE > /dev/null 2>&1 || true
|
||||
fi
|
||||
return "$ec"
|
||||
}
|
||||
trap cleanup_staging EXIT
|
||||
|
||||
# Stage and verify the full asset set on a draft first so upload failures never
|
||||
# publish a half-empty release.
|
||||
gh release create "$staging_tag" \
|
||||
--repo "$repo" \
|
||||
--title "$release_title" \
|
||||
--notes-file "${notes_file}" \
|
||||
--draft \
|
||||
--prerelease \
|
||||
--latest=false \
|
||||
--target "${GITHUB_SHA}"
|
||||
|
||||
staging_id="$(gh release view "$staging_tag" --repo "$repo" --json databaseId --jq '.databaseId')"
|
||||
node scripts/upload-release-assets.mjs "$staging_tag" "${assets_dir}" "$repo"
|
||||
|
||||
assets_list="$(gh api "repos/${repo}/releases/${staging_id}/assets?per_page=100" --paginate --jq '.[].name')"
|
||||
for name in "${expected_assets[@]}"; do
|
||||
if ! grep -Fxq "$name" <<< "$assets_list"; then
|
||||
echo "::error::Missing release asset: ${name}" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
gh api "repos/${repo}/git/refs" \
|
||||
-X POST \
|
||||
-f ref="refs/tags/${tag}" \
|
||||
-f sha="${GITHUB_SHA}"
|
||||
created_tag="$tag"
|
||||
|
||||
promoted_draft="$(gh api "repos/${repo}/releases/${staging_id}" \
|
||||
-X PATCH \
|
||||
-f tag_name="$tag" \
|
||||
-f target_commitish="${GITHUB_SHA}" \
|
||||
-f name="$release_title" \
|
||||
-F body=@"${notes_file}" \
|
||||
-F draft=false \
|
||||
-F prerelease=true \
|
||||
-f make_latest="false" \
|
||||
--jq '.draft')"
|
||||
|
||||
if [[ "$promoted_draft" != "false" ]]; then
|
||||
echo "::error::Promoted release is still a draft" >&2
|
||||
exit 1
|
||||
fi
|
||||
staging_id=""
|
||||
created_tag=""
|
||||
@@ -1,61 +0,0 @@
|
||||
name: Nix Update Hash
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- "nix/**"
|
||||
- "flake.nix"
|
||||
- "flake.lock"
|
||||
- "package.json"
|
||||
- "package-lock.json"
|
||||
- "packages/highlight/**"
|
||||
- "packages/plugin/**"
|
||||
- "packages/server/**"
|
||||
- "packages/relay/**"
|
||||
- "packages/cli/**"
|
||||
- "scripts/update-nix.sh"
|
||||
- "scripts/fix-lockfile.mjs"
|
||||
- ".github/workflows/nix-update-hash.yml"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
update-hash:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/create-github-app-token@d72941d797fd3113feb6b93fd0dec494b13a2547 # v1
|
||||
id: app-token
|
||||
with:
|
||||
app-id: ${{ secrets.PASEO_BOT_APP_ID }}
|
||||
private-key: ${{ secrets.PASEO_BOT_APP_PRIVATE_KEY }}
|
||||
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
with:
|
||||
ref: ${{ github.ref }}
|
||||
token: ${{ steps.app-token.outputs.token }}
|
||||
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: "npm"
|
||||
|
||||
- uses: cachix/install-nix-action@3dc140bfc76c49fbd4dd958429132e3746bcb086 # v31
|
||||
with:
|
||||
nix_path: nixpkgs=channel:nixos-unstable
|
||||
|
||||
- name: Update lockfile + Nix hash if stale
|
||||
run: ./scripts/update-nix.sh
|
||||
|
||||
- name: Build Nix package
|
||||
run: nix build .#default -o result
|
||||
|
||||
- name: Commit hash/lockfile updates
|
||||
run: |
|
||||
git diff --quiet package-lock.json nix/npm-deps.hash && exit 0
|
||||
git config user.name "paseo-ai[bot]"
|
||||
git config user.email "266920839+paseo-ai[bot]@users.noreply.github.com"
|
||||
git add package-lock.json nix/npm-deps.hash
|
||||
git commit -m "fix: update lockfile signatures and Nix hash [skip ci]"
|
||||
git push
|
||||
@@ -27,8 +27,6 @@ on:
|
||||
- "scripts/trace-daemon.mjs"
|
||||
- "scripts/is-main-module.mjs"
|
||||
- "scripts/build-daemon-web-ui.mjs"
|
||||
- "scripts/update-nix.sh"
|
||||
- "scripts/fix-lockfile.mjs"
|
||||
- ".github/workflows/nix.yml"
|
||||
workflow_dispatch:
|
||||
|
||||
@@ -45,18 +43,10 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: "npm"
|
||||
|
||||
- uses: cachix/install-nix-action@3dc140bfc76c49fbd4dd958429132e3746bcb086 # v31
|
||||
with:
|
||||
nix_path: nixpkgs=channel:nixos-unstable
|
||||
|
||||
- name: Update lockfile + Nix hash if stale
|
||||
run: ./scripts/update-nix.sh
|
||||
|
||||
- name: Build Nix package
|
||||
run: nix build .#default -o result
|
||||
|
||||
|
||||
@@ -99,3 +99,5 @@ app.json
|
||||
|
||||
# Project-local Serena configuration and memories.
|
||||
.serena/
|
||||
|
||||
!packages/app/gpui/app.json
|
||||
|
||||
+3
-5
@@ -184,15 +184,13 @@
|
||||
"server/session/daemon/install-origin.ts": ["existsSync", "readFileSync"],
|
||||
// TODO: npm self-update inspection probes the reported install path; move the probe into bounded async installation inspection.
|
||||
"server/session/daemon/npm-global-cli.ts": ["lstatSync"],
|
||||
// Speech child process: model-file validation runs in the worker-backed local speech provider.
|
||||
"server/speech/providers/local/sherpa/sherpa-offline-recognizer.ts": ["existsSync"],
|
||||
// Speech child process: native addon discovery and patchelf run outside the daemon.
|
||||
"server/speech/providers/local/sherpa/sherpa-onnx-node-loader.ts": [
|
||||
"existsSync",
|
||||
"spawnSync"
|
||||
],
|
||||
// Speech child process: model-file validation runs in the worker-backed local speech provider.
|
||||
"server/speech/providers/local/sherpa/sherpa-tts.ts": ["existsSync"],
|
||||
// Speech child process: modelsDir directory creation and model-file validation run outside the daemon.
|
||||
"server/speech/providers/local/worker-paths.ts": ["existsSync", "mkdirSync"],
|
||||
// TODO: static request selection and index injection need bounded async serving with response/error ownership; keep this as a separate request-path conversion.
|
||||
"server/web-ui.ts": ["readFileSync", "statSync"],
|
||||
// Startup registry hydration: check persisted workspace directories before the runtime reconciliation service starts.
|
||||
@@ -634,7 +632,7 @@
|
||||
"packages/app/src/components/combined-model-selector.tsx",
|
||||
"packages/app/src/components/compact-explorer-sidebar.tsx",
|
||||
"packages/app/src/components/context-window-meter.tsx",
|
||||
"packages/app/src/components/desktop/window-controls.tsx",
|
||||
"packages/app/src/components/desktop/caption-button.tsx",
|
||||
"packages/app/src/components/dictation-controls.tsx",
|
||||
"packages/app/src/components/download-toast.tsx",
|
||||
"packages/app/src/components/file-explorer-pane.tsx",
|
||||
|
||||
@@ -21,60 +21,60 @@ This is an npm workspace monorepo:
|
||||
|
||||
At the start of non-trivial work, list `docs/` and skim anything relevant to the task.
|
||||
|
||||
| Doc | What's in it |
|
||||
| -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| [docs/product.md](docs/product.md) | What Paseo is, who it's for, where it's going |
|
||||
| [docs/architecture.md](docs/architecture.md) | System design, package layering, WebSocket protocol, agent lifecycle, data flow |
|
||||
| [docs/agent-lifecycle.md](docs/agent-lifecycle.md) | Agent states, parent/child relationships, archive semantics, tabs vs archive, subagents track |
|
||||
| [docs/data-model.md](docs/data-model.md) | File-based JSON persistence, Zod schemas, atomic writes, no migrations |
|
||||
| [docs/glossary.md](docs/glossary.md) | Authoritative terminology — UI label wins, no synonyms |
|
||||
| [docs/coding-standards.md](docs/coding-standards.md) | Type hygiene, error handling, state design, React patterns, file organization |
|
||||
| [docs/design.md](docs/design.md) | Design system — tokens, buttons, hierarchy, density, alignment rails, states, what's forbidden |
|
||||
| [docs/forms.md](docs/forms.md) | Form architecture — non-React form model, form kit, load-state gating; the schedule form is the golden example |
|
||||
| [docs/hover.md](docs/hover.md) | Hover — the canonical pattern (plain View + onPointerEnter/Leave, separate inner Pressable) and the three ways agents break it |
|
||||
| [docs/unistyles.md](docs/unistyles.md) | Unistyles gotchas — `useUnistyles()` is forbidden, alternatives in order |
|
||||
| [docs/floating-panels.md](docs/floating-panels.md) | Anchored popovers — Portal/Modal escape for Android, lifecycle gates, keyboard-shared-value, status-bar offset, the flash |
|
||||
| [docs/keyboard-shortcuts.md](docs/keyboard-shortcuts.md) | The binding table, per-platform key sources, badges vs routing, iOS `UIKeyCommand` limits |
|
||||
| [docs/menus.md](docs/menus.md) | The menu engine — popover vs sheet, submenu pages, hover intent, when a decision earns a submenu |
|
||||
| [docs/drag-reorder.md](docs/drag-reorder.md) | Drag to reorder — `DraggableList` and its handle, the scroll view that must host the drag, grip placement, testing on a phone |
|
||||
| [docs/expo-router.md](docs/expo-router.md) | Expo Router route ownership, startup restore, and native blank-screen gotchas |
|
||||
| [docs/notifications.md](docs/notifications.md) | Notification tap ownership, native replay and acknowledgement, startup handoff, and payload QA |
|
||||
| [docs/file-icons.md](docs/file-icons.md) | Material icon theme integration for the file explorer |
|
||||
| [docs/providers.md](docs/providers.md) | Adding a new agent provider end-to-end |
|
||||
| [docs/forge-providers.md](docs/forge-providers.md) | Adding a git forge: registry/manifest, drop-in checklist, self-host/GHES, the two facts tiers |
|
||||
| [docs/custom-providers.md](docs/custom-providers.md) | Custom provider config: Z.AI, Alibaba/Qwen, ACP agents, profiles, custom binaries |
|
||||
| [docs/plugins.md](docs/plugins.md) | Local plugin manifest, directory source config, RPCs, native surfaces, and attachment sources |
|
||||
| [docs/website-i18n.md](docs/website-i18n.md) | Website languages: locale URLs, translated Markdown pairs, `{#id}` anchors, Chinese style |
|
||||
| [docs/relay-endpoint-security.md](docs/relay-endpoint-security.md) | Relay E2EE modes: Noise NK mapping, record framing, negotiation, the `requireProtectedSecurity` flag, close codes |
|
||||
| [docs/development.md](docs/development.md) | Dev server, build sync gotchas, CLI reference, agent state, Playwright MCP |
|
||||
| [docs/rpc-namespacing.md](docs/rpc-namespacing.md) | WebSocket RPC naming convention — dotted namespaces and `.request`/`.response` pairs |
|
||||
| [docs/protocol-compatibility.md](docs/protocol-compatibility.md) | Why app/daemon versions drift, protocol vs feature contract, capability gating, COMPAT tagging |
|
||||
| [docs/protocol-validation.md](docs/protocol-validation.md) | zod-aot generated inbound WebSocket validation, patched compiler regressions, schema-purity rules |
|
||||
| [docs/connected-hosts.md](docs/connected-hosts.md) | Daemon-owned host registrations, routed SDK scopes, identity and authority boundaries |
|
||||
| [docs/permissions.md](docs/permissions.md) | Semantic daemon permissions, principals, credentials, pairing invitations, and Hub authority |
|
||||
| [docs/terminal-performance.md](docs/terminal-performance.md) | Terminal latency pipeline, coalescing/backpressure invariants, benchmark + perf spec usage |
|
||||
| [docs/terminal-rendering.md](docs/terminal-rendering.md) | Native terminal view: xterm owns the grid, cluster placement, emoji widths, mixed-direction limits, render regression |
|
||||
| [docs/timeline-sync.md](docs/timeline-sync.md) | Owned agent history, rewind retirements, live stream vs authoritative fetch, paged catch-up, client replica |
|
||||
| [docs/agent-stream-performance.md](docs/agent-stream-performance.md) | Assistant text pipeline — coalescing window, paced reveal, why arrival lumps are smoothed at render |
|
||||
| [docs/agent-stream-disclosure.md](docs/agent-stream-disclosure.md) | Expand/collapse in the chat timeline — hold contract, native anchor sequence, frame spacing, render-window cost |
|
||||
| [docs/running-indicators.md](docs/running-indicators.md) | Loader, status ring, tool-call shimmer — motion policy, compositor loops on web, native-driver clock, why not CSS keyframes |
|
||||
| [docs/markdown-renderer.md](docs/markdown-renderer.md) | Shared Markdown engine, the vendored library fork, native selection, links, images and library constraints |
|
||||
| [docs/native-text-selection.md](docs/native-text-selection.md) | Native diagram grouping, selection boundaries and leading inline image limitations |
|
||||
| [docs/file-observation.md](docs/file-observation.md) | Recursive watcher ownership, Linux constraints, teardown invariants, and Parcel comparison |
|
||||
| [docs/testing.md](docs/testing.md) | TDD workflow, determinism, real dependencies over mocks, test organization |
|
||||
| [docs/qa.md](docs/qa.md) | QA evidence bar for pull requests — platform matrix, version drift, performance, UI proof |
|
||||
| [docs/mobile-testing.md](docs/mobile-testing.md) | Maestro and mobile test workflows |
|
||||
| [docs/mobile-panels.md](docs/mobile-panels.md) | Compact left/center/right panel ownership, worklet motion, gesture revisions, and Fabric constraints |
|
||||
| [docs/explorer-sidebar.md](docs/explorer-sidebar.md) | Explorer sidebar, side-pane, and compact workspace sheet host contracts, lifecycle, placement, routing preferences |
|
||||
| [docs/ad-hoc-daemon-testing.md](docs/ad-hoc-daemon-testing.md) | Isolated in-process daemon test harness |
|
||||
| [docs/browser-capture-harness.md](docs/browser-capture-harness.md) | Real-Electron browser screenshot harness and compositor-surface gotcha |
|
||||
| [docs/android.md](docs/android.md) | App variants, local/cloud builds, EAS workflows, version codes, F-Droid source builds and store metadata |
|
||||
| [docs/docker.md](docs/docker.md) | Running the daemon and bundled web UI in Docker, volumes, agent images, security |
|
||||
| [docs/release.md](docs/release.md) | Release playbook, draft releases, completion checklist |
|
||||
| [docs/terminal-worker.md](docs/terminal-worker.md) | Terminal worker process model, socket/record/secret, protocol-bump rule and draining, the worker's file copy, Windows desktop |
|
||||
| [docs/terminal-activity.md](docs/terminal-activity.md) | Terminal activity indicators — source-agnostic tracker, agent hook reporting, adding a new hook provider |
|
||||
| [SECURITY.md](SECURITY.md) | Relay threat model, E2E encryption, DNS rebinding, agent auth |
|
||||
| [public-docs/hub/security.md](public-docs/hub/security.md) | Public Hub guide — trust boundaries, untrusted triggers, provider controls, and output authority |
|
||||
| Doc | What's in it |
|
||||
| -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| [docs/product.md](docs/product.md) | What Paseo is, who it's for, where it's going |
|
||||
| [docs/architecture.md](docs/architecture.md) | System design, package layering, WebSocket protocol, agent lifecycle, data flow |
|
||||
| [docs/agent-lifecycle.md](docs/agent-lifecycle.md) | Agent states, parent/child relationships, archive semantics, tabs vs archive, subagents track |
|
||||
| [docs/data-model.md](docs/data-model.md) | File-based JSON persistence, Zod schemas, atomic writes, no migrations |
|
||||
| [docs/glossary.md](docs/glossary.md) | Authoritative terminology — UI label wins, no synonyms |
|
||||
| [docs/coding-standards.md](docs/coding-standards.md) | Type hygiene, error handling, state design, React patterns, file organization |
|
||||
| [docs/design.md](docs/design.md) | Design system — tokens, buttons, hierarchy, density, alignment rails, states, what's forbidden |
|
||||
| [docs/forms.md](docs/forms.md) | Form architecture — non-React form model, form kit, load-state gating; the schedule form is the golden example |
|
||||
| [docs/hover.md](docs/hover.md) | Hover — the canonical pattern (plain View + onPointerEnter/Leave, separate inner Pressable) and the three ways agents break it |
|
||||
| [docs/unistyles.md](docs/unistyles.md) | Unistyles gotchas — `useUnistyles()` is forbidden, alternatives in order |
|
||||
| [docs/floating-panels.md](docs/floating-panels.md) | Anchored popovers — Portal/Modal escape for Android, lifecycle gates, keyboard-shared-value, status-bar offset, the flash |
|
||||
| [docs/keyboard-shortcuts.md](docs/keyboard-shortcuts.md) | Action and keybinding registries, action scopes, overlay covers, plugin actions, key sources, badges, iOS `UIKeyCommand` limits |
|
||||
| [docs/menus.md](docs/menus.md) | The menu engine — popover vs sheet, submenu pages, hover intent, when a decision earns a submenu |
|
||||
| [docs/drag-reorder.md](docs/drag-reorder.md) | Drag to reorder — `DraggableList` and its handle, the scroll view that must host the drag, grip placement, testing on a phone |
|
||||
| [docs/expo-router.md](docs/expo-router.md) | Expo Router route ownership, startup restore, and native blank-screen gotchas |
|
||||
| [docs/notifications.md](docs/notifications.md) | Notification tap ownership, native replay and acknowledgement, startup handoff, and payload QA |
|
||||
| [docs/file-icons.md](docs/file-icons.md) | Material icon theme integration for the file explorer |
|
||||
| [docs/providers.md](docs/providers.md) | Adding a new agent provider end-to-end |
|
||||
| [docs/forge-providers.md](docs/forge-providers.md) | Adding a git forge: registry/manifest, drop-in checklist, self-host/GHES, the two facts tiers |
|
||||
| [docs/custom-providers.md](docs/custom-providers.md) | Custom provider config: Z.AI, Alibaba/Qwen, ACP agents, profiles, custom binaries |
|
||||
| [docs/plugins.md](docs/plugins.md) | Local plugin manifest, directory source config, RPCs, native surfaces, and attachment sources |
|
||||
| [docs/website-i18n.md](docs/website-i18n.md) | Website languages: locale URLs, translated Markdown pairs, `{#id}` anchors, Chinese style |
|
||||
| [docs/relay-endpoint-security.md](docs/relay-endpoint-security.md) | Relay E2EE modes: Noise NK mapping, record framing, negotiation, the `requireProtectedSecurity` flag, close codes |
|
||||
| [docs/development.md](docs/development.md) | Dev server, build sync gotchas, CLI reference, agent state, Playwright MCP |
|
||||
| [docs/rpc-namespacing.md](docs/rpc-namespacing.md) | WebSocket RPC naming convention — dotted namespaces and `.request`/`.response` pairs |
|
||||
| [docs/protocol-compatibility.md](docs/protocol-compatibility.md) | Why app/daemon versions drift, protocol vs feature contract, capability gating, COMPAT tagging |
|
||||
| [docs/protocol-validation.md](docs/protocol-validation.md) | zod-aot generated inbound WebSocket validation, patched compiler regressions, schema-purity rules |
|
||||
| [docs/connected-hosts.md](docs/connected-hosts.md) | Daemon-owned host registrations, routed SDK scopes, identity and authority boundaries |
|
||||
| [docs/permissions.md](docs/permissions.md) | Semantic daemon permissions, principals, credentials, pairing invitations, and Hub authority |
|
||||
| [docs/terminal-performance.md](docs/terminal-performance.md) | Terminal latency pipeline, coalescing/backpressure invariants, benchmark + perf spec usage |
|
||||
| [docs/terminal-rendering.md](docs/terminal-rendering.md) | Native terminal view: xterm owns the grid, cluster placement, emoji widths, mixed-direction limits, render regression |
|
||||
| [docs/timeline-sync.md](docs/timeline-sync.md) | Owned agent history, rewind retirements, live stream vs authoritative fetch, paged catch-up, client replica |
|
||||
| [docs/agent-stream-performance.md](docs/agent-stream-performance.md) | Assistant text pipeline — coalescing window, paced reveal, why arrival lumps are smoothed at render |
|
||||
| [docs/agent-stream-disclosure.md](docs/agent-stream-disclosure.md) | Expand/collapse in the chat timeline — hold contract, native anchor sequence, frame spacing, render-window cost |
|
||||
| [docs/running-indicators.md](docs/running-indicators.md) | Loader, status ring, tool-call shimmer — motion policy, compositor loops on web, native-driver clock, why not CSS keyframes |
|
||||
| [docs/markdown-renderer.md](docs/markdown-renderer.md) | Shared Markdown engine, the vendored library fork, native selection, links, images and library constraints |
|
||||
| [docs/native-text-selection.md](docs/native-text-selection.md) | Native diagram grouping, selection boundaries and leading inline image limitations |
|
||||
| [docs/file-observation.md](docs/file-observation.md) | Recursive watcher ownership, Linux constraints, teardown invariants, and Parcel comparison |
|
||||
| [docs/testing.md](docs/testing.md) | TDD workflow, determinism, real dependencies over mocks, test organization |
|
||||
| [docs/qa.md](docs/qa.md) | QA evidence bar for pull requests — platform matrix, version drift, performance, UI proof |
|
||||
| [docs/mobile-testing.md](docs/mobile-testing.md) | Maestro and mobile test workflows |
|
||||
| [docs/mobile-panels.md](docs/mobile-panels.md) | Compact left/center/right panel ownership, worklet motion, gesture revisions, and Fabric constraints |
|
||||
| [docs/explorer-sidebar.md](docs/explorer-sidebar.md) | Explorer sidebar, side-pane, and compact workspace sheet host contracts, lifecycle, placement, routing preferences |
|
||||
| [docs/ad-hoc-daemon-testing.md](docs/ad-hoc-daemon-testing.md) | Isolated in-process daemon test harness |
|
||||
| [docs/browser-capture-harness.md](docs/browser-capture-harness.md) | Real-Electron browser screenshot harness and compositor-surface gotcha |
|
||||
| [docs/android.md](docs/android.md) | App variants, local/cloud builds, EAS workflows, version codes, F-Droid source builds and store metadata |
|
||||
| [docs/docker.md](docs/docker.md) | Running the daemon and bundled web UI in Docker, volumes, agent images, security |
|
||||
| [docs/release.md](docs/release.md) | Release playbook, draft releases, completion checklist |
|
||||
| [docs/terminal-worker.md](docs/terminal-worker.md) | Terminal worker process model, socket/record/secret, protocol-bump rule and draining, the worker's file copy, Windows desktop |
|
||||
| [docs/terminal-activity.md](docs/terminal-activity.md) | Terminal activity indicators — source-agnostic tracker, agent hook reporting, adding a new hook provider |
|
||||
| [SECURITY.md](SECURITY.md) | Relay threat model, E2E encryption, DNS rebinding, agent auth |
|
||||
| [public-docs/hub/security.md](public-docs/hub/security.md) | Public Hub guide — trust boundaries, untrusted triggers, provider controls, and output authority |
|
||||
|
||||
### Writing docs
|
||||
|
||||
|
||||
@@ -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 macOS and 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:
|
||||
|
||||
+2
-2
@@ -120,9 +120,9 @@ const revealsWithoutHover = useRevealsWithoutHover();
|
||||
const showControls = isHovered || revealsWithoutHover;
|
||||
```
|
||||
|
||||
`useRevealsWithoutHover()` (`@/hooks/hover-reveal`) asks the pointer, not the platform: it is true when no mouse-like pointer drives the UI or the layout is compact. Don't use `isNative` for this. A touch-first browser such as iPad Safari is `isWeb` yet cannot hover, so `isNative` would leave its hover controls unreachable.
|
||||
`useRevealsWithoutHover()` (`@/hooks/hover-reveal`) asks the pointer, not the platform: it is true when no mouse-like pointer drives the UI or the layout is compact. Don't use `isNative` for this. A touch-first browser such as iPad Safari is `isWeb` yet cannot hover, and the GPUI desktop client is native yet driven by a mouse, so `isNative` gets both wrong.
|
||||
|
||||
`onPointerEnter` / `onPointerLeave` are DOM events. They fire on the web and do not fire on iOS or Android. You do not need to gate them: on a touch screen, hover is unreachable and visibility comes from `useRevealsWithoutHover()`. This is why the workspace row's pointer events are not wrapped in `if (isWeb)`.
|
||||
`onPointerEnter` / `onPointerLeave` fire on the web and in the GPUI desktop client. They do not fire on iOS or Android. You do not need to gate them: on a touch screen, hover is unreachable and visibility comes from `useRevealsWithoutHover()`. This is why the workspace row's pointer events are not wrapped in `if (isWeb)`.
|
||||
|
||||
## What about `Pressable.onHoverIn` / `onHoverOut`?
|
||||
|
||||
|
||||
@@ -1,6 +1,63 @@
|
||||
# Keyboard shortcuts
|
||||
|
||||
Define shortcuts in [the shared binding table](../packages/app/src/keyboard/keyboard-shortcuts.ts). Platforms contribute key sources, not separate action maps, so matching and user rebinds stay consistent across runtimes. Add a shortcut through a binding; add platform support through a key source.
|
||||
A shortcut is two registrations. An action in the action registry (`@/actions`) is something the app can run. A binding in the keybinding registry (`@/keyboard`) connects keys to an action. `@/keyboard` imports `@/actions`; `@/actions` knows nothing about keys.
|
||||
|
||||
Paseo's own actions and default bindings are in [`core-actions/internal/actions.ts`](../packages/app/src/core-actions/internal/actions.ts) and [`bindings.ts`](../packages/app/src/core-actions/internal/bindings.ts). `CoreActionsProvider` registers them at app start, so Settings, badges and Command Center see every core shortcut before any surface mounts. Add a shortcut by adding a binding; add platform support through a key source.
|
||||
|
||||
## Actions and handlers
|
||||
|
||||
An action id such as `paseo/workspace.tab.next` is the only key for dispatch, badges (`useShortcutKeys`, `Shortcut`), Command Center rows and Settings rows.
|
||||
|
||||
A mounted surface supplies behavior with `useActionHandler(actionId, handler, { enabled, scope })`. Dispatch tries handlers in active action scopes innermost first, then unscoped handlers while no overlay covers the app, with the earliest registration first among equals. When every handler declines, the action's own `run` handles it. The app shell supplies `run` for the core actions no screen owns (`APP_SHELL_ACTION_IDS` in [`app-shell-runs.ts`](../packages/app/src/core-actions/internal/app-shell-runs.ts)). Every other core action has no `run`, so it can run only while a surface handles it. Do not give such an action a declining `run`: an action with a `run` counts as available, and its chords then reserve a first step that another shortcut needs.
|
||||
|
||||
A handler declines only by returning `{ handled: false }` synchronously. Any other return, including a promise, counts as handled. Express which handler wins with `enabled` and scopes, not with mount order.
|
||||
|
||||
Finite variants are separate actions: `workspace.tab.next` and `workspace.tab.previous`, one action per `message-input.*` operation. Only a binding declared with `Digit` supplies data, as `index`. It keeps supplying the pressed digit when an override narrows it to one digit, because Settings saved captured digits literally before it captured number groups.
|
||||
|
||||
## Action scopes
|
||||
|
||||
A surface that should shadow a shortcut while it is active creates a scope with `useActionScope(name, { active })`, and passes it to its handlers as `scope` or wraps its children in `<ActionScope activation>`. The innermost active scope wins. There are no priorities.
|
||||
|
||||
Example: the composer activates `paseo/composer` while it takes input, and the New Workspace screen activates `paseo/new-workspace` while it is focused. Shift+Tab on the New Workspace screen reaches its composer, and never the mode control of a backgrounded agent composer that is still mounted.
|
||||
|
||||
Scopes order by activation, so they cannot tell which of two active surfaces the user is in. Say that with `enabled`:
|
||||
|
||||
- Several composers can be active at once, such as the main pane's and an Explorer dock agent tab's. Composer handlers register through `useComposerKeyboardActions` ([`composer/keyboard-scope.tsx`](../packages/app/src/composer/keyboard-scope.tsx)), which enables only the composer whose input had focus last. A blur, such as a click on the timeline, keeps that composer; deactivating or unmounting it releases the keys. Until an active composer's input has had focus, the innermost composer wins.
|
||||
- Desktop Settings covers the workspace, which stays mounted beneath it. Composers go inactive while `useSettingsCoversWorkspace()` holds, so Escape reaches Settings' handler and closes Settings. Compact Settings covers nothing, and Escape there still interrupts the agent.
|
||||
|
||||
An overlay that holds the keyboard, such as a dialog, a menu or the Command Center, covers the app while it is open. `useOverlayRegistration` makes the cover when the overlay takes focus (`manageFocus`, on by default) and returns it as `actionScope`. Pass the overlay's scope `name`, such as `paseo/dialog`, and wrap its content in `<ActionScope activation={actionScope}>`. While the overlay is the latest cover, it hides every activation not inside it, including ones made after it opened, and every handler mounted in no scope. An action's `run` stays available. A shortcut that a screen beneath the dialog handles does nothing while the dialog is open, and works again when it closes.
|
||||
|
||||
A registration that only claims keys, such as the hover card or select mode's Escape, passes `manageFocus: false` and covers nothing. `<ActionCover name>` covers without a key registration; only the mobile menu sheet uses it. An overlay opened with a shortcut closes with the same shortcut only through a handler inside its cover, such as `KeyboardToggleClose` in the model picker, because the cover hides the trigger's handler.
|
||||
|
||||
A Command Center row runs its action for the screen beneath the Command Center. The row calls `canDispatch` and `dispatch` with `{ beneath: "paseo/command-center" }`, which answer as if the latest Command Center cover were closed. The list is built for each opening, so it shows only rows that a handler on that screen or the action's `run` can take.
|
||||
|
||||
A handler is bound to one activation, not to a scope name. Two panes that show the same surface activate the same name separately, and a handler in one pane never runs for the other.
|
||||
|
||||
An action scope is different from the focus scope in a binding's `when` clause. Action scopes come from mounted surfaces. The focus scope comes from the focused input; see [Focus scopes](#focus-scopes).
|
||||
|
||||
## Bindings
|
||||
|
||||
A binding has an id, an action id, a combo and a `when` clause. User overrides are keyed by binding id, so never rename a shipped id, even when its combo changes (`agent-new-cmd-shift-o-mac` is bound to Cmd+O).
|
||||
|
||||
Among bindings that match the same key in the same context, a user-set binding wins over a default, then the earliest registered wins. If its action declines, the registry tries the next matching binding. A chord's first step is reserved only while the chord's action can run. On every step, a key continues a chord only when the chord ranks ahead of every runnable binding that the key completes. A plugin's default `Mod+K J` therefore leaves Ctrl+K to the Command Center until the user sets that chord, and a saved `Ctrl+G J K` continues past a default `Ctrl+G J`.
|
||||
|
||||
Settings → Shortcuts asks the registry about every captured combo with `checkCapture` (`canFire`, `conflicts`). A combo that can never fire for that binding is refused with a reason and cannot be saved: an unmodified or Shift-only printable key on a binding whose `when` only holds while typing, such as mode cycle on `Shift+M`. A combo that shares a key press with another binding is saved and shown on both rows as "Also used by …", and the user-set binding runs. The shipped defaults share no key press, so a fresh install shows no warning.
|
||||
|
||||
Badges show the first assigned binding for the platform (`displayKeysFor`). Settings → Shortcuts builds its rows from the registry with `buildShortcutSections`, so it lists every core binding with only Settings mounted.
|
||||
|
||||
A surface that reads keys itself while it holds the keyboard, such as the workspace switcher HUD, matches them with `createChordMatcher` against the bindings it picks. A binding whose action finishes when its modifier is released, such as Ctrl+Tab in the switcher, sets `holdRelease`; key sources outside the app, such as the Electron browser pane, forward that key-up.
|
||||
|
||||
Tests that drive real keys through the real table use `createRecordingCoreRegistries` from `@/core-actions/testing`.
|
||||
|
||||
## Plugin actions
|
||||
|
||||
Plugins register actions and bindings through the same two registries; the author contract is in [Actions and keyboard shortcuts](../public-docs/plugins/reference.md#actions). [`plugins/shortcuts/`](../packages/app/src/plugins/shortcuts/index.ts) connects each installation's contributions.
|
||||
|
||||
- Ids are namespaced: the plugin's `open` is the action `plugin-<pluginId>/open`, its binding ids are `plugin-<pluginId>/<id>`, and its scopes are `plugin-<pluginId>/<name>`. Overrides key off these ids, so the user's rebinding survives reinstalls and reloads.
|
||||
- A plugin installed on several hosts adds the same action once per host. The registry keeps one action whose owners are the host ids; core actions have owner `null`. `pluginActionOwnerOrder`, passed to `CoreActionsProvider`, picks the host that runs it: a global action runs on the host of the screen the user is on, else the host the user last picked for the plugin's screens, else the first online host. A workspace or agent action runs only on the active host. Offline hosts never run.
|
||||
- Every plugin screen, panel and popover activates `paseo/plugin-surface`. A plugin handler without `scope` belongs to that activation, so two panes of the same panel never run each other's handlers.
|
||||
- Core actions and bindings register before any plugin, so a core default binding is tried before a plugin binding on the same key.
|
||||
- Settings → Shortcuts and the shortcuts dialog add one section per plugin, titled with its name, with one row per action across all hosts.
|
||||
|
||||
## Badges and routing
|
||||
|
||||
@@ -26,8 +83,14 @@ after the focused text control has already handled the press, so the pipeline's
|
||||
must be claimed up front. `UIKeyCommand` takes only those keys: composer Return, the
|
||||
top overlay's Enter and arrows, and the Shift or Option shortcuts whose binding is
|
||||
active in the current focus scope, such as Shift+Tab in the composer.
|
||||
`sources/native.ts` computes the claims from the published bindings and recomputes
|
||||
them when the focus scope changes. Cmd and Ctrl combos are never claimed, because
|
||||
`sources/native.ts` computes the claims from the published bindings, the focus scope,
|
||||
Command Center and the visible action scopes, and recomputes them when any of these
|
||||
change. A first key is checked without the action scope stack, so a binding whose
|
||||
`when` names an action scope never claims its first key. While a chord waits, only the
|
||||
next key of each pending candidate is claimed, and a scoped candidate keeps its claim
|
||||
while its scope stays visible. A covering overlay drops the claim, so the key reaches
|
||||
the overlay's text field. Gate a key
|
||||
that a text control would type with `focusScope`, as mode cycle does. Cmd and Ctrl combos are never claimed, because
|
||||
text controls do not type them. Android takes no claims: a focused `EditText`
|
||||
types nothing for these combos. Keep the stream as the sole shortcut emitter: a command-owned
|
||||
press is still observed by the window.
|
||||
@@ -56,6 +119,15 @@ Verify the iOS absence case on a physical iPhone.
|
||||
Xcode 27.2 has Device Hub in place of Simulator. AppleScript keystrokes reach the
|
||||
device only while its view has Mac focus. Give it focus with a real mouse click
|
||||
(a `CGEvent`); keystrokes sent elsewhere drive Device Hub's own controls.
|
||||
Send both steps of a chord from one AppleScript `tell` block. A chord expires
|
||||
after 1.5 s, and separate `osascript` calls with settle delays exceed it, so the
|
||||
second key types into the focused field.
|
||||
|
||||
On Android debug builds, the Expo dev menu reads unmodified R, P and I on key-up
|
||||
outside text fields: R reloads, P opens the performance monitor (and the overlay
|
||||
permission page), I toggles the inspector. Before hardware-keyboard QA, set
|
||||
`keyCommandsEnabled` to `false` in the app's `expo.modules.devmenu.sharedpreferences`
|
||||
SharedPreferences.
|
||||
|
||||
Never register Backspace: it would take deletion away from text fields. Changes
|
||||
to the native module require a native rebuild; an over-the-air JavaScript update
|
||||
@@ -110,6 +182,6 @@ leaving active IME composition spans untouched for candidate navigation.
|
||||
## Keys shared with text editing
|
||||
|
||||
A binding on a key the platform already uses for editing, such as Cmd/Ctrl+Z for
|
||||
workspace archive undo, declares `editable: false` and registers its handler with
|
||||
`isActive` true only while it has work. An inactive handler leaves the key
|
||||
workspace archive undo, declares `when: { editable: false }`, and its handler is
|
||||
`enabled` only while it has work. A disabled or declining handler leaves the key
|
||||
unhandled, so the pipeline skips `preventDefault` and the platform's own undo runs.
|
||||
|
||||
+9
-5
@@ -1,7 +1,7 @@
|
||||
# Plugins
|
||||
|
||||
Local plugins contribute daemon RPCs, native app surfaces, workspace panels, Command Center items,
|
||||
client slash commands, timeline items, notifications, header buttons, composer pills, app themes, composer attachment sources, and settings screens.
|
||||
keyboard shortcuts, client slash commands, timeline items, notifications, header buttons, composer pills, app themes, composer attachment sources, and settings screens.
|
||||
Paseo executes `index.server.ts` in a subprocess and `index.client.tsx` in every connected app.
|
||||
|
||||
> **Trust every plugin you add.** `paseo plugin add` and `paseo plugin install` mean “I trust this codebase.” Plugins are unsandboxed: server code and preparation commands run with the daemon user's access on the daemon host, and client contributions run inside Paseo. The repository's dependencies and future updates are part of that trust decision. With `--host`, preparation runs on that remote daemon host.
|
||||
@@ -431,7 +431,7 @@ When the same plugin contribution exists on multiple hosts, Paseo shows it once
|
||||
adds a host picker to the screen header. The selected host supplies the bundle, RPC transport, and
|
||||
query cache. Explicit SDK targets follow the [host API contract](../public-docs/plugins/reference.md#discover-hosts-and-target-another-host).
|
||||
|
||||
Workspace panels, Command Center items, and client slash commands are client contributions. The
|
||||
Workspace panels, Command Center items, actions, keybindings, and client slash commands are client contributions. The
|
||||
daemon transports their compiled bundle without interpreting placement or callbacks. Panel props
|
||||
carry `workspaceId`, validated read-only `params` (with host-enforced `agentId` on agent panels),
|
||||
`revision`, and `tab`; optional `identity(params)` sets the coalescing key on the persisted
|
||||
@@ -464,6 +464,10 @@ See the public [navigation fields](../public-docs/plugins/reference.md#screens-a
|
||||
and [external links and workspace browsers](../public-docs/plugins/reference.md#external-links-and-workspace-browsers)
|
||||
for the author-facing contract.
|
||||
|
||||
Plugin actions and keybindings join the app's action and keybinding registries. Namespacing, which
|
||||
host runs an action, and the Settings sections are in
|
||||
[Plugin actions](keyboard-shortcuts.md#plugin-actions).
|
||||
|
||||
### Plugin icons
|
||||
|
||||
The [public reference](../public-docs/plugins/reference.md#icons) owns the author API: a contribution
|
||||
@@ -915,9 +919,9 @@ implementations and `toPluginComposer`; never branch on `context` in the host.
|
||||
`useComposers` and `composers()` reach an agent's model by reference (`plugins/composer-items/source.ts`):
|
||||
`PluginInstallationProvider` provides the plugin's source to every surface, and
|
||||
`createPluginCapabilities` puts `composers` on every command context. `{ focused: true }` is the
|
||||
agent Command Center registration hands to agent items, published through `plugins/focused-agent.ts`
|
||||
(null outside a workspace route). The source reads that module, not the navigation or layout
|
||||
stores, so the plugin runtime does not import them. The remembered workspace selection is
|
||||
agent Command Center registration hands to agent items, published with the active host and
|
||||
workspace through `plugins/location.ts` (null when no host is active). The source and plugin actions
|
||||
read that module, not the navigation or layout stores, so the plugin runtime does not import them. The remembered workspace selection is
|
||||
navigation restore state and is not the focused agent. The query-cache subscriptions react to
|
||||
`updated` events only: a `useQuery` in another component's render announces `added`, and a
|
||||
subscriber that updates then triggers React's "update a component while rendering a different one"
|
||||
|
||||
+6
-2
@@ -442,6 +442,7 @@ const MY_PROVIDER_MODES: AgentProviderModeDefinition[] = [
|
||||
description: "Standard agent mode",
|
||||
icon: "ShieldCheck",
|
||||
colorTier: "safe",
|
||||
permissionTier: "safe",
|
||||
},
|
||||
{
|
||||
id: "autonomous",
|
||||
@@ -449,11 +450,14 @@ const MY_PROVIDER_MODES: AgentProviderModeDefinition[] = [
|
||||
description: "Runs without prompting",
|
||||
icon: "ShieldOff",
|
||||
colorTier: "dangerous",
|
||||
permissionTier: "dangerous",
|
||||
isUnattended: true,
|
||||
},
|
||||
];
|
||||
```
|
||||
|
||||
Available `colorTier` values: `"safe"`, `"moderate"`, `"dangerous"`, `"planning"`.
|
||||
Available `permissionTier` values (lowest to highest security rank for MCP mode-ceiling checks): `"planning"`, `"safe"`, `"moderate"`, `"dangerous"`.
|
||||
Available `colorTier` values (display styling, independent of `permissionTier`): `"safe"`, `"moderate"`, `"dangerous"`, `"planning"`, or a `#rrggbb` hex color.
|
||||
Available `icon` values: `"ShieldCheck"`, `"ShieldAlert"`, `"ShieldOff"`.
|
||||
|
||||
Then add to the `AGENT_PROVIDER_DEFINITIONS` array:
|
||||
@@ -711,7 +715,7 @@ Tests use `isProviderAvailable(provider)` to skip when the binary or credentials
|
||||
|
||||
**Auth patterns vary.** Some providers need API keys in env vars (`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`), some use OAuth tokens (`CLAUDE_CODE_OAUTH_TOKEN`), some use auth files (`~/.codex/auth.json`), and some handle auth entirely in their CLI binary (Copilot). Your `isAvailable()` method should check whatever is needed.
|
||||
|
||||
**The manifest mode list and the agent class mode list are separate.** The manifest in `provider-manifest.ts` includes UI metadata (`icon`, `colorTier`). The agent class defines modes without UI metadata (just `id`, `label`, `description`). Keep them in sync.
|
||||
**The manifest mode list and the agent class mode list are separate.** The manifest in `provider-manifest.ts` includes UI and policy metadata (`icon`, `colorTier`, `permissionTier`, `isUnattended`). The agent class defines modes without that static metadata (just `id`, `label`, `description`). Keep them in sync.
|
||||
|
||||
**`defaultCommand` is a tuple.** The first element is the binary name, the rest are default arguments. The base class uses this to find the executable and spawn the process.
|
||||
|
||||
|
||||
+1
-1
@@ -18,7 +18,7 @@ Preparation is reversible and runs on the release branch before the user authori
|
||||
6. Run `npm run release:prep:<mode>` to create the `chore(release): cut <version>` commit without a tag.
|
||||
7. Push `release/vX.Y.Z` or `release/vX.Y.Z-beta.N`.
|
||||
8. Right after the push, open the unmerged [reconcile `main`](#reconcile-main) PR from `reconcile/vX.Y.Z` or `reconcile/vX.Y.Z-beta.N`, so its CI runs in parallel with the release branch's `CI` and `Desktop Packages`. Do not merge it during Preparation.
|
||||
9. Wait for `CI` and `Desktop Packages` on the release branch to pass (never wait on `main` CI), and run the [pre-release dependency checks](#pre-release-dependency-checks) on the release commit.
|
||||
9. Wait for `CI` and `Desktop Packages` on the release branch to pass (never wait on `main` CI), and run the [pre-release dependency checks](#pre-release-dependency-checks) on the release commit. Because `release:prep:<mode>` updates `package-lock.json`, `CI`'s `quality` job verifies `nix/npm-deps.hash` on `release/**` branches and prints the exact `printf '%s\n' '<hash>' > nix/npm-deps.hash` command if stale.
|
||||
|
||||
### Ship
|
||||
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
sha256-+JWe/7lan6F71xfaMMDMAKU0/qW84gaXvGxm+MRKWrk=
|
||||
sha256-nWaU16CvKjT2bhQ/Q0gxZOv2NGxODBwn7lZ/EQgE+u0=
|
||||
|
||||
Generated
-56
@@ -22440,18 +22440,6 @@
|
||||
"node": "6.* || 8.* || >= 10.*"
|
||||
}
|
||||
},
|
||||
"node_modules/get-east-asian-width": {
|
||||
"version": "1.7.0",
|
||||
"resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.7.0.tgz",
|
||||
"integrity": "sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/get-intrinsic": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
|
||||
@@ -39835,7 +39823,6 @@
|
||||
"chalk": "5.6.2",
|
||||
"commander": "12.1.0",
|
||||
"mime-types": "2.1.35",
|
||||
"string-width": "9.0.0",
|
||||
"tree-kill": "1.2.2",
|
||||
"ws": "8.20.0",
|
||||
"yaml": "2.8.4",
|
||||
@@ -39942,18 +39929,6 @@
|
||||
"url": "https://opencollective.com/vitest"
|
||||
}
|
||||
},
|
||||
"packages/cli/node_modules/ansi-regex": {
|
||||
"version": "6.6.0",
|
||||
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.6.0.tgz",
|
||||
"integrity": "sha512-XZ5apbzreCbXSKwPjJstu8R0zOi247w3XYwWxtwBXgpZrCyc1Ka7p9/xY0A9/diMewmHbEKz+FIraWaEWjlN5g==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/chalk/ansi-regex?sponsor=1"
|
||||
}
|
||||
},
|
||||
"packages/cli/node_modules/chalk": {
|
||||
"version": "5.6.2",
|
||||
"resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz",
|
||||
@@ -39975,37 +39950,6 @@
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"packages/cli/node_modules/string-width": {
|
||||
"version": "9.0.0",
|
||||
"resolved": "https://registry.npmjs.org/string-width/-/string-width-9.0.0.tgz",
|
||||
"integrity": "sha512-2MOboAIRIszVGZVPA2Zqwj0ujd0o+xAZ5y2ft4OcD4kuVQ4phZxq0Sv7YTY8yaDA2CSMXch1EWTkJw+tTJZTzA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"get-east-asian-width": "^1.7.0",
|
||||
"strip-ansi": "^7.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"packages/cli/node_modules/strip-ansi": {
|
||||
"version": "7.2.0",
|
||||
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz",
|
||||
"integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ansi-regex": "^6.2.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/chalk/strip-ansi?sponsor=1"
|
||||
}
|
||||
},
|
||||
"packages/cli/node_modules/vitest": {
|
||||
"version": "4.1.6",
|
||||
"resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.6.tgz",
|
||||
|
||||
+5
-1
@@ -129,7 +129,11 @@
|
||||
"release:push": "node scripts/push-current-release-tag.mjs",
|
||||
"release:ship": "npm run release:push",
|
||||
"release:ship:beta": "npm run release:push",
|
||||
"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",
|
||||
|
||||
@@ -137,3 +137,36 @@ test("applies the content font size to an already-open chat", async ({ page }) =
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps agent tab menu labels whole at the largest interface font size", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
test.setTimeout(120_000);
|
||||
await page.addInitScript(() => {
|
||||
localStorage.setItem("@paseo:app-settings", JSON.stringify({ uiBaseFontSize: 21 }));
|
||||
});
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "tab-menu-font-size-",
|
||||
title: "Tab menu",
|
||||
});
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
const tab = page.getByTestId(`workspace-tab-agent_${agent.agentId}`).first();
|
||||
await expect(tab).toBeVisible({ timeout: 30_000 });
|
||||
await tab.click({ button: "right" });
|
||||
|
||||
const menu = page.getByTestId(`workspace-tab-context-agent_${agent.agentId}`);
|
||||
const item = page.getByTestId(
|
||||
`workspace-tab-context-agent_${agent.agentId}-copy-resume-command`,
|
||||
);
|
||||
const label = item.getByText("Copy resume command", { exact: true });
|
||||
await expect(label).toHaveCSS("font-size", "21px");
|
||||
await menu.screenshot({ path: testInfo.outputPath("agent-tab-menu-21px.png") });
|
||||
|
||||
// A single-line label that ellipsizes has a scrollWidth wider than its clientWidth.
|
||||
const overflow = await label.evaluate((element) => element.scrollWidth - element.clientWidth);
|
||||
expect(overflow).toBeLessThanOrEqual(0);
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -570,13 +570,13 @@ test("Changes selects exact local and remote bases and retains the selection aft
|
||||
const picker = tree.getByTestId("workspace-base-branch-trigger");
|
||||
await expect(picker).toBeVisible();
|
||||
await picker.click();
|
||||
await expect(page.getByRole("button", { name: "release", exact: true })).toBeVisible();
|
||||
await expect(page.getByRole("option", { name: "release", exact: true })).toBeVisible();
|
||||
await page.screenshot({ path: testInfo.outputPath("base-picker.png") });
|
||||
await page.getByRole("button", { name: "release", exact: true }).click();
|
||||
await page.getByRole("option", { name: "release", exact: true }).click();
|
||||
await expect(picker).toContainText("release");
|
||||
await expect(tree.getByText("No changes to display", { exact: true })).toBeVisible();
|
||||
await picker.click();
|
||||
await page.getByRole("button", { name: "upstream/release", exact: true }).click();
|
||||
await page.getByRole("option", { name: "upstream/release", exact: true }).click();
|
||||
await expect(picker).toContainText("upstream/release");
|
||||
await expect(tree.getByText("committed-only.ts", { exact: true })).toBeVisible();
|
||||
await page.screenshot({ path: testInfo.outputPath("base-selected.png") });
|
||||
@@ -639,7 +639,7 @@ test("Changes shows a failed base selection and lets the user retry", async ({ p
|
||||
.filter({ visible: true })
|
||||
.first();
|
||||
await picker.click();
|
||||
const option = page.getByRole("button", { name: "release", exact: true });
|
||||
const option = page.getByRole("option", { name: "release", exact: true });
|
||||
await expect(option).toBeVisible();
|
||||
execFileSync("git", ["branch", "-D", "release"], { cwd: workspace.repoPath });
|
||||
await option.click();
|
||||
@@ -2307,7 +2307,7 @@ async function chooseBase(page: Page, picker: Locator, label: string): Promise<v
|
||||
await picker.click();
|
||||
await page
|
||||
.getByTestId("combobox-desktop-container")
|
||||
.getByRole("button", { name: label, exact: true })
|
||||
.getByRole("option", { name: label, exact: true })
|
||||
.click();
|
||||
}
|
||||
|
||||
|
||||
@@ -66,7 +66,7 @@ async function selectSpeed(page: Page, label: string): Promise<void> {
|
||||
await expect(pill).toHaveAttribute("aria-selected", "true");
|
||||
return;
|
||||
}
|
||||
await page.getByRole("button", { name: label, exact: true }).last().click();
|
||||
await page.getByRole("option", { name: label, exact: true }).last().click();
|
||||
const toolbarTrigger = page.getByRole("button", { name: `Speed: ${label}`, exact: true });
|
||||
const sheetTrigger = page.getByRole("button", { name: "Select speed", exact: true });
|
||||
await expect(toolbarTrigger.or(sheetTrigger)).toBeVisible();
|
||||
|
||||
@@ -1,16 +1,20 @@
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import {
|
||||
closeCommandCenter,
|
||||
enterChangeThemeSublist,
|
||||
enterCommandCenterSublist,
|
||||
expectCommandCenterSublist,
|
||||
expectCommandCenterTab,
|
||||
expectCommandCenterTabs,
|
||||
expectCommandCenterThemeSelected,
|
||||
openCommandCenter,
|
||||
switchThemeViaCommandCenter,
|
||||
} from "../support/helpers/command-center";
|
||||
import { expectWorkspaceAgentConfiguration } from "../support/helpers/command-center-agent-controls";
|
||||
import { holdDirectorySuggestionResponses } from "../support/helpers/command-center-file-search";
|
||||
import { expectFileTabOpen } from "../support/helpers/file-explorer";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
import { seedWorkspace } from "../support/helpers/seed-client";
|
||||
|
||||
const SAMPLE_FILES = [
|
||||
@@ -154,3 +158,121 @@ test("Switch model and Search files sub-lists keep top-level search clean and qu
|
||||
await leanSpec.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("Change theme sub-list filters, switches themes across Dark, Light, and Pure black, and backs out cleanly", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(180_000);
|
||||
|
||||
const workspace = await seedWorkspace({
|
||||
repoPrefix: "cc-theme-switcher-",
|
||||
title: "Theme switcher workspace",
|
||||
});
|
||||
|
||||
try {
|
||||
await page.goto(`/h/${encodeURIComponent(getServerId())}/workspace/${workspace.workspaceId}`);
|
||||
const sidebarRow = page.getByTestId(
|
||||
`sidebar-workspace-row-${getServerId()}:${workspace.workspaceId}`,
|
||||
);
|
||||
await expect(sidebarRow).toBeVisible({ timeout: 30_000 });
|
||||
|
||||
const panel = await openCommandCenter(page);
|
||||
const searchInput = panel.getByTestId("command-center-input");
|
||||
|
||||
await test.step("top-level Change theme shows active theme and keeps theme options out of root search", async () => {
|
||||
const trigger = panel.getByTestId("command-center-change-theme");
|
||||
await expect(trigger).toBeVisible();
|
||||
await expect(trigger).toContainText("Change theme");
|
||||
await expect(trigger).toContainText("System");
|
||||
|
||||
await searchInput.fill("pure black");
|
||||
await expect(panel.locator('[data-testid^="command-center-theme-"]')).toHaveCount(0);
|
||||
await expect(panel.getByTestId("command-center-change-theme")).toHaveCount(0);
|
||||
});
|
||||
|
||||
await test.step("entering Change theme lists all supported themes with active indicator and backs out without changing theme", async () => {
|
||||
await enterChangeThemeSublist(panel);
|
||||
await expect(searchInput).toHaveValue("");
|
||||
await expect(searchInput).toBeFocused();
|
||||
|
||||
for (const themeName of [
|
||||
"System",
|
||||
"Light",
|
||||
"Dark",
|
||||
"Zinc",
|
||||
"Midnight",
|
||||
"Claude",
|
||||
"Ghostty",
|
||||
"Pure black",
|
||||
]) {
|
||||
await expect(panel.getByRole("button", { name: themeName, exact: true })).toBeVisible();
|
||||
}
|
||||
await expectCommandCenterThemeSelected(panel, "System");
|
||||
|
||||
await searchInput.fill("pure");
|
||||
await expect(panel.getByRole("button", { name: "Pure black", exact: true })).toBeVisible();
|
||||
await expect(panel.getByRole("button", { name: "Light", exact: true })).toHaveCount(0);
|
||||
|
||||
// Backing out via Escape returns to root without applying the filtered/highlighted theme.
|
||||
await page.keyboard.press("Escape");
|
||||
await expectCommandCenterTab(panel, "All");
|
||||
await expect(panel.getByTestId("command-center-change-theme")).toContainText("System");
|
||||
|
||||
// Re-entering and backing out via Backspace on empty query also keeps System active.
|
||||
await enterChangeThemeSublist(panel);
|
||||
await page.keyboard.press("ArrowDown");
|
||||
await page.keyboard.press("Backspace");
|
||||
await expectCommandCenterTab(panel, "All");
|
||||
await expect(panel.getByTestId("command-center-change-theme")).toContainText("System");
|
||||
await closeCommandCenter(page);
|
||||
});
|
||||
|
||||
await test.step("switching to Default Dark updates the app theme and active indicator", async () => {
|
||||
await switchThemeViaCommandCenter(page, "dark", "Dark");
|
||||
await expect(sidebarRow).toHaveCSS("background-color", "rgb(40, 42, 41)");
|
||||
|
||||
await openCommandCenter(page);
|
||||
await expect(panel.getByTestId("command-center-change-theme")).toContainText("Dark");
|
||||
await expect(panel).toHaveCSS("background-color", "rgb(24, 27, 26)");
|
||||
await enterChangeThemeSublist(panel);
|
||||
await expectCommandCenterThemeSelected(panel, "Dark");
|
||||
await page.keyboard.press("Escape");
|
||||
await expectCommandCenterTab(panel, "All");
|
||||
await closeCommandCenter(page);
|
||||
});
|
||||
|
||||
await test.step("switching to Light updates the app theme and active indicator", async () => {
|
||||
await switchThemeViaCommandCenter(page, "light", "Light");
|
||||
await expect(sidebarRow).toHaveCSS("background-color", "rgb(212, 212, 213)");
|
||||
|
||||
await openCommandCenter(page);
|
||||
await expect(panel.getByTestId("command-center-change-theme")).toContainText("Light");
|
||||
await expect(panel).toHaveCSS("background-color", "rgb(255, 255, 255)");
|
||||
await enterChangeThemeSublist(panel);
|
||||
await expectCommandCenterThemeSelected(panel, "Light");
|
||||
await page.keyboard.press("Escape");
|
||||
await expectCommandCenterTab(panel, "All");
|
||||
await closeCommandCenter(page);
|
||||
});
|
||||
|
||||
await test.step("switching to Pure black updates the app theme and persists across reload", async () => {
|
||||
await switchThemeViaCommandCenter(page, "pure black", "Pure black");
|
||||
await expect(sidebarRow).toHaveCSS("background-color", "rgb(29, 29, 29)");
|
||||
|
||||
await page.reload();
|
||||
await expect(sidebarRow).toBeVisible({ timeout: 30_000 });
|
||||
await expect(sidebarRow).toHaveCSS("background-color", "rgb(29, 29, 29)");
|
||||
|
||||
await openCommandCenter(page);
|
||||
await expect(panel.getByTestId("command-center-change-theme")).toContainText("Pure black");
|
||||
await expect(panel).toHaveCSS("background-color", "rgb(0, 0, 0)");
|
||||
await enterChangeThemeSublist(panel);
|
||||
await expectCommandCenterThemeSelected(panel, "Pure black");
|
||||
await page.keyboard.press("Escape");
|
||||
await expectCommandCenterTab(panel, "All");
|
||||
await closeCommandCenter(page);
|
||||
});
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
import { expect, test, type Page } from "../support/fixtures";
|
||||
import { gotoWorkspace } from "../support/helpers/launcher";
|
||||
import { seedWorkspace } from "../support/helpers/seed-client";
|
||||
import { dragTabIntoExplorer, ensureExplorerSidebar } from "../support/helpers/workspace-tabs";
|
||||
|
||||
type SeededWorkspace = Awaited<ReturnType<typeof seedWorkspace>>;
|
||||
type Pane = "main" | "dock";
|
||||
|
||||
const PANE_TEST_IDS: Record<Pane, string> = {
|
||||
main: "workspace-pane-main",
|
||||
dock: "workspace-explorer-sidebar",
|
||||
};
|
||||
|
||||
test.use({ viewport: { width: 1600, height: 900 } });
|
||||
|
||||
function pane(page: Page, which: Pane) {
|
||||
return page.getByTestId(PANE_TEST_IDS[which]).filter({ visible: true });
|
||||
}
|
||||
|
||||
function composerInput(page: Page, which: Pane) {
|
||||
return pane(page, which).getByRole("textbox", { name: "Message agent..." });
|
||||
}
|
||||
|
||||
function agentTab(page: Page, which: Pane, agentId: string) {
|
||||
return pane(page, which).getByTestId(`workspace-tab-agent_${agentId}`);
|
||||
}
|
||||
|
||||
/** Starts a long-streaming mock agent and waits until its tab shows in the main pane. */
|
||||
async function startRunningAgent(
|
||||
page: Page,
|
||||
workspace: SeededWorkspace,
|
||||
title: string,
|
||||
): Promise<string> {
|
||||
const agent = await workspace.client.createAgent({
|
||||
provider: "mock",
|
||||
cwd: workspace.repoPath,
|
||||
workspaceId: workspace.workspaceId,
|
||||
title,
|
||||
modeId: "load-test",
|
||||
model: "one-minute-stream",
|
||||
initialPrompt: `Keep running ${title}.`,
|
||||
});
|
||||
await workspace.client.waitForAgentUpsert(
|
||||
agent.id,
|
||||
(snapshot) => snapshot.status === "running",
|
||||
15_000,
|
||||
);
|
||||
await expect(agentTab(page, "main", agent.id)).toBeVisible();
|
||||
return agent.id;
|
||||
}
|
||||
|
||||
/** Moves an agent's tab into the Explorer dock, then shows the other agent in the main pane. */
|
||||
async function dockAgentBesideMain(page: Page, dockAgentId: string, mainAgentId: string) {
|
||||
await ensureExplorerSidebar(page);
|
||||
await dragTabIntoExplorer(page, `agent_${dockAgentId}`);
|
||||
await expect(agentTab(page, "dock", dockAgentId)).toBeVisible();
|
||||
// Click the tab's leading edge; its close button overlays the trailing edge on hover.
|
||||
await agentTab(page, "main", mainAgentId).click({ position: { x: 12, y: 13 } });
|
||||
await expect(composerInput(page, "dock")).toBeVisible();
|
||||
}
|
||||
|
||||
async function focusComposer(page: Page, which: Pane) {
|
||||
await composerInput(page, which).click();
|
||||
}
|
||||
|
||||
/** Leaves the composer the way a click on the agent's timeline does. */
|
||||
async function blurComposer(page: Page, which: Pane) {
|
||||
await composerInput(page, which).blur();
|
||||
}
|
||||
|
||||
async function openSettings(page: Page) {
|
||||
await page.getByTestId("sidebar-settings").filter({ visible: true }).first().click();
|
||||
await expect(page).toHaveURL(/\/settings/);
|
||||
}
|
||||
|
||||
async function agentStatus(workspace: SeededWorkspace, agentId: string): Promise<string | null> {
|
||||
const fetched = await workspace.client.fetchAgent({ agentId });
|
||||
return fetched?.agent.status ?? null;
|
||||
}
|
||||
|
||||
async function expectAgentInterrupted(workspace: SeededWorkspace, agentId: string) {
|
||||
await expect.poll(() => agentStatus(workspace, agentId), { timeout: 15_000 }).toBe("idle");
|
||||
}
|
||||
|
||||
async function expectAgentRunning(workspace: SeededWorkspace, agentId: string) {
|
||||
expect(await agentStatus(workspace, agentId)).toBe("running");
|
||||
}
|
||||
|
||||
test("Escape interrupts the agent whose composer had focus last, not the Explorer dock's", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(180_000);
|
||||
const workspace = await seedWorkspace({ repoPrefix: "composer-escape-dock-" });
|
||||
try {
|
||||
await gotoWorkspace(page, workspace.workspaceId);
|
||||
const mainAgentId = await startRunningAgent(page, workspace, "main agent");
|
||||
// The dock's composer mounts after the main pane's.
|
||||
const dockAgentId = await startRunningAgent(page, workspace, "dock agent");
|
||||
await dockAgentBesideMain(page, dockAgentId, mainAgentId);
|
||||
|
||||
await test.step("Escape after the main composer blurs interrupts only the main agent", async () => {
|
||||
await focusComposer(page, "main");
|
||||
await blurComposer(page, "main");
|
||||
await page.keyboard.press("Escape");
|
||||
await expectAgentInterrupted(workspace, mainAgentId);
|
||||
await expectAgentRunning(workspace, dockAgentId);
|
||||
});
|
||||
|
||||
await test.step("Escape in the dock's composer interrupts the dock agent", async () => {
|
||||
await focusComposer(page, "dock");
|
||||
await page.keyboard.press("Escape");
|
||||
await expectAgentInterrupted(workspace, dockAgentId);
|
||||
});
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("Escape on desktop Settings closes it and leaves the agent running", async ({ page }) => {
|
||||
test.setTimeout(180_000);
|
||||
const workspace = await seedWorkspace({ repoPrefix: "composer-escape-settings-" });
|
||||
try {
|
||||
await gotoWorkspace(page, workspace.workspaceId);
|
||||
const agentId = await startRunningAgent(page, workspace, "running agent");
|
||||
await focusComposer(page, "main");
|
||||
await openSettings(page);
|
||||
|
||||
await page.keyboard.press("Escape");
|
||||
|
||||
await expect(page).toHaveURL(new RegExp(`/workspace/${workspace.workspaceId}`));
|
||||
await expectAgentRunning(workspace, agentId);
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
@@ -173,28 +173,33 @@ test("customizes a host badge and preserves its appearance after reload", async
|
||||
});
|
||||
|
||||
base(
|
||||
"activates Add host from the sidebar host picker via focus+Enter and Arrow+Enter",
|
||||
"activates Add host from the sidebar host picker via Arrow+Enter and click",
|
||||
async ({ page }) => {
|
||||
await gotoAppShell(page);
|
||||
const trigger = page.getByTestId("sidebar-hosts-trigger");
|
||||
await expect(trigger).toBeVisible();
|
||||
|
||||
// Focus + Enter on Add host must open the Add connection dialog rather than selecting the active host.
|
||||
// ArrowDown + Enter on Add host must open the Add connection dialog rather than selecting the active host.
|
||||
const addConnectionDialog = page.getByRole("dialog").filter({ hasText: "Add connection" });
|
||||
await trigger.click();
|
||||
const addHostButton = page.getByRole("button", { name: "Add host", exact: true });
|
||||
await expect(addHostButton).toBeVisible();
|
||||
await addHostButton.focus();
|
||||
const listbox = page.getByTestId("combobox-desktop-container");
|
||||
const addHostOption = page.getByRole("option", { name: "Add host", exact: true });
|
||||
await expect(addHostOption).toBeVisible();
|
||||
await expect(addHostOption).toHaveAttribute("tabindex", "-1");
|
||||
await page.keyboard.press("ArrowDown");
|
||||
await expect(listbox).toHaveAttribute(
|
||||
"aria-activedescendant",
|
||||
(await addHostOption.getAttribute("id"))!,
|
||||
);
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(addConnectionDialog).toBeVisible();
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(addConnectionDialog).toBeHidden();
|
||||
|
||||
// ArrowDown + Enter must also reach Add host from the host list.
|
||||
// Clicking the Add host option also opens Add connection.
|
||||
await trigger.click();
|
||||
await expect(addHostButton).toBeVisible();
|
||||
await page.keyboard.press("ArrowDown");
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(addHostOption).toBeVisible();
|
||||
await addHostOption.click();
|
||||
await expect(addConnectionDialog).toBeVisible();
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { expect, type Locator, type Page } from "@playwright/test";
|
||||
import { test } from "../support/fixtures";
|
||||
import { openSettings } from "../support/helpers/app";
|
||||
import { gotoWorkspace } from "../support/helpers/launcher";
|
||||
import { seedWorkspace } from "../support/helpers/seed-client";
|
||||
import { openSettingsSection } from "../support/helpers/settings";
|
||||
import { waitForWorkspaceTabsVisible } from "../support/helpers/workspace-tabs";
|
||||
|
||||
const HEADER_ICON_BUTTONS = ["workspace-header-menu-trigger", "workspace-explorer-toggle"];
|
||||
@@ -14,12 +16,18 @@ function matchesFocusVisible(target: Locator): Promise<boolean> {
|
||||
return target.evaluate((el) => el.matches(":focus-visible"));
|
||||
}
|
||||
|
||||
async function expectKeyboardFocusRing(page: Page, testId: string): Promise<void> {
|
||||
async function tabUntilFocused(page: Page, target: Locator): Promise<void> {
|
||||
// Start from the preceding tabbable sibling so Tab naturally lands on target,
|
||||
// or step back and Tab forward onto target.
|
||||
await target.focus();
|
||||
await page.keyboard.press("Shift+Tab");
|
||||
await page.keyboard.press("Tab");
|
||||
await expect(target).toBeFocused();
|
||||
}
|
||||
|
||||
async function expectTabFocusRing(page: Page, testId: string): Promise<void> {
|
||||
const button = visible(page, testId);
|
||||
// Chromium matches :focus-visible on a programmatic focus that follows keyboard input.
|
||||
await page.keyboard.press("Shift");
|
||||
await button.focus();
|
||||
await expect(button).toBeFocused();
|
||||
await tabUntilFocused(page, button);
|
||||
expect(await matchesFocusVisible(button)).toBe(true);
|
||||
await expect(button).toHaveCSS("outline-style", "solid");
|
||||
await expect(button).toHaveCSS("outline-width", "2px");
|
||||
@@ -30,6 +38,16 @@ async function expectKeyboardFocusRing(page: Page, testId: string): Promise<void
|
||||
async function expectNoPointerFocusRing(page: Page, testId: string): Promise<void> {
|
||||
const button = visible(page, testId);
|
||||
await button.blur();
|
||||
if (testId === "workspace-header-menu-trigger") {
|
||||
await button.click();
|
||||
const backdrop = page.getByTestId("workspace-header-menu-backdrop");
|
||||
await expect(backdrop).toBeVisible();
|
||||
await backdrop.click();
|
||||
await expect(backdrop).toHaveCount(0);
|
||||
expect(await matchesFocusVisible(button)).toBe(false);
|
||||
await expect(button).toHaveCSS("outline-style", "none");
|
||||
return;
|
||||
}
|
||||
// Toggle twice so the layout ends where it started.
|
||||
await button.click();
|
||||
await button.click();
|
||||
@@ -39,16 +57,44 @@ async function expectNoPointerFocusRing(page: Page, testId: string): Promise<voi
|
||||
}
|
||||
|
||||
test.describe("Icon button focus ring", () => {
|
||||
test("header icon buttons show the focus ring for keyboard focus only", async ({ page }) => {
|
||||
test("header icon buttons show the focus ring for keyboard :focus-visible only", async ({
|
||||
page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1440, height: 900 });
|
||||
const workspace = await seedWorkspace({ repoPrefix: "icon-button-focus-" });
|
||||
try {
|
||||
await gotoWorkspace(page, workspace.workspaceId);
|
||||
await waitForWorkspaceTabsVisible(page);
|
||||
for (const testId of HEADER_ICON_BUTTONS) {
|
||||
await expectKeyboardFocusRing(page, testId);
|
||||
await expectTabFocusRing(page, testId);
|
||||
await expectNoPointerFocusRing(page, testId);
|
||||
}
|
||||
await expectNoPointerFocusRing(page, "workspace-explorer-toggle");
|
||||
|
||||
// Verify the New tab panel edit-terminal-profiles pencil button (#9758) draws a :focus-visible ring.
|
||||
const editProfilesButton = visible(page, "workspace-new-tab-edit-terminal-profiles");
|
||||
await expect(editProfilesButton).toBeVisible();
|
||||
await tabUntilFocused(page, editProfilesButton);
|
||||
expect(await matchesFocusVisible(editProfilesButton)).toBe(true);
|
||||
await expect(editProfilesButton).toHaveCSS("outline-style", "solid");
|
||||
await expect(editProfilesButton).toHaveCSS("outline-width", "2px");
|
||||
await editProfilesButton.blur();
|
||||
await expect(editProfilesButton).toHaveCSS("outline-style", "none");
|
||||
|
||||
await openSettings(page);
|
||||
await openSettingsSection(page, "chat");
|
||||
const outlineSwitch = page.getByRole("switch", { name: "Chat outline" });
|
||||
await expect(outlineSwitch).toBeVisible();
|
||||
await tabUntilFocused(page, outlineSwitch);
|
||||
expect(await matchesFocusVisible(outlineSwitch)).toBe(true);
|
||||
await expect(outlineSwitch).toHaveCSS("outline-style", "none");
|
||||
const switchTrack = outlineSwitch.locator('[data-switch-track="true"]');
|
||||
await expect(switchTrack).toHaveCSS("outline-style", "solid");
|
||||
await expect(switchTrack).toHaveCSS("outline-width", "2px");
|
||||
await outlineSwitch.blur();
|
||||
await outlineSwitch.click();
|
||||
await outlineSwitch.click();
|
||||
expect(await matchesFocusVisible(outlineSwitch)).toBe(false);
|
||||
await expect(switchTrack).toHaveCSS("outline-style", "none");
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
|
||||
@@ -1,17 +1,22 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import type { Locator, Page } from "@playwright/test";
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import { closeCommandCenter, openCommandCenter } from "../support/helpers/command-center";
|
||||
|
||||
// Where Settings → Keyboard shortcuts persists a rebound shortcut.
|
||||
const OVERRIDE_STORAGE_KEY = "@paseo:keyboard-shortcut-overrides";
|
||||
const COMMAND_CENTER_BINDING = "command-center-toggle-ctrl-k-non-mac";
|
||||
const COMMAND_CENTER_BINDINGS = [
|
||||
"command-center-toggle-cmd-k-mac",
|
||||
"command-center-toggle-ctrl-k-non-mac",
|
||||
] as const;
|
||||
|
||||
async function rebindCommandCenter(page: Page, combo: string): Promise<void> {
|
||||
await page.addInitScript(
|
||||
([key, bindingId, value]) => {
|
||||
window.localStorage.setItem(key, JSON.stringify({ [bindingId]: value }));
|
||||
([key, bindingIds, value]) => {
|
||||
const overrides = Object.fromEntries(bindingIds.map((id) => [id, value]));
|
||||
window.localStorage.setItem(key, JSON.stringify(overrides));
|
||||
},
|
||||
[OVERRIDE_STORAGE_KEY, COMMAND_CENTER_BINDING, combo] as const,
|
||||
[OVERRIDE_STORAGE_KEY, COMMAND_CENTER_BINDINGS, combo] as const,
|
||||
);
|
||||
await gotoAppShell(page);
|
||||
await expect(page.getByTestId("sidebar-search")).toBeVisible({ timeout: 30_000 });
|
||||
@@ -21,6 +26,18 @@ async function expectCommandCenterOpen(page: Page): Promise<void> {
|
||||
await expect(page.getByTestId("command-center-panel")).toBeVisible({ timeout: 10_000 });
|
||||
}
|
||||
|
||||
async function expectCommandCenterSearchAcceptsKey(
|
||||
page: Page,
|
||||
panel: Locator,
|
||||
key: string,
|
||||
): Promise<void> {
|
||||
const searchInput = panel.getByTestId("command-center-input");
|
||||
await expect(searchInput).toBeFocused({ timeout: 10_000 });
|
||||
await page.keyboard.press(key);
|
||||
await expect(searchInput).toHaveValue(key);
|
||||
await expectCommandCenterOpen(page);
|
||||
}
|
||||
|
||||
test.describe("Multi-step shortcut", () => {
|
||||
test("completes a chord whose second step is a bare key", async ({ page }) => {
|
||||
await rebindCommandCenter(page, "Ctrl+K J");
|
||||
@@ -41,4 +58,17 @@ test.describe("Multi-step shortcut", () => {
|
||||
|
||||
await expectCommandCenterOpen(page);
|
||||
});
|
||||
|
||||
test("typing a rebound printable shortcut inside Command Center enters text instead of toggling it closed", async ({
|
||||
page,
|
||||
}) => {
|
||||
await rebindCommandCenter(page, "J");
|
||||
|
||||
const commandCenter = await openCommandCenter(page);
|
||||
await expectCommandCenterSearchAcceptsKey(page, commandCenter, "j");
|
||||
|
||||
await closeCommandCenter(page);
|
||||
await page.keyboard.press("j");
|
||||
await expectCommandCenterOpen(page);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
type TerminalProfile,
|
||||
} from "../support/helpers/new-workspace-launch";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import { runCommandCenterItem } from "../support/helpers/command-center";
|
||||
import { waitForSidebarHydration } from "../support/helpers/workspace-ui";
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
|
||||
@@ -192,6 +193,20 @@ test.describe("Tab creation", () => {
|
||||
await expect(agent).toBeFocused();
|
||||
});
|
||||
|
||||
test("the Command Center's New terminal row replaces a focused New tab", async ({ page }) => {
|
||||
await gotoWorkspace(page, workspace.workspaceId);
|
||||
await openNewTabMenuWithShortcut(page);
|
||||
const tabs = (await getTabTestIds(page)).length;
|
||||
|
||||
await runCommandCenterItem(page, "New terminal");
|
||||
|
||||
await expect(
|
||||
page.getByTestId("workspace-new-tab-panel").filter({ visible: true }),
|
||||
).toBeHidden();
|
||||
await expectTerminalSurfaceVisible(page);
|
||||
await expect.poll(async () => (await getTabTestIds(page)).length).toBe(tabs);
|
||||
});
|
||||
|
||||
test("the Agent menu creates a draft and shows its composer within the visual budget", async ({
|
||||
page,
|
||||
}) => {
|
||||
|
||||
@@ -86,7 +86,7 @@ async function selectMode(page: Page, label: string): Promise<void> {
|
||||
await expect(popup).toBeVisible({ timeout: 10_000 });
|
||||
await expectNoTruncation(popup);
|
||||
|
||||
const searchInput = page.getByRole("textbox", { name: /search mode/i });
|
||||
const searchInput = page.getByRole("combobox", { name: /search mode/i });
|
||||
await expect(searchInput).toBeVisible({ timeout: 10_000 });
|
||||
await searchInput.fill(label);
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import { runCommandCenterItem } from "../support/helpers/command-center";
|
||||
import {
|
||||
chooseProjectWithKeyboard,
|
||||
connectNewWorkspaceDaemonClient,
|
||||
@@ -161,6 +162,23 @@ test.describe("New workspace entry points", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("the Command Center's New workspace row opens the project picker on the New Workspace screen", async ({
|
||||
page,
|
||||
}) => {
|
||||
const seeded: SeededWorkspace = await seedWorkspace({ repoPrefix: "entry-command-center-" });
|
||||
|
||||
try {
|
||||
await gotoAppShell(page);
|
||||
await waitForSidebarHydration(page);
|
||||
await openGlobalNewWorkspaceComposer(page);
|
||||
|
||||
await runCommandCenterItem(page, "New workspace");
|
||||
await expect(page.getByPlaceholder("Search projects")).toBeVisible();
|
||||
} finally {
|
||||
await seeded.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("Ctrl+N opens the project picker with search focused", async ({ page }) => {
|
||||
const seeded: SeededWorkspace = await seedWorkspace({ repoPrefix: "entry-shortcut-" });
|
||||
|
||||
|
||||
@@ -97,7 +97,8 @@ test.describe("New Workspace mode cycle safety", () => {
|
||||
// Regression guard for the P1 safety bug: cycling the execution mode with Shift+Tab in
|
||||
// the New Workspace composer must never reach a backgrounded, still-mounted agent's mode
|
||||
// control and silently change that (possibly running) agent's mode — e.g. into a
|
||||
// permissive/bypass mode. See use-keyboard-action-handler.ts.
|
||||
// permissive/bypass mode. The New Workspace screen's `paseo/new-workspace` action scope
|
||||
// must shadow a backgrounded composer's handler.
|
||||
test("Shift+Tab in New Workspace never changes a backgrounded agent's mode", async ({ page }) => {
|
||||
const seeded = await seedWorkspace({ repoPrefix: "mode-cycle-safety-" });
|
||||
await seedCodexDefaultPreferences(page);
|
||||
|
||||
@@ -50,6 +50,7 @@ import { createTempDirectory, createTempGitRepo } from "../support/helpers/works
|
||||
const MIDNIGHT_MUTED_FOREGROUND = "rgb(154, 157, 176)";
|
||||
|
||||
test("a new user is walked through setup once", async ({ page }, testInfo) => {
|
||||
test.setTimeout(180_000);
|
||||
const host = await startSetupHost("fresh");
|
||||
const repo = await createTempGitRepo("onboarding-folder-");
|
||||
|
||||
@@ -89,6 +90,24 @@ test("a new user is walked through setup once", async ({ page }, testInfo) => {
|
||||
await expectSetupStep(page, "Your providers");
|
||||
});
|
||||
|
||||
await test.step("a removed provider can be added back with Remove enabled", async () => {
|
||||
const detail = setupSheet(page, "provider-settings-sheet");
|
||||
const remove = detail.getByRole("button", { name: "Remove", exact: true });
|
||||
|
||||
await openAddProvider(page);
|
||||
await installAcpCatalogProvider(page, "Junie");
|
||||
page.once("dialog", (dialog) => void dialog.accept());
|
||||
await remove.click();
|
||||
await expect(detail).toHaveCount(0);
|
||||
|
||||
await openAddProvider(page);
|
||||
await installAcpCatalogProvider(page, "Junie");
|
||||
await expect(remove).toHaveText("Remove");
|
||||
await expect(remove).toBeEnabled();
|
||||
await detail.getByRole("button", { name: "Back to providers", exact: true }).click();
|
||||
await expect(detail).toHaveCount(0);
|
||||
});
|
||||
|
||||
await test.step("with no agent history, Add project opens the regular flow and the folder shows as added", async () => {
|
||||
await continueSetup(page);
|
||||
await expectSetupStep(page, "Add your projects");
|
||||
@@ -128,33 +147,6 @@ test("a new user is walked through setup once", async ({ page }, testInfo) => {
|
||||
}
|
||||
});
|
||||
|
||||
test("a provider removed in setup can be added back and removed again", async ({ page }) => {
|
||||
test.setTimeout(180_000);
|
||||
const host = await startSetupHost("re-add");
|
||||
const detail = setupSheet(page, "provider-settings-sheet");
|
||||
const remove = detail.getByTestId("provider-remove");
|
||||
page.on("dialog", (dialog) => void dialog.accept());
|
||||
|
||||
try {
|
||||
await openAppAsNewUser(page, host);
|
||||
await continueSetup(page);
|
||||
await expectSetupStep(page, "Your providers");
|
||||
|
||||
await openAddProvider(page);
|
||||
await installAcpCatalogProvider(page, "Junie");
|
||||
await remove.click();
|
||||
await expect(detail).toHaveCount(0);
|
||||
|
||||
// Adding it back opens the same provider's sheet, which must not still be removing it.
|
||||
await openAddProvider(page);
|
||||
await installAcpCatalogProvider(page, "Junie");
|
||||
await expect(remove).toHaveText("Remove");
|
||||
await expect(remove).toBeEnabled();
|
||||
} finally {
|
||||
await host.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("a new user goes from the loading screen straight into setup", async ({ page }) => {
|
||||
const host = await startSetupHost("first-launch");
|
||||
|
||||
|
||||
@@ -261,7 +261,7 @@ async function pickCurrentMode(page: Page, embed: ReturnType<Page["getByTestId"]
|
||||
await trigger.click();
|
||||
const popup = page.getByTestId("combobox-desktop-container").last();
|
||||
await expect(popup).toBeVisible({ timeout: 10_000 });
|
||||
await popup.getByRole("button", { name: label, exact: true }).click();
|
||||
await popup.getByRole("option", { name: label, exact: true }).click();
|
||||
await expect(page.getByTestId("combobox-desktop-container")).toHaveCount(0);
|
||||
}
|
||||
|
||||
|
||||
@@ -29,12 +29,15 @@ function InboxScreen({ theme, params }) {
|
||||
);
|
||||
}
|
||||
|
||||
function InboxPopover({ theme, layout, close, openScreen }) {
|
||||
function InboxPopover({ theme, layout, close, openScreen, workspaceId, agentId }) {
|
||||
const workspaceName = useWorkspace(${JSON.stringify(workspaceId)}, (w) => w.name);
|
||||
return (
|
||||
<View style={{ padding: 12, gap: 10 }}>
|
||||
<Text style={{ color: theme.colors.foreground, fontSize: 16 }}>Inbox decisions</Text>
|
||||
<Text style={{ color: theme.colors.foregroundMuted }}>Workspace: {workspaceName}</Text>
|
||||
<Text style={{ color: theme.colors.foregroundMuted }}>
|
||||
Pill IDs: {workspaceId} / {agentId}
|
||||
</Text>
|
||||
<Text style={{ color: theme.colors.foregroundMuted }}>
|
||||
Presentation: {layout.compact ? "compact" : "wide"}
|
||||
</Text>
|
||||
@@ -692,6 +695,9 @@ test("declarative addComposerPillItem + ComposerPill and imperative pill fixes w
|
||||
const popoverTitle = page.getByText("Inbox decisions", { exact: true });
|
||||
await expect(popoverTitle).toBeInViewport();
|
||||
await expect(page.getByText("Presentation: wide", { exact: true })).toBeVisible();
|
||||
await expect(
|
||||
page.getByText(`Pill IDs: ${workspace.workspaceId} / ${agent.id}`, { exact: true }),
|
||||
).toBeVisible();
|
||||
await expectStill(popoverTitle);
|
||||
|
||||
const pillBox = (await inboxPill.boundingBox())!;
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
openFromInstalledTab,
|
||||
openListingPage,
|
||||
uninstallFromPage,
|
||||
verifyLocalizedMediaInDirectory,
|
||||
} from "../support/helpers/plugin-directory";
|
||||
|
||||
test("installs a listed plugin from Browse and uninstalls it from either of its pages", async ({
|
||||
@@ -170,3 +171,11 @@ test("opens plugin pages without empty markdown collapse, stacked back flash, or
|
||||
await expectStableDesktopBackToListing(page);
|
||||
await expectStackedFirstFrameOnNarrowDesktop(page);
|
||||
});
|
||||
|
||||
test("shows localized featured card and detail screenshots when the app language changes", async ({
|
||||
page,
|
||||
directoryHost,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1280, height: 960 });
|
||||
await verifyLocalizedMediaInDirectory(page, directoryHost);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import { openSettings } from "../support/helpers/app";
|
||||
import { closeCommandCenter } from "../support/helpers/command-center";
|
||||
import { openSettingsSection } from "../support/helpers/settings";
|
||||
import { runCommand } from "../support/helpers/plugin-sidebar-items";
|
||||
import {
|
||||
activateList,
|
||||
closeDialogWithEscape,
|
||||
closeRecentDecisions,
|
||||
expectInboxOpen,
|
||||
expectSelection,
|
||||
expectSubmitted,
|
||||
findCommandCenterRow,
|
||||
focusDecisionPane,
|
||||
installShortcutsExample,
|
||||
installShortcutsExampleOnTwoHosts,
|
||||
expectInboxOpenOn,
|
||||
showScreenOnHost,
|
||||
decisionList,
|
||||
openHelpDialog,
|
||||
openRecentDecisions,
|
||||
searchField,
|
||||
SHORTCUTS_PLUGIN_NAME,
|
||||
} from "../support/helpers/plugin-shortcuts";
|
||||
import {
|
||||
openShortcutSettings,
|
||||
pressCapturedKeys,
|
||||
saveRebinding,
|
||||
shortcutRow,
|
||||
startRebinding,
|
||||
} from "../support/helpers/shortcut-settings";
|
||||
|
||||
// Linux Chromium is not mac: the example's Mod+Shift+I is Ctrl+Shift+I here.
|
||||
test.describe("Plugin shortcuts", () => {
|
||||
test("the example's keys open its screen, move the active list and submit the focused pane", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(180_000);
|
||||
const example = await installShortcutsExample(page);
|
||||
try {
|
||||
await test.step("Ctrl+Shift+I opens the Inbox from a workspace", async () => {
|
||||
await page.keyboard.press("Control+Shift+I");
|
||||
await expectInboxOpen(page);
|
||||
await expectSelection(page, "Open", "Approve the migration");
|
||||
});
|
||||
|
||||
await test.step("J moves the active list only", async () => {
|
||||
await page.keyboard.press("j");
|
||||
await expectSelection(page, "Open", "Merge the docs");
|
||||
|
||||
await activateList(page, "Done");
|
||||
await page.keyboard.press("j");
|
||||
await expectSelection(page, "Done", "Rename the CLI");
|
||||
await expectSelection(page, "Open", "Merge the docs");
|
||||
});
|
||||
|
||||
await test.step("typing j in the search field types it", async () => {
|
||||
await searchField(page).click();
|
||||
await page.keyboard.press("j");
|
||||
await expect(searchField(page)).toHaveValue("j");
|
||||
await expectSelection(page, "Done", "Rename the CLI");
|
||||
await searchField(page).fill("");
|
||||
});
|
||||
|
||||
await test.step("a dialog over the list stops K, and closing it gives K back", async () => {
|
||||
const dialog = await openHelpDialog(page);
|
||||
await page.keyboard.press("k");
|
||||
await expectSelection(page, "Done", "Rename the CLI");
|
||||
await closeDialogWithEscape(page, dialog);
|
||||
|
||||
await page.keyboard.press("k");
|
||||
await expectSelection(page, "Done", "Pick a logo");
|
||||
});
|
||||
|
||||
await test.step("a popover over the list takes J, and closing it gives J back", async () => {
|
||||
await openRecentDecisions(page);
|
||||
await page.keyboard.press("j");
|
||||
await expectSelection(page, "Recent", "Open the beta");
|
||||
await expectSelection(page, "Done", "Pick a logo");
|
||||
await closeRecentDecisions(page);
|
||||
|
||||
await page.keyboard.press("j");
|
||||
await expectSelection(page, "Done", "Rename the CLI");
|
||||
});
|
||||
|
||||
await test.step("the Next decision row in the Command Center moves the active list", async () => {
|
||||
await activateList(page, "Open");
|
||||
await (await findCommandCenterRow(page, "Next decision")).click();
|
||||
await expectSelection(page, "Open", "Ship the release");
|
||||
});
|
||||
|
||||
await test.step("the Command Center row and the popover badge show the keys", async () => {
|
||||
const row = await findCommandCenterRow(page, "Open Inbox");
|
||||
await expect(row).toContainText("Ctrl+Shift+I");
|
||||
await closeCommandCenter(page);
|
||||
|
||||
await openRecentDecisions(page);
|
||||
await expect(page.getByRole("button", { name: /^Open Inbox/ })).toContainText(
|
||||
"Ctrl+Shift+I",
|
||||
);
|
||||
await closeRecentDecisions(page);
|
||||
});
|
||||
|
||||
await test.step("Ctrl+Enter submits the decision in the focused pane only", async () => {
|
||||
await example.openWorkspace();
|
||||
await runCommand(page, "Compare decisions");
|
||||
await expectSubmitted(page, "Approve the migration", false);
|
||||
await expectSubmitted(page, "Ship the release", false);
|
||||
|
||||
await focusDecisionPane(page, "Ship the release");
|
||||
await page.keyboard.press("Control+Enter");
|
||||
await expectSubmitted(page, "Ship the release", true);
|
||||
await expectSubmitted(page, "Approve the migration", false);
|
||||
|
||||
await focusDecisionPane(page, "Approve the migration");
|
||||
await page.keyboard.press("Control+Enter");
|
||||
await expectSubmitted(page, "Approve the migration", true);
|
||||
});
|
||||
|
||||
await test.step("Settings lists the actions under the plugin's name, and a new key replaces the old", async () => {
|
||||
await openShortcutSettings(page);
|
||||
await expect(page.getByText(SHORTCUTS_PLUGIN_NAME, { exact: true })).toBeVisible();
|
||||
await expect(shortcutRow(page, "Open Inbox")).toContainText("Ctrl+Shift+I");
|
||||
await expect(shortcutRow(page, "Next decision")).toContainText("J");
|
||||
|
||||
await startRebinding(page, "Open Inbox");
|
||||
await pressCapturedKeys(page, "Control+Shift+U");
|
||||
await saveRebinding(page, "Open Inbox");
|
||||
await expect(shortcutRow(page, "Open Inbox")).toContainText("Ctrl+Shift+U");
|
||||
|
||||
await page.keyboard.press("Control+Shift+U");
|
||||
await expectInboxOpen(page);
|
||||
|
||||
const row = await findCommandCenterRow(page, "Open Inbox");
|
||||
await expect(row).toContainText("Ctrl+Shift+U");
|
||||
await closeCommandCenter(page);
|
||||
});
|
||||
} finally {
|
||||
await example.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("a plugin on two hosts has one Settings row and keeps its shortcut when one host goes offline", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(180_000);
|
||||
const hosts = await installShortcutsExampleOnTwoHosts(page);
|
||||
try {
|
||||
await test.step("Settings lists each action once", async () => {
|
||||
await openSettings(page);
|
||||
await openSettingsSection(page, "shortcuts");
|
||||
await expect(shortcutRow(page, "Open Inbox")).toHaveCount(1);
|
||||
await expect(shortcutRow(page, "Next decision")).toHaveCount(1);
|
||||
});
|
||||
|
||||
await test.step("Ctrl+Shift+I opens the Inbox, and the user moves it to Secondary", async () => {
|
||||
await page.keyboard.press("Control+Shift+I");
|
||||
await expect(decisionList(page, "Open")).toBeVisible();
|
||||
await showScreenOnHost(page, "Secondary");
|
||||
await expectInboxOpenOn(page, hosts.secondaryServerId);
|
||||
});
|
||||
|
||||
await test.step("with Secondary offline, Ctrl+Shift+I opens the Inbox on Primary", async () => {
|
||||
await hosts.disconnectSecondary();
|
||||
await page.keyboard.press("Control+Shift+I");
|
||||
await expectInboxOpenOn(page, hosts.primaryServerId);
|
||||
});
|
||||
} finally {
|
||||
await hosts.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -326,7 +326,7 @@ test("sidebar Add host preserves its caller and stays closed after theme changes
|
||||
|
||||
async function openSidebarAddHost(page: import("@playwright/test").Page) {
|
||||
await page.getByRole("button", { name: "Hosts", exact: true }).click();
|
||||
await page.getByRole("button", { name: "Add host", exact: true }).click();
|
||||
await page.getByRole("option", { name: "Add host", exact: true }).click();
|
||||
await expect(page.getByRole("button", { name: "Direct connection", exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
@@ -400,7 +400,7 @@ test("New workspace Add host preserves the prompt after connecting", async ({ pa
|
||||
|
||||
async function openNewWorkspaceAddHost(page: import("@playwright/test").Page) {
|
||||
await page.getByTestId("host-picker-trigger").click();
|
||||
await page.getByRole("button", { name: "Add host", exact: true }).click();
|
||||
await page.getByRole("option", { name: "Add host", exact: true }).click();
|
||||
}
|
||||
|
||||
async function connectToTestHost(page: import("@playwright/test").Page) {
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import {
|
||||
cancelRebinding,
|
||||
openShortcutSettings,
|
||||
pressCapturedKeys,
|
||||
saveRebinding,
|
||||
shortcutRow,
|
||||
startRebinding,
|
||||
} from "../support/helpers/shortcut-settings";
|
||||
|
||||
// Linux Chromium is not mac: Toggle command center is Ctrl+K, and Toggle
|
||||
// Explorer sidebar has a row for Ctrl+E and another for its alternate, Ctrl+`.
|
||||
const COMMAND_CENTER = "Toggle command center";
|
||||
const EXPLORER_SIDEBAR = "Toggle Explorer sidebar";
|
||||
const MODE_CYCLE = "Cycle agent mode";
|
||||
|
||||
function explorerBackquoteRow(page: Page) {
|
||||
return shortcutRow(page, EXPLORER_SIDEBAR).filter({ hasText: "`" });
|
||||
}
|
||||
|
||||
test.describe("Settings → Shortcuts capture", () => {
|
||||
test("refuses a key that can never fire, warns on a collision and lets the user's choice win", async ({
|
||||
page,
|
||||
}) => {
|
||||
await openShortcutSettings(page);
|
||||
|
||||
await test.step("refuses a plain key for a shortcut that only works while typing", async () => {
|
||||
await startRebinding(page, MODE_CYCLE);
|
||||
await pressCapturedKeys(page, "Shift+M");
|
||||
|
||||
const row = shortcutRow(page, MODE_CYCLE);
|
||||
await expect(row.getByRole("alert")).toHaveText(
|
||||
"This shortcut works while typing, so it needs Ctrl, Cmd or Alt.",
|
||||
);
|
||||
await expect(row.getByText("End with a number from 1 to 9.")).toBeHidden();
|
||||
await expect(row.getByRole("button", { name: "Done" })).toBeDisabled();
|
||||
|
||||
await pressCapturedKeys(page, "Backspace", "Control+M");
|
||||
await expect(row.getByRole("alert")).toBeHidden();
|
||||
await expect(row.getByRole("button", { name: "Done" })).toBeEnabled();
|
||||
|
||||
await cancelRebinding(page, MODE_CYCLE);
|
||||
await expect(row.getByText("Press shortcut...")).toBeHidden();
|
||||
});
|
||||
|
||||
await test.step("warns on a collision on both rows and still saves", async () => {
|
||||
await startRebinding(page, COMMAND_CENTER);
|
||||
await pressCapturedKeys(page, "Control+Backquote");
|
||||
await expect(shortcutRow(page, COMMAND_CENTER)).toContainText(
|
||||
`Also used by ${EXPLORER_SIDEBAR}`,
|
||||
);
|
||||
await saveRebinding(page, COMMAND_CENTER);
|
||||
|
||||
await expect(shortcutRow(page, COMMAND_CENTER)).toContainText(
|
||||
`Also used by ${EXPLORER_SIDEBAR}`,
|
||||
);
|
||||
await expect(shortcutRow(page, EXPLORER_SIDEBAR)).toHaveCount(2);
|
||||
await expect(
|
||||
page.getByRole("button", { name: `Actions for ${EXPLORER_SIDEBAR} (1/2, Ctrl+E)` }),
|
||||
).toBeVisible();
|
||||
await expect(
|
||||
page.getByRole("button", { name: `Actions for ${EXPLORER_SIDEBAR} (2/2, Ctrl+\`)` }),
|
||||
).toBeVisible();
|
||||
await expect(explorerBackquoteRow(page)).toContainText(`Also used by ${COMMAND_CENTER}`);
|
||||
await expect(
|
||||
shortcutRow(page, EXPLORER_SIDEBAR).filter({ hasNotText: "`" }),
|
||||
).not.toContainText("Also used by");
|
||||
});
|
||||
|
||||
await test.step("runs the user's shortcut, not the default it shares keys with", async () => {
|
||||
await page.keyboard.press("Control+Backquote");
|
||||
|
||||
await expect(page.getByTestId("command-center-panel")).toBeVisible();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -94,26 +94,46 @@ test("switches workspaces by visit MRU with fast tap-release, hold cycling, Esc
|
||||
betaId,
|
||||
alphaId,
|
||||
]);
|
||||
await expect(
|
||||
hud.getByTestId(`workspace-switcher-row-${serverId}:${gammaId}`),
|
||||
).toHaveAttribute("aria-selected", "true");
|
||||
await expect(hud).toHaveAttribute("tabindex", "-1");
|
||||
await expect(hud).toBeFocused();
|
||||
await expect(hud).toHaveCSS("outline-style", "none");
|
||||
const row0 = hud.getByTestId(`workspace-switcher-row-${serverId}:${deltaId}`);
|
||||
const gammaRow = hud.getByTestId(`workspace-switcher-row-${serverId}:${gammaId}`);
|
||||
const betaRow = hud.getByTestId(`workspace-switcher-row-${serverId}:${betaId}`);
|
||||
const alphaRow = hud.getByTestId(`workspace-switcher-row-${serverId}:${alphaId}`);
|
||||
await expect(row0).toHaveAttribute("tabindex", "-1");
|
||||
await expect(row0).toHaveCSS("outline-style", "none");
|
||||
await expect(gammaRow).toHaveAttribute("aria-selected", "true");
|
||||
await expect(hud).toHaveAttribute(
|
||||
"aria-activedescendant",
|
||||
(await gammaRow.getAttribute("id"))!,
|
||||
);
|
||||
|
||||
await page.keyboard.press("Tab");
|
||||
await expect(
|
||||
hud.getByTestId(`workspace-switcher-row-${serverId}:${betaId}`),
|
||||
).toHaveAttribute("aria-selected", "true");
|
||||
await expect(betaRow).toHaveAttribute("aria-selected", "true");
|
||||
await expect(hud).toBeFocused();
|
||||
await expect(hud).toHaveAttribute(
|
||||
"aria-activedescendant",
|
||||
(await betaRow.getAttribute("id"))!,
|
||||
);
|
||||
await expect(row0).toHaveCSS("outline-style", "none");
|
||||
await expect(betaRow).toHaveCSS("outline-style", "none");
|
||||
// Must not switch intermediate workspaces while stepping.
|
||||
await expect(page).toHaveURL(new RegExp(`/workspace/${deltaId}$`));
|
||||
|
||||
await page.keyboard.press("Tab");
|
||||
await expect(
|
||||
hud.getByTestId(`workspace-switcher-row-${serverId}:${alphaId}`),
|
||||
).toHaveAttribute("aria-selected", "true");
|
||||
await expect(alphaRow).toHaveAttribute("aria-selected", "true");
|
||||
await expect(hud).toHaveAttribute(
|
||||
"aria-activedescendant",
|
||||
(await alphaRow.getAttribute("id"))!,
|
||||
);
|
||||
|
||||
await page.keyboard.press("Shift+Tab");
|
||||
await expect(
|
||||
hud.getByTestId(`workspace-switcher-row-${serverId}:${betaId}`),
|
||||
).toHaveAttribute("aria-selected", "true");
|
||||
await expect(betaRow).toHaveAttribute("aria-selected", "true");
|
||||
await expect(hud).toHaveAttribute(
|
||||
"aria-activedescendant",
|
||||
(await betaRow.getAttribute("id"))!,
|
||||
);
|
||||
} finally {
|
||||
await page.keyboard.up("Alt");
|
||||
}
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
import { test } from "../support/fixtures";
|
||||
import {
|
||||
createWorkspaceTabs,
|
||||
expectSelectedWorkspaceTabInView,
|
||||
openOverflowingWorkspaceTabs,
|
||||
openWorkspaceTabTarget,
|
||||
panWorkspaceTabsWithWheel,
|
||||
selectFirstWorkspaceTab,
|
||||
switchWorkspaceTab,
|
||||
} from "../support/helpers/workspace-tabs-wheel-scroll";
|
||||
|
||||
test("a vertical mouse wheel pans the overflowing workspace tab strip", async ({
|
||||
@@ -12,3 +17,39 @@ test("a vertical mouse wheel pans the overflowing workspace tab strip", async ({
|
||||
await openOverflowingWorkspaceTabs(page, workspace);
|
||||
await panWorkspaceTabsWithWheel(page);
|
||||
});
|
||||
|
||||
test("the active workspace tab stays in view as tabs are opened and switched", async ({
|
||||
page,
|
||||
withWorkspace,
|
||||
}) => {
|
||||
const workspace = await withWorkspace({ prefix: "workspace-tabs-active-" });
|
||||
await page.setViewportSize({ width: 1100, height: 800 });
|
||||
await workspace.navigateTo();
|
||||
await openWorkspaceTabTarget(page, "Diff");
|
||||
|
||||
await test.step("reveal a new tab and the draft that replaces it", async () => {
|
||||
await createWorkspaceTabs(page, 15);
|
||||
await expectSelectedWorkspaceTabInView(page, { index: 15, count: 16, label: "New tab" });
|
||||
await openWorkspaceTabTarget(page, "Agent");
|
||||
await expectSelectedWorkspaceTabInView(page, { index: 15, count: 16, label: "New Agent" });
|
||||
});
|
||||
|
||||
await test.step("wrap from Diff to New Agent and back", async () => {
|
||||
await selectFirstWorkspaceTab(page);
|
||||
await switchWorkspaceTab(page, "previous");
|
||||
await expectSelectedWorkspaceTabInView(page, { index: 15, count: 16, label: "New Agent" });
|
||||
await switchWorkspaceTab(page, "next");
|
||||
await expectSelectedWorkspaceTabInView(page, { index: 0, count: 16, label: "Diff" });
|
||||
});
|
||||
|
||||
await test.step("step forward past the right edge of the strip", async () => {
|
||||
await switchWorkspaceTab(page, "next", 8);
|
||||
await expectSelectedWorkspaceTabInView(page, { index: 8, count: 16, label: "New tab" });
|
||||
});
|
||||
|
||||
await test.step("reveal a new tab in a narrower desktop window", async () => {
|
||||
await page.setViewportSize({ width: 860, height: 800 });
|
||||
await createWorkspaceTabs(page, 1);
|
||||
await expectSelectedWorkspaceTabInView(page, { index: 16, count: 17, label: "New tab" });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -274,7 +274,7 @@ async function chooseSelectFieldOption(
|
||||
await editSurface(page).getByTestId(`agent-profile-${input.field}-trigger`).click();
|
||||
const option = page
|
||||
.getByTestId("combobox-desktop-container")
|
||||
.getByRole("button", { name: input.option, exact: true });
|
||||
.getByRole("option", { name: input.option, exact: true });
|
||||
await expect(option).toBeVisible({ timeout: 30_000 });
|
||||
await option.click();
|
||||
}
|
||||
|
||||
@@ -404,7 +404,7 @@ export const selectMode = async (page: Page, mode: string) => {
|
||||
}
|
||||
|
||||
// Wait for the mode dropdown to open
|
||||
const searchInput = page.getByRole("textbox", { name: /search mode/i });
|
||||
const searchInput = page.getByRole("combobox", { name: /search mode/i });
|
||||
await expect(searchInput).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// Type to filter modes
|
||||
|
||||
@@ -21,6 +21,21 @@ export async function openCommandCenterWithShortcut(page: Page): Promise<void> {
|
||||
await expect(page.getByTestId("command-center-panel")).toBeVisible();
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the Command Center with its keys, so the screen beneath keeps its focus, and runs the row
|
||||
* whose title starts with `title`.
|
||||
*/
|
||||
export async function runCommandCenterItem(page: Page, title: string): Promise<void> {
|
||||
await openCommandCenterWithShortcut(page);
|
||||
const panel = page.getByTestId("command-center-panel");
|
||||
await panel.getByTestId("command-center-input").fill(title);
|
||||
await panel
|
||||
.getByRole("button", { name: new RegExp(`^${title}`) })
|
||||
.first()
|
||||
.click();
|
||||
await expect(panel).not.toBeVisible();
|
||||
}
|
||||
|
||||
export async function closeCommandCenter(page: Page): Promise<void> {
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(page.getByTestId("command-center-panel")).not.toBeVisible();
|
||||
@@ -93,6 +108,33 @@ export async function exitCommandCenterSublist(panel: Locator, title: string): P
|
||||
await expectCommandCenterTab(panel, "All");
|
||||
}
|
||||
|
||||
export async function enterChangeThemeSublist(panel: Locator): Promise<void> {
|
||||
await enterCommandCenterSublist(panel, "Change theme", "Search themes...");
|
||||
}
|
||||
|
||||
export async function expectCommandCenterThemeSelected(
|
||||
panel: Locator,
|
||||
themeName: string,
|
||||
): Promise<void> {
|
||||
await expect(panel.getByRole("button", { name: themeName, exact: true })).toHaveAttribute(
|
||||
"aria-pressed",
|
||||
"true",
|
||||
);
|
||||
}
|
||||
|
||||
export async function switchThemeViaCommandCenter(
|
||||
page: Page,
|
||||
query: string,
|
||||
themeName: string,
|
||||
): Promise<void> {
|
||||
const panel = await openCommandCenter(page);
|
||||
await enterChangeThemeSublist(panel);
|
||||
await panel.getByTestId("command-center-input").fill(query);
|
||||
await expect(panel.getByRole("button", { name: themeName, exact: true })).toBeVisible();
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(panel).not.toBeVisible();
|
||||
}
|
||||
|
||||
export function commandCenterSection(panel: Locator, title: string): Locator {
|
||||
return panel.getByTestId("command-center-results").getByText(title, { exact: true });
|
||||
}
|
||||
|
||||
@@ -226,7 +226,7 @@ export class ImportSessionFlow {
|
||||
const panel = await openCommandCenter(this.page);
|
||||
await panel.getByTestId("command-center-input").fill("import");
|
||||
await panel.getByText("Import session", { exact: true }).click();
|
||||
await this.page.getByRole("dialog").getByRole("button", { name: hostLabel }).click();
|
||||
await this.page.getByRole("dialog").getByRole("option", { name: hostLabel }).click();
|
||||
await this.expectScope(`Sessions on ${hostLabel}`);
|
||||
}
|
||||
async expectCommandCenterMatch() {
|
||||
|
||||
@@ -301,7 +301,7 @@ export async function expectNewWorkspaceDraft(page: Page, draft: string): Promis
|
||||
export async function selectNewWorkspaceHost(page: Page, hostLabel: string): Promise<void> {
|
||||
const trigger = page.getByTestId("host-picker-trigger");
|
||||
await trigger.click();
|
||||
await page.getByRole("button", { name: hostLabel, exact: true }).click();
|
||||
await page.getByRole("option", { name: hostLabel, exact: true }).click();
|
||||
await expect(trigger).toContainText(hostLabel);
|
||||
}
|
||||
|
||||
@@ -415,7 +415,7 @@ export async function searchAndSelectBranchInPicker(page: Page, name: string): P
|
||||
// Ref picker rows are named for a user: "main, origin branch" is the upstream copy and
|
||||
// "main, local branch, 2 commits ahead of origin main" is the local one.
|
||||
export function startingRefRow(page: Page, accessibleName: string) {
|
||||
return page.getByRole("button", { name: accessibleName, exact: true });
|
||||
return page.getByRole("option", { name: accessibleName, exact: true });
|
||||
}
|
||||
|
||||
export async function expectStartingRefRows(page: Page, accessibleNames: string[]): Promise<void> {
|
||||
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
selectInstalledTab,
|
||||
selectPluginPageAction,
|
||||
} from "./plugin-gallery";
|
||||
import { openHostSection, selectSettingsHost } from "./settings";
|
||||
import { openHostSection, openSettingsSection, selectSettingsHost } from "./settings";
|
||||
import { startHostDaemon } from "./versioned-host-daemon";
|
||||
|
||||
/**
|
||||
@@ -220,10 +220,16 @@ function createRelatedFixtures(date: string) {
|
||||
});
|
||||
}
|
||||
|
||||
const PNG_1X1 = Buffer.from(
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=",
|
||||
"base64",
|
||||
);
|
||||
|
||||
async function startRegistry(listing: Record<string, unknown>) {
|
||||
const date = "2026-10-03T00:00:00.000Z";
|
||||
const commit = (listing.artifact as { commit: string }).commit;
|
||||
const related = createRelatedFixtures(date);
|
||||
const prRadar = related.find((entry) => entry.id === "acme/pr-radar")!;
|
||||
const detailDocument = {
|
||||
...listing,
|
||||
readme: `# ${LISTING.name}\n\n${LISTING.overview}\n\n## Capabilities\n\n- Adds a lightweight review checklist panel to every workspace.\n- Works across Desktop, Web, and Mobile without extra setup.`,
|
||||
@@ -311,7 +317,7 @@ async function startRegistry(listing: Record<string, unknown>) {
|
||||
registry: { name: "Local", url: "http://127.0.0.1" },
|
||||
categories: [{ slug: "tools", label: "Tools" }],
|
||||
plugins: [listing, ...related],
|
||||
featured: [],
|
||||
featured: ["acme/pr-radar"],
|
||||
generatedAt: date,
|
||||
},
|
||||
[`/plugins/${LISTING.id}.json`]: detailDocument,
|
||||
@@ -337,6 +343,10 @@ async function startRegistry(listing: Record<string, unknown>) {
|
||||
}
|
||||
};
|
||||
const server = createServer((request, response) => {
|
||||
if (request.url === "/media/en.png" || request.url === "/media/zh-CN.png") {
|
||||
response.writeHead(200, { "Content-Type": "image/png" }).end(PNG_1X1);
|
||||
return;
|
||||
}
|
||||
const document = request.url ? documents[request.url] : undefined;
|
||||
if (!document) {
|
||||
response.writeHead(404).end();
|
||||
@@ -355,8 +365,16 @@ async function startRegistry(listing: Record<string, unknown>) {
|
||||
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 registry address");
|
||||
const origin = `http://127.0.0.1:${address.port}`;
|
||||
prRadar.media = [`${origin}/media/en.png`];
|
||||
prRadar.translations = {
|
||||
"zh-CN": { name: "PR 雷达", media: [`${origin}/media/zh-CN.png`] },
|
||||
};
|
||||
(documents["/plugins/acme/pr-radar.json"] as Record<string, unknown>).media = prRadar.media;
|
||||
(documents["/plugins/acme/pr-radar.json"] as Record<string, unknown>).translations =
|
||||
prRadar.translations;
|
||||
return {
|
||||
url: `http://127.0.0.1:${address.port}`,
|
||||
url: origin,
|
||||
setDetailDelayMs: (ms: number) => {
|
||||
detailDelayMs = ms;
|
||||
},
|
||||
@@ -676,3 +694,41 @@ export async function expectStackedFirstFrameOnNarrowDesktop(page: Page) {
|
||||
}
|
||||
assertOverviewNeverCollapsed(onPage, { minHeight: 80 });
|
||||
}
|
||||
|
||||
/** Verifies featured card and detail media strip switch screenshots with the app language. */
|
||||
export async function verifyLocalizedMediaInDirectory(
|
||||
page: Page,
|
||||
host: { serverId: string; port: number },
|
||||
) {
|
||||
await openDirectory(page, host);
|
||||
const enCard = page.getByTestId("plugin-featured-acme/pr-radar").filter({ visible: true });
|
||||
await expect(enCard.locator("img").first()).toHaveAttribute("src", /\/media\/en\.png$/);
|
||||
|
||||
await enCard.click();
|
||||
await expect(pluginPageName(page)).toHaveText("PR Radar");
|
||||
await expect(
|
||||
page.getByRole("button", { name: "Open image", exact: true }).locator("img"),
|
||||
).toHaveAttribute("src", /\/media\/en\.png$/);
|
||||
|
||||
await page
|
||||
.getByRole("button", { name: "Back to plugins", exact: true })
|
||||
.filter({ visible: true })
|
||||
.click();
|
||||
await openSettingsSection(page, "general");
|
||||
await page.getByRole("button", { name: "System", exact: true }).click();
|
||||
await page.getByRole("menuitem", { name: "简体中文 - Simplified Chinese", exact: true }).click();
|
||||
await expect(page.getByText("语言", { exact: true }).first()).toBeVisible();
|
||||
|
||||
await openHostSection(page, host.serverId, "plugins");
|
||||
await page.getByTestId("plugin-tab-browse").filter({ visible: true }).click();
|
||||
|
||||
const zhCard = page.getByTestId("plugin-featured-acme/pr-radar").filter({ visible: true });
|
||||
await expect(zhCard).toContainText("PR 雷达");
|
||||
await expect(zhCard.locator("img").first()).toHaveAttribute("src", /\/media\/zh-CN\.png$/);
|
||||
|
||||
await zhCard.click();
|
||||
await expect(pluginPageName(page)).toHaveText("PR 雷达");
|
||||
await expect(
|
||||
page.getByRole("button", { name: "打开图片", exact: true }).locator("img"),
|
||||
).toHaveAttribute("src", /\/media\/zh-CN\.png$/);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
import { expect, type Locator, type Page } from "@playwright/test";
|
||||
import { gotoAppShell } from "./app";
|
||||
import { openCommandCenter } from "./command-center";
|
||||
import { addConnectedHostAndReload } from "./hosts";
|
||||
import { startIsolatedHostDaemon } from "./isolated-host-daemon";
|
||||
import { seedMockAgentWorkspace, openAgentRoute } from "./mock-agent";
|
||||
import { connectNewWorkspaceDaemonClient } from "./new-workspace";
|
||||
import { approveClientPluginsInUi } from "./plugin-execution-approval";
|
||||
import { copyPluginExample } from "./plugin-fixture";
|
||||
import { getServerId } from "./server-id";
|
||||
import { selectWorkspaceInSidebar } from "./sidebar";
|
||||
|
||||
export const SHORTCUTS_PLUGIN = "shortcuts";
|
||||
export const SHORTCUTS_PLUGIN_NAME = "Shortcut examples";
|
||||
|
||||
/**
|
||||
* Installs `plugin-examples/shortcuts` on the worker's daemon, opens a workspace with an agent and
|
||||
* allows the plugin to run. The page stays on that workspace.
|
||||
*/
|
||||
export async function installShortcutsExample(page: Page) {
|
||||
const example = await copyPluginExample("shortcuts");
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "plugin-shortcuts-",
|
||||
title: "Shortcuts agent",
|
||||
});
|
||||
const client = await connectNewWorkspaceDaemonClient({ ownProjects: false });
|
||||
const previous = await client.getDaemonConfig();
|
||||
async function close() {
|
||||
await client.removePlugin(SHORTCUTS_PLUGIN).catch(() => undefined);
|
||||
await client.patchDaemonConfig({ pluginsEnabled: previous.config.pluginsEnabled ?? false });
|
||||
await client.close();
|
||||
await workspace.cleanup();
|
||||
await example.cleanup();
|
||||
}
|
||||
try {
|
||||
await client.patchDaemonConfig({ pluginsEnabled: true });
|
||||
await client.installDirectoryPlugin(example.directory);
|
||||
await page.setViewportSize({ width: 1600, height: 900 });
|
||||
await openAgentRoute(page, workspace);
|
||||
await approveClientPluginsInUi(page, [SHORTCUTS_PLUGIN]);
|
||||
// Shortcut badges show once a hardware keyboard has been seen.
|
||||
await page.keyboard.press("Shift");
|
||||
} catch (error) {
|
||||
await close();
|
||||
throw error;
|
||||
}
|
||||
return {
|
||||
close,
|
||||
/** Opens the seeded workspace from the sidebar. */
|
||||
openWorkspace: () => selectWorkspaceInSidebar(page, workspace.workspaceId),
|
||||
};
|
||||
}
|
||||
|
||||
export function decisionList(page: Page, title: string): Locator {
|
||||
return page.getByText(new RegExp(`^${title} selection: `)).filter({ visible: true });
|
||||
}
|
||||
|
||||
export async function expectSelection(page: Page, list: string, decision: string): Promise<void> {
|
||||
await expect(decisionList(page, list)).toHaveText(`${list} selection: ${decision}`);
|
||||
}
|
||||
|
||||
export async function expectInboxOpen(page: Page): Promise<void> {
|
||||
await expect(page).toHaveURL(/\/plugin\/shortcuts\/surface\/inbox/);
|
||||
await expect(decisionList(page, "Open")).toBeVisible();
|
||||
}
|
||||
|
||||
/** Makes a list on the Inbox the active one by pressing its title. */
|
||||
export async function activateList(page: Page, list: string): Promise<void> {
|
||||
await page.getByRole("button", { name: list, exact: true }).click();
|
||||
await expect(page.getByText(`${list} (active)`, { exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
export function searchField(page: Page): Locator {
|
||||
return page.getByRole("textbox", { name: "Search decisions" });
|
||||
}
|
||||
|
||||
export async function openHelpDialog(page: Page): Promise<Locator> {
|
||||
await page.getByRole("button", { name: "How to decide", exact: true }).click();
|
||||
const dialog = page.getByRole("dialog").filter({ hasText: "How to decide" });
|
||||
await expect(dialog).toBeVisible();
|
||||
return dialog;
|
||||
}
|
||||
|
||||
export async function closeDialogWithEscape(page: Page, dialog: Locator): Promise<void> {
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(dialog).toBeHidden();
|
||||
}
|
||||
|
||||
export async function openRecentDecisions(page: Page): Promise<void> {
|
||||
await page.getByRole("button", { name: "Recent decisions", exact: true }).click();
|
||||
await expect(decisionList(page, "Recent")).toBeVisible();
|
||||
}
|
||||
|
||||
export async function closeRecentDecisions(page: Page): Promise<void> {
|
||||
await page.getByRole("button", { name: "Close", exact: true }).click();
|
||||
await expect(decisionList(page, "Recent")).toBeHidden();
|
||||
}
|
||||
|
||||
/** The Command Center row for `title`, searched for and left open. */
|
||||
export async function findCommandCenterRow(page: Page, title: string): Promise<Locator> {
|
||||
const panel = await openCommandCenter(page);
|
||||
await panel.getByTestId("command-center-input").fill(title);
|
||||
const row = panel.getByRole("button", { name: new RegExp(`^${title}`) });
|
||||
await expect(row).toBeVisible();
|
||||
return row;
|
||||
}
|
||||
|
||||
export function decisionPanel(page: Page, decision: string): Locator {
|
||||
return page
|
||||
.getByTestId(/^workspace-pane-/)
|
||||
.filter({ has: page.getByText(decision, { exact: true }) })
|
||||
.filter({ visible: true });
|
||||
}
|
||||
|
||||
export async function expectSubmitted(page: Page, decision: string, submitted: boolean) {
|
||||
const status = decisionPanel(page, decision).getByText(
|
||||
submitted ? `Submitted: ${decision}` : "Not submitted",
|
||||
{ exact: true },
|
||||
);
|
||||
await expect(status).toBeVisible();
|
||||
}
|
||||
|
||||
/** Focuses the pane that shows `decision` by clicking its submit status. */
|
||||
export async function focusDecisionPane(page: Page, decision: string): Promise<void> {
|
||||
await decisionPanel(page, decision)
|
||||
.getByText(/^(Not submitted|Submitted: .*)$/)
|
||||
.click();
|
||||
}
|
||||
|
||||
/**
|
||||
* Installs `plugin-examples/shortcuts` on the worker's daemon ("Primary") and on a second daemon
|
||||
* ("Secondary"), connects the app to both and allows the plugin on each.
|
||||
*/
|
||||
export async function installShortcutsExampleOnTwoHosts(page: Page) {
|
||||
const example = await copyPluginExample("shortcuts");
|
||||
const primary = await connectNewWorkspaceDaemonClient({ ownProjects: false });
|
||||
const secondary = await startIsolatedHostDaemon("plugin-shortcuts-secondary");
|
||||
const remote = await connectNewWorkspaceDaemonClient({
|
||||
port: secondary.port,
|
||||
ownProjects: false,
|
||||
});
|
||||
const previous = await primary.getDaemonConfig();
|
||||
async function close() {
|
||||
await remote.close().catch(() => undefined);
|
||||
await secondary.close();
|
||||
await primary.removePlugin(SHORTCUTS_PLUGIN).catch(() => undefined);
|
||||
await primary.patchDaemonConfig({ pluginsEnabled: previous.config.pluginsEnabled ?? false });
|
||||
await primary.close();
|
||||
await example.cleanup();
|
||||
}
|
||||
try {
|
||||
for (const client of [primary, remote]) {
|
||||
await client.patchDaemonConfig({ pluginsEnabled: true });
|
||||
await client.installDirectoryPlugin(example.directory);
|
||||
}
|
||||
await gotoAppShell(page);
|
||||
await addConnectedHostAndReload(page, {
|
||||
serverId: secondary.serverId,
|
||||
label: "Secondary",
|
||||
port: secondary.port,
|
||||
primaryLabel: "Primary",
|
||||
});
|
||||
// One prompt per host.
|
||||
await approveClientPluginsInUi(page, [SHORTCUTS_PLUGIN, SHORTCUTS_PLUGIN]);
|
||||
await page.keyboard.press("Shift");
|
||||
} catch (error) {
|
||||
await close();
|
||||
throw error;
|
||||
}
|
||||
return {
|
||||
primaryServerId: getServerId(),
|
||||
secondaryServerId: secondary.serverId,
|
||||
close,
|
||||
async disconnectSecondary() {
|
||||
await secondary.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function expectInboxOpenOn(page: Page, serverId: string): Promise<void> {
|
||||
await expect(page).toHaveURL(new RegExp(`/h/${serverId}/plugin/shortcuts/surface/inbox`));
|
||||
await expect(decisionList(page, "Open")).toBeVisible();
|
||||
}
|
||||
|
||||
/** Picks the host the open plugin screen shows, with the host filter in its header. */
|
||||
export async function showScreenOnHost(page: Page, label: string): Promise<void> {
|
||||
await page.getByRole("button", { name: /^Filter: / }).click();
|
||||
await page.getByRole("option", { name: new RegExp(`^${label}`) }).click();
|
||||
}
|
||||
@@ -80,7 +80,7 @@ export async function beginWorkspaceFromProject(page: Page, projectName: string)
|
||||
|
||||
export async function selectWorkspaceHost(page: Page, hostName: string): Promise<void> {
|
||||
await page.getByRole("button", { name: "Host", exact: true }).click();
|
||||
await page.getByRole("button", { name: hostName, exact: true }).click();
|
||||
await page.getByRole("option", { name: hostName, exact: true }).click();
|
||||
await expect(page.getByRole("button", { name: "Host", exact: true })).toContainText(hostName);
|
||||
}
|
||||
|
||||
|
||||
@@ -36,7 +36,11 @@ export async function bindCommandCenterToEnter(page: Page) {
|
||||
export async function activateSidebarHostSettingsWithKeyboard(page: Page) {
|
||||
const host = sidebarHostRowButton(page);
|
||||
await expect(host).toBeVisible();
|
||||
await expect(host).toBeFocused();
|
||||
const popup = page.getByTestId("combobox-desktop-container");
|
||||
await expect(popup).toBeFocused();
|
||||
const hostId = await host.getAttribute("id");
|
||||
expect(hostId).toBeTruthy();
|
||||
await expect(popup).toHaveAttribute("aria-activedescendant", hostId!);
|
||||
await page.keyboard.press("Enter");
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { expect, type Locator, type Page } from "@playwright/test";
|
||||
import { gotoAppShell, openSettings } from "./app";
|
||||
import { openSettingsSection } from "./settings";
|
||||
|
||||
/** Settings → Shortcuts, opened through the sidebar like a user would. */
|
||||
export async function openShortcutSettings(page: Page): Promise<void> {
|
||||
await gotoAppShell(page);
|
||||
await expect(page.getByTestId("sidebar-search")).toBeVisible({ timeout: 30_000 });
|
||||
// A hardware keyboard has to be detected before Settings lists shortcuts.
|
||||
await page.keyboard.press("Shift");
|
||||
await openSettings(page);
|
||||
await openSettingsSection(page, "shortcuts");
|
||||
}
|
||||
|
||||
export function shortcutRow(page: Page, action: string): Locator {
|
||||
return page
|
||||
.getByTestId(/^shortcut-row-/)
|
||||
.filter({ has: page.getByText(action, { exact: true }) });
|
||||
}
|
||||
|
||||
export async function startRebinding(page: Page, action: string): Promise<void> {
|
||||
await page.getByRole("button", { name: `Actions for ${action}` }).click();
|
||||
await page.getByTestId(/^shortcut-bind-/).click();
|
||||
await expect(shortcutRow(page, action).getByText("Press shortcut...")).toBeVisible();
|
||||
}
|
||||
|
||||
export async function pressCapturedKeys(page: Page, ...keys: string[]): Promise<void> {
|
||||
for (const key of keys) {
|
||||
await page.keyboard.press(key);
|
||||
}
|
||||
}
|
||||
|
||||
export async function saveRebinding(page: Page, action: string): Promise<void> {
|
||||
await shortcutRow(page, action).getByRole("button", { name: "Done" }).click();
|
||||
}
|
||||
|
||||
export async function cancelRebinding(page: Page, action: string): Promise<void> {
|
||||
await shortcutRow(page, action).getByRole("button", { name: "Cancel" }).click();
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, type Page } from "@playwright/test";
|
||||
import { pressNewTabShortcut } from "./launcher";
|
||||
import { panWorkspaceTabsWithWheel } from "./workspace-tabs";
|
||||
import type { CreatedWorkspace } from "./with-workspace";
|
||||
@@ -14,9 +14,51 @@ export async function openOverflowingWorkspaceTabs(
|
||||
await page.setViewportSize(OVERFLOWING_TABS_VIEWPORT);
|
||||
await workspace.navigateTo();
|
||||
|
||||
for (let index = 0; index < OVERFLOWING_TABS_COUNT; index += 1) {
|
||||
await createWorkspaceTabs(page, OVERFLOWING_TABS_COUNT);
|
||||
}
|
||||
|
||||
export async function createWorkspaceTabs(page: Page, count: number) {
|
||||
for (let index = 0; index < count; index += 1) {
|
||||
await pressNewTabShortcut(page);
|
||||
}
|
||||
}
|
||||
|
||||
export { panWorkspaceTabsWithWheel };
|
||||
|
||||
function workspaceTabs(page: Page) {
|
||||
return page
|
||||
.getByTestId("workspace-tabs-scroll")
|
||||
.getByRole("button")
|
||||
.and(page.locator("[aria-selected]"));
|
||||
}
|
||||
|
||||
export async function openWorkspaceTabTarget(page: Page, target: "Diff" | "Agent") {
|
||||
await page
|
||||
.getByTestId("workspace-new-tab-panel")
|
||||
.filter({ visible: true })
|
||||
.getByRole("button", { name: target, exact: true })
|
||||
.click();
|
||||
}
|
||||
|
||||
export async function selectFirstWorkspaceTab(page: Page) {
|
||||
await workspaceTabs(page).first().click();
|
||||
}
|
||||
|
||||
export async function switchWorkspaceTab(page: Page, direction: "previous" | "next", steps = 1) {
|
||||
const shortcut = direction === "previous" ? "Alt+Shift+BracketLeft" : "Alt+Shift+BracketRight";
|
||||
for (let step = 0; step < steps; step += 1) {
|
||||
await page.keyboard.press(shortcut);
|
||||
}
|
||||
}
|
||||
|
||||
export async function expectSelectedWorkspaceTabInView(
|
||||
page: Page,
|
||||
{ index, count, label }: { index: number; count: number; label: string },
|
||||
) {
|
||||
const tabs = workspaceTabs(page);
|
||||
await expect(tabs).toHaveCount(count);
|
||||
const tab = tabs.nth(index);
|
||||
await expect(tab).toHaveText(label);
|
||||
await expect(tab).toHaveAttribute("aria-selected", "true");
|
||||
await expect.soft(tab).toBeInViewport({ ratio: 0.99, timeout: 3_000 });
|
||||
}
|
||||
|
||||
@@ -233,9 +233,10 @@ export async function panWorkspaceTabsWithWheel(page: Page): Promise<void> {
|
||||
const overflow = () => strip.evaluate((element) => element.scrollWidth - element.clientWidth);
|
||||
const scrollLeft = () => strip.evaluate((element) => element.scrollLeft);
|
||||
await expect.poll(overflow).toBeGreaterThan(0);
|
||||
expect(await scrollLeft()).toBe(0);
|
||||
|
||||
await strip.hover();
|
||||
await page.mouse.wheel(0, -(await strip.evaluate((element) => element.scrollWidth)));
|
||||
await expect.poll(scrollLeft).toBe(0);
|
||||
|
||||
await page.mouse.wheel(0, 200);
|
||||
await expect.poll(scrollLeft).toBeGreaterThan(0);
|
||||
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
node_modules/
|
||||
desktop/build/
|
||||
desktop/autolink/
|
||||
@@ -0,0 +1,3 @@
|
||||
workspaces=false
|
||||
legacy-peer-deps=true
|
||||
install-links=true
|
||||
@@ -0,0 +1,316 @@
|
||||
# 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 JavaScript bundle (`paseo.bundle`)
|
||||
executed by V8 14.6 (`@react-native-gpui/v8`); Fast Refresh is not wired
|
||||
into this launcher. `build:gpui` builds without opening a window.
|
||||
`gpui:bundle -- --dev false` writes the bundle to `.artifacts/gpui/`: the
|
||||
JS source (`paseo.bundle`), its source map, and assets. 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 V8/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,v8}` and the seven `@react-native-gpui/*` modules (Hermes stays installed for `@react-native-gpui/worklets` headers while V8 14.6 is the active JS engine). |
|
||||
| `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,v8}` 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. Prebuilt V8 binaries (`libv8.so` / `libv8.dylib` and headers) are fetched and SHA-256 verified by `@react-native-gpui/v8/scripts/fetch-binaries.mjs`, and the C++ runtime is built or fetched when needed.
|
||||
|
||||
## 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 default native
|
||||
regression restores existing drafts and does not send a message (an opt-in
|
||||
Enter-to-send check sends a disposable test message when
|
||||
`PASEO_GPUI_TEST_ALLOW_SEND=1` is set). 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 | `surface.gpui.tsx` lays diff lines out with React Native views and text. No inline review, drag selection, or scroll-to-file 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. The default suite restores drafts and
|
||||
sends no messages; to include the Enter-to-send test (which clears the composer
|
||||
and sends `GPUI Enter <timestamp>\nline2` to the first workspace), run against a
|
||||
disposable workspace and session with `PASEO_GPUI_TEST_ALLOW_SEND=1`. 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/`.
|
||||
|
||||
### Runtime globals and the relay regression
|
||||
|
||||
V8 gives the app no web platform beyond the language: no `atob`, `btoa`,
|
||||
`TextEncoder`, `TextDecoder` or `DOMException`, and React Native's `URL` is a stub
|
||||
(its `hostname` is empty). Shared code reads all of them while it parses a
|
||||
pairing link and opens a relay session. They are installed by `bootstrap.js`,
|
||||
which `index.js` and every native fixture import first: `adapters/text-encoding.js`
|
||||
before `adapters/web-globals.js`, because the URL implementation reads
|
||||
`TextEncoder` while it loads. Add a missing global there, not behind a platform
|
||||
check in `packages/app/src`.
|
||||
|
||||
`relay.native.test.ts` runs the real `HostRuntimeStore` inside the V8 binary.
|
||||
It imports a pairing link, confirms the new host, completes the E2EE handshake
|
||||
with a fake relay and daemon (protected and legacy endpoint security), sends an
|
||||
encrypted `ping` and reads the `pong`, then boots a second store from the saved
|
||||
registry and does it again. It needs the same executable and display as the
|
||||
WebSocket test, and no daemon:
|
||||
|
||||
```sh
|
||||
PASEO_GPUI_TEST_BINARY="/absolute/path/to/react-native-gpui-paseo-gpui" \
|
||||
npx vitest run packages/app/gpui/relay.native.test.ts --bail=1
|
||||
```
|
||||
|
||||
The first run bundles the whole app and takes several minutes. In tests in this
|
||||
directory `ws` resolves to React Native's 6.x, which has no `isBinary` argument.
|
||||
@@ -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;
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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();
|
||||
@@ -0,0 +1,241 @@
|
||||
const pathOf = (value) => String(value?.uri ?? value).replace(/^file:\/\//, "");
|
||||
const join = (parts) =>
|
||||
parts
|
||||
.map(pathOf)
|
||||
.join("/")
|
||||
.replace(/\/{2,}/g, "/");
|
||||
|
||||
function parentDir(filePath) {
|
||||
const index = filePath.lastIndexOf("/");
|
||||
return index > 0 ? filePath.slice(0, index) : "";
|
||||
}
|
||||
|
||||
export function createFileSystem({ fs, promises, paths }) {
|
||||
let nextDownloadPartId = 0;
|
||||
|
||||
function ensureParentSync(targetPath) {
|
||||
const dir = parentDir(targetPath);
|
||||
if (dir) fs.mkdirSync(dir, { recursive: true });
|
||||
}
|
||||
|
||||
function reserveExclusiveSync(targetPath) {
|
||||
ensureParentSync(targetPath);
|
||||
try {
|
||||
fs.writeFileSync(targetPath, "", { flag: "wx" });
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (error?.code === "EEXIST") return false;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureParentAsync(targetPath) {
|
||||
const dir = parentDir(targetPath);
|
||||
if (dir) await promises.mkdir(dir, { recursive: true });
|
||||
}
|
||||
|
||||
const cacheDirectory = `file://${paths.appCache}/paseo-gpui/`;
|
||||
const documentDirectory = `file://${paths.appData}/paseo-gpui/`;
|
||||
const EncodingType = { Base64: "base64", UTF8: "utf8" };
|
||||
const Paths = { cache: cacheDirectory, document: documentDirectory };
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
const makeDirectoryAsync = (uri, options = {}) =>
|
||||
promises.mkdir(pathOf(uri), { recursive: options.intermediates });
|
||||
|
||||
const copyAsync = async ({ from, to }) => {
|
||||
const target = pathOf(to);
|
||||
await ensureParentAsync(target);
|
||||
return promises.copyFile(pathOf(from), target);
|
||||
};
|
||||
|
||||
const moveAsync = async ({ from, to }) => {
|
||||
const target = pathOf(to);
|
||||
await ensureParentAsync(target);
|
||||
return promises.rename(pathOf(from), target);
|
||||
};
|
||||
|
||||
const readAsStringAsync = (uri, options = {}) =>
|
||||
promises.readFile(pathOf(uri), options.encoding ?? "utf8");
|
||||
|
||||
const writeAsStringAsync = async (uri, contents, options = {}) => {
|
||||
const target = pathOf(uri);
|
||||
await ensureParentAsync(target);
|
||||
return promises.writeFile(target, contents, options.encoding ?? "utf8");
|
||||
};
|
||||
|
||||
const deleteAsync = (uri, options = {}) =>
|
||||
promises.rm(pathOf(uri), { recursive: true, force: options.idempotent });
|
||||
|
||||
const readDirectoryAsync = (uri) => promises.readdir(pathOf(uri));
|
||||
|
||||
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) ensureParentSync(pathOf(this));
|
||||
fs.writeFileSync(pathOf(this), "", { flag: overwrite ? "w" : "wx" });
|
||||
}
|
||||
write(value) {
|
||||
const target = pathOf(this);
|
||||
ensureParentSync(target);
|
||||
fs.writeFileSync(target, 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) {
|
||||
const target = pathOf(destination);
|
||||
ensureParentSync(target);
|
||||
fs.renameSync(pathOf(this), target);
|
||||
this.uri = destination.uri;
|
||||
}
|
||||
copy(destination) {
|
||||
const target = pathOf(destination);
|
||||
ensureParentSync(target);
|
||||
fs.copyFileSync(pathOf(this), target);
|
||||
}
|
||||
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);
|
||||
const target = pathOf(file);
|
||||
await ensureParentAsync(target);
|
||||
await promises.writeFile(target, new Uint8Array(await response.arrayBuffer()));
|
||||
return file;
|
||||
}
|
||||
}
|
||||
|
||||
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),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const stagingDirectory = `${paths.appCache}/paseo-gpui-staging`;
|
||||
|
||||
function createDownloadResumable(url, uri, options = {}, onProgress) {
|
||||
const controller = new AbortController();
|
||||
const target = pathOf(uri);
|
||||
// Reserve the cache slot synchronously before awaiting fetch so concurrent downloads
|
||||
// picking unused filenames with `File.exists` never collide on the same target path.
|
||||
const reservedTarget = reserveExclusiveSync(target);
|
||||
// Stage in a private sibling directory with a short synthetic name so staging never
|
||||
// collides with user filenames or pushes a 255-byte filename past OS limits.
|
||||
const partPath = `${stagingDirectory}/${++nextDownloadPartId}-${Math.random().toString(36).slice(2, 8)}.part`;
|
||||
let downloaded = false;
|
||||
|
||||
const cleanup = async () => {
|
||||
if (reservedTarget && !downloaded) {
|
||||
await promises.rm(target, { force: true }).catch(() => {});
|
||||
}
|
||||
await promises.rm(partPath, { force: true }).catch(() => {});
|
||||
};
|
||||
|
||||
return {
|
||||
async downloadAsync() {
|
||||
try {
|
||||
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());
|
||||
await ensureParentAsync(target);
|
||||
await ensureParentAsync(partPath);
|
||||
await promises.writeFile(partPath, bytes);
|
||||
try {
|
||||
await promises.rename(partPath, target);
|
||||
} catch (error) {
|
||||
if (error?.code !== "EXDEV") throw error;
|
||||
await promises.copyFile(partPath, target);
|
||||
await promises.rm(partPath, { force: true }).catch(() => {});
|
||||
}
|
||||
downloaded = true;
|
||||
onProgress?.({
|
||||
totalBytesWritten: bytes.length,
|
||||
totalBytesExpectedToWrite: bytes.length,
|
||||
});
|
||||
return {
|
||||
uri,
|
||||
status: response.status,
|
||||
headers: Object.fromEntries(response.headers.entries()),
|
||||
};
|
||||
} catch (error) {
|
||||
await cleanup();
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
async cancelAsync() {
|
||||
controller.abort();
|
||||
await cleanup();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
cacheDirectory,
|
||||
documentDirectory,
|
||||
EncodingType,
|
||||
Paths,
|
||||
getInfoAsync,
|
||||
makeDirectoryAsync,
|
||||
copyAsync,
|
||||
moveAsync,
|
||||
readAsStringAsync,
|
||||
writeAsStringAsync,
|
||||
deleteAsync,
|
||||
readDirectoryAsync,
|
||||
File,
|
||||
Directory,
|
||||
createDownloadResumable,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import fs, { paths, promises } from "@react-native-gpui/fs";
|
||||
import { createFileSystem } from "./file-system-ops";
|
||||
|
||||
export const {
|
||||
cacheDirectory,
|
||||
documentDirectory,
|
||||
EncodingType,
|
||||
Paths,
|
||||
getInfoAsync,
|
||||
makeDirectoryAsync,
|
||||
copyAsync,
|
||||
moveAsync,
|
||||
readAsStringAsync,
|
||||
writeAsStringAsync,
|
||||
deleteAsync,
|
||||
readDirectoryAsync,
|
||||
File,
|
||||
Directory,
|
||||
createDownloadResumable,
|
||||
} = createFileSystem({ fs, promises, paths });
|
||||
@@ -0,0 +1,140 @@
|
||||
import fs, { promises } from "node:fs";
|
||||
import http from "node:http";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, expect, test } from "vitest";
|
||||
import { createFileSystem } from "./file-system-ops";
|
||||
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of tempDirs.splice(0)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("File.write and writeAsStringAsync create missing cache parent directories on first write", async () => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "paseo-gpui-fs-"));
|
||||
tempDirs.push(root);
|
||||
const { Directory, File, Paths, writeAsStringAsync } = createFileSystem({
|
||||
fs,
|
||||
promises,
|
||||
paths: { appCache: path.join(root, "cache"), appData: path.join(root, "data") },
|
||||
});
|
||||
|
||||
const file = new File(new Directory(Paths.cache), "report.txt");
|
||||
expect(file.exists).toBe(false);
|
||||
file.write(new Uint8Array([65, 66, 67]));
|
||||
expect(file.exists).toBe(true);
|
||||
expect(await file.text()).toBe("ABC");
|
||||
|
||||
const asyncUri = `${Paths.document}nested/note.txt`;
|
||||
await writeAsStringAsync(asyncUri, "hello");
|
||||
expect(fs.readFileSync(asyncUri.replace(/^file:\/\//, ""), "utf8")).toBe("hello");
|
||||
});
|
||||
|
||||
test("overlapping createDownloadResumable transfers keep distinct targets and clean up failures", async () => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "paseo-gpui-dl-"));
|
||||
tempDirs.push(root);
|
||||
const { createDownloadResumable, Directory, File, Paths } = createFileSystem({
|
||||
fs,
|
||||
promises,
|
||||
paths: { appCache: path.join(root, "cache"), appData: path.join(root, "data") },
|
||||
});
|
||||
|
||||
let releaseFirst: (() => void) | null = null;
|
||||
let firstRequested!: () => void;
|
||||
const firstRequestedPromise = new Promise<void>((resolve) => {
|
||||
firstRequested = resolve;
|
||||
});
|
||||
|
||||
const server = http.createServer((req, res) => {
|
||||
if (req.url === "/a/report.txt") {
|
||||
firstRequested();
|
||||
releaseFirst = () => {
|
||||
res.writeHead(200, { "Content-Type": "text/plain" });
|
||||
res.end("first-report");
|
||||
};
|
||||
return;
|
||||
}
|
||||
if (req.url === "/b/report.txt") {
|
||||
res.writeHead(200, { "Content-Type": "text/plain" });
|
||||
res.end("second-report");
|
||||
return;
|
||||
}
|
||||
res.writeHead(500);
|
||||
res.end("boom");
|
||||
});
|
||||
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("Expected ephemeral IPv4 server address");
|
||||
}
|
||||
const baseUrl = `http://127.0.0.1:${address.port}`;
|
||||
|
||||
try {
|
||||
const resolveSlot = (name: string) => {
|
||||
const dir = new Directory(Paths.cache);
|
||||
let candidate = new File(dir, name);
|
||||
let index = 1;
|
||||
while (candidate.exists) {
|
||||
candidate = new File(dir, `report (${index}).txt`);
|
||||
index += 1;
|
||||
}
|
||||
return candidate.uri;
|
||||
};
|
||||
|
||||
const firstUri = resolveSlot("report.txt");
|
||||
const first = createDownloadResumable(`${baseUrl}/a/report.txt`, firstUri);
|
||||
const firstDone = first.downloadAsync();
|
||||
await firstRequestedPromise;
|
||||
|
||||
const secondUri = resolveSlot("report.txt");
|
||||
expect(secondUri).not.toBe(firstUri);
|
||||
const second = createDownloadResumable(`${baseUrl}/b/report.txt`, secondUri);
|
||||
const secondResult = await second.downloadAsync();
|
||||
|
||||
releaseFirst?.();
|
||||
const firstResult = await firstDone;
|
||||
|
||||
expect(firstResult.uri).toBe(firstUri);
|
||||
expect(secondResult.uri).toBe(secondUri);
|
||||
expect(fs.readFileSync(firstResult.uri.replace(/^file:\/\//, ""), "utf8")).toBe("first-report");
|
||||
expect(fs.readFileSync(secondResult.uri.replace(/^file:\/\//, ""), "utf8")).toBe(
|
||||
"second-report",
|
||||
);
|
||||
|
||||
const failedUri = resolveSlot("report.txt");
|
||||
const failed = createDownloadResumable(`${baseUrl}/error`, failedUri);
|
||||
await expect(failed.downloadAsync()).rejects.toThrow("Download failed: 500");
|
||||
expect(new File(failedUri).exists).toBe(false);
|
||||
|
||||
// Staging in a private directory must neither collide with `.part` filenames nor exceed 255B.
|
||||
const partNamedUri = resolveSlot("report.txt.2.part");
|
||||
const partNamedResult = await createDownloadResumable(
|
||||
`${baseUrl}/b/report.txt`,
|
||||
partNamedUri,
|
||||
).downloadAsync();
|
||||
const adjacentResult = await createDownloadResumable(
|
||||
`${baseUrl}/b/report.txt`,
|
||||
resolveSlot("adjacent.txt"),
|
||||
).downloadAsync();
|
||||
expect(fs.readFileSync(partNamedResult.uri.replace(/^file:\/\//, ""), "utf8")).toBe(
|
||||
"second-report",
|
||||
);
|
||||
expect(fs.readFileSync(adjacentResult.uri.replace(/^file:\/\//, ""), "utf8")).toBe(
|
||||
"second-report",
|
||||
);
|
||||
|
||||
const maxName = `${"x".repeat(251)}.txt`;
|
||||
const maxNameResult = await createDownloadResumable(
|
||||
`${baseUrl}/b/report.txt`,
|
||||
resolveSlot(maxName),
|
||||
).downloadAsync();
|
||||
expect(fs.readFileSync(maxNameResult.uri.replace(/^file:\/\//, ""), "utf8")).toBe(
|
||||
"second-report",
|
||||
);
|
||||
} finally {
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
}
|
||||
});
|
||||
@@ -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,19 @@
|
||||
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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Installs the host timezone at startup, falling back to UTC if the OS reports
|
||||
* a POSIX TZ rule or localtime path that FormatJS cannot resolve.
|
||||
*/
|
||||
export function applySystemTimeZone(timeZone) {
|
||||
try {
|
||||
setDefaultTimeZone(timeZone);
|
||||
return timeZone.toUpperCase() === "GMT" ? "UTC" : timeZone;
|
||||
} catch {
|
||||
setDefaultTimeZone("UTC");
|
||||
return "UTC";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/* 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 { applySystemTimeZone, 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);
|
||||
});
|
||||
|
||||
test.each([
|
||||
[":/etc/localtime", "UTC"],
|
||||
["EST5EDT,M3.2.0,M11.1.0", "UTC"],
|
||||
["Europe/Berlin", "Europe/Berlin"],
|
||||
["GMT", "UTC"],
|
||||
])(
|
||||
"falls back to UTC on startup when host timezone %s is unsupported by FormatJS",
|
||||
(systemZone, expectedZone) => {
|
||||
expect(applySystemTimeZone(systemZone)).toBe(expectedZone);
|
||||
expect(new Intl.DateTimeFormat("en").resolvedOptions().timeZone).toBe(expectedZone);
|
||||
},
|
||||
);
|
||||
@@ -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 { applySystemTimeZone } from "./intl-timezone";
|
||||
applySystemTimeZone(Desktop.timezone());
|
||||
@@ -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() {}
|
||||
@@ -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,15 @@
|
||||
import { useMemo } from "react";
|
||||
import { View } from "react-native";
|
||||
|
||||
const CLIP_STYLE = { overflow: "hidden" };
|
||||
|
||||
// GPUI has no native RNCMaskedView component; render children in an
|
||||
// overflow-clipped container so splash and shimmer views never throw on lookup.
|
||||
export default function MaskedView({ style, maskElement: _maskElement, children, ...props }) {
|
||||
const containerStyle = useMemo(() => (style ? [CLIP_STYLE, style] : CLIP_STYLE), [style]);
|
||||
return (
|
||||
<View style={containerStyle} {...props}>
|
||||
{children}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -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";
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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,21 @@
|
||||
// TextEncoder and a strict UTF-8 TextDecoder for the GPUI V8 runtime, which has
|
||||
// neither. This module is imported before anything that reads them while it
|
||||
// evaluates (the URL implementation does), so it must stay free of other
|
||||
// web-global dependencies.
|
||||
import { Buffer } from "buffer";
|
||||
import { TextDecoder } from "expo/src/winter/TextDecoder";
|
||||
|
||||
class Utf8TextEncoder {
|
||||
get encoding() {
|
||||
return "utf-8";
|
||||
}
|
||||
|
||||
encode(input = "") {
|
||||
// Buffer encodes lone surrogates as U+FFFD, as the Encoding Standard requires.
|
||||
return new Uint8Array(Buffer.from(String(input), "utf8"));
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof globalThis.TextEncoder === "undefined") globalThis.TextEncoder = Utf8TextEncoder;
|
||||
// `fatal: true` must throw on malformed UTF-8; Buffer-based decoding cannot.
|
||||
if (typeof globalThis.TextDecoder === "undefined") globalThis.TextDecoder = TextDecoder;
|
||||
@@ -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),
|
||||
};
|
||||
@@ -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;
|
||||
@@ -0,0 +1,50 @@
|
||||
// Web-platform globals that Paseo's shared code reads (pairing links, relay
|
||||
// endpoints) and the GPUI V8 runtime lacks or stubs. Hermes apps get the same
|
||||
// URL from Expo's winter runtime, which GPUI does not load; take its
|
||||
// self-contained modules directly rather than its fetch and native-module
|
||||
// installers. Needs the globals from ./text-encoding installed first.
|
||||
import { Buffer } from "buffer";
|
||||
import { DOMException } from "expo/src/winter/DOMException";
|
||||
import { URL, URLSearchParams } from "expo/src/winter/url";
|
||||
|
||||
const ASCII_WHITESPACE = /[\t\n\f\r ]/g;
|
||||
const BASE64_ALPHABET = /^[A-Za-z0-9+/]*$/;
|
||||
|
||||
// WHATWG forgiving-base64 decode: whitespace is ignored, padding is optional,
|
||||
// and the result is a binary string with one character per byte.
|
||||
function atob(data) {
|
||||
const input = String(data).replace(ASCII_WHITESPACE, "");
|
||||
const unpadded = input.length % 4 === 0 ? input.replace(/==?$/, "") : input;
|
||||
if (unpadded.length % 4 === 1 || !BASE64_ALPHABET.test(unpadded)) {
|
||||
throw new DOMException(
|
||||
"The string to be decoded is not correctly encoded.",
|
||||
"InvalidCharacterError",
|
||||
);
|
||||
}
|
||||
return Buffer.from(unpadded, "base64").toString("latin1");
|
||||
}
|
||||
|
||||
function btoa(data) {
|
||||
const input = String(data);
|
||||
for (let index = 0; index < input.length; index++) {
|
||||
if (input.charCodeAt(index) > 0xff) {
|
||||
throw new DOMException(
|
||||
"The string to be encoded contains characters outside of Latin1.",
|
||||
"InvalidCharacterError",
|
||||
);
|
||||
}
|
||||
}
|
||||
return Buffer.from(input, "latin1").toString("base64");
|
||||
}
|
||||
|
||||
function installIfMissing(name, value) {
|
||||
if (typeof globalThis[name] === "undefined") globalThis[name] = value;
|
||||
}
|
||||
|
||||
installIfMissing("DOMException", DOMException);
|
||||
installIfMissing("atob", atob);
|
||||
installIfMissing("btoa", btoa);
|
||||
// React Native's own URL is a stub (empty `hostname`, unimplemented
|
||||
// `searchParams`), so it is replaced rather than kept.
|
||||
globalThis.URL = URL;
|
||||
globalThis.URLSearchParams = URLSearchParams;
|
||||
@@ -0,0 +1,61 @@
|
||||
import { afterEach, beforeEach, expect, test, vi } from "vitest";
|
||||
import { decodeOfferFragmentPayload } from "@getpaseo/protocol/connection-offer";
|
||||
|
||||
// GPUI's V8 runtime has no atob or btoa. Remove them, load the adapter, and
|
||||
// compare it with the platform's own implementation.
|
||||
const nativeAtob = globalThis.atob;
|
||||
const nativeBtoa = globalThis.btoa;
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.resetModules();
|
||||
Reflect.deleteProperty(globalThis, "atob");
|
||||
Reflect.deleteProperty(globalThis, "btoa");
|
||||
await import("./web-globals");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
globalThis.atob = nativeAtob;
|
||||
globalThis.btoa = nativeBtoa;
|
||||
});
|
||||
|
||||
test("pairing links decode where the runtime has no atob", () => {
|
||||
const offer = {
|
||||
v: 2,
|
||||
serverId: "srv_1",
|
||||
daemonPublicKeyB64: "a2V5",
|
||||
relay: { endpoint: "relay.paseo.sh:443" },
|
||||
};
|
||||
const encoded = Buffer.from(JSON.stringify(offer)).toString("base64url");
|
||||
expect(globalThis.atob).not.toBe(nativeAtob);
|
||||
expect(decodeOfferFragmentPayload(encoded)).toEqual(offer);
|
||||
});
|
||||
|
||||
test.each(["", "AA==", "AA", "AAA=", " QU JD\nRA== ", "+/+/", "w6k=", "SGVsbG8gd29ybGQ"])(
|
||||
"atob decodes %j as the platform does",
|
||||
(input) => {
|
||||
expect(globalThis.atob(input)).toBe(nativeAtob(input));
|
||||
},
|
||||
);
|
||||
|
||||
test.each(["A", "AAAAA", "A===", "AA=A", "A*==", "-_-_", "é"])(
|
||||
"atob rejects %j as the platform does",
|
||||
(input) => {
|
||||
expect(() => nativeAtob(input)).toThrow();
|
||||
expect(() => globalThis.atob(input)).toThrow(
|
||||
expect.objectContaining({ name: "InvalidCharacterError" }),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test.each(["", "Hello, world", "ÿ\u0000\u0080", "a"])(
|
||||
"btoa encodes %j as the platform does",
|
||||
(input) => {
|
||||
expect(globalThis.btoa(input)).toBe(nativeBtoa(input));
|
||||
},
|
||||
);
|
||||
|
||||
test("btoa rejects characters outside Latin1", () => {
|
||||
expect(() => globalThis.btoa("Ā")).toThrow(
|
||||
expect.objectContaining({ name: "InvalidCharacterError" }),
|
||||
);
|
||||
});
|
||||
@@ -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);
|
||||
@@ -0,0 +1,39 @@
|
||||
import { transformSync } from "@babel/core";
|
||||
import path from "node:path";
|
||||
import { afterEach, describe, expect, test } from "vitest";
|
||||
|
||||
const GPUI_DIR = import.meta.dirname;
|
||||
const previousNodeEnv = process.env.NODE_ENV;
|
||||
|
||||
// `react-native bundle --dev false` sets NODE_ENV=production and Metro's babel
|
||||
// transformer reports the bundle platform as the caller.
|
||||
function transformReleaseModule(source: string): string {
|
||||
process.env.NODE_ENV = "production";
|
||||
const result = transformSync(source, {
|
||||
filename: path.join(GPUI_DIR, "../src/release-module.ts"),
|
||||
configFile: path.join(GPUI_DIR, "babel.config.js"),
|
||||
caller: { name: "metro", bundler: "metro", platform: "desktop" } as never,
|
||||
babelrc: false,
|
||||
});
|
||||
return result?.code ?? "";
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
process.env.NODE_ENV = previousNodeEnv;
|
||||
});
|
||||
|
||||
describe("GPUI release babel config", () => {
|
||||
test("keeps Platform.OS a runtime read so one bundle serves macOS, Linux and Windows", () => {
|
||||
const code = transformReleaseModule(
|
||||
'import { Platform } from "react-native";\nexport const isMac = Platform.OS === "macos";\n',
|
||||
);
|
||||
|
||||
expect(code).toMatch(/Platform\.OS\s*===\s*"macos"/);
|
||||
});
|
||||
|
||||
test("still folds development globals in a release bundle", () => {
|
||||
const code = transformReleaseModule("export const dev = __DEV__;\n");
|
||||
|
||||
expect(code).toMatch(/dev\s*=\s*false/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
// One GPUI bundle runs on macOS, Linux and Windows, so `Platform.OS` is the host
|
||||
// the runtime reports, and @react-native-gpui/core turns Metro's platform
|
||||
// inlining off. babel-preset-expo still folds `Platform.OS` to the Metro
|
||||
// platform ("desktop") in release bundles. Plugins visit a node before presets
|
||||
// do, so skipping it here keeps the runtime read.
|
||||
function keepRuntimePlatformOS() {
|
||||
return {
|
||||
name: "paseo-gpui-runtime-platform-os",
|
||||
visitor: {
|
||||
MemberExpression(path) {
|
||||
if (path.matchesPattern("Platform.OS")) path.skip();
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = function (api) {
|
||||
api.cache(true);
|
||||
return {
|
||||
presets: [[require.resolve("babel-preset-expo"), { unstable_transformImportMeta: true }]],
|
||||
plugins: [
|
||||
keepRuntimePlatformOS,
|
||||
[require.resolve("react-native-unistyles/plugin"), { root: "../src" }],
|
||||
],
|
||||
};
|
||||
};
|
||||
Vendored
+8
@@ -0,0 +1,8 @@
|
||||
/* oxlint-disable import/no-unassigned-import -- Install globals before app modules evaluate. */
|
||||
// Runtime globals every GPUI entry needs before app modules evaluate. The app
|
||||
// entry and the native regression fixtures both start here, so a fixture runs
|
||||
// on the same globals the shipped app does.
|
||||
import "./adapters/intl";
|
||||
import "./adapters/text-encoding";
|
||||
import "./adapters/web-globals";
|
||||
import "../src/polyfills/install-early";
|
||||
@@ -0,0 +1,4 @@
|
||||
build/
|
||||
.cache/
|
||||
autolink/
|
||||
target/
|
||||
Generated
+8786
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,66 @@
|
||||
[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" }
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
image = { version = "0.25.1", default-features = false, features = ["png"] }
|
||||
|
||||
[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.
|
||||
@@ -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())
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"identifier": "sh.paseo.gpui",
|
||||
"icon": "../../../desktop/assets/icon.png",
|
||||
"window": {
|
||||
"title": "Paseo",
|
||||
"width": 1200,
|
||||
"height": 800,
|
||||
"titleBar": "hidden",
|
||||
"menuBar": false
|
||||
},
|
||||
"bundle": { "macos": { "minimumSystemVersion": "15.0" } }
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"icon": "../../../desktop/assets/icon.icns",
|
||||
"window": {
|
||||
"trafficLightPosition": { "x": 16, "y": 10 }
|
||||
},
|
||||
"bundle": {
|
||||
"macos": {
|
||||
"entitlements": "desktop/entitlements.mac.adhoc.plist"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>com.apple.security.cs.allow-jit</key>
|
||||
<true/>
|
||||
<key>com.apple.security.cs.disable-library-validation</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>com.apple.security.cs.allow-jit</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,274 @@
|
||||
use gpui::{
|
||||
div, px, App, AppContext, Context, IntoElement, ParentElement, Render, Styled, Window,
|
||||
WindowBounds, WindowOptions,
|
||||
};
|
||||
use react_native_gpui::DesktopAppConfig;
|
||||
use rn_gpui_enriched_markdown::interaction::InteractionState;
|
||||
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>,
|
||||
interaction: InteractionState,
|
||||
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, &self.interaction);
|
||||
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()),
|
||||
interaction: InteractionState::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);
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
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",
|
||||
"@react-native-masked-view/masked-view": "masked-view.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");
|
||||
@@ -0,0 +1,52 @@
|
||||
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"),
|
||||
)
|
||||
.js_engine("v8")
|
||||
.dev_menu(true);
|
||||
let app_id = config.app_id.clone();
|
||||
let config = config.configure_window(move |options| {
|
||||
// GPUI window options are public: titlebar, resizability, display,
|
||||
// decorations, min size, and other native window behavior.
|
||||
options.is_resizable = true;
|
||||
options.app_id = Some(app_id);
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
options.icon = linux_window_icon();
|
||||
}
|
||||
});
|
||||
|
||||
react_native_gpui::run_with(config);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn linux_window_icon() -> Option<std::sync::Arc<image::RgbaImage>> {
|
||||
const ICON_BYTES: &[u8] = include_bytes!("../../../../desktop/assets/128x128.png");
|
||||
let decoded = image::load_from_memory_with_format(ICON_BYTES, image::ImageFormat::Png).ok()?;
|
||||
Some(std::sync::Arc::new(decoded.to_rgba8()))
|
||||
}
|
||||
|
||||
#[cfg(all(test, target_os = "linux"))]
|
||||
mod tests {
|
||||
use super::linux_window_icon;
|
||||
|
||||
#[test]
|
||||
fn linux_window_icon_decodes_canonical_paseo_png() {
|
||||
let icon = linux_window_icon().expect("bundled Paseo Linux window icon should decode");
|
||||
assert_eq!(icon.dimensions(), (128, 128));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
use crate::{NativePaseoDesktopEvents, NativePaseoDesktopSpec};
|
||||
use rn_gpui_module::ModuleError;
|
||||
use std::io::Read;
|
||||
|
||||
pub struct PaseoDesktop {
|
||||
database: std::sync::Mutex<Option<rusqlite::Connection>>,
|
||||
}
|
||||
impl PaseoDesktop {
|
||||
fn database(
|
||||
&self,
|
||||
) -> Result<std::sync::MutexGuard<'_, Option<rusqlite::Connection>>, ModuleError> {
|
||||
let mut guard = self
|
||||
.database
|
||||
.lock()
|
||||
.map_err(|e| ModuleError::new(e.to_string()))?;
|
||||
if guard.is_none() {
|
||||
let base = std::env::var("XDG_DATA_HOME")
|
||||
.map(std::path::PathBuf::from)
|
||||
.unwrap_or_else(|_| {
|
||||
std::path::PathBuf::from(std::env::var("HOME").expect("HOME is set"))
|
||||
.join(".local/share")
|
||||
});
|
||||
let dir = base.join("paseo-gpui");
|
||||
std::fs::create_dir_all(&dir).map_err(|e| ModuleError::new(e.to_string()))?;
|
||||
*guard = Some(
|
||||
rusqlite::Connection::open(dir.join("replica.db"))
|
||||
.map_err(|e| ModuleError::new(e.to_string()))?,
|
||||
);
|
||||
}
|
||||
Ok(guard)
|
||||
}
|
||||
}
|
||||
impl NativePaseoDesktopSpec for PaseoDesktop {
|
||||
fn new(_events: NativePaseoDesktopEvents) -> Self {
|
||||
Self {
|
||||
database: std::sync::Mutex::new(None),
|
||||
}
|
||||
}
|
||||
fn sqlite(&self, sql: String, params: String) -> Result<String, ModuleError> {
|
||||
let fail = |e: rusqlite::Error| ModuleError::new(e.to_string());
|
||||
let db = self.database()?;
|
||||
let db = db.as_ref().unwrap();
|
||||
if params == "batch" {
|
||||
db.execute_batch(&sql).map_err(fail)?;
|
||||
return Ok("[]".into());
|
||||
}
|
||||
let values: Vec<serde_json::Value> =
|
||||
serde_json::from_str(¶ms).map_err(|e| ModuleError::new(e.to_string()))?;
|
||||
let values: Vec<rusqlite::types::Value> = values
|
||||
.into_iter()
|
||||
.map(|v| match v {
|
||||
serde_json::Value::Null => rusqlite::types::Value::Null,
|
||||
serde_json::Value::String(v) => rusqlite::types::Value::Text(v),
|
||||
serde_json::Value::Number(v) => v
|
||||
.as_i64()
|
||||
.map(rusqlite::types::Value::Integer)
|
||||
.unwrap_or_else(|| rusqlite::types::Value::Real(v.as_f64().unwrap())),
|
||||
_ => rusqlite::types::Value::Text(v.to_string()),
|
||||
})
|
||||
.collect();
|
||||
let mut stmt = db.prepare(&sql).map_err(fail)?;
|
||||
let names: Vec<String> = stmt.column_names().into_iter().map(str::to_owned).collect();
|
||||
let mut rows = stmt
|
||||
.query(rusqlite::params_from_iter(values))
|
||||
.map_err(fail)?;
|
||||
let mut results = Vec::new();
|
||||
while let Some(row) = rows.next().map_err(fail)? {
|
||||
let mut object = serde_json::Map::new();
|
||||
for (index, name) in names.iter().enumerate() {
|
||||
let value = match row.get_ref(index).map_err(fail)? {
|
||||
rusqlite::types::ValueRef::Null => serde_json::Value::Null,
|
||||
rusqlite::types::ValueRef::Integer(v) => v.into(),
|
||||
rusqlite::types::ValueRef::Real(v) => serde_json::json!(v),
|
||||
rusqlite::types::ValueRef::Text(v) => {
|
||||
String::from_utf8_lossy(v).into_owned().into()
|
||||
}
|
||||
rusqlite::types::ValueRef::Blob(_) => {
|
||||
return Err(ModuleError::new(
|
||||
"Replica store does not support blob columns",
|
||||
))
|
||||
}
|
||||
};
|
||||
object.insert(name.clone(), value);
|
||||
}
|
||||
results.push(object);
|
||||
}
|
||||
serde_json::to_string(&results).map_err(|e| ModuleError::new(e.to_string()))
|
||||
}
|
||||
fn timezone(&self) -> Result<String, ModuleError> {
|
||||
if let Ok(zone) = std::env::var("TZ") {
|
||||
let trimmed = zone.trim();
|
||||
if !trimmed.is_empty() {
|
||||
if let Some(path) = trimmed.strip_prefix(':') {
|
||||
if let Some(iana) = zoneinfo_name(std::path::Path::new(path)) {
|
||||
return Ok(iana);
|
||||
}
|
||||
if let Ok(target) = std::fs::read_link(path) {
|
||||
if let Some(iana) = zoneinfo_name(&target) {
|
||||
return Ok(iana);
|
||||
}
|
||||
}
|
||||
}
|
||||
return Ok(trimmed.trim_start_matches(':').into());
|
||||
}
|
||||
}
|
||||
if let Ok(path) = std::fs::read_link("/etc/localtime") {
|
||||
if let Some(iana) = zoneinfo_name(&path) {
|
||||
return Ok(iana);
|
||||
}
|
||||
}
|
||||
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())
|
||||
}
|
||||
}
|
||||
|
||||
fn zoneinfo_name(path: &std::path::Path) -> Option<String> {
|
||||
path.to_string_lossy()
|
||||
.split_once("/zoneinfo/")
|
||||
.map(|(_, zone)| zone.trim().to_owned())
|
||||
.filter(|zone| !zone.is_empty())
|
||||
}
|
||||
|
||||
#[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"}])
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
import { expect } from "vitest";
|
||||
|
||||
export interface DriverNode {
|
||||
tag: number;
|
||||
component: string;
|
||||
testID: string;
|
||||
text: string;
|
||||
frame?: [number, number, number, number];
|
||||
children?: DriverNode[];
|
||||
}
|
||||
|
||||
export interface GpuiDriver {
|
||||
request<T = unknown>(method: string, params?: Record<string, unknown>): Promise<T>;
|
||||
nodes(): Promise<DriverNode[]>;
|
||||
query(by: "testID" | "text", value: string): Promise<Array<DriverNode & { visible?: boolean }>>;
|
||||
nodeWithId(testID: string, requireLayout?: boolean): Promise<DriverNode>;
|
||||
click(tag: number): Promise<void>;
|
||||
hover(tag: number): Promise<void>;
|
||||
pressKey(key: string): Promise<void>;
|
||||
typeText(tag: number, text: string): Promise<void>;
|
||||
getText(tag: number): Promise<string>;
|
||||
replaceText(tag: number, text: string): Promise<void>;
|
||||
openWorkspaceAndWaitForComposer(workspaceRow: DriverNode): Promise<DriverNode>;
|
||||
openCommandCenter(): Promise<void>;
|
||||
closeCommandCenter(): Promise<void>;
|
||||
close(): void;
|
||||
}
|
||||
|
||||
function flatten(node: DriverNode): DriverNode[] {
|
||||
return [node, ...(node.children ?? []).flatMap(flatten)];
|
||||
}
|
||||
|
||||
export async function connectGpuiDriver(options: {
|
||||
endpoint: string;
|
||||
token: string;
|
||||
settleMs?: number;
|
||||
}): Promise<GpuiDriver> {
|
||||
const { endpoint, token, settleMs = 0 } = options;
|
||||
const socket = new WebSocket(endpoint);
|
||||
let nextId = 0;
|
||||
const pending = new Map<number, { resolve(value: unknown): void; reject(error: Error): void }>();
|
||||
|
||||
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);
|
||||
});
|
||||
|
||||
if (settleMs > 0) {
|
||||
await new Promise((resolve) => setTimeout(resolve, settleMs));
|
||||
}
|
||||
|
||||
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 } }));
|
||||
});
|
||||
}
|
||||
|
||||
async function nodes(): Promise<DriverNode[]> {
|
||||
return (await request<{ children: DriverNode[] }>("tree")).children.flatMap(flatten);
|
||||
}
|
||||
|
||||
async function query(by: "testID" | "text", value: string) {
|
||||
const matches = await request<Array<DriverNode & { visible?: boolean }>>("query", {
|
||||
by,
|
||||
value,
|
||||
});
|
||||
return matches.filter((node) => node.visible !== false);
|
||||
}
|
||||
|
||||
async function nodeWithId(testID: string, requireLayout = false): Promise<DriverNode> {
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const node = (await nodes()).find((item) => item.testID === testID);
|
||||
if (!node) return false;
|
||||
return !requireLayout || ((node.frame?.[2] ?? 0) > 0 && (node.frame?.[3] ?? 0) > 0);
|
||||
})
|
||||
.toBe(true);
|
||||
return (await nodes()).find((node) => node.testID === testID)!;
|
||||
}
|
||||
|
||||
async function click(tag: number): Promise<void> {
|
||||
expect(await request("click", { tag })).toEqual({ clicked: true });
|
||||
}
|
||||
|
||||
async function hover(tag: number): Promise<void> {
|
||||
await request("hover", { tag });
|
||||
}
|
||||
|
||||
async function pressKey(key: string): Promise<void> {
|
||||
await request("press", { key });
|
||||
}
|
||||
|
||||
async function typeText(tag: number, text: string): Promise<void> {
|
||||
expect(await request("type", { tag, text })).toEqual({ typed: true });
|
||||
}
|
||||
|
||||
async function getText(tag: number): Promise<string> {
|
||||
return (await request<{ text: string }>("getProps", { tag })).text;
|
||||
}
|
||||
|
||||
async function replaceText(tag: number, text: string): Promise<void> {
|
||||
await click(tag);
|
||||
await pressKey("secondary-a");
|
||||
await pressKey("backspace");
|
||||
if (text) await typeText(tag, text);
|
||||
await expect.poll(() => getText(tag)).toBe(text);
|
||||
}
|
||||
|
||||
async function openWorkspaceAndWaitForComposer(workspaceRow: DriverNode): Promise<DriverNode> {
|
||||
await click(workspaceRow.tag);
|
||||
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);
|
||||
return (await nodes()).find((node) => node.component === "TextInput")!;
|
||||
}
|
||||
|
||||
async function commandCenterOpen(): Promise<boolean> {
|
||||
return (await query("testID", "command-center-input")).length > 0;
|
||||
}
|
||||
|
||||
async function openCommandCenter(): Promise<void> {
|
||||
await pressKey("secondary-k");
|
||||
await expect.poll(commandCenterOpen, { timeout: 5_000 }).toBe(true);
|
||||
}
|
||||
|
||||
async function closeCommandCenter(): Promise<void> {
|
||||
await pressKey("escape");
|
||||
await expect.poll(commandCenterOpen).toBe(false);
|
||||
}
|
||||
|
||||
return {
|
||||
request,
|
||||
nodes,
|
||||
query,
|
||||
nodeWithId,
|
||||
click,
|
||||
hover,
|
||||
pressKey,
|
||||
typeText,
|
||||
getText,
|
||||
replaceText,
|
||||
openWorkspaceAndWaitForComposer,
|
||||
openCommandCenter,
|
||||
closeCommandCenter,
|
||||
close: () => socket.close(),
|
||||
};
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user