- Relay UI: user-facing TensorZero strings -> Relay; bug-report links point to the Relay operator; API Keys card description; tests updated to match - Vend admin/console, Turnstile admin: load failures render as red role=alert error state instead of muted empty state - Rithub web: capitalized brand in title/header/footer/sign-in - README: complete, current Apps table with console locations Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1150 lines
35 KiB
TypeScript
1150 lines
35 KiB
TypeScript
import {
|
|
AlertCircle,
|
|
AlertTriangle,
|
|
BarChart3,
|
|
ChevronRight,
|
|
KeyRound,
|
|
Loader2,
|
|
RotateCcw,
|
|
} from "lucide-react";
|
|
import { Button } from "~/components/ui/button";
|
|
import { Component, type RefObject, useMemo, useState } from "react";
|
|
import {
|
|
AnimatedEllipsis,
|
|
EllipsisMode,
|
|
} from "~/components/ui/AnimatedEllipsis";
|
|
import { Markdown, ReadOnlyCodeBlock } from "~/components/ui/markdown";
|
|
import { CodeEditor, useFormattedJson } from "~/components/ui/code-editor";
|
|
import { UuidLink } from "~/components/autopilot/UuidLink";
|
|
import {
|
|
remarkUuidLinks,
|
|
UUID_LINK_ELEMENT,
|
|
} from "~/components/autopilot/remarkUuidLinks";
|
|
import { Skeleton } from "~/components/ui/skeleton";
|
|
import { logger } from "~/utils/logger";
|
|
import { DotSeparator } from "~/components/ui/DotSeparator";
|
|
import { TableItemTime } from "~/components/ui/TableItems";
|
|
import {
|
|
Tooltip,
|
|
TooltipContent,
|
|
TooltipTrigger,
|
|
} from "~/components/ui/tooltip";
|
|
import { useAutopilotSession } from "~/contexts/AutopilotSessionContext";
|
|
import type {
|
|
AutoEvalContentBlock,
|
|
AutoEvalLabeledExample,
|
|
AutopilotStatus,
|
|
EventPayloadMessageContent,
|
|
EventPayloadUserQuestion,
|
|
GatewayEvent,
|
|
GatewayEventPayload,
|
|
UserQuestionAnswer,
|
|
VisualizationType,
|
|
} from "~/types/tensorzero";
|
|
import { formatResponse } from "~/components/autopilot/question-cards/formatResponse";
|
|
import { hasAnsweredResponse } from "~/components/autopilot/question-cards/responseStatus";
|
|
import { Check, Cross } from "~/components/icons/Icons";
|
|
import { cn } from "~/utils/common";
|
|
import { ApplyConfigChangeButton } from "~/components/autopilot/ApplyConfigChangeButton";
|
|
import EventVisualization, {
|
|
detectEventVisualization,
|
|
type EventVisualizationData,
|
|
} from "./EventVisualization";
|
|
|
|
/**
|
|
* Max height for expandable tool content (tool call arguments, tool results, errors).
|
|
* Keeps long content from dominating the chat view by making it scrollable.
|
|
*/
|
|
export const TOOL_CONTENT_MAX_HEIGHT = "400px";
|
|
|
|
/**
|
|
* Optimistic messages are shown after the API confirms receipt but before
|
|
* SSE delivers the real event.
|
|
*
|
|
* Flow:
|
|
* 1. User sends message → POST request fires
|
|
* 2. API responds with event_id → optimistic message created (eventId already set)
|
|
* 3. SSE delivers event with matching ID → optimistic message is removed
|
|
*
|
|
* By waiting for the API response, we always have the eventId, eliminating
|
|
* the race condition where SSE could arrive before we know the ID.
|
|
*/
|
|
export type OptimisticMessage = {
|
|
tempId: string; // Client-generated UUID, only used as React key
|
|
eventId: string; // Real ID from API response, used to match SSE events
|
|
text: string;
|
|
status: "sending" | "failed";
|
|
};
|
|
|
|
type EventSummary = {
|
|
description?: string;
|
|
};
|
|
|
|
type EventStreamProps = {
|
|
events: GatewayEvent[];
|
|
className?: string;
|
|
isLoadingOlder?: boolean;
|
|
hasReachedStart?: boolean;
|
|
loadError?: string | null;
|
|
onRetryLoad?: () => void;
|
|
topSentinelRef?: RefObject<HTMLDivElement | null>;
|
|
pendingToolCallIds?: Set<string>;
|
|
pendingUserQuestionIds?: Set<string>;
|
|
optimisticMessages?: OptimisticMessage[];
|
|
status?: AutopilotStatus;
|
|
configApplyEnabled?: boolean;
|
|
sessionId?: string;
|
|
};
|
|
|
|
export function ToolEventId({ id }: { id: string }) {
|
|
return (
|
|
<Tooltip>
|
|
<TooltipTrigger asChild>
|
|
<span
|
|
className="inline-block max-w-12 cursor-help overflow-hidden align-middle font-mono text-xs text-ellipsis whitespace-nowrap"
|
|
dir="rtl"
|
|
>
|
|
{id}
|
|
</span>
|
|
</TooltipTrigger>
|
|
<TooltipContent
|
|
className="border-border bg-bg-secondary text-fg-primary border text-xs shadow-lg"
|
|
sideOffset={5}
|
|
>
|
|
Tool Call ID: <span className="font-mono text-xs">{id}</span>
|
|
</TooltipContent>
|
|
</Tooltip>
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Tool event payload types - events related to tool calls.
|
|
*/
|
|
export type ToolEventPayload = Extract<
|
|
GatewayEventPayload,
|
|
{
|
|
type:
|
|
| "tool_call"
|
|
| "tool_call_authorization"
|
|
| "tool_result"
|
|
| "visualization";
|
|
}
|
|
>;
|
|
|
|
/**
|
|
* An event with a tool-related payload.
|
|
*/
|
|
export type ToolEvent = GatewayEvent & { payload: ToolEventPayload };
|
|
|
|
/**
|
|
* Type guard to check if an event is a tool event.
|
|
*/
|
|
export function isToolEvent(event: GatewayEvent): event is ToolEvent {
|
|
return (
|
|
event.payload.type === "tool_call" ||
|
|
event.payload.type === "tool_call_authorization" ||
|
|
event.payload.type === "tool_result" ||
|
|
event.payload.type === "visualization"
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Extracts the tool execution ID from a tool event.
|
|
* For tool_call events, this is in side_info.tool_call_event_id.
|
|
* For tool_call_authorization and tool_result events, this is tool_call_event_id on the payload.
|
|
* For visualization events, this is tool_execution_id on the payload.
|
|
*/
|
|
export function getToolCallEventId(event: ToolEvent): string {
|
|
const { payload } = event;
|
|
if (payload.type === "tool_call") {
|
|
return payload.side_info.tool_call_event_id;
|
|
}
|
|
if (payload.type === "visualization") {
|
|
return payload.tool_execution_id;
|
|
}
|
|
return payload.tool_call_event_id;
|
|
}
|
|
|
|
/**
|
|
* Type guard to check if an event is a config write event.
|
|
* A config write event is a tool_call with name === "write_config",
|
|
* or a tool_result / tool_call_authorization whose tool_call_name === "write_config"
|
|
* (which supersedes the original tool_call in the event stream).
|
|
*/
|
|
export function isConfigWriteEvent(event: GatewayEvent): boolean {
|
|
if (
|
|
event.payload.type === "tool_call" &&
|
|
event.payload.name === "write_config"
|
|
) {
|
|
return true;
|
|
}
|
|
if (
|
|
(event.payload.type === "tool_result" ||
|
|
event.payload.type === "tool_call_authorization") &&
|
|
event.payload.tool_call_name === "write_config"
|
|
) {
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
function getMessageText(content: EventPayloadMessageContent[]) {
|
|
return content.map((cb) => cb.text).join("\n\n");
|
|
}
|
|
|
|
/**
|
|
* Get the title for a visualization based on its type.
|
|
*/
|
|
function getVisualizationTitle(visualization: VisualizationType): string {
|
|
if (typeof visualization !== "object" || visualization === null) {
|
|
return "Visualization";
|
|
}
|
|
if ("type" in visualization) {
|
|
if (visualization.type === "top_k_evaluation") {
|
|
return "Top-K Evaluation Results";
|
|
}
|
|
// Unknown visualization type with a type field
|
|
return `Visualization (${String(visualization.type)})`;
|
|
}
|
|
return "Visualization";
|
|
}
|
|
|
|
/**
|
|
* Format a tool error for display.
|
|
* Extracts a human-readable message from the structured error JSON.
|
|
*/
|
|
function formatToolError(error: unknown): string {
|
|
if (typeof error === "object" && error !== null) {
|
|
const e = error as Record<string, unknown>;
|
|
// AutopilotToolError has a "message" field
|
|
if (typeof e.message === "string") {
|
|
return e.message;
|
|
}
|
|
}
|
|
// Fallback to JSON stringification
|
|
return JSON.stringify(error);
|
|
}
|
|
|
|
type ToolStatusVariant =
|
|
| "success"
|
|
| "failure"
|
|
| "pending_execution"
|
|
| "pending_approval"
|
|
| "warning";
|
|
|
|
type ToolStatusInfo = {
|
|
label: string;
|
|
variant: ToolStatusVariant;
|
|
};
|
|
|
|
function getToolEventStatus(event: GatewayEvent): ToolStatusInfo | null {
|
|
const { payload } = event;
|
|
|
|
if (payload.type === "tool_call") {
|
|
if (payload.requires_approval) {
|
|
return { label: "Pending Approval", variant: "pending_approval" };
|
|
}
|
|
return { label: "Pending Execution", variant: "pending_execution" };
|
|
}
|
|
|
|
if (payload.type === "tool_call_authorization") {
|
|
switch (payload.status.type) {
|
|
case "approved":
|
|
return { label: "Pending Execution", variant: "pending_execution" };
|
|
case "rejected":
|
|
return { label: "Rejected", variant: "failure" };
|
|
default: {
|
|
const _exhaustiveCheck: never = payload.status;
|
|
return _exhaustiveCheck;
|
|
}
|
|
}
|
|
}
|
|
|
|
if (payload.type === "tool_result") {
|
|
switch (payload.outcome.type) {
|
|
case "success":
|
|
return { label: "Success", variant: "success" };
|
|
case "failure":
|
|
return { label: "Error", variant: "failure" };
|
|
case "rejected":
|
|
return { label: "Rejected", variant: "failure" };
|
|
case "missing":
|
|
return { label: "Missing Tool", variant: "failure" };
|
|
case "unknown":
|
|
return { label: "Unknown", variant: "warning" };
|
|
default: {
|
|
const _exhaustiveCheck: never = payload.outcome;
|
|
return _exhaustiveCheck;
|
|
}
|
|
}
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
function ToolStatusIcon({ variant }: { variant: ToolStatusVariant }) {
|
|
switch (variant) {
|
|
case "success":
|
|
return <Check className="h-3 w-3 text-green-600 dark:text-green-400" />;
|
|
case "failure":
|
|
return <Cross className="h-3 w-3 text-red-400" />;
|
|
case "pending_execution":
|
|
return (
|
|
<Loader2 className="h-3 w-3 animate-spin text-gray-400 dark:text-gray-500" />
|
|
);
|
|
case "pending_approval":
|
|
return (
|
|
<KeyRound className="h-3 w-3 text-yellow-500 dark:text-yellow-400" />
|
|
);
|
|
case "warning":
|
|
return (
|
|
<AlertTriangle className="h-3 w-3 text-yellow-500 dark:text-yellow-400" />
|
|
);
|
|
default: {
|
|
const _exhaustiveCheck: never = variant;
|
|
return _exhaustiveCheck;
|
|
}
|
|
}
|
|
}
|
|
|
|
function ToolStatusBadge({ status }: { status: ToolStatusInfo }) {
|
|
return (
|
|
<span className="border-border bg-bg-primary text-fg-muted inline-flex items-center gap-1 rounded border px-1.5 py-0.5 text-xs font-medium">
|
|
<ToolStatusIcon variant={status.variant} />
|
|
{status.label}
|
|
</span>
|
|
);
|
|
}
|
|
|
|
function summarizeEvent(event: GatewayEvent): EventSummary {
|
|
const { payload } = event;
|
|
|
|
switch (payload.type) {
|
|
case "message":
|
|
return {
|
|
description: getMessageText(payload.content),
|
|
};
|
|
case "status_update":
|
|
return {
|
|
description: payload.status_update.text,
|
|
};
|
|
case "tool_call": {
|
|
return { description: JSON.stringify(payload.arguments, null, 2) };
|
|
}
|
|
case "tool_call_authorization":
|
|
return {};
|
|
case "tool_result":
|
|
if (payload.outcome.type === "success") {
|
|
const description =
|
|
"result_value" in payload.outcome
|
|
? JSON.stringify(payload.outcome.result_value, null, 2)
|
|
: payload.outcome.result;
|
|
return { description };
|
|
}
|
|
if (payload.outcome.type === "failure") {
|
|
return {
|
|
description: formatToolError(payload.outcome.error),
|
|
};
|
|
}
|
|
return {};
|
|
case "error":
|
|
return {
|
|
description: payload.message,
|
|
};
|
|
case "user_questions":
|
|
case "user_questions_answers":
|
|
case "auto_eval_example_labeling":
|
|
case "auto_eval_example_labeling_answers":
|
|
case "auto_eval_behavior_spec":
|
|
case "auto_eval_behavior_spec_answers":
|
|
case "visualization":
|
|
case "unknown":
|
|
return {};
|
|
}
|
|
}
|
|
|
|
function renderEventTitle(event: GatewayEvent) {
|
|
const { payload } = event;
|
|
|
|
switch (payload.type) {
|
|
case "message": {
|
|
if (payload.role === "user") return "User";
|
|
if (payload.role === "assistant") return "Assistant";
|
|
const _exhaustiveCheck: never = payload.role;
|
|
return _exhaustiveCheck;
|
|
}
|
|
case "status_update":
|
|
return "Status Update";
|
|
case "tool_call":
|
|
return (
|
|
<span className="inline-flex items-center gap-2">
|
|
Tool Call
|
|
<DotSeparator />
|
|
<span className="font-mono font-medium">{payload.name}</span>
|
|
</span>
|
|
);
|
|
case "tool_call_authorization":
|
|
case "tool_result":
|
|
return (
|
|
<span className="inline-flex items-center gap-2">
|
|
Tool Call
|
|
{payload.tool_call_name && (
|
|
<>
|
|
<DotSeparator />
|
|
<span className="font-mono font-medium">
|
|
{payload.tool_call_name}
|
|
</span>
|
|
</>
|
|
)}
|
|
</span>
|
|
);
|
|
case "error":
|
|
// TODO: handle errors better
|
|
return "Error";
|
|
case "visualization":
|
|
return (
|
|
<span className="inline-flex items-center gap-2">
|
|
<BarChart3 className="h-4 w-4" />
|
|
<span>{getVisualizationTitle(payload.visualization)}</span>
|
|
</span>
|
|
);
|
|
case "user_questions": {
|
|
const questionCount = payload.questions.length;
|
|
return (
|
|
<span className="inline-flex items-center gap-2">
|
|
{questionCount === 1 ? "Question" : "Questions"}
|
|
</span>
|
|
);
|
|
}
|
|
case "user_questions_answers": {
|
|
const answerCount = Object.keys(payload.responses).length;
|
|
return (
|
|
<span className="inline-flex items-center gap-2">
|
|
{answerCount === 1 ? "Question" : "Questions"}
|
|
<DotSeparator />
|
|
{hasAnsweredResponse(payload.responses) ? "Answered" : "Skipped"}
|
|
</span>
|
|
);
|
|
}
|
|
case "auto_eval_example_labeling":
|
|
return "Example Labeling";
|
|
case "auto_eval_example_labeling_answers": {
|
|
const exampleCount = payload.examples.length;
|
|
return (
|
|
<span className="inline-flex items-center gap-2">
|
|
{exampleCount === 1 ? "Example Label" : "Example Labels"}
|
|
<DotSeparator />
|
|
Submitted
|
|
</span>
|
|
);
|
|
}
|
|
case "auto_eval_behavior_spec":
|
|
return "Behavior Spec";
|
|
case "auto_eval_behavior_spec_answers":
|
|
return (
|
|
<span className="inline-flex items-center gap-2">
|
|
Behavior Spec
|
|
<DotSeparator />
|
|
Submitted
|
|
</span>
|
|
);
|
|
case "unknown":
|
|
return (
|
|
<span className="inline-flex items-center gap-2">
|
|
<span>Unknown Event</span>
|
|
<Tooltip>
|
|
<TooltipTrigger asChild>
|
|
<span
|
|
className="inline-flex cursor-help items-center text-yellow-600"
|
|
aria-label="Unknown event"
|
|
>
|
|
<AlertTriangle className="h-4 w-4" />
|
|
</span>
|
|
</TooltipTrigger>
|
|
<TooltipContent className="max-w-xs text-xs">
|
|
The Autopilot API returned an unknown event. This likely means
|
|
your Relay deployment version is outdated.
|
|
</TooltipContent>
|
|
</Tooltip>
|
|
</span>
|
|
);
|
|
default:
|
|
return "Event";
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Error boundary for individual event items.
|
|
* Prevents a single malformed event from crashing the entire chat.
|
|
*/
|
|
interface EventErrorBoundaryState {
|
|
hasError: boolean;
|
|
}
|
|
|
|
interface EventErrorBoundaryProps {
|
|
eventId: string;
|
|
children: React.ReactNode;
|
|
}
|
|
|
|
class EventErrorBoundary extends Component<
|
|
EventErrorBoundaryProps,
|
|
EventErrorBoundaryState
|
|
> {
|
|
constructor(props: EventErrorBoundaryProps) {
|
|
super(props);
|
|
this.state = { hasError: false };
|
|
}
|
|
|
|
static getDerivedStateFromError(): EventErrorBoundaryState {
|
|
return { hasError: true };
|
|
}
|
|
|
|
componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
|
|
logger.error(
|
|
`Event ${this.props.eventId} failed to render:`,
|
|
error,
|
|
errorInfo,
|
|
);
|
|
}
|
|
|
|
render() {
|
|
if (this.state.hasError) {
|
|
return (
|
|
<div className="border-border bg-bg-secondary rounded-md border px-4 py-3">
|
|
<div className="flex items-center gap-2 text-sm">
|
|
<AlertCircle className="h-4 w-4 text-amber-500" />
|
|
<span className="text-fg-muted">
|
|
Failed to display event. The event data may be corrupted.
|
|
</span>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
return this.props.children;
|
|
}
|
|
}
|
|
|
|
type UserQuestionsContentProps = {
|
|
questions: EventPayloadUserQuestion[];
|
|
};
|
|
|
|
function UserQuestionsContent({ questions }: UserQuestionsContentProps) {
|
|
return (
|
|
<div className="flex flex-col gap-2">
|
|
{questions.map((q) => (
|
|
<div key={q.id} className="flex flex-col gap-0.5">
|
|
<span className="text-fg-muted text-xs font-medium">{q.header}</span>
|
|
<span className="text-fg-secondary text-sm">{q.question}</span>
|
|
</div>
|
|
))}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
type UserQuestionsAnswersContentProps = {
|
|
responses: Record<string, UserQuestionAnswer>;
|
|
questions: EventPayloadUserQuestion[];
|
|
};
|
|
|
|
function UserQuestionsAnswersContent({
|
|
responses,
|
|
questions,
|
|
}: UserQuestionsAnswersContentProps) {
|
|
return (
|
|
<div className="flex flex-col gap-2">
|
|
{Object.entries(responses).map(([questionId, response]) => {
|
|
const question = questions.find((q) => q.id === questionId);
|
|
return (
|
|
<div key={questionId} className="flex flex-col gap-0.5">
|
|
<span className="text-fg-muted text-xs font-medium">
|
|
{question?.header ?? questionId}
|
|
</span>
|
|
<span className="text-fg-primary text-sm">
|
|
{formatResponse(response, question)}
|
|
</span>
|
|
</div>
|
|
);
|
|
})}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function formatLabelAnswer(
|
|
answer: UserQuestionAnswer,
|
|
example: AutoEvalLabeledExample,
|
|
): string {
|
|
return formatResponse(answer, {
|
|
id: example.label_question.id,
|
|
header: example.label_question.header,
|
|
question: example.label_question.question,
|
|
type: "multiple_choice",
|
|
options: example.label_question.options,
|
|
multi_select: false,
|
|
});
|
|
}
|
|
|
|
function AutoEvalLabelingAnswersContent({
|
|
examples,
|
|
}: {
|
|
examples: AutoEvalLabeledExample[];
|
|
}) {
|
|
return (
|
|
<div className="flex flex-col gap-4">
|
|
{examples.map((example, idx) => (
|
|
<div key={idx} className="flex flex-col gap-2">
|
|
{/* Context blocks */}
|
|
{[example.maybe_excerpted_prompt, example.maybe_excerpted_response]
|
|
.filter((block): block is AutoEvalContentBlock => block !== null)
|
|
.map((block, blockIdx) => (
|
|
<div key={blockIdx} className="flex flex-col gap-0.5">
|
|
{block.label && (
|
|
<span className="text-fg-muted text-xs font-medium">
|
|
{block.label}
|
|
</span>
|
|
)}
|
|
{block.type === "markdown" ? (
|
|
<p className="text-fg-secondary text-sm whitespace-pre-wrap">
|
|
{block.text}
|
|
</p>
|
|
) : (
|
|
<pre className="text-fg-secondary overflow-x-auto rounded bg-black/5 p-2 text-xs dark:bg-white/5">
|
|
{JSON.stringify(block.data, null, 2)}
|
|
</pre>
|
|
)}
|
|
</div>
|
|
))}
|
|
{/* Label answer */}
|
|
<div className="flex flex-col gap-0.5">
|
|
<span className="text-fg-muted text-xs font-medium">
|
|
{example.label_question.header}
|
|
</span>
|
|
<span className="text-fg-primary text-sm">
|
|
{formatLabelAnswer(example.label_answer, example)}
|
|
</span>
|
|
</div>
|
|
{/* Explanation answer */}
|
|
{example.explanation_question && example.explanation_answer && (
|
|
<div className="flex flex-col gap-0.5">
|
|
<span className="text-fg-muted text-xs font-medium">
|
|
{example.explanation_question.header}
|
|
</span>
|
|
<span className="text-fg-primary text-sm">
|
|
{formatResponse(example.explanation_answer, {
|
|
id: example.explanation_question.id,
|
|
header: example.explanation_question.header,
|
|
question: example.explanation_question.question,
|
|
type: "free_response",
|
|
})}
|
|
</span>
|
|
</div>
|
|
)}
|
|
</div>
|
|
))}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
type ToolResultPayload = Extract<GatewayEventPayload, { type: "tool_result" }>;
|
|
type ToolCallAuthPayload = Extract<
|
|
GatewayEventPayload,
|
|
{ type: "tool_call_authorization" }
|
|
>;
|
|
|
|
function ToolCallArgumentsSection({ arguments: args }: { arguments: unknown }) {
|
|
if (!args) return null;
|
|
return (
|
|
<div className="flex flex-col gap-1">
|
|
<span className="text-fg-muted text-xs font-medium">Arguments</span>
|
|
<ReadOnlyCodeBlock code={JSON.stringify(args, null, 2)} language="json" />
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function ToolResultContent({
|
|
payload,
|
|
description,
|
|
}: {
|
|
payload: ToolResultPayload;
|
|
description?: string;
|
|
}) {
|
|
const rejectionReason =
|
|
payload.outcome.type === "rejected" ? payload.outcome.reason : null;
|
|
const formattedDescription = useFormattedJson(description ?? "");
|
|
|
|
return (
|
|
<div className="flex flex-col gap-3">
|
|
{payload.tool_call_arguments && (
|
|
<ToolCallArgumentsSection arguments={payload.tool_call_arguments} />
|
|
)}
|
|
{description && (
|
|
<div className="flex flex-col gap-1">
|
|
<span className="text-fg-muted text-xs font-medium">Result</span>
|
|
<CodeEditor
|
|
value={formattedDescription}
|
|
readOnly
|
|
allowedLanguages={["json", "text"]}
|
|
showLineNumbers={false}
|
|
/>
|
|
</div>
|
|
)}
|
|
{rejectionReason && (
|
|
<div className="flex flex-col gap-1">
|
|
<span className="text-fg-muted text-xs font-medium">
|
|
Rejection Reason
|
|
</span>
|
|
<ReadOnlyCodeBlock code={rejectionReason} language="text" />
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function ToolCallAuthorizationContent({
|
|
payload,
|
|
}: {
|
|
payload: ToolCallAuthPayload;
|
|
}) {
|
|
return (
|
|
<div className="flex flex-col gap-3">
|
|
{payload.tool_call_arguments && (
|
|
<ToolCallArgumentsSection arguments={payload.tool_call_arguments} />
|
|
)}
|
|
{payload.status.type === "rejected" && (
|
|
<div className="flex flex-col gap-1">
|
|
<span className="text-fg-muted text-xs font-medium">
|
|
Rejection Reason
|
|
</span>
|
|
<ReadOnlyCodeBlock code={payload.status.reason} language="text" />
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
const uuidRemarkPlugins = [remarkUuidLinks];
|
|
const uuidComponents = { [UUID_LINK_ELEMENT]: UuidLink };
|
|
|
|
interface EventItemContentProps {
|
|
event: GatewayEvent;
|
|
description?: string;
|
|
visualizationData: EventVisualizationData | null;
|
|
questionsMap?: Map<string, EventPayloadUserQuestion[]>;
|
|
}
|
|
|
|
function EventItemContent({
|
|
event,
|
|
description,
|
|
visualizationData,
|
|
questionsMap,
|
|
}: EventItemContentProps) {
|
|
if (visualizationData) {
|
|
return <EventVisualization data={visualizationData} />;
|
|
}
|
|
|
|
if (event.payload.type === "user_questions") {
|
|
return <UserQuestionsContent questions={event.payload.questions} />;
|
|
}
|
|
|
|
if (event.payload.type === "user_questions_answers") {
|
|
return (
|
|
<UserQuestionsAnswersContent
|
|
responses={event.payload.responses}
|
|
questions={
|
|
questionsMap?.get(event.payload.user_questions_event_id) ?? []
|
|
}
|
|
/>
|
|
);
|
|
}
|
|
|
|
if (event.payload.type === "auto_eval_example_labeling_answers") {
|
|
return <AutoEvalLabelingAnswersContent examples={event.payload.examples} />;
|
|
}
|
|
|
|
if (event.payload.type === "tool_result") {
|
|
return (
|
|
<ToolResultContent payload={event.payload} description={description} />
|
|
);
|
|
}
|
|
|
|
if (event.payload.type === "tool_call_authorization") {
|
|
return <ToolCallAuthorizationContent payload={event.payload} />;
|
|
}
|
|
|
|
if (!description) return null;
|
|
|
|
switch (event.payload.type) {
|
|
case "message":
|
|
return (
|
|
<Markdown remarkPlugins={uuidRemarkPlugins} components={uuidComponents}>
|
|
{description}
|
|
</Markdown>
|
|
);
|
|
|
|
case "tool_call":
|
|
return <ToolCallArgumentsSection arguments={event.payload.arguments} />;
|
|
|
|
case "error":
|
|
return (
|
|
<p
|
|
className="text-fg-secondary overflow-y-auto text-sm whitespace-pre-wrap font-mono"
|
|
style={{ maxHeight: TOOL_CONTENT_MAX_HEIGHT }}
|
|
>
|
|
{description}
|
|
</p>
|
|
);
|
|
|
|
case "status_update":
|
|
case "visualization":
|
|
case "auto_eval_example_labeling":
|
|
case "auto_eval_behavior_spec":
|
|
case "auto_eval_behavior_spec_answers":
|
|
case "unknown":
|
|
return (
|
|
<p className="text-fg-secondary text-sm whitespace-pre-wrap">
|
|
{description}
|
|
</p>
|
|
);
|
|
|
|
default: {
|
|
const _exhaustiveCheck: never = event.payload;
|
|
return _exhaustiveCheck;
|
|
}
|
|
}
|
|
}
|
|
|
|
type EventItemProps = {
|
|
event: GatewayEvent;
|
|
questionsMap?: Map<string, EventPayloadUserQuestion[]>;
|
|
isPendingToolCall?: boolean;
|
|
isPendingQuestion?: boolean;
|
|
configApplyEnabled?: boolean;
|
|
sessionId?: string;
|
|
};
|
|
|
|
function EventItem({
|
|
event,
|
|
questionsMap,
|
|
isPendingToolCall = false,
|
|
isPendingQuestion = false,
|
|
configApplyEnabled = false,
|
|
sessionId,
|
|
}: EventItemProps) {
|
|
const { yoloMode } = useAutopilotSession();
|
|
|
|
const visualizationData = useMemo(
|
|
() => detectEventVisualization(event),
|
|
[event],
|
|
);
|
|
|
|
const summary = summarizeEvent(event);
|
|
const title = renderEventTitle(event);
|
|
const eventIsToolEvent = isToolEvent(event);
|
|
const isConfigWrite = isConfigWriteEvent(event);
|
|
const isExpandable =
|
|
event.payload.type === "tool_call" ||
|
|
event.payload.type === "error" ||
|
|
event.payload.type === "visualization" ||
|
|
event.payload.type === "user_questions" ||
|
|
event.payload.type === "user_questions_answers" ||
|
|
event.payload.type === "auto_eval_example_labeling_answers" ||
|
|
(event.payload.type === "tool_call_authorization" &&
|
|
(event.payload.status.type === "rejected" ||
|
|
event.payload.tool_call_arguments != null)) ||
|
|
(event.payload.type === "tool_result" &&
|
|
(event.payload.outcome.type === "success" ||
|
|
event.payload.outcome.type === "failure" ||
|
|
event.payload.outcome.type === "rejected" ||
|
|
event.payload.tool_call_arguments != null));
|
|
const [isExpanded, setIsExpanded] = useState(visualizationData != null);
|
|
const shouldShowDetails = !isExpandable || isExpanded;
|
|
const toolStatus = getToolEventStatus(event);
|
|
const label = <span className="text-sm font-medium">{title}</span>;
|
|
|
|
return (
|
|
<div className="border-border bg-bg-secondary flex flex-col gap-2 rounded-md border px-4 py-3">
|
|
<div className="flex items-center justify-between gap-4">
|
|
<div className="flex min-w-0 items-center gap-2">
|
|
{isExpandable ? (
|
|
<button
|
|
type="button"
|
|
aria-expanded={isExpanded}
|
|
aria-label={
|
|
isExpanded ? "Collapse event details" : "Expand event details"
|
|
}
|
|
className="inline-flex cursor-pointer items-center gap-2 text-left"
|
|
onClick={() => setIsExpanded((current) => !current)}
|
|
>
|
|
{label}
|
|
<span
|
|
className={cn(
|
|
"text-fg-muted inline-flex transition-transform duration-200",
|
|
isExpanded ? "rotate-90" : "rotate-0",
|
|
)}
|
|
>
|
|
<ChevronRight className="h-4 w-4" />
|
|
</span>
|
|
{((isPendingToolCall && !yoloMode) || isPendingQuestion) && (
|
|
<span className="rounded bg-blue-200 px-1.5 py-0.5 text-xs font-medium text-blue-800 dark:bg-blue-800 dark:text-blue-200">
|
|
Action Required
|
|
</span>
|
|
)}
|
|
</button>
|
|
) : (
|
|
label
|
|
)}
|
|
{toolStatus && <ToolStatusBadge status={toolStatus} />}
|
|
</div>
|
|
<div className="text-fg-muted flex items-center gap-1.5 text-xs">
|
|
{isConfigWrite && configApplyEnabled && sessionId && (
|
|
<ApplyConfigChangeButton sessionId={sessionId} event={event} />
|
|
)}
|
|
{eventIsToolEvent && (
|
|
<>
|
|
<ToolEventId id={getToolCallEventId(event)} />
|
|
<DotSeparator />
|
|
</>
|
|
)}
|
|
<TableItemTime timestamp={event.created_at} />
|
|
</div>
|
|
</div>
|
|
{shouldShowDetails && (
|
|
<EventItemContent
|
|
event={event}
|
|
description={summary.description}
|
|
visualizationData={visualizationData}
|
|
questionsMap={questionsMap}
|
|
/>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function EventSkeletons({ count = 3 }: { count?: number }) {
|
|
return (
|
|
<div className="flex flex-col gap-3">
|
|
{Array.from({ length: count }).map((_, i) => (
|
|
<div
|
|
key={i}
|
|
className="border-border bg-bg-secondary rounded-md border px-4 py-3"
|
|
>
|
|
<div className="flex items-center justify-between gap-4">
|
|
<Skeleton className="h-5 w-32" />
|
|
<Skeleton className="h-4 w-24" />
|
|
</div>
|
|
<Skeleton className="mt-2 h-4 w-3/4" />
|
|
</div>
|
|
))}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function Divider({ children }: { children: React.ReactNode }) {
|
|
return (
|
|
<div className="flex items-center gap-5 py-2">
|
|
<div className="border-border flex-1 border-t" />
|
|
<span className="text-fg-muted relative text-xs">{children}</span>
|
|
<div className="border-border flex-1 border-t" />
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function SessionStartDivider() {
|
|
return <Divider>Start</Divider>;
|
|
}
|
|
|
|
function OptimisticMessageItem({ message }: { message: OptimisticMessage }) {
|
|
// Optimistic messages are shown after POST succeeds, so the message is saved.
|
|
// We display it like a regular user message, with a skeleton for the timestamp.
|
|
return (
|
|
<div className="border-border bg-bg-secondary flex flex-col gap-2 rounded-md border px-4 py-3">
|
|
<div className="flex items-center justify-between gap-4">
|
|
<span className="text-sm font-medium">User</span>
|
|
<Skeleton className="h-4 w-32" />
|
|
</div>
|
|
<Markdown remarkPlugins={uuidRemarkPlugins} components={uuidComponents}>
|
|
{message.text}
|
|
</Markdown>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function getStatusLabel(status: AutopilotStatus): {
|
|
text: string;
|
|
showEllipsis: boolean;
|
|
} {
|
|
switch (status.status) {
|
|
case "idle":
|
|
return { text: "Ready", showEllipsis: false };
|
|
case "server_side_processing":
|
|
return { text: "Thinking", showEllipsis: true };
|
|
case "waiting_for_tool_call_authorization":
|
|
return { text: "Waiting", showEllipsis: false };
|
|
case "waiting_for_tool_execution":
|
|
return { text: "Executing tool", showEllipsis: true };
|
|
case "waiting_for_user_questions_answers":
|
|
return { text: "Waiting for your response", showEllipsis: false };
|
|
case "waiting_for_auto_eval_example_labeling_answers":
|
|
return { text: "Waiting for your response", showEllipsis: false };
|
|
case "waiting_for_auto_eval_behavior_spec_answers":
|
|
return { text: "Waiting for your response", showEllipsis: false };
|
|
case "waiting_for_retry":
|
|
return { text: "Something went wrong. Retrying", showEllipsis: true };
|
|
case "failed":
|
|
return {
|
|
text: "Something went wrong. Please try again.",
|
|
showEllipsis: false,
|
|
};
|
|
}
|
|
}
|
|
|
|
function StatusIndicator({ status }: { status: AutopilotStatus }) {
|
|
const { text, showEllipsis } = getStatusLabel(status);
|
|
return (
|
|
<Divider>
|
|
{text}
|
|
{showEllipsis && <AnimatedEllipsis mode={EllipsisMode.Absolute} />}
|
|
</Divider>
|
|
);
|
|
}
|
|
|
|
function LoadErrorNotice({ onRetry }: { onRetry?: () => void }) {
|
|
return (
|
|
<div className="flex items-center justify-center gap-2 py-2 text-sm text-amber-600">
|
|
<span>Failed to load older messages</span>
|
|
{onRetry && (
|
|
<Button
|
|
variant="ghost"
|
|
size="sm"
|
|
onClick={onRetry}
|
|
className="h-6 gap-1 px-2 text-amber-600 hover:text-amber-700"
|
|
>
|
|
<RotateCcw className="h-3 w-3" />
|
|
Retry
|
|
</Button>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
export default function EventStream({
|
|
events,
|
|
className,
|
|
isLoadingOlder = false,
|
|
hasReachedStart = false,
|
|
loadError,
|
|
onRetryLoad,
|
|
topSentinelRef,
|
|
pendingToolCallIds,
|
|
pendingUserQuestionIds,
|
|
optimisticMessages = [],
|
|
status,
|
|
configApplyEnabled = false,
|
|
sessionId,
|
|
}: EventStreamProps) {
|
|
// Map from user_questions event ID → questions array, used to resolve
|
|
// option labels when rendering user_questions_answers events.
|
|
const questionsMap = useMemo(() => {
|
|
const map = new Map<string, EventPayloadUserQuestion[]>();
|
|
for (const event of events) {
|
|
if (event.payload.type === "user_questions") {
|
|
map.set(event.id, event.payload.questions);
|
|
}
|
|
}
|
|
return map;
|
|
}, [events]);
|
|
|
|
// Set of event IDs that are superseded by a later "fat" event containing
|
|
// all the same information. We hide these to avoid redundancy in the stream.
|
|
//
|
|
// Sequences collapsed:
|
|
// - tool_call + tool_call_authorization → hidden when tool_result exists
|
|
// (tool_result contains tool_call_name, arguments, and auth status)
|
|
// - tool_call → hidden when tool_call_authorization exists (but no result yet)
|
|
// - auto_eval_example_labeling → hidden when answers exist
|
|
// - auto_eval_behavior_spec → hidden when answers exist
|
|
const supersededEventIds = useMemo(() => {
|
|
const ids = new Set<string>();
|
|
// Track which tool_call_event_ids have an authorization event
|
|
const authByToolCallId = new Map<string, string>(); // tool_call_event_id → auth event's tool_call_event_id
|
|
for (const event of events) {
|
|
const { payload } = event;
|
|
if (payload.type === "tool_call_authorization") {
|
|
authByToolCallId.set(payload.tool_call_event_id, event.id);
|
|
}
|
|
}
|
|
for (const event of events) {
|
|
const { payload } = event;
|
|
if (payload.type === "tool_result") {
|
|
// tool_result supersedes both the tool_call and tool_call_authorization
|
|
ids.add(payload.tool_call_event_id);
|
|
const authEventId = authByToolCallId.get(payload.tool_call_event_id);
|
|
if (authEventId) {
|
|
ids.add(authEventId);
|
|
}
|
|
} else if (payload.type === "tool_call_authorization") {
|
|
// tool_call_authorization supersedes the tool_call
|
|
ids.add(payload.tool_call_event_id);
|
|
} else if (payload.type === "auto_eval_example_labeling_answers") {
|
|
ids.add(payload.auto_eval_example_labeling_event_id);
|
|
} else if (payload.type === "auto_eval_behavior_spec_answers") {
|
|
ids.add(payload.auto_eval_behavior_spec_event_id);
|
|
}
|
|
}
|
|
return ids;
|
|
}, [events]);
|
|
|
|
// Determine what to show at the top: sentinel, error, or session start
|
|
// Only show session start when there's content to display (events or optimistic messages)
|
|
const showSessionStart =
|
|
(hasReachedStart || optimisticMessages.length > 0) &&
|
|
!isLoadingOlder &&
|
|
!loadError &&
|
|
(events.length > 0 || optimisticMessages.length > 0);
|
|
|
|
return (
|
|
<div className={cn("flex flex-col gap-3", className)}>
|
|
{/* Sentinel for loading more - always present unless showing session start */}
|
|
{/* Must stay in DOM during loading/error so IntersectionObserver keeps working */}
|
|
{!showSessionStart && (
|
|
<div ref={topSentinelRef} className="h-1" aria-hidden="true" />
|
|
)}
|
|
|
|
{/* Error state - show retry notice (after sentinel so it appears below) */}
|
|
{loadError && <LoadErrorNotice onRetry={onRetryLoad} />}
|
|
|
|
{/* Session start indicator */}
|
|
{showSessionStart && <SessionStartDivider />}
|
|
|
|
{/* Show skeletons when more content exists above (not yet loaded) */}
|
|
{/* This prevents layout jump when loading starts */}
|
|
{!showSessionStart && !hasReachedStart && !loadError && (
|
|
<EventSkeletons count={3} />
|
|
)}
|
|
|
|
{events
|
|
.filter((event) => !supersededEventIds.has(event.id))
|
|
.map((event) => (
|
|
<EventErrorBoundary key={event.id} eventId={event.id}>
|
|
<EventItem
|
|
event={event}
|
|
questionsMap={questionsMap}
|
|
isPendingToolCall={pendingToolCallIds?.has(event.id)}
|
|
isPendingQuestion={pendingUserQuestionIds?.has(event.id)}
|
|
configApplyEnabled={configApplyEnabled}
|
|
sessionId={sessionId}
|
|
/>
|
|
</EventErrorBoundary>
|
|
))}
|
|
|
|
{/* Optimistic messages at the end */}
|
|
{optimisticMessages.map((message) => (
|
|
<OptimisticMessageItem key={message.tempId} message={message} />
|
|
))}
|
|
|
|
{/* Status indicator at the bottom */}
|
|
{status && <StatusIndicator status={status} />}
|
|
</div>
|
|
);
|
|
}
|