From cc382b92262d0d05fe7197f18055c865de141b60 Mon Sep 17 00:00:00 2001 From: Gregory Schier Date: Fri, 6 Nov 2026 18:45:52 -0700 Subject: [PATCH] Messages tab for streams, with messages as the single record (#819) Co-authored-by: Claude Opus 5.5 --- .../components/core/EventViewer.tsx | 314 +---------- .../components/core/EventViewerRow.tsx | 39 +- .../responseViewers/EventStreamViewer.tsx | 66 ++- .../hooks/useSendAnyHttpRequest.test.ts | 5 + apps/yaak-client/lib/confirmWebProxy.test.tsx | 5 + apps/yaak-proxy/components/FlowBodyViewer.tsx | 5 +- apps/yaak-proxy/components/FlowDetail.tsx | 25 + apps/yaak-proxy/components/FlowMessages.tsx | 131 +++++ apps/yaak-proxy/harness/MessagesHarness.tsx | 80 +++ apps/yaak-proxy/harness/main.tsx | 6 +- apps/yaak-proxy/harness/streamFixtures.ts | 372 +++++++++++++ apps/yaak-proxy/hooks/useFlowMessages.ts | 140 +++++ apps/yaak-proxy/lib/body.test.ts | 18 + apps/yaak-proxy/lib/body.ts | 35 +- apps/yaak-proxy/lib/messages.test.ts | 118 +++++ apps/yaak-proxy/lib/messages.ts | 132 +++++ .../yaak-proxy-lib/bindings/gen_models.ts | 9 +- .../yaak-proxy-lib/bindings/gen_rpc.ts | 12 +- crates-proxy/yaak-proxy-lib/src/bodies.rs | 422 ++++++++++++++- crates-proxy/yaak-proxy-lib/src/client.rs | 7 +- crates-proxy/yaak-proxy-lib/src/control.rs | 10 +- crates-proxy/yaak-proxy-lib/src/convert.rs | 12 +- crates-proxy/yaak-proxy-lib/src/flows.rs | 7 +- crates-proxy/yaak-proxy-lib/src/grpc.rs | 6 +- crates-proxy/yaak-proxy-lib/src/har.rs | 12 +- crates-proxy/yaak-proxy-lib/src/lib.rs | 434 ++++++++++++++- crates-proxy/yaak-proxy-lib/src/models.rs | 9 +- crates-proxy/yaak-proxy-lib/tests/flow.rs | 4 +- crates-proxy/yaak-proxy-lib/tests/streams.rs | 144 ++++- crates/yaak-proxy/src/body.rs | 2 +- crates/yaak-proxy/src/grpc.rs | 51 +- crates/yaak-proxy/src/lib.rs | 2 +- packages/ui/src/components/Select.tsx | 11 +- .../src/components/events}/AutoScroller.tsx | 55 +- .../events/EventStreamViewer.test.tsx | 110 ++++ .../components/events/EventStreamViewer.tsx | 492 ++++++++++++++++++ .../ui/src/components/events/EventViewer.tsx | 331 ++++++++++++ .../src/components/events/EventViewerRow.tsx | 59 +++ .../components/events/streamEvents.test.ts | 53 ++ .../ui/src/components/events/streamEvents.ts | 90 ++++ .../ui/src}/hooks/useEventViewerKeyboard.ts | 0 packages/ui/src/index.ts | 21 +- 42 files changed, 3403 insertions(+), 453 deletions(-) create mode 100644 apps/yaak-proxy/components/FlowMessages.tsx create mode 100644 apps/yaak-proxy/harness/MessagesHarness.tsx create mode 100644 apps/yaak-proxy/harness/streamFixtures.ts create mode 100644 apps/yaak-proxy/hooks/useFlowMessages.ts create mode 100644 apps/yaak-proxy/lib/messages.test.ts create mode 100644 apps/yaak-proxy/lib/messages.ts rename {apps/yaak-client/components/core => packages/ui/src/components/events}/AutoScroller.tsx (63%) create mode 100644 packages/ui/src/components/events/EventStreamViewer.test.tsx create mode 100644 packages/ui/src/components/events/EventStreamViewer.tsx create mode 100644 packages/ui/src/components/events/EventViewer.tsx create mode 100644 packages/ui/src/components/events/EventViewerRow.tsx create mode 100644 packages/ui/src/components/events/streamEvents.test.ts create mode 100644 packages/ui/src/components/events/streamEvents.ts rename {apps/yaak-client => packages/ui/src}/hooks/useEventViewerKeyboard.ts (100%) diff --git a/apps/yaak-client/components/core/EventViewer.tsx b/apps/yaak-client/components/core/EventViewer.tsx index 77ecfc95f..7d7f5f2a7 100644 --- a/apps/yaak-client/components/core/EventViewer.tsx +++ b/apps/yaak-client/components/core/EventViewer.tsx @@ -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 { - /** 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({ - events, - getEventKey, - renderRow, - renderDetail, - header, - error, - splitLayoutStorageKey, - defaultRatio = 0.4, - enableKeyboardNav = true, - isLoading = false, - loadingMessage = "Loading events...", - emptyMessage = "No events recorded", - onActiveIndexChange, -}: EventViewerProps) { - const [activeIndex, setActiveIndexInternal] = useState(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(null); - const virtualizerRef = useRef | 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) => { - 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
{loadingMessage}
; - } - - if (events.length === 0 && !error) { - return
{emptyMessage}
; - } - - return ( -
- ( -
- {header ?? } - - {error} - - ) - } - render={(event, index) => ( -
- {renderRow({ - event, - index, - isActive: index === activeIndex, - onClick: () => handleRowClick(index), - })} -
- )} - /> -
- )} - secondSlot={ - activeEvent != null && renderDetail && isPanelOpen - ? ({ style }) => ( -
-
- -
-
- {renderDetail({ - event: activeEvent, - index: activeIndex ?? 0, - onClose: handleClose, - })} -
-
- ) - : null - } - /> -
- ); -} - -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["options"]; - /** Change handler */ - onChange: (value: string) => void; - }; - -interface EventDetailHeaderProps { - title: string; - prefix?: ReactNode; - timestamp?: string; - actions?: EventDetailAction[]; - copyText?: string | (() => Promise); - 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 ( -
- - {prefix} -

{title}

-
- - {actions?.map((action) => - action.type === "select" ? ( -
- +
+ ) : ( + + ), + )} + {copyText != null && ( + + )} + {formattedTime && ( + {formattedTime} + )} + {onClose != null && ( +
0 && "border-l border-l-surface-highlight ml-2 pl-3"), + )} + > + +
+ )} +
+
+ ); +} diff --git a/packages/ui/src/components/events/EventViewerRow.tsx b/packages/ui/src/components/events/EventViewerRow.tsx new file mode 100644 index 000000000..184439f04 --- /dev/null +++ b/packages/ui/src/components/events/EventViewerRow.tsx @@ -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 ( +
+ +
+ ); +} diff --git a/packages/ui/src/components/events/streamEvents.test.ts b/packages/ui/src/components/events/streamEvents.test.ts new file mode 100644 index 000000000..3035f6302 --- /dev/null +++ b/packages/ui/src/components/events/streamEvents.test.ts @@ -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(""); + }); +}); diff --git a/packages/ui/src/components/events/streamEvents.ts b/packages/ui/src/components/events/streamEvents.ts new file mode 100644 index 000000000..40a518557 --- /dev/null +++ b/packages/ui/src/components/events/streamEvents.ts @@ -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; + } + | { 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[]): (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; +} diff --git a/apps/yaak-client/hooks/useEventViewerKeyboard.ts b/packages/ui/src/hooks/useEventViewerKeyboard.ts similarity index 100% rename from apps/yaak-client/hooks/useEventViewerKeyboard.ts rename to packages/ui/src/hooks/useEventViewerKeyboard.ts diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.ts index f0276fa99..3e5c69a72 100644 --- a/packages/ui/src/index.ts +++ b/packages/ui/src/index.ts @@ -41,6 +41,23 @@ export type { } from "./components/EditorHost"; export { EditorHostProvider, useEditorHost } from "./components/EditorHost"; export { EmptyStateText } from "./components/EmptyStateText"; +export { AutoScroller } from "./components/events/AutoScroller"; +export type { + EventStreamColumns, + EventStreamViewerProps, +} from "./components/events/EventStreamViewer"; +export { EventStreamViewer, payloadText } from "./components/events/EventStreamViewer"; +export type { EventDetailAction } from "./components/events/EventViewer"; +export { EventDetailHeader, EventViewer } from "./components/events/EventViewer"; +export { EventViewerRow } from "./components/events/EventViewerRow"; +export type { + StreamEvent, + StreamEventDirection, + StreamPayload, + StreamPayloadText, + StreamPayloadView, +} from "./components/events/streamEvents"; +export { eventDeltas, formatEventDelta, formatEventTime } from "./components/events/streamEvents"; export type { ExternalLinkProps } from "./components/ExternalLink"; export { ExternalLink } from "./components/ExternalLink"; export { ConfirmLargeResponse } from "./components/http/ConfirmLargeResponse"; @@ -104,6 +121,8 @@ export { PairOrBulkEditor } from "./components/pairs/PairOrBulkEditor"; export { PillButton } from "./components/PillButton"; export type { RadioDropdownItem, RadioDropdownProps } from "./components/RadioDropdown"; export { RadioDropdown } from "./components/RadioDropdown"; +export type { SelectProps } from "./components/Select"; +export { Select } from "./components/Select"; export type { ErrorBoundaryProps } from "./components/ErrorBoundary"; export { ErrorBoundary } from "./components/ErrorBoundary"; export { FormattedError } from "./components/FormattedError"; @@ -128,8 +147,6 @@ export { Overlay } from "./components/Overlay"; export type { PlainInputProps } from "./components/PlainInput"; export { PlainInput } from "./components/PlainInput"; export { Portal } from "./components/Portal"; -export type { SelectProps } from "./components/Select"; -export { Select } from "./components/Select"; export type { SeparatorAction } from "./components/Separator"; export { Separator } from "./components/Separator"; export type { SettingRowBaseProps, SettingSnippetLanguage } from "./components/settings/SettingRow";