From e7d616d430209bd396964fb3a5340e412d24e4db Mon Sep 17 00:00:00 2001 From: "Md. Asaduzzaman Nur" Date: Mon, 24 Aug 2026 13:35:17 +0600 Subject: [PATCH 1/3] The endpoints list in device side should not cutoff in small width devices. --- .../compose/InspectorDesignSystemPreviews.kt | 74 ++++++++++++++++++- .../ui/compose/InspectorListComponents.kt | 9 ++- .../ui/compose/InspectorObserveTrafficTab.kt | 1 + 3 files changed, 82 insertions(+), 2 deletions(-) diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDesignSystemPreviews.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDesignSystemPreviews.kt index 7db91f2..810e479 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDesignSystemPreviews.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDesignSystemPreviews.kt @@ -10,12 +10,15 @@ import android.content.res.Configuration import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding +import androidx.compose.material3.Checkbox +import androidx.compose.material3.Switch import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp @@ -118,9 +121,10 @@ private fun TonalListRowPreview() { Column(modifier = Modifier.padding(12.dp)) { TonalListRow( leadText = "GET", + titleMaxLines = 2, leadColor = DevConsoleTheme.colors.signal, leadContainerColor = DevConsoleTheme.colors.signalSoft, - title = "/v1/menu/store/8821", + title = "/v1/menu/store/8821db vdvbdv", subtitle = "api.acmeship.com · 210 ms", trailValue = "200", trailValueColor = DevConsoleTheme.colors.signal, @@ -131,6 +135,74 @@ private fun TonalListRowPreview() { } } +/** + * The slot-bearing [TonalListRow] shapes the plain [TonalListRowPreview] never reaches: the traffic + * tab's selection row (leading checkbox, selected `containerColor`, long-press), the Control tab's + * mock-rule row (trailing [Switch]) -- both `mergeDescendants = false`, so TalkBack keeps the row's + * own tap apart from the control's toggle -- the More tab's expandable row, and a purely + * informational row that takes no click at all. + */ +@Preview(name = "Dark", uiMode = Configuration.UI_MODE_NIGHT_YES, showBackground = true, backgroundColor = 0xFF0B0E0D) +@Preview(name = "Light", uiMode = Configuration.UI_MODE_NIGHT_NO, showBackground = true, backgroundColor = 0xFFF3F6EE) +@Composable +private fun TonalListRowVariantsPreview() { + var selected by remember { mutableStateOf(true) } + var mockEnabled by remember { mutableStateOf(true) } + var expanded by remember { mutableStateOf(false) } + DevConsoleTheme(darkTheme = isSystemInDarkTheme()) { + val colors = DevConsoleTheme.colors + Column { + TonalListRow( + leadText = "POST", + leadColor = colors.put, + leadContainerColor = colors.putSoft, + title = "/v1/orders", + subtitle = "api.acmeship.com · 12:04:31", + trailValue = "201", + trailValueColor = colors.put, + trailSubtitle = "88 ms", + containerColor = if (selected) colors.surface2 else Color.Transparent, + leading = { Checkbox(checked = selected, onCheckedChange = { selected = it }) }, + onClick = { selected = !selected }, + onLongClick = { selected = !selected }, + mergeDescendants = false, + ) + TonalListRow( + leadText = if (mockEnabled) "ON" else "OFF", + leadColor = if (mockEnabled) colors.signal else colors.muted, + leadContainerColor = if (mockEnabled) colors.signalSoft else colors.surface2, + title = "checkout-503", + subtitle = "POST /v1/checkout → 503 · 12 hits · 4m ago", + trailValue = "session", + trailValueColor = colors.muted, + trailContent = { Switch(checked = mockEnabled, onCheckedChange = { mockEnabled = it }) }, + onClick = {}, + mergeDescendants = false, + ) + TonalListRow( + leadText = "DB", + leadColor = colors.warn, + leadContainerColor = colors.warnSoft, + title = "orders.db", + subtitle = "4 tables · 1.2 MB", + trailValue = "3", + trailSubtitle = "indexes", + trailContent = { TonalRowExpandChevron(expanded) }, + onClick = { expanded = !expanded }, + ) + TonalListRow( + leadText = "SDK", + leadColor = colors.muted, + leadContainerColor = colors.surface2, + title = "io.devconsole", + subtitle = "Informational row -- no onClick, so the row grows no click semantics.", + trailValue = "1.2.3", + trailValueColor = colors.muted, + ) + } + } +} + @Preview(name = "Dark", uiMode = Configuration.UI_MODE_NIGHT_YES, showBackground = true, backgroundColor = 0xFF0B0E0D) @Preview(name = "Light", uiMode = Configuration.UI_MODE_NIGHT_NO, showBackground = true, backgroundColor = 0xFFF3F6EE) @Composable diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorListComponents.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorListComponents.kt index cf99b64..b00d454 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorListComponents.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorListComponents.kt @@ -107,6 +107,13 @@ internal fun TonalListRow( subtitle: String, trailValue: String, modifier: Modifier = Modifier, + /** + * Lines [title] may wrap to before it ellipsizes. `1` -- one line, the row's fixed 48dp shape -- + * for every list whose titles are scannable at a glance; raise it only where the title is the + * row's payload rather than its label (a log message, a crash reason) and truncating it loses + * the thing the reader came for. The row grows to fit, since its height is a `heightIn` floor. + */ + titleMaxLines: Int = 1, trailValueColor: Color = DevConsoleTheme.colors.ink, trailSubtitle: String? = null, containerColor: Color = Color.Transparent, @@ -160,7 +167,7 @@ internal fun TonalListRow( title, color = DevConsoleTheme.colors.ink, style = DevConsoleType.rowTitle, - maxLines = 1, + maxLines = titleMaxLines, overflow = TextOverflow.Ellipsis, ) Text( diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveTrafficTab.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveTrafficTab.kt index 6559f0e..0d0f897 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveTrafficTab.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveTrafficTab.kt @@ -379,6 +379,7 @@ private fun TrafficRow( leadColor = leadColor, leadContainerColor = leadBg, title = transaction.path.substringBefore('?'), + titleMaxLines = 2, subtitle = "${transaction.host} · ${formatCaptureClockTime(transaction.startedAtEpochMs)}$mockedSuffix", trailValue = transaction.statusCode?.toString() ?: "ERR", trailValueColor = statusTint(transaction.statusCode, colors), From 61dd19f43d8a27ad1a27e40ae918dbf14122a718 Mon Sep 17 00:00:00 2001 From: "Md. Asaduzzaman Nur" Date: Mon, 24 Aug 2026 14:35:48 +0600 Subject: [PATCH 2/3] Clear http traffic captures feature --- CHANGELOG.md | 45 ++++ docs/NETWORK_INSPECTOR.md | 11 + docs/PROTOCOL_REFERENCE.md | 10 + .../io/devconsole/FullInspectorDataSource.kt | 11 + .../AndroidInspectorExporterTest.kt | 2 + .../devconsole/FullInspectorDataSourceTest.kt | 42 ++++ sdk/network/api/network.api | 3 +- .../network/NetworkTransactionStore.kt | 11 +- .../InMemoryNetworkTransactionStoreTest.kt | 51 ++++ .../server/ktor/DevConsoleKtorModule.kt | 54 ++++- .../resources/devconsole-web/dashboard.js | 28 +++ .../main/resources/devconsole-web/index.html | 1 + .../server/ktor/NetworkClearRouteTest.kt | 226 ++++++++++++++++++ sdk/ui-compose/api/ui-compose.api | 18 ++ .../devconsole/ui/compose/InspectorAction.kt | 7 + .../ui/compose/InspectorDataSource.kt | 15 ++ .../ui/compose/InspectorNavComponents.kt | 14 ++ .../ui/compose/InspectorObserveGlyphs.kt | 15 +- .../ui/compose/InspectorObservePreviews.kt | 20 ++ .../ui/compose/InspectorObserveScreen.kt | 97 +++++++- .../ui/compose/InspectorViewModel.kt | 17 ++ .../ui/compose/InspectorViewModelTest.kt | 79 ++++++ 22 files changed, 761 insertions(+), 16 deletions(-) create mode 100644 sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/NetworkClearRouteTest.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 84d12e2..b9a2fcf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,51 @@ before it can reach a release. (There was briefly a separate `sdk:plugin-api` mo third-party plugin framework; it was removed before ever shipping — see Removed, below — so it never joined this list.) +## Unreleased + +Captured requests could only ever be discarded by restarting the session, so a long debugging run +turned the Traffic list into a haystack ([#23](https://github.com/devconsole-android/DevConsole/issues/23)). +Both operator surfaces can now clear them. + +**Version note, deliberately unresolved here:** `NetworkTransactionStore` gains an abstract +`clear()`. That interface is not documented as a host extension point and nothing outside this repo +is known to implement it, but under this file's own [policy](#versioning-and-stability-policy) a new +abstract member is source-breaking for anyone who does. It is in `sdk:network`, not `sdk:api`, so it +does not automatically read as a major. The number is left for the release decision rather than +assumed. + +### Added + +- **Clear captured requests**, on the device and in the browser. The in-app inspector grows a trash + action in the Observe screen's top area, shown on the Traffic tab once there is something to + discard; the dashboard's Network toolbar grows a **Clear captures** button beside the HAR and + Postman exports. Both confirm first, and both name what survives. + + The two surfaces share one store, so a clear on either empties the other on its next read. Captures + are held in memory only, which is what makes this irreversible and why the confirmation is not + optional. + + Evidence is deliberately spared: the tray holds materialized copies of flagged captures and + outlives the live buffer by design, so clearing never costs anyone the bug they were collecting. + Timeline events recorded for those requests are a separate store and are likewise untouched. + +- **`DELETE /api/v1/network/transactions`**, backing the dashboard button. Gated like the + evidence-tray mutations rather than by an editing capability — bearer session plus `Origin` and + `X-DevConsole-CSRF`, audited as `network.clear` — because it empties this SDK's own capture buffer + and never reaches host application state. Subject to the same `network` capture-category check as + the read routes, and idempotent: clearing an already-empty store is a plain success. See + [docs/PROTOCOL_REFERENCE.md](docs/PROTOCOL_REFERENCE.md). + +- **`InspectorDataSource.clearTransactions()`**, defaulting to `Unavailable` so existing adapters + keep compiling, and `InspectorAction.ClearTransactions` to reach it. + +### Changed + +- **`NetworkTransactionStore.clear()` is now part of the interface** rather than only of + `InMemoryNetworkTransactionStore`. The Ktor module holds its store through the interface, so the + new route could not otherwise reach it. Left abstract rather than given a no-op default: a custom + store that silently declined to clear would fail invisibly, which is worse than failing to compile. + ## 1.2.4 — 2026-08-20 ### Fixed diff --git a/docs/NETWORK_INSPECTOR.md b/docs/NETWORK_INSPECTOR.md index c284acd..31ca4c8 100644 --- a/docs/NETWORK_INSPECTOR.md +++ b/docs/NETWORK_INSPECTOR.md @@ -107,6 +107,17 @@ detail pane showing redacted headers and body. From the detail pane you can: export is available as an in-app action on the device — see [DATA_INSPECTORS_AND_EXPORTS.md](DATA_INSPECTORS_AND_EXPORTS.md). +The Network page's toolbar also carries **Clear captures** (`DELETE /api/v1/network/transactions`), +which discards every captured transaction on the device after a confirmation. The same action is +available in the in-app inspector, as the trash icon in the Observe screen's top area on the Traffic +tab. Either one empties the single shared store, so a clear on the device empties the dashboard's +list too (and vice versa) on its next read. + +Captures are held in memory only, so a clear cannot be undone. Anything flagged as evidence survives +it: the evidence tray stores materialized copies of flagged captures and outlives the live buffer by +design — see [EVIDENCE_AND_BUG_REPORTS.md](EVIDENCE_AND_BUG_REPORTS.md). Timeline events recorded for +those requests are a separate store and are likewise untouched. + The Overview page's network-status-distribution widget (`GET /api/v1/overview`) buckets recent transactions by `2xx`/`3xx`/`4xx`/`5xx`/`pending` via `NetworkTransactionStore.statusDistribution()`. diff --git a/docs/PROTOCOL_REFERENCE.md b/docs/PROTOCOL_REFERENCE.md index 507cc07..93374fc 100644 --- a/docs/PROTOCOL_REFERENCE.md +++ b/docs/PROTOCOL_REFERENCE.md @@ -183,6 +183,16 @@ id, if the selected transactions happen to share a dedup key; it can also make `X-DevConsole-Export-Count` (measured before dedup) read higher than the number of `item`s that actually end up in the Postman collection body. +`DELETE /api/v1/network/transactions` discards every captured transaction — the dashboard's "Clear +captures" toolbar button, and the counterpart of the in-app inspector's own clear action. Gated like +the evidence-tray mutations rather than by an editing capability: bearer session plus `Origin` and +`X-DevConsole-CSRF`, audited as `network.clear`, and subject to the same `network` capture-category +check as the read routes above (`CATEGORY_DISABLED` 403 when the host disabled the category). It +answers `{"status":"cleared"}` and is idempotent — clearing an already-empty store is a plain +success. Evidence is untouched: the tray holds materialized copies of flagged captures, so clearing +the live buffer never destroys collected evidence. Any outstanding pagination cursor is invalidated +by the shrink, per §4.2. + ### Mocks `GET /api/v1/mocks` (enabled flag), `POST /api/v1/mocks/disable-all` (auth), `POST diff --git a/sdk/full/src/main/kotlin/io/devconsole/FullInspectorDataSource.kt b/sdk/full/src/main/kotlin/io/devconsole/FullInspectorDataSource.kt index 5d4d889..9091381 100644 --- a/sdk/full/src/main/kotlin/io/devconsole/FullInspectorDataSource.kt +++ b/sdk/full/src/main/kotlin/io/devconsole/FullInspectorDataSource.kt @@ -819,6 +819,17 @@ internal class FullInspectorDataSource( return shareableFileResolver(root, relativePath)?.absolutePath } + /** + * Ungated by capability for the same reason the exports below are: this empties the SDK's own + * capture buffer and never reaches host application state. Evidence is untouched -- `EvidenceStore` + * holds materialized copies of flagged captures (see [flagTransaction]) and outlives the buffer + * by design. + */ + override fun clearTransactions(): InspectorCommandResult { + networkTransactionStore.clear() + return InspectorCommandResult.Success(summary = "Captured requests cleared") + } + /** * Ungated by capability: exports read already-captured, already-redacted data, the same as * [listFiles]/[previewFile]/[listTables] above. diff --git a/sdk/full/src/test/kotlin/io/devconsole/AndroidInspectorExporterTest.kt b/sdk/full/src/test/kotlin/io/devconsole/AndroidInspectorExporterTest.kt index 7eab59e..7a1e156 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/AndroidInspectorExporterTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/AndroidInspectorExporterTest.kt @@ -112,6 +112,8 @@ class AndroidInspectorExporterTest { override fun find(id: String): NetworkTransaction? = null override fun statusDistribution(): Map = emptyMap() + + override fun clear() = Unit } @Test diff --git a/sdk/full/src/test/kotlin/io/devconsole/FullInspectorDataSourceTest.kt b/sdk/full/src/test/kotlin/io/devconsole/FullInspectorDataSourceTest.kt index 55bb212..2fc1a01 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/FullInspectorDataSourceTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/FullInspectorDataSourceTest.kt @@ -502,6 +502,48 @@ class FullInspectorDataSourceTest { assertTrue(source.flaggedTransactionIds().isEmpty()) } + @Test + fun `clearTransactions empties the capture store and the snapshot it feeds`() { + val store = networkStore() + recordTransaction(store, "tx-1", startedAtEpochMs = 0, completedAtEpochMs = 5) + recordTransaction(store, "tx-2", startedAtEpochMs = 10, completedAtEpochMs = 15) + val source = FullInspectorDataSource(store, MockEngine(emptyList()), configSupplier = { null }) + assertEquals(2, source.snapshot().transactions.size) + + val result = source.clearTransactions() + + assertTrue(result is InspectorCommandResult.Success) + assertTrue(source.snapshot().transactions.isEmpty()) + assertNull(store.find("tx-1")) + } + + /** + * Evidence is durable and materialized at flag time -- clearing the live capture buffer must not + * take collected bug evidence with it. + */ + @Test + fun `clearTransactions leaves flagged evidence intact`() = + runTest { + val store = networkStore() + recordTransaction(store, "tx-1", startedAtEpochMs = 0, completedAtEpochMs = 5) + val evidence = FakeEvidenceStore() + val source = + FullInspectorDataSource( + store, + MockEngine(emptyList()), + configSupplier = { null }, + evidenceStore = evidence, + evidenceSessionId = { "session-1" }, + ) + source.flagTransaction("tx-1") + + source.clearTransactions() + + assertTrue(source.snapshot().transactions.isEmpty()) + assertEquals(setOf("tx-1"), source.flaggedTransactionIds()) + assertEquals(1, evidence.items("session-1").size) + } + @Test fun `flagTransaction surfaces AlreadyFlagged with a human-readable message instead of throwing or no-opping`() = runTest { diff --git a/sdk/network/api/network.api b/sdk/network/api/network.api index c1c54aa..05bcfb1 100644 --- a/sdk/network/api/network.api +++ b/sdk/network/api/network.api @@ -180,7 +180,7 @@ public final class io/devconsole/network/InMemoryNetworkTransactionStore : io/de public static final field DEFAULT_MAX_TRANSACTIONS I public fun (Lio/devconsole/network/NetworkCursorCodec;I)V public synthetic fun (Lio/devconsole/network/NetworkCursorCodec;IILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun clear ()V + public fun clear ()V public fun find (Ljava/lang/String;)Lio/devconsole/network/NetworkTransaction; public fun page (Lio/devconsole/network/NetworkTransactionQuery;)Lio/devconsole/network/NetworkTransactionPage; public fun record (Lio/devconsole/network/NetworkTransaction;)V @@ -551,6 +551,7 @@ public final class io/devconsole/network/NetworkTransactionRecorder$Companion { } public abstract interface class io/devconsole/network/NetworkTransactionStore { + public abstract fun clear ()V public abstract fun find (Ljava/lang/String;)Lio/devconsole/network/NetworkTransaction; public abstract fun page (Lio/devconsole/network/NetworkTransactionQuery;)Lio/devconsole/network/NetworkTransactionPage; public abstract fun record (Lio/devconsole/network/NetworkTransaction;)V diff --git a/sdk/network/src/main/kotlin/io/devconsole/network/NetworkTransactionStore.kt b/sdk/network/src/main/kotlin/io/devconsole/network/NetworkTransactionStore.kt index b5ae688..593b6b1 100644 --- a/sdk/network/src/main/kotlin/io/devconsole/network/NetworkTransactionStore.kt +++ b/sdk/network/src/main/kotlin/io/devconsole/network/NetworkTransactionStore.kt @@ -98,6 +98,15 @@ interface NetworkTransactionStore { fun find(id: String): NetworkTransaction? fun statusDistribution(): Map + + /** + * Discards every stored transaction. Backs the operator-facing "clear captures" affordance on + * both the in-app inspector and the dashboard, as well as the session-rollover reset in + * `PlatformFacadeProvider`. On the interface rather than only on + * [InMemoryNetworkTransactionStore] because callers that hold a store through this type -- the + * Ktor module's `networkTransactions`, notably -- are exactly the ones that need it. + */ + fun clear() } /** Bounded, thread-safe transaction store for the live network inspector. */ @@ -133,7 +142,7 @@ class InMemoryNetworkTransactionStore( return this } - fun clear() = + override fun clear() = synchronized(lock) { transactions.clear() storedBytes = 0 diff --git a/sdk/network/src/test/kotlin/io/devconsole/network/InMemoryNetworkTransactionStoreTest.kt b/sdk/network/src/test/kotlin/io/devconsole/network/InMemoryNetworkTransactionStoreTest.kt index 4539578..09032e4 100644 --- a/sdk/network/src/test/kotlin/io/devconsole/network/InMemoryNetworkTransactionStoreTest.kt +++ b/sdk/network/src/test/kotlin/io/devconsole/network/InMemoryNetworkTransactionStoreTest.kt @@ -170,6 +170,57 @@ class InMemoryNetworkTransactionStoreTest { assertEquals(listOf("matching"), page.transactions.map(NetworkTransaction::id)) } + @Test + fun `clear empties the store`() { + val store = InMemoryNetworkTransactionStore(NetworkCursorCodec("network-cursor-key".encodeToByteArray())) + store.record(transaction("first", 100, "GET", "https://api.test/first", 200)) + store.record(transaction("second", 200, "POST", "https://api.test/second", 201)) + + store.clear() + + assertEquals(emptyList(), store.page(NetworkTransactionQuery(limit = 10)).transactions) + assertNull(store.find("first")) + assertEquals(emptyMap(), store.statusDistribution()) + } + + /** + * [InMemoryNetworkTransactionStore] prunes on a running byte total, so a clear that emptied the + * list without zeroing that total would leave the store believing it still held the cleared + * bytes -- and evict freshly recorded captures to get back under a budget nothing is using. + */ + @Test + fun `clear resets the byte budget so later records are not evicted`() { + val store = + InMemoryNetworkTransactionStore( + NetworkCursorCodec("network-cursor-key".encodeToByteArray()), + maxTransactions = 10, + ).withByteCapacity(700) + val factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())) + val bulky = { id: String -> + NetworkTransaction( + id = id, + startedAtEpochMs = 1L, + completedAtEpochMs = 2L, + capture = + factory.capture( + NetworkRequestInput( + "POST", + "https://api.test/$id", + body = "x".repeat(500).encodeToByteArray(), + contentType = "text/plain", + ), + null, + ), + ) + } + store.record(bulky("before-clear")) + + store.clear() + store.record(bulky("after-clear")) + + assertEquals(listOf("after-clear"), store.page(NetworkTransactionQuery(limit = 10)).transactions.map { it.id }) + } + private fun transaction( id: String, startedAt: Long, diff --git a/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/DevConsoleKtorModule.kt b/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/DevConsoleKtorModule.kt index 0bd529f..5fd2d9b 100644 --- a/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/DevConsoleKtorModule.kt +++ b/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/DevConsoleKtorModule.kt @@ -1232,6 +1232,35 @@ fun Application.devConsoleModule( } call.respondNetworkTransactionPage(networkTransactions.page(query)) } + /** + * Discards every captured transaction -- the dashboard's "Clear" action beside the HAR and + * Postman exports, and the counterpart of the in-app inspector's own clear. + * + * Gated like the evidence-tray mutations rather than like a capability-guarded control + * route: it empties this SDK's own capture buffer and never reaches host application state. + * Evidence is deliberately left alone -- `EvidenceStore` holds materialized copies of + * flagged captures, so clearing the live buffer must not destroy collected bug evidence. + * + * Idempotent: clearing an already-empty store is a plain success, so the button never has to + * reason about whether anything is left to clear. + */ + delete("/api/v1/network/transactions") { + val session = + call.captureControlSession( + sessionAuthority, + commandAuditLog, + "network.clear", + "transactions", + ) ?: return@delete + if (!categoryEnabled("network")) { + commandAuditLog.recordControlFailure(session.id, "network.clear", "transactions") + call.respondCategoryDisabled("network") + return@delete + } + networkTransactions.clear() + commandAuditLog.recordControlSuccess(session.id, "network.clear", "transactions") + call.respondText("{\"status\":\"cleared\"}", contentType = io.ktor.http.ContentType.Application.Json) + } get("/api/v1/retained-events") { if (sessionAuthority.bearerSession(call.request.headers[HttpHeaders.Authorization]) == null) { call.respondText("{\"code\":\"AUTH_REQUIRED\"}", status = HttpStatusCode.Unauthorized) @@ -1774,7 +1803,7 @@ fun Application.devConsoleModule( } post("/api/v1/evidence") { val session = - call.evidenceControlSession( + call.captureControlSession( sessionAuthority, commandAuditLog, "evidence.flag", @@ -1852,7 +1881,7 @@ fun Application.devConsoleModule( delete("/api/v1/evidence/{kind}/{id}") { val subjectId = call.parameters["id"].orEmpty() val session = - call.evidenceControlSession( + call.captureControlSession( sessionAuthority, commandAuditLog, "evidence.unflag", @@ -1878,7 +1907,7 @@ fun Application.devConsoleModule( } delete("/api/v1/evidence") { val session = - call.evidenceControlSession( + call.captureControlSession( sessionAuthority, commandAuditLog, "evidence.clear", @@ -1896,7 +1925,7 @@ fun Application.devConsoleModule( } put("/api/v1/evidence/report") { val session = - call.evidenceControlSession( + call.captureControlSession( sessionAuthority, commandAuditLog, "evidence.report.save", @@ -1951,7 +1980,7 @@ fun Application.devConsoleModule( // so this route only needs to map every ScreenshotResult variant to its own response. post("/api/v1/screenshots") { val session = - call.evidenceControlSession( + call.captureControlSession( sessionAuthority, commandAuditLog, "screenshot.capture", @@ -4334,15 +4363,16 @@ private suspend fun io.ktor.server.application.ApplicationCall.composerExecution } /** - * Shared entry gate for every evidence-tray and screenshot mutation route: authenticated bearer - * session, then origin and CSRF. Unlike mocks/capture-rules/preferences/files/database, there is no - * separate editing capability here -- flagging evidence or capturing a screenshot never lets a - * session touch host application state, so this mirrors [isReadMutationAuthorized]'s two-stage gate - * (auth, then CSRF) rather than [mockRuleControlSession]'s three-stage one, while still auditing every - * rejection past authentication under [commandType] like every other command route. + * Shared entry gate for every mutation that touches only this SDK's own captured data -- the + * evidence tray, screenshots, and clearing the network capture buffer: authenticated bearer session, + * then origin and CSRF. Unlike mocks/capture-rules/preferences/files/database, there is no separate + * editing capability here -- flagging evidence, capturing a screenshot or discarding captures never + * lets a session touch host application state, so this mirrors [isReadMutationAuthorized]'s two-stage + * gate (auth, then CSRF) rather than [mockRuleControlSession]'s three-stage one, while still auditing + * every rejection past authentication under [commandType] like every other command route. */ @Suppress("ReturnCount") // One early-exit per gate stage (auth, CSRF) reads clearest. -private suspend fun io.ktor.server.application.ApplicationCall.evidenceControlSession( +private suspend fun io.ktor.server.application.ApplicationCall.captureControlSession( sessionAuthority: SessionAuthority, commandAuditLog: CommandAuditLog, commandType: String, diff --git a/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js b/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js index 183ead0..f13e6e7 100644 --- a/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js +++ b/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js @@ -5970,6 +5970,9 @@ // Note: the timeline note textarea/save button are rendered inside the event detail pane // (renderEventDetail) with their disabled state set directly from `token` at render time, // since they only exist in the DOM once an event is selected. + // Clearing is a CSRF-gated mutation, so it needs a full session, not just a read token. + $('networkClear').disabled = !enabled; + $('networkClear').title = enabled ? 'Discard every captured request on the device' : 'Connect this browser first'; $('quickExport').disabled = !token; // Capture is off by default on the host (ScreenshotPolicy.enabled = false) and no route // reports that ahead of time — this button is only @@ -7075,6 +7078,30 @@ async function downloadPostman() { await downloadNetworkExport('/api/v1/network/postman', 'devconsole-network.postman_collection.json'); } + /** + * DELETE /api/v1/network/transactions — discards every captured transaction on the device, then + * reloads so the list renders from the real post-clear server state rather than an assumed-empty + * local one (same reasoning as clearEvidenceTray). Confirmed first: captures live in memory only, + * so there is nothing to undo it with. The local selection is dropped too, since its ids no longer + * resolve to anything. + */ + async function clearNetworkCaptures() { + if (!hasSession()) return; + const ok = await openConfirm('Clear captured requests?', 'Every captured request is discarded on the device. Captures are held in memory only, so this cannot be undone. Anything flagged as evidence is kept.', 'Clear captures'); + if (!ok) return; + const r = await fetch('/api/v1/network/transactions', { method: 'DELETE', headers: controlHeaders() }); + if (r.ok) { + clearNetworkSelection(); + toast('Captured requests cleared.'); + } else { + // One read only — the body stream cannot be consumed twice. CATEGORY_DISABLED arrives nested + // under `error` (respondCategoryDisabled), every other code at the top level. + let code; + try { const body = await r.json(); code = body.code || body.error?.code; } catch { code = undefined; } + toast(code === 'CATEGORY_DISABLED' ? 'Network capture is disabled for this app run.' : 'Could not clear captures: ' + r.status, 'error'); + } + loadNetwork(); + } /** Backs the 'related' tab in renderNetworkDetail. Guarded against duplicate in-flight fetches * for the same id (a re-render can happen — e.g. focus restore — while the request is still * out) and only re-renders if that tab/transaction is still what's on screen when it resolves. */ @@ -7339,6 +7366,7 @@ $('networkOlder').onclick = () => networkCursor && loadNetwork(networkCursor); $('networkHarDownload').onclick = downloadHar; $('networkPostmanDownload').onclick = downloadPostman; + $('networkClear').onclick = clearNetworkCaptures; $('networkSelectAllVisible').onclick = () => toggleSelectAllVisibleNetwork(); $('networkSelectionBar').addEventListener('click', (e) => { const btn = e.target.closest('[data-sel-action]'); diff --git a/sdk/server-ktor/src/main/resources/devconsole-web/index.html b/sdk/server-ktor/src/main/resources/devconsole-web/index.html index 94ef5ab..8e27c88 100644 --- a/sdk/server-ktor/src/main/resources/devconsole-web/index.html +++ b/sdk/server-ktor/src/main/resources/devconsole-web/index.html @@ -241,6 +241,7 @@
+ diff --git a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/NetworkClearRouteTest.kt b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/NetworkClearRouteTest.kt new file mode 100644 index 0000000..7719127 --- /dev/null +++ b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/NetworkClearRouteTest.kt @@ -0,0 +1,226 @@ +/** + * @author Shakib + * @since 24/08/26 + */ +package io.devconsole.server.ktor + +import io.devconsole.network.InMemoryNetworkTransactionStore +import io.devconsole.network.NetworkCaptureFactory +import io.devconsole.network.NetworkCursorCodec +import io.devconsole.network.NetworkRequestInput +import io.devconsole.network.NetworkResponseInput +import io.devconsole.network.NetworkTransaction +import io.devconsole.network.NetworkTransactionQuery +import io.devconsole.security.RedactionEngine +import io.devconsole.security.RedactionPolicy +import io.devconsole.server.api.BrowserSession +import io.devconsole.server.api.CommandAuditResult +import io.devconsole.server.api.InMemoryCommandAuditLog +import io.devconsole.server.api.ServerMetadata +import io.devconsole.server.api.SessionAuthority +import io.devconsole.server.api.SessionCodeAuthority +import io.ktor.client.request.HttpRequestBuilder +import io.ktor.client.request.delete +import io.ktor.client.request.get +import io.ktor.client.request.header +import io.ktor.client.request.post +import io.ktor.client.request.setBody +import io.ktor.client.statement.bodyAsText +import io.ktor.http.ContentType +import io.ktor.http.HttpHeaders +import io.ktor.http.HttpStatusCode +import io.ktor.server.testing.ApplicationTestBuilder +import io.ktor.server.testing.testApplication +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * Covers `DELETE /api/v1/network/transactions` -- the dashboard's "clear captures" action. Follows + * [EvidenceAndScreenshotRoutesTest]'s fixture conventions (same `approvedSession`/`controlHeaders` + * pattern, same `testApplication` setup), since this route shares that family's gate: authenticated + * bearer session plus origin/CSRF, with no separate editing capability. + */ +class NetworkClearRouteTest { + @Test + fun `clearing requires an authenticated session`() = + testApplication { + val store = networkStore("tx-1") + application { devConsoleModule(SessionAuthority()) { networkTransactions = store } } + + val response = client.delete("/api/v1/network/transactions") { header(HttpHeaders.Host, "localhost") } + + assertEquals(HttpStatusCode.Unauthorized, response.status) + assertTrue(response.bodyAsText().contains("AUTH_REQUIRED")) + assertEquals(1, store.page(NetworkTransactionQuery(limit = 10)).transactions.size) + } + + @Test + fun `clearing requires csrf and is audited on rejection`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + val audit = InMemoryCommandAuditLog() + val store = networkStore("tx-1") + application { + devConsoleModule(sessions, sessionCodes) { + networkTransactions = store + commandAuditLog = audit + } + } + val session = approvedSession(sessions, sessionCodes) + + val response = + client.delete("/api/v1/network/transactions") { + header(HttpHeaders.Host, "localhost") + header(HttpHeaders.Authorization, "Bearer ${session.token}") + } + + assertEquals(HttpStatusCode.Forbidden, response.status) + assertTrue(response.bodyAsText().contains("CSRF_INVALID")) + assertTrue(audit.events().any { it.commandType == "network.clear" }) + assertEquals(1, store.page(NetworkTransactionQuery(limit = 10)).transactions.size) + } + + @Test + fun `clearing empties the store and reports success`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + val audit = InMemoryCommandAuditLog() + val store = networkStore("tx-1", "tx-2") + application { + devConsoleModule(sessions, sessionCodes) { + networkTransactions = store + commandAuditLog = audit + } + } + val session = approvedSession(sessions, sessionCodes) + + val response = client.delete("/api/v1/network/transactions") { controlHeaders(session) } + + assertEquals(HttpStatusCode.OK, response.status) + assertTrue(response.bodyAsText().contains("cleared")) + assertTrue(store.page(NetworkTransactionQuery(limit = 10)).transactions.isEmpty()) + assertNull(store.find("tx-1")) + assertTrue( + audit.events().any { + it.commandType == "network.clear" && it.result == CommandAuditResult.SUCCESS + }, + ) + } + + /** The listing route is what the dashboard re-reads after a clear; it must agree with the store. */ + @Test + fun `the listing route reports no transactions after a clear`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + val store = networkStore("tx-1", "tx-2") + application { devConsoleModule(sessions, sessionCodes) { networkTransactions = store } } + val session = approvedSession(sessions, sessionCodes) + val before = client.get("/api/v1/network/transactions") { authHeaders(session) } + assertTrue(before.bodyAsText().contains("tx-1")) + + client.delete("/api/v1/network/transactions") { controlHeaders(session) } + val after = client.get("/api/v1/network/transactions") { authHeaders(session) } + + assertEquals(HttpStatusCode.OK, after.status) + assertFalse(after.bodyAsText().contains("tx-1")) + } + + /** + * Same category gate every other network route carries: a host that never enabled + * network capture must not expose a route that mutates the network buffer either. + */ + @Test + fun `clearing is refused while the network category is disabled`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + val audit = InMemoryCommandAuditLog() + val store = networkStore("tx-1") + application { + devConsoleModule(sessions, sessionCodes) { + networkTransactions = store + commandAuditLog = audit + metadata = ServerMetadata(captureCategories = listOf("logs")) + } + } + val session = approvedSession(sessions, sessionCodes) + + val response = client.delete("/api/v1/network/transactions") { controlHeaders(session) } + + assertEquals(HttpStatusCode.Forbidden, response.status) + assertTrue(response.bodyAsText().contains("CATEGORY_DISABLED")) + assertEquals(1, store.page(NetworkTransactionQuery(limit = 10)).transactions.size) + assertTrue( + audit.events().any { + it.commandType == "network.clear" && it.result == CommandAuditResult.REJECTED + }, + ) + } + + /** Clearing an already-empty store is a no-op success, not a 404 -- the button stays idempotent. */ + @Test + fun `clearing an empty store still succeeds`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + val store = networkStore() + application { devConsoleModule(sessions, sessionCodes) { networkTransactions = store } } + val session = approvedSession(sessions, sessionCodes) + + val response = client.delete("/api/v1/network/transactions") { controlHeaders(session) } + + assertEquals(HttpStatusCode.OK, response.status) + } +} + +private fun networkStore(vararg ids: String): InMemoryNetworkTransactionStore = + InMemoryNetworkTransactionStore(NetworkCursorCodec(ByteArray(16))).also { store -> + ids.forEachIndexed { index, id -> + store.record( + NetworkTransaction( + id = id, + startedAtEpochMs = index.toLong() + 1, + completedAtEpochMs = index.toLong() + 2, + capture = + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())).capture( + NetworkRequestInput("GET", "https://api.test/$id"), + NetworkResponseInput(200), + ), + ), + ) + } + } + +private fun HttpRequestBuilder.controlHeaders(session: BrowserSession) { + header(HttpHeaders.Host, "localhost") + header(HttpHeaders.Authorization, "Bearer ${session.token}") + header(HttpHeaders.Origin, "http://localhost") + header("X-DevConsole-CSRF", session.csrfToken) +} + +/** Bearer-only headers for a plain GET -- no Origin/CSRF, since a read route never needs them. */ +private fun HttpRequestBuilder.authHeaders(session: BrowserSession) { + header(HttpHeaders.Host, "localhost") + header(HttpHeaders.Authorization, "Bearer ${session.token}") +} + +private suspend fun ApplicationTestBuilder.approvedSession( + sessions: SessionAuthority, + sessionCodes: SessionCodeAuthority, +): BrowserSession { + val code = sessionCodes.issueCode().code + val response = + client.post("/api/v1/auth/session-code/exchange") { + header(HttpHeaders.Host, "localhost") + header(HttpHeaders.ContentType, ContentType.Application.FormUrlEncoded) + setBody("code=$code") + } + val token = Regex("\"accessToken\":\"([^\"]+)\"").find(response.bodyAsText())!!.groupValues[1] + return sessions.sessionForToken(token)!! +} diff --git a/sdk/ui-compose/api/ui-compose.api b/sdk/ui-compose/api/ui-compose.api index 8cd66f7..3c35eba 100644 --- a/sdk/ui-compose/api/ui-compose.api +++ b/sdk/ui-compose/api/ui-compose.api @@ -121,6 +121,7 @@ public final class io/devconsole/ui/compose/ComposableSingletons$InspectorNavCom public static final field INSTANCE Lio/devconsole/ui/compose/ComposableSingletons$InspectorNavComponentsKt; public fun ()V public final fun getLambda$-1348228066$ui_compose_release ()Lkotlin/jvm/functions/Function2; + public final fun getLambda$-945241836$ui_compose_release ()Lkotlin/jvm/functions/Function2; public final fun getLambda$1070396343$ui_compose_release ()Lkotlin/jvm/functions/Function2; } @@ -138,6 +139,7 @@ public final class io/devconsole/ui/compose/ComposableSingletons$InspectorObserv public final fun getLambda$-1017166837$ui_compose_release ()Lkotlin/jvm/functions/Function2; public final fun getLambda$-1550195010$ui_compose_release ()Lkotlin/jvm/functions/Function2; public final fun getLambda$-1782394095$ui_compose_release ()Lkotlin/jvm/functions/Function2; + public final fun getLambda$-219796685$ui_compose_release ()Lkotlin/jvm/functions/Function2; public final fun getLambda$-650102098$ui_compose_release ()Lkotlin/jvm/functions/Function2; public final fun getLambda$-970086269$ui_compose_release ()Lkotlin/jvm/functions/Function2; public final fun getLambda$-998201989$ui_compose_release ()Lkotlin/jvm/functions/Function2; @@ -156,6 +158,12 @@ public final class io/devconsole/ui/compose/ComposableSingletons$InspectorObserv public final fun getLambda$-1125610964$ui_compose_release ()Lkotlin/jvm/functions/Function3; } +public final class io/devconsole/ui/compose/ComposableSingletons$InspectorObserveScreenKt { + public static final field INSTANCE Lio/devconsole/ui/compose/ComposableSingletons$InspectorObserveScreenKt; + public fun ()V + public final fun getLambda$-606130299$ui_compose_release ()Lkotlin/jvm/functions/Function2; +} + public final class io/devconsole/ui/compose/ComposableSingletons$InspectorObserveSignalsKt { public static final field INSTANCE Lio/devconsole/ui/compose/ComposableSingletons$InspectorObserveSignalsKt; public fun ()V @@ -263,6 +271,14 @@ public final class io/devconsole/ui/compose/InspectorAction$ClearTransactionSele public fun toString ()Ljava/lang/String; } +public final class io/devconsole/ui/compose/InspectorAction$ClearTransactions : io/devconsole/ui/compose/InspectorAction { + public static final field $stable I + public static final field INSTANCE Lio/devconsole/ui/compose/InspectorAction$ClearTransactions; + public fun equals (Ljava/lang/Object;)Z + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + public final class io/devconsole/ui/compose/InspectorAction$CloseFilePreview : io/devconsole/ui/compose/InspectorAction { public static final field $stable I public static final field INSTANCE Lio/devconsole/ui/compose/InspectorAction$CloseFilePreview; @@ -881,6 +897,7 @@ public final class io/devconsole/ui/compose/InspectorCrashUi { public abstract interface class io/devconsole/ui/compose/InspectorDataSource { public fun captureRules ()Ljava/util/List; public fun captureScreenshot (Lkotlin/coroutines/Continuation;)Ljava/lang/Object; + public fun clearTransactions ()Lio/devconsole/ui/compose/InspectorCommandResult; public fun crashesForSession (Ljava/lang/String;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public abstract fun deleteCaptureRule (Ljava/lang/String;)Lio/devconsole/ui/compose/InspectorCommandResult; public abstract fun deleteFile (Ljava/lang/String;Ljava/lang/String;)Lio/devconsole/ui/compose/InspectorCommandResult; @@ -927,6 +944,7 @@ public abstract interface class io/devconsole/ui/compose/InspectorDataSource { public final class io/devconsole/ui/compose/InspectorDataSource$DefaultImpls { public static fun captureRules (Lio/devconsole/ui/compose/InspectorDataSource;)Ljava/util/List; public static fun captureScreenshot (Lio/devconsole/ui/compose/InspectorDataSource;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; + public static fun clearTransactions (Lio/devconsole/ui/compose/InspectorDataSource;)Lio/devconsole/ui/compose/InspectorCommandResult; public static fun crashesForSession (Lio/devconsole/ui/compose/InspectorDataSource;Ljava/lang/String;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public static synthetic fun exportHar$default (Lio/devconsole/ui/compose/InspectorDataSource;Ljava/util/Set;ILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorCommandResult; public static synthetic fun exportPostman$default (Lio/devconsole/ui/compose/InspectorDataSource;Ljava/util/Set;ILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorCommandResult; diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorAction.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorAction.kt index 0d56502..7338716 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorAction.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorAction.kt @@ -148,6 +148,13 @@ sealed interface InspectorAction { data object DismissCommandResult : InspectorAction + /** + * Discards every captured network transaction -- the Traffic tab's "clear captures" action. + * Irreversible: captures live only in the in-memory store, so nothing can restore them. The + * surface is expected to confirm before dispatching this. + */ + data object ClearTransactions : InspectorAction + /** Exports the current traffic selection ([InspectorState.selectedTransactionIds]) as a HAR file. */ data object ExportHar : InspectorAction diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDataSource.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDataSource.kt index 6808816..db025c0 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDataSource.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDataSource.kt @@ -625,6 +625,21 @@ interface InspectorDataSource { sql: String, ): InspectorSqlResultUi + /** + * Discards every captured network transaction, backing the Traffic tab's "clear captures" + * action. Ungated by capability for the same reason the exports below are: it touches only this + * SDK's own capture buffer, never host application state. + * + * Evidence flags are deliberately left alone -- `EvidenceStore` holds materialized copies of + * flagged captures and the tray is durable across sessions, so clearing the live buffer must not + * quietly destroy collected bug evidence. + * + * Defaults to [InspectorCommandResult.Unavailable] so every existing adapter and fake keeps + * compiling, matching this interface's other "only override if you actually implement it" + * defaults. + */ + fun clearTransactions(): InspectorCommandResult = InspectorCommandResult.Unavailable + /** * Exports captured network traffic as a HAR file, sharing the result via the same * `FileProvider`/Share-sheet flow as [shareableFilePath]. [transactionIds] mirrors whatever the diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorNavComponents.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorNavComponents.kt index 7bedd29..f47898d 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorNavComponents.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorNavComponents.kt @@ -114,6 +114,20 @@ internal fun InspectorTopArea( * kind of thing [InspectorTopAction] already models. */ @Composable +/** + * The Traffic tab's "clear captures" action. Tinted [DevConsoleColors.error] rather than muted like + * [themeToggleTopAction]: it is the only destructive control in the top area, and the colour is what + * separates it from its neighbour at a glance. + */ +internal fun clearCapturesTopAction(onClear: () -> Unit): InspectorTopAction = + InspectorTopAction( + contentDescription = "Clear captured requests", + onClick = onClear, + icon = { + ObserveGlyphIcon(ObserveGlyph.Trash, contentDescription = null, tint = DevConsoleTheme.colors.error) + }, + ) + internal fun themeToggleTopAction(onToggleTheme: () -> Unit): InspectorTopAction = InspectorTopAction( contentDescription = "Toggle theme", diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveGlyphs.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveGlyphs.kt index 0933274..ede094a 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveGlyphs.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveGlyphs.kt @@ -32,7 +32,7 @@ import androidx.compose.ui.unit.dp * bezier replication of arcs -- the design spec's pixel-authoritative language covers * sizes/spacing/radii/colors/typography/states, not icon vector art). */ -internal enum class ObserveGlyph { Plug, Activity, Filter, Refresh, Download, Sun, Tag } +internal enum class ObserveGlyph { Plug, Activity, Filter, Refresh, Download, Sun, Tag, Trash } private const val GLYPH_VIEWBOX = 16f private const val GLYPH_STROKE_WIDTH = 1.4f @@ -106,6 +106,19 @@ private fun DrawScope.drawObserveGlyph( path.lineTo(10.5f * scale, 8f * scale) path.lineTo(14f * scale, 8f * scale) } + ObserveGlyph.Trash -> { + // M2.5 4h11M6.5 4V2.5h3V4M4 4l.75 9.5h6.5L12 4 -- lid line, handle, tapered can. + path.moveTo(2.5f * scale, 4f * scale) + path.lineTo(13.5f * scale, 4f * scale) + path.moveTo(6.5f * scale, 4f * scale) + path.lineTo(6.5f * scale, 2.5f * scale) + path.lineTo(9.5f * scale, 2.5f * scale) + path.lineTo(9.5f * scale, 4f * scale) + path.moveTo(4f * scale, 4f * scale) + path.lineTo(4.75f * scale, 13.5f * scale) + path.lineTo(11.25f * scale, 13.5f * scale) + path.lineTo(12f * scale, 4f * scale) + } ObserveGlyph.Tag -> { // M2 8.5 7.5 3h5.5v5.5L8.5 13 2 8.5Z + a small punch-hole -- a price tag shape. path.moveTo(2f * scale, 8.5f * scale) diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObservePreviews.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObservePreviews.kt index f2ecee4..1bbd60c 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObservePreviews.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObservePreviews.kt @@ -175,6 +175,9 @@ private val PreviewObserveActions = onToggleTransactionSelection = {}, onSelectAllFilteredTransactions = {}, onClearTransactionSelection = {}, + onRequestClearTransactions = {}, + onConfirmClearTransactions = {}, + onCancelClearTransactions = {}, onExportHar = {}, onExportPostman = {}, copyText = {}, @@ -323,3 +326,20 @@ private fun ObserveScreenTrafficHeroCollapsedPreview() { ) } } + +/** + * The Traffic tab with the clear confirmation up -- also the only preview showing the trash action + * in the top area, since it renders only on Traffic and only with captures present. + */ +@Preview(name = "Dark", uiMode = Configuration.UI_MODE_NIGHT_YES, showBackground = true, backgroundColor = 0xFF0B0E0D) +@Preview(name = "Light", uiMode = Configuration.UI_MODE_NIGHT_NO, showBackground = true, backgroundColor = 0xFFF3F6EE) +@Composable +private fun ObserveScreenClearTransactionsConfirmPreview() { + DevConsoleTheme(darkTheme = isSystemInDarkTheme()) { + ObserveScreen( + state = PreviewObserveState.copy(observeTab = ObserveTab.TRAFFIC), + ui = PreviewObserveUi.copy(clearTransactionsPending = true), + actions = PreviewObserveActions, + ) + } +} diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveScreen.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveScreen.kt index 926e0b7..07b598c 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveScreen.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveScreen.kt @@ -14,13 +14,16 @@ import androidx.compose.animation.slideInHorizontally import androidx.compose.animation.slideOutHorizontally import androidx.compose.animation.togetherWith import androidx.compose.foundation.background +import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding +import androidx.compose.material3.AlertDialog import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Text +import androidx.compose.material3.minimumInteractiveComponentSize import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.MutableState @@ -36,9 +39,11 @@ import androidx.compose.ui.platform.ClipboardManager import androidx.compose.ui.platform.LocalClipboardManager import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle @@ -104,6 +109,8 @@ internal data class ObserveUiState( val detailTarget: ObserveDetailTarget? = null, /** Non-null while the net detail's "Mock this response" action has a create sheet open. */ val mockDraft: MockRuleEditorTarget.New? = null, + /** True while the Traffic tab's "clear captures" confirmation is showing. */ + val clearTransactionsPending: Boolean = false, /** Hero collapse is hoisted per tab, independent of every other tab's. */ val trafficHeroCollapsed: Boolean = true, val socketsHeroCollapsed: Boolean = true, @@ -150,6 +157,11 @@ internal data class ObserveActions( val onSelectAllFilteredTransactions: (Set) -> Unit, /** Explicit close or back-press out of selection mode. */ val onClearTransactionSelection: () -> Unit, + /** Traffic tab trash action: opens the confirmation, never clears on its own. */ + val onRequestClearTransactions: () -> Unit, + /** Confirms the pending clear -- the only path that actually discards captures. */ + val onConfirmClearTransactions: () -> Unit, + val onCancelClearTransactions: () -> Unit, /** Exports [InspectorState.selectedTransactionIds] (or everything, if empty) as a HAR file. */ val onExportHar: () -> Unit, /** Same scope as [onExportHar], as a Postman collection instead. */ @@ -204,6 +216,13 @@ private class ObserveRouteState( var detailTarget by mutableStateOf(null) var mockDraft by mockDraftState + /** + * Plain `mutableStateOf`, not `rememberSaveable`: losing an open confirmation across a rotation + * is the safe direction to fail for a destructive action -- the operator re-taps rather than + * having a pre-armed "clear everything" dialog survive a configuration change. + */ + var clearTransactionsPending by mutableStateOf(false) + // Collapsed by default on every tab. var trafficHeroCollapsed by trafficHeroCollapsedState var socketsHeroCollapsed by socketsHeroCollapsedState @@ -270,6 +289,7 @@ private fun ObserveRouteState.toUiState( flaggedCrashIds = flaggedCrashIds, detailTarget = detailTarget, mockDraft = mockDraft, + clearTransactionsPending = clearTransactionsPending, trafficHeroCollapsed = trafficHeroCollapsed, socketsHeroCollapsed = socketsHeroCollapsed, pushHeroCollapsed = pushHeroCollapsed, @@ -399,6 +419,14 @@ private fun rememberObserveActions( onToggleTransactionSelection = { id -> viewModel.dispatch(InspectorAction.ToggleTransactionSelection(id)) }, onSelectAllFilteredTransactions = { ids -> viewModel.dispatch(InspectorAction.SelectTransactions(ids)) }, onClearTransactionSelection = { viewModel.dispatch(InspectorAction.ClearTransactionSelection) }, + onRequestClearTransactions = { routeState.clearTransactionsPending = true }, + // The toast comes from lastCommandResult like every other mutation (see ObserveRoute's + // LaunchedEffect); this only has to close the dialog. + onConfirmClearTransactions = { + routeState.clearTransactionsPending = false + viewModel.dispatch(InspectorAction.ClearTransactions) + }, + onCancelClearTransactions = { routeState.clearTransactionsPending = false }, onExportHar = { viewModel.dispatch(InspectorAction.ExportHar) }, onExportPostman = { viewModel.dispatch(InspectorAction.ExportPostman) }, copyText = { text -> @@ -556,7 +584,18 @@ internal fun ObserveScreen( // The old search icon here only ever showed a "search opens the keyboard on device" // message (dead chrome) -- InspectorSearchBar below, in each tab's own list, is the // one real search affordance, so the top-area action is dropped rather than kept. - actions = listOf(themeToggleTopAction(actions.onToggleTheme)), + // + // Clear only exists on Traffic (the only tab whose captures it discards) and only + // once there is something to discard, so it never offers a no-op. It sits *before* + // the theme toggle so that toggle keeps its usual rightmost slot instead of sliding + // sideways as captures come and go. + actions = + buildList { + if (state.observeTab == ObserveTab.TRAFFIC && state.transactions.isNotEmpty()) { + add(clearCapturesTopAction(actions.onRequestClearTransactions)) + } + add(themeToggleTopAction(actions.onToggleTheme)) + }, ) previousCrashedSession(state.sessions)?.let { session -> PreviousRunCrashedBanner(session = session, onViewCrash = { actions.onViewPreviousCrash(session.id) }) @@ -583,6 +622,13 @@ internal fun ObserveScreen( } } } + if (ui.clearTransactionsPending) { + ClearTransactionsConfirmDialog( + captureCount = state.transactions.size, + onConfirm = actions.onConfirmClearTransactions, + onDismiss = actions.onCancelClearTransactions, + ) + } ui.detailTarget?.let { target -> ObserveDetailOverlay(target, state, ui, actions) } ui.mockDraft?.let { target -> MockRuleEditorScreen( @@ -594,6 +640,55 @@ internal fun ObserveScreen( } } +/** + * Confirmation for the Traffic tab's clear action, shaped like `MockRuleDeleteConfirmDialog` on the + * Control screen. Names the count so the operator sees what they are about to lose, and says plainly + * that evidence survives -- flagged captures are materialized into the durable `EvidenceStore`, so a + * clear does not cost anyone the bug they were collecting. + */ +@Composable +private fun ClearTransactionsConfirmDialog( + captureCount: Int, + onConfirm: () -> Unit, + onDismiss: () -> Unit, +) { + val colors = DevConsoleTheme.colors + val plural = if (captureCount == 1) "capture" else "captures" + AlertDialog( + onDismissRequest = onDismiss, + title = { Text("Clear $captureCount $plural?") }, + text = { + Text( + "Captured requests are held in memory only, so this can't be undone. " + + "Anything you flagged as evidence is kept.", + ) + }, + confirmButton = { + Text( + "CLEAR", + color = colors.error, + fontWeight = FontWeight.Bold, + modifier = + Modifier + .minimumInteractiveComponentSize() + .clickable(onClick = onConfirm, role = Role.Button) + .padding(12.dp), + ) + }, + dismissButton = { + Text( + "CANCEL", + color = colors.muted, + modifier = + Modifier + .minimumInteractiveComponentSize() + .clickable(onClick = onDismiss, role = Role.Button) + .padding(12.dp), + ) + }, + ) +} + /** * The previous-run-crashed marker: the most recent *non-active* session (i.e. not the one * currently capturing) whose [InspectorSessionUi.status] is `"CRASHED"` -- mirroring diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorViewModel.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorViewModel.kt index bfc28cc..1f4078f 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorViewModel.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorViewModel.kt @@ -102,6 +102,7 @@ class InspectorViewModel is InspectorAction.OpenTable -> openTable(action.database, action.table) is InspectorAction.ExecuteSql -> executeSql(action.database, action.sql) InspectorAction.DismissCommandResult -> dismissCommandResult() + InspectorAction.ClearTransactions -> clearTransactions() InspectorAction.ExportHar -> exportHar() InspectorAction.ExportPostman -> exportPostman() InspectorAction.ExportSessionZip -> exportSessionZip() @@ -548,6 +549,22 @@ class InspectorViewModel } } + /** + * Ungated, like the exports below: clearing discards this SDK's own capture buffer and never + * touches host application state (see FullInspectorDataSource). The selection is dropped + * before the reload because it holds ids, not captures -- keeping it would leave the traffic + * tab in selection mode over rows that no longer exist. [loadSnapshot] then re-reads, so the + * emptied list comes from the adapter's real post-clear state rather than an assumed-empty + * local one. + */ + private fun clearTransactions() { + viewModelScope.launch(dispatcher) { + showComposerResult(dataSource.clearTransactions()) + mutableState.update { it.copy(selectedTransactionIds = emptySet()) } + loadSnapshot() + } + } + /** Ungated: exports read already-captured, already-redacted data (see FullInspectorDataSource). */ private fun exportHar() { val selection = mutableState.value.selectedTransactionIds diff --git a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorViewModelTest.kt b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorViewModelTest.kt index 1db030e..c3429ce 100644 --- a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorViewModelTest.kt +++ b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorViewModelTest.kt @@ -609,6 +609,77 @@ class InspectorViewModelTest { assertEquals(browser, state.browser) } + @Test + fun `clearing transactions calls through and re-reads the emptied snapshot`() = + runTest { + val dispatcher = StandardTestDispatcher(testScheduler) + val source = + RecordingInspectorDataSource( + InspectorSnapshot(available = true, transactions = listOf(sampleTransaction("tx-1"))), + ) + val viewModel = InspectorViewModel(dataSource = source, dispatcher = dispatcher) + dispatcher.scheduler.advanceUntilIdle() + assertEquals(1, viewModel.state.value.transactions.size) + // The adapter is the one that actually empties the store, so the fake models that too -- + // otherwise the reload after the clear would hand back the same captures and the test + // would pass without the view model ever having refreshed. + source.snapshotToReturn = InspectorSnapshot(available = true, transactions = emptyList()) + + viewModel.dispatch(InspectorAction.ClearTransactions) + dispatcher.scheduler.advanceUntilIdle() + + assertEquals(1, source.clearTransactionsCallCount) + assertTrue( + viewModel.state.value.transactions + .isEmpty(), + ) + assertEquals(source.clearTransactionsResult, viewModel.state.value.lastCommandResult) + } + + /** + * Selection holds ids, not captures. Leaving it populated across a clear would leave the traffic + * tab in selection mode over rows that no longer exist, and hand the exporters a selection that + * resolves to nothing. + */ + @Test + fun `clearing transactions drops the traffic selection`() = + runTest { + val dispatcher = StandardTestDispatcher(testScheduler) + val transactions = listOf(sampleTransaction("tx-1"), sampleTransaction("tx-2")) + val source = RecordingInspectorDataSource(InspectorSnapshot(available = true, transactions = transactions)) + val viewModel = InspectorViewModel(dataSource = source, dispatcher = dispatcher) + dispatcher.scheduler.advanceUntilIdle() + viewModel.dispatch(InspectorAction.ToggleTransactionSelection("tx-1")) + assertEquals(setOf("tx-1"), viewModel.state.value.selectedTransactionIds) + source.snapshotToReturn = InspectorSnapshot(available = true, transactions = emptyList()) + + viewModel.dispatch(InspectorAction.ClearTransactions) + dispatcher.scheduler.advanceUntilIdle() + + assertTrue( + viewModel.state.value.selectedTransactionIds + .isEmpty(), + ) + } + + /** An adapter with no capture store to empty reports Unavailable; the surface still shows it. */ + @Test + fun `an unavailable clear surfaces its result without emptying anything`() = + runTest { + val dispatcher = StandardTestDispatcher(testScheduler) + val transactions = listOf(sampleTransaction("tx-1")) + val source = RecordingInspectorDataSource(InspectorSnapshot(available = true, transactions = transactions)) + source.clearTransactionsResult = InspectorCommandResult.Unavailable + val viewModel = InspectorViewModel(dataSource = source, dispatcher = dispatcher) + dispatcher.scheduler.advanceUntilIdle() + + viewModel.dispatch(InspectorAction.ClearTransactions) + dispatcher.scheduler.advanceUntilIdle() + + assertEquals(InspectorCommandResult.Unavailable, viewModel.state.value.lastCommandResult) + assertEquals(transactions, viewModel.state.value.transactions) + } + @Test fun `exporting HAR calls through and stores the result`() = runTest { @@ -1567,6 +1638,7 @@ private class RecordingInspectorDataSource( var tablesToReturn: InspectorDatabaseListingUi? = null var queryToReturn: InspectorQueryResultUi? = null var sqlResult: InspectorSqlResultUi = InspectorSqlResultUi.Failed("n/a") + var clearTransactionsResult: InspectorCommandResult = InspectorCommandResult.Success(summary = "Captures cleared") var exportHarResult: InspectorCommandResult = InspectorCommandResult.Success(summary = "Saved to har") var exportPostmanResult: InspectorCommandResult = InspectorCommandResult.Success(summary = "Saved to postman") var exportSessionZipResult: InspectorCommandResult = InspectorCommandResult.Success(summary = "Saved to zip") @@ -1618,6 +1690,8 @@ private class RecordingInspectorDataSource( private set var lastSql: String? = null private set + var clearTransactionsCallCount = 0 + private set var exportHarCallCount = 0 private set var exportPostmanCallCount = 0 @@ -1829,6 +1903,11 @@ private class RecordingInspectorDataSource( return sqlResult } + override fun clearTransactions(): InspectorCommandResult { + clearTransactionsCallCount++ + return clearTransactionsResult + } + override fun exportHar(transactionIds: Set): InspectorCommandResult { exportHarCallCount++ lastExportHarSelection = transactionIds From 3ea8d81c510bd9f62d13c214d663229b6601c123 Mon Sep 17 00:00:00 2001 From: "Md. Asaduzzaman Nur" Date: Mon, 24 Aug 2026 15:05:10 +0600 Subject: [PATCH 3/3] Fix dev console search --- .../resources/devconsole-web/dashboard.js | 30 +++++++++++++++++++ .../main/resources/devconsole-web/index.html | 2 +- .../server/ktor/DashboardAssetsTest.kt | 28 +++++++++++++++++ 3 files changed, 59 insertions(+), 1 deletion(-) diff --git a/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js b/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js index f13e6e7..7450801 100644 --- a/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js +++ b/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js @@ -5956,6 +5956,34 @@ // Shared control helpers // ================================================================ + + /** + * Wires a search box whose filtering happens on the *server* (Network, Sockets) — as opposed to + * Timeline/Push/Crashes, which filter an already-loaded page in the browser and so can listen + * straight to `input` and re-render. + * + * Those two shipped with no listener at all: `loadNetwork`/`loadSocketMessages` read the box at + * request time, so the query did reach the server, but only when some unrelated control happened + * to trigger a reload — and the one button that always does ("Apply") sits inside the collapsed + * "More filters" block. Typing and pressing Enter did nothing, which is what #22 reported. + * + * Debounced because each reload is a request against the shared 120/min read budget + * (`readQueryLimiter`), and a 12-character query typed at speed would otherwise be 12 of them. + * Enter and blur flush immediately, so an operator who wants the result now never waits on the + * timer. Clearing the box via the native ✕ fires `input` like any other edit, so it reloads too. + */ + const SEARCH_DEBOUNCE_MS = 300; + function wireServerSearch(id, reload) { + const input = $(id); + if (!input) return; + let timer = null; + const flush = () => { clearTimeout(timer); timer = null; reload(); }; + input.addEventListener('input', () => { clearTimeout(timer); timer = setTimeout(flush, SEARCH_DEBOUNCE_MS); }); + input.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); flush(); } }); + // Only flush on blur if an edit is still pending — otherwise every focus change reloads. + input.addEventListener('blur', () => { if (timer) flush(); }); + } + const controlHeaders = () => ({ ...auth(), 'X-DevConsole-CSRF': csrf }); const updateControlUi = () => { const enabled = hasSession(); @@ -7361,6 +7389,7 @@ // ---- Network ----------------------------------------------------------------- wireSeg($('networkStatusSeg'), (value) => { networkStatusFilter = value; applyNetworkFilters(); }); wireSeg($('networkMethodSeg'), (value) => { networkMethodFilter = value; applyNetworkFilters(); }); + wireServerSearch('networkSearch', () => loadNetwork()); $('networkRefresh').onclick = () => loadNetwork(); $('networkNewest').onclick = () => loadNetwork(); $('networkOlder').onclick = () => networkCursor && loadNetwork(networkCursor); @@ -7382,6 +7411,7 @@ $('timelineOlder').onclick = () => timelineCursor && load(timelineCursor); // ---- WebSockets ---------------------------------------------------------------- + wireServerSearch('socketSearch', () => loadSocketMessages()); wireSeg($('socketFrameTypeSeg'), (value) => { socketFrameTypeFilter = value; loadSocketMessages(); }); wireSeg($('socketDirectionSeg'), (value) => { socketDirectionFilter = value; loadSocketMessages(); }); // Protocol changes which connections are in scope too, not just which messages, so it re-runs diff --git a/sdk/server-ktor/src/main/resources/devconsole-web/index.html b/sdk/server-ktor/src/main/resources/devconsole-web/index.html index 8e27c88..ffe0657 100644 --- a/sdk/server-ktor/src/main/resources/devconsole-web/index.html +++ b/sdk/server-ktor/src/main/resources/devconsole-web/index.html @@ -210,7 +210,7 @@

Network

-

Full request and response — headers, payload, body, timing — side by side. Search spans every field.

+

Full request and response — headers, payload, body, timing — side by side. Search matches method, URL, headers, tags, status and content type; bodies are not indexed.

diff --git a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DashboardAssetsTest.kt b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DashboardAssetsTest.kt index 454e5b6..44d5a90 100644 --- a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DashboardAssetsTest.kt +++ b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DashboardAssetsTest.kt @@ -24,6 +24,34 @@ class DashboardAssetsTest { assertFalse(script.contains("structuredClone")) } + /** + * Regression for #22 ("Search Functionality Is Not Working"). Network and Socket search are + * server-side filters, so unlike the Timeline/Push/Crashes boxes -- which re-render an + * already-loaded page and can listen straight to `input` -- they have to re-issue the query. + * Both shipped with no listener at all, so typing in "Search captures" did nothing until some + * unrelated control (Apply, a status chip, Refresh) happened to trigger a reload. + */ + @Test + fun `server-backed search boxes are wired to re-issue their query`() { + val script = DashboardAssets.js() + + assertTrue(script.contains("function wireServerSearch(")) + assertTrue(script.contains("wireServerSearch('networkSearch'")) + assertTrue(script.contains("wireServerSearch('socketSearch'")) + } + + /** + * The Network hint used to claim "Search spans every field", but the server matches against + * `NetworkTransactionStore.searchableText()`, which deliberately excludes request and response + * bodies. Copy that promises a capability the filter does not have reads as a broken search. + */ + @Test + fun `network search hint does not promise fields the server never matches`() { + val dashboard = DashboardAssets.index() + + assertFalse(dashboard.contains("Search spans every field")) + } + @Test fun `navigation rail groups views under the six design-mock workspace labels`() { val dashboard = DashboardAssets.index()