diff --git a/web/src/app/(main)/function/traffic/_components/stream-messages.tsx b/web/src/app/(main)/function/traffic/_components/stream-messages.tsx new file mode 100644 index 0000000..83c0bc3 --- /dev/null +++ b/web/src/app/(main)/function/traffic/_components/stream-messages.tsx @@ -0,0 +1,200 @@ +"use client"; + +import * as React from "react"; + +import { Loader2Icon, RefreshCwIcon } from "lucide-react"; + +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { api } from "@/lib/api"; +import type { TrafficStreamMessage } from "@/lib/types"; + +const PAGE_SIZE = 50; +// Binary payloads loaded in full are shown as hex of their first 64 KiB. +const HEX_PREVIEW_BYTES = 64 * 1024; + +function fmtBytes(n: number) { + if (n <= 0) return "0 B"; + const units = ["B", "KB", "MB", "GB"]; + const i = Math.min(Math.floor(Math.log(n) / Math.log(1024)), units.length - 1); + const v = n / 1024 ** i; + return `${i === 0 ? v : v.toFixed(1)} ${units[i]}`; +} + +function fmtDirection(direction: string) { + if (direction === "c2s") return "client -> server"; + if (direction === "s2c") return "server -> client"; + return direction; +} + +// Hex dump: 16 bytes per line, offset first. +function hexDump(bytes: Uint8Array) { + const lines: string[] = []; + for (let i = 0; i < bytes.length; i += 16) { + const row = Array.from(bytes.subarray(i, i + 16), (b) => b.toString(16).padStart(2, "0")).join(" "); + lines.push(`${i.toString(16).padStart(8, "0")} ${row}`); + } + return lines.join("\n"); +} + +type FullPayload = { loading: boolean; text?: string; error?: string }; + +const payloadClass = + "max-h-64 overflow-auto rounded-md bg-muted/50 p-2 font-mono text-xs break-all whitespace-pre-wrap"; + +function StreamMessageRow({ message }: { message: TrafficStreamMessage }) { + const [full, setFull] = React.useState(null); + const binary = message.type === "binary"; + + const loadFull = () => { + if (!message.blob) return; + setFull({ loading: true }); + api + .trafficBlob(message.blob) + .then((bytes) => { + const text = binary + ? `${hexDump(bytes.subarray(0, HEX_PREVIEW_BYTES))}\n(${bytes.length} bytes total)` + : new TextDecoder().decode(bytes); + setFull({ loading: false, text }); + }) + .catch((e: Error) => setFull({ loading: false, error: e.message })); + }; + + if (message.type === "meta") { + return ( +
+
+ #{message.seq} Recording limit reached: later messages were not stored +
+
{message.payload}
+
+ ); + } + + return ( +
+
+ #{message.seq} + {fmtDirection(message.direction)} + {message.type} + {binary && message.encoding === "base64" && base64} + {message.truncated && truncated} + {message.event && event: {message.event}} + {message.event_id && id: {message.event_id}} + {message.retry ? retry: {message.retry} : null} + + {fmtBytes(message.size)} · {new Date(message.ts * 1000).toLocaleTimeString()} + +
+
{full?.text ?? message.payload}
+ {message.blob && ( +
+ blob {message.blob} + {!full?.text && ( + + )} + {full?.error && {full.error}} +
+ )} +
+ ); +} + +// StreamMessagesPanel lists the messages of one WebSocket or SSE exchange, a +// page at a time. It does not poll: Refresh reloads from the start. +export function StreamMessagesPanel({ exchangeId, kind }: { exchangeId: string; kind: "websocket" | "sse" }) { + const [items, setItems] = React.useState([]); + const [total, setTotal] = React.useState(0); + const [loading, setLoading] = React.useState(true); + const [loadingMore, setLoadingMore] = React.useState(false); + const [error, setError] = React.useState(null); + // Answers for an older exchange (or an older refresh) are dropped. + const generation = React.useRef(0); + + const load = React.useCallback( + (offset: number) => { + const gen = offset === 0 ? ++generation.current : generation.current; + if (offset === 0) { + setLoading(true); + setError(null); + } else { + setLoadingMore(true); + } + api + .trafficStream(exchangeId, offset, PAGE_SIZE) + .then((page) => { + if (gen !== generation.current) return; + const next = page.items ?? []; + setItems((prev) => (offset === 0 ? next : [...prev, ...next])); + setTotal(page.total ?? 0); + }) + .catch((e: Error) => { + if (gen === generation.current) setError(e.message); + }) + .finally(() => { + if (gen !== generation.current) return; + setLoading(false); + setLoadingMore(false); + }); + }, + [exchangeId], + ); + + React.useEffect(() => { + setItems([]); + setTotal(0); + load(0); + }, [load]); + + return ( +
+
+ + {kind === "websocket" ? "WebSocket" : "Server-Sent Events"} · {items.length} of {total} messages + + +
+ {renderBody()} +
+ ); + + function renderBody() { + if (loading) { + return ( +
+ + Loading messages… +
+ ); + } + if (error) { + return
Failed to load messages: {error}
; + } + if (items.length === 0) { + return
No messages recorded for this stream.
; + } + return ( + <> +
+ {items.map((m) => ( + + ))} +
+ {items.length < total && ( +
+ +
+ )} + + ); + } +} diff --git a/web/src/app/(main)/function/traffic/page.tsx b/web/src/app/(main)/function/traffic/page.tsx index 07fb213..115d59b 100644 --- a/web/src/app/(main)/function/traffic/page.tsx +++ b/web/src/app/(main)/function/traffic/page.tsx @@ -42,10 +42,12 @@ import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@ import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; import { api } from "@/lib/api"; +import { setVisibleInterval } from "@/lib/polling"; import { useStoredSortPreference } from "@/lib/sort-preference"; import type { TrafficDetail, TrafficExchange, TrafficHost, TrafficResp } from "@/lib/types"; import { cn } from "@/lib/utils"; -import { setVisibleInterval } from "@/lib/polling"; + +import { StreamMessagesPanel } from "./_components/stream-messages"; function fmtTime(ts: string) { return new Date(ts).toLocaleString("zh-CN", { @@ -141,6 +143,9 @@ export default function TrafficPage() { const [selected, setSelected] = React.useState(null); const [detail, setDetail] = React.useState(null); const [detailLoading, setDetailLoading] = React.useState(false); + const [detailTab, setDetailTab] = React.useState("request"); + const streamKind = detail?.stream_kind === "websocket" || detail?.stream_kind === "sse" ? detail.stream_kind : null; + const hasStream = streamKind !== null; const [hosts, setHosts] = React.useState([]); // target picker const [selectedHosts, setSelectedHosts] = React.useState([]); // checked in picker @@ -298,8 +303,10 @@ export default function TrafficPage() { .finally(() => setDeleting(false)); }; - // Lazy-load the raw request/response for the selected exchange. + // Lazy-load the raw request/response for the selected exchange. A new + // selection opens on Request; a WebSocket/SSE exchange then opens on Stream. React.useEffect(() => { + setDetailTab("request"); if (!selected) { setDetail(null); return; @@ -310,7 +317,9 @@ export default function TrafficPage() { api .trafficExchange(selected.id) .then((d) => { - if (alive) setDetail(d); + if (!alive) return; + setDetail(d); + if (d.stream_kind === "websocket" || d.stream_kind === "sse") setDetailTab("stream"); }) .catch(() => { if (alive) setDetail({ req: "(failed to load the messages)", resp: "" }); @@ -742,10 +751,18 @@ export default function TrafficPage() { {selected.host} {selected.url} - - + + Request Response + {hasStream && ( + + Stream + {(detail?.stream_count ?? 0) > 0 && ( + {detail?.stream_count} + )} + + )} {detailLoading ? ( @@ -767,6 +784,11 @@ export default function TrafficPage() { )} + {streamKind && ( + + + + )} )} diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts index 03f5eb2..943e2e2 100644 --- a/web/src/lib/api.ts +++ b/web/src/lib/api.ts @@ -102,6 +102,7 @@ import type { TrafficEvidenceRole, TrafficHost, TrafficResp, + TrafficStreamPage, UsageStats, WorkspaceFile, WorkspaceListing, @@ -816,6 +817,20 @@ export const api = { (opts.order ? `&order=${encodeURIComponent(opts.order)}` : ""), ), trafficExchange: (id: string) => get(`/traffic/exchange?id=${encodeURIComponent(id)}`), + // One page of a WebSocket/SSE exchange's messages, in order. + trafficStream: (id: string, offset = 0, limit = 50) => + get(`/traffic/stream?exchange=${encodeURIComponent(id)}&offset=${offset}&limit=${limit}`), + // Raw bytes of one stored blob (a full message payload or an oversized body). + // The JSON-only `get` cannot carry binary, hence the direct fetch. + trafficBlob: async (hash: string) => { + if (MOCK) throw new Error("Blob download is not available in mock mode"); + const token = getToken(); + const r = await fetch(`/api/traffic/blob?hash=${encodeURIComponent(hash)}`, { + headers: { ...(token ? { Authorization: `Bearer ${token}` } : {}) }, + }); + if (!r.ok) throw new Error(`Blob download failed: ${r.status}`); + return new Uint8Array(await r.arrayBuffer()); + }, trafficHosts: () => get<{ hosts: TrafficHost[] }>(`/traffic/hosts`), trafficDeleteHost: (host: string) => del<{ deleted: number }>(`/traffic?host=${encodeURIComponent(host)}`), trafficDeleteHosts: (hosts: string[]) => del<{ deleted: number }>(`/traffic/hosts`, { hosts }), diff --git a/web/src/lib/types.ts b/web/src/lib/types.ts index 7d6d1dd..bd9d14a 100644 --- a/web/src/lib/types.ts +++ b/web/src/lib/types.ts @@ -911,6 +911,34 @@ export interface TrafficResp { export interface TrafficDetail { req: string; resp: string; + // WebSocket/SSE exchanges carry their messages separately (trafficStream); + // stream_kind is "" for an ordinary exchange. + stream_count?: number; + stream_kind?: "websocket" | "sse" | ""; +} + +// One recorded WebSocket message or SSE event. ts is in Unix seconds; seq +// orders. payload is a preview of at most 4 KiB (base64 when encoding is +// "base64"); blob names the full payload when it was stored separately. +export interface TrafficStreamMessage { + seq: number; + ts: number; + direction: "c2s" | "s2c" | "meta" | (string & {}); + kind: number; + type: "text" | "binary" | "event" | "meta" | (string & {}); + event?: string; + event_id?: string; + retry?: number; + size: number; + payload: string; + encoding?: string; + blob?: string; + truncated?: boolean; +} + +export interface TrafficStreamPage { + items: TrafficStreamMessage[]; + total: number; } // One distinct recorded host with its exchange count (target picker).