Compare commits

...
Author SHA1 Message Date
Mohamed Boudra 6e1f985ba5 fix(gpui): drop the unreachable split layout from the GPUI diff surface
Callers enable split only when isWeb holds, so GPUI always passes unified.
The split rows could never render; remove them and keep a test that a split
preference still renders unified rows.
2026-12-06 16:12:54 +01:00
Mohamed Boudra 200066ffe3 feat(gpui): render the Changes panel diff without Skia
The Changes tab crashed on GPUI with "Cannot read properties of undefined
(reading 'listFontFamilies')". The diff surface resolved to the Skia canvas
implementation, whose native module does not exist on GPUI.

Add surface.gpui.tsx, which Metro selects ahead of .native on GPUI only. It
lays out hunk headers, line numbers, add/remove/context rows, syntax colors,
collapse, split layout, and unwrapped horizontal scrolling with plain React
Native views, so Skia never enters the GPUI bundle. Inline review, drag
selection, and scroll-to-file stay canvas-only.

DocumentFileHeader now asks only for the section fields it reads.
2026-12-06 16:07:39 +01:00
neihyud c5caa9a009 Show provider CLI versions as plain text when the CLI styles its output (#10616)
Some provider CLIs color their `--version` output even when piped, and the
escape codes showed up in the provider settings version row. Strip them in
readCommandVersionOutput, which the version label, Codex version checks and
diagnostics all read from.

Fixes #10316
2026-12-06 14:12:41 +00:00
SunicemanandShane Su d69527bbe5 Show platform-specific crash log hints for local speech workers (#11219)
Co-authored-by: Shane Su <26364206+suniceman@users.noreply.github.com>
2026-12-06 13:43:04 +00:00
Mohamed Boudra 99045250d0 fix(gpui): switch experimental desktop release to manual timestamped tags and fix Linux/macOS CI builds (#12233)
* fix(gpui): update nightly release in place with experimental title and notes

Previously the GPUI nightly workflow staged and published a brand-new release every night, which sent daily release notification emails to repository watchers. Updating the existing gpui-nightly prerelease in place preserves the same release ID, refreshes the tag and assets, deletes stale assets, and avoids repeat watcher emails while keeping initial draft staging when the release does not exist yet.

* fix(gpui): install fontconfig and freetype dev packages on Linux

yeslogic-fontconfig-sys requires fontconfig via pkg-config on ubuntu-24.04 (failed in run 47633672297); install libfontconfig-dev and libfreetype-dev alongside the existing X11/Wayland/Vulkan build dependencies.

* fix(gpui): back up existing nightly assets and defer tag update until upload succeeds

Addresses review feedback on in-place nightly updates: download existing release assets into a temporary backup before replacing them, move refs/tags/gpui-nightly only after all uploads are verified, and restore the backed-up assets and prior tag SHA if any step fails before the release metadata PATCH completes.

* fix(gpui): cache native deps with target and keep untouched assets on rollback

Restoring .artifacts/gpui/macos/target without RN_GPUI_NATIVE_DEPS_CACHE caused CMake regeneration to fail with missing OpenSSL::SSL and OpenSSL::Crypto targets on macOS. Set RN_GPUI_NATIVE_DEPS_CACHE inside .artifacts/gpui/{macos,linux}/native-deps, cache it alongside target under v2 keys, and clear restored CMakeCache.txt before configure. Also skip re-uploading assets whose IDs are unchanged during in-place rollback and report any rollback errors.

* fix(gpui): retry selective asset uploads during in-place rollback

Keep skipping untouched asset IDs when rolling back a failed in-place nightly release update, while routing only replaced or deleted backup files through scripts/upload-release-assets.mjs so transient upload failures retain retries.

* feat(gpui): switch experimental desktop release to manual timestamped tags

Implements Decision D622: remove the daily cron schedule from .github/workflows/gpui-nightly.yml so builds are manual-only (workflow_dispatch), rename the workflow and artifacts to GPUI Experimental, and stage-then-promote each run to a unique timestamped tag (gpui-experimental-DD-MM-YYYY-HHMM) with title Paseo GPUI Experimental DD-MM-YYYY HH:MM UTC and the approved Simple English release notes.

* fix(gpui): clean up newly created tag when promotion fails

Addresses review feedback on experimental release staging: track whether the current run created the timestamped tag and delete that ref alongside the staging draft if the promotion PATCH fails.
2026-12-06 20:37:13 +07:00
Mohamed Boudra 7f07d3e028 Unify desktop window chrome and bring GPUI to frameless parity (#12234)
* refactor(app): unify desktop window chrome behind platform seam

Extract renderer-agnostic window-chrome primitives so shared headers, sidebars, tabs, and window controls no longer gate on isNative or Electron globals directly:

- Add @/desktop/window-chrome-host (.ts no-op default and .web.ts Electron adapter) and migrate WindowChromeProvider, DesktopWindowControlsSync, and DesktopWindowControls onto it.
- Add @/components/desktop/caption-button and migrate DesktopWindowControls off raw Pressable and Electron window calls.
- Add @/components/desktop/titlebar-drag-surface (.tsx plain View and .web.tsx wrapping TitlebarDragRegion) and migrate header, sidebar, split pane, settings, drawer, and splash mount sites while keeping Electron drag/no-drag DOM/CSS behavior intact.
- Place explorerControls.titlebarAction after sharedExplorer so paint and hit-test order does not rely on zIndex, and tighten non-overflowing tab scroll width.

* test(app): assert drag overlay and 4px resizer styles in chrome seam test

* test(app): inject Electron deps in window-chrome-host and test default noop host

* refactor(app): remove unused Electron window command wrappers

* fix(app): initialize Electron window-chrome host lazily without platform gate import

* fix(app): preserve Explorer titlebar toggle header Tab order

* feat(gpui): implement desktop window chrome parity

Implements the .gpui.* platform adapters for Paseo's renderer-agnostic window chrome seam, bumps @react-native-gpui/* dependencies to paseo-6, and updates desktop*.json + main.rs so desktop.json is the single source of truth (1200x800, titleBar: hidden, menuBar: false, macOS trafficLightPosition {x: 16, y: 10}).

Uses DesktopWindowControlNativeComponent (codegenNativeComponent) so Bridgeless Fabric receives a static view config without touching UIManager, normalizes SafeArea top inset to 0 in window-layout/index.gpui.tsx for integrated 36px headers, and re-syncs menuSetMenuBarVisible(false, 1) on Linux/Windows so the initial surface reclaims the 26px menu strip.

* fix(app): pass system chrome appearance and action-only caption contract

Resolves two review findings:
- Pass "system" from DesktopWindowControlsSync when theme is "auto" (or missing-plugin fallback) so macOS GPUI clears NSWindow.setAppearance instead of locking dark/light across Light -> Dark -> System.
- Make DesktopCaptionButton action-only across web and GPUI adapters so GPUI does not accept and ignore a shared onPress prop.
2026-12-06 20:23:10 +07:00
Mohamed Boudra 9e8bce0789 feat(gpui): give GPUI desktop app icon parity with Electron (#12238)
* feat(gpui): ship Paseo app icons across macOS and Linux packages

Reuse the canonical Paseo desktop assets in packages/desktop/assets/ instead of duplicating icon blobs or falling back to @react-native-gpui/cli's default-icon.png:

- Point packages/app/gpui/desktop/desktop.json at icon.png and desktop.macos.json at icon.icns so cargo-packager bundles the full macOS iconset and dev runs receive the Dock icon via RN_GPUI_APP_ICON.
- Compile packages/desktop/assets/icon.icon into Assets.car (when Xcode 26+ actool is available) and stamp packages/desktop/assets/icon.icns onto the nightly macOS DMG volume.
- Fail verify-macos-package.mjs if CFBundleIconFile is missing, falls back to default-icon.png, diverges from packages/desktop/assets/icon.icns, or mismatches Assets.car/CFBundleIconName.
- Set window app_id and embed the Linux window icon in main.rs, and ship sh.paseo.gpui.desktop plus hicolor icons in scripts/gpui.mjs package-linux.

* fix(gpui): address icon verification and Linux launcher review findings

- Verify CFBundleIconName against assetutil catalog entries in verify-macos-package.mjs and drop the duplicate XML plist parser in favor of passing parsed Info.plist metadata in tests.
- Reuse @react-native-gpui/cli's loadDesktopConfig in scripts/gpui.mjs resolveConfiguredAppIcon so dev runs validate desktop.json identically to packaging.
- Place the Linux launcher at bin/paseo-gpui with readlink -f symlink resolution and symlink paseo-gpui -> bin/paseo-gpui so PATH symlinks and menu launches resolve libv8.so and resources.
- Require @react-native-gpui/cli assets unconditionally in verify-macos-package.test.mjs and add wrong-catalog-name and symlinked-launcher tests.

* fix(gpui): verify mounted macOS DMG icons and drop standalone CLI fallback requirement

* fix(gpui): run nightly macOS icon compilation on macos-latest
2026-12-06 19:47:40 +07:00
Mohamed Boudra 4d2a997d57 Make relay pairing and encrypted relay sessions work in the GPUI desktop app (#12242)
* fix(gpui): pair and connect over a relay on the V8 runtime

Pasting a pairing link failed with "globalThis.atob is not a function".
That was the first of several web globals the shared pairing and relay
code reads and V8 does not provide: atob/btoa, TextEncoder, TextDecoder
and DOMException were missing, and React Native's URL is a stub with an
empty hostname, so relay endpoints were rejected as invalid.

Install them from the GPUI-owned bootstrap, using the same Expo winter URL
and strict UTF-8 TextDecoder the mobile app gets. The encoding globals
load first because the URL implementation reads TextEncoder while it
evaluates. Shared packages are unchanged.

relay.native.test.ts runs the real HostRuntimeStore in the V8 binary
against a fake relay and daemon: pair, protected and legacy E2EE
handshakes, an encrypted ping/pong, and reconnect from the saved
registry. native-fixture.ts holds the bundle-and-run harness shared with
the WebSocket native test.

* test(gpui): share the fake relay and daemon between relay checks

Move the relay fixture out of relay.native.test.ts so a UI-driven pairing
run can start the same daemon the headless regression uses.

* test(gpui): keep the relay regression off the developer's localhost daemon

boot() also probes localhost:6767 (or EXPO_PUBLIC_LOCAL_DAEMON) unless the app's E2E
flag is stored. The fixture sets that flag so it reaches only its fake relay daemons.

* test(gpui): require Noise in the protected relay check and isolate saved hosts per run

The protected fake daemon accepted legacy handshakes, so a client that dropped Noise
would still pass. Each native run also now owns its app data directory, which macOS
and Windows read instead of XDG_DATA_HOME.
2026-12-06 19:47:03 +07:00
paseo-bot[bot] a6ac88ebe0 test(app): consolidate onboarding provider coverage (#12244)
Reuse the first-run setup host and Providers visit for the provider removal and re-add checks.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-06 12:38:28 +00:00
igayowaiandpaseo-bot[bot] baacb7aaac fix(acp): prevent Windows cancel deadlock when child pipes stay open (#12216)
* fix(acp): prevent Windows cancel deadlock when child pipes stay open

* Acknowledge ACP interrupt retries before closing the session

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-06 19:33:17 +07:00
Mohamed Boudra de1b414c25 feat(usage): add dedicated Oh My Pi usage source via omp usage --json (#12231)
* feat(usage): add dedicated Oh My Pi usage source via omp usage --json

When Oh My Pi authenticates through an auth broker, local agent.db has no auth_credentials rows, so the old SQLite-reading OMP routes in claude-usage-source and codex-usage-source discovered zero accounts. For local accounts, those routes also polled /api/oauth/usage independently on top of OMP's own polling and cache.

This adds a dedicated built-in omp-usage-source plugin that owns OMP usage through `omp usage --json` using the configured OMP command and environment, with bounded process execution, coalesced discovery/fetch snapshots, model-scoped session and list_profiles matching, and graceful skipping on older or missing OMP installs. The old local-only OMP SQLite routes are removed from claude-usage-source and codex-usage-source so both broker-backed and local OMP accounts report once without duplicates or duplicate polling.

* fix(usage): terminate wrapped OMP process groups and avoid stale refresh snapshots

Addresses review feedback on PR #12231:
- Remove the 30-second plugin-side unconsumed discovery snapshot cache so per-account refreshes always invoke `omp usage --json` fresh instead of replaying an earlier unconsumed discovery result, while keeping in-flight coalescing across concurrent requests and letting the daemon and OMP own caching.
- Spawn POSIX usage commands in their own process group (`detached: true`) and signal `-child.pid` on timeout/abort/overflow without skipping the SIGKILL grace escalation when a wrapper launcher exits before its grandchild.

* fix(usage): pass OMP provider launch to host discovery, consume discovery reports per request, and fix Windows fixture tests

* fix(usage): deduplicate OMP store credential IDs, preserve configured plugin registration, and remove wrapped test startup race

* fix(usage): gate global launch forwarding, keep wrapper OMP stores distinct, and stream fast sources during host discovery

* fix(usage): bound list discovery deadline, skip redundant fetch after failed discovery, and scope byAgent entries by session

* fix(usage): keep single list completion contract without detached cutoff and isolate previous agent reports by session identity
2026-12-06 19:23:28 +07:00
Mohamed Boudra 99b55930c5 fix(server): load local speech models from non-ASCII Windows profile paths (#12241)
* fix(server): resolve local speech model paths relative to modelsDir in worker

On Windows, sherpa-onnx-node@1.12.28 and espeak-ng check and open model files via narrow ANSI APIs (std::ifstream, GetFullPathNameA), which fail when $PASEO_HOME or modelsDir contains non-ASCII characters outside the system ANSI code page.

Inside the isolated Paseo Voice child process, create modelsDir if missing, chdir into it, validate that resolved paths stay within modelsDir, and pass pure-ASCII relative paths with POSIX separators to sherpa-onnx-node for STT, VAD, and TTS without mutating the daemon's cwd or upgrading sherpa-onnx-node (which breaks espeak-ng TTS in 2.0.x).

* fix(server): anchor worker modelsDir to initial cwd and preserve VAD fallback

Addresses review feedback on #12241:
- Anchor WorkerModelsDirScope relative path resolution to the worker's initial cwd so repeated relative modelsDir calls do not drift after process.chdir().
- Keep VAD directory preparation inside the recoverable try block so read-only or missing modelsDir falls back to the bundled Silero VAD model.
- Move optional loadNative and fileExists test dependencies onto config objects instead of adding positional constructor arguments.

* test(server): wait for worker process exit before cleaning up modelsDir

On Windows, the worker process holds a handle on its modelsDir cwd until OS process termination completes, causing immediate rmSync() in afterEach to hit EBUSY. Wait for the spawned worker PID to exit and retry rmSync during cleanup.

* test(server): use async rm with backoff for Windows worker dir cleanup

fs.rmSync retries EBUSY synchronously with zero delay; async fs/promises rm honors retryDelay backoff while Windows releases the exited worker's cwd handle.
2026-12-06 19:21:44 +07:00
880c040287 Keep Import Session quiet when default provider CLIs are absent (#12226)
* fix(server): skip missing CLIs when listing importable sessions

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>

* Keep Import Session warnings for configured launchers

Treat a missing default executable as an empty provider listing. Keep errors for missing configured launchers visible, with the command that failed.

Co-authored-by: jamescordrey-ops <335786770+jamescordrey-ops@users.noreply.github.com>

* Keep Import Session warnings for installed CLIs that fail to start

* Keep Import Session warnings for non-executable launchers

---------

Co-authored-by: Dhruv Singal <dhruvsingalabc@gmail.com>
Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: jamescordrey-ops <335786770+jamescordrey-ops@users.noreply.github.com>
2026-12-06 11:43:23 +00:00
lukeandRoundRedDot 7f94f5662c fix(acp): keep web search queries and results (#10835)
ACP agents that run a web search (Grok) report it as kind `search` with
the OpenAI Responses `web_search_call.action` in `rawOutput.action`:
`{type: "search", query, sources: [{url}]}` or `{type: "open_page", url}`.
Both ACP mappers (the daemon's and the plugin SDK's) read only
`rawInput.query|pattern` and text content, so the row showed the tool
title ("Web search:") as its query and no results.

For kind `search`, read the query from the action (its query, else the
opened URL), collect `webResults` from the action's sources,
`rawOutput.sources` / `rawOutput.results`, `resource_link` content and an
opened page, deduplicated by URL and limited to http(s), and mark such a
search `web_search`. File searches are unchanged.

Co-authored-by: RoundRedDot <roundreddot@gmail.com>
2026-12-06 11:42:46 +00:00
Mohamed Boudra 1704ba4fbb polish(app): align Command Center chevrons, row icons, and filter pills (#12235)
* polish(app): align Command Center chevrons, row icons, and filter pills

Move drill-down chevrons beside the row title so shortcuts and trailing values align on one right rail. Center single-line icons with 20px text and multi-line icons with 18px first-line titles. Add a trackless pills variant to SegmentedControl backed by segmentedSegmentSm geometry so Command Center filter tabs stay compact and aligned with the left rail.

* test(app): verify long-title ellipsis and chevron width in Command Center rows
2026-12-06 18:16:41 +07:00
NikandMohamed Boudra a5c32c5944 fix(app): normalize Windows checkout status paths (#3891)
* fix(app): normalize workspace paths at cache boundary

* fix(app): unify Windows checkout path identity across git caches

Normalizing only daemon checkout payloads was insufficient when Windows paths differed in drive-letter casing, trailing slashes, or drive-root spelling, or when query keys, invalidation predicates, and git-action stores keyed on raw caller cwd values.

Normalize Windows drive-letter casing, preserve drive roots and UNC prefixes, and route checkout query keys, invalidation predicates, git actions, working-diff comparison keys, and diff fallback matching through normalizeWorkspacePath.

* fix(app): preserve literal backslashes in POSIX workspace paths

Applying Windows separator conversion to POSIX paths merged distinct Linux directories such as /work/team\repo and /work/team/repo under one cache key. Restrict Windows separator, drive-letter, extended-prefix, and UNC normalization to Windows-shaped paths, and exercise an observer without route metadata in the fallback diff-routing test.

---------

Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
2026-12-06 17:59:17 +07:00
Ryan大然 922c682a30 Stop OpenCode resumes from piling duplicate permission rules onto the session (#12232)
OpenCode appends PATCH /session/{id} permission rules to the session's list, so every resume added another copy of the agent's rules. Resume now reads the session first and skips the update when its rules already end with the agent's rules; any other state still gets the full list, so the agent's rules stay last and win.

Closes #12211
2026-12-06 10:43:52 +00:00
paseo-bot[bot] 6da4247646 fix(plugins): restore the previous plugin when an update cannot save (#12197)
The candidate was already running when saving its source failed. Include that save in update recovery so the configured source and the running plugin agree after the error.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-06 10:43:23 +00:00
138 changed files with 10935 additions and 1812 deletions
+114 -130
View File
@@ -1,8 +1,6 @@
name: GPUI Nightly
name: GPUI Experimental
on:
schedule:
- cron: "0 6 * * *"
workflow_dispatch:
inputs:
platform:
@@ -15,7 +13,7 @@ on:
- macos
- linux
publish:
description: "Publish built artifacts to the rolling gpui-nightly prerelease."
description: "Publish built artifacts as a timestamped gpui-experimental prerelease."
required: false
default: "true"
type: choice
@@ -24,7 +22,7 @@ on:
- "false"
concurrency:
group: gpui-nightly-${{ github.ref }}
group: gpui-experimental-${{ github.ref }}
cancel-in-progress: false
permissions:
@@ -38,9 +36,9 @@ env:
jobs:
build-macos:
name: gpui-nightly (macos-15, arm64)
if: ${{ github.event_name != 'workflow_dispatch' || github.event.inputs.platform == 'all' || github.event.inputs.platform == 'macos' }}
runs-on: macos-15
name: gpui-experimental (macos-latest, arm64)
if: ${{ inputs.platform == 'all' || inputs.platform == 'macos' }}
runs-on: macos-latest
timeout-minutes: 60
permissions:
contents: read
@@ -64,9 +62,13 @@ jobs:
~/.cargo/registry
~/.cargo/git
.artifacts/gpui/macos/target
key: gpui-nightly-cargo-macos-arm64-${{ hashFiles('packages/app/gpui/desktop/Cargo.lock', 'packages/app/gpui/package-lock.json') }}
.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-macos-arm64-
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
@@ -89,6 +91,7 @@ jobs:
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
@@ -128,6 +131,8 @@ jobs:
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"
@@ -160,7 +165,8 @@ jobs:
--entitlements packages/app/gpui/desktop/entitlements.mac.plist \
"$app_path"
node packages/app/gpui/verify-macos-package.mjs "$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)"
@@ -181,17 +187,11 @@ jobs:
xcrun stapler staple "$app_path"
spctl --assess --type execute -v "$app_path"
out_dir="$RUNNER_TEMP/gpui-nightly-macos-arm64"
dmg_stage="$RUNNER_TEMP/dmg-stage"
rm -rf "$out_dir" "$dmg_stage"
mkdir -p "$out_dir" "$dmg_stage"
cp -R "$app_path" "$dmg_stage/"
ln -s /Applications "$dmg_stage/Applications"
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-nightly-macos-arm64.dmg"
zip_path="$out_dir/Paseo-GPUI-nightly-macos-arm64.zip"
hdiutil create -volname "Paseo GPUI" -srcfolder "$dmg_stage" -ov -format UDZO "$dmg_path"
rm -rf "$dmg_stage"
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" \
@@ -200,7 +200,6 @@ jobs:
--wait
xcrun stapler staple "$dmg_path"
xcrun stapler validate "$dmg_path"
ditto -c -k --keepParent "$app_path" "$zip_path"
- name: Verify and package unsigned macOS DMG (fork fallback)
if: steps.signing_secrets.outputs.enabled != 'true'
@@ -209,21 +208,14 @@ jobs:
repo_root="$PWD"
app_path="$repo_root/.artifacts/gpui/macos/dist/Paseo GPUI.app"
test -d "$app_path"
node packages/app/gpui/verify-macos-package.mjs "$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-nightly-macos-arm64"
dmg_stage="$RUNNER_TEMP/dmg-stage"
rm -rf "$out_dir" "$dmg_stage"
mkdir -p "$out_dir" "$dmg_stage"
cp -R "$app_path" "$dmg_stage/"
ln -s /Applications "$dmg_stage/Applications"
dmg_path="$out_dir/Paseo-GPUI-nightly-macos-arm64.dmg"
zip_path="$out_dir/Paseo-GPUI-nightly-macos-arm64.zip"
hdiutil create -volname "Paseo GPUI" -srcfolder "$dmg_stage" -ov -format UDZO "$dmg_path"
rm -rf "$dmg_stage"
ditto -c -k --keepParent "$app_path" "$zip_path"
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()
@@ -234,18 +226,18 @@ jobs:
fi
- name: Generate macOS checksums
run: node scripts/release-checksums.mjs "${{ runner.temp }}/gpui-nightly-macos-arm64" "SHA256SUMS-gpui-nightly-macos-arm64.txt"
run: node scripts/release-checksums.mjs "${{ runner.temp }}/gpui-experimental-macos-arm64" "SHA256SUMS-gpui-experimental-macos-arm64.txt"
- name: Upload macOS nightly artifact
- name: Upload macOS experimental artifact
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: gpui-nightly-macos-arm64
path: ${{ runner.temp }}/gpui-nightly-macos-arm64
name: gpui-experimental-macos-arm64
path: ${{ runner.temp }}/gpui-experimental-macos-arm64
retention-days: 7
build-linux:
name: gpui-nightly (ubuntu-24.04, x64)
if: ${{ github.event_name != 'workflow_dispatch' || github.event.inputs.platform == 'all' || github.event.inputs.platform == 'linux' }}
name: gpui-experimental (ubuntu-24.04, x64)
if: ${{ inputs.platform == 'all' || inputs.platform == 'linux' }}
runs-on: ubuntu-24.04
timeout-minutes: 60
permissions:
@@ -270,9 +262,13 @@ jobs:
~/.cargo/registry
~/.cargo/git
.artifacts/gpui/linux/target
key: gpui-nightly-cargo-linux-x64-${{ hashFiles('packages/app/gpui/desktop/Cargo.lock', 'packages/app/gpui/package-lock.json') }}
.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-linux-x64-
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: |
@@ -284,6 +280,8 @@ jobs:
ninja-build \
pkg-config \
libssl-dev \
libfontconfig-dev \
libfreetype-dev \
libvulkan-dev \
libwayland-dev \
libx11-xcb-dev \
@@ -307,30 +305,34 @@ jobs:
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-nightly-linux-x64"
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-nightly-linux-x64" "SHA256SUMS-gpui-nightly-linux-x64.txt"
run: node scripts/release-checksums.mjs "${{ runner.temp }}/gpui-experimental-linux-x64" "SHA256SUMS-gpui-experimental-linux-x64.txt"
- name: Upload Linux nightly artifact
- name: Upload Linux experimental artifact
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: gpui-nightly-linux-x64
path: ${{ runner.temp }}/gpui-nightly-linux-x64
name: gpui-experimental-linux-x64
path: ${{ runner.temp }}/gpui-experimental-linux-x64
retention-days: 7
publish:
name: Publish gpui-nightly prerelease
name: Publish gpui-experimental prerelease
needs: [build-macos, build-linux]
if: ${{ !cancelled() && (github.event_name != 'workflow_dispatch' || github.event.inputs.publish != 'false') && needs.build-macos.result == 'success' && needs.build-linux.result == 'success' }}
if: ${{ !cancelled() && inputs.publish != 'false' && needs.build-macos.result == 'success' && needs.build-linux.result == 'success' }}
concurrency:
group: gpui-nightly-release
group: gpui-experimental-release
cancel-in-progress: false
runs-on: ubuntu-latest
permissions:
@@ -344,142 +346,124 @@ jobs:
with:
node-version: "22"
- name: Download built nightly artifacts
- name: Download built experimental artifacts
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
with:
pattern: gpui-nightly-*
path: ${{ runner.temp }}/nightly-assets
pattern: gpui-experimental-*
path: ${{ runner.temp }}/experimental-assets
merge-multiple: true
- name: Publish rolling gpui-nightly prerelease
- name: Publish gpui-experimental prerelease
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
assets_dir="${RUNNER_TEMP}/nightly-assets"
notes_file="${RUNNER_TEMP}/gpui-nightly-notes.md"
build_date="$(date -u +"%Y-%m-%d %H:%M UTC")"
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"
cat > "${assets_dir}/SHA256SUMS-gpui-nightly.txt" <<'EOF'
EOF
rm -f "${assets_dir}/SHA256SUMS-gpui-nightly.txt"
if compgen -G "${assets_dir}/SHA256SUMS-gpui-nightly-*.txt" > /dev/null; then
cat "${assets_dir}"/SHA256SUMS-gpui-nightly-*.txt > "${assets_dir}/SHA256SUMS-gpui-nightly.txt"
rm -f "${assets_dir}"/SHA256SUMS-gpui-nightly-*.txt
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 "## Paseo GPUI Nightly Preview"
echo "This build is the native desktop app for Paseo. It runs on GPUI instead of Electron."
echo ""
echo "- **Build date:** ${build_date}"
echo "- **Commit:** \`${GITHUB_SHA}\` (\`${short_sha}\`)"
echo "- **JS engine:** V8 14.6 (\`@react-native-gpui/v8\`)"
echo "- **Targets:** macOS arm64 (\`.dmg\`, \`.zip\`), Linux x64 (\`.tar.gz\`)"
echo "It is under heavy development and is not ready for daily use. It is not a Paseo beta."
echo ""
echo "### Preview Limitations"
echo "If you want to use Paseo normally, download the [latest release](https://github.com/getpaseo/paseo/releases/latest)."
echo ""
echo "- Connects to a separately running Paseo daemon (defaults to \`localhost:6767\` or remote hosts); does not bundle the daemon."
echo "- \`HtmlFrame\` / HTML previews and Mermaid diagrams render placeholders / source fallback (no embedded WebView backend)."
echo "- Embedded terminal and Skia diff views are not yet ported to GPUI."
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-nightly.txt" ]]; then
cat "${assets_dir}/SHA256SUMS-gpui-nightly.txt"
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}"
tag="gpui-nightly"
staging_tag="gpui-nightly-stage-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}"
repo="${{ github.repository }}"
staging_tag="gpui-experimental-stage-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}"
staging_id=""
old_id=""
old_sha=""
swapping="false"
created_tag=""
cleanup_staging() {
local ec=$?
set +e
if [[ "$swapping" == "true" && $ec -ne 0 && -n "$old_id" && -n "$old_sha" ]]; then
gh api "repos/${{ github.repository }}/git/refs/tags/${tag}" \
-X PATCH -f sha="${old_sha}" -F force=true > /dev/null 2>&1 || true
gh api "repos/${{ github.repository }}/releases/${old_id}" \
-X PATCH -f tag_name="$tag" -F draft=false -F prerelease=true -f make_latest="false" > /dev/null 2>&1 || true
return 0
if [[ -n "$staging_id" ]]; then
gh api "repos/${repo}/releases/${staging_id}" -X DELETE > /dev/null 2>&1 || true
fi
if [[ -n "$staging_id" && "$swapping" != "true" ]]; then
gh api "repos/${{ github.repository }}/releases/${staging_id}" -X DELETE > /dev/null 2>&1 || true
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 touch
# the public gpui-nightly release or its downloads.
# 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 "${{ github.repository }}" \
--title "Paseo GPUI Nightly (${short_sha})" \
--repo "$repo" \
--title "$release_title" \
--notes-file "${notes_file}" \
--draft \
--prerelease \
--latest=false \
--target "${GITHUB_SHA}"
staging_id="$(gh release view "$staging_tag" --repo "${{ github.repository }}" --json databaseId --jq '.databaseId')"
node scripts/upload-release-assets.mjs "$staging_tag" "${assets_dir}" "${{ github.repository }}"
staging_id="$(gh release view "$staging_tag" --repo "$repo" --json databaseId --jq '.databaseId')"
node scripts/upload-release-assets.mjs "$staging_tag" "${assets_dir}" "$repo"
uploaded_assets="$(gh release view "$staging_tag" --repo "${{ github.repository }}" --json assets --jq '.assets[].name')"
for file in "${assets_dir}"/*; do
[[ -f "$file" ]] || continue
name="$(basename "$file")"
if ! grep -Fxq "$name" <<< "$uploaded_assets"; then
echo "::error::Missing staged release asset: ${name}"
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
if old_id="$(gh release view "$tag" --repo "${{ github.repository }}" --json databaseId --jq '.databaseId' 2>/dev/null)"; then
old_sha="$(gh api "repos/${{ github.repository }}/git/refs/tags/${tag}" --jq '.object.sha' 2>/dev/null || true)"
swapping="true"
# Hold the prior release as a draft rather than deleting it before promotion completes.
gh api "repos/${{ github.repository }}/releases/${old_id}" \
-X PATCH \
-F draft=true > /dev/null
else
old_id=""
swapping="true"
fi
gh api "repos/${repo}/git/refs" \
-X POST \
-f ref="refs/tags/${tag}" \
-f sha="${GITHUB_SHA}"
created_tag="$tag"
if gh api "repos/${{ github.repository }}/git/refs/tags/${tag}" > /dev/null 2>&1; then
gh api "repos/${{ github.repository }}/git/refs/tags/${tag}" \
-X PATCH \
-f sha="${GITHUB_SHA}" \
-F force=true
else
gh api "repos/${{ github.repository }}/git/refs" \
-X POST \
-f ref="refs/tags/${tag}" \
-f sha="${GITHUB_SHA}"
fi
promoted_draft="$(gh api "repos/${{ github.repository }}/releases/${staging_id}" \
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"
echo "::error::Promoted release is still a draft" >&2
exit 1
fi
swapping="false"
staging_id=""
if [[ -n "$old_id" ]]; then
gh api "repos/${{ github.repository }}/releases/${old_id}" -X DELETE > /dev/null 2>&1 || true
fi
created_tag=""
+3 -5
View File
@@ -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",
+19 -27
View File
@@ -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");
+27 -1
View File
@@ -180,7 +180,7 @@ The following are not feature-parity claims:
| Image conversion/image clipboard | Unavailable. The picker accepts PNG/JPEG without conversion. |
| Mermaid/HTML/document previews | Mermaid and HTML show source. Document previews report unavailable. No embedded browser backend. |
| Terminals | The mobile view expects an Expo `PaseoTerminal` component. No GPUI implementation yet. |
| Diffs | The mobile surface uses React Native Skia. No GPUI drawing backend yet. |
| 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. |
@@ -288,3 +288,29 @@ 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,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;
+50
View File
@@ -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" }),
);
});
+8
View File
@@ -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";
+1
View File
@@ -5530,6 +5530,7 @@ version = "0.1.0"
dependencies = [
"gpui",
"gpui_platform",
"image",
"react-native-gpui",
"rn-gpui-autolink",
"rn-gpui-enriched-markdown",
+3
View File
@@ -52,6 +52,9 @@ rn-gpui-module = { path = "../node_modules/@react-native-gpui/core/ReactGpui/rn-
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" }
+8
View File
@@ -1,4 +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" } }
}
@@ -1,4 +1,8 @@
{
"icon": "../../../desktop/assets/icon.icns",
"window": {
"trafficLightPosition": { "x": 16, "y": 10 }
},
"bundle": {
"macos": {
"entitlements": "desktop/entitlements.mac.adhoc.plist"
+26 -4
View File
@@ -17,14 +17,36 @@ fn main() {
env!("RN_GPUI_APP_ID"),
)
.js_engine("v8")
.window_title("Paseo GPUI")
.window_size(1024.0, 768.0)
.dev_menu(true)
.configure_window(|options| {
.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));
}
}
+1 -2
View File
@@ -1,6 +1,5 @@
/* oxlint-disable import/no-unassigned-import -- Install globals before app modules evaluate. */
import "./adapters/intl";
import "../src/polyfills/install-early";
import "./bootstrap";
import "../src/styles/unistyles";
import { AppRegistry } from "react-native";
import { RootApp } from "../src/root-app";
+106 -2
View File
@@ -1,6 +1,7 @@
import { realpathSync, statSync } from "node:fs";
import { readFileSync, realpathSync, statSync } from "node:fs";
import { createRequire } from "node:module";
import path from "node:path";
import ts from "typescript";
import { afterEach, describe, expect, test } from "vitest";
const require = createRequire(import.meta.url);
@@ -202,6 +203,47 @@ const CASES = [
native: path.join(APP_DIR, "src/components/ui/press-highlight.native.tsx"),
web: path.join(APP_DIR, "src/components/ui/press-highlight.tsx"),
},
{
label: "window chrome host",
origin: path.join(APP_DIR, "src/utils/desktop-window.tsx"),
specifier: "../desktop/window-chrome-host",
gpui: path.join(APP_DIR, "src/desktop/window-chrome-host.gpui.ts"),
native: path.join(APP_DIR, "src/desktop/window-chrome-host.ts"),
web: path.join(APP_DIR, "src/desktop/window-chrome-host.web.ts"),
},
{
label: "titlebar drag surface",
origin: path.join(APP_DIR, "src/components/headers/screen-header.tsx"),
specifier: "../desktop/titlebar-drag-surface",
gpui: path.join(APP_DIR, "src/components/desktop/titlebar-drag-surface.gpui.tsx"),
native: path.join(APP_DIR, "src/components/desktop/titlebar-drag-surface.tsx"),
web: path.join(APP_DIR, "src/components/desktop/titlebar-drag-surface.web.tsx"),
},
{
label: "caption button",
origin: path.join(APP_DIR, "src/components/desktop/window-controls.tsx"),
specifier: "./caption-button",
gpui: path.join(APP_DIR, "src/components/desktop/caption-button.gpui.tsx"),
native: path.join(APP_DIR, "src/components/desktop/caption-button.tsx"),
web: path.join(APP_DIR, "src/components/desktop/caption-button.tsx"),
},
{
label: "diff surface",
origin: path.join(APP_DIR, "src/git/diff-document/index.tsx"),
specifier: "./surface",
gpui: path.join(APP_DIR, "src/git/diff-document/surface.gpui.tsx"),
native: path.join(APP_DIR, "src/git/diff-document/surface.native.tsx"),
web: path.join(APP_DIR, "src/git/diff-document/surface.web.tsx"),
},
{
label: "window layout",
origin: path.join(APP_DIR, "src/utils/desktop-window.tsx"),
specifier: "../window-layout",
gpui: path.join(APP_DIR, "src/window-layout/index.gpui.tsx"),
ios: path.join(APP_DIR, "src/window-layout/index.ios.tsx"),
native: path.join(APP_DIR, "src/window-layout/index.tsx"),
web: path.join(APP_DIR, "src/window-layout/index.tsx"),
},
];
afterEach(() => {
@@ -223,6 +265,31 @@ describe("GPUI Metro platform rule", () => {
).toBe(item.gpui);
}
// GPUI must resolve @/ alias specifiers for window chrome modules to .gpui.*.
for (const [alias, expected] of [
[
"@/desktop/window-chrome-host",
path.join(APP_DIR, "src/desktop/window-chrome-host.gpui.ts"),
],
[
"@/components/desktop/titlebar-drag-surface",
path.join(APP_DIR, "src/components/desktop/titlebar-drag-surface.gpui.tsx"),
],
[
"@/components/desktop/caption-button",
path.join(APP_DIR, "src/components/desktop/caption-button.gpui.tsx"),
],
["@/window-layout", path.join(APP_DIR, "src/window-layout/index.gpui.tsx")],
] as const) {
const ctx = createResolutionContext(
path.join(APP_DIR, "src/app/_layout.tsx"),
config.resolver.sourceExts,
true,
resolver,
);
expect(config.resolver.resolveRequest(ctx, alias, "desktop").filePath, alias).toBe(expected);
}
// GPUI must not pick Electron's .electron.* files as "desktop".
const browserCtx = createResolutionContext(
path.join(APP_DIR, "src/components/split-container.tsx"),
@@ -259,9 +326,46 @@ describe("GPUI Metro platform rule", () => {
item.specifier,
target.platform,
).filePath;
expect(filePath, `${target.platform}: ${item.label}`).toBe(item[target.expected]);
const expected =
target.platform === "ios" && "ios" in item && item.ios ? item.ios : item[target.expected];
expect(filePath, `${target.platform}: ${item.label}`).toBe(expected);
expect(filePath).not.toContain(".gpui.");
}
}
});
test("the GPUI diff surface's import graph never reaches React Native Skia", () => {
const config = require(path.join(GPUI_DIR, "desktop/metro.config.js")) as MetroConfig;
const resolver = require(require.resolve("metro-resolver", { paths: [GPUI_DIR] })) as {
resolve: (...args: unknown[]) => unknown;
};
const entry = path.join(APP_DIR, "src/git/diff-document/surface.gpui.tsx");
const sourceRoot = path.join(APP_DIR, "src") + path.sep;
const visited = new Set<string>();
const bareSpecifiers = new Set<string>();
const pending = [entry];
while (pending.length > 0) {
const file = pending.pop()!;
if (visited.has(file)) continue;
visited.add(file);
const { importedFiles } = ts.preProcessFile(readFileSync(file, "utf8"), true, true);
for (const { fileName: specifier } of importedFiles) {
if (!specifier.startsWith(".") && !specifier.startsWith("@/")) {
bareSpecifiers.add(specifier);
continue;
}
const ctx = createResolutionContext(file, config.resolver.sourceExts, true, resolver);
const resolved = config.resolver.resolveRequest(ctx, specifier, "desktop").filePath;
if (resolved?.startsWith(sourceRoot) && /\.[cm]?[jt]sx?$/.test(resolved)) {
pending.push(resolved);
}
}
}
expect(visited.size).toBeGreaterThan(1);
expect([...bareSpecifiers].filter((name) => name.includes("react-native-skia"))).toEqual([]);
expect(
[...visited].filter((file) => /diff-document[\\/](text|paint)\.native\./.test(file)),
).toEqual([]);
});
});
+102
View File
@@ -0,0 +1,102 @@
import { spawn, execFileSync } from "node:child_process";
import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const project = path.dirname(fileURLToPath(import.meta.url));
const root = path.resolve(project, "../../..");
export interface NativeFixtureRun {
/** Fixture entry file in this directory, bundled for the desktop platform. */
fixture: string;
/** Directory-name prefix under `.artifacts/gpui/`. */
name: string;
/** JSON-serialisable values the bundle reads from `globalThis` before it loads. */
globals: Record<string, unknown>;
/** Console line that ends a passing run. A line containing `failMarker` fails it. */
completeMarker: string;
failMarker: string;
timeoutMs: number;
/** Lower the descriptor limit, as Finder launches the app with. */
descriptorLimit?: number;
}
/**
* Bundles a fixture with the app's Metro config and runs it in the compiled
* GPUI binary (V8), resolving with everything the app printed.
*/
export async function runNativeFixture(binary: string, run: NativeFixtureRun): Promise<string> {
mkdirSync(path.join(root, ".artifacts/gpui"), { recursive: true });
const artifacts = mkdtempSync(path.join(root, ".artifacts/gpui", `${run.name}-`));
const bundle = path.join(artifacts, "regression.bundle");
execFileSync(
process.execPath,
[
"node_modules/react-native/cli.js",
"bundle",
"--platform",
"desktop",
"--entry-file",
run.fixture,
"--config",
"desktop/metro.config.js",
"--bundle-output",
bundle,
"--dev",
"false",
"--max-workers",
"1",
],
{ cwd: project, env: { ...process.env, PASEO_RENDERER: "gpui" }, timeout: 300_000 },
);
const prelude = Object.entries(run.globals)
.map(([key, value]) => `globalThis.${key} = ${JSON.stringify(value)};\n`)
.join("");
writeFileSync(bundle, `${prelude}${readFileSync(bundle, "utf8")}`);
const limit = run.descriptorLimit ? `ulimit -n ${run.descriptorLimit}; ` : "";
const app = spawn("/bin/sh", ["-c", `${limit}exec "$@"`, "gpui-test", binary], {
env: {
...process.env,
RN_GPUI_BUNDLE: bundle,
RN_GPUI_APP_ID: `sh.paseo.gpui.${run.name}-test`,
XDG_DATA_HOME: path.join(artifacts, "data"),
// macOS and Windows ignore XDG_DATA_HOME; this keeps each run on its own saved hosts everywhere.
RN_GPUI_APP_DATA_DIR: path.join(artifacts, "app-data"),
},
stdio: ["ignore", "pipe", "pipe"],
});
let output = "";
try {
await new Promise<void>((resolve, reject) => {
const timeout = setTimeout(
() => reject(new Error(`Native ${run.name} test timed out:\n${output}`)),
run.timeoutMs,
);
const collect = (chunk: Buffer) => {
output += chunk.toString();
if (output.includes(run.completeMarker)) {
clearTimeout(timeout);
resolve();
} else if (output.includes(run.failMarker)) {
clearTimeout(timeout);
reject(new Error(output));
}
};
app.stdout.on("data", collect);
app.stderr.on("data", collect);
app.once("error", (error) => {
clearTimeout(timeout);
reject(error);
});
app.once("exit", (code, signal) => {
clearTimeout(timeout);
reject(new Error(`Native process exited (${code}, ${signal}):\n${output}`));
});
});
return output;
} finally {
writeFileSync(path.join(artifacts, "native.log"), output);
app.kill("SIGTERM");
}
}
+25 -25
View File
@@ -15,17 +15,17 @@
"@formatjs/intl-numberformat": "^9.5.0",
"@formatjs/intl-pluralrules": "^6.4.0",
"@formatjs/intl-segmenter": "^12.3.0",
"@react-native-gpui/codegen": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-5/react-native-gpui-codegen-0.87.0-alpha.2.tgz",
"@react-native-gpui/core": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-5/react-native-gpui-core-0.87.0-alpha.5.tgz",
"@react-native-gpui/fs": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-5/react-native-gpui-fs-0.0.1-alpha.1.tgz",
"@react-native-gpui/gesture-handler": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-5/react-native-gpui-gesture-handler-3.3.0-alpha.1.tgz",
"@react-native-gpui/hermes": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-5/react-native-gpui-hermes-0.87.0-alpha.1.tgz",
"@react-native-gpui/reanimated": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-5/react-native-gpui-reanimated-4.7.0-alpha.1.tgz",
"@react-native-gpui/safe-area-context": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-5/react-native-gpui-safe-area-context-5.10.0-alpha.0.tgz",
"@react-native-gpui/screens": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-5/react-native-gpui-screens-4.28.0-alpha.2.tgz",
"@react-native-gpui/svg": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-5/react-native-gpui-svg-15.15.0-alpha.1.tgz",
"@react-native-gpui/v8": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-5/react-native-gpui-v8-0.87.0-alpha.0.tgz",
"@react-native-gpui/worklets": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-5/react-native-gpui-worklets-0.13.0-alpha.1.tgz",
"@react-native-gpui/codegen": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-6/react-native-gpui-codegen-0.87.0-alpha.2.tgz",
"@react-native-gpui/core": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-6/react-native-gpui-core-0.87.0-alpha.5.tgz",
"@react-native-gpui/fs": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-6/react-native-gpui-fs-0.0.1-alpha.1.tgz",
"@react-native-gpui/gesture-handler": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-6/react-native-gpui-gesture-handler-3.3.0-alpha.1.tgz",
"@react-native-gpui/hermes": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-6/react-native-gpui-hermes-0.87.0-alpha.1.tgz",
"@react-native-gpui/reanimated": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-6/react-native-gpui-reanimated-4.7.0-alpha.1.tgz",
"@react-native-gpui/safe-area-context": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-6/react-native-gpui-safe-area-context-5.10.0-alpha.0.tgz",
"@react-native-gpui/screens": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-6/react-native-gpui-screens-4.28.0-alpha.2.tgz",
"@react-native-gpui/svg": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-6/react-native-gpui-svg-15.15.0-alpha.1.tgz",
"@react-native-gpui/v8": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-6/react-native-gpui-v8-0.87.0-alpha.0.tgz",
"@react-native-gpui/worklets": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-6/react-native-gpui-worklets-0.13.0-alpha.1.tgz",
"@react-native/assets-registry": "^0.87.1",
"react": "19.2.3",
"react-native": "0.87.1",
@@ -38,7 +38,7 @@
},
"devDependencies": {
"@react-native-community/cli": "20.2.0",
"@react-native-gpui/cli": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-5/react-native-gpui-cli-0.87.0-alpha.5.tgz",
"@react-native-gpui/cli": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-6/react-native-gpui-cli-0.87.0-alpha.5.tgz",
"@react-native/babel-preset": "0.87.1",
"@react-native/metro-config": "0.87.1",
"typescript": "^5.8.3"
@@ -1535,7 +1535,7 @@
},
"node_modules/@react-native-gpui/cli": {
"version": "0.87.0-alpha.5",
"resolved": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-5/react-native-gpui-cli-0.87.0-alpha.5.tgz",
"resolved": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-6/react-native-gpui-cli-0.87.0-alpha.5.tgz",
"integrity": "sha512-UFtxDVt2+S/S4v0GRSM611jfPbE76Ah8/7F4sm/OgfxnyHFKrc6pFXlDYZvWx5i8jnH0WQESoH4azUneR62Nxw==",
"dev": true,
"license": "MIT",
@@ -1545,7 +1545,7 @@
},
"node_modules/@react-native-gpui/codegen": {
"version": "0.87.0-alpha.2",
"resolved": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-5/react-native-gpui-codegen-0.87.0-alpha.2.tgz",
"resolved": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-6/react-native-gpui-codegen-0.87.0-alpha.2.tgz",
"integrity": "sha512-VIQDIUELddQTWI5NyAXkopzwCGtEh28LQDpNKsWn4kfomxK1uJ2/TaDjnokw7oQ6ZX/2nJL4hPsmOapvpdpgxg==",
"license": "MIT",
"dependencies": {
@@ -1554,8 +1554,8 @@
},
"node_modules/@react-native-gpui/core": {
"version": "0.87.0-alpha.5",
"resolved": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-5/react-native-gpui-core-0.87.0-alpha.5.tgz",
"integrity": "sha512-KMP26Y4940QDk+MRF3jPmq3E8Pg3y0c6/Uln2IWrTbJ4+BdQQsWw+v3ykyj9iPPA1IlQLEWaBVDoq7L6DXiXVg==",
"resolved": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-6/react-native-gpui-core-0.87.0-alpha.5.tgz",
"integrity": "sha512-0rGzTzIJ1/xsxIYxnvx6JNMVrGgu+cW/3MGLtrlJy3/lS0Lkmx6Havv6zjQKnF40FZemFFeV/DfQ/QG32XPK8Q==",
"license": "MIT",
"dependencies": {
"@react-native-gpui/codegen": "0.87.0-alpha.2",
@@ -1569,7 +1569,7 @@
},
"node_modules/@react-native-gpui/fs": {
"version": "0.0.1-alpha.1",
"resolved": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-5/react-native-gpui-fs-0.0.1-alpha.1.tgz",
"resolved": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-6/react-native-gpui-fs-0.0.1-alpha.1.tgz",
"integrity": "sha512-rY8P9oeP/b5bD4Eqyar+7HG1zii0SeqNkTRFnxrYe9kFBbWZjIlHIuI3gMJzJxeDklbGkx4P4DgpLiXQafv3rQ==",
"license": "MIT",
"peerDependencies": {
@@ -1578,7 +1578,7 @@
},
"node_modules/@react-native-gpui/gesture-handler": {
"version": "3.3.0-alpha.1",
"resolved": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-5/react-native-gpui-gesture-handler-3.3.0-alpha.1.tgz",
"resolved": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-6/react-native-gpui-gesture-handler-3.3.0-alpha.1.tgz",
"integrity": "sha512-r49zj2PVzKNdsktSFu7nr6lcHLaJLqEwU/NYMxKmoOxL3Wew4HWHIgq9wskQI30CrRAwCdwqXMbgMdTIid+GjQ==",
"license": "MIT",
"peerDependencies": {
@@ -1590,13 +1590,13 @@
},
"node_modules/@react-native-gpui/hermes": {
"version": "0.87.0-alpha.1",
"resolved": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-5/react-native-gpui-hermes-0.87.0-alpha.1.tgz",
"resolved": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-6/react-native-gpui-hermes-0.87.0-alpha.1.tgz",
"integrity": "sha512-Hn7rdXbmOi63i5u02j2dFTyBN73573tsxigu2zS1qo0jCgezc/LwAZruU3p94UQ4/GU2OIyvro3zCSvT+qzr2w==",
"license": "MIT"
},
"node_modules/@react-native-gpui/reanimated": {
"version": "4.7.0-alpha.1",
"resolved": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-5/react-native-gpui-reanimated-4.7.0-alpha.1.tgz",
"resolved": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-6/react-native-gpui-reanimated-4.7.0-alpha.1.tgz",
"integrity": "sha512-eclRX3zcObjBfnn6QTkIah9lqc1raoV6X4yC84AF7PZVp+5OddpXlwMxlZSVLdGxSfQ6YjOih3LphrzUNJkahA==",
"license": "MIT",
"peerDependencies": {
@@ -1608,7 +1608,7 @@
},
"node_modules/@react-native-gpui/safe-area-context": {
"version": "5.10.0-alpha.0",
"resolved": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-5/react-native-gpui-safe-area-context-5.10.0-alpha.0.tgz",
"resolved": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-6/react-native-gpui-safe-area-context-5.10.0-alpha.0.tgz",
"integrity": "sha512-j+RyCz5J+rQW4FYYNCMvoQSAPnAmgI0iPcCTGmKzSwRcFEx6GZJ8UbosxW1+YbsmiL8hIdEF3baOMYFkr068ZA==",
"license": "MIT",
"peerDependencies": {
@@ -1618,7 +1618,7 @@
},
"node_modules/@react-native-gpui/screens": {
"version": "4.28.0-alpha.2",
"resolved": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-5/react-native-gpui-screens-4.28.0-alpha.2.tgz",
"resolved": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-6/react-native-gpui-screens-4.28.0-alpha.2.tgz",
"integrity": "sha512-ynH6vfr7kIC2tYTSpfZul1i1NKaSiVYJtNyW+/zT5lO3BfuM4Ya68nr0Zc1LUEuczqN2kWpsuQp9YulSql156Q==",
"license": "MIT",
"peerDependencies": {
@@ -1628,7 +1628,7 @@
},
"node_modules/@react-native-gpui/svg": {
"version": "15.15.0-alpha.1",
"resolved": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-5/react-native-gpui-svg-15.15.0-alpha.1.tgz",
"resolved": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-6/react-native-gpui-svg-15.15.0-alpha.1.tgz",
"integrity": "sha512-8rgCGIzRfOtUwDCHseAnxonVvmd0qM3dyH7X5p6kCAMuJok2nD/zR45CobxbtWS0dU+nU/T6MJ6th6ENMmRDVg==",
"license": "MIT",
"peerDependencies": {
@@ -1638,13 +1638,13 @@
},
"node_modules/@react-native-gpui/v8": {
"version": "0.87.0-alpha.0",
"resolved": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-5/react-native-gpui-v8-0.87.0-alpha.0.tgz",
"resolved": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-6/react-native-gpui-v8-0.87.0-alpha.0.tgz",
"integrity": "sha512-NhVYj74T+ZDPDS4EoMaguLeW+dbC+aI+R1JlPJmpPal6MNdgz7iwwo18mWWQ+B0hTz4ov0WB3h3um9rprl8jGw==",
"license": "MIT"
},
"node_modules/@react-native-gpui/worklets": {
"version": "0.13.0-alpha.1",
"resolved": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-5/react-native-gpui-worklets-0.13.0-alpha.1.tgz",
"resolved": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-6/react-native-gpui-worklets-0.13.0-alpha.1.tgz",
"integrity": "sha512-TTN9CFwirHVojJM4s6UHUPU/3qA1zdCcUrokS5gf+G9lmdpKKV3sCr7Cqpdr8MzAAC/4ohpou13JZIbnyP3dSg==",
"license": "MIT",
"peerDependencies": {
+12 -12
View File
@@ -10,17 +10,17 @@
"@formatjs/intl-numberformat": "^9.5.0",
"@formatjs/intl-pluralrules": "^6.4.0",
"@formatjs/intl-segmenter": "^12.3.0",
"@react-native-gpui/codegen": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-5/react-native-gpui-codegen-0.87.0-alpha.2.tgz",
"@react-native-gpui/core": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-5/react-native-gpui-core-0.87.0-alpha.5.tgz",
"@react-native-gpui/fs": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-5/react-native-gpui-fs-0.0.1-alpha.1.tgz",
"@react-native-gpui/gesture-handler": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-5/react-native-gpui-gesture-handler-3.3.0-alpha.1.tgz",
"@react-native-gpui/hermes": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-5/react-native-gpui-hermes-0.87.0-alpha.1.tgz",
"@react-native-gpui/reanimated": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-5/react-native-gpui-reanimated-4.7.0-alpha.1.tgz",
"@react-native-gpui/safe-area-context": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-5/react-native-gpui-safe-area-context-5.10.0-alpha.0.tgz",
"@react-native-gpui/screens": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-5/react-native-gpui-screens-4.28.0-alpha.2.tgz",
"@react-native-gpui/svg": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-5/react-native-gpui-svg-15.15.0-alpha.1.tgz",
"@react-native-gpui/v8": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-5/react-native-gpui-v8-0.87.0-alpha.0.tgz",
"@react-native-gpui/worklets": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-5/react-native-gpui-worklets-0.13.0-alpha.1.tgz",
"@react-native-gpui/codegen": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-6/react-native-gpui-codegen-0.87.0-alpha.2.tgz",
"@react-native-gpui/core": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-6/react-native-gpui-core-0.87.0-alpha.5.tgz",
"@react-native-gpui/fs": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-6/react-native-gpui-fs-0.0.1-alpha.1.tgz",
"@react-native-gpui/gesture-handler": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-6/react-native-gpui-gesture-handler-3.3.0-alpha.1.tgz",
"@react-native-gpui/hermes": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-6/react-native-gpui-hermes-0.87.0-alpha.1.tgz",
"@react-native-gpui/reanimated": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-6/react-native-gpui-reanimated-4.7.0-alpha.1.tgz",
"@react-native-gpui/safe-area-context": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-6/react-native-gpui-safe-area-context-5.10.0-alpha.0.tgz",
"@react-native-gpui/screens": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-6/react-native-gpui-screens-4.28.0-alpha.2.tgz",
"@react-native-gpui/svg": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-6/react-native-gpui-svg-15.15.0-alpha.1.tgz",
"@react-native-gpui/v8": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-6/react-native-gpui-v8-0.87.0-alpha.0.tgz",
"@react-native-gpui/worklets": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-6/react-native-gpui-worklets-0.13.0-alpha.1.tgz",
"@react-native/assets-registry": "^0.87.1",
"react": "19.2.3",
"react-native": "0.87.1",
@@ -33,7 +33,7 @@
},
"devDependencies": {
"@react-native-community/cli": "20.2.0",
"@react-native-gpui/cli": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-5/react-native-gpui-cli-0.87.0-alpha.5.tgz",
"@react-native-gpui/cli": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-6/react-native-gpui-cli-0.87.0-alpha.5.tgz",
"@react-native/babel-preset": "0.87.1",
"@react-native/metro-config": "0.87.1",
"typescript": "^5.8.3"
+123
View File
@@ -0,0 +1,123 @@
import { createServer } from "node:http";
import { once } from "node:events";
import { Server as WebSocketServer } from "ws";
import {
createDaemonChannel,
exportPublicKey,
generateKeyPair,
openDaemonSecureChannel,
type Transport,
} from "@getpaseo/relay/e2ee";
export type EndpointSecurity = "protected" | "legacy";
export interface FixtureDaemon {
serverId: string;
hostname: string;
security: EndpointSecurity;
}
// A daemon behind a relay: accepts client sockets, runs the daemon half of the
// E2EE handshake, and answers the session messages the client sends.
export async function startRelayFixture(daemon: FixtureDaemon) {
const daemonKeys = generateKeyPair();
const http = createServer();
const sockets = new WebSocketServer({ server: http });
const decryptedFromClient: unknown[] = [];
sockets.on("connection", (socket) => {
const wire: Transport = {
send: (data) => socket.send(data),
close: (code, reason) => socket.close(code, reason),
onmessage: null,
onclose: null,
onerror: null,
};
// `ws` resolves to React Native's 6.x from this directory: it hands text as a
// string and binary as a Buffer, with no `isBinary` argument.
socket.on("message", (data: string | Buffer) => {
const isBinary = typeof data !== "string";
wire.onmessage?.({
data: isBinary
? (data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength) as ArrayBuffer)
: data,
isBinary,
});
});
socket.on("close", (code, reason) => wire.onclose?.(code, reason.toString()));
const events = {
onmessage: (data: string | ArrayBuffer) => {
if (typeof data !== "string") return;
const message = JSON.parse(data);
decryptedFromClient.push(message);
const reply = replyTo(daemon, message);
if (reply) void channel.then((secure) => secure.send(JSON.stringify(reply)));
},
};
const channel =
daemon.security === "protected"
? openDaemonSecureChannel(wire, {
daemonKeyPair: daemonKeys,
// A client that falls back to legacy encryption must fail this check.
minimumMode: "protected",
events,
})
: createDaemonChannel(wire, daemonKeys, events);
void channel.catch(() => {});
});
http.listen(0, "127.0.0.1");
await once(http, "listening");
const address = http.address();
if (!address || typeof address === "string") throw new Error("Missing relay port");
const offer = {
v: 2,
serverId: daemon.serverId,
daemonPublicKeyB64: exportPublicKey(daemonKeys.publicKey),
relay: { endpoint: `127.0.0.1:${address.port}`, useTls: false },
};
const link = `https://app.paseo.sh/#offer=${Buffer.from(JSON.stringify(offer)).toString("base64url")}`;
return {
link,
hostLabel: daemon.hostname,
decryptedFromClient,
async close() {
for (const socket of sockets.clients) socket.terminate();
await new Promise<void>((resolve) => sockets.close(() => resolve()));
await new Promise<void>((resolve) => http.close(() => resolve()));
},
};
}
function replyTo(
daemon: FixtureDaemon,
message: { type?: string; message?: { type?: string; requestId?: string } },
) {
if (message.type === "hello") {
return {
type: "session",
message: {
type: "status",
payload: {
status: "server_info",
serverId: daemon.serverId,
hostname: daemon.hostname,
version: "0.12.0",
},
},
};
}
if (message.type === "session" && message.message?.type === "ping") {
const now = Date.now();
return {
type: "session",
message: {
type: "pong",
payload: {
requestId: message.message.requestId,
serverReceivedAt: now,
serverSentAt: now,
},
},
};
}
return null;
}
@@ -0,0 +1,78 @@
/* oxlint-disable import/no-unassigned-import -- Install runtime globals before app modules evaluate. */
import "./bootstrap";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { AppRegistry } from "react-native";
import { HostRuntimeStore } from "../src/runtime/host-runtime";
AppRegistry.registerComponent("Paseo", () => () => null);
// The native test supplies a pairing link and the hostname its daemon reports,
// per daemon, before loading this bundle.
const targets = globalThis.__relayRegressionTargets;
function describe(error) {
return error instanceof Error ? `${error.message}\n${error.stack}` : String(error);
}
async function waitFor(read, what) {
for (let attempt = 0; attempt < 200; attempt++) {
const value = read();
if (value) return value;
await new Promise((resolve) => setTimeout(resolve, 50));
}
throw new Error(`timed out waiting for ${what}`);
}
async function pair(store, link) {
// The pairing screen asks the user to confirm a new host; answer as the user does.
const unsubscribe = store.subscribeHostConfirmation(() => {
const pending = store.getPendingHostConfirmation();
if (pending) store.answerHostConfirmation(pending.id, true);
});
try {
return await store.importConnectionLink(link, "hostRoot");
} finally {
unsubscribe();
}
}
async function pingOverRelay(store, serverId) {
const client = await waitFor(() => store.getClient(serverId), "a connected relay client");
await client.ping({ timeoutMs: 10_000 });
}
// The app's own E2E switch: boot() loads the saved hosts and stops, instead of
// also probing localhost:6767 (or EXPO_PUBLIC_LOCAL_DAEMON), so the run reaches
// only its fixture daemons whatever is running on the developer's machine.
const E2E_STORAGE_KEY = "@paseo:e2e";
async function verify(name, { link, hostLabel }) {
await AsyncStorage.setItem(E2E_STORAGE_KEY, "1");
const store = new HostRuntimeStore();
await store.boot();
const outcome = await pair(store, link);
if (outcome.status !== "connected") throw new Error(`${name}: pairing ended ${outcome.status}`);
console.log(`RELAY_REGRESSION_PASS ${name} pair`);
await pingOverRelay(store, outcome.serverId);
console.log(`RELAY_REGRESSION_PASS ${name} encrypted-round-trip`);
// A second store reads the saved registry, the way the app does after a restart.
const restarted = new HostRuntimeStore();
await restarted.boot();
const saved = restarted.getHosts().find((host) => host.serverId === outcome.serverId);
if (!saved || saved.label !== hostLabel) {
throw new Error(`${name}: saved host missing after restart: ${JSON.stringify(saved)}`);
}
await pingOverRelay(restarted, outcome.serverId);
console.log(`RELAY_REGRESSION_PASS ${name} reconnect`);
}
async function run() {
for (const [name, target] of Object.entries(targets)) await verify(name, target);
console.log("RELAY_REGRESSION_COMPLETE");
}
setTimeout(() => {
run().catch((error) => console.error(`RELAY_REGRESSION_FAIL ${describe(error)}`));
}, 0);
+56
View File
@@ -0,0 +1,56 @@
import { expect, test } from "vitest";
import { startRelayFixture } from "./relay-fixture";
import { runNativeFixture } from "./native-fixture";
const binary = process.env.PASEO_GPUI_TEST_BINARY;
// Pairs through the app's HostRuntimeStore in the compiled GPUI binary (V8),
// against daemons that negotiate each endpoint security mode.
test.skipIf(!binary)(
"pairing links pair, round-trip encrypted frames and reconnect on the V8 runtime",
async () => {
const daemons = {
protected: await startRelayFixture({
serverId: "srv_gpui_protected",
hostname: "gpui-protected-fixture",
security: "protected",
}),
legacy: await startRelayFixture({
serverId: "srv_gpui_legacy",
hostname: "gpui-legacy-fixture",
security: "legacy",
}),
};
try {
const output = await runNativeFixture(binary!, {
fixture: "relay-regression.fixture.js",
name: "relay",
globals: {
__relayRegressionTargets: {
protected: { link: daemons.protected.link, hostLabel: daemons.protected.hostLabel },
legacy: { link: daemons.legacy.link, hostLabel: daemons.legacy.hostLabel },
},
},
completeMarker: "RELAY_REGRESSION_COMPLETE",
failMarker: "RELAY_REGRESSION_FAIL",
timeoutMs: 90_000,
});
for (const mode of ["protected", "legacy"]) {
for (const stage of ["pair", "encrypted-round-trip", "reconnect"]) {
expect(output).toContain(`RELAY_REGRESSION_PASS ${mode} ${stage}`);
}
}
for (const daemon of Object.values(daemons)) {
expect(daemon.decryptedFromClient).toContainEqual(
expect.objectContaining({
type: "session",
message: expect.objectContaining({ type: "ping" }),
}),
);
}
} finally {
await Promise.all(Object.values(daemons).map((daemon) => daemon.close()));
}
},
480_000,
);
+187 -42
View File
@@ -1,41 +1,131 @@
import assert from "node:assert/strict";
import { execFileSync, spawnSync } from "node:child_process";
import { readdirSync } from "node:fs";
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
assert.equal(process.platform, "darwin", "Run package verification on macOS");
assert.ok(process.argv[2], "Pass the packaged .app path");
const app = path.resolve(process.argv[2]);
const contents = path.join(app, "Contents");
const info = JSON.parse(
execFileSync("plutil", ["-convert", "json", "-o", "-", path.join(contents, "Info.plist")]),
const gpuiDir = fileURLToPath(new URL(".", import.meta.url));
export const DEFAULT_CANONICAL_ICNS_PATH = path.resolve(gpuiDir, "../../desktop/assets/icon.icns");
export const DEFAULT_CLI_ICON_PNG_PATH = path.join(
gpuiDir,
"node_modules/@react-native-gpui/cli/assets/default-icon.png",
);
const executable = path.join(contents, "MacOS", info.CFBundleExecutable);
const frameworks = path.join(contents, "Frameworks");
const libraries = readdirSync(frameworks, { recursive: true })
.filter((name) => name.endsWith(".dylib"))
.map((name) => path.join(frameworks, name));
execFileSync("codesign", ["--verify", "--deep", "--strict", app], { stdio: "inherit" });
const signature = spawnSync("codesign", ["-dvvv", executable], { encoding: "utf8" });
assert.equal(signature.status, 0, signature.stderr);
if (
signature.stderr.includes("Signature=adhoc") &&
/flags=[^\n]*\bruntime\b/.test(signature.stderr) &&
libraries.length > 0
) {
const entitlements = execFileSync("codesign", ["-d", "--entitlements", "-", "--xml", executable]);
assert.ok(entitlements.length > 0, "Ad-hoc app has no library-validation entitlement");
const values = JSON.parse(
execFileSync("plutil", ["-convert", "json", "-o", "-", "--", "-"], {
input: entitlements,
}),
);
export function readBundleInfoPlist(appPath) {
const plistPath = path.join(appPath, "Contents", "Info.plist");
assert.ok(existsSync(plistPath), `Missing Info.plist in bundle: ${plistPath}`);
return JSON.parse(execFileSync("plutil", ["-convert", "json", "-o", "-", plistPath]));
}
export function readAssetCatalogEntries(assetsCarPath) {
const output = execFileSync("assetutil", ["--info", assetsCarPath], { encoding: "utf8" });
const parsed = JSON.parse(output);
return Array.isArray(parsed) ? parsed : [];
}
export function parseIcnsChunks(buffer) {
assert.ok(buffer.length >= 8, "Invalid .icns file: shorter than 8-byte header");
assert.equal(
values["com.apple.security.cs.disable-library-validation"],
true,
"Ad-hoc app cannot satisfy Team ID library validation on a Mac with SIP enabled",
buffer.subarray(0, 4).toString("latin1"),
"icns",
"Invalid .icns file: missing icns magic header",
);
const declaredLength = buffer.readUInt32BE(4);
assert.equal(
declaredLength,
buffer.length,
`Invalid .icns file: header declares ${declaredLength} bytes, got ${buffer.length}`,
);
const chunks = [];
let offset = 8;
while (offset < buffer.length) {
assert.ok(offset + 8 <= buffer.length, `Truncated .icns chunk header at offset ${offset}`);
const type = buffer.subarray(offset, offset + 4).toString("latin1");
const length = buffer.readUInt32BE(offset + 4);
assert.ok(
length >= 8 && offset + length <= buffer.length,
`Invalid .icns chunk length for ${type}`,
);
chunks.push({ type, data: buffer.subarray(offset + 8, offset + length) });
offset += length;
}
return chunks;
}
function resolveBundleIcnsPath(resourcesDir, iconFileName) {
const direct = path.join(resourcesDir, iconFileName);
if (existsSync(direct)) return direct;
if (!iconFileName.endsWith(".icns")) {
const withExtension = path.join(resourcesDir, `${iconFileName}.icns`);
if (existsSync(withExtension)) return withExtension;
}
return null;
}
export function verifyMacosAppIcon(
appPath,
{
info = readBundleInfoPlist(appPath),
canonicalIcnsPath = DEFAULT_CANONICAL_ICNS_PATH,
defaultIconPngPath = DEFAULT_CLI_ICON_PNG_PATH,
requireAssetCatalog = false,
inspectAssetCatalog = readAssetCatalogEntries,
} = {},
) {
const resourcesDir = path.join(appPath, "Contents", "Resources");
assert.ok(
typeof info.CFBundleIconFile === "string" && info.CFBundleIconFile.trim().length > 0,
"Info.plist must declare a non-empty CFBundleIconFile",
);
const bundledIconPath = resolveBundleIcnsPath(resourcesDir, info.CFBundleIconFile.trim());
assert.ok(
bundledIconPath,
`Packaged macOS app is missing CFBundleIconFile (${info.CFBundleIconFile}) in ${resourcesDir}`,
);
const actualIcns = readFileSync(bundledIconPath);
if (existsSync(defaultIconPngPath)) {
const chunks = parseIcnsChunks(actualIcns);
const defaultIconPng = readFileSync(defaultIconPngPath);
assert.ok(
!chunks.some((chunk) => chunk.data.equals(defaultIconPng)),
`Packaged macOS app icon fell back to @react-native-gpui/cli default-icon.png (${bundledIconPath})`,
);
}
assert.ok(existsSync(canonicalIcnsPath), `Missing canonical Paseo .icns: ${canonicalIcnsPath}`);
const canonicalIcns = readFileSync(canonicalIcnsPath);
assert.ok(
actualIcns.equals(canonicalIcns),
`Packaged macOS app icon (${bundledIconPath}) does not match canonical ${canonicalIcnsPath}`,
);
const assetsCarPath = path.join(resourcesDir, "Assets.car");
const hasAssetsCar = existsSync(assetsCarPath);
const iconName = typeof info.CFBundleIconName === "string" ? info.CFBundleIconName.trim() : "";
const hasIconName = iconName.length > 0;
if (hasIconName) {
assert.ok(
hasAssetsCar,
`Info.plist sets CFBundleIconName=${iconName} but ${assetsCarPath} is missing`,
);
}
if (hasAssetsCar) {
assert.ok(hasIconName, `${assetsCarPath} exists but Info.plist is missing CFBundleIconName`);
assert.ok(statSync(assetsCarPath).size > 0, `${assetsCarPath} must not be empty`);
const catalogEntries = inspectAssetCatalog(assetsCarPath);
assert.ok(
catalogEntries.some((entry) => entry && typeof entry === "object" && entry.Name === iconName),
`Compiled ${assetsCarPath} does not contain CFBundleIconName "${iconName}"`,
);
}
if (requireAssetCatalog) {
assert.ok(
hasAssetsCar && hasIconName,
`Expected compiled Asset Catalog icon (Assets.car + CFBundleIconName) in ${appPath}`,
);
}
return { bundledIconPath, hasAssetsCar };
}
function version(value) {
@@ -43,19 +133,74 @@ function version(value) {
return (parts[0] * 256 + (parts[1] ?? 0)) * 256 + (parts[2] ?? 0);
}
assert.ok(info.LSMinimumSystemVersion, "The app must declare its minimum macOS version");
for (const binary of [executable, ...libraries]) {
const build = execFileSync("xcrun", ["vtool", "-show-build", binary], { encoding: "utf8" });
const minima = [...build.matchAll(/\bminos\s+(\d+(?:\.\d+)*)/g)].map((match) => match[1]);
assert.ok(minima.length > 0, `No macOS deployment target found in ${binary}`);
for (const minimum of minima) {
assert.ok(
version(minimum) <= version(info.LSMinimumSystemVersion),
`${path.basename(binary)} requires macOS ${minimum}, above the app's ${info.LSMinimumSystemVersion}`,
export function verifyMacosPackage(appPath, options = {}) {
assert.equal(process.platform, "darwin", "Run package verification on macOS");
const app = path.resolve(appPath);
const contents = path.join(app, "Contents");
const info = readBundleInfoPlist(app);
const executable = path.join(contents, "MacOS", info.CFBundleExecutable);
const frameworks = path.join(contents, "Frameworks");
const libraries = existsSync(frameworks)
? readdirSync(frameworks, { recursive: true })
.filter((name) => name.endsWith(".dylib"))
.map((name) => path.join(frameworks, name))
: [];
verifyMacosAppIcon(app, { info, ...options });
execFileSync("codesign", ["--verify", "--deep", "--strict", app], { stdio: "inherit" });
const signature = spawnSync("codesign", ["-dvvv", executable], { encoding: "utf8" });
assert.equal(signature.status, 0, signature.stderr);
if (
signature.stderr.includes("Signature=adhoc") &&
/flags=[^\n]*\bruntime\b/.test(signature.stderr) &&
libraries.length > 0
) {
const entitlements = execFileSync("codesign", [
"-d",
"--entitlements",
"-",
"--xml",
executable,
]);
assert.ok(entitlements.length > 0, "Ad-hoc app has no library-validation entitlement");
const values = JSON.parse(
execFileSync("plutil", ["-convert", "json", "-o", "-", "--", "-"], {
input: entitlements,
}),
);
assert.equal(
values["com.apple.security.cs.disable-library-validation"],
true,
"Ad-hoc app cannot satisfy Team ID library validation on a Mac with SIP enabled",
);
}
assert.ok(info.LSMinimumSystemVersion, "The app must declare its minimum macOS version");
for (const binary of [executable, ...libraries]) {
const build = execFileSync("xcrun", ["vtool", "-show-build", binary], { encoding: "utf8" });
const minima = [...build.matchAll(/\bminos\s+(\d+(?:\.\d+)*)/g)].map((match) => match[1]);
assert.ok(minima.length > 0, `No macOS deployment target found in ${binary}`);
for (const minimum of minima) {
assert.ok(
version(minimum) <= version(info.LSMinimumSystemVersion),
`${path.basename(binary)} requires macOS ${minimum}, above the app's ${info.LSMinimumSystemVersion}`,
);
}
}
console.log(
`PASS: bundle icon, signatures, ad-hoc library loading policy, and macOS deployment targets: ${app}`,
);
}
console.log(
`PASS: bundle signatures, ad-hoc library loading policy, and macOS deployment targets: ${app}`,
);
const isCli =
Boolean(process.argv[1]) && fileURLToPath(import.meta.url) === path.resolve(process.argv[1]);
if (isCli) {
const args = process.argv.slice(2);
const requireAssetCatalog = args.includes("--require-asset-catalog");
const target = args.find((arg) => !arg.startsWith("-"));
assert.ok(target, "Pass the packaged .app path");
verifyMacosPackage(target, { requireAssetCatalog });
}
@@ -0,0 +1,327 @@
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import {
existsSync,
mkdirSync,
mkdtempSync,
readFileSync,
rmSync,
symlinkSync,
writeFileSync,
} from "node:fs";
import os from "node:os";
import path from "node:path";
import test from "node:test";
import { fileURLToPath, pathToFileURL } from "node:url";
import {
renderLinuxLauncher,
resolveConfiguredAppIcon,
stageLinuxDesktopAssets,
verifyLinuxDesktopAssets,
} from "../../../scripts/gpui.mjs";
import {
DEFAULT_CANONICAL_ICNS_PATH,
DEFAULT_CLI_ICON_PNG_PATH,
readBundleInfoPlist,
verifyMacosAppIcon,
} from "./verify-macos-package.mjs";
const gpuiDir = fileURLToPath(new URL(".", import.meta.url));
const repoRoot = path.resolve(gpuiDir, "../../..");
function buildIcnsWithChunk(type, payload) {
const chunk = Buffer.alloc(8 + payload.length);
chunk.write(type, 0, "latin1");
chunk.writeUInt32BE(chunk.length, 4);
payload.copy(chunk, 8);
const header = Buffer.alloc(8);
header.write("icns", 0, "latin1");
header.writeUInt32BE(8 + chunk.length, 4);
return Buffer.concat([header, chunk]);
}
function createFakeMacosApp(
parentDir,
{
bundleName = "Paseo GPUI.app",
iconFileName = "icon@2x.icns",
plistIconFile = iconFileName,
icnsBytes = readFileSync(DEFAULT_CANONICAL_ICNS_PATH),
iconName = null,
assetsCarBytes = null,
} = {},
) {
const appPath = path.join(parentDir, bundleName);
const contentsDir = path.join(appPath, "Contents");
const resourcesDir = path.join(contentsDir, "Resources");
mkdirSync(resourcesDir, { recursive: true });
const info = {
CFBundleExecutable: "react-native-gpui-paseo-gpui",
CFBundleIdentifier: "sh.paseo.gpui",
LSMinimumSystemVersion: "15.0",
...(plistIconFile !== null ? { CFBundleIconFile: plistIconFile } : {}),
...(iconName !== null ? { CFBundleIconName: iconName } : {}),
};
const plistEntries = [
" <key>CFBundleExecutable</key>",
" <string>react-native-gpui-paseo-gpui</string>",
" <key>CFBundleIdentifier</key>",
" <string>sh.paseo.gpui</string>",
" <key>LSMinimumSystemVersion</key>",
" <string>15.0</string>",
];
if (plistIconFile !== null) {
plistEntries.push(` <key>CFBundleIconFile</key>`, ` <string>${plistIconFile}</string>`);
}
if (iconName !== null) {
plistEntries.push(` <key>CFBundleIconName</key>`, ` <string>${iconName}</string>`);
}
writeFileSync(
path.join(contentsDir, "Info.plist"),
[
'<?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>",
...plistEntries,
"</dict>",
"</plist>",
"",
].join("\n"),
);
if (iconFileName !== null && icnsBytes !== null) {
writeFileSync(path.join(resourcesDir, iconFileName), icnsBytes);
}
if (assetsCarBytes !== null) {
writeFileSync(path.join(resourcesDir, "Assets.car"), assetsCarBytes);
}
return { appPath, info };
}
test("GPUI desktop config resolves canonical Paseo icons on macOS and Linux via CLI loader", async () => {
const cliConfigModule = path.join(
gpuiDir,
"node_modules/@react-native-gpui/cli/src/desktop-config.js",
);
assert.ok(
existsSync(cliConfigModule),
`Missing ${cliConfigModule}; run npm run gpui:install before running GPUI packaging tests`,
);
const { loadDesktopConfig } = await import(pathToFileURL(cliConfigModule).href);
const macConfig = loadDesktopConfig(gpuiDir, "darwin");
const linuxConfig = loadDesktopConfig(gpuiDir, "linux");
assert.equal(
path.resolve(gpuiDir, "desktop", macConfig.icon),
path.join(repoRoot, "packages/desktop/assets/icon.icns"),
);
assert.equal(
path.resolve(gpuiDir, "desktop", linuxConfig.icon),
path.join(repoRoot, "packages/desktop/assets/icon.png"),
);
assert.equal(
await resolveConfiguredAppIcon(gpuiDir, "darwin"),
path.join(repoRoot, "packages/desktop/assets/icon.icns"),
);
assert.equal(
await resolveConfiguredAppIcon(gpuiDir, "linux"),
path.join(repoRoot, "packages/desktop/assets/icon.png"),
);
// Missing configured icon files must surface an error rather than falling back silently.
const brokenProject = mkdtempSync(path.join(os.tmpdir(), "paseo-gpui-bad-icon-"));
try {
mkdirSync(path.join(brokenProject, "desktop"), { recursive: true });
symlinkSync(path.join(gpuiDir, "node_modules"), path.join(brokenProject, "node_modules"));
writeFileSync(path.join(brokenProject, "app.json"), '{"name":"Paseo"}\n');
writeFileSync(path.join(brokenProject, "package.json"), '{"name":"paseo-gpui"}\n');
writeFileSync(
path.join(brokenProject, "desktop/desktop.json"),
JSON.stringify({ identifier: "sh.paseo.gpui", icon: "missing-icon.png" }),
);
await assert.rejects(() => resolveConfiguredAppIcon(brokenProject, "linux"), /does not exist/);
} finally {
rmSync(brokenProject, { recursive: true, force: true });
}
});
test("verifyMacosAppIcon accepts canonical Paseo .icns (with and without Assets.car)", () => {
const tempDir = mkdtempSync(path.join(os.tmpdir(), "paseo-gpui-mac-icon-ok-"));
try {
const legacy = createFakeMacosApp(tempDir, { bundleName: "Legacy.app" });
const legacyResult = verifyMacosAppIcon(legacy.appPath, { info: legacy.info });
assert.equal(legacyResult.hasAssetsCar, false);
// Standalone verification must still work from a clean checkout before gpui:install.
verifyMacosAppIcon(legacy.appPath, {
info: legacy.info,
defaultIconPngPath: path.join(tempDir, "missing-cli-default-icon.png"),
});
const stemOnly = createFakeMacosApp(tempDir, {
bundleName: "StemOnly.app",
iconFileName: "icon@2x.icns",
plistIconFile: "icon@2x",
});
verifyMacosAppIcon(stemOnly.appPath, { info: stemOnly.info });
const glass = createFakeMacosApp(tempDir, {
bundleName: "Glass.app",
iconName: "Icon",
assetsCarBytes: JSON.stringify([{ Name: "Icon", AssetType: "Icon Image" }]),
});
const glassResult = verifyMacosAppIcon(glass.appPath, {
info: glass.info,
requireAssetCatalog: true,
inspectAssetCatalog: (carPath) => JSON.parse(readFileSync(carPath, "utf8")),
});
assert.equal(glassResult.hasAssetsCar, true);
if (process.platform === "darwin") {
const parsedFromPlutil = readBundleInfoPlist(glass.appPath);
assert.equal(parsedFromPlutil.CFBundleIconName, "Icon");
assert.equal(parsedFromPlutil.CFBundleIconFile, "icon@2x.icns");
}
} finally {
rmSync(tempDir, { recursive: true, force: true });
}
});
test("verifyMacosAppIcon rejects missing icons, mismatched icons, wrong catalog names, and default-icon fallback", () => {
assert.ok(
existsSync(DEFAULT_CLI_ICON_PNG_PATH),
`Missing ${DEFAULT_CLI_ICON_PNG_PATH}; run npm run gpui:install before running GPUI packaging tests`,
);
const tempDir = mkdtempSync(path.join(os.tmpdir(), "paseo-gpui-mac-icon-bad-"));
try {
const missingKey = createFakeMacosApp(tempDir, {
bundleName: "MissingKey.app",
plistIconFile: null,
});
assert.throws(
() => verifyMacosAppIcon(missingKey.appPath, { info: missingKey.info }),
/CFBundleIconFile/,
);
const missingFile = createFakeMacosApp(tempDir, {
bundleName: "MissingFile.app",
icnsBytes: null,
});
assert.throws(
() => verifyMacosAppIcon(missingFile.appPath, { info: missingFile.info }),
/missing CFBundleIconFile/,
);
const defaultIcns = buildIcnsWithChunk("ic10", readFileSync(DEFAULT_CLI_ICON_PNG_PATH));
const fallback = createFakeMacosApp(tempDir, {
bundleName: "Fallback.app",
icnsBytes: defaultIcns,
});
assert.throws(
() => verifyMacosAppIcon(fallback.appPath, { info: fallback.info }),
/default-icon\.png/,
);
const wrongIcns = createFakeMacosApp(tempDir, {
bundleName: "WrongIcon.app",
icnsBytes: buildIcnsWithChunk("ic10", Buffer.from("not-paseo-icon")),
});
assert.throws(
() => verifyMacosAppIcon(wrongIcns.appPath, { info: wrongIcns.info }),
/does not match canonical/,
);
const danglingCatalogName = createFakeMacosApp(tempDir, {
bundleName: "DanglingName.app",
iconName: "Icon",
});
assert.throws(
() => verifyMacosAppIcon(danglingCatalogName.appPath, { info: danglingCatalogName.info }),
/Assets\.car is missing/,
);
const missingCatalogName = createFakeMacosApp(tempDir, {
bundleName: "MissingName.app",
assetsCarBytes: JSON.stringify([{ Name: "Icon" }]),
});
assert.throws(
() => verifyMacosAppIcon(missingCatalogName.appPath, { info: missingCatalogName.info }),
/missing CFBundleIconName/,
);
const wrongCatalogName = createFakeMacosApp(tempDir, {
bundleName: "WrongCatalogName.app",
iconName: "WrongIcon",
assetsCarBytes: JSON.stringify([{ Name: "Icon", AssetType: "Icon Image" }]),
});
assert.throws(
() =>
verifyMacosAppIcon(wrongCatalogName.appPath, {
info: wrongCatalogName.info,
requireAssetCatalog: true,
inspectAssetCatalog: (carPath) => JSON.parse(readFileSync(carPath, "utf8")),
}),
/does not contain CFBundleIconName "WrongIcon"/,
);
const noCatalog = createFakeMacosApp(tempDir, { bundleName: "NoCatalog.app" });
assert.throws(
() =>
verifyMacosAppIcon(noCatalog.appPath, {
info: noCatalog.info,
requireAssetCatalog: true,
}),
/Asset Catalog/,
);
} finally {
rmSync(tempDir, { recursive: true, force: true });
}
});
test("stageLinuxDesktopAssets, verifyLinuxDesktopAssets, and symlinked Linux launcher work as installed", () => {
const tempDir = mkdtempSync(path.join(os.tmpdir(), "paseo-gpui-linux-icon-"));
try {
const pkgDir = path.join(tempDir, "paseo-gpui-linux-x64");
const binaryName = "react-native-gpui-paseo-gpui";
const binDir = path.join(pkgDir, "bin");
const resourceDir = path.join(pkgDir, "lib", binaryName);
mkdirSync(binDir, { recursive: true });
mkdirSync(resourceDir, { recursive: true });
stageLinuxDesktopAssets(pkgDir, resourceDir, repoRoot);
verifyLinuxDesktopAssets(pkgDir, binaryName, repoRoot);
// Simulate extracting the archive and symlinking ~/.local/bin/paseo-gpui -> <pkg>/paseo-gpui.
writeFileSync(path.join(binDir, "paseo-gpui"), renderLinuxLauncher(binaryName), {
mode: 0o755,
});
symlinkSync("bin/paseo-gpui", path.join(pkgDir, "paseo-gpui"));
writeFileSync(path.join(binDir, binaryName), '#!/bin/sh\nprintf "launched:%s\\n" "$*"\n', {
mode: 0o755,
});
const pathBinDir = path.join(tempDir, "local-bin");
mkdirSync(pathBinDir, { recursive: true });
symlinkSync(path.join(pkgDir, "paseo-gpui"), path.join(pathBinDir, "paseo-gpui"));
const output = execFileSync("paseo-gpui", ["--probe-arg"], {
encoding: "utf8",
env: { ...process.env, PATH: `${pathBinDir}:${process.env.PATH}` },
});
assert.equal(output.trim(), "launched:--probe-arg");
writeFileSync(
path.join(pkgDir, "share/icons/hicolor/512x512/apps/sh.paseo.gpui.png"),
Buffer.from("corrupted"),
);
assert.throws(() => verifyLinuxDesktopAssets(pkgDir, binaryName, repoRoot), /does not match/);
} finally {
rmSync(tempDir, { recursive: true, force: true });
}
});
+10 -73
View File
@@ -1,14 +1,9 @@
import { spawn, execFileSync } from "node:child_process";
import { createServer } from "node:http";
import { mkdtempSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { Server as WebSocketServer } from "ws";
import { expect, test } from "vitest";
import { runNativeFixture } from "./native-fixture";
const binary = process.env.PASEO_GPUI_TEST_BINARY;
const project = path.dirname(fileURLToPath(import.meta.url));
const root = path.resolve(project, "../../..");
function createPeer() {
const server = createServer();
@@ -31,83 +26,25 @@ function createPeer() {
test.skipIf(!binary)(
"native WebSocket retries and peer closes release their resources",
async () => {
mkdirSync(path.join(root, ".artifacts/gpui"), { recursive: true });
const artifacts = mkdtempSync(path.join(root, ".artifacts/gpui/websocket-"));
const bundle = path.join(artifacts, "regression.bundle");
execFileSync(
process.execPath,
[
"node_modules/react-native/cli.js",
"bundle",
"--platform",
"desktop",
"--entry-file",
"websocket-regression.fixture.js",
"--config",
"desktop/metro.config.js",
"--bundle-output",
bundle,
"--dev",
"false",
"--max-workers",
"1",
],
{ cwd: project, env: { ...process.env, PASEO_RENDERER: "gpui" }, timeout: 120_000 },
);
const { server, sockets } = createPeer();
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const address = server.address();
if (!address || typeof address === "string") throw new Error("Missing server address");
writeFileSync(
bundle,
`globalThis.__webSocketRegressionUrl = "ws://127.0.0.1:${address.port}";\n${readFileSync(bundle, "utf8")}`,
);
// Match Finder's descriptor limit even when the test shell has raised it.
const app = spawn("/bin/sh", ["-c", 'ulimit -n 256; exec "$@"', "gpui-test", binary!], {
env: {
...process.env,
RN_GPUI_BUNDLE: bundle,
RN_GPUI_APP_ID: "sh.paseo.gpui.websocket-test",
XDG_DATA_HOME: path.join(artifacts, "data"),
},
stdio: ["ignore", "pipe", "pipe"],
});
let output = "";
try {
await new Promise<void>((resolve, reject) => {
const timeout = setTimeout(
() => reject(new Error(`Native retry test timed out:\n${output}`)),
60_000,
);
const collect = (chunk: Buffer) => {
output += chunk.toString();
if (output.includes("WEBSOCKET_REGRESSION_COMPLETE")) {
clearTimeout(timeout);
resolve();
} else if (output.includes("WEBSOCKET_REGRESSION_FAIL")) {
clearTimeout(timeout);
reject(new Error(output));
}
};
app.stdout.on("data", collect);
app.stderr.on("data", collect);
app.once("error", (error) => {
clearTimeout(timeout);
reject(error);
});
app.once("exit", (code, signal) => {
clearTimeout(timeout);
reject(new Error(`Native process exited (${code}, ${signal}):\n${output}`));
});
const output = await runNativeFixture(binary!, {
fixture: "websocket-regression.fixture.js",
name: "websocket",
globals: { __webSocketRegressionUrl: `ws://127.0.0.1:${address.port}` },
completeMarker: "WEBSOCKET_REGRESSION_COMPLETE",
failMarker: "WEBSOCKET_REGRESSION_FAIL",
timeoutMs: 60_000,
// Match Finder's descriptor limit even when the test shell has raised it.
descriptorLimit: 256,
});
expect(app.exitCode).toBeNull();
expect(output).toContain("WEBSOCKET_REGRESSION_PASS reject");
expect(output).toContain("WEBSOCKET_REGRESSION_PASS remote-close");
expect(output).toContain("WEBSOCKET_REGRESSION_PASS local-close");
} finally {
writeFileSync(path.join(artifacts, "native.log"), output);
app.kill("SIGTERM");
for (const client of sockets.clients) client.terminate();
sockets.close();
server.close();
@@ -9,7 +9,7 @@ import Trash2 from "lucide-react-native/icons/trash";
import X from "lucide-react-native/icons/x";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import type { AgentProfile } from "@getpaseo/protocol/messages";
import { TitlebarDragRegion } from "@/components/desktop/titlebar-drag-region";
import { TitlebarDragSurface } from "@/components/desktop/titlebar-drag-surface";
import { Button } from "@/components/ui/button";
import { DismissBackdrop } from "@/components/ui/dismiss-backdrop";
import {
@@ -182,8 +182,7 @@ function DrawerHeader({
const showSteppers = mode === "edit" && Boolean(onStepPrev && onStepNext);
return (
<View style={styles.headerChrome}>
<TitlebarDragRegion />
<TitlebarDragSurface style={styles.headerChrome}>
<WindowChromeSafeArea placement="below" />
<View style={styles.header}>
<View style={styles.headerIdentity}>
@@ -246,7 +245,7 @@ function DrawerHeader({
</ToolbarButton>
</View>
</View>
</View>
</TitlebarDragSurface>
);
}
+22 -12
View File
@@ -36,7 +36,8 @@ import { AppState, useWindowDimensions, View } from "react-native";
import { GestureDetector, GestureHandlerRootView } from "react-native-gesture-handler";
import { KeyboardProvider } from "react-native-keyboard-controller";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import { AppearanceProvider } from "@/appearance/provider";
import { AppearanceProvider, useContributedThemes } from "@/appearance/provider";
import { resolveWindowChromeAppearance } from "@/appearance/theme-catalog";
import { CommandCenter } from "@/command-center/command-center";
import { WorkspaceSwitcherHud } from "@/workspace-switcher";
import { CommandCenterRootActions } from "@/command-center/root-registration";
@@ -81,7 +82,7 @@ import {
resolveSidebarActivity,
resolveLeftSidebarPresentation,
} from "@/components/desktop-sidebar-layout";
import { isNative, isWeb } from "@/constants/platform";
import { isWeb } from "@/constants/platform";
import { HorizontalScrollProvider } from "@/contexts/horizontal-scroll-context";
import { SessionProvider } from "@/contexts/session-context";
import { SidebarCalloutProvider } from "@/contexts/sidebar-callout-context";
@@ -106,7 +107,7 @@ import { AgentNavigationListener } from "@/desktop/agent-navigation";
import { LegacyAgentSkillsMigration } from "@/agent-skills/legacy-migration";
import { legacyFavoriteProfileMigration } from "@/agent-profiles/migration";
import { listenToDesktopEvent } from "@/desktop/electron/events";
import { updateDesktopWindowChrome } from "@/desktop/electron/window";
import { desktopWindowChromeHost } from "@/desktop/window-chrome-host";
import { getDesktopHost } from "@/desktop/host";
import { loadDesktopSettings } from "@/desktop/settings/desktop-settings";
import { RosettaCalloutSource } from "@/desktop/updates/rosetta-callout-source";
@@ -696,19 +697,28 @@ function ProvidersWrapper({ children }: { children: ReactNode }) {
}
function DesktopWindowControlsSync() {
const { isLoading } = useAppSettings();
const { settings, isLoading } = useAppSettings();
const { selected: selectedPluginTheme } = useContributedThemes();
const { theme } = useUnistyles();
const surface0 = theme.colors.surface0;
const appearance = resolveWindowChromeAppearance({
theme: settings.theme,
hasContributedTheme: selectedPluginTheme !== null,
colorScheme: theme.colorScheme,
});
useEffect(() => {
if (isLoading || isNative) return;
void updateDesktopWindowChrome({
backgroundColor: surface0,
trafficLightOffsetY: -4,
}).catch((error) => {
console.warn("[DesktopWindow] Failed to update window controls overlay", error);
});
}, [isLoading, surface0]);
if (isLoading) return;
void desktopWindowChromeHost
.updateChrome({
backgroundColor: surface0,
appearance,
trafficLightOffsetY: -4,
})
.catch((error) => {
console.warn("[DesktopWindow] Failed to update window controls overlay", error);
});
}, [appearance, isLoading, surface0]);
return null;
}
@@ -70,3 +70,20 @@ export function resolveThemeCatalog(input: ResolveThemeCatalogInput): ThemeCatal
return [...builtIn, ...contributed];
}
/**
* Resolves the native window chrome appearance from the user's theme preference.
* Keeps `"system"` when following the OS (including missing-plugin fallback) so
* desktop windows do not lock `NSWindow.appearance` to the current effective colorScheme.
*/
export function resolveWindowChromeAppearance(input: {
theme: ThemePreference;
hasContributedTheme: boolean;
colorScheme: "light" | "dark";
}): "light" | "dark" | "system" {
const effectiveTheme =
input.theme === PLUGIN_THEME_PREFERENCE && !input.hasContributedTheme
? FALLBACK_THEME_PREFERENCE
: input.theme;
return effectiveTheme === "auto" ? "system" : input.colorScheme;
}
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { darkTheme } from "@/styles/theme";
import { resolveThemeCatalog } from "./theme-catalog";
import { resolveThemeCatalog, resolveWindowChromeAppearance } from "./theme-catalog";
import type { PluginThemeOption } from "@/plugins/themes";
const PLUGIN_THEME: PluginThemeOption = {
@@ -68,4 +68,43 @@ describe("resolveThemeCatalog", () => {
missingPlugin.find((option) => option.id === "auto")?.select();
expect(selected).toEqual(["auto"]);
});
it("maps auto and missing plugin fallback to system chrome appearance across Light -> Dark -> System", () => {
expect(
resolveWindowChromeAppearance({
theme: "auto",
hasContributedTheme: false,
colorScheme: "light",
}),
).toBe("system");
expect(
resolveWindowChromeAppearance({
theme: "dark",
hasContributedTheme: false,
colorScheme: "dark",
}),
).toBe("dark");
// Switching back to System ("auto") while theme.colorScheme still reads "dark" must emit "system".
expect(
resolveWindowChromeAppearance({
theme: "auto",
hasContributedTheme: false,
colorScheme: "dark",
}),
).toBe("system");
expect(
resolveWindowChromeAppearance({
theme: "plugin",
hasContributedTheme: true,
colorScheme: "dark",
}),
).toBe("dark");
expect(
resolveWindowChromeAppearance({
theme: "plugin",
hasContributedTheme: false,
colorScheme: "dark",
}),
).toBe("system");
});
});
@@ -0,0 +1,188 @@
import React from "react";
import { View } from "react-native";
import { cleanup, render } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { CommandCenterResultRow } from "./command-center";
import type { CommandCenterResult } from "./results";
const WIDE_CONTAINER_STYLE = { width: 640 };
const NARROW_CONTAINER_STYLE = { width: 320 };
afterEach(cleanup);
function makeActionResult(overrides: {
id: string;
title: string;
value?: string;
shortcutKeys?: string[][];
withSublist?: boolean;
testId?: string;
}): CommandCenterResult {
const presentation = {
kind: "action" as const,
title: overrides.title,
value: overrides.value,
shortcutKeys: overrides.shortcutKeys,
testId: overrides.testId,
};
return {
kind: "contribution",
id: overrides.id,
contribution: overrides.withSublist
? {
id: overrides.id,
group: "actions",
groupRank: 0,
rank: 0,
keywords: [],
visibility: "always",
presentation,
sublist: {
kind: "items",
id: `${overrides.id}-sublist`,
title: overrides.title,
placeholder: "Search...",
items: [],
},
}
: {
id: overrides.id,
group: "actions",
groupRank: 0,
rank: 0,
keywords: [],
visibility: "always",
presentation,
run: () => {},
},
};
}
describe("CommandCenterResultRow", () => {
it("places the sub-list chevron next to the title so shortcuts and trailing values stay right-aligned", () => {
const onSelect = vi.fn();
const searchFiles = makeActionResult({
id: "search-files",
title: "Search files",
shortcutKeys: [["mod", "P"]],
withSublist: true,
testId: "row-search-files",
});
const newAgent = makeActionResult({
id: "new-agent",
title: "New agent",
shortcutKeys: [["mod", "shift", "A"]],
testId: "row-new-agent",
});
const changeTheme = makeActionResult({
id: "change-theme",
title: "Change theme",
value: "Dark",
withSublist: true,
testId: "row-change-theme",
});
const { getByTestId } = render(
<View style={WIDE_CONTAINER_STYLE}>
<CommandCenterResultRow
result={newAgent}
height={32}
query=""
active={false}
pointerHoverEnabled={false}
onSelect={onSelect}
/>
<CommandCenterResultRow
result={searchFiles}
height={32}
query=""
active={true}
pointerHoverEnabled={false}
onSelect={onSelect}
/>
<CommandCenterResultRow
result={changeTheme}
height={32}
query=""
active={false}
pointerHoverEnabled={false}
onSelect={onSelect}
/>
</View>,
);
const searchRow = getByTestId("row-search-files");
const chevron = searchRow.querySelector('[data-testid="command-center-sublist-chevron"]');
const searchTrailing = searchRow.querySelector('[data-testid="command-center-row-trailing"]');
expect(chevron).not.toBeNull();
expect(searchTrailing).not.toBeNull();
// Chevron sits beside the title in rowMain, not inside rowTrailing.
expect(searchTrailing?.contains(chevron)).toBe(false);
expect(chevron?.querySelector('[data-icon="ChevronRight"]')).not.toBeNull();
const newAgentTrailing = getByTestId("row-new-agent").querySelector(
'[data-testid="command-center-row-trailing"]',
);
const themeTrailing = getByTestId("row-change-theme").querySelector(
'[data-testid="command-center-row-trailing"]',
);
expect(newAgentTrailing).not.toBeNull();
expect(themeTrailing).not.toBeNull();
const searchRect = searchTrailing!.getBoundingClientRect();
const newAgentRect = newAgentTrailing!.getBoundingClientRect();
const themeRect = themeTrailing!.getBoundingClientRect();
expect(Math.abs(searchRect.right - newAgentRect.right)).toBeLessThanOrEqual(1);
expect(Math.abs(themeRect.right - newAgentRect.right)).toBeLessThanOrEqual(1);
// Chevron sits after the title text and before the trailing column.
const chevronRect = chevron!.getBoundingClientRect();
expect(chevronRect.right).toBeLessThan(searchRect.left);
});
it("ellipsizes long drill-down titles without pushing the chevron into the trailing column", () => {
const longRow = makeActionResult({
id: "long-sublist",
title:
"Very long drill-down command center action title that must truncate cleanly before the chevron",
value: "Selected value",
withSublist: true,
testId: "row-long-sublist",
});
const { getByTestId } = render(
<View style={NARROW_CONTAINER_STYLE}>
<CommandCenterResultRow
result={longRow}
height={32}
query=""
active={false}
pointerHoverEnabled={false}
onSelect={vi.fn()}
/>
</View>,
);
const row = getByTestId("row-long-sublist");
const titleEl = row.querySelector<HTMLElement>('[dir="auto"]');
const chevron = row.querySelector<HTMLElement>(
'[data-testid="command-center-sublist-chevron"]',
);
const trailing = row.querySelector<HTMLElement>('[data-testid="command-center-row-trailing"]');
expect(titleEl).not.toBeNull();
expect(chevron).not.toBeNull();
expect(trailing).not.toBeNull();
const titleStyle = getComputedStyle(titleEl!);
expect(titleStyle.textOverflow).toBe("ellipsis");
expect(titleStyle.overflow).toBe("hidden");
expect(titleEl!.scrollWidth).toBeGreaterThan(titleEl!.clientWidth);
const titleRect = titleEl!.getBoundingClientRect();
const chevronRect = chevron!.getBoundingClientRect();
const trailingRect = trailing!.getBoundingClientRect();
expect(chevronRect.width).toBe(14);
expect(titleRect.right).toBeLessThan(chevronRect.left);
expect(chevronRect.right).toBeLessThanOrEqual(trailingRect.left);
});
});
+223 -168
View File
@@ -1,4 +1,8 @@
import { useOverlayRegistration, type KeyboardInputEvent } from "@/keyboard";
import {
useHardwareKeyboardPresent,
useOverlayRegistration,
type KeyboardInputEvent,
} from "@/keyboard";
import { Modal } from "@/components/ui/modal";
import equal from "fast-deep-equal";
import { recordRenderProfileReasons } from "@/utils/render-profiler";
@@ -51,6 +55,7 @@ import {
import { Button } from "@/components/ui/button";
import { getScrollOffsetToRevealItem } from "@/components/ui/scroll-reveal";
import { ScrollView } from "@/components/ui/scroll-view";
import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control";
import { Shortcut } from "@/components/ui/shortcut";
import {
IsolatedBottomSheetModal,
@@ -631,7 +636,7 @@ interface ResultRowProps {
onSelect(result: CommandCenterResult): void;
}
const ResultRow = memo(function ResultRow({
export const CommandCenterResultRow = memo(function ResultRow({
result,
height,
query,
@@ -808,128 +813,172 @@ function DecorativeProjectIcon({ project }: { project: CommandCenterWorkspaceRes
);
}
function ResultContent({
function FileResultContent({ result, query }: { result: CommandCenterFileResult; query: string }) {
return (
<View style={styles.rowContent}>
<View style={[styles.rowMain, styles.rowMainSingleLine]}>
<View style={styles.iconSlot} testID="command-center-file-icon">
<MaterialFileIcon fileName={result.title} size={16} />
</View>
<Text style={styles.fileLine} numberOfLines={1} testID="command-center-file-line">
<QueryHighlightedText
query={query}
text={result.title}
style={styles.fileName}
testID="command-center-file-name"
/>
{result.subtitle ? (
<Text style={styles.filePath} testID="command-center-file-path">
{" "}
<QueryHighlightedText query={query} text={result.subtitle} />
</Text>
) : null}
</Text>
</View>
</View>
);
}
function WorkspaceResultContent({
result,
query,
backdrop,
}: {
result: CommandCenterResult;
result: CommandCenterWorkspaceResult;
query: string;
backdrop: SurfaceBackdrop;
}) {
if (result.kind === "file") {
return (
<View style={styles.rowContent}>
<View style={styles.rowMain}>
<View style={styles.iconSlot} testID="command-center-file-icon">
<MaterialFileIcon fileName={result.title} size={16} />
</View>
<Text style={styles.fileLine} numberOfLines={1} testID="command-center-file-line">
<QueryHighlightedText
query={query}
text={result.title}
style={styles.fileName}
testID="command-center-file-name"
/>
{result.subtitle ? (
<Text style={styles.filePath} testID="command-center-file-path">
{" "}
<QueryHighlightedText query={query} text={result.subtitle} />
</Text>
) : null}
</Text>
const key = result.id.slice("workspace:".length);
return (
<View style={styles.rowContent} testID={`command-center-workspace-${key}`}>
<View style={[styles.rowMain, styles.rowMainMultiLine]}>
<View style={[styles.iconSlot, styles.iconSlotMultiLine]}>
{/* An archived workspace runs nothing, so it has no status to show. */}
{result.archived ? (
<DecorativeProjectIcon project={result.project} />
) : (
<WorkspaceResultIcon result={result} backdrop={backdrop} />
)}
</View>
</View>
);
}
if (result.kind === "workspace") {
const key = result.id.slice("workspace:".length);
return (
<View style={styles.rowContent} testID={`command-center-workspace-${key}`}>
<View style={styles.rowMain}>
<View style={styles.iconSlot}>
{/* An archived workspace runs nothing, so it has no status to show. */}
{result.archived ? (
<DecorativeProjectIcon project={result.project} />
) : (
<WorkspaceResultIcon result={result} backdrop={backdrop} />
)}
</View>
<View style={styles.textContent}>
<QueryHighlightedText
<View style={styles.textContent}>
<QueryHighlightedText
query={query}
text={result.title}
style={styles.title}
numberOfLines={1}
/>
<SubtitleWithTimestamp
query={query}
subtitle={result.subtitle}
activityAt={result.activityAt}
testID="command-center-workspace-subtitle"
/>
{result.matchedAgent ? (
<MatchedAgentLine
agent={result.matchedAgent}
serverId={result.serverId}
query={query}
text={result.title}
style={styles.title}
numberOfLines={1}
/>
<SubtitleWithTimestamp
query={query}
subtitle={result.subtitle}
activityAt={result.activityAt}
testID="command-center-workspace-subtitle"
/>
{result.matchedAgent ? (
<MatchedAgentLine
agent={result.matchedAgent}
serverId={result.serverId}
query={query}
/>
) : null}
</View>
</View>
{result.archived ? <ArchivedBadge /> : null}
</View>
);
}
const presentation = result.contribution.presentation;
const Icon = presentation.icon;
if (presentation.kind === "action") {
const hasSublist = Boolean(result.contribution.sublist);
const hasTrailing = Boolean(presentation.value || presentation.shortcutKeys || hasSublist);
return (
<View style={styles.rowContent}>
<View style={styles.rowMain}>
{Icon ? (
<View style={styles.iconSlot}>
<Icon size={16} />
</View>
) : null}
<View style={styles.textContent}>
</View>
</View>
{result.archived ? <ArchivedBadge /> : null}
</View>
);
}
function ActionResultContent({
result,
query,
}: {
result: Extract<CommandCenterResult, { kind: "contribution" }>;
query: string;
}) {
const shortcutsAvailable = useHardwareKeyboardPresent();
const presentation = result.contribution.presentation;
if (presentation.kind !== "action") return null;
const Icon = presentation.icon;
const hasSublist = Boolean(result.contribution.sublist);
const hasSubtitle = Boolean(presentation.subtitle);
const hasShortcut = Boolean(shortcutsAvailable && presentation.shortcutKeys);
const hasTrailing = Boolean(presentation.value || hasShortcut);
const titleStyle = hasSubtitle ? styles.title : styles.titleSingleLine;
return (
<View style={styles.rowContent}>
<View
style={[styles.rowMain, hasSubtitle ? styles.rowMainMultiLine : styles.rowMainSingleLine]}
>
{Icon ? (
<View style={[styles.iconSlot, hasSubtitle ? styles.iconSlotMultiLine : null]}>
<Icon size={16} />
</View>
) : null}
<View style={styles.textContent}>
{hasSublist ? (
<View style={styles.titleRow}>
<QueryHighlightedText
query={query}
text={presentation.title}
style={titleStyle}
numberOfLines={1}
/>
<View
style={styles.sublistChevron}
testID="command-center-sublist-chevron"
accessibilityElementsHidden
importantForAccessibility="no-hide-descendants"
aria-hidden
>
<ThemedChevronRight size={14} strokeWidth={2} />
</View>
</View>
) : (
<QueryHighlightedText
query={query}
text={presentation.title}
style={styles.title}
style={titleStyle}
numberOfLines={1}
/>
{presentation.subtitle ? (
<QueryHighlightedText
query={query}
text={presentation.subtitle}
style={styles.subtitle}
numberOfLines={1}
/>
) : null}
</View>
)}
{presentation.subtitle ? (
<QueryHighlightedText
query={query}
text={presentation.subtitle}
style={styles.subtitle}
numberOfLines={1}
/>
) : null}
</View>
{hasTrailing ? (
<View style={styles.rowTrailing}>
{presentation.value ? (
<Text style={styles.rowValue} numberOfLines={1}>
{presentation.value}
</Text>
) : null}
{presentation.shortcutKeys ? (
<Shortcut chord={presentation.shortcutKeys} style={styles.rowShortcut} />
) : null}
{hasSublist ? <ThemedChevronRight size={14} strokeWidth={2} /> : null}
</View>
) : null}
</View>
);
}
{hasTrailing ? (
<View style={styles.rowTrailing} testID="command-center-row-trailing">
{presentation.value ? (
<Text style={styles.rowValue} numberOfLines={1}>
{presentation.value}
</Text>
) : null}
{hasShortcut && presentation.shortcutKeys ? (
<Shortcut chord={presentation.shortcutKeys} style={styles.rowShortcut} />
) : null}
</View>
) : null}
</View>
);
}
function ChoiceResultContent({
result,
query,
}: {
result: Extract<CommandCenterResult, { kind: "contribution" }>;
query: string;
}) {
const presentation = result.contribution.presentation;
if (presentation.kind !== "choice") return null;
const Icon = presentation.icon;
return (
<View style={styles.rowContent}>
<View style={styles.rowMain}>
<View style={[styles.rowMain, styles.rowMainSingleLine]}>
{Icon ? (
<View style={styles.iconSlot}>
<Icon size={16} />
@@ -946,7 +995,9 @@ function ResultContent({
query={query}
text={part}
style={
index === presentation.path.length - 1 ? styles.title : styles.breadcrumbGroup
index === presentation.path.length - 1
? styles.titleSingleLine
: styles.breadcrumbGroup
}
numberOfLines={1}
/>
@@ -963,6 +1014,27 @@ function ResultContent({
);
}
function ResultContent({
result,
query,
backdrop,
}: {
result: CommandCenterResult;
query: string;
backdrop: SurfaceBackdrop;
}) {
if (result.kind === "file") {
return <FileResultContent result={result} query={query} />;
}
if (result.kind === "workspace") {
return <WorkspaceResultContent result={result} query={query} backdrop={backdrop} />;
}
if (result.contribution.presentation.kind === "action") {
return <ActionResultContent result={result} query={query} />;
}
return <ChoiceResultContent result={result} query={query} />;
}
function SectionRow({ row }: { row: Extract<CommandCenterListRow, { kind: "section" }> }) {
const style = useMemo(() => [styles.section, { height: row.height }], [row.height]);
return (
@@ -1039,7 +1111,7 @@ export function CommandCenter() {
item.kind === "section" ? (
<SectionRow row={item} />
) : (
<ResultRow
<CommandCenterResultRow
result={item.result}
height={item.height}
query={state.query}
@@ -1131,7 +1203,7 @@ export function CommandCenter() {
onKeyDown: handleOverlayKeyDown,
});
const tabOptions = useMemo<CommandCenterTabOption[]>(
const tabOptions = useMemo<SegmentedControlOption<CommandCenterTab>[]>(
() =>
state.tabs.map((tab) => ({
value: tab,
@@ -1236,54 +1308,12 @@ export function CommandCenter() {
);
}
interface CommandCenterTabOption {
value: CommandCenterTab;
label: string;
testID: string;
}
function CommandCenterTabPill({
option,
selected,
onSelect,
onLayoutPill,
}: {
option: CommandCenterTabOption;
selected: boolean;
onSelect(tab: CommandCenterTab): void;
onLayoutPill(tab: CommandCenterTab, event: LayoutChangeEvent): void;
}) {
const handlePress = useCallback(() => {
if (!selected) onSelect(option.value);
}, [onSelect, option.value, selected]);
const handleLayout = useCallback(
(event: LayoutChangeEvent) => onLayoutPill(option.value, event),
[onLayoutPill, option.value],
);
const accessibilityState = useMemo(() => ({ selected }), [selected]);
return (
<Button
variant={selected ? "secondary" : "ghost"}
size="sm"
numberOfLines={1}
accessibilityState={accessibilityState}
aria-selected={selected}
testID={option.testID}
onPress={handlePress}
onLayout={handleLayout}
style={styles.tabPill}
>
{option.label}
</Button>
);
}
function CommandCenterTabPills({
options,
value,
onValueChange,
}: {
options: readonly CommandCenterTabOption[];
options: SegmentedControlOption<CommandCenterTab>[];
value: CommandCenterTab;
onValueChange(tab: CommandCenterTab): void;
}) {
@@ -1351,17 +1381,15 @@ function CommandCenterTabPills({
style={styles.tabScroll}
testID="command-center-tabs"
>
<View style={styles.tabList}>
{options.map((option) => (
<CommandCenterTabPill
key={option.value}
option={option}
selected={option.value === value}
onSelect={onValueChange}
onLayoutPill={handlePillLayout}
/>
))}
</View>
<SegmentedControl
variant="pills"
size="sm"
options={options}
value={value}
onValueChange={onValueChange}
onOptionLayout={handlePillLayout}
style={styles.tabList}
/>
</ScrollView>
);
}
@@ -1463,15 +1491,9 @@ const styles = StyleSheet.create((theme) => ({
flexShrink: 0,
},
tabList: {
flexDirection: "row",
alignItems: "center",
flexShrink: 0,
gap: theme.spacing[1],
paddingHorizontal: theme.spacing[4],
},
tabPill: {
flexShrink: 0,
},
sublistBar: {
minHeight: CONTROL_HEIGHTS.sm,
flexDirection: "row",
@@ -1522,15 +1544,43 @@ const styles = StyleSheet.create((theme) => ({
flex: 1,
minWidth: 0,
flexDirection: "row",
alignItems: "flex-start",
gap: theme.spacing[3],
},
rowMainSingleLine: {
alignItems: "center",
},
rowMainMultiLine: {
alignItems: "flex-start",
},
textContent: { flex: 1, minWidth: 0 },
titleRow: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[1],
minWidth: 0,
},
// Optical nudge: center the chevron glyph on the title text's x-height.
sublistChevron: {
width: 14,
height: 14,
flexShrink: 0,
alignItems: "center",
justifyContent: "center",
marginTop: 1,
},
title: {
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
lineHeight: COMMAND_CENTER_LINE_HEIGHT.title,
flexShrink: 1,
minWidth: 0,
},
titleSingleLine: {
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
lineHeight: COMMAND_CENTER_LINE_HEIGHT.singleLine,
flexShrink: 1,
minWidth: 0,
},
fileLine: {
flex: 1,
@@ -1561,6 +1611,9 @@ const styles = StyleSheet.create((theme) => ({
alignItems: "center",
justifyContent: "center",
},
iconSlotMultiLine: {
height: COMMAND_CENTER_LINE_HEIGHT.title,
},
projectIconFallbackText: { fontSize: 9 },
rowTrailing: {
flexDirection: "row",
@@ -1574,6 +1627,7 @@ const styles = StyleSheet.create((theme) => ({
fontSize: theme.fontSize.sm,
lineHeight: COMMAND_CENTER_LINE_HEIGHT.singleLine,
flexShrink: 1,
minWidth: 0,
},
rowShortcut: { flexShrink: 0 },
breadcrumb: {
@@ -1588,6 +1642,7 @@ const styles = StyleSheet.create((theme) => ({
alignItems: "center",
gap: theme.spacing[1],
flexShrink: 1,
minWidth: 0,
},
breadcrumbGroup: {
color: theme.colors.foregroundMuted,
@@ -0,0 +1,15 @@
import { codegenNativeComponent, type CodegenTypes, type ViewProps } from "react-native";
export type ControlStateEvent = Readonly<{
hovered: boolean;
pressed: boolean;
maximized: boolean;
}>;
export interface NativeProps extends ViewProps {
action?: CodegenTypes.WithDefault<"minimize" | "maximize" | "close", "close">;
disabled?: CodegenTypes.WithDefault<boolean, false>;
onControlStateChange?: CodegenTypes.DirectEventHandler<ControlStateEvent>;
}
export default codegenNativeComponent<NativeProps>("DesktopWindowControl");
@@ -0,0 +1,42 @@
import { useCallback, useState, type ReactNode } from "react";
import type { NativeSyntheticEvent, StyleProp, ViewStyle } from "react-native";
import DesktopWindowControl, {
type ControlStateEvent,
} from "./DesktopWindowControlNativeComponent";
export interface DesktopCaptionButtonProps {
action: "minimize" | "maximize" | "close";
label: string;
style?: StyleProp<ViewStyle>;
children: (state: { hovered: boolean; pressed: boolean }) => ReactNode;
}
export function DesktopCaptionButton({
action,
label,
style,
children,
}: DesktopCaptionButtonProps) {
const [state, setState] = useState({ hovered: false, pressed: false });
const handleControlStateChange = useCallback((event: NativeSyntheticEvent<ControlStateEvent>) => {
const { hovered, pressed } = event.nativeEvent;
setState((previous) =>
previous.hovered === hovered && previous.pressed === pressed
? previous
: { hovered, pressed },
);
}, []);
return (
<DesktopWindowControl
action={action}
accessibilityRole="button"
accessibilityLabel={label}
style={style}
onControlStateChange={handleControlStateChange}
>
{children(state)}
</DesktopWindowControl>
);
}
@@ -0,0 +1,55 @@
import { useCallback, type ReactNode } from "react";
import {
Pressable,
type PressableStateCallbackType,
type StyleProp,
type ViewStyle,
} from "react-native";
import { desktopWindowChromeHost } from "@/desktop/window-chrome-host";
export interface DesktopCaptionButtonProps {
action: "minimize" | "maximize" | "close";
label: string;
style?: StyleProp<ViewStyle>;
children: (state: { hovered: boolean; pressed: boolean }) => ReactNode;
}
function executeCaptionAction(action: DesktopCaptionButtonProps["action"]): void {
if (action === "minimize") {
void desktopWindowChromeHost.minimize();
return;
}
if (action === "maximize") {
void desktopWindowChromeHost.toggleMaximize();
return;
}
void desktopWindowChromeHost.close();
}
export function DesktopCaptionButton({
action,
label,
style,
children,
}: DesktopCaptionButtonProps) {
const handlePress = useCallback(() => {
executeCaptionAction(action);
}, [action]);
const renderChildren = useCallback(
(state: PressableStateCallbackType & { hovered?: boolean }) =>
children({ hovered: Boolean(state.hovered), pressed: state.pressed }),
[children],
);
return (
<Pressable
accessibilityRole="button"
accessibilityLabel={label}
onPress={handlePress}
style={style}
>
{renderChildren}
</Pressable>
);
}
@@ -0,0 +1,9 @@
import { View, type ViewProps } from "react-native";
import type { TitlebarDragSurfaceProps } from "./titlebar-drag-surface.types";
export type { TitlebarDragSurfaceProps } from "./titlebar-drag-surface.types";
export function TitlebarDragSurface({ draggable = true, ...props }: TitlebarDragSurfaceProps) {
const dragProps = { desktopDragRegion: draggable } as ViewProps;
return <View {...props} {...dragProps} />;
}
@@ -0,0 +1,11 @@
import { View } from "react-native";
import type { TitlebarDragSurfaceProps } from "./titlebar-drag-surface.types";
export type { TitlebarDragSurfaceProps } from "./titlebar-drag-surface.types";
export function TitlebarDragSurface({
draggable: _draggable = true,
...props
}: TitlebarDragSurfaceProps) {
return <View {...props} />;
}
@@ -0,0 +1,6 @@
import type { ViewProps } from "react-native";
export interface TitlebarDragSurfaceProps extends ViewProps {
/** Whether empty non-interactive regions of this surface drag the window. Defaults to true. */
draggable?: boolean;
}
@@ -0,0 +1,18 @@
import { View } from "react-native";
import { TitlebarDragRegion } from "@/components/desktop/titlebar-drag-region";
import type { TitlebarDragSurfaceProps } from "./titlebar-drag-surface.types";
export type { TitlebarDragSurfaceProps } from "./titlebar-drag-surface.types";
export function TitlebarDragSurface({
draggable = true,
children,
...props
}: TitlebarDragSurfaceProps) {
return (
<View {...props}>
{draggable ? <TitlebarDragRegion /> : null}
{children}
</View>
);
}
@@ -0,0 +1,154 @@
import React, { act } from "react";
import { createRoot } from "react-dom/client";
import { Text } from "react-native";
import { afterEach, describe, expect, it, vi } from "vitest";
import { TitlebarDragSurface } from "@/components/desktop/titlebar-drag-surface.web";
import { DesktopWindowControls } from "@/components/desktop/window-controls";
import { i18n } from "@/i18n/i18next";
import { WindowChromeProvider } from "@/utils/desktop-window";
vi.stubGlobal("React", React);
const container = document.createElement("div");
document.body.appendChild(container);
const root = createRoot(container);
afterEach(() => {
act(() => root.render(null));
delete (window as { paseoDesktop?: unknown }).paseoDesktop;
});
function installElectronDesktop(mode: "native-mac" | "custom-windows" | "custom-linux") {
let isFullscreen = false;
let isMaximized = false;
let resizeHandler: (() => void) | null = null;
const actions: string[] = [];
Object.assign(window, {
paseoDesktop: {
platform: mode === "native-mac" ? "darwin" : "linux",
windowChromeMode: mode,
window: {
getCurrentWindow: () => ({
minimize: async () => {
actions.push("minimize");
},
toggleMaximize: async () => {
actions.push("toggleMaximize");
},
close: async () => {
actions.push("close");
},
isFullscreen: async () => isFullscreen,
isMaximized: async () => isMaximized,
onResized: (handler: () => void) => {
resizeHandler = handler;
return () => {
if (resizeHandler === handler) resizeHandler = null;
};
},
}),
},
},
});
return {
actions,
async emitResize(next: { isFullscreen?: boolean; isMaximized?: boolean }) {
if (next.isFullscreen !== undefined) isFullscreen = next.isFullscreen;
if (next.isMaximized !== undefined) isMaximized = next.isMaximized;
await act(async () => {
resizeHandler?.();
await Promise.resolve();
await Promise.resolve();
});
},
};
}
describe("window chrome seam", () => {
it("renders no drag region outside Electron and renders drag overlay + resizer in Electron", () => {
act(() =>
root.render(
<TitlebarDragSurface testID="drag-surface">
<Text>Title</Text>
</TitlebarDragSurface>,
),
);
expect(container.querySelector("[data-window-drag-region]")).toBeNull();
installElectronDesktop("custom-linux");
act(() =>
root.render(
<>
<TitlebarDragSurface testID="drag-surface-on">
<Text>Title</Text>
</TitlebarDragSurface>
<TitlebarDragSurface testID="drag-surface-off" draggable={false}>
<Text>Static</Text>
</TitlebarDragSurface>
</>,
),
);
const onSurface = container.querySelector('[data-testid="drag-surface-on"]');
const offSurface = container.querySelector('[data-testid="drag-surface-off"]');
const dragRegions = onSurface?.querySelectorAll("[data-window-drag-region]");
expect(dragRegions?.length).toBe(1);
const dragOverlay = dragRegions?.[0] as HTMLElement;
expect(getComputedStyle(dragOverlay).position).toBe("absolute");
expect(getComputedStyle(dragOverlay).getPropertyValue("-webkit-app-region")).toBe("drag");
const resizer = dragOverlay.nextElementSibling as HTMLElement | null;
expect(resizer).not.toBeNull();
expect(getComputedStyle(resizer as HTMLElement).position).toBe("absolute");
expect(getComputedStyle(resizer as HTMLElement).top).toBe("0px");
expect(getComputedStyle(resizer as HTMLElement).height).toBe("4px");
expect(getComputedStyle(resizer as HTMLElement).getPropertyValue("-webkit-app-region")).toBe(
"no-drag",
);
expect(offSurface?.querySelectorAll("[data-window-drag-region]").length).toBe(0);
expect(
[...(offSurface?.querySelectorAll("div") ?? [])].some(
(node) => getComputedStyle(node).getPropertyValue("-webkit-app-region") === "no-drag",
),
).toBe(false);
});
it("drives DesktopWindowControls through WindowChromeProvider and DesktopCaptionButton", async () => {
await i18n.changeLanguage("en");
const electron = installElectronDesktop("custom-linux");
await act(async () => {
root.render(
<WindowChromeProvider>
<DesktopWindowControls />
</WindowChromeProvider>,
);
await Promise.resolve();
await Promise.resolve();
});
const controls = container.querySelector('[data-testid="desktop-window-controls"]');
expect(controls?.getAttribute("data-window-no-drag")).toBe("");
const minimizeBtn = container.querySelector('[aria-label="Minimize window"]');
const maximizeBtn = container.querySelector('[aria-label="Maximize window"]');
const closeBtn = container.querySelector('[aria-label="Close window"]');
expect(minimizeBtn).not.toBeNull();
expect(maximizeBtn).not.toBeNull();
expect(closeBtn).not.toBeNull();
await act(async () => {
(minimizeBtn as HTMLElement).click();
(maximizeBtn as HTMLElement).click();
(closeBtn as HTMLElement).click();
await Promise.resolve();
});
expect(electron.actions).toEqual(["minimize", "toggleMaximize", "close"]);
await electron.emitResize({ isMaximized: true });
expect(container.querySelector('[aria-label="Restore window"]')).not.toBeNull();
await electron.emitResize({ isFullscreen: true });
expect(container.querySelector('[data-testid="desktop-window-controls"]')).toBeNull();
});
});
@@ -1,18 +1,17 @@
import { useCallback, useMemo } from "react";
import { Pressable, View } from "react-native";
import { View } from "react-native";
import Svg, { Line, Rect } from "react-native-svg";
import { useTranslation } from "react-i18next";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import {
closeDesktopWindow,
minimizeDesktopWindow,
toggleDesktopMaximize,
} from "@/desktop/electron/window";
DesktopCaptionButton,
type DesktopCaptionButtonProps,
} from "@/components/desktop/caption-button";
import { WINDOW_NO_DRAG_DATASET } from "@/components/desktop/titlebar-drag-region";
import {
getDesktopWindowControlsPresentation,
type DesktopWindowControlsPresentation,
} from "@/desktop/window-chrome-presentation";
import { WINDOW_NO_DRAG_DATASET } from "@/components/desktop/titlebar-drag-region";
import { useCustomDesktopWindowControls } from "@/utils/desktop-window";
import type { Theme } from "@/styles/theme";
@@ -81,18 +80,18 @@ const mutedGlyphMapping = (theme: Theme) => ({ color: theme.colors.foregroundMut
const whiteGlyphMapping = () => ({ color: "#ffffff" });
function WindowControl({
action,
kind,
label,
onPress,
presentation,
}: {
action: DesktopCaptionButtonProps["action"];
kind: WindowControlKind;
label: string;
onPress: () => void;
presentation: DesktopWindowControlsPresentation;
}) {
const glyph = useCallback(
({ hovered, pressed }: { hovered?: boolean; pressed: boolean }) => {
({ hovered, pressed }: { hovered: boolean; pressed: boolean }) => {
const highlighted = hovered || pressed;
const closeHighlighted = kind === "close" && highlighted;
return (
@@ -122,23 +121,15 @@ function WindowControl({
[presentation.controlWidth],
);
return (
<Pressable
accessibilityRole="button"
accessibilityLabel={label}
onPress={onPress}
style={controlStyle}
>
<DesktopCaptionButton action={action} label={label} style={controlStyle}>
{glyph}
</Pressable>
</DesktopCaptionButton>
);
}
export function DesktopWindowControls() {
const { t } = useTranslation();
const { visible, mode, isMaximized } = useCustomDesktopWindowControls();
const minimize = useCallback(() => void minimizeDesktopWindow(), []);
const toggleMaximize = useCallback(() => void toggleDesktopMaximize(), []);
const close = useCallback(() => void closeDesktopWindow(), []);
if (!visible || !mode) return null;
const presentation = getDesktopWindowControlsPresentation(mode);
@@ -149,23 +140,23 @@ export function DesktopWindowControls() {
testID="desktop-window-controls"
>
<WindowControl
action="minimize"
kind="minimize"
label={t("desktop.windowControls.minimize")}
onPress={minimize}
presentation={presentation}
/>
<WindowControl
action="maximize"
kind={isMaximized ? "restore" : "maximize"}
label={t(
isMaximized ? "desktop.windowControls.restore" : "desktop.windowControls.maximize",
)}
onPress={toggleMaximize}
presentation={presentation}
/>
<WindowControl
action="close"
kind="close"
label={t("desktop.windowControls.close")}
onPress={close}
presentation={presentation}
/>
</View>
@@ -5,7 +5,7 @@ import { router } from "expo-router";
import ArrowLeft from "lucide-react-native/icons/arrow-left";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { TitlebarDragRegion } from "@/components/desktop/titlebar-drag-region";
import { TitlebarDragSurface } from "@/components/desktop/titlebar-drag-surface";
import { HeaderToggleButton } from "@/components/headers/header-toggle-button";
import { SidebarMenuToggle } from "@/components/headers/sidebar-menu-toggle";
import {
@@ -77,30 +77,31 @@ export function CompactHeader({
return (
<IconButtonChromeProvider value="header-island">
<WindowChromeSafeArea placement="inline" style={styles.chromeContainer}>
<TitlebarDragRegion />
<View style={rootStyle}>
<View
style={[
usesTitlebarHeight ? styles.titlebarRow : styles.row,
inDesktopTitlebar && styles.desktopTitlebarDividerSpace,
]}
>
<View style={styles.island}>
{navigation === "menu" ? <SidebarMenuToggle /> : <BackButton onBack={onBack} />}
<TitlebarDragSurface style={styles.chromeContainer}>
<WindowChromeSafeArea placement="inline">
<View style={rootStyle}>
<View
style={[
usesTitlebarHeight ? styles.titlebarRow : styles.row,
inDesktopTitlebar && styles.desktopTitlebarDividerSpace,
]}
>
<View style={styles.island}>
{navigation === "menu" ? <SidebarMenuToggle /> : <BackButton onBack={onBack} />}
</View>
<View style={styles.titleGroup}>
<CompactHeaderTitle
loading={loading}
title={title}
titleTestID={titleTestID}
subtitle={subtitle}
/>
</View>
{actions ? <View style={styles.island}>{actions}</View> : null}
</View>
<View style={styles.titleGroup}>
<CompactHeaderTitle
loading={loading}
title={title}
titleTestID={titleTestID}
subtitle={subtitle}
/>
</View>
{actions ? <View style={styles.island}>{actions}</View> : null}
</View>
</View>
</WindowChromeSafeArea>
</WindowChromeSafeArea>
</TitlebarDragSurface>
</IconButtonChromeProvider>
);
}
@@ -11,7 +11,7 @@ import {
useIsCompactFormFactor,
} from "@/constants/layout";
import { WindowChromeSafeArea } from "@/utils/desktop-window";
import { TitlebarDragRegion } from "@/components/desktop/titlebar-drag-region";
import { TitlebarDragSurface } from "@/components/desktop/titlebar-drag-surface";
interface ScreenHeaderProps {
left?: ReactNode;
@@ -52,16 +52,17 @@ export function ScreenHeader({
return (
<ComposerDockBackground style={styles.header} testID="composer-dock-header">
<View style={innerStyle}>
<WindowChromeSafeArea
placement="inline"
horizontalPadding={baseHorizontalPadding}
onLayout={onRowLayout}
style={rowStyle}
>
<TitlebarDragRegion />
<View style={leftCombinedStyle}>{left}</View>
<View style={rightCombinedStyle}>{right}</View>
</WindowChromeSafeArea>
<TitlebarDragSurface style={styles.dragSurface}>
<WindowChromeSafeArea
placement="inline"
horizontalPadding={baseHorizontalPadding}
onLayout={onRowLayout}
style={rowStyle}
>
<View style={leftCombinedStyle}>{left}</View>
<View style={rightCombinedStyle}>{right}</View>
</WindowChromeSafeArea>
</TitlebarDragSurface>
</View>
</ComposerDockBackground>
);
@@ -72,6 +73,9 @@ const styles = StyleSheet.create((theme) => ({
backgroundColor: theme.colors.surface0,
},
inner: {},
dragSurface: {
position: "relative",
},
row: {
position: "relative",
height: {
+7 -7
View File
@@ -35,7 +35,7 @@ import Animated, { runOnJS, useAnimatedStyle, useSharedValue } from "react-nativ
import { scheduleOnRN } from "react-native-worklets";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import { TitlebarDragRegion } from "@/components/desktop/titlebar-drag-region";
import { TitlebarDragSurface } from "@/components/desktop/titlebar-drag-surface";
import { SidebarCloseButton } from "@/components/headers/sidebar-close-button";
import {
resolveDesktopSidebarInsetLeft,
@@ -868,8 +868,7 @@ function DesktopSidebar({
<View style={desktopSidebarBorderStyle}>
<View style={styles.sidebarDragArea}>
{showsChromeRow ? (
<View style={styles.desktopChromeRow}>
<TitlebarDragRegion />
<TitlebarDragSurface style={styles.desktopChromeRow}>
{DEV_BUILD_LABEL ? (
<View
pointerEvents="none"
@@ -883,12 +882,13 @@ function DesktopSidebar({
</Text>
</View>
) : null}
</View>
</TitlebarDragSurface>
) : null}
{showsDragStrip ? (
<View style={styles.desktopDragStrip} testID="sidebar-nav-drag-strip">
<TitlebarDragRegion />
</View>
<TitlebarDragSurface
style={styles.desktopDragStrip}
testID="sidebar-nav-drag-strip"
/>
) : null}
</View>
{hasNavRows ? (
+43 -38
View File
@@ -39,7 +39,7 @@ import {
resolveChildWindowChromeCorners,
type WindowChromeCorners,
} from "@/utils/desktop-window";
import { TitlebarDragRegion } from "@/components/desktop/titlebar-drag-region";
import { TitlebarDragSurface } from "@/components/desktop/titlebar-drag-surface";
import { type TabDropPreview } from "@/components/split-container-tab-drop-preview";
import { SplitDropZone, type SplitDropZoneHover } from "@/components/split-drop-zone";
import { deriveWorkspacePaneState } from "@/screens/workspace/workspace-pane-state";
@@ -816,43 +816,44 @@ const SplitPaneView = memo(function SplitPaneView({
<AdaptiveWorkspaceChrome compactHeader={compactHeader}>
{ownsWorkspaceHeader ? renderMainHeader?.() : null}
<WindowChromeRegion corners={focusModeEnabled ? "both" : "none"}>
<WindowChromeSafeArea placement="inline" style={styles.paneTabs}>
<TitlebarDragRegion />
<WorkspaceDesktopTabsRow
paneId={pane.id}
isFocused={isFocused && isWorkspaceFocused}
tabs={desktopTabRowItems}
normalizedServerId={normalizedServerId}
normalizedWorkspaceId={normalizedWorkspaceId}
setHoveredCloseTabKey={setHoveredCloseTabKey}
onNavigateTab={onNavigateTab}
onCloseTab={onCloseTab}
onCopyResumeCommand={onCopyResumeCommand}
onCopyAgentId={onCopyAgentId}
onCopyTerminalId={onCopyTerminalId}
onReloadAgent={onReloadAgent}
onRenameTab={onRenameTab}
onCloseTabsToLeft={handleCloseTabsToLeft}
onCloseTabsToRight={handleCloseTabsToRight}
onCloseOtherTabs={handleCloseOtherTabs}
onCreateNewTab={onCreateNewTab}
onReorderTabs={handleReorderTabs}
ownsKeyboardShortcuts={false}
externalDndContext
activeDragTabId={activeDragTabId}
tabDropPreviewIndex={
tabDropPreview?.paneId === pane.id ? tabDropPreview.indicatorIndex : null
}
showPaneSplitActions={!focusModeEnabled}
showPaneMaximizeAction={workspaceHasMultiplePanes && !focusModeEnabled}
paneMaximized={paneId === maximizedPaneId}
onTogglePaneMaximized={handleTogglePaneMaximized}
onSplitRight={handleSplitRight}
onSplitDown={handleSplitDown}
focusModeEnabled={Boolean(focusModeEnabled)}
onExitFocusMode={onExitFocusMode}
/>
</WindowChromeSafeArea>
<TitlebarDragSurface style={styles.paneTabsDragSurface}>
<WindowChromeSafeArea placement="inline" style={styles.paneTabs}>
<WorkspaceDesktopTabsRow
paneId={pane.id}
isFocused={isFocused && isWorkspaceFocused}
tabs={desktopTabRowItems}
normalizedServerId={normalizedServerId}
normalizedWorkspaceId={normalizedWorkspaceId}
setHoveredCloseTabKey={setHoveredCloseTabKey}
onNavigateTab={onNavigateTab}
onCloseTab={onCloseTab}
onCopyResumeCommand={onCopyResumeCommand}
onCopyAgentId={onCopyAgentId}
onCopyTerminalId={onCopyTerminalId}
onReloadAgent={onReloadAgent}
onRenameTab={onRenameTab}
onCloseTabsToLeft={handleCloseTabsToLeft}
onCloseTabsToRight={handleCloseTabsToRight}
onCloseOtherTabs={handleCloseOtherTabs}
onCreateNewTab={onCreateNewTab}
onReorderTabs={handleReorderTabs}
ownsKeyboardShortcuts={false}
externalDndContext
activeDragTabId={activeDragTabId}
tabDropPreviewIndex={
tabDropPreview?.paneId === pane.id ? tabDropPreview.indicatorIndex : null
}
showPaneSplitActions={!focusModeEnabled}
showPaneMaximizeAction={workspaceHasMultiplePanes && !focusModeEnabled}
paneMaximized={paneId === maximizedPaneId}
onTogglePaneMaximized={handleTogglePaneMaximized}
onSplitRight={handleSplitRight}
onSplitDown={handleSplitDown}
focusModeEnabled={Boolean(focusModeEnabled)}
onExitFocusMode={onExitFocusMode}
/>
</WindowChromeSafeArea>
</TitlebarDragSurface>
</WindowChromeRegion>
</AdaptiveWorkspaceChrome>
@@ -935,6 +936,10 @@ const styles = StyleSheet.create((theme) => ({
backgroundColor: theme.colors.surface0,
overflow: "hidden",
},
paneTabsDragSurface: {
position: "relative",
minWidth: 0,
},
paneTabs: {
position: "relative",
minWidth: 0,
@@ -278,6 +278,10 @@ describe("control geometry", () => {
expect(geometry.segmentedSegmentMd.borderRadius).toBe(geometry.buttonMd.borderRadius);
expect(geometry.segmentedContainerSm.minHeight).toEqual(geometry.buttonSm.minHeight);
expect(geometry.segmentedContainerMd.minHeight).toEqual(geometry.buttonMd.minHeight);
expect(geometry.segmentedPillsContainerSm.minHeight).toEqual(CONTROL_HEIGHTS.sm);
expect(geometry.segmentedPillsContainerMd.minHeight).toEqual(CONTROL_HEIGHTS.md);
expect(geometry.segmentedPillsContainerSm.paddingHorizontal).toBe(0);
expect(geometry.segmentedPillsContainerSm.paddingVertical).toBe(0);
expect(geometry.segmentedSegmentSm.minHeight).toEqual({ xs: 28, md: 24 });
expect(geometry.segmentedSegmentMd.minHeight).toEqual({ xs: 40, md: 28 });
});
@@ -497,6 +497,18 @@ export function createControlGeometry(theme: Theme) {
gap: SEGMENTED_INSET,
borderRadius: theme.borderRadius.full,
},
segmentedPillsContainerSm: {
minHeight: CONTROL_HEIGHTS.sm,
paddingHorizontal: 0,
paddingVertical: 0,
gap: theme.spacing[1],
},
segmentedPillsContainerMd: {
minHeight: CONTROL_HEIGHTS.md,
paddingHorizontal: 0,
paddingVertical: 0,
gap: theme.spacing[1],
},
segmentedSegmentSm: {
minHeight: mapLayout(CONTROL_HEIGHTS.sm, (height) => height - SEGMENTED_INSET * 2),
paddingHorizontal: theme.spacing[2],
@@ -1,6 +1,7 @@
import React from "react";
import { cleanup, fireEvent, render } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { Button } from "./button";
import { SegmentedControl } from "./segmented-control";
afterEach(cleanup);
@@ -60,4 +61,57 @@ describe("SegmentedControl", () => {
expect(onValueChange).toHaveBeenCalledTimes(1);
expect(onValueChange).toHaveBeenCalledWith("uri");
});
it("renders trackless pills with surface3 selected fill and segment size in pills variant", () => {
const onValueChange = vi.fn();
const onOptionLayout = vi.fn();
const { getByTestId } = render(
<>
<SegmentedControl
size="sm"
testID="track-tabs"
value="all"
onValueChange={vi.fn()}
options={[{ value: "all", label: "All", testID: "track-all" }]}
/>
<Button size="sm" testID="button-sm">
All
</Button>
<SegmentedControl
variant="pills"
size="sm"
testID="filter-tabs"
value="all"
onValueChange={onValueChange}
onOptionLayout={onOptionLayout}
options={[
{ value: "all", label: "All", testID: "tab-all" },
{ value: "actions", label: "Actions", testID: "tab-actions" },
]}
/>
</>,
);
const strip = getByTestId("filter-tabs");
const selected = getByTestId("tab-all");
const unselected = getByTestId("tab-actions");
const trackSegment = getByTestId("track-all");
const buttonSm = getByTestId("button-sm");
expect(getComputedStyle(strip).backgroundColor).toBe("rgba(0, 0, 0, 0)");
expect(getComputedStyle(selected).backgroundColor).toBe("rgb(228, 228, 231)");
expect(getComputedStyle(unselected).backgroundColor).toBe("rgba(0, 0, 0, 0)");
expect(selected.getBoundingClientRect().height).toBe(
trackSegment.getBoundingClientRect().height,
);
expect(selected.getBoundingClientRect().height).toBeLessThan(
buttonSm.getBoundingClientRect().height,
);
expect(selected.getAttribute("aria-selected")).toBe("true");
expect(unselected.getAttribute("aria-selected")).toBe("false");
fireEvent.click(unselected);
expect(onValueChange).toHaveBeenCalledTimes(1);
expect(onValueChange).toHaveBeenCalledWith("actions");
});
});
@@ -1,5 +1,11 @@
import { useCallback, useMemo, type ReactNode } from "react";
import { Pressable, Text, View, type PressableStateCallbackType } from "react-native";
import {
Pressable,
Text,
View,
type LayoutChangeEvent,
type PressableStateCallbackType,
} from "react-native";
import type { StyleProp, TextStyle, ViewStyle } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import {
@@ -23,14 +29,18 @@ export interface SegmentedControlOption<T extends string> {
tooltip?: string;
}
export type SegmentedControlVariant = "track" | "pills";
interface SegmentedControlProps<T extends string> {
options: SegmentedControlOption<T>[];
value: T | null;
onValueChange: (value: T) => void;
size?: ControlSize;
variant?: SegmentedControlVariant;
hideLabels?: boolean;
/** Share the container's width equally between the segments, for a control that heads a surface. */
fill?: boolean;
onOptionLayout?: (value: T, event: LayoutChangeEvent) => void;
style?: StyleProp<ViewStyle>;
testID?: string;
}
@@ -55,25 +65,36 @@ export function SegmentedControl<T extends string>({
value,
onValueChange,
size: sizeProp,
variant = "track",
hideLabels = false,
fill = false,
onOptionLayout,
style,
testID,
}: SegmentedControlProps<T>) {
const containedSize = useContainedControlSize();
const size = sizeProp ?? containedSize ?? "md";
const sizeStyles = {
sm: { container: styles.containerSm, segment: styles.segmentSm, label: styles.labelSm },
md: { container: styles.containerMd, segment: styles.segmentMd, label: styles.labelMd },
sm: {
container: variant === "pills" ? styles.containerPillsSm : styles.containerSm,
segment: styles.segmentSm,
label: styles.labelSm,
},
md: {
container: variant === "pills" ? styles.containerPillsMd : styles.containerMd,
segment: styles.segmentMd,
label: styles.labelMd,
},
}[size];
const containerVariantStyle = variant === "pills" ? styles.containerPills : styles.containerTrack;
const containerSizeStyle = sizeStyles.container;
const segmentSizeStyle = sizeStyles.segment;
const labelSizeStyle = sizeStyles.label;
const iconSize = controlIconSize[size];
const containerStyle = useMemo(
() => [styles.container, containerSizeStyle, style],
[containerSizeStyle, style],
() => [styles.container, containerVariantStyle, containerSizeStyle, style],
[containerSizeStyle, containerVariantStyle, style],
);
return (
@@ -86,6 +107,7 @@ export function SegmentedControl<T extends string>({
key={option.value}
option={option}
isSelected={isSelected}
variant={variant}
iconSize={iconSize}
hideLabels={hideLabels}
fill={fill}
@@ -93,6 +115,7 @@ export function SegmentedControl<T extends string>({
labelSizeStyle={labelSizeStyle}
currentValue={value}
onValueChange={onValueChange}
onOptionLayout={onOptionLayout}
/>
);
})}
@@ -103,6 +126,7 @@ export function SegmentedControl<T extends string>({
function SegmentItem<T extends string>({
option,
isSelected,
variant,
iconSize,
hideLabels,
fill,
@@ -110,9 +134,11 @@ function SegmentItem<T extends string>({
labelSizeStyle,
currentValue,
onValueChange,
onOptionLayout,
}: {
option: SegmentedControlOption<T>;
isSelected: boolean;
variant: SegmentedControlVariant;
iconSize: number;
hideLabels: boolean;
fill: boolean;
@@ -120,6 +146,7 @@ function SegmentItem<T extends string>({
labelSizeStyle: StyleProp<TextStyle>;
currentValue: T | null;
onValueChange: (value: T) => void;
onOptionLayout?: (value: T, event: LayoutChangeEvent) => void;
}) {
const labelStyle = useMemo(
() => [styles.label, labelSizeStyle, isSelected && styles.labelSelected],
@@ -130,17 +157,24 @@ function SegmentItem<T extends string>({
onValueChange(option.value);
}
}, [option.disabled, option.value, currentValue, onValueChange]);
const handleLayout = useCallback(
(event: LayoutChangeEvent) => {
onOptionLayout?.(option.value, event);
},
[onOptionLayout, option.value],
);
const selectedStyle = variant === "pills" ? styles.segmentPillSelected : styles.segmentSelected;
const pressableStyle = useCallback(
({ hovered, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [
styles.segment,
segmentSizeStyle,
fill && styles.segmentFill,
isSelected && styles.segmentSelected,
isSelected && selectedStyle,
Boolean(hovered) && !isSelected && styles.segmentHover,
pressed && !isSelected && styles.segmentPressed,
option.disabled && styles.segmentDisabled,
],
[fill, isSelected, option.disabled, segmentSizeStyle],
[fill, isSelected, option.disabled, segmentSizeStyle, selectedStyle],
);
const accessibilityState = useMemo(
() => ({ selected: isSelected, disabled: option.disabled }),
@@ -154,6 +188,7 @@ function SegmentItem<T extends string>({
disabled={option.disabled}
testID={option.testID}
onPress={handlePress}
onLayout={onOptionLayout ? handleLayout : undefined}
style={pressableStyle}
>
{option.icon ? (
@@ -188,14 +223,25 @@ const styles = StyleSheet.create((theme) => {
container: {
flexDirection: "row",
alignItems: "center",
},
containerTrack: {
backgroundColor: theme.colors.surface2,
},
containerPills: {
backgroundColor: "transparent",
},
containerSm: {
...geometry.segmentedContainerSm,
},
containerMd: {
...geometry.segmentedContainerMd,
},
containerPillsSm: {
...geometry.segmentedPillsContainerSm,
},
containerPillsMd: {
...geometry.segmentedPillsContainerMd,
},
segment: {
flexDirection: "row",
alignItems: "center",
@@ -226,6 +272,9 @@ const styles = StyleSheet.create((theme) => {
shadowOpacity: 1,
elevation: 1,
},
segmentPillSelected: {
backgroundColor: theme.colors.surface3,
},
segmentHover: {
backgroundColor: theme.colors.interactionHighlight,
},
+66
View File
@@ -716,6 +716,72 @@ describe("server data push router", () => {
unmount();
});
it("routes diff updates for Windows paths even when fallback query-key matching is used", () => {
const queryClient = new QueryClient();
const fake = createFakeClient();
const serverId = "server-1";
const rawCwd = "f:\\repo\\";
const queryKey = checkoutDiffQueryKey(serverId, rawCwd, "uncommitted", undefined, false);
const subscriptionId = `checkoutDiff:${JSON.stringify(queryKey)}`;
const observer = new QueryObserver(queryClient, {
queryKey,
queryFn: skipToken,
enabled: true,
gcTime: Infinity,
staleTime: Infinity,
meta: checkoutDiffPushRoute({
enabled: true,
serverId,
subscriptionId,
cwd: rawCwd,
compare: { mode: "uncommitted", ignoreWhitespace: false },
}),
});
const unsubscribeObserver = observer.subscribe(() => undefined);
const unmount = mountServerDataPushRouter({ client: fake.client, queryClient, serverId });
const serverSubscriptionId = fake.subscribeCheckoutDiffCalls[0]!.subscriptionId;
const plainObserver = new QueryObserver(queryClient, {
queryKey,
queryFn: skipToken,
enabled: true,
gcTime: Infinity,
staleTime: Infinity,
});
const unsubscribePlainObserver = plainObserver.subscribe(() => undefined);
const query = queryClient.getQueryCache().find({ queryKey, exact: true });
query?.setOptions({ ...query.options, meta: undefined });
unsubscribeObserver();
expect(fake.unsubscribeCheckoutDiffCalls).toEqual([]);
fake.emit({
type: "checkout_diff_update",
payload: {
subscriptionId: serverSubscriptionId,
cwd: rawCwd,
files: [],
error: null,
diffTooLarge: false,
},
});
expect(
queryClient.getQueryData(
checkoutDiffQueryKey(serverId, "F:/repo", "uncommitted", undefined, false),
),
).toEqual({
cwd: rawCwd,
files: [],
error: null,
diffTooLarge: false,
requestId: "diff:2:ready",
});
unsubscribePlainObserver();
unmount();
});
it("does not retry failed subscriptions on unrelated cache events", async () => {
const queryClient = new QueryClient();
const fake = createFakeClient({ rejectCheckoutDiffSubscribe: true });
+5 -1
View File
@@ -23,6 +23,7 @@ import {
providersSnapshotQueryKey,
providersSnapshotQueryRoot,
} from "@/data/providers-snapshot";
import { normalizeWorkspacePath } from "@/utils/workspace-identity";
type ProvidersSnapshotUpdateMessage = Extract<
SessionOutboundMessage,
@@ -702,10 +703,13 @@ function areCheckoutDiffRoutesEqual(
}
function isCheckoutDiffQueryKeyForRoute(queryKey: QueryKey, route: CheckoutDiffRoute): boolean {
const keyCwd =
typeof queryKey[2] === "string" ? (normalizeWorkspacePath(queryKey[2]) ?? queryKey[2]) : null;
const routeCwd = normalizeWorkspacePath(route.cwd) ?? route.cwd;
return (
queryKey[0] === "checkoutDiff" &&
queryKey[1] === route.serverId &&
queryKey[2] === route.cwd &&
keyCwd === routeCwd &&
queryKey[3] === route.compare.mode &&
queryKey[4] === (route.compare.baseRef ?? "") &&
queryKey[5] === (route.compare.ignoreWhitespace === true)
+1 -42
View File
@@ -1,8 +1,4 @@
import {
getDesktopHost,
type DesktopWindowBridge,
type DesktopWindowChromeUpdate,
} from "@/desktop/host";
import { getDesktopHost, type DesktopWindowBridge } from "@/desktop/host";
export function getDesktopWindow(): DesktopWindowBridge | null {
const getter = getDesktopHost()?.window?.getCurrentWindow;
@@ -15,40 +11,3 @@ export function getDesktopWindow(): DesktopWindowBridge | null {
return null;
}
}
export async function minimizeDesktopWindow(): Promise<void> {
await getDesktopWindow()?.minimize?.();
}
export async function closeDesktopWindow(): Promise<void> {
await getDesktopWindow()?.close?.();
}
export async function toggleDesktopMaximize(): Promise<void> {
const win = getDesktopWindow();
if (!win || typeof win.toggleMaximize !== "function") {
return;
}
await win.toggleMaximize();
}
export async function isDesktopMaximized(): Promise<boolean> {
return (await getDesktopWindow()?.isMaximized?.()) ?? false;
}
export async function isDesktopFullscreen(): Promise<boolean> {
const win = getDesktopWindow();
if (!win || typeof win.isFullscreen !== "function") {
return false;
}
return await win.isFullscreen();
}
export async function updateDesktopWindowChrome(update: DesktopWindowChromeUpdate): Promise<void> {
const win = getDesktopWindow();
if (!win || typeof win.updateChrome !== "function") {
return;
}
await win.updateChrome(update);
}
@@ -0,0 +1,260 @@
import { DeviceEventEmitter, Platform, processColor, TurboModuleRegistry } from "react-native";
import type { DesktopWindowChromeMode } from "@/desktop/host";
import type {
DesktopWindowChromeHost,
DesktopWindowChromeSnapshot,
DesktopWindowChromeUpdate,
} from "./window-chrome-host.types";
export type {
DesktopWindowChromeHost,
DesktopWindowChromeSnapshot,
DesktopWindowChromeUpdate,
} from "./window-chrome-host.types";
const MAIN_WINDOW_ID = 1;
export interface GpuiWindowStateResult {
windowId?: number;
isFullscreen?: boolean;
isMaximized?: boolean;
}
export interface GpuiWindowsModule {
windowGetStateSync?(windowId: number): GpuiWindowStateResult | null | undefined;
windowMinimize?(windowId: number): Promise<void>;
windowToggleMaximize?(windowId: number): Promise<void>;
windowClose?(windowId: number, force: boolean): Promise<void>;
windowSetFullscreen?(windowId: number, fullscreen: boolean): Promise<void>;
windowSetBackgroundColor?(windowId: number, color: number): Promise<void>;
windowSetChromeAppearance?(windowId: number, appearance: string): Promise<void>;
}
export interface GpuiDesktopModule {
capabilities?(): { clientDecorations?: boolean; menuBarInWindow?: boolean } | null | undefined;
}
export interface GpuiAppMenuModule {
menuSetMenuBarVisible?(visible: boolean, windowId?: number): Promise<void>;
}
export interface GpuiEventSubscription {
remove(): void;
}
export interface GpuiWindowChromeDeps {
getPlatformOS: () => string;
getWindowsModule: () => GpuiWindowsModule | null;
getDesktopModule: () => GpuiDesktopModule | null;
getAppMenuModule?: () => GpuiAppMenuModule | null;
addEventListener: (
eventName: string,
handler: (payload: unknown) => void,
) => GpuiEventSubscription;
resolveColor: (color: string) => number | null | undefined;
}
const DEFAULT_GPUI_DEPS: GpuiWindowChromeDeps = {
getPlatformOS: () => Platform.OS,
getWindowsModule: () => TurboModuleRegistry.get("GpuiWindows") as GpuiWindowsModule | null,
getDesktopModule: () => TurboModuleRegistry.get("GpuiDesktop") as GpuiDesktopModule | null,
getAppMenuModule: () => TurboModuleRegistry.get("GpuiAppMenu") as GpuiAppMenuModule | null,
addEventListener: (eventName, handler) => DeviceEventEmitter.addListener(eventName, handler),
resolveColor: (color) => {
const resolved = processColor(color);
return typeof resolved === "number" ? resolved : null;
},
};
function resolveChromeMode(deps: GpuiWindowChromeDeps): DesktopWindowChromeMode | null {
const os = deps.getPlatformOS();
if (os === "macos") return "native-mac";
if (os === "windows") return "custom-windows";
if (os === "linux") {
return deps.getDesktopModule()?.capabilities?.()?.clientDecorations ? "custom-linux" : null;
}
return null;
}
function readWindowFlags(deps: GpuiWindowChromeDeps): {
isFullscreen: boolean;
isMaximized: boolean;
} {
try {
const state = deps.getWindowsModule()?.windowGetStateSync?.(MAIN_WINDOW_ID);
return {
isFullscreen: Boolean(state?.isFullscreen),
isMaximized: Boolean(state?.isMaximized),
};
} catch {
return { isFullscreen: false, isMaximized: false };
}
}
function isUnsupportedError(error: unknown): boolean {
if (typeof error !== "object" || error === null) {
return false;
}
const code = (error as { code?: unknown }).code;
if (code === "unsupported") {
return true;
}
const message = (error as { message?: unknown }).message;
return typeof message === "string" && /not supported/i.test(message);
}
function ignoreUnsupported(promise: Promise<void> | undefined): Promise<void> {
if (!promise) return Promise.resolve();
return promise.catch((error: unknown) => {
if (!isUnsupportedError(error)) {
throw error;
}
});
}
export function createGpuiWindowChromeHost(
deps: GpuiWindowChromeDeps = DEFAULT_GPUI_DEPS,
): DesktopWindowChromeHost {
const listeners = new Set<() => void>();
let snapshot: DesktopWindowChromeSnapshot | null = null;
let stateSub: GpuiEventSubscription | undefined;
let decorationsSub: GpuiEventSubscription | undefined;
function readSnapshot(): DesktopWindowChromeSnapshot {
const { isFullscreen, isMaximized } = readWindowFlags(deps);
return {
mode: resolveChromeMode(deps),
isFullscreen,
isMaximized,
};
}
function ensureSnapshot(): DesktopWindowChromeSnapshot {
if (snapshot === null) {
snapshot = readSnapshot();
}
return snapshot;
}
function setSnapshot(next: DesktopWindowChromeSnapshot): void {
const current = ensureSnapshot();
if (
current.mode === next.mode &&
current.isFullscreen === next.isFullscreen &&
current.isMaximized === next.isMaximized
) {
return;
}
snapshot = next;
for (const listener of listeners) {
listener();
}
}
function startListening(): void {
if (deps.getDesktopModule()?.capabilities?.()?.menuBarInWindow) {
// Re-sync hidden menu bar so rn-gpui reclaims the 26pt strip reserved before bootstrap hid it.
void deps
.getAppMenuModule?.()
?.menuSetMenuBarVisible?.(false, MAIN_WINDOW_ID)
?.catch(() => {});
}
stateSub = deps.addEventListener("gpuiDesktop:windowStateChange", (payload: unknown) => {
if (!payload || typeof payload !== "object") return;
const event = payload as {
windowId?: unknown;
isFullscreen?: unknown;
isMaximized?: unknown;
};
if (event.windowId !== MAIN_WINDOW_ID) return;
const current = ensureSnapshot();
setSnapshot({
mode: resolveChromeMode(deps),
isFullscreen:
typeof event.isFullscreen === "boolean" ? event.isFullscreen : current.isFullscreen,
isMaximized:
typeof event.isMaximized === "boolean" ? event.isMaximized : current.isMaximized,
});
});
decorationsSub = deps.addEventListener("gpuiDesktop:windowDecorations", () => {
const current = ensureSnapshot();
setSnapshot({
mode: resolveChromeMode(deps),
isFullscreen: current.isFullscreen,
isMaximized: current.isMaximized,
});
});
setSnapshot(readSnapshot());
}
function stopListening(): void {
stateSub?.remove();
stateSub = undefined;
decorationsSub?.remove();
decorationsSub = undefined;
}
return {
getSnapshot() {
const current = ensureSnapshot();
if (!stateSub) {
const next = readSnapshot();
if (
current.mode !== next.mode ||
current.isFullscreen !== next.isFullscreen ||
current.isMaximized !== next.isMaximized
) {
snapshot = next;
}
}
return ensureSnapshot();
},
subscribe(listener) {
listeners.add(listener);
if (listeners.size === 1) {
startListening();
}
return () => {
listeners.delete(listener);
if (listeners.size === 0) {
stopListening();
}
};
},
async minimize() {
await deps.getWindowsModule()?.windowMinimize?.(MAIN_WINDOW_ID);
},
async toggleMaximize() {
await deps.getWindowsModule()?.windowToggleMaximize?.(MAIN_WINDOW_ID);
},
async close() {
await deps.getWindowsModule()?.windowClose?.(MAIN_WINDOW_ID, false);
},
async setFullscreen(fullscreen: boolean) {
await deps.getWindowsModule()?.windowSetFullscreen?.(MAIN_WINDOW_ID, fullscreen);
},
async updateChrome(update: DesktopWindowChromeUpdate) {
if (deps.getPlatformOS() !== "macos") return;
const win = deps.getWindowsModule();
if (!win) return;
const tasks: Promise<void>[] = [];
if (update.backgroundColor !== undefined) {
const argb = deps.resolveColor(update.backgroundColor);
if (typeof argb === "number") {
tasks.push(ignoreUnsupported(win.windowSetBackgroundColor?.(MAIN_WINDOW_ID, argb)));
}
}
if (update.appearance !== undefined) {
tasks.push(
ignoreUnsupported(win.windowSetChromeAppearance?.(MAIN_WINDOW_ID, update.appearance)),
);
}
await Promise.all(tasks);
},
};
}
export const desktopWindowChromeHost: DesktopWindowChromeHost = createGpuiWindowChromeHost();
@@ -0,0 +1,23 @@
import type {
DesktopWindowChromeHost,
DesktopWindowChromeSnapshot,
} from "./window-chrome-host.types";
const NOOP_SNAPSHOT: DesktopWindowChromeSnapshot = {
mode: null,
isFullscreen: false,
isMaximized: false,
};
const noopAsync = async (): Promise<void> => {};
const noopUnsubscribe = (): void => {};
export const desktopWindowChromeHost: DesktopWindowChromeHost = {
getSnapshot: () => NOOP_SNAPSHOT,
subscribe: () => noopUnsubscribe,
minimize: noopAsync,
toggleMaximize: noopAsync,
close: noopAsync,
setFullscreen: noopAsync,
updateChrome: noopAsync,
};
@@ -0,0 +1,389 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import type { DesktopWindowBridge, DesktopWindowChromeMode } from "@/desktop/host";
import { desktopWindowChromeHost as defaultWindowChromeHost } from "@/desktop/window-chrome-host.noop";
import {
createElectronWindowChromeHost,
type ElectronWindowChromeDeps,
} from "@/desktop/window-chrome-host.web";
import {
createGpuiWindowChromeHost,
type GpuiDesktopModule,
type GpuiWindowChromeDeps,
type GpuiWindowsModule,
} from "@/desktop/window-chrome-host.gpui";
interface FakeElectronBridgeOptions {
mode: DesktopWindowChromeMode;
ready?: boolean;
isFullscreen?: boolean;
isMaximized?: boolean;
}
function createFakeElectronDeps(options: FakeElectronBridgeOptions) {
let ready = options.ready ?? true;
let isFullscreen = options.isFullscreen ?? false;
let isMaximized = options.isMaximized ?? false;
let resizeHandler: (() => void) | null = null;
const calls: Array<{ method: string; arg?: unknown }> = [];
const bridge: DesktopWindowBridge = {
minimize: async () => {
calls.push({ method: "minimize" });
},
toggleMaximize: async () => {
calls.push({ method: "toggleMaximize" });
},
close: async () => {
calls.push({ method: "close" });
},
setFullscreen: async (fullscreen: boolean) => {
calls.push({ method: "setFullscreen", arg: fullscreen });
},
updateChrome: async (update) => {
calls.push({ method: "updateChrome", arg: update });
},
isFullscreen: async () => isFullscreen,
isMaximized: async () => isMaximized,
onResized: <TEvent = unknown>(handler: (event: TEvent) => void) => {
const invoke = () => handler({} as TEvent);
resizeHandler = invoke;
return () => {
if (resizeHandler === invoke) {
resizeHandler = null;
}
};
},
};
const deps: ElectronWindowChromeDeps = {
isElectronRuntime: () => ready,
getChromeMode: () => (ready ? options.mode : null),
getWindow: () => (ready ? bridge : null),
};
return {
deps,
calls,
hasResizeListener: () => resizeHandler !== null,
setReady(nextReady: boolean) {
ready = nextReady;
},
emitResize(next: { isFullscreen?: boolean; isMaximized?: boolean }) {
if (next.isFullscreen !== undefined) isFullscreen = next.isFullscreen;
if (next.isMaximized !== undefined) isMaximized = next.isMaximized;
resizeHandler?.();
},
};
}
async function flushAsyncWork() {
await Promise.resolve();
await Promise.resolve();
await Promise.resolve();
}
describe("window-chrome-host", () => {
afterEach(() => {
vi.useRealTimers();
});
it("provides a null-mode no-op host through the default module", async () => {
expect(defaultWindowChromeHost.getSnapshot()).toEqual({
mode: null,
isFullscreen: false,
isMaximized: false,
});
const listener = vi.fn();
const unsubscribe = defaultWindowChromeHost.subscribe(listener);
await expect(defaultWindowChromeHost.minimize()).resolves.toBeUndefined();
await expect(defaultWindowChromeHost.toggleMaximize()).resolves.toBeUndefined();
await expect(defaultWindowChromeHost.close()).resolves.toBeUndefined();
await expect(defaultWindowChromeHost.setFullscreen(true)).resolves.toBeUndefined();
await expect(
defaultWindowChromeHost.updateChrome({ backgroundColor: "#181b1a", appearance: "dark" }),
).resolves.toBeUndefined();
unsubscribe();
expect(listener).not.toHaveBeenCalled();
});
it("syncs Electron window state, forwards commands, and strips GPUI-only chrome fields", async () => {
const fake = createFakeElectronDeps({
mode: "custom-linux",
isFullscreen: false,
isMaximized: false,
});
const host = createElectronWindowChromeHost(fake.deps);
expect(host.getSnapshot()).toEqual({
mode: "custom-linux",
isFullscreen: false,
isMaximized: false,
});
const onChange = vi.fn();
const unsubscribe = host.subscribe(onChange);
await flushAsyncWork();
expect(fake.hasResizeListener()).toBe(true);
fake.emitResize({ isMaximized: true });
await flushAsyncWork();
expect(host.getSnapshot()).toEqual({
mode: "custom-linux",
isFullscreen: false,
isMaximized: true,
});
expect(onChange).toHaveBeenCalled();
fake.emitResize({ isFullscreen: true });
await flushAsyncWork();
expect(host.getSnapshot()).toEqual({
mode: "custom-linux",
isFullscreen: true,
isMaximized: true,
});
await host.minimize();
await host.toggleMaximize();
await host.close();
await host.setFullscreen(false);
await host.updateChrome({
backgroundColor: "#181B1A",
appearance: "dark",
trafficLightOffsetY: -4,
});
expect(fake.calls).toEqual([
{ method: "minimize" },
{ method: "toggleMaximize" },
{ method: "close" },
{ method: "setFullscreen", arg: false },
{
method: "updateChrome",
arg: { backgroundColor: "#181B1A", trafficLightOffsetY: -4 },
},
]);
unsubscribe();
expect(fake.hasResizeListener()).toBe(false);
});
it("retries until the Electron preload bridge becomes available", async () => {
vi.useFakeTimers();
const fake = createFakeElectronDeps({
mode: "native-mac",
ready: false,
isFullscreen: false,
isMaximized: false,
});
const host = createElectronWindowChromeHost(fake.deps);
expect(host.getSnapshot()).toEqual({
mode: null,
isFullscreen: false,
isMaximized: false,
});
const onChange = vi.fn();
const unsubscribe = host.subscribe(onChange);
expect(onChange).not.toHaveBeenCalled();
fake.setReady(true);
await vi.advanceTimersByTimeAsync(250);
await flushAsyncWork();
expect(fake.hasResizeListener()).toBe(true);
expect(host.getSnapshot()).toEqual({
mode: "native-mac",
isFullscreen: false,
isMaximized: false,
});
expect(onChange).toHaveBeenCalled();
unsubscribe();
});
it("reads GPUI sync window state, maps OS/CSD chrome modes, subscribes to main-window events, and forwards commands", async () => {
let platformOS = "macos";
let clientDecorations = true;
let isFullscreen = false;
let isMaximized = true;
const listeners = new Map<string, Set<(payload: unknown) => void>>();
const calls: Array<{ method: string; args: unknown[] }> = [];
const windowsModule: GpuiWindowsModule = {
windowGetStateSync: (windowId) => ({
windowId,
isFullscreen,
isMaximized,
}),
windowMinimize: async (windowId) => {
calls.push({ method: "windowMinimize", args: [windowId] });
},
windowToggleMaximize: async (windowId) => {
calls.push({ method: "windowToggleMaximize", args: [windowId] });
},
windowClose: async (windowId, force) => {
calls.push({ method: "windowClose", args: [windowId, force] });
},
windowSetFullscreen: async (windowId, fullscreen) => {
calls.push({ method: "windowSetFullscreen", args: [windowId, fullscreen] });
},
windowSetBackgroundColor: async (windowId, color) => {
calls.push({ method: "windowSetBackgroundColor", args: [windowId, color] });
},
windowSetChromeAppearance: async (windowId, appearance) => {
calls.push({ method: "windowSetChromeAppearance", args: [windowId, appearance] });
},
};
const desktopModule: GpuiDesktopModule = {
capabilities: () => ({ clientDecorations, menuBarInWindow: platformOS !== "macos" }),
};
const deps: GpuiWindowChromeDeps = {
getPlatformOS: () => platformOS,
getWindowsModule: () => windowsModule,
getDesktopModule: () => desktopModule,
getAppMenuModule: () => ({
menuSetMenuBarVisible: async (visible, windowId) => {
calls.push({ method: "menuSetMenuBarVisible", args: [visible, windowId] });
},
}),
addEventListener: (eventName, handler) => {
let bucket = listeners.get(eventName);
if (!bucket) {
bucket = new Set();
listeners.set(eventName, bucket);
}
bucket.add(handler);
return {
remove: () => {
bucket.delete(handler);
},
};
},
resolveColor: () => 0xff181b1a,
};
const emit = (eventName: string, payload: unknown) => {
for (const handler of listeners.get(eventName) ?? []) {
handler(payload);
}
};
// macOS -> native-mac with initial sync state
const macHost = createGpuiWindowChromeHost(deps);
expect(macHost.getSnapshot()).toEqual({
mode: "native-mac",
isFullscreen: false,
isMaximized: true,
});
// Windows -> custom-windows
platformOS = "windows";
expect(createGpuiWindowChromeHost(deps).getSnapshot().mode).toBe("custom-windows");
// Linux -> custom-linux when CSD is active, null when SSD
platformOS = "linux";
isMaximized = false;
const linuxHost = createGpuiWindowChromeHost(deps);
expect(linuxHost.getSnapshot()).toEqual({
mode: "custom-linux",
isFullscreen: false,
isMaximized: false,
});
const onChange = vi.fn();
const unsubscribe = linuxHost.subscribe(onChange);
expect(listeners.get("gpuiDesktop:windowStateChange")?.size).toBe(1);
expect(listeners.get("gpuiDesktop:windowDecorations")?.size).toBe(1);
// Secondary window state changes must not affect main window snapshot
emit("gpuiDesktop:windowStateChange", {
windowId: 2,
isFullscreen: true,
isMaximized: true,
});
expect(linuxHost.getSnapshot()).toEqual({
mode: "custom-linux",
isFullscreen: false,
isMaximized: false,
});
// Main window state changes update snapshot
emit("gpuiDesktop:windowStateChange", {
windowId: 1,
isFullscreen: true,
isMaximized: true,
});
expect(linuxHost.getSnapshot()).toEqual({
mode: "custom-linux",
isFullscreen: true,
isMaximized: true,
});
// Wayland decorations settling to SSD switches mode to null
clientDecorations = false;
emit("gpuiDesktop:windowDecorations", {});
expect(linuxHost.getSnapshot()).toEqual({
mode: null,
isFullscreen: true,
isMaximized: true,
});
expect(onChange).toHaveBeenCalledTimes(2);
await linuxHost.minimize();
await linuxHost.toggleMaximize();
await linuxHost.close();
await linuxHost.setFullscreen(false);
// Non-macOS updateChrome skips unsupported macOS-only calls; macOS forwards them.
await linuxHost.updateChrome({
backgroundColor: "#181B1A",
appearance: "dark",
trafficLightOffsetY: -4,
});
platformOS = "macos";
await linuxHost.updateChrome({
backgroundColor: "#181B1A",
appearance: "dark",
trafficLightOffsetY: -4,
});
expect(calls).toEqual([
{ method: "menuSetMenuBarVisible", args: [false, 1] },
{ method: "windowMinimize", args: [1] },
{ method: "windowToggleMaximize", args: [1] },
{ method: "windowClose", args: [1, false] },
{ method: "windowSetFullscreen", args: [1, false] },
{ method: "windowSetBackgroundColor", args: [1, 0xff181b1a] },
{ method: "windowSetChromeAppearance", args: [1, "dark"] },
]);
unsubscribe();
expect(listeners.get("gpuiDesktop:windowStateChange")?.size).toBe(0);
expect(listeners.get("gpuiDesktop:windowDecorations")?.size).toBe(0);
});
it("ignores unsupported rejections in GPUI updateChrome", async () => {
const unsupported = Object.assign(
new Error("window background colors are not supported on this platform"),
{
code: "",
},
);
const host = createGpuiWindowChromeHost({
getPlatformOS: () => "macos",
getWindowsModule: () => ({
windowSetBackgroundColor: async () => {
throw unsupported;
},
windowSetChromeAppearance: async () => {
throw Object.assign(new Error("unsupported"), { code: "unsupported" });
},
}),
getDesktopModule: () => ({ capabilities: () => ({ clientDecorations: true }) }),
addEventListener: () => ({ remove: () => {} }),
resolveColor: () => 0xff181b1a,
});
await expect(
host.updateChrome({ backgroundColor: "#181B1A", appearance: "dark" }),
).resolves.toBeUndefined();
});
});
@@ -0,0 +1,7 @@
export type {
DesktopWindowChromeHost,
DesktopWindowChromeSnapshot,
DesktopWindowChromeUpdate,
} from "./window-chrome-host.types";
export { desktopWindowChromeHost } from "./window-chrome-host.noop";
@@ -0,0 +1,23 @@
import type { DesktopWindowChromeMode } from "@/desktop/host";
export interface DesktopWindowChromeSnapshot {
mode: DesktopWindowChromeMode | null;
isFullscreen: boolean;
isMaximized: boolean;
}
export interface DesktopWindowChromeUpdate {
backgroundColor?: string;
appearance?: "light" | "dark" | "system";
trafficLightOffsetY?: number;
}
export interface DesktopWindowChromeHost {
getSnapshot(): DesktopWindowChromeSnapshot;
subscribe(listener: () => void): () => void;
minimize(): Promise<void>;
toggleMaximize(): Promise<void>;
close(): Promise<void>;
setFullscreen(fullscreen: boolean): Promise<void>;
updateChrome(update: DesktopWindowChromeUpdate): Promise<void>;
}
@@ -0,0 +1,253 @@
import { getDesktopWindow } from "@/desktop/electron/window";
import {
getDesktopWindowChromeMode,
isElectronRuntime,
type DesktopWindowBridge,
type DesktopWindowChromeMode,
} from "@/desktop/host";
import type {
DesktopWindowChromeHost,
DesktopWindowChromeSnapshot,
DesktopWindowChromeUpdate,
} from "./window-chrome-host.types";
export type {
DesktopWindowChromeHost,
DesktopWindowChromeSnapshot,
DesktopWindowChromeUpdate,
} from "./window-chrome-host.types";
export interface ElectronWindowChromeDeps {
isElectronRuntime: () => boolean;
getChromeMode: () => DesktopWindowChromeMode | null;
getWindow: () => DesktopWindowBridge | null;
}
const DEFAULT_ELECTRON_DEPS: ElectronWindowChromeDeps = {
isElectronRuntime,
getChromeMode: getDesktopWindowChromeMode,
getWindow: getDesktopWindow,
};
const MAX_PRELOAD_RETRIES = 40;
const PRELOAD_RETRY_DELAY_MS = 250;
export function createElectronWindowChromeHost(
deps: ElectronWindowChromeDeps = DEFAULT_ELECTRON_DEPS,
): DesktopWindowChromeHost {
const listeners = new Set<() => void>();
const readCurrentMode = () => (deps.isElectronRuntime() ? deps.getChromeMode() : null);
let snapshot: DesktopWindowChromeSnapshot | null = null;
let connectionGeneration = 0;
let connecting = false;
let disposeResize: (() => void) | undefined;
let retryCount = 0;
let retryTimer: ReturnType<typeof setTimeout> | undefined;
function ensureSnapshot(): DesktopWindowChromeSnapshot {
if (snapshot === null) {
snapshot = {
mode: readCurrentMode(),
isFullscreen: false,
isMaximized: false,
};
}
return snapshot;
}
function setSnapshot(next: DesktopWindowChromeSnapshot): void {
const current = ensureSnapshot();
if (
current.mode === next.mode &&
current.isFullscreen === next.isFullscreen &&
current.isMaximized === next.isMaximized
) {
return;
}
snapshot = next;
for (const listener of listeners) {
listener();
}
}
function stopConnection(): void {
connectionGeneration += 1;
connecting = false;
retryCount = 0;
if (retryTimer) {
clearTimeout(retryTimer);
retryTimer = undefined;
}
const dispose = disposeResize;
disposeResize = undefined;
dispose?.();
}
function scheduleRetry(generation: number, warnOnExhaustion = false): void {
if (
generation !== connectionGeneration ||
listeners.size === 0 ||
disposeResize ||
retryTimer
) {
return;
}
if (retryCount >= MAX_PRELOAD_RETRIES) {
if (warnOnExhaustion) {
console.warn("[DesktopWindow] Chrome bridge unavailable; window controls may overlap UI");
}
return;
}
retryCount += 1;
retryTimer = setTimeout(() => {
retryTimer = undefined;
connect(generation);
}, PRELOAD_RETRY_DELAY_MS);
}
function connect(generation: number): void {
if (
generation !== connectionGeneration ||
listeners.size === 0 ||
disposeResize ||
connecting
) {
return;
}
if (!deps.isElectronRuntime()) {
scheduleRetry(generation);
return;
}
const desktopWindow = deps.getWindow();
if (
!desktopWindow ||
typeof desktopWindow.isFullscreen !== "function" ||
typeof desktopWindow.onResized !== "function"
) {
scheduleRetry(generation, true);
return;
}
const readFullscreen = desktopWindow.isFullscreen;
const readMaximized = desktopWindow.isMaximized;
const subscribeToResized = desktopWindow.onResized;
connecting = true;
void (async () => {
async function syncWindowState(): Promise<void> {
if (generation !== connectionGeneration || listeners.size === 0) return;
try {
const [isFullscreen, isMaximized] = await Promise.all([
readFullscreen(),
readMaximized?.() ?? false,
]);
if (generation !== connectionGeneration || listeners.size === 0) return;
setSnapshot({
mode: readCurrentMode(),
isFullscreen,
isMaximized,
});
} catch (error) {
if (generation === connectionGeneration && listeners.size > 0) {
console.warn("[DesktopWindow] Failed to read window state", error);
}
}
}
try {
const nextDispose = await subscribeToResized(() => {
void syncWindowState();
});
if (generation !== connectionGeneration || listeners.size === 0) {
nextDispose();
return;
}
disposeResize = nextDispose;
const current = ensureSnapshot();
setSnapshot({
mode: readCurrentMode(),
isFullscreen: current.isFullscreen,
isMaximized: current.isMaximized,
});
await syncWindowState();
} catch (error) {
if (generation === connectionGeneration && listeners.size > 0) {
console.warn("[DesktopWindow] Failed to subscribe to resize", error);
}
} finally {
if (generation === connectionGeneration) {
connecting = false;
if (!disposeResize) {
scheduleRetry(generation);
}
}
}
})();
}
return {
getSnapshot() {
const current = ensureSnapshot();
if (!disposeResize) {
const mode = readCurrentMode();
if (mode !== current.mode) {
snapshot = {
mode,
isFullscreen: false,
isMaximized: false,
};
}
}
return ensureSnapshot();
},
subscribe(listener) {
listeners.add(listener);
if (listeners.size === 1) {
connect(connectionGeneration);
}
return () => {
listeners.delete(listener);
if (listeners.size === 0) {
stopConnection();
}
};
},
async minimize() {
await deps.getWindow()?.minimize?.();
},
async toggleMaximize() {
const win = deps.getWindow();
if (typeof win?.toggleMaximize === "function") {
await win.toggleMaximize();
}
},
async close() {
await deps.getWindow()?.close?.();
},
async setFullscreen(fullscreen: boolean) {
await deps.getWindow()?.setFullscreen?.(fullscreen);
},
async updateChrome(update: DesktopWindowChromeUpdate) {
const win = deps.getWindow();
if (typeof win?.updateChrome !== "function") {
return;
}
const electronUpdate = {
...(update.backgroundColor !== undefined
? { backgroundColor: update.backgroundColor }
: {}),
...(update.trafficLightOffsetY !== undefined
? { trafficLightOffsetY: update.trafficLightOffsetY }
: {}),
};
if (
electronUpdate.backgroundColor === undefined &&
electronUpdate.trafficLightOffsetY === undefined
) {
return;
}
await win.updateChrome(electronUpdate);
},
};
}
export const desktopWindowChromeHost: DesktopWindowChromeHost = createElectronWindowChromeHost();
@@ -73,6 +73,33 @@ describe("checkout-git-actions-store", () => {
expect(store.getStatus({ serverId, cwd, actionId: "commit" })).toBe("idle");
});
it("shares pending state and de-dupes in-flight calls across Windows path spellings", async () => {
const deferred = createDeferred<unknown>();
const client = {
checkoutRefresh: vi.fn(() => deferred.promise),
};
useSessionStore.setState((state) => ({
...state,
sessions: {
...state.sessions,
[serverId]: { client } as unknown as (typeof state.sessions)[string],
},
}));
const store = useCheckoutGitActionsStore.getState();
const first = store.refresh({ serverId, cwd: "f:\\repo" });
const second = store.refresh({ serverId, cwd: "F:/repo/" });
expect(store.getStatus({ serverId, cwd: "F:/repo", actionId: "refresh" })).toBe("pending");
expect(client.checkoutRefresh).toHaveBeenCalledTimes(1);
deferred.resolve({});
await Promise.all([first, second]);
expect(store.getStatus({ serverId, cwd: "F:\\repo\\", actionId: "refresh" })).toBe("success");
});
it("runs pull then push sequentially for pull-and-push", async () => {
const order: string[] = [];
const client = {
+2 -1
View File
@@ -4,6 +4,7 @@ import { queryClient as appQueryClient } from "@/data/query-client";
import { useSessionStore } from "@/stores/session-store";
import { invalidateCheckoutGitQueriesForClient } from "@/git/query-keys";
import { i18n } from "@/i18n/i18next";
import { normalizeWorkspacePath } from "@/utils/workspace-identity";
const SUCCESS_DISPLAY_MS = 1000;
@@ -31,7 +32,7 @@ type CheckoutKey = string;
type StatusMap = Partial<Record<CheckoutGitAsyncActionId, CheckoutGitActionStatus>>;
function checkoutKey(serverId: string, cwd: string): CheckoutKey {
return `${serverId}::${cwd}`;
return `${serverId}::${normalizeWorkspacePath(cwd) ?? cwd}`;
}
function resolveClient(serverId: string) {
@@ -77,4 +77,16 @@ describe("selectGitActionsWorkspace", () => {
expect(workspace?.id).toBe("ws-b");
});
it("falls back to the workspace when Windows checkout paths differ in spelling", () => {
seed([createWorkspace("ws-win", "F:/repo")]);
const workspace = selectGitActionsWorkspace(useSessionStore.getState(), {
serverId: SERVER_ID,
workspaceId: null,
workspaceDirectory: "f:\\repo\\",
});
expect(workspace?.id).toBe("ws-win");
});
});
+7 -3
View File
@@ -1,6 +1,9 @@
import type { SessionsSnapshot } from "@/stores/session-store-hooks/selectors";
import type { WorkspaceDescriptor } from "@/stores/session-store";
import { resolveWorkspaceMapKeyByIdentity } from "@/utils/workspace-identity";
import {
normalizeWorkspacePath,
resolveWorkspaceMapKeyByIdentity,
} from "@/utils/workspace-identity";
export interface GitActionsWorkspaceInput {
serverId: string;
@@ -26,11 +29,12 @@ export function selectGitActionsWorkspace(
if (workspaceKey) {
return workspaces?.get(workspaceKey) ?? null;
}
if (!input.workspaceDirectory) {
const normalizedWorkspaceDirectory = normalizeWorkspacePath(input.workspaceDirectory);
if (!normalizedWorkspaceDirectory) {
return null;
}
for (const candidate of workspaces?.values() ?? []) {
if (candidate.workspaceDirectory === input.workspaceDirectory) {
if (normalizeWorkspacePath(candidate.workspaceDirectory) === normalizedWorkspaceDirectory) {
return candidate;
}
}
@@ -1,5 +1,5 @@
// @vitest-environment jsdom
import { QueryClient } from "@tanstack/react-query";
import { QueryClient, QueryObserver } from "@tanstack/react-query";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { CheckoutStatusUpdate } from "@getpaseo/protocol/messages";
import {
@@ -119,6 +119,18 @@ describe("fetchCheckoutStatus", () => {
expect(client.getCheckoutStatus).toHaveBeenCalledExactlyOnceWith(cwd);
});
it("normalizes a Windows cwd at the cache boundary", async () => {
const windowsCwd = String.raw`C:\repo`;
const client = {
getCheckoutStatus: vi.fn(async () => checkoutStatus({ cwd: windowsCwd })),
};
const result = await fetchCheckoutStatus({ client, serverId, cwd: "C:/repo" });
expect(result.cwd).toBe("C:/repo");
expect(client.getCheckoutStatus).toHaveBeenCalledExactlyOnceWith("C:/repo");
});
it("keeps a manual working-diff comparison when the fetched dirty state flips", async () => {
selectBaseComparison();
const client = { getCheckoutStatus: vi.fn(async () => checkoutStatus({ isDirty: false })) };
@@ -161,6 +173,32 @@ describe("ensureCheckoutStatus", () => {
expect(result.currentBranch).toBe("feature/current");
expect(client.getCheckoutStatus).toHaveBeenCalledExactlyOnceWith(cwd);
});
it("reuses cached status across mismatched Windows path spellings", async () => {
const queryClient = createQueryClient();
const fetched = checkoutStatus({
cwd: "f:\\repo",
currentBranch: "feature/current",
isDirty: true,
});
const client = { getCheckoutStatus: vi.fn(async () => fetched) };
const first = await ensureCheckoutStatus({
queryClient,
client,
serverId,
cwd: "f:/repo",
});
const second = await ensureCheckoutStatus({
queryClient,
client,
serverId,
cwd: "F:\\repo\\",
});
expect(first.cwd).toBe("F:/repo");
expect(second).toEqual(first);
expect(client.getCheckoutStatus).toHaveBeenCalledTimes(1);
});
});
describe("applyCheckoutStatusUpdateFromEvent", () => {
@@ -177,6 +215,239 @@ describe("applyCheckoutStatusUpdateFromEvent", () => {
expect(queryClient.getQueryData(checkoutStatusQueryKey(serverId, cwd))).toEqual(pushed);
});
it("applies a Windows status push to the canonical workspace cache key", () => {
const queryClient = createQueryClient();
const canonicalCwd = "C:/repo";
const windowsCwd = String.raw`C:\repo`;
queryClient.setQueryData(
checkoutStatusQueryKey(serverId, canonicalCwd),
checkoutStatus({ cwd: canonicalCwd, isDirty: false }),
);
applyCheckoutStatusUpdateFromEvent({
queryClient,
serverId,
message: checkoutStatusUpdate(checkoutStatus({ cwd: windowsCwd, isDirty: true })),
});
expect(
queryClient.getQueryData<CheckoutStatusPayload>(
checkoutStatusQueryKey(serverId, canonicalCwd),
),
).toMatchObject({ cwd: canonicalCwd, isDirty: true });
expect(queryClient.getQueryData(["checkoutStatus", serverId, windowsCwd])).toBeUndefined();
});
it("updates Push -> Commit when a dirty status push arrives with mismatched Windows path casing and slashes", () => {
const queryClient = createQueryClient();
queryClient.setQueryData(
checkoutStatusQueryKey(serverId, "f:/repo"),
checkoutStatus({
cwd: "F:/repo",
isDirty: false,
aheadOfOrigin: 1,
}),
);
const observer = new QueryObserver<CheckoutStatusPayload>(queryClient, {
queryKey: checkoutStatusQueryKey(serverId, "f:/repo"),
staleTime: Infinity,
enabled: false,
});
const unsubscribe = observer.subscribe(() => undefined);
applyCheckoutStatusUpdateFromEvent({
queryClient,
serverId,
message: checkoutStatusUpdate(
checkoutStatus({
cwd: "F:\\repo\\",
isDirty: true,
aheadOfOrigin: 1,
}),
),
});
expect(observer.getCurrentResult().data).toMatchObject({
cwd: "F:/repo",
isDirty: true,
aheadOfOrigin: 1,
});
expect(
queryClient.getQueryData<CheckoutStatusPayload>(checkoutStatusQueryKey(serverId, "f:\\repo")),
).toMatchObject({ cwd: "F:/repo", isDirty: true, aheadOfOrigin: 1 });
unsubscribe();
});
it("updates Commit -> Push when the last edit is committed with mismatched Windows path casing and slashes", () => {
const queryClient = createQueryClient();
queryClient.setQueryData(
checkoutStatusQueryKey(serverId, "F:\\repo\\"),
checkoutStatus({
cwd: "F:/repo",
isDirty: true,
aheadOfOrigin: 0,
}),
);
const observer = new QueryObserver<CheckoutStatusPayload>(queryClient, {
queryKey: checkoutStatusQueryKey(serverId, "f:/repo"),
staleTime: Infinity,
enabled: false,
});
const unsubscribe = observer.subscribe(() => undefined);
applyCheckoutStatusUpdateFromEvent({
queryClient,
serverId,
message: checkoutStatusUpdate(
checkoutStatus({
cwd: "f:\\repo",
isDirty: false,
aheadOfOrigin: 2,
}),
),
});
expect(observer.getCurrentResult().data).toMatchObject({
cwd: "F:/repo",
isDirty: false,
aheadOfOrigin: 2,
});
expect(
queryClient.getQueryData<CheckoutStatusPayload>(checkoutStatusQueryKey(serverId, "f:/repo")),
).toMatchObject({ cwd: "F:/repo", isDirty: false, aheadOfOrigin: 2 });
unsubscribe();
});
it("keeps distinct Windows worktrees, drive roots, UNC paths, and POSIX case sensitivity separate", () => {
const queryClient = createQueryClient();
const worktreeA = "F:\\repo\\.paseo\\worktrees\\feat-a\\";
const worktreeB = "f:\\repo\\.paseo\\worktrees\\feat-b";
queryClient.setQueryData(
checkoutStatusQueryKey(serverId, worktreeA),
checkoutStatus({ cwd: "F:/repo/.paseo/worktrees/feat-a", isDirty: false }),
);
queryClient.setQueryData(
checkoutStatusQueryKey(serverId, worktreeB),
checkoutStatus({ cwd: "F:/repo/.paseo/worktrees/feat-b", isDirty: false }),
);
queryClient.setQueryData(
checkoutStatusQueryKey(serverId, "C:/"),
checkoutStatus({ cwd: "C:/", isDirty: false }),
);
queryClient.setQueryData(
checkoutStatusQueryKey(serverId, "//server/share/repo"),
checkoutStatus({ cwd: "//server/share/repo", isDirty: false }),
);
queryClient.setQueryData(
checkoutStatusQueryKey(serverId, "/Repo"),
checkoutStatus({ cwd: "/Repo", isDirty: false }),
);
queryClient.setQueryData(
checkoutStatusQueryKey(serverId, "/repo"),
checkoutStatus({ cwd: "/repo", isDirty: false }),
);
queryClient.setQueryData(
checkoutStatusQueryKey(serverId, "/work/team\\repo"),
checkoutStatus({ cwd: "/work/team\\repo", isDirty: false }),
);
queryClient.setQueryData(
checkoutStatusQueryKey(serverId, "/work/team/repo"),
checkoutStatus({ cwd: "/work/team/repo", isDirty: false }),
);
applyCheckoutStatusUpdateFromEvent({
queryClient,
serverId,
message: checkoutStatusUpdate(
checkoutStatus({ cwd: "f:/repo/.paseo/worktrees/feat-a", isDirty: true }),
),
});
applyCheckoutStatusUpdateFromEvent({
queryClient,
serverId,
message: checkoutStatusUpdate(checkoutStatus({ cwd: "c:\\", isDirty: true })),
});
applyCheckoutStatusUpdateFromEvent({
queryClient,
serverId,
message: checkoutStatusUpdate(
checkoutStatus({ cwd: "\\\\server\\share\\repo\\", isDirty: true }),
),
});
applyCheckoutStatusUpdateFromEvent({
queryClient,
serverId,
message: checkoutStatusUpdate(checkoutStatus({ cwd: "/repo", isDirty: true })),
});
applyCheckoutStatusUpdateFromEvent({
queryClient,
serverId,
message: checkoutStatusUpdate(checkoutStatus({ cwd: "/work/team\\repo", isDirty: true })),
});
expect(
queryClient.getQueryData<CheckoutStatusPayload>(checkoutStatusQueryKey(serverId, worktreeA)),
).toMatchObject({ isDirty: true });
expect(
queryClient.getQueryData<CheckoutStatusPayload>(checkoutStatusQueryKey(serverId, worktreeB)),
).toMatchObject({ isDirty: false });
expect(
queryClient.getQueryData<CheckoutStatusPayload>(checkoutStatusQueryKey(serverId, "C:\\")),
).toMatchObject({ cwd: "C:/", isDirty: true });
expect(
queryClient.getQueryData<CheckoutStatusPayload>(
checkoutStatusQueryKey(serverId, "\\\\server\\share\\repo"),
),
).toMatchObject({ cwd: "//server/share/repo", isDirty: true });
expect(
queryClient.getQueryData<CheckoutStatusPayload>(checkoutStatusQueryKey(serverId, "/repo")),
).toMatchObject({ isDirty: true });
expect(
queryClient.getQueryData<CheckoutStatusPayload>(checkoutStatusQueryKey(serverId, "/Repo")),
).toMatchObject({ isDirty: false });
expect(
queryClient.getQueryData<CheckoutStatusPayload>(
checkoutStatusQueryKey(serverId, "/work/team\\repo"),
),
).toMatchObject({ cwd: "/work/team\\repo", isDirty: true });
expect(
queryClient.getQueryData<CheckoutStatusPayload>(
checkoutStatusQueryKey(serverId, "/work/team/repo"),
),
).toMatchObject({ cwd: "/work/team/repo", isDirty: false });
});
it("refreshes draft slash commands on Windows branch change and avoids invalidation when branch is unchanged", () => {
const queryClient = createQueryClient();
queryClient.setQueryData(
checkoutStatusQueryKey(serverId, "f:/repo"),
checkoutStatus({ cwd: "F:/repo", currentBranch: "chore/build-paseo" }),
);
const thisCheckout = draftAgentCommandsQueryKey({
serverId,
draftConfig: { provider: "claude", cwd: "F:\\repo\\", model: "haiku" },
});
queryClient.setQueryData(thisCheckout, [{ name: "build-paseo" }]);
// Unchanged branch with mismatched Windows spelling must not spuriously invalidate commands.
applyCheckoutStatusUpdateFromEvent({
queryClient,
serverId,
message: checkoutStatusUpdate(
checkoutStatus({ cwd: "f:\\repo", currentBranch: "chore/build-paseo", isDirty: true }),
),
});
expect(queryClient.getQueryState(thisCheckout)?.isInvalidated).toBe(false);
// Branch change with mismatched Windows spelling must invalidate draft commands.
applyCheckoutStatusUpdateFromEvent({
queryClient,
serverId,
message: checkoutStatusUpdate(checkoutStatus({ cwd: "f:\\repo", currentBranch: "main" })),
});
expect(queryClient.getQueryState(thisCheckout)?.isInvalidated).toBe(true);
});
it("invalidates recent commits when checkout status is pushed", () => {
const queryClient = createQueryClient();
queryClient.setQueryData(checkoutCommitsQueryKey(serverId, cwd), { commits: [] });
@@ -9,6 +9,7 @@ import {
} from "@/git/query-keys";
import { type CheckoutPrStatusPayload, normalizeCheckoutPrStatusPayload } from "@/git/pr-status";
import { invalidateDraftAgentCommandsForCheckout } from "@/agent-commands/cache";
import { normalizeWorkspacePath } from "@/utils/workspace-identity";
export type CheckoutStatusPayload = CheckoutStatusResponse["payload"];
export type { CheckoutPrStatusPayload } from "@/git/pr-status";
@@ -17,6 +18,12 @@ export interface CheckoutStatusClient {
getCheckoutStatus: (cwd: string) => Promise<CheckoutStatusPayload>;
}
function normalizeCheckoutStatusPayload<T extends CheckoutStatusPayload>(payload: T): T {
const baseNormalized = normalizeCheckoutBaseRef(payload);
const cwd = normalizeWorkspacePath(baseNormalized.cwd) ?? baseNormalized.cwd;
return cwd === baseNormalized.cwd ? baseNormalized : { ...baseNormalized, cwd };
}
export async function fetchCheckoutStatus({
client,
cwd,
@@ -25,7 +32,7 @@ export async function fetchCheckoutStatus({
serverId: string;
cwd: string;
}): Promise<CheckoutStatusPayload> {
const payload = normalizeCheckoutBaseRef(await client.getCheckoutStatus(cwd));
const payload = normalizeCheckoutStatusPayload(await client.getCheckoutStatus(cwd));
return payload;
}
@@ -56,7 +63,7 @@ export function applyCheckoutStatusUpdateFromEvent({
serverId: string;
message: CheckoutStatusUpdate;
}): void {
const payload = normalizeCheckoutBaseRef(message.payload);
const payload = normalizeCheckoutStatusPayload(message.payload);
const prStatus = payload.prStatus
? normalizeCheckoutPrStatusPayload(payload.prStatus)
: undefined;
@@ -4,7 +4,7 @@ import type { DiffFileSection } from "./types";
import type { DiffDocumentProps } from "./types";
interface DocumentFileHeaderProps {
file: DiffFileSection;
file: Pick<DiffFileSection, "file" | "fileIndex" | "path" | "isCollapsed">;
selectedPath: string | null;
mode: DiffDocumentProps["mode"];
onToggleFile: (path: string) => void;
@@ -0,0 +1,176 @@
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import type { ParsedDiffFile } from "@getpaseo/protocol/messages";
import { DiffSurface } from "./surface.gpui";
import type { DiffPalette, DiffSurfaceProps } from "./types";
const PALETTE: DiffPalette = {
surface: "rgb(1, 2, 3)",
headerSurface: "rgb(1, 2, 3)",
border: "rgb(9, 9, 9)",
foreground: "rgb(240, 240, 240)",
foregroundMuted: "rgb(120, 120, 120)",
addition: "rgb(0, 200, 0)",
deletion: "rgb(200, 0, 0)",
additionBackground: "rgba(0, 128, 0, 0.15)",
deletionBackground: "rgba(128, 0, 0, 0.1)",
emptyBackground: "rgb(1, 2, 3)",
selection: "rgb(0, 0, 255)",
headerActiveSurface: "rgb(4, 5, 6)",
headerBorder: "rgb(7, 8, 9)",
statusSuccess: "rgb(0, 200, 0)",
statusDanger: "rgb(200, 0, 0)",
statusWarning: "rgb(200, 200, 0)",
syntax: { keyword: "rgb(255, 0, 255)" },
};
const GREETING_FILE: ParsedDiffFile = {
path: "src/greeting.ts",
isNew: false,
isDeleted: false,
additions: 1,
deletions: 1,
hunks: [
{
oldStart: 10,
oldCount: 2,
newStart: 10,
newCount: 2,
lines: [
{ type: "header", content: "@@ -10,2 +10,2 @@ export function greet()" },
{ type: "context", content: "const greeting = prefix;" },
{ type: "remove", content: 'return "hello";' },
{
type: "add",
content: "return `hi`;",
tokens: [
{ text: "return", style: "keyword" },
{ text: " `hi`;", style: null },
],
},
],
},
],
};
function renderSurface(overrides: Partial<DiffSurfaceProps> = {}): string {
const props = {
files: [GREETING_FILE],
mode: { kind: "commit" },
displayPreferences: {
layout: "unified",
wrapLines: true,
codeFontSize: 13,
monoFontFamily: "Menlo",
},
palette: PALETTE,
headerTypography: { family: "Inter", size: 14, statSize: 12 },
collapsedFilePaths: new Set<string>(),
onToggleFile: () => {},
selectedPath: null,
onSelectPath: () => {},
...overrides,
} as DiffSurfaceProps;
return renderToStaticMarkup(<DiffSurface {...props} />);
}
describe("GPUI DiffSurface", () => {
it("renders hunk headers and added, removed, and context lines with their line numbers", () => {
const markup = renderSurface();
expect(markup).toContain("@@ -10,2 +10,2 @@ export function greet()");
expect(markup).toContain("const greeting = prefix;");
expect(markup).toContain("hello");
expect(markup).toContain("hi");
expect(markup).toContain('data-testid="diff-line-context"');
expect(markup).toContain('data-testid="diff-line-remove"');
expect(markup).toContain('data-testid="diff-line-add"');
// context line 10 (old and new), removed old line 11, added new line 11
expect(markup).toMatch(/>10</);
expect(markup).toMatch(/>11</);
});
it("paints added and removed rows with the palette backgrounds", () => {
const markup = renderSurface();
expect(markup).toContain("rgba(0,128,0,0.15)");
expect(markup).toContain("rgba(128,0,0,0.10)");
});
it("colors syntax tokens from the palette and leaves unstyled tokens in the foreground", () => {
const markup = renderSurface();
expect(markup).toMatch(/color:rgba\(255,0,255,1\.00\)[^>]*>return</);
});
it("renders every file in the document", () => {
const other: ParsedDiffFile = {
...GREETING_FILE,
path: "src/other.ts",
hunks: [
{
oldStart: 1,
oldCount: 0,
newStart: 1,
newCount: 1,
lines: [
{ type: "header", content: "@@ -0,0 +1 @@" },
{ type: "add", content: "export const other = 1;" },
],
},
],
};
const markup = renderSurface({ files: [GREETING_FILE, other] });
expect(markup).toContain("greeting.ts");
expect(markup).toContain("other.ts");
expect(markup).toContain("export const other = 1;");
});
it("hides the body of a collapsed file", () => {
const markup = renderSurface({ collapsedFilePaths: new Set(["src/greeting.ts"]) });
expect(markup).toContain("greeting.ts");
expect(markup).not.toContain("const greeting = prefix;");
});
it("colors line numbers by line type", () => {
const markup = renderSurface();
expect(markup).toMatch(/color:rgba\(0,200,0,1\.00\)[^>]*>11</);
expect(markup).toMatch(/color:rgba\(200,0,0,1\.00\)[^>]*>11</);
expect(markup).toMatch(/color:rgba\(120,120,120,1\.00\)[^>]*>10</);
});
it("renders no rows for an empty diff", () => {
const markup = renderSurface({ files: [] });
expect(markup).not.toContain("diff-line-");
});
it("explains files whose diff is not shown", () => {
const binary: ParsedDiffFile = { ...GREETING_FILE, hunks: [], status: "binary" };
const markup = renderSurface({ files: [binary] });
expect(markup).toContain('data-testid="diff-status"');
expect(markup).not.toContain("diff-line-");
});
it("renders split preferences as unified rows", () => {
const markup = renderSurface({
displayPreferences: {
layout: "split",
wrapLines: true,
codeFontSize: 13,
monoFontFamily: "Menlo",
},
});
expect(markup).toContain('data-testid="diff-line-remove"');
expect(markup).toContain('data-testid="diff-line-add"');
});
it("keeps scrollable space below the last line for floating controls", () => {
expect(renderSurface({ contentInsetBottom: 73 })).toContain("padding-bottom:73px");
});
});
@@ -0,0 +1,273 @@
import { memo, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { ScrollView, StyleSheet, Text, View, type TextStyle, type ViewStyle } from "react-native";
import type { ParsedDiffFile } from "@getpaseo/protocol/messages";
import { lineNumberGutterWidth } from "@/components/code-insets";
import { buildUnifiedDiffLines } from "@/utils/diff-layout";
import { compactHighlightTokens, formatDiffContentText } from "@/utils/diff-rendering";
import { DocumentFileHeader } from "./document-file-header";
import type { DiffPalette, DiffSurfaceProps } from "./types";
// GPUI has no Skia canvas, so this surface lays each diff line out with plain React Native
// views and text. The canvas-only features of the mobile surface (inline review threads,
// drag selection, scroll-to-file) are not part of it. It always lays lines out unified: the
// split layout is offered only where `isWeb` holds, so callers never pass it on GPUI.
type LineType = "add" | "remove" | "context" | "header";
interface CodeStyle {
fontFamily: string;
fontSize: number;
lineHeight: number;
}
interface LineCell {
type: LineType;
content: string;
lineNumber: number | null;
tokens?: ParsedDiffFile["hunks"][number]["lines"][number]["tokens"];
}
const MONOSPACE = "monospace";
const CODE_PADDING = 8;
export function DiffSurface(props: DiffSurfaceProps) {
const { displayPreferences, palette } = props;
const code = useMemo<CodeStyle>(
() => ({
fontFamily: displayPreferences.monoFontFamily.trim() || MONOSPACE,
fontSize: displayPreferences.codeFontSize,
lineHeight: Math.round(displayPreferences.codeFontSize * 1.5),
}),
[displayPreferences.monoFontFamily, displayPreferences.codeFontSize],
);
const contentStyle = useMemo<ViewStyle>(
() => ({ paddingBottom: props.contentInsetBottom ?? 0 }),
[props.contentInsetBottom],
);
return (
<ScrollView
style={[styles.fill, { backgroundColor: palette.surface }]}
contentContainerStyle={contentStyle}
>
{props.files.map((file, fileIndex) => (
<FileSection
key={file.path}
file={file}
fileIndex={fileIndex}
surface={props}
code={code}
/>
))}
</ScrollView>
);
}
interface FileSectionProps {
file: ParsedDiffFile;
fileIndex: number;
surface: DiffSurfaceProps;
code: CodeStyle;
}
function FileSection({ file, fileIndex, surface, code }: FileSectionProps) {
const isCollapsed = surface.collapsedFilePaths.has(file.path);
const section = useMemo(
() => ({ file, fileIndex, path: file.path, isCollapsed }),
[file, fileIndex, isCollapsed],
);
return (
<View>
<DocumentFileHeader
file={section}
selectedPath={surface.selectedPath}
mode={surface.mode}
onToggleFile={surface.onToggleFile}
onSelectPath={surface.onSelectPath}
/>
{isCollapsed ? null : (
<FileBody
file={file}
wrapLines={surface.displayPreferences.wrapLines}
palette={surface.palette}
code={code}
/>
)}
</View>
);
}
interface FileBodyProps {
file: ParsedDiffFile;
wrapLines: boolean;
palette: DiffPalette;
code: CodeStyle;
}
const FileBody = memo(function FileBody({ file, wrapLines, palette, code }: FileBodyProps) {
const { t } = useTranslation();
const bodyStyle = useMemo<ViewStyle>(
() => ({ borderTopWidth: StyleSheet.hairlineWidth, borderColor: palette.border }),
[palette.border],
);
const rows = useMemo(
() => (file.status === "binary" || file.status === "too_large" ? [] : bodyRows(file)),
[file],
);
const gutterWidth = useMemo(
() => lineNumberGutterWidth(maxLineNumber(file), code.fontSize),
[file, code.fontSize],
);
if (file.status === "binary" || file.status === "too_large") {
const label =
file.status === "binary"
? t("workspace.git.diff.binaryFile")
: t("workspace.git.diff.tooLarge");
return (
<View style={[bodyStyle, styles.status]} testID="diff-status">
<ColoredText color={palette.foregroundMuted} fontFamily={code.fontFamily}>
{label}
</ColoredText>
</View>
);
}
const lines = rows.map((row) => (
<LineRow
key={row.key}
cell={row.cell}
palette={palette}
code={code}
gutterWidth={gutterWidth}
wrapLines={wrapLines}
/>
));
if (wrapLines) return <View style={bodyStyle}>{lines}</View>;
return (
<ScrollView horizontal style={bodyStyle} contentContainerStyle={styles.unwrappedContent}>
<View style={styles.unwrappedRows}>{lines}</View>
</ScrollView>
);
});
function bodyRows(file: ParsedDiffFile): Array<{ key: string; cell: LineCell }> {
return buildUnifiedDiffLines(file).map((entry) => ({
key: entry.key,
cell: {
type: entry.line.type,
content: entry.line.content,
lineNumber: entry.lineNumber,
tokens: entry.line.tokens,
},
}));
}
function maxLineNumber(file: ParsedDiffFile): number {
return file.hunks.reduce(
(max, hunk) => Math.max(max, hunk.oldStart + hunk.oldCount, hunk.newStart + hunk.newCount),
0,
);
}
interface CellProps {
palette: DiffPalette;
code: CodeStyle;
gutterWidth: number;
wrapLines: boolean;
}
function LineRow({ cell, ...rest }: CellProps & { cell: LineCell }) {
return (
<View testID={`diff-line-${cell.type}`} style={rowStyle(cell.type, rest.palette)}>
<LineCellContent cell={cell} {...rest} />
</View>
);
}
function LineCellContent({
cell,
palette,
code,
gutterWidth,
wrapLines,
}: CellProps & { cell: LineCell }) {
const isHeader = cell.type === "header";
const textStyle = useMemo<TextStyle>(
() => ({
...code,
color: isHeader ? palette.foregroundMuted : palette.foreground,
}),
[code, isHeader, palette.foreground, palette.foregroundMuted],
);
const tokens = isHeader || !cell.tokens ? [] : compactHighlightTokens(cell.tokens);
return (
<View style={styles.cell}>
{isHeader ? null : (
<Text
numberOfLines={1}
style={[
textStyle,
styles.gutter,
{ width: gutterWidth, color: lineNumberColor(cell.type, palette) },
]}
>
{cell.lineNumber == null ? " " : cell.lineNumber}
</Text>
)}
<Text
numberOfLines={wrapLines ? undefined : 1}
style={[styles.code, textStyle, isHeader ? undefined : styles.codeInset]}
>
{tokens.length > 0
? tokens.map((token, index) => (
<ColoredText
// Tokens carry no identity beyond their position in the line.
// eslint-disable-next-line react/no-array-index-key
key={index}
color={(token.style && palette.syntax[token.style]) || palette.foreground}
>
{token.text}
</ColoredText>
))
: formatDiffContentText(cell.content)}
</Text>
</View>
);
}
function ColoredText({
color,
fontFamily,
children,
}: {
color: string;
fontFamily?: string;
children: string;
}) {
const style = useMemo<TextStyle>(() => ({ color, fontFamily }), [color, fontFamily]);
return <Text style={style}>{children}</Text>;
}
function rowStyle(type: LineType, palette: DiffPalette): ViewStyle {
if (type === "add") return { backgroundColor: palette.additionBackground };
if (type === "remove") return { backgroundColor: palette.deletionBackground };
return {};
}
function lineNumberColor(type: LineType, palette: DiffPalette): string {
if (type === "add") return palette.addition;
if (type === "remove") return palette.deletion;
return palette.foregroundMuted;
}
const styles = StyleSheet.create({
fill: { flex: 1 },
status: { paddingHorizontal: 12, paddingVertical: 12 },
unwrappedContent: { minWidth: "100%" },
unwrappedRows: { minWidth: "100%", alignSelf: "flex-start" },
cell: { flexDirection: "row", alignItems: "flex-start" },
gutter: { textAlign: "right", paddingRight: 4, flexShrink: 0 },
code: { flex: 1, minWidth: 0 },
codeInset: { paddingLeft: CODE_PADDING },
});
+6
View File
@@ -17,6 +17,12 @@ function payload(
}
describe("normalizeCheckoutPrStatusPayload", () => {
it("normalizes Windows path separators", () => {
expect(normalizeCheckoutPrStatusPayload(payload({ cwd: String.raw`C:\repo` })).cwd).toBe(
"C:/repo",
);
});
it("preserves known auth states", () => {
expect(normalizeCheckoutPrStatusPayload(payload({ authState: "cli_missing" })).authState).toBe(
"cli_missing",
+2
View File
@@ -1,5 +1,6 @@
import type { CheckoutPrStatusResponse, ForgeAuthState } from "@getpaseo/protocol/messages";
import { parseForgeAuthState } from "@/git/forge";
import { normalizeWorkspacePath } from "@/utils/workspace-identity";
type WireCheckoutPrStatusPayload = CheckoutPrStatusResponse["payload"];
@@ -12,6 +13,7 @@ export function normalizeCheckoutPrStatusPayload(
): CheckoutPrStatusPayload {
return {
...payload,
cwd: normalizeWorkspacePath(payload.cwd) ?? payload.cwd,
// COMPAT(forgeAuthState): normalize the legacy GitHub boolean for daemons
// predating v0.2.0-beta.1. Remove after 2027-01-17 once the supported daemon
// floor is >= v0.2.0.
@@ -1,3 +1,5 @@
import { normalizeWorkspacePath } from "@/utils/workspace-identity";
export const prPaneTimelineQueryKind = "prPaneTimeline";
export function prPaneTimelineQueryKey({
@@ -9,7 +11,7 @@ export function prPaneTimelineQueryKey({
cwd: string;
prNumber: number | null;
}) {
return [prPaneTimelineQueryKind, serverId, cwd, prNumber] as const;
return [prPaneTimelineQueryKind, serverId, normalizeWorkspacePath(cwd) ?? cwd, prNumber] as const;
}
export const prPanePipelineQueryKind = "prPanePipeline";
@@ -26,5 +28,11 @@ export function prPanePipelineQueryKey({
/** MR iid the pipeline is fetched by; part of the key since the fetch routes by it. */
changeRequestNumber: number;
}) {
return [prPanePipelineQueryKind, serverId, cwd, pipelineId, changeRequestNumber] as const;
return [
prPanePipelineQueryKind,
serverId,
normalizeWorkspacePath(cwd) ?? cwd,
pipelineId,
changeRequestNumber,
] as const;
}
+69
View File
@@ -164,4 +164,73 @@ describe("checkout query keys", () => {
queryClient.clear();
});
it("matches equivalent Windows checkout paths during manual invalidation without touching distinct checkouts", async () => {
const queryClient = new QueryClient();
const canonical = "F:/repo";
const backslashLower = "f:\\repo";
const backslashTrailing = "F:\\repo\\";
const otherWorktree = "F:\\repo\\.paseo\\worktrees\\other";
queryClient.setQueryData(checkoutStatusQueryKey(serverId, canonical), { isGit: true });
queryClient.setQueryData(checkoutDiffQueryKey(serverId, canonical, "base", "main", true), {
files: [],
});
queryClient.setQueryData(checkoutPrStatusQueryKey(serverId, canonical), {
status: { number: 12 },
});
queryClient.setQueryData(checkoutCommitsQueryKey(serverId, canonical), { commits: [] });
queryClient.setQueryData(prPaneTimelineQueryKey({ serverId, cwd: canonical, prNumber: 12 }), {
items: [],
});
queryClient.setQueryData(
prPanePipelineQueryKey({
serverId,
cwd: canonical,
pipelineId: 9001,
changeRequestNumber: 1,
}),
{ stages: [] },
);
queryClient.setQueryData(checkoutStatusQueryKey(serverId, otherWorktree), { isGit: true });
await invalidateCheckoutGitQueriesForClient(queryClient, { serverId, cwd: backslashLower });
expect(
queryClient.getQueryState(checkoutStatusQueryKey(serverId, backslashTrailing))?.isInvalidated,
).toBe(true);
expect(
queryClient.getQueryState(
checkoutDiffQueryKey(serverId, backslashTrailing, "base", "main", true),
)?.isInvalidated,
).toBe(true);
expect(
queryClient.getQueryState(checkoutPrStatusQueryKey(serverId, backslashTrailing))
?.isInvalidated,
).toBe(true);
expect(
queryClient.getQueryState(checkoutCommitsQueryKey(serverId, backslashTrailing))
?.isInvalidated,
).toBe(true);
expect(
queryClient.getQueryState(
prPaneTimelineQueryKey({ serverId, cwd: backslashTrailing, prNumber: 12 }),
)?.isInvalidated,
).toBe(true);
expect(
queryClient.getQueryState(
prPanePipelineQueryKey({
serverId,
cwd: backslashTrailing,
pipelineId: 9001,
changeRequestNumber: 1,
}),
)?.isInvalidated,
).toBe(true);
expect(
queryClient.getQueryState(checkoutStatusQueryKey(serverId, otherWorktree))?.isInvalidated,
).toBe(false);
queryClient.clear();
});
});
+19 -6
View File
@@ -1,6 +1,11 @@
import type { Query, QueryClient } from "@tanstack/react-query";
import { normalizeWorkspacePath } from "@/utils/workspace-identity";
import { prPanePipelineQueryKind, prPaneTimelineQueryKind } from "./pull-request-panel/query-keys";
function canonicalCheckoutCwd(cwd: string): string {
return normalizeWorkspacePath(cwd) ?? cwd;
}
interface CheckoutQueryIdentity {
serverId: string;
cwd: string;
@@ -18,7 +23,7 @@ type CheckoutQueryKey = readonly unknown[];
export const COMMIT_FILE_DIFF_STALE_TIME = 5 * 60_000;
export function checkoutStatusQueryKey(serverId: string, cwd: string) {
return ["checkoutStatus", serverId, cwd] as const;
return ["checkoutStatus", serverId, canonicalCheckoutCwd(cwd)] as const;
}
export function checkoutDiffQueryKey(
@@ -28,15 +33,22 @@ export function checkoutDiffQueryKey(
baseRef?: string,
ignoreWhitespace?: boolean,
) {
return ["checkoutDiff", serverId, cwd, mode, baseRef ?? "", ignoreWhitespace === true] as const;
return [
"checkoutDiff",
serverId,
canonicalCheckoutCwd(cwd),
mode,
baseRef ?? "",
ignoreWhitespace === true,
] as const;
}
export function checkoutPrStatusQueryKey(serverId: string, cwd: string) {
return ["checkoutPrStatus", serverId, cwd] as const;
return ["checkoutPrStatus", serverId, canonicalCheckoutCwd(cwd)] as const;
}
export function checkoutCommitsQueryKey(serverId: string, cwd: string) {
return ["checkoutCommits", serverId, cwd] as const;
return ["checkoutCommits", serverId, canonicalCheckoutCwd(cwd)] as const;
}
export function checkoutCommitFileDiffQueryKey(
@@ -45,7 +57,7 @@ export function checkoutCommitFileDiffQueryKey(
sha: string,
path: string,
) {
return ["checkoutCommitFileDiff", serverId, cwd, sha, path] as const;
return ["checkoutCommitFileDiff", serverId, canonicalCheckoutCwd(cwd), sha, path] as const;
}
export async function invalidateCheckoutGitQueriesForClient(
@@ -113,13 +125,14 @@ function checkoutQueryPredicate(
queryKind: CheckoutQueryKey[0],
scope: CheckoutQueryScope,
): (query: Query) => boolean {
const scopeCwd = scope.cwd === undefined ? undefined : canonicalCheckoutCwd(scope.cwd);
return (query) => {
const key = query.queryKey;
return (
isCheckoutQueryKey(key) &&
key[0] === queryKind &&
key[1] === scope.serverId &&
(scope.cwd === undefined || key[2] === scope.cwd)
(scopeCwd === undefined || canonicalCheckoutCwd(key[2] as string) === scopeCwd)
);
};
}
@@ -23,6 +23,12 @@ describe("working diff comparison", () => {
expect(workingDiffComparisonKey({ ...checkout, workspaceId: null, cwd: "/repo/" })).toBe(
"working-diff:server=server-1:cwd=%2Frepo",
);
expect(workingDiffComparisonKey({ ...checkout, workspaceId: null, cwd: "f:\\repo" })).toBe(
workingDiffComparisonKey({ ...checkout, workspaceId: null, cwd: "F:/repo/" }),
);
expect(workingDiffComparisonKey({ ...checkout, workspaceId: null, cwd: "c:\\" })).toBe(
"working-diff:server=server-1:cwd=C%3A%2F",
);
});
it.each([true, false])("defaults to All changes when checkout dirtiness is %s", (isDirty) => {
@@ -1,3 +1,5 @@
import { normalizeWorkspacePath } from "@/utils/workspace-identity";
export type WorkingDiffComparison = "uncommitted" | "base" | "all";
export interface WorkingDiffComparisonOverride {
@@ -15,8 +17,7 @@ export interface WorkingDiffCheckoutIdentity {
}
function normalizeCwd(cwd: string): string {
const trimmed = cwd.trim();
return trimmed === "/" ? trimmed : trimmed.replace(/\/+$/, "");
return normalizeWorkspacePath(cwd) ?? cwd.trim();
}
export function workingDiffComparisonKey(input: WorkingDiffCheckoutIdentity): string {
+3 -4
View File
@@ -59,7 +59,7 @@ import {
resolveActiveHostServerId,
type HostProfile,
} from "@/types/host-connection";
import { TitlebarDragRegion } from "@/components/desktop/titlebar-drag-region";
import { TitlebarDragSurface } from "@/components/desktop/titlebar-drag-surface";
import { WindowChromeRegion, WindowChromeSafeArea } from "@/utils/desktop-window";
import { confirmDialog } from "@/utils/confirm-dialog";
import { BackHeader } from "@/components/headers/back-header";
@@ -1223,8 +1223,7 @@ function SettingsSidebar({
>
{isDesktop ? (
<View style={innerContainerStyle}>
<View style={sidebarStyles.sidebarDragArea}>
<TitlebarDragRegion />
<TitlebarDragSurface style={sidebarStyles.sidebarDragArea}>
<WindowChromeSafeArea placement="below" />
<SidebarHeaderRow
icon={ArrowLeft}
@@ -1232,7 +1231,7 @@ function SettingsSidebar({
onPress={onBackToWorkspace}
testID="settings-back-to-workspace"
/>
</View>
</TitlebarDragSurface>
<ScrollView
style={sidebarStyles.scrollBody}
showsVerticalScrollIndicator={false}
@@ -21,7 +21,7 @@ import { StyleSheet, useUnistyles } from "react-native-unistyles";
import { PaseoLogo } from "@/components/icons/paseo-logo";
import { Button } from "@/components/ui/button";
import { getDesktopDaemonLogs, type DesktopDaemonLogs } from "@/desktop/daemon/desktop-daemon";
import { TitlebarDragRegion } from "@/components/desktop/titlebar-drag-region";
import { TitlebarDragSurface } from "@/components/desktop/titlebar-drag-surface";
import { isNative, isWeb } from "@/constants/platform";
import { useNativeSplashHold } from "@/native-splash";
import { CODE_SURFACE_DATASET } from "@/styles/code-surface";
@@ -394,18 +394,16 @@ export function StartupSplashScreen({ bootstrapState }: StartupSplashScreenProps
if (!isError) {
return (
<View testID="startup-splash" style={styles.container}>
<TitlebarDragRegion />
<TitlebarDragSurface testID="startup-splash" style={styles.container}>
<View style={styles.logo}>
<LogoShimmer />
</View>
</View>
</TitlebarDragSurface>
);
}
return (
<View style={styles.errorScreen}>
<TitlebarDragRegion />
<TitlebarDragSurface style={styles.errorScreen}>
<ScrollView
style={styles.errorScrollView}
contentContainerStyle={styles.errorScrollContent}
@@ -453,6 +451,6 @@ export function StartupSplashScreen({ bootstrapState }: StartupSplashScreenProps
</View>
</View>
</ScrollView>
</View>
</TitlebarDragSurface>
);
}
@@ -3,7 +3,7 @@ import { View } from "react-native";
import { useWorkspaceTabDrag } from "@/components/workspace-tab-drag-context";
import { StyleSheet } from "react-native-unistyles";
import { RetainedPanel } from "@/components/retained-panel";
import { TitlebarDragRegion } from "@/components/desktop/titlebar-drag-region";
import { TitlebarDragSurface } from "@/components/desktop/titlebar-drag-surface";
import { WorkspacePanelHost } from "@/screens/workspace/workspace-panel-host";
import { deriveWorkspacePaneState } from "@/screens/workspace/workspace-pane-state";
import {
@@ -121,43 +121,44 @@ export function ExplorerSidebarDock({
<RetainedPanel active>
<WindowChromeRegion corners="top-right">
<View style={styles.dock} testID="workspace-explorer-sidebar">
<WindowChromeSafeArea placement="inline" style={styles.tabRail}>
<TitlebarDragRegion />
<View style={styles.tabRow}>
<WorkspaceDesktopTabsRow
host="explorer"
launchPurpose="supporting"
isFocused={isWorkspaceFocused}
ownsKeyboardShortcuts={false}
setHoveredCloseTabKey={setHoveredCloseTabKey}
onCopyResumeCommand={onCopyResumeCommand}
onCopyAgentId={onCopyAgentId}
onCopyTerminalId={onCopyTerminalId}
onReloadAgent={onReloadAgent}
onRenameTab={onRenameTab}
onCloseTabsToLeft={handleCloseTabsToLeft}
onCloseTabsToRight={handleCloseTabsToRight}
onCloseOtherTabs={handleCloseOtherTabs}
focusModeEnabled={false}
onExitFocusMode={onExitFocusMode}
externalDndContext={externalDndContext}
paneId={pane.id}
tabs={tabItems}
normalizedServerId={normalizedServerId}
normalizedWorkspaceId={normalizedWorkspaceId}
activeDragTabId={activeDragTabId}
tabDropPreviewIndex={
tabDropPreview?.paneId === pane.id ? tabDropPreview.indicatorIndex : null
}
onNavigateTab={handleSelectTab}
onCloseTab={onCloseTab}
onCreateNewTab={onCreateNewTab}
onReorderTabs={handleReorderTabs}
/>
</View>
{headerAction ? <View style={styles.headerAction}>{headerAction}</View> : null}
<View pointerEvents="none" style={styles.tabRailDivider} />
</WindowChromeSafeArea>
<TitlebarDragSurface style={styles.tabRailDragSurface}>
<WindowChromeSafeArea placement="inline" style={styles.tabRail}>
<View style={styles.tabRow}>
<WorkspaceDesktopTabsRow
host="explorer"
launchPurpose="supporting"
isFocused={isWorkspaceFocused}
ownsKeyboardShortcuts={false}
setHoveredCloseTabKey={setHoveredCloseTabKey}
onCopyResumeCommand={onCopyResumeCommand}
onCopyAgentId={onCopyAgentId}
onCopyTerminalId={onCopyTerminalId}
onReloadAgent={onReloadAgent}
onRenameTab={onRenameTab}
onCloseTabsToLeft={handleCloseTabsToLeft}
onCloseTabsToRight={handleCloseTabsToRight}
onCloseOtherTabs={handleCloseOtherTabs}
focusModeEnabled={false}
onExitFocusMode={onExitFocusMode}
externalDndContext={externalDndContext}
paneId={pane.id}
tabs={tabItems}
normalizedServerId={normalizedServerId}
normalizedWorkspaceId={normalizedWorkspaceId}
activeDragTabId={activeDragTabId}
tabDropPreviewIndex={
tabDropPreview?.paneId === pane.id ? tabDropPreview.indicatorIndex : null
}
onNavigateTab={handleSelectTab}
onCloseTab={onCloseTab}
onCreateNewTab={onCreateNewTab}
onReorderTabs={handleReorderTabs}
/>
</View>
{headerAction ? <View style={styles.headerAction}>{headerAction}</View> : null}
<View pointerEvents="none" style={styles.tabRailDivider} />
</WindowChromeSafeArea>
</TitlebarDragSurface>
<View style={styles.content}>
<WorkspacePanelHost
paneId={pane.id}
@@ -183,6 +184,10 @@ const styles = StyleSheet.create((theme) => ({
minHeight: 0,
backgroundColor: theme.colors.surfaceSidebar,
},
tabRailDragSurface: {
position: "relative",
flexShrink: 0,
},
tabRail: {
position: "relative",
flexDirection: "row",
@@ -1666,9 +1666,12 @@ const styles = StyleSheet.create((theme) => ({
minWidth: 0,
flex: 1,
alignSelf: "stretch",
flexDirection: "row",
alignItems: "stretch",
},
tabsScrollFitContent: {
flex: 1,
flexGrow: 0,
flexShrink: 1,
},
tabsScrollOverflow: {
flex: 1,
+13 -96
View File
@@ -1,17 +1,12 @@
import { createContext, useContext, useEffect, useMemo, useState, type ReactNode } from "react";
import { createContext, useContext, useMemo, useSyncExternalStore, type ReactNode } from "react";
import { View, type ViewProps } from "react-native";
import {
DESKTOP_TRAFFIC_LIGHT_HEIGHT,
DESKTOP_TRAFFIC_LIGHT_WIDTH,
getIsElectronRuntime,
} from "@/constants/layout";
import { getDesktopWindow } from "@/desktop/electron/window";
import { getDesktopWindowChromeMode, type DesktopWindowChromeMode } from "@/desktop/host";
import { DESKTOP_TRAFFIC_LIGHT_HEIGHT, DESKTOP_TRAFFIC_LIGHT_WIDTH } from "@/constants/layout";
import type { DesktopWindowChromeMode } from "@/desktop/host";
import { desktopWindowChromeHost } from "@/desktop/window-chrome-host";
import {
getDesktopWindowControlsPresentation,
getDesktopWindowControlsWidth,
} from "@/desktop/window-chrome-presentation";
import { isNative } from "@/constants/platform";
import { useTopBand, type TopBand } from "@/window-layout";
export type WindowChromeCorners = "none" | "top-left" | "top-right" | "both";
@@ -148,101 +143,23 @@ export function resolveWindowChromeSafeArea(input: {
}
export function WindowChromeProvider({ children }: { children: ReactNode }) {
const [isElectronReady, setIsElectronReady] = useState(getIsElectronRuntime);
const [windowState, setWindowState] = useState({ isFullscreen: false, isMaximized: false });
useEffect(() => {
let active = true;
let dispose: (() => void) | undefined;
let connecting = false;
let retryCount = 0;
let retryTimer: ReturnType<typeof setTimeout> | undefined;
function scheduleRetry(warnOnExhaustion = false) {
if (!active || dispose || retryTimer) return;
if (retryCount >= 40) {
if (warnOnExhaustion) {
console.warn("[DesktopWindow] Chrome bridge unavailable; window controls may overlap UI");
}
return;
}
retryCount += 1;
retryTimer = setTimeout(() => {
retryTimer = undefined;
connect();
}, 250);
}
function connect() {
if (!active || dispose || connecting) return;
if (!getIsElectronRuntime()) return scheduleRetry();
const desktopWindow = getDesktopWindow();
if (
!desktopWindow ||
typeof desktopWindow.isFullscreen !== "function" ||
typeof desktopWindow.onResized !== "function"
)
return scheduleRetry(true);
const readFullscreen = desktopWindow.isFullscreen;
const readMaximized = desktopWindow.isMaximized;
const subscribeToResized = desktopWindow.onResized;
connecting = true;
void (async () => {
async function syncWindowState() {
try {
const [isFullscreen, isMaximized] = await Promise.all([
readFullscreen(),
readMaximized?.() ?? false,
]);
if (active) setWindowState({ isFullscreen, isMaximized });
} catch (error) {
if (active) console.warn("[DesktopWindow] Failed to read window state", error);
}
}
try {
const nextDispose = await subscribeToResized(syncWindowState);
if (!active) return nextDispose();
dispose = nextDispose;
setIsElectronReady(true);
await syncWindowState();
} catch (error) {
if (active) console.warn("[DesktopWindow] Failed to subscribe to resize", error);
} finally {
connecting = false;
if (!dispose) scheduleRetry();
}
})();
}
if (!isNative) connect();
return () => {
active = false;
if (retryTimer) clearTimeout(retryTimer);
dispose?.();
};
}, []);
const chrome = useSyncExternalStore(
desktopWindowChromeHost.subscribe,
desktopWindowChromeHost.getSnapshot,
desktopWindowChromeHost.getSnapshot,
);
const topBand = useTopBand();
const obstruction = useMemo(
() =>
resolveWindowChromeObstruction({
mode: isElectronReady ? getDesktopWindowChromeMode() : null,
isFullscreen: windowState.isFullscreen,
mode: chrome.mode,
isFullscreen: chrome.isFullscreen,
topBand,
}),
[isElectronReady, windowState.isFullscreen, topBand],
);
const desktopWindowChrome = useMemo(
() => ({
mode: isElectronReady ? getDesktopWindowChromeMode() : null,
isFullscreen: windowState.isFullscreen,
isMaximized: windowState.isMaximized,
}),
[isElectronReady, windowState],
[chrome.mode, chrome.isFullscreen, topBand],
);
return (
<DesktopWindowChromeContext.Provider value={desktopWindowChrome}>
<DesktopWindowChromeContext.Provider value={chrome}>
<WindowChromeContext.Provider value={obstruction}>
<WindowChromeCornersContext.Provider value="both">
{children}
@@ -1,6 +1,10 @@
import { describe, expect, it } from "vitest";
import type { WorkspaceDescriptor } from "@/stores/session-store";
import { resolveWorkspaceMapKeyByIdentity, resolveWorkspaceRouteId } from "./workspace-identity";
import {
normalizeWorkspacePath,
resolveWorkspaceMapKeyByIdentity,
resolveWorkspaceRouteId,
} from "./workspace-identity";
function createWorkspace(
input: Partial<WorkspaceDescriptor> & Pick<WorkspaceDescriptor, "id">,
@@ -24,6 +28,48 @@ function createWorkspace(
};
}
describe("normalizeWorkspacePath", () => {
it("normalizes Windows separators, drive-letter casing, and trailing slashes", () => {
expect(normalizeWorkspacePath("f:\\repo")).toBe("F:/repo");
expect(normalizeWorkspacePath("f:/repo")).toBe("F:/repo");
expect(normalizeWorkspacePath("F:\\repo")).toBe("F:/repo");
expect(normalizeWorkspacePath("F:\\repo\\")).toBe("F:/repo");
expect(normalizeWorkspacePath("f:/repo///")).toBe("F:/repo");
expect(normalizeWorkspacePath("\\\\?\\f:\\repo\\")).toBe("F:/repo");
});
it("preserves Windows drive roots instead of stripping to a relative drive", () => {
expect(normalizeWorkspacePath("C:\\")).toBe("C:/");
expect(normalizeWorkspacePath("C:/")).toBe("C:/");
expect(normalizeWorkspacePath("c:\\")).toBe("C:/");
expect(normalizeWorkspacePath("c:///")).toBe("C:/");
expect(normalizeWorkspacePath("\\\\?\\c:\\")).toBe("C:/");
});
it("normalizes UNC paths while preserving share identity", () => {
expect(normalizeWorkspacePath("\\\\server\\share")).toBe("//server/share");
expect(normalizeWorkspacePath("\\\\server\\share\\")).toBe("//server/share");
expect(normalizeWorkspacePath("//server/share/")).toBe("//server/share");
expect(normalizeWorkspacePath("\\\\server\\share\\repo\\")).toBe("//server/share/repo");
expect(normalizeWorkspacePath("\\\\?\\UNC\\server\\share\\repo\\")).toBe("//server/share/repo");
});
it("preserves distinct worktrees and POSIX case sensitivity", () => {
expect(normalizeWorkspacePath("F:\\repo\\.paseo\\worktrees\\feat-a\\")).toBe(
"F:/repo/.paseo/worktrees/feat-a",
);
expect(normalizeWorkspacePath("f:\\repo\\.paseo\\worktrees\\feat-b")).toBe(
"F:/repo/.paseo/worktrees/feat-b",
);
expect(normalizeWorkspacePath("/Repo/App/")).toBe("/Repo/App");
expect(normalizeWorkspacePath("/repo/app/")).toBe("/repo/app");
expect(normalizeWorkspacePath("/work/team\\repo/")).toBe("/work/team\\repo");
expect(normalizeWorkspacePath("/work/team/repo/")).toBe("/work/team/repo");
expect(normalizeWorkspacePath("/")).toBe("/");
expect(normalizeWorkspacePath("/repo ")).toBe("/repo ");
});
});
describe("resolveWorkspaceRouteId", () => {
it("trims route workspace ids without path normalization", () => {
expect(resolveWorkspaceRouteId({ routeWorkspaceId: " C:\\tmp\\repo\\ " })).toBe(
+42 -4
View File
@@ -12,15 +12,53 @@ export function normalizeWorkspaceOpaqueId(value: string | null | undefined): st
return trimNonEmpty(value);
}
function isWindowsPath(value: string): boolean {
return (
/^[A-Za-z]:[\\/]/.test(value) ||
/^[\\/]{2}\?[\\/]/.test(value) ||
/^[\\/]{2}[^\\/]+[\\/][^\\/]+/.test(value)
);
}
function unwrapWindowsExtendedPath(value: string): string {
const extendedUncMatch = /^\/\/\?\/UNC\/([^/]+)\/([^/]+)(?:\/(.*))?$/i.exec(value);
if (extendedUncMatch) {
const [, host, share, rest] = extendedUncMatch;
return rest !== undefined ? `//${host}/${share}/${rest}` : `//${host}/${share}`;
}
if (/^\/\/\?\/([A-Za-z]:\/.*)$/.test(value)) {
return value.slice(4);
}
return value;
}
export function normalizeWorkspacePath(value: string | null | undefined): string | null {
if (typeof value !== "string" || value.trim().length === 0) {
return null;
}
const withUnixSeparators = value.replace(/\\/g, "/");
if (withUnixSeparators === "/") {
return withUnixSeparators;
if (isWindowsPath(value)) {
const unwrapped = unwrapWindowsExtendedPath(value.replace(/\\/g, "/"));
const driveMatch = /^([A-Za-z]):\/(.*)$/.exec(unwrapped);
if (driveMatch) {
const drive = driveMatch[1].toUpperCase();
const rest = driveMatch[2].replace(/\/+$/, "");
return rest.length > 0 ? `${drive}:/${rest}` : `${drive}:/`;
}
const uncMatch = /^\/\/([^/]+)\/([^/]+)(?:\/(.*))?$/.exec(unwrapped);
if (uncMatch) {
const [, host, share, rawRest = ""] = uncMatch;
const rest = rawRest.replace(/\/+$/, "");
return rest.length > 0 ? `//${host}/${share}/${rest}` : `//${host}/${share}`;
}
}
const withoutTrailingSlash = withUnixSeparators.replace(/\/+$/, "");
if (value === "/") {
return value;
}
const withoutTrailingSlash = value.replace(/\/+$/, "");
return withoutTrailingSlash.length > 0 ? withoutTrailingSlash : "/";
}
@@ -0,0 +1,28 @@
import { useMemo, type ReactNode } from "react";
import { SafeAreaInsetsContext, useSafeAreaInsets } from "react-native-safe-area-context";
import { WindowInsetsContext } from "./context";
export { useWindowLayout } from "./context";
export { WindowLayoutActions, WindowLayoutActionsHost } from "./actions";
export { WindowLayoutSurface, WindowLayoutDivisionGap } from "./surface";
export { useTopBand } from "./context";
export { WindowSafeArea, useWindowSafeAreaInsets } from "./window-safe-area";
export {
resolveDesktopDivisionLayout,
resolveWorkspaceActionPlacement,
resolveWorkspaceBarActions,
} from "./model";
export type { DesktopDivisionLayout, TopBand, WindowLayout, WindowLayoutRect } from "./model";
export function WindowLayoutProvider({ children }: { children: ReactNode }) {
const systemInsets = useSafeAreaInsets();
const insets = useMemo(
() => (systemInsets.top === 0 ? systemInsets : { ...systemInsets, top: 0 }),
[systemInsets],
);
return (
<WindowInsetsContext.Provider value={insets}>
<SafeAreaInsetsContext.Provider value={insets}>{children}</SafeAreaInsetsContext.Provider>
</WindowInsetsContext.Provider>
);
}
@@ -670,6 +670,7 @@ class AcpRuntime {
private closePromise: Promise<void> | null = null;
private activeInterrupt: Promise<InterruptResult> | null = null;
private activeRetirement: Promise<InterruptResult> | null = null;
private pendingRetirement: { turnId: string; error?: ProviderError } | null = null;
private retirementFinalized = false;
private processFailed = false;
private processFailureMessage: string | null = null;
@@ -1084,6 +1085,30 @@ class AcpRuntime {
async interrupt(): Promise<InterruptResult> {
if (this.activeRetirement) return this.activeRetirement;
if (this.activeInterrupt) return this.activeInterrupt;
if (this.pendingRetirement) {
const pending = this.pendingRetirement;
const killGraceMs =
this.options.options.acpOptions?.interruptKillGraceMs ?? DEFAULT_INTERRUPT_KILL_GRACE_MS;
const retry = this.closeAndRetire(
pending.turnId,
{
force: true,
timeoutMs: killGraceMs,
killGraceMs,
},
pending.error,
).catch((error) => {
if (this.activeRetirement === retry) this.activeRetirement = null;
throw error;
});
this.activeRetirement = retry;
return retry;
}
if (this.closing || this.processFailed) {
if (this.retirementFinalized || !this.activePrompt) {
return { retired: true };
}
}
const active = this.activePrompt;
const deferredTurnId = active?.deferred ? active.turnId : null;
if (active && deferredTurnId) {
@@ -1134,6 +1159,7 @@ class AcpRuntime {
private finalizeRetiredTurn(turnId: string, emitRetired: boolean, error?: ProviderError): void {
if (this.retirementFinalized) return;
this.retirementFinalized = true;
this.pendingRetirement = null;
if (this.activePrompt?.turnId === turnId) this.activePrompt = null;
this.finishPromptTurn(turnId, "canceled", undefined, {
suppressTrailingToolEcho: true,
@@ -1141,6 +1167,47 @@ class AcpRuntime {
if (emitRetired) this.options.onRetired?.(error);
}
private whenCloseSettles(): Promise<void> | null {
const child = this.child;
if (child) {
if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve();
return new Promise<void>((resolve) => {
const done = () => {
child.off("exit", done);
child.off("close", done);
resolve();
};
child.once("exit", done);
child.once("close", done);
});
}
return this.whenConnectorClosed();
}
private async closeAndRetire(
turnId: string,
options: { force: boolean; timeoutMs: number; killGraceMs?: number },
error?: ProviderError,
): Promise<InterruptResult> {
const attempt = { turnId, error };
this.pendingRetirement = attempt;
try {
await this.close(options);
} catch (closeError) {
void this.whenCloseSettles()?.then(
() => {
// A retry owns retirement once it starts. Its request must complete before session closure.
if (this.pendingRetirement === attempt) this.finalizeRetiredTurn(turnId, true, error);
return undefined;
},
() => undefined,
);
throw closeError;
}
this.finalizeRetiredTurn(turnId, false, error);
return { retired: true, ...(error ? { error } : {}) };
}
private async retireUnresponsivePrompt(
active: ActivePrompt,
forceClose: boolean,
@@ -1154,17 +1221,11 @@ class AcpRuntime {
: {
message: `Stopped unresponsive ${this.options.options.id} process after cancel timed out. This provider does not support session resume; start a new agent or reload to continue.`,
};
try {
await this.close({ force: forceClose, timeoutMs: killGraceMs, killGraceMs });
} catch (closeError) {
void this.whenConnectorClosed()?.then(
() => this.finalizeRetiredTurn(active.turnId, true, error),
() => undefined,
);
throw closeError;
}
this.finalizeRetiredTurn(active.turnId, false, error);
return { retired: true, ...(error ? { error } : {}) };
return this.closeAndRetire(
active.turnId,
{ force: forceClose, timeoutMs: killGraceMs, killGraceMs },
error,
);
}
private async retireDeferredTurn(
@@ -1195,17 +1256,7 @@ class AcpRuntime {
// already returned. Close the process first while the turn still appears running,
// then emit the canceled turn synchronously before request.completed and session.closed
// so queued work and config changes immediately observe the retired session.
try {
await this.close({ force: cancelTimedOut, timeoutMs: 1_000 });
} catch (error) {
void this.whenConnectorClosed()?.then(
() => this.finalizeRetiredTurn(deferredTurnId, true),
() => undefined,
);
throw error;
}
this.finalizeRetiredTurn(deferredTurnId, false);
return { retired: true };
return this.closeAndRetire(deferredTurnId, { force: cancelTimedOut, timeoutMs: 1_000 });
}
/** Selects the most recent sessions from a bounded scan of the provider's pages. */
@@ -1410,13 +1461,30 @@ class AcpRuntime {
await this.closeConnector(options);
const child = this.child;
if (!child || this.processFailed) return;
if (child.exitCode !== null || child.signalCode !== null) return;
const closed = new Promise<void>((resolve) => child.once("close", () => resolve()));
if (child.exitCode !== null || child.signalCode !== null) {
destroyChildStreams(child);
return;
}
// Wait for process exit rather than stream "close" alone: on Windows, a grandchild that
// inherited stdio handles can keep the pipes open long after the ACP child exits.
const exited = new Promise<void>((resolve) => {
const done = () => {
child.off("exit", done);
child.off("close", done);
resolve();
};
child.once("exit", done);
child.once("close", done);
});
const killGraceMs = options?.killGraceMs ?? 1_000;
await terminateProcess(child, "SIGTERM");
if (await settlesWithin(closed, killGraceMs)) return;
if (await settlesWithin(exited, killGraceMs)) {
destroyChildStreams(child);
return;
}
await terminateProcess(child);
if (!(await settlesWithin(closed, 1_000))) {
destroyChildStreams(child);
if (!(await settlesWithin(exited, 1_000))) {
throw new Error(`ACP provider ${this.options.options.id} did not terminate after SIGKILL`);
}
}
@@ -3013,6 +3081,16 @@ function withTimeout<Value>(
});
}
function destroyChildStreams(child: ChildProcessWithoutNullStreams): void {
for (const stream of [child.stdin, child.stdout, child.stderr]) {
try {
if (!stream.destroyed) stream.destroy();
} catch {
// Ignore stream teardown errors after the child has been killed.
}
}
}
async function settlesWithin(promise: Promise<void>, timeoutMs: number): Promise<boolean> {
let timer: ReturnType<typeof setTimeout> | null = null;
try {
@@ -24,13 +24,7 @@ const KIND_DETAILS = new Map<string, KindDetail>(
}),
edit: editDetail,
delete: editDetail,
search: ({ call, input, output, text }) => ({
type: "search",
query: string(input, "query", "pattern") ?? call.title,
toolName: "search",
content: text ?? string(output, "content", "text"),
filePaths: call.locations.length > 0 ? [...call.locations] : undefined,
}),
search: searchDetail,
execute: ({ call, input, output, text }) => ({
type: "shell",
command: shellCommand(input) ?? call.title,
@@ -98,6 +92,61 @@ function editDetail({ call, input, text }: ToolCallParts): ProviderToolCallDetai
};
}
function searchDetail({ call, input, output, text }: ToolCallParts): ProviderToolCallDetail {
const webAction = webSearchAction(output);
const webResults = webSearchResults(output, webAction, call.content);
return {
type: "search",
query:
string(input, "query", "pattern") ??
(webAction ? (string(webAction, "query") ?? string(webAction, "url")) : undefined) ??
call.title,
toolName: webAction || webResults.length > 0 ? "web_search" : "search",
content: text ?? string(output, "content", "text"),
filePaths: call.locations.length > 0 ? [...call.locations] : undefined,
...(webResults.length > 0 ? { webResults } : {}),
};
}
const WEB_SEARCH_ACTION_TYPES = new Set(["search", "open_page", "find_in_page"]);
/** The OpenAI Responses `web_search_call.action` some ACP agents (Grok) report as `rawOutput.action`. */
function webSearchAction(output: JsonRecord): JsonRecord | undefined {
const action = record(output.action ?? null);
const type = string(action, "type");
return type && WEB_SEARCH_ACTION_TYPES.has(type) ? action : undefined;
}
function webSearchResults(
output: JsonRecord,
webAction: JsonRecord | undefined,
content: JsonValue | undefined,
): Array<{ title: string; url: string }> {
const results: Array<{ title: string; url: string }> = [];
const seen = new Set<string>();
const add = (url: string | undefined, title: string | undefined) => {
if (!url || !/^https?:\/\//i.test(url) || seen.has(url)) return;
seen.add(url);
results.push({ title: title ?? url, url });
};
for (const list of [webAction?.sources, output.sources, output.results]) {
if (!Array.isArray(list)) continue;
for (const entry of list) {
const source = record(entry);
add(string(source, "url"), string(source, "title"));
}
}
for (const block of contentBlocks(content)) {
if (block.type !== "content") continue;
const link = record(block.content ?? null);
if (link.type === "resource_link") add(string(link, "uri"), string(link, "title", "name"));
}
if (webAction && string(webAction, "type") === "open_page") {
add(string(webAction, "url"), undefined);
}
return results;
}
function shellCommand(input: JsonRecord): string | undefined {
const command = string(input, "command");
if (!command) return undefined;
+341
View File
@@ -7384,6 +7384,113 @@ describe("ACP tool call rows", () => {
filePaths: ["/repo/a.ts"],
},
},
{
kind: "search",
start: { title: "Web search:", rawInput: { variant: "WebSearch", backend: true } },
end: {
title: "Web search:",
rawOutput: {
action: {
type: "search",
query: "react native onLayout nativeEvent",
sources: [
{ type: "url", url: "https://reactnative.dev/docs/layoutevent" },
{ type: "url", url: "https://stackoverflow.com/questions/56738500" },
{ type: "url", url: "https://reactnative.dev/docs/layoutevent" },
],
},
id: "ws_1",
status: "completed",
},
},
detail: {
type: "search",
query: "react native onLayout nativeEvent",
toolName: "web_search",
webResults: [
{
title: "https://reactnative.dev/docs/layoutevent",
url: "https://reactnative.dev/docs/layoutevent",
},
{
title: "https://stackoverflow.com/questions/56738500",
url: "https://stackoverflow.com/questions/56738500",
},
],
},
},
{
kind: "search",
start: { title: "Web search:", rawInput: { variant: "WebSearch", backend: true } },
end: {
rawOutput: {
action: { type: "open_page", url: "https://reactnative.dev/docs/view" },
id: "ws_2",
status: "completed",
},
},
detail: {
type: "search",
query: "https://reactnative.dev/docs/view",
toolName: "web_search",
webResults: [
{ title: "https://reactnative.dev/docs/view", url: "https://reactnative.dev/docs/view" },
],
},
},
{
kind: "search",
start: { title: "Search the web", rawInput: { query: "acp spec" } },
end: {
content: [
{
type: "content",
content: {
type: "resource_link",
uri: "https://agentclientprotocol.com/",
name: "ACP",
},
},
{
type: "content",
content: {
type: "resource_link",
uri: "https://github.com/agentclientprotocol",
name: "repo",
title: "ACP on GitHub",
},
},
],
},
detail: {
type: "search",
query: "acp spec",
toolName: "web_search",
webResults: [
{ title: "ACP", url: "https://agentclientprotocol.com/" },
{ title: "ACP on GitHub", url: "https://github.com/agentclientprotocol" },
],
},
},
{
kind: "search",
start: { title: "Find a.ts", rawInput: { pattern: "*.ts" } },
end: {
content: [
{
type: "content",
content: { type: "resource_link", uri: "file:///repo/a.ts", name: "a.ts" },
},
],
locations: [{ path: "/repo/a.ts" }],
},
detail: {
type: "search",
query: "*.ts",
toolName: "search",
filePaths: ["/repo/a.ts"],
},
},
{
kind: "fetch",
start: { title: "Fetch example", rawInput: { url: "https://example.com" } },
@@ -8873,6 +8980,240 @@ describe("runAcpProvider interrupt settlement and hung-cancel retirement (#3256)
vi.useRealTimers();
}
});
it("retires a hung ACP child cleanly even when a detached grandchild holds inherited stdio pipes open", async () => {
const dir = await mkdtemp(path.join(tmpdir(), "paseo-plugin-acp-grandchild-pipe-"));
temporaryDirectories.push(dir);
const pidFile = path.join(dir, "pids.log");
const grandchildPidFile = path.join(dir, "grandchild.pid");
const scriptPath = path.join(dir, "grandchild-pipe-acp.mjs");
await writeFile(
scriptPath,
[
`import { spawn } from "node:child_process";`,
`import { appendFileSync, writeFileSync } from "node:fs";`,
`import { createInterface } from "node:readline";`,
`const cfg = ${JSON.stringify({ pidFile, grandchildPidFile })};`,
`appendFileSync(cfg.pidFile, String(process.pid) + "\\n");`,
`const write = (msg) => process.stdout.write(JSON.stringify(msg) + "\\n");`,
`createInterface({ input: process.stdin }).on("line", (line) => {`,
` if (!line.trim()) return;`,
` const msg = JSON.parse(line);`,
` if (msg.method === "initialize") {`,
` write({ jsonrpc: "2.0", id: msg.id, result: { protocolVersion: 1, agentCapabilities: { loadSession: true } } });`,
` return;`,
` }`,
` if (msg.method === "session/new") {`,
` write({ jsonrpc: "2.0", id: msg.id, result: { sessionId: "gc-acp-session" } });`,
` return;`,
` }`,
` if (msg.method === "session/prompt") {`,
` const gc = spawn(process.execPath, ["-e", "setTimeout(() => {}, 30000)"], {`,
` detached: true,`,
` stdio: ["ignore", "inherit", "inherit"],`,
` });`,
` writeFileSync(cfg.grandchildPidFile, String(gc.pid));`,
` gc.unref();`,
` write({ jsonrpc: "2.0", method: "session/update", params: { sessionId: msg.params.sessionId, update: { sessionUpdate: "tool_call", toolCallId: "gc-tool", name: "run", title: "Background", status: "in_progress" } } });`,
` }`,
`});`,
].join("\n"),
"utf8",
);
const registration = runAcpProvider({
id: "grandchild-pipe-acp",
label: "Grandchild Pipe ACP",
command: [process.execPath, scriptPath],
acpOptions: { interruptGraceMs: 120, interruptKillGraceMs: 120 },
});
const connection = await registration.connect({
versions: [1],
capabilities: ["prompt.message", "session.persistence"],
});
const events: ProviderEvent[] = [];
connection.onEvent((event) => events.push(event));
try {
await connection.send(openInput());
await waitForEvent(events, (event) => event.type === "session.ready");
const sessionPid = (await readFile(pidFile, "utf8")).trim().split("\n").map(Number).at(-1)!;
await connection.send({
type: "session.prompt",
sessionId: "session-1",
prompt: {
clientMessageId: "gc-turn-1",
delivery: "auto",
input: { type: "message", content: [{ type: "text", text: "spawn-grandchild" }] },
},
});
await waitForEvent(
events,
(event) => event.type === "timeline.item" && event.item.type === "tool_call",
);
await connection.send({
type: "session.interrupt",
requestId: "stop-gc",
sessionId: "session-1",
});
await waitForEvent(
events,
(event) => event.type === "request.completed" && event.requestId === "stop-gc",
3_000,
);
await waitForEvent(events, (event) => event.type === "session.closed", 3_000);
expect(() => process.kill(sessionPid, 0)).toThrow();
expect(
events.some((event) => event.type === "request.failed" && event.requestId === "stop-gc"),
).toBe(false);
expect(
events.filter(
(event) =>
event.type === "session.turn" &&
event.turnId === "acp:gc-turn-1" &&
event.state === "canceled",
),
).toHaveLength(1);
} finally {
if (existsSync(grandchildPidFile)) {
const gcPid = Number((await readFile(grandchildPidFile, "utf8")).trim());
if (Number.isFinite(gcPid) && gcPid > 0) {
try {
process.kill(gcPid, "SIGKILL");
} catch {
// Already terminated by taskkill /T on Windows.
}
}
}
await connection.close();
}
});
it("retries pending retirement on follow-up interrupt instead of failing with ACP transport is closed", async () => {
let connectorCall = 0;
let releaseStalledClose: (() => void) | null = null;
const base = connectorHarness({
capabilities: { loadSession: true },
handleRequest(_instance, request) {
if (request.method === "session/prompt") {
return true; // Never answer prompt or cancel.
}
return false;
},
});
const connector = () => {
connectorCall += 1;
const stream = base.connector();
if (connectorCall !== 2) return stream;
const writer = stream.writable.getWriter();
let released = false;
const releaseOnce = (action: () => Promise<void>, resolve: () => void) => {
releaseStalledClose = () => {
if (released) return;
released = true;
void action()
.catch(() => undefined)
.finally(resolve);
};
};
return {
readable: stream.readable,
writable: new WritableStream<AcpStreamMessage>({
write: (message) => writer.write(message),
close: () =>
new Promise<void>((resolve) => {
releaseOnce(() => writer.close(), resolve);
}),
abort: () =>
new Promise<void>((resolve) => {
releaseOnce(() => writer.abort(), resolve);
}),
}),
};
};
const registration = runAcpProvider({
id: "retry-pending-retirement-acp",
label: "Retry Pending Retirement ACP",
connector,
acpOptions: { interruptGraceMs: 80, interruptKillGraceMs: 80 },
});
const connection = await registration.connect({
versions: [1],
capabilities: ["prompt.message", "session.persistence"],
});
const events: ProviderEvent[] = [];
connection.onEvent((event) => events.push(event));
try {
await connection.send(openInput());
await waitForEvent(events, (event) => event.type === "session.ready");
await connection.send({
type: "session.prompt",
sessionId: "session-1",
prompt: {
clientMessageId: "retry-retire-1",
delivery: "auto",
input: { type: "message", content: [{ type: "text", text: "hang" }] },
},
});
await waitForEvent(
events,
(event) =>
event.type === "session.turn" &&
event.turnId === "acp:retry-retire-1" &&
event.state === "started",
);
// First interrupt times out closing the stalled connector.
await connection.send({
type: "session.interrupt",
requestId: "stop-retry-1",
sessionId: "session-1",
});
const firstFail = await waitForEvent(
events,
(event) => event.type === "request.failed" && event.requestId === "stop-retry-1",
3_000,
);
expect(firstFail.type === "request.failed" && firstFail.error.message).toContain(
"ACP connector did not close",
);
// Even after the connector stream is already aborted and activePrompt settled as null,
// a follow-up interrupt must retry retirement instead of calling cancel() on the closed transport.
await connection.send({
type: "session.interrupt",
requestId: "stop-retry-2",
sessionId: "session-1",
});
releaseStalledClose!();
await waitForEvent(
events,
(event) => event.type === "request.completed" && event.requestId === "stop-retry-2",
3_000,
);
await waitForEvent(events, (event) => event.type === "session.closed", 3_000);
expect(
events
.filter(
(event) =>
event.type === "session.closed" ||
(event.type === "request.completed" && event.requestId === "stop-retry-2"),
)
.map((event) => event.type),
).toEqual(["request.completed", "session.closed"]);
expect(
events.some(
(event) =>
event.type === "request.failed" &&
event.error.message.includes("ACP transport is closed"),
),
).toBe(false);
} finally {
releaseStalledClose?.();
await connection.close();
}
});
});
describe("turnEnd transformer hook", () => {
+6
View File
@@ -77,6 +77,12 @@ export interface UsageAccount {
provider?: string;
/** Store locator, opaque to the daemon. */
input: JsonValue;
/**
* Optional usage report already obtained during discovery (for CLI-backed sources whose
* discovery command returns full quota data). Consumed only by the current discovery-to-fetch
* pass; standalone refreshes still call `fetch` live.
*/
report?: UsageReport;
}
export const UsageScopeSchema = z.discriminatedUnion("kind", [
+1 -1
View File
@@ -100,7 +100,7 @@
"speech:transcribe:local": "tsx scripts/transcribe-local-wav.ts",
"test": "npm run test:unit && npm run test:integration",
"test:unit": "vitest run --fileParallelism --exclude \"**/*.e2e.test.ts\"",
"test:integration": "vitest run --fileParallelism --maxWorkers=3 src/server/daemon-e2e/daemon-shutdown.e2e.test.ts src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/concurrent-agent-refresh.e2e.test.ts src/server/daemon-e2e/agent-archive-overlap.e2e.test.ts src/server/daemon-e2e/create-agent-mode.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/frame-compression.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/creation-status.e2e.test.ts src/server/daemon-e2e/persisted-creation-caller.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/acp-child-exit-recovery.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts src/server/plugins/usage-sources.e2e.test.ts src/server/plugins/lifecycle.e2e.test.ts src/server/plugins/agent-configuration.e2e.test.ts src/server/plugins/worktree-manager.e2e.test.ts src/server/connected-hosts/hosts.e2e.test.ts src/server/owned-subscriptions.e2e.test.ts && vitest run --fileParallelism --maxWorkers=3 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts src/server/agent/agent-mcp.e2e.test.ts src/server/plugins/agent-tools.e2e.test.ts -t \"agent MCP protocol negotiation|merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history|changes the launch wrap|negotiates protected endpoint security\"",
"test:integration": "vitest run --fileParallelism --maxWorkers=3 src/server/daemon-e2e/daemon-shutdown.e2e.test.ts src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/concurrent-agent-refresh.e2e.test.ts src/server/daemon-e2e/agent-archive-overlap.e2e.test.ts src/server/daemon-e2e/create-agent-mode.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/frame-compression.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/creation-status.e2e.test.ts src/server/daemon-e2e/persisted-creation-caller.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/acp-child-exit-recovery.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/managed-update.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts src/server/plugins/usage-sources.e2e.test.ts src/server/plugins/lifecycle.e2e.test.ts src/server/plugins/agent-configuration.e2e.test.ts src/server/plugins/worktree-manager.e2e.test.ts src/server/connected-hosts/hosts.e2e.test.ts src/server/owned-subscriptions.e2e.test.ts && vitest run --fileParallelism --maxWorkers=3 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts src/server/agent/agent-mcp.e2e.test.ts src/server/plugins/agent-tools.e2e.test.ts -t \"agent MCP protocol negotiation|merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history|changes the launch wrap|negotiates protected endpoint security\"",
"test:hub-cli-contract": "vitest run --maxWorkers=1 src/server/hub/hub-cli-contract.test.ts",
"test:integration:all": "npm run test:e2e",
"test:integration:real": "vitest run real.e2e.test.ts",
@@ -239,6 +239,36 @@ export async function findExecutable(
return null;
}
/** Find a launcher on disk even if it cannot be executed. */
export async function findInstalledExecutable(name: string): Promise<string | null> {
const command = name.trim();
if (!command) {
return null;
}
if (process.platform === "win32") {
return findExecutable(command, { probe: false });
}
const candidates = hasPathSeparator(command)
? [command]
: extractAbsolutePathDirs(process.env.PATH).map((directory) => resolve(directory, command));
for (const candidate of candidates) {
try {
if ((await stat(candidate)).isFile()) {
return candidate;
}
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (code !== "ENOENT" && code !== "ENOTDIR") {
throw error;
}
}
}
return null;
}
export async function isCommandAvailable(command: string): Promise<boolean> {
return (await findExecutable(command)) !== null;
}
@@ -32,6 +32,8 @@ import {
} from "./providers/codex-app-server-agent.js";
import { spawnProcess } from "../../utils/spawn.js";
import { createFakeCodexAppServer } from "./providers/codex/test-utils/fake-app-server.js";
import { CopilotACPAgentClient } from "./providers/copilot-acp-agent.js";
import { OpenCodeRuntimeClient } from "./providers/opencode/runtime-client.js";
import { PiRpcAgentClient } from "./providers/pi/agent.js";
import { FakePi } from "./providers/pi/test-utils/fake-pi.js";
import { limitAgentTimelineItemContent } from "./agent-timeline-content.js";
@@ -14961,6 +14963,100 @@ test("listImportableSessions skips providers that lack supportsSessionListing ev
expect(result.sessions.map((d) => d.provider)).toEqual(["claude"]);
});
test("listImportableSessions skips missing default CLIs without skipping disk-backed history", async () => {
const emptyPath = join(process.cwd(), `missing-provider-path-${randomUUID()}`);
vi.stubEnv("PATH", emptyPath);
vi.stubEnv("LOCALAPPDATA", emptyPath);
vi.stubEnv("XDG_STATE_HOME", emptyPath);
vi.stubEnv("PASEO_OPENCODE_SERVER_URL", undefined);
const historyClient = new RecordingPersistedAgentsClient("claude");
historyClient.isAvailable = async () => false;
const opencode = new OpenCodeRuntimeClient(logger);
try {
const manager = new AgentManager({
clients: {
claude: historyClient,
codex: new CodexAppServerAgentClient(logger),
copilot: new CopilotACPAgentClient({ logger }),
opencode,
},
logger,
});
const result = await manager.listImportableSessions();
expect(
result.sessions.map(({ provider, providerHandleId }) => [provider, providerHandleId]),
).toEqual([["claude", "claude-session"]]);
expect(result.providerErrors).toEqual([]);
} finally {
vi.unstubAllEnvs();
await opencode.shutdown();
}
});
test.skipIf(process.platform === "win32").each([
{ failure: "missing interpreters", mode: 0o755 },
{ failure: "missing execute permission", mode: 0o644 },
])("listImportableSessions reports installed default CLIs with $failure", async ({ mode }) => {
const directory = mkdtempSync(join(tmpdir(), "broken-provider-launchers-"));
const interpreter = join(directory, "missing-interpreter");
vi.stubEnv("PATH", directory);
vi.stubEnv("XDG_STATE_HOME", directory);
vi.stubEnv("PASEO_OPENCODE_SERVER_URL", undefined);
const opencode = new OpenCodeRuntimeClient(logger);
try {
for (const command of ["codex", "copilot", "opencode"]) {
writeFileSync(join(directory, command), `#!${interpreter}\n`, { mode });
}
const manager = new AgentManager({
clients: {
codex: new CodexAppServerAgentClient(logger),
copilot: new CopilotACPAgentClient({ logger }),
opencode,
},
logger,
});
const result = await manager.listImportableSessions();
expect(result.sessions).toEqual([]);
expect(result.providerErrors.map(({ provider }) => provider).sort()).toEqual([
"codex",
"copilot",
"opencode",
]);
} finally {
vi.unstubAllEnvs();
await opencode.shutdown();
rmSync(directory, { recursive: true, force: true });
}
});
test("listImportableSessions reports missing explicitly configured launchers", async () => {
const missingDirectory = join(tmpdir(), `missing-provider-launchers-${randomUUID()}`);
const codexCommand = join(missingDirectory, "codex-launcher");
const copilotCommand = join(missingDirectory, "copilot-launcher");
const manager = new AgentManager({
clients: {
codex: new CodexAppServerAgentClient(logger, {
command: { mode: "replace", argv: [codexCommand] },
}),
copilot: new CopilotACPAgentClient({
logger,
runtimeSettings: { command: { mode: "replace", argv: [copilotCommand] } },
}),
},
logger,
});
expect(await manager.listImportableSessions()).toEqual({
sessions: [],
providerErrors: [
{ provider: "codex", message: `Codex command '${codexCommand}' not found` },
{ provider: "copilot", message: `copilot command '${copilotCommand}' not found` },
],
});
});
test("listImportableSessions returns healthy rows alongside thrown and timed-out provider errors", async () => {
vi.useFakeTimers();
try {
@@ -147,6 +147,7 @@ import {
projectAgentMessages,
} from "./agent-messages/index.js";
import { isStaleProviderSessionError } from "./stale-provider-session-error.js";
import { DefaultProviderExecutableNotFoundError } from "./provider-launch-config.js";
import {
PASEO_MCP_SERVER_NAME,
stripInternalPaseoMcpServer,
@@ -1818,6 +1819,10 @@ export class AgentManager {
};
} catch (error) {
cancellation.abort(error);
// Some providers read history without a CLI, so only skip when listing needs one.
if (error instanceof DefaultProviderExecutableNotFoundError) {
return { sessions: [], error: null };
}
this.logger.warn(
{ err: error, provider },
"Failed to list importable sessions for provider",
@@ -2,6 +2,7 @@ import { isAbsolute } from "node:path";
import {
executableExists,
findExecutable,
findInstalledExecutable,
} from "../../executable-resolution/executable-resolution.js";
import {
createExternalProcessEnv,
@@ -51,6 +52,25 @@ export interface ProviderLaunchAvailability {
resolvedPath: string | null;
}
export class DefaultProviderExecutableNotFoundError extends Error {
constructor(message: string) {
super(message);
this.name = "DefaultProviderExecutableNotFoundError";
}
}
export async function defaultProviderExecutableError(
command: string,
notFoundMessage: string,
findAdditionalInstalledExecutable?: () => Promise<string | null>,
): Promise<Error> {
const installedPath =
(await findInstalledExecutable(command)) ?? (await findAdditionalInstalledExecutable?.());
return installedPath
? new Error(`Command '${command}' was found but could not start`)
: new DefaultProviderExecutableNotFoundError(notFoundMessage);
}
export interface ProviderLaunchDefault {
command: string;
resolvePath?: () => Promise<string | null>;
@@ -4378,6 +4378,19 @@ test("listProviderEnvironments returns enabled env-configured providers with bas
extends: "codex",
label: "Codex (No Env)",
},
"omp-command-only": {
extends: "omp",
label: "OMP (Custom Command)",
command: ["/opt/omp/bin/omp", "--profile", "team"],
},
"omp-broker": {
extends: "omp",
label: "OMP (Broker)",
env: {
OMP_AUTH_BROKER_URL: "http://127.0.0.1:4321",
OMP_AUTH_BROKER_TOKEN: "broker-token",
},
},
},
});
try {
@@ -4408,6 +4421,18 @@ test("listProviderEnvironments returns enabled env-configured providers with bas
configuredEnvKeys: ["CODEX_HOME"],
launch: { command: "/opt/homebrew/bin/teamcodex", args: ["run", "--"] },
},
{
provider: "omp",
label: "OMP (Custom Command)",
configuredEnvKeys: [],
launch: { command: "/opt/omp/bin/omp", args: ["--profile", "team"] },
},
{
provider: "omp",
label: "OMP (Broker)",
configuredEnvKeys: ["OMP_AUTH_BROKER_URL", "OMP_AUTH_BROKER_TOKEN"],
launch: { command: "omp", args: [] },
},
]);
expect(envs[0]!.env.CLAUDE_CONFIG_DIR).toBe("/tmp/claude-work");
expect(envs[0]!.env.CLAUDE_SECURESTORAGE_CONFIG_DIR).toBe("/tmp/claude-work-secure");
@@ -529,12 +529,12 @@ export class ProviderSnapshotManager {
return this.createAgentManagerState(this.generation.definitions, this.providerClients);
}
/** Enabled providers that configure their own env, for host usage discovery. */
/** Enabled providers that configure their own env or command, for host usage discovery. */
listProviderEnvironments(): ProviderUsageEnvironment[] {
return this.generation.order.flatMap((provider) => {
const definition = this.generation.definitions[provider];
const runtimeSettings = definition?.configuration?.runtimeSettings;
if (!definition?.enabled || !runtimeSettings?.env) return [];
if (!definition?.enabled || (!runtimeSettings?.env && !runtimeSettings?.command)) return [];
const baseProvider = definition.derivedFromProviderId ?? provider;
const env = createProviderEnv({ baseEnv: process.env, runtimeSettings });
const { command, args } = buildProviderUsageLaunch(baseProvider, runtimeSettings, env);
@@ -543,7 +543,7 @@ export class ProviderSnapshotManager {
provider: baseProvider,
label: definition.label,
env,
configuredEnvKeys: Object.keys(runtimeSettings.env),
configuredEnvKeys: Object.keys(runtimeSettings.env ?? {}),
launch: { command, args },
},
];
@@ -1185,6 +1185,152 @@ describe("ACP selection validity helpers", () => {
});
});
describe("ACP search tool details", () => {
function completedSearchDetail(
start: Record<string, unknown>,
end: Record<string, unknown>,
): unknown {
const internals = asInternals<ACPSessionInternals>(createSession());
internals.translateSessionUpdate({
sessionUpdate: "tool_call",
toolCallId: "ws-1",
kind: "search",
status: "in_progress",
title: "Web search:",
...start,
} as SessionUpdate);
const events = internals.translateSessionUpdate({
sessionUpdate: "tool_call_update",
toolCallId: "ws-1",
status: "completed",
...end,
} as SessionUpdate);
const last = events.at(-1);
if (last?.type !== "timeline" || last.item.type !== "tool_call") {
throw new Error("Expected a tool call timeline item");
}
return last.item.detail;
}
test("reads a Grok web search query and its sources", () => {
const detail = completedSearchDetail(
{ rawInput: { variant: "WebSearch", backend: true } },
{
title: "Web search:",
rawOutput: {
action: {
type: "search",
query: "react native onLayout nativeEvent",
sources: [
{ type: "url", url: "https://reactnative.dev/docs/layoutevent" },
{ type: "url", url: "https://stackoverflow.com/questions/56738500" },
{ type: "url", url: "https://reactnative.dev/docs/layoutevent" },
],
},
id: "ws-1",
status: "completed",
},
},
);
expect(detail).toEqual({
type: "search",
query: "react native onLayout nativeEvent",
toolName: "web_search",
webResults: [
{
title: "https://reactnative.dev/docs/layoutevent",
url: "https://reactnative.dev/docs/layoutevent",
},
{
title: "https://stackoverflow.com/questions/56738500",
url: "https://stackoverflow.com/questions/56738500",
},
],
});
});
test("shows the page a Grok open_page action opened", () => {
const detail = completedSearchDetail(
{ rawInput: { variant: "WebSearch", backend: true } },
{
rawOutput: {
action: { type: "open_page", url: "https://reactnative.dev/docs/view" },
id: "ws-1",
status: "completed",
},
},
);
expect(detail).toEqual({
type: "search",
query: "https://reactnative.dev/docs/view",
toolName: "web_search",
webResults: [
{ title: "https://reactnative.dev/docs/view", url: "https://reactnative.dev/docs/view" },
],
});
});
test("lists web resource_link content blocks as results", () => {
const detail = completedSearchDetail(
{ title: "Search the web", rawInput: { query: "acp spec" } },
{
content: [
{
type: "content",
content: {
type: "resource_link",
uri: "https://agentclientprotocol.com/",
name: "ACP",
},
},
{
type: "content",
content: {
type: "resource_link",
uri: "https://github.com/agentclientprotocol",
name: "repo",
title: "ACP on GitHub",
},
},
],
},
);
expect(detail).toEqual({
type: "search",
query: "acp spec",
toolName: "web_search",
content: "https://agentclientprotocol.com/\nACP on GitHub",
webResults: [
{ title: "ACP", url: "https://agentclientprotocol.com/" },
{ title: "ACP on GitHub", url: "https://github.com/agentclientprotocol" },
],
});
});
test("keeps a file search as a plain search", () => {
const detail = completedSearchDetail(
{ title: "Find a.ts", rawInput: { pattern: "*.ts" } },
{
content: [
{
type: "content",
content: { type: "resource_link", uri: "file:///repo/a.ts", name: "a.ts" },
},
{ type: "content", content: { type: "text", text: "a.ts:1" } },
],
locations: [{ path: "/repo/a.ts" }],
},
);
expect(detail).toEqual({
type: "search",
query: "*.ts",
toolName: "search",
content: "file:///repo/a.ts\na.ts:1",
filePaths: ["/repo/a.ts"],
});
});
});
describe("ACPAgentSession Zed parity", () => {
test("applies valid stored mode/model values, routes current_mode_update, and skips invalid Cursor-style stored values with warnings", async () => {
const validSession = createSessionWithConfig({ modeId: "plan", model: "sonnet" });
@@ -126,6 +126,7 @@ import {
import { importSessionFromPersistence } from "../provider-session-import.js";
import { StaleProviderSessionError } from "../stale-provider-session-error.js";
import {
defaultProviderExecutableError,
checkProviderLaunchAvailable,
createProviderEnv,
createProviderEnvSpec,
@@ -1992,7 +1993,11 @@ export class ACPAgentClient implements AgentClient {
});
const availability = await checkProviderLaunchAvailable(prefix);
if (!availability.available) {
throw new Error(`${this.provider} command '${this.defaultCommand[0]}' not found`);
const message = `${this.provider} command '${prefix.command}' not found`;
if (prefix.source === "override") {
throw new Error(message);
}
throw await defaultProviderExecutableError(prefix.command, message);
}
return {
command: prefix.command,
@@ -4676,15 +4681,71 @@ function buildEditToolDetail(context: MapToolDetailContext): ToolCallDetail {
function buildSearchAcpToolDetail(context: MapToolDetailContext): ToolCallDetail {
const { snapshot, textContent, rawInput, rawOutput } = context;
const webAction = readWebSearchAction(rawOutput);
const webResults = collectWebSearchResults(rawOutput, webAction, snapshot.content);
return {
type: "search",
query: readString(rawInput, ["query", "pattern"]) ?? snapshot.title,
toolName: "search",
query:
readString(rawInput, ["query", "pattern"]) ??
readString(webAction, ["query"]) ??
readString(webAction, ["url"]) ??
snapshot.title,
toolName: webAction || webResults.length > 0 ? "web_search" : "search",
content: textContent ?? readString(rawOutput, ["content", "text"]),
filePaths: snapshot.locations?.map((location) => location.path),
...(webResults.length > 0 ? { webResults } : {}),
};
}
const WEB_SEARCH_ACTION_TYPES = new Set(["search", "open_page", "find_in_page"]);
/** The OpenAI Responses `web_search_call.action` some ACP agents (Grok) report as `rawOutput.action`. */
function readWebSearchAction(
rawOutput: Record<string, unknown> | null,
): Record<string, unknown> | null {
const action = readRecord(rawOutput?.action);
const type = readString(action, ["type"]);
return action && type && WEB_SEARCH_ACTION_TYPES.has(type) ? action : null;
}
function collectWebSearchResults(
rawOutput: Record<string, unknown> | null,
webAction: Record<string, unknown> | null,
content: ToolCallContent[] | null | undefined,
): Array<{ title: string; url: string }> {
const results: Array<{ title: string; url: string }> = [];
const seen = new Set<string>();
const add = (url: unknown, title: unknown) => {
if (typeof url !== "string" || !isWebUrl(url) || seen.has(url)) {
return;
}
seen.add(url);
results.push({ title: typeof title === "string" && title.trim() ? title : url, url });
};
for (const list of [webAction?.sources, rawOutput?.sources, rawOutput?.results]) {
if (!Array.isArray(list)) {
continue;
}
for (const entry of list) {
const record = readRecord(entry);
add(record?.url, record?.title);
}
}
for (const item of content ?? []) {
if (item.type === "content" && item.content.type === "resource_link") {
add(item.content.uri, item.content.title ?? item.content.name);
}
}
if (readString(webAction, ["type"]) === "open_page") {
add(webAction?.url, undefined);
}
return results;
}
function isWebUrl(value: string): boolean {
return /^https?:\/\//i.test(value);
}
function buildShellToolDetail(context: MapToolDetailContext): ToolCallDetail {
const { snapshot, textContent, terminalContent, rawInput, rawOutput } = context;
return {
@@ -82,6 +82,7 @@ import {
import { normalizeCodexFilePath } from "./codex/tool-call-detail-parser.js";
import {
buildProviderUsageLaunch,
defaultProviderExecutableError,
checkProviderLaunchAvailable,
createProviderEnv,
createProviderEnvSpec,
@@ -639,7 +640,7 @@ export function codexMicrosoftStoreBinaryCandidates(
.sort();
}
export async function findCodexMicrosoftStoreBinary(): Promise<string | null> {
export async function findCodexMicrosoftStoreBinary(probe = true): Promise<string | null> {
if (process.platform !== "win32") {
return null;
}
@@ -657,7 +658,7 @@ export async function findCodexMicrosoftStoreBinary(): Promise<string | null> {
}
for (const candidate of codexMicrosoftStoreBinaryCandidates(packageRoot, entries)) {
if (await probeExecutable(candidate)) {
if (probe ? await probeExecutable(candidate) : await findExecutable(candidate, { probe })) {
return candidate;
}
}
@@ -677,8 +678,13 @@ async function resolveCodexLaunchPrefix(
const launch = await resolveCodexLaunch(runtimeSettings);
const availability = await checkCodexLaunchAvailable(launch);
if (!availability.available) {
throw new Error(
if (launch.source === "override") {
throw new Error(`Codex command '${launch.command}' not found`);
}
throw await defaultProviderExecutableError(
launch.command,
"Codex binary not found. Install the Codex CLI (https://github.com/openai/codex) and ensure it is available in your shell PATH.",
() => findCodexMicrosoftStoreBinary(false),
);
}
return {
@@ -5,6 +5,7 @@ import { afterEach, describe, expect, test } from "vitest";
import {
buildCommandResolutionDiagnosticRows,
readCommandVersionOutput,
toDiagnosticErrorMessage,
} from "./diagnostic-utils.js";
@@ -127,6 +128,17 @@ describe("buildCommandResolutionDiagnosticRows", () => {
});
});
describe("readCommandVersionOutput", () => {
test("returns the version as plain text when the CLI styles it for a terminal", async () => {
const output = await readCommandVersionOutput({
command: process.execPath,
args: ["-e", String.raw`process.stdout.write("\x1b[1m\x1b[32mtool 1.2.3\x1b[0m\n")`],
});
expect(output).toBe("tool 1.2.3");
});
});
describe("toDiagnosticErrorMessage", () => {
test("returns message for plain Error", () => {
expect(toDiagnosticErrorMessage(new Error("boom"))).toBe("boom");
@@ -1,6 +1,7 @@
import { constants } from "node:fs";
import { access, stat } from "node:fs/promises";
import path from "node:path";
import stripAnsi from "strip-ansi";
import {
createProviderEnvSpec,
@@ -397,7 +398,8 @@ export async function readCommandVersionOutput(
timeout: 5_000,
signal: invocation.signal,
});
return stdout.trim() || stderr.trim();
// Some CLIs style `--version` for a terminal even when piped; callers show the text as is.
return stripAnsi(stdout).trim() || stripAnsi(stderr).trim();
}
async function resolveCommandVersion(invocation: BinaryDiagnosticVersionCommand): Promise<string> {
@@ -2834,3 +2834,39 @@ test("OMP catalog sessions skip startup work that agent sessions keep", async ()
expect(agentLaunch?.argv).not.toContain(flag);
}
});
test("OMP resolves configured command and env for usage discovery and sessions", async () => {
const runtime = new FakeOmp();
const client = new OmpAgentClient({
logger: createTestLogger(),
runtime,
runtimeSettings: {
command: { mode: "replace", argv: ["/custom/bin/omp", "--profile", "broker"] },
env: {
OMP_AUTH_BROKER_URL: "http://127.0.0.1:8787",
OMP_AUTH_BROKER_TOKEN: "test-token",
},
},
});
const launch = await client.resolveUsageLaunch();
expect(launch).toMatchObject({
command: "/custom/bin/omp",
args: ["--profile", "broker"],
env: expect.objectContaining({
OMP_AUTH_BROKER_URL: "http://127.0.0.1:8787",
OMP_AUTH_BROKER_TOKEN: "test-token",
}),
});
const session = await client.createSession({ provider: "omp", cwd: "/workspace/project" });
onTestFinished(() => session.close());
expect(session.usageSession?.()).toMatchObject({
provider: "omp",
launch: {
command: "/custom/bin/omp",
args: ["--profile", "broker"],
},
});
});
@@ -54,7 +54,9 @@ import { importSessionFromPersistence } from "../../provider-session-import.js";
import { runProviderRefreshActivity } from "../../provider-refresh-deadline.js";
import { runProviderTurn } from "../provider-runner.js";
import {
buildProviderUsageLaunch,
checkProviderLaunchAvailable,
createProviderEnv,
resolveProviderLaunch,
type ProviderRuntimeSettings,
type ResolvedProviderLaunch,
@@ -221,6 +223,7 @@ interface StartTurnResult {
interface OmpAgentSessionOptions {
runtimeSession: OmpRuntimeSession;
runtimeSettings?: ProviderRuntimeSettings;
commandProfile?: string;
hostTools?: OmpHostToolRouter;
restartRuntime: (
@@ -797,14 +800,17 @@ export class OmpAgentSession implements AgentSession {
provider: "omp",
model: modelToId(this.state.model) ?? undefined,
env,
launch: buildProviderUsageLaunch("omp", this.runtimeSettings, env),
sessionKey: this.usageSessionKey,
};
}
private readonly runtimeSettings?: ProviderRuntimeSettings;
private readonly commandProfile?: string;
constructor(options: OmpAgentSessionOptions) {
this.runtimeSession = options.runtimeSession;
this.runtimeSettings = options.runtimeSettings;
this.commandProfile = options.commandProfile;
this.hostTools = options.hostTools;
this.canStopBackgroundJobs = options.canStopBackgroundJobs;
@@ -2694,6 +2700,14 @@ export class OmpAgentClient implements AgentClient {
this.runtime = options.runtime;
}
async resolveUsageLaunch() {
return buildProviderUsageLaunch(
"omp",
this.runtimeSettings,
createProviderEnv({ baseEnv: process.env, runtimeSettings: this.runtimeSettings }),
);
}
private async configureNativePaseoTools(
runtimeSession: OmpRuntimeSession,
catalog: PaseoToolCatalog | undefined,
@@ -2772,6 +2786,7 @@ export class OmpAgentClient implements AgentClient {
);
return new OmpAgentSession({
runtimeSession,
runtimeSettings: this.runtimeSettings,
commandProfile: readOmpCommandProfile(this.runtimeSettings?.command),
hostTools,
restartRuntime: this.buildRestartRuntime(startInput, config, launchContext),
@@ -2850,6 +2865,7 @@ export class OmpAgentClient implements AgentClient {
const initialState = await this.restoreFastMode(runtimeSession, config, resumedState);
return new OmpAgentSession({
runtimeSession,
runtimeSettings: this.runtimeSettings,
commandProfile: readOmpCommandProfile(this.runtimeSettings?.command),
hostTools,
restartRuntime: this.buildRestartRuntime(startInput, config, launchContext),
@@ -7331,6 +7331,73 @@ describe("OpenCode session permission rules", () => {
}
});
// OpenCode appends PATCH /session/{id} permission rules to the session's list, so resending
// rules the session already ends with only grows it.
test("does not resend rules a resumed session already ends with", async () => {
const cwd = tmpCwd();
const runtime = new TestOpenCodeHarness();
const openCode = new TestOpenCodeClient();
openCode.sessionGetResponse = {
data: { id: "ses_resumed_again", directory: cwd, title: null, permission: expectedRules },
};
runtime.enqueueClient(openCode);
const client = new OpenCodeAgentClient(logger, undefined, {
serverManager: runtime,
createClient: runtime.createClient,
});
try {
const session = await client.resumeSession(
{ provider: "opencode", sessionId: "ses_resumed_again", metadata: { cwd } },
permissionConfig(cwd),
);
try {
expect(openCode.calls.sessionUpdate).toEqual([]);
} finally {
await session.close();
}
} finally {
rmSync(cwd, { recursive: true, force: true });
}
});
test("resends the rules when later rules follow them on the session", async () => {
const cwd = tmpCwd();
const runtime = new TestOpenCodeHarness();
const openCode = new TestOpenCodeClient();
// OpenCode applies the last matching rule, so the agent's rules must end the list again.
openCode.sessionGetResponse = {
data: {
id: "ses_resumed_changed",
directory: cwd,
title: null,
permission: [...expectedRules, { permission: "bash", pattern: "*", action: "allow" }],
},
};
runtime.enqueueClient(openCode);
const client = new OpenCodeAgentClient(logger, undefined, {
serverManager: runtime,
createClient: runtime.createClient,
});
try {
const session = await client.resumeSession(
{ provider: "opencode", sessionId: "ses_resumed_changed", metadata: { cwd } },
permissionConfig(cwd),
);
try {
expect(openCode.calls.sessionUpdate).toEqual([
expect.objectContaining({
sessionID: "ses_resumed_changed",
permission: expectedRules,
}),
]);
} finally {
await session.close();
}
} finally {
rmSync(cwd, { recursive: true, force: true });
}
});
test("fails the resume when the rules cannot be applied", async () => {
const cwd = tmpCwd();
const runtime = new TestOpenCodeHarness();
@@ -120,6 +120,7 @@ import type { ManagedProcessRegistry } from "../../managed-processes/managed-pro
import {
buildOpenCodePermissionRules,
OpenCodeProviderOptionsSchema,
type OpenCodePermissionRule,
type OpenCodeProviderOptions,
} from "./opencode/options.js";
@@ -1588,6 +1589,12 @@ export class OpenCodeAgentClient implements AgentClient {
): Promise<void> {
const permission = buildOpenCodePermissionRules(config.providerOptions, config.toolPolicy);
if (!permission) return;
// OpenCode appends updated rules to the session's list and applies the last matching rule,
// so a session whose list already ends with these rules is already governed by them.
const current = readOpenCodeRecord(
await client.session.get({ sessionID: sessionId, directory: config.cwd }),
);
if (endsWithPermissionRules(readOpenCodeRecord(current?.data)?.permission, permission)) return;
const response = readOpenCodeRecord(
await client.session.update({ sessionID: sessionId, directory: config.cwd, permission }),
);
@@ -2108,6 +2115,20 @@ async function listOpenCodeCommandsFromSdk(
return Array.from(commandsByName.values());
}
/** Whether `current` ends with `rules`, compared rule by rule. */
function endsWithPermissionRules(current: unknown, rules: OpenCodePermissionRule[]): boolean {
if (!Array.isArray(current) || current.length < rules.length) return false;
const tail = current.slice(current.length - rules.length);
return rules.every((rule, index) => {
const existing = readOpenCodeRecord(tail[index]);
return (
existing?.permission === rule.permission &&
existing.pattern === rule.pattern &&
existing.action === rule.action
);
});
}
function readOpenCodeRecord(value: unknown): Record<string, unknown> | null {
return typeof value === "object" && value !== null && !Array.isArray(value)
? (value as Record<string, unknown>)

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