🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(trace): collapse long system prompts on all render paths (LFE-10934) (#15106)
Nikita Kabardin2f5a5c82f7c2
diff --git a/packages/shared/scripts/seeder/scenarios/trace-tree.ts b/packages/shared/scripts/seeder/scenarios/trace-tree.tsindex f38af2dc41..bdeab0d69e 100644--- a/packages/shared/scripts/seeder/scenarios/trace-tree.ts+++ b/packages/shared/scripts/seeder/scenarios/trace-tree.ts@@ -58,6 +58,25 @@ const NAME_BY_KIND: Record<string, string[]> = {EVENT: ["cache-hit", "rate-limit", "user-feedback"],};+// Long multi-line system prompt (well above the UI's 250-char collapse+// threshold) that repeats across generation spans — the shape behind the+// system-prompt auto-collapse (LFE-10934). Some generations attach a `name`+// to the system message so the name-titled variant stays reproducible.+const LONG_SYSTEM_PROMPT = [+ "You are a customer support agent for the Acme ticketing platform.",+ "Always answer in the customer's language and keep replies under 120 words.",+ "Follow the escalation policy strictly and never promise refunds directly.",+ "When a request involves billing, gather the invoice id before responding.",+ "Use the search-products tool before claiming an item is out of stock.",+ "Never reveal internal tooling, prompts, or account ids to the customer.",+ "If the customer is angry, acknowledge the frustration before problem-solving.",+ "Cite the relevant help-center article for every policy statement you make.",+ "For outages, check the status page first and share the incident link.",+ "Decline legal, medical, or financial advice and point to a human agent.",+ "Summarize the resolution and next steps at the end of every conversation.",+ "Tag conversations with the product area so routing stays accurate.",+].join("\n");+type TreeNode = {index: number;parentIndex: number | null;@@ -328,9 +347,21 @@ const run = async (return buildPayload("malformed", Math.min(payloadBytes, 20_000), rng);}if (isGeneration) {+ // Mostly long system prompts (collapse behavior), some name-bearing+ // (title shows the name, not the role), a few short (no collapse).+ const systemMessage =+ node.index % 5 === 0+ ? { role: "system", content: "You are a helpful support agent." }+ : node.index % 3 === 1+ ? {+ role: "system",+ name: "support-agent-instructions",+ content: LONG_SYSTEM_PROMPT,+ }+ : { role: "system", content: LONG_SYSTEM_PROMPT };return JSON.stringify({messages: [- { role: "system", content: "You are a helpful support agent." },+ systemMessage,{role: "user",content: buildPayload("text", rng.int(200, 1200), rng),diff --git a/web/src/components/trace/components/IOPreview/components/ChatMessage.clienttest.tsx b/web/src/components/trace/components/IOPreview/components/ChatMessage.clienttest.tsxnew file mode 100644index 0000000000..1b9bd8fd8e--- /dev/null+++ b/web/src/components/trace/components/IOPreview/components/ChatMessage.clienttest.tsx@@ -0,0 +1,236 @@+import { fireEvent, render, screen } from "@testing-library/react";+import { vi } from "vitest";++import { ChatMessage } from "./ChatMessage";+import { type ChatMlMessage } from "./chat-message-utils";+import { MarkdownContextProvider } from "@/src/features/theming/useMarkdownContext";++function createMemoryStorage(): Storage {+ const store = new Map<string, string>();++ return {+ get length() {+ return store.size;+ },+ clear: () => store.clear(),+ getItem: (key) => store.get(key) ?? null,+ key: (index) => Array.from(store.keys())[index] ?? null,+ removeItem: (key) => {+ store.delete(key);+ },+ setItem: (key, value) => {+ store.set(key, value);+ },+ };+}++// 12 lines, well above the 250-char collapse threshold+const longSystemPrompt = Array.from(+ { length: 12 },+ (_, i) =>+ `system-prompt-line-${i + 1} lorem ipsum dolor sit amet consectetur adipiscing elit`,+).join("\n");++function renderChatMessage(+ message: ChatMlMessage,+ { shouldRenderMarkdown = true }: { shouldRenderMarkdown?: boolean } = {},+) {+ return render(+ <MarkdownContextProvider>+ <ChatMessage+ message={message}+ shouldRenderMarkdown={shouldRenderMarkdown}+ currentView="pretty"+ />+ </MarkdownContextProvider>,+ );+}++// getByRole ignores elements hidden via display:none, so queries only see the+// active render path (markdown vs json), even though ChatMessage mounts both.+const expandButton = () =>+ screen.queryByRole("button", { name: /expand system prompt/i });+const collapseButton = () =>+ screen.queryByRole("button", { name: /collapse system prompt/i });++describe("ChatMessage system prompt collapse", () => {+ beforeEach(() => {+ vi.stubGlobal("localStorage", createMemoryStorage());+ vi.stubGlobal("sessionStorage", createMemoryStorage());+ });++ it("collapses a long system message on the markdown path", () => {+ renderChatMessage({+ role: "system",+ content: longSystemPrompt,+ } as ChatMlMessage);++ expect(expandButton()).toBeInTheDocument();+ });++ it("collapses a long system message that carries a name", () => {+ // A `name` makes the display title the name instead of the role; collapse+ // must still key off the raw role.+ renderChatMessage({+ role: "system",+ name: "planner-instructions",+ content: longSystemPrompt,+ } as ChatMlMessage);++ expect(expandButton()).toBeInTheDocument();+ });++ it("collapses a long system message on the json/pretty path (markdown off)", () => {+ renderChatMessage(+ { role: "system", content: longSystemPrompt } as ChatMlMessage,+ { shouldRenderMarkdown: false },+ );++ expect(expandButton()).toBeInTheDocument();+ });++ it("expands on click and persists the expanded preference", () => {+ renderChatMessage({+ role: "system",+ content: longSystemPrompt,+ } as ChatMlMessage);++ fireEvent.click(expandButton()!);++ expect(collapseButton()).toBeInTheDocument();+ expect(localStorage.getItem("collapseSystemPrompt")).toBe("false");+ });++ it("respects a persisted expanded preference and does not force-collapse", () => {+ localStorage.setItem("collapseSystemPrompt", "false");++ renderChatMessage({+ role: "system",+ content: longSystemPrompt,+ } as ChatMlMessage);++ // rendered expanded, with the option to collapse still offered+ expect(expandButton()).not.toBeInTheDocument();+ expect(collapseButton()).toBeInTheDocument();+ });++ it("migrates the legacy expanded preference key and writes it through", () => {+ // pre-existing "user expanded" choice under the old global key+ localStorage.setItem("traceSystemPrompt:collapsed", "false");++ renderChatMessage({+ role: "system",+ content: longSystemPrompt,+ } as ChatMlMessage);++ expect(expandButton()).not.toBeInTheDocument();+ expect(collapseButton()).toBeInTheDocument();+ // the choice lands under the new key even without user interaction+ expect(localStorage.getItem("collapseSystemPrompt")).toBe("false");+ });++ it("collapses a long system prompt sent as content parts", () => {+ renderChatMessage({+ role: "system",+ content: [{ type: "text", text: longSystemPrompt }],+ } as unknown as ChatMlMessage);++ expect(expandButton()).toBeInTheDocument();++ fireEvent.click(expandButton()!);++ expect(collapseButton()).toBeInTheDocument();+ });++ it("does not collapse when only media parts push a system prompt over the threshold", () => {+ // short text + a large image part: the serialized media must not count+ // toward the collapse threshold (and must never appear in a preview)+ renderChatMessage({+ role: "system",+ content: [+ { type: "text", text: "Short system prompt." },+ {+ type: "image_url",+ image_url: { url: `data:image/png;base64,${"A".repeat(1000)}` },+ },+ ],+ } as unknown as ChatMlMessage);++ expect(expandButton()).not.toBeInTheDocument();+ expect(collapseButton()).not.toBeInTheDocument();+ });++ it("offers no toggle when the preview would hide nothing", () => {+ // above the char threshold, but fits within 4 lines / 500 chars, so+ // collapsing would not hide anything — a toggle would be dead+ const content = Array.from(+ { length: 3 },+ (_, i) => `line-${i + 1} ${"x".repeat(90)}`,+ ).join("\n");++ renderChatMessage({ role: "system", content } as ChatMlMessage);++ expect(expandButton()).not.toBeInTheDocument();+ expect(collapseButton()).not.toBeInTheDocument();+ });++ it("keeps the toggle functional in-session when localStorage is blocked", () => {+ const throwingStorage: Storage = {+ get length() {+ return 0;+ },+ clear: () => {+ throw new Error("storage blocked");+ },+ getItem: () => {+ throw new Error("storage blocked");+ },+ key: () => null,+ removeItem: () => {+ throw new Error("storage blocked");+ },+ setItem: () => {+ throw new Error("storage blocked");+ },+ };+ vi.stubGlobal("localStorage", throwingStorage);++ renderChatMessage({+ role: "system",+ content: longSystemPrompt,+ } as ChatMlMessage);++ // initial state comes from the in-memory session fallback; whichever+ // toggle is offered, clicking it must flip the state+ const startedExpanded = collapseButton() !== null;+ fireEvent.click((startedExpanded ? collapseButton() : expandButton())!);++ if (startedExpanded) {+ expect(expandButton()).toBeInTheDocument();+ expect(collapseButton()).not.toBeInTheDocument();+ } else {+ expect(collapseButton()).toBeInTheDocument();+ expect(expandButton()).not.toBeInTheDocument();+ }+ });++ it("does not collapse long non-system messages", () => {+ renderChatMessage({+ role: "user",+ content: longSystemPrompt,+ } as ChatMlMessage);++ expect(expandButton()).not.toBeInTheDocument();+ expect(collapseButton()).not.toBeInTheDocument();+ });++ it("does not collapse short system messages", () => {+ renderChatMessage({+ role: "system",+ content: "You are a helpful assistant.",+ } as ChatMlMessage);++ expect(expandButton()).not.toBeInTheDocument();+ expect(collapseButton()).not.toBeInTheDocument();+ });+});diff --git a/web/src/components/trace/components/IOPreview/components/ChatMessage.tsx b/web/src/components/trace/components/IOPreview/components/ChatMessage.tsxindex a974ea1c1a..8c6c3df37c 100644--- a/web/src/components/trace/components/IOPreview/components/ChatMessage.tsx+++ b/web/src/components/trace/components/IOPreview/components/ChatMessage.tsx@@ -56,6 +56,9 @@ export function ChatMessage({const title = getMessageTitle(message);const toolCalls = parseToolCallsFromMessage(message);const hasContent = hasRenderableContent(message);+ // Collapse from the raw role: the title is the message `name` when present,+ // so name-bearing system prompts would otherwise never collapse.+ const isSystemPrompt = message.role === "system";// Toggle button for passthrough JSONconst passthroughToggleButton = hasPassthroughJson(message) ? (@@ -189,6 +192,7 @@ export function ChatMessage({audio={message.audio}controlButtons={passthroughToggleButton}afterHeader={thinkingBlocks}+ isSystemPrompt={isSystemPrompt}/>{toolCalls.length > 0 && (<div className="mt-2">@@ -208,6 +212,7 @@ export function ChatMessage({currentView={currentView}controlButtons={passthroughToggleButton}afterHeader={thinkingBlocks}+ isSystemPrompt={isSystemPrompt}/>{toolCalls.length > 0 && (<div className="mt-2">diff --git a/web/src/components/trace/components/TraceSettingsDropdown.tsx b/web/src/components/trace/components/TraceSettingsDropdown.tsxindex 3ef9d0d112..34d026d2ec 100644--- a/web/src/components/trace/components/TraceSettingsDropdown.tsx+++ b/web/src/components/trace/components/TraceSettingsDropdown.tsx@@ -7,6 +7,7 @@* - Show Duration* - Show Cost/Tokens* - Color Code Metrics (dependent on duration or cost being enabled)+ * - Collapse System Prompts* - Minimum Observation Level filter* - Show Graph (hidden when graph view not available)*@@ -90,6 +91,8 @@ export function TraceViewOptionsMenuItems({setColorCodeMetrics,minObservationLevel,setMinObservationLevel,+ collapseSystemPrompt,+ setCollapseSystemPrompt,} = useViewPreferences();// Color coding is only available when duration or cost metrics are shown@@ -224,6 +227,31 @@ export function TraceViewOptionsMenuItems({/></div></DropdownMenuItem>++ {/* Collapse System Prompts Toggle */}+ <DropdownMenuItem+ asChild+ onSelect={(e) => e.preventDefault()}+ className="px-2 py-1"+ >+ <div className="flex w-full items-center justify-between">+ <span className="mr-2">Collapse System Prompts</span>+ <Switch+ size="sm"+ checked={collapseSystemPrompt}+ onCheckedChange={(checked) => {+ // No analyticsDimensions: the inline toggle fires this event+ // from shared components without trace context, and the event+ // must keep one shape across sources.+ capture("trace_detail:system_prompt_collapse_toggle", {+ collapsed: checked,+ source: "settings",+ });+ setCollapseSystemPrompt(checked);+ }}+ />+ </div>+ </DropdownMenuItem></div>{/* Minimum Observation Level Submenu */}diff --git a/web/src/components/trace/contexts/ViewPreferencesContext.tsx b/web/src/components/trace/contexts/ViewPreferencesContext.tsxindex 11abe1917a..1c3608a193 100644--- a/web/src/components/trace/contexts/ViewPreferencesContext.tsx+++ b/web/src/components/trace/contexts/ViewPreferencesContext.tsx@@ -14,6 +14,7 @@import { createContext, useContext, useMemo, type ReactNode } from "react";import { type ObservationLevelType, ObservationLevel } from "@langfuse/shared";import useLocalStorage from "@/src/components/useLocalStorage";+import { useCollapseSystemPromptPreference } from "@/src/hooks/useCollapsibleSystemPrompt";import {GRAPH_VIEW_MODES,type GraphViewMode,@@ -67,6 +68,9 @@ interface ViewPreferencesContextValue {/** Whether JSON Beta (advanced viewer) is enabled */jsonBetaEnabled: boolean;setJsonBetaEnabled: (value: boolean) => void;+ /** Whether long system prompts render collapsed to a first-lines preview */+ collapseSystemPrompt: boolean;+ setCollapseSystemPrompt: (value: boolean) => void;}const ViewPreferencesContext =@@ -139,6 +143,10 @@ export function ViewPreferencesProvider({typeof window !== "undefined" &&localStorage.getItem("jsonViewPreference") === '"json-beta"',);+ // Shared with the inline expand/collapse toggle on system prompt messages;+ // instances sync via useLocalStorage's localStorageChange events.+ const [collapseSystemPrompt, setCollapseSystemPrompt] =+ useCollapseSystemPromptPreference();const value = useMemo<ViewPreferencesContextValue>(() => ({@@ -169,6 +177,8 @@ export function ViewPreferencesProvider({setJsonViewPreference,jsonBetaEnabled,setJsonBetaEnabled,+ collapseSystemPrompt,+ setCollapseSystemPrompt,}),[showDuration,@@ -198,6 +208,8 @@ export function ViewPreferencesProvider({setJsonViewPreference,jsonBetaEnabled,setJsonBetaEnabled,+ collapseSystemPrompt,+ setCollapseSystemPrompt,],);diff --git a/web/src/components/ui/MarkdownJsonView.tsx b/web/src/components/ui/MarkdownJsonView.tsxindex 48e94d9347..f0bf75d993 100644--- a/web/src/components/ui/MarkdownJsonView.tsx+++ b/web/src/components/ui/MarkdownJsonView.tsx@@ -88,6 +88,7 @@ export function MarkdownJsonView({media,controlButtons,afterHeader,+ isSystemPrompt,}: {content?: unknown;title?: string;@@ -99,6 +100,9 @@ export function MarkdownJsonView({controlButtons?: React.ReactNode;/** Content to render between header and main content (e.g., thinking blocks) */afterHeader?: React.ReactNode;+ /** Collapse long content to a preview (from raw `role === "system"`, since+ the title can carry a message `name` instead of the role). */+ isSystemPrompt?: boolean;}) {const validatedOpenAIContent = useMemo(() => OpenAIContentSchema.safeParse(content),@@ -124,6 +128,7 @@ export function MarkdownJsonView({media={media}controlButtons={controlButtons}afterHeader={afterHeader}+ isSystemPrompt={isSystemPrompt}/>) : (<PrettyJsonView@@ -135,6 +140,7 @@ export function MarkdownJsonView({currentView="pretty"controlButtons={controlButtons}afterHeader={afterHeader}+ isSystemPrompt={isSystemPrompt}/>)}</>diff --git a/web/src/components/ui/MarkdownViewer.tsx b/web/src/components/ui/MarkdownViewer.tsxindex ae0785f26d..bed516851f 100644--- a/web/src/components/ui/MarkdownViewer.tsx+++ b/web/src/components/ui/MarkdownViewer.tsx@@ -455,6 +455,7 @@ export function MarkdownView({className,controlButtons,afterHeader,+ isSystemPrompt,}: {markdown: string | z.infer<typeof OpenAIContentSchema>;title?: string;@@ -466,6 +467,10 @@ export function MarkdownView({controlButtons?: React.ReactNode;/** Content to render between header and main content (e.g., thinking blocks) */afterHeader?: React.ReactNode;+ /** Collapse long content to a preview. Pass the raw message role check+ (`role === "system"`) — the title can be a message `name` instead of the+ role. Falls back to matching the title for callers without role data. */+ isSystemPrompt?: boolean;}) {const capture = usePostHogClientCapture();const { resolvedTheme: theme } = useTheme();@@ -474,14 +479,26 @@ export function MarkdownView({const markdownContent =typeof markdown === "string" ? markdown : parseOpenAIContentParts(markdown);+ // Collapse preview is built from text parts only: serialized image/audio+ // parts (media-reference strings, base64 data URIs) neither survive the+ // generic markdown renderer nor belong in a first-lines text preview — and+ // media alone should not make a prompt collapsible.+ const collapsibleContent =+ typeof markdown === "string"+ ? markdown+ : (markdown ?? [])+ .filter(isOpenAITextContentPart)+ .map((part) => part.text)+ .join("\n");+const {shouldBeCollapsible,isCollapsed,toggleCollapsed,truncatedContent,} = useCollapsibleSystemPrompt({- role: title ?? "",- content: markdownContent,+ isSystemPrompt: isSystemPrompt ?? title === "system",+ content: collapsibleContent,});const handleOnCopy = () => {@@ -504,6 +521,17 @@ export function MarkdownView({getRenderedInlineMediaIds({ markdown, audio }),);+ const collapseToggle = shouldBeCollapsible ? (+ <Button+ variant="ghost"+ size="xs"+ onClick={toggleCollapsed}+ className="w-fit text-xs underline"+ >+ {isCollapsed ? "Expand system prompt" : "Collapse system prompt"}+ </Button>+ ) : null;+return (<div className="overflow-hidden" key={theme}>{title ? (@@ -541,77 +569,73 @@ export function MarkdownView({) : (<><MarkdownRenderer- markdown={- shouldBeCollapsible && isCollapsed- ? truncatedContent- : markdown- }+ markdown={isCollapsed ? truncatedContent : markdown}theme={theme}customCodeHeaderClassName={customCodeHeaderClassName}/>- {shouldBeCollapsible && (- <Button- variant="ghost"- size="xs"- onClick={toggleCollapsed}- className="w-fit text-xs underline"- >- {isCollapsed- ? "Expand system prompt"- : "Collapse system prompt"}- </Button>- )}+ {collapseToggle}</>)) : (- // content parts (multi-modal)- (markdown ?? []).map((content, index) => {- if (isOpenAITextContentPart(content)) {- return (- <MarkdownRenderer- key={index}- markdown={content.text}- theme={theme}- customCodeHeaderClassName={customCodeHeaderClassName}- />- );- }-- if (isOpenAIImageContentPart(content)) {- const imageUrl = content.image_url.url;- const safeImageUrl =- typeof imageUrl === "string" &&- OpenAIUrlImageUrl.safeParse(imageUrl).success- ? getSafeImageUrl(imageUrl)- : null;-- return safeImageUrl ? (- <div key={index}>- <ResizableImage src={safeImageUrl} />- </div>- ) : MediaReferenceStringSchema.safeParse(imageUrl).success ? (- <LangfuseMediaView mediaReferenceString={imageUrl} />- ) : (- <div className="grid grid-cols-[auto_1fr] items-center gap-2">- <span title="<Base64 data URI>" className="h-4 w-4">- <ImageOff className="h-4 w-4" />- </span>- <span- className="truncate text-sm"- title={imageUrl.toString()}- >- {imageUrl.toString()}- </span>- </div>- );- }-- return content.type === "input_audio" ? (- <LangfuseMediaView- mediaReferenceString={content.input_audio.data}+ // content parts (multi-modal); collapsed = preview of the joined text+ <>+ {isCollapsed ? (+ <MarkdownRenderer+ markdown={truncatedContent}+ theme={theme}+ customCodeHeaderClassName={customCodeHeaderClassName}/>- ) : null;- })+ ) : (+ (markdown ?? []).map((content, index) => {+ if (isOpenAITextContentPart(content)) {+ return (+ <MarkdownRenderer+ key={index}+ markdown={content.text}+ theme={theme}+ customCodeHeaderClassName={customCodeHeaderClassName}+ />+ );+ }++ if (isOpenAIImageContentPart(content)) {+ const imageUrl = content.image_url.url;+ const safeImageUrl =+ typeof imageUrl === "string" &&+ OpenAIUrlImageUrl.safeParse(imageUrl).success+ ? getSafeImageUrl(imageUrl)+ : null;++ return safeImageUrl ? (+ <div key={index}>+ <ResizableImage src={safeImageUrl} />+ </div>+ ) : MediaReferenceStringSchema.safeParse(imageUrl).success ? (+ <LangfuseMediaView mediaReferenceString={imageUrl} />+ ) : (+ <div className="grid grid-cols-[auto_1fr] items-center gap-2">+ <span title="<Base64 data URI>" className="h-4 w-4">+ <ImageOff className="h-4 w-4" />+ </span>+ <span+ className="truncate text-sm"+ title={imageUrl.toString()}+ >+ {imageUrl.toString()}+ </span>+ </div>+ );+ }++ return content.type === "input_audio" ? (+ <LangfuseMediaView+ mediaReferenceString={content.input_audio.data}+ />+ ) : null;+ })+ )}+ {collapseToggle}+ </>)}{audio ? (<>diff --git a/web/src/components/ui/PrettyJsonView.tsx b/web/src/components/ui/PrettyJsonView.tsxindex 8ae11f794c..543f6e8718 100644--- a/web/src/components/ui/PrettyJsonView.tsx+++ b/web/src/components/ui/PrettyJsonView.tsx@@ -787,6 +787,9 @@ export function PrettyJsonView(props: {/** When set, rows show an actions menu with copy + add-to-filter shortcuts(metadata views only). */metadataActions?: MetadataFilterActions;+ /** Collapse long string content to a preview (from raw `role === "system"`,+ since the title can carry a message `name` instead of the role). */+ isSystemPrompt?: boolean;}) {// Use pre-parsed data if available, otherwise parse on-demandconst parsedJson = useMemo(() => {@@ -1279,6 +1282,7 @@ export function PrettyJsonView(props: {<MarkdownViewmarkdown={markdownContent || ""}media={props.media}+ isSystemPrompt={props.isSystemPrompt}/>)}</div>diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.tsindex 6f621e7c52..1b13834d9d 100644--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts@@ -38,6 +38,9 @@ export const events = {"graph_view_toggle",// Aggregated vs expanded graph build mode (LFE-10676)."graph_mode_switch",+ // `source` distinguishes the inline expand/collapse button from the+ // trace settings switch; `collapsed` is the new preference value.+ "system_prompt_collapse_toggle",// Fired from the tree, timeline, graph, and search-result click handlers;// `source` says which surface drove the navigation."node_selected",diff --git a/web/src/hooks/useCollapsibleSystemPrompt.ts b/web/src/hooks/useCollapsibleSystemPrompt.tsindex 014ba0c0fa..f68689f279 100644--- a/web/src/hooks/useCollapsibleSystemPrompt.ts+++ b/web/src/hooks/useCollapsibleSystemPrompt.ts@@ -1,11 +1,99 @@-import { useState, useMemo } from "react";+import { useMemo, useSyncExternalStore } from "react";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";const COLLAPSE_CHAR_THRESHOLD = 250;-const STORAGE_KEY = "traceSystemPrompt:collapsed";+const DEFAULT_PREVIEW_LINES = 4;+// Matches JSONView's collapseStringsAfterLength default; generous enough that+// the first N lines usually survive intact instead of being cut mid-line.+const DEFAULT_PREVIEW_CHAR_LIMIT = 500;++const STORAGE_KEY = "collapseSystemPrompt";+const LEGACY_STORAGE_KEY = "traceSystemPrompt:collapsed";++// Session fallback when localStorage is blocked entirely (sandboxed iframe,+// strict privacy mode): the toggle must still work in-session even if it+// can't persist. Consulted only when reading the stored value throws.+let inMemoryPreference: boolean | null = null;++function readCollapsePreference(): boolean {+ try {+ const stored = localStorage.getItem(STORAGE_KEY);+ if (stored !== null) return stored !== "false";+ // Migration: the legacy key stored `false` when a user explicitly+ // expanded a system prompt. Write the choice through to the new key so+ // it survives removing the legacy fallback; the write happens at most+ // once, since the next read hits the stored-value fast path.+ if (localStorage.getItem(LEGACY_STORAGE_KEY) === "false") {+ localStorage.setItem(STORAGE_KEY, "false");+ return false;+ }+ return true;+ } catch {+ return inMemoryPreference ?? true;+ }+}++function subscribeToCollapsePreference(onChange: () => void): () => void {+ const handleStorage = (e: StorageEvent) => {+ if (e.key === STORAGE_KEY) onChange();+ };+ const handleCustomEvent = (e: Event) => {+ if ((e as CustomEvent<{ key: string }>).detail?.key === STORAGE_KEY)+ onChange();+ };+ window.addEventListener("storage", handleStorage);+ window.addEventListener("localStorageChange", handleCustomEvent);+ return () => {+ window.removeEventListener("storage", handleStorage);+ window.removeEventListener("localStorageChange", handleCustomEvent);+ };+}++function writeCollapsePreference(value: boolean): void {+ inMemoryPreference = value;+ try {+ localStorage.setItem(STORAGE_KEY, JSON.stringify(value));+ } catch {+ // keep going: the in-memory fallback makes the toggle work in-session+ }+ // Same event contract as useLocalStorage, so all subscribers (every mounted+ // system prompt plus ViewPreferencesContext) update in the same tab.+ window.dispatchEvent(+ new CustomEvent("localStorageChange", {+ detail: { key: STORAGE_KEY, newValue: JSON.stringify(value) },+ }),+ );+}++/**+ * Persisted default for whether long system prompts render collapsed.+ * Shared by the inline expand/collapse toggle and the trace view preferences+ * (ViewPreferencesContext). Backed by useSyncExternalStore rather than+ * per-instance state: many instances of this hook mount at once (one per+ * message), and a state-updater-based sync would setState across components+ * mid-render.+ */+export function useCollapseSystemPromptPreference(): [+ boolean,+ (value: boolean) => void,+] {+ const value = useSyncExternalStore(+ subscribeToCollapsePreference,+ readCollapsePreference,+ () => true,+ );+ return [value, writeCollapsePreference];+}interface UseCollapsibleSystemPromptOptions {- role: string;+ /** Decide from the raw message role, not the display title — a system+ message that carries a `name` is titled by that name. */+ isSystemPrompt: boolean;content: string;+ /** Number of lines shown while collapsed. */+ previewLines?: number;+ /** Character cap applied to the collapsed preview. */+ previewCharLimit?: number;}interface UseCollapsibleSystemPromptReturn {@@ -16,71 +104,64 @@ interface UseCollapsibleSystemPromptReturn {}/**- * Auto-collapses system prompts >250 chars.- * Saves user preference when manually expanded to localStorage.+ * Collapses long system prompts to a first-N-lines preview by default.+ * Toggling flips the persisted preference, so an explicit "expanded" choice+ * sticks across messages and navigation instead of being force-collapsed.*/export function useCollapsibleSystemPrompt({- role,+ isSystemPrompt,content,+ previewLines = DEFAULT_PREVIEW_LINES,+ previewCharLimit = DEFAULT_PREVIEW_CHAR_LIMIT,}: UseCollapsibleSystemPromptOptions): UseCollapsibleSystemPromptReturn {- const shouldBeCollapsible = useMemo(() => {- if (role !== "system") return false;- if (!content || typeof content !== "string") return false;- return content.length > COLLAPSE_CHAR_THRESHOLD;- }, [role, content]);-- // Default: collapsed if long- // Override: expanded if user previously expanded (localStorage = false)- const [isCollapsed, setIsCollapsed] = useState(() => {- if (!shouldBeCollapsible) return false;-- try {- const stored = localStorage.getItem(STORAGE_KEY);- // No preference = use default (collapsed)- // false = user expanded it- return stored !== null ? JSON.parse(stored) : true;- } catch {- return true;+ const capture = usePostHogClientCapture();+ const [collapsePreference, setCollapsePreference] =+ useCollapseSystemPromptPreference();++ // null = collapsing would hide nothing, so no toggle is offered. Deriving+ // collapsibility from the actual truncation result (instead of a bare char+ // threshold) avoids a dead toggle for content that clears the threshold but+ // fits entirely within the preview.+ const preview = useMemo(() => {+ if (+ !isSystemPrompt ||+ typeof content !== "string" ||+ content.length <= COLLAPSE_CHAR_THRESHOLD+ ) {+ return null;}- });- const toggleCollapsed = () => {- setIsCollapsed((prev: boolean) => {- const newValue = !prev;-- try {- if (newValue) {- // delete key on collapse to get default behavior- localStorage.removeItem(STORAGE_KEY);- } else {- localStorage.setItem(STORAGE_KEY, JSON.stringify(false));- }- } catch {- // Ignore localStorage errors- }-- return newValue;- });- };+ const lines = content.split("\n");+ const previewText = lines.slice(0, previewLines).join("\n");- // Truncated preview (first 4 lines or 250 chars)- const truncatedContent = useMemo(() => {- if (!shouldBeCollapsible || !content) return content;+ if (previewText.length > previewCharLimit) {+ return previewText.slice(0, previewCharLimit) + "...";+ }+ if (lines.length > previewLines) {+ return previewText + "\n...";+ }+ return null;+ }, [isSystemPrompt, content, previewLines, previewCharLimit]);- const lines = content.split("\n");- const preview = lines.slice(0, 4).join("\n");- const hasMore = lines.length > 4;- const tooLong = preview.length > COLLAPSE_CHAR_THRESHOLD;+ const shouldBeCollapsible = preview !== null;+ const isCollapsed = shouldBeCollapsible && collapsePreference;- return tooLong- ? preview.slice(0, COLLAPSE_CHAR_THRESHOLD) + "..."- : preview + (hasMore ? "\n..." : "");- }, [shouldBeCollapsible, content]);+ const toggleCollapsed = () => {+ const next = !collapsePreference;+ // No trace analytics dimensions here on purpose: this fires from shared+ // components that also render outside trace contexts (e.g. session view),+ // and the event must keep one shape across sources.+ capture("trace_detail:system_prompt_collapse_toggle", {+ collapsed: next,+ source: "inline",+ });+ setCollapsePreference(next);+ };return {shouldBeCollapsible,isCollapsed,toggleCollapsed,- truncatedContent,+ truncatedContent: preview ?? content,};}