Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(sessions): Add syntax highlighting to session tool previews (#18472)

Ben Bachem81663ae4f5b0
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 1c4489406a..ea732bd8e0 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -789,6 +789,9 @@ importers:
fflate:
specifier: 0.8.3
version: 0.8.3
+ highlight.js:
+ specifier: ^11.12.0
+ version: 11.12.0
https-proxy-agent:
specifier: ^7.0.6
version: 7.0.6([email protected])
diff --git a/web/package.json b/web/package.json
index f89fa5c53e..23a3f07b66 100644
--- a/web/package.json
+++ b/web/package.json
@@ -131,6 +131,7 @@
"exponential-backoff": "^3.1.2",
"fastest-levenshtein": "^1.0.16",
"fflate": "0.8.3",
+ "highlight.js": "^11.12.0",
"https-proxy-agent": "^7.0.6",
"ioredis": "^5.10.1",
"json-schema-faker": "0.6.1",
diff --git a/web/src/components/design-system/Codeblock/Codeblock.stories.tsx b/web/src/components/design-system/Codeblock/Codeblock.stories.tsx
index aad5e13c19..cb09539a38 100644
--- a/web/src/components/design-system/Codeblock/Codeblock.stories.tsx
+++ b/web/src/components/design-system/Codeblock/Codeblock.stories.tsx
@@ -1,4 +1,6 @@
import preview from "../../../../.storybook/preview";
+import { expect } from "storybook/test";
+import { themes } from "prism-react-renderer";
import { Codeblock as CodeBlock } from "./Codeblock";
const meta = preview.meta({
@@ -23,3 +25,52 @@ export const ReadOnly = meta.story({
variant: "read-only",
},
});
+
+export const LightThemeTokenRendering = Default.extend({
+ name: "(Test) Light Theme Token Rendering",
+ play: async ({ args, canvasElement, canvas }) => {
+ const preview = canvasElement.querySelector("pre")!;
+ await expect(preview).toHaveTextContent(args.value);
+ const keyword = preview.querySelector(".token.keyword")!;
+ await expect(keyword).toHaveTextContent("const");
+ await expect(preview.querySelector(".token.string")).toHaveTextContent(
+ '"Hello, Langfuse!"',
+ );
+ const theme = args.theme === "dark" ? themes.vsDark : themes.github;
+ const keywordStyle = theme.styles
+ .filter((rule) => {
+ if (!rule.types.includes("keyword")) return false;
+ if (rule.languages && !rule.languages.includes(args.language)) {
+ return false;
+ }
+ return true;
+ })
+ .reduce<(typeof theme.styles)[number]["style"]>(
+ (style, rule) => ({ ...style, ...rule.style }),
+ {},
+ );
+ await expect(keyword).toHaveStyle(keywordStyle);
+ await expect(
+ canvas.getByRole("button", { name: "Copy code" }),
+ ).toBeVisible();
+ },
+});
+
+export const DarkThemeTokenRendering = LightThemeTokenRendering.extend({
+ name: "(Test) Dark Theme Token Rendering",
+ args: { theme: "dark" },
+});
+
+export const HtmlSafety = Default.extend({
+ name: "(Test) HTML Is Highlighted Without Executing It",
+ args: {
+ language: "markup",
+ value: '<script>alert("unsafe")</script>',
+ },
+ play: async ({ args, canvasElement }) => {
+ const preview = canvasElement.querySelector("pre")!;
+ await expect(preview.textContent).toBe(args.value);
+ await expect(preview.querySelector("script")).toBeNull();
+ await expect(preview.querySelector(".token.tag")).toBeInTheDocument();
+ },
+});
diff --git a/web/src/components/design-system/Codeblock/Codeblock.tsx b/web/src/components/design-system/Codeblock/Codeblock.tsx
index 169b007965..ae4eb3e8f0 100644
--- a/web/src/components/design-system/Codeblock/Codeblock.tsx
+++ b/web/src/components/design-system/Codeblock/Codeblock.tsx
@@ -2,8 +2,7 @@ import { IconButton } from "@/src/components/design-system/IconButton/IconButton
import { copyTextToClipboard } from "@/src/utils/clipboard";
import { Check, Copy } from "lucide-react";
import { type FC, memo, useState } from "react";
-import { Highlight, themes } from "prism-react-renderer";
-import { useTheme } from "next-themes";
+import { SyntaxHighlight } from "@/src/components/design-system/SyntaxHighlight/SyntaxHighlight";
import { cn } from "@/src/utils/tailwind";
interface Props {
@@ -27,8 +26,6 @@ const CodeBlock: FC<Props> = memo(
variant = "default",
}) => {
const [isCopied, setIsCopied] = useState(false);
- const { resolvedTheme } = useTheme();
- const appliedTheme = theme ?? resolvedTheme;
const handleCopy = () => {
setIsCopied(true);
copyTextToClipboard(value ?? "");
@@ -65,12 +62,8 @@ const CodeBlock: FC<Props> = memo(
{copyButton}
</div>
)}
- <Highlight
- theme={appliedTheme === "dark" ? themes.vsDark : themes.github}
- code={value}
- language={language}
- >
- {({ className, style, tokens, getLineProps, getTokenProps }) => (
+ <SyntaxHighlight theme={theme} code={value} language={language}>
+ {({ className, style, content }) => (
<pre
className={className}
style={{
@@ -87,16 +80,10 @@ const CodeBlock: FC<Props> = memo(
overflow: "auto",
}}
>
- {tokens.map((line, i) => (
- <div key={i} {...getLineProps({ line })}>
- {line.map((token, key) => (
- <span key={key} {...getTokenProps({ token })} />
- ))}
- </div>
- ))}
+ {content}
</pre>
)}
- </Highlight>
+ </SyntaxHighlight>
</div>
);
},
diff --git a/web/src/components/design-system/SelectDropdown/SelectDropdown.stories.tsx b/web/src/components/design-system/SelectDropdown/SelectDropdown.stories.tsx
new file mode 100644
index 0000000000..f6648ef43e
--- /dev/null
+++ b/web/src/components/design-system/SelectDropdown/SelectDropdown.stories.tsx
@@ -0,0 +1,134 @@
+import { useState } from "react";
+import { expect, fn, userEvent, waitFor, within } from "storybook/test";
+import preview from "../../../../.storybook/preview";
+import { DropdownIndicator } from "../DropdownIndicator/DropdownIndicator";
+import { SelectDropdown } from "./SelectDropdown";
+
+const meta = preview.meta({ component: SelectDropdown });
+
+export const CompactTrigger = meta.story({
+ name: "(Test) Compact trigger",
+ args: {
+ "aria-label": "Output language",
+ value: "auto",
+ options: [
+ { value: "auto", label: "Auto (JSON)" },
+ { value: "text", label: "Plain text" },
+ { value: "json", label: "JSON" },
+ { value: "python", label: "Python" },
+ ],
+ onValueChange: fn(),
+ ref: fn(),
+ children: ({ getTriggerProps, selectedLabel }) => (
+ <button
+ {...getTriggerProps()}
+ className="text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:ring-ring inline-flex items-center gap-1 rounded px-1.5 py-1 text-xs focus-visible:ring-2 focus-visible:outline-hidden"
+ >
+ {selectedLabel}
+ <DropdownIndicator />
+ </button>
+ ),
+ },
+ render: (args) => {
+ const [value, setValue] = useState(args.value);
+ return (
+ <SelectDropdown
+ {...args}
+ value={value}
+ onValueChange={(newValue) => {
+ setValue(newValue);
+ args.onValueChange(newValue);
+ }}
+ />
+ );
+ },
+ play: async ({ canvas, args }) => {
+ const trigger = canvas.getByRole("combobox", { name: "Output language" });
+ await expect(args.ref).toHaveBeenCalledWith(trigger);
+ await userEvent.click(trigger);
+ await userEvent.click(
+ within(document.body).getByRole("option", { name: "Python" }),
+ );
+ await expect(trigger).toHaveTextContent("Python");
+ await expect(args.onValueChange).toHaveBeenCalledWith("python");
+ },
+});
+
+export const WrappedTrigger = CompactTrigger.extend({
+ name: "(Test) Wrapped trigger with keyboard selection",
+ args: {
+ children: ({ getTriggerProps, selectedLabel }) => (
+ <div>
+ <button {...getTriggerProps()}>{selectedLabel}</button>
+ </div>
+ ),
+ },
+ play: async ({ canvas, args }) => {
+ const trigger = canvas.getByRole("combobox", { name: "Output language" });
+ await expect(args.ref).toHaveBeenCalledWith(trigger);
+ trigger.focus();
+ await userEvent.keyboard("{ArrowDown}");
+ await expect(trigger).toHaveAttribute("aria-expanded", "true");
+ await userEvent.keyboard("{End}{Enter}");
+ await expect(trigger).toHaveTextContent("Python");
+ await expect(args.onValueChange).toHaveBeenCalledWith("python");
+ },
+});
+
+export const PreventOpening = CompactTrigger.extend({
+ name: "(Test) Trigger handler can prevent opening",
+ args: {
+ children: ({ getTriggerProps, selectedLabel }) => (
+ <button
+ {...getTriggerProps({
+ onKeyDown: (event) => event.preventDefault(),
+ })}
+ >
+ {selectedLabel}
+ </button>
+ ),
+ },
+ play: async ({ canvas }) => {
+ const trigger = canvas.getByRole("combobox", { name: "Output language" });
+ trigger.focus();
+ await userEvent.keyboard("{ArrowDown}");
+ await expect(trigger).toHaveAttribute("aria-expanded", "false");
+ await expect(within(document.body).queryByRole("listbox")).toBeNull();
+ },
+});
+
+export const GroupedDisabledOptions = CompactTrigger.extend({
+ name: "(Test) Grouped and disabled options",
+ args: {
+ value: "json",
+ options: [
+ {
+ type: "group",
+ id: "languages",
+ label: "Languages",
+ options: [
+ { value: "json", label: "JSON" },
+ {
+ value: "python",
+ label: "Python",
+ disabled: true,
+ disabledReason: "Unavailable",
+ },
+ ],
+ },
+ ],
+ },
+ play: async ({ canvas }) => {
+ await userEvent.click(
+ canvas.getByRole("combobox", { name: "Output language" }),
+ );
+ const body = within(document.body);
+ await waitFor(() =>
+ expect(body.getByRole("group", { name: "Languages" })).toBeVisible(),
+ );
+ await expect(body.getByRole("option", { name: "Python" })).toHaveAttribute(
+ "aria-disabled",
+ "true",
+ );
+ },
+});
diff --git a/web/src/components/design-system/SelectDropdown/SelectDropdown.tsx b/web/src/components/design-system/SelectDropdown/SelectDropdown.tsx
new file mode 100644
index 0000000000..03156aea98
--- /dev/null
+++ b/web/src/components/design-system/SelectDropdown/SelectDropdown.tsx
@@ -0,0 +1,194 @@
+"use client";
+
+import * as React from "react";
+import * as SelectPrimitive from "@radix-ui/react-select";
+import { ChevronDown, ChevronUp } from "lucide-react";
+import { useLayerContainer } from "@/src/context/LayerContext/LayerContext";
+import { Badge } from "@/src/components/design-system/Badge/Badge";
+import { InputDropdown } from "@/src/components/design-system/internal/InputDropdown/InputDropdown";
+
+type SelectOption<V> = {
+ value: V;
+ label: string;
+ badges?: Array<
+ Pick<React.ComponentProps<typeof Badge>, "text" | "color" | "title">
+ >;
+} & (
+ | { disabled?: false; disabledReason?: never }
+ | { disabled: true; disabledReason: string }
+);
+
+type SelectNode<V> =
+ | SelectOption<V>
+ | {
+ type: "group";
+ id: string;
+ label: string;
+ options: SelectOption<V>[];
+ };
+
+function isSelectGroup<V>(
+ node: SelectNode<V>,
+): node is Extract<SelectNode<V>, { type: "group" }> {
+ return "type" in node && node.type === "group";
+}
+
+type TriggerControls = {
+ getTriggerProps: (
+ props?: React.ComponentPropsWithoutRef<"button">,
+ ) => React.ComponentPropsWithRef<"button">;
+};
+
+// Radix injects its trigger handlers and measurement ref through asChild.
+// Forward them to the registered button even when the caller wraps it in styling.
+const RegisteredTrigger = React.forwardRef<
+ HTMLButtonElement,
+ Omit<React.ComponentPropsWithoutRef<"button">, "children"> & {
+ children: (controls: TriggerControls) => React.ReactNode;
+ }
+>(({ children, ...triggerProps }, ref) =>
+ children({
+ getTriggerProps: (props = {}) => ({
+ ...triggerProps,
+ ...props,
+ ref,
+ onClick: (event) => {
+ props.onClick?.(event);
+ if (!event.defaultPrevented) triggerProps.onClick?.(event);
+ },
+ onPointerDown: (event) => {
+ props.onPointerDown?.(event);
+ if (!event.defaultPrevented) triggerProps.onPointerDown?.(event);
+ },
+ onKeyDown: (event) => {
+ props.onKeyDown?.(event);
+ if (!event.defaultPrevented) triggerProps.onKeyDown?.(event);
+ },
+ }),
+ }),
+);
+RegisteredTrigger.displayName = "RegisteredTrigger";
+
+export function SelectDropdown<V extends string>({
+ value,
+ options,
+ onValueChange,
+ emptyMessage = "No options available.",
+ children,
+ ref,
+ ...triggerProps
+}: {
+ value: V;
+ options: SelectNode<V>[];
+ onValueChange: (value: V) => void;
+ emptyMessage?: string;
+ children: (
+ controls: TriggerControls & { selectedLabel: string | undefined },
+ ) => React.ReactNode;
+ ref?: React.Ref<HTMLButtonElement>;
+} & Pick<
+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>,
+ "id" | "aria-describedby" | "aria-invalid" | "aria-label" | "disabled"
+>) {
+ const container = useLayerContainer("popover");
+ const selectedOption = options
+ .flatMap((node) => (isSelectGroup(node) ? node.options : [node]))
+ .find((option) => option.value === value);
+ const hasOptions = options.some((node) =>
+ isSelectGroup(node) ? node.options.length > 0 : true,
+ );
+ const renderNode = (
+ node: SelectNode<V>,
+ hasPreviousGroup: boolean,
+ ): React.ReactElement => {
+ if (isSelectGroup(node)) {
+ return (
+ <React.Fragment key={node.id}>
+ {hasPreviousGroup && (
+ <SelectPrimitive.Separator className="bg-border my-2 h-px" />
+ )}
+ <SelectPrimitive.Group>
+ <SelectPrimitive.Label className="text-muted-foreground px-1 py-1.5 text-xs font-bold">
+ {node.label}
+ </SelectPrimitive.Label>
+ {node.options.map((option) => renderNode(option, false))}
+ </SelectPrimitive.Group>
+ </React.Fragment>
+ );
+ }
+
+ return (
+ <React.Fragment key={node.value}>
+ {hasPreviousGroup && <div aria-hidden="true" className="h-4" />}
+ <InputDropdown.Option highlight="focus">
+ <SelectPrimitive.Item value={node.value} disabled={node.disabled}>
+ <InputDropdown.OptionContent
+ type="radio"
+ checked={value === node.value}
+ label={
+ <SelectPrimitive.ItemText>
+ {node.label}
+ </SelectPrimitive.ItemText>
+ }
+ title={node.disabled ? node.disabledReason : node.label}
+ badges={node.badges?.map((badge, index) => (
+ <Badge key={index} {...badge} />
+ ))}
+ />
+ </SelectPrimitive.Item>
+ </InputDropdown.Option>
+ </React.Fragment>
+ );
+ };
+
+ return (
+ <SelectPrimitive.Root value={value} onValueChange={onValueChange}>
+ <SelectPrimitive.Trigger
+ asChild
+ ref={ref}
+ title={selectedOption?.label}
+ {...triggerProps}
+ >
+ <RegisteredTrigger>
+ {(controls) =>
+ children({ ...controls, selectedLabel: selectedOption?.label })
+ }
+ </RegisteredTrigger>
+ </SelectPrimitive.Trigger>
+ <SelectPrimitive.Portal container={container}>
+ <InputDropdown.Content width="select-trigger">
+ <SelectPrimitive.Content position="popper" sideOffset={4}>
+ <SelectPrimitive.ScrollUpButton
+ aria-label="Scroll up"
+ className="animate-in fade-in-0 fill-mode-both absolute inset-x-0 top-0 z-3 flex h-6 cursor-pointer items-center justify-center duration-300 [animation-delay:.5s]"
+ >
+ <ChevronUp className="icon-base" />
+ </SelectPrimitive.ScrollUpButton>
+ <InputDropdown.List>
+ <SelectPrimitive.Viewport>
+ {!hasOptions ? (
+ <div className="text-muted-foreground py-6 text-center text-sm">
+ {emptyMessage}
+ </div>
+ ) : (
+ options.map((node, index) =>
+ renderNode(
+ node,
+ index > 0 && isSelectGroup(options[index - 1]),
+ ),
+ )
+ )}
+ </SelectPrimitive.Viewport>
+ </InputDropdown.List>
+ <SelectPrimitive.ScrollDownButton
+ aria-label="Scroll down"
+ className="animate-in fade-in-0 fill-mode-both absolute inset-x-0 bottom-0 z-3 flex h-6 cursor-pointer items-center justify-center duration-300 [animation-delay:.5s]"
+ >
+ <ChevronDown className="icon-base" />
+ </SelectPrimitive.ScrollDownButton>
+ </SelectPrimitive.Content>
+ </InputDropdown.Content>
+ </SelectPrimitive.Portal>
+ </SelectPrimitive.Root>
+ );
+}
diff --git a/web/src/components/design-system/SelectInput/SelectInput.tsx b/web/src/components/design-system/SelectInput/SelectInput.tsx
index 6be6724bf4..f57d23ba1c 100644
--- a/web/src/components/design-system/SelectInput/SelectInput.tsx
+++ b/web/src/components/design-system/SelectInput/SelectInput.tsx
@@ -1,61 +1,41 @@
"use client";
import * as React from "react";
-import * as SelectPrimitive from "@radix-ui/react-select";
import * as PopoverPrimitive from "@radix-ui/react-popover";
import { Command as CommandPrimitive } from "cmdk";
import { useLayerContainer } from "@/src/context/LayerContext/LayerContext";
-import { ChevronDown, ChevronUp } from "lucide-react";
+import { SelectDropdown } from "../SelectDropdown/SelectDropdown";
import { DropdownIndicator } from "@/src/components/design-system/DropdownIndicator/DropdownIndicator";
import { Badge } from "../Badge/Badge";
import { stopScrollPropagation } from "@/src/hooks/stopScrollPropagation";
import { InputControl } from "../internal/InputControl/InputControl";
import { InputDropdown } from "../internal/InputDropdown/InputDropdown";
-type SelectOption<V> =
- | {
- value: V;
- label: string;
- badges?: Array<
- Pick<React.ComponentProps<typeof Badge>, "text" | "color" | "title">
- >;
- disabled?: false;
- disabledReason?: never;
- }
- | {
- value: V;
- label: string;
- badges?: Array<
- Pick<React.ComponentProps<typeof Badge>, "text" | "color" | "title">
- >;
- disabled: true;
- disabledReason: string;
- };
-
-type SelectGroup<V> = {
- type: "group";
- id: string;
- label: string;
- options: SelectOption<V>[];
-};
-
-type SelectInputNode<V> = SelectOption<V> | SelectGroup<V>;
-
-type SelectInputProps<V> = {
- value: V;
- options: SelectInputNode<V>[];
- onValueChange: (newValue: V) => void;
+type SelectInputNode<V extends string> = React.ComponentProps<
+ typeof SelectDropdown<V>
+>["options"][number];
+
+type SelectInputProps<V extends string> = Pick<
+ React.ComponentProps<typeof SelectDropdown<V>>,
+ | "value"
+ | "options"
+ | "onValueChange"
+ | "emptyMessage"
+ | "id"
+ | "aria-describedby"
+ | "aria-invalid"
+ | "aria-label"
+ | "disabled"
+> & {
placeholder: string;
- emptyMessage?: string;
search?: { placeholder: string };
error?: boolean;
-} & Pick<
- React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>,
- "id" | "aria-describedby" | "aria-invalid" | "aria-label" | "disabled"
->;
+};
-function isSelectGroup<V>(node: SelectInputNode<V>): node is SelectGroup<V> {
+function isSelectGroup<V extends string>(
+ node: SelectInputNode<V>,
+): node is Extract<SelectInputNode<V>, { type: "group" }> {
return "type" in node && node.type === "group";
}
@@ -77,9 +57,6 @@ function SelectInputInner<V extends string>(
const selectedOption = options
.flatMap((node) => (isSelectGroup(node) ? node.options : [node]))
.find((option) => option.value === value);
- const hasOptions = options.some((node) =>
- isSelectGroup(node) ? node.options.length > 0 : true,
- );
const listId = React.useId();
if (search) {
@@ -189,112 +166,29 @@ function SelectInputInner<V extends string>(
</PopoverPrimitive.Root>
);
}
- const renderNode = (
- node: SelectInputNode<V>,
- hasPreviousGroup: boolean,
- ): React.ReactElement => {
- if (isSelectGroup(node)) {
- return (
- <React.Fragment key={node.id}>
- {hasPreviousGroup && (
- <SelectPrimitive.Separator className="bg-border my-2 h-px" />
- )}
- <SelectPrimitive.Group>
- <SelectPrimitive.Label className="text-muted-foreground px-1 py-1.5 text-xs font-bold">
- {node.label}
- </SelectPrimitive.Label>
- {node.options.map((option) => renderNode(option, false))}
- </SelectPrimitive.Group>
- </React.Fragment>
- );
- }
-
- return (
- <React.Fragment key={node.value}>
- {hasPreviousGroup && <div aria-hidden="true" className="h-4" />}
- <InputDropdown.Option highlight="focus">
- <SelectPrimitive.SelectItem
- value={node.value}
- disabled={node.disabled}
- >
- <InputDropdown.OptionContent
- type="radio"
- checked={value === node.value}
- label={
- <SelectPrimitive.ItemText>
- {node.label}
- </SelectPrimitive.ItemText>
- }
- title={node.disabled ? node.disabledReason : node.label}
- badges={node.badges?.map((badge, index) => (
- <Badge key={index} {...badge} />
- ))}
- />
- </SelectPrimitive.SelectItem>
- </InputDropdown.Option>
- </React.Fragment>
- );
- };
-
return (
- <SelectPrimitive.Root
+ <SelectDropdown
value={value}
+ options={options}
onValueChange={onValueChange}
- open={open}
- onOpenChange={setOpen}
+ emptyMessage={emptyMessage}
+ ref={ref}
+ {...triggerProps}
>
- <InputControl contentLayout="spread" error={error}>
- <SelectPrimitive.Trigger
- ref={ref}
- title={selectedOption?.label}
- {...triggerProps}
- >
- <span
- className="min-w-0 flex-1 truncate text-left"
- title={selectedOption?.label}
- >
- <SelectPrimitive.SelectValue placeholder={placeholder} />
- </span>
- <SelectPrimitive.Icon asChild>
- <DropdownIndicator />
- </SelectPrimitive.Icon>
- </SelectPrimitive.Trigger>
- </InputControl>
- <SelectPrimitive.Portal container={container}>
- <InputDropdown.Content width="select-trigger">
- <SelectPrimitive.Content position="popper" sideOffset={4}>
- <SelectPrimitive.ScrollUpButton
- aria-label="Scroll up"
- className="animate-in fade-in-0 fill-mode-both absolute inset-x-0 top-0 z-3 flex h-6 cursor-pointer items-center justify-center duration-300 [animation-delay:.5s]"
- >
- <ChevronUp className="icon-base" />
- </SelectPrimitive.ScrollUpButton>
- <InputDropdown.List>
- <SelectPrimitive.Viewport>
- {!hasOptions ? (
- <div className="text-muted-foreground py-6 text-center text-sm">
- {emptyMessage}
- </div>
- ) : (
- options.map((node, index) =>
- renderNode(
- node,
- index > 0 && isSelectGroup(options[index - 1]),
- ),
- )
- )}
- </SelectPrimitive.Viewport>
- </InputDropdown.List>
- <SelectPrimitive.ScrollDownButton
- aria-label="Scroll down"
- className="animate-in fade-in-0 fill-mode-both absolute inset-x-0 bottom-0 z-3 flex h-6 cursor-pointer items-center justify-center duration-300 [animation-delay:.5s]"
+ {({ getTriggerProps, selectedLabel }) => (
+ <InputControl contentLayout="spread" error={error}>
+ <button {...getTriggerProps()}>
+ <span
+ className="min-w-0 flex-1 truncate text-left"
+ title={selectedLabel}
>
- <ChevronDown className="icon-base" />
- </SelectPrimitive.ScrollDownButton>
- </SelectPrimitive.Content>
- </InputDropdown.Content>
- </SelectPrimitive.Portal>
- </SelectPrimitive.Root>
+ {selectedLabel ?? placeholder}
+ </span>
+ <DropdownIndicator />
+ </button>
+ </InputControl>
+ )}
+ </SelectDropdown>
);
}
diff --git a/web/src/components/design-system/SyntaxHighlight/SyntaxHighlight.tsx b/web/src/components/design-system/SyntaxHighlight/SyntaxHighlight.tsx
new file mode 100644
index 0000000000..5f0d5bf100
--- /dev/null
+++ b/web/src/components/design-system/SyntaxHighlight/SyntaxHighlight.tsx
@@ -0,0 +1,44 @@
+import { type ComponentProps, type ReactNode } from "react";
+import { Highlight, themes } from "prism-react-renderer";
+import { useTheme } from "next-themes";
+
+/** Shares token rendering while callers own the code container and controls. */
+export function SyntaxHighlight({
+ code,
+ language,
+ theme,
+ children,
+}: Pick<ComponentProps<typeof Highlight>, "code" | "language"> & {
+ theme?: "light" | "dark";
+ children: (
+ props: Pick<
+ Parameters<ComponentProps<typeof Highlight>["children"]>[0],
+ "className" | "style"
+ > & { content: ReactNode },
+ ) => ReactNode;
+}) {
+ const { resolvedTheme } = useTheme();
+ const appliedTheme = theme ?? resolvedTheme;
+
+ return (
+ <Highlight
+ code={code}
+ language={language}
+ theme={appliedTheme === "dark" ? themes.vsDark : themes.github}
+ >
+ {({ className, style, tokens, getLineProps, getTokenProps }) =>
+ children({
+ className,
+ style,
+ content: tokens.map((line, index) => (
+ <div key={index} {...getLineProps({ line })}>
+ {line.map((token, key) => (
+ <span key={key} {...getTokenProps({ token })} />
+ ))}
+ </div>
+ )),
+ })
+ }
+ </Highlight>
+ );
+}
diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.stories.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.stories.tsx
index 8285a49246..160cf90734 100644
--- a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.stories.tsx
+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.stories.tsx
@@ -147,6 +147,54 @@ const weatherState = transcriptState({
messages: result.transcript?.threads[0]?.currentTurn.messages ?? [],
history: result.transcript?.threads[0]?.conversationHistory ?? [],
});
+
+function toolPreviewState(
+ previews: {
+ name: string;
+ input: Extract<
+ Thread["currentTurn"]["messages"][number]["parts"][number],
+ { type: "tool-call" }
+ >["input"];
+ output: Extract<
+ Thread["currentTurn"]["messages"][number]["parts"][number],
+ { type: "tool-result" }
+ >["output"];
+ }[],
+): TranscriptState {
+ return transcriptState({
+ history: [],
+ messages: previews.flatMap<Thread["currentTurn"]["messages"][number]>(
+ ({ name, input, output }) => [
+ {
+ ...provenance,
+ role: "assistant",
+ source: "output",
+ parts: [
+ {
+ type: "tool-call",
+ toolCallId: name,
+ toolName: name,
+ input,
+ },
+ ],
+ },
+ {
+ ...provenance,
+ role: "tool",
+ source: "output",
+ parts: [
+ {
+ type: "tool-result",
+ toolCallId: name,
+ toolName: name,
+ output,
+ },
+ ],
+ },
+ ],
+ ),
+ });
+}
export const NestedThreadsHidden = meta.story({
name: "(Test) Nested Threads Hidden",
args: {
@@ -258,14 +306,254 @@ export const ExpandTool = meta.story({
await userEvent.click(
canvas.getByRole("button", { name: "Expand weather" }),
);
- await expect(canvas.getByText(/"city": "Berlin"/)).toBeInTheDocument();
- await expect(canvas.getByText(/"temperature": 12/)).toBeInTheDocument();
+ const [inputPreview, outputPreview] = canvasElement.querySelectorAll("pre");
+ await expect(inputPreview).toHaveTextContent('"city": "Berlin"');
+ await expect(outputPreview).toHaveTextContent('"temperature": 12');
await userEvent.click(
canvas.getByRole("button", { name: "Collapse weather" }),
);
+ await expect(outputPreview).not.toBeInTheDocument();
+ },
+});
+
+export const ToolPreviewJsonHighlighting = meta.story({
+ name: "(Test) Highlights JSON Tool Inputs and Outputs",
+ args: {
+ ...commonArgs,
+ state: toolPreviewState([
+ {
+ name: "json-object",
+ input: { query: "example" },
+ output: { answer: 42 },
+ },
+ {
+ name: "json-string",
+ input: '{"query": "example"}',
+ output: '{"answer": 42}',
+ },
+ ]),
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ for (const name of ["json-object", "json-string"]) {
+ const expand = canvas.getByRole("button", { name: `Expand ${name}` });
+ const row = expand.closest("section")!;
+ await userEvent.click(expand);
+ const controls = within(row);
+ await expect(
+ controls.getByRole("combobox", { name: "Tool input language" }),
+ ).toHaveTextContent("Auto (JSON)");
+ await expect(
+ controls.getByRole("combobox", { name: "Tool output language" }),
+ ).toHaveTextContent("Auto (JSON)");
+ const [inputPreview, outputPreview] = row.querySelectorAll("pre");
+ await expect(inputPreview).toHaveClass("max-h-48");
+ await expect(outputPreview).toHaveClass("max-h-96");
+ await expect(
+ inputPreview.querySelector(".token.property"),
+ ).toHaveTextContent('"query"');
+ await expect(
+ outputPreview.querySelector(".token.property"),
+ ).toHaveTextContent('"answer"');
+ }
+ },
+});
+
+const largeToolPreviewCases = [
+ {
+ name: "highlight-limit",
+ input: { text: "x".repeat(9_984) },
+ output: { text: "x".repeat(9_985) },
+ },
+ {
+ name: "large-multiline",
+ input: { text: "x".repeat(9_985) },
+ output: `${"\n".repeat(10_000)}full value ends here`,
+ },
+];
+
+export const LargeToolPreviews = meta.story({
+ name: "(Test) Large Tool Previews Bypass Highlighting Without Truncation",
+ args: {
+ ...commonArgs,
+ state: toolPreviewState(largeToolPreviewCases),
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ for (const { name, input, output } of largeToolPreviewCases) {
+ const expand = canvas.getByRole("button", { name: `Expand ${name}` });
+ const row = expand.closest("section")!;
+ await userEvent.click(expand);
+ const controls = within(row);
+ const [inputPreview, outputPreview] = row.querySelectorAll("pre");
+ const expectedInput = JSON.stringify(input, undefined, 2);
+ const expectedOutput =
+ typeof output === "string"
+ ? output
+ : JSON.stringify(output, undefined, 2);
+ await expect(outputPreview.textContent).toBe(expectedOutput);
+ await expect(inputPreview).toHaveClass("max-h-48");
+ await expect(outputPreview).toHaveClass("max-h-96");
+ await expect(outputPreview.childElementCount).toBe(0);
+ await expect(
+ controls.queryByRole("combobox", { name: "Tool output language" }),
+ ).toBeNull();
+
+ if (name === "highlight-limit") {
+ await expect(expectedInput.length).toBe(10_000);
+ await expect(expectedOutput.length).toBe(10_001);
+ await expect(
+ inputPreview.querySelector(".token.string")?.textContent,
+ ).toBe(JSON.stringify(input.text));
+ await expect(
+ inputPreview.querySelector(".token.property"),
+ ).toBeInTheDocument();
+ await expect(
+ controls.getByRole("combobox", { name: "Tool input language" }),
+ ).toHaveTextContent("Auto (JSON)");
+ } else {
+ await expect(inputPreview.textContent).toBe(expectedInput);
+ await expect(inputPreview.childElementCount).toBe(0);
+ await expect(controls.queryByRole("combobox")).toBeNull();
+ await expect(
+ controls.getAllByText("Plain text (large value)"),
+ ).toHaveLength(2);
+ }
+ }
+ },
+});
+
+export const ToolPreviewLanguageOverrides = meta.story({
+ name: "(Test) Independent Tool Preview Language Overrides",
+ args: {
+ ...commonArgs,
+ state: toolPreviewState([
+ { name: "search", input: { query: "example" }, output: { answer: 42 } },
+ ]),
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await userEvent.click(
+ canvas.getByRole("button", { name: "Expand search" }),
+ );
+ const inputSelect = canvas.getByRole("combobox", {
+ name: "Tool input language",
+ });
+ const outputSelect = canvas.getByRole("combobox", {
+ name: "Tool output language",
+ });
+ const [inputContainer, outputContainer] = Array.from(
+ canvasElement.querySelectorAll("pre"),
+ (preview) => preview.parentElement!,
+ );
+ const body = within(document.body);
+
+ await userEvent.click(inputSelect);
+ await userEvent.click(body.getByRole("option", { name: "Plain text" }));
+ await expect(inputSelect).toHaveTextContent("Plain text");
+ await expect(inputContainer.querySelector(".token.property")).toBeNull();
+ await expect(inputContainer.querySelector("pre")).toHaveTextContent(
+ '"query": "example"',
+ );
+ await expect(outputSelect).toHaveTextContent("Auto (JSON)");
await expect(
- canvas.queryByText(/"temperature": 12/),
- ).not.toBeInTheDocument();
+ outputContainer.querySelector(".token.property"),
+ ).toBeInTheDocument();
+
+ await userEvent.click(outputSelect);
+ await userEvent.click(body.getByRole("option", { name: "Python" }));
+ await expect(outputSelect).toHaveTextContent("Python");
+ await expect(outputContainer.querySelector(".token.property")).toBeNull();
+ await expect(inputSelect).toHaveTextContent("Plain text");
+
+ await userEvent.click(inputSelect);
+ await userEvent.click(body.getByRole("option", { name: "Auto (JSON)" }));
+ await expect(
+ inputContainer.querySelector(".token.property"),
+ ).toBeInTheDocument();
+ await expect(outputSelect).toHaveTextContent("Python");
+
+ await userEvent.click(outputSelect);
+ await userEvent.click(body.getByRole("option", { name: "Plain text" }));
+ await expect(outputContainer.querySelector(".token.property")).toBeNull();
+ await expect(outputContainer.querySelector("pre")).toHaveTextContent(
+ '"answer": 42',
+ );
+ await userEvent.click(outputSelect);
+ await userEvent.click(body.getByRole("option", { name: "Auto (JSON)" }));
+ await expect(
+ outputContainer.querySelector(".token.property"),
+ ).toBeInTheDocument();
+ },
+});
+
+export const ToolPreviewFallbacks = meta.story({
+ name: "(Test) Tool Preview Plain Text, HTML Safety, and Empty Values",
+ args: {
+ ...commonArgs,
+ state: toolPreviewState([
+ { name: "plain-text", input: null, output: "Hello world" },
+ {
+ name: "html",
+ input: null,
+ output: '<script>alert("unsafe")</script>',
+ },
+ { name: "input-only", input: { query: "example" }, output: null },
+ { name: "empty", input: null, output: null },
+ ]),
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await userEvent.click(
+ canvas.getByRole("button", {
+ name: "Show tools: plain-text · html · input-only · empty",
+ }),
+ );
+ for (const name of ["plain-text", "html", "input-only", "empty"]) {
+ await userEvent.click(
+ canvas.getByRole("button", { name: `Expand ${name}` }),
+ );
+ }
+ const plainRow = canvas
+ .getByRole("button", { name: "Collapse plain-text" })
+ .closest("section")!;
+ await expect(
+ within(plainRow).getByRole("combobox", { name: "Tool output language" }),
+ ).toHaveTextContent("Auto (Plain text)");
+ await expect(
+ within(plainRow).queryByRole("combobox", { name: "Tool input language" }),
+ ).toBeNull();
+ await expect(plainRow.querySelector("pre")).toHaveTextContent(
+ "Hello world",
+ );
+
+ const htmlRow = canvas
+ .getByRole("button", { name: "Collapse html" })
+ .closest("section")!;
+ await expect(htmlRow.querySelector("script")).toBeNull();
+ await expect(htmlRow.querySelector("pre")).toHaveTextContent(
+ '<script>alert("unsafe")</script>',
+ );
+
+ const inputRow = canvas
+ .getByRole("button", { name: "Collapse input-only" })
+ .closest("section")!;
+ await expect(
+ within(inputRow).getByRole("combobox", { name: "Tool input language" }),
+ ).toHaveTextContent("Auto (JSON)");
+ await expect(
+ within(inputRow).queryByRole("combobox", {
+ name: "Tool output language",
+ }),
+ ).toBeNull();
+
+ const emptyRow = canvas
+ .getByRole("button", { name: "Collapse empty" })
+ .closest("section")!;
+ await expect(within(emptyRow).queryByRole("combobox")).toBeNull();
+ await expect(
+ within(emptyRow).getByText("No input or output"),
+ ).toBeInTheDocument();
},
});
@@ -411,12 +699,9 @@ export const PairMatchingToolData = meta.story({
const toolRow = canvas
.getByRole("button", { name: "Collapse weather" })
.closest("section")!;
- await expect(
- within(toolRow).getByText(/"city": "Berlin"/),
- ).toBeInTheDocument();
- await expect(
- within(toolRow).getByText(/"temperature": 12/),
- ).toBeInTheDocument();
+ const [inputPreview, outputPreview] = toolRow.querySelectorAll("pre");
+ await expect(inputPreview).toHaveTextContent('"city": "Berlin"');
+ await expect(outputPreview).toHaveTextContent('"temperature": 12');
},
});
diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineToolRow/SessionTimelineToolRow.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineToolRow/SessionTimelineToolRow.tsx
index cdeab12325..db828c479e 100644
--- a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineToolRow/SessionTimelineToolRow.tsx
+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineToolRow/SessionTimelineToolRow.tsx
@@ -1,8 +1,22 @@
import { CircleAlert } from "lucide-react";
-import { type ReactNode } from "react";
+import { type ReactNode, useMemo, useState } from "react";
+import hljs from "highlight.js/lib/core";
+import json from "highlight.js/lib/languages/json";
+import javascript from "highlight.js/lib/languages/javascript";
+import typescript from "highlight.js/lib/languages/typescript";
+import python from "highlight.js/lib/languages/python";
+import sql from "highlight.js/lib/languages/sql";
+import yaml from "highlight.js/lib/languages/yaml";
+import xml from "highlight.js/lib/languages/xml";
+import css from "highlight.js/lib/languages/css";
+import markdown from "highlight.js/lib/languages/markdown";
+import { SyntaxHighlight } from "@/src/components/design-system/SyntaxHighlight/SyntaxHighlight";
+import { SelectDropdown } from "@/src/components/design-system/SelectDropdown/SelectDropdown";
+import { DropdownIndicator } from "@/src/components/design-system/DropdownIndicator/DropdownIndicator";
import { renderFilterIcon } from "@/src/components/ItemBadge";
import { SessionTimelineCollapsibleRow } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineCollapsibleRow/SessionTimelineCollapsibleRow";
import { decodeUnicodeEscapesOnly } from "@/src/utils/unicode";
+import { cn } from "@/src/utils/tailwind";
const toPreviewText = (value: unknown) => {
const text =
@@ -15,6 +29,98 @@ const toPreviewText = (value: unknown) => {
const hasPreviewValue = (value: unknown) =>
value !== null && value !== undefined && value !== "";
+const MAX_HIGHLIGHT_CHARACTERS = 10_000;
+
+const languageOptions = [
+ { value: "json", label: "JSON", grammar: json },
+ { value: "javascript", label: "JavaScript", grammar: javascript },
+ { value: "typescript", label: "TypeScript", grammar: typescript },
+ { value: "python", label: "Python", grammar: python },
+ { value: "sql", label: "SQL", grammar: sql },
+ { value: "yaml", label: "YAML", grammar: yaml },
+ { value: "xml", label: "HTML / XML", grammar: xml },
+ { value: "css", label: "CSS", grammar: css },
+ { value: "markdown", label: "Markdown", grammar: markdown },
+];
+
+// Prism handles rendering but has no autodetection; only load detection grammars here.
+const detector = hljs.newInstance();
+for (const { value, grammar } of languageOptions) {
+ detector.registerLanguage(value, grammar);
+}
+
+function SessionTimelineToolPreview({
+ value,
+ kind,
+}: {
+ value: unknown;
+ kind: "input" | "output";
+}) {
+ const [selectedLanguage, setSelectedLanguage] = useState("auto");
+ const text = useMemo(() => toPreviewText(value), [value]);
+ const isLargePreview = text.length > MAX_HIGHLIGHT_CHARACTERS;
+ const detectedLanguage = useMemo(() => {
+ if (isLargePreview) return "text";
+ if (typeof value !== "string") return "json";
+ return detector.highlightAuto(text).language ?? "text";
+ }, [isLargePreview, value, text]);
+ const language =
+ selectedLanguage === "auto" ? detectedLanguage : selectedLanguage;
+ const detectedLabel =
+ languageOptions.find((option) => option.value === detectedLanguage)
+ ?.label ?? "Plain text";
+ const previewClassName = cn(
+ "bg-muted/30 overflow-auto rounded-md border p-3 font-mono text-xs break-all whitespace-pre-wrap",
+ kind === "input" ? "max-h-48" : "max-h-96",
+ );
+
+ return (
+ <div className="relative flex min-w-0 flex-col gap-1">
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-muted-foreground font-mono text-[10px] font-bold uppercase">
+ {kind === "input" ? "Input" : "Output"}
+ </span>
+ {isLargePreview ? (
+ <span
+ className="text-muted-foreground px-1.5 py-1 text-xs"
+ title="Syntax highlighting is disabled for previews over 10,000 characters."
+ >
+ Plain text (large value)
+ </span>
+ ) : (
+ <SelectDropdown
+ aria-label={`Tool ${kind} language`}
+ value={selectedLanguage}
+ onValueChange={setSelectedLanguage}
+ options={[
+ { value: "auto", label: `Auto (${detectedLabel})` },
+ { value: "text", label: "Plain text" },
+ ...languageOptions.map(({ value, label }) => ({ value, label })),
+ ]}
+ >
+ {({ getTriggerProps, selectedLabel }) => (
+ <button
+ {...getTriggerProps()}
+ className="text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:ring-ring inline-flex items-center gap-1 rounded px-1.5 py-1 text-xs focus-visible:ring-2 focus-visible:outline-hidden"
+ >
+ {selectedLabel}
+ <DropdownIndicator />
+ </button>
+ )}
+ </SelectDropdown>
+ )}
+ </div>
+ {isLargePreview || language === "text" ? (
+ <pre className={previewClassName}>{text}</pre>
+ ) : (
+ <SyntaxHighlight code={text} language={language}>
+ {({ content }) => <pre className={previewClassName}>{content}</pre>}
+ </SyntaxHighlight>
+ )}
+ </div>
+ );
+}
+
export function SessionTimelineToolRow({
name,
input,
@@ -53,24 +159,10 @@ export function SessionTimelineToolRow({
>
<div className="flex min-w-0 flex-col gap-3 pl-[22px]">
{hasPreviewValue(input) ? (
- <div className="relative flex min-w-0 flex-col gap-1">
- <span className="text-muted-foreground font-mono text-[10px] font-bold uppercase">
- Input
- </span>
- <pre className="bg-muted/30 max-h-48 overflow-auto rounded-md border p-3 font-mono text-xs break-all whitespace-pre-wrap">
- {toPreviewText(input)}
- </pre>
- </div>
+ <SessionTimelineToolPreview kind="input" value={input} />
) : null}
{hasPreviewValue(output) ? (
- <div className="relative flex min-w-0 flex-col gap-1">
- <span className="text-muted-foreground font-mono text-[10px] font-bold uppercase">
- Output
- </span>
- <pre className="bg-muted/30 max-h-48 overflow-auto rounded-md border p-3 font-mono text-xs break-all whitespace-pre-wrap">
- {toPreviewText(output)}
- </pre>
- </div>
+ <SessionTimelineToolPreview kind="output" value={output} />
) : null}
{!hasPreviewValue(input) && !hasPreviewValue(output) ? (
<div className="relative">