The platform for continuously improving AI agents.
import {
type CSSProperties,
type ReactNode,
type RefObject,
useEffect,
useRef,
useState,
} from "react";
import { Button } from "@/components/ui/button";
import { Icon } from "@/components/ui/icons";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { WorkspaceChatPanelContext } from "@/components/workspace/workspace-chat-panel";
import { usePersistedState } from "@/hooks/use-persisted-state";
export const CHAT_WIDTH = { default: 384, min: 320 };
const MAX_WIDTH = 720;
// The canvas keeps at least this much beside the panel.
const CANVAS_MIN = 376;
const KEY_STEP = 16;
/** The chat sidebar's state for the current page: open unless closed on this page, and a
* kept width that the shell's own width bounds. */
export function useChatSidebar(pathname: string, shell: RefObject<HTMLElement | null>) {
const available = /^\/(experiments|datasets)\/[^/]+\/?$/.test(pathname);
// An experiment's panel holds its chat and its agents' activity.
const name = pathname.startsWith("/experiments/") ? "Monitoring" : "Chat";
const [closedOn, setClosedOn] = useState<string | null>(null);
const [kept, keep] = usePersistedState("chat:panelWidth", CHAT_WIDTH.default);
const [dragged, setDragged] = useState<number | null>(null);
const [max, setMax] = useState(MAX_WIDTH);
const [host, setHost] = useState<HTMLDivElement | null>(null);
useEffect(() => {
const node = shell.current;
if (!node) return;
const measure = () => {
const width = node.getBoundingClientRect().width;
if (width > 0) setMax(Math.max(CHAT_WIDTH.min, Math.min(MAX_WIDTH, width - CANVAS_MIN)));
};
measure();
const observer = new ResizeObserver(measure);
observer.observe(node);
return () => observer.disconnect();
}, [shell]);
const open = available && closedOn !== pathname;
return {
available,
dragged,
host,
keep,
max,
name,
open,
setDragged,
setHost,
toggle: () => setClosedOn(open ? pathname : null),
width: Math.max(CHAT_WIDTH.min, Math.min(max, dragged ?? kept)),
};
}
type Sidebar = ReturnType<typeof useChatSidebar>;
export function ChatSidebarProvider({
sidebar,
children,
}: {
sidebar: Sidebar;
children: ReactNode;
}) {
return (
<WorkspaceChatPanelContext.Provider value={sidebar.host}>
{children}
</WorkspaceChatPanelContext.Provider>
);
}
/** The canvas's top-right button that opens and closes the chat sidebar. */
export function ChatToggle({
sidebar,
ref,
}: {
sidebar: Sidebar;
ref?: RefObject<HTMLButtonElement | null>;
}) {
if (!sidebar.available) return null;
const label = `${sidebar.open ? "Close" : "Open"} ${sidebar.name.toLowerCase()} panel`;
return (
<div className="chat-toggle absolute top-3.5 right-3 z-30">
<Tooltip>
<TooltipTrigger asChild>
<Button
aria-controls="workspace-chat-panel"
aria-expanded={sidebar.open}
aria-label={label}
onClick={sidebar.toggle}
ref={ref}
size="icon-sm"
variant="send"
>
<Icon.sidebar className="rotate-180" />
</Button>
</TooltipTrigger>
<TooltipContent>{label}</TooltipContent>
</Tooltip>
</div>
);
}
/** The divider that sets the sidebar's width, and the sidebar the page's chat renders into.
* Dragging left widens the panel; arrow keys, Home and End resize it; a double click resets. */
export function ChatSidebar({
sidebar,
toggle,
}: {
sidebar: Sidebar;
toggle: RefObject<HTMLButtonElement | null>;
}) {
const { open, width, max } = sidebar;
const origin = useRef<{ x: number; width: number } | null>(null);
const resizing = open && sidebar.dragged !== null;
const clamp = (value: number) => Math.round(Math.min(max, Math.max(CHAT_WIDTH.min, value)));
const end = () => {
if (!origin.current) return;
origin.current = null;
sidebar.keep(width);
sidebar.setDragged(null);
};
return (
<>
<div
aria-hidden={!open}
className="workspace-chat-divider col-start-2 row-start-2 hidden sm:flex"
data-open={open}
data-resizing={resizing}
inert={!open}
>
<div
aria-controls="workspace-chat-panel"
aria-label={`${sidebar.name} panel width`}
aria-orientation="vertical"
aria-valuemax={max}
aria-valuemin={CHAT_WIDTH.min}
aria-valuenow={width}
className="chat-resize-handle"
onDoubleClick={() => sidebar.keep(CHAT_WIDTH.default)}
onKeyDown={(event) => {
const next = {
ArrowLeft: width + KEY_STEP,
ArrowRight: width - KEY_STEP,
End: max,
Home: CHAT_WIDTH.min,
}[event.key];
if (next === undefined) return;
event.preventDefault();
sidebar.keep(clamp(next));
}}
onLostPointerCapture={end}
onPointerCancel={end}
onPointerDown={(event) => {
if (event.button !== 0) return;
event.currentTarget.setPointerCapture(event.pointerId);
origin.current = { width, x: event.clientX };
sidebar.setDragged(width);
}}
onPointerMove={(event) => {
if (!origin.current) return;
sidebar.setDragged(clamp(origin.current.width - (event.clientX - origin.current.x)));
}}
onPointerUp={end}
role="separator"
tabIndex={0}
>
<span className="chat-resize-grip" />
</div>
</div>
<aside
aria-hidden={!open}
aria-label={`${sidebar.name} panel`}
className="workspace-chat-panel col-start-3 row-start-2 flex min-h-0 min-w-0 shrink-0 flex-col overflow-hidden bg-sidebar text-sidebar-foreground"
data-open={open}
data-resizing={resizing}
id="workspace-chat-panel"
inert={!open}
style={{ "--chat-panel-width": `${width}px` } as CSSProperties}
>
<Button
aria-label={`Close ${sidebar.name.toLowerCase()} panel`}
className="m-2 self-end sm:hidden"
onClick={() => {
sidebar.toggle();
requestAnimationFrame(() => toggle.current?.focus());
}}
size="icon-sm"
variant="send"
>
<Icon.sidebar className="rotate-180" />
</Button>
<div
className="workspace-chat-content flex min-h-0 flex-1 flex-col"
ref={sidebar.setHost}
/>
</aside>
</>
);
}