A local-first multi-agent app development platform, built on PenguinHarness
/**
* Trace panel — the current conversation's Trace files as a dock tab, wrapping the shared
* file view (performance timeline + event list) around one Session. The file pills page
* newest-first; the export link downloads the selected file raw. This is the ONLY way to
* read a Trace: the standalone cross-Session browsing page is gone, so a Trace is read
* where it was produced, as the "what did this conversation do" view. Importing a Trace
* from another install is the one thing that outlived the page — it moved to System
* 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, 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 "@adelie/server/api";
import { DownloadIcon, EmptyState, ICON_SIZE, NoticeStrip, Skeleton } from "@adelie/ui";
import * as api from "../../api/endpoints";
import { S } from "../../lib/strings";
import { apiErrorText } from "../../lib/api-error";
import { formatBytes } from "../../lib/format";
import { TraceFileView } from "./trace-file-view";
import { SseFrameList } from "./sse-frame-list";
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). */
const FILE_PILL_CAP = 6;
interface FileRef {
index: number;
date: string;
sizeBytes: number;
}
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, 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 refresh = useRef(createTraceRefresh({ active, signal: reloadSignal }));
useEffect(() => {
if (advanceTraceRefresh(refresh.current, { active, signal: reloadSignal })) {
setListTick((t) => t + 1);
}
}, [active, reloadSignal]);
useEffect(() => {
if (!active) return;
let cancelled = false;
void api
.getSessionTraces(session.sessionId)
.then((res) => {
if (cancelled) return;
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 open 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;
// 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 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 Transport view is rendered ABOVE these branches rather than inside the populated one:
// a Session with no Trace at all — nothing has run yet, or a run died before its first write —
// is exactly when "did the stream deliver anything" is the question being asked, and an empty
// state that swallowed the one view that answers it made the feature unreachable there.
const transport = <SseFrameList sessionId={session.sessionId} active={active} />;
// 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) {
return (
<div className="min-h-0 flex-1 overflow-y-auto p-3">
<div className="space-y-3">
{transport}
{error !== null ? (
<EmptyState title={S.tracePanel.loadFailed} description={error} />
) : (
<>
<Skeleton className="h-5 w-2/3" />
<Skeleton className="h-5 w-1/2" />
</>
)}
</div>
</div>
);
}
// 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) {
return (
<div className="min-h-0 flex-1 overflow-y-auto p-3">
<div className="space-y-3">
{transport}
{error !== null ? (
<EmptyState title={S.tracePanel.loadFailed} description={error} />
) : (
<EmptyState title={S.tracePanel.empty} description={S.tracePanel.emptyHint} />
)}
</div>
</div>
);
}
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 && (
<NoticeStrip tone="danger" as="p" className="rounded-md border px-2.5 py-1.5 text-xs">
{S.tracePanel.loadFailed} · {error}
</NoticeStrip>
)}
{/* What this browser received on the live streams (off unless switched off): the one
place a stalled stream can be told from a quiet one. */}
{transport}
<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) => (
<button
key={f.index}
type="button"
onClick={() => setFileIndex(f.index)}
data-tooltip={`${f.date} · ${formatBytes(f.sizeBytes)}`}
data-tooltip-extra
className={`rounded-md border px-2 py-0.5 font-mono text-xs transition-colors duration-150 ${
f.index === activeFile.index
? "border-gray-400 bg-gray-200/70 font-semibold text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100"
: "border-gray-200 text-gray-500 hover:bg-gray-100 dark:border-gray-800 dark:text-gray-400 dark:hover:bg-gray-800/60"
}`}
>
#{String(f.index).padStart(3, "0")}
</button>
))}
{!showAllFiles && files.length > FILE_PILL_CAP && (
<button
type="button"
data-tooltip={S.chat.loadMore}
aria-label={S.chat.loadMore}
onClick={() => setShowAllFiles(true)}
className="rounded-md border border-gray-200 px-2 py-0.5 font-mono text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-100 dark:border-gray-800 dark:text-gray-400 dark:hover:bg-gray-800/60"
>
+{files.length - FILE_PILL_CAP}
</button>
)}
</div>
<div className="flex flex-wrap items-center gap-2">
<p className="min-w-0 flex-1 truncate font-mono text-xs text-gray-400">
{activeFile.date} · {formatBytes(activeFile.sizeBytes)}
</p>
{/* Raw-file download for the selected Trace file (same styling as the inactive pills). */}
<a
href={api.agentTraceDownloadUrl(
session.projectId,
session.agentId,
session.sessionId,
activeFile.index,
)}
download
className="inline-flex shrink-0 items-center gap-1 rounded-md border border-gray-200 px-2 py-0.5 text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-100 dark:border-gray-800 dark:text-gray-400 dark:hover:bg-gray-800/60"
>
<DownloadIcon size={ICON_SIZE.rowLead} />
{S.traces.exportFile}
</a>
{/* Whole-Session export: one bundle file holding every compaction shard, so a long
Session can be moved to another install in one piece. Only offered when the Session
really has several shards — with one, the per-file download above IS the Session. */}
{files.length > 1 && (
<a
href={api.agentTraceBundleExportUrl(
session.projectId,
session.agentId,
session.sessionId,
)}
download
data-tooltip={S.traces.exportSessionHint}
className="inline-flex shrink-0 items-center gap-1 rounded-md border border-gray-200 px-2 py-0.5 text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-100 dark:border-gray-800 dark:text-gray-400 dark:hover:bg-gray-800/60"
>
<DownloadIcon size={ICON_SIZE.rowLead} />
{S.traces.exportSession}
</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}
/>
</div>
</div>
);
}