Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: mount sidebar Recents a page at a time so long chat histories stay fast (#13165)

oobabooga6ded031092e3
diff --git a/.github/workflows/studio-frontend-ci.yml b/.github/workflows/studio-frontend-ci.yml
index 1f09e3ad01d..e8033811bd9 100644
--- a/.github/workflows/studio-frontend-ci.yml
+++ b/.github/workflows/studio-frontend-ci.yml
@@ -36,6 +36,7 @@ on:
- 'tests/studio/playwright_code_block_flicker.py'
- 'tests/studio/playwright_link_definition_probe.py'
- 'tests/studio/playwright_user_message_time.py'
+ - 'tests/studio/playwright_progressive_rows.py'
- 'tests/studio/_code_block_flicker_analysis.py'
- 'tests/studio/test_code_block_flicker_contract.py'
# Shared lifecycle helpers, and the contract tests that keep verdicts from going unread.
@@ -76,6 +77,7 @@ on:
- 'tests/studio/playwright_code_block_flicker.py'
- 'tests/studio/playwright_link_definition_probe.py'
- 'tests/studio/playwright_user_message_time.py'
+ - 'tests/studio/playwright_progressive_rows.py'
- 'tests/studio/_code_block_flicker_analysis.py'
- 'tests/studio/test_code_block_flicker_contract.py'
- 'tests/studio/_playwright_robust.py'
@@ -494,6 +496,12 @@ jobs:
timeout-minutes: 5
run: python3 tests/studio/playwright_user_message_time.py
+ # the node suite runs no effects, so only this browser check covers the observer, re-arming, and cleanup.
+ - name: Browser check for paged sidebar lists
+ working-directory: ${{ github.workspace }}
+ timeout-minutes: 5
+ run: python3 tests/studio/playwright_progressive_rows.py
+
# Two small sizes and one repetition on Chromium: enough to prove the fixture still
# renders every kind of content it claims to and that the curve still rises, which is all
# a PR gate can afford. The measurement this harness exists for is the three-engine,
diff --git a/studio/frontend/src/components/app-sidebar.tsx b/studio/frontend/src/components/app-sidebar.tsx
index 1a092b53166..e57eaebdc46 100644
--- a/studio/frontend/src/components/app-sidebar.tsx
+++ b/studio/frontend/src/components/app-sidebar.tsx
@@ -47,6 +47,7 @@ import {
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { NonModalDropdownMenu } from "@/components/ui/non-modal-dropdown-menu";
+import { ProgressiveRows } from "@/components/progressive-rows";
import {
HELP_GROUPS,
HELP_ITEMS,
@@ -354,30 +355,26 @@ type NavRowDef = {
children?: ReactNode;
};
-// An expanded project shows this many recent chats before "Show more".
-// Row kebab with centred dots: Hugeicons draws them half a unit low.
+// row kebab with centred dots: Hugeicons draws them half a unit low.
const MoreVerticalCenteredIcon = MoreVerticalIcon.map(([tag, attrs]) => [
tag,
{ ...attrs, transform: "translate(0 -0.5)" },
]) as unknown as IconSvgElement;
const PROJECT_CHAT_LIMIT = 4;
-// And the Projects section shows this many folders before its own "Show more".
const SIDEBAR_PROJECT_LIMIT = 5;
+const RECENTS_PAGE_SIZE = 50;
-// The shared radio item ticks on the right; these read as settings, so tick first.
-// A sidebar or account menu's side and top padding (.sidebar-row-menu in index.css, before the
-// UI scale), the 2px margin every menu row keeps, and the gap a submenu keeps from its menu.
+// shared radio items tick on the right; these read as settings, so tick first.
+// sidebar and account menu padding precedes UI scaling; rows keep 2px margins and submenu gaps.
const SIDEBAR_MENU_PAD_X = 8;
const SIDEBAR_MENU_PAD_Y = 6;
const MENU_ROW_MARGIN_PX = 2;
-// px-2.5 and the 1px transparent border the account menu draws its edge with.
+// account padding combines px-2.5 with its 1px transparent border.
const ACCOUNT_MENU_PAD_X = 11;
const SUBMENU_GAP_PX = 6;
-// Whether cmd or ctrl adds a row to the selection. This is the user's own keyboard, not the host
-// Unsloth runs on, so it reads the browser rather than the platform store: a Mac browser on a Linux
-// host still uses cmd. Ctrl is left alone on macOS, where ctrl click is the right click chord.
+// read the browser platform, not the host; macOS uses cmd because ctrl-click opens a context menu.
const SELECT_WITH_META =
typeof navigator !== "undefined" &&
/mac/i.test(navigator.platform || navigator.userAgent);
@@ -5828,8 +5825,7 @@ export function AppSidebar() {
})}
</SidebarGroupLabel>
<CollapsibleContent>
- {/* The section as a whole takes the drop, so a chat dragged out of a folder has
- somewhere to land even when Recents is empty. */}
+ {/* Recents accepts drops so chats can leave folders when empty. */}
<SidebarGroupContent
className={cn(
unrailedRowPadding,
@@ -5839,33 +5835,37 @@ export function AppSidebar() {
{...dnd.dropZoneProps({ section: "recents" })}
>
<SidebarMenu>
- {sortedRecentChatItems.map((item) =>
- renderChatSidebarItem(item, "recent", {
- scope: RECENTS_ORDER_SCOPE,
- ids: recentRowIds,
- section: "recents",
- sort: { value: chatSort, set: setChatSort },
- }),
- )}
- {sortedRecentChatItems.length > 0 && (
- // The end of the list, as somewhere to aim; see Pinned's. The empty sidebar
- // below it aims here too (use-sidebar-drag.ts).
- <SidebarMenuItem
- aria-hidden
- className={cn(
- "relative z-[1] h-[calc(8px*var(--ui-space-scale,1))]",
- dropCueClass(SIDEBAR_TAIL_SCOPE, "recents"),
- )}
- {...dnd.dropZoneProps({
+ {/* only Recents pages unfiled chats; mount its end drop after the last row. */}
+ <ProgressiveRows
+ items={sortedRecentChatItems}
+ pageSize={RECENTS_PAGE_SIZE}
+ renderItem={(item) =>
+ renderChatSidebarItem(item, "recent", {
+ scope: RECENTS_ORDER_SCOPE,
+ ids: recentRowIds,
section: "recents",
- blockEnd: { scope: SIDEBAR_TAIL_SCOPE, id: "recents" },
- })}
- />
- )}
+ sort: { value: chatSort, set: setChatSort },
+ })
+ }
+ end={
+ sortedRecentChatItems.length > 0 && (
+ // the end drop matches Pinned and receives empty-sidebar drops.
+ <SidebarMenuItem
+ aria-hidden
+ className={cn(
+ "relative z-[1] h-[calc(8px*var(--ui-space-scale,1))]",
+ dropCueClass(SIDEBAR_TAIL_SCOPE, "recents"),
+ )}
+ {...dnd.dropZoneProps({
+ section: "recents",
+ blockEnd: { scope: SIDEBAR_TAIL_SCOPE, id: "recents" },
+ })}
+ />
+ )
+ }
+ />
</SidebarMenu>
- {/* "No chats yet" only when there is truly no history:
- project-scoped and archived threads leave Recents empty
- but still count as existing chats. */}
+ {/* existing project or archived threads can leave Recents empty. */}
{chatItemsLoaded &&
allChatItems.length === 0 &&
archivedChatItems.length === 0 && (
diff --git a/studio/frontend/src/components/progressive-rows.tsx b/studio/frontend/src/components/progressive-rows.tsx
new file mode 100644
index 00000000000..324190f2db6
--- /dev/null
+++ b/studio/frontend/src/components/progressive-rows.tsx
@@ -0,0 +1,60 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { memo, type ReactNode, useEffect, useRef, useState } from "react";
+
+/** mounts the next page this far below the sidebar's visible edge. */
+const PRELOAD_PX = 800;
+
+/** preserves mounted rows when the list grows because `render` remains stable. */
+const Row = memo(function Row<T>({
+ item,
+ render,
+}: { item: T; render: (item: T) => ReactNode }) {
+ return render(item);
+}) as <T>(props: { item: T; render: (item: T) => ReactNode }) => ReactNode;
+
+/** pages mounted rows to bound Radix keydown listeners while callers retain the full list state. */
+export function ProgressiveRows<T extends { id: string }>({
+ items,
+ pageSize,
+ renderItem,
+ end,
+}: {
+ items: readonly T[];
+ pageSize: number;
+ renderItem: (item: T) => ReactNode;
+ end?: ReactNode;
+}) {
+ const [limit, setLimit] = useState(pageSize);
+ const sentinelRef = useRef<HTMLLIElement>(null);
+ const hasMore = items.length > limit;
+ // re-observe because IntersectionObserver does not repeat while the sentinel stays intersecting
+ // biome-ignore lint/correctness/useExhaustiveDependencies: `limit` is the re-observe trigger
+ useEffect(() => {
+ const sentinel = sentinelRef.current;
+ if (!hasMore || !sentinel) return;
+ const observer = new IntersectionObserver(
+ (entries) => {
+ if (entries.some((entry) => entry.isIntersecting)) {
+ setLimit((count) => count + pageSize);
+ }
+ },
+ {
+ // use the sidebar scroller because the viewport sees its clipped sentinel only when visible
+ root: sentinel.closest<HTMLElement>("[data-sidebar='content']"),
+ rootMargin: `0px 0px ${PRELOAD_PX}px 0px`,
+ },
+ );
+ observer.observe(sentinel);
+ return () => observer.disconnect();
+ }, [hasMore, limit, pageSize]);
+ return (
+ <>
+ {items.slice(0, limit).map((item) => (
+ <Row key={item.id} item={item} render={renderItem} />
+ ))}
+ {hasMore ? <li ref={sentinelRef} aria-hidden className="h-px" /> : end}
+ </>
+ );
+}
diff --git a/studio/frontend/tests/fixtures/progressive-rows/index.html b/studio/frontend/tests/fixtures/progressive-rows/index.html
new file mode 100644
index 00000000000..46ac66aa500
--- /dev/null
+++ b/studio/frontend/tests/fixtures/progressive-rows/index.html
@@ -0,0 +1,13 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <script src="/crypto-boot.js"></script>
+ <title>Progressive rows regression</title>
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="/main.tsx"></script>
+ </body>
+</html>
diff --git a/studio/frontend/tests/fixtures/progressive-rows/main.tsx b/studio/frontend/tests/fixtures/progressive-rows/main.tsx
new file mode 100644
index 00000000000..e73e56d352a
--- /dev/null
+++ b/studio/frontend/tests/fixtures/progressive-rows/main.tsx
@@ -0,0 +1,69 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// matches AppSidebar's scroller root and unstable renderItem identity.
+import { useEffect, useState } from "react";
+import { createRoot } from "react-dom/client";
+import { ProgressiveRows } from "@/components/progressive-rows";
+import "./styles.css";
+
+const params = new URLSearchParams(location.search);
+const height = Number(params.get("height") ?? 600);
+
+type Item = { id: string };
+const makeItems = (count: number): Item[] =>
+ Array.from({ length: count }, (_, i) => ({ id: `chat-${i}` }));
+
+declare global {
+ interface Window {
+ rowRenders: number;
+ fixture: {
+ setCount: (count: number) => void;
+ setMounted: (mounted: boolean) => void;
+ // uses new item objects with stable ids, matching a chat-list refetch.
+ refresh: () => void;
+ };
+ }
+}
+window.rowRenders = 0;
+// tracks renderItem calls to detect unnecessary row redraws.
+const countRowRender = () => {
+ window.rowRenders += 1;
+};
+
+function App() {
+ const [items, setItems] = useState(() =>
+ makeItems(Number(params.get("count") ?? 1000)),
+ );
+ const [mounted, setMounted] = useState(true);
+ useEffect(() => {
+ window.fixture = {
+ setCount: (count) => setItems(makeItems(count)),
+ setMounted,
+ refresh: () => setItems((current) => current.map(({ id }) => ({ id }))),
+ };
+ }, []);
+ return (
+ <div data-sidebar="content" style={{ height, overflowY: "auto" }}>
+ {mounted ? (
+ <ul style={{ margin: 0, padding: 0, listStyle: "none" }}>
+ <ProgressiveRows
+ items={items}
+ pageSize={50}
+ renderItem={(item) => {
+ countRowRender();
+ return (
+ <li key={item.id} data-row={item.id} style={{ height: 30 }}>
+ {item.id}
+ </li>
+ );
+ }}
+ end={<li data-end="">end</li>}
+ />
+ </ul>
+ ) : null}
+ </div>
+ );
+}
+
+createRoot(document.getElementById("root") as HTMLElement).render(<App />);
diff --git a/studio/frontend/tests/fixtures/progressive-rows/styles.css b/studio/frontend/tests/fixtures/progressive-rows/styles.css
new file mode 100644
index 00000000000..816f80ef368
--- /dev/null
+++ b/studio/frontend/tests/fixtures/progressive-rows/styles.css
@@ -0,0 +1,5 @@
+/* SPDX-License-Identifier: AGPL-3.0-only */
+/* Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0 */
+
+@import "tailwindcss";
+@source "../../../src/components/progressive-rows.tsx";
diff --git a/studio/frontend/tests/fixtures/progressive-rows/vite.config.ts b/studio/frontend/tests/fixtures/progressive-rows/vite.config.ts
new file mode 100644
index 00000000000..db69f19f2e2
--- /dev/null
+++ b/studio/frontend/tests/fixtures/progressive-rows/vite.config.ts
@@ -0,0 +1,39 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// ProgressiveRows runs in a sidebar-shaped scroller without a backend.
+
+// biome-ignore lint/correctness/noNodejsModules: Vite configs execute in Node.
+import path from "node:path";
+import tailwindcss from "@tailwindcss/vite";
+import react from "@vitejs/plugin-react";
+import { defineConfig } from "vite";
+
+const frontendRoot = path.resolve(__dirname, "../../..");
+const sourceFrontend = path.resolve(
+ process.env.PW_SOURCE_FRONTEND_DIR ?? frontendRoot,
+);
+
+// biome-ignore lint/style/noDefaultExport: Vite loads its config as a default export.
+export default defineConfig({
+ root: __dirname,
+ publicDir: path.resolve(frontendRoot, "public"),
+ plugins: [react(), tailwindcss()],
+ css: { postcss: { plugins: [] } },
+ server: {
+ host: "127.0.0.1",
+ fs: { allow: [frontendRoot, sourceFrontend] },
+ },
+ resolve: {
+ // dedupe React because the negative-control worktree has its own dependency tree.
+ dedupe: ["react", "react-dom"],
+ alias: {
+ "@": path.resolve(sourceFrontend, "src"),
+ "@dagrejs/dagre": path.resolve(
+ frontendRoot,
+ "node_modules/@dagrejs/dagre/dist/dagre.cjs.js",
+ ),
+ },
+ },
+ optimizeDeps: { include: ["@dagrejs/dagre", "@dagrejs/graphlib"] },
+});
diff --git a/studio/frontend/tests/sidebar-recents-paging.test.ts b/studio/frontend/tests/sidebar-recents-paging.test.ts
new file mode 100644
index 00000000000..5d3da62ea35
--- /dev/null
+++ b/studio/frontend/tests/sidebar-recents-paging.test.ts
@@ -0,0 +1,110 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+import * as React from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import * as jsxRuntime from "react/jsx-runtime";
+import ts from "typescript";
+import type * as ProgressiveRowsModule from "../src/components/progressive-rows.tsx";
+import { readSrc } from "./helpers/kit.ts";
+import { loadWithStubs } from "./helpers/module-stubs.ts";
+import { openingTag } from "./helpers/tsx-ast.ts";
+
+const { ProgressiveRows } = loadWithStubs<typeof ProgressiveRowsModule>(
+ new URL("../src/components/progressive-rows.tsx", import.meta.url),
+ { react: React, "react/jsx-runtime": jsxRuntime },
+);
+
+function render(count: number, pageSize: number): string {
+ const items = Array.from({ length: count }, (_, i) => ({ id: `chat-${i}` }));
+ return renderToStaticMarkup(
+ React.createElement(
+ "ul",
+ null,
+ React.createElement(ProgressiveRows<{ id: string }>, {
+ items,
+ pageSize,
+ renderItem: ({ id }) => React.createElement("li", { "data-row": id }),
+ end: React.createElement("li", { "data-end": "" }),
+ }),
+ ),
+ );
+}
+
+test("a list longer than a page mounts one page, then the sentinel, and no end", () => {
+ const html = render(5000, 50);
+ assert.equal(html.match(/data-row=/g)?.length, 50);
+ assert.match(html, /data-row="chat-49"/);
+ assert.doesNotMatch(html, /data-row="chat-50"/);
+ assert.doesNotMatch(html, /data-end/);
+ const last = html.slice(html.lastIndexOf("<li"));
+ assert.match(last, /^<li aria-hidden="true"/);
+ assert.doesNotMatch(last, /data-row/);
+});
+
+test("a list that fits in a page mounts every row and then the end", () => {
+ for (const count of [0, 1, 50]) {
+ const html = render(count, 50);
+ assert.equal(html.match(/data-row=/g)?.length ?? 0, count);
+ assert.match(html, /<li data-end=""><\/li><\/ul>$/);
+ }
+});
+
+function attrText(
+ tag: ts.JsxOpeningLikeElement,
+ name: string,
+): string | undefined {
+ const prop = tag.attributes.properties.find(
+ (p): p is ts.JsxAttribute =>
+ ts.isJsxAttribute(p) && p.name.getText() === name,
+ );
+ return prop?.initializer?.getText();
+}
+
+function isRecentsTail(node: ts.Node): boolean {
+ if (!ts.isObjectLiteralExpression(node)) return false;
+ const value = (name: string) =>
+ node.properties
+ .find(
+ (p): p is ts.PropertyAssignment =>
+ ts.isPropertyAssignment(p) && p.name.getText() === name,
+ )
+ ?.initializer.getText();
+ return value("scope") === "SIDEBAR_TAIL_SCOPE" && value("id") === '"recents"';
+}
+
+test("Recents pages its rows and draws its end strip only after the last one", () => {
+ const path = "components/app-sidebar.tsx";
+ const file = ts.createSourceFile(
+ path,
+ readSrc(path),
+ ts.ScriptTarget.Latest,
+ true,
+ ts.ScriptKind.TSX,
+ );
+ let recents: ts.JsxOpeningLikeElement | undefined;
+ const tails: ts.Node[] = [];
+ const visit = (node: ts.Node) => {
+ const tag = openingTag(node);
+ if (
+ tag?.tagName.getText() === "ProgressiveRows" &&
+ attrText(tag, "items") === "{sortedRecentChatItems}"
+ ) {
+ recents = tag;
+ }
+ if (isRecentsTail(node)) tails.push(node);
+ ts.forEachChild(node, visit);
+ };
+ visit(file);
+ assert.ok(recents, "Recents is not a ProgressiveRows");
+ assert.match(attrText(recents, "renderItem") ?? "", /RECENTS_ORDER_SCOPE/);
+ // sidebar-drag.ts drops the strip after Recents' last chat, so it belongs only in end.
+ const end = recents.attributes.properties.find(
+ (p) => ts.isJsxAttribute(p) && p.name.getText() === "end",
+ );
+ assert.ok(end, "Recents passes no `end`");
+ assert.equal(tails.length, 1);
+ assert.ok(tails[0].pos >= end.pos && tails[0].end <= end.end);
+});
diff --git a/tests/studio/playwright_progressive_rows.py b/tests/studio/playwright_progressive_rows.py
new file mode 100644
index 00000000000..d6d646c05e5
--- /dev/null
+++ b/tests/studio/playwright_progressive_rows.py
@@ -0,0 +1,189 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""exercise ProgressiveRows paging, cleanup, remounting, and observer rearming in browsers."""
+
+from __future__ import annotations
+
+import asyncio
+import os
+import shutil
+import socket
+import subprocess
+import tempfile
+from pathlib import Path
+from urllib.request import urlopen
+
+from playwright.async_api import async_playwright
+
+FRONTEND = Path(__file__).resolve().parents[2] / "studio" / "frontend"
+ENGINES = [e for e in os.environ.get("SMOKE_ENGINES", "chromium").split(",") if e]
+
+# track live observers to verify that completed or unmounted lists release them
+COUNT_OBSERVERS = """
+ window.liveObservers = 0;
+ const Original = window.IntersectionObserver;
+ window.IntersectionObserver = class extends Original {
+ constructor(...args) { super(...args); this.live = false; }
+ observe(target) { if (!this.live) { this.live = true; window.liveObservers++; } return super.observe(target); }
+ disconnect() { if (this.live) { this.live = false; window.liveObservers--; } return super.disconnect(); }
+ };
+"""
+
+STATE = """() => {
+ const items = [...document.querySelectorAll('[data-sidebar="content"] li')];
+ const last = items[items.length - 1];
+ return {
+ rows: document.querySelectorAll('[data-row]').length,
+ end: !!document.querySelector('[data-end]'),
+ sentinelLast: !!last && !last.hasAttribute('data-row') && !last.hasAttribute('data-end'),
+ renders: window.rowRenders,
+ observers: window.liveObservers,
+ };
+}"""
+
+
+async def settle(page):
+ """wait until the row count has held for half a second."""
+ last, stable = None, 0
+ for _ in range(200):
+ state = await page.evaluate(STATE)
+ stable = stable + 1 if state["rows"] == last else 0
+ if stable >= 5:
+ return state
+ last = state["rows"]
+ await page.wait_for_timeout(100)
+ raise AssertionError(f"row count never settled: {state}")
+
+
+async def scroll_to_bottom(page):
+ await page.evaluate(
+ "() => { const s = document.querySelector('[data-sidebar=\"content\"]'); s.scrollTop = s.scrollHeight; }"
+ )
+ return await settle(page)
+
+
+async def check(browser, url, engine):
+ page = await browser.new_page(viewport = {"width": 600, "height": 700})
+ errors = []
+ page.on("pageerror", lambda error: errors.append(str(error)))
+ await page.add_init_script(COUNT_OBSERVERS)
+
+ await page.goto(url + "?count=1000")
+ await page.locator("[data-row]").first.wait_for()
+ state = await settle(page)
+ assert state["rows"] == 50 and state["sentinelLast"] and not state["end"], state
+ assert state["renders"] == 50 and state["observers"] == 1, state
+
+ # prior rows must remain mounted without rerendering as each page adds 50 rows
+ for expected in (100, 150, 200):
+ state = await scroll_to_bottom(page)
+ assert state["rows"] == expected, state
+ assert state["renders"] == expected, state
+ assert state["observers"] == 1, state
+
+ # refetching preserves page depth but rerenders each mounted row once
+ await page.evaluate("window.fixture.refresh()")
+ state = await settle(page)
+ assert state["rows"] == 200 and state["renders"] == 400, state
+
+ # unmounting disconnects the observer, and remounting restarts from the first page
+ assert await page.evaluate("window.liveObservers") == 1
+ await page.evaluate("window.fixture.setMounted(false)")
+ await page.wait_for_timeout(200)
+ assert await page.evaluate("window.liveObservers") == 0
+ await page.evaluate("window.fixture.setMounted(true)")
+ state = await settle(page)
+ assert state["rows"] == 50 and state["observers"] == 1, state
+
+ # shrinking within a page releases the observer, while regrowth restarts paging
+ await page.evaluate("window.fixture.setCount(30)")
+ state = await settle(page)
+ assert state["rows"] == 30 and state["end"] and state["observers"] == 0, state
+ await page.evaluate("window.fixture.setCount(1000)")
+ state = await settle(page)
+ assert state["rows"] == 50 and state["sentinelLast"] and state["observers"] == 1, state
+
+ # the final page leaves only rows and the end marker, with no sentinel or observer
+ for _ in range(40):
+ state = await scroll_to_bottom(page)
+ if state["end"]:
+ break
+ assert state["rows"] == 1000 and state["end"] and not state["sentinelLast"], state
+ assert state["observers"] == 0, state
+
+ # a sentinel in range must rearm each page; 100 rows fit in the 3000 px viewport plus 800 px margin, but 150 do not
+ await page.goto(url + "?count=1000&height=3000")
+ await page.locator("[data-row]").first.wait_for()
+ state = await settle(page)
+ assert state["rows"] == 150 and state["sentinelLast"], state
+
+ assert not errors, errors
+ await page.close()
+ print(
+ f"{engine}: paging, render reuse, refresh, end, cleanup, remount, shrink and refill passed",
+ flush = True,
+ )
+
+
+async def run_checks(url):
+ async with async_playwright() as playwright:
+ for engine in ENGINES:
+ launch = {"headless": True}
+ executable = os.environ.get(f"PW_{engine.upper()}_EXECUTABLE")
+ if executable:
+ launch["executable_path"] = executable
+ browser = await getattr(playwright, engine).launch(**launch)
+ try:
+ await check(browser, url, engine)
+ finally:
+ await browser.close()
+
+
+async def main():
+ with socket.socket() as sock:
+ sock.bind(("127.0.0.1", 0))
+ port = sock.getsockname()[1]
+ url = f"http://127.0.0.1:{port}/"
+ node = shutil.which("node")
+ assert node, "Node.js is required"
+ with tempfile.TemporaryFile(mode = "w+") as log:
+ server = subprocess.Popen(
+ [
+ node,
+ "node_modules/vite/bin/vite.js",
+ "--config",
+ "tests/fixtures/progressive-rows/vite.config.ts",
+ "--port",
+ str(port),
+ "--strictPort",
+ ],
+ cwd = FRONTEND,
+ stdout = log,
+ stderr = subprocess.STDOUT,
+ )
+ try:
+ for _ in range(150):
+ if server.poll() is not None:
+ log.seek(0)
+ raise RuntimeError(log.read())
+ try:
+ with urlopen(url, timeout = 1) as response:
+ if response.status == 200:
+ break
+ except OSError:
+ await asyncio.sleep(0.2)
+ else:
+ raise RuntimeError("Vite did not start")
+ await run_checks(url)
+ finally:
+ server.terminate()
+ try:
+ server.wait(timeout = 5)
+ except subprocess.TimeoutExpired:
+ server.kill()
+ server.wait()
+
+
+if __name__ == "__main__":
+ asyncio.run(main())