mirror of
https://github.com/getpaseo/paseo.git
synced 2026-12-05 22:55:33 +00:00
Compare commits
26
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6291549834 | ||
|
|
51f22b3d42 | ||
|
|
d4b380f4e0 | ||
|
|
bf8a357717 | ||
|
|
bce9375580 | ||
|
|
f64d11ac60 | ||
|
|
c323914ca2 | ||
|
|
a923b4c4c5 | ||
|
|
05e273826b | ||
|
|
fd22f024c4 | ||
|
|
ff69af881d | ||
|
|
d78032e899 | ||
|
|
1a5bd739a6 | ||
|
|
5bee8eacc8 | ||
|
|
80e1089fb6 | ||
|
|
087b789035 | ||
|
|
238172244b | ||
|
|
b6fdf099b6 | ||
|
|
f8691c480f | ||
|
|
765aec33e5 | ||
|
|
073743647a | ||
|
|
6b3b349c8b | ||
|
|
b1bb161133 | ||
|
|
2f1fc53cdb | ||
|
|
617ebbdb1a | ||
|
|
c174f475c8 |
@@ -63,7 +63,7 @@ jobs:
|
||||
filters: .github/ci-paths.yml
|
||||
|
||||
- name: Validate CI contracts
|
||||
run: node --test packages/react-native-enriched-markdown/vendor-grammars.test.mjs scripts/ci-workflow.test.mjs scripts/daemon-launch-contract.test.mjs scripts/changelog-utils.test.mjs scripts/release-version-utils.test.mjs scripts/publish-release-packages.test.mjs scripts/push-current-release-tag.test.mjs scripts/reconcile-release.test.mjs scripts/sync-fdroid-changelogs.test.mjs scripts/sync-release-notes-from-changelog.test.mjs scripts/upload-release-assets.test.mjs scripts/release-checksums.test.mjs scripts/precompress-assets.test.mjs
|
||||
run: node --test packages/react-native-enriched-markdown/vendor-grammars.test.mjs scripts/ci-workflow.test.mjs scripts/daemon-launch-contract.test.mjs scripts/changelog-utils.test.mjs scripts/release-version-utils.test.mjs scripts/publish-release-packages.test.mjs scripts/push-current-release-tag.test.mjs scripts/reconcile-release.test.mjs scripts/sync-fdroid-changelogs.test.mjs scripts/sync-release-notes-from-changelog.test.mjs scripts/upload-release-assets.test.mjs scripts/release-checksums.test.mjs scripts/precompress-assets.test.mjs scripts/check-web-export-size.test.mjs
|
||||
|
||||
quality:
|
||||
name: quality
|
||||
@@ -523,6 +523,13 @@ jobs:
|
||||
- name: Run app unit tests
|
||||
run: npm run test --workspace=@getpaseo/app
|
||||
|
||||
# Cloudflare Pages rejects files over 25 MiB; fail here, not at release-tag deploy.
|
||||
- name: Export web app and check file sizes
|
||||
working-directory: packages/app
|
||||
run: |
|
||||
npx expo export --platform web
|
||||
npm run check:web-size
|
||||
|
||||
playwright-1:
|
||||
name: playwright (shard 1/8)
|
||||
needs: changes
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
# Changelog
|
||||
|
||||
## 0.19.2 - 2026-12-05
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed OpenCode v2 skills picked inline, with attachments, or while a turn is running being sent as literal `/skill` text instead of loading the skill ([#12142](https://github.com/getpaseo/paseo/pull/12142))
|
||||
- Fixed Codex skills picked inline, with attachments, or while a turn is running not loading ([#12143](https://github.com/getpaseo/paseo/pull/12143))
|
||||
- Fixed Desktop image attachments disappearing across multiple windows, tab switches, and queued follow-up sends ([#12082](https://github.com/getpaseo/paseo/pull/12082))
|
||||
|
||||
## 0.19.1 - 2026-12-03
|
||||
|
||||
### Changed
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
# Changelog
|
||||
|
||||
## 0.19.2 - 2026-12-05
|
||||
|
||||
### 修复
|
||||
|
||||
- 修复 OpenCode v2 中在消息中间、带附件或运行中选择的 Skill 被当作字面 `/skill` 文本发送而未加载的问题 ([#12142](https://github.com/getpaseo/paseo/pull/12142))
|
||||
- 修复 Codex 中在消息中间、带附件或运行中选择的 Skill 未加载的问题 ([#12143](https://github.com/getpaseo/paseo/pull/12143))
|
||||
- 修复桌面端图片附件在多窗口、切换标签页和排队发送追问消息时丢失的问题 ([#12082](https://github.com/getpaseo/paseo/pull/12082))
|
||||
|
||||
## 0.19.1 - 2026-12-03
|
||||
|
||||
### 变更
|
||||
|
||||
@@ -175,7 +175,7 @@ The app runs on iOS, Android, web (browser), and web (Electron desktop). Code is
|
||||
| Use a native-only API (Haptics, push tokens, camera) | `if (isNative)` |
|
||||
| Use an Electron bridge (file dialog, titlebar, updates) | `if (getIsElectron())` |
|
||||
| Switch layout between phone and tablet/desktop | `useIsCompactFormFactor()` |
|
||||
| Show something on hover, always-visible on native | `isHovered \|\| isNative \|\| isCompact` (hover only works on web) |
|
||||
| Show something on hover, always-visible on touch screens | `isHovered \|\| revealsWithoutHover` (see [docs/hover.md](docs/hover.md)) |
|
||||
| Gate to iOS or Android specifically | `Platform.OS === "ios"` / `Platform.OS === "android"` (rare, keep inline) |
|
||||
|
||||
### Rules
|
||||
@@ -198,7 +198,7 @@ The app runs on iOS, Android, web (browser), and web (Electron desktop). Code is
|
||||
Import as `@/desktop/browser/pane` — Electron desktop gets the `.electron.tsx` file, browser web gets `.web.tsx`, and native gets the native/base implementation.
|
||||
- **NEVER use raw DOM APIs without `isWeb` guard.** DOM APIs crash native. Casting a RN ref to `HTMLElement` is a red flag — ensure the block is web-only.
|
||||
- **NEVER use `onPointerEnter`/`onPointerLeave`.** They don't fire on native iOS.
|
||||
- **Hover only works on web.** React Native's `onHoverIn`/`onHoverOut` on `Pressable` does NOT fire on native iOS/iPad — the underlying W3C pointer events are behind disabled experimental flags. For hover-to-show UI (kebab menus, action buttons), use `isHovered || isNative || isCompact` so the controls are always visible on native and hover-to-show on web.
|
||||
- **Hover needs a mouse-like pointer.** React Native's `onHoverIn`/`onHoverOut` on `Pressable` does NOT fire on native iOS/iPad — the underlying W3C pointer events are behind disabled experimental flags. For hover-to-show UI (kebab menus, action buttons), call `useRevealsWithoutHover()` unconditionally, then use `isHovered || revealsWithoutHover` so the controls are always visible on touch screens and hover-to-show elsewhere. Don't use `isNative` for this: a native build is not the only touch-first surface, since a touch-first browser such as iPad Safari is `isWeb` but cannot hover.
|
||||
- **Don't use Platform.OS as a proxy for layout capabilities.** Use breakpoints for layout decisions, not platform checks.
|
||||
- **Import `isWeb`/`isNative` from `@/constants/platform`.** Never write `const isWeb = Platform.OS === "web"` locally.
|
||||
|
||||
|
||||
+7
-6
@@ -111,17 +111,18 @@ rendered while the menu is up. `useOpenKebabMenuVisibility`
|
||||
sidebar rows: it owns `open`, hands the menu its controlled props, and ORs `open` into the
|
||||
row's own `showKebab`.
|
||||
|
||||
## Native fallback
|
||||
## Touch fallback
|
||||
|
||||
Hover doesn't exist on touch devices. Anything you hide behind hover must have a non-hover path on native and compact layouts:
|
||||
Hover doesn't exist on touch screens. Anything you hide behind hover must have a non-hover path on touch screens and compact layouts:
|
||||
|
||||
```tsx
|
||||
const showControls = isHovered || isNative || isCompact;
|
||||
const revealsWithoutHover = useRevealsWithoutHover();
|
||||
const showControls = isHovered || revealsWithoutHover;
|
||||
```
|
||||
|
||||
`isNative` and `isCompact` come from `@/constants/platform` and `@/constants/layout`. Don't use `Platform.OS === "ios"` as a proxy.
|
||||
`useRevealsWithoutHover()` (`@/hooks/hover-reveal`) asks the pointer, not the platform: it is true when no mouse-like pointer drives the UI or the layout is compact. Don't use `isNative` for this. A touch-first browser such as iPad Safari is `isWeb` yet cannot hover, so `isNative` would leave its hover controls unreachable.
|
||||
|
||||
`onPointerEnter` / `onPointerLeave` are DOM events. They do not fire on native. You do not need to gate them — on native, hover is unreachable anyway and visibility is driven by `isNative` / `isCompact` in your show-the-controls expression above. This is why the workspace row's pointer events are not wrapped in `if (isWeb)`.
|
||||
`onPointerEnter` / `onPointerLeave` are DOM events. They fire on the web and do not fire on iOS or Android. You do not need to gate them: on a touch screen, hover is unreachable and visibility comes from `useRevealsWithoutHover()`. This is why the workspace row's pointer events are not wrapped in `if (isWeb)`.
|
||||
|
||||
## What about `Pressable.onHoverIn` / `onHoverOut`?
|
||||
|
||||
@@ -148,7 +149,7 @@ Before opening a PR that touches hover:
|
||||
- [ ] The hover trigger's bounding box contains every element the user might mouse into while interacting with the feature.
|
||||
- [ ] Hovered state does **not** change the trigger's outer geometry (`width`, `height`, `padding`, `borderWidth`, mount/unmount of siblings that shift it). Internal swaps fit inside a fixed `minHeight` / `minWidth`.
|
||||
- [ ] Revealed content inside the trigger uses `opacity` + `pointerEvents`, not conditional rendering, if mounting it would reflow the trigger.
|
||||
- [ ] Visibility on native and compact layouts works without hover (`isHovered || isNative || isCompact`).
|
||||
- [ ] Visibility on touch screens and compact layouts works without hover (`isHovered || revealsWithoutHover`, with `useRevealsWithoutHover()` called unconditionally).
|
||||
- [ ] A menu opened from the revealed trigger keeps the trigger rendered while it is open, so losing hover can't strand it.
|
||||
- [ ] If the revealed content sits in a separate layer (portal, floating panel) and the user can point at it, it is a `HoverCard`.
|
||||
- [ ] You opened the dev server, hovered the trigger, and slowly moved the mouse along **every** revealed element — including any visible gaps — without losing hover state.
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
Fixed
|
||||
- Fixed OpenCode v2 skills picked inline, with attachments, or while a turn is running being sent as literal /skill text instead of loading the skill
|
||||
- Fixed Codex skills picked inline, with attachments, or while a turn is running not loading
|
||||
- Fixed Desktop image attachments disappearing across multiple windows, tab switches, and queued follow-up sends
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -0,0 +1,6 @@
|
||||
Fixed
|
||||
- Fixed OpenCode v2 skills picked inline, with attachments, or while a turn is running being sent as literal /skill text instead of loading the skill
|
||||
- Fixed Codex skills picked inline, with attachments, or while a turn is running not loading
|
||||
- Fixed Desktop image attachments disappearing across multiple windows, tab switches, and queued follow-up sends
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -0,0 +1,6 @@
|
||||
Fixed
|
||||
- Fixed OpenCode v2 skills picked inline, with attachments, or while a turn is running being sent as literal /skill text instead of loading the skill
|
||||
- Fixed Codex skills picked inline, with attachments, or while a turn is running not loading
|
||||
- Fixed Desktop image attachments disappearing across multiple windows, tab switches, and queued follow-up sends
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -0,0 +1,6 @@
|
||||
Fixed
|
||||
- Fixed OpenCode v2 skills picked inline, with attachments, or while a turn is running being sent as literal /skill text instead of loading the skill
|
||||
- Fixed Codex skills picked inline, with attachments, or while a turn is running not loading
|
||||
- Fixed Desktop image attachments disappearing across multiple windows, tab switches, and queued follow-up sends
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
+1
-1
@@ -1 +1 @@
|
||||
sha256-C21T1lgFJLeGaA7hVUXH/i6YUFq6rlOJFo5pq5yfHY8=
|
||||
sha256-nWaU16CvKjT2bhQ/Q0gxZOv2NGxODBwn7lZ/EQgE+u0=
|
||||
|
||||
Generated
+29
-29
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "paseo",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "paseo",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"hasInstallScript": true,
|
||||
"license": "Apache-2.0",
|
||||
"workspaces": [
|
||||
@@ -37659,7 +37659,7 @@
|
||||
},
|
||||
"packages/app": {
|
||||
"name": "@getpaseo/app",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"dependencies": {
|
||||
"@codemirror/commands": "6.10.4",
|
||||
"@codemirror/language": "6.12.4",
|
||||
@@ -39813,13 +39813,13 @@
|
||||
},
|
||||
"packages/cli": {
|
||||
"name": "@getpaseo/cli",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@clack/prompts": "1.1.0",
|
||||
"@getpaseo/client": "0.19.1",
|
||||
"@getpaseo/protocol": "0.19.1",
|
||||
"@getpaseo/server": "0.19.1",
|
||||
"@getpaseo/client": "0.19.2",
|
||||
"@getpaseo/protocol": "0.19.2",
|
||||
"@getpaseo/server": "0.19.2",
|
||||
"chalk": "5.6.2",
|
||||
"commander": "12.1.0",
|
||||
"mime-types": "2.1.35",
|
||||
@@ -40069,11 +40069,11 @@
|
||||
},
|
||||
"packages/client": {
|
||||
"name": "@getpaseo/client",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@getpaseo/protocol": "0.19.1",
|
||||
"@getpaseo/relay": "0.19.1",
|
||||
"@getpaseo/protocol": "0.19.2",
|
||||
"@getpaseo/relay": "0.19.2",
|
||||
"ws": "^8.20.0",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
@@ -40085,7 +40085,7 @@
|
||||
},
|
||||
"packages/desktop": {
|
||||
"name": "@getpaseo/desktop",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@getpaseo/cli": "*",
|
||||
@@ -40329,7 +40329,7 @@
|
||||
},
|
||||
"packages/expo-two-way-audio": {
|
||||
"name": "@getpaseo/expo-two-way-audio",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@types/jest": "^29.5.14",
|
||||
@@ -40375,7 +40375,7 @@
|
||||
},
|
||||
"packages/highlight": {
|
||||
"name": "@getpaseo/highlight",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@codemirror/language": "6.12.4",
|
||||
@@ -40405,7 +40405,7 @@
|
||||
},
|
||||
"packages/plugin": {
|
||||
"name": "@getpaseo/plugin",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "^1.4.0",
|
||||
@@ -40413,8 +40413,8 @@
|
||||
"use-sync-external-store": "^1.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@getpaseo/client": "0.19.1",
|
||||
"@getpaseo/protocol": "0.19.1",
|
||||
"@getpaseo/client": "0.19.2",
|
||||
"@getpaseo/protocol": "0.19.2",
|
||||
"@types/node": "^20.9.0",
|
||||
"@types/react": "~19.2.0",
|
||||
"react": "19.2.3",
|
||||
@@ -40424,8 +40424,8 @@
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@getpaseo/client": "0.19.1",
|
||||
"@getpaseo/protocol": "0.19.1",
|
||||
"@getpaseo/client": "0.19.2",
|
||||
"@getpaseo/protocol": "0.19.2",
|
||||
"react": ">=19.1.0 <20",
|
||||
"react-native": ">=0.81.5",
|
||||
"zod": "^4.4.3"
|
||||
@@ -40447,7 +40447,7 @@
|
||||
},
|
||||
"packages/protocol": {
|
||||
"name": "@getpaseo/protocol",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"semver": "^7.8.5",
|
||||
@@ -40474,7 +40474,7 @@
|
||||
}
|
||||
},
|
||||
"packages/react-native-enriched-markdown": {
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
@@ -40490,7 +40490,7 @@
|
||||
},
|
||||
"packages/relay": {
|
||||
"name": "@getpaseo/relay",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@noble/ciphers": "^2.4.0",
|
||||
@@ -40712,17 +40712,17 @@
|
||||
},
|
||||
"packages/server": {
|
||||
"name": "@getpaseo/server",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "0.17.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "0.3.326",
|
||||
"@anthropic-ai/sdk": "0.104.2",
|
||||
"@getpaseo/client": "0.19.1",
|
||||
"@getpaseo/highlight": "0.19.1",
|
||||
"@getpaseo/plugin": "0.19.1",
|
||||
"@getpaseo/protocol": "0.19.1",
|
||||
"@getpaseo/relay": "0.19.1",
|
||||
"@getpaseo/client": "0.19.2",
|
||||
"@getpaseo/highlight": "0.19.2",
|
||||
"@getpaseo/plugin": "0.19.2",
|
||||
"@getpaseo/protocol": "0.19.2",
|
||||
"@getpaseo/relay": "0.19.2",
|
||||
"@isaacs/ttlcache": "2.1.4",
|
||||
"@modelcontextprotocol/node": "2.1.2",
|
||||
"@modelcontextprotocol/sdk": "1.29.0",
|
||||
@@ -41687,7 +41687,7 @@
|
||||
},
|
||||
"packages/website": {
|
||||
"name": "@getpaseo/website",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"dependencies": {
|
||||
"@cloudflare/vite-plugin": "^1.29.1",
|
||||
"@cloudflare/workers-types": "^4.20260317.1",
|
||||
@@ -43313,7 +43313,7 @@
|
||||
},
|
||||
"plugins": {
|
||||
"name": "@getpaseo/builtin-plugins",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"dependencies": {
|
||||
"@getpaseo/plugin": "*",
|
||||
"zod": "^4.4.3"
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "paseo",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"private": true,
|
||||
"description": "Paseo: voice-controlled development environment for local AI coding agents",
|
||||
"keywords": [
|
||||
|
||||
@@ -29,6 +29,8 @@ import {
|
||||
expectWorkspaceAgentConfiguration,
|
||||
openCommandCenterForAgent,
|
||||
} from "../support/helpers/command-center-agent-controls";
|
||||
import { openSettingsWithShortcut } from "../support/helpers/app";
|
||||
import { clickSettingsBackToWorkspace } from "../support/helpers/settings";
|
||||
import { expectComposerVisible } from "../support/helpers/composer";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
|
||||
@@ -297,6 +299,34 @@ test.describe("Agent profiles in the model picker", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("the composer profile editor reopens after visiting Settings", async ({ page }) => {
|
||||
const seed = await seedAgentProfiles([PROFILE]);
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "agent-profiles-settings-return-",
|
||||
title: "Agent profiles Settings return",
|
||||
model: "ten-second-stream",
|
||||
modeId: "load-test",
|
||||
});
|
||||
const model = { provider: PROFILE.provider, modelId: PROFILE.model };
|
||||
|
||||
try {
|
||||
await openAgentRoute(page, workspace);
|
||||
await expectComposerVisible(page);
|
||||
await openModelPicker(page);
|
||||
await openEditProfileFromModelRow(page, model);
|
||||
|
||||
await openSettingsWithShortcut(page);
|
||||
await clickSettingsBackToWorkspace(page);
|
||||
await expectComposerVisible(page);
|
||||
await openModelPicker(page);
|
||||
await openEditProfileFromModelRow(page, model);
|
||||
await expectAgentProfileNameDraft(page, PROFILE.name);
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
await seed.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("canceling Remove in the composer profile editor keeps the editor and draft open", async ({
|
||||
page,
|
||||
}) => {
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { expect } from "@playwright/test";
|
||||
import { test } from "../support/fixtures";
|
||||
import {
|
||||
expectCompletedDiagram,
|
||||
requestDiagram,
|
||||
waitForDiagramTurnToComplete,
|
||||
} from "../support/helpers/diagram";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
|
||||
const MERMAID_DIAGRAM = [
|
||||
"```mermaid",
|
||||
"flowchart LR",
|
||||
" Start --> Middle",
|
||||
" Middle --> Ship",
|
||||
"```",
|
||||
].join("\n");
|
||||
|
||||
test("keeps the diagram source when the Mermaid runtime fails to load, then renders after it recovers", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(120_000);
|
||||
let runtimeChunkReachable = false;
|
||||
let blockedRequests = 0;
|
||||
await page.route(/html\.gen/, async (route) => {
|
||||
if (runtimeChunkReachable) {
|
||||
await route.continue();
|
||||
return;
|
||||
}
|
||||
blockedRequests += 1;
|
||||
await route.abort("connectionrefused");
|
||||
});
|
||||
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "mermaid-runtime-load-",
|
||||
title: "Mermaid runtime load",
|
||||
featureValues: {
|
||||
mockStreamingAssistantResponse: MERMAID_DIAGRAM,
|
||||
mockStreamingAssistantIntervalMs: 10,
|
||||
},
|
||||
});
|
||||
try {
|
||||
await test.step("A failed runtime load leaves the diagram source on screen", async () => {
|
||||
await openAgentRoute(page, agent);
|
||||
await requestDiagram(agent);
|
||||
await waitForDiagramTurnToComplete(agent);
|
||||
await expect(page.getByText("Middle --> Ship")).toBeVisible({ timeout: 30_000 });
|
||||
expect(blockedRequests).toBeGreaterThan(0);
|
||||
await expect(page.getByRole("img", { name: "Diagram" }).locator("iframe")).toHaveCount(0);
|
||||
});
|
||||
|
||||
await test.step("Once the chunk is reachable, the next diagram loads it and renders", async () => {
|
||||
runtimeChunkReachable = true;
|
||||
await requestDiagram(agent);
|
||||
await waitForDiagramTurnToComplete(agent);
|
||||
await expectCompletedDiagram(page, ["Start", "Ship"]);
|
||||
});
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
withPluginFocusingAnAgentWithContextUsage,
|
||||
withPluginHoldingNewWorkspaceComposer,
|
||||
withPluginWritingToAnotherWorkspace,
|
||||
withPluginSettingsFromComposer,
|
||||
} from "../support/helpers/plugin-composers-by-reference";
|
||||
|
||||
test("a panel in the Explorer inserts at the cursor of the focused agent's composer", async ({
|
||||
@@ -221,3 +222,26 @@ test("focus reaches an agent kept in the Explorer on a compact screen", async ({
|
||||
await author.expectParentReadyToType();
|
||||
});
|
||||
});
|
||||
|
||||
test("Settings accepts clicks after a composer plugin closes its dialog and navigates", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(120_000);
|
||||
await withPluginSettingsFromComposer(page, { width: 1280, height: 800 }, async (flow) => {
|
||||
await flow.openPluginDialog();
|
||||
await flow.openSettingsFromPlugin();
|
||||
await flow.changeSetting();
|
||||
await flow.returnToChat();
|
||||
});
|
||||
});
|
||||
|
||||
test("Settings accepts clicks after navigation from the compact model sheet", async ({ page }) => {
|
||||
test.setTimeout(120_000);
|
||||
await withPluginSettingsFromComposer(page, { width: 430, height: 900 }, async (flow) => {
|
||||
await flow.openModelSheet();
|
||||
await flow.openPluginDialog();
|
||||
await flow.openSettingsFromPlugin();
|
||||
await flow.changeSetting();
|
||||
await flow.returnToChat();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -410,3 +410,41 @@ async function connectToTestHost(page: import("@playwright/test").Page) {
|
||||
await page.getByRole("button", { name: "Connect", exact: true }).click();
|
||||
await expect(page.getByTestId("add-host-modal")).toBeHidden({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
test.describe("Settings host page on a wide touch screen", () => {
|
||||
test.use({ viewport: { width: 1400, height: 480 }, hasTouch: true, isMobile: true });
|
||||
|
||||
test("an info tip opened by a tap closes when the pane scrolls or another spot is tapped", async ({
|
||||
page,
|
||||
}) => {
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
await openSettingsHost(page, getServerId());
|
||||
|
||||
const infoTip = page
|
||||
.getByTestId("host-page-idle-runtime-cleanup-card")
|
||||
.getByRole("button", { name: /^About / });
|
||||
await infoTip.scrollIntoViewIfNeeded();
|
||||
await infoTip.tap();
|
||||
await expect(page.getByRole("tooltip")).toBeVisible();
|
||||
|
||||
await infoTip.evaluate((element) => {
|
||||
for (let node = element.parentElement; node; node = node.parentElement) {
|
||||
if (
|
||||
node.scrollHeight > node.clientHeight &&
|
||||
getComputedStyle(node).overflowY !== "visible"
|
||||
) {
|
||||
node.scrollTop += 40;
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw new Error("The settings pane has nothing to scroll");
|
||||
});
|
||||
await expect(page.getByRole("tooltip")).toHaveCount(0);
|
||||
|
||||
await infoTip.tap();
|
||||
await expect(page.getByRole("tooltip")).toBeVisible();
|
||||
await page.getByTestId("host-page-identity").tap();
|
||||
await expect(page.getByRole("tooltip")).toHaveCount(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -112,24 +112,25 @@ test.describe("Settings sidebar scroll position", () => {
|
||||
await expectSettingsSidebarScrollOffset(page, 0);
|
||||
});
|
||||
|
||||
test("updates appearance without losing the detail scroll or form edits", async ({ page }) => {
|
||||
test("updates typography and normalizes font sizes in one Appearance visit", async ({ page }) => {
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
await openSettingsSection(page, "appearance");
|
||||
const { offset, keywordColor } = await revealSettingsSyntaxTheme(page);
|
||||
await changeSettingsSyntaxTheme(page, "Dracula");
|
||||
await expectSettingsDetailScrollOffset(page, offset);
|
||||
await expectSettingsSyntaxColorChanged(page, keywordColor);
|
||||
await changeSettingsTypography(page);
|
||||
});
|
||||
|
||||
test("shows normalized font sizes after committing out-of-range and empty values", async ({
|
||||
page,
|
||||
}) => {
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
await openSettingsSection(page, "appearance");
|
||||
await normalizeSettingsFontSizes(page);
|
||||
await test.step("change the syntax theme without losing the detail scroll", async () => {
|
||||
const { offset, keywordColor } = await revealSettingsSyntaxTheme(page);
|
||||
await changeSettingsSyntaxTheme(page, "Dracula");
|
||||
await expectSettingsDetailScrollOffset(page, offset);
|
||||
await expectSettingsSyntaxColorChanged(page, keywordColor);
|
||||
});
|
||||
|
||||
await test.step("apply valid font edits to Settings and the preview", async () => {
|
||||
await changeSettingsTypography(page);
|
||||
});
|
||||
|
||||
await test.step("normalize out-of-range and empty font sizes on commit", async () => {
|
||||
await normalizeSettingsFontSizes(page);
|
||||
});
|
||||
});
|
||||
|
||||
test("keeps the sidebar context through interface font changes", async ({ page }) => {
|
||||
|
||||
@@ -805,3 +805,36 @@ test.describe("Half-screen desktop layout", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
test.describe("Wide touch layout", () => {
|
||||
test.use({ viewport: { width: 1400, height: 900 }, hasTouch: true, isMobile: true });
|
||||
|
||||
test("tapping a sidebar row opens its workspace without a hover card and shows the row menu", async ({
|
||||
page,
|
||||
}) => {
|
||||
const workspace = await seedWorkspace({ repoPrefix: "sidebar-touch-tap-" });
|
||||
|
||||
try {
|
||||
const created = await workspace.client.createWorkspace({
|
||||
source: { kind: "directory", path: workspace.repoPath, projectId: workspace.projectId },
|
||||
title: "Tapped workspace",
|
||||
});
|
||||
if (!created.workspace) throw new Error(created.error ?? "Failed to create a second row");
|
||||
const tappedId = created.workspace.id;
|
||||
|
||||
await gotoAppShell(page);
|
||||
const row = await waitForSidebarWorkspace(page, tappedId);
|
||||
await expect(
|
||||
page.getByTestId(`sidebar-workspace-kebab-${getServerId()}:${tappedId}`),
|
||||
).toBeVisible();
|
||||
|
||||
await row.tap();
|
||||
await expect(page).toHaveURL(new RegExp(`/workspace/${escapeRegex(tappedId)}`), {
|
||||
timeout: 30_000,
|
||||
});
|
||||
await expectWorkspaceHoverCardClosed(page);
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,21 @@
|
||||
import { test } from "../support/fixtures";
|
||||
import { expect, metroTest, test } from "../support/fixtures";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
import { startupScenario } from "../support/helpers/startup-dsl";
|
||||
|
||||
// Modules the Metro dev bundle has evaluated when the first screen is visible, set 10% above
|
||||
// the measured count (Welcome 3,985; restored chat 4,725). Before inline requires both screens
|
||||
// evaluated 6,167. A failure means startup now evaluates code the first screen does not
|
||||
// render: find what pulled it in before raising the budget.
|
||||
const WELCOME_MODULE_BUDGET = 4_380;
|
||||
const RESTORED_CHAT_MODULE_BUDGET = 5_200;
|
||||
|
||||
const MERMAID_RUNTIME = /mermaid\/runtime\/html\.gen\.ts$/;
|
||||
// The Markdown renderer's KaTeX loader (`web/katex.js`) and the runtime it imports (`katex.mjs`).
|
||||
const KATEX = /\/katex\.m?js$/;
|
||||
|
||||
const PLAIN_TEXT_REPLY_PROMPT = "Emit 1 assistant messages before synthetic user message.";
|
||||
const PLAIN_TEXT_REPLY = "Synthetic pre-echo message 1";
|
||||
|
||||
test.describe("Startup loading presentation", () => {
|
||||
test("mobile reconnect preserves the saved host shell", async ({ page }) => {
|
||||
const startup = await startupScenario(page)
|
||||
@@ -16,4 +31,36 @@ test.describe("Startup loading presentation", () => {
|
||||
await startup.expectsNoSavedHostErrorStatus();
|
||||
await startup.expectsNoLocalServerStartupCopy();
|
||||
});
|
||||
|
||||
test("a returning user's restored chat loads only what it renders", async ({ page }) => {
|
||||
test.setTimeout(120_000);
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "startup-budget-",
|
||||
title: "Startup budget chat",
|
||||
initialPrompt: PLAIN_TEXT_REPLY_PROMPT,
|
||||
});
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
await expect(page.getByText(PLAIN_TEXT_REPLY, { exact: true })).toBeVisible();
|
||||
|
||||
const startup = await startupScenario(page).withModuleEvaluationRecording().openRoot();
|
||||
|
||||
await startup.expectsRestoredChat(PLAIN_TEXT_REPLY);
|
||||
await startup.expectsFirstScreenEvaluatedAtMost(RESTORED_CHAT_MODULE_BUDGET);
|
||||
await startup.expectsFirstScreenSkipped([MERMAID_RUNTIME]);
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
metroTest("a new user's Welcome screen loads only what it renders", async ({ page }) => {
|
||||
const startup = await startupScenario(page)
|
||||
.asNewUser()
|
||||
.withModuleEvaluationRecording()
|
||||
.openRoot();
|
||||
|
||||
await startup.expectsWelcomeScreen();
|
||||
await startup.expectsFirstScreenEvaluatedAtMost(WELCOME_MODULE_BUDGET);
|
||||
await startup.expectsFirstScreenSkipped([MERMAID_RUNTIME, KATEX]);
|
||||
});
|
||||
|
||||
@@ -706,63 +706,55 @@ test("loads complete long turns and preserves expansion while revealing older hi
|
||||
}
|
||||
});
|
||||
|
||||
async function useThinkingDisplay(
|
||||
page: Page,
|
||||
autoExpandReasoning: boolean,
|
||||
chatDisplay: ChatDisplay,
|
||||
) {
|
||||
await page.addInitScript(
|
||||
(settings) => {
|
||||
localStorage.setItem(
|
||||
"@paseo:app-settings",
|
||||
JSON.stringify({
|
||||
...settings,
|
||||
chatDisplay: sessionStorage.getItem("e2e-chat-display") ?? settings.chatDisplay,
|
||||
}),
|
||||
);
|
||||
},
|
||||
{ autoExpandReasoning, chatDisplay },
|
||||
);
|
||||
}
|
||||
|
||||
for (const autoExpandReasoning of [false, true]) {
|
||||
test(`reasoning follows Expand thinking (${autoExpandReasoning}) when opening its turn`, async ({
|
||||
page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1280, height: 1000 });
|
||||
await useThinkingDisplay(page, autoExpandReasoning, "collapseToolCalls");
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "thinking-group-",
|
||||
title: "Thinking with tools",
|
||||
model: "ten-second-stream",
|
||||
initialPrompt: "Inspect the scroll container",
|
||||
});
|
||||
try {
|
||||
await agent.client.waitForFinish(agent.agentId, 30_000);
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
const reasoning = page
|
||||
.getByText(/Need to find the scroll container, the layout effect/)
|
||||
.filter({ visible: true })
|
||||
.first();
|
||||
await expectThinkingPresentation(page, autoExpandReasoning);
|
||||
await switchToCollapsedTurns(page);
|
||||
await expectComposerVisible(page);
|
||||
const summary = page.getByTestId("turn-summary").last().getByRole("button");
|
||||
await expect(summary).toBeVisible();
|
||||
await expect(summary).not.toContainText(/thought/i);
|
||||
await expect(reasoning).toHaveCount(0);
|
||||
await summary.click();
|
||||
await expect(reasoning).toHaveCount(autoExpandReasoning ? 1 : 0);
|
||||
await expect.poll(() => groupedToolsInsideLatestTurn(page)).toEqual([]);
|
||||
await openOneToolOutput(page);
|
||||
await summary.click();
|
||||
await expect(reasoning).toHaveCount(0);
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
test("reasoning follows Expand thinking when opening its turn", async ({ page }) => {
|
||||
await page.setViewportSize({ width: 1280, height: 1000 });
|
||||
await page.addInitScript(() => {
|
||||
const initialSettings = { autoExpandReasoning: false, chatDisplay: "collapseToolCalls" };
|
||||
localStorage.setItem(
|
||||
"@paseo:app-settings",
|
||||
sessionStorage.getItem("e2e-thinking-display") ?? JSON.stringify(initialSettings),
|
||||
);
|
||||
});
|
||||
}
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "thinking-group-",
|
||||
title: "Thinking with tools",
|
||||
model: "ten-second-stream",
|
||||
initialPrompt: "Inspect the scroll container",
|
||||
});
|
||||
try {
|
||||
await agent.client.waitForFinish(agent.agentId, 30_000);
|
||||
await openAgentRoute(page, agent);
|
||||
const reasoning = page
|
||||
.getByText(/Need to find the scroll container, the layout effect/)
|
||||
.filter({ visible: true })
|
||||
.first();
|
||||
|
||||
for (const autoExpandReasoning of [false, true]) {
|
||||
await test.step(`Expand thinking is ${autoExpandReasoning ? "on" : "off"}`, async () => {
|
||||
if (autoExpandReasoning) {
|
||||
await reloadWithThinkingDisplay(page, autoExpandReasoning, "collapseToolCalls");
|
||||
}
|
||||
await expectComposerVisible(page);
|
||||
await expectThinkingPresentation(page, autoExpandReasoning);
|
||||
|
||||
await reloadWithThinkingDisplay(page, autoExpandReasoning, "collapseTurns");
|
||||
await expectComposerVisible(page);
|
||||
const summary = page.getByTestId("turn-summary").last().getByRole("button");
|
||||
await expect(summary).toBeVisible();
|
||||
await expect(summary).not.toContainText(/thought/i);
|
||||
await expect(reasoning).toHaveCount(0);
|
||||
await summary.click();
|
||||
await expect(reasoning).toHaveCount(autoExpandReasoning ? 1 : 0);
|
||||
await expect.poll(() => groupedToolsInsideLatestTurn(page)).toEqual([]);
|
||||
await openOneToolOutput(page);
|
||||
await summary.click();
|
||||
await expect(reasoning).toHaveCount(0);
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
async function openOneToolOutput(page: Page) {
|
||||
const output = page.getByText(/\[burst\] tick 1 userIsAtBottom=true/).filter({ visible: true });
|
||||
@@ -812,10 +804,15 @@ async function expectThinkingPresentation(page: Page, autoExpandReasoning: boole
|
||||
}
|
||||
}
|
||||
|
||||
async function switchToCollapsedTurns(page: Page) {
|
||||
await page.evaluate(() => {
|
||||
sessionStorage.setItem("e2e-chat-display", "collapseTurns");
|
||||
});
|
||||
async function reloadWithThinkingDisplay(
|
||||
page: Page,
|
||||
autoExpandReasoning: boolean,
|
||||
chatDisplay: ChatDisplay,
|
||||
) {
|
||||
await page.evaluate(
|
||||
(settings) => sessionStorage.setItem("e2e-thinking-display", JSON.stringify(settings)),
|
||||
{ autoExpandReasoning, chatDisplay },
|
||||
);
|
||||
await page.reload();
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,6 @@ import { clickNewTerminal } from "../support/helpers/launcher";
|
||||
import { expectTerminalSurfaceVisible } from "../support/helpers/terminal-perf";
|
||||
import {
|
||||
connectWorkspaceSetupClient,
|
||||
createWorkspaceThroughDaemon,
|
||||
findWorktreeWorkspaceForProject,
|
||||
navigateToWorkspaceViaSidebar,
|
||||
openHomeWithProject,
|
||||
@@ -15,34 +14,7 @@ import {
|
||||
test.describe("Workspace setup runtime authority", () => {
|
||||
test.describe.configure({ retries: 1 });
|
||||
|
||||
test("worktree workspace is created in its own directory", async ({ page }) => {
|
||||
test.setTimeout(90_000);
|
||||
|
||||
const client = await connectWorkspaceSetupClient();
|
||||
const repo = await createTempGitRepo("workspace-setup-chat-");
|
||||
|
||||
try {
|
||||
await seedProjectForWorkspaceSetup(client, repo.path);
|
||||
const workspace = await createWorkspaceThroughDaemon(client, {
|
||||
cwd: repo.path,
|
||||
worktreeSlug: `setup-chat-${Date.now()}`,
|
||||
});
|
||||
const workspaceId = workspace.id;
|
||||
|
||||
const wsInfo = await findWorktreeWorkspaceForProject(client, repo.path);
|
||||
expect(wsInfo.workspaceDirectory).not.toBe(repo.path);
|
||||
expect(existsSync(wsInfo.workspaceDirectory)).toBe(true);
|
||||
|
||||
await openHomeWithProject(page, repo.path);
|
||||
await navigateToWorkspaceViaSidebar(page, workspaceId);
|
||||
await expect(page).toHaveURL(/\/workspace\//, { timeout: 30_000 });
|
||||
} finally {
|
||||
await client.close();
|
||||
await repo.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("first terminal opens in the created workspace directory", async ({ page }) => {
|
||||
test("opens a new worktree and starts its first terminal there", async ({ page }) => {
|
||||
test.setTimeout(90_000);
|
||||
|
||||
const client = await connectWorkspaceSetupClient();
|
||||
@@ -51,35 +23,37 @@ test.describe("Workspace setup runtime authority", () => {
|
||||
try {
|
||||
await seedProjectForWorkspaceSetup(client, repo.path);
|
||||
|
||||
// Create workspace via daemon API since the new workspace screen
|
||||
// no longer has a standalone terminal button
|
||||
const worktreeSlug = `setup-terminal-${Date.now()}`;
|
||||
const result = await client.createPaseoWorktree({
|
||||
cwd: repo.path,
|
||||
worktreeSlug,
|
||||
const workspace = await test.step("creates a worktree in its own directory", async () => {
|
||||
const result = await client.createPaseoWorktree({
|
||||
cwd: repo.path,
|
||||
worktreeSlug: `setup-terminal-${Date.now()}`,
|
||||
});
|
||||
if (!result.workspace || result.error) {
|
||||
throw new Error(result.error ?? "Failed to create workspace");
|
||||
}
|
||||
|
||||
const listedWorkspace = await findWorktreeWorkspaceForProject(client, repo.path);
|
||||
expect(listedWorkspace.workspaceDirectory).toBe(result.workspace.workspaceDirectory);
|
||||
expect(listedWorkspace.workspaceDirectory).not.toBe(repo.path);
|
||||
expect(existsSync(listedWorkspace.workspaceDirectory)).toBe(true);
|
||||
return result.workspace;
|
||||
});
|
||||
if (!result.workspace || result.error) {
|
||||
throw new Error(result.error ?? "Failed to create workspace");
|
||||
}
|
||||
const workspaceDir = result.workspace.workspaceDirectory;
|
||||
const workspaceId = result.workspace.id;
|
||||
|
||||
// Navigate to the worktree workspace via sidebar click (direct URL
|
||||
// navigation for freshly created worktree workspaces can race with
|
||||
// Expo Router hydration, so we use the sidebar which is authoritative).
|
||||
await openHomeWithProject(page, repo.path);
|
||||
await navigateToWorkspaceViaSidebar(page, workspaceId);
|
||||
await test.step("opens the worktree from the sidebar", async () => {
|
||||
await openHomeWithProject(page, repo.path);
|
||||
await navigateToWorkspaceViaSidebar(page, workspace.id);
|
||||
await expect(page).toHaveURL(/\/workspace\//, { timeout: 30_000 });
|
||||
});
|
||||
|
||||
await clickNewTerminal(page);
|
||||
await expectTerminalSurfaceVisible(page);
|
||||
const countWorktreeTerminals = async () =>
|
||||
(await client.listTerminals(workspace.workspaceDirectory)).terminals.length;
|
||||
await test.step("registers the first terminal under the worktree directory", async () => {
|
||||
await clickNewTerminal(page);
|
||||
await expectTerminalSurfaceVisible(page);
|
||||
|
||||
// Verify terminal is listed under the worktree directory, not the original repo
|
||||
await expect
|
||||
.poll(async () => (await client.listTerminals(workspaceDir)).terminals.length > 0, {
|
||||
timeout: 30_000,
|
||||
})
|
||||
.toBe(true);
|
||||
expect((await client.listTerminals(repo.path)).terminals.length).toBe(0);
|
||||
await expect.poll(countWorktreeTerminals, { timeout: 30_000 }).toBeGreaterThan(0);
|
||||
expect((await client.listTerminals(repo.path)).terminals.length).toBe(0);
|
||||
});
|
||||
} finally {
|
||||
await client.close();
|
||||
await repo.cleanup();
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { test } from "../support/fixtures";
|
||||
import {
|
||||
openOverflowingWorkspaceTabs,
|
||||
panWorkspaceTabsWithWheel,
|
||||
} from "../support/helpers/workspace-tabs-wheel-scroll";
|
||||
|
||||
test("a vertical mouse wheel pans the overflowing workspace tab strip", async ({
|
||||
page,
|
||||
withWorkspace,
|
||||
}) => {
|
||||
const workspace = await withWorkspace({ prefix: "workspace-tabs-wheel-" });
|
||||
await openOverflowingWorkspaceTabs(page, workspace);
|
||||
await panWorkspaceTabsWithWheel(page);
|
||||
});
|
||||
@@ -38,6 +38,11 @@ export const openSettings = async (page: Page) => {
|
||||
await expect(page).toHaveURL(/\/settings\/general$/);
|
||||
};
|
||||
|
||||
export async function openSettingsWithShortcut(page: Page): Promise<void> {
|
||||
await page.keyboard.press("ControlOrMeta+,");
|
||||
await expect(page).toHaveURL(/\/settings\/general$/);
|
||||
}
|
||||
|
||||
export const setWorkingDirectory = async (page: Page, directory: string) => {
|
||||
const workingDirectorySelect = page
|
||||
.locator('[data-testid="working-directory-select"]:visible')
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
|
||||
const EVALUATED_MODULES_KEY = "__paseoEvaluatedModules";
|
||||
|
||||
/**
|
||||
* Records every Metro module the page evaluates, in order. Metro's runtime assigns its module
|
||||
* definer to `globalThis.__d` before the bundle calls `__d(factory, id, deps, path)`; trapping that
|
||||
* assignment wraps each factory so it logs the module path (dev bundles pass it as the 4th argument)
|
||||
* when the module first evaluates. Install before navigating; each new document records afresh.
|
||||
*/
|
||||
export async function recordModuleEvaluation(page: Page): Promise<void> {
|
||||
await page.addInitScript((key) => {
|
||||
type Factory = (...args: unknown[]) => unknown;
|
||||
type Define = (factory: Factory, id: unknown, ...rest: unknown[]) => unknown;
|
||||
// `null` marks a module defined without a path; reading the recording rejects it.
|
||||
const evaluated: (string | null)[] = [];
|
||||
let define: Define | undefined;
|
||||
const recordingDefine: Define = (factory, id, ...rest) => {
|
||||
const modulePath = typeof rest[1] === "string" ? rest[1] : null;
|
||||
return define?.(
|
||||
function (this: unknown, ...args: unknown[]) {
|
||||
evaluated.push(modulePath);
|
||||
return factory.apply(this, args);
|
||||
},
|
||||
id,
|
||||
...rest,
|
||||
);
|
||||
};
|
||||
Object.defineProperty(globalThis, key, { value: evaluated });
|
||||
Object.defineProperty(globalThis, "__d", {
|
||||
configurable: true,
|
||||
get: () => (define ? recordingDefine : undefined),
|
||||
set: (next: Define) => {
|
||||
define = next;
|
||||
},
|
||||
});
|
||||
}, EVALUATED_MODULES_KEY);
|
||||
}
|
||||
|
||||
/** The module paths evaluated so far. Throws when the recording could not see module paths. */
|
||||
export async function readEvaluatedModules(page: Page): Promise<string[]> {
|
||||
const evaluated = await page.evaluate((key) => {
|
||||
const recording = (globalThis as unknown as Record<string, (string | null)[] | undefined>)[key];
|
||||
return recording ? recording.slice() : null;
|
||||
}, EVALUATED_MODULES_KEY);
|
||||
if (!evaluated) {
|
||||
throw new Error("Module evaluation was not recorded. Call recordModuleEvaluation first.");
|
||||
}
|
||||
if (evaluated.length === 0) {
|
||||
throw new Error("No module evaluation was recorded. Metro's module definer was not trapped.");
|
||||
}
|
||||
const paths = evaluated.filter((path): path is string => path !== null);
|
||||
if (paths.length !== evaluated.length) {
|
||||
throw new Error("Metro defined modules without paths. Recording needs a development bundle.");
|
||||
}
|
||||
return paths;
|
||||
}
|
||||
@@ -766,3 +766,108 @@ export async function withPluginFocusingAnAgentWithContextUsage(
|
||||
await agent.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
export async function withPluginSettingsFromComposer(
|
||||
page: Page,
|
||||
viewport: typeof WIDE,
|
||||
run: (flow: {
|
||||
openModelSheet(): Promise<void>;
|
||||
openPluginDialog(): Promise<void>;
|
||||
openSettingsFromPlugin(): Promise<void>;
|
||||
changeSetting(): Promise<void>;
|
||||
returnToChat(): Promise<void>;
|
||||
}) => Promise<void>,
|
||||
) {
|
||||
const workspace = await seedWorkspace({ repoPrefix: "composer-settings-" });
|
||||
const agent = await createMockAgent(workspace, "Composer settings agent");
|
||||
const directory = await mkdtemp(path.join(tmpdir(), "paseo-composer-settings-"));
|
||||
await writeFile(
|
||||
path.join(directory, "paseo-plugin.json"),
|
||||
JSON.stringify({ id: "composer-settings", requirements: pluginRequirements }),
|
||||
);
|
||||
await writeFile(
|
||||
path.join(directory, "index.client.tsx"),
|
||||
`import { useState } from "react";
|
||||
import { Pressable, Text } from "react-native";
|
||||
import { Action, Modal } from "@getpaseo/plugin/client/ui";
|
||||
|
||||
function Button({ title, onPress }) {
|
||||
return <Pressable accessibilityRole="button" onPress={onPress}><Text>{title}</Text></Pressable>;
|
||||
}
|
||||
|
||||
export default function contribute(client) {
|
||||
client.addSettingsScreen({
|
||||
id: "preferences",
|
||||
title: "Composer preferences",
|
||||
icon: "SlidersHorizontal",
|
||||
Component() {
|
||||
const [saved, setSaved] = useState(false);
|
||||
return <Button title={saved ? "Preference saved" : "Save preference"} onPress={() => setSaved(true)} />;
|
||||
},
|
||||
});
|
||||
client.addComposerItem({
|
||||
id: "preferences",
|
||||
Component() {
|
||||
const [open, setOpen] = useState(false);
|
||||
return <>
|
||||
<Action title="Composer preferences" icon="ListChecks" onPress={() => setOpen(true)} />
|
||||
<Modal title="Composer preferences" open={open} onOpenChange={setOpen}>
|
||||
<Modal.Content>
|
||||
<Button title="Open plugin settings" onPress={() => {
|
||||
setOpen(false);
|
||||
client.openSettings("preferences");
|
||||
}} />
|
||||
</Modal.Content>
|
||||
</Modal>
|
||||
</>;
|
||||
},
|
||||
});
|
||||
return () => {};
|
||||
}`,
|
||||
);
|
||||
const client = await connectNewWorkspaceDaemonClient({ ownProjects: false });
|
||||
const previous = await client.getDaemonConfig();
|
||||
const settingsButton = page.getByRole("button", { name: "Open plugin settings", exact: true });
|
||||
try {
|
||||
await client.patchDaemonConfig({ pluginsEnabled: true });
|
||||
await client.installDirectoryPlugin(directory);
|
||||
await page.setViewportSize(viewport);
|
||||
await gotoAppShell(page);
|
||||
await approveClientPluginsInUi(page, ["composer-settings"]);
|
||||
await openAgentRoute(page, { workspaceId: workspace.workspaceId, agentId: agent.id });
|
||||
await run({
|
||||
openModelSheet: () =>
|
||||
test.step("open Agent settings from the model button", () =>
|
||||
page.getByRole("button", { name: /^Select model/ }).click()),
|
||||
openPluginDialog: () =>
|
||||
test.step("open the composer plugin's preferences dialog", async () => {
|
||||
await page.getByRole("button", { name: "Composer preferences", exact: true }).click();
|
||||
await expect(settingsButton).toBeVisible();
|
||||
}),
|
||||
openSettingsFromPlugin: () =>
|
||||
test.step("navigate to Settings from the plugin dialog", () => settingsButton.click()),
|
||||
changeSetting: () =>
|
||||
test.step("save a preference in Settings", async () => {
|
||||
await page
|
||||
.getByRole("button", { name: "Save preference", exact: true })
|
||||
.click({ timeout: 10_000 });
|
||||
await expect(
|
||||
page.getByRole("button", { name: "Preference saved", exact: true }),
|
||||
).toBeVisible();
|
||||
}),
|
||||
returnToChat: () =>
|
||||
test.step("return to chat with the dialog and model sheet closed", async () => {
|
||||
await page.goBack();
|
||||
await expect(prompt(page)).toBeVisible();
|
||||
await expect(settingsButton).toBeHidden();
|
||||
await expect(page.getByText("Agent settings", { exact: true })).toBeHidden();
|
||||
}),
|
||||
});
|
||||
} finally {
|
||||
await client.removePlugin("composer-settings");
|
||||
await client.patchDaemonConfig({ pluginsEnabled: previous.config.pluginsEnabled });
|
||||
await client.close();
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
await workspace.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { Route } from "@playwright/test";
|
||||
import { expect, type Page } from "../fixtures";
|
||||
import { buildCreateAgentPreferences, buildSeededHost } from "./daemon-registry";
|
||||
import { wsRoutePatternForPort } from "./daemon-port";
|
||||
import { readEvaluatedModules, recordModuleEvaluation } from "./module-evaluation";
|
||||
|
||||
const DISABLE_DEFAULT_SEED_ONCE_KEY = "@paseo:e2e-disable-default-seed-once";
|
||||
const SEED_NONCE_KEY = "@paseo:e2e-seed-nonce";
|
||||
@@ -25,6 +26,8 @@ class StartupScenario {
|
||||
private desktopBridge = false;
|
||||
private blockedEndpointPorts = new Set<string>();
|
||||
private viewport: { width: number; height: number } | null = null;
|
||||
private newUser = false;
|
||||
private recordsModuleEvaluation = false;
|
||||
|
||||
constructor(page: Page) {
|
||||
this.page = page;
|
||||
@@ -44,6 +47,18 @@ class StartupScenario {
|
||||
return this;
|
||||
}
|
||||
|
||||
/** No saved hosts, and the developer's local daemon is unreachable: the app lands on Welcome. */
|
||||
asNewUser(): this {
|
||||
this.newUser = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Records which modules the app evaluates, so assertions can budget the first screen. */
|
||||
withModuleEvaluationRecording(): this {
|
||||
this.recordsModuleEvaluation = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
withPendingDesktopDaemon(): this {
|
||||
this.desktopBridge = true;
|
||||
return this;
|
||||
@@ -80,6 +95,14 @@ class StartupScenario {
|
||||
await installPendingDesktopBridge(this.page);
|
||||
}
|
||||
|
||||
if (this.newUser) {
|
||||
await blockDeveloperDaemon(this.page);
|
||||
}
|
||||
|
||||
if (this.recordsModuleEvaluation) {
|
||||
await recordModuleEvaluation(this.page);
|
||||
}
|
||||
|
||||
for (const port of this.blockedEndpointPorts) {
|
||||
await this.page.routeWebSocket(wsRoutePatternForPort(port), async (ws) => {
|
||||
await ws.close({ code: 1008, reason: "Blocked unreachable startup test host." });
|
||||
@@ -182,6 +205,34 @@ class StartupAssertions {
|
||||
return this;
|
||||
}
|
||||
|
||||
async expectsWelcomeScreen(): Promise<this> {
|
||||
await expect(this.page.getByTestId("welcome-screen")).toBeVisible({ timeout: 30_000 });
|
||||
return this;
|
||||
}
|
||||
|
||||
async expectsRestoredChat(message: string): Promise<this> {
|
||||
await expect(this.page).toHaveURL(/\/workspace\//, { timeout: 30_000 });
|
||||
await expect(this.page.getByText(message, { exact: true })).toBeVisible({ timeout: 30_000 });
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Call right after the first screen is visible: counts modules evaluated since navigation. */
|
||||
async expectsFirstScreenEvaluatedAtMost(budget: number): Promise<this> {
|
||||
const evaluated = await readEvaluatedModules(this.page);
|
||||
expect(
|
||||
evaluated.length,
|
||||
`First screen evaluated ${evaluated.length} modules; the startup budget is ${budget}.`,
|
||||
).toBeLessThanOrEqual(budget);
|
||||
return this;
|
||||
}
|
||||
|
||||
async expectsFirstScreenSkipped(modules: readonly RegExp[]): Promise<this> {
|
||||
const evaluated = await readEvaluatedModules(this.page);
|
||||
const loaded = evaluated.filter((path) => modules.some((pattern) => pattern.test(path)));
|
||||
expect(loaded, "Modules the first screen does not use were evaluated at startup.").toEqual([]);
|
||||
return this;
|
||||
}
|
||||
|
||||
async expectsDesktopDaemonStartup(): Promise<this> {
|
||||
await expect(this.page.getByTestId("startup-splash")).toBeVisible({
|
||||
timeout: 15_000,
|
||||
@@ -201,6 +252,13 @@ class StartupAssertions {
|
||||
}
|
||||
}
|
||||
|
||||
async function blockDeveloperDaemon(page: Page): Promise<void> {
|
||||
await page.route(/:6767\b/, (route) => route.abort());
|
||||
await page.routeWebSocket(/:6767\b/, async (ws) => {
|
||||
await ws.close({ code: 1008, reason: "Blocked developer daemon during e2e." });
|
||||
});
|
||||
}
|
||||
|
||||
async function installPendingDesktopBridge(page: Page): Promise<void> {
|
||||
await page.addInitScript(() => {
|
||||
(window as unknown as { paseoDesktop: unknown }).paseoDesktop = {
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import { pressNewTabShortcut } from "./launcher";
|
||||
import { panWorkspaceTabsWithWheel } from "./workspace-tabs";
|
||||
import type { CreatedWorkspace } from "./with-workspace";
|
||||
|
||||
const OVERFLOWING_TABS_VIEWPORT = { width: 1100, height: 800 };
|
||||
const OVERFLOWING_TABS_COUNT = 24;
|
||||
|
||||
/** Open a narrow workspace with enough tabs to exercise the horizontal strip. */
|
||||
export async function openOverflowingWorkspaceTabs(
|
||||
page: Page,
|
||||
workspace: CreatedWorkspace,
|
||||
): Promise<void> {
|
||||
await page.setViewportSize(OVERFLOWING_TABS_VIEWPORT);
|
||||
await workspace.navigateTo();
|
||||
|
||||
for (let index = 0; index < OVERFLOWING_TABS_COUNT; index += 1) {
|
||||
await pressNewTabShortcut(page);
|
||||
}
|
||||
}
|
||||
|
||||
export { panWorkspaceTabsWithWheel };
|
||||
@@ -226,6 +226,26 @@ export async function expectNoTerminalTabs(page: Page): Promise<void> {
|
||||
await expect(page.locator('[data-testid^="workspace-tab-terminal_"]')).toHaveCount(0);
|
||||
}
|
||||
|
||||
export async function panWorkspaceTabsWithWheel(page: Page): Promise<void> {
|
||||
const strip = page.getByTestId("workspace-tabs-scroll").filter({ visible: true }).first();
|
||||
await expect(strip).toBeVisible({ timeout: 30_000 });
|
||||
|
||||
const overflow = () => strip.evaluate((element) => element.scrollWidth - element.clientWidth);
|
||||
const scrollLeft = () => strip.evaluate((element) => element.scrollLeft);
|
||||
await expect.poll(overflow).toBeGreaterThan(0);
|
||||
expect(await scrollLeft()).toBe(0);
|
||||
|
||||
await strip.hover();
|
||||
await page.mouse.wheel(0, 200);
|
||||
await expect.poll(scrollLeft).toBeGreaterThan(0);
|
||||
|
||||
await page.mouse.wheel(0, await overflow());
|
||||
await expect.poll(async () => (await overflow()) - (await scrollLeft())).toBeLessThanOrEqual(1);
|
||||
|
||||
await page.mouse.wheel(0, -(await strip.evaluate((element) => element.scrollWidth)));
|
||||
await expect.poll(scrollLeft).toBe(0);
|
||||
}
|
||||
|
||||
export async function clickFirstTerminalTab(
|
||||
page: Page,
|
||||
options?: { timeout?: number },
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
// A cold CI runner transforms the whole web bundle (≈ 6,200 modules) on this request: 70–120 s
|
||||
// on GitHub's runners. The limit only catches a Metro that stopped making progress.
|
||||
const COLD_BUNDLE_TIMEOUT_MS = 300_000;
|
||||
|
||||
/** @param {number} port */
|
||||
export async function warmMetro(port) {
|
||||
const origin = `http://127.0.0.1:${port}`;
|
||||
const documentResponse = await fetch(origin, { signal: AbortSignal.timeout(120_000) });
|
||||
const documentResponse = await fetch(origin, {
|
||||
signal: AbortSignal.timeout(COLD_BUNDLE_TIMEOUT_MS),
|
||||
});
|
||||
if (!documentResponse.ok) {
|
||||
throw new Error(`Metro document warmup failed with HTTP ${documentResponse.status}`);
|
||||
}
|
||||
@@ -15,7 +21,9 @@ export async function warmMetro(port) {
|
||||
for (const source of scriptSources) {
|
||||
const scriptUrl = new URL(source, origin);
|
||||
if (scriptUrl.origin !== origin) continue;
|
||||
const response = await fetch(scriptUrl, { signal: AbortSignal.timeout(120_000) });
|
||||
const response = await fetch(scriptUrl, {
|
||||
signal: AbortSignal.timeout(COLD_BUNDLE_TIMEOUT_MS),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
`Metro bundle warmup failed for ${scriptUrl.pathname}: HTTP ${response.status}`,
|
||||
|
||||
@@ -15,7 +15,10 @@ import { startWatchdog } from "./src/watchdog";
|
||||
import { RootApp } from "./src/root-app";
|
||||
|
||||
import { sweepOrphanedWorkspaceDrafts } from "./src/workspace-tabs/sweep-orphaned-drafts";
|
||||
import { hydrateLastWorkspaceSelection } from "./src/stores/navigation-active-workspace-store";
|
||||
|
||||
startWatchdog();
|
||||
void sweepOrphanedWorkspaceDrafts();
|
||||
// Startup routing waits for the remembered workspace; start reading it before the first render.
|
||||
void hydrateLastWorkspaceSelection();
|
||||
renderRootComponent(RootApp);
|
||||
|
||||
@@ -20,7 +20,23 @@ const config = getDefaultConfig(projectRoot);
|
||||
if (!config.resolver.assetExts.includes("woff2")) {
|
||||
config.resolver.assetExts.push("woff2");
|
||||
}
|
||||
config.cacheVersion = isWatchdogBuild ? "watchdog" : "standard";
|
||||
// The suffix invalidates transform caches written before inline requires.
|
||||
config.cacheVersion = `${isWatchdogBuild ? "watchdog" : "standard"}-inline-requires`;
|
||||
|
||||
// Inline requires: a named, default or namespace import becomes a `require` at each use, so a
|
||||
// module evaluates when the code that uses it first runs, not when the bundle loads. Cold start
|
||||
// then evaluates what the first screen renders instead of the whole app. A bare `import "x"`
|
||||
// stays eager and in source order; `index.ts` lists the startup side effects that way. A
|
||||
// module whose only purpose is an import-time side effect stops running once nothing
|
||||
// references it: start that work explicitly from `index.ts`.
|
||||
const getDefaultTransformOptions = config.transformer.getTransformOptions;
|
||||
config.transformer.getTransformOptions = async (...args) => {
|
||||
const options = await getDefaultTransformOptions(...args);
|
||||
return {
|
||||
...options,
|
||||
transform: { ...options.transform, inlineRequires: true },
|
||||
};
|
||||
};
|
||||
const defaultResolveRequest = config.resolver.resolveRequest ?? resolve;
|
||||
|
||||
// Keep app exports deterministic across dev machines and CI. Metro's Watchman
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/app",
|
||||
"version": "0.19.1",
|
||||
"version": "0.19.2",
|
||||
"private": true,
|
||||
"main": "index.ts",
|
||||
"scripts": {
|
||||
@@ -30,12 +30,13 @@
|
||||
"test:e2e:ui": "playwright test --ui",
|
||||
"build": "npm run build:web",
|
||||
"build:web": "npm --prefix ../.. run build:app-deps && expo export --platform web",
|
||||
"check:web-size": "node ../../scripts/check-web-export-size.mjs dist",
|
||||
"profile:composer-typing": "node ./scripts/profile-composer-typing.mjs",
|
||||
"profile:explorer-toggle": "node ./scripts/profile-explorer-toggle.mjs",
|
||||
"profile:side-pane": "playwright test --config playwright.profile.config.ts side-pane-performance.spec.ts",
|
||||
"profile:workspace-switching": "node ./scripts/profile-workspace-switching.mjs",
|
||||
"profile:workspace-tabs": "node ./scripts/profile-workspace-tabs.mjs",
|
||||
"deploy:web": "npm run build:web && wrangler pages deploy dist --project-name paseo-app --branch main",
|
||||
"deploy:web": "npm run build:web && npm run check:web-size && wrangler pages deploy dist --project-name paseo-app --branch main",
|
||||
"build:mermaid-runtime": "node ./src/components/markdown/fence/mermaid/build-runtime.mjs",
|
||||
"dev:android": "npm --prefix ../.. run build:client && cross-env APP_VARIANT=development expo prebuild --platform android --clean --non-interactive && cross-env APP_VARIANT=development expo run:android --variant=debug",
|
||||
"dev:ios": "npm --prefix ../.. run build:client && cross-env APP_VARIANT=development expo run:ios",
|
||||
|
||||
@@ -20,11 +20,11 @@ import {
|
||||
getWorkspaceSelectionKey,
|
||||
orderWorkspaceSelectionsForStableRender,
|
||||
reconcileRetainedWorkspaceSelections,
|
||||
resolveWorkspaceDeckRetentionLimit,
|
||||
type RetainedWorkspaceSelection,
|
||||
resolveWorkspaceDeckEntries,
|
||||
shouldKeepWorkspaceDeckEntryMounted,
|
||||
} from "@/screens/workspace/workspace-deck-retention";
|
||||
import { workspaceDeckRetentionLimit } from "@/constants/resource-budget";
|
||||
import {
|
||||
decodeWorkspaceIdFromPathSegment,
|
||||
parseWorkspaceOpenIntent,
|
||||
@@ -35,7 +35,7 @@ import {
|
||||
stripHostWorkspaceRouteEchoSearchFromBrowserUrlAfterCommit,
|
||||
} from "@/utils/host-route-browser";
|
||||
import { prepareWorkspaceTab } from "@/utils/prepare-workspace-tab";
|
||||
import { isNative, isWeb } from "@/constants/platform";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { RenderProfile } from "@/utils/render-profiler";
|
||||
|
||||
function getParamValue(value: string | string[] | undefined): string {
|
||||
@@ -167,7 +167,7 @@ function WorkspaceDeck() {
|
||||
currentEntries: retainedSelections,
|
||||
activeSelection,
|
||||
now: reconciliationNow,
|
||||
maxMountedWorkspaces: resolveWorkspaceDeckRetentionLimit({ isNative }),
|
||||
maxMountedWorkspaces: workspaceDeckRetentionLimit,
|
||||
}),
|
||||
[activeSelection, reconciliationNow, retainedSelections],
|
||||
);
|
||||
@@ -204,7 +204,7 @@ function WorkspaceDeck() {
|
||||
currentEntries: current,
|
||||
activeSelection,
|
||||
now: Date.now(),
|
||||
maxMountedWorkspaces: resolveWorkspaceDeckRetentionLimit({ isNative }),
|
||||
maxMountedWorkspaces: workspaceDeckRetentionLimit,
|
||||
}),
|
||||
);
|
||||
}, expirationDelay + 1);
|
||||
|
||||
@@ -56,6 +56,7 @@ import {
|
||||
} from "@/components/ui/isolated-bottom-sheet-modal";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { isNative, isWeb } from "@/constants/platform";
|
||||
import { usesCompactBottomSheet } from "@/constants/presentation";
|
||||
import { useAggregatedAgents, type AggregatedAgent } from "@/hooks/use-aggregated-agents";
|
||||
import { useProjects } from "@/hooks/use-projects";
|
||||
import { useTimeAgo } from "@/hooks/use-time-ago";
|
||||
@@ -991,7 +992,7 @@ export function CommandCenter() {
|
||||
const bottomSheetListRef = useRef<BottomSheetFlatListMethods>(null);
|
||||
const inputRef = useRef<EditingTextInputHandle>(null);
|
||||
const bottomSheetInputRef = useRef<EditingTextInputHandle>(null);
|
||||
const showBottomSheet = isCompact && isNative;
|
||||
const showBottomSheet = isCompact && usesCompactBottomSheet;
|
||||
const getInputHandle = useCallback(
|
||||
() => (showBottomSheet ? bottomSheetInputRef.current : inputRef.current),
|
||||
[showBottomSheet],
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useOverlayRegistration, type KeyboardInputEvent } from "@/keyboard";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import type { ComponentProps, ReactNode } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
useBottomSheetSafeAreaPaddingStyle,
|
||||
useIsolatedBottomSheetVisibility,
|
||||
} from "@/components/ui/isolated-bottom-sheet-modal";
|
||||
import { useRetainedPanelActive } from "@/components/retained-panel";
|
||||
import { ScrollView } from "@/components/ui/scroll-view";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { BottomSafeAreaInset } from "@/components/ui/bottom-safe-area-inset";
|
||||
@@ -693,7 +694,36 @@ function CompactSheetBody({
|
||||
);
|
||||
}
|
||||
|
||||
export function AdaptiveModalSheet({
|
||||
export function AdaptiveModalSheet(props: AdaptiveModalSheetProps) {
|
||||
const panelActive = useRetainedPanelActive();
|
||||
const { visible, onClose, onDismiss } = props;
|
||||
const dismissalPending = useRef(false);
|
||||
|
||||
const finishDismissal = useCallback(() => {
|
||||
if (!dismissalPending.current) return;
|
||||
dismissalPending.current = false;
|
||||
onDismiss?.();
|
||||
}, [onDismiss]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!isWeb) return;
|
||||
if (visible) dismissalPending.current = true;
|
||||
if (panelActive) return;
|
||||
|
||||
// Complete dismissal when the inactive commit removes the portal, including when
|
||||
// a close animation was already running. Compact portal cleanup can also report dismissal.
|
||||
if (visible) onClose();
|
||||
finishDismissal();
|
||||
}, [panelActive, visible, onClose, finishDismissal]);
|
||||
|
||||
// A web portal escapes its hidden panel. Unmount its presentation in the inactive commit
|
||||
// so a chat that freezes on the next commit cannot strand the overlay above another screen.
|
||||
return !isWeb || panelActive ? (
|
||||
<AdaptiveModalSheetPresentation {...props} onDismiss={isWeb ? finishDismissal : onDismiss} />
|
||||
) : null;
|
||||
}
|
||||
|
||||
function AdaptiveModalSheetPresentation({
|
||||
header,
|
||||
showCloseButton = true,
|
||||
visible,
|
||||
|
||||
@@ -2,8 +2,7 @@ import { type ReactNode, useCallback, useMemo, useState } from "react";
|
||||
import { Image, Pressable, Text, View } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { X } from "lucide-react-native";
|
||||
import { isNative } from "@/constants/platform";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { useRevealsWithoutHover } from "@/hooks/hover-reveal";
|
||||
import type { AttachmentMetadata } from "@/attachments/types";
|
||||
import { useAttachmentPreviewUrl } from "@/attachments/use-attachment-preview-url";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
@@ -31,10 +30,9 @@ export function AttachmentPill({
|
||||
testID,
|
||||
children,
|
||||
}: AttachmentPillProps) {
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
const [isBodyHovered, setIsBodyHovered] = useState(false);
|
||||
const [isCloseHovered, setIsCloseHovered] = useState(false);
|
||||
const alwaysShow = isNative || isCompact;
|
||||
const alwaysShow = useRevealsWithoutHover();
|
||||
const showRemove = alwaysShow || isBodyHovered || isCloseHovered;
|
||||
const closeButtonStyle = useMemo(
|
||||
() => [styles.closeButton, !showRemove && styles.closeButtonHidden],
|
||||
|
||||
@@ -12,7 +12,8 @@ import { useTranslation } from "react-i18next";
|
||||
import { HoverCard, HoverCardContent, HoverCardTrigger } from "@/components/ui/hover-card";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { isNative } from "@/constants/platform";
|
||||
import { isNative, isWeb } from "@/constants/platform";
|
||||
import { usePointerCapabilities } from "@/hooks/pointer-capabilities";
|
||||
import type { AgentMetric } from "@getpaseo/protocol/agent-types";
|
||||
import { useHostReportsUsage } from "@/usage";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
@@ -171,8 +172,11 @@ export function ContextWindowMeter({
|
||||
const showsUsage = useHostReportsUsage(serverId);
|
||||
const isWide = showsUsage || sessionMetrics.length > 0;
|
||||
const popoverWidth = Math.min(USAGE_POPOVER_WIDTH, width - 24);
|
||||
// Compact screens open the details in a sheet, which can hold a pressable Refresh.
|
||||
// Compact screens and touch-first browsers open the details in a sheet, which can hold a
|
||||
// pressable Refresh.
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
const { finePointer } = usePointerCapabilities();
|
||||
const opensSheet = isCompact || (isWeb && !finePointer);
|
||||
const [isSheetOpen, setIsSheetOpen] = useState(false);
|
||||
const openSheet = useCallback(() => setIsSheetOpen(true), []);
|
||||
const closeSheet = useCallback(() => setIsSheetOpen(false), []);
|
||||
@@ -220,7 +224,7 @@ export function ContextWindowMeter({
|
||||
? t("contextWindow.accessibility", { percentage: context.percentage })
|
||||
: t("contextWindow.accessibilityNoData");
|
||||
|
||||
if (isCompact) {
|
||||
if (opensSheet) {
|
||||
return (
|
||||
<>
|
||||
<Pressable
|
||||
@@ -252,7 +256,7 @@ export function ContextWindowMeter({
|
||||
? [styles.usagePopover, { width: popoverWidth }]
|
||||
: styles.plainPopover;
|
||||
|
||||
// Native wide screens have no hover, so the details open in a tooltip on press. The tooltip
|
||||
// Wide native screens have no hover, so the details open in a tooltip on press. The tooltip
|
||||
// takes no presses, so its usage cards have no Refresh.
|
||||
if (isNative) {
|
||||
return (
|
||||
|
||||
@@ -16,6 +16,7 @@ import DraggableFlatList, {
|
||||
import type { GestureType } from "react-native-gesture-handler";
|
||||
import { useUnistyles } from "react-native-unistyles";
|
||||
import { useContentDrag } from "@/components/ui/content-drag";
|
||||
import { supportsTouchHaptics } from "@/constants/touch-timing";
|
||||
import { createDragHold } from "./drag-reorder/drag-hold";
|
||||
import { movedItemKey } from "./drag-reorder/native-drop";
|
||||
import type {
|
||||
@@ -52,7 +53,7 @@ export function DraggableListHandle({ testID, style, children }: DraggableListHa
|
||||
delayMs: HANDLE_HOLD_MS,
|
||||
slopPx: HANDLE_HOLD_SLOP_PX,
|
||||
onArm: () => {
|
||||
void Haptics.selectionAsync().catch(() => {});
|
||||
if (supportsTouchHaptics) void Haptics.selectionAsync().catch(() => {});
|
||||
drag();
|
||||
},
|
||||
})
|
||||
|
||||
@@ -4,8 +4,8 @@ import * as Clipboard from "expo-clipboard";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { HighlightToken } from "@getpaseo/highlight";
|
||||
import { BlockCopyButton } from "@/components/markdown/block-copy-button";
|
||||
import { isNative, isWeb } from "@/constants/platform";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { useRevealsWithoutHover } from "@/hooks/hover-reveal";
|
||||
import { syntaxTokenStyleFor } from "@/styles/syntax-token-styles";
|
||||
import { CODE_SURFACE_DATASET } from "@/styles/code-surface";
|
||||
import { highlightToKeyedLines, type KeyedLine } from "@/utils/highlight-cache";
|
||||
@@ -87,11 +87,11 @@ export const HighlightedCodeBlock = React.memo(function HighlightedCodeBlock({
|
||||
);
|
||||
|
||||
const { t } = useTranslation();
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
const revealsWithoutHover = useRevealsWithoutHover();
|
||||
const [isHovered, setIsHovered] = useState(false);
|
||||
const handlePointerEnter = useCallback(() => setIsHovered(true), []);
|
||||
const handlePointerLeave = useCallback(() => setIsHovered(false), []);
|
||||
const controlsVisible = isHovered || isNative || isCompact;
|
||||
const controlsVisible = isHovered || revealsWithoutHover;
|
||||
// Copy the code without its trailing blank lines. A fence body ends in a newline,
|
||||
// and ends in more than one when the author left a blank line before the closing
|
||||
// fence; pasting any of them into a terminal runs the last line.
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Animated, StyleSheet, Text, View } from "react-native";
|
||||
import MaskedView from "@react-native-masked-view/masked-view";
|
||||
import Svg, { Defs, Rect, Stop, LinearGradient as SvgLinearGradient } from "react-native-svg";
|
||||
import { useIndicatorMotion } from "@/components/indicator-motion";
|
||||
import { supportsMaskedEffects } from "@/constants/platform";
|
||||
import { sharedIndicatorClock, useRunningClock } from "@/components/indicator-motion/clock";
|
||||
import { type LabelShimmerProps, getRowSweep, getShimmerCycle } from "./sweep";
|
||||
|
||||
@@ -60,7 +61,8 @@ export const LabelShimmer = memo(function LabelShimmer({
|
||||
measurements,
|
||||
}: LabelShimmerProps) {
|
||||
const { rowSize } = measurements;
|
||||
const measured = rowSize.width > 0 && rowSize.height > 0;
|
||||
// Without an alpha-mask compositor the band would paint as a bare white bar.
|
||||
const measured = supportsMaskedEffects && rowSize.width > 0 && rowSize.height > 0;
|
||||
const motion = useIndicatorMotion();
|
||||
// A held band stays on the clock, so it keeps its place and its pass.
|
||||
const sweeping = motion !== "resting" && measured;
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { useCallback, useEffect, useRef } from "react";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import type { DiagramColorScheme, MermaidRenderRequest } from "./render-model";
|
||||
import { mermaidRuntimeHtml } from "./runtime/html.gen";
|
||||
import { parseMermaidRuntimeMessage, type MermaidRuntimeRenderMessage } from "./runtime/messages";
|
||||
import { MermaidRuntimeRequestDriver } from "./runtime/request-driver";
|
||||
|
||||
@@ -18,6 +17,25 @@ interface MermaidIframeRuntimeProps {
|
||||
onRenderFailed: (revision: number) => void;
|
||||
}
|
||||
|
||||
// The embedded runtime is ~3.4 MiB. Loading it through `import()` keeps it out of the web entry
|
||||
// chunk (Cloudflare Pages rejects files over 25 MiB); Metro emits it as its own async chunk.
|
||||
let loadedRuntimeHtml: string | null = null;
|
||||
let runtimeHtmlLoad: Promise<string> | null = null;
|
||||
|
||||
function loadMermaidRuntimeHtml(): Promise<string> {
|
||||
runtimeHtmlLoad ??= import("./runtime/html.gen").then(
|
||||
({ mermaidRuntimeHtml }) => {
|
||||
loadedRuntimeHtml = mermaidRuntimeHtml;
|
||||
return mermaidRuntimeHtml;
|
||||
},
|
||||
(error: unknown) => {
|
||||
runtimeHtmlLoad = null;
|
||||
throw error;
|
||||
},
|
||||
);
|
||||
return runtimeHtmlLoad;
|
||||
}
|
||||
|
||||
/** Sandboxed Mermaid renderer. Sizing and gestures belong to the surrounding viewport. */
|
||||
export function MermaidIframeRuntime({
|
||||
request,
|
||||
@@ -27,6 +45,31 @@ export function MermaidIframeRuntime({
|
||||
const iframeRef = useRef<HTMLIFrameElement | null>(null);
|
||||
const driverRef = useRef<MermaidRuntimeRequestDriver | null>(null);
|
||||
driverRef.current ??= new MermaidRuntimeRequestDriver();
|
||||
const [runtimeHtml, setRuntimeHtml] = useState(loadedRuntimeHtml);
|
||||
const [runtimeLoadFailed, setRuntimeLoadFailed] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (runtimeHtml !== null) return;
|
||||
let cancelled = false;
|
||||
async function load() {
|
||||
try {
|
||||
const html = await loadMermaidRuntimeHtml();
|
||||
if (!cancelled) setRuntimeHtml(html);
|
||||
} catch {
|
||||
if (!cancelled) setRuntimeLoadFailed(true);
|
||||
}
|
||||
}
|
||||
void load();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [runtimeHtml]);
|
||||
|
||||
// Without the runtime nothing can render, so each revision fails and the host shows the source.
|
||||
const revision = request?.revision;
|
||||
useEffect(() => {
|
||||
if (runtimeLoadFailed && revision !== undefined) onRenderFailed(revision);
|
||||
}, [onRenderFailed, revision, runtimeLoadFailed]);
|
||||
|
||||
const sendRequest = useCallback((current: MermaidRenderRequest | null) => {
|
||||
const target = iframeRef.current?.contentWindow;
|
||||
@@ -66,6 +109,8 @@ export function MermaidIframeRuntime({
|
||||
return () => window.removeEventListener("message", receiveMessage);
|
||||
}, [onRenderFailed, onRendered, sendRequest]);
|
||||
|
||||
if (runtimeHtml === null) return null;
|
||||
|
||||
// `inert` (not just tabIndex) because the Modal focus trap focuses descendants
|
||||
// programmatically; a focused iframe swallows every keystroke, including Escape.
|
||||
return (
|
||||
@@ -75,7 +120,7 @@ export function MermaidIframeRuntime({
|
||||
aria-hidden
|
||||
inert
|
||||
sandbox="allow-scripts"
|
||||
srcDoc={mermaidRuntimeHtml}
|
||||
srcDoc={runtimeHtml}
|
||||
tabIndex={-1}
|
||||
style={iframeStyle}
|
||||
/>
|
||||
|
||||
@@ -26,6 +26,8 @@ import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { isNative, isWeb } from "@/constants/platform";
|
||||
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
|
||||
import { usePointerCapabilities } from "@/hooks/pointer-capabilities";
|
||||
import { useRevealsWithoutHover } from "@/hooks/hover-reveal";
|
||||
import { useRevealedText, type MarkdownPhase } from "@/hooks/use-revealed-text";
|
||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||
import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
|
||||
@@ -463,7 +465,7 @@ export const UserMessage = memo(function UserMessage({
|
||||
isPending = false,
|
||||
disableOuterSpacing,
|
||||
}: UserMessageProps) {
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
const revealsWithoutHover = useRevealsWithoutHover();
|
||||
const { t } = useTranslation();
|
||||
const [isHovered, setIsHovered] = useState(false);
|
||||
const [lightboxMetadata, setLightboxMetadata] = useState<AttachmentMetadata | null>(null);
|
||||
@@ -476,7 +478,7 @@ export const UserMessage = memo(function UserMessage({
|
||||
const hasText = message.trim().length > 0;
|
||||
const hasImages = images.length > 0;
|
||||
const hasAttachments = attachments.length > 0;
|
||||
const showTrailingRow = !isPending && hasText && (isCompact || isNative || isHovered);
|
||||
const showTrailingRow = !isPending && hasText && (revealsWithoutHover || isHovered);
|
||||
const formattedTimestamp = useMemo(
|
||||
() => formatMessageTimestamp(new Date(timestamp)),
|
||||
[timestamp],
|
||||
@@ -680,6 +682,7 @@ export const AssistantTurnFooter = memo(function AssistantTurnFooter({
|
||||
metrics,
|
||||
}: AssistantTurnFooterProps) {
|
||||
const { t } = useTranslation();
|
||||
const { finePointer } = usePointerCapabilities();
|
||||
const [hovered, setHovered] = useState(false);
|
||||
const [pressedReveal, setPressedReveal] = useState(false);
|
||||
const revealTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
@@ -705,12 +708,12 @@ export const AssistantTurnFooter = memo(function AssistantTurnFooter({
|
||||
|
||||
const primaryLabel = durationLabel || timestampLabel;
|
||||
const canSwap = Boolean(durationLabel && timestampLabel);
|
||||
const showTimestamp = canSwap && (isWeb ? hovered : pressedReveal);
|
||||
const showTimestamp = canSwap && (finePointer ? hovered : pressedReveal);
|
||||
|
||||
const handleHoverIn = useCallback(() => setHovered(true), []);
|
||||
const handleHoverOut = useCallback(() => setHovered(false), []);
|
||||
const handlePress = useCallback(() => {
|
||||
if (isWeb || !canSwap) return;
|
||||
if (finePointer || !canSwap) return;
|
||||
if (revealTimerRef.current) {
|
||||
clearTimeout(revealTimerRef.current);
|
||||
}
|
||||
@@ -719,7 +722,7 @@ export const AssistantTurnFooter = memo(function AssistantTurnFooter({
|
||||
setPressedReveal(false);
|
||||
revealTimerRef.current = null;
|
||||
}, TIMESTAMP_REVEAL_MS);
|
||||
}, [canSwap]);
|
||||
}, [canSwap, finePointer]);
|
||||
const handleFork = useCallback(
|
||||
(target: AssistantForkTarget) => {
|
||||
return onFork?.(target);
|
||||
|
||||
@@ -60,9 +60,15 @@ import { useRevealActiveFlatListRow, useRevealActiveItem } from "@/components/ui
|
||||
import type { EditingTextInputHandle } from "@/components/ui/text-input";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { useProviderIcon } from "@/components/provider-icons";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { isNative, isWeb } from "@/constants/platform";
|
||||
import { useHardwareKeyboardPresent, type KeyboardInputEvent } from "@/keyboard";
|
||||
import { isNative } from "@/constants/platform";
|
||||
import { usesDesktopPopoverSpacing } from "@/constants/presentation";
|
||||
import { usePointerCapabilities } from "@/hooks/pointer-capabilities";
|
||||
import { useRevealsWithoutHover } from "@/hooks/hover-reveal";
|
||||
import {
|
||||
hasSoftwareKeyboard,
|
||||
useHardwareKeyboardPresent,
|
||||
type KeyboardInputEvent,
|
||||
} from "@/keyboard";
|
||||
import {
|
||||
buildProviderQualifiedDescription,
|
||||
buildSelectedTriggerLabel,
|
||||
@@ -105,7 +111,7 @@ const DESKTOP_PROVIDER_VIEW_BASE_HEIGHT = 80;
|
||||
const DESKTOP_MODEL_ROW_HEIGHT = 40;
|
||||
|
||||
/** Fixed picker row heights so virtualized lists can mount directly at the selected row via `getItemLayout`. */
|
||||
export const MODEL_PICKER_ROW_HEIGHT = isWeb ? 36 : 44;
|
||||
export const MODEL_PICKER_ROW_HEIGHT = usesDesktopPopoverSpacing ? 36 : 44;
|
||||
export const MODEL_PICKER_HEADING_HEIGHT = 32;
|
||||
|
||||
const ThemedAlertTriangle = withUnistyles(AlertTriangle);
|
||||
@@ -144,7 +150,7 @@ function ProviderSettingsAction({
|
||||
|
||||
/**
|
||||
* An icon button that explains itself in a tooltip on desktop hover. Tooltips
|
||||
* never open on mobile, so native renders the shared gesture-aware pressable
|
||||
* need a hovering pointer, so a touch screen renders the shared gesture-aware pressable
|
||||
* instead of a plain Pressable: inside the model list's independent scroll
|
||||
* viewport (Android, wide windows) the native scroll gesture cancels a plain
|
||||
* Pressable's touches and the button would never fire.
|
||||
@@ -164,7 +170,8 @@ function IconActionButton({
|
||||
| ((state: PressableStateCallbackType & { hovered?: boolean }) => StyleProp<ViewStyle>);
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
if (isNative) {
|
||||
const { finePointer } = usePointerCapabilities();
|
||||
if (!finePointer) {
|
||||
return (
|
||||
<ModelBrowserPressable
|
||||
onPress={onPress}
|
||||
@@ -386,7 +393,7 @@ export function useModelBrowser({
|
||||
selectedProvider,
|
||||
selectedModel,
|
||||
isLoading,
|
||||
autoFocusSearch = isWeb,
|
||||
autoFocusSearch = !hasSoftwareKeyboard,
|
||||
profiles = null,
|
||||
serverId = null,
|
||||
}: ModelBrowserInput): ModelBrowserState {
|
||||
@@ -821,8 +828,8 @@ function ModelRowProfileAction({
|
||||
testID: string;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
const visible = hovered || isNative || isCompact;
|
||||
const revealsWithoutHover = useRevealsWithoutHover();
|
||||
const visible = hovered || revealsWithoutHover;
|
||||
const pressableStyle = useCallback(
|
||||
({ hovered: buttonHovered, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [
|
||||
styles.rowIconButton,
|
||||
@@ -1649,7 +1656,7 @@ function ModelSearchEmptyState() {
|
||||
// React Native Web blurs the focused input on every scroll in "on-drag" mode, including wheel
|
||||
// scrolls and the scroll that reveals an arrowed-to row. That moves focus out of search, so
|
||||
// typing stops and Enter lands on the header's Back button. Only a native keyboard needs it.
|
||||
const MODEL_LIST_KEYBOARD_DISMISS_MODE = isNative ? "on-drag" : "none";
|
||||
const MODEL_LIST_KEYBOARD_DISMISS_MODE = hasSoftwareKeyboard ? "on-drag" : "none";
|
||||
|
||||
interface ModelBrowserKeyboardBinding {
|
||||
view: ModelBrowserView;
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { Component, type ErrorInfo, type ReactNode } from "react";
|
||||
|
||||
interface RenderErrorBoundaryProps {
|
||||
children: ReactNode;
|
||||
/** A caught error is cleared when any of these values change, so new content renders. */
|
||||
resetKeys: readonly unknown[];
|
||||
/** The error state shown in place of the children. `retry` renders the children again. */
|
||||
renderError(error: string, retry: () => void): ReactNode;
|
||||
onError(error: unknown, componentStack: string | null | undefined): void;
|
||||
}
|
||||
|
||||
interface RenderErrorBoundaryState {
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps a render error inside one surface. Without it the error reaches the root boundary,
|
||||
* which replaces the whole app.
|
||||
*/
|
||||
export class RenderErrorBoundary extends Component<
|
||||
RenderErrorBoundaryProps,
|
||||
RenderErrorBoundaryState
|
||||
> {
|
||||
state: RenderErrorBoundaryState = { error: null };
|
||||
|
||||
static getDerivedStateFromError(error: unknown): RenderErrorBoundaryState {
|
||||
return { error: error instanceof Error ? error.message : String(error) };
|
||||
}
|
||||
|
||||
componentDidCatch(error: unknown, info: ErrorInfo): void {
|
||||
this.props.onError(error, info.componentStack);
|
||||
}
|
||||
|
||||
componentDidUpdate(previous: RenderErrorBoundaryProps): void {
|
||||
if (this.state.error !== null && resetKeysChanged(previous.resetKeys, this.props.resetKeys)) {
|
||||
this.retry();
|
||||
}
|
||||
}
|
||||
|
||||
retry = (): void => {
|
||||
this.setState({ error: null });
|
||||
};
|
||||
|
||||
render() {
|
||||
if (this.state.error !== null) return this.props.renderError(this.state.error, this.retry);
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
||||
|
||||
function resetKeysChanged(previous: readonly unknown[], next: readonly unknown[]): boolean {
|
||||
return previous.length !== next.length || previous.some((key, index) => key !== next[index]);
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { startResizeHandleDrag } from "@/components/resize-handle-drag";
|
||||
import {
|
||||
resolveResizeHandleInteraction,
|
||||
startResizeHandleDrag,
|
||||
} from "@/components/resize-handle-drag";
|
||||
|
||||
describe("startResizeHandleDrag", () => {
|
||||
it("previews pointer frames and commits only the final size", () => {
|
||||
@@ -29,3 +32,14 @@ describe("startResizeHandleDrag", () => {
|
||||
expect(commit.mock.calls[0]?.[0][1]).toBeCloseTo(0.4, 10);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveResizeHandleInteraction", () => {
|
||||
it("uses DOM pointer events only on fine-pointer web targets, gesture pan on fine-pointer non-web targets, and touch grip on touch targets", () => {
|
||||
expect(resolveResizeHandleInteraction({ finePointer: true, isWeb: true })).toBe("web-pointer");
|
||||
expect(resolveResizeHandleInteraction({ finePointer: true, isWeb: false })).toBe(
|
||||
"native-pointer",
|
||||
);
|
||||
expect(resolveResizeHandleInteraction({ finePointer: false, isWeb: false })).toBe("touch");
|
||||
expect(resolveResizeHandleInteraction({ finePointer: false, isWeb: true })).toBe("touch");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -7,6 +7,24 @@ interface StartResizeHandleDragInput {
|
||||
commit: (sizes: number[]) => void;
|
||||
}
|
||||
|
||||
export type ResizeHandleInteraction = "web-pointer" | "native-pointer" | "touch";
|
||||
|
||||
/**
|
||||
* Selects how the resize bar is hit-tested and dragged: thin pointer bar with DOM events on a
|
||||
* fine-pointer web target, thin pointer bar with gesture pan on a fine-pointer non-web target, and a
|
||||
* wide touch target with a grip pill otherwise.
|
||||
*/
|
||||
export function resolveResizeHandleInteraction({
|
||||
finePointer,
|
||||
isWeb,
|
||||
}: {
|
||||
finePointer: boolean;
|
||||
isWeb: boolean;
|
||||
}): ResizeHandleInteraction {
|
||||
if (!finePointer) return "touch";
|
||||
return isWeb ? "web-pointer" : "native-pointer";
|
||||
}
|
||||
|
||||
export interface ResizeHandleDrag {
|
||||
move: (deltaRatio: number) => void;
|
||||
finish: () => void;
|
||||
|
||||
@@ -2,7 +2,12 @@ import { useCallback, useMemo, useRef, useState } from "react";
|
||||
import { View, type PointerEvent as RNPointerEvent } from "react-native";
|
||||
import { Gesture, GestureDetector } from "react-native-gesture-handler";
|
||||
import { StyleSheet, useUnistyles } from "react-native-unistyles";
|
||||
import { startResizeHandleDrag, type ResizeHandleDrag } from "@/components/resize-handle-drag";
|
||||
import {
|
||||
resolveResizeHandleInteraction,
|
||||
startResizeHandleDrag,
|
||||
type ResizeHandleDrag,
|
||||
} from "@/components/resize-handle-drag";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { usePointerCapabilities } from "@/hooks/pointer-capabilities";
|
||||
import {
|
||||
SIDEBAR_RESIZE_ACTIVATION_OFFSET,
|
||||
@@ -48,6 +53,7 @@ export function ResizeHandle({
|
||||
}: ResizeHandleProps) {
|
||||
const { theme } = useUnistyles();
|
||||
const { finePointer } = usePointerCapabilities();
|
||||
const interaction = resolveResizeHandleInteraction({ finePointer, isWeb });
|
||||
const pointerStatesRef = useRef(new Map<number, PointerState>());
|
||||
const touchStateRef = useRef<PointerState | null>(null);
|
||||
const cursorBeforeDragRef = useRef<string | null>(null);
|
||||
@@ -225,8 +231,12 @@ export function ResizeHandle({
|
||||
...(direction === "horizontal"
|
||||
? { left: hitAreaAlignment === "end" ? 0 : -5 }
|
||||
: { top: hitAreaAlignment === "end" ? 0 : -5 }),
|
||||
cursor: direction === "horizontal" ? "col-resize" : "row-resize",
|
||||
touchAction: "none",
|
||||
...(isWeb
|
||||
? {
|
||||
cursor: direction === "horizontal" ? "col-resize" : "row-resize",
|
||||
touchAction: "none",
|
||||
}
|
||||
: {}),
|
||||
} as object,
|
||||
],
|
||||
[direction, hitAreaAlignment],
|
||||
@@ -254,6 +264,32 @@ export function ResizeHandle({
|
||||
[direction, highlighted, theme.colors.foreground],
|
||||
);
|
||||
|
||||
const ariaOrientation = direction === "horizontal" ? "vertical" : "horizontal";
|
||||
const separatorHitArea =
|
||||
interaction === "web-pointer" ? (
|
||||
<View
|
||||
role="separator"
|
||||
aria-orientation={ariaOrientation}
|
||||
style={hitAreaStyle}
|
||||
onPointerDown={handlePointerDown}
|
||||
onPointerEnter={handlePointerEnter}
|
||||
onPointerLeave={handlePointerLeave}
|
||||
/>
|
||||
) : (
|
||||
<GestureDetector gesture={touchGesture}>
|
||||
<View
|
||||
role="separator"
|
||||
aria-orientation={ariaOrientation}
|
||||
collapsable={false}
|
||||
style={interaction === "native-pointer" ? hitAreaStyle : touchHitAreaStyle}
|
||||
onPointerEnter={interaction === "native-pointer" ? handlePointerEnter : undefined}
|
||||
onPointerLeave={interaction === "native-pointer" ? handlePointerLeave : undefined}
|
||||
>
|
||||
{interaction === "touch" ? <View pointerEvents="none" style={touchGripStyle} /> : null}
|
||||
</View>
|
||||
</GestureDetector>
|
||||
);
|
||||
|
||||
return (
|
||||
<View style={handleStyle} testID={testID}>
|
||||
{highlighted && (
|
||||
@@ -263,27 +299,7 @@ export function ResizeHandle({
|
||||
testID={testID ? `${testID}-highlight` : undefined}
|
||||
/>
|
||||
)}
|
||||
{finePointer ? (
|
||||
<View
|
||||
role="separator"
|
||||
aria-orientation={direction === "horizontal" ? "vertical" : "horizontal"}
|
||||
style={hitAreaStyle}
|
||||
onPointerDown={handlePointerDown}
|
||||
onPointerEnter={handlePointerEnter}
|
||||
onPointerLeave={handlePointerLeave}
|
||||
/>
|
||||
) : (
|
||||
<GestureDetector gesture={touchGesture}>
|
||||
<View
|
||||
role="separator"
|
||||
aria-orientation={direction === "horizontal" ? "vertical" : "horizontal"}
|
||||
collapsable={false}
|
||||
style={touchHitAreaStyle}
|
||||
>
|
||||
<View pointerEvents="none" style={touchGripStyle} />
|
||||
</View>
|
||||
</GestureDetector>
|
||||
)}
|
||||
{separatorHitArea}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -56,6 +56,7 @@ import {
|
||||
import { useSidebarCollapsedSectionsStore } from "@/stores/sidebar-collapsed-sections-store";
|
||||
import { useHostFeatureMap } from "@/runtime/host-features";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { useRevealsWithoutHover } from "@/hooks/hover-reveal";
|
||||
import { useProjectIcons } from "@/projects/icons";
|
||||
import {
|
||||
buildNewWorkspaceRoute,
|
||||
@@ -422,7 +423,6 @@ function ProjectRowTrailingActions({
|
||||
settingsTarget,
|
||||
projectPath,
|
||||
isHovered,
|
||||
isMobileBreakpoint,
|
||||
isProjectActive,
|
||||
onBeginWorkspaceSetup,
|
||||
onRemoveProject,
|
||||
@@ -434,13 +434,13 @@ function ProjectRowTrailingActions({
|
||||
settingsTarget: { serverId: string; projectId: string } | null;
|
||||
projectPath: string;
|
||||
isHovered: boolean;
|
||||
isMobileBreakpoint: boolean;
|
||||
isProjectActive: boolean;
|
||||
onBeginWorkspaceSetup: () => void;
|
||||
onRemoveProject?: () => void;
|
||||
removeProjectStatus: "idle" | "pending" | "success";
|
||||
}) {
|
||||
const actionsVisible = isHovered || platformIsNative || isMobileBreakpoint;
|
||||
const revealsWithoutHover = useRevealsWithoutHover();
|
||||
const actionsVisible = isHovered || revealsWithoutHover;
|
||||
return (
|
||||
<View style={styles.projectTrailingActions}>
|
||||
{worktreeTarget ? (
|
||||
@@ -907,7 +907,6 @@ function ProjectHeaderRow({
|
||||
const [isHovered, setIsHovered] = useState(false);
|
||||
const [isHighlighted, setIsHighlighted] = useState(false);
|
||||
const [contextMenuOpen, setContextMenuOpen] = useState(false);
|
||||
const isMobileBreakpoint = useIsCompactFormFactor();
|
||||
const localDaemonServerId = useLocalDaemonServerId();
|
||||
const projectPath = resolveSidebarProjectLocalPath(project, localDaemonServerId);
|
||||
const settingsTarget = project.hosts[0] ?? null;
|
||||
@@ -990,7 +989,6 @@ function ProjectHeaderRow({
|
||||
settingsTarget={settingsTarget}
|
||||
projectPath={projectPath}
|
||||
isHovered={isHovered}
|
||||
isMobileBreakpoint={isMobileBreakpoint}
|
||||
isProjectActive={isProjectActive}
|
||||
onBeginWorkspaceSetup={handleBeginWorkspaceSetup}
|
||||
onRemoveProject={onRemoveProject}
|
||||
@@ -1104,11 +1102,13 @@ function WorkspaceRowInner({
|
||||
onTogglePin,
|
||||
reserveIdleStatusIndicatorSpace = true,
|
||||
}: WorkspaceRowInnerProps) {
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
const [isHighlighted, setIsHighlighted] = useState(false);
|
||||
const isSelectionMode = useIsSidebarSelectionMode();
|
||||
const isBulkSelected = useIsWorkspaceBulkSelected(workspace.workspaceKey);
|
||||
const isTouchPlatform = platformIsNative || isCompact;
|
||||
const isTouchPlatform = useRevealsWithoutHover();
|
||||
// Service status is row metadata, not a hover control: it follows the layout, not the pointer.
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
const showsServiceStatus = !(platformIsNative || isCompact);
|
||||
const interaction = useLongPressDragInteraction({
|
||||
drag,
|
||||
menuController,
|
||||
@@ -1149,8 +1149,9 @@ function WorkspaceRowInner({
|
||||
showArchiveIndicator={showArchiveIndicator}
|
||||
>
|
||||
{({ isHovered, contextMenuOpen, onContextMenuOpenChange, hoverHandlers }) => {
|
||||
const isDesktop = !isTouchPlatform;
|
||||
const serviceSummary = isDesktop ? selectWorkspaceServiceSummary(workspace.scripts) : null;
|
||||
const serviceSummary = showsServiceStatus
|
||||
? selectWorkspaceServiceSummary(workspace.scripts)
|
||||
: null;
|
||||
const workspaceRowStyle = getProjectWorkspaceRowStyle({
|
||||
isDragging,
|
||||
selected: rowSelected,
|
||||
|
||||
@@ -4,8 +4,7 @@ import { ChevronDown, ChevronRight } from "lucide-react-native";
|
||||
import { Text, View } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { DensityIcon } from "@/components/ui/density-icon";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { isNative } from "@/constants/platform";
|
||||
import { useRevealsWithoutHover } from "@/hooks/hover-reveal";
|
||||
import { density } from "@/styles/density";
|
||||
|
||||
/** A sidebar section label such as "Pinned" or "Workspaces". A section with `onToggle`
|
||||
@@ -53,7 +52,7 @@ function CollapsibleTitle({
|
||||
onToggle: () => void;
|
||||
testID?: string;
|
||||
}) {
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
const revealsWithoutHover = useRevealsWithoutHover();
|
||||
const accessibilityState = useMemo(() => ({ expanded: !collapsed }), [collapsed]);
|
||||
|
||||
return (
|
||||
@@ -67,7 +66,7 @@ function CollapsibleTitle({
|
||||
{({ hovered }) => (
|
||||
<>
|
||||
<Text style={styles.title}>{title}</Text>
|
||||
{hovered || isNative || isCompact ? (
|
||||
{hovered || revealsWithoutHover ? (
|
||||
<DensityIcon
|
||||
icon={collapsed ? ChevronRight : ChevronDown}
|
||||
size="xs"
|
||||
|
||||
@@ -24,6 +24,7 @@ import { SidebarFilterEmptyState } from "@/components/sidebar/empty-states";
|
||||
import type { HostBadgeModel } from "@/hosts/appearance";
|
||||
import { isWeb as platformIsWeb, isNative as platformIsNative } from "@/constants/platform";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { useRevealsWithoutHover } from "@/hooks/hover-reveal";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { density, densityIconBox, densityIconProps } from "@/styles/density";
|
||||
import type { SidebarSurfaceBackdrop } from "@/styles/surface-backdrop";
|
||||
@@ -909,8 +910,10 @@ function StatusWorkspaceRowInnerContent({
|
||||
}: StatusWorkspaceRowInnerProps & {
|
||||
dragInteraction?: ReturnType<typeof useLongPressDragInteraction>;
|
||||
}) {
|
||||
const isTouchPlatform = useRevealsWithoutHover();
|
||||
// Service status is row metadata, not a hover control: it follows the layout, not the pointer.
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
const isTouchPlatform = platformIsNative || isCompact;
|
||||
const showsServiceStatus = !(platformIsNative || isCompact);
|
||||
const [isHighlighted, setIsHighlighted] = useState(false);
|
||||
const isSelectionMode = useIsSidebarSelectionMode();
|
||||
const isBulkSelected = useIsWorkspaceBulkSelected(workspace.workspaceKey);
|
||||
@@ -922,8 +925,9 @@ function StatusWorkspaceRowInnerContent({
|
||||
...dragAttributes
|
||||
} = dragHandleProps?.attributes ?? {};
|
||||
|
||||
const isDesktop = !isTouchPlatform;
|
||||
const serviceSummary = isDesktop ? selectWorkspaceServiceSummary(workspace.scripts) : null;
|
||||
const serviceSummary = showsServiceStatus
|
||||
? selectWorkspaceServiceSummary(workspace.scripts)
|
||||
: null;
|
||||
|
||||
const rowSelected = isSelectionMode ? isBulkSelected : selected;
|
||||
const accessibilityState = useMemo(
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useCallback, useEffect, useRef } from "react";
|
||||
import type { GestureResponderEvent } from "react-native";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { isWeb as platformIsWeb } from "@/constants/platform";
|
||||
import { supportsTouchHaptics, usesTouchLongPressHold } from "@/constants/touch-timing";
|
||||
import { decideLongPressMove } from "@/utils/sidebar-gesture-arbitration";
|
||||
import type { useContextMenu } from "@/components/ui/context-menu";
|
||||
|
||||
@@ -59,7 +59,7 @@ export function useLongPressDragInteraction(input: {
|
||||
|
||||
const armTimers = useCallback(() => {
|
||||
clearTimers();
|
||||
if (platformIsWeb || !drag) {
|
||||
if (!usesTouchLongPressHold || !drag) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -86,7 +86,7 @@ export function useLongPressDragInteraction(input: {
|
||||
dragArmedRef.current = true;
|
||||
dragActivatedRef.current = true;
|
||||
didLongPressRef.current = true;
|
||||
void Haptics.selectionAsync().catch(() => {});
|
||||
if (supportsTouchHaptics) void Haptics.selectionAsync().catch(() => {});
|
||||
drag();
|
||||
}, DRAG_ARM_DELAY_MS);
|
||||
|
||||
@@ -109,7 +109,7 @@ export function useLongPressDragInteraction(input: {
|
||||
if (distance > CONTEXT_MENU_STATIONARY_SLOP_PX) {
|
||||
return;
|
||||
}
|
||||
void Haptics.selectionAsync().catch(() => {});
|
||||
if (supportsTouchHaptics) void Haptics.selectionAsync().catch(() => {});
|
||||
openContextMenuAtStartPoint();
|
||||
}, CONTEXT_MENU_DELAY_MS);
|
||||
}, [clearTimers, drag, menuController, openContextMenuAtStartPoint]);
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
} from "@getpaseo/protocol/terminal-input-mode";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
|
||||
import { hasSoftwareKeyboard } from "@/keyboard";
|
||||
import { useKeyboardShiftStyle } from "@/keyboard/shift";
|
||||
import { useAppActivelyVisible } from "@/hooks/use-app-visible";
|
||||
import { useStableEvent } from "@/hooks/use-stable-event";
|
||||
@@ -89,7 +90,6 @@ import {
|
||||
type TerminalResizeRequest,
|
||||
} from "./terminal-resize-debouncer";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { isNative } from "@/constants/platform";
|
||||
import { useKeyboardFocusSurface } from "@/keyboard";
|
||||
import {
|
||||
applyTerminalRendererReadyChange,
|
||||
@@ -305,7 +305,10 @@ export function TerminalPane({
|
||||
return trimmed.length > 0 ? trimmed : undefined;
|
||||
}, [settings.monoFontFamily]);
|
||||
const isMobile = useIsCompactFormFactor();
|
||||
const showVirtualKeyBar = shouldShowTerminalVirtualKeyBar({ isNative, isCompact: isMobile });
|
||||
const showVirtualKeyBar = shouldShowTerminalVirtualKeyBar({
|
||||
hasSoftwareKeyboard,
|
||||
isCompact: isMobile,
|
||||
});
|
||||
const [keyBarWidth, setKeyBarWidth] = useState(0);
|
||||
const virtualKeyboardRows = resolveTerminalVirtualKeyboardRows({
|
||||
isCompact: isMobile,
|
||||
@@ -316,7 +319,7 @@ export function TerminalPane({
|
||||
const swipeGesturesEnabled = isMobile;
|
||||
const { shift: keyboardShift, style: keyboardPaddingStyle } = useKeyboardShiftStyle({
|
||||
mode: "padding",
|
||||
enabled: isNative || isMobile,
|
||||
enabled: hasSoftwareKeyboard || isMobile,
|
||||
});
|
||||
const [keyboardInset, setKeyboardInset] = useState(0);
|
||||
const [isKeyboardVisible, setIsKeyboardVisible] = useState(false);
|
||||
@@ -608,7 +611,7 @@ export function TerminalPane({
|
||||
|
||||
const handleKeyboardChange = useCallback(
|
||||
(nextShift: number) => {
|
||||
setKeyboardInset(isNative || isMobile ? nextShift : 0);
|
||||
setKeyboardInset(hasSoftwareKeyboard || isMobile ? nextShift : 0);
|
||||
setIsKeyboardVisible(nextShift > 0);
|
||||
pulseKeyboardRefits();
|
||||
},
|
||||
@@ -1180,10 +1183,10 @@ export function TerminalPane({
|
||||
emulatorRef.current?.blur();
|
||||
onOpenFileExplorer();
|
||||
}, [swipeGesturesEnabled, onOpenFileExplorer]);
|
||||
const showPasteAction = shouldShowTerminalPasteAction({ isNative });
|
||||
const showPasteAction = shouldShowTerminalPasteAction({ hasSoftwareKeyboard });
|
||||
const showFloatingCopyAction = shouldShowTerminalFloatingCopyAction({
|
||||
hasSelection,
|
||||
isNative,
|
||||
hasSoftwareKeyboard,
|
||||
});
|
||||
const keyboardToggleIconColor = theme.colors.foregroundMuted;
|
||||
|
||||
@@ -1332,7 +1335,9 @@ export function TerminalPane({
|
||||
<View
|
||||
style={styles.keyboardRows}
|
||||
onLayout={handleKeyBarLayout}
|
||||
testID={isNative && !isMobile ? "terminal-virtual-keyboard-native-wide" : undefined}
|
||||
testID={
|
||||
hasSoftwareKeyboard && !isMobile ? "terminal-virtual-keyboard-native-wide" : undefined
|
||||
}
|
||||
>
|
||||
{virtualKeyboardRows.map((row) => (
|
||||
<View
|
||||
|
||||
@@ -13,7 +13,8 @@ import {
|
||||
import { PressHighlight } from "@/components/ui/press-highlight";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { isNative } from "@/constants/platform";
|
||||
import { isNative, isWeb } from "@/constants/platform";
|
||||
import { usePointerCapabilities } from "@/hooks/pointer-capabilities";
|
||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||
import { DetailsSheet } from "./details-sheet";
|
||||
import { MetricsList } from "./metrics-list";
|
||||
@@ -24,7 +25,8 @@ const foregroundMutedColorMapping = (theme: Theme) => ({ color: theme.colors.for
|
||||
|
||||
/**
|
||||
* The turn footer's stats button: what the provider reported about this turn, in a hover card on
|
||||
* web, a tooltip opened by press on native wide screens, and a sheet on compact screens.
|
||||
* desktop, a tooltip opened by press on wide native screens, and a sheet on compact screens and
|
||||
* touch-first browsers.
|
||||
*/
|
||||
export const TurnMetricsButton = memo(function TurnMetricsButton({
|
||||
metrics,
|
||||
@@ -32,7 +34,8 @@ export const TurnMetricsButton = memo(function TurnMetricsButton({
|
||||
metrics: AgentMetric[];
|
||||
}) {
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
if (isCompact) return <TurnMetricsSheetButton metrics={metrics} />;
|
||||
const { finePointer } = usePointerCapabilities();
|
||||
if (isCompact || (isWeb && !finePointer)) return <TurnMetricsSheetButton metrics={metrics} />;
|
||||
if (isNative) return <TurnMetricsTooltipButton metrics={metrics} />;
|
||||
return <TurnMetricsHoverCardButton metrics={metrics} />;
|
||||
});
|
||||
|
||||
@@ -20,6 +20,7 @@ import { OverlayLayerProvider, useOverlayLayer } from "@/lib/overlay-root";
|
||||
import { FloatingSurface } from "@/components/ui/floating";
|
||||
import { useFloatingPanelPortalHostName } from "@/components/ui/floating-panel-portal";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { usePointerCapabilities } from "@/hooks/pointer-capabilities";
|
||||
import { useHoverSafeZone } from "@/hooks/use-hover-safe-zone";
|
||||
import { computePosition, type Alignment, type Placement, type Rect } from "./anchor";
|
||||
|
||||
@@ -43,8 +44,8 @@ const HoverCardContext = createContext<HoverCardContextValue | null>(null);
|
||||
|
||||
/**
|
||||
* A card that opens while the pointer is on its trigger and stays open while the pointer crosses
|
||||
* onto it, so its content can be pressed. Hover only exists on web; elsewhere the trigger renders
|
||||
* alone and the content never mounts. See docs/hover.md.
|
||||
* onto it, so its content can be pressed. Only a mouse-like pointer hovers; on a touch screen the
|
||||
* trigger renders alone and the content never mounts. See docs/hover.md.
|
||||
*
|
||||
* ```tsx
|
||||
* <HoverCard>
|
||||
@@ -61,7 +62,8 @@ export function HoverCard({
|
||||
disabled?: boolean;
|
||||
children: ReactNode;
|
||||
}): ReactNode {
|
||||
if (!isWeb) return children;
|
||||
const { finePointer } = usePointerCapabilities();
|
||||
if (!finePointer) return children;
|
||||
return <WebHoverCard disabled={disabled}>{children}</WebHoverCard>;
|
||||
}
|
||||
|
||||
|
||||
@@ -25,10 +25,11 @@ import {
|
||||
} from "react-native";
|
||||
import { FadeIn, FadeOut } from "react-native-reanimated";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { FloatingSurface } from "@/components/ui/floating";
|
||||
import { useRetainedPanelActive } from "@/components/retained-panel";
|
||||
import { isNative, isWeb } from "@/constants/platform";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { useRevealsWithoutHover } from "@/hooks/hover-reveal";
|
||||
import { usePointerCapabilities } from "@/hooks/pointer-capabilities";
|
||||
import { getOverlayRoot, OVERLAY_Z } from "@/lib/overlay-root";
|
||||
import { holdSurfaceEdge, surfaceFrameStyles, type SurfacePosition } from "./anchor";
|
||||
|
||||
@@ -50,6 +51,8 @@ interface TooltipContextValue {
|
||||
triggerRef: React.RefObject<TooltipTriggerElement | null>;
|
||||
enabled: boolean;
|
||||
openOnPress: boolean;
|
||||
/** A mouse-like pointer drives the UI, so entering and leaving the trigger opens and closes it. */
|
||||
opensOnHover: boolean;
|
||||
delayDuration: number;
|
||||
}
|
||||
|
||||
@@ -257,9 +260,12 @@ export function Tooltip({
|
||||
onOpenChange,
|
||||
});
|
||||
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
const active = useRetainedPanelActive();
|
||||
const opensOnPress = isNative || isCompact;
|
||||
// Where nothing hovers, a press opens the tooltip instead.
|
||||
const opensOnPress = useRevealsWithoutHover();
|
||||
// A touch fires compatibility mouse events around its tap, which would close the tooltip the tap
|
||||
// just opened.
|
||||
const { finePointer: opensOnHover } = usePointerCapabilities();
|
||||
const enabled = active && (opensOnPress ? enabledOnMobile : enabledOnDesktop);
|
||||
|
||||
// Remove the portal in the inactive commit, before the retained chat freezes.
|
||||
@@ -275,9 +281,10 @@ export function Tooltip({
|
||||
triggerRef,
|
||||
enabled,
|
||||
openOnPress: opensOnPress,
|
||||
opensOnHover,
|
||||
delayDuration,
|
||||
}),
|
||||
[isOpen, setIsOpen, enabled, opensOnPress, delayDuration],
|
||||
[isOpen, setIsOpen, enabled, opensOnPress, opensOnHover, delayDuration],
|
||||
);
|
||||
|
||||
return <TooltipContext.Provider value={value}>{children}</TooltipContext.Provider>;
|
||||
@@ -345,17 +352,17 @@ export function TooltipTrigger({
|
||||
const handleHoverIn = useCallback(
|
||||
(e?: unknown) => {
|
||||
if (isCallable(onHoverIn)) onHoverIn(e);
|
||||
scheduleOpen();
|
||||
if (ctx.opensOnHover) scheduleOpen();
|
||||
},
|
||||
[onHoverIn, scheduleOpen],
|
||||
[ctx.opensOnHover, onHoverIn, scheduleOpen],
|
||||
);
|
||||
|
||||
const handleHoverOut = useCallback(
|
||||
(e?: unknown) => {
|
||||
if (isCallable(onHoverOut)) onHoverOut(e);
|
||||
close();
|
||||
if (ctx.opensOnHover) close();
|
||||
},
|
||||
[onHoverOut, close],
|
||||
[ctx.opensOnHover, onHoverOut, close],
|
||||
);
|
||||
|
||||
const handleFocus = useCallback(
|
||||
@@ -532,6 +539,26 @@ export function TooltipContent({
|
||||
|
||||
const handleDismiss = useCallback(() => ctx.setOpen(false), [ctx]);
|
||||
|
||||
// A tooltip opened by a tap has no pointer leaving to close it, and the web measures its anchor
|
||||
// once. It closes on a tap elsewhere, and when the page scrolls it would sit over other content.
|
||||
const closesOnTouchDismiss = isWeb && ctx.openOnPress && ctx.open;
|
||||
useEffect(() => {
|
||||
if (!closesOnTouchDismiss) return;
|
||||
const dismissOutsideTrigger = (event: Event) => {
|
||||
const trigger = ctx.triggerRef.current;
|
||||
if (trigger instanceof HTMLElement && event.target instanceof Node) {
|
||||
if (trigger.contains(event.target)) return;
|
||||
}
|
||||
handleDismiss();
|
||||
};
|
||||
window.addEventListener("scroll", handleDismiss, { capture: true, passive: true });
|
||||
window.addEventListener("pointerdown", dismissOutsideTrigger, { capture: true });
|
||||
return () => {
|
||||
window.removeEventListener("scroll", handleDismiss, { capture: true });
|
||||
window.removeEventListener("pointerdown", dismissOutsideTrigger, { capture: true });
|
||||
};
|
||||
}, [closesOnTouchDismiss, ctx.triggerRef, handleDismiss]);
|
||||
|
||||
if (!ctx.open || !ctx.enabled) return null;
|
||||
|
||||
// On web, avoid React Native's <Modal/> implementation (it uses <dialog> and can
|
||||
|
||||
@@ -21,7 +21,7 @@ import { ComposerToolbarGlyph } from "@/composer/agent-controls/glyph";
|
||||
import { resolveModelTriggerLabels } from "@/composer/agent-controls/layout";
|
||||
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { hasSoftwareKeyboard } from "@/keyboard";
|
||||
import { readMeasuredWidth } from "@/hooks/use-container-width";
|
||||
import {
|
||||
toolbarContentSlot,
|
||||
@@ -186,7 +186,7 @@ export function CompactModelSheet({
|
||||
selectedProvider,
|
||||
selectedModel,
|
||||
isLoading,
|
||||
autoFocusSearch: isWeb && !usesBottomSheet,
|
||||
autoFocusSearch: !hasSoftwareKeyboard && !usesBottomSheet,
|
||||
profiles,
|
||||
serverId,
|
||||
});
|
||||
|
||||
@@ -61,6 +61,7 @@ import {
|
||||
toolbarSlot,
|
||||
} from "@/components/ui/control-geometry";
|
||||
import { usePanelStore, type MobilePanelView } from "@/stores/panel-store";
|
||||
import { hasSoftwareKeyboard } from "@/keyboard";
|
||||
import { usePointerCapabilities } from "@/hooks/pointer-capabilities";
|
||||
import { useShallow } from "zustand/shallow";
|
||||
import {
|
||||
@@ -254,7 +255,7 @@ function resolveKeyboardPriority(isMessageInputFocused: boolean): number {
|
||||
}
|
||||
|
||||
function resolveIsDesktopWebBreakpoint(isMobile: boolean): boolean {
|
||||
return isWeb && !isMobile;
|
||||
return !hasSoftwareKeyboard && !isMobile;
|
||||
}
|
||||
|
||||
function resolveCompactLayout(override: boolean | undefined, formFactor: boolean): boolean {
|
||||
|
||||
@@ -82,8 +82,11 @@ import { useIosHardwareKeyboardSubmit } from "@/hooks/use-ios-hardware-keyboard-
|
||||
import { formatShortcut, type ShortcutKey } from "@/utils/format-shortcut";
|
||||
import { getShortcutOs } from "@/utils/shortcut-platform";
|
||||
import type { MessageInputKeyboardActionKind } from "@/keyboard/actions";
|
||||
import { supportsConfigurableComposerSendKeys } from "@/keyboard";
|
||||
import { isImeComposingKeyboardEvent } from "@/utils/keyboard-ime";
|
||||
import { getIsElectron, isNative, isWeb } from "@/constants/platform";
|
||||
import { getIsElectron, isWeb } from "@/constants/platform";
|
||||
import { composerMinInputHeight } from "@/constants/presentation";
|
||||
import { supportsTouchHaptics } from "@/constants/touch-timing";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { useComposerKeyboardScope } from "@/composer/keyboard-scope";
|
||||
import { RenderProfile } from "@/utils/render-profiler";
|
||||
@@ -238,11 +241,9 @@ export interface MessageInputRef {
|
||||
getNativeElement?: () => HTMLElement | null;
|
||||
}
|
||||
|
||||
const MIN_INPUT_HEIGHT_MOBILE = 30;
|
||||
const MIN_INPUT_HEIGHT_DESKTOP = 46;
|
||||
const DEFAULT_MAX_INPUT_HEIGHT = 160;
|
||||
const MAX_INPUT_VIEWPORT_RATIO = 0.5;
|
||||
const MIN_INPUT_HEIGHT = isWeb ? MIN_INPUT_HEIGHT_DESKTOP : MIN_INPUT_HEIGHT_MOBILE;
|
||||
const MIN_INPUT_HEIGHT = composerMinInputHeight;
|
||||
type WebTextInputKeyPressEvent = NativeSyntheticEvent<
|
||||
TextInputKeyPressEventData & {
|
||||
metaKey?: boolean;
|
||||
@@ -1883,7 +1884,7 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
});
|
||||
|
||||
const handleLongPressSend = useCallback(() => {
|
||||
if (alternateSendAction && isNative) {
|
||||
if (alternateSendAction && supportsTouchHaptics) {
|
||||
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium).catch(() => {});
|
||||
}
|
||||
handleAlternateSendAction();
|
||||
@@ -1910,12 +1911,12 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
[onSelectionChangeCallback],
|
||||
);
|
||||
|
||||
const shouldHandleWebKeyPress = isWeb;
|
||||
const shouldSubmitOnEnter = isWeb && !isCompact;
|
||||
const shouldHandleKeyPress = supportsConfigurableComposerSendKeys;
|
||||
const shouldSubmitOnEnter = supportsConfigurableComposerSendKeys && !isCompact;
|
||||
|
||||
const handleDesktopKeyPress = useCallback(
|
||||
(event: WebTextInputKeyPressEvent) => {
|
||||
if (!shouldHandleWebKeyPress) return;
|
||||
if (!shouldHandleKeyPress) return;
|
||||
handleDesktopKeyPressImpl(event, {
|
||||
onKeyPressCallback,
|
||||
input: getComposerInputSnapshot(
|
||||
@@ -1935,7 +1936,7 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
});
|
||||
},
|
||||
[
|
||||
shouldHandleWebKeyPress,
|
||||
shouldHandleKeyPress,
|
||||
onKeyPressCallback,
|
||||
shouldSubmitOnEnter,
|
||||
sendShortcut,
|
||||
@@ -2222,14 +2223,19 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
editable={!isDictating && !isRealtimeVoiceForCurrentAgent && !disabled}
|
||||
scrollEnabled={isComposerScrollEnabled}
|
||||
autoFocus={false}
|
||||
onKeyPress={shouldHandleWebKeyPress ? handleDesktopKeyPress : undefined}
|
||||
onKeyPress={shouldHandleKeyPress ? handleDesktopKeyPress : undefined}
|
||||
onSelectionChange={handleSelectionChange}
|
||||
onPasteImages={onPasteImages}
|
||||
onPasteError={handlePasteError}
|
||||
fullscreen={isFullscreen}
|
||||
compact={isCompact}
|
||||
onRenderedLinesChange={setRenderedLines}
|
||||
focusHintVisible={!isFullscreen && isWeb && !isInputFocused && !hasLiveText}
|
||||
focusHintVisible={
|
||||
!isFullscreen &&
|
||||
supportsConfigurableComposerSendKeys &&
|
||||
!isInputFocused &&
|
||||
!hasLiveText
|
||||
}
|
||||
focusInputKeys={focusInputKeys}
|
||||
focusHintLabel={t("composer.input.focusHint", {
|
||||
shortcut: focusInputKeys ? formatShortcut(focusInputKeys[0], getShortcutOs()) : "",
|
||||
@@ -2253,7 +2259,7 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
isRealtimeVoiceForCurrentAgent,
|
||||
disabled,
|
||||
isComposerScrollEnabled,
|
||||
shouldHandleWebKeyPress,
|
||||
shouldHandleKeyPress,
|
||||
handleDesktopKeyPress,
|
||||
handleSelectionChange,
|
||||
onPasteImages,
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { DaemonConnectionError } from "@getpaseo/client/internal/daemon-client";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { createLocalFileAttachmentStore } from "@/attachments/local-file-attachment-store";
|
||||
import {
|
||||
@@ -26,39 +25,6 @@ function createDeferredPromise<T>() {
|
||||
}
|
||||
|
||||
describe("submitAgentInput", () => {
|
||||
it("explains an interrupted send and restores the draft", async () => {
|
||||
let draft = "hello";
|
||||
let sendError: string | null = null;
|
||||
const result = await submitAgentInput({
|
||||
message: draft,
|
||||
attachments: [],
|
||||
isAgentRunning: false,
|
||||
canSubmit: true,
|
||||
queueMessage: async () => {
|
||||
throw new Error("Expected to send directly");
|
||||
},
|
||||
submitMessage: async () => {
|
||||
throw new DaemonConnectionError("Software caused connection abort");
|
||||
},
|
||||
getDraftRevision: () => 0,
|
||||
clearDraft: () => {
|
||||
draft = "";
|
||||
},
|
||||
setUserInput: (text) => {
|
||||
draft = text;
|
||||
},
|
||||
setAttachments: () => {},
|
||||
setSendError: (message) => {
|
||||
sendError = message;
|
||||
},
|
||||
setIsProcessing: () => {},
|
||||
});
|
||||
|
||||
expect(result).toBe("failed");
|
||||
expect(draft).toBe("hello");
|
||||
expect(sendError).toBe("Connection lost. Paseo could not confirm that your message was sent.");
|
||||
});
|
||||
|
||||
it("clears the composer before an in-flight submit resolves", async () => {
|
||||
const deferred = createDeferredPromise<void>();
|
||||
const queueMessage = vi.fn();
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import { DaemonConnectionError } from "@getpaseo/client/internal/daemon-client";
|
||||
|
||||
import { retainAttachmentForGarbageCollection } from "@/attachments/gc-retention";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
|
||||
@@ -114,7 +112,11 @@ export async function submitAgentInput<TAttachment>(
|
||||
input.setUserInput(trimmedMessage);
|
||||
input.setAttachments(attachments);
|
||||
}
|
||||
input.setSendError(describeSendError(error, input.failedToSendMessage));
|
||||
input.setSendError(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: (input.failedToSendMessage ?? i18n.t("composer.errors.failedToSend")),
|
||||
);
|
||||
input.setIsProcessing(false);
|
||||
return "failed";
|
||||
}
|
||||
@@ -124,12 +126,3 @@ export async function submitAgentInput<TAttachment>(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function describeSendError(error: unknown, fallback?: string): string {
|
||||
if (error instanceof DaemonConnectionError && error.code === "DAEMON_CONNECTION_LOST") {
|
||||
return i18n.t("composer.errors.sendConnectionLost");
|
||||
}
|
||||
return error instanceof Error
|
||||
? error.message
|
||||
: (fallback ?? i18n.t("composer.errors.failedToSend"));
|
||||
}
|
||||
|
||||
@@ -25,6 +25,9 @@ export const isWeb = Platform.OS === "web";
|
||||
/** iOS or Android — the JS runtime is React Native. */
|
||||
export const isNative = Platform.OS !== "web";
|
||||
|
||||
/** Platforms with an alpha-mask compositor for decorative shimmer effects. */
|
||||
export const supportsMaskedEffects = ["web", "ios", "android"].includes(Platform.OS);
|
||||
|
||||
/** Development build/runtime — true in Metro dev bundles, false in production. */
|
||||
export const isDev = Boolean((globalThis as { __DEV__?: boolean }).__DEV__);
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { resolvePresentationCapabilities } from "./presentation";
|
||||
|
||||
describe("presentation capabilities per target", () => {
|
||||
it("resolves mobile and desktop presentation answers for iOS, Android, web, and Electron", () => {
|
||||
expect(resolvePresentationCapabilities({ isNative: true, isWeb: false })).toEqual({
|
||||
allowsInlineWorkspaceRename: false,
|
||||
usesCompactBottomSheet: true,
|
||||
usesDesktopPopoverSpacing: false,
|
||||
initialUiBaseFontSize: 15,
|
||||
initialContentFontSize: 16,
|
||||
usesMobileContentFontMigration: true,
|
||||
composerMinInputHeight: 30,
|
||||
});
|
||||
expect(resolvePresentationCapabilities({ isNative: false, isWeb: true })).toEqual({
|
||||
allowsInlineWorkspaceRename: true,
|
||||
usesCompactBottomSheet: false,
|
||||
usesDesktopPopoverSpacing: true,
|
||||
initialUiBaseFontSize: 14,
|
||||
initialContentFontSize: 15,
|
||||
usesMobileContentFontMigration: false,
|
||||
composerMinInputHeight: 46,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import { FONT_SIZE } from "@/styles/theme";
|
||||
import { isNative, isWeb } from "./platform";
|
||||
|
||||
export interface PresentationCapabilities {
|
||||
/** Wide sidebar rows rename in place instead of opening a rename modal. */
|
||||
allowsInlineWorkspaceRename: boolean;
|
||||
/** Compact screens present bottom sheets (`SheetFlatList` / Gorhom modal) instead of dialogs. */
|
||||
usesCompactBottomSheet: boolean;
|
||||
/** Popover lists use tight desktop row padding instead of touch-sheet spacing. */
|
||||
usesDesktopPopoverSpacing: boolean;
|
||||
/** Initial UI font size (pt) when no user preference is saved. */
|
||||
initialUiBaseFontSize: number;
|
||||
/** Initial chat content font size (pt) when no user preference is saved. */
|
||||
initialContentFontSize: number;
|
||||
/** Whether legacy 15 pt persisted content size migrates up to the mobile 16 pt default. */
|
||||
usesMobileContentFontMigration: boolean;
|
||||
/** Minimum multiline composer input height (pt). */
|
||||
composerMinInputHeight: number;
|
||||
}
|
||||
|
||||
export function resolvePresentationCapabilities(input: {
|
||||
isNative: boolean;
|
||||
isWeb: boolean;
|
||||
}): PresentationCapabilities {
|
||||
return {
|
||||
allowsInlineWorkspaceRename: input.isWeb,
|
||||
usesCompactBottomSheet: input.isNative,
|
||||
usesDesktopPopoverSpacing: input.isWeb,
|
||||
initialUiBaseFontSize: input.isNative ? 15 : FONT_SIZE.base,
|
||||
initialContentFontSize: input.isNative ? 16 : FONT_SIZE.content,
|
||||
usesMobileContentFontMigration: input.isNative,
|
||||
composerMinInputHeight: input.isWeb ? 46 : 30,
|
||||
};
|
||||
}
|
||||
|
||||
const CAPABILITIES = resolvePresentationCapabilities({ isNative, isWeb });
|
||||
|
||||
export const allowsInlineWorkspaceRename = CAPABILITIES.allowsInlineWorkspaceRename;
|
||||
export const usesCompactBottomSheet = CAPABILITIES.usesCompactBottomSheet;
|
||||
export const usesDesktopPopoverSpacing = CAPABILITIES.usesDesktopPopoverSpacing;
|
||||
export const initialUiBaseFontSize = CAPABILITIES.initialUiBaseFontSize;
|
||||
export const initialContentFontSize = CAPABILITIES.initialContentFontSize;
|
||||
export const usesMobileContentFontMigration = CAPABILITIES.usesMobileContentFontMigration;
|
||||
export const composerMinInputHeight = CAPABILITIES.composerMinInputHeight;
|
||||
@@ -0,0 +1,26 @@
|
||||
// Platform-free: Playwright imports this through workspace-deck-retention in plain Node.
|
||||
|
||||
export interface SourceFileBudgets {
|
||||
readonly highlighted: number;
|
||||
readonly plain: number;
|
||||
}
|
||||
|
||||
export interface PlatformResourceBudgets {
|
||||
readonly workspaceDeckRetentionLimit: number;
|
||||
readonly sourceFileBudgets: SourceFileBudgets;
|
||||
}
|
||||
|
||||
const MOBILE_RESOURCE_BUDGETS: PlatformResourceBudgets = {
|
||||
workspaceDeckRetentionLimit: 1,
|
||||
sourceFileBudgets: { highlighted: 1024 * 1024, plain: 10 * 1024 * 1024 },
|
||||
};
|
||||
|
||||
const WEB_RESOURCE_BUDGETS: PlatformResourceBudgets = {
|
||||
workspaceDeckRetentionLimit: 10,
|
||||
sourceFileBudgets: { highlighted: 10 * 1024 * 1024, plain: 50 * 1024 * 1024 },
|
||||
};
|
||||
|
||||
/** Native phones use mobile memory budgets; web and Electron use desktop budgets. */
|
||||
export function resolveResourceBudgets(input: { isNative: boolean }): PlatformResourceBudgets {
|
||||
return input.isNative ? MOBILE_RESOURCE_BUDGETS : WEB_RESOURCE_BUDGETS;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { resolveResourceBudgets } from "./resource-budget-tables";
|
||||
|
||||
describe("resource budget per target", () => {
|
||||
it("resolves mobile and desktop resource budget limits for iOS, Android, web, and Electron", () => {
|
||||
expect(resolveResourceBudgets({ isNative: true })).toEqual({
|
||||
workspaceDeckRetentionLimit: 1,
|
||||
sourceFileBudgets: { highlighted: 1024 * 1024, plain: 10 * 1024 * 1024 },
|
||||
});
|
||||
expect(resolveResourceBudgets({ isNative: false })).toEqual({
|
||||
workspaceDeckRetentionLimit: 10,
|
||||
sourceFileBudgets: { highlighted: 10 * 1024 * 1024, plain: 50 * 1024 * 1024 },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
import { isNative } from "./platform";
|
||||
import { resolveResourceBudgets } from "./resource-budget-tables";
|
||||
|
||||
const RESOURCE_BUDGETS = resolveResourceBudgets({ isNative });
|
||||
|
||||
export const workspaceDeckRetentionLimit = RESOURCE_BUDGETS.workspaceDeckRetentionLimit;
|
||||
export const sourceFileBudgets = RESOURCE_BUDGETS.sourceFileBudgets;
|
||||
@@ -0,0 +1,15 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { resolveTouchTiming } from "./touch-timing";
|
||||
|
||||
describe("touch timing per target", () => {
|
||||
it("enables touch timing and haptics only on iOS and Android, not on web or Electron", () => {
|
||||
expect(resolveTouchTiming({ isNative: true })).toEqual({
|
||||
supportsTouchHaptics: true,
|
||||
usesTouchLongPressHold: true,
|
||||
});
|
||||
expect(resolveTouchTiming({ isNative: false })).toEqual({
|
||||
supportsTouchHaptics: false,
|
||||
usesTouchLongPressHold: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import { isNative } from "./platform";
|
||||
|
||||
export interface TouchTimingCapabilities {
|
||||
/** Fire tactile `expo-haptics` feedback on touch interactions. */
|
||||
supportsTouchHaptics: boolean;
|
||||
/** Require a stationary long-press delay to arm drag or open context menus. */
|
||||
usesTouchLongPressHold: boolean;
|
||||
}
|
||||
|
||||
export function resolveTouchTiming(input: { isNative: boolean }): TouchTimingCapabilities {
|
||||
return {
|
||||
supportsTouchHaptics: input.isNative,
|
||||
usesTouchLongPressHold: input.isNative,
|
||||
};
|
||||
}
|
||||
|
||||
const TOUCH_TIMING = resolveTouchTiming({ isNative });
|
||||
|
||||
export const supportsTouchHaptics = TOUCH_TIMING.supportsTouchHaptics;
|
||||
export const usesTouchLongPressHold = TOUCH_TIMING.usesTouchLongPressHold;
|
||||
@@ -73,7 +73,7 @@ type TextFilePanelProps = BuiltinFilePanelProps & {
|
||||
*/
|
||||
export function TextFilePanel(props: TextFilePanelProps) {
|
||||
const size = props.file.size;
|
||||
const presentation = selectSourcePresentation({ size, platform: isWeb ? "web" : "native" });
|
||||
const presentation = selectSourcePresentation({ size });
|
||||
if (presentation === "unsupported") return <TooLargeTextFile size={size} />;
|
||||
if (isWeb && size <= MAX_EDITABLE_BYTES) return <EditableTextFile {...props} />;
|
||||
return <ReadonlyTextFile {...props} presentation={presentation} />;
|
||||
|
||||
@@ -11,4 +11,11 @@ describe("selectSourcePresentation", () => {
|
||||
expect(selectSourcePresentation({ platform, size: budgets.plain + 1 })).toBe("unsupported");
|
||||
});
|
||||
}
|
||||
|
||||
it("defaults to the target resource budget limits when no platform override is passed", () => {
|
||||
const webBudgets = SOURCE_PRESENTATION_BUDGETS.web;
|
||||
expect(selectSourcePresentation({ size: webBudgets.highlighted })).toBe("highlighted");
|
||||
expect(selectSourcePresentation({ size: webBudgets.highlighted + 1 })).toBe("plain");
|
||||
expect(selectSourcePresentation({ size: webBudgets.plain + 1 })).toBe("unsupported");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { sourceFileBudgets } from "@/constants/resource-budget";
|
||||
import { resolveResourceBudgets } from "@/constants/resource-budget-tables";
|
||||
|
||||
export const SOURCE_PRESENTATION_BUDGETS = {
|
||||
web: { highlighted: 10 * 1024 * 1024, plain: 50 * 1024 * 1024 },
|
||||
native: { highlighted: 1024 * 1024, plain: 10 * 1024 * 1024 },
|
||||
web: resolveResourceBudgets({ isNative: false }).sourceFileBudgets,
|
||||
native: resolveResourceBudgets({ isNative: true }).sourceFileBudgets,
|
||||
} as const;
|
||||
|
||||
export type SourcePresentation = "highlighted" | "plain" | "unsupported";
|
||||
@@ -8,9 +11,9 @@ export type SourcePlatform = keyof typeof SOURCE_PRESENTATION_BUDGETS;
|
||||
|
||||
export function selectSourcePresentation(input: {
|
||||
size: number;
|
||||
platform: SourcePlatform;
|
||||
platform?: SourcePlatform;
|
||||
}): SourcePresentation {
|
||||
const budgets = SOURCE_PRESENTATION_BUDGETS[input.platform];
|
||||
const budgets = input.platform ? SOURCE_PRESENTATION_BUDGETS[input.platform] : sourceFileBudgets;
|
||||
if (input.size <= budgets.highlighted) return "highlighted";
|
||||
if (input.size <= budgets.plain) return "plain";
|
||||
return "unsupported";
|
||||
|
||||
@@ -35,7 +35,7 @@ import { useSessionStore } from "@/stores/session-store";
|
||||
import { useWorkspaceAttachmentsStore } from "@/attachments/workspace-attachments-store";
|
||||
import { useToast } from "@/contexts/toast-context";
|
||||
import { useCheckoutGitActionsStore } from "@/git/actions-store";
|
||||
import { isNative } from "@/constants/platform";
|
||||
import { useRevealsWithoutHover } from "@/hooks/hover-reveal";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import {
|
||||
PaneContentToolbar,
|
||||
@@ -659,12 +659,12 @@ function TimelineEntryCard({
|
||||
}
|
||||
|
||||
function useRevealOnHover() {
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
const revealsWithoutHover = useRevealsWithoutHover();
|
||||
const [isHovered, setIsHovered] = useState(false);
|
||||
const [menuOpen, setMenuOpen] = useState(false);
|
||||
const handlePointerEnter = useCallback(() => setIsHovered(true), []);
|
||||
const handlePointerLeave = useCallback(() => setIsHovered(false), []);
|
||||
const actionsVisible = isHovered || menuOpen || isNative || isCompact;
|
||||
const actionsVisible = isHovered || menuOpen || revealsWithoutHover;
|
||||
return { actionsVisible, handlePointerEnter, handlePointerLeave, setMenuOpen };
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { resolveRevealsWithoutHover } from "./hover-reveal";
|
||||
import { createPointerCapabilitiesSource, type PointerCapabilities } from "./pointer-capabilities";
|
||||
|
||||
function browserPointer(queries: Record<string, boolean>): PointerCapabilities {
|
||||
const matchMedia = (query: string) =>
|
||||
({
|
||||
matches: queries[query],
|
||||
addEventListener() {},
|
||||
removeEventListener() {},
|
||||
}) as unknown as MediaQueryList;
|
||||
return createPointerCapabilitiesSource(matchMedia).getSnapshot();
|
||||
}
|
||||
|
||||
const desktopBrowser = browserPointer({
|
||||
"(hover: hover) and (pointer: fine)": true,
|
||||
"(any-pointer: coarse)": false,
|
||||
"(pointer: coarse)": false,
|
||||
});
|
||||
// iPad Safari: a wide web layout that no mouse drives.
|
||||
const touchBrowser = browserPointer({
|
||||
"(hover: hover) and (pointer: fine)": false,
|
||||
"(any-pointer: coarse)": true,
|
||||
"(pointer: coarse)": true,
|
||||
});
|
||||
const nativeTouch: PointerCapabilities = { finePointer: false, touchScreen: true };
|
||||
|
||||
describe("hover-revealed controls per target", () => {
|
||||
it("hides them until hover on a desktop browser", () => {
|
||||
expect(resolveRevealsWithoutHover(desktopBrowser, false)).toBe(false);
|
||||
});
|
||||
|
||||
it("pins them on a touch screen, native or in a wide browser", () => {
|
||||
expect(resolveRevealsWithoutHover(nativeTouch, false)).toBe(true);
|
||||
expect(resolveRevealsWithoutHover(touchBrowser, false)).toBe(true);
|
||||
});
|
||||
|
||||
it("pins them in the compact layout whatever the pointer", () => {
|
||||
expect(resolveRevealsWithoutHover(desktopBrowser, true)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { usePointerCapabilities, type PointerCapabilities } from "@/hooks/pointer-capabilities";
|
||||
|
||||
/**
|
||||
* Whether controls a hover would reveal stay visible instead: the pointer
|
||||
* cannot hover (a touch screen), or the compact layout shows them anyway.
|
||||
* Ask this rather than `isNative`: a touch-first browser such as iPad Safari
|
||||
* is web yet cannot hover.
|
||||
*/
|
||||
export function resolveRevealsWithoutHover(
|
||||
pointer: PointerCapabilities,
|
||||
isCompact: boolean,
|
||||
): boolean {
|
||||
return !pointer.finePointer || isCompact;
|
||||
}
|
||||
|
||||
export function useRevealsWithoutHover(): boolean {
|
||||
return resolveRevealsWithoutHover(usePointerCapabilities(), useIsCompactFormFactor());
|
||||
}
|
||||
@@ -23,7 +23,12 @@ import {
|
||||
isChecksHiddenByLegacyRowItem,
|
||||
type SidebarRowItems,
|
||||
} from "@/components/sidebar/display-preferences/row-items";
|
||||
import { isNative } from "@/constants/platform";
|
||||
import {
|
||||
initialContentFontSize,
|
||||
initialUiBaseFontSize,
|
||||
resolvePresentationCapabilities,
|
||||
usesMobileContentFontMigration,
|
||||
} from "@/constants/presentation";
|
||||
import {
|
||||
DEFAULT_CONTENT_MAX_WIDTH,
|
||||
FONT_SIZE,
|
||||
@@ -60,17 +65,19 @@ export const DEFAULT_TERMINAL_SCROLLBACK_LINES = 10_000;
|
||||
export const MIN_TERMINAL_SCROLLBACK_LINES = 0;
|
||||
export const MAX_TERMINAL_SCROLLBACK_LINES = 1_000_000;
|
||||
export function defaultUiBaseFontSize(native: boolean): number {
|
||||
return native ? 15 : FONT_SIZE.base;
|
||||
return resolvePresentationCapabilities({ isNative: native, isWeb: !native })
|
||||
.initialUiBaseFontSize;
|
||||
}
|
||||
|
||||
export const DEFAULT_UI_BASE_FONT_SIZE = defaultUiBaseFontSize(isNative);
|
||||
export const DEFAULT_UI_BASE_FONT_SIZE = initialUiBaseFontSize;
|
||||
export const MIN_UI_BASE_FONT_SIZE = 10;
|
||||
export const MAX_UI_BASE_FONT_SIZE = 21;
|
||||
export function defaultContentFontSize(native: boolean): number {
|
||||
return native ? 16 : FONT_SIZE.content;
|
||||
return resolvePresentationCapabilities({ isNative: native, isWeb: !native })
|
||||
.initialContentFontSize;
|
||||
}
|
||||
|
||||
export const DEFAULT_CONTENT_FONT_SIZE = defaultContentFontSize(isNative);
|
||||
export const DEFAULT_CONTENT_FONT_SIZE = initialContentFontSize;
|
||||
export const MIN_CONTENT_FONT_SIZE = 10;
|
||||
export const MAX_CONTENT_FONT_SIZE = 21;
|
||||
export const DEFAULT_CODE_FONT_SIZE = 12; // == FONT_SIZE.code
|
||||
@@ -410,7 +417,9 @@ export async function loadAppSettingsFromStorage(deps: SettingsDeps): Promise<Ap
|
||||
await writeAppSettings(deps.storage, read.stored, read.settings);
|
||||
}
|
||||
const { needsWrite: _needsWrite, ...stored } = read.stored;
|
||||
return await migrateAppSettings(read.settings, deps.storage, stored, { native: isNative });
|
||||
return await migrateAppSettings(read.settings, deps.storage, stored, {
|
||||
native: usesMobileContentFontMigration,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[AppSettings] Failed to load settings:", error);
|
||||
throw error;
|
||||
|
||||
@@ -220,7 +220,6 @@ export const ar: TranslationResources = {
|
||||
errors: {
|
||||
removePluginCommandAttachments: "أزل المرفقات لتشغيل الأمر /{{command}}.",
|
||||
failedToSend: "فشل في إرسال الرسالة",
|
||||
sendConnectionLost: "انقطع الاتصال. لم يتمكن Paseo من تأكيد إرسال رسالتك.",
|
||||
failedToCreateAgent: "فشل في إنشاء الوكيل",
|
||||
noHostSelected: "لم يتم تحديد مضيف",
|
||||
initialPromptRequired: "مطلوب موجه الأولي",
|
||||
@@ -2436,6 +2435,9 @@ export const ar: TranslationResources = {
|
||||
archiveFinishedRetry: "إعادة المحاولة ({{failed}}/{{total}})",
|
||||
},
|
||||
panels: {
|
||||
renderError: {
|
||||
title: "تعذّر عرض هذه اللوحة",
|
||||
},
|
||||
draft: {
|
||||
newAgent: "وكيل جديد",
|
||||
creatingAgent: "وكيل الخلق",
|
||||
|
||||
@@ -218,7 +218,6 @@ export const en = {
|
||||
errors: {
|
||||
removePluginCommandAttachments: "Remove attachments to run /{{command}}.",
|
||||
failedToSend: "Failed to send message",
|
||||
sendConnectionLost: "Connection lost. Paseo could not confirm that your message was sent.",
|
||||
failedToCreateAgent: "Failed to create agent",
|
||||
noHostSelected: "No host selected",
|
||||
initialPromptRequired: "Initial prompt is required",
|
||||
@@ -2468,6 +2467,9 @@ export const en = {
|
||||
archiveFinishedRetry: "Retry ({{failed}}/{{total}})",
|
||||
},
|
||||
panels: {
|
||||
renderError: {
|
||||
title: "Unable to show this panel",
|
||||
},
|
||||
draft: {
|
||||
newAgent: "New Agent",
|
||||
creatingAgent: "Creating agent",
|
||||
|
||||
@@ -221,8 +221,6 @@ export const es: TranslationResources = {
|
||||
errors: {
|
||||
removePluginCommandAttachments: "Quita los archivos adjuntos para ejecutar /{{command}}.",
|
||||
failedToSend: "No se pudo enviar el mensaje",
|
||||
sendConnectionLost:
|
||||
"Se perdió la conexión. Paseo no pudo confirmar que se enviara tu mensaje.",
|
||||
failedToCreateAgent: "No se pudo crear el agente",
|
||||
noHostSelected: "Ningún anfitrión seleccionado",
|
||||
initialPromptRequired: "Se requiere aviso inicial",
|
||||
@@ -2497,6 +2495,9 @@ export const es: TranslationResources = {
|
||||
archiveFinishedRetry: "Reintentar ({{failed}}/{{total}})",
|
||||
},
|
||||
panels: {
|
||||
renderError: {
|
||||
title: "No se puede mostrar este panel",
|
||||
},
|
||||
draft: {
|
||||
newAgent: "Nuevo agente",
|
||||
creatingAgent: "Agente creador",
|
||||
|
||||
@@ -222,8 +222,6 @@ export const fr: TranslationResources = {
|
||||
errors: {
|
||||
removePluginCommandAttachments: "Retirez les pièces jointes pour exécuter /{{command}}.",
|
||||
failedToSend: "Impossible d’envoyer le message",
|
||||
sendConnectionLost:
|
||||
"La connexion a été interrompue. Paseo n’a pas pu confirmer l’envoi de votre message.",
|
||||
failedToCreateAgent: "Impossible de créer l’agent",
|
||||
noHostSelected: "Aucun hôte sélectionné",
|
||||
initialPromptRequired: "Un prompt initial est requis",
|
||||
@@ -2493,6 +2491,9 @@ export const fr: TranslationResources = {
|
||||
archiveFinishedRetry: "Réessayer ({{failed}}/{{total}})",
|
||||
},
|
||||
panels: {
|
||||
renderError: {
|
||||
title: "Impossible d'afficher ce panneau",
|
||||
},
|
||||
draft: {
|
||||
newAgent: "Nouvel agent",
|
||||
creatingAgent: "Création de l’agent",
|
||||
|
||||
@@ -221,8 +221,6 @@ export const ja: TranslationResources = {
|
||||
errors: {
|
||||
removePluginCommandAttachments: "/{{command}} を実行するには添付ファイルを削除してください。",
|
||||
failedToSend: "メッセージの送信に失敗しました",
|
||||
sendConnectionLost:
|
||||
"接続が切断されました。Paseo はメッセージが送信されたことを確認できませんでした。",
|
||||
failedToCreateAgent: "エージェントの作成に失敗しました",
|
||||
noHostSelected: "ホストが選択されていません",
|
||||
initialPromptRequired: "初期プロンプトが必要です",
|
||||
@@ -2463,6 +2461,9 @@ export const ja: TranslationResources = {
|
||||
archiveFinishedRetry: "再試行 ({{failed}}/{{total}})",
|
||||
},
|
||||
panels: {
|
||||
renderError: {
|
||||
title: "このパネルを表示できません",
|
||||
},
|
||||
draft: {
|
||||
newAgent: "新しいエージェント",
|
||||
creatingAgent: "エージェントを作成中",
|
||||
|
||||
@@ -220,7 +220,6 @@ export const ko: TranslationResources = {
|
||||
errors: {
|
||||
removePluginCommandAttachments: "/{{command}} 명령을 실행하려면 첨부 파일을 제거하세요.",
|
||||
failedToSend: "메시지를 보내지 못했습니다",
|
||||
sendConnectionLost: "연결이 끊겼습니다. Paseo에서 메시지가 전송되었는지 확인하지 못했습니다.",
|
||||
failedToCreateAgent: "에이전트를 생성하지 못했습니다",
|
||||
noHostSelected: "선택된 호스트가 없습니다",
|
||||
initialPromptRequired: "초기 프롬프트가 필요합니다",
|
||||
@@ -2453,6 +2452,9 @@ export const ko: TranslationResources = {
|
||||
archiveFinishedRetry: "다시 시도 ({{failed}}/{{total}})",
|
||||
},
|
||||
panels: {
|
||||
renderError: {
|
||||
title: "이 패널을 표시할 수 없습니다",
|
||||
},
|
||||
draft: {
|
||||
newAgent: "새 에이전트",
|
||||
creatingAgent: "에이전트 생성 중",
|
||||
|
||||
@@ -221,8 +221,6 @@ export const ptBR: TranslationResources = {
|
||||
errors: {
|
||||
removePluginCommandAttachments: "Remova os anexos para executar /{{command}}.",
|
||||
failedToSend: "Falha ao enviar mensagem",
|
||||
sendConnectionLost:
|
||||
"A conexão foi perdida. O Paseo não conseguiu confirmar o envio da sua mensagem.",
|
||||
failedToCreateAgent: "Falha ao criar agente",
|
||||
noHostSelected: "Nenhum host selecionado",
|
||||
initialPromptRequired: "O prompt inicial é obrigatório",
|
||||
@@ -2479,6 +2477,9 @@ export const ptBR: TranslationResources = {
|
||||
archiveFinishedRetry: "Tentar novamente ({{failed}}/{{total}})",
|
||||
},
|
||||
panels: {
|
||||
renderError: {
|
||||
title: "Não foi possível exibir este painel",
|
||||
},
|
||||
draft: {
|
||||
newAgent: "Novo Agente",
|
||||
creatingAgent: "Criando agente",
|
||||
|
||||
@@ -221,7 +221,6 @@ export const ru: TranslationResources = {
|
||||
errors: {
|
||||
removePluginCommandAttachments: "Чтобы выполнить /{{command}}, удалите вложения.",
|
||||
failedToSend: "Не удалось отправить сообщение",
|
||||
sendConnectionLost: "Соединение прервано. Paseo не удалось подтвердить отправку сообщения.",
|
||||
failedToCreateAgent: "Не удалось создать агента.",
|
||||
noHostSelected: "Хост не выбран",
|
||||
initialPromptRequired: "Необходим инициализирующий промпт",
|
||||
@@ -2478,6 +2477,9 @@ export const ru: TranslationResources = {
|
||||
archiveFinishedRetry: "Повторить ({{failed}}/{{total}})",
|
||||
},
|
||||
panels: {
|
||||
renderError: {
|
||||
title: "Не удалось показать эту панель",
|
||||
},
|
||||
draft: {
|
||||
newAgent: "Новый агент",
|
||||
creatingAgent: "Создание агента",
|
||||
|
||||
@@ -220,7 +220,6 @@ export const zhCN: TranslationResources = {
|
||||
errors: {
|
||||
removePluginCommandAttachments: "请先移除附件,再运行 /{{command}}。",
|
||||
failedToSend: "发送消息失败",
|
||||
sendConnectionLost: "连接已断开。Paseo 无法确认消息是否已发送。",
|
||||
failedToCreateAgent: "创建 Agent 失败",
|
||||
noHostSelected: "未选择 Host",
|
||||
initialPromptRequired: "初始 prompt 必填",
|
||||
@@ -2409,6 +2408,9 @@ export const zhCN: TranslationResources = {
|
||||
archiveFinishedRetry: "重试 ({{failed}}/{{total}})",
|
||||
},
|
||||
panels: {
|
||||
renderError: {
|
||||
title: "无法显示此面板",
|
||||
},
|
||||
draft: {
|
||||
newAgent: "新建 Agent",
|
||||
creatingAgent: "正在创建 Agent",
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createHardwareKeyboardPresence } from "./internal/hardware-presence";
|
||||
import * as webConventions from "./internal/conventions.web";
|
||||
import { createWebHardwareKeyboardPresence } from "./internal/presence.web";
|
||||
import { buildEffectiveBindings } from "./keyboard-shortcuts";
|
||||
import { createKeyboardPipeline } from "./internal/pipeline";
|
||||
import { createOverlayRegistry } from "./internal/overlays";
|
||||
@@ -65,4 +67,39 @@ describe("hardware keyboard availability", () => {
|
||||
expect(actions).toEqual(["command-center.toggle"]);
|
||||
pipeline.dispose();
|
||||
});
|
||||
|
||||
it("answers keyboard presence and conventions per target", async () => {
|
||||
const nativeConventions = (await import(
|
||||
new URL("./internal/conventions.ts", import.meta.url).href
|
||||
)) as typeof webConventions & { usesDesktopBindings: boolean };
|
||||
const { hardwareKeyboardPresence: nativePresence } = (await import(
|
||||
new URL("./internal/presence.ts", import.meta.url).href
|
||||
)) as { hardwareKeyboardPresence: { getSnapshot(): boolean } };
|
||||
|
||||
expect(nativePresence.getSnapshot()).toBe(false);
|
||||
expect(
|
||||
createWebHardwareKeyboardPresence({ matches: true } as MediaQueryList, null).getSnapshot(),
|
||||
).toBe(true);
|
||||
expect(
|
||||
createWebHardwareKeyboardPresence({ matches: false } as MediaQueryList, null).getSnapshot(),
|
||||
).toBe(false);
|
||||
|
||||
expect({
|
||||
usesDesktopBindings: nativeConventions.usesDesktopBindings,
|
||||
supportsConfigurableComposerSendKeys: nativeConventions.supportsConfigurableComposerSendKeys,
|
||||
hasSoftwareKeyboard: nativeConventions.hasSoftwareKeyboard,
|
||||
}).toEqual({
|
||||
usesDesktopBindings: true,
|
||||
supportsConfigurableComposerSendKeys: false,
|
||||
hasSoftwareKeyboard: true,
|
||||
});
|
||||
|
||||
expect({
|
||||
supportsConfigurableComposerSendKeys: webConventions.supportsConfigurableComposerSendKeys,
|
||||
hasSoftwareKeyboard: webConventions.hasSoftwareKeyboard,
|
||||
}).toEqual({
|
||||
supportsConfigurableComposerSendKeys: true,
|
||||
hasSoftwareKeyboard: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -11,7 +11,11 @@ export { hasFocusedTextInput, registerFocusedTextInput } from "./internal/focuse
|
||||
export { useKeyboardFocusSurface } from "./internal/use-focus-surface";
|
||||
export { subscribeHardwareKeyboard } from "./internal/sources/hardware";
|
||||
export type { HardwareKeyboardEvent } from "./internal/sources/hardware";
|
||||
export { usesDesktopBindings, supportsConfigurableComposerSendKeys } from "./internal/conventions";
|
||||
export {
|
||||
hasSoftwareKeyboard,
|
||||
usesDesktopBindings,
|
||||
supportsConfigurableComposerSendKeys,
|
||||
} from "./internal/conventions";
|
||||
export type { BrowserKeyboardPolicy } from "./internal/sources/electron-browser";
|
||||
export { useHardwareKeyboardPresent } from "./availability";
|
||||
export { readPressModifiers } from "./internal/press-modifiers";
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
export const usesDesktopBindings = true;
|
||||
// Native composer Return retains its existing submit path in this feature.
|
||||
export const supportsConfigurableComposerSendKeys = false;
|
||||
export const hasSoftwareKeyboard = true;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isElectronRuntime } from "@/desktop/host";
|
||||
export const usesDesktopBindings = isElectronRuntime();
|
||||
export const supportsConfigurableComposerSendKeys = true;
|
||||
export const hasSoftwareKeyboard = false;
|
||||
|
||||
@@ -28,7 +28,7 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { scheduleOnRN, scheduleOnUI } from "react-native-worklets";
|
||||
import { resolveDesktopSidebarWidth } from "@/components/desktop-sidebar-layout";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { isNative } from "@/constants/platform";
|
||||
import { hasSoftwareKeyboard } from "@/keyboard";
|
||||
import {
|
||||
usePanelStore,
|
||||
type MobilePanelSelection,
|
||||
@@ -138,7 +138,7 @@ export function MobilePanelsProvider({ children }: { children: ReactNode }) {
|
||||
if (selection.revision !== revision || selection.target !== panel) {
|
||||
return;
|
||||
}
|
||||
if (isNative && panel !== "agent") {
|
||||
if (hasSoftwareKeyboard && panel !== "agent") {
|
||||
Keyboard.dismiss();
|
||||
}
|
||||
settledPanel.setState(panel);
|
||||
|
||||
@@ -57,7 +57,8 @@ import {
|
||||
import type { WorkspaceComposerAttachment } from "@/attachments/types";
|
||||
import { useWorkspaceAttachmentScopeKey } from "@/attachments/workspace-attachments-store";
|
||||
import { COMPACT_CONTENT_WIDTH, useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { isNative, isWeb } from "@/constants/platform";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { hasSoftwareKeyboard } from "@/keyboard";
|
||||
import { useAgentAttentionClear } from "@/hooks/use-agent-attention-clear";
|
||||
import { useAgentInputDraft, type AgentInputDraft } from "@/composer/draft/input-draft";
|
||||
import {
|
||||
@@ -1883,7 +1884,7 @@ function AgentComposer({
|
||||
agentId={agentId}
|
||||
serverId={serverId}
|
||||
workspaceId={workspaceId}
|
||||
blurOnSubmit={isNative}
|
||||
blurOnSubmit={hasSoftwareKeyboard}
|
||||
isPaneFocused={isPaneFocused}
|
||||
textSource={agentInputDraft.textSource}
|
||||
onChangeText={agentInputDraft.editText}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import React, { Component, type ErrorInfo, type ReactNode } from "react";
|
||||
import type { ReactNode } from "react";
|
||||
import { Text } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { RenderErrorBoundary } from "@/components/render-error-boundary";
|
||||
|
||||
interface SurfaceErrorBoundaryProps {
|
||||
children: ReactNode;
|
||||
@@ -10,42 +11,30 @@ interface SurfaceErrorBoundaryProps {
|
||||
renderError?(error: string): ReactNode;
|
||||
}
|
||||
|
||||
interface SurfaceErrorBoundaryState {
|
||||
error: string | null;
|
||||
export function SurfaceErrorBoundary({
|
||||
children,
|
||||
installation,
|
||||
resetKey,
|
||||
Surface,
|
||||
renderError,
|
||||
}: SurfaceErrorBoundaryProps) {
|
||||
return (
|
||||
<RenderErrorBoundary
|
||||
resetKeys={[installation, resetKey, Surface]}
|
||||
onError={warnSurfaceRenderFailed}
|
||||
renderError={renderError ?? renderPluginFailed}
|
||||
>
|
||||
{children}
|
||||
</RenderErrorBoundary>
|
||||
);
|
||||
}
|
||||
|
||||
export class SurfaceErrorBoundary extends Component<
|
||||
SurfaceErrorBoundaryProps,
|
||||
SurfaceErrorBoundaryState
|
||||
> {
|
||||
state: SurfaceErrorBoundaryState = { error: null };
|
||||
function renderPluginFailed(error: string) {
|
||||
return <Text style={styles.errorText}>Plugin failed: {error}</Text>;
|
||||
}
|
||||
|
||||
static getDerivedStateFromError(error: unknown): SurfaceErrorBoundaryState {
|
||||
return { error: error instanceof Error ? error.message : String(error) };
|
||||
}
|
||||
|
||||
componentDidCatch(error: Error, info: ErrorInfo): void {
|
||||
console.warn("[Plugins] Surface render failed", error, info.componentStack);
|
||||
}
|
||||
|
||||
componentDidUpdate(previous: SurfaceErrorBoundaryProps): void {
|
||||
if (
|
||||
this.state.error &&
|
||||
(previous.installation !== this.props.installation ||
|
||||
previous.resetKey !== this.props.resetKey ||
|
||||
previous.Surface !== this.props.Surface)
|
||||
) {
|
||||
this.setState({ error: null });
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
if (this.state.error) {
|
||||
if (this.props.renderError) return this.props.renderError(this.state.error);
|
||||
return <Text style={styles.errorText}>Plugin failed: {this.state.error}</Text>;
|
||||
}
|
||||
return this.props.children;
|
||||
}
|
||||
function warnSurfaceRenderFailed(error: unknown, componentStack: string | null | undefined): void {
|
||||
console.warn("[Plugins] Surface render failed", error, componentStack);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
|
||||
@@ -4,7 +4,6 @@ import {
|
||||
getNextWorkspaceDeckExpirationDelay,
|
||||
orderWorkspaceSelectionsForStableRender,
|
||||
reconcileRetainedWorkspaceSelections,
|
||||
resolveWorkspaceDeckRetentionLimit,
|
||||
resolveWorkspaceDeckEntries,
|
||||
shouldKeepWorkspaceDeckEntryMounted,
|
||||
WORKSPACE_DECK_INACTIVE_TTL_MS,
|
||||
@@ -30,21 +29,26 @@ function retainedWorkspaceIds(
|
||||
}
|
||||
|
||||
describe("reconcileRetainedWorkspaceSelections", () => {
|
||||
it("retains only the active workspace on native", () => {
|
||||
it("retains only the active workspace when limited to one mounted workspace", () => {
|
||||
const entries = reconcileRetainedWorkspaceSelections({
|
||||
currentEntries: [retained("A", null)],
|
||||
activeSelection: workspace("B"),
|
||||
now: 2,
|
||||
maxMountedWorkspaces: resolveWorkspaceDeckRetentionLimit({ isNative: true }),
|
||||
maxMountedWorkspaces: 1,
|
||||
});
|
||||
|
||||
expect(retainedWorkspaceIds(entries)).toEqual(["B"]);
|
||||
});
|
||||
|
||||
it("retains the desktop deck limit on web", () => {
|
||||
expect(resolveWorkspaceDeckRetentionLimit({ isNative: false })).toBe(
|
||||
WORKSPACE_DECK_MAX_MOUNTED_WORKSPACES,
|
||||
);
|
||||
it("retains up to the configured limit when higher", () => {
|
||||
const entries = reconcileRetainedWorkspaceSelections({
|
||||
currentEntries: [retained("A", null)],
|
||||
activeSelection: workspace("B"),
|
||||
now: 2,
|
||||
maxMountedWorkspaces: WORKSPACE_DECK_MAX_MOUNTED_WORKSPACES,
|
||||
});
|
||||
|
||||
expect(retainedWorkspaceIds(entries)).toEqual(["B", "A"]);
|
||||
});
|
||||
|
||||
it("retains inactive workspaces for ten minutes across app-wide routes", () => {
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { resolveResourceBudgets } from "../../constants/resource-budget-tables";
|
||||
import type { ActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store";
|
||||
|
||||
export const WORKSPACE_DECK_MAX_MOUNTED_WORKSPACES = 10;
|
||||
// Relative import: Playwright loads this file in plain Node, without the `@/` alias or react-native.
|
||||
export const WORKSPACE_DECK_MAX_MOUNTED_WORKSPACES = resolveResourceBudgets({
|
||||
isNative: false,
|
||||
}).workspaceDeckRetentionLimit;
|
||||
export const WORKSPACE_DECK_INACTIVE_TTL_MS = 10 * 60 * 1000;
|
||||
|
||||
export interface RetainedWorkspaceSelection {
|
||||
@@ -8,10 +12,6 @@ export interface RetainedWorkspaceSelection {
|
||||
inactiveSince: number | null;
|
||||
}
|
||||
|
||||
export function resolveWorkspaceDeckRetentionLimit(input: { isNative: boolean }): number {
|
||||
return input.isNative ? 1 : WORKSPACE_DECK_MAX_MOUNTED_WORKSPACES;
|
||||
}
|
||||
|
||||
interface ReconcileRetainedWorkspaceSelectionsInput {
|
||||
currentEntries: RetainedWorkspaceSelection[];
|
||||
activeSelection: ActiveWorkspaceSelection | null;
|
||||
|
||||
@@ -12,7 +12,7 @@ import React, {
|
||||
type Dispatch,
|
||||
type SetStateAction,
|
||||
} from "react";
|
||||
import { Pressable, Text, View, type LayoutChangeEvent, type ScrollView } from "react-native";
|
||||
import { Pressable, Text, View, type LayoutChangeEvent } from "react-native";
|
||||
import { useFilePanelOpenWithMenu } from "@/file-panels";
|
||||
import { useFileTabMenu } from "@/screens/workspace/use-file-tab-menu";
|
||||
import {
|
||||
@@ -39,6 +39,7 @@ import type {
|
||||
DraggableRenderItemInfo,
|
||||
} from "@/components/draggable-list.types";
|
||||
import { isNative, isWeb } from "@/constants/platform";
|
||||
import { useRevealsWithoutHover } from "@/hooks/hover-reveal";
|
||||
import {
|
||||
ContextMenu,
|
||||
ContextMenuContent,
|
||||
@@ -55,6 +56,7 @@ import type { ShortcutKey } from "@/utils/format-shortcut";
|
||||
import { Shortcut } from "@/components/ui/shortcut";
|
||||
import { useWorkspaceTabLayout } from "@/screens/workspace/use-workspace-tab-layout";
|
||||
import { retainWorkspaceTabMeasuredWidth } from "@/screens/workspace/workspace-tab-layout";
|
||||
import { useWorkspaceTabsWheelScroll } from "@/screens/workspace/workspace-tabs-wheel-scroll";
|
||||
import {
|
||||
WorkspaceTabPresentationResolver,
|
||||
WorkspaceTabIcon,
|
||||
@@ -795,7 +797,7 @@ function TabChip({
|
||||
const middleClickRef = useMiddleClickClose(
|
||||
useCallback(() => void onCloseTab(tab.tabId), [onCloseTab, tab.tabId]),
|
||||
);
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
const revealsWithoutHover = useRevealsWithoutHover();
|
||||
const [hovered, setHovered] = useState(false);
|
||||
// An active tab in a pane that does not have focus stays legible but quiet: it keeps the fill of
|
||||
// a hovered chip and the muted label, so only one chip in the window reads as the live one.
|
||||
@@ -808,7 +810,7 @@ function TabChip({
|
||||
isActiveFocused,
|
||||
isFilled,
|
||||
});
|
||||
const showCloseControl = showCloseButton && (isHovered || isNative || isCompact || isClosingTab);
|
||||
const showCloseControl = showCloseButton && (isHovered || revealsWithoutHover || isClosingTab);
|
||||
const closeButtonDragBlockers = isWeb
|
||||
? ({
|
||||
onPointerDown: (event: { stopPropagation?: () => void }) => {
|
||||
@@ -1130,7 +1132,6 @@ function ResolvedWorkspaceDesktopTabsRow({
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
const newTabKeys = useShortcutKeys("workspace-tab-new");
|
||||
const [tabsContainerWidth, setTabsContainerWidth] = useState<number>(0);
|
||||
const tabsScrollRef = useRef<ScrollView>(null);
|
||||
const [exitFocusModeWidth, setExitFocusModeWidth] = useState<number>(0);
|
||||
const tabScrollBoundary = useHorizontalScrollBoundary();
|
||||
const measurementCache = useContext(TabMeasurementCache);
|
||||
@@ -1298,13 +1299,17 @@ function ResolvedWorkspaceDesktopTabsRow({
|
||||
metrics: layoutMetrics,
|
||||
compact: isCompact,
|
||||
});
|
||||
// The strip hides its scrollbar and relies on the edge shades, so a plain mouse wheel
|
||||
// has to pan it; otherwise tabs past the viewport are unreachable without a trackpad.
|
||||
const tabsScrollRef = useWorkspaceTabsWheelScroll(layout.requiresHorizontalScrollFallback);
|
||||
|
||||
// A scroll view keeps its offset when its content shrinks under the viewport, so a row that
|
||||
// stops scrolling would leave the tabs it had panned past out of view with no way back.
|
||||
useEffect(() => {
|
||||
if (!layout.requiresHorizontalScrollFallback) {
|
||||
tabsScrollRef.current?.scrollTo({ x: 0, animated: false });
|
||||
}
|
||||
}, [layout.requiresHorizontalScrollFallback]);
|
||||
}, [layout.requiresHorizontalScrollFallback, tabsScrollRef]);
|
||||
|
||||
const handleDragEnd = useCallback(
|
||||
(nextTabs: ResolvedWorkspaceDesktopTabRowItem[]) => {
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
import { act } from "@testing-library/react";
|
||||
import React from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { Text } from "react-native";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { definePanel, registerPanel } from "@/panels/panel-registry";
|
||||
import {
|
||||
buildWorkspacePaneContentModel,
|
||||
WorkspacePaneContent,
|
||||
} from "@/screens/workspace/workspace-pane-content";
|
||||
import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-types";
|
||||
|
||||
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
|
||||
|
||||
let panelFails = false;
|
||||
let panelMounts = 0;
|
||||
|
||||
function TestPanel() {
|
||||
React.useEffect(() => {
|
||||
panelMounts += 1;
|
||||
}, []);
|
||||
if (panelFails) throw new Error("Panel exploded");
|
||||
return <Text>Panel content</Text>;
|
||||
}
|
||||
|
||||
// The workspace screen registers the real panels; this one stands in for each kind the tests open.
|
||||
for (const kind of ["agent", "draft"] as const) {
|
||||
registerPanel(
|
||||
definePanel(kind, {
|
||||
component: TestPanel,
|
||||
useDescriptor: () => {
|
||||
throw new Error("The test panel has no descriptor");
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const draftTab: WorkspaceTabDescriptor = {
|
||||
key: "tab-a",
|
||||
tabId: "tab-a",
|
||||
kind: "draft",
|
||||
target: { kind: "draft", draftId: "draft-a" },
|
||||
};
|
||||
const agentTab: WorkspaceTabDescriptor = {
|
||||
key: "tab-a",
|
||||
tabId: "tab-a",
|
||||
kind: "agent",
|
||||
target: { kind: "agent", agentId: "agent-a" },
|
||||
};
|
||||
|
||||
function buildContent(tab: WorkspaceTabDescriptor) {
|
||||
return buildWorkspacePaneContentModel({
|
||||
tab,
|
||||
normalizedServerId: "server-a",
|
||||
normalizedWorkspaceId: "workspace-a",
|
||||
host: "main",
|
||||
onOpenTab: vi.fn(),
|
||||
onOpenPreferredTarget: vi.fn(),
|
||||
onOpenTargetToSide: vi.fn(),
|
||||
onCloseCurrentTab: vi.fn(),
|
||||
onRetargetCurrentTab: vi.fn(),
|
||||
onSetCurrentTabState: vi.fn(),
|
||||
onOpenWorkspaceFile: vi.fn(),
|
||||
onOpenImportSheet: vi.fn(),
|
||||
});
|
||||
}
|
||||
|
||||
function byTestId(container: HTMLElement, testID: string): HTMLElement | null {
|
||||
return container.querySelector(`[data-testid="${testID}"]`);
|
||||
}
|
||||
|
||||
// Every host (explorer, split pane, compact center, sheet) mounts panels through
|
||||
// WorkspacePaneContent, so its boundary keeps a panel's render error from reaching the root screen.
|
||||
describe("WorkspacePaneContent when the panel throws while rendering", () => {
|
||||
let root: Root;
|
||||
let container: HTMLDivElement;
|
||||
|
||||
function show(tab: WorkspaceTabDescriptor) {
|
||||
act(() =>
|
||||
root.render(
|
||||
<>
|
||||
<Text>Sibling</Text>
|
||||
<WorkspacePaneContent content={buildContent(tab)} isPaneFocused isWorkspaceFocused />
|
||||
</>,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
panelFails = false;
|
||||
panelMounts = 0;
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
});
|
||||
|
||||
it("shows the error in place of the panel and retries on demand", () => {
|
||||
panelFails = true;
|
||||
show(agentTab);
|
||||
|
||||
expect(container.textContent).toContain("Sibling");
|
||||
expect(byTestId(container, "panel-render-error")?.textContent).toContain("Panel exploded");
|
||||
|
||||
panelFails = false;
|
||||
act(() => byTestId(container, "panel-render-error-retry")?.click());
|
||||
|
||||
expect(byTestId(container, "panel-render-error")).toBeNull();
|
||||
expect(container.textContent).toContain("Panel content");
|
||||
expect(container.textContent).toContain("Sibling");
|
||||
});
|
||||
|
||||
it("clears the error when the tab is retargeted", () => {
|
||||
panelFails = true;
|
||||
show(draftTab);
|
||||
expect(byTestId(container, "panel-render-error")).not.toBeNull();
|
||||
|
||||
panelFails = false;
|
||||
show(agentTab);
|
||||
|
||||
expect(byTestId(container, "panel-render-error")).toBeNull();
|
||||
expect(container.textContent).toContain("Panel content");
|
||||
});
|
||||
|
||||
it("keeps a healthy panel mounted when its tab is retargeted in place", () => {
|
||||
show(draftTab);
|
||||
show(agentTab);
|
||||
|
||||
expect(container.textContent).toContain("Panel content");
|
||||
expect(panelMounts).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,12 @@
|
||||
import { ComposerEditingScope } from "@/composer/editing-session";
|
||||
import React, { useMemo, type ComponentType } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { View } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import invariant from "tiny-invariant";
|
||||
import { RenderErrorBoundary } from "@/components/render-error-boundary";
|
||||
import { Alert } from "@/components/ui/alert";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
createPaneFocusContextValue,
|
||||
PaneFocusProvider,
|
||||
@@ -87,6 +93,31 @@ export interface WorkspacePaneContentProps {
|
||||
onFocusPane?: () => void;
|
||||
}
|
||||
|
||||
function logPanelRenderError(error: unknown, componentStack: string | null | undefined): void {
|
||||
console.error("[WorkspacePanel] Render failed", error, componentStack);
|
||||
}
|
||||
|
||||
function renderPanelError(error: string, retry: () => void) {
|
||||
return <PanelRenderError error={error} onRetry={retry} />;
|
||||
}
|
||||
|
||||
function PanelRenderError({ error, onRetry }: { error: string; onRetry: () => void }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<View style={styles.renderError} testID="panel-render-error">
|
||||
<Alert variant="error" title={t("panels.renderError.title")} description={error}>
|
||||
<Button variant="outline" size="sm" onPress={onRetry} testID="panel-render-error-retry">
|
||||
{t("common.actions.retry")}
|
||||
</Button>
|
||||
</Alert>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mounts one panel with its pane context. A render error stays inside the panel, so every host
|
||||
* (explorer, split pane, compact center, sheet) keeps the rest of the app alive.
|
||||
*/
|
||||
export function WorkspacePaneContent({
|
||||
content,
|
||||
isWorkspaceFocused,
|
||||
@@ -159,10 +190,22 @@ export function WorkspacePaneContent({
|
||||
tabId={paneContextValue.tabId}
|
||||
targetKey={JSON.stringify(paneContextValue.target)}
|
||||
>
|
||||
<Component key={key} />
|
||||
<RenderErrorBoundary
|
||||
resetKeys={[key, paneContextValue.target, paneContextValue.state]}
|
||||
onError={logPanelRenderError}
|
||||
renderError={renderPanelError}
|
||||
>
|
||||
<Component key={key} />
|
||||
</RenderErrorBoundary>
|
||||
</ComposerEditingScope>
|
||||
</PaneFocusProvider>
|
||||
</PaneProvider>
|
||||
</RenderProfile>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
renderError: {
|
||||
padding: theme.spacing[4],
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
// Wheel events report `deltaMode` in DOM units: pixels, lines, or pages. Only pixel
|
||||
// deltas are usable as-is; the other two need the axis size to become a scroll offset.
|
||||
const WHEEL_DELTA_MODE_LINE = 1;
|
||||
const WHEEL_DELTA_MODE_PAGE = 2;
|
||||
const WHEEL_LINE_HEIGHT_PX = 16;
|
||||
|
||||
export interface WorkspaceTabsWheelScrollInput {
|
||||
scrollLeft: number;
|
||||
scrollWidth: number;
|
||||
clientWidth: number;
|
||||
deltaX: number;
|
||||
deltaY: number;
|
||||
deltaMode: number;
|
||||
shiftKey: boolean;
|
||||
ctrlKey: boolean;
|
||||
}
|
||||
|
||||
export interface WorkspaceTabsWheelScrollResult {
|
||||
scrollLeft: number;
|
||||
handled: boolean;
|
||||
}
|
||||
|
||||
export interface WorkspaceTabsScrollElement {
|
||||
scrollLeft: number;
|
||||
scrollWidth: number;
|
||||
clientWidth: number;
|
||||
addEventListener: (
|
||||
type: string,
|
||||
listener: (event: unknown) => void,
|
||||
options?: { passive?: boolean },
|
||||
) => void;
|
||||
removeEventListener: (type: string, listener: (event: unknown) => void) => void;
|
||||
}
|
||||
|
||||
function clamp(value: number, min: number, max: number): number {
|
||||
if (value < min) {
|
||||
return min;
|
||||
}
|
||||
if (value > max) {
|
||||
return max;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a wheel event on the workspace tab strip into a horizontal scroll offset.
|
||||
*
|
||||
* `handled: false` leaves the event to the browser: there is nothing to scroll, the
|
||||
* gesture already carries horizontal intent (`deltaX` trackpad swipe or shift+wheel),
|
||||
* or the strip is already pinned at the requested edge.
|
||||
*/
|
||||
export function resolveWorkspaceTabsWheelScroll(
|
||||
input: WorkspaceTabsWheelScrollInput,
|
||||
): WorkspaceTabsWheelScrollResult {
|
||||
const maxScrollLeft = Math.max(0, input.scrollWidth - input.clientWidth);
|
||||
const currentScrollLeft = clamp(input.scrollLeft, 0, maxScrollLeft);
|
||||
if (maxScrollLeft <= 0) {
|
||||
return { scrollLeft: currentScrollLeft, handled: false };
|
||||
}
|
||||
if (input.shiftKey || input.ctrlKey || input.deltaX !== 0) {
|
||||
return { scrollLeft: currentScrollLeft, handled: false };
|
||||
}
|
||||
let delta = input.deltaY;
|
||||
if (input.deltaMode === WHEEL_DELTA_MODE_LINE) {
|
||||
delta = input.deltaY * WHEEL_LINE_HEIGHT_PX;
|
||||
} else if (input.deltaMode === WHEEL_DELTA_MODE_PAGE) {
|
||||
delta = input.deltaY * input.clientWidth;
|
||||
}
|
||||
if (delta === 0) {
|
||||
return { scrollLeft: currentScrollLeft, handled: false };
|
||||
}
|
||||
const nextScrollLeft = clamp(currentScrollLeft + delta, 0, maxScrollLeft);
|
||||
return { scrollLeft: nextScrollLeft, handled: nextScrollLeft !== currentScrollLeft };
|
||||
}
|
||||
|
||||
/**
|
||||
* A React Native Web ScrollView ref resolves to the ScrollView instance, whose
|
||||
* `getScrollableNode()` returns the overflowing element. A platform that hands back the
|
||||
* element itself (or a test double) is used as-is; anything without an `addEventListener`
|
||||
* is not a scrollable element and is ignored.
|
||||
*/
|
||||
export function resolveWorkspaceTabsScrollElement(
|
||||
handle: unknown,
|
||||
): WorkspaceTabsScrollElement | null {
|
||||
if (!handle || typeof handle !== "object") {
|
||||
return null;
|
||||
}
|
||||
const scrollableNode = (handle as { getScrollableNode?: () => unknown }).getScrollableNode;
|
||||
if (typeof scrollableNode === "function") {
|
||||
const node = scrollableNode.call(handle);
|
||||
return isScrollElement(node) ? (node as WorkspaceTabsScrollElement) : null;
|
||||
}
|
||||
return isScrollElement(handle) ? (handle as WorkspaceTabsScrollElement) : null;
|
||||
}
|
||||
|
||||
function isScrollElement(candidate: unknown): candidate is WorkspaceTabsScrollElement {
|
||||
return (
|
||||
Boolean(candidate) &&
|
||||
typeof candidate === "object" &&
|
||||
typeof (candidate as { addEventListener?: unknown }).addEventListener === "function" &&
|
||||
typeof (candidate as { removeEventListener?: unknown }).removeEventListener === "function"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import { act, renderHook } from "@testing-library/react";
|
||||
import type { ScrollView } from "react-native";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import * as nativeWheelScroll from "@/screens/workspace/workspace-tabs-wheel-scroll.native";
|
||||
import * as webWheelScroll from "@/screens/workspace/workspace-tabs-wheel-scroll.web";
|
||||
|
||||
const { useWorkspaceTabsWheelScroll } = webWheelScroll;
|
||||
|
||||
interface WheelHookProps {
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
function createScrollableStrip(): HTMLDivElement {
|
||||
const strip = document.createElement("div");
|
||||
strip.style.width = "800px";
|
||||
strip.style.height = "20px";
|
||||
strip.style.overflow = "scroll";
|
||||
const content = document.createElement("div");
|
||||
content.style.width = "1600px";
|
||||
content.style.height = "1px";
|
||||
strip.append(content);
|
||||
Object.defineProperties(strip, {
|
||||
clientWidth: { configurable: true, value: 800 },
|
||||
scrollWidth: { configurable: true, value: 1600 },
|
||||
});
|
||||
document.body.append(strip);
|
||||
return strip;
|
||||
}
|
||||
|
||||
function recordWheelListener(strip: HTMLDivElement): () => number {
|
||||
const originalAddEventListener = strip.addEventListener.bind(strip);
|
||||
const originalRemoveEventListener = strip.removeEventListener.bind(strip);
|
||||
let added = 0;
|
||||
let removed = 0;
|
||||
strip.addEventListener = ((
|
||||
type: string,
|
||||
listener: EventListenerOrEventListenerObject,
|
||||
options?: boolean | AddEventListenerOptions,
|
||||
) => {
|
||||
if (type === "wheel") added += 1;
|
||||
originalAddEventListener(type, listener, options);
|
||||
}) as typeof strip.addEventListener;
|
||||
strip.removeEventListener = ((
|
||||
type: string,
|
||||
listener: EventListenerOrEventListenerObject,
|
||||
options?: boolean | EventListenerOptions,
|
||||
) => {
|
||||
if (type === "wheel") removed += 1;
|
||||
originalRemoveEventListener(type, listener, options);
|
||||
}) as typeof strip.removeEventListener;
|
||||
return () => added - removed;
|
||||
}
|
||||
|
||||
async function attachStripToHook(
|
||||
strip: HTMLDivElement,
|
||||
enabled = true,
|
||||
refValue: unknown = strip,
|
||||
): Promise<{ rerender: (props: WheelHookProps) => void; unmount: () => void }> {
|
||||
const hook = renderHook(({ enabled: isEnabled }) => useWorkspaceTabsWheelScroll(isEnabled), {
|
||||
initialProps: { enabled: false },
|
||||
});
|
||||
(hook.result.current as { current: ScrollView | null }).current = refValue as ScrollView;
|
||||
await act(async () => {
|
||||
hook.rerender({ enabled });
|
||||
});
|
||||
expect(hook.result.current.current).toBe(refValue);
|
||||
return hook;
|
||||
}
|
||||
|
||||
function wheel(deltaY: number, options: Partial<WheelEventInit> = {}): WheelEvent {
|
||||
return new WheelEvent("wheel", { cancelable: true, deltaY, ...options });
|
||||
}
|
||||
|
||||
describe("useWorkspaceTabsWheelScroll", () => {
|
||||
it("exposes the hook as the platform module interface", () => {
|
||||
expect(Object.keys(webWheelScroll)).toEqual(["useWorkspaceTabsWheelScroll"]);
|
||||
expect(Object.keys(nativeWheelScroll)).toEqual(["useWorkspaceTabsWheelScroll"]);
|
||||
});
|
||||
|
||||
it("pans a vertical wheel and prevents the browser default", async () => {
|
||||
const strip = createScrollableStrip();
|
||||
const activeListeners = recordWheelListener(strip);
|
||||
const scrollViewHandle = { getScrollableNode: () => strip };
|
||||
const hook = await attachStripToHook(strip, true, scrollViewHandle);
|
||||
expect(activeListeners()).toBe(1);
|
||||
const event = wheel(120);
|
||||
|
||||
expect(strip.scrollWidth).toBe(1600);
|
||||
expect(strip.clientWidth).toBe(800);
|
||||
expect(event.deltaY).toBe(120);
|
||||
strip.dispatchEvent(event);
|
||||
|
||||
expect(strip.scrollLeft).toBe(120);
|
||||
expect(event.defaultPrevented).toBe(true);
|
||||
hook.unmount();
|
||||
expect(activeListeners()).toBe(0);
|
||||
strip.remove();
|
||||
});
|
||||
|
||||
it("keeps horizontal and modifier gestures with the browser", async () => {
|
||||
const strip = createScrollableStrip();
|
||||
const hook = await attachStripToHook(strip);
|
||||
const horizontal = wheel(120, { deltaX: 20 });
|
||||
const shifted = wheel(120, { shiftKey: true });
|
||||
const zoom = wheel(120, { ctrlKey: true });
|
||||
|
||||
strip.dispatchEvent(horizontal);
|
||||
strip.dispatchEvent(shifted);
|
||||
strip.dispatchEvent(zoom);
|
||||
|
||||
expect(strip.scrollLeft).toBe(0);
|
||||
expect(horizontal.defaultPrevented).toBe(false);
|
||||
expect(shifted.defaultPrevented).toBe(false);
|
||||
expect(zoom.defaultPrevented).toBe(false);
|
||||
hook.unmount();
|
||||
strip.remove();
|
||||
});
|
||||
|
||||
it("removes the listener when disabled or unmounted", async () => {
|
||||
const strip = createScrollableStrip();
|
||||
const hook = await attachStripToHook(strip);
|
||||
|
||||
await act(async () => {
|
||||
hook.rerender({ enabled: false });
|
||||
});
|
||||
strip.dispatchEvent(wheel(120));
|
||||
expect(strip.scrollLeft).toBe(0);
|
||||
|
||||
hook.unmount();
|
||||
strip.dispatchEvent(wheel(120));
|
||||
expect(strip.scrollLeft).toBe(0);
|
||||
strip.remove();
|
||||
});
|
||||
|
||||
it("normalizes line and page wheel deltas through the public hook", async () => {
|
||||
const strip = createScrollableStrip();
|
||||
const hook = await attachStripToHook(strip);
|
||||
|
||||
strip.dispatchEvent(wheel(3, { deltaMode: 1 }));
|
||||
expect(strip.scrollLeft).toBe(48);
|
||||
strip.dispatchEvent(wheel(1, { deltaMode: 2 }));
|
||||
expect(strip.scrollLeft).toBe(800);
|
||||
|
||||
hook.unmount();
|
||||
strip.remove();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
import { useRef, type RefObject } from "react";
|
||||
import type { ScrollView } from "react-native";
|
||||
|
||||
/** Native tab strips already expose platform scrolling; no wheel listener is needed. */
|
||||
export function useWorkspaceTabsWheelScroll(_enabled: boolean): RefObject<ScrollView | null> {
|
||||
return useRef<ScrollView>(null);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import type { RefObject } from "react";
|
||||
import type { ScrollView } from "react-native";
|
||||
|
||||
// The platform files provide the runtime implementation; this declaration keeps the
|
||||
// extensionless import typed for TypeScript, whose resolver does not select .web/.native files.
|
||||
export declare function useWorkspaceTabsWheelScroll(enabled: boolean): RefObject<ScrollView | null>;
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user