Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

perf(desktop): quiet when idle — unread mascots hold still, small mascots at 20 fps, stepped compositor sheen (#4149)

Milind Sonicc86ddb2d607
diff --git a/src/components/AttachmentPreview.tsx b/src/components/AttachmentPreview.tsx
index 312fac9487..1e0e10cff0 100644
--- a/src/components/AttachmentPreview.tsx
+++ b/src/components/AttachmentPreview.tsx
@@ -33,6 +33,7 @@ import {
import { cn } from "@/lib/cn";
import { t } from "@/lib/i18n";
import { FilePreviewButton } from "./FilePreviewButton";
+import { ImageLoading } from "./ImageLoading";
export interface PreviewImage {
src: string;
@@ -676,12 +677,7 @@ export function AttachmentThumbnail({
style={ratio ? { aspectRatio: String(ratio) } : undefined}
className={cn("group/image relative block aspect-[4/3] min-w-0 overflow-hidden rounded-xl border border-hairline/40 bg-inset", className)}
>
- {state === "loading" && (
- <span className="absolute inset-0 flex animate-pulse items-center justify-center bg-raised/65" role="status">
- <LoaderCircle size={17} className="animate-spin text-ink-tertiary" />
- <span className="sr-only">Loading {image.name}</span>
- </span>
- )}
+ {state === "loading" && <ImageLoading name={image.name} className="absolute inset-0 bg-raised/65" />}
{state === "failed" ? (
<span className="absolute inset-0 flex flex-col items-center justify-center gap-2 px-3 text-center text-ink-secondary" role="alert">
<ImageOff size={22} />
@@ -879,10 +875,7 @@ export function MarkdownImagePreview({
) : visibleSource ? (
<AttachmentThumbnail key={image.src} image={image} onPreview={() => setOpen(true)} className="max-h-96" eager explainRefusal={localMessageImage} />
) : (
- <span className="flex aspect-[4/3] max-h-96 animate-pulse items-center justify-center rounded-xl border border-hairline/40 bg-inset" role="status">
- <LoaderCircle size={17} className="animate-spin text-ink-tertiary" />
- <span className="sr-only">Loading {name}</span>
- </span>
+ <ImageLoading name={name} className="aspect-[4/3] max-h-96 rounded-xl border border-hairline/40 bg-inset" />
)}
{openUrl && (
<a href={openUrl} target="_blank" rel="noreferrer" className="mt-1 inline-flex text-[11px] text-accent hover:underline">
diff --git a/src/components/CarvedAvatar.tsx b/src/components/CarvedAvatar.tsx
index b0d7c5b543..223f0c07f2 100644
--- a/src/components/CarvedAvatar.tsx
+++ b/src/components/CarvedAvatar.tsx
@@ -11,7 +11,8 @@ import {
import { MAUS_COLORS, type MausColor, type MausMotion, type MausState } from "@/lib/mascot";
import { HALLOWEEN_BODIES, type HalloweenBody, type HalloweenBodyId } from "../../shared/halloween-bodies";
import type { CursorAvatarHandle } from "./CursorAvatar";
-import { usePrefersReducedMotion } from "./mascot-clock";
+import { mascotClock, usePrefersReducedMotion } from "./mascot-clock";
+import { frameFloorMs, nextFrameAt } from "./mascot-motion";
import { mascotFaceInk, type MascotFaceColor } from "../../shared/bot-avatar";
/** Where the face looks and how it feels. */
@@ -214,7 +215,6 @@ function CarvedAvatarComponent(
useEffect(() => {
if (!live) return;
- let frame = 0;
let last = performance.now();
let glanceAt = last + 900 + Math.random() * 2600;
let blinkAt = last + 1500 + Math.random() * 3500;
@@ -251,11 +251,11 @@ function CarvedAvatarComponent(
const blink = since >= 1 ? 0 : since < 0.45 ? since / 0.45 : 1 - (since - 0.45) / 0.55;
p.shut += (Math.max(want.shut, blink) - p.shut) * (blink > 0 ? 1 : k(10));
paint(p);
- frame = requestAnimationFrame(step);
+ return nextFrameAt(now, frameFloorMs(size));
};
- frame = requestAnimationFrame(step);
- return () => cancelAnimationFrame(frame);
- }, [body, live]);
+ const ticket = mascotClock().add(step, group.current?.ownerSVGElement);
+ return () => ticket.remove();
+ }, [body, live, size]);
const onPointerMove = (event: ReactPointerEvent<HTMLSpanElement>) => {
const rect = event.currentTarget.getBoundingClientRect();
diff --git a/src/components/CursorAvatar.clock.test.ts b/src/components/CursorAvatar.clock.test.ts
index ee8577f3a0..5affddd533 100644
--- a/src/components/CursorAvatar.clock.test.ts
+++ b/src/components/CursorAvatar.clock.test.ts
@@ -6,6 +6,7 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi }
import { MausAvatar, type MausAvatarHandle, type MausAvatarProps } from "./Avatar";
import { EFFECTS, EXPRESSIONS, POOLS } from "./CursorAvatar";
import { mascotClock } from "./mascot-clock";
+import { UNREAD_NOTICE_MS, useUnreadNotice } from "./unread-notice";
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -67,7 +68,7 @@ const toPath = (ring: Array<[number, number]>) => "M" + ring.map((p) => p[0].toF
describe("CursorAvatar on the shared clock", () => {
it("draws every animated mascot from one animation frame", () => {
- render(Array.from({ length: 12 }, () => ({ state: "working" as const, size: 36 })));
+ render(Array.from({ length: 12 }, () => ({ state: "working" as const, size: 96 })));
run(100);
frameRequests = 0;
run(1000);
@@ -76,6 +77,15 @@ describe("CursorAvatar on the shared clock", () => {
expect(mascotClock().pending()).toBe(12);
});
+ it("draws a sidebar full of working mascots 20 times a second", () => {
+ render(Array.from({ length: 12 }, (_, i) => ({ state: "working" as const, size: [24, 28, 42, 56][i % 4] })));
+ run(100);
+ frameRequests = 0;
+ run(1000);
+ expect(frameRequests).toBeGreaterThanOrEqual(18);
+ expect(frameRequests).toBeLessThanOrEqual(21);
+ });
+
it("paints a still mascot with its state's face and then asks for nothing", () => {
render([{ state: "sleeping", animated: false, size: 24 }]);
run(100);
@@ -123,6 +133,24 @@ describe("CursorAvatar on the shared clock", () => {
expect(writes).toHaveBeenCalled();
});
+ it("lets an unread mascot play its notice, then draws nothing while the news waits", () => {
+ function Row({ unread }: { unread: boolean }) {
+ return createElement(MausAvatar, { color: "green", state: unread ? "notifying" : "idle", size: 42, animated: useUnreadNotice(unread) });
+ }
+ act(() => root.render(createElement(Row, { unread: false })));
+ run(200);
+ act(() => root.render(createElement(Row, { unread: true })));
+ frameRequests = 0;
+ run(2000);
+ expect(frameRequests).toBeGreaterThan(20);
+ run(UNREAD_NOTICE_MS);
+ run(100);
+ frameRequests = 0;
+ run(30_000);
+ expect(frameRequests).toBe(0);
+ expect(mascotClock().pending()).toBe(0);
+ });
+
it("stops drawing a mascot that leaves the screen", () => {
render([{ state: "working", size: 36 }]);
run(200);
@@ -132,7 +160,7 @@ describe("CursorAvatar on the shared clock", () => {
expect(frameRequests).toBe(0);
act(() => observed.callback!([{ target: host.querySelector("svg")!, isIntersecting: true }]));
run(500);
- expect(frameRequests).toBeGreaterThan(10);
+ expect(frameRequests).toBeGreaterThan(5);
});
it("holds still under reduced motion: no body motion, blinks or spins", () => {
diff --git a/src/components/CursorAvatar.tsx b/src/components/CursorAvatar.tsx
index 17e5f6cc1d..f8925f9624 100644
--- a/src/components/CursorAvatar.tsx
+++ b/src/components/CursorAvatar.tsx
@@ -14,7 +14,7 @@ import {
mouthFrame,
type Ring,
} from "./cursor-face-data"
-import { GLYPH_EASE_MS, MOTION, VIEW_SPAN, bodyTransform, faceTravelUnits, morphUnitsPerMs, nextMascotFrame, type BodyMotion } from "./mascot-motion"
+import { GLYPH_EASE_MS, MOTION, VIEW_SPAN, bodyTransform, faceTravelUnits, frameFloorMs, morphUnitsPerMs, nextFrameAt, nextMascotFrame, type BodyMotion } from "./mascot-motion"
import { mascotClock, usePrefersReducedMotion, type MascotTicket } from "./mascot-clock"
export { MOTION, bodyTransform }
@@ -957,7 +957,7 @@ export const CursorAvatar = React.forwardRef<CursorAvatarHandle, CursorAvatarPro
const confettiLayer = useRef<SVGGElement | null>(null)
const glyphLayer = useRef<SVGGElement | null>(null)
const ticket = useRef<MascotTicket | null>(null)
- const wake = () => ticket.current?.wake()
+ const wake = () => ticket.current?.wake(nextFrameAt(performance.now(), frameFloorMs(engine.current.props.sizePx)))
const reduced = usePrefersReducedMotion()
const motionStrength = motion ?? (reduced ? 0 : 1)
diff --git a/src/components/ImageLoading.test.ts b/src/components/ImageLoading.test.ts
new file mode 100644
index 0000000000..c4012fc0df
--- /dev/null
+++ b/src/components/ImageLoading.test.ts
@@ -0,0 +1,56 @@
+// @vitest-environment happy-dom
+import { act, createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { ImageLoading } from "./ImageLoading";
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+type Change = { target: Element; isIntersecting: boolean };
+const observer: { report: ((changes: Change[]) => void) | null; watched: Set<Element> } = { report: null, watched: new Set() };
+vi.stubGlobal("IntersectionObserver", class {
+ constructor(report: (changes: Change[]) => void) {
+ observer.report = report;
+ }
+ observe(target: Element) { observer.watched.add(target); }
+ unobserve(target: Element) { observer.watched.delete(target); }
+ disconnect() {}
+});
+
+let host: HTMLDivElement;
+let root: Root;
+
+beforeEach(() => {
+ host = document.createElement("div");
+ document.body.append(host);
+ root = createRoot(host);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ host.remove();
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+describe("an image's loading tile", () => {
+ it("holds still off screen and pulses only while it can be seen", () => {
+ act(() => root.render(createElement(ImageLoading, { name: "chart.png", className: "absolute inset-0" })));
+ const tile = host.querySelector<HTMLElement>("[role=status]")!;
+ const moving = () => [tile.classList.contains("animate-pulse"), tile.querySelector("svg")!.classList.contains("animate-spin")];
+ expect(tile.textContent).toBe("Loading chart.png");
+ expect(moving()).toEqual([false, false]);
+ act(() => observer.report!([{ target: tile, isIntersecting: true }]));
+ expect(moving()).toEqual([true, true]);
+ act(() => observer.report!([{ target: tile, isIntersecting: false }]));
+ expect(moving()).toEqual([false, false]);
+ });
+
+ it("stops watching once the image has loaded", () => {
+ act(() => root.render(createElement(ImageLoading, { name: "chart.png", className: "absolute inset-0" })));
+ expect(observer.watched.size).toBe(1);
+ act(() => root.render(null));
+ expect(observer.watched.size).toBe(0);
+ });
+});
diff --git a/src/components/ImageLoading.tsx b/src/components/ImageLoading.tsx
new file mode 100644
index 0000000000..4748ea98c7
--- /dev/null
+++ b/src/components/ImageLoading.tsx
@@ -0,0 +1,16 @@
+import { LoaderCircle } from "lucide-react";
+import { useRef } from "react";
+
+import { cn } from "@/lib/cn";
+import { useOnScreen } from "@/lib/on-screen";
+
+export function ImageLoading({ name, className }: { name: string; className: string }) {
+ const tile = useRef<HTMLSpanElement>(null);
+ const moving = useOnScreen(tile);
+ return (
+ <span ref={tile} className={cn("flex items-center justify-center", moving && "animate-pulse", className)} role="status">
+ <LoaderCircle size={17} className={cn("text-ink-tertiary", moving && "animate-spin")} />
+ <span className="sr-only">Loading {name}</span>
+ </span>
+ );
+}
diff --git a/src/components/PinnedCircleThreads.tsx b/src/components/PinnedCircleThreads.tsx
index 94539f2bc3..b0bfc77182 100644
--- a/src/components/PinnedCircleThreads.tsx
+++ b/src/components/PinnedCircleThreads.tsx
@@ -18,6 +18,7 @@ import { PINNED_CIRCLE_DRAG_TYPE, pinnedCircleDropPlace, rankPinnedCircles, reor
import { sidebarSectionAttention } from "@/lib/sidebar-attention";
import { SidebarSectionHeader } from "./SidebarSectionHeader";
import { BotListItem, BotThreadList, type BotRowProps } from "./Sidebar";
+import { useUnreadNotice } from "./unread-notice";
function useVisibleMessages(bot: Bot): Message[] {
const { messages, activeLeafId } = bot;
@@ -189,6 +190,7 @@ export const PinnedBotCircle = memo(function PinnedBotCircle({
const waiting = bot.activity === "waiting-on-you" || activityTasks.some((task) => task.activity === "waiting-on-you");
const working = !waiting && (Boolean(bot.busy) || activityTasks.some((task) => task.busy || task.activity === "working"));
const unread = bot.unread || activityTasks.some((task) => task.unread);
+ const noticing = useUnreadNotice(Boolean(bot.unread));
const radius = avatarCropRadius(botAvatarProfile(bot).avatarCrop);
return (
<div className="flex w-full min-w-0 flex-col items-center">
@@ -226,7 +228,7 @@ export const PinnedBotCircle = memo(function PinnedBotCircle({
size={64}
motion={mascotMotion?.kind ?? "none"}
motionKey={mascotMotion?.nonce ?? 0}
- animated={working || Boolean(bot.unread) || (mascotMotion?.kind ?? "none") !== "none"}
+ animated={working || noticing || (mascotMotion?.kind ?? "none") !== "none"}
/>
</span>
{unread && (
diff --git a/src/components/Sidebar.tsx b/src/components/Sidebar.tsx
index 2d8daa015e..7c809bc119 100644
--- a/src/components/Sidebar.tsx
+++ b/src/components/Sidebar.tsx
@@ -84,7 +84,7 @@ import { PHONE_TOP_BUTTON, SIMPLE_CORNER_BUTTON, SIMPLE_ROW_FOCUS, SIMPLE_TOP_BU
import { isSidebarToggle } from "@/lib/keyboard-shortcuts";
import { SidebarRailSeparator, SimpleRailFooter } from "./SidebarSimpleRail";
import { useShowThreads } from "@/lib/thread-preferences";
-import { botShowsUnread } from "@/lib/bot-unread";
+import { useBotUnread } from "./unread-notice";
import { attentionHasRunningWork, attentionJumpAction, attentionTriggerLabel, attentionUnpinAction, AttentionThreadRows, crossBotAttentionThreads, crossBotPinnedThreads, SidebarBotActivity, sidebarBotActivityTasks, sidebarBotStatus } from "./SidebarBotActivity";
import { SidebarNoBots, SidebarTileGrid } from "./SidebarTiles";
import { BotContextMenu } from "./SidebarBotMenu";
@@ -727,7 +727,7 @@ export const BotListItem = memo(function BotListItem(props: BotRowProps) {
simpleRow && rowSurface(selected),
);
const { waiting, working, teammateWait, queued } = sidebarBotStatus(bot, pendingQueued);
- const unread = botShowsUnread(bot);
+ const { unread, noticing } = useBotUnread(bot);
const onLiveCall = liveBadgeFor(bot.id, liveMedia, liveCall);
const body = (
<>
@@ -738,7 +738,7 @@ export const BotListItem = memo(function BotListItem(props: BotRowProps) {
size={simpleRow ? avatarSize + 6 : avatarSize}
motion={mascotMotion?.kind ?? "none"}
motionKey={mascotMotion?.nonce ?? 0}
- animated={working || unread || (mascotMotion?.kind ?? "none") !== "none"}
+ animated={working || noticing || (mascotMotion?.kind ?? "none") !== "none"}
/>
{/* Bottom-left, clear of the status dots on the right and of the row's hover actions. */}
{(iconOnly || !simpleList) && <BotModelBadge bot={bot} instances={instances} avatarSize={avatarSize} />}
diff --git a/src/components/SidebarTiles.tsx b/src/components/SidebarTiles.tsx
index b24a369acc..903e88212a 100644
--- a/src/components/SidebarTiles.tsx
+++ b/src/components/SidebarTiles.tsx
@@ -1,7 +1,6 @@
import { Crown, Loader2, Phone } from "lucide-react";
import { memo, useLayoutEffect, useRef, useState, type KeyboardEvent, type MouseEvent } from "react";
-import { botShowsUnread } from "@/lib/bot-unread";
import { cn } from "@/lib/cn";
import { t } from "@/lib/i18n";
import { useLiveMedia } from "@/lib/live-call-media";
@@ -18,6 +17,7 @@ import { RenameTitle } from "./RenameTitle";
import { openBotContextMenu, useVisibleMessages, type BotRowProps } from "./Sidebar";
import { sidebarBotStatus } from "./SidebarBotActivity";
import { SIMPLE_ROW_FOCUS } from "./SidebarSimpleTop";
+import { useBotUnread } from "./unread-notice";
const RING = "ring-2 ring-[var(--tile)]";
@@ -31,7 +31,7 @@ export const SidebarBotTile = memo(function SidebarBotTile({ primary = false, dr
const [renaming, setRenaming] = useState(false);
const visible = useVisibleMessages(bot);
const { waiting, working, teammateWait, queued } = sidebarBotStatus(bot, pendingQueued);
- const unread = botShowsUnread(bot);
+ const { unread, noticing } = useBotUnread(bot);
const onLiveCall = liveBadgeFor(bot.id, liveMedia, liveCall);
const tooltip = botTooltip(bot, instances);
const status = waiting ? t("sidebar.preview.waiting") : working ? t("chat.activity.working") : teammateWait ? t("sidebar.preview.waitingOnTeammate") : queued ? t("task.queued") : "";
@@ -87,7 +87,7 @@ export const SidebarBotTile = memo(function SidebarBotTile({ primary = false, dr
size={56}
motion={mascotMotion?.kind ?? "none"}
motionKey={mascotMotion?.nonce ?? 0}
- animated={working || unread || (mascotMotion?.kind ?? "none") !== "none"}
+ animated={working || noticing || (mascotMotion?.kind ?? "none") !== "none"}
/>
{primary && bot.chiefOfStaff && (
<span data-testid="chief-badge" className={cn("absolute -bottom-px -right-px flex size-4 items-center justify-center rounded-full bg-[#E8993A] text-white", RING)}>
diff --git a/src/components/TurnPresence.test.ts b/src/components/TurnPresence.test.ts
index 7bd39f8796..39120f6912 100644
--- a/src/components/TurnPresence.test.ts
+++ b/src/components/TurnPresence.test.ts
@@ -192,11 +192,30 @@ describe("the Now card", () => {
});
describe("thinking shimmer box", () => {
- it("pads the sheen past ascenders, descenders and arabic marks without moving the layout", () => {
- const css = readFileSync("src/styles.css", "utf8");
+ const css = readFileSync("src/styles.css", "utf8");
+
+ it("pads the phrase and its sheen past ascenders, descenders and arabic marks without moving the layout", () => {
const rule = css.match(/\.thinking-shimmer \{[^}]*\}/)?.[0] ?? "";
- expect(rule).toContain("background-clip: text");
expect(rule).toMatch(/padding: 0\.35em 0\.12em/);
expect(rule).toMatch(/margin: -0\.35em -0\.12em/);
+ const copy = css.match(/\.thinking-sheen > span::before \{[^}]*\}/)?.[0] ?? "";
+ expect(copy).toMatch(/padding: 0\.35em 0\.12em/);
+ expect(copy).toContain("content: attr(data-text) / \"\"");
+ });
+
+ it("moves the sheen by transform alone, in steps, so a turn does not redraw the page every display frame", () => {
+ for (const name of ["sheen-band", "sheen-letters"]) {
+ const frames = css.match(new RegExp(`@keyframes ${name} \\{([\\s\\S]*?)\\n\\}`))?.[1] ?? "";
+ const properties = [...frames.matchAll(/([a-z-]+):/g)].map((match) => match[1]);
+ expect(new Set(properties)).toEqual(new Set(["transform", "animation-timing-function"]));
+ expect(frames).toMatch(/steps\(\d+/);
+ }
+ });
+
+ it("keeps the phrase's text to one copy for screen readers, selection and tests", () => {
+ render({ label: "Running a command", since: null });
+ const phrase = host.querySelector(".thinking-shimmer")!;
+ expect(phrase.textContent).toBe("Running a command");
+ expect(phrase.querySelector(".thinking-sheen")?.getAttribute("aria-hidden")).toBe("true");
});
});
diff --git a/src/components/TurnPresence.tsx b/src/components/TurnPresence.tsx
index e0ce6e9d62..7d7a071caa 100644
--- a/src/components/TurnPresence.tsx
+++ b/src/components/TurnPresence.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useId, useRef, useState, type ReactNode } from "react";
+import { useEffect, useId, useRef, useState, type CSSProperties, type ReactNode } from "react";
import { ChevronDown } from "lucide-react";
import { cn } from "@/lib/cn";
import { WorkingTimer } from "@/components/WorkingIndicator";
@@ -41,15 +41,14 @@ export function useRotatingPhrase(
return { current, previous };
}
-// 2s matches --animate-shimmer.
+const SHEEN_PERIOD_MS = 2000;
+
function ShimmerPhrase({ text, className }: { text: string; className?: string }) {
- const [delay] = useState(() => `-${Date.now() % 2000}ms`);
+ const [delay] = useState(() => `-${Date.now() % SHEEN_PERIOD_MS}ms`);
return (
- <span
- className={cn("thinking-shimmer animate-shimmer [grid-area:1/1]", className)}
- style={{ animationDelay: `${delay}, 0ms` }}
- >
+ <span className={cn("thinking-shimmer [grid-area:1/1]", className)} style={{ "--sheen-period": `${SHEEN_PERIOD_MS}ms`, "--sheen-delay": delay } as CSSProperties}>
{text}
+ <span aria-hidden="true" className="thinking-sheen"><span data-text={text} /></span>
</span>
);
}
diff --git a/src/components/mascot-clock.test.ts b/src/components/mascot-clock.test.ts
index de5bf952de..f379e6056a 100644
--- a/src/components/mascot-clock.test.ts
+++ b/src/components/mascot-clock.test.ts
@@ -122,6 +122,22 @@ describe("mascot clock", () => {
expect(fake.pendingFrames() + fake.pendingTimers()).toBe(0);
});
+ it("draws a mascot woken for a later frame on that frame, with the others on its grid", () => {
+ const fake = fakeEnvironment();
+ const clock = createMascotClock(fake.env);
+ const drawnAt: number[] = [];
+ const ticket = clock.add((now) => { drawnAt.push(now); return Infinity; });
+ fake.advance(110);
+ drawnAt.length = 0;
+ ticket.wake(nextFrameAt(110, 50));
+ fake.advance(39);
+ expect(drawnAt).toEqual([]);
+ fake.advance(20);
+ expect(drawnAt).toHaveLength(1);
+ expect(drawnAt[0]).toBeGreaterThanOrEqual(150 - 4);
+ expect(drawnAt[0]).toBeLessThan(150 + FULL_FRAME_MS);
+ });
+
it("sleeps on a timer between slow frames instead of polling every display frame", () => {
const fake = fakeEnvironment(120);
const clock = createMascotClock(fake.env);
diff --git a/src/components/mascot-clock.ts b/src/components/mascot-clock.ts
index bba4791bcc..c80422290d 100644
--- a/src/components/mascot-clock.ts
+++ b/src/components/mascot-clock.ts
@@ -5,7 +5,7 @@ import { FRAME_SLACK_MS, FULL_FRAME_MS } from "./mascot-motion";
export type MascotFrame = (now: number) => number;
export interface MascotTicket {
- wake(): void;
+ wake(by?: number): void;
remove(): void;
}
@@ -36,6 +36,8 @@ interface Entry {
onScreen: boolean;
}
+const TIMER_LEAD_MS = 1;
+
export function createMascotClock(env: ClockEnvironment): MascotClock {
const entries = new Set<Entry>();
const byElement = new Map<Element, Entry>();
@@ -61,7 +63,7 @@ export function createMascotClock(env: ClockEnvironment): MascotClock {
timerHandle = env.setTimer(() => {
timerHandle = null;
if (frameHandle === null && !hidden) frameHandle = env.requestFrame(run);
- }, wait - FULL_FRAME_MS / 2);
+ }, wait - TIMER_LEAD_MS);
};
const draw = (entry: Entry, now: number) => {
@@ -112,9 +114,9 @@ export function createMascotClock(env: ClockEnvironment): MascotClock {
}
schedule();
return {
- wake() {
+ wake(by = -Infinity) {
if (!entries.has(entry)) return;
- entry.due = -Infinity;
+ entry.due = Math.min(entry.due, by);
schedule();
},
remove() {
diff --git a/src/components/mascot-motion.test.ts b/src/components/mascot-motion.test.ts
index c5dd5dbe20..93e0721ba2 100644
--- a/src/components/mascot-motion.test.ts
+++ b/src/components/mascot-motion.test.ts
@@ -5,6 +5,7 @@ import {
FULL_FRAME_MS,
GLYPH_EASE_MS,
MOTION,
+ SMALL_MASCOT_PX,
SMOOTH_STEP_PX,
frameIntervalFor,
morphUnitsPerMs,
@@ -47,11 +48,22 @@ describe("mascot cadence", () => {
});
it("runs real motion at full rate", () => {
- expect(delay("working", 36)).toBeCloseTo(FULL_FRAME_MS);
- expect(delay("celebrate", 24)).toBeCloseTo(FULL_FRAME_MS);
- expect(delay("idle", 24, { blinkingOrSpinning: true })).toBeCloseTo(FULL_FRAME_MS);
- expect(delay("spawning", 64, { stateElapsedMs: 100 })).toBeCloseTo(FULL_FRAME_MS);
- expect(delay("spawning", 64, { stateElapsedMs: 5_000 })).toBeGreaterThan(30);
+ expect(delay("working", 96)).toBeCloseTo(FULL_FRAME_MS);
+ expect(delay("celebrate", 96)).toBeCloseTo(FULL_FRAME_MS);
+ expect(delay("idle", 96, { blinkingOrSpinning: true })).toBeCloseTo(FULL_FRAME_MS);
+ expect(delay("spawning", 96, { stateElapsedMs: 100 })).toBeCloseTo(FULL_FRAME_MS);
+ expect(delay("spawning", 96, { stateElapsedMs: 5_000 })).toBeGreaterThan(30);
+ });
+
+ it("draws row, chip and header mascots at most 20 times a second", () => {
+ for (const size of [24, 36, 42, SMALL_MASCOT_PX]) {
+ expect(delay("working", size)).toBeGreaterThan(40);
+ expect(delay("working", size)).toBeLessThanOrEqual(50);
+ expect(delay("celebrate", size)).toBeLessThanOrEqual(50);
+ expect(delay("idle", size, { blinkingOrSpinning: true })).toBeLessThanOrEqual(50);
+ expect(delay("idle", size, { blinkingOrSpinning: true })).toBeGreaterThan(40);
+ }
+ expect(delay("working", SMALL_MASCOT_PX + 1)).toBeCloseTo(FULL_FRAME_MS);
});
it("holds still with no motion strength", () => {
@@ -72,13 +84,13 @@ describe("mascot cadence", () => {
it("draws an alert glyph's fades at full rate and rests between them", () => {
const glyph = EFFECTS.confused!.glyph!;
const shown = glyph.period - glyph.hold;
- const at = (position: number) => delay("confused", 28, { stateElapsedMs: glyph.period * 3 + position });
+ const at = (position: number) => delay("confused", 112, { stateElapsedMs: glyph.period * 3 + position });
expect(at(shown - 400)).toBeGreaterThan(2 * FULL_FRAME_MS);
expect(at(shown - 400)).toBeLessThanOrEqual(400);
expect(at(shown + 10)).toBeCloseTo(FULL_FRAME_MS);
expect(at(shown + GLYPH_EASE_MS + 100)).toBeGreaterThan(2 * FULL_FRAME_MS);
expect(at(glyph.period - 10)).toBeCloseTo(FULL_FRAME_MS);
- expect(delay("confused", 28, { stateElapsedMs: glyph.period * 3 + shown + 10, showGlyphs: false })).toBeGreaterThan(2 * FULL_FRAME_MS);
+ expect(delay("confused", 112, { stateElapsedMs: glyph.period * 3 + shown + 10, showGlyphs: false })).toBeGreaterThan(2 * FULL_FRAME_MS);
});
it("follows an expression change until it settles", () => {
diff --git a/src/components/mascot-motion.ts b/src/components/mascot-motion.ts
index 8ed73b2cfa..9f8ba6a796 100644
--- a/src/components/mascot-motion.ts
+++ b/src/components/mascot-motion.ts
@@ -4,6 +4,8 @@ import type { CursorState, StateEffects } from "./CursorAvatar";
export const FULL_FRAME_MS = 1000 / 60;
export const FRAME_SLACK_MS = 4;
const FRAME_TIERS_MS = [1000 / 20, 1000 / 30, FULL_FRAME_MS];
+export const SMALL_MASCOT_PX = 64;
+const SMALL_MASCOT_FRAME_MS = FRAME_TIERS_MS[0]!;
export const SMOOTH_STEP_PX = 0.5;
export const VISIBLE_PX = 0.2;
const SETTLE_MS = 1400;
@@ -188,7 +190,15 @@ export function nextFrameAt(now: number, interval: number): number {
return (Math.floor((now + FRAME_SLACK_MS) / interval) + 1) * interval;
}
+export function frameFloorMs(sizePx: number): number {
+ return sizePx <= SMALL_MASCOT_PX ? SMALL_MASCOT_FRAME_MS : FULL_FRAME_MS;
+}
+
export function nextMascotFrame(now: number, input: CadenceInput): number {
+ return Math.max(smoothFrameAt(now, input), nextFrameAt(now, frameFloorMs(input.sizePx)));
+}
+
+function smoothFrameAt(now: number, input: CadenceInput): number {
const { motion, effects, stateElapsedMs: elapsed, strength } = input;
const full = nextFrameAt(now, FULL_FRAME_MS);
if (input.blinkingOrSpinning) return full;
diff --git a/src/components/unread-notice.test.ts b/src/components/unread-notice.test.ts
new file mode 100644
index 0000000000..9a47dd597f
--- /dev/null
+++ b/src/components/unread-notice.test.ts
@@ -0,0 +1,65 @@
+// @vitest-environment happy-dom
+import { act, createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { UNREAD_NOTICE_MS, useUnreadNotice } from "./unread-notice";
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+let noticing: boolean | undefined;
+function Row({ unread }: { unread: boolean }) {
+ noticing = useUnreadNotice(unread);
+ return null;
+}
+
+let host: HTMLDivElement;
+let root: Root;
+const show = (unread: boolean) => act(() => root.render(createElement(Row, { unread })));
+const wait = (ms: number) => act(() => void vi.advanceTimersByTime(ms));
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ host = document.createElement("div");
+ root = createRoot(host);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ vi.useRealTimers();
+});
+
+describe("an unread bot's notice", () => {
+ it("plays when news arrives, then holds still while the bot stays unread", () => {
+ show(false);
+ expect(noticing).toBe(false);
+ show(true);
+ expect(noticing).toBe(true);
+ wait(UNREAD_NOTICE_MS - 1);
+ expect(noticing).toBe(true);
+ wait(1);
+ expect(noticing).toBe(false);
+ show(true);
+ wait(60_000);
+ expect(noticing).toBe(false);
+ });
+
+ it("holds still for a bot that was already unread when its row appeared", () => {
+ show(true);
+ expect(noticing).toBe(false);
+ wait(UNREAD_NOTICE_MS);
+ expect(noticing).toBe(false);
+ });
+
+ it("stops when the bot is read and plays again for the next news", () => {
+ show(false);
+ show(true);
+ wait(1_000);
+ show(false);
+ expect(noticing).toBe(false);
+ show(true);
+ expect(noticing).toBe(true);
+ wait(UNREAD_NOTICE_MS);
+ expect(noticing).toBe(false);
+ });
+});
diff --git a/src/components/unread-notice.ts b/src/components/unread-notice.ts
new file mode 100644
index 0000000000..9aff535ee6
--- /dev/null
+++ b/src/components/unread-notice.ts
@@ -0,0 +1,29 @@
+import { useEffect, useState } from "react";
+
+import { botShowsUnread } from "@/lib/bot-unread";
+
+import { EFFECTS } from "./CursorAvatar";
+
+export const UNREAD_NOTICE_MS = 2 * EFFECTS.notifying!.glyph!.period;
+
+/** True for UNREAD_NOTICE_MS after `unread` turns on while the row is shown; a bot unread when its row appears holds still. */
+export function useUnreadNotice(unread: boolean): boolean {
+ const [seen, setSeen] = useState(unread);
+ const [noticing, setNoticing] = useState(false);
+ if (seen !== unread) {
+ setSeen(unread);
+ setNoticing(unread);
+ }
+ useEffect(() => {
+ if (!noticing) return;
+ const timer = setTimeout(() => setNoticing(false), UNREAD_NOTICE_MS);
+ return () => clearTimeout(timer);
+ }, [noticing]);
+ return noticing;
+}
+
+/** Whether `bot` shows unread, and whether its mascot is still playing the notice for it. */
+export function useBotUnread(bot: Parameters<typeof botShowsUnread>[0]): { unread: boolean; noticing: boolean } {
+ const unread = botShowsUnread(bot);
+ return { unread, noticing: useUnreadNotice(unread) };
+}
diff --git a/src/lib/on-screen.ts b/src/lib/on-screen.ts
new file mode 100644
index 0000000000..6f14de0e63
--- /dev/null
+++ b/src/lib/on-screen.ts
@@ -0,0 +1,28 @@
+import { useEffect, useState, type RefObject } from "react";
+
+const watchers = new Map<Element, (onScreen: boolean) => void>();
+let observer: IntersectionObserver | undefined;
+
+function watch(element: Element, onChange: (onScreen: boolean) => void): () => void {
+ observer ??= new IntersectionObserver((entries) => {
+ for (const entry of entries) watchers.get(entry.target)?.(entry.isIntersecting);
+ });
+ watchers.set(element, onChange);
+ observer.observe(element);
+ return () => {
+ watchers.delete(element);
+ observer?.unobserve(element);
+ };
+}
+
+/** Whether the element is on screen: false until the browser says so, true where it cannot tell. */
+export function useOnScreen(ref: RefObject<Element | null>): boolean {
+ const [onScreen, setOnScreen] = useState(false);
+ useEffect(() => {
+ const element = ref.current;
+ if (!element) return;
+ if (typeof IntersectionObserver === "undefined") return setOnScreen(true);
+ return watch(element, setOnScreen);
+ }, [ref]);
+ return onScreen;
+}
diff --git a/src/styles.css b/src/styles.css
index de83531d39..ead060cc89 100644
--- a/src/styles.css
+++ b/src/styles.css
@@ -118,7 +118,6 @@
--animate-pop-out: pop-out 0.2s cubic-bezier(0.22, 1, 0.36, 1) forwards;
--animate-caret: caret-blink 1s step-end infinite;
--animate-msg-in: msg-in 0.18s cubic-bezier(0.22, 1, 0.36, 1);
- --animate-shimmer: shimmer 2s linear infinite;
--animate-status-pulse: status-pulse 1.6s steps(2, jump-none) infinite;
/* onboarding: a block of copy or a row arriving in a beat; `.stagger`
spaces siblings out. Rare, first-time motion, so it may run past the
@@ -1916,10 +1915,17 @@ html[data-cloud-intent-morph] [data-tour="composer"] { view-transition-name: clo
@keyframes progress-fill {
from { clip-path: inset(0 100% 0 0 round 999px); }
}
-/* "Thinking…" label sheen while the model reasons */
-@keyframes shimmer {
- from { background-position: 200% 50%; }
- to { background-position: -200% 50%; }
+/* "Thinking…" label sheen while the model reasons. The band crosses the phrase while the brighter copy inside it
+ crosses back, so the letters hold still and only the light moves. It moves by transform, in a dozen steps, and
+ rests between sweeps: a smooth sweep (or a background-position one) draws the whole page every display frame for
+ as long as a turn runs. */
+@keyframes sheen-band {
+ from { transform: translateX(-70%); animation-timing-function: steps(12, jump-none); }
+ 35%, to { transform: translateX(70%); }
+}
+@keyframes sheen-letters {
+ from { transform: translateX(70%); animation-timing-function: steps(12, jump-none); }
+ 35%, to { transform: translateX(-70%); }
}
@keyframes reduced-loader-pulse {
0%, 100% { opacity: 0.45; }
@@ -1934,28 +1940,47 @@ html[data-cloud-intent-morph] [data-tour="composer"] { view-transition-name: clo
60% { opacity: 0.25; }
}
.thinking-shimmer {
- background: linear-gradient(90deg, var(--color-ink-secondary) 40%, var(--color-ink) 50%, var(--color-ink-secondary) 60%);
- background-size: 200% 100%;
- -webkit-background-clip: text;
- background-clip: text;
- color: transparent;
- /* background-clip:text only paints glyphs inside the background box. A
- tight line box (leading-none) is shorter than ascenders, descenders and
- arabic marks, so they were cut. Pad the box past the glyphs and pull the
- margins back so the layout doesn't move. */
+ position: relative;
+ color: var(--color-ink-secondary);
+ /* A truncated phrase clips to its box, and a tight line box (leading-none)
+ is shorter than ascenders, descenders and arabic marks. Pad the box past
+ the glyphs and pull the margins back so the layout doesn't move. */
padding: 0.35em 0.12em;
margin: -0.35em -0.12em;
}
-/* Simple mode's typing row is quieter: the shimmer runs from tertiary ink up to secondary. */
-.turn-phrase-quiet .thinking-shimmer {
- background-image: linear-gradient(90deg, var(--color-ink-tertiary) 40%, var(--color-ink-secondary) 50%, var(--color-ink-tertiary) 60%);
+.thinking-sheen {
+ position: absolute;
+ inset: 0;
+ overflow: hidden;
+ pointer-events: none;
+ user-select: none;
+}
+.thinking-sheen > span {
+ position: absolute;
+ inset: 0;
+ -webkit-mask-image: linear-gradient(90deg, transparent 30%, #000 50%, transparent 70%);
+ mask-image: linear-gradient(90deg, transparent 30%, #000 50%, transparent 70%);
+ animation: sheen-band var(--sheen-period) linear var(--sheen-delay) infinite;
+}
+.thinking-sheen > span::before {
+ content: attr(data-text) / "";
+ position: absolute;
+ inset: 0;
+ padding: 0.35em 0.12em;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ color: var(--color-ink);
+ animation: sheen-letters var(--sheen-period) linear var(--sheen-delay) infinite;
}
+/* Simple mode's typing row is quieter: the sheen runs from tertiary ink up to secondary. */
+.turn-phrase-quiet .thinking-shimmer { color: var(--color-ink-tertiary); }
+.turn-phrase-quiet .thinking-sheen > span::before { color: var(--color-ink-secondary); }
/* rotating presence phrase: the new phrase fades in where the old one was;
only one is ever drawn */
@keyframes turn-phrase-in {
from { opacity: 0; }
}
-.turn-phrase-in { animation: shimmer 2s linear infinite, turn-phrase-in 0.32s ease-out both; }
+.turn-phrase-in { animation: turn-phrase-in 0.32s ease-out both; }
.turn-now-toggle {
display: flex;
min-width: 0;
@@ -1996,10 +2021,9 @@ html[data-cloud-intent-morph] [data-tour="composer"] { view-transition-name: clo
@media (prefers-reduced-motion: reduce) {
.turn-now-card { animation: none; }
.turn-now-chevron { transition: none; }
- .animate-caret, .animate-msg-in, .animate-shimmer, .animate-pop-in, .animate-pop-out { animation: none; }
+ .animate-caret, .animate-msg-in, .animate-pop-in, .animate-pop-out { animation: none; }
.animate-status-pulse { animation: none; opacity: 0.6; }
- .thinking-shimmer { background: none; color: var(--color-ink-secondary); }
- .turn-phrase-quiet .thinking-shimmer { background: none; color: var(--color-ink-tertiary); }
+ .thinking-sheen { display: none; }
.turn-phrase-in { animation: none; }
.turn-mascot-in, .turn-mascot-out, .turn-answer { animation: none; }
.reply-bubble-in { animation: none; }