From 7e555e86d7bef13b72adea2d0449897b1cab8076 Mon Sep 17 00:00:00 2001 From: APZN <129354802+jsk1004ha@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:26:56 +0900 Subject: [PATCH] fix(web): reset stream filters and exclude warning rows from counts Reset the stream panel's filter and request state when the exchange changes. Keep recording-limit warnings visible while reporting only actual messages in the header, including first-page and warning-only counts. Add message_total to the stream page without changing raw pagination totals or existing Go paging signatures. Cover the count and pagination boundaries in the stream and HTTP route tests. --- CHANGELOG.md | 2 +- server/server.go | 5 +- server/traffic_stream_test.go | 36 ++++++-- traffic/stream.go | 36 ++++++-- traffic/stream_direction_test.go | 50 ++++++++++ web/scripts/traffic-stream.test.mjs | 91 ++++++++++++++++--- .../traffic/_components/stream-messages.tsx | 41 +++++---- web/src/lib/mock/handler.ts | 6 +- web/src/lib/traffic-stream.ts | 6 +- web/src/lib/types.ts | 2 + 10 files changed, 225 insertions(+), 50 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6dce878..3ee1e5e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ All notable changes to this project are documented in this file. The format is b ### 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. +- **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 opening another exchange resets the direction to all. Recording-limit warnings remain visible but are excluded from the displayed message counts. - **Security response headers on every response**: `X-Content-Type-Options: nosniff`, a same-origin referrer policy, `X-Frame-Options: SAMEORIGIN` and a `frame-ancestors 'self'` CSP are now set by one wrapper around the whole handler tree, so the JSON API carries them too; previously only the console route did. Console documents additionally get `Permissions-Policy` and COOP/CORP. `Strict-Transport-Security` is sent only when the request is known to be HTTPS: directly over TLS, or via `X-Forwarded-Proto: https` from a peer in `ARTEX_TRUSTED_PROXIES`, so a direct client cannot claim HTTPS on its own. The README reverse-proxy recipe now starts with an 80 to 443 redirect. - **Global company switcher**: the sidebar header carries a company picker (search, an explicit "all companies", the asset count). It persists per browser and narrows these views on the server: the findings list, grouped view, asset tree and stat cards (`GET /api/exploration/findings`, `/groups`, `/asset-tree`, `/stats` take `company`), the dashboard findings panels (same list endpoint), the task list (`GET /api/tasks?company=`), the traffic list (`GET /api/traffic?company=`, the hosts the company owns) and the asset tabs (`GET /api/assets?company_id=`, plain and DSL path; the company clause is ANDed outside the compiled DSL). A finding belongs to a company through its live assets. A finding with no live asset belongs to a company only when its task is scoped to that company (`task_scope` kind `company`); otherwise it shows under "all companies" only. An unknown or non-numeric company id returns nothing (#425). diff --git a/server/server.go b/server/server.go index e8fde7e..78eb3c1 100644 --- a/server/server.go +++ b/server/server.go @@ -3715,6 +3715,7 @@ func (s *Server) getTrafficExchange(w http.ResponseWriter, r *http.Request) { // getTrafficStream returns one page of a WebSocket/SSE exchange's messages in // order (limit 1..200, default 50). direction=c2s or s2c keeps one side of the // conversation (plus the meta limit marker); any other non-empty value is a 400. +// total counts rows for pagination; message_total excludes meta limit markers. func (s *Server) getTrafficStream(w http.ResponseWriter, r *http.Request) { tr := s.m.Traffic() if tr == nil { @@ -3730,7 +3731,7 @@ func (s *Server) getTrafficStream(w http.ResponseWriter, r *http.Request) { offset, _ := strconv.Atoi(q.Get("offset")) limit, _ := strconv.Atoi(q.Get("limit")) direction := strings.ToLower(strings.TrimSpace(q.Get("direction"))) - msgs, total, err := tr.StreamMessagesByDirection(id, direction, offset, limit) + page, err := tr.StreamMessagePageByDirection(id, direction, offset, limit) if errors.Is(err, traffic.ErrBadStreamDirection) { writeErr(w, 400, err.Error()) return @@ -3739,7 +3740,7 @@ func (s *Server) getTrafficStream(w http.ResponseWriter, r *http.Request) { writeErr(w, 500, err.Error()) return } - writeJSON(w, 200, map[string]any{"items": msgs, "total": total}) + writeJSON(w, 200, page) } // maxReplayRequestBytes bounds the replay request body (JSON, with the payload diff --git a/server/traffic_stream_test.go b/server/traffic_stream_test.go index 4e3f1cd..1448ea6 100644 --- a/server/traffic_stream_test.go +++ b/server/traffic_stream_test.go @@ -41,7 +41,8 @@ VALUES('1-0001',1,'ws.example.com','GET','/ws','wss://ws.example.com/ws',101,'we Payload string `json:"payload"` Encoding string `json:"encoding"` } `json:"items"` - Total int `json:"total"` + Total int `json:"total"` + MessageTotal *int `json:"message_total"` } get := func(path string, wantStatus int) page { t.Helper() @@ -54,16 +55,19 @@ VALUES('1-0001',1,'ws.example.com','GET','/ws','wss://ws.example.com/ws',101,'we if err := json.Unmarshal(w.Body.Bytes(), &p); err != nil { t.Fatalf("GET %s: %v in %s", path, err, w.Body) } + if p.MessageTotal == nil { + t.Fatalf("GET %s: message_total missing in %s", path, w.Body) + } } return p } get("/api/traffic/stream", 400) - if p := get("/api/traffic/stream?exchange=nope", 200); p.Items == nil || len(p.Items) != 0 || p.Total != 0 { + if p := get("/api/traffic/stream?exchange=nope", 200); p.Items == nil || len(p.Items) != 0 || p.Total != 0 || *p.MessageTotal != 0 { t.Fatalf("unknown exchange = %+v, want items [] and total 0", p) } p := get("/api/traffic/stream?exchange=1-0001", 200) - if p.Total != total || len(p.Items) != 50 || p.Items[0].Seq != 1 { + if p.Total != total || *p.MessageTotal != total || len(p.Items) != 50 || p.Items[0].Seq != 1 { t.Fatalf("default page: total %d, %d items, first seq %d", p.Total, len(p.Items), p.Items[0].Seq) } if first, second := p.Items[0], p.Items[1]; first.Type != "text" || first.Payload != "hello" || second.Type != "binary" || second.Encoding != "base64" || second.Payload != "AAEC" { @@ -112,7 +116,8 @@ VALUES('1-0002',1,'ws.example.com','GET','/ws','wss://ws.example.com/ws',101,'we Seq int64 `json:"seq"` Direction string `json:"direction"` } `json:"items"` - Total int `json:"total"` + Total int `json:"total"` + MessageTotal *int `json:"message_total"` } get := func(query string) page { t.Helper() @@ -124,6 +129,9 @@ VALUES('1-0002',1,'ws.example.com','GET','/ws','wss://ws.example.com/ws',101,'we if err := json.Unmarshal(w.Body.Bytes(), &p); err != nil { t.Fatal(err) } + if p.MessageTotal == nil { + t.Fatalf("GET %s: message_total missing in %s", query, w.Body) + } return p } seqs := func(p page) []int64 { @@ -134,19 +142,31 @@ VALUES('1-0002',1,'ws.example.com','GET','/ws','wss://ws.example.com/ws',101,'we return out } - if p := get(""); p.Total != 5 || len(p.Items) != 5 { + if p := get(""); p.Total != 5 || *p.MessageTotal != 4 || len(p.Items) != 5 { t.Fatalf("unfiltered = %+v", p) } - if p := get("&direction=c2s"); p.Total != 3 || fmt.Sprint(seqs(p)) != "[1 3 5]" { + if p := get("&direction=c2s"); p.Total != 3 || *p.MessageTotal != 2 || fmt.Sprint(seqs(p)) != "[1 3 5]" { t.Fatalf("c2s = total %d seqs %v, want 3 and [1 3 5]", p.Total, seqs(p)) } - if p := get("&direction=S2C"); p.Total != 3 || fmt.Sprint(seqs(p)) != "[2 4 5]" { + if p := get("&direction=S2C"); p.Total != 3 || *p.MessageTotal != 2 || fmt.Sprint(seqs(p)) != "[2 4 5]" { t.Fatalf("S2C = total %d seqs %v, want 3 and [2 4 5]", p.Total, seqs(p)) } - if p := get("&direction=s2c&offset=1&limit=1"); p.Total != 3 || fmt.Sprint(seqs(p)) != "[4]" { + if p := get("&direction=s2c&offset=1&limit=1"); p.Total != 3 || *p.MessageTotal != 2 || fmt.Sprint(seqs(p)) != "[4]" { t.Fatalf("s2c offset=1 limit=1 = total %d seqs %v, want 3 and [4]", p.Total, seqs(p)) } if w := request("GET", "/api/traffic/stream?exchange=1-0002&direction=meta", ""); w.Code != 400 { t.Fatalf("direction=meta = %d %s, want 400", w.Code, w.Body) } + if p := get("&direction=c2s&limit=1"); p.Total != 3 || *p.MessageTotal != 2 || fmt.Sprint(seqs(p)) != "[1]" { + t.Fatalf("first page without warning = %+v", p) + } + if p := get("&direction=c2s&offset=2&limit=1"); p.Total != 3 || *p.MessageTotal != 2 || fmt.Sprint(seqs(p)) != "[5]" { + t.Fatalf("warning page = %+v", p) + } + if _, err := db.Exec(`DELETE FROM stream_messages WHERE exchange_id='1-0002' AND direction='c2s'`); err != nil { + t.Fatal(err) + } + if p := get("&direction=c2s"); p.Total != 1 || *p.MessageTotal != 0 || fmt.Sprint(seqs(p)) != "[5]" { + t.Fatalf("warning-only direction = %+v", p) + } } diff --git a/traffic/stream.go b/traffic/stream.go index c70a3bc..deb6269 100644 --- a/traffic/stream.go +++ b/traffic/stream.go @@ -523,6 +523,15 @@ type StreamMessage struct { Truncated bool `json:"truncated,omitempty"` } +// StreamMessagePage keeps row totals for pagination separate from message +// totals for display. Items and Total include any 'meta' limit marker; +// MessageTotal counts only recorded WebSocket messages or SSE events. +type StreamMessagePage struct { + Items []StreamMessage `json:"items"` + Total int `json:"total"` + MessageTotal int `json:"message_total"` +} + // StreamMessages returns one page of an exchange's stream messages in order. // limit is 1..200 (default 50) and offset >= 0. Every payload comes back as at // most streamPreview (4 KiB); a longer one lives in the blob store and the row @@ -555,9 +564,17 @@ func streamDirectionFilter(direction string) (cond string, args []any, err error // The 'meta' row (messages dropped past the recorder's limits) is kept in a // filtered page. Seq stays the message's position in the whole stream. func (t *Traffic) StreamMessagesByDirection(exchangeID, direction string, offset, limit int) ([]StreamMessage, int, error) { + page, err := t.StreamMessagePageByDirection(exchangeID, direction, offset, limit) + return page.Items, page.Total, err +} + +// StreamMessagePageByDirection returns the same rows and pagination total as +// StreamMessagesByDirection, plus a message total that excludes limit markers. +// Both totals cover the entire filtered stream, regardless of offset or limit. +func (t *Traffic) StreamMessagePageByDirection(exchangeID, direction string, offset, limit int) (StreamMessagePage, error) { cond, dirArgs, err := streamDirectionFilter(direction) if err != nil { - return nil, 0, err + return StreamMessagePage{}, err } if limit <= 0 { limit = 50 @@ -568,25 +585,26 @@ func (t *Traffic) StreamMessagesByDirection(exchangeID, direction string, offset if offset < 0 { offset = 0 } - var total int + var page StreamMessagePage args := append([]any{exchangeID}, dirArgs...) - if err := t.db.QueryRow(`SELECT COUNT(*) FROM stream_messages WHERE exchange_id=?`+cond, args...).Scan(&total); err != nil { - return nil, 0, err + if err := t.db.QueryRow(`SELECT COUNT(*), COUNT(CASE WHEN direction <> 'meta' THEN 1 END) +FROM stream_messages WHERE exchange_id=?`+cond, args...).Scan(&page.Total, &page.MessageTotal); err != nil { + return StreamMessagePage{}, err } rows, err := t.db.Query(`SELECT seq,ts,direction,kind,event,event_id,retry,size,payload,payload_blob,truncated FROM stream_messages WHERE exchange_id=?`+cond+` ORDER BY seq LIMIT ? OFFSET ?`, append(args, limit, offset)...) if err != nil { - return nil, 0, err + return StreamMessagePage{}, err } defer rows.Close() - out := []StreamMessage{} + page.Items = []StreamMessage{} for rows.Next() { var m StreamMessage var payload []byte var blob sql.NullString var truncated int if err := rows.Scan(&m.Seq, &m.TS, &m.Direction, &m.Kind, &m.Event, &m.EventID, &m.Retry, &m.Size, &payload, &blob, &truncated); err != nil { - return nil, 0, err + return StreamMessagePage{}, err } m.Truncated = truncated != 0 m.Blob = blob.String @@ -610,9 +628,9 @@ FROM stream_messages WHERE exchange_id=?`+cond+` ORDER BY seq LIMIT ? OFFSET ?`, } else { m.Payload = truncateUTF8(payload, streamPreview) } - out = append(out, m) + page.Items = append(page.Items, m) } - return out, total, rows.Err() + return page, rows.Err() } // StreamInfo reports how many stream messages an exchange holds and whether it diff --git a/traffic/stream_direction_test.go b/traffic/stream_direction_test.go index 897e6b7..cfbfe1a 100644 --- a/traffic/stream_direction_test.go +++ b/traffic/stream_direction_test.go @@ -91,6 +91,56 @@ func TestStreamMessagesByDirectionKeepsMetaRow(t *testing.T) { } } +func TestStreamMessagePageCounts(t *testing.T) { + tr, id := directionStream(t, 2) + if _, err := tr.db.Exec(`INSERT INTO stream_messages(exchange_id,seq,ts,direction,kind,size,payload) +VALUES(?,5,1,'meta',0,2,'{}')`, id); err != nil { + t.Fatal(err) + } + + for _, tc := range []struct { + name, exchange, direction string + offset, total, messages int + seq int64 + }{ + {"all first page", id, "", 0, 5, 4, 1}, + {"client first page", id, "c2s", 0, 3, 2, 1}, + {"server first page", id, "s2c", 0, 3, 2, 2}, + {"client warning page", id, "c2s", 2, 3, 2, 5}, + {"server past last page", id, "s2c", 3, 3, 2, 0}, + {"unknown exchange", "missing", "c2s", 0, 0, 0, 0}, + } { + t.Run(tc.name, func(t *testing.T) { + // Limit 1 keeps the warning off the first page: the message total + // must describe the whole filtered stream, not only loaded rows. + page, err := tr.StreamMessagePageByDirection(tc.exchange, tc.direction, tc.offset, 1) + if err != nil || page.Total != tc.total || page.MessageTotal != tc.messages { + t.Fatalf("page = %+v, err %v; want total %d and message total %d", page, err, tc.total, tc.messages) + } + if tc.seq == 0 { + if page.Items == nil || len(page.Items) != 0 { + t.Fatalf("items = %+v, want []", page.Items) + } + } else if len(page.Items) != 1 || page.Items[0].Seq != tc.seq { + t.Fatalf("items = %+v, want seq %d", page.Items, tc.seq) + } + if tc.seq == 5 && page.Items[0].Type != "meta" { + t.Fatalf("warning page = %+v, want meta row", page.Items) + } + }) + } + + // A direction with no recorded messages still returns its warning, with a + // raw pagination total of one and a displayed message total of zero. + if _, err := tr.db.Exec(`DELETE FROM stream_messages WHERE exchange_id=? AND direction='c2s'`, id); err != nil { + t.Fatal(err) + } + page, err := tr.StreamMessagePageByDirection(id, "c2s", 0, 50) + if err != nil || page.Total != 1 || page.MessageTotal != 0 || len(page.Items) != 1 || page.Items[0].Type != "meta" { + t.Fatalf("warning-only page = %+v, err %v", page, err) + } +} + func TestTrafficMessagesToolDirection(t *testing.T) { tr, id := directionStream(t, 2) diff --git a/web/scripts/traffic-stream.test.mjs b/web/scripts/traffic-stream.test.mjs index 7b891c8..4826ed7 100644 --- a/web/scripts/traffic-stream.test.mjs +++ b/web/scripts/traffic-stream.test.mjs @@ -42,6 +42,7 @@ function loadModule(file) { const { createTrafficStreamPager } = loadModule(path.join(web, "src/lib/traffic-stream.ts")); const { api } = loadModule(path.join(web, "src/lib/api.ts")); +const { trafficStreamMessages } = loadModule(path.join(web, "src/lib/mock/data.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(); @@ -68,6 +69,7 @@ function pendingPager() { 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.message_total, 120); assert.equal(all.items.length, 50); assert.deepEqual(plain(all.items.slice(0, 2).map((item) => item.direction)), ["c2s", "s2c"]); @@ -76,6 +78,8 @@ test("API pages the selected direction and keeps original seqs and the limit war const last = await api.trafficStream("x-ws", 50, 50, direction); assert.equal(first.total, 61); assert.equal(last.total, 61); + assert.equal(first.message_total, 60); + assert.equal(last.message_total, 60); assert.equal(first.items.length, 50); assert.equal(last.items.length, 11); assert.equal(first.items[0].seq, direction === "c2s" ? 1 : 2); @@ -92,40 +96,66 @@ test("mock stream details expose both protocols and an empty SSE client directio 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); + assert.deepEqual(plain(await api.trafficStream("x-sse", 0, 50, "c2s")), { + items: [], + total: 0, + message_total: 0, + }); + const events = await api.trafficStream("x-sse", 0, 50, "s2c"); + assert.equal(events.total, 3); + assert.equal(events.message_total, 3); +}); + +test("warning-only results keep the recording warning with a zero message total", async () => { + const id = "test-sse-with-limit"; + const warning = { ...message(4, "meta"), type: "meta" }; + trafficStreamMessages[id] = [...trafficStreamMessages["x-sse"], warning]; + try { + const page = await api.trafficStream(id, 0, 50, "c2s"); + assert.equal(page.total, 1); + assert.equal(page.message_total, 0); + assert.deepEqual(plain(page.items), [warning]); + const beyond = await api.trafficStream(id, 1, 50, "c2s"); + assert.equal(beyond.total, 1); + assert.equal(beyond.message_total, 0); + assert.deepEqual(plain(beyond.items), []); + } finally { + delete trafficStreamMessages[id]; + } }); 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 }); + p.calls[0].resolve({ items: [message(1), message(3)], total: 60, message_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().messageTotal, 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 }); + p.calls[1].resolve({ items: [message(5)], total: 60, message_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 }); + p.calls[2].resolve({ items: [message(2, "s2c")], total: 60, message_total: 60 }); + p.calls[3].resolve({ items: [message(1, "s2c")], total: 1, message_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); + assert.equal(p.state().messageTotal, 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 }); + p.calls[0].resolve({ items: [message(2, "s2c"), message(4, "s2c")], total: 4, message_total: 3 }); await flush(); p.pager.loadMore(); p.pager.loadMore(); @@ -138,13 +168,16 @@ test("Load more uses the filtered offset, and Refresh invalidates a pending page await flush(); assert.equal(p.state().error, null); assert.equal(p.state().loading, true); - p.calls[2].resolve({ items: [message(2, "s2c")], total: 2 }); + p.calls[2].resolve({ items: [message(2, "s2c")], total: 2, message_total: 1 }); await flush(); + assert.equal(p.state().messageTotal, 1); + // All actual messages are loaded, but the warning must still be fetched. 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 }); + p.calls[3].resolve({ items: [{ ...message(121, "meta"), type: "meta" }], total: 2, message_total: 1 }); await flush(); assert.deepEqual(plain(p.state().items.map((item) => item.seq)), [2, 121]); + assert.equal(p.state().messageTotal, 1); p.pager.loadMore(); assert.equal(p.calls.length, 4); }); @@ -153,7 +186,7 @@ test("cancellation suppresses late results, and a current error can be refreshed const p = pendingPager(); p.pager.select("ws", ""); p.pager.cancel(); - p.calls[0].resolve({ items: [message(1)], total: 1 }); + p.calls[0].resolve({ items: [message(1)], total: 1, message_total: 1 }); await flush(); assert.deepEqual(plain(p.state().items), []); p.pager.select("sse", "c2s"); @@ -163,9 +196,45 @@ test("cancellation suppresses late results, and a current error can be refreshed 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 }); + p.calls[2].resolve({ items: [], total: 0, message_total: 0 }); await flush(); assert.equal(p.state().error, null); assert.equal(p.state().loading, false); assert.equal(p.state().total, 0); + assert.equal(p.state().messageTotal, 0); +}); + +test("the pager keeps separate message and row totals through pagination and exchange changes", async () => { + let state; + const calls = []; + const pager = createTrafficStreamPager( + (...args) => { + calls.push(args); + return api.trafficStream(...args); + }, + (next) => { + state = next; + }, + ); + pager.select("x-ws", "c2s"); + await flush(); + assert.equal(state.items.length, 50); + assert.equal(state.total, 61); + assert.equal(state.messageTotal, 60); + assert.ok(state.items.every((item) => item.type !== "meta")); + pager.loadMore(); + await flush(); + assert.deepEqual(calls[1], ["x-ws", 50, 50, "c2s"]); + assert.equal(state.items.length, 61); + assert.equal(state.items.filter((item) => item.type !== "meta").length, 60); + assert.equal(state.messageTotal, 60); + assert.equal(state.items.at(-1).type, "meta"); + pager.loadMore(); + assert.equal(calls.length, 2); + + pager.select("x-sse", ""); + assert.equal(state.messageTotal, 0); + await flush(); + assert.equal(state.total, 3); + assert.equal(state.messageTotal, 3); }); diff --git a/web/src/app/(main)/function/traffic/_components/stream-messages.tsx b/web/src/app/(main)/function/traffic/_components/stream-messages.tsx index eff71a8..dbaf0ee 100644 --- a/web/src/app/(main)/function/traffic/_components/stream-messages.tsx +++ b/web/src/app/(main)/function/traffic/_components/stream-messages.tsx @@ -107,10 +107,19 @@ 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" }) { +type StreamMessagesProps = { exchangeId: string; kind: "websocket" | "sse" }; + +export function StreamMessagesPanel(props: StreamMessagesProps) { + // A different exchange starts with All directions and its own request state. + return ; +} + +function StreamMessages({ exchangeId, kind }: StreamMessagesProps) { const [direction, setDirection] = React.useState(""); - const [{ items, total, loading, loadingMore, error }, setPage] = React.useState(emptyTrafficStreamState); + const [{ items, total, messageTotal, loading, loadingMore, error }, setPage] = + React.useState(emptyTrafficStreamState); const pager = React.useMemo(() => createTrafficStreamPager(api.trafficStream, setPage), []); + const messageCount = items.filter((message) => message.type !== "meta").length; React.useEffect(() => { pager.select(exchangeId, direction); @@ -123,8 +132,8 @@ export function StreamMessagesPanel({ exchangeId, kind }: { exchangeId: string; {t("{kind} ยท {count} of {total} messages", { kind: kind === "websocket" ? "WebSocket" : "Server-Sent Events", - count: items.length, - total, + count: messageCount, + total: messageTotal, })} {t("Failed to load messages: {error}", { error })}; } - if (items.length === 0) { - return ( - - {direction ? t("No messages recorded in this direction.") : t("No messages recorded for this stream.")} - - ); - } return ( <> - - {items.map((m) => ( - - ))} - + {messageTotal === 0 && ( + + {direction ? t("No messages recorded in this direction.") : t("No messages recorded for this stream.")} + + )} + {items.length > 0 && ( + + {items.map((m) => ( + + ))} + + )} {items.length < total && ( diff --git a/web/src/lib/mock/handler.ts b/web/src/lib/mock/handler.ts index 8d75cb5..001e5da 100644 --- a/web/src/lib/mock/handler.ts +++ b/web/src/lib/mock/handler.ts @@ -2256,7 +2256,11 @@ function route(m: string, path: string, seg: string[], q: URLSearchParams, b: Re 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 }; + return { + items: items.slice(offset, offset + limit), + total: items.length, + message_total: items.filter((message) => message.direction !== "meta").length, + }; } if (path === "/settings" && m === "GET") return D.settings; if (path === "/settings" && m === "PUT") return { ...D.settings, ...b }; diff --git a/web/src/lib/traffic-stream.ts b/web/src/lib/traffic-stream.ts index f3a648f..094bb4c 100644 --- a/web/src/lib/traffic-stream.ts +++ b/web/src/lib/traffic-stream.ts @@ -3,13 +3,14 @@ import type { TrafficStreamDirection, TrafficStreamMessage, TrafficStreamPage } export interface TrafficStreamState { items: TrafficStreamMessage[]; total: number; + messageTotal: number; loading: boolean; loadingMore: boolean; error: string | null; } export function emptyTrafficStreamState(): TrafficStreamState { - return { items: [], total: 0, loading: true, loadingMore: false, error: null }; + return { items: [], total: 0, messageTotal: 0, loading: true, loadingMore: false, error: null }; } type FetchPage = ( @@ -35,7 +36,7 @@ export function createTrafficStreamPager(fetchPage: FetchPage, onChange: (state: async function load(offset: number) { const gen = ++generation; update({ - ...(offset === 0 ? { items: [], total: 0 } : {}), + ...(offset === 0 ? { items: [], total: 0, messageTotal: 0 } : {}), loading: offset === 0, loadingMore: offset > 0, error: null, @@ -46,6 +47,7 @@ export function createTrafficStreamPager(fetchPage: FetchPage, onChange: (state: update({ items: offset === 0 ? (page.items ?? []) : [...state.items, ...(page.items ?? [])], total: page.total ?? 0, + messageTotal: page.message_total, loading: false, loadingMore: false, }); diff --git a/web/src/lib/types.ts b/web/src/lib/types.ts index 570793d..b24a855 100644 --- a/web/src/lib/types.ts +++ b/web/src/lib/types.ts @@ -982,7 +982,9 @@ export type TrafficStreamDirection = "" | "c2s" | "s2c"; export interface TrafficStreamPage { items: TrafficStreamMessage[]; + // Pagination includes recording-limit rows; the message count does not. total: number; + message_total: number; } export interface TrafficReplayHeader {