Messages tab for streams, with messages as the single record (#819)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Gregory SchierandClaude Opus 5.5 authored and GitHub committed 2026-11-06 18:45:52 -07:00
1 parent f63586f9f0
commit cc382b9226
42 files changed
+3403 -453

No files matched your search

+10 -1
View File
@@ -27,6 +27,15 @@ export interface SelectProps<T extends string> {
filterable?: boolean;
}
/** On macOS, where the host can say; an app with no platform host (the proxy) says no */
function isMacOs(): boolean {
try {
return platform.osType() === "macos";
} catch {
return false;
}
}
export function Select<T extends string>({
labelPosition = "top",
name,
@@ -66,7 +75,7 @@ export function Select<T extends string>({
<Label htmlFor={id} visuallyHidden={hideLabel} className={labelClassName} help={help}>
{label}
</Label>
{platform.osType() === "macos" && !filterable ? (
{isMacOs() && !filterable ? (
<HStack
space={2}
className={classNames(
@@ -0,0 +1,165 @@
import { useVirtualizer, type Virtualizer } from "@tanstack/react-virtual";
import classNames from "classnames";
import type { ReactElement, ReactNode, UIEvent } from "react";
import { useCallback, useLayoutEffect, useRef, useState } from "react";
import { Icon } from "../Icon";
import { IconButton } from "../IconButton";
interface Props<T> {
data: T[];
render: (item: T, index: number) => ReactElement<HTMLElement>;
header?: ReactNode;
/** Make container focusable for keyboard navigation */
focusable?: boolean;
/** Callback to expose the virtualizer for keyboard navigation */
onVirtualizerReady?: (virtualizer: Virtualizer<HTMLDivElement, Element>) => void;
/**
* Holds and catches up as the proxy's flow list does: once scrolled away from the end (or
* `holdSignal` changes), new items wait under a pill counting them, which scrolls back down.
* Without it, a button locks the scroll to the bottom again.
*/
catchUp?: { label: (count: number) => string };
/** Holds the scroll where it is whenever this changes, as selecting an item does */
holdSignal?: unknown;
}
export function AutoScroller<T>({
data,
render,
header,
focusable = false,
onVirtualizerReady,
catchUp,
holdSignal,
}: Props<T>) {
const containerRef = useRef<HTMLDivElement>(null);
const [autoScroll, setAutoScroll] = useState<boolean>(true);
// How many items there were when the scroll was held, to count the new ones
const [heldAt, setHeldAt] = useState<number>(0);
const latestLength = useRef(data.length);
latestLength.current = data.length;
// The virtualizer
const rowVirtualizer = useVirtualizer({
count: data.length,
getScrollElement: () => containerRef.current,
estimateSize: () => 27, // react-virtual requires a height, so we'll give it one
});
// Expose virtualizer to parent for keyboard navigation
useLayoutEffect(() => {
onVirtualizerReady?.(rowVirtualizer);
}, [rowVirtualizer, onVirtualizerReady]);
const hold = useCallback(() => {
setAutoScroll(false);
setHeldAt(latestLength.current);
}, []);
// Scroll to new items
const handleScroll = useCallback(
(e: UIEvent<HTMLDivElement>) => {
const el = e.currentTarget;
// Set auto-scroll when container is scrolled
const pixelsFromBottom = el.scrollHeight - (el.scrollTop + el.clientHeight);
const newAutoScroll = pixelsFromBottom <= 0;
if (newAutoScroll !== autoScroll) {
if (newAutoScroll) setAutoScroll(true);
else hold();
}
},
[autoScroll, hold],
);
// Selecting an item holds the list where it is
const lastHoldSignal = useRef(holdSignal);
useLayoutEffect(() => {
if (Object.is(lastHoldSignal.current, holdSignal)) return;
lastHoldSignal.current = holdSignal;
if (catchUp != null && autoScroll) hold();
}, [autoScroll, catchUp, hold, holdSignal]);
// Scroll to bottom on count change
useLayoutEffect(() => {
if (!autoScroll) return;
void data.length; // Trigger refresh when length changes
const el = containerRef.current;
if (el == null) return;
el.scrollTop = el.scrollHeight;
}, [autoScroll, data.length]);
const newCount = data.length - heldAt;
return (
<div className="h-full w-full relative grid grid-rows-[auto_minmax(0,1fr)]">
{!autoScroll && catchUp == null && (
<div className="absolute bottom-0 right-0 m-2">
<IconButton
title="Lock scroll to bottom"
icon="arrow_down"
size="sm"
iconSize="md"
variant="border"
className="bg-surface! z-10"
onClick={() => setAutoScroll((v) => !v)}
/>
</div>
)}
{!autoScroll && catchUp != null && newCount > 0 && (
<button
type="button"
onClick={() => setAutoScroll(true)}
className={classNames(
"absolute bottom-3 left-1/2 -translate-x-1/2 z-10",
"flex items-center gap-1.5 h-6 px-3 rounded-full",
"bg-surface border border-border shadow-lg text-text text-xs",
"hover:bg-surface-highlight",
)}
>
<Icon icon="arrow_down_to_line" size="sm" color="primary" />
{catchUp.label(newCount)}
</button>
)}
{header ?? <span aria-hidden />}
<div
ref={containerRef}
className="h-full w-full overflow-y-auto focus:outline-hidden"
onScroll={handleScroll}
tabIndex={focusable ? 0 : undefined}
>
<div
style={{
height: `${rowVirtualizer.getTotalSize()}px`,
width: "100%",
position: "relative",
}}
>
{rowVirtualizer.getVirtualItems().map((virtualItem) => {
const item = data[virtualItem.index];
return (
item != null && (
<div
key={virtualItem.key}
style={{
position: "absolute",
top: 0,
left: 0,
width: "100%",
height: `${virtualItem.size}px`,
transform: `translateY(${virtualItem.start}px)`,
}}
>
{render(item, virtualItem.index)}
</div>
)
);
})}
</div>
</div>
</div>
);
}
@@ -0,0 +1,110 @@
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, test, vi } from "vite-plus/test";
import { isLargePayload, payloadText, shouldLoadText, StreamEventRow } from "./EventStreamViewer";
import type { StreamEvent } from "./streamEvents";
// The detail header's select asks the platform which OS it runs on
vi.mock("@yaakapp-internal/platform", () => ({ platform: { osType: () => "macos" } }));
const event: StreamEvent = {
key: "3",
direction: "sent",
kind: "text",
timestamp: "2026-11-06T09:30:00.250",
size: 2048,
preview: '{"op":1}',
};
describe("StreamEventRow", () => {
test("without columns, draws the client's row: arrow, labels and preview", () => {
const markup = renderToStaticMarkup(
<StreamEventRow
event={{ ...event, direction: "received", labels: ["7", "tick"] }}
preview="hello"
delta={null}
isActive={false}
onClick={() => {}}
/>,
);
expect(markup).toContain('title="Server Message"');
expect(markup).toContain("grid-cols-[auto_minmax(0,1fr)_auto]");
expect(markup.indexOf(">7<")).toBeLessThan(markup.indexOf(">tick<"));
expect(markup).toContain('<span class="truncate text-xs">hello</span>');
// No size or time without the columns asking for them
expect(markup).not.toContain("2 KB");
});
test("with columns, draws direction, kind, preview, size, delta and time in order", () => {
const markup = renderToStaticMarkup(
<StreamEventRow
event={event}
preview={event.preview}
delta={1500}
columns={{ direction: true, kind: "Type", size: true, time: true }}
isActive={false}
onClick={() => {}}
/>,
);
expect(markup).toContain("grid-template-columns:1rem 4rem minmax(0,1fr) 4.5rem 4.5rem 6.5rem");
expect(markup).toContain('title="Client Message"');
const order = [">text<", "{&quot;op&quot;:1}", "2 KB", "+1.5 s"].map((s) => markup.indexOf(s));
expect(order.every((i) => i >= 0)).toBe(true);
expect([...order].sort((a, b) => a - b)).toEqual(order);
});
test("an event stream's row has no direction column, and a note replaces the preview", () => {
const markup = renderToStaticMarkup(
<StreamEventRow
event={{ ...event, direction: "info", note: "12 UNIMPLEMENTED", warning: true }}
preview={null}
delta={null}
columns={{ kind: "Event", size: true }}
isActive={false}
onClick={() => {}}
/>,
);
expect(markup).not.toContain("Client Message");
expect(markup).toContain('class="text-xs text-warning">12 UNIMPLEMENTED<');
});
test("an empty binary payload reads as no content, a non-empty one as binary", () => {
const row = (size: number) =>
renderToStaticMarkup(
<StreamEventRow
event={{ ...event, preview: null, binary: true, size }}
preview={null}
delta={null}
columns={{ kind: "Type" }}
isActive={false}
onClick={() => {}}
/>,
);
expect(row(0)).toContain("No content");
expect(row(4)).toContain("Binary");
});
});
describe("payloadText", () => {
test("pretty-prints JSON and leaves other text as it is", () => {
const bytes = (s: string) => new TextEncoder().encode(s);
expect(payloadText(bytes('{"a":[1]}'))).toEqual({
text: '{\n "a": [\n 1\n ]\n}',
language: "json",
});
expect(payloadText(bytes("42"))).toEqual({ text: "42", language: "text" });
expect(payloadText(bytes("plain"))).toEqual({ text: "plain", language: "text" });
});
});
describe("large payloads", () => {
test("nothing is decoded or pretty-printed over 1 MB until asked to", () => {
const big = 2_000_000;
expect(isLargePayload(big, false)).toBe(true);
expect(isLargePayload(big, true)).toBe(false);
expect(isLargePayload(1000, false)).toBe(false);
// Nothing is decoded before the bytes are in, as only they say how large it decodes to
expect(shouldLoadText({ hasBytes: false, tooLarge: false })).toBe(false);
expect(shouldLoadText({ hasBytes: true, tooLarge: true })).toBe(false);
expect(shouldLoadText({ hasBytes: true, tooLarge: false })).toBe(true);
});
});
@@ -0,0 +1,492 @@
import classNames from "classnames";
import type { ReactNode } from "react";
import { useEffect, useMemo, useState } from "react";
import { formatSize } from "@yaakapp-internal/lib/formatSize";
import { Banner } from "../Banner";
import { Button } from "../Button";
import { useEditorHost } from "../EditorHost";
import { EmptyStateText } from "../EmptyStateText";
import { Icon } from "../Icon";
import { InlineCode } from "../InlineCode";
import { HStack, VStack } from "../Stacks";
import { HexdumpViewer } from "../viewers/HexdumpViewer";
import { type EventDetailAction, EventDetailHeader, EventViewer } from "./EventViewer";
import { EventViewerRow } from "./EventViewerRow";
import {
eventDeltas,
formatEventDelta,
formatEventTime,
type StreamEvent,
type StreamPayload,
type StreamPayloadText,
type StreamPayloadView,
} from "./streamEvents";
/** Which columns the list draws beside each event's preview */
export interface EventStreamColumns {
/** The direction arrow, for a stream that goes both ways */
direction?: boolean;
/** The kind column's heading, like `Type` or `Event`; no column when not given */
kind?: string;
/** The kind column's width, as CSS: rows are laid out one by one, so it can't fit its content */
kindWidth?: string;
size?: boolean;
/** The time each passed, and how long after the one before */
time?: boolean;
/** The preview column's heading */
preview?: string;
}
export interface EventStreamViewerProps {
events: StreamEvent[];
/** Where the list and detail split is remembered */
splitLayoutStorageKey: string;
defaultRatio?: number;
/** Above the list, as a connection's status */
header?: ReactNode;
error?: string | null;
isLoading?: boolean;
emptyMessage?: string;
/** Without columns, a row is the client's: its arrow, its labels and its preview */
columns?: EventStreamColumns;
/** The text a row previews, when it isn't the event's own `preview` */
getPreview?: (event: StreamEvent) => string | null;
/** Reads an event's whole payload, for the default detail */
loadPayload?: (event: StreamEvent) => Promise<StreamPayload>;
/** Ways to show an event's payload beyond its text and hexdump, as a gRPC message's decodes */
payloadViews?: (event: StreamEvent) => StreamPayloadView[] | null;
/** Replaces the default detail, which shows the payload `loadPayload` reads */
renderDetail?: (props: { event: StreamEvent; index: number; onClose: () => void }) => ReactNode;
/** Holds and catches up, as the proxy's flow list does, while more events arrive */
catchUp?: { label: (count: number) => string };
}
/** A stream's events as a list, with the selected one's payload below */
export function EventStreamViewer({
events,
splitLayoutStorageKey,
defaultRatio = 0.4,
header,
error,
isLoading,
emptyMessage,
columns,
getPreview,
loadPayload,
payloadViews,
renderDetail,
catchUp,
}: EventStreamViewerProps) {
const deltas = useMemo(() => (columns?.time ? eventDeltas(events) : null), [columns, events]);
return (
<EventViewer
events={events}
getEventKey={(event) => event.key}
error={error}
isLoading={isLoading}
emptyMessage={emptyMessage}
splitLayoutStorageKey={splitLayoutStorageKey}
defaultRatio={defaultRatio}
catchUp={catchUp}
header={
columns == null ? (
header
) : (
<div>
{header}
<ColumnHeadings columns={columns} />
</div>
)
}
renderRow={({ event, index, isActive, onClick }) => (
<StreamEventRow
event={event}
preview={getPreview ? getPreview(event) : event.preview}
delta={deltas?.[index] ?? null}
columns={columns}
isActive={isActive}
onClick={onClick}
/>
)}
renderDetail={
renderDetail ??
(({ event, onClose }) => (
<StreamEventDetail
event={event}
loadPayload={loadPayload}
views={payloadViews?.(event) ?? null}
onClose={onClose}
/>
))
}
/>
);
}
/** One event's row: the client's arrow, labels and preview, or the columns asked for */
export function StreamEventRow({
event,
preview,
delta,
columns,
isActive,
onClick,
}: {
event: StreamEvent;
preview: string | null;
/** Milliseconds since the event before, for the time columns */
delta: number | null;
columns?: EventStreamColumns;
isActive: boolean;
onClick: () => void;
}) {
const template = columns == null ? null : gridTemplate(columns);
if (columns == null || template == null) {
return (
<EventViewerRow
isActive={isActive}
onClick={onClick}
icon={<DirectionIcon event={event} />}
content={
<HStack space={2} className="items-center">
{event.labels != null && event.labels.length > 0 && (
<HStack space={1.5} alignItems="center">
{event.labels.map((label, i) => (
// oxlint-disable-next-line no-array-index-key -- labels may repeat
<EventLabel key={`${i}:${label}`} isActive={isActive}>
{label}
</EventLabel>
))}
</HStack>
)}
<span className="truncate text-xs">{preview}</span>
</HStack>
}
/>
);
}
const trailing: ReactNode[] = [];
if (columns.size) {
trailing.push(
<span className="text-text-subtlest">
{event.size == null ? "" : formatSize(event.size)}
</span>,
);
}
if (columns.time) {
trailing.push(
<span className="text-text-subtlest">{formatEventDelta(delta)}</span>,
<span className="opacity-70">{formatEventTime(event.timestamp)}</span>,
);
}
return (
<EventViewerRow
isActive={isActive}
onClick={onClick}
columns={template}
icon={columns.direction ? <DirectionIcon event={event} /> : null}
cells={{
kind:
columns.kind == null ? undefined : (
<span className={classNames(event.warning && "text-warning")}>{event.kind}</span>
),
trailing,
}}
content={<RowPreview event={event} preview={preview} />}
/>
);
}
function gridTemplate(columns: EventStreamColumns): string {
return [
columns.direction ? "1rem" : null,
columns.kind == null ? null : (columns.kindWidth ?? "4rem"),
"minmax(0,1fr)",
columns.size ? "4.5rem" : null,
columns.time ? "4.5rem 6.5rem" : null,
]
.filter((c) => c != null)
.join(" ");
}
function ColumnHeadings({ columns }: { columns: EventStreamColumns }) {
const template = gridTemplate(columns);
return (
<div className="px-1">
<div
style={{ gridTemplateColumns: template }}
className="grid gap-2 items-center px-1.5 h-xs text-xs text-text-subtlest border-b border-surface-highlight mb-1"
>
{columns.direction && <span />}
{columns.kind != null && <span>{columns.kind}</span>}
<span>{columns.preview ?? "Message"}</span>
{columns.size && <span className="text-right">Size</span>}
{columns.time && (
<>
<span className="text-right" title="Since the message before">
Delta
</span>
<span className="text-right">Time</span>
</>
)}
</div>
</div>
);
}
function RowPreview({ event, preview }: { event: StreamEvent; preview: string | null }) {
if (event.note != null) {
return (
<span className={classNames("text-xs", event.warning ? "text-warning" : "text-text-subtle")}>
{event.note}
</span>
);
}
if (preview != null && preview !== "") {
return <span className="text-xs">{preview.slice(0, 1000)}</span>;
}
if (event.binary && (event.size ?? 0) > 0) {
return <em className="italic text-text-subtlest">Binary</em>;
}
return <em className="italic text-text-subtlest">No content</em>;
}
function DirectionIcon({ event }: { event: StreamEvent }) {
if (event.direction === "info") {
return event.warning ? (
<Icon color="warning" icon="alert_triangle" />
) : (
<Icon color="secondary" icon="info" />
);
}
return event.direction === "sent" ? (
<Icon color="primary" title="Client Message" icon="arrow_big_up_dash" />
) : (
<Icon color="info" title="Server Message" icon="arrow_big_down_dash" />
);
}
function EventLabel({ children, isActive }: { children: ReactNode; isActive?: boolean }) {
return (
<InlineCode className={classNames("py-0", isActive && "relative overflow-hidden")}>
{isActive && <span className="absolute inset-0 bg-text opacity-5 pointer-events-none" />}
<span className="relative">{children}</span>
</InlineCode>
);
}
const LARGE_PAYLOAD = 1000 * 1000;
/** A payload too large to show until asked to: over 1 MB, and not yet asked */
export function isLargePayload(size: number, showLarge: boolean): boolean {
return !showLarge && size > LARGE_PAYLOAD;
}
/**
* Whether a payload's text view may load: decoding, parsing and pretty-printing it. Only once its
* bytes are in, so its size is known (a compressed gRPC message's is not until then), and not
* while it is too large to show.
*/
export function shouldLoadText({
hasBytes,
tooLarge,
}: {
hasBytes: boolean;
tooLarge: boolean;
}): boolean {
return hasBytes && !tooLarge;
}
/** The text and hexdump views every payload has */
function defaultViews(bytes: Uint8Array | null): StreamPayloadView[] {
return [
{
value: "message",
label: "Message",
type: "text",
load: async () => payloadText(bytes ?? new Uint8Array()),
},
{ value: "hexdump", label: "Hexdump", type: "hexdump" },
];
}
/** A payload's text, highlighted and pretty-printed as JSON when it is JSON */
export function payloadText(bytes: Uint8Array): StreamPayloadText {
const text = new TextDecoder("utf-8").decode(bytes);
try {
const parsed: unknown = JSON.parse(text);
if (parsed != null && typeof parsed === "object") {
return { text: JSON.stringify(parsed, null, 2), language: "json" };
}
} catch {
// Not JSON
}
return { text, language: "text" };
}
interface Loaded<T> {
data: T | null;
error: string | null;
loading: boolean;
}
function useLoaded<T>(load: (() => Promise<T>) | null, key: string): Loaded<T> {
const [state, setState] = useState<Loaded<T> & { key: string }>({
key: "",
data: null,
error: null,
loading: load != null,
});
// oxlint-disable-next-line react-hooks/exhaustive-deps -- reloads by key, not by callback identity
useEffect(() => {
if (load == null) return;
let cancelled = false;
setState({ key, data: null, error: null, loading: true });
load().then(
(data) => !cancelled && setState({ key, data, error: null, loading: false }),
(e) => !cancelled && setState({ key, data: null, error: String(e), loading: false }),
);
return () => {
cancelled = true;
};
}, [key]);
return state.key === key ? state : { data: null, error: null, loading: load != null };
}
function StreamEventDetail({
event,
loadPayload,
views: extraViews,
onClose,
}: {
event: StreamEvent;
loadPayload?: (event: StreamEvent) => Promise<StreamPayload>;
views: StreamPayloadView[] | null;
onClose: () => void;
}) {
const { Editor } = useEditorHost();
const payload = useLoaded(loadPayload ? () => loadPayload(event) : null, event.key);
const bytes = payload.data?.bytes ?? null;
const views = extraViews ?? defaultViews(bytes);
const [chosen, setChosen] = useState<Record<string, string>>({});
const defaultView = event.binary && extraViews == null ? "hexdump" : views[0]?.value;
const viewValue = chosen[event.key] ?? defaultView ?? "message";
const view = views.find((v) => v.value === viewValue) ?? views[0];
const [shownLarge, setShownLarge] = useState<Record<string, boolean>>({});
const showLarge = shownLarge[event.key] === true;
const tooLarge = isLargePayload(bytes?.length ?? event.size ?? 0, showLarge);
const textLoad =
view?.type === "text" && shouldLoadText({ hasBytes: bytes != null, tooLarge })
? view.load
: null;
const text = useLoaded(
textLoad,
`${event.key}:${view?.value}:${bytes == null ? 0 : 1}:${textLoad == null ? 0 : 1}`,
);
const setView = (value: string) => setChosen((c) => ({ ...c, [event.key]: value }));
const actions: EventDetailAction[] =
views.length > 2
? [
{
type: "select",
key: "payload-view",
label: "View as",
value: view?.value ?? "",
options: views.map((v) => ({ label: v.label, value: v.value })),
onChange: setView,
},
]
: (bytes?.length ?? 0) > 0 && views.length === 2
? [
{
key: "toggle-hexdump",
label: view?.type === "hexdump" ? "Show Message" : "Show Hexdump",
onClick: () =>
setView(
(view?.type === "hexdump"
? views.find((v) => v.type === "text")
: views.find((v) => v.type === "hexdump")
)?.value ?? viewValue,
),
},
]
: [];
const title = event.title ?? (event.direction === "sent" ? "Message Sent" : "Message Received");
const copyText =
view?.type === "hexdump" ? undefined : (text.data?.text ?? undefined) || undefined;
let body: ReactNode;
if (payload.error != null) {
body = <Banner color="danger">{payload.error}</Banner>;
} else if (payload.loading) {
body = null;
} else if (
(bytes == null || bytes.length === 0) &&
(extraViews == null || view?.type !== "text")
) {
// An empty payload has nothing to show as text or bytes; a decode of one may (an empty
// protobuf message is its defaults)
body = <EmptyStateText>No Content</EmptyStateText>;
} else if (tooLarge) {
body = (
<VStack space={2} className="italic text-text-subtlest">
Message previews larger than 1MB are hidden
<div>
<Button
onClick={() => setShownLarge((s) => ({ ...s, [event.key]: true }))}
color="secondary"
variant="border"
size="xs"
>
Try Showing
</Button>
</div>
</VStack>
);
} else if (view?.type === "hexdump" && bytes != null) {
body = <HexdumpViewer data={bytes} renderEditor={(props) => <Editor {...props} />} />;
} else if (text.error != null) {
body = <Banner color="danger">{text.error}</Banner>;
} else if (text.data != null) {
body = (
<div className="h-full grid grid-rows-[auto_minmax(0,1fr)] gap-1">
{text.data.note ? (
<div className="text-xs text-text-subtle">{text.data.note}</div>
) : (
<span aria-hidden />
)}
<Editor
key={`${event.key}:${view?.value}`}
language={text.data.language}
defaultValue={text.data.text}
wrapLines={false}
readOnly
stateKey={null}
/>
</div>
);
}
return (
<div className="h-full grid grid-rows-[auto_auto_minmax(0,1fr)]">
<EventDetailHeader
title={title}
timestamp={event.timestamp ?? undefined}
actions={actions}
copyText={copyText}
onClose={onClose}
/>
{event.truncated || event.error ? (
<Banner color={event.error ? "danger" : "notice"} className="mb-2 text-sm">
{event.error ?? "The message is cut at the capture limit."}
</Banner>
) : (
<span aria-hidden />
)}
{body}
</div>
);
}
@@ -0,0 +1,331 @@
import type { Virtualizer } from "@tanstack/react-virtual";
import classNames from "classnames";
import { format } from "date-fns";
import type { ReactNode } from "react";
import { useCallback, useMemo, useRef, useState } from "react";
import { useEventViewerKeyboard } from "../../hooks/useEventViewerKeyboard";
import { Banner } from "../Banner";
import { Button } from "../Button";
import { CopyIconButton } from "../CopyIconButton";
import { useEditorHost } from "../EditorHost";
import { IconButton } from "../IconButton";
import { Select, type SelectProps } from "../Select";
import { Separator } from "../Separator";
import { SplitLayout } from "../SplitLayout";
import { HStack } from "../Stacks";
import { AutoScroller } from "./AutoScroller";
interface EventViewerProps<T> {
/** Array of events to display */
events: T[];
/** Get unique key for each event */
getEventKey: (event: T, index: number) => string;
/** Render the event row - receives event, index, isActive, and onClick */
renderRow: (props: {
event: T;
index: number;
isActive: boolean;
onClick: () => void;
}) => ReactNode;
/** Render the detail pane for the selected event */
renderDetail?: (props: { event: T; index: number; onClose: () => void }) => ReactNode;
/** Optional header above the event list (e.g., connection status) */
header?: ReactNode;
/** Error message to display as a banner */
error?: string | null;
/** Key for SplitLayout state persistence */
splitLayoutStorageKey: string;
/** Default ratio for the split (0.0 - 1.0) */
defaultRatio?: number;
/** Enable keyboard navigation (arrow keys) */
enableKeyboardNav?: boolean;
/** Loading state */
isLoading?: boolean;
/** Message to show while loading */
loadingMessage?: string;
/** Message to show when no events */
emptyMessage?: string;
/** Callback when active index changes (for controlled state in parent) */
onActiveIndexChange?: (index: number | null) => void;
/**
* Holds and catches up as the proxy's flow list does: selecting an event or scrolling up holds
* the list, and new events wait under a pill that counts them
*/
catchUp?: { label: (count: number) => string };
}
export function EventViewer<T>({
events,
getEventKey,
renderRow,
renderDetail,
header,
error,
splitLayoutStorageKey,
defaultRatio = 0.4,
enableKeyboardNav = true,
isLoading = false,
loadingMessage = "Loading events...",
emptyMessage = "No events recorded",
onActiveIndexChange,
catchUp,
}: EventViewerProps<T>) {
const [activeIndex, setActiveIndexInternal] = useState<number | null>(null);
const [isPanelOpen, setIsPanelOpen] = useState(false);
// Wrap setActiveIndex to notify parent
const setActiveIndex = useCallback(
(indexOrUpdater: number | null | ((prev: number | null) => number | null)) => {
setActiveIndexInternal((prev) => {
const newIndex =
typeof indexOrUpdater === "function" ? indexOrUpdater(prev) : indexOrUpdater;
onActiveIndexChange?.(newIndex);
return newIndex;
});
},
[onActiveIndexChange],
);
const containerRef = useRef<HTMLDivElement>(null);
const virtualizerRef = useRef<Virtualizer<HTMLDivElement, Element> | null>(null);
const activeEvent = useMemo(
() => (activeIndex != null ? events[activeIndex] : null),
[activeIndex, events],
);
// Check if the event list container is focused
const isContainerFocused = useCallback(() => {
return containerRef.current?.contains(document.activeElement) ?? false;
}, []);
// Keyboard navigation
useEventViewerKeyboard({
totalCount: events.length,
activeIndex,
setActiveIndex,
virtualizer: virtualizerRef.current,
isContainerFocused,
enabled: enableKeyboardNav,
closePanel: () => setIsPanelOpen(false),
openPanel: () => setIsPanelOpen(true),
});
// Handle virtualizer ready callback
const handleVirtualizerReady = useCallback(
(virtualizer: Virtualizer<HTMLDivElement, Element>) => {
virtualizerRef.current = virtualizer;
},
[],
);
// Handle row click - select and open panel, scroll into view
const handleRowClick = useCallback(
(index: number) => {
setActiveIndex(index);
setIsPanelOpen(true);
// Scroll to ensure selected item is visible after panel opens
requestAnimationFrame(() => {
virtualizerRef.current?.scrollToIndex(index, { align: "auto" });
});
},
[setActiveIndex],
);
const handleClose = useCallback(() => {
setIsPanelOpen(false);
}, []);
if (isLoading) {
return <div className="p-3 text-text-subtlest italic">{loadingMessage}</div>;
}
if (events.length === 0 && !error) {
return <div className="p-3 text-text-subtlest italic">{emptyMessage}</div>;
}
return (
<div ref={containerRef} className="h-full">
<SplitLayout
layout="vertical"
storageKey={splitLayoutStorageKey}
defaultRatio={defaultRatio}
minHeightPx={72}
firstSlot={({ style }) => (
<div style={style} className="w-full h-full grid grid-rows-[auto_minmax(0,1fr)]">
{header ?? <span aria-hidden />}
<AutoScroller
data={events}
focusable={enableKeyboardNav}
onVirtualizerReady={handleVirtualizerReady}
catchUp={catchUp}
holdSignal={activeIndex}
header={
error && (
<Banner color="danger" className="m-3">
{error}
</Banner>
)
}
render={(event, index) => (
<div key={getEventKey(event, index)}>
{renderRow({
event,
index,
isActive: index === activeIndex,
onClick: () => handleRowClick(index),
})}
</div>
)}
/>
</div>
)}
secondSlot={
activeEvent != null && renderDetail && isPanelOpen
? ({ style }) => (
<div style={style} className="grid grid-rows-[auto_minmax(0,1fr)] bg-surface">
<div className="pb-3 px-2">
<Separator />
</div>
<div className="mx-2 overflow-y-auto">
{renderDetail({
event: activeEvent,
index: activeIndex ?? 0,
onClose: handleClose,
})}
</div>
</div>
)
: null
}
/>
</div>
);
}
export type EventDetailAction =
| {
type?: "button";
/** Unique key for React */
key: string;
/** Button label */
label: string;
/** Optional icon */
icon?: ReactNode;
/** Click handler */
onClick: () => void;
}
| {
type: "select";
/** Unique key for React */
key: string;
/** Select label */
label: string;
/** Selected value */
value: string;
/** Select options */
options: SelectProps<string>["options"];
/** Change handler */
onChange: (value: string) => void;
};
interface EventDetailHeaderProps {
title: string;
prefix?: ReactNode;
timestamp?: string;
actions?: EventDetailAction[];
copyText?: string | (() => Promise<string | null>);
onClose?: () => void;
}
export function EventDetailHeader({
title,
prefix,
timestamp,
actions,
copyText,
onClose,
}: EventDetailHeaderProps) {
const { copy } = useEditorHost();
const formattedTime = timestamp ? format(new Date(`${timestamp}Z`), "HH:mm:ss.SSS") : null;
return (
<div className="flex items-center justify-between gap-2 mb-2 h-xs">
<HStack space={2} className="items-center min-w-0">
{prefix}
<h3 className="font-semibold select-auto cursor-auto truncate">{title}</h3>
</HStack>
<HStack space={2} className="items-center">
{actions?.map((action) =>
action.type === "select" ? (
<div key={action.key} className="w-32">
<Select
name={action.key}
label={action.label}
hideLabel
size="xs"
value={action.value}
options={action.options}
onChange={action.onChange}
/>
</div>
) : (
<Button
key={action.key}
type="button"
variant="border"
size="xs"
onClick={action.onClick}
>
{action.icon}
{action.label}
</Button>
),
)}
{copyText != null && (
<CopyIconButton
text={copyText}
copy={copy}
size="xs"
title="Copy"
variant="border"
iconSize="sm"
/>
)}
{formattedTime && (
<span className="text-text-subtlest font-mono text-editor ml-2">{formattedTime}</span>
)}
{onClose != null && (
<div
className={classNames(
copyText != null ||
formattedTime ||
((actions ?? []).length > 0 && "border-l border-l-surface-highlight ml-2 pl-3"),
)}
>
<IconButton
color="custom"
className="text-text-subtle -mr-3"
size="xs"
icon="x"
title="Close event panel"
onClick={onClose}
/>
</div>
)}
</HStack>
</div>
);
}
@@ -0,0 +1,59 @@
import classNames from "classnames";
import { format } from "date-fns";
import type { CSSProperties, ReactNode } from "react";
interface EventViewerRowProps {
isActive: boolean;
onClick: () => void;
icon: ReactNode;
content: ReactNode;
timestamp?: string;
/**
* Cells after the icon and content, as a message list's type, size and time columns. When
* given, `columns` lays out the icon, `content` and these, and `timestamp` is not drawn.
*/
cells?: { kind?: ReactNode; trailing?: ReactNode[] };
/** The grid's `grid-template-columns`, for `cells` */
columns?: string;
}
export function EventViewerRow({
isActive,
onClick,
icon,
content,
timestamp,
cells,
columns,
}: EventViewerRowProps) {
const style: CSSProperties | undefined =
cells != null && columns != null ? { gridTemplateColumns: columns } : undefined;
return (
<div className="px-1">
<button
type="button"
onClick={onClick}
style={style}
className={classNames(
"w-full grid gap-2 items-center text-left",
style == null && "grid-cols-[auto_minmax(0,1fr)_auto]",
"px-1.5 h-xs font-mono text-editor cursor-default group focus:outline-hidden focus:text-text rounded-sm",
isActive && "bg-surface-active text-text!",
"text-text-subtle hover:text",
)}
>
{icon}
{cells?.kind != null && <div className="truncate">{cells.kind}</div>}
<div className="w-full truncate">{content}</div>
{style == null
? timestamp && <div className="opacity-50">{format(`${timestamp}Z`, "HH:mm:ss.SSS")}</div>
: cells?.trailing?.map((cell, i) => (
// oxlint-disable-next-line no-array-index-key -- fixed columns, in order
<div key={i} className="truncate text-right">
{cell}
</div>
))}
</button>
</div>
);
}
@@ -0,0 +1,53 @@
import { describe, expect, test } from "vite-plus/test";
import { eventDeltas, formatEventDelta, formatEventTime } from "./streamEvents";
describe("eventDeltas", () => {
test("measures each event from the one before it", () => {
const deltas = eventDeltas([
{ timestamp: "2026-11-06T09:30:00.000" },
{ timestamp: "2026-11-06T09:30:00.012" },
{ timestamp: "2026-11-06T09:30:01.512" },
{ timestamp: "2026-11-06T09:32:05.512" },
]);
expect(deltas).toEqual([null, 12, 1500, 124_000]);
expect(deltas.map(formatEventDelta)).toEqual(["", "+12 ms", "+1.5 s", "+2m 4s"]);
});
test("skips an undated event, measuring the next from the last dated one", () => {
expect(
eventDeltas([
{ timestamp: "2026-11-06T09:30:00.000" },
{ timestamp: null },
{ timestamp: "2026-11-06T09:30:00.250" },
]),
).toEqual([null, null, 250]);
});
test("never goes negative when timestamps tie or step back", () => {
expect(
eventDeltas([
{ timestamp: "2026-11-06T09:30:00.500" },
{ timestamp: "2026-11-06T09:30:00.400" },
]),
).toEqual([null, 0]);
});
test("reads timestamps with or without a zone as UTC", () => {
expect(
eventDeltas([
{ timestamp: "2026-11-06T09:30:00.000Z" },
{ timestamp: "2026-11-06T09:30:00.100" },
]),
).toEqual([null, 100]);
});
});
describe("formatEventTime", () => {
test("shows the local time of day to the millisecond", () => {
const local = new Date(Date.UTC(2026, 10, 6, 9, 30, 0, 7));
const pad = (n: number, w = 2) => String(n).padStart(w, "0");
const expected = `${pad(local.getHours())}:${pad(local.getMinutes())}:${pad(local.getSeconds())}.007`;
expect(formatEventTime("2026-11-06T09:30:00.007")).toBe(expected);
expect(formatEventTime(null)).toBe("");
});
});
@@ -0,0 +1,90 @@
import { format } from "date-fns";
import { formatMillis } from "../tags/HttpResponseDurationTag";
/**
* What the event stream viewer draws. Each app maps its own records onto these (the client the
* events of an SSE response, the proxy a stream's stored messages), so the viewer never imports
* either app's model types.
*/
/** Which side sent it: the app, the server, or neither, as a connection's status */
export type StreamEventDirection = "sent" | "received" | "info";
export interface StreamEvent {
/** Unique within the stream, and stable as more events arrive */
key: string;
direction: StreamEventDirection;
/** What kind it is, as its type column shows it: `text`, `close`, an SSE event's name */
kind: string | null;
/** Small chips before the preview, as the client's SSE event ids */
labels?: string[];
/** When it passed, in UTC without a zone (`2026-11-06T09:30:00.123`), as the models store it */
timestamp: string | null;
/** Bytes on the wire */
size: number | null;
/** The start of the payload as text, null when it's binary or empty */
preview: string | null;
/** In place of the preview, dimmed: a close's code and reason, a call's status */
note?: string | null;
/** The detail's title, like `Connection Closed`; by direction when not given */
title?: string;
/** Its payload is binary, so the detail opens on the hexdump */
binary?: boolean;
/** Its payload was cut at the capture limit */
truncated?: boolean;
/** Why its payload could not be read */
error?: string | null;
/** Coloured as a warning, as an error or a failed status */
warning?: boolean;
}
/** A way of showing an event's payload, as its body view's switch offers them */
export type StreamPayloadView =
| {
value: string;
label: string;
/** Text, with the language it's highlighted and formatted as */
type: "text";
load: () => Promise<StreamPayloadText>;
}
| { value: string; label: string; type: "hexdump" };
export interface StreamPayloadText {
text: string;
language: "json" | "text";
/** Shown above the text, as how a gRPC message was decoded */
note?: string | null;
}
/** An event's payload */
export interface StreamPayload {
bytes: Uint8Array;
}
/** Milliseconds from each event to the one before it, null for the first or an undated one */
export function eventDeltas(events: Pick<StreamEvent, "timestamp">[]): (number | null)[] {
let previous: number | null = null;
return events.map((event) => {
const at = parseTimestamp(event.timestamp);
const delta = at == null || previous == null ? null : Math.max(0, at - previous);
if (at != null) previous = at;
return delta;
});
}
/** A delta as its column shows it: `+12 ms`, `+1.5 s` */
export function formatEventDelta(delta: number | null): string {
return delta == null ? "" : `+${formatMillis(Math.round(delta))}`;
}
/** An event's time of day, to the millisecond, in the local zone */
export function formatEventTime(timestamp: string | null): string {
const at = parseTimestamp(timestamp);
return at == null ? "" : format(at, "HH:mm:ss.SSS");
}
function parseTimestamp(timestamp: string | null): number | null {
if (timestamp == null) return null;
const at = Date.parse(/[zZ]|[+-]\d\d:?\d\d$/.test(timestamp) ? timestamp : `${timestamp}Z`);
return Number.isNaN(at) ? null : at;
}