feat(server,web): import and export Trace files in the trace viewer (#73)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
@@ -57,6 +57,8 @@ import type {
|
||||
TaskCreateResponse,
|
||||
TraceAnalysisResponse,
|
||||
TraceEventsResponse,
|
||||
TraceImportRequest,
|
||||
TraceImportResponse,
|
||||
UiPrefs,
|
||||
UsageGroupBy,
|
||||
UsageResponse,
|
||||
@@ -332,6 +334,23 @@ export const getAgentTraceAnalysis = (
|
||||
`/traces/${encodeURIComponent(sessionId)}/${index}/analysis`,
|
||||
);
|
||||
|
||||
/** Trace file download URL: the server sets Content-Disposition attachment, usable directly in <a download>. */
|
||||
export const agentTraceDownloadUrl = (
|
||||
projectId: string,
|
||||
agentId: string,
|
||||
sessionId: string,
|
||||
index: number,
|
||||
): string =>
|
||||
`/api/projects/${encodeURIComponent(projectId)}/agents/${encodeURIComponent(agentId)}` +
|
||||
`/traces/${encodeURIComponent(sessionId)}/${index}/download`;
|
||||
|
||||
/** Imports a Trace JSONL file (owner only); the response says where the file landed (sessionId / index / date). */
|
||||
export const importAgentTrace = (projectId: string, agentId: string, body: TraceImportRequest) =>
|
||||
apiFetch<TraceImportResponse>(
|
||||
`/api/projects/${encodeURIComponent(projectId)}/agents/${encodeURIComponent(agentId)}/traces/import`,
|
||||
{ method: "POST", body },
|
||||
);
|
||||
|
||||
// Usage statistics ----------------------------------------------------------------------
|
||||
|
||||
export const getUsage = (
|
||||
|
||||
@@ -70,6 +70,50 @@ export function PlusIcon({
|
||||
);
|
||||
}
|
||||
|
||||
/** Download glyph (tray with a down arrow), used by export/download affordances. */
|
||||
export function DownloadIcon({ size = 13, className = "" }: { size?: number; className?: string }) {
|
||||
return (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
aria-hidden
|
||||
className={`shrink-0 ${className}`}
|
||||
>
|
||||
<path
|
||||
d="M12 4v11m0 0l-5-5m5 5l5-5M4 20h16"
|
||||
strokeWidth="1.7"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
/** Upload glyph (tray with an up arrow), used by import/upload affordances. */
|
||||
export function UploadIcon({ size = 13, className = "" }: { size?: number; className?: string }) {
|
||||
return (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
aria-hidden
|
||||
className={`shrink-0 ${className}`}
|
||||
>
|
||||
<path
|
||||
d="M12 15V4m0 0L7 9m5-5l5 5M4 20h16"
|
||||
strokeWidth="1.7"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The X close button shared by the Modal / Drawer / Sheet headers: same glyph,
|
||||
* padding and hover treatment. Extra button props (e.g. Sheet's onPointerDown
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
* analysis (an execution timeline) + an event timeline.
|
||||
*/
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import type { ChangeEvent } from "react";
|
||||
import { useSearchParams } from "react-router";
|
||||
import type { AgentTracesResponse } from "@prismshadow/penguin-server/api";
|
||||
import * as api from "../../api/endpoints";
|
||||
@@ -16,6 +17,8 @@ import { formatBytes } from "../../lib/format";
|
||||
import { agentDisplayName, useProject } from "../../state/project";
|
||||
import { AgentAvatar } from "../../components/ui/agent-avatar";
|
||||
import { Chevron } from "../../components/ui/chevron";
|
||||
import { DownloadIcon, UploadIcon } from "../../components/ui/icons";
|
||||
import { toastError } from "../../components/ui/toast";
|
||||
import { Truncated } from "../../components/ui/truncated";
|
||||
import { useSessions } from "../../state/sessions";
|
||||
import { EmptyState } from "../../components/ui/empty-state";
|
||||
@@ -23,6 +26,14 @@ import { SkeletonList } from "../../components/ui/skeleton";
|
||||
import { TraceFileView } from "./trace-file-view";
|
||||
import type { TraceHighlight } from "./timeline-chart";
|
||||
|
||||
/**
|
||||
* Import file size cap, mirroring the server's route-side limit (agent-traces.ts).
|
||||
* Checked on the raw picked file before it is read: base64-encoding an oversized
|
||||
* pick and uploading it just to receive the server's 400 would materialize and
|
||||
* send many times the cap for nothing.
|
||||
*/
|
||||
const MAX_TRACE_BYTES = 14 * 1024 * 1024;
|
||||
|
||||
interface TraceFileRef {
|
||||
index: number;
|
||||
date: string;
|
||||
@@ -67,6 +78,7 @@ function AgentNode({
|
||||
name,
|
||||
defaultOpen,
|
||||
focusSessionId,
|
||||
canImport,
|
||||
titleOf,
|
||||
selection,
|
||||
onSelect,
|
||||
@@ -78,6 +90,8 @@ function AgentNode({
|
||||
defaultOpen: boolean;
|
||||
/** ?sessionId= deep link (jumped to directly from the evaluation center's runs): auto-selects that Session once the list is ready (only once). */
|
||||
focusSessionId?: string;
|
||||
/** Trace import is owner-only on the server; non-owners don't get the button. */
|
||||
canImport: boolean;
|
||||
titleOf: (agentId: string, sessionId: string) => string | undefined;
|
||||
selection: Selection | null;
|
||||
onSelect: (sel: Selection) => void;
|
||||
@@ -85,6 +99,9 @@ function AgentNode({
|
||||
const [open, setOpen] = useState(defaultOpen);
|
||||
const [groups, setGroups] = useState<SessionGroup[] | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [importing, setImporting] = useState(false);
|
||||
/** Session to auto-select once the refreshed list arrives (the import response's sessionId). */
|
||||
const importedSession = useRef<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || groups) return;
|
||||
@@ -106,6 +123,53 @@ function AgentNode({
|
||||
if (target) onSelect({ agentId, sessionId: target.sessionId, files: target.files });
|
||||
}, [groups, focusSessionId, agentId, onSelect]);
|
||||
|
||||
// Post-import selection: once the refreshed list is in, select the imported
|
||||
// Session — an import always creates a new Session whose only file is the
|
||||
// imported one, so the default file pick is the imported file.
|
||||
useEffect(() => {
|
||||
const sid = importedSession.current;
|
||||
if (sid === null || !groups) return;
|
||||
importedSession.current = null;
|
||||
const target = groups.find((g) => g.sessionId === sid);
|
||||
if (target) onSelect({ agentId, sessionId: target.sessionId, files: target.files });
|
||||
}, [groups, agentId, onSelect]);
|
||||
|
||||
const runImport = async (dataBase64: string) => {
|
||||
setImporting(true);
|
||||
try {
|
||||
const res = await api.importAgentTrace(projectId, agentId, { dataBase64 });
|
||||
// Drop the cached list so the fetch effect above reloads it; the effect
|
||||
// watching `groups` then jumps to the imported Session.
|
||||
importedSession.current = res.sessionId;
|
||||
setGroups(null);
|
||||
setOpen(true);
|
||||
} catch (e: unknown) {
|
||||
// Transient action failure → toast (the app's one notification rule; a
|
||||
// rejected import isn't a state of the tree, unlike the load error below).
|
||||
toastError(apiErrorText(e));
|
||||
} finally {
|
||||
setImporting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const onPickFile = (e: ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
// Reset before reading so re-picking the same file fires change again.
|
||||
e.target.value = "";
|
||||
if (!file) return;
|
||||
if (file.size > MAX_TRACE_BYTES) {
|
||||
toastError(S.traces.fileTooLarge);
|
||||
return;
|
||||
}
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
const url = reader.result as string;
|
||||
void runImport(url.slice(url.indexOf(",") + 1)); // strip the data:...;base64, prefix
|
||||
};
|
||||
reader.onerror = () => toastError(S.common.unknownError);
|
||||
reader.readAsDataURL(file);
|
||||
};
|
||||
|
||||
// The group header and Session row styling matches the sidebar
|
||||
// (components/layout/sidebar.tsx): the same information appearing in two
|
||||
// places with a different shape would make it look like two different things.
|
||||
@@ -126,9 +190,29 @@ function AgentNode({
|
||||
<Chevron open={open} size={12} className="text-gray-400" />
|
||||
<span className="min-w-0 flex-1" />
|
||||
</button>
|
||||
{canImport && (
|
||||
<label
|
||||
title={importing ? S.traces.importing : S.traces.importTrace}
|
||||
className={`shrink-0 cursor-pointer rounded p-1 text-gray-400 transition-colors duration-150 hover:bg-gray-200/50 hover:text-gray-600 dark:hover:bg-gray-800/50 dark:hover:text-gray-300 ${
|
||||
importing ? "pointer-events-none opacity-60" : ""
|
||||
}`}
|
||||
>
|
||||
{/* sr-only rather than hidden: keeps it keyboard-Tab-focusable (same as the snapshot import). */}
|
||||
<input
|
||||
type="file"
|
||||
accept=".jsonl"
|
||||
className="sr-only"
|
||||
disabled={importing}
|
||||
onChange={onPickFile}
|
||||
/>
|
||||
<UploadIcon size={13} />
|
||||
<span className="sr-only">{importing ? S.traces.importing : S.traces.importTrace}</span>
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
{open && (
|
||||
<div className="anim-fade">
|
||||
{/* Load failure of the tree itself stays inline (the one-notification-rule keeps load states with their content, not in a disappearing toast). */}
|
||||
{error && <p className="px-2.5 py-1 text-xs text-red-500">{error}</p>}
|
||||
{!groups && !error && (
|
||||
<p className="px-2.5 py-1 text-xs text-gray-400">{S.common.loading}</p>
|
||||
@@ -232,6 +316,7 @@ export function TracesPage() {
|
||||
{...(focusSessionId !== null && focusAgentId === a.agentId
|
||||
? { focusSessionId }
|
||||
: {})}
|
||||
canImport={currentProject?.role === "owner"}
|
||||
titleOf={titleOf}
|
||||
selection={selection}
|
||||
onSelect={(sel) => {
|
||||
@@ -275,9 +360,25 @@ export function TracesPage() {
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<p className="truncate font-mono text-xs text-gray-400">
|
||||
{selection.sessionId} · {activeFile.date} · {formatBytes(activeFile.sizeBytes)}
|
||||
</p>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<p className="min-w-0 flex-1 truncate font-mono text-xs text-gray-400">
|
||||
{selection.sessionId} · {activeFile.date} · {formatBytes(activeFile.sizeBytes)}
|
||||
</p>
|
||||
{/* Raw-file download for the selected Trace file (same styling as the inactive file pills). */}
|
||||
<a
|
||||
href={api.agentTraceDownloadUrl(
|
||||
projectId,
|
||||
selection.agentId,
|
||||
selection.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={12} />
|
||||
{S.traces.exportFile}
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<TraceFileView
|
||||
projectId={projectId}
|
||||
|
||||
@@ -846,6 +846,11 @@ When done, open index.html in a browser and self-test once.`,
|
||||
inProgress: "in progress",
|
||||
systemPrompt: "System prompt",
|
||||
toolDefs: (n: number) => `Tool definitions (${n})`,
|
||||
exportFile: "Export",
|
||||
importTrace: "Import Trace",
|
||||
importing: "Importing…",
|
||||
/** Client-side pre-check before reading the picked file (same cap as the server's import route). */
|
||||
fileTooLarge: "The file exceeds the 14MB limit.",
|
||||
},
|
||||
|
||||
benchmark: {
|
||||
@@ -899,6 +904,9 @@ When done, open index.html in a browser and self-test once.`,
|
||||
task_in_progress: "This Session already has a task running.",
|
||||
version_conflict: "The snapshot's version is not newer than the current one.",
|
||||
invalid_title: "The title is invalid.",
|
||||
invalid_trace: "This file is not a valid Trace file.",
|
||||
trace_session_exists:
|
||||
"This agent already has a Session with that id; a duplicate Trace cannot be imported.",
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -825,6 +825,11 @@ Penguin 视觉风格(见 web-design 技能),深色/浅色主题(<html da
|
||||
inProgress: "进行中",
|
||||
systemPrompt: "系统提示词",
|
||||
toolDefs: (n: number) => `工具定义(${n})`,
|
||||
exportFile: "导出",
|
||||
importTrace: "导入 Trace",
|
||||
importing: "导入中…",
|
||||
/** Client-side pre-check before reading the picked file (same cap as the server's import route). */
|
||||
fileTooLarge: "文件超过 14MB 上限。",
|
||||
},
|
||||
|
||||
benchmark: {
|
||||
@@ -882,6 +887,8 @@ Penguin 视觉风格(见 web-design 技能),深色/浅色主题(<html da
|
||||
task_in_progress: "该 Session 已有任务在运行。",
|
||||
version_conflict: "快照版本不高于当前版本。",
|
||||
invalid_title: "标题无效。",
|
||||
invalid_trace: "该文件不是有效的 Trace 文件。",
|
||||
trace_session_exists: "该 Agent 已存在同名 Session,无法导入重复的 Trace。",
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user