Compare commits

..
37 changed files with 1095 additions and 1729 deletions
-1
View File
@@ -58,7 +58,6 @@ 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 |
-82
View File
@@ -1,82 +0,0 @@
# 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.
@@ -1,208 +0,0 @@
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();
}
});
});
@@ -5,34 +5,30 @@ import { expectComposerVisible } from "../support/helpers/composer";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
interface ShimmerEvidence {
durationMs: number;
animationDuration: string;
endPx: number;
label: string;
renderedWidth: number;
startPx: number;
}
// 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,
};
});
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")),
};
});
}
test("measures an overview heading that becomes loading after its idle mount", async ({
@@ -67,11 +63,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.getByTestId("label-shimmer")).toHaveCount(0);
await expect(group.locator('[style*="paseo-toolcall-shimmer"]')).toHaveCount(0);
await gate.waitForSecondRunning();
gate.releaseSecondRunning();
await expect(group.getByTestId("label-shimmer")).not.toHaveCount(0);
await expect(group.locator('[style*="paseo-toolcall-shimmer"]')).not.toHaveCount(0);
const sameGroupNode = await group.evaluate(
(node, previous) => node === previous,
idleGroupHandle,
@@ -7,29 +7,9 @@ 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. 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
```
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`.
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:
@@ -0,0 +1,45 @@
# 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.
@@ -0,0 +1,71 @@
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");
@@ -0,0 +1,69 @@
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>
);
}
@@ -1,198 +0,0 @@
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);
}
@@ -1,157 +0,0 @@
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);
}
}
@@ -1,60 +0,0 @@
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]);
}
@@ -1,49 +0,0 @@
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;
}
@@ -1,50 +0,0 @@
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;
}
@@ -1,140 +0,0 @@
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>
);
}
@@ -1,116 +0,0 @@
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>
);
});
@@ -1,67 +0,0 @@
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,
};
}
@@ -1,48 +0,0 @@
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 });
});
});
@@ -1,62 +0,0 @@
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 };
}
+524 -16
View File
@@ -13,6 +13,7 @@ import {
AttachmentThumbnail,
} from "@/components/attachment-pill";
import { MarkdownRenderer } from "@/components/markdown/renderer";
import { useRetainedPanelActive } from "@/components/retained-panel";
import {
isRewindableMessage,
RewindMenu,
@@ -28,7 +29,6 @@ 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,6 +54,7 @@ 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,
@@ -93,6 +94,15 @@ 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";
@@ -143,6 +153,8 @@ 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);
@@ -161,6 +173,17 @@ 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).
@@ -168,6 +191,31 @@ 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) {
@@ -1043,6 +1091,14 @@ 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,
},
@@ -1081,8 +1137,160 @@ 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,
@@ -1676,30 +1884,77 @@ interface ExpandableBadgeProps {
interface ExpandableBadgeSecondaryLabelProps {
secondaryLabel?: string;
secondaryLabelStyle: StyleProp<TextStyle>;
onLayout: ((event: LayoutChangeEvent) => void) | undefined;
shouldMeasureWebShimmer: boolean;
onSecondaryLayout: (event: LayoutChangeEvent) => void;
}
function ExpandableBadgeSecondaryLabel({
secondaryLabel,
secondaryLabelStyle,
onLayout,
shouldMeasureWebShimmer,
onSecondaryLayout,
}: ExpandableBadgeSecondaryLabelProps) {
if (!secondaryLabel) {
return null;
}
return (
<Text style={secondaryLabelStyle} numberOfLines={1} onLayout={onLayout}>
<Text
style={secondaryLabelStyle}
numberOfLines={1}
onLayout={shouldMeasureWebShimmer ? onSecondaryLayout : undefined}
>
{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>;
isLoading: boolean;
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;
}
function ExpandableBadgeLabelRow({
@@ -1707,26 +1962,56 @@ function ExpandableBadgeLabelRow({
labelStyle,
secondaryLabel,
secondaryLabelStyle,
isLoading,
shouldMeasureWebShimmer,
shouldMeasureNativeShimmer,
isWebShimmer,
isNativeShimmer,
shimmerLabelTextStyle,
shimmerSecondaryTextStyle,
labelRowWidth,
labelRowHeight,
nativeShimmerPeakWidth,
shimmerDuration,
nativeGradientId,
onLabelRowLayout,
onLabelLayout,
onSecondaryLayout,
}: ExpandableBadgeLabelRowProps) {
const measuring = useLabelMeasurements(isLoading);
return (
<View style={expandableBadgeStylesheet.labelRow} onLayout={measuring.onRowLayout}>
<Text style={labelStyle} numberOfLines={1} onLayout={measuring.onLabelLayout}>
<View
style={expandableBadgeStylesheet.labelRow}
onLayout={shouldMeasureNativeShimmer ? onLabelRowLayout : undefined}
>
<Text
style={labelStyle}
numberOfLines={1}
onLayout={shouldMeasureWebShimmer ? onLabelLayout : undefined}
>
{label}
</Text>
<ExpandableBadgeSecondaryLabel
secondaryLabel={secondaryLabel}
secondaryLabelStyle={secondaryLabelStyle}
onLayout={measuring.onSecondaryLayout}
shouldMeasureWebShimmer={shouldMeasureWebShimmer}
onSecondaryLayout={onSecondaryLayout}
/>
{isLoading ? (
<LabelShimmer
{isWebShimmer ? (
<ExpandableBadgeWebShimmerOverlay
label={label}
secondaryLabel={secondaryLabel}
labelStyle={expandableBadgeStylesheet.label}
secondaryLabelStyle={expandableBadgeStylesheet.secondaryLabel}
measurements={measuring.measurements}
shimmerLabelTextStyle={shimmerLabelTextStyle}
shimmerSecondaryTextStyle={shimmerSecondaryTextStyle}
/>
) : null}
{isNativeShimmer ? (
<NativeExpandableBadgeShimmer
label={label}
secondaryLabel={secondaryLabel}
rowWidth={labelRowWidth}
rowHeight={labelRowHeight}
peakWidth={nativeShimmerPeakWidth}
durationSeconds={shimmerDuration}
gradientId={nativeGradientId}
/>
) : null}
</View>
@@ -1801,6 +2086,55 @@ 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;
@@ -1827,6 +2161,33 @@ 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,
@@ -1870,11 +2231,126 @@ 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,
@@ -1932,6 +2408,25 @@ 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,
@@ -1980,7 +2475,20 @@ export const ExpandableBadge = memo(function ExpandableBadge({
labelStyle={labelStyle}
secondaryLabel={secondaryLabel}
secondaryLabelStyle={secondaryLabelStyle}
isLoading={isLoading}
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}
/>
</Pressable>
{onOpenFile && isHovered ? (
@@ -0,0 +1,74 @@
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;
}
@@ -0,0 +1,35 @@
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)]} testID="status-ring">
<View style={[styles.frame, getBackdropStyle(backdrop)]}>
<View style={styles.track} />
{children}
<View style={styles.centerDot} />
@@ -60,9 +60,10 @@ function getBackdropStyle(backdrop: SurfaceBackdrop | null | undefined) {
}
// The rotating quarter's geometry, deliberately plain React Native rather than Unistyles: on
// 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.
// 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.
export const rotatorStyles = RNStyleSheet.create({
rotator: {
position: "absolute",
@@ -26,11 +26,17 @@ 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 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.
// 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.
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,31 +1,30 @@
import { memo } from "react";
import { Animated, View } from "react-native";
import { useIndicatorMotion } from "@/components/indicator-motion";
import { sharedIndicatorClock, useRunningClock } from "@/components/indicator-motion/clock";
import { View } from "react-native";
import Animated, { useAnimatedStyle } from "react-native-reanimated";
import {
StatusRingFrame,
type StatusRingProps,
rotatorStyles,
styles,
} from "@/components/status-ring/frame";
import { STATUS_RING_PERIOD_MS } from "@/components/status-ring/geometry";
import { useStatusRingRotation } from "@/components/status-ring/clock";
// 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`. */
/**
* 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).
*/
export const StatusRing = memo(function StatusRing({ backdrop }: StatusRingProps) {
const moving = useIndicatorMotion();
useRunningClock(sharedIndicatorClock, moving);
const rotation = useStatusRingRotation();
const rotatorStyle = useAnimatedStyle(() => ({
transform: [{ rotate: `${rotation.value}deg` }],
}));
return (
<StatusRingFrame backdrop={backdrop}>
<Animated.View style={[rotatorStyles.rotator, moving && turning]}>
<Animated.View style={[rotatorStyles.rotator, rotatorStyle]}>
<View style={styles.arc} />
</Animated.View>
</StatusRingFrame>
@@ -1,27 +1,20 @@
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 { STATUS_RING_PERIOD_MS } from "@/components/status-ring/geometry";
import { useStatusRingAnimationRef } from "@/components/status-ring/clock.web";
// 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`. */
/**
* 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`.
*/
export const StatusRing = memo(function StatusRing({ backdrop }: StatusRingProps) {
const moving = useIndicatorMotion();
const rotatorRef = useIndicatorLoop(moving ? TURNING : null);
const rotatorRef = useStatusRingAnimationRef();
return (
<StatusRingFrame backdrop={backdrop}>
@@ -1,5 +1,5 @@
import { describe, expect, test } from "vitest";
import { getSyncedLoaderDotOpacity, getSyncedLoaderStep } from "./state";
import { getSyncedLoaderDotOpacity, getSyncedLoaderStep } from "./synced-loader-state";
describe("synced loader state", () => {
test("advances through six wall-clock-aligned steps every 950 milliseconds", () => {
@@ -1,4 +1,4 @@
export const SYNCED_LOADER_DURATION_MS = 950;
const SYNCED_LOADER_DURATION_MS = 950;
export const SYNCED_LOADER_DOT_COUNT = 6;
const SYNCED_LOADER_OPACITY_STATES = [
@@ -10,22 +10,13 @@ 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,184 @@
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} />;
}
@@ -1,58 +0,0 @@
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>
);
}
@@ -1,55 +0,0 @@
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" />;
}
@@ -1,43 +0,0 @@
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,93 +0,0 @@
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]);
});
});
@@ -1,42 +0,0 @@
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;
}
};
},
};
}
@@ -1786,6 +1786,8 @@ export class DaemonClientCore {
// An endpoint security policy close cannot be fixed by retrying.
const securityFailure = describeEndpointSecurityClose(event);
if (securityFailure) this.setReconnectEnabled(false);
// A transport error may already have scheduled this socket's retry before its close.
if (this.reconnectTimeout && !securityFailure && !this.authFailureReasonValue) return;
const reason = this.authFailureReasonValue
? new DaemonAuthenticationError(this.authFailureReasonValue).message
: (securityFailure ?? describeTransportClose(event));
+28
View File
@@ -3020,6 +3020,34 @@ test("foreground keeps a connect attempt that just started", async () => {
expect(client.getConnectionState().status).toBe("connected");
});
test("a handshake error followed by a close consumes one reconnect attempt", async () => {
useHeartbeatClock();
const [first, failed, recovered] = [
new FakeDaemon(),
new FakeDaemon(),
new FakeDaemon(),
] as const;
const { client, attempts } = connectThroughReplacements("error-and-close", [
first,
failed,
recovered,
]);
const connection = client.connect();
first.openConnection();
await connection;
first.daemonClosesWith("connection lost");
await vi.advanceTimersByTimeAsync(1_500);
expect(attempts()).toBe(2);
failed.triggerError(new Error("read ECONNRESET"));
failed.daemonClosesWith("abnormal closure");
await vi.advanceTimersByTimeAsync(2_999);
expect(attempts()).toBe(2);
await vi.advanceTimersByTimeAsync(1);
expect(attempts()).toBe(3);
recovered.openConnection();
expect(client.getConnectionState().status).toBe("connected");
});
test("foreground resets the retry delay after failed connections in the background", async () => {
useHeartbeatClock();
const daemons = Array.from({ length: 7 }, () => new FakeDaemon());
@@ -537,38 +537,6 @@ describe("MockLoadTestAgentClient", () => {
unsubscribe();
});
test("holds one running tool call with no other activity for the requested time", async () => {
vi.useFakeTimers();
const client = new MockLoadTestAgentClient();
const session = await client.createSession({
provider: "mock",
cwd: process.cwd(),
model: "e2e-fast-stream",
});
const activity: string[] = [];
const unsubscribe = session.subscribe((event) => {
if (event.type !== "timeline") {
activity.push(event.type);
} else if (event.item.type === "tool_call") {
activity.push(`tool_call:${event.item.status}`);
} else {
activity.push(event.item.type);
}
});
const resultPromise = session.run("Hold a running shell tool call for 60000ms.");
await vi.advanceTimersByTimeAsync(59_999);
expect(activity).toEqual(["turn_started", "user_message", "tool_call:running"]);
await vi.advanceTimersByTimeAsync(1);
await expect(resultPromise).resolves.toMatchObject({
finalText: "Held command completed.",
canceled: false,
});
expect(activity.slice(3, 5)).toEqual(["tool_call:completed", "assistant_message"]);
unsubscribe();
});
test("agent manager coalesces adjacent assistant tokens into fewer messages", async () => {
vi.useFakeTimers();
const workdir = mkdtempSync(join(tmpdir(), "paseo-mock-load-test-"));
@@ -275,19 +275,6 @@ function parseSteeringReplayShape(prompt: AgentPromptInput): SteeringReplayShape
return match?.[1] === "claude" || match?.[1] === "codex" ? match[1] : null;
}
const MAX_HELD_TOOL_CALL_MS = 30 * 60 * 1000;
// A turn whose only activity is one running tool call. Nothing streams while it holds, so a
// client shows its running indicators over an otherwise idle conversation.
function parseHeldToolCallMs(prompt: AgentPromptInput): number | null {
const match = /hold a running shell tool call for (\d+)ms/i.exec(promptToText(prompt));
if (!match) {
return null;
}
const holdMs = Number(match[1]);
return Number.isSafeInteger(holdMs) ? Math.min(holdMs, MAX_HELD_TOOL_CALL_MS) : null;
}
function parseSettledAssistantImageMarkdown(prompt: AgentPromptInput): string | null {
const match = /^emit settled assistant image markdown:\s*(!\[[^\]\r\n]*\]\(.+\))\s*$/i.exec(
promptToText(prompt),
@@ -959,12 +946,9 @@ export class MockLoadTestAgentSession implements AgentSession {
const structuredBranchName = parseStructuredBranchNamePrompt(prompt);
const settledAssistantImageMarkdown = parseSettledAssistantImageMarkdown(prompt);
const steeringReplayShape = parseSteeringReplayShape(prompt);
const heldToolCallMs = parseHeldToolCallMs(prompt);
const scheduleTurn = () => {
if (shouldEmitTurnFailure(prompt)) {
this.scheduleFailedTurn(turn);
} else if (heldToolCallMs !== null) {
this.scheduleHeldToolCallTurn(turn, heldToolCallMs);
} else if (steeringReplayShape) {
this.scheduleSteeringReplayTurn(turn, steeringReplayShape);
} else if (this.streamingAssistantResponse !== null) {
@@ -1330,45 +1314,6 @@ export class MockLoadTestAgentSession implements AgentSession {
turn.timer.unref?.();
}
private scheduleHeldToolCallTurn(turn: ActiveTurn, holdMs: number): void {
turn.timer = setTimeout(() => {
if (this.activeTurn !== turn) return;
this.clearTurnTimer(turn);
this.emitTurnStarted(turn);
const callId = `${turn.turnId}:held-shell`;
const detail: ToolCallDetail = {
type: "shell",
command: `sleep ${Math.ceil(holdMs / 1000)}`,
cwd: "/tmp/paseo-mock-load",
};
this.emitTimeline(
turn.turnId,
createToolCall({ callId, name: "bash", status: "running", detail }),
);
turn.timer = setTimeout(() => {
if (this.activeTurn !== turn) return;
this.clearTurnTimer(turn);
this.emitTimeline(
turn.turnId,
createToolCall({
callId,
name: "bash",
status: "completed",
detail: { ...detail, output: "", exitCode: 0 },
}),
);
this.emitTimeline(turn.turnId, {
type: "assistant_message",
text: "Held command completed.",
messageId: turn.assistantMessageId,
});
this.finishTurnWithText(turn, "Held command completed.");
}, holdMs);
turn.timer.unref?.();
}, 0);
turn.timer.unref?.();
}
private scheduleSplitClosingFenceTurn(turn: ActiveTurn): void {
const chunks = [...SPLIT_CLOSING_FENCE_CHUNKS];
const finalText = chunks.map((chunk) => chunk.text).join("");