mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-30 20:25:50 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d71ac161e8 | ||
|
|
81357c6e7b | ||
|
|
95cc11ab7b | ||
|
|
93c883a398 | ||
|
|
d5880784e2 | ||
|
|
5d4a1b4ed7 | ||
|
|
e350293d13 | ||
|
|
69563e111b | ||
|
|
8f696db2f2 | ||
|
|
c9ec9863ba | ||
|
|
24ceb52147 | ||
|
|
4c4b384c7f | ||
|
|
1a606451cd | ||
|
|
23934841f0 | ||
|
|
d2d4105366 | ||
|
|
37cb22dac8 | ||
|
|
397d1e14d6 | ||
|
|
d193e419e9 | ||
|
|
bd20e3fe98 | ||
|
|
39eaba6181 | ||
|
|
63ede58d7d |
@@ -58,6 +58,7 @@ At the start of non-trivial work, list `docs/` and skim anything relevant to the
|
||||
| [docs/timeline-sync.md](docs/timeline-sync.md) | Owned agent history, rewind retirements, live stream vs authoritative fetch, paged catch-up, client replica |
|
||||
| [docs/agent-stream-performance.md](docs/agent-stream-performance.md) | Assistant text pipeline — coalescing window, paced reveal, why arrival lumps are smoothed at render |
|
||||
| [docs/agent-stream-disclosure.md](docs/agent-stream-disclosure.md) | Expand/collapse in the chat timeline — hold contract, native anchor sequence, frame spacing, render-window cost |
|
||||
| [docs/running-indicators.md](docs/running-indicators.md) | Loader, status ring, tool-call shimmer — motion policy, compositor loops on web, native-driver clock, why not CSS keyframes |
|
||||
| [docs/markdown-renderer.md](docs/markdown-renderer.md) | Shared Markdown engine, the vendored library fork, native selection, links, images and library constraints |
|
||||
| [docs/native-text-selection.md](docs/native-text-selection.md) | Native diagram grouping, selection boundaries and leading inline image limitations |
|
||||
| [docs/file-observation.md](docs/file-observation.md) | Recursive watcher ownership, Linux constraints, teardown invariants, and Parcel comparison |
|
||||
|
||||
+7
-4
@@ -249,7 +249,8 @@ snapshot so a mixed edit can apply its live subset and still name the paths that
|
||||
listen: "127.0.0.1:6767",
|
||||
hostnames: true | string[], // legacy alias `allowedHosts` is migrated on load
|
||||
trustedProxies: true | string[], // defaults to ["loopback"]; Express proxy names/CIDRs
|
||||
mcp: { enabled: boolean, injectIntoAgents: boolean },
|
||||
tools: { enabled: boolean, groups: { orchestration, schedules, changeRequests, browser: boolean } },
|
||||
mcp: { enabled: boolean, injectIntoAgents: boolean }, // legacy, read only when `tools` is absent
|
||||
git: { maxProcessesPerSecond: number, maxProcessConcurrency: number },
|
||||
appendSystemPrompt: string, // appended to supported provider system/developer prompts
|
||||
terminalProfiles: TerminalProfile[], // named shell commands; omitted means DEFAULT_TERMINAL_PROFILES
|
||||
@@ -351,12 +352,14 @@ Each entry may include a Paseo-tool policy:
|
||||
Absent `paseoTools`, or absent fields within it, means Paseo tools are enabled and all tools are
|
||||
allowed. `enabled: false` disables the provider's Paseo catalog; `disabledTools` lists exact tool
|
||||
IDs to omit. The policy covers the core and browser catalog, not the voice-only `speak` tool.
|
||||
Browser tools also require `daemon.browserTools.enabled` and a connected browser host.
|
||||
Browser tools also require `daemon.tools.groups.browser` and a connected browser host.
|
||||
This policy controls the catalog presented to an agent. It is not an authorization boundary for
|
||||
agents that can access the host through a shell.
|
||||
|
||||
`daemon.mcp.injectIntoAgents` is the global override. When it is `false`, no provider receives
|
||||
Paseo tools; otherwise the provider policy applies. Provider and global policy are resolved when a
|
||||
`daemon.tools` is the global override. When `enabled` is `false`, no provider receives Paseo or
|
||||
plugin tools; otherwise each group in `daemon.tools.groups` and then the provider policy applies.
|
||||
When `daemon.tools` is absent, the daemon reads the legacy `daemon.mcp.injectIntoAgents` and
|
||||
`daemon.browserTools.enabled` fields. Provider and global policy are resolved when a
|
||||
session is created, resumed, imported, or reloaded, so configuration changes affect the next
|
||||
session rather than an already-running one.
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ The package keeps the npm tarball's layout, including its build output:
|
||||
|
||||
- Metro, Vitest and TypeScript load `lib/`, not `src/`. A JavaScript change edits `src/` and the matching `lib/module` and `lib/typescript` files.
|
||||
- `android/generated` and `ios/generated` are checked-in codegen output (`includesGeneratedCode`). A change to a native component spec regenerates both; `scripts/postinstall-patches.test.mjs` compares them against the specs.
|
||||
- `src/web/wasm/md4c.js` and `lib/module/web/wasm/md4c.js` are an Emscripten build of `cpp/md4c`. A parser change rebuilds them with upstream's `packages/core/cpp/wasm/build.sh`.
|
||||
- `src/web/wasm/md4c.js` and `lib/module/web/wasm/md4c.js` are an Emscripten build of `cpp/md4c`, `cpp/parser` and `cpp/wasm`. A parser change rebuilds both, or web keeps the old behavior while iOS and Android change. Run `cpp/wasm/build.sh` with `OUT_DIR` set to `src/web/wasm`, in `emscripten/emsdk:4.0.10` with the `-s GROWABLE_ARRAYBUFFERS=0` line removed. That version reproduces the committed JavaScript glue and has no such setting. The `lib/module` copy is the Babel output of the new file.
|
||||
- Upstream's Gradle, CMake and CocoaPods scripts detect upstream's own monorepo by the paths `packages/core` and a root `vendor/`. Do not add either path to this repository.
|
||||
- `postinstall.mjs` downloads the tree-sitter grammars into the ignored `cpp/highlight/vendor/grammars` and `vendor/tree-sitter`. The `enriched-markdown` block in `packages/app/package.json` chooses the languages.
|
||||
|
||||
@@ -42,7 +42,7 @@ Some fork changes are backports. A sync past the upstream version drops them in
|
||||
|
||||
## Engine constraints
|
||||
|
||||
Math and video are disabled. Task lists and admonitions are enabled; task checkboxes are read-only. Source adaptation spaces adjacent empty GFM table delimiters before escaping prose spoiler delimiters and decodes entity text before the engine can discard it. Code spans and fences keep their literal source. Comment HTML is normalized to Markdown before parsing; details show their summary and body expanded.
|
||||
Math and video are disabled. Task lists and admonitions are enabled; task checkboxes are read-only. Source adaptation spaces adjacent empty GFM table delimiters before escaping prose spoiler delimiters and decodes entity text before the engine can discard it. Code spans and fences keep their literal source. Comment HTML is normalized to Markdown before parsing; details show their summary and body expanded. `<br>` becomes a Markdown hard break, except inside a table, where a newline would end the row. There it becomes U+2028, and `cpp/parser/MD4CParser.cpp` turns U+2028 back into a line break in table cell text, never in code.
|
||||
|
||||
Mermaid fences use the existing isolated diagram runtime and fullscreen viewer. Web dispatches them through the library’s code-block override. Native has no block-renderer hook, so the renderer extracts only Mermaid fences and places the existing WebView host between library-rendered segments. This is the only block exception; see [native selection limitations](native-text-selection.md) for diagram grouping and leading inline images. Streaming keeps the last valid diagram visible while the next revision renders.
|
||||
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
# Online client replacement: timeline recovery
|
||||
|
||||
Verified on macOS arm64 with Node 22.20.0, Chromium 145 (Playwright), and a real isolated daemon. Replies use the deterministic test provider; no external AI API is involved.
|
||||
|
||||
## Reproduction
|
||||
|
||||
1. Open two chats on one host and return to the first.
|
||||
2. Delay the active connection's real pong frames by 1 second, forwarding all real traffic, and wait for a measured liveness RTT.
|
||||
3. Add another direct endpoint for the same daemon.
|
||||
4. Advance the browser clock in 10-second steps. Each step waits for real delayed heartbeat replies and the public probe-cycle completion barrier, including replacement handshakes. The production selector and its timer constants are unchanged.
|
||||
5. Verify that every observed host snapshot stays online with a client, then confirm exactly one client-generation change to the faster endpoint.
|
||||
6. Require the Reconnecting alert to disappear within 3 seconds and verify a new message in the visible chat.
|
||||
7. Commit a message to the hidden second chat before reopening it. Verify that message is recovered, then verify another live message.
|
||||
|
||||
The two paths are localhost and 127.0.0.1 to the same daemon. The test does not force host state or replace a private client field. It controls browser time, not the daemon clock or real socket responses. Subscription assertions require the needed agents without requiring all other agents to be absent; exact matching remains the shared helper's default. The test has a 180-second timeout and a bounded clock-step budget allowing one candidate backoff. Observers, handles, timers, and scenario data are cleaned up even on failure.
|
||||
|
||||
## Before: exact final test source
|
||||
|
||||
Temporarily remove only the production `sync.setConnected(...)` seed, run the final regression, and restore the source in a `finally` block. The host remains online and changes to generation 2, but Reconnecting does not settle:
|
||||
|
||||
```text
|
||||
Error: expect(locator).toHaveCount(expected) failed
|
||||
Locator: getByRole('alert').filter({ hasText: 'Reconnecting' })
|
||||
Expected: 0
|
||||
Received: 1
|
||||
Timeout: 3000ms
|
||||
1 failed
|
||||
```
|
||||
|
||||
The frame below is extracted without modification from that final RED trace while the assertion was waiting, before fixture cleanup.
|
||||
|
||||

|
||||
|
||||
## After
|
||||
|
||||
Restore the production seed without changing the test files, then run:
|
||||
|
||||
```sh
|
||||
npm run test:e2e --workspace=@getpaseo/app -- \
|
||||
e2e/browser/viewed-agent-timelines.spec.ts \
|
||||
--grep 'online connection replacement|visible chat reports updating until reconnect' \
|
||||
--workers=1
|
||||
```
|
||||
|
||||
```text
|
||||
✓ an online connection replacement keeps every open chat synchronized (1.6m)
|
||||
✓ a visible chat reports updating until reconnect catch-up completes (35.9s)
|
||||
2 passed (2.3m)
|
||||
```
|
||||
|
||||
The online replacement case previously took 4.8 minutes with wall-clock probe waits. The final controlled-clock run takes 1.6 minutes. [Recorded hashes](red-green.json) confirm both test files are identical between final RED and GREEN and the production source was restored exactly.
|
||||
|
||||

|
||||
|
||||
## Other checks
|
||||
|
||||
```sh
|
||||
npm run typecheck
|
||||
npm run lint -- packages/app/e2e/browser/viewed-agent-timelines.spec.ts packages/app/e2e/support/helpers/timeline-delivery.ts
|
||||
npm run format
|
||||
```
|
||||
|
||||
Whole-workspace typecheck exited 0. Changed-file lint reported `Found 0 warnings and 0 errors.` Formatting passed.
|
||||
|
||||
The original runtime fix is unchanged by this test follow-up. Its previous native validation remains: both unmodified and fixed renderers exported with `PASEO_WEB_PLATFORM=electron npm exec -- expo export --platform web`; server dependencies and desktop main built through repository scripts; both packaged locally with `electron-builder --config electron-builder.yml --publish never --mac --arm64 --dir -c.mac.notarize=false`, with certificate discovery disabled.
|
||||
|
||||
The existing `packages/desktop/e2e/packaged-app-smoke.js --app <built-app>` passed for both packages with fresh temporary user data/daemon homes and loopback ports:
|
||||
|
||||
```text
|
||||
Packaged desktop smoke: real app renderer and preload bridge loaded
|
||||
Packaged desktop smoke: renderer-started desktop daemon reported running
|
||||
Packaged desktop smoke: every built-in plugin started
|
||||
Packaged desktop smoke: running bundled CLI shim daemon status
|
||||
Packaged desktop smoke: creating terminal through bundled CLI shim
|
||||
Packaged desktop smoke: terminal hook command completed
|
||||
Packaged desktop smoke passed: real renderer and preload loaded; renderer-started desktop daemon;
|
||||
CLI shim daemon status and terminal smoke succeeded
|
||||
```
|
||||
|
||||
The final summary omits ephemeral PID/listen values. The native smoke establishes packaged startup and terminal functionality, not native reconnect coverage.
|
||||
|
||||
## Coverage limits
|
||||
|
||||
- Web: real browser/daemon regression, with controlled browser scheduling, before and after.
|
||||
- macOS desktop: prior arm64 packaging and native startup/CLI/terminal smoke of the unchanged runtime fix.
|
||||
- iOS, Android, Windows desktop, Linux desktop: not tested.
|
||||
- External relay transport and a real provider turn: not tested by this regression.
|
||||
- The test requires eventual history recovery; it does not change the product's hidden-chat subscription policy or prohibit every transient toast frame.
|
||||
- These are local results. No full-suite or GitHub CI pass is claimed.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 128 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 57 KiB |
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"production_source_restored": true,
|
||||
"test_sha256": {
|
||||
"packages/app/e2e/browser/viewed-agent-timelines.spec.ts": "1857d0ca187648d8377557cd82428a64546530795cf884c7474e921a1118c003",
|
||||
"packages/app/e2e/support/helpers/timeline-delivery.ts": "23d0adb9f92daac6d0841d584abb7aa272a2981861d7d211c8213e98a9af90da"
|
||||
},
|
||||
"red": {
|
||||
"result": "expected failure",
|
||||
"assertion": "Reconnecting alert expected 0, received 1",
|
||||
"timeout_ms": 3000
|
||||
},
|
||||
"green": {
|
||||
"passed": 2,
|
||||
"online_replacement_duration": "1.6m",
|
||||
"ordinary_reconnect_duration": "35.9s",
|
||||
"total_duration": "2.3m"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
# Running indicators
|
||||
|
||||
Three things animate for as long as an agent works: the six-dot loader in the turn footer
|
||||
(`components/synced-loader`), the status ring on a running workspace or tab
|
||||
(`components/status-ring`), and the highlight that sweeps a running tool call's label
|
||||
(`components/label-shimmer`). A turn can run for an hour, so each of them must cost nothing on the
|
||||
thread that runs React.
|
||||
|
||||
## The rule
|
||||
|
||||
A perpetual animation is handed to the platform's animation engine once and then left alone. It
|
||||
does not go through React state, `requestAnimationFrame`, a timer per frame, or a Reanimated shared
|
||||
value.
|
||||
|
||||
`components/indicator-motion` owns the two pieces every indicator shares:
|
||||
|
||||
- `useIndicatorMotion()` decides whether an indicator may move: not under reduced motion, not in a
|
||||
retained panel that is not showing, not while the app is in the background. An indicator that may
|
||||
not move draws its resting frame and runs nothing. Ask this hook; do not read reduced motion or
|
||||
visibility yourself.
|
||||
- The driver: `loop.web.ts` on web, `clock.ts` on native.
|
||||
|
||||
Animate only `transform` and `opacity`. Anything else is painted on the main thread every frame.
|
||||
|
||||
## Web
|
||||
|
||||
`useIndicatorLoop` runs a keyframe loop through the Web Animations API (`element.animate`). The
|
||||
compositor carries it; the page runs no script, restyles nothing and repaints nothing to keep it
|
||||
moving.
|
||||
|
||||
Do not declare these as CSS `@keyframes`. A CSS animation fires `animationiteration`, React listens
|
||||
for it at the root, and Chromium wakes the main thread around the end of every cycle of every CSS
|
||||
animation in a document that has such a listener. Measured on a quiet running turn: 13 main-thread
|
||||
commits and 14 style recalculations a second with `@keyframes`, against the 3 commits a second the
|
||||
page produces with nothing moving. The Web Animations API has no iteration event.
|
||||
|
||||
Two more reasons the stylesheet route does not work here:
|
||||
|
||||
- Unistyles owns style conversion on web, so React Native Web's `animationKeyframes` is ignored.
|
||||
- React Native Web's `StyleSheet.create` validation deletes `animationName` in development.
|
||||
|
||||
Indicators that must move together use `phase: "shared"`, which starts the loop at the document
|
||||
timeline's origin instead of at mount. Every ring and every loader is then at the same point of its
|
||||
cycle wherever and whenever it mounted. A stepped animation sets `easing: "step-end"` on each
|
||||
keyframe; the compositor then draws a frame when a step changes and none in between.
|
||||
|
||||
## Native
|
||||
|
||||
Reanimated commits a cloned shadow tree on the UI thread for every frame a shared value changes.
|
||||
For a transition that is fine. For an indicator that runs for an hour it was 22–28% of a core on
|
||||
the UI thread of an Android emulator.
|
||||
|
||||
React Native's own `Animated` with `useNativeDriver: true` updates the view from the native driver
|
||||
and commits nothing. `clock.ts` builds a clock out of it: a decay that never slows, at one unit per
|
||||
millisecond, is the time since it started. Decay is the one native-driven animation that computes
|
||||
its value from the frame timestamp instead of replaying a 60 fps recording, so it is exact at any
|
||||
refresh rate and needs no loop restart. `Animated.modulo` and `interpolate` turn the clock into a
|
||||
rotation or a translation, all inside the native driver.
|
||||
|
||||
The loader changes six times per cycle, so it does not ride the frame clock. `step-ticker.ts` wakes
|
||||
the JS thread once per step, aligned to wall-clock step boundaries, and publishes the step into a
|
||||
native `Animated.Value`. A wake-up that arrives late publishes the step that is current by then, so
|
||||
the loader never drifts and every loader shows the same step.
|
||||
|
||||
Do not apply Unistyles dynamic styles to these `Animated.View`s; see
|
||||
[unistyles.md](unistyles.md#reanimated-animatedview--dynamic-styles-crashes).
|
||||
|
||||
## Measuring
|
||||
|
||||
`e2e/browser/running-indicators.spec.ts` holds the web budgets: animation-frame callbacks, style
|
||||
recalculations, paints and main-thread commits per second on a quiet running turn, React renders of
|
||||
the indicator components, the loader's cadence, reduced motion, and a hidden tab. Run it with
|
||||
`PASEO_RUNNING_INDICATORS_FRAMES=1` to also save reference frames of every indicator at fixed
|
||||
points of its cycle, for a pixel comparison across a change.
|
||||
|
||||
To hold a turn in the running state without streaming, send the mock load-test agent
|
||||
`Hold a running shell tool call for <N>ms`.
|
||||
|
||||
On Android, compare `adb shell dumpsys gfxinfo <package>` frame counts and per-thread CPU from
|
||||
`/proc/<pid>/task/*/stat` over a fixed window. The UI thread (`sh.paseo.debug`) is the one a
|
||||
regression shows up on; `RenderThread` draws 60 frames a second whenever a ring or a shimmer is on
|
||||
screen, and that part is the cost of the motion itself.
|
||||
@@ -2,7 +2,8 @@ import { expect, test } from "../support/fixtures";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import { seedWorkspace } from "../support/helpers/seed-client";
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
import { openSettingsSection } from "../support/helpers/settings";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
import { clickSettingsBackToWorkspace, openSettingsSection } from "../support/helpers/settings";
|
||||
|
||||
test("shows Pure black in the appearance picker", async ({ page }, testInfo) => {
|
||||
await page.goto("/settings");
|
||||
@@ -96,3 +97,43 @@ test("applies the interface font size to settings text", async ({ page }) => {
|
||||
await expect(contentSizeInput).toHaveValue("21");
|
||||
await expect(sectionTitle).toHaveCSS("font-size", "10px");
|
||||
});
|
||||
|
||||
test("applies the content font size to an already-open chat", async ({ page }) => {
|
||||
const agent = await seedMockAgentWorkspace({ repoPrefix: "chat-font-size-", title: "Font size" });
|
||||
const prompt = "Existing message for the font size check";
|
||||
try {
|
||||
await agent.client.sendAgentMessage(agent.agentId, prompt);
|
||||
await agent.client.waitForFinish(agent.agentId, 30_000);
|
||||
await openAgentRoute(page, agent);
|
||||
|
||||
const userText = page.getByText(prompt, { exact: true });
|
||||
const assistantText = page.getByTestId("assistant-message").first().locator("p").first();
|
||||
const initialSize = await test.step("Read both messages at the default size", async () => {
|
||||
await expect(userText).toBeVisible();
|
||||
await expect(assistantText).toBeVisible();
|
||||
return userText.evaluate((element) => getComputedStyle(element).fontSize);
|
||||
});
|
||||
const timeOrigin = await page.evaluate(() => performance.timeOrigin);
|
||||
|
||||
await test.step("Increase Content font size and return to the same chat", async () => {
|
||||
await page.getByTestId("sidebar-settings").filter({ visible: true }).first().click();
|
||||
await openSettingsSection(page, "appearance");
|
||||
const size = page.getByRole("textbox", { name: "Content font size", exact: true });
|
||||
await size.fill("21");
|
||||
await size.press("Tab");
|
||||
await expect(size).toHaveValue("21");
|
||||
await clickSettingsBackToWorkspace(page);
|
||||
});
|
||||
|
||||
await test.step("Read both messages at the new size without reloading", async () => {
|
||||
expect(await page.evaluate(() => performance.timeOrigin)).toBe(timeOrigin);
|
||||
await expect(assistantText).not.toHaveCSS("font-size", initialSize);
|
||||
const updatedSize = await assistantText.evaluate(
|
||||
(element) => getComputedStyle(element).fontSize,
|
||||
);
|
||||
await expect(userText).toHaveCSS("font-size", updatedSize);
|
||||
});
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
finishSetup,
|
||||
goToSetupStep,
|
||||
hostGivesAgentsPaseoTools,
|
||||
hostToolGroups,
|
||||
openAppAsNewUser,
|
||||
openRelayPairingFromSetup,
|
||||
closeRelayPairing,
|
||||
@@ -24,6 +25,7 @@ import {
|
||||
recordFirstLaunch,
|
||||
setupModal,
|
||||
setupPrimaryButton,
|
||||
setHostTools,
|
||||
setupSheet,
|
||||
showSetupAgainFromSettings,
|
||||
skipSetup,
|
||||
@@ -426,6 +428,30 @@ test("setup choices carry over to Settings and the phone step pairs over relay",
|
||||
}
|
||||
});
|
||||
|
||||
test("setup offers only Enable tools and keeps the host's tool groups", async ({ page }) => {
|
||||
const host = await startSetupHost("tool-groups");
|
||||
|
||||
try {
|
||||
await setHostTools(host, { groups: { schedules: false, browser: true } });
|
||||
await openAppAsNewUser(page, host);
|
||||
await expectSetupStep(page, "Welcome to Paseo");
|
||||
await goToSetupStep(page, "Orchestration");
|
||||
await expectSetupStep(page, "Let agents use Paseo");
|
||||
await expect(paseoToolsSwitch(setupModal(page))).toBeChecked();
|
||||
// Setup offers only the main switch; tool groups live in Settings.
|
||||
await expect(
|
||||
setupModal(page).getByRole("switch", { name: "Browser", exact: true }),
|
||||
).toHaveCount(0);
|
||||
await continueSetup(page);
|
||||
await expectSetupStep(page, "Take your agents with you");
|
||||
|
||||
await expect.poll(() => hostGivesAgentsPaseoTools(host), { timeout: 30_000 }).toBe(true);
|
||||
expect(await hostToolGroups(host)).toMatchObject({ schedules: false, browser: true });
|
||||
} finally {
|
||||
await host.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("with no skills picked, skills read as off and Continue moves on", async ({ page }) => {
|
||||
const host = await startSetupHost("no-skills");
|
||||
|
||||
@@ -463,6 +489,7 @@ test("in the compact layout, Finish on Orchestration applies its switches", asyn
|
||||
const primary = (label: string) => page.getByRole("button", { name: label, exact: true });
|
||||
|
||||
try {
|
||||
await setHostTools(host, { enabled: false });
|
||||
await openAppAsNewUser(page, host);
|
||||
await step("Welcome to Paseo");
|
||||
await primary("Continue").click();
|
||||
@@ -471,7 +498,7 @@ test("in the compact layout, Finish on Orchestration applies its switches", asyn
|
||||
await step("Add your projects");
|
||||
await primary("Continue").click();
|
||||
|
||||
// The setup host starts with Paseo tools off; the switch starts on.
|
||||
// The host has tools off; the setup switch still starts on.
|
||||
expect(await hostGivesAgentsPaseoTools(host)).toBe(false);
|
||||
await step("Let agents use Paseo");
|
||||
await expect(paseoToolsSwitch(page)).toBeChecked();
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { test, expect } from "../support/fixtures";
|
||||
import {
|
||||
readReactRenders,
|
||||
recordReactRenders,
|
||||
resetReactRenders,
|
||||
} from "../support/helpers/react-renders";
|
||||
import {
|
||||
captureLoaderSteps,
|
||||
freezeAnimationsAt,
|
||||
openQuietRunningTurn,
|
||||
readAnimatingTargets,
|
||||
readLoaderStep,
|
||||
readRunningAnimations,
|
||||
recordLoaderStepChanges,
|
||||
runningToolCall,
|
||||
statusRings,
|
||||
workingLoader,
|
||||
} from "../support/helpers/running-indicators";
|
||||
import { measureSteadyStateActivity } from "../support/helpers/steady-state-activity";
|
||||
import { setTabVisibility } from "../support/helpers/workspace-ui";
|
||||
|
||||
/**
|
||||
* A running turn that is otherwise quiet shows three animated indicators: the six-dot loader, the
|
||||
* tool-call label shimmer and the status rings. None of them may cost main-thread work: the
|
||||
* browser's compositor carries them, so the page neither runs script, restyles nor repaints to
|
||||
* keep them moving.
|
||||
*
|
||||
* The budgets sit between what the rest of the page does on its own and the cheapest way these
|
||||
* indicators have been measured getting it wrong. With nothing moving, the main thread still
|
||||
* commits to the compositor about three times a second (the elapsed counter and the app's own
|
||||
* timers), and each commit restyles whatever is animating. Declaring the same animations as CSS
|
||||
* `@keyframes` costs thirteen commits and fourteen restyles a second; driving them from script
|
||||
* costs sixty frames a second.
|
||||
*/
|
||||
|
||||
const SAMPLE_WINDOW_MS = 5_000;
|
||||
const ANIMATION_FRAME_CALLBACKS_PER_SECOND_BUDGET = 2;
|
||||
const STYLE_RECALCS_PER_SECOND_BUDGET = 8;
|
||||
const MAIN_THREAD_COMMITS_PER_SECOND_BUDGET = 8;
|
||||
const PAINTS_PER_SECOND_BUDGET = 4;
|
||||
// The elapsed counter's repaint reports the whole viewport as its clip once a second. Sixty
|
||||
// indicator frames a second repainted seventy viewports' worth.
|
||||
const PAINTED_VIEWPORTS_PER_SECOND_BUDGET = 4;
|
||||
const LOADER_PERIOD_MS = 950;
|
||||
const LOADER_STEP_MS = LOADER_PERIOD_MS / 6;
|
||||
const STATUS_RING_PERIOD_MS = 900;
|
||||
|
||||
// React renders these once when the indicator appears. Rendering again while the turn is quiet
|
||||
// means the animation is being driven through React.
|
||||
const INDICATOR_COMPONENTS = /SyncedLoader|StatusRing|Shimmer|ExpandableBadge|WorkingIndicator/;
|
||||
|
||||
function indicatorRenders(renders: Record<string, number>): string[] {
|
||||
return Object.keys(renders).filter((name) => INDICATOR_COMPONENTS.test(name));
|
||||
}
|
||||
|
||||
test.describe("Running indicators", () => {
|
||||
test("keep moving without waking the main thread", async ({ page, browser }, testInfo) => {
|
||||
test.setTimeout(180_000);
|
||||
await recordReactRenders(page);
|
||||
const agent = await openQuietRunningTurn(page);
|
||||
try {
|
||||
await resetReactRenders(page);
|
||||
const activity = await measureSteadyStateActivity({
|
||||
browser,
|
||||
page,
|
||||
windowMs: SAMPLE_WINDOW_MS,
|
||||
});
|
||||
const renders = await readReactRenders(page);
|
||||
const animations = await readRunningAnimations(page);
|
||||
const stepChanges = await recordLoaderStepChanges(page, 3_000);
|
||||
const evidence = { activity, renders, animations, stepChanges };
|
||||
await writeFile(testInfo.outputPath("evidence.json"), JSON.stringify(evidence, null, 2));
|
||||
|
||||
expect
|
||||
.soft(activity.animationFrameCallbacksPerSecond)
|
||||
.toBeLessThan(ANIMATION_FRAME_CALLBACKS_PER_SECOND_BUDGET);
|
||||
expect.soft(activity.styleRecalcsPerSecond).toBeLessThan(STYLE_RECALCS_PER_SECOND_BUDGET);
|
||||
expect.soft(activity.paintsPerSecond).toBeLessThan(PAINTS_PER_SECOND_BUDGET);
|
||||
expect
|
||||
.soft(activity.paintedViewportsPerSecond)
|
||||
.toBeLessThan(PAINTED_VIEWPORTS_PER_SECOND_BUDGET);
|
||||
expect
|
||||
.soft(activity.mainThreadCommitsPerSecond)
|
||||
.toBeLessThan(MAIN_THREAD_COMMITS_PER_SECOND_BUDGET);
|
||||
expect.soft(indicatorRenders(renders)).toEqual([]);
|
||||
|
||||
// The cadence is part of the design: six even steps in 950 ms, in order.
|
||||
const steps = stepChanges.slice(1);
|
||||
expect.soft(steps.length).toBeGreaterThan(12);
|
||||
for (let index = 1; index < steps.length; index += 1) {
|
||||
expect.soft(steps[index].step).toBe((steps[index - 1].step + 1) % 6);
|
||||
}
|
||||
const measuredStepMs = (steps.at(-1)!.atMs - steps[0].atMs) / (steps.length - 1);
|
||||
expect.soft(Math.abs(measuredStepMs - LOADER_STEP_MS)).toBeLessThan(8);
|
||||
|
||||
const ringAnimations = animations.filter((animation) => animation.target === "status-ring");
|
||||
expect.soft(ringAnimations.length).toBeGreaterThan(0);
|
||||
for (const ring of ringAnimations) {
|
||||
expect.soft(ring).toMatchObject({
|
||||
durationMs: STATUS_RING_PERIOD_MS,
|
||||
easing: "linear",
|
||||
iterations: Number.POSITIVE_INFINITY,
|
||||
properties: ["transform"],
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("hold still when the system asks for reduced motion", async ({
|
||||
page,
|
||||
browser,
|
||||
}, testInfo) => {
|
||||
test.setTimeout(180_000);
|
||||
await page.emulateMedia({ reducedMotion: "reduce" });
|
||||
await recordReactRenders(page);
|
||||
const agent = await openQuietRunningTurn(page);
|
||||
try {
|
||||
await resetReactRenders(page);
|
||||
const activity = await measureSteadyStateActivity({
|
||||
browser,
|
||||
page,
|
||||
windowMs: SAMPLE_WINDOW_MS,
|
||||
});
|
||||
const renders = await readReactRenders(page);
|
||||
const animations = await readRunningAnimations(page);
|
||||
await writeFile(
|
||||
testInfo.outputPath("evidence.json"),
|
||||
JSON.stringify({ activity, renders, animations }, null, 2),
|
||||
);
|
||||
await page.screenshot({ path: testInfo.outputPath("page-reduced-motion.png") });
|
||||
await workingLoader(page).screenshot({ path: testInfo.outputPath("loader.png") });
|
||||
await runningToolCall(page).screenshot({ path: testInfo.outputPath("tool-call.png") });
|
||||
await statusRings(page)
|
||||
.first()
|
||||
.screenshot({ path: testInfo.outputPath("status-ring.png") });
|
||||
|
||||
expect.soft(animations).toEqual([]);
|
||||
expect.soft(await readLoaderStep(page)).toBe(0);
|
||||
expect
|
||||
.soft(activity.animationFrameCallbacksPerSecond)
|
||||
.toBeLessThan(ANIMATION_FRAME_CALLBACKS_PER_SECOND_BUDGET);
|
||||
expect.soft(activity.styleRecalcsPerSecond).toBeLessThan(STYLE_RECALCS_PER_SECOND_BUDGET);
|
||||
expect.soft(activity.paintsPerSecond).toBeLessThan(PAINTS_PER_SECOND_BUDGET);
|
||||
// With nothing moving the compositor only draws for the elapsed counter.
|
||||
expect.soft(activity.compositorFramesPerSecond).toBeLessThan(4);
|
||||
expect.soft(indicatorRenders(renders)).toEqual([]);
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("stop while the tab is hidden and resume when it is shown", async ({ page }) => {
|
||||
test.setTimeout(180_000);
|
||||
const agent = await openQuietRunningTurn(page);
|
||||
try {
|
||||
const everyIndicator = expect.arrayContaining([
|
||||
"status-ring",
|
||||
"synced-loader-dot",
|
||||
"label-shimmer",
|
||||
]);
|
||||
await expect.poll(() => readAnimatingTargets(page)).toEqual(everyIndicator);
|
||||
|
||||
await setTabVisibility(page, "hidden");
|
||||
await expect.poll(() => readAnimatingTargets(page)).toEqual([]);
|
||||
expect(await readLoaderStep(page)).toBe(0);
|
||||
|
||||
await setTabVisibility(page, "visible");
|
||||
await expect.poll(() => readAnimatingTargets(page)).toEqual(everyIndicator);
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("look the same frame for frame", async ({ page }, testInfo) => {
|
||||
test.setTimeout(180_000);
|
||||
test.skip(
|
||||
process.env.PASEO_RUNNING_INDICATORS_FRAMES !== "1",
|
||||
"Captures reference frames for a before/after comparison; not an assertion.",
|
||||
);
|
||||
const agent = await openQuietRunningTurn(page);
|
||||
try {
|
||||
const capturedSteps = await captureLoaderSteps(page, (step) =>
|
||||
testInfo.outputPath(`loader-step-${step}.png`),
|
||||
);
|
||||
expect(capturedSteps).toEqual([0, 1, 2, 3, 4, 5]);
|
||||
|
||||
for (const progress of [0, 0.13, 0.31, 0.5, 0.77, 0.94]) {
|
||||
await freezeAnimationsAt(page, progress);
|
||||
const label = String(Math.round(progress * 100)).padStart(2, "0");
|
||||
await runningToolCall(page).screenshot({
|
||||
path: testInfo.outputPath(`tool-call-${label}.png`),
|
||||
});
|
||||
await statusRings(page)
|
||||
.first()
|
||||
.screenshot({ path: testInfo.outputPath(`status-ring-${label}.png`) });
|
||||
await page.screenshot({
|
||||
path: testInfo.outputPath(`page-${label}.png`),
|
||||
mask: [page.getByTestId("turn-footer")],
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -52,17 +52,28 @@ async function exitSelection(page: Page) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Walks the Finder click matrix on four rows, starting with the first row open: a modifier click
|
||||
* from normal mode selects only the clicked row, Cmd/Ctrl+click toggles, Shift+click extends and
|
||||
* shrinks a range from the anchor, and plain clicks keep toggling while select mode is on.
|
||||
* Walks the sidebar selection click matrix on four rows: Cmd/Ctrl+click (and Cmd/Ctrl+Shift+click)
|
||||
* from normal mode navigates instead of entering select mode, Shift+click enters select mode on the
|
||||
* clicked row alone, Cmd/Ctrl+click and plain clicks toggle while select mode is active, and
|
||||
* Shift+click extends, shrinks, and flips a range from the anchor.
|
||||
*/
|
||||
async function exerciseClickMatrix(page: Page, rows: readonly Locator[]) {
|
||||
const [first, second, third, fourth] = rows;
|
||||
await first.click();
|
||||
await expect(first).toHaveAttribute("aria-selected", "true");
|
||||
|
||||
// Cmd/Ctrl+click and Cmd/Ctrl+Shift+click outside select mode navigate normally.
|
||||
await third.click({ modifiers: [MOD] });
|
||||
await expect(third).toHaveAttribute("aria-selected", "true");
|
||||
await expect(page.getByTestId("workspace-selection-toast")).toHaveCount(0);
|
||||
|
||||
await first.click({ modifiers: [MOD, "Shift"] });
|
||||
await expect(first).toHaveAttribute("aria-selected", "true");
|
||||
await expect(page.getByTestId("workspace-selection-toast")).toHaveCount(0);
|
||||
const openWorkspaceUrl = page.url();
|
||||
|
||||
await third.click({ modifiers: [MOD] });
|
||||
// Shift+click enters select mode on the clicked row alone; Cmd/Ctrl+click and plain clicks toggle.
|
||||
await third.click({ modifiers: ["Shift"] });
|
||||
await expectSelectedCount(page, 1);
|
||||
await expectChecked(rows, [false, false, true, false]);
|
||||
|
||||
@@ -102,7 +113,7 @@ test.describe("sidebar workspace selection clicks", () => {
|
||||
seeded = null;
|
||||
});
|
||||
|
||||
test("Cmd/Ctrl+click and Shift+click select like Finder in project grouping", async ({
|
||||
test("Shift+click enters select mode while Cmd/Ctrl+click navigates in project grouping", async ({
|
||||
page,
|
||||
}) => {
|
||||
seeded = await seedProjectWithWorkspaces(4);
|
||||
@@ -111,7 +122,9 @@ test.describe("sidebar workspace selection clicks", () => {
|
||||
await exerciseClickMatrix(page, await rowsInSidebarOrder(page, seeded.workspaceIds));
|
||||
});
|
||||
|
||||
test("Cmd/Ctrl+click and Shift+click select like Finder in status grouping", async ({ page }) => {
|
||||
test("Shift+click enters select mode while Cmd/Ctrl+click navigates in status grouping", async ({
|
||||
page,
|
||||
}) => {
|
||||
seeded = await seedProjectWithWorkspaces(4);
|
||||
await gotoAppShell(page);
|
||||
await waitForSidebarHydration(page);
|
||||
|
||||
@@ -5,30 +5,34 @@ import { expectComposerVisible } from "../support/helpers/composer";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
|
||||
interface ShimmerEvidence {
|
||||
animationDuration: string;
|
||||
durationMs: number;
|
||||
endPx: number;
|
||||
label: string;
|
||||
renderedWidth: number;
|
||||
startPx: number;
|
||||
}
|
||||
|
||||
async function readShimmerEvidence(locator: Locator): Promise<ShimmerEvidence> {
|
||||
return locator.evaluate((root) => {
|
||||
const shimmer = Array.from(root.querySelectorAll<HTMLElement>("*")).find((element) =>
|
||||
getComputedStyle(element).animationName.includes("paseo-toolcall-shimmer"),
|
||||
);
|
||||
if (!shimmer) {
|
||||
throw new Error("Expected a running shimmer inside the badge");
|
||||
}
|
||||
const style = getComputedStyle(shimmer);
|
||||
return {
|
||||
animationDuration: style.animationDuration,
|
||||
endPx: Number.parseFloat(style.getPropertyValue("--paseo-shimmer-end")),
|
||||
label: shimmer.textContent ?? "",
|
||||
renderedWidth: shimmer.getBoundingClientRect().width,
|
||||
startPx: Number.parseFloat(style.getPropertyValue("--paseo-shimmer-start")),
|
||||
};
|
||||
});
|
||||
// The band is the shimmer's moving window; its animation carries the sweep it was measured for.
|
||||
async function readShimmerEvidence(badge: Locator): Promise<ShimmerEvidence> {
|
||||
return badge
|
||||
.getByTestId("label-shimmer")
|
||||
.first()
|
||||
.evaluate((shimmer) => {
|
||||
const effect = shimmer.firstElementChild?.getAnimations()[0]?.effect;
|
||||
if (!(effect instanceof KeyframeEffect)) {
|
||||
throw new Error("Expected a running shimmer inside the badge");
|
||||
}
|
||||
const [startPx, endPx] = effect
|
||||
.getKeyframes()
|
||||
.map((keyframe) => new DOMMatrix(String(keyframe.transform)).m41);
|
||||
return {
|
||||
durationMs: Number(effect.getComputedTiming().duration),
|
||||
endPx,
|
||||
label: shimmer.textContent ?? "",
|
||||
renderedWidth: shimmer.getBoundingClientRect().width,
|
||||
startPx,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
test("measures an overview heading that becomes loading after its idle mount", async ({
|
||||
@@ -63,11 +67,11 @@ test("measures an overview heading that becomes loading after its idle mount", a
|
||||
if (!idleGroupHandle) {
|
||||
throw new Error("Expected the idle tool-call group to be mounted");
|
||||
}
|
||||
await expect(group.locator('[style*="paseo-toolcall-shimmer"]')).toHaveCount(0);
|
||||
await expect(group.getByTestId("label-shimmer")).toHaveCount(0);
|
||||
|
||||
await gate.waitForSecondRunning();
|
||||
gate.releaseSecondRunning();
|
||||
await expect(group.locator('[style*="paseo-toolcall-shimmer"]')).not.toHaveCount(0);
|
||||
await expect(group.getByTestId("label-shimmer")).not.toHaveCount(0);
|
||||
const sameGroupNode = await group.evaluate(
|
||||
(node, previous) => node === previous,
|
||||
idleGroupHandle,
|
||||
|
||||
@@ -3,6 +3,7 @@ import { buildHostAgentDetailRoute } from "@/utils/host-routes";
|
||||
import { test } from "../support/fixtures";
|
||||
import { seedWorkspace, type SeedDaemonClient } from "../support/helpers/seed-client";
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
import { getE2EDaemonPort } from "../support/helpers/daemon-port";
|
||||
import { observeTimelineSubscriptions } from "../support/helpers/timeline-delivery";
|
||||
import { waitForWorkspaceTabsVisible } from "../support/helpers/workspace-tabs";
|
||||
import { selectWorkspaceInSidebar } from "../support/helpers/sidebar";
|
||||
@@ -254,7 +255,226 @@ async function expectCurrentChatWithoutCatchUp(page: Page, message: string) {
|
||||
await expect(page.getByRole("alert").filter({ hasText: "Updating messages" })).toHaveCount(0);
|
||||
}
|
||||
|
||||
async function delayActiveDaemonPongs(page: Page, port: string) {
|
||||
let deliveredPongs = 0;
|
||||
let inFlightPings = 0;
|
||||
const delayedPongs = new Set<ReturnType<typeof setTimeout>>();
|
||||
await page.routeWebSocket(
|
||||
(url) => url.hostname === "localhost" && url.port === port,
|
||||
(socket) => {
|
||||
const server = socket.connectToServer();
|
||||
socket.onMessage((message) => {
|
||||
if (typeof message === "string" && JSON.parse(message).type === "ping") inFlightPings += 1;
|
||||
server.send(message);
|
||||
});
|
||||
server.onMessage((message) => {
|
||||
if (typeof message === "string" && JSON.parse(message).type === "pong") {
|
||||
const timer = setTimeout(() => {
|
||||
delayedPongs.delete(timer);
|
||||
socket.send(message);
|
||||
deliveredPongs += 1;
|
||||
inFlightPings -= 1;
|
||||
}, 1_000);
|
||||
delayedPongs.add(timer);
|
||||
} else {
|
||||
socket.send(message);
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
return {
|
||||
delivered: () => deliveredPongs,
|
||||
settled: () => inFlightPings === 0 && delayedPongs.size === 0,
|
||||
dispose: () => {
|
||||
for (const timer of delayedPongs) clearTimeout(timer);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function readActiveLivenessRtt(page: Page): Promise<number> {
|
||||
return page.evaluate((serverId) => {
|
||||
const runtime = Reflect.get(globalThis, "__paseoHostRuntimeStore") as {
|
||||
getClient(id: string): { getLastLivenessRttMs(): number | null } | null;
|
||||
};
|
||||
return runtime.getClient(serverId)?.getLastLivenessRttMs() ?? 0;
|
||||
}, getServerId());
|
||||
}
|
||||
|
||||
async function readHostConnection(page: Page) {
|
||||
return page.evaluate((serverId) => {
|
||||
const runtime = Reflect.get(globalThis, "__paseoHostRuntimeStore") as {
|
||||
getSnapshot(id: string): {
|
||||
clientGeneration: number;
|
||||
connectionStatus: string;
|
||||
activeConnectionId: string;
|
||||
};
|
||||
};
|
||||
const snapshot = runtime.getSnapshot(serverId);
|
||||
return {
|
||||
generation: snapshot.clientGeneration,
|
||||
status: snapshot.connectionStatus,
|
||||
connection: snapshot.activeConnectionId,
|
||||
};
|
||||
}, getServerId());
|
||||
}
|
||||
|
||||
async function settleHostProbeCycle(page: Page): Promise<void> {
|
||||
await page.evaluate(async (serverId) => {
|
||||
const runtime = Reflect.get(globalThis, "__paseoHostRuntimeStore") as {
|
||||
runProbeCycleNow(id: string): Promise<void>;
|
||||
};
|
||||
// Joins any in-flight cycle through its final replacement handshake.
|
||||
await runtime.runProbeCycleNow(serverId);
|
||||
}, getServerId());
|
||||
}
|
||||
|
||||
async function observeContinuousHostConnection(page: Page) {
|
||||
const observation = await page.evaluateHandle((serverId) => {
|
||||
const runtime = Reflect.get(globalThis, "__paseoHostRuntimeStore") as {
|
||||
getSnapshot(id: string): { connectionStatus: string; client: unknown } | null;
|
||||
subscribe(id: string, listener: () => void): () => void;
|
||||
};
|
||||
const connected: boolean[] = [];
|
||||
const record = () => {
|
||||
const snapshot = runtime.getSnapshot(serverId);
|
||||
connected.push(snapshot?.connectionStatus === "online" && snapshot.client !== null);
|
||||
};
|
||||
record();
|
||||
const unsubscribe = runtime.subscribe(serverId, record);
|
||||
return {
|
||||
stop() {
|
||||
unsubscribe();
|
||||
return connected;
|
||||
},
|
||||
};
|
||||
}, getServerId());
|
||||
let stopped: Promise<boolean[]> | null = null;
|
||||
return {
|
||||
stop() {
|
||||
stopped ??= observation
|
||||
.evaluate((recorder) => recorder.stop())
|
||||
.finally(() => observation.dispose());
|
||||
return stopped;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function advanceToOnlineReplacement(
|
||||
page: Page,
|
||||
delayedPongs: Awaited<ReturnType<typeof delayActiveDaemonPongs>>,
|
||||
beforeGeneration: number,
|
||||
) {
|
||||
// Advance scheduling, not the sockets: settle real heartbeat and probe replies
|
||||
// between hops, including the replacement handshake, without altering production timers.
|
||||
for (let step = 0; step < 60; step += 1) {
|
||||
if ((await readHostConnection(page)).generation !== beforeGeneration) break;
|
||||
await expect.poll(delayedPongs.settled, { timeout: 10_000 }).toBe(true);
|
||||
await settleHostProbeCycle(page);
|
||||
const pongsBefore = delayedPongs.delivered();
|
||||
await page.clock.fastForward(10_000);
|
||||
await expect
|
||||
.poll(
|
||||
async () =>
|
||||
(await readHostConnection(page)).generation !== beforeGeneration ||
|
||||
delayedPongs.delivered() > pongsBefore,
|
||||
{ timeout: 10_000 },
|
||||
)
|
||||
.toBe(true);
|
||||
await settleHostProbeCycle(page);
|
||||
}
|
||||
}
|
||||
|
||||
test.describe("Viewed agent timelines", () => {
|
||||
test("an online connection replacement keeps every open chat synchronized", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
test.setTimeout(180_000);
|
||||
await page.clock.install();
|
||||
const port = getE2EDaemonPort();
|
||||
const delayedEndpoint = `localhost:${port}`;
|
||||
const fasterEndpoint = `127.0.0.1:${port}`;
|
||||
const delayedPongs = await delayActiveDaemonPongs(page, port);
|
||||
const subscriptions = observeTimelineSubscriptions(page);
|
||||
const scenario = await seedViewedTimelineScenario();
|
||||
let connectionObservation:
|
||||
| Awaited<ReturnType<typeof observeContinuousHostConnection>>
|
||||
| undefined;
|
||||
try {
|
||||
await commitMessage(scenario, scenario.firstAgentId, "BEFORE_CONNECTION_REPLACEMENT");
|
||||
await openAgent(page, scenario, scenario.firstAgentId);
|
||||
await selectAgent(page, "Second viewed chat");
|
||||
await selectAgent(page, "First viewed chat");
|
||||
await subscriptions.waitForSubscribedAgents([scenario.firstAgentId, scenario.secondAgentId]);
|
||||
await expectReconnectingToastGone(page);
|
||||
// The adaptive selector needs an RTT from the active socket, not only its startup probe.
|
||||
await expect.poll(delayedPongs.delivered, { timeout: 30_000 }).toBeGreaterThan(1);
|
||||
await expect
|
||||
.poll(() => readActiveLivenessRtt(page), { timeout: 30_000 })
|
||||
.toBeGreaterThanOrEqual(800);
|
||||
|
||||
// Add another real route to the same daemon. Delaying only the active route's real
|
||||
// pong frames gives the ordinary adaptive selector three consistently faster probes.
|
||||
// No host state is forced offline and no client or timeline owner is replaced by the test.
|
||||
connectionObservation = await observeContinuousHostConnection(page);
|
||||
const beforeGeneration = await page.evaluate(
|
||||
async ({ serverId, endpoint, activeEndpoint }) => {
|
||||
const runtime = Reflect.get(globalThis, "__paseoHostRuntimeStore") as {
|
||||
getSnapshot(id: string): {
|
||||
clientGeneration: number;
|
||||
connectionStatus: string;
|
||||
activeConnectionId: string;
|
||||
};
|
||||
upsertDirectConnection(input: { serverId: string; endpoint: string }): Promise<unknown>;
|
||||
};
|
||||
const before = runtime.getSnapshot(serverId);
|
||||
if (
|
||||
before.connectionStatus !== "online" ||
|
||||
before.activeConnectionId !== `direct:${activeEndpoint}`
|
||||
) {
|
||||
throw new Error("Expected the initial real connection to be online");
|
||||
}
|
||||
await runtime.upsertDirectConnection({ serverId, endpoint });
|
||||
return before.clientGeneration;
|
||||
},
|
||||
{ serverId: getServerId(), endpoint: fasterEndpoint, activeEndpoint: delayedEndpoint },
|
||||
);
|
||||
subscriptions.reset();
|
||||
await advanceToOnlineReplacement(page, delayedPongs, beforeGeneration);
|
||||
await expect
|
||||
.poll(() => readHostConnection(page), { timeout: 3_000 })
|
||||
.toEqual({
|
||||
generation: beforeGeneration + 1,
|
||||
status: "online",
|
||||
connection: `direct:${fasterEndpoint}`,
|
||||
});
|
||||
expect(await connectionObservation.stop()).not.toContain(false);
|
||||
await expectReconnectingToastGone(page, { timeout: 3_000 });
|
||||
await page.screenshot({
|
||||
path: testInfo.outputPath("after-online-connection-replacement.png"),
|
||||
});
|
||||
await subscriptions.waitForSubscribedAgents([scenario.firstAgentId], { match: "includes" });
|
||||
await commitMessage(scenario, scenario.firstAgentId, "FIRST_CHAT_AFTER_REPLACEMENT");
|
||||
await expect(page.getByText("FIRST_CHAT_AFTER_REPLACEMENT", { exact: true })).toBeVisible();
|
||||
await commitMessage(scenario, scenario.secondAgentId, "SECOND_CHAT_WHILE_HIDDEN");
|
||||
await selectAgent(page, "Second viewed chat");
|
||||
await expectReconnectingToastGone(page, { timeout: 3_000 });
|
||||
await expect(page.getByText("SECOND_CHAT_WHILE_HIDDEN", { exact: true })).toBeVisible();
|
||||
await subscriptions.waitForSubscribedAgents([scenario.firstAgentId, scenario.secondAgentId], {
|
||||
match: "includes",
|
||||
});
|
||||
await commitMessage(scenario, scenario.secondAgentId, "SECOND_CHAT_AFTER_REPLACEMENT");
|
||||
await expect(page.getByText("SECOND_CHAT_AFTER_REPLACEMENT", { exact: true })).toBeVisible();
|
||||
await page.screenshot({ path: testInfo.outputPath("both-chats-synchronized.png") });
|
||||
} finally {
|
||||
try {
|
||||
await connectionObservation?.stop();
|
||||
} finally {
|
||||
delayedPongs.dispose();
|
||||
await scenario.cleanup();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("a reloaded layout subscribes only the chat it restores into", async ({ page }) => {
|
||||
test.setTimeout(120_000);
|
||||
const subscriptions = observeTimelineSubscriptions(page);
|
||||
|
||||
@@ -30,7 +30,7 @@ import {
|
||||
pressArchiveShortcut,
|
||||
pressUndoShortcut,
|
||||
readSidebarListLayout,
|
||||
recordLastRowBottomPerFrame,
|
||||
recordLastRowDuringToastExpiry,
|
||||
resizeSidebarToMinimum,
|
||||
rowArchiveButton,
|
||||
rowKebab,
|
||||
@@ -187,7 +187,6 @@ test.describe("Workspace archive undo", () => {
|
||||
test("a long list scrolls its last row clear of the toast, and settles back smoothly after it", async ({
|
||||
page,
|
||||
}) => {
|
||||
await page.clock.install({ time: Date.now() });
|
||||
const fillers: Array<{ path: string; cleanup: () => Promise<void> }> = [];
|
||||
const fillerProjectIds: string[] = [];
|
||||
try {
|
||||
@@ -204,30 +203,30 @@ test.describe("Workspace archive undo", () => {
|
||||
|
||||
await archiveFromRowButton(page, worktree.workspaceId);
|
||||
await page.mouse.move(0, 0);
|
||||
const toastBox = await archivedToast(page).boundingBox();
|
||||
if (!toastBox) throw new Error("Toast is not laid out");
|
||||
// The list keeps its usual end gap, measured from the toast's top instead of its own bottom.
|
||||
// Read both edges together because the sidebar can resize while the toast is open.
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const layout = await scrollSidebarListToEnd(page);
|
||||
const toastBox = await archivedToast(page).boundingBox();
|
||||
if (!toastBox) throw new Error("Toast is not laid out");
|
||||
return Math.round(toastBox.y - layout.rowBottoms.at(-1)!);
|
||||
})
|
||||
.toBe(Math.round(restingEndGap));
|
||||
.toBeGreaterThanOrEqual(Math.round(restingEndGap));
|
||||
|
||||
const frames = recordLastRowBottomPerFrame(page, 40);
|
||||
await outlastUndoWindow(page);
|
||||
const bottoms = await frames;
|
||||
await expect(archivedToast(page)).toHaveCount(0);
|
||||
const bottoms = await recordLastRowDuringToastExpiry(page);
|
||||
|
||||
// Without scrolling again, the list ends just below its last row once more.
|
||||
// Without scrolling again, the list returns to its usual gap below the last row.
|
||||
const settled = await readSidebarListLayout(page);
|
||||
expect(settled.listBottom - settled.rowBottoms.at(-1)!).toBeCloseTo(restingEndGap, 0);
|
||||
// The rows travel down by the toast's height over several frames, never in one jump.
|
||||
const travel = bottoms.at(-1)! - bottoms[0]!;
|
||||
expect(travel).toBeGreaterThan(toastBox.height);
|
||||
const steps = bottoms.slice(1).map((bottom, index) => bottom - bottoms[index]!);
|
||||
const settledBottom = settled.rowBottoms.at(-1)!;
|
||||
expect(settled.listBottom - settledBottom).toBeCloseTo(restingEndGap, 0);
|
||||
|
||||
// The last row moves through an intermediate position without reversing direction.
|
||||
const startBottom = bottoms[0]!;
|
||||
expect(bottoms.some((bottom) => bottom > startBottom && bottom < settledBottom)).toBe(true);
|
||||
const steps = [...bottoms, settledBottom]
|
||||
.slice(1)
|
||||
.map((bottom, index) => bottom - bottoms[index]!);
|
||||
expect(Math.min(...steps)).toBeGreaterThanOrEqual(0);
|
||||
expect(Math.max(...steps)).toBeLessThan(travel / 2);
|
||||
} finally {
|
||||
for (const projectId of fillerProjectIds) {
|
||||
await client.removeProject(projectId).catch(() => undefined);
|
||||
|
||||
@@ -7,9 +7,29 @@ code-to-body size ratio at every heading level; fenced code keeps the code-size
|
||||
token. Bold and links preserve the resulting size. Check the glyphs, not the background height: native backgrounds use
|
||||
line metrics.
|
||||
|
||||
Use a development client rebuilt from this checkout. Follow the temporary entry
|
||||
point and Metro workflow in [status-ring](../status-ring/README.md), importing
|
||||
`MarkdownFormattingRegression` from `./e2e/mobile/markdown-formatting/native`.
|
||||
Use a development client rebuilt from this checkout. In a disposable checkout,
|
||||
temporarily replace `packages/app/index.ts` with:
|
||||
|
||||
```tsx
|
||||
import "./src/polyfills/install-early";
|
||||
import "./src/styles/unistyles";
|
||||
import { registerRootComponent } from "expo";
|
||||
import MarkdownFormattingRegression from "./e2e/mobile/markdown-formatting/native";
|
||||
registerRootComponent(MarkdownFormattingRegression);
|
||||
```
|
||||
|
||||
Start Metro in `packages/app`:
|
||||
|
||||
```sh
|
||||
APP_VARIANT=development npx expo start --localhost --port 8096
|
||||
```
|
||||
|
||||
With one Android emulator running, open that bundle:
|
||||
|
||||
```sh
|
||||
agent-device open sh.paseo.debug 'exp+voice-mobile://expo-development-client/?url=http%3A%2F%2F10.0.2.2%3A8096' --platform android --session <session> --metro-port 8096
|
||||
```
|
||||
|
||||
Open the same Metro URL in a browser to compare web. Restore `index.ts` afterward.
|
||||
|
||||
With this fixture open in an Android Agent Device session, run:
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
# Native retained status-ring regression
|
||||
|
||||
This runs the production native ring and clock inside real retained panels with
|
||||
Reanimated on Android. A probe consumes the same public rotation hook and counts
|
||||
UI-runtime value changes. No Reanimated mocks or provider processes are used.
|
||||
|
||||
Use an Android development client compatible with the checkout's native dependencies.
|
||||
In a disposable checkout, temporarily replace `packages/app/index.ts` with:
|
||||
|
||||
```tsx
|
||||
import "./src/polyfills/install-early";
|
||||
import "./src/styles/unistyles";
|
||||
import { registerRootComponent } from "expo";
|
||||
import NativeRingRegression from "./e2e/mobile/status-ring/native";
|
||||
registerRootComponent(NativeRingRegression);
|
||||
```
|
||||
|
||||
Start Metro in `packages/app`:
|
||||
|
||||
```sh
|
||||
APP_VARIANT=development npx expo start --localhost --port 8096
|
||||
```
|
||||
|
||||
With one Android emulator running, open that bundle:
|
||||
|
||||
```sh
|
||||
agent-device open sh.paseo.debug 'exp+voice-mobile://expo-development-client/?url=http%3A%2F%2F10.0.2.2%3A8096' --platform android --session status-ring --metro-port 8096
|
||||
```
|
||||
|
||||
From the repository root:
|
||||
|
||||
```sh
|
||||
node packages/app/e2e/mobile/status-ring/android.mjs status-ring http://127.0.0.1:8096
|
||||
```
|
||||
|
||||
The test checks visible rotation, hidden-panel inactivity while another ring is
|
||||
visible, inactivity with both panels hidden, and synchronized resumption. Each
|
||||
sample reads counters on the UI runtime; elapsed time includes device-command
|
||||
latency. The baseline fails at the first hidden-panel assertion.
|
||||
|
||||
Restore the original `packages/app/index.ts`, close the agent-device session,
|
||||
and stop Metro afterward. The fixture substitutes running rings for a live agent
|
||||
and toggles retained panels directly; it does not exercise workspace navigation
|
||||
or measure whole-app CPU usage. It is excluded from routine unit tests because
|
||||
it requires a native runtime.
|
||||
@@ -1,71 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { setTimeout as delay } from "node:timers/promises";
|
||||
|
||||
const [, , session, metroUrl] = process.argv;
|
||||
assert(session && metroUrl, "Pass an agent-device session and Metro URL serving native.tsx");
|
||||
function ad(...args) {
|
||||
return execFileSync("agent-device", ["--session", session, ...args], {
|
||||
encoding: "utf8",
|
||||
timeout: 60_000,
|
||||
});
|
||||
}
|
||||
function evaluate(expression) {
|
||||
const value = ad("cdp", "runtime", "eval", "--expr", expression, "--json").trim();
|
||||
return value === "undefined" ? undefined : JSON.parse(value);
|
||||
}
|
||||
let target;
|
||||
const deadline = Date.now() + 30_000;
|
||||
do {
|
||||
target = ad("cdp", "target", "list", "--url", metroUrl)
|
||||
.split("\n")
|
||||
.find((line) => line.includes("sh.paseo.debug"));
|
||||
if (!target) await delay(250);
|
||||
} while (!target && Date.now() < deadline);
|
||||
assert(target, "Open the Android dev client on this Metro bundle first");
|
||||
ad("cdp", "target", "select", target.split(/\s+/)[0]);
|
||||
let ready = false;
|
||||
do {
|
||||
ready = evaluate("Object.keys(globalThis.__ringReaders ?? {}).length === 2");
|
||||
if (!ready) await delay(250);
|
||||
} while (!ready && Date.now() < deadline);
|
||||
assert(ready, "The two native probes must mount before sampling");
|
||||
async function sample() {
|
||||
evaluate("Object.values(globalThis.__ringReaders).forEach(read => read())");
|
||||
await delay(100);
|
||||
return JSON.parse(evaluate("JSON.stringify(globalThis.__ringSamples)"));
|
||||
}
|
||||
async function observe(label) {
|
||||
const before = await sample();
|
||||
await delay(600);
|
||||
const after = await sample();
|
||||
const deltas = Object.fromEntries(
|
||||
Object.keys(before).map((key) => [key, after[key].updates - before[key].updates]),
|
||||
);
|
||||
console.log(JSON.stringify({ label, deltas, after }));
|
||||
return { deltas, after };
|
||||
}
|
||||
const visible = await observe("both visible");
|
||||
assert(visible.deltas.first > 0 && visible.deltas.second > 0);
|
||||
assert.equal(visible.after.first.rotation, visible.after.second.rotation);
|
||||
ad("press", 'label="HIDE FIRST"');
|
||||
await delay(200);
|
||||
const hidden = await observe("first hidden, second visible");
|
||||
assert.equal(hidden.deltas.first, 0, "A retained hidden ring must stop UI-thread rotation updates");
|
||||
assert(hidden.deltas.second > 0, "Visible rings must continue rotating");
|
||||
ad("press", 'label="HIDE SECOND"');
|
||||
await delay(200);
|
||||
const allHidden = await observe("both hidden");
|
||||
assert.equal(allHidden.deltas.first, 0);
|
||||
assert.equal(allHidden.deltas.second, 0);
|
||||
ad("press", 'label="SHOW FIRST"');
|
||||
ad("press", 'label="SHOW SECOND"');
|
||||
await delay(200);
|
||||
const restored = await observe("both shown again");
|
||||
assert(restored.deltas.first > 0 && restored.deltas.second > 0);
|
||||
assert.equal(
|
||||
restored.after.first.rotation,
|
||||
restored.after.second.rotation,
|
||||
"Restored rings must share the current phase",
|
||||
);
|
||||
console.log("PASS native retained-ring lifecycle");
|
||||
@@ -1,69 +0,0 @@
|
||||
import { useCallback, useLayoutEffect, useState } from "react";
|
||||
import { Button, Text, View } from "react-native";
|
||||
import { useAnimatedReaction, useSharedValue } from "react-native-reanimated";
|
||||
import { scheduleOnRN, scheduleOnUI } from "react-native-worklets";
|
||||
import { RetainedPanel } from "@/components/retained-panel";
|
||||
import { useStatusRingRotation } from "@/components/status-ring/clock";
|
||||
import { StatusRing } from "@/components/status-ring";
|
||||
|
||||
interface Sample {
|
||||
updates: number;
|
||||
rotation: number;
|
||||
}
|
||||
|
||||
declare global {
|
||||
var __ringSamples: Record<string, Sample>;
|
||||
var __ringReaders: Record<string, () => void>;
|
||||
}
|
||||
|
||||
function recordSample(name: string, value: { updates: number; rotation: number }) {
|
||||
globalThis.__ringSamples[name] = value;
|
||||
}
|
||||
|
||||
function Probe({ name }: { name: string }) {
|
||||
const rotation = useStatusRingRotation();
|
||||
const updates = useSharedValue(0);
|
||||
useAnimatedReaction(
|
||||
() => rotation.value,
|
||||
() => {
|
||||
updates.value += 1;
|
||||
},
|
||||
);
|
||||
// Read the real UI runtime, without scheduling a continuous JS observer.
|
||||
useLayoutEffect(() => {
|
||||
globalThis.__ringSamples ??= {};
|
||||
globalThis.__ringReaders ??= {};
|
||||
globalThis.__ringReaders[name] = () =>
|
||||
scheduleOnUI(() => {
|
||||
"worklet";
|
||||
const sample = { updates: updates.value, rotation: rotation.value };
|
||||
scheduleOnRN(recordSample, name, sample);
|
||||
});
|
||||
return () => {
|
||||
delete globalThis.__ringReaders[name];
|
||||
};
|
||||
}, [name, rotation, updates]);
|
||||
return <StatusRing />;
|
||||
}
|
||||
|
||||
const containerStyle = { flex: 1, padding: 60, backgroundColor: "white" };
|
||||
|
||||
export default function NativeRingRegression() {
|
||||
const [first, setFirst] = useState(true);
|
||||
const [second, setSecond] = useState(true);
|
||||
const toggleFirst = useCallback(() => setFirst((value) => !value), []);
|
||||
const toggleSecond = useCallback(() => setSecond((value) => !value), []);
|
||||
return (
|
||||
<View style={containerStyle}>
|
||||
<Text>Native retained status rings</Text>
|
||||
<Button title={first ? "Hide first" : "Show first"} onPress={toggleFirst} />
|
||||
<Button title={second ? "Hide second" : "Show second"} onPress={toggleSecond} />
|
||||
<RetainedPanel active={first}>
|
||||
<Probe name="first" />
|
||||
</RetainedPanel>
|
||||
<RetainedPanel active={second}>
|
||||
<Probe name="second" />
|
||||
</RetainedPanel>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -4,6 +4,10 @@ import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { expect, type Locator, type Page } from "@playwright/test";
|
||||
import type { DaemonClient as InternalDaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import type {
|
||||
MutableDaemonToolGroups,
|
||||
MutableDaemonToolsConfigPatch,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
import { addProjectFlow, addProjectFlowInput, expectAddProjectTab } from "./add-project-flow";
|
||||
import { connectDaemonClient } from "./daemon-client-loader";
|
||||
import { buildCreateAgentPreferences, buildSeededHost } from "./daemon-registry";
|
||||
@@ -138,7 +142,7 @@ export async function goToSetupStep(page: Page, label: string): Promise<void> {
|
||||
}
|
||||
|
||||
export function paseoToolsSwitch(scope: Page | Locator): Locator {
|
||||
return scope.getByRole("switch", { name: "Inject Paseo tools", exact: true });
|
||||
return scope.getByRole("switch", { name: "Enable tools", exact: true });
|
||||
}
|
||||
|
||||
/** Whether the host gives its agents Paseo tools, read from the host itself. */
|
||||
@@ -147,7 +151,37 @@ export async function hostGivesAgentsPaseoTools(host: { port: number }): Promise
|
||||
Pick<InternalDaemonClient, "connect" | "close" | "getDaemonConfig">
|
||||
>({ clientIdPrefix: "app-e2e-onboarding", port: host.port });
|
||||
try {
|
||||
return (await client.getDaemonConfig()).config.mcp.injectIntoAgents !== false;
|
||||
const config = (await client.getDaemonConfig()).config;
|
||||
return config.tools?.enabled ?? config.mcp.injectIntoAgents !== false;
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
}
|
||||
|
||||
/** The host's saved tool groups, read from the host itself. */
|
||||
export async function hostToolGroups(host: {
|
||||
port: number;
|
||||
}): Promise<MutableDaemonToolGroups | undefined> {
|
||||
const client = await connectDaemonClient<
|
||||
Pick<InternalDaemonClient, "connect" | "close" | "getDaemonConfig">
|
||||
>({ clientIdPrefix: "app-e2e-onboarding", port: host.port });
|
||||
try {
|
||||
return (await client.getDaemonConfig()).config.tools?.groups;
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
}
|
||||
|
||||
/** Saves tool settings on the host, the way Settings does. */
|
||||
export async function setHostTools(
|
||||
host: { port: number },
|
||||
tools: MutableDaemonToolsConfigPatch,
|
||||
): Promise<void> {
|
||||
const client = await connectDaemonClient<
|
||||
Pick<InternalDaemonClient, "connect" | "close" | "patchDaemonConfig">
|
||||
>({ clientIdPrefix: "app-e2e-onboarding", port: host.port });
|
||||
try {
|
||||
await client.patchDaemonConfig({ tools });
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { expect, type Locator, type Page } from "@playwright/test";
|
||||
import {
|
||||
SYNCED_LOADER_DOT_COUNT,
|
||||
getSyncedLoaderDotOpacity,
|
||||
} from "../../../src/components/synced-loader/state";
|
||||
import { expectComposerVisible } from "./composer";
|
||||
import { openAgentRoute, seedMockAgentWorkspace, type MockAgentWorkspace } from "./mock-agent";
|
||||
|
||||
const HELD_TOOL_CALL_PROMPT = "Hold a running shell tool call for 600000ms.";
|
||||
|
||||
export function workingLoader(page: Page): Locator {
|
||||
return page.getByTestId("synced-loader").filter({ visible: true });
|
||||
}
|
||||
|
||||
function loaderDots(page: Page): Locator {
|
||||
return page.getByTestId("synced-loader-dot").filter({ visible: true });
|
||||
}
|
||||
|
||||
export function statusRings(page: Page): Locator {
|
||||
return page.getByTestId("status-ring").filter({ visible: true });
|
||||
}
|
||||
|
||||
export function runningToolCall(page: Page): Locator {
|
||||
return page.getByTestId("tool-call-badge").last();
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens an agent whose turn is one running tool call and nothing else: the six-dot loader, the
|
||||
* tool-call label shimmer and the status rings are all on screen, and nothing streams.
|
||||
*/
|
||||
export async function openQuietRunningTurn(page: Page): Promise<MockAgentWorkspace> {
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "running-indicators-",
|
||||
title: "Running indicators",
|
||||
});
|
||||
try {
|
||||
await openAgentRoute(page, { workspaceId: agent.workspaceId, agentId: agent.agentId });
|
||||
await expectComposerVisible(page);
|
||||
await agent.client.sendAgentMessage(agent.agentId, HELD_TOOL_CALL_PROMPT);
|
||||
await expect(workingLoader(page)).toBeVisible({ timeout: 30_000 });
|
||||
await expect(runningToolCall(page)).toBeVisible();
|
||||
await expect(statusRings(page).first()).toBeVisible();
|
||||
// Park the pointer on empty chat so no hover state repaints during a measurement.
|
||||
await page.mouse.move(900, 300);
|
||||
return agent;
|
||||
} catch (error) {
|
||||
await agent.cleanup();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/** The loader's current step, or null while the dots are between two readable states. */
|
||||
export async function readLoaderStep(page: Page): Promise<number | null> {
|
||||
const opacities = await loaderDots(page).evaluateAll((dots) =>
|
||||
dots.map((dot) => Number.parseFloat(getComputedStyle(dot).opacity)),
|
||||
);
|
||||
if (opacities.length !== SYNCED_LOADER_DOT_COUNT) {
|
||||
throw new Error(`Expected ${SYNCED_LOADER_DOT_COUNT} loader dots, found ${opacities.length}`);
|
||||
}
|
||||
for (let step = 0; step < SYNCED_LOADER_DOT_COUNT; step += 1) {
|
||||
const matches = opacities.every(
|
||||
(opacity, dot) => Math.abs(opacity - getSyncedLoaderDotOpacity(step, dot)) < 0.005,
|
||||
);
|
||||
if (matches) {
|
||||
return step;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export interface LoaderStepChange {
|
||||
step: number;
|
||||
atMs: number;
|
||||
}
|
||||
|
||||
/** Every step change the loader shows over the window, timestamped on the page's clock. */
|
||||
export async function recordLoaderStepChanges(
|
||||
page: Page,
|
||||
windowMs: number,
|
||||
): Promise<LoaderStepChange[]> {
|
||||
const states = Array.from({ length: SYNCED_LOADER_DOT_COUNT }, (_, step) =>
|
||||
Array.from({ length: SYNCED_LOADER_DOT_COUNT }, (__, dot) =>
|
||||
getSyncedLoaderDotOpacity(step, dot),
|
||||
),
|
||||
);
|
||||
return loaderDots(page).evaluateAll(
|
||||
(dots, input) =>
|
||||
new Promise<LoaderStepChange[]>((resolve) => {
|
||||
const readStep = () => {
|
||||
const opacities = dots.map((dot) => Number.parseFloat(getComputedStyle(dot).opacity));
|
||||
return input.states.findIndex((state) =>
|
||||
state.every((opacity, dot) => Math.abs(opacity - opacities[dot]) < 0.005),
|
||||
);
|
||||
};
|
||||
const changes: LoaderStepChange[] = [];
|
||||
const startedAt = performance.now();
|
||||
const sample = () => {
|
||||
const atMs = performance.now() - startedAt;
|
||||
const step = readStep();
|
||||
if (step !== -1 && step !== changes.at(-1)?.step) {
|
||||
changes.push({ step, atMs });
|
||||
}
|
||||
if (atMs >= input.windowMs) {
|
||||
resolve(changes);
|
||||
return;
|
||||
}
|
||||
requestAnimationFrame(sample);
|
||||
};
|
||||
sample();
|
||||
}),
|
||||
{ states, windowMs },
|
||||
);
|
||||
}
|
||||
|
||||
export interface RunningAnimation {
|
||||
name: string;
|
||||
target: string;
|
||||
durationMs: number;
|
||||
easing: string;
|
||||
iterations: number;
|
||||
properties: string[];
|
||||
}
|
||||
|
||||
/** Every animation the document is currently running, by what it animates. */
|
||||
export async function readRunningAnimations(page: Page): Promise<RunningAnimation[]> {
|
||||
return page.evaluate(() => {
|
||||
const timingKeys = new Set(["offset", "computedOffset", "easing", "composite"]);
|
||||
const running: RunningAnimation[] = [];
|
||||
for (const animation of document.getAnimations()) {
|
||||
const effect = animation.effect;
|
||||
if (animation.playState !== "running" || !(effect instanceof KeyframeEffect)) {
|
||||
continue;
|
||||
}
|
||||
const properties = new Set<string>();
|
||||
for (const keyframe of effect.getKeyframes()) {
|
||||
for (const key of Object.keys(keyframe)) {
|
||||
if (!timingKeys.has(key)) {
|
||||
properties.add(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
const timing = effect.getComputedTiming();
|
||||
const target = effect.target;
|
||||
running.push({
|
||||
name: animation instanceof CSSAnimation ? animation.animationName : "script",
|
||||
target:
|
||||
target?.closest("[data-testid]")?.getAttribute("data-testid") ?? target?.tagName ?? "",
|
||||
durationMs: Number(timing.duration),
|
||||
easing: String(timing.easing),
|
||||
iterations: Number(timing.iterations),
|
||||
properties: [...properties],
|
||||
});
|
||||
}
|
||||
return running;
|
||||
});
|
||||
}
|
||||
|
||||
/** What is currently animating, by test id. */
|
||||
export async function readAnimatingTargets(page: Page): Promise<string[]> {
|
||||
const animations = await readRunningAnimations(page);
|
||||
return animations.map((animation) => animation.target);
|
||||
}
|
||||
|
||||
/** Freezes every running animation at the same point of its cycle so a frame can be compared. */
|
||||
export async function freezeAnimationsAt(page: Page, progress: number): Promise<void> {
|
||||
await page.evaluate(async (cycleProgress) => {
|
||||
for (const animation of document.getAnimations()) {
|
||||
const duration = Number(animation.effect?.getComputedTiming().duration);
|
||||
animation.pause();
|
||||
animation.currentTime = duration * cycleProgress;
|
||||
}
|
||||
await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
|
||||
}, progress);
|
||||
}
|
||||
|
||||
/** Saves one image of the loader for each of its steps, named by step. */
|
||||
export async function captureLoaderSteps(
|
||||
page: Page,
|
||||
pathForStep: (step: number) => string,
|
||||
): Promise<number[]> {
|
||||
const loader = workingLoader(page);
|
||||
const captured = new Set<number>();
|
||||
for (let attempt = 0; attempt < 200 && captured.size < SYNCED_LOADER_DOT_COUNT; attempt += 1) {
|
||||
const before = await readLoaderStep(page);
|
||||
if (before === null || captured.has(before)) {
|
||||
continue;
|
||||
}
|
||||
const image = await loader.screenshot();
|
||||
// The step can turn over mid-capture; only an image bracketed by one step is that step.
|
||||
if ((await readLoaderStep(page)) !== before) {
|
||||
continue;
|
||||
}
|
||||
await writeFile(pathForStep(before), image);
|
||||
captured.add(before);
|
||||
}
|
||||
return [...captured].sort((a, b) => a - b);
|
||||
}
|
||||
@@ -519,7 +519,7 @@ export async function expectHostConnectionsCard(page: Page, port: string): Promi
|
||||
export async function expectHostInjectMcpCard(page: Page): Promise<void> {
|
||||
const card = page.getByTestId("host-page-inject-mcp-card");
|
||||
await expect(card).toBeVisible();
|
||||
await expect(card.getByRole("switch", { name: "Inject Paseo tools" })).toBeVisible();
|
||||
await expect(card.getByRole("switch", { name: "Enable tools" })).toBeVisible();
|
||||
}
|
||||
|
||||
function idleAgentReleaseSwitch(page: Page) {
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
import type { Browser, CDPSession, Page } from "@playwright/test";
|
||||
|
||||
/**
|
||||
* What a page costs while nothing on it is supposed to be changing: how often the main thread is
|
||||
* woken, how much it restyles and repaints, and how much CPU the renderer burns doing it.
|
||||
* Rates are per second of the sampled window.
|
||||
*/
|
||||
export interface SteadyStateActivity {
|
||||
animationFrameCallbacksPerSecond: number;
|
||||
timerCallbacksPerSecond: number;
|
||||
styleRecalcsPerSecond: number;
|
||||
layoutsPerSecond: number;
|
||||
paintsPerSecond: number;
|
||||
/** Repainted area per second, in viewports. */
|
||||
paintedViewportsPerSecond: number;
|
||||
/** Times the main thread committed new work to the compositor. */
|
||||
mainThreadCommitsPerSecond: number;
|
||||
rasterTasksPerSecond: number;
|
||||
/** Frames the compositor drew, with or without the main thread. */
|
||||
compositorFramesPerSecond: number;
|
||||
mainThreadBusyMsPerSecond: number;
|
||||
rendererCpuPercent: number;
|
||||
gpuCpuPercent: number;
|
||||
}
|
||||
|
||||
interface TraceEvent {
|
||||
name: string;
|
||||
ph: string;
|
||||
pid: number;
|
||||
args?: {
|
||||
data?: {
|
||||
clip?: number[];
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
const TRACE_CATEGORIES = [
|
||||
"devtools.timeline",
|
||||
"disabled-by-default-devtools.timeline",
|
||||
"disabled-by-default-devtools.timeline.frame",
|
||||
];
|
||||
|
||||
async function readProcessCpuSeconds(session: CDPSession): Promise<Map<string, number>> {
|
||||
const { processInfo } = await session.send("SystemInfo.getProcessInfo");
|
||||
const cpuByType = new Map<string, number>();
|
||||
for (const process of processInfo) {
|
||||
cpuByType.set(process.type, (cpuByType.get(process.type) ?? 0) + process.cpuTime);
|
||||
}
|
||||
return cpuByType;
|
||||
}
|
||||
|
||||
async function readMainThreadBusySeconds(session: CDPSession): Promise<number> {
|
||||
const { metrics } = await session.send("Performance.getMetrics");
|
||||
return metrics.find((metric) => metric.name === "TaskDuration")?.value ?? 0;
|
||||
}
|
||||
|
||||
function quadArea(clip: number[] | undefined): number {
|
||||
if (!clip || clip.length !== 8) {
|
||||
return 0;
|
||||
}
|
||||
const xs = [clip[0], clip[2], clip[4], clip[6]];
|
||||
const ys = [clip[1], clip[3], clip[5], clip[7]];
|
||||
return (Math.max(...xs) - Math.min(...xs)) * (Math.max(...ys) - Math.min(...ys));
|
||||
}
|
||||
|
||||
function summarizeTrace(input: {
|
||||
events: TraceEvent[];
|
||||
seconds: number;
|
||||
viewportArea: number;
|
||||
}): Pick<
|
||||
SteadyStateActivity,
|
||||
| "animationFrameCallbacksPerSecond"
|
||||
| "timerCallbacksPerSecond"
|
||||
| "styleRecalcsPerSecond"
|
||||
| "layoutsPerSecond"
|
||||
| "paintsPerSecond"
|
||||
| "paintedViewportsPerSecond"
|
||||
| "mainThreadCommitsPerSecond"
|
||||
| "rasterTasksPerSecond"
|
||||
| "compositorFramesPerSecond"
|
||||
> {
|
||||
const { events, seconds, viewportArea } = input;
|
||||
const counts = new Map<string, number>();
|
||||
let paintedArea = 0;
|
||||
for (const event of events) {
|
||||
// "B"/"X" open a slice and "I" is an instant; skipping "E" keeps begin/end pairs at one count.
|
||||
if (event.ph === "E") {
|
||||
continue;
|
||||
}
|
||||
counts.set(event.name, (counts.get(event.name) ?? 0) + 1);
|
||||
if (event.name === "Paint") {
|
||||
paintedArea += quadArea(event.args?.data?.clip);
|
||||
}
|
||||
}
|
||||
const perSecond = (name: string) => (counts.get(name) ?? 0) / seconds;
|
||||
return {
|
||||
animationFrameCallbacksPerSecond: perSecond("FireAnimationFrame"),
|
||||
timerCallbacksPerSecond: perSecond("TimerFire"),
|
||||
styleRecalcsPerSecond: perSecond("UpdateLayoutTree"),
|
||||
layoutsPerSecond: perSecond("Layout"),
|
||||
paintsPerSecond: perSecond("Paint"),
|
||||
paintedViewportsPerSecond: paintedArea / viewportArea / seconds,
|
||||
mainThreadCommitsPerSecond: perSecond("BeginCommitCompositorFrame"),
|
||||
rasterTasksPerSecond: perSecond("RasterTask"),
|
||||
compositorFramesPerSecond: perSecond("DrawFrame"),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Samples the page twice: once untraced for CPU and main-thread time, so the tracer's own cost
|
||||
* stays out of those numbers, then once traced for the per-event counts.
|
||||
*/
|
||||
export async function measureSteadyStateActivity(input: {
|
||||
browser: Browser;
|
||||
page: Page;
|
||||
windowMs: number;
|
||||
}): Promise<SteadyStateActivity> {
|
||||
const { browser, page, windowMs } = input;
|
||||
const seconds = windowMs / 1000;
|
||||
const viewport = page.viewportSize();
|
||||
if (!viewport) {
|
||||
throw new Error("Steady-state activity needs a fixed viewport");
|
||||
}
|
||||
|
||||
const pageSession = await page.context().newCDPSession(page);
|
||||
const browserSession = await browser.newBrowserCDPSession();
|
||||
try {
|
||||
await pageSession.send("Performance.enable");
|
||||
const cpuBefore = await readProcessCpuSeconds(browserSession);
|
||||
const busyBefore = await readMainThreadBusySeconds(pageSession);
|
||||
await page.waitForTimeout(windowMs);
|
||||
const busyAfter = await readMainThreadBusySeconds(pageSession);
|
||||
const cpuAfter = await readProcessCpuSeconds(browserSession);
|
||||
|
||||
await browser.startTracing(page, { categories: TRACE_CATEGORIES });
|
||||
await page.waitForTimeout(windowMs);
|
||||
const trace = JSON.parse((await browser.stopTracing()).toString("utf8")) as {
|
||||
traceEvents: TraceEvent[];
|
||||
};
|
||||
|
||||
const cpuPercent = (type: string) =>
|
||||
(((cpuAfter.get(type) ?? 0) - (cpuBefore.get(type) ?? 0)) / seconds) * 100;
|
||||
return {
|
||||
...summarizeTrace({
|
||||
events: trace.traceEvents,
|
||||
seconds,
|
||||
viewportArea: viewport.width * viewport.height,
|
||||
}),
|
||||
mainThreadBusyMsPerSecond: ((busyAfter - busyBefore) * 1000) / seconds,
|
||||
rendererCpuPercent: cpuPercent("renderer"),
|
||||
gpuCpuPercent: cpuPercent("GPU"),
|
||||
};
|
||||
} finally {
|
||||
await pageSession.detach().catch(() => undefined);
|
||||
await browserSession.detach().catch(() => undefined);
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ interface SessionMessage {
|
||||
|
||||
interface TimelineSubscriptionWaitOptions {
|
||||
timeout?: number;
|
||||
match?: "exact" | "includes";
|
||||
}
|
||||
|
||||
function readSessionMessage(message: WebSocketMessage): SessionMessage | null {
|
||||
@@ -56,7 +57,7 @@ export function observeTimelineSubscriptions(page: Page) {
|
||||
.poll(() => acknowledgedAgentIds?.slice().sort() ?? null, {
|
||||
timeout: options.timeout ?? 15_000,
|
||||
})
|
||||
.toEqual(expected);
|
||||
.toEqual(options.match === "includes" ? expect.arrayContaining(expected) : expected);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -204,25 +204,25 @@ export async function readSidebarListLayout(page: Page): Promise<SidebarListLayo
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts recording the bottom edge of the sidebar list's last row once per painted frame.
|
||||
* Resolves with one value per frame after `frameCount` frames.
|
||||
*/
|
||||
export function recordLastRowBottomPerFrame(page: Page, frameCount: number): Promise<number[]> {
|
||||
/** Records the last row's positions until the archive toast finishes fading out. */
|
||||
export function recordLastRowDuringToastExpiry(page: Page): Promise<number[]> {
|
||||
return page.getByTestId(SIDEBAR_LIST).evaluate(
|
||||
(element, count) =>
|
||||
(element) =>
|
||||
new Promise<number[]>((resolve) => {
|
||||
const bottoms: number[] = [];
|
||||
const sample = () => {
|
||||
const rows = element.querySelectorAll<HTMLElement>(
|
||||
'[data-testid^="sidebar-workspace-row-"],[data-testid^="sidebar-project-row-"]',
|
||||
);
|
||||
bottoms.push(Math.max(...Array.from(rows, (row) => row.getBoundingClientRect().bottom)));
|
||||
if (bottoms.length >= count) resolve(bottoms);
|
||||
else requestAnimationFrame(sample);
|
||||
const bottom = Math.max(...Array.from(rows, (row) => row.getBoundingClientRect().bottom));
|
||||
if (bottom !== bottoms.at(-1)) bottoms.push(bottom);
|
||||
if (document.querySelector('[data-testid="workspace-archived-toast"]')) {
|
||||
requestAnimationFrame(sample);
|
||||
} else {
|
||||
resolve(bottoms);
|
||||
}
|
||||
};
|
||||
requestAnimationFrame(sample);
|
||||
sample();
|
||||
}),
|
||||
frameCount,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -954,6 +954,19 @@ it("keeps table cell pipes escaped in text/plain table syntax and literal in tex
|
||||
expect(content?.html).toContain("<td>Value | detail</td>");
|
||||
});
|
||||
|
||||
it("keeps a table cell's line breaks inside its row", () => {
|
||||
const message = mountFixture();
|
||||
message.innerHTML =
|
||||
"<table><thead><tr><th>Name<br>label</th><th>Note</th></tr></thead><tbody><tr><td>first<br>second</td><td><br> stays text</td></tr></tbody></table>";
|
||||
const content = createAssistantSelectionClipboardContent(selectNodeContents(message));
|
||||
expect(content?.plainText).toBe(
|
||||
"| Name<br>label | Note |\n| --- | --- |\n| first<br>second | <br> stays text |",
|
||||
);
|
||||
expect(content?.html).toContain("<th>Name<br>\nlabel</th>");
|
||||
expect(content?.html).toContain("<td>first<br>\nsecond</td>");
|
||||
expect(content?.html).toContain("<td><br> stays text</td>");
|
||||
});
|
||||
|
||||
it("copies a workspace image path instead of its temporary display URL", () => {
|
||||
const message = mountFixture();
|
||||
const sources = JSON.stringify({ "blob:preview": "assets/chart.png" });
|
||||
|
||||
@@ -69,12 +69,13 @@ function createTurndown(flavor: "markdown" | "plain"): TurndownService {
|
||||
});
|
||||
turndown.use(gfm);
|
||||
// text/plain still carries tables as GFM syntax, so a cell's pipe stays escaped there.
|
||||
// A row is one line, so a cell's line break goes back to `<br>`.
|
||||
turndown.addRule("escapedGfmTableCell", {
|
||||
filter: ["th", "td"],
|
||||
replacement: (content, node) => {
|
||||
const index = node.parentNode ? Array.from(node.parentNode.childNodes).indexOf(node) : 0;
|
||||
const prefix = index === 0 ? "| " : " ";
|
||||
return `${prefix}${content.replace(/\|/g, "\\|")} |`;
|
||||
return `${prefix}${content.replace(/\|/g, "\\|").replace(/ *\n/g, "<br>")} |`;
|
||||
},
|
||||
});
|
||||
// A link Paseo recognized pastes as the text the reply showed. Rich paste keeps it as a
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { useEffect } from "react";
|
||||
import { Animated } from "react-native";
|
||||
|
||||
// A decay that never slows is a clock: with a velocity of one unit per millisecond the value is the
|
||||
// time since it started. Decay is the one native-driven animation that computes its value from the
|
||||
// frame's timestamp instead of replaying a 60 fps recording, so the motion is exact at any refresh
|
||||
// rate and never ends or loops.
|
||||
const CLOCK_CONFIG = { velocity: 1, deceleration: 1 - 1e-12, useNativeDriver: true };
|
||||
|
||||
/**
|
||||
* Milliseconds, counted on the UI thread by React Native's native animation driver.
|
||||
*
|
||||
* Views bound to it are updated by the native driver directly. Nothing reaches the JS thread, React
|
||||
* does not render, and no shadow tree is committed — which is what a Reanimated shared value costs
|
||||
* on every frame it changes.
|
||||
*/
|
||||
export interface IndicatorClock {
|
||||
/** Where a cycle of `periodMs` currently is, as milliseconds into the cycle. */
|
||||
cycle(periodMs: number): Animated.AnimatedModulo<number>;
|
||||
/** Runs the clock until the returned function is called. It restarts from zero when idle. */
|
||||
run(): () => void;
|
||||
}
|
||||
|
||||
export function createIndicatorClock(): IndicatorClock {
|
||||
const elapsedMs = new Animated.Value(0, { useNativeDriver: true });
|
||||
let runners = 0;
|
||||
let ticking: Animated.CompositeAnimation | null = null;
|
||||
|
||||
return {
|
||||
cycle(periodMs) {
|
||||
return Animated.modulo(elapsedMs, periodMs);
|
||||
},
|
||||
run() {
|
||||
runners += 1;
|
||||
if (!ticking) {
|
||||
elapsedMs.setValue(0);
|
||||
ticking = Animated.decay(elapsedMs, CLOCK_CONFIG);
|
||||
ticking.start();
|
||||
}
|
||||
return () => {
|
||||
runners -= 1;
|
||||
if (runners === 0) {
|
||||
ticking?.stop();
|
||||
ticking = null;
|
||||
}
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** One clock for indicators that must move as one, wherever they are on screen. */
|
||||
export const sharedIndicatorClock = createIndicatorClock();
|
||||
|
||||
/** Runs the clock for as long as an indicator bound to it is moving. */
|
||||
export function useRunningClock(clock: IndicatorClock, moving: boolean): void {
|
||||
useEffect(() => {
|
||||
if (!moving) return;
|
||||
return clock.run();
|
||||
}, [clock, moving]);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { useSyncExternalStore } from "react";
|
||||
import { AccessibilityInfo } from "react-native";
|
||||
import { useReducedMotion as useReducedMotionAtLaunch } from "react-native-reanimated";
|
||||
import { useRetainedPanelActive } from "@/components/retained-panel";
|
||||
import { useAppVisible } from "@/hooks/use-app-visible";
|
||||
|
||||
// Reanimated knows the setting synchronously but only as it was at launch; React Native reports
|
||||
// every later change but answers the first question asynchronously. Together they are right from
|
||||
// the first render onwards.
|
||||
let reducedMotionSinceLaunch: boolean | null = null;
|
||||
const reducedMotionListeners = new Set<() => void>();
|
||||
|
||||
AccessibilityInfo.addEventListener("reduceMotionChanged", (reducedMotion) => {
|
||||
reducedMotionSinceLaunch = reducedMotion;
|
||||
for (const listener of reducedMotionListeners) listener();
|
||||
});
|
||||
|
||||
function subscribeToReducedMotion(listener: () => void): () => void {
|
||||
reducedMotionListeners.add(listener);
|
||||
return () => reducedMotionListeners.delete(listener);
|
||||
}
|
||||
|
||||
function getReducedMotionSinceLaunch(): boolean | null {
|
||||
return reducedMotionSinceLaunch;
|
||||
}
|
||||
|
||||
function useReducedMotion(): boolean {
|
||||
const atLaunch = useReducedMotionAtLaunch();
|
||||
const sinceLaunch = useSyncExternalStore(
|
||||
subscribeToReducedMotion,
|
||||
getReducedMotionSinceLaunch,
|
||||
getReducedMotionSinceLaunch,
|
||||
);
|
||||
return sinceLaunch ?? atLaunch;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a running indicator may move right now. It holds still when the system asks for reduced
|
||||
* motion, and while nobody can see it: in a retained panel that is not showing, or in an app that
|
||||
* is in the background.
|
||||
*
|
||||
* An indicator that is not moving draws its resting frame and runs nothing.
|
||||
*/
|
||||
export function useIndicatorMotion(): boolean {
|
||||
const panelActive = useRetainedPanelActive();
|
||||
const appVisible = useAppVisible();
|
||||
const reducedMotion = useReducedMotion();
|
||||
return panelActive && appVisible && !reducedMotion;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { useLayoutEffect, useRef, type RefObject } from "react";
|
||||
import type { View } from "react-native";
|
||||
|
||||
const TIMELINE_ORIGIN_MS = 0;
|
||||
|
||||
export interface IndicatorLoop {
|
||||
/** One cycle. Keep the array's identity stable: a new array restarts the loop. */
|
||||
keyframes: Keyframe[];
|
||||
durationMs: number;
|
||||
/**
|
||||
* `shared` puts every instance at the same point of the cycle, wherever and whenever it mounted:
|
||||
* the loop counts from the document timeline's origin instead of from its own start. `own` starts
|
||||
* the cycle when the loop does.
|
||||
*/
|
||||
phase: "shared" | "own";
|
||||
}
|
||||
|
||||
/**
|
||||
* Repeats `loop` on the element the returned ref is attached to, for as long as `loop` is given.
|
||||
*
|
||||
* The browser's animation engine runs it. A loop over `transform` or `opacity` is carried by the
|
||||
* compositor, so the page does no work per frame: no script, no style, no paint.
|
||||
*
|
||||
* It is declared through the Web Animations API, not a CSS `@keyframes` rule, on purpose. A CSS
|
||||
* animation fires `animationiteration`, React listens for that event at the root, and a document
|
||||
* with a listener for it makes Chromium bring the main thread up around the end of every cycle of
|
||||
* every CSS animation. A script-declared animation has no such event and never wakes it.
|
||||
*/
|
||||
export function useIndicatorLoop(loop: IndicatorLoop | null): RefObject<View | null> {
|
||||
const target = useRef<View | null>(null);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const element: unknown = target.current;
|
||||
if (!loop || !(element instanceof HTMLElement)) {
|
||||
return;
|
||||
}
|
||||
const animation = element.animate(loop.keyframes, {
|
||||
duration: loop.durationMs,
|
||||
iterations: Number.POSITIVE_INFINITY,
|
||||
});
|
||||
// An explicit start also keeps loops that start in the same commit exactly together.
|
||||
animation.startTime =
|
||||
loop.phase === "shared" ? TIMELINE_ORIGIN_MS : document.timeline.currentTime;
|
||||
return () => {
|
||||
animation.cancel();
|
||||
};
|
||||
}, [loop]);
|
||||
|
||||
return target;
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
import { memo, useMemo, useState } from "react";
|
||||
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 { createIndicatorClock, useRunningClock } from "@/components/indicator-motion/clock";
|
||||
import { type LabelShimmerProps, getRowSweep, getShimmerDurationMs } from "./sweep";
|
||||
|
||||
export { useLabelMeasurements } from "./measurements";
|
||||
|
||||
const MASK_TEXT = { color: "#000000", opacity: 1 };
|
||||
|
||||
// Plain React Native styles: the band is an `Animated.View` the native animation driver writes to,
|
||||
// and a theme-tracked style on the same node gives it two writers. See docs/unistyles.md.
|
||||
const styles = StyleSheet.create({
|
||||
overlay: {
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
overflow: "hidden",
|
||||
},
|
||||
track: {
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
overflow: "hidden",
|
||||
},
|
||||
maskRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
},
|
||||
band: {
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
},
|
||||
spacer: {
|
||||
flex: 1,
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Native label shimmer: a gradient band slides behind a mask cut in the shape of the label. The
|
||||
* native animation driver moves the band; see `indicator-motion/clock.ts`. Each shimmer has its own
|
||||
* clock so the highlight enters from the left when the label appears.
|
||||
*/
|
||||
export const LabelShimmer = memo(function LabelShimmer({
|
||||
label,
|
||||
secondaryLabel,
|
||||
labelStyle,
|
||||
secondaryLabelStyle,
|
||||
measurements,
|
||||
}: LabelShimmerProps) {
|
||||
const { rowSize } = measurements;
|
||||
const measured = rowSize.width > 0 && rowSize.height > 0;
|
||||
const moving = useIndicatorMotion() && measured;
|
||||
const [clock] = useState(createIndicatorClock);
|
||||
const [gradientId] = useState(
|
||||
() => `shimmer-gradient-${Math.random().toString(36).substring(2, 9)}`,
|
||||
);
|
||||
useRunningClock(clock, moving);
|
||||
|
||||
const durationMs = getShimmerDurationMs(label, secondaryLabel);
|
||||
const { peakWidth, fromX, toX } = getRowSweep(rowSize.width);
|
||||
const { width, height } = rowSize;
|
||||
|
||||
const trackStyle = useMemo(() => [styles.track, { width, height }], [height, width]);
|
||||
const bandStyle = useMemo(
|
||||
() => [
|
||||
styles.band,
|
||||
{ width: peakWidth, height },
|
||||
{
|
||||
transform: [
|
||||
{
|
||||
translateX: clock.cycle(durationMs).interpolate({
|
||||
inputRange: [0, durationMs],
|
||||
outputRange: [fromX, toX],
|
||||
}),
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
[clock, durationMs, fromX, height, peakWidth, toX],
|
||||
);
|
||||
const maskElement = useMemo(
|
||||
() => (
|
||||
<View pointerEvents="none" style={[styles.maskRow, { width, height }]}>
|
||||
<Text style={[labelStyle, MASK_TEXT]} numberOfLines={1}>
|
||||
{label}
|
||||
</Text>
|
||||
{secondaryLabel ? (
|
||||
<Text style={[secondaryLabelStyle, MASK_TEXT]} numberOfLines={1}>
|
||||
{secondaryLabel}
|
||||
</Text>
|
||||
) : (
|
||||
<View style={styles.spacer} />
|
||||
)}
|
||||
</View>
|
||||
),
|
||||
[height, label, labelStyle, secondaryLabel, secondaryLabelStyle, width],
|
||||
);
|
||||
|
||||
if (!moving) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={styles.overlay} pointerEvents="none">
|
||||
<MaskedView pointerEvents="none" style={trackStyle} maskElement={maskElement}>
|
||||
<View pointerEvents="none" style={trackStyle}>
|
||||
<Animated.View pointerEvents="none" style={bandStyle}>
|
||||
<BandGradient id={gradientId} />
|
||||
</Animated.View>
|
||||
</View>
|
||||
</MaskedView>
|
||||
</View>
|
||||
);
|
||||
});
|
||||
|
||||
function BandGradient({ id }: { id: string }) {
|
||||
return (
|
||||
<Svg width="100%" height="100%" preserveAspectRatio="none">
|
||||
<Defs>
|
||||
<SvgLinearGradient id={id} x1="0%" y1="0%" x2="100%" y2="0%">
|
||||
<Stop offset="0%" stopColor="#ffffff" stopOpacity={0} />
|
||||
<Stop offset="50%" stopColor="#ffffff" stopOpacity={1} />
|
||||
<Stop offset="100%" stopColor="#ffffff" stopOpacity={0} />
|
||||
</SvgLinearGradient>
|
||||
</Defs>
|
||||
<Rect x="0" y="0" width="100%" height="100%" fill={`url(#${id})`} />
|
||||
</Svg>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { memo, useMemo } from "react";
|
||||
import { Text, View, type TextStyle, type ViewStyle } from "react-native";
|
||||
import { useIndicatorMotion } from "@/components/indicator-motion";
|
||||
import { type IndicatorLoop, useIndicatorLoop } from "@/components/indicator-motion/loop.web";
|
||||
import { type LabelShimmerProps, getShimmerDurationMs, getTextSweep } from "./sweep";
|
||||
|
||||
export { useLabelMeasurements } from "./measurements";
|
||||
|
||||
const BAND_GRADIENT =
|
||||
"linear-gradient(90deg, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.45) 24%, #ffffff 40%, #ffffff 60%, rgba(255, 255, 255, 0.45) 76%, rgba(255, 255, 255, 0) 100%)";
|
||||
|
||||
// Solid white text. Filling the glyphs through a clipped background instead of colouring them keeps
|
||||
// the rasteriser on the path the highlight has always been drawn with; plain white text is drawn
|
||||
// measurably heavier.
|
||||
const WHITE_TEXT = {
|
||||
opacity: 1,
|
||||
color: "transparent",
|
||||
WebkitTextFillColor: "transparent",
|
||||
backgroundColor: "#ffffff",
|
||||
backgroundClip: "text",
|
||||
WebkitBackgroundClip: "text",
|
||||
} as TextStyle;
|
||||
|
||||
const FILL: ViewStyle = { position: "absolute", top: 0, right: 0, bottom: 0, left: 0 };
|
||||
|
||||
// React Native's style types do not know the CSS mask properties.
|
||||
const overlayStyle: ViewStyle = { ...FILL, overflow: "hidden" };
|
||||
// The window: the row, cut down by a mask to a band with soft edges.
|
||||
const bandBaseStyle = {
|
||||
...FILL,
|
||||
maskImage: BAND_GRADIENT,
|
||||
WebkitMaskImage: BAND_GRADIENT,
|
||||
maskRepeat: "no-repeat",
|
||||
WebkitMaskRepeat: "no-repeat",
|
||||
} as ViewStyle;
|
||||
// The white text seen through the window, laid out exactly over the label.
|
||||
const textStyle: ViewStyle = { ...FILL, flexDirection: "row", alignItems: "center" };
|
||||
const spacerStyle: ViewStyle = { flex: 1 };
|
||||
|
||||
function slide(fromX: number, toX: number, durationMs: number): IndicatorLoop {
|
||||
return {
|
||||
keyframes: [{ transform: `translateX(${fromX}px)` }, { transform: `translateX(${toX}px)` }],
|
||||
durationMs,
|
||||
phase: "own",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Web label shimmer. The window slides across the row while the text seen through it slides back by
|
||||
* the same amount, and so stays where it is. Both are `transform` loops, so the browser's
|
||||
* compositor moves two layers it has already painted; see `loop.web.ts`. Animating the highlight as
|
||||
* a text-clipped background instead repaints the text on the main thread every frame.
|
||||
*/
|
||||
export const LabelShimmer = memo(function LabelShimmer({
|
||||
label,
|
||||
secondaryLabel,
|
||||
labelStyle,
|
||||
secondaryLabelStyle,
|
||||
measurements,
|
||||
}: LabelShimmerProps) {
|
||||
const { labelSpan, secondarySpan } = measurements;
|
||||
const moving = useIndicatorMotion();
|
||||
const durationMs = getShimmerDurationMs(label, secondaryLabel);
|
||||
const sweep = getTextSweep({ labelSpan, secondarySpan: secondaryLabel ? secondarySpan : null });
|
||||
|
||||
// Both loops change together, so they restart together and stay exactly opposed.
|
||||
const bandLoop = useMemo(
|
||||
() => (moving ? slide(sweep.fromX, sweep.toX, durationMs) : null),
|
||||
[durationMs, moving, sweep.fromX, sweep.toX],
|
||||
);
|
||||
const textLoop = useMemo(
|
||||
() => (moving ? slide(-sweep.fromX, -sweep.toX, durationMs) : null),
|
||||
[durationMs, moving, sweep.fromX, sweep.toX],
|
||||
);
|
||||
const bandRef = useIndicatorLoop(bandLoop);
|
||||
const textRef = useIndicatorLoop(textLoop);
|
||||
|
||||
const bandStyle = useMemo(
|
||||
() => [
|
||||
bandBaseStyle,
|
||||
{
|
||||
maskSize: `${sweep.peakWidth}px 100%`,
|
||||
WebkitMaskSize: `${sweep.peakWidth}px 100%`,
|
||||
} as ViewStyle,
|
||||
],
|
||||
[sweep.peakWidth],
|
||||
);
|
||||
const labelTextStyle = useMemo(() => [labelStyle, WHITE_TEXT], [labelStyle]);
|
||||
const secondaryTextStyle = useMemo(
|
||||
() => [secondaryLabelStyle, WHITE_TEXT],
|
||||
[secondaryLabelStyle],
|
||||
);
|
||||
|
||||
if (!moving) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={overlayStyle} pointerEvents="none" testID="label-shimmer">
|
||||
<View ref={bandRef} style={bandStyle}>
|
||||
<View ref={textRef} style={textStyle}>
|
||||
<Text style={labelTextStyle} numberOfLines={1}>
|
||||
{label}
|
||||
</Text>
|
||||
{secondaryLabel ? (
|
||||
<Text style={secondaryTextStyle} numberOfLines={1}>
|
||||
{secondaryLabel}
|
||||
</Text>
|
||||
) : (
|
||||
<View style={spacerStyle} />
|
||||
)}
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import type { LayoutChangeEvent } from "react-native";
|
||||
import { isNative, isWeb } from "@/constants/platform";
|
||||
import type { LabelMeasurements, LabelRowSize, LabelSpan } from "./sweep";
|
||||
|
||||
type LayoutHandler = (event: LayoutChangeEvent) => void;
|
||||
|
||||
export interface LabelMeasuring {
|
||||
measurements: LabelMeasurements;
|
||||
/** Attach each to its element's `onLayout`. One that is undefined needs no measuring. */
|
||||
onRowLayout: LayoutHandler | undefined;
|
||||
onLabelLayout: LayoutHandler | undefined;
|
||||
onSecondaryLayout: LayoutHandler | undefined;
|
||||
}
|
||||
|
||||
const UNMEASURED_ROW_SIZE: LabelRowSize = { width: 0, height: 0 };
|
||||
const UNMEASURED_SPAN: LabelSpan = { x: 0, width: 0 };
|
||||
|
||||
// Layout reports sub-pixel noise; a measurement that moved less than half a pixel is the same one.
|
||||
function isSameMeasurement(previous: number, next: number): boolean {
|
||||
return Math.abs(previous - next) <= 0.5;
|
||||
}
|
||||
|
||||
function isSameSpan(previous: LabelSpan, x: number, width: number): boolean {
|
||||
return isSameMeasurement(previous.x, x) && isSameMeasurement(previous.width, width);
|
||||
}
|
||||
|
||||
/**
|
||||
* Measures a label row for its shimmer. The web highlight follows the two pieces of text; the
|
||||
* native one crosses the whole row.
|
||||
*/
|
||||
export function useLabelMeasurements(shimmering: boolean): LabelMeasuring {
|
||||
const [rowSize, setRowSize] = useState(UNMEASURED_ROW_SIZE);
|
||||
const [labelSpan, setLabelSpan] = useState(UNMEASURED_SPAN);
|
||||
const [secondarySpan, setSecondarySpan] = useState(UNMEASURED_SPAN);
|
||||
|
||||
const handleRowLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
const { width, height } = event.nativeEvent.layout;
|
||||
setRowSize((previous) =>
|
||||
isSameMeasurement(previous.width, width) && isSameMeasurement(previous.height, height)
|
||||
? previous
|
||||
: { width, height },
|
||||
);
|
||||
}, []);
|
||||
const handleLabelLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
const { x, width } = event.nativeEvent.layout;
|
||||
setLabelSpan((previous) => (isSameSpan(previous, x, width) ? previous : { x, width }));
|
||||
}, []);
|
||||
const handleSecondaryLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
const { x, width } = event.nativeEvent.layout;
|
||||
setSecondarySpan((previous) => (isSameSpan(previous, x, width) ? previous : { x, width }));
|
||||
}, []);
|
||||
|
||||
const measurements = useMemo(
|
||||
() => ({ rowSize, labelSpan, secondarySpan }),
|
||||
[rowSize, labelSpan, secondarySpan],
|
||||
);
|
||||
|
||||
return {
|
||||
measurements,
|
||||
onRowLayout: isNative && shimmering ? handleRowLayout : undefined,
|
||||
// React Native Web only observes a node when onLayout exists at mount. Measure while idle too,
|
||||
// so a retained row has its dimensions when it starts shimmering.
|
||||
onLabelLayout: isWeb ? handleLabelLayout : undefined,
|
||||
onSecondaryLayout: isWeb ? handleSecondaryLayout : undefined,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { getRowSweep, getShimmerDurationMs, getTextSweep } from "./sweep";
|
||||
|
||||
describe("label shimmer sweep", () => {
|
||||
test("takes longer on longer labels, between one and 2.3 seconds", () => {
|
||||
expect(getShimmerDurationMs("Shell", "sleep 600")).toBeCloseTo(1362);
|
||||
expect(getShimmerDurationMs("Read", undefined)).toBeCloseTo(1032);
|
||||
expect(getShimmerDurationMs(" Edit ", " a.ts ")).toBe(getShimmerDurationMs("Edit", "a.ts"));
|
||||
expect(getShimmerDurationMs("", undefined)).toBe(1000);
|
||||
expect(getShimmerDurationMs("x".repeat(400), undefined)).toBe(2300);
|
||||
});
|
||||
|
||||
test("crosses the text from one band width before the label to the end of the last text", () => {
|
||||
const sweep = getTextSweep({
|
||||
labelSpan: { x: 20, width: 36 },
|
||||
secondarySpan: { x: 64, width: 400 },
|
||||
});
|
||||
|
||||
expect(sweep.peakWidth).toBeCloseTo(97.68);
|
||||
expect(sweep.fromX).toBeCloseTo(20 - 97.68);
|
||||
expect(sweep.toX).toBe(464);
|
||||
});
|
||||
|
||||
test("ends at the label when there is no secondary text", () => {
|
||||
expect(getTextSweep({ labelSpan: { x: 20, width: 36 }, secondarySpan: null })).toEqual({
|
||||
peakWidth: 42,
|
||||
fromX: -22,
|
||||
toX: 56,
|
||||
});
|
||||
});
|
||||
|
||||
test("keeps the band between 42 and 120 wide on text", () => {
|
||||
const wide = getTextSweep({ labelSpan: { x: 0, width: 2000 }, secondarySpan: null });
|
||||
const unmeasured = getTextSweep({ labelSpan: { x: 0, width: 0 }, secondarySpan: null });
|
||||
|
||||
expect(wide.peakWidth).toBe(120);
|
||||
expect(unmeasured).toEqual({ peakWidth: 42, fromX: -42, toX: 0 });
|
||||
});
|
||||
|
||||
test("crosses the whole row with one band width of run-in and run-out", () => {
|
||||
const sweep = getRowSweep(300);
|
||||
expect(sweep.peakWidth).toBeCloseTo(84);
|
||||
expect(sweep.fromX).toBeCloseTo(-84);
|
||||
expect(sweep.toX).toBeCloseTo(384);
|
||||
expect(getRowSweep(50)).toEqual({ peakWidth: 32, fromX: -32, toX: 82 });
|
||||
expect(getRowSweep(2000)).toEqual({ peakWidth: 120, fromX: -120, toX: 2120 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import type { StyleProp, TextStyle } from "react-native";
|
||||
|
||||
/** Where a piece of text sits on the label row, as the row's layout reported it. */
|
||||
export interface LabelSpan {
|
||||
x: number;
|
||||
width: number;
|
||||
}
|
||||
|
||||
export interface LabelRowSize {
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
/** The row's measured geometry. A measurement that has not arrived yet is zero. */
|
||||
export interface LabelMeasurements {
|
||||
rowSize: LabelRowSize;
|
||||
labelSpan: LabelSpan;
|
||||
secondarySpan: LabelSpan;
|
||||
}
|
||||
|
||||
export interface LabelShimmerProps {
|
||||
label: string;
|
||||
secondaryLabel?: string;
|
||||
/** The row's own text styles: the highlight is set in the same type, at the same place. */
|
||||
labelStyle: StyleProp<TextStyle>;
|
||||
secondaryLabelStyle: StyleProp<TextStyle>;
|
||||
measurements: LabelMeasurements;
|
||||
}
|
||||
|
||||
/** One pass of the highlight: a band `peakWidth` wide whose left edge travels `fromX` to `toX`. */
|
||||
export interface ShimmerSweep {
|
||||
peakWidth: number;
|
||||
fromX: number;
|
||||
toX: number;
|
||||
}
|
||||
|
||||
/** Longer labels take longer to cross, within limits, so the highlight's speed reads the same. */
|
||||
export function getShimmerDurationMs(label: string, secondaryLabel: string | undefined): number {
|
||||
const characters = label.trim().length + (secondaryLabel?.trim().length ?? 0);
|
||||
const shortLabelAdjustment = characters <= 12 ? 0.25 : 0;
|
||||
const seconds = Math.max(1, Math.min(2.3, 1.25 + characters * 0.008 - shortLabelAdjustment));
|
||||
return seconds * 1000;
|
||||
}
|
||||
|
||||
/** Sweeps the text itself: in from just left of the label, out at the end of the last text. */
|
||||
export function getTextSweep(input: {
|
||||
labelSpan: LabelSpan;
|
||||
secondarySpan: LabelSpan | null;
|
||||
}): ShimmerSweep {
|
||||
const startX = input.labelSpan.x;
|
||||
const endX = input.secondarySpan
|
||||
? input.secondarySpan.x + input.secondarySpan.width
|
||||
: input.labelSpan.x + input.labelSpan.width;
|
||||
const peakWidth = Math.max(42, Math.min(120, Math.max(1, endX - startX) * 0.22));
|
||||
return { peakWidth, fromX: startX - peakWidth, toX: endX };
|
||||
}
|
||||
|
||||
/** Sweeps the whole row: in from just left of it, out just right of it. */
|
||||
export function getRowSweep(rowWidth: number): ShimmerSweep {
|
||||
const peakWidth = Math.max(32, Math.min(120, rowWidth * 0.28));
|
||||
return { peakWidth, fromX: -peakWidth, toX: rowWidth + peakWidth };
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
import { Parser } from "htmlparser2";
|
||||
import { fromMarkdown } from "mdast-util-from-markdown";
|
||||
import { gfmTableFromMarkdown } from "mdast-util-gfm-table";
|
||||
import { gfmTable } from "micromark-extension-gfm-table";
|
||||
import { decodeString } from "micromark-util-decode-string";
|
||||
import type { Nodes } from "mdast";
|
||||
|
||||
@@ -53,6 +55,8 @@ export function normalizeMarkdownHtml(source: string): string {
|
||||
} else if ("children" in node) node.children.forEach(protectCode);
|
||||
}
|
||||
protectCode(tree);
|
||||
// Only `<br>` reads these, so a source without one skips the extra parse.
|
||||
const tableRanges = /<br/i.test(source) ? collectTableRanges(source, codeRanges) : [];
|
||||
const links: (string | undefined)[] = [];
|
||||
let previousTag: { name: string; end: number } | null = null;
|
||||
const convert = (raw: string, offset: number): string => {
|
||||
@@ -84,7 +88,16 @@ export function normalizeMarkdownHtml(source: string): string {
|
||||
: /^\s*$/.test(source.slice(0, offset));
|
||||
previousTag = { name, end: offset + raw.length };
|
||||
if (EMPHASIS[name]) return EMPHASIS[name];
|
||||
const boundary = layoutBoundary(name, source, raw, offset, closing, startsAfterBoundary);
|
||||
const inTable = tableRanges.some(({ start, end }) => offset >= start && offset < end);
|
||||
const boundary = layoutBoundary(
|
||||
name,
|
||||
source,
|
||||
raw,
|
||||
offset,
|
||||
closing,
|
||||
startsAfterBoundary,
|
||||
inTable,
|
||||
);
|
||||
if (boundary !== null) return boundary;
|
||||
if (name === "a") return markdownAnchor(raw, closing, links);
|
||||
if (name === "img" && !closing) {
|
||||
@@ -167,8 +180,15 @@ function layoutBoundary(
|
||||
offset: number,
|
||||
closing: boolean,
|
||||
startsAfterBoundary: boolean,
|
||||
inTable: boolean,
|
||||
): string | null {
|
||||
if (name === "br") return closing ? "" : " \n";
|
||||
// Inside GFM table cells, emit ` \u2028 ` so row boundaries stay intact while giving flanking
|
||||
// emphasis/strikethrough delimiters and URLs/autolinks whitespace boundaries on both sides before
|
||||
// the cell-scoped parser turns ` \u2028 ` back into a `LineBreak` node.
|
||||
if (name === "br") {
|
||||
if (closing) return "";
|
||||
return inTable ? " \u2028 " : " \n";
|
||||
}
|
||||
if (name === "summary") return closing ? "**\n\n" : "**";
|
||||
if (name === "details")
|
||||
return (closing ? offset + raw.length === source.length : offset === 0) ? "" : "\n\n";
|
||||
@@ -177,3 +197,67 @@ function layoutBoundary(
|
||||
return /^<t[dh]\b/i.test(source.slice(offset + raw.length)) ? " " : "";
|
||||
return null;
|
||||
}
|
||||
|
||||
function hasNonWhitespaceAfterNewline(value: string): boolean {
|
||||
const lastNewline = value.lastIndexOf("\n");
|
||||
return /[^\s]/.test(lastNewline === -1 ? value : value.slice(lastNewline + 1));
|
||||
}
|
||||
|
||||
function isTableWrapperTag(raw: string, inCode: boolean): boolean {
|
||||
if (inCode) return false;
|
||||
if (raw.startsWith("<!--")) return true;
|
||||
const name = /^<\/?([A-Za-z][A-Za-z0-9-]*)/.exec(raw)?.[1].toLowerCase();
|
||||
return name === "summary" || name === "details" || (name !== undefined && BLOCK_TAGS.has(name));
|
||||
}
|
||||
|
||||
function collectTableRanges(
|
||||
source: string,
|
||||
codeRanges: readonly { start: number; end: number }[],
|
||||
): { start: number; end: number }[] {
|
||||
let cursor = 0;
|
||||
let codeIndex = 0;
|
||||
let lineHasPrefixText = false;
|
||||
// Advance line/code state monotonically in a single forward pass so large single-line HTML tables stay O(n)
|
||||
// while nested leading wrappers (e.g. `<details><summary>Results</summary><div>| A | B |`) follow
|
||||
// line breaks introduced by earlier masked tags.
|
||||
const tableSource = source.replace(HTML, (raw, offset: number) => {
|
||||
for (let index = cursor; index < offset; index++) {
|
||||
const code = source.charCodeAt(index);
|
||||
if (code === 10) lineHasPrefixText = false;
|
||||
else if (code !== 32 && code !== 9 && code !== 13) lineHasPrefixText = true;
|
||||
}
|
||||
cursor = offset + raw.length;
|
||||
while (codeIndex < codeRanges.length && codeRanges[codeIndex].end <= offset) codeIndex++;
|
||||
const inCode = codeIndex < codeRanges.length && offset >= codeRanges[codeIndex].start;
|
||||
if (!isTableWrapperTag(raw, inCode)) {
|
||||
if (inCode || /^<code\b/i.test(raw)) {
|
||||
if (hasNonWhitespaceAfterNewline(raw)) lineHasPrefixText = true;
|
||||
else if (raw.includes("\n")) lineHasPrefixText = false;
|
||||
} else if (raw.includes("\n")) {
|
||||
lineHasPrefixText = false;
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
const blanked = raw.replace(/[^\n]/g, " ");
|
||||
if (!lineHasPrefixText && blanked.length > 0 && !blanked.endsWith("\n")) {
|
||||
return `${blanked.slice(0, -1)}\n`;
|
||||
}
|
||||
if (blanked.includes("\n")) lineHasPrefixText = false;
|
||||
return blanked;
|
||||
});
|
||||
const tableRanges: { start: number; end: number }[] = [];
|
||||
function findTables(node: Nodes) {
|
||||
if (node.type === "table" && node.position) {
|
||||
const start = node.position.start.offset;
|
||||
const end = node.position.end.offset;
|
||||
if (start !== undefined && end !== undefined) tableRanges.push({ start, end });
|
||||
} else if ("children" in node) node.children.forEach(findTables);
|
||||
}
|
||||
findTables(
|
||||
fromMarkdown(tableSource, {
|
||||
extensions: [{ disable: { null: ["htmlFlow", "htmlText"] } }, gfmTable()],
|
||||
mdastExtensions: [gfmTableFromMarkdown()],
|
||||
}),
|
||||
);
|
||||
return tableRanges;
|
||||
}
|
||||
|
||||
@@ -838,6 +838,188 @@ describe("GitHub comment HTML normalization", () => {
|
||||
])("normalizes %s without changing code", (source, expected) => {
|
||||
expect(prepareMarkdownSource(source).render()).toBe(expected);
|
||||
});
|
||||
|
||||
it("keeps <br> line breaks inside GFM table headers and cells within a single row", async () => {
|
||||
const source = [
|
||||
"| Col<br>One | Col<br />Two |",
|
||||
"| --- | --- |",
|
||||
"| First<br>Second<br/>Third | Plain |",
|
||||
].join("\n");
|
||||
const tree = await parseMarkdown(prepareMarkdownSource(source).render(), {
|
||||
hardSoftBreaks: true,
|
||||
latexMath: false,
|
||||
});
|
||||
const table = tree.children?.find((node) => node.type === "Table");
|
||||
expect(table).toBeDefined();
|
||||
const headRows = table?.children?.find((node) => node.type === "TableHead")?.children ?? [];
|
||||
const bodyRows = table?.children?.find((node) => node.type === "TableBody")?.children ?? [];
|
||||
expect(headRows).toHaveLength(1);
|
||||
expect(bodyRows).toHaveLength(1);
|
||||
const [headCells, bodyCells] = [headRows[0].children ?? [], bodyRows[0].children ?? []];
|
||||
expect(headCells[0].children).toEqual([
|
||||
{ type: "Text", content: "Col" },
|
||||
{ type: "LineBreak" },
|
||||
{ type: "Text", content: "One" },
|
||||
]);
|
||||
expect(headCells[1].children).toEqual([
|
||||
{ type: "Text", content: "Col" },
|
||||
{ type: "LineBreak" },
|
||||
{ type: "Text", content: "Two" },
|
||||
]);
|
||||
expect(bodyCells[0].children).toEqual([
|
||||
{ type: "Text", content: "First" },
|
||||
{ type: "LineBreak" },
|
||||
{ type: "Text", content: "Second" },
|
||||
{ type: "LineBreak" },
|
||||
{ type: "Text", content: "Third" },
|
||||
]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
"<details><summary>Results</summary>\n\n| A | B |\n| - | - |\n| 1<br>2 | 3 |\n</details>",
|
||||
"<details><summary>Results</summary>| A | B |\n| - | - |\n| 1<br>2 | 3 |</details>",
|
||||
"<details><summary>Results</summary><div>| A | B |\n| - | - |\n| 1<br>2 | 3 |</div></details>",
|
||||
"<span></span><div>| A | B |\n| - | - |\n| 1<br>2 | 3 |</div>",
|
||||
])("keeps table <br> inside wrapped table cells: %s", async (source) => {
|
||||
const tree = await parseMarkdown(prepareMarkdownSource(source).render(), {
|
||||
hardSoftBreaks: true,
|
||||
latexMath: false,
|
||||
});
|
||||
const table = tree.children?.find((node) => node.type === "Table");
|
||||
expect(table).toBeDefined();
|
||||
const body = table?.children?.find((node) => node.type === "TableBody");
|
||||
expect(body?.children).toHaveLength(1);
|
||||
expect(body?.children?.[0]?.children?.[0]?.children).toEqual([
|
||||
{ type: "Text", content: "1" },
|
||||
{ type: "LineBreak" },
|
||||
{ type: "Text", content: "2" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("recognizes file paths and URLs separated by <br> inside table cells", async () => {
|
||||
const source = [
|
||||
"| Paths | Mixed | URLs |",
|
||||
"| --- | --- | --- |",
|
||||
"| src/first.ts<br>src/second.ts | https://example.com/first<br>src/second.ts | https://example.com/first<br>https://example.com/second |",
|
||||
].join("\n");
|
||||
const prepared = prepareMarkdownSource(source);
|
||||
const linked = recognizeTextLinks(
|
||||
await parseMarkdown(prepared.render(), {
|
||||
hardSoftBreaks: true,
|
||||
latexMath: false,
|
||||
}),
|
||||
prepared.linkRecognition.text,
|
||||
prepared.linkRecognition.inlineCode,
|
||||
);
|
||||
const table = linked.children?.find((node) => node.type === "Table");
|
||||
const row = table?.children?.find((node) => node.type === "TableBody")?.children?.[0];
|
||||
expect(row?.children?.[0]?.children).toEqual([
|
||||
{
|
||||
type: "Link",
|
||||
attributes: { url: "src/first.ts", recognizedLink: "true" },
|
||||
children: [{ type: "Text", content: "src/first.ts" }],
|
||||
},
|
||||
{ type: "LineBreak" },
|
||||
{
|
||||
type: "Link",
|
||||
attributes: { url: "src/second.ts", recognizedLink: "true" },
|
||||
children: [{ type: "Text", content: "src/second.ts" }],
|
||||
},
|
||||
]);
|
||||
expect(row?.children?.[1]?.children).toEqual([
|
||||
{
|
||||
type: "Link",
|
||||
attributes: { url: "https://example.com/first" },
|
||||
children: [{ type: "Text", content: "https://example.com/first" }],
|
||||
},
|
||||
{ type: "LineBreak" },
|
||||
{
|
||||
type: "Link",
|
||||
attributes: { url: "src/second.ts", recognizedLink: "true" },
|
||||
children: [{ type: "Text", content: "src/second.ts" }],
|
||||
},
|
||||
]);
|
||||
expect(row?.children?.[2]?.children).toEqual([
|
||||
{
|
||||
type: "Link",
|
||||
attributes: { url: "https://example.com/first" },
|
||||
children: [{ type: "Text", content: "https://example.com/first" }],
|
||||
},
|
||||
{ type: "LineBreak" },
|
||||
{
|
||||
type: "Link",
|
||||
attributes: { url: "https://example.com/second" },
|
||||
children: [{ type: "Text", content: "https://example.com/second" }],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps literal U+2028 outside tables, inline code, and escaped <br> untouched", async () => {
|
||||
const source = [
|
||||
"before\u2028after `before\u2028after`",
|
||||
"",
|
||||
"| Inline | Escaped | Entity |",
|
||||
"| --- | --- | --- |",
|
||||
"| `before\u2028after` | \\<br> | <br> `<br>` |",
|
||||
].join("\n");
|
||||
const tree = await parseMarkdown(prepareMarkdownSource(source).render(), {
|
||||
hardSoftBreaks: true,
|
||||
latexMath: false,
|
||||
});
|
||||
const collectLineBreaks = (node: ASTNode): number =>
|
||||
(node.type === "LineBreak" ? 1 : 0) +
|
||||
(node.children?.reduce((count, child) => count + collectLineBreaks(child), 0) ?? 0);
|
||||
expect(collectLineBreaks(tree)).toBe(0);
|
||||
|
||||
const paragraph = tree.children?.find((node) => node.type === "Paragraph");
|
||||
expect(paragraph?.children).toEqual([
|
||||
{ type: "Text", content: "before\u2028after " },
|
||||
{ type: "Code", children: [{ type: "Text", content: "before\u2028after" }] },
|
||||
]);
|
||||
|
||||
const row = tree.children
|
||||
?.find((node) => node.type === "Table")
|
||||
?.children?.find((node) => node.type === "TableBody")?.children?.[0];
|
||||
expect(row?.children?.[0]?.children).toEqual([
|
||||
{ type: "Code", children: [{ type: "Text", content: "before\u2028after" }] },
|
||||
]);
|
||||
expect(row?.children?.[1]?.children).toEqual([{ type: "Text", content: "<br>" }]);
|
||||
expect(row?.children?.[2]?.children).toEqual([
|
||||
{ type: "Text", content: "<br> " },
|
||||
{ type: "Code", children: [{ type: "Text", content: "<br>" }] },
|
||||
]);
|
||||
expect(prepareMarkdownSource("<table><tr><td>a<br>b</td></tr></table>").render()).toBe(
|
||||
"a \nb",
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves emphasis and strong delimiters adjacent to <br> inside table cells", async () => {
|
||||
const source = [
|
||||
"| A | B |",
|
||||
"| --- | --- |",
|
||||
"| **方案 B(最猛 · 推荐)**<br>阶梯首充 | **`基准 → 30% → 50%`**<br>*(复购:基准)* |",
|
||||
].join("\n");
|
||||
const tree = await parseMarkdown(prepareMarkdownSource(source).render(), {
|
||||
hardSoftBreaks: true,
|
||||
latexMath: false,
|
||||
});
|
||||
const row = tree.children
|
||||
?.find((node) => node.type === "Table")
|
||||
?.children?.find((node) => node.type === "TableBody")?.children?.[0];
|
||||
expect(row?.children?.[0]?.children).toEqual([
|
||||
{ type: "Strong", children: [{ type: "Text", content: "方案 B(最猛 · 推荐)" }] },
|
||||
{ type: "LineBreak" },
|
||||
{ type: "Text", content: "阶梯首充" },
|
||||
]);
|
||||
expect(row?.children?.[1]?.children).toEqual([
|
||||
{
|
||||
type: "Strong",
|
||||
children: [{ type: "Code", children: [{ type: "Text", content: "基准 → 30% → 50%" }] }],
|
||||
},
|
||||
{ type: "LineBreak" },
|
||||
{ type: "Emphasis", children: [{ type: "Text", content: "(复购:基准)" }] },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves backslashes and decodes entities inside HTML code", () => {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AppearanceText } from "@/appearance/text";
|
||||
import { useDisclosureHold } from "@/agent-stream/disclosure";
|
||||
import { MessagePreview, MessageSender } from "@/components/user-message";
|
||||
import { useStableEvent } from "@/hooks/use-stable-event";
|
||||
@@ -13,7 +14,6 @@ import {
|
||||
AttachmentThumbnail,
|
||||
} from "@/components/attachment-pill";
|
||||
import { MarkdownRenderer } from "@/components/markdown/renderer";
|
||||
import { useRetainedPanelActive } from "@/components/retained-panel";
|
||||
import {
|
||||
isRewindableMessage,
|
||||
RewindMenu,
|
||||
@@ -29,6 +29,7 @@ import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
|
||||
import { useRevealedText, type MarkdownPhase } from "@/hooks/use-revealed-text";
|
||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||
import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
|
||||
import { LabelShimmer, useLabelMeasurements } from "@/components/label-shimmer";
|
||||
import { buildToolCallPresentation } from "@/tool-calls/presentation";
|
||||
import type {
|
||||
DaemonUploadedImageAttachment,
|
||||
@@ -54,7 +55,6 @@ import type {
|
||||
ToolCallDetail,
|
||||
} from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentAttachment } from "@getpaseo/protocol/messages";
|
||||
import MaskedView from "@react-native-masked-view/masked-view";
|
||||
import {
|
||||
ArrowRightLeft,
|
||||
Check,
|
||||
@@ -94,15 +94,6 @@ import {
|
||||
type LayoutChangeEvent,
|
||||
type TextStyle,
|
||||
} from "react-native";
|
||||
import Animated, {
|
||||
Easing,
|
||||
cancelAnimation,
|
||||
useAnimatedStyle,
|
||||
useSharedValue,
|
||||
withRepeat,
|
||||
withTiming,
|
||||
} from "react-native-reanimated";
|
||||
import Svg, { Defs, Rect, Stop, LinearGradient as SvgLinearGradient } from "react-native-svg";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { capAssistantMessageForRender, getUtf8ByteLength } from "./assistant-message-render-limit";
|
||||
import { getTurnDurationLabel } from "./assistant-turn-footer-label";
|
||||
@@ -153,8 +144,6 @@ function useDisableOuterSpacing(disableOuterSpacing: boolean | undefined) {
|
||||
return disableOuterSpacing ?? contextValue;
|
||||
}
|
||||
|
||||
const WEB_TOOLCALL_SHIMMER_KEYFRAME_ID = "paseo-toolcall-shimmer-keyframes";
|
||||
const WEB_TOOLCALL_SHIMMER_ANIMATION_NAME = "paseo-toolcall-shimmer";
|
||||
const ThemedMicVocal = withUnistyles(MicVocal);
|
||||
const ThemedFileSymlinkIcon = withUnistyles(FileSymlink);
|
||||
const ThemedTriangleAlertIcon = withUnistyles(TriangleAlertIcon);
|
||||
@@ -173,17 +162,6 @@ const mutedForegroundColorMapping = (theme: Theme) => ({
|
||||
const destructiveColorMapping = (theme: Theme) => ({ color: theme.colors.destructive });
|
||||
const infoColorMapping = (theme: Theme) => ({ color: theme.colors.palette.blue[300] });
|
||||
const warningColorMapping = (theme: Theme) => ({ color: theme.colors.palette.amber[500] });
|
||||
const WEB_TOOLCALL_SHIMMER_KEYFRAME_CSS = `
|
||||
@keyframes ${WEB_TOOLCALL_SHIMMER_ANIMATION_NAME} {
|
||||
0% {
|
||||
background-position: var(--paseo-shimmer-start, -200px) 0;
|
||||
}
|
||||
100% {
|
||||
background-position: var(--paseo-shimmer-end, 200px) 0;
|
||||
}
|
||||
}
|
||||
`;
|
||||
let webToolCallShimmerRegistered = false;
|
||||
const SCROLL_EDGE_EPSILON = 0.5;
|
||||
|
||||
// Font size for stream metadata (timestamps, durations, live elapsed timer).
|
||||
@@ -191,31 +169,6 @@ const SCROLL_EDGE_EPSILON = 0.5;
|
||||
export const STREAM_METADATA_FONT_SIZE = 13;
|
||||
type ScrollAxis = "x" | "y";
|
||||
|
||||
function ensureWebToolCallShimmerKeyframes() {
|
||||
if (isNative) {
|
||||
return;
|
||||
}
|
||||
if (typeof document === "undefined") {
|
||||
return;
|
||||
}
|
||||
const existing = document.getElementById(WEB_TOOLCALL_SHIMMER_KEYFRAME_ID);
|
||||
if (existing) {
|
||||
if (existing.textContent !== WEB_TOOLCALL_SHIMMER_KEYFRAME_CSS) {
|
||||
existing.textContent = WEB_TOOLCALL_SHIMMER_KEYFRAME_CSS;
|
||||
}
|
||||
webToolCallShimmerRegistered = true;
|
||||
return;
|
||||
}
|
||||
if (webToolCallShimmerRegistered) {
|
||||
return;
|
||||
}
|
||||
const styleElement = document.createElement("style");
|
||||
styleElement.id = WEB_TOOLCALL_SHIMMER_KEYFRAME_ID;
|
||||
styleElement.textContent = WEB_TOOLCALL_SHIMMER_KEYFRAME_CSS;
|
||||
document.head.appendChild(styleElement);
|
||||
webToolCallShimmerRegistered = true;
|
||||
}
|
||||
|
||||
function getWheelEventElementTarget(event: WheelEvent, fallback: HTMLElement): HTMLElement {
|
||||
const { target } = event;
|
||||
if (target instanceof HTMLElement) {
|
||||
@@ -618,9 +571,13 @@ export const UserMessage = memo(function UserMessage({
|
||||
</View>
|
||||
) : null}
|
||||
{hasText ? (
|
||||
<Text selectable style={userMessageStylesheet.text} dataSet={MESSAGE_TEXT_DATASET}>
|
||||
<AppearanceText
|
||||
selectable
|
||||
style={userMessageStylesheet.text}
|
||||
dataSet={MESSAGE_TEXT_DATASET}
|
||||
>
|
||||
{message}
|
||||
</Text>
|
||||
</AppearanceText>
|
||||
) : null}
|
||||
</MessagePreview>
|
||||
</View>
|
||||
@@ -1091,14 +1048,6 @@ const expandableBadgeStylesheet = StyleSheet.create((theme) => ({
|
||||
secondaryLabelActive: {
|
||||
color: theme.colors.foreground,
|
||||
},
|
||||
shimmerText: {
|
||||
color: "transparent",
|
||||
fontSize: theme.fontSize.base,
|
||||
fontWeight: theme.fontWeight.normal,
|
||||
},
|
||||
spacer: {
|
||||
flex: 1,
|
||||
},
|
||||
chevron: {
|
||||
flexShrink: 0,
|
||||
},
|
||||
@@ -1137,160 +1086,8 @@ const expandableBadgeStylesheet = StyleSheet.create((theme) => ({
|
||||
detailWrapperBorderless: {
|
||||
borderWidth: 0,
|
||||
},
|
||||
shimmerOverlay: {
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
overflow: "hidden",
|
||||
},
|
||||
shimmerMaskRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
},
|
||||
nativeShimmerTrack: {
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
overflow: "hidden",
|
||||
},
|
||||
nativeShimmerPeak: {
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
},
|
||||
}));
|
||||
|
||||
interface NativeExpandableBadgeShimmerProps {
|
||||
label: string;
|
||||
secondaryLabel?: string;
|
||||
rowWidth: number;
|
||||
rowHeight: number;
|
||||
peakWidth: number;
|
||||
durationSeconds: number;
|
||||
gradientId: string;
|
||||
}
|
||||
|
||||
const NativeExpandableBadgeShimmer = memo(function NativeExpandableBadgeShimmer({
|
||||
label,
|
||||
secondaryLabel,
|
||||
rowWidth,
|
||||
rowHeight,
|
||||
peakWidth,
|
||||
durationSeconds,
|
||||
gradientId,
|
||||
}: NativeExpandableBadgeShimmerProps) {
|
||||
const isPanelActive = useRetainedPanelActive();
|
||||
const shimmerTranslateX = useSharedValue(0);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isPanelActive) {
|
||||
cancelAnimation(shimmerTranslateX);
|
||||
return;
|
||||
}
|
||||
const startPosition = -peakWidth;
|
||||
const endPosition = rowWidth + peakWidth;
|
||||
shimmerTranslateX.value = startPosition;
|
||||
shimmerTranslateX.value = withRepeat(
|
||||
withTiming(endPosition, {
|
||||
duration: durationSeconds * 1000,
|
||||
easing: Easing.linear,
|
||||
}),
|
||||
-1,
|
||||
false,
|
||||
);
|
||||
return () => {
|
||||
cancelAnimation(shimmerTranslateX);
|
||||
};
|
||||
}, [durationSeconds, isPanelActive, peakWidth, rowWidth, shimmerTranslateX]);
|
||||
|
||||
const nativeShimmerPeakStyle = useAnimatedStyle(() => ({
|
||||
transform: [{ translateX: shimmerTranslateX.value }],
|
||||
}));
|
||||
|
||||
const nativeShimmerTrackStyle = useMemo(
|
||||
() => [expandableBadgeStylesheet.nativeShimmerTrack, { width: rowWidth, height: rowHeight }],
|
||||
[rowHeight, rowWidth],
|
||||
);
|
||||
|
||||
const nativeShimmerMaskStyle = useMemo(
|
||||
() => [expandableBadgeStylesheet.shimmerMaskRow, { width: rowWidth, height: rowHeight }],
|
||||
[rowHeight, rowWidth],
|
||||
);
|
||||
|
||||
const nativeLabelMaskStyle = useMemo(
|
||||
() => [expandableBadgeStylesheet.label, { color: "#000000", opacity: 1 }],
|
||||
[],
|
||||
);
|
||||
|
||||
const nativeSecondaryMaskStyle = useMemo(
|
||||
() => [expandableBadgeStylesheet.secondaryLabel, { color: "#000000", opacity: 1 }],
|
||||
[],
|
||||
);
|
||||
|
||||
const nativeShimmerPeakCombinedStyle = useMemo(
|
||||
() => [
|
||||
expandableBadgeStylesheet.nativeShimmerPeak,
|
||||
nativeShimmerPeakStyle,
|
||||
{ width: peakWidth, height: rowHeight },
|
||||
],
|
||||
[nativeShimmerPeakStyle, peakWidth, rowHeight],
|
||||
);
|
||||
|
||||
const maskElement = useMemo(
|
||||
() => (
|
||||
<View pointerEvents="none" style={nativeShimmerMaskStyle}>
|
||||
<Text style={nativeLabelMaskStyle} numberOfLines={1}>
|
||||
{label}
|
||||
</Text>
|
||||
{secondaryLabel ? (
|
||||
<Text style={nativeSecondaryMaskStyle} numberOfLines={1}>
|
||||
{secondaryLabel}
|
||||
</Text>
|
||||
) : (
|
||||
<View style={expandableBadgeStylesheet.spacer} />
|
||||
)}
|
||||
</View>
|
||||
),
|
||||
[nativeShimmerMaskStyle, nativeLabelMaskStyle, nativeSecondaryMaskStyle, label, secondaryLabel],
|
||||
);
|
||||
|
||||
return (
|
||||
<View style={expandableBadgeStylesheet.shimmerOverlay} pointerEvents="none">
|
||||
<MaskedView pointerEvents="none" style={nativeShimmerTrackStyle} maskElement={maskElement}>
|
||||
<View pointerEvents="none" style={nativeShimmerTrackStyle}>
|
||||
<Animated.View pointerEvents="none" style={nativeShimmerPeakCombinedStyle}>
|
||||
<NativeShimmerPeakSvg gradientId={gradientId} />
|
||||
</Animated.View>
|
||||
</View>
|
||||
</MaskedView>
|
||||
</View>
|
||||
);
|
||||
});
|
||||
|
||||
function NativeShimmerPeakSvg({ gradientId }: { gradientId: string }) {
|
||||
return (
|
||||
<Svg width="100%" height="100%" preserveAspectRatio="none">
|
||||
<Defs>
|
||||
<SvgLinearGradient id={gradientId} x1="0%" y1="0%" x2="100%" y2="0%">
|
||||
<Stop offset="0%" stopColor="#ffffff" stopOpacity={0} />
|
||||
<Stop offset="50%" stopColor="#ffffff" stopOpacity={1} />
|
||||
<Stop offset="100%" stopColor="#ffffff" stopOpacity={0} />
|
||||
</SvgLinearGradient>
|
||||
</Defs>
|
||||
<Rect x="0" y="0" width="100%" height="100%" fill={`url(#${gradientId})`} />
|
||||
</Svg>
|
||||
);
|
||||
}
|
||||
|
||||
export const AssistantMessage = memo(function AssistantMessage({
|
||||
renderFullContent = false,
|
||||
occurrenceKey,
|
||||
@@ -1884,77 +1681,30 @@ interface ExpandableBadgeProps {
|
||||
interface ExpandableBadgeSecondaryLabelProps {
|
||||
secondaryLabel?: string;
|
||||
secondaryLabelStyle: StyleProp<TextStyle>;
|
||||
shouldMeasureWebShimmer: boolean;
|
||||
onSecondaryLayout: (event: LayoutChangeEvent) => void;
|
||||
onLayout: ((event: LayoutChangeEvent) => void) | undefined;
|
||||
}
|
||||
|
||||
function ExpandableBadgeSecondaryLabel({
|
||||
secondaryLabel,
|
||||
secondaryLabelStyle,
|
||||
shouldMeasureWebShimmer,
|
||||
onSecondaryLayout,
|
||||
onLayout,
|
||||
}: ExpandableBadgeSecondaryLabelProps) {
|
||||
if (!secondaryLabel) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<Text
|
||||
style={secondaryLabelStyle}
|
||||
numberOfLines={1}
|
||||
onLayout={shouldMeasureWebShimmer ? onSecondaryLayout : undefined}
|
||||
>
|
||||
<Text style={secondaryLabelStyle} numberOfLines={1} onLayout={onLayout}>
|
||||
{secondaryLabel}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
interface ExpandableBadgeWebShimmerOverlayProps {
|
||||
label: string;
|
||||
secondaryLabel?: string;
|
||||
shimmerLabelTextStyle: StyleProp<TextStyle>;
|
||||
shimmerSecondaryTextStyle: StyleProp<TextStyle>;
|
||||
}
|
||||
|
||||
function ExpandableBadgeWebShimmerOverlay({
|
||||
label,
|
||||
secondaryLabel,
|
||||
shimmerLabelTextStyle,
|
||||
shimmerSecondaryTextStyle,
|
||||
}: ExpandableBadgeWebShimmerOverlayProps) {
|
||||
return (
|
||||
<View style={expandableBadgeStylesheet.shimmerOverlay} pointerEvents="none">
|
||||
<Text style={shimmerLabelTextStyle} numberOfLines={1}>
|
||||
{label}
|
||||
</Text>
|
||||
{secondaryLabel ? (
|
||||
<Text style={shimmerSecondaryTextStyle} numberOfLines={1}>
|
||||
{secondaryLabel}
|
||||
</Text>
|
||||
) : null}
|
||||
{!secondaryLabel ? <View style={expandableBadgeStylesheet.spacer} /> : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
interface ExpandableBadgeLabelRowProps {
|
||||
label: string;
|
||||
labelStyle: StyleProp<TextStyle>;
|
||||
secondaryLabel?: string;
|
||||
secondaryLabelStyle: StyleProp<TextStyle>;
|
||||
shouldMeasureWebShimmer: boolean;
|
||||
shouldMeasureNativeShimmer: boolean;
|
||||
isWebShimmer: boolean;
|
||||
isNativeShimmer: boolean;
|
||||
shimmerLabelTextStyle: StyleProp<TextStyle>;
|
||||
shimmerSecondaryTextStyle: StyleProp<TextStyle>;
|
||||
labelRowWidth: number;
|
||||
labelRowHeight: number;
|
||||
nativeShimmerPeakWidth: number;
|
||||
shimmerDuration: number;
|
||||
nativeGradientId: string;
|
||||
onLabelRowLayout: (event: LayoutChangeEvent) => void;
|
||||
onLabelLayout: (event: LayoutChangeEvent) => void;
|
||||
onSecondaryLayout: (event: LayoutChangeEvent) => void;
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
function ExpandableBadgeLabelRow({
|
||||
@@ -1962,56 +1712,26 @@ function ExpandableBadgeLabelRow({
|
||||
labelStyle,
|
||||
secondaryLabel,
|
||||
secondaryLabelStyle,
|
||||
shouldMeasureWebShimmer,
|
||||
shouldMeasureNativeShimmer,
|
||||
isWebShimmer,
|
||||
isNativeShimmer,
|
||||
shimmerLabelTextStyle,
|
||||
shimmerSecondaryTextStyle,
|
||||
labelRowWidth,
|
||||
labelRowHeight,
|
||||
nativeShimmerPeakWidth,
|
||||
shimmerDuration,
|
||||
nativeGradientId,
|
||||
onLabelRowLayout,
|
||||
onLabelLayout,
|
||||
onSecondaryLayout,
|
||||
isLoading,
|
||||
}: ExpandableBadgeLabelRowProps) {
|
||||
const measuring = useLabelMeasurements(isLoading);
|
||||
return (
|
||||
<View
|
||||
style={expandableBadgeStylesheet.labelRow}
|
||||
onLayout={shouldMeasureNativeShimmer ? onLabelRowLayout : undefined}
|
||||
>
|
||||
<Text
|
||||
style={labelStyle}
|
||||
numberOfLines={1}
|
||||
onLayout={shouldMeasureWebShimmer ? onLabelLayout : undefined}
|
||||
>
|
||||
<View style={expandableBadgeStylesheet.labelRow} onLayout={measuring.onRowLayout}>
|
||||
<Text style={labelStyle} numberOfLines={1} onLayout={measuring.onLabelLayout}>
|
||||
{label}
|
||||
</Text>
|
||||
<ExpandableBadgeSecondaryLabel
|
||||
secondaryLabel={secondaryLabel}
|
||||
secondaryLabelStyle={secondaryLabelStyle}
|
||||
shouldMeasureWebShimmer={shouldMeasureWebShimmer}
|
||||
onSecondaryLayout={onSecondaryLayout}
|
||||
onLayout={measuring.onSecondaryLayout}
|
||||
/>
|
||||
{isWebShimmer ? (
|
||||
<ExpandableBadgeWebShimmerOverlay
|
||||
{isLoading ? (
|
||||
<LabelShimmer
|
||||
label={label}
|
||||
secondaryLabel={secondaryLabel}
|
||||
shimmerLabelTextStyle={shimmerLabelTextStyle}
|
||||
shimmerSecondaryTextStyle={shimmerSecondaryTextStyle}
|
||||
/>
|
||||
) : null}
|
||||
{isNativeShimmer ? (
|
||||
<NativeExpandableBadgeShimmer
|
||||
label={label}
|
||||
secondaryLabel={secondaryLabel}
|
||||
rowWidth={labelRowWidth}
|
||||
rowHeight={labelRowHeight}
|
||||
peakWidth={nativeShimmerPeakWidth}
|
||||
durationSeconds={shimmerDuration}
|
||||
gradientId={nativeGradientId}
|
||||
labelStyle={expandableBadgeStylesheet.label}
|
||||
secondaryLabelStyle={expandableBadgeStylesheet.secondaryLabel}
|
||||
measurements={measuring.measurements}
|
||||
/>
|
||||
) : null}
|
||||
</View>
|
||||
@@ -2086,55 +1806,6 @@ function renderExpandableBadgeIconSlot({
|
||||
return iconNode;
|
||||
}
|
||||
|
||||
function computeShimmerMetrics(input: {
|
||||
label: string;
|
||||
secondaryLabel: string | undefined;
|
||||
isLoading: boolean;
|
||||
labelRowWidth: number;
|
||||
labelRowHeight: number;
|
||||
labelOffsetX: number;
|
||||
labelWidth: number;
|
||||
secondaryOffsetX: number;
|
||||
secondaryWidth: number;
|
||||
}) {
|
||||
const totalShimmerChars = input.label.trim().length + (input.secondaryLabel?.trim().length ?? 0);
|
||||
const shortTextDurationAdjustment = totalShimmerChars <= 12 ? 0.25 : 0;
|
||||
const shimmerDuration = Math.max(
|
||||
1,
|
||||
Math.min(2.3, 1.25 + totalShimmerChars * 0.008 - shortTextDurationAdjustment),
|
||||
);
|
||||
const nativeShimmerPeakWidth = Math.max(
|
||||
32,
|
||||
Math.min(120, input.labelRowWidth > 0 ? input.labelRowWidth * 0.28 : 0),
|
||||
);
|
||||
const isWebShimmer = input.isLoading && isWeb;
|
||||
// React Native Web only observes a node when onLayout exists at mount. Keep
|
||||
// measuring while idle so a retained badge has dimensions when it starts loading.
|
||||
const shouldMeasureWebShimmer = isWeb;
|
||||
const shouldMeasureNativeShimmer = input.isLoading && isNative;
|
||||
const isNativeShimmer =
|
||||
shouldMeasureNativeShimmer && input.labelRowWidth > 0 && input.labelRowHeight > 0;
|
||||
const webShimmerSpanStartX = input.labelOffsetX;
|
||||
const webShimmerSpanEndX = input.secondaryLabel
|
||||
? input.secondaryOffsetX + input.secondaryWidth
|
||||
: input.labelOffsetX + input.labelWidth;
|
||||
const webShimmerSpanWidth = Math.max(1, webShimmerSpanEndX - webShimmerSpanStartX);
|
||||
const webShimmerPeakWidth = Math.max(42, Math.min(120, webShimmerSpanWidth * 0.22));
|
||||
const webShimmerTrackStart = webShimmerSpanStartX - webShimmerPeakWidth;
|
||||
const webShimmerTrackEnd = webShimmerSpanEndX;
|
||||
return {
|
||||
shimmerDuration,
|
||||
nativeShimmerPeakWidth,
|
||||
isWebShimmer,
|
||||
shouldMeasureWebShimmer,
|
||||
shouldMeasureNativeShimmer,
|
||||
isNativeShimmer,
|
||||
webShimmerPeakWidth,
|
||||
webShimmerTrackStart,
|
||||
webShimmerTrackEnd,
|
||||
};
|
||||
}
|
||||
|
||||
function useDetailWheelPropagationBlocker(input: {
|
||||
detailWrapperRef: React.RefObject<View | null>;
|
||||
enabled: boolean;
|
||||
@@ -2161,33 +1832,6 @@ function useDetailWheelPropagationBlocker(input: {
|
||||
}, [detailWrapperRef, enabled]);
|
||||
}
|
||||
|
||||
const SHIMMER_GRADIENT =
|
||||
"linear-gradient(90deg, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.45) 24%, #ffffff 40%, #ffffff 60%, rgba(255, 255, 255, 0.45) 76%, rgba(255, 255, 255, 0) 100%)";
|
||||
|
||||
function buildShimmerTextStyle(input: {
|
||||
isWebShimmer: boolean;
|
||||
webShimmerPeakWidth: number;
|
||||
shimmerDuration: number;
|
||||
webShimmerTrackStart: number;
|
||||
webShimmerTrackEnd: number;
|
||||
offsetX: number;
|
||||
}): object | null {
|
||||
if (!input.isWebShimmer) return null;
|
||||
return inlineUnistylesStyle({
|
||||
opacity: 1,
|
||||
color: "transparent",
|
||||
backgroundImage: SHIMMER_GRADIENT,
|
||||
backgroundSize: `${input.webShimmerPeakWidth}px 100%`,
|
||||
backgroundRepeat: "no-repeat",
|
||||
backgroundClip: "text",
|
||||
WebkitBackgroundClip: "text",
|
||||
WebkitTextFillColor: "transparent",
|
||||
animation: `${WEB_TOOLCALL_SHIMMER_ANIMATION_NAME} ${input.shimmerDuration}s linear infinite`,
|
||||
"--paseo-shimmer-start": `${input.webShimmerTrackStart - input.offsetX}px`,
|
||||
"--paseo-shimmer-end": `${input.webShimmerTrackEnd - input.offsetX}px`,
|
||||
});
|
||||
}
|
||||
|
||||
export const ExpandableBadge = memo(function ExpandableBadge({
|
||||
label,
|
||||
style,
|
||||
@@ -2231,126 +1875,11 @@ export const ExpandableBadge = memo(function ExpandableBadge({
|
||||
const handleOpenFileHoverIn = useCallback(() => setIsOpenFileHovered(true), []);
|
||||
const handleOpenFileHoverOut = useCallback(() => setIsOpenFileHovered(false), []);
|
||||
|
||||
const nativeGradientIdRef = useRef(
|
||||
`shimmer-gradient-${Math.random().toString(36).substring(2, 9)}`,
|
||||
);
|
||||
const [labelRowWidth, setLabelRowWidth] = useState(0);
|
||||
const [labelRowHeight, setLabelRowHeight] = useState(0);
|
||||
const [labelOffsetX, setLabelOffsetX] = useState(0);
|
||||
const [labelWidth, setLabelWidth] = useState(0);
|
||||
const [secondaryOffsetX, setSecondaryOffsetX] = useState(0);
|
||||
const [secondaryWidth, setSecondaryWidth] = useState(0);
|
||||
|
||||
const {
|
||||
shimmerDuration,
|
||||
nativeShimmerPeakWidth,
|
||||
isWebShimmer,
|
||||
shouldMeasureWebShimmer,
|
||||
shouldMeasureNativeShimmer,
|
||||
isNativeShimmer,
|
||||
webShimmerPeakWidth,
|
||||
webShimmerTrackStart,
|
||||
webShimmerTrackEnd,
|
||||
} = computeShimmerMetrics({
|
||||
label,
|
||||
secondaryLabel,
|
||||
isLoading,
|
||||
labelRowWidth,
|
||||
labelRowHeight,
|
||||
labelOffsetX,
|
||||
labelWidth,
|
||||
secondaryOffsetX,
|
||||
secondaryWidth,
|
||||
});
|
||||
|
||||
const handleLabelRowLayout = useCallback(
|
||||
(event: LayoutChangeEvent) => {
|
||||
if (!shouldMeasureNativeShimmer) {
|
||||
return;
|
||||
}
|
||||
const { width, height } = event.nativeEvent.layout;
|
||||
setLabelRowWidth((previous) => (Math.abs(previous - width) > 0.5 ? width : previous));
|
||||
setLabelRowHeight((previous) => (Math.abs(previous - height) > 0.5 ? height : previous));
|
||||
},
|
||||
[shouldMeasureNativeShimmer],
|
||||
);
|
||||
|
||||
const handleLabelLayout = useCallback(
|
||||
(event: LayoutChangeEvent) => {
|
||||
if (!shouldMeasureWebShimmer) {
|
||||
return;
|
||||
}
|
||||
const { x, width } = event.nativeEvent.layout;
|
||||
setLabelOffsetX((previous) => (Math.abs(previous - x) > 0.5 ? x : previous));
|
||||
setLabelWidth((previous) => (Math.abs(previous - width) > 0.5 ? width : previous));
|
||||
},
|
||||
[shouldMeasureWebShimmer],
|
||||
);
|
||||
|
||||
const handleSecondaryLayout = useCallback(
|
||||
(event: LayoutChangeEvent) => {
|
||||
if (!shouldMeasureWebShimmer || !secondaryLabel) {
|
||||
return;
|
||||
}
|
||||
const { x, width } = event.nativeEvent.layout;
|
||||
setSecondaryOffsetX((previous) => (Math.abs(previous - x) > 0.5 ? x : previous));
|
||||
setSecondaryWidth((previous) => (Math.abs(previous - width) > 0.5 ? width : previous));
|
||||
},
|
||||
[shouldMeasureWebShimmer, secondaryLabel],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isWebShimmer) {
|
||||
return;
|
||||
}
|
||||
ensureWebToolCallShimmerKeyframes();
|
||||
}, [isWebShimmer]);
|
||||
|
||||
useDetailWheelPropagationBlocker({
|
||||
detailWrapperRef,
|
||||
enabled: !isNative && isExpanded && hasDetailContent,
|
||||
});
|
||||
|
||||
const shimmerLabelStyle = useMemo<StyleProp<TextStyle>>(
|
||||
() =>
|
||||
buildShimmerTextStyle({
|
||||
isWebShimmer,
|
||||
webShimmerPeakWidth,
|
||||
shimmerDuration,
|
||||
webShimmerTrackStart,
|
||||
webShimmerTrackEnd,
|
||||
offsetX: labelOffsetX,
|
||||
}),
|
||||
[
|
||||
isWebShimmer,
|
||||
webShimmerPeakWidth,
|
||||
shimmerDuration,
|
||||
webShimmerTrackStart,
|
||||
webShimmerTrackEnd,
|
||||
labelOffsetX,
|
||||
],
|
||||
);
|
||||
|
||||
const shimmerSecondaryStyle = useMemo<StyleProp<TextStyle>>(
|
||||
() =>
|
||||
buildShimmerTextStyle({
|
||||
isWebShimmer,
|
||||
webShimmerPeakWidth,
|
||||
shimmerDuration,
|
||||
webShimmerTrackStart,
|
||||
webShimmerTrackEnd,
|
||||
offsetX: secondaryOffsetX,
|
||||
}),
|
||||
[
|
||||
isWebShimmer,
|
||||
webShimmerPeakWidth,
|
||||
shimmerDuration,
|
||||
webShimmerTrackStart,
|
||||
webShimmerTrackEnd,
|
||||
secondaryOffsetX,
|
||||
],
|
||||
);
|
||||
|
||||
const containerStyle = useMemo(
|
||||
() => [
|
||||
expandableBadgeStylesheet.container,
|
||||
@@ -2408,25 +1937,6 @@ export const ExpandableBadge = memo(function ExpandableBadge({
|
||||
[isActive],
|
||||
);
|
||||
|
||||
const shimmerLabelTextStyle = useMemo(
|
||||
() => [
|
||||
expandableBadgeStylesheet.label,
|
||||
isLoading && expandableBadgeStylesheet.labelLoading,
|
||||
expandableBadgeStylesheet.shimmerText,
|
||||
shimmerLabelStyle,
|
||||
],
|
||||
[isLoading, shimmerLabelStyle],
|
||||
);
|
||||
|
||||
const shimmerSecondaryTextStyle = useMemo(
|
||||
() => [
|
||||
expandableBadgeStylesheet.secondaryLabel,
|
||||
expandableBadgeStylesheet.shimmerText,
|
||||
shimmerSecondaryStyle,
|
||||
],
|
||||
[shimmerSecondaryStyle],
|
||||
);
|
||||
|
||||
const chevronStyle = useMemo(
|
||||
() => [
|
||||
expandableBadgeStylesheet.chevron,
|
||||
@@ -2475,20 +1985,7 @@ export const ExpandableBadge = memo(function ExpandableBadge({
|
||||
labelStyle={labelStyle}
|
||||
secondaryLabel={secondaryLabel}
|
||||
secondaryLabelStyle={secondaryLabelStyle}
|
||||
shouldMeasureWebShimmer={shouldMeasureWebShimmer}
|
||||
shouldMeasureNativeShimmer={shouldMeasureNativeShimmer}
|
||||
isWebShimmer={isWebShimmer}
|
||||
isNativeShimmer={isNativeShimmer}
|
||||
shimmerLabelTextStyle={shimmerLabelTextStyle}
|
||||
shimmerSecondaryTextStyle={shimmerSecondaryTextStyle}
|
||||
labelRowWidth={labelRowWidth}
|
||||
labelRowHeight={labelRowHeight}
|
||||
nativeShimmerPeakWidth={nativeShimmerPeakWidth}
|
||||
shimmerDuration={shimmerDuration}
|
||||
nativeGradientId={nativeGradientIdRef.current}
|
||||
onLabelRowLayout={handleLabelRowLayout}
|
||||
onLabelLayout={handleLabelLayout}
|
||||
onSecondaryLayout={handleSecondaryLayout}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
</Pressable>
|
||||
{onOpenFile && isHovered ? (
|
||||
|
||||
@@ -2,12 +2,19 @@ import { useCallback, useMemo, useState, type ReactNode } from "react";
|
||||
import { View } from "react-native";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { SettingsRowChildren } from "./row-children";
|
||||
import { SettingsRowHeader } from "./row-header";
|
||||
import { SettingsRowHeader, type SettingsRowHintStatus } from "./row-header";
|
||||
|
||||
interface SettingsCollapsibleRowProps {
|
||||
label: string;
|
||||
/** A line under the label explaining the group. */
|
||||
hint?: string;
|
||||
hintStatus?: SettingsRowHintStatus;
|
||||
/** A short status shown before the chevron, so the row says something while collapsed. */
|
||||
summary?: string;
|
||||
/** A control acting on the row's subject in place, such as a switch, before the chevron. */
|
||||
control?: ReactNode;
|
||||
/** Names the expand/collapse button for assistive tech when the label alone is not enough. */
|
||||
accessibilityLabel?: string;
|
||||
defaultExpanded?: boolean;
|
||||
testID?: string;
|
||||
/** The rows revealed underneath, separated like the rows of a `SettingsCard` and laid out as nested rows. */
|
||||
@@ -21,7 +28,11 @@ interface SettingsCollapsibleRowProps {
|
||||
*/
|
||||
export function SettingsCollapsibleRow({
|
||||
label,
|
||||
hint,
|
||||
hintStatus,
|
||||
summary,
|
||||
control,
|
||||
accessibilityLabel,
|
||||
defaultExpanded = false,
|
||||
testID,
|
||||
children,
|
||||
@@ -39,7 +50,11 @@ export function SettingsCollapsibleRow({
|
||||
<View testID={testID}>
|
||||
<SettingsRowHeader
|
||||
label={label}
|
||||
hint={hint}
|
||||
hintStatus={hintStatus}
|
||||
summary={summary}
|
||||
control={control}
|
||||
accessibilityLabel={accessibilityLabel}
|
||||
onPress={toggle}
|
||||
expanded={expanded}
|
||||
accessibilityState={accessibilityState}
|
||||
|
||||
@@ -555,6 +555,7 @@ function ProjectMenuItems({
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const localDaemonServerId = useLocalDaemonServerId();
|
||||
const handleOpenProjectSettings = useCallback(() => {
|
||||
if (!settingsTarget) return;
|
||||
router.navigate(buildProjectSettingsRoute(settingsTarget.serverId, settingsTarget.projectId));
|
||||
@@ -594,6 +595,7 @@ function ProjectMenuItems({
|
||||
</ProjectMenuItem>
|
||||
) : null}
|
||||
<OpenInFileManagerMenuItem
|
||||
serverId={localDaemonServerId}
|
||||
surface={surface}
|
||||
path={projectPath}
|
||||
testID={`sidebar-project-menu-open-folder-${projectViewKey}`}
|
||||
|
||||
@@ -268,6 +268,7 @@ function SidebarWorkspaceMenuItems({
|
||||
</DropdownMenuSubTrigger>
|
||||
) : null}
|
||||
<OpenInFileManagerMenuItem
|
||||
serverId={serverId}
|
||||
surface={surface}
|
||||
path={openInFileManagerPath}
|
||||
testID={`sidebar-workspace-menu-open-folder-${workspaceKey}`}
|
||||
|
||||
@@ -1,74 +0,0 @@
|
||||
import { useLayoutEffect, useState } from "react";
|
||||
import { makeMutable, type SharedValue, useSharedValue } from "react-native-reanimated";
|
||||
import { scheduleOnUI } from "react-native-worklets";
|
||||
import { useRetainedPanelActive } from "@/components/retained-panel";
|
||||
import { getStatusRingRotation } from "@/components/status-ring/geometry";
|
||||
|
||||
const sharedRotation = makeMutable(getStatusRingRotation(Date.now()));
|
||||
const activeRingCount = makeMutable(0);
|
||||
const clockRunning = makeMutable(false);
|
||||
let nextListenerId = 1;
|
||||
|
||||
function advanceSharedRotation(): void {
|
||||
"worklet";
|
||||
if (activeRingCount.value === 0) {
|
||||
clockRunning.value = false;
|
||||
return;
|
||||
}
|
||||
|
||||
sharedRotation.value = getStatusRingRotation(Date.now());
|
||||
requestAnimationFrame(advanceSharedRotation);
|
||||
}
|
||||
|
||||
function registerStatusRing(
|
||||
rotation: SharedValue<number>,
|
||||
registered: SharedValue<boolean>,
|
||||
listenerId: number,
|
||||
): void {
|
||||
"worklet";
|
||||
if (registered.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
registered.value = true;
|
||||
rotation.value = getStatusRingRotation(Date.now());
|
||||
sharedRotation.addListener(listenerId, (value) => {
|
||||
rotation.value = value;
|
||||
});
|
||||
activeRingCount.value += 1;
|
||||
|
||||
if (!clockRunning.value) {
|
||||
clockRunning.value = true;
|
||||
sharedRotation.value = getStatusRingRotation(Date.now());
|
||||
requestAnimationFrame(advanceSharedRotation);
|
||||
}
|
||||
}
|
||||
|
||||
function unregisterStatusRing(registered: SharedValue<boolean>, listenerId: number): void {
|
||||
"worklet";
|
||||
if (!registered.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
registered.value = false;
|
||||
sharedRotation.removeListener(listenerId);
|
||||
activeRingCount.value -= 1;
|
||||
}
|
||||
|
||||
export function useStatusRingRotation(): SharedValue<number> {
|
||||
const active = useRetainedPanelActive();
|
||||
// Hidden retained views must not subscribe their animated styles to the shared clock.
|
||||
const rotation = useSharedValue(getStatusRingRotation(Date.now()));
|
||||
const registered = useSharedValue(false);
|
||||
const [listenerId] = useState(() => nextListenerId++);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!active) return;
|
||||
scheduleOnUI(registerStatusRing, rotation, registered, listenerId);
|
||||
return () => {
|
||||
scheduleOnUI(unregisterStatusRing, registered, listenerId);
|
||||
};
|
||||
}, [active, listenerId, registered, rotation]);
|
||||
|
||||
return rotation;
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
import { useCallback, useLayoutEffect, useRef, type RefCallback } from "react";
|
||||
import type { View as NativeView } from "react-native";
|
||||
import { STATUS_RING_PERIOD_MS } from "@/components/status-ring/geometry";
|
||||
|
||||
const STATUS_RING_KEYFRAMES: PropertyIndexedKeyframes = {
|
||||
transform: ["rotate(0deg)", "rotate(360deg)"],
|
||||
};
|
||||
const STATUS_RING_TIMING: KeyframeAnimationOptions = {
|
||||
duration: STATUS_RING_PERIOD_MS,
|
||||
easing: "linear",
|
||||
iterations: Number.POSITIVE_INFINITY,
|
||||
};
|
||||
const STATUS_RING_TIMELINE_START_MS = 0;
|
||||
|
||||
export function useStatusRingAnimationRef(): RefCallback<NativeView> {
|
||||
const arcElement = useRef<HTMLElement | null>(null);
|
||||
const setArcElement = useCallback((instance: NativeView | null) => {
|
||||
arcElement.current = instance instanceof HTMLElement ? instance : null;
|
||||
}, []);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const element = arcElement.current;
|
||||
if (!element) {
|
||||
return;
|
||||
}
|
||||
|
||||
const animation = element.animate(STATUS_RING_KEYFRAMES, STATUS_RING_TIMING);
|
||||
animation.startTime = STATUS_RING_TIMELINE_START_MS;
|
||||
return () => {
|
||||
animation.cancel();
|
||||
};
|
||||
}, []);
|
||||
|
||||
return setArcElement;
|
||||
}
|
||||
@@ -32,7 +32,7 @@ export interface StatusRingProps {
|
||||
*/
|
||||
export function StatusRingFrame({ backdrop, children }: StatusRingProps & { children: ReactNode }) {
|
||||
return (
|
||||
<View style={[styles.frame, getBackdropStyle(backdrop)]}>
|
||||
<View style={[styles.frame, getBackdropStyle(backdrop)]} testID="status-ring">
|
||||
<View style={styles.track} />
|
||||
{children}
|
||||
<View style={styles.centerDot} />
|
||||
@@ -60,10 +60,9 @@ function getBackdropStyle(backdrop: SurfaceBackdrop | null | undefined) {
|
||||
}
|
||||
|
||||
// The rotating quarter's geometry, deliberately plain React Native rather than Unistyles: on
|
||||
// native this style lands on a Reanimated `Animated.View`, and applying a theme-tracked style to
|
||||
// one crashes when the theme changes — Unistyles and Reanimated both mutate the same native node.
|
||||
// See docs/unistyles.md. The colour it needs lives on `styles.arc`, one level in, on a view
|
||||
// Reanimated never touches.
|
||||
// native this style lands on an `Animated.View` the native animation driver writes to, and a
|
||||
// theme-tracked style on the same node gives it two writers. See docs/unistyles.md. The colour it
|
||||
// needs lives on `styles.arc`, one level in, on a view nothing animates.
|
||||
export const rotatorStyles = RNStyleSheet.create({
|
||||
rotator: {
|
||||
position: "absolute",
|
||||
|
||||
@@ -26,17 +26,11 @@ export const STATUS_RING_FRAME_SIZE = STATUS_RING_SIZE + STATUS_RING_HALO_INSET
|
||||
export const STATUS_RING_TRACK_OPACITY = 0.3;
|
||||
export const STATUS_RING_HEAD_OPACITY = 0.9;
|
||||
|
||||
// One period for every ring in the app. Each platform owns one mount-independent timeline: web
|
||||
// animations share an absolute document-timeline start, while native publishes this wall-clock
|
||||
// phase from one UI-thread clock. A row that appears mid-flight therefore lands in step with the
|
||||
// rings already turning.
|
||||
// One period for every ring in the app. Each platform runs the rings off one clock that does not
|
||||
// depend on when a ring mounted, so a row that appears mid-flight lands in step with the rings
|
||||
// already turning.
|
||||
export const STATUS_RING_PERIOD_MS = 900;
|
||||
|
||||
export function getStatusRingRotation(nowMs: number): number {
|
||||
"worklet";
|
||||
return ((nowMs % STATUS_RING_PERIOD_MS) / STATUS_RING_PERIOD_MS) * 360;
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-anchors a corner status dot's offset for the ring that replaces it.
|
||||
*
|
||||
|
||||
@@ -1,30 +1,31 @@
|
||||
import { memo } from "react";
|
||||
import { View } from "react-native";
|
||||
import Animated, { useAnimatedStyle } from "react-native-reanimated";
|
||||
import { Animated, View } from "react-native";
|
||||
import { useIndicatorMotion } from "@/components/indicator-motion";
|
||||
import { sharedIndicatorClock, useRunningClock } from "@/components/indicator-motion/clock";
|
||||
import {
|
||||
StatusRingFrame,
|
||||
type StatusRingProps,
|
||||
rotatorStyles,
|
||||
styles,
|
||||
} from "@/components/status-ring/frame";
|
||||
import { useStatusRingRotation } from "@/components/status-ring/clock";
|
||||
import { STATUS_RING_PERIOD_MS } from "@/components/status-ring/geometry";
|
||||
|
||||
/**
|
||||
* Native running indicator. The rotation is published by one shared UI-thread clock rather than
|
||||
* per-instance timing, so a ring that mounts mid-flight is already in phase — see `clock.ts`.
|
||||
*
|
||||
* The rotated view carries no theme-tracked style; the coloured arc is nested inside it. Putting
|
||||
* a Unistyles style on a Reanimated view crashes on theme change (docs/unistyles.md).
|
||||
*/
|
||||
// One rotation for every ring in the app, so a row that appears mid-flight lands in step with the
|
||||
// rings already turning.
|
||||
const rotation = sharedIndicatorClock.cycle(STATUS_RING_PERIOD_MS).interpolate({
|
||||
inputRange: [0, STATUS_RING_PERIOD_MS],
|
||||
outputRange: ["0deg", "360deg"],
|
||||
});
|
||||
const turning = { transform: [{ rotate: rotation }] };
|
||||
|
||||
/** Native running indicator. The native animation driver turns the quarter; see `clock.ts`. */
|
||||
export const StatusRing = memo(function StatusRing({ backdrop }: StatusRingProps) {
|
||||
const rotation = useStatusRingRotation();
|
||||
const rotatorStyle = useAnimatedStyle(() => ({
|
||||
transform: [{ rotate: `${rotation.value}deg` }],
|
||||
}));
|
||||
const moving = useIndicatorMotion();
|
||||
useRunningClock(sharedIndicatorClock, moving);
|
||||
|
||||
return (
|
||||
<StatusRingFrame backdrop={backdrop}>
|
||||
<Animated.View style={[rotatorStyles.rotator, rotatorStyle]}>
|
||||
<Animated.View style={[rotatorStyles.rotator, moving && turning]}>
|
||||
<View style={styles.arc} />
|
||||
</Animated.View>
|
||||
</StatusRingFrame>
|
||||
|
||||
@@ -1,20 +1,27 @@
|
||||
import { memo } from "react";
|
||||
import { View } from "react-native";
|
||||
import { useIndicatorMotion } from "@/components/indicator-motion";
|
||||
import { type IndicatorLoop, useIndicatorLoop } from "@/components/indicator-motion/loop.web";
|
||||
import {
|
||||
StatusRingFrame,
|
||||
type StatusRingProps,
|
||||
rotatorStyles,
|
||||
styles,
|
||||
} from "@/components/status-ring/frame";
|
||||
import { useStatusRingAnimationRef } from "@/components/status-ring/clock.web";
|
||||
import { STATUS_RING_PERIOD_MS } from "@/components/status-ring/geometry";
|
||||
|
||||
/**
|
||||
* Web running indicator. A sidebar full of agents can hold dozens of these at once, so the browser
|
||||
* drives the rotation from one absolute document-timeline epoch rather than from mount time — see
|
||||
* `clock.web.ts`.
|
||||
*/
|
||||
// A sidebar full of agents can hold dozens of rings at once; the shared phase keeps them turning as
|
||||
// one, and a row that appears mid-flight lands in step with the rings already turning.
|
||||
const TURNING: IndicatorLoop = {
|
||||
keyframes: [{ transform: "rotate(0deg)" }, { transform: "rotate(360deg)" }],
|
||||
durationMs: STATUS_RING_PERIOD_MS,
|
||||
phase: "shared",
|
||||
};
|
||||
|
||||
/** Web running indicator. The browser's compositor turns the quarter; see `loop.web.ts`. */
|
||||
export const StatusRing = memo(function StatusRing({ backdrop }: StatusRingProps) {
|
||||
const rotatorRef = useStatusRingAnimationRef();
|
||||
const moving = useIndicatorMotion();
|
||||
const rotatorRef = useIndicatorLoop(moving ? TURNING : null);
|
||||
|
||||
return (
|
||||
<StatusRingFrame backdrop={backdrop}>
|
||||
|
||||
@@ -1,184 +0,0 @@
|
||||
import { useLayoutEffect, useMemo, useState } from "react";
|
||||
import { View } from "react-native";
|
||||
import Animated, {
|
||||
makeMutable,
|
||||
type SharedValue,
|
||||
useAnimatedStyle,
|
||||
useReducedMotion,
|
||||
useSharedValue,
|
||||
} from "react-native-reanimated";
|
||||
import { scheduleOnUI } from "react-native-worklets";
|
||||
import { useRetainedPanelActive } from "@/components/retained-panel";
|
||||
import {
|
||||
SYNCED_LOADER_DOT_COUNT,
|
||||
getSyncedLoaderDotOpacity,
|
||||
getSyncedLoaderStep,
|
||||
} from "@/components/synced-loader-state";
|
||||
|
||||
const GRID_COLUMNS = 2;
|
||||
const DOT_KEYS = Array.from({ length: SYNCED_LOADER_DOT_COUNT }, (_, i) => `dot-${i}`);
|
||||
const sharedStep = makeMutable(0);
|
||||
const activeLoaderCount = makeMutable(0);
|
||||
const clockRunning = makeMutable(false);
|
||||
let nextStepListenerId = 1;
|
||||
|
||||
function advanceSharedStep(): void {
|
||||
"worklet";
|
||||
if (activeLoaderCount.value === 0) {
|
||||
clockRunning.value = false;
|
||||
return;
|
||||
}
|
||||
|
||||
const nextStep = getSyncedLoaderStep(Date.now());
|
||||
if (sharedStep.value !== nextStep) {
|
||||
sharedStep.value = nextStep;
|
||||
}
|
||||
requestAnimationFrame(advanceSharedStep);
|
||||
}
|
||||
|
||||
function registerStepListener(
|
||||
step: SharedValue<number>,
|
||||
registered: SharedValue<boolean>,
|
||||
listenerId: number,
|
||||
): void {
|
||||
"worklet";
|
||||
if (registered.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
registered.value = true;
|
||||
step.value = getSyncedLoaderStep(Date.now());
|
||||
sharedStep.addListener(listenerId, (nextStep) => {
|
||||
step.value = nextStep;
|
||||
});
|
||||
activeLoaderCount.value += 1;
|
||||
|
||||
if (!clockRunning.value) {
|
||||
clockRunning.value = true;
|
||||
sharedStep.value = step.value;
|
||||
requestAnimationFrame(advanceSharedStep);
|
||||
}
|
||||
}
|
||||
|
||||
function unregisterStepListener(registered: SharedValue<boolean>, listenerId: number): void {
|
||||
"worklet";
|
||||
if (!registered.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
registered.value = false;
|
||||
sharedStep.removeListener(listenerId);
|
||||
activeLoaderCount.value -= 1;
|
||||
}
|
||||
|
||||
function useSyncedLoaderStep(active: boolean, reduceMotion: boolean): SharedValue<number> {
|
||||
// The local value lets retained loaders detach from the app-wide clock without
|
||||
// unmounting their animated views or leaving hidden style worklets subscribed.
|
||||
const step = useSharedValue(reduceMotion ? 0 : getSyncedLoaderStep(Date.now()));
|
||||
const registered = useSharedValue(false);
|
||||
const [listenerId] = useState(() => nextStepListenerId++);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!active || reduceMotion) {
|
||||
return;
|
||||
}
|
||||
|
||||
scheduleOnUI(registerStepListener, step, registered, listenerId);
|
||||
return () => {
|
||||
scheduleOnUI(unregisterStepListener, registered, listenerId);
|
||||
};
|
||||
}, [active, listenerId, reduceMotion, registered, step]);
|
||||
|
||||
return step;
|
||||
}
|
||||
|
||||
export function SyncedLoader({ size = 10, color }: { size?: number; color: string }) {
|
||||
const active = useRetainedPanelActive();
|
||||
const reduceMotion = useReducedMotion();
|
||||
const step = useSyncedLoaderStep(active, reduceMotion);
|
||||
|
||||
// The 2x3 grid fills `size` exactly on its long axis: the dot is whatever is left after
|
||||
// the two gaps, not a floored integer. Flooring cost the grid up to a third of a dot per
|
||||
// row — at size 10 it drew 8pt of ink in a 10pt box and read as a small mark in a large
|
||||
// slot. Fractional dots are fine here; these are sub-pixel radii on a moving glyph.
|
||||
const gap = Math.max(1, Math.round(size * 0.12));
|
||||
const dotSize = Math.max(2, (size - gap * 2) / 3);
|
||||
const gridWidth = dotSize * 2 + gap;
|
||||
const gridHeight = dotSize * 3 + gap * 2;
|
||||
|
||||
const gridStyle = useMemo(
|
||||
() => ({ width: gridWidth, height: gridHeight }),
|
||||
[gridHeight, gridWidth],
|
||||
);
|
||||
const containerStyle = useMemo(
|
||||
() =>
|
||||
({
|
||||
width: size,
|
||||
height: size,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
}) as const,
|
||||
[size],
|
||||
);
|
||||
|
||||
return (
|
||||
<View style={containerStyle}>
|
||||
<View style={gridStyle}>
|
||||
{Array.from({ length: SYNCED_LOADER_DOT_COUNT }).map((_, dotIndex) => {
|
||||
const rowIndex = Math.floor(dotIndex / GRID_COLUMNS);
|
||||
const columnIndex = dotIndex % GRID_COLUMNS;
|
||||
|
||||
return (
|
||||
<SpinnerDot
|
||||
key={DOT_KEYS[dotIndex]}
|
||||
color={color}
|
||||
dotSize={dotSize}
|
||||
dotIndex={dotIndex}
|
||||
step={step}
|
||||
left={columnIndex * (dotSize + gap)}
|
||||
top={rowIndex * (dotSize + gap)}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function SpinnerDot({
|
||||
color,
|
||||
dotSize,
|
||||
dotIndex,
|
||||
step,
|
||||
left,
|
||||
top,
|
||||
}: {
|
||||
color: string;
|
||||
dotSize: number;
|
||||
dotIndex: number;
|
||||
step: SharedValue<number>;
|
||||
left: number;
|
||||
top: number;
|
||||
}) {
|
||||
const animatedStyle = useAnimatedStyle(() => ({
|
||||
opacity: getSyncedLoaderDotOpacity(step.value, dotIndex),
|
||||
}));
|
||||
|
||||
const dotStyle = useMemo(
|
||||
() => [
|
||||
animatedStyle,
|
||||
{
|
||||
width: dotSize,
|
||||
height: dotSize,
|
||||
borderRadius: dotSize / 2,
|
||||
backgroundColor: color,
|
||||
position: "absolute" as const,
|
||||
left,
|
||||
top,
|
||||
},
|
||||
],
|
||||
[animatedStyle, dotSize, color, left, top],
|
||||
);
|
||||
|
||||
return <Animated.View style={dotStyle} />;
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { useEffect } from "react";
|
||||
import { Animated, View } from "react-native";
|
||||
import { useIndicatorMotion } from "@/components/indicator-motion";
|
||||
import { type SyncedLoaderProps, useSyncedLoaderLayout } from "./layout";
|
||||
import {
|
||||
SYNCED_LOADER_DOT_COUNT,
|
||||
SYNCED_LOADER_RESTING_STEP,
|
||||
getSyncedLoaderDotOpacity,
|
||||
} from "./state";
|
||||
import { createSyncedLoaderStepTicker } from "./step-ticker";
|
||||
|
||||
const DOTS = Array.from({ length: SYNCED_LOADER_DOT_COUNT }, (_, dot) => dot);
|
||||
const STEPS = DOTS;
|
||||
|
||||
// The step every loader in the app is on. It lives in the native animation driver: setting it
|
||||
// updates the dots on the UI thread without a React render or a shadow tree commit.
|
||||
const step = new Animated.Value(SYNCED_LOADER_RESTING_STEP, { useNativeDriver: true });
|
||||
const ticker = createSyncedLoaderStepTicker((nextStep) => step.setValue(nextStep));
|
||||
|
||||
const blinking = DOTS.map((dot) => ({
|
||||
opacity: step.interpolate({
|
||||
inputRange: STEPS,
|
||||
outputRange: STEPS.map((atStep) => getSyncedLoaderDotOpacity(atStep, dot)),
|
||||
}),
|
||||
}));
|
||||
|
||||
const resting = DOTS.map((dot) => ({
|
||||
opacity: getSyncedLoaderDotOpacity(SYNCED_LOADER_RESTING_STEP, dot),
|
||||
}));
|
||||
|
||||
/**
|
||||
* Native loader. The step changes six times a cycle, so a timer wakes the JS thread six times a
|
||||
* cycle and hands the step to the native animation driver. No frame callback runs between steps.
|
||||
*/
|
||||
export function SyncedLoader(props: SyncedLoaderProps) {
|
||||
const layout = useSyncedLoaderLayout(props);
|
||||
const moving = useIndicatorMotion();
|
||||
const motion = moving ? blinking : resting;
|
||||
|
||||
useEffect(() => {
|
||||
if (!moving) return;
|
||||
return ticker.run();
|
||||
}, [moving]);
|
||||
|
||||
return (
|
||||
<View style={layout.container} testID="synced-loader">
|
||||
<View style={layout.grid}>
|
||||
{DOTS.map((dot) => (
|
||||
<Animated.View
|
||||
key={dot}
|
||||
style={[layout.dots[dot], motion[dot]]}
|
||||
testID="synced-loader-dot"
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { View, type ViewStyle } from "react-native";
|
||||
import { useIndicatorMotion } from "@/components/indicator-motion";
|
||||
import { type IndicatorLoop, useIndicatorLoop } from "@/components/indicator-motion/loop.web";
|
||||
import { type SyncedLoaderProps, useSyncedLoaderLayout } from "./layout";
|
||||
import {
|
||||
SYNCED_LOADER_DOT_COUNT,
|
||||
SYNCED_LOADER_DURATION_MS,
|
||||
SYNCED_LOADER_RESTING_STEP,
|
||||
getSyncedLoaderDotOpacity,
|
||||
} from "./state";
|
||||
|
||||
const DOTS = Array.from({ length: SYNCED_LOADER_DOT_COUNT }, (_, dot) => dot);
|
||||
|
||||
// One keyframe per step, held until the next: `step-end` makes the opacity jump instead of fade.
|
||||
// The shared phase keeps every loader in the app on the same step.
|
||||
const BLINKING: IndicatorLoop[] = DOTS.map((dot) => ({
|
||||
keyframes: [
|
||||
...DOTS.map((step) => ({
|
||||
offset: step / SYNCED_LOADER_DOT_COUNT,
|
||||
opacity: getSyncedLoaderDotOpacity(step, dot),
|
||||
easing: "step-end",
|
||||
})),
|
||||
{ offset: 1, opacity: getSyncedLoaderDotOpacity(0, dot) },
|
||||
],
|
||||
durationMs: SYNCED_LOADER_DURATION_MS,
|
||||
phase: "shared",
|
||||
}));
|
||||
|
||||
const RESTING = DOTS.map(
|
||||
(dot): ViewStyle => ({ opacity: getSyncedLoaderDotOpacity(SYNCED_LOADER_RESTING_STEP, dot) }),
|
||||
);
|
||||
|
||||
/**
|
||||
* Web loader. Each dot steps through its six opacities on the browser's compositor, which draws a
|
||||
* frame when a step changes and nothing in between; see `loop.web.ts`.
|
||||
*/
|
||||
export function SyncedLoader(props: SyncedLoaderProps) {
|
||||
const layout = useSyncedLoaderLayout(props);
|
||||
const moving = useIndicatorMotion();
|
||||
|
||||
return (
|
||||
<View style={layout.container} testID="synced-loader">
|
||||
<View style={layout.grid}>
|
||||
{DOTS.map((dot) => (
|
||||
<Dot key={dot} dot={dot} style={layout.dots[dot]} moving={moving} />
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function Dot({ dot, style, moving }: { dot: number; style: ViewStyle; moving: boolean }) {
|
||||
const dotRef = useIndicatorLoop(moving ? BLINKING[dot] : null);
|
||||
return <View ref={dotRef} style={[style, RESTING[dot]]} testID="synced-loader-dot" />;
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { useMemo } from "react";
|
||||
import type { ViewStyle } from "react-native";
|
||||
import { SYNCED_LOADER_DOT_COUNT } from "./state";
|
||||
|
||||
const GRID_COLUMNS = 2;
|
||||
|
||||
export interface SyncedLoaderProps {
|
||||
size?: number;
|
||||
color: string;
|
||||
}
|
||||
|
||||
export interface SyncedLoaderLayout {
|
||||
container: ViewStyle;
|
||||
grid: ViewStyle;
|
||||
/** One entry per dot, in the order the opacity states list them. */
|
||||
dots: ViewStyle[];
|
||||
}
|
||||
|
||||
/** Where the loader's six dots sit and what they look like. The platform files own how they blink. */
|
||||
export function useSyncedLoaderLayout({ size = 10, color }: SyncedLoaderProps): SyncedLoaderLayout {
|
||||
return useMemo(() => {
|
||||
// The 2x3 grid fills `size` exactly on its long axis: the dot is whatever is left after
|
||||
// the two gaps, not a floored integer. Flooring cost the grid up to a third of a dot per
|
||||
// row — at size 10 it drew 8pt of ink in a 10pt box and read as a small mark in a large
|
||||
// slot. Fractional dots are fine here; these are sub-pixel radii on a moving glyph.
|
||||
const gap = Math.max(1, Math.round(size * 0.12));
|
||||
const dotSize = Math.max(2, (size - gap * 2) / 3);
|
||||
|
||||
return {
|
||||
container: { width: size, height: size, alignItems: "center", justifyContent: "center" },
|
||||
grid: { width: dotSize * 2 + gap, height: dotSize * 3 + gap * 2 },
|
||||
dots: Array.from({ length: SYNCED_LOADER_DOT_COUNT }, (_, dot) => ({
|
||||
position: "absolute",
|
||||
left: (dot % GRID_COLUMNS) * (dotSize + gap),
|
||||
top: Math.floor(dot / GRID_COLUMNS) * (dotSize + gap),
|
||||
width: dotSize,
|
||||
height: dotSize,
|
||||
borderRadius: dotSize / 2,
|
||||
backgroundColor: color,
|
||||
})),
|
||||
};
|
||||
}, [color, size]);
|
||||
}
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { getSyncedLoaderDotOpacity, getSyncedLoaderStep } from "./synced-loader-state";
|
||||
import { getSyncedLoaderDotOpacity, getSyncedLoaderStep } from "./state";
|
||||
|
||||
describe("synced loader state", () => {
|
||||
test("advances through six wall-clock-aligned steps every 950 milliseconds", () => {
|
||||
+12
-3
@@ -1,4 +1,4 @@
|
||||
const SYNCED_LOADER_DURATION_MS = 950;
|
||||
export const SYNCED_LOADER_DURATION_MS = 950;
|
||||
export const SYNCED_LOADER_DOT_COUNT = 6;
|
||||
|
||||
const SYNCED_LOADER_OPACITY_STATES = [
|
||||
@@ -10,13 +10,22 @@ const SYNCED_LOADER_OPACITY_STATES = [
|
||||
[0, 0, 1, 0.34, 0.78, 0.56],
|
||||
] as const;
|
||||
|
||||
// The frame a loader rests on when it is not moving.
|
||||
export const SYNCED_LOADER_RESTING_STEP = 0;
|
||||
|
||||
export function getSyncedLoaderStep(nowMs: number): number {
|
||||
"worklet";
|
||||
const elapsedMs = nowMs % SYNCED_LOADER_DURATION_MS;
|
||||
return Math.floor((elapsedMs * SYNCED_LOADER_DOT_COUNT) / SYNCED_LOADER_DURATION_MS);
|
||||
}
|
||||
|
||||
/** How long after `nowMs` the loader shows its next step. Always at least a millisecond. */
|
||||
export function getSyncedLoaderStepRemainingMs(nowMs: number): number {
|
||||
const elapsedMs = nowMs % SYNCED_LOADER_DURATION_MS;
|
||||
const nextStepAtMs =
|
||||
((getSyncedLoaderStep(nowMs) + 1) * SYNCED_LOADER_DURATION_MS) / SYNCED_LOADER_DOT_COUNT;
|
||||
return Math.max(1, Math.ceil(nextStepAtMs - elapsedMs));
|
||||
}
|
||||
|
||||
export function getSyncedLoaderDotOpacity(step: number, dot: number): number {
|
||||
"worklet";
|
||||
return SYNCED_LOADER_OPACITY_STATES[step]?.[dot] ?? 0;
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
||||
import { createSyncedLoaderStepTicker } from "./step-ticker";
|
||||
|
||||
interface PublishedStep {
|
||||
step: number;
|
||||
atMs: number;
|
||||
}
|
||||
|
||||
function startRecordingTicker() {
|
||||
const published: PublishedStep[] = [];
|
||||
const ticker = createSyncedLoaderStepTicker((step) => {
|
||||
published.push({ step, atMs: Date.now() });
|
||||
});
|
||||
return { ticker, published };
|
||||
}
|
||||
|
||||
describe("synced loader step ticker", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(0);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
test("wakes once per step, six times a cycle", () => {
|
||||
const { ticker, published } = startRecordingTicker();
|
||||
|
||||
const stop = ticker.run();
|
||||
vi.advanceTimersByTime(949);
|
||||
stop();
|
||||
|
||||
expect(published).toEqual([
|
||||
{ step: 0, atMs: 0 },
|
||||
{ step: 1, atMs: 159 },
|
||||
{ step: 2, atMs: 317 },
|
||||
{ step: 3, atMs: 475 },
|
||||
{ step: 4, atMs: 634 },
|
||||
{ step: 5, atMs: 792 },
|
||||
]);
|
||||
});
|
||||
|
||||
test("starts mid-cycle on the step the wall clock is on", () => {
|
||||
vi.setSystemTime(950 * 4 + 500);
|
||||
const { ticker, published } = startRecordingTicker();
|
||||
|
||||
const stop = ticker.run();
|
||||
vi.advanceTimersByTime(140);
|
||||
stop();
|
||||
|
||||
expect(published).toEqual([
|
||||
{ step: 3, atMs: 950 * 4 + 500 },
|
||||
{ step: 4, atMs: 950 * 4 + 634 },
|
||||
]);
|
||||
});
|
||||
|
||||
test("catches up to the wall clock after a late wake-up instead of drifting", () => {
|
||||
const { ticker, published } = startRecordingTicker();
|
||||
|
||||
const stop = ticker.run();
|
||||
// The thread is busy for 400 ms, so the wake-up due at 159 ms happens at 559 ms.
|
||||
vi.setSystemTime(400);
|
||||
vi.advanceTimersByTime(159);
|
||||
vi.advanceTimersByTime(75);
|
||||
stop();
|
||||
|
||||
expect(published).toEqual([
|
||||
{ step: 0, atMs: 0 },
|
||||
{ step: 3, atMs: 559 },
|
||||
{ step: 4, atMs: 634 },
|
||||
]);
|
||||
});
|
||||
|
||||
test("keeps one timer for every loader and stops with the last one", () => {
|
||||
const { ticker, published } = startRecordingTicker();
|
||||
|
||||
const stopFirst = ticker.run();
|
||||
const stopSecond = ticker.run();
|
||||
vi.advanceTimersByTime(160);
|
||||
expect(published.map((entry) => entry.step)).toEqual([0, 1]);
|
||||
expect(vi.getTimerCount()).toBe(1);
|
||||
|
||||
stopFirst();
|
||||
vi.advanceTimersByTime(158);
|
||||
expect(published.map((entry) => entry.step)).toEqual([0, 1, 2]);
|
||||
|
||||
stopSecond();
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
vi.advanceTimersByTime(950);
|
||||
expect(published.map((entry) => entry.step)).toEqual([0, 1, 2]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
import { getSyncedLoaderStep, getSyncedLoaderStepRemainingMs } from "./state";
|
||||
|
||||
/**
|
||||
* Publishes the loader's step each time it changes, and at no other time.
|
||||
*
|
||||
* The loader has six frames a cycle, so it needs six wake-ups a cycle. Each wake-up reads the wall
|
||||
* clock and sleeps until the next step is due, which keeps a late timer from pushing every later
|
||||
* step back and keeps every loader in the app on the same step.
|
||||
*/
|
||||
export interface SyncedLoaderStepTicker {
|
||||
/** Ticks until the returned function is called. Publishes the current step at once. */
|
||||
run(): () => void;
|
||||
}
|
||||
|
||||
export function createSyncedLoaderStepTicker(
|
||||
publish: (step: number) => void,
|
||||
): SyncedLoaderStepTicker {
|
||||
let runners = 0;
|
||||
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
function tick(): void {
|
||||
const nowMs = Date.now();
|
||||
publish(getSyncedLoaderStep(nowMs));
|
||||
timer = setTimeout(tick, getSyncedLoaderStepRemainingMs(nowMs));
|
||||
}
|
||||
|
||||
return {
|
||||
run() {
|
||||
runners += 1;
|
||||
if (timer === null) {
|
||||
tick();
|
||||
}
|
||||
return () => {
|
||||
runners -= 1;
|
||||
if (runners === 0 && timer !== null) {
|
||||
clearTimeout(timer);
|
||||
timer = null;
|
||||
}
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import React, { act, useCallback, useMemo, useRef, useState, type FormEvent } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { expect, it } from "vitest";
|
||||
import { useComposerHeight } from "./height.web";
|
||||
|
||||
it("keeps height measurement bounded when editing a long multiline draft", () => {
|
||||
function Composer() {
|
||||
const textarea = useRef<HTMLTextAreaElement>(null);
|
||||
const [renderedLines, setRenderedLines] = useState(1);
|
||||
const getText = useCallback(() => textarea.current?.value ?? "", []);
|
||||
const sizing = useComposerHeight({
|
||||
getText,
|
||||
textareaRef: textarea,
|
||||
minHeight: 24,
|
||||
maxHeight: 96,
|
||||
onRenderedLinesChange: setRenderedLines,
|
||||
});
|
||||
if (sizing.mode !== "measured") throw new Error("Expected web height measurement");
|
||||
|
||||
const { onTextChange } = sizing;
|
||||
const edit = useCallback(
|
||||
(event: FormEvent<HTMLTextAreaElement>) => onTextChange("", event.currentTarget.value),
|
||||
[onTextChange],
|
||||
);
|
||||
const style = useMemo(
|
||||
() => ({ height: Number(sizing.style.height), width: 400, lineHeight: "20px" }),
|
||||
[sizing.style.height],
|
||||
);
|
||||
|
||||
return (
|
||||
<textarea ref={textarea} onInput={edit} style={style} data-multiline={renderedLines > 2} />
|
||||
);
|
||||
}
|
||||
|
||||
const container = document.body.appendChild(document.createElement("div"));
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
act(() => root.render(<Composer />));
|
||||
const editor = container.querySelector("textarea")!;
|
||||
const draft = "Review the resulting change.\n".repeat(9_000);
|
||||
|
||||
function replaceText(text: string) {
|
||||
act(() => {
|
||||
editor.value = text;
|
||||
editor.dispatchEvent(new InputEvent("input", { bubbles: true }));
|
||||
});
|
||||
}
|
||||
|
||||
replaceText(draft);
|
||||
replaceText(draft + "x");
|
||||
|
||||
expect(editor.value).toBe(draft + "x");
|
||||
expect(editor.style.height).toBe("96px");
|
||||
expect(editor.dataset.multiline).toBe("true");
|
||||
const measurement = document.querySelector<HTMLTextAreaElement>(
|
||||
'textarea[aria-hidden="true"]',
|
||||
)!;
|
||||
expect(measurement.value.length).toBeLessThan(400);
|
||||
|
||||
replaceText("Short draft");
|
||||
expect(editor.style.height).toBe("24px");
|
||||
expect(editor.dataset.multiline).toBe("false");
|
||||
} finally {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
}
|
||||
});
|
||||
@@ -33,6 +33,15 @@ const COPIED_STYLES = [
|
||||
"paddingLeft",
|
||||
] as const;
|
||||
|
||||
function prefixThroughHardLines(text: string, lines: number): string {
|
||||
let lineEnd = -1;
|
||||
for (let line = 0; line < lines; line += 1) {
|
||||
lineEnd = text.indexOf("\n", lineEnd + 1);
|
||||
if (lineEnd === -1) return text;
|
||||
}
|
||||
return text.slice(0, lineEnd + 1);
|
||||
}
|
||||
|
||||
export function useComposerHeight({
|
||||
getText,
|
||||
textareaRef,
|
||||
@@ -68,15 +77,29 @@ export function useComposerHeight({
|
||||
mirror.style[property] = computedStyle[property];
|
||||
}
|
||||
mirror.style.width = `${sourceWidth}px`;
|
||||
mirror.value = text.endsWith("\n") ? `${text} ` : text;
|
||||
const padding =
|
||||
parseFloat(computedStyle.paddingTop) + parseFloat(computedStyle.paddingBottom);
|
||||
const lineHeight = parseFloat(computedStyle.lineHeight);
|
||||
if (lineHeight > 0)
|
||||
paramsRef.current.onRenderedLinesChange?.(
|
||||
Math.round((mirror.scrollHeight - padding) / lineHeight),
|
||||
);
|
||||
setBoundedHeight(mirror.scrollHeight);
|
||||
const { maxHeight: currentMax, onRenderedLinesChange: reportLines } = paramsRef.current;
|
||||
// Complete hard lines can prove the height cap and the three-line fullscreen threshold.
|
||||
// Keep measuring the whole draft when the prefix cannot prove both.
|
||||
const measuredText =
|
||||
Number.isFinite(currentMax) && lineHeight > 0
|
||||
? prefixThroughHardLines(
|
||||
text,
|
||||
Math.max(3, Math.ceil((currentMax - padding) / lineHeight)),
|
||||
)
|
||||
: text;
|
||||
mirror.value = measuredText.endsWith("\n") ? `${measuredText} ` : measuredText;
|
||||
let scrollHeight = mirror.scrollHeight;
|
||||
if (measuredText !== text && scrollHeight < currentMax) {
|
||||
mirror.value = text.endsWith("\n") ? `${text} ` : text;
|
||||
scrollHeight = mirror.scrollHeight;
|
||||
}
|
||||
if (lineHeight > 0) {
|
||||
reportLines?.(Math.round((scrollHeight - padding) / lineHeight));
|
||||
}
|
||||
setBoundedHeight(scrollHeight);
|
||||
},
|
||||
[setBoundedHeight, textareaRef],
|
||||
);
|
||||
|
||||
@@ -366,6 +366,8 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
|
||||
viewedTimelineSyncRef.current = sync;
|
||||
setViewedTimelineSync(serverId, sync);
|
||||
sync.setActive(getIsAppVisible(appStateRef.current));
|
||||
// An online client replacement leaves isConnected unchanged, so seed each new owner.
|
||||
sync.setConnected(client.getConnectionState().status === "connected");
|
||||
const stopObservingOpenChats = observeOpenWorkspaceAgentIds(serverId, (agentIds) =>
|
||||
sync.replaceOpenTabAgentIds(agentIds),
|
||||
);
|
||||
|
||||
@@ -385,7 +385,7 @@ describe("translation resources", () => {
|
||||
expect(en.settings.host.notFound).toBe("Host not found");
|
||||
expect(en.settings.host.connections.title).toBe("Connections");
|
||||
expect(en.settings.host.daemon.restart.title).toBe("Restart daemon");
|
||||
expect(en.settings.host.orchestration.enableTools.title).toBe("Enable Paseo tools");
|
||||
expect(en.settings.host.orchestration.enableTools.title).toBe("Enable tools");
|
||||
expect(en.settings.providers.title).toBe("Providers");
|
||||
expect(en.settings.providers.models.addModel).toBe("Add model");
|
||||
expect(en.settings.providers.diagnostic.title).toBe("Diagnostic");
|
||||
|
||||
@@ -3147,15 +3147,35 @@ export const ar: TranslationResources = {
|
||||
tools: {
|
||||
instructionsTitle: "التعليمات",
|
||||
toolsTitle: "أدوات الوكلاء",
|
||||
pluginNote: "الأدوات التي تضيفها الإضافات تتبع أيضًا خيار تمكين الأدوات",
|
||||
updateHostForGroups: "حدّث هذا المضيف لضبط مجموعات الأدوات الفردية",
|
||||
groups: {
|
||||
orchestration: {
|
||||
title: "التنسيق",
|
||||
hint: "إدارة مساحات العمل والوكلاء والطرفيات والسكربتات",
|
||||
},
|
||||
schedules: {
|
||||
title: "الجداول الزمنية",
|
||||
hint: "إنشاء وإدارة الجداول الزمنية ونبضات المتابعة",
|
||||
},
|
||||
changeRequests: {
|
||||
title: "مراقبة طلبات السحب",
|
||||
hint: "مراقبة تحديثات طلبات السحب والدمج",
|
||||
},
|
||||
browser: {
|
||||
title: "المتصفح",
|
||||
hint: "التحكم في علامات تبويب متصفح Paseo بما في ذلك الجلسات المسجّل الدخول إليها. فعّل هذا الخيار فقط للوكلاء الموثوقين.",
|
||||
},
|
||||
},
|
||||
},
|
||||
orchestration: {
|
||||
title: "التنسيق",
|
||||
unavailable: "اتصل بهذا المضيف لإدارة التنسيق",
|
||||
enableTools: {
|
||||
title: "تمكين أدوات Paseo",
|
||||
hint: "سيتمكن الوكلاء من إدارة أشجار العمل والوكلاء والجداول الزمنية",
|
||||
accessibilityLabel: "حقن أدوات Paseo",
|
||||
updateFailed: "تعذر تحديث أدوات Paseo.",
|
||||
title: "تمكين الأدوات",
|
||||
hint: "يسمح لـ Paseo والإضافات بتوفير الأدوات للوكلاء.",
|
||||
accessibilityLabel: "تمكين الأدوات",
|
||||
updateFailed: "تعذر تحديث الأدوات.",
|
||||
},
|
||||
systemPrompt: {
|
||||
title: "موجه النظام",
|
||||
|
||||
@@ -3247,15 +3247,35 @@ export const en = {
|
||||
tools: {
|
||||
instructionsTitle: "Instructions",
|
||||
toolsTitle: "Agent tools",
|
||||
pluginNote: "Tools added by plugins also follow Enable tools",
|
||||
updateHostForGroups: "Update this host to configure individual tool groups",
|
||||
groups: {
|
||||
orchestration: {
|
||||
title: "Orchestration",
|
||||
hint: "Manage workspaces, agents, terminals, and scripts",
|
||||
},
|
||||
schedules: {
|
||||
title: "Schedules",
|
||||
hint: "Create and manage schedules and heartbeats",
|
||||
},
|
||||
changeRequests: {
|
||||
title: "PR watching",
|
||||
hint: "Watch pull requests and merge requests for updates",
|
||||
},
|
||||
browser: {
|
||||
title: "Browser",
|
||||
hint: "Control Paseo browser tabs, including logged-in state. Enable only for agents you trust.",
|
||||
},
|
||||
},
|
||||
},
|
||||
orchestration: {
|
||||
title: "Orchestration",
|
||||
unavailable: "Connect to this host to manage orchestration",
|
||||
enableTools: {
|
||||
title: "Enable Paseo tools",
|
||||
hint: "Agents will be able to manage worktrees, agents and schedules",
|
||||
accessibilityLabel: "Inject Paseo tools",
|
||||
updateFailed: "Unable to update Paseo tools.",
|
||||
title: "Enable tools",
|
||||
hint: "Let Paseo and plugins give tools to agents.",
|
||||
accessibilityLabel: "Enable tools",
|
||||
updateFailed: "Unable to update tools.",
|
||||
},
|
||||
systemPrompt: {
|
||||
title: "System prompt",
|
||||
|
||||
@@ -3180,15 +3180,35 @@ export const es: TranslationResources = {
|
||||
tools: {
|
||||
instructionsTitle: "Instrucciones",
|
||||
toolsTitle: "Herramientas de agentes",
|
||||
pluginNote: "Las herramientas de los plugins también siguen Habilitar herramientas",
|
||||
updateHostForGroups: "Actualiza este host para configurar grupos de herramientas",
|
||||
groups: {
|
||||
orchestration: {
|
||||
title: "Orquestación",
|
||||
hint: "Gestiona workspaces, agentes, terminales y scripts",
|
||||
},
|
||||
schedules: {
|
||||
title: "Programaciones",
|
||||
hint: "Crea y gestiona programaciones y heartbeats",
|
||||
},
|
||||
changeRequests: {
|
||||
title: "Seguimiento de PR",
|
||||
hint: "Supervisa pull requests y merge requests para ver actualizaciones",
|
||||
},
|
||||
browser: {
|
||||
title: "Navegador",
|
||||
hint: "Controla las pestañas del navegador de Paseo, incluido el estado con sesión iniciada. Actívalo solo para agentes de confianza.",
|
||||
},
|
||||
},
|
||||
},
|
||||
orchestration: {
|
||||
title: "Orquestación",
|
||||
unavailable: "Conéctese a este host para administrar la orquestación",
|
||||
enableTools: {
|
||||
title: "Habilitar herramientasPaseo",
|
||||
hint: "Los agentes podrán gestionar árboles de trabajo, agentes y horarios.",
|
||||
accessibilityLabel: "Inyectar herramientasPaseo",
|
||||
updateFailed: "No se pudieron actualizar las herramientas de Paseo.",
|
||||
title: "Habilitar herramientas",
|
||||
hint: "Permite que Paseo y los plugins proporcionen herramientas a los agentes.",
|
||||
accessibilityLabel: "Habilitar herramientas",
|
||||
updateFailed: "No se pudieron actualizar las herramientas.",
|
||||
},
|
||||
systemPrompt: {
|
||||
title: "Aviso del sistema",
|
||||
|
||||
@@ -3182,15 +3182,35 @@ export const fr: TranslationResources = {
|
||||
tools: {
|
||||
instructionsTitle: "Instructions",
|
||||
toolsTitle: "Outils des agents",
|
||||
pluginNote: "Les outils ajoutés par les plugins suivent aussi Activer les outils",
|
||||
updateHostForGroups: "Mettez à jour cet hôte pour configurer chaque groupe d'outils",
|
||||
groups: {
|
||||
orchestration: {
|
||||
title: "Orchestration",
|
||||
hint: "Gérer les workspaces, les agents, les terminaux et les scripts",
|
||||
},
|
||||
schedules: {
|
||||
title: "Planifications",
|
||||
hint: "Créer et gérer des planifications et des heartbeats",
|
||||
},
|
||||
changeRequests: {
|
||||
title: "Suivi des PR",
|
||||
hint: "Surveiller les pull requests et merge requests",
|
||||
},
|
||||
browser: {
|
||||
title: "Navigateur",
|
||||
hint: "Contrôler les onglets du navigateur Paseo, y compris les sessions connectées. Activez uniquement pour des agents de confiance.",
|
||||
},
|
||||
},
|
||||
},
|
||||
orchestration: {
|
||||
title: "Orchestration",
|
||||
unavailable: "Connectez-vous à cet hôte pour gérer l’orchestration",
|
||||
enableTools: {
|
||||
title: "Activer les outils Paseo",
|
||||
hint: "Les agents pourront gérer les worktrees, les agents et les planifications",
|
||||
accessibilityLabel: "Injecter les outils Paseo",
|
||||
updateFailed: "Impossible de mettre à jour les outils Paseo.",
|
||||
title: "Activer les outils",
|
||||
hint: "Autorise Paseo et les plugins à fournir des outils aux agents.",
|
||||
accessibilityLabel: "Activer les outils",
|
||||
updateFailed: "Impossible de mettre à jour les outils.",
|
||||
},
|
||||
systemPrompt: {
|
||||
title: "Prompt système",
|
||||
|
||||
@@ -3142,15 +3142,35 @@ export const ja: TranslationResources = {
|
||||
tools: {
|
||||
instructionsTitle: "指示",
|
||||
toolsTitle: "エージェントツール",
|
||||
pluginNote: "プラグインが追加するツールもこのスイッチに従います",
|
||||
updateHostForGroups: "ツールグループを個別に設定するにはホストを更新してください",
|
||||
groups: {
|
||||
orchestration: {
|
||||
title: "オーケストレーション",
|
||||
hint: "ワークスペース、エージェント、ターミナル、スクリプトを管理します",
|
||||
},
|
||||
schedules: {
|
||||
title: "スケジュール",
|
||||
hint: "スケジュールとハートビートを作成・管理します",
|
||||
},
|
||||
changeRequests: {
|
||||
title: "PRの監視",
|
||||
hint: "プルリクエストやマージリクエストの更新を監視します",
|
||||
},
|
||||
browser: {
|
||||
title: "ブラウザ",
|
||||
hint: "ログイン状態を含む Paseo のブラウザタブを操作します。信頼できるエージェントにのみ有効にしてください。",
|
||||
},
|
||||
},
|
||||
},
|
||||
orchestration: {
|
||||
title: "オーケストレーション",
|
||||
unavailable: "オーケストレーションを管理するにはこのホストに接続してください",
|
||||
enableTools: {
|
||||
title: "Paseoツールを有効にする",
|
||||
hint: "エージェントがワークツリー、エージェント、スケジュールを管理できるようになります",
|
||||
accessibilityLabel: "Paseoツールを有効にする",
|
||||
updateFailed: "Paseoツールを更新できませんでした。",
|
||||
title: "ツールを有効にする",
|
||||
hint: "Paseo とプラグインからエージェントへツールを提供します。",
|
||||
accessibilityLabel: "ツールを有効にする",
|
||||
updateFailed: "ツールを更新できませんでした。",
|
||||
},
|
||||
systemPrompt: {
|
||||
title: "システムプロンプト",
|
||||
|
||||
@@ -3126,15 +3126,35 @@ export const ko: TranslationResources = {
|
||||
tools: {
|
||||
instructionsTitle: "지침",
|
||||
toolsTitle: "에이전트 도구",
|
||||
pluginNote: "플러그인이 추가한 도구도 도구 활성화 스위치를 따릅니다",
|
||||
updateHostForGroups: "개별 도구 그룹을 설정하려면 이 호스트를 업데이트하세요",
|
||||
groups: {
|
||||
orchestration: {
|
||||
title: "오케스트레이션",
|
||||
hint: "워크스페이스, 에이전트, 터미널, 스크립트 관리",
|
||||
},
|
||||
schedules: {
|
||||
title: "일정",
|
||||
hint: "일정 및 하트비트 생성과 관리",
|
||||
},
|
||||
changeRequests: {
|
||||
title: "PR 감시",
|
||||
hint: "풀 리퀘스트와 머지 리퀘스트 업데이트 감시",
|
||||
},
|
||||
browser: {
|
||||
title: "브라우저",
|
||||
hint: "로그인된 상태를 포함해 Paseo 브라우저 탭을 제어합니다. 신뢰하는 에이전트에만 활성화하세요.",
|
||||
},
|
||||
},
|
||||
},
|
||||
orchestration: {
|
||||
title: "오케스트레이션",
|
||||
unavailable: "오케스트레이션을 관리하려면 이 호스트에 연결하세요",
|
||||
enableTools: {
|
||||
title: "Paseo 도구 활성화",
|
||||
hint: "에이전트가 워크트리, 에이전트, 일정을 관리할 수 있습니다",
|
||||
accessibilityLabel: "Paseo 도구 주입",
|
||||
updateFailed: "Paseo 도구를 업데이트할 수 없습니다.",
|
||||
title: "도구 활성화",
|
||||
hint: "Paseo와 플러그인이 에이전트에 도구를 제공할 수 있게 합니다.",
|
||||
accessibilityLabel: "도구 활성화",
|
||||
updateFailed: "도구를 업데이트할 수 없습니다.",
|
||||
},
|
||||
systemPrompt: {
|
||||
title: "시스템 프롬프트",
|
||||
|
||||
@@ -3161,15 +3161,35 @@ export const ptBR: TranslationResources = {
|
||||
tools: {
|
||||
instructionsTitle: "Instruções",
|
||||
toolsTitle: "Ferramentas de agentes",
|
||||
pluginNote: "Ferramentas adicionadas por plugins também seguem Ativar ferramentas",
|
||||
updateHostForGroups: "Atualize este host para configurar grupos de ferramentas",
|
||||
groups: {
|
||||
orchestration: {
|
||||
title: "Orquestração",
|
||||
hint: "Gerencie workspaces, agentes, terminais e scripts",
|
||||
},
|
||||
schedules: {
|
||||
title: "Agendamentos",
|
||||
hint: "Crie e gerencie agendamentos e heartbeats",
|
||||
},
|
||||
changeRequests: {
|
||||
title: "Monitoramento de PR",
|
||||
hint: "Acompanhe atualizações de pull requests e merge requests",
|
||||
},
|
||||
browser: {
|
||||
title: "Navegador",
|
||||
hint: "Controle abas do navegador do Paseo, incluindo sessões conectadas. Ative apenas para agentes confiáveis.",
|
||||
},
|
||||
},
|
||||
},
|
||||
orchestration: {
|
||||
title: "Orquestração",
|
||||
unavailable: "Conecte-se a este host para gerenciar a orquestração",
|
||||
enableTools: {
|
||||
title: "Ativar ferramentas do Paseo",
|
||||
hint: "Agentes poderão gerenciar worktrees, agentes e agendamentos",
|
||||
accessibilityLabel: "Injetar ferramentas do Paseo",
|
||||
updateFailed: "Não foi possível atualizar as ferramentas do Paseo.",
|
||||
title: "Ativar ferramentas",
|
||||
hint: "Permite que o Paseo e plugins forneçam ferramentas aos agentes.",
|
||||
accessibilityLabel: "Ativar ferramentas",
|
||||
updateFailed: "Não foi possível atualizar as ferramentas.",
|
||||
},
|
||||
systemPrompt: {
|
||||
title: "Prompt do sistema",
|
||||
|
||||
@@ -3169,15 +3169,35 @@ export const ru: TranslationResources = {
|
||||
tools: {
|
||||
instructionsTitle: "Инструкции",
|
||||
toolsTitle: "Инструменты агентов",
|
||||
pluginNote: "Инструменты плагинов также зависят от переключателя «Включить инструменты»",
|
||||
updateHostForGroups: "Обновите этот хост, чтобы настраивать отдельные группы инструментов",
|
||||
groups: {
|
||||
orchestration: {
|
||||
title: "Оркестрация",
|
||||
hint: "Управление рабочими пространствами, агентами, терминалами и скриптами",
|
||||
},
|
||||
schedules: {
|
||||
title: "Расписания",
|
||||
hint: "Создание и управление расписаниями и heartbeat",
|
||||
},
|
||||
changeRequests: {
|
||||
title: "Отслеживание PR",
|
||||
hint: "Отслеживание обновлений pull request и merge request",
|
||||
},
|
||||
browser: {
|
||||
title: "Браузер",
|
||||
hint: "Управление вкладками браузера Paseo, включая авторизованные сессии. Включайте только для доверенных агентов.",
|
||||
},
|
||||
},
|
||||
},
|
||||
orchestration: {
|
||||
title: "Оркестрация",
|
||||
unavailable: "Подключитесь к этому хосту, чтобы управлять оркестрацией.",
|
||||
enableTools: {
|
||||
title: "Включить инструменты Paseo",
|
||||
hint: "Агенты смогут управлять worktree, агентами и расписаниями.",
|
||||
accessibilityLabel: "Добавить инструменты Paseo",
|
||||
updateFailed: "Не удалось обновить инструменты Paseo.",
|
||||
title: "Включить инструменты",
|
||||
hint: "Позволяет Paseo и плагинам предоставлять агентам инструменты.",
|
||||
accessibilityLabel: "Включить инструменты",
|
||||
updateFailed: "Не удалось обновить инструменты.",
|
||||
},
|
||||
systemPrompt: {
|
||||
title: "Системный промпт",
|
||||
|
||||
@@ -3080,15 +3080,35 @@ export const zhCN: TranslationResources = {
|
||||
tools: {
|
||||
instructionsTitle: "指令",
|
||||
toolsTitle: "代理工具",
|
||||
pluginNote: "插件提供的工具同样受“启用工具”开关控制",
|
||||
updateHostForGroups: "更新此 Host 以单独配置各个工具组",
|
||||
groups: {
|
||||
orchestration: {
|
||||
title: "编排",
|
||||
hint: "管理工作区、智能体、终端和脚本",
|
||||
},
|
||||
schedules: {
|
||||
title: "计划任务",
|
||||
hint: "创建和管理计划任务与心跳",
|
||||
},
|
||||
changeRequests: {
|
||||
title: "PR 监控",
|
||||
hint: "监控 Pull Request 和 Merge Request 的更新",
|
||||
},
|
||||
browser: {
|
||||
title: "浏览器",
|
||||
hint: "控制 Paseo 浏览器标签页,包括已登录状态。仅对受信任的智能体启用。",
|
||||
},
|
||||
},
|
||||
},
|
||||
orchestration: {
|
||||
title: "编排",
|
||||
unavailable: "连接到这个 Host 以管理编排",
|
||||
enableTools: {
|
||||
title: "启用 Paseo tools",
|
||||
hint: "Agent 将能够管理 worktree、Agent 和计划",
|
||||
accessibilityLabel: "注入 Paseo tools",
|
||||
updateFailed: "无法更新 Paseo 工具。",
|
||||
title: "启用工具",
|
||||
hint: "允许 Paseo 和插件为智能体提供工具。",
|
||||
accessibilityLabel: "启用工具",
|
||||
updateFailed: "无法更新工具设置。",
|
||||
},
|
||||
systemPrompt: {
|
||||
title: "System prompt",
|
||||
|
||||
@@ -93,19 +93,54 @@ export function readPressModifiers(
|
||||
context: PressModifierContext = { isMac: getShortcutOs() === "mac", held: heldModifiers },
|
||||
): PressModifiers {
|
||||
const modKey: HeldModifierKey = context.isMac ? "Meta" : "Control";
|
||||
const trustEventFlags = !isTouchPressEvent(event);
|
||||
return {
|
||||
shift: hasPressFlag(event, "shiftKey") || context.held.isDown("Shift"),
|
||||
mod: hasPressFlag(event, MODIFIER_FLAGS[modKey]) || context.held.isDown(modKey),
|
||||
shift: resolveModifierFlag(event, "shiftKey", "Shift", trustEventFlags, context.held),
|
||||
mod: resolveModifierFlag(event, MODIFIER_FLAGS[modKey], modKey, trustEventFlags, context.held),
|
||||
};
|
||||
}
|
||||
|
||||
function hasPressFlag(event: unknown, flag: "shiftKey" | "metaKey" | "ctrlKey"): boolean {
|
||||
if (typeof event !== "object" || event === null) return false;
|
||||
if (Reflect.get(event, flag) === true) return true;
|
||||
function resolveModifierFlag(
|
||||
event: unknown,
|
||||
flag: "shiftKey" | "metaKey" | "ctrlKey",
|
||||
heldKey: HeldModifierKey,
|
||||
trustEventFlags: boolean,
|
||||
held: Pick<HeldModifierTracker, "isDown">,
|
||||
): boolean {
|
||||
const eventFlag = readPressFlag(event, flag);
|
||||
if (trustEventFlags && eventFlag !== undefined) {
|
||||
return eventFlag;
|
||||
}
|
||||
return eventFlag === true || held.isDown(heldKey);
|
||||
}
|
||||
|
||||
function readPressFlag(
|
||||
event: unknown,
|
||||
flag: "shiftKey" | "metaKey" | "ctrlKey",
|
||||
): boolean | undefined {
|
||||
if (typeof event !== "object" || event === null) return undefined;
|
||||
const direct = Reflect.get(event, flag);
|
||||
if (typeof direct === "boolean") return direct;
|
||||
const nativeEvent = Reflect.get(event, "nativeEvent");
|
||||
if (typeof nativeEvent !== "object" || nativeEvent === null) return undefined;
|
||||
const nativeFlag = Reflect.get(nativeEvent, flag);
|
||||
return typeof nativeFlag === "boolean" ? nativeFlag : undefined;
|
||||
}
|
||||
|
||||
function isTouchPressEvent(event: unknown): boolean {
|
||||
if (typeof event !== "object" || event === null) return false;
|
||||
return isTouchEventRecord(event) || isTouchEventRecord(Reflect.get(event, "nativeEvent"));
|
||||
}
|
||||
|
||||
function isTouchEventRecord(record: unknown): boolean {
|
||||
if (typeof record !== "object" || record === null) return false;
|
||||
if (Reflect.get(record, "pointerType") === "touch") return true;
|
||||
const type = Reflect.get(record, "type");
|
||||
if (typeof type === "string" && type.startsWith("touch")) return true;
|
||||
const sourceCapabilities = Reflect.get(record, "sourceCapabilities");
|
||||
return (
|
||||
typeof nativeEvent === "object" &&
|
||||
nativeEvent !== null &&
|
||||
Reflect.get(nativeEvent, flag) === true
|
||||
typeof sourceCapabilities === "object" &&
|
||||
sourceCapabilities !== null &&
|
||||
Reflect.get(sourceCapabilities, "firesTouchEvents") === true
|
||||
);
|
||||
}
|
||||
|
||||
@@ -407,6 +407,45 @@ describe("press modifiers", () => {
|
||||
mod: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("trusts explicit boolean flags on non-touch pointer events over stale held keys", async () => {
|
||||
const { createHeldModifierTracker, readPressModifiers } =
|
||||
await import("./internal/press-modifiers");
|
||||
const held = createHeldModifierTracker();
|
||||
// Simulate a missed key-up (e.g. OS overlay or native menu swallowing release).
|
||||
held.handleKeyDown(modifierKey("Shift", "ShiftLeft", { shiftKey: true }));
|
||||
held.handleKeyDown(modifierKey("Meta", "MetaLeft", { shiftKey: true, metaKey: true }));
|
||||
|
||||
const mouseClick = {
|
||||
nativeEvent: { shiftKey: false, metaKey: false, ctrlKey: false, pointerType: "mouse" },
|
||||
};
|
||||
expect(readPressModifiers(mouseClick, { isMac: true, held })).toEqual({
|
||||
shift: false,
|
||||
mod: false,
|
||||
});
|
||||
|
||||
// Touch-synthesized clicks on web may report false modifier flags while a hardware key is held.
|
||||
const touchPointerClick = {
|
||||
nativeEvent: { shiftKey: false, metaKey: false, ctrlKey: false, pointerType: "touch" },
|
||||
};
|
||||
expect(readPressModifiers(touchPointerClick, { isMac: true, held })).toEqual({
|
||||
shift: true,
|
||||
mod: true,
|
||||
});
|
||||
|
||||
const touchCapabilityClick = {
|
||||
nativeEvent: {
|
||||
shiftKey: false,
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
sourceCapabilities: { firesTouchEvents: true },
|
||||
},
|
||||
};
|
||||
expect(readPressModifiers(touchCapabilityClick, { isMac: true, held })).toEqual({
|
||||
shift: true,
|
||||
mod: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("non-TextInput native focus registration", () => {
|
||||
|
||||
@@ -9,6 +9,11 @@ import {
|
||||
import { useToast } from "@/contexts/toast-context";
|
||||
import { useCliInstall } from "@/desktop/hooks/use-install-status";
|
||||
import { useDaemonConfig } from "@/hooks/use-daemon-config";
|
||||
import { useHostFeature } from "@/runtime/host-features";
|
||||
import {
|
||||
createOnboardingAgentToolsPatch,
|
||||
isHostAgentToolsEnabled,
|
||||
} from "@/screens/settings/agent-tools-config";
|
||||
|
||||
export type OrchestrationChoice = "tools" | "skills" | "cli";
|
||||
type Choices = Record<OrchestrationChoice, boolean>;
|
||||
@@ -39,6 +44,7 @@ export function useOrchestrationSetup(serverId: string): OrchestrationSetupContr
|
||||
const toast = useToast();
|
||||
const skills = useAgentSkills(serverId);
|
||||
const cli = useCliInstall();
|
||||
const supportsToolsConfig = useHostFeature(serverId, "daemonToolsConfig");
|
||||
const { config, patchConfig } = useDaemonConfig(serverId);
|
||||
const [chosen, setChosen] = useState<Choices>(ALL_ON);
|
||||
// With nothing picked there is nothing to install, so skills read as off, as they do in Settings.
|
||||
@@ -60,7 +66,7 @@ export function useOrchestrationSetup(serverId: string): OrchestrationSetupContr
|
||||
|
||||
// What the host and this computer have now, or null while it is still being read. A choice is
|
||||
// skipped only when it is known to match; an unknown state is always written.
|
||||
const toolsOn = config ? config.mcp.injectIntoAgents !== false : null;
|
||||
const toolsEnabled = config ? isHostAgentToolsEnabled(config) : null;
|
||||
const skillsInstalled = skills.status ? areSkillsInstalled(skills.status) : null;
|
||||
const cliInstalled = cli.status ? cli.status.installed : null;
|
||||
const { reconcile, uninstall } = skills;
|
||||
@@ -68,16 +74,21 @@ export function useOrchestrationSetup(serverId: string): OrchestrationSetupContr
|
||||
const offersSkills = offered.skills;
|
||||
const offersCli = offered.cli;
|
||||
|
||||
const setTools = useCallback(
|
||||
(on: boolean) =>
|
||||
patchConfig({ mcp: { injectIntoAgents: on } })
|
||||
.then(Boolean, () => false)
|
||||
.then((done) => {
|
||||
if (!done) toast.error(t("settings.host.orchestration.enableTools.updateFailed"));
|
||||
return done;
|
||||
}),
|
||||
[patchConfig, t, toast],
|
||||
);
|
||||
const applyTools = useCallback(() => {
|
||||
const patch = createOnboardingAgentToolsPatch({
|
||||
enabled: choices.tools,
|
||||
currentEnabled: toolsEnabled,
|
||||
supportsToolsConfig,
|
||||
});
|
||||
if (!patch) return Promise.resolve(true);
|
||||
return patchConfig(patch)
|
||||
.then(Boolean, () => false)
|
||||
.then((done) => {
|
||||
if (!done) toast.error(t("settings.host.orchestration.enableTools.updateFailed"));
|
||||
return done;
|
||||
});
|
||||
}, [choices.tools, toolsEnabled, patchConfig, supportsToolsConfig, t, toast]);
|
||||
|
||||
const setSkillsInstalled = useCallback(
|
||||
(on: boolean) => (on ? reconcile() : uninstall()),
|
||||
[reconcile, uninstall],
|
||||
@@ -87,7 +98,7 @@ export function useOrchestrationSetup(serverId: string): OrchestrationSetupContr
|
||||
setIsApplying(true);
|
||||
try {
|
||||
const results = await Promise.all([
|
||||
choices.tools === toolsOn ? true : setTools(choices.tools),
|
||||
applyTools(),
|
||||
!offersSkills || choices.skills === skillsInstalled
|
||||
? true
|
||||
: setSkillsInstalled(choices.skills),
|
||||
@@ -98,16 +109,23 @@ export function useOrchestrationSetup(serverId: string): OrchestrationSetupContr
|
||||
setIsApplying(false);
|
||||
}
|
||||
}, [
|
||||
choices,
|
||||
toolsOn,
|
||||
setTools,
|
||||
offersSkills,
|
||||
applyTools,
|
||||
choices.cli,
|
||||
choices.skills,
|
||||
skillsInstalled,
|
||||
setSkillsInstalled,
|
||||
offersSkills,
|
||||
offersCli,
|
||||
cliInstalled,
|
||||
setCliInstalled,
|
||||
]);
|
||||
|
||||
return { choices, setChoice, offered, skills, isApplying, apply };
|
||||
return {
|
||||
choices,
|
||||
setChoice,
|
||||
offered,
|
||||
skills,
|
||||
isApplying,
|
||||
apply,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useCallback } from "react";
|
||||
import { AgentSkillsRow } from "@/agent-skills";
|
||||
import { SettingsCard } from "@/components/settings";
|
||||
import { CommandLineRow } from "@/desktop/components/integrations-section";
|
||||
import { PaseoToolsRow } from "@/screens/settings/paseo-tools-card";
|
||||
import { EnableToolsSwitchRow } from "@/screens/settings/agent-tools-row";
|
||||
import type { OrchestrationSetupController } from "../orchestration-setup";
|
||||
|
||||
/** Three switches, all on to start; Continue applies them. */
|
||||
@@ -13,7 +13,7 @@ export function OrchestrationStep({ setup }: { setup: OrchestrationSetupControll
|
||||
const setCli = useCallback((on: boolean) => setChoice("cli", on), [setChoice]);
|
||||
return (
|
||||
<SettingsCard>
|
||||
<PaseoToolsRow value={choices.tools} onValueChange={setTools} disabled={isApplying} />
|
||||
<EnableToolsSwitchRow value={choices.tools} onValueChange={setTools} disabled={isApplying} />
|
||||
{offered.skills ? (
|
||||
<AgentSkillsRow
|
||||
skills={setup.skills}
|
||||
|
||||
@@ -73,10 +73,29 @@ class FakeDirectoryClient {
|
||||
return () => handlers.delete(registered);
|
||||
}
|
||||
|
||||
private readonly rawListeners = new Set<(message: SessionOutboundMessage) => void>();
|
||||
private readonly replyWaiters = new Map<string, () => void>();
|
||||
|
||||
subscribeRawMessages(handler: (message: SessionOutboundMessage) => void): () => void {
|
||||
this.rawListeners.add(handler);
|
||||
return () => this.rawListeners.delete(handler);
|
||||
}
|
||||
|
||||
/** Resolves when a reply carrying `requestId` arrives, after every listener saw it. */
|
||||
awaitReply(requestId: string): Promise<void> {
|
||||
return new Promise((resolve) => this.replyWaiters.set(requestId, resolve));
|
||||
}
|
||||
|
||||
emit<TType extends SessionOutboundMessage["type"]>(
|
||||
message: Extract<SessionOutboundMessage, { type: TType }>,
|
||||
): void {
|
||||
for (const listener of this.rawListeners) listener(message);
|
||||
for (const handler of this.handlers.get(message.type) ?? []) handler(message);
|
||||
if (!("payload" in message)) return;
|
||||
const requestId = (message.payload as { requestId?: unknown }).requestId;
|
||||
if (typeof requestId !== "string") return;
|
||||
this.replyWaiters.get(requestId)?.();
|
||||
this.replyWaiters.delete(requestId);
|
||||
}
|
||||
|
||||
holdWorkspaceFetch(): (result: WorkspaceFetchResult) => void {
|
||||
@@ -2417,3 +2436,40 @@ it("coalesces duplicate upserts and removals within a single workspace_update ba
|
||||
directory.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("applies workspace updates the host sent before a reply by the time the reply resolves", async () => {
|
||||
const serverId = "workspace-update-before-reply";
|
||||
const { client, directory } = createDirectory(serverId);
|
||||
const store = useSessionStore.getState();
|
||||
store.initializeSession(serverId, client as unknown as DaemonClient, 1);
|
||||
store.updateSessionServerInfo(serverId, {
|
||||
serverId,
|
||||
hostname: null,
|
||||
version: "test",
|
||||
features: { workspaceMultiplicity: true, directorySync: true },
|
||||
});
|
||||
directory.setDemand({}, true);
|
||||
await directory.refreshDemand();
|
||||
|
||||
try {
|
||||
const restored = client.awaitReply("restore-1");
|
||||
client.emit({
|
||||
type: "workspace_update",
|
||||
payload: {
|
||||
kind: "upsert",
|
||||
workspace: createWorkspaceEntry("ws-restored"),
|
||||
generation: "gen-restore",
|
||||
seq: 1,
|
||||
},
|
||||
});
|
||||
client.emit({
|
||||
type: "workspace.recovery.restore.response",
|
||||
payload: { requestId: "restore-1", workspaceId: "ws-restored", accepted: true, error: null },
|
||||
});
|
||||
await restored;
|
||||
|
||||
expect(useSessionStore.getState().sessions[serverId]?.workspaces.has("ws-restored")).toBe(true);
|
||||
} finally {
|
||||
directory.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -4,7 +4,7 @@ import type {
|
||||
FetchAgentsEntry,
|
||||
FetchAgentsOptions,
|
||||
} from "@getpaseo/client/internal/daemon-client";
|
||||
import type { AgentSnapshotPayload } from "@getpaseo/protocol/messages";
|
||||
import type { AgentSnapshotPayload, SessionOutboundMessage } from "@getpaseo/protocol/messages";
|
||||
import { fetchAgentTimelineOnce } from "@/timeline/fetch-agent-timeline-once";
|
||||
import {
|
||||
normalizeProjectDescriptor,
|
||||
@@ -49,6 +49,17 @@ interface WorkspaceDeltaFlushHandle {
|
||||
cancel: () => void;
|
||||
}
|
||||
|
||||
function isReply(message: SessionOutboundMessage): boolean {
|
||||
if (!("payload" in message)) return false;
|
||||
const payload: unknown = message.payload;
|
||||
return (
|
||||
typeof payload === "object" &&
|
||||
payload !== null &&
|
||||
"requestId" in payload &&
|
||||
typeof payload.requestId === "string"
|
||||
);
|
||||
}
|
||||
|
||||
function scheduleWorkspaceDeltaFlush(callback: () => void): WorkspaceDeltaFlushHandle {
|
||||
let done = false;
|
||||
let rafId: number | null = null;
|
||||
@@ -204,6 +215,7 @@ export class DirectorySync {
|
||||
delta: WorkspaceDirectoryDelta;
|
||||
}> = [];
|
||||
private workspaceDeltaFlush: WorkspaceDeltaFlushHandle | null = null;
|
||||
private stopObservingReplies: (() => void) | null = null;
|
||||
|
||||
constructor(
|
||||
private readonly serverId: string,
|
||||
@@ -235,10 +247,13 @@ export class DirectorySync {
|
||||
this.flushAbortedTransactions();
|
||||
this.releaseSubscriptions();
|
||||
this.releaseScriptStatusEvents();
|
||||
this.stopObservingReplies?.();
|
||||
this.stopObservingReplies = null;
|
||||
workspaceLabels.disconnect(this.serverId);
|
||||
this.connection = connection;
|
||||
this.abortPendingSessionWaits();
|
||||
if (!connection.client || connection.status !== "online") return true;
|
||||
this.stopObservingReplies = this.applyWorkspaceUpdatesBeforeReplies(connection.client);
|
||||
if (this.scriptStatusDemand.size > 0) this.observeScriptStatusEvents();
|
||||
// Reattach labels here because route-only demand can satisfy the epoch before full demand requests them.
|
||||
void this.connectWorkspaceLabels().catch(() => undefined);
|
||||
@@ -294,6 +309,8 @@ export class DirectorySync {
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.stopObservingReplies?.();
|
||||
this.stopObservingReplies = null;
|
||||
this.cancelPendingWorkspaceDeltas();
|
||||
this.flushAbortedTransactions();
|
||||
this.abortPendingSessionWaits();
|
||||
@@ -357,6 +374,16 @@ export class DirectorySync {
|
||||
this.applyWorkspaceDeltas([{ source, delta }]);
|
||||
}
|
||||
|
||||
/**
|
||||
* The host sends a workspace update before the reply to the request that caused it, so a
|
||||
* caller reading the store after its reply must see the update. Buffered updates end at a reply.
|
||||
*/
|
||||
private applyWorkspaceUpdatesBeforeReplies(client: DaemonClient): () => void {
|
||||
return client.subscribeRawMessages((message) => {
|
||||
if (isReply(message)) this.flushPendingWorkspaceDeltas();
|
||||
});
|
||||
}
|
||||
|
||||
private flushPendingWorkspaceDeltas(): void {
|
||||
if (this.workspaceDeltaFlush) {
|
||||
this.workspaceDeltaFlush.cancel();
|
||||
|
||||
@@ -206,6 +206,10 @@ class FakeDaemonClient {
|
||||
this.setConnectionState({ status: "connected" });
|
||||
}
|
||||
|
||||
subscribeRawMessages(_handler: (message: SessionOutboundMessage) => void): () => void {
|
||||
return () => {};
|
||||
}
|
||||
|
||||
subscribeConnectionStatus(listener: (status: ConnectionState) => void): () => void {
|
||||
this.listeners.add(listener);
|
||||
listener(this.state);
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
import type { MutableDaemonConfig } from "@getpaseo/protocol/messages";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
createAgentToolGroupPatch,
|
||||
createAgentToolsMasterPatch,
|
||||
createOnboardingAgentToolsPatch,
|
||||
DEFAULT_AGENT_TOOL_GROUPS,
|
||||
isHostAgentToolsEnabled,
|
||||
resolveAgentToolsState,
|
||||
} from "./agent-tools-config";
|
||||
|
||||
function makeConfig(overrides: Partial<MutableDaemonConfig> = {}): MutableDaemonConfig {
|
||||
return {
|
||||
relay: { enabled: false },
|
||||
mcp: { injectIntoAgents: true },
|
||||
browserTools: { enabled: false },
|
||||
providers: {},
|
||||
metadataGeneration: { providers: [] },
|
||||
autoArchiveAfterMerge: false,
|
||||
enableTerminalAgentHooks: false,
|
||||
appendSystemPrompt: "",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("agent tools UI state and legacy daemon compatibility", () => {
|
||||
it("reads unified daemon.tools state from a modern daemon", () => {
|
||||
const state = resolveAgentToolsState({
|
||||
config: makeConfig({
|
||||
tools: {
|
||||
enabled: true,
|
||||
groups: {
|
||||
orchestration: true,
|
||||
schedules: false,
|
||||
changeRequests: true,
|
||||
browser: true,
|
||||
},
|
||||
},
|
||||
mcp: { injectIntoAgents: true },
|
||||
browserTools: { enabled: true },
|
||||
}),
|
||||
supportsToolsConfig: true,
|
||||
});
|
||||
|
||||
expect(state).toEqual({
|
||||
enabled: true,
|
||||
groups: {
|
||||
orchestration: true,
|
||||
schedules: false,
|
||||
changeRequests: true,
|
||||
browser: true,
|
||||
},
|
||||
supportsGroupControls: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves saved group values when master enabled is false", () => {
|
||||
const state = resolveAgentToolsState({
|
||||
config: makeConfig({
|
||||
tools: {
|
||||
enabled: false,
|
||||
groups: {
|
||||
orchestration: false,
|
||||
schedules: true,
|
||||
changeRequests: false,
|
||||
browser: true,
|
||||
},
|
||||
},
|
||||
mcp: { injectIntoAgents: false },
|
||||
browserTools: { enabled: true },
|
||||
}),
|
||||
supportsToolsConfig: true,
|
||||
});
|
||||
|
||||
expect(state.enabled).toBe(false);
|
||||
expect(state.groups).toEqual({
|
||||
orchestration: false,
|
||||
schedules: true,
|
||||
changeRequests: false,
|
||||
browser: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back cleanly to legacy mcp.injectIntoAgents and browserTools.enabled on older daemons", () => {
|
||||
const state = resolveAgentToolsState({
|
||||
config: makeConfig({
|
||||
mcp: { injectIntoAgents: false },
|
||||
browserTools: { enabled: true },
|
||||
}),
|
||||
supportsToolsConfig: false,
|
||||
});
|
||||
|
||||
expect(state).toEqual({
|
||||
enabled: false,
|
||||
groups: {
|
||||
...DEFAULT_AGENT_TOOL_GROUPS,
|
||||
browser: true,
|
||||
},
|
||||
supportsGroupControls: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("builds tools.* patches for modern daemons and legacy mcp/browserTools patches for older daemons", () => {
|
||||
expect(createAgentToolsMasterPatch({ enabled: false, supportsToolsConfig: true })).toEqual({
|
||||
tools: { enabled: false },
|
||||
});
|
||||
expect(createAgentToolsMasterPatch({ enabled: false, supportsToolsConfig: false })).toEqual({
|
||||
mcp: { injectIntoAgents: false },
|
||||
});
|
||||
|
||||
expect(
|
||||
createAgentToolGroupPatch({
|
||||
group: "schedules",
|
||||
enabled: false,
|
||||
supportsToolsConfig: true,
|
||||
}),
|
||||
).toEqual({
|
||||
tools: { groups: { schedules: false } },
|
||||
});
|
||||
expect(
|
||||
createAgentToolGroupPatch({
|
||||
group: "browser",
|
||||
enabled: true,
|
||||
supportsToolsConfig: false,
|
||||
}),
|
||||
).toEqual({
|
||||
browserTools: { enabled: true },
|
||||
});
|
||||
expect(
|
||||
createAgentToolGroupPatch({
|
||||
group: "orchestration",
|
||||
enabled: false,
|
||||
supportsToolsConfig: false,
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("setup writes only the main switch, and only when it differs from the host", () => {
|
||||
expect(
|
||||
createOnboardingAgentToolsPatch({
|
||||
enabled: true,
|
||||
currentEnabled: true,
|
||||
supportsToolsConfig: true,
|
||||
}),
|
||||
).toBeNull();
|
||||
|
||||
expect(
|
||||
createOnboardingAgentToolsPatch({
|
||||
enabled: true,
|
||||
currentEnabled: false,
|
||||
supportsToolsConfig: true,
|
||||
}),
|
||||
).toEqual({ tools: { enabled: true } });
|
||||
|
||||
expect(
|
||||
createOnboardingAgentToolsPatch({
|
||||
enabled: true,
|
||||
currentEnabled: null,
|
||||
supportsToolsConfig: true,
|
||||
}),
|
||||
).toEqual({ tools: { enabled: true } });
|
||||
|
||||
expect(
|
||||
createOnboardingAgentToolsPatch({
|
||||
enabled: false,
|
||||
currentEnabled: true,
|
||||
supportsToolsConfig: false,
|
||||
}),
|
||||
).toEqual({ mcp: { injectIntoAgents: false } });
|
||||
});
|
||||
|
||||
it("reports whether host agent tools are enabled", () => {
|
||||
expect(isHostAgentToolsEnabled(null)).toBe(true);
|
||||
expect(isHostAgentToolsEnabled(makeConfig({ tools: { enabled: true } }))).toBe(true);
|
||||
expect(isHostAgentToolsEnabled(makeConfig({ tools: { enabled: false } }))).toBe(false);
|
||||
expect(isHostAgentToolsEnabled(makeConfig({ mcp: { injectIntoAgents: false } }))).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,85 @@
|
||||
import {
|
||||
BUILTIN_TOOL_GROUPS,
|
||||
DEFAULT_DAEMON_TOOL_GROUPS,
|
||||
type BuiltInToolGroup,
|
||||
type MutableDaemonConfig,
|
||||
type MutableDaemonConfigPatch,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
|
||||
export type AgentToolGroupId = BuiltInToolGroup;
|
||||
export type AgentToolGroupsState = Record<AgentToolGroupId, boolean>;
|
||||
|
||||
export const AGENT_TOOL_GROUP_ORDER: readonly AgentToolGroupId[] = BUILTIN_TOOL_GROUPS;
|
||||
export const DEFAULT_AGENT_TOOL_GROUPS: AgentToolGroupsState = { ...DEFAULT_DAEMON_TOOL_GROUPS };
|
||||
|
||||
export interface ResolvedAgentToolsState {
|
||||
enabled: boolean;
|
||||
groups: AgentToolGroupsState;
|
||||
supportsGroupControls: boolean;
|
||||
}
|
||||
|
||||
export function isHostAgentToolsEnabled(config: MutableDaemonConfig | null | undefined): boolean {
|
||||
if (!config) return true;
|
||||
// COMPAT(daemonToolsConfig): added in v0.18.2, remove after 2027-06-01.
|
||||
return config.tools?.enabled ?? config.mcp.injectIntoAgents !== false;
|
||||
}
|
||||
|
||||
export function resolveAgentToolsState(input: {
|
||||
config: MutableDaemonConfig | null | undefined;
|
||||
supportsToolsConfig: boolean;
|
||||
}): ResolvedAgentToolsState {
|
||||
const { config, supportsToolsConfig } = input;
|
||||
const enabled = isHostAgentToolsEnabled(config);
|
||||
const groups: AgentToolGroupsState = {
|
||||
orchestration: config?.tools?.groups?.orchestration ?? DEFAULT_AGENT_TOOL_GROUPS.orchestration,
|
||||
schedules: config?.tools?.groups?.schedules ?? DEFAULT_AGENT_TOOL_GROUPS.schedules,
|
||||
changeRequests:
|
||||
config?.tools?.groups?.changeRequests ?? DEFAULT_AGENT_TOOL_GROUPS.changeRequests,
|
||||
// COMPAT(daemonToolsConfig): added in v0.18.2, remove after 2027-06-01.
|
||||
browser: config?.tools?.groups?.browser ?? config?.browserTools.enabled === true,
|
||||
};
|
||||
return {
|
||||
enabled,
|
||||
groups,
|
||||
supportsGroupControls: supportsToolsConfig,
|
||||
};
|
||||
}
|
||||
|
||||
export function createAgentToolsMasterPatch(input: {
|
||||
enabled: boolean;
|
||||
supportsToolsConfig: boolean;
|
||||
}): MutableDaemonConfigPatch {
|
||||
if (input.supportsToolsConfig) {
|
||||
return { tools: { enabled: input.enabled } };
|
||||
}
|
||||
// COMPAT(daemonToolsConfig): added in v0.18.2, remove after 2027-06-01.
|
||||
return { mcp: { injectIntoAgents: input.enabled } };
|
||||
}
|
||||
|
||||
export function createAgentToolGroupPatch(input: {
|
||||
group: AgentToolGroupId;
|
||||
enabled: boolean;
|
||||
supportsToolsConfig: boolean;
|
||||
}): MutableDaemonConfigPatch | null {
|
||||
if (input.supportsToolsConfig) {
|
||||
return { tools: { groups: { [input.group]: input.enabled } } };
|
||||
}
|
||||
// COMPAT(daemonToolsConfig): added in v0.18.2, remove after 2027-06-01.
|
||||
if (input.group === "browser") {
|
||||
return { browserTools: { enabled: input.enabled } };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup only sets the main switch. It never writes tool groups, so the host keeps the groups saved
|
||||
* in Settings. An unknown host state is always written.
|
||||
*/
|
||||
export function createOnboardingAgentToolsPatch(input: {
|
||||
enabled: boolean;
|
||||
currentEnabled: boolean | null;
|
||||
supportsToolsConfig: boolean;
|
||||
}): MutableDaemonConfigPatch | null {
|
||||
if (input.currentEnabled === input.enabled) return null;
|
||||
return createAgentToolsMasterPatch(input);
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import React, { act, useCallback, useState } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { I18nextProvider } from "react-i18next";
|
||||
import { SettingsCard } from "@/components/settings";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import {
|
||||
DEFAULT_AGENT_TOOL_GROUPS,
|
||||
type AgentToolGroupId,
|
||||
type AgentToolGroupsState,
|
||||
} from "./agent-tools-config";
|
||||
import { AgentToolsRow } from "./agent-tools-row";
|
||||
|
||||
let root: Root | null = null;
|
||||
let container: HTMLDivElement | null = null;
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root?.unmount());
|
||||
container?.remove();
|
||||
root = null;
|
||||
container = null;
|
||||
});
|
||||
|
||||
function Harness({
|
||||
initialEnabled = true,
|
||||
initialGroups = DEFAULT_AGENT_TOOL_GROUPS,
|
||||
supportsGroupControls = true,
|
||||
}: {
|
||||
initialEnabled?: boolean;
|
||||
initialGroups?: AgentToolGroupsState;
|
||||
supportsGroupControls?: boolean;
|
||||
}) {
|
||||
const [enabled, setEnabled] = useState(initialEnabled);
|
||||
const [groups, setGroups] = useState<AgentToolGroupsState>(initialGroups);
|
||||
|
||||
const handleGroupChange = useCallback((group: AgentToolGroupId, next: boolean) => {
|
||||
setGroups((current) => ({ ...current, [group]: next }));
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<I18nextProvider i18n={i18n}>
|
||||
<SettingsCard>
|
||||
<AgentToolsRow
|
||||
enabled={enabled}
|
||||
groups={groups}
|
||||
supportsGroupControls={supportsGroupControls}
|
||||
onEnabledChange={setEnabled}
|
||||
onGroupChange={handleGroupChange}
|
||||
/>
|
||||
</SettingsCard>
|
||||
</I18nextProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function mount(props?: React.ComponentProps<typeof Harness>) {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
act(() => {
|
||||
root?.render(<Harness {...props} />);
|
||||
});
|
||||
}
|
||||
|
||||
function byTestId(testID: string): HTMLElement | null {
|
||||
return document.querySelector(`[data-testid="${testID}"]`);
|
||||
}
|
||||
|
||||
function expandButton(): HTMLElement {
|
||||
const row = byTestId("host-page-tools-row-toggle");
|
||||
const button = row?.querySelector('[role="button"]');
|
||||
if (!(button instanceof HTMLElement)) {
|
||||
throw new Error("Expected expand button in host-page-tools-row-toggle");
|
||||
}
|
||||
return button;
|
||||
}
|
||||
|
||||
describe("AgentToolsRow collapsible behavior", () => {
|
||||
it("starts collapsed, expands to show all four groups, and preserves selections when toggled off and on", () => {
|
||||
mount({
|
||||
initialEnabled: true,
|
||||
initialGroups: {
|
||||
orchestration: true,
|
||||
schedules: false,
|
||||
changeRequests: true,
|
||||
browser: true,
|
||||
},
|
||||
});
|
||||
|
||||
const masterSwitch = byTestId("host-page-tools-master-switch");
|
||||
expect(masterSwitch?.getAttribute("aria-checked")).toBe("true");
|
||||
expect(byTestId("host-page-tool-group-orchestration")).toBeNull();
|
||||
|
||||
// Expand the row
|
||||
act(() => {
|
||||
expandButton().click();
|
||||
});
|
||||
|
||||
expect(byTestId("host-page-tool-group-orchestration")).not.toBeNull();
|
||||
expect(byTestId("host-page-tool-group-schedules")).not.toBeNull();
|
||||
expect(byTestId("host-page-tool-group-changeRequests")).not.toBeNull();
|
||||
expect(byTestId("host-page-browser-tools-card")).not.toBeNull();
|
||||
expect(document.body.textContent).toContain("Tools added by plugins also follow Enable tools");
|
||||
expect(document.body.textContent).not.toContain("MCP");
|
||||
|
||||
const browserSwitch = byTestId("host-page-browser-tools-switch")!;
|
||||
const schedulesSwitch = byTestId("host-page-tool-group-schedules-switch")!;
|
||||
expect(browserSwitch.getAttribute("aria-checked")).toBe("true");
|
||||
expect(schedulesSwitch.getAttribute("aria-checked")).toBe("false");
|
||||
expect(browserSwitch.getAttribute("aria-disabled")).not.toBe("true");
|
||||
|
||||
// Turn master switch off: stays expanded, disables group switches, preserves selections
|
||||
act(() => {
|
||||
masterSwitch?.click();
|
||||
});
|
||||
|
||||
expect(masterSwitch?.getAttribute("aria-checked")).toBe("false");
|
||||
expect(browserSwitch.getAttribute("aria-disabled")).toBe("true");
|
||||
expect(browserSwitch.getAttribute("aria-checked")).toBe("true");
|
||||
expect(schedulesSwitch.getAttribute("aria-disabled")).toBe("true");
|
||||
expect(schedulesSwitch.getAttribute("aria-checked")).toBe("false");
|
||||
|
||||
// Turn master switch back on: group switches become interactive again with saved state
|
||||
act(() => {
|
||||
masterSwitch?.click();
|
||||
});
|
||||
|
||||
expect(masterSwitch?.getAttribute("aria-checked")).toBe("true");
|
||||
expect(browserSwitch.getAttribute("aria-disabled")).not.toBe("true");
|
||||
expect(browserSwitch.getAttribute("aria-checked")).toBe("true");
|
||||
});
|
||||
|
||||
it("shows only Browser and an update hint on older daemons without daemonToolsConfig", () => {
|
||||
mount({ supportsGroupControls: false });
|
||||
|
||||
act(() => {
|
||||
expandButton().click();
|
||||
});
|
||||
|
||||
expect(byTestId("host-page-browser-tools-card")).not.toBeNull();
|
||||
expect(byTestId("host-page-tool-group-orchestration")).toBeNull();
|
||||
expect(byTestId("host-page-tool-group-schedules")).toBeNull();
|
||||
expect(byTestId("host-page-tool-group-changeRequests")).toBeNull();
|
||||
expect(document.body.textContent).toContain(
|
||||
"Update this host to configure individual tool groups",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,272 @@
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { Text, View } from "react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import type { MutableDaemonConfigPatch } from "@getpaseo/protocol/messages";
|
||||
import { SettingsCollapsibleRow, SettingsRow } from "@/components/settings";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { useDaemonConfig } from "@/hooks/use-daemon-config";
|
||||
import { useHostFeature } from "@/runtime/host-features";
|
||||
import { useHostRuntimeIsConnected } from "@/runtime/host-runtime";
|
||||
import { settingsStyles } from "@/styles/settings";
|
||||
import {
|
||||
AGENT_TOOL_GROUP_ORDER,
|
||||
createAgentToolGroupPatch,
|
||||
createAgentToolsMasterPatch,
|
||||
resolveAgentToolsState,
|
||||
type AgentToolGroupId,
|
||||
type AgentToolGroupsState,
|
||||
} from "./agent-tools-config";
|
||||
|
||||
const GROUP_TRANSLATION_KEYS: Record<
|
||||
AgentToolGroupId,
|
||||
{
|
||||
title:
|
||||
| "settings.host.tools.groups.orchestration.title"
|
||||
| "settings.host.tools.groups.schedules.title"
|
||||
| "settings.host.tools.groups.changeRequests.title"
|
||||
| "settings.host.tools.groups.browser.title";
|
||||
hint:
|
||||
| "settings.host.tools.groups.orchestration.hint"
|
||||
| "settings.host.tools.groups.schedules.hint"
|
||||
| "settings.host.tools.groups.changeRequests.hint"
|
||||
| "settings.host.tools.groups.browser.hint";
|
||||
}
|
||||
> = {
|
||||
orchestration: {
|
||||
title: "settings.host.tools.groups.orchestration.title",
|
||||
hint: "settings.host.tools.groups.orchestration.hint",
|
||||
},
|
||||
schedules: {
|
||||
title: "settings.host.tools.groups.schedules.title",
|
||||
hint: "settings.host.tools.groups.schedules.hint",
|
||||
},
|
||||
changeRequests: {
|
||||
title: "settings.host.tools.groups.changeRequests.title",
|
||||
hint: "settings.host.tools.groups.changeRequests.hint",
|
||||
},
|
||||
browser: {
|
||||
title: "settings.host.tools.groups.browser.title",
|
||||
hint: "settings.host.tools.groups.browser.hint",
|
||||
},
|
||||
};
|
||||
|
||||
function toErrorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
function resolveHintStatus(
|
||||
error: string | null | undefined,
|
||||
isPending: boolean | undefined,
|
||||
): "error" | "busy" | undefined {
|
||||
if (error) return "error";
|
||||
if (isPending) return "busy";
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** The host's expandable "Enable tools" row, bound to the host's config, for composing inside a SettingsCard. */
|
||||
export function HostAgentToolsRow({ serverId }: { serverId: string }) {
|
||||
const { t } = useTranslation();
|
||||
const isConnected = useHostRuntimeIsConnected(serverId);
|
||||
const supportsToolsConfig = useHostFeature(serverId, "daemonToolsConfig");
|
||||
const { config, patchConfig } = useDaemonConfig(serverId);
|
||||
const state = useMemo(
|
||||
() => resolveAgentToolsState({ config, supportsToolsConfig }),
|
||||
[config, supportsToolsConfig],
|
||||
);
|
||||
|
||||
const mutation = useMutation({
|
||||
mutationFn: async (patch: MutableDaemonConfigPatch) => {
|
||||
const result = await patchConfig(patch);
|
||||
if (!result) {
|
||||
throw new Error(t("workspace.terminal.hostDisconnected"));
|
||||
}
|
||||
return result;
|
||||
},
|
||||
});
|
||||
|
||||
const handleEnabledChange = useCallback(
|
||||
(enabled: boolean) => {
|
||||
mutation.mutate(createAgentToolsMasterPatch({ enabled, supportsToolsConfig }));
|
||||
},
|
||||
[mutation, supportsToolsConfig],
|
||||
);
|
||||
|
||||
const handleGroupChange = useCallback(
|
||||
(group: AgentToolGroupId, enabled: boolean) => {
|
||||
const patch = createAgentToolGroupPatch({ group, enabled, supportsToolsConfig });
|
||||
if (!patch) return;
|
||||
mutation.mutate(patch);
|
||||
},
|
||||
[mutation, supportsToolsConfig],
|
||||
);
|
||||
|
||||
if (!isConnected) return null;
|
||||
|
||||
return (
|
||||
<AgentToolsRow
|
||||
enabled={state.enabled}
|
||||
groups={state.groups}
|
||||
supportsGroupControls={state.supportsGroupControls}
|
||||
onEnabledChange={handleEnabledChange}
|
||||
onGroupChange={handleGroupChange}
|
||||
isPending={mutation.isPending}
|
||||
error={mutation.error ? toErrorMessage(mutation.error) : null}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/** Plain "Enable tools" switch with no group controls, for setup. Groups stay in Settings. */
|
||||
export function EnableToolsSwitchRow({
|
||||
value,
|
||||
onValueChange,
|
||||
disabled,
|
||||
}: {
|
||||
value: boolean;
|
||||
onValueChange: (enabled: boolean) => void;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<SettingsRow
|
||||
label={t("settings.host.orchestration.enableTools.title")}
|
||||
hint={t("settings.host.orchestration.enableTools.hint")}
|
||||
>
|
||||
<Switch
|
||||
value={value}
|
||||
onValueChange={onValueChange}
|
||||
disabled={disabled}
|
||||
accessibilityLabel={t("settings.host.orchestration.enableTools.accessibilityLabel")}
|
||||
/>
|
||||
</SettingsRow>
|
||||
);
|
||||
}
|
||||
|
||||
/** Expandable "Enable tools" row on its own, for callers that control the state. */
|
||||
export function AgentToolsRow({
|
||||
enabled,
|
||||
groups,
|
||||
supportsGroupControls,
|
||||
onEnabledChange,
|
||||
onGroupChange,
|
||||
disabled,
|
||||
isPending,
|
||||
error,
|
||||
}: {
|
||||
enabled: boolean;
|
||||
groups: AgentToolGroupsState;
|
||||
supportsGroupControls: boolean;
|
||||
onEnabledChange: (enabled: boolean) => void;
|
||||
onGroupChange: (group: AgentToolGroupId, enabled: boolean) => void;
|
||||
disabled?: boolean;
|
||||
isPending?: boolean;
|
||||
error?: string | null;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const visibleGroups: readonly AgentToolGroupId[] = supportsGroupControls
|
||||
? AGENT_TOOL_GROUP_ORDER
|
||||
: ["browser"];
|
||||
const controlsDisabled = Boolean(disabled || isPending);
|
||||
const hint = error ?? t("settings.host.orchestration.enableTools.hint");
|
||||
const hintStatus = resolveHintStatus(error, isPending);
|
||||
|
||||
const masterControl = useMemo(
|
||||
() => (
|
||||
<Switch
|
||||
value={enabled}
|
||||
onValueChange={onEnabledChange}
|
||||
disabled={controlsDisabled}
|
||||
accessibilityLabel={t("settings.host.orchestration.enableTools.accessibilityLabel")}
|
||||
testID="host-page-tools-master-switch"
|
||||
/>
|
||||
),
|
||||
[controlsDisabled, enabled, onEnabledChange, t],
|
||||
);
|
||||
|
||||
return (
|
||||
<SettingsCollapsibleRow
|
||||
label={t("settings.host.orchestration.enableTools.title")}
|
||||
hint={hint}
|
||||
hintStatus={hintStatus}
|
||||
control={masterControl}
|
||||
testID="host-page-tools-row"
|
||||
>
|
||||
{visibleGroups.map((group) => (
|
||||
<ToolGroupSwitchRow
|
||||
key={group}
|
||||
group={group}
|
||||
value={groups[group]}
|
||||
disabled={controlsDisabled || !enabled}
|
||||
dimmed={!enabled}
|
||||
onGroupChange={onGroupChange}
|
||||
/>
|
||||
))}
|
||||
<View style={styles.noteRow}>
|
||||
<Text style={settingsStyles.rowHint}>
|
||||
{supportsGroupControls
|
||||
? t("settings.host.tools.pluginNote")
|
||||
: t("settings.host.tools.updateHostForGroups")}
|
||||
</Text>
|
||||
</View>
|
||||
</SettingsCollapsibleRow>
|
||||
);
|
||||
}
|
||||
|
||||
function ToolGroupSwitchRow({
|
||||
group,
|
||||
value,
|
||||
disabled,
|
||||
dimmed,
|
||||
onGroupChange,
|
||||
}: {
|
||||
group: AgentToolGroupId;
|
||||
value: boolean;
|
||||
disabled: boolean;
|
||||
dimmed: boolean;
|
||||
onGroupChange: (group: AgentToolGroupId, enabled: boolean) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const keys = GROUP_TRANSLATION_KEYS[group];
|
||||
const label = t(keys.title);
|
||||
const handleChange = useCallback(
|
||||
(next: boolean) => {
|
||||
onGroupChange(group, next);
|
||||
},
|
||||
[group, onGroupChange],
|
||||
);
|
||||
|
||||
return (
|
||||
<View style={dimmed ? styles.disabledGroup : undefined}>
|
||||
<SettingsRow
|
||||
label={label}
|
||||
hint={t(keys.hint)}
|
||||
testID={
|
||||
group === "browser" ? "host-page-browser-tools-card" : `host-page-tool-group-${group}`
|
||||
}
|
||||
>
|
||||
<Switch
|
||||
value={value}
|
||||
onValueChange={handleChange}
|
||||
disabled={disabled}
|
||||
accessibilityLabel={label}
|
||||
testID={
|
||||
group === "browser"
|
||||
? "host-page-browser-tools-switch"
|
||||
: `host-page-tool-group-${group}-switch`
|
||||
}
|
||||
/>
|
||||
</SettingsRow>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
disabledGroup: {
|
||||
opacity: theme.opacity[50],
|
||||
},
|
||||
noteRow: {
|
||||
paddingHorizontal: theme.spacing[4],
|
||||
paddingVertical: theme.spacing[2],
|
||||
},
|
||||
}));
|
||||
@@ -1,74 +0,0 @@
|
||||
import React, { useCallback, useMemo } from "react";
|
||||
import { Text, View } from "react-native";
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { SettingsRow } from "@/components/settings";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { useDaemonConfig } from "@/hooks/use-daemon-config";
|
||||
import { useHostRuntimeIsConnected } from "@/runtime/host-runtime";
|
||||
import { settingsStyles } from "@/styles/settings";
|
||||
import {
|
||||
createBrowserToolsPatch,
|
||||
getBrowserToolsCardState,
|
||||
getBrowserToolsMutationViewState,
|
||||
} from "./browser-tools-config";
|
||||
|
||||
export function BrowserToolsRow({ serverId }: { serverId: string }) {
|
||||
const { t } = useTranslation();
|
||||
const isConnected = useHostRuntimeIsConnected(serverId);
|
||||
const { config, patchConfig } = useDaemonConfig(serverId);
|
||||
const state = getBrowserToolsCardState({ isConnected, config });
|
||||
const mutation = useMutation({
|
||||
mutationFn: async (next: boolean) => {
|
||||
const result = await patchConfig(createBrowserToolsPatch(next));
|
||||
if (!result) {
|
||||
throw new Error(t("workspace.terminal.hostDisconnected"));
|
||||
}
|
||||
return result;
|
||||
},
|
||||
});
|
||||
const mutationView = getBrowserToolsMutationViewState({
|
||||
isPending: mutation.isPending,
|
||||
error: mutation.error,
|
||||
});
|
||||
|
||||
const handleValueChange = useCallback(
|
||||
(next: boolean) => {
|
||||
mutation.mutate(next);
|
||||
},
|
||||
[mutation],
|
||||
);
|
||||
|
||||
const hint = useMemo(
|
||||
() => (
|
||||
<View>
|
||||
<Text style={settingsStyles.rowHint}>{state.warning}</Text>
|
||||
{mutationView.loadingText ? (
|
||||
<Text style={settingsStyles.rowHint} testID="host-page-browser-tools-loading">
|
||||
{mutationView.loadingText}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
),
|
||||
[mutationView.loadingText, state.warning],
|
||||
);
|
||||
|
||||
if (!state.isVisible) return null;
|
||||
|
||||
return (
|
||||
<SettingsRow
|
||||
label={state.title}
|
||||
hint={hint}
|
||||
error={mutationView.errorText ?? undefined}
|
||||
testID="host-page-browser-tools-card"
|
||||
>
|
||||
<Switch
|
||||
value={state.isEnabled}
|
||||
onValueChange={handleValueChange}
|
||||
disabled={mutationView.isSwitchDisabled}
|
||||
accessibilityLabel="Enable browser tools"
|
||||
testID="host-page-browser-tools-switch"
|
||||
/>
|
||||
</SettingsRow>
|
||||
);
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
import type { MutableDaemonConfig } from "@getpaseo/protocol/messages";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
BROWSER_TOOLS_WARNING,
|
||||
createBrowserToolsPatch,
|
||||
getBrowserToolsCardState,
|
||||
getBrowserToolsMutationViewState,
|
||||
} from "./browser-tools-config";
|
||||
|
||||
function makeConfig(browserToolsEnabled = false): MutableDaemonConfig {
|
||||
return {
|
||||
relay: { enabled: false },
|
||||
mcp: { injectIntoAgents: false },
|
||||
browserTools: { enabled: browserToolsEnabled },
|
||||
providers: {},
|
||||
metadataGeneration: { providers: [] },
|
||||
autoArchiveAfterMerge: false,
|
||||
enableTerminalAgentHooks: false,
|
||||
appendSystemPrompt: "",
|
||||
};
|
||||
}
|
||||
|
||||
describe("browser tools opt-in config", () => {
|
||||
it("shows the card with the logged-in browser state warning when connected", () => {
|
||||
expect(getBrowserToolsCardState({ isConnected: true, config: makeConfig(false) })).toEqual({
|
||||
isVisible: true,
|
||||
isEnabled: false,
|
||||
title: "Browser tools",
|
||||
warning: BROWSER_TOOLS_WARNING,
|
||||
});
|
||||
});
|
||||
|
||||
it("reads enabled state from daemon config", () => {
|
||||
expect(getBrowserToolsCardState({ isConnected: true, config: makeConfig(true) })).toMatchObject(
|
||||
{
|
||||
isEnabled: true,
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it("hides the card when the host is disconnected", () => {
|
||||
expect(
|
||||
getBrowserToolsCardState({ isConnected: false, config: makeConfig(true) }),
|
||||
).toMatchObject({
|
||||
isVisible: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("writes daemon.browserTools.enabled when toggled", () => {
|
||||
expect(createBrowserToolsPatch(true)).toEqual({ browserTools: { enabled: true } });
|
||||
expect(createBrowserToolsPatch(false)).toEqual({ browserTools: { enabled: false } });
|
||||
});
|
||||
|
||||
it("shows loading and disables the toggle while browser tool settings save", () => {
|
||||
expect(getBrowserToolsMutationViewState({ isPending: true, error: null })).toEqual({
|
||||
isSwitchDisabled: true,
|
||||
loadingText: "Updating browser tools…",
|
||||
errorText: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("shows the save error when browser tool settings fail", () => {
|
||||
expect(
|
||||
getBrowserToolsMutationViewState({ isPending: false, error: new Error("Disk full") }),
|
||||
).toEqual({
|
||||
isSwitchDisabled: false,
|
||||
loadingText: null,
|
||||
errorText: "Disk full",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,49 +0,0 @@
|
||||
import type { MutableDaemonConfig } from "@getpaseo/protocol/messages";
|
||||
|
||||
export const BROWSER_TOOLS_TITLE = "Browser tools";
|
||||
export const BROWSER_TOOLS_WARNING =
|
||||
"Allow agents to access and control Paseo browser tabs, including logged-in browser state. Only enable this for agents you trust.";
|
||||
|
||||
export interface BrowserToolsCardState {
|
||||
isVisible: boolean;
|
||||
isEnabled: boolean;
|
||||
title: string;
|
||||
warning: string;
|
||||
}
|
||||
|
||||
export interface BrowserToolsMutationViewState {
|
||||
isSwitchDisabled: boolean;
|
||||
loadingText: string | null;
|
||||
errorText: string | null;
|
||||
}
|
||||
|
||||
export function getBrowserToolsCardState(input: {
|
||||
isConnected: boolean;
|
||||
config: MutableDaemonConfig | null;
|
||||
}): BrowserToolsCardState {
|
||||
return {
|
||||
isVisible: input.isConnected,
|
||||
isEnabled: input.config?.browserTools.enabled === true,
|
||||
title: BROWSER_TOOLS_TITLE,
|
||||
warning: BROWSER_TOOLS_WARNING,
|
||||
};
|
||||
}
|
||||
|
||||
export function createBrowserToolsPatch(enabled: boolean): Partial<MutableDaemonConfig> {
|
||||
return { browserTools: { enabled } };
|
||||
}
|
||||
|
||||
export function getBrowserToolsMutationViewState(input: {
|
||||
isPending: boolean;
|
||||
error: unknown;
|
||||
}): BrowserToolsMutationViewState {
|
||||
return {
|
||||
isSwitchDisabled: input.isPending,
|
||||
loadingText: input.isPending ? "Updating browser tools…" : null,
|
||||
errorText: input.error ? toErrorMessage(input.error) : null,
|
||||
};
|
||||
}
|
||||
|
||||
function toErrorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
@@ -61,8 +61,7 @@ import { formatConnectionStatus, getConnectionStatusTone } from "@/utils/daemons
|
||||
import { ICON_SIZE } from "@/styles/theme";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import { useProviderIcon } from "@/components/provider-icons";
|
||||
import { BrowserToolsRow } from "./browser-tools-card";
|
||||
import { HostPaseoToolsRow } from "./paseo-tools-card";
|
||||
import { HostAgentToolsRow } from "./agent-tools-row";
|
||||
import { RestartRecoveryRow } from "./restart-recovery-card";
|
||||
import { IdleRuntimeCleanupRow } from "./idle-runtime-cleanup-card";
|
||||
import { restartDaemonFromSettings, updateDaemonFromSettings } from "./daemon-lifecycle";
|
||||
@@ -261,8 +260,7 @@ export function HostToolsPage({ serverId }: { serverId: string }) {
|
||||
</SettingsSection>
|
||||
<SettingsSection title={t("settings.host.tools.toolsTitle")}>
|
||||
<SettingsCard testID="host-page-inject-mcp-card">
|
||||
<HostPaseoToolsRow serverId={serverId} />
|
||||
<BrowserToolsRow serverId={serverId} />
|
||||
<HostAgentToolsRow serverId={serverId} />
|
||||
</SettingsCard>
|
||||
</SettingsSection>
|
||||
</>
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
import { useCallback } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { SettingsRow } from "@/components/settings";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { useDaemonConfig } from "@/hooks/use-daemon-config";
|
||||
import { useHostRuntimeIsConnected } from "@/runtime/host-runtime";
|
||||
|
||||
/** The host's "give agents Paseo tools" row, bound to the host's config, for composing inside a SettingsCard. */
|
||||
export function HostPaseoToolsRow({ serverId }: { serverId: string }) {
|
||||
const isConnected = useHostRuntimeIsConnected(serverId);
|
||||
const { config, patchConfig } = useDaemonConfig(serverId);
|
||||
|
||||
const handleValueChange = useCallback(
|
||||
(next: boolean) => {
|
||||
void patchConfig({ mcp: { injectIntoAgents: next } });
|
||||
},
|
||||
[patchConfig],
|
||||
);
|
||||
|
||||
if (!isConnected) return null;
|
||||
|
||||
return (
|
||||
<PaseoToolsRow
|
||||
value={config?.mcp.injectIntoAgents !== false}
|
||||
onValueChange={handleValueChange}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/** The Paseo tools row on its own, for a caller that decides what the switch is bound to. */
|
||||
export function PaseoToolsRow({
|
||||
value,
|
||||
onValueChange,
|
||||
disabled,
|
||||
}: {
|
||||
value: boolean;
|
||||
onValueChange: (next: boolean) => void;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<SettingsRow
|
||||
label={t("settings.host.orchestration.enableTools.title")}
|
||||
hint={t("settings.host.orchestration.enableTools.hint")}
|
||||
>
|
||||
<Switch
|
||||
value={value}
|
||||
onValueChange={onValueChange}
|
||||
disabled={disabled}
|
||||
accessibilityLabel={t("settings.host.orchestration.enableTools.accessibilityLabel")}
|
||||
/>
|
||||
</SettingsRow>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { render } from "@testing-library/react";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { RetainedPanelActivity } from "@/components/retained-panel";
|
||||
import {
|
||||
createPostRestoreRevealHolds,
|
||||
type PostRestoreRevealHolds,
|
||||
PostRestoreRevealHoldsProvider,
|
||||
usePostRestoreRevealHold,
|
||||
} from "./post-restore-reveal-holds";
|
||||
|
||||
function Chrome({ pending }: { pending: boolean }) {
|
||||
usePostRestoreRevealHold(pending);
|
||||
return null;
|
||||
}
|
||||
|
||||
function Workspace(props: {
|
||||
holds: PostRestoreRevealHolds | null;
|
||||
pending: boolean;
|
||||
onScreen: boolean;
|
||||
mounted?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<PostRestoreRevealHoldsProvider holds={props.holds}>
|
||||
<RetainedPanelActivity active={props.onScreen}>
|
||||
{props.mounted === false ? null : <Chrome pending={props.pending} />}
|
||||
</RetainedPanelActivity>
|
||||
</PostRestoreRevealHoldsProvider>
|
||||
);
|
||||
}
|
||||
|
||||
describe("post-restore reveal holds", () => {
|
||||
it("holds the reveal while on-screen chrome is pending and releases when it settles", () => {
|
||||
const holds = createPostRestoreRevealHolds();
|
||||
const view = render(<Workspace holds={holds} pending onScreen />);
|
||||
expect(holds.isHeld()).toBe(true);
|
||||
|
||||
view.rerender(<Workspace holds={holds} pending={false} onScreen />);
|
||||
expect(holds.isHeld()).toBe(false);
|
||||
});
|
||||
|
||||
it("does not hold for chrome in a hidden pane", () => {
|
||||
const holds = createPostRestoreRevealHolds();
|
||||
render(<Workspace holds={holds} pending onScreen={false} />);
|
||||
expect(holds.isHeld()).toBe(false);
|
||||
});
|
||||
|
||||
it("releases when pending chrome unmounts", () => {
|
||||
const holds = createPostRestoreRevealHolds();
|
||||
const view = render(<Workspace holds={holds} pending onScreen />);
|
||||
view.rerender(<Workspace holds={holds} pending onScreen mounted={false} />);
|
||||
expect(holds.isHeld()).toBe(false);
|
||||
});
|
||||
|
||||
it("releases when the handoff ends and the provider stops offering holds", () => {
|
||||
const holds = createPostRestoreRevealHolds();
|
||||
const view = render(<Workspace holds={holds} pending onScreen />);
|
||||
view.rerender(<Workspace holds={null} pending onScreen />);
|
||||
expect(holds.isHeld()).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,77 @@
|
||||
import {
|
||||
createContext,
|
||||
type ReactNode,
|
||||
useContext,
|
||||
useLayoutEffect,
|
||||
useSyncExternalStore,
|
||||
} from "react";
|
||||
import { useRetainedPanelActive } from "@/components/retained-panel";
|
||||
|
||||
/**
|
||||
* Workspace chrome mounted behind the `Restoring...` gate that has nothing to show until a layout
|
||||
* pass answers it. The gate stays up while any on-screen chrome holds it.
|
||||
*/
|
||||
export interface PostRestoreRevealHolds {
|
||||
hold: () => () => void;
|
||||
subscribe: (listener: () => void) => () => void;
|
||||
isHeld: () => boolean;
|
||||
}
|
||||
|
||||
export function createPostRestoreRevealHolds(): PostRestoreRevealHolds {
|
||||
let count = 0;
|
||||
const listeners = new Set<() => void>();
|
||||
const notify = () => {
|
||||
for (const listener of listeners) listener();
|
||||
};
|
||||
return {
|
||||
hold: () => {
|
||||
count += 1;
|
||||
notify();
|
||||
let released = false;
|
||||
return () => {
|
||||
if (released) return;
|
||||
released = true;
|
||||
count -= 1;
|
||||
notify();
|
||||
};
|
||||
},
|
||||
subscribe: (listener) => {
|
||||
listeners.add(listener);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
};
|
||||
},
|
||||
isHeld: () => count > 0,
|
||||
};
|
||||
}
|
||||
|
||||
const PostRestoreRevealHoldsContext = createContext<PostRestoreRevealHolds | null>(null);
|
||||
|
||||
/** `holds` is null outside a post-restore handoff, so chrome mounting normally never holds. */
|
||||
export function PostRestoreRevealHoldsProvider({
|
||||
holds,
|
||||
children,
|
||||
}: {
|
||||
holds: PostRestoreRevealHolds | null;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return <PostRestoreRevealHoldsContext value={holds}>{children}</PostRestoreRevealHoldsContext>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Holds the post-restore reveal while `pending`. A hidden pane or a closed explorer never lays
|
||||
* out, so only chrome that is on screen holds.
|
||||
*/
|
||||
export function usePostRestoreRevealHold(pending: boolean): void {
|
||||
const holds = useContext(PostRestoreRevealHoldsContext);
|
||||
const isOnScreen = useRetainedPanelActive();
|
||||
const isHolding = pending && isOnScreen;
|
||||
useLayoutEffect(() => {
|
||||
if (!isHolding || !holds) return;
|
||||
return holds.hold();
|
||||
}, [holds, isHolding]);
|
||||
}
|
||||
|
||||
export function usePostRestoreRevealHeld(holds: PostRestoreRevealHolds): boolean {
|
||||
return useSyncExternalStore(holds.subscribe, holds.isHeld, holds.isHeld);
|
||||
}
|
||||
@@ -1,4 +1,9 @@
|
||||
import { useCallback, useEffect, useState, useSyncExternalStore } from "react";
|
||||
import {
|
||||
createPostRestoreRevealHolds,
|
||||
type PostRestoreRevealHolds,
|
||||
usePostRestoreRevealHeld,
|
||||
} from "@/screens/workspace/post-restore-reveal-holds";
|
||||
import { selectAgentTimelineState, useSessionStore } from "@/stores/session-store";
|
||||
import { useWorkspaceLayoutStore } from "@/stores/workspace-layout-store";
|
||||
import type { WorkspaceRouteState } from "@/screens/workspace/workspace-route-state";
|
||||
@@ -101,6 +106,7 @@ export function resolvePostRestoreDisplayedRouteState(input: {
|
||||
visibleAgentsTimelineSynced: boolean;
|
||||
visibleAgentsVisibilityStatus: ViewedTimelineStatus;
|
||||
visibleAgentsLoadingOlder: boolean;
|
||||
isRevealHeld: boolean;
|
||||
routeState: WorkspaceRouteState;
|
||||
}): {
|
||||
displayedRouteState: WorkspaceRouteState;
|
||||
@@ -119,6 +125,7 @@ export function resolvePostRestoreDisplayedRouteState(input: {
|
||||
visibleAgentsTimelineSynced,
|
||||
visibleAgentsVisibilityStatus,
|
||||
visibleAgentsLoadingOlder,
|
||||
isRevealHeld,
|
||||
routeState,
|
||||
} = input;
|
||||
const isRestoringNow =
|
||||
@@ -138,6 +145,7 @@ export function resolvePostRestoreDisplayedRouteState(input: {
|
||||
const isHandoffReadyToMount = hasReconciledTabs && areVisibleAgentsReadyToMount;
|
||||
const isHandoffReadyToRelease =
|
||||
isHandoffReadyToMount &&
|
||||
!isRevealHeld &&
|
||||
(visibleAgentsVisibilityStatus === "error" || !visibleAgentsLoadingOlder);
|
||||
return {
|
||||
displayedRouteState: isWaitingForHandoffReveal ? handoff.archivedState : routeState,
|
||||
@@ -168,6 +176,7 @@ export function usePostRestoreWorkspaceRouteState(input: {
|
||||
paneFocusSuspended: boolean;
|
||||
}): {
|
||||
displayedRouteState: WorkspaceRouteState;
|
||||
revealHolds: PostRestoreRevealHolds;
|
||||
isHoldingHandoff: boolean;
|
||||
isPaneRouteFocused: boolean;
|
||||
effectivePaneFocusSuspended: boolean;
|
||||
@@ -191,6 +200,8 @@ export function usePostRestoreWorkspaceRouteState(input: {
|
||||
const scopeKey = `${serverId}:${workspaceId}`;
|
||||
const [handoff, setHandoff] = useState<PostRestoreHandoffState | null>(null);
|
||||
const [mountedHandoff, setMountedHandoff] = useState<PostRestoreHandoffState | null>(null);
|
||||
const [revealHolds] = useState(createPostRestoreRevealHolds);
|
||||
const isRevealHeld = usePostRestoreRevealHeld(revealHolds);
|
||||
|
||||
const reconciledHandoff = nextPostRestoreHandoff({ current: handoff, scopeKey, routeState });
|
||||
if (reconciledHandoff !== handoff) {
|
||||
@@ -271,6 +282,7 @@ export function usePostRestoreWorkspaceRouteState(input: {
|
||||
visibleAgentsTimelineSynced,
|
||||
visibleAgentsVisibilityStatus,
|
||||
visibleAgentsLoadingOlder,
|
||||
isRevealHeld,
|
||||
routeState,
|
||||
});
|
||||
|
||||
@@ -286,8 +298,8 @@ export function usePostRestoreWorkspaceRouteState(input: {
|
||||
useEffect(() => {
|
||||
if (!isWaitingForHandoffReveal) return;
|
||||
if (isHandoffReadyToRelease) {
|
||||
// Wait 3 rAFs after hidden workspace chrome mounts so tab label `onLayout` and stream row
|
||||
// ResizeObservers commit (and any underfilled history fetch starts) before lifting overlay.
|
||||
// Chrome that waits on its own layout (tab label measurement) holds the reveal explicitly.
|
||||
// The frames let stream row ResizeObservers commit and any underfilled history fetch start.
|
||||
return scheduleAnimationFrames(POST_RESTORE_LAYOUT_SETTLE_FRAMES, () => {
|
||||
setHandoff(null);
|
||||
});
|
||||
@@ -300,6 +312,7 @@ export function usePostRestoreWorkspaceRouteState(input: {
|
||||
|
||||
return {
|
||||
displayedRouteState,
|
||||
revealHolds,
|
||||
isHoldingHandoff: isMountedBehindOverlay,
|
||||
isPaneRouteFocused: isRouteFocused && !isMountedBehindOverlay,
|
||||
effectivePaneFocusSuspended: paneFocusSuspended || isMountedBehindOverlay,
|
||||
|
||||
@@ -96,6 +96,7 @@ import {
|
||||
useHorizontalScrollBoundary,
|
||||
} from "@/components/ui/horizontal-scroll-boundary";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { usePostRestoreRevealHold } from "@/screens/workspace/post-restore-reveal-holds";
|
||||
|
||||
const DROPDOWN_WIDTH = 220;
|
||||
const DEFAULT_INLINE_ADD_BUTTON_RESERVED_WIDTH = 36;
|
||||
@@ -1062,6 +1063,7 @@ export function WorkspaceDesktopTabsRow(props: WorkspaceDesktopTabsRowProps) {
|
||||
}),
|
||||
[presentations, props.tabs],
|
||||
);
|
||||
usePostRestoreRevealHold(resolvedTabs.length < props.tabs.length);
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -1245,6 +1247,7 @@ function ResolvedWorkspaceDesktopTabsRow({
|
||||
useLayoutEffect(() => {
|
||||
publishMeasuredTrack();
|
||||
}, [publishMeasuredTrack]);
|
||||
usePostRestoreRevealHold(tabs.length > 0 && trackSnapshot?.signature !== tabLabelSignature);
|
||||
|
||||
const handleTabLabelLayout = useCallback(
|
||||
(key: string, label: string, event: LayoutChangeEvent) => {
|
||||
|
||||
@@ -264,6 +264,7 @@ describe("post-restore handoff state machine", () => {
|
||||
visibleAgentsTimelineSynced: true,
|
||||
visibleAgentsVisibilityStatus: "ready",
|
||||
visibleAgentsLoadingOlder: false,
|
||||
isRevealHeld: false,
|
||||
routeState: { kind: "ready" },
|
||||
});
|
||||
expect(waitingTabs.displayedRouteState).toBe(restoringState);
|
||||
@@ -283,6 +284,7 @@ describe("post-restore handoff state machine", () => {
|
||||
visibleAgentsTimelineSynced: false,
|
||||
visibleAgentsVisibilityStatus: "checking",
|
||||
visibleAgentsLoadingOlder: false,
|
||||
isRevealHeld: false,
|
||||
routeState: { kind: "ready" },
|
||||
});
|
||||
expect(waitingTimeline.displayedRouteState).toBe(restoringState);
|
||||
@@ -301,6 +303,7 @@ describe("post-restore handoff state machine", () => {
|
||||
visibleAgentsTimelineSynced: true,
|
||||
visibleAgentsVisibilityStatus: "checking",
|
||||
visibleAgentsLoadingOlder: false,
|
||||
isRevealHeld: false,
|
||||
routeState: { kind: "ready" },
|
||||
});
|
||||
expect(waitingCatchUp.displayedRouteState).toBe(restoringState);
|
||||
@@ -319,6 +322,7 @@ describe("post-restore handoff state machine", () => {
|
||||
visibleAgentsTimelineSynced: true,
|
||||
visibleAgentsVisibilityStatus: "ready",
|
||||
visibleAgentsLoadingOlder: true,
|
||||
isRevealHeld: false,
|
||||
routeState: { kind: "ready" },
|
||||
});
|
||||
expect(waitingOlderFill.isHandoffReadyToMount).toBe(true);
|
||||
@@ -336,6 +340,7 @@ describe("post-restore handoff state machine", () => {
|
||||
visibleAgentsTimelineSynced: true,
|
||||
visibleAgentsVisibilityStatus: "ready",
|
||||
visibleAgentsLoadingOlder: false,
|
||||
isRevealHeld: false,
|
||||
routeState: { kind: "ready" },
|
||||
});
|
||||
expect(revealed.displayedRouteState).toBe(restoringState);
|
||||
@@ -355,6 +360,7 @@ describe("post-restore handoff state machine", () => {
|
||||
visibleAgentsTimelineSynced: true,
|
||||
visibleAgentsVisibilityStatus: "ready",
|
||||
visibleAgentsLoadingOlder: false,
|
||||
isRevealHeld: false,
|
||||
routeState: { kind: "ready" },
|
||||
});
|
||||
expect(cleared.displayedRouteState).toEqual({ kind: "ready" });
|
||||
@@ -372,11 +378,38 @@ describe("post-restore handoff state machine", () => {
|
||||
visibleAgentsTimelineSynced: false,
|
||||
visibleAgentsVisibilityStatus: "error",
|
||||
visibleAgentsLoadingOlder: false,
|
||||
isRevealHeld: false,
|
||||
routeState: { kind: "ready" },
|
||||
});
|
||||
expect(errored.isHandoffReadyToRelease).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps Restoring up while on-screen workspace chrome holds the reveal", () => {
|
||||
const handoff = nextPostRestoreHandoff({ current: null, scopeKey, routeState: restoringState });
|
||||
const settled = {
|
||||
handoff,
|
||||
scopeKey,
|
||||
hasActiveWorkspace: true,
|
||||
hasHydratedWorkspaceLayoutStore: true,
|
||||
hasHydratedAgents: true,
|
||||
hasReconciledAutoOpenAgentTabs: true,
|
||||
visibleAgentCount: 1,
|
||||
visibleAgentsTimelineSynced: true,
|
||||
visibleAgentsVisibilityStatus: "ready" as const,
|
||||
visibleAgentsLoadingOlder: false,
|
||||
routeState: { kind: "ready" as const },
|
||||
};
|
||||
|
||||
// A tab row mounted behind the gate has not measured its tabs yet.
|
||||
const held = resolvePostRestoreDisplayedRouteState({ ...settled, isRevealHeld: true });
|
||||
expect(held.displayedRouteState).toBe(restoringState);
|
||||
expect(held.isHandoffReadyToMount).toBe(true);
|
||||
expect(held.isHandoffReadyToRelease).toBe(false);
|
||||
|
||||
const released = resolvePostRestoreDisplayedRouteState({ ...settled, isRevealHeld: false });
|
||||
expect(released.isHandoffReadyToRelease).toBe(true);
|
||||
});
|
||||
|
||||
it("marks handoff ready to release immediately when the workspace only has non-auto-open agents", () => {
|
||||
const captured = nextPostRestoreHandoff({
|
||||
current: null,
|
||||
@@ -394,6 +427,7 @@ describe("post-restore handoff state machine", () => {
|
||||
visibleAgentsTimelineSynced: false,
|
||||
visibleAgentsVisibilityStatus: "ready",
|
||||
visibleAgentsLoadingOlder: false,
|
||||
isRevealHeld: false,
|
||||
routeState: { kind: "ready" },
|
||||
});
|
||||
expect(resolved.isHandoffReadyToRelease).toBe(true);
|
||||
|
||||
@@ -164,6 +164,10 @@ import {
|
||||
canSyncVisibleAgents,
|
||||
usePostRestoreWorkspaceRouteState,
|
||||
} from "@/screens/workspace/use-post-restore-handoff";
|
||||
import {
|
||||
type PostRestoreRevealHolds,
|
||||
PostRestoreRevealHoldsProvider,
|
||||
} from "@/screens/workspace/post-restore-reveal-holds";
|
||||
import {
|
||||
renderWorkspaceRouteGate,
|
||||
WorkspaceLoading,
|
||||
@@ -1432,6 +1436,7 @@ function WorkspaceScreenContent({
|
||||
|
||||
const {
|
||||
displayedRouteState: displayedWorkspaceRouteState,
|
||||
revealHolds,
|
||||
isHoldingHandoff,
|
||||
isPaneRouteFocused,
|
||||
effectivePaneFocusSuspended,
|
||||
@@ -3506,6 +3511,7 @@ function WorkspaceScreenContent({
|
||||
return (
|
||||
<PostRestoreOverlayShell
|
||||
isHoldingHandoff={isHoldingHandoff}
|
||||
revealHolds={revealHolds}
|
||||
overlay={gatedWorkspaceScreen}
|
||||
workspaceKey={persistenceKey}
|
||||
sheetPaneHost={sheetPaneHost}
|
||||
@@ -3529,12 +3535,14 @@ function WorkspaceScreenContent({
|
||||
/** Keeps mounted workspace chrome hidden beneath the restoring gate during layout settle. */
|
||||
function PostRestoreOverlayShell({
|
||||
isHoldingHandoff,
|
||||
revealHolds,
|
||||
overlay,
|
||||
workspaceKey,
|
||||
sheetPaneHost,
|
||||
children,
|
||||
}: {
|
||||
isHoldingHandoff: boolean;
|
||||
revealHolds: PostRestoreRevealHolds;
|
||||
overlay: ReactNode;
|
||||
workspaceKey: string | null;
|
||||
sheetPaneHost: Parameters<typeof WorkspaceContentProviders>[0]["sheetPaneHost"];
|
||||
@@ -3552,13 +3560,15 @@ function PostRestoreOverlayShell({
|
||||
accessibilityElementsHidden={isHoldingHandoff}
|
||||
importantForAccessibility={isHoldingHandoff ? "no-hide-descendants" : "auto"}
|
||||
>
|
||||
<WorkspaceContentProviders
|
||||
key={workspaceKey}
|
||||
workspaceKey={workspaceKey}
|
||||
sheetPaneHost={sheetPaneHost}
|
||||
>
|
||||
{children}
|
||||
</WorkspaceContentProviders>
|
||||
<PostRestoreRevealHoldsProvider holds={isHoldingHandoff ? revealHolds : null}>
|
||||
<WorkspaceContentProviders
|
||||
key={workspaceKey}
|
||||
workspaceKey={workspaceKey}
|
||||
sheetPaneHost={sheetPaneHost}
|
||||
>
|
||||
{children}
|
||||
</WorkspaceContentProviders>
|
||||
</PostRestoreRevealHoldsProvider>
|
||||
</View>
|
||||
) : null}
|
||||
{overlay ? <View style={styles.postRestoreOverlay}>{overlay}</View> : null}
|
||||
|
||||
@@ -100,12 +100,14 @@ export async function archiveSelectedWorkspaces(input: {
|
||||
}
|
||||
|
||||
const riskyWorkspaces: WorktreeArchiveConfirmationInput[] = [];
|
||||
const dirtyWorktrees = new Set<SidebarWorkspaceEntry>();
|
||||
const worktrees = resolved.filter((item) => item.entry.workspaceKind === "worktree");
|
||||
if (worktrees.length > 0) {
|
||||
try {
|
||||
const risks = await Promise.all(
|
||||
worktrees.map(async ({ entry, client }) => {
|
||||
const risk = await deps.readWorktreeRisk(client, entry.workspaceDirectory);
|
||||
if (risk.isDirty) dirtyWorktrees.add(entry);
|
||||
return {
|
||||
workspaceName: entry.name,
|
||||
diffStat: entry.diffStat,
|
||||
@@ -162,6 +164,7 @@ export async function archiveSelectedWorkspaces(input: {
|
||||
return {
|
||||
client,
|
||||
workspace,
|
||||
force: dirtyWorktrees.has(entry) || undefined,
|
||||
onArchiveCommitted: () => deps.purgeWorkspaceState(workspace),
|
||||
};
|
||||
}),
|
||||
@@ -175,7 +178,11 @@ export async function archiveSelectedWorkspaces(input: {
|
||||
...legacy.map(async ({ entry, client }) => {
|
||||
const workspace = { serverId: entry.serverId, workspaceId: entry.workspaceId };
|
||||
try {
|
||||
await deps.archiveWithoutUndo({ client, workspace });
|
||||
await deps.archiveWithoutUndo({
|
||||
client,
|
||||
workspace,
|
||||
force: dirtyWorktrees.has(entry) || undefined,
|
||||
});
|
||||
deps.purgeWorkspaceState(workspace);
|
||||
} catch (error) {
|
||||
failures.push({ error });
|
||||
|
||||
+25
-8
@@ -218,14 +218,24 @@ async function slowClick(element: HTMLElement) {
|
||||
const MOD_KEY = getShortcutOs() === "mac" ? "Meta" : "Control";
|
||||
|
||||
describe("sidebar workspace row presses", () => {
|
||||
it("enters select mode on the Cmd/Ctrl+clicked row alone and toggles rows without navigating", async () => {
|
||||
it("navigates on Cmd/Ctrl+click and Cmd/Ctrl+Shift+click outside select mode, and toggles with Cmd/Ctrl+click once active", async () => {
|
||||
mountHost(["a", "b", "c", "d"].map(makeEntry));
|
||||
|
||||
await userEvent.click(row("a"));
|
||||
expect(navigatedKeys).toEqual(["srv:a"]);
|
||||
expect(useSidebarSelectionStore.getState().active).toBe(false);
|
||||
|
||||
// Cmd/Ctrl+click (and Cmd/Ctrl+Shift+click) must not enter select mode from idle.
|
||||
await userEvent.click(row("c"), { modifiers: [MOD_KEY] });
|
||||
expect(useSidebarSelectionStore.getState().active).toBe(false);
|
||||
expect(navigatedKeys).toEqual(["srv:a", "srv:c"]);
|
||||
|
||||
await userEvent.click(row("d"), { modifiers: [MOD_KEY, "Shift"] });
|
||||
expect(useSidebarSelectionStore.getState().active).toBe(false);
|
||||
expect(navigatedKeys).toEqual(["srv:a", "srv:c", "srv:d"]);
|
||||
|
||||
// Once select mode is entered (e.g. via Shift+click), Cmd/Ctrl+click and plain clicks toggle.
|
||||
await userEvent.click(row("c"), { modifiers: ["Shift"] });
|
||||
expect(selectedIds()).toEqual(["c"]);
|
||||
|
||||
await userEvent.click(row("b"), { modifiers: [MOD_KEY] });
|
||||
@@ -238,31 +248,38 @@ describe("sidebar workspace row presses", () => {
|
||||
// Plain clicks keep toggling while select mode is on.
|
||||
await userEvent.click(row("a"));
|
||||
expect(selectedIds()).toEqual(["a", "b", "d"]);
|
||||
expect(navigatedKeys).toEqual(["srv:a"]);
|
||||
expect(navigatedKeys).toEqual(["srv:a", "srv:c", "srv:d"]);
|
||||
});
|
||||
|
||||
it("selects on the first modifier or select-mode click after an earlier gesture ended as a long press", async () => {
|
||||
mountHost(["a", "b"].map(makeEntry));
|
||||
it("selects on the first Shift+click or select-mode click after an earlier gesture ended as a long press", async () => {
|
||||
mountHost(["a", "b", "c"].map(makeEntry));
|
||||
|
||||
// A scroll, swipe, drag, or long-press menu leaves the flag set without firing onPress.
|
||||
// Ctrl+click on Windows/Linux gets no press-in on web, so nothing clears it first.
|
||||
markGestureCanceled("a");
|
||||
await userEvent.click(row("a"), { modifiers: [MOD_KEY] });
|
||||
await userEvent.click(row("a"), { modifiers: ["Shift"] });
|
||||
expect(selectedIds()).toEqual(["a"]);
|
||||
|
||||
markGestureCanceled("b");
|
||||
await userEvent.click(row("b"));
|
||||
await userEvent.click(row("b"), { modifiers: [MOD_KEY] });
|
||||
expect(selectedIds()).toEqual(["a", "b"]);
|
||||
|
||||
markGestureCanceled("c");
|
||||
await userEvent.click(row("c"));
|
||||
expect(selectedIds()).toEqual(["a", "b", "c"]);
|
||||
});
|
||||
|
||||
it("opens a row on a slow click and still selects it on the next Cmd/Ctrl+click", async () => {
|
||||
it("opens a row on a slow click and still selects it on the next Shift+click and Cmd/Ctrl+click", async () => {
|
||||
mountHost(["a", "b"].map(makeEntry));
|
||||
|
||||
await act(() => slowClick(row("a")));
|
||||
expect(navigatedKeys).toEqual(["srv:a"]);
|
||||
|
||||
await userEvent.click(row("a"), { modifiers: [MOD_KEY] });
|
||||
await userEvent.click(row("a"), { modifiers: ["Shift"] });
|
||||
expect(selectedIds()).toEqual(["a"]);
|
||||
|
||||
await userEvent.click(row("b"), { modifiers: [MOD_KEY] });
|
||||
expect(selectedIds()).toEqual(["a", "b"]);
|
||||
});
|
||||
|
||||
it("enters select mode on the Shift+clicked row alone, then extends and shrinks the range", async () => {
|
||||
|
||||
@@ -12,10 +12,12 @@ interface WorkspaceSelectionPressInput {
|
||||
}
|
||||
|
||||
/**
|
||||
* Routes a sidebar workspace row press between navigation and select mode, Finder-style:
|
||||
* Shift+click selects a range, Cmd+click (Ctrl+click off macOS) toggles one row, and either one
|
||||
* enters select mode on the clicked row alone. In select mode every press selects, so touch and
|
||||
* mouse users can keep tapping without a modifier.
|
||||
* Routes a sidebar workspace row press between navigation and select mode:
|
||||
* - Outside select mode, Shift+click (without Cmd/Ctrl) enters select mode on the clicked row
|
||||
* alone; plain clicks and Cmd/Ctrl+clicks navigate normally so shortcut rollover and Cmd-held
|
||||
* badge peeks never trigger bulk selection.
|
||||
* - Inside select mode, Shift+click selects a Finder-style range from the anchor, and plain clicks
|
||||
* or Cmd/Ctrl+clicks toggle one row without navigating.
|
||||
*
|
||||
* Selecting presses never consult the row's long-press flag. They never arm the long-press
|
||||
* gesture, a native long press already cancels the press, and react-native-web gives Ctrl+click
|
||||
@@ -30,7 +32,7 @@ export function useWorkspaceSelectionPress({
|
||||
(event: GestureResponderEvent) => {
|
||||
const modifiers = readPressModifiers(event);
|
||||
const store = useSidebarSelectionStore.getState();
|
||||
if (!store.active && !modifiers.shift && !modifiers.mod) {
|
||||
if (!store.active && (!modifiers.shift || modifiers.mod)) {
|
||||
onNavigate();
|
||||
return;
|
||||
}
|
||||
@@ -43,12 +45,14 @@ export function useWorkspaceSelectionPress({
|
||||
const handlePressIn = useCallback(
|
||||
(event: GestureResponderEvent) => {
|
||||
const modifiers = readPressModifiers(event);
|
||||
if (modifiers.shift || modifiers.mod) {
|
||||
const isSelectionMode = useSidebarSelectionStore.getState().active;
|
||||
const entersSelection = !isSelectionMode && modifiers.shift && !modifiers.mod;
|
||||
if (entersSelection || (isSelectionMode && (modifiers.shift || modifiers.mod))) {
|
||||
// Keep the browser from extending a text selection or starting a drag on modifier clicks.
|
||||
event.preventDefault?.();
|
||||
return;
|
||||
}
|
||||
if (!useSidebarSelectionStore.getState().active) {
|
||||
if (!isSelectionMode) {
|
||||
onPressIn?.(event);
|
||||
}
|
||||
},
|
||||
|
||||
@@ -1349,6 +1349,33 @@ test("membership retry cannot run while disconnected", async () => {
|
||||
expect(restored.agentIds).toEqual(["agent-a"]);
|
||||
});
|
||||
|
||||
test("reopening a cached chat while its previous subscription is pending rechecks freshness", async () => {
|
||||
const world = new TimelineWorld(undefined, true);
|
||||
const agentId = "agent-a";
|
||||
world.cursors.set(agentId, { epoch: "cached", endSeq: 9 });
|
||||
world.show("workspace", [agentId]);
|
||||
world.sync.setConnected(true);
|
||||
|
||||
try {
|
||||
const previous = await world.nextMembership();
|
||||
world.show("workspace", []);
|
||||
world.sync.replaceOpenTabAgentIds([]);
|
||||
world.show("workspace", [agentId]);
|
||||
previous.succeed({ [agentId]: "current" });
|
||||
|
||||
const reopened = await world.nextMembership();
|
||||
expect(reopened.agentIds).toEqual([agentId]);
|
||||
expect(reopened.cursors).toEqual({ [agentId]: { epoch: "cached", seq: 9 } });
|
||||
reopened.succeed({ [agentId]: "current" });
|
||||
|
||||
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus(agentId)).toBe("ready"));
|
||||
expect(world.appliedCurrent).toEqual([agentId]);
|
||||
world.expectNoPendingFetch();
|
||||
} finally {
|
||||
world.sync.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
test("returning to an open hidden agent stays live after inactivity", async () => {
|
||||
const world = new TimelineWorld();
|
||||
world.sync.setConnected(true);
|
||||
|
||||
@@ -778,7 +778,7 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
let connected = false;
|
||||
let observation: {
|
||||
handle: ReturnType<ViewedTimelineSyncPorts["observe"]>;
|
||||
agentIds: string[];
|
||||
generation: number;
|
||||
} | null = null;
|
||||
let disposed = false;
|
||||
let desired: string[] = [];
|
||||
@@ -1049,10 +1049,12 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
}
|
||||
};
|
||||
|
||||
const membershipIsSettled = (requested: string[]) =>
|
||||
// A request from an earlier generation can have the same IDs after a tab
|
||||
// closes and reopens. Its answer will be ignored, so it cannot satisfy this one.
|
||||
const membershipIsCovered = (generation: number, requested: string[]) =>
|
||||
!membershipNeedsRetry &&
|
||||
!freshnessCheckOwed &&
|
||||
sameAgentIds(requested, observation?.agentIds ?? acknowledged);
|
||||
(observation ? observation.generation === generation : requested.length === 0);
|
||||
|
||||
// A chat with no fetch running and a cursor to compare; the daemon can answer without a fetch.
|
||||
const collectFreshnessCursors = (requested: string[]) => {
|
||||
@@ -1104,13 +1106,13 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
if (disposed || !connected) return;
|
||||
const generation = membershipGeneration;
|
||||
const requested = desired;
|
||||
if (membershipIsSettled(requested)) return;
|
||||
if (membershipIsCovered(generation, requested)) return;
|
||||
const canCheck = ports.canCheckFreshness();
|
||||
if (canCheck) {
|
||||
// The cursor sent to the daemon must include whatever the cache restores.
|
||||
await Promise.all(requested.map((agentId) => cacheLoads.get(agentId)));
|
||||
if (isReconcileSuperseded(generation)) return;
|
||||
if (membershipIsSettled(requested)) return;
|
||||
if (membershipIsCovered(generation, requested)) return;
|
||||
}
|
||||
membershipNeedsRetry = false;
|
||||
freshnessCheckOwed = false;
|
||||
@@ -1122,7 +1124,7 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
try {
|
||||
const previous = observation;
|
||||
const handle = ports.observe(requested, cursors);
|
||||
observation = { handle, agentIds: requested };
|
||||
observation = { handle, generation };
|
||||
// A subscription routes events only once the daemon accepts it, so the old one delivers until then.
|
||||
const answer = await handle.ready.finally(() => {
|
||||
void previous?.handle.release().catch(ports.reportError);
|
||||
|
||||
@@ -3,6 +3,13 @@ import { createAssistantMarkdownParser } from "./assistant-markdown-parser";
|
||||
const markdownRenderer = createAssistantMarkdownParser();
|
||||
// Disable linkify for selection HTML so text from unwrapped links stays unlinked.
|
||||
const unlinkedMarkdownRenderer = createAssistantMarkdownParser().set({ linkify: false });
|
||||
// Selection Markdown escapes every literal `<`, so a bare `<br>` is a table cell's line break.
|
||||
unlinkedMarkdownRenderer.inline.ruler.after("escape", "cell_line_break", (state, silent) => {
|
||||
if (!state.src.startsWith("<br>", state.pos)) return false;
|
||||
if (!silent) state.push("hardbreak", "br", 0);
|
||||
state.pos += "<br>".length;
|
||||
return true;
|
||||
});
|
||||
|
||||
type ClipboardMimeType = "text/plain" | "text/html";
|
||||
|
||||
|
||||
@@ -6,20 +6,21 @@ import {
|
||||
isWorkspaceListed,
|
||||
undoWorkspaceArchiveOptimistically,
|
||||
type WorkspaceArchiveTarget,
|
||||
type WorkspaceArchiveClient,
|
||||
} from "@/workspace/workspace-archive";
|
||||
import { WorkspaceArchivedToast } from "./workspace-archived-toast";
|
||||
|
||||
/** How long the archived toast, and with it the chance to undo, stays up. */
|
||||
export const WORKSPACE_ARCHIVE_UNDO_WINDOW_MS = 6000;
|
||||
|
||||
export interface UndoableWorkspaceArchiveClient {
|
||||
archiveWorkspace: (workspaceId: string) => Promise<{ error: string | null; canceled?: boolean }>;
|
||||
export interface UndoableWorkspaceArchiveClient extends WorkspaceArchiveClient {
|
||||
undoWorkspaceArchive: (workspaceId: string) => Promise<void>;
|
||||
}
|
||||
|
||||
export interface UndoableWorkspaceArchiveEntryInput {
|
||||
client: UndoableWorkspaceArchiveClient;
|
||||
workspace: WorkspaceArchiveTarget;
|
||||
force?: boolean;
|
||||
onArchiveCommitted: () => void;
|
||||
}
|
||||
|
||||
@@ -229,6 +230,7 @@ export async function archiveWorkspacesWithUndo(input: {
|
||||
export async function archiveWorkspaceWithUndo(input: {
|
||||
client: UndoableWorkspaceArchiveClient;
|
||||
workspace: WorkspaceArchiveTarget;
|
||||
force?: boolean;
|
||||
toast: ToastApi;
|
||||
onArchiveCommitted: () => void;
|
||||
}): Promise<void> {
|
||||
@@ -237,6 +239,7 @@ export async function archiveWorkspaceWithUndo(input: {
|
||||
{
|
||||
client: input.client,
|
||||
workspace: input.workspace,
|
||||
force: input.force,
|
||||
onArchiveCommitted: input.onArchiveCommitted,
|
||||
},
|
||||
],
|
||||
|
||||
@@ -6,10 +6,12 @@ import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
|
||||
import { ContextMenuItem } from "@/components/ui/context-menu";
|
||||
import { getIsElectron } from "@/constants/platform";
|
||||
import { useToast } from "@/contexts/toast-context";
|
||||
import { useIsLocalDaemon } from "@/hooks/use-is-local-daemon";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import { openDesktopTarget, useDesktopOpenTargets } from "@/workspace/desktop-open-targets";
|
||||
|
||||
interface OpenInFileManagerMenuItemProps {
|
||||
serverId: string | null | undefined;
|
||||
path?: string | null;
|
||||
testID: string;
|
||||
surface?: "context" | "dropdown";
|
||||
@@ -24,6 +26,7 @@ const foregroundMutedColorMapping = (theme: Theme) => ({
|
||||
const leadingIcon = <ThemedFolderOpen size={14} uniProps={foregroundMutedColorMapping} />;
|
||||
|
||||
export function OpenInFileManagerMenuItem({
|
||||
serverId,
|
||||
path,
|
||||
testID,
|
||||
surface = "dropdown",
|
||||
@@ -31,9 +34,10 @@ export function OpenInFileManagerMenuItem({
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const isElectron = getIsElectron();
|
||||
const isLocalDaemon = useIsLocalDaemon(serverId ?? "");
|
||||
const workspacePath = path?.trim() ?? "";
|
||||
const { targets } = useDesktopOpenTargets({
|
||||
isLocalExecution: isElectron && workspacePath.length > 0,
|
||||
isLocalExecution: isLocalDaemon && workspacePath.length > 0,
|
||||
});
|
||||
const fileManagerTarget = targets.find((target) => target.kind === "file-manager");
|
||||
|
||||
|
||||
@@ -62,44 +62,47 @@ export function useWorkspaceArchive(input: ArchiveWorkspaceInput): WorkspaceArch
|
||||
const onArchiveStartedRef = useRef(onArchiveStarted);
|
||||
onArchiveStartedRef.current = onArchiveStarted;
|
||||
|
||||
const archiveWorkspaceRecord = useCallback(async () => {
|
||||
const client = getHostRuntimeStore().getClient(serverId);
|
||||
if (!client) {
|
||||
toast.error(t("sidebar.workspace.toasts.hostDisconnected"));
|
||||
return;
|
||||
}
|
||||
const workspace = { serverId, workspaceId };
|
||||
onSetHiding?.(true);
|
||||
try {
|
||||
onArchiveStartedRef.current(workspace);
|
||||
if (supportsWorkspaceArchiveUndo(serverId)) {
|
||||
await archiveWorkspaceWithUndo({
|
||||
client,
|
||||
workspace,
|
||||
toast,
|
||||
onArchiveCommitted: () => purgeArchivedWorkspaceState(workspace),
|
||||
});
|
||||
} else {
|
||||
// COMPAT(workspaceArchiveUndo): hosts before v0.15.3 cannot undo; remove after 2027-05-06.
|
||||
await archiveWorkspaceOptimistically({ client, workspace });
|
||||
purgeArchivedWorkspaceState(workspace);
|
||||
const archiveWorkspaceRecord = useCallback(
|
||||
async (options?: { force: boolean }) => {
|
||||
const client = getHostRuntimeStore().getClient(serverId);
|
||||
if (!client) {
|
||||
toast.error(t("sidebar.workspace.toasts.hostDisconnected"));
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
error instanceof Error ? error.message : t("sidebar.workspace.toasts.archiveFailed"),
|
||||
);
|
||||
} finally {
|
||||
onSetHiding?.(false);
|
||||
}
|
||||
}, [onSetHiding, serverId, t, toast, workspaceId]);
|
||||
const workspace = { serverId, workspaceId };
|
||||
onSetHiding?.(true);
|
||||
try {
|
||||
onArchiveStartedRef.current(workspace);
|
||||
if (supportsWorkspaceArchiveUndo(serverId)) {
|
||||
await archiveWorkspaceWithUndo({
|
||||
client,
|
||||
workspace,
|
||||
force: options?.force,
|
||||
toast,
|
||||
onArchiveCommitted: () => purgeArchivedWorkspaceState(workspace),
|
||||
});
|
||||
} else {
|
||||
// COMPAT(workspaceArchiveUndo): hosts before v0.15.3 cannot undo; remove after 2027-05-06.
|
||||
await archiveWorkspaceOptimistically({ client, workspace, force: options?.force });
|
||||
purgeArchivedWorkspaceState(workspace);
|
||||
}
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
error instanceof Error ? error.message : t("sidebar.workspace.toasts.archiveFailed"),
|
||||
);
|
||||
} finally {
|
||||
onSetHiding?.(false);
|
||||
}
|
||||
},
|
||||
[onSetHiding, serverId, t, toast, workspaceId],
|
||||
);
|
||||
|
||||
// The host removes a worktree it archives, uncommitted work included. Ask it what that would
|
||||
// lose: the sidebar row's git status is empty until the row receives it.
|
||||
const confirmWorktreeArchive = useCallback(async (): Promise<boolean> => {
|
||||
// Ask the host what the archive would lose. The sidebar may not have loaded Git status.
|
||||
const confirmWorktreeArchive = useCallback(async (): Promise<{ force: boolean } | null> => {
|
||||
const client = getHostRuntimeStore().getClient(serverId);
|
||||
if (!client) {
|
||||
toast.error(t("sidebar.workspace.toasts.hostDisconnected"));
|
||||
return false;
|
||||
return null;
|
||||
}
|
||||
const risk = await readWorktreeArchiveRisk(client, workspaceDirectory).catch(
|
||||
(error: unknown) => {
|
||||
@@ -110,12 +113,13 @@ export function useWorkspaceArchive(input: ArchiveWorkspaceInput): WorkspaceArch
|
||||
},
|
||||
);
|
||||
if (!risk) {
|
||||
return false;
|
||||
return null;
|
||||
}
|
||||
return await confirmRiskyWorktreeArchive(
|
||||
const confirmed = await confirmRiskyWorktreeArchive(
|
||||
{ workspaceName: name, diffStat, ...risk },
|
||||
warningLabels,
|
||||
);
|
||||
return confirmed ? { force: risk.isDirty === true } : null;
|
||||
}, [diffStat, name, serverId, t, toast, warningLabels, workspaceDirectory]);
|
||||
|
||||
const archive = useCallback(() => {
|
||||
|
||||
@@ -26,8 +26,8 @@ const pendingArchiveAttempts = new Set<string>();
|
||||
/** Checks and starts one archive at a time for a workspace. */
|
||||
export async function runWorkspaceArchiveAttempt(input: {
|
||||
workspace: WorkspaceArchiveTarget;
|
||||
confirm?: () => Promise<boolean>;
|
||||
archive: () => Promise<void>;
|
||||
confirm?: () => Promise<{ force: boolean } | null>;
|
||||
archive: (options?: { force: boolean }) => Promise<void>;
|
||||
}): Promise<void> {
|
||||
const { serverId, workspaceId } = input.workspace;
|
||||
const key = JSON.stringify([serverId, workspaceId]);
|
||||
@@ -35,18 +35,23 @@ export async function runWorkspaceArchiveAttempt(input: {
|
||||
|
||||
pendingArchiveAttempts.add(key);
|
||||
try {
|
||||
if (input.confirm && !(await input.confirm())) return;
|
||||
const confirmed = input.confirm ? await input.confirm() : undefined;
|
||||
if (confirmed === null) return;
|
||||
if (!isWorkspaceListed(input.workspace)) return;
|
||||
// Archive hides the row synchronously. Undo can restore it and start a new
|
||||
// archive while the previous daemon request is still settling.
|
||||
return input.archive();
|
||||
return input.archive(confirmed);
|
||||
} finally {
|
||||
pendingArchiveAttempts.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
interface WorkspaceArchiveClient {
|
||||
archiveWorkspace: (workspaceId: string) => Promise<{ error: string | null; canceled?: boolean }>;
|
||||
export interface WorkspaceArchiveClient {
|
||||
archiveWorkspace: (
|
||||
workspaceId: string,
|
||||
requestId?: string,
|
||||
options?: { force?: boolean },
|
||||
) => Promise<{ error: string | null; canceled?: boolean }>;
|
||||
}
|
||||
|
||||
interface WorkspaceArchiveUndoClient {
|
||||
@@ -158,8 +163,11 @@ function invalidateAgentHistory(serverId: string): void {
|
||||
async function archiveWorkspaceOrThrow(input: {
|
||||
client: WorkspaceArchiveClient;
|
||||
workspaceId: string;
|
||||
force?: boolean;
|
||||
}): Promise<WorkspaceArchiveOutcome> {
|
||||
const payload = await input.client.archiveWorkspace(input.workspaceId);
|
||||
const payload = input.force
|
||||
? await input.client.archiveWorkspace(input.workspaceId, undefined, { force: true })
|
||||
: await input.client.archiveWorkspace(input.workspaceId);
|
||||
if (payload.canceled) {
|
||||
return "canceled";
|
||||
}
|
||||
@@ -176,6 +184,7 @@ async function archiveWorkspaceOrThrow(input: {
|
||||
export function beginOptimisticWorkspaceArchive(input: {
|
||||
client: WorkspaceArchiveClient;
|
||||
workspace: WorkspaceArchiveTarget;
|
||||
force?: boolean;
|
||||
}): OptimisticWorkspaceArchive {
|
||||
const snapshot = hideWorkspaceOptimistically(input.workspace);
|
||||
const done = (async () => {
|
||||
@@ -183,6 +192,7 @@ export function beginOptimisticWorkspaceArchive(input: {
|
||||
const outcome = await archiveWorkspaceOrThrow({
|
||||
client: input.client,
|
||||
workspaceId: input.workspace.workspaceId,
|
||||
force: input.force,
|
||||
});
|
||||
if (outcome === "canceled") {
|
||||
restoreOptimisticallyHiddenWorkspace({ serverId: input.workspace.serverId, snapshot });
|
||||
@@ -201,6 +211,7 @@ export function beginOptimisticWorkspaceArchive(input: {
|
||||
export async function archiveWorkspaceOptimistically(input: {
|
||||
client: WorkspaceArchiveClient;
|
||||
workspace: WorkspaceArchiveTarget;
|
||||
force?: boolean;
|
||||
}): Promise<WorkspaceArchiveOutcome> {
|
||||
return beginOptimisticWorkspaceArchive(input).done;
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user