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

@@ -1,118 +0,0 @@
import { useVirtualizer, type Virtualizer } from "@tanstack/react-virtual";
import type { ReactElement, ReactNode, UIEvent } from "react";
import { useCallback, useLayoutEffect, useRef, useState } from "react";
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;
}
export function AutoScroller<T>({
data,
render,
header,
focusable = false,
onVirtualizerReady,
}: Props<T>) {
const containerRef = useRef<HTMLDivElement>(null);
const [autoScroll, setAutoScroll] = useState<boolean>(true);
// 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]);
// 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) {
setAutoScroll(newAutoScroll);
}
},
[autoScroll],
);
// 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]);
return (
<div className="h-full w-full relative grid grid-rows-[auto_minmax(0,1fr)]">
{!autoScroll && (
<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>
)}
{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>
);
}
@@ -1,312 +1,2 @@
import type { Virtualizer } from "@tanstack/react-virtual";
import { Banner, HStack, SplitLayout } from "@yaakapp-internal/ui";
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 { CopyIconButton } from "../CopyIconButton";
import { AutoScroller } from "./AutoScroller";
import { Button } from "./Button";
import { IconButton } from "./IconButton";
import type { SelectProps } from "./Select";
import { Select } from "./Select";
import { Separator } from "./Separator";
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;
}
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,
}: 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}
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 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} 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>
);
}
export type { EventDetailAction } from "@yaakapp-internal/ui";
export { EventDetailHeader, EventViewer } from "@yaakapp-internal/ui";
@@ -1,38 +1 @@
import classNames from "classnames";
import { format } from "date-fns";
import type { ReactNode } from "react";
interface EventViewerRowProps {
isActive: boolean;
onClick: () => void;
icon: ReactNode;
content: ReactNode;
timestamp?: string;
}
export function EventViewerRow({
isActive,
onClick,
icon,
content,
timestamp,
}: EventViewerRowProps) {
return (
<div className="px-1">
<button
type="button"
onClick={onClick}
className={classNames(
"w-full grid grid-cols-[auto_minmax(0,1fr)_auto] gap-2 items-center text-left",
"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}
<div className="w-full truncate">{content}</div>
{timestamp && <div className="opacity-50">{format(`${timestamp}Z`, "HH:mm:ss.SSS")}</div>}
</button>
</div>
);
}
export { EventViewerRow } from "@yaakapp-internal/ui";
@@ -1,6 +1,15 @@
import type { HttpResponse } from "@yaakapp-internal/models";
import { extractSseValueAtPath, type ServerSentEvent } from "@yaakapp-internal/sse";
import { HStack, Icon, InlineCode, SplitLayout, VStack, IconTooltip } from "@yaakapp-internal/ui";
import {
EventStreamViewer as SharedEventStreamViewer,
HStack,
Icon,
InlineCode,
SplitLayout,
type StreamEvent,
VStack,
IconTooltip,
} from "@yaakapp-internal/ui";
import classNames from "classnames";
import type { CSSProperties, ReactNode } from "react";
import { Fragment, useMemo, useState } from "react";
@@ -20,8 +29,7 @@ import type { DropdownItem } from "../core/Dropdown";
import { Dropdown } from "../core/Dropdown";
import type { EditorProps } from "../core/Editor/Editor";
import { Editor } from "../core/Editor/LazyEditor";
import { EventDetailHeader, EventViewer } from "../core/EventViewer";
import { EventViewerRow } from "../core/EventViewerRow";
import { EventDetailHeader } from "../core/EventViewer";
import { IconButton } from "../core/IconButton";
import { Input } from "../core/Input";
import { Select } from "../core/Select";
@@ -62,6 +70,7 @@ function ActualEventStreamViewer({ response }: Props) {
});
const summarySettings = useSseSummaryResultKeyPath({ response });
const events = useResponseBodyEventSource(response);
const streamEvents = useMemo(() => (events.data ?? []).map(toStreamEvent), [events.data]);
const summary = useResponseBodySseSummary(response, summarySettings.resultKeyPath);
const showExtractedText = summarySettings.resultKeyPath != null;
const showResultKeyPathWarning =
@@ -105,10 +114,7 @@ function ActualEventStreamViewer({ response }: Props) {
),
},
],
[
applyToDetailsSetting,
filterEventPreviewsSetting,
],
[applyToDetailsSetting, filterEventPreviewsSetting],
);
return (
@@ -175,30 +181,21 @@ function ActualEventStreamViewer({ response }: Props) {
resizeHandleClassName="hover:bg-surface-highlight active:bg-surface-highlight"
firstSlot={({ style }) => (
<div style={style} className="min-h-0">
<EventViewer
events={events.data ?? []}
getEventKey={(_, index) => String(index)}
<SharedEventStreamViewer
events={streamEvents}
error={events.error ? String(events.error) : null}
splitLayoutStorageKey="sse_events"
defaultRatio={0.4}
renderRow={({ event, index, isActive, onClick }) => (
<EventViewerRow
isActive={isActive}
onClick={onClick}
icon={<Icon color="info" title="Server Message" icon="arrow_big_down_dash" />}
content={
<HStack space={2} className="items-center">
<EventLabels event={event} index={index} isActive={isActive} />
<span className="truncate text-xs">
{getEventPreview(event, summarySettings.resultKeyPath, filterEventPreviews)}
</span>
</HStack>
}
/>
)}
getPreview={(event) =>
getEventPreview(
sseEventOf(events.data, event),
summarySettings.resultKeyPath,
filterEventPreviews,
)
}
renderDetail={({ event, index, onClose }) => (
<EventDetail
event={event}
event={sseEventOf(events.data, event)}
index={index}
applyJsonPath={applyToDetails}
resultKeyPath={summarySettings.resultKeyPath}
@@ -312,6 +309,23 @@ function SseSummaryFooter({
);
}
/** An SSE event as the shared viewer lists it: received, with its id (or place) and type */
function toStreamEvent(event: ServerSentEvent, index: number): StreamEvent {
return {
key: String(index),
direction: "received",
kind: event.eventType || null,
labels: [String(event.id ?? index), ...(event.eventType ? [event.eventType] : [])],
timestamp: null,
size: null,
preview: event.data,
};
}
function sseEventOf(events: ServerSentEvent[] | undefined, event: StreamEvent): ServerSentEvent {
return events?.[Number(event.key)] ?? { data: "", eventType: "", id: null, retry: null };
}
function getEventPreview(
event: ServerSentEvent,
resultKeyPath: string | null,
@@ -1,85 +0,0 @@
import type { Virtualizer } from "@tanstack/react-virtual";
import { useCallback } from "react";
import { useKey } from "react-use";
interface UseEventViewerKeyboardProps {
totalCount: number;
activeIndex: number | null;
setActiveIndex: (index: number | null) => void;
virtualizer?: Virtualizer<HTMLDivElement, Element> | null;
isContainerFocused: () => boolean;
enabled?: boolean;
closePanel?: () => void;
openPanel?: () => void;
}
export function useEventViewerKeyboard({
totalCount,
activeIndex,
setActiveIndex,
virtualizer,
isContainerFocused,
enabled = true,
closePanel,
openPanel,
}: UseEventViewerKeyboardProps) {
const selectPrev = useCallback(() => {
if (totalCount === 0) return;
const newIndex = activeIndex == null ? 0 : Math.max(0, activeIndex - 1);
setActiveIndex(newIndex);
virtualizer?.scrollToIndex(newIndex, { align: "auto" });
}, [activeIndex, setActiveIndex, totalCount, virtualizer]);
const selectNext = useCallback(() => {
if (totalCount === 0) return;
const newIndex = activeIndex == null ? 0 : Math.min(totalCount - 1, activeIndex + 1);
setActiveIndex(newIndex);
virtualizer?.scrollToIndex(newIndex, { align: "auto" });
}, [activeIndex, setActiveIndex, totalCount, virtualizer]);
useKey(
(e) => e.key === "ArrowUp" || e.key === "k",
(e) => {
if (!enabled || !isContainerFocused()) return;
e.preventDefault();
selectPrev();
},
undefined,
[enabled, isContainerFocused, selectPrev],
);
useKey(
(e) => e.key === "ArrowDown" || e.key === "j",
(e) => {
if (!enabled || !isContainerFocused()) return;
e.preventDefault();
selectNext();
},
undefined,
[enabled, isContainerFocused, selectNext],
);
useKey(
(e) => e.key === "Escape",
(e) => {
if (!enabled || !isContainerFocused()) return;
e.preventDefault();
closePanel?.();
},
undefined,
[enabled, isContainerFocused, closePanel],
);
useKey(
(e) => e.key === "Enter" || e.key === " ",
(e) => {
if (!enabled || !isContainerFocused() || activeIndex == null) return;
e.preventDefault();
openPanel?.();
},
undefined,
[enabled, isContainerFocused, activeIndex, openPanel],
);
}
@@ -1,4 +1,9 @@
import { afterEach, beforeEach, describe, expect, test, vi } from "vite-plus/test";
// Loaded once as the file is collected (the mocks below are hoisted above it), so the first
// transform of its module graph, the shared UI package among it, is not timed against whichever
// test imports it first. Each test still gets the module fresh after `vi.resetModules()`, which
// reuses that transform.
import "./useSendAnyHttpRequest";
const mocks = vi.hoisted(() => ({
platform: { httpProxyUrl: "https://web.yaak.test" as string | null },
@@ -1,6 +1,11 @@
import { renderToStaticMarkup } from "react-dom/server";
import { afterEach, beforeEach, describe, expect, test, vi } from "vite-plus/test";
import type { DialogInstance } from "../components/Dialogs";
// Loaded once as the file is collected (the mocks below are hoisted above it), so the first
// transform of its module graph, the shared UI package among it, is not timed against whichever
// test imports it first. Each test still gets the module fresh after `vi.resetModules()`, which
// reuses that transform.
import "./confirmWebProxy";
const mocks = vi.hoisted(() => ({
platform: { httpProxyUrl: "https://web.yaak.app" },
@@ -23,6 +23,7 @@ import {
bodyImageType,
filterText,
findHeader,
emptyBodyText,
flowBodyQueryOptions,
formatText,
mimeEssence,
@@ -53,9 +54,9 @@ export function FlowBodyViewer({ flow, which, pretty }: Props) {
return <Banner color="danger">{body.error.message}</Banner>;
}
const { bytes, truncated, storedSize, decodeError } = body.data;
const { bytes, truncated, storedSize, decodeError, note } = body.data;
if (bytes.length === 0 && decodeError == null) {
return <EmptyState>{which === "request" ? "No request body" : "Empty"}</EmptyState>;
return <EmptyState>{emptyBodyText(which, note)}</EmptyState>;
}
const headers = which === "request" ? flow.requestHeaders : flow.responseHeaders;
+25
View File
@@ -11,6 +11,7 @@ import {
HttpStatusTagRaw,
Icon,
IconButton,
LoadingIcon,
SizeTag,
type TabButtonRenderProps,
type TabItem,
@@ -25,13 +26,16 @@ import { selectedFlowAtom } from "../lib/atoms";
import { findHeader, mimeEssence } from "../lib/body";
import { saveDialogFlowAtom, useFlowActions } from "../lib/flowActions";
import { statusReason } from "../lib/statusReason";
import { messagesTabLabel, streamIsOpen } from "../lib/messages";
import { EmptyState, FlowBodyViewer, useFlowBody } from "./FlowBodyViewer";
import { FlowHeaders, FlowQuery, queryParams } from "./FlowHeaders";
import { FlowMessages } from "./FlowMessages";
const TAB_RESPONSE = "response";
const TAB_REQUEST = "request";
const TAB_HEADERS = "headers";
const TAB_QUERY = "query";
const TAB_MESSAGES = "messages";
export function FlowDetail({ style, sideBySide }: { style?: CSSProperties; sideBySide: boolean }) {
const flow = useAtomValue(selectedFlowAtom);
@@ -75,9 +79,19 @@ function FlowPane({ flow }: { flow: Flow }) {
const queryCount = useMemo(() => queryParams(flow.url).length, [flow.url]);
const openSave = useSetAtom(saveDialogFlowAtom);
const flowActions = useFlowActions();
const messagesLabel = messagesTabLabel(flow);
const tabs = useMemo<TabItem[]>(
() => [
...(messagesLabel == null
? []
: [
{
value: TAB_MESSAGES,
label: messagesLabel,
rightSlot: <CountBadge count={flow.messageCount} color="info" showZero />,
},
]),
{
value: TAB_RESPONSE,
renderButton: ({ buttonProps, isActive }) => (
@@ -114,6 +128,8 @@ function FlowPane({ flow }: { flow: Flow }) {
},
],
[
messagesLabel,
flow.messageCount,
pretty,
mime,
flow.requestSize,
@@ -133,6 +149,7 @@ function FlowPane({ flow }: { flow: Flow }) {
)}
>
<HStack space={2} className="w-full shrink-0">
{streamIsOpen(flow) && <LoadingIcon size="sm" />}
{flow.cancelled && flow.status == null ? (
<span>Cancelled</span>
) : (
@@ -209,6 +226,9 @@ function FlowPane({ flow }: { flow: Flow }) {
</Banner>
)}
<Tabs
// A stream opens on its messages; moving between streams keeps the tab chosen
key={flow.streamKind == null ? "http" : "stream"}
defaultValue={messagesLabel == null ? undefined : TAB_MESSAGES}
tabs={tabs}
label="Flow"
className="ml-3 mr-3 mb-3 min-h-0 flex-1"
@@ -240,6 +260,11 @@ function FlowPane({ flow }: { flow: Flow }) {
<TabContent value={TAB_QUERY}>
<FlowQuery flow={flow} />
</TabContent>
{messagesLabel != null && (
<TabContent value={TAB_MESSAGES}>
<FlowMessages flow={flow} />
</TabContent>
)}
</Tabs>
</div>
</div>
+131
View File
@@ -0,0 +1,131 @@
import type { Flow } from "@yaakapp-internal/proxy-lib";
import {
type EventStreamColumns,
EventStreamViewer,
HStack,
type StreamEvent,
type StreamPayloadView,
} from "@yaakapp-internal/ui";
import { useCallback, useMemo } from "react";
import { useFlowMessages, useMessageSource } from "../hooks/useFlowMessages";
import { base64ToBytes } from "../lib/body";
import { grpcStatusText, messageToStreamEvent, streamIsOpen } from "../lib/messages";
const WEBSOCKET_COLUMNS: EventStreamColumns = {
direction: true,
kind: "Type",
preview: "Message",
size: true,
time: true,
};
const SSE_COLUMNS: EventStreamColumns = {
kind: "Event",
kindWidth: "9.5rem",
preview: "Data",
size: true,
time: true,
};
const GRPC_COLUMNS: EventStreamColumns = {
direction: true,
kind: "Type",
preview: "Message",
size: true,
time: true,
};
/**
* A streaming flow's messages: a WebSocket's frames, an event stream's events, a gRPC call's
* messages and status, following new ones while the stream is open. The selected message's
* payload opens below as text or a hexdump; a gRPC message's also decoded, with its schema or
* without one.
*/
export function FlowMessages({ flow }: { flow: Flow }) {
const source = useMessageSource();
const { messages, loading, error } = useFlowMessages(flow.id, source, flow.messageCount);
const events = useMemo(() => messages.map(messageToStreamEvent), [messages]);
const kind = flow.streamKind;
const grpc = kind === "grpc" || kind === "grpc_web";
const columns = kind === "sse" ? SSE_COLUMNS : grpc ? GRPC_COLUMNS : WEBSOCKET_COLUMNS;
const noun = kind === "sse" ? "Event" : "Message";
const catchUp = useMemo(
() => ({
label: (count: number) => `${count} new ${noun.toLowerCase()}${count === 1 ? "" : "s"}`,
}),
[noun],
);
const loadPayload = useCallback(
async (event: StreamEvent) => {
const res = await source.payload(flow.id, Number(event.key));
return { bytes: base64ToBytes(res.data) };
},
[flow.id, source],
);
const payloadViews = useCallback(
(event: StreamEvent): StreamPayloadView[] | null => {
if (!grpc || event.direction === "info") return null;
const decode = (schemaless: boolean) => async () => {
const decoded = await source.decodeGrpc(flow.id, Number(event.key), schemaless);
const note = [
decoded.messageType == null ? null : `Decoded as ${decoded.messageType}`,
decoded.note,
]
.filter(Boolean)
.join(". ");
return { text: decoded.json, language: "json" as const, note: note || null };
};
return [
{ value: "decoded", label: "Decoded", type: "text", load: decode(false) },
{ value: "schemaless", label: "Schemaless", type: "text", load: decode(true) },
{ value: "raw", label: "Raw bytes", type: "hexdump" },
];
},
[flow.id, grpc, source],
);
const open = streamIsOpen(flow);
const count = Math.max(flow.messageCount, messages.length);
const header = (
<HStack space={2} className="pl-2 mb-1 h-xs font-mono text-xs text-text-subtle">
{kind === "websocket" && (
<>
{open ? (
<span className="text-success">CONNECTED</span>
) : flow.error != null ? (
<span className="text-danger">ERROR</span>
) : (
<span className="text-text-subtle">CLOSED</span>
)}
<span>&bull;</span>
</>
)}
<span>
{count} {count === 1 ? noun : `${noun}s`}
</span>
{grpc && flow.grpcStatus != null && (
<>
<span>&bull;</span>
<span className={flow.grpcStatus === 0 ? "text-success" : "text-danger"}>
{grpcStatusText(flow.grpcStatus, flow.grpcMessage)}
</span>
</>
)}
</HStack>
);
return (
<EventStreamViewer
events={events}
header={header}
error={error ?? (open ? null : flow.error)}
isLoading={loading && events.length === 0}
emptyMessage={open ? `Waiting for the first ${noun.toLowerCase()}` : `No ${noun}s`}
splitLayoutStorageKey="proxy_flow_messages"
columns={columns}
loadPayload={loadPayload}
payloadViews={payloadViews}
catchUp={catchUp}
/>
);
}
@@ -0,0 +1,80 @@
import type { Flow } from "@yaakapp-internal/proxy-lib";
import { useSetAtom } from "jotai";
import { useLayoutEffect, useMemo, useState } from "react";
import { FlowDetail } from "../components/FlowDetail";
import { FlowList } from "../components/FlowList";
import { ProxyEditorHost } from "../components/ProxyEditorHost";
import { MessageSourceContext } from "../hooks/useFlowMessages";
import { selectedFlowAtom } from "../lib/atoms";
import { flowWindowAtom } from "../lib/store";
import { fixtureSource, type StreamFixture, streamFixtures } from "./streamFixtures";
/**
* Dev only: a streaming flow's detail, opened on its Messages tab, over fixtures served the way
* the engine serves them. Open `/harness.html?stream=0&theme=dark`; add `&list` for the flow list
* beside it, holding every fixture's flow.
*/
export function MessagesHarness() {
const params = new URLSearchParams(location.search);
const [index, setIndex] = useState(Number(params.get("stream") ?? 0));
const fixture = streamFixtures[index] ?? streamFixtures[0];
if (fixture == null) return null;
return (
<ProxyEditorHost>
<div className="h-full w-full grid grid-rows-[auto_minmax(0,1fr)] gap-2 p-2 bg-surface">
<div className="flex gap-2 text-sm">
{streamFixtures.map((f, i) => (
<button
key={f.flow.id}
type="button"
className={i === index ? "text-text" : "text-text-subtle"}
onClick={() => setIndex(i)}
>
{f.label}
</button>
))}
</div>
<StreamDetail key={fixture.flow.id} fixture={fixture} />
</div>
</ProxyEditorHost>
);
}
/** Each fixture's flow as the list holds it, one after another, the shown one as it is now */
function listedFlows(shown: Flow): Flow[] {
return streamFixtures.map((f, i) => {
const flow = f.flow.id === shown.id ? shown : f.flow;
return { ...flow, number: 1410 + i, startedAt: `2026-11-05T21:41:1${i}.000` };
});
}
function StreamDetail({ fixture }: { fixture: StreamFixture }) {
const source = useMemo(() => fixtureSource(fixture), [fixture]);
const setSelected = useSetAtom(selectedFlowAtom);
const setWindow = useSetAtom(flowWindowAtom);
const [flow, setFlow] = useState(fixture.flow);
const withList = new URLSearchParams(location.search).has("list");
useLayoutEffect(() => {
const flows = listedFlows(flow);
setWindow({ flows, hasOlder: false, total: flows.length });
setSelected(flows.find((f) => f.id === flow.id) ?? flow);
}, [flow, setSelected, setWindow]);
// The count on the flow follows its messages, as the engine writes it
useLayoutEffect(
() => source.subscribe(() => setFlow((f) => ({ ...f, messageCount: f.messageCount + 1 }))),
[source],
);
return (
<MessageSourceContext.Provider value={source}>
{withList ? (
<div className="h-full min-h-0 grid grid-cols-[minmax(0,0.9fr)_minmax(0,1.1fr)]">
<FlowList className="min-h-0" />
<FlowDetail sideBySide />
</div>
) : (
<FlowDetail sideBySide={false} />
)}
</MessageSourceContext.Provider>
);
}
+4 -2
View File
@@ -4,16 +4,18 @@ import { createStore, Provider } from "jotai";
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { FlowPanesHarness } from "./FlowPanesHarness";
import { MessagesHarness } from "./MessagesHarness";
import "../main.css";
const dark = new URLSearchParams(location.search).get("theme") !== "light";
const params = new URLSearchParams(location.search);
const dark = params.get("theme") !== "light";
applyThemeToDocument(dark ? defaultDarkTheme : defaultLightTheme);
createRoot(document.getElementById("root") as HTMLElement).render(
<StrictMode>
<QueryClientProvider client={new QueryClient()}>
<Provider store={createStore()}>
<FlowPanesHarness />
{params.has("stream") ? <MessagesHarness /> : <FlowPanesHarness />}
</Provider>
</QueryClientProvider>
</StrictMode>,
+372
View File
@@ -0,0 +1,372 @@
import type { DecodedGrpcMessage, Flow, FlowMessage } from "@yaakapp-internal/proxy-lib";
import type { MessageSource } from "../hooks/useFlowMessages";
/** A streaming flow with its messages and their payloads, for the Messages tab */
export interface StreamFixture {
label: string;
flow: Flow;
messages: FlowMessage[];
payloads: Uint8Array[];
/** Messages still to come while the harness runs, one at a time */
later?: { message: FlowMessage; payload: Uint8Array }[];
decoded?: Record<number, { decoded: DecodedGrpcMessage; schemaless: DecodedGrpcMessage }>;
}
const encode = (s: string) => new TextEncoder().encode(s);
const flowBase: Flow = {
id: "fl_stream",
number: 1410,
createdAt: "2026-11-05T21:41:12",
updatedAt: "2026-11-05T21:41:20",
startedAt: "2026-11-05T21:41:12.100",
method: "GET",
url: "https://gateway.discord.gg/?v=10&encoding=json",
clientHttpVersion: "HTTP/1.1",
upstreamHttpVersion: "HTTP/1.1",
remoteAddr: "162.159.135.234:443",
status: 101,
contentType: null,
requestHeaders: [{ name: "Upgrade", value: "websocket" }],
responseHeaders: [{ name: "Upgrade", value: "websocket" }],
requestSize: 0,
responseSize: 0,
requestTruncated: false,
responseTruncated: false,
elapsedHeadersMs: 88,
elapsedMs: 128_400,
error: null,
cancelled: false,
savedRequestId: null,
clientPid: 812,
clientName: "Discord",
clientBundleId: "com.hnc.Discord",
clientPath: "/Applications/Discord.app",
clientCwd: null,
streamKind: "websocket",
messageCount: 0,
grpcService: null,
grpcMethod: null,
grpcStatus: null,
grpcMessage: null,
};
/** Seconds past 21:41:12 as a stored timestamp */
function at(seconds: number): string {
const ms = Math.round(seconds * 1000);
const s = 12 + Math.floor(ms / 1000);
const m = 41 + Math.floor(s / 60);
const pad = (n: number, w = 2) => String(n).padStart(w, "0");
return `2026-11-05T21:${pad(m)}:${pad(s % 60)}.${pad(ms % 1000, 3)}`;
}
function build(
flowId: string,
rows: [number, FlowMessage["direction"], FlowMessage["kind"], Uint8Array, FlowMessage["meta"]?][],
): { messages: FlowMessage[]; payloads: Uint8Array[] } {
const messages = rows.map(([seconds, direction, kind, payload, meta], seq) => {
const text = new TextDecoder().decode(payload);
const binary = kind === "websocket_binary" || kind === "grpc_message";
return {
id: `fm_${flowId}_${seq}`,
flowId,
seq,
direction,
kind,
timestamp: at(seconds),
size: kind === "sse_event" ? (meta?.raw?.length ?? payload.length) : payload.length,
storedSize: payload.length,
truncated: false,
compressed: false,
error: null,
meta: meta ?? {},
preview:
binary || kind === "grpc_trailers"
? null
: kind === "websocket_close"
? (meta?.closeReason ?? null)
: text.slice(0, 200) || null,
} satisfies FlowMessage;
});
return { messages, payloads: rows.map((r) => r[3]) };
}
const json = (v: unknown) => encode(JSON.stringify(v));
const ws = build("fl_ws", [
[0.09, "server", "websocket_text", json({ op: 10, d: { heartbeat_interval: 41250 } })],
[0.11, "client", "websocket_text", json({ op: 2, d: { token: "mfa.••••", intents: 3276799 } })],
[
0.41,
"server",
"websocket_text",
json({ t: "READY", s: 1, op: 0, d: { v: 10, session_id: "5f1c…" } }),
],
[
1.02,
"server",
"websocket_binary",
Uint8Array.from([0x78, 0x9c, 0xab, 0x56, 0xca, 0x2f, 0x50, 0xb2, 0x32, 0xd4, 0x51, 0x02, 0x00]),
],
[41.25, "client", "websocket_text", json({ op: 1, d: 1 })],
[41.31, "server", "websocket_text", json({ op: 11 })],
[
43.3,
"server",
"websocket_text",
json({
t: "MESSAGE_CREATE",
s: 5,
op: 0,
d: { content: "shipping the proxy beta tonight?", author: { username: "mara" } },
}),
],
[60.0, "server", "websocket_ping", new Uint8Array()],
[60.0, "client", "websocket_pong", new Uint8Array()],
[82.5, "client", "websocket_text", json({ op: 1, d: 5 })],
[82.56, "server", "websocket_text", json({ op: 11 })],
[
128.3,
"client",
"websocket_close",
Uint8Array.from([0x03, 0xe8, 0x62, 0x79, 0x65]),
{ closeCode: 1000, closeReason: "bye" },
],
[128.4, "server", "websocket_close", Uint8Array.from([0x03, 0xe8]), { closeCode: 1000 }],
]);
const sseEvents: [string, unknown][] = [
[
"message_start",
{
type: "message_start",
message: { id: "msg_01HqX", model: "claude-opus-5-5", usage: { input_tokens: 18204 } },
},
],
[
"content_block_start",
{ type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
],
["ping", { type: "ping" }],
[
"content_block_delta",
{
type: "content_block_delta",
index: 0,
delta: { type: "text_delta", text: "The 402 comes from" },
},
],
[
"content_block_delta",
{
type: "content_block_delta",
index: 0,
delta: { type: "text_delta", text: " Stripe: the card on" },
},
],
[
"content_block_delta",
{
type: "content_block_delta",
index: 0,
delta: { type: "text_delta", text: " file was declined with" },
},
],
[
"content_block_delta",
{
type: "content_block_delta",
index: 0,
delta: { type: "text_delta", text: " insufficient_funds." },
},
],
["content_block_stop", { type: "content_block_stop", index: 0 }],
[
"message_delta",
{ type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 312 } },
],
["message_stop", { type: "message_stop" }],
];
function sse(flowId: string, count: number) {
return build(
flowId,
sseEvents.slice(0, count).map(([event, data], i) => {
const payload = json(data);
const raw = `event: ${event}\ndata: ${new TextDecoder().decode(payload)}\n\n`;
return [0.8 + i * (i < 3 ? 0.05 : 0.18), "server", "sse_event", payload, { event, raw }];
}),
);
}
const sseFlow: Flow = {
...flowBase,
method: "POST",
url: "https://api.anthropic.com/v1/messages",
clientHttpVersion: "HTTP/2",
upstreamHttpVersion: "HTTP/2",
status: 200,
contentType: "text/event-stream; charset=utf-8",
responseHeaders: [{ name: "content-type", value: "text/event-stream; charset=utf-8" }],
clientName: "claude",
clientBundleId: null,
clientPath: "/opt/homebrew/bin/claude",
streamKind: "sse",
elapsedMs: 2_610,
};
const sseDone = sse("fl_sse_done", sseEvents.length);
const sseOpen = sse("fl_sse_open", sseEvents.length);
// A string in field 1, as a server-streaming call's replies
function proto(text: string, n?: number): Uint8Array {
const bytes = encode(text);
const out = [0x0a, bytes.length, ...bytes];
if (n != null) out.push(0x10, n);
return Uint8Array.from(out);
}
const grpcReplies = ["us-east-1a ok", "us-east-1b ok", "us-east-1c degraded", "eu-west-1a ok"];
const grpc = build("fl_grpc", [
[0.02, "client", "grpc_message", proto("prod")],
...grpcReplies.map(
(r, i) =>
[0.31 + i * 0.42, "server", "grpc_message", proto(r, i + 1)] as [
number,
"server",
"grpc_message",
Uint8Array,
],
),
[2.1, "server", "grpc_trailers", encode("grpc-status: 0\r\n"), { grpcStatus: 0 }],
]);
const schema = {
id: "gs_1",
createdAt: "2026-11-05T20:00:00",
updatedAt: "2026-11-05T20:00:00",
hostPattern: "health.internal",
source: "reflection" as const,
protoPaths: [],
services: ["ops.Health"],
};
const grpcDecoded: StreamFixture["decoded"] = Object.fromEntries(
[["prod"], ...grpcReplies.map((r, i) => [r, i + 1])].map(([text, n], seq) => [
seq,
{
decoded: {
json: JSON.stringify(
seq === 0
? { environment: text }
: { zone: String(text).split(" ")[0], state: String(text).split(" ")[1], sequence: n },
null,
2,
),
messageType: seq === 0 ? "ops.WatchRequest" : "ops.ZoneHealth",
schema,
note: null,
},
schemaless: {
json: JSON.stringify(
[
{ field: 1, wireType: "len", string: text },
...(n == null ? [] : [{ field: 2, wireType: "varint", value: n }]),
],
null,
2,
),
messageType: null,
schema: null,
note: "Decoded without a schema: field names and types are guesses",
},
},
]),
);
export const streamFixtures: StreamFixture[] = [
{
label: "WebSocket",
flow: { ...flowBase, id: "fl_ws", messageCount: ws.messages.length },
...ws,
},
{
label: "SSE, open",
flow: { ...sseFlow, id: "fl_sse_open", elapsedMs: null, messageCount: 6 },
messages: sseOpen.messages.slice(0, 6),
payloads: sseOpen.payloads,
later: sseOpen.messages.slice(6).map((message) => ({
message,
payload: sseOpen.payloads[message.seq] ?? new Uint8Array(),
})),
},
{
label: "SSE, done",
flow: { ...sseFlow, id: "fl_sse_done", messageCount: sseDone.messages.length },
...sseDone,
},
{
label: "gRPC stream",
flow: {
...flowBase,
id: "fl_grpc",
method: "POST",
url: "https://health.internal/ops.Health/Watch",
clientHttpVersion: "HTTP/2",
upstreamHttpVersion: "HTTP/2",
status: 200,
contentType: "application/grpc",
responseHeaders: [{ name: "content-type", value: "application/grpc" }],
clientName: "grpcurl",
clientPath: "/opt/homebrew/bin/grpcurl",
streamKind: "grpc",
grpcService: "ops.Health",
grpcMethod: "Watch",
grpcStatus: 0,
elapsedMs: 2_100,
messageCount: grpc.messages.length,
},
...grpc,
decoded: grpcDecoded,
},
];
function base64(bytes: Uint8Array): string {
let binary = "";
for (const b of bytes) binary += String.fromCharCode(b);
return btoa(binary);
}
/** The fixture's messages as the engine would serve them, the later ones arriving every 900 ms */
export function fixtureSource(fixture: StreamFixture): MessageSource {
const messages = [...fixture.messages];
const listeners = new Set<(m: FlowMessage) => void>();
const later = [...(fixture.later ?? [])];
if (later.length > 0) {
const timer = setInterval(() => {
const next = later.shift();
if (next == null) return clearInterval(timer);
messages.push(next.message);
for (const l of listeners) l(next.message);
}, 900);
}
return {
list: async (_flowId, afterSeq, limit) => {
const after = messages.filter((m) => afterSeq == null || m.seq > afterSeq);
return { messages: after.slice(0, limit), total: messages.length };
},
subscribe: (callback) => {
listeners.add(callback);
return () => listeners.delete(callback);
},
payload: async (_flowId, seq) => ({
data: base64(fixture.payloads[seq] ?? new Uint8Array()),
truncated: false,
}),
decodeGrpc: async (_flowId, seq, schemaless) => {
const entry = fixture.decoded?.[seq];
if (entry == null) throw new Error(`Message ${seq} is not a gRPC message`);
return schemaless ? entry.schemaless : entry.decoded;
},
};
}
+140
View File
@@ -0,0 +1,140 @@
import type {
DecodedGrpcMessage,
FlowMessage,
GetMessagePayloadResponse,
ListMessagesResponse,
} from "@yaakapp-internal/proxy-lib";
import { createContext, useContext, useEffect, useRef, useState } from "react";
import { mergeMessages } from "../lib/messages";
import { listen, rpc } from "../lib/rpc";
/** Where a flow's messages come from: the engine, or fixtures in the harness */
export interface MessageSource {
list: (
flowId: string,
afterSeq: number | undefined,
limit: number,
) => Promise<ListMessagesResponse>;
/** Calls back with each message as it is written. Returns an unsubscribe function */
subscribe: (callback: (message: FlowMessage) => void) => () => void;
payload: (flowId: string, seq: number) => Promise<GetMessagePayloadResponse>;
decodeGrpc: (flowId: string, seq: number, schemaless: boolean) => Promise<DecodedGrpcMessage>;
}
export const engineMessageSource: MessageSource = {
list: (flowId, afterSeq, limit) => rpc("list_messages", { flowId, afterSeq, limit }),
subscribe: (callback) => listen("message_write", ({ message }) => callback(message)),
payload: (flowId, seq) => rpc("get_message_payload", { flowId, seq }),
decodeGrpc: (flowId, seq, schemaless) => rpc("decode_grpc_message", { flowId, seq, schemaless }),
};
/** Where the Messages tab reads from: the engine, unless the harness provides fixtures */
export const MessageSourceContext = createContext<MessageSource>(engineMessageSource);
export function useMessageSource(): MessageSource {
return useContext(MessageSourceContext);
}
/** Messages read in one call at most, while catching up */
const PAGE = 500;
interface State {
flowId: string;
messages: FlowMessage[];
loading: boolean;
error: string | null;
}
/**
* A flow's messages, kept up to date while it streams: read in pages after the last one held,
* and added as each is written. A message that does not follow on from the last one held (one
* written while a page loaded) reads the pages after it instead.
*/
export function useFlowMessages(flowId: string, source: MessageSource, messageCount: number) {
// Reads what's after the last message held, for a count that says there's more
const readMore = useRef<(() => void) | null>(null);
const [state, setState] = useState<State>({
flowId,
messages: [],
loading: true,
error: null,
});
useEffect(() => {
let cancelled = false;
let messages: FlowMessage[] = [];
let reading = false;
let readAgain = false;
let frame: number | null = null;
const publish = (loading: boolean, error: string | null = null) => {
if (cancelled) return;
if (frame != null) cancelAnimationFrame(frame);
frame = null;
setState({ flowId, messages, loading, error });
};
// A chatty stream is drawn at most once a frame
const publishSoon = () => {
if (frame != null || cancelled) return;
frame = requestAnimationFrame(() => {
frame = null;
if (!cancelled) setState({ flowId, messages, loading: false, error: null });
});
};
const readAfter = async () => {
if (reading) {
readAgain = true;
return;
}
reading = true;
try {
for (;;) {
readAgain = false;
const last = messages[messages.length - 1];
const page = await source.list(flowId, last?.seq, PAGE);
if (cancelled) return;
messages = mergeMessages(messages, page.messages);
// Shown as each page lands, so a stream that never pauses still shows what's read
if (page.messages.length < PAGE && !readAgain) break;
publishSoon();
}
publish(false);
} catch (e) {
publish(false, String(e));
} finally {
reading = false;
}
};
setState({ flowId, messages: [], loading: true, error: null });
readMore.current = () => void readAfter();
void readAfter();
const unsubscribe = source.subscribe((message) => {
if (message.flowId !== flowId) return;
const last = messages[messages.length - 1];
const next = last == null ? 0 : last.seq + 1;
if (!reading && message.seq === next) {
messages = [...messages, message];
publishSoon();
} else if (last == null || message.seq > last.seq) {
void readAfter();
}
});
return () => {
cancelled = true;
if (frame != null) cancelAnimationFrame(frame);
unsubscribe();
};
}, [flowId, source]);
// A message written before the subscription took hold is in neither the first page nor its
// events; the flow's count, written after its messages, says it's there to read.
const held = state.flowId === flowId ? state.messages.length : 0;
useEffect(() => {
if (messageCount > held) readMore.current?.();
}, [held, messageCount]);
// Another flow's, until the effect has started over for this one
return state.flowId === flowId ? state : { flowId, messages: [], loading: true, error: null };
}
+18
View File
@@ -6,7 +6,9 @@ import {
bodyFileName,
bodyImageType,
bytesToText,
emptyBodyText,
flowBodyQueryOptions,
viewerBody,
viewerText,
} from "./body";
import { rpc } from "./rpc";
@@ -225,3 +227,19 @@ describe("flowBodyQueryOptions", () => {
client.clear();
});
});
describe("a body that isn't there", () => {
test("a WebSocket's note reaches the viewer, which points at its messages", () => {
const note = "A WebSocket has no body after its 101 response. Its frames are its messages.";
const body = viewerBody({ data: "", truncated: false, storedSize: 0, note });
expect(body.note).toBe(note);
expect(emptyBodyText("response", body.note)).toBe("No body. See Messages.");
});
test("any other empty body says so as before", () => {
const body = viewerBody({ data: "", truncated: false, storedSize: 0 });
expect(body.note).toBeNull();
expect(emptyBodyText("response", body.note)).toBe("Empty");
expect(emptyBodyText("request", body.note)).toBe("No request body");
});
});
+25 -10
View File
@@ -4,7 +4,12 @@ import {
decodeBodyText,
strictUtf8Text,
} from "@yaakapp-internal/lib/decodeBodyText";
import type { FilterLanguage, Flow, FlowBody } from "@yaakapp-internal/proxy-lib";
import type {
FilterLanguage,
Flow,
FlowBody,
GetFlowBodyResponse,
} from "@yaakapp-internal/proxy-lib";
import type { CodeEditorProps } from "@yaakapp-internal/ui/editor";
import vkBeautify from "vkbeautify";
import { rpc } from "./rpc";
@@ -13,20 +18,30 @@ import { rpc } from "./rpc";
export function flowBodyQueryOptions(flow: Flow, which: FlowBody) {
return queryOptions({
queryKey: ["get_flow_body", flow.id, which, flow.updatedAt],
queryFn: async () => {
const res = await rpc("get_flow_body", { flowId: flow.id, which });
return {
bytes: base64ToBytes(res.data),
truncated: res.truncated,
storedSize: res.storedSize,
decodeError: res.decodeError ?? null,
};
},
queryFn: async () => viewerBody(await rpc("get_flow_body", { flowId: flow.id, which })),
// Reading a stored body fails the same way every time, so the error shows at once.
retry: false,
});
}
/** The body RPC's answer as the viewer reads it, with what to know of it beyond its bytes */
export function viewerBody(res: GetFlowBodyResponse) {
return {
bytes: base64ToBytes(res.data),
truncated: res.truncated,
storedSize: res.storedSize,
decodeError: res.decodeError ?? null,
/** Why there is no body, as a WebSocket has none after its 101 */
note: res.note ?? null,
};
}
/** What an empty body's pane says: a WebSocket's points at its messages */
export function emptyBodyText(which: FlowBody, note: string | null): string {
if (note != null) return "No body. See Messages.";
return which === "request" ? "No request body" : "Empty";
}
export function base64ToBytes(data: string): Uint8Array<ArrayBuffer> {
const binary = atob(data);
const bytes = new Uint8Array(binary.length);
+118
View File
@@ -0,0 +1,118 @@
import type { FlowMessage } from "@yaakapp-internal/proxy-lib";
import { describe, expect, test } from "vite-plus/test";
import {
closeText,
grpcStatusText,
mergeMessages,
messagesTabLabel,
messageToStreamEvent,
streamIsOpen,
} from "./messages";
function message(seq: number, patch: Partial<FlowMessage> = {}): FlowMessage {
return {
id: `fm_${seq}`,
flowId: "fl_1",
seq,
direction: "server",
kind: "websocket_text",
timestamp: "2026-11-06T09:30:00.000",
size: 5,
storedSize: 5,
truncated: false,
compressed: false,
error: null,
meta: {},
preview: "hello",
...patch,
};
}
describe("mergeMessages", () => {
test("appends what follows on", () => {
const merged = mergeMessages([message(0), message(1)], [message(2), message(3)]);
expect(merged.map((m) => m.seq)).toEqual([0, 1, 2, 3]);
});
test("drops repeats and keeps order when a page overlaps live messages", () => {
const merged = mergeMessages([message(0), message(2)], [message(1), message(2), message(3)]);
expect(merged.map((m) => m.seq)).toEqual([0, 1, 2, 3]);
});
test("keeps the same array when nothing came", () => {
const existing = [message(0)];
expect(mergeMessages(existing, [])).toBe(existing);
});
});
describe("messageToStreamEvent", () => {
test("a WebSocket frame keeps its direction, type, size and time", () => {
expect(messageToStreamEvent(message(4, { direction: "client" }))).toMatchObject({
key: "4",
direction: "sent",
kind: "text",
size: 5,
timestamp: "2026-11-06T09:30:00.000",
preview: "hello",
binary: false,
});
expect(messageToStreamEvent(message(5, { kind: "websocket_binary" })).binary).toBe(true);
});
test("a close says its code and reason, and warns when it wasn't a normal close", () => {
const normal = messageToStreamEvent(
message(6, { kind: "websocket_close", meta: { closeCode: 1000, closeReason: "bye" } }),
);
expect([normal.kind, normal.note, normal.warning]).toEqual(["close", "1000 bye", false]);
const abnormal = messageToStreamEvent(
message(7, { kind: "websocket_close", meta: { closeCode: 1011 } }),
);
expect([abnormal.note, abnormal.warning]).toEqual(["1011", true]);
});
test("an event is named by its event field, or message", () => {
const named = messageToStreamEvent(message(0, { kind: "sse_event", meta: { event: "tick" } }));
expect(named.kind).toBe("tick");
expect(messageToStreamEvent(message(1, { kind: "sse_event" })).kind).toBe("message");
});
test("a gRPC call's trailers are its status row", () => {
const status = messageToStreamEvent(
message(2, { kind: "grpc_trailers", meta: { grpcStatus: 12, grpcMessage: "not here" } }),
);
expect(status).toMatchObject({
direction: "info",
kind: "status",
note: "12 UNIMPLEMENTED: not here",
warning: true,
});
});
});
describe("labels", () => {
test("statuses and closes", () => {
expect(grpcStatusText(0)).toBe("0 OK");
expect(grpcStatusText(42)).toBe("42");
expect(grpcStatusText(null, "gone")).toBe("gone");
expect(closeText(null, null)).toBe("No status code");
});
test("the tab is Events for an event stream and Messages for the rest", () => {
expect(messagesTabLabel({ streamKind: "sse" })).toBe("Events");
expect(messagesTabLabel({ streamKind: "websocket" })).toBe("Messages");
expect(messagesTabLabel({ streamKind: null })).toBeNull();
});
test("a stream is open until it ends, fails or is cancelled", () => {
const open = {
streamKind: "websocket" as const,
elapsedMs: null,
error: null,
cancelled: false,
};
expect(streamIsOpen(open)).toBe(true);
expect(streamIsOpen({ ...open, elapsedMs: 10 })).toBe(false);
expect(streamIsOpen({ ...open, error: "reset" })).toBe(false);
expect(streamIsOpen({ ...open, streamKind: null })).toBe(false);
});
});
+132
View File
@@ -0,0 +1,132 @@
import type { Flow, FlowMessage, MessageKind } from "@yaakapp-internal/proxy-lib";
import type { StreamEvent } from "@yaakapp-internal/ui";
/** gRPC's status codes by number, as a call's status row names them */
const GRPC_STATUS = [
"OK",
"CANCELLED",
"UNKNOWN",
"INVALID_ARGUMENT",
"DEADLINE_EXCEEDED",
"NOT_FOUND",
"ALREADY_EXISTS",
"PERMISSION_DENIED",
"RESOURCE_EXHAUSTED",
"FAILED_PRECONDITION",
"ABORTED",
"OUT_OF_RANGE",
"UNIMPLEMENTED",
"INTERNAL",
"UNAVAILABLE",
"DATA_LOSS",
"UNAUTHENTICATED",
];
const KIND_LABELS: Record<MessageKind, string> = {
websocket_text: "text",
websocket_binary: "binary",
websocket_ping: "ping",
websocket_pong: "pong",
websocket_close: "close",
sse_event: "message",
grpc_message: "message",
grpc_trailers: "status",
};
/** A gRPC status as its row shows it: `0 OK`, `12 UNIMPLEMENTED: not here` */
export function grpcStatusText(status: number | null | undefined, message?: string | null) {
if (status == null) return message ?? "No status";
const name = GRPC_STATUS[status];
const code = name == null ? String(status) : `${status} ${name}`;
return message ? `${code}: ${message}` : code;
}
/** A WebSocket close as its row shows it: `1000 bye`, or that it had no code */
export function closeText(code: number | null | undefined, reason: string | null | undefined) {
const parts = [code == null ? "No status code" : String(code), reason ?? ""].filter(Boolean);
return parts.join(" ");
}
/** A stored message as the shared event stream viewer lists it */
export function messageToStreamEvent(message: FlowMessage): StreamEvent {
const { kind, meta } = message;
const base: StreamEvent = {
key: String(message.seq),
direction: message.direction === "client" ? "sent" : "received",
kind: KIND_LABELS[kind],
timestamp: message.timestamp,
size: message.size,
preview: message.preview,
binary: kind === "websocket_binary" || kind === "grpc_message",
truncated: message.truncated,
error: message.error,
};
switch (kind) {
case "sse_event":
return { ...base, kind: meta.event ?? "message", title: "Event Received" };
case "websocket_close":
return {
...base,
note: closeText(meta.closeCode, meta.closeReason),
title: message.direction === "client" ? "Closed by the App" : "Closed by the Server",
warning: meta.closeCode != null && meta.closeCode !== 1000 && meta.closeCode !== 1001,
};
case "websocket_ping":
case "websocket_pong":
return { ...base, title: kind === "websocket_ping" ? "Ping" : "Pong" };
case "grpc_trailers":
return {
...base,
direction: "info",
note: grpcStatusText(meta.grpcStatus, meta.grpcMessage),
title: "Call Status",
warning: meta.grpcStatus != null && meta.grpcStatus !== 0,
};
default:
return base;
}
}
/**
* `incoming` added to `existing`, both in order by seq, without repeats: a page and the
* messages that arrived while it loaded can overlap.
*/
export function mergeMessages(existing: FlowMessage[], incoming: FlowMessage[]): FlowMessage[] {
if (incoming.length === 0) return existing;
const last = existing[existing.length - 1];
if (last == null) return dedupeSorted(incoming);
const first = incoming[0];
// The usual case: what comes next follows on
if (first != null && first.seq > last.seq && isSorted(incoming)) {
return [...existing, ...incoming];
}
return dedupeSorted([...existing, ...incoming]);
}
function isSorted(messages: FlowMessage[]): boolean {
for (let i = 1; i < messages.length; i++) {
const prev = messages[i - 1];
const next = messages[i];
if (prev == null || next == null || next.seq <= prev.seq) return false;
}
return true;
}
function dedupeSorted(messages: FlowMessage[]): FlowMessage[] {
const bySeq = new Map<number, FlowMessage>();
for (const message of messages) bySeq.set(message.seq, message);
return [...bySeq.values()].sort((a, b) => a.seq - b.seq);
}
/** The Messages tab's name for a flow's stream, or null for a flow that isn't one */
export function messagesTabLabel(flow: Pick<Flow, "streamKind">): string | null {
if (flow.streamKind == null) return null;
return flow.streamKind === "sse" ? "Events" : "Messages";
}
/** Whether a stream is still open: it has no end, error or cancel yet */
export function streamIsOpen(
flow: Pick<Flow, "streamKind" | "elapsedMs" | "error" | "cancelled">,
): boolean {
return flow.streamKind != null && flow.elapsedMs == null && flow.error == null && !flow.cancelled;
}