Compare commits

...
Author SHA1 Message Date
Mohamed Boudra 7ab4c8a208 fix(usage): resolve sources and manual accounts independently 2026-12-05 07:16:34 +01:00
Mohamed Boudra 4cb11b0feb fix(usage): resolve independent profile account readings 2026-12-05 07:06:30 +01:00
Mohamed Boudra 3c57d9db99 feat(usage): match OpenRouter profiles across harnesses 2026-12-05 06:57:27 +01:00
Mohamed Boudra a71452a009 feat(usage): expose quota reports with agent profiles 2026-12-05 06:57:22 +01:00
Mohamed Boudra 5f8f3c3a44 Give plugin popovers a raw bounded canvas with plugin-owned scroll and spacing (#12088)
* fix(plugins): hand scroll and spacing ownership to plugin popovers

Plugin popovers previously wrapped every body in an outer scroll view with forced 12px padding, which broke fixed-header/footer layouts and prevented plugins from sharing one isomorphic layout across panels, screens, modals, and popovers.

- Remove the host scroll wrapper and forced padding/gap on PluginPopoverSurface and PluginPopoverContent while letting explicit menu pages keep scrollable behavior.
- Enforce bounded maxHeight with overflow hidden on non-scrollable desktop AnchoredSurface popovers so short popovers hug content and tall Header + ScrollView + Footer popovers cap at 440px.
- Skip MenuSheetScrollView for scrollable={false} bottom sheets while keeping BottomSheetScope, BottomSafeAreaInset, MenuSheetHeader, and animated visible-frame sizing so Android/mobile sheets hug short content, cap tall scrolling bodies at 80% height above system nav bars, and dismiss on swipe.
- Update button/E2E popover examples and plugin docs.

* fix(app): keep compact sheet content mounted when revealing a scroller

Keep MenuSheetCanvasBody's outer Animated.View, BottomSafeAreaInset, wrappers, and MenuPage mounted when hasScrollView flips false <-> true so lazily revealing a ScrollView or FlatList preserves plugin state cleanly. Track scroll measuring with a shared value to size newly revealed scrollers at maxHeight before settling.

Also replace the mocked JSDOM sheet test with real Chromium Playwright coverage of compact lazy-reveal state preservation and extract composable popover layout helpers in plugin-composer-pill-items.spec.ts.

* fix(app): hug fixed-height scrollers in compact plugin sheets

* fix(app): remeasure compact plugin sheets when scroller sizing mode changes

* fix(app): track intrinsic scroll canvas growth via wrapper height

* fix(app): retain scroller layout height across remeasurement

* fix(app): keep raw-canvas sheet height ownership on native and Android initial mount
2026-12-05 12:42:03 +07:00
Mohamed Boudra 9859997f9c polish(app): fix hover, selection, and sidebar contrast across Pure Black and Light (#12095)
* polish(app): derive surfaceHover/surfaceSelected and fix Pure Black and Light contrast

Twelve interactive surfaces on surface0 reused surface1 (only 1.06:1 in Pure Black and 1.04:1 in Light), while Pure Black surface3 (#202020) sat below borderAccent and barely stepped off active rows. Meanwhile, Light mode surface2 equals surfaceSidebar (#f4f4f5), making pressed rows, kebab hovers, and sidebar skeletons invisible on the sidebar.

Derive surfaceHover and surfaceSelected from surface0 across built-in and plugin themes (stepping Light 1.11/1.21 so active rows stay below surface3), lift Pure Black surface3/surface4 to #303030/#454545, migrate the twelve page-surface consumers, and switch sidebar pressed/skeleton/kebab states and Settings nav selection to sidebar-aware tokens.

* polish(app): address PR review feedback on session press fill and theme helpers
2026-12-05 12:22:33 +07:00
Mohamed Boudra 7526bf1260 feat(plugins): add optional minWidth to Explorer plugin panels (#12084)
* feat(plugins): add optional minWidth to Explorer plugin panels

Allows addWorkspacePanel, addAgentPanel, and addFilePanel to declare a positive finite minWidth for desktop Explorer without overwriting the user's saved Explorer width when temporarily widened. Clamps at containerWidth - 360 so the main workspace body stays usable on narrow desktop windows, and ignores minWidth on compact/mobile overlays.

* test(app): replace hook-only browser probe with unit test

* test(app): wait for ExplorerFrame layout before dragging in browser test
2026-12-05 10:29:52 +07:00
360c2b0b3c feat(plugin): add sandboxed HtmlFrame to @getpaseo/plugin/client/ui (#11943)
* refactor(app): let the file preview policy take extra origins and host head markup

* feat(plugin): sandboxed HtmlFrame on web and native, exposed next to DocumentFrame

* docs(plugins): document HtmlFrame and how it inherits CSP

* fix(html-frame): harden navigation token, native sizing, auto-height, and event contracts

* fix(html-frame): follow CSS transitions/animations without 100vh growth loops

* fix(html-frame): freeze-probe 100vh loops and observe body child transitions

* fix(html-frame): settle exact height on transitionend and animationend

* fix(html-frame): only settle transitions/animations that change target and document height

---------

Co-authored-by: Brandon Elliott <923787+Brandon168@users.noreply.github.com>
Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
2026-12-05 09:54:42 +07:00
c7fdc1d3ba fix(app): keep the sidebar project filter inside the window (#11386)
* fix(app): keep the sidebar project filter inside the window

The display preferences popover renders the host, project, and label
pages from data that grows with a host. The wide presentation had no
scroll container, so with more projects than fit the window every row
past the bottom edge was unreachable (#9182). The compact sheet path
already scrolled.

Enable the menu engine's scrolling surface for this menu. It caps the
surface at the window height and gives each page a scroll viewport.

Add a component regression test and an e2e test that seed more projects
than fit the viewport.

* test(app): drop the fixed-path screenshot from the e2e

The assertions already prove the flyout scrolls, and a screenshot at an
absolute /tmp path does not belong in the test. The before/after images
live on the PR instead.

* fix(app): re-anchor scrolling menu surfaces on window resize

The height cap and surface position read Dimensions.get once, so a flyout
opened before a resize kept the old window height and hung past the new
bottom edge. Use useWindowDimensions and include it in the measurement and
placement effects.

The component test now waits for the menu's initial focus before touching
the scroll position, and shrinks the viewport to prove the surface follows.

* test(app): keep browser mechanics in helpers for the project filter e2e

The test body now reads as the user's scenario: the flyout stays in the
window, the last row is below it, the wheel reaches the row. Wheel retries,
layout measurements, and the scroll-container lookup live in helpers.

* test(app): replace mocked menu test and tighten project filter e2e

Remove the mocked display-preferences browser test and move scrollable surface resize coverage into menu-overlay.browser.test.tsx without mocks. Seed the 36 E2E projects in parallel, reuse shared sidebar helpers, and assert resize re-anchoring in the real app.

---------

Co-authored-by: jrd <jrd.dwj@gmail.com>
Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
2026-12-05 09:53:26 +07:00
Mohamed Boudra 279a152c20 Keep Desktop image attachments alive across windows, tab switches, and queued sends (#12082)
* fix(desktop,app): track attachment ownership across windows and in-flight sends

Desktop previously treated each renderer's garbage-collection report as the complete reference set for the shared desktop-attachments directory. Opening or mutating a draft in a second window therefore deleted another window's unsent drafts, sent-message copies, and cached previews with ENOENT. In addition, clearing a composer draft before queueing or uploading a message allowed microtask GC to remove local image files before they were read or restored on failure.

Move shared-directory reference ownership to the Electron main process (tracking per-window reported IDs, in-flight/recent reads and writes, reloads, and window teardown), converge persisted drafts across windows via storage events, and retain local attachments across composer submission, rollback, upload/encoding, and file preview URL resolution.

* fix(desktop,app): harden queued GC read tracking and cross-window draft sync

Track a per-window monotonic touch sequence in DesktopAttachmentManager so a queued GC sweep only clears reads/writes that occurred before it was queued, skip setState when a peer storage update produces no state change, publish text replacement requests for drafts changed by another window, and emit abandoned tombstones when clearing deleted or orphaned drafts.

* fix(app): flush staged draft typing before merging peer storage updates

Flush pending AfterPaintPublication staged keystrokes for keys present in an incoming storage event before comparing timestamps in applyPersistedDraftStorageUpdate so delayed peer updates cannot overwrite in-progress typing.
2026-12-05 09:46:28 +07:00
Mohamed Boudra 7e4617279b fix(plugins): keep plugin panels, screens, and file panels above the system navigation bar (#12079)
* fix(plugins): apply bottom safe-area inset on plugin host surfaces

Outer workspace, explorer, file, and surface containers omit bottom padding so built-in panels can read useSafeAreaInsets().bottom directly. Plugin panels, screens, and file panels did not apply that inset, causing bottom-pinned controls to sit behind Android's system navigation bar.

Extract BottomSafeAreaInset (shared with SheetBottomInset) to pad insets.bottom at the plugin host boundary and provide SafeAreaInsetsContext with bottom=0 to descendants so SheetPane and embedded AgentChat never double-pad.

* test(plugins): verify plugin bottom safe-area layout in browser tests

Replace JSDOM component tests with real Chromium browser tests (*.browser.test.tsx) that assert getBoundingClientRect() bottom clearance, computed paddingBottom, and zeroed SafeAreaInsetsContext.bottom without mocks.

* test(plugins): remove leftover JSDOM bottom safe-area test files
2026-12-05 09:28:39 +07:00
2c8afcf4bd Check the TIFF signature before attaching pasted text on iOS (#11232)
* Check the TIFF signature before attaching pasted text on iOS

* fix(ios): validate full magic-byte headers in paste mime fallback

Extend the NSData+MimeType patch on @mattermost/react-native-paste-input beyond TIFF so GIF, PNG, and JPEG also verify their full signatures with self.length guards before reading bytes.

- GIF: require GIF87a or GIF89a so text starting with 'G' (such as "Good morning" or "Git status") is not attached as .gif
- PNG: require the 8-byte PNG signature
- JPEG: require FF D8 FF so a UTF-16 LE BOM (FF FE) is not attached as .jpg
- TIFF/BigTIFF: preserve suniceman's II*/MM* and II+/MM+ checks

Add macOS clang test coverage in scripts/postinstall-patches.test.mjs for plain text prefixes, UTF-16 LE BOM, truncated headers, and valid signatures across all four image formats.

---------

Co-authored-by: Shane Su <26364206+suniceman@users.noreply.github.com>
Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
2026-12-05 09:23:02 +07:00
Mohamed Boudra 7924d86621 feat(plugins): add author-defined params and identity to workspace and agent panels (#12026)
* feat(plugins): add author-defined params and identity to workspace and agent panels

Lets plugin panels declare an optional Zod params schema and identity(params) coalescing function while preserving tab.state across in-place params updates and revision bumps.

* fix(plugins): validate restored panel params against current schema

* fix(plugins): isolate launcher panel errors and tighten test selectors

* fix(plugins): evaluate panel param transforms once and preserve surface errors

* fix(plugins): cache parsed panel params per contribution and target

* chore(plugins): remove unused EMPTY_WORKSPACE_PARAMS after rebase

* fix(plugins): store idempotent parsed panel params to keep generated defaults aligned with identity
2026-12-04 21:40:47 +07:00
Mohamed Boudra 3484943a7e feat(plugin): add setTitle to PluginTab (#12020)
* feat(plugin): add setTitle to PluginTab

Allow mounted workspace, agent, and file panels to override their tab title at runtime via tab.setTitle(title) and reset back to the static descriptor title on null, empty/whitespace, unmount, reload, or unavailability.

* fix(app): preserve mount-effect tab title and modified state

* fix(app): reset file panel attributes on reload and render error

* test(app): add composerPillItems to navigation test plugin fixture
2026-12-04 20:57:22 +07:00
Mohamed Boudra 55bba06161 feat(plugins): expose openScreen on panel and screen props (#12021)
* feat(plugins): expose openScreen on panel and screen props

Adds top-level openScreen({ screenId, params? }) to PluginPanelProps (covering workspace, agent, and file panels) and PluginScreenProps, matching sidebar items and popovers. Built-in file panels share BuiltinFilePanelProps without plugin-owned navigation capabilities.

* docs(plugins): document app version guidance for panel/screen openScreen

* refactor(plugins): use object params in screen navigation and ports in unit tests
2026-12-04 20:27:18 +07:00
Mohamed Boudra 4863e7e761 feat(plugins): add declarative addComposerPillItem, ComposerPill, and fix button store updates (#12019)
* feat(plugins): add addComposerPillItem, ComposerPill, and fix button store updates

* fix(plugins): encode submenu page IDs and anchor fallback composer popovers

* docs(plugins): add addComposerPillItem to migration guide and dedupe buttonPageId test
2026-12-04 20:26:12 +07:00
Mohamed Boudra ad9073dc8a test(e2e): hold all running agent updates until release in consecutive turns spec (#12034)
Since PR #12011 moved lastUserMessageAt updates and emitState(agent) to the SQLite user_message commit callback, submitting a follow-up prompt emits a second agent_update(status: running) after the initial running snapshot.

holdNextAgentUpdate() cleared its pending hold after the first match, letting that second running snapshot reach the browser before turn_started or send_agent_message_response were released and causing turn-working-elapsed to mount early.

Add holdAgentUpdates/releaseHeldAgentUpdates to hold every matching agent_update until explicitly released in arrival order, preserving all release-order assertions in agent-consecutive-turns.spec.ts.
2026-12-04 20:26:06 +07:00
paseo-bot[bot]andClaude Opus 5.5 35f0ff6ff1 Stop the relay E2E from losing its port to a parallel test (#12017)
* test(relay): let wrangler pick the relay port in the relay E2E

The relay E2E reserved a free port, closed it, then started wrangler on it.
Test files run three at a time, and another file could bind the port in
between: workerd failed with "Address already in use" and the test failed
with "Local relay did not stop". Wrangler now binds port 0 itself and the
test reads the port from its "Ready on" line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(relay): read the relay port from a complete line, keep startup errors

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 12:00:40 +00:00
paseo-bot[bot] b31565fbf7 fix(terminal): paste once on Linux middle-click (#12025)
Mouse tracking sends the click to the terminal application, while Chromium also pastes the primary selection on release. Suppress the native paste when the application owns the press, and leave the terminal paste available for the shell or forced selection.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-04 10:43:42 +00:00
paseo-bot[bot] 8302319f54 Keep old replies out of finish notifications (#12014)
* fix(server): keep old replies out of finish notifications

A tool-only turn can finish without producing a reply. Scope the preview to the completed turn so the notification uses the existing generic body when that turn has no reply.

* fix(server): keep background finish previews through runtime refresh

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-04 10:43:19 +00:00
babo-jeongukandClaude Opus 5.5 8b0c22ca31 fix(server): persist the last user message time once a submitted prompt is recorded (#12011)
Since the timeline moved to async SQLite commits, a prompt submitted through
Paseo set lastUserMessageAt in the commit callback without emitting state.
The stored record and the live agent_state kept the previous prompt's time
until the next state change, and a daemon crash in that window left the
record stale after restart.

Set lastUserMessageAt and emit state at the timeline commit point for every
user_message, and drop the two caller-side copies of that rule.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 10:42:59 +00:00
TheCouchCommanderandCodex 26175ed408 Coalesce Gitea and Forgejo PR status polling and honor rate limits (#12004)
* Coalesce Gitea PR status polling and honor rate limits

* Honor Forgejo proxy backoff and share Actions task reads

---------

Co-authored-by: Codex <codex@localhost>
2026-12-04 09:13:03 +00:00
paseo-bot[bot] 41e21d8d5f fix(desktop): keep the workspace aligned when editing chat drafts (#11983)
Anchor the top resize strip to the titlebar edge so titlebar padding cannot create horizontal overflow. Cover Page Down in the packaged desktop smoke test.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-04 08:42:53 +00:00
paseo-bot[bot] 5700dc3ea1 Keep Android image previews sharp when zooming (#11989)
* fix(app): keep Android image previews sharp when zooming

Android decodes the image to the fitted layout size by default. A pinch scales that bitmap, so details lost during decoding cannot come back. Preserve the source resolution in the zoomable image viewer.

* Keep Android zoom detail within the native bitmap limit

* Remove the obsolete Git object in the plugin update test

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-04 08:13:02 +00:00
Mohamed Boudra aabb5764d3 ci(website): isolate website tests from typecheck and clean up E2E specs (#11992)
* ci(website): isolate website tests from typecheck and clean up E2E specs

Website Playwright runs were bundled into the required typecheck job, so WebKit downloads and website timing failures blocked unrelated PRs. Moving website unit and E2E runs into a dedicated website-tests job keeps typecheck focused on build and type verification.

Also remove layout/geometry assertions and fake-clock mockup animation tests from packages/website/e2e, keeping interactive user journeys and placement-specific checks, and align Playwright CI workers and retries with the app and desktop suites.

* ci(website): include README sponsor tables in website path filter
2026-12-04 15:12:47 +07:00
Mohamed Boudra 4fe15a6918 fix(plugins): keep Git plugin revision lookup local in blobless clones (#11999)
Switching Git plugin clones to --filter=blob:none registered a promisor remote in the cloned repository, causing rev-parse to lazily fetch unadvertised or amended-away commits from origin (without GIT_ENV or credential rewrites) instead of failing revision verification. Set GIT_NO_LAZY_FETCH=1 on revParse so revision lookups stay strictly against the cloned refs and commit graph while checkout continues fetching blobs on demand. Also route managed-source.ts changes through the browser CI path filter.
2026-12-04 14:35:36 +07:00
Mohamed Boudra 32a5dd8bad test(e2e): approve AgentChat client plugins in browser specs (#11986)
Both AgentChat browser specs (#9602) were merged without calling approveClientPluginsInUi after per-host client plugin execution approval (#11717) landed, causing all 7 tests to time out waiting for the unapproved plugin's sidebar button.
2026-12-04 13:32:30 +07:00
paseo-bot[bot] 70f374f269 fix(desktop): save the stop-on-quit migration (#11984)
Desktop applied the reset in memory on every launch until another setting was saved. Save the reset and its marker together so the settings file reflects the quit policy after the first launch.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-04 06:13:38 +00:00
e31ee658c2 Avoid downloading old files when installing Git plugins (#11980)
* perf(server): clone Git plugin sources without history blobs

- Use blobless clone filter when fetching Git plugin sources to improve install performance
- Add POSIX test verification for blobless git operations

Co-authored-by: RoundRedDot <roundreddot@gmail.com>

* fix(server): preserve credentials during filtered plugin checkout

Co-authored-by: RoundRedDot <roundreddot@gmail.com>

* Merge remote-tracking branch 'origin/main' into fix/plugin-blobless-auth-review

# Conflicts:
#	packages/server/src/server/plugins/managed-source.posix.test.ts

Co-authored-by: RoundRedDot <roundreddot@gmail.com>

* refactor(server): use named Git checkout arguments

Co-authored-by: RoundRedDot <roundreddot@gmail.com>

* Name the bare Git fixture explicitly

Co-authored-by: luke <luopeihuan@gmail.com>

---------

Co-authored-by: luke <luopeihuan@gmail.com>
Co-authored-by: RoundRedDot <roundreddot@gmail.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-04 06:12:59 +00:00
paseo-bot[bot] acde63e614 test(terminal): prove an obsolete worker's program gone by its socket, not its pid (#11967)
On Windows the inspector reports no birth times, so the hard-cut test
could only prove the program gone by its pid not answering. Windows
reuses a freed pid at once, so a busy runner could keep the pid alive
under another process for the whole 10 s wait. The program now listens
on a socket of its own, and the test waits for that socket to close.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-04 06:00:53 +00:00
paseo-bot[bot] 25d9ed2985 fix(app): collapse turns with plugin-rendered work (#11974)
Calculate the summary from the work each card represents so a completed turn folds when a plugin renders its tools and reasoning.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-04 05:12:58 +00:00
252 changed files with 16245 additions and 1960 deletions
+11 -1
View File
@@ -72,7 +72,7 @@ browser:
- "packages/server/src/server/agent/providers/codex-app-server-agent.ts"
- "packages/server/src/server/agent/providers/claude/agent.ts"
- "packages/server/src/server/agent/plugin-provider.ts"
- "packages/server/src/server/plugins/{index,plugin-process,plugin-process-protocol,runtime}.ts"
- "packages/server/src/server/plugins/{index,managed-source,plugin-process,plugin-process-protocol,runtime}.ts"
- "packages/server/src/executable-resolution/**"
- "packages/plugin/src/server/provider.ts"
- "packages/app/src/!(desktop)/**"
@@ -88,6 +88,16 @@ browser:
relay:
- "packages/relay/**"
website:
- "packages/website/**"
- "packages/protocol/**"
- "public-docs/**"
- "CHANGELOG.md"
- "CHANGELOG.zh-CN.md"
- "README*.md"
- "assets/brand/**"
- "packages/app/assets/images/editor-apps/finder.png"
# cli-tests is also a daemon end-to-end suite: it drives a real daemon, built-in
# plugins and the plugin runtime included, so their changes run it too.
cli:
+32 -10
View File
@@ -43,6 +43,7 @@ jobs:
browser: ${{ steps.filter.outputs.browser }}
relay: ${{ steps.filter.outputs.relay }}
cli: ${{ steps.filter.outputs.cli }}
website: ${{ steps.filter.outputs.website }}
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
with:
@@ -163,12 +164,11 @@ jobs:
- name: Run plugin SDK tests
run: npm run test --workspace=@getpaseo/plugin
# The locked Playwright installers do not support ubuntu-latest's Ubuntu 26.04.
typecheck:
name: typecheck
needs: changes
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.quality != 'false') }}
runs-on: ubuntu-24.04
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@@ -195,6 +195,32 @@ jobs:
- name: Typecheck all packages
run: npm run typecheck
- name: Verify public package contents
run: |
npm pack --dry-run --ignore-scripts --workspace=@getpaseo/protocol
npm pack --dry-run --ignore-scripts --workspace=@getpaseo/client
npm pack --dry-run --ignore-scripts --workspace=@getpaseo/server
# The locked Playwright installers do not support ubuntu-latest's Ubuntu 26.04.
website-tests:
name: website-tests
needs: changes
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.website != 'false') }}
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: "22"
cache: "npm"
- name: Install dependencies
run: node scripts/npm-retry.mjs ci
- name: Build protocol
run: npm run build:protocol
- name: Run website tests
run: npx vitest run packages/website/src --bail=1
@@ -222,7 +248,7 @@ jobs:
cp "${archive_debs[@]}" ~/website-browser-debs/
fi
- name: Verify website mockups
- name: Run website E2E tests
run: npm run test:e2e --workspace=@getpaseo/website
- name: Upload website test artifacts
@@ -230,16 +256,12 @@ jobs:
if: failure()
with:
name: website-playwright-results
path: packages/website/test-results/
path: |
packages/website/test-results/
packages/website/playwright-report/
if-no-files-found: ignore
retention-days: 7
- name: Verify public package contents
run: |
npm pack --dry-run --ignore-scripts --workspace=@getpaseo/protocol
npm pack --dry-run --ignore-scripts --workspace=@getpaseo/client
npm pack --dry-run --ignore-scripts --workspace=@getpaseo/server
server-tests-ubuntu:
name: server-tests (ubuntu-latest)
needs: changes
+19 -3
View File
@@ -433,7 +433,9 @@ query cache. Explicit SDK targets follow the [host API contract](../public-docs/
Workspace panels, Command Center items, and client slash commands are client contributions. The
daemon transports their compiled bundle without interpreting placement or callbacks. Panel props
contain workspace and agent IDs. Required-selector hooks read normalized client state synchronously
carry `workspaceId`, validated read-only `params` (with host-enforced `agentId` on agent panels),
`revision`, and `tab`; optional `identity(params)` sets the coalescing key on the persisted
`plugin` target. Required-selector hooks read normalized client state synchronously
and use shallow equality, so a panel does not subscribe to fields it does not render. Command
callbacks materialize their snapshots only when invoked. Contribution discovery and panel opening
never fetch active context through plugin RPC. Snapshot DTOs are deeply readonly and frozen at
@@ -442,8 +444,8 @@ runtime so plugin code cannot mutate normalized app state or a memoized selectio
current installed-plugin catalog. A missing contribution renders unavailable inside the tab.
Panels declare `locations: ["workspace", "explorer"]` to opt into Explorer hosting; omission means
workspace only. Location controls hosting, not context. An agent panel target keeps its `agentId`
when moved between hosts. Explorer configuration can create workspace-context panels and remove
existing agent-context instances, but it cannot create an agent panel without an agent-aware command.
and `params` when moved between hosts. UI launchers only offer workspace-context panels whose
`params` schema accepts `{}`.
`AgentChat` renders the agent tab's own chain (`AgentPanelContent` in
`packages/app/src/panels/agent-panel.tsx`) through `packages/app/src/agent-embed`. The chain takes
@@ -802,6 +804,20 @@ read. See the [public file panel reference](../public-docs/plugins/reference.md#
the author API, selection, `DocumentFrame`, and the version requirement. The examples live in
`plugin-examples/pdf-panel` and `plugin-examples/markdown-panel`.
## HtmlFrame
`HtmlFrame` (`packages/app/src/html-frame`) runs HTML in a sandboxed frame for plugins; the
[public reference](../public-docs/plugins/reference.md#htmlframe) owns the author API. It reuses the
file preview hardening: `file-panels/html-preview-csp.ts` builds the policy,
`html-preview-navigation.ts` guards the native WebView. Web uses a `sandbox="allow-scripts"`
`srcdoc` iframe verified with a per-mount bootstrap token before flushing queued host messages,
native wraps the WebView in a sized `View` so inline auto-height frames work inside scrolling lists,
and one bootstrap script (`bootstrap.ts`) gives the page the same `window.parent.postMessage`
contract on both. A `srcdoc` iframe inherits its embedder's CSP. Neither the daemon's web UI
(`web-ui.ts`), nor the desktop `paseo://` protocol handler, nor `index.html` sets one, so allowed
CDN scripts load; a reverse proxy that adds a `Content-Security-Policy` header to the app page would
also bind the frame and block them.
## Contribute buttons
Header buttons and composer pills share the client-only descriptor and registration lifecycle in
@@ -745,7 +745,8 @@ async function recordDelayedRunningTransition(
const prompt = "Second prompt keeps streaming.";
gate.holdNextAgentStreamEvent("turn_started");
gate.holdNextAgentUpdate(agent.agentId, "running");
// Hold every running snapshot until release so the prompt-commit emitState does not leak early.
gate.holdAgentUpdates(agent.agentId, "running");
gate.holdNextServerMessage("send_agent_message_response");
gate.setAgentStreamSuppressed(true);
await recordTurnFrames(page, prompt);
@@ -773,7 +774,7 @@ async function recordDelayedRunningTransition(
await expect(page.getByTestId("turn-working-elapsed")).toBeVisible();
gate.releaseHeldServerMessage("send_agent_message_response");
responseReleased = true;
gate.releaseHeldAgentUpdate(agent.agentId, "running");
gate.releaseHeldAgentUpdates(agent.agentId, "running");
snapshotReleased = true;
} else if (releaseOrder === "response-before-turn") {
gate.releaseHeldServerMessage("send_agent_message_response");
@@ -782,13 +783,13 @@ async function recordDelayedRunningTransition(
gate.releaseHeldAgentStreamEvent("turn_started");
turnReleased = true;
await expect(page.getByTestId("turn-working-elapsed")).toBeVisible();
gate.releaseHeldAgentUpdate(agent.agentId, "running");
gate.releaseHeldAgentUpdates(agent.agentId, "running");
snapshotReleased = true;
} else {
gate.releaseHeldServerMessage("send_agent_message_response");
responseReleased = true;
await recordPaintsFor(page, 80);
gate.releaseHeldAgentUpdate(agent.agentId, "running");
gate.releaseHeldAgentUpdates(agent.agentId, "running");
snapshotReleased = true;
await expect(page.getByTestId("turn-working-elapsed")).toBeVisible();
gate.releaseHeldAgentStreamEvent("turn_started");
@@ -804,7 +805,7 @@ async function recordDelayedRunningTransition(
return { frames, checkpoints };
} finally {
if (!turnReleased) gate.releaseHeldAgentStreamEvent("turn_started");
if (!snapshotReleased) gate.releaseHeldAgentUpdate(agent.agentId, "running");
if (!snapshotReleased) gate.releaseHeldAgentUpdates(agent.agentId, "running");
if (!responseReleased) gate.releaseHeldServerMessage("send_agent_message_response");
gate.setAgentStreamSuppressed(false);
}
@@ -10,6 +10,7 @@ import {
type MockAgentWorkspace,
} from "../support/helpers/mock-agent";
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
import { approveClientPluginsInUi } from "../support/helpers/plugin-execution-approval";
import { pluginRequirements } from "../support/helpers/plugin-fixture";
const PLUGIN_ID = "agent-chat-focus-e2e";
@@ -135,6 +136,7 @@ async function withEmbeds(
await client.patchDaemonConfig({ pluginsEnabled: true });
await client.installDirectoryPlugin(directory);
await gotoAppShell(page);
await approveClientPluginsInUi(page, [PLUGIN_ID]);
await page.getByRole("button", { name: SCREEN_TITLE, exact: true }).click();
const embed = (agentId: string) => page.getByTestId(`embed-${agentId}`);
for (const agent of agents) {
@@ -2,6 +2,7 @@ import { expect, test, type Page } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
import { approveClientPluginsInUi } from "../support/helpers/plugin-execution-approval";
import { copyPluginExample } from "../support/helpers/plugin-fixture";
const PLUGIN_ID = "agent-chat-example";
@@ -14,6 +15,7 @@ function embed(page: Page) {
async function openAgentInEmbed(page: Page): Promise<void> {
await gotoAppShell(page);
await approveClientPluginsInUi(page, [PLUGIN_ID]);
await page.getByRole("button", { name: "Agents", exact: true }).click();
await page
.getByTestId("example-agent-list")
@@ -0,0 +1,775 @@
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import type { Locator, Page } from "@playwright/test";
import { expect, test } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { openCommandCenter } from "../support/helpers/command-center";
import { buildAgentRoute } from "../support/helpers/mock-agent";
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
import { approveClientPluginsInUi } from "../support/helpers/plugin-execution-approval";
import { pluginRequirements } from "../support/helpers/plugin-fixture";
import { seedWorkspace } from "../support/helpers/seed-client";
const PLUGIN_ID = "composer-pill-items-e2e";
const WIDE = { width: 1440, height: 900 };
const COMPACT = { width: 390, height: 844 };
function pluginSource(workspaceId: string, agentId: string): string {
return `import React from "react";
import { Pressable, Text, View } from "react-native";
import { useWorkspace } from "@getpaseo/plugin/client";
import { ComposerPill, ScrollView } from "@getpaseo/plugin/client/ui";
function InboxScreen({ theme, params }) {
return (
<View style={{ flex: 1, padding: 24, gap: 8 }}>
<Text style={{ color: theme.colors.foreground }}>Inbox screen for {params.agentId}</Text>
</View>
);
}
function InboxPopover({ theme, layout, close, openScreen }) {
const workspaceName = useWorkspace(${JSON.stringify(workspaceId)}, (w) => w.name);
return (
<View style={{ padding: 12, gap: 10 }}>
<Text style={{ color: theme.colors.foreground, fontSize: 16 }}>Inbox decisions</Text>
<Text style={{ color: theme.colors.foregroundMuted }}>Workspace: {workspaceName}</Text>
<Text style={{ color: theme.colors.foregroundMuted }}>
Presentation: {layout.compact ? "compact" : "wide"}
</Text>
<Pressable
accessibilityRole="button"
accessibilityLabel="Open inbox screen"
onPress={() => openScreen({ screenId: "inbox", params: { agentId: ${JSON.stringify(agentId)} } })}
>
<Text style={{ color: theme.colors.foreground }}>Open screen</Text>
</Pressable>
<Pressable
accessibilityRole="button"
accessibilityLabel="Close inbox popover"
onPress={close}
>
<Text style={{ color: theme.colors.foreground }}>Done</Text>
</Pressable>
</View>
);
}
function TallDecisionsPopover({ theme, close }) {
return (
<View style={{ flex: 1, minHeight: 0 }}>
<View
testID="tall-popover-header"
style={{
paddingHorizontal: 14,
paddingVertical: 12,
borderBottomWidth: 1,
borderBottomColor: theme.colors.border,
}}
>
<Text style={{ color: theme.colors.foreground, fontWeight: "600" }}>Open decisions</Text>
</View>
<ScrollView testID="tall-popover-scroll" style={{ flex: 1 }}>
{Array.from({ length: 24 }, (_, index) => (
<View
key={index}
style={{
paddingHorizontal: 14,
paddingVertical: 10,
borderBottomWidth: 1,
borderBottomColor: theme.colors.border,
}}
>
<Text style={{ color: theme.colors.foreground }}>{"Decision item " + index}</Text>
</View>
))}
</ScrollView>
<View
testID="tall-popover-footer"
style={{
paddingHorizontal: 14,
paddingVertical: 12,
borderTopWidth: 1,
borderTopColor: theme.colors.border,
}}
>
<Pressable
accessibilityRole="button"
accessibilityLabel="Submit decisions"
onPress={close}
style={{
paddingVertical: 8,
paddingHorizontal: 12,
borderRadius: 6,
backgroundColor: theme.colors.surface2,
alignItems: "center",
}}
>
<Text style={{ color: theme.colors.foreground }}>Submit</Text>
</Pressable>
</View>
</View>
);
}
function TallDecisionsPill({ openPopover }) {
return (
<ComposerPill
icon="ListChecks"
label="All decisions"
onPress={() => openPopover(TallDecisionsPopover)}
/>
);
}
function RevealResultsPopover({ theme, close }) {
const [clicks, setClicks] = React.useState(0);
const [revealed, setRevealed] = React.useState(false);
return (
<View style={revealed ? { flex: 1, minHeight: 0 } : { padding: 12, gap: 8 }}>
<View
testID="reveal-popover-header"
style={{
paddingHorizontal: revealed ? 14 : 0,
paddingVertical: revealed ? 10 : 0,
gap: 8,
}}
>
<Pressable
accessibilityRole="button"
accessibilityLabel={"Reveal count: " + clicks}
onPress={() => setClicks((count) => count + 1)}
>
<Text style={{ color: theme.colors.foreground }}>{"Reveal count: " + clicks}</Text>
</Pressable>
{revealed ? null : (
<Pressable
accessibilityRole="button"
accessibilityLabel="Show results"
onPress={() => setRevealed(true)}
>
<Text style={{ color: theme.colors.foreground }}>Show results</Text>
</Pressable>
)}
</View>
{revealed ? (
<ScrollView testID="reveal-popover-scroll" style={{ flex: 1 }}>
{Array.from({ length: 24 }, (_, index) => (
<View
key={index}
style={{
paddingHorizontal: 14,
paddingVertical: 10,
borderBottomWidth: 1,
borderBottomColor: theme.colors.border,
}}
>
<Text style={{ color: theme.colors.foreground }}>{"Result item " + index}</Text>
</View>
))}
</ScrollView>
) : null}
<View style={{ paddingHorizontal: revealed ? 14 : 0, paddingVertical: revealed ? 10 : 0 }}>
<Pressable
accessibilityRole="button"
accessibilityLabel="Close reveal popover"
onPress={close}
>
<Text style={{ color: theme.colors.foreground }}>Close results</Text>
</Pressable>
</View>
</View>
);
}
function RevealResultsPill({ openPopover }) {
return (
<ComposerPill
icon="Search"
label="Lazy results"
onPress={() => openPopover(RevealResultsPopover)}
/>
);
}
function FixedScrollPopover({ theme, close }) {
const [expanded, setExpanded] = React.useState(false);
const [extraFooterAction, setExtraFooterAction] = React.useState(false);
const [filtered, setFiltered] = React.useState(false);
return (
<View style={expanded ? { flex: 1, minHeight: 0 } : undefined}>
<View testID="fixed-scroll-header" style={{ paddingHorizontal: 14, paddingVertical: 10 }}>
<Text style={{ color: theme.colors.foreground, fontWeight: "600" }}>Fixed viewport</Text>
</View>
<ScrollView testID="fixed-scroll-body" style={expanded ? { flex: 1 } : { height: 120 }}>
{Array.from({ length: filtered ? 1 : 16 }, (_, index) => (
<View key={index} style={{ height: 28, justifyContent: "center", paddingHorizontal: 14 }}>
<Text style={{ color: theme.colors.foreground }}>{"Fixed row " + index}</Text>
</View>
))}
</ScrollView>
<View
testID="fixed-scroll-footer"
style={{ gap: 8, paddingHorizontal: 14, paddingVertical: 10 }}
>
<View style={{ flexDirection: "row", flexWrap: "wrap", gap: 12 }}>
<Pressable
accessibilityRole="button"
accessibilityLabel="Filter fixed rows"
onPress={() => setFiltered((value) => !value)}
>
<Text style={{ color: theme.colors.foreground }}>Filter rows</Text>
</Pressable>
<Pressable
accessibilityRole="button"
accessibilityLabel="Add footer action"
onPress={() => setExtraFooterAction((value) => !value)}
>
<Text style={{ color: theme.colors.foreground }}>Add footer action</Text>
</Pressable>
<Pressable
accessibilityRole="button"
accessibilityLabel="Expand fixed viewport"
onPress={() => setExpanded((value) => !value)}
>
<Text style={{ color: theme.colors.foreground }}>
{expanded ? "Collapse fixed" : "Expand fixed"}
</Text>
</Pressable>
<Pressable
accessibilityRole="button"
accessibilityLabel="Close fixed viewport"
onPress={close}
>
<Text style={{ color: theme.colors.foreground }}>Close fixed</Text>
</Pressable>
</View>
{extraFooterAction ? (
<View testID="fixed-scroll-extra-action" style={{ height: 48, justifyContent: "center" }}>
<Text style={{ color: theme.colors.foreground }}>Secondary footer action</Text>
</View>
) : null}
</View>
</View>
);
}
function FixedScrollPill({ openPopover }) {
return (
<ComposerPill
icon="PanelTop"
label="Fixed scroll"
onPress={() => openPopover(FixedScrollPopover)}
/>
);
}
function LivePopover({ theme, close }) {
return (
<View style={{ padding: 12, gap: 8 }}>
<Text style={{ color: theme.colors.foreground }}>Live popover content</Text>
<Pressable
accessibilityRole="button"
accessibilityLabel="Trigger live update"
onPress={() => updateLivePopover?.()}
>
<Text style={{ color: theme.colors.foreground }}>Update</Text>
</Pressable>
<Pressable
accessibilityRole="button"
accessibilityLabel="Close live popover"
onPress={close}
>
<Text style={{ color: theme.colors.foreground }}>Close</Text>
</Pressable>
</View>
);
}
let updateLivePopover = null;
function QuietPill({ workspaceId }) {
const name = useWorkspace(workspaceId, (w) => w.name);
if (name !== "Show quiet pill") return null;
return <ComposerPill icon="Sparkles" label="Quiet" onPress={() => {}} />;
}
let finishAction = () => {};
let actionAttempts = 0;
function ActionPill() {
const [checks, setChecks] = React.useState(0);
return (
<ComposerPill
icon="Play"
label={checks === 0 ? "Run check" : "Checks · " + checks}
title="Run check action"
onPress={async () => {
actionAttempts += 1;
if (actionAttempts === 1) throw new Error("Action check failed");
await new Promise((resolve) => {
finishAction = resolve;
});
setChecks((n) => n + 1);
}}
/>
);
}
function InboxPill({ openPopover }) {
return (
<ComposerPill
icon="Inbox"
label="2 decisions"
onPress={() => openPopover(InboxPopover)}
/>
);
}
export default function contribute(client) {
const workspaceId = ${JSON.stringify(workspaceId)};
const agentId = ${JSON.stringify(agentId)};
client.addScreen({ id: "inbox", title: "Inbox Screen", Component: InboxScreen });
const removeQuiet = client.addComposerPillItem({ id: "quiet", title: "Quiet", Component: QuietPill });
const removeAction = client.addComposerPillItem({ id: "action", title: "Run check", Component: ActionPill });
const removeInbox = client.addComposerPillItem({ id: "inbox", title: "Inbox decisions", Component: InboxPill });
const removeTall = client.addComposerPillItem({ id: "tall", title: "All decisions", Component: TallDecisionsPill });
const removeReveal = client.addComposerPillItem({ id: "reveal", title: "Reveal results", Component: RevealResultsPill });
const removeFixed = client.addComposerPillItem({ id: "fixed", title: "Fixed viewport", Component: FixedScrollPill });
const live = client.addComposerPill({
id: "live-popover",
workspaceId,
agentId,
button: {
title: "Live popover",
icon: "Eye",
label: "Live",
behavior: { kind: "popover", Content: LivePopover },
},
});
const dynamicMenu = client.addComposerPill({
id: "dynamic-menu",
workspaceId,
agentId,
button: {
title: "Dynamic menu",
icon: "List",
label: "Decisions",
behavior: {
kind: "menu",
items: [
{
kind: "item",
id: "D42",
title: "Decision D42",
behavior: {
kind: "action",
onPress() {
dynamicMenu.update({ label: "Picked D42" });
},
},
},
],
},
},
});
client.addCommandCenterItem({
id: "finish-check",
title: "Finish check action",
icon: "Check",
context: "workspace",
onSelect: () => finishAction(),
});
updateLivePopover = () =>
live.update({
label: "Live · 2",
behavior: { kind: "popover", Content: LivePopover },
});
return () => {
finishAction();
removeQuiet();
removeAction();
removeInbox();
removeTall();
removeReveal();
removeFixed();
live.remove();
dynamicMenu.remove();
};
}
`;
}
async function runCommand(page: Page, title: string) {
const panel = await openCommandCenter(page);
await panel.getByTestId("command-center-input").fill(title);
await panel.getByRole("button", { name: title, exact: true }).click();
await expect(panel).not.toBeVisible();
}
async function expectStill(subject: Locator) {
let previous: {
buffer: Buffer;
box: { x: number; y: number; width: number; height: number };
} | null = null;
await expect
.poll(
async () => {
const box = await subject.boundingBox();
if (!box || box.width <= 0 || box.height <= 0) {
previous = null;
return false;
}
const buffer = await subject.screenshot();
const still =
previous !== null &&
Math.abs(box.x - previous.box.x) < 0.5 &&
Math.abs(box.y - previous.box.y) < 0.5 &&
Math.abs(box.width - previous.box.width) < 0.5 &&
Math.abs(box.height - previous.box.height) < 0.5 &&
buffer.equals(previous.buffer);
previous = { buffer, box };
return still;
},
{ intervals: [150] },
)
.toBe(true);
}
async function qaScreenshot(page: Page, name: string) {
const directory = process.env.PASEO_QA_SCREENSHOT_DIR;
if (!directory) return;
await page.waitForTimeout(300);
await page.screenshot({ path: path.join(directory, `${name}.png`) });
}
async function scrollToEndAndExpectPinned(options: {
page: Page;
header: Locator;
footer: Locator;
scroll: Locator;
bottomItemLabel: string;
}) {
const { page, header, footer, scroll, bottomItemLabel } = options;
const initialHeaderY = (await header.boundingBox())!.y;
const initialFooterY = (await footer.boundingBox())!.y;
const canScroll = await scroll.evaluate((node) => node.scrollHeight > node.clientHeight + 1);
expect(canScroll).toBe(true);
await scroll.evaluate((node) => {
node.scrollTop = node.scrollHeight;
});
await expect(page.getByText(bottomItemLabel, { exact: true })).toBeVisible();
expect((await header.boundingBox())!.y).toBe(initialHeaderY);
expect((await footer.boundingBox())!.y).toBe(initialFooterY);
}
async function expectPinnedScrollableDesktopPopover(page: Page, pluginId: string) {
const surface = page.getByTestId(`plugin-composer-pill-${pluginId}-tall-popover`);
const header = page.getByTestId("tall-popover-header");
const footer = page.getByTestId("tall-popover-footer");
const scroll = page.getByTestId("tall-popover-scroll");
await expect(header).toBeVisible();
await expect(footer).toBeVisible();
await expectStill(header);
const surfaceBox = (await surface.boundingBox())!;
const headerBox = (await header.boundingBox())!;
const footerBox = (await footer.boundingBox())!;
expect(surfaceBox.height).toBeLessThanOrEqual(441);
// 0px outer padding (1px surface border only).
expect(Math.abs(headerBox.y - surfaceBox.y - 1)).toBeLessThanOrEqual(1);
expect(
Math.abs(surfaceBox.y + surfaceBox.height - (footerBox.y + footerBox.height) - 1),
).toBeLessThanOrEqual(1);
await scrollToEndAndExpectPinned({
page,
header,
footer,
scroll,
bottomItemLabel: "Decision item 23",
});
}
async function expectPinnedScrollableCompactSheet(page: Page, pluginId: string) {
const sheetContent = page.getByTestId(`plugin-composer-pill-${pluginId}-tall-popover-content`);
const header = page.getByTestId("tall-popover-header");
const footer = page.getByTestId("tall-popover-footer");
const scroll = page.getByTestId("tall-popover-scroll");
await expect(sheetContent).toBeVisible();
await expect(footer).toBeInViewport();
await expectStill(sheetContent);
const sheetBox = (await sheetContent.boundingBox())!;
const footerBox = (await footer.boundingBox())!;
expect(sheetBox.height).toBeLessThanOrEqual(COMPACT.height * 0.8 + 1);
expect(footerBox.y + footerBox.height).toBeLessThanOrEqual(COMPACT.height + 1);
await scrollToEndAndExpectPinned({
page,
header,
footer,
scroll,
bottomItemLabel: "Decision item 23",
});
}
async function expectRevealedScrollerPreservesCompactState(page: Page, pluginId: string) {
const revealPill = page.getByRole("button", { name: "Lazy results", exact: true });
await expect(revealPill).toBeVisible();
await revealPill.click();
const sheetContent = page.getByTestId(`plugin-composer-pill-${pluginId}-reveal-popover-content`);
await expect(sheetContent).toBeVisible();
await expect(page.getByRole("button", { name: "Reveal count: 0", exact: true })).toBeInViewport();
await expectStill(sheetContent);
await page.getByRole("button", { name: "Reveal count: 0", exact: true }).click();
await expect(page.getByRole("button", { name: "Reveal count: 1", exact: true })).toBeVisible();
await page.getByRole("button", { name: "Show results", exact: true }).click();
const scroll = page.getByTestId("reveal-popover-scroll");
await expect(scroll).toBeVisible();
await expectStill(sheetContent);
// Revealing a ScrollView in an open sheet must keep plugin state mounted and cap sheet height.
await expect(page.getByRole("button", { name: "Reveal count: 1", exact: true })).toBeVisible();
expect((await sheetContent.boundingBox())!.height).toBeLessThanOrEqual(COMPACT.height * 0.8 + 1);
await scroll.evaluate((node) => {
node.scrollTop = node.scrollHeight;
});
await expect(page.getByText("Result item 23", { exact: true })).toBeVisible();
await page.getByRole("button", { name: "Close reveal popover", exact: true }).click();
await expect(scroll).toHaveCount(0);
}
async function expectCompactSheetHugsFixedScrollPopover(page: Page, pluginId: string) {
const fixedPill = page.getByRole("button", { name: "Fixed scroll", exact: true });
await expect(fixedPill).toBeVisible();
await fixedPill.click();
const sheetContent = page.getByTestId(`plugin-composer-pill-${pluginId}-fixed-popover-content`);
const scroll = page.getByTestId("fixed-scroll-body");
await expect(sheetContent).toBeVisible();
await expect(page.getByTestId("fixed-scroll-footer")).toBeInViewport();
await expectStill(sheetContent);
const sheetBox = (await sheetContent.boundingBox())!;
const footerBox = (await page.getByTestId("fixed-scroll-footer").boundingBox())!;
// A 120px fixed-height ScrollView with short header/footer must hug its own ~200-260px height
// rather than expanding to the 80% sheet cap (675px).
expect(sheetBox.height).toBeLessThan(340);
expect(
Math.abs(sheetBox.y + sheetBox.height - (footerBox.y + footerBox.height)),
).toBeLessThanOrEqual(2);
await scroll.evaluate((node) => {
node.scrollTop = node.scrollHeight;
});
await expect(page.getByText("Fixed row 15", { exact: true })).toBeVisible();
await page.getByRole("button", { name: "Add footer action", exact: true }).click();
await expectStill(sheetContent);
const grownSheetBox = (await sheetContent.boundingBox())!;
const extraActionBox = (await page.getByTestId("fixed-scroll-extra-action").boundingBox())!;
expect(grownSheetBox.height).toBeGreaterThanOrEqual(sheetBox.height + 40);
expect(extraActionBox.y + extraActionBox.height).toBeLessThanOrEqual(
grownSheetBox.y + grownSheetBox.height + 2,
);
await page.getByRole("button", { name: "Add footer action", exact: true }).click();
await expectStill(sheetContent);
await page.getByRole("button", { name: "Filter fixed rows", exact: true }).click();
await expectStill(sheetContent);
const filteredBox = (await sheetContent.boundingBox())!;
const filteredFooterBox = (await page.getByTestId("fixed-scroll-footer").boundingBox())!;
expect(Math.abs(filteredBox.height - sheetBox.height)).toBeLessThanOrEqual(2);
expect(
Math.abs(filteredBox.y + filteredBox.height - (filteredFooterBox.y + filteredFooterBox.height)),
).toBeLessThanOrEqual(2);
await page.getByRole("button", { name: "Filter fixed rows", exact: true }).click();
await expectStill(sheetContent);
await page.getByRole("button", { name: "Expand fixed viewport", exact: true }).click();
await expectStill(sheetContent);
const expandedBox = (await sheetContent.boundingBox())!;
const expandedScrollBox = (await scroll.boundingBox())!;
expect(expandedBox.height).toBeGreaterThan(450);
expect(expandedBox.height).toBeLessThanOrEqual(COMPACT.height * 0.8 + 2);
expect(expandedScrollBox.height).toBeGreaterThan(300);
await page.getByRole("button", { name: "Expand fixed viewport", exact: true }).click();
await expectStill(sheetContent);
const collapsedBox = (await sheetContent.boundingBox())!;
expect(collapsedBox.height).toBeLessThan(340);
await page.getByRole("button", { name: "Close fixed viewport", exact: true }).click();
await expect(scroll).toHaveCount(0);
}
test("declarative addComposerPillItem + ComposerPill and imperative pill fixes work end-to-end", async ({
page,
}) => {
test.setTimeout(180_000);
const workspace = await seedWorkspace({ repoPrefix: "composer-pill-items-" });
const agent = await workspace.client.createAgent({
provider: "mock",
cwd: workspace.repoPath,
workspaceId: workspace.workspaceId,
title: "Declarative composer pills",
model: "e2e-fast-stream",
modeId: "load-test",
});
const client = await connectNewWorkspaceDaemonClient({ ownProjects: false });
const config = await client.getDaemonConfig();
const directory = await mkdtemp(path.join(tmpdir(), "paseo-pill-items-"));
try {
await writeFile(
path.join(directory, "paseo-plugin.json"),
JSON.stringify({ id: PLUGIN_ID, requirements: pluginRequirements }),
);
await writeFile(
path.join(directory, "index.client.tsx"),
pluginSource(workspace.workspaceId, agent.id),
);
await client.patchDaemonConfig({ pluginsEnabled: true });
await client.installDirectoryPlugin(directory);
await page.setViewportSize(WIDE);
await gotoAppShell(page);
await approveClientPluginsInUi(page, [PLUGIN_ID]);
await page.goto(buildAgentRoute(workspace.workspaceId, agent.id));
const actionPill = page.getByRole("button", { name: "Run check action", exact: true });
const inboxPill = page.getByRole("button", { name: "2 decisions", exact: true });
await expect(actionPill).toBeVisible();
await expect(inboxPill).toBeVisible();
await test.step("null items leave no empty gap in the composer track", async () => {
await expect(page.getByRole("button", { name: "Quiet", exact: true })).toHaveCount(0);
const actionBox = (await actionPill.boundingBox())!;
const inboxBox = (await inboxPill.boundingBox())!;
expect(Math.abs(actionBox.y - inboxBox.y)).toBeLessThan(2);
expect(actionBox.height).toBeGreaterThanOrEqual(32);
expect(inboxBox.height).toBeGreaterThanOrEqual(32);
// 4px track gap between adjacent pills with no empty wrapper gap in between.
expect(inboxBox.x - (actionBox.x + actionBox.width)).toBeLessThanOrEqual(8);
await qaScreenshot(page, "01-desktop-track");
});
await test.step("ComposerPill shows error toast on rejection, enters pending busy state, and recovers", async () => {
await actionPill.click();
await expect(page.getByText("Action check failed", { exact: true })).toBeVisible();
await expect(actionPill).toBeEnabled();
await actionPill.click();
await expect(actionPill).toBeDisabled();
await expect(actionPill).toHaveAttribute("aria-busy", "true");
await qaScreenshot(page, "02-desktop-pill-pending");
await runCommand(page, "Finish check action");
await expect(actionPill).toBeEnabled();
await expect(actionPill).toContainText("Checks · 1");
});
await test.step("openPopover anchors above the pill on desktop, dismisses cleanly, and openScreen navigates", async () => {
await inboxPill.click();
const popoverTitle = page.getByText("Inbox decisions", { exact: true });
await expect(popoverTitle).toBeInViewport();
await expect(page.getByText("Presentation: wide", { exact: true })).toBeVisible();
await expectStill(popoverTitle);
const pillBox = (await inboxPill.boundingBox())!;
const popoverBox = (await page
.getByTestId(`plugin-composer-pill-${PLUGIN_ID}-inbox-popover`)
.boundingBox())!;
expect(popoverBox.y + popoverBox.height).toBeLessThanOrEqual(pillBox.y + 1);
expect(Math.abs(popoverBox.x - pillBox.x)).toBeLessThan(80);
await qaScreenshot(page, "03-desktop-popover");
await page.keyboard.press("Escape");
await expect(popoverTitle).toHaveCount(0);
await inboxPill.click();
await expect(popoverTitle).toBeVisible();
await page.getByRole("button", { name: "Open inbox screen", exact: true }).click();
await expect(popoverTitle).toHaveCount(0);
await expect(page.getByText(`Inbox screen for ${agent.id}`, { exact: true })).toBeVisible();
await page.getByTestId("plugin-surface-close").click();
await expect(inboxPill).toBeVisible();
});
await test.step("imperative PluginButtonStore fixes: same-Content popover stays open on update and dynamic menu IDs work", async () => {
const livePill = page.getByRole("button", { name: "Live popover", exact: true });
await livePill.click();
await expect(page.getByText("Live popover content", { exact: true })).toBeVisible();
await page.getByRole("button", { name: "Trigger live update", exact: true }).click();
await expect(livePill).toContainText("Live · 2");
await expect(page.getByText("Live popover content", { exact: true })).toBeVisible();
await page.getByRole("button", { name: "Close live popover", exact: true }).click();
await expect(page.getByText("Live popover content", { exact: true })).toHaveCount(0);
const menuPill = page.getByRole("button", { name: "Dynamic menu", exact: true });
await menuPill.click();
await page.getByRole("menuitem", { name: "Decision D42", exact: true }).click();
await expect(menuPill).toContainText("Picked D42");
});
await test.step("on compact layouts openPopover renders a bottom sheet and dismisses cleanly", async () => {
await page.setViewportSize(COMPACT);
await expect(inboxPill).toBeVisible();
await inboxPill.click();
const compactLabel = page.getByText("Presentation: compact", { exact: true });
await expect(compactLabel).toBeInViewport();
const sheetBox = (await compactLabel.boundingBox())!;
expect(sheetBox.y).toBeGreaterThan(COMPACT.height / 2);
await qaScreenshot(page, "04-compact-sheet");
await page.getByRole("button", { name: "Close inbox popover", exact: true }).click();
await expect(compactLabel).toHaveCount(0);
});
await test.step("tall raw-canvas popover caps at <= 440px on desktop and <= 80% on compact sheet with pinned header/footer and scrolling body", async () => {
const tallPill = page.getByRole("button", { name: "All decisions", exact: true });
await page.setViewportSize(WIDE);
await expect(tallPill).toBeVisible();
await tallPill.click();
await expectPinnedScrollableDesktopPopover(page, PLUGIN_ID);
await qaScreenshot(page, "05-desktop-tall-popover");
await page.getByRole("button", { name: "Submit decisions", exact: true }).click();
await expect(page.getByTestId("tall-popover-header")).toHaveCount(0);
await page.setViewportSize(COMPACT);
await tallPill.click();
await expectPinnedScrollableCompactSheet(page, PLUGIN_ID);
await qaScreenshot(page, "06-compact-tall-sheet");
await page.getByRole("button", { name: "Submit decisions", exact: true }).click();
await expect(page.getByTestId("tall-popover-header")).toHaveCount(0);
});
await test.step("compact raw-canvas sheet preserves plugin state when revealing a ScrollView via user action", async () => {
await page.setViewportSize(COMPACT);
await expectRevealedScrollerPreservesCompactState(page, PLUGIN_ID);
});
await test.step("compact raw-canvas sheet hugs a fixed-height ScrollView without expanding to 80%", async () => {
await page.setViewportSize(COMPACT);
await expectCompactSheetHugsFixedScrollPopover(page, PLUGIN_ID);
});
} finally {
await client.removePlugin(PLUGIN_ID).catch(() => undefined);
await client.patchDaemonConfig({ pluginsEnabled: config.config.pluginsEnabled });
await client.close();
await rm(directory, { recursive: true, force: true });
await workspace.cleanup();
}
});
@@ -27,7 +27,10 @@ import {
} from "@getpaseo/plugin/client";
import { useQueryClient } from "@tanstack/react-query";
import { DocumentFrame, Loading } from "@getpaseo/plugin/client/ui";
function Pdf({ file, workspaceId }) {
function FileDetailsScreen({ params }) {
return <View><Text>File screen: {params.file}</Text></View>;
}
function Pdf({ file, workspaceId, openScreen }) {
usePaseo();
useQueryClient();
const workspace = useWorkspace(workspaceId, value => ({ id: value.id }));
@@ -44,6 +47,9 @@ function Pdf({ file, workspaceId }) {
<Text>Path {file.path}</Text>
<Text>Bytes {bytes.bytes.length}; URL bytes {urlBytes}</Text>
<Text>Workspace {workspace?.id}</Text>
<Pressable accessibilityRole="button" onPress={() => openScreen({ screenId: "details", params: { file: file.name } })}>
<Text>Open screen from file panel</Text>
</Pressable>
<DocumentFrame url={href} testID="plugin-pdf-frame" />
</View>;
}
@@ -69,6 +75,7 @@ function Markdown({ file, tab }) {
</View>;
}
export default function contribute(client) {
client.addScreen({ id: "details", title: "File details", Component: FileDetailsScreen });
client.addFilePanel({ id: "pdf", title: "PDF", icon: "FileText",
files: { extensions: ["pdf", "txt"] }, Component: Pdf });
client.addFilePanel({ id: "markdown", title: "Plugin Markdown", icon: "FileText",
@@ -92,6 +99,16 @@ async function associateMarkdownWithPlugin(page: Page) {
async function editMarkdownThroughPlugin(page: Page) {
await page.getByRole("button", { name: "Edit Markdown through plugin", exact: true }).click();
}
async function openFileDetailsScreenFromPanel(page: Page, name: string) {
await page.getByRole("button", { name: "Open screen from file panel", exact: true }).click();
await expect(page).toHaveURL(
new RegExp(`/plugin/${PLUGIN_ID}/surface/details\\?param\\.file=${encodeURIComponent(name)}$`),
);
await expect(page.getByText(`File screen: ${name}`, { exact: true })).toBeVisible();
await page.getByTestId("plugin-surface-close").click();
await expect(page.getByText(`PDF plugin: ${name}`, { exact: true })).toBeVisible();
}
/** Opens the tab with Paseo's Markdown panel from "Open with…" and shows its Source view. */
async function openBuiltinMarkdownSource(page: Page, name: string) {
await page.getByTestId(`workspace-tab-file_${name}`).first().click({ button: "right" });
@@ -152,6 +169,7 @@ test("directory plugins render PDF bytes and write Markdown through the file han
const pdfScreenshot = testInfo.outputPath("plugin-pdf-web.png");
await page.screenshot({ path: pdfScreenshot });
await testInfo.attach("plugin-pdf-web", { path: pdfScreenshot, contentType: "image/png" });
await openFileDetailsScreenFromPanel(page, "report.pdf");
// A plugin panel claiming a text file competes with Source, so Paseo asks over the plugin.
await openWorkspaceFile(page, "bytes.txt");
@@ -690,16 +690,20 @@ async function updateGitPlugin(page: Page, repository: string) {
async function failUpdateFromPluginPage(page: Page, repository: string) {
await publishGitPluginChange(repository, "Git plugin v3");
await page.reload();
const update = page.getByTestId("plugin-update").filter({ visible: true });
await expect(update).toHaveText("Update");
// Rewriting the commit the page checked leaves its update pointing at a commit the remote no
// longer serves. The next check offers the rewritten commit.
const update = page.getByRole("button", { name: "Update", exact: true });
await expect(update).toBeVisible();
// Remove the advertised commit from the fixture. A file:// remote can still serve an
// amended-away commit by SHA while its object remains in the repository.
execFileSync("git", ["commit", "--amend", "-m", "Git plugin v3, amended"], {
cwd: repository,
stdio: "ignore",
});
execFileSync("git", ["-c", "gc.reflogExpireUnreachable=now", "gc", "--prune=now"], {
cwd: repository,
stdio: "ignore",
});
await update.click();
await expect(update).toHaveText("Retry");
await expect(page.getByRole("button", { name: "Retry", exact: true })).toBeVisible();
await expect(page.getByText(/Git command failed/)).toBeVisible();
}
@@ -0,0 +1,288 @@
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import type { Locator, TestInfo } from "@playwright/test";
import { expect, test, type Page } from "../support/fixtures";
import { openCommandCenter } from "../support/helpers/command-center";
import { openFileExplorer, openFileFromExplorer } from "../support/helpers/file-explorer";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
import { approveClientPluginsInUi } from "../support/helpers/plugin-execution-approval";
import { pluginRequirements } from "../support/helpers/plugin-fixture";
const PLUGIN_ID = "tab-set-title-e2e";
const WIDE = { width: 1440, height: 900 };
const CLIENT_SOURCE = `import React from "react";
import { Pressable, Text, View } from "react-native";
import type {
PluginAgentPanelProps,
PluginClientContext,
PluginFilePanelProps,
PluginWorkspacePanelProps,
} from "@getpaseo/plugin/client";
function TitleControls({
prefix,
nextTitle,
tab,
}: {
prefix: string;
nextTitle: string;
tab: PluginWorkspacePanelProps["tab"];
}) {
return (
<View style={{ padding: 16, gap: 8 }}>
<Text>{prefix} panel</Text>
<Pressable
accessibilityRole="button"
onPress={() => tab.setTitle(" " + nextTitle + " ")}
>
<Text>Set {prefix} title</Text>
</Pressable>
<Pressable
accessibilityRole="button"
onPress={() => tab.setTitle(" ")}
>
<Text>Whitespace {prefix} title</Text>
</Pressable>
<Pressable
accessibilityRole="button"
onPress={() => tab.setTitle(null)}
>
<Text>Reset {prefix} title</Text>
</Pressable>
</View>
);
}
function StatusPanel({ tab }: PluginWorkspacePanelProps) {
return <TitleControls prefix="status" nextTitle="Status (3)" tab={tab} />;
}
function ExplorerStatusPanel({ tab }: PluginWorkspacePanelProps) {
return <TitleControls prefix="explorer" nextTitle="Explorer (7)" tab={tab} />;
}
function InspectorPanel({ tab }: PluginAgentPanelProps) {
return <TitleControls prefix="agent" nextTitle="Inspector: live" tab={tab} />;
}
function NotesTxtPanel({ tab }: PluginFilePanelProps) {
return <TitleControls prefix="file" nextTitle="Readout" tab={tab} />;
}
export default function contribute(client: PluginClientContext) {
client.addWorkspacePanel({
id: "status",
title: "Status",
icon: "PanelsTopLeft",
locations: ["workspace", "explorer"],
Component: StatusPanel,
});
client.addWorkspacePanel({
id: "explorer-status",
title: "Explorer status",
icon: "PanelsTopLeft",
locations: ["workspace", "explorer"],
Component: ExplorerStatusPanel,
});
client.addAgentPanel({
id: "inspector",
title: "Inspector",
icon: "Scan",
locations: ["workspace", "explorer"],
Component: InspectorPanel,
});
client.addFilePanel({
id: "txt-viewer",
title: "Custom TXT",
icon: "FileText",
files: { extensions: ["txt"] },
Component: NotesTxtPanel,
});
client.addCommandCenterItem({
id: "open-status",
title: "Open status panel",
icon: "PanelsTopLeft",
context: "workspace",
onSelect({ workspaceLayout }) {
workspaceLayout.open({ panelId: "status" });
},
});
client.addCommandCenterItem({
id: "open-explorer-status",
title: "Open explorer status panel",
icon: "PanelsTopLeft",
context: "workspace",
onSelect({ workspaceLayout }) {
workspaceLayout.open({ panelId: "explorer-status" }, { placement: { type: "explorer" } });
},
});
client.addCommandCenterItem({
id: "open-inspector",
title: "Open inspector panel",
icon: "Scan",
context: "agent",
onSelect({ workspaceLayout, agent }) {
workspaceLayout.open({ panelId: "inspector", params: { agentId: agent.id } });
},
});
return () => {};
}
`;
async function runCommand(page: Page, title: string): Promise<void> {
const panel = await openCommandCenter(page);
await panel.getByTestId("command-center-input").fill(title);
await panel.getByRole("button", { name: title, exact: true }).click();
await expect(panel).not.toBeVisible();
}
function mainPane(page: Page): Locator {
return page.locator('[data-testid^="workspace-pane-"]').filter({ visible: true }).first();
}
function explorer(page: Page): Locator {
return page.getByTestId("workspace-explorer-sidebar");
}
function tabChip(scope: Locator, idPart: string): Locator {
return scope
.locator(
`[data-testid^="workspace-tab-"][data-testid*="${idPart}"]:not([data-testid^="workspace-tab-tooltip"]):not([data-testid^="workspace-tab-modified"])`,
)
.first();
}
async function capture(page: Page, testInfo: TestInfo, name: string): Promise<void> {
const screenshot = testInfo.outputPath(`${name}.png`);
await page.screenshot({ path: screenshot });
await testInfo.attach(name, { path: screenshot, contentType: "image/png" });
}
test("PluginTab.setTitle updates and resets tab labels in main pane, Explorer, agent, and file panels", async ({
page,
}, testInfo) => {
test.setTimeout(180_000);
const directory = await mkdtemp(path.join(tmpdir(), "paseo-plugin-tab-set-title-"));
const workspace = await seedMockAgentWorkspace({
repoPrefix: "plugin-tab-set-title-",
title: "Tab Title Agent",
repo: {
files: [{ path: "notes.txt", content: "Sample notes\n" }],
},
});
const client = await connectNewWorkspaceDaemonClient({ ownProjects: false });
const previousConfig = await client.getDaemonConfig();
await writeFile(
path.join(directory, "paseo-plugin.json"),
JSON.stringify({ id: PLUGIN_ID, requirements: pluginRequirements }),
);
await writeFile(path.join(directory, "index.client.tsx"), CLIENT_SOURCE);
try {
await client.patchDaemonConfig({ pluginsEnabled: true });
await client.installDirectoryPlugin(directory);
await page.setViewportSize(WIDE);
await openAgentRoute(page, {
workspaceId: workspace.workspaceId,
agentId: workspace.agentId,
});
await approveClientPluginsInUi(page, [PLUGIN_ID]);
await test.step("main pane workspace panel sets, trims, clears, and resets title + tooltip", async () => {
await runCommand(page, "Open status panel");
const tab = tabChip(mainPane(page), "_status");
await expect(tab).toContainText("Status");
await expect(tab).toHaveAttribute("aria-label", "Status");
await page.getByRole("button", { name: "Set status title", exact: true }).click();
await expect(tab).toContainText("Status (3)");
await expect(tab).toHaveAttribute("aria-label", "Status (3)");
await expect.poll(() => page.title()).toBe("Status (3)");
await tab.hover();
await expect(page.getByText("Status (3)").last()).toBeVisible();
await capture(page, testInfo, "main-pane-title-override");
await page.getByRole("button", { name: "Whitespace status title", exact: true }).click();
await expect(tab).toContainText("Status");
await expect(tab).toHaveAttribute("aria-label", "Status");
await page.getByRole("button", { name: "Set status title", exact: true }).click();
await expect(tab).toContainText("Status (3)");
await page.getByRole("button", { name: "Reset status title", exact: true }).click();
await expect(tab).toContainText("Status");
await expect.poll(() => page.title()).toBe("Status");
});
await test.step("Explorer workspace panel sets and resets title", async () => {
await runCommand(page, "Open explorer status panel");
const explorerTab = tabChip(explorer(page), "explorer-status");
await expect(explorerTab).toContainText("Explorer status");
await expect(explorerTab).toHaveAttribute("aria-label", "Explorer status");
await page.getByRole("button", { name: "Set explorer title", exact: true }).click();
await expect(explorerTab).toContainText("Explorer (7)");
await expect(explorerTab).toHaveAttribute("aria-label", "Explorer (7)");
await capture(page, testInfo, "explorer-title-override");
await page.getByRole("button", { name: "Reset explorer title", exact: true }).click();
await expect(explorerTab).toContainText("Explorer status");
await expect(explorerTab).toHaveAttribute("aria-label", "Explorer status");
});
await test.step("agent panel sets and resets title", async () => {
await mainPane(page).getByTestId(`workspace-tab-agent_${workspace.agentId}`).click();
await runCommand(page, "Open inspector panel");
const agentTab = tabChip(mainPane(page), "inspector");
await expect(agentTab).toContainText("Inspector");
await page.getByRole("button", { name: "Set agent title", exact: true }).click();
await expect(agentTab).toContainText("Inspector: live");
await page.getByRole("button", { name: "Reset agent title", exact: true }).click();
await expect(agentTab).toContainText("Inspector");
});
await test.step("file panel sets and resets title", async () => {
await openFileExplorer(page);
await openFileFromExplorer(page, "notes.txt");
await expect(page.getByText("Open .txt files with", { exact: true })).toBeVisible();
await page.keyboard.press("Escape");
await expect(page.getByText("Open .txt files with", { exact: true })).toBeHidden();
const fileTab = mainPane(page).getByTestId("workspace-tab-file_notes.txt");
await expect(fileTab).toContainText("notes.txt");
await page.getByRole("button", { name: "Set file title", exact: true }).click();
await expect(fileTab).toContainText("Readout");
await expect(fileTab).toHaveAttribute("aria-label", "Readout");
await page.getByRole("button", { name: "Reset file title", exact: true }).click();
await expect(fileTab).toContainText("notes.txt");
await expect(fileTab).toHaveAttribute("aria-label", "notes.txt");
});
await test.step("removing the plugin clears active title override to Plugin unavailable", async () => {
await tabChip(mainPane(page), "_status").click();
await page.getByRole("button", { name: "Set status title", exact: true }).click();
const tab = tabChip(mainPane(page), "_status");
await expect(tab).toContainText("Status (3)");
await client.removePlugin(PLUGIN_ID);
await expect(tab).toContainText("Plugin unavailable", { timeout: 30_000 });
await expect(tab).toHaveAttribute("aria-label", "This plugin panel is unavailable");
});
} finally {
await client.removePlugin(PLUGIN_ID).catch(() => undefined);
await client
.patchDaemonConfig({ pluginsEnabled: previousConfig.config.pluginsEnabled ?? false })
.catch(() => undefined);
await client.close().catch(() => undefined);
await workspace.cleanup().catch(() => undefined);
await rm(directory, { recursive: true, force: true });
}
});
@@ -326,3 +326,537 @@ test("a file a plugin opens in another workspace waits there on a phone", async
});
});
});
const PARAMS_AND_IDENTITY_ENTRY = `import {
type PluginClientContext,
type PluginWorkspacePanelProps,
useTabState,
useWorkspaceLayout,
} from "@getpaseo/plugin/client";
import { Pressable, Text, View } from "react-native";
import { z } from "zod";
const decisionParams = z.object({ decisionId: z.string() });
const decisionStateSchema = z.object({ note: z.string() });
function DecisionsPanel({
params,
revision,
tab,
theme,
}: PluginWorkspacePanelProps<z.infer<typeof decisionParams>>) {
const [state, setState] = useTabState(tab, decisionStateSchema, { note: "initial" });
return (
<View style={{ flex: 1, padding: 16, gap: 8 }}>
<Text style={{ color: theme.colors.foreground }}>
{\`decision:\${params.decisionId}|rev:\${revision}|state:\${state.note}\`}
</Text>
<Pressable
accessibilityRole="button"
onPress={() => setState({ note: "pinned" })}
>
<Text style={{ color: theme.colors.foreground }}>Pin decision state</Text>
</Pressable>
</View>
);
}
const prParams = z.object({
prNumber: z.number(),
commentId: z.string().optional(),
});
function PrPanel({
workspaceId,
params,
revision,
theme,
}: PluginWorkspacePanelProps<z.infer<typeof prParams>>) {
const readBack = useWorkspaceLayout(workspaceId, (layout) => {
const found = layout.tabs.find((entry) => entry.panelId === "workspace-layout/pr" && entry.params.prNumber === params.prNumber);
return found ? JSON.stringify(found.params) : "missing";
});
return (
<View style={{ flex: 1, padding: 16, gap: 8 }}>
<Text style={{ color: theme.colors.foreground }}>
{\`pr:\${params.prNumber}|comment:\${params.commentId ?? "none"}|rev:\${revision}\`}
</Text>
<Text style={{ color: theme.colors.foregroundMuted }}>
{\`readback:\${params.prNumber}:\${readBack}\`}
</Text>
</View>
);
}
function StaticPanel({ theme }: PluginWorkspacePanelProps) {
return (
<View style={{ flex: 1, padding: 16 }}>
<Text style={{ color: theme.colors.foreground }}>Static parameterless panel</Text>
</View>
);
}
export default function contribute(client: PluginClientContext) {
client.addWorkspacePanel({
id: "decisions",
title: "Decisions",
icon: "ListChecks",
locations: ["explorer"],
params: decisionParams,
Component: DecisionsPanel,
});
client.addWorkspacePanel({
id: "pr",
title: "PR",
icon: "GitPullRequest",
params: prParams,
identity: (p) => String(p.prNumber),
Component: PrPanel,
});
client.addWorkspacePanel({
id: "static",
title: "Static",
icon: "Square",
locations: ["workspace", "explorer"],
Component: StaticPanel,
});
client.addCommandCenterItem({
id: "open-decision-d1",
title: "Open decision D1",
icon: "ListChecks",
context: "workspace",
onSelect({ workspaceLayout }) {
workspaceLayout.open({ panelId: "decisions", params: { decisionId: "D1" } });
},
});
client.addCommandCenterItem({
id: "open-decision-d2",
title: "Open decision D2",
icon: "ListChecks",
context: "workspace",
onSelect({ workspaceLayout }) {
workspaceLayout.open({ panelId: "decisions", params: { decisionId: "D2" } });
},
});
client.addCommandCenterItem({
id: "open-pr-1a",
title: "Open PR 1 comment a",
icon: "GitPullRequest",
context: "workspace",
onSelect({ workspaceLayout }) {
workspaceLayout.open({ panelId: "pr", params: { prNumber: 1, commentId: "a" } });
},
});
client.addCommandCenterItem({
id: "open-pr-2x",
title: "Open PR 2 comment x",
icon: "GitPullRequest",
context: "workspace",
onSelect({ workspaceLayout }) {
workspaceLayout.open({ panelId: "pr", params: { prNumber: 2, commentId: "x" } });
},
});
client.addCommandCenterItem({
id: "open-pr-1b",
title: "Open PR 1 comment b",
icon: "GitPullRequest",
context: "workspace",
onSelect({ workspaceLayout }) {
workspaceLayout.open({ panelId: "pr", params: { prNumber: 1, commentId: "b" } });
},
});
return () => {};
}
`;
async function expectNewTabLauncherPanelAvailability(
page: Page,
input: { present: readonly string[]; absent: readonly string[] },
): Promise<void> {
await mainPanes(page).first().getByTestId("workspace-new-tab-button").click();
const menu = page.getByTestId("workspace-new-tab-menu").filter({ visible: true });
for (const label of input.present) {
await expect(menu.getByText(label, { exact: true })).toBeVisible();
}
for (const label of input.absent) {
await expect(menu.getByText(label, { exact: true })).toHaveCount(0);
}
await page.keyboard.press("Escape");
}
async function expectDecisionsPanel(
page: Page,
input: { tabs: number; decisionId: string; revision: number; stateNote: string },
): Promise<void> {
await expect(
explorer(page)
.getByTestId("workspace-tabs-row")
.getByRole("button", { name: "Decisions", exact: true }),
).toHaveCount(input.tabs);
await expect(
explorer(page).getByText(
`decision:${input.decisionId}|rev:${input.revision}|state:${input.stateNote}`,
{ exact: true },
),
).toBeVisible();
}
async function pinDecisionState(page: Page): Promise<void> {
await explorer(page).getByRole("button", { name: "Pin decision state" }).click();
}
async function expectPrPanel(
page: Page,
input: {
tabs: number;
prNumber: number;
commentId: string;
revision: number;
persistedParams?: { prNumber: number; commentId: string };
},
): Promise<void> {
await expect(
mainPanes(page)
.first()
.getByTestId("workspace-tabs-row")
.getByRole("button", { name: "PR", exact: true }),
).toHaveCount(input.tabs);
await expect(
page.getByText(`pr:${input.prNumber}|comment:${input.commentId}|rev:${input.revision}`, {
exact: true,
}),
).toBeVisible();
if (input.persistedParams) {
await expect(
page.getByText(`readback:${input.prNumber}:${JSON.stringify(input.persistedParams)}`, {
exact: true,
}),
).toBeVisible();
}
}
test("reused Explorer panels and keyed workspace panels deliver params, identity, revision, and tab state", async ({
page,
}) => {
test.setTimeout(180_000);
const example = await copyPluginExample("workspace-layout");
await writeFile(path.join(example.directory, "index.client.tsx"), PARAMS_AND_IDENTITY_ENTRY);
const workspace = await seedMockAgentWorkspace({
repoPrefix: "plugin-params-identity-",
title: AGENT_TITLE,
repo: { files: REPO_FILES },
});
try {
await withPluginInstalled(example.directory, async () => {
await page.setViewportSize(WIDE);
await openAgentRoute(page, workspace);
await approveClientPluginsInUi(page, ["workspace-layout"]);
await test.step("parameterless launcher hides panels with required params and keeps parameterless ones", async () => {
await expectNewTabLauncherPanelAvailability(page, {
present: ["Static"],
absent: ["PR", "Decisions"],
});
});
await test.step("reused Explorer panel updates params in place, bumps revision, and preserves tab.state", async () => {
await runCommand(page, "Open decision D1");
await expectDecisionsPanel(page, {
tabs: 1,
decisionId: "D1",
revision: 1,
stateNote: "initial",
});
await pinDecisionState(page);
await expectDecisionsPanel(page, {
tabs: 1,
decisionId: "D1",
revision: 1,
stateNote: "pinned",
});
await runCommand(page, "Open decision D2");
await expectDecisionsPanel(page, {
tabs: 1,
decisionId: "D2",
revision: 2,
stateNote: "pinned",
});
});
await test.step("keyed panel opens separate tabs per identity key and updates hint params on reveal", async () => {
await runCommand(page, "Open PR 1 comment a");
await expectPrPanel(page, { tabs: 1, prNumber: 1, commentId: "a", revision: 1 });
await runCommand(page, "Open PR 2 comment x");
await expectPrPanel(page, { tabs: 2, prNumber: 2, commentId: "x", revision: 1 });
await runCommand(page, "Open PR 1 comment b");
await expectPrPanel(page, {
tabs: 2,
prNumber: 1,
commentId: "b",
revision: 2,
persistedParams: { prNumber: 1, commentId: "b" },
});
});
});
} finally {
await workspace.cleanup();
await example.cleanup();
}
});
const MIN_WIDTH_ENTRY = `import type {
PluginAgentPanelProps,
PluginClientContext,
PluginFilePanelProps,
PluginWorkspacePanelProps,
} from "@getpaseo/plugin/client";
import { Text, View } from "react-native";
function WideWorkspacePanel({ theme }: PluginWorkspacePanelProps) {
return (
<View style={{ flex: 1, padding: 16, backgroundColor: theme.colors.surface0 }}>
<Text style={{ color: theme.colors.foreground }}>Wide workspace panel content</Text>
</View>
);
}
function WideAgentPanel({ theme, params }: PluginAgentPanelProps) {
return (
<View style={{ flex: 1, padding: 16, backgroundColor: theme.colors.surface0 }}>
<Text style={{ color: theme.colors.foreground }}>{\`Wide agent panel \${params.agentId}\`}</Text>
</View>
);
}
function WideSpecFilePanel({ theme, file }: PluginFilePanelProps) {
return (
<View style={{ flex: 1, padding: 16, backgroundColor: theme.colors.surface0 }}>
<Text style={{ color: theme.colors.foreground }}>{\`Wide spec file \${file.name}\`}</Text>
</View>
);
}
export default function contribute(client: PluginClientContext) {
client.addWorkspacePanel({
id: "wide-board",
title: "Wide board",
icon: "PanelsTopLeft",
locations: ["explorer"],
minWidth: 480,
Component: WideWorkspacePanel,
});
client.addAgentPanel({
id: "wide-review",
title: "Wide review",
icon: "Scan",
locations: ["explorer"],
minWidth: 520,
Component: WideAgentPanel,
});
client.addFilePanel({
id: "wide-spec",
title: "Wide spec",
icon: "FileText",
files: { extensions: ["specfile"] },
minWidth: 600,
Component: WideSpecFilePanel,
});
client.addCommandCenterItem({
id: "open-wide-board",
title: "Open wide board",
icon: "PanelsTopLeft",
context: "workspace",
onSelect({ workspaceLayout }) {
workspaceLayout.open({ panelId: "wide-board" }, { placement: { type: "explorer" } });
},
});
client.addCommandCenterItem({
id: "open-wide-review",
title: "Open wide review",
icon: "Scan",
context: "agent",
onSelect({ workspaceLayout, agent }) {
workspaceLayout.open(
{ panelId: "wide-review", params: { agentId: agent.id } },
{ placement: { type: "explorer" } },
);
},
});
client.addCommandCenterItem({
id: "open-wide-spec",
title: "Open wide spec",
icon: "FileText",
context: "workspace",
onSelect({ workspaceLayout }) {
workspaceLayout.open(
{ panelId: "paseo/file", params: { path: "sample.specfile" } },
{ placement: { type: "explorer" } },
);
},
});
return () => {};
}
`;
async function expectExplorerWidth(page: Page, expected: number): Promise<void> {
await expect
.poll(async () => (await explorer(page).boundingBox())?.width)
.toBeCloseTo(expected, 0);
}
async function expectExplorerWidthAtMost(page: Page, max: number): Promise<void> {
await expect
.poll(async () => (await explorer(page).boundingBox())?.width)
.toBeLessThanOrEqual(max);
}
async function dragExplorerHandle(page: Page, deltaX: number): Promise<void> {
const handle = page
.getByTestId("workspace-explorer-sidebar-resize-handle")
.getByRole("separator");
const bounds = await handle.boundingBox();
if (!bounds) throw new Error("Explorer resize handle is missing");
const startX = bounds.x + bounds.width / 2;
const startY = bounds.y + Math.min(100, bounds.height / 2);
await page.mouse.move(startX, startY);
await page.mouse.down();
await page.mouse.move(startX + deltaX, startY, { steps: 10 });
await page.mouse.up();
}
test("plugin panel minWidth widens desktop Explorer non-destructively, respects body minimum, and is ignored on compact", async ({
page,
}) => {
test.setTimeout(180_000);
const example = await copyPluginExample("workspace-layout");
await writeFile(path.join(example.directory, "index.client.tsx"), MIN_WIDTH_ENTRY);
const workspace = await seedMockAgentWorkspace({
repoPrefix: "plugin-min-width-",
title: AGENT_TITLE,
repo: {
files: [...REPO_FILES, { path: "sample.specfile", content: "spec v1\n" }],
},
});
try {
await withPluginInstalled(example.directory, async () => {
await page.setViewportSize({ width: 1440, height: 900 });
await openAgentRoute(page, workspace);
await approveClientPluginsInUi(page, ["workspace-layout"]);
await test.step("workspace panel minWidth: 480 widens Explorer and restores 320px on Files", async () => {
await runCommand(page, "Open wide board");
await expect(
explorer(page).getByText("Wide workspace panel content", { exact: true }),
).toBeVisible();
await expectExplorerWidth(page, 480);
await explorer(page)
.getByRole("button", { name: "Browse workspace files", exact: true })
.click();
await expectExplorerWidth(page, 320);
});
await test.step("agent panel minWidth: 520 and file panel minWidth: 600 widen Explorer and restore 320px", async () => {
await runCommand(page, "Open wide review");
await expect(
explorer(page).getByText(`Wide agent panel ${workspace.agentId}`, { exact: true }),
).toBeVisible();
await expectExplorerWidth(page, 520);
await explorer(page)
.getByRole("button", { name: "Browse workspace files", exact: true })
.click();
await expectExplorerWidth(page, 320);
await runCommand(page, "Open wide spec");
await page.getByRole("button", { name: "Use", exact: true }).click();
await expect(
explorer(page).getByText("Wide spec file sample.specfile", { exact: true }),
).toBeVisible();
await expectExplorerWidth(page, 600);
await explorer(page)
.getByRole("button", { name: "Browse workspace files", exact: true })
.click();
await expectExplorerWidth(page, 320);
});
await test.step("live drag clamps at minWidth and preserves dragged wider width across tabs", async () => {
await runCommand(page, "Open wide board");
await expectExplorerWidth(page, 480);
// Drag narrower -> clamps at 480 and does not overwrite default 320 on Files.
await dragExplorerHandle(page, 120);
await expectExplorerWidth(page, 480);
await explorer(page)
.getByRole("button", { name: "Browse workspace files", exact: true })
.click();
await expectExplorerWidth(page, 320);
// Drag wider to 560 -> persists 560 across Files, and minWidth: 600 still widens to 600.
await runCommand(page, "Open wide board");
await expectExplorerWidth(page, 480);
await dragExplorerHandle(page, -80);
await expectExplorerWidth(page, 560);
await explorer(page)
.getByRole("button", { name: "Browse workspace files", exact: true })
.click();
await expectExplorerWidth(page, 560);
await explorer(page)
.getByTestId("workspace-tabs-row")
.getByRole("button", { name: "sample.specfile", exact: true })
.click();
await expectExplorerWidth(page, 600);
await explorer(page)
.getByRole("button", { name: "Browse workspace files", exact: true })
.click();
await expectExplorerWidth(page, 560);
});
await test.step("narrow desktop viewport keeps at least 360px for the workspace body", async () => {
await explorer(page)
.getByTestId("workspace-tabs-row")
.getByRole("button", { name: "sample.specfile", exact: true })
.click();
await expectExplorerWidth(page, 600);
await page.setViewportSize({ width: 750, height: 900 });
await expectExplorerWidthAtMost(page, 390);
const mainBox = await mainPanes(page).first().boundingBox();
expect(mainBox?.width ?? 0).toBeGreaterThanOrEqual(360);
});
await test.step("compact/mobile viewport ignores minWidth and renders full-width Explorer overlay", async () => {
await page.setViewportSize(COMPACT);
await expect(page.getByTestId("compact-shell")).toBeVisible();
await expectMobileExplorerHidden(page);
await page
.getByTestId("workspace-explorer-toggle")
.filter({ visible: true })
.first()
.click();
await expectMobileExplorerVisible(page);
await explorer(page)
.getByTestId("workspace-tabs-row")
.getByRole("button", { name: "Wide board", exact: true })
.click();
await expect(
explorer(page).getByText("Wide workspace panel content", { exact: true }),
).toBeVisible();
await expectExplorerWidth(page, COMPACT.width);
await closeMobileExplorer(page);
await expectMobileExplorerHidden(page);
});
});
} finally {
await workspace.cleanup();
await example.cleanup();
}
});
@@ -42,17 +42,40 @@ import { useAgent, useWorkspace, openExternalUrl } from "@getpaseo/plugin/client
import { ExternalLink } from "@getpaseo/plugin/client/ui";
import { recordComposerOpen } from "./shared/rpc";
function WorkspacePanel({ workspaceId, host, layout }) {
function WorkspacePanel({ workspaceId, host, layout, openScreen }) {
const workspace = useWorkspace(workspaceId, (value) => ({ id: value.id }));
const renderCount = useRef(0);
renderCount.current += 1;
return <View><Text>Workspace bridge {workspace?.id}</Text><Text>Workspace renders {renderCount.current}</Text><Text>Host {host.id}</Text><Text>Layout {layout.compact ? "compact" : "wide"}</Text></View>;
return <View>
<Text>Workspace bridge {workspace?.id}</Text>
<Text>Workspace renders {renderCount.current}</Text>
<Text>Host {host.id}</Text>
<Text>Layout {layout.compact ? "compact" : "wide"}</Text>
<Pressable accessibilityRole="button" onPress={() => openScreen({ screenId: "details", params: { source: "workspace-panel", item: workspaceId } })}><Text>Open screen from workspace panel</Text></Pressable>
</View>;
}
function AgentPanel({ workspaceId, agentId, host, layout }) {
function AgentPanel({ workspaceId, agentId, host, layout, openScreen }) {
const workspace = useWorkspace(workspaceId, (value) => ({ id: value.id }));
const agent = useAgent(agentId, (value) => ({ id: value.id }));
return <View><Text>Agent bridge {agent?.id}</Text><Text>Workspace {workspace?.id}</Text><Text>Host {host.id}</Text><Text>Layout {layout.compact ? "compact" : "wide"}</Text></View>;
return <View>
<Text>Agent bridge {agent?.id}</Text>
<Text>Workspace {workspace?.id}</Text>
<Text>Host {host.id}</Text>
<Text>Layout {layout.compact ? "compact" : "wide"}</Text>
<Pressable accessibilityRole="button" onPress={() => openScreen({ screenId: "details", params: { source: "agent-panel", item: agentId } })}><Text>Open screen from agent panel</Text></Pressable>
</View>;
}
function DetailsScreen({ params, openScreen }) {
return <View>
<Text>{"Details screen: " + params.source + " / " + params.item}</Text>
<Pressable accessibilityRole="button" onPress={() => openScreen({ screenId: "chained", params: { from: params.source ?? "" } })}><Text>Open chained screen</Text></Pressable>
</View>;
}
function ChainedScreen({ params }) {
return <View><Text>{"Chained screen from " + params.from}</Text></View>;
}
function DirectCollisionSurface({ navigation }) {
@@ -127,6 +150,8 @@ function contributeClient(client) {
}
export default function contribute(client) {
client.addScreen({ id: "details", title: (params) => "Details: " + (params.source ?? ""), Component: DetailsScreen });
client.addScreen({ id: "chained", title: "Chained", Component: ChainedScreen });
client.addSurface("collision", DirectCollisionSurface);
client.addSurface("sidebar-destination", SidebarCollisionSurface);
client.addSidebarItem({ id: "collision", title: "Collision sidebar", icon: "Blocks", surface: "sidebar-destination" });
@@ -252,6 +277,34 @@ async function openCompactSidebar(page: Page): Promise<void> {
await expect(page.getByTestId("sidebar-search")).toBeVisible();
}
async function openPluginScreenFromButton(
page: Page,
input: {
buttonName: string;
screenId: string;
params: Record<string, string>;
expectedText: string;
},
): Promise<void> {
await page.getByRole("button", { name: input.buttonName, exact: true }).click();
const query = Object.entries(input.params)
.map(([key, value]) => `${encodeURIComponent(`param.${key}`)}=${encodeURIComponent(value)}`)
.join("&");
await expect(page).toHaveURL(
new RegExp(`/plugin/${PLUGIN_ID}/surface/${input.screenId}\\?${query.replaceAll(".", "\\.")}$`),
);
await expect(page.getByText(input.expectedText, { exact: true })).toBeVisible();
}
async function closeTopPluginScreen(
page: Page,
options: { compact?: boolean; expectedText: string },
): Promise<void> {
const testId = options.compact ? "header-back-button" : "plugin-surface-close";
await page.getByTestId(testId).filter({ visible: true }).last().click();
await expect(page.getByText(options.expectedText, { exact: true })).toBeVisible();
}
async function capture(page: Page, testInfo: TestInfo, name: string): Promise<void> {
const screenshot = testInfo.outputPath(`${name}.png`);
await page.screenshot({ path: screenshot });
@@ -338,6 +391,24 @@ test.describe("plugin workspace panels and Command Center", () => {
await expect(page.getByText(`Host ${getServerId()}`, { exact: true })).toBeVisible();
await expect(page.getByText("Layout wide", { exact: true })).toBeVisible();
await capture(page, testInfo, "plugin-workspace-panel-wide");
await openPluginScreenFromButton(page, {
buttonName: "Open screen from workspace panel",
screenId: "details",
params: { source: "workspace-panel", item: primary.workspaceId },
expectedText: `Details screen: workspace-panel / ${primary.workspaceId}`,
});
await openPluginScreenFromButton(page, {
buttonName: "Open chained screen",
screenId: "chained",
params: { from: "workspace-panel" },
expectedText: "Chained screen from workspace-panel",
});
await closeTopPluginScreen(page, {
expectedText: `Details screen: workspace-panel / ${primary.workspaceId}`,
});
await closeTopPluginScreen(page, {
expectedText: `Workspace bridge ${primary.workspaceId}`,
});
});
await test.step("plugin links open browser tabs and in-app browsing is unavailable", async () => {
@@ -475,6 +546,16 @@ test.describe("plugin workspace panels and Command Center", () => {
).toBeVisible();
await expect(page.getByText(`Host ${getServerId()}`, { exact: true })).toBeVisible();
await expect(page.getByText("Layout compact", { exact: true })).toBeVisible();
await openPluginScreenFromButton(page, {
buttonName: "Open screen from agent panel",
screenId: "details",
params: { source: "agent-panel", item: agent.id },
expectedText: `Details screen: agent-panel / ${agent.id}`,
});
await closeTopPluginScreen(page, {
compact: true,
expectedText: `Agent bridge ${agent.id}`,
});
});
await test.step("removing the active plugin renders the panel unavailable", async () => {
@@ -0,0 +1,171 @@
import { mkdir, mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import type { Locator, Page } from "@playwright/test";
import { expect, test } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { connectSeedClient } from "../support/helpers/seed-client";
import {
closeSidebarDisplayPreferences,
openSidebarProjectFilter,
} from "../support/helpers/sidebar";
const PROJECT_COUNT = 36;
const LAST_PROJECT_NAME = `Project ${String(PROJECT_COUNT - 1).padStart(2, "0")}`;
interface SeededProjects {
cleanup(): Promise<void>;
}
/**
* Adds enough projects to overflow the display-preferences popover. Each project
* owns its own directory under one temporary parent, removed with the daemon
* records in `cleanup`.
*/
async function seedManyProjects(): Promise<SeededProjects> {
const parentDirectory = await mkdtemp(path.join(tmpdir(), "paseo-e2e-project-filter-"));
const client = await connectSeedClient();
try {
const directoryPaths = Array.from({ length: PROJECT_COUNT }, (_, index) =>
path.join(parentDirectory, `Project ${String(index).padStart(2, "0")}`),
);
await Promise.all(directoryPaths.map((directoryPath) => mkdir(directoryPath)));
const addedProjectIds = await Promise.all(
directoryPaths.map(async (directoryPath) => {
const added = await client.addProject(directoryPath);
if (!added.project) throw new Error(`The daemon did not add ${directoryPath}`);
return added.project.projectId;
}),
);
return {
cleanup: async () => {
await Promise.all(
addedProjectIds.map((projectId) =>
client.removeProject(projectId).catch(() => undefined),
),
);
await client.close().catch(() => undefined);
await rm(parentDirectory, { recursive: true, force: true }).catch(() => undefined);
},
};
} catch (error) {
await client.close().catch(() => undefined);
await rm(parentDirectory, { recursive: true, force: true }).catch(() => undefined);
throw error;
}
}
function projectFilterFlyout(page: Page): Locator {
return page.getByTestId("sidebar-display-preferences-content-projectFilter");
}
function viewportHeight(page: Page): number {
const viewport = page.viewportSize();
if (!viewport) throw new Error("The page has no viewport");
return viewport.height;
}
async function openProjectFilter(page: Page): Promise<Locator> {
await gotoAppShell(page);
await expect(page.getByTestId("sidebar-display-preferences-menu")).toBeVisible({
timeout: 30_000,
});
await openSidebarProjectFilter(page);
const flyout = projectFilterFlyout(page);
await expect(flyout).toBeVisible();
// The flyout paints off-screen until it has measured its anchor and content.
await expect.poll(async () => (await flyout.boundingBox())?.y ?? -9999).toBeGreaterThan(0);
return flyout;
}
async function requireBox(locator: Locator): Promise<{ y: number; height: number }> {
const box = await locator.boundingBox();
if (!box) throw new Error(`${locator.toString()} has no box`);
return box;
}
/** The flyout must sit entirely inside the window, not run past its bottom edge. */
async function expectProjectFilterInsideWindow(flyout: Locator, height: number): Promise<void> {
await expect(async () => {
const box = await requireBox(flyout);
expect(box.y).toBeGreaterThanOrEqual(0);
expect(box.y + box.height).toBeLessThanOrEqual(height);
expect(box.height).toBeLessThan(height);
}).toPass({ timeout: 10_000 });
}
/** The row exists in the list but starts below the visible window. */
async function expectBelowWindow(row: Locator, height: number): Promise<void> {
const box = await requireBox(row);
expect(box.y).toBeGreaterThan(height);
}
/** The row is reachable inside the flyout's viewport after scrolling. */
async function expectInsideFlyout(flyout: Locator, row: Locator): Promise<void> {
const surface = await requireBox(flyout);
const box = await requireBox(row);
expect(box.y).toBeGreaterThanOrEqual(surface.y);
expect(box.y + box.height).toBeLessThanOrEqual(surface.y + surface.height + 1);
}
function scrollTopOf(flyout: Locator): Promise<number | null> {
return flyout.evaluate((root) => {
const candidates = [root, ...Array.from(root.querySelectorAll<HTMLElement>("*"))];
const found = candidates.find((candidate) => {
const overflowY = getComputedStyle(candidate).overflowY;
return (
(overflowY === "auto" || overflowY === "scroll") &&
candidate.scrollHeight > candidate.clientHeight + 1
);
});
return found ? found.scrollTop : null;
});
}
/** Drives the flyout with the mouse wheel until the target row lands inside its viewport. */
async function scrollToLastProject(page: Page, flyout: Locator, lastRow: Locator): Promise<void> {
await flyout.hover();
await expect(async () => {
await page.mouse.wheel(0, 2_000);
const surface = await requireBox(flyout);
const row = await requireBox(lastRow);
expect(row.y).toBeGreaterThanOrEqual(surface.y);
expect(row.y + row.height).toBeLessThanOrEqual(surface.y + surface.height + 1);
expect(await scrollTopOf(flyout)).toBeGreaterThan(0);
}).toPass({ timeout: 10_000 });
}
// #9182: with more projects than fit in the window, the project filter grew past
// the bottom edge and had no scroll container, so the rows below the fold could
// not be reached or toggled.
test("the project filter stays inside the window and scrolls to its last row", async ({ page }) => {
const projects = await seedManyProjects();
try {
await page.setViewportSize({ width: 1280, height: 720 });
const flyout = await openProjectFilter(page);
const lastRow = flyout.getByText(LAST_PROJECT_NAME, { exact: true });
await test.step("the flyout fits inside the window while the last project starts below it", async () => {
const height = viewportHeight(page);
await expectProjectFilterInsideWindow(flyout, height);
await expectBelowWindow(lastRow, height);
});
await test.step("mouse wheel scrolling reaches the last project inside the flyout", async () => {
await scrollToLastProject(page, flyout, lastRow);
await expectInsideFlyout(flyout, lastRow);
});
await test.step("shrinking the window keeps the flyout inside the viewport and scrollable", async () => {
await page.setViewportSize({ width: 1280, height: 540 });
await expectProjectFilterInsideWindow(flyout, viewportHeight(page));
await scrollToLastProject(page, flyout, lastRow);
await expectInsideFlyout(flyout, lastRow);
await closeSidebarDisplayPreferences(page);
});
} finally {
await projects.cleanup();
}
});
@@ -0,0 +1,59 @@
import assert from "node:assert/strict";
import { readFileSync, writeFileSync } from "node:fs";
import { PNG } from "pngjs";
// Generate resolution-chart.png in an Android test workspace with the "fixture" command.
// Open it from Files on a 1080 x 2400 emulator, pinch out by 4x at (540, 1250),
// then pass the zoomed screenshot from adb exec-out screencap -p to the "check" command.
// Generate a 6,000 x 5,000 PNG with "fixture-large" to exercise Android's bitmap size
// limit. Open it from Files at fit and pass the screenshot to the same "check" command.
// Pass the width and height from Expo Image's onLoad event to "check-decode" on an
// emulator with the default 100 MiB canvas limit.
const [command, path, height] = process.argv.slice(2);
assert.ok(
path && ["fixture", "fixture-large", "check", "check-decode"].includes(command),
"Use fixture <png>, fixture-large <png>, check <png>, or check-decode <width> <height>",
);
if (command === "check-decode") {
const width = Number(path);
const decodedHeight = Number(height);
assert.ok(width > 0 && decodedHeight > 0, "Provide the positive decoded dimensions");
assert.ok(
width * decodedHeight * 4 <= 100 * 1024 * 1024,
`Decoded bitmap exceeds 100 MiB at ${width} × ${decodedHeight}`,
);
} else if (command === "fixture" || command === "fixture-large") {
const size =
command === "fixture-large" ? { width: 6000, height: 5000 } : { width: 4000, height: 3000 };
const chart = new PNG(size);
const stripeWidth = command === "fixture-large" ? 240 : 3;
for (let x = 0; x < chart.width; x++) {
const shade = Math.floor(x / stripeWidth) % 2 === 0 ? 0 : 255;
chart.data.set([shade, shade, shade, 255], x * 4);
}
for (let y = 1; y < chart.height; y++) {
chart.data.copy(chart.data, y * chart.width * 4, 0, chart.width * 4);
}
writeFileSync(path, PNG.sync.write(chart));
} else {
const screenshot = PNG.sync.read(readFileSync(path));
assert.equal(screenshot.width, 1080, "Use a 1080 x 2400 emulator");
assert.equal(screenshot.height, 2400, "Use a 1080 x 2400 emulator");
// The center of each stripe should be nearly black or white. Antialiased edges
// may stay gray, so sample a wide span and allow for those pixels.
const row = 1200;
let dark = 0;
let light = 0;
for (let x = 340; x < 740; x++) {
const shade = screenshot.data[(row * screenshot.width + x) * 4];
if (shade < 35) dark++;
if (shade > 220) light++;
}
assert.ok(
dark >= 80 && light >= 80,
`Fine stripes lost contrast (${dark} dark, ${light} light pixels)`,
);
}
@@ -55,6 +55,7 @@ interface HeldServerMessage {
interface PendingServerMessageHold {
matches: (message: ClientRequest | null) => boolean;
blockAgentStreamFollowers?: boolean;
keepHolding?: boolean;
}
function readSessionMessage(message: string | Buffer): ClientRequest | null {
@@ -412,7 +413,7 @@ export async function installDaemonWebSocketGate(page: Page, options: { port?: n
);
if (!matchedHold) return suppressed;
const [key, hold] = matchedHold;
pendingServerMessageHolds.delete(key);
if (!hold.keepHolding) pendingServerMessageHolds.delete(key);
heldServerMessages.push({
browser: input.browser,
message: input.message,
@@ -550,6 +551,23 @@ export async function installDaemonWebSocketGate(page: Page, options: { port?: n
});
});
const sendHeldServerMessage = (heldServerMessage: HeldServerMessage): void => {
heldServerMessage.browser.send(heldServerMessage.message);
for (const follower of heldServerMessage.agentStreamFollowers) {
heldServerMessage.browser.send(follower);
}
};
const releaseFirstHeldMessage = (
predicate: (message: HeldServerMessage) => boolean,
errorMessage: string,
): void => {
const index = heldServerMessages.findIndex(predicate);
const [heldServerMessage] = index >= 0 ? heldServerMessages.splice(index, 1) : [];
if (!heldServerMessage) throw new Error(errorMessage);
sendHeldServerMessage(heldServerMessage);
};
return {
waitForFileSubscription(path: string): Promise<void> {
if (subscribedFilePaths.has(path)) return Promise.resolve();
@@ -661,6 +679,13 @@ export async function installDaemonWebSocketGate(page: Page, options: { port?: n
matches: (message) => matchesAgentUpdate(message, heldAgentUpdate),
});
},
holdAgentUpdates(agentId: string, status: string): void {
const heldAgentUpdate = { agentId, status };
pendingServerMessageHolds.set(agentUpdateKey(agentId, status), {
matches: (message) => matchesAgentUpdate(message, heldAgentUpdate),
keepHolding: true,
});
},
holdNextAgentStreamEvent(type: string): void {
pendingServerMessageHolds.set(agentStreamEventKey(type), {
matches: (message) => readAgentStreamEventType(message) === type,
@@ -690,13 +715,10 @@ export async function installDaemonWebSocketGate(page: Page, options: { port?: n
},
releaseHeldServerMessage(type?: string): void {
const key = type ? serverMessageKey(type) : null;
const index = heldServerMessages.findIndex((message) => key === null || message.key === key);
const [heldServerMessage] = index >= 0 ? heldServerMessages.splice(index, 1) : [];
if (!heldServerMessage) throw new Error("No held server message to release");
heldServerMessage.browser.send(heldServerMessage.message);
for (const follower of heldServerMessage.agentStreamFollowers) {
heldServerMessage.browser.send(follower);
}
releaseFirstHeldMessage(
(message) => key === null || message.key === key,
"No held server message to release",
);
},
async waitForHeldAgentUpdate(agentId: string, status: string): Promise<void> {
const key = agentUpdateKey(agentId, status);
@@ -706,12 +728,20 @@ export async function installDaemonWebSocketGate(page: Page, options: { port?: n
},
releaseHeldAgentUpdate(agentId: string, status: string): void {
const key = agentUpdateKey(agentId, status);
const index = heldServerMessages.findIndex((message) => message.key === key);
const [heldServerMessage] = index >= 0 ? heldServerMessages.splice(index, 1) : [];
if (!heldServerMessage) throw new Error("No held agent update to release");
heldServerMessage.browser.send(heldServerMessage.message);
for (const follower of heldServerMessage.agentStreamFollowers) {
heldServerMessage.browser.send(follower);
releaseFirstHeldMessage((message) => message.key === key, "No held agent update to release");
},
releaseHeldAgentUpdates(agentId: string, status: string): void {
const key = agentUpdateKey(agentId, status);
pendingServerMessageHolds.delete(key);
const matching: HeldServerMessage[] = [];
for (let index = heldServerMessages.length - 1; index >= 0; index -= 1) {
if (heldServerMessages[index]?.key === key) {
matching.unshift(...heldServerMessages.splice(index, 1));
}
}
if (matching.length === 0) throw new Error("No held agent update to release");
for (const heldServerMessage of matching) {
sendHeldServerMessage(heldServerMessage);
}
},
async waitForHeldAgentStreamEvent(type: string): Promise<void> {
@@ -722,13 +752,10 @@ export async function installDaemonWebSocketGate(page: Page, options: { port?: n
},
releaseHeldAgentStreamEvent(type: string): void {
const key = agentStreamEventKey(type);
const index = heldServerMessages.findIndex((message) => message.key === key);
const [heldServerMessage] = index >= 0 ? heldServerMessages.splice(index, 1) : [];
if (!heldServerMessage) throw new Error("No held agent stream event to release");
heldServerMessage.browser.send(heldServerMessage.message);
for (const follower of heldServerMessage.agentStreamFollowers) {
heldServerMessage.browser.send(follower);
}
releaseFirstHeldMessage(
(message) => message.key === key,
"No held agent stream event to release",
);
},
async waitForHeldAgentStreamItem(type: string): Promise<void> {
const key = agentStreamItemKey(type);
@@ -738,13 +765,10 @@ export async function installDaemonWebSocketGate(page: Page, options: { port?: n
},
releaseHeldAgentStreamItem(type: string): void {
const key = agentStreamItemKey(type);
const index = heldServerMessages.findIndex((message) => message.key === key);
const [heldServerMessage] = index >= 0 ? heldServerMessages.splice(index, 1) : [];
if (!heldServerMessage) throw new Error("No held agent stream item to release");
heldServerMessage.browser.send(heldServerMessage.message);
for (const follower of heldServerMessage.agentStreamFollowers) {
heldServerMessage.browser.send(follower);
}
releaseFirstHeldMessage(
(message) => message.key === key,
"No held agent stream item to release",
);
},
requestTimelineTail(agentId: string): void {
if (!latestServer) throw new Error("No daemon WebSocket is connected");
@@ -52,7 +52,7 @@ function Details({ workspaceId, theme, layout, close }) {
const rpc = useRpc(summary);
const query = useQuery({ queryKey: ["summary"], queryFn: () => rpc({}) });
if (failed) throw new Error("Button content failed");
return <View style={{ gap: 12 }}>
return <View style={{ padding: 12, gap: 12 }}>
<Text accessibilityLabel="Content observation" style={{ color: theme.colors.foreground }}>{ownerId}</Text>
<Text style={{ color: theme.colors.foreground }}>Observed updates: {updates}</Text>
<Pressable accessibilityRole="button" accessibilityLabel="Fail button content" onPress={() => setFailed(true)}><Text style={{ color: theme.colors.foreground }}>Fail content</Text></Pressable>
@@ -59,7 +59,7 @@ function DeploysItem({ theme, currentScreen, openScreen }) {
function SyncDetails({ theme, layout, close, openScreen }) {
return (
<View style={{ gap: 8 }}>
<View style={{ padding: 12, gap: 8 }}>
<Text style={{ color: theme.colors.foreground }}>Sync details</Text>
<Text style={{ color: theme.colors.foregroundMuted }}>Presentation: {layout.compact ? "compact" : "wide"}</Text>
<Pressable accessibilityRole="button" accessibilityLabel="Open deploys from popover" onPress={() => openScreen({ screenId: "deploys" })}><Text style={{ color: theme.colors.foreground }}>Open deploys</Text></Pressable>
@@ -124,7 +124,7 @@ const botMenus = {};
function botMenu(bot) {
botMenus[bot.id] ??= function BotMenu({ theme, close }) {
return (
<View style={{ gap: 8 }}>
<View style={{ padding: 12, gap: 8 }}>
<Text style={{ color: theme.colors.foreground }}>{bot.name + " options"}</Text>
<Pressable accessibilityRole="button" accessibilityLabel={"Close " + bot.name + " options"} onPress={close}><Text style={{ color: theme.colors.foreground }}>Done</Text></Pressable>
</View>
@@ -143,7 +143,7 @@ function MoreButton({ theme, bot, onPress }) {
function BotStatus({ theme, close }) {
return (
<View style={{ gap: 8 }}>
<View style={{ padding: 12, gap: 8 }}>
<Text style={{ color: theme.colors.foreground }}>Bot status details</Text>
<Pressable accessibilityRole="button" accessibilityLabel="Close bot status" onPress={close}><Text style={{ color: theme.colors.foreground }}>Done</Text></Pressable>
</View>
@@ -948,3 +948,46 @@ it.each([false, true])(
expect(opened.groupsByHostId.size).toBe(0);
},
);
it("folds a completed turn whose plugin replaces every tool and reasoning row", () => {
const present = createStreamPresentation();
const timestamp = new Date();
const tail: StreamItem[] = [
{ kind: "user_message", id: "prompt", text: "Work", timestamp },
{ kind: "thought", id: "reasoning", text: "Plan", status: "ready", timestamp },
toolCall("one", "Bash"),
{ kind: "assistant_message", id: "reply", text: "Done", timestamp },
];
const toolPlugin = installedTransform(installProbe("tool_call"));
const reasoningPlugin = installedTransform(installProbe("reasoning"));
const input = {
...presentationOptions,
tail,
head: [],
display: "collapseTurns" as const,
isTurnActive: false,
};
const transform: TimelineItemTransform = (item) =>
toolPlugin(item)?.flatMap((card) => [card, { ...card, id: `${card.id}/detail` }]) ??
reasoningPlugin(item);
const control = present({ ...input, transform: undefined });
expect(control.tail.map((item) => item.kind)).toEqual([
"user_message",
"turn_summary",
"assistant_message",
]);
const closed = present({ ...input, transform });
expect(closed.tail.map((item) => item.kind)).toEqual(control.tail.map((item) => item.kind));
expect(closed.turns.summaryRowsByHostId.get("prompt")?.tools).toEqual(
control.turns.summaryRowsByHostId.get("prompt")?.tools,
);
const opened = present({ ...input, transform, expandedTurnHostIds: new Set(["prompt"]) });
expect(opened.tail.map((item) => item.kind)).toEqual([
"user_message",
"turn_summary",
"plugin",
"plugin",
"plugin",
"assistant_message",
]);
});
@@ -45,9 +45,14 @@ function summarizeTurn(
getGroupedCalls: CollapseTurnsInput["getGroupedCalls"],
): OverviewSummary {
const calls: (ToolCallItem | ThoughtItem)[] = [];
const countedSources = new Set<string>();
for (const item of items) {
if ((item.kind === "tool_call" || item.kind === "thought") && !isTurnTrigger(item))
calls.push(...(getGroupedCalls(item.id) ?? [item]));
const source = item.kind === "plugin" ? item.source : item;
if (!source || (source.kind !== "tool_call" && source.kind !== "thought")) continue;
if (isTurnTrigger(source) || countedSources.has(source.id)) continue;
// One source tool call can render as several plugin cards.
countedSources.add(source.id);
calls.push(...(getGroupedCalls(source.id) ?? [source]));
}
return summarizeToolCalls(calls);
}
+69 -43
View File
@@ -1,5 +1,8 @@
import type { UploadedFileAttachment } from "@getpaseo/protocol/messages";
import { collectRetainedAttachmentIds } from "@/attachments/gc-retention";
import {
collectRetainedAttachmentIds,
retainAttachmentForGarbageCollection,
} from "@/attachments/gc-retention";
import { getAttachmentStore } from "@/attachments/store";
import type { AttachmentMetadata, SaveAttachmentInput } from "@/attachments/types";
import { FILE_UPLOAD_MAX_BYTES } from "@/attachments/upload-limit";
@@ -95,6 +98,25 @@ export async function persistAttachmentFromFileUri(input: {
});
}
export async function withRetainedAttachments<T>(
attachments: readonly AttachmentMetadata[] | undefined,
run: () => Promise<T>,
): Promise<T> {
if (!attachments || attachments.length === 0) {
return await run();
}
const releases = attachments.map((attachment) =>
retainAttachmentForGarbageCollection(attachment.id),
);
try {
return await run();
} finally {
for (const release of releases) {
release();
}
}
}
export async function encodeAttachmentsForSend(
attachments: readonly AttachmentMetadata[] | undefined,
): Promise<Array<{ data: string; mimeType: string }> | undefined> {
@@ -102,29 +124,31 @@ export async function encodeAttachmentsForSend(
return undefined;
}
const store = await getAttachmentStore();
const encoded = await Promise.all(
attachments.map(async (attachment) => {
try {
const data = await store.encodeBase64({ attachment });
return {
data,
mimeType: attachment.mimeType,
};
} catch (error) {
console.error("[attachments] Failed to encode attachment for send", {
id: attachment.id,
error,
});
return null;
}
}),
);
return await withRetainedAttachments(attachments, async () => {
const store = await getAttachmentStore();
const encoded = await Promise.all(
attachments.map(async (attachment) => {
try {
const data = await store.encodeBase64({ attachment });
return {
data,
mimeType: attachment.mimeType,
};
} catch (error) {
console.error("[attachments] Failed to encode attachment for send", {
id: attachment.id,
error,
});
return null;
}
}),
);
const valid = encoded.filter(
(entry): entry is { data: string; mimeType: string } => entry !== null,
);
return valid.length > 0 ? valid : undefined;
const valid = encoded.filter(
(entry): entry is { data: string; mimeType: string } => entry !== null,
);
return valid.length > 0 ? valid : undefined;
});
}
const DEFAULT_UPLOAD_EXTENSION_BY_MIME: Record<string, string> = {
@@ -180,28 +204,30 @@ export async function uploadImageAttachments(input: {
return undefined;
}
const uploaded: UploadedFileAttachment[] = [];
for (const attachment of input.images) {
const fileName = resolveUploadedImageFileName(attachment);
const bytes = await readAttachmentBytes(attachment);
if (bytes.byteLength > FILE_UPLOAD_MAX_BYTES) {
throw new Error(i18n.t("composer.errors.fileTooLarge", { size: "50MB", fileName }));
return await withRetainedAttachments(input.images, async () => {
const uploaded: UploadedFileAttachment[] = [];
for (const attachment of input.images ?? []) {
const fileName = resolveUploadedImageFileName(attachment);
const bytes = await readAttachmentBytes(attachment);
if (bytes.byteLength > FILE_UPLOAD_MAX_BYTES) {
throw new Error(i18n.t("composer.errors.fileTooLarge", { size: "50MB", fileName }));
}
const response = await input.client.uploadFile({
fileName,
mimeType: attachment.mimeType,
bytes,
});
if (response.error || !response.file) {
throw new Error(response.error ?? "Upload failed.");
}
uploaded.push({
...response.file,
role: "image",
});
}
const response = await input.client.uploadFile({
fileName,
mimeType: attachment.mimeType,
bytes,
});
if (response.error || !response.file) {
throw new Error(response.error ?? "Upload failed.");
}
uploaded.push({
...response.file,
role: "image",
});
}
return uploaded;
return uploaded;
});
}
/**
@@ -602,7 +602,7 @@ const ResultRow = memo(function ResultRow({
active ||
state.pressed ||
Boolean((state as PressableStateCallbackType & { hovered?: boolean }).hovered)
? "surface1"
? "surfaceSelected"
: "surface0"
}
/>
@@ -1202,7 +1202,7 @@ const styles = StyleSheet.create((theme) => ({
backgroundColor: theme.colors.border,
},
row: { paddingHorizontal: theme.spacing[4], justifyContent: "center" },
activeRow: { backgroundColor: theme.colors.surface1 },
activeRow: { backgroundColor: theme.colors.surfaceSelected },
rowContent: {
flexDirection: "row",
alignItems: "center",
@@ -25,7 +25,7 @@ import {
} from "@/components/ui/isolated-bottom-sheet-modal";
import { ScrollView } from "@/components/ui/scroll-view";
import { isWeb } from "@/constants/platform";
import { SafeAreaInsetsContext, useSafeAreaInsets } from "react-native-safe-area-context";
import { BottomSafeAreaInset } from "@/components/ui/bottom-safe-area-inset";
import type { EditingTextInputHandle } from "@/components/ui/text-input";
import { AdaptiveTextInput } from "@/components/adaptive-text-input";
import { useDismissibleOverlay } from "@/components/ui/overlay-dismissal";
@@ -336,17 +336,8 @@ export function SheetDragArea({ children }: { children: ReactNode }) {
* navigation inset: it pads it once and tells its content none is left, so content that pads the
* inset itself, like the composer dock, sits the same in a sheet as in a tab.
*/
export function SheetBottomInset({ style, children, ...props }: ViewProps) {
const insets = useSafeAreaInsets();
const contentInsets = useMemo(() => ({ ...insets, bottom: 0 }), [insets]);
const insetStyle = useMemo(() => [style, { paddingBottom: insets.bottom }], [style, insets]);
return (
<View {...props} style={insetStyle}>
<SafeAreaInsetsContext.Provider value={contentInsets}>
{children}
</SafeAreaInsetsContext.Provider>
</View>
);
export function SheetBottomInset(props: ViewProps) {
return <BottomSafeAreaInset {...props} />;
}
/**
+3 -3
View File
@@ -623,13 +623,13 @@ const styles = StyleSheet.create((theme) => ({
marginLeft: theme.spacing[2],
},
rowSelected: {
backgroundColor: theme.colors.surface2,
backgroundColor: theme.colors.surfaceSelected,
},
rowHovered: {
backgroundColor: theme.colors.surface1,
backgroundColor: theme.colors.surfaceHover,
},
rowPressed: {
backgroundColor: theme.colors.surface2,
backgroundColor: theme.colors.surfaceSelected,
},
sessionTitle: {
flexShrink: 1,
@@ -46,6 +46,7 @@ const DRAG_OVERLAY_STYLE: React.CSSProperties = {
const TOP_RESIZER_STYLE: React.CSSProperties = {
position: "absolute",
top: 0,
left: 0,
width: "100%",
height: 4,
// @ts-expect-error — WebkitAppRegion is not in CSSProperties
@@ -25,6 +25,43 @@ describe("Explorer sidebar layout", () => {
expect(resolveExplorerSidebarWidth({ requestedWidth: 600, containerWidth: 750 })).toBe(390);
});
it("applies panel minWidth as a non-destructive floor capped by workspace body minimum", () => {
// Widens default 320px to 480px
expect(resolveExplorerSidebarWidth({ containerWidth: 1200, minWidth: 480 })).toBe(480);
expect(
resolveExplorerSidebarWidth({ requestedWidth: 320, containerWidth: 1200, minWidth: 480 }),
).toBe(480);
// Preserves wider user-saved width
expect(
resolveExplorerSidebarWidth({ requestedWidth: 560, containerWidth: 1200, minWidth: 480 }),
).toBe(560);
// Caps at containerWidth - 360 on narrow windows
expect(
resolveExplorerSidebarWidth({ requestedWidth: 320, containerWidth: 750, minWidth: 480 }),
).toBe(390);
expect(
resolveExplorerSidebarWidth({ requestedWidth: 320, containerWidth: 500, minWidth: 480 }),
).toBe(240);
// Omitted or <= 240 leaves behavior identical
expect(
resolveExplorerSidebarWidth({
requestedWidth: 320,
containerWidth: 1200,
minWidth: undefined,
}),
).toBe(320);
expect(
resolveExplorerSidebarWidth({ requestedWidth: 320, containerWidth: 1200, minWidth: 200 }),
).toBe(320);
expect(
resolveExplorerSidebarWidth({ requestedWidth: 100, containerWidth: 1200, minWidth: 240 }),
).toBe(240);
// Dock sizes honor minWidth
const dockSizes = resolveExplorerSidebarDockSizes({ containerWidth: 1200, minWidth: 480 });
expect(dockSizes[1] * 1200).toBeCloseTo(480);
expect(dockSizes[0] * 1200).toBeCloseTo(720);
});
describe("native resize ownership", () => {
const allocation = {
width: 320,
@@ -6,14 +6,20 @@ export const EXPLORER_WORKSPACE_MIN_WIDTH = MIN_EXPLORER_SIDEBAR_WIDTH + MIN_WOR
export function resolveExplorerSidebarWidth(input: {
requestedWidth?: number;
containerWidth: number;
minWidth?: number;
}): number {
"worklet";
const requestedWidth = input.requestedWidth ?? DEFAULT_EXPLORER_SIDEBAR_WIDTH;
const effectiveMinWidth =
input.minWidth !== undefined && Number.isFinite(input.minWidth) && input.minWidth > 0
? Math.max(MIN_EXPLORER_SIDEBAR_WIDTH, input.minWidth)
: MIN_EXPLORER_SIDEBAR_WIDTH;
const maximumVisibleWidth =
input.containerWidth > 0
? Math.max(MIN_EXPLORER_SIDEBAR_WIDTH, input.containerWidth - MIN_WORKSPACE_BODY_WIDTH)
: requestedWidth;
return Math.max(MIN_EXPLORER_SIDEBAR_WIDTH, Math.min(maximumVisibleWidth, requestedWidth));
: Math.max(effectiveMinWidth, requestedWidth);
const clampedMinWidth = Math.min(maximumVisibleWidth, effectiveMinWidth);
return Math.max(clampedMinWidth, Math.min(maximumVisibleWidth, requestedWidth));
}
// A release keeps its UI width until React acknowledges it or replaces its allocation.
@@ -98,6 +104,7 @@ export function resolveExplorerSidebarFrameWidth(
export function resolveExplorerSidebarDockSizes(input: {
requestedWidth?: number;
containerWidth: number;
minWidth?: number;
}): number[] {
if (input.containerWidth <= 0) {
return [1, 0];
@@ -429,7 +429,7 @@ const styles = StyleSheet.create((theme) => ({
borderRadius: theme.borderRadius.md,
},
rowHighlighted: {
backgroundColor: theme.colors.surface1,
backgroundColor: theme.colors.surfaceSelected,
},
hostBody: {
flex: 1,
@@ -1052,10 +1052,10 @@ const styles = StyleSheet.create((theme) => ({
borderRadius: theme.borderRadius.lg,
},
rowHovered: {
backgroundColor: theme.colors.surface1,
backgroundColor: theme.colors.surfaceHover,
},
rowPressed: {
backgroundColor: theme.colors.surface2,
backgroundColor: theme.colors.surfaceSelected,
},
rowIconWrap: {
width: theme.iconSize.md,
+1 -1
View File
@@ -1072,7 +1072,7 @@ const expandableBadgeStylesheet = StyleSheet.create((theme) => ({
...(isWeb ? { cursor: "auto" as const, userSelect: "text" as const } : {}),
},
pressableExpanded: {
backgroundColor: theme.colors.surface1,
backgroundColor: theme.colors.surfaceHover,
},
pressableExpandedAttached: {
borderColor: theme.colors.border,
@@ -2051,13 +2051,13 @@ const styles = StyleSheet.create((theme) => ({
},
browserModelRow: {},
browserRowHovered: {
backgroundColor: theme.colors.surface1,
backgroundColor: theme.colors.surfaceSelected,
},
browserRowHoveredElevated: {
backgroundColor: theme.colors.surface2,
},
browserRowPressed: {
backgroundColor: theme.colors.surface1,
backgroundColor: theme.colors.surfaceSelected,
},
browserRowPressedElevated: {
backgroundColor: theme.colors.surface2,
@@ -86,20 +86,20 @@ const styles = StyleSheet.create((theme) => ({
width: 14,
height: 14,
borderRadius: theme.borderRadius.sm,
backgroundColor: theme.colors.surface2,
backgroundColor: theme.colors.surfaceSidebarSelected,
},
projectIcon: {
width: PROJECT_ICON_SIZE,
height: PROJECT_ICON_SIZE,
// Matches the real icon it stands in for, so the skeleton doesn't change shape on load.
borderRadius: projectIconRadius(PROJECT_ICON_SIZE),
backgroundColor: theme.colors.surface2,
backgroundColor: theme.colors.surfaceSidebarSelected,
},
sectionTitle: {
width: "45%",
height: 12,
borderRadius: theme.borderRadius.sm,
backgroundColor: theme.colors.surface2,
backgroundColor: theme.colors.surfaceSidebarSelected,
},
rows: {
gap: theme.spacing[1],
@@ -116,18 +116,18 @@ const styles = StyleSheet.create((theme) => ({
width: 8,
height: 8,
borderRadius: theme.borderRadius.full,
backgroundColor: theme.colors.surface2,
backgroundColor: theme.colors.surfaceSidebarSelected,
},
rowTitle: {
flex: 1,
height: 12,
borderRadius: theme.borderRadius.sm,
backgroundColor: theme.colors.surface2,
backgroundColor: theme.colors.surfaceSidebarSelected,
},
rowBadge: {
width: 40,
height: 20,
borderRadius: theme.borderRadius.md,
backgroundColor: theme.colors.surface2,
backgroundColor: theme.colors.surfaceSidebarSelected,
},
}));
@@ -2748,7 +2748,7 @@ const styles = StyleSheet.create((theme) => ({
backgroundColor: theme.colors.surfaceSidebarHover,
},
newWorkspaceGhostRowPressed: {
backgroundColor: theme.colors.surface2,
backgroundColor: theme.colors.surfaceSidebarSelected,
},
// The width of a workspace row's status slot, so the label lands on the same rail as the
// titles above it.
@@ -2788,10 +2788,10 @@ const styles = StyleSheet.create((theme) => ({
backgroundColor: theme.colors.surfaceSidebarHover,
},
projectRowPressed: {
backgroundColor: theme.colors.surface2,
backgroundColor: theme.colors.surfaceSidebarSelected,
},
projectRowDragging: {
backgroundColor: theme.colors.surface2,
backgroundColor: theme.colors.surfaceSidebarSelected,
borderWidth: 1,
borderColor: theme.colors.border,
transform: [{ scale: 1.02 }],
@@ -2874,7 +2874,7 @@ const styles = StyleSheet.create((theme) => ({
opacity: 0,
},
projectKebabButtonHovered: {
backgroundColor: theme.colors.surface2,
backgroundColor: theme.colors.interactionHighlight,
},
projectTrailingControlSlot: {
width: 24,
@@ -2935,10 +2935,10 @@ const styles = StyleSheet.create((theme) => ({
backgroundColor: theme.colors.surfaceSidebarHover,
},
workspaceRowPressed: {
backgroundColor: theme.colors.surface2,
backgroundColor: theme.colors.surfaceSidebarSelected,
},
workspaceRowDragging: {
backgroundColor: theme.colors.surface2,
backgroundColor: theme.colors.surfaceSidebarSelected,
borderWidth: 1,
borderColor: theme.colors.border,
transform: [{ scale: 1.02 }],
@@ -3007,6 +3007,6 @@ const styles = StyleSheet.create((theme) => ({
marginLeft: 2,
},
kebabButtonHovered: {
backgroundColor: theme.colors.surface2,
backgroundColor: theme.colors.interactionHighlight,
},
}));
@@ -308,9 +308,13 @@ export function SidebarDisplayPreferencesMenu(): ReactElement {
>
<ThemedSettings2 size={14} uniProps={mutedIconMapping} />
</MenuTrigger>
{/* Host, project, and label pages grow with the host's data, so the popover has to
scroll once they outgrow the window. A sheet already scrolls; without this the wide
presentation clipped every row past the bottom edge. */}
<MenuSurface
align="end"
width={MENU_WIDTH}
scrollable
pages={pages}
sheetTitle={t("sidebar.display.heading")}
testID="sidebar-display-preferences-content"
@@ -88,7 +88,7 @@ const styles = StyleSheet.create((theme) => ({
backgroundColor: theme.colors.surfaceSidebarHover,
},
rowPressed: {
backgroundColor: theme.colors.surface2,
backgroundColor: theme.colors.surfaceSidebarSelected,
},
// The width of a workspace row's status slot, so the label lands on the same rail as the
// titles above it rather than two points to their left.
@@ -152,7 +152,7 @@ const styles = StyleSheet.create((theme) => ({
},
// The workspace rows' pressed fill.
rowPressed: {
backgroundColor: theme.colors.surface2,
backgroundColor: theme.colors.surfaceSidebarSelected,
},
button: {
flex: 1,
@@ -1,7 +1,6 @@
import { useCallback, type ReactNode, type RefObject } from "react";
import type { View } from "react-native";
import { MenuRoot, useMenuContext } from "@/components/ui/menu";
import { PluginPopoverSurface } from "@/plugins/popover";
import type { ReactNode } from "react";
import { MenuRoot } from "@/components/ui/menu";
import { PluginPopoverSurface, usePluginPopoverAnchor } from "@/plugins/popover";
import type { SidebarSection } from "@/sidebar-nav/model";
/**
@@ -26,41 +25,7 @@ export function SidebarPopoverRoot({
);
}
function assignRef(ref: RefObject<View | null>, node: View | null) {
Object.assign(ref, { current: node });
}
/**
* Where the popover anchors. `anchorTo` moves it to an element, such as the row just pressed;
* `offerAnchor` sets it only when nothing is anchored; `releaseAnchor` drops an element that is
* going away; `anchorToFallback` covers an item that anchored nothing.
*/
export function useSidebarPopoverAnchor(name: string): {
anchorTo: (node: View | null) => void;
offerAnchor: (node: View | null) => void;
releaseAnchor: (node: View | null) => void;
anchorToFallback: (fallback: RefObject<View | null>) => void;
} {
const { triggerRef } = useMenuContext(name);
const anchorTo = useCallback((node: View | null) => assignRef(triggerRef, node), [triggerRef]);
const offerAnchor = useCallback(
(node: View | null) => {
if (!triggerRef.current) assignRef(triggerRef, node);
},
[triggerRef],
);
const releaseAnchor = useCallback(
(node: View | null) => {
if (triggerRef.current === node) assignRef(triggerRef, null);
},
[triggerRef],
);
const anchorToFallback = useCallback(
(fallback: RefObject<View | null>) => offerAnchor(fallback.current),
[offerAnchor],
);
return { anchorTo, offerAnchor, releaseAnchor, anchorToFallback };
}
export const useSidebarPopoverAnchor = usePluginPopoverAnchor;
const PLACEMENT = {
header: { side: "right", align: "start" },
@@ -11,4 +11,9 @@ describe("getSidebarRowBackdrop", () => {
it("uses the hover surface for an unselected hovered row", () => {
expect(getSidebarRowBackdrop({ isHovered: true })).toBe("surfaceSidebarHover");
});
it("uses the selected sidebar surface when pressed or dragging", () => {
expect(getSidebarRowBackdrop({ isHighlighted: true })).toBe("surfaceSidebarSelected");
expect(getSidebarRowBackdrop({ isDragging: true })).toBe("surfaceSidebarSelected");
});
});
@@ -22,8 +22,7 @@ export function getSidebarRowBackdrop({
selected?: boolean;
isHovered?: boolean;
}): SidebarSurfaceBackdrop {
if (isDragging || isHighlighted) return "surface2";
if (selected) return "surfaceSidebarSelected";
if (isDragging || isHighlighted || selected) return "surfaceSidebarSelected";
if (isHovered) return "surfaceSidebarHover";
return "surfaceSidebar";
}
@@ -1235,7 +1235,7 @@ const styles = StyleSheet.create((theme) => ({
backgroundColor: theme.colors.surfaceSidebarHover,
},
statusGroupRowPressed: {
backgroundColor: theme.colors.surface2,
backgroundColor: theme.colors.surfaceSidebarSelected,
},
statusGroupRowLeft: {
flexDirection: "row",
@@ -1286,10 +1286,10 @@ const styles = StyleSheet.create((theme) => ({
backgroundColor: theme.colors.surfaceSidebarHover,
},
workspaceRowPressed: {
backgroundColor: theme.colors.surface2,
backgroundColor: theme.colors.surfaceSidebarSelected,
},
workspaceRowDragging: {
backgroundColor: theme.colors.surface2,
backgroundColor: theme.colors.surfaceSidebarSelected,
borderWidth: 1,
borderColor: theme.colors.border,
transform: [{ scale: 1.02 }],
@@ -539,7 +539,7 @@ const styles = StyleSheet.create((theme) => ({
marginRight: bySizing({ touch: -14, pointer: -7 }),
},
triggerHovered: {
backgroundColor: theme.colors.surface2,
backgroundColor: theme.colors.interactionHighlight,
},
// The kebab's box without its offsets: the archive glyph fills its view box, so it needs
// none of the nudging the three dots do.
@@ -102,6 +102,8 @@ const styles = StyleSheet.create((theme) => ({
surface0: { borderColor: theme.colors.surface0 },
surface1: { borderColor: theme.colors.surface1 },
surface2: { borderColor: theme.colors.surface2 },
surfaceHover: { borderColor: theme.colors.surfaceHover },
surfaceSelected: { borderColor: theme.colors.surfaceSelected },
surfaceSidebar: { borderColor: theme.colors.surfaceSidebar },
surfaceSidebarHover: { borderColor: theme.colors.surfaceSidebarHover },
surfaceSidebarSelected: { borderColor: theme.colors.surfaceSidebarSelected },
@@ -46,6 +46,10 @@ function getBackdropStyle(backdrop: SurfaceBackdrop | null | undefined) {
return styles.backdropSurface0;
case "surface1":
return styles.backdropSurface1;
case "surfaceHover":
return styles.backdropSurfaceHover;
case "surfaceSelected":
return styles.backdropSurfaceSelected;
case "surfaceSidebar":
return styles.backdropSurfaceSidebar;
case "surfaceSidebarHover":
@@ -90,6 +94,8 @@ export const styles = StyleSheet.create((theme) => {
},
backdropSurface0: { backgroundColor: theme.colors.surface0 },
backdropSurface1: { backgroundColor: theme.colors.surface1 },
backdropSurfaceHover: { backgroundColor: theme.colors.surfaceHover },
backdropSurfaceSelected: { backgroundColor: theme.colors.surfaceSelected },
backdropSurfaceSidebar: { backgroundColor: theme.colors.surfaceSidebar },
backdropSurfaceSidebarHover: { backgroundColor: theme.colors.surfaceSidebarHover },
backdropSurfaceSidebarSelected: { backgroundColor: theme.colors.surfaceSidebarSelected },
@@ -0,0 +1,136 @@
import React, { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { Pressable, Text, View } from "react-native";
import {
SafeAreaInsetsContext,
useSafeAreaInsets,
type EdgeInsets,
} from "react-native-safe-area-context";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { SheetBottomInset } from "@/components/adaptive-modal-sheet";
import { BottomSafeAreaInset } from "./bottom-safe-area-inset";
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
beforeEach(() => vi.stubGlobal("React", React));
const FRAME_HEIGHT = 600;
const FILL_STYLE = { flex: 1, minHeight: 0 };
const BOTTOM_BAR_STYLE = { padding: 12 };
const INSETS_48: EdgeInsets = { top: 24, right: 0, bottom: 48, left: 0 };
const INSETS_0: EdgeInsets = { top: 0, right: 0, bottom: 0, left: 0 };
const NON_ZERO_CASES = [
{ bottom: 48, insets: { top: 24, right: 8, bottom: 48, left: 4 } },
{ bottom: 34, insets: { top: 24, right: 8, bottom: 34, left: 4 } },
] as const;
let root: Root | null = null;
let container: HTMLDivElement | null = null;
afterEach(() => {
act(() => root?.unmount());
container?.remove();
root = null;
container = null;
});
function BottomPinnedSurface() {
const insets = useSafeAreaInsets();
return (
<View style={FILL_STYLE}>
<View style={FILL_STYLE}>
<Text testID="descendant-insets">
{`${insets.top}|${insets.right}|${insets.bottom}|${insets.left}`}
</Text>
</View>
<View testID="bottom-bar" style={BOTTOM_BAR_STYLE}>
<Pressable accessibilityRole="button">
<Text>Submit</Text>
</Pressable>
</View>
</View>
);
}
function mount(node: React.ReactNode) {
container = document.createElement("div");
container.style.width = "390px";
container.style.height = `${FRAME_HEIGHT}px`;
container.style.display = "flex";
container.style.flexDirection = "column";
document.body.appendChild(container);
root = createRoot(container);
act(() => root?.render(node));
return container;
}
function queryEl(host: HTMLElement, testID: string): HTMLElement {
const el = host.querySelector(`[data-testid="${testID}"]`);
if (!(el instanceof HTMLElement)) throw new Error(`Missing element ${testID}`);
return el;
}
describe("BottomSafeAreaInset", () => {
it.each(NON_ZERO_CASES)(
"clears bottom=$bottom in Chromium layout and zeroes descendant bottom inset",
({ bottom, insets }) => {
const host = mount(
<SafeAreaInsetsContext.Provider value={insets}>
<BottomSafeAreaInset style={FILL_STYLE} testID="host-boundary">
<BottomPinnedSurface />
</BottomSafeAreaInset>
</SafeAreaInsetsContext.Provider>,
);
const frameRect = host.getBoundingClientRect();
const boundary = queryEl(host, "host-boundary");
const bottomBarRect = queryEl(host, "bottom-bar").getBoundingClientRect();
expect(getComputedStyle(boundary).paddingBottom).toBe(`${bottom}px`);
expect(bottomBarRect.bottom).toBeLessThanOrEqual(frameRect.bottom - bottom + 1);
expect(bottomBarRect.bottom).toBeGreaterThanOrEqual(frameRect.bottom - bottom - 1);
expect(queryEl(host, "descendant-insets").textContent).toBe("24|8|0|4");
},
);
it("does not double-pad when nested inside SheetBottomInset", () => {
const host = mount(
<SafeAreaInsetsContext.Provider value={INSETS_48}>
<SheetBottomInset style={FILL_STYLE} testID="sheet-boundary">
<BottomSafeAreaInset style={FILL_STYLE} testID="host-boundary">
<BottomPinnedSurface />
</BottomSafeAreaInset>
</SheetBottomInset>
</SafeAreaInsetsContext.Provider>,
);
const frameRect = host.getBoundingClientRect();
const sheet = queryEl(host, "sheet-boundary");
const boundary = queryEl(host, "host-boundary");
const bottomBarRect = queryEl(host, "bottom-bar").getBoundingClientRect();
expect(getComputedStyle(sheet).paddingBottom).toBe("48px");
expect(getComputedStyle(boundary).paddingBottom).toBe("0px");
expect(bottomBarRect.bottom).toBeLessThanOrEqual(frameRect.bottom - 48 + 1);
expect(bottomBarRect.bottom).toBeGreaterThanOrEqual(frameRect.bottom - 48 - 1);
expect(queryEl(host, "descendant-insets").textContent).toBe("24|0|0|0");
});
it("adds no bottom padding when insets.bottom is 0", () => {
const host = mount(
<SafeAreaInsetsContext.Provider value={INSETS_0}>
<BottomSafeAreaInset style={FILL_STYLE} testID="host-boundary">
<BottomPinnedSurface />
</BottomSafeAreaInset>
</SafeAreaInsetsContext.Provider>,
);
const frameRect = host.getBoundingClientRect();
const boundary = queryEl(host, "host-boundary");
const bottomBarRect = queryEl(host, "bottom-bar").getBoundingClientRect();
expect(getComputedStyle(boundary).paddingBottom).toBe("0px");
expect(bottomBarRect.bottom).toBeLessThanOrEqual(frameRect.bottom + 1);
expect(bottomBarRect.bottom).toBeGreaterThanOrEqual(frameRect.bottom - 1);
expect(queryEl(host, "descendant-insets").textContent).toBe("0|0|0|0");
});
});
@@ -0,0 +1,27 @@
import { useMemo } from "react";
import { View, type ViewProps } from "react-native";
import { SafeAreaInsetsContext, useSafeAreaInsets } from "react-native-safe-area-context";
/**
* Owns the remaining bottom safe-area inset at a host boundary: pads `insets.bottom` once
* (when positive) and publishes `SafeAreaInsetsContext` with `bottom: 0` to descendants so nested
* inset-aware views (such as `ComposerDock` or nested host containers) never double-pad.
*/
export function BottomSafeAreaInset({ style, children, ...props }: ViewProps) {
const insets = useSafeAreaInsets();
const contentInsets = useMemo(
() => (insets.bottom > 0 ? { ...insets, bottom: 0 } : insets),
[insets],
);
const insetStyle = useMemo(
() => (insets.bottom > 0 ? [style, { paddingBottom: insets.bottom }] : style),
[insets.bottom, style],
);
return (
<View {...props} style={insetStyle}>
<SafeAreaInsetsContext.Provider value={contentInsets}>
{children}
</SafeAreaInsetsContext.Provider>
</View>
);
}
@@ -1,10 +1,14 @@
import React, {
createContext,
useCallback,
useContext,
useLayoutEffect,
useMemo,
useRef,
type MutableRefObject,
type ReactNode,
} from "react";
import { StyleSheet, type StyleProp, type ViewStyle } from "react-native";
import type { GestureType } from "react-native-gesture-handler";
/**
@@ -22,17 +26,29 @@ export type SheetContentDragGesture = MutableRefObject<GestureType | undefined>;
*/
export type AttachSheetContentDrag = (gesture: SheetContentDragGesture) => () => void;
export interface SheetScrollMetricsReporter {
registerScroll: () => () => void;
reportLayoutHeight: (height: number) => void;
reportContentHeight: (height: number) => void;
remeasure?: () => void;
}
interface BottomSheetScopeValue {
attachContentDrag: AttachSheetContentDrag;
reportScrollMetrics?: SheetScrollMetricsReporter;
}
const BottomSheetScopeContext = createContext<BottomSheetScopeValue | null>(null);
export function BottomSheetScope({
attachContentDrag,
reportScrollMetrics,
children,
}: BottomSheetScopeValue & { children: ReactNode }) {
const value = useMemo(() => ({ attachContentDrag }), [attachContentDrag]);
const value = useMemo(
() => ({ attachContentDrag, reportScrollMetrics }),
[attachContentDrag, reportScrollMetrics],
);
return (
<BottomSheetScopeContext.Provider value={value}>{children}</BottomSheetScopeContext.Provider>
);
@@ -45,3 +61,75 @@ export function useIsInsideBottomSheet(): boolean {
export function useAttachSheetContentDrag(): AttachSheetContentDrag | undefined {
return useContext(BottomSheetScopeContext)?.attachContentDrag;
}
type ScrollStyleMode = "fixed" | "flex" | "auto";
function getScrollStyleMode(style: StyleProp<ViewStyle>): ScrollStyleMode {
const flat = StyleSheet.flatten(style);
if (
(typeof flat?.flex === "number" && flat.flex > 0) ||
(typeof flat?.flexGrow === "number" && flat.flexGrow > 0)
) {
return "flex";
}
if (typeof flat?.height === "number" || typeof flat?.maxHeight === "number") {
return "fixed";
}
return "auto";
}
export function useSheetScrollMetricsProps<
L extends { nativeEvent: { layout: { height: number } } },
>(
enabled: boolean,
onLayout: ((event: L) => void) | undefined,
onContentSizeChange: ((width: number, height: number) => void) | undefined,
style?: StyleProp<ViewStyle>,
): {
onLayout: ((event: L) => void) | undefined;
onContentSizeChange: ((width: number, height: number) => void) | undefined;
} {
const reporter = useContext(BottomSheetScopeContext)?.reportScrollMetrics;
const active = enabled && reporter !== undefined;
const styleMode = getScrollStyleMode(style);
const prevStyleModeRef = useRef<ScrollStyleMode | null>(null);
useLayoutEffect(() => {
if (!active || !reporter) {
prevStyleModeRef.current = null;
return undefined;
}
return reporter.registerScroll();
}, [active, reporter]);
useLayoutEffect(() => {
if (!active || !reporter) {
prevStyleModeRef.current = null;
return;
}
const previous = prevStyleModeRef.current;
prevStyleModeRef.current = styleMode;
if (previous !== null && previous !== styleMode) {
reporter.remeasure?.();
}
}, [active, reporter, styleMode]);
const handleLayout = useCallback(
(event: L) => {
if (active && reporter) {
reporter.reportLayoutHeight(event.nativeEvent.layout.height);
}
onLayout?.(event);
},
[active, onLayout, reporter],
);
const handleContentSizeChange = useCallback(
(width: number, height: number) => {
if (active && reporter) {
reporter.reportContentHeight(height);
}
onContentSizeChange?.(width, height);
},
[active, onContentSizeChange, reporter],
);
return active
? { onLayout: handleLayout, onContentSizeChange: handleContentSizeChange }
: { onLayout, onContentSizeChange };
}
+3 -3
View File
@@ -1930,19 +1930,19 @@ const styles = StyleSheet.create((theme) => ({
alignSelf: "stretch",
},
comboboxItemHovered: {
backgroundColor: theme.colors.surface1,
backgroundColor: theme.colors.surfaceHover,
},
comboboxItemHoveredElevated: {
backgroundColor: theme.colors.surface2,
},
comboboxItemPressed: {
backgroundColor: theme.colors.surface1,
backgroundColor: theme.colors.surfaceSelected,
},
comboboxItemPressedElevated: {
backgroundColor: theme.colors.surface2,
},
comboboxItemActive: {
backgroundColor: theme.colors.surface1,
backgroundColor: theme.colors.surfaceSelected,
},
comboboxItemDisabled: {
opacity: 0.55,
@@ -263,5 +263,6 @@ export function useIsolatedBottomSheetVisibility({
}
export { SheetVisibleFrame, useBottomSheetSafeAreaPaddingStyle } from "./visible-frame";
export { getBottomSheetVisibleContentHeight } from "./visible-frame-layout";
export { systemBackPress } from "./back-press";
export { SheetHostScope } from "./host-scope";
@@ -5,11 +5,13 @@ import {
type PropsWithChildren,
type ReactElement,
type ReactNode,
type RefObject,
} from "react";
import {
Pressable,
Text,
View,
type LayoutChangeEvent,
type PressableStateCallbackType,
type ViewStyle,
} from "react-native";
@@ -72,10 +74,36 @@ export type ActionStatus = "idle" | "pending" | "success";
*
* It also carries the page's depth, so the two presentations cannot disagree about what a page is.
*/
export function MenuPage({ depth, children }: PropsWithChildren<{ depth: number }>): ReactElement {
function resolveMenuPageStyle(raw: boolean | "fill") {
if (raw === "fill") return styles.rawFillPage;
return raw ? styles.rawPage : styles.page;
}
export function MenuPage({
depth,
raw = false,
onContentEndLayout,
contentEndRef,
children,
}: PropsWithChildren<{
depth: number;
raw?: boolean | "fill";
onContentEndLayout?: (event: LayoutChangeEvent) => void;
contentEndRef?: RefObject<View | null>;
}>): ReactElement {
return (
<MenuDepthProvider value={depth}>
<View style={styles.page}>{children}</View>
<View style={resolveMenuPageStyle(raw)}>
{children}
{onContentEndLayout ? (
<View
ref={contentEndRef}
pointerEvents="none"
style={styles.rawEndMarker}
onLayout={onContentEndLayout}
/>
) : null}
</View>
</MenuDepthProvider>
);
}
@@ -451,6 +479,19 @@ const styles = StyleSheet.create((theme) => ({
paddingVertical: theme.spacing[1],
gap: MENU_ROW_GAP,
},
rawPage: {
flexGrow: 1,
flexShrink: 1,
minHeight: 0,
},
rawFillPage: {
flex: 1,
minHeight: 0,
},
rawEndMarker: {
height: 0,
flexShrink: 0,
},
labelContainer: {
paddingHorizontal: theme.spacing[3],
paddingTop: theme.spacing[2],
@@ -1,6 +1,6 @@
import React, { act, useEffect, useState, type ReactNode } from "react";
import { createRoot, type Root } from "react-dom/client";
import { Text, View } from "react-native";
import { ScrollView, Text, View, type ViewStyle } from "react-native";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { page } from "vitest/browser";
import {
@@ -271,3 +271,219 @@ describe("submenu flyout side", () => {
expect(flyout.left).toBeGreaterThanOrEqual(panel.right - MAX_OVERLAP);
});
});
function scrollerInside(root: HTMLElement): HTMLElement {
const candidates = [root, ...Array.from(root.querySelectorAll<HTMLElement>("*"))];
const scroller = candidates.find((candidate) => {
const overflowY = getComputedStyle(candidate).overflowY;
return (
(overflowY === "auto" || overflowY === "scroll") &&
candidate.scrollHeight > candidate.clientHeight + 1
);
});
if (!scroller) throw new Error("The scrollable menu surface has no scroll viewport");
return scroller;
}
describe("scrollable menu surface on window resize", () => {
const ITEM_COUNT = 40;
beforeEach(async () => {
await page.viewport(1280, 720);
});
it("stays inside the window when shrunk and scrolls to the last item", async () => {
mount(
<View style={AWAY_FROM_EDGE}>
<MenuRoot>
<MenuTrigger testID="pill" accessibilityLabel="Open menu">
<Text>Open menu</Text>
</MenuTrigger>
<MenuSurface scrollable width={232} testID="panel">
{Array.from({ length: ITEM_COUNT }, (_, index) => (
<MenuItem key={index} testID={`scroll-item-${index}`} closeOnSelect={false}>
{`Item ${index}`}
</MenuItem>
))}
</MenuSurface>
</MenuRoot>
</View>,
);
act(() => element("pill").click());
await expect
.poll(() => {
const found = document.querySelector('[data-testid="panel"]');
return found instanceof HTMLElement ? found.getBoundingClientRect().top : -9999;
})
.toBeGreaterThan(0);
const panel = element("panel");
const initialRect = panel.getBoundingClientRect();
expect(initialRect.top).toBeGreaterThanOrEqual(0);
expect(initialRect.bottom).toBeLessThanOrEqual(window.innerHeight);
expect(initialRect.height).toBeLessThan(window.innerHeight);
// Wait for initial item focus so it does not reset scroll position right after scrolling.
await expect
.poll(() => document.activeElement?.getAttribute("data-testid"))
.toBe("scroll-item-0");
const lastItem = element(`scroll-item-${ITEM_COUNT - 1}`);
expect(lastItem.getBoundingClientRect().bottom).toBeGreaterThan(window.innerHeight);
await page.viewport(1280, 540);
await expect.poll(() => panel.getBoundingClientRect().bottom).toBeLessThanOrEqual(540);
const scroller = scrollerInside(panel);
act(() => {
scroller.scrollTop = scroller.scrollHeight;
});
await expect
.poll(() => {
const row = lastItem.getBoundingClientRect();
const surface = panel.getBoundingClientRect();
return row.top >= surface.top && row.bottom <= surface.bottom + 1;
})
.toBe(true);
});
});
const BOUNDED_MAX_HEIGHT = 440;
const RAW_ROOT_STYLE: ViewStyle = { flex: 1, minHeight: 0 };
const RAW_SCROLL_STYLE: ViewStyle = { flex: 1 };
const RAW_HEADER_STYLE: ViewStyle = { height: 48, justifyContent: "center" };
const RAW_FOOTER_STYLE: ViewStyle = { height: 48, justifyContent: "center" };
const RAW_ROW_STYLE: ViewStyle = { height: 40, justifyContent: "center" };
const RAW_SHORT_STYLE: ViewStyle = { height: 96, justifyContent: "center" };
const RAW_OVERFLOW_STYLE: ViewStyle = { height: 900 };
function mountBoundedRawCanvas(body: ReactNode): void {
mount(
<View style={AWAY_FROM_EDGE}>
<MenuRoot>
<MenuTrigger testID="pill" accessibilityLabel="Open panel">
<Text>Open panel</Text>
</MenuTrigger>
<MenuSurface
scrollable={false}
minWidth={280}
maxWidth={420}
maxHeight={BOUNDED_MAX_HEIGHT}
testID="panel"
>
{body}
</MenuSurface>
</MenuRoot>
</View>,
);
act(() => element("pill").click());
}
describe("bounded non-scrollable menu surface (raw canvas)", () => {
beforeEach(async () => {
await page.viewport(1280, 900);
});
it("hugs short content with 0px outer padding", async () => {
mountBoundedRawCanvas(
<View testID="raw-short" style={RAW_SHORT_STYLE}>
<Text>Short</Text>
</View>,
);
await expect
.poll(() => {
const found = document.querySelector('[data-testid="panel"]');
return found instanceof HTMLElement ? found.getBoundingClientRect().top : -9999;
})
.toBeGreaterThan(0);
const panel = element("panel").getBoundingClientRect();
const shortBox = element("raw-short").getBoundingClientRect();
// 1px border on each side, 0px outer padding.
expect(panel.height).toBeLessThan(150);
expect(Math.abs(shortBox.top - panel.top - 1)).toBeLessThanOrEqual(1);
expect(Math.abs(panel.bottom - shortBox.bottom - 1)).toBeLessThanOrEqual(1);
expect(Math.abs(shortBox.left - panel.left - 1)).toBeLessThanOrEqual(1);
expect(Math.abs(panel.right - shortBox.right - 1)).toBeLessThanOrEqual(1);
});
it("caps tall header + ScrollView + footer at maxHeight, pins header/footer, and scrolls body", async () => {
mountBoundedRawCanvas(
<View style={RAW_ROOT_STYLE}>
<View testID="raw-header" style={RAW_HEADER_STYLE}>
<Text>Fixed Header</Text>
</View>
<ScrollView testID="raw-scroll" style={RAW_SCROLL_STYLE}>
{Array.from({ length: 30 }, (_, index) => (
<View key={index} testID={`raw-row-${index}`} style={RAW_ROW_STYLE}>
<Text>{`Row ${index}`}</Text>
</View>
))}
</ScrollView>
<View testID="raw-footer" style={RAW_FOOTER_STYLE}>
<Text>Fixed Footer</Text>
</View>
</View>,
);
await expect
.poll(() => {
const found = document.querySelector('[data-testid="panel"]');
return found instanceof HTMLElement ? found.getBoundingClientRect().top : -9999;
})
.toBeGreaterThan(0);
const panel = element("panel");
const panelRect = panel.getBoundingClientRect();
const headerBefore = element("raw-header").getBoundingClientRect();
const footerBefore = element("raw-footer").getBoundingClientRect();
expect(panelRect.height).toBeLessThanOrEqual(BOUNDED_MAX_HEIGHT + 1);
expect(panelRect.height).toBeGreaterThan(400);
expect(Math.abs(headerBefore.top - panelRect.top - 1)).toBeLessThanOrEqual(1);
expect(Math.abs(panelRect.bottom - footerBefore.bottom - 1)).toBeLessThanOrEqual(1);
const scroller = scrollerInside(panel);
const lastRow = element("raw-row-29");
expect(lastRow.getBoundingClientRect().bottom).toBeGreaterThan(footerBefore.top);
act(() => {
scroller.scrollTop = scroller.scrollHeight;
});
await expect
.poll(() => {
const row = lastRow.getBoundingClientRect();
const scrollerRect = scroller.getBoundingClientRect();
return row.top >= scrollerRect.top - 1 && row.bottom <= scrollerRect.bottom + 1;
})
.toBe(true);
// Header and footer remain pinned in place after scrolling.
expect(element("raw-header").getBoundingClientRect().top).toBe(headerBefore.top);
expect(element("raw-footer").getBoundingClientRect().bottom).toBe(footerBefore.bottom);
});
it("clips tall non-scrolling content at maxHeight and respects shorter viewports", async () => {
mountBoundedRawCanvas(
<View testID="raw-overflow" style={RAW_OVERFLOW_STYLE}>
<Text>Tall static</Text>
</View>,
);
await expect
.poll(() => {
const found = document.querySelector('[data-testid="panel"]');
return found instanceof HTMLElement ? found.getBoundingClientRect().top : -9999;
})
.toBeGreaterThan(0);
const panel = element("panel");
expect(panel.getBoundingClientRect().height).toBeLessThanOrEqual(BOUNDED_MAX_HEIGHT + 1);
expect(getComputedStyle(panel).overflowY).toBe("hidden");
await page.viewport(1280, 360);
await expect.poll(() => panel.getBoundingClientRect().height).toBeLessThanOrEqual(360 - 16 + 1);
});
});
@@ -15,9 +15,9 @@ import {
import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
import {
Dimensions,
Platform,
Pressable,
useWindowDimensions,
View,
type PointerEvent,
type StyleProp,
@@ -119,26 +119,26 @@ export function useAnchoredPosition({
*/
flipHorizontal?: boolean;
}) {
const { width: screenWidth, height: screenHeight } = useWindowDimensions();
const [triggerRect, setTriggerRect] = useState<Rect | null>(null);
const [contentSize, setContentSize] = useState<Size | null>(null);
const [position, setPosition] = useState<SurfacePosition | null>(null);
const [actualPlacement, setActualPlacement] = useState<Placement>(side);
const heldSideRef = useRef<Placement | null>(null);
const viewportMaxHeight = Math.max(screenHeight - 16, 0);
const resolvedMaxHeight =
typeof maxHeight === "number" ? Math.min(maxHeight, viewportMaxHeight) : viewportMaxHeight;
const visibleContentSize = useMemo(() => {
if (!contentSize) return null;
if (!scrollable) return contentSize;
const { height: screenHeight } = Dimensions.get("window");
const viewportMaxHeight = Math.max(screenHeight - 16, 0);
const resolvedMaxHeight =
typeof maxHeight === "number" ? Math.min(maxHeight, viewportMaxHeight) : viewportMaxHeight;
if (!scrollable && typeof maxHeight !== "number") return contentSize;
return {
width: contentSize.width,
height: Math.min(contentSize.height, resolvedMaxHeight),
};
}, [contentSize, scrollable, maxHeight]);
}, [contentSize, scrollable, maxHeight, resolvedMaxHeight]);
useEffect(() => {
if (!open) {
@@ -172,12 +172,12 @@ export function useAnchoredPosition({
return () => {
cancelled = true;
};
}, [anchorRect, anchorRef, open]);
// A resize moves the anchor and changes the display area, so both measurements repeat.
}, [anchorRect, anchorRef, open, screenWidth, screenHeight]);
useEffect(() => {
if (!triggerRect || !visibleContentSize) return;
const { width: screenWidth, height: screenHeight } = Dimensions.get("window");
// measureInWindow and Modal both use full-screen coordinates, so the display area starts at 0.
const heldSide = heldSideRef.current;
const result = computePosition({
@@ -193,7 +193,16 @@ export function useAnchoredPosition({
setPosition(holdSurfaceEdge(result, visibleContentSize.height));
setActualPlacement(result.actualPlacement);
}, [triggerRect, visibleContentSize, side, align, offset, flipHorizontal]);
}, [
triggerRect,
visibleContentSize,
screenWidth,
screenHeight,
side,
align,
offset,
flipHorizontal,
]);
const onContentLayout = useCallback(
(event: { nativeEvent: { layout: { width: number; height: number } } }) => {
@@ -206,7 +215,15 @@ export function useAnchoredPosition({
[],
);
return { position, actualPlacement, contentSize, visibleContentSize, onContentLayout };
return {
position,
actualPlacement,
contentSize,
visibleContentSize,
resolvedMaxHeight,
onContentLayout,
screenWidth,
};
}
export interface AnchoredSurfaceProps {
@@ -240,6 +257,76 @@ export interface AnchoredSurfaceProps {
children: ReactElement;
}
function buildAnchoredFrameStyle({
fullWidth,
horizontalPadding,
width,
minWidth,
maxWidth,
screenWidth,
hasBoundedHeight,
resolvedMaxHeight,
surfacePositionStyle,
actualPlacement,
align,
}: {
fullWidth: boolean;
horizontalPadding: number;
width?: number;
minWidth: number;
maxWidth?: number;
screenWidth: number;
hasBoundedHeight: boolean;
resolvedMaxHeight: number | undefined;
surfacePositionStyle: ViewStyle;
actualPlacement: Placement;
align: Alignment;
}): StyleProp<ViewStyle> {
const resolvedWidthStyle: ViewStyle = fullWidth
? { width: screenWidth - horizontalPadding * 2 }
: fitSurfaceWidth({ width, minWidth, maxWidth }, screenWidth);
return [
resolvedWidthStyle,
hasBoundedHeight ? { maxHeight: resolvedMaxHeight } : null,
surfacePositionStyle,
{
...(fullWidth ? { left: horizontalPadding } : null),
transformOrigin: getTransformOrigin(actualPlacement, align),
},
];
}
function buildSurfaceExiting(placed: boolean, onExited?: () => void) {
if (!placed || isWeb || !onExited) return undefined;
return contentExiting.withCallback((finished) => {
"worklet";
if (finished) {
runOnJS(onExited)();
}
});
}
function useFocusFirstMenuItemOnPlace({
open,
placed,
surfaceNativeID,
}: {
open: boolean;
placed: boolean;
surfaceNativeID: string;
}): void {
useEffect(() => {
if (!isWeb || !open || !placed || typeof document === "undefined") return undefined;
const frame = requestAnimationFrame(() => {
document
.getElementById(surfaceNativeID)
?.querySelector<HTMLElement>('[data-menu-item="true"]:not([data-menu-disabled="true"])')
?.focus();
});
return () => cancelAnimationFrame(frame);
}, [open, placed, surfaceNativeID]);
}
/**
* One floating menu surface, positioned against an anchor. The root menu renders one of these
* against its trigger; every open submenu renders another against the row that opened it.
@@ -270,7 +357,14 @@ export function AnchoredSurface({
}: AnchoredSurfaceProps): ReactElement | null {
const { t } = useTranslation();
const surfaceNativeID = useId();
const { position, actualPlacement, visibleContentSize, onContentLayout } = useAnchoredPosition({
const {
position,
actualPlacement,
visibleContentSize,
resolvedMaxHeight,
onContentLayout,
screenWidth,
} = useAnchoredPosition({
open,
anchorRect,
anchorRef,
@@ -281,6 +375,7 @@ export function AnchoredSurface({
maxHeight,
flipHorizontal,
});
const hasBoundedHeight = !scrollable && typeof maxHeight === "number";
// The surface is placed once both measurements land. Until then it sits off-screen so it can
// be measured, and it must not animate: an entering animation that ran there would be over
@@ -292,42 +387,38 @@ export function AnchoredSurface({
const surfaceKey = isWeb || placed ? "placed" : "measuring";
useWebContentEntering({ placed, surfaceNativeID });
useEffect(() => {
if (!isWeb || !open || !placed || typeof document === "undefined") return undefined;
const frame = requestAnimationFrame(() => {
document
.getElementById(surfaceNativeID)
?.querySelector<HTMLElement>('[data-menu-item="true"]:not([data-menu-disabled="true"])')
?.focus();
});
return () => cancelAnimationFrame(frame);
}, [open, placed, surfaceNativeID]);
useFocusFirstMenuItemOnPlace({ open, placed, surfaceNativeID });
const frame = useMemo(() => surfaceFrameStyles(position), [position]);
const frameStyle = useMemo<StyleProp<ViewStyle>>(() => {
const { width: screenWidth } = Dimensions.get("window");
const resolvedWidthStyle: ViewStyle = fullWidth
? { width: screenWidth - horizontalPadding * 2 }
: fitSurfaceWidth({ width, minWidth, maxWidth }, screenWidth);
return [
resolvedWidthStyle,
const frameStyle = useMemo(
() =>
buildAnchoredFrameStyle({
fullWidth,
horizontalPadding,
width,
minWidth,
maxWidth,
screenWidth,
hasBoundedHeight,
resolvedMaxHeight,
surfacePositionStyle: frame.surface,
actualPlacement,
align,
}),
[
fullWidth,
horizontalPadding,
width,
minWidth,
maxWidth,
screenWidth,
hasBoundedHeight,
resolvedMaxHeight,
frame.surface,
{
...(fullWidth ? { left: horizontalPadding } : null),
transformOrigin: getTransformOrigin(actualPlacement, align),
},
];
}, [
fullWidth,
horizontalPadding,
width,
minWidth,
maxWidth,
frame.surface,
actualPlacement,
align,
]);
actualPlacement,
align,
],
);
const scrollViewportStyle = useMemo(
() => [visibleContentSize ? { height: visibleContentSize.height } : null],
@@ -349,6 +440,7 @@ export function AnchoredSurface({
onLayout={onContentLayout}
onPointerEnter={onPointerEnter}
onPointerLeave={onPointerLeave}
style={hasBoundedHeight ? styles.boundedContent : undefined}
>
{children}
</View>
@@ -377,16 +469,7 @@ export function AnchoredSurface({
style={styles.content}
frameStyle={frameStyle}
entering={placed ? nativeContentEntering : undefined}
exiting={
!placed || isWeb || !onExited
? undefined
: contentExiting.withCallback((finished) => {
"worklet";
if (finished) {
runOnJS(onExited)();
}
})
}
exiting={buildSurfaceExiting(placed, onExited)}
>
{scrollable ? (
<FloatingScrollView
@@ -506,4 +589,9 @@ const styles = StyleSheet.create((theme) => ({
overflow: "hidden",
...theme.shadow.md,
},
boundedContent: {
flexGrow: 1,
flexShrink: 1,
minHeight: 0,
},
}));
@@ -1,5 +1,9 @@
import { describe, expect, it } from "vitest";
import { getMenuSheetBottomPadding } from "./menu-sheet-layout";
import {
getMenuSheetBottomPadding,
resolveSheetCanvasScrollContentHeight,
resolveSheetCanvasStaticContentHeight,
} from "./menu-sheet-layout";
describe("getMenuSheetBottomPadding", () => {
it("keeps breathing room below the last row when there is no system inset", () => {
@@ -20,3 +24,80 @@ describe("getMenuSheetBottomPadding", () => {
).toBe(52);
});
});
describe("resolveSheetCanvasScrollContentHeight", () => {
it("adds non-scroll chrome (header, footer, safe area) to scroll content height for flex scrollers", () => {
expect(
resolveSheetCanvasScrollContentHeight({
frameHeight: 600,
bodyHeight: 500,
contentEndY: 500,
scrollLayoutHeight: 400,
scrollContentHeight: 1100,
intrinsicScrollHeight: false,
}),
).toEqual({ height: 1300, intrinsicScrollHeight: false });
});
it("shrinks smoothly for short flex lists without clipping fixed chrome", () => {
expect(
resolveSheetCanvasScrollContentHeight({
frameHeight: 600,
bodyHeight: 500,
contentEndY: 500,
scrollLayoutHeight: 400,
scrollContentHeight: 90,
intrinsicScrollHeight: false,
}),
).toEqual({ height: 290, intrinsicScrollHeight: false });
});
it("hugs fixed-height scrollers without counting unused maxHeight space", () => {
const initial = resolveSheetCanvasScrollContentHeight({
frameHeight: 675,
bodyHeight: 675,
contentEndY: 200,
scrollLayoutHeight: 120,
scrollContentHeight: 400,
intrinsicScrollHeight: false,
});
expect(initial).toEqual({ height: 200, intrinsicScrollHeight: true });
// Once settled at 200px, bodyHeight equals contentEndY and must keep hugging 200px.
const settled = resolveSheetCanvasScrollContentHeight({
frameHeight: 200,
bodyHeight: 200,
contentEndY: 200,
scrollLayoutHeight: 120,
scrollContentHeight: 400,
intrinsicScrollHeight: initial.intrinsicScrollHeight,
});
expect(settled).toEqual({ height: 200, intrinsicScrollHeight: true });
// If the same mounted scroller switches from fixed-height to flex during a re-measure at
// maxHeight, clear the intrinsic latch so the sheet grows with the expanded flex body.
expect(
resolveSheetCanvasScrollContentHeight({
frameHeight: 675,
bodyHeight: 675,
contentEndY: 675,
scrollLayoutHeight: 595,
scrollContentHeight: 400,
intrinsicScrollHeight: settled.intrinsicScrollHeight,
measuring: true,
}),
).toEqual({ height: 480, intrinsicScrollHeight: false });
});
});
describe("resolveSheetCanvasStaticContentHeight", () => {
it("sums sheet header, static content height, and bottom safe area", () => {
expect(
resolveSheetCanvasStaticContentHeight({
headerHeight: 44,
staticHeight: 120,
safeAreaBottom: 48,
}),
).toBe(212);
});
});
@@ -4,3 +4,45 @@ export function getMenuSheetBottomPadding(input: {
}): number {
return input.safeAreaBottom + input.breathingRoom;
}
export function resolveSheetCanvasScrollContentHeight(input: {
frameHeight: number;
bodyHeight: number;
contentEndY: number;
scrollLayoutHeight: number;
scrollContentHeight: number;
intrinsicScrollHeight: boolean;
measuring?: boolean;
}): { height: number; intrinsicScrollHeight: boolean } {
const hostChrome = Math.max(0, input.frameHeight - input.bodyHeight);
// Measure at maxHeight first: when the plugin tree stops short of the host body (for example a
// fixed-height ScrollView), its laid-out height (`contentEndY`) already includes the exact
// viewport height it chose, so adding scrollContentHeight would create dead space below it.
// When `measuring` is true (initial mount or sizing-mode flip), re-evaluate from `bodyHeight`
// rather than keeping an old intrinsic latch.
const bodyTruncated = input.contentEndY > 0 && input.bodyHeight - input.contentEndY > 1;
const intrinsic = input.measuring ? bodyTruncated : input.intrinsicScrollHeight || bodyTruncated;
if (intrinsic) {
return {
height: hostChrome + Math.max(0, input.contentEndY),
intrinsicScrollHeight: true,
};
}
const nonScrollHeight = Math.max(0, input.frameHeight - input.scrollLayoutHeight);
return {
height: nonScrollHeight + Math.max(0, input.scrollContentHeight),
intrinsicScrollHeight: false,
};
}
export function resolveSheetCanvasStaticContentHeight(input: {
headerHeight: number;
staticHeight: number;
safeAreaBottom: number;
}): number {
return (
Math.max(0, input.headerHeight) +
Math.max(0, input.staticHeight) +
Math.max(0, input.safeAreaBottom)
);
}
@@ -5,16 +5,40 @@ import {
useEffect,
useMemo,
useRef,
useState,
type ReactElement,
type ReactNode,
} from "react";
import { useTranslation } from "react-i18next";
import { Pressable, Text, View, useWindowDimensions, type PointerEvent } from "react-native";
import {
Pressable,
Text,
View,
useWindowDimensions,
type LayoutChangeEvent,
type PointerEvent,
} from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { BottomSheetScrollView } from "@gorhom/bottom-sheet";
import {
BottomSheetScrollView,
KEYBOARD_STATUS,
useBottomSheetInternal,
} from "@gorhom/bottom-sheet";
import Animated, {
useAnimatedReaction,
useAnimatedStyle,
useSharedValue,
} from "react-native-reanimated";
import { ChevronLeft } from "lucide-react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { BottomSafeAreaInset } from "@/components/ui/bottom-safe-area-inset";
import {
BottomSheetScope,
useAttachSheetContentDrag,
type SheetScrollMetricsReporter,
} from "@/components/ui/bottom-sheet-scope";
import {
getBottomSheetVisibleContentHeight,
IsolatedBottomSheetModal,
useIsolatedBottomSheetVisibility,
type ContextBridge,
@@ -31,7 +55,11 @@ import { MenuPage } from "./menu-item";
import { currentPageId, isSubPageOpen } from "./menu-navigation";
import { AnchoredSurface, MenuOverlay } from "./menu-overlay";
import { isHoverPointer } from "./menu-pointer";
import { getMenuSheetBottomPadding } from "./menu-sheet-layout";
import {
getMenuSheetBottomPadding,
resolveSheetCanvasScrollContentHeight,
resolveSheetCanvasStaticContentHeight,
} from "./menu-sheet-layout";
import type { Alignment, Placement } from "../anchor";
import type { KeyboardFocusScope } from "@/keyboard/actions";
@@ -66,6 +94,8 @@ export interface MenuListPageDefinition {
* surface stops closing on hover, since its parent leads back to the same dismissal.
*/
hoverIntent?: boolean;
/** Overrides the surface's `scrollable` mode for this page when provided. */
scrollable?: boolean;
fill?: false;
}
@@ -223,7 +253,7 @@ function MenuPopoverSurface({
maxHeight,
fullWidth = false,
horizontalPadding = 16,
scrollable = false,
scrollable,
testID,
keyboardFocusScope,
}: MenuSurfaceProps): ReactElement | null {
@@ -279,11 +309,13 @@ function MenuPopoverSurface({
maxHeight={maxHeight}
fullWidth={fullWidth}
horizontalPadding={horizontalPadding}
scrollable={scrollable}
scrollable={Boolean(scrollable)}
testID={testID}
keyboardFocusScope={keyboardFocusScope}
>
<MenuPage depth={0}>{children}</MenuPage>
<MenuPage depth={0} raw={scrollable === false}>
{children}
</MenuPage>
</AnchoredSurface>
{openPages.map(({ page, depth }) => (
<MenuFlyout
@@ -344,6 +376,8 @@ function MenuFlyout({
if (!anchorRef) return null;
const pageScrollable = page.fill === true ? false : (page.scrollable ?? scrollable);
return (
<AnchoredSurface
open
@@ -356,13 +390,15 @@ function MenuFlyout({
offset={-SUBMENU_OVERLAP}
minWidth={minWidth}
maxHeight={maxHeight}
scrollable={scrollable}
scrollable={Boolean(pageScrollable)}
backdrop={false}
onPointerEnter={handleHoverIn}
onPointerLeave={handleHoverOut}
testID={testID}
>
<MenuPage depth={depth + 1}>{page.content}</MenuPage>
<MenuPage depth={depth + 1} raw={pageScrollable === false}>
{page.content}
</MenuPage>
</AnchoredSurface>
);
}
@@ -372,6 +408,7 @@ function MenuSheetSurface({
pages = [],
sheetTitle,
sheetTrailing,
scrollable,
testID,
keyboardFocusScope,
}: MenuSurfaceProps): ReactElement | null {
@@ -397,6 +434,12 @@ function MenuSheetSurface({
const depth = menu.path.length;
const fillPage = openPage?.fill === true ? openPage : null;
const listPage = openPage?.fill === true ? null : openPage;
const pageScrollable = listPage ? (listPage.scrollable ?? scrollable) : scrollable;
const isRawCanvas = !fillPage && pageScrollable === false;
const maxDynamicContentSize = windowHeight * 0.8;
const headerTitle = listPage ? listPage.title : sheetTitle;
const onHeaderBack = listPage ? menu.goBack : null;
const headerTrailing = listPage ? undefined : sheetTrailing;
// The sheet's content is teleported out of this subtree, so both menu contexts have to be
// rebuilt on the other side. Providing them around the modal instead would put them on the
@@ -410,6 +453,44 @@ function MenuSheetSurface({
[menu, surfaceValue],
);
const renderSheetBody = () => {
const activeChildren = listPage ? listPage.content : children;
const activeDepth = listPage ? depth : 0;
if (fillPage) {
return (
<View style={styles.fillPage} testID={testID ? `${testID}-${fillPage.id}` : undefined}>
{fillPage.content}
</View>
);
}
if (isRawCanvas) {
return (
<MenuSheetCanvasBody
headerTitle={headerTitle}
onHeaderBack={onHeaderBack}
headerTrailing={headerTrailing}
depth={activeDepth}
maxHeight={maxDynamicContentSize}
dataSet={sheetDataSet}
testID={testID}
>
{activeChildren}
</MenuSheetCanvasBody>
);
}
return (
<MenuSheetScrollView dataSet={sheetDataSet} testID={testID}>
{headerTitle ? (
<MenuSheetHeader title={headerTitle} onBack={onHeaderBack} trailing={headerTrailing} />
) : null}
<MenuPage depth={activeDepth}>{activeChildren}</MenuPage>
</MenuSheetScrollView>
);
};
return (
<IsolatedBottomSheetModal
ref={sheetRef}
@@ -423,7 +504,7 @@ function MenuSheetSurface({
enableDynamicSizing={!fillPage}
snapPoints={fillPage ? FULL_SHEET_SNAP_POINTS : undefined}
enableContentPanningGesture={!fillPage}
maxDynamicContentSize={windowHeight * 0.8}
maxDynamicContentSize={maxDynamicContentSize}
onChange={handleSheetChange}
onDismiss={handleSheetDismiss}
backdropOpacity={0.45}
@@ -436,31 +517,394 @@ function MenuSheetSurface({
keyboardBehavior="interactive"
keyboardBlurBehavior="restore"
>
{fillPage ? (
<View style={styles.fillPage} testID={testID ? `${testID}-${fillPage.id}` : undefined}>
{fillPage.content}
</View>
) : (
<MenuSheetScrollView dataSet={sheetDataSet} testID={testID}>
{listPage ? (
<>
<MenuSheetHeader title={listPage.title} onBack={menu.goBack} />
<MenuPage depth={depth}>{listPage.content}</MenuPage>
</>
) : (
<>
{sheetTitle ? (
<MenuSheetHeader title={sheetTitle} onBack={null} trailing={sheetTrailing} />
) : null}
<MenuPage depth={0}>{children}</MenuPage>
</>
)}
</MenuSheetScrollView>
)}
{renderSheetBody()}
</IsolatedBottomSheetModal>
);
}
/**
* Raw bounded canvas inside a dynamic sheet (`scrollable={false}`). Hands scroll and padding
* ownership to the content while keeping `BottomSheetScope` (so plugin `<ScrollView>` / `<FlatList>`
* use Gorhom's gesture-integrated scrollers), `BottomSafeAreaInset` (clearing Android 3-button nav
* and iOS home indicator once), and `MenuSheetHeader` fixed at the top.
*/
function MenuSheetCanvasBody({
headerTitle,
onHeaderBack,
headerTrailing,
depth,
maxHeight,
dataSet,
testID,
children,
}: {
headerTitle?: string;
onHeaderBack: (() => void) | null;
headerTrailing?: ReactNode;
depth: number;
maxHeight: number;
dataSet: { keyboardScope: KeyboardFocusScope } | undefined;
testID?: string;
children: ReactNode;
}): ReactElement {
const {
animatedDetentsState,
animatedKeyboardState,
animatedLayoutState,
animatedPosition,
enableDynamicSizing,
} = useBottomSheetInternal();
const attachContentDrag = useAttachSheetContentDrag();
const safeAreaInsets = useSafeAreaInsets();
const [scrollCount, setScrollCount] = useState(0);
const [intrinsicScrollMode, setIntrinsicScrollMode] = useState(false);
const scrollCountRef = useRef(0);
const scrollMeasuring = useSharedValue(false);
const hasScrollView = scrollCount > 0;
const hasHeader = Boolean(headerTitle);
const metricsRef = useRef({
frameHeight: null as number | null,
bodyHeight: null as number | null,
contentEndY: null as number | null,
scrollLayoutHeight: null as number | null,
scrollContentHeight: null as number | null,
headerHeight: hasHeader ? (null as number | null) : 0,
staticHeight: null as number | null,
intrinsicScrollHeight: false,
measuring: false,
});
useEffect(() => {
if (!hasHeader) {
metricsRef.current.headerHeight = 0;
} else {
metricsRef.current.headerHeight = null;
}
}, [hasHeader]);
const canvasContentHeight = useSharedValue(0);
const commitContentHeight = useCallback(
(height: number) => {
if (!enableDynamicSizing || !(height > 0)) return;
canvasContentHeight.value = height;
animatedLayoutState.modify((state) => {
"worklet";
state.contentHeight = height;
return state;
});
metricsRef.current.measuring = false;
scrollMeasuring.value = false;
},
[animatedLayoutState, canvasContentHeight, enableDynamicSizing, scrollMeasuring],
);
// MenuSheetCanvasBody owns animatedLayoutState.contentHeight for both static and scrollable
// raw-canvas sheets. Guard against Gorhom BottomSheetScrollView's internal onContentSizeChange
// setter writing raw row height without header/footer/viewport framing.
useAnimatedReaction(
() => animatedLayoutState.get().contentHeight,
(layoutHeight) => {
const owned = canvasContentHeight.value;
if (enableDynamicSizing && owned > 0 && layoutHeight !== owned) {
animatedLayoutState.modify((state) => {
"worklet";
state.contentHeight = owned;
return state;
});
}
},
[animatedLayoutState, canvasContentHeight, enableDynamicSizing],
);
const tryCommitStatic = useCallback(() => {
if (
scrollCountRef.current > 0 &&
(!metricsRef.current.intrinsicScrollHeight || metricsRef.current.measuring)
) {
return;
}
const { headerHeight, staticHeight } = metricsRef.current;
if (headerHeight === null || staticHeight === null) return;
commitContentHeight(
Math.min(
maxHeight,
resolveSheetCanvasStaticContentHeight({
headerHeight,
staticHeight,
safeAreaBottom: safeAreaInsets.bottom,
}),
),
);
}, [commitContentHeight, maxHeight, safeAreaInsets.bottom]);
const tryCommitScroll = useCallback(() => {
const {
frameHeight,
bodyHeight,
contentEndY,
scrollLayoutHeight,
scrollContentHeight,
intrinsicScrollHeight,
measuring,
} = metricsRef.current;
// Once intrinsic mode settles, handleStaticLayout owns size changes (such as a growing
// footer beside a fixed-height scroller) until the next remeasure pass. Re-assert canvas
// height on scroller callbacks so Gorhom's content-size setter never takes over the sheet.
if (intrinsicScrollHeight && !measuring) {
tryCommitStatic();
return;
}
if (
frameHeight === null ||
bodyHeight === null ||
contentEndY === null ||
scrollLayoutHeight === null ||
scrollContentHeight === null
) {
return;
}
const resolved = resolveSheetCanvasScrollContentHeight({
frameHeight,
bodyHeight,
contentEndY,
scrollLayoutHeight,
scrollContentHeight,
intrinsicScrollHeight,
measuring,
});
if (resolved.intrinsicScrollHeight && !metricsRef.current.intrinsicScrollHeight) {
metricsRef.current.staticHeight = null;
}
metricsRef.current.intrinsicScrollHeight = resolved.intrinsicScrollHeight;
setIntrinsicScrollMode(resolved.intrinsicScrollHeight);
commitContentHeight(resolved.height);
}, [commitContentHeight, tryCommitStatic]);
const measureEpochRef = useRef(0);
const bodyRef = useRef<View | null>(null);
const contentEndRef = useRef<View | null>(null);
const measureContentEnd = useCallback(() => {
if (scrollCountRef.current === 0) return;
if (metricsRef.current.intrinsicScrollHeight && !metricsRef.current.measuring) return;
const body = bodyRef.current;
const marker = contentEndRef.current;
if (!body || !marker) return;
const epoch = measureEpochRef.current;
marker.measureLayout(body, (_left, top) => {
if (epoch !== measureEpochRef.current || scrollCountRef.current === 0) return;
metricsRef.current.contentEndY = top;
tryCommitScroll();
});
}, [tryCommitScroll]);
const reportScrollMetrics = useMemo<SheetScrollMetricsReporter>(
() => ({
registerScroll() {
scrollCountRef.current += 1;
if (scrollCountRef.current === 1) {
measureEpochRef.current += 1;
metricsRef.current.intrinsicScrollHeight = false;
metricsRef.current.staticHeight = null;
metricsRef.current.measuring = true;
scrollMeasuring.value = true;
setIntrinsicScrollMode(false);
}
setScrollCount(scrollCountRef.current);
return () => {
scrollCountRef.current = Math.max(0, scrollCountRef.current - 1);
if (scrollCountRef.current === 0) {
measureEpochRef.current += 1;
metricsRef.current.intrinsicScrollHeight = false;
metricsRef.current.measuring = false;
scrollMeasuring.value = false;
setIntrinsicScrollMode(false);
}
setScrollCount(scrollCountRef.current);
};
},
reportLayoutHeight(height: number) {
metricsRef.current.scrollLayoutHeight = height;
measureContentEnd();
tryCommitScroll();
},
reportContentHeight(height: number) {
metricsRef.current.scrollContentHeight = height;
tryCommitScroll();
},
remeasure() {
if (scrollCountRef.current === 0) return;
measureEpochRef.current += 1;
metricsRef.current.intrinsicScrollHeight = false;
metricsRef.current.staticHeight = null;
metricsRef.current.measuring = true;
setIntrinsicScrollMode(false);
if ((metricsRef.current.frameHeight ?? 0) < maxHeight - 1) {
metricsRef.current.frameHeight = null;
metricsRef.current.bodyHeight = null;
metricsRef.current.contentEndY = null;
// Retain the previous scrollLayoutHeight until reportLayoutHeight fires so switching to
// automatic sizing at the same pixel height never leaves tryCommitScroll blocked.
scrollMeasuring.value = true;
return;
}
scrollMeasuring.value = true;
measureContentEnd();
},
}),
[maxHeight, measureContentEnd, scrollMeasuring, tryCommitScroll],
);
useEffect(() => {
if (!hasScrollView && scrollCountRef.current === 0) {
metricsRef.current.intrinsicScrollHeight = false;
metricsRef.current.measuring = false;
metricsRef.current.scrollLayoutHeight = null;
metricsRef.current.scrollContentHeight = null;
setIntrinsicScrollMode(false);
tryCommitStatic();
}
}, [hasScrollView, tryCommitStatic]);
const handleFrameLayout = useCallback(
(event: LayoutChangeEvent) => {
metricsRef.current.frameHeight = event.nativeEvent.layout.height;
if (hasScrollView) tryCommitScroll();
},
[hasScrollView, tryCommitScroll],
);
const handleBodyLayout = useCallback(
(event: LayoutChangeEvent) => {
metricsRef.current.bodyHeight = event.nativeEvent.layout.height;
if (hasScrollView) {
measureContentEnd();
tryCommitScroll();
}
},
[hasScrollView, measureContentEnd, tryCommitScroll],
);
const handleContentEndLayout = useCallback(
(event: LayoutChangeEvent) => {
metricsRef.current.contentEndY = event.nativeEvent.layout.y;
if (hasScrollView) tryCommitScroll();
},
[hasScrollView, tryCommitScroll],
);
const handleHeaderLayout = useCallback(
(event: LayoutChangeEvent) => {
metricsRef.current.headerHeight = event.nativeEvent.layout.height;
tryCommitStatic();
},
[tryCommitStatic],
);
const handleStaticLayout = useCallback(
(event: LayoutChangeEvent) => {
metricsRef.current.staticHeight = event.nativeEvent.layout.height;
tryCommitStatic();
},
[tryCommitStatic],
);
const scrollFrameAnimatedStyle = useAnimatedStyle(() => {
if (!hasScrollView) return { height: undefined };
const { containerHeight, handleHeight } = animatedLayoutState.get();
const lowestDetentPosition = animatedDetentsState.get().detents?.[0];
if (
containerHeight <= 0 ||
handleHeight < 0 ||
lowestDetentPosition === undefined ||
scrollMeasuring.value
) {
return { height: maxHeight };
}
const keyboard = animatedKeyboardState.get();
return {
height: getBottomSheetVisibleContentHeight({
containerHeight,
handleHeight,
contentPosition: animatedPosition.get(),
lowestDetentPosition,
keyboardHeight: keyboard.heightWithinContainer,
isKeyboardVisible: keyboard.status === KEYBOARD_STATUS.SHOWN,
}),
};
}, [
animatedDetentsState,
animatedKeyboardState,
animatedLayoutState,
animatedPosition,
hasScrollView,
maxHeight,
scrollMeasuring,
]);
const frameStyle = useMemo(
() => [
hasScrollView ? styles.rawSheetScrollFrame : styles.rawSheetFrameAuto,
{ maxHeight },
hasScrollView ? { height: maxHeight } : undefined,
scrollFrameAnimatedStyle,
],
[hasScrollView, maxHeight, scrollFrameAnimatedStyle],
);
const useIntrinsicMeasure = !hasScrollView || intrinsicScrollMode;
const insetStyle = hasScrollView ? styles.rawSheetFrameFilled : styles.rawSheetFrameAuto;
const bodyContainerStyle = hasScrollView ? styles.rawSheetBodyFilled : styles.rawSheetBodyClipped;
const staticMeasureStyle = useIntrinsicMeasure
? styles.rawStaticMeasure
: styles.rawSheetBodyFilled;
// Keep the same React element tree mounted across !hasScrollView <-> hasScrollView so lazily
// revealing a ScrollView/FlatList inside an open popover never remounts plugin state.
const content = (
<Animated.View style={frameStyle}>
<BottomSafeAreaInset
dataSet={dataSet}
onLayout={handleFrameLayout}
style={insetStyle}
testID={testID ? `${testID}-content` : undefined}
>
{headerTitle ? (
<View onLayout={handleHeaderLayout}>
<MenuSheetHeader title={headerTitle} onBack={onHeaderBack} trailing={headerTrailing} />
</View>
) : null}
<View ref={bodyRef} onLayout={handleBodyLayout} style={bodyContainerStyle}>
<View
onLayout={useIntrinsicMeasure ? handleStaticLayout : undefined}
style={staticMeasureStyle}
>
<MenuPage
depth={depth}
raw={useIntrinsicMeasure ? true : "fill"}
contentEndRef={contentEndRef}
onContentEndLayout={handleContentEndLayout}
>
{children}
</MenuPage>
</View>
</View>
</BottomSafeAreaInset>
</Animated.View>
);
if (!attachContentDrag) return content;
return (
<BottomSheetScope
attachContentDrag={attachContentDrag}
reportScrollMetrics={reportScrollMetrics}
>
{content}
</BottomSheetScope>
);
}
/**
* Rendered on the far side of the sheet's portal so it clears the screen's bottom inset, not the
* one left where the menu was opened: inside a sheet tab, none is.
@@ -534,6 +978,30 @@ const styles = StyleSheet.create((theme) => ({
flex: 1,
minHeight: 0,
},
rawSheetFrameAuto: {
flexShrink: 1,
minHeight: 0,
},
rawSheetScrollFrame: {
minHeight: 0,
overflow: "hidden",
},
rawSheetFrameFilled: {
flex: 1,
minHeight: 0,
},
rawSheetBodyFilled: {
flex: 1,
minHeight: 0,
},
rawSheetBodyClipped: {
flexShrink: 1,
minHeight: 0,
overflow: "hidden",
},
rawStaticMeasure: {
flexShrink: 0,
},
sheetHeader: {
flexDirection: "row",
alignItems: "center",
@@ -8,7 +8,11 @@ import {
import { BottomSheetScrollView, BottomSheetFlatList } from "@gorhom/bottom-sheet";
import { GestureDetector } from "react-native-gesture-handler";
import { usePanelAwareHorizontalScrollGesture } from "@/mobile-panels/gestures";
import { useAttachSheetContentDrag, useIsInsideBottomSheet } from "./bottom-sheet-scope";
import {
useAttachSheetContentDrag,
useIsInsideBottomSheet,
useSheetScrollMetricsProps,
} from "./bottom-sheet-scope";
import { withContentDrag } from "./content-drag";
// Gorhom forwards to the RN FlatList and ScrollView instances. Its published ref types disagree
@@ -20,6 +24,12 @@ const SheetFlatList = BottomSheetFlatList as unknown as typeof NativeFlatList;
export const ScrollView = forwardRef<NativeScrollView, ScrollViewProps>(
function ScrollView(props, ref) {
const inSheet = useIsInsideBottomSheet();
const metricsProps = useSheetScrollMetricsProps(
inSheet && !props.horizontal,
props.onLayout,
props.onContentSizeChange,
props.style,
);
if (props.horizontal) {
return (
<HorizontalScrollGesture>
@@ -27,7 +37,7 @@ export const ScrollView = forwardRef<NativeScrollView, ScrollViewProps>(
</HorizontalScrollGesture>
);
}
if (inSheet) return <SheetScrollView {...props} ref={ref} />;
if (inSheet) return <SheetScrollView {...props} {...metricsProps} ref={ref} />;
return <PageScrollView {...props} ref={ref} />;
},
);
@@ -47,6 +57,12 @@ const SheetScrollView = withContentDrag<ScrollViewProps, NativeScrollView>(
function PresentationFlatList<Item>(props: FlatListProps<Item>, ref: Ref<NativeFlatList<Item>>) {
const inSheet = useIsInsideBottomSheet();
const metricsProps = useSheetScrollMetricsProps(
inSheet && !props.horizontal,
props.onLayout,
props.onContentSizeChange,
props.style,
);
if (props.horizontal) {
return (
<HorizontalScrollGesture>
@@ -54,7 +70,7 @@ function PresentationFlatList<Item>(props: FlatListProps<Item>, ref: Ref<NativeF
</HorizontalScrollGesture>
);
}
if (inSheet) return <SheetFlatList {...props} ref={ref} />;
if (inSheet) return <SheetFlatList {...props} {...metricsProps} ref={ref} />;
return <NativeFlatList {...props} ref={ref} />;
}
@@ -1,3 +1,38 @@
// Web dialogs use ordinary scrolling at every breakpoint. Keep native gesture
// dependencies out of this module's import graph.
export { ScrollView, FlatList } from "react-native";
import { forwardRef, type ReactElement, type Ref } from "react";
import {
FlatList as NativeFlatList,
ScrollView as NativeScrollView,
type FlatListProps,
type ScrollViewProps,
} from "react-native";
import { useIsInsideBottomSheet, useSheetScrollMetricsProps } from "./bottom-sheet-scope";
export const ScrollView = forwardRef<NativeScrollView, ScrollViewProps>(
function ScrollView(props, ref) {
const inSheet = useIsInsideBottomSheet();
const metricsProps = useSheetScrollMetricsProps(
inSheet && !props.horizontal,
props.onLayout,
props.onContentSizeChange,
props.style,
);
return <NativeScrollView {...props} {...metricsProps} ref={ref} />;
},
);
function WebFlatList<Item>(props: FlatListProps<Item>, ref: Ref<NativeFlatList<Item>>) {
const inSheet = useIsInsideBottomSheet();
const metricsProps = useSheetScrollMetricsProps(
inSheet && !props.horizontal,
props.onLayout,
props.onContentSizeChange,
props.style,
);
return <NativeFlatList {...props} {...metricsProps} ref={ref} />;
}
export const FlatList = forwardRef(WebFlatList) as <Item>(
props: FlatListProps<Item> & { ref?: Ref<NativeFlatList<Item>> },
) => ReactElement;
@@ -40,6 +40,8 @@ const backdropColorMappings: Record<SurfaceBackdrop, (theme: Theme) => { color:
surface0: (theme) => ({ color: theme.colors.surface0 }),
surface1: (theme) => ({ color: theme.colors.surface1 }),
surface2: (theme) => ({ color: theme.colors.surface2 }),
surfaceHover: (theme) => ({ color: theme.colors.surfaceHover }),
surfaceSelected: (theme) => ({ color: theme.colors.surfaceSelected }),
surfaceSidebar: (theme) => ({ color: theme.colors.surfaceSidebar }),
surfaceSidebarHover: (theme) => ({ color: theme.colors.surfaceSidebarHover }),
surfaceSidebarSelected: (theme) => ({ color: theme.colors.surfaceSidebarSelected }),
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { Image } from "expo-image";
import { View, type StyleProp, type ViewStyle } from "react-native";
import { Platform, View, type StyleProp, type ViewStyle } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import type { ViewportFitOptions, ViewportSize } from "./geometry";
import { measureImage } from "./image-size";
@@ -84,7 +84,9 @@ export function ZoomableImage({
<ViewportImage
// No transition, so the image appears together with its toolbar.
transition={null}
contentFit="contain"
// The viewport already fits the image's aspect ratio. On Android, fill selects
// Expo Image's bitmap size cap while preserving detail below that cap for zoom.
contentFit={Platform.OS === "android" ? "fill" : "contain"}
onError={onError}
onLoad={handleLoad}
source={source}
+58
View File
@@ -1,4 +1,8 @@
import { describe, expect, it, vi } from "vitest";
import { createLocalFileAttachmentStore } from "@/attachments/local-file-attachment-store";
import { garbageCollectAttachments, persistAttachmentFromBytes } from "@/attachments/service";
import { __setAttachmentStoreForTests } from "@/attachments/store";
import { createTestAttachmentFileSystem } from "@/attachments/test-attachment-file-system";
import type {
AgentAttachment,
ForgeSearchItem,
@@ -739,6 +743,60 @@ describe("dispatchComposerAgentMessage", () => {
});
describe("enqueueComposerAgentMessage", () => {
it("keeps all queued images available when garbage collection runs during upload", async () => {
const fileSystem = createTestAttachmentFileSystem();
const store = createLocalFileAttachmentStore({
storageType: "native-file",
baseDirectoryName: "attachments",
fileSystem,
resolvePreviewUrl: async (attachment) => attachment.storageKey,
});
__setAttachmentStoreForTests(store);
try {
const first = await persistAttachmentFromBytes({
id: "first",
bytes: new Uint8Array([1]),
mimeType: "image/png",
});
const second = await persistAttachmentFromBytes({
id: "second",
bytes: new Uint8Array([2]),
mimeType: "image/png",
});
const client = createFakeSendClient();
await enqueueComposerAgentMessage({
client: {
...client,
async uploadFile(input) {
if (client.uploadCalls.length === 0) {
// Draft has already been cleared before the queue action runs.
await garbageCollectAttachments({ referencedIds: new Set() });
}
return await client.uploadFile(input);
},
},
agentId: "agent",
text: "follow up",
attachments: [
{ kind: "image", metadata: first },
{ kind: "image", metadata: second },
],
});
expect(client.uploadCalls.map(({ bytes }) => Array.from(bytes))).toEqual([[1], [2]]);
expect(client.calls[0]?.options).toMatchObject({
activeTurnBehavior: "queue",
attachments: [{ role: "image" }, { role: "image" }],
});
await garbageCollectAttachments({ referencedIds: new Set() });
expect(fileSystem.files.size).toBe(0);
} finally {
__setAttachmentStoreForTests(null);
}
});
it("hands a trimmed message to the host queue without adding a timeline row", async () => {
const client = createFakeSendClient();
const review = reviewWorkspaceAttachment("Queued review.");
+5 -3
View File
@@ -1,5 +1,5 @@
import type { SelectedFile } from "@/attachments/selected-file";
import { prepareImageAttachmentsForSend } from "@/attachments/service";
import { prepareImageAttachmentsForSend, withRetainedAttachments } from "@/attachments/service";
import { FILE_UPLOAD_MAX_BYTES } from "@/attachments/upload-limit";
import type { AgentProvider, ProviderOptions } from "@getpaseo/protocol/agent-types";
import { optimisticEnqueueAgentMessage } from "@/agent-queue";
@@ -324,8 +324,10 @@ async function prepareImagePayload(
input: Pick<DispatchComposerAgentMessageInput, "client" | "uploadImages">,
images: AttachmentMetadata[],
) {
if (input.uploadImages) return { attachments: await input.uploadImages(images) };
return await prepareImageAttachmentsForSend({ client: input.client, images });
return await withRetainedAttachments(images, async () => {
if (input.uploadImages) return { attachments: await input.uploadImages(images) };
return await prepareImageAttachmentsForSend({ client: input.client, images });
});
}
/** Images the host already holds render as images, the way its timeline echo does. */
+138
View File
@@ -1,4 +1,13 @@
import { describe, expect, it, vi } from "vitest";
import { createLocalFileAttachmentStore } from "@/attachments/local-file-attachment-store";
import {
garbageCollectAttachments,
persistAttachmentFromBytes,
readAttachmentBytes,
} from "@/attachments/service";
import { __setAttachmentStoreForTests } from "@/attachments/store";
import { createTestAttachmentFileSystem } from "@/attachments/test-attachment-file-system";
import type { UserComposerAttachment } from "@/attachments/types";
import { submitAgentInput } from "./submit";
function createDeferredPromise<T>() {
@@ -333,4 +342,133 @@ describe("submitAgentInput", () => {
});
expect(clearDraft).toHaveBeenCalledWith("sent");
});
it("keeps queued image files on disk when draft clearing schedules GC and restores them intact if queueing fails", async () => {
const fileSystem = createTestAttachmentFileSystem();
const store = createLocalFileAttachmentStore({
storageType: "native-file",
baseDirectoryName: "attachments",
fileSystem,
resolvePreviewUrl: async (attachment) => attachment.storageKey,
});
__setAttachmentStoreForTests(store);
try {
const first = await persistAttachmentFromBytes({
id: "queued-1",
bytes: new Uint8Array([10, 20]),
mimeType: "image/png",
});
const second = await persistAttachmentFromBytes({
id: "queued-2",
bytes: new Uint8Array([30, 40]),
mimeType: "image/png",
});
let draftAttachments: UserComposerAttachment[] = [
{ kind: "image", metadata: first },
{ kind: "image", metadata: second },
];
let revision = 0;
const pendingGcs: Promise<void>[] = [];
const runScheduledGc = async () => {
await Promise.resolve();
const referencedIds = new Set<string>();
for (const entry of draftAttachments) {
if (entry.kind === "image") {
referencedIds.add(entry.metadata.id);
}
}
await garbageCollectAttachments({ referencedIds });
};
const scheduleGc = () => {
pendingGcs.push(runScheduledGc());
};
const result = await submitAgentInput<UserComposerAttachment>({
message: "queued follow-up",
attachments: draftAttachments,
isAgentRunning: true,
canSubmit: true,
queueMessage: async ({ attachments }) => {
// Yield to let the microtask GC triggered by setAttachments([]) run before reads.
await Promise.all(pendingGcs);
for (const attachment of attachments) {
if (attachment.kind === "image") {
await readAttachmentBytes(attachment.metadata);
}
}
throw new Error("Host disconnected");
},
submitMessage: vi.fn(),
getDraftRevision: () => revision,
clearDraft: vi.fn(),
setUserInput: vi.fn(),
setAttachments: (next) => {
draftAttachments = next;
revision += 1;
scheduleGc();
},
setSendError: vi.fn(),
setIsProcessing: vi.fn(),
});
await Promise.all(pendingGcs);
expect(result).toBe("failed");
expect(draftAttachments).toHaveLength(2);
await expect(readAttachmentBytes(first)).resolves.toEqual(new Uint8Array([10, 20]));
await expect(readAttachmentBytes(second)).resolves.toEqual(new Uint8Array([30, 40]));
} finally {
__setAttachmentStoreForTests(null);
}
});
it("releases queued image holds after a successful queue submission so unreferenced files can be collected", async () => {
const fileSystem = createTestAttachmentFileSystem();
const store = createLocalFileAttachmentStore({
storageType: "native-file",
baseDirectoryName: "attachments",
fileSystem,
resolvePreviewUrl: async (attachment) => attachment.storageKey,
});
__setAttachmentStoreForTests(store);
try {
const image = await persistAttachmentFromBytes({
id: "queued-success",
bytes: new Uint8Array([7, 8, 9]),
mimeType: "image/png",
});
let draftAttachments: UserComposerAttachment[] = [{ kind: "image", metadata: image }];
let revision = 0;
const result = await submitAgentInput<UserComposerAttachment>({
message: "queued ok",
attachments: draftAttachments,
isAgentRunning: true,
canSubmit: true,
queueMessage: async () => {
await garbageCollectAttachments({ referencedIds: new Set() });
await expect(readAttachmentBytes(image)).resolves.toEqual(new Uint8Array([7, 8, 9]));
},
submitMessage: vi.fn(),
getDraftRevision: () => revision,
clearDraft: vi.fn(),
setUserInput: vi.fn(),
setAttachments: (next) => {
draftAttachments = next;
revision += 1;
},
setSendError: vi.fn(),
setIsProcessing: vi.fn(),
});
expect(result).toBe("queued");
await garbageCollectAttachments({ referencedIds: new Set() });
expect(fileSystem.files.size).toBe(0);
} finally {
__setAttachmentStoreForTests(null);
}
});
});
+74 -26
View File
@@ -1,7 +1,42 @@
import { retainAttachmentForGarbageCollection } from "@/attachments/gc-retention";
import { i18n } from "@/i18n/i18next";
export type AgentInputSubmitResult = "noop" | "queued" | "submitted" | "failed";
function collectManagedAttachmentIds(attachments: readonly unknown[]): string[] {
const ids: string[] = [];
for (const attachment of attachments) {
if (typeof attachment !== "object" || attachment === null || !("kind" in attachment)) {
continue;
}
if (
attachment.kind === "image" &&
"metadata" in attachment &&
typeof attachment.metadata === "object" &&
attachment.metadata !== null &&
"id" in attachment.metadata &&
typeof attachment.metadata.id === "string"
) {
ids.push(attachment.metadata.id);
continue;
}
if (
attachment.kind === "browser_element" &&
"attachment" in attachment &&
typeof attachment.attachment === "object" &&
attachment.attachment !== null &&
"screenshot" in attachment.attachment &&
typeof attachment.attachment.screenshot === "object" &&
attachment.attachment.screenshot !== null &&
"id" in attachment.attachment.screenshot &&
typeof attachment.attachment.screenshot.id === "string"
) {
ids.push(attachment.attachment.screenshot.id);
}
}
return ids;
}
export interface AgentInputSubmitActionInput<TAttachment> {
message: string;
attachments: TAttachment[];
@@ -46,35 +81,48 @@ export async function submitAgentInput<TAttachment>(
const shouldQueue = input.isAgentRunning && !input.forceSend;
// Clear immediately so the submitted timeline row and composer state stay in sync.
if (shouldClearOnSubmit) {
input.setUserInput("");
input.setAttachments([]);
}
const submittedRevision = shouldClearOnSubmit ? input.getDraftRevision() : null;
input.setSendError(null);
input.setIsProcessing(true);
// Retain local attachment files before clearing the draft so scheduled GC cannot
// delete them while delivery is in flight (especially queued sends that add no
// timeline row) or before a failed send restores them to the composer.
const releaseAttachments = collectManagedAttachmentIds(attachments).map((id) =>
retainAttachmentForGarbageCollection(id),
);
try {
const deliver = shouldQueue ? input.queueMessage : input.submitMessage;
await deliver({ message: trimmedMessage, attachments });
if (!shouldClearOnSubmit || input.getDraftRevision() === submittedRevision) {
input.clearDraft("sent");
// Clear immediately so the submitted timeline row and composer state stay in sync.
if (shouldClearOnSubmit) {
input.setUserInput("");
input.setAttachments([]);
}
input.setIsProcessing(false);
return shouldQueue ? "queued" : "submitted";
} catch (error) {
input.onSubmitError?.(error);
if (shouldClearOnSubmit && input.getDraftRevision() === submittedRevision) {
input.setUserInput(trimmedMessage);
input.setAttachments(attachments);
const submittedRevision = shouldClearOnSubmit ? input.getDraftRevision() : null;
input.setSendError(null);
input.setIsProcessing(true);
try {
const deliver = shouldQueue ? input.queueMessage : input.submitMessage;
await deliver({ message: trimmedMessage, attachments });
if (!shouldClearOnSubmit || input.getDraftRevision() === submittedRevision) {
input.clearDraft("sent");
}
input.setIsProcessing(false);
return shouldQueue ? "queued" : "submitted";
} catch (error) {
input.onSubmitError?.(error);
if (shouldClearOnSubmit && input.getDraftRevision() === submittedRevision) {
input.setUserInput(trimmedMessage);
input.setAttachments(attachments);
}
input.setSendError(
error instanceof Error
? error.message
: (input.failedToSendMessage ?? i18n.t("composer.errors.failedToSend")),
);
input.setIsProcessing(false);
return "failed";
}
} finally {
for (const release of releaseAttachments) {
release();
}
input.setSendError(
error instanceof Error
? error.message
: (input.failedToSendMessage ?? i18n.t("composer.errors.failedToSend")),
);
input.setIsProcessing(false);
return "failed";
}
}
+16 -3
View File
@@ -1,4 +1,11 @@
import { useCallback, useMemo, useState, type ReactElement, type ReactNode } from "react";
import {
useCallback,
useMemo,
useState,
type ReactElement,
type ReactNode,
type RefObject,
} from "react";
import { Pressable, Text, View } from "react-native";
import { GestureDetector } from "react-native-gesture-handler";
import Animated from "react-native-reanimated";
@@ -42,12 +49,18 @@ import { COMPOSER_PILL_CLEARANCE, composerPillStyles } from "./pill-styles";
* or without pills: that keeps the final footer clear, and pills that come and go every turn do not
* move the transcript.
*/
export function ComposerTrackBar({ children }: { children: ReactNode }): ReactElement {
export function ComposerTrackBar({
children,
trackViewportRef,
}: {
children: ReactNode;
trackViewportRef?: RefObject<View | null>;
}): ReactElement {
const scrollGesture = usePanelAwareHorizontalScrollGesture();
const scrollBoundary = useHorizontalScrollBoundary();
return (
<View style={styles.bar} dataSet={CHAT_COLUMN_RAIL_DATASET} pointerEvents="box-none">
<View style={styles.trackViewport} pointerEvents="box-none">
<View ref={trackViewportRef} style={styles.trackViewport} pointerEvents="box-none">
<GestureDetector gesture={scrollGesture}>
<Animated.ScrollView
testID="composer-track-scroll"
+9 -38
View File
@@ -1,6 +1,4 @@
import { usePaneContext } from "@/panels/pane-context";
import { useCallback, useEffect, useMemo, useState } from "react";
import type { PluginFile, PluginTab } from "@getpaseo/plugin/client";
import { useCallback, useMemo } from "react";
import { Text, View } from "react-native";
import { Download } from "lucide-react-native";
import { StyleSheet } from "react-native-unistyles";
@@ -9,11 +7,11 @@ import { Button } from "@/components/ui/button";
import { useRetainedPanelActive } from "@/components/retained-panel";
import { useFileHandle, useFileHandleSnapshot } from "@/file-panels/file";
import { FilePanelLoading } from "@/file-panels/loading";
import { FilePanelPicker, FilePanelView, useFilePanelChoice, type FilePanel } from "@/file-panels";
import { FilePanelPicker, FilePanelView, useFilePanelChoice } from "@/file-panels";
import { resolveFilePreviewReadTarget } from "@/file-explorer/preview-target";
import { useFileDownload } from "@/hooks/use-file-download";
import { useAppActivelyVisible } from "@/hooks/use-app-visible";
import { usePublishPanelInstanceAttributes } from "@/panels/panel-instance-attributes";
import { getComponentMountKey } from "@/panels/panel-instance-attributes";
import { useHostRuntimeConnectionStatus } from "@/runtime/host-runtime";
import { buildAbsoluteExplorerPath } from "@/utils/explorer-paths";
import { formatFileSize } from "@/utils/format-file-size";
@@ -79,8 +77,6 @@ export function FilePane({
presentable: isActive,
lineNavigation: location.lineStart ? navigationRevision : null,
});
const [modified, setModified] = useState(false);
usePublishPanelInstanceAttributes({ modified, suspendPendingSave: handle?.holdWrites });
const panelLocation = useMemo(
() => ({
lineStart: location.lineStart,
@@ -121,16 +117,19 @@ export function FilePane({
</>
);
} else {
const panelMountKey = panel.builtin
? `${panel.id}:${targetKey}`
: `${panel.id}:${targetKey}:${getComponentMountKey(panel.contribution.Component)}`;
return (
<View style={styles.container} testID="workspace-file-pane">
<FilePanelPicker choice={choice} />
<MountedFilePanel
key={`${panel.id}:${targetKey}`}
<FilePanelView
key={panelMountKey}
panel={panel}
file={handle.file}
params={panelLocation}
revision={navigationRevision}
onModifiedChange={setModified}
suspendPendingSave={handle.holdWrites}
/>
</View>
);
@@ -142,34 +141,6 @@ export function FilePane({
);
}
/** One panel mount. Its tab reports unsaved changes until the panel unmounts. */
function MountedFilePanel({
panel,
file,
params,
revision,
onModifiedChange,
}: {
panel: FilePanel;
file: PluginFile;
params: { path: string; lineStart?: number; lineEnd?: number };
revision: number;
onModifiedChange: (modified: boolean) => void;
}) {
const { tabId, state, setCurrentTabState } = usePaneContext();
const tab = useMemo<PluginTab>(
() => ({
id: tabId,
setModified: onModifiedChange,
state,
setState: setCurrentTabState,
}),
[tabId, onModifiedChange, state, setCurrentTabState],
);
useEffect(() => () => onModifiedChange(false), [onModifiedChange]);
return <FilePanelView panel={panel} file={file} tab={tab} params={params} revision={revision} />;
}
const styles = StyleSheet.create((theme) => ({
container: {
flex: 1,
+7 -6
View File
@@ -1,4 +1,5 @@
import { useWorkspace, useFileUrl, type PluginFilePanelProps } from "@getpaseo/plugin/client";
import { useWorkspace, useFileUrl } from "@getpaseo/plugin/client";
import type { BuiltinFilePanelProps } from "./panels";
import { useCallback, useState } from "react";
import { ScrollView, Text, View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
@@ -11,17 +12,17 @@ import { TextFilePanel, type TextFilePreviewProps } from "./source/panel";
import type { RenderingFilePanel, SourceFilePanel } from "./catalog";
/** Source: the text file panel with no Preview, for text files no other built-in panel claims. */
function SourcePanel(props: PluginFilePanelProps) {
function SourcePanel(props: BuiltinFilePanelProps) {
return <TextFilePanel {...props} />;
}
/** Markdown: the text file panel with the rendered document as its Preview. */
function MarkdownPanel(props: PluginFilePanelProps) {
function MarkdownPanel(props: BuiltinFilePanelProps) {
return <TextFilePanel {...props} preview={MarkdownPreview} />;
}
/** HTML: the text file panel with the sandboxed page as its Preview. */
function HtmlPanel(props: PluginFilePanelProps) {
function HtmlPanel(props: BuiltinFilePanelProps) {
return <TextFilePanel {...props} preview={HtmlPreview} />;
}
@@ -58,7 +59,7 @@ function HtmlPreview({ text }: TextFilePreviewProps) {
);
}
function ImagePanel({ file }: PluginFilePanelProps) {
function ImagePanel({ file }: BuiltinFilePanelProps) {
const url = useFileUrl(file);
if (url.status === "loading") return <FilePanelLoading />;
if (url.status === "error") return <FilePanelError message={url.error.message} />;
@@ -83,7 +84,7 @@ const components = {
export function BuiltinFilePanelView({
panel,
...props
}: PluginFilePanelProps & { panel: RenderingFilePanel | SourceFilePanel }) {
}: BuiltinFilePanelProps & { panel: RenderingFilePanel | SourceFilePanel }) {
const Component = components[panel.id];
return <Component {...props} />;
}
+11 -3
View File
@@ -57,6 +57,7 @@ export function useFilePanelChoice(input: {
const NO_CHOICE_SNAPSHOT: FilePanelChoiceSnapshot<FilePanel> = {
targetKey: null,
activePanel: null,
chosenPanelId: null,
picker: null,
openWith: null,
@@ -65,10 +66,17 @@ const subscribeNothing = () => () => {};
const getNoChoiceSnapshot = () => NO_CHOICE_SNAPSHOT;
/** The choice of an open file tab, looked up by the tab's identity, for chrome outside its pane. */
export function useTabFilePanelChoice(identity: PanelInstanceIdentity): FilePanelChoice | null {
const { serverId, workspaceId, tabId } = identity;
export function useTabFilePanelChoice(
identity: PanelInstanceIdentity | null,
): FilePanelChoice | null {
const serverId = identity?.serverId ?? null;
const workspaceId = identity?.workspaceId ?? null;
const tabId = identity?.tabId ?? null;
const getSnapshot = useCallback(
() => getFilePanelChoice({ serverId, workspaceId, tabId }),
() =>
serverId && workspaceId && tabId
? getFilePanelChoice({ serverId, workspaceId, tabId })
: null,
[serverId, tabId, workspaceId],
);
return useSyncExternalStore(subscribeFilePanelChoices, getSnapshot, getSnapshot);
@@ -204,4 +204,21 @@ describe("FilePanelChoiceModel", () => {
tab.render();
expect(tab.picker()).not.toBeNull();
});
it("tracks activePanel in snapshot for single-candidate and switched file panels", () => {
const binaryPdf: FilePanelCandidate = {
id: "plugin:pdf/viewer",
builtin: false,
files: { extensions: ["pdf"] },
};
const single = openTab({}, [binaryPdf], { path: "doc.pdf" });
expect(single.model.getSnapshot().openWith).toBeNull();
expect(single.model.getSnapshot().activePanel).toBe(binaryPdf);
const multi = openTab({});
expect(multi.model.getSnapshot().activePanel?.id).toBe(markdown);
multi.model.openWith(rich.id);
multi.render();
expect(multi.model.getSnapshot().activePanel).toBe(rich);
});
});
+6 -1
View File
@@ -27,6 +27,8 @@ export interface FilePanelOpenWithState<Candidate> {
export interface FilePanelChoiceSnapshot<Candidate> {
targetKey: string | null;
/** The resolved panel currently active for this tab, or null while loading/unavailable. */
activePanel: Candidate | null;
/** The panel picked for this tab open. Resolution prefers it over the association. */
chosenPanelId: string | null;
picker: FilePanelPickerState<Candidate> | null;
@@ -49,6 +51,7 @@ export function chosenPanelFor(
const EMPTY: FilePanelChoiceSnapshot<never> = {
targetKey: null,
activePanel: null,
chosenPanelId: null,
picker: null,
openWith: null,
@@ -114,7 +117,8 @@ export class FilePanelChoiceModel<Candidate extends FilePanelCandidate> {
};
}
}
this.publish({ ...current, openWith, picker });
const activePanel = source.resolution?.panel ?? null;
this.publish({ ...current, activePanel, openWith, picker });
}
selectInPicker(panelId: string): void {
@@ -163,6 +167,7 @@ export class FilePanelChoiceModel<Candidate extends FilePanelCandidate> {
const current = this.snapshot;
if (
current.targetKey === next.targetKey &&
current.activePanel === next.activePanel &&
current.chosenPanelId === next.chosenPanelId &&
current.picker === next.picker &&
current.openWith === next.openWith
@@ -1,5 +1,6 @@
import type { DaemonClient, FileReadResult } from "@getpaseo/client/internal/daemon-client";
import type { FileVersion } from "@getpaseo/protocol/messages";
import { retainAttachmentForGarbageCollection } from "@/attachments/gc-retention";
import {
persistAttachmentFromBytes,
releaseAttachmentPreviewUrl,
@@ -84,10 +85,18 @@ export function createDaemonFileSession(
mimeType,
fileName: getFileNameFromPath(target.path),
});
const url = await resolveAttachmentPreviewUrl(attachment);
const releaseRetention = retainAttachmentForGarbageCollection(attachment.id);
let url: string;
try {
url = await resolveAttachmentPreviewUrl(attachment);
} catch (error) {
releaseRetention();
throw error;
}
return {
url,
release() {
releaseRetention();
void releaseAttachmentPreviewUrl({ attachment, url });
},
};
@@ -46,4 +46,45 @@ describe("withPreviewCsp", () => {
expect(withPreviewCsp(source).endsWith(source)).toBe(true);
});
it("keeps the closed policy when no origins are given", () => {
expect(withPreviewCsp("<p>x</p>")).toContain("connect-src 'none'");
expect(withPreviewCsp("<p>x</p>")).not.toContain("https://");
});
it("opens only the origins it is handed and puts host head markup after the policy", () => {
const output = withPreviewCsp("<p>x</p>", {
origins: {
resourceSources: ["https://cdn.example.com"],
connectSources: ["wss://a.example.com"],
},
head: "<style>x{}</style>",
});
expect(output).toContain(
"script-src 'unsafe-inline' 'unsafe-eval' blob: https://cdn.example.com;",
);
expect(output).toContain("connect-src wss://a.example.com;");
expect(output.indexOf("Content-Security-Policy")).toBeLessThan(
output.indexOf("<style>x{}</style>"),
);
expect(output.endsWith("<style>x{}</style><p>x</p>")).toBe(true);
});
it("refuses unvalidated origin sources containing CSP separators or quotes", () => {
expect(() =>
withPreviewCsp("<p>x</p>", {
origins: { resourceSources: ['https://example.com"'] },
}),
).toThrow();
expect(() =>
withPreviewCsp("<p>x</p>", {
origins: { connectSources: ["https://example.com; script-src *"] },
}),
).toThrow();
expect(() =>
withPreviewCsp("<p>x</p>", {
origins: { resourceSources: ["https://a.example https://b.example"] },
}),
).toThrow();
});
});
@@ -12,21 +12,62 @@
// no parent access, and no way to read any file but itself. Native narrows it
// further in html-preview.tsx, because a WebView can refuse navigation outside CSP — see the
// caveat there on why that is a mitigation rather than a guarantee.
const POLICY = [
"default-src 'none'",
"script-src 'unsafe-inline' 'unsafe-eval' blob:",
"style-src 'unsafe-inline'",
"img-src data: blob:",
"font-src data:",
"media-src data: blob:",
"connect-src 'none'",
"form-action 'none'",
"base-uri 'none'",
"frame-src 'none'",
"object-src 'none'",
].join("; ");
/** Extra origins a caller may open on top of the preview policy. Already validated by the caller. */
export interface PreviewCspOrigins {
/** Added to script-src, style-src, img-src, font-src and media-src. */
resourceSources?: readonly string[];
/** Replaces `connect-src 'none'`. */
connectSources?: readonly string[];
}
const META = `<meta http-equiv="Content-Security-Policy" content="${POLICY}">`;
const UNSAFE_CSP_CHARS = /[\s;,<>"']/;
function isUnsafeCspSource(source: string): boolean {
if (source.length === 0 || UNSAFE_CSP_CHARS.test(source)) return true;
for (let index = 0; index < source.length; index += 1) {
const code = source.charCodeAt(index);
if (code <= 0x1f || code === 0x7f) return true;
}
return false;
}
function assertSafeSources(sources: readonly string[] | undefined): readonly string[] | undefined {
if (!sources) return undefined;
for (const source of sources) {
if (isUnsafeCspSource(source)) {
throw new Error(`Unsafe CSP origin source: ${JSON.stringify(source)}`);
}
}
return sources;
}
function withSources(base: string, sources: readonly string[] | undefined): string {
return sources && sources.length > 0 ? `${base} ${sources.join(" ")}` : base;
}
export function buildPreviewPolicy(origins: PreviewCspOrigins = {}): string {
const resourceSources = assertSafeSources(origins.resourceSources);
const connectSources = assertSafeSources(origins.connectSources);
return [
"default-src 'none'",
withSources("script-src 'unsafe-inline' 'unsafe-eval' blob:", resourceSources),
withSources("style-src 'unsafe-inline'", resourceSources),
withSources("img-src data: blob:", resourceSources),
withSources("font-src data:", resourceSources),
withSources("media-src data: blob:", resourceSources),
connectSources && connectSources.length > 0
? `connect-src ${connectSources.join(" ")}`
: "connect-src 'none'",
"form-action 'none'",
"base-uri 'none'",
"frame-src 'none'",
"object-src 'none'",
].join("; ");
}
function policyMeta(origins?: PreviewCspOrigins): string {
return `<meta http-equiv="Content-Security-Policy" content="${buildPreviewPolicy(origins)}">`;
}
// The policy must reach the parser before any markup the document declares, and it
// only counts if it lands in `<head>` — once the parser has moved on to `<body>`, a
@@ -45,11 +86,18 @@ const META = `<meta http-equiv="Content-Security-Policy" content="${POLICY}">`;
// the parser ignores wherever it appears. Standards mode is guaranteed, the policy
// is always the first element and therefore always in the head, and no part of the
// document has to be parsed to place it.
const PROLOGUE = `<!doctype html>${META}`;
// Left where it is, a BOM would sit mid-document and render as a zero-width space.
const BOM = "\uFEFF";
export function withPreviewCsp(html: string): string {
return PROLOGUE + (html.startsWith(BOM) ? html.slice(BOM.length) : html);
/**
* `head` is host-authored markup (never page content) placed right after the policy, so the policy
* stays the first element. `origins` come from a validator, never straight from a page.
*/
export function withPreviewCsp(
html: string,
options: { origins?: PreviewCspOrigins; head?: string } = {},
): string {
const prologue = `<!doctype html>${policyMeta(options.origins)}${options.head ?? ""}`;
return prologue + (html.startsWith(BOM) ? html.slice(BOM.length) : html);
}
+1
View File
@@ -3,6 +3,7 @@ export type { FilePanel } from "./panels";
export {
useFilePanelChoice,
useFilePanelChoiceSnapshot,
useTabFilePanelChoice,
type FilePanelChoice,
} from "./choice/hook";
export { FilePanelPicker } from "./choice/picker";
+4
View File
@@ -1,8 +1,12 @@
import { useMemo } from "react";
import type { PluginFilePanelProps } from "@getpaseo/plugin/client";
import { useInstalledPlugins } from "@/plugins/registry";
import type { PluginFilePanelContribution, InstalledPlugin } from "@/plugins/types";
import { filePanelCatalog, type RenderingFilePanel, type SourceFilePanel } from "./catalog";
/** Props shared by built-in file panels; excludes plugin-owned capabilities such as `openScreen`. */
export type BuiltinFilePanelProps = Omit<PluginFilePanelProps, "openScreen">;
export interface PluginFilePanel {
id: string;
builtin: false;
@@ -0,0 +1,238 @@
import { createPaseoApi } from "@getpaseo/client";
import { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import type { PluginFilePanelProps } from "@getpaseo/plugin/client";
import { PluginTranslationRuntime } from "@getpaseo/plugin/client/host";
import { QueryClient } from "@tanstack/react-query";
import React, { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { Text, View } from "react-native";
import {
SafeAreaInsetsContext,
useSafeAreaInsets,
type EdgeInsets,
} from "react-native-safe-area-context";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { SheetBottomInset } from "@/components/adaptive-modal-sheet";
import { PaneProvider, type PaneContextValue } from "@/panels/pane-context";
import type { InstalledPlugin } from "@/plugins/types";
import type { PluginFilePanel } from "./panels";
import { PluginFilePanelHost } from "./plugin-host";
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
beforeEach(() => vi.stubGlobal("React", React));
const SERVER_ID = "file-panel-safe-area-server";
const WORKSPACE_ID = "file-panel-safe-area-workspace";
const FRAME_HEIGHT = 600;
const FILL_STYLE = { flex: 1, minHeight: 0 };
const BAR_STYLE = { padding: 12 };
const INSETS_48: EdgeInsets = { top: 24, right: 0, bottom: 48, left: 0 };
const INSETS_34: EdgeInsets = { top: 47, right: 0, bottom: 34, left: 0 };
const INSETS_0: EdgeInsets = { top: 0, right: 0, bottom: 0, left: 0 };
const FILE_PARAMS = { path: "/repo/notes.md" };
const FILE_THEME = {} as PluginFilePanelProps["theme"];
const FILE_HOST = { id: SERVER_ID, label: "local" };
const FILE_LAYOUT = { compact: true, platform: "android" as const };
const noop = () => {};
const fakeDaemon = new DaemonClient({
url: "ws://127.0.0.1:1",
clientId: "file-panel-safe-area-test",
reconnect: { enabled: false },
});
const fakeFile: PluginFilePanelProps["file"] = {
path: "/repo/notes.md",
name: "notes.md",
kind: "text",
size: 12,
mtimeMs: 0,
readText: async () => "hello",
writeText: async () => undefined,
getUrl: async () => "file:///repo/notes.md",
subscribe: () => noop,
} as unknown as PluginFilePanelProps["file"];
const PANE_CONTEXT_VALUE: PaneContextValue = {
serverId: SERVER_ID,
workspaceId: WORKSPACE_ID,
host: "main",
tabId: "file-tab-1",
target: { kind: "file", path: "/repo/notes.md" },
state: null,
openTab: noop,
openPreferredTarget: noop,
closeCurrentTab: noop,
retargetCurrentTab: noop,
setCurrentTabState: noop,
openFileInWorkspace: noop,
openImportSheet: noop,
};
let root: Root | null = null;
let container: HTMLDivElement | null = null;
afterEach(() => {
act(() => root?.unmount());
container?.remove();
root = null;
container = null;
});
function createPluginFilePanel(
Component: React.ComponentType<PluginFilePanelProps>,
): PluginFilePanel {
const contribution = {
id: "notes",
title: "Notes",
icon: "FileText" as const,
files: { extensions: ["md"] },
Component,
};
const plugin: InstalledPlugin = {
id: "test-plugin",
serverId: SERVER_ID,
clientBundle: "",
lifetime: new AbortController(),
locale: "en",
i18n: new PluginTranslationRuntime({ getLocale: () => "en", subscribe: () => noop }),
queryClient: new QueryClient(),
paseo: createPaseoApi(fakeDaemon),
invoke: async () => undefined,
subscribe: () => {
throw new Error("Subscriptions are not used here");
},
cleanup: noop,
settingsScreens: [],
surfaces: [],
sidebarViews: [],
sidebarItems: { header: [], footer: [] },
legacySidebarItems: [],
workspaceRowBadgeItems: [],
filePanels: [contribution],
composerItems: [],
composerPillItems: [],
newWorkspaceItems: [],
workspacePanels: [],
commandCenterItems: [],
clientSlashCommands: [],
attachmentSources: [],
themes: [],
timelineTransformers: [],
timelineRenderers: [],
notificationOpenHandlers: [],
};
return {
id: "plugin:test-plugin/notes",
builtin: false,
files: contribution.files,
plugin,
contribution,
};
}
function mountFilePanel(insets: EdgeInsets, options?: { insideSheet?: boolean }) {
const panel = createPluginFilePanel(function ProbeFilePanel() {
const descendantInsets = useSafeAreaInsets();
return (
<View style={FILL_STYLE}>
<View style={FILL_STYLE}>
<Text testID="file-panel-descendant-insets">
{`${descendantInsets.top}|${descendantInsets.bottom}`}
</Text>
</View>
<View testID="file-panel-bottom-bar" style={BAR_STYLE}>
<Text>Save</Text>
</View>
</View>
);
});
container = document.createElement("div");
container.style.width = "390px";
container.style.height = `${FRAME_HEIGHT}px`;
container.style.display = "flex";
container.style.flexDirection = "column";
document.body.appendChild(container);
root = createRoot(container);
const hostNode = (
<PaneProvider value={PANE_CONTEXT_VALUE}>
<PluginFilePanelHost
panel={panel}
file={fakeFile}
params={FILE_PARAMS}
revision={1}
workspaceId={WORKSPACE_ID}
theme={FILE_THEME}
host={FILE_HOST}
layout={FILE_LAYOUT}
/>
</PaneProvider>
);
const tree = options?.insideSheet ? (
<SheetBottomInset style={FILL_STYLE} testID="sheet-body">
{hostNode}
</SheetBottomInset>
) : (
hostNode
);
act(() =>
root?.render(
<SafeAreaInsetsContext.Provider value={insets}>{tree}</SafeAreaInsetsContext.Provider>,
),
);
return container;
}
function queryEl(host: HTMLElement, testID: string): HTMLElement {
const el = host.querySelector(`[data-testid="${testID}"]`);
if (!(el instanceof HTMLElement)) throw new Error(`Missing element ${testID}`);
return el;
}
describe("PluginFilePanelHost bottom safe-area inset (browser)", () => {
it.each([
{ label: "48", insets: INSETS_48 },
{ label: "34", insets: INSETS_34 },
])("pads file panel bottom=$label and clears layout below bottom bar", ({ insets }) => {
const host = mountFilePanel(insets);
const frameRect = host.getBoundingClientRect();
const boundary = queryEl(host, "plugin-file-panel-safe-area");
const barRect = queryEl(host, "file-panel-bottom-bar").getBoundingClientRect();
expect(getComputedStyle(boundary).paddingBottom).toBe(`${insets.bottom}px`);
expect(barRect.bottom).toBeLessThanOrEqual(frameRect.bottom - insets.bottom + 1);
expect(barRect.bottom).toBeGreaterThanOrEqual(frameRect.bottom - insets.bottom - 1);
expect(queryEl(host, "file-panel-descendant-insets").textContent).toBe(`${insets.top}|0`);
});
it("does not double-pad when nested inside SheetBottomInset", () => {
const host = mountFilePanel(INSETS_48, { insideSheet: true });
const frameRect = host.getBoundingClientRect();
const sheet = queryEl(host, "sheet-body");
const boundary = queryEl(host, "plugin-file-panel-safe-area");
const barRect = queryEl(host, "file-panel-bottom-bar").getBoundingClientRect();
expect(getComputedStyle(sheet).paddingBottom).toBe("48px");
expect(getComputedStyle(boundary).paddingBottom).toBe("0px");
expect(barRect.bottom).toBeLessThanOrEqual(frameRect.bottom - 48 + 1);
expect(barRect.bottom).toBeGreaterThanOrEqual(frameRect.bottom - 48 - 1);
expect(queryEl(host, "file-panel-descendant-insets").textContent).toBe("24|0");
});
it("adds no bottom padding when insets.bottom is 0", () => {
const host = mountFilePanel(INSETS_0);
const frameRect = host.getBoundingClientRect();
const boundary = queryEl(host, "plugin-file-panel-safe-area");
const barRect = queryEl(host, "file-panel-bottom-bar").getBoundingClientRect();
expect(getComputedStyle(boundary).paddingBottom).toBe("0px");
expect(barRect.bottom).toBeLessThanOrEqual(frameRect.bottom + 1);
expect(barRect.bottom).toBeGreaterThanOrEqual(frameRect.bottom - 1);
expect(queryEl(host, "file-panel-descendant-insets").textContent).toBe("0|0");
});
});
+45 -7
View File
@@ -1,19 +1,57 @@
import type { PluginFilePanelProps } from "@getpaseo/plugin/client";
import { StyleSheet } from "react-native-unistyles";
import { BottomSafeAreaInset } from "@/components/ui/bottom-safe-area-inset";
import { usePanelTab } from "@/panels/panel-instance-attributes";
import { PluginInstallationProvider } from "@/plugins/installation-provider";
import { usePluginOpenScreen } from "@/plugins/navigation";
import { SurfaceErrorBoundary } from "@/plugins/surface-error-boundary";
import type { PluginFilePanel } from "./panels";
import type { BuiltinFilePanelProps, PluginFilePanel } from "./panels";
type PluginFilePanelHostProps = Omit<BuiltinFilePanelProps, "tab"> & {
panel: PluginFilePanel;
suspendPendingSave?: () => () => void;
};
function MountedPluginFilePanel({
panel,
suspendPendingSave,
...props
}: Omit<PluginFilePanelProps, "tab"> & {
panel: PluginFilePanel;
suspendPendingSave?: () => () => void;
}) {
const tab = usePanelTab({ suspendPendingSave });
const Component = panel.contribution.Component;
return <Component {...props} tab={tab} />;
}
export function PluginFilePanelHost({
panel,
suspendPendingSave,
...props
}: PluginFilePanelProps & { panel: PluginFilePanel }) {
}: PluginFilePanelHostProps) {
const { plugin, contribution } = panel;
const openScreen = usePluginOpenScreen(plugin);
const Component = contribution.Component;
return (
<SurfaceErrorBoundary installation={plugin} Surface={Component} key={panel.id}>
<PluginInstallationProvider plugin={plugin}>
<Component {...props} />
</PluginInstallationProvider>
</SurfaceErrorBoundary>
<BottomSafeAreaInset style={styles.container} testID="plugin-file-panel-safe-area">
<SurfaceErrorBoundary installation={plugin} Surface={Component} key={panel.id}>
<PluginInstallationProvider plugin={plugin}>
<MountedPluginFilePanel
{...props}
openScreen={openScreen}
panel={panel}
suspendPendingSave={suspendPendingSave}
/>
</PluginInstallationProvider>
</SurfaceErrorBoundary>
</BottomSafeAreaInset>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
minHeight: 0,
},
});
@@ -8,11 +8,8 @@ import {
type ComponentType,
type ReactNode,
} from "react";
import {
useFileText,
type PluginFilePanelProps,
type PluginFilePanelParams,
} from "@getpaseo/plugin/client";
import { useFileText, type PluginFilePanelParams } from "@getpaseo/plugin/client";
import type { BuiltinFilePanelProps } from "../panels";
import { Text, View } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { useTranslation } from "react-i18next";
@@ -56,12 +53,12 @@ const MAX_EDITABLE_BYTES = 1024 * 1024;
/** A rendered view of the file's text: the panel's Preview, shown instead of its source. */
export interface TextFilePreviewProps {
text: string;
params: PluginFilePanelProps["params"];
params: BuiltinFilePanelProps["params"];
workspaceId: string;
host: PluginFilePanelProps["host"];
host: BuiltinFilePanelProps["host"];
}
type TextFilePanelProps = PluginFilePanelProps & {
type TextFilePanelProps = BuiltinFilePanelProps & {
/** The panel's Preview; with one, the toolbar switches between Preview and Source. */
preview?: ComponentType<TextFilePreviewProps>;
};
+34 -6
View File
@@ -6,19 +6,40 @@ import type { PluginTheme } from "@getpaseo/plugin";
import { withUnistyles } from "react-native-unistyles";
import { useIsCompactFormFactor } from "@/constants/layout";
import { usePaneContext } from "@/panels/pane-context";
import { usePanelTab } from "@/panels/panel-instance-attributes";
import { useHosts } from "@/runtime/host-runtime";
import { usePluginHostNavigation } from "@/plugins/host-navigation";
import { resolvePluginPlatform } from "@/plugins/platform";
import { toPluginTheme } from "@/plugins/theme";
import type { Theme } from "@/styles/theme";
import type { FilePanel } from "./panels";
import type { BuiltinFilePanelProps, FilePanel } from "./panels";
import type { RenderingFilePanel, SourceFilePanel } from "./catalog";
import { BuiltinFilePanelView } from "./builtin";
import { PluginFilePanelHost } from "./plugin-host";
type Props = Pick<PluginFilePanelProps, "file" | "tab" | "params" | "revision"> & {
type Props = Pick<PluginFilePanelProps, "file" | "params" | "revision"> & {
panel: FilePanel;
suspendPendingSave?: () => () => void;
};
function FilePanelHost({ panel, theme, ...input }: Props & { theme: PluginTheme }) {
function BuiltinFilePanelHost({
panel,
suspendPendingSave,
...props
}: Omit<BuiltinFilePanelProps, "tab"> & {
panel: RenderingFilePanel | SourceFilePanel;
suspendPendingSave?: () => () => void;
}) {
const tab = usePanelTab({ suspendPendingSave });
return <BuiltinFilePanelView {...props} tab={tab} panel={panel} />;
}
function FilePanelHost({
panel,
suspendPendingSave,
theme,
...input
}: Props & { theme: PluginTheme }) {
const { workspaceId, serverId } = usePaneContext();
const compact = useIsCompactFormFactor();
const hosts = useHosts();
@@ -27,14 +48,21 @@ function FilePanelHost({ panel, theme, ...input }: Props & { theme: PluginTheme
const layout = useMemo(() => ({ compact, platform: resolvePluginPlatform() }), [compact]);
const stateSource = useMemo(() => createPluginClientStateSource(serverId), [serverId]);
const navigation = usePluginHostNavigation(serverId);
const props: PluginFilePanelProps = { ...input, workspaceId, theme, host, layout, navigation };
const props: Omit<BuiltinFilePanelProps, "tab"> = {
...input,
workspaceId,
theme,
host,
layout,
navigation,
};
if (panel.builtin)
return (
<PluginClientStateProvider source={stateSource}>
<BuiltinFilePanelView {...props} panel={panel} />
<BuiltinFilePanelHost {...props} panel={panel} suspendPendingSave={suspendPendingSave} />
</PluginClientStateProvider>
);
return <PluginFilePanelHost {...props} panel={panel} />;
return <PluginFilePanelHost {...props} panel={panel} suspendPendingSave={suspendPendingSave} />;
}
const ThemedHost = withUnistyles(FilePanelHost);
const themeMapping = (theme: Theme) => ({ theme: toPluginTheme(theme) });
@@ -15,7 +15,7 @@ export function createDiffPalette(theme: Theme): DiffPalette {
deletionBackground: hexColorWithAlpha(theme.colors.statusDanger, 0.1),
emptyBackground: theme.colors.surface0,
selection: theme.colors.terminal.blue,
headerActiveSurface: theme.colors.surface1,
headerActiveSurface: theme.colors.surfaceHover,
headerBorder: theme.colors.borderAccent,
statusSuccess: theme.colors.statusSuccess,
statusDanger: theme.colors.statusDanger,
+2 -2
View File
@@ -391,8 +391,8 @@ const styles = StyleSheet.create((theme) => ({
paddingLeft: theme.spacing[3],
paddingRight: WORKSPACE_PANE_TRAILING_GLYPH_RAIL,
},
documentActive: { backgroundColor: theme.colors.surface1 },
documentPressFeedback: { backgroundColor: theme.colors.surface1 },
documentActive: { backgroundColor: theme.colors.surfaceHover },
documentPressFeedback: { backgroundColor: theme.colors.surfaceSelected },
canvasInteraction: {
backgroundColor: "transparent",
borderColor: "transparent",
+1 -1
View File
@@ -281,7 +281,7 @@ const styles = StyleSheet.create((theme) => ({
color: theme.colors.foregroundMuted,
},
hoverable: {
backgroundColor: theme.colors.surface1,
backgroundColor: theme.colors.surfaceSidebarHover,
},
pipelineStageHeader: {
flexDirection: "row",
@@ -36,7 +36,7 @@ const styles = StyleSheet.create((theme) => ({
width: 20,
height: 20,
borderRadius: theme.borderRadius.full,
backgroundColor: theme.colors.surface2,
backgroundColor: theme.colors.surfaceSidebarSelected,
},
lines: {
flex: 1,
@@ -46,12 +46,12 @@ const styles = StyleSheet.create((theme) => ({
width: "70%",
height: 12,
borderRadius: theme.borderRadius.sm,
backgroundColor: theme.colors.surface2,
backgroundColor: theme.colors.surfaceSidebarSelected,
},
lineNarrow: {
width: "45%",
height: 10,
borderRadius: theme.borderRadius.sm,
backgroundColor: theme.colors.surface2,
backgroundColor: theme.colors.surfaceSidebarSelected,
},
}));
@@ -57,13 +57,13 @@ const styles = StyleSheet.create((theme) => ({
width: "75%",
height: 16,
borderRadius: theme.borderRadius.sm,
backgroundColor: theme.colors.surface2,
backgroundColor: theme.colors.surfaceSidebarSelected,
},
subtitle: {
width: "40%",
height: 12,
borderRadius: theme.borderRadius.sm,
backgroundColor: theme.colors.surface2,
backgroundColor: theme.colors.surfaceSidebarSelected,
},
toolbar: {
flexDirection: "row",
@@ -75,7 +75,7 @@ const styles = StyleSheet.create((theme) => ({
width: 96,
height: 24,
borderRadius: theme.borderRadius.lg,
backgroundColor: theme.colors.surface2,
backgroundColor: theme.colors.surfaceSidebarSelected,
},
section: {
paddingVertical: theme.spacing[2],
@@ -101,12 +101,12 @@ const styles = StyleSheet.create((theme) => ({
width: 14,
height: 14,
borderRadius: theme.borderRadius.full,
backgroundColor: theme.colors.surface2,
backgroundColor: theme.colors.surfaceSidebarSelected,
},
checkName: {
width: "60%",
height: 12,
borderRadius: theme.borderRadius.sm,
backgroundColor: theme.colors.surface2,
backgroundColor: theme.colors.surfaceSidebarSelected,
},
}));
@@ -1366,7 +1366,7 @@ const styles = StyleSheet.create((theme) => ({
borderRadius: 4,
},
kebabButtonHovered: {
backgroundColor: theme.colors.surface2,
backgroundColor: theme.colors.interactionHighlight,
},
cardBody: {
paddingHorizontal: theme.spacing[3],
+1 -1
View File
@@ -354,7 +354,7 @@ const styles = StyleSheet.create((theme) => ({
paddingVertical: theme.spacing[3],
},
rowActive: {
backgroundColor: theme.colors.surface1,
backgroundColor: theme.colors.surfaceSelected,
},
rowTrailing: {
flexDirection: "row",
@@ -96,6 +96,10 @@ function backdropStyle(backdrop: SurfaceBackdrop): ViewStyle {
return styles.backdropSurface1;
case "surface2":
return styles.backdropSurface2;
case "surfaceHover":
return styles.backdropSurfaceHover;
case "surfaceSelected":
return styles.backdropSurfaceSelected;
case "surfaceSidebar":
return styles.backdropSurfaceSidebar;
case "surfaceSidebarHover":
@@ -155,6 +159,12 @@ const styles = StyleSheet.create((theme) => ({
backdropSurface2: {
borderColor: theme.colors.surface2,
},
backdropSurfaceHover: {
borderColor: theme.colors.surfaceHover,
},
backdropSurfaceSelected: {
borderColor: theme.colors.surfaceSelected,
},
backdropSurfaceSidebar: {
borderColor: theme.colors.surfaceSidebar,
},
@@ -0,0 +1,163 @@
// @vitest-environment jsdom
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { htmlFrameBootstrapSource } from "./bootstrap";
import { INTERNAL_MARKER } from "./messages";
// jsdom has no WebView. A fake `ReactNativeWebView` records what the page posts, and the shim's
// receive function stands in for the host's injectJavaScript call.
interface Receiver {
__paseoHtmlFrameReceive(text: string): void;
}
function load(platform: "ios" | "android") {
const posted: string[] = [];
const win = window as unknown as Record<string, unknown>;
win.ReactNativeWebView = { postMessage: (text: string) => posted.push(text) };
// eslint-disable-next-line no-new-func
new Function(htmlFrameBootstrapSource(platform)).call(window);
return { posted, win };
}
// Every load() adds listeners and observers to the shared jsdom window and document; clean them up.
const added: Array<() => void> = [];
function trackListeners(target: EventTarget) {
const original = target.addEventListener.bind(target);
vi.spyOn(target, "addEventListener").mockImplementation(
(type: string, listener: EventListenerOrEventListenerObject | null, options?: unknown) => {
if (listener) {
added.push(() => target.removeEventListener(type, listener, options as boolean));
}
original(type, listener, options as boolean);
},
);
}
function trackMutationObservers() {
const original = MutationObserver.prototype.observe;
vi.spyOn(MutationObserver.prototype, "observe").mockImplementation(function (
this: MutationObserver,
target: Node,
options?: MutationObserverInit,
) {
added.push(() => this.disconnect());
return original.call(this, target, options);
});
}
afterEach(async () => {
// A load schedules a measure on the next frame; let it fire into this test's fake bridge.
await new Promise((resolve) => setTimeout(resolve, 40));
for (const remove of added.splice(0)) remove();
});
beforeEach(() => {
vi.restoreAllMocks();
trackListeners(window);
trackListeners(document);
trackMutationObservers();
// The shim redefines window.parent; put the jsdom default back between tests.
Reflect.deleteProperty(window, "parent");
Reflect.deleteProperty(window, "__paseoHtmlFrameReceive");
Reflect.deleteProperty(window, "ReactNativeWebView");
delete document.documentElement.dataset.paseoPlatform;
});
describe("native bootstrap shim", () => {
it.each(["ios", "android"] as const)("sets the platform attribute: %s", (platform) => {
load(platform);
expect(document.documentElement.dataset.paseoPlatform).toBe(platform);
});
it("routes window.parent.postMessage to ReactNativeWebView as JSON", () => {
const { posted } = load("ios");
window.parent.postMessage({ hello: "host", n: [1, 2] }, "*");
window.parent.postMessage("plain", "*");
expect(posted).toEqual(['{"hello":"host","n":[1,2]}', '"plain"']);
});
it("makes window.parent something other than the window itself", () => {
load("android");
expect(window.parent).not.toBe(window);
});
it("ignores values that cannot be serialized", () => {
const { posted } = load("ios");
window.parent.postMessage(undefined, "*");
window.parent.postMessage(() => 1, "*");
const cyclic: Record<string, unknown> = {};
cyclic.self = cyclic;
window.parent.postMessage(cyclic, "*");
expect(posted).toEqual([]);
});
it("delivers host messages as message events whose source is window.parent", () => {
load("ios");
const received: MessageEvent[] = [];
window.addEventListener("message", (event) => received.push(event));
(window as unknown as Receiver).__paseoHtmlFrameReceive('{"jsonrpc":"2.0","id":1}');
expect(received).toHaveLength(1);
expect(received[0].data).toEqual({ jsonrpc: "2.0", id: 1 });
expect(received[0].source).toBe(window.parent);
});
it("drops host text that is not JSON", () => {
load("ios");
const listener = vi.fn();
window.addEventListener("message", listener);
(window as unknown as Receiver).__paseoHtmlFrameReceive("{nope");
expect(listener).not.toHaveBeenCalled();
window.removeEventListener("message", listener);
});
it("reports script errors to the host through the private envelope", () => {
const { posted } = load("ios");
window.dispatchEvent(
new ErrorEvent("error", { message: "boom", filename: "x", lineno: 3, colno: 4 }),
);
const message = JSON.parse(posted[0]);
expect(message[INTERNAL_MARKER]).toEqual({ type: "error", message: "boom (3:4)" });
});
it("measures the page and posts the height once per change", async () => {
const { posted } = load("ios");
Object.defineProperty(document.body, "scrollHeight", { value: 321, configurable: true });
window.dispatchEvent(new Event("load"));
await new Promise((resolve) => setTimeout(resolve, 50));
const heights = posted
.map((text) => JSON.parse(text)[INTERNAL_MARKER])
.filter((message) => message?.type === "height");
expect(heights).toEqual([{ type: "height", height: 321 }]);
});
it("swallows link clicks on HTML <a>, SVG <a>, and <area>, and scrolls to in-page anchors", () => {
load("ios");
document.body.innerHTML =
'<a id="out" href="https://example.com">x</a><a id="in" href="#sec">y</a><div id="sec"></div><svg><a id="svg" href="https://example.com"><rect /></a></svg><map name="m"><area id="area" href="https://example.com" /></map>';
const section = document.getElementById("sec") as HTMLElement;
const scroll = vi.fn();
section.scrollIntoView = scroll;
const outside = new MouseEvent("click", { bubbles: true, cancelable: true });
document.getElementById("out")?.dispatchEvent(outside);
expect(outside.defaultPrevented).toBe(true);
expect(scroll).not.toHaveBeenCalled();
const svgClick = new MouseEvent("click", { bubbles: true, cancelable: true });
document.getElementById("svg")?.dispatchEvent(svgClick);
expect(svgClick.defaultPrevented).toBe(true);
const areaClick = new MouseEvent("click", { bubbles: true, cancelable: true });
document.getElementById("area")?.dispatchEvent(areaClick);
expect(areaClick.defaultPrevented).toBe(true);
const inside = new MouseEvent("click", { bubbles: true, cancelable: true });
document.getElementById("in")?.dispatchEvent(inside);
expect(inside.defaultPrevented).toBe(true);
expect(scroll).toHaveBeenCalledTimes(1);
});
it("makes window.open do nothing", () => {
load("android");
expect(window.open("https://example.com")).toBeNull();
});
});
+358
View File
@@ -0,0 +1,358 @@
import { INTERNAL_MARKER } from "./messages";
export type HtmlFramePlatform = "ios" | "android" | "web";
// Runs first in the page, on every platform. Written as ES5-ish text because it is inlined into the
// document the page loads, not bundled. It must never contain a closing script tag.
//
// Native: a WebView page is the top window, so `window.parent` is itself. The shim replaces
// `parent` with an object whose postMessage reaches `ReactNativeWebView.postMessage`, and
// `__paseoHtmlFrameReceive` turns host text into a `message` event whose `source` is that same
// object. That makes `event.source === window.parent` true, which the MCP Apps SDK transport checks.
const SOURCE = `(function () {
var MARKER = __MARKER__;
var PLATFORM = __PLATFORM__;
var TOKEN = __TOKEN__;
var root = document.documentElement;
root.dataset.paseoPlatform = PLATFORM;
var send;
if (PLATFORM === "web") {
send = function (value) { window.parent.postMessage(value, "*"); };
} else {
var hostParent = {
postMessage: function (value) {
var text;
try { text = JSON.stringify(value); } catch (e) { return; }
if (typeof text !== "string") return;
var bridge = window.ReactNativeWebView;
if (bridge && typeof bridge.postMessage === "function") bridge.postMessage(text);
}
};
try {
Object.defineProperty(window, "parent", { value: hostParent, configurable: true });
} catch (e) {}
try {
Object.defineProperty(window, "__paseoHtmlFrameReceive", {
configurable: true,
value: function (text) {
var data;
try { data = JSON.parse(text); } catch (e) { return; }
var event = new MessageEvent("message", { data: data });
try { Object.defineProperty(event, "source", { value: hostParent }); } catch (e) {}
window.dispatchEvent(event);
}
});
} catch (e) {}
send = function (value) { hostParent.postMessage(value); };
}
function internal(message) {
var envelope = {};
envelope[MARKER] = message;
send(envelope);
}
try { window.open = function () { return null; }; } catch (e) {}
// The host refuses every navigation after the first load; swallowing the click here also keeps
// an in-page "#anchor" from resolving against the embedding page's URL on web.
document.addEventListener("click", function (event) {
var node = event.target;
if (node && node.nodeType !== 1) node = node.parentNode;
while (node && node.nodeType === 1) {
var name = (node.localName || node.tagName || "").toLowerCase();
if (
(name === "a" || name === "area") &&
(node.hasAttribute("href") || node.hasAttribute("xlink:href"))
) {
break;
}
node = node.parentNode;
}
if (!node || node.nodeType !== 1) return;
event.preventDefault();
var href = node.getAttribute("href") || node.getAttribute("xlink:href") || "";
if (href.charAt(0) !== "#" || href.length < 2) return;
var id = href.slice(1);
try { id = decodeURIComponent(id); } catch (e) {}
var target = document.getElementById(id) || document.getElementsByName(id)[0];
if (target && target.scrollIntoView) target.scrollIntoView();
}, true);
var errors = 0;
function reportError(message) {
if (errors >= 20) return;
errors += 1;
internal({ type: "error", message: String(message).slice(0, 500) });
}
window.addEventListener("error", function (event) {
var where = event.filename ? " (" + event.lineno + ":" + event.colno + ")" : "";
reportError(event.message ? event.message + where : "Script error");
});
window.addEventListener("unhandledrejection", function (event) {
var reason = event.reason;
reportError("Unhandled rejection: " + (reason && reason.message ? reason.message : reason));
});
var SKIP_TAGS = { SCRIPT: 1, STYLE: 1, LINK: 1, META: 1, TITLE: 1, TEMPLATE: 1 };
function px(value) {
var parsed = parseFloat(value);
return isFinite(parsed) ? parsed : 0;
}
function measureContentHeight() {
var body = document.body;
if (!body) return 0;
var scrollY = window.scrollY || window.pageYOffset || 0;
var bottom = 0;
var foundFlow = false;
if (typeof document.createRange === "function") {
try {
var range = document.createRange();
range.selectNodeContents(body);
var rangeRect = range.getBoundingClientRect();
if (rangeRect && rangeRect.height > 0) {
bottom = Math.max(bottom, rangeRect.bottom + scrollY);
foundFlow = true;
}
} catch (e) {}
}
var children = body.children;
for (var index = 0; index < children.length; index += 1) {
var child = children[index];
if (SKIP_TAGS[(child.tagName || "").toUpperCase()]) continue;
var childRect = child.getBoundingClientRect ? child.getBoundingClientRect() : null;
if (!childRect || (childRect.width === 0 && childRect.height === 0)) continue;
foundFlow = true;
var childStyle = window.getComputedStyle ? window.getComputedStyle(child) : null;
var marginBottom = childStyle ? px(childStyle.marginBottom) : 0;
bottom = Math.max(bottom, childRect.bottom + scrollY + marginBottom);
}
if (!foundFlow) {
return Math.ceil(Math.max(root.getBoundingClientRect().height, body.scrollHeight || 0));
}
var bodyStyle = window.getComputedStyle ? window.getComputedStyle(body) : null;
var rootStyle = window.getComputedStyle ? window.getComputedStyle(root) : null;
var chrome =
(bodyStyle
? px(bodyStyle.paddingBottom) + px(bodyStyle.borderBottomWidth) + px(bodyStyle.marginBottom)
: 0) +
(rootStyle
? px(rootStyle.paddingBottom) + px(rootStyle.borderBottomWidth)
: 0);
return Math.ceil(Math.max(0, bottom + chrome));
}
var last = -1;
var lastWidth = window.innerWidth || 0;
var lastViewportHeight = window.innerHeight || 0;
var blockedVh = -1;
var blockedHeight = -1;
var probeTimer = null;
var probeVh = -1;
var probeHeight = -1;
var pending = false;
function clearProbe() {
if (probeTimer !== null) {
clearTimeout(probeTimer);
probeTimer = null;
}
probeVh = -1;
probeHeight = -1;
}
function reportHeight(height, vh) {
lastViewportHeight = vh;
if (height === last) return;
last = height;
internal({ type: "height", height: height });
}
function measure() {
pending = false;
var width = window.innerWidth || 0;
var vh = window.innerHeight || 0;
if (width !== lastWidth) {
lastWidth = width;
blockedVh = -1;
blockedHeight = -1;
clearProbe();
}
var height = measureContentHeight();
if (vh === blockedVh && Math.abs(height - blockedHeight) <= 2) {
lastViewportHeight = vh;
return;
}
if (height === last) {
lastViewportHeight = vh;
return;
}
var dVh = vh - lastViewportHeight;
var dH = last >= 0 ? height - last : 0;
if (last >= 0 && dVh > 0 && dH > 0 && Math.abs(dH - dVh) <= 2) {
// Height grew by the exact viewport change. Hold 40ms without resizing: a running CSS
// transition or animation keeps changing while vh stays fixed; a 100vh + padding loop stops.
if (probeTimer !== null && vh === probeVh && Math.abs(height - probeHeight) <= 2) return;
clearProbe();
probeVh = vh;
probeHeight = height;
probeTimer = setTimeout(function () {
var candidateVh = probeVh;
var candidate = probeHeight;
clearProbe();
if (typeof window === "undefined") return;
var currentVh = window.innerHeight || 0;
var remeasured = measureContentHeight();
if (currentVh === candidateVh && Math.abs(remeasured - candidate) <= 2) {
blockedVh = currentVh;
blockedHeight = remeasured;
lastViewportHeight = currentVh;
return;
}
blockedVh = -1;
blockedHeight = -1;
reportHeight(remeasured, currentVh);
}, 40);
return;
}
clearProbe();
blockedVh = -1;
blockedHeight = -1;
reportHeight(height, vh);
}
function schedule() {
if (pending || typeof window === "undefined") return;
pending = true;
if (window.requestAnimationFrame) window.requestAnimationFrame(measure);
else setTimeout(measure, 16);
}
function observe() {
var observedChildren = [];
var resizeObserver = null;
function syncBodyChildren() {
if (!resizeObserver || !document.body) return;
var next = [];
var children = document.body.children;
for (var index = 0; index < children.length; index += 1) {
var child = children[index];
if (SKIP_TAGS[(child.tagName || "").toUpperCase()]) continue;
next.push(child);
if (observedChildren.indexOf(child) === -1) resizeObserver.observe(child);
}
for (var oldIndex = 0; oldIndex < observedChildren.length; oldIndex += 1) {
var oldChild = observedChildren[oldIndex];
if (next.indexOf(oldChild) === -1) resizeObserver.unobserve(oldChild);
}
observedChildren = next;
}
if (typeof ResizeObserver === "function") {
resizeObserver = new ResizeObserver(schedule);
resizeObserver.observe(root);
if (document.body) {
resizeObserver.observe(document.body);
syncBodyChildren();
}
}
if (typeof MutationObserver === "function" && document.body) {
var mutations = new MutationObserver(function (records) {
for (var i = 0; i < records.length; i += 1) {
if (records[i].type === "childList" && records[i].target === document.body) {
syncBodyChildren();
break;
}
}
schedule();
});
mutations.observe(document.body, {
childList: true,
subtree: true,
attributes: true,
characterData: true
});
}
var motionStarts = typeof WeakMap === "function" ? new WeakMap() : null;
function measureTargetSpan(target) {
if (!target || typeof target.getBoundingClientRect !== "function") return null;
var rect = target.getBoundingClientRect();
var style = window.getComputedStyle ? window.getComputedStyle(target) : null;
return rect.height + (style ? px(style.marginTop) + px(style.marginBottom) : 0);
}
function onMotionStart(event) {
if (!motionStarts || !event || !event.target || typeof event.target !== "object") return;
if (motionStarts.has(event.target)) return;
var targetSpan = measureTargetSpan(event.target);
if (targetSpan === null) return;
motionStarts.set(event.target, {
docHeight: measureContentHeight(),
targetSpan: targetSpan
});
}
function onMotionCancel(event) {
if (!motionStarts || !event || !event.target || typeof event.target !== "object") return;
motionStarts.delete(event.target);
}
function onMotionEnd(event) {
if (typeof window === "undefined") return;
var target = event && event.target && typeof event.target === "object" ? event.target : null;
var start = motionStarts && target ? motionStarts.get(target) : null;
if (motionStarts && target) motionStarts.delete(target);
if (start) {
var currentDocHeight = measureContentHeight();
var currentTargetSpan = measureTargetSpan(target);
if (
currentTargetSpan !== null &&
Math.abs(currentTargetSpan - start.targetSpan) > 0.5 &&
Math.abs(currentDocHeight - start.docHeight) > 1
) {
clearProbe();
blockedVh = -1;
blockedHeight = -1;
reportHeight(currentDocHeight, window.innerHeight || 0);
return;
}
}
schedule();
}
document.addEventListener("transitionrun", onMotionStart, true);
document.addEventListener("transitionstart", onMotionStart, true);
document.addEventListener("animationstart", onMotionStart, true);
document.addEventListener("transitioncancel", onMotionCancel, true);
document.addEventListener("animationcancel", onMotionCancel, true);
document.addEventListener("transitionend", onMotionEnd, true);
document.addEventListener("animationend", onMotionEnd, true);
schedule();
}
var readySent = false;
function signalReady() {
if (readySent || !TOKEN) return;
readySent = true;
internal({ type: "ready", token: TOKEN });
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", observe);
} else {
observe();
}
if (document.readyState === "complete") {
signalReady();
}
window.addEventListener("load", function () {
signalReady();
schedule();
});
})();`;
export function htmlFrameBootstrap(platform: HtmlFramePlatform, token = ""): string {
const script = SOURCE.replace("__MARKER__", JSON.stringify(INTERNAL_MARKER))
.replace("__PLATFORM__", JSON.stringify(platform))
.replace("__TOKEN__", JSON.stringify(token));
return `<script>${script}</script>`;
}
/** The script body alone, for tests that evaluate it in a DOM. */
export function htmlFrameBootstrapSource(platform: HtmlFramePlatform, token = ""): string {
return htmlFrameBootstrap(platform, token).slice("<script>".length, -"</script>".length);
}
@@ -0,0 +1,89 @@
import { describe, expect, it } from "vitest";
import { buildHtmlFrameDocument } from "./document";
const build = (html: string, platform: "ios" | "android" | "web" = "web", csp?: object) =>
buildHtmlFrameDocument({ html, platform, csp });
describe("buildHtmlFrameDocument", () => {
it("puts doctype, then the policy, then viewport, style and bootstrap, then the page", () => {
const { document } = build("<h1>hi</h1>");
const order = [
"<!doctype html>",
'<meta http-equiv="Content-Security-Policy"',
'<meta name="viewport"',
"<style>html{-webkit-text-size-adjust:100%}</style>",
"<script>",
"<h1>hi</h1>",
].map((part) => document.indexOf(part));
expect(order.every((index) => index >= 0)).toBe(true);
expect(order).toEqual([...order].sort((a, b) => a - b));
expect(document.startsWith('<!doctype html><meta http-equiv="Content-Security-Policy"')).toBe(
true,
);
expect(document.endsWith("<h1>hi</h1>")).toBe(true);
});
it("keeps a page's own markup, doctype included, verbatim after the prologue", () => {
const page = "<!doctype html><html><body><p>x</p></body></html>";
expect(build(page).document.endsWith(page)).toBe(true);
});
it("drops a leading BOM", () => {
const { document } = build("<p>x</p>");
expect(document.includes("")).toBe(false);
expect(document.endsWith("<p>x</p>")).toBe(true);
});
it("bakes the platform into the bootstrap", () => {
expect(build("", "ios").document).toContain('var PLATFORM = "ios"');
expect(build("", "android").document).toContain('var PLATFORM = "android"');
expect(build("", "web").document).toContain('var PLATFORM = "web"');
});
it("starts from the closed preview policy", () => {
const { document } = build("");
expect(document).toContain("default-src 'none'");
expect(document).toContain("connect-src 'none'");
expect(document).toContain("form-action 'none'");
expect(document).toContain("frame-src 'none'");
});
it("appends resource domains to every resource directive and replaces connect-src", () => {
const { document, dropped } = build("", "web", {
resourceDomains: ["https://cdn.jsdelivr.net/npm/"],
connectDomains: ["https://api.example.com", "wss://live.example.com"],
});
expect(dropped).toEqual([]);
expect(document).toContain(
"script-src 'unsafe-inline' 'unsafe-eval' blob: https://cdn.jsdelivr.net/npm/;",
);
expect(document).toContain("style-src 'unsafe-inline' https://cdn.jsdelivr.net/npm/;");
expect(document).toContain("img-src data: blob: https://cdn.jsdelivr.net/npm/;");
expect(document).toContain("font-src data: https://cdn.jsdelivr.net/npm/;");
expect(document).toContain("media-src data: blob: https://cdn.jsdelivr.net/npm/;");
expect(document).toContain("connect-src https://api.example.com wss://live.example.com;");
expect(document).not.toContain("connect-src 'none'");
});
it("never lets an invalid entry reach the policy", () => {
const { document, dropped } = build("", "web", {
resourceDomains: ["*", "https://ok.example.com", "https://x.com; script-src *"],
connectDomains: ["http://insecure.example.com"],
});
expect(dropped).toHaveLength(3);
expect(document).not.toContain("script-src *");
expect(document).not.toContain("insecure.example.com");
expect(document).toContain("connect-src 'none'");
expect(document).toContain("https://ok.example.com");
});
it("keeps the host's policy first even when the page declares its own", () => {
const { document } = build(
'<meta http-equiv="Content-Security-Policy" content="default-src *">',
);
expect(document.indexOf("default-src 'none'")).toBeLessThan(document.indexOf("default-src *"));
expect(document.startsWith('<!doctype html><meta http-equiv="Content-Security-Policy"')).toBe(
true,
);
});
});
+36
View File
@@ -0,0 +1,36 @@
import { withPreviewCsp } from "@/file-panels/html-preview-csp";
import { htmlFrameBootstrap, type HtmlFramePlatform } from "./bootstrap";
import { validateHtmlFrameCsp, type HtmlFrameDroppedDomain } from "./domains";
const VIEWPORT =
'<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">';
const BASE_STYLE = "<style>html{-webkit-text-size-adjust:100%}</style>";
export interface HtmlFrameDocumentInput {
html: string;
csp?: { resourceDomains?: readonly string[]; connectDomains?: readonly string[] };
platform: HtmlFramePlatform;
token?: string;
}
export interface HtmlFrameDocument {
document: string;
/** CSP entries that were refused. */
dropped: HtmlFrameDroppedDomain[];
}
/**
* doctype, CSP meta (first element), viewport, base style, host bootstrap, then the page verbatim.
* See html-preview-csp.ts for why the page's own doctype is left in place.
*/
export function buildHtmlFrameDocument(input: HtmlFrameDocumentInput): HtmlFrameDocument {
const domains = validateHtmlFrameCsp(input.csp);
const document = withPreviewCsp(input.html, {
origins: {
resourceSources: domains.resourceDomains,
connectSources: domains.connectDomains,
},
head: VIEWPORT + BASE_STYLE + htmlFrameBootstrap(input.platform, input.token),
});
return { document, dropped: domains.dropped };
}
+133
View File
@@ -0,0 +1,133 @@
import { describe, expect, it } from "vitest";
import { parseHtmlFrameDomain, validateHtmlFrameCsp } from "./domains";
const resource = (entry: string) => parseHtmlFrameDomain(entry, "resourceDomains");
const connect = (entry: string) => parseHtmlFrameDomain(entry, "connectDomains");
describe("parseHtmlFrameDomain", () => {
it("accepts https origins, ports, wildcard subdomains and path prefixes", () => {
expect(resource("https://cdnjs.cloudflare.com")).toEqual({
ok: true,
source: "https://cdnjs.cloudflare.com",
});
expect(resource("https://*.example.com")).toEqual({
ok: true,
source: "https://*.example.com",
});
expect(resource("https://cdn.jsdelivr.net/npm/")).toEqual({
ok: true,
source: "https://cdn.jsdelivr.net/npm/",
});
expect(resource("https://example.com:8443/a/b/")).toEqual({
ok: true,
source: "https://example.com:8443/a/b/",
});
});
it("lowercases scheme and host but keeps the path", () => {
expect(resource("HTTPS://CDN.Example.COM/Lib/")).toEqual({
ok: true,
source: "https://cdn.example.com/Lib/",
});
});
it("accepts wss only for connect domains", () => {
expect(connect("wss://live.example.com")).toEqual({
ok: true,
source: "wss://live.example.com",
});
expect(resource("wss://live.example.com").ok).toBe(false);
});
it.each([
["http scheme", "http://example.com"],
["ws scheme", "ws://example.com"],
["bare wildcard", "*"],
["scheme only", "https:"],
["scheme wildcard", "https://*"],
["wildcard top-level domain", "https://*.com"],
["single label", "https://localhost"],
["IPv4 address", "https://192.168.1.1"],
["IPv4 with port", "https://10.0.0.1:8443"],
["hex IPv4", "https://0x7f.0x1"],
["mixed-radix IPv4", "https://127.0.0.0x1"],
["octal IPv4", "https://0177.0.0.1"],
["no scheme", "example.com"],
["missing trailing slash on path", "https://example.com/npm"],
["file extension path", "https://example.com/a.js"],
["dot segment", "https://example.com/a/../"],
["double slash", "https://example.com//"],
["query", "https://example.com/?a=b"],
["fragment", "https://example.com/#a"],
["user info", "https://user@example.com"],
["space", "https://example.com evil.com"],
["semicolon", "https://example.com; script-src *"],
["single quote", "https://example.com'"],
["double quote", 'https://example.com"'],
["comma", "https://example.com,https://evil.com"],
["newline", "https://example.com\nhttps://evil.com"],
["port zero", "https://example.com:0"],
["port too large", "https://example.com:70000"],
["wildcard in the middle", "https://cdn.*.example.com"],
["wildcard without dot", "https://*example.com"],
["keyword", "'unsafe-eval'"],
["data scheme", "data:"],
["too long", `https://${"a".repeat(300)}.com`],
])("rejects %s", (_name, entry) => {
expect(resource(entry).ok).toBe(false);
expect(connect(entry).ok).toBe(false);
});
it("rejects non-strings", () => {
expect(resource(42 as unknown as string).ok).toBe(false);
expect(resource(null as unknown as string).ok).toBe(false);
});
});
describe("validateHtmlFrameCsp", () => {
it("returns canonical lists, drops bad entries and says why", () => {
const result = validateHtmlFrameCsp({
resourceDomains: ["https://a.example.com", "https://a.example.com", "http://b.example.com"],
connectDomains: ["wss://c.example.com", "*"],
});
expect(result.resourceDomains).toEqual(["https://a.example.com"]);
expect(result.connectDomains).toEqual(["wss://c.example.com"]);
expect(result.dropped).toHaveLength(2);
expect(result.dropped[0]).toMatchObject({
list: "resourceDomains",
entry: "http://b.example.com",
});
expect(result.dropped[0].message).toContain("http://b.example.com");
expect(result.dropped[1]).toMatchObject({
list: "connectDomains",
entry: "*",
});
expect(result.dropped[1].message).toContain('"*"');
});
it("returns empty lists for no csp", () => {
expect(validateHtmlFrameCsp(undefined)).toEqual({
resourceDomains: [],
connectDomains: [],
dropped: [],
});
});
it("caps each list and truncates long entries in reports", () => {
const many = Array.from({ length: 40 }, (_, index) => `https://h${index}.example.com`);
const result = validateHtmlFrameCsp({ connectDomains: many });
expect(result.connectDomains).toHaveLength(32);
expect(result.dropped).toHaveLength(8);
const long = validateHtmlFrameCsp({ resourceDomains: [`https://${"a".repeat(200)}.com`] });
expect(long.dropped[0].message.length).toBeLessThan(200);
});
it("refuses a list that is not an array", () => {
const result = validateHtmlFrameCsp({
resourceDomains: "https://example.com" as unknown as string[],
});
expect(result.resourceDomains).toEqual([]);
expect(result.dropped).toHaveLength(1);
});
});
+131
View File
@@ -0,0 +1,131 @@
// One tested place that decides which origins a page may reach. Plugins hand us strings and the
// strings are placed inside a CSP header, so anything that is not a plain https/wss origin is
// dropped rather than repaired. A dropped entry is reported to the host, never silently widened.
const MAX_ENTRIES = 32;
const MAX_ENTRY_LENGTH = 256;
const LABEL = "[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?";
const HOST = `(?:\\*\\.)?${LABEL}(?:\\.${LABEL})+`;
const ENTRY = new RegExp(
`^(https|wss)://(${HOST})(?::([0-9]{1,5}))?((?:/[A-Za-z0-9._~-]+)*/)?$`,
"i",
);
export type HtmlFrameDomainListKind = "resourceDomains" | "connectDomains";
export interface HtmlFrameDroppedDomain {
list: HtmlFrameDomainListKind;
entry?: string;
message: string;
}
export interface HtmlFrameDomains {
resourceDomains: string[];
connectDomains: string[];
/** One structured report per entry that was refused. */
dropped: HtmlFrameDroppedDomain[];
}
function describe(entry: unknown): string {
if (typeof entry !== "string") return `a ${typeof entry} value`;
const shown = entry.length > 80 ? `${entry.slice(0, 80)}…` : entry;
return JSON.stringify(shown);
}
/** Returns the canonical CSP source expression, or why the entry was refused. */
export function parseHtmlFrameDomain(
entry: unknown,
kind: HtmlFrameDomainListKind,
): { ok: true; source: string } | { ok: false; reason: string } {
if (typeof entry !== "string") return { ok: false, reason: "not a string" };
if (entry.length > MAX_ENTRY_LENGTH) return { ok: false, reason: "too long" };
const match = ENTRY.exec(entry);
if (!match) {
return { ok: false, reason: 'expected "https://host[:port][/path/]" with no other characters' };
}
const [, rawScheme, rawHost, rawPort, path] = match;
const scheme = rawScheme.toLowerCase();
if (scheme === "wss" && kind === "resourceDomains") {
return { ok: false, reason: "resources load over https only" };
}
const host = rawHost.toLowerCase();
const bareHost = host.replace(/^\*\./, "");
const labels = bareHost.split(".");
if (/^[0-9]+$/.test(labels[labels.length - 1])) {
return { ok: false, reason: "IP addresses are not allowed" };
}
// Reject non-canonical / hex / octal / mixed-radix IPv4 forms (e.g. 0x7f.0x1, 127.0.0.0x1).
let normalizedHost: string;
try {
normalizedHost = new URL(`https://${bareHost}`).hostname;
} catch {
return { ok: false, reason: "invalid host" };
}
if (normalizedHost !== bareHost || /^[0-9.]+$/.test(normalizedHost)) {
return { ok: false, reason: "IP addresses are not allowed" };
}
if (rawPort !== undefined) {
const port = Number(rawPort);
if (port < 1 || port > 65535) return { ok: false, reason: "invalid port" };
}
if (path && path.split("/").some((segment) => segment === "." || segment === "..")) {
return { ok: false, reason: "path segments must not be . or .." };
}
return {
ok: true,
source: `${scheme}://${host}${rawPort ? `:${Number(rawPort)}` : ""}${path ?? ""}`,
};
}
function parseList(
entries: readonly unknown[] | undefined,
kind: HtmlFrameDomainListKind,
dropped: HtmlFrameDroppedDomain[],
): string[] {
const accepted: string[] = [];
if (entries === undefined) return accepted;
if (!Array.isArray(entries)) {
dropped.push({ list: kind, message: `${kind}: expected an array` });
return accepted;
}
for (const entry of entries) {
const parsed = parseHtmlFrameDomain(entry, kind);
const entryText = typeof entry === "string" ? entry : undefined;
if (!parsed.ok) {
dropped.push({
list: kind,
entry: entryText,
message: `${kind}: dropped ${describe(entry)} (${parsed.reason})`,
});
continue;
}
if (accepted.includes(parsed.source)) continue;
if (accepted.length >= MAX_ENTRIES) {
dropped.push({
list: kind,
entry: entryText,
message: `${kind}: dropped ${describe(entry)} (more than ${MAX_ENTRIES} entries)`,
});
continue;
}
accepted.push(parsed.source);
}
return accepted;
}
export function validateHtmlFrameCsp(
csp:
| {
resourceDomains?: readonly unknown[];
connectDomains?: readonly unknown[];
}
| undefined,
): HtmlFrameDomains {
const dropped: HtmlFrameDroppedDomain[] = [];
return {
resourceDomains: parseList(csp?.resourceDomains, "resourceDomains", dropped),
connectDomains: parseList(csp?.connectDomains, "connectDomains", dropped),
dropped,
};
}
@@ -0,0 +1,374 @@
import { act, createRef } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, describe, expect, it } from "vitest";
import { i18n } from "@/i18n/i18next";
import { HtmlFrame } from "./index.web";
import type { HtmlFrameErrorEvent, HtmlFrameHandle, HtmlFrameProps } from "./types";
// Real Chromium: the iframe is sandboxed the way it ships, so these tests run the page's scripts,
// its postMessage round trips and its refused navigations rather than reading attributes.
const CAPPED = { min: 80, max: 500 };
const BOUNDED = { min: 80, max: 600 };
const mentions = (events: HtmlFrameErrorEvent[], text: string) =>
events.some((event) => event.message.includes(text));
const hasNavigationError = (events: HtmlFrameErrorEvent[]) =>
events.some((event) => event.type === "navigation");
const hasHeightAtLeast = (heights: number[], min: number) => heights.some((value) => value >= min);
const hasHeightAtMost = (heights: number[], max: number) => heights.some((value) => value <= max);
let root: Root | null = null;
let container: HTMLDivElement | null = null;
afterEach(() => {
act(() => root?.unmount());
container?.remove();
root = null;
container = null;
});
async function mount(props: HtmlFrameProps, ref?: React.Ref<HtmlFrameHandle>) {
await i18n.changeLanguage("en");
container = document.createElement("div");
container.style.width = "360px";
document.body.append(container);
root = createRoot(container);
await act(async () => root?.render(<HtmlFrame ref={ref} {...props} />));
return container.querySelector("iframe") as HTMLIFrameElement | null;
}
async function rerender(props: HtmlFrameProps, ref?: React.Ref<HtmlFrameHandle>) {
await act(async () => root?.render(<HtmlFrame ref={ref} {...props} />));
}
function until<T>(read: () => T | undefined | false, what: string): Promise<T> {
return new Promise((resolve, reject) => {
const started = Date.now();
const tick = () => {
const value = read();
if (value) return resolve(value);
if (Date.now() - started > 5000) return reject(new Error(`Timed out waiting for ${what}`));
setTimeout(tick, 20);
};
tick();
});
}
describe("HtmlFrame on web", () => {
it("sandboxes the frame with scripts only and an opaque origin", async () => {
const frame = await mount({ html: "<p>hi</p>" });
expect(frame?.getAttribute("sandbox")).toBe("allow-scripts");
expect(frame?.getAttribute("referrerpolicy")).toBe("no-referrer");
expect(() => frame?.contentWindow?.document).toThrow();
});
it("runs page scripts, tags the platform and delivers page messages without the internal ones", async () => {
const messages: unknown[] = [];
await mount({
html: `<p id="p">hi</p><script>
window.parent.postMessage({ platform: document.documentElement.dataset.paseoPlatform }, "*");
window.parent.postMessage([1, 2, 3], "*");
</script>`,
onMessage: (message) => messages.push(message),
});
await until(() => messages.length >= 2, "page messages");
expect(messages).toEqual([{ platform: "web" }, [1, 2, 3]]);
});
it("auto-sizes to the content within the clamp and reports the measured height", async () => {
const heights: number[] = [];
const frame = await mount({
html: '<div style="height:300px;margin:0"></div><style>body{margin:0}</style>',
onContentHeight: ({ height }) => heights.push(height),
});
await until(() => heights.includes(300), "measured height");
await until(() => frame?.style.height === "300px", "frame resize");
await act(async () =>
root?.render(
<HtmlFrame
html='<style>body{margin:0}</style><div style="height:3000px"></div>'
autoHeight={CAPPED}
/>,
),
);
const resized = container?.querySelector("iframe");
await until(() => resized?.style.height === "500px", "clamped frame");
expect(resized?.getAttribute("scrolling")).toBe("yes");
});
it("delivers ref.postMessage to the page as a message event from window.parent", async () => {
const ref = createRef<HtmlFrameHandle>();
const echoes: unknown[] = [];
await mount(
{
html: `<script>
window.addEventListener("message", function (event) {
window.parent.postMessage({ echo: event.data, fromParent: event.source === window.parent }, "*");
});
window.parent.postMessage("ready", "*");
</script>`,
onMessage: (message) => echoes.push(message),
},
ref,
);
await until(() => echoes.includes("ready"), "page ready");
// Posted before load would queue; after load it goes straight through.
ref.current?.postMessage({ hello: "page" });
await until(() => echoes.length >= 2, "echo");
expect(echoes[1]).toEqual({ echo: { hello: "page" }, fromParent: true });
});
it("reports script errors and dropped csp entries as discriminated events", async () => {
const errors: HtmlFrameErrorEvent[] = [];
await mount({
html: '<script>throw new Error("kaboom")</script>',
csp: { resourceDomains: ["http://insecure.example.com", "https://ok.example.com"] },
onError: (event) => errors.push(event),
});
await until(() => mentions(errors, "kaboom"), "script error");
expect(
errors.some((event) => event.type === "script" && event.message.includes("kaboom")),
).toBe(true);
expect(
errors.some(
(event) =>
event.type === "csp" &&
event.list === "resourceDomains" &&
event.entry === "http://insecure.example.com",
),
).toBe(true);
});
it("caps forged page error envelopes on the host side", async () => {
const errors: HtmlFrameErrorEvent[] = [];
await mount({
html: `<script>
for (var i = 0; i < 40; i++) {
window.parent.postMessage({ __paseoHtmlFrame: { type: "error", message: "spam-" + i } }, "*");
}
</script>`,
onError: (event) => errors.push(event),
});
await until(() => errors.length >= 20, "capped errors");
await new Promise((resolve) => setTimeout(resolve, 100));
expect(errors.filter((event) => event.type === "script")).toHaveLength(20);
});
it("blocks network the policy does not allow", async () => {
const messages: unknown[] = [];
await mount({
html: `<script>
fetch("https://example.com/").then(
function () { window.parent.postMessage("fetched", "*"); },
function () { window.parent.postMessage("blocked", "*"); }
);
</script>`,
onMessage: (message) => messages.push(message),
});
await until(() => messages.length > 0, "fetch result");
expect(messages).toEqual(["blocked"]);
});
it("refuses a page that navigates itself and replaces it with an empty page", async () => {
const errors: HtmlFrameErrorEvent[] = [];
const frame = await mount({
html: '<script>setTimeout(function () { location.href = "about:blank#x"; location.replace("data:text/html,<p>away</p>"); }, 50)</script>',
onError: (event) => errors.push(event),
});
await until(
() => hasNavigationError(errors) && mentions(errors, "navigate"),
"navigation refusal",
);
const blank = await until(() => {
const current = container?.querySelector("iframe");
return current && current !== frame ? current : undefined;
}, "replacement frame");
expect(blank.getAttribute("srcdoc")).not.toContain("<script>");
});
it("does not follow link clicks", async () => {
const messages: unknown[] = [];
const frame = await mount({
html: '<a id="a" href="https://example.com/">x</a><script>document.getElementById("a").click(); setTimeout(function(){window.parent.postMessage("still here","*")}, 100)</script>',
onMessage: (message) => messages.push(message),
});
await until(() => messages.includes("still here"), "page after click");
expect(container?.querySelector("iframe")).toBe(frame);
});
it("refuses synchronous navigation before initial load and never flushes queued host messages to it", async () => {
const ref = createRef<HtmlFrameHandle>();
const errors: HtmlFrameErrorEvent[] = [];
const received: unknown[] = [];
const attacker =
'<!doctype html><script>window.addEventListener("message",function(e){window.parent.postMessage({stolen:e.data},"*");});window.parent.postMessage("attacker-loaded","*");</script>';
const attackerUrl = `data:text/html,${encodeURIComponent(attacker)}`;
const frame = await mount(
{
html: `<script>location.replace(${JSON.stringify(attackerUrl)});</script>`,
onMessage: (message) => received.push(message),
onError: (event) => errors.push(event),
},
ref,
);
// Queue a secret before the frame loads; it must never reach the navigated document.
ref.current?.postMessage({ secret: "workspace-token" });
await until(() => hasNavigationError(errors), "navigation error");
const blank = await until(() => {
const current = container?.querySelector("iframe");
return current && current !== frame ? current : undefined;
}, "replacement frame");
expect(blank.getAttribute("srcdoc")).not.toContain("<script>");
expect(
received.some((item) => typeof item === "object" && item !== null && "stolen" in item),
).toBe(false);
});
it("does not follow SVG <a> or <area> link clicks", async () => {
const messages: unknown[] = [];
const frame = await mount({
html: `<svg width="40" height="40"><a id="svg-link" href="https://example.com/"><rect width="40" height="40"/></a></svg>
<map name="m"><area id="area-link" shape="rect" coords="0,0,10,10" href="https://example.com/"/></map>
<script>
document.getElementById("svg-link").dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
document.getElementById("area-link").dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
setTimeout(function () { window.parent.postMessage("still here", "*"); }, 120);
</script>`,
onMessage: (message) => messages.push(message),
});
await until(() => messages.includes("still here"), "page after svg/area click");
expect(container?.querySelector("iframe")).toBe(frame);
});
it("does not enter a growth loop on height:100% + padding and shrinks when content collapses", async () => {
const heights: number[] = [];
const frame = await mount({
html: `<style>html,body{height:100%;padding:16px;margin:0}</style><p>Hello</p>`,
autoHeight: { min: 80, max: 600 },
onContentHeight: ({ height }) => heights.push(height),
});
await until(() => heights.length > 0, "initial height");
await new Promise((resolve) => setTimeout(resolve, 250));
expect(Number.parseInt(frame?.style.height ?? "0", 10)).toBeLessThan(200);
// Expand then collapse inside a height:100% document and verify the frame shrinks back.
const ref = createRef<HtmlFrameHandle>();
const shrinkHeights: number[] = [];
await rerender(
{
html: `<style>html,body{height:100%;margin:0}</style><div id="box" style="height:360px"></div><script>
window.addEventListener("message", function (e) {
if (e.data === "collapse") document.getElementById("box").style.height = "120px";
});
</script>`,
autoHeight: BOUNDED,
onContentHeight: ({ height }) => shrinkHeights.push(height),
},
ref,
);
await until(() => hasHeightAtLeast(shrinkHeights, 350), "expanded height");
ref.current?.postMessage("collapse");
await until(() => hasHeightAtMost(shrinkHeights, 130), "shrunk height");
const current = container?.querySelector("iframe");
await until(() => Number.parseInt(current?.style.height ?? "999", 10) <= 130, "shrunk iframe");
});
it("follows CSS transitions and keyframes animations while halting 100vh + padding feedback loops", async () => {
const transitionHeights: number[] = [];
const frame = await mount({
html: `<style>
body { margin: 0; }
#box { height: 20px; transition: height 150ms linear; }
#box.open { height: 400px; }
</style>
<div id="box"></div>
<script>
setTimeout(function () { document.getElementById("box").classList.add("open"); }, 40);
</script>`,
autoHeight: BOUNDED,
onContentHeight: ({ height }) => transitionHeights.push(height),
});
await until(() => hasHeightAtLeast(transitionHeights, 395), "transition final height");
await until(() => Number.parseInt(frame?.style.height ?? "0", 10) >= 395, "transition iframe");
const keyframeHeights: number[] = [];
await rerender({
html: `<style>
body { margin: 0; }
@keyframes grow { from { height: 10px; } to { height: 300px; } }
#anim { height: 10px; animation: grow 150ms linear forwards; }
</style>
<div id="anim"></div>`,
autoHeight: BOUNDED,
onContentHeight: ({ height }) => keyframeHeights.push(height),
});
await until(() => hasHeightAtLeast(keyframeHeights, 295), "keyframes final height");
const vhHeights: number[] = [];
await rerender({
html: `<style>
body{margin:0}
.wrap{min-height:100vh;padding:16px}
#btn{background:#222;transition:background-color 50ms ease}
#btn.on{background:#444}
</style>
<div class="wrap"><p id="tick">0</p><button id="btn" type="button">Hover</button></div>
<script>
var n = 0;
setInterval(function () {
n += 1;
document.getElementById("tick").textContent = String(n);
document.getElementById("btn").classList.toggle("on");
}, 70);
</script>`,
autoHeight: BOUNDED,
onContentHeight: ({ height }) => vhHeights.push(height),
});
await until(() => vhHeights.length > 0, "100vh initial height");
await new Promise((resolve) => setTimeout(resolve, 600));
const vhFrame = container?.querySelector("iframe");
expect(Number.parseInt(vhFrame?.style.height ?? "0", 10)).toBeLessThan(200);
const fixedBodyTransitionHeights: number[] = [];
await rerender({
html: `<style>
html, body { height: 100%; margin: 0; }
#box { height: 20px; transition: height 300ms ease; }
#box.open { height: 400px; }
</style>
<div id="box"></div>
<script>
setTimeout(function () { document.getElementById("box").classList.add("open"); }, 40);
</script>`,
autoHeight: BOUNDED,
onContentHeight: ({ height }) => fixedBodyTransitionHeights.push(height),
});
await until(
() => fixedBodyTransitionHeights.includes(400),
"ease transition final height inside height:100% body",
);
const settledFrame = container?.querySelector("iframe");
await until(
() => Number.parseInt(settledFrame?.style.height ?? "0", 10) === 400,
"ease transition settled iframe height",
);
});
it("keeps a placeholder of the last height when inactive and loads again when active", async () => {
const heights: number[] = [];
await mount({
html: '<style>body{margin:0}</style><div style="height:200px"></div>',
onContentHeight: ({ height }) => heights.push(height),
});
await until(() => heights.includes(200), "height");
await act(async () =>
root?.render(
<HtmlFrame html="<div style='height:200px'></div>" active={false} testID="gone" />,
),
);
expect(container?.querySelector("iframe")).toBeNull();
const placeholder = container?.querySelector('[data-testid="gone"]') as HTMLElement;
expect(placeholder.style.height).toBe("200px");
});
});
+155
View File
@@ -0,0 +1,155 @@
import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef } from "react";
import { Platform, View } from "react-native";
import { WebView, type WebViewMessageEvent } from "react-native-webview";
import { useHtmlPreviewNavigationGuard } from "@/file-panels/html-preview-navigation";
import { routeNativePageText } from "./messages";
import { PageOutbox } from "./outbox";
import type { HtmlFramePlatform } from "./bootstrap";
import type { HtmlFrameHandle, HtmlFrameProps } from "./types";
import { useHtmlFrameState } from "./use-html-frame-state";
// Same reasoning as file-panels/html-preview.tsx: the whitelist must match every scheme so the
// navigation guard sees each request, and the inert base URL keeps "initial document" meaning only
// inert URLs.
const ORIGIN_WHITELIST = ["*"];
const BASE_URL = "about:blank";
const NATIVE_PLATFORM: HtmlFramePlatform = Platform.OS === "android" ? "android" : "ios";
export const HtmlFrame = forwardRef<HtmlFrameHandle, HtmlFrameProps>(
function HtmlFrame(props, ref) {
const state = useHtmlFrameState(props, NATIVE_PLATFORM);
const { sizing } = state;
const active = props.active !== false;
const lastHeight = useRef(sizing.height);
if (active && sizing.height !== null) lastHeight.current = sizing.height;
const outbox = useRef<PageOutbox | null>(null);
const webView = useRef<WebView | null>(null);
if (outbox.current === null) {
outbox.current = new PageOutbox(
(text) => {
webView.current?.injectJavaScript(
`window.__paseoHtmlFrameReceive&&window.__paseoHtmlFrameReceive(${JSON.stringify(text)});true;`,
);
},
(message) =>
state.callbacks.current.onError?.({
type: "message",
direction: "outbound",
message,
}),
);
}
useImperativeHandle(
ref,
() => ({ postMessage: (message) => outbox.current?.post(message) }),
[],
);
const placeholderHeight = lastHeight.current ?? 0;
const placeholderStyle = useMemo(
() => (sizing.fill ? fillStyle : { height: placeholderHeight }),
[sizing.fill, placeholderHeight],
);
useEffect(() => {
outbox.current?.reset();
}, [state.document, active]);
if (!active) {
return <View testID={props.testID} style={placeholderStyle} />;
}
return (
<HtmlFrameWebView
state={state}
webView={webView}
outbox={outbox.current}
testID={props.testID}
/>
);
},
);
function HtmlFrameWebView({
state,
webView,
outbox,
testID,
}: {
state: ReturnType<typeof useHtmlFrameState>;
webView: React.RefObject<WebView | null>;
outbox: PageOutbox;
testID?: string;
}) {
const { document, sizing, handleRouted, callbacks } = state;
const source = useMemo(() => ({ html: document, baseUrl: BASE_URL }), [document]);
// One guard per mounted WebView: an `active` toggle remounts it, and that load must pass again.
const allowOnlyInitialDocument = useHtmlPreviewNavigationGuard(document);
const onMessage = useCallback(
(event: WebViewMessageEvent) => handleRouted(routeNativePageText(event.nativeEvent.data)),
[handleRouted],
);
const onLoadStart = useCallback(() => outbox.reset(), [outbox]);
const onLoadEnd = useCallback(() => {
outbox.loaded();
callbacks.current.onLoad?.();
}, [outbox, callbacks]);
const onError = useCallback(
() =>
callbacks.current.onError?.({
type: "load",
message: "The page failed to load",
}),
[callbacks],
);
// react-native-webview wraps the native view in a `flex: 1` container; sizing an outer View
// guarantees exact pixel heights inside scrolling lists (LegendList, FlatList, ScrollView).
const boxStyle = useMemo(
() => (sizing.fill ? fillStyle : { height: sizing.height ?? 0, overflow: "hidden" as const }),
[sizing.fill, sizing.height],
);
return (
<View testID={testID} style={boxStyle}>
<WebView
ref={webView}
style={webViewStyle}
containerStyle={fillStyle}
source={source}
originWhitelist={ORIGIN_WHITELIST}
onShouldStartLoadWithRequest={allowOnlyInitialDocument}
onMessage={onMessage}
onLoadStart={onLoadStart}
onLoadEnd={onLoadEnd}
onError={onError}
javaScriptEnabled
scrollEnabled={sizing.scrollEnabled}
bounces={false}
scalesPageToFit={false}
setBuiltInZoomControls={false}
setDisplayZoomControls={false}
textZoom={100}
automaticallyAdjustContentInsets={false}
contentInsetAdjustmentBehavior="never"
overScrollMode="never"
allowsLinkPreview={false}
allowsInlineMediaPlayback
mediaPlaybackRequiresUserAction
allowsFullscreenVideo={false}
allowFileAccess={false}
geolocationEnabled={false}
mixedContentMode="never"
setSupportMultipleWindows={false}
javaScriptCanOpenWindowsAutomatically={false}
domStorageEnabled={false}
thirdPartyCookiesEnabled={false}
cacheEnabled={false}
incognito
/>
</View>
);
}
const fillStyle = { flex: 1 } as const;
const webViewStyle = { flex: 1, backgroundColor: "transparent" } as const;
+173
View File
@@ -0,0 +1,173 @@
import {
forwardRef,
useCallback,
useEffect,
useImperativeHandle,
useMemo,
useRef,
useState,
} from "react";
import { useTranslation } from "react-i18next";
import { routePageMessage } from "./messages";
import { PageOutbox } from "./outbox";
import type { HtmlFrameHandle, HtmlFrameProps } from "./types";
import { useHtmlFrameState } from "./use-html-frame-state";
// `allow-scripts` alone: an opaque origin, so the page cannot reach Paseo's DOM, cookies or
// storage, and none of popups, forms, downloads or top navigation. Same token set as
// file-panels/html-preview.web.tsx and the Mermaid runtime.
const SANDBOX = "allow-scripts";
// An iframe that navigates itself fires `load` without our bootstrap token (if it navigated
// synchronously before load) or fires `load` a second time (after initial load). Either way, the
// frame is replaced with an empty page instead of showing wherever it went.
const BLANK_DOCUMENT = "<!doctype html><title></title>";
const READY_TOKEN_GRACE_MS = 50;
export const HtmlFrame = forwardRef<HtmlFrameHandle, HtmlFrameProps>(
function HtmlFrame(props, ref) {
const { t } = useTranslation();
const { document, token, sizing, handleRouted, callbacks } = useHtmlFrameState(props, "web");
const iframe = useRef<HTMLIFrameElement | null>(null);
const [navigated, setNavigated] = useState<string | null>(null);
const loads = useRef(0);
const verified = useRef(false);
const unverifiedTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const active = props.active !== false;
const lastHeight = useRef(sizing.height);
if (active && sizing.height !== null) lastHeight.current = sizing.height;
const refused = navigated === document;
const refusedRef = useRef(refused);
refusedRef.current = refused;
const outbox = useRef<PageOutbox | null>(null);
if (outbox.current === null) {
outbox.current = new PageOutbox(
(text) => iframe.current?.contentWindow?.postMessage(JSON.parse(text), "*"),
(message) =>
callbacks.current.onError?.({
type: "message",
direction: "outbound",
message,
}),
);
}
useImperativeHandle(
ref,
() => ({
postMessage: (message) => {
if (refusedRef.current) return;
outbox.current?.post(message);
},
}),
[],
);
const clearUnverifiedTimer = useCallback(() => {
if (unverifiedTimer.current !== null) {
clearTimeout(unverifiedTimer.current);
unverifiedTimer.current = null;
}
}, []);
const refuseNavigation = useCallback(() => {
if (refusedRef.current) return;
refusedRef.current = true;
clearUnverifiedTimer();
outbox.current?.reset(true);
setNavigated(document);
callbacks.current.onError?.({
type: "navigation",
message: "The page tried to navigate and was stopped",
});
}, [clearUnverifiedTimer, document, callbacks]);
const handleReadyToken = useCallback(
(receivedToken: string) => {
if (refusedRef.current || verified.current || loads.current > 1) return;
if (receivedToken !== token) return;
verified.current = true;
clearUnverifiedTimer();
outbox.current?.loaded();
callbacks.current.onLoad?.();
},
[clearUnverifiedTimer, token, callbacks],
);
useEffect(() => {
loads.current = 0;
verified.current = false;
clearUnverifiedTimer();
outbox.current?.reset();
return clearUnverifiedTimer;
}, [document, active, clearUnverifiedTimer]);
useEffect(() => {
if (!active || refused) return;
function receive(event: MessageEvent): void {
if (refusedRef.current) return;
if (event.source === null || event.source !== iframe.current?.contentWindow) return;
handleRouted(routePageMessage(event.data), handleReadyToken);
}
window.addEventListener("message", receive);
return () => window.removeEventListener("message", receive);
}, [active, refused, handleRouted, handleReadyToken]);
const onLoad = useCallback(() => {
if (refusedRef.current) return;
loads.current += 1;
if (loads.current > 1) {
refuseNavigation();
return;
}
if (verified.current) return;
clearUnverifiedTimer();
unverifiedTimer.current = setTimeout(() => {
unverifiedTimer.current = null;
if (!verified.current && !refusedRef.current) {
refuseNavigation();
}
}, READY_TOKEN_GRACE_MS);
}, [clearUnverifiedTimer, refuseNavigation]);
const style = useMemo(
() => ({
display: "block",
border: 0,
width: "100%",
colorScheme: "normal",
background: "transparent",
...(sizing.fill
? { flex: 1, minHeight: 0, height: "100%" }
: { height: sizing.height ?? 0 }),
}),
[sizing.fill, sizing.height],
);
const placeholderHeight = lastHeight.current ?? 0;
const placeholderStyle = useMemo(
() => (sizing.fill ? { flex: 1 } : { height: placeholderHeight }),
[sizing.fill, placeholderHeight],
);
if (!active) {
return <div data-testid={props.testID} style={placeholderStyle} />;
}
return (
// Keyed by document so a changed page loads in a fresh frame (see html-preview.web.tsx).
<iframe
key={`${document}${refused ? "#blank" : ""}`}
ref={iframe}
data-testid={props.testID}
title={t("panels.file.filePanels.builtin.html")}
srcDoc={refused ? BLANK_DOCUMENT : document}
sandbox={SANDBOX}
referrerPolicy="no-referrer"
scrolling={sizing.scrollEnabled ? "yes" : "no"}
onLoad={refused ? undefined : onLoad}
style={style}
/>
);
},
);
@@ -0,0 +1,104 @@
import { describe, expect, it } from "vitest";
import {
INTERNAL_MARKER,
MAX_MESSAGE_BYTES,
routeNativePageText,
routePageMessage,
serializeForPage,
utf8Length,
} from "./messages";
describe("utf8Length", () => {
it("counts bytes, not code units", () => {
expect(utf8Length("abc")).toBe(3);
expect(utf8Length("é")).toBe(2);
expect(utf8Length("€")).toBe(3);
expect(utf8Length("😀")).toBe(4);
});
});
describe("routePageMessage", () => {
it("passes ordinary JSON values to the host", () => {
for (const value of [{ a: 1 }, [1, 2], "text", 5, null, true]) {
expect(routePageMessage(value)).toEqual({ kind: "page", value });
}
});
it("keeps height reports away from onMessage and rounds them up", () => {
expect(routePageMessage({ [INTERNAL_MARKER]: { type: "height", height: 120.2 } })).toEqual({
kind: "internal",
message: { type: "height", height: 121 },
});
});
it("truncates reported script errors", () => {
const routed = routePageMessage({
[INTERNAL_MARKER]: { type: "error", message: "x".repeat(2000) },
});
expect(routed.kind).toBe("internal");
if (routed.kind === "internal" && routed.message.type === "error") {
expect(routed.message.message).toHaveLength(500);
}
});
it("keeps ready tokens away from onMessage", () => {
expect(routePageMessage({ [INTERNAL_MARKER]: { type: "ready", token: "abc123" } })).toEqual({
kind: "internal",
message: { type: "ready", token: "abc123" },
});
});
it.each([
["empty ready token", { type: "ready", token: "" }],
["non-string ready token", { type: "ready", token: 123 }],
["negative height", { type: "height", height: -1 }],
["infinite height", { type: "height", height: Infinity }],
["string height", { type: "height", height: "9" }],
["unknown type", { type: "resize" }],
["non-string error", { type: "error", message: 4 }],
["not an object", "height"],
])("drops a malformed internal envelope: %s", (_name, inner) => {
expect(routePageMessage({ [INTERNAL_MARKER]: inner }).kind).toBe("dropped");
});
it("drops values that are not JSON", () => {
const cyclic: Record<string, unknown> = {};
cyclic.self = cyclic;
expect(routePageMessage(cyclic).kind).toBe("dropped");
expect(routePageMessage(undefined).kind).toBe("dropped");
});
it("drops a message over 4 MB", () => {
expect(routePageMessage("x".repeat(MAX_MESSAGE_BYTES)).kind).toBe("dropped");
expect(routePageMessage("x".repeat(MAX_MESSAGE_BYTES - 2)).kind).toBe("page");
});
});
describe("routeNativePageText", () => {
it("parses JSON text and routes it", () => {
expect(routeNativePageText('{"hello":"world"}')).toEqual({
kind: "page",
value: { hello: "world" },
});
expect(
routeNativePageText(JSON.stringify({ [INTERNAL_MARKER]: { type: "height", height: 10 } }))
.kind,
).toBe("internal");
});
it("drops non-text, invalid JSON and oversized text", () => {
expect(routeNativePageText(5).kind).toBe("dropped");
expect(routeNativePageText("{nope").kind).toBe("dropped");
expect(routeNativePageText(`"${"x".repeat(MAX_MESSAGE_BYTES)}"`).kind).toBe("dropped");
});
});
describe("serializeForPage", () => {
it("serializes JSON and refuses what cannot be sent", () => {
expect(serializeForPage({ a: 1 })).toEqual({ ok: true, text: '{"a":1}' });
expect(serializeForPage(undefined).ok).toBe(false);
expect(serializeForPage(() => 1).ok).toBe(false);
expect(serializeForPage(10n).ok).toBe(false);
expect(serializeForPage("x".repeat(MAX_MESSAGE_BYTES)).ok).toBe(false);
});
});
+110
View File
@@ -0,0 +1,110 @@
// Messages between the host and the page. Everything the page sends is untrusted: it can forge the
// private marker too, so internal messages only ever carry values the host clamps, truncates, or
// checks against a per-mount token.
/** Cap per message, in each direction. */
export const MAX_MESSAGE_BYTES = 4 * 1024 * 1024;
/** Key of the private envelope the bootstrap uses. Pages that post it get it treated as internal. */
export const INTERNAL_MARKER = "__paseoHtmlFrame";
const MAX_ERROR_LENGTH = 500;
const MAX_TOKEN_LENGTH = 128;
export type InternalMessage =
| { type: "ready"; token: string }
| { type: "height"; height: number }
| { type: "error"; message: string };
export function utf8Length(text: string): number {
let bytes = 0;
for (let index = 0; index < text.length; index += 1) {
const code = text.charCodeAt(index);
if (code < 0x80) bytes += 1;
else if (code < 0x800) bytes += 2;
else if (code >= 0xd800 && code <= 0xdbff) {
bytes += 4;
index += 1;
} else bytes += 3;
}
return bytes;
}
export type Serialized = { ok: true; text: string } | { ok: false; reason: string };
/** JSON text of a value bound for the page, or why it cannot be sent. */
export function serializeForPage(value: unknown): Serialized {
let text: string | undefined;
try {
text = JSON.stringify(value);
} catch {
return { ok: false, reason: "message is not JSON-serializable" };
}
if (text === undefined) return { ok: false, reason: "message is not JSON-serializable" };
if (utf8Length(text) > MAX_MESSAGE_BYTES) {
return { ok: false, reason: "message is larger than 4 MB" };
}
return { ok: true, text };
}
export type Routed =
| { kind: "internal"; message: InternalMessage }
| { kind: "page"; value: unknown }
| { kind: "dropped"; reason: string };
function parseInternal(value: Record<string, unknown>): InternalMessage | null {
if (value.type === "ready") {
if (typeof value.token !== "string" || value.token.length === 0) return null;
if (value.token.length > MAX_TOKEN_LENGTH) return null;
return { type: "ready", token: value.token };
}
if (value.type === "height") {
const height = value.height;
if (typeof height !== "number" || !Number.isFinite(height) || height < 0) return null;
return { type: "height", height: Math.ceil(height) };
}
if (value.type === "error") {
if (typeof value.message !== "string") return null;
return { type: "error", message: value.message.slice(0, MAX_ERROR_LENGTH) };
}
return null;
}
/**
* Classifies a value the page posted. `value` is the already-parsed message (native: after
* JSON.parse; web: the structured-clone result, re-measured through JSON here).
*/
export function routePageMessage(value: unknown): Routed {
const serialized = serializeForPage(value);
if (!serialized.ok) return { kind: "dropped", reason: `page ${serialized.reason}` };
if (typeof value === "object" && value !== null && !Array.isArray(value)) {
const record = value as Record<string, unknown>;
if (INTERNAL_MARKER in record) {
const inner = record[INTERNAL_MARKER];
const message =
typeof inner === "object" && inner !== null
? parseInternal(inner as Record<string, unknown>)
: null;
// A malformed internal envelope is dropped, never forwarded to onMessage.
return message
? { kind: "internal", message }
: { kind: "dropped", reason: "malformed internal message" };
}
}
return { kind: "page", value };
}
/** Routes the text a native WebView delivered. Size is checked before parsing. */
export function routeNativePageText(text: unknown): Routed {
if (typeof text !== "string") return { kind: "dropped", reason: "page message is not text" };
if (utf8Length(text) > MAX_MESSAGE_BYTES) {
return { kind: "dropped", reason: "page message is larger than 4 MB" };
}
let value: unknown;
try {
value = JSON.parse(text);
} catch {
return { kind: "dropped", reason: "page message is not JSON" };
}
return routePageMessage(value);
}
@@ -0,0 +1,58 @@
import { describe, expect, it } from "vitest";
import { PageOutbox } from "./outbox";
function setup() {
const delivered: string[] = [];
const errors: string[] = [];
const outbox = new PageOutbox(
(text) => delivered.push(text),
(message) => errors.push(message),
);
return { outbox, delivered, errors };
}
describe("PageOutbox", () => {
it("holds messages until the page loaded, then delivers them in order", () => {
const { outbox, delivered } = setup();
outbox.post({ n: 1 });
outbox.post({ n: 2 });
expect(delivered).toEqual([]);
outbox.loaded();
expect(delivered).toEqual(['{"n":1}', '{"n":2}']);
outbox.post({ n: 3 });
expect(delivered).toHaveLength(3);
});
it("holds messages again after reset", () => {
const { outbox, delivered } = setup();
outbox.loaded();
outbox.reset();
outbox.post("a");
expect(delivered).toEqual([]);
outbox.loaded();
expect(delivered).toEqual(['"a"']);
});
it("drops queued messages when reset with clearQueue", () => {
const { outbox, delivered } = setup();
outbox.post({ secret: "token" });
outbox.reset(true);
outbox.loaded();
expect(delivered).toEqual([]);
});
it("reports what cannot be sent and never delivers it", () => {
const { outbox, delivered, errors } = setup();
outbox.loaded();
outbox.post(undefined);
outbox.post("x".repeat(5 * 1024 * 1024));
expect(delivered).toEqual([]);
expect(errors).toHaveLength(2);
});
it("caps the queue", () => {
const { outbox, errors } = setup();
for (let index = 0; index < 60; index += 1) outbox.post(index);
expect(errors).toHaveLength(10);
});
});
+48
View File
@@ -0,0 +1,48 @@
import { serializeForPage } from "./messages";
const MAX_QUEUED = 50;
/**
* Host → page messages. Posts made before the page finished loading wait for it, because a message
* delivered earlier would arrive before the page can have a listener.
*/
export class PageOutbox {
private queue: string[] = [];
private ready = false;
constructor(
private readonly deliver: (text: string) => void,
private readonly onError: (message: string) => void,
) {}
post(value: unknown): void {
const serialized = serializeForPage(value);
if (!serialized.ok) {
this.onError(`postMessage: ${serialized.reason}`);
return;
}
if (this.ready) {
this.deliver(serialized.text);
return;
}
if (this.queue.length >= MAX_QUEUED) {
this.onError("postMessage: too many messages before the page loaded");
return;
}
this.queue.push(serialized.text);
}
/** The page loaded: flush what is waiting. */
loaded(): void {
this.ready = true;
const waiting = this.queue;
this.queue = [];
for (const text of waiting) this.deliver(text);
}
/** A new document is loading (or the view went away): hold messages again, optionally clearing the queue. */
reset(clearQueue = false): void {
this.ready = false;
if (clearQueue) this.queue = [];
}
}
@@ -0,0 +1,68 @@
import { describe, expect, it } from "vitest";
import { resolveSizing } from "./sizing";
describe("resolveSizing", () => {
it("auto-sizes by default, clamped to 80..1400", () => {
expect(resolveSizing({}, null)).toMatchObject({
height: 80,
autoSize: true,
scrollEnabled: false,
});
expect(resolveSizing({}, 300).height).toBe(300);
expect(resolveSizing({}, 20).height).toBe(80);
expect(resolveSizing({}, 5000).height).toBe(1400);
});
it("treats bare `height` as fixed height unless `autoHeight` is also provided", () => {
expect(resolveSizing({ height: 300 }, null)).toMatchObject({
height: 300,
autoSize: false,
scrollEnabled: true,
});
expect(resolveSizing({ height: 300 }, 900)).toMatchObject({
height: 300,
autoSize: false,
scrollEnabled: true,
});
expect(resolveSizing({ height: 200, autoHeight: {} }, null).height).toBe(200);
expect(resolveSizing({ height: 200, autoHeight: {} }, 300).height).toBe(300);
});
it("honours custom bounds and repairs inverted ones", () => {
expect(resolveSizing({ autoHeight: { min: 100, max: 200 } }, 900).height).toBe(200);
expect(resolveSizing({ autoHeight: { max: 50 } }, 10).height).toBe(50);
expect(resolveSizing({ autoHeight: { max: 50 } }, 200).height).toBe(50);
expect(resolveSizing({ autoHeight: { min: 0, max: 50 } }, 20).height).toBe(20);
expect(resolveSizing({ autoHeight: { min: 300, max: 200 } }, 10).height).toBe(300);
});
it("scrolls inside an auto-sized frame only once content outgrows the cap", () => {
expect(resolveSizing({}, 1400).scrollEnabled).toBe(false);
expect(resolveSizing({}, 1401).scrollEnabled).toBe(true);
expect(resolveSizing({ scrollEnabled: false }, 5000).scrollEnabled).toBe(false);
});
it("uses the fixed height and scrolls when auto-height is off", () => {
expect(resolveSizing({ autoHeight: false, height: 320 }, 900)).toMatchObject({
height: 320,
autoSize: false,
scrollEnabled: true,
});
expect(resolveSizing({ autoHeight: false }, null).height).toBe(240);
});
it("fills the parent and scrolls, ignoring the measure", () => {
expect(resolveSizing({ fill: true, height: 100, autoHeight: { min: 1 } }, 500)).toEqual({
fill: true,
height: null,
scrollEnabled: true,
autoSize: false,
});
expect(resolveSizing({ fill: true, scrollEnabled: false }, null).scrollEnabled).toBe(false);
});
it("ignores non-finite inputs", () => {
expect(resolveSizing({ height: Number.NaN, autoHeight: false }, null).height).toBe(240);
expect(resolveSizing({ autoHeight: { min: Number.NaN } }, null).height).toBe(80);
});
});
+75
View File
@@ -0,0 +1,75 @@
export const DEFAULT_AUTO_HEIGHT = { min: 80, max: 1400 } as const;
const DEFAULT_FIXED_HEIGHT = 240;
export interface HtmlFrameSizing {
autoHeight?: { min?: number; max?: number } | false;
height?: number;
fill?: boolean;
scrollEnabled?: boolean;
}
export interface ResolvedSizing {
fill: boolean;
/** Pixel height of the frame; null when `fill` owns the size. */
height: number | null;
scrollEnabled: boolean;
autoSize: boolean;
}
function finiteOrUndefined(value: unknown): number | undefined {
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
}
function finite(value: unknown, fallback: number): number {
return finiteOrUndefined(value) ?? fallback;
}
export function autoHeightBounds(autoHeight: HtmlFrameSizing["autoHeight"]): {
min: number;
max: number;
} {
const explicitMin = autoHeight ? finiteOrUndefined(autoHeight.min) : undefined;
const explicitMax = autoHeight ? finiteOrUndefined(autoHeight.max) : undefined;
const rawMax = Math.max(0, explicitMax ?? DEFAULT_AUTO_HEIGHT.max);
const min =
explicitMin !== undefined
? Math.max(0, explicitMin)
: Math.min(DEFAULT_AUTO_HEIGHT.min, rawMax);
const max = Math.max(min, rawMax);
return { min, max };
}
/** `measured` is the page's content height, or null before the first measure. */
export function resolveSizing(props: HtmlFrameSizing, measured: number | null): ResolvedSizing {
if (props.fill) {
return {
fill: true,
height: null,
scrollEnabled: props.scrollEnabled ?? true,
autoSize: false,
};
}
const explicitHeight = finiteOrUndefined(props.height);
if (
props.autoHeight === false ||
(props.autoHeight === undefined && explicitHeight !== undefined)
) {
return {
fill: false,
height: Math.max(0, finite(props.height, DEFAULT_FIXED_HEIGHT)),
scrollEnabled: props.scrollEnabled ?? true,
autoSize: false,
};
}
const { min, max } = autoHeightBounds(props.autoHeight);
const content = measured ?? finite(props.height, min);
const height = Math.min(max, Math.max(min, content));
// Inline apps do not scroll inside themselves, unless content outgrew the cap and would be cut off.
const overflowing = measured !== null && measured > max;
return {
fill: false,
height,
scrollEnabled: props.scrollEnabled ?? overflowing,
autoSize: true,
};
}
+7
View File
@@ -0,0 +1,7 @@
export type {
HtmlFrameContentHeightEvent,
HtmlFrameCsp,
HtmlFrameErrorEvent,
HtmlFrameHandle,
HtmlFrameProps,
} from "@getpaseo/plugin/client/ui";

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