Skip to content

πŸͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(web): track trace detail tab switches (Preview / Log View / Scores) (#17334)

Trang Nguyenc7909af5c987
diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
index e299b9ad3e..70333fb3c1 100644
--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts
+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
@@ -57,6 +57,22 @@ const events = {
// Raw download from the JSON-view fallback shown when a field is too large
// to render in the unvirtualized viewer (LFE-10989).
"json_view_large_field_download",
+ // Detail-panel tab switch (Preview / Log View / Scores). `tab` is the
+ // target tab, `target` is trace vs observation. Answers whether the Log
+ // View and Scores tabs earn their place.
+ "detail_tab_switch",
+ // Controls used *inside* the Log View tab, so a removal decision can weigh
+ // what people actually do there. `target` is trace vs observation;
+ // `action` is one of (see `LogViewAction` in TraceLogView.tsx):
+ // search_focus (once per focus, not per keystroke), indent_toggle,
+ // milliseconds_toggle, expand_all, collapse_all, row_expand, row_collapse,
+ // copy_json, json_mode_collapse_toggle, and view_mode_switch (the
+ // Formatted/JSON toggle, emitted by the hosting detail views).
+ // Metadata only β€” never an observation id or the search text.
+ "log_view_interaction",
+ // The JSON-view Beta switch (legacy JSON <-> virtualized json-beta).
+ // `enabled` is the new value. Decides whether json-beta graduates.
+ "json_beta_toggle",
],
// The shared table peek panel (opened via the `peek` URL param). Props carry
// `routePattern` (the Next.js route pattern, never a concrete URL) so opens
diff --git a/web/src/features/traces/components/ObservationDetailView/ConnectedObservationDetailView.tsx b/web/src/features/traces/components/ObservationDetailView/ConnectedObservationDetailView.tsx
index d07cdb4fa4..6a3718403e 100644
--- a/web/src/features/traces/components/ObservationDetailView/ConnectedObservationDetailView.tsx
+++ b/web/src/features/traces/components/ObservationDetailView/ConnectedObservationDetailView.tsx
@@ -49,6 +49,8 @@ import { getMostRecentCorrection } from "@/src/features/corrections/utils/getMos
import { useJsonExpansion } from "@/src/features/traces/contexts/JsonExpansionContext";
import { useMedia } from "@/src/features/traces/hooks/useMedia";
import { useSelection } from "@/src/features/traces/contexts/SelectionContext";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
+import { useTraceAnalyticsDimensions } from "@/src/features/traces/hooks/useTraceAnalyticsDimensions";
import { useViewPreferences } from "@/src/features/traces/contexts/ViewPreferencesContext";
// Contexts and hooks
@@ -88,6 +90,8 @@ export function ConnectedObservationDetailView({
setSelectedTab: setGlobalSelectedTab,
} = useSelection();
const utils = api.useUtils();
+ const capture = usePostHogClientCapture();
+ const analyticsDimensions = useTraceAnalyticsDimensions();
// V4 beta mode and observations for log tab
const { isV4: isV4Enabled } = useReadPath();
@@ -178,6 +182,13 @@ export function ConnectedObservationDetailView({
if (tab === "scores") {
refreshTraceScores();
}
+ if (tab !== selectedTab) {
+ capture("trace_detail:detail_tab_switch", {
+ tab,
+ target: "observation",
+ ...analyticsDimensions,
+ });
+ }
setGlobalSelectedTab(tab);
};
@@ -188,6 +199,14 @@ export function ConnectedObservationDetailView({
const handleViewTabChange = useCallback(
(tab: string) => {
+ if (selectedTab === "log") {
+ capture("trace_detail:log_view_interaction", {
+ action: "view_mode_switch",
+ target: "observation",
+ mode: tab,
+ ...analyticsDimensions,
+ });
+ }
if (tab === "pretty") {
setJsonViewPreference(tab);
} else {
@@ -195,15 +214,26 @@ export function ConnectedObservationDetailView({
setJsonViewPreference(jsonBetaEnabled ? "json-beta" : "json");
}
},
- [jsonBetaEnabled, setJsonViewPreference],
+ [
+ jsonBetaEnabled,
+ setJsonViewPreference,
+ selectedTab,
+ capture,
+ analyticsDimensions,
+ ],
);
const handleBetaToggle = useCallback(
(enabled: boolean) => {
+ capture("trace_detail:json_beta_toggle", {
+ enabled,
+ target: "observation",
+ ...analyticsDimensions,
+ });
setJsonBetaEnabled(enabled);
setJsonViewPreference(enabled ? "json-beta" : "json");
},
- [setJsonBetaEnabled, setJsonViewPreference],
+ [setJsonBetaEnabled, setJsonViewPreference, capture, analyticsDimensions],
);
// Get comments, scores, corrections, and expansion state from contexts
@@ -551,6 +581,7 @@ export function ConnectedObservationDetailView({
traceId={traceId}
projectId={projectId}
currentView={isLogViewVirtualized ? "pretty" : currentView}
+ target="observation"
/>
</TabsBarContent>
) : null}
diff --git a/web/src/features/traces/components/TraceDetailView/TraceDetailView.tsx b/web/src/features/traces/components/TraceDetailView/TraceDetailView.tsx
index a5e280e20c..d7e4acca7e 100644
--- a/web/src/features/traces/components/TraceDetailView/TraceDetailView.tsx
+++ b/web/src/features/traces/components/TraceDetailView/TraceDetailView.tsx
@@ -43,6 +43,8 @@ import { useParsedTrace } from "@/src/hooks/useParsedTrace";
import { useTraceData } from "@/src/features/traces/contexts/TraceDataContext";
import { useViewPreferences } from "@/src/features/traces/contexts/ViewPreferencesContext";
import { useSelection } from "@/src/features/traces/contexts/SelectionContext";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
+import { useTraceAnalyticsDimensions } from "@/src/features/traces/hooks/useTraceAnalyticsDimensions";
import { useIsAuthenticatedAndProjectMember } from "@/src/features/auth";
import { useCommentedPaths } from "@/src/features/comments/hooks/useCommentedPaths";
import { useHasProjectAccess } from "@/src/features/rbac";
@@ -78,6 +80,8 @@ export function TraceDetailView({
// Tab and view state from URL (via SelectionContext)
const { selectedTab, setSelectedTab } = useSelection();
const utils = api.useUtils();
+ const capture = usePostHogClientCapture();
+ const analyticsDimensions = useTraceAnalyticsDimensions();
const [isPrettyViewAvailable, setIsPrettyViewAvailable] = useState(true);
const [isJSONBetaVirtualized, setIsJSONBetaVirtualized] = useState(false);
@@ -101,21 +105,40 @@ export function TraceDetailView({
const handleViewTabChange = useCallback(
(tab: string) => {
+ if (selectedTab === "log") {
+ capture("trace_detail:log_view_interaction", {
+ action: "view_mode_switch",
+ target: "trace",
+ mode: tab,
+ ...analyticsDimensions,
+ });
+ }
if (tab === "pretty") {
setJsonViewPreference(tab);
} else {
setJsonViewPreference(jsonBetaEnabled ? "json-beta" : "json");
}
},
- [jsonBetaEnabled, setJsonViewPreference],
+ [
+ jsonBetaEnabled,
+ setJsonViewPreference,
+ selectedTab,
+ capture,
+ analyticsDimensions,
+ ],
);
const handleBetaToggle = useCallback(
(enabled: boolean) => {
+ capture("trace_detail:json_beta_toggle", {
+ enabled,
+ target: "trace",
+ ...analyticsDimensions,
+ });
setJsonBetaEnabled(enabled);
setJsonViewPreference(enabled ? "json-beta" : "json");
},
- [setJsonBetaEnabled, setJsonViewPreference],
+ [setJsonBetaEnabled, setJsonViewPreference, capture, analyticsDimensions],
);
// Context hooks
@@ -205,6 +228,13 @@ export function TraceDetailView({
if (value === "scores") {
refreshTraceScores();
}
+ if (value !== selectedTab) {
+ capture("trace_detail:detail_tab_switch", {
+ tab: value,
+ target: "trace",
+ ...analyticsDimensions,
+ });
+ }
setSelectedTab(value as "preview" | "log" | "scores");
};
@@ -457,6 +487,7 @@ export function TraceDetailView({
traceId={trace.id}
projectId={projectId}
currentView={isLogViewVirtualized ? "pretty" : currentView}
+ target="trace"
/>
</TabsBarContent>
diff --git a/web/src/features/traces/components/TraceLogView/LogViewToolbar.tsx b/web/src/features/traces/components/TraceLogView/LogViewToolbar.tsx
index 0832b348ae..474d3e3917 100644
--- a/web/src/features/traces/components/TraceLogView/LogViewToolbar.tsx
+++ b/web/src/features/traces/components/TraceLogView/LogViewToolbar.tsx
@@ -3,7 +3,7 @@
*
* Provides:
* - Search input for filtering observations (hidden in JSON view)
- * - Action buttons: expand/collapse all, copy JSON, download JSON
+ * - Action buttons: expand/collapse all, copy JSON
* - Large Trace indicator for virtualized mode
*/
@@ -12,7 +12,6 @@ import {
FoldVertical,
UnfoldVertical,
Copy,
- Download,
Check,
IndentIncrease,
Timer,
@@ -37,6 +36,8 @@ export interface LogViewToolbarProps {
searchQuery: string;
/** Callback when search query changes */
onSearchChange: (query: string) => void;
+ /** Callback when the search input gains focus (analytics: once per focus) */
+ onSearchFocus?: () => void;
/** Whether virtualization is active (for large traces) */
isVirtualized?: boolean;
/** Total number of observations (shown in Large Trace indicator) */
@@ -53,8 +54,6 @@ export interface LogViewToolbarProps {
isCopyOrDownloadCacheOnly?: boolean;
/** Callback to copy JSON */
onCopyJson?: () => void;
- /** Callback to download JSON */
- onDownloadJson?: () => void;
/** Current view type (pretty/json/json-beta) */
currentView?: "pretty" | "json" | "json-beta";
/** Whether indent visualization is enabled */
@@ -75,6 +74,7 @@ export interface LogViewToolbarProps {
export const LogViewToolbar = memo(function LogViewToolbar({
searchQuery,
onSearchChange,
+ onSearchFocus,
isVirtualized = true,
observationCount,
loadedObservationCount,
@@ -82,7 +82,6 @@ export const LogViewToolbar = memo(function LogViewToolbar({
allRowsExpanded,
onCopyJson,
isCopyOrDownloadLoading = false,
- onDownloadJson,
isCopyOrDownloadCacheOnly = false,
currentView = "pretty",
indentEnabled = false,
@@ -141,6 +140,7 @@ export const LogViewToolbar = memo(function LogViewToolbar({
className="h-7 border-0 focus:ring-0"
value={searchQuery}
onValueChange={onSearchChange}
+ onFocus={onSearchFocus}
/>
</Command>
)}
@@ -285,58 +285,6 @@ export const LogViewToolbar = memo(function LogViewToolbar({
)}
</HoverCard>
)}
-
- {/* Download JSON */}
- {onDownloadJson && (
- <HoverCard openDelay={200}>
- <HoverCardTrigger asChild>
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- variant="ghost"
- size="icon"
- className="h-7 w-7"
- onClick={
- isCopyOrDownloadLoading ? undefined : onDownloadJson
- }
- disabled={isCopyOrDownloadLoading}
- >
- {isCopyOrDownloadLoading ? (
- <Spinner size="xs" />
- ) : (
- <Download className="h-3.5 w-3.5" />
- )}
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- {isCopyOrDownloadLoading
- ? "Loading data..."
- : isCopyOrDownloadCacheOnly
- ? "Download as JSON (cache only)"
- : "Download as JSON"}
- </TooltipContent>
- </Tooltip>
- </HoverCardTrigger>
- {isCopyOrDownloadCacheOnly && !isCopyOrDownloadLoading && (
- <HoverCardContent className="w-64 text-sm" sideOffset={8}>
- <p className="font-bold">Cache-only mode</p>
- <p className="text-muted-foreground mt-1">
- For large traces, only expanded observations include full I/O
- data.
- </p>
- {loadedObservationCount !== undefined &&
- observationCount !== undefined && (
- <p className="text-muted-foreground mt-1.5">
- <span className="font-bold">
- {loadedObservationCount} of {observationCount}
- </span>{" "}
- observations loaded
- </p>
- )}
- </HoverCardContent>
- )}
- </HoverCard>
- )}
</div>
</div>
);
diff --git a/web/src/features/traces/components/TraceLogView/TraceLogView.tsx b/web/src/features/traces/components/TraceLogView/TraceLogView.tsx
index 3f9fa5daff..a8789ea663 100644
--- a/web/src/features/traces/components/TraceLogView/TraceLogView.tsx
+++ b/web/src/features/traces/components/TraceLogView/TraceLogView.tsx
@@ -9,7 +9,7 @@
* - Two view modes: chronological (by time) and tree-order (DFS hierarchy)
* - Search filtering by name, type, or ID
* - Expandable rows with full I/O preview
- * - Copy/Download JSON functionality
+ * - Copy JSON functionality
*
* Uses JSONTableView for table rendering with domain-specific column definitions.
*
@@ -33,6 +33,8 @@
import { useState, useMemo, useCallback } from "react";
import { TRACE_VIEW_CONFIG } from "@/src/features/traces/constants/traceViewConfig";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
+import { useTraceAnalyticsDimensions } from "@/src/features/traces/hooks/useTraceAnalyticsDimensions";
import { useTraceData } from "@/src/features/traces/contexts/TraceDataContext";
import { useViewPreferences } from "@/src/features/traces/contexts/ViewPreferencesContext";
import { useJsonExpansion } from "@/src/features/traces/contexts/JsonExpansionContext";
@@ -55,8 +57,28 @@ export interface TraceLogViewProps {
traceId: string;
projectId: string;
currentView?: "pretty" | "json" | "json-beta";
+ /** Which detail panel hosts this log view β€” analytics segmentation only. */
+ target?: "trace" | "observation";
}
+/**
+ * Log View controls reported as `action` on
+ * `trace_detail:log_view_interaction`. Kept as a union so a typo cannot
+ * silently create a new action value in PostHog. `view_mode_switch` is the one
+ * action emitted by the hosting detail views instead β€” the Formatted/JSON
+ * toggle lives in their tabs bar, not in this subtree.
+ */
+type LogViewAction =
+ | "search_focus"
+ | "indent_toggle"
+ | "milliseconds_toggle"
+ | "expand_all"
+ | "collapse_all"
+ | "row_expand"
+ | "row_collapse"
+ | "copy_json"
+ | "json_mode_collapse_toggle";
+
// Import configuration constants
const {
virtualizationThreshold: LOG_VIEW_VIRTUALIZATION_THRESHOLD,
@@ -70,10 +92,27 @@ export const TraceLogView = ({
traceId,
projectId,
currentView = "pretty",
+ target = "trace",
}: TraceLogViewProps) => {
const { roots, observations } = useTraceData();
const { logViewMode, logViewTreeStyle } = useViewPreferences();
const { formattedExpansion, setFormattedFieldExpansion } = useJsonExpansion();
+ const capture = usePostHogClientCapture();
+ const analyticsDimensions = useTraceAnalyticsDimensions();
+
+ // Single funnel for every Log View control so `action`/`target`/dimensions
+ // can never drift between call sites. Never pass ids or search text.
+ const captureLogView = useCallback(
+ (action: LogViewAction, properties?: Record<string, unknown>) => {
+ capture("trace_detail:log_view_interaction", {
+ action,
+ target,
+ ...properties,
+ ...analyticsDimensions,
+ });
+ },
+ [capture, target, analyticsDimensions],
+ );
// Determine if we should virtualize based on observation count
const isVirtualized =
@@ -116,6 +155,18 @@ export const TraceLogView = ({
[expandedKeys, setFormattedFieldExpansion, expandedRowsKey],
);
+ // Row chevron toggles only. `handleToggleExpandAll` keeps calling the raw
+ // setter so a bulk toggle is not also counted as a row toggle.
+ const handleExpandedKeysChange = useCallback(
+ (keys: Set<string>) => {
+ captureLogView(
+ keys.size > expandedKeys.size ? "row_expand" : "row_collapse",
+ );
+ setExpandedKeys(keys);
+ },
+ [captureLogView, expandedKeys, setExpandedKeys],
+ );
+
// Local state for search
const [searchQuery, setSearchQuery] = useState("");
@@ -215,6 +266,7 @@ export const TraceLogView = ({
// Toggle expand/collapse all (non-virtualized mode only)
const handleToggleExpandAll = useCallback(() => {
+ captureLogView(allRowsExpanded ? "collapse_all" : "expand_all");
if (allRowsExpanded) {
// Collapse all
setExpandedKeys(new Set());
@@ -223,7 +275,7 @@ export const TraceLogView = ({
const allKeys = new Set(flatItems.map((item) => item.node.id));
setExpandedKeys(allKeys);
}
- }, [allRowsExpanded, flatItems, setExpandedKeys]);
+ }, [allRowsExpanded, flatItems, setExpandedKeys, captureLogView]);
// On-demand loading hook for observation I/O data
// Does NOT auto-fetch - call loadAllData() or buildDataFromCache() when needed
@@ -240,10 +292,9 @@ export const TraceLogView = ({
projectId,
});
- // Download and copy handlers
- const { handleCopyJson, isActionLoading: isCopyOrDownloadLoading } =
+ // Copy handler
+ const { handleCopyJson: copyJson, isActionLoading: isCopyOrDownloadLoading } =
useLogViewDownload({
- traceId,
isCacheOnly: isCopyOrDownloadCacheOnly,
allObservationsData: allObservationsIO.data,
isLoadingAllData: allObservationsIO.isLoading,
@@ -252,10 +303,18 @@ export const TraceLogView = ({
buildDataFromCache: allObservationsIO.buildDataFromCache,
});
+ const handleCopyJson = useCallback(() => {
+ captureLogView("copy_json", { cacheOnly: isCopyOrDownloadCacheOnly });
+ return copyJson();
+ }, [captureLogView, copyJson, isCopyOrDownloadCacheOnly]);
+
// Toggle JSON view collapse
const handleToggleJsonCollapse = useCallback(() => {
+ captureLogView("json_mode_collapse_toggle", {
+ collapsed: !jsonViewCollapsed,
+ });
setJsonViewCollapsed((prev) => !prev);
- }, []);
+ }, [captureLogView, jsonViewCollapsed]);
// Check if there are any observations at all
const hasNoObservations = allItems.length === 0;
@@ -267,6 +326,7 @@ export const TraceLogView = ({
<LogViewToolbar
searchQuery={searchQuery}
onSearchChange={setSearchQuery}
+ onSearchFocus={() => captureLogView("search_focus")}
isVirtualized={isVirtualized}
observationCount={observations.length}
loadedObservationCount={loadedObservationCount}
@@ -278,9 +338,15 @@ export const TraceLogView = ({
currentView={currentView}
indentEnabled={indentEnabled}
indentDisabled={indentDisabled}
- onToggleIndent={() => setIndentEnabled(!indentEnabledPref)}
+ onToggleIndent={() => {
+ captureLogView("indent_toggle", { enabled: !indentEnabledPref });
+ setIndentEnabled(!indentEnabledPref);
+ }}
showMilliseconds={showMilliseconds}
- onToggleMilliseconds={() => setShowMilliseconds(!showMilliseconds)}
+ onToggleMilliseconds={() => {
+ captureLogView("milliseconds_toggle", { enabled: !showMilliseconds });
+ setShowMilliseconds(!showMilliseconds);
+ }}
/>
{/* Empty states */}
@@ -322,7 +388,7 @@ export const TraceLogView = ({
expandable
renderExpanded={renderExpanded}
expandedKeys={expandedKeys}
- onExpandedKeysChange={setExpandedKeys}
+ onExpandedKeysChange={handleExpandedKeysChange}
virtualized={isVirtualized}
overscan={100}
collapsedRowHeight={COLLAPSED_ROW_HEIGHT}
diff --git a/web/src/features/traces/components/TraceLogView/useLogViewAllObservationsIO.ts b/web/src/features/traces/components/TraceLogView/useLogViewAllObservationsIO.ts
index 11a7e5d4ee..b9f4f31e82 100644
--- a/web/src/features/traces/components/TraceLogView/useLogViewAllObservationsIO.ts
+++ b/web/src/features/traces/components/TraceLogView/useLogViewAllObservationsIO.ts
@@ -2,7 +2,7 @@
* Hook for on-demand batch-loading all observation I/O data.
*
* IMPORTANT: This hook does NOT fetch data automatically.
- * Call `loadAllData()` to trigger fetching when needed (e.g., download button click).
+ * Call `loadAllData()` to trigger fetching when needed (e.g., copy button click).
*
* This avoids creating 10k+ queries on mount which would freeze the browser.
*/
diff --git a/web/src/features/traces/components/TraceLogView/useLogViewDownload.clienttest.ts b/web/src/features/traces/components/TraceLogView/useLogViewDownload.clienttest.ts
index 59c089264e..b155cee13f 100644
--- a/web/src/features/traces/components/TraceLogView/useLogViewDownload.clienttest.ts
+++ b/web/src/features/traces/components/TraceLogView/useLogViewDownload.clienttest.ts
@@ -1,5 +1,5 @@
import { act, renderHook } from "@testing-library/react";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
import { useLogViewDownload } from "./useLogViewDownload";
import { type ObservationIOData } from "./useLogViewAllObservationsIO";
@@ -13,20 +13,6 @@ vi.mock("sonner", () => ({
toast: { success: vi.fn(), warning: vi.fn(), error: vi.fn() },
}));
-// jsdom implements neither URL.createObjectURL nor Blob#text.
-const createObjectURL = vi.fn<(blob: Blob) => string>();
-const revokeObjectURL = vi.fn();
-let lastBlob: Blob | undefined;
-
-function readBlobAsText(blob: Blob): Promise<string> {
- return new Promise((resolve, reject) => {
- const reader = new FileReader();
- reader.onload = () => resolve(String(reader.result));
- reader.onerror = () => reject(reader.error);
- reader.readAsText(blob);
- });
-}
-
// Escaped Japanese as ingested via the Python SDK's ensure_ascii=True.
const observations: ObservationIOData[] = [
{
@@ -43,7 +29,6 @@ const observations: ObservationIOData[] = [
function renderDownloadHook() {
return renderHook(() =>
useLogViewDownload({
- traceId: "trace-1",
isCacheOnly: false,
allObservationsData: observations,
isLoadingAllData: false,
@@ -54,30 +39,9 @@ function renderDownloadHook() {
);
}
-// jsdom ships no URL.createObjectURL, so capture whatever is (not) there and
-// restore it β€” Object.assign alone would leak the stub past this file if the
-// client project ever ran with a shared context.
-const originalCreateObjectURL = URL.createObjectURL;
-const originalRevokeObjectURL = URL.revokeObjectURL;
-
describe("useLogViewDownload", () => {
beforeEach(() => {
- lastBlob = undefined;
copyTextToClipboard.mockClear();
- createObjectURL.mockImplementation((blob: Blob) => {
- lastBlob = blob;
- return "blob:mock";
- });
- Object.assign(URL, { createObjectURL, revokeObjectURL });
- vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {});
- });
-
- afterEach(() => {
- Object.assign(URL, {
- createObjectURL: originalCreateObjectURL,
- revokeObjectURL: originalRevokeObjectURL,
- });
- vi.restoreAllMocks();
});
it("decodes \\uXXXX escapes in the copied JSON", async () => {
@@ -93,18 +57,4 @@ describe("useLogViewDownload", () => {
expect(copied).toContain("γ‚γ‚ŠγŒγ¨γ†");
expect(copied).not.toContain("\\u3053");
});
-
- it("decodes \\uXXXX escapes in the downloaded JSON", async () => {
- const { result } = renderDownloadHook();
-
- await act(async () => {
- await result.current.handleDownloadJson();
- });
-
- expect(lastBlob).toBeDefined();
- const content = await readBlobAsText(lastBlob!);
- expect(content).toContain("こんにけは");
- expect(content).toContain("γ‚γ‚ŠγŒγ¨γ†");
- expect(content).not.toContain("\\u3053");
- });
});
diff --git a/web/src/features/traces/components/TraceLogView/useLogViewDownload.ts b/web/src/features/traces/components/TraceLogView/useLogViewDownload.ts
index 7b32aa421b..5e735db3fd 100644
--- a/web/src/features/traces/components/TraceLogView/useLogViewDownload.ts
+++ b/web/src/features/traces/components/TraceLogView/useLogViewDownload.ts
@@ -1,9 +1,8 @@
/**
- * Hook for download and copy JSON functionality in LogView.
+ * Hook for copy JSON functionality in LogView.
*
* Handles:
* - Copy to clipboard (non-virtualized mode)
- * - Download as JSON file (both modes)
* - Loading state management
*/
@@ -14,8 +13,6 @@ import { copyTextToClipboard } from "@/src/utils/clipboard";
import { type ObservationIOData } from "./useLogViewAllObservationsIO";
export interface UseLogViewDownloadParams {
- /** Trace ID for filename */
- traceId: string;
/** Whether to use cached I/O only (vs loading all data) */
isCacheOnly: boolean;
/** Already loaded observation data (null if not loaded) */
@@ -31,10 +28,9 @@ export interface UseLogViewDownloadParams {
}
/**
- * Hook for managing download and copy JSON functionality.
+ * Hook for managing copy JSON functionality.
*/
export function useLogViewDownload({
- traceId,
isCacheOnly,
allObservationsData,
isLoadingAllData,
@@ -44,26 +40,11 @@ export function useLogViewDownload({
}: UseLogViewDownloadParams) {
const [isActionLoading, setIsActionLoading] = useState(false);
- // Helper to download JSON data. Serializes through the shared stringify
- // helper (not the raw JSON.stringify) so \uXXXX escapes in string fields
- // (e.g. Japanese ingested with Python ensure_ascii=True) are decoded to
- // real characters, matching the server-side trace download route.
- const downloadJsonData = useCallback(
- (data: unknown) => {
- const blob = new Blob([stringify(data, undefined, 2)], {
- type: "application/json",
- });
- const url = URL.createObjectURL(blob);
- const a = document.createElement("a");
- a.href = url;
- a.download = `trace-${traceId}.json`;
- a.click();
- URL.revokeObjectURL(url);
- },
- [traceId],
- );
-
- // Copy JSON handler - uses cache only or loads all based on threshold
+ // Copy JSON handler - uses cache only or loads all based on threshold.
+ // Serializes through the shared stringify helper (not the raw
+ // JSON.stringify) so \uXXXX escapes in string fields (e.g. Japanese
+ // ingested with Python ensure_ascii=True) are decoded to real characters,
+ // matching the server-side trace download route.
const handleCopyJson = useCallback(async () => {
if (isCacheOnly) {
// Cache-only mode: build from tree + cache (no fetching)
@@ -115,63 +96,8 @@ export function useLogViewDownload({
failedObservationIds,
]);
- // Download JSON handler - uses cache only or loads all based on threshold
- const handleDownloadJson = useCallback(async () => {
- if (isCacheOnly) {
- // Cache-only mode: build from tree + cache (no fetching)
- setIsActionLoading(true);
- // Use setTimeout to allow spinner to render before potentially heavy operation
- setTimeout(() => {
- try {
- const data = buildDataFromCache();
- downloadJsonData(data);
- toast.success("Downloaded trace data (cache only)");
- } finally {
- setIsActionLoading(false);
- }
- }, 0);
- } else {
- // Load all mode: fetch all data if needed
- if (allObservationsData) {
- downloadJsonData(allObservationsData);
- // Show warning if some observations failed to load
- if (failedObservationIds.length > 0) {
- toast.warning(
- `Downloaded trace data. ${failedObservationIds.length} observation${failedObservationIds.length === 1 ? "" : "s"} failed to load and ${failedObservationIds.length === 1 ? "is" : "are"} missing I/O data.`,
- );
- } else {
- toast.success("Downloaded trace data");
- }
- } else {
- setIsActionLoading(true);
- try {
- const data = await loadAllData();
- downloadJsonData(data);
- // Check for failures after loading
- if (failedObservationIds.length > 0) {
- toast.warning(
- `Downloaded trace data. ${failedObservationIds.length} observation${failedObservationIds.length === 1 ? "" : "s"} failed to load and ${failedObservationIds.length === 1 ? "is" : "are"} missing I/O data.`,
- );
- } else {
- toast.success("Downloaded trace data");
- }
- } finally {
- setIsActionLoading(false);
- }
- }
- }
- }, [
- isCacheOnly,
- allObservationsData,
- loadAllData,
- buildDataFromCache,
- downloadJsonData,
- failedObservationIds,
- ]);
-
return {
handleCopyJson,
- handleDownloadJson,
isActionLoading: isActionLoading || isLoadingAllData,
};
}