Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

feat(ui): traffic-inspector hooks (stream, filters, virtual-list, resizable, session, replay) (F8)

diegosouzapw442457af755e
diff --git a/src/app/(dashboard)/dashboard/tools/traffic-inspector/hooks/useAnnotations.ts b/src/app/(dashboard)/dashboard/tools/traffic-inspector/hooks/useAnnotations.ts
new file mode 100644
index 0000000000..e53759c5ac
--- /dev/null
+++ b/src/app/(dashboard)/dashboard/tools/traffic-inspector/hooks/useAnnotations.ts
@@ -0,0 +1,43 @@
+"use client";
+
+import { useCallback, useRef, useState } from "react";
+
+const DEBOUNCE_MS = 500;
+
+export function useAnnotations(requestId: string | null) {
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ const save = useCallback(
+ (annotation: string) => {
+ if (!requestId) return;
+ if (timerRef.current) clearTimeout(timerRef.current);
+ timerRef.current = setTimeout(async () => {
+ setSaving(true);
+ setError(null);
+ try {
+ const res = await fetch(
+ `/api/tools/traffic-inspector/requests/${encodeURIComponent(requestId)}/annotation`,
+ {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ annotation }),
+ }
+ );
+ if (!res.ok) {
+ const body = (await res.json().catch(() => ({}))) as { error?: { message?: string } };
+ setError(body?.error?.message ?? "Failed to save annotation");
+ }
+ } catch {
+ setError("Network error saving annotation");
+ } finally {
+ setSaving(false);
+ }
+ }, DEBOUNCE_MS);
+ },
+ [requestId]
+ );
+
+ return { save, saving, error };
+}
diff --git a/src/app/(dashboard)/dashboard/tools/traffic-inspector/hooks/useReplay.ts b/src/app/(dashboard)/dashboard/tools/traffic-inspector/hooks/useReplay.ts
new file mode 100644
index 0000000000..9a837aeaa1
--- /dev/null
+++ b/src/app/(dashboard)/dashboard/tools/traffic-inspector/hooks/useReplay.ts
@@ -0,0 +1,30 @@
+"use client";
+
+import { useCallback, useState } from "react";
+import type { InterceptedRequest } from "@/mitm/inspector/types";
+
+export function useReplay() {
+ const [replaying, setReplaying] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ const replay = useCallback(async (req: InterceptedRequest) => {
+ setReplaying(true);
+ setError(null);
+ try {
+ const res = await fetch(
+ `/api/tools/traffic-inspector/requests/${encodeURIComponent(req.id)}/replay`,
+ { method: "POST" }
+ );
+ if (!res.ok) {
+ const body = (await res.json().catch(() => ({}))) as { error?: { message?: string } };
+ setError(body?.error?.message ?? "Replay failed");
+ }
+ } catch {
+ setError("Network error during replay");
+ } finally {
+ setReplaying(false);
+ }
+ }, []);
+
+ return { replay, replaying, error };
+}
diff --git a/src/app/(dashboard)/dashboard/tools/traffic-inspector/hooks/useResizablePanels.ts b/src/app/(dashboard)/dashboard/tools/traffic-inspector/hooks/useResizablePanels.ts
new file mode 100644
index 0000000000..5d40e9cfe0
--- /dev/null
+++ b/src/app/(dashboard)/dashboard/tools/traffic-inspector/hooks/useResizablePanels.ts
@@ -0,0 +1,82 @@
+"use client";
+
+import { useCallback, useEffect, useRef, useState } from "react";
+
+const STORAGE_KEY = "inspector.listWidth";
+const MIN_WIDTH = 280;
+const MAX_WIDTH = 720;
+const COLLAPSED_RAIL = 48;
+const DEFAULT_WIDTH = 360;
+
+export interface ResizablePanelsState {
+ listWidth: number;
+ collapsed: boolean;
+}
+
+export interface ResizablePanelsActions {
+ startDrag: (e: React.MouseEvent) => void;
+ toggleCollapse: () => void;
+}
+
+export function useResizablePanels(): [ResizablePanelsState, ResizablePanelsActions] {
+ const [listWidth, setListWidth] = useState<number>(() => {
+ if (typeof window === "undefined") return DEFAULT_WIDTH;
+ const stored = localStorage.getItem(STORAGE_KEY);
+ const parsed = stored ? Number(stored) : NaN;
+ return isNaN(parsed) ? DEFAULT_WIDTH : Math.min(MAX_WIDTH, Math.max(MIN_WIDTH, parsed));
+ });
+ const [collapsed, setCollapsed] = useState(false);
+
+ const draggingRef = useRef(false);
+ const startXRef = useRef(0);
+ const startWidthRef = useRef(DEFAULT_WIDTH);
+ // Store handler refs to avoid stale closure issues
+ const onMouseMoveRef = useRef<(e: MouseEvent) => void>(() => {});
+ const onMouseUpRef = useRef<() => void>(() => {});
+
+ useEffect(() => {
+ if (!collapsed) {
+ localStorage.setItem(STORAGE_KEY, String(listWidth));
+ }
+ }, [listWidth, collapsed]);
+
+ useEffect(() => {
+ onMouseMoveRef.current = (e: MouseEvent) => {
+ if (!draggingRef.current) return;
+ const delta = e.clientX - startXRef.current;
+ const next = Math.min(MAX_WIDTH, Math.max(MIN_WIDTH, startWidthRef.current + delta));
+ setListWidth(next);
+ setCollapsed(false);
+ };
+
+ onMouseUpRef.current = () => {
+ draggingRef.current = false;
+ document.body.style.cursor = "";
+ document.body.style.userSelect = "";
+ window.removeEventListener("mousemove", onMouseMoveRef.current);
+ window.removeEventListener("mouseup", onMouseUpRef.current);
+ };
+ });
+
+ const startDrag = useCallback(
+ (e: React.MouseEvent) => {
+ e.preventDefault();
+ draggingRef.current = true;
+ startXRef.current = e.clientX;
+ startWidthRef.current = collapsed ? COLLAPSED_RAIL : listWidth;
+ document.body.style.cursor = "col-resize";
+ document.body.style.userSelect = "none";
+ window.addEventListener("mousemove", onMouseMoveRef.current);
+ window.addEventListener("mouseup", onMouseUpRef.current);
+ },
+ [collapsed, listWidth]
+ );
+
+ const toggleCollapse = useCallback(() => {
+ setCollapsed((prev) => !prev);
+ }, []);
+
+ const effectiveWidth = collapsed ? COLLAPSED_RAIL : listWidth;
+
+ return [{ listWidth: effectiveWidth, collapsed }, { startDrag, toggleCollapse }];
+}
diff --git a/src/app/(dashboard)/dashboard/tools/traffic-inspector/hooks/useSessionRecorder.ts b/src/app/(dashboard)/dashboard/tools/traffic-inspector/hooks/useSessionRecorder.ts
new file mode 100644
index 0000000000..b16e0b8c0c
--- /dev/null
+++ b/src/app/(dashboard)/dashboard/tools/traffic-inspector/hooks/useSessionRecorder.ts
@@ -0,0 +1,125 @@
+"use client";
+
+import { useCallback, useEffect, useRef, useState } from "react";
+
+export interface SessionInfo {
+ id: string;
+ name?: string;
+ startedAt: string;
+ requestCount: number;
+}
+
+async function fetchSessionsRemote(): Promise<SessionInfo[]> {
+ const res = await fetch("/api/tools/traffic-inspector/sessions");
+ if (!res.ok) return [];
+ const data = (await res.json()) as { sessions: SessionInfo[] };
+ return data.sessions ?? [];
+}
+
+export function useSessionRecorder() {
+ const [recording, setRecording] = useState(false);
+ const [session, setSession] = useState<SessionInfo | null>(null);
+ const [elapsed, setElapsed] = useState(0);
+ const [sessions, setSessions] = useState<SessionInfo[]>([]);
+ const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);
+ const startTimeRef = useRef<number>(0);
+ const mountedRef = useRef(true);
+
+ useEffect(() => {
+ mountedRef.current = true;
+ return () => {
+ mountedRef.current = false;
+ };
+ }, []);
+
+ const fetchSessions = useCallback(async () => {
+ try {
+ const list = await fetchSessionsRemote();
+ if (mountedRef.current) setSessions(list);
+ } catch {
+ // silently ignore
+ }
+ }, []);
+
+ // Fetch sessions on mount — use an async wrapper to avoid direct setState in effect
+ useEffect(() => {
+ let cancelled = false;
+ fetchSessionsRemote()
+ .then((list) => {
+ if (!cancelled) setSessions(list);
+ })
+ .catch(() => {});
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ const start = useCallback(async (name?: string) => {
+ try {
+ const res = await fetch("/api/tools/traffic-inspector/sessions", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ name }),
+ });
+ if (!res.ok) return;
+ const data = (await res.json()) as { session: SessionInfo };
+ setSession(data.session);
+ setRecording(true);
+ startTimeRef.current = Date.now();
+ setElapsed(0);
+ timerRef.current = setInterval(() => {
+ setElapsed(Math.floor((Date.now() - startTimeRef.current) / 1000));
+ }, 1000);
+ } catch {
+ // ignore
+ }
+ }, []);
+
+ const stop = useCallback(async () => {
+ if (!session) return;
+ if (timerRef.current) {
+ clearInterval(timerRef.current);
+ timerRef.current = null;
+ }
+ setRecording(false);
+ try {
+ await fetch(`/api/tools/traffic-inspector/sessions/${encodeURIComponent(session.id)}`, {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ action: "stop" }),
+ });
+ } catch {
+ // ignore
+ }
+ await fetchSessions();
+ setSession(null);
+ }, [session, fetchSessions]);
+
+ const deleteSession = useCallback(async (id: string) => {
+ try {
+ await fetch(`/api/tools/traffic-inspector/sessions/${encodeURIComponent(id)}`, {
+ method: "DELETE",
+ });
+ await fetchSessions();
+ } catch {
+ // ignore
+ }
+ }, [fetchSessions]);
+
+ useEffect(() => {
+ return () => {
+ if (timerRef.current) clearInterval(timerRef.current);
+ };
+ }, []);
+
+ return {
+ recording,
+ session,
+ elapsed,
+ sessions,
+ start,
+ stop,
+ deleteSession,
+ fetchSessions,
+ };
+}
diff --git a/src/app/(dashboard)/dashboard/tools/traffic-inspector/hooks/useTrafficFilters.ts b/src/app/(dashboard)/dashboard/tools/traffic-inspector/hooks/useTrafficFilters.ts
new file mode 100644
index 0000000000..19b33e8b8c
--- /dev/null
+++ b/src/app/(dashboard)/dashboard/tools/traffic-inspector/hooks/useTrafficFilters.ts
@@ -0,0 +1,56 @@
+"use client";
+
+import { useCallback, useState } from "react";
+import type { ListFilters } from "@/mitm/inspector/types";
+
+export interface FiltersState extends ListFilters {
+ sameContextKey?: string;
+}
+
+export function useTrafficFilters() {
+ const [filters, setFilters] = useState<FiltersState>({ profile: "llm" });
+
+ const setProfile = useCallback((profile: ListFilters["profile"]) => {
+ setFilters((prev) => ({ ...prev, profile }));
+ }, []);
+
+ const setHost = useCallback((host: string | undefined) => {
+ setFilters((prev) => ({ ...prev, host: host || undefined }));
+ }, []);
+
+ const setAgent = useCallback((agent: ListFilters["agent"]) => {
+ setFilters((prev) => ({ ...prev, agent }));
+ }, []);
+
+ const setStatus = useCallback((status: ListFilters["status"]) => {
+ setFilters((prev) => ({ ...prev, status }));
+ }, []);
+
+ const setSource = useCallback((source: ListFilters["source"]) => {
+ setFilters((prev) => ({ ...prev, source }));
+ }, []);
+
+ const setSessionId = useCallback((sessionId: string | undefined) => {
+ setFilters((prev) => ({ ...prev, sessionId }));
+ }, []);
+
+ const setSameContext = useCallback((contextKey: string | undefined) => {
+ setFilters((prev) => ({ ...prev, sameContextKey: contextKey }));
+ }, []);
+
+ const reset = useCallback(() => {
+ setFilters({ profile: "llm" });
+ }, []);
+
+ return {
+ filters,
+ setProfile,
+ setHost,
+ setAgent,
+ setStatus,
+ setSource,
+ setSessionId,
+ setSameContext,
+ reset,
+ };
+}
diff --git a/src/app/(dashboard)/dashboard/tools/traffic-inspector/hooks/useTrafficStream.ts b/src/app/(dashboard)/dashboard/tools/traffic-inspector/hooks/useTrafficStream.ts
new file mode 100644
index 0000000000..2f6c8ac8f3
--- /dev/null
+++ b/src/app/(dashboard)/dashboard/tools/traffic-inspector/hooks/useTrafficStream.ts
@@ -0,0 +1,177 @@
+"use client";
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import type { InterceptedRequest, ListFilters, WsEvent } from "@/mitm/inspector/types";
+
+const WS_PATH = "/api/tools/traffic-inspector/ws";
+const INITIAL_BACKOFF_MS = 500;
+const MAX_BACKOFF_MS = 30_000;
+const BACKOFF_MULTIPLIER = 2;
+
+export interface TrafficStreamState {
+ requests: InterceptedRequest[];
+ connected: boolean;
+ paused: boolean;
+ total: number;
+}
+
+export interface TrafficStreamActions {
+ pause: () => void;
+ resume: () => void;
+ clear: () => void;
+}
+
+export function useTrafficStream(
+ filters: ListFilters
+): [TrafficStreamState, TrafficStreamActions] {
+ const [requests, setRequests] = useState<InterceptedRequest[]>([]);
+ const [connected, setConnected] = useState(false);
+ const [paused, setPaused] = useState(false);
+
+ const wsRef = useRef<WebSocket | null>(null);
+ const backoffRef = useRef(INITIAL_BACKOFF_MS);
+ const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const mountedRef = useRef(true);
+ const pausedRef = useRef(false);
+ const pendingRef = useRef<InterceptedRequest[]>([]);
+ const filtersRef = useRef(filters);
+ // connectRef breaks the circular dep between connect's closure and onclose
+ const connectRef = useRef<() => void>(() => {});
+
+ // Keep filtersRef in sync without triggering re-render (effect runs after render)
+ useEffect(() => {
+ filtersRef.current = filters;
+ });
+
+ const applyFilter = useCallback((req: InterceptedRequest): boolean => {
+ const f = filtersRef.current;
+ if (f.profile === "llm" && req.detectedKind !== "llm") return false;
+ if (f.profile === "custom" && req.source !== "custom-host") return false;
+ if (f.host && !req.host.includes(f.host)) return false;
+ if (f.agent && req.agent !== f.agent) return false;
+ if (f.source && req.source !== f.source) return false;
+ if (f.sessionId && req.sessionId !== f.sessionId) return false;
+ if (f.status) {
+ const s = req.status;
+ if (typeof s === "number") {
+ const cat = `${Math.floor(s / 100)}xx`;
+ if (cat !== f.status) return false;
+ } else if (f.status === "error" && s !== "error") {
+ return false;
+ }
+ }
+ return true;
+ }, []);
+
+ useEffect(() => {
+ mountedRef.current = true;
+
+ const connect = () => {
+ if (!mountedRef.current) return;
+ if (wsRef.current && wsRef.current.readyState < WebSocket.CLOSING) {
+ wsRef.current.close();
+ }
+
+ const proto = window.location.protocol === "https:" ? "wss:" : "ws:";
+ const url = `${proto}//${window.location.host}${WS_PATH}`;
+ const ws = new WebSocket(url);
+ wsRef.current = ws;
+
+ ws.onopen = () => {
+ if (!mountedRef.current) return;
+ backoffRef.current = INITIAL_BACKOFF_MS;
+ setConnected(true);
+ };
+
+ ws.onmessage = (ev: MessageEvent) => {
+ if (!mountedRef.current) return;
+ let event: WsEvent;
+ try {
+ event = JSON.parse(ev.data as string) as WsEvent;
+ } catch {
+ return;
+ }
+
+ if (pausedRef.current) {
+ if (event.type === "new") pendingRef.current.push(event.data);
+ if (event.type === "update") {
+ const idx = pendingRef.current.findIndex((r) => r.id === event.data.id);
+ if (idx !== -1) pendingRef.current[idx] = event.data;
+ }
+ return;
+ }
+
+ if (event.type === "snapshot") {
+ setRequests(event.data.filter(applyFilter));
+ } else if (event.type === "new") {
+ if (applyFilter(event.data)) {
+ setRequests((prev) => [event.data, ...prev].slice(0, 1000));
+ }
+ } else if (event.type === "update") {
+ setRequests((prev) =>
+ prev.map((r) => (r.id === event.data.id ? event.data : r))
+ );
+ } else if (event.type === "clear") {
+ setRequests([]);
+ }
+ };
+
+ ws.onclose = () => {
+ if (!mountedRef.current) return;
+ setConnected(false);
+ const delay = Math.min(backoffRef.current, MAX_BACKOFF_MS);
+ backoffRef.current = Math.min(
+ backoffRef.current * BACKOFF_MULTIPLIER,
+ MAX_BACKOFF_MS
+ );
+ reconnectTimerRef.current = setTimeout(() => {
+ // Use ref so we always call the current connect version
+ connectRef.current();
+ }, delay);
+ };
+
+ ws.onerror = () => {
+ ws.close();
+ };
+ };
+
+ // Store in ref for reconnect callback
+ connectRef.current = connect;
+ connect();
+
+ return () => {
+ mountedRef.current = false;
+ if (reconnectTimerRef.current) clearTimeout(reconnectTimerRef.current);
+ wsRef.current?.close();
+ };
+ }, [applyFilter]);
+
+ const pause = useCallback(() => {
+ pausedRef.current = true;
+ setPaused(true);
+ }, []);
+
+ const resume = useCallback(() => {
+ pausedRef.current = false;
+ setPaused(false);
+ if (pendingRef.current.length > 0) {
+ const pending = pendingRef.current.filter(applyFilter);
+ pendingRef.current = [];
+ setRequests((prev) => [...pending, ...prev].slice(0, 1000));
+ }
+ }, [applyFilter]);
+
+ const clear = useCallback(() => {
+ setRequests([]);
+ pendingRef.current = [];
+ }, []);
+
+ const state: TrafficStreamState = {
+ requests,
+ connected,
+ paused,
+ total: requests.length,
+ };
+
+ return [state, { pause, resume, clear }];
+}
diff --git a/src/app/(dashboard)/dashboard/tools/traffic-inspector/hooks/useVirtualList.ts b/src/app/(dashboard)/dashboard/tools/traffic-inspector/hooks/useVirtualList.ts
new file mode 100644
index 0000000000..d955bba0d9
--- /dev/null
+++ b/src/app/(dashboard)/dashboard/tools/traffic-inspector/hooks/useVirtualList.ts
@@ -0,0 +1,107 @@
+"use client";
+
+import { useCallback, useEffect, useRef, useState } from "react";
+
+const ESTIMATED_ROW_HEIGHT = 48;
+const OVERSCAN = 5;
+
+export interface VirtualListState<T> {
+ virtualItems: Array<{ index: number; item: T; top: number; height: number }>;
+ totalHeight: number;
+ containerRef: React.RefObject<HTMLDivElement | null>;
+ rowRef: (index: number) => (el: HTMLDivElement | null) => void;
+}
+
+export function useVirtualList<T>(items: T[], containerHeight: number): VirtualListState<T> {
+ const containerRef = useRef<HTMLDivElement | null>(null);
+ const [scrollTop, setScrollTop] = useState(0);
+ // Heights stored in state so reads during render are tracked by React
+ const [heights, setHeights] = useState<Map<number, number>>(new Map());
+ const observersRef = useRef<Map<number, ResizeObserver>>(new Map());
+
+ useEffect(() => {
+ const el = containerRef.current;
+ if (!el) return;
+ const handler = () => setScrollTop(el.scrollTop);
+ el.addEventListener("scroll", handler, { passive: true });
+ return () => el.removeEventListener("scroll", handler);
+ }, []);
+
+ // Cleanup observers on unmount
+ useEffect(() => {
+ const observers = observersRef.current;
+ return () => {
+ observers.forEach((obs) => obs.disconnect());
+ };
+ }, []);
+
+ const rowRef = useCallback((index: number) => (el: HTMLDivElement | null) => {
+ const observers = observersRef.current;
+ if (el) {
+ const existing = observers.get(index);
+ if (existing) existing.disconnect();
+ const ro = new ResizeObserver((entries) => {
+ for (const entry of entries) {
+ const h = entry.contentRect.height;
+ if (h > 0) {
+ setHeights((prev) => {
+ if (prev.get(index) === h) return prev;
+ const next = new Map(prev);
+ next.set(index, h);
+ return next;
+ });
+ }
+ }
+ });
+ ro.observe(el);
+ observers.set(index, ro);
+ } else {
+ const existing = observers.get(index);
+ if (existing) {
+ existing.disconnect();
+ observers.delete(index);
+ }
+ }
+ }, []);
+
+ // Compute cumulative offsets — reads heights from state (not a ref)
+ const offsets: number[] = [];
+ let total = 0;
+ for (let i = 0; i < items.length; i++) {
+ offsets.push(total);
+ total += heights.get(i) ?? ESTIMATED_ROW_HEIGHT;
+ }
+ const totalHeight = total;
+
+ // Find visible range
+ let startIdx = 0;
+ let endIdx = items.length - 1;
+ for (let i = 0; i < offsets.length; i++) {
+ if ((offsets[i] ?? 0) + (heights.get(i) ?? ESTIMATED_ROW_HEIGHT) < scrollTop) {
+ startIdx = i + 1;
+ } else {
+ break;
+ }
+ }
+ for (let i = startIdx; i < offsets.length; i++) {
+ if ((offsets[i] ?? 0) > scrollTop + containerHeight) {
+ endIdx = i - 1;
+ break;
+ }
+ }
+
+ startIdx = Math.max(0, startIdx - OVERSCAN);
+ endIdx = Math.min(items.length - 1, endIdx + OVERSCAN);
+
+ const virtualItems: Array<{ index: number; item: T; top: number; height: number }> = [];
+ for (let i = startIdx; i <= endIdx; i++) {
+ virtualItems.push({
+ index: i,
+ item: items[i] as T,
+ top: offsets[i] ?? 0,
+ height: heights.get(i) ?? ESTIMATED_ROW_HEIGHT,
+ });
+ }
+
+ return { virtualItems, totalHeight, containerRef, rowRef };
+}