Skip to content

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

feat: multi window playground (#7661)

Thorsten Spieker6a8bdae22e82
diff --git a/web/src/components/ChatMessages/index.tsx b/web/src/components/ChatMessages/index.tsx
index 3b79c56735..a24e687542 100644
--- a/web/src/components/ChatMessages/index.tsx
+++ b/web/src/components/ChatMessages/index.tsx
@@ -82,7 +82,7 @@ export const ChatMessages: React.FC<ChatMessagesProps> = (props) => {
>
<div className="flex h-full flex-col">
<div className="flex-1 overflow-auto scroll-smooth" ref={scrollAreaRef}>
- <div className="mb-4 flex-1 space-y-2">
+ <div className="flex-1 space-y-2">
<SortableContext
items={props.messages.map((message) => message.id)}
strategy={verticalListSortingStrategy}
@@ -102,11 +102,11 @@ export const ChatMessages: React.FC<ChatMessagesProps> = (props) => {
);
})}
</SortableContext>
+ <div className="mb-4 py-3">
+ <AddMessageButton {...props} />
+ </div>
</div>
</div>
- <div className="py-3">
- <AddMessageButton {...props} />
- </div>
</div>
</DndContext>
);
@@ -163,7 +163,7 @@ const AddMessageButton: React.FC<AddMessageButtonProps> = ({
onClick={addRegularMessage}
>
<PlusCircleIcon size={14} className="mr-2" />
- <p>Add message</p>
+ <p>Message</p>
</Button>
<TooltipProvider>
<Tooltip>
@@ -175,7 +175,7 @@ const AddMessageButton: React.FC<AddMessageButtonProps> = ({
onClick={addPlaceholderMessage}
>
<PlusCircleIcon size={14} className="mr-2" />
- <p>Add message placeholder</p>
+ <p>Placeholder</p>
</Button>
</TooltipTrigger>
<TooltipContent>
diff --git a/web/src/components/ModelParameters/index.tsx b/web/src/components/ModelParameters/index.tsx
index b303ee2fbf..aa1e9d905e 100644
--- a/web/src/components/ModelParameters/index.tsx
+++ b/web/src/components/ModelParameters/index.tsx
@@ -41,6 +41,7 @@ export type ModelParamsContext = {
formDisabled?: boolean;
modelParamsDescription?: string;
customHeader?: React.ReactNode;
+ layout?: "vertical" | "compact";
};
export const ModelParameters: React.FC<ModelParamsContext> = ({
@@ -52,6 +53,7 @@ export const ModelParameters: React.FC<ModelParamsContext> = ({
formDisabled = false,
modelParamsDescription,
customHeader,
+ layout = "vertical",
}) => {
const projectId = useProjectIdFromURL();
const [modelSettingsOpen, setModelSettingsOpen] = useState(false);
@@ -89,77 +91,159 @@ export const ModelParameters: React.FC<ModelParamsContext> = ({
);
}
+ // Settings button component for reuse
+ const SettingsButton = (
+ <Popover open={modelSettingsOpen} onOpenChange={setModelSettingsOpen}>
+ <PopoverTrigger asChild>
+ <Button
+ variant="outline"
+ size="icon"
+ className="relative h-7 w-7"
+ disabled={formDisabled}
+ >
+ <Settings2 size={14} />
+ {modelSettingsUsed && (
+ <div className="absolute -right-0.5 -top-0.5 h-2 w-2 rounded-full bg-primary" />
+ )}
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent
+ className="p-4"
+ align={layout === "compact" ? "start" : "end"}
+ sideOffset={5}
+ >
+ <div className="mb-3">
+ <h4 className="mb-1 text-sm font-medium">Model Advanced Settings</h4>
+ <p className="text-xs text-muted-foreground">
+ Configure advanced parameters for your model.
+ </p>
+ </div>
+ <div className="space-y-4">
+ <ModelParamsSlider
+ title="Temperature"
+ modelParamsKey="temperature"
+ formDisabled={formDisabled}
+ enabled={modelParams.temperature.enabled}
+ setModelParamEnabled={setModelParamEnabled}
+ value={modelParams.temperature.value}
+ min={0}
+ max={modelParams.maxTemperature.value}
+ step={0.01}
+ tooltip="The sampling temperature. Higher values will make the output more random, while lower values will make it more focused and deterministic."
+ updateModelParam={updateModelParamValue}
+ />
+ <ModelParamsSlider
+ title="Output token limit"
+ modelParamsKey="max_tokens"
+ formDisabled={formDisabled}
+ enabled={modelParams.max_tokens.enabled}
+ setModelParamEnabled={setModelParamEnabled}
+ value={modelParams.max_tokens.value}
+ min={1}
+ max={16384}
+ step={1}
+ tooltip="The maximum number of tokens that can be generated in the chat completion."
+ updateModelParam={updateModelParamValue}
+ />
+ <ModelParamsSlider
+ title="Top P"
+ modelParamsKey="top_p"
+ formDisabled={formDisabled}
+ enabled={modelParams.top_p.enabled}
+ setModelParamEnabled={setModelParamEnabled}
+ value={modelParams.top_p.value}
+ min={0}
+ max={1}
+ step={0.01}
+ tooltip="An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or temperature but not both."
+ updateModelParam={updateModelParamValue}
+ />
+ <LLMApiKeyComponent {...{ projectId, modelParams }} />
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+
+ // Compact layout - single horizontal row following standard codebase patterns
+ if (layout === "compact") {
+ // Create combined options in "Provider: model" format
+ // We create combinations of all available providers with all available models
+ const combinedOptions: string[] = [];
+ availableProviders.forEach((provider) => {
+ availableModels.forEach((model) => {
+ combinedOptions.push(`${provider}: ${model}`);
+ });
+ });
+
+ // Current combined value in "Provider: model" format
+ const currentCombinedValue = `${modelParams.provider.value}: ${modelParams.model.value}`;
+
+ const handleCombinedSelection = (combinedValue: string) => {
+ // Parse the combined value back into provider and model
+ const colonIndex = combinedValue.indexOf(": ");
+ if (colonIndex !== -1) {
+ const provider = combinedValue.substring(0, colonIndex);
+ const model = combinedValue.substring(colonIndex + 2);
+ updateModelParamValue("provider", provider);
+ updateModelParamValue("model", model);
+ }
+ };
+
+ return (
+ <div className="flex flex-col space-y-2 pb-1 pr-1 pt-2">
+ <div className="flex items-center gap-2">
+ <div className="min-w-0 flex-1 space-y-1">
+ <Select
+ disabled={formDisabled}
+ onValueChange={handleCombinedSelection}
+ value={currentCombinedValue}
+ >
+ <SelectTrigger className="h-8">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {combinedOptions.map((option) => (
+ <SelectItem value={option} key={option}>
+ {option}
+ </SelectItem>
+ ))}
+ <SelectSeparator />
+ <CreateLLMApiKeyDialog />
+ </SelectContent>
+ </Select>
+ {modelParamsDescription ? (
+ <FormDescription className="mt-1 text-xs">
+ {modelParamsDescription}
+ </FormDescription>
+ ) : undefined}
+ </div>
+ <div className="flex-shrink-0">{SettingsButton}</div>
+ </div>
+
+ {modelParams.model.value?.startsWith("o1-") ? (
+ <p className="mt-1 text-xs text-dark-yellow">
+ For {modelParams.model.value}, the system message and the
+ temperature, max_tokens and top_p setting are not supported while it
+ is in beta.{" "}
+ <a
+ href="https://platform.openai.com/docs/guides/reasoning/beta-limitations"
+ target="_blank"
+ rel="noreferrer noopener"
+ >
+ More info ↗
+ </a>
+ </p>
+ ) : null}
+ </div>
+ );
+ }
+
+ // Vertical layout (default) - existing behavior
return (
<div className="flex flex-col space-y-2 pb-1 pr-1 pt-2">
<div className="flex items-center justify-between">
{customHeader ? customHeader : <p className="font-semibold">Model</p>}
- <Popover open={modelSettingsOpen} onOpenChange={setModelSettingsOpen}>
- <PopoverTrigger asChild>
- <Button
- variant="outline"
- size="icon"
- className="relative h-7 w-7"
- disabled={formDisabled}
- >
- <Settings2 size={14} />
- {modelSettingsUsed && (
- <div className="absolute -right-0.5 -top-0.5 h-2 w-2 rounded-full bg-primary" />
- )}
- </Button>
- </PopoverTrigger>
- <PopoverContent className="p-4" align="end" sideOffset={5}>
- <div className="mb-3">
- <h4 className="mb-1 text-sm font-medium">
- Model Advanced Settings
- </h4>
- <p className="text-xs text-muted-foreground">
- Configure advanced parameters for your model.
- </p>
- </div>
- <div className="space-y-4">
- <ModelParamsSlider
- title="Temperature"
- modelParamsKey="temperature"
- formDisabled={formDisabled}
- enabled={modelParams.temperature.enabled}
- setModelParamEnabled={setModelParamEnabled}
- value={modelParams.temperature.value}
- min={0}
- max={modelParams.maxTemperature.value}
- step={0.01}
- tooltip="The sampling temperature. Higher values will make the output more random, while lower values will make it more focused and deterministic."
- updateModelParam={updateModelParamValue}
- />
- <ModelParamsSlider
- title="Output token limit"
- modelParamsKey="max_tokens"
- formDisabled={formDisabled}
- enabled={modelParams.max_tokens.enabled}
- setModelParamEnabled={setModelParamEnabled}
- value={modelParams.max_tokens.value}
- min={1}
- max={65535}
- step={1}
- tooltip="The maximum number of tokens that can be generated in the chat completion."
- updateModelParam={updateModelParamValue}
- />
- <ModelParamsSlider
- title="Top P"
- modelParamsKey="top_p"
- formDisabled={formDisabled}
- enabled={modelParams.top_p.enabled}
- setModelParamEnabled={setModelParamEnabled}
- value={modelParams.top_p.value}
- min={0}
- max={1}
- step={0.01}
- tooltip="An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or temperature but not both."
- updateModelParam={updateModelParamValue}
- />
- <LLMApiKeyComponent {...{ projectId, modelParams }} />
- </div>
- </PopoverContent>
- </Popover>
+ {SettingsButton}
</div>
<div className="space-y-4">
@@ -171,6 +255,7 @@ export const ModelParameters: React.FC<ModelParamsContext> = ({
value={modelParams.provider.value}
options={availableProviders}
updateModelParam={updateModelParamValue}
+ layout="vertical"
/>
<ModelParamsSelect
title="Model name"
@@ -180,6 +265,7 @@ export const ModelParameters: React.FC<ModelParamsContext> = ({
options={[...new Set(availableModels)]}
updateModelParam={updateModelParamValue}
modelParamsDescription={modelParamsDescription}
+ layout="vertical"
/>
</div>
@@ -210,6 +296,7 @@ type ModelParamsSelectProps = {
updateModelParam: ModelParamsContext["updateModelParamValue"];
disabled?: boolean;
modelParamsDescription?: string;
+ layout?: "vertical" | "compact";
};
const ModelParamsSelect = ({
title,
@@ -219,7 +306,45 @@ const ModelParamsSelect = ({
updateModelParam,
disabled,
modelParamsDescription,
+ layout = "vertical",
}: ModelParamsSelectProps) => {
+ // Compact layout - simplified, space-efficient (no individual labels)
+ if (layout === "compact") {
+ return (
+ <div className="space-y-1">
+ <Select
+ disabled={disabled}
+ onValueChange={(value) =>
+ updateModelParam(
+ modelParamsKey,
+ value as (typeof supportedModels)[LLMAdapter][number],
+ )
+ }
+ value={value}
+ >
+ <SelectTrigger className="h-8">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {options.map((option) => (
+ <SelectItem value={option} key={option}>
+ {option}
+ </SelectItem>
+ ))}
+ <SelectSeparator />
+ <CreateLLMApiKeyDialog />
+ </SelectContent>
+ </Select>
+ {modelParamsDescription ? (
+ <FormDescription className="mt-1 text-xs">
+ {modelParamsDescription}
+ </FormDescription>
+ ) : undefined}
+ </div>
+ );
+ }
+
+ // Vertical layout (default) - existing behavior
return (
<div className="flex items-center gap-4">
<div className="w-24 flex-shrink-0">
diff --git a/web/src/features/playground/page/components/CollapsibleSection.tsx b/web/src/features/playground/page/components/CollapsibleSection.tsx
new file mode 100644
index 0000000000..ad63a2fe74
--- /dev/null
+++ b/web/src/features/playground/page/components/CollapsibleSection.tsx
@@ -0,0 +1,100 @@
+import React, { useState } from "react";
+import { Button } from "@/src/components/ui/button";
+import { Badge } from "@/src/components/ui/badge";
+import { ChevronRight, ChevronDown } from "lucide-react";
+import { cn } from "@/src/utils/tailwind";
+
+interface CollapsibleSectionProps {
+ title: string;
+ badge?: string;
+ count?: number;
+ defaultExpanded?: boolean;
+ actionButton?: React.ReactNode;
+ children: React.ReactNode;
+ isEmpty?: boolean;
+ emptyMessage?: string;
+ className?: string;
+ summaryContent?: string | React.ReactNode;
+}
+
+export const CollapsibleSection: React.FC<CollapsibleSectionProps> = ({
+ title,
+ badge,
+ count,
+ defaultExpanded = false,
+ actionButton,
+ children,
+ isEmpty = false,
+ emptyMessage,
+ className,
+ summaryContent,
+}) => {
+ const [isExpanded, setIsExpanded] = useState(defaultExpanded);
+
+ const toggleExpanded = () => {
+ setIsExpanded(!isExpanded);
+ };
+
+ const hasContent = count !== undefined ? count > 0 : !isEmpty;
+
+ return (
+ <div className={cn("space-y-1", className)}>
+ {/* Header */}
+ <div className="flex items-center justify-between">
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={toggleExpanded}
+ className="h-8 gap-2 px-1 hover:bg-transparent"
+ >
+ {isExpanded ? (
+ <ChevronDown className="h-3 w-3" />
+ ) : (
+ <ChevronRight className="h-3 w-3" />
+ )}
+ <span className="text-sm font-semibold">{title}</span>
+ {badge && (
+ <Badge variant="secondary" className="h-4 text-xs">
+ {badge}
+ </Badge>
+ )}
+ {count !== undefined && count > 0 && (
+ <Badge variant="outline" className="h-4 text-xs">
+ {count}
+ </Badge>
+ )}
+ </Button>
+ {actionButton && (
+ <div className="flex items-center gap-1">{actionButton}</div>
+ )}
+ </div>
+
+ {/* Content */}
+ {isExpanded && (
+ <div className="space-y-2">
+ {hasContent ? (
+ children
+ ) : (
+ <div className="px-2 py-1">
+ <p className="text-xs text-muted-foreground">
+ {emptyMessage || "No items configured."}
+ </p>
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Compact summary when collapsed */}
+ {!isExpanded && (hasContent || summaryContent) && (
+ <div className="px-2 py-0.5">
+ <p className="text-xs text-muted-foreground">
+ {summaryContent ||
+ (count !== undefined && count > 0
+ ? `${count} item${count === 1 ? "" : "s"} configured`
+ : "Configured")}
+ </p>
+ </div>
+ )}
+ </div>
+ );
+};
diff --git a/web/src/features/playground/page/components/ConfigurationDropdowns.tsx b/web/src/features/playground/page/components/ConfigurationDropdowns.tsx
new file mode 100644
index 0000000000..2d443a7805
--- /dev/null
+++ b/web/src/features/playground/page/components/ConfigurationDropdowns.tsx
@@ -0,0 +1,185 @@
+import React from "react";
+import { Button } from "@/src/components/ui/button";
+import { Badge } from "@/src/components/ui/badge";
+import { ChevronDown, Wrench, Braces, Variable } from "lucide-react";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/src/components/ui/popover";
+import { usePlaygroundContext } from "../context";
+import { usePlaygroundWindowSize } from "../hooks/usePlaygroundWindowSize";
+import { PlaygroundTools, PlaygroundToolsPopover } from "./PlaygroundTools";
+import {
+ StructuredOutputSchemaSection,
+ StructuredOutputSchemaPopover,
+} from "./StructuredOutputSchemaSection";
+import { Variables } from "./Variables";
+import { MessagePlaceholders } from "./MessagePlaceholders";
+
+export const ConfigurationDropdowns: React.FC = () => {
+ const { containerRef, isVeryCompact, isCompact } = usePlaygroundWindowSize();
+ const {
+ tools,
+ structuredOutputSchema,
+ promptVariables,
+ messagePlaceholders,
+ } = usePlaygroundContext();
+
+ const toolsCount = tools.length;
+ const hasSchema = structuredOutputSchema ? 1 : 0;
+ const variablesCount = promptVariables.length + messagePlaceholders.length;
+
+ // Helper function to get responsive content (text or icon)
+ const getResponsiveContent = (
+ fullText: string,
+ IconComponent: React.ComponentType<{ className?: string }>,
+ abbreviation?: string,
+ ) => {
+ if (isVeryCompact) {
+ return <IconComponent className="h-3 w-3" />;
+ }
+ if (isCompact) {
+ return (
+ <>
+ <IconComponent className="h-3 w-3" />
+ <span className="text-sm">{abbreviation ?? fullText}</span>
+ </>
+ );
+ }
+ return (
+ <>
+ <IconComponent className="h-3 w-3" />
+ <span className="text-sm">{fullText}</span>
+ </>
+ );
+ };
+
+ return (
+ <div
+ ref={containerRef}
+ className="flex-shrink-0 border-b bg-muted/25 px-3 py-2"
+ >
+ <div className="flex items-center justify-start gap-2">
+ {/* Tools Dropdown */}
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button variant="outline" size="sm" className="h-8 gap-2">
+ {getResponsiveContent("Tools", Wrench)}
+ {toolsCount > 0 && (
+ <Badge variant="secondary" className="h-4 text-xs">
+ {toolsCount}
+ </Badge>
+ )}
+ <ChevronDown className="h-3 w-3" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-80 p-4" align="start">
+ <div className="mb-3">
+ <h4 className="mb-1 text-sm font-medium">Tools</h4>
+ <p className="text-xs text-muted-foreground">
+ Configure tools for your model to use.
+ </p>
+ </div>
+ {toolsCount > 0 ? (
+ <div className="mb-3">
+ <PlaygroundTools />
+ </div>
+ ) : (
+ <div className="mb-3">
+ <p className="text-xs text-muted-foreground">
+ No tools attached.
+ </p>
+ </div>
+ )}
+ <div className="border-t pt-3">
+ <PlaygroundToolsPopover />
+ </div>
+ </PopoverContent>
+ </Popover>
+
+ {/* Structured Output Dropdown */}
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button variant="outline" size="sm" className="h-8 gap-2">
+ {getResponsiveContent("Schema", Braces)}
+ {hasSchema > 0 && (
+ <Badge variant="secondary" className="h-4 text-xs">
+ {hasSchema}
+ </Badge>
+ )}
+ <ChevronDown className="h-3 w-3" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-80 p-4" align="start">
+ <div className="mb-3">
+ <h4 className="mb-1 text-sm font-medium">Structured Output</h4>
+ <p className="text-xs text-muted-foreground">
+ Configure JSON schema for structured output.
+ </p>
+ </div>
+ {structuredOutputSchema ? (
+ <div className="mb-3">
+ <StructuredOutputSchemaSection />
+ </div>
+ ) : (
+ <div className="mb-3">
+ <p className="text-xs text-muted-foreground">
+ No schema provided.
+ </p>
+ </div>
+ )}
+ <div className="border-t pt-3">
+ <StructuredOutputSchemaPopover />
+ </div>
+ </PopoverContent>
+ </Popover>
+
+ {/* Variables & Placeholders Dropdown */}
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button variant="outline" size="sm" className="h-8 gap-2">
+ {getResponsiveContent("Variables", Variable, "Vars")}
+ {variablesCount > 0 && (
+ <Badge variant="secondary" className="h-4 text-xs">
+ {variablesCount}
+ </Badge>
+ )}
+ <ChevronDown className="h-3 w-3" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-80 p-4" align="start">
+ <div className="mb-3">
+ <h4 className="mb-1 text-sm font-medium">
+ Variables & Message Placeholders
+ </h4>
+ <p className="text-xs text-muted-foreground">
+ Configure variables and message placeholders for your prompts.
+ </p>
+ </div>
+ {variablesCount > 0 ? (
+ <div className="mb-3 space-y-4">
+ <div>
+ <h5 className="mb-2 text-xs font-medium">Variables</h5>
+ <Variables />
+ </div>
+ <div>
+ <h5 className="mb-2 text-xs font-medium">
+ Message Placeholders
+ </h5>
+ <MessagePlaceholders />
+ </div>
+ </div>
+ ) : (
+ <div className="mb-3">
+ <p className="text-xs text-muted-foreground">
+ No variables or message placeholders defined.
+ </p>
+ </div>
+ )}
+ </PopoverContent>
+ </Popover>
+ </div>
+ </div>
+ );
+};
diff --git a/web/src/features/playground/page/components/JumpToPlaygroundButton.tsx b/web/src/features/playground/page/components/JumpToPlaygroundButton.tsx
index e93b2df998..6809e5b3ef 100644
--- a/web/src/features/playground/page/components/JumpToPlaygroundButton.tsx
+++ b/web/src/features/playground/page/components/JumpToPlaygroundButton.tsx
@@ -1,11 +1,18 @@
-import { Terminal } from "lucide-react";
+import { Terminal, ChevronDown } from "lucide-react";
import { useEffect, useState, useMemo } from "react";
import { useRouter } from "next/router";
import { z } from "zod/v4";
+import { v4 as uuidv4 } from "uuid";
import { createEmptyMessage } from "@/src/components/ChatMessages/utils/createEmptyMessage";
import { Button } from "@/src/components/ui/button";
-import usePlaygroundCache from "@/src/features/playground/page/hooks/usePlaygroundCache";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/src/components/ui/dropdown-menu";
+import { usePersistedWindowIds } from "@/src/features/playground/page/hooks/usePersistedWindowIds";
import {
type PlaygroundCache,
type PlaygroundSchema,
@@ -38,6 +45,7 @@ import {
} from "@/src/features/trace-graph-view/types";
import { api } from "@/src/utils/api";
import { cn } from "@/src/utils/tailwind";
+import usePlaygroundCache from "@/src/features/playground/page/hooks/usePlaygroundCache";
type JumpToPlaygroundButtonProps = (
| {
@@ -65,10 +73,21 @@ export const JumpToPlaygroundButton: React.FC<JumpToPlaygroundButtonProps> = (
const router = useRouter();
const capture = usePostHogClientCapture();
const projectId = useProjectIdFromURL();
- const { setPlaygroundCache } = usePlaygroundCache();
+ const { addWindowWithId, clearAllCache } = usePersistedWindowIds();
const [capturedState, setCapturedState] = useState<PlaygroundCache>(null);
const [isAvailable, setIsAvailable] = useState<boolean>(false);
+ // Generate a stable window ID based on the source data
+ const stableWindowId = useMemo(() => {
+ if (props.source === "prompt") {
+ return `playground-prompt-${props.prompt.id}`;
+ } else if (props.source === "generation") {
+ return `playground-generation-${props.generation.id}`;
+ }
+ return `playground-${uuidv4()}`;
+ }, [props]);
+ const { setPlaygroundCache } = usePlaygroundCache(stableWindowId);
+
const apiKeys = api.llmApiKey.all.useQuery(
{
projectId: projectId as string,
@@ -112,35 +131,84 @@ export const JumpToPlaygroundButton: React.FC<JumpToPlaygroundButtonProps> = (
}
}, [capturedState, setIsAvailable]);
- const handleClick = () => {
- capture(props.analyticsEventName);
- setPlaygroundCache(capturedState);
+ const handlePlaygroundAction = (useFreshPlayground: boolean) => {
+ capture(props.analyticsEventName, {
+ playgroundMode: useFreshPlayground ? "fresh" : "add_to_existing",
+ });
- router.push(`/project/${projectId}/playground`);
- };
+ // First, ensure we have state to save
+ if (!capturedState) {
+ console.warn("No captured state available for playground");
+ return;
+ }
- return (
- <Button
- variant={props.variant ?? "secondary"}
- disabled={!isAvailable}
- title={
- isAvailable
- ? "Test in LLM playground"
- : "Test in LLM playground is not available since messages are not in valid ChatML format or tool calls have been used. If you think this is not correct, please open a GitHub issue."
+ if (useFreshPlayground) {
+ // Clear all existing playground data and reset to single window
+ clearAllCache(stableWindowId);
+ } else {
+ // Add to existing playground
+ const addedWindowId = addWindowWithId(stableWindowId);
+
+ if (!addedWindowId) {
+ console.warn(
+ "Failed to add window to existing playground, maximum windows reached",
+ );
+ return;
}
- onClick={handleClick}
- asChild
- className={
- !isAvailable ? "cursor-not-allowed opacity-50" : "cursor-pointer"
+ }
+
+ // Use requestAnimationFrame to ensure the state update has been processed
+ requestAnimationFrame(() => {
+ try {
+ setPlaygroundCache(capturedState);
+ console.log(
+ `Cache saved for existing playground window ${stableWindowId}`,
+ );
+
+ // Navigate after cache is successfully saved
+ router.push(`/project/${projectId}/playground`);
+ } catch (error) {
+ console.error("Failed to save playground cache:", error);
+ // Navigate anyway, but user might not see their data
+ router.push(`/project/${projectId}/playground`);
}
- >
- <span>
- <Terminal className="h-4 w-4" />
- <span className={cn("hidden md:ml-2 md:inline", props.className)}>
- Playground
- </span>
- </span>
- </Button>
+ });
+ };
+
+ const tooltipMessage = isAvailable
+ ? "Test in LLM playground"
+ : "Test in LLM playground is not available since messages are not in valid ChatML format or tool calls have been used. If you think this is not correct, please open a GitHub issue.";
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant={props.variant ?? "secondary"}
+ disabled={!isAvailable}
+ title={tooltipMessage}
+ className={cn(
+ "flex items-center gap-1",
+ !isAvailable ? "cursor-not-allowed opacity-50" : "cursor-pointer",
+ )}
+ >
+ <Terminal className="h-4 w-4" />
+ <span className={cn("hidden md:inline", props.className)}>
+ Playground
+ </span>
+ <ChevronDown className="h-3 w-3" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={() => handlePlaygroundAction(true)}>
+ <Terminal className="mr-2 h-4 w-4" />
+ Fresh playground
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => handlePlaygroundAction(false)}>
+ <Terminal className="mr-2 h-4 w-4" />
+ Add to existing
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
);
};
diff --git a/web/src/features/playground/page/components/MessagePlaceholders.tsx b/web/src/features/playground/page/components/MessagePlaceholders.tsx
index 30c58249df..36aafda105 100644
--- a/web/src/features/playground/page/components/MessagePlaceholders.tsx
+++ b/web/src/features/playground/page/components/MessagePlaceholders.tsx
@@ -8,38 +8,33 @@ export const MessagePlaceholders = () => {
return (
<div className="flex h-full flex-col">
- <p className="font-semibold">Message Placeholders</p>
- <div className="min-h-0 flex-1 overflow-y-auto overflow-x-hidden">
- {messagePlaceholders.length === 0 ? (
- <div className="mt-4 text-xs">
- <p className="mb-2">No message placeholders defined.</p>
- <p>
- Placeholders can be used to e.g. inject message histories into
- prompts.
- </p>
- </div>
- ) : (
- <>
- {messagePlaceholders
- .slice()
- .sort((a, b) => {
- if (a.isUsed && !b.isUsed) return -1;
- if (!a.isUsed && b.isUsed) return 1;
- return a.name.localeCompare(b.name);
- })
- .map((placeholder, index) => (
- <div key={placeholder.name}>
- <MessagePlaceholderComponent
- messagePlaceholder={placeholder}
- />
- {index !== messagePlaceholders.length - 1 && (
- <Divider className="my-2 text-muted-foreground" />
- )}
- </div>
- ))}
- </>
- )}
- </div>
+ {messagePlaceholders.length === 0 ? (
+ <div className="text-xs">
+ <p className="mb-2">No message placeholders defined.</p>
+ <p>
+ Placeholders can be used to e.g. inject message histories into
+ prompts.
+ </p>
+ </div>
+ ) : (
+ <div className="h-full overflow-auto">
+ {messagePlaceholders
+ .slice()
+ .sort((a, b) => {
+ if (a.isUsed && !b.isUsed) return -1;
+ if (!a.isUsed && b.isUsed) return 1;
+ return a.name.localeCompare(b.name);
+ })
+ .map((placeholder, index) => (
+ <div key={placeholder.name}>
+ <MessagePlaceholderComponent messagePlaceholder={placeholder} />
+ {index !== messagePlaceholders.length - 1 && (
+ <Divider className="my-2 text-muted-foreground" />
+ )}
+ </div>
+ ))}
+ </div>
+ )}
</div>
);
};
diff --git a/web/src/features/playground/page/components/Messages.tsx b/web/src/features/playground/page/components/Messages.tsx
index d7b61ca54d..7cfd422f5c 100644
--- a/web/src/features/playground/page/components/Messages.tsx
+++ b/web/src/features/playground/page/components/Messages.tsx
@@ -10,7 +10,6 @@ import { Switch } from "@/src/components/ui/switch";
import { Settings } from "lucide-react";
import useLocalStorage from "@/src/components/useLocalStorage";
import { env } from "@/src/env.mjs";
-import useCommandEnter from "@/src/features/playground/page/hooks/useCommandEnter";
import { GenerationOutput } from "./GenerationOutput";
import { ChatMessages } from "@/src/components/ChatMessages";
@@ -30,7 +29,7 @@ export const Messages: React.FC<MessagesContext> = (props) => {
</ResizablePanel>
<ResizableHandle withHandle className="bg-transparent" />
<ResizablePanel
- minSize={10}
+ minSize={20}
defaultSize={20}
className="flex flex-col space-y-4"
>
@@ -51,11 +50,6 @@ const SubmitButton = () => {
defaultStreamingEnabled,
);
- // Handle command+enter with streaming preference
- useCommandEnter(!isStreaming, async () => {
- await handleSubmit(streamingEnabled);
- });
-
return (
<div className="flex items-center gap-2">
<Button
@@ -65,7 +59,7 @@ const SubmitButton = () => {
}}
loading={isStreaming}
>
- <p>Submit (Ctrl + Enter)</p>
+ <p>Submit</p>
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
diff --git a/web/src/features/playground/page/components/MultiWindowPlayground.tsx b/web/src/features/playground/page/components/MultiWindowPlayground.tsx
new file mode 100644
index 0000000000..c39c068cca
--- /dev/null
+++ b/web/src/features/playground/page/components/MultiWindowPlayground.tsx
@@ -0,0 +1,198 @@
+import React, { useMemo, useCallback } from "react";
+import { PlaygroundProvider } from "../context";
+import { SaveToPromptButton } from "./SaveToPromptButton";
+import { Button } from "@/src/components/ui/button";
+import { Copy, X } from "lucide-react";
+import { MULTI_WINDOW_CONFIG, type MultiWindowState } from "../types";
+import { ModelParameters } from "@/src/components/ModelParameters";
+import { usePlaygroundContext } from "../context";
+import { Messages } from "@/src/features/playground/page/components/Messages";
+import { ConfigurationDropdowns } from "@/src/features/playground/page/components/ConfigurationDropdowns";
+
+/**
+ * MultiWindowPlayground Component
+ *
+ * Container component that renders multiple playground windows for side-by-side
+ * prompt comparison and testing. Receives window state and management functions
+ * from the parent page component.
+ *
+ * Key Features:
+ * - Responsive layout with horizontal scrolling
+ * - Window-specific state isolation
+ * - Equal-width distribution with minimum width constraints
+ * - Individual window controls (save, copy, close)
+ * - Window state copying for rapid iteration
+ *
+ * Architecture:
+ * - Receives window state from parent (page-level management)
+ * - Each window gets its own PlaygroundProvider with unique windowId
+ * - State copying handled by parent component through hooks
+ * - Clean separation of concerns with parent handling global actions
+ */
+
+interface MultiWindowPlaygroundProps {
+ windowState: MultiWindowState;
+ onRemoveWindow: (windowId: string) => void;
+ onAddWindow: (sourceWindowId?: string) => void;
+}
+
+export default function MultiWindowPlayground({
+ windowState,
+ onRemoveWindow,
+ onAddWindow,
+}: MultiWindowPlaygroundProps) {
+ /**
+ * Calculate responsive window width based on screen size and window count
+ * Ensures minimum width while distributing available space equally
+ */
+ const windowWidth = useMemo(() => {
+ const minWidth = MULTI_WINDOW_CONFIG.MIN_WINDOW_WIDTH;
+ const windowCount = windowState.windowIds.length;
+
+ // Calculate ideal width: 100% divided by number of windows
+ const idealWidth = `${100 / windowCount}%`;
+
+ // Use CSS minmax to ensure minimum width is respected
+ return `minmax(${minWidth}px, ${idealWidth})`;
+ }, [windowState.windowIds.length]);
+
+ /**
+ * Handle copying a specific window to create a new window
+ * This is called when the individual window "Copy" button is clicked
+ *
+ * @param sourceWindowId - The window ID to copy from
+ */
+ const handleCopyWindow = useCallback(
+ (sourceWindowId: string) => {
+ onAddWindow(sourceWindowId);
+ },
+ [onAddWindow],
+ );
+
+ const firstWindowId = windowState.windowIds[0];
+ if (!firstWindowId) return null;
+
+ return (
+ <>
+ {/* Mobile layout: single window only - visible below md breakpoint */}
+ <div className="block h-full p-4 md:hidden">
+ <PlaygroundProvider windowId={firstWindowId}>
+ <PlaygroundWindowContent
+ windowId={firstWindowId}
+ onRemove={onRemoveWindow}
+ onCopy={handleCopyWindow}
+ canRemove={false}
+ isMobile={true}
+ />
+ </PlaygroundProvider>
+ </div>
+
+ {/* Desktop layout: multi-window with horizontal grid - visible at md breakpoint and above */}
+ <div className="hidden h-full md:block">
+ <div
+ className="h-full overflow-x-auto"
+ style={{
+ display: "grid",
+ gridAutoFlow: "column",
+ gridAutoColumns: windowWidth,
+ gap: "1rem",
+ padding: "1rem",
+ scrollBehavior: "smooth",
+ }}
+ >
+ {windowState.windowIds.map((windowId) => (
+ <PlaygroundProvider key={windowId} windowId={windowId}>
+ <PlaygroundWindowContent
+ windowId={windowId}
+ onRemove={onRemoveWindow}
+ onCopy={handleCopyWindow}
+ canRemove={windowState.windowIds.length > 1}
+ isMobile={false}
+ />
+ </PlaygroundProvider>
+ ))}
+ </div>
+ </div>
+ </>
+ );
+}
+
+/**
+ * Inner component that has access to the PlaygroundProvider context
+ */
+function PlaygroundWindowContent({
+ windowId,
+ onRemove,
+ onCopy,
+ canRemove,
+ isMobile,
+}: {
+ windowId: string;
+ onRemove: (windowId: string) => void;
+ onCopy: (windowId: string) => void;
+ canRemove: boolean;
+ windowCount?: number;
+ isMobile?: boolean;
+}) {
+ const playgroundContext = usePlaygroundContext();
+
+ const handleRemove = useCallback(() => {
+ onRemove(windowId);
+ }, [windowId, onRemove]);
+
+ const handleCopy = useCallback(() => {
+ onCopy(windowId);
+ }, [windowId, onCopy]);
+
+ return (
+ <div className="playground-window flex h-full min-w-0 flex-col rounded-lg border bg-background shadow-sm">
+ {/* Window Header */}
+ <div className="relative flex-shrink-0 border-b bg-muted/50 px-3 py-1">
+ <div className="flex items-center pr-24">
+ <div className="flex items-center gap-2">
+ <ModelParameters {...playgroundContext} layout="compact" />
+ </div>
+
+ <div className="absolute right-3 top-1/2 flex -translate-y-1/2 items-center gap-2">
+ <SaveToPromptButton />
+
+ {/* Hide copy button on mobile */}
+ {!isMobile && (
+ <Button
+ variant="ghost"
+ onClick={handleCopy}
+ className="h-6 w-6 p-0 hover:bg-muted"
+ title="Duplicate window configuration"
+ >
+ <Copy size={14} />
+ <span className="sr-only">Copy window</span>
+ </Button>
+ )}
+ {canRemove && (
+ <Button
+ variant="ghost"
+ onClick={handleRemove}
+ className="h-6 w-6 p-0 hover:bg-destructive/10 hover:text-destructive"
+ title="Remove window"
+ >
+ <X size={14} />
+ <span className="sr-only">Remove window</span>
+ </Button>
+ )}
+ </div>
+ </div>
+ </div>
+
+ {/* Window Content */}
+ <div className="flex-1 overflow-hidden">
+ <div className="flex h-full flex-col">
+ <ConfigurationDropdowns />
+
+ <div className="flex-1 overflow-auto p-4">
+ <Messages {...playgroundContext} />
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/web/src/features/playground/page/components/PlaygroundTools/index.tsx b/web/src/features/playground/page/components/PlaygroundTools/index.tsx
index f8c269fde7..1749821e02 100644
--- a/web/src/features/playground/page/components/PlaygroundTools/index.tsx
+++ b/web/src/features/playground/page/components/PlaygroundTools/index.tsx
@@ -1,4 +1,4 @@
-import React, { useCallback, useEffect, useState } from "react";
+import React, { useCallback, useEffect } from "react";
import { usePlaygroundContext } from "@/src/features/playground/page/context";
import { Button } from "@/src/components/ui/button";
@@ -17,18 +17,128 @@ import {
CommandList,
CommandSeparator,
} from "@/src/components/ui/command";
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from "@/src/components/ui/popover";
import { type PlaygroundTool } from "@/src/features/playground/page/types";
+// Popover content component for use in CollapsibleSection action buttons
+export const PlaygroundToolsPopover = () => {
+ const { setTools } = usePlaygroundContext();
+ const projectId = useProjectIdFromURL();
+
+ const { data: savedTools = [] } = api.llmTools.getAll.useQuery(
+ {
+ projectId: projectId as string,
+ },
+ {
+ enabled: Boolean(projectId),
+ staleTime: 1000 * 60 * 5, // 5 minutes
+ },
+ );
+
+ const handleSelectTool = (selectedLLMTool: LlmTool) => {
+ setTools((prev: PlaygroundTool[]) => {
+ let existingToolIndex = -1;
+ existingToolIndex = prev.findIndex((t) => t.id === selectedLLMTool.id);
+
+ if (existingToolIndex === -1) {
+ const unsavedToolIndexWithSameName = prev.findIndex(
+ (t) => t.name === selectedLLMTool.name,
+ );
+
+ if (unsavedToolIndexWithSameName !== -1) {
+ existingToolIndex = unsavedToolIndexWithSameName;
+ }
+ }
+
+ const newTool: PlaygroundTool = {
+ id: selectedLLMTool.id,
+ name: selectedLLMTool.name,
+ description: selectedLLMTool.description,
+ parameters: selectedLLMTool.parameters as Record<string, unknown>,
+ existingLlmTool: selectedLLMTool,
+ };
+
+ if (existingToolIndex !== -1) {
+ const newTools = [...prev];
+ newTools[existingToolIndex] = newTool;
+ return newTools;
+ }
+
+ return [...prev, newTool];
+ });
+ };
+
+ const handleRemoveTool = (toolId: string) => {
+ setTools(
+ (prev: PlaygroundTool[]) =>
+ prev.filter((t) => !(t.id === toolId)) as PlaygroundTool[],
+ );
+ };
+
+ return (
+ <Command className="flex flex-col">
+ <CommandInput
+ placeholder="Search tools..."
+ className="h-8 border-none p-1 focus:ring-0 focus:ring-offset-0"
+ />
+ <CommandList className="max-h-[300px] overflow-y-auto">
+ <CommandEmpty>No tools found.</CommandEmpty>
+ <CommandGroup>
+ {savedTools.map((tool) => (
+ <CommandItem
+ key={tool.id}
+ value={tool.name}
+ onSelect={() => handleSelectTool(tool)}
+ className="flex items-center justify-between px-1 py-2"
+ >
+ <div className="flex items-center gap-2">
+ <WrenchIcon size={12} className="text-muted-foreground" />
+ <div className="flex-1 overflow-hidden">
+ <div className="truncate font-medium">{tool.name}</div>
+ <div className="line-clamp-1 text-xs text-muted-foreground">
+ {tool.description}
+ </div>
+ </div>
+ </div>
+ <CreateOrEditLLMToolDialog
+ projectId={projectId as string}
+ onSave={handleSelectTool}
+ onDelete={() => handleRemoveTool(tool.id)}
+ existingLlmTool={tool}
+ >
+ <Button
+ variant="ghost"
+ size="icon"
+ className="ml-2 h-7 w-7 shrink-0"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <PencilIcon className="h-3.5 w-3.5" />
+ </Button>
+ </CreateOrEditLLMToolDialog>
+ </CommandItem>
+ ))}
+ </CommandGroup>
+ <CommandSeparator />
+ </CommandList>
+ <div className="mt-auto p-1">
+ <CreateOrEditLLMToolDialog
+ projectId={projectId as string}
+ onSave={handleSelectTool}
+ >
+ <Button variant="outline" size="default" className="w-full">
+ <PlusIcon className="mr-2 h-4 w-4" />
+ Create new tool
+ </Button>
+ </CreateOrEditLLMToolDialog>
+ </div>
+ </Command>
+ );
+};
+
+// Main component for embedding in CollapsibleSection content
export const PlaygroundTools = () => {
const { tools, setTools } = usePlaygroundContext();
const projectId = useProjectIdFromURL();
- const [isSearchOpen, setIsSearchOpen] = useState(false);
const { data: savedTools = [] } = api.llmTools.getAll.useQuery(
{
@@ -99,13 +209,11 @@ export const PlaygroundTools = () => {
if (existingToolIndex !== -1) {
const newTools = [...prev];
newTools[existingToolIndex] = newTool;
-
return newTools;
}
return [...prev, newTool];
});
- setIsSearchOpen(false);
};
const handleRemoveTool = (toolId: string) => {
@@ -116,159 +224,71 @@ export const PlaygroundTools = () => {
};
return (
- <div className="flex h-full flex-col pr-1">
- <div className="mb-2 flex items-center justify-between">
- <div className="flex items-center gap-2">
- <p className="font-semibold">Tools</p>
- <a
- href="https://github.com/orgs/langfuse/discussions/3166"
- target="_blank"
- rel="noopener noreferrer"
- className="inline-flex items-center"
- title="Tool calling is currently in beta. Click here to learn more and provide feedback!"
- >
- <span className="rounded bg-muted px-1.5 py-0.5 text-xs font-medium text-muted-foreground">
- Beta
- </span>
- </a>
+ <ScrollArea className="h-full">
+ {tools.length === 0 ? (
+ <div className="flex h-16 flex-col items-center justify-center p-4 text-center">
+ <p className="text-xs text-muted-foreground">No tools attached.</p>
</div>
- <Popover open={isSearchOpen} onOpenChange={setIsSearchOpen}>
- <PopoverTrigger asChild>
- <Button className="h-7 w-7" variant="outline" size="icon">
- <PlusIcon size={14} />
- </Button>
- </PopoverTrigger>
- <PopoverContent align="end" className="p-1">
- <Command className="flex flex-col">
- <CommandInput
- placeholder="Search tools..."
- className="h-8 border-none p-1 focus:ring-0 focus:ring-offset-0"
- />
- <CommandList className="max-h-[300px] overflow-y-auto">
- <CommandEmpty>No tools found.</CommandEmpty>
- <CommandGroup>
- {savedTools.map((tool) => (
- <CommandItem
- key={tool.id}
- value={tool.name}
- onSelect={() => handleSelectTool(tool)}
- className="flex items-center justify-between px-1 py-2"
+ ) : (
+ <div className="space-y-1">
+ {tools.map((tool) => (
+ <CreateOrEditLLMToolDialog
+ key={tool.id}
+ projectId={projectId as string}
+ onSave={handleSelectTool}
+ onDelete={() => handleRemoveTool(tool.id)}
+ existingLlmTool={tool.existingLlmTool}
+ defaultValues={
+ !isToolSaved(tool)
+ ? {
+ name: tool.name,
+ description: tool.description,
+ parameters: JSON.stringify(tool.parameters, null, 2),
+ }
+ : undefined
+ }
+ >
+ <div className="cursor-pointer rounded-md border bg-background p-2 transition-colors duration-200 hover:bg-accent/50">
+ <div className="mb-1 flex items-center justify-between">
+ <div className="flex items-center gap-1">
+ <WrenchIcon className="h-4 w-4 text-muted-foreground" />
+ <h3
+ className="max-w-[200px] truncate text-ellipsis text-sm font-medium"
+ title={tool.name}
>
- <div className="flex items-center gap-2">
- <WrenchIcon
- size={12}
- className="text-muted-foreground"
- />
- <div className="flex-1 overflow-hidden">
- <div className="truncate font-medium">
- {tool.name}
- </div>
- <div className="line-clamp-1 text-xs text-muted-foreground">
- {tool.description}
- </div>
- </div>
- </div>
- <CreateOrEditLLMToolDialog
- projectId={projectId as string}
- onSave={handleSelectTool}
- onDelete={() => handleRemoveTool(tool.id)}
- existingLlmTool={tool}
- >
- <Button
- variant="ghost"
- size="icon"
- className="ml-2 h-7 w-7 shrink-0"
- >
- <PencilIcon className="h-3.5 w-3.5" />
- </Button>
- </CreateOrEditLLMToolDialog>
- </CommandItem>
- ))}
- </CommandGroup>
- <CommandSeparator />
- </CommandList>
- <div className="mt-auto p-1">
- <CreateOrEditLLMToolDialog
- projectId={projectId as string}
- onSave={handleSelectTool}
- >
- <Button variant="outline" size="default" className="w-full">
- <PlusIcon className="mr-2 h-4 w-4" />
- Create new tool
- </Button>
- </CreateOrEditLLMToolDialog>
- </div>
- </Command>
- </PopoverContent>
- </Popover>
- </div>
-
- <ScrollArea className="h-[calc(100%-2rem)]">
- {tools.length === 0 ? (
- <div className="flex h-16 flex-col items-center justify-center p-4 text-center">
- <p className="text-xs text-muted-foreground">No tools attached.</p>
- </div>
- ) : (
- <div className="space-y-1">
- {tools.map((tool) => (
- <CreateOrEditLLMToolDialog
- key={tool.id}
- projectId={projectId as string}
- onSave={handleSelectTool}
- onDelete={() => handleRemoveTool(tool.id)}
- existingLlmTool={tool.existingLlmTool}
- defaultValues={
- !isToolSaved(tool)
- ? {
- name: tool.name,
- description: tool.description,
- parameters: JSON.stringify(tool.parameters, null, 2),
- }
- : undefined
- }
- >
- <div className="cursor-pointer rounded-md border bg-background p-2 transition-colors duration-200 hover:bg-accent/50">
- <div className="mb-1 flex items-center justify-between">
- <div className="flex items-center gap-1">
- <WrenchIcon className="h-4 w-4 text-muted-foreground" />
- <h3
- className="max-w-[200px] truncate text-ellipsis text-sm font-medium"
- title={tool.name}
- >
- {tool.name}
- </h3>
- {!isToolSaved(tool) ? (
- <span className="rounded bg-muted px-1 py-0.5 text-xs text-muted-foreground">
- Unsaved
- </span>
- ) : null}
- </div>
- <div className="flex items-center gap-1">
- <Button
- variant="ghost"
- size="sm"
- className="h-6 w-6 p-0"
- onClick={(e) => {
- e.stopPropagation();
- handleRemoveTool(tool.id);
- }}
- >
- <MinusCircle className="h-4 w-4" />
- </Button>
- </div>
+ {tool.name}
+ </h3>
+ {!isToolSaved(tool) ? (
+ <span className="rounded bg-muted px-1 py-0.5 text-xs text-muted-foreground">
+ Unsaved
+ </span>
+ ) : null}
+ </div>
+ <div className="flex items-center gap-1">
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-6 w-6 p-0"
+ onClick={(e) => {
+ e.stopPropagation();
+ handleRemoveTool(tool.id);
+ }}
+ >
+ <MinusCircle className="h-4 w-4" />
+ </Button>
</div>
- <p
- className="line-clamp-2 break-all text-xs text-muted-foreground"
- title={tool.description}
- >
- {tool.description}
- </p>
</div>
- </CreateOrEditLLMToolDialog>
- ))}
- </div>
- )}
- </ScrollArea>
- </div>
+ <p
+ className="line-clamp-2 break-all text-xs text-muted-foreground"
+ title={tool.description}
+ >
+ {tool.description}
+ </p>
+ </div>
+ </CreateOrEditLLMToolDialog>
+ ))}
+ </div>
+ )}
+ </ScrollArea>
);
};
diff --git a/web/src/features/playground/page/components/ResetPlaygroundButton.tsx b/web/src/features/playground/page/components/ResetPlaygroundButton.tsx
index 620b0bfb44..a8f21712bc 100644
--- a/web/src/features/playground/page/components/ResetPlaygroundButton.tsx
+++ b/web/src/features/playground/page/components/ResetPlaygroundButton.tsx
@@ -2,26 +2,26 @@ import { ListRestartIcon } from "lucide-react";
import { useRouter } from "next/router";
import { Button } from "@/src/components/ui/button";
-import usePlaygroundCache from "@/src/features/playground/page/hooks/usePlaygroundCache";
+import { usePersistedWindowIds } from "@/src/features/playground/page/hooks/usePersistedWindowIds";
export const ResetPlaygroundButton: React.FC = () => {
const router = useRouter();
- const { setPlaygroundCache } = usePlaygroundCache();
+ const { clearAllCache } = usePersistedWindowIds();
const handleClick = () => {
- setPlaygroundCache(null);
-
+ clearAllCache();
router.reload();
};
return (
<Button
- variant={"outline"}
+ variant="outline"
title="Reset playground state"
onClick={handleClick}
+ className="gap-1"
>
- <ListRestartIcon className="mr-1 h-4 w-4" />
- <span>Reset playground</span>
+ <ListRestartIcon className="h-4 w-4" />
+ <span className="hidden lg:inline">Reset playground</span>
</Button>
);
};
diff --git a/web/src/features/playground/page/components/SaveToPromptButton.tsx b/web/src/features/playground/page/components/SaveToPromptButton.tsx
index 38ce3ba549..6b25fc08e4 100644
--- a/web/src/features/playground/page/components/SaveToPromptButton.tsx
+++ b/web/src/features/playground/page/components/SaveToPromptButton.tsx
@@ -1,5 +1,4 @@
-import { Check, FileInput } from "lucide-react";
-import Link from "next/link";
+import { Check, Save } from "lucide-react";
import { useRouter } from "next/router";
import { useState } from "react";
@@ -26,7 +25,13 @@ import { cn } from "@/src/utils/tailwind";
import DocPopup from "@/src/components/layouts/doc-popup";
import { PromptType } from "@langfuse/shared";
-export const SaveToPromptButton: React.FC = () => {
+interface SaveToPromptButtonProps {
+ className?: string;
+}
+
+export const SaveToPromptButton: React.FC<SaveToPromptButtonProps> = ({
+ className,
+}) => {
const [selectedPromptId, setSelectedPromptId] = useState("");
const { modelParams, messages, output, promptVariables } =
usePlaygroundContext();
@@ -82,11 +87,13 @@ export const SaveToPromptButton: React.FC = () => {
return (
<Popover>
<PopoverTrigger asChild>
- <Button variant={"outline"} title="Save to prompt" asChild>
- <Link href={`/project/${projectId}/playground`}>
- <FileInput className="mr-1 h-4 w-4" />
- <span>Save as prompt</span>
- </Link>
+ <Button
+ variant="ghost"
+ className={cn("h-6 w-6 p-0 hover:bg-muted", className)}
+ title="Save current configuration as a prompt template for reuse across your project"
+ >
+ <Save size={14} />
+ <span className="sr-only">Save as prompt</span>
</Button>
</PopoverTrigger>
<PopoverContent>
diff --git a/web/src/features/playground/page/components/StructuredOutputSchemaSection.tsx b/web/src/features/playground/page/components/StructuredOutputSchemaSection.tsx
index f8ed40da99..258762ffff 100644
--- a/web/src/features/playground/page/components/StructuredOutputSchemaSection.tsx
+++ b/web/src/features/playground/page/components/StructuredOutputSchemaSection.tsx
@@ -1,4 +1,4 @@
-import React, { useState, useCallback, useEffect } from "react";
+import React, { useCallback, useEffect } from "react";
import { usePlaygroundContext } from "@/src/features/playground/page/context";
import { Button } from "@/src/components/ui/button";
@@ -17,18 +17,144 @@ import {
CommandList,
CommandSeparator,
} from "@/src/components/ui/command";
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from "@/src/components/ui/popover";
import { type PlaygroundSchema } from "@/src/features/playground/page/types";
+// Popover content component for use in CollapsibleSection action buttons
+export const StructuredOutputSchemaPopover = () => {
+ const { structuredOutputSchema, setStructuredOutputSchema } =
+ usePlaygroundContext();
+ const projectId = useProjectIdFromURL();
+
+ const { data: savedSchemas = [] } = api.llmSchemas.getAll.useQuery(
+ {
+ projectId: projectId as string,
+ },
+ {
+ enabled: Boolean(projectId),
+ staleTime: 1000 * 60 * 5, // 5 minutes
+ },
+ );
+
+ const isSchemaSaved = useCallback(
+ (schema: PlaygroundSchema) => {
+ return savedSchemas.some(
+ (savedSchema) =>
+ savedSchema.id === schema.id &&
+ savedSchema.description === schema.description &&
+ JSON.stringify(savedSchema.schema) === JSON.stringify(schema.schema),
+ );
+ },
+ [savedSchemas],
+ );
+
+ const handleSelectSchema = (selectedLLMSchema: LlmSchema) => {
+ if (
+ structuredOutputSchema &&
+ structuredOutputSchema.id === selectedLLMSchema.id
+ ) {
+ // Schema already selected, just update it
+ setStructuredOutputSchema({
+ ...structuredOutputSchema,
+ name: selectedLLMSchema.name,
+ description: selectedLLMSchema.description,
+ schema: selectedLLMSchema.schema as Record<string, unknown>,
+ existingLlmSchema: selectedLLMSchema,
+ });
+ } else if (
+ structuredOutputSchema &&
+ structuredOutputSchema.name === selectedLLMSchema.name &&
+ !isSchemaSaved(structuredOutputSchema)
+ ) {
+ // Replace unsaved schema with same name
+ setStructuredOutputSchema({
+ id: selectedLLMSchema.id,
+ name: selectedLLMSchema.name,
+ description: selectedLLMSchema.description,
+ schema: selectedLLMSchema.schema as Record<string, unknown>,
+ existingLlmSchema: selectedLLMSchema,
+ });
+ } else {
+ // New schema
+ const newPlaygroundSchema: PlaygroundSchema = {
+ id: selectedLLMSchema.id,
+ name: selectedLLMSchema.name,
+ description: selectedLLMSchema.description,
+ schema: selectedLLMSchema.schema as Record<string, unknown>,
+ existingLlmSchema: selectedLLMSchema,
+ };
+ setStructuredOutputSchema(newPlaygroundSchema);
+ }
+ };
+
+ const handleRemoveSchema = () => {
+ setStructuredOutputSchema(null);
+ };
+
+ return (
+ <Command className="flex flex-col">
+ <CommandInput
+ placeholder="Search schemas..."
+ className="h-8 border-none p-1 focus:ring-0 focus:ring-offset-0"
+ />
+ <CommandList className="max-h-[300px] overflow-y-auto">
+ <CommandEmpty>No schemas found.</CommandEmpty>
+ <CommandGroup>
+ {savedSchemas.map((schema) => (
+ <CommandItem
+ key={schema.id}
+ value={schema.name}
+ onSelect={() => handleSelectSchema(schema)}
+ className="flex items-center justify-between px-1 py-2"
+ >
+ <div className="flex items-center gap-2">
+ <BoxIcon className="h-4 w-4 text-muted-foreground" />
+ <div className="flex-1 overflow-hidden">
+ <div className="truncate font-medium">{schema.name}</div>
+ <div className="line-clamp-1 text-xs text-muted-foreground">
+ {schema.description}
+ </div>
+ </div>
+ </div>
+ <CreateOrEditLLMSchemaDialog
+ projectId={projectId as string}
+ onSave={handleSelectSchema}
+ onDelete={() => handleRemoveSchema()}
+ existingLlmSchema={schema}
+ >
+ <Button
+ variant="ghost"
+ size="icon"
+ className="ml-2 h-7 w-7 shrink-0"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <PencilIcon className="h-3.5 w-3.5" />
+ </Button>
+ </CreateOrEditLLMSchemaDialog>
+ </CommandItem>
+ ))}
+ </CommandGroup>
+ <CommandSeparator />
+ </CommandList>
+ <div className="mt-auto p-1">
+ <CreateOrEditLLMSchemaDialog
+ projectId={projectId as string}
+ onSave={handleSelectSchema}
+ >
+ <Button variant="outline" size="default" className="w-full">
+ <PlusIcon className="mr-2 h-4 w-4" />
+ Create new schema
+ </Button>
+ </CreateOrEditLLMSchemaDialog>
+ </div>
+ </Command>
+ );
+};
+
+// Main component for embedding in CollapsibleSection content
export const StructuredOutputSchemaSection = () => {
const { structuredOutputSchema, setStructuredOutputSchema } =
usePlaygroundContext();
const projectId = useProjectIdFromURL();
- const [isSearchOpen, setIsSearchOpen] = useState(false);
const { data: savedSchemas = [] } = api.llmSchemas.getAll.useQuery(
{
@@ -105,7 +231,6 @@ export const StructuredOutputSchemaSection = () => {
};
setStructuredOutputSchema(newPlaygroundSchema);
}
- setIsSearchOpen(false);
};
const handleRemoveSchema = () => {
@@ -113,158 +238,72 @@ export const StructuredOutputSchemaSection = () => {
};
return (
- <div className="flex h-full flex-col pr-1">
- <div className="mb-2 flex items-center justify-between">
- <div className="flex items-center gap-2">
- <p className="font-semibold">Structured Output</p>
- <a
- href="https://github.com/orgs/langfuse/discussions/3166"
- target="_blank"
- rel="noopener noreferrer"
- className="inline-flex items-center"
- title="Structured output is currently in beta. Click here to learn more and provide feedback!"
- >
- <span className="rounded bg-muted px-1.5 py-0.5 text-xs font-medium text-muted-foreground">
- Beta
- </span>
- </a>
+ <ScrollArea className="h-full">
+ {!structuredOutputSchema ? (
+ <div className="flex h-16 flex-col items-center justify-center p-4 text-center">
+ <p className="text-xs text-muted-foreground">No schema provided.</p>
</div>
- <Popover open={isSearchOpen} onOpenChange={setIsSearchOpen}>
- <PopoverTrigger asChild>
- <Button className="h-7 w-7" variant="outline" size="icon">
- <PlusIcon size={14} />
- </Button>
- </PopoverTrigger>
- <PopoverContent align="end" className="p-1">
- <Command className="flex flex-col">
- <CommandInput
- placeholder="Search schemas..."
- className="h-8 border-none p-1 focus:ring-0 focus:ring-offset-0"
- />
- <CommandList className="max-h-[300px] overflow-y-auto">
- <CommandEmpty>No schemas found.</CommandEmpty>
- <CommandGroup>
- {savedSchemas.map((schema) => (
- <CommandItem
- key={schema.id}
- value={schema.name}
- onSelect={() => handleSelectSchema(schema)}
- className="flex items-center justify-between px-1 py-2"
- >
- <div className="flex items-center gap-2">
- <BoxIcon className="h-4 w-4 text-muted-foreground" />
- <div className="flex-1 overflow-hidden">
- <div className="truncate font-medium">
- {schema.name}
- </div>
- <div className="line-clamp-1 text-xs text-muted-foreground">
- {schema.description}
- </div>
- </div>
- </div>
- <CreateOrEditLLMSchemaDialog
- projectId={projectId as string}
- onSave={handleSelectSchema}
- onDelete={() => handleRemoveSchema()}
- existingLlmSchema={schema}
- >
- <Button
- variant="ghost"
- size="icon"
- className="ml-2 h-7 w-7 shrink-0"
- onClick={(e) => e.stopPropagation()}
- >
- <PencilIcon className="h-3.5 w-3.5" />
- </Button>
- </CreateOrEditLLMSchemaDialog>
- </CommandItem>
- ))}
- </CommandGroup>
- <CommandSeparator />
- </CommandList>
- <div className="mt-auto p-1">
- <CreateOrEditLLMSchemaDialog
- projectId={projectId as string}
- onSave={handleSelectSchema}
- >
- <Button variant="outline" size="default" className="w-full">
- <PlusIcon className="mr-2 h-4 w-4" />
- Create new schema
+ ) : (
+ <div className="space-y-1">
+ <CreateOrEditLLMSchemaDialog
+ projectId={projectId as string}
+ onSave={handleSelectSchema}
+ onDelete={() => handleRemoveSchema()}
+ existingLlmSchema={structuredOutputSchema.existingLlmSchema}
+ defaultValues={
+ !isSchemaSaved(structuredOutputSchema)
+ ? {
+ name: structuredOutputSchema.name,
+ description: structuredOutputSchema.description,
+ schema: JSON.stringify(
+ structuredOutputSchema.schema,
+ null,
+ 2,
+ ),
+ }
+ : undefined
+ }
+ >
+ <div className="cursor-pointer rounded-md border bg-background p-2 transition-colors duration-200 hover:bg-accent/50">
+ <div className="mb-1 flex items-center justify-between">
+ <div className="flex items-center gap-1">
+ <BoxIcon className="h-4 w-4 text-muted-foreground" />
+ <h3
+ className="max-w-[200px] truncate text-ellipsis text-sm font-medium"
+ title={structuredOutputSchema.name}
+ >
+ {structuredOutputSchema.name}
+ </h3>
+ {!isSchemaSaved(structuredOutputSchema) ? (
+ <span className="rounded bg-muted px-1 py-0.5 text-xs text-muted-foreground">
+ Unsaved
+ </span>
+ ) : null}
+ </div>
+ <div className="flex items-center gap-1">
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-6 w-6 p-0"
+ onClick={(e) => {
+ e.stopPropagation();
+ handleRemoveSchema();
+ }}
+ >
+ <MinusCircle className="h-4 w-4" />
</Button>
- </CreateOrEditLLMSchemaDialog>
- </div>
- </Command>
- </PopoverContent>
- </Popover>
- </div>
-
- <ScrollArea className="h-[calc(100%-2rem)]">
- {!structuredOutputSchema ? (
- <div className="flex h-16 flex-col items-center justify-center p-4 text-center">
- <p className="text-xs text-muted-foreground">No schema provided.</p>
- </div>
- ) : (
- <div className="space-y-1">
- <CreateOrEditLLMSchemaDialog
- projectId={projectId as string}
- onSave={handleSelectSchema}
- onDelete={() => handleRemoveSchema()}
- existingLlmSchema={structuredOutputSchema.existingLlmSchema}
- defaultValues={
- !isSchemaSaved(structuredOutputSchema)
- ? {
- name: structuredOutputSchema.name,
- description: structuredOutputSchema.description,
- schema: JSON.stringify(
- structuredOutputSchema.schema,
- null,
- 2,
- ),
- }
- : undefined
- }
- >
- <div className="cursor-pointer rounded-md border bg-background p-2 transition-colors duration-200 hover:bg-accent/50">
- <div className="mb-1 flex items-center justify-between">
- <div className="flex items-center gap-1">
- <BoxIcon className="h-4 w-4 text-muted-foreground" />
- <h3
- className="max-w-[200px] truncate text-ellipsis text-sm font-medium"
- title={structuredOutputSchema.name}
- >
- {structuredOutputSchema.name}
- </h3>
- {!isSchemaSaved(structuredOutputSchema) ? (
- <span className="rounded bg-muted px-1 py-0.5 text-xs text-muted-foreground">
- Unsaved
- </span>
- ) : null}
- </div>
- <div className="flex items-center gap-1">
- <Button
- variant="ghost"
- size="sm"
- className="h-6 w-6 p-0"
- onClick={(e) => {
- e.stopPropagation();
- handleRemoveSchema();
- }}
- >
- <MinusCircle className="h-4 w-4" />
- </Button>
- </div>
</div>
- <p
- className="line-clamp-2 break-all text-xs text-muted-foreground"
- title={structuredOutputSchema.description}
- >
- {structuredOutputSchema.description}
- </p>
</div>
- </CreateOrEditLLMSchemaDialog>
- </div>
- )}
- </ScrollArea>
- </div>
+ <p
+ className="line-clamp-2 break-all text-xs text-muted-foreground"
+ title={structuredOutputSchema.description}
+ >
+ {structuredOutputSchema.description}
+ </p>
+ </div>
+ </CreateOrEditLLMSchemaDialog>
+ </div>
+ )}
+ </ScrollArea>
);
};
diff --git a/web/src/features/playground/page/components/Variables.tsx b/web/src/features/playground/page/components/Variables.tsx
index 33628df528..3072cbdb57 100644
--- a/web/src/features/playground/page/components/Variables.tsx
+++ b/web/src/features/playground/page/components/Variables.tsx
@@ -5,8 +5,9 @@ import { PromptVariableComponent } from "./PromptVariableComponent";
export const Variables = () => {
const { promptVariables } = usePlaygroundContext();
+
const renderNoVariables = () => (
- <div className="mt-4 text-xs">
+ <div className="text-xs">
<p className="mb-2">No variables defined.</p>
<p>
Use handlebars in your prompts to add a variable:
@@ -14,6 +15,7 @@ export const Variables = () => {
</p>
</div>
);
+
const renderVariables = () => (
<div className="min-h-0 flex-1 overflow-y-auto overflow-x-hidden">
{promptVariables
@@ -36,7 +38,6 @@ export const Variables = () => {
return (
<div className="flex h-full flex-col">
- <p className="font-semibold">Variables</p>
{promptVariables.length === 0 ? renderNoVariables() : renderVariables()}
</div>
);
diff --git a/web/src/features/playground/page/context/index.tsx b/web/src/features/playground/page/context/index.tsx
index c0aa8ec27a..9f8da485a4 100644
--- a/web/src/features/playground/page/context/index.tsx
+++ b/web/src/features/playground/page/context/index.tsx
@@ -1,10 +1,10 @@
import React, {
createContext,
- type PropsWithChildren,
useCallback,
useContext,
useEffect,
useState,
+ useRef,
} from "react";
import { v4 as uuidv4 } from "uuid";
@@ -37,7 +37,15 @@ import {
type PlaygroundSchema,
type PlaygroundTool,
type PlaceholderMessageFillIn,
+ type PlaygroundProviderProps,
+ type PlaygroundHandle,
+ PLAYGROUND_EVENTS,
+ MULTI_WINDOW_CONFIG,
} from "@/src/features/playground/page/types";
+import {
+ getPlaygroundEventBus,
+ useWindowCoordination,
+} from "@/src/features/playground/page/hooks/useWindowCoordination";
import { getFinalModelParams } from "@/src/utils/getFinalModelParams";
type PlaygroundContextType = {
@@ -78,12 +86,13 @@ export const usePlaygroundContext = () => {
return context;
};
-export const PlaygroundProvider: React.FC<PropsWithChildren> = ({
+export const PlaygroundProvider: React.FC<PlaygroundProviderProps> = ({
children,
+ windowId,
}) => {
const capture = usePostHogClientCapture();
const projectId = useProjectIdFromURL();
- const { playgroundCache, setPlaygroundCache } = usePlaygroundCache();
+ const { playgroundCache, setPlaygroundCache } = usePlaygroundCache(windowId);
const [promptVariables, setPromptVariables] = useState<PromptVariable[]>([]);
const [messagePlaceholders, setMessagePlaceholders] = useState<
PlaceholderMessageFillIn[]
@@ -92,6 +101,7 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({
const [outputToolCalls, setOutputToolCalls] = useState<LLMToolCall[]>([]);
const [outputJson, setOutputJson] = useState("");
const [isStreaming, setIsStreaming] = useState(false);
+ const isStreamingRef = useRef(isStreaming);
const [tools, setTools] = useState<PlaygroundTool[]>([]);
const [structuredOutputSchema, setStructuredOutputSchema] =
useState<PlaygroundSchema | null>(null);
@@ -115,7 +125,8 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({
availableModels,
updateModelParamValue,
setModelParamEnabled,
- } = useModelParams();
+ } = useModelParams(windowId);
+ const { registerWindow, unregisterWindow } = useWindowCoordination();
const toolCallIds = messages.reduce((acc, m) => {
if (m.type === ChatMessageType.AssistantToolCall) {
@@ -125,14 +136,19 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({
}, [] as string[]);
// Load state from cache
+ const [cacheLoaded, setCacheLoaded] = useState(false);
useEffect(() => {
- if (!playgroundCache) return;
+ if (!playgroundCache) {
+ setCacheLoaded(true);
+ return;
+ }
const {
messages: cachedMessages,
modelParams: cachedModelParams,
output: cachedOutput,
promptVariables: cachedPromptVariables,
+ messagePlaceholders: cachedMessagePlaceholders,
tools: cachedTools,
structuredOutputSchema: cachedStructuredOutputSchema,
} = playgroundCache;
@@ -166,6 +182,10 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({
setPromptVariables(cachedPromptVariables);
}
+ if (cachedMessagePlaceholders) {
+ setMessagePlaceholders(cachedMessagePlaceholders);
+ }
+
if (cachedTools) {
setTools(cachedTools);
}
@@ -173,6 +193,8 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({
if (cachedStructuredOutputSchema) {
setStructuredOutputSchema(cachedStructuredOutputSchema);
}
+
+ setCacheLoaded(true);
}, [playgroundCache, setModelParams]);
const updatePromptVariables = useCallback(() => {
@@ -294,6 +316,11 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({
messages,
messagePlaceholders,
);
+
+ if (finalMessages.length === 0) {
+ throw new Error("Please add at least one message with content");
+ }
+
const leftOverVariables = extractVariables(
finalMessages
.map((m) => (typeof m.content === "string" ? m.content : ""))
@@ -381,6 +408,7 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({
modelParams,
output: response,
promptVariables,
+ messagePlaceholders,
tools,
structuredOutputSchema,
});
@@ -480,6 +508,106 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({
useEffect(updateMessagePlaceholders, [messages, updateMessagePlaceholders]);
+ // Save state to cache whenever it changes
+ // This ensures that user changes are persisted across refreshes and navigation
+ useEffect(() => {
+ // Only save after cache has been loaded to avoid overwriting with initial state
+ if (!cacheLoaded) return;
+
+ // Don't save empty initial state to avoid overwriting valid cache
+ if (messages.length > 0 && modelParams.provider.value) {
+ setPlaygroundCache({
+ messages,
+ modelParams,
+ output,
+ promptVariables,
+ messagePlaceholders,
+ tools,
+ structuredOutputSchema,
+ });
+ }
+ }, [
+ messages,
+ modelParams,
+ output,
+ promptVariables,
+ messagePlaceholders,
+ tools,
+ structuredOutputSchema,
+ setPlaygroundCache,
+ cacheLoaded,
+ ]);
+
+ // Window self-registration for global coordination
+ // This effect registers the window with the global coordination system
+ // and sets up event listeners for global actions like "Run All" and "Stop All"
+ useEffect(() => {
+ const effectiveWindowId = windowId || MULTI_WINDOW_CONFIG.DEFAULT_WINDOW_ID;
+ const playgroundEventBus = getPlaygroundEventBus();
+
+ const playgroundHandle: PlaygroundHandle = {
+ handleSubmit,
+ stopExecution: () => {
+ setIsStreaming(false);
+ isStreamingRef.current = false;
+ },
+ getIsStreaming: () => isStreamingRef.current,
+ };
+
+ registerWindow(effectiveWindowId, playgroundHandle);
+
+ const handleGlobalExecute = () => {
+ if (!isStreamingRef.current) {
+ handleSubmit(true);
+ }
+ };
+
+ const handleGlobalStop = () => {
+ if (isStreamingRef.current) {
+ setIsStreaming(false);
+ isStreamingRef.current = false;
+ }
+ };
+
+ playgroundEventBus.addEventListener(
+ PLAYGROUND_EVENTS.EXECUTE_ALL,
+ handleGlobalExecute,
+ );
+ playgroundEventBus.addEventListener(
+ PLAYGROUND_EVENTS.STOP_ALL,
+ handleGlobalStop,
+ );
+
+ return () => {
+ unregisterWindow(effectiveWindowId);
+
+ playgroundEventBus.removeEventListener(
+ PLAYGROUND_EVENTS.EXECUTE_ALL,
+ handleGlobalExecute,
+ );
+ playgroundEventBus.removeEventListener(
+ PLAYGROUND_EVENTS.STOP_ALL,
+ handleGlobalStop,
+ );
+ };
+ }, [windowId, handleSubmit, registerWindow, unregisterWindow]);
+
+ // Keep ref in sync with state for external consumers
+ useEffect(() => {
+ isStreamingRef.current = isStreaming;
+
+ // Dispatch execution state change event so global coordinator can update counts
+ const playgroundEventBus = getPlaygroundEventBus();
+ playgroundEventBus.dispatchEvent(
+ new CustomEvent(PLAYGROUND_EVENTS.WINDOW_EXECUTION_STATE_CHANGE, {
+ detail: {
+ windowId: windowId || MULTI_WINDOW_CONFIG.DEFAULT_WINDOW_ID,
+ isStreaming,
+ },
+ }),
+ );
+ }, [windowId, isStreaming]);
+
return (
<PlaygroundContext.Provider
value={{
diff --git a/web/src/features/playground/page/hooks/useModelParams.ts b/web/src/features/playground/page/hooks/useModelParams.ts
index f489ba4fd4..2f5daf4c62 100644
--- a/web/src/features/playground/page/hooks/useModelParams.ts
+++ b/web/src/features/playground/page/hooks/useModelParams.ts
@@ -9,8 +9,16 @@ import {
type UIModelParams,
} from "@langfuse/shared";
import { type ModelParamsContext } from "@/src/components/ModelParameters";
+import { getModelNameKey, getModelProviderKey } from "../storage/keys";
-export const useModelParams = () => {
+/**
+ * Hook for managing model parameters with window isolation support
+ * Supports both single-window and multi-window scenarios through window-specific localStorage keys
+ *
+ * @param windowId - Optional window identifier for state isolation. Defaults to "default" for backward compatibility
+ * @returns Object with model parameters state and management functions
+ */
+export const useModelParams = (windowId?: string) => {
const [modelParams, setModelParams] = useState<UIModelParams>({
...getDefaultAdapterParams(LLMAdapter.OpenAI),
provider: { value: "", enabled: true },
@@ -26,13 +34,17 @@ export const useModelParams = () => {
{ enabled: Boolean(projectId) },
);
+ // Generate window-specific localStorage keys
+ const modelNameKey = getModelNameKey(windowId ?? "");
+ const modelProviderKey = getModelProviderKey(windowId ?? "");
+
const [persistedModelName, setPersistedModelName] = useLocalStorage<
string | null
- >("llmModelName", null);
+ >(modelNameKey, null);
const [persistedModelProvider, setPersistedModelProvider] = useLocalStorage<
string | null
- >("llmModelProvider", null);
+ >(modelProviderKey, null);
const availableProviders = useMemo(() => {
const adapter = availableLLMApiKeys.data?.data ?? [];
diff --git a/web/src/features/playground/page/hooks/usePersistedWindowIds.ts b/web/src/features/playground/page/hooks/usePersistedWindowIds.ts
new file mode 100644
index 0000000000..a9f467f91e
--- /dev/null
+++ b/web/src/features/playground/page/hooks/usePersistedWindowIds.ts
@@ -0,0 +1,116 @@
+import { useCallback, useEffect, useState } from "react";
+import { v4 as uuidv4 } from "uuid";
+import { MULTI_WINDOW_CONFIG } from "../types";
+import {
+ getWindowIds,
+ saveWindowIds,
+ cloneWindowState,
+ removeWindowState,
+ clearAllPlaygroundData,
+} from "../storage/windowStorage";
+
+/**
+ * Hook to persist window IDs across page refreshes.
+ * Manages the list of active playground windows by orchestrating with storage utilities.
+ */
+export function usePersistedWindowIds() {
+ const [windowIds, setWindowIds] = useState<string[]>([]);
+ const [isLoaded, setIsLoaded] = useState(false);
+
+ // Load window IDs from storage on initial mount
+ useEffect(() => {
+ const savedWindowIds = getWindowIds();
+ setWindowIds(savedWindowIds ?? [uuidv4()]);
+ setIsLoaded(true);
+ }, []);
+
+ // Save window IDs to storage whenever they change
+ useEffect(() => {
+ if (isLoaded) {
+ saveWindowIds(windowIds);
+ }
+ }, [windowIds, isLoaded]);
+
+ /**
+ * Adds a window with a specific ID, if it doesn't already exist.
+ * @param windowId - The ID of the window to add.
+ * @returns The windowId if it was successfully added or already existed, otherwise null.
+ */
+ const addWindowWithId = useCallback(
+ (windowId: string) => {
+ if (windowIds.includes(windowId)) {
+ return windowId;
+ }
+ if (windowIds.length >= MULTI_WINDOW_CONFIG.MAX_WINDOWS) {
+ console.warn(
+ `Maximum window limit of ${MULTI_WINDOW_CONFIG.MAX_WINDOWS} reached`,
+ );
+ return null;
+ }
+ setWindowIds((prev) => [...prev, windowId]);
+ return windowId;
+ },
+ [windowIds],
+ );
+
+ /**
+ * Adds a new window, copying the state from a source window.
+ * @param sourceWindowId - Optional ID of the window to copy. Defaults to the most recent window.
+ * @returns The ID of the newly created window, or null if the window limit is reached.
+ */
+ const addWindowWithCopy = useCallback(
+ (sourceWindowId?: string) => {
+ if (windowIds.length >= MULTI_WINDOW_CONFIG.MAX_WINDOWS) {
+ console.warn(
+ `Maximum window limit of ${MULTI_WINDOW_CONFIG.MAX_WINDOWS} reached`,
+ );
+ return null;
+ }
+
+ const newWindowId = uuidv4();
+ const sourceId = sourceWindowId ?? windowIds[windowIds.length - 1];
+
+ if (sourceId) {
+ cloneWindowState(sourceId, newWindowId);
+ }
+
+ setWindowIds((prev) => [...prev, newWindowId]);
+ return newWindowId;
+ },
+ [windowIds],
+ );
+
+ /**
+ * Removes a window and its associated storage.
+ * @param windowId - The ID of the window to remove.
+ */
+ const removeWindowId = useCallback(
+ (windowId: string) => {
+ if (windowIds.length <= 1) {
+ console.warn("Cannot remove the last remaining window");
+ return;
+ }
+
+ removeWindowState(windowId);
+ setWindowIds((prev) => prev.filter((id) => id !== windowId));
+ },
+ [windowIds.length],
+ );
+
+ /**
+ * Clears all playground data from storage and resets to a single window.
+ */
+ const clearAllCache = useCallback((windowId?: string) => {
+ clearAllPlaygroundData();
+ setWindowIds([windowId ?? uuidv4()]);
+ }, []);
+
+ return {
+ windowIds,
+ isLoaded,
+ addWindowWithId,
+ addWindowWithCopy,
+ removeWindowId,
+ clearAllCache,
+ };
+}
diff --git a/web/src/features/playground/page/hooks/usePlaygroundCache.ts b/web/src/features/playground/page/hooks/usePlaygroundCache.ts
index d738369456..57dbbfe0cb 100644
--- a/web/src/features/playground/page/hooks/usePlaygroundCache.ts
+++ b/web/src/features/playground/page/hooks/usePlaygroundCache.ts
@@ -1,26 +1,55 @@
import { useEffect, useState } from "react";
-
import { type PlaygroundCache } from "../types";
+import { getCacheKey } from "../storage/keys";
-const playgroundCacheKey = "playgroundCache";
-
-export default function usePlaygroundCache() {
+/**
+ * Hook for managing playground cache with window isolation support.
+ * Relies on storage utilities for key generation and persistence.
+ *
+ * @param windowId - Optional window identifier for state isolation.
+ * @returns Object with playgroundCache state and setPlaygroundCache function.
+ */
+export default function usePlaygroundCache(windowId?: string) {
const [cache, setCache] = useState<PlaygroundCache>(null);
+ const playgroundCacheKey = getCacheKey(windowId ?? "");
+
+ /**
+ * Set playground cache for this specific window.
+ * Stores the cache in sessionStorage with a window-specific key.
+ *
+ * @param cache - PlaygroundCache object to store, or null to clear
+ */
const setPlaygroundCache = (cache: PlaygroundCache) => {
- sessionStorage.setItem(playgroundCacheKey, JSON.stringify(cache));
+ if (cache === null) {
+ sessionStorage.removeItem(playgroundCacheKey);
+ } else {
+ sessionStorage.setItem(playgroundCacheKey, JSON.stringify(cache));
+ }
};
+ /**
+ * Load cached state from sessionStorage on mount and when windowId changes
+ * Attempts to parse JSON and handles errors gracefully
+ */
useEffect(() => {
const savedCache = sessionStorage.getItem(playgroundCacheKey);
if (savedCache) {
try {
setCache(JSON.parse(savedCache));
} catch (e) {
- console.error("Failed to parse playground cache", e);
+ console.error(
+ `Failed to parse playground cache for window ${windowId}`,
+ e,
+ );
+ // Clear corrupted cache
+ sessionStorage.removeItem(playgroundCacheKey);
+ setCache(null);
}
+ } else {
+ setCache(null);
}
- }, []);
+ }, [playgroundCacheKey, windowId]);
return {
playgroundCache: cache,
diff --git a/web/src/features/playground/page/hooks/usePlaygroundWindowSize.ts b/web/src/features/playground/page/hooks/usePlaygroundWindowSize.ts
new file mode 100644
index 0000000000..b88bb200f0
--- /dev/null
+++ b/web/src/features/playground/page/hooks/usePlaygroundWindowSize.ts
@@ -0,0 +1,37 @@
+import { useState, useEffect, useRef } from "react";
+
+/**
+ * Custom hook to track playground window container size and provide responsive breakpoints
+ *
+ * Uses ResizeObserver to monitor the container width and provides boolean flags
+ * for different responsive states based on the playground window size rather than
+ * the browser window size.
+ */
+export const usePlaygroundWindowSize = () => {
+ const [width, setWidth] = useState(0);
+ const containerRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ const container = containerRef.current;
+ if (!container) return;
+
+ const resizeObserver = new ResizeObserver((entries) => {
+ for (const entry of entries) {
+ setWidth(entry.contentRect.width);
+ }
+ });
+
+ resizeObserver.observe(container);
+
+ return () => {
+ resizeObserver.disconnect();
+ };
+ }, []);
+
+ return {
+ containerRef,
+ width,
+ isVeryCompact: width < 423,
+ isCompact: width < 460,
+ };
+};
diff --git a/web/src/features/playground/page/hooks/useWindowCoordination.ts b/web/src/features/playground/page/hooks/useWindowCoordination.ts
new file mode 100644
index 0000000000..b495cde3a5
--- /dev/null
+++ b/web/src/features/playground/page/hooks/useWindowCoordination.ts
@@ -0,0 +1,256 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+import {
+ type PlaygroundHandle,
+ type WindowCoordinationReturn,
+ PLAYGROUND_EVENTS,
+} from "../types";
+
+/**
+ * Playground window registry for coordinating actions across multiple playground windows
+ * This Map stores references to all active playground windows and their handles
+ * Key: windowId, Value: PlaygroundHandle interface
+ */
+const playgroundWindowRegistry = new Map<string, PlaygroundHandle>();
+
+/**
+ * Playground event bus for coordinating actions across playground windows
+ * Uses the native EventTarget API for performance and simplicity
+ */
+const playgroundEventBus = new EventTarget();
+
+/**
+ * Hook for managing global coordination between multiple playground windows
+ * Provides functions to register/unregister windows and execute global actions
+ *
+ * Key features:
+ * - Window registration/unregistration
+ * - Parallel execution of all windows
+ * - Global stop functionality
+ * - Execution status tracking
+ * - Event-based coordination (no React re-renders)
+ *
+ * @returns WindowCoordinationReturn interface with coordination functions
+ */
+export const useWindowCoordination = (): WindowCoordinationReturn => {
+ const [isExecutingAll, setIsExecutingAll] = useState(false);
+ const [executionVersion, setExecutionVersion] = useState(0);
+ const executionTimeoutRef = useRef<NodeJS.Timeout | null>(null);
+
+ /**
+ * Register a playground window with the global coordination system
+ * Adds the window to the registry and dispatches a registration event
+ *
+ * @param windowId - Unique identifier for the window
+ * @param handle - PlaygroundHandle interface for the window
+ */
+ const registerWindow = useCallback(
+ (windowId: string, handle: PlaygroundHandle) => {
+ playgroundWindowRegistry.set(windowId, handle);
+
+ // Dispatch registration event for potential listeners
+ playgroundEventBus.dispatchEvent(
+ new CustomEvent(PLAYGROUND_EVENTS.WINDOW_REGISTERED, {
+ detail: { windowId },
+ }),
+ );
+ },
+ [],
+ );
+
+ /**
+ * Unregister a playground window from the global coordination system
+ * Removes the window from the registry and dispatches an unregistration event
+ *
+ * @param windowId - Unique identifier for the window to remove
+ */
+ const unregisterWindow = useCallback((windowId: string) => {
+ const wasRegistered = playgroundWindowRegistry.has(windowId);
+ playgroundWindowRegistry.delete(windowId);
+
+ if (wasRegistered) {
+ // Dispatch unregistration event for potential listeners
+ playgroundEventBus.dispatchEvent(
+ new CustomEvent(PLAYGROUND_EVENTS.WINDOW_UNREGISTERED, {
+ detail: { windowId },
+ }),
+ );
+ }
+ }, []);
+
+ /**
+ * Execute all registered playground windows in parallel
+ * Dispatches execute-all event to all windows and manages global execution state
+ */
+ const executeAllWindows = useCallback(() => {
+ const registeredWindows = Array.from(playgroundWindowRegistry.values());
+
+ if (registeredWindows.length === 0) {
+ return;
+ }
+
+ // Check if any windows are already executing
+ const alreadyExecuting = registeredWindows.some((handle) =>
+ handle.getIsStreaming(),
+ );
+ if (alreadyExecuting) {
+ return;
+ }
+
+ setIsExecutingAll(true);
+
+ // Clear any existing timeout
+ if (executionTimeoutRef.current) {
+ clearTimeout(executionTimeoutRef.current);
+ }
+
+ // Dispatch execute-all event
+ playgroundEventBus.dispatchEvent(
+ new CustomEvent(PLAYGROUND_EVENTS.EXECUTE_ALL),
+ );
+
+ // Set a timeout to reset the execution state
+ // This provides a fallback in case some windows don't respond
+ executionTimeoutRef.current = setTimeout(() => {
+ setIsExecutingAll(false);
+ }, 30000); // 30 second timeout
+
+ // Monitor execution completion
+ const checkExecutionCompletion = () => {
+ const stillExecuting = Array.from(playgroundWindowRegistry.values()).some(
+ (handle) => handle.getIsStreaming(),
+ );
+
+ if (!stillExecuting) {
+ setIsExecutingAll(false);
+ if (executionTimeoutRef.current) {
+ clearTimeout(executionTimeoutRef.current);
+ executionTimeoutRef.current = null;
+ }
+ } else {
+ // Check again in a short interval
+ setTimeout(checkExecutionCompletion, 500);
+ }
+ };
+
+ // Start monitoring after a short delay to allow windows to start
+ setTimeout(checkExecutionCompletion, 1000);
+ }, []);
+
+ /**
+ * Stop all currently executing playground windows
+ * Dispatches stop-all event to all windows and resets global execution state
+ */
+ const stopAllWindows = useCallback(() => {
+ setIsExecutingAll(false);
+
+ // Clear any existing timeout
+ if (executionTimeoutRef.current) {
+ clearTimeout(executionTimeoutRef.current);
+ executionTimeoutRef.current = null;
+ }
+
+ // Dispatch stop-all event
+ playgroundEventBus.dispatchEvent(
+ new CustomEvent(PLAYGROUND_EVENTS.STOP_ALL),
+ );
+ }, []);
+
+ /**
+ * Get current execution status across all registered windows
+ * Provides a summary of the execution state for display purposes
+ *
+ * @returns String describing current execution status or null if no windows
+ */
+ const getExecutionStatus = useCallback((): string | null => {
+ const registeredWindows = Array.from(playgroundWindowRegistry.values());
+
+ if (registeredWindows.length === 0) {
+ return null;
+ }
+
+ const executingCount = registeredWindows.filter((handle) =>
+ handle.getIsStreaming(),
+ ).length;
+ const totalCount = registeredWindows.length;
+
+ if (executingCount === 0) {
+ return null;
+ }
+
+ if (executingCount === totalCount) {
+ return `Executing all ${totalCount} windows`;
+ }
+
+ return `Executing ${executingCount} of ${totalCount} windows`;
+ }, []);
+
+ /**
+ * Cleanup function to clear timeouts when component unmounts
+ * Prevents memory leaks from lingering timeouts
+ */
+ useEffect(() => {
+ const handleExecutionChange = () => {
+ setExecutionVersion((v) => v + 1);
+ };
+
+ playgroundEventBus.addEventListener(
+ PLAYGROUND_EVENTS.WINDOW_EXECUTION_STATE_CHANGE,
+ handleExecutionChange,
+ );
+
+ return () => {
+ playgroundEventBus.removeEventListener(
+ PLAYGROUND_EVENTS.WINDOW_EXECUTION_STATE_CHANGE,
+ handleExecutionChange,
+ );
+
+ if (executionTimeoutRef.current) {
+ clearTimeout(executionTimeoutRef.current);
+ }
+ };
+ }, []);
+
+ executionVersion;
+
+ return {
+ registerWindow,
+ unregisterWindow,
+ executeAllWindows,
+ stopAllWindows,
+ getExecutionStatus,
+ isExecutingAll,
+ };
+};
+
+/**
+ * Utility function to get the current playground window registry
+ * Useful for debugging and testing purposes
+ *
+ * @returns Map of windowId to PlaygroundHandle
+ */
+export const getPlaygroundWindowRegistry = (): Map<
+ string,
+ PlaygroundHandle
+> => {
+ return playgroundWindowRegistry;
+};
+
+/**
+ * Utility function to get the playground event bus
+ * Useful for advanced coordination scenarios and testing
+ *
+ * @returns EventTarget instance
+ */
+export const getPlaygroundEventBus = (): EventTarget => {
+ return playgroundEventBus;
+};
+
+/**
+ * Utility function to get the current window count
+ * Useful for UI components that need to display window statistics
+ *
+ * @returns Number of currently registered windows
+ */
+export const getWindowCount = (): number => {
+ return playgroundWindowRegistry.size;
+};
diff --git a/web/src/features/playground/page/index.tsx b/web/src/features/playground/page/index.tsx
index 9734044918..f63e186fbd 100644
--- a/web/src/features/playground/page/index.tsx
+++ b/web/src/features/playground/page/index.tsx
@@ -1,32 +1,193 @@
+import React, { useCallback } from "react";
+import { Button } from "@/src/components/ui/button";
+import { Plus, Play, Loader2 } from "lucide-react";
import { ResetPlaygroundButton } from "@/src/features/playground/page/components/ResetPlaygroundButton";
-import { SaveToPromptButton } from "@/src/features/playground/page/components/SaveToPromptButton";
+import { useWindowCoordination } from "@/src/features/playground/page/hooks/useWindowCoordination";
+import { usePersistedWindowIds } from "@/src/features/playground/page/hooks/usePersistedWindowIds";
+import useCommandEnter from "@/src/features/playground/page/hooks/useCommandEnter";
+import {
+ MULTI_WINDOW_CONFIG,
+ type MultiWindowState,
+} from "@/src/features/playground/page/types";
import Page from "@/src/components/layouts/page";
-import { PlaygroundProvider } from "@/src/features/playground/page/context";
-import Playground from "@/src/features/playground/page/playground";
+import MultiWindowPlayground from "@/src/features/playground/page/components/MultiWindowPlayground";
+/**
+ * PlaygroundPage Component
+ *
+ * Main playground page that provides the multi-window playground experience
+ * for prompt testing and comparison. Manages window state at the page level
+ * to enable header controls integration.
+ *
+ * Key Features:
+ * - Multi-window playground for side-by-side comparison
+ * - Integrated header controls for window management
+ * - Global execution controls (Run All, Stop All)
+ * - Window count display and management
+ * - Reset playground functionality for starting fresh
+ * - Persistent window IDs across page refreshes
+ *
+ * Architecture:
+ * - Page-level window state management
+ * - Header integration with multi-window controls
+ * - Global coordination through useWindowCoordination hook
+ * - Clean single-header design
+ */
export default function PlaygroundPage() {
- return (
- <PlaygroundProvider>
+ const { windowIds, isLoaded, addWindowWithCopy, removeWindowId } =
+ usePersistedWindowIds();
+
+ // Global coordination hook for managing window actions
+ const {
+ executeAllWindows,
+ getExecutionStatus,
+ isExecutingAll: globalIsExecutingAll,
+ } = useWindowCoordination();
+
+ /**
+ * Add a new window to the playground
+ * @param sourceWindowId - Optional source window ID to copy state from. If not provided, copies from the most recent window.
+ */
+ const addWindow = useCallback(
+ (sourceWindowId?: string) => {
+ const newWindowId = addWindowWithCopy(sourceWindowId);
+ if (newWindowId) {
+ console.log(`Added new window: ${newWindowId}`);
+ } else {
+ console.warn("Failed to add new window");
+ }
+ },
+ [addWindowWithCopy],
+ );
+
+ /**
+ * Remove a window from the playground
+ */
+ const removeWindow = useCallback(
+ (windowId: string) => {
+ removeWindowId(windowId);
+ },
+ [removeWindowId],
+ );
+
+ /**
+ * Handle global execution of all windows
+ */
+ const handleExecuteAll = useCallback(() => {
+ executeAllWindows();
+ }, [executeAllWindows]);
+
+ // Handle command+enter for "Run All" button
+ useCommandEnter(!globalIsExecutingAll, async () => {
+ executeAllWindows();
+ });
+
+ // Don't render until window IDs are loaded
+ if (!isLoaded) {
+ return (
<Page
- withPadding
+ withPadding={false}
headerProps={{
title: "Playground",
help: {
- description: "A sandbox to test and iterate your prompts",
+ description:
+ "A sandbox to test and iterate your prompts across multiple windows",
href: "https://langfuse.com/docs/playground",
},
- actionButtonsRight: (
- <>
- <SaveToPromptButton />
- <ResetPlaygroundButton />
- </>
- ),
}}
>
- <div className="flex-1 overflow-auto">
- <Playground />
+ <div className="flex h-full items-center justify-center">
+ <Loader2 className="h-8 w-8 animate-spin" />
</div>
</Page>
- </PlaygroundProvider>
+ );
+ }
+
+ // Execution status and control states
+ const executionStatus = globalIsExecutingAll
+ ? getExecutionStatus() ||
+ `Executing ${windowIds.length} window${windowIds.length === 1 ? "" : "s"}`
+ : getExecutionStatus();
+ const isAddWindowDisabled =
+ windowIds.length >= MULTI_WINDOW_CONFIG.MAX_WINDOWS;
+ const isRunAllDisabled = globalIsExecutingAll;
+
+ const windowState: MultiWindowState = {
+ windowIds,
+ isExecutingAll: globalIsExecutingAll,
+ };
+
+ return (
+ <Page
+ scrollable={false}
+ withPadding={false}
+ headerProps={{
+ title: "Playground",
+ help: {
+ description:
+ "A sandbox to test and iterate your prompts across multiple windows",
+ href: "https://langfuse.com/docs/playground",
+ },
+ actionButtonsRight: (
+ <div className="flex flex-nowrap items-center gap-2">
+ {/* Window Count Display - Hidden on mobile */}
+ <div className="hidden items-center gap-2 text-sm text-muted-foreground md:flex">
+ <span className="whitespace-nowrap">
+ {windowIds.length} window
+ {windowIds.length === 1 ? "" : "s"}
+ </span>
+ {executionStatus && (
+ <>
+ <span className="hidden sm:inline">•</span>
+ <div className="flex items-center gap-1">
+ <Loader2 className="h-3 w-3 animate-spin" />
+ <span className="hidden whitespace-nowrap sm:inline">
+ {executionStatus}
+ </span>
+ </div>
+ </>
+ )}
+ </div>
+
+ {/* Add Window Button - Hidden on mobile */}
+ <Button
+ variant="outline"
+ onClick={() => addWindow()}
+ disabled={isAddWindowDisabled}
+ className="hidden flex-shrink-0 gap-1 md:flex"
+ title="Add a new playground window"
+ >
+ <Plus className="h-3 w-3" />
+ <span className="hidden lg:inline">Add Window</span>
+ </Button>
+
+ {/* Multi-Window Controls - Hidden on mobile */}
+ <Button
+ variant="outline"
+ onClick={handleExecuteAll}
+ disabled={isRunAllDisabled}
+ className="hidden flex-shrink-0 gap-1 md:flex"
+ title="Execute all playground windows simultaneously"
+ >
+ {isRunAllDisabled ? (
+ <Loader2 className="h-3 w-3 animate-spin" />
+ ) : (
+ <Play className="h-3 w-3" />
+ )}
+ <span className="hidden lg:inline">Run All (Ctrl + Enter)</span>
+ </Button>
+
+ {/* Reset Playground Button */}
+ <ResetPlaygroundButton />
+ </div>
+ ),
+ }}
+ >
+ <MultiWindowPlayground
+ windowState={windowState}
+ onRemoveWindow={removeWindow}
+ onAddWindow={addWindow}
+ />
+ </Page>
);
}
diff --git a/web/src/features/playground/page/playground.tsx b/web/src/features/playground/page/playground.tsx
deleted file mode 100644
index c376265a09..0000000000
--- a/web/src/features/playground/page/playground.tsx
+++ /dev/null
@@ -1,40 +0,0 @@
-import { ModelParameters } from "@/src/components/ModelParameters";
-import { usePlaygroundContext } from "./context";
-import { Variables } from "./components/Variables";
-import { MessagePlaceholders } from "./components/MessagePlaceholders";
-import { Messages } from "./components/Messages";
-import { PlaygroundTools } from "./components/PlaygroundTools";
-import { StructuredOutputSchemaSection } from "./components/StructuredOutputSchemaSection";
-
-export default function Playground() {
- const playgroundContext = usePlaygroundContext();
-
- return (
- <div className="flex h-full flex-row space-x-8">
- <div className="h-full basis-3/4 overflow-auto">
- <Messages {...playgroundContext} />
- </div>
- <div className="max-h-full min-h-0 basis-1/4 pr-2">
- <div className="flex h-full flex-col gap-4">
- <div className="mb-4 flex-shrink-0 overflow-y-auto">
- <ModelParameters {...playgroundContext} />
- </div>
- <div className="mb-4 max-h-[25vh] flex-shrink-0 overflow-y-auto">
- <PlaygroundTools />
- </div>
- <div className="mb-4 flex-shrink-0">
- <StructuredOutputSchemaSection />
- </div>
- <div className="flex min-h-0 flex-1 flex-col gap-6">
- <div className="min-h-0 flex-1">
- <Variables />
- </div>
- <div className="min-h-0 flex-1">
- <MessagePlaceholders />
- </div>
- </div>
- </div>
- </div>
- </div>
- );
-}
diff --git a/web/src/features/playground/page/storage/keys.ts b/web/src/features/playground/page/storage/keys.ts
new file mode 100644
index 0000000000..dc7bcb0f5f
--- /dev/null
+++ b/web/src/features/playground/page/storage/keys.ts
@@ -0,0 +1,20 @@
+import { MULTI_WINDOW_CONFIG } from "../types";
+
+export const WINDOW_IDS_KEY = "playgroundWindowIds";
+
+const getPrefixedKey = (prefix: string, windowId: string) => {
+ const effectiveWindowId = windowId || MULTI_WINDOW_CONFIG.DEFAULT_WINDOW_ID;
+ if (effectiveWindowId === MULTI_WINDOW_CONFIG.DEFAULT_WINDOW_ID) {
+ return prefix.endsWith("_") ? prefix.slice(0, -1) : prefix;
+ }
+ return `${prefix}${effectiveWindowId}`;
+};
+
+export const getCacheKey = (windowId: string) =>
+ getPrefixedKey("langfuse-playgroundCache_", windowId);
+
+export const getModelNameKey = (windowId: string) =>
+ getPrefixedKey("langfuse-llmModelName_", windowId);
+
+export const getModelProviderKey = (windowId: string) =>
+ getPrefixedKey("langfuse-llmModelProvider_", windowId);
diff --git a/web/src/features/playground/page/storage/windowStorage.ts b/web/src/features/playground/page/storage/windowStorage.ts
new file mode 100644
index 0000000000..661607fe32
--- /dev/null
+++ b/web/src/features/playground/page/storage/windowStorage.ts
@@ -0,0 +1,129 @@
+import { type PlaygroundCache } from "../types";
+import {
+ getCacheKey,
+ getModelNameKey,
+ getModelProviderKey,
+ WINDOW_IDS_KEY,
+} from "./keys";
+
+/**
+ * Retrieves the list of window IDs from sessionStorage.
+ * @returns An array of window IDs.
+ */
+export const getWindowIds = (): string[] | null => {
+ const saved = sessionStorage.getItem(WINDOW_IDS_KEY);
+ if (saved) {
+ try {
+ const parsed = JSON.parse(saved);
+ if (Array.isArray(parsed) && parsed.length > 0) {
+ return parsed;
+ }
+ } catch (e) {
+ console.error("Failed to parse saved window IDs, clearing.", e);
+ sessionStorage.removeItem(WINDOW_IDS_KEY);
+ }
+ }
+ return null;
+};
+
+/**
+ * Saves the list of window IDs to sessionStorage.
+ * @param ids - The array of window IDs to save.
+ */
+export const saveWindowIds = (ids: string[]): void => {
+ sessionStorage.setItem(WINDOW_IDS_KEY, JSON.stringify(ids));
+};
+
+/**
+ * Retrieves the cached state for a specific window.
+ * @param windowId - The ID of the window.
+ * @returns The cached state or null if not found.
+ */
+export const getWindowState = (windowId: string): PlaygroundCache | null => {
+ const key = getCacheKey(windowId);
+ const cachedState = sessionStorage.getItem(key);
+ if (!cachedState) return null;
+ try {
+ return JSON.parse(cachedState) as PlaygroundCache;
+ } catch (error) {
+ console.error(`Failed to parse cache for window ${windowId}:`, error);
+ sessionStorage.removeItem(key);
+ return null;
+ }
+};
+
+/**
+ * Clones the entire state (cache and model params) from a source window to a target window.
+ * @param sourceWindowId - The ID of the window to copy from.
+ * @param targetWindowId - The ID of the window to copy to.
+ */
+export const cloneWindowState = (
+ sourceWindowId: string,
+ targetWindowId: string,
+): void => {
+ try {
+ // 1. Clone sessionStorage (cache)
+ const sourceState = getWindowState(sourceWindowId);
+ if (sourceState) {
+ const clonedState = JSON.parse(JSON.stringify(sourceState));
+ sessionStorage.setItem(
+ getCacheKey(targetWindowId),
+ JSON.stringify(clonedState),
+ );
+ }
+
+ const sourceModelName = sessionStorage.getItem(
+ getModelNameKey(sourceWindowId),
+ );
+ if (sourceModelName) {
+ sessionStorage.setItem(getModelNameKey(targetWindowId), sourceModelName);
+ }
+ const sourceModelProvider = sessionStorage.getItem(
+ getModelProviderKey(sourceWindowId),
+ );
+ if (sourceModelProvider) {
+ sessionStorage.setItem(
+ getModelProviderKey(targetWindowId),
+ sourceModelProvider,
+ );
+ }
+ } catch (error) {
+ console.error(
+ `Failed to clone window state from ${sourceWindowId} to ${targetWindowId}`,
+ error,
+ );
+ }
+};
+
+/**
+ * Removes all storage associated with a single window.
+ * @param windowId - The ID of the window to remove.
+ */
+export const removeWindowState = (windowId: string): void => {
+ sessionStorage.removeItem(getCacheKey(windowId));
+ sessionStorage.removeItem(getModelNameKey(windowId));
+ sessionStorage.removeItem(getModelProviderKey(windowId));
+};
+
+/**
+ * Clears all playground-related data from storage.
+ */
+export const clearAllPlaygroundData = (): void => {
+ const sessionKeysToRemove: string[] = [];
+ for (let i = 0; i < sessionStorage.length; i++) {
+ const key = sessionStorage.key(i);
+ if (key?.startsWith("playground")) {
+ sessionKeysToRemove.push(key);
+ }
+ }
+ sessionKeysToRemove.forEach((key) => sessionStorage.removeItem(key));
+
+ const localKeysToRemove: string[] = [];
+ for (let i = 0; i < sessionStorage.length; i++) {
+ const key = sessionStorage.key(i);
+ if (key?.startsWith("llmModel")) {
+ localKeysToRemove.push(key);
+ }
+ }
+ localKeysToRemove.forEach((key) => sessionStorage.removeItem(key));
+};
diff --git a/web/src/features/playground/page/types.ts b/web/src/features/playground/page/types.ts
index e984e998e0..15ff0597f5 100644
--- a/web/src/features/playground/page/types.ts
+++ b/web/src/features/playground/page/types.ts
@@ -34,7 +34,91 @@ export type PlaygroundCache = {
Pick<UIModelParams, "provider" | "model">;
output?: string | null;
promptVariables?: PromptVariable[];
- // TODO: also cache placeholders?
+ messagePlaceholders?: PlaceholderMessageFillIn[];
tools?: PlaygroundTool[];
structuredOutputSchema?: PlaygroundSchema | null;
} | null;
+
+// Multi-window types and interfaces
+
+/**
+ * Handle interface for coordinating actions with individual playground windows
+ * Used by the global coordination system to execute actions on specific windows
+ */
+export interface PlaygroundHandle {
+ /** Execute the playground with optional streaming */
+ handleSubmit: (streaming?: boolean) => Promise<void>;
+ /** Stop the current execution */
+ stopExecution: () => void;
+ /** Getter for current streaming state */
+ getIsStreaming: () => boolean;
+}
+
+/**
+ * Return type for the useWindowCoordination hook
+ * Provides functions for managing the global window coordination system
+ */
+export interface WindowCoordinationReturn {
+ /** Register a window with the global coordination system */
+ registerWindow: (windowId: string, handle: PlaygroundHandle) => void;
+ /** Unregister a window from the global coordination system */
+ unregisterWindow: (windowId: string) => void;
+ /** Execute all registered windows in parallel */
+ executeAllWindows: () => void;
+ /** Stop all currently executing windows */
+ stopAllWindows: () => void;
+ /** Get current execution status across all windows */
+ getExecutionStatus: () => string | null;
+ /** Whether any windows are currently executing */
+ isExecutingAll: boolean;
+}
+
+/**
+ * Props for PlaygroundProvider with multi-window support
+ * Extends the existing provider to support window-specific state isolation
+ */
+export interface PlaygroundProviderProps {
+ children: React.ReactNode;
+ /** Optional window ID for state isolation. Defaults to "default" for single-window mode */
+ windowId?: string;
+}
+
+/**
+ * State management for the multi-window playground container
+ * Tracks all active windows and global execution state
+ */
+export interface MultiWindowState {
+ /** Array of window IDs currently active */
+ windowIds: string[];
+ /** Whether a global "execute all" operation is in progress */
+ isExecutingAll: boolean;
+}
+
+/**
+ * Event types for the global coordination system
+ * Custom events dispatched through the EventTarget-based event bus
+ */
+export const PLAYGROUND_EVENTS = {
+ EXECUTE_ALL: "playground:execute-all",
+ STOP_ALL: "playground:stop-all",
+ WINDOW_REGISTERED: "playground:window-registered",
+ WINDOW_UNREGISTERED: "playground:window-unregistered",
+ WINDOW_EXECUTION_STATE_CHANGE: "playground:window-execution-state-change",
+} as const;
+
+/**
+ * Configuration for window limits and validation
+ * Defines constraints for multi-window functionality
+ */
+export const MULTI_WINDOW_CONFIG = {
+ /** Maximum number of windows allowed */
+ MAX_WINDOWS: 10,
+ /** Maximum number of windows allowed on mobile/small screens */
+ MAX_WINDOWS_MOBILE: 1,
+ /** Minimum window width in pixels */
+ MIN_WINDOW_WIDTH: 400,
+ /** Mobile breakpoint in pixels (below this, mobile behavior applies) */
+ MOBILE_BREAKPOINT: 768,
+ /** Default window ID for single-window mode */
+ DEFAULT_WINDOW_ID: "default",
+} as const;