ARTEX - AI autonomous penetration testing system (English translation; upstream: Autumn-27/ARTEX, AGPL-3.0)
Go aiai-agentsautonomous-agentsbug-bountydockergolanglinuxllmmcpnextjspenetration-testingpentestpostgresqlreareactred-teamsecuritysecurity-automationsqlitetypescript
feat(web): add direction filters to recorded stream messages
APZN6acfd510047e
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex d28c17d..027ea46 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -147,6 +147,7 @@ jobs:- run: npm run test:polling- run: npm run test:replay- run: npm run test:upload+ - run: npm run test:traffic-stream- run: npm run test:i18n- run: npm run test:bash- run: npm run build:staticdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8c6ced3..1d18b02 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,10 @@ All notable changes to this project are documented in this file. The format is b## [Unreleased]+### Added++- **Stream viewer direction filter** (follow-up to #380): the Traffic detail's Stream tab can show all messages, client-to-server messages or server-to-client messages. Pagination and refresh keep the selected direction, changing the filter resets the list, and recording-limit warnings remain visible.+### Fixed- **Live log subscribers can no longer crash the process**: a client disconnect closes its log channel. The sink now delivers a line while it still holds the subscriber lock, so that close cannot land in the middle of the send.diff --git a/scripts/verify.sh b/scripts/verify.shindex b6fb56c..1a1c72e 100755--- a/scripts/verify.sh+++ b/scripts/verify.sh@@ -130,6 +130,7 @@ if want_web; thenrun_step "web polling tests" bash -c 'cd web && npm run test:polling'run_step "web replay tests" bash -c 'cd web && npm run test:replay'run_step "web upload tests" bash -c 'cd web && npm run test:upload'+ run_step "web traffic stream tests" bash -c 'cd web && npm run test:traffic-stream'if [ "$FULL" -eq 1 ]; thenrun_step "web static build" bash -c 'cd web && npm run build:static'fidiff --git a/web/package.json b/web/package.jsonindex 70e9c00..1f6c97a 100644--- a/web/package.json+++ b/web/package.json@@ -17,6 +17,7 @@"test:replay": "node --test scripts/replay.test.mjs","test:tamper-hooks": "node --test scripts/tamper-hooks.test.mjs","test:upload": "node --test scripts/upload.test.mjs",+ "test:traffic-stream": "node --test scripts/traffic-stream.test.mjs","test:i18n": "node scripts/check-i18n.mjs && node --test scripts/i18n.test.mjs","test:bash": "node --test src/lib/bash-exit-status.test.mjs"},diff --git a/web/scripts/traffic-stream.test.mjs b/web/scripts/traffic-stream.test.mjsnew file mode 100644index 0000000..7b891c8--- /dev/null+++ b/web/scripts/traffic-stream.test.mjs@@ -0,0 +1,171 @@+import ts from "typescript";++import assert from "node:assert/strict";+import fs from "node:fs";+import path from "node:path";+import { test } from "node:test";+import { setImmediate } from "node:timers/promises";+import { fileURLToPath } from "node:url";+import vm from "node:vm";++const web = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");+const modules = new Map();++// Run the same TypeScript modules as the UI, without a browser or live server.+// Only the locale, mock switch and artificial mock delay are replaced.+function loadModule(file) {+ if (modules.has(file)) return modules.get(file);+ const exports = {};+ modules.set(file, exports);+ const output = ts.transpileModule(fs.readFileSync(file, "utf8"), {+ compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },+ }).outputText;+ vm.runInNewContext(output, {+ exports,+ Error,+ URL,+ URLSearchParams,+ TextEncoder,+ structuredClone,+ setTimeout: (callback) => callback(),+ require: (name) => {+ if (name === "@/i18n") return { t: (key) => key };+ if (name === "@/lib/mock/enabled") return { MOCK: true };+ const base = name.startsWith("@/")+ ? path.join(web, "src", name.slice(2))+ : path.resolve(path.dirname(file), name);+ return loadModule(`${base}.ts`);+ },+ });+ return exports;+}++const { createTrafficStreamPager } = loadModule(path.join(web, "src/lib/traffic-stream.ts"));+const { api } = loadModule(path.join(web, "src/lib/api.ts"));+const plain = (value) => JSON.parse(JSON.stringify(value));+// Await an event-loop turn so promises crossing the vm context also settle.+const flush = () => setImmediate();++function message(seq, direction = "c2s") {+ return { seq, direction, ts: seq, kind: 1, type: "text", size: 1, payload: String(seq) };+}++function pendingPager() {+ const calls = [];+ let state;+ const pager = createTrafficStreamPager(+ (...args) =>+ new Promise((resolve, reject) => {+ calls.push({ args, resolve, reject });+ }),+ (next) => {+ state = next;+ },+ );+ return { pager, calls, state: () => state };+}++test("API pages the selected direction and keeps original seqs and the limit warning", async () => {+ const all = await api.trafficStream("x-ws");+ assert.equal(all.total, 121);+ assert.equal(all.items.length, 50);+ assert.deepEqual(plain(all.items.slice(0, 2).map((item) => item.direction)), ["c2s", "s2c"]);++ for (const direction of ["c2s", "s2c"]) {+ const first = await api.trafficStream("x-ws", 0, 50, direction);+ const last = await api.trafficStream("x-ws", 50, 50, direction);+ assert.equal(first.total, 61);+ assert.equal(last.total, 61);+ assert.equal(first.items.length, 50);+ assert.equal(last.items.length, 11);+ assert.equal(first.items[0].seq, direction === "c2s" ? 1 : 2);+ assert.equal(last.items[0].seq, direction === "c2s" ? 101 : 102);+ assert.ok(+ [...first.items, ...last.items].every((item) => item.direction === direction || item.direction === "meta"),+ );+ assert.equal(last.items.at(-1).type, "meta");+ assert.equal(last.items.at(-1).seq, 121);+ }+});++test("mock stream details expose both protocols and an empty SSE client direction", async () => {+ assert.equal((await api.trafficExchange("x-ws")).stream_kind, "websocket");+ assert.equal((await api.trafficExchange("x-sse")).stream_kind, "sse");+ assert.equal((await api.trafficExchange("x-9")).stream_kind, undefined);+ assert.deepEqual(plain(await api.trafficStream("x-sse", 0, 50, "c2s")), { items: [], total: 0 });+ assert.equal((await api.trafficStream("x-sse", 0, 50, "s2c")).total, 3);+});++test("changing the filter or exchange resets pagination and discards a stale response", async () => {+ const p = pendingPager();+ p.pager.select("ws", "c2s");+ p.calls[0].resolve({ items: [message(1), message(3)], total: 60 });+ await flush();+ p.pager.loadMore();++ p.pager.select("ws", "s2c");+ assert.deepEqual(plain(p.state().items), []);+ assert.equal(p.state().total, 0);+ assert.equal(p.state().loadingMore, false);+ assert.deepEqual(p.calls[2].args, ["ws", 0, 50, "s2c"]);+ p.calls[1].resolve({ items: [message(5)], total: 60 });+ await flush();+ assert.deepEqual(plain(p.state().items), []);+ assert.equal(p.state().loading, true);++ p.pager.select("sse", "s2c");+ p.calls[2].resolve({ items: [message(2, "s2c")], total: 60 });+ p.calls[3].resolve({ items: [message(1, "s2c")], total: 1 });+ await flush();+ assert.deepEqual(p.calls[3].args, ["sse", 0, 50, "s2c"]);+ assert.deepEqual(plain(p.state().items.map((item) => item.seq)), [1]);+ assert.equal(p.state().total, 1);+});++test("Load more uses the filtered offset, and Refresh invalidates a pending page and its error", async () => {+ const p = pendingPager();+ p.pager.select("ws", "s2c");+ p.calls[0].resolve({ items: [message(2, "s2c"), message(4, "s2c")], total: 4 });+ await flush();+ p.pager.loadMore();+ p.pager.loadMore();+ assert.equal(p.calls.length, 2);+ assert.deepEqual(p.calls[1].args, ["ws", 2, 50, "s2c"]);++ p.pager.refresh();+ assert.deepEqual(p.calls[2].args, ["ws", 0, 50, "s2c"]);+ p.calls[1].reject(new Error("old page failed"));+ await flush();+ assert.equal(p.state().error, null);+ assert.equal(p.state().loading, true);+ p.calls[2].resolve({ items: [message(2, "s2c")], total: 2 });+ await flush();+ p.pager.loadMore();+ assert.deepEqual(p.calls[3].args, ["ws", 1, 50, "s2c"]);+ p.calls[3].resolve({ items: [{ ...message(121, "meta"), type: "meta" }], total: 2 });+ await flush();+ assert.deepEqual(plain(p.state().items.map((item) => item.seq)), [2, 121]);+ p.pager.loadMore();+ assert.equal(p.calls.length, 4);+});++test("cancellation suppresses late results, and a current error can be refreshed", async () => {+ const p = pendingPager();+ p.pager.select("ws", "");+ p.pager.cancel();+ p.calls[0].resolve({ items: [message(1)], total: 1 });+ await flush();+ assert.deepEqual(plain(p.state().items), []);+ p.pager.select("sse", "c2s");+ p.calls[1].reject(new Error("connection lost"));+ await flush();+ assert.equal(p.state().error, "connection lost");+ assert.equal(p.state().loading, false);+ p.pager.refresh();+ assert.deepEqual(p.calls[2].args, ["sse", 0, 50, "c2s"]);+ p.calls[2].resolve({ items: [], total: 0 });+ await flush();+ assert.equal(p.state().error, null);+ assert.equal(p.state().loading, false);+ assert.equal(p.state().total, 0);+});diff --git a/web/src/app/(main)/function/traffic/_components/stream-messages.tsx b/web/src/app/(main)/function/traffic/_components/stream-messages.tsxindex 4ca0d01..eff71a8 100644--- a/web/src/app/(main)/function/traffic/_components/stream-messages.tsx+++ b/web/src/app/(main)/function/traffic/_components/stream-messages.tsx@@ -6,11 +6,12 @@ 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";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";import { intlLocale, t } from "@/i18n";+import { api } from "@/lib/api";+import { createTrafficStreamPager, emptyTrafficStreamState } from "@/lib/traffic-stream";+import type { TrafficStreamDirection, 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;@@ -107,52 +108,18 @@ function StreamMessageRow({ message }: { message: TrafficStreamMessage }) {// 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<TrafficStreamMessage[]>([]);- const [total, setTotal] = React.useState(0);- const [loading, setLoading] = React.useState(true);- const [loadingMore, setLoadingMore] = React.useState(false);- const [error, setError] = React.useState<string | null>(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],- );+ const [direction, setDirection] = React.useState<TrafficStreamDirection>("");+ const [{ items, total, loading, loadingMore, error }, setPage] = React.useState(emptyTrafficStreamState);+ const pager = React.useMemo(() => createTrafficStreamPager(api.trafficStream, setPage), []);React.useEffect(() => {- setItems([]);- setTotal(0);- load(0);- }, [load]);+ pager.select(exchangeId, direction);+ return pager.cancel;+ }, [exchangeId, direction, pager]);return (<div className="flex flex-col">- <div className="flex items-center gap-2 px-5 py-3 text-muted-foreground text-xs">+ <div className="flex flex-wrap items-center gap-2 px-5 py-3 text-muted-foreground text-xs"><span>{t("{kind} · {count} of {total} messages", {kind: kind === "websocket" ? "WebSocket" : "Server-Sent Events",@@ -160,7 +127,27 @@ export function StreamMessagesPanel({ exchangeId, kind }: { exchangeId: string;total,})}</span>- <Button variant="outline" size="xs" className="ml-auto" disabled={loading} onClick={() => load(0)}>+ <Select+ value={direction || "all"}+ onValueChange={(value) => {+ const next = value === "all" ? "" : (value as TrafficStreamDirection);+ if (next === direction) return;+ // Invalidate before the next effect, so an old page cannot land+ // between the selection event and the new filter's first request.+ pager.cancel();+ setDirection(next);+ }}+ >+ <SelectTrigger size="sm" className="ml-auto" aria-label={t("Message direction")}>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="all">{t("All directions")}</SelectItem>+ <SelectItem value="c2s">{t("client -> server")}</SelectItem>+ <SelectItem value="s2c">{t("server -> client")}</SelectItem>+ </SelectContent>+ </Select>+ <Button variant="outline" size="xs" disabled={loading} onClick={pager.refresh}><RefreshCwIcon className={loading ? "animate-spin" : undefined} />{t("Refresh")}</Button>@@ -182,7 +169,11 @@ export function StreamMessagesPanel({ exchangeId, kind }: { exchangeId: string;return <div className="p-5 text-destructive text-xs">{t("Failed to load messages: {error}", { error })}</div>;}if (items.length === 0) {- return <div className="p-5 text-muted-foreground text-xs">{t("No messages recorded for this stream.")}</div>;+ return (+ <div className="p-5 text-muted-foreground text-xs">+ {direction ? t("No messages recorded in this direction.") : t("No messages recorded for this stream.")}+ </div>+ );}return (<>@@ -193,7 +184,7 @@ export function StreamMessagesPanel({ exchangeId, kind }: { exchangeId: string;</div>{items.length < total && (<div className="flex justify-center p-4">- <Button variant="outline" size="sm" disabled={loadingMore} onClick={() => load(items.length)}>+ <Button variant="outline" size="sm" disabled={loadingMore} onClick={pager.loadMore}>{loadingMore && <Loader2Icon className="animate-spin" />}{t("Load more")}</Button>diff --git a/web/src/i18n/locales/tr.json b/web/src/i18n/locales/tr.jsonindex 263307c..05e42d6 100644--- a/web/src/i18n/locales/tr.json+++ b/web/src/i18n/locales/tr.json@@ -233,6 +233,7 @@"All assets": "Tüm varlıklar","All categories": "Tüm kategoriler","All channels": "Tüm kanallar",+ "All directions": "Tüm yönler","All findings": "Tüm bulgular","all intents of this task": "bu görevin tüm niyetleri","All legal liability and consequences arising from your violation of the above laws and regulations or of this Statement are borne by you alone and have nothing to do with this software's authors and contributors.": "Yukarıdaki yasa ve yönetmelikleri ya da bu Beyan'ı ihlal etmenizden doğan tüm hukuki sorumluluk ve sonuçlar yalnızca size aittir; bu yazılımın yazarları ve katkıda bulunanlarla hiçbir ilgisi yoktur.",@@ -1338,6 +1339,7 @@"Merge by task": "Göreve göre birleştir","Merge mode": "Birleştirme modu","Message copied": "Mesaj kopyalandı",+ "Message direction": "Mesaj yönü","Message sent to the agent on task timeout (the system attaches the task id and goals)": "Görev zaman aşımında ajana gönderilecek mesaj (sistem görev kimliğini ve hedefleri ekler)","Message sent to the agent when a finding is found (the system attaches task and finding details)": "Bir bulgu bulunduğunda ajana gönderilecek mesaj (sistem görev ve bulgu ayrıntılarını ekler)","Message sent to the agent when a goal is met (the system attaches the task and the met goal)": "Bir hedefe ulaşıldığında ajana gönderilecek mesaj (sistem görevi ve ulaşılan hedefi ekler)",@@ -1475,6 +1477,7 @@"No MCP servers yet; add one on the \"MCP\" page.": "Henüz MCP sunucusu yok; \"MCP\" sayfasından ekleyin.","No merge": "Birleştirme yok","No messages recorded for this stream.": "Bu akış için kaydedilmiş mesaj yok.",+ "No messages recorded in this direction.": "Bu yönde kaydedilmiş mesaj yok.","No model matches “{query}”": "“{query}” ile eşleşen model yok","No model profiles yet — click \"Create\" in the top right to add the first one.": "Henüz model profili yok — ilkini eklemek için sağ üstteki \"Oluştur\" düğmesine tıklayın.","no models returned": "hiç model döndürülmedi",diff --git a/web/src/i18n/locales/zh-CN.json b/web/src/i18n/locales/zh-CN.jsonindex 2256d8b..adc28f7 100644--- a/web/src/i18n/locales/zh-CN.json+++ b/web/src/i18n/locales/zh-CN.json@@ -233,6 +233,7 @@"All assets": "全部资产","All categories": "全部分类","All channels": "全部渠道",+ "All directions": "全部方向","All findings": "全部发现","all intents of this task": "本任务全部意图","All legal liability and consequences arising from your violation of the above laws and regulations or of this Statement are borne by you alone and have nothing to do with this software's authors and contributors.": "因您违反上述法律法规或本声明约定而产生的一切法律责任与后果,均由您本人独立承担,与本软件作者及贡献者无关。",@@ -1338,6 +1339,7 @@"Merge by task": "按任务合并","Merge mode": "合并模式","Message copied": "已复制报文",+ "Message direction": "消息方向","Message sent to the agent on task timeout (the system attaches the task id and goals)": "任务超时时发给 agent 的话(系统会附带任务编号与目标)","Message sent to the agent when a finding is found (the system attaches task and finding details)": "发现 finding 时发给 agent 的话(系统会附带任务与 finding 详情)","Message sent to the agent when a goal is met (the system attaches the task and the met goal)": "目标达成时发给 agent 的话(系统会附带任务与达成的目标)",@@ -1475,6 +1477,7 @@"No MCP servers yet; add one on the \"MCP\" page.": "暂无 MCP,可在「MCP」页添加。","No merge": "不合并","No messages recorded for this stream.": "此流尚未录制任何消息。",+ "No messages recorded in this direction.": "此方向尚未录制任何消息。","No model matches “{query}”": "没有匹配“{query}”的模型","No model profiles yet — click \"Create\" in the top right to add the first one.": "还没有模型配置,点击右上角「新建」创建第一个。","no models returned": "未返回模型",diff --git a/web/src/lib/api.ts b/web/src/lib/api.tsindex 790be32..c1be514 100644--- a/web/src/lib/api.ts+++ b/web/src/lib/api.ts@@ -114,6 +114,7 @@ import type {TrafficReplayRequest,TrafficReplayResult,TrafficResp,+ TrafficStreamDirection,TrafficStreamPage,UsageStats,WorkspaceFile,@@ -871,8 +872,10 @@ export const api = {),trafficExchange: (id: string) => get<TrafficDetail>(`/traffic/exchange?id=${encodeURIComponent(id)}`),// One page of a WebSocket/SSE exchange's messages, in order.- trafficStream: (id: string, offset = 0, limit = 50) =>- get<TrafficStreamPage>(`/traffic/stream?exchange=${encodeURIComponent(id)}&offset=${offset}&limit=${limit}`),+ trafficStream: (id: string, offset = 0, limit = 50, direction: TrafficStreamDirection = "") =>+ get<TrafficStreamPage>(+ `/traffic/stream?exchange=${encodeURIComponent(id)}&offset=${offset}&limit=${limit}${direction ? `&direction=${direction}` : ""}`,+ ),// 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) => {diff --git a/web/src/lib/mock/data.ts b/web/src/lib/mock/data.tsindex f5094a7..f5f3e49 100644--- a/web/src/lib/mock/data.ts+++ b/web/src/lib/mock/data.ts@@ -43,6 +43,7 @@ import type {TrafficDetail,TrafficHost,TrafficResp,+ TrafficStreamMessage,} from "@/lib/types";const T = (iso: string) => iso; // readability helper for timestamps@@ -2883,6 +2884,8 @@ const exchanges = [["x-17", "10.10.10.20", "GET", "http://10.10.10.20:8080/script", 200, "text/html", 14200],["x-18", "10.10.10.20", "POST", "http://10.10.10.20:8080/scriptText", 200, "text/plain", 86],["x-19", "10.10.10.10", "POST", "https://10.10.10.10:445/psexec", 200, "application/octet-stream", 0],+ ["x-ws", "api.acme.com", "GET", "wss://api.acme.com/live", 101, "websocket", 3600],+ ["x-sse", "api.acme.com", "GET", "https://api.acme.com/events", 200, "text/event-stream", 90],] as const;export const traffic: TrafficResp = {@@ -2931,6 +2934,64 @@ Content-Length: 655}`,};+// More than one page in either direction, with original seqs and a recording+// limit warning. The SSE sample also lets the viewer exercise an empty c2s page.+export const trafficStreamMessages: Record<string, TrafficStreamMessage[]> = {+ "x-ws": [+ ...Array.from({ length: 120 }, (_, index): TrafficStreamMessage => {+ const direction = index % 2 === 0 ? "c2s" : "s2c";+ const payload = JSON.stringify({ action: direction === "c2s" ? "subscribe" : "update", order: index + 1 });+ return {+ seq: index + 1,+ ts: 1794618000 + index,+ direction,+ kind: 1,+ type: "text",+ size: payload.length,+ payload,+ };+ }),+ {+ seq: 121,+ ts: 1794618120,+ direction: "meta",+ kind: 0,+ type: "meta",+ size: 46,+ payload: '{"dropped_messages":3,"dropped_bytes":1024000}',+ },+ ],+ "x-sse": Array.from({ length: 3 }, (_, index): TrafficStreamMessage => {+ const payload = JSON.stringify({ status: "running", progress: (index + 1) * 10 });+ return {+ seq: index + 1,+ ts: 1794618000 + index,+ direction: "s2c",+ kind: 0,+ type: "event",+ event: "progress",+ event_id: String(index + 1),+ size: payload.length,+ payload,+ };+ }),+};++export const trafficStreamDetails: Record<string, TrafficDetail> = {+ "x-ws": {+ req: "GET /live HTTP/1.1\nHost: api.acme.com\nConnection: Upgrade\nUpgrade: websocket\n\n",+ resp: "HTTP/1.1 101 Switching Protocols\nConnection: Upgrade\nUpgrade: websocket\n\n",+ stream_kind: "websocket",+ stream_count: trafficStreamMessages["x-ws"].length,+ },+ "x-sse": {+ req: "GET /events HTTP/1.1\nHost: api.acme.com\nAccept: text/event-stream\n\n",+ resp: "HTTP/1.1 200 OK\nContent-Type: text/event-stream\n\n",+ stream_kind: "sse",+ stream_count: trafficStreamMessages["x-sse"].length,+ },+};+// ── Security / Audit ─────────────────────────────────────────────────────────export const audit: Audit = {attributions: { allow: 312, block: 9 },diff --git a/web/src/lib/mock/handler.ts b/web/src/lib/mock/handler.tsindex 9a65cf2..8d75cb5 100644--- a/web/src/lib/mock/handler.ts+++ b/web/src/lib/mock/handler.ts@@ -2246,7 +2246,18 @@ function route(m: string, path: string, seg: string[], q: URLSearchParams, b: Reif (path === "/traffic/hosts" && m === "DELETE") return { deleted: (b.hosts as unknown[])?.length ?? 0 };if (path === "/traffic/hosts") return { hosts: D.trafficHosts };if (path === "/traffic") return D.traffic;- if (path === "/traffic/exchange") return D.trafficDetail;+ if (path === "/traffic/exchange") return D.trafficStreamDetails[q.get("id") ?? ""] ?? D.trafficDetail;+ if (path === "/traffic/stream") {+ const direction = (q.get("direction") ?? "").trim().toLowerCase();+ if (direction && direction !== "c2s" && direction !== "s2c") throw new Error("invalid stream direction");+ const items = (D.trafficStreamMessages[q.get("exchange") ?? ""] ?? []).filter(+ (message) => !direction || message.direction === direction || message.direction === "meta",+ );+ const offset = Math.max(0, Number(q.get("offset")) || 0);+ const requestedLimit = Number(q.get("limit"));+ const limit = requestedLimit > 0 ? Math.min(200, requestedLimit) : 50;+ return { items: items.slice(offset, offset + limit), total: items.length };+ }if (path === "/settings" && m === "GET") return D.settings;if (path === "/settings" && m === "PUT") return { ...D.settings, ...b };if (path === "/settings/web-search/test") return { ok: true, count: 5, backend: D.settings.web_search_backend };diff --git a/web/src/lib/traffic-stream.ts b/web/src/lib/traffic-stream.tsnew file mode 100644index 0000000..f3a648f--- /dev/null+++ b/web/src/lib/traffic-stream.ts@@ -0,0 +1,76 @@+import type { TrafficStreamDirection, TrafficStreamMessage, TrafficStreamPage } from "./types";++export interface TrafficStreamState {+ items: TrafficStreamMessage[];+ total: number;+ loading: boolean;+ loadingMore: boolean;+ error: string | null;+}++export function emptyTrafficStreamState(): TrafficStreamState {+ return { items: [], total: 0, loading: true, loadingMore: false, error: null };+}++type FetchPage = (+ id: string,+ offset: number,+ limit: number,+ direction: TrafficStreamDirection,+) => Promise<TrafficStreamPage>;++// Offsets count rows in the filtered result, not the original stream's seq.+// Every refresh/selection invalidates pending pages, including their errors.+export function createTrafficStreamPager(fetchPage: FetchPage, onChange: (state: TrafficStreamState) => void) {+ let state = emptyTrafficStreamState();+ let generation = 0;+ let exchangeId = "";+ let direction: TrafficStreamDirection = "";++ function update(patch: Partial<TrafficStreamState>) {+ state = { ...state, ...patch };+ onChange(state);+ }++ async function load(offset: number) {+ const gen = ++generation;+ update({+ ...(offset === 0 ? { items: [], total: 0 } : {}),+ loading: offset === 0,+ loadingMore: offset > 0,+ error: null,+ });+ try {+ const page = await fetchPage(exchangeId, offset, 50, direction);+ if (gen !== generation) return;+ update({+ items: offset === 0 ? (page.items ?? []) : [...state.items, ...(page.items ?? [])],+ total: page.total ?? 0,+ loading: false,+ loadingMore: false,+ });+ } catch (error) {+ if (gen !== generation) return;+ update({ error: error instanceof Error ? error.message : String(error), loading: false, loadingMore: false });+ }+ }++ return {+ select(id: string, nextDirection: TrafficStreamDirection) {+ exchangeId = id;+ direction = nextDirection;+ void load(0);+ },+ refresh() {+ void load(0);+ },+ loadMore() {+ // Guard synchronously, before React renders a disabled Load more button.+ if (state.loading || state.loadingMore || state.items.length >= state.total) return;+ void load(state.items.length);+ },+ cancel() {+ ++generation;+ },+ };+}diff --git a/web/src/lib/types.ts b/web/src/lib/types.tsindex e8b23a2..8105c22 100644--- a/web/src/lib/types.ts+++ b/web/src/lib/types.ts@@ -976,6 +976,8 @@ export interface TrafficStreamMessage {truncated?: boolean;}+export type TrafficStreamDirection = "" | "c2s" | "s2c";+export interface TrafficStreamPage {items: TrafficStreamMessage[];total: number;