Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Chat switch tests: draw the rows above the newest ones when the test paints (#6632)
Milind Soni010206c182c6
diff --git a/src/components/ChatView.switch.test.ts b/src/components/ChatView.switch.test.tsindex 4855fbb9ca..783425aad0 100644--- a/src/components/ChatView.switch.test.ts+++ b/src/components/ChatView.switch.test.ts@@ -1,7 +1,7 @@// @vitest-environment happy-dom// The real provider, two long chats: switching between them draws the newest rows first and mounts no hover-only part.import { commitMark, commitsSince, countBy, renderMark, renderedSince } from "@/testing/render-counts";-import { createElement } from "react";+import { act, createElement } from "react";import { flushSync } from "react-dom";import { createRoot, type Root } from "react-dom/client";import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";@@ -13,6 +13,15 @@ vi.mock("./DesktopCapabilities", async (importOriginal) => ({useDesktopCapabilities: () => ({ capabilities: { dictation: { available: false }, host: { packaged: true, platform: "other" }, localComputer: { available: false } }, ready: true }),}));vi.mock("@/lib/analytics", () => ({ track: vi.fn() }));+// The frame after the click's paint, run by the test: rows queued for it are drawn exactly when `paint()` says.+const painted = vi.hoisted(() => [] as (() => void)[]);+vi.mock("@/lib/after-paint", () => ({ afterPaint: (callback: () => void) => {+ painted.push(callback);+ return () => {+ const at = painted.indexOf(callback);+ if (at >= 0) painted.splice(at, 1);+ };+} }));vi.mock("@/lib/cloud-guest", async (importOriginal) => ({ ...await importOriginal<typeof import("@/lib/cloud-guest")>(), useReactor: () => "user" }));vi.mock("@/lib/interface-mode", () => ({ useAdvancedMode: () => true, setAdvancedMode: vi.fn() }));@@ -80,6 +89,16 @@ const settle = async () => { for (let i = 0; i < 6; i++) await task(); };const frames = async () => { for (let i = 0; i < 4; i++) { await new Promise((resolve) => requestAnimationFrame(resolve)); await settle(); } };const stream = () => FixtureEventSource.opened[0]!;const rows = () => document.querySelectorAll('[role="log"] [data-mid]');+/** The paint happened: what waited for it runs, and act draws the transition it starts before returning. */+async function paint() {+ const flag = globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean };+ flag.IS_REACT_ACT_ENVIRONMENT = true;+ try {+ await act(async () => { for (const run of painted.splice(0)) run(); });+ } finally {+ flag.IS_REACT_ACT_ENVIRONMENT = false;+ }+}/** No layout here: the scroller reads as a 900px view over rows 120px tall each. */function layout() {@@ -93,6 +112,7 @@ async function switchTo(id: string) {const mark = renderMark(), commits = commitMark();flushSync(() => dispatch({ type: "select", id }));const first = { mounted: renderedSince(mark).filter((entry) => entry.mounted).length, rows: rows().length, ids: [...rows()].map((row) => row.getAttribute("data-mid")) };+ await paint();await frames();const mounted = renderedSince(mark).filter((entry) => entry.mounted);const again = renderedSince(mark).filter((entry) => !entry.mounted && entry.row !== null);diff --git a/src/hooks/use-transcript-viewport.test.ts b/src/hooks/use-transcript-viewport.test.tsindex 50bc85c7ca..a31ea2cc40 100644--- a/src/hooks/use-transcript-viewport.test.ts+++ b/src/hooks/use-transcript-viewport.test.ts@@ -162,9 +162,19 @@ function mount(initial: Partial<Props> = {}) {react.render(draw, commit);flushFrames();},+ unmount,};}+/** Runs every committed effect's cleanup, as an unmount does. */+function unmount() {+ for (const slot of react.runtime.slots) {+ const cleanup = (slot as { cleanup?: unknown } | undefined)?.cleanup;+ if (typeof cleanup === "function") cleanup();+ }+ react.runtime.slots = [];+}+beforeEach(() => {react.runtime.slots = [];scroller = new Scroller();@@ -200,7 +210,10 @@ beforeEach(() => {});vi.stubGlobal("HTMLTextAreaElement", class {});vi.stubGlobal("HTMLInputElement", class {});- return () => vi.unstubAllGlobals();+ return () => {+ unmount();+ vi.unstubAllGlobals();+ };});const press = (key: string, target: unknown = {}) => {@@ -812,3 +825,46 @@ describe("following a reply and coming back to a conversation", () => {}});});++describe("a switch draws the newest rows first", () => {+ it("draws from the twentieth newest row, and the rest once the frame is painted", () => {+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });+ try {+ const view = mount({ messages: rows(80) });+ view.rerender({ threadId: "other", messages: rows(80, 500) });+ expect(view.current.drawFrom).toBe("m560");+ view.act(() => {});+ expect(view.current.drawFrom, "the frame callback only queues the fill").toBe("m560");+ vi.advanceTimersByTime(0);+ view.rerender({});+ expect(view.current.drawFrom).toBeUndefined();+ expect(scroller.scrollTop, "still at the end").toBeGreaterThanOrEqual(scroller.bottom);+ } finally {+ vi.useRealTimers();+ }+ });++ it("leaves no frame or timer behind when the chat goes away before the paint", () => {+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });+ try {+ const view = mount({ messages: rows(80) });+ view.rerender({ threadId: "other", messages: rows(80, 500) });+ expect(view.current.drawFrom).toBe("m560");+ expect(vi.getTimerCount()).toBeGreaterThan(0);+ view.unmount();+ expect(vi.getTimerCount()).toBe(0);+ expect(frames).toEqual([]);+ } finally {+ vi.useRealTimers();+ }+ });++ it("draws a short chat, or a jump to an older message, at once", () => {+ const view = mount({ messages: rows(80) });+ view.rerender({ threadId: "other", messages: rows(15, 500) });+ expect(view.current.drawFrom).toBeUndefined();+ store.state.focusMessage = { threadId: "third", messageId: "m700", nonce: 7, consumed: false };+ view.rerender({ threadId: "third", messages: rows(80, 700) });+ expect(view.current.drawFrom).toBeUndefined();+ });+});diff --git a/src/hooks/use-transcript-viewport.ts b/src/hooks/use-transcript-viewport.tsindex 8ef8c91671..1ccd74b34c 100644--- a/src/hooks/use-transcript-viewport.ts+++ b/src/hooks/use-transcript-viewport.ts@@ -12,6 +12,7 @@ import {type WheelEvent,} from "react";import { BOTTOM_FOLLOW_THRESHOLD, followBottomGrowth, useBottomFollowResize } from "@/lib/bottom-follow";+import { afterPaint } from "@/lib/after-paint";import { useFocusMessage } from "@/lib/focus-message";import {TRANSCRIPT_WINDOW_MAX,@@ -176,8 +177,9 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({drawFromRef.current = drawFrom;const filling = useRef<{ key: string; height: number } | null>(null);const fillNow = useCallback(() => {- filling.current = { key: followNow.current.key, height: scrollRef.current?.scrollHeight ?? 0 };- setFirstFrame(null);+ const key = followNow.current.key;+ filling.current = { key, height: scrollRef.current?.scrollHeight ?? 0 };+ setFirstFrame((staged) => staged?.key === key ? null : staged);}, []);useLayoutEffect(() => {const el = scrollRef.current, filled = filling.current;@@ -192,22 +194,7 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({el.scrollTop = followRef.current ? el.scrollHeight : el.scrollTop + el.scrollHeight - filled.height;lastTop.current = el.scrollTop;}, [drawFrom, fillNow, transcriptKey]);- useEffect(() => {- if (!drawFrom) return;- let timer: ReturnType<typeof setTimeout> | undefined;- const fill = () => {- clearTimeout(timer);- cancelAnimationFrame(frame);- timer = setTimeout(() => startTransition(fillNow), 0);- };- // A frame callback runs just before the paint; the task it queues runs after it. A hidden window gets no frames.- const frame = requestAnimationFrame(fill);- timer = setTimeout(fill, 100);- return () => {- cancelAnimationFrame(frame);- clearTimeout(timer);- };- }, [drawFrom, fillNow]);+ useEffect(() => drawFrom ? afterPaint(() => startTransition(fillNow)) : undefined, [drawFrom, fillNow]);const windowRef = useRef(transcriptWindow);windowRef.current = transcriptWindow;restingCardId.current = windowedMessages[0] && windowedMessages[0] !== messages[startIndex] ? windowedMessages[0].id : undefined;diff --git a/src/lib/after-paint.ts b/src/lib/after-paint.tsnew file mode 100644index 0000000000..69b5565283--- /dev/null+++ b/src/lib/after-paint.ts@@ -0,0 +1,18 @@+/**+ * Runs `callback` in a task after the next paint: a frame callback runs just before the paint and the task it queues runs+ * after it. A hidden window gets no frames, so `fallbackMs` stands in. Returns the cancel.+ */+export function afterPaint(callback: () => void, fallbackMs = 100): () => void {+ let timer: ReturnType<typeof setTimeout> | undefined;+ const queue = () => {+ clearTimeout(timer);+ cancelAnimationFrame(frame);+ timer = setTimeout(callback, 0);+ };+ const frame = requestAnimationFrame(queue);+ timer = setTimeout(queue, fallbackMs);+ return () => {+ cancelAnimationFrame(frame);+ clearTimeout(timer);+ };+}