Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

fix(web): the Trace view loads every page of a file, so late rounds keep their messages (#710)

Yaowei Zheng0c742e5b1611
diff --git a/changelog/unreleased/2026-09-12-trace-view-all-events.md b/changelog/unreleased/2026-09-12-trace-view-all-events.md
new file mode 100644
index 00000000..ef045e0e
--- /dev/null
+++ b/changelog/unreleased/2026-09-12-trace-view-all-events.md
@@ -0,0 +1,34 @@
+# The Trace view loads every page of a file
+
+- **Date:** 2026-09-12
+- **Type:** fix
+- **Scope:** `web`
+- **PR:** [#710](https://github.com/Prism-Shadow/penguin-harness/pull/710)
+
+[中文版](2026-09-12-trace-view-all-events.zh.md)
+
+A long Trace file's later rounds — the compaction round among them, which sits at the end of the
+file — showed a timeline with zero messages: the analysis described the whole file and attributed
+messages to rounds by index range, while only the first 1000 events were ever fetched, so every
+round whose range started past that page had nothing to list. The view pages through the whole
+file now, and no round of a loaded file shows an empty message list.
+
+## Details
+
+- `features/traces/trace-events-loader.ts` walks the events endpoint: page after page from offset
+ 0, each next offset taken from what the previous page actually delivered, ending when the walk
+ reaches the latest page's `total`. The total is re-read per page, so a file appended to while
+ the walk runs is followed to its new end; a page carrying no events ends the walk, the number
+ of requests one walk may make is capped, and the walk resolves with the last page's `total`.
+- The file view renders progressively: each page is spliced into the list at its own offset, so
+ the start of a long file is readable while the rest arrives. A refresh — the panel re-reads the
+ file on every settled turn — therefore updates the list in place rather than dropping it back
+ to a single page, and the completed walk trims the list to the length it has just read.
+- Switching files, unmounting the panel or a refresh cancels the walk in flight, and a page that
+ fails reports its error beside the part already loaded rather than clearing it.
+- The footer below the message list changed from "showing first N" to a loading note
+ (`Loaded 5 / 12 messages…`), and disappears once every message is on screen.
+- `test/trace-events-loader.test.ts` covers the walk against a fake endpoint: a 2500-event file
+ paged in three requests, a page that came back shorter than it was asked for, a file that grew
+ mid-walk, a truncated file whose pages run out before its `total`, cancellation both between
+ two pages and while one was in flight, the request cap, and the length the walk resolves with.
diff --git a/changelog/unreleased/2026-09-12-trace-view-all-events.zh.md b/changelog/unreleased/2026-09-12-trace-view-all-events.zh.md
new file mode 100644
index 00000000..afdf2bce
--- /dev/null
+++ b/changelog/unreleased/2026-09-12-trace-view-all-events.zh.md
@@ -0,0 +1,27 @@
+# Trace 页加载轨迹文件的全部分页
+
+- **Date:** 2026-09-12
+- **Type:** fix
+- **Scope:** `web`
+- **PR:** [#710](https://github.com/Prism-Shadow/penguin-harness/pull/710)
+
+[English](2026-09-12-trace-view-all-events.md)
+
+较长的轨迹文件里,靠后的轮次——包括位于文件末尾的压缩轮——时间线下的消息数为 0:分析覆盖整个文件,并按
+索引区间把消息归入各轮,而事件只取了前 1000 条,于是区间起点落在该分页之后的轮次无消息可列。现在 Trace
+页会翻完整个文件,已加载完成的文件中不会再有消息列表为空的轮次。
+
+## 细节
+
+- `features/traces/trace-events-loader.ts` 负责翻页:从 offset 0 起逐页请求,下一个 offset 取自上一页
+ 实际返回的条数,直到走到最新一页的 `total` 为止。`total` 每页重读,因此翻页期间被追加写入的文件会跟到
+ 新的末尾;返回空页即结束翻页,单次翻页的请求数有上限,翻页结束后返回最后一页的 `total`。
+- 文件视图渐进渲染:每一页按自己的 offset 就位插入列表,长文件的开头在其余部分到达之前即可阅读。因此刷新
+ (面板在每轮结束时都会重读文件)是就地更新列表,不会把列表退回只剩一页;翻页结束后按刚读到的长度裁掉
+ 多余的行。
+- 切换文件、面板卸载或触发刷新都会取消进行中的翻页;某一页失败时,错误显示在已加载内容旁边,不清空已有
+ 内容。
+- 消息列表底部的脚注由「仅展示前 N 条」改为加载提示(`已载入 5 / 12 条消息…`),全部消息到位后消失。
+- `test/trace-events-loader.test.ts` 用假接口覆盖翻页行为:2500 条事件分三次请求、返回条数少于请求条数
+ 的分页、翻页途中变长的文件、分页在 `total` 之前就耗尽的截断文件、两页之间以及某页在途中的取消、请求数
+ 上限,以及翻页结束时返回的长度。
diff --git a/packages/web/src/features/traces/trace-events-loader.ts b/packages/web/src/features/traces/trace-events-loader.ts
new file mode 100644
index 00000000..9a000747
--- /dev/null
+++ b/packages/web/src/features/traces/trace-events-loader.ts
@@ -0,0 +1,90 @@
+/**
+ * Sequential pager for a Trace file's events (pure — unit-tested in test/trace-events-loader.test.ts).
+ *
+ * The events endpoint is paginated and its `limit` is capped server-side, while the analysis
+ * beside it describes the WHOLE file: every round carries a `messageFrom`/`messageTo` index
+ * range, so a view that fetched one page only had nothing to show for any round whose range
+ * started past that page — the last rounds of a long file, the compaction round among them.
+ * The walk here is what closes that gap: it keeps asking for the next page until the file is
+ * covered, reporting each page as it arrives so the first one is on screen while the rest load.
+ *
+ * Pages are fetched one at a time rather than in parallel: the file is read from disk in order,
+ * the next offset is only known from the page before it (a page may come back short), and a
+ * reader looking at round one does not benefit from round nine's page racing it.
+ */
+import type { TraceEventsResponse } from "@prismshadow/penguin-server/api";
+
+/**
+ * Hard stop on the number of requests one walk may make. With the endpoint's 1000-event page
+ * this covers a 500,000-event file, far past any Trace a Session produces (files rotate on
+ * compaction), so the cap is only ever reached by a server that stops making progress — a page
+ * that reports a `total` it never delivers would otherwise loop for as long as the view is open.
+ */
+export const MAX_TRACE_EVENT_PAGES = 500;
+
+/**
+ * Events per request: the largest `limit` the events endpoint accepts (it rejects anything
+ * above 1000), so a file is covered in the fewest round trips the server allows.
+ */
+export const TRACE_EVENT_PAGE_SIZE = 1000;
+
+/** Cancellation handed to a walk by its caller; flipped by a React effect's cleanup. */
+export interface TraceEventsSignal {
+ cancelled: boolean;
+}
+
+export interface LoadTraceEventPagesOptions {
+ /** Events per request. The endpoint rejects a `limit` above its own maximum, so pass TRACE_EVENT_PAGE_SIZE. */
+ pageSize: number;
+ /** Called once per fetched page, in file order, for the caller to render. */
+ onPage: (page: TraceEventsResponse) => void;
+ /** When its `cancelled` turns true the walk stops and reports nothing further. */
+ signal?: TraceEventsSignal;
+}
+
+/**
+ * Walk a Trace file's events from its start, reporting every page through `onPage`.
+ *
+ * The next offset is the end of what has actually been delivered (`offset + events.length`),
+ * never `offset + pageSize`: the last page of a file is short, and any page the server answers
+ * with fewer events than were asked for must not leave a hole behind it either. The walk ends
+ * when that offset reaches the LATEST page's `total` — read per page, so a file appended to
+ * while the walk runs is followed to its new end rather than cut at the length it had when the
+ * first page was served.
+ *
+ * A page carrying no events also ends the walk, whatever its `total` claims: a file truncated
+ * under the reader cannot be paged any further, and continuing would re-request the same offset
+ * forever. Cancellation is checked on both sides of every await — after one, so a page that
+ * arrives for a view that is gone is not rendered into it; before the next, so no further
+ * request is issued once the caller has stopped caring about the answer.
+ *
+ * Rejections are not caught: the caller decides what a failed page means for what is already on
+ * screen. Pages reported before it stand.
+ *
+ * Resolves with the `total` of the LAST page it reported — the walk's final word on how long the
+ * file is, which a caller holding pages from an earlier walk uses to drop whatever sits past the
+ * end. A walk that reported no page at all (cancelled before its first) resolves with 0, so the
+ * caller must consult its own cancellation before acting on the number.
+ */
+export async function loadTraceEventPages(
+ fetchPage: (offset: number, limit: number) => Promise<TraceEventsResponse>,
+ opts: LoadTraceEventPagesOptions,
+): Promise<number> {
+ let offset = 0;
+ let total = 0;
+ // Read through a call, not inline: the flag flips while a page is in flight, and an inline
+ // check narrows it to `false` for the rest of the loop body, so the post-await check would
+ // compare a type the checker believes cannot be `true`.
+ const cancelled = (): boolean => opts.signal?.cancelled === true;
+ for (let page = 0; page < MAX_TRACE_EVENT_PAGES; page++) {
+ if (cancelled()) return total;
+ const res = await fetchPage(offset, opts.pageSize);
+ if (cancelled()) return total;
+ opts.onPage(res);
+ total = res.total;
+ if (res.events.length === 0) return total;
+ offset += res.events.length;
+ if (offset >= res.total) return total;
+ }
+ return total;
+}
diff --git a/packages/web/src/features/traces/trace-file-view.tsx b/packages/web/src/features/traces/trace-file-view.tsx
index 4f3a84de..d2698218 100644
--- a/packages/web/src/features/traces/trace-file-view.tsx
+++ b/packages/web/src/features/traces/trace-file-view.tsx
@@ -52,6 +52,7 @@ import { Skeleton } from "../../components/ui/skeleton";
import { Chevron } from "../../components/ui/chevron";
import { GlyphIcon } from "../../components/ui/glyph-icon";
import { TokenDonut } from "../../components/ui/token-donut";
+import { TRACE_EVENT_PAGE_SIZE, loadTraceEventPages } from "./trace-events-loader";
import { TimelineChart } from "./timeline-chart";
import type { TraceHighlight } from "./timeline-chart";
import { EventRow } from "./trace-event-row";
@@ -225,8 +226,6 @@ export function TraceFileView({
const { currency } = useTheme();
const [analysis, setAnalysis] = useState<TraceAnalysisResponse | null>(null);
const [events, setEvents] = useState<OmniMessage[]>([]);
- /** events' starting index within the file (pagination offset): used to align with analysis.tasks' index ranges. */
- const [eventsOffset, setEventsOffset] = useState(0);
const [total, setTotal] = useState(0);
const [error, setError] = useState<string | null>(null);
const [collapsed, setCollapsed] = useState<ReadonlySet<number>>(new Set());
@@ -262,25 +261,68 @@ export function TraceFileView({
// Load the file, and re-load it whenever the panel's signal moves. Results overwrite what is
// on screen in place — an in-flight refresh keeps the current content readable, and its
// outcome is what clears or sets the error, since nothing was cleared up front.
+ //
+ // The events are paged through to the END of the file, not fetched once: the analysis
+ // describes every round by index range, so a round whose messages sit past the first page
+ // would render an empty message list. Each page lands at its own offset, so a long file is
+ // readable from its start while the rest of it arrives, and a REFRESH of a file already on
+ // screen updates the list in place instead of shrinking it back to one page per settled turn.
useEffect(() => {
- let cancelled = false;
- Promise.all([
- api.getAgentTraceAnalysis(projectId, agentId, sessionId, index),
- api.getAgentTraceEvents(projectId, agentId, sessionId, index, 0, 1000),
- ])
- .then(([a, e]) => {
- if (cancelled) return;
+ const signal = { cancelled: false };
+ const fail = (err: unknown) => {
+ if (!signal.cancelled) setError(apiErrorText(err));
+ };
+ // The error is cleared only once BOTH halves of the first load have landed: cleared on
+ // either one alone, a failure on one side would be wiped by the other side's success.
+ let haveAnalysis = false;
+ let haveFirstPage = false;
+ const clearErrorWhenBothLanded = () => {
+ if (haveAnalysis && haveFirstPage) setError(null);
+ };
+ api
+ .getAgentTraceAnalysis(projectId, agentId, sessionId, index)
+ .then((a) => {
+ if (signal.cancelled) return;
setAnalysis(a);
- setEvents(e.events);
- setEventsOffset(e.offset);
- setTotal(e.total);
- setError(null);
+ haveAnalysis = true;
+ clearErrorWhenBothLanded();
+ })
+ .catch(fail);
+ loadTraceEventPages(
+ (offset, limit) =>
+ api.getAgentTraceEvents(projectId, agentId, sessionId, index, offset, limit),
+ {
+ pageSize: TRACE_EVENT_PAGE_SIZE,
+ signal,
+ onPage: (page) => {
+ // `total` comes from the latest page: the file is appended to while the Session runs.
+ setTotal(page.total);
+ // The page is spliced in AT ITS OFFSET rather than replacing or appending: a refresh
+ // re-walks a file already on screen (the panel re-reads on every settled turn), and
+ // a first page that replaced the list would drop a 2500-event file back to 1000 rows
+ // and empty its later rounds for a moment, once per turn. A file SWITCH starts from
+ // an empty list instead — the renderedFileKey reset above — so nothing is spliced
+ // into another file's rows.
+ setEvents((prev) => {
+ const next = prev.slice();
+ next.splice(page.offset, page.events.length, ...page.events);
+ return next;
+ });
+ haveFirstPage = true;
+ clearErrorWhenBothLanded();
+ },
+ },
+ )
+ .then((loaded) => {
+ // The completed walk's last word on the file's length: rows past it are an earlier
+ // walk's leftovers, from a file that came back shorter than it was read as before.
+ if (!signal.cancelled) {
+ setEvents((prev) => (prev.length > loaded ? prev.slice(0, loaded) : prev));
+ }
})
- .catch((err: unknown) => {
- if (!cancelled) setError(apiErrorText(err));
- });
+ .catch(fail);
return () => {
- cancelled = true;
+ signal.cancelled = true;
};
}, [projectId, agentId, sessionId, index, reloadSignal]);
@@ -360,9 +402,9 @@ export function TraceFileView({
// round (the server already knows this message-by-message from its
// sequential scan, no need to re-guess it here).
// events is only used to populate the message list (a list view that
- // truthfully indicates truncation at the bottom); no **numeric value**
- // is ever derived from it: events is paginated (limit=1000, not
- // continued), so using it for aggregation would undercount Token/cost for a long Trace.
+ // names its loading progress at the bottom); no **numeric value** is ever
+ // derived from it: the pages arrive one after another, so aggregating over
+ // events would undercount Token/cost for as long as a long Trace is still loading.
const taskOfIndex = (k: number): number | null => {
for (const t of analysis.tasks) {
if (k >= t.messageFrom && k <= t.messageTo) return t.taskIndex;
@@ -372,7 +414,7 @@ export function TraceFileView({
for (let i = 0; i < events.length; i++) {
const msg = events[i]!;
if (msg.origin && msg.origin.length > 0) continue; // sub-session messages don't enter this file's grouping
- const ti = taskOfIndex(eventsOffset + i); // events is fetched starting at offset; recover the global index within the file
+ const ti = taskOfIndex(i); // events is paged from the file's start, so i IS the index within the file
if (ti !== null) ensure(ti).messages.push(msg);
}
g.toolCalls = analysis.toolSpans.length;
@@ -394,7 +436,7 @@ export function TraceFileView({
const gLlm = analysis.tasks.reduce((s, t) => s + t.llmMs, 0);
const tasks = [...map.values()].sort((a, b) => a.taskIndex - b.taskIndex);
return { tasks, global: g, statsByTask, globalLlmMs: gLlm };
- }, [analysis, events, eventsOffset]);
+ }, [analysis, events]);
// The error takes the whole view only while there is nothing to take it from: this re-reads
// on every settled turn now, so a blip mid-read would otherwise blank a file the user is in
@@ -651,7 +693,7 @@ export function TraceFileView({
})}
{events.length < total && (
- <p className="text-xs text-gray-400">{S.traces.truncatedNote(events.length, total)}</p>
+ <p className="text-xs text-gray-400">{S.traces.loadingNote(events.length, total)}</p>
)}
</div>
);
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 5cd6c018..e00ae5a4 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -2691,7 +2691,8 @@ Scenarios:
globalSummary: "Overall",
tasksLabel: "Turns",
messages: "Messages",
- truncatedNote: (shown: number, total: number) => `Showing first ${shown} / ${total} messages`,
+ /** Shown while the file's remaining pages are still being fetched; gone once every message is on screen. */
+ loadingNote: (shown: number, total: number) => `Loaded ${shown} / ${total} messages…`,
zoom: "Zoom",
zoomReset: "Double-click to reset zoom",
zoomOut: "Zoom out",
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 41ab3a35..e44677fb 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -2644,7 +2644,8 @@ Benchmark:
globalSummary: "全局统计",
tasksLabel: "轮次",
messages: "消息",
- truncatedNote: (shown: number, total: number) => `仅展示前 ${shown} / ${total} 条消息`,
+ /** Shown while the file's remaining pages are still being fetched; gone once every message is on screen. */
+ loadingNote: (shown: number, total: number) => `已载入 ${shown} / ${total} 条消息…`,
zoom: "缩放",
zoomReset: "双击复位缩放",
zoomOut: "缩小",
diff --git a/packages/web/test/trace-events-loader.test.ts b/packages/web/test/trace-events-loader.test.ts
new file mode 100644
index 00000000..35fa7adc
--- /dev/null
+++ b/packages/web/test/trace-events-loader.test.ts
@@ -0,0 +1,217 @@
+/**
+ * The Trace file view's event pager (features/traces/trace-events-loader.ts).
+ *
+ * What matters here is that the walk covers the WHOLE file: the analysis beside it attributes
+ * messages to rounds by index range, so an event the walk never fetched is a round that renders
+ * an empty message list. The cases below are the four ways a walk ends — the file is covered,
+ * the file cannot be paged any further, the reader left, and the page cap — plus the one that
+ * moves the finish line, a file appended to while the walk is running.
+ */
+import { describe, expect, it } from "vitest";
+import type { OmniMessage } from "@prismshadow/penguin-core/omnimessage";
+import type { TraceEventsResponse } from "@prismshadow/penguin-server/api";
+import {
+ MAX_TRACE_EVENT_PAGES,
+ TRACE_EVENT_PAGE_SIZE,
+ loadTraceEventPages,
+} from "../src/features/traces/trace-events-loader";
+
+/** One synthetic event, identified by its index so a page's slice can be checked exactly. */
+const event = (i: number): OmniMessage => ({
+ timestamp: "2026-09-12T00:00:00.000Z",
+ type: "model_msg",
+ payload: { type: "text", role: "assistant", text: `m${i}` },
+});
+
+const textsOf = (events: readonly OmniMessage[]): string[] =>
+ events.map((m) => (m.payload as { text: string }).text);
+
+const expectedTexts = (from: number, count: number): string[] =>
+ Array.from({ length: count }, (_, i) => `m${from + i}`);
+
+/**
+ * A fake events endpoint over a file of `size` synthetic events.
+ *
+ * `state.size` is what the file can actually deliver and `state.total` what it reports, held
+ * apart so a truncated file (a `total` above what comes back) can be staged. `serverLimit` caps
+ * how many events a page comes back with — a server answering with fewer than were asked for —
+ * and `onFetch` is the hook the growing-file, truncation and cancellation cases use to change
+ * the file between two pages.
+ */
+function fakeFile(
+ size: number,
+ opts: { serverLimit?: number; onFetch?: (call: number) => void } = {},
+) {
+ const state = { size, total: size };
+ const calls: { offset: number; limit: number }[] = [];
+ const pages: TraceEventsResponse[] = [];
+ const fetchPage = (offset: number, limit: number): Promise<TraceEventsResponse> => {
+ calls.push({ offset, limit });
+ opts.onFetch?.(calls.length);
+ const capped = Math.min(limit, opts.serverLimit ?? limit);
+ const events: OmniMessage[] = [];
+ for (let i = offset; i < Math.min(offset + capped, state.size); i++) events.push(event(i));
+ return Promise.resolve({ events, offset, limit: capped, total: state.total });
+ };
+ return {
+ state,
+ calls,
+ pages,
+ fetchPage,
+ onPage: (page: TraceEventsResponse) => pages.push(page),
+ };
+}
+
+describe("loadTraceEventPages", () => {
+ it("pages a 2500-event file in three requests, reporting every page in file order", async () => {
+ const f = fakeFile(2500);
+ await loadTraceEventPages(f.fetchPage, { pageSize: 1000, onPage: f.onPage });
+
+ expect(f.calls).toEqual([
+ { offset: 0, limit: 1000 },
+ { offset: 1000, limit: 1000 },
+ { offset: 2000, limit: 1000 },
+ ]);
+ expect(f.pages.map((p) => p.offset)).toEqual([0, 1000, 2000]);
+ expect(f.pages.map((p) => p.events.length)).toEqual([1000, 1000, 500]);
+ expect(textsOf(f.pages[0]!.events)).toEqual(expectedTexts(0, 1000));
+ expect(textsOf(f.pages[1]!.events)).toEqual(expectedTexts(1000, 1000));
+ expect(textsOf(f.pages[2]!.events)).toEqual(expectedTexts(2000, 500));
+ // Concatenated, the pages are the file — nothing dropped, nothing repeated.
+ expect(textsOf(f.pages.flatMap((p) => p.events))).toEqual(expectedTexts(0, 2500));
+ });
+
+ it("advances by what a page delivered, not by the page size it asked for", async () => {
+ // Whatever cuts a page short, the next offset follows the events that arrived rather than
+ // the number asked for, so no event is skipped between two pages.
+ const f = fakeFile(500, { serverLimit: 200 });
+ await loadTraceEventPages(f.fetchPage, { pageSize: 1000, onPage: f.onPage });
+
+ expect(f.calls.map((c) => c.offset)).toEqual([0, 200, 400]);
+ expect(textsOf(f.pages.flatMap((p) => p.events))).toEqual(expectedTexts(0, 500));
+ });
+
+ it("follows a file that was appended to while the walk was running", async () => {
+ // The Session keeps writing: the file grows by 600 events after the second page was served.
+ const f = fakeFile(2500, {
+ onFetch: (call) => {
+ if (call === 2) {
+ f.state.size = 3100;
+ f.state.total = 3100;
+ }
+ },
+ });
+ await loadTraceEventPages(f.fetchPage, { pageSize: 1000, onPage: f.onPage });
+
+ // A walk pinned to the FIRST page's total would have stopped at 2500, three pages in.
+ expect(f.calls.map((c) => c.offset)).toEqual([0, 1000, 2000, 3000]);
+ expect(f.pages.map((p) => p.total)).toEqual([2500, 3100, 3100, 3100]);
+ expect(textsOf(f.pages.flatMap((p) => p.events))).toEqual(expectedTexts(0, 3100));
+ });
+
+ it("ends the walk on a page with no events, however long the file claims to be", async () => {
+ // A file truncated under the reader: `total` still says 3000, nothing comes back past 1000.
+ const f = fakeFile(3000, {
+ onFetch: (call) => {
+ if (call === 2) f.state.size = 1000;
+ },
+ });
+ await loadTraceEventPages(f.fetchPage, { pageSize: 1000, onPage: f.onPage });
+
+ expect(f.calls.map((c) => c.offset)).toEqual([0, 1000]);
+ expect(f.pages.map((p) => p.events.length)).toEqual([1000, 0]);
+ expect(f.pages[1]!.total).toBe(3000);
+ });
+
+ it("stops without reporting or requesting anything more once it is cancelled", async () => {
+ const signal = { cancelled: false };
+ const f = fakeFile(4000);
+ await loadTraceEventPages(f.fetchPage, {
+ pageSize: 1000,
+ signal,
+ onPage: (page) => {
+ f.onPage(page);
+ // The view is gone — the file switched, or the panel unmounted — mid-walk.
+ signal.cancelled = true;
+ },
+ });
+
+ expect(f.calls).toEqual([{ offset: 0, limit: 1000 }]);
+ expect(f.pages).toHaveLength(1);
+ });
+
+ it("does not report a page that arrived after the walk was cancelled", async () => {
+ // The flag is flipped by a React effect's cleanup, which runs while a page is IN FLIGHT —
+ // not from inside `onPage`. Checked only before each request, the walk would still splice
+ // this page into a view that has already moved to another Trace file.
+ const signal = { cancelled: false };
+ const calls: number[] = [];
+ const pages: TraceEventsResponse[] = [];
+ let deliver!: (page: TraceEventsResponse) => void;
+ const walk = loadTraceEventPages(
+ (offset) => {
+ calls.push(offset);
+ return new Promise<TraceEventsResponse>((resolve) => {
+ deliver = resolve;
+ });
+ },
+ { pageSize: 1000, signal, onPage: (page) => pages.push(page) },
+ );
+
+ // The view switched files while the first page was still out; the page lands afterwards.
+ signal.cancelled = true;
+ deliver({ events: [event(0)], offset: 0, limit: 1000, total: 2500 });
+
+ // Nothing rendered, nothing requested beyond the page already out, and the 0 tells the
+ // caller it has no answer about the file's length.
+ await expect(walk).resolves.toBe(0);
+ expect(pages).toEqual([]);
+ expect(calls).toEqual([0]);
+ });
+
+ it("caps a walk that never finishes, rather than requesting for as long as the view is open", async () => {
+ // A server reporting a total it never delivers: one event per page, forever.
+ const f = fakeFile(Number.MAX_SAFE_INTEGER, { serverLimit: 1 });
+ await loadTraceEventPages(f.fetchPage, { pageSize: 1000, onPage: f.onPage });
+
+ expect(f.calls).toHaveLength(MAX_TRACE_EVENT_PAGES);
+ });
+
+ it("resolves with the last page's total, the walk's final word on the file's length", async () => {
+ // The caller truncates to this number, so an earlier walk's rows cannot outlive a file
+ // that came back shorter than it was read as before.
+ const plain = fakeFile(2500);
+ await expect(
+ loadTraceEventPages(plain.fetchPage, { pageSize: 1000, onPage: plain.onPage }),
+ ).resolves.toBe(2500);
+
+ const grown = fakeFile(2500, {
+ onFetch: (call) => {
+ if (call === 2) {
+ grown.state.size = 3100;
+ grown.state.total = 3100;
+ }
+ },
+ });
+ await expect(
+ loadTraceEventPages(grown.fetchPage, { pageSize: 1000, onPage: grown.onPage }),
+ ).resolves.toBe(3100);
+
+ // Cancelled before any page was reported, there is no answer to give: 0, which the caller
+ // must not act on — it checks its own cancellation first.
+ const gone = fakeFile(2500);
+ await expect(
+ loadTraceEventPages(gone.fetchPage, {
+ pageSize: 1000,
+ signal: { cancelled: true },
+ onPage: gone.onPage,
+ }),
+ ).resolves.toBe(0);
+ expect(gone.calls).toEqual([]);
+ });
+
+ it("asks for the largest page the events endpoint accepts", () => {
+ // The route parses `limit` as 1-1000 (server/src/http/validate.ts); a larger ask is a 400.
+ expect(TRACE_EVENT_PAGE_SIZE).toBe(1000);
+ });
+});