Skip to content

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

fix(web): the Trace panel refreshes when a turn ends (#492)

Yaowei Zheng9cffaea74383
diff --git a/changelog/unreleased/2026-08-26-trace-panel-turn-refresh.md b/changelog/unreleased/2026-08-26-trace-panel-turn-refresh.md
new file mode 100644
index 00000000..cc420438
--- /dev/null
+++ b/changelog/unreleased/2026-08-26-trace-panel-turn-refresh.md
@@ -0,0 +1,40 @@
+# The Trace panel refreshes when a turn ends
+
+- **Date:** 2026-08-26
+- **Type:** fix
+- **Scope:** `web`
+- **PR:** [#492](https://github.com/Prism-Shadow/penguin-harness/pull/492)
+
+[中文版](2026-08-26-trace-panel-turn-refresh.zh.md)
+
+The Trace dock panel used to fetch only when its tab became visible, so a Trace opened while the
+Session kept working stayed at the size and the contents it had been read at. It was hooked up to
+the settled-turn signal the Files panel already reads: a turn ending while the Trace tab is
+showing re-lists the Session's Trace files and re-reads the selected one.
+
+## Details
+
+- The chat page's settled-turn counter — bumped on the `running` → `idle` edge of the selected
+ Session, and guarded against the phantom `idle` a detaching stream emits — was handed to the
+ Trace panel beside the Files browser, and renamed for its two readers.
+- A settled turn arriving while the tab is hidden fetched nothing. The hidden → visible edge kept
+ its own re-fetch, so the panel came up current on return whatever went by in between, in one
+ request rather than one per turn.
+- A re-list left the selection alone: the pill the user had clicked survived while its file was
+ still listed, and a selection whose file had vanished fell back to the newest one. The default
+ was pinned to the newest file the moment the first listing arrived, rather than left to resolve
+ itself on every re-list — unpinned, a compaction shard appearing mid-run would have walked a
+ reader who had never clicked a pill onto the new file.
+- The selected file's contents were re-read on the same edge. A Trace file is appended to while
+ the Session runs, so the ordinary refresh is the same file grown rather than a new file
+ appearing, and a load keyed on the file's index alone never re-ran for it.
+- Refreshing the file already on screen stopped clearing the view: the skeleton, the collapsed
+ round cards and the pinned timeline row are dropped only when a different file is selected.
+- A refresh that failed kept what was on screen. The failed re-list reported itself as a strip
+ above the file pills and the failed re-read as a line above the file's summary, both leaving
+ the panel below them standing; only a load with nothing to keep yet — no listing, or a listing
+ with no file in it — gave the whole panel over to the failure. With no manual refresh control
+ to fall back on, an emptied panel would have stood until the next turn ended.
+- The project's model catalog moved to a fetch of its own, keyed on the project. Pricing is a
+ catalog the project owns rather than something a turn produces, so it stopped riding along with
+ the selected file's load and a refresh went from three requests to two.
diff --git a/changelog/unreleased/2026-08-26-trace-panel-turn-refresh.zh.md b/changelog/unreleased/2026-08-26-trace-panel-turn-refresh.zh.md
new file mode 100644
index 00000000..15e07cc2
--- /dev/null
+++ b/changelog/unreleased/2026-08-26-trace-panel-turn-refresh.zh.md
@@ -0,0 +1,32 @@
+# 轨迹面板在一轮结束时自动刷新
+
+- **Date:** 2026-08-26
+- **Type:** fix
+- **Scope:** `web`
+- **PR:** [#492](https://github.com/Prism-Shadow/penguin-harness/pull/492)
+
+[English](2026-08-26-trace-panel-turn-refresh.md)
+
+轨迹面板此前只在标签页由隐藏转为显示时抓取一次,因此在 Session 仍在工作时打开的 Trace,会一直停在
+被读到时的大小与内容。此次将它接到文件面板已经在用的「一轮结束」信号上:轨迹标签页正在显示时一轮
+结束,会重新列出该 Session 的 Trace 文件,并重新读取当前选中的那一个。
+
+## 细节
+
+- 会话页的「一轮结束」计数器——在选中 Session 的 `running` → `idle` 边沿递增,并对流分离时发出的
+ 假 `idle` 做了防护——在交给文件浏览器之外,也交给了轨迹面板,并按这两个读者重新命名。
+- 标签页隐藏期间到达的信号不触发任何抓取。隐藏 → 显示的边沿保留了它自己的重新抓取,因此无论期间过了
+ 多少轮,回到该标签页时面板都是最新的,且只发一次请求,而不是每轮一次。
+- 重新列出不动用户的选择:用户点过的 pill 只要对应文件仍在列表中就保持不变,对应文件已经消失的选择
+ 则回退到最新的那一个。默认选择在第一次列出到达时就被钉到最新文件上,而不是留给每次重新列出去重新
+ 解析——不钉住的话,运行中途出现的压缩分片会把从没点过 pill 的读者拽到新文件上。
+- 选中文件的内容在同一边沿被重新读取。Trace 文件会在 Session 运行期间被不断追加,因此常见的刷新是
+ 同一个文件变大,而不是出现新文件;只以文件序号为键的加载对这种情况永远不会重跑。
+- 刷新屏幕上已有的文件不再清空视图:骨架屏、已折叠的轮次卡片和被固定的时间线行,只有在切换到另一个
+ 文件时才会丢弃。
+- 刷新失败不再带走屏幕上的内容。重新列出失败会在文件 pill 上方显示为一条提示条,重新读取失败会在文件
+ 概览上方显示为一行提示,两者都让下方的面板继续留在原处;只有还没有任何内容可保留的加载——尚无列表,
+ 或列表里没有文件——才会把整个面板让给这次失败。面板没有手动刷新入口可退,一旦被清空就会一直空到下
+ 一轮结束。
+- 项目的模型目录被挪到它自己的一次抓取上,以项目为键。定价属于项目这一层的目录,而不是某一轮产生的
+ 东西,因此它不再搭着选中文件的加载一起走,一次刷新也从三个请求降到两个。
diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsx
index 7661d08b..62a30329 100644
--- a/packages/web/src/features/chat/chat-page.tsx
+++ b/packages/web/src/features/chat/chat-page.tsx
@@ -665,8 +665,11 @@ export function ChatPage() {
id: selectedSessionId,
state: "idle",
});
- /** Settled-turn counter handed to the Files panel; every bump means "re-read". */
- const [filesReloadSignal, setFilesReloadSignal] = useState(0);
+ /**
+ * Settled-turn counter handed to the dock panels that read what the Session produced — the
+ * Files browser and the Trace panel; every bump means "re-read".
+ */
+ const [settledTurnSignal, setSettledTurnSignal] = useState(0);
useEffect(() => {
const prev = prevTaskRef.current;
const sameSession = prev.id === selectedSessionId;
@@ -680,9 +683,10 @@ export function ChatPage() {
void reloadAgents();
// The turn that just ended is when the Agent's file writes landed: the Files panel's
// listing and whatever it has open are stale from this moment on (see the browser's
- // reloadSignal). Same edge, same guard — a phantom "idle" from a detaching stream
- // never reaches here.
- setFilesReloadSignal((n) => n + 1);
+ // reloadSignal), and so are the Trace panel's file list and the file it is showing —
+ // the turn appended its own record to it. Same edge, same guard — a phantom "idle"
+ // from a detaching stream never reaches here.
+ setSettledTurnSignal((n) => n + 1);
}
}, [stream.taskState, selectedSessionId, reloadSessions, reloadAgents]);
@@ -1494,7 +1498,7 @@ export function ChatPage() {
session={selected}
openRequest={fileOpenRequest}
active={active}
- reloadSignal={filesReloadSignal}
+ reloadSignal={settledTurnSignal}
/>
);
case "memory":
@@ -1512,7 +1516,14 @@ export function ChatPage() {
/>
);
case "trace":
- return <TracePanel key={selected.sessionId} session={selected} active={active} />;
+ return (
+ <TracePanel
+ key={selected.sessionId}
+ session={selected}
+ active={active}
+ reloadSignal={settledTurnSignal}
+ />
+ );
case "messaging":
return (
<MessagingPanel key={selected.sessionId} sessionId={selected.sessionId} active={active} />
diff --git a/packages/web/src/features/traces/trace-file-view.tsx b/packages/web/src/features/traces/trace-file-view.tsx
index 675f7a46..0a697891 100644
--- a/packages/web/src/features/traces/trace-file-view.tsx
+++ b/packages/web/src/features/traces/trace-file-view.tsx
@@ -174,6 +174,7 @@ export function TraceFileView({
agentId,
sessionId,
index,
+ reloadSignal,
highlight,
onHighlight,
}: {
@@ -181,6 +182,13 @@ export function TraceFileView({
agentId: string;
sessionId: string;
index: number;
+ /**
+ * Bumped by the panel every time it re-lists (a re-show, or a turn settling while the panel
+ * is showing). Any change means "re-read this file": a Trace is APPENDED TO while the
+ * Session runs, so the same `index` at a larger size is the ordinary case and a load keyed
+ * on `index` alone would never re-run for it.
+ */
+ reloadSignal: number;
highlight: TraceHighlight | null;
onHighlight: (h: TraceHighlight | null) => void;
}) {
@@ -205,25 +213,39 @@ export function TraceFileView({
[],
);
- useEffect(() => {
+ // Switching to a DIFFERENT file clears the view — back to the skeleton, with the collapsed
+ // rounds and the pinned row forgotten because they name rounds this file does not have.
+ // Reset during render (React's documented "adjust state when a prop changes" pattern), which
+ // is what keeps it out of the load effect below: that effect also runs for a REFRESH of the
+ // file already on screen, and blanking there would flash a skeleton, drop the highlight and
+ // reopen every round card the user collapsed, several times per run.
+ const fileKey = `${projectId}/${agentId}/${sessionId}/${index}`;
+ const [renderedFileKey, setRenderedFileKey] = useState(fileKey);
+ if (renderedFileKey !== fileKey) {
+ setRenderedFileKey(fileKey);
setAnalysis(null);
setEvents([]);
setError(null);
setCollapsed(new Set());
setPinnedRow(null);
+ }
+
+ // 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.
+ useEffect(() => {
let cancelled = false;
Promise.all([
api.getAgentTraceAnalysis(projectId, agentId, sessionId, index),
api.getAgentTraceEvents(projectId, agentId, sessionId, index, 0, 1000),
- api.getModels(projectId).catch(() => null),
])
- .then(([a, e, m]) => {
+ .then(([a, e]) => {
if (cancelled) return;
setAnalysis(a);
setEvents(e.events);
setEventsOffset(e.offset);
setTotal(e.total);
- setModels(m);
+ setError(null);
})
.catch((err: unknown) => {
if (!cancelled) setError(apiErrorText(err));
@@ -231,7 +253,24 @@ export function TraceFileView({
return () => {
cancelled = true;
};
- }, [projectId, agentId, sessionId, index]);
+ }, [projectId, agentId, sessionId, index, reloadSignal]);
+
+ // Pricing is a PROJECT-level catalog, so it is fetched per project and deliberately left out
+ // of the load above: no turn changes it, and riding along there would refetch the whole
+ // catalog on every settled turn. It is optional and allowed to fail — a project whose models
+ // cannot be listed simply shows no cost column, and that is not the view's error.
+ useEffect(() => {
+ let cancelled = false;
+ void api
+ .getModels(projectId)
+ .then((m) => {
+ if (!cancelled) setModels(m);
+ })
+ .catch(() => undefined);
+ return () => {
+ cancelled = true;
+ };
+ }, [projectId]);
// Pricing for the session's Model (main session only; sub-session Tokens
// live in their own Trace and aren't part of this file): session_meta carries a paired
@@ -364,7 +403,11 @@ export function TraceFileView({
return { tasks, global: g, statsByTask, globalLlmMs: gLlm };
}, [analysis, events, eventsOffset]);
- if (error) return <p className="text-xs text-red-600 dark:text-red-400">{error}</p>;
+ // 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
+ // the middle of. With a file already rendered the failure is a line above it (below).
+ if (error !== null && analysis === null)
+ return <p className="text-xs text-red-600 dark:text-red-400">{error}</p>;
if (!analysis) return <Skeleton className="h-40" />;
// Duration is likewise "the sum across rounds" computed by the server over
@@ -412,6 +455,9 @@ export function TraceFileView({
return (
<div ref={rootRef} className="space-y-4">
+ {/* A re-read that failed: what follows is the last read that succeeded, so it may be a
+ turn or two behind. */}
+ {error !== null && <p className="text-xs text-red-600 dark:text-red-400">{error}</p>}
{/* Global summary: split into three groups by nature (count / Token
usage / duration·cost·TPS), separated by vertical rules — a dozen
metrics laid out in one row would read as a blur of digits; grouping lets you spot the kind you want at a glance. */}
diff --git a/packages/web/src/features/traces/trace-panel.tsx b/packages/web/src/features/traces/trace-panel.tsx
index fff30ac4..48540f69 100644
--- a/packages/web/src/features/traces/trace-panel.tsx
+++ b/packages/web/src/features/traces/trace-panel.tsx
@@ -8,8 +8,10 @@
* settings, beside the CLI-sessions filter.
*
* Loading is gated on `active` (the dock keeps inactive tabs mounted): the listing is
- * fetched on the first show and re-fetched on every re-show, so a Task that finished while
- * the tab was hidden appears on return without a manual refresh.
+ * fetched on the first show, re-fetched on every re-show, and re-fetched again whenever a
+ * turn settles while the tab IS showing. So the Trace grows under the eye watching it, and a
+ * Task that finished while the tab was hidden still appears on return without a manual
+ * refresh — while a hidden tab fetches nothing. trace-refresh.ts states the rule exactly.
*/
import { useEffect, useRef, useState } from "react";
import type { SessionInfo } from "@prismshadow/penguin-server/api";
@@ -21,7 +23,14 @@ import { DownloadIcon } from "../../components/ui/icons";
import { EmptyState } from "../../components/ui/empty-state";
import { Skeleton } from "../../components/ui/skeleton";
import { ICON_SIZE } from "../../lib/icon-scale";
+import { toneStrip } from "../../lib/tone";
import { TraceFileView } from "./trace-file-view";
+import {
+ activeTraceFile,
+ advanceTraceRefresh,
+ createTraceRefresh,
+ sortTraceFiles,
+} from "./trace-refresh";
import type { TraceHighlight } from "./timeline-chart";
/** File pills rendered before the "+N" overflow control expands them (a long Session can hold dozens of compaction shards). */
@@ -33,26 +42,44 @@ interface FileRef {
sizeBytes: number;
}
-export function TracePanel({ session, active }: { session: SessionInfo; active: boolean }) {
+export function TracePanel({
+ session,
+ active,
+ reloadSignal,
+}: {
+ session: SessionInfo;
+ /** Whether the dock tab is showing; a hidden tab stays mounted and fetches nothing. */
+ active: boolean;
+ /**
+ * The chat page's settled-turn counter, the same one the Files panel reads: bumped every time
+ * a Task settles on this Session. A bump while the panel is showing re-lists the files and
+ * re-reads the selected one — a Trace file GROWS during a run, so the ordinary refresh is the
+ * same file at a larger size, not a new file appearing.
+ */
+ reloadSignal: number;
+}) {
const [files, setFiles] = useState<FileRef[] | null>(null);
const [error, setError] = useState<string | null>(null);
const [fileIndex, setFileIndex] = useState<number | null>(null);
const [showAllFiles, setShowAllFiles] = useState(false);
const [highlight, setHighlight] = useState<TraceHighlight | null>(null);
- // Fetch on show: the first activation loads, later re-activations re-list (a Task may
- // have written a new file while the tab was hidden). Split into a rising-edge tick and
- // a fetch effect keyed on it — a single edge-detecting fetch effect would lose the
- // FIRST load under StrictMode's dev-mode double-invoke (the ref flips on the first run,
- // whose fetch the cleanup cancels; the second run then sees no edge and never refetches,
- // leaving the skeleton up forever). The selected pill survives a re-list while its file
- // still exists; a vanished selection falls back to the newest file.
+ // Fetch on show, and again on every settled turn while showing (trace-refresh.ts owns the
+ // rule; a signal arriving while hidden is dropped and the re-show edge covers it). Split
+ // into an edge tracker that bumps a tick and a fetch effect keyed on that tick — a single
+ // edge-detecting fetch effect would lose the FIRST load under StrictMode's dev-mode
+ // double-invoke (the tracker advances on the first run, whose fetch the cleanup cancels;
+ // the second run then sees no edge and never refetches, leaving the skeleton up forever).
+ // The selected pill survives a re-list while its file still exists; a vanished selection
+ // falls back to the newest file, and the default is pinned to a real index as soon as the
+ // first listing arrives rather than left to that fallback.
const [listTick, setListTick] = useState(0);
- const prevActive = useRef(active);
+ const refresh = useRef(createTraceRefresh({ active, signal: reloadSignal }));
useEffect(() => {
- if (active && !prevActive.current) setListTick((t) => t + 1);
- prevActive.current = active;
- }, [active]);
+ if (advanceTraceRefresh(refresh.current, { active, signal: reloadSignal })) {
+ setListTick((t) => t + 1);
+ }
+ }, [active, reloadSignal]);
useEffect(() => {
if (!active) return;
let cancelled = false;
@@ -60,24 +87,37 @@ export function TracePanel({ session, active }: { session: SessionInfo; active:
.getSessionTraces(session.sessionId)
.then((res) => {
if (cancelled) return;
- // Newest first: the pill row and the default selection both read left-to-right
- // from the most recent context.
- setFiles([...res.files].sort((a, b) => b.index - a.index));
+ const sorted = sortTraceFiles(res.files);
+ setFiles(sorted);
+ // Pin the default the first time a listing arrives. Left as null the selection is
+ // "whatever activeTraceFile falls back to" — the newest file, re-resolved on every
+ // re-list — so a compaction shard appearing mid-run would move a reader who never
+ // clicked a pill onto the new file, remounting the view below onto a different index
+ // and taking its collapsed rounds, pinned row and scroll position with it. Pinned,
+ // only a pill click moves the selection.
+ setFileIndex((cur) => cur ?? sorted[0]?.index ?? null);
setError(null);
})
.catch((err: unknown) => {
if (cancelled) return;
- setFiles([]);
+ // The listing already on screen is kept: this fires on every settled turn now, so a
+ // blip mid-read must not unmount the pills and the view below it. Only a first load
+ // (files still null) has nothing to fall back to.
setError(apiErrorText(err));
});
return () => {
cancelled = true;
};
- // listTick re-runs the fetch on every re-show; `active` alone would only load once.
+ // listTick re-runs the fetch on every re-show and on every settled turn while showing;
+ // `active` alone would only load once.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [active, listTick, session.sessionId]);
+ // The failure owns the whole panel only where there is nothing to keep: no listing yet
+ // (here), or a listing with no file in it (below). With a file on screen it is a strip
+ // above it instead.
if (files === null) {
+ if (error !== null) return <EmptyState title={S.tracePanel.loadFailed} description={error} />;
return (
<div className="space-y-3 p-4">
<Skeleton className="h-5 w-2/3" />
@@ -86,20 +126,26 @@ export function TracePanel({ session, active }: { session: SessionInfo; active:
);
}
- if (error !== null) {
- return <EmptyState title={S.tracePanel.loadFailed} description={error} />;
- }
-
- if (files.length === 0) {
+ // null only when the Session has produced no Trace at all: a re-list that dropped the
+ // selected file falls back to the newest one rather than emptying the panel.
+ const activeFile = activeTraceFile(files, fileIndex);
+ if (activeFile === null) {
+ if (error !== null) return <EmptyState title={S.tracePanel.loadFailed} description={error} />;
return <EmptyState title={S.tracePanel.empty} description={S.tracePanel.emptyHint} />;
}
- const activeFile = files.find((f) => f.index === fileIndex) ?? files[0]!;
const visibleFiles = showAllFiles ? files : files.slice(0, FILE_PILL_CAP);
return (
<div className="min-h-0 flex-1 overflow-y-auto p-3">
<div className="space-y-3">
+ {/* A re-list that failed keeps everything below it and says so here; the listing on
+ screen is the last one that arrived, so it may be a turn or two behind. */}
+ {error !== null && (
+ <p className={`rounded-md border px-2.5 py-1.5 text-xs ${toneStrip.danger}`}>
+ {S.tracePanel.loadFailed} · {error}
+ </p>
+ )}
<div className="flex flex-wrap items-center gap-1.5">
<span className="mr-1 text-xs text-gray-400">{S.traces.filesTitle}</span>
{visibleFiles.map((f) => (
@@ -149,11 +195,15 @@ export function TracePanel({ session, active }: { session: SessionInfo; active:
</a>
</div>
+ {/* The listing tick doubles as the view's re-read signal: every edge that re-lists
+ (a re-show, a settled turn while showing) also re-reads the selected file, since
+ the usual change is this same file having grown rather than a new one appearing. */}
<TraceFileView
projectId={session.projectId}
agentId={session.agentId}
sessionId={session.sessionId}
index={activeFile.index}
+ reloadSignal={listTick}
highlight={highlight}
onHighlight={setHighlight}
/>
diff --git a/packages/web/src/features/traces/trace-refresh.ts b/packages/web/src/features/traces/trace-refresh.ts
new file mode 100644
index 00000000..ea765241
--- /dev/null
+++ b/packages/web/src/features/traces/trace-refresh.ts
@@ -0,0 +1,88 @@
+/**
+ * The Trace panel's refresh rules (pure — unit-tested in test/trace-refresh.test.ts): WHEN the
+ * panel re-fetches, and what a re-fetch must leave standing.
+ *
+ * Two edges re-fetch: the dock tab becoming visible, and a turn settling on the Session while
+ * the tab IS visible (the chat page's settled-turn counter, the same one the Files panel reads
+ * — the writes an Agent makes land as its turn ends, and a Trace file is appended to by the
+ * very turn being watched). A settled turn that arrives while the tab is hidden is dropped
+ * rather than queued: the dock keeps hidden tabs mounted, fetching for a tab nobody is looking
+ * at is waste, and the hidden→visible edge re-fetches anyway — so the panel is current the
+ * moment it is looked at again, however many turns went by meanwhile.
+ *
+ * The tracker only decides. The panel applies the decision by bumping the tick its fetch effect
+ * is keyed on, and that split is load-bearing under StrictMode — see trace-panel.tsx.
+ */
+
+/** One observation of the panel's props, made per render by the panel's edge effect. */
+export interface TraceRefreshObservation {
+ /** Whether the dock tab is showing. */
+ active: boolean;
+ /** The chat page's settled-turn counter: ANY change of the number means "the turn ended — re-read". */
+ signal: number;
+}
+
+/** Mutable tracker state, held in a ref by the panel. */
+export interface TraceRefreshTracker {
+ active: boolean;
+ signal: number;
+}
+
+/**
+ * Seeded from the panel's first render, so a mount is never itself an edge: the fetch effect
+ * already loads on mount, and a tracker that started from `{ active: false, signal: 0 }` would
+ * report a spurious edge for a panel mounted already showing.
+ */
+export function createTraceRefresh(obs: TraceRefreshObservation): TraceRefreshTracker {
+ return { active: obs.active, signal: obs.signal };
+}
+
+/**
+ * Advance the tracker with one observation and return whether the panel should re-fetch:
+ * - hidden → visible: yes. This is also what makes a signal dropped while hidden harmless —
+ * the re-show re-lists and re-reads, whatever happened in between.
+ * - the signal changed while visible: yes — the turn that just ended wrote to the file the
+ * panel is showing.
+ * - the signal changed while hidden: no. The change is still consumed (the tracker adopts
+ * it), so the re-show edge is what brings the panel current, not a queued backlog.
+ * - anything else, including going visible → hidden: no.
+ * Both edges landing in ONE observation (a turn settling in the same commit that shows the
+ * tab) is still a single re-fetch, not two.
+ */
+export function advanceTraceRefresh(
+ state: TraceRefreshTracker,
+ obs: TraceRefreshObservation,
+): boolean {
+ const shown = obs.active && !state.active;
+ const settled = obs.signal !== state.signal;
+ state.active = obs.active;
+ state.signal = obs.signal;
+ return shown || (settled && obs.active);
+}
+
+/**
+ * The pill row's order: newest first, so the row and the default selection both read
+ * left-to-right from the most recent context. Copies rather than sorting the response in place.
+ */
+export function sortTraceFiles<T extends { index: number }>(files: readonly T[]): T[] {
+ return [...files].sort((a, b) => b.index - a.index);
+}
+
+/**
+ * The selected file after a listing arrives: the user's pick while its file is still listed, the
+ * newest file otherwise, and null only when the Session has no Trace at all. Selection is held
+ * by index rather than by the listed object, so a re-list — which returns fresh objects, and
+ * usually the SAME file at a larger size — leaves the pick where the user put it; a pick that
+ * vanished (a Trace deleted out from under the panel) falls back instead of blanking the view.
+ *
+ * A null `selected` is only ever the state BEFORE the first listing arrives: the panel pins the
+ * newest file as the default the moment one does. The fallback re-resolves on every re-list, so
+ * leaving it unpinned would walk a reader who never clicked a pill onto a freshly rotated
+ * compaction shard the instant one appeared.
+ */
+export function activeTraceFile<T extends { index: number }>(
+ files: readonly T[],
+ selected: number | null,
+): T | null {
+ return files.find((f) => f.index === selected) ?? files[0] ?? null;
+}
diff --git a/packages/web/test/trace-refresh.test.ts b/packages/web/test/trace-refresh.test.ts
new file mode 100644
index 00000000..2d06eea6
--- /dev/null
+++ b/packages/web/test/trace-refresh.test.ts
@@ -0,0 +1,211 @@
+/**
+ * The Trace panel's refresh rules (features/traces/trace-refresh.ts): the tab re-fetches when
+ * it becomes visible and when a turn settles WHILE it is visible, never for a hidden tab, and
+ * a re-fetch leaves the user's selected file where they put it — including the default they
+ * never picked, and including a re-fetch that fails while they are reading.
+ *
+ * The panel's edges are decided by a pure tracker for the same reason the subagents panel's
+ * auto-open is (panel-task-scope.test.ts): the Web suite runs in a node environment and renders
+ * no React, so the rule is unit-testable only where it is separable from the effect that applies
+ * it. The wiring that carries the decision into the two components is pinned at the bottom,
+ * against their source.
+ */
+import { describe, expect, it } from "vitest";
+import { readFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import {
+ activeTraceFile,
+ advanceTraceRefresh,
+ createTraceRefresh,
+ sortTraceFiles,
+} from "../src/features/traces/trace-refresh";
+
+const obs = (active: boolean, signal: number) => ({ active, signal });
+
+/**
+ * Source of the two components the rules are wired into. The suite renders no React, so a rule
+ * that lives inside an effect or a render guard is pinned against the text that implements it.
+ */
+const read = (p: string) => readFileSync(fileURLToPath(new URL(p, import.meta.url)), "utf8");
+const chatPage = read("../src/features/chat/chat-page.tsx");
+const panel = read("../src/features/traces/trace-panel.tsx");
+const fileView = read("../src/features/traces/trace-file-view.tsx");
+
+describe("advanceTraceRefresh (when the Trace panel re-fetches)", () => {
+ it("treats the panel's own first render as no edge — the fetch effect already loads on mount", () => {
+ const shown = createTraceRefresh(obs(true, 3));
+ expect(advanceTraceRefresh(shown, obs(true, 3))).toBe(false);
+ const hidden = createTraceRefresh(obs(false, 0));
+ expect(advanceTraceRefresh(hidden, obs(false, 0))).toBe(false);
+ });
+
+ it("re-fetches on the hidden→visible edge, and not on the way back", () => {
+ const s = createTraceRefresh(obs(false, 0));
+ expect(advanceTraceRefresh(s, obs(true, 0))).toBe(true);
+ // Still showing, nothing settled: renders alone must not fetch.
+ expect(advanceTraceRefresh(s, obs(true, 0))).toBe(false);
+ expect(advanceTraceRefresh(s, obs(false, 0))).toBe(false);
+ expect(advanceTraceRefresh(s, obs(true, 0))).toBe(true);
+ });
+
+ it("re-fetches when a turn settles while the panel is showing", () => {
+ const s = createTraceRefresh(obs(true, 0));
+ expect(advanceTraceRefresh(s, obs(true, 1))).toBe(true);
+ // One bump is one fetch: re-rendering at the same count does not fetch again.
+ expect(advanceTraceRefresh(s, obs(true, 1))).toBe(false);
+ expect(advanceTraceRefresh(s, obs(true, 2))).toBe(true);
+ });
+
+ it("fetches nothing for a hidden tab, and the re-show is what brings it current", () => {
+ const s = createTraceRefresh(obs(false, 0));
+ expect(advanceTraceRefresh(s, obs(false, 1))).toBe(false);
+ expect(advanceTraceRefresh(s, obs(false, 2))).toBe(false);
+ expect(advanceTraceRefresh(s, obs(false, 3))).toBe(false);
+ // Three turns went by unread; showing the tab again re-fetches ONCE, not once per turn.
+ expect(advanceTraceRefresh(s, obs(true, 3))).toBe(true);
+ expect(advanceTraceRefresh(s, obs(true, 3))).toBe(false);
+ });
+
+ it("counts a turn settling in the same observation as the re-show as one fetch", () => {
+ const s = createTraceRefresh(obs(false, 4));
+ expect(advanceTraceRefresh(s, obs(true, 5))).toBe(true);
+ expect(advanceTraceRefresh(s, obs(true, 5))).toBe(false);
+ });
+
+ it("reads any change of the counter as a bump, so a reset source cannot go unnoticed", () => {
+ const s = createTraceRefresh(obs(true, 7));
+ expect(advanceTraceRefresh(s, obs(true, 0))).toBe(true);
+ });
+});
+
+describe("the Trace file list across a re-fetch", () => {
+ const file = (index: number, sizeBytes = 100) => ({ index, date: "2026-08-26", sizeBytes });
+
+ it("orders the pill row newest first, without sorting the response in place", () => {
+ const res = [file(1), file(3), file(2)];
+ expect(sortTraceFiles(res).map((f) => f.index)).toEqual([3, 2, 1]);
+ expect(res.map((f) => f.index)).toEqual([1, 3, 2]);
+ });
+
+ it("keeps the selected file when a re-fetch returns it grown, or with newer files beside it", () => {
+ const before = sortTraceFiles([file(1, 200), file(2, 900)]);
+ expect(activeTraceFile(before, 1)?.index).toBe(1);
+ // The ordinary refresh: the SAME file, larger. The pick survives and reports the new size.
+ const grown = sortTraceFiles([file(1, 4200), file(2, 900)]);
+ expect(activeTraceFile(grown, 1)).toMatchObject({ index: 1, sizeBytes: 4200 });
+ // A compaction shard appearing must not yank the user onto it.
+ const withNew = sortTraceFiles([file(1, 4200), file(2, 900), file(3, 10)]);
+ expect(activeTraceFile(withNew, 1)?.index).toBe(1);
+ // Held as null it WOULD yank: the fallback is re-resolved on every re-list, so the shard
+ // that just appeared becomes the selection and the view below remounts onto it. That is
+ // the whole reason the panel pins a real index the first time a listing arrives — a reader
+ // who never clicked a pill is otherwise the one reader a refresh is allowed to disturb.
+ expect(activeTraceFile(withNew, null)?.index).toBe(3);
+ });
+
+ it("falls back to the newest file when the selection vanished, and to nothing when the Session has no Trace", () => {
+ const files = sortTraceFiles([file(4), file(5)]);
+ expect(activeTraceFile(files, 9)?.index).toBe(5);
+ // Null reaches here only before the first listing has been shown; the panel pins the
+ // default from that listing, so this fallback is what it pins TO.
+ expect(activeTraceFile(files, null)?.index).toBe(5);
+ expect(activeTraceFile([], null)).toBeNull();
+ expect(activeTraceFile([], 2)).toBeNull();
+ });
+});
+
+/**
+ * The decision has to reach both halves of the panel: the listing AND the file it is showing.
+ * A Trace file is appended to while the Session runs, so re-listing alone would refresh the
+ * sizes on the pills while the timeline below them stayed as it was read minutes ago.
+ */
+describe("the settled-turn signal's wiring", () => {
+ /** The identifier a mounted component is handed as its reloadSignal, or null. */
+ const signalOf = (tag: string) =>
+ new RegExp(`<${tag}[^>]*reloadSignal=\\{(\\w+)\\}`).exec(chatPage)?.[1] ?? null;
+
+ it("hands the Trace panel the very counter the Files panel refreshes on", () => {
+ expect(signalOf("WorkspaceBrowser")).not.toBeNull();
+ expect(signalOf("TracePanel")).toBe(signalOf("WorkspaceBrowser"));
+ });
+
+ it("carries it one level further, into the view that reads the selected file", () => {
+ expect(panel).toMatch(/<TraceFileView[^>]*reloadSignal=\{listTick\}/);
+ expect(panel).toMatch(
+ /advanceTraceRefresh\(refresh\.current, \{ active, signal: reloadSignal \}\)/,
+ );
+ });
+
+ it("re-runs the file's load on that signal, and clears no view state doing it", () => {
+ const load = fileView.slice(
+ fileView.indexOf("useEffect(() => {", fileView.indexOf("const fileKey")),
+ );
+ const body = load.slice(0, load.indexOf("\n }, ["));
+ const deps = /\n {2}\}, \[([^\]]*)\]/.exec(load)?.[1] ?? "";
+ expect(deps).toContain("reloadSignal");
+ // The collapsed rounds and the pinned row are cleared where a DIFFERENT file is adopted,
+ // never on a refresh of the one on screen.
+ expect(body).not.toContain("setCollapsed");
+ expect(body).not.toContain("setPinnedRow");
+ expect(fileView).toMatch(/renderedFileKey !== fileKey[\s\S]{0,320}setCollapsed\(new Set\(\)\)/);
+ });
+});
+
+/**
+ * What a refresh is allowed to move, now that one fires on every settled turn rather than only
+ * when the user brings the tab up. Both rules below are about the same reader: someone part-way
+ * through a Trace while the Session keeps working, who did nothing to ask for any of this.
+ */
+describe("what a settled-turn refresh must leave alone", () => {
+ /** The panel's listing effect, and the failure branch inside it. */
+ const listing = panel.slice(
+ panel.indexOf("getSessionTraces"),
+ panel.indexOf("}, [active, listTick"),
+ );
+ const listingFailure = listing.slice(listing.indexOf(".catch("));
+
+ it("pins the default selection to the first listing instead of re-resolving it each time", () => {
+ // activeTraceFile resolves a null pick to the newest file EVERY time it is called, so the
+ // panel has to commit to an index once rather than leave the default to that fallback.
+ expect(listing).toMatch(/setFileIndex\(\(cur\) => cur \?\?/);
+ // And the pin is one-way: the only other write is the user's own pill click.
+ expect(panel.match(/setFileIndex\(/g)).toHaveLength(2);
+ expect(panel).toMatch(/onClick=\{\(\) => setFileIndex\(f\.index\)\}/);
+ });
+
+ it("keeps the listing on screen when a re-list fails, reporting it beside the pills", () => {
+ // Emptying the list here would unmount the pills, the header, the download link and the
+ // whole file view below them — collapsed rounds, pinned row and scroll position included.
+ expect(listingFailure).not.toContain("setFiles");
+ expect(listingFailure).toContain("setError(");
+ expect(panel).toMatch(/\{error !== null && \([\s\S]{0,200}toneStrip\.danger/);
+ });
+
+ it("gives the panel over to the failure only when there is nothing to keep", () => {
+ // The two whole-panel failure states: no listing yet, and a listing with no file in it.
+ expect(panel).toMatch(
+ /if \(files === null\) \{\s*if \(error !== null\) return <EmptyState title=\{S\.tracePanel\.loadFailed\}/,
+ );
+ expect(panel).toMatch(
+ /if \(activeFile === null\) \{\s*if \(error !== null\) return <EmptyState title=\{S\.tracePanel\.loadFailed\}/,
+ );
+ });
+
+ it("keeps the file on screen when its re-read fails, reporting it above the summary", () => {
+ expect(fileView).toMatch(/if \(error !== null && analysis === null\)/);
+ expect(fileView).toMatch(/\{error !== null && <p /);
+ });
+
+ it("leaves the project's model catalog out of the refresh, on an effect of its own", () => {
+ const load = fileView.slice(
+ fileView.indexOf("useEffect(() => {", fileView.indexOf("const fileKey")),
+ );
+ // Pricing is a project-level catalog no turn produces: refetching it per settled turn was
+ // waste, and the `?? prev` guard that kept a failed refetch from dropping the cost column
+ // went with it.
+ expect(load.slice(0, load.indexOf("\n }, ["))).not.toContain("getModels");
+ expect(fileView).not.toContain("setModels((prev)");
+ const pricing = fileView.slice(fileView.indexOf("getModels(projectId)"));
+ expect(/\n {2}\}, \[([^\]]*)\]/.exec(pricing)?.[1]).toBe("projectId");
+ });
+});