diff --git a/CHANGELOG.md b/CHANGELOG.md index c2f2cfa..cc089a3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,9 +35,9 @@ joined this list.) (`COMPOSER_HOST_REJECTED` vs a private-network refusal, `AGENT_UNAVAILABLE`, `AGENT_TIMEOUT`, `EXECUTION_FAILED` with a `detail`). The Execute button is re-enabled after a failed request instead of staying disabled. -- **Composer hosts can be added from the dashboard.** With `DevConsoleConfig.composerHostsEditable` - on (off by default), the Host allowlist card takes a hostname and a rejected request offers an - "Allow " button, so trying another API no longer needs a rebuild. Added hosts last for the +- **Composer hosts can be added from the dashboard.** When the app sets `composerAllowedHosts`, + `DevConsoleConfig.composerHostsEditable` (on by default) lets the Host allowlist card take a + hostname, and a rejected request offers an "Allow " button, so trying another API no longer needs a rebuild. Added hosts last for the current run only, are audited, and cannot override hosts set by the app. The in-app Composer screen uses the same live list. - `sdk:composer` exposes `ResolvedComposerRequest.wireBody()` so every transport encodes bodies diff --git a/README.md b/README.md index 3d23bf6..2a23f19 100644 --- a/README.md +++ b/README.md @@ -78,7 +78,7 @@ DevConsole.initialize( ) ``` -That's the setup. You now have crash and ANR reports, feature flags, and read-only inspectors for +That's the setup. You now have crash and ANR reports, feature flags, and editable inspectors for SharedPreferences, SQLite, and files. Add one line to your HTTP client (see [Wire up your network stack](#wire-up-your-network-stack)) and network, WebSocket, and MQTT traffic show up too. @@ -131,12 +131,12 @@ Then open the URL. With the default `BrowserSecurity.NONE`, the bare address is | **Find in a capture** | Every detail screen has a find field that filters and highlights as you type. Network captures go further: step through hits with a counter and arrows, scope the search to the sections you choose, and match field names, values, or both. Any body can be expanded full-screen to read or copy. | | **WebSocket & MQTT inspectors** | Connection lifecycles and every frame, inbound and outbound. MQTT rides the Eclipse Paho adapter. | | **Mock rules** | Serve canned responses for matching requests (OkHttp), toggled from the dashboard, with deterministic priority matching. Wired by `installDevConsole` and editable out of the box. | -| **Request composer** | Make the device issue ad-hoc HTTP requests from the dashboard. Off by default, host-allowlist confinable. | +| **Request composer** | Make the device issue ad-hoc HTTP requests from the dashboard. Enabled by default; empty host lists allow any host, non-empty lists restrict destinations. | | **Crash & ANR capture** | Uncaught exceptions and a main-looper watchdog with bounded all-thread dumps and breadcrumbs. Always delegates to any crash reporter you already have. | | **Push timeline** | Record FCM (or any) push messages and their lifecycle: received → displayed → opened. The Firebase adapter uses reflection — no compile-time Firebase dependency. | | **State & feature flags** | Snapshot host-registered state and override feature flags from the browser. | | **Remote Config inspector** | Every Remote Config value active on the device, and where each one came from — server, in-app default, static fallback, or a local override — plus last fetch time and status. Read-only. The Firebase adapter uses reflection — no compile-time Firebase dependency. | -| **Data inspectors** | Browse SharedPreferences, SQLite (incl. a SQL console), and app files. Read-only by default; every edit surface is opt-in. | +| **Data inspectors** | Browse and edit SharedPreferences, SQLite (incl. a SQL console), and app files. All editing capabilities enabled; read-only operation is opt-in. | | **Evidence tray & exports** | Flag anything, attach it to a bug report bundle or Markdown/Jira/GitHub clipboard text. Export HAR, Postman Collection, or a full session ZIP. | | **Background keep-alive** | Default foreground service that keeps the server alive while your app is backgrounded. Enabled by the debug-only full runtime; the no-op runtime contributes no service or permissions. | @@ -420,7 +420,8 @@ Not using Firebase? Implement `RemoteConfigProvider` for any other service — t vendor-neutral, and [docs/REMOTE_CONFIG.md](docs/REMOTE_CONFIG.md) has a worked example. The inspector is read-only: DevConsole never sets overrides and never triggers `fetch()` or `activate()`. -Values are redacted by key name before either surface sees them, matched separator-insensitively so +With `RedactionPolicy.recommended()`, values are redacted by key name before either surface sees +them, matched separator-insensitively so `api_key` and `apiKey` are caught as well as `api-key`. It is still an allowlist, so a secret under a name nobody listed is shown in full — extend `RedactionPolicy.sensitiveFieldNames` if you keep anything sensitive in Remote Config. @@ -565,32 +566,47 @@ devConsole { ## Security model -DevConsole deliberately exposes your app's internals to a browser, and two of its defaults trade -safety for a working first run. Know where the edges are: +DevConsole is a debug-only developer tool. Runtime security layers are **off by default and opt-in**. +Use these settings for shared networks or production-like data: + +| Layer | Default | Enable protection | +|---|---|---| +| Redaction | Off | `DevConsoleConfig(redactionPolicy = RedactionPolicy.recommended())` | +| Rate limits | Off | `.withNetworkProtection(NetworkProtection(rateLimiting = true))` | +| Host/Origin checks | Off | `.withNetworkProtection(NetworkProtection(hostAndOriginChecks = true))` | +| Both network protections | Off | `.withNetworkProtection(NetworkProtection.recommended())` | +| Browser auth | `NONE` | `.withBrowserSecurity(BrowserSecurity.SESSION_CODE)` | +| Read-only editing | Off; all seven capabilities true | `.withEditingCapabilities(EditingCapabilities.readOnly())` | +| Composer host restriction | Any host (empty list) | `DevConsoleConfig(composerAllowedHosts = setOf("api.example.test"))` | +| Disable Composer | Enabled | `DevConsoleConfig(composerEnabled = false)` | +| Disable state mutations | Enabled | `DevConsoleConfig(stateMutationsEnabled = false)` | +| Disable screenshots | Enabled | `.withScreenshotPolicy(ScreenshotPolicy(enabled = false))` | + +`withNetworkProtection` replaces the policy, so use `recommended()` to enable both switches. +The release/noop build guard is unchanged; static security headers remain on. `/api/v1/meta` reports +`redaction: "off" | "on"` and both effective `networkProtection` switches. - **The dashboard speaks plaintext HTTP, and the default browser mode is open.** There is no TLS. `BindingMode.AUTO` binds your device's network address whenever it can, and `BrowserSecurity.NONE` means any client that can reach that address can read the dashboard and use - whatever editing capabilities the host enabled. Open mode still rejects browser mutations that - carry a foreign `Origin`; this protects against a cross-site browser request, not against another - client on the same reachable network. For a shared or untrusted network, pass + every editing capability by default. Host and Origin checks require + `NetworkProtection(hostAndOriginChecks = true)`. For a shared or untrusted network, pass `BindingMode.LOOPBACK`, set `BrowserConfig(binding = BrowserBinding.LOOPBACK)`, or opt into `BrowserSecurity.SESSION_CODE`. - **The connect URL is a credential only in SESSION_CODE mode.** Holding a live `#code=` fragment creates a session, with no approval step on the device. Codes are single-use and expire in five minutes; sessions last 30. Treat that URL like a password. You can revoke sessions from the More screen. -- **Redaction is an allowlist.** About 25 well-known field names and `Bearer` tokens get masked. - Custom header names, signed-URL query params, and PII inside bodies pass through verbatim. See +- **Redaction is opt-in.** `default()` and `none()` mask nothing. `recommended()` restores the + previous built-in sensitive field names; Authorization headers and Bearer text remain visible + unless you add rules. Unmatched custom fields and PII remain visible. See [docs/SECURITY_AND_REDACTION.md](docs/SECURITY_AND_REDACTION.md). -- **Screenshots cannot be redacted.** Pixels don't have field names. Capture is **off by default** +- **Screenshots cannot be redacted.** Pixels don't have field names. Capture is **on by default** and everything it produces is marked `UNREDACTED`. -- **Editing is off by default, except mocks.** Preferences/database/file writes and capture-rule - editing are each gated per surface via `EditingCapabilities`; the composer and state mutation have - their own `DevConsoleConfig` flags. All of those default to off/read-only. Mock editing is the one - exception: a mock rule writes nothing of yours, it only short-circuits DevConsole's own - interceptor, so it ships editable. `EditingCapabilities.readOnly()` still refuses everything - including mocks. +- **Editing is enabled by default.** Preferences, feature flags, database, files, mocks, request + execution, and capture rules all default to true, in constructors and Java Builders. + `EditingCapabilities.readOnly()` refuses everything including mocks. Composer and state mutations + have independent flags, both enabled by default. For the full analysis, including what a malicious network peer or a co-installed app can and cannot do, read [docs/THREAT_MODEL.md](docs/THREAT_MODEL.md). @@ -602,8 +618,8 @@ Three runnable samples under [`samples/`](samples/), one per integration style: | Sample | Stack | Posture | |---|---|---| | [`compose-app`](samples/compose-app) | Jetpack Compose | Everything unlocked: all editing capabilities, composer, screenshots, OkHttp + Ktor (CIO) network demos, MQTT + WebSocket demos, in-app inspector, shake + floating-button open triggers | -| [`foundation-app`](samples/foundation-app) | Stock widgets, no UI framework | Everything at its locked-down default — the read-only contrast | -| [`views-java-app`](samples/views-java-app) | Java + XML, `ui-views` panel | Middle ground: mocks and capture rules editable, data read-only, async Java APIs, shake-to-open (LIGHT) + floating button — the same draggable one Compose hosts get, since it is a plain `View` on the decor view, not a Compose feature | +| [`foundation-app`](samples/foundation-app) | Stock widgets, no UI framework | Explicit read-only capabilities, Composer/state mutations disabled, screenshots disabled | +| [`views-java-app`](samples/views-java-app) | Java + XML, `ui-views` panel | Java Builder integration, editable defaults, async Java APIs, shake-to-open (LIGHT) + floating button | ```bash ./gradlew :samples:compose-app:assembleDebug diff --git a/docs/BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md b/docs/BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md index 00bb809..39994e8 100644 --- a/docs/BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md +++ b/docs/BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md @@ -149,6 +149,18 @@ Run against `samples/compose-app` — the sample with every feature switched on `FOREGROUND_SERVICE_SPECIAL_USE`, `POST_NOTIFICATIONS` and `INTERNET`, while its release APK lists only `INTERNET` (the sample's own) and the auto-generated dynamic-receiver permission. +## Runtime security is opt-in + +The release/noop guard is unchanged. It still refuses the full runtime in non-debuggable apps and +keeps protected variants on the noop artifact. Runtime defaults in an enabled debug build now favor +inspection: no redaction, no rate limiting or Host/Origin checks, open browser access, all editing +capabilities enabled, unrestricted Composer hosts, state mutations enabled, and screenshots enabled. +Opt in with `RedactionPolicy.recommended()`, `NetworkProtection.recommended()`, +`EditingCapabilities.readOnly()`, and `BrowserSecurity.SESSION_CODE`; set `composerEnabled = false`, +`stateMutationsEnabled = false`, and `ScreenshotPolicy(enabled = false)` when needed. The complete +[default/one-line configuration table](SECURITY_AND_REDACTION.md#opt-in-security-layers) and hardening +checklist cover shared networks and production-like data. + ## Publication status The artifacts are `com.github.devconsole-android.DevConsole:devconsole` (the full runtime, from `:sdk:full`) and diff --git a/docs/COMPOSER_AND_MOCKS.md b/docs/COMPOSER_AND_MOCKS.md index 434c7c5..d99892d 100644 --- a/docs/COMPOSER_AND_MOCKS.md +++ b/docs/COMPOSER_AND_MOCKS.md @@ -10,10 +10,12 @@ authenticated session can open the Composer page in `SESSION_CODE` mode — see [PROTOCOL_REFERENCE.md](PROTOCOL_REFERENCE.md#2-auth-handshake-session_code)), and either build a request by hand or use "Copy redacted cURL to composer" from a captured Network transaction (see [NETWORK_INSPECTOR.md](NETWORK_INSPECTOR.md)). The browser route -(`POST /api/v1/composer/execute`) is off by default — the host must set -`DevConsoleConfig.composerEnabled = true`, optionally with a `composerAllowedHosts` allowlist — -and is independent of the in-app inspector's own composer UI, which is instead gated by the host's -`EditingCapabilities.requestExecution` flag. See [THREAT_MODEL.md](THREAT_MODEL.md). +(`POST /api/v1/composer/execute`) is enabled by default. An empty `composerAllowedHosts` permits +any host; a non-empty set restricts every destination, including redirects, to those hosts. +Set `composerEnabled = false` to disable the browser Composer. The in-app inspector also requires +`EditingCapabilities.requestExecution`, which defaults to true. Use +`.withEditingCapabilities(EditingCapabilities.readOnly())` to refuse all inspector writes. +See [THREAT_MODEL.md](THREAT_MODEL.md). ### Calling an API with an access token (and why there is no CORS) @@ -42,19 +44,20 @@ The result panel shows the status, timing, where it ran, the response headers an ### Adding a host without rebuilding -`composerAllowedHosts` is fixed when the app is built. To try another API without a rebuild, opt in -with `composerHostsEditable(true)`. The Composer's **Host allowlist** card then has an *Allow host* +An empty `composerAllowedHosts` (the default) lets the Composer reach any host, so there is nothing to +add. Once the app lists hosts, the list is fixed when the app is built; to try another API without a +rebuild, keep `composerHostsEditable` on (the default; `composerHostsEditable(false)` locks it). The Composer's **Host allowlist** card then has an *Allow host* box (a pasted URL is reduced to its hostname), and a request rejected with `COMPOSER_HOST_REJECTED` shows an **Allow \** button. Hosts added this way last until DevConsole stops, can be removed from the same card, and are audited as `composer.host.add` / `composer.host.remove`. Hosts set by the app cannot be removed from the dashboard, wildcards are not accepted, and at most 50 can be added. The in-app Composer screen consults the same live list, so a host allowed from the dashboard also works -there while the server runs; with the server stopped it falls back to `composerAllowedHosts`. In the -samples, `compose-app` and `views-java-app` turn this on and `foundation-app` keeps its locked-down -defaults, where the card reads "The app fixes this list". +there while the server runs; with the server stopped it falls back to `composerAllowedHosts`. The +`views-java-app` sample lists hosts, so its card shows the editor; the other samples list none and permit +any host. With `composerHostsEditable(false)` the card reads "The app fixes this list". -Leave it off for anything reachable by other people: every added host widens where the device will send +Turn it off for anything reachable by other people: every added host widens where the device will send requests, and in the default open mode that is anyone who can open the dashboard. ### Run on a host computer (macOS, Linux, Windows) @@ -89,7 +92,12 @@ second, local lock, not a bypass. Composer executions appear as first-class network events tagged `source=composer`, so they show up in the Timeline and Network pages like any other captured request. Imported cURL and saved -collections never persist secret variable values by default. +collections follow the configured redaction policy. By default, secret values remain visible; +`DevConsoleConfig(redactionPolicy = RedactionPolicy.recommended())` opts into masking and secret +variable removal in collections. Rate budgets and Host/Origin checks are also opt-in through +`.withNetworkProtection(NetworkProtection.recommended())`. Browser authentication is independently +enabled with `.withBrowserSecurity(BrowserSecurity.SESSION_CODE)`. See the full +[layer/default table and hardening checklist](SECURITY_AND_REDACTION.md#opt-in-security-layers). ## Mocks diff --git a/docs/DATA_INSPECTORS_AND_EXPORTS.md b/docs/DATA_INSPECTORS_AND_EXPORTS.md index 4cf59cc..ae1fbec 100644 --- a/docs/DATA_INSPECTORS_AND_EXPORTS.md +++ b/docs/DATA_INSPECTORS_AND_EXPORTS.md @@ -3,27 +3,15 @@ This page covers the three pieces of the dashboard that read and act on the app sandbox rather than network/socket/push traffic: the **Data** inspectors (preferences, database, files), the device's **More** screen, and the **export** formats (HAR, Postman, and the Android session ZIP). -All of it sits behind the same SESSION_CODE auth as everything else — see -[PROTOCOL_REFERENCE.md](PROTOCOL_REFERENCE.md#2-auth-handshake-session_code) — and every mutating -action additionally gates on the host's `EditingCapabilities`. Every one of them defaults to `false` -except `mocks`, which ships editable because a mock rule writes nothing of the host's — it only -short-circuits DevConsole's own interceptor. `EditingCapabilities.readOnly()` still refuses -everything, mocks included. A host opts specific features in: +Browser access is open by default. Opt into SESSION_CODE with +`.withBrowserSecurity(BrowserSecurity.SESSION_CODE)`; every mutating action also checks the host's +`EditingCapabilities`. Every capability defaults to `true`, including preferences, feature flags, +database, files, mocks, request execution, and capture rules. Opt into read-only operation: ```kotlin DevConsole.initialize( application, - DevConsoleConfig( - editingCapabilities = EditingCapabilities( - preferences = true, - database = true, - files = true, - mocks = true, - captureRules = true, - featureFlags = true, - requestExecution = true, - ), - ), + DevConsoleConfig().withEditingCapabilities(EditingCapabilities.readOnly()), ) ``` @@ -33,6 +21,13 @@ allowing raw SQL against its database. See role: every authenticated session is equivalent, and these flags bound *what the console can do*, not *who* can do it. +Redaction is off by default; pass `redactionPolicy = RedactionPolicy.recommended()` to mask the +built-in fields in inspectors and exports. Screenshots default to enabled and remain unredacted; +disable them with `.withScreenshotPolicy(ScreenshotPolicy(enabled = false))`. Composer and state +mutations also default to enabled. Rate limiting and Host/Origin checks default to off; enable both +with `.withNetworkProtection(NetworkProtection.recommended())`. See the complete +[layer/default table](SECURITY_AND_REDACTION.md#opt-in-security-layers). + ## Preferences inspector Lists every `shared_prefs` XML file and its entries (`GET /api/v1/preferences`). String values pass @@ -48,7 +43,7 @@ value. See [PROTOCOL_REFERENCE.md](PROTOCOL_REFERENCE.md#3-rest-routes) for the Lists the app's SQLite databases and, per database, its tables with row counts (internal `sqlite_%` tables are excluded from the table/row browser). `GET /api/v1/database/{name}/tables/{table}` returns the first 200 rows with column-name-based -redaction applied. The `database` capability is required for **every** statement against `POST +redaction applied only when the policy is enabled. The `database` capability is required for **every** statement against `POST /api/v1/database/{name}/sql`, including `SELECT` — a caller who controls the SQL text can alias any column past name-based redaction (`SELECT password AS p ...`), so enabling this capability is enabling raw, unredacted database access over the session, not just "editing." The SQL console can @@ -192,7 +187,7 @@ the 500-row cap directly in their subtitle whenever the export scope is "everyth all captured traffic (capped at the 500 most recent)"), so a capped export is never presented as if it were complete. -**In-app exports are full-fidelity, redacted diagnostic artifacts, not throwaway files.** They +**In-app exports are full-fidelity diagnostic artifacts using the configured redaction policy.** They persist under `filesDir/devconsole-exports` (pruned to the five most recent), which inherits your app's Android auto-backup settings unless you add your own backup-exclusion rule — see [THREAT_MODEL.md](THREAT_MODEL.md) for what that implies and why the SDK doesn't add the exclusion diff --git a/docs/LAN_PERMISSION_AND_TROUBLESHOOTING.md b/docs/LAN_PERMISSION_AND_TROUBLESHOOTING.md index bdb8d05..2a9abdd 100644 --- a/docs/LAN_PERMISSION_AND_TROUBLESHOOTING.md +++ b/docs/LAN_PERMISSION_AND_TROUBLESHOOTING.md @@ -1,5 +1,15 @@ # LAN permission and troubleshooting +Runtime protections are opt-in: redaction, rate limiting, Host/Origin checks, and browser +authentication are off by default. All editing capabilities, unrestricted Composer, state mutations, +and screenshots are enabled. For shared networks, configure +`DevConsoleConfig(redactionPolicy = RedactionPolicy.recommended())`, +`.withNetworkProtection(NetworkProtection.recommended())`, +`.withBrowserSecurity(BrowserSecurity.SESSION_CODE)`, and +`.withEditingCapabilities(EditingCapabilities.readOnly())`; disable Composer/state mutations and +screenshots as appropriate. See the complete +[default/one-line configuration table](SECURITY_AND_REDACTION.md#opt-in-security-layers). + ## LAN binding ```kotlin @@ -152,6 +162,14 @@ variant). See [BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md](BUILD_VARIANTS_AND_PRODU an absolute 30-minute TTL (refreshable via `/auth/refresh`) and are revoked immediately on server stop. Issue a fresh session code from the device and reconnect. Open mode has no browser session to expire. +**429 / `RATE_LIMITED`** — ordinary query/mutation/export budgets apply only when +`networkProtection.rateLimiting` is true. The session-code exchange attempt budget remains active +whenever SESSION_CODE is selected. **403 / `ORIGIN_REJECTED`** — Host and Origin validation applies +only when `networkProtection.hostAndOriginChecks` is true. SESSION_CODE still requires CSRF tokens +on mutations when those checks are disabled. `/api/v1/meta` reports effective `redaction` and +`networkProtection` values; CSP continues to allow the dashboard's own WebSocket using the parsed +request Host, including when allowlist checks are off. + ## Session codes ("SESSION_CODE_EXPIRED" / "SESSION_CODE_INVALID") There is no device-approval step: presenting a live session code to the exchange endpoint creates diff --git a/docs/MIGRATION.md b/docs/MIGRATION.md index 09e1739..14f4903 100644 --- a/docs/MIGRATION.md +++ b/docs/MIGRATION.md @@ -43,7 +43,39 @@ The Gradle plugin itself is unaffected: it still comes from the Gradle Plugin Po `io.github.devconsole-android` library group, so a module you have not migrated yet keeps its release-build protection. -## Upgrading from 1.2.0 +## Security layers are now opt-in + +DevConsole remains debug-only. Constructor and Java Builder defaults now favor inspection: + +| Setting | Previous default | New default | Restore previous behavior | +|---|---|---|---| +| Redaction | Built-in field rules | None | `DevConsoleConfig(redactionPolicy = RedactionPolicy.recommended())` | +| Editing capabilities | All false except mocks | All true | `.withEditingCapabilities(EditingCapabilities.readOnly().copy(mocks = true))` | +| Composer | Disabled | Enabled | `DevConsoleConfig(composerEnabled = false)` | +| Composer hosts | Empty denies every host | Empty permits any host | Disable Composer, or supply an explicit non-empty host set | +| Composer host editing (new) | — | On, once hosts are listed | `.withComposerHostsEditable(false)` | +| State mutations | Disabled | Enabled | `DevConsoleConfig(stateMutationsEnabled = false)` | +| Screenshots | Disabled | Enabled | `.withScreenshotPolicy(ScreenshotPolicy(enabled = false))` | +| Rate limits | Enabled | Disabled | `.withNetworkProtection(NetworkProtection(rateLimiting = true))` | +| Host/Origin checks | Enabled | Disabled | `.withNetworkProtection(NetworkProtection(hostAndOriginChecks = true))` | +| Public browser authentication | NONE | NONE (unchanged) | `.withBrowserSecurity(BrowserSecurity.SESSION_CODE)` opts in | + +Use `NetworkProtection.recommended()` to enable both network switches together. Network protection +is an additive policy, preserved by other `with...` methods and supported by +`DevConsoleConfig.builder().networkProtection(...)` for Java. `RedactionPolicy.default()` now returns +`none()`. `recommended()` preserves the exact previous built-in set, including its intentional +preservation of Authorization headers and Bearer text. Add rules for those if required. + +The standalone Ktor module and engine now also default to `BrowserSecurity.NONE` and editable +capabilities. Direct callers testing authentication must explicitly select SESSION_CODE. It always +retains bearer/CSRF validation, expiry, and code-attempt limits, independently of network protection. +Static response headers and the release/noop guard are unchanged. + +`/api/v1/meta.redaction` keeps its shape and gains `enabled` (false by default); +`sensitiveFieldNames` is unchanged. The new `networkProtection` object reports both effective switches. +Other metadata fields remain. See [security defaults and the hardening checklist](SECURITY_AND_REDACTION.md). + +## Upgrading from 1.2.0 (historical changes) Three defaults changed. No API was removed and nothing has to be rewritten — but two of these change behaviour on a build you do not otherwise touch, so read them before upgrading. diff --git a/docs/PROTOCOL_REFERENCE.md b/docs/PROTOCOL_REFERENCE.md index 13b0e74..0f004b0 100644 --- a/docs/PROTOCOL_REFERENCE.md +++ b/docs/PROTOCOL_REFERENCE.md @@ -265,9 +265,10 @@ a redacted field is already masked. Failures: `409 AGENT_UNAVAILABLE` (unknown/d COMPOSER_HOST_REJECTED`. `GET /api/v1/composer/agents` (auth) lists `{id, name, os, version, address, connectedAtEpochMs}`. -`GET /api/v1/composer/hosts` (auth) answers `{editable, data: [{host, source}]}` with `source` of `app` -or `session`. When `editable` is true (the app set `composerHostsEditable`), `POST /api/v1/composer/hosts` -(form field `host`, bearer + CSRF, 30 changes per minute) adds a host for the current server run and +`GET /api/v1/composer/hosts` (auth) answers `{editable, anyHost, data: [{host, source}]}` with `source` of +`app` or `session`. `anyHost` is true when the app configured no hosts: every host is permitted and session +hosts are not needed. When `editable` is true (`composerHostsEditable`, on by default), `POST /api/v1/composer/hosts` +(form field `host`, bearer + CSRF, 30 changes per minute with rate limiting on) adds a host for the current server run and `DELETE /api/v1/composer/hosts/{host}` removes a session host. Errors: `403 COMPOSER_HOSTS_READ_ONLY`, `400 VALIDATION_FAILED` (not a plain hostname), `409 COMPOSER_HOST_LIMIT`, `409 COMPOSER_HOST_SET_BY_APP`. `GET /api/v1/meta` lists session hosts in `composer.allowedHosts` too. diff --git a/docs/SECURITY_AND_REDACTION.md b/docs/SECURITY_AND_REDACTION.md index b748e41..1dde3db 100644 --- a/docs/SECURITY_AND_REDACTION.md +++ b/docs/SECURITY_AND_REDACTION.md @@ -3,15 +3,62 @@ See [SECURITY.md](../SECURITY.md) at the repository root for the vulnerability-reporting policy. This document covers how redaction actually works, for anyone integrating or auditing it. +## Opt-in security layers + +DevConsole is a debug-only developer tool. Runtime security layers are off by default, and +development features are enabled. Configure the protections your environment needs explicitly. + +| Layer | Default | One-line opt-in | +|---|---|---| +| Redaction | Off; no field names or text patterns | `DevConsoleConfig(redactionPolicy = RedactionPolicy.recommended())` | +| Rate limiting | Off | `.withNetworkProtection(NetworkProtection(rateLimiting = true))` | +| Host and Origin checks | Off | `.withNetworkProtection(NetworkProtection(hostAndOriginChecks = true))` | +| Both network protections | Off | `.withNetworkProtection(NetworkProtection.recommended())` | +| Browser authentication | `BrowserSecurity.NONE` | `.withBrowserSecurity(BrowserSecurity.SESSION_CODE)` | +| Read-only editing capabilities | Off; preferences, feature flags, database, files, mocks, request execution, and capture rules are all editable | `.withEditingCapabilities(EditingCapabilities.readOnly())` | +| Composer restriction | Enabled, any host; empty allowlist permits all | `DevConsoleConfig(composerAllowedHosts = setOf("api.example.test"))` | +| Disable Composer | Composer enabled | `DevConsoleConfig(composerEnabled = false)` | +| Disable state mutations | State mutations enabled | `DevConsoleConfig(stateMutationsEnabled = false)` | +| Disable screenshots | Screenshots enabled | `.withScreenshotPolicy(ScreenshotPolicy(enabled = false))` | + +Network settings replace the previous `NetworkProtection` value; use `recommended()` to enable +both switches together. Java uses `DevConsoleConfig.builder().networkProtection(...)` and the other +policy setters. Additive `with...` methods preserve the other configured policies. + +Static response headers (`nosniff`, X-Frame-Options, CSP, and no-store) remain enabled. The release +build guard and noop artifact are unchanged: they are build-variant safety nets, not runtime layers. +SESSION_CODE always keeps bearer-token validation, CSRF tokens, session expiry, and the session-code +attempt limiter, even when network protection is off. Origin validation is controlled separately by +`hostAndOriginChecks`. + +`GET /api/v1/meta` reports `redaction: { enabled, sensitiveFieldNames }` (`enabled` is true when any +rule exists) and `networkProtection: { rateLimiting, hostAndOriginChecks }`; existing endpoint, +composer, and capture-category fields remain. + +## Hardening checklist + +Use this checklist on shared networks or with production-like data: + +- Set `redactionPolicy = RedactionPolicy.recommended()` and extend its names or patterns for your data. +- Add `.withNetworkProtection(NetworkProtection.recommended())` for budgets and Host/Origin checks. +- Add `.withBrowserSecurity(BrowserSecurity.SESSION_CODE)` for authenticated browser sessions. +- Add `.withEditingCapabilities(EditingCapabilities.readOnly())`; enable individual writes only as needed. +- Set `composerEnabled = false` and `stateMutationsEnabled = false`, or explicitly restrict Composer hosts. +- Add `.withScreenshotPolicy(ScreenshotPolicy(enabled = false))` when screen contents must stay private. +- Bind loopback with `BrowserConfig(binding = BrowserBinding.LOOPBACK)` when LAN access is unnecessary. +- Keep the noop artifact and release-build guard in protected variants. + ## Where redaction happens -Before an event reaches any store or the live dashboard stream — never after. Every capture path +When enabled, before an event reaches any store or the live dashboard stream. Every capture path (network, WebSocket, push) shares one `RedactionEngine`, so the same field is redacted identically regardless of which inspector captured it. -## Default policy +## Default and recommended policies -`RedactionPolicy.default()`'s sensitive field names (case-insensitive, matched against header +`RedactionPolicy.default()` returns `RedactionPolicy.none()`: no names, no text patterns, nothing +masked. `RedactionPolicy.recommended()` opts into the previous built-in sensitive field names +(case-insensitive, matched against header names, JSON keys, and form field names): ```text @@ -23,11 +70,15 @@ passphrase secret client_secret private_key session_id ``` -A matched value is replaced wholesale with ``. `Authorization` headers and Bearer tokens are kept unredacted by default to allow developers to inspect and copy tokens during debugging; custom `textPatterns` and additional `sensitiveFieldNames` can be configured via `RedactionPolicy` if further redaction is desired. +A matched value is replaced wholesale with ``. The historical recommended set preserves +`Authorization` headers and Bearer text. Add `authorization` to `sensitiveFieldNames` or supply +custom `textPatterns` to mask those too. Push tokens, preference values, Remote Config keys, capture +bodies, crash breadcrumbs, and cURL/HAR/Postman exports follow the configured policy. Database +column heuristics and Composer secret-variable masking apply only when redaction is enabled. ## Redaction strategies beyond removal -The engine's default behavior is whole-value replacement. The wire-protocol design additionally +When enabled, the engine uses whole-value replacement. The wire-protocol design additionally specifies `KEEP_PREFIX_SUFFIX(4, 4)` and `HASH_SHA256` strategies for cases where a partially visible or comparable-but-opaque value is more useful than a blank `` — these are declared in the spec but not yet exposed as configuration on `RedactionPolicy` in this codebase; only @@ -52,8 +103,8 @@ is its own resource-exhaustion risk regardless of whether it's sensitive. ## `RedactionApplicability` and the storage boundary -Redaction, as described above, is a text operation: it recognizes field names and pattern-matches -`Bearer ` text, then replaces the matched value. Some content this SDK stores — most notably a +Redaction, as described above, is a text operation: configured rules recognize field names or match +text patterns, then replace matched values. Some content this SDK stores — most notably a captured screenshot (see [THREAT_MODEL.md](THREAT_MODEL.md#screenshots-are-unredactable-by-construction)) — is binary, and there is no equivalent operation for a bitmap. `RedactionApplicability` exists so the storage layer can tell those two situations apart honestly instead of collapsing them into the same diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index 635bb18..e7140a1 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -14,6 +14,14 @@ operator, someone running a packet capture in a café — reads all of it. The p to `BrowserSecurity.NONE` for local development: a reachable browser does not need a bearer token or per-build session code. `BrowserSecurity.SESSION_CODE` restores the single-use credential flow. +Runtime security layers are opt-in. The default redaction policy masks nothing; rate limiting and +Host/Origin checks are off; every editing capability, Composer, state mutations, and screenshots are +enabled. An empty Composer host list permits any host. See the +[complete default and opt-in table](SECURITY_AND_REDACTION.md#opt-in-security-layers) and +[hardening checklist](SECURITY_AND_REDACTION.md#hardening-checklist). The release/noop guard remains +unchanged. Static security headers remain on. SESSION_CODE always retains bearer validation, CSRF +tokens, expiry, and its code-attempt limiter; enabling it does not implicitly enable Origin checks. + **The default binding reaches the network.** `BindingMode.AUTO` — what a bare `StartRequest()` and an unconfigured `BrowserConfig` both mean — binds a real interface whenever the device has one, and only falls back to `127.0.0.1` when it does not. Reachability is the default @@ -26,9 +34,8 @@ something you get. ## Screenshots are unredactable by construction -**If you turn on screenshot capture, unredacted screen content crosses your network in plaintext.** -This is the single most important thing to understand before setting `ScreenshotPolicy.enabled = true`, -so it is stated here, not buried in a feature doc. +**Screenshots are enabled by default; unredacted screen content can cross your network in plaintext.** +Disable capture explicitly with `.withScreenshotPolicy(ScreenshotPolicy(enabled = false))` when needed. A screenshot is pixels. Redaction works by recognizing field *names* — a header called `Authorization`, a JSON key called `password` — and replacing the *value* behind that name. There is @@ -48,10 +55,8 @@ whatever is on someone's screen is one HTTP response away from anyone else on th Because of that, several design decisions in this feature are deliberately unforgiving: -- **Capture defaults to off** (`ScreenshotPolicy.enabled = false`). This is the single most sensitive - artifact this SDK can produce, so it does not ship enabled the way network capture does — a host - must opt in explicitly, the same posture `EditingCapabilities.readOnly()` takes for every other - high-consequence feature. +- **Capture defaults to on** (`ScreenshotPolicy.enabled = true`). A host can disable it explicitly; + redaction settings never mask pixels. - **A `FLAG_SECURE` window is refused, never captured as a black rectangle — and the check is race-free by construction, not just by a single read.** `ScreenshotCapture` reads `Window.attributes.flags` for `FLAG_SECURE` before any capture is attempted, deterministically, rather than trying to infer @@ -120,9 +125,9 @@ the same recommendation this document makes for every other sensitive artifact t |---|---|---| | `BrowserSecurity.SESSION_CODE` | Uncredentialed browsers reaching the dashboard | A code holder, traffic observation, or attacks after a session is created | | `BrowserSecurity.NONE` | Nothing at the browser-authentication boundary | Any reachable client; use only on a trusted network or with loopback | -| Bearer token + CSRF token | Cross-site requests from another origin | Reading the tokens off the wire | -| Origin allowlist | Requests claiming a foreign `Host` | An attacker on the allowed network | -| Redaction | Known-sensitive field *names* | Every field name not on the list | +| Bearer token + CSRF token (SESSION_CODE) | Unauthenticated requests and mutations missing the session's CSRF token | Reading the tokens off the wire | +| Host/Origin checks (opt-in) | Requests claiming an unlisted `Host` or foreign Origin | An attacker on the allowed network | +| Redaction (opt-in) | Configured sensitive fields and patterns | Unmatched fields and screenshot pixels | | 5-minute session-code TTL, 30-minute session TTL | Indefinite reuse of a stale credential | Use inside the window | **There is no on-device approval gate.** When enabled, SESSION_CODE (see @@ -146,8 +151,8 @@ hands a complete credential to every app with clipboard access. In `BrowserSecurity.NONE`, there is no code or authenticated principal. The dashboard still honors the host's `EditingCapabilities`, Composer allowlist, state-mutation flag, and capture-category -gates, but those are feature boundaries rather than browser identity. Mutation routes also reject a -foreign browser `Origin` (while allowing an absent `Origin` for command-line clients), which blocks +gates, but those are feature boundaries rather than browser identity. When Host/Origin checks are +enabled, mutation routes reject a foreign browser `Origin` (while allowing an absent `Origin` for command-line clients), which blocks cross-site browser requests but does not authenticate a client. Anyone who can reach the server can use the enabled surfaces, so do not use open mode on a shared or untrusted LAN. @@ -165,7 +170,8 @@ a remedy, not a proof of control. ## Redaction is an allowlist, and allowlists miss things -`RedactionPolicy.default()` matches a set of sensitive field names (case-insensitively) against +`RedactionPolicy.default()` is `none()` and masks nothing. The opt-in +`RedactionPolicy.recommended()` matches a set of sensitive field names (case-insensitively) against header names, JSON keys, and form/query field names. See [SECURITY_AND_REDACTION.md](SECURITY_AND_REDACTION.md) for the exact list. @@ -185,13 +191,13 @@ Everything not on that list is transmitted and stored **verbatim**. In practice `POST /api/v1/database/{name}/sql` requires the explicit `database` capability even for SELECT: enabling that capability is enabling raw, unredacted database access over the session. -Redaction is a guard against the *predictable* leak — the `Authorization` header you would otherwise -paste into a bug report. It is not a data-loss-prevention system, and it should not be the reason +When enabled, redaction guards against predictable leaks such as a known `password` field. +Authorization headers require an additional rule. Redaction is not a data-loss-prevention system, and it should not be the reason you feel comfortable putting a device on an untrusted network. Bodies are also truncated to 64 KiB before storage. That is a resource bound, not a privacy control. -## Safe defaults +## Explicit hardening **Untrusted or shared network — use loopback.** This is the recommended posture, and it is no longer the SDK's default: you have to ask for it. @@ -264,12 +270,13 @@ start `devconsole-agent`. The device allowlist still decides which hosts any age call; `--allow-host`/`--block-private` on the agent are an additional local lock. Unlike the phone's own transport, the agent reaches localhost/private/VPN addresses by default -- that is its purpose. -**`composerHostsEditable` hands the allowlist to anyone with the dashboard.** It is off by default. -When on, an authenticated session (anyone who can open the dashboard, in the default open mode) can +**`composerHostsEditable` hands the allowlist to anyone with the dashboard.** It is on by default, and +only matters once the app sets `composerAllowedHosts` (an empty list already permits any host). When on, +an authenticated session (anyone who can open the dashboard, in the default open mode) can add hosts that the device -- and any connected Composer agent -- will then call with whatever headers the request carries. Added hosts are session-only, capped, never override the app's own list, and every add or remove is in the command audit log. Enable it for debug builds on networks you control, -and use `BrowserSecurity.SESSION_CODE` anywhere else. +and use `BrowserSecurity.SESSION_CODE` with `composerHostsEditable(false)` anywhere else. **The bug report bundle, HAR export, Postman export, evidence bundle, and Android session ZIP are full-fidelity dumps.** `GET /api/v1/report`, `GET /api/v1/network/har`, and @@ -357,15 +364,17 @@ merge the `` entries into your existing files rather than replacing the **The Composer turns the device into a request proxy.** When enabled, an authenticated session can make the device issue arbitrary outbound HTTP requests from wherever it sits — including inside a corporate -network. It is off by default for this reason, and can be confined to an allowlist of hosts. See +network. It is enabled by default, with any host permitted. Set `composerEnabled = false` to disable +it or pass a non-empty `composerAllowedHosts` set to restrict destinations. See [COMPOSER_AND_MOCKS.md](COMPOSER_AND_MOCKS.md). **The `files` capability is write access to the app sandbox.** With it enabled, an authenticated session can create, replace, rename, and delete regular files anywhere under the four sandbox roots, and download raw, unredacted bytes. If your app loads anything executable or executable-adjacent out of those directories — a JS or Dex bundle, a dynamic config, a plugin — granting `files` to a browser -session is effectively granting code execution in your app. It is off by default; treat enabling it -with the same weight as the Composer and the SQL console. The Share action also registers a +session is effectively granting code execution in your app. It is enabled by default; use +`.withEditingCapabilities(EditingCapabilities.readOnly())` to disable writes, including this surface. +The Share action also registers a non-exported `FileProvider` (`.devconsole.files`) via manifest merge in every build that depends on `sdk:full`; grants are single-URI and temporary, but the provider's existence in your merged manifest is worth knowing about. diff --git a/docs/images/devconsole-mark.webp b/docs/images/devconsole-mark.webp index 11b58ba..a8af6ff 100644 Binary files a/docs/images/devconsole-mark.webp and b/docs/images/devconsole-mark.webp differ diff --git a/samples/compose-app/src/main/kotlin/io/devconsole/sample/compose/MainActivity.kt b/samples/compose-app/src/main/kotlin/io/devconsole/sample/compose/MainActivity.kt index 4dbdc51..ba386b1 100644 --- a/samples/compose-app/src/main/kotlin/io/devconsole/sample/compose/MainActivity.kt +++ b/samples/compose-app/src/main/kotlin/io/devconsole/sample/compose/MainActivity.kt @@ -80,10 +80,8 @@ import io.devconsole.api.BrowserEndpoint import io.devconsole.api.CrashPolicy import io.devconsole.api.DevConsoleConfig import io.devconsole.api.DevConsoleState -import io.devconsole.api.EditingCapabilities import io.devconsole.api.InspectorOpenResult import io.devconsole.api.OpenTriggers -import io.devconsole.api.ScreenshotPolicy import io.devconsole.api.ScreenshotResult import io.devconsole.api.ShakeIntensity import io.devconsole.api.StartRequest @@ -327,27 +325,23 @@ class MainActivity : ComponentActivity() { } /** - * Capability-flag matrix across the three samples (see each MainActivity's own comment for - * the rest of the row): compose-app is the full showcase, so every [EditingCapabilities] flag - * is unlocked -- the Data rail (preferences/database/files), mocks, capture rules, and the - * request composer are all live and editable from the browser and the in-app inspector -- and - * the two server-side gates that sit outside that enum, `composerEnabled` (with a host - * allowlist) and `stateMutationsEnabled`, are opted into as well. - * foundation-app leaves every flag at its `false` default to demonstrate the locked-down, - * read-only posture a production-adjacent debug build might ship with. views-java-app sits in - * between: mocks and capture rules are editable, but preferences/database/files stay read-only. + * This showcase relies on the SDK defaults: all editing capabilities, Composer, state + * mutations, and screenshots are enabled. Redaction and network protection are opt-in. + * foundation-app explicitly selects read-only capabilities and disables screenshots. * [OpenTriggers] follows the same gradient: this sample opts into both shake-to-open and the * floating button, views-java-app enables shake only, and foundation-app leaves both off. * - * Screenshot capture is off by default across the whole SDK -- [ScreenshotPolicy.enabled] - * defaults to `false` because a screenshot can't be redacted. This sample is the one that opts - * in, via [ScreenshotPolicy], so its "Capture screenshot" button renders a real - * [ScreenshotResult.Captured]; foundation-app leaves the default alone and shows the refusal - * verbatim instead -- seeing both side by side is the fastest way to understand the gate. + * Screenshots are enabled by default and cannot be redacted. The capture button renders a real + * [ScreenshotResult.Captured]; foundation-app explicitly disables capture to show the refusal. * [CrashPolicy.anrThresholdMs] is also shortened here (see [DEMO_ANR_THRESHOLD_MS]) purely so * the hazard-zone ANR button below trips the watchdog quickly during a demo. */ private fun buildConfig() = + // Optional hardening (imports: io.devconsole.api.*, io.devconsole.security.RedactionPolicy): + // DevConsoleConfig(redactionPolicy = RedactionPolicy.recommended()) + // .withNetworkProtection(NetworkProtection.recommended()) + // .withEditingCapabilities(EditingCapabilities.readOnly()) + // .withBrowserSecurity(BrowserSecurity.SESSION_CODE) DevConsoleConfig( stateProviders = listOf( @@ -363,13 +357,6 @@ class MainActivity : ComponentActivity() { description = "Shows the order-history placeholder in the sample UI", ), ), - // The Composer makes the device issue outbound requests, so it stays off unless the - // host opts in. This showcase opts in, but confines it to the hosts the sample itself - // talks to -- an empty allowlist denies every destination, so naming them is required. - composerEnabled = true, - composerAllowedHosts = setOf("jsonplaceholder.typicode.com", "example.test", "postman-echo.com"), - // Lets the dashboard drive registered state mutations; state is read-only otherwise. - stateMutationsEnabled = true, ).withRemoteConfigProviders( listOf(SampleRemoteConfigProvider()), ).withBrowserConfig( @@ -379,19 +366,7 @@ class MainActivity : ComponentActivity() { // URLs depending on where you pressed start. LAN carries the exposure spelled out at // that call site and in docs/THREAT_MODEL.md. BrowserConfig(binding = BrowserBinding.LAN), - ).withEditingCapabilities( - EditingCapabilities - .builder() - .preferences(true) - .database(true) - .files(true) - .mocks(true) - .captureRules(true) - .featureFlags(true) - .requestExecution(true) - .build(), - ).withScreenshotPolicy(ScreenshotPolicy(enabled = true)) - .withCrashPolicy(CrashPolicy(anrThresholdMs = DEMO_ANR_THRESHOLD_MS)) + ).withCrashPolicy(CrashPolicy(anrThresholdMs = DEMO_ANR_THRESHOLD_MS)) .withOpenTriggers( OpenTriggers(shakeToOpen = true, shakeIntensity = ShakeIntensity.MEDIUM, floatingButton = true), ).withComposerHostsEditable(true) @@ -598,7 +573,7 @@ class MainActivity : ComponentActivity() { ) CapabilityCard( title = "Capture screenshot", - subtitle = "ScreenshotPolicy.enabled = true here -- foundation-app shows the default-off refusal", + subtitle = "Screenshots are enabled by default -- foundation-app explicitly disables capture", onClick = { scope.launch { lastResponse = captureScreenshot() } }, ) CapabilityCard( @@ -756,7 +731,7 @@ class MainActivity : ComponentActivity() { /** * Exercises every [ScreenshotResult] variant Kotlin's exhaustive `when` demands. Because this - * sample's [buildConfig] opts into [ScreenshotPolicy], the ordinary path here is + * sample's [buildConfig] uses the default screenshot policy, the ordinary path here is * [ScreenshotResult.Captured] -- the other branches exist for completeness and are the ones * foundation-app actually reaches from its default-off policy. */ @@ -806,7 +781,7 @@ private fun seedSampleData(context: Context) { .putBoolean("darkModeEnabled", true) .putFloat("checkoutProgress", 0.65f) // Two non-secret values that together show how key-based redaction actually behaves. - // "access_token" is on RedactionPolicy.default()'s name list, so the inspector masks it. + // "access_token" is visible by default; RedactionPolicy.recommended() opts into masking it. .putString("access_token", "sample-not-a-real-token-4f9c2b") // "authToken" is NOT on that list. Redaction matches field names exactly, so this one is // shown verbatim -- the allowlist blind spot docs/THREAT_MODEL.md warns about, made diff --git a/samples/foundation-app/src/main/kotlin/io/devconsole/sample/MainActivity.kt b/samples/foundation-app/src/main/kotlin/io/devconsole/sample/MainActivity.kt index a59e70b..9bbd6db 100644 --- a/samples/foundation-app/src/main/kotlin/io/devconsole/sample/MainActivity.kt +++ b/samples/foundation-app/src/main/kotlin/io/devconsole/sample/MainActivity.kt @@ -31,6 +31,7 @@ import io.devconsole.api.BrowserConfig import io.devconsole.api.DevConsoleConfig import io.devconsole.api.DevConsoleState import io.devconsole.api.EditingCapabilities +import io.devconsole.api.ScreenshotPolicy import io.devconsole.api.ScreenshotResult import io.devconsole.api.StartRequest import io.devconsole.api.StartResult @@ -89,14 +90,14 @@ private const val ANR_BLOCK_MS = 6_000L * Capability-flag posture (see compose-app's `MainActivity` for the full three-sample matrix): * [EditingCapabilities.readOnly] refuses every write here, on purpose -- this sample is the * locked-down contrast to compose-app's fully-unlocked one. Note that this now takes an explicit - * call: the SDK's own default leaves `mocks` editable, and `readOnly()` is what opts back out. The + * call: the SDK's own default enables every capability, and `readOnly()` opts out. The * Data rail (preferences/database/files, seeded below) is still visible and browsable in both the * browser dashboard and the SDK's in-app inspector; only the write/edit actions are refused. * - * Screenshot capture follows the same posture: `ScreenshotPolicy.enabled` is left at its SDK-wide - * `false` default (no `withScreenshotPolicy` override), so the "Capture screenshot" button here + * Screenshot capture follows the same posture: `ScreenshotPolicy.enabled` is explicitly set to + * `false`, so the "Capture screenshot" button here * always renders [ScreenshotResult.Disabled] verbatim, naming the property a host would set to turn - * it on. compose-app is the sample that opts in -- seeing the refusal here next to compose-app's + * it on. compose-app uses the enabled default -- seeing the refusal here next to compose-app's * real capture is the fastest way to understand the gate. * * The HAZARD ZONE below is deliberately set apart from the ordinary demo buttons: one button throws @@ -122,6 +123,11 @@ class MainActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) + // Optional hardening (imports: io.devconsole.api.*, io.devconsole.security.RedactionPolicy): + // DevConsoleConfig(redactionPolicy = RedactionPolicy.recommended()) + // .withNetworkProtection(NetworkProtection.recommended()) + // .withEditingCapabilities(EditingCapabilities.readOnly()) + // .withBrowserSecurity(BrowserSecurity.SESSION_CODE) DevConsole.initialize( application, DevConsoleConfig( @@ -139,10 +145,13 @@ class MainActivity : Activity() { description = "Shows extra diagnostics in the sample UI", ), ), + composerEnabled = false, + stateMutationsEnabled = false, // Explicit, not just the default: this sample's whole point is the locked-down // contrast to compose-app's fully-unlocked EditingCapabilities. // OpenTriggers likewise stays at its all-off default -- no shake-to-open, no floating button. ).withEditingCapabilities(EditingCapabilities.readOnly()) + .withScreenshotPolicy(ScreenshotPolicy(enabled = false)) // Matches the BindingMode.LAN this sample's own Start button passes: the in-app // inspector's More screen issues no StartRequest, so without this it would bind // loopback and the two start paths would hand out different connect URLs. This is @@ -412,8 +421,8 @@ class MainActivity : Activity() { /** * Exercises every [ScreenshotResult] variant Kotlin's exhaustive `when` demands. Since this - * sample's config never calls `withScreenshotPolicy`, [ScreenshotResult.Disabled] is the branch - * actually reached here -- the other variants are what compose-app's opted-in capture reaches + * sample's config explicitly disables screenshots, [ScreenshotResult.Disabled] is the branch + * actually reached here -- the other variants are what compose-app's default capture reaches * instead. */ private fun captureScreenshot() { @@ -423,7 +432,7 @@ class MainActivity : Activity() { "Screenshot captured: ${result.widthPx}x${result.heightPx}, ${result.byteCount} bytes" ScreenshotResult.Disabled -> "Screenshot capture is off -- set screenshotPolicy.enabled = true on DevConsoleConfig " + - "(left at the default here to show the locked-down refusal; compose-app opts in)" + "(explicitly disabled here to show the read-only setup; compose-app uses defaults)" ScreenshotResult.DisabledForBuild -> "Screenshot capture isn't available in this release build" ScreenshotResult.NoForegroundActivity -> "No foreground activity to capture -- bring the app to the front and try again" diff --git a/sdk/api/api/api.api b/sdk/api/api/api.api index 5db4bf0..8f28093 100644 --- a/sdk/api/api/api.api +++ b/sdk/api/api/api.api @@ -266,6 +266,7 @@ public final class io/devconsole/api/DevConsoleConfig { public final fun getEditingCapabilities ()Lio/devconsole/api/EditingCapabilities; public final fun getEventBufferCapacity ()I public final fun getFeatureFlags ()Ljava/util/List; + public final fun getNetworkProtection ()Lio/devconsole/api/NetworkProtection; public final fun getOpenTriggers ()Lio/devconsole/api/OpenTriggers; public final fun getRedactionPolicy ()Lio/devconsole/security/RedactionPolicy; public final fun getRemoteConfigProviders ()Ljava/util/List; @@ -288,6 +289,7 @@ public final class io/devconsole/api/DevConsoleConfig { public final fun withComposerHostsEditable (Z)Lio/devconsole/api/DevConsoleConfig; public final fun withCrashPolicy (Lio/devconsole/api/CrashPolicy;)Lio/devconsole/api/DevConsoleConfig; public final fun withEditingCapabilities (Lio/devconsole/api/EditingCapabilities;)Lio/devconsole/api/DevConsoleConfig; + public final fun withNetworkProtection (Lio/devconsole/api/NetworkProtection;)Lio/devconsole/api/DevConsoleConfig; public final fun withOpenTriggers (Lio/devconsole/api/OpenTriggers;)Lio/devconsole/api/DevConsoleConfig; public final fun withRemoteConfigProviders (Ljava/util/List;)Lio/devconsole/api/DevConsoleConfig; public final fun withRetentionPolicy (Lio/devconsole/api/RetentionPolicy;)Lio/devconsole/api/DevConsoleConfig; @@ -312,6 +314,7 @@ public final class io/devconsole/api/DevConsoleConfig$Builder { public final fun crashPolicy (Lio/devconsole/api/CrashPolicy;)Lio/devconsole/api/DevConsoleConfig$Builder; public final fun editingCapabilities (Lio/devconsole/api/EditingCapabilities;)Lio/devconsole/api/DevConsoleConfig$Builder; public final fun eventBufferCapacity (I)Lio/devconsole/api/DevConsoleConfig$Builder; + public final fun networkProtection (Lio/devconsole/api/NetworkProtection;)Lio/devconsole/api/DevConsoleConfig$Builder; public final fun openTriggers (Lio/devconsole/api/OpenTriggers;)Lio/devconsole/api/DevConsoleConfig$Builder; public final fun redactionPolicy (Lio/devconsole/security/RedactionPolicy;)Lio/devconsole/api/DevConsoleConfig$Builder; public final fun retentionPolicy (Lio/devconsole/api/RetentionPolicy;)Lio/devconsole/api/DevConsoleConfig$Builder; @@ -618,6 +621,27 @@ public final class io/devconsole/api/InspectorOpenResult$Opened : io/devconsole/ public fun toString ()Ljava/lang/String; } +public final class io/devconsole/api/NetworkProtection { + public static final field Companion Lio/devconsole/api/NetworkProtection$Companion; + public fun ()V + public fun (ZZ)V + public synthetic fun (ZZILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Z + public final fun component2 ()Z + public final fun copy (ZZ)Lio/devconsole/api/NetworkProtection; + public static synthetic fun copy$default (Lio/devconsole/api/NetworkProtection;ZZILjava/lang/Object;)Lio/devconsole/api/NetworkProtection; + public fun equals (Ljava/lang/Object;)Z + public final fun getHostAndOriginChecks ()Z + public final fun getRateLimiting ()Z + public fun hashCode ()I + public static final fun recommended ()Lio/devconsole/api/NetworkProtection; + public fun toString ()Ljava/lang/String; +} + +public final class io/devconsole/api/NetworkProtection$Companion { + public final fun recommended ()Lio/devconsole/api/NetworkProtection; +} + public final class io/devconsole/api/OpenTriggers { public static final field Companion Lio/devconsole/api/OpenTriggers$Companion; public fun ()V diff --git a/sdk/api/src/main/kotlin/io/devconsole/api/DevConsoleConfig.kt b/sdk/api/src/main/kotlin/io/devconsole/api/DevConsoleConfig.kt index ffc4952..198992e 100644 --- a/sdk/api/src/main/kotlin/io/devconsole/api/DevConsoleConfig.kt +++ b/sdk/api/src/main/kotlin/io/devconsole/api/DevConsoleConfig.kt @@ -24,14 +24,14 @@ data class DevConsoleConfig( val featureFlags: List = emptyList(), /** * Enables the Composer, which lets an authenticated session make the device issue arbitrary - * outbound HTTP requests. Off by default because that turns the device into a proxy onto its - * network; pair with [composerAllowedHosts] to confine it to known backends. + * outbound HTTP requests. Enabled by default; set [composerAllowedHosts] to confine it to + * known backends, or disable it explicitly. */ - val composerEnabled: Boolean = false, - /** Exact hosts the Composer may reach when [composerEnabled]. Empty denies every destination. */ + val composerEnabled: Boolean = true, + /** Exact hosts the Composer may reach when [composerEnabled]. Empty allows any host. */ val composerAllowedHosts: Set = emptySet(), - /** Enables dashboard-driven state mutations. Off by default; state stays read-only otherwise. */ - val stateMutationsEnabled: Boolean = false, + /** Enables dashboard-driven state mutations. Set false to opt in to read-only state. */ + val stateMutationsEnabled: Boolean = true, /** Redaction applied at every capture boundary and reported to the dashboard. */ val redactionPolicy: RedactionPolicy = RedactionPolicy.default(), ) { @@ -39,13 +39,13 @@ data class DevConsoleConfig( var storagePolicy: StoragePolicy = StoragePolicy() private set - var composerHostsEditable: Boolean = false + var composerHostsEditable: Boolean = true private set var sessionPolicy: SessionPolicy = SessionPolicy() private set - /** Defaults to [EditingCapabilities]'s own defaults -- everything read-only but mocks. */ + /** Defaults to [EditingCapabilities]'s own defaults -- every capability enabled. */ var editingCapabilities: EditingCapabilities = EditingCapabilities() private set @@ -62,11 +62,15 @@ data class DevConsoleConfig( var browserSecurity: BrowserSecurity = BrowserSecurity.NONE private set + /** Request budgets and Host/Origin validation are opt-in, independently of browser authentication. */ + var networkProtection: NetworkProtection = NetworkProtection() + private set + /** Uncaught-exception / ANR capture depth. See [CrashPolicy] for the enable gates and caps. */ var crashPolicy: CrashPolicy = CrashPolicy() private set - /** Foreground-window screenshot capture. See [ScreenshotPolicy] for why it is off by default. */ + /** Foreground-window screenshot capture, enabled by default. */ var screenshotPolicy: ScreenshotPolicy = ScreenshotPolicy() private set @@ -125,6 +129,9 @@ data class DevConsoleConfig( fun withBrowserSecurity(value: BrowserSecurity): DevConsoleConfig = duplicate().also { it.browserSecurity = value } + fun withNetworkProtection(value: NetworkProtection): DevConsoleConfig = + duplicate().also { it.networkProtection = value } + fun withCrashPolicy(value: CrashPolicy): DevConsoleConfig = duplicate().also { it.crashPolicy = value } fun withScreenshotPolicy(value: ScreenshotPolicy): DevConsoleConfig = @@ -187,6 +194,7 @@ data class DevConsoleConfig( retentionPolicy == other.retentionPolicy && browserConfig == other.browserConfig && browserSecurity == other.browserSecurity && + networkProtection == other.networkProtection && crashPolicy == other.crashPolicy && screenshotPolicy == other.screenshotPolicy && captureCategories == other.captureCategories && @@ -202,6 +210,7 @@ data class DevConsoleConfig( it.retentionPolicy = retentionPolicy it.browserConfig = browserConfig it.browserSecurity = browserSecurity + it.networkProtection = networkProtection it.crashPolicy = crashPolicy it.screenshotPolicy = screenshotPolicy it.captureCategories = captureCategories @@ -215,10 +224,10 @@ data class DevConsoleConfig( private var eventBufferCapacity: Int = DEFAULT_EVENT_BUFFER_CAPACITY private val stateProviders = mutableListOf() private val featureFlags = mutableListOf() - private var composerEnabled: Boolean = false + private var composerEnabled: Boolean = true private var composerAllowedHosts: Set = emptySet() - private var composerHostsEditable: Boolean = false - private var stateMutationsEnabled: Boolean = false + private var composerHostsEditable: Boolean = true + private var stateMutationsEnabled: Boolean = true private var redactionPolicy: RedactionPolicy = RedactionPolicy.default() private var storagePolicy: StoragePolicy = StoragePolicy() private var sessionPolicy: SessionPolicy = SessionPolicy() @@ -226,6 +235,7 @@ data class DevConsoleConfig( private var retentionPolicy: RetentionPolicy? = null private var browserConfig = BrowserConfig() private var browserSecurity = BrowserSecurity.NONE + private var networkProtection = NetworkProtection() private var crashPolicy = CrashPolicy() private var screenshotPolicy = ScreenshotPolicy() private var captureCategories: Set = CaptureCategory.all() @@ -260,6 +270,8 @@ data class DevConsoleConfig( fun browserSecurity(value: BrowserSecurity) = apply { browserSecurity = value } + fun networkProtection(value: NetworkProtection) = apply { networkProtection = value } + fun crashPolicy(value: CrashPolicy) = apply { crashPolicy = value } fun screenshotPolicy(value: ScreenshotPolicy) = apply { screenshotPolicy = value } @@ -288,6 +300,7 @@ data class DevConsoleConfig( .withEditingCapabilities(editingCapabilities) .withBrowserConfig(browserConfig) .withBrowserSecurity(browserSecurity) + .withNetworkProtection(networkProtection) .withCrashPolicy(crashPolicy) .withScreenshotPolicy(screenshotPolicy) .withCaptureCategories(captureCategories) diff --git a/sdk/api/src/main/kotlin/io/devconsole/api/EditingCapabilities.kt b/sdk/api/src/main/kotlin/io/devconsole/api/EditingCapabilities.kt index 6b5cfbe..8c56ae8 100644 --- a/sdk/api/src/main/kotlin/io/devconsole/api/EditingCapabilities.kt +++ b/sdk/api/src/main/kotlin/io/devconsole/api/EditingCapabilities.kt @@ -3,32 +3,29 @@ package io.devconsole.api /** * Per-surface write permissions for the dashboard and the in-app inspector. * - * Everything defaults to off except [mocks]. A mock rule writes nothing that belongs to the host -- - * it only short-circuits DevConsole's own OkHttp interceptor -- so the read-only posture that - * protects preferences, databases, and files has nothing to protect here, while a Mocks screen that - * cannot add a mock is the most common "is this thing broken?" first run. Pass `mocks = false`, or - * use [readOnly], to take it back. + * Every capability is enabled by default for this debug-only tool. Use [readOnly] to opt in + * to a read-only inspector, or disable individual capabilities explicitly. * * Editing mock rules still requires [CaptureCategory.MOCKS] to be enabled; the two gates are * separate and both must hold. */ data class EditingCapabilities( - val preferences: Boolean = false, - val featureFlags: Boolean = false, - val database: Boolean = false, - val files: Boolean = false, + val preferences: Boolean = true, + val featureFlags: Boolean = true, + val database: Boolean = true, + val files: Boolean = true, val mocks: Boolean = true, - val requestExecution: Boolean = false, - val captureRules: Boolean = false, + val requestExecution: Boolean = true, + val captureRules: Boolean = true, ) { class Builder { - private var preferences = false - private var featureFlags = false - private var database = false - private var files = false + private var preferences = true + private var featureFlags = true + private var database = true + private var files = true private var mocks = true - private var requestExecution = false - private var captureRules = false + private var requestExecution = true + private var captureRules = true fun preferences(value: Boolean) = apply { preferences = value } @@ -58,9 +55,7 @@ data class EditingCapabilities( companion object { /** - * Grants nothing at all, [mocks] included. Spelled out rather than delegating to the no-arg - * constructor, which now enables mocks -- a host that asks for read-only must get exactly - * that, whatever the defaults drift to later. + * Opt-in read-only policy: grants no editing capability, including mocks. */ @JvmStatic fun readOnly(): EditingCapabilities = diff --git a/sdk/api/src/main/kotlin/io/devconsole/api/NetworkProtection.kt b/sdk/api/src/main/kotlin/io/devconsole/api/NetworkProtection.kt new file mode 100644 index 0000000..56d8337 --- /dev/null +++ b/sdk/api/src/main/kotlin/io/devconsole/api/NetworkProtection.kt @@ -0,0 +1,16 @@ +/** + * @author Shakib + * @since 19/10/26 + */ +package io.devconsole.api + +/** Optional request budgets and Host/Origin validation for the embedded dashboard server. */ +data class NetworkProtection( + val rateLimiting: Boolean = false, + val hostAndOriginChecks: Boolean = false, +) { + companion object { + @JvmStatic + fun recommended(): NetworkProtection = NetworkProtection(true, true) + } +} diff --git a/sdk/api/src/main/kotlin/io/devconsole/api/ScreenshotPolicy.kt b/sdk/api/src/main/kotlin/io/devconsole/api/ScreenshotPolicy.kt index 8049d4f..dad33e4 100644 --- a/sdk/api/src/main/kotlin/io/devconsole/api/ScreenshotPolicy.kt +++ b/sdk/api/src/main/kotlin/io/devconsole/api/ScreenshotPolicy.kt @@ -8,14 +8,13 @@ package io.devconsole.api * Controls whether and how [io.devconsole.DevConsole.captureScreenshot] may capture the foreground * window. * - * [enabled] defaults to `false` -- a deliberate product decision, not an oversight. A screenshot - * cannot be redacted (see `RedactionApplicability.NOT_APPLICABLE` in `sdk:storage-api`), so it is the - * single most sensitive artifact this SDK can produce; a host must opt in explicitly. [maxLongestEdgePx] + * [enabled] defaults to `true`; set it to `false` to disable screenshots. A screenshot + * cannot be redacted (see `RedactionApplicability.NOT_APPLICABLE` in `sdk:storage-api`). [maxLongestEdgePx] * bounds the downscaled image's longer edge; [maxBytes] bounds the encoded PNG, and a capture that * would exceed it is rejected rather than stored. */ data class ScreenshotPolicy( - val enabled: Boolean = false, + val enabled: Boolean = true, val maxLongestEdgePx: Int = DEFAULT_MAX_LONGEST_EDGE_PX, val maxBytes: Long = DEFAULT_MAX_BYTES, ) { diff --git a/sdk/api/src/test/kotlin/io/devconsole/api/ComposerHostsEditableConfigTest.kt b/sdk/api/src/test/kotlin/io/devconsole/api/ComposerHostsEditableConfigTest.kt index c111d01..535a53a 100644 --- a/sdk/api/src/test/kotlin/io/devconsole/api/ComposerHostsEditableConfigTest.kt +++ b/sdk/api/src/test/kotlin/io/devconsole/api/ComposerHostsEditableConfigTest.kt @@ -7,9 +7,9 @@ import kotlin.test.assertTrue class ComposerHostsEditableConfigTest { @Test - fun `the allowlist is read-only unless the app opts in`() { - assertFalse(DevConsoleConfig.default().composerHostsEditable) - assertFalse( + fun `the allowlist is editable unless the app opts out`() { + assertTrue(DevConsoleConfig.default().composerHostsEditable) + assertTrue( DevConsoleConfig .Builder() .composerEnabled(true) @@ -40,9 +40,9 @@ class ComposerHostsEditableConfigTest { @Test fun `runtime equivalence notices a changed flag`() { - val off = DevConsoleConfig.default() + val editable = DevConsoleConfig.default() - assertFalse(off.runtimeEquivalentTo(off.withComposerHostsEditable(true))) - assertTrue(off.runtimeEquivalentTo(off.withComposerHostsEditable(false))) + assertFalse(editable.runtimeEquivalentTo(editable.withComposerHostsEditable(false))) + assertTrue(editable.runtimeEquivalentTo(editable.withComposerHostsEditable(true))) } } diff --git a/sdk/api/src/test/kotlin/io/devconsole/api/FocusedConfigurationTest.kt b/sdk/api/src/test/kotlin/io/devconsole/api/FocusedConfigurationTest.kt index f70ce37..b289995 100644 --- a/sdk/api/src/test/kotlin/io/devconsole/api/FocusedConfigurationTest.kt +++ b/sdk/api/src/test/kotlin/io/devconsole/api/FocusedConfigurationTest.kt @@ -6,23 +6,17 @@ import org.junit.Assert.assertTrue import org.junit.Test class FocusedConfigurationTest { - /** - * Mocks are the one editable-by-default surface. They write nothing of the host's -- a mock rule - * only ever short-circuits DevConsole's own interceptor -- so the read-only posture that protects - * preferences, databases, and files buys nothing here, and an empty Mocks screen with a disabled - * "Add rule" button was the single most common "is this broken?" first run. - */ @Test - fun `editing is read only by default except for mocks`() { + fun `editing is enabled by default`() { val policy = EditingCapabilities() - assertFalse(policy.preferences) - assertFalse(policy.featureFlags) - assertFalse(policy.database) - assertFalse(policy.files) + assertTrue(policy.preferences) + assertTrue(policy.featureFlags) + assertTrue(policy.database) + assertTrue(policy.files) assertTrue(policy.mocks) - assertFalse(policy.requestExecution) - assertFalse(policy.captureRules) + assertTrue(policy.requestExecution) + assertTrue(policy.captureRules) } @Test @@ -30,11 +24,6 @@ class FocusedConfigurationTest { assertFalse(EditingCapabilities(mocks = false).mocks) } - /** - * [EditingCapabilities.readOnly] has to keep meaning what its name says even though the no-arg - * constructor no longer does. A host that asked for read-only and silently got writable mocks - * would be the worst possible reading of this change. - */ @Test fun `read only factory grants nothing including mocks`() { val policy = EditingCapabilities.readOnly() @@ -49,7 +38,7 @@ class FocusedConfigurationTest { } @Test - fun `java builder starts from the mocks enabled default`() { + fun `java builder starts from the editable default`() { assertTrue(EditingCapabilities.builder().build().mocks) assertFalse( EditingCapabilities @@ -60,20 +49,15 @@ class FocusedConfigurationTest { ) } - /** - * The capability object's default is only half the story -- [DevConsoleConfig] has to actually - * carry it. It used to seed [EditingCapabilities.readOnly], which still grants nothing, so a - * host that configured no capabilities at all would otherwise keep getting read-only mocks. - */ @Test - fun `default config makes mocks editable and nothing else`() { + fun `default config makes every capability editable`() { val editing = DevConsoleConfig.default().editingCapabilities assertTrue(editing.mocks) - assertFalse(editing.preferences) - assertFalse(editing.database) - assertFalse(editing.files) - assertFalse(editing.captureRules) + assertTrue(editing.preferences) + assertTrue(editing.database) + assertTrue(editing.files) + assertTrue(editing.captureRules) } @Test @@ -87,19 +71,19 @@ class FocusedConfigurationTest { } @Test - fun `java builder enables only requested editing capabilities`() { + fun `java builder disables only requested editing capabilities`() { val policy = EditingCapabilities .builder() - .preferences(true) + .preferences(false) .mocks(true) .build() - assertTrue(policy.preferences) + assertFalse(policy.preferences) assertTrue(policy.mocks) - assertFalse(policy.database) - assertFalse(policy.files) - assertFalse(policy.requestExecution) + assertTrue(policy.database) + assertTrue(policy.files) + assertTrue(policy.requestExecution) } @Test diff --git a/sdk/api/src/test/kotlin/io/devconsole/api/ScreenshotPolicyTest.kt b/sdk/api/src/test/kotlin/io/devconsole/api/ScreenshotPolicyTest.kt index d637738..5730f18 100644 --- a/sdk/api/src/test/kotlin/io/devconsole/api/ScreenshotPolicyTest.kt +++ b/sdk/api/src/test/kotlin/io/devconsole/api/ScreenshotPolicyTest.kt @@ -11,10 +11,10 @@ import org.junit.Test class ScreenshotPolicyTest { @Test - fun `defaults match the design spec, including being off by default`() { + fun `screenshots are enabled by default with bounded dimensions and bytes`() { val policy = ScreenshotPolicy() - assertFalse(policy.enabled) + assertTrue(policy.enabled) assertEquals(1080, policy.maxLongestEdgePx) assertEquals(2L * 1024 * 1024, policy.maxBytes) assertTrue(policy.validationErrors().isEmpty()) @@ -93,7 +93,7 @@ class ScreenshotPolicyTest { } @Test - fun `default DevConsoleConfig keeps screenshot capture disabled`() { - assertFalse(DevConsoleConfig.default().screenshotPolicy.enabled) + fun `default DevConsoleConfig enables screenshot capture`() { + assertTrue(DevConsoleConfig.default().screenshotPolicy.enabled) } } diff --git a/sdk/api/src/test/kotlin/io/devconsole/api/SecurityDefaultsTest.kt b/sdk/api/src/test/kotlin/io/devconsole/api/SecurityDefaultsTest.kt new file mode 100644 index 0000000..67b0dea --- /dev/null +++ b/sdk/api/src/test/kotlin/io/devconsole/api/SecurityDefaultsTest.kt @@ -0,0 +1,53 @@ +/** + * @author Shakib + * @since 19/10/26 + */ +package io.devconsole.api + +import io.devconsole.security.RedactionPolicy +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class SecurityDefaultsTest { + @Test + fun `constructor and Java builder enable development features without security layers`() { + listOf(DevConsoleConfig(), DevConsoleConfig.builder().build()).forEach { config -> + assertEquals(RedactionPolicy.none(), config.redactionPolicy) + assertEquals(NetworkProtection(false, false), config.networkProtection) + assertEquals(BrowserSecurity.NONE, config.browserSecurity) + assertEquals(EditingCapabilities(), config.editingCapabilities) + assertTrue(config.composerEnabled) + assertTrue(config.composerAllowedHosts.isEmpty()) + assertTrue(config.stateMutationsEnabled) + assertTrue(config.screenshotPolicy.enabled) + } + assertEquals(EditingCapabilities(), EditingCapabilities.builder().build()) + } + + @Test + fun `network protection survives additive copies and changes runtime equivalence`() { + val protection = NetworkProtection.recommended() + val config = + DevConsoleConfig() + .withNetworkProtection(protection) + .withEditingCapabilities(EditingCapabilities.readOnly()) + .withBrowserSecurity(BrowserSecurity.SESSION_CODE) + + assertEquals(protection, config.networkProtection) + assertFalse(config.runtimeEquivalentTo(DevConsoleConfig())) + assertFalse( + DevConsoleConfig().withNetworkProtection(protection).runtimeEquivalentTo(DevConsoleConfig()), + ) + assertEquals( + protection, + DevConsoleConfig + .builder() + .networkProtection(protection) + .build() + .networkProtection, + ) + assertEquals(NetworkProtection(false, false), DevConsoleConfig().networkProtection) + } +} diff --git a/sdk/composer/src/main/kotlin/io/devconsole/composer/ComposerImportAndCollections.kt b/sdk/composer/src/main/kotlin/io/devconsole/composer/ComposerImportAndCollections.kt index 9a420a3..8ef86ac 100644 --- a/sdk/composer/src/main/kotlin/io/devconsole/composer/ComposerImportAndCollections.kt +++ b/sdk/composer/src/main/kotlin/io/devconsole/composer/ComposerImportAndCollections.kt @@ -120,7 +120,7 @@ interface ComposerCollectionStore { fun remove(id: String): Boolean } -/** Ephemeral store; secret variable values are intentionally stripped before retaining a collection. */ +/** Ephemeral store; the configured policy controls masking, including secret variables. */ class InMemoryComposerCollectionStore( private val redaction: RedactionEngine = RedactionEngine(RedactionPolicy.default()), ) : ComposerCollectionStore { @@ -137,7 +137,7 @@ class InMemoryComposerCollectionStore( .copy( variables = redactedRequest.variables.map { variable -> - if (variable.secret) variable.copy(value = "") else variable + if (variable.secret && redaction.isEnabled()) variable.copy(value = "") else variable }, ).detached() val stored = ComposerCollection(UUID.randomUUID().toString(), redaction.redactText(name.trim()), safeRequest) diff --git a/sdk/composer/src/main/kotlin/io/devconsole/composer/ComposerRequest.kt b/sdk/composer/src/main/kotlin/io/devconsole/composer/ComposerRequest.kt index 4f96445..ea1bb27 100644 --- a/sdk/composer/src/main/kotlin/io/devconsole/composer/ComposerRequest.kt +++ b/sdk/composer/src/main/kotlin/io/devconsole/composer/ComposerRequest.kt @@ -79,8 +79,8 @@ data class ComposerRequest( /** * Returns the only representation that may be persisted or sent to a browser. Binary bytes and - * secret variable values are dropped; every remaining string crosses the active redaction - * boundary before it is copied. + * binary payloads are omitted; secret variables are masked only when redaction is enabled. + * Every remaining string crosses the active redaction boundary before it is copied. */ fun redacted(redaction: RedactionEngine): ComposerRequest = copy( @@ -120,7 +120,12 @@ data class ComposerRequest( variables.map { variable -> variable.copy( name = redaction.redactText(variable.name), - value = if (variable.secret) redaction.replacement() else redaction.redactText(variable.value), + value = + if (variable.secret && redaction.isEnabled()) { + redaction.replacement() + } else { + redaction.redactText(variable.value) + }, ) }, ) diff --git a/sdk/composer/src/test/kotlin/io/devconsole/composer/ComposerRequestTest.kt b/sdk/composer/src/test/kotlin/io/devconsole/composer/ComposerRequestTest.kt index 29a1d7c..9a7227f 100644 --- a/sdk/composer/src/test/kotlin/io/devconsole/composer/ComposerRequestTest.kt +++ b/sdk/composer/src/test/kotlin/io/devconsole/composer/ComposerRequestTest.kt @@ -61,7 +61,7 @@ class ComposerRequestTest { @Test fun `redacted projection removes secrets from every persisted composer field`() { - val engine = RedactionEngine(RedactionPolicy.default()) + val engine = RedactionEngine(RedactionPolicy.recommended()) val request = ComposerRequest( method = "POST", @@ -150,7 +150,7 @@ class ComposerRequestTest { } @Test fun `stores collections without persisting variables marked secret`() { - val store = InMemoryComposerCollectionStore() + val store = InMemoryComposerCollectionStore(RedactionEngine(RedactionPolicy.recommended())) val saved = store.save( "smoke", @@ -173,4 +173,20 @@ class ComposerRequestTest { ) assertEquals(saved.id, store.collections().single().id) } + + @Test + fun `default policy preserves secret variables and token fields in saved collections`() { + val request = + ComposerRequest( + method = "POST", + url = "https://api.test?token=raw-url-token", + body = """{"token":"raw-body-token"}""", + variables = listOf(ComposerVariable("token", "raw-variable", secret = true)), + ) + val projected = request.redacted(RedactionEngine(RedactionPolicy.default())) + val saved = InMemoryComposerCollectionStore().save("default", request) + + assertEquals(request, projected) + assertEquals(request, saved.request) + } } diff --git a/sdk/core/src/test/kotlin/io/devconsole/core/EventBatchWriterTest.kt b/sdk/core/src/test/kotlin/io/devconsole/core/EventBatchWriterTest.kt index 18d78b5..0e4c62c 100644 --- a/sdk/core/src/test/kotlin/io/devconsole/core/EventBatchWriterTest.kt +++ b/sdk/core/src/test/kotlin/io/devconsole/core/EventBatchWriterTest.kt @@ -106,8 +106,14 @@ class EventBatchWriterTest { private fun event( summary: String, severity: EventSeverity = EventSeverity.INFO, - ) = EventPipeline(UUID.randomUUID(), 2) - .publish(EventDraft("network", "request", severity, summary)) + ) = EventPipeline( + UUID.randomUUID(), + 2, + io.devconsole.security.RedactionEngine( + io.devconsole.security.RedactionPolicy + .recommended(), + ), + ).publish(EventDraft("network", "request", severity, summary)) private class RecordingEventStore : EventStore { val batches = mutableListOf>() diff --git a/sdk/core/src/test/kotlin/io/devconsole/core/EventPipelineTest.kt b/sdk/core/src/test/kotlin/io/devconsole/core/EventPipelineTest.kt index 1675545..1ab1ad1 100644 --- a/sdk/core/src/test/kotlin/io/devconsole/core/EventPipelineTest.kt +++ b/sdk/core/src/test/kotlin/io/devconsole/core/EventPipelineTest.kt @@ -37,7 +37,16 @@ class EventPipelineTest { @Test fun `redacts event content before it reaches the observable bus`() = runTest { - val pipeline = EventPipeline(UUID.randomUUID(), capacity = 2) + val pipeline = + EventPipeline( + UUID.randomUUID(), + capacity = 2, + redactionEngine = + io.devconsole.security.RedactionEngine( + io.devconsole.security.RedactionPolicy + .recommended(), + ), + ) pipeline.publish( EventDraft( diff --git a/sdk/export/src/test/kotlin/io/devconsole/export/EventExportWriterTest.kt b/sdk/export/src/test/kotlin/io/devconsole/export/EventExportWriterTest.kt index 99f100a..660553c 100644 --- a/sdk/export/src/test/kotlin/io/devconsole/export/EventExportWriterTest.kt +++ b/sdk/export/src/test/kotlin/io/devconsole/export/EventExportWriterTest.kt @@ -1,5 +1,7 @@ package io.devconsole.export +import io.devconsole.security.RedactionEngine +import io.devconsole.security.RedactionPolicy import io.devconsole.storage.api.RedactionApplicability import io.devconsole.storage.api.StoredEvent import io.devconsole.timeline.TimelineAnnotation @@ -19,7 +21,7 @@ class EventExportWriterTest { try { val destination = File(directory, "export.zip") val result = - EventExportWriter().write( + EventExportWriter(RedactionEngine(RedactionPolicy.recommended())).write( ExportRequest( sessionId = "session-1", destination = destination, @@ -43,7 +45,7 @@ class EventExportWriterTest { val directory = Files.createTempDirectory("devconsole-export-limit-test").toFile() try { val result = - EventExportWriter().write( + EventExportWriter(RedactionEngine(RedactionPolicy.recommended())).write( ExportRequest( sessionId = "session-1", destination = File(directory, "export.zip"), @@ -68,7 +70,7 @@ class EventExportWriterTest { destination = File(directory, "export.zip"), events = listOf(event(summary = "request")), ) - val writer = EventExportWriter() + val writer = EventExportWriter(RedactionEngine(RedactionPolicy.recommended())) val estimated = writer.estimateBytes(request) assertTrue(directory.listFiles().isNullOrEmpty()) @@ -97,7 +99,7 @@ class EventExportWriterTest { val withAttachment = withoutAttachment.withAttachments(mapOf("attachment-1" to ByteArray(4_096))) val metadataOnly = withAttachment.withMetadataOnly() - val writer = EventExportWriter() + val writer = EventExportWriter(RedactionEngine(RedactionPolicy.recommended())) val baseline = writer.estimateBytes(withoutAttachment) val withBytes = writer.estimateBytes(withAttachment) @@ -127,7 +129,11 @@ class EventExportWriterTest { ), ) - assertTrue(EventExportWriter().write(request) is ExportResult.Success) + assertTrue( + EventExportWriter( + RedactionEngine(RedactionPolicy.recommended()), + ).write(request) is ExportResult.Success, + ) ZipFile(destination).use { zip -> val timeline = zip.getInputStream(zip.getEntry("timeline.jsonl")).bufferedReader().readText() assertTrue(timeline.contains("\"bookmarked\":true")) @@ -152,11 +158,11 @@ class EventExportWriterTest { event(id = "event-3", wallTimeMs = 300, summary = "third"), ) - EventExportWriter().write( + EventExportWriter(RedactionEngine(RedactionPolicy.recommended())).write( ExportRequest("session-1", events, selectedDestination) .withScope(ExportScope.EventIds(setOf("event-2"))), ) - EventExportWriter().write( + EventExportWriter(RedactionEngine(RedactionPolicy.recommended())).write( ExportRequest("session-1", events, rangedDestination) .withScope(ExportScope.TimeRange(fromEpochMs = 100, toEpochMs = 200)), ) @@ -175,7 +181,7 @@ class EventExportWriterTest { val destination = File(directory, "export.zip") assertTrue( - EventExportWriter().write( + EventExportWriter(RedactionEngine(RedactionPolicy.recommended())).write( ExportRequest( "session-1", listOf(event(summary = "integrity")), @@ -220,13 +226,13 @@ class EventExportWriterTest { attachmentId = "capture/body", ) val metadataResult = - EventExportWriter().write( + EventExportWriter(RedactionEngine(RedactionPolicy.recommended())).write( ExportRequest("session-1", listOf(attached), metadataDestination) .withMetadataOnly() .withAttachments(mapOf("capture/body" to "binary-secret".encodeToByteArray())), ) val rejected = - EventExportWriter().write( + EventExportWriter(RedactionEngine(RedactionPolicy.recommended())).write( ExportRequest("session-1", listOf(attached), destination, maxBytes = 1), ) @@ -255,7 +261,11 @@ class EventExportWriterTest { val destination = File(directory, "evidence.zip") val request = evidenceRequest(destination) - assertTrue(EventExportWriter().write(request) is ExportResult.Success) + assertTrue( + EventExportWriter( + RedactionEngine(RedactionPolicy.recommended()), + ).write(request) is ExportResult.Success, + ) ZipFile(destination).use { zip -> assertTrue(zip.readText("report.md").contains("QA Evidence Report")) assertTrue(zip.readText("report.json").contains("\"items\"")) @@ -275,7 +285,11 @@ class EventExportWriterTest { val directory = Files.createTempDirectory("devconsole-evidence-manifest-test").toFile() try { val destination = File(directory, "evidence.zip") - assertTrue(EventExportWriter().write(evidenceRequest(destination)) is ExportResult.Success) + assertTrue( + EventExportWriter( + RedactionEngine(RedactionPolicy.recommended()), + ).write(evidenceRequest(destination)) is ExportResult.Success, + ) ZipFile(destination).use { zip -> val manifest = zip.readText("manifest.json") @@ -320,7 +334,11 @@ class EventExportWriterTest { ), ) - assertTrue(EventExportWriter().write(request) is ExportResult.Success) + assertTrue( + EventExportWriter( + RedactionEngine(RedactionPolicy.recommended()), + ).write(request) is ExportResult.Success, + ) ZipFile(destination).use { zip -> val reportMd = zip.readText("report.md") assertFalse(reportMd.contains("report-secret")) @@ -343,8 +361,14 @@ class EventExportWriterTest { ).withScope(ExportScope.Evidence) val oversized = evidenceRequest(File(directory, "oversized.zip"), maxBytes = 1) - assertEquals(ExportResult.Unavailable, EventExportWriter().write(missingBundle)) - assertEquals(ExportResult.ExceedsSizeLimit, EventExportWriter().write(oversized)) + assertEquals( + ExportResult.Unavailable, + EventExportWriter(RedactionEngine(RedactionPolicy.recommended())).write(missingBundle), + ) + assertEquals( + ExportResult.ExceedsSizeLimit, + EventExportWriter(RedactionEngine(RedactionPolicy.recommended())).write(oversized), + ) assertTrue(directory.listFiles().orEmpty().none { it.name.endsWith(".tmp") }) } finally { directory.deleteRecursively() @@ -371,7 +395,7 @@ class EventExportWriterTest { evidenceRequest(File(directory, "oversized.zip"), maxBytes = 1_000_000L) .withEvidenceBundle(baseEvidenceBundle().copy(attachments = listOf(hugeAttachment))) - val result = EventExportWriter().write(request) + val result = EventExportWriter(RedactionEngine(RedactionPolicy.recommended())).write(request) assertEquals(ExportResult.ExceedsSizeLimit, result) assertFalse("the size gate must reject using metadata alone, never opening the attachment", opened) @@ -385,13 +409,24 @@ class EventExportWriterTest { fun `evidence estimateBytes matches what write() gates on, without touching disk`() { val directory = Files.createTempDirectory("devconsole-evidence-estimate-test").toFile() try { - val estimated = EventExportWriter().estimateBytes(evidenceRequest(File(directory, "unused.zip"))) + val estimated = + EventExportWriter( + RedactionEngine(RedactionPolicy.recommended()), + ).estimateBytes(evidenceRequest(File(directory, "unused.zip"))) assertTrue(directory.listFiles().isNullOrEmpty()) val refused = - EventExportWriter().write(evidenceRequest(File(directory, "refused.zip"), maxBytes = estimated - 1)) + EventExportWriter(RedactionEngine(RedactionPolicy.recommended())).write( + evidenceRequest( + File(directory, "refused.zip"), + maxBytes = + estimated - 1, + ), + ) val accepted = - EventExportWriter().write(evidenceRequest(File(directory, "accepted.zip"), maxBytes = estimated)) + EventExportWriter( + RedactionEngine(RedactionPolicy.recommended()), + ).write(evidenceRequest(File(directory, "accepted.zip"), maxBytes = estimated)) assertTrue(estimated > 0) assertEquals(ExportResult.ExceedsSizeLimit, refused) diff --git a/sdk/full/src/main/kotlin/io/devconsole/AndroidDatabaseInspector.kt b/sdk/full/src/main/kotlin/io/devconsole/AndroidDatabaseInspector.kt index aafd589..315fe88 100644 --- a/sdk/full/src/main/kotlin/io/devconsole/AndroidDatabaseInspector.kt +++ b/sdk/full/src/main/kotlin/io/devconsole/AndroidDatabaseInspector.kt @@ -144,7 +144,7 @@ internal class AndroidDatabaseInspector( android.database.Cursor.FIELD_TYPE_BLOB -> "[blob ${getBlob(index).size} bytes]" else -> getString(index).orEmpty() } - if (column.looksSensitiveColumn()) return redaction.replacement() + if (redaction.isEnabled() && column.looksSensitiveColumn()) return redaction.replacement() return redaction.redactFields(mapOf(column to raw)).getValue(column) } diff --git a/sdk/full/src/main/kotlin/io/devconsole/FullInspectorDataSource.kt b/sdk/full/src/main/kotlin/io/devconsole/FullInspectorDataSource.kt index 49fff8c..65d775d 100644 --- a/sdk/full/src/main/kotlin/io/devconsole/FullInspectorDataSource.kt +++ b/sdk/full/src/main/kotlin/io/devconsole/FullInspectorDataSource.kt @@ -376,6 +376,7 @@ internal class FullInspectorDataSource( retention = retentionSupplier(), keepAlivePromptNeeded = keepAlivePromptSupplier(), captureCategories = categories, + redactionEnabled = (config?.redactionPolicy ?: RedactionPolicy.default()).hasRules(), ) } @@ -907,10 +908,10 @@ private fun InspectorTrafficQuery.toEngineQuery(): NetworkTransactionQuery { return NetworkTransactionQuery(limit = SNAPSHOT_TRANSACTION_LIMIT, methods = methods).withFilters(filters) } -/** Exact-host allow-list match, mirroring the server's Composer host gate. */ +/** Empty permits any host; otherwise use an exact-host allow-list match. */ private fun Set.permitsHostOf(url: String): Boolean { val host = url.hostOrEmpty().lowercase() - return host.isNotEmpty() && any { it.lowercase() == host } + return host.isNotEmpty() && (isEmpty() || any { it.lowercase() == host }) } private fun String.hostOrEmpty(): String = runCatching { URI(this).host.orEmpty() }.getOrDefault("") diff --git a/sdk/full/src/main/kotlin/io/devconsole/InspectorExporter.kt b/sdk/full/src/main/kotlin/io/devconsole/InspectorExporter.kt index b76e8c8..375a159 100644 --- a/sdk/full/src/main/kotlin/io/devconsole/InspectorExporter.kt +++ b/sdk/full/src/main/kotlin/io/devconsole/InspectorExporter.kt @@ -15,6 +15,7 @@ import io.devconsole.network.NetworkTransaction import io.devconsole.network.NetworkTransactionStore import io.devconsole.network.resolveExportSelection import io.devconsole.security.RedactionEngine +import io.devconsole.security.RedactionPolicy import io.devconsole.server.api.ServerMetadata import io.devconsole.storage.api.StoredEvent import io.devconsole.timeline.InMemoryTimelineAnnotations @@ -135,7 +136,7 @@ internal class AndroidInspectorExporter( val timelineResult = runBlocking { val annotations = sessionExportSources.annotationsSupplier() - EventExportWriter().writeAsync( + EventExportWriter(exportRedaction ?: RedactionEngine(RedactionPolicy.default())).writeAsync( ExportRequest(sessionId = sessionId, events = events, destination = timelinePart) .withAnnotations(events.associate { it.id to annotations.get(it.id) }) .withAttachments(collectAttachments(events)), diff --git a/sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt b/sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt index 6ef35ce..eca9000 100644 --- a/sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt +++ b/sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt @@ -939,6 +939,7 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { filesEditable = config.editingCapabilities.files, ) serverEngine.withBrowserSecurity(config.browserSecurity) + serverEngine.withNetworkProtection(config.networkProtection) } } @@ -1013,6 +1014,7 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { sessionsProvider = { sessionStore?.sessions().orEmpty() }, screenshotCapture = ::captureScreenshot, ).withRetainedCaptures(RetainedCaptureQuery({ eventStore }, runtime::currentSessionId)) + .withNetworkProtection(config.networkProtection) .withBrowserSecurity(config.browserSecurity) .withAttachmentReader { attachmentId -> roomAttachmentStore?.read(attachmentId) } .withAttachmentMetadataReader { attachmentId -> roomAttachmentStore?.metadata(attachmentId) } diff --git a/sdk/full/src/main/res/drawable-hdpi/devconsole_logo.webp b/sdk/full/src/main/res/drawable-hdpi/devconsole_logo.webp index 2190137..3d78269 100644 Binary files a/sdk/full/src/main/res/drawable-hdpi/devconsole_logo.webp and b/sdk/full/src/main/res/drawable-hdpi/devconsole_logo.webp differ diff --git a/sdk/full/src/main/res/drawable-mdpi/devconsole_logo.webp b/sdk/full/src/main/res/drawable-mdpi/devconsole_logo.webp index fd1ad5b..074346b 100644 Binary files a/sdk/full/src/main/res/drawable-mdpi/devconsole_logo.webp and b/sdk/full/src/main/res/drawable-mdpi/devconsole_logo.webp differ diff --git a/sdk/full/src/main/res/drawable-xhdpi/devconsole_logo.webp b/sdk/full/src/main/res/drawable-xhdpi/devconsole_logo.webp index 220314d..179fdef 100644 Binary files a/sdk/full/src/main/res/drawable-xhdpi/devconsole_logo.webp and b/sdk/full/src/main/res/drawable-xhdpi/devconsole_logo.webp differ diff --git a/sdk/full/src/main/res/drawable-xxhdpi/devconsole_logo.webp b/sdk/full/src/main/res/drawable-xxhdpi/devconsole_logo.webp index 11b58ba..a8af6ff 100644 Binary files a/sdk/full/src/main/res/drawable-xxhdpi/devconsole_logo.webp and b/sdk/full/src/main/res/drawable-xxhdpi/devconsole_logo.webp differ diff --git a/sdk/full/src/main/res/drawable-xxxhdpi/devconsole_logo.webp b/sdk/full/src/main/res/drawable-xxxhdpi/devconsole_logo.webp index 44e2483..1128bcc 100644 Binary files a/sdk/full/src/main/res/drawable-xxxhdpi/devconsole_logo.webp and b/sdk/full/src/main/res/drawable-xxxhdpi/devconsole_logo.webp differ diff --git a/sdk/full/src/main/res/drawable/devconsole_notification.xml b/sdk/full/src/main/res/drawable/devconsole_notification.xml index 19a383d..94bd6c4 100644 --- a/sdk/full/src/main/res/drawable/devconsole_notification.xml +++ b/sdk/full/src/main/res/drawable/devconsole_notification.xml @@ -1,31 +1,19 @@ - + - - - + android:viewportWidth="900" + android:viewportHeight="900"> + + + + diff --git a/sdk/full/src/test/kotlin/io/devconsole/AndroidDatabaseInspectorTest.kt b/sdk/full/src/test/kotlin/io/devconsole/AndroidDatabaseInspectorTest.kt index ec0cebb..0f37f9a 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/AndroidDatabaseInspectorTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/AndroidDatabaseInspectorTest.kt @@ -25,7 +25,7 @@ import org.robolectric.annotation.Config class AndroidDatabaseInspectorTest { private val application: Application = ApplicationProvider.getApplicationContext() private val inspector = - AndroidDatabaseInspector(application, RedactionEngine(RedactionPolicy.default())) + AndroidDatabaseInspector(application, RedactionEngine(RedactionPolicy.recommended())) @Before fun createDemoDatabase() { @@ -45,6 +45,14 @@ class AndroidDatabaseInspectorTest { assertFalse(names.any { it.endsWith("-shm") }) } + @Test + fun `default policy preserves columns covered by built in personal data heuristics`() { + val unmasked = AndroidDatabaseInspector(application, RedactionEngine(RedactionPolicy.default())) + val result = requireNotNull(unmasked.query("demo.db", "users")) + + assertEquals("a@example.test", result.rows.single()[1]) + } + @Test fun `tables lists user tables with row counts and excludes sqlite internal tables`() { val listing = requireNotNull(inspector.tables("demo.db")) diff --git a/sdk/full/src/test/kotlin/io/devconsole/AndroidFileInspectorTest.kt b/sdk/full/src/test/kotlin/io/devconsole/AndroidFileInspectorTest.kt index 0348515..5ae65a8 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/AndroidFileInspectorTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/AndroidFileInspectorTest.kt @@ -25,7 +25,7 @@ import java.io.File class AndroidFileInspectorTest { private val application: Application = ApplicationProvider.getApplicationContext() private val inspector = - AndroidFileInspector(application, RedactionEngine(RedactionPolicy.default())) + AndroidFileInspector(application, RedactionEngine(RedactionPolicy.recommended())) @Test fun `roots expose only app-owned storage`() { diff --git a/sdk/full/src/test/kotlin/io/devconsole/AndroidInspectorExporterTest.kt b/sdk/full/src/test/kotlin/io/devconsole/AndroidInspectorExporterTest.kt index 5e17cc5..a31f16e 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/AndroidInspectorExporterTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/AndroidInspectorExporterTest.kt @@ -43,7 +43,7 @@ private const val PRUNE_TEST_BASE_TIME_MS = 1_700_000_000_000L @Config(sdk = [34]) class AndroidInspectorExporterTest { private val application: Application = ApplicationProvider.getApplicationContext() - private val captureFactory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())) + private val captureFactory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())) private fun networkStore(): InMemoryNetworkTransactionStore = InMemoryNetworkTransactionStore(NetworkCursorCodec("network-cursor-key".encodeToByteArray())) @@ -201,7 +201,7 @@ class AndroidInspectorExporterTest { metadataSupplier = { ServerMetadata(appDisplayName = "Sample App", appPackageName = "com.example.sample") }, - ) + ).apply { exportRedaction = RedactionEngine(RedactionPolicy.recommended()) } val outcome = exporter.exportSessionZip() diff --git a/sdk/full/src/test/kotlin/io/devconsole/AndroidPreferencesInspectorTest.kt b/sdk/full/src/test/kotlin/io/devconsole/AndroidPreferencesInspectorTest.kt index 6c53938..77df027 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/AndroidPreferencesInspectorTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/AndroidPreferencesInspectorTest.kt @@ -23,7 +23,7 @@ import org.robolectric.annotation.Config class AndroidPreferencesInspectorTest { private val application: Application = ApplicationProvider.getApplicationContext() private val inspector = - AndroidPreferencesInspector(application, RedactionEngine(RedactionPolicy.default())) + AndroidPreferencesInspector(application, RedactionEngine(RedactionPolicy.recommended())) @Test fun `files lists typed entries from the app shared preferences`() { @@ -63,6 +63,25 @@ class AndroidPreferencesInspectorTest { assertFalse(countEntry.redacted) } + @Test + fun `default policy preserves token looking preference values`() { + application + .getSharedPreferences("unmasked_prefs", Context.MODE_PRIVATE) + .edit() + .putString("access_token", "raw-token") + .commit() + val unmasked = AndroidPreferencesInspector(application, RedactionEngine(RedactionPolicy.default())) + val entry = + unmasked + .files() + .first { it.name == "unmasked_prefs" } + .entries + .single() + + assertEquals("raw-token", entry.value) + assertFalse(entry.redacted) + } + @Test fun `put writes a typed value that is then reflected in the store`() { application diff --git a/sdk/full/src/test/kotlin/io/devconsole/CaptureCategoryGatingTest.kt b/sdk/full/src/test/kotlin/io/devconsole/CaptureCategoryGatingTest.kt index 94263ef..7a0dca7 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/CaptureCategoryGatingTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/CaptureCategoryGatingTest.kt @@ -53,7 +53,7 @@ class CaptureCategoryGatingTest { val store = InMemoryNetworkTransactionStore(NetworkCursorCodec("network-cursor-key-1234567890".encodeToByteArray())) val capture = - NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())).capture( + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())).capture( NetworkRequestInput(method = "GET", url = "https://api.example.test/orders"), NetworkResponseInput(statusCode = 200), ) diff --git a/sdk/full/src/test/kotlin/io/devconsole/CaptureTimelineTest.kt b/sdk/full/src/test/kotlin/io/devconsole/CaptureTimelineTest.kt index 3d55753..e8d7faa 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/CaptureTimelineTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/CaptureTimelineTest.kt @@ -48,7 +48,7 @@ class CaptureTimelineTest { bridge, ) val capture = - NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())) + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())) .capture( NetworkRequestInput( "GET", @@ -96,7 +96,7 @@ class CaptureTimelineTest { @Test fun `socket recorder mirrors each lifecycle and frame once`() { val store = TeeingSocketStore(InMemorySocketStore(), bridge) - val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.default()), store, clock = { 10L }) + val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.recommended()), store, clock = { 10L }) recorder.onCreated("c1", "wss://echo.test/raw") recorder.onOpen("c1", "wss://echo.test/raw") @@ -129,7 +129,7 @@ class CaptureTimelineTest { ) val push = TeeingPushStore(InMemoryPushStore(), bridge) val capture = - NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())) + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())) .capture(NetworkRequestInput("GET", "https://api.test/a"), null) network.record(NetworkTransaction("tx-1", 0, 1, capture)) diff --git a/sdk/full/src/test/kotlin/io/devconsole/CrashCaptureTest.kt b/sdk/full/src/test/kotlin/io/devconsole/CrashCaptureTest.kt index 2408180..783956a 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/CrashCaptureTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/CrashCaptureTest.kt @@ -56,7 +56,7 @@ class CrashCaptureTest { private fun capture() = CrashCapture( sessionId = "session", - redaction = RedactionEngine(RedactionPolicy.default()), + redaction = RedactionEngine(RedactionPolicy.recommended()), appender = { appender }, store = { store }, ) @@ -122,7 +122,7 @@ class CrashCaptureTest { val capture = CrashCapture( sessionId = { "session" }, - redaction = RedactionEngine(RedactionPolicy.default()), + redaction = RedactionEngine(RedactionPolicy.recommended()), appender = { appender }, store = { store }, sessionStore = { null }, @@ -149,7 +149,7 @@ class CrashCaptureTest { val capture = CrashCapture( sessionId = { "session" }, - redaction = RedactionEngine(RedactionPolicy.default()), + redaction = RedactionEngine(RedactionPolicy.recommended()), appender = { appender }, store = { store }, sessionStore = { null }, @@ -166,7 +166,7 @@ class CrashCaptureTest { val capture = CrashCapture( sessionId = { "session" }, - redaction = RedactionEngine(RedactionPolicy.default()), + redaction = RedactionEngine(RedactionPolicy.recommended()), appender = { appender }, store = { store }, sessionStore = { null }, @@ -189,7 +189,7 @@ class CrashCaptureTest { val capture = CrashCapture( sessionId = { "session" }, - redaction = RedactionEngine(RedactionPolicy.default()), + redaction = RedactionEngine(RedactionPolicy.recommended()), appender = { appender }, store = { store }, sessionStore = { null }, @@ -217,7 +217,7 @@ class CrashCaptureTest { val capture = CrashCapture( sessionId = { "session" }, - redaction = RedactionEngine(RedactionPolicy.default()), + redaction = RedactionEngine(RedactionPolicy.recommended()), appender = { appender }, store = { store }, sessionStore = { null }, @@ -244,7 +244,7 @@ class CrashCaptureTest { val capture = CrashCapture( sessionId = { "session" }, - redaction = RedactionEngine(RedactionPolicy.default()), + redaction = RedactionEngine(RedactionPolicy.recommended()), appender = { appender }, store = { store }, sessionStore = { null }, @@ -263,7 +263,7 @@ class CrashCaptureTest { val capture = CrashCapture( sessionId = { "session" }, - redaction = RedactionEngine(RedactionPolicy.default()), + redaction = RedactionEngine(RedactionPolicy.recommended()), appender = { appender }, store = { store }, sessionStore = { null }, @@ -304,7 +304,7 @@ class CrashCaptureTest { val capture = CrashCapture( sessionId = { "session" }, - redaction = RedactionEngine(RedactionPolicy.default()), + redaction = RedactionEngine(RedactionPolicy.recommended()), appender = { appender }, store = { neverReturningStore }, sessionStore = { null }, @@ -387,7 +387,7 @@ class CrashCaptureTest { val capture = CrashCapture( sessionId = { "session" }, - redaction = RedactionEngine(RedactionPolicy.default()), + redaction = RedactionEngine(RedactionPolicy.recommended()), appender = { appender }, store = { neverReturningStore }, sessionStore = { neverReturningSessions }, @@ -428,7 +428,7 @@ class CrashCaptureTest { val capture = CrashCapture( sessionId = { "session" }, - redaction = RedactionEngine(RedactionPolicy.default()), + redaction = RedactionEngine(RedactionPolicy.recommended()), appender = { throwingAppender }, store = { store }, sessionStore = { null }, @@ -484,7 +484,7 @@ class CrashCaptureTest { val capture = CrashCapture( sessionId = "session", - redaction = RedactionEngine(RedactionPolicy.default()), + redaction = RedactionEngine(RedactionPolicy.recommended()), appender = { appender }, store = { store }, ) diff --git a/sdk/full/src/test/kotlin/io/devconsole/FullFacadeTest.kt b/sdk/full/src/test/kotlin/io/devconsole/FullFacadeTest.kt index f0b48bd..eb4566a 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/FullFacadeTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/FullFacadeTest.kt @@ -232,7 +232,13 @@ class FullFacadeTest { InitResult.Initialized, provider.initialize( ApplicationProvider.getApplicationContext(), - DevConsoleConfig(stateProviders = listOf(provided), featureFlags = listOf(flag)), + DevConsoleConfig( + stateProviders = listOf(provided), + featureFlags = listOf(flag), + redactionPolicy = + io.devconsole.security.RedactionPolicy + .recommended(), + ), ), ) diff --git a/sdk/full/src/test/kotlin/io/devconsole/FullInspectorDataSourceTest.kt b/sdk/full/src/test/kotlin/io/devconsole/FullInspectorDataSourceTest.kt index e4ecbc1..f78c3a4 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/FullInspectorDataSourceTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/FullInspectorDataSourceTest.kt @@ -80,7 +80,7 @@ import org.junit.Test @Suppress("LargeClass", "LongParameterList") // Exhaustive adapter coverage; configWith mirrors the capability flags. class FullInspectorDataSourceTest { - private val captureFactory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())) + private val captureFactory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())) private fun networkStore(): InMemoryNetworkTransactionStore = InMemoryNetworkTransactionStore(NetworkCursorCodec("network-cursor-key".encodeToByteArray())) @@ -140,6 +140,7 @@ class FullInspectorDataSourceTest { .preferences(preferences) .files(files) .database(database) + .captureRules(false) .build(), ) diff --git a/sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderScreenshotTest.kt b/sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderScreenshotTest.kt index cca2f4a..0dec6fa 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderScreenshotTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderScreenshotTest.kt @@ -37,10 +37,13 @@ import java.net.URLEncoder @Config(sdk = [34]) class PlatformFacadeProviderScreenshotTest { @Test - fun `screenshot capture is disabled by default and captures nothing`() = + fun `screenshot capture can be disabled explicitly and captures nothing`() = runTest { val provider = PlatformFacadeProvider() - provider.initialize(ApplicationProvider.getApplicationContext(), DevConsoleConfig.default()) + provider.initialize( + ApplicationProvider.getApplicationContext(), + DevConsoleConfig.default().withScreenshotPolicy(ScreenshotPolicy(enabled = false)), + ) val result = provider.captureScreenshot() diff --git a/sdk/full/src/test/kotlin/io/devconsole/RemoteConfigInspectorTest.kt b/sdk/full/src/test/kotlin/io/devconsole/RemoteConfigInspectorTest.kt index 21c9179..9f23c80 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/RemoteConfigInspectorTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/RemoteConfigInspectorTest.kt @@ -61,7 +61,21 @@ class RemoteConfigInspectorTest { remoteConfigRegistry = registry, ) - private fun enabledConfig() = DevConsoleConfig().withCaptureCategories(CaptureCategory.all()) + private fun enabledConfig() = + DevConsoleConfig(redactionPolicy = RedactionPolicy.recommended()).withCaptureCategories(CaptureCategory.all()) + + @Test + fun `default config preserves token looking remote config values`() { + val snapshot = source(DevConsoleConfig(), registryWith(entry("api_key", "raw-key"))).snapshot() + val entry = + snapshot.remoteConfig + .single() + .entries + .single() + + assertEquals("raw-key", entry.value) + assertFalse(entry.redacted) + } @Test fun `exposes remote config entries with their source`() { @@ -106,7 +120,7 @@ class RemoteConfigInspectorTest { .single() .entries .single() - assertEquals(RedactionPolicy.default().replacement, redacted.value) + assertEquals(RedactionPolicy.recommended().replacement, redacted.value) assertTrue(redacted.redacted) } @@ -177,7 +191,7 @@ class RemoteConfigInspectorTest { listOf(entry("access_token", "raw"), entry("checkout_v2", "true")), ) - assertEquals(RedactionPolicy.default().replacement, entries.first().value) + assertEquals(RedactionPolicy.recommended().replacement, entries.first().value) assertTrue(entries.first().redacted) assertEquals("true", entries.last().value) assertFalse(entries.last().redacted) @@ -203,7 +217,7 @@ class RemoteConfigInspectorTest { ) assertTrue(entries.all { it.redacted }) - assertTrue(entries.all { it.value == RedactionPolicy.default().replacement }) + assertTrue(entries.all { it.value == RedactionPolicy.recommended().replacement }) } @Test @@ -229,5 +243,5 @@ class RemoteConfigInspectorTest { } private fun redactingBoundary() = - RedactingRemoteConfig(RedactionEngine(RedactionPolicy.default()), RedactionPolicy.default()) + RedactingRemoteConfig(RedactionEngine(RedactionPolicy.recommended()), RedactionPolicy.recommended()) } diff --git a/sdk/logs/src/test/kotlin/io/devconsole/logs/LogRecorderTest.kt b/sdk/logs/src/test/kotlin/io/devconsole/logs/LogRecorderTest.kt index 1c9bc8d..ff71618 100644 --- a/sdk/logs/src/test/kotlin/io/devconsole/logs/LogRecorderTest.kt +++ b/sdk/logs/src/test/kotlin/io/devconsole/logs/LogRecorderTest.kt @@ -8,7 +8,7 @@ import org.junit.Assert.assertTrue import org.junit.Test class LogRecorderTest { - private val redaction = RedactionEngine(RedactionPolicy.default()) + private val redaction = RedactionEngine(RedactionPolicy.recommended()) private val emitted = mutableListOf() private val sink = LogSink(emitted::add) diff --git a/sdk/network-ktor/src/test/kotlin/io/devconsole/network/ktor/DevConsoleKtorClientPluginTest.kt b/sdk/network-ktor/src/test/kotlin/io/devconsole/network/ktor/DevConsoleKtorClientPluginTest.kt index 69771c1..88e98ac 100644 --- a/sdk/network-ktor/src/test/kotlin/io/devconsole/network/ktor/DevConsoleKtorClientPluginTest.kt +++ b/sdk/network-ktor/src/test/kotlin/io/devconsole/network/ktor/DevConsoleKtorClientPluginTest.kt @@ -45,7 +45,7 @@ class DevConsoleKtorClientPluginTest { val store = InMemoryNetworkTransactionStore(NetworkCursorCodec("1234567890123456".encodeToByteArray())) val recorder = NetworkTransactionRecorder( - factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())), + factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())), store = store, ) @@ -89,7 +89,7 @@ class DevConsoleKtorClientPluginTest { val store = InMemoryNetworkTransactionStore(NetworkCursorCodec("1234567890123456".encodeToByteArray())) val recorder = NetworkTransactionRecorder( - factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())), + factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())), store = store, ) val mockEngine = MockEngine { _ -> respond(content = "ok", status = HttpStatusCode.OK) } @@ -117,7 +117,7 @@ class DevConsoleKtorClientPluginTest { val store = InMemoryNetworkTransactionStore(NetworkCursorCodec("1234567890123456".encodeToByteArray())) val recorder = NetworkTransactionRecorder( - factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())), + factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())), store = store, ) val mockEngine = MockEngine { _ -> respond(content = "ok", status = HttpStatusCode.OK) } @@ -141,7 +141,7 @@ class DevConsoleKtorClientPluginTest { val store = InMemoryNetworkTransactionStore(NetworkCursorCodec("1234567890123456".encodeToByteArray())) val recorder = NetworkTransactionRecorder( - factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())), + factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())), store = store, ) val mockEngine = MockEngine { _ -> respond(content = "response body", status = HttpStatusCode.OK) } @@ -182,7 +182,7 @@ class DevConsoleKtorClientPluginTest { val store = InMemoryNetworkTransactionStore(NetworkCursorCodec("1234567890123456".encodeToByteArray())) val recorder = NetworkTransactionRecorder( - factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())), + factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())), store = store, ) val payload = "{\"status\":\"ok\",\"items\":[1,2,3]}" @@ -219,7 +219,7 @@ class DevConsoleKtorClientPluginTest { val store = InMemoryNetworkTransactionStore(NetworkCursorCodec("1234567890123456".encodeToByteArray())) val recorder = NetworkTransactionRecorder( - factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())), + factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())), store = store, ) val payload = "{\"status\":\"ok\"}" @@ -255,7 +255,7 @@ class DevConsoleKtorClientPluginTest { val store = InMemoryNetworkTransactionStore(NetworkCursorCodec("1234567890123456".encodeToByteArray())) val recorder = NetworkTransactionRecorder( - factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())), + factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())), store = store, ) val originBody = ByteChannel() @@ -299,7 +299,7 @@ class DevConsoleKtorClientPluginTest { val store = InMemoryNetworkTransactionStore(NetworkCursorCodec("1234567890123456".encodeToByteArray())) val recorder = NetworkTransactionRecorder( - factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())), + factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())), store = store, ) val mockEngine = @@ -333,7 +333,7 @@ class DevConsoleKtorClientPluginTest { val store = InMemoryNetworkTransactionStore(NetworkCursorCodec("1234567890123456".encodeToByteArray())) val recorder = NetworkTransactionRecorder( - factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())), + factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())), store = store, ) val bigBody = "a".repeat(300 * 1024) @@ -369,7 +369,7 @@ class DevConsoleKtorClientPluginTest { val store = InMemoryNetworkTransactionStore(NetworkCursorCodec("1234567890123456".encodeToByteArray())) val recorder = NetworkTransactionRecorder( - factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())), + factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())), store = store, ) val bigBody = "b".repeat(300 * 1024) @@ -403,7 +403,7 @@ class DevConsoleKtorClientPluginTest { val store = InMemoryNetworkTransactionStore(NetworkCursorCodec("1234567890123456".encodeToByteArray())) val recorder = NetworkTransactionRecorder( - factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())), + factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())), store = store, ) val binaryBody = ByteArray(64) { it.toByte() } diff --git a/sdk/network-okhttp-noop/src/test/kotlin/io/devconsole/network/okhttp/DevConsoleOkHttpInterceptorNoopTest.kt b/sdk/network-okhttp-noop/src/test/kotlin/io/devconsole/network/okhttp/DevConsoleOkHttpInterceptorNoopTest.kt index 46037f9..c6dd980 100644 --- a/sdk/network-okhttp-noop/src/test/kotlin/io/devconsole/network/okhttp/DevConsoleOkHttpInterceptorNoopTest.kt +++ b/sdk/network-okhttp-noop/src/test/kotlin/io/devconsole/network/okhttp/DevConsoleOkHttpInterceptorNoopTest.kt @@ -30,7 +30,7 @@ class DevConsoleOkHttpInterceptorNoopTest { val store = InMemoryNetworkTransactionStore(NetworkCursorCodec(ByteArray(16) { it.toByte() })) val recorder = NetworkTransactionRecorder( - factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())), + factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())), store = store, executor = Executor(Runnable::run), ) diff --git a/sdk/network-okhttp/src/test/kotlin/io/devconsole/network/okhttp/DevConsoleOkHttpEventListenerFactoryTest.kt b/sdk/network-okhttp/src/test/kotlin/io/devconsole/network/okhttp/DevConsoleOkHttpEventListenerFactoryTest.kt index 2031f04..3a4ebb3 100644 --- a/sdk/network-okhttp/src/test/kotlin/io/devconsole/network/okhttp/DevConsoleOkHttpEventListenerFactoryTest.kt +++ b/sdk/network-okhttp/src/test/kotlin/io/devconsole/network/okhttp/DevConsoleOkHttpEventListenerFactoryTest.kt @@ -215,7 +215,7 @@ class DevConsoleOkHttpEventListenerFactoryTest { .addInterceptor( DevConsoleOkHttpInterceptor( NetworkTransactionRecorder( - NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())), + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())), transactions, ), listenerFactory, diff --git a/sdk/network-okhttp/src/test/kotlin/io/devconsole/network/okhttp/DevConsoleOkHttpInstallerTest.kt b/sdk/network-okhttp/src/test/kotlin/io/devconsole/network/okhttp/DevConsoleOkHttpInstallerTest.kt index 2618342..da0bac2 100644 --- a/sdk/network-okhttp/src/test/kotlin/io/devconsole/network/okhttp/DevConsoleOkHttpInstallerTest.kt +++ b/sdk/network-okhttp/src/test/kotlin/io/devconsole/network/okhttp/DevConsoleOkHttpInstallerTest.kt @@ -42,7 +42,7 @@ class DevConsoleOkHttpInstallerTest { InMemoryNetworkTransactionStore(NetworkCursorCodec("installer-test-key-1".encodeToByteArray())) val recorder = NetworkTransactionRecorder( - NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())), + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())), transactions, ) val client = @@ -79,7 +79,7 @@ class DevConsoleOkHttpInstallerTest { InMemoryNetworkTransactionStore(NetworkCursorCodec("installer-test-key-2".encodeToByteArray())) val recorder = NetworkTransactionRecorder( - NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())), + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())), transactions, ) val client = @@ -113,7 +113,7 @@ class DevConsoleOkHttpInstallerTest { InMemoryNetworkTransactionStore(NetworkCursorCodec("installer-test-key-3".encodeToByteArray())) val recorder = NetworkTransactionRecorder( - NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())), + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())), transactions, ) val hostListener = RecordingEventListenerFactory() diff --git a/sdk/network-okhttp/src/test/kotlin/io/devconsole/network/okhttp/DevConsoleOkHttpInterceptorTest.kt b/sdk/network-okhttp/src/test/kotlin/io/devconsole/network/okhttp/DevConsoleOkHttpInterceptorTest.kt index 2fe5c28..b1a2749 100644 --- a/sdk/network-okhttp/src/test/kotlin/io/devconsole/network/okhttp/DevConsoleOkHttpInterceptorTest.kt +++ b/sdk/network-okhttp/src/test/kotlin/io/devconsole/network/okhttp/DevConsoleOkHttpInterceptorTest.kt @@ -575,7 +575,7 @@ class DevConsoleOkHttpInterceptorTest { .addInterceptor( DevConsoleOkHttpInterceptor( NetworkTransactionRecorder( - NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())), + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())), transactions, ), listenerFactory, @@ -626,7 +626,7 @@ class DevConsoleOkHttpInterceptorTest { .addInterceptor( DevConsoleOkHttpInterceptor( NetworkTransactionRecorder( - NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())), + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())), transactions, ), ), diff --git a/sdk/network-okhttp/src/test/kotlin/io/devconsole/network/okhttp/DevConsoleOkHttpMockInstallTest.kt b/sdk/network-okhttp/src/test/kotlin/io/devconsole/network/okhttp/DevConsoleOkHttpMockInstallTest.kt index 4ec6dfa..9ef2f34 100644 --- a/sdk/network-okhttp/src/test/kotlin/io/devconsole/network/okhttp/DevConsoleOkHttpMockInstallTest.kt +++ b/sdk/network-okhttp/src/test/kotlin/io/devconsole/network/okhttp/DevConsoleOkHttpMockInstallTest.kt @@ -140,7 +140,7 @@ class DevConsoleOkHttpMockInstallTest { private fun recorder() = NetworkTransactionRecorder( - NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())), + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())), InMemoryNetworkTransactionStore(NetworkCursorCodec("mock-install-test-key".encodeToByteArray())), ) diff --git a/sdk/network/src/test/kotlin/io/devconsole/network/ExportSelectionTest.kt b/sdk/network/src/test/kotlin/io/devconsole/network/ExportSelectionTest.kt index 0d95e11..f155a13 100644 --- a/sdk/network/src/test/kotlin/io/devconsole/network/ExportSelectionTest.kt +++ b/sdk/network/src/test/kotlin/io/devconsole/network/ExportSelectionTest.kt @@ -24,7 +24,7 @@ class ExportSelectionTest { startedAtEpochMs = startedAt, completedAtEpochMs = startedAt + 5, capture = - NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())).capture( + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())).capture( NetworkRequestInput("GET", url), NetworkResponseInput(200), ), 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 09032e4..02d486a 100644 --- a/sdk/network/src/test/kotlin/io/devconsole/network/InMemoryNetworkTransactionStoreTest.kt +++ b/sdk/network/src/test/kotlin/io/devconsole/network/InMemoryNetworkTransactionStoreTest.kt @@ -16,7 +16,7 @@ class InMemoryNetworkTransactionStoreTest { NetworkCursorCodec("network-cursor-key".encodeToByteArray()), maxTransactions = 10, ).withByteCapacity(700) - val factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())) + val factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())) repeat(3) { index -> store.record( @@ -195,7 +195,7 @@ class InMemoryNetworkTransactionStoreTest { NetworkCursorCodec("network-cursor-key".encodeToByteArray()), maxTransactions = 10, ).withByteCapacity(700) - val factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())) + val factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())) val bulky = { id: String -> NetworkTransaction( id = id, diff --git a/sdk/network/src/test/kotlin/io/devconsole/network/NetworkCaptureFactoryTest.kt b/sdk/network/src/test/kotlin/io/devconsole/network/NetworkCaptureFactoryTest.kt index 1412e52..cafa6ba 100644 --- a/sdk/network/src/test/kotlin/io/devconsole/network/NetworkCaptureFactoryTest.kt +++ b/sdk/network/src/test/kotlin/io/devconsole/network/NetworkCaptureFactoryTest.kt @@ -8,7 +8,7 @@ import org.junit.Assert.assertTrue import org.junit.Test class NetworkCaptureFactoryTest { - private val factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())) + private val factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())) @Test fun `redacts headers query and textual body before producing capture while preserving authorization`() { @@ -143,7 +143,7 @@ class NetworkCaptureFactoryTest { fun `aggregate capture limit omits previews before exceeding the event budget`() { val constrained = NetworkCaptureFactory( - RedactionEngine(RedactionPolicy.default()), + RedactionEngine(RedactionPolicy.recommended()), NetworkCaptureLimits(totalCaptureBytes = 1_024), ) diff --git a/sdk/network/src/test/kotlin/io/devconsole/network/NetworkExportTest.kt b/sdk/network/src/test/kotlin/io/devconsole/network/NetworkExportTest.kt index fef37a5..55b0eb1 100644 --- a/sdk/network/src/test/kotlin/io/devconsole/network/NetworkExportTest.kt +++ b/sdk/network/src/test/kotlin/io/devconsole/network/NetworkExportTest.kt @@ -11,7 +11,7 @@ class NetworkExportTest { @Test fun `curl and har use only redacted capture fields`() { val capture = - NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())).capture( + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())).capture( NetworkRequestInput( method = "POST", url = "https://example.test/orders?access_token=query-secret", @@ -36,7 +36,7 @@ class NetworkExportTest { @Test fun `curl export emits the captured request body via data-raw`() { val capture = - NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())).capture( + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())).capture( NetworkRequestInput( method = "POST", url = "https://example.test/orders", @@ -54,7 +54,7 @@ class NetworkExportTest { @Test fun `curl export shell-escapes single quotes in the body`() { val capture = - NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())).capture( + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())).capture( NetworkRequestInput( method = "POST", url = "https://example.test/orders", @@ -123,7 +123,7 @@ class NetworkExportTest { // header value is already replaced with the redaction marker before NetworkExport ever sees // it. Cookie parsing must format whatever that redacted string is, not crash or fabricate. val capture = - NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())).capture( + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())).capture( NetworkRequestInput( method = "GET", url = "https://example.test/orders", @@ -142,7 +142,7 @@ class NetworkExportTest { @Test fun `har request cookies parsing skips a fully-redacted Cookie header instead of fabricating an entry`() { val capture = - NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())).capture( + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())).capture( NetworkRequestInput( method = "GET", url = "https://example.test/orders", @@ -166,7 +166,7 @@ class NetworkExportTest { "tx-1", 1_000, 1_010, - NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())).capture( + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())).capture( NetworkRequestInput("GET", "https://example.test/orders"), NetworkResponseInput(statusCode = 404, error = "socket timeout"), ), @@ -185,7 +185,7 @@ class NetworkExportTest { @Test fun `har content object includes the response body size`() { val capture = - NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())).capture( + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())).capture( NetworkRequestInput("GET", "https://example.test/orders"), NetworkResponseInput( statusCode = 200, @@ -203,12 +203,12 @@ class NetworkExportTest { @Test fun `har redirectURL is populated from the Location header on a redirect and stays empty otherwise`() { val redirect = - NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())).capture( + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())).capture( NetworkRequestInput("GET", "https://example.test/old"), NetworkResponseInput(statusCode = 302, headers = mapOf("Location" to "https://example.test/new")), ) val nonRedirect = - NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())).capture( + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())).capture( NetworkRequestInput("GET", "https://example.test/orders"), NetworkResponseInput(statusCode = 200, headers = mapOf("Location" to "https://example.test/ignored")), ) @@ -242,7 +242,7 @@ class NetworkExportTest { .contains("still-raw-secret"), ) val transaction = NetworkTransaction("tx-1", 1_000, 1_010, capture) - val stricter = RedactionEngine(RedactionPolicy.default()) + val stricter = RedactionEngine(RedactionPolicy.recommended()) val unredactedHar = NetworkExport.toHarTransactions(listOf(transaction)) val redactedHar = NetworkExport.toHarTransactions(listOf(transaction), stricter) @@ -258,7 +258,7 @@ class NetworkExportTest { @Test fun `transaction HAR uses real start duration and timing phases`() { val capture = - NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())).capture( + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())).capture( NetworkRequestInput("GET", "https://example.test/orders"), NetworkResponseInput(200, protocol = "h2") .withMetadata( @@ -282,7 +282,7 @@ class NetworkExportTest { @Test fun `postman export includes request and response bodies with no raw secret`() { val capture = - NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())).capture( + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())).capture( NetworkRequestInput( method = "POST", url = "https://example.test/orders", @@ -314,7 +314,7 @@ class NetworkExportTest { @Test fun `postman export deduplicates identical repeated requests`() { - val factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())) + val factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())) fun capture() = factory.capture( @@ -335,7 +335,7 @@ class NetworkExportTest { @Test fun `postman export keeps a 200 and a 401 for the same request separate`() { - val factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())) + val factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())) fun capture(statusCode: Int) = factory.capture( @@ -357,7 +357,7 @@ class NetworkExportTest { @Test fun `postman export still collapses the same request repeated with the same status`() { - val factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())) + val factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())) fun capture() = factory.capture( @@ -377,7 +377,7 @@ class NetworkExportTest { @Test fun `postman export keeps distinct requests separate`() { - val factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())) + val factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())) val transactions = listOf( NetworkTransaction( @@ -412,7 +412,7 @@ class NetworkExportTest { // unescaped quote in a URL, header, or body value) could defeat -- the substring might // still be present while the surrounding document is corrupted. Parsing the whole output // as JSON is the only way to catch that class of bug. - val factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())) + val factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())) val hostile = factory.capture( NetworkRequestInput( @@ -438,7 +438,7 @@ class NetworkExportTest { @Test fun `postman export of quote- and backslash-laden values is still one well-formed json document`() { - val factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())) + val factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())) val hostile = factory.capture( NetworkRequestInput( diff --git a/sdk/network/src/test/kotlin/io/devconsole/network/NetworkTransactionRecorderTest.kt b/sdk/network/src/test/kotlin/io/devconsole/network/NetworkTransactionRecorderTest.kt index 0ea6467..9d158cc 100644 --- a/sdk/network/src/test/kotlin/io/devconsole/network/NetworkTransactionRecorderTest.kt +++ b/sdk/network/src/test/kotlin/io/devconsole/network/NetworkTransactionRecorderTest.kt @@ -13,7 +13,7 @@ class NetworkTransactionRecorderTest { val store = InMemoryNetworkTransactionStore(NetworkCursorCodec("network-cursor-key".encodeToByteArray())) val recorder = NetworkTransactionRecorder( - factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())), + factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())), store = store, idProvider = { "transaction-1" }, ) @@ -38,7 +38,7 @@ class NetworkTransactionRecorderTest { val store = InMemoryNetworkTransactionStore(NetworkCursorCodec("network-cursor-key".encodeToByteArray())) val recorder = NetworkTransactionRecorder( - factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())), + factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())), store = store, enabled = false, idProvider = { "transaction-1" }, @@ -69,7 +69,7 @@ class NetworkTransactionRecorderTest { val recorder = NetworkTransactionRecorder( - factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())), + factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())), store = store, idProvider = { "transaction-blocked" }, executor = customExecutor, @@ -107,7 +107,7 @@ class NetworkTransactionRecorderTest { val recorder = NetworkTransactionRecorder( - factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())), + factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())), store = store, maxQueueSize = 2, executor = customExecutor, @@ -142,7 +142,7 @@ class NetworkTransactionRecorderTest { // force an eviction here, mirroring EventBatchWriter's dual count+byte queue budget. val recorder = NetworkTransactionRecorder( - factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())), + factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())), store = store, maxQueueSize = 100, maxQueuedBytes = 150_000L, @@ -178,7 +178,7 @@ class NetworkTransactionRecorderTest { val attachments = CopyOnWriteArrayList() val recorder = NetworkTransactionRecorder( - factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())), + factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())), store = store, idProvider = { "transaction-attachments" }, ).withAttachmentSink { payload -> diff --git a/sdk/push/src/test/kotlin/io/devconsole/push/PushEventStoreTest.kt b/sdk/push/src/test/kotlin/io/devconsole/push/PushEventStoreTest.kt index 430a258..7661edf 100644 --- a/sdk/push/src/test/kotlin/io/devconsole/push/PushEventStoreTest.kt +++ b/sdk/push/src/test/kotlin/io/devconsole/push/PushEventStoreTest.kt @@ -10,7 +10,7 @@ class PushEventStoreTest { @Test fun `records generic lifecycle payloads with redaction and explicit simulation labeling`() { val store = InMemoryPushStore(capacity = 2) - val recorder = PushRecorder(RedactionEngine(RedactionPolicy.default()), store) + val recorder = PushRecorder(RedactionEngine(RedactionPolicy.recommended()), store) val event = recorder.record( diff --git a/sdk/push/src/test/kotlin/io/devconsole/push/PushRecorderTest.kt b/sdk/push/src/test/kotlin/io/devconsole/push/PushRecorderTest.kt index 251d4ef..d435e06 100644 --- a/sdk/push/src/test/kotlin/io/devconsole/push/PushRecorderTest.kt +++ b/sdk/push/src/test/kotlin/io/devconsole/push/PushRecorderTest.kt @@ -8,7 +8,7 @@ import org.junit.Test class PushRecorderTest { @Test fun `redacts push data before recording`() { - val recorder = PushRecorder(RedactionEngine(RedactionPolicy.default())) + val recorder = PushRecorder(RedactionEngine(RedactionPolicy.recommended())) val event = recorder.record(PushInput("fcm", mapOf("access_token" to "raw"))) assertEquals("", event.data.getValue("access_token")) } @@ -16,7 +16,7 @@ class PushRecorderTest { @Test fun `disabled recorder never redacts or stores an event`() { val store = InMemoryPushStore() - val recorder = PushRecorder(RedactionEngine(RedactionPolicy.default()), store, enabled = false) + val recorder = PushRecorder(RedactionEngine(RedactionPolicy.recommended()), store, enabled = false) recorder.record(PushInput("fcm", mapOf("access_token" to "raw"))) diff --git a/sdk/security/api/security.api b/sdk/security/api/security.api index dbeddb0..7d5208c 100644 --- a/sdk/security/api/security.api +++ b/sdk/security/api/security.api @@ -2,6 +2,7 @@ public final class io/devconsole/security/RedactionEngine { public static final field Companion Lio/devconsole/security/RedactionEngine$Companion; public static final field DEFAULT_TEXT_LIMIT I public fun (Lio/devconsole/security/RedactionPolicy;)V + public final fun isEnabled ()Z public final fun redactFields (Ljava/util/Map;)Ljava/util/Map; public final fun redactText (Ljava/lang/String;I)Ljava/lang/String; public static synthetic fun redactText$default (Lio/devconsole/security/RedactionEngine;Ljava/lang/String;IILjava/lang/Object;)Ljava/lang/String; @@ -21,15 +22,21 @@ public final class io/devconsole/security/RedactionPolicy { public final fun component3 ()Ljava/util/List; public final fun copy (Ljava/util/Set;Ljava/lang/String;Ljava/util/List;)Lio/devconsole/security/RedactionPolicy; public static synthetic fun copy$default (Lio/devconsole/security/RedactionPolicy;Ljava/util/Set;Ljava/lang/String;Ljava/util/List;ILjava/lang/Object;)Lio/devconsole/security/RedactionPolicy; + public static final fun default ()Lio/devconsole/security/RedactionPolicy; public fun equals (Ljava/lang/Object;)Z public final fun getReplacement ()Ljava/lang/String; public final fun getSensitiveFieldNames ()Ljava/util/Set; public final fun getTextPatterns ()Ljava/util/List; + public final fun hasRules ()Z public fun hashCode ()I + public static final fun none ()Lio/devconsole/security/RedactionPolicy; + public static final fun recommended ()Lio/devconsole/security/RedactionPolicy; public fun toString ()Ljava/lang/String; } public final class io/devconsole/security/RedactionPolicy$Companion { public final fun default ()Lio/devconsole/security/RedactionPolicy; + public final fun none ()Lio/devconsole/security/RedactionPolicy; + public final fun recommended ()Lio/devconsole/security/RedactionPolicy; } diff --git a/sdk/security/src/main/kotlin/io/devconsole/security/RedactionEngine.kt b/sdk/security/src/main/kotlin/io/devconsole/security/RedactionEngine.kt index c5776cb..8a54150 100644 --- a/sdk/security/src/main/kotlin/io/devconsole/security/RedactionEngine.kt +++ b/sdk/security/src/main/kotlin/io/devconsole/security/RedactionEngine.kt @@ -19,15 +19,25 @@ data class RedactionPolicy( /** Normalized once here so every lookup can compare against a lower-cased name. */ internal val normalizedFieldNames: Set = sensitiveFieldNames.mapTo(mutableSetOf(), String::lowercase) + /** Whether this policy masks anything at all; [none] has no rules. */ + fun hasRules(): Boolean = sensitiveFieldNames.isNotEmpty() || textPatterns.isNotEmpty() + companion object { - /** - * Memoized so every `default()` caller shares one instance. [textPatterns] holds [Regex] - * values, which compare by reference, so a fresh policy per call would make two otherwise - * identical configs (e.g. [io.devconsole.api.DevConsoleConfig]) unequal. - */ - private val DEFAULT: RedactionPolicy by lazy { buildDefault() } + private val NONE = RedactionPolicy(sensitiveFieldNames = emptySet(), textPatterns = emptyList()) + + // Regex instances compare by reference, so share the recommended policy across callers. + private val RECOMMENDED: RedactionPolicy by lazy { buildDefault() } + + /** Out-of-the-box policy: no field or text masking. */ + @JvmStatic + fun default(): RedactionPolicy = none() - fun default(): RedactionPolicy = DEFAULT + @JvmStatic + fun none(): RedactionPolicy = NONE + + /** Opt-in built-in sensitive-field rules. */ + @JvmStatic + fun recommended(): RedactionPolicy = RECOMMENDED private fun buildDefault(): RedactionPolicy = RedactionPolicy( @@ -88,7 +98,10 @@ class RedactionEngine( jsonSecretField = compiledJsonSecretField } - /** The active policy's marker for a value that must never cross a redaction boundary. */ + /** Whether the active policy has any field or text rule. */ + fun isEnabled(): Boolean = policy.hasRules() + + /** The active policy's marker for a value withheld at a redaction boundary. */ fun replacement(): String = policy.replacement fun redactFields(fields: Map): Map = @@ -142,6 +155,8 @@ class RedactionEngine( } private fun jsonSecretFieldFor(policy: RedactionPolicy): Regex { + // An empty alternation would match an empty JSON key; none() must mask nothing. + if (policy.normalizedFieldNames.isEmpty()) return Regex("(?!)") val sensitiveNamePattern = policy.normalizedFieldNames.joinToString("|") { Regex.escape(it) } return Regex( "(\\\"(?:$sensitiveNamePattern)\\\"\\s*:\\s*)(?:\\\"(?:\\\\.|[^\\\"])*\\\"|[^,}\\s]+)", diff --git a/sdk/security/src/test/kotlin/io/devconsole/security/RedactionEngineTest.kt b/sdk/security/src/test/kotlin/io/devconsole/security/RedactionEngineTest.kt index 2a444ce..3f44ce0 100644 --- a/sdk/security/src/test/kotlin/io/devconsole/security/RedactionEngineTest.kt +++ b/sdk/security/src/test/kotlin/io/devconsole/security/RedactionEngineTest.kt @@ -6,7 +6,7 @@ import org.junit.Assert.assertTrue import org.junit.Test class RedactionEngineTest { - private val engine = RedactionEngine(RedactionPolicy.default()) + private val engine = RedactionEngine(RedactionPolicy.recommended()) @Test fun `redacts default sensitive headers case insensitively`() { @@ -16,11 +16,28 @@ class RedactionEngineTest { } @Test - fun `preserves authorization header unredacted by default`() { + fun `recommended policy preserves historical authorization header behavior`() { val fields = engine.redactFields(mapOf("Authorization" to "Bearer secret-token-123")) assertEquals("Bearer secret-token-123", fields["Authorization"]) } + @Test + fun `default and none policies mask no fields or text including empty JSON keys`() { + assertEquals(RedactionPolicy.none(), RedactionPolicy.default()) + val engine = RedactionEngine(RedactionPolicy.default()) + val fields = mapOf("Cookie" to "session=raw", "Authorization" to "Bearer raw", "token" to "raw") + val text = """{"":"raw","token":"raw"}?access_token=raw""" + + assertFalse(engine.isEnabled()) + assertEquals(fields, engine.redactFields(fields)) + assertEquals(text, engine.redactText(text)) + engine.updatePolicy(RedactionPolicy.recommended()) + assertTrue(engine.isEnabled()) + assertEquals("", engine.redactFields(fields)["token"]) + engine.updatePolicy(RedactionPolicy.none()) + assertEquals(text, engine.redactText(text)) + } + @Test fun `redacts access token query values before storage`() { assertEquals("", engine.redactFields(mapOf("access_token" to "abc"))["access_token"]) @@ -63,7 +80,7 @@ class RedactionEngineTest { @Test fun `redacts newly covered auth header names`() { - val engine = RedactionEngine(RedactionPolicy.default()) + val engine = RedactionEngine(RedactionPolicy.recommended()) val redacted = engine.redactFields( mapOf( diff --git a/sdk/server-ktor/api/server-ktor.api b/sdk/server-ktor/api/server-ktor.api index 8a41e35..be17186 100644 --- a/sdk/server-ktor/api/server-ktor.api +++ b/sdk/server-ktor/api/server-ktor.api @@ -31,6 +31,7 @@ public final class io/devconsole/server/ktor/DevConsoleModuleConfig { public final fun getMetadata ()Lio/devconsole/server/api/ServerMetadata; public final fun getMockEngine ()Lio/devconsole/mocks/MockEngine; public final fun getMocksEditable ()Z + public final fun getNetworkProtection ()Lio/devconsole/api/NetworkProtection; public final fun getNetworkTransactions ()Lio/devconsole/network/NetworkTransactionStore; public final fun getPreferencesEditable ()Z public final fun getPreferencesInspector ()Lio/devconsole/server/api/PreferencesInspector; @@ -74,6 +75,7 @@ public final class io/devconsole/server/ktor/DevConsoleModuleConfig { public final fun setMetadata (Lio/devconsole/server/api/ServerMetadata;)V public final fun setMockEngine (Lio/devconsole/mocks/MockEngine;)V public final fun setMocksEditable (Z)V + public final fun setNetworkProtection (Lio/devconsole/api/NetworkProtection;)V public final fun setNetworkTransactions (Lio/devconsole/network/NetworkTransactionStore;)V public final fun setPreferencesEditable (Z)V public final fun setPreferencesInspector (Lio/devconsole/server/api/PreferencesInspector;)V @@ -121,6 +123,7 @@ public final class io/devconsole/server/ktor/KtorLocalServerEngine : io/devconso public final fun withAttachmentMetadataReader (Lkotlin/jvm/functions/Function2;)Lio/devconsole/server/ktor/KtorLocalServerEngine; public final fun withAttachmentReader (Lkotlin/jvm/functions/Function2;)Lio/devconsole/server/ktor/KtorLocalServerEngine; public final fun withBrowserSecurity (Lio/devconsole/api/BrowserSecurity;)Lio/devconsole/server/ktor/KtorLocalServerEngine; + public final fun withNetworkProtection (Lio/devconsole/api/NetworkProtection;)Lio/devconsole/server/ktor/KtorLocalServerEngine; public final fun withRetainedCaptures (Lio/devconsole/storage/api/RetainedCaptureQuery;)Lio/devconsole/server/ktor/KtorLocalServerEngine; } diff --git a/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/ComposerHostAllowlist.kt b/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/ComposerHostAllowlist.kt index 7a30fc1..63dfe82 100644 --- a/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/ComposerHostAllowlist.kt +++ b/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/ComposerHostAllowlist.kt @@ -11,6 +11,9 @@ internal class ComposerHostAllowlist( configuredHosts.map { it.trim().lowercase() }.filter(String::isNotEmpty).toSortedSet() private val sessionHosts: MutableSet = Collections.newSetFromMap(ConcurrentHashMap()) + /** An app that configures no hosts opts out of the allowlist, so session hosts never narrow it. */ + val permitsAnyHost: Boolean = appHosts.isEmpty() + enum class Source { APP, SESSION } data class Entry( @@ -47,7 +50,7 @@ internal class ComposerHostAllowlist( fun permits(host: String): Boolean { val name = host.lowercase() - return name.isNotEmpty() && (name in appHosts || name in sessionHosts) + return name.isNotEmpty() && (permitsAnyHost || name in appHosts || name in sessionHosts) } fun entries(): List = 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 1c538ed..3c647a7 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 @@ -3,6 +3,7 @@ package io.devconsole.server.ktor import io.devconsole.api.BrowserSecurity import io.devconsole.api.CaptureRule import io.devconsole.api.CaptureRuleEngine +import io.devconsole.api.NetworkProtection import io.devconsole.api.ScreenshotResult import io.devconsole.composer.ComposerBinaryBody import io.devconsole.composer.ComposerBodyType @@ -190,10 +191,11 @@ class DevConsoleModuleConfig { var allowedHosts: Set = setOf("localhost", "127.0.0.1") /** - * Browser authentication policy. The standalone Ktor module keeps its historical secure - * default; the public full SDK explicitly supplies [BrowserSecurity.NONE] by default. + * Browser authentication is opt-in, matching the public full SDK. */ - var browserSecurity: BrowserSecurity = BrowserSecurity.SESSION_CODE + var browserSecurity: BrowserSecurity = BrowserSecurity.NONE + + var networkProtection: NetworkProtection = NetworkProtection() var streamHub: EventStreamHub = EventStreamHub() var timeline: Timeline = InMemoryTimeline(emptyList(), CursorCodec(ByteArray(16).also(SecureRandom()::nextBytes))) @@ -208,14 +210,14 @@ class DevConsoleModuleConfig { * available to any authenticated session; every rule-mutation route (create, delete, per-rule * enable/disable) answers 403 while this is false. */ - var mocksEditable: Boolean = false + var mocksEditable: Boolean = true var captureRules: CaptureRuleEngine = CaptureRuleEngine() /** * Mirrors `EditingCapabilities.captureRules`. Listing exclusions stays available to any * authenticated session; every mutation route answers 403 while this is false. */ - var captureRulesEditable: Boolean = false + var captureRulesEditable: Boolean = true var featureFlags: SessionFeatureFlags = SessionFeatureFlags(emptyList()) /** @@ -223,9 +225,9 @@ class DevConsoleModuleConfig { * session whenever the `state` capture category is enabled; the flag-override route answers 403 * while this is false. */ - var featureFlagsEditable: Boolean = false + var featureFlagsEditable: Boolean = true var stateRegistry: StateRegistry = StateRegistry() - var stateMutationsEnabled: Boolean = false + var stateMutationsEnabled: Boolean = true /** * Remote Config snapshots, **already redacted** by the caller. `:sdk:full` owns that boundary @@ -236,7 +238,7 @@ class DevConsoleModuleConfig { /** Reads (file/entry listing) always work; [preferencesEditable] mirrors `EditingCapabilities.preferences`. */ var preferencesInspector: PreferencesInspector? = null - var preferencesEditable: Boolean = false + var preferencesEditable: Boolean = true /** * Reads (database/table listing, row paging, read-only SQL) always work; [databaseEditable] mirrors @@ -244,11 +246,11 @@ class DevConsoleModuleConfig { * refused with `DatabaseExecResult.WriteBlocked` while this is false, exactly like the Compose adapter. */ var databaseInspector: DatabaseInspector? = null - var databaseEditable: Boolean = false + var databaseEditable: Boolean = true /** Reads (root/entry listing, bounded preview) always work; [filesEditable] mirrors `EditingCapabilities.files`. */ var fileInspector: FileInspector? = null - var filesEditable: Boolean = false + var filesEditable: Boolean = true var composerExecutor: ComposerExecutor = ComposerExecutor(UrlConnectionComposerTransport()) var composerCollections: ComposerCollectionStore = InMemoryComposerCollectionStore() var pushStore: PushStore = InMemoryPushStore() @@ -299,18 +301,17 @@ class DevConsoleModuleConfig { /** * The Composer lets an authenticated session make the device issue arbitrary outbound HTTP - * requests, effectively turning it into a proxy into whatever network it sits on. It is off - * unless a host opts in; every `/api/v1/composer` route answers 404 while disabled. + * requests. Enabled by default; every `/api/v1/composer` route answers 404 while disabled. */ - var composerEnabled: Boolean = false + var composerEnabled: Boolean = true /** - * Hosts the Composer may issue outbound requests to. Every destination, including redirects, - * must be explicitly listed; an empty set denies all requests. + * Hosts the Composer may issue outbound requests to, including redirects. + * An empty set permits any host; a non-empty set restricts destinations to exact matches. */ var composerAllowedHosts: Set = emptySet() - var composerHostsEditable: Boolean = false + var composerHostsEditable: Boolean = true internal var sharedComposerHosts: ComposerHostAllowlist? = null } @@ -327,6 +328,8 @@ fun Application.devConsoleModule( configure: DevConsoleModuleConfig.() -> Unit = {}, ) { val config = DevConsoleModuleConfig().apply(configure) + val networkProtection = config.networkProtection + attributes.put(NETWORK_PROTECTION_KEY, networkProtection) sessionAuthority.configureBrowserAuthentication(config.browserSecurity == BrowserSecurity.SESSION_CODE) val allowedHosts = config.allowedHosts val streamHub = config.streamHub @@ -447,7 +450,7 @@ fun Application.devConsoleModule( // future XSS would use to exfiltrate to an attacker-controlled WebSocket server -- down to // just the one endpoint the dashboard is actually allowed to talk to. val webSocketSource = - if (hostAllowed) { + if (parsedHost != null && (!networkProtection.hostAndOriginChecks || hostAllowed)) { val uriHost = if (':' in host) "[$host]" else host // re-bracket an IPv6 literal val portSuffix = parsedHost.port?.let { ":$it" }.orEmpty() "'self' ws://$uriHost$portSuffix" @@ -474,7 +477,7 @@ fun Application.devConsoleModule( ) call.response.headers.append(HttpHeaders.CacheControl, "no-store") - if (!hostAllowed) { + if (networkProtection.hostAndOriginChecks && !hostAllowed) { call.respondText("{\"code\":\"ORIGIN_REJECTED\"}", status = HttpStatusCode.Forbidden) finish() return@intercept @@ -525,7 +528,7 @@ fun Application.devConsoleModule( else -> null } } - if (limiter != null && !limiter.allow(browserSession.id)) { + if (networkProtection.rateLimiting && limiter != null && !limiter.allow(browserSession.id)) { path.commandAuditIdentity(method)?.let { (commandType, target) -> commandAuditLog.recordControlFailure(browserSession.id, commandType, target) } @@ -655,7 +658,10 @@ fun Application.devConsoleModule( metadata.captureCategories.joinToString(",") { "\"${it.escapeJson()}\"" } val body = metadata.json().dropLast(1) + - ",\"endpoint\":$endpointJson,\"redaction\":{\"sensitiveFieldNames\":[$redactedNames]}," + + ",\"endpoint\":$endpointJson," + + "\"redaction\":{\"enabled\":${redaction.isEnabled()},\"sensitiveFieldNames\":[$redactedNames]}," + + "\"networkProtection\":{\"rateLimiting\":${networkProtection.rateLimiting}," + + "\"hostAndOriginChecks\":${networkProtection.hostAndOriginChecks}}," + "\"composer\":{\"enabled\":$composerEnabled,\"allowedHosts\":[$allowedHosts]}," + "\"captureCategories\":[$captureCategories]}" call.respondText(body, contentType = io.ktor.http.ContentType.Application.Json) @@ -687,7 +693,9 @@ fun Application.devConsoleModule( } post("/api/v1/auth/session-code/exchange") { // Keyed by source IP rather than session id: exchange runs before any session exists. - if (!sessionCodeAttemptLimiter.allow(call.request.origin.remoteHost)) { + if (sessionAuthority.isBrowserAuthenticationRequired() && + !sessionCodeAttemptLimiter.allow(call.request.origin.remoteHost) + ) { call.respondText("{\"code\":\"RATE_LIMITED\"}", status = HttpStatusCode.TooManyRequests) return@post } @@ -858,7 +866,7 @@ fun Application.devConsoleModule( call.respondText("{\"code\":\"AUTH_REQUIRED\"}", status = HttpStatusCode.Unauthorized) return@get } - if (!exportLimiter.allow(session.id)) { + if (networkProtection.rateLimiting && !exportLimiter.allow(session.id)) { call.respondText("{\"code\":\"RATE_LIMITED\"}", status = HttpStatusCode.TooManyRequests) return@get } @@ -2657,7 +2665,7 @@ fun Application.devConsoleModule( } catch (rejected: io.devconsole.composer.ComposerDestinationRejectedException) { recordComposerCapture( request = resolvedRequest, - secretValues = request.secretValues(), + secretValues = if (redaction.isEnabled()) request.secretValues() else emptyList(), response = null, error = rejected, correlationId = correlationId, @@ -2678,7 +2686,7 @@ fun Application.devConsoleModule( } catch (failure: Throwable) { recordComposerCapture( request = resolvedRequest, - secretValues = request.secretValues(), + secretValues = if (redaction.isEnabled()) request.secretValues() else emptyList(), response = null, error = failure, correlationId = correlationId, @@ -2707,7 +2715,7 @@ fun Application.devConsoleModule( val transaction = recordComposerCapture( request = resolvedRequest, - secretValues = request.secretValues(), + secretValues = if (redaction.isEnabled()) request.secretValues() else emptyList(), response = execution.response, error = null, correlationId = correlationId, @@ -2723,12 +2731,12 @@ fun Application.devConsoleModule( session.id, "composer.execute", method, - mapOf("url" to url.withoutQuery()), + mapOf("url" to if (redaction.isEnabled()) url.withoutQuery() else url), ) call.respondText( "{\"correlationId\":\"${correlationId.escapeJson()}\"," + "\"executor\":\"${executorLabel.escapeJson()}\"," + - "\"request\":${execution.requestMetadata}," + + "\"request\":${request.toRedactedMetadata(redaction)}," + "\"response\":{\"statusCode\":${execution.response.statusCode}," + "\"durationMs\":${execution.response.durationMs ?: "null"}," + "${transaction.capture.response.composerResultJson()}}}", @@ -2745,7 +2753,8 @@ fun Application.devConsoleModule( "{\"host\":\"${entry.host.escapeJson()}\",\"source\":\"${entry.source.name.lowercase()}\"}" } call.respondText( - "{\"editable\":${composerHosts.editable},\"data\":[$hosts]}", + "{\"editable\":${composerHosts.editable},\"anyHost\":${composerHosts.permitsAnyHost}," + + "\"data\":[$hosts]}", contentType = io.ktor.http.ContentType.Application.Json, ) } @@ -3425,7 +3434,7 @@ fun Application.devConsoleModule( } catch (rejected: io.devconsole.composer.ComposerDestinationRejectedException) { recordComposerCapture( request = resolvedRequest, - secretValues = request.secretValues(), + secretValues = if (redaction.isEnabled()) request.secretValues() else emptyList(), response = null, error = rejected, correlationId = correlationId, @@ -3445,7 +3454,7 @@ fun Application.devConsoleModule( } catch (failure: Throwable) { recordComposerCapture( request = resolvedRequest, - secretValues = request.secretValues(), + secretValues = if (redaction.isEnabled()) request.secretValues() else emptyList(), response = null, error = failure, correlationId = correlationId, @@ -3461,7 +3470,7 @@ fun Application.devConsoleModule( } recordComposerCapture( request = resolvedRequest, - secretValues = request.secretValues(), + secretValues = if (redaction.isEnabled()) request.secretValues() else emptyList(), response = execution.response, error = null, correlationId = correlationId, @@ -3475,10 +3484,12 @@ fun Application.devConsoleModule( session.id, "network.resend", captured.method, - mapOf("url" to url.withoutQuery()), + mapOf("url" to if (redaction.isEnabled()) url.withoutQuery() else url), ) call.respondText( - "{\"correlationId\":\"${correlationId.escapeJson()}\",\"request\":${execution.requestMetadata}," + + "{\"correlationId\":\"${correlationId.escapeJson()}\",\"request\":${request.toRedactedMetadata( + redaction, + )}," + "\"response\":{\"statusCode\":${execution.response.statusCode}," + "\"durationMs\":${execution.response.durationMs ?: "null"}}}", contentType = io.ktor.http.ContentType.Application.Json, @@ -3614,7 +3625,7 @@ fun Application.devConsoleModule( } else { origin != null && origin != expectedOrigin } - if (originRejected) { + if (networkProtection.hostAndOriginChecks && originRejected) { commandAuditLog.recordControlFailure(session.id, "session.stop", "server") call.respondText("{\"code\":\"ORIGIN_REJECTED\"}", status = HttpStatusCode.Forbidden) return@post @@ -3637,7 +3648,10 @@ fun Application.devConsoleModule( // origin is rejected; a legitimate non-browser client (bearer token, no Origin header) // is allowed through, so absent-Origin is permitted while a mismatched one is not. val origin = call.request.headers[HttpHeaders.Origin] - if (origin != null && origin != "http://${call.request.headers[HttpHeaders.Host].orEmpty()}") { + if (networkProtection.hostAndOriginChecks && + origin != null && + origin != "http://${call.request.headers[HttpHeaders.Host].orEmpty()}" + ) { close(CloseReason(CloseReason.Codes.VIOLATED_POLICY.code, "ORIGIN_REJECTED")) return@webSocket } @@ -3693,7 +3707,7 @@ private const val STREAM_AUTH_RECHECK_MS = 100L * not from every route the device happens to have. Android's local-network runtime permission * (where applicable) is gated upstream, by the caller, before `start` is ever invoked in LAN mode. */ -@Suppress("LongParameterList") // Every capture engine/inspector the dashboard can reach is injected here. +@Suppress("LongParameterList", "TooManyFunctions") // Every inspector is injected here; each policy has a with-copy. class KtorLocalServerEngine( private val sessionAuthority: SessionAuthority = SessionAuthority(), private val sessionCodeAuthority: SessionCodeAuthority = SessionCodeAuthority(sessionAuthority), @@ -3707,24 +3721,24 @@ class KtorLocalServerEngine( /** Already-redacted Remote Config snapshots; see [DevConsoleModuleConfig.remoteConfigSnapshots]. */ private val remoteConfigSnapshots: () -> List = { emptyList() }, featureFlags: SessionFeatureFlags = SessionFeatureFlags(emptyList()), - featureFlagsEditable: Boolean = false, + featureFlagsEditable: Boolean = true, private val mockEngine: MockEngine = MockEngine(emptyList()), - mocksEditable: Boolean = false, + mocksEditable: Boolean = true, private val captureRules: CaptureRuleEngine = CaptureRuleEngine(), - captureRulesEditable: Boolean = false, + captureRulesEditable: Boolean = true, private val preferencesInspector: PreferencesInspector? = null, - preferencesEditable: Boolean = false, + preferencesEditable: Boolean = true, private val databaseInspector: DatabaseInspector? = null, - databaseEditable: Boolean = false, + databaseEditable: Boolean = true, private val fileInspector: FileInspector? = null, - filesEditable: Boolean = false, + filesEditable: Boolean = true, /** Supplied by the platform facade so events can be persisted; defaults to in-memory. */ private val timeline: Timeline = InMemoryTimeline(emptyList(), CursorCodec(ByteArray(16).also(SecureRandom()::nextBytes))), - composerEnabled: Boolean = false, + composerEnabled: Boolean = true, composerAllowedHosts: Set = emptySet(), - composerHostsEditable: Boolean = false, - stateMutationsEnabled: Boolean = false, + composerHostsEditable: Boolean = true, + stateMutationsEnabled: Boolean = true, redactionPolicy: RedactionPolicy = RedactionPolicy.default(), private val pushSimulator: PushSimulator? = null, private val commandAuditLog: CommandAuditLog = InMemoryCommandAuditLog(), @@ -3765,7 +3779,11 @@ class KtorLocalServerEngine( /** Applied before the next server start; a running Ktor application captures its mode. */ @Volatile - private var browserSecurity: BrowserSecurity = BrowserSecurity.SESSION_CODE + private var browserSecurity: BrowserSecurity = BrowserSecurity.NONE + + /** Applied before the next server start, matching browser authentication reconfiguration. */ + @Volatile + private var networkProtection: NetworkProtection = NetworkProtection() @Volatile private var attachmentReader: suspend (String) -> ByteArray? = { null } @@ -3787,6 +3805,11 @@ class KtorLocalServerEngine( browserSecurity = value } + fun withNetworkProtection(value: NetworkProtection): KtorLocalServerEngine = + apply { + networkProtection = value + } + @Volatile private var composerHosts = ComposerHostAllowlist(composerAllowedHosts, composerHostsEditable) @@ -3817,13 +3840,13 @@ class KtorLocalServerEngine( composerAllowedHosts: Set, stateMutationsEnabled: Boolean, redactionPolicy: RedactionPolicy, - composerHostsEditable: Boolean = false, - mocksEditable: Boolean = false, - captureRulesEditable: Boolean = false, - preferencesEditable: Boolean = false, - databaseEditable: Boolean = false, - filesEditable: Boolean = false, - featureFlagsEditable: Boolean = false, + composerHostsEditable: Boolean = true, + mocksEditable: Boolean = true, + captureRulesEditable: Boolean = true, + preferencesEditable: Boolean = true, + databaseEditable: Boolean = true, + filesEditable: Boolean = true, + featureFlagsEditable: Boolean = true, ) { if (!composerHosts.hasConfiguration(composerAllowedHosts, composerHostsEditable)) { composerHosts = ComposerHostAllowlist(composerAllowedHosts, composerHostsEditable) @@ -3942,6 +3965,7 @@ class KtorLocalServerEngine( this.pushSimulator = this@KtorLocalServerEngine.pushSimulator this.commandAuditLog = this@KtorLocalServerEngine.commandAuditLog this.redactionPolicy = configuration.redactionPolicy + this.networkProtection = this@KtorLocalServerEngine.networkProtection this.attachmentReader = this@KtorLocalServerEngine.attachmentReader this.attachmentMetadataReader = this@KtorLocalServerEngine.attachmentMetadataReader this.retainedCaptures = this@KtorLocalServerEngine.retainedCaptures @@ -4471,19 +4495,20 @@ private fun SessionAuthority.bearerSession(authorization: String?) = ?.let { token -> sessionForToken(token) } } +private val NETWORK_PROTECTION_KEY = io.ktor.util.AttributeKey("devconsole.networkProtection") + private fun io.ktor.server.application.ApplicationCall.isOriginAndCsrfAuthorized( authority: SessionAuthority, ): Boolean { val expectedOrigin = "http://${request.headers[HttpHeaders.Host].orEmpty()}" val origin = request.headers[HttpHeaders.Origin] + val checkOrigin = application.attributes[NETWORK_PROTECTION_KEY].hostAndOriginChecks return if (!authority.isBrowserAuthenticationRequired()) { - // Open mode removes credentials, not the browser's same-origin boundary. Browsers send an - // Origin on cross-site mutations, so reject a foreign value while keeping curl/CLI clients - // (which normally omit Origin) usable without inventing a replacement secret. - origin == null || origin == expectedOrigin + // Origin validation is independent of authentication; open CLI clients may omit Origin. + !checkOrigin || origin == null || origin == expectedOrigin } else { authority.bearerSession(request.headers[HttpHeaders.Authorization])?.let { session -> - origin == expectedOrigin && request.headers[CSRF_HEADER] == session.csrfToken + (!checkOrigin || origin == expectedOrigin) && request.headers[CSRF_HEADER] == session.csrfToken } ?: false } } @@ -5336,7 +5361,7 @@ private fun parseAgentFrame(text: String): Parameters? = private fun String.withoutQuery(): String = substringBefore('?') -/** Composer is a device-side proxy, so every destination must be explicitly allowlisted. */ +/** No app-configured host permits any host; otherwise every destination must be allowlisted. */ private fun ComposerHostAllowlist.permitsHostOf(url: String): Boolean = permits(url.hostOrEmpty()) private fun String.isHttpUrl(): Boolean = @@ -5829,17 +5854,8 @@ private fun StateValue.json(): String = } ?: "null"}}" } -private fun io.ktor.server.application.ApplicationCall.isReadMutationAuthorized(authority: SessionAuthority): Boolean { - val expectedOrigin = "http://${request.headers[HttpHeaders.Host].orEmpty()}" - val origin = request.headers[HttpHeaders.Origin] - return if (!authority.isBrowserAuthenticationRequired()) { - origin == null || origin == expectedOrigin - } else { - authority.bearerSession(request.headers[HttpHeaders.Authorization])?.let { session -> - origin == expectedOrigin && request.headers[CSRF_HEADER] == session.csrfToken - } ?: false - } -} +private fun io.ktor.server.application.ApplicationCall.isReadMutationAuthorized(authority: SessionAuthority): Boolean = + isOriginAndCsrfAuthorized(authority) // ============================================================================================ // Evidence snapshot materialization (A -- see the design spec's "Snapshot at flag time" section). diff --git a/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css b/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css index 78901d3..6638cfd 100644 --- a/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css +++ b/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css @@ -1,5 +1,5 @@ /* ============================================================ - DevConsole dashboard — graphite/cobalt diagnostic workbench. + DevConsole dashboard — graphite/signal-green diagnostic workbench. Dual theme via [data-theme] on ; dark is the default. ============================================================ */ @@ -7,69 +7,69 @@ --font-ui: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; --font-mono: ui-monospace, "SF Mono", Menlo, Consolas, monospace; - /* Dark graphite/cobalt (default) */ - --ground: #111317; - --panel: #171a20; - --surface-2: #1d2129; - --surface-3: #242a34; - --code-bg: #0d0f13; - --ink: #eceef2; - --muted: #969da8; - --text-3: #858d99; - --line: #343a45; - --border-strong: #4a5260; - --control-outline: #667080; - --signal: #72a7ff; - --signal-ink: #0e1624; - --warn: #f2b66d; - --error: #ff7b72; - --put: #72c4ce; - --success: #7bc9a5; - - --signal-soft: rgba(114, 167, 255, 0.13); - --error-soft: rgba(255, 123, 114, 0.13); - --warn-soft: rgba(242, 182, 109, 0.13); - --put-soft: rgba(114, 196, 206, 0.13); - --success-soft: rgba(123, 201, 165, 0.13); + /* Dark graphite/signal green (default) */ + --ground: #111413; + --panel: #181c1a; + --surface-2: #1e2320; + --surface-3: #252b27; + --code-bg: #141816; + --ink: #ecebe4; + --muted: #8d9289; + --text-3: #8d9289; + --line: #242a26; + --border-strong: #3a423d; + --control-outline: #6b726b; + --signal: #b7ed65; + --signal-ink: #111413; + --warn: #e8b45c; + --error: #ff7a6b; + --put: #8fcfc9; + --success: #a9d99a; + + --signal-soft: rgba(183, 237, 101, 0.14); + --error-soft: rgba(255, 122, 107, 0.14); + --warn-soft: rgba(232, 180, 92, 0.14); + --put-soft: rgba(143, 207, 201, 0.14); + --success-soft: rgba(169, 217, 154, 0.14); --elev-3: 0 8px 24px rgba(0, 0, 0, 0.28); - --json-key: #8cb8ff; - --json-string: #a9d6b9; + --json-key: #8fcfc9; + --json-string: #a9d99a; --json-number: var(--warn); - --json-boolean: #c7a7ff; + --json-boolean: #c9b3f2; --json-null: var(--muted); --json-brace-0: var(--signal); --json-brace-1: var(--warn); --json-brace-2: var(--put); --json-brace-3: var(--ink); - --json-brace-4: #c7a7ff; + --json-brace-4: #c9b3f2; } :root[data-theme="light"] { - --ground: #f7f8fa; + --ground: #f2f3f0; --panel: #ffffff; - --surface-2: #eef1f5; - --surface-3: #e4e8ee; - --code-bg: #f2f4f7; - --ink: #1c1f24; - --muted: #68707b; - --text-3: #5f6874; - --line: #d5d9e0; - --border-strong: #aab1bc; - --control-outline: #808996; - --signal: #245da8; + --surface-2: #eceee9; + --surface-3: #e2e5df; + --code-bg: #f6f7f4; + --ink: #151714; + --muted: #62675f; + --text-3: #62675f; + --line: #e3e5e0; + --border-strong: #c9cdc4; + --control-outline: #8f948b; + --signal: #2f7a1f; --signal-ink: #ffffff; - --warn: #8a5a12; - --error: #b33a31; - --put: #1e6d76; - --success: #2f7255; + --warn: #9a5b00; + --error: #c0261d; + --put: #1e6d6a; + --success: #3d6b2a; - --signal-soft: rgba(36, 93, 168, 0.10); - --error-soft: rgba(179, 58, 49, 0.10); - --warn-soft: rgba(138, 90, 18, 0.10); - --put-soft: rgba(30, 109, 118, 0.10); - --success-soft: rgba(47, 114, 85, 0.10); + --signal-soft: rgba(47, 122, 31, 0.10); + --error-soft: rgba(192, 38, 29, 0.10); + --warn-soft: rgba(154, 91, 0, 0.10); + --put-soft: rgba(30, 109, 106, 0.10); + --success-soft: rgba(61, 107, 42, 0.10); --json-key: var(--signal); --json-string: var(--success); @@ -183,14 +183,14 @@ body { -webkit-font-smoothing: antialiased; } -::selection { background: var(--signal); color: var(--signal-ink); } -a { color: var(--signal); } +::selection { background: var(--ink); color: var(--panel); } +a { color: var(--ink); } a:hover { color: var(--ink); text-decoration: underline; } /* Visible focus ring everywhere (mock: 2px signal, offset 2) — WCAG 2.2 AA gate. No border-radius here: the universal selector would override each element's own radius. */ *:focus-visible { - outline: 2px solid var(--signal); + outline: 2px solid var(--ink); outline-offset: 2px; } @@ -208,13 +208,13 @@ div::-webkit-scrollbar-track, nav::-webkit-scrollbar-track { background: transpa .ic { width: 16px; height: 16px; flex-shrink: 0; display: inline-block; vertical-align: middle; - fill: none; stroke: currentColor; stroke-width: 2; + fill: none; stroke: currentColor; stroke-width: 1.5; stroke-linecap: round; stroke-linejoin: round; color: inherit; pointer-events: none; } .ic-sm { width: 12px; height: 12px; } .ic-lg { width: 20px; height: 20px; } -.ic-xl { width: 38px; height: 38px; stroke-width: 1.6; } +.ic-xl { width: 38px; height: 38px; stroke-width: 1.5; } /* The brand mark is drawn at 22x22 with the SVG's default 1px stroke — distinct from .ic-lg (20px / stroke-width 2), so it gets its own class instead of reusing that one. */ .brand-mark { width: 22px; height: 22px; stroke-width: 1; } @@ -237,10 +237,10 @@ div::-webkit-scrollbar-track, nav::-webkit-scrollbar-track { background: transpa width: 30px; height: 30px; padding: 0; border: 1px solid var(--control-outline); border-radius: 6px; background: var(--surface-2); color: var(--muted); cursor: pointer; } -.rail-toggle:hover { color: var(--signal); border-color: var(--border-strong); } -.rail-toggle[aria-pressed="true"] { border-color: var(--signal); background: var(--signal-soft); color: var(--signal); } +.rail-toggle:hover { color: var(--ink); border-color: var(--border-strong); } +.rail-toggle[aria-pressed="true"] { border-color: var(--ink); background: var(--surface-2); color: var(--ink); } .brand { display: flex; align-items: center; gap: 8px; flex: 0 0 auto; } -.brand-logo { display: inline-flex; align-items: center; justify-content: center; color: var(--signal); } +.brand-logo { display: inline-flex; align-items: center; justify-content: center; color: var(--ink); } .brand-name { font-size: 13px; font-weight: 650; letter-spacing: -0.01em; white-space: nowrap; } .session-pill { @@ -255,7 +255,7 @@ div::-webkit-scrollbar-track, nav::-webkit-scrollbar-track { background: transpa flex: 0 0 auto; width: 6px; height: 6px; border-radius: 99px; background: var(--warn); animation: dcPulse 2.4s ease-in-out infinite; } -.session-pill .dot.live { background: var(--signal); } +.session-pill .dot.live { background: var(--ink); } /* Session-expired state (see handleSessionExpired in dashboard.js): a solid, non-pulsing error dot so it reads as distinct from the ordinary "reconnecting" warn-pulse below. */ .session-pill .dot.expired { background: var(--error); animation: none; } @@ -276,7 +276,7 @@ div::-webkit-scrollbar-track, nav::-webkit-scrollbar-track { background: transpa } .stream-seg button:last-child { border-right: none; } .stream-seg button .ic { width: 12px; height: 12px; opacity: 1; } -.stream-seg button.active { color: var(--signal-ink); background: var(--signal); } +.stream-seg button.active { color: var(--panel); background: var(--ink); } .host-line { flex: 0 1 auto; min-width: 0; font-family: var(--font-mono); font-size: 11.5px; color: var(--text-3); @@ -292,8 +292,8 @@ div::-webkit-scrollbar-track, nav::-webkit-scrollbar-track { background: transpa display: inline-flex; align-items: center; justify-content: center; transition: color 0.15s, border-color 0.15s, background 0.15s; } -.icon-btn:hover { color: var(--signal); border-color: var(--border-strong); } -.icon-btn.active { color: var(--signal-ink); background: var(--signal); border-color: var(--signal); } +.icon-btn:hover { color: var(--ink); border-color: var(--border-strong); } +.icon-btn.active { color: var(--panel); background: var(--ink); border-color: var(--ink); } .icon-btn:disabled { cursor: not-allowed; opacity: 0.5; } .icon-btn:disabled:hover { color: var(--muted); border-color: var(--line); } @@ -349,7 +349,7 @@ body.rail-hidden .rail { display: none; } background: var(--surface-2); color: var(--ink); font-weight: 600; } .rail button.active::before, .rail button[aria-current="page"]::before { - content: ""; position: absolute; left: 0; top: 7px; bottom: 7px; width: 2px; border-radius: 99px; background: var(--signal); + content: ""; position: absolute; left: 0; top: 7px; bottom: 7px; width: 2px; border-radius: 99px; background: var(--ink); } .rail-name { font-size: 13px; font-weight: 500; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .rail button.active .rail-name, .rail button[aria-current="page"] .rail-name { font-weight: 600; } @@ -359,7 +359,7 @@ body.rail-hidden .rail { display: none; } padding: 1px 4px; display: none; border-radius: 99px; background: var(--surface-3); color: var(--muted); } .rail-count.show { display: inline-block; } -.rail button.active .rail-count, .rail button[aria-current="page"] .rail-count { background: var(--signal); color: var(--signal-ink); } +.rail button.active .rail-count, .rail button[aria-current="page"] .rail-count { background: var(--ink); color: var(--panel); } .rail-shortcuts { margin-top: 24px; padding: 0 10px; color: var(--text-3); } .rail-shortcuts-title { @@ -429,6 +429,18 @@ main { flex: 1 1 0%; min-width: 0; min-height: 0; display: flex; flex-direction: } @media (max-width: 1000px) { .view-badge { display: none; } } .view-hint { margin: 0; flex: 0 1 auto; min-width: 0; font-size: 12.5px; color: var(--muted); text-align: right; max-width: 520px; } +.view-hint:empty { display: none; } +.visually-hidden { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border: 0; +} /* Title + badge row inside `.view-head`'s left side (every view repeats this). */ .view-title-row { display: flex; align-items: baseline; gap: 12px; min-width: 0; } @@ -446,13 +458,11 @@ input, select, textarea, button { textarea { font-family: var(--font-mono); } input::placeholder, textarea::placeholder { color: var(--text-3); } input:focus, select:focus, textarea:focus { - outline: none; border-color: var(--signal); - box-shadow: 0 0 0 3px color-mix(in srgb, var(--signal) 18%, transparent); + outline: 2px solid var(--signal); outline-offset: 2px; border-color: var(--line); + box-shadow: none; } select { - appearance: none; cursor: pointer; - background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6'%3E%3Cpath d='M1 1l4 4 4-4' stroke='%2392968e' stroke-width='1.5' fill='none' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E"); - background-repeat: no-repeat; background-position: right 10px center; background-size: 10px 6px; + appearance: auto; cursor: pointer; padding-right: 28px; } @@ -463,12 +473,26 @@ button { font-weight: 500; white-space: nowrap; } button .ic { opacity: 0.85; } -button:hover { border-color: var(--signal); color: var(--signal); } +button:hover { border-color: var(--ink); color: var(--ink); } button:disabled { cursor: not-allowed; opacity: 0.5; } -button.primary { background: var(--signal); color: var(--signal-ink); border-color: var(--signal); font-weight: 700; } -button.primary:hover { background: color-mix(in srgb, var(--signal) 85%, black); color: var(--signal-ink); } +button.primary { background: var(--ink); color: var(--panel); border-color: var(--ink); font-weight: 700; } +button.primary:hover { background: var(--ink); color: var(--panel); } button.danger { color: var(--error); border-color: var(--error); background: var(--error-soft); } button.danger:hover { border-color: var(--error); background: color-mix(in srgb, var(--error) 20%, transparent); color: var(--error); } +#mockDisable.danger, +.toolbar > button.danger { + color: var(--muted); + border-color: var(--line); + background: transparent; +} +#mockDisable.danger:hover, +#mockDisable.danger:focus-visible, +.toolbar > button.danger:hover, +.toolbar > button.danger:focus-visible { + color: var(--error); + border-color: var(--error); + background: var(--error-soft); +} button.xs { padding: 5px 9px; font-size: 11.5px; } button.ghost { background: transparent; } .toolbar > button, .toolbar .filter-actions > button { @@ -495,7 +519,7 @@ button.ghost { background: transparent; } letter-spacing: 0.02em; color: var(--muted); } .seg button:hover { color: var(--ink); background: var(--surface-2); } -.seg button.active { color: var(--signal-ink); background: var(--signal); } +.seg button.active { color: var(--panel); background: var(--ink); } .seg-count { margin-left: 8px; color: var(--text-3); font-size: 10.5px; } /* Labeled multi-select dropdown — behavior is attached in dashboard.js (dropdownHtml). */ @@ -505,9 +529,9 @@ button.ghost { background: transparent; } padding: 0 12px; border: 1px solid var(--line); border-radius: 8px; background: var(--code-bg); color: var(--ink); } -.drop-btn:hover { border-color: var(--signal); color: var(--ink); } -.drop-btn[aria-expanded="true"], .drop-btn.has-selection { border-color: var(--signal); } -.drop-btn.has-selection { background: var(--signal-soft); } +.drop-btn:hover { border-color: var(--ink); color: var(--ink); } +.drop-btn[aria-expanded="true"], .drop-btn.has-selection { border-color: var(--ink); } +.drop-btn.has-selection { background: var(--surface-2); } .drop-summary { flex: 1; text-align: left; font-family: var(--font-mono); font-size: 11.5px; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; @@ -515,7 +539,7 @@ button.ghost { background: transparent; } .drop-btn.has-selection .drop-summary { color: var(--ink); } .drop-count { font-family: var(--font-mono); font-size: 10.5px; font-weight: 700; padding: 1px 8px; - border-radius: 99px; background: var(--signal); color: var(--signal-ink); + border-radius: 99px; background: var(--ink); color: var(--panel); } .drop-btn .ic-chevron { flex: 0 0 auto; color: var(--text-3); transform: rotate(-90deg); transition: transform 0.12s ease; } .drop-btn[aria-expanded="true"] .ic-chevron { transform: rotate(0deg); } @@ -530,12 +554,12 @@ button.ghost { background: transparent; } border: none; border-radius: 6px; background: transparent; text-align: left; color: var(--muted); } .drop-item:hover { background: var(--surface-2); border-color: transparent; color: var(--ink); } -.drop-item[aria-checked="true"] { background: var(--signal-soft); color: var(--ink); } +.drop-item[aria-checked="true"] { background: var(--surface-2); color: var(--ink); } .drop-box { display: grid; place-items: center; flex: 0 0 auto; width: 15px; height: 15px; - border: 1px solid var(--control-outline); border-radius: 6px; background: transparent; color: var(--signal-ink); + border: 1px solid var(--control-outline); border-radius: 6px; background: transparent; color: var(--panel); } -.drop-item[aria-checked="true"] .drop-box { border-color: var(--signal); background: var(--signal); } +.drop-item[aria-checked="true"] .drop-box { border-color: var(--ink); background: var(--ink); } .drop-dot { flex: 0 0 auto; width: 6px; height: 6px; border-radius: 99px; } .drop-item-label { flex: 1; min-width: 0; font-family: var(--font-mono); font-size: 11.5px; @@ -553,12 +577,12 @@ button.ghost { background: transparent; } .applied-filters-label { font-size: 10.5px; font-weight: 600; color: var(--text-3); } .applied-filter { display: flex; align-items: center; gap: 8px; height: 24px; padding: 0 4px 0 8px; - border: 1px solid var(--signal); border-radius: 99px; background: var(--signal-soft); color: var(--ink); cursor: pointer; + border: 1px solid var(--ink); border-radius: 99px; background: var(--surface-2); color: var(--ink); cursor: pointer; } .applied-filter-label { font-family: var(--font-mono); font-size: 11.5px; white-space: nowrap; } .applied-filter-x { display: grid; place-items: center; width: 14px; height: 14px; border-radius: 99px; - background: var(--signal); color: var(--signal-ink); font-size: 11.5px; line-height: 1; + background: var(--ink); color: var(--panel); font-size: 11.5px; line-height: 1; } .applied-filters-reset { height: 24px; padding: 0 8px; font-size: 11.5px; font-weight: 600; color: var(--muted); @@ -570,7 +594,7 @@ button.ghost { background: transparent; } same toolbar family rather than a new, unrelated widget. */ .selection-bar { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; margin-bottom: 12px; - padding: 6px 10px; border: 1px solid var(--signal); border-radius: 8px; background: var(--signal-soft); + padding: 6px 10px; border: 1px solid var(--ink); border-radius: 8px; background: var(--surface-2); } .selection-count { font-family: var(--font-mono); font-size: 11.5px; font-weight: 700; color: var(--ink); white-space: nowrap; } .selection-spacer { flex: 1; } @@ -633,18 +657,19 @@ button.ghost { background: transparent; } .empty-state-actions { justify-content: center; margin-top: 0; padding: 4px 0 8px; } .host-add-row { display: flex; gap: 8px; } .host-add-row input { flex: 1; min-width: 0; } -.host-list { display: flex; flex-direction: column; margin-top: 12px; border: 1px solid var(--line); border-radius: 8px; max-height: 280px; overflow-y: auto; } -.host-row { display: flex; align-items: center; gap: 10px; padding: 8px 12px; border-bottom: 1px solid var(--line); } +.host-list { display: flex; flex-direction: column; margin-top: 12px; border-top: 1px solid var(--line); max-height: 280px; overflow-y: auto; } +.host-row { display: flex; align-items: center; gap: 10px; padding: 8px 0; border-bottom: 1px solid var(--line); } .host-row:last-child { border-bottom: 0; } .host-row-name { flex: 1; min-width: 0; overflow-wrap: anywhere; font-family: var(--font-mono); color: var(--text); } .host-row-tag { font-size: 11px; color: var(--text-3); } .host-row.is-added .host-row-tag { color: var(--signal); } .host-row.is-removed .host-row-name { text-decoration: line-through; color: var(--text-3); } .host-row.is-removed .host-row-tag { color: var(--error); } -.host-list-empty { padding: 14px 12px; color: var(--text-3); } +.host-list-empty { padding: 14px 0; color: var(--text-3); } .host-dialog-error { margin: 8px 0 0; color: var(--error); white-space: pre-line; } button.is-refreshing .ic { animation: composerSpin 0.8s linear infinite; } .field.field-highlight select { border-color: var(--signal); animation: composerFieldPulse 0.9s ease-in-out 3; } +#mocksRulesBadge:empty { display: none; } .card-shell-badge { font-family: var(--font-mono); font-size: 10.5px; padding: 2px 8px; border-radius: 99px; border: 1px solid var(--line); color: var(--text-3); } .card-shell-body { flex: 1; display: flex; flex-direction: column; padding: 14px 0 0; } /* --d-card-pad, not a literal 16px: this is the consumer that token was declared for, and until @@ -655,18 +680,25 @@ button.is-refreshing .ic { animation: composerSpin 0.8s linear infinite; } /* Toggle switch, 38x22 — scaffolding for capability toggles. */ .toggle-switch { position: relative; flex: 0 0 auto; width: 38px; height: 22px; border-radius: 99px; border: 1px solid var(--control-outline); background: var(--surface-3); } .toggle-switch .knob { position: absolute; top: 2px; left: 2px; width: 16px; height: 16px; border-radius: 99px; background: var(--muted); transition: left 0.15s ease; } -.toggle-switch[aria-checked="true"] { border-color: var(--signal); background: var(--signal); } -.toggle-switch[aria-checked="true"] .knob { left: 18px; background: var(--signal-ink); } +.toggle-switch[aria-checked="true"] { border-color: var(--ink); background: var(--ink); } +.toggle-switch[aria-checked="true"] .knob { left: 18px; background: var(--panel); } .toggle-switch:disabled { opacity: 0.5; cursor: not-allowed; } /* Advanced filters disclosure */ -details.adv-filters { border: 1px solid var(--line); background: var(--panel); border-radius: 8px; margin-bottom: 12px; } -details.adv-filters > summary { - list-style: none; cursor: pointer; padding: 10px 14px; display: flex; align-items: center; gap: 8px; - color: var(--muted); font-size: 11.5px; font-weight: 700; -} -details.adv-filters > summary::-webkit-details-marker { display: none; } -details.adv-filters > summary .ic { color: var(--text-3); } +details.adv-filters, details.fold { border: 0; background: transparent; border-radius: 0; margin: 8px 0 12px; min-width: 0; } +details.adv-filters > summary, details.fold > summary { + list-style: none; cursor: pointer; padding: 8px 0; display: flex; align-items: center; gap: 8px; + color: var(--muted); font-size: 13px; font-weight: 400; +} +details.adv-filters > summary::-webkit-details-marker, details.fold > summary::-webkit-details-marker { display: none; } +details.adv-filters > summary .ic, details.fold > summary .fold-chevron { color: var(--text-3); flex: 0 0 auto; transition: transform 120ms; } +details.adv-filters > summary .ic, details.fold > summary .fold-chevron { transform: rotate(-90deg); } +details.adv-filters[open] > summary .ic, details.fold[open] > summary .fold-chevron { transform: rotate(0); } +.fold-count { margin-left: auto; color: var(--text-3); font-size: 12px; } +.fold-content { padding: 4px 0 8px; min-width: 0; } +.fold-content > :first-child { margin-top: 0; } +.load-status { padding: 20px 12px; color: var(--muted); font-size: 13px; } +.load-retry { border: 0; padding: 2px 6px; background: transparent; color: var(--ink); text-decoration: underline; } .filter-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 190px), 1fr)); gap: 10px; padding: 4px 14px 14px; @@ -675,6 +707,9 @@ details.adv-filters > summary .ic { color: var(--text-3); } /* A `.filter-grid` used inside a card-shell-body that already has its own padding (Composer's Request card) needs to flush its own to avoid doubling up. */ .filter-grid-flush { padding: 0; } +@media (min-width: 700px) { .filter-grid .field-url { grid-column: 2 / -1; } } +#captureRuleStatus:empty, #composerHostNote:empty { display: none; } +.agent-command { display: block; margin-top: 4px; font-family: var(--font-mono); font-size: 12px; color: var(--text); overflow-wrap: anywhere; } /* ---------------- List / detail split ---------------- */ /* A `.row` spends 298px on fixed columns, so the list column must stay well above that or @@ -770,10 +805,10 @@ body.detail-zoom .split-shell.collapse-detail { grid-template-columns: 1fr; } view opts in. */ .col-check, .row-check { flex: 0 0 24px; display: grid; place-items: center; width: 24px; height: 24px; padding: 0; - border: 1px solid var(--control-outline); border-radius: 6px; background: transparent; color: var(--signal-ink); + border: 1px solid var(--control-outline); border-radius: 6px; background: transparent; color: var(--panel); } -.row-check:hover, .col-check:hover { border-color: var(--signal); } -.row-check[aria-checked="true"], .col-check[aria-checked="true"] { border-color: var(--signal); background: var(--signal); } +.row-check:hover, .col-check:hover { border-color: var(--ink); } +.row-check[aria-checked="true"], .col-check[aria-checked="true"] { border-color: var(--ink); background: var(--ink); } /* A left accent bar (box-shadow, never background) so a checked-but-not-open-in-detail row still reads as picked without fighting .row.selected's own background/::before for the same pixels. */ .row.row-picked { box-shadow: inset 2px 0 0 var(--put); } @@ -783,7 +818,7 @@ body.detail-zoom .split-shell.collapse-detail { grid-template-columns: 1fr; } .splitter { width: 5px; background: var(--line); } .splitter:hover, .splitter:focus-visible, -.splitter.dragging { background: var(--signal); } +.splitter.dragging { background: var(--ink); } .detail-pane-v2 { min-width: 0; display: flex; flex-direction: column; overflow: hidden; background: var(--ground); } @@ -799,7 +834,7 @@ body.detail-zoom .split-shell.collapse-detail { grid-template-columns: 1fr; } background: transparent; color: var(--ink); font: inherit; font-size: var(--d-row-font); } .row:hover { background: var(--surface-2); } -.row.selected, .row[aria-selected="true"], .trace-row.selected { background: var(--surface-2); box-shadow: inset 2px 0 var(--signal); } +.row.selected, .row[aria-selected="true"], .trace-row.selected { background: var(--surface-2); box-shadow: inset 2px 0 var(--ink); } .row-badge { flex: 0 0 50px; font-family: var(--font-mono); font-size: 10.5px; font-weight: 700; letter-spacing: 0.04em; text-align: center; padding: 2px 0; border-radius: 4px; @@ -825,7 +860,7 @@ body.detail-zoom .split-shell.collapse-detail { grid-template-columns: 1fr; } /* Query string trailing a Network row's path: present and readable, but never louder than the endpoint. */ .row-main-sub { color: var(--text-3); } .row-tag { - flex: 0 0 auto; font-family: var(--font-mono); font-size: 9.5px; font-weight: 700; letter-spacing: 0.06em; + flex: 0 1 auto; min-width: 0; max-width: 45%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-family: var(--font-mono); font-size: 9.5px; font-weight: 700; letter-spacing: 0.06em; padding: 1px 4px; border-radius: 99px; border: 1px solid var(--border-strong); } /* Network stacks its status over its duration in one column (rowHtml's `stackMetrics`), the way @@ -848,22 +883,22 @@ body.detail-zoom .split-shell.collapse-detail { grid-template-columns: 1fr; } flex: 0 0 auto; display: grid; place-items: center; width: 24px; height: 24px; padding: 0; border: none; border-radius: 6px; background: transparent; color: var(--text-3); } -.row-flag:hover { color: var(--signal); border-color: transparent; background: var(--surface-3); } -.row-flag[aria-pressed="true"] { color: var(--signal-ink); background: var(--signal); } +.row-flag:hover { color: var(--ink); border-color: transparent; background: var(--surface-3); } +.row-flag[aria-pressed="true"] { color: var(--panel); background: var(--ink); } /* Badge / tag / status color tones -- shared by method, level, direction and provider badges */ -.badge-signal { color: var(--signal); background: var(--signal-soft); } +.badge-signal { color: var(--ink); background: var(--surface-2); } .badge-put { color: var(--put); background: var(--put-soft); } .badge-warn { color: var(--warn); background: var(--warn-soft); } .badge-error { color: var(--error); background: var(--error-soft); } .badge-muted { color: var(--muted); background: var(--surface-2); } .tone-text-ink { color: var(--ink); } -.tone-text-signal { color: var(--signal); } +.tone-text-signal { color: var(--ink); } .tone-text-put { color: var(--put); } .tone-text-warn { color: var(--warn); } .tone-text-error { color: var(--error); } .tone-text-muted { color: var(--muted); } -.tone-bg-signal { background: var(--signal); } +.tone-bg-signal { background: var(--ink); } .tone-bg-put { background: var(--put); } .tone-bg-warn { background: var(--warn); } .tone-bg-error { background: var(--error); } @@ -876,8 +911,8 @@ body.detail-zoom .split-shell.collapse-detail { grid-template-columns: 1fr; } border: none; border-bottom: 1px solid var(--line); background: transparent; color: var(--ink); font: inherit; } .trace-row:hover { background: var(--surface-2); } -.trace-row.selected { background: var(--signal-soft); } -.trace-row.selected::before { content: ""; position: absolute; left: 0; top: 0; bottom: 0; width: 2px; background: var(--signal); } +.trace-row.selected { background: var(--surface-2); } +.trace-row.selected::before { content: ""; position: absolute; left: 0; top: 0; bottom: 0; width: 2px; background: var(--ink); } .trace-time { display: grid; gap: 2px; justify-items: end; } .trace-t { font-family: var(--font-mono); font-size: 11.5px; font-variant-numeric: tabular-nums; color: var(--muted); } .trace-gap { font-family: var(--font-mono); font-size: 10.5px; color: var(--text-3); } @@ -906,13 +941,13 @@ body.detail-zoom .split-shell.collapse-detail { grid-template-columns: 1fr; } .detail-head-title { font-family: var(--font-mono); font-size: 13px; font-weight: 600; flex: 1; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .detail-head-status { font-family: var(--font-mono); font-size: 13px; font-weight: 700; } .detail-expand { display: grid; place-items: center; width: 26px; height: 26px; padding: 0; flex: 0 0 auto; border: 1px solid var(--line); border-radius: 8px; background: var(--surface-2); color: var(--muted); } -.detail-expand.active { border-color: var(--signal); background: var(--signal-soft); color: var(--signal); } +.detail-expand.active { border-color: var(--ink); background: var(--surface-2); color: var(--ink); } /* Kebab (⋮) actions menu, sitting immediately right of .detail-expand — same 26px footprint, so the head row's right edge reads as one pair of controls rather than two sizes. */ .detail-menu-btn { display: grid; place-items: center; width: 26px; height: 26px; padding: 0; flex: 0 0 auto; border: 1px solid var(--line); border-radius: 8px; background: var(--surface-2); color: var(--muted); } .detail-menu-btn:hover { color: var(--ink); border-color: var(--border-strong); } -.detail-menu-btn.active { border-color: var(--signal); background: var(--signal-soft); color: var(--signal); } +.detail-menu-btn.active { border-color: var(--ink); background: var(--surface-2); color: var(--ink); } /* position: fixed, not absolute: .detail-pane-v2 is overflow: hidden, so an absolutely positioned popup would be clipped at the pane's edge. Placed by positionDetailMenuPanel(), same contract as the toolbar dropdowns' .drop-panel. */ @@ -928,8 +963,8 @@ body.detail-zoom .split-shell.collapse-detail { grid-template-columns: 1fr; } .detail-menu-item .ic { flex: 0 0 auto; color: var(--text-3); } .detail-menu-item:hover:not(:disabled) { background: var(--surface-2); color: var(--ink); } .detail-menu-item:hover:not(:disabled) .ic { color: inherit; } -.detail-menu-item.on { color: var(--signal); background: var(--signal-soft); } -.detail-menu-item.on .ic { color: var(--signal); } +.detail-menu-item.on { color: var(--ink); background: var(--surface-2); } +.detail-menu-item.on .ic { color: var(--ink); } .detail-menu-item:disabled { opacity: 0.5; cursor: not-allowed; } .detail-facts { display: flex; flex-wrap: wrap; gap: 16px; margin-top: 8px; } .detail-fact { display: flex; align-items: baseline; gap: 8px; font-size: 11.5px; } @@ -938,22 +973,22 @@ body.detail-zoom .split-shell.collapse-detail { grid-template-columns: 1fr; } /* Clickable fact (M2: "mock rule: " linking to the Mocks view) — same layout as a plain .detail-fact but as a button, so it needs its own background/border/padding reset. */ .detail-fact-link { background: transparent; border: none; padding: 0; border-radius: 4px; cursor: pointer; } -.detail-fact-link:hover .detail-fact-v { color: var(--signal); text-decoration: underline; } +.detail-fact-link:hover .detail-fact-v { color: var(--ink); text-decoration: underline; } /* Brief flash on a mock rule row when linked to from the Network detail pane's "mock rule: " fact — respects prefers-reduced-motion via the duration override below. */ -@keyframes dcRowFlash { from { background: var(--signal-soft); } to { background: transparent; } } +@keyframes dcRowFlash { from { background: var(--surface-2); } to { background: transparent; } } .row-flash { animation: dcRowFlash 900ms ease; } .detail-actions-row { display: flex; gap: 8px; margin-top: 12px; flex-wrap: wrap; } .detail-action-btn { display: flex; align-items: center; gap: 8px; height: 26px; padding: 0 8px; border: 1px solid var(--line); border-radius: 8px; font-size: 11.5px; color: var(--ink); background: var(--surface-2); } -.detail-action-btn.on { color: var(--signal); border-color: var(--signal); background: var(--signal-soft); } +.detail-action-btn.on { color: var(--ink); border-color: var(--ink); background: var(--surface-2); } .detail-action-btn:disabled { opacity: 0.5; cursor: not-allowed; } .detail-tabs { display: flex; align-items: center; gap: 2px; margin-top: 12px; flex-wrap: wrap; } .detail-tab { position: relative; padding: 0 12px; height: 32px; font-size: 12.5px; font-weight: 500; color: var(--muted); background: transparent; border: none; border-bottom: 2px solid transparent; border-radius: 0; } -.detail-tab.active { font-weight: 600; color: var(--ink); border-color: var(--signal); } +.detail-tab.active { font-weight: 600; color: var(--ink); border-color: var(--ink); } .detail-tab-count { margin-left: 8px; font-family: var(--font-mono); font-size: 10.5px; color: var(--text-3); } .detail-layout-toggle { display: flex; align-items: center; gap: 8px; height: 26px; padding: 0 10px; margin-bottom: 4px; margin-left: auto; border: 1px solid var(--line); border-radius: 8px; font-size: 11.5px; color: var(--muted); background: var(--surface-2); } -.detail-layout-toggle.on { border-color: var(--signal); background: var(--signal-soft); color: var(--signal); } +.detail-layout-toggle.on { border-color: var(--ink); background: var(--surface-2); color: var(--ink); } /* ---- Find-in-detail bar ---- */ .detail-find { display: flex; align-items: center; gap: 8px; padding: 8px 16px; border-bottom: 1px solid var(--line); background: var(--surface-2); } @@ -999,10 +1034,10 @@ body.detail-zoom .split-shell.collapse-detail { grid-template-columns: 1fr; } .kv-grid.kv-grid-lg .kv-v { padding: 8px 12px; font-size: 11.5px; background: var(--panel); word-break: break-all; } /* Find-highlight must win over both grid sizes' background overrides above — same (0,3,0) specificity as `.kv-grid.kv-grid-lg .kv-v` but declared after it, so source order decides. */ -.kv-grid .kv-k.hit, .kv-grid .kv-v.hit { background: var(--signal-soft); } +.kv-grid .kv-k.hit, .kv-grid .kv-v.hit { background: var(--surface-2); } /* Clickable kv value (Network summary's "mock rule: " → Mocks). A '; + container.querySelector('button').onclick = retry; + } + async function runViewLoader(view, loader) { + if (!hasSession()) return; + viewLoadedAt.delete(view); + const revision = viewRevision.get(view) || 0; + const generation = cacheGeneration; + const container = $(viewContainers[view]); + if (container?.querySelector('.empty-connect, .load-status')) { + container.innerHTML = '
Loading…
'; + } + const pending = (async () => { + try { + const result = await loader(); + if (result !== false && hasSession() && generation === cacheGeneration && revision === (viewRevision.get(view) || 0)) viewLoadedAt.set(view, Date.now()); + return result; + } catch (error) { + viewLoadedAt.delete(view); + if (container && hasSession() && generation === cacheGeneration) renderLoadFailure(container, 'Could not load this view', error.status || 0, () => runViewLoader(view, loader)); + return false; + } finally { + if (viewPending.get(view) === pending) viewPending.delete(view); + } + })(); + viewPending.set(view, pending); + return pending; + } + function requireLoad(response) { + if (!response.ok) throw Object.assign(new Error(unavailableReason(response.status)), { status: response.status }); + } let openAccess = false; let currentView = 'overview'; + let sessionRetryTimer = 0; let csrf = ''; let paused = true; let events = []; @@ -96,7 +252,10 @@ const networkSelectedIds = new Set(); let networkShowHost = true; let networkPinnedId = ''; - let networkTab = 'compare'; + let networkTab = 'response'; + let networkFullEndpoint = false; + let networkListController = null; + try { networkFullEndpoint = localStorage.getItem('devconsole.network.fullEndpoint') === 'true'; } catch { /* storage unavailable */ } let networkDetailQuery = ''; let networkSbsStacked = false; // Open state of the detail pane's kebab (⋮) actions menu. Module-level, not DOM state, because @@ -241,6 +400,9 @@ const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); const icon = (name, cls) => ``; + /** Two-layer empty-state illustration (see the dc-spot-* symbols): muted lines plus one signal accent. */ + const spot = (name) => + ``; const hasSession = () => Boolean(token); // Wrapped once, globally, instead of at each of this file's ~100 fetch call sites: a stray 401 on // an authenticated request can just be a request racing a fresh reconnect, but several in a row @@ -288,7 +450,7 @@ const SEVERITY_SHORT = ['DBG', 'INF', 'WRN', 'ERR']; function renderEmpty(container, iconName, title, sub) { - container.innerHTML = `
${icon(iconName, 'empty-icon')}
${esc( + container.innerHTML = `
${/ selected$/.test(title) ? spot('select') : icon(iconName, 'empty-icon')}
${esc( title, )}
${sub ? `
${esc(sub)}
` : ''}
`; } @@ -327,8 +489,7 @@ if (!status) return 'error'; if (status >= 500) return 'error'; if (status >= 400) return 'warn'; - if (status >= 300) return 'put'; - return 'signal'; + return 'ink'; } function levelTone(shortName) { if (shortName === 'ERR') return 'error'; @@ -353,7 +514,7 @@ * text is prose (a log summary, a crash reason), which `word-break: break-all` would chop * mid-word. Both are opt-in, so those lists keep the single-line row they always had. */ function rowHtml(opts) { - const { id, selected, badgeText, badgeTone, mainText, mainSub, mainRtl, tagText, tagTone, duration, statusText, sTone, flagKind, flagLabel, checkbox, checked, posinset, setsize, stackMetrics, wrapMain } = opts; + const { id, selected, badgeText, badgeTone, mainText, mainSub, mainRtl, tagText, tagTone, duration, statusText, sTone, flagKind, flagLabel, checkbox, checked, posinset, setsize, stackMetrics, wrapMain, metricsInline, mainPrefix } = opts; const flagId = opts.flagId ?? id; // selection id and evidence id may differ (socket frames) const flagged = flagKind ? isFlagged(flagKind, flagId) : false; // aria-posinset/aria-setsize: with the list virtualized, only a window of `role="option"` @@ -369,11 +530,13 @@ } ${esc(badgeText)} - ${esc(mainText)}${mainSub ? `${esc(mainSub)}` : ''} + ${mainPrefix ? `${esc(mainPrefix)}` : ''}${esc(mainText)}${mainSub ? `${esc(mainSub)}` : ''} ${tagText ? `${esc(tagText)}` : ''} ${ - stackMetrics + metricsInline + ? `${esc(statusText ?? '—')} · ${esc(duration ?? '—')}` + : stackMetrics ? ` ${esc(statusText ?? '')} ${esc(duration ?? '')} @@ -617,9 +780,9 @@ const anchorDelta = el.scrollTop - ensureOffsets()[anchorIndex]; const focusSnap = captureFocus(el); const offs = ensureOffsets(); - let html = start > 0 ? `
` : ''; + let html = start > 0 ? `` : ''; for (let i = start; i < end; i++) html += renderRow(i, count); - if (end < count) html += `
`; + if (end < count) html += ``; el.innerHTML = html; restoreFocus(focusSnap, el); // Roving tabindex meets virtualization: the selected row is normally the list's only tab @@ -846,9 +1009,9 @@ return `
${bars .map( (b) => - `
${esc(b.label)}${esc(b.label)}${esc(b.val)}
`, + }">${esc(b.val)}
`, ) .join('')}
`; } @@ -906,7 +1069,7 @@ function cardStackHtml(segs) { if (!segs || !segs.length) return ''; return `
${segs - .map((s) => ``) + .map((s) => ``) .join('')}
${segs .map((s) => `${esc(s.label)}${esc(s.val)}`) .join('')}
`; @@ -929,9 +1092,8 @@ } function cardMetricsHtml(metrics) { if (!metrics || !metrics.length) return ''; - return `
${metrics - .map((m) => `
${esc(m.label)}
${esc(m.val)}
`) - .join('')}
`; + // Tiles are banned by design (.card-metrics is display:none), so the numbers render as flat rows. + return cardRowsHtml(metrics.map((m) => ({ k: m.label, v: m.val + (m.sub ? ' ' + m.sub : ''), tone: m.tone || 'ink' }))); } /** `radioLabel` switches this from a set of independent `role="switch"` toggles (mocks rules, * state flags — any combination may be on) into a single-choice `role="radiogroup"` of @@ -987,14 +1149,12 @@ } function cardTreeHtml(nodes, treeMax) { if (!nodes || !nodes.length) return ''; - return `
${nodes + return `
${nodes .map( (n) => ``, ) @@ -1011,14 +1171,21 @@ ) .join('')}
`; } + function foldHtml(label, content, count = '', open = false) { + return '
' + + icon('chevron', 'ic-sm fold-chevron') + esc(label) + + (count ? '' + esc(count) + '' : '') + + '
' + content + '
'; + } function cardHtml(c) { + if (c.bodyFold) return foldHtml(c.bodyFold, c.bodyHtml || esc(c.emptyText || ''), c.foldCount); return `
1 ? ` data-span="${c.span}"` : ''}>
${c.icon ? icon(c.icon, `tone-text-${c.iconTone || 'signal'}`) : ''}

${esc( c.title, )}

${c.badge ? `${esc(c.badge)}` : ''}
- ${c.lede ? `

${esc(c.lede)}

` : ''} - ${c.fieldsHtml || ''} + ${c.lede ? (c.ledeFold ? foldHtml(c.ledeFold, `

${esc(c.lede)}

`) : `

${esc(c.lede)}

`) : ''} + ${c.editFold ? '' : (c.fieldsHtml || '')} ${cardStackHtml(c.stack)} ${cardRowsHtml(c.rows)} ${cardMetricsHtml(c.metrics)} @@ -1028,7 +1195,7 @@ ${cardFindingsHtml(c.findings)} ${cardTreeHtml(c.tree, c.treeMax)} ${c.bodyHtml || ''} - ${cardButtonsHtml(c.buttons)} + ${c.editFold ? foldHtml(c.editFold, (c.fieldsHtml || '') + cardButtonsHtml((c.buttons || []).filter((b) => b.id !== 'download'))) + cardButtonsHtml((c.buttons || []).filter((b) => b.id === 'download')) : cardButtonsHtml(c.buttons)}
`; } @@ -1226,7 +1393,7 @@ const body = $('railAdvancedBody'); const group = $('railGroupAdvanced'); const data = $('railGroupData'); - if (!body || !group) return; + if (!body || !group || group.hidden) return; if (uiMode === 'simple') { RAIL_ADVANCED_IDS.forEach((id) => { const btn = $(id); if (btn && btn.parentElement !== body) body.appendChild(btn); }); group.hidden = false; @@ -1302,6 +1469,7 @@ /** Persisted independently of the mode itself — collapsed by default, but once a user opens it * (or navigation auto-expands it, see `show()`) it stays open across reloads. */ function setRailAdvancedOpen(open) { + if (!$('railGroupAdvanced') || $('railGroupAdvanced').hidden) return; railAdvancedOpen = open; const bodyEl = $('railAdvancedBody'); if (bodyEl) bodyEl.hidden = !open; @@ -1317,19 +1485,14 @@ const btn = $('modeToggle'); if (!btn) return; const advanced = uiMode === 'advanced'; - btn.innerHTML = icon(advanced ? 'collapse' : 'expand'); + btn.querySelector('.ic').outerHTML = icon(advanced ? 'collapse' : 'expand'); btn.setAttribute('aria-pressed', String(advanced)); btn.title = (advanced ? 'Advanced mode on — showing every view (a)' : 'Advanced mode off — Simple view (a)'); } - /** The Diff tab is allowed to stay in Simple mode (it needs a baseline the user pinned via the - * `b` shortcut, which keeps working in both modes); Headers/Timing/Related do not survive a - * switch to Simple, so land back on the always-visible Request & response tab rather than - * leaving the detail pane rendering a tab with no visible way to reach it. */ + /** Normalize legacy tab names; both UI modes expose the same Network inspector tabs. */ function normalizeNetworkTabForMode() { - if (uiMode === 'simple' && !['compare', 'summary', 'diff'].includes(networkTab)) { - networkTab = 'compare'; - if (currentView === 'network' && selectedTransactionDetail) renderNetworkDetail(); - } + if (networkTab === 'compare') networkTab = 'response'; + if (networkTab === 'summary') networkTab = 'timing'; } function applyUiMode() { document.body.classList.toggle('mode-simple', uiMode === 'simple'); @@ -2326,7 +2489,7 @@ * counterpart (see `renderNetworkDetail`'s `mockDiffSig`) — required whenever `diffInfo` is set, * so the tree-reuse cache below can tell "same diff as last render" apart from "different rule * or snapshot, must rebuild". */ - function bodyViewerHtml(raw, contentType, codeLines, title, large, groupKey, diffInfo, diffSig) { + function bodyViewerHtml(raw, contentType, codeLines, title, large, groupKey, diffInfo, diffSig, lineView = false) { const rawBlock = codeLines && codeLines.length ? codeBlockHtml(codeLines, Boolean(large), title) : `${raw ? esc(raw) : '(empty body)'}`; @@ -2351,16 +2514,15 @@ return `
- - + ${lineView ? '\n ' : '\n '}
-
- +
+
${rawBlock}
`; } @@ -2423,6 +2585,13 @@ const applyCollapseClass = () => { shell.classList.toggle('collapse-list', collapsed === 'list'); shell.classList.toggle('collapse-detail', collapsed === 'detail'); + if (viewKey === 'network') { + shell.classList.toggle('list-collapsed', collapsed === 'list'); + shell.classList.remove('list-overlay-open'); + try { localStorage.setItem('devconsole.network.listCollapsed', String(collapsed === 'list')); } catch { /* storage unavailable */ } + syncNetworkListToggle(); + requestAnimationFrame(() => virtualLists.get('transactions')?.remeasure()); + } }; const restoreFallback = () => (lastWidth != null ? lastWidth : Math.round((MIN_WIDTH + maxWidth()) / 2)); @@ -2470,6 +2639,19 @@ // ---- Restore persisted width/collapse state before this splitter's first paint. ---- const saved = readSaved(); + // Read the dedicated preference before applyCollapseClass persists any state. + let networkSavedCollapse = false; + if (viewKey === 'network') { + try { networkSavedCollapse = localStorage.getItem('devconsole.network.listCollapsed') === 'true'; } catch { /* storage unavailable */ } + listPane.id = 'networkListPane'; + networkListController = { + toggle() { + if (collapsed !== 'list') { collapse('list'); persist(); $('networkListToggle')?.focus(); return; } + setNetworkListOverlay(!shell.classList.contains('list-overlay-open')); + }, + close: () => setNetworkListOverlay(false), + }; + } if (saved && (saved.collapsed === 'list' || saved.collapsed === 'detail')) { lastWidth = typeof saved.width === 'number' ? saved.width : null; if (lastWidth != null) shell.style.setProperty('--list-w', Math.max(MIN_WIDTH, Math.min(lastWidth, maxWidth())) + 'px'); @@ -2478,6 +2660,7 @@ } else if (saved && typeof saved.width === 'number') { setWidth(saved.width); } + if (viewKey === 'network' && networkSavedCollapse) collapse('list'); syncAria(); let startX = 0; @@ -2663,7 +2846,7 @@ $('timelineBookmarkOnly').setAttribute('aria-pressed', String(timelineBookmarkedOnly)); } - const TIMELINE_EMPTY_HTML = '
' + icon('activity', 'ic-lg') + '
No events match
Clear a filter to see the other captured events.
'; + const TIMELINE_EMPTY_HTML = '
' + spot('search') + '
No events match
Clear a filter to see the other captured events.
'; const render = () => { const q = $('search').value.toLowerCase(); const rows = events.filter( @@ -2723,7 +2906,7 @@ events.forEach((e) => { counts[e.pluginId] = (counts[e.pluginId] || 0) + 1; }); $('timelineSourceSeg').innerHTML = `` + - sources.map((s) => ``).join(''); + sources.map((s) => ``).join(''); } const refreshSources = renderTimelineSourceSeg; @@ -2885,8 +3068,8 @@ ${screenshotHtml} ${kvGridHtml(kvs, true)} ${stackTraceHtml} - -
+
${icon('chevron', 'ic-sm fold-chevron')}Add note
+
`; restoreFocus(focusSnap, pane); // toggle-zoom is handled by the delegated listener wired once in wireEvents (`$('eventDetail') @@ -3022,6 +3205,15 @@ } function updateRecordButton() { + const toggle = $('liveToggle'); + if (toggle) { + toggle.hidden = !token || sessionExpired; + toggle.classList.toggle('is-paused', paused); + toggle.setAttribute('aria-pressed', String(!paused)); + toggle.setAttribute('aria-label', paused ? 'Resume live events' : 'Pause live events'); + $('liveToggleLabel').textContent = paused ? 'Paused' : 'Live'; + document.querySelector('.session-pill').hidden = !toggle.hidden; + } const live = $('streamLive'); const stopped = $('streamPaused'); if (!live || !stopped) return; @@ -3048,7 +3240,7 @@ } flushLiveTailRefreshes(); } - $('status').textContent = paused ? 'LIVE / PAUSED' : 'LIVE / TAILING'; + $('status').textContent = paused ? 'Paused' : 'Live'; } function noteSequenceSeen(seq) { @@ -3070,7 +3262,10 @@ clearTimeout(streamRetry); const scheme = location.protocol === 'https:' ? 'wss:' : 'ws:'; stream = new WebSocket(`${scheme}//${location.host}/api/v1/stream`); - stream.onopen = () => stream.send('{"type":"client.hello","protocolVersion":1}'); + stream.onopen = () => { + invalidateSessionCache(); + stream.send('{"type":"client.hello","protocolVersion":1}'); + }; stream.onmessage = (message) => { let value; try { @@ -3081,7 +3276,7 @@ if (value.type === 'server.welcome') { $('lamp').classList.remove('expired'); $('lamp').classList.add('live'); - $('status').textContent = paused ? 'LIVE / PAUSED' : 'LIVE / TAILING'; + $('status').textContent = paused ? 'Paused' : 'Live'; // lastKnownSequence starts at -1, so this only fires on a genuine reconnect (one that // already saw at least one sequence number before now) -- a fresh first connect has // nothing to backfill and every view loads its own initial data anyway. @@ -3091,6 +3286,15 @@ return; } if (value.type !== 'event.appended' || !value.event) return; + // Responses started before an event cannot mark affected views fresh. + const affected = new Set(['overview', 'timeline', 'sdkHealth', 'session']); + const pluginView = { websocket: 'socket', crash: 'crashes', preferences: 'preferences', + database: 'database', files: 'files', remoteconfig: 'remoteConfig', 'remote-config': 'remoteConfig' }; + affected.add(pluginView[value.event.pluginId] || value.event.pluginId); + affected.forEach((view) => { + viewLoadedAt.delete(view); + viewRevision.set(view, (viewRevision.get(view) || 0) + 1); + }); noteSequenceSeen(value.event.sequence); if (paused) { const queued = new Map(pendingLiveEvents.map((e) => [e.id, e])); @@ -3147,6 +3351,7 @@ clearTimeout(streamRetry); openAccess = false; token = ''; + invalidateSessionCache(); csrf = ''; stream?.close(); stream = null; @@ -3165,11 +3370,15 @@ const TIMELINE_FETCH_LIMIT = 500; let timelineLoadingMore = false; async function load(cursor = null) { + if (!hasSession()) return loadImpl(cursor); + return runViewLoader('timeline', () => loadImpl(cursor)); + } + async function loadImpl(cursor = null) { if (!token) return; const params = new URLSearchParams({ limit: String(TIMELINE_FETCH_LIMIT), sort: 'DESC' }); if (cursor) params.set('cursor', cursor); const r = await fetch('/api/v1/events?' + params, { headers: auth() }); - if (!r.ok) return; + requireLoad(r); const body = await r.json(); events = (body.data || []) .map((raw) => ({ ...raw, wallTimeMs: raw.wallTimeMs ?? raw.timestampEpochMs ?? 0 })) @@ -3182,7 +3391,7 @@ refreshSources(); render(); setNavCount('navCountTimeline', events.length); - $('status').textContent = paused ? 'LIVE / PAUSED' : 'LIVE / TAILING'; + $('status').textContent = paused ? 'Paused' : 'Live'; // Best-effort priming so a log/crash event's message + stack trace (see // ensureEventPayloadsLoaded above) is usually already cached by the time something is // clicked; renderEventDetail() re-renders itself once this resolves if it's still relevant. @@ -3228,6 +3437,10 @@ * Network/Timeline views' shared state) so it renders correctly whether or not those views have * been visited yet — same "each view loads its own data" convention every other view follows. */ async function loadOverview() { + if (!hasSession()) return loadOverviewImpl(); + return runViewLoader('overview', () => loadOverviewImpl()); + } + async function loadOverviewImpl() { $('overviewBadge').textContent = hasSession() ? 'connected' : 'not connected'; if (!hasSession()) { $('overviewMetrics').innerHTML = ''; @@ -3235,17 +3448,18 @@ $('overviewCrashBanner').hidden = true; return; } - const [overviewRes, metaRes, networkRes, eventsRes, runsRes] = await Promise.all([ + const [overviewRes, metaRes, networkRes, eventsRes, runsRes, crashesRes] = await Promise.all([ fetch('/api/v1/overview', { headers: auth() }), - fetch('/api/v1/meta', { headers: auth() }), + cachedJson('/api/v1/meta', 30000), fetch('/api/v1/network/transactions?limit=100', { headers: auth() }), fetch('/api/v1/events?limit=6&sort=DESC', { headers: auth() }), // The "previous-run-crashed banner": GET /api/v1/runs reports every // retained run's StoredSessionStatus, sorted newest-first by the server. The most recent // *non-active* run is the "previous run". - fetch('/api/v1/runs', { headers: auth() }), + cachedJson('/api/v1/runs', 30000), + fetch('/api/v1/retained-events?pluginId=crash&limit=500', { headers: auth() }), ]); - if (!overviewRes.ok) return; + requireLoad(overviewRes); const meta = metaRes.ok ? await metaRes.json() : {}; // Fail-open when captureCategories is missing (older SDK) or malformed -- see // applyCaptureCategoryGating's own null-means-unknown handling. @@ -3254,7 +3468,8 @@ const eventSample = eventsRes.ok ? (await eventsRes.json()).data || [] : []; const runs = runsRes.ok ? (await runsRes.json()).data || [] : []; const previousRun = runs.find((run) => run.status !== 'ACTIVE') || null; - renderOverview(await overviewRes.json(), meta, netSample, eventSample, previousRun); + const crashSample = crashesRes.ok ? ((await crashesRes.json()).data || []).map(decorateCrashRow) : []; + renderOverview(await overviewRes.json(), meta, netSample, eventSample, previousRun, crashSample); } /** Keeps the session-pill's visible label and its hover tooltip (the full text, for when the * pill has ellipsised at a narrow width — see the topbar breakpoint ladder in dashboard.css) in @@ -3266,14 +3481,20 @@ el.title = title || text; } function activateBrowserAccess(accessToken, csrfToken, source, isOpen = false) { + invalidateSessionCache(); openAccess = isOpen; token = isOpen ? 'open' : accessToken; csrf = isOpen ? '' : csrfToken; sessionExpired = false; consecutiveAuthFailures = 0; + Object.values(viewContainers).forEach((id) => { + const container = $(id); + if (container && (id === 'overviewCards' || container.querySelector('.empty-connect'))) container.innerHTML = '
Select this view to load captures.
'; + }); if (source !== 'manual') history.replaceState(null, '', location.pathname); - setStatus(isOpen ? 'Connected (open)' : 'Connected'); + setStatus('Live', isOpen ? 'Connected (open)' : 'Connected'); toast(isOpen ? 'Connected to DevConsole.' : 'Connected to DevConsole session.'); + if ($('composerResult').querySelector('.empty-connect')) $('composerResult').innerHTML = '
Execute a request to see its response.
'; updateControlUi(); connectStream(); // `paused` starts true because there is nothing to tail before a session exists. Connecting is @@ -3334,57 +3555,51 @@ }${esc(time(when))}${previousRun.deviceModel ? ' · ' + esc(previousRun.deviceModel) : ''}. Open Crashes for the breadcrumb trail and full dump.
VIEW`; $('overviewCrashBannerBtn').onclick = () => focusCrashesOnRun(previousRun.id); } - function renderOverview(body, meta, netSample, eventSample, previousRun) { - renderOverviewCrashBanner(previousRun); - if (!body) { - cardsGridHtml('overviewCards', [ - { - icon: 'lock', iconTone: 'warn', title: 'Connect this browser', span: 2, - // fieldsHtml (unlike `lede`) is inserted raw, not HTML-escaped — the only field on this - // card that can carry / markup (device path, the - // adb forward command, and the #code= credential note) ahead of the actual connect - // input, since cardHtml() always renders fieldsHtml before its own buttons/lede order - // isn't ours to change (it's shared by every card-grid view, not scoped to Overview). - fieldsHtml: ` -

This server requires a browser session. On the device, open DevConsole → More — it shows the connect QR and an 8-character, single-use code that expires after five minutes. Scan the QR, or paste the code below.

-
    -
  • The #code= fragment in that link is the credential because this server is using SESSION_CODE; a bare http://host:port/ address is not enough.
  • -
  • Emulator or firewalled device? Forward the port first: adb forward tcp:8080 tcp:8080 — 8080 is only the first port tried; the server takes the next free one up to 8099, so confirm the exact address on the device's More screen.
  • -
  • Logcat deliberately never prints the code — read it from the device screen, not the log.
  • -
-
`, - buttons: [{ id: 'connect', label: 'Connect', icon: 'plug', kind: 'primary' }], - }, - ]); - wireCardGrid('overviewCards', { onButton: (id) => { if (id === 'connect') exchangeSessionCode($('connectCode').value.trim(), 'manual'); } }); - return; - } + function overviewNetworkRow(t) { + return ``; + } + function renderOverview(body, meta, netSample, eventSample, previousRun, crashSample = []) { + $('overviewCrashBanner').hidden = true; + $('overviewMetrics').innerHTML = ''; + $('overviewCards').classList.remove('cards-grid'); + const latest = netSample.slice().sort((a, b) => (b.startedAtEpochMs || 0) - (a.startedAtEpochMs || 0)); const durations = netSample.map((t) => t.durationMs).filter((d) => d != null).sort((a, b) => a - b); const p95 = percentile(durations, 0.95); - const failCount = netSample.filter(failing).length; - $('overviewMetrics').innerHTML = metricsStripHtml([ - { label: 'Requests', val: String(netSample.length), sub: 'sample', tone: 'ink' }, - { label: 'Failing', val: String(failCount), sub: netSample.length ? Math.round((failCount / netSample.length) * 100) + '%' : '', tone: 'error' }, - { label: 'p95', val: p95 != null ? (p95 / 1000).toFixed(2) : '—', sub: p95 != null ? 's' : '', tone: 'warn' }, - { label: 'Flagged', val: String(evidenceFlags.size), sub: 'as evidence', tone: 'signal' }, - ]); - cardsGridHtml('overviewCards', [ - overviewNeedsAttentionCard(netSample, failCount), - overviewTrafficHealthCard(netSample, durations, p95, failCount), - overviewServerCard(body, meta), - overviewSignalsCard(eventSample), - overviewHealthCard(body.sdkHealth), - ]); - wireCardGrid('overviewCards', { - onButton: (id) => { - if (id === 'open-failures') { networkFailOnly = true; show('network'); loadNetwork(); } - else if (id === 'flag-all') { - netSample.filter(failing).forEach((t) => { if (!isFlagged('network', t.id)) toggleEvidenceFlag('network', t.id, t.method + ' ' + t.path); }); - toast(failCount + ' capture' + (failCount === 1 ? '' : 's') + ' flagged as evidence'); - loadOverview(); - } - }, - }); + const requestCount = body ? Object.values(body.networkStatusDistribution || {}).reduce((sum, count) => sum + Number(count), 0) : 0; + $('overviewSubtitle').textContent = body + ? (requestCount || netSample.length) + ' requests in this session' + (p95 != null ? ' · p95 ' + p95 + ' ms' : '') + : 'Connect this browser to see session activity.'; + const failures = latest.filter(failing).map((t) => ({ time: t.startedAtEpochMs || 0, html: overviewNetworkRow(t) })); + const crashes = crashSample.map((e) => ({ time: e.wallTimeMs || 0, html: `` })); + const attention = failures.concat(crashes).sort((a, b) => b.time - a.time).slice(0, 5); + const connect = body ? '' : `
`; + $('overviewCards').innerHTML = `${connect} +

Needs attention

${attention.length ? attention.map((r) => r.html).join('') : '
Nothing needs attention
'}
+

Recent activity

${latest.length ? latest.slice(0, 6).map(overviewNetworkRow).join('') : '
No requests captured yet
'}
`; + const form = $('overviewConnect'); + if (form) form.onsubmit = (event) => { event.preventDefault(); exchangeSessionCode($('connectCode').value.trim(), 'manual'); }; + $('overviewCards').onclick = async (event) => { + const networkRow = event.target.closest('[data-overview-network]'); + if (networkRow) { + await show('network'); + const id = networkRow.dataset.overviewNetwork; + // A prior search may exclude the Overview capture; keep this explicit selection reachable. + if (!transactions.some((t) => t.id === id)) transactions.unshift(latest.find((t) => t.id === id)); + await showTransaction(id); + return; + } + const crashRow = event.target.closest('[data-overview-crash]'); + if (crashRow) { + await show('crashes'); + selectedCrashId = crashRow.dataset.overviewCrash; + crashKindFilter = ''; + $('crashesSearch').value = ''; + renderCrashes(); + } + }; } function overviewNeedsAttentionCard(netSample, failCount) { const bad = netSample.filter(failing).slice(0, 8); @@ -3439,15 +3654,17 @@ }; } function overviewServerCard(body, meta) { - const endpoint = meta.endpoint; + const endpoint = meta?.endpoint; + const isLan = endpoint?.bindingMode === 'LAN'; + const isLoopback = endpoint?.bindingMode === 'LOOPBACK'; return { icon: 'grid', iconTone: 'signal', title: 'Server & app', rows: [ { k: 'Package', v: body.app?.packageName || '—', tone: 'ink' }, { k: 'Version', v: body.app?.versionName || '—', tone: 'ink' }, - { k: 'Bound to', v: endpoint ? endpoint.host + ':' + endpoint.port : location.host, tone: 'ink', tag: endpoint?.bindingMode === 'LAN' ? 'LAN' : false, tagTone: 'warn' }, - { k: 'Protocol', v: meta.protocolVersion ? 'devconsole/' + meta.protocolVersion : '—', tone: 'muted' }, - { k: 'Build', v: meta.build?.variant || '—', tone: 'muted' }, + { k: 'Bound to', v: endpoint ? endpoint.host + ':' + endpoint.port : '—', tone: 'ink', tag: isLan ? 'LAN' : (isLoopback ? 'LOOPBACK' : false), tagTone: isLan ? 'warn' : 'signal' }, + { k: 'Protocol', v: meta?.protocolVersion ? 'devconsole/' + meta.protocolVersion : '—', tone: 'muted' }, + { k: 'Build', v: meta?.build?.variant || '—', tone: 'muted' }, { k: 'Mocks', v: body.mocks?.enabled ? body.mocks.ruleCount + ' rule' + (body.mocks.ruleCount === 1 ? '' : 's') + ' active' : 'disabled', tone: body.mocks?.enabled ? 'put' : 'muted' }, body.sessionIntegrity ? { k: 'Session', v: body.sessionIntegrity.pristine ? 'pristine' : 'modified', tone: body.sessionIntegrity.pristine ? 'signal' : 'warn', tag: body.sessionIntegrity.pristine ? false : 'MODIFIED', tagTone: 'warn' } : false, ].filter(Boolean), @@ -3538,18 +3755,17 @@ .filter(([, value]) => value); } async function loadNetwork(cursor = null) { + if (!hasSession()) return loadNetworkImpl(cursor); + return runViewLoader('network', () => loadNetworkImpl(cursor)); + } + async function loadNetworkImpl(cursor = null) { if (!token) return; networkPagedIntoHistory = Boolean(cursor); const params = new URLSearchParams({ limit: String(NETWORK_FETCH_LIMIT) }); if (cursor) params.set('cursor', cursor); networkFilterEntries().forEach(([name, value]) => params.append(name, value)); const r = await fetch('/api/v1/network/transactions?' + params, { headers: auth() }); - if (!r.ok) { - // Never clobber the detail pane (a background live-tail refresh hitting a 429 would wipe - // the transaction the operator is reading, permanently). Surface on the transient channel. - toast(r.status === 429 ? 'Refresh rate-limited — retrying shortly.' : 'Network filter rejected: ' + r.status, 'error'); - return; - } + requireLoad(r); const body = await r.json(); networkPage = body.data || []; networkCursor = body.page?.nextCursor || null; @@ -3654,9 +3870,10 @@ } let networkOrder = []; - const NETWORK_EMPTY_HTML = '
' + icon('funnel', 'ic-lg') + '
No transactions match
Clear a filter or widen the status/method selection to see the other captures.
'; + const NETWORK_EMPTY_HTML = '
' + spot('search') + '
No transactions match
Clear a filter or widen the status/method selection to see the other captures.
'; function renderNetwork() { $('networkMainColLabel').textContent = 'Path'; + $('networkFullEndpoint').setAttribute('aria-pressed', String(networkFullEndpoint)); // Normalize the selection BEFORE painting, like the other four list views: rows gate tabindex // on `selected`, so painting with a stale id would leave zero tabbable rows until // showTransaction()'s async re-render -- or forever, if that detail fetch rejects. @@ -3671,15 +3888,16 @@ checkbox: true, checked: networkSelectedIds.has(t.id), badgeText: t.method, badgeTone: methodTone(t.method), mainText: t.path, + mainPrefix: networkFullEndpoint ? t.host : '', // The query is what separates two rows on the same endpoint, so it belongs in the row -- // dimmed and after the path, which stays the part that survives the ellipsis. mainSub: t.query ? '?' + t.query : '', // Single row-tag slot: a pinned diff baseline always wins over the mocked marker. - tagText: networkPinnedId === t.id ? 'BASE' : t.tags?.mocked === 'true' ? 'MOCK' : false, + tagText: false, tagTone: 'put', duration: t.durationMs != null ? t.durationMs + ' ms' : t.error ? 'failed' : '—', - statusText: t.status != null ? String(t.status) : t.error ? 'ERR' : '—', sTone: statusTone(t.status), - stackMetrics: true, wrapMain: true, + statusText: t.status != null ? String(t.status) : t.error ? 'ERR' : '—', sTone: t.status != null ? statusTone(t.status) : t.error ? 'error' : 'muted', + metricsInline: true, flagKind: 'network', flagLabel: t.method + ' ' + t.path, posinset: i + 1, setsize: total, }); @@ -3697,7 +3915,7 @@ renderNetworkSelectionBar(); if (networkSelectionStale) { if (transactions.length) showTransaction(selectedTransactionId); - else renderEmpty($('networkDetailPane'), 'network', 'No transaction selected', 'Select a transaction from the list to inspect its redacted metadata.'); + else renderNetworkEmpty(); } } @@ -3865,8 +4083,8 @@ const on = selected.has(it.value); return ``; }) @@ -3933,7 +4151,7 @@ // WebSockets // ================================================================ function listEmptyHtml(iconName, title, sub) { - return `
${icon(iconName, 'ic-lg')}
${esc(title)}
${esc(sub)}
`; + return `
${spot('search')}
${esc(title)}
${esc(sub)}
`; } function shortSocketUrl(url) { return (url || '').replace(/^wss?:\/\/[^/]+/, '') || '/'; @@ -3972,20 +4190,28 @@ }); async function loadSockets() { + if (!hasSession()) return loadSocketsImpl(); + return runViewLoader('socket', () => loadSocketsImpl()); + } + async function loadSocketsImpl() { if (!token) return; const connParams = new URLSearchParams(); if (socketProtocolFilter !== 'all') connParams.append('protocol', socketProtocolFilter); const r = await fetch('/api/v1/websockets/connections?' + connParams, { headers: auth() }); - if (!r.ok) return; + requireLoad(r); socketConnections = (await r.json()).data || []; [...socketSelectedConnIds].forEach((id) => { if (!socketConnections.some((s) => s.id === id)) socketSelectedConnIds.delete(id); }); setNavCount('navCountSockets', socketConnections.length); - await loadSocketMessages(); + return await loadSocketMessages(); } /** Broad fetch respecting every server-side filter (connections, frame type, direction, search, * time, error) — List/Timeline mode is purely a client-side presentation choice on top. */ async function loadSocketMessages() { + if (!hasSession()) return; + return runViewLoader('socket', loadSocketMessagesImpl); + } + async function loadSocketMessagesImpl() { if (!token) return; const params = new URLSearchParams(); socketSelectedConnIds.forEach((id) => params.append('connectionId', id)); @@ -3997,7 +4223,11 @@ if (value) params.append(name, value); }); const r = await fetch('/api/v1/websockets/messages?' + params, { headers: auth() }); - if (!r.ok) { renderEmpty($('socketMessages'), 'alert', 'Invalid WebSocket filter combination.'); return; } + if (!r.ok) { + renderLoadFailure($('sockets'), 'Could not load messages', r.status, loadSocketMessages); + viewLoadedAt.delete('socket'); + return false; + } socketMessages_ = formatSocketMessages((await r.json()).data || []); if (socketSelectedIndex >= socketMessages_.length) socketSelectedIndex = -1; renderSockets(); @@ -4008,7 +4238,7 @@ function renderSockets() { const timelineMode = socketMode === 'timeline'; $('socketListHead').innerHTML = timelineMode - ? 'TimeFrame · payload size' + ? 'TimeFrame · payload size' : 'DirPayload previewSizeTime'; // Normalize the selection before painting (not after) so a stale/dropped selectedIndex never // leaves every row tabindex=-1 for a frame — both sub-modes below read socketSelectedIndex. @@ -4037,7 +4267,7 @@ ${time(m.timestampEpochMs)}${prev ? '+' + (gapMs < 1000 ? gapMs + 'ms' : (gapMs / 1000).toFixed(2) + 's') : 'start'} ${icon(rec ? 'arrow-down' : 'arrow-up')} - ${esc(m.direction)}${esc(protoPrefix + framePreviewText(m))}${esc(frameSizeLabel(m))} + ${esc(m.direction)}${esc(protoPrefix + framePreviewText(m))}${esc(frameSizeLabel(m))} `; }, SOCKETS_EMPTY_HTML, @@ -4055,7 +4285,8 @@ // when more than one connection is in scope), rather than reusing dashboard.css for a // second badge slot this row layout doesn't have. const protoTag = conn?.protocol === 'mqtt' ? 'MQTT' : null; - const scopeTag = socketSelectedConnIds.size === 1 ? (m.frameType === 'BINARY' ? 'BIN' : null) : conn ? shortSocketUrl(conn.url) : null; + // The connection URL only tells rows apart when more than one connection is in view. + const scopeTag = socketSelectedConnIds.size === 1 || socketConnections.length < 2 ? (m.frameType === 'BINARY' ? 'BIN' : null) : conn ? shortSocketUrl(conn.url) : null; return rowHtml({ id: String(i), selected: socketSelectedIndex === i, badgeText: rec ? 'RECV' : 'SENT', badgeTone: rec ? 'put' : 'signal', @@ -4204,7 +4435,7 @@ body = bodyViewerHtml(preview, null, lines, conn ? conn.url : 'Socket frame payload', true, 'socket:' + socketFlagId(socketSelectedIndex, m)); } const findBar = findBarHtml(query, lines ? countPaneHits([{ groups: [{ code: lines }] }]) : 0, 'socketDetailFindInput'); - body += `
${icon('lock', 'ic-sm')}Frame payloads pass through the same redaction allowlist as HTTP bodies.
`; + if (redactionShown()) body += `
${icon('lock', 'ic-sm')}Frame payloads are redacted on device.
`; const focusSnap = captureFocus(pane); pane.innerHTML = head + findBar + `
${body}
`; mountBodyViewers(pane); @@ -4230,6 +4461,7 @@ // ================================================================ let pushOrder = []; const PUSH_EMPTY_HTML = listEmptyHtml('push', 'No push events match', 'Clear the provider filter or search to see the other captured events.'); + const PUSH_NONE_HTML = listEmptyHtml('push', 'No push events yet', 'Push messages the app receives appear here.'); function renderPush() { const q = $('pushSearch').value.toLowerCase(); const rows = pushes @@ -4255,10 +4487,10 @@ posinset: n + 1, setsize: total, }); }, - PUSH_EMPTY_HTML, + pushes.length ? PUSH_EMPTY_HTML : PUSH_NONE_HTML, ); $('pushFootLeft').textContent = rows.length + ' of ' + pushes.length; - $('pushFootRight').textContent = 'push tokens are redacted'; + $('pushFootRight').textContent = redactionShown() ? 'push tokens are redacted' : ''; $('pushBadge').textContent = pushes.length + ' events'; renderPushMetrics(); renderPushDetail(); @@ -4306,7 +4538,7 @@ const body = codeBlockHtml(lines, true, p.notification?.title || p.messageId || 'Push payload') + `
${icon('lock', 'ic-sm')}${ p.simulated ? 'This event was injected from the Push view — it never came from a provider.' - : 'Captured from ' + esc(p.provider.toUpperCase()) + ' on device. Redacted fields are replaced by the on-device allowlist before this browser receives them.' + : 'Captured from ' + esc(p.provider.toUpperCase()) + ' on device.' + (redactionShown() ? ' Redacted fields are replaced by the on-device allowlist before this browser receives them.' : '') }
`; const focusSnap = captureFocus(pane); pane.innerHTML = head + findBar + `
${body}
`; @@ -4346,13 +4578,17 @@ pushes.forEach((p) => { counts[p.provider] = (counts[p.provider] || 0) + 1; }); $('pushProviderSeg').innerHTML = `` + - providers.map((p) => ``).join(''); + providers.map((p) => ``).join(''); } async function loadPush() { + if (!hasSession()) return loadPushImpl(); + return runViewLoader('push', () => loadPushImpl()); + } + async function loadPushImpl() { if (!token) return; const r = await fetch('/api/v1/push/events', { headers: auth() }); - if (!r.ok) return; + requireLoad(r); pushes = (await r.json()).data || []; if (selectedPushIndex >= pushes.length) selectedPushIndex = -1; refreshPushChips(); @@ -4416,6 +4652,7 @@ let crashKindFilter = ''; let crashRunsById = new Map(); // sessionId -> row from GET /api/v1/runs, refreshed by loadCrashes() const CRASHES_EMPTY_HTML = listEmptyHtml('bug', 'No crashes or ANRs match', 'Clear the kind filter or search to see the other captured events.'); + const CRASHES_NONE_HTML = listEmptyHtml('bug', 'No crashes yet', 'Crashes and ANRs from this session appear here.'); /** Splits raw multi-line text (the all-thread dump — not JSON) into codeBlockHtml()'s line-object * shape so the crash dump gets the exact same collapsible/fullscreen/copy treatment as every * JSON code block, without pretending the text is JSON. Truncation markers @@ -4468,14 +4705,18 @@ * every row can be joined to the run that produced it (crashRunInfo()); a failed runs fetch just * leaves crashRunsById empty, so every row's run info falls back to "omit" rather than guessing. */ async function loadCrashes() { + if (!hasSession()) return loadCrashesImpl(); + return runViewLoader('crashes', () => loadCrashesImpl()); + } + async function loadCrashesImpl() { if (!token) return; const params = new URLSearchParams({ limit: '500' }); params.append('pluginId', 'crash'); const [crashesRes, runsRes] = await Promise.all([ fetch('/api/v1/retained-events?' + params, { headers: auth() }), - fetch('/api/v1/runs', { headers: auth() }), + cachedJson('/api/v1/runs', 30000), ]); - if (!crashesRes.ok) { toast('Crashes fetch failed: ' + crashesRes.status, 'error'); return; } + requireLoad(crashesRes); const body = await crashesRes.json(); const runs = runsRes.ok ? (await runsRes.json()).data || [] : []; crashRunsById = new Map(runs.map((run) => [run.id, run])); @@ -4524,7 +4765,7 @@ posinset: n + 1, setsize: total, }); }, - CRASHES_EMPTY_HTML, + crashEvents.length ? CRASHES_EMPTY_HTML : CRASHES_NONE_HTML, ); $('crashesFootLeft').textContent = rows.length + ' of ' + crashEvents.length; $('crashesFootRight').textContent = 'auto-flagged as evidence'; @@ -4604,7 +4845,7 @@
Breadcrumbs
${breadcrumbsHtml} ${dumpGroup} -
${icon('lock', 'ic-sm')}Breadcrumbs are already-redacted summaries; the all-thread dump is redacted the same way any other stack trace/text payload is before it ever leaves the device.
+ ${redactionShown() ? `
${icon('lock', 'ic-sm')}Breadcrumbs and stack traces are redacted on device.
` : ''} `; restoreFocus(focusSnap, pane); } @@ -4643,8 +4884,14 @@ let selectedStateMutators = []; let cachedFlags = []; async function loadState() { + if (!hasSession()) return loadStateImpl(); + return runViewLoader('state', () => loadStateImpl()); + } + async function loadStateImpl() { if (!token) return; const [statesRes, flagsRes] = await Promise.all([fetch('/api/v1/state', { headers: auth() }), fetch('/api/v1/flags', { headers: auth() })]); + requireLoad(statesRes); + requireLoad(flagsRes); stateProviderIds = statesRes.ok ? ((await statesRes.json()).data || []).map((s) => s.id) : []; if (!stateProviderIds.includes(selectedStateProviderId)) { selectedStateProviderId = stateProviderIds[0] || ''; @@ -4752,7 +4999,7 @@ const otherFlags = cachedFlags.filter((f) => f.type !== 'BOOLEAN'); cardsGridHtml('stateCards', [ { - icon: 'flag', iconTone: 'signal', title: 'Feature flags', badge: cachedFlags.length + ' flag' + (cachedFlags.length === 1 ? '' : 's'), badgeTone: 'muted', + icon: 'toggle', iconTone: 'signal', title: 'Feature flags', badge: cachedFlags.length + ' flag' + (cachedFlags.length === 1 ? '' : 's'), badgeTone: 'muted', lede: cachedFlags.length ? false : 'No feature flags are registered for this session.', rows: otherFlags.map((f) => ({ k: f.key, v: f.value, tone: 'ink', tag: f.mutable ? false : 'FIXED', tagTone: 'muted' })), toggles: boolFlags.map((f) => ({ @@ -4764,7 +5011,7 @@ { icon: 'database', iconTone: 'signal', title: 'State providers', badge: stateProviderIds.length + ' registered', badgeTone: 'muted', lede: stateProviderIds.length ? false : 'This application has not registered any state providers.', - tree: stateProviderIds.map((id) => ({ id, label: id, icon: 'flag', selected: id === selectedStateProviderId, tone: id === selectedStateProviderId ? 'ink' : 'muted' })), + tree: stateProviderIds.map((id) => ({ id, label: id, icon: 'toggle', selected: id === selectedStateProviderId, tone: id === selectedStateProviderId ? 'ink' : 'muted' })), }, { icon: 'grid', iconTone: 'signal', title: selectedStateProviderId ? 'App state · ' + selectedStateProviderId : 'App state', span: 2, @@ -4789,17 +5036,13 @@ let remoteConfigSourceFilter = 'all'; const REMOTE_CONFIG_SOURCE_TONE = { remote: 'signal', override: 'warn', default: 'muted', static: 'muted', unknown: 'muted' }; async function loadRemoteConfig() { + if (!hasSession()) return loadRemoteConfigImpl(); + return runViewLoader('remoteConfig', () => loadRemoteConfigImpl()); + } + async function loadRemoteConfigImpl() { if (!token) return; const r = await fetch('/api/v1/remote-config', { headers: auth() }); - if (!r.ok) { - // Counter and badge are reset here too: leaving the last successful load's numbers next to a - // card that says the fetch failed is the one reading that is worse than either alone. - remoteConfigProviders = []; - setNavCount('navCountRemoteConfig', 0); - $('remoteConfigBadge').textContent = 'unavailable'; - cardsGridHtml('remoteConfigCards', [{ icon: 'sliders', iconTone: 'signal', title: 'Remote Config', lede: 'Remote Config unavailable: ' + r.status }]); - return; - } + requireLoad(r); remoteConfigProviders = (await r.json()).data || []; renderRemoteConfigCards(); } @@ -4819,7 +5062,7 @@ : 'no providers'; if (!remoteConfigProviders.length) { cardsGridHtml('remoteConfigCards', [{ - icon: 'sliders', iconTone: 'signal', title: 'Remote Config', span: 2, + icon: 'cloud', iconTone: 'signal', title: 'Remote Config', span: 2, lede: 'No Remote Config provider is registered for this session. Register one with DevConsoleConfig.withRemoteConfigProviders(...) — see docs/REMOTE_CONFIG.md.', }]); return; @@ -4838,7 +5081,7 @@ : 'No values returned by the last fetch.'; } else if (!shown.length) lede = 'No key matches the current filter.'; return { - icon: 'sliders', iconTone: provider.unavailableReason ? 'warn' : 'signal', span: 2, + icon: 'cloud', iconTone: provider.unavailableReason ? 'warn' : 'signal', span: 2, title: 'Remote Config · ' + provider.id, badge: remoteConfigFetchLine(provider), badgeTone: provider.unavailableReason ? 'warn' : 'muted', lede, @@ -4974,12 +5217,13 @@ const SENSITIVE_KEY_PATTERN = /token|secret|password|passwd|auth|credential|cookie/i; const canEditPreferences = () => hasSession() && preferencesEditable; async function loadPreferences() { + if (!hasSession()) return loadPreferencesImpl(); + return runViewLoader('preferences', () => loadPreferencesImpl()); + } + async function loadPreferencesImpl() { if (!token) return; const r = await fetch('/api/v1/preferences', { headers: auth() }); - if (!r.ok) { - cardsGridHtml('prefCards', [{ icon: 'sliders', iconTone: 'signal', title: 'Preferences', lede: 'Preferences unavailable: ' + r.status }]); - return; - } + requireLoad(r); const body = await r.json(); preferencesEditable = body.editable === true; updateControlUi(); @@ -4995,10 +5239,12 @@ const file = preferenceFiles.find((f) => f.name === name); const entries = file?.entries || []; const masked = entries.filter((e) => e.redacted); - const blindSpots = entries.filter((e) => !e.redacted && SENSITIVE_KEY_PATTERN.test(e.key)); + // With redaction off (the default) values are shown on purpose: no blind spots, no Redaction column. + const redacting = redactionShown(); + const blindSpots = redacting ? entries.filter((e) => !e.redacted && SENSITIVE_KEY_PATTERN.test(e.key)) : []; const cards = [ - { - icon: 'alert', iconTone: blindSpots.length ? 'warn' : 'signal', title: 'Known redaction blind spot', span: 2, + redacting && { + icon: 'alert', iconTone: blindSpots.length ? 'warn' : 'signal', title: 'Known redaction blind spot', span: 2, ledeFold: 'Why this happens', lede: 'The allowlist matches key names literally. A key that merely *looks* sensitive but isn’t on the deny list is transmitted verbatim — shown honestly here rather than hidden, since the fix is a pattern rule, not a UI change.', rows: masked.slice(0, 4).map((e) => ({ k: e.key, v: e.value, tone: 'warn', tag: 'MASKED', tagTone: 'warn' })).concat( blindSpots.map((e) => ({ k: e.key, v: e.value, tone: 'error', tag: 'VERBATIM', tagTone: 'error' })), @@ -5006,20 +5252,21 @@ }, file ? { - icon: 'sliders', iconTone: 'signal', title: name, span: 2, badge: entries.length + ' entries', badgeTone: 'muted', + icon: 'sliders', iconTone: 'signal', title: name, span: 2, editFold: 'Add or change a key', badge: entries.length + ' entries', badgeTone: 'muted', lede: entries.length ? false : 'This file has no entries.', table: entries.length ? { - cols: ['Key', 'Value', 'Type', 'Redaction'], + cols: redacting ? ['Key', 'Value', 'Type', 'Redaction'] : ['Key', 'Value', 'Type'], rows: entries.map((e) => [ { v: e.key, tone: 'ink' }, - { v: e.value, tone: e.redacted ? 'warn' : SENSITIVE_KEY_PATTERN.test(e.key) ? 'error' : 'ink' }, + { v: e.value, tone: e.redacted ? 'warn' : redacting && SENSITIVE_KEY_PATTERN.test(e.key) ? 'error' : 'ink' }, { v: e.type, tone: 'muted' }, + ].concat(redacting ? [ { v: e.redacted ? 'masked' : SENSITIVE_KEY_PATTERN.test(e.key) ? 'NOT MATCHED' : 'none', tone: e.redacted ? 'warn' : SENSITIVE_KEY_PATTERN.test(e.key) ? 'error' : 'muted' }, - ]), + ] : [])), } : false, - fieldsHtml: `
+ fieldsHtml: `
@@ -5031,7 +5278,7 @@ } : { icon: 'sliders', iconTone: 'signal', title: 'Entries', span: 2, lede: 'Choose a file to inspect its entries.' }, ]; - cardsGridHtml('prefCards', cards); + cardsGridHtml('prefCards', cards.filter(Boolean)); wireCardGrid('prefCards', { onButton: (id) => { if (id === 'save') savePreference(); else if (id === 'remove') removePreference(); } }); } async function savePreference() { @@ -5071,12 +5318,13 @@ let dbSizeBytes = null; const canEditDatabase = () => hasSession() && databaseEditable; async function loadDatabases() { + if (!hasSession()) return loadDatabasesImpl(); + return runViewLoader('database', () => loadDatabasesImpl()); + } + async function loadDatabasesImpl() { if (!token) return; const r = await fetch('/api/v1/database', { headers: auth() }); - if (!r.ok) { - cardsGridHtml('dbCards', [{ icon: 'database', iconTone: 'signal', title: 'Database', lede: 'Databases unavailable: ' + r.status }]); - return; - } + requireLoad(r); const body = await r.json(); databaseEditable = body.editable === true; updateControlUi(); @@ -5093,7 +5341,7 @@ if (!token || !name) return; const r = await fetch('/api/v1/database/' + encodeURIComponent(name), { headers: auth() }); if (!r.ok) { - cardsGridHtml('dbCards', [{ icon: 'database', iconTone: 'signal', title: 'Tables', lede: 'Tables unavailable: ' + r.status }]); + cardsGridHtml('dbCards', [{ icon: 'database', iconTone: 'signal', title: 'Tables', lede: 'Tables unavailable. ' + unavailableReason(r.status) }]); return; } const body = await r.json(); @@ -5284,12 +5532,13 @@ let filePreviewStatus = 'Choose a file to preview its contents.'; let filePreviewContent = null; // raw text, only when preview.kind === 'TEXT' async function loadFileRoots() { + if (!hasSession()) return loadFileRootsImpl(); + return runViewLoader('files', () => loadFileRootsImpl()); + } + async function loadFileRootsImpl() { if (!token) return; const r = await fetch('/api/v1/files', { headers: auth() }); - if (!r.ok) { - cardsGridHtml('filesCards', [{ icon: 'folder', iconTone: 'signal', title: 'Files', lede: 'Files unavailable: ' + r.status }]); - return; - } + requireLoad(r); const body = await r.json(); filesEditable = body.editable === true; updateControlUi(); @@ -5311,7 +5560,7 @@ if (!token || !root) return; const r = await fetch('/api/v1/files/' + encodeURIComponent(root) + '?path=' + encodeURIComponent(path || ''), { headers: auth() }); if (!r.ok) { - cardsGridHtml('filesCards', [{ icon: 'folder', iconTone: 'signal', title: 'Tree', lede: 'Listing unavailable: ' + r.status }]); + cardsGridHtml('filesCards', [{ icon: 'folder', iconTone: 'signal', title: 'Tree', lede: 'Listing unavailable. ' + unavailableReason(r.status) }]); return; } const listing = await r.json(); @@ -5333,7 +5582,7 @@ renderFilesCards(); const r = await fetch('/api/v1/files/' + encodeURIComponent(root) + '/preview?path=' + encodeURIComponent(relativePath), { headers: auth() }); if (!r.ok) { - filePreviewStatus = 'Preview unavailable: ' + r.status; + filePreviewStatus = 'Preview unavailable. ' + unavailableReason(r.status); renderFilesCards(); return; } @@ -5447,11 +5696,11 @@ })), }, { - icon: 'file', iconTone: 'signal', title: selectedFilePath || 'Preview', span: 2, + icon: 'file', iconTone: 'signal', title: selectedFilePath || 'Preview', span: 2, editFold: 'Edit file', badge: selectedFilePath ? (canEditFiles() ? 'editable' : 'read-only') : false, badgeTone: canEditFiles() ? 'signal' : 'warn', lede: filePreviewStatus || false, code: filePreviewContent != null ? filePreviewContent.split('\n').map((line) => ({ pad: '', k: '', v: line, cls: 'tone-text-ink' })) : false, - fieldsHtml: `
+ fieldsHtml: `
`, @@ -5481,18 +5730,19 @@ // SDK health // ================================================================ async function loadSdkHealth() { + if (!hasSession()) return loadSdkHealthImpl(); + return runViewLoader('sdkHealth', () => loadSdkHealthImpl()); + } + async function loadSdkHealthImpl() { if (!token) return; const [healthRes, metaRes, overviewRes] = await Promise.all([ fetch('/api/v1/sdk-health', { headers: auth() }), - fetch('/api/v1/meta', { headers: auth() }), + cachedJson('/api/v1/meta', 30000), fetch('/api/v1/overview', { headers: auth() }), ]); - if (!healthRes.ok) { - renderEmpty($('sdkHealthDetail'), 'health', 'Health unavailable: ' + healthRes.status); - return; - } + requireLoad(healthRes); const health = await healthRes.json(); - const meta = metaRes.ok ? await metaRes.json() : {}; + const meta = metaRes.ok ? await metaRes.json() : null; const csp = metaRes.ok ? metaRes.headers.get('Content-Security-Policy') : null; const integrity = overviewRes.ok ? (await overviewRes.json()).sessionIntegrity : null; $('sdkHealthMetrics').innerHTML = metricsStripHtml([ @@ -5507,13 +5757,13 @@ { label: 'Active principals', val: String(health.activePrincipalCount ?? 0), tone: 'ink' }, ] }, { icon: 'grid', iconTone: 'signal', title: 'Protocol', rows: [ - { k: 'Protocol', v: meta.protocolVersion ? 'devconsole/' + meta.protocolVersion : '—', tone: 'ink' }, + { k: 'Protocol', v: meta?.protocolVersion ? 'devconsole/' + meta.protocolVersion : '—', tone: 'ink' }, { k: 'Transport', v: 'ws + http (same origin)', tone: 'muted' }, { k: 'CSP', v: csp || 'not reported', tone: 'muted', tag: csp ? 'ENFORCED' : false, tagTone: 'signal' }, - { k: 'Capabilities', v: (meta.capabilities || []).join(', ') || '—', tone: 'muted' }, + { k: 'Capabilities', v: meta ? (meta.capabilities || []).join(', ') || '—' : 'unknown', tone: 'muted' }, ] }, integrity - ? { icon: 'shield', iconTone: 'warn', title: 'Session integrity', lede: 'Guardrail counters the SDK tracks for this session — not fabricated response-time budgets, since none are reported by the on-device SDK.', metrics: [ + ? { icon: 'shield', iconTone: 'warn', title: 'Session integrity', lede: 'Guardrail counters reported by the SDK.', metrics: [ { label: 'Active mocks', val: String((integrity.activeMockRuleIds || []).length), tone: 'put' }, { label: 'Flag overrides', val: String(Object.keys(integrity.featureFlagOverrides || {}).length), tone: 'ink' }, { label: 'State mutations', val: String(integrity.stateMutationCount ?? 0), tone: integrity.stateMutationCount ? 'warn' : 'ink' }, @@ -5543,11 +5793,21 @@ toast('Session code rotated.'); renderSessionCards(lastSessionMeta, lastSessionCapabilities); } + /** meta.networkProtection ({rateLimiting, hostAndOriginChecks}, both opt-in) as one short value. */ + function networkProtectionLabel(np) { + if (!np) return 'unknown'; + const on = [np.rateLimiting && 'rate limits', np.hostAndOriginChecks && 'host & origin checks'].filter(Boolean); + return on.length ? on.join(' + ') : 'off'; + } let retainedRuns = []; async function loadSession() { + if (!hasSession()) return loadSessionImpl(); + return runViewLoader('session', () => loadSessionImpl()); + } + async function loadSessionImpl() { if (!token) return; const [metaRes, principalsRes, prefsRes, dbRes, filesRes, mocksRes, captureRes, flagsRes, composerRes, runsRes] = await Promise.all([ - fetch('/api/v1/meta', { headers: auth() }), + cachedJson('/api/v1/meta', 30000), fetch('/api/v1/auth/principals', { headers: auth() }), fetch('/api/v1/preferences', { headers: auth() }), fetch('/api/v1/database', { headers: auth() }), @@ -5556,24 +5816,61 @@ fetch('/api/v1/capture-rules', { headers: auth() }), fetch('/api/v1/flags', { headers: auth() }), fetch('/api/v1/composer/collections', { headers: auth() }), - fetch('/api/v1/runs', { headers: auth() }), + cachedJson('/api/v1/runs', 30000), ]); - const meta = metaRes.ok ? await metaRes.json() : {}; + requireLoad(metaRes); + const meta = metaRes.ok ? await metaRes.json() : null; sessionPrincipals = principalsRes.ok ? (await principalsRes.json()).data || [] : []; - const flags = flagsRes.ok ? (await flagsRes.json()).data || [] : []; + const parseEditable = async (res) => { + if (!res.ok) return null; + try { + return (await res.json()).editable === true; + } catch { + return null; + } + }; + const prefsEditable = await parseEditable(prefsRes); + const dbEditable = await parseEditable(dbRes); + const filesEditable = await parseEditable(filesRes); + const mocksEditable = await parseEditable(mocksRes); + const captureEditable = await parseEditable(captureRes); + + let flagsMutable = null; + if (flagsRes.ok) { + try { + flagsMutable = ((await flagsRes.json()).data || []).some((f) => f.mutable); + } catch { + flagsMutable = null; + } + } + + let composerExecution = null; + if (composerRes.ok) { + composerExecution = true; + } else if (composerRes.status === 404) { + composerExecution = false; + } else { + composerExecution = null; + } + const capabilities = { - preferences: prefsRes.ok && (await prefsRes.json()).editable === true, - database: dbRes.ok && (await dbRes.json()).editable === true, - files: filesRes.ok && (await filesRes.json()).editable === true, - mocks: mocksRes.ok && (await mocksRes.json()).editable === true, - captureRules: captureRes.ok && (await captureRes.json()).editable === true, - featureFlags: flags.some((f) => f.mutable), - requestExecution: composerRes.status !== 404, + preferences: prefsEditable, + database: dbEditable, + files: filesEditable, + mocks: mocksEditable, + captureRules: captureEditable, + featureFlags: flagsMutable, + requestExecution: composerExecution, }; retainedRuns = runsRes.ok ? (await runsRes.json()).data || [] : []; lastSessionMeta = meta; lastSessionCapabilities = capabilities; renderSessionCards(meta, capabilities); + // The binding card says "Retrying…" when meta failed (usually the read-rate limit), so retry. + clearTimeout(sessionRetryTimer); + if (!meta?.endpoint) { + sessionRetryTimer = setTimeout(() => { if (currentView === 'session') loadSession(); }, 5000); + } } async function revokePrincipal(id) { if (!hasSession()) return; @@ -5619,33 +5916,44 @@ }); } function renderSessionCards(meta, capabilities) { - const endpoint = meta.endpoint; + const endpoint = meta?.endpoint; const lan = endpoint?.bindingMode === 'LAN'; + const loopback = endpoint?.bindingMode === 'LOOPBACK'; + const hasEndpoint = Boolean(endpoint); const capRows = [ ['preferences', capabilities.preferences], ['database', capabilities.database], ['files', capabilities.files], ['mocks', capabilities.mocks], ['captureRules', capabilities.captureRules], ['featureFlags', capabilities.featureFlags], ['requestExecution', capabilities.requestExecution], ]; - const capOnCount = capRows.filter(([, on]) => on).length; + const capKnown = capRows.filter(([, on]) => on !== null && on !== undefined); + const capOnCount = capRows.filter(([, on]) => on === true).length; $('sessionMetrics').innerHTML = metricsStripHtml([ { label: openAccess ? 'Auth' : 'Browsers', val: openAccess ? 'open' : String(sessionPrincipals.length + 1), sub: openAccess ? 'no session' : 'incl. this one', tone: 'ink' }, - { label: 'Capabilities', val: String(capOnCount), sub: 'of ' + capRows.length + ' on', tone: capOnCount ? 'signal' : 'warn' }, - { label: 'Build', val: meta.build?.variant || '—', tone: 'ink' }, - { label: 'Protocol', val: meta.protocolVersion ? 'v' + meta.protocolVersion : '—', tone: 'muted' }, + { label: 'Capabilities', val: capKnown.length ? String(capOnCount) : '—', sub: capKnown.length ? capOnCount + ' of ' + capRows.length + ' on' : 'unknown', tone: capOnCount ? 'signal' : 'warn' }, + { label: 'Build', val: meta?.build?.variant || '—', tone: 'ink' }, + { label: 'Protocol', val: meta?.protocolVersion ? 'v' + meta.protocolVersion : '—', tone: 'muted' }, ]); cardsGridHtml('sessionCards', [ { - icon: 'alert', iconTone: lan ? 'warn' : 'signal', title: lan ? 'This console is reachable on your LAN' : 'This console is bound to the loopback interface', span: 2, - lede: lan - ? (openAccess - ? 'Anyone on this network can read every capture and use the enabled dashboard capabilities. Use LOOPBACK or SESSION_CODE on shared networks. Debug builds only — the SDK refuses to start in release.' - : 'Anyone on this network who has the session code can read every capture in this session, including redacted-but-present metadata. Debug builds only — the SDK refuses to start in release.') - : 'Only this device can reach the console — the SDK bound to loopback rather than a LAN-visible address.', + icon: 'alert', iconTone: lan ? 'warn' : (loopback ? 'signal' : 'muted'), + ledeFold: 'What this means', + title: lan ? 'This console is reachable on your LAN' : (loopback ? 'This console is bound to the loopback interface' : 'Connection details'), span: 2, + lede: !hasEndpoint + ? "Couldn't load the connection details. Retrying…" + : (lan + ? (openAccess + ? 'Anyone on this network can read every capture and use the enabled dashboard capabilities. Use LOOPBACK or SESSION_CODE on shared networks. Debug builds only — the SDK refuses to start in release.' + : 'Anyone on this network who has the session code can read every capture in this session, including redacted-but-present metadata. Debug builds only — the SDK refuses to start in release.') + : (loopback + ? 'Only this device can reach the console — the SDK bound to loopback rather than a LAN-visible address.' + : 'Bound to ' + endpoint.bindingMode)), rows: [ - { k: 'Bound address', v: endpoint ? endpoint.host + ':' + endpoint.port : '—', tone: 'ink', tag: endpoint?.bindingMode || false, tagTone: lan ? 'warn' : 'signal' }, + { k: 'Bound address', v: endpoint ? endpoint.host + ':' + endpoint.port : '—', tone: 'ink', tag: endpoint?.bindingMode || (hasEndpoint ? false : 'UNKNOWN'), tagTone: lan ? 'warn' : (loopback ? 'signal' : 'muted') }, { k: 'Transport', v: 'http + ws, no TLS', tone: 'warn', tag: 'PLAINTEXT', tagTone: 'warn' }, { k: 'Auth', v: openAccess ? 'open browser access' : 'rotating session code', tone: openAccess ? 'warn' : 'signal', tag: openAccess ? 'OPEN' : false, tagTone: 'warn' }, - { k: 'Build type', v: meta.build?.variant || 'unknown', tone: meta.build?.variant === 'debug' ? 'signal' : 'muted', tag: meta.build?.variant === 'debug' ? 'GUARDED' : false, tagTone: 'signal' }, + { k: 'Redaction', v: meta?.redaction?.enabled === false ? 'off — values shown as captured' : meta?.redaction?.enabled ? 'on' : 'unknown', tone: meta?.redaction?.enabled ? 'signal' : 'muted' }, + { k: 'Network protection', v: networkProtectionLabel(meta?.networkProtection), tone: meta?.networkProtection?.rateLimiting || meta?.networkProtection?.hostAndOriginChecks ? 'signal' : 'muted' }, + { k: 'Build type', v: meta?.build?.variant || 'unknown', tone: meta?.build?.variant === 'debug' ? 'signal' : 'muted', tag: meta?.build?.variant === 'debug' ? 'GUARDED' : false, tagTone: 'signal' }, ].concat( rotatedSessionCode ? [ @@ -5666,26 +5974,34 @@ bodyHtml: sessionPrincipals.length ? principalsTableHtml(sessionPrincipals) : '', }, { - icon: 'database', iconTone: retainedRuns.some((r) => r.status === 'CRASHED') ? 'error' : 'signal', title: 'Retained runs', span: 2, - badge: retainedRuns.length + ' run' + (retainedRuns.length === 1 ? '' : 's'), badgeTone: 'muted', - lede: retainedRuns.length ? false : 'No retained runs on this device yet.', + icon: 'database', iconTone: retainedRuns.some((r) => r.status === 'CRASHED') ? 'error' : 'signal', title: 'Run history', span: 2, + bodyFold: 'Retained runs', foldCount: retainedRuns.length + ' runs', + emptyText: 'No retained runs on this device yet.', bodyHtml: retainedRuns.length ? retainedRunsTableHtml(retainedRuns) : '', }, { - icon: 'lock', iconTone: 'signal', title: 'Capabilities', badge: capOnCount + ' of ' + capRows.length + ' on', badgeTone: capOnCount ? 'signal' : 'warn', - rows: capRows.map(([k, on]) => ({ k, v: on ? 'on' : 'off', tone: on ? 'signal' : 'warn', tag: on ? 'WRITE' : 'BLOCKED', tagTone: on ? 'signal' : 'warn' })), + icon: 'lock', iconTone: 'signal', title: 'Capabilities', + badge: capKnown.length ? capOnCount + ' of ' + capRows.length + ' on' : 'unknown', + badgeTone: capOnCount ? 'signal' : (capKnown.length ? 'warn' : 'muted'), + rows: capRows.map(([k, on]) => ({ + k, + v: on === true ? 'on' : (on === false ? 'off' : 'unknown'), + tone: on === true ? 'signal' : (on === false ? 'warn' : 'muted'), + tag: on === true ? 'WRITE' : (on === false ? 'BLOCKED' : 'UNKNOWN'), + tagTone: on === true ? 'signal' : (on === false ? 'warn' : 'muted') + })), }, { icon: 'download', iconTone: 'signal', title: 'Export & retention', - lede: 'Redaction is applied before anything leaves the device.', + lede: redactionShown() ? 'Redaction is applied before anything leaves the device.' : 'Redaction is off, so exports hold values as captured.', fieldsHtml: `
- +
-
${esc(hasSession() ? 'Choose a scope, then create a redacted ZIP.' : 'Connect this browser to create a diagnostic export.')}
`, +
${esc(hasSession() ? 'Choose a scope, then create a redacted ZIP.' : 'Connect this browser to create a diagnostic export.')}
`, buttons: [ { id: 'export-estimate', label: 'Estimate size', icon: 'grid', disabled: !hasSession(), title: 'Check the ZIP size for the current scope before creating it' }, { id: 'export-create', label: 'Session ZIP', icon: 'download', kind: hasSession() ? 'primary' : 'default', disabled: !hasSession() }, @@ -5882,7 +6198,7 @@ async function loadEvidenceFlags() { if (!token) { evidenceFlags.clear(); updateEvidenceUi(); return { items: [], report: evidenceReport }; } const r = await fetch('/api/v1/evidence', { headers: auth() }); - if (!r.ok) return { items: [...evidenceFlags.values()], report: evidenceReport }; + if (!r.ok) return { items: [...evidenceFlags.values()], report: evidenceReport, failureStatus: r.status }; const body = await r.json(); const items = body.data || []; evidenceFlags.clear(); @@ -5899,7 +6215,12 @@ return { items: [...evidenceFlags.values()], report: evidenceReport }; } async function loadEvidence() { - const { items } = await loadEvidenceFlags(); + if (!hasSession()) return loadEvidenceImpl(); + return runViewLoader('evidence', () => loadEvidenceImpl()); + } + async function loadEvidenceImpl() { + const { items, failureStatus } = await loadEvidenceFlags(); + if (failureStatus) requireLoad({ ok: false, status: failureStatus }); let environment = null; if (hasSession()) { const r = await fetch('/api/v1/overview', { headers: auth() }); @@ -6215,7 +6536,8 @@ cardsGridHtml('evidenceList', [ { icon: 'flag', iconTone: 'muted', title: 'Nothing flagged yet', span: 3, - lede: 'Flag a transaction, frame, push event, timeline event or crash with the flag button at the end of its row — or from its detail header — and it lands here with the full redacted detail the server captured at flag time, not just a label. Draft the report while the session is still live; once it ends the proof is gone. A browser refresh keeps everything: flagged items and any typed report text are saved server-side.', + lede: 'Flag a request, event or crash from its row or detail header to collect it here.', + bodyHtml: foldHtml('How the tray works', '

' + esc("Flag a transaction, frame, push event, timeline event or crash with the flag button at the end of its row — or from its detail header — and it lands here with the full redacted detail the server captured at flag time, not just a label. Draft the report while the session is still live; once it ends the proof is gone. A browser refresh keeps everything: flagged items and any typed report text are saved server-side.") + '

'), buttons: [ { id: 'go-network', label: 'Go to Network', icon: 'network', kind: 'primary' }, { id: 'capture-screenshot', label: 'Capture screenshot', icon: 'camera', disabled: !hasSession(), title: hasSession() ? 'Capture the device\'s foreground screen — off by default; set screenshotPolicy.enabled to allow it' : 'Connect this browser first' }, @@ -6271,7 +6593,9 @@ // Exactly one severity is ever selected — a radiogroup, not five independent switches. radioLabel: 'Severity', toggles: EVIDENCE_SEVERITIES.map((s) => ({ id: s, k: evidenceSeverityLabel(s), checked: evidenceReport.severity === s, sub: EVIDENCE_SEVERITY_SUB[s] })), - rows: [{ k: 'Redaction', v: 'applied before export (screenshots excepted — see below)', tone: 'signal', tag: 'SAFE', tagTone: 'signal' }], + rows: [redactionShown() + ? { k: 'Redaction', v: 'applied before export (screenshots excepted — see below)', tone: 'signal', tag: 'SAFE', tagTone: 'signal' } + : { k: 'Redaction', v: 'off — values are exported as captured', tone: 'muted' }], }, { icon: 'camera', iconTone: 'signal', title: 'Screenshots', @@ -6362,6 +6686,7 @@ const controlHeaders = () => (openAccess ? {} : { ...auth(), 'X-DevConsole-CSRF': csrf }); const updateControlUi = () => { const enabled = hasSession(); + updateRecordButton(); $('composerRun').disabled = !enabled; $('composerImport').disabled = !enabled; $('composerCollectionSave').disabled = !enabled; @@ -6418,14 +6743,17 @@ gate.hidden = false; gate.innerHTML = gateBannerHtml({ title: 'Composer is turned off in this app', - body: 'Set composerEnabled(true) in the app\'s DevConsole config, and list the hosts it may call with composerAllowedHosts, to send requests from here.', + body: 'Set composerEnabled(true) in the app\'s DevConsole config to send requests from here.', code: 'COMPOSER_DISABLED', }); - return; + return false; } gate.hidden = true; gate.innerHTML = ''; - if (!r.ok) return; + if (!r.ok) { + renderLoadFailure($('composerCollectionList'), 'Could not load collections', r.status, loadComposerCollections); + return false; + } const collections = (await r.json()).data || []; $('composerCollectionList').innerHTML = collections.length ? cardRowsHtml( @@ -6451,6 +6779,7 @@ let composerAgents = []; let composerAllowedHostList = []; let composerHostsEditable = false; + let composerAnyHost = false; let composerHostEntries = []; let rejectedComposerHost = ''; @@ -6461,19 +6790,24 @@ return ''; } } - const isComposerHostAllowed = (host) => composerAllowedHostList.some((allowed) => allowed.toLowerCase() === host); + const isComposerHostAllowed = (host) => + composerAnyHost || composerAllowedHostList.some((allowed) => allowed.toLowerCase() === host); async function loadComposerHostAllowlist() { if (!token) return; const [metaResponse, hostsResponse] = await Promise.all([ - fetch('/api/v1/meta', { headers: auth() }), + cachedJson('/api/v1/meta', 30000), fetch('/api/v1/composer/hosts', { headers: auth() }), ]); if (metaResponse.ok) composerCapabilityEnabled = ((await metaResponse.json()).composer || {}).enabled === true; - if (!hostsResponse.ok) return; - const { editable, data } = await hostsResponse.json(); + if (!hostsResponse.ok) { + renderLoadFailure($('composerAllowedHosts'), 'Could not load allowed hosts', hostsResponse.status, loadComposerHostAllowlist); + return false; + } + const { editable, anyHost, data } = await hostsResponse.json(); const hosts = data || []; - composerHostsEditable = editable === true; + composerAnyHost = anyHost === true; + composerHostsEditable = editable === true && !composerAnyHost; composerHostEntries = hosts; composerAllowedHostList = hosts.map((entry) => entry.host); renderComposerHostList(hosts); @@ -6491,6 +6825,8 @@ tagTone: 'error', })), ); + } else if (composerAnyHost) { + list.innerHTML = '

No allowlist configured — the composer can reach any host.

'; } else { const hint = composerHostsEditable ? 'Add one below.' : 'The host app has to allow some.'; list.innerHTML = `

No hosts allowed yet, so every Composer host is refused. ${hint}

`; @@ -6506,9 +6842,11 @@ $('composerHostEditor').hidden = !canEdit; updateComposerAllowHostButton(); syncRejectedHostPanel(); - $('composerHostNote').textContent = composerHostsEditable - ? 'Hosts added here last until DevConsole stops. You can paste a full URL; only the hostname is kept.' - : 'The app fixes this list. Turn on composerHostsEditable in its DevConsole config to add hosts here.'; + $('composerHostNote').textContent = composerAnyHost + ? '' + : composerHostsEditable + ? 'Hosts added here last until DevConsole stops. You can paste a full URL; only the hostname is kept.' + : 'The app fixes this list. Turn on composerHostsEditable in its DevConsole config to add hosts here.'; } const COMPOSER_HOST_ERRORS = { @@ -6720,10 +7058,8 @@ return `${composerAgents.length} ${noun} connected. Requests sent to one use its network, VPN and localhost.`; } const codeFlag = openAccess ? '' : ' --code '; - return ( - 'To run requests from your Mac, Linux or Windows computer (VPN, localhost or private APIs the phone ' + - `cannot reach), start: devconsole-agent --device http://${location.host}${codeFlag}` - ); + const command = `devconsole-agent --device http://${location.host}${codeFlag}`; + return `For VPN, localhost or private APIs, run requests on a computer:${esc(command)}`; } async function loadComposerAgents() { if (!token) return false; @@ -6745,7 +7081,7 @@ }); const stillAvailable = [...select.options].some((option) => option.value === previousChoice); select.value = stillAvailable ? previousChoice : COMPOSER_DEVICE_EXECUTOR; - $('composerAgentHint').textContent = composerAgentHint(); + $('composerAgentHint').innerHTML = composerAgentHint(); return true; } const waitMs = (duration) => new Promise((resolve) => setTimeout(resolve, duration)); @@ -7002,13 +7338,18 @@ async function loadMockRules() { if (!token) return; const r = await fetch('/api/v1/mocks/rules', { headers: auth() }); + if (!r.ok) { + viewLoadedAt.delete('mocks'); + renderLoadFailure($('mockRuleList'), 'Could not load mock rules', r.status, loadMocks); + return false; + } if (r.ok) { const body = await r.json(); mocksEditable = body.editable === true; updateControlUi(); const rules = body.data || []; mockRulesCache = rules; - $('mocksRulesBadge').textContent = rules.filter((rule) => rule.enabled).length + ' of ' + rules.length + ' active'; + $('mocksRulesBadge').textContent = ''; $('mockRuleList').innerHTML = rules.length ? cardTogglesHtml( rules.map((rule) => ({ @@ -7067,11 +7408,16 @@ : '

No overlapping rules detected.

'; } async function loadMocks() { + if (!hasSession()) return loadMocksImpl(); + return runViewLoader('mocks', () => loadMocksImpl()); + } + async function loadMocksImpl() { if (!token) return; const r = await fetch('/api/v1/mocks', { headers: auth() }); + requireLoad(r); mocksGloballyEnabled = r.ok ? (await r.json()).enabled === true : true; syncMockEngineButton(); - loadMockRules(); + return await loadMockRules(); } /** Turning mocking off stays on the ungated `disable-all` route, so a host that publishes mocks * as read-only can still fall back to real traffic; turning it back on goes through the @@ -7128,16 +7474,17 @@ // ================================================================ const canEditCaptureRules = () => hasSession() && captureRulesEditable; async function loadCaptureRules() { + if (!hasSession()) return loadCaptureRulesImpl(); + return runViewLoader('captureRules', () => loadCaptureRulesImpl()); + } + async function loadCaptureRulesImpl() { if (!token) return; - const [rulesRes, metaRes] = await Promise.all([fetch('/api/v1/capture-rules', { headers: auth() }), fetch('/api/v1/meta', { headers: auth() })]); - if (!rulesRes.ok) { - $('captureRuleStatus').textContent = 'Capture exclusions unavailable: ' + rulesRes.status; - return; - } + const [rulesRes, metaRes] = await Promise.all([fetch('/api/v1/capture-rules', { headers: auth() }), cachedJson('/api/v1/meta', 30000)]); + requireLoad(rulesRes); const body = await rulesRes.json(); captureRulesEditable = body.editable === true; updateControlUi(); - $('captureRuleStatus').textContent = canEditCaptureRules() ? 'Capture exclusions are editable.' : 'Read-only — sign in and enable the captureRules capability to edit.'; + $('captureRuleStatus').textContent = canEditCaptureRules() ? '' : 'Read-only — sign in and enable the captureRules capability to edit.'; const rules = body.data || []; $('captureRulesBadge').textContent = rules.length + ' rule' + (rules.length === 1 ? '' : 's'); $('captureRuleList').innerHTML = rules.length ? captureRuleTableHtml(rules) : '

No capture exclusions are configured — everything matching a capture rule is retained.

'; @@ -7151,6 +7498,7 @@ } if (metaRes.ok) { const names = (await metaRes.json()).redaction?.sensitiveFieldNames || []; + $('captureRedactionCount').textContent = String(names.length); $('captureRedaction').innerHTML = names.length ? cardRowsHtml(names.map((n) => ({ k: n, v: 'masked before capture', tone: 'warn', tag: 'MASK', tagTone: 'warn' }))) : '

No redacted field names were reported.

'; @@ -7172,7 +7520,7 @@ EXCLUDE ${ editable - ? `` + ? `` : `${rule.enabled ? 'ACTIVE' : 'PAUSED'}` } ${editable ? `` : ''} @@ -7246,7 +7594,8 @@ * today) rather than a blanket switch: the other detail panes carry two or three actions each, * where a row costs nothing and a menu would only add a click. `menuOpen` is the caller's own * state, since these panes re-render wholesale and the flag has to outlive the innerHTML swap. */ - function detailHeadHtml({ badgeText, badgeTone, title, statusText, sTone, mocked, extraBadge, facts, actions, tabs, layoutToggle, actionsMenu, menuOpen }) { + function detailHeadHtml({ badgeText, badgeTone, title, statusText, sTone, mocked, extraBadge, facts, actions, tabs, layoutToggle, actionsMenu, menuOpen, networkHeader }) { + if (networkHeader) return networkDetailHeadHtml({ badgeText, title, actions, tabs, menuOpen, ...networkHeader }); const zoom = document.body.classList.contains('detail-zoom'); const hasActions = actions && actions.length; return `
@@ -7304,7 +7653,8 @@ * lives in the DOM at once (only one view is visible, but none are torn down when hidden). */ function findBarHtml(query, matchCount, inputId = 'detailFindInput') { return `
${ - query ? matchCount + ' match' + (matchCount === 1 ? '' : 'es') : 'headers + payload + response' + // The placeholder already names the scope; the count only appears once there is a query. + query ? matchCount + ' match' + (matchCount === 1 ? '' : 'es') : '' }
`; } function sbsPaneHtml(pane) { @@ -7320,6 +7670,63 @@ } const networkGroupOpen = {}; + function networkListToggleHtml() { + const shell = $('networkDetailPane').parentElement; + const visible = !shell.classList.contains('list-collapsed') || shell.classList.contains('list-overlay-open'); + const label = visible ? 'Hide request list' : 'Show request list'; + return ``; + } + function syncNetworkListToggle() { + const btn = $('networkListToggle'); + if (!btn) return; + const shell = $('networkDetailPane').parentElement; + const visible = !shell.classList.contains('list-collapsed') || shell.classList.contains('list-overlay-open'); + const label = visible ? 'Hide request list' : 'Show request list'; + btn.title = label; + btn.setAttribute('aria-label', label); + btn.setAttribute('aria-expanded', String(visible)); + } + function setNetworkListOverlay(open) { + const shell = $('networkDetailPane').parentElement; + const wasOpen = shell.classList.contains('list-overlay-open'); + shell.classList.toggle('list-overlay-open', open && shell.classList.contains('list-collapsed')); + syncNetworkListToggle(); + if (open) requestAnimationFrame(() => { + if (!shell.classList.contains('list-overlay-open')) return; + const list = virtualLists.get('transactions'); + list?.remeasure(); + focusSelectedRow('transactions', networkOrder.indexOf(selectedTransactionId)); + }); + else if (wasOpen) $('networkListToggle')?.focus(); + } + function renderNetworkEmpty() { + const pane = $('networkDetailPane'); + renderEmpty(pane, 'network', 'No transaction selected', 'Select a request to inspect it.'); + pane.insertAdjacentHTML('afterbegin', `
${networkListToggleHtml()}
`); + } + function networkDetailHeadHtml({ badgeText, title, actions, tabs, menuOpen, fullUrl, metaLine }) { + const primary = ['curl', 'clone', 'flag']; + const menuActions = actions.filter((a) => !primary.includes(a.id)); + return `
+ ${networkListToggleHtml()}${esc(badgeText)} + ${esc(title)} +
${primary.map((id) => { + const a = actions.find((item) => item.id === id); + const label = id === 'curl' ? 'Copy cURL' : id === 'clone' ? 'Open in Composer' : 'Flag as evidence'; + return ``; + }).join('')}
+ ${menuOpen ? `` : ''} +
${esc(metaLine)}
+
${tabs.map((t) => ``).join('')}
`; + } + const NETWORK_STATUS_REASONS = { + 200: 'OK', 201: 'Created', 202: 'Accepted', 204: 'No Content', 206: 'Partial Content', + 301: 'Moved Permanently', 302: 'Found', 304: 'Not Modified', 307: 'Temporary Redirect', 308: 'Permanent Redirect', + 400: 'Bad Request', 401: 'Unauthorized', 403: 'Forbidden', 404: 'Not Found', 405: 'Method Not Allowed', + 408: 'Request Timeout', 409: 'Conflict', 422: 'Unprocessable Content', 429: 'Too Many Requests', + 500: 'Internal Server Error', 502: 'Bad Gateway', 503: 'Service Unavailable', 504: 'Gateway Timeout', + }; + async function fetchTransactionDetail(id) { if (networkDetailCache.has(id)) { const cached = networkDetailCache.get(id); @@ -7336,7 +7743,7 @@ if (!token || !id) return; selectedTransactionId = id; selectedTransactionDetail = await fetchTransactionDetail(id); - if (networkTab === 'diff' && !networkPinnedId) networkTab = 'compare'; + if (networkTab === 'diff' && !networkPinnedId) networkTab = 'response'; renderNetwork(); renderNetworkDetail(); } @@ -7373,6 +7780,14 @@ return body?.type === 'text' ? body.value : undefined; } + // Keep plain text literal rather than JSON-quoting it; JSON keeps the shared formatter. + function networkBodyLines(body, query) { + if (body?.type !== 'text') return bodyPreviewLines(body, query); + try { return formatJsonLines(JSON.parse(body.value), query); } catch { /* plain text */ } + const q = (query || '').trim().toLowerCase(); + return (body.value || '').split('\n').map((v) => ({ pad: '', k: '', v, cls: 'code-text', hit: Boolean(q && v.toLowerCase().includes(q)) })); + } + // ================================================================ // Mocked-response diff: when a transaction was served by a "Mock this response" rule, its // `sourceBodySnapshot` (the original response body the rule was created from) is diffed @@ -7553,16 +7968,15 @@ * mockRulesCache) and passed down rather than recomputed. */ function networkSummaryKvs(detail, { mockRuleId, mockDiffTotal } = {}) { const rows = [ - { k: 'time', v: time(detail.startedAtEpochMs) }, + { k: 'started at', v: time(detail.startedAtEpochMs) }, { k: 'duration', v: detail.durationMs != null ? detail.durationMs + ' ms' : '—' }, { k: 'request.url', v: detail.request?.url || '' }, { k: 'request.method', v: detail.method }, { k: 'response.status', v: detail.status != null ? String(detail.status) : detail.error ? '— no response' : '—', tone: statusTone(detail.status) }, ]; - // The error string used to be parenthesised into response.status above, and to double as the - // compare tab's failure "General" group. Both are gone: this is its one home, on its own row - // so a long exception message isn't buried inside another value. + // Preserve capture facts in Timing, including failures and mock provenance. if (detail.error) rows.push({ k: 'response.error', v: detail.error, tone: 'error' }); + if (detail.request?.contentType) rows.push({ k: 'request.contentType', v: detail.request.contentType }); if (detail.response?.contentType) rows.push({ k: 'response.contentType', v: detail.response.contentType }); if (detail.correlationId) rows.push({ k: 'correlationId', v: detail.correlationId }); if (mockRuleId) rows.push({ k: 'mock rule', v: mockRuleId, mockRuleLink: true }); @@ -7610,24 +8024,18 @@ // `pane` — in compare/diff mode the two side-by-side panes both emit `data-group-toggle` for // like-named groups, so a document-wide restore query could land on the wrong one. const focusSnap = captureFocus(pane); - if (!detail) { renderEmpty(pane, 'network', 'No transaction selected', 'Select a transaction from the list to inspect its redacted metadata.'); return; } + if (!detail) { renderNetworkEmpty(); return; } + normalizeNetworkTabForMode(); resetBodyViewers(); const pinId = networkPinnedId; const samePin = pinId === selectedTransactionId; const hasPin = Boolean(pinId) && !samePin && networkDetailCache.has(pinId); - if (networkTab === 'diff' && !pinId) networkTab = 'compare'; - const diffCount = hasPin ? diffHeaderStats(networkDetailCache.get(pinId), detail) : null; + if (networkTab === 'diff' && !pinId) networkTab = 'response'; const relatedFresh = networkRelatedEventsForId === detail.id; - // Summary leads: it absorbed the head's old facts strip (time/duration/content type/ - // correlation/mock rule/error), so it is the "what is this capture" tab and reads first. - // `networkTab` still defaults to 'compare' — order here, not which tab opens selected. - const tabs = [{ id: 'summary', label: 'Summary' }, { id: 'compare', label: 'Request & response' }] - .concat(pinId ? [{ id: 'diff', label: 'Diff vs baseline', count: hasPin ? String(diffCount.changed + diffCount.added) : 'pick one' }] : []) - .concat([ - { id: 'headers', label: 'Headers', count: String(headerRows(detail.request?.headers).length + headerRows(detail.response?.headers).length) }, - { id: 'timing', label: 'Timing' }, - { id: 'related', label: 'Related events', count: relatedFresh ? String(networkRelatedEvents.length) : undefined }, - ]) + // Response opens first; extra tabs exist only while their context is active. + const tabs = [{ id: 'response', label: 'Response' }, { id: 'request', label: 'Request' }, { id: 'headers', label: 'Headers' }, { id: 'timing', label: 'Timing' }] + .concat(pinId ? [{ id: 'diff', label: 'Diff' }] : []) + .concat(networkTab === 'related' ? [{ id: 'related', label: 'Related events' }] : []) .map((t) => ({ ...t, active: networkTab === t.id })); const flagged = isFlagged('network', detail.id); const mockRuleId = detail.tags?.mockRuleId; @@ -7659,28 +8067,39 @@ // exception; it's advanced-only in every state. { id: 'pin', label: samePin ? 'Baseline — unpin' : pinId ? 'Diff against baseline' : 'Pin as baseline', icon: 'star', on: samePin, title: pinId && !samePin ? 'Compare this response against the pinned baseline' : 'Pin this response as the baseline to diff others against (b)', hideInSimple: !pinId }, { id: 'resend', label: 'Resend', icon: 'refresh', disabled: !canResend(), title: canResend() ? 'Re-execute this exact request through the device (same gating as Composer)' : 'Sign in and enable the composer capability' }, - { id: 'clone', label: 'Clone to composer', icon: 'terminal' }, + { id: 'clone', label: 'Open in Composer', icon: 'pencil' }, ...(mockAction ? [mockAction] : []), { id: 'curl', label: 'cURL', icon: 'copy' }, { id: 'fetch', label: 'fetch', icon: 'copy', hideInSimple: true }, + { id: 'related', label: 'Related events', icon: 'activity' }, ]; - const showLayoutToggle = (networkTab === 'compare' || networkTab === 'diff') && (hasPin || networkTab === 'compare'); - const layoutToggle = showLayoutToggle ? { on: !networkSbsStacked, label: networkSbsStacked ? 'Side by side' : 'Stacked', title: networkSbsStacked ? 'Show the two panes side by side' : 'Stack the two panes in one column', icon: 'grid' } : null; + const fullUrl = detail.request?.url || detail.host + detail.path + (detail.query ? '?' + detail.query : ''); + const statusLabel = detail.status != null ? detail.status + (NETWORK_STATUS_REASONS[detail.status] ? ' ' + NETWORK_STATUS_REASONS[detail.status] : '') : detail.error ? 'ERR' : '—'; + const metaLine = [detail.host, statusLabel, detail.durationMs != null ? detail.durationMs + ' ms' : '—', time(detail.startedAtEpochMs)].join(' · ') + (isMocked ? ' · mocked' : ''); const head = detailHeadHtml({ - badgeText: detail.method, badgeTone: methodTone(detail.method), title: detail.host + detail.path, + badgeText: detail.method, badgeTone: methodTone(detail.method), title: detail.path + (detail.query ? '?' + detail.query : ''), statusText: detail.status != null ? String(detail.status) : detail.error ? 'FAILED' : '—', sTone: statusTone(detail.status), mocked: isMocked, - // No facts strip: time/duration/content type/correlation/mock rule now live in the Summary + // No facts strip: time/duration/content type/correlation/mock rule now live in the Timing // tab (see networkSummaryKvs) instead of being repeated under the title. - actions, tabs, layoutToggle, + actions, tabs, networkHeader: { fullUrl, metaLine }, actionsMenu: true, menuOpen: networkActionsMenuOpen, }); let findBar = ''; let bodyHtml; - if (networkTab === 'compare') { - const panes = networkComparePanes(detail, networkDetailQuery, mockDiff, mockDiffSig); - findBar = findBarHtml(networkDetailQuery, countPaneHits(panes)); - bodyHtml = `
${panes.map(sbsPaneHtml).join('')}
`; + if (networkTab === 'response' || networkTab === 'request') { + const response = networkTab === 'response'; + const side = response ? detail.response : detail.request; + const headers = headerRows(side?.headers); + const lines = networkBodyLines(side?.body, networkDetailQuery); + const hits = markKvHits(headers, networkDetailQuery).filter((r) => r.hit).length + (lines || []).filter((l) => l.hit).length; + findBar = findBarHtml(networkDetailQuery, hits); + // The body viewer's own toolbar carries Tree/Code, Copy and Full screen: one row, no second copy. + bodyHtml = `
`; + if (response && detail.error) bodyHtml += `
${esc(detail.error)}
`; + else if (lines) bodyHtml += bodyViewerHtml(bodyRawText(side?.body), side?.contentType, lines, response ? 'Response body' : 'Request body', true, 'network/' + detail.id + '/' + networkTab, response ? mockDiff : undefined, response ? mockDiffSig : undefined, true); + else bodyHtml += `
${esc(response ? 'No response body.' : detail.method + ' request — no body sent.')}
`; + bodyHtml += `
${icon('chevron', 'ic-sm fold-chevron')}${response ? 'Response' : 'Request'} headers · ${headers.length}
${kvGridHtml(markKvHits(headers, networkDetailQuery), true)}
`; } else if (networkTab === 'diff') { if (!hasPin) { bodyHtml = `
${sbsPaneHtml({ @@ -7694,10 +8113,9 @@ const panes = [diffPaneHtml('Baseline · ' + time(pinDetail.startedAtEpochMs), pinDetail, detail, true), diffPaneHtml('Selected · ' + time(detail.startedAtEpochMs), detail, pinDetail, false)]; bodyHtml = `
${panes.map(sbsPaneHtml).join('')}
`; } - } else if (networkTab === 'summary') { - bodyHtml = kvGridHtml(networkSummaryKvs(detail, { mockRuleId, mockDiffTotal }), true); } else if (networkTab === 'headers') { - bodyHtml = kvGridHtml(networkHeadersKvs(detail), true); + bodyHtml = `${kvGridHtml(markKvHits(headerRows(detail.request?.headers), networkDetailQuery), true)}${kvGridHtml(markKvHits(headerRows(detail.response?.headers), networkDetailQuery), true)}`; + findBar = findBarHtml(networkDetailQuery, markKvHits(headerRows(detail.request?.headers).concat(headerRows(detail.response?.headers)), networkDetailQuery).filter((r) => r.hit).length); } else if (networkTab === 'timing') { const { bars, fallback } = networkTimingBars(detail); if (!bars) { @@ -7708,6 +8126,7 @@ bodyHtml += `
Phase-level timing (DNS/connect/TLS/wait/receive) requires the OkHttp event listener to be installed; showing total duration only.
`; } } + bodyHtml += kvGridHtml(networkSummaryKvs(detail, { mockRuleId, mockDiffTotal }), true); } else { // 'related' — a real tab (not a one-shot action that clobbered .detail-body with no way // back) so it survives re-render like every other tab. Data is per-transaction and fetched @@ -7721,7 +8140,7 @@ bodyHtml = `No related timeline events found for this transaction's correlation id.`; } } - bodyHtml += `
${icon('lock', 'ic-sm')}Headers and bodies are redacted by the on-device allowlist before they reach this browser. Values shown as •••• never left the app.
`; + if (redactionShown()) bodyHtml += `
${icon('lock', 'ic-sm')}Redacted on device.
`; pane.innerHTML = head + findBar + `
${bodyHtml}
`; mountBodyViewers(pane); // The menu panel is position: fixed (the detail pane is overflow: hidden, so an absolutely @@ -7767,7 +8186,25 @@ * toggle, zoom, find, and the header/pane action buttons — wired once (not per render). */ function wireNetworkDetailPane() { const pane = $('networkDetailPane'); + $('networkFullEndpoint').addEventListener('click', () => { + networkFullEndpoint = !networkFullEndpoint; + try { localStorage.setItem('devconsole.network.fullEndpoint', String(networkFullEndpoint)); } catch { /* storage unavailable */ } + renderNetwork(); + }); + document.addEventListener('keydown', (e) => { + if (currentView !== 'network') return; + if (e.key === 'Escape') { networkListController?.close(); return; } + if (e.key !== '[' || e.ctrlKey || e.metaKey || e.altKey || (e.target instanceof Element && e.target.closest('input, textarea, select, [contenteditable="true"]'))) return; + e.preventDefault(); + networkListController?.toggle(); + }); + document.addEventListener('click', (e) => { + const shell = pane.parentElement; + if (shell.classList.contains('list-overlay-open') && !e.target.closest('#networkListPane, #networkListToggle')) networkListController?.close(); + }); + if (!selectedTransactionDetail) renderNetworkEmpty(); pane.addEventListener('click', (e) => { + if (e.target.closest('[data-action="toggle-request-list"]')) { networkListController?.toggle(); return; } if (e.target.closest('[data-action="toggle-actions-menu"]')) { networkActionsMenuOpen = !networkActionsMenuOpen; renderNetworkDetail(); return; } if (e.target.closest('[data-action="toggle-zoom"]')) { toggleDetailZoom(); return; } const mockLink = e.target.closest('[data-open-mock-rule]'); @@ -7809,13 +8246,24 @@ // read first since the repaint detaches `actionBtn` from the tree. if (networkActionsMenuOpen) { networkActionsMenuOpen = false; renderNetworkDetail(); } if (id === 'flag') { const d = selectedTransactionDetail; toggleEvidenceFlag('network', d.id, d.method + ' ' + d.host + d.path); renderNetworkDetail(); } - else if (id === 'pin') pinNetworkBaseline(selectedTransactionId); + else if (id === 'pin') { + if (networkPinnedId && networkPinnedId !== selectedTransactionId) { + networkTab = 'diff'; + fetchTransactionDetail(networkPinnedId).then(renderNetworkDetail); + renderNetworkDetail(); + } else pinNetworkBaseline(selectedTransactionId); + } else if (id === 'resend') resendCapturedRequest(); else if (id === 'clone') cloneCapturedRequest(); else if (id === 'mock') mockThisResponse(); else if (id === 'unmock') unmockNetworkResponse(); else if (id === 'curl') copyNetworkCurl(); else if (id === 'fetch') copyNetworkFetch(); + else if (id === 'related') { networkTab = 'related'; renderNetworkDetail(); } + else if (id === 'copy-response-body' || id === 'copy-request-body') { + const side = id === 'copy-response-body' ? selectedTransactionDetail.response : selectedTransactionDetail.request; + copyToClipboard(bodyRawText(side?.body) ?? selectedTransactionDetail.error ?? '', 'Body'); + } else copyToClipboard(detailActionText(id, selectedTransactionDetail), actionBtn.textContent.trim() || 'Value'); }); pane.addEventListener('input', (e) => { @@ -8174,7 +8622,10 @@ files: loadFileRoots, push: loadPush, crashes: loadCrashes, - composer: () => Promise.all([loadComposerCollections(), loadComposerHostAllowlist(), loadComposerAgents()]), + composer: () => runViewLoader('composer', async () => { + const results = await Promise.all([loadComposerCollections(), loadComposerHostAllowlist(), loadComposerAgents().then(() => true)]); + return results.every((result) => result !== false); + }), mocks: loadMocks, captureRules: loadCaptureRules, sdkHealth: loadSdkHealth, @@ -8185,6 +8636,8 @@ // `show()` was ever called with one directly (e.g. a future caller that bypasses the redirect), // so nothing ever fetches a route the server now answers 403 CATEGORY_DISABLED for. if (isViewDisabledByCapture(view)) return undefined; + if (viewPending.has(view)) return viewPending.get(view); + if (hasSession() && Date.now() - (viewLoadedAt.get(view) || 0) < 5000) return Promise.resolve(); return loaders[view] ? loaders[view]() : undefined; } @@ -8224,15 +8677,17 @@ const el = $('hostLine'); if (!el) return; if (!token) { - el.textContent = "Not connected — see the device's More screen for the connect QR"; + el.textContent = ''; return; } try { - const [overviewRes, metaRes] = await Promise.all([fetch('/api/v1/overview', { headers: auth() }), fetch('/api/v1/meta', { headers: auth() })]); + const [overviewRes, metaRes] = await Promise.all([fetch('/api/v1/overview', { headers: auth() }), cachedJson('/api/v1/meta', 30000)]); const overview = overviewRes.ok ? await overviewRes.json() : null; const meta = metaRes.ok ? await metaRes.json() : null; + if (currentView === 'network') renderNetworkDetail(); const parts = [overview?.app?.packageName, overview?.app?.versionName, meta?.endpoint ? `${meta.endpoint.host}:${meta.endpoint.port}` : location.host].filter(Boolean); - if (parts.length) el.textContent = parts.join(' · '); + el.textContent = overview?.app?.packageName || ''; + el.title = parts.join(' · '); } catch { /* keep previous text on transient failure */ } @@ -8241,6 +8696,98 @@ // ================================================================ // Wiring // ================================================================ + function wireTopbarOverflow() { + const container = $('topbarOverflow'); + const toggle = $('topbarOverflowToggle'); + const panel = $('topbarOverflowPanel'); + const items = () => [...panel.querySelectorAll('button:not(:disabled)')]; + function setOpen(open, focusFirst = false) { + panel.hidden = !open; + toggle.setAttribute('aria-expanded', String(open)); + if (open && focusFirst) items()[0]?.focus(); + } + toggle.onclick = () => setOpen(panel.hidden); + toggle.addEventListener('keydown', (event) => { + if (event.key === 'ArrowDown') { event.preventDefault(); setOpen(true, true); } + }); + panel.addEventListener('keydown', (event) => { + const buttons = items(); + const index = buttons.indexOf(document.activeElement); + let next; + if (event.key === 'ArrowDown') next = (index + 1) % buttons.length; + if (event.key === 'ArrowUp') next = (index - 1 + buttons.length) % buttons.length; + if (event.key === 'Home') next = 0; + if (event.key === 'End') next = buttons.length - 1; + if (next !== undefined) { event.preventDefault(); buttons[next]?.focus(); } + }); + panel.addEventListener('click', (event) => { + if (event.composedPath().some((node) => node.matches?.('button:not(:disabled)'))) { + setOpen(false); + // The shortcuts handler may have already moved focus into its dialog. + if (panel.contains(document.activeElement)) toggle.focus(); + } + }); + document.addEventListener('click', (event) => { + if (!container.contains(event.target)) setOpen(false); + }); + document.addEventListener('keydown', (event) => { + if (event.key === 'Escape' && !panel.hidden) { + event.preventDefault(); + setOpen(false); + toggle.focus(); + } + }); + container.addEventListener('focusout', (event) => { + if (!container.contains(event.relatedTarget)) setOpen(false); + }); + } + + function wireNetworkExportMenu() { + const container = $('networkExportMenu'); + const toggle = $('networkExportToggle'); + const panel = $('networkExportPanel'); + if (!container || !toggle || !panel) return; + const items = () => [...panel.querySelectorAll('button:not(:disabled)')]; + function setOpen(open, focusFirst = false) { + panel.hidden = !open; + toggle.setAttribute('aria-expanded', String(open)); + if (open && focusFirst) items()[0]?.focus(); + } + toggle.onclick = () => setOpen(panel.hidden); + toggle.addEventListener('keydown', (event) => { + if (event.key === 'ArrowDown') { event.preventDefault(); setOpen(true, true); } + }); + panel.addEventListener('keydown', (event) => { + const buttons = items(); + const index = buttons.indexOf(document.activeElement); + let next; + if (event.key === 'ArrowDown') next = (index + 1) % buttons.length; + if (event.key === 'ArrowUp') next = (index - 1 + buttons.length) % buttons.length; + if (event.key === 'Home') next = 0; + if (event.key === 'End') next = buttons.length - 1; + if (next !== undefined) { event.preventDefault(); buttons[next]?.focus(); } + }); + panel.addEventListener('click', (event) => { + if (event.composedPath().some((node) => node.matches?.('button:not(:disabled)'))) { + setOpen(false); + if (panel.contains(document.activeElement)) toggle.focus(); + } + }); + document.addEventListener('click', (event) => { + if (!container.contains(event.target)) setOpen(false); + }); + document.addEventListener('keydown', (event) => { + if (event.key === 'Escape' && !panel.hidden) { + event.preventDefault(); + setOpen(false); + toggle.focus(); + } + }); + container.addEventListener('focusout', (event) => { + if (!container.contains(event.relatedTarget)) setOpen(false); + }); + } + function wireEvents() { initTheme(); initMode(); @@ -8249,9 +8796,9 @@ $('themeToggle').onclick = toggleTheme; $('modeToggle').onclick = toggleMode; - $('railAdvancedToggle').onclick = () => setRailAdvancedOpen(!railAdvancedOpen); + if ($('railAdvancedToggle')) $('railAdvancedToggle').onclick = () => setRailAdvancedOpen(!railAdvancedOpen); wireRowList('events', { onSelect: (id) => { selectedEventId = id; render(); } }); - wireRowList('transactions', { onSelect: (id) => showTransaction(id), onCheck: (id) => toggleNetworkSelection(id) }); + wireRowList('transactions', { onSelect: (id) => { showTransaction(id); networkListController?.close(); }, onCheck: (id) => toggleNetworkSelection(id) }); wireRowList('sockets', { onSelect: (id) => { socketSelectedIndex = Number(id); renderSockets(); }, rowSelector: '.row, .trace-row' }); wireRowList('pushEvents', { onSelect: (id) => { selectedPushIndex = Number(id); renderPush(); } }); wireRowList('crashesList', { onSelect: (id) => { selectedCrashId = id; renderCrashes(); } }); @@ -8326,6 +8873,7 @@ $('networkRefresh').onclick = () => loadNetwork(); $('networkNewest').onclick = () => loadNetwork(); $('networkOlder').onclick = () => networkCursor && loadNetwork(networkCursor); + wireNetworkExportMenu(); $('networkHarDownload').onclick = downloadHar; $('networkPostmanDownload').onclick = downloadPostman; $('networkClear').onclick = clearNetworkCaptures; @@ -8507,6 +9055,8 @@ // wired directly in renderEventDetail() since it only exists once an event is selected. $('streamLive').onclick = () => setPaused(false); $('streamPaused').onclick = () => setPaused(true); + $('liveToggle').onclick = () => setPaused(!paused); + wireTopbarOverflow(); // ---- Topbar: rail toggle, evidence tray, quick export ----------------------- $('viewEvidence').onclick = () => show('evidence'); @@ -8569,7 +9119,7 @@ overlay.hidden = !willShow; $('shortcutsBtn').classList.toggle('active', willShow); if (willShow) { - shortcutsOpenerEl = document.activeElement; + shortcutsOpenerEl = $('topbarOverflowPanel').contains(document.activeElement) ? $('topbarOverflowToggle') : document.activeElement; document.addEventListener('keydown', shortcutsKeydown); $('shortcutsClose').focus(); } else { diff --git a/sdk/server-ktor/src/main/resources/devconsole-web/favicon.webp b/sdk/server-ktor/src/main/resources/devconsole-web/favicon.webp index 2190137..3d78269 100644 Binary files a/sdk/server-ktor/src/main/resources/devconsole-web/favicon.webp and b/sdk/server-ktor/src/main/resources/devconsole-web/favicon.webp differ 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 84e75c1..71c7c53 100644 --- a/sdk/server-ktor/src/main/resources/devconsole-web/index.html +++ b/sdk/server-ktor/src/main/resources/devconsole-web/index.html @@ -8,84 +8,110 @@ - +
- + DevConsole
- Not connected — see the device's More screen for the dashboard URL +
Open DevConsole on device → More → scan the QR
+
- - - - +
+ + +
+
@@ -93,11 +119,9 @@
Control
- +
Data
- - + + @@ -127,10 +151,9 @@
- @@ -211,11 +231,10 @@

Network

-

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.

- +
Status
@@ -240,9 +259,15 @@
- - - +
+ + +
@@ -266,27 +291,25 @@
-
-
+
+
- MethodPathDurationStatus + MethodPathStatus · time
- -
Not connected yet
-
Captured HTTP transactions appear here once this browser is connected. On the device, open DevConsole → More — it shows the dashboard URL, and a code only when SESSION_CODE is enabled.
+ +
Not connected yet
Open DevConsole on the device → More, then open the dashboard URL.
How to connect

Captured HTTP transactions appear here once this browser is connected. On the device, open DevConsole → More — it shows the dashboard URL, and a code only when SESSION_CODE is enabled.

  • Open mode accepts the bare http://host:port/ address. In SESSION_CODE mode, the #code= fragment is the credential.
  • Emulator or firewalled device? Forward the port first: adb forward tcp:8080 tcp:8080 — 8080 is only the first port tried; the server takes the next free one up to 8099, so confirm the exact address on the device's More screen.
  • Open the URL directly, or scan the QR/paste the code when SESSION_CODE is enabled.
  • -
-
+
@@ -295,11 +318,11 @@

WebSockets

-

Connections and redacted frames. Binary previews appear only when the host opted in.

+

- +
Frame type
@@ -351,20 +374,18 @@
- -
Not connected yet
-
WebSocket connections and frames appear here once this browser is connected. On the device, open DevConsole → More — it shows the dashboard URL, and a code only when SESSION_CODE is enabled.
+ +
Not connected yet
Open DevConsole on the device → More, then open the dashboard URL.
How to connect

WebSocket connections and frames appear here once this browser is connected. On the device, open DevConsole → More — it shows the dashboard URL, and a code only when SESSION_CODE is enabled.

  • Open mode accepts the bare http://host:port/ address. In SESSION_CODE mode, the #code= fragment is the credential.
  • Emulator or firewalled device? Forward the port first: adb forward tcp:8080 tcp:8080 — 8080 is only the first port tried; the server takes the next free one up to 8099, so confirm the exact address on the device's More screen.
  • Open the URL directly, or scan the QR/paste the code when SESSION_CODE is enabled.
  • -
-
+
@@ -373,11 +394,10 @@

Push

-

Captured push lifecycle events. Simulated payloads are labelled everywhere they appear.

- +
@@ -398,20 +418,18 @@ ProviderMessageLifecycleTime
- -
Not connected yet
-
Captured push lifecycle events appear here once this browser is connected. On the device, open DevConsole → More — it shows the dashboard URL, and a code only when SESSION_CODE is enabled.
+ +
Not connected yet
Open DevConsole on the device → More, then open the dashboard URL.
How to connect

Captured push lifecycle events appear here once this browser is connected. On the device, open DevConsole → More — it shows the dashboard URL, and a code only when SESSION_CODE is enabled.

  • Open mode accepts the bare http://host:port/ address. In SESSION_CODE mode, the #code= fragment is the credential.
  • Emulator or firewalled device? Forward the port first: adb forward tcp:8080 tcp:8080 — 8080 is only the first port tried; the server takes the next free one up to 8099, so confirm the exact address on the device's More screen.
  • Open the URL directly, or scan the QR/paste the code when SESSION_CODE is enabled.
  • -
-
+
@@ -420,11 +438,10 @@

Crashes

-

Uncaught exceptions and ANRs from the crash plugin — every crash and ANR is flagged into the evidence tray automatically.

- +
Kind
@@ -442,74 +459,68 @@ KindSummaryThreadTime
- -
Not connected yet
-
Crashes and ANRs appear here once this browser is connected. On the device, open DevConsole → More — it shows the dashboard URL, and a code only when SESSION_CODE is enabled.
+ +
Not connected yet
Open DevConsole on the device → More, then open the dashboard URL.
How to connect

Crashes and ANRs appear here once this browser is connected. On the device, open DevConsole → More — it shows the dashboard URL, and a code only when SESSION_CODE is enabled.

  • Open mode accepts the bare http://host:port/ address. In SESSION_CODE mode, the #code= fragment is the credential.
  • Emulator or firewalled device? Forward the port first: adb forward tcp:8080 tcp:8080 — 8080 is only the first port tried; the server takes the next free one up to 8099, so confirm the exact address on the device's More screen.
  • Open the URL directly, or scan the QR/paste the code when SESSION_CODE is enabled.
  • -
-
+
-

State & Flags

App state snapshots and feature flags. Each flag's own `mutable` bit gates its toggle — the SDK reports no session-wide write switch for either.

+

State & Flags

-
Not connected yet
Open DevConsole on the device → More → scan the QR or paste the code in Overview to inspect state and flags.
+
Not connected yet
Open DevConsole on the device → More, then open the dashboard URL.
How to connect

Open DevConsole on the device → More → scan the QR or paste the code in Overview to inspect state and flags.

Remote Config

-

Read-only view of the Remote Config values active on this device. The source badge is the point: a key serving a default because the last fetch failed or was throttled looks identical to a published one until you can see where it came from.

- +
Source
-
Not connected yet
Open DevConsole on the device → More → scan the QR or paste the code in Overview to inspect Remote Config.
+
Not connected yet
Open DevConsole on the device → More, then open the dashboard URL.
How to connect

Open DevConsole on the device → More → scan the QR or paste the code in Overview to inspect Remote Config.

Preferences

-

SharedPreferences viewer. Redaction is allowlist-based — keys that merely look sensitive can still slip through unmasked.

-
Not connected yet
Open DevConsole on the device → More → scan the QR or paste the code in Overview to browse SharedPreferences.
+
Not connected yet
Open DevConsole on the device → More, then open the dashboard URL.
How to connect

Open DevConsole on the device → More → scan the QR or paste the code in Overview to browse SharedPreferences.

Database

-

Read-only SQLite browser unless the database capability is enabled. Filter the table list, then query inside it.

- +
Sort
-
Not connected yet
Open DevConsole on the device → More → scan the QR or paste the code in Overview to browse the SQLite databases.
+
Not connected yet
Open DevConsole on the device → More, then open the dashboard URL.
How to connect

Open DevConsole on the device → More → scan the QR or paste the code in Overview to browse the SQLite databases.

Files

-

Sandbox browser. Create, rename, and save need the files capability.

@@ -517,21 +528,20 @@
-
Not connected yet
Open DevConsole on the device → More → scan the QR or paste the code in Overview to browse the sandbox.
+
Not connected yet
Open DevConsole on the device → More, then open the dashboard URL.
How to connect

Open DevConsole on the device → More → scan the QR or paste the code in Overview to browse the sandbox.

-

SDK Health

Bounded health snapshot and protocol metadata reported by the on-device SDK.

+

SDK Health

-
Not connected yet
Open DevConsole on the device → More → scan the QR or paste the code in Overview to inspect SDK health.
+
Not connected yet
Open DevConsole on the device → More, then open the dashboard URL.
How to connect

Open DevConsole on the device → More → scan the QR or paste the code in Overview to inspect SDK health.

Evidence tray

-

Everything a developer needs to reproduce, assembled while the session is still live.

@@ -539,14 +549,14 @@
-

Session & Security

Who is connected, what is retained, and what this build exposes on the LAN.

+

Session & Security

-
Not connected yet
Open DevConsole on the device → More → scan the QR or paste the code in Overview to see who's connected and what this build exposes.
+
Not connected yet
Open DevConsole on the device → More, then open the dashboard URL.
How to connect

Open DevConsole on the device → More → scan the QR or paste the code in Overview to see who's connected and what this build exposes.

-

Composer

Run requests on the device or on a connected computer — never in the browser, so CORS does not apply. Import cURL and save ephemeral collections.

+

Composer

@@ -557,50 +567,41 @@
-
- - - - - - - - - - - - - - -
+
+ + + +
More options
+ + + + + + + +

-
-

cURL import

-
+
cURL import
-
-
+

Last response

-
Not connected yet
Open DevConsole on the device → More → scan the QR or paste the code in Overview to execute or import requests.
+
Not connected yet
Open DevConsole on the device → More, then open the dashboard URL.
How to connect

Open DevConsole on the device → More → scan the QR or paste the code in Overview to execute or import requests.

-
-

Ephemeral collections

-
+
Collections
Collections contain no persisted secret variable values.
-
-
+

Host allowlist

@@ -617,7 +618,7 @@
-

Mocks

Rules that intercept matching requests on device before they reach the network.

+

Mocks

@@ -640,30 +641,27 @@
-

Capture rules

What the SDK records, and what it drops before anything is retained.

+

Capture rules

Active exclusions

-
+
Add exclusion
-
-
Connect this browser to inspect capture exclusions.
+
+

Connect this browser to inspect capture exclusions.

-
-

Redacted field names

-
-

Header and body keys matching these names are masked before anything leaves the device. This is the real denylist reported by the SDK — not an allowlist of what stays verbatim.

+
Redacted field names
+

Matching header and body keys are masked on device.

-
-
+
diff --git a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/CapabilityGateMatrixTest.kt b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/CapabilityGateMatrixTest.kt index 994f18d..f77762e 100644 --- a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/CapabilityGateMatrixTest.kt +++ b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/CapabilityGateMatrixTest.kt @@ -68,7 +68,7 @@ class CapabilityGateMatrixTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { mocksEditable = target == Capability.MOCKS captureRulesEditable = target == Capability.CAPTURE_RULES preferencesEditable = target == Capability.PREFERENCES diff --git a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/CaptureRuleRoutesTest.kt b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/CaptureRuleRoutesTest.kt index 0e39191..7b51ba3 100644 --- a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/CaptureRuleRoutesTest.kt +++ b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/CaptureRuleRoutesTest.kt @@ -38,7 +38,7 @@ class CaptureRuleRoutesTest { @Test fun `unauthenticated requests are rejected across every capture-rule route`() = testApplication { - application { devConsoleModule(SessionAuthority()) } + application { protectedDevConsoleModule(SessionAuthority()) } val unauthenticated = listOf( @@ -64,7 +64,7 @@ class CaptureRuleRoutesTest { val sessionCodes = SessionCodeAuthority(sessions) val engine = CaptureRuleEngine(listOf(CaptureRule.of(id = "r", host = "api.example.test"))) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { captureRules = engine captureRulesEditable = true } @@ -91,7 +91,7 @@ class CaptureRuleRoutesTest { val sessionCodes = SessionCodeAuthority(sessions) val engine = CaptureRuleEngine() application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { captureRules = engine captureRulesEditable = false } @@ -125,7 +125,7 @@ class CaptureRuleRoutesTest { val sessionCodes = SessionCodeAuthority(sessions) val engine = CaptureRuleEngine() application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { captureRules = engine captureRulesEditable = true } @@ -160,7 +160,7 @@ class CaptureRuleRoutesTest { val sessionCodes = SessionCodeAuthority(sessions) val engine = CaptureRuleEngine(listOf(CaptureRule.of(id = "r", host = "api.example.test"))) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { captureRules = engine captureRulesEditable = true } @@ -193,7 +193,7 @@ class CaptureRuleRoutesTest { val sessionCodes = SessionCodeAuthority(sessions) val engine = CaptureRuleEngine(listOf(CaptureRule.of(id = "r", host = "api.example.test"))) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { captureRules = engine captureRulesEditable = false } @@ -215,7 +215,7 @@ class CaptureRuleRoutesTest { val sessionCodes = SessionCodeAuthority(sessions) val engine = CaptureRuleEngine(listOf(CaptureRule.of(id = "r", host = "api.example.test"))) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { captureRules = engine captureRulesEditable = true } @@ -237,7 +237,7 @@ class CaptureRuleRoutesTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { captureRules = CaptureRuleEngine() captureRulesEditable = true } diff --git a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/ComposerAgentRoutesTest.kt b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/ComposerAgentRoutesTest.kt index ad4db73..891d5ba 100644 --- a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/ComposerAgentRoutesTest.kt +++ b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/ComposerAgentRoutesTest.kt @@ -43,7 +43,7 @@ class ComposerAgentRoutesTest { testApplication { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) - application { devConsoleModule(sessions, sessionCodes) { composerEnabled = true } } + application { protectedDevConsoleModule(sessions, sessionCodes) { composerEnabled = true } } val session = client.exchangeSession(sessions, sessionCodes) val agentClient = createClient { install(WebSockets) } @@ -69,7 +69,7 @@ class ComposerAgentRoutesTest { val network = InMemoryNetworkTransactionStore(NetworkCursorCodec("network-cursor-key".encodeToByteArray())) val audit = InMemoryCommandAuditLog() application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { composerEnabled = true composerAllowedHosts = setOf("api.corp.test") networkTransactions = network @@ -129,7 +129,7 @@ class ComposerAgentRoutesTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { composerEnabled = true composerAllowedHosts = setOf("api.corp.test") } @@ -163,7 +163,7 @@ class ComposerAgentRoutesTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) application { - devConsoleModule(sessions, sessionCodes) { composerEnabled = true } + protectedDevConsoleModule(sessions, sessionCodes) { composerEnabled = true } } val session = client.exchangeSession(sessions, sessionCodes) val agentClient = createClient { install(WebSockets) } @@ -191,7 +191,7 @@ class ComposerAgentRoutesTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { composerEnabled = true browserSecurity = io.devconsole.api.BrowserSecurity.SESSION_CODE } @@ -216,7 +216,7 @@ class ComposerAgentRoutesTest { testApplication { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) - application { devConsoleModule(sessions, sessionCodes) } + application { protectedDevConsoleModule(sessions, sessionCodes) } val session = client.exchangeSession(sessions, sessionCodes) val agents = @@ -235,7 +235,7 @@ class ComposerAgentRoutesTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { composerEnabled = true composerAllowedHosts = setOf("api.corp.test") } @@ -258,7 +258,7 @@ class ComposerAgentRoutesTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { composerEnabled = true composerAllowedHosts = setOf("api.corp.test") } @@ -285,7 +285,7 @@ class ComposerAgentRoutesTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { composerEnabled = true composerAllowedHosts = setOf("api.corp.test") } @@ -313,7 +313,7 @@ class ComposerAgentRoutesTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { composerEnabled = true composerAllowedHosts = setOf("api.corp.test") } @@ -350,7 +350,7 @@ class ComposerAgentRoutesTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { composerEnabled = true composerAllowedHosts = setOf("api.corp.test") } @@ -384,7 +384,7 @@ class ComposerAgentRoutesTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { composerEnabled = true composerAllowedHosts = setOf("api.corp.test", "cdn.corp.test") } @@ -443,7 +443,7 @@ class ComposerAgentRoutesTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { composerEnabled = true composerAllowedHosts = setOf("api.corp.test") } diff --git a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/ComposerHostAllowlistTest.kt b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/ComposerHostAllowlistTest.kt index 313847a..4987909 100644 --- a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/ComposerHostAllowlistTest.kt +++ b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/ComposerHostAllowlistTest.kt @@ -70,7 +70,7 @@ class ComposerHostAllowlistTest { @Test fun `invalid input is not added and the session list is bounded`() { - val list = ComposerHostAllowlist(emptySet(), editable = true) + val list = ComposerHostAllowlist(setOf("acme.com"), editable = true) assertEquals(ComposerHostAllowlist.AddResult.Invalid, list.add("*.acme.com")) repeat(ComposerHostAllowlist.MAX_SESSION_HOSTS) { list.add("host$it.example") } @@ -78,6 +78,17 @@ class ComposerHostAllowlistTest { assertFalse(list.permits("one-too-many.example")) } + @Test + fun `an app that configures no hosts permits any host and session hosts never narrow it`() { + val list = ComposerHostAllowlist(emptySet(), editable = true) + + assertTrue(list.permitsAnyHost) + assertTrue(list.permits("api.acme.com")) + assertEquals(ComposerHostAllowlist.AddResult.AlreadyAllowed("acme.com"), list.add("acme.com")) + assertTrue(list.permits("other.example")) + assertFalse(list.permits("")) + } + @Test fun `permits matches the host exactly, never a suffix`() { val list = ComposerHostAllowlist(setOf("acme.com"), editable = false) diff --git a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/ComposerHostRoutesTest.kt b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/ComposerHostRoutesTest.kt index 798757d..a533128 100644 --- a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/ComposerHostRoutesTest.kt +++ b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/ComposerHostRoutesTest.kt @@ -37,7 +37,7 @@ class ComposerHostRoutesTest { val sessionCodes = SessionCodeAuthority(sessions) val audit = InMemoryCommandAuditLog() application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { composerEnabled = true composerHostsEditable = true composerAllowedHosts = setOf("fixed.example.test") @@ -74,7 +74,7 @@ class ComposerHostRoutesTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { composerEnabled = true composerHostsEditable = true composerAllowedHosts = setOf("fixed.example.test") @@ -95,7 +95,7 @@ class ComposerHostRoutesTest { val sessionCodes = SessionCodeAuthority(sessions) val audit = InMemoryCommandAuditLog() application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { composerEnabled = true composerAllowedHosts = setOf("fixed.example.test") commandAuditLog = audit @@ -119,7 +119,7 @@ class ComposerHostRoutesTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { composerEnabled = true composerHostsEditable = true } @@ -144,7 +144,7 @@ class ComposerHostRoutesTest { testApplication { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) - application { devConsoleModule(sessions, sessionCodes) { composerHostsEditable = true } } + application { protectedDevConsoleModule(sessions, sessionCodes) { composerHostsEditable = true } } val session = client.exchangeSession(sessions, sessionCodes) assertEquals(HttpStatusCode.NotFound, client.addHost(session, "api.acme.com").status) @@ -156,7 +156,7 @@ class ComposerHostRoutesTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { composerEnabled = true composerHostsEditable = true composerAllowedHosts = setOf("b.example.test") 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 dcd9c70..32e78cb 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 @@ -186,18 +186,19 @@ class DashboardAssetsTest { } @Test - fun `dashboard uses the graphite cobalt design tokens`() { + fun `dashboard uses the graphite signal green design tokens`() { val css = DashboardAssets.css().lowercase() listOf( - "--ground: #111317", - "--panel: #171a20", - "--surface-2: #1d2129", - "--ink: #eceef2", - "--signal: #72a7ff", + "--ground: #111413", + "--panel: #181c1a", + "--surface-2: #1e2320", + "--ink: #ecebe4", + "--signal: #b7ed65", + "--signal: #2f7a1f", ).forEach { token -> assertTrue("missing $token", css.contains(token)) } - listOf("#b7ed65", "#427526", "terminal-green", "instrument panel").forEach { legacy -> + listOf("#72a7ff", "#245da8", "#111317", "terminal-green", "instrument panel").forEach { legacy -> assertFalse("legacy design value remains: $legacy", css.contains(legacy)) } } diff --git a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DevConsoleKtorModuleTest.kt b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DevConsoleKtorModuleTest.kt index 255147e..8c8c97f 100644 --- a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DevConsoleKtorModuleTest.kt +++ b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DevConsoleKtorModuleTest.kt @@ -110,7 +110,7 @@ class DevConsoleKtorModuleTest { fun `open browser mode exposes data and mutations without credentials`() = testApplication { application { - devConsoleModule(SessionAuthority()) { + protectedDevConsoleModule(SessionAuthority()) { browserSecurity = BrowserSecurity.NONE } } @@ -132,7 +132,7 @@ class DevConsoleKtorModuleTest { fun `open browser mode rejects cross-site mutations without requiring credentials`() = testApplication { application { - devConsoleModule(SessionAuthority()) { + protectedDevConsoleModule(SessionAuthority()) { browserSecurity = BrowserSecurity.NONE } } @@ -157,7 +157,7 @@ class DevConsoleKtorModuleTest { fun `unauthenticated health exposes only auth status protocol and display name`() = testApplication { application { - devConsoleModule(SessionAuthority()) { + protectedDevConsoleModule(SessionAuthority()) { metadata = ServerMetadata( protocolVersion = 7, @@ -186,7 +186,7 @@ class DevConsoleKtorModuleTest { val audit = InMemoryCommandAuditLog() val collections = InMemoryComposerCollectionStore() application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { composerEnabled = true commandAuditLog = audit composerCollections = collections @@ -245,7 +245,7 @@ class DevConsoleKtorModuleTest { @Test fun `health and dashboard are available without credentials`() = testApplication { - application { devConsoleModule(SessionAuthority()) } + application { protectedDevConsoleModule(SessionAuthority()) } assertEquals(HttpStatusCode.OK, client.get("/health") { header(HttpHeaders.Host, "localhost") }.status) val dashboardResponse = client.get("/") { header(HttpHeaders.Host, "localhost") } @@ -286,7 +286,7 @@ class DevConsoleKtorModuleTest { @Test fun `dashboard css and js assets are available without credentials and cache disabled`() = testApplication { - application { devConsoleModule(SessionAuthority()) } + application { protectedDevConsoleModule(SessionAuthority()) } val cssResponse = client.get("/assets/dashboard.css") { header(HttpHeaders.Host, "localhost") } assertEquals(HttpStatusCode.OK, cssResponse.status) @@ -315,7 +315,7 @@ class DevConsoleKtorModuleTest { @Test fun `favicon is served unauthenticated as webp`() = testApplication { - application { devConsoleModule(SessionAuthority()) } + application { protectedDevConsoleModule(SessionAuthority()) } val response = client.get("/assets/favicon.webp") { header(HttpHeaders.Host, "localhost") } @@ -336,7 +336,7 @@ class DevConsoleKtorModuleTest { testApplication { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) - application { devConsoleModule(sessions, sessionCodes) } + application { protectedDevConsoleModule(sessions, sessionCodes) } val session = client.exchangeSession(sessions, sessionCodes) repeat(10) { @@ -364,7 +364,7 @@ class DevConsoleKtorModuleTest { testApplication { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) - application { devConsoleModule(sessions, sessionCodes) } + application { protectedDevConsoleModule(sessions, sessionCodes) } val session = client.exchangeSession(sessions, sessionCodes) repeat(120) { @@ -392,7 +392,7 @@ class DevConsoleKtorModuleTest { testApplication { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) - application { devConsoleModule(sessions, sessionCodes) } + application { protectedDevConsoleModule(sessions, sessionCodes) } val session = client.exchangeSession(sessions, sessionCodes) val poll = @@ -426,7 +426,7 @@ class DevConsoleKtorModuleTest { testApplication { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) - application { devConsoleModule(sessions, sessionCodes) } + application { protectedDevConsoleModule(sessions, sessionCodes) } val session = client.exchangeSession(sessions, sessionCodes, "Chrome") val refresh = @@ -470,7 +470,7 @@ class DevConsoleKtorModuleTest { testApplication { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) - application { devConsoleModule(sessions, sessionCodes) } + application { protectedDevConsoleModule(sessions, sessionCodes) } val session = client.exchangeSession(sessions, sessionCodes) val unauthenticated = client.get("/api/v1/meta") { header(HttpHeaders.Host, "localhost") } @@ -501,7 +501,7 @@ class DevConsoleKtorModuleTest { testApplication { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) - application { devConsoleModule(sessions, sessionCodes) } + application { protectedDevConsoleModule(sessions, sessionCodes) } val session = client.exchangeSession(sessions, sessionCodes) val metadata = @@ -514,13 +514,13 @@ class DevConsoleKtorModuleTest { val body = metadata.bodyAsText() assertTrue(body.contains("\"endpoint\":null")) assertTrue(body.contains("\"sensitiveFieldNames\"")) - assertTrue(RedactionPolicy.default().sensitiveFieldNames.any { body.contains("\"$it\"") }) + assertTrue(RedactionPolicy.recommended().sensitiveFieldNames.any { body.contains("\"$it\"") }) } testApplication { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { boundEndpoint = { Endpoint("127.0.0.1", 8080, BindingMode.LOOPBACK) } } } @@ -545,7 +545,7 @@ class DevConsoleKtorModuleTest { testApplication { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) - application { devConsoleModule(sessions, sessionCodes) } + application { protectedDevConsoleModule(sessions, sessionCodes) } val session = client.exchangeSession(sessions, sessionCodes) val metadata = @@ -564,7 +564,7 @@ class DevConsoleKtorModuleTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { composerEnabled = true composerAllowedHosts = setOf("auth.example.test", "api.example.test") } @@ -590,7 +590,7 @@ class DevConsoleKtorModuleTest { testApplication { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) - application { devConsoleModule(sessions, sessionCodes) } + application { protectedDevConsoleModule(sessions, sessionCodes) } val session = client.exchangeSession(sessions, sessionCodes) val streamClient = createClient { install(WebSockets) } @@ -624,7 +624,7 @@ class DevConsoleKtorModuleTest { val sessionCodes = SessionCodeAuthority(sessions) val testStreamHub = EventStreamHub() application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { streamHub = testStreamHub } } @@ -670,7 +670,7 @@ class DevConsoleKtorModuleTest { testApplication { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) - application { devConsoleModule(sessions, sessionCodes) } + application { protectedDevConsoleModule(sessions, sessionCodes) } val session = client.exchangeSession(sessions, sessionCodes) val streamClient = createClient { install(WebSockets) } @@ -705,7 +705,7 @@ class DevConsoleKtorModuleTest { CursorCodec("timeline-cursor-key".encodeToByteArray()), ) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { timeline = testTimeline } } @@ -734,7 +734,7 @@ class DevConsoleKtorModuleTest { ) val testAnnotations = InMemoryTimelineAnnotations() application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { timeline = testTimeline annotations = testAnnotations } @@ -765,7 +765,7 @@ class DevConsoleKtorModuleTest { startedAtEpochMs = 1, completedAtEpochMs = 2, capture = - NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())).capture( + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())).capture( NetworkRequestInput( "GET", "https://api.test/orders?access_token=raw-secret", @@ -785,14 +785,14 @@ class DevConsoleKtorModuleTest { startedAtEpochMs = 3, completedAtEpochMs = 4, capture = - NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())).capture( + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())).capture( NetworkRequestInput("GET", "https://api.test/not-selected"), NetworkResponseInput(200), ), ), ) NetworkTransactionRecorder( - factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())), + factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())), store = store, idProvider = { "transaction-attachment" }, executor = java.util.concurrent.Executor(Runnable::run), @@ -808,7 +808,7 @@ class DevConsoleKtorModuleTest { completedAtEpochMs = 6, ) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { networkTransactions = store } } @@ -888,7 +888,7 @@ class DevConsoleKtorModuleTest { startedAtEpochMs = index.toLong(), completedAtEpochMs = index.toLong() + 1, capture = - NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())).capture( + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())).capture( NetworkRequestInput("GET", "https://api.test/item/$index"), NetworkResponseInput(200), ), @@ -896,7 +896,7 @@ class DevConsoleKtorModuleTest { ) } application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { networkTransactions = store } } @@ -953,7 +953,7 @@ class DevConsoleKtorModuleTest { startedAtEpochMs = 1, completedAtEpochMs = 2, capture = - NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())).capture( + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())).capture( NetworkRequestInput( "GET", "https://api.test/orders", @@ -969,14 +969,14 @@ class DevConsoleKtorModuleTest { startedAtEpochMs = 3, completedAtEpochMs = 4, capture = - NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())).capture( + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())).capture( NetworkRequestInput("GET", "https://api.test/not-selected"), NetworkResponseInput(200), ), ), ) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { networkTransactions = store } } @@ -1040,7 +1040,7 @@ class DevConsoleKtorModuleTest { startedAtEpochMs = index.toLong(), completedAtEpochMs = index.toLong() + 1, capture = - NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())).capture( + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())).capture( NetworkRequestInput("GET", "https://api.test/health"), NetworkResponseInput(200), ), @@ -1048,7 +1048,7 @@ class DevConsoleKtorModuleTest { ) } application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { networkTransactions = store } } @@ -1094,14 +1094,14 @@ class DevConsoleKtorModuleTest { startedAtEpochMs = 100, completedAtEpochMs = 120, capture = - NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())).capture( + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())).capture( NetworkRequestInput("GET", "https://api.test/orders?status=open&page=2"), NetworkResponseInput(200), ), ), ) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { networkTransactions = network } } @@ -1130,7 +1130,7 @@ class DevConsoleKtorModuleTest { startedAtEpochMs = 100, completedAtEpochMs = 120, capture = - NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())).capture( + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())).capture( NetworkRequestInput("GET", "https://api.test/orders", correlationId = "corr-1"), NetworkResponseInput(200), ), @@ -1157,7 +1157,7 @@ class DevConsoleKtorModuleTest { CursorCodec("timeline-cursor-key".encodeToByteArray()), ) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { networkTransactions = network this.timeline = timeline } @@ -1188,14 +1188,14 @@ class DevConsoleKtorModuleTest { startedAtEpochMs = 1, completedAtEpochMs = 2, capture = - NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())).capture( + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())).capture( NetworkRequestInput("GET", "https://api.test/orders"), NetworkResponseInput(200), ), ), ) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { networkTransactions = store } } @@ -1237,7 +1237,7 @@ class DevConsoleKtorModuleTest { error = "boom", ) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { socketStore = sockets } } @@ -1279,7 +1279,7 @@ class DevConsoleKtorModuleTest { testApplication { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) - application { devConsoleModule(sessions, sessionCodes) } + application { protectedDevConsoleModule(sessions, sessionCodes) } val session = client.exchangeSession(sessions, sessionCodes) val metadata = @@ -1303,7 +1303,7 @@ class DevConsoleKtorModuleTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { metadata = ServerMetadata(captureCategories = listOf("socket", "mqtt")) } } @@ -1349,7 +1349,7 @@ class DevConsoleKtorModuleTest { ), ) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { socketStore = sockets } } @@ -1389,7 +1389,7 @@ class DevConsoleKtorModuleTest { ), ) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { socketStore = sockets } } @@ -1415,7 +1415,7 @@ class DevConsoleKtorModuleTest { val mocks = MockEngine(listOf(MockRule("orders", 1, path = "/orders"))) val audit = InMemoryCommandAuditLog() application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { mockEngine = mocks commandAuditLog = audit } @@ -1449,7 +1449,7 @@ class DevConsoleKtorModuleTest { val mocks = MockEngine(listOf(MockRule("orders", 1, path = "/orders"))) val audit = InMemoryCommandAuditLog() application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { mockEngine = mocks mocksEditable = true commandAuditLog = audit @@ -1486,7 +1486,7 @@ class DevConsoleKtorModuleTest { val sessionCodes = SessionCodeAuthority(sessions) val mocks = MockEngine(listOf(MockRule("orders", 1, path = "/orders"))) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { mockEngine = mocks mocksEditable = false } @@ -1513,7 +1513,7 @@ class DevConsoleKtorModuleTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { mockEngine = MockEngine(emptyList()) mocksEditable = true } @@ -1554,7 +1554,7 @@ class DevConsoleKtorModuleTest { val sessionCodes = SessionCodeAuthority(sessions) val mocks = MockEngine(emptyList()) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { mockEngine = mocks mocksEditable = true } @@ -1609,7 +1609,7 @@ class DevConsoleKtorModuleTest { val sessionCodes = SessionCodeAuthority(sessions) val mocks = MockEngine(emptyList()) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { mockEngine = mocks mocksEditable = true } @@ -1645,7 +1645,7 @@ class DevConsoleKtorModuleTest { val sessionCodes = SessionCodeAuthority(sessions) val mocks = MockEngine(emptyList()) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { mockEngine = mocks mocksEditable = true } @@ -1704,7 +1704,7 @@ class DevConsoleKtorModuleTest { ), ) application { - devConsoleModule(sessions, sessionCodes) { mockEngine = mocks } + protectedDevConsoleModule(sessions, sessionCodes) { mockEngine = mocks } } val session = client.exchangeSession(sessions, sessionCodes) @@ -1726,7 +1726,7 @@ class DevConsoleKtorModuleTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { mockEngine = MockEngine(emptyList()) mocksEditable = true } @@ -1758,7 +1758,7 @@ class DevConsoleKtorModuleTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { mockEngine = MockEngine(emptyList()) mocksEditable = true } @@ -1813,7 +1813,7 @@ class DevConsoleKtorModuleTest { ), ) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { mockEngine = mocks } } @@ -1844,7 +1844,7 @@ class DevConsoleKtorModuleTest { val audit = InMemoryCommandAuditLog() val testTimeline = InMemoryTimeline(emptyList(), CursorCodec("timeline-test-key".encodeToByteArray())) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { featureFlags = flags featureFlagsEditable = true commandAuditLog = audit @@ -1903,7 +1903,7 @@ class DevConsoleKtorModuleTest { ) } application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { stateRegistry = states } } @@ -1951,7 +1951,7 @@ class DevConsoleKtorModuleTest { }, ) } - application { devConsoleModule(sessions, sessionCodes) { stateRegistry = states } } + application { protectedDevConsoleModule(sessions, sessionCodes) { stateRegistry = states } } val session = client.exchangeSession(sessions, sessionCodes) val listing = @@ -2013,7 +2013,7 @@ class DevConsoleKtorModuleTest { } val audit = InMemoryCommandAuditLog() application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { stateRegistry = states stateMutationsEnabled = true commandAuditLog = audit @@ -2051,7 +2051,7 @@ class DevConsoleKtorModuleTest { ) val audit = InMemoryCommandAuditLog() application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { composerEnabled = true composerAllowedHosts = setOf("api.example.test") composerExecutor = executor @@ -2097,7 +2097,7 @@ class DevConsoleKtorModuleTest { }, ) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { composerEnabled = true composerAllowedHosts = setOf("api.example.test") composerExecutor = executor @@ -2156,7 +2156,7 @@ class DevConsoleKtorModuleTest { ) val audit = InMemoryCommandAuditLog() application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { composerEnabled = true composerAllowedHosts = setOf("api.example.test") composerExecutor = executor @@ -2187,7 +2187,7 @@ class DevConsoleKtorModuleTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) application { - devConsoleModule(sessions, sessionCodes) { composerEnabled = true } + protectedDevConsoleModule(sessions, sessionCodes) { composerEnabled = true } } val noAuth = client.post("/api/v1/network/transactions/any/resend") { @@ -2220,14 +2220,14 @@ class DevConsoleKtorModuleTest { startedAtEpochMs = 1, completedAtEpochMs = 2, capture = - NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())).capture( + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())).capture( NetworkRequestInput("GET", "https://api.example.test/orders"), NetworkResponseInput(200), ), ), ) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { composerEnabled = false networkTransactions = store } @@ -2255,7 +2255,7 @@ class DevConsoleKtorModuleTest { startedAtEpochMs = 1, completedAtEpochMs = 2, capture = - NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())).capture( + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())).capture( NetworkRequestInput("GET", "https://not-allowed.test/orders"), NetworkResponseInput(200), ), @@ -2263,7 +2263,7 @@ class DevConsoleKtorModuleTest { ) val audit = InMemoryCommandAuditLog() application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { composerEnabled = true composerAllowedHosts = setOf("api.example.test") networkTransactions = store @@ -2295,7 +2295,7 @@ class DevConsoleKtorModuleTest { startedAtEpochMs = 1, completedAtEpochMs = 2, capture = - NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())).capture( + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())).capture( NetworkRequestInput( "POST", "https://api.example.test/orders", @@ -2318,7 +2318,7 @@ class DevConsoleKtorModuleTest { val timeline = InMemoryTimeline(emptyList(), CursorCodec("timeline-cursor-key".encodeToByteArray())) val audit = InMemoryCommandAuditLog() application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { composerEnabled = true composerAllowedHosts = setOf("api.example.test") composerExecutor = executor @@ -2355,7 +2355,7 @@ class DevConsoleKtorModuleTest { val sessionCodes = SessionCodeAuthority(sessions) val audit = InMemoryCommandAuditLog() application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { commandAuditLog = audit composerEnabled = true composerAllowedHosts = setOf("api.example.test") @@ -2432,7 +2432,7 @@ class DevConsoleKtorModuleTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) val audit = InMemoryCommandAuditLog() - application { devConsoleModule(sessions, sessionCodes) { commandAuditLog = audit } } + application { protectedDevConsoleModule(sessions, sessionCodes) { commandAuditLog = audit } } val session = client.exchangeSession(sessions, sessionCodes) val response = @@ -2454,7 +2454,7 @@ class DevConsoleKtorModuleTest { val sessionCodes = SessionCodeAuthority(sessions) val audit = InMemoryCommandAuditLog() application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { commandAuditLog = audit composerEnabled = true } @@ -2504,7 +2504,7 @@ class DevConsoleKtorModuleTest { testApplication { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) - application { devConsoleModule(sessions, sessionCodes) { composerEnabled = true } } + application { protectedDevConsoleModule(sessions, sessionCodes) { composerEnabled = true } } val session = client.exchangeSession(sessions, sessionCodes) val imported = @@ -2554,7 +2554,7 @@ class DevConsoleKtorModuleTest { ) } application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { pushStore = pushes } } @@ -2581,11 +2581,11 @@ class DevConsoleKtorModuleTest { val simulator = PushSimulator( PushSimulationCallback { PushLifecycle.DISPLAYED }, - PushRecorder(RedactionEngine(RedactionPolicy.default()), store), + PushRecorder(RedactionEngine(RedactionPolicy.recommended()), store), ) val audit = InMemoryCommandAuditLog() application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { pushSimulator = simulator commandAuditLog = audit } @@ -2643,7 +2643,7 @@ class DevConsoleKtorModuleTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) application { - devConsoleModule(sessions, sessionCodes) + protectedDevConsoleModule(sessions, sessionCodes) } val session = client.exchangeSession( @@ -2670,7 +2670,7 @@ class DevConsoleKtorModuleTest { fun `origin rejection returns single 403 Forbidden without pipeline exception`() = testApplication { application { - devConsoleModule(SessionAuthority()) { + protectedDevConsoleModule(SessionAuthority()) { allowedHosts = setOf("localhost") } } @@ -2688,7 +2688,7 @@ class DevConsoleKtorModuleTest { fun `emits security headers on dashboard and api responses`() = testApplication { application { - devConsoleModule(SessionAuthority()) + protectedDevConsoleModule(SessionAuthority()) } val result = @@ -2726,7 +2726,7 @@ class DevConsoleKtorModuleTest { // server, and dashboard.js's `location.host` (what it actually dials over ws://) is // whichever one the browser tab is currently using. Pinning to a fixed bind address // instead of the request's Host would silently block the alias that wasn't picked. - application { devConsoleModule(SessionAuthority()) { allowedHosts = setOf("localhost") } } + application { protectedDevConsoleModule(SessionAuthority()) { allowedHosts = setOf("localhost") } } val result = client.get("/") { header(HttpHeaders.Host, "localhost:4321") } @@ -2742,7 +2742,7 @@ class DevConsoleKtorModuleTest { // below) -- its Host value must never be reflected into the CSP on the way there, or an // attacker-chosen Host header would land in a response header of the very request that's // supposed to be refused. - application { devConsoleModule(SessionAuthority()) { allowedHosts = setOf("localhost") } } + application { protectedDevConsoleModule(SessionAuthority()) { allowedHosts = setOf("localhost") } } val result = client.get("/") { header(HttpHeaders.Host, "evil.example.com:1234") } @@ -2765,7 +2765,7 @@ class DevConsoleKtorModuleTest { // legitimately always carries its own `frame-ancestors 'none'` directive (see S7), so this // asserts the attacker's *value* ('self' https://evil.example.com) never appears rather // than asserting the directive name is absent altogether. - application { devConsoleModule(SessionAuthority()) { allowedHosts = setOf("localhost") } } + application { protectedDevConsoleModule(SessionAuthority()) { allowedHosts = setOf("localhost") } } val maliciousHost = "localhost:4321; frame-ancestors 'self' https://evil.example.com" val result = client.get("/") { header(HttpHeaders.Host, maliciousHost) } @@ -2794,7 +2794,7 @@ class DevConsoleKtorModuleTest { // Application. lateinit var webSockets: ServerWebSockets application { - devConsoleModule(SessionAuthority()) + protectedDevConsoleModule(SessionAuthority()) webSockets = plugin(ServerWebSockets) } // The plugin instance is only installed once the application has actually started; @@ -2810,7 +2810,7 @@ class DevConsoleKtorModuleTest { testApplication { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) - application { devConsoleModule(sessions, sessionCodes) } + application { protectedDevConsoleModule(sessions, sessionCodes) } val session = client.exchangeSession(sessions, sessionCodes) val response = @@ -2833,7 +2833,7 @@ class DevConsoleKtorModuleTest { val flags = SessionFeatureFlags(listOf(FeatureFlag("checkout_v2", defaultValue = false))) val mocks = MockEngine(emptyList()) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { featureFlags = flags mockEngine = mocks } @@ -2879,7 +2879,7 @@ class DevConsoleKtorModuleTest { val flags = SessionFeatureFlags(listOf(FeatureFlag("checkout_v2", defaultValue = false))) flags.override("checkout_v2", "true") application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { featureFlags = flags metadata = ServerMetadata(appDisplayName = "Sample", appPackageName = "io.sample") } @@ -2939,7 +2939,7 @@ class DevConsoleKtorModuleTest { ) val audit = InMemoryCommandAuditLog() application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { this.timeline = timeline this.exportDirectory = exportDirectory commandAuditLog = audit @@ -2989,7 +2989,7 @@ class DevConsoleKtorModuleTest { testApplication { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) - application { devConsoleModule(sessions, sessionCodes) } + application { protectedDevConsoleModule(sessions, sessionCodes) } val session = client.exchangeSession(sessions, sessionCodes) val unauthenticated = @@ -3029,7 +3029,7 @@ class DevConsoleKtorModuleTest { CursorCodec("estimate-cursor-secret".encodeToByteArray()), ) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { this.timeline = timeline this.exportDirectory = exportDirectory } @@ -3069,7 +3069,7 @@ class DevConsoleKtorModuleTest { testApplication { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) - application { devConsoleModule(sessions, sessionCodes) } + application { protectedDevConsoleModule(sessions, sessionCodes) } val session = client.exchangeSession(sessions, sessionCodes) // exportLimiter allows 5 per 10 minutes -- far tighter than readQueryLimiter's 120/min the @@ -3102,7 +3102,7 @@ class DevConsoleKtorModuleTest { val sessionCodes = SessionCodeAuthority(sessions) val audit = InMemoryCommandAuditLog() application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { commandAuditLog = audit attachmentReader = { id -> when (id) { @@ -3144,7 +3144,7 @@ class DevConsoleKtorModuleTest { val bytes = byteArrayOf(1, 2, 3, 4) val audit = InMemoryCommandAuditLog() application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { commandAuditLog = audit attachmentReader = { id -> if (id == "attachment-1") bytes else null } } @@ -3185,7 +3185,7 @@ class DevConsoleKtorModuleTest { val sessionCodes = SessionCodeAuthority(sessions) val bytes = byteArrayOf(9) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { attachmentReader = { bytes } attachmentMetadataReader = { id -> when (id) { @@ -3219,7 +3219,7 @@ class DevConsoleKtorModuleTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { attachmentReader = { byteArrayOf(1) } // attachmentMetadataReader left at its default ({ null }) -- absent, not defaulted. } @@ -3249,7 +3249,7 @@ class DevConsoleKtorModuleTest { retainedTestEvent("no-attachment", 3, "logs", "No attachment"), ) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { retainedCaptures = RetainedCaptureQuery({ FakeEventStore(events) }, { "current" }) attachmentMetadataReader = { id -> when (id) { @@ -3307,7 +3307,7 @@ class DevConsoleKtorModuleTest { // *new* session is live, exactly like the dashboard reconnecting post-crash. The // crash itself lives only under "previous-run", a session id nothing in this // request ever names. - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { retainedCaptures = RetainedCaptureQuery({ FakeEventStore(events) }, { "current" }) } } @@ -3343,7 +3343,7 @@ class DevConsoleKtorModuleTest { retainedTestEvent("crash-b", 3, "crash", "Crash in run B").copy(sessionId = "run-b"), ) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { retainedCaptures = RetainedCaptureQuery({ FakeEventStore(events) }, { "run-a" }) } } @@ -3369,7 +3369,7 @@ class DevConsoleKtorModuleTest { val sessionCodes = SessionCodeAuthority(sessions) val events = listOf(retainedTestEvent("log-event", 1, "logs", "just a log")) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { retainedCaptures = RetainedCaptureQuery({ FakeEventStore(events) }, { "current" }) } } @@ -3408,7 +3408,7 @@ class DevConsoleKtorModuleTest { @Test fun `runs requires authentication`() = testApplication { - application { devConsoleModule(SessionAuthority()) } + application { protectedDevConsoleModule(SessionAuthority()) } val response = client.get("/api/v1/runs") { header(HttpHeaders.Host, "localhost") } @@ -3438,7 +3438,10 @@ class DevConsoleKtorModuleTest { val active = testSession(id = "run-active", status = StoredSessionStatus.ACTIVE, startedAtMs = 2_000) application { // Deliberately out of order -- the route must sort, not trust the provider. - devConsoleModule(sessions, sessionCodes) { sessionsProvider = { listOf(older, active, crashed) } } + protectedDevConsoleModule(sessions, sessionCodes) { + sessionsProvider = + { listOf(older, active, crashed) } + } } val session = client.exchangeSession(sessions, sessionCodes) @@ -3462,7 +3465,7 @@ class DevConsoleKtorModuleTest { @Test fun `a bug report requires authentication`() = testApplication { - application { devConsoleModule(SessionAuthority()) } + application { protectedDevConsoleModule(SessionAuthority()) } val response = client.get("/api/v1/report") { header(HttpHeaders.Host, "localhost") } @@ -3481,7 +3484,7 @@ class DevConsoleKtorModuleTest { startedAtEpochMs = 1, completedAtEpochMs = 2, capture = - NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())).capture( + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())).capture( NetworkRequestInput("GET", "https://api.test/full-timings"), NetworkResponseInput(200).withMetadata( NetworkResponseMetadata( @@ -3500,7 +3503,7 @@ class DevConsoleKtorModuleTest { ), ) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { networkTransactions = store } } @@ -3532,14 +3535,14 @@ class DevConsoleKtorModuleTest { startedAtEpochMs = 1, completedAtEpochMs = 2, capture = - NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())).capture( + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())).capture( NetworkRequestInput("GET", "https://api.test/no-timings"), NetworkResponseInput(200), ), ), ) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { networkTransactions = store } } @@ -3572,7 +3575,7 @@ class DevConsoleKtorModuleTest { startedAtEpochMs = 1, completedAtEpochMs = 2, capture = - NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())).capture( + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())).capture( NetworkRequestInput("GET", "https://api.test/pooled-connection"), // A reused pooled connection performs no DNS/connect/TLS handshake, so // those phases are legitimately absent -- only wait/receive are measured. @@ -3585,7 +3588,7 @@ class DevConsoleKtorModuleTest { ), ) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { networkTransactions = store } } diff --git a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/EvidenceAndScreenshotRoutesTest.kt b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/EvidenceAndScreenshotRoutesTest.kt index 0dc7293..0884868 100644 --- a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/EvidenceAndScreenshotRoutesTest.kt +++ b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/EvidenceAndScreenshotRoutesTest.kt @@ -68,7 +68,7 @@ class EvidenceAndScreenshotRoutesTest { @Test fun `unauthenticated requests are rejected across every evidence and screenshot route`() = testApplication { - application { devConsoleModule(SessionAuthority()) } + application { protectedDevConsoleModule(SessionAuthority()) } val unauthenticated = listOf( @@ -95,7 +95,7 @@ class EvidenceAndScreenshotRoutesTest { val audit = InMemoryCommandAuditLog() val store = FakeEvidenceStore() application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { evidenceStore = store commandAuditLog = audit } @@ -127,7 +127,7 @@ class EvidenceAndScreenshotRoutesTest { val audit = InMemoryCommandAuditLog() val store = FakeEvidenceStore() application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { evidenceStore = store commandAuditLog = audit } @@ -153,7 +153,7 @@ class EvidenceAndScreenshotRoutesTest { val audit = InMemoryCommandAuditLog() val store = FakeEvidenceStore() application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { evidenceStore = store commandAuditLog = audit } @@ -181,7 +181,7 @@ class EvidenceAndScreenshotRoutesTest { testApplication { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) - application { devConsoleModule(sessions, sessionCodes) } + application { protectedDevConsoleModule(sessions, sessionCodes) } val session = approvedSession(sessions, sessionCodes) val listed = client.get("/api/v1/evidence") { authHeaders(session) } @@ -203,7 +203,7 @@ class EvidenceAndScreenshotRoutesTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) val store = FakeEvidenceStore() - application { devConsoleModule(sessions, sessionCodes) { evidenceStore = store } } + application { protectedDevConsoleModule(sessions, sessionCodes) { evidenceStore = store } } val session = approvedSession(sessions, sessionCodes) val response = @@ -233,7 +233,7 @@ class EvidenceAndScreenshotRoutesTest { val timeline = InMemoryTimeline(emptyList(), CursorCodec(ByteArray(16))) timeline.append(timelineEvent(id = "log-1", pluginId = "logs", summary = "just a log line")) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { this.timeline = timeline evidenceStore = store } @@ -275,7 +275,7 @@ class EvidenceAndScreenshotRoutesTest { val timeline = InMemoryTimeline(emptyList(), CursorCodec(ByteArray(16))) timeline.append(timelineEvent(id = "event-1", summary = "x".repeat(600))) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { this.timeline = timeline evidenceStore = store } @@ -299,7 +299,7 @@ class EvidenceAndScreenshotRoutesTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) val store = FakeEvidenceStore() - application { devConsoleModule(sessions, sessionCodes) { evidenceStore = store } } + application { protectedDevConsoleModule(sessions, sessionCodes) { evidenceStore = store } } val session = approvedSession(sessions, sessionCodes) val response = @@ -323,7 +323,7 @@ class EvidenceAndScreenshotRoutesTest { networkStore.record(networkTransaction("tx-1")) networkStore.record(networkTransaction("tx-2")) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { networkTransactions = networkStore evidenceStore = store } @@ -355,7 +355,7 @@ class EvidenceAndScreenshotRoutesTest { val networkStore = InMemoryNetworkTransactionStore(NetworkCursorCodec(ByteArray(16))) repeat(3) { networkStore.record(networkTransaction("tx-$it")) } application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { networkTransactions = networkStore evidenceStore = store } @@ -399,7 +399,7 @@ class EvidenceAndScreenshotRoutesTest { val networkStore = InMemoryNetworkTransactionStore(NetworkCursorCodec(ByteArray(16))) networkStore.record(networkTransaction("tx-1")) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { networkTransactions = networkStore evidenceStore = store } @@ -435,7 +435,7 @@ class EvidenceAndScreenshotRoutesTest { networkTransaction("tx-1", startedAtEpochMs = 1_000, completedAtEpochMs = 1_250, status = 503), ) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { networkTransactions = networkStore evidenceStore = store } @@ -478,7 +478,7 @@ class EvidenceAndScreenshotRoutesTest { ), ) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { this.timeline = timeline evidenceStore = store } @@ -517,7 +517,7 @@ class EvidenceAndScreenshotRoutesTest { ), ) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { this.timeline = timeline evidenceStore = store } @@ -563,7 +563,7 @@ class EvidenceAndScreenshotRoutesTest { ), ) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { this.timeline = timeline evidenceStore = store attachmentMetadataReader = { id -> @@ -608,7 +608,7 @@ class EvidenceAndScreenshotRoutesTest { ), ) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { this.timeline = timeline evidenceStore = store attachmentMetadataReader = { id -> @@ -643,7 +643,7 @@ class EvidenceAndScreenshotRoutesTest { val networkStore = InMemoryNetworkTransactionStore(NetworkCursorCodec(ByteArray(16))) networkStore.record(networkTransaction("tx-1")) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { networkTransactions = networkStore evidenceStore = store } @@ -681,7 +681,7 @@ class EvidenceAndScreenshotRoutesTest { ), ) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { this.timeline = timeline evidenceStore = store } @@ -734,7 +734,7 @@ class EvidenceAndScreenshotRoutesTest { ), ) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { this.timeline = timeline evidenceStore = store } @@ -777,7 +777,7 @@ class EvidenceAndScreenshotRoutesTest { ), ) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { this.socketStore = socketStore evidenceStore = store } @@ -807,7 +807,7 @@ class EvidenceAndScreenshotRoutesTest { val pushStore = InMemoryPushStore() pushStore.append(PushEvent(provider = "fcm", data = mapOf("k" to "v"), lifecycle = PushLifecycle.DISPLAYED)) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { this.pushStore = pushStore evidenceStore = store } @@ -835,7 +835,7 @@ class EvidenceAndScreenshotRoutesTest { val networkStore = InMemoryNetworkTransactionStore(NetworkCursorCodec(ByteArray(16))) networkStore.record(networkTransaction("tx-1")) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { networkTransactions = networkStore evidenceStore = store } @@ -881,7 +881,7 @@ class EvidenceAndScreenshotRoutesTest { val networkStore = InMemoryNetworkTransactionStore(NetworkCursorCodec(ByteArray(16))) networkStore.record(networkTransaction("tx-1")) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { this.timeline = timeline this.networkTransactions = networkStore this.exportDirectory = exportDirectory @@ -947,7 +947,7 @@ class EvidenceAndScreenshotRoutesTest { val sessionCodes = SessionCodeAuthority(sessions) val audit = InMemoryCommandAuditLog() application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { commandAuditLog = audit screenshotCapture = { result } } @@ -968,7 +968,7 @@ class EvidenceAndScreenshotRoutesTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { screenshotCapture = { ScreenshotResult.Captured( attachmentId = "attach-1", @@ -999,7 +999,7 @@ class EvidenceAndScreenshotRoutesTest { val sessionCodes = SessionCodeAuthority(sessions) var captured = false application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { screenshotCapture = { captured = true ScreenshotResult.Captured("a", "e", 1, 1, 1) @@ -1075,7 +1075,7 @@ private fun networkTransaction( startedAtEpochMs = startedAtEpochMs, completedAtEpochMs = completedAtEpochMs, capture = - NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())).capture( + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())).capture( NetworkRequestInput("GET", "https://api.test/orders"), NetworkResponseInput(status), ), diff --git a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/ExceptionBoundaryTest.kt b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/ExceptionBoundaryTest.kt index 23e8763..cad1480 100644 --- a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/ExceptionBoundaryTest.kt +++ b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/ExceptionBoundaryTest.kt @@ -56,7 +56,7 @@ class ExceptionBoundaryTest { val sessionCodes = SessionCodeAuthority(sessions) val secretMarker = "sqlite disk I/O error at offset 0xDEADBEEF" application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { databaseInspector = ThrowingDatabaseInspector(secretMarker) } } @@ -82,7 +82,7 @@ class ExceptionBoundaryTest { val sessionCodes = SessionCodeAuthority(sessions) val secretMarker = "column 'hunter2_api_key' does not exist" application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { databaseInspector = ThrowingDatabaseInspector(secretMarker) databaseEditable = true } @@ -108,7 +108,7 @@ class ExceptionBoundaryTest { val sessionCodes = SessionCodeAuthority(sessions) val secretMarker = "/private/var/mobile/Containers/Data/host-only-path" application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { fileInspector = ThrowingFileInspector(secretMarker) } } @@ -140,7 +140,7 @@ class ExceptionBoundaryTest { val sessionCodes = SessionCodeAuthority(sessions) val secretMarker = "audit-sink-unavailable: replica lease lost at 0xFEEDFACE" application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { commandAuditLog = ThrowingCommandAuditLog(secretMarker) } } @@ -168,7 +168,7 @@ class ExceptionBoundaryTest { testApplication { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) - application { devConsoleModule(sessions, sessionCodes) } + application { protectedDevConsoleModule(sessions, sessionCodes) } val session = approvedSession(sessions, sessionCodes) val response = @@ -193,7 +193,7 @@ class ExceptionBoundaryTest { testApplication { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) - application { devConsoleModule(sessions, sessionCodes) } + application { protectedDevConsoleModule(sessions, sessionCodes) } val session = approvedSession(sessions, sessionCodes) val response = @@ -211,7 +211,7 @@ class ExceptionBoundaryTest { testApplication { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) - application { devConsoleModule(sessions, sessionCodes) } + application { protectedDevConsoleModule(sessions, sessionCodes) } val response = client.get("/health") { diff --git a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/FeatureFlagAndExportBundleRoutesTest.kt b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/FeatureFlagAndExportBundleRoutesTest.kt index 760acb7..db26a2a 100644 --- a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/FeatureFlagAndExportBundleRoutesTest.kt +++ b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/FeatureFlagAndExportBundleRoutesTest.kt @@ -54,7 +54,7 @@ class FeatureFlagAndExportBundleRoutesTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { featureFlags = SessionFeatureFlags(listOf(FeatureFlag.ofBoolean("newCheckout", false))) // Every default category except "state" -- so the flag routes' STATE gate is the // only thing standing between the caller and the flag list. @@ -80,7 +80,7 @@ class FeatureFlagAndExportBundleRoutesTest { val sessionCodes = SessionCodeAuthority(sessions) val flags = SessionFeatureFlags(listOf(FeatureFlag.ofBoolean("newCheckout", false))) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { featureFlags = flags featureFlagsEditable = false } @@ -105,7 +105,7 @@ class FeatureFlagAndExportBundleRoutesTest { val sessionCodes = SessionCodeAuthority(sessions) val audit = InMemoryCommandAuditLog() application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { featureFlags = SessionFeatureFlags(listOf(FeatureFlag.ofBoolean("newCheckout", false))) featureFlagsEditable = true commandAuditLog = audit @@ -140,7 +140,7 @@ class FeatureFlagAndExportBundleRoutesTest { val networkStore = InMemoryNetworkTransactionStore(NetworkCursorCodec(ByteArray(16))) networkStore.record(networkTransaction("tx-1").withSessionId("current")) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { this.timeline = timeline this.networkTransactions = networkStore this.exportDirectory = exportDirectory @@ -195,9 +195,9 @@ class FeatureFlagAndExportBundleRoutesTest { ).withSessionId("current"), ) application { - // redactionPolicy defaults to RedactionPolicy.default(), which masks the + // redactionPolicy defaults to RedactionPolicy.recommended(), which masks the // Cookie header the permissive capture-time policy above let through. - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { this.networkTransactions = networkStore } } @@ -223,7 +223,7 @@ private fun networkTransaction(id: String): NetworkTransaction = startedAtEpochMs = 1, completedAtEpochMs = 2, capture = - NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())).capture( + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())).capture( NetworkRequestInput("GET", "https://api.test/orders"), NetworkResponseInput(200), ), diff --git a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/InspectorRoutesTest.kt b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/InspectorRoutesTest.kt index b29db77..69a7ca8 100644 --- a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/InspectorRoutesTest.kt +++ b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/InspectorRoutesTest.kt @@ -54,7 +54,7 @@ class InspectorRoutesTest { @Test fun `unauthenticated requests are rejected across preferences database and files routes`() = testApplication { - application { devConsoleModule(SessionAuthority()) } + application { protectedDevConsoleModule(SessionAuthority()) } val unauthenticated = listOf( @@ -112,7 +112,7 @@ class InspectorRoutesTest { ), ) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { preferencesInspector = inspector preferencesEditable = true } @@ -142,7 +142,7 @@ class InspectorRoutesTest { val sessionCodes = SessionCodeAuthority(sessions) val inspector = FakePreferencesInspector(filesResult = emptyList()) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { preferencesInspector = inspector preferencesEditable = true } @@ -176,7 +176,7 @@ class InspectorRoutesTest { val sessionCodes = SessionCodeAuthority(sessions) val rejectingInspector = FakePreferencesInspector(filesResult = emptyList(), putResult = false) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { preferencesInspector = rejectingInspector preferencesEditable = true } @@ -221,7 +221,7 @@ class InspectorRoutesTest { ), ) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { preferencesInspector = inspector preferencesEditable = true } @@ -245,7 +245,7 @@ class InspectorRoutesTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { // preferencesInspector left null on purpose. preferencesEditable = true } @@ -269,7 +269,7 @@ class InspectorRoutesTest { val sessionCodes = SessionCodeAuthority(sessions) val inspector = FakePreferencesInspector(filesResult = emptyList(), removeResult = true) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { preferencesInspector = inspector preferencesEditable = true } @@ -300,7 +300,7 @@ class InspectorRoutesTest { val sessionCodes = SessionCodeAuthority(sessions) val audit = InMemoryCommandAuditLog() application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { preferencesInspector = FakePreferencesInspector(filesResult = emptyList()) preferencesEditable = false commandAuditLog = audit @@ -343,7 +343,7 @@ class InspectorRoutesTest { ), ) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { databaseInspector = inspector } } @@ -400,7 +400,7 @@ class InspectorRoutesTest { ), ) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { databaseInspector = inspector } } @@ -438,7 +438,7 @@ class InspectorRoutesTest { ), ) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { databaseInspector = inspector databaseEditable = true } @@ -468,7 +468,7 @@ class InspectorRoutesTest { ), ) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { databaseInspector = inspector databaseEditable = true } @@ -502,7 +502,7 @@ class InspectorRoutesTest { val sessionCodes = SessionCodeAuthority(sessions) val inspector = FakeDatabaseInspector() application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { databaseInspector = inspector databaseEditable = true } @@ -534,7 +534,7 @@ class InspectorRoutesTest { val sessionCodes = SessionCodeAuthority(sessions) val inspector = FakeDatabaseInspector(executeResult = DatabaseExecResult.Write(affectedRows = 2)) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { databaseInspector = inspector databaseEditable = true } @@ -566,7 +566,7 @@ class InspectorRoutesTest { ), ) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { databaseInspector = inspector databaseEditable = false } @@ -591,7 +591,7 @@ class InspectorRoutesTest { val sessionCodes = SessionCodeAuthority(sessions) val inspector = FakeDatabaseInspector(executeResult = DatabaseExecResult.Failed("no such table: ghost")) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { databaseInspector = inspector databaseEditable = true } @@ -622,7 +622,7 @@ class InspectorRoutesTest { previewResult = FilePreviewData.Text("hello world", truncated = false), ) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { fileInspector = inspector } } @@ -666,7 +666,7 @@ class InspectorRoutesTest { testApplication { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) - application { devConsoleModule(sessions, sessionCodes) } + application { protectedDevConsoleModule(sessions, sessionCodes) } val session = approvedSession(sessions, sessionCodes) val response = @@ -702,7 +702,7 @@ class InspectorRoutesTest { deleteProvider = { _, path -> !path.contains("..") }, ) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { fileInspector = inspector filesEditable = true } @@ -731,7 +731,7 @@ class InspectorRoutesTest { val sessionCodes = SessionCodeAuthority(sessions) val inspector = FakeFileInspector(rootNames = listOf("storage")) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { fileInspector = inspector filesEditable = false } @@ -766,7 +766,7 @@ class InspectorRoutesTest { "a.txt" }) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { fileInspector = inspector filesEditable = true } @@ -804,7 +804,7 @@ class InspectorRoutesTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { preferencesInspector = FakePreferencesInspector(filesResult = emptyList()) preferencesEditable = true } @@ -837,7 +837,7 @@ class InspectorRoutesTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { databaseInspector = FakeDatabaseInspector( executeResult = @@ -876,7 +876,7 @@ class InspectorRoutesTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { fileInspector = FakeFileInspector(rootNames = listOf("storage"), deleteProvider = { _, _ -> true }) filesEditable = true } @@ -908,7 +908,7 @@ class InspectorRoutesTest { val sessionCodes = SessionCodeAuthority(sessions) val inspector = FakeFileInspector(rootNames = listOf("storage")) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { fileInspector = inspector filesEditable = false } @@ -942,7 +942,7 @@ class InspectorRoutesTest { val inspector = FakeFileInspector(rootNames = listOf("storage"), createProvider = { _, path, _ -> path == "new.txt" }) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { fileInspector = inspector filesEditable = true } @@ -981,7 +981,7 @@ class InspectorRoutesTest { val sessionCodes = SessionCodeAuthority(sessions) val inspector = FakeFileInspector(rootNames = listOf("storage")) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { fileInspector = inspector filesEditable = true } @@ -1006,7 +1006,7 @@ class InspectorRoutesTest { val inspector = FakeFileInspector(rootNames = listOf("storage"), replaceProvider = { _, path, _ -> path == "a.txt" }) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { fileInspector = inspector filesEditable = true } @@ -1041,7 +1041,7 @@ class InspectorRoutesTest { renameProvider = { _, _, newPath -> newPath == "b.txt" }, ) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { fileInspector = inspector filesEditable = true } @@ -1078,7 +1078,7 @@ class InspectorRoutesTest { val sessionCodes = SessionCodeAuthority(sessions) val inspector = FakeFileInspector(rootNames = listOf("storage")) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { fileInspector = inspector filesEditable = false } @@ -1108,7 +1108,7 @@ class InspectorRoutesTest { readBytesProvider = { _, path -> if (path == "a.bin") bytes else null }, ) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { fileInspector = inspector filesEditable = false } @@ -1137,7 +1137,7 @@ class InspectorRoutesTest { readBytesProvider = { _, path -> if (path == "a.bin") bytes else null }, ) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { fileInspector = inspector filesEditable = true } @@ -1176,7 +1176,7 @@ class InspectorRoutesTest { readBytesProvider = { _, path -> if (path == maliciousName) bytes else null }, ) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { fileInspector = inspector filesEditable = true } @@ -1206,7 +1206,7 @@ class InspectorRoutesTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { fileInspector = FakeFileInspector(rootNames = listOf("storage")) filesEditable = true } @@ -1236,7 +1236,7 @@ class InspectorRoutesTest { /** * Mints an authenticated [BrowserSession] the only way an external caller can: issue a session code - * and exchange it over the real HTTP route. Must be called after `application { devConsoleModule(...) }` + * and exchange it over the real HTTP route. Must be called after `application { protectedDevConsoleModule(...) }` * has been registered, since the exchange request is what triggers the test application to start. */ private suspend fun ApplicationTestBuilder.approvedSession( diff --git a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/KtorLocalServerEngineTest.kt b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/KtorLocalServerEngineTest.kt index e999e78..922d0e4 100644 --- a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/KtorLocalServerEngineTest.kt +++ b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/KtorLocalServerEngineTest.kt @@ -54,7 +54,13 @@ class KtorLocalServerEngineTest { fun `falls forward through a requested loopback port range`() = runBlocking { ServerSocket(0).use { occupied -> - val engine = KtorLocalServerEngine() + val engine = + KtorLocalServerEngine() + .withBrowserSecurity(io.devconsole.api.BrowserSecurity.SESSION_CODE) + .withNetworkProtection( + io.devconsole.api.NetworkProtection + .recommended(), + ) try { val result = engine.start( @@ -78,7 +84,13 @@ class KtorLocalServerEngineTest { // never terminates TLS), so the CSP's connect-src must name that exact host:port rather // than the old blanket "ws: wss:" (any host, any scheme) -- see the CSP-building comment // in devConsoleModule for the Safari same-origin-ws compatibility reasoning. - val engine = KtorLocalServerEngine() + val engine = + KtorLocalServerEngine() + .withBrowserSecurity(io.devconsole.api.BrowserSecurity.SESSION_CODE) + .withNetworkProtection( + io.devconsole.api.NetworkProtection + .recommended(), + ) val started = engine.start(StartRequest(BindingMode.LOOPBACK, 8520..8539)) assertTrue(started is ServerStartResult.Started) started as ServerStartResult.Started @@ -106,7 +118,13 @@ class KtorLocalServerEngineTest { // dashboard.js's WebSocket actually dials -- connect-src must follow that alias, not the // server's own bind address ("127.0.0.1"), or the ws:// upgrade is silently blocked // (worse in Safari, which doesn't reliably treat bare 'self' as covering it either). - val engine = KtorLocalServerEngine() + val engine = + KtorLocalServerEngine() + .withBrowserSecurity(io.devconsole.api.BrowserSecurity.SESSION_CODE) + .withNetworkProtection( + io.devconsole.api.NetworkProtection + .recommended(), + ) val started = engine.start(StartRequest(BindingMode.LOOPBACK, 8580..8599)) assertTrue(started is ServerStartResult.Started) started as ServerStartResult.Started @@ -137,7 +155,13 @@ class KtorLocalServerEngineTest { // death. This can't fault-inject a throwing embedded engine without a bigger refactor // (it's constructed inline inside start()), but it does prove the happy path actually // clears every piece of state stop() is responsible for, twice over. - val engine = KtorLocalServerEngine() + val engine = + KtorLocalServerEngine() + .withBrowserSecurity(io.devconsole.api.BrowserSecurity.SESSION_CODE) + .withNetworkProtection( + io.devconsole.api.NetworkProtection + .recommended(), + ) val first = engine.start(StartRequest(BindingMode.LOOPBACK, 8540..8559)) assertTrue(first is ServerStartResult.Started) @@ -154,7 +178,13 @@ class KtorLocalServerEngineTest { @Test fun `stop is a safe no-op when the engine was never started`() = runBlocking { - val engine = KtorLocalServerEngine() + val engine = + KtorLocalServerEngine() + .withBrowserSecurity(io.devconsole.api.BrowserSecurity.SESSION_CODE) + .withNetworkProtection( + io.devconsole.api.NetworkProtection + .recommended(), + ) // Must not throw even though `engine` (the private EmbeddedServer field) is null. engine.stop() @@ -164,7 +194,13 @@ class KtorLocalServerEngineTest { @Test fun `LAN mode binds to a real non-loopback address`() = runBlocking { - val engine = KtorLocalServerEngine() + val engine = + KtorLocalServerEngine() + .withBrowserSecurity(io.devconsole.api.BrowserSecurity.SESSION_CODE) + .withNetworkProtection( + io.devconsole.api.NetworkProtection + .recommended(), + ) try { val result = engine.start(StartRequest(BindingMode.LAN, 8180..8199)) @@ -181,7 +217,15 @@ class KtorLocalServerEngineTest { @Test fun `LAN mode reports no eligible network when no interface qualifies`() = runBlocking { - val engine = KtorLocalServerEngine(lanInterfaces = { emptyList() }) + val engine = + KtorLocalServerEngine(lanInterfaces = { + emptyList() + }) + .withBrowserSecurity(io.devconsole.api.BrowserSecurity.SESSION_CODE) + .withNetworkProtection( + io.devconsole.api.NetworkProtection + .recommended(), + ) try { val result = engine.start(StartRequest(BindingMode.LAN, 8180..8199)) @@ -218,7 +262,13 @@ class KtorLocalServerEngineTest { @Test fun `a fresh LAN engine reports no bind-address change against its own real interfaces`() = runBlocking { - val engine = KtorLocalServerEngine() + val engine = + KtorLocalServerEngine() + .withBrowserSecurity(io.devconsole.api.BrowserSecurity.SESSION_CODE) + .withNetworkProtection( + io.devconsole.api.NetworkProtection + .recommended(), + ) try { engine.start(StartRequest(BindingMode.LAN, 8200..8219)) @@ -235,7 +285,11 @@ class KtorLocalServerEngineTest { KtorLocalServerEngine( composerEnabled = true, stateMutationsEnabled = true, - ) + ).withBrowserSecurity(io.devconsole.api.BrowserSecurity.SESSION_CODE) + .withNetworkProtection( + io.devconsole.api.NetworkProtection + .recommended(), + ) val started = engine.start(StartRequest(BindingMode.LOOPBACK, 8460..8479)) assertTrue(started is ServerStartResult.Started) started as ServerStartResult.Started @@ -270,7 +324,10 @@ class KtorLocalServerEngineTest { sessionAuthority = authority, composerEnabled = true, composerAllowedHosts = setOf("api.example.test"), - redactionPolicy = RedactionPolicy.default().copy(sensitiveFieldNames = setOf("x-tenant-secret")), + redactionPolicy = + RedactionPolicy.recommended().copy( + sensitiveFieldNames = setOf("x-tenant-secret"), + ), commandAuditLog = audit, composerCollections = collections, composerExecutor = @@ -280,7 +337,11 @@ class KtorLocalServerEngineTest { ComposerResponse(statusCode = 202, body = "accepted") }, ), - ) + ).withBrowserSecurity(io.devconsole.api.BrowserSecurity.SESSION_CODE) + .withNetworkProtection( + io.devconsole.api.NetworkProtection + .recommended(), + ) val started = engine.start(StartRequest(BindingMode.LOOPBACK, 8480..8499)) assertTrue(started is ServerStartResult.Started) started as ServerStartResult.Started @@ -337,10 +398,14 @@ class KtorLocalServerEngineTest { pushSimulator = PushSimulator( PushSimulationCallback { PushLifecycle.DISPLAYED }, - PushRecorder(RedactionEngine(RedactionPolicy.default()), pushes), + PushRecorder(RedactionEngine(RedactionPolicy.recommended()), pushes), ), annotations = annotations, - ) + ).withBrowserSecurity(io.devconsole.api.BrowserSecurity.SESSION_CODE) + .withNetworkProtection( + io.devconsole.api.NetworkProtection + .recommended(), + ) val started = engine.start(StartRequest(BindingMode.LOOPBACK, 8500..8519)) assertTrue(started is ServerStartResult.Started) started as ServerStartResult.Started 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 index 7719127..b323eb6 100644 --- 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 @@ -48,7 +48,7 @@ class NetworkClearRouteTest { fun `clearing requires an authenticated session`() = testApplication { val store = networkStore("tx-1") - application { devConsoleModule(SessionAuthority()) { networkTransactions = store } } + application { protectedDevConsoleModule(SessionAuthority()) { networkTransactions = store } } val response = client.delete("/api/v1/network/transactions") { header(HttpHeaders.Host, "localhost") } @@ -65,7 +65,7 @@ class NetworkClearRouteTest { val audit = InMemoryCommandAuditLog() val store = networkStore("tx-1") application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { networkTransactions = store commandAuditLog = audit } @@ -92,7 +92,7 @@ class NetworkClearRouteTest { val audit = InMemoryCommandAuditLog() val store = networkStore("tx-1", "tx-2") application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { networkTransactions = store commandAuditLog = audit } @@ -119,7 +119,7 @@ class NetworkClearRouteTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) val store = networkStore("tx-1", "tx-2") - application { devConsoleModule(sessions, sessionCodes) { networkTransactions = store } } + application { protectedDevConsoleModule(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")) @@ -143,7 +143,7 @@ class NetworkClearRouteTest { val audit = InMemoryCommandAuditLog() val store = networkStore("tx-1") application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { networkTransactions = store commandAuditLog = audit metadata = ServerMetadata(captureCategories = listOf("logs")) @@ -170,7 +170,7 @@ class NetworkClearRouteTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) val store = networkStore() - application { devConsoleModule(sessions, sessionCodes) { networkTransactions = store } } + application { protectedDevConsoleModule(sessions, sessionCodes) { networkTransactions = store } } val session = approvedSession(sessions, sessionCodes) val response = client.delete("/api/v1/network/transactions") { controlHeaders(session) } @@ -188,7 +188,7 @@ private fun networkStore(vararg ids: String): InMemoryNetworkTransactionStore = startedAtEpochMs = index.toLong() + 1, completedAtEpochMs = index.toLong() + 2, capture = - NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())).capture( + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())).capture( NetworkRequestInput("GET", "https://api.test/$id"), NetworkResponseInput(200), ), diff --git a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/NetworkTransactionQueryEquivalenceTest.kt b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/NetworkTransactionQueryEquivalenceTest.kt index fbb538d..1ba2023 100644 --- a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/NetworkTransactionQueryEquivalenceTest.kt +++ b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/NetworkTransactionQueryEquivalenceTest.kt @@ -48,7 +48,7 @@ import java.net.URLEncoder * multi-dimension combination, and cursor pagination. */ class NetworkTransactionQueryEquivalenceTest { - private val captureFactory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())) + private val captureFactory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())) private fun store(): InMemoryNetworkTransactionStore = InMemoryNetworkTransactionStore(NetworkCursorCodec("query-equivalence-key".encodeToByteArray())).apply { @@ -139,7 +139,7 @@ class NetworkTransactionQueryEquivalenceTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { networkTransactions = transactionStore } } @@ -282,7 +282,7 @@ class NetworkTransactionQueryEquivalenceTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { networkTransactions = transactionStore } } diff --git a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/ProtectedModuleFixture.kt b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/ProtectedModuleFixture.kt new file mode 100644 index 0000000..6302207 --- /dev/null +++ b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/ProtectedModuleFixture.kt @@ -0,0 +1,37 @@ +/** + * @author Shakib + * @since 19/10/26 + */ +package io.devconsole.server.ktor + +import io.devconsole.api.BrowserSecurity +import io.devconsole.api.EditingCapabilities +import io.devconsole.api.NetworkProtection +import io.devconsole.security.RedactionPolicy +import io.devconsole.server.api.SessionAuthority +import io.devconsole.server.api.SessionCodeAuthority +import io.ktor.server.application.Application + +/** Explicit opt-ins for tests of authentication, redaction, budgets, and read-only gates. */ +internal fun Application.protectedDevConsoleModule( + sessionAuthority: SessionAuthority, + sessionCodeAuthority: SessionCodeAuthority = SessionCodeAuthority(sessionAuthority), + configure: DevConsoleModuleConfig.() -> Unit = {}, +) { + devConsoleModule(sessionAuthority, sessionCodeAuthority) { + browserSecurity = BrowserSecurity.SESSION_CODE + networkProtection = NetworkProtection.recommended() + redactionPolicy = RedactionPolicy.recommended() + val editing = EditingCapabilities.readOnly() + mocksEditable = editing.mocks + captureRulesEditable = editing.captureRules + featureFlagsEditable = editing.featureFlags + preferencesEditable = editing.preferences + databaseEditable = editing.database + filesEditable = editing.files + composerEnabled = false + composerHostsEditable = false + stateMutationsEnabled = false + configure() + } +} diff --git a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/RedactingBoundariesTest.kt b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/RedactingBoundariesTest.kt index dd7e703..e95ca15 100644 --- a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/RedactingBoundariesTest.kt +++ b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/RedactingBoundariesTest.kt @@ -13,7 +13,7 @@ import org.junit.Assert.assertTrue import org.junit.Test class RedactingBoundariesTest { - private val redaction = RedactionEngine(RedactionPolicy.default()) + private val redaction = RedactionEngine(RedactionPolicy.recommended()) @Test fun `audit read boundary sanitizes legacy raw records`() { diff --git a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/RemoteConfigRoutesTest.kt b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/RemoteConfigRoutesTest.kt index e0632b3..3545c5c 100644 --- a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/RemoteConfigRoutesTest.kt +++ b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/RemoteConfigRoutesTest.kt @@ -54,7 +54,7 @@ class RemoteConfigRoutesTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { remoteConfigSnapshots = { listOf(snapshot()) } } } @@ -71,7 +71,7 @@ class RemoteConfigRoutesTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { remoteConfigSnapshots = { listOf(snapshot()) } metadata = ServerMetadata(captureCategories = listOf("network", "logs")) } @@ -90,7 +90,7 @@ class RemoteConfigRoutesTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { remoteConfigSnapshots = { listOf(snapshot()) } } } @@ -114,7 +114,7 @@ class RemoteConfigRoutesTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { remoteConfigSnapshots = { listOf( RemoteConfigSnapshot( @@ -141,7 +141,7 @@ class RemoteConfigRoutesTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { remoteConfigSnapshots = { listOf(snapshot(unavailableReason = "disabled-build", entries = emptyList())) } } @@ -158,7 +158,7 @@ class RemoteConfigRoutesTest { testApplication { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) - application { devConsoleModule(sessions, sessionCodes) {} } + application { protectedDevConsoleModule(sessions, sessionCodes) {} } val session = approvedSession(sessions, sessionCodes) val response = client.get("/api/v1/remote-config") { authed(session) } @@ -173,7 +173,7 @@ class RemoteConfigRoutesTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { remoteConfigSnapshots = { listOf( snapshot( @@ -197,7 +197,7 @@ class RemoteConfigRoutesTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { remoteConfigSnapshots = { listOf( snapshot( diff --git a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/SecurityOptInTest.kt b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/SecurityOptInTest.kt new file mode 100644 index 0000000..dec9c61 --- /dev/null +++ b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/SecurityOptInTest.kt @@ -0,0 +1,271 @@ +/** + * @author Shakib + * @since 19/10/26 + */ +package io.devconsole.server.ktor + +import io.devconsole.api.BrowserSecurity +import io.devconsole.api.DevConsoleConfig +import io.devconsole.api.NetworkProtection +import io.devconsole.composer.ComposerExecutor +import io.devconsole.composer.ComposerResponse +import io.devconsole.composer.ComposerTransport +import io.devconsole.network.BodyPreview +import io.devconsole.network.NetworkCaptureFactory +import io.devconsole.network.NetworkExport +import io.devconsole.network.NetworkRequestInput +import io.devconsole.network.NetworkTransaction +import io.devconsole.security.RedactionEngine +import io.devconsole.security.RedactionPolicy +import io.devconsole.server.api.SessionAuthority +import io.devconsole.server.api.SessionCodeAuthority +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.testApplication +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class SecurityOptInTest { + @Test + fun `default config preserves authorization cookies token fields and export values`() { + val config = DevConsoleConfig() + val capture = capture(config) + + assertEquals("Bearer header-secret", capture.request.headers["Authorization"]) + assertEquals("session=cookie-secret", capture.request.headers["Cookie"]) + assertEquals("query-secret", capture.request.url.query["access_token"]) + assertEquals("""{"token":"body-secret","":"empty-key"}""", (capture.request.body as BodyPreview.Text).value) + val transaction = NetworkTransaction("default", 0, 1, capture) + listOf( + NetworkExport.toCurl(capture), + NetworkExport.toHarTransactions(listOf(transaction)), + NetworkExport.toPostman(listOf(transaction)), + ).forEach { output -> + assertTrue(output.contains("header-secret")) + assertTrue(output.contains("cookie-secret")) + assertTrue(output.contains("body-secret")) + } + } + + @Test + fun `recommended config masks historical fields while preserving authorization as before`() { + val config = DevConsoleConfig(redactionPolicy = RedactionPolicy.recommended()) + val capture = capture(config) + + // Authorization was intentionally absent from the old built-in set, and remains absent. + assertEquals("Bearer header-secret", capture.request.headers["Authorization"]) + assertEquals("", capture.request.headers["Cookie"]) + assertEquals("", capture.request.url.query["access_token"]) + assertFalse((capture.request.body as BodyPreview.Text).value.contains("body-secret")) + val transaction = NetworkTransaction("recommended", 0, 1, capture) + listOf( + NetworkExport.toCurl(capture), + NetworkExport.toHarTransactions(listOf(transaction)), + NetworkExport.toPostman(listOf(transaction)), + ).forEach { output -> + assertFalse(output.contains("cookie-secret")) + assertFalse(output.contains("body-secret")) + } + } + + @Test + fun `hosts can explicitly add authorization to the recommended policy`() { + val recommended = RedactionPolicy.recommended() + val config = + DevConsoleConfig( + redactionPolicy = + recommended.copy( + sensitiveFieldNames = + recommended.sensitiveFieldNames + "authorization", + ), + ) + assertEquals("", capture(config).request.headers["Authorization"]) + } + + @Test + fun `default Composer permits an arbitrary destination and preserves response metadata`() = + testApplication { + var destination = "" + application { + devConsoleModule(SessionAuthority()) { + composerExecutor = + ComposerExecutor( + ComposerTransport { request -> + destination = request.url + ComposerResponse(statusCode = 200) + }, + ) + } + } + val response = + client.post("/api/v1/composer/execute") { + header(HttpHeaders.ContentType, ContentType.Application.FormUrlEncoded) + setBody("method=GET&url=https%3A%2F%2Fanywhere.example%2Forders%3Ftoken%3Draw-token") + } + assertEquals(HttpStatusCode.OK, response.status) + assertEquals("https://anywhere.example/orders?token=raw-token", destination) + assertTrue(response.bodyAsText().contains("raw-token")) + } + + @Test + fun `default server accepts 200 rapid reads with an unknown Host`() = + testApplication { + application { devConsoleModule(SessionAuthority()) } + repeat(200) { + val response = client.get("/api/v1/meta") { header(HttpHeaders.Host, "unknown.example:8080") } + assertEquals(HttpStatusCode.OK, response.status) + assertTrue(response.headers["Content-Security-Policy"].orEmpty().contains("ws://unknown.example:8080")) + } + } + + @Test + fun `rate limiting alone enforces the read budget without requiring an allowed Host`() = + testApplication { + application { + devConsoleModule(SessionAuthority()) { + networkProtection = NetworkProtection(rateLimiting = true) + } + } + val statuses = + (1..200).map { + client.get("/api/v1/meta") { header(HttpHeaders.Host, "unknown.example") }.status + } + assertTrue(statuses.contains(HttpStatusCode.OK)) + assertTrue(statuses.contains(HttpStatusCode.TooManyRequests)) + assertFalse(statuses.contains(HttpStatusCode.Forbidden)) + } + + @Test + fun `Host checks alone reject unknown hosts and permit 200 allowed reads`() = + testApplication { + application { + devConsoleModule(SessionAuthority()) { + networkProtection = NetworkProtection(hostAndOriginChecks = true) + } + } + val rejected = client.get("/api/v1/meta") { header(HttpHeaders.Host, "unknown.example") } + assertEquals(HttpStatusCode.Forbidden, rejected.status) + assertTrue(rejected.bodyAsText().contains("ORIGIN_REJECTED")) + repeat(200) { + assertEquals( + HttpStatusCode.OK, + client.get("/api/v1/meta") { header(HttpHeaders.Host, "localhost") }.status, + ) + } + } + + @Test + fun `meta reports default redaction and network protection`() = + testApplication { + application { devConsoleModule(SessionAuthority()) } + val body = client.get("/api/v1/meta").bodyAsText() + assertTrue(body.contains("\"redaction\":{\"enabled\":false")) + assertTrue(body.contains("\"networkProtection\":{\"rateLimiting\":false,\"hostAndOriginChecks\":false}")) + assertTrue(body.contains("\"sensitiveFieldNames\":[]")) + assertTrue(body.contains("\"composer\":{\"enabled\":true,\"allowedHosts\":[]}")) + } + + @Test + fun `meta reports text only redaction and recommended protection`() = + testApplication { + application { + devConsoleModule(SessionAuthority()) { + redactionPolicy = RedactionPolicy(emptySet(), textPatterns = listOf(Regex("private"))) + networkProtection = NetworkProtection.recommended() + } + } + val body = client.get("/api/v1/meta") { header(HttpHeaders.Host, "localhost") }.bodyAsText() + assertTrue(body.contains("\"redaction\":{\"enabled\":true")) + assertTrue(body.contains("\"networkProtection\":{\"rateLimiting\":true,\"hostAndOriginChecks\":true}")) + } + + @Test + fun `default mutations accept a foreign Origin`() = + testApplication { + application { devConsoleModule(SessionAuthority()) } + val response = + client.post("/api/v1/session/stop") { + header(HttpHeaders.Host, "unknown.example") + header(HttpHeaders.Origin, "https://elsewhere.example") + } + assertEquals(HttpStatusCode.Accepted, response.status) + } + + @Test + fun `opted in Origin checks reject foreign mutations in open mode`() = + testApplication { + application { + devConsoleModule(SessionAuthority()) { + networkProtection = NetworkProtection(hostAndOriginChecks = true) + } + } + val response = + client.post("/api/v1/session/stop") { + header(HttpHeaders.Host, "localhost") + header(HttpHeaders.Origin, "https://elsewhere.example") + } + assertEquals(HttpStatusCode.Forbidden, response.status) + assertTrue(response.bodyAsText().contains("ORIGIN_REJECTED")) + } + + @Test + fun `session code keeps auth csrf and attempt limits when network protection is off`() = + testApplication { + val sessions = SessionAuthority() + val codes = SessionCodeAuthority(sessions) + application { + devConsoleModule(sessions, codes) { browserSecurity = BrowserSecurity.SESSION_CODE } + } + assertEquals(HttpStatusCode.Unauthorized, client.get("/api/v1/meta").status) + val exchange = + client.post("/api/v1/auth/session-code/exchange") { + header(HttpHeaders.ContentType, ContentType.Application.FormUrlEncoded) + setBody("code=${codes.issueCode().code}&browserLabel=Test") + } + assertEquals(HttpStatusCode.OK, exchange.status) + val token = Regex("\"accessToken\":\"([^\"]+)\"").find(exchange.bodyAsText())!!.groupValues[1] + val session = sessions.sessionForToken(token)!! + val missingCsrf = + client.post("/api/v1/session/stop") { + header(HttpHeaders.Authorization, "Bearer $token") + } + assertEquals(HttpStatusCode.Forbidden, missingCsrf.status) + assertTrue(missingCsrf.bodyAsText().contains("CSRF_INVALID")) + val accepted = + client.post("/api/v1/session/stop") { + header(HttpHeaders.Authorization, "Bearer $token") + header("X-DevConsole-CSRF", session.csrfToken) + header(HttpHeaders.Origin, "https://elsewhere.example") + } + assertEquals(HttpStatusCode.Accepted, accepted.status) + val attempts = + (1..6).map { + client + .post("/api/v1/auth/session-code/exchange") { + header(HttpHeaders.ContentType, ContentType.Application.FormUrlEncoded) + setBody("code=invalid&browserLabel=Test") + }.status + } + assertTrue(attempts.contains(HttpStatusCode.TooManyRequests)) + } + + private fun capture(config: DevConsoleConfig) = + NetworkCaptureFactory(RedactionEngine(config.redactionPolicy)).capture( + NetworkRequestInput( + method = "POST", + url = "https://api.test/orders?access_token=query-secret", + headers = mapOf("Authorization" to "Bearer header-secret", "Cookie" to "session=cookie-secret"), + body = """{"token":"body-secret","":"empty-key"}""".encodeToByteArray(), + contentType = "application/json", + ), + null, + ) +} diff --git a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/SessionCodeRoutesTest.kt b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/SessionCodeRoutesTest.kt index 2112624..3c38ba3 100644 --- a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/SessionCodeRoutesTest.kt +++ b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/SessionCodeRoutesTest.kt @@ -22,7 +22,7 @@ import org.junit.Test /** * SESSION_CODE is the only browser-access flow -- there is no more `AccessMode` to gate on, so - * every test here exercises `devConsoleModule(sessionAuthority, sessionCodeAuthority)` directly + * every test here exercises `protectedDevConsoleModule(sessionAuthority, sessionCodeAuthority)` directly * rather than opting into a mode. */ class SessionCodeRoutesTest { @@ -32,7 +32,7 @@ class SessionCodeRoutesTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) val info = sessionCodes.issueCode() - application { devConsoleModule(sessions, sessionCodes) } + application { protectedDevConsoleModule(sessions, sessionCodes) } val response = client.post("/api/v1/auth/session-code/exchange") { @@ -61,7 +61,7 @@ class SessionCodeRoutesTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) val info = sessionCodes.issueCode() - application { devConsoleModule(sessions, sessionCodes) } + application { protectedDevConsoleModule(sessions, sessionCodes) } suspend fun exchange() = client.post("/api/v1/auth/session-code/exchange") { @@ -84,7 +84,7 @@ class SessionCodeRoutesTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) sessionCodes.issueCode() - application { devConsoleModule(sessions, sessionCodes) } + application { protectedDevConsoleModule(sessions, sessionCodes) } val response = client.post("/api/v1/auth/session-code/exchange") { @@ -104,7 +104,7 @@ class SessionCodeRoutesTest { val sessions = SessionAuthority(nowEpochMs = { now }) val sessionCodes = SessionCodeAuthority(sessions, nowEpochMs = { now }, codeTtlMs = 10L) val info = sessionCodes.issueCode() - application { devConsoleModule(sessions, sessionCodes) } + application { protectedDevConsoleModule(sessions, sessionCodes) } now = 11L val response = @@ -123,7 +123,7 @@ class SessionCodeRoutesTest { testApplication { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) - application { devConsoleModule(sessions, sessionCodes) } + application { protectedDevConsoleModule(sessions, sessionCodes) } suspend fun attempt() = client.post("/api/v1/auth/session-code/exchange") { @@ -145,7 +145,7 @@ class SessionCodeRoutesTest { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) val info = sessionCodes.issueCode() - application { devConsoleModule(sessions, sessionCodes) } + application { protectedDevConsoleModule(sessions, sessionCodes) } val exchanged = client.post("/api/v1/auth/session-code/exchange") { header(HttpHeaders.Host, "localhost") @@ -178,7 +178,7 @@ class SessionCodeRoutesTest { testApplication { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) - application { devConsoleModule(sessions, sessionCodes) } + application { protectedDevConsoleModule(sessions, sessionCodes) } val exchanged = client.post("/api/v1/auth/session-code/exchange") { header(HttpHeaders.Host, "localhost") @@ -221,7 +221,7 @@ class SessionCodeRoutesTest { testApplication { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) - application { devConsoleModule(sessions, sessionCodes) } + application { protectedDevConsoleModule(sessions, sessionCodes) } val exchanged = client.post("/api/v1/auth/session-code/exchange") { header(HttpHeaders.Host, "localhost") @@ -268,7 +268,7 @@ class SessionCodeRoutesTest { assertTrue(sessions.configurePolicy(SessionPolicy(maxAuthenticatedSessions = 1))) val sessionCodes = SessionCodeAuthority(sessions) val first = sessionCodes.issueCode() - application { devConsoleModule(sessions, sessionCodes) } + application { protectedDevConsoleModule(sessions, sessionCodes) } client.post("/api/v1/auth/session-code/exchange") { header(HttpHeaders.Host, "localhost") header(HttpHeaders.ContentType, ContentType.Application.FormUrlEncoded) diff --git a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/SessionExpiryRouteFamilyTest.kt b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/SessionExpiryRouteFamilyTest.kt index 3937e04..a51132b 100644 --- a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/SessionExpiryRouteFamilyTest.kt +++ b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/SessionExpiryRouteFamilyTest.kt @@ -57,7 +57,7 @@ class SessionExpiryRouteFamilyTest { val sessions = SessionAuthority(nowEpochMs = { now }, sessionTtlMs = 1_000L) val sessionCodes = SessionCodeAuthority(sessions, nowEpochMs = { now }) application { - devConsoleModule(sessions, sessionCodes) { + protectedDevConsoleModule(sessions, sessionCodes) { mocksEditable = true captureRulesEditable = true preferencesEditable = true @@ -153,7 +153,7 @@ class SessionExpiryRouteFamilyTest { var now = 0L val sessions = SessionAuthority(nowEpochMs = { now }, sessionTtlMs = 1_000L) val sessionCodes = SessionCodeAuthority(sessions, nowEpochMs = { now }) - application { devConsoleModule(sessions, sessionCodes) } + application { protectedDevConsoleModule(sessions, sessionCodes) } val session = approvedSession(sessions, sessionCodes) now = 1_001L val streamClient = createClient { install(WebSockets) } @@ -176,7 +176,7 @@ class SessionExpiryRouteFamilyTest { var now = 0L val sessions = SessionAuthority(nowEpochMs = { now }, sessionTtlMs = 1_000L) val sessionCodes = SessionCodeAuthority(sessions, nowEpochMs = { now }) - application { devConsoleModule(sessions, sessionCodes) } + application { protectedDevConsoleModule(sessions, sessionCodes) } val session = approvedSession(sessions, sessionCodes) val streamClient = createClient { install(WebSockets) } diff --git a/sdk/socket-okhttp/src/test/kotlin/io/devconsole/socket/okhttp/DevConsoleOkHttpWebSocketListenerTest.kt b/sdk/socket-okhttp/src/test/kotlin/io/devconsole/socket/okhttp/DevConsoleOkHttpWebSocketListenerTest.kt index a60f590..8ce619d 100644 --- a/sdk/socket-okhttp/src/test/kotlin/io/devconsole/socket/okhttp/DevConsoleOkHttpWebSocketListenerTest.kt +++ b/sdk/socket-okhttp/src/test/kotlin/io/devconsole/socket/okhttp/DevConsoleOkHttpWebSocketListenerTest.kt @@ -26,7 +26,7 @@ class DevConsoleOkHttpWebSocketListenerTest { val store = InMemorySocketStore() val listener = DevConsoleOkHttpWebSocketListener( - SocketRecorder(RedactionEngine(RedactionPolicy.default()), store), + SocketRecorder(RedactionEngine(RedactionPolicy.recommended()), store), connectionIdProvider = { "socket-1" }, ) val socket = FakeWebSocket() @@ -48,7 +48,7 @@ class DevConsoleOkHttpWebSocketListenerTest { @Test fun `recording socket preserves delegate results and records accepted sends and closing`() { val store = InMemorySocketStore() - val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.default()), store) + val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.recommended()), store) val delegate = FakeWebSocket() val socket = DevConsoleRecordingWebSocket.wrap(delegate, recorder) { "socket-1" } @@ -68,7 +68,7 @@ class DevConsoleOkHttpWebSocketListenerTest { fun `wrap after the listener already opened the socket keeps OPEN state and preserves openedAtEpochMs`() { val store = InMemorySocketStore() var time = 100L - val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.default()), store, clock = { time }) + val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.recommended()), store, clock = { time }) val listener = DevConsoleOkHttpWebSocketListener(recorder, connectionIdProvider = { "socket-1" }) val socket = FakeWebSocket() @@ -92,7 +92,7 @@ class DevConsoleOkHttpWebSocketListenerTest { @Test fun `delegate receives every callback after it has been recorded`() { val store = InMemorySocketStore() - val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.default()), store) + val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.recommended()), store) val hostDelegate = RecordingWebSocketListener() val listener = DevConsoleOkHttpWebSocketListener( @@ -117,7 +117,7 @@ class DevConsoleOkHttpWebSocketListenerTest { @Test fun `cancel records a non-error CANCELLED lifecycle instead of FAILED`() { val store = InMemorySocketStore() - val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.default()), store) + val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.recommended()), store) val socket = DevConsoleRecordingWebSocket.wrap(FakeWebSocket(), recorder) { "socket-1" } socket.cancel() diff --git a/sdk/socket-paho/src/test/kotlin/io/devconsole/socket/paho/DevConsolePahoMqttTest.kt b/sdk/socket-paho/src/test/kotlin/io/devconsole/socket/paho/DevConsolePahoMqttTest.kt index 646aacd..647969b 100644 --- a/sdk/socket-paho/src/test/kotlin/io/devconsole/socket/paho/DevConsolePahoMqttTest.kt +++ b/sdk/socket-paho/src/test/kotlin/io/devconsole/socket/paho/DevConsolePahoMqttTest.kt @@ -32,7 +32,7 @@ class DevConsolePahoMqttTest { @Test fun `received message with a secret is stored redacted, tagged mqtt, and the topic round-trips`() { val store = InMemorySocketStore() - val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.default()), store) + val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.recommended()), store) val client = FakeMqttAsyncClient() val delivered = mutableListOf() val hostDelegate = @@ -73,7 +73,7 @@ class DevConsolePahoMqttTest { @Test fun `publish stores exactly one sent message and returns the delegate token`() { val store = InMemorySocketStore() - val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.default()), store) + val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.recommended()), store) val client = FakeMqttAsyncClient() val publisher = DevConsolePahoMqtt.install(client, recorder) @@ -88,7 +88,7 @@ class DevConsolePahoMqttTest { @Test fun `host callbacks fire for connect complete, connection lost and delivery complete`() { val store = InMemorySocketStore() - val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.default()), store) + val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.recommended()), store) val client = FakeMqttAsyncClient() var connectCompleteCalls = 0 var connectionLostCalls = 0 diff --git a/sdk/socket/src/test/kotlin/io/devconsole/socket/SocketRecorderTest.kt b/sdk/socket/src/test/kotlin/io/devconsole/socket/SocketRecorderTest.kt index 56f713e..cfdaf7e 100644 --- a/sdk/socket/src/test/kotlin/io/devconsole/socket/SocketRecorderTest.kt +++ b/sdk/socket/src/test/kotlin/io/devconsole/socket/SocketRecorderTest.kt @@ -12,7 +12,7 @@ class SocketRecorderTest { @Test fun `redacts textual messages before storing a bounded preview`() { val store = InMemorySocketStore() - val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.default()), store, clock = { 100L }) + val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.recommended()), store, clock = { 100L }) recorder.onOpen("connection", "wss://api.test/socket") recorder.onMessage( @@ -37,7 +37,7 @@ class SocketRecorderTest { fun `disabled recorder never opens a connection or stores a message`() { val store = InMemorySocketStore() val recorder = - SocketRecorder(RedactionEngine(RedactionPolicy.default()), store, enabled = false, clock = { 100L }) + SocketRecorder(RedactionEngine(RedactionPolicy.recommended()), store, enabled = false, clock = { 100L }) recorder.onOpen("connection", "wss://api.test/socket") recorder.onMessage( @@ -54,7 +54,7 @@ class SocketRecorderTest { fun `records the complete lifecycle plus ping and pong frames`() { var time = 0L val store = InMemorySocketStore() - val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.default()), store, clock = { ++time }) + val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.recommended()), store, clock = { ++time }) recorder.onCreated("connection", "wss://api.test/socket") recorder.onOpen("connection", "wss://api.test/socket") @@ -84,12 +84,12 @@ class SocketRecorderTest { val metadataOnly = InMemorySocketStore() val preview = InMemorySocketStore() val bytes = byteArrayOf(0, 15, -1, 16) - SocketRecorder(RedactionEngine(RedactionPolicy.default()), metadataOnly).apply { + SocketRecorder(RedactionEngine(RedactionPolicy.recommended()), metadataOnly).apply { onOpen("connection", "wss://api.test/socket") onBinaryMessage("connection", SocketDirection.RECEIVED, bytes) } SocketRecorder( - RedactionEngine(RedactionPolicy.default()), + RedactionEngine(RedactionPolicy.recommended()), preview, true, System::currentTimeMillis, @@ -110,7 +110,7 @@ class SocketRecorderTest { @Test fun `withProtocol returns a configured copy without mutating the original`() { val store = InMemorySocketStore() - val base = SocketRecorder(RedactionEngine(RedactionPolicy.default()), store, clock = { 100L }) + val base = SocketRecorder(RedactionEngine(RedactionPolicy.recommended()), store, clock = { 100L }) val mqtt = base.withProtocol(SocketProtocol.MQTT) mqtt.onOpen("mqtt-conn", "tcp://broker.test:1883") @@ -126,7 +126,7 @@ class SocketRecorderTest { fun `protocol gate drops the disallowed protocol and keeps the other`() { val store = InMemorySocketStore() val base = - SocketRecorder(RedactionEngine(RedactionPolicy.default()), store, clock = { 100L }) + SocketRecorder(RedactionEngine(RedactionPolicy.recommended()), store, clock = { 100L }) .withProtocolGate { it != SocketProtocol.MQTT } val mqtt = base.withProtocol(SocketProtocol.MQTT) @@ -141,7 +141,7 @@ class SocketRecorderTest { fun `onCreated after onOpen keeps OPEN state and openedAtEpochMs with no duplicate CREATED event`() { var time = 0L val store = InMemorySocketStore() - val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.default()), store, clock = { ++time }) + val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.recommended()), store, clock = { ++time }) recorder.onOpen("connection", "wss://api.test/socket") val openedAt = store.connection("connection")!!.openedAtEpochMs @@ -162,7 +162,7 @@ class SocketRecorderTest { @Test fun `redacts the MQTT topic embedded in an application-mqtt content type`() { val store = InMemorySocketStore() - val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.default()), store, clock = { 100L }) + val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.recommended()), store, clock = { 100L }) recorder.onOpen("connection", "tcp://broker.test:1883") val contentType = MqttFrameMetadata.format("devices/?password=socket-secret/status", qos = 1, retained = true) @@ -182,7 +182,7 @@ class SocketRecorderTest { @Test fun `a frame for a connection that was never opened registers that connection instead of being dropped`() { val store = InMemorySocketStore() - val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.default()), store, clock = { 100L }) + val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.recommended()), store, clock = { 100L }) recorder.onMessage("connection", SocketDirection.SENT, "{\"type\":\"register\"}") @@ -198,7 +198,7 @@ class SocketRecorderTest { @Test fun `binary and control frames for an unknown connection are kept too`() { val store = InMemorySocketStore() - val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.default()), store, clock = { 100L }) + val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.recommended()), store, clock = { 100L }) recorder.onBinaryMessage("binary-bytes", SocketDirection.RECEIVED, byteArrayOf(1, 2)) recorder.onBinaryMessage("binary-length", SocketDirection.RECEIVED, 12L) @@ -218,7 +218,7 @@ class SocketRecorderTest { @Test fun `frames after the store is cleared mid-connection are still recorded`() { val store = InMemorySocketStore() - val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.default()), store, clock = { 100L }) + val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.recommended()), store, clock = { 100L }) recorder.onOpen("connection", "wss://api.test/socket") store.clear() @@ -230,7 +230,7 @@ class SocketRecorderTest { @Test fun `an implicit registration does not replace a url set by a later onOpen`() { val store = InMemorySocketStore() - val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.default()), store, clock = { 100L }) + val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.recommended()), store, clock = { 100L }) recorder.onMessage("connection", SocketDirection.RECEIVED, "early frame") recorder.onOpen("connection", "wss://api.test/socket") @@ -244,7 +244,7 @@ class SocketRecorderTest { fun `a gated-off recorder never registers a connection from a frame`() { val store = InMemorySocketStore() val recorder = - SocketRecorder(RedactionEngine(RedactionPolicy.default()), store, clock = { 100L }) + SocketRecorder(RedactionEngine(RedactionPolicy.recommended()), store, clock = { 100L }) .withProtocolGate { false } recorder.onMessage("connection", SocketDirection.RECEIVED, "frame") @@ -256,7 +256,7 @@ class SocketRecorderTest { fun `a throwing protocol gate still records -- fail-open`() { val store = InMemorySocketStore() val recorder = - SocketRecorder(RedactionEngine(RedactionPolicy.default()), store, clock = { 100L }) + SocketRecorder(RedactionEngine(RedactionPolicy.recommended()), store, clock = { 100L }) .withProtocolGate { throw IllegalStateException("boom") } recorder.onOpen("connection", "wss://api.test/socket") diff --git a/sdk/ui-compose/api/ui-compose.api b/sdk/ui-compose/api/ui-compose.api index d2e1875..c9215cd 100644 --- a/sdk/ui-compose/api/ui-compose.api +++ b/sdk/ui-compose/api/ui-compose.api @@ -20,10 +20,8 @@ public final class io/devconsole/ui/compose/ComposableSingletons$DevConsolePanel public final class io/devconsole/ui/compose/ComposableSingletons$InspectorControlScreenKt { public static final field INSTANCE Lio/devconsole/ui/compose/ComposableSingletons$InspectorControlScreenKt; public fun ()V - public final fun getLambda$-1373757892$ui_compose_release ()Lkotlin/jvm/functions/Function3; public final fun getLambda$-153603954$ui_compose_release ()Lkotlin/jvm/functions/Function2; public final fun getLambda$-1946392255$ui_compose_release ()Lkotlin/jvm/functions/Function3; - public final fun getLambda$-320721125$ui_compose_release ()Lkotlin/jvm/functions/Function3; public final fun getLambda$-63518038$ui_compose_release ()Lkotlin/jvm/functions/Function3; public final fun getLambda$-703251647$ui_compose_release ()Lkotlin/jvm/functions/Function3; public final fun getLambda$1476698320$ui_compose_release ()Lkotlin/jvm/functions/Function2; @@ -32,7 +30,7 @@ public final class io/devconsole/ui/compose/ComposableSingletons$InspectorContro public final class io/devconsole/ui/compose/ComposableSingletons$InspectorDataScreenKt { public static final field INSTANCE Lio/devconsole/ui/compose/ComposableSingletons$InspectorDataScreenKt; public fun ()V - public final fun getLambda$-1044807204$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$-1206510292$ui_compose_release ()Lkotlin/jvm/functions/Function3; public final fun getLambda$-677010572$ui_compose_release ()Lkotlin/jvm/functions/Function2; public final fun getLambda$477918812$ui_compose_release ()Lkotlin/jvm/functions/Function3; } @@ -62,19 +60,14 @@ public final class io/devconsole/ui/compose/ComposableSingletons$InspectorDesign public final fun getLambda$579827964$ui_compose_release ()Lkotlin/jvm/functions/Function2; } -public final class io/devconsole/ui/compose/ComposableSingletons$InspectorDetailHeaderKt { - public static final field INSTANCE Lio/devconsole/ui/compose/ComposableSingletons$InspectorDetailHeaderKt; - public fun ()V - public final fun getLambda$520449243$ui_compose_release ()Lkotlin/jvm/functions/Function2; -} - public final class io/devconsole/ui/compose/ComposableSingletons$InspectorDetailPreviewsKt { public static final field INSTANCE Lio/devconsole/ui/compose/ComposableSingletons$InspectorDetailPreviewsKt; public fun ()V + public final fun getLambda$-1516177484$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$-181929186$ui_compose_release ()Lkotlin/jvm/functions/Function2; public final fun getLambda$102583745$ui_compose_release ()Lkotlin/jvm/functions/Function2; public final fun getLambda$1051213960$ui_compose_release ()Lkotlin/jvm/functions/Function2; public final fun getLambda$141092982$ui_compose_release ()Lkotlin/jvm/functions/Function2; - public final fun getLambda$307009779$ui_compose_release ()Lkotlin/jvm/functions/Function3; public final fun getLambda$506757289$ui_compose_release ()Lkotlin/jvm/functions/Function2; public final fun getLambda$838729754$ui_compose_release ()Lkotlin/jvm/functions/Function2; public final fun getLambda$916258535$ui_compose_release ()Lkotlin/jvm/functions/Function2; @@ -104,17 +97,18 @@ public final class io/devconsole/ui/compose/ComposableSingletons$InspectorMockRu public final class io/devconsole/ui/compose/ComposableSingletons$InspectorMoreScreenKt { public static final field INSTANCE Lio/devconsole/ui/compose/ComposableSingletons$InspectorMoreScreenKt; public fun ()V + public final fun getLambda$-1399186756$ui_compose_release ()Lkotlin/jvm/functions/Function3; public final fun getLambda$-1671241350$ui_compose_release ()Lkotlin/jvm/functions/Function3; - public final fun getLambda$-1807268647$ui_compose_release ()Lkotlin/jvm/functions/Function3; - public final fun getLambda$-996758428$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$-1899534585$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$-1943295944$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$-605975602$ui_compose_release ()Lkotlin/jvm/functions/Function3; public final fun getLambda$1129667334$ui_compose_release ()Lkotlin/jvm/functions/Function2; public final fun getLambda$1180200415$ui_compose_release ()Lkotlin/jvm/functions/Function3; public final fun getLambda$1347851092$ui_compose_release ()Lkotlin/jvm/functions/Function2; - public final fun getLambda$1403158116$ui_compose_release ()Lkotlin/jvm/functions/Function3; - public final fun getLambda$272598894$ui_compose_release ()Lkotlin/jvm/functions/Function3; - public final fun getLambda$538904397$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$364036633$ui_compose_release ()Lkotlin/jvm/functions/Function3; public final fun getLambda$636091227$ui_compose_release ()Lkotlin/jvm/functions/Function3; public final fun getLambda$908145821$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$91982039$ui_compose_release ()Lkotlin/jvm/functions/Function3; } public final class io/devconsole/ui/compose/ComposableSingletons$InspectorNavComponentsKt { @@ -128,9 +122,8 @@ public final class io/devconsole/ui/compose/ComposableSingletons$InspectorNavCom public final class io/devconsole/ui/compose/ComposableSingletons$InspectorObserveCrashesTabKt { public static final field INSTANCE Lio/devconsole/ui/compose/ComposableSingletons$InspectorObserveCrashesTabKt; public fun ()V - public final fun getLambda$-1421458169$ui_compose_release ()Lkotlin/jvm/functions/Function3; - public final fun getLambda$1866586438$ui_compose_release ()Lkotlin/jvm/functions/Function3; - public final fun getLambda$208432142$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$-1292996319$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$1311345751$ui_compose_release ()Lkotlin/jvm/functions/Function3; } public final class io/devconsole/ui/compose/ComposableSingletons$InspectorObservePreviewsKt { @@ -155,35 +148,35 @@ public final class io/devconsole/ui/compose/ComposableSingletons$InspectorObserv public static final field INSTANCE Lio/devconsole/ui/compose/ComposableSingletons$InspectorObserveRemoteConfigTabKt; public fun ()V public final fun getLambda$-1047114689$ui_compose_release ()Lkotlin/jvm/functions/Function3; - public final fun getLambda$-1125610964$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$-1767828600$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$1329341694$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 fun getLambda$1105471844$ui_compose_release ()Lkotlin/jvm/functions/Function2; + public final fun getLambda$1281281800$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 - public final fun getLambda$-221440175$ui_compose_release ()Lkotlin/jvm/functions/Function3; - public final fun getLambda$-464977038$ui_compose_release ()Lkotlin/jvm/functions/Function3; - public final fun getLambda$-724470528$ui_compose_release ()Lkotlin/jvm/functions/Function3; - public final fun getLambda$-89809548$ui_compose_release ()Lkotlin/jvm/functions/Function3; - public final fun getLambda$1361372287$ui_compose_release ()Lkotlin/jvm/functions/Function3; - public final fun getLambda$2068262215$ui_compose_release ()Lkotlin/jvm/functions/Function3; - public final fun getLambda$2119314933$ui_compose_release ()Lkotlin/jvm/functions/Function3; - public final fun getLambda$268215722$ui_compose_release ()Lkotlin/jvm/functions/Function3; - public final fun getLambda$617080380$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$-1037306481$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$-1043254971$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$-1938845183$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$-821038729$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$407926864$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$413875354$ui_compose_release ()Lkotlin/jvm/functions/Function3; } public final class io/devconsole/ui/compose/ComposableSingletons$InspectorObserveTrafficTabKt { public static final field INSTANCE Lio/devconsole/ui/compose/ComposableSingletons$InspectorObserveTrafficTabKt; public fun ()V - public final fun getLambda$-2007802131$ui_compose_release ()Lkotlin/jvm/functions/Function3; - public final fun getLambda$1510917611$ui_compose_release ()Lkotlin/jvm/functions/Function3; - public final fun getLambda$2040262323$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$-1894236537$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$-361684419$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$1397675452$ui_compose_release ()Lkotlin/jvm/functions/Function3; } public final class io/devconsole/ui/compose/DatabaseBrowserActions { @@ -1388,8 +1381,8 @@ public final class io/devconsole/ui/compose/InspectorSessionUi { public final class io/devconsole/ui/compose/InspectorSnapshot { public static final field $stable I public fun ()V - public fun (ZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;ZLjava/util/Set;)V - public synthetic fun (ZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;ZLjava/util/Set;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public fun (ZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;ZLjava/util/Set;Z)V + public synthetic fun (ZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;ZLjava/util/Set;ZILkotlin/jvm/internal/DefaultConstructorMarker;)V public final fun component1 ()Z public final fun component10 ()Ljava/util/List; public final fun component11 ()Ljava/util/List; @@ -1405,6 +1398,7 @@ public final class io/devconsole/ui/compose/InspectorSnapshot { public final fun component20 ()Lio/devconsole/ui/compose/InspectorRetentionUi; public final fun component21 ()Z public final fun component22 ()Ljava/util/Set; + public final fun component23 ()Z public final fun component3 ()Lio/devconsole/ui/compose/InspectorEditingUi; public final fun component4 ()Z public final fun component5 ()Ljava/util/List; @@ -1412,8 +1406,8 @@ public final class io/devconsole/ui/compose/InspectorSnapshot { public final fun component7 ()Ljava/util/List; public final fun component8 ()Ljava/util/List; public final fun component9 ()Ljava/util/List; - public final fun copy (ZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;ZLjava/util/Set;)Lio/devconsole/ui/compose/InspectorSnapshot; - public static synthetic fun copy$default (Lio/devconsole/ui/compose/InspectorSnapshot;ZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;ZLjava/util/Set;ILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorSnapshot; + public final fun copy (ZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;ZLjava/util/Set;Z)Lio/devconsole/ui/compose/InspectorSnapshot; + public static synthetic fun copy$default (Lio/devconsole/ui/compose/InspectorSnapshot;ZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;ZLjava/util/Set;ZILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorSnapshot; public fun equals (Ljava/lang/Object;)Z public final fun getAvailable ()Z public final fun getBrowser ()Lio/devconsole/ui/compose/InspectorBrowserUi; @@ -1431,6 +1425,7 @@ public final class io/devconsole/ui/compose/InspectorSnapshot { public final fun getMocksEnabled ()Z public final fun getPreferenceFiles ()Ljava/util/List; public final fun getPushEvents ()Ljava/util/List; + public final fun getRedactionEnabled ()Z public final fun getRemoteConfig ()Ljava/util/List; public final fun getRetention ()Lio/devconsole/ui/compose/InspectorRetentionUi; public final fun getSessions ()Ljava/util/List; @@ -1549,8 +1544,8 @@ public final class io/devconsole/ui/compose/InspectorSqlResultUi$Wrote : io/devc public final class io/devconsole/ui/compose/InspectorState { public static final field $stable I public fun ()V - public fun (ZZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorCommandResult;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/Set;Ljava/util/Set;Lio/devconsole/ui/compose/ObserveTab;Ljava/util/Set;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorFileListingUi;Lio/devconsole/ui/compose/InspectorFilePreviewUi;Ljava/lang/String;Ljava/util/List;Lio/devconsole/ui/compose/InspectorDatabaseListingUi;Lio/devconsole/ui/compose/InspectorQueryResultUi;Lio/devconsole/ui/compose/InspectorSqlResultUi;Ljava/util/List;Ljava/lang/String;ZLio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;Lio/devconsole/api/ScreenshotResult;ZLjava/util/Set;)V - public synthetic fun (ZZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorCommandResult;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/Set;Ljava/util/Set;Lio/devconsole/ui/compose/ObserveTab;Ljava/util/Set;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorFileListingUi;Lio/devconsole/ui/compose/InspectorFilePreviewUi;Ljava/lang/String;Ljava/util/List;Lio/devconsole/ui/compose/InspectorDatabaseListingUi;Lio/devconsole/ui/compose/InspectorQueryResultUi;Lio/devconsole/ui/compose/InspectorSqlResultUi;Ljava/util/List;Ljava/lang/String;ZLio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;Lio/devconsole/api/ScreenshotResult;ZLjava/util/Set;IILkotlin/jvm/internal/DefaultConstructorMarker;)V + public fun (ZZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorCommandResult;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/Set;Ljava/util/Set;Lio/devconsole/ui/compose/ObserveTab;Ljava/util/Set;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorFileListingUi;Lio/devconsole/ui/compose/InspectorFilePreviewUi;Ljava/lang/String;Ljava/util/List;Lio/devconsole/ui/compose/InspectorDatabaseListingUi;Lio/devconsole/ui/compose/InspectorQueryResultUi;Lio/devconsole/ui/compose/InspectorSqlResultUi;Ljava/util/List;Ljava/lang/String;ZLio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;Lio/devconsole/api/ScreenshotResult;ZLjava/util/Set;Z)V + public synthetic fun (ZZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorCommandResult;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/Set;Ljava/util/Set;Lio/devconsole/ui/compose/ObserveTab;Ljava/util/Set;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorFileListingUi;Lio/devconsole/ui/compose/InspectorFilePreviewUi;Ljava/lang/String;Ljava/util/List;Lio/devconsole/ui/compose/InspectorDatabaseListingUi;Lio/devconsole/ui/compose/InspectorQueryResultUi;Lio/devconsole/ui/compose/InspectorSqlResultUi;Ljava/util/List;Ljava/lang/String;ZLio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;Lio/devconsole/api/ScreenshotResult;ZLjava/util/Set;ZIILkotlin/jvm/internal/DefaultConstructorMarker;)V public final fun component1 ()Z public final fun component10 ()Ljava/util/List; public final fun component11 ()Ljava/util/List; @@ -1582,14 +1577,15 @@ public final class io/devconsole/ui/compose/InspectorState { public final fun component35 ()Lio/devconsole/api/ScreenshotResult; public final fun component36 ()Z public final fun component37 ()Ljava/util/Set; + public final fun component38 ()Z public final fun component4 ()Lio/devconsole/ui/compose/InspectorEditingUi; public final fun component5 ()Z public final fun component6 ()Ljava/util/List; public final fun component7 ()Ljava/util/List; public final fun component8 ()Lio/devconsole/ui/compose/InspectorCommandResult; public final fun component9 ()Ljava/util/List; - public final fun copy (ZZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorCommandResult;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/Set;Ljava/util/Set;Lio/devconsole/ui/compose/ObserveTab;Ljava/util/Set;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorFileListingUi;Lio/devconsole/ui/compose/InspectorFilePreviewUi;Ljava/lang/String;Ljava/util/List;Lio/devconsole/ui/compose/InspectorDatabaseListingUi;Lio/devconsole/ui/compose/InspectorQueryResultUi;Lio/devconsole/ui/compose/InspectorSqlResultUi;Ljava/util/List;Ljava/lang/String;ZLio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;Lio/devconsole/api/ScreenshotResult;ZLjava/util/Set;)Lio/devconsole/ui/compose/InspectorState; - public static synthetic fun copy$default (Lio/devconsole/ui/compose/InspectorState;ZZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorCommandResult;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/Set;Ljava/util/Set;Lio/devconsole/ui/compose/ObserveTab;Ljava/util/Set;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorFileListingUi;Lio/devconsole/ui/compose/InspectorFilePreviewUi;Ljava/lang/String;Ljava/util/List;Lio/devconsole/ui/compose/InspectorDatabaseListingUi;Lio/devconsole/ui/compose/InspectorQueryResultUi;Lio/devconsole/ui/compose/InspectorSqlResultUi;Ljava/util/List;Ljava/lang/String;ZLio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;Lio/devconsole/api/ScreenshotResult;ZLjava/util/Set;IILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorState; + public final fun copy (ZZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorCommandResult;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/Set;Ljava/util/Set;Lio/devconsole/ui/compose/ObserveTab;Ljava/util/Set;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorFileListingUi;Lio/devconsole/ui/compose/InspectorFilePreviewUi;Ljava/lang/String;Ljava/util/List;Lio/devconsole/ui/compose/InspectorDatabaseListingUi;Lio/devconsole/ui/compose/InspectorQueryResultUi;Lio/devconsole/ui/compose/InspectorSqlResultUi;Ljava/util/List;Ljava/lang/String;ZLio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;Lio/devconsole/api/ScreenshotResult;ZLjava/util/Set;Z)Lio/devconsole/ui/compose/InspectorState; + public static synthetic fun copy$default (Lio/devconsole/ui/compose/InspectorState;ZZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorCommandResult;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/Set;Ljava/util/Set;Lio/devconsole/ui/compose/ObserveTab;Ljava/util/Set;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorFileListingUi;Lio/devconsole/ui/compose/InspectorFilePreviewUi;Ljava/lang/String;Ljava/util/List;Lio/devconsole/ui/compose/InspectorDatabaseListingUi;Lio/devconsole/ui/compose/InspectorQueryResultUi;Lio/devconsole/ui/compose/InspectorSqlResultUi;Ljava/util/List;Ljava/lang/String;ZLio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;Lio/devconsole/api/ScreenshotResult;ZLjava/util/Set;ZIILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorState; public fun equals (Ljava/lang/Object;)Z public final fun getAvailable ()Z public final fun getBrowser ()Lio/devconsole/ui/compose/InspectorBrowserUi; @@ -1617,6 +1613,7 @@ public final class io/devconsole/ui/compose/InspectorState { public final fun getPreferenceFiles ()Ljava/util/List; public final fun getPushEvents ()Ljava/util/List; public final fun getQueryResult ()Lio/devconsole/ui/compose/InspectorQueryResultUi; + public final fun getRedactionEnabled ()Z public final fun getRemoteConfig ()Ljava/util/List; public final fun getRetention ()Lio/devconsole/ui/compose/InspectorRetentionUi; public final fun getSelectedSessionId ()Ljava/lang/String; diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/CollapsibleSection.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/CollapsibleSection.kt index 3a0c564..71b555a 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/CollapsibleSection.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/CollapsibleSection.kt @@ -56,6 +56,7 @@ internal fun CollapsibleSection( metaColor: Color = DevConsoleTheme.colors.muted, onCopy: (() -> Unit)? = null, copyContentDescription: String = "Copy $label", + showTopDivider: Boolean = true, content: @Composable ColumnScope.() -> Unit, ) { // Open: chevron points down (0deg); collapsed: chevron points right (-90deg). @@ -66,7 +67,9 @@ internal fun CollapsibleSection( label = "sectionChevron", ) Column(modifier = modifier.fillMaxWidth()) { - HorizontalDivider(color = DevConsoleTheme.colors.line) + if (showTopDivider) { + HorizontalDivider(color = DevConsoleTheme.colors.line) + } CollapsibleSectionHeader(label, onToggle, rotation, meta, metaColor, onCopy, copyContentDescription) // The chevron was already animating while the content it controls snapped in and out, which // reads as two unrelated events rather than one. Expanding the height ties them together: @@ -100,7 +103,7 @@ private fun CollapsibleSectionHeader( modifier = Modifier .weight(1f) - .height(56.dp) + .height(48.dp) .clickable(onClick = onToggle, role = Role.Button) .padding(horizontal = 8.dp), verticalAlignment = Alignment.CenterVertically, @@ -110,7 +113,7 @@ private fun CollapsibleSectionHeader( InspectorGlyph.ChevronDown, contentDescription = null, tint = DevConsoleTheme.colors.muted, - size = 16.dp, + size = 14.dp, rotationDegrees = rotation, ) Text( @@ -136,7 +139,7 @@ private fun CollapsibleSectionHeader( InspectorGlyph.Copy, contentDescription = null, tint = DevConsoleTheme.colors.muted, - size = 17.dp, + size = 18.dp, ) }, ) diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/DevConsoleActivity.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/DevConsoleActivity.kt index be0883e..40f6b7f 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/DevConsoleActivity.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/DevConsoleActivity.kt @@ -4,11 +4,32 @@ import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge +import androidx.compose.ui.ExperimentalComposeUiApi +import androidx.compose.ui.contentcapture.ContentCaptureManager class DevConsoleActivity : ComponentActivity() { + /** The host's value, put back when the inspector leaves the foreground. */ + private var hostContentCaptureEnabled: Boolean? = null + override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContent { DevConsoleWorkspace() } } + + // Content capture re-walks the semantics tree on every change (~1/5 of main-thread time); pause it + // while this full-screen inspector is in front. The flag is process-wide, so onPause restores it. + @OptIn(ExperimentalComposeUiApi::class) + override fun onResume() { + super.onResume() + hostContentCaptureEnabled = ContentCaptureManager.isEnabled + ContentCaptureManager.isEnabled = false + } + + @OptIn(ExperimentalComposeUiApi::class) + override fun onPause() { + hostContentCaptureEnabled?.let { ContentCaptureManager.isEnabled = it } + hostContentCaptureEnabled = null + super.onPause() + } } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/DevConsoleIcon.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/DevConsoleIcon.kt new file mode 100644 index 0000000..6f4b648 --- /dev/null +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/DevConsoleIcon.kt @@ -0,0 +1,36 @@ +/** + * @author Shakib + * @since 19/10/26 + */ +@file:Suppress("FunctionNaming") + +package io.devconsole.ui.compose + +import androidx.annotation.DrawableRes +import androidx.compose.foundation.layout.size +import androidx.compose.material3.Icon +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.unit.Dp + +/** + * One `devconsole_ic_*` vector drawable, tinted. A null [contentDescription] keeps the icon out of + * the accessibility tree, which is what every glyph nested in an already-labelled control wants. + */ +@Composable +internal fun DevConsoleIcon( + @DrawableRes id: Int, + contentDescription: String?, + modifier: Modifier, + tint: Color, + size: Dp, +) { + Icon( + painter = painterResource(id), + contentDescription = contentDescription, + modifier = modifier.size(size), + tint = tint, + ) +} diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/DevConsoleTheme.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/DevConsoleTheme.kt index 68803ee..648a5bc 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/DevConsoleTheme.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/DevConsoleTheme.kt @@ -74,58 +74,60 @@ internal data class DevConsoleColors( val jsonBraces: List, ) -private val DarkPrimary = Color(0xFF72A7FF) -private val DarkError = Color(0xFFFF7B72) -private val DarkWarning = Color(0xFFF2B66D) -private val DarkSecondary = Color(0xFF72C4CE) +// Signal green is the only accent; warn/error mark 4xx/5xx. Text roles clear WCAG AA on ground and +// panel, borderStrong (control outlines) clears 3:1. +private val DarkPrimary = Color(0xFFB7ED65) +private val DarkError = Color(0xFFFF7A6B) +private val DarkWarning = Color(0xFFE8B45C) +private val DarkSecondary = Color(0xFF8FCFC9) internal val DevConsoleDarkColors = DevConsoleColors( - ground = Color(0xFF111317), - panel = Color(0xFF171A20), - surface2 = Color(0xFF1D2129), - surface3 = Color(0xFF242A34), - codeBg = Color(0xFF0D0F13), - ink = Color(0xFFECEEF2), - muted = Color(0xFF969DA8), - text3 = Color(0xFF858D99), - line = Color(0xFF343A45), - borderStrong = Color(0xFF4A5260), + ground = Color(0xFF111413), + panel = Color(0xFF181C1A), + surface2 = Color(0xFF1E2320), + surface3 = Color(0xFF252B27), + codeBg = Color(0xFF141816), + ink = Color(0xFFECEBE4), + muted = Color(0xFF8D9289), + text3 = Color(0xFF8D9289), + line = Color(0xFF242A26), + borderStrong = Color(0xFF6B726B), signal = DarkPrimary, - signalInk = Color(0xFF0E1624), + signalInk = Color(0xFF111413), warn = DarkWarning, error = DarkError, - errorInk = Color(0xFF0E1624), + errorInk = Color(0xFF111413), put = DarkSecondary, - signalSoft = DarkPrimary.copy(alpha = 0.13f), - errorSoft = DarkError.copy(alpha = 0.13f), - warnSoft = DarkWarning.copy(alpha = 0.13f), - putSoft = DarkSecondary.copy(alpha = 0.13f), - jsonKey = Color(0xFF8CB8FF), - jsonString = Color(0xFFA9D6B9), + signalSoft = DarkPrimary.copy(alpha = 0.14f), + errorSoft = DarkError.copy(alpha = 0.14f), + warnSoft = DarkWarning.copy(alpha = 0.14f), + putSoft = DarkSecondary.copy(alpha = 0.14f), + jsonKey = DarkSecondary, + jsonString = Color(0xFFA9D99A), jsonNumber = DarkWarning, - jsonBoolean = Color(0xFFC7A7FF), - jsonNull = Color(0xFF969DA8), - jsonBraces = listOf(DarkPrimary, DarkWarning, DarkSecondary, Color(0xFFECEEF2), Color(0xFFC7A7FF)), + jsonBoolean = Color(0xFFC9B3F2), + jsonNull = Color(0xFF8D9289), + jsonBraces = listOf(DarkPrimary, DarkWarning, DarkSecondary, Color(0xFFECEBE4), Color(0xFFC9B3F2)), ) -private val LightPrimary = Color(0xFF245DA8) -private val LightError = Color(0xFFB6392A) -private val LightWarn = Color(0xFF93630A) -private val LightPut = Color(0xFF1F7A6C) +private val LightPrimary = Color(0xFF2F7A1F) +private val LightError = Color(0xFFC0261D) +private val LightWarn = Color(0xFF9A5B00) +private val LightPut = Color(0xFF1E6D6A) internal val DevConsoleLightColors = DevConsoleColors( - ground = Color(0xFFF7F8FA), + ground = Color(0xFFF2F3F0), panel = Color(0xFFFFFFFF), - surface2 = Color(0xFFEEF1F5), - surface3 = Color(0xFFE4E8EE), - codeBg = Color(0xFFF7F8FA), - ink = Color(0xFF1C1F24), - muted = Color(0xFF68707B), - text3 = Color(0xFF68707B), - line = Color(0xFFD5D9E0), - borderStrong = Color(0xFFAAB1BC), + surface2 = Color(0xFFECEEE9), + surface3 = Color(0xFFE2E5DF), + codeBg = Color(0xFFF6F7F4), + ink = Color(0xFF151714), + muted = Color(0xFF62675F), + text3 = Color(0xFF62675F), + line = Color(0xFFE3E5E0), + borderStrong = Color(0xFF8F948B), signal = LightPrimary, signalInk = Color(0xFFFFFFFF), warn = LightWarn, @@ -136,18 +138,18 @@ internal val DevConsoleLightColors = errorSoft = LightError.copy(alpha = 0.10f), warnSoft = LightWarn.copy(alpha = 0.10f), putSoft = LightPut.copy(alpha = 0.10f), - jsonKey = Color(0xFF1F7A6C), - jsonString = Color(0xFF4A5B1F), + jsonKey = LightPut, + jsonString = Color(0xFF3D6B2A), jsonNumber = LightWarn, - jsonBoolean = LightPrimary, - jsonNull = Color(0xFF68707B), + jsonBoolean = Color(0xFF6A46A5), + jsonNull = Color(0xFF62675F), jsonBraces = listOf( LightPrimary, LightWarn, LightPut, - Color(0xFF1C1F24), - Color(0xFF6A4C93), + Color(0xFF151714), + Color(0xFF6A46A5), ), ) @@ -179,7 +181,7 @@ internal val DevConsoleShapes = internal val DevConsoleTypography = Typography( headlineSmall = - TextStyle(fontSize = 27.sp, fontWeight = FontWeight.Medium, letterSpacing = (-0.02).em, lineHeight = 31.sp), + TextStyle(fontSize = 28.sp, fontWeight = FontWeight.Bold, letterSpacing = (-0.02).em, lineHeight = 34.sp), bodyLarge = TextStyle(fontSize = 14.5.sp), bodySmall = TextStyle(fontSize = 12.5.sp), labelMedium = TextStyle(fontSize = 12.5.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.04.em), diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/DevConsoleWorkspace.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/DevConsoleWorkspace.kt index f960e4c..fb9f9f4 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/DevConsoleWorkspace.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/DevConsoleWorkspace.kt @@ -6,8 +6,8 @@ package io.devconsole.ui.compose -import androidx.compose.animation.Crossfade import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize @@ -16,18 +16,26 @@ import androidx.compose.material3.LocalContentColor import androidx.compose.material3.Scaffold import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.State +import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.mutableStateMapOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.saveable.listSaver import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.saveable.rememberSaveableStateHolder import androidx.compose.runtime.setValue +import androidx.compose.runtime.withFrameNanos import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewmodel.compose.viewModel +import kotlinx.coroutines.delay @Composable fun DevConsoleWorkspace() { @@ -60,60 +68,30 @@ internal fun DevConsoleWorkspace( val store = remember { SharedPreferencesInspectorThemeStore(context.applicationContext) } val systemDark = isSystemInDarkTheme() var darkTheme by rememberSaveable { mutableStateOf(resolveDarkTheme(store.readOverride(), systemDark)) } - var detailOverlayOpen by rememberSaveable { mutableStateOf(false) } - val state by viewModel.state.collectAsStateWithLifecycle() + val visibleDestinations by rememberVisibleDestinations(viewModel) // A capture category disabled at init (or, dynamically, mid-session) can take the currently - // selected destination out of workspaceNavItems() entirely -- e.g. INSPECTION off hides DATA. A + // selected destination out of the visible destinations entirely -- e.g. INSPECTION off hides DATA. A // bottom nav that still reports a hidden destination as "selected" would strand the operator on // a screen with no way back to it via the nav itself, so this snaps to the first still-visible // destination the moment that happens. visibleDestinations() always includes MORE (see its own // doc), so `first()` never throws. - LaunchedEffect(state.captureCategories, selected) { - val visible = state.visibleDestinations() - if (selected !in visible) onDestinationSelected(visible.first()) + LaunchedEffect(visibleDestinations, selected) { + if (selected !in visibleDestinations) onDestinationSelected(visibleDestinations.first()) } DevConsoleTheme(darkTheme = darkTheme) { BoxWithConstraints(modifier = Modifier.fillMaxSize()) { - val layout = inspectorNavigationLayout(maxWidth) - if (layout == InspectorNavigationLayout.Bar) { - Scaffold( - containerColor = DevConsoleTheme.colors.ground, - bottomBar = { - if (!detailOverlayOpen) { - InspectorNavigationBar(items = workspaceNavItems(selected, state, onDestinationSelected)) - } - }, - ) { padding -> - WorkspaceContent( - selected = selected, - onToggleTheme = { - val next = !darkTheme - store.writeOverride(next) - darkTheme = next - }, - onDetailOverlayOpen = { open -> detailOverlayOpen = open }, - modifier = Modifier.fillMaxSize().padding(padding), - viewModel = viewModel, - ) - } - } else { - Row(modifier = Modifier.fillMaxSize()) { - if (!detailOverlayOpen) { - InspectorNavigationRail(items = workspaceNavItems(selected, state, onDestinationSelected)) - } - WorkspaceContent( - selected = selected, - onToggleTheme = { - val next = !darkTheme - store.writeOverride(next) - darkTheme = next - }, - onDetailOverlayOpen = { open -> detailOverlayOpen = open }, - modifier = Modifier.weight(1f), - viewModel = viewModel, - ) - } - } + WorkspaceContent( + selected = selected, + onDestinationSelected = onDestinationSelected, + onToggleTheme = { + val next = !darkTheme + store.writeOverride(next) + darkTheme = next + }, + navigationLayout = inspectorNavigationLayout(maxWidth), + modifier = Modifier.fillMaxSize(), + viewModel = viewModel, + ) } } } @@ -124,19 +102,35 @@ internal fun DevConsoleWorkspace( * for the gating rule. */ @Composable -private fun workspaceNavItems( +private fun rememberWorkspaceNavItems( selected: InspectorDestination, - state: InspectorState, + visibleDestinations: List, onDestinationSelected: (InspectorDestination) -> Unit, -): List = - state.visibleDestinations().map { destination -> - InspectorNavItem( - label = destination.label, - selected = destination == selected, - onClick = { onDestinationSelected(destination) }, - icon = { DestinationNavIcon(destination) }, - ) +): List { + val currentOnDestinationSelected by rememberUpdatedState(onDestinationSelected) + // Remembered so live state updates (new traffic, polling) don't hand the nav a fresh list and + // recompose all four items; only a selection or visibility change rebuilds it. + return remember(selected, visibleDestinations) { + visibleDestinations.map { destination -> + InspectorNavItem( + label = destination.label, + selected = destination == selected, + onClick = { currentOnDestinationSelected(destination) }, + icon = { DestinationNavIcon(destination) }, + ) + } } +} + +/** + * The visible destinations as their own state: [derivedStateOf] only invalidates readers when the + * list actually changes, so the workspace shell does not recompose on every [InspectorState] emission. + */ +@Composable +private fun rememberVisibleDestinations(viewModel: InspectorViewModel): State> { + val state = viewModel.state.collectAsStateWithLifecycle() + return remember(state) { derivedStateOf { state.value.visibleDestinations() } } +} @Composable private fun DestinationNavIcon(destination: InspectorDestination) { @@ -145,78 +139,110 @@ private fun DestinationNavIcon(destination: InspectorDestination) { // and vanishes against the selected pill. val tint = LocalContentColor.current when (destination) { - InspectorDestination.OBSERVE -> ObserveGlyphIcon(ObserveGlyph.Activity, contentDescription = null, tint = tint) - InspectorDestination.CONTROL -> NavGlyphIcon(NavGlyph.Send, contentDescription = null, tint = tint) - InspectorDestination.DATA -> NavGlyphIcon(NavGlyph.Db, contentDescription = null, tint = tint) - InspectorDestination.MORE -> NavGlyphIcon(NavGlyph.Grid, contentDescription = null, tint = tint) + InspectorDestination.OBSERVE -> NavGlyphIcon(NavGlyph.Observe, contentDescription = null, tint = tint) + InspectorDestination.CONTROL -> NavGlyphIcon(NavGlyph.Control, contentDescription = null, tint = tint) + InspectorDestination.DATA -> NavGlyphIcon(NavGlyph.Data, contentDescription = null, tint = tint) + InspectorDestination.MORE -> NavGlyphIcon(NavGlyph.More, contentDescription = null, tint = tint) } } /** * Hosts the one [InspectorState.pendingShareFilePath] side effect (launching the system Share * sheet) for every destination, not just DATA -- MORE's export actions set the same pending path a - * Files-screen share does, but only the currently selected destination's route composable is part - * of the composition, so a `LaunchedEffect` scoped to one route would never fire for the other. + * Files-screen share does. Keeping it here ensures one consumer even while several destination + * routes remain composed. * - * Each destination's content is wrapped in [rememberSaveableStateHolder]'s - * [androidx.compose.runtime.saveable.SaveableStateHolder.SaveableStateProvider], keyed on the - * destination itself -- the plain `when` below disposes the composition of whichever destination - * just lost selection, so without this every route's `rememberSaveable` UI state (search text, - * hero-collapse, scroll position, ...) would reset on every bottom-nav switch instead of surviving - * re-selection like the standard bottom-nav contract expects. This only covers `rememberSaveable` - * state, not every field a route happens to hold -- e.g. ObserveRoute's bookmarkedIds and - * detailTarget are plain `mutableStateOf` and still reset on destination switch like any other - * disposed composition's state would. + * Visited destinations stay composed inside [DestinationHost], preserving scroll and open detail + * state while hidden routes are unplaced and capped at CREATED. Each destination retains its named + * [androidx.compose.runtime.saveable.SaveableStateHolder.SaveableStateProvider] so saveable state + * also survives configuration changes and process recreation. */ @Composable private fun WorkspaceContent( selected: InspectorDestination, + onDestinationSelected: (InspectorDestination) -> Unit, onToggleTheme: () -> Unit, - onDetailOverlayOpen: (Boolean) -> Unit, + navigationLayout: InspectorNavigationLayout, modifier: Modifier = Modifier, viewModel: InspectorViewModel = viewModel(), ) { - val state by viewModel.state.collectAsStateWithLifecycle() + val state = viewModel.state.collectAsStateWithLifecycle() + val pendingShareFilePath by remember(state) { derivedStateOf { state.value.pendingShareFilePath } } val context = LocalContext.current - LaunchedEffect(state.pendingShareFilePath) { - val path = state.pendingShareFilePath ?: return@LaunchedEffect + LaunchedEffect(pendingShareFilePath) { + val path = pendingShareFilePath ?: return@LaunchedEffect shareFileFromPath(context, path) viewModel.dispatch(InspectorAction.ConsumeShareFile) } - // Observe (capture detail) and Control (mock rule sheet) both have full-screen overlays; reset - // on every destination switch so the nav never stays hidden after navigating away from one -- - // the newly active route's own LaunchedEffect asserts the correct value right after. - LaunchedEffect(selected) { onDetailOverlayOpen(false) } + val overlays = remember { mutableStateMapOf() } + val detailOverlayOpen = overlays[selected] == true val stateHolder = rememberSaveableStateHolder() - // The dashboard's `.view { animation: fadein 0.15s ease; }`. Fade-through rather than a slide: - // the four destinations are siblings, not a hierarchy, so nothing should imply a direction of - // travel between them. Short enough that it reads as a settle, never as a wait. - Crossfade(targetState = selected, animationSpec = feedbackSpec(), label = "destination") { destination -> - when (destination) { - InspectorDestination.OBSERVE -> - stateHolder.SaveableStateProvider(InspectorDestination.OBSERVE.name) { - ObserveRoute( - onToggleTheme = onToggleTheme, - onDetailOverlayOpen = onDetailOverlayOpen, - modifier = modifier, - ) + var visited by + rememberSaveable( + stateSaver = listSaver, String>(save = { it.toList() }, restore = { it.toSet() }), + ) { mutableStateOf(setOf(selected.name)) } + val visibleDestinations by remember(state) { derivedStateOf { state.value.visibleDestinations() } } + val currentVisibleDestinations by rememberUpdatedState(visibleDestinations) + LaunchedEffect(selected) { visited += selected.name } + // Let the first screen settle, then spread hidden composition work across frame batches. + LaunchedEffect(Unit) { + delay(1_000) + for (destination in currentVisibleDestinations) { + if (destination in currentVisibleDestinations && destination.name !in visited) { + visited += destination.name + withFrameNanos { } + delay(300) + } + } + } + val destinationContent: @Composable (Modifier) -> Unit = { contentModifier -> + Box(modifier = contentModifier) { + for (destination in visibleDestinations.filter { it == selected || it.name in visited }) { + key(destination) { + DestinationHost(active = destination == selected) { + stateHolder.SaveableStateProvider(destination.name) { + when (destination) { + InspectorDestination.OBSERVE -> + ObserveRoute( + onToggleTheme = onToggleTheme, + onDetailOverlayOpen = { open -> overlays[destination] = open }, + ) + InspectorDestination.CONTROL -> + ControlRoute( + onToggleTheme = onToggleTheme, + onDetailOverlayOpen = { open -> overlays[destination] = open }, + ) + InspectorDestination.DATA -> DataRoute(onToggleTheme = onToggleTheme) + InspectorDestination.MORE -> MoreRoute(onToggleTheme = onToggleTheme) + } + } + } } - InspectorDestination.CONTROL -> - stateHolder.SaveableStateProvider(InspectorDestination.CONTROL.name) { - ControlRoute( - onToggleTheme = onToggleTheme, - onDetailOverlayOpen = onDetailOverlayOpen, - modifier = modifier, + } + } + } + if (navigationLayout == InspectorNavigationLayout.Bar) { + Scaffold( + modifier = modifier, + containerColor = DevConsoleTheme.colors.ground, + bottomBar = { + if (!detailOverlayOpen) { + InspectorNavigationBar( + items = rememberWorkspaceNavItems(selected, visibleDestinations, onDestinationSelected), ) } - InspectorDestination.DATA -> - stateHolder.SaveableStateProvider(InspectorDestination.DATA.name) { - DataRoute(onToggleTheme = onToggleTheme, modifier = modifier) - } - InspectorDestination.MORE -> - stateHolder.SaveableStateProvider(InspectorDestination.MORE.name) { - MoreRoute(onToggleTheme = onToggleTheme, modifier = modifier) - } + }, + ) { padding -> + destinationContent(Modifier.fillMaxSize().padding(padding)) + } + } else { + Row(modifier = modifier) { + if (!detailOverlayOpen) { + InspectorNavigationRail( + items = rememberWorkspaceNavItems(selected, visibleDestinations, onDestinationSelected), + ) + } + destinationContent(Modifier.weight(1f)) } } } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeBlock.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeBlock.kt index 08e7f7a..af0fb37 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeBlock.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeBlock.kt @@ -9,8 +9,8 @@ package io.devconsole.ui.compose import androidx.compose.foundation.background import androidx.compose.foundation.horizontalScroll -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.BoxScope +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.heightIn @@ -23,13 +23,15 @@ import androidx.compose.foundation.relocation.bringIntoViewRequester import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.remember -import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.dp @@ -56,7 +58,7 @@ internal data class InspectorCodeLine( internal val InlineCodeBlockMaxHeight = 420.dp /** - * Code / JSON viewer for a [CollapsibleSection]'s code variant: 16dp radius, code-bg background, + * Code / JSON viewer for a detail panel: 8dp radius, code-bg background, * mono 13sp lines at 1.7 line-height, horizontally scrolling, with a signal-soft row highlight for * search hits. Backed by a [LazyColumn] (not a `Column`+`forEach`) so a pretty-printed body of * thousands of lines only composes/measures the rows actually scrolled into view -- capture-detail @@ -86,13 +88,13 @@ internal fun InspectorCodeBlock( } if (activeLineIndex != null) bringIntoViewRequester.bringIntoView() } - Box(modifier = modifier.fillMaxWidth().bringIntoViewRequester(bringIntoViewRequester)) { + Column(modifier = modifier.fillMaxWidth().bringIntoViewRequester(bringIntoViewRequester)) { LazyColumn( state = listState, modifier = Modifier .fillMaxWidth() - .clip(RoundedCornerShape(16.dp)) + .clip(RoundedCornerShape(8.dp)) .background(colors.codeBg) .heightIn(max = InlineCodeBlockMaxHeight) // A lazy layout can't be measured with `IntrinsicSize.Max` (no intrinsic-measurement @@ -123,25 +125,18 @@ internal fun InspectorCodeBlock( } } -/** The small top-right "open full screen" button every code-ish block variant shares. */ +/** Plain trailing full-screen action below the code area. */ @Composable -internal fun BoxScope.InspectorCodeBlockExpandButton(onExpandFullScreen: () -> Unit) { +internal fun InspectorCodeBlockExpandButton(onExpandFullScreen: () -> Unit) { val colors = DevConsoleTheme.colors - InspectorRoundIconButton( - contentDescription = "Full screen", - onClick = onExpandFullScreen, - modifier = Modifier.align(Alignment.TopEnd).padding(4.dp), - size = 28.dp, - containerColor = colors.surface3, - icon = { - InspectorGlyphIcon( - InspectorGlyph.Expand, - contentDescription = null, - tint = colors.muted, - size = 14.dp, - ) - }, - ) + Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { + TextButton( + onClick = onExpandFullScreen, + modifier = Modifier.semantics { contentDescription = "Full screen" }, + ) { + Text("Expand", color = colors.signal, fontSize = 14.sp) + } + } } /** One [InspectorCodeLine] row, shared by [InspectorCodeBlock] and [InspectorCodeFullScreenOverlay]. */ diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorControlScreen.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorControlScreen.kt index ba6ebc1..83a92df 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorControlScreen.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorControlScreen.kt @@ -2,6 +2,7 @@ * @author Shakib * @since 04/08/26 */ +@file:OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class) @file:Suppress("FunctionNaming", "MagicNumber", "UnusedPrivateMember", "TooManyFunctions") package io.devconsole.ui.compose @@ -9,6 +10,7 @@ package io.devconsole.ui.compose import android.content.res.Configuration import androidx.compose.foundation.background import androidx.compose.foundation.clickable +import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column @@ -19,13 +21,16 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.material3.AlertDialog +import androidx.compose.material3.IconButton import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Switch +import androidx.compose.material3.SwitchColors +import androidx.compose.material3.SwitchDefaults import androidx.compose.material3.Text import androidx.compose.material3.minimumInteractiveComponentSize import androidx.compose.runtime.Composable @@ -38,20 +43,26 @@ import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.text.withStyle import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.compose.LifecycleStartEffect +import androidx.lifecycle.compose.LocalLifecycleOwner import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.compose.currentStateAsState import androidx.lifecycle.viewmodel.compose.viewModel import io.devconsole.api.CaptureCategory import kotlinx.coroutines.launch -import java.util.Locale /** * Stateful entry point wired into the CONTROL destination. Theme is owned by [DevConsoleWorkspace] @@ -66,13 +77,17 @@ internal fun ControlRoute( viewModel: InspectorViewModel = viewModel(), ) { val state by viewModel.state.collectAsStateWithLifecycle() + val lifecycleState by LocalLifecycleOwner.current.lifecycle.currentStateAsState() val snackbarHostState = remember { SnackbarHostState() } val scope = rememberCoroutineScope() var heroCollapsed by rememberSaveable { mutableStateOf(true) } // starts collapsed var editorTarget by remember { mutableStateOf(null) } var pendingDeleteId by remember { mutableStateOf(null) } - LaunchedEffect(Unit) { viewModel.dispatch(InspectorAction.Refresh) } + LifecycleStartEffect(Unit) { + viewModel.dispatch(InspectorAction.Refresh) + onStopOrDispose { } + } LaunchedEffect(state.lastCommandResult) { state.lastCommandResult?.let { result -> scope.launch { snackbarHostState.showSnackbar(result.toFlashMessage()) } @@ -85,7 +100,7 @@ internal fun ControlRoute( } LaunchedEffect(editorTarget) { onDetailOverlayOpen(editorTarget != null) } KeepAliveNotificationPromptEffect( - promptNeeded = state.keepAlivePromptNeeded, + promptNeeded = state.keepAlivePromptNeeded && lifecycleState.isAtLeast(Lifecycle.State.STARTED), snackbarHostState = snackbarHostState, onPermissionResult = { viewModel.dispatch(InspectorAction.NotificationPermissionGranted) }, ) @@ -112,10 +127,17 @@ internal fun ControlRoute( // the draft before the result (and any rejection) is even known. onSave = { rule -> viewModel.dispatch(InspectorAction.UpsertMockRule(rule)) }, onCancel = { editorTarget = null }, + onDelete = { + val id = (target as? MockRuleEditorTarget.Edit)?.rule?.id + if (id != null) { + editorTarget = null + pendingDeleteId = id + } + }, ) } } - pendingDeleteId?.let { id -> + pendingDeleteId?.takeIf { lifecycleState.isAtLeast(Lifecycle.State.STARTED) }?.let { id -> MockRuleDeleteConfirmDialog( ruleId = id, onConfirm = { @@ -166,9 +188,7 @@ private fun toggleControlFlag( } /** - * Stateless, previewable Control surface: hero, mock-rule rows, flag rows, and the composer-absent - * note. The composer/capture-rules cards the old screen had are gone -- the Control view shows - * neither ("Composer is intentionally absent" below). + * Stateless, previewable Control surface with grouped mock rules and feature flags. */ @Composable @Suppress("LongParameterList") // One callback per real interaction this screen dispatches. @@ -185,114 +205,61 @@ internal fun ControlScreen( modifier: Modifier = Modifier, ) { val colors = DevConsoleTheme.colors - val overrides = rememberControlOverrides(state) + val switchColors = controlSwitchColors(colors) Column(modifier = modifier.fillMaxSize().background(colors.ground)) { InspectorTopArea( - subLine = "Mocks and flags", + subLine = "", title = "Control", actions = listOf(themeToggleTopAction(onToggleTheme)), ) LazyColumn( modifier = Modifier.weight(1f), - contentPadding = PaddingValues(start = 16.dp, top = 4.dp, end = 16.dp, bottom = 16.dp), + contentPadding = PaddingValues(top = 4.dp, bottom = 16.dp), ) { - item { ControlHero(overrides, heroCollapsed, onToggleHero, colors) } - item { Spacer(Modifier.height(16.dp)) } // Mock rules are the MOCKS category's control surface -- when the host didn't enable it // at init, the section (header, New-rule affordance and rows) does not exist at all, // rather than rendering with a permanently-empty/disabled list. if (state.captures(CaptureCategory.MOCKS)) { - item { MockRulesHeader(onNewMockRule, colors) } + item(contentType = "mock_rules_header") { MockRulesHeader(onNewMockRule, colors) } if (state.mockRules.isEmpty()) { - item { MockRulesEmptyNote(colors) } + item(contentType = "mock_rules_empty") { MockRulesEmptyNote(colors) } } else { - items(state.mockRules, key = { it.id }) { rule -> - MockRuleRow(rule, onToggleMockRule, onEditMockRule, onDeleteMockRule, colors) + itemsIndexed( + items = state.mockRules, + key = { _, rule -> rule.id }, + contentType = { _, _ -> "mock_rule" }, + ) { index, rule -> + Column(Modifier.groupedPanelItem(GroupPosition.of(index, state.mockRules.size))) { + MockRuleRow(rule, onToggleMockRule, onEditMockRule, onDeleteMockRule, colors, switchColors) + } } } - item { Spacer(Modifier.height(8.dp)) } + item(contentType = "mock_rules_spacer") { Spacer(Modifier.height(8.dp)) } } // Flags belong to the STATE category; `state.featureFlags` is already emptied by the // data source when STATE is off, but the explicit gate keeps this defensive against a // directly-navigated route the way DATA's sections are (see InspectorDataScreen). if (state.captures(CaptureCategory.STATE) && state.featureFlags.isNotEmpty()) { - item { GroupLabel("Flags") } - items(state.featureFlags, key = { it.key }) { flag -> - FlagRow(flag, colors) { onToggleFlag(flag) } + item(contentType = "feature_flags_header") { GroupLabel("Feature flags") } + itemsIndexed( + items = state.featureFlags, + key = { _, flag -> flag.key }, + contentType = { _, _ -> "feature_flag" }, + ) { index, flag -> + Column(Modifier.groupedPanelItem(GroupPosition.of(index, state.featureFlags.size))) { + FlagRow(flag, colors, switchColors) { onToggleFlag(flag) } + } } - item { Spacer(Modifier.height(8.dp)) } + item(contentType = "feature_flags_spacer") { Spacer(Modifier.height(8.dp)) } } // Remote Config used to render here, beside flags. It moved to the Observe surface's // Config tab (see RemoteConfigTabContent): it is read-only, so nothing on it was ever // a control, and a value big enough to need reading in full needed a detail screen // this list had no way to open. - item { - WarnNote( - "Composer is intentionally absent — typing URLs on a phone is hostile, so " + - "cloning a request hands off to the dashboard.", - ) - } } } } -/** Real, computed count of active overrides. */ -private data class ControlOverrides( - val activeCount: Int, - val total: Int, - val sub: String, -) - -@Composable -private fun rememberControlOverrides(state: InspectorState): ControlOverrides = - remember(state.mockRules, state.featureFlags) { - val enabledMocks = state.mockRules.count { it.enabled } - val overriddenFlags = state.featureFlags.count { it.isOverridden } - val total = state.mockRules.size + state.featureFlags.size - val sub = - if (enabledMocks > 0 || overriddenFlags > 0) { - val parts = - buildList { - if (enabledMocks > 0) add("$enabledMocks mock rule${if (enabledMocks == 1) "" else "s"}") - if (overriddenFlags > 0) { - add("$overriddenFlags flag${if (overriddenFlags == 1) "" else "s"} overridden locally") - } - } - "${parts.joinToString(" and ")} — the app is not in its default state." - } else { - "Nothing is overridden — the app matches its default configuration." - } - ControlOverrides(enabledMocks + overriddenFlags, total, sub) - } - -@Composable -private fun ControlHero( - overrides: ControlOverrides, - collapsed: Boolean, - onToggleCollapse: () -> Unit, - colors: DevConsoleColors, -) { - if (collapsed) { - HeroBar( - value = overrides.activeCount.toString(), - label = "of ${overrides.total} overrides active", - onExpand = onToggleCollapse, - valueColor = colors.put, - labelColor = colors.put, - ) - } else { - HeroCard( - label = "Active overrides", - value = overrides.activeCount.toString(), - valueSuffix = "of ${overrides.total}", - subtitle = overrides.sub, - labelColor = colors.put, - valueColor = colors.put, - onCollapse = onToggleCollapse, - ) - } -} - /** "Mock rules" group label plus the New rule affordance. */ @Composable private fun MockRulesHeader( @@ -304,29 +271,21 @@ private fun MockRulesHeader( verticalAlignment = Alignment.CenterVertically, ) { GroupLabel("Mock rules", modifier = Modifier.weight(1f)) - androidx.compose.material3.OutlinedButton( - onClick = onNewRule, - ) { - Text("New rule", fontSize = 13.sp, color = colors.ink) + IconButton(onClick = onNewRule, modifier = Modifier.padding(end = 12.dp)) { + DevConsoleIcon(R.drawable.devconsole_ic_composer, "New rule", Modifier, colors.muted, 22.dp) } } } @Composable private fun MockRulesEmptyNote(colors: DevConsoleColors) { - Text( - "No mock rules yet — tap New rule to add one.", - color = colors.muted, - fontSize = 13.sp, - modifier = Modifier.padding(start = 8.dp, bottom = 16.dp), - ) + InspectorEmptyState(EmptySpot.Mocks, "No mock rules yet — tap New rule to add one.", spotSize = 64.dp) } /** * Tap opens the edit sheet; enable/disable moved onto the trailing [Switch] so it no longer - * competes with the row's own tap target for "toggle" vs "edit" intent. Delete is a separate small - * destructive action below the row, matching FilesSection's SHARE/DEL convention for a row that - * already does something else on tap. + * competes with the row's own tap target for "toggle" vs "edit" intent. Delete keeps its own + * labelled icon action alongside the switch. */ @Composable private fun MockRuleRow( @@ -335,75 +294,97 @@ private fun MockRuleRow( onEdit: (InspectorMockRuleUi) -> Unit, onDelete: (String) -> Unit, colors: DevConsoleColors, + switchColors: SwitchColors, ) { - val leadColor = if (rule.enabled) colors.signal else colors.text3 - val leadBg = if (rule.enabled) colors.signalSoft else colors.surface3 - val match = - buildString { - append(rule.method ?: "*") - append(' ') - append(rule.pathPattern) - append(" → ") - append(rule.statusCode) - if (rule.actionLabel.isNotBlank()) append(" · ${rule.actionLabel}") - if (rule.hitCount > 0) { - append(" · ${rule.hitCount} hit${if (rule.hitCount == 1L) "" else "s"}") - rule.lastHitEpochMs?.let { append(" · ${formatRelativeHitTime(it)}") } + val subtitleText = + remember(rule) { + val match = + buildString { + append("returns ") + append(rule.statusCode) + // "Static response (200)" only repeats the status already printed above. + if (rule.actionLabel.isNotBlank() && !rule.actionLabel.startsWith("Static response")) { + append(" · ${rule.actionLabel}") + } + if (rule.hitCount > 0) { + append(" · ${rule.hitCount} hit${if (rule.hitCount == 1L) "" else "s"}") + rule.lastHitEpochMs?.let { append(" · ${formatRelativeHitTime(it)}") } + } + } + buildAnnotatedString { + append("returns ") + withStyle( + SpanStyle( + color = + when (rule.statusCode) { + in 500..599 -> colors.error + in 400..499 -> colors.warn + else -> colors.muted + }, + ), + ) { append(rule.statusCode.toString()) } + append(match.substringAfter("returns ${rule.statusCode}")) } } - Column { - TonalListRow( - leadText = if (rule.enabled) "ON" else "OFF", - leadColor = leadColor, - leadContainerColor = leadBg, - title = rule.id, - subtitle = match, - trailValue = rule.scope.lowercase(Locale.US), - trailValueColor = colors.muted, - trailContent = { - Switch( - checked = rule.enabled, - onCheckedChange = { checked -> onToggle(rule.id, checked) }, - modifier = - Modifier.semantics { - contentDescription = - "${if (rule.enabled) "Disable" else "Enable"} mock rule ${rule.id}" - }, + Row( + Modifier + .fillMaxWidth() + .combinedClickable( + onClick = { onEdit(rule) }, + onLongClick = { onDelete(rule.id) }, + onLongClickLabel = "Delete mock rule", + ).semantics { contentDescription = "Edit mock rule ${rule.id}" } + .padding(start = 16.dp, end = 16.dp, top = 12.dp, bottom = 12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + rule.method ?: "ANY", + Modifier.width(64.dp), + color = colors.muted, + fontFamily = FontFamily.Monospace, + fontSize = 14.sp, ) - }, - onClick = { onEdit(rule) }, - // The trailing Switch is its own actionable control -- keep it out of the row's merged - // semantics node so TalkBack exposes both the row's "edit" tap and the switch's toggle. - mergeDescendants = false, - ) - Row(modifier = Modifier.padding(start = 12.dp, bottom = 8.dp)) { - MockRuleDeleteAction(rule.id, colors) { onDelete(rule.id) } + Text( + rule.pathPattern, + color = colors.ink, + fontFamily = FontFamily.Monospace, + fontSize = 14.sp, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + Text( + subtitleText, + color = colors.muted, + fontSize = 12.5.sp, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.padding(top = 4.dp), + ) } + Switch( + checked = rule.enabled, + onCheckedChange = { checked -> onToggle(rule.id, checked) }, + colors = switchColors, + modifier = + Modifier.semantics { + contentDescription = "${if (rule.enabled) "Disable" else "Enable"} mock rule ${rule.id}" + }, + ) } } @Composable -private fun MockRuleDeleteAction( - ruleId: String, - colors: DevConsoleColors, - onClick: () -> Unit, -) { - Text( - "DELETE", - color = colors.error, - fontFamily = FontFamily.Monospace, - fontWeight = FontWeight.Bold, - fontSize = 11.5.sp, - modifier = - Modifier - .minimumInteractiveComponentSize() - .clip(RoundedCornerShape(6.dp)) - .background(colors.errorSoft) - .clickable(onClick = onClick, role = Role.Button) - .padding(horizontal = 10.dp, vertical = 8.dp) - .semantics { contentDescription = "Delete mock rule $ruleId" }, +private fun controlSwitchColors(colors: DevConsoleColors): SwitchColors = + SwitchDefaults.colors( + checkedTrackColor = colors.signal, + checkedThumbColor = colors.signalInk, + uncheckedTrackColor = colors.surface3, + uncheckedThumbColor = colors.muted, + uncheckedBorderColor = colors.borderStrong, ) -} @Composable private fun MockRuleDeleteConfirmDialog( @@ -460,49 +441,33 @@ private fun formatRelativeHitTime(epochMs: Long): String { private fun FlagRow( flag: InspectorFeatureFlagUi, colors: DevConsoleColors, + switchColors: SwitchColors, onClick: () -> Unit, ) { val isBool = flag.type == "BOOLEAN" val isOn = flag.value == "true" - val leadColor = - if (flag.isOverridden) { - colors.warn - } else if (isBool && isOn) { - colors.signal - } else { - colors.text3 - } - val leadBg = - if (flag.isOverridden) { - colors.warnSoft - } else if (isBool && isOn) { - colors.signalSoft - } else { - colors.surface3 - } - val sub = - buildString { - append("flag") - // Non-boolean flags carry their real value in the sub-line -- an ON/OFF badge would lie. - if (!isBool) append(" · ${flag.value}") - if (flag.isOverridden) append(" · overridden locally") - if (flag.description.isNotBlank()) append(" · ${flag.description}") - } TonalListRow( - leadText = - if (!isBool) { - "VAL" - } else if (isOn) { - "ON" - } else { - "OFF" - }, - leadColor = leadColor, - leadContainerColor = leadBg, + leadText = "", + leadColor = colors.muted, + leadContainerColor = colors.panel, title = flag.key, - subtitle = sub, - trailValue = if (flag.isOverridden) "local" else "remote", - trailValueColor = if (flag.isOverridden) colors.warn else colors.muted, + subtitle = + listOfNotNull( + if (!isBool) flag.value else null, + if (flag.isOverridden) "overridden" else null, + ).joinToString(" · "), + trailValue = "", + trailContent = { + if (isBool) { + Switch( + checked = isOn, + onCheckedChange = { onClick() }, + colors = switchColors, + modifier = Modifier.semantics { contentDescription = "Toggle feature flag ${flag.key}" }, + ) + } + }, + mergeDescendants = false, onClick = onClick, ) } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDataScreen.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDataScreen.kt index 43e68d6..4da16c2 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDataScreen.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDataScreen.kt @@ -9,31 +9,47 @@ package io.devconsole.ui.compose import android.content.Context import android.content.Intent import android.content.res.Configuration +import androidx.activity.compose.BackHandler +import androidx.compose.animation.AnimatedContent +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.togetherWith import androidx.compose.foundation.background +import androidx.compose.foundation.clickable import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListScope -import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.Text import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp import androidx.core.content.FileProvider +import androidx.lifecycle.compose.LifecycleStartEffect import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewmodel.compose.viewModel import io.devconsole.api.CaptureCategory @@ -45,9 +61,8 @@ import java.util.Locale * * The [InspectorState.pendingShareFilePath] side effect (launching the system Share sheet) is * handled once, at [DevConsoleWorkspace]'s top level, not here -- that path is set by export - * actions on the MORE destination as well as file shares on this one, and only the currently - * selected destination's composable is part of the composition, so a `LaunchedEffect` here would - * never fire for a share requested while MORE is showing. + * actions on the MORE destination as well as file shares on this one. One workspace consumer + * handles shares even while several destination routes remain composed. */ @Composable internal fun DataRoute( @@ -57,7 +72,10 @@ internal fun DataRoute( ) { val state by viewModel.state.collectAsStateWithLifecycle() var heroCollapsed by rememberSaveable { mutableStateOf(true) } - LaunchedEffect(Unit) { viewModel.dispatch(InspectorAction.Refresh) } + LifecycleStartEffect(Unit) { + viewModel.dispatch(InspectorAction.Refresh) + onStopOrDispose { } + } DataScreen( state = state, heroCollapsed = heroCollapsed, @@ -109,10 +127,8 @@ internal fun shareFileFromPath( } /** - * Stateless, previewable Data surface: hero, read-only prefs rows, and the - * existing Database/Files drill-ins restyled as [TonalListRow]s. Feature-flag editing moved to - * Control's compact toggle rows; per this screen's own note ("Read-only on device"), Data no longer - * offers an inline value editor at all. + * Stateless, previewable Data surface: landing list of sources (Preferences, Database, Files, + * App state) and real drill-in sub-screens for each source. */ @Composable @Suppress("LongParameterList") // One callback group per real interaction this screen dispatches. @@ -124,52 +140,197 @@ internal fun DataScreen( fileActions: FileBrowserActions, databaseActions: DatabaseBrowserActions, modifier: Modifier = Modifier, + initialSource: String? = null, ) { val colors = DevConsoleTheme.colors val hero = rememberDataHero(state) - // imePadding() so the SQL console's OutlinedTextField (DatabaseSection -> SqlConsoleCard) isn't - // rendered underneath the soft keyboard -- same precedent as InspectorDetailScaffold.kt -- a - // no-op when the IME is hidden. Applied here, at the route's outer container, rather than deep - // inside DatabaseSection, so the whole LazyColumn shrinks and its own bringIntoView behavior - // scrolls the focused field above the keyboard instead of just the field's own bounds moving. + var activeSource by rememberSaveable { mutableStateOf(initialSource) } + + val active = availableDataSource(activeSource, state) + + BackHandler(enabled = active != null) { + activeSource = null + } + + val fadeSpec = feedbackSpec() + // imePadding() keeps the SQL console above the soft keyboard; a no-op while the IME is hidden. Column(modifier = modifier.fillMaxSize().background(colors.ground).imePadding()) { + AnimatedContent( + targetState = active, + transitionSpec = { fadeIn(animationSpec = fadeSpec) togetherWith fadeOut(animationSpec = fadeSpec) }, + label = "dataSourceScreen", + modifier = Modifier.fillMaxSize(), + ) { sourceKey -> + when (sourceKey) { + null -> + DataSourceList(state, hero, heroCollapsed, onToggleHero, onToggleTheme, colors) { + activeSource = it + } + "preferences" -> { + DataSourceSubScreen(title = "Preferences", onBack = { activeSource = null }) { + LazyColumn( + modifier = Modifier.weight(1f), + contentPadding = PaddingValues(top = 4.dp, bottom = 16.dp), + ) { + dataPreferenceRows(state, colors) + } + } + } + "database" -> { + DataSourceSubScreen(title = "Database", onBack = { activeSource = null }) { + Column( + modifier = + Modifier + .weight(1f) + .verticalScroll(rememberScrollState()) + .padding(top = 4.dp, bottom = 16.dp), + ) { + DatabaseSection( + state = state, + canWrite = state.capabilities.database, + actions = databaseActions, + ) + } + } + } + "files" -> { + DataSourceSubScreen(title = "Files", onBack = { activeSource = null }) { + Column( + modifier = + Modifier + .weight(1f) + .verticalScroll(rememberScrollState()) + .padding(top = 4.dp, bottom = 16.dp), + ) { + FilesSection( + state = state, + canEdit = state.capabilities.files, + actions = fileActions, + ) + } + } + } + "state" -> { + DataSourceSubScreen(title = "App state", onBack = { activeSource = null }) { + Column( + modifier = + Modifier + .weight(1f) + .verticalScroll(rememberScrollState()) + .padding(top = 4.dp, bottom = 16.dp), + ) { + DataStateProviders(state, colors) + } + } + } + } + } + } +} + +/** The opened source, or null once it is no longer offered (capture turned off, providers gone). */ +private fun availableDataSource( + source: String?, + state: InspectorState, +): String? = + when (source) { + "preferences", "database", "files" -> source.takeIf { state.captures(CaptureCategory.INSPECTION) } + "state" -> source.takeIf { state.stateProviders.isNotEmpty() } + else -> null + } + +@Composable +private fun DataSourceList( + state: InspectorState, + hero: DataHeroInfo, + heroCollapsed: Boolean, + onToggleHero: () -> Unit, + onToggleTheme: () -> Unit, + colors: DevConsoleColors, + onOpenSource: (String) -> Unit, +) { + Column(Modifier.fillMaxSize()) { InspectorTopArea( - subLine = "Preferences · database · files", + subLine = "", title = "Data", actions = listOf(themeToggleTopAction(onToggleTheme)), ) LazyColumn( modifier = Modifier.weight(1f), - contentPadding = PaddingValues(start = 16.dp, top = 4.dp, end = 16.dp, bottom = 16.dp), + contentPadding = PaddingValues(top = 4.dp, bottom = 16.dp), ) { - item { DataHero(hero, heroCollapsed, onToggleHero, colors) } - item { Spacer(Modifier.height(16.dp)) } - dataPreferenceRows(state, colors) + if (hero.blindSpot) { + item { + Box(modifier = Modifier.padding(bottom = 8.dp)) { + DataHero(hero, heroCollapsed, onToggleHero, colors) + } + } + } item { - Column { - Box(modifier = Modifier.padding(top = 4.dp)) { - FilesSection(state = state, canEdit = state.capabilities.files, actions = fileActions) + GroupedPanel { + if (state.captures(CaptureCategory.INSPECTION)) { + DataSourceRow( + "Preferences", + "${state.preferenceFiles.size} files", + R.drawable.devconsole_ic_preferences, + ) { + onOpenSource("preferences") + } + GroupedPanelDivider() + DataSourceRow( + "Database", + state.databaseListing?.let { "${it.name} · ${it.tables.size} tables" } + ?: "${state.databases.size} databases", + R.drawable.devconsole_ic_database, + ) { + onOpenSource("database") + } + GroupedPanelDivider() + DataSourceRow( + "Files", + state.fileListing?.let { "${it.entries.size} items" } + ?: "${state.fileRoots.size} roots", + R.drawable.devconsole_ic_files, + ) { + onOpenSource("files") + } } - Box(modifier = Modifier.padding(top = 16.dp)) { - DatabaseSection( - state = state, - canWrite = state.capabilities.database, - actions = databaseActions, - ) + if (state.stateProviders.isNotEmpty()) { + if (state.captures(CaptureCategory.INSPECTION)) GroupedPanelDivider() + DataSourceRow( + "App state", + state.stateProviders.size.let { "$it ${if (it == 1) "provider" else "providers"}" }, + R.drawable.devconsole_ic_mocks, + ) { + onOpenSource("state") + } } - DataStateProviders(state, colors) - WarnNote( - modifier = Modifier.padding(top = 16.dp), - text = - "Read-only on device. Editing lives on the dashboard, where there is a " + - "keyboard and a wider undo.", - ) } } } } } +@Composable +private fun DataSourceRow( + label: String, + meta: String, + icon: Int, + onClick: () -> Unit, +) { + val colors = DevConsoleTheme.colors + Row( + Modifier.fillMaxWidth().clickable(onClick = onClick).padding(16.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(16.dp), + ) { + DevConsoleIcon(icon, null, Modifier, colors.muted, 22.dp) + Text(label, color = colors.ink, fontSize = 16.sp, modifier = Modifier.weight(1f)) + Text(meta, color = colors.muted, fontFamily = FontFamily.Monospace, fontSize = 12.sp, textAlign = TextAlign.End) + DevConsoleIcon(R.drawable.devconsole_ic_chevron_right, null, Modifier, colors.muted, 18.dp) + } +} + /** * Real prefs entries as read-only rows -- no editor, per this screen's own "Read-only on device" * note. Defensive INSPECTION gate mirrors [FilesSection]/[DatabaseSection]'s: preferences belong to @@ -180,9 +341,22 @@ private fun LazyListScope.dataPreferenceRows( colors: DevConsoleColors, ) { if (!state.captures(CaptureCategory.INSPECTION)) return + if (state.preferenceFiles.isEmpty()) { + item { InspectorEmptyState(EmptySpot.Folder, "No SharedPreferences files found.") } + return + } state.preferenceFiles.forEach { file -> item { GroupLabel(file.name) } - items(file.entries, key = { "${file.name}/${it.key}" }) { entry -> PreferenceRow(entry, colors) } + if (file.entries.isEmpty()) { + item { + GroupedPanel { Text("No preferences.", color = colors.muted, modifier = Modifier.padding(16.dp)) } + } + } + itemsIndexed(file.entries, key = { _, entry -> "${file.name}/${entry.key}" }) { index, entry -> + Column(Modifier.groupedPanelItem(GroupPosition.of(index, file.entries.size))) { + PreferenceRow(entry, colors, state.redactionEnabled) + } + } item { Spacer(Modifier.height(8.dp)) } } } @@ -191,18 +365,29 @@ private fun LazyListScope.dataPreferenceRows( private fun PreferenceRow( entry: InspectorPreferenceEntryUi, colors: DevConsoleColors, + redactionEnabled: Boolean, ) { val style = prefRowStyle(entry, colors) - TonalListRow( - leadText = prefTypeLabel(entry.type), - leadColor = style.leadColor, - leadContainerColor = style.leadBg, - title = entry.key, - subtitle = if (entry.redacted) "••••••••••••••••" else entry.value, - trailValue = style.trailValue, - trailValueColor = style.trailColor, - containerColor = style.rowBg, - ) + // "verbatim" only means something once the host opted in to redaction; by default every value is shown. + val showTokenNote = looksLikeTokenKey(entry.key) && (entry.redacted || redactionEnabled) + Row( + Modifier.fillMaxWidth().padding(16.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(16.dp), + ) { + Column(Modifier.weight(1f)) { + Text(entry.key, color = colors.ink, fontFamily = FontFamily.Monospace, fontSize = 15.sp) + if (showTokenNote) Text(style.trailValue, color = style.trailColor, fontSize = 13.sp) + } + Text( + if (entry.redacted) "••••••••••••••••" else entry.value, + color = colors.muted, + fontFamily = FontFamily.Monospace, + fontSize = 13.sp, + textAlign = TextAlign.End, + modifier = Modifier.weight(1f), + ) + } } private data class PrefRowStyle( @@ -257,9 +442,11 @@ private data class DataHeroInfo( @Composable private fun rememberDataHero(state: InspectorState): DataHeroInfo = - remember(state.preferenceFiles, state.databases, state.fileRoots) { + remember(state.preferenceFiles, state.databases, state.fileRoots, state.redactionEnabled) { val entries = state.preferenceFiles.flatMap { it.entries } - val blindSpots = entries.filter { looksLikeTokenKey(it.key) && !it.redacted } + // With redaction off (the default) every value is shown on purpose, so nothing is a blind spot. + val blindSpots = + if (state.redactionEnabled) entries.filter { looksLikeTokenKey(it.key) && !it.redacted } else emptyList() val maskedTokenLike = entries.filter { looksLikeTokenKey(it.key) && it.redacted } if (blindSpots.isNotEmpty()) { dataBlindSpotHero(blindSpots, maskedTokenLike) @@ -332,12 +519,17 @@ private fun DataHero( private fun DataStateProviders( state: InspectorState, colors: DevConsoleColors, + modifier: Modifier = Modifier, ) { if (state.stateProviders.isEmpty()) return - Column(modifier = Modifier.padding(top = 16.dp)) { + Column(modifier = modifier) { GroupLabel("State providers") - state.stateProviders.forEach { provider -> - provider.entries.forEach { entry -> StateEntryTonalRow(provider.id, entry, colors) } + GroupedPanel { + val entries = state.stateProviders.flatMap { provider -> provider.entries.map { provider.id to it } } + entries.forEachIndexed { index, (id, entry) -> + if (index > 0) GroupedPanelDivider() + StateEntryTonalRow(id, entry, colors) + } } } } @@ -349,12 +541,12 @@ private fun StateEntryTonalRow( colors: DevConsoleColors, ) { TonalListRow( - leadText = "VAR", + leadText = "", leadColor = colors.put, leadContainerColor = colors.putSoft, title = "$providerId.${entry.key}", - subtitle = if (entry.redacted) "redacted" else entry.value, - trailValue = if (entry.redacted) "hidden" else "read", + subtitle = if (entry.redacted) "redacted" else "", + trailValue = if (entry.redacted) "••••••••" else entry.value, trailValueColor = colors.muted, ) } 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 162025a..f60901f 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 @@ -94,6 +94,9 @@ private val URL_BREAK_CHARS = "/?&=.-_,;:+%~@".toSet() */ private const val JOINER_HEADROOM_DIVISOR = 4 +/** [breakingAnywhere]'s inverse: the plain string, for the accessibility tree and text matching. */ +internal fun String.withoutBreakControls(): String = if (WORD_JOINER in this) filterNot { it == WORD_JOINER } else this + /** * Renders a URL as a single unbreakable run, so a row wrapping it fills every line to its edge * instead of leaving a ragged tail. @@ -503,6 +506,8 @@ data class InspectorSnapshot( val keepAlivePromptNeeded: Boolean = false, /** Capture categories the host enabled at init; every list above is already filtered to this set. */ val captureCategories: Set = CaptureCategory.all(), + /** Whether the host opted in to a redaction policy with any rule; off by default. */ + val redactionEnabled: Boolean = false, ) data class InspectorComposerRequest( diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDataSourceScreen.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDataSourceScreen.kt new file mode 100644 index 0000000..405cd69 --- /dev/null +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDataSourceScreen.kt @@ -0,0 +1,72 @@ +/** + * @author Shakib + * @since 19/10/26 + */ +@file:Suppress("FunctionNaming", "MagicNumber") + +package io.devconsole.ui.compose + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.material3.IconButton +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp + +/** + * Top bar for a Data source sub-screen: 48dp back arrow button followed by the screen title. + */ +@Composable +internal fun DataSourceTopBar( + title: String, + onBack: () -> Unit, + modifier: Modifier = Modifier, +) { + val colors = DevConsoleTheme.colors + Row( + modifier = modifier.fillMaxWidth().padding(horizontal = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + IconButton(onClick = onBack, modifier = Modifier.size(48.dp)) { + DevConsoleIcon( + id = R.drawable.devconsole_ic_arrow_back, + contentDescription = "Back to Data", + modifier = Modifier, + tint = colors.ink, + size = 24.dp, + ) + } + Text( + text = title, + modifier = Modifier.weight(1f), + color = colors.ink, + fontSize = 20.sp, + ) + } +} + +/** + * Sub-screen shell for a Data source: renders [DataSourceTopBar] above scrollable [content]. + */ +@Composable +internal fun DataSourceSubScreen( + title: String, + onBack: () -> Unit, + modifier: Modifier = Modifier, + content: @Composable ColumnScope.() -> Unit, +) { + Column( + modifier = modifier.fillMaxSize(), + ) { + DataSourceTopBar(title = title, onBack = onBack) + content() + } +} diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDatabaseSection.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDatabaseSection.kt index 87134e3..cce5e82 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDatabaseSection.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDatabaseSection.kt @@ -6,7 +6,6 @@ package io.devconsole.ui.compose -import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Arrangement @@ -14,6 +13,7 @@ import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.OutlinedTextField @@ -25,13 +25,14 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp import io.devconsole.api.CaptureCategory /** Grouped callbacks for the Room/SQLite database browser and its SQL console. */ @@ -50,9 +51,8 @@ internal fun DatabaseSection( // Defensive: databases belong to the INSPECTION category -- see FilesSection's identical guard. if (!state.captures(CaptureCategory.INSPECTION)) return Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { - TerminalSectionLabel("Databases") when { - state.databases.isEmpty() -> SectionEmptyText("No app databases found.") + state.databases.isEmpty() -> InspectorEmptyState(EmptySpot.Database, "No app databases found.") else -> { DatabaseChips( databases = state.databases, @@ -63,9 +63,11 @@ internal fun DatabaseSection( DatabaseTablesCard(listing = listing, onOpenTable = actions.onOpenTable) } state.queryResult?.let { result -> - TerminalCard { - TerminalSectionLabel("Table rows") - QueryResultTable(result) + GroupedPanel { + Column(Modifier.padding(16.dp)) { + Text("Table rows", color = DevConsoleTheme.colors.ink) + QueryResultTable(result) + } } } SqlConsoleCard( @@ -86,24 +88,22 @@ private fun DatabaseChips( onOpenDatabase: (String) -> Unit, ) { val colors = DevConsoleTheme.colors - Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { - databases.forEach { database -> + GroupedPanel { + databases.forEachIndexed { index, database -> + if (index > 0) GroupedPanelDivider() val isSelected = database == selected - val background = if (isSelected) colors.signal else colors.surface2 - val foreground = if (isSelected) colors.signalInk else colors.muted Text( text = database, - color = foreground, + color = colors.ink, fontFamily = FontFamily.Monospace, - fontWeight = FontWeight.Bold, - style = TerminalType.labelSmall, + fontWeight = if (isSelected) FontWeight.SemiBold else FontWeight.Normal, + fontSize = 14.sp, modifier = Modifier .minimumInteractiveComponentSize() - .clip(RoundedCornerShape(6.dp)) - .background(background) + .fillMaxWidth() .clickable { onOpenDatabase(database) } - .padding(horizontal = 10.dp, vertical = 6.dp) + .padding(horizontal = 16.dp, vertical = 14.dp) .semantics { contentDescription = "Open database $database" }, ) } @@ -128,17 +128,23 @@ private fun DatabaseTablesCard( listing: InspectorDatabaseListingUi, onOpenTable: (String, String) -> Unit, ) { - TerminalCard { - TerminalSectionLabel(listing.name) - DatabaseSizeSubtitle(listing) + GroupedPanel { + Column(Modifier.padding(16.dp)) { + Text(listing.name, color = DevConsoleTheme.colors.ink, fontFamily = FontFamily.Monospace) + DatabaseSizeSubtitle(listing) + } if (listing.tables.isEmpty()) { Text( text = "No tables found.", color = DevConsoleTheme.colors.muted, style = TerminalType.bodySmall, + modifier = Modifier.padding(16.dp), ) } else { - listing.tables.forEach { table -> DatabaseTableRow(listing.name, table, onOpenTable) } + listing.tables.forEach { table -> + GroupedPanelDivider() + DatabaseTableRow(listing.name, table, onOpenTable) + } } } } @@ -153,21 +159,15 @@ private fun DatabaseTableRow( val colors = DevConsoleTheme.colors Column(modifier = Modifier.fillMaxWidth()) { TonalListRow( - leadText = "TBL", + leadText = "", leadColor = colors.put, leadContainerColor = colors.putSoft, title = table.name, - subtitle = database, - trailValue = table.rowCount.toString(), - trailValueColor = colors.ink, - trailSubtitle = if (table.rowCount == 1L) "row" else "rows", - containerColor = androidx.compose.ui.graphics.Color.Transparent, + subtitle = "", + trailValue = "${table.rowCount} ${if (table.rowCount == 1L) "row" else "rows"}", + trailValueColor = colors.muted, onClick = { onOpenTable(database, table.name) }, ) - androidx.compose.material3.HorizontalDivider( - modifier = Modifier.padding(start = 76.dp), - color = colors.line, - ) } } @@ -178,20 +178,33 @@ private fun QueryResultTable(result: InspectorQueryResultUi) { modifier = Modifier.horizontalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(4.dp), ) { - Text( - text = result.columns.joinToString(" | "), - color = colors.signal, - fontFamily = FontFamily.Monospace, - fontWeight = FontWeight.Bold, - style = TerminalType.bodySmall, - ) + Row { + result.columns.forEach { column -> + Text( + column, + color = colors.ink, + fontFamily = FontFamily.Monospace, + fontWeight = FontWeight.Bold, + style = TerminalType.bodySmall, + modifier = Modifier.width(160.dp).padding(8.dp), + textAlign = TextAlign.End, + ) + } + } result.rows.forEach { row -> - Text( - text = row.joinToString(" | "), - color = colors.ink, - fontFamily = FontFamily.Monospace, - style = TerminalType.bodySmall, - ) + GroupedPanelDivider() + Row { + row.forEach { value -> + Text( + value, + color = colors.muted, + fontFamily = FontFamily.Monospace, + style = TerminalType.bodySmall, + modifier = Modifier.width(160.dp).padding(8.dp), + textAlign = TextAlign.End, + ) + } + } } if (result.truncated) { Text( @@ -211,39 +224,41 @@ private fun SqlConsoleCard( onExecuteSql: (String, String) -> Unit, ) { val colors = DevConsoleTheme.colors - TerminalCard { - TerminalSectionLabel("SQL console") - var draft by remember { mutableStateOf("") } - OutlinedTextField( - value = draft, - onValueChange = { draft = it }, - textStyle = TerminalType.bodySmall.copy(fontFamily = FontFamily.Monospace), - modifier = Modifier.fillMaxWidth().semantics { contentDescription = "SQL statement input" }, - ) - if (!canWrite) { - CapabilityDisabledNotice( - text = "Read-only — enable the database capability to run write statements.", - ) - } - val canRun = selectedDatabase != null && draft.isNotBlank() - if (canRun) { - Text( - text = "RUN", - color = colors.signal, - fontFamily = FontFamily.Monospace, - fontWeight = FontWeight.Bold, - style = TerminalType.labelSmall, - modifier = - Modifier - .minimumInteractiveComponentSize() - .clip(RoundedCornerShape(6.dp)) - .background(colors.surface2) - .clickable { onExecuteSql(requireNotNull(selectedDatabase), draft) } - .padding(horizontal = 10.dp, vertical = 8.dp) - .semantics { contentDescription = "Run SQL statement" }, + GroupedPanel { + Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + Text("SQL console", color = colors.ink) + var draft by remember { mutableStateOf("") } + OutlinedTextField( + value = draft, + onValueChange = { draft = it }, + textStyle = TerminalType.bodySmall.copy(fontFamily = FontFamily.Monospace), + shape = RoundedCornerShape(12.dp), + colors = + androidx.compose.material3.OutlinedTextFieldDefaults.colors( + focusedBorderColor = colors.signal, + unfocusedBorderColor = colors.line, + focusedContainerColor = colors.panel, + unfocusedContainerColor = colors.panel, + ), + modifier = Modifier.fillMaxWidth().semantics { contentDescription = "SQL statement input" }, ) + if (!canWrite) { + CapabilityDisabledNotice( + text = "Read-only — enable the database capability to run write statements.", + ) + } + val canRun = selectedDatabase != null && draft.isNotBlank() + if (canRun) { + InspectorPillButton( + label = "RUN", + onClick = { onExecuteSql(requireNotNull(selectedDatabase), draft) }, + containerColor = colors.signal, + contentColor = colors.signalInk, + modifier = Modifier.semantics { contentDescription = "Run SQL statement" }, + ) + } + sqlResult?.let { SqlResultView(it) } } - sqlResult?.let { SqlResultView(it) } } } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDestinationHost.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDestinationHost.kt new file mode 100644 index 0000000..bfca87b --- /dev/null +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDestinationHost.kt @@ -0,0 +1,97 @@ +/** + * @author Shakib + * @since 19/10/26 + */ +@file:Suppress("DEPRECATION", "FunctionNaming") + +package io.devconsole.ui.compose + +import androidx.compose.animation.core.Animatable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.SideEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.layout.layout +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleEventObserver +import androidx.lifecycle.LifecycleOwner +import androidx.lifecycle.LifecycleRegistry +import androidx.lifecycle.compose.LocalLifecycleOwner +import androidx.compose.ui.platform.LocalLifecycleOwner as LegacyLocalLifecycleOwner + +/** Keeps a destination composed while its lifecycle, placement and input follow selection. */ +@Composable +internal fun DestinationHost( + active: Boolean, + content: @Composable () -> Unit, +) { + val parentLifecycle = LocalLifecycleOwner.current.lifecycle + val owner = remember(parentLifecycle) { InspectorDestinationLifecycleOwner() } + val currentActive by rememberUpdatedState(active) + DisposableEffect(parentLifecycle, owner) { + val observer = LifecycleEventObserver { _, _ -> owner.update(parentLifecycle.currentState, currentActive) } + parentLifecycle.addObserver(observer) + owner.update(parentLifecycle.currentState, currentActive) + onDispose { + parentLifecycle.removeObserver(observer) + owner.update(Lifecycle.State.DESTROYED, active = false) + } + } + SideEffect { owner.update(parentLifecycle.currentState, active) } + + val alpha = remember { Animatable(0f) } + val animationSpec = feedbackSpec() + LaunchedEffect(active) { + alpha.snapTo(0f) + if (active) alpha.animateTo(1f, animationSpec) + } + // Supply both entry points so legacy BackHandlers and lifecycle-aware collectors share the cap. + CompositionLocalProvider( + LocalLifecycleOwner provides owner, + LegacyLocalLifecycleOwner provides owner, + ) { + Box( + modifier = + Modifier + .fillMaxSize() + .then(if (active) Modifier else Modifier.clearAndSetSemantics {}) + .layout { measurable, constraints -> + val placeable = measurable.measure(constraints) + layout(placeable.width, placeable.height) { + if (active) placeable.place(0, 0) + } + }.graphicsLayer { this.alpha = alpha.value }, + ) { + content() + } + } +} + +/** A main-thread registry capped at CREATED whenever its destination is hidden. */ +private class InspectorDestinationLifecycleOwner : LifecycleOwner { + private val registry = LifecycleRegistry(this) + + override val lifecycle: Lifecycle = registry + + fun update( + parentState: Lifecycle.State, + active: Boolean, + ) { + val cap = if (active) Lifecycle.State.RESUMED else Lifecycle.State.CREATED + val target = minOf(parentState, cap) + // A destination can leave composition before its parent has emitted ON_CREATE. + if (target == Lifecycle.State.DESTROYED && registry.currentState == Lifecycle.State.INITIALIZED) { + registry.currentState = Lifecycle.State.CREATED + } + registry.currentState = target + } +} diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailHeader.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailHeader.kt index b2d99bc..cb0c2c1 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailHeader.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailHeader.kt @@ -2,38 +2,31 @@ * @author Shakib * @since 04/08/26 */ -@file:Suppress("FunctionNaming", "MagicNumber") +@file:Suppress("FunctionNaming", "MagicNumber", "UNUSED_PARAMETER") package io.devconsole.ui.compose -import androidx.compose.foundation.background -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size -import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.rememberScrollState +import androidx.compose.material3.IconButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip -import androidx.compose.ui.draw.drawBehind -import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.font.FontFamily -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.text.withStyle import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp -/** - * Detail screen header (header portion only -- the find field is [InspectorDetailSearchField]): - * 48dp round back button + kind label + trailing 48dp round actions, then a lead badge, mono - * title (wraps, does not truncate), sub, and a big mono status. - */ +/** Compact capture identity and a single metadata line. Badge parameters preserve callers. */ @Suppress("LongParameterList") // Every field below is part of the header payload. @Composable internal fun InspectorDetailHeader( @@ -50,92 +43,50 @@ internal fun InspectorDetailHeader( backContentDescription: String = "Back to the list", actions: List = emptyList(), ) { - val lineColor = DevConsoleTheme.colors.line - Column( - modifier = - modifier - .fillMaxWidth() - .drawBehind { - // Centred on the exact bottom edge clips half the stroke outside the layout's - // bounds; inset by half the stroke width so the whole 1dp line stays on-canvas. - val strokeWidth = 1.dp.toPx() - val y = size.height - strokeWidth / 2 - drawLine(lineColor, Offset(0f, y), Offset(size.width, y), strokeWidth) - }.padding(top = 8.dp, start = 8.dp, end = 8.dp, bottom = 4.dp), - ) { - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(2.dp)) { - InspectorRoundIconButton( - contentDescription = backContentDescription, - onClick = onBack, - icon = { - InspectorGlyphIcon( - InspectorGlyph.ChevronDown, - contentDescription = null, - tint = DevConsoleTheme.colors.ink, - size = 20.dp, - rotationDegrees = 90f, - ) - }, - ) + val colors = DevConsoleTheme.colors + Column(modifier = modifier.fillMaxWidth().padding(top = 8.dp, bottom = 16.dp)) { + Row( + modifier = Modifier.fillMaxWidth().padding(horizontal = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + IconButton(onClick = onBack, modifier = Modifier.size(48.dp)) { + DevConsoleIcon( + R.drawable.devconsole_ic_arrow_back, + backContentDescription, + Modifier, + colors.ink, + 24.dp, + ) + } Text( - kindLabel, + title, modifier = Modifier.weight(1f), - color = DevConsoleTheme.colors.muted, - fontSize = 13.sp, - fontWeight = FontWeight.SemiBold, - maxLines = 1, - overflow = TextOverflow.Ellipsis, + color = colors.ink, + fontFamily = FontFamily.Monospace, + fontSize = 20.sp, ) actions.forEach { action -> InspectorRoundIconButton( contentDescription = action.contentDescription, onClick = action.onClick, - containerColor = action.containerColor, icon = action.icon, ) } } - DetailHeaderIdentityRow(leadText, leadColor, leadContainerColor, title, subtitle, status, statusColor) - } -} - -@Suppress("LongParameterList") // Same header payload as InspectorDetailHeader. -@Composable -private fun DetailHeaderIdentityRow( - leadText: String, - leadColor: Color, - leadContainerColor: Color, - title: String, - subtitle: String, - status: String, - statusColor: Color, -) { - Row( - modifier = Modifier.padding(top = 2.dp, start = 12.dp, end = 12.dp, bottom = 12.dp), - horizontalArrangement = Arrangement.spacedBy(12.dp), - ) { - Box( - modifier = Modifier.size(44.dp).clip(CircleShape).background(leadContainerColor), - contentAlignment = Alignment.Center, - ) { - Text( - leadText, - color = leadColor, - fontFamily = FontFamily.Monospace, - fontSize = 11.5.sp, - fontWeight = FontWeight.Bold, - ) - } - Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) { - Text(title, color = DevConsoleTheme.colors.ink, fontFamily = FontFamily.Monospace, fontSize = 14.5.sp) - Text(subtitle, color = DevConsoleTheme.colors.muted, fontSize = 12.5.sp) - } Text( - status, - color = statusColor, + buildAnnotatedString { + withStyle(SpanStyle(color = statusColor)) { append(status) } + if (status.isNotEmpty() && subtitle.isNotEmpty()) append(' ') + append(subtitle) + }, + modifier = + Modifier + .padding(start = 20.dp, end = 20.dp, top = 12.dp) + .horizontalScroll(rememberScrollState()), + color = colors.muted, fontFamily = FontFamily.Monospace, - fontSize = 20.sp, - fontWeight = FontWeight.Bold, + fontSize = 13.sp, + maxLines = 1, ) } } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailPreviews.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailPreviews.kt index b0d61c9..dab1278 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailPreviews.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailPreviews.kt @@ -43,6 +43,46 @@ private fun InspectorDetailHeaderPreview() { } } +@Preview(name = "Network tabs · Dark", uiMode = Configuration.UI_MODE_NIGHT_YES, widthDp = 390, heightDp = 840) +@Preview(name = "Network tabs · Light", uiMode = Configuration.UI_MODE_NIGHT_NO, widthDp = 390, heightDp = 840) +@Composable +private fun InspectorNetworkDetailTabsPreview() { + DevConsoleTheme(darkTheme = isSystemInDarkTheme()) { + val transaction = + InspectorTransactionUi( + id = "detail-tabs-preview", + method = "DELETE", + host = "api.example.test", + path = "/todos/1", + statusCode = 500, + durationMs = 612, + requestHeaders = mapOf("accept" to "application/json"), + responseHeaders = mapOf("content-type" to "application/json", "content-length" to "1434"), + responsePreview = """{"error":"internal","traceId":"a91f3e2c-5b8a-4c21"}""", + ) + val content = + netDetailContent( + transaction = transaction, + colors = DevConsoleTheme.colors, + isFlagged = false, + onToggleFlag = {}, + copyText = {}, + shareText = { _, _ -> }, + onMockThisResponse = {}, + onUnmockThisResponse = {}, + ) + InspectorObserveDetailScreen( + resetKey = transaction.id, + header = content.header, + sections = content.sections, + initiallyOpenSectionKeys = content.initiallyOpenSectionKeys, + footerActions = content.footerActions, + onBack = {}, + searchOptions = content.searchOptions, + ) + } +} + @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/InspectorEmptyState.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorEmptyState.kt new file mode 100644 index 0000000..d36be74 --- /dev/null +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorEmptyState.kt @@ -0,0 +1,87 @@ +/** + * @author Shakib + * @since 19/10/26 + */ +@file:Suppress("FunctionNaming", "MagicNumber", "MatchingDeclarationName") // Named for its main composable. + +package io.devconsole.ui.compose + +import androidx.annotation.DrawableRes +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.widthIn +import androidx.compose.material3.Icon +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp + +/** Empty-state spot illustrations (the web's `dc-spot-*` symbols): a muted base vector with a + * signal accent vector drawn over it, so both follow the theme. */ +internal enum class EmptySpot( + @DrawableRes val base: Int, + @DrawableRes val accent: Int, +) { + Traffic(R.drawable.devconsole_spot_traffic, R.drawable.devconsole_spot_traffic_accent), + Sockets(R.drawable.devconsole_spot_sockets, R.drawable.devconsole_spot_sockets_accent), + CrashesClear(R.drawable.devconsole_spot_crashes, R.drawable.devconsole_spot_crashes_accent), + Push(R.drawable.devconsole_spot_push, R.drawable.devconsole_spot_push_accent), + Logs(R.drawable.devconsole_spot_logs, R.drawable.devconsole_spot_logs_accent), + Mocks(R.drawable.devconsole_spot_mocks, R.drawable.devconsole_spot_mocks_accent), + RemoteConfig(R.drawable.devconsole_spot_remote_config, R.drawable.devconsole_spot_remote_config_accent), + Search(R.drawable.devconsole_spot_search, R.drawable.devconsole_spot_search_accent), + Folder(R.drawable.devconsole_spot_folder, R.drawable.devconsole_spot_folder_accent), + Database(R.drawable.devconsole_spot_database, R.drawable.devconsole_spot_database_accent), +} + +@Composable +internal fun EmptySpotImage( + spot: EmptySpot, + size: Dp = 80.dp, + modifier: Modifier = Modifier, +) { + val colors = DevConsoleTheme.colors + Box(modifier.size(size)) { + Icon(painterResource(spot.base), contentDescription = null, tint = colors.text3, modifier = Modifier.size(size)) + Icon( + painterResource(spot.accent), + contentDescription = null, + tint = colors.signal, + modifier = Modifier.size(size), + ) + } +} + +/** Centred spot plus one muted sentence; the sentence is the whole message, the spot is decoration. */ +@Composable +internal fun InspectorEmptyState( + spot: EmptySpot, + message: String, + modifier: Modifier = Modifier, + spotSize: Dp = 80.dp, +) { + Column( + modifier = modifier.fillMaxWidth().padding(horizontal = 32.dp, vertical = 40.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(16.dp), + ) { + EmptySpotImage(spot, spotSize) + Text( + message, + modifier = Modifier.widthIn(max = 280.dp), + color = DevConsoleTheme.colors.muted, + fontSize = 14.sp, + lineHeight = 20.sp, + textAlign = TextAlign.Center, + ) + } +} diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorFilesSection.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorFilesSection.kt index 25c22bc..71151f0 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorFilesSection.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorFilesSection.kt @@ -6,7 +6,6 @@ package io.devconsole.ui.compose -import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column @@ -52,9 +51,8 @@ internal fun FilesSection( // its own too, in case something ever reaches it by a route other than that nav item. if (!state.captures(CaptureCategory.INSPECTION)) return Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { - TerminalSectionLabel("App files") when { - state.fileRoots.isEmpty() -> SectionEmptyText("No file storage roots available.") + state.fileRoots.isEmpty() -> InspectorEmptyState(EmptySpot.Folder, "No file storage roots available.") else -> { FileRootChips( roots = state.fileRoots, @@ -79,11 +77,11 @@ private fun FileRootChips( onOpenRoot: (String, String) -> Unit, ) { val colors = DevConsoleTheme.colors - Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { - roots.forEach { root -> + GroupedPanel { + roots.forEachIndexed { index, root -> + if (index > 0) GroupedPanelDivider() val isSelected = root == selected - val background = if (isSelected) colors.signal else colors.surface2 - val foreground = if (isSelected) colors.signalInk else colors.muted + val foreground = if (isSelected) colors.ink else colors.muted Text( text = root, color = foreground, @@ -93,10 +91,9 @@ private fun FileRootChips( modifier = Modifier .minimumInteractiveComponentSize() - .clip(RoundedCornerShape(6.dp)) - .background(background) + .fillMaxWidth() .clickable { onOpenRoot(root, "") } - .padding(horizontal = 10.dp, vertical = 6.dp) + .padding(horizontal = 16.dp, vertical = 14.dp) .semantics { contentDescription = "Open $root storage root" }, ) } @@ -109,9 +106,14 @@ private fun FileListingCard( canEdit: Boolean, actions: FileBrowserActions, ) { - TerminalCard { + GroupedPanel { val here = if (listing.relativePath.isEmpty()) listing.root else "${listing.root}/${listing.relativePath}" - TerminalSectionLabel(here) + Text( + here, + color = DevConsoleTheme.colors.muted, + fontFamily = FontFamily.Monospace, + modifier = Modifier.padding(16.dp), + ) if (listing.relativePath.isNotEmpty()) { FileRow( label = "..", @@ -125,9 +127,11 @@ private fun FileListingCard( text = "Empty directory.", color = DevConsoleTheme.colors.muted, style = TerminalType.bodySmall, + modifier = Modifier.padding(16.dp), ) } else { listing.entries.forEach { entry -> + GroupedPanelDivider() FileEntryRow(root = listing.root, entry = entry, canEdit = canEdit, actions = actions) } } @@ -149,14 +153,13 @@ private fun FileEntryRow( val colors = DevConsoleTheme.colors Column(modifier = Modifier.fillMaxWidth()) { TonalListRow( - leadText = if (entry.isDirectory) "DIR" else "FILE", + leadText = "", leadColor = if (entry.isDirectory) colors.signal else colors.put, leadContainerColor = if (entry.isDirectory) colors.signalSoft else colors.putSoft, title = entry.name, - subtitle = if (entry.isDirectory) "directory" else "${entry.sizeBytes} B", - trailValue = if (entry.isDirectory) "›" else "", + subtitle = "", + trailValue = if (entry.isDirectory) "›" else formatByteSize(entry.sizeBytes), trailValueColor = colors.muted, - containerColor = androidx.compose.ui.graphics.Color.Transparent, onClick = { if (entry.isDirectory) { actions.onOpenPath(root, entry.relativePath) @@ -166,10 +169,6 @@ private fun FileEntryRow( }, ) if (canEdit && !entry.isDirectory) FileEntryActions(root, entry, actions) - androidx.compose.material3.HorizontalDivider( - modifier = Modifier.padding(start = 76.dp), - color = colors.line, - ) } } @@ -194,7 +193,7 @@ private fun FileEntryActionText( val colors = DevConsoleTheme.colors Text( text = label, - color = colors.put, + color = colors.muted, fontFamily = FontFamily.Monospace, fontWeight = FontWeight.Bold, style = TerminalType.labelSmall, @@ -202,7 +201,6 @@ private fun FileEntryActionText( Modifier .minimumInteractiveComponentSize() .clip(RoundedCornerShape(6.dp)) - .background(colors.putSoft) .clickable(onClick = onClick) .padding(horizontal = 10.dp, vertical = 8.dp) .semantics { contentDescription = description }, @@ -220,13 +218,14 @@ private fun FileRow( val colors = DevConsoleTheme.colors Text( text = label, - color = if (isDirectory) colors.signal else colors.ink, + color = colors.ink, fontFamily = FontFamily.Monospace, style = TerminalType.bodySmall, modifier = modifier .clickable(onClick = onClick) - .padding(vertical = 6.dp) + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 12.dp) .semantics { contentDescription = description }, ) } @@ -237,53 +236,47 @@ private fun FilePreviewCard( onClose: () -> Unit, ) { val colors = DevConsoleTheme.colors - TerminalCard { - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically, - ) { - TerminalSectionLabel("Preview") - Text( - text = "CLOSE", - color = colors.signal, - fontFamily = FontFamily.Monospace, - fontWeight = FontWeight.Bold, - style = TerminalType.labelSmall, - modifier = - Modifier - .clickable(onClick = onClose) - .semantics { contentDescription = "Close file preview" }, - ) - } - when (preview) { - is InspectorFilePreviewUi.Text -> { + GroupedPanel { + Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically, + ) { + Text("Preview", color = colors.ink) Text( - text = preview.content, - color = colors.ink, + text = "CLOSE", + color = colors.muted, fontFamily = FontFamily.Monospace, - style = TerminalType.bodySmall, + fontWeight = FontWeight.Bold, + style = TerminalType.labelSmall, + modifier = + Modifier + .clickable(onClick = onClose) + .semantics { contentDescription = "Close file preview" }, ) - if (preview.truncated) { + } + when (preview) { + is InspectorFilePreviewUi.Text -> { Text( - text = "… truncated", - color = colors.muted, - style = TerminalType.labelSmall, + text = preview.content, + color = colors.ink, + fontFamily = FontFamily.Monospace, + style = TerminalType.bodySmall, ) + if (preview.truncated) { + Text("… truncated", color = colors.muted, style = TerminalType.labelSmall) + } } + is InspectorFilePreviewUi.Binary -> + Text( + text = "Binary file, ${preview.sizeBytes} bytes — preview withheld.", + color = colors.muted, + style = TerminalType.bodySmall, + ) + is InspectorFilePreviewUi.Unavailable -> + Text(preview.reason, color = colors.muted, style = TerminalType.bodySmall) } - is InspectorFilePreviewUi.Binary -> - Text( - text = "Binary file, ${preview.sizeBytes} bytes — preview withheld.", - color = colors.muted, - style = TerminalType.bodySmall, - ) - is InspectorFilePreviewUi.Unavailable -> - Text( - text = preview.reason, - color = colors.muted, - style = TerminalType.bodySmall, - ) } } } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorFormattableBody.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorFormattableBody.kt index a8f5a15..3d5bf26 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorFormattableBody.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorFormattableBody.kt @@ -10,7 +10,6 @@ package io.devconsole.ui.compose import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.horizontalScroll -import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer @@ -53,7 +52,7 @@ import androidx.compose.ui.unit.sp * [InspectorCodeBlock]): a Raw/Formatted toggle when formatting is available, a size-guard notice * when it isn't (body too large), and either the raw redaction-aware lines, a pretty-printed XML * code block, or -- for JSON -- the collapsible tree ([flattenJsonTree]). [onExpandFullScreen], when - * given, shows the same top-right expand button [InspectorCodeBlock] does. + * given, shows the same trailing Expand action [InspectorCodeBlock] does. */ @Composable internal fun InspectorFormattableBody( @@ -96,12 +95,8 @@ internal fun InspectorFormattableBody( RawFormattedToggle( showRaw = renderedShowRaw, onToggle = updateShowRaw, - // Matches the 16dp horizontal inset InspectorKeyValueList/InspectorProgressBars/ - // InspectorDetailEmptyText each apply themselves for a CollapsibleSection's content -- - // FilterChipRow carries no inset of its own (its other callers sit inside a parent - // that already pads), so without this the chip row alone sat flush against the - // section/card edge while every sibling body stayed inset. - modifier = Modifier.padding(horizontal = 16.dp).padding(bottom = 8.dp), + // The enclosing detail panel supplies the code area inset. + modifier = Modifier.padding(bottom = 8.dp), ) } if (body.tooLarge) { @@ -116,13 +111,13 @@ internal fun InspectorFormattableBody( modifier = Modifier.padding(bottom = 8.dp), ) } - Box(modifier = Modifier.fillMaxWidth()) { + Column(modifier = Modifier.fillMaxWidth()) { LazyColumn( state = listState, modifier = Modifier .fillMaxWidth() - .clip(RoundedCornerShape(16.dp)) + .clip(RoundedCornerShape(8.dp)) .background(colors.codeBg) .heightIn(max = InlineCodeBlockMaxHeight) // Same known tradeoff as InspectorCodeBlock's own horizontalScroll: a diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorGlyphs.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorGlyphs.kt index ce48adb..df1038e 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorGlyphs.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorGlyphs.kt @@ -3,11 +3,9 @@ * @since 04/08/26 */ @file:Suppress("FunctionNaming", "MagicNumber", "MatchingDeclarationName") -@file:OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class) package io.devconsole.ui.compose -import androidx.compose.foundation.Canvas import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable @@ -27,17 +25,9 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.rotate -import androidx.compose.ui.geometry.Offset -import androidx.compose.ui.geometry.RoundRect import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.Path -import androidx.compose.ui.graphics.StrokeCap -import androidx.compose.ui.graphics.StrokeJoin -import androidx.compose.ui.graphics.drawscope.DrawScope -import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.contentDescription -import androidx.compose.ui.semantics.invisibleToUser import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow @@ -47,16 +37,14 @@ import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp /** - * The small, hand-authored glyph set the shared components need (search, chevron, check, alert, - * flag, copy). There is no icon library dependency in this module; the glyphs are bespoke (not - * Material Symbols), with coordinates below on a 16x16 viewBox `` data. + * The small glyph set the shared components need (search, chevron, check, alert, flag, copy). Each + * maps to one of the module's `devconsole_ic_*` vector drawables -- the same 24dp, 1.5-stroke set the + * web dashboard's sprite ships -- so the two surfaces draw identical icons. */ internal enum class InspectorGlyph { Search, ChevronDown, Check, Alert, Flag, Copy, Expand } /** DESIGN.md's disabled treatment: the whole control at half opacity, container and content alike. */ private const val DISABLED_PILL_ALPHA = 0.5f -private const val GLYPH_VIEWBOX = 16f -private const val GLYPH_STROKE_WIDTH = 1.4f /** * Renders one [InspectorGlyph]. Pass [contentDescription] only when this icon is the sole @@ -76,96 +64,19 @@ internal fun InspectorGlyphIcon( size: Dp = 18.dp, rotationDegrees: Float = 0f, ) { - Canvas( - modifier = - modifier - .size(size) - .rotate(rotationDegrees) - .then( - if (contentDescription != null) { - Modifier.semantics { this.contentDescription = contentDescription } - } else { - Modifier.semantics { invisibleToUser() } - }, - ), - ) { - drawInspectorGlyph(glyph, tint) - } + DevConsoleIcon(glyph.drawableRes(), contentDescription, modifier.rotate(rotationDegrees), tint, size) } -@Suppress("LongMethod") // One draw routine per glyph shape, all in one when -- see ObserveGlyph's own suppression. -private fun DrawScope.drawInspectorGlyph( - glyph: InspectorGlyph, - tint: Color, -) { - val scale = size.width / GLYPH_VIEWBOX - val stroke = - Stroke( - width = size.width * (GLYPH_STROKE_WIDTH / GLYPH_VIEWBOX), - cap = StrokeCap.Round, - join = StrokeJoin.Round, - ) - val path = Path() - when (glyph) { - InspectorGlyph.Search -> { - drawCircle(color = tint, radius = 4.2f * scale, center = Offset(7f * scale, 7f * scale), style = stroke) - path.moveTo(10.2f * scale, 10.2f * scale) - path.lineTo(14f * scale, 14f * scale) - } - InspectorGlyph.ChevronDown -> { - path.moveTo(4f * scale, 6.5f * scale) - path.lineTo(8f * scale, 10.5f * scale) - path.lineTo(12f * scale, 6.5f * scale) - } - InspectorGlyph.Check -> { - path.moveTo(3f * scale, 8.5f * scale) - path.lineTo(6.2f * scale, 11.5f * scale) - path.lineTo(13f * scale, 4.5f * scale) - } - InspectorGlyph.Alert -> { - path.moveTo(8f * scale, 2.5f * scale) - path.lineTo(14.5f * scale, 13.5f * scale) - path.lineTo(1.5f * scale, 13.5f * scale) - path.close() - path.moveTo(8f * scale, 6.6f * scale) - path.lineTo(8f * scale, 9.6f * scale) - drawCircle(color = tint, radius = stroke.width / 2f, center = Offset(8f * scale, 11.6f * scale)) - } - InspectorGlyph.Flag -> { - path.moveTo(4f * scale, 14f * scale) - path.lineTo(4f * scale, 2.5f * scale) - path.lineTo(12f * scale, 2.5f * scale) - path.lineTo(10f * scale, 5.5f * scale) - path.lineTo(12f * scale, 8.5f * scale) - path.lineTo(4f * scale, 8.5f * scale) - } - InspectorGlyph.Copy -> { - path.addRoundRect( - RoundRect(6.8f * scale, 5.5f * scale, 13.5f * scale, 12.2f * scale, 1.3f * scale, 1.3f * scale), - ) - path.addRoundRect( - RoundRect(3.3f * scale, 3f * scale, 10.3f * scale, 10f * scale, 1.3f * scale, 1.3f * scale), - ) - } - InspectorGlyph.Expand -> { - // Four open corner brackets -- a fullscreen/expand affordance, disconnected on purpose - // (no closed outline) so it reads distinct from Copy's two overlapping rectangles. - path.moveTo(2f * scale, 5.5f * scale) - path.lineTo(2f * scale, 2f * scale) - path.lineTo(5.5f * scale, 2f * scale) - path.moveTo(10.5f * scale, 2f * scale) - path.lineTo(14f * scale, 2f * scale) - path.lineTo(14f * scale, 5.5f * scale) - path.moveTo(14f * scale, 10.5f * scale) - path.lineTo(14f * scale, 14f * scale) - path.lineTo(10.5f * scale, 14f * scale) - path.moveTo(5.5f * scale, 14f * scale) - path.lineTo(2f * scale, 14f * scale) - path.lineTo(2f * scale, 10.5f * scale) - } +private fun InspectorGlyph.drawableRes(): Int = + when (this) { + InspectorGlyph.Search -> R.drawable.devconsole_ic_search + InspectorGlyph.ChevronDown -> R.drawable.devconsole_ic_chevron_down + InspectorGlyph.Check -> R.drawable.devconsole_ic_check + InspectorGlyph.Alert -> R.drawable.devconsole_ic_crashes + InspectorGlyph.Flag -> R.drawable.devconsole_ic_evidence + InspectorGlyph.Copy -> R.drawable.devconsole_ic_copy + InspectorGlyph.Expand -> R.drawable.devconsole_ic_expand } - drawPath(path, color = tint, style = stroke) -} /** A 48dp (or [size]) round icon-only button. Every call site must supply a real [contentDescription]. */ @Suppress("LongParameterList") // Size/color/icon vary per call site (top area, header, section copy...). diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorGroupedPanel.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorGroupedPanel.kt new file mode 100644 index 0000000..6c5833b --- /dev/null +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorGroupedPanel.kt @@ -0,0 +1,97 @@ +/** + * @author Shakib + * @since 19/10/26 + */ +@file:Suppress("FunctionNaming", "MagicNumber", "MatchingDeclarationName") // Named for its main composable. + +package io.devconsole.ui.compose + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.HorizontalDivider +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.drawBehind +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp + +/** Outer corners for independently composed rows in a single grouped panel. */ +internal enum class GroupPosition { + Single, + First, + Middle, + Last, + ; + + companion object { + fun of( + index: Int, + count: Int, + ): GroupPosition = + when { + count <= 1 -> Single + index == 0 -> First + index == count - 1 -> Last + else -> Middle + } + } +} + +/** + * Places one row of a flush group: rows sit straight on the ground (no raised panel) and are + * separated by a hairline inset 16dp from both edges. Rows bring their own 16dp content padding. + */ +internal fun Modifier.groupedPanelItem( + position: GroupPosition, + line: Color, +): Modifier = + drawBehind { + if (position == GroupPosition.Middle || position == GroupPosition.Last) { + val strokeWidth = 1.dp.toPx() + val inset = 16.dp.toPx() + drawLine(line, Offset(inset, strokeWidth / 2), Offset(size.width - inset, strokeWidth / 2), strokeWidth) + } + } + +/** + * The one raised surface left in the list language: a 12dp-radius panel strip on the 16dp gutter, + * kept for the single problem notice so it reads apart from the flush rows below it. + */ +@Composable +internal fun Modifier.noticeStrip(): Modifier = + padding(horizontal = 16.dp) + .clip(RoundedCornerShape(12.dp)) + .background(DevConsoleTheme.colors.panel) + +/** Theme-reading convenience for callers composing grouped list rows. */ +@Composable +internal fun Modifier.groupedPanelItem(position: GroupPosition): Modifier = + groupedPanelItem(position, DevConsoleTheme.colors.line) + +/** One flush group of non-lazy rows; separate them with [GroupedPanelDivider]. */ +@Composable +internal fun GroupedPanel( + modifier: Modifier = Modifier, + content: @Composable ColumnScope.() -> Unit, +) { + Column( + modifier = modifier.fillMaxWidth(), + content = content, + ) +} + +/** Hairline between rows inside a [GroupedPanel], inset 16dp from both edges. */ +@Composable +internal fun GroupedPanelDivider() { + HorizontalDivider( + modifier = Modifier.padding(horizontal = 16.dp), + thickness = 1.dp, + color = DevConsoleTheme.colors.line, + ) +} diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorHeroComponents.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorHeroComponents.kt index bafa8af..42aa1d3 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorHeroComponents.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorHeroComponents.kt @@ -6,40 +6,39 @@ package io.devconsole.ui.compose +import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.MaterialTheme +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.text.withStyle import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp /** - * A screen's summary readout: rules above and below, a label, a big value with an optional suffix, - * a subtitle, an optional collapse chevron, and an optional full-width pill CTA. - * - * Deliberately unfilled. This is the native twin of the dashboard's `.metric-strip` -- transparent - * ground, `border-block: 1px solid var(--line)` -- so state reads through [labelColor] and - * [valueColor] (error red for failing traffic, warn amber for logs) rather than through a tinted - * container. Callers that want to shout pass the hue in those two, not in a background: a filled - * card would reintroduce exactly the chrome this surface and its web sibling both dropped. + * A compact grouped notice: status dot, one-line summary and optional navigation chevron. + * Legacy headline and CTA styling parameters remain for source compatibility; [ctaLabel] names + * the whole row's click action. [onCtaClick] takes precedence over [onCollapse]. */ -@Suppress("LongParameterList") // Label, value, subtitle, collapse, and the optional CTA's five knobs. +@Suppress("LongParameterList", "UnusedParameter") // Preserve the existing summary API. @Composable internal fun HeroCard( label: String, @@ -58,83 +57,21 @@ internal fun HeroCard( ctaContentColor: Color = DevConsoleTheme.colors.signalInk, onCtaClick: (() -> Unit)? = null, ) { - Column(modifier = modifier.fillMaxWidth()) { - HorizontalDivider(color = DevConsoleTheme.colors.line) - Row( - modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(16.dp), - ) { - HeroReadout(label, value, subtitle, valueSuffix, labelColor, valueColor, valueFontFamily) - if (onCollapse != null) { - InspectorRoundIconButton( - contentDescription = collapseContentDescription, - onClick = onCollapse, - size = 40.dp, - icon = { - InspectorGlyphIcon( - InspectorGlyph.ChevronDown, - contentDescription = null, - tint = labelColor, - size = 18.dp, - rotationDegrees = 180f, - ) - }, - ) - } - } - if (ctaLabel != null && onCtaClick != null) { - InspectorPillButton( - label = ctaLabel, - onClick = onCtaClick, - modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp).padding(bottom = 12.dp), - containerColor = ctaContainerColor, - contentColor = ctaContentColor, - icon = ctaIcon, - ) - } - HorizontalDivider(color = DevConsoleTheme.colors.line) - } -} - -/** The label / value+suffix / subtitle stack that fills [HeroCard]'s leading column. */ -@Suppress("LongParameterList") // Every part of the readout varies per screen. -@Composable -private fun RowScope.HeroReadout( - label: String, - value: String, - subtitle: String, - valueSuffix: String?, - labelColor: Color, - valueColor: Color, - valueFontFamily: FontFamily?, -) { - Column(modifier = Modifier.weight(1f)) { - Text(label, color = labelColor, style = MaterialTheme.typography.labelMedium) - Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.Bottom) { - Text( - value, - color = valueColor, - style = MaterialTheme.typography.headlineSmall.copy(fontFamily = valueFontFamily), - ) - if (valueSuffix != null) { - Text( - valueSuffix, - color = DevConsoleTheme.colors.muted, - style = MaterialTheme.typography.bodySmall, - modifier = Modifier.padding(bottom = 2.dp), - ) - } - } - Text(subtitle, color = DevConsoleTheme.colors.muted, style = MaterialTheme.typography.bodySmall) - } + HeroNoticeRow( + value = value, + label = subtitle.ifBlank { label }, + valueColor = valueColor, + modifier = modifier, + onClick = onCtaClick ?: onCollapse, + onClickLabel = ctaLabel ?: collapseContentDescription, + ) } /** * The collapsed one-line variant of [HeroCard], shown once a screen's hero has been collapsed. * Callers own the collapsed/expanded boolean and swap between the two composables. */ -@Suppress("LongParameterList") // Colors and the expand description vary per screen, same as HeroCard. +@Suppress("LongParameterList", "UnusedParameter") // Preserve the existing summary API. @Composable internal fun HeroBar( value: String, @@ -145,32 +82,68 @@ internal fun HeroBar( labelColor: Color = DevConsoleTheme.colors.text3, expandContentDescription: String = "Expand the summary", ) { + HeroNoticeRow(value, label, valueColor, modifier, onExpand, expandContentDescription) +} + +/** Shared notice surface for expanded and collapsed summaries. */ +@Composable +private fun HeroNoticeRow( + value: String, + label: String, + valueColor: Color, + modifier: Modifier, + onClick: (() -> Unit)?, + onClickLabel: String?, +) { + val colors = DevConsoleTheme.colors Row( modifier = modifier .fillMaxWidth() + .noticeStrip() .heightIn(min = 48.dp) - .clickable(onClick = onExpand, onClickLabel = expandContentDescription, role = Role.Button) - .semantics(mergeDescendants = true) {} - .padding(horizontal = 16.dp), + .then( + if (onClick != null) { + Modifier.clickable(onClick = onClick, onClickLabel = onClickLabel, role = Role.Button) + } else { + Modifier + }, + ).semantics(mergeDescendants = true) {} + .padding(horizontal = 16.dp, vertical = 10.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), ) { - Text( - value, - color = valueColor, - fontFamily = FontFamily.Monospace, - fontSize = 15.sp, - fontWeight = FontWeight.Bold, + Box( + Modifier.size(8.dp).clip(CircleShape).background( + if (valueColor != + colors.ink + ) { + valueColor + } else { + colors.signal + }, + ), ) Text( - label, + buildAnnotatedString { + withStyle(SpanStyle(fontWeight = FontWeight.SemiBold)) { append(value) } + append(" $label") + }, modifier = Modifier.weight(1f), - color = labelColor, - style = MaterialTheme.typography.bodySmall, + color = colors.ink, + fontSize = 14.sp, + fontWeight = FontWeight.Normal, maxLines = 1, overflow = TextOverflow.Ellipsis, ) - InspectorGlyphIcon(InspectorGlyph.ChevronDown, contentDescription = null, tint = labelColor, size = 18.dp) + if (onClick != null) { + InspectorGlyphIcon( + InspectorGlyph.ChevronDown, + contentDescription = null, + tint = colors.muted, + size = 20.dp, + rotationDegrees = -90f, + ) + } } } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorKeyValueList.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorKeyValueList.kt index 37c07df..73a27fa 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorKeyValueList.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorKeyValueList.kt @@ -7,19 +7,20 @@ package io.devconsole.ui.compose -import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width import androidx.compose.foundation.relocation.BringIntoViewRequester import androidx.compose.foundation.relocation.bringIntoViewRequester import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.drawBehind -import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.unit.dp @@ -33,8 +34,7 @@ internal data class InspectorKeyValue( ) /** - * Mono key/value list used inside a [CollapsibleSection]: 12sp json-key-colored key, 13.5sp value, - * 1dp hairline divider above each entry. + * Fixed-width muted keys and monospace values, separated by inset panel hairlines. */ @Composable internal fun InspectorKeyValueList( @@ -45,15 +45,12 @@ internal fun InspectorKeyValueList( currentMatchOrdinal: Int? = null, ) { val colors = DevConsoleTheme.colors - val lineColor = colors.line val sectionMatches = searchMatches.filter { it.sectionKey == sectionKey || sectionKey.isEmpty() } val highlightIndex = remember(sectionMatches, currentMatchOrdinal) { indexInspectorSearchHighlights(sectionMatches, currentMatchOrdinal) } - // No top inset on this padding, so the first divider sits flush under the section header - // instead of 8dp below it. - Column(modifier = modifier.fillMaxWidth().padding(start = 16.dp, end = 16.dp, bottom = 8.dp)) { + Column(modifier = modifier.fillMaxWidth()) { entries.forEachIndexed { index, entry -> val itemId = "row:$index" val bringIntoViewRequester = remember { BringIntoViewRequester() } @@ -61,15 +58,15 @@ internal fun InspectorKeyValueList( LaunchedEffect(isActive, currentMatchOrdinal) { if (isActive) bringIntoViewRequester.bringIntoView() } - Column( + if (index > 0) GroupedPanelDivider() + Row( modifier = Modifier .fillMaxWidth() .bringIntoViewRequester(bringIntoViewRequester) - .drawBehind { - drawLine(lineColor, Offset(0f, 0f), Offset(size.width, 0f), 1.dp.toPx()) - }.padding(vertical = 12.dp), - verticalArrangement = Arrangement.spacedBy(4.dp), + .heightIn(min = 48.dp) + .padding(horizontal = 16.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, ) { Text( inspectorHighlightedText( @@ -77,9 +74,10 @@ internal fun InspectorKeyValueList( highlights = highlightIndex.highlightsFor(itemId, InspectorSearchField.KEY), colors = colors, ), - color = colors.jsonKey, + modifier = Modifier.width(96.dp).padding(end = 12.dp), + color = colors.muted, fontFamily = FontFamily.Monospace, - fontSize = 12.sp, + fontSize = 13.sp, ) Text( inspectorHighlightedText( @@ -89,7 +87,7 @@ internal fun InspectorKeyValueList( ), color = entry.valueColor ?: colors.ink, fontFamily = FontFamily.Monospace, - fontSize = 13.5.sp, + fontSize = 14.sp, ) } } 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 b00d454..c04c9e5 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 @@ -9,7 +9,6 @@ package io.devconsole.ui.compose import androidx.compose.animation.core.animateFloatAsState import androidx.compose.foundation.background -import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.horizontalScroll @@ -32,8 +31,8 @@ import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.FilterChip import androidx.compose.material3.FilterChipDefaults -import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text +import androidx.compose.material3.minimumInteractiveComponentSize import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment @@ -41,16 +40,18 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.clearAndSetSemantics import androidx.compose.ui.semantics.role import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.text +import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.em import androidx.compose.ui.unit.sp -/** 12.5sp/600-weight uppercase section header. */ +/** Sentence-case heading above a grouped panel. */ @Composable internal fun GroupLabel( text: String, @@ -58,14 +59,15 @@ internal fun GroupLabel( ) { Text( text, - modifier = modifier.padding(start = 16.dp, top = 16.dp, end = 16.dp, bottom = 8.dp), - color = DevConsoleTheme.colors.text3, - style = MaterialTheme.typography.labelMedium, + modifier = modifier.padding(start = 16.dp, top = 24.dp, end = 16.dp, bottom = 8.dp), + color = DevConsoleTheme.colors.muted, + fontSize = 14.sp, + fontWeight = FontWeight.SemiBold, ) } /** - * mergeDescendants: without it TalkBack reads the lead badge, title, sub, trail value and trail sub + * mergeDescendants: without it TalkBack reads the method, title, sub, trail value and trail sub * as separate stops instead of one row. No-op when both [onClick] and [onLongClick] are null (a purely informational * row). [onLongClick] backs the Observe traffic tab's "long-press to enter selection mode" gesture; * `combinedClickable` is used instead of plain `clickable` only once a caller actually supplies one, @@ -92,12 +94,11 @@ private fun Modifier.tonalRowClickable( } /** - * A tonal list row: round mono lead badge, mono title + muted sub, trailing mono value + sub. - * `min 48dp` (the Material touch-target floor), whole row clickable, content inset 16dp to match - * [GroupLabel], [HeroCard] and [CollapsibleSection]. Rows carry no margin of their own -- they sit - * flush against each other, and the list separates groups with [GroupLabel] instead. + * A grouped list row with a fixed muted method column, monospace title and inline status/duration. + * Colour is reserved for status; [leadColor] and [leadContainerColor] remain for source compatibility. + * Rows carry no margin or fill by default; callers supply their grouped panel surface. */ -@Suppress("LongParameterList") // One row primitive covers every Observe/Control/Data list item shape. +@Suppress("LongParameterList", "UnusedParameter") // Keep the shared row's existing colour parameters. @Composable internal fun TonalListRow( leadText: String, @@ -108,7 +109,7 @@ internal fun TonalListRow( trailValue: String, modifier: Modifier = Modifier, /** - * Lines [title] may wrap to before it ellipsizes. `1` -- one line, the row's fixed 48dp shape -- + * Lines [title] may wrap to before it ellipsizes. `1` -- one line, the row's minimum 56dp 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. @@ -117,9 +118,9 @@ internal fun TonalListRow( trailValueColor: Color = DevConsoleTheme.colors.ink, trailSubtitle: String? = null, containerColor: Color = Color.Transparent, - /** Real composable trailing content (e.g. [TonalRowExpandChevron]) rendered after [trailValue]'s column. */ + /** Real composable trailing content (e.g. [TonalRowExpandChevron]) rendered after the status/duration. */ trailContent: (@Composable () -> Unit)? = null, - /** Optional composable rendered before the lead badge -- e.g. the traffic tab's selection checkbox. */ + /** Optional composable rendered before the method -- e.g. the traffic tab's selection checkbox. */ leading: (@Composable () -> Unit)? = null, onClick: (() -> Unit)? = null, onLongClick: (() -> Unit)? = null, @@ -140,54 +141,59 @@ internal fun TonalListRow( modifier = modifier .fillMaxWidth() - .heightIn(min = 48.dp) + .heightIn(min = 52.dp) .background(containerColor) .arrivalFlash(isArrival) .tonalRowClickable(onClick, onLongClick, mergeDescendants) - .padding(start = 16.dp, top = 8.dp, end = 16.dp, bottom = 8.dp), + .padding(horizontal = 16.dp, vertical = 10.dp), verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(16.dp), + horizontalArrangement = Arrangement.spacedBy(12.dp), ) { leading?.invoke() - Box( - modifier = Modifier.size(44.dp).clip(CircleShape).background(leadContainerColor), - contentAlignment = Alignment.Center, - ) { + if (leadText.isNotBlank()) { Text( leadText, - color = leadColor, + modifier = Modifier.width(64.dp), + color = DevConsoleTheme.colors.muted, fontFamily = FontFamily.Monospace, - fontSize = 11.5.sp, - fontWeight = FontWeight.Bold, - letterSpacing = 0.02.em, + fontSize = 12.sp, + fontWeight = FontWeight.Medium, + maxLines = 1, ) } Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) { Text( title, + // A path drawn with breakingAnywhere()'s joiners is still read and matched as plain text. + modifier = Modifier.clearAndSetSemantics { text = AnnotatedString(title.withoutBreakControls()) }, color = DevConsoleTheme.colors.ink, - style = DevConsoleType.rowTitle, + fontFamily = FontFamily.Monospace, + fontSize = 14.sp, maxLines = titleMaxLines, overflow = TextOverflow.Ellipsis, ) - Text( - subtitle, - color = DevConsoleTheme.colors.muted, - style = DevConsoleType.rowSub, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) + if (subtitle.isNotBlank()) { + Text( + subtitle, + color = DevConsoleTheme.colors.muted, + fontSize = 12.5.sp, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } } - Column(horizontalAlignment = Alignment.End, verticalArrangement = Arrangement.spacedBy(4.dp)) { + Row(verticalAlignment = Alignment.CenterVertically) { Text( trailValue, color = trailValueColor, fontFamily = FontFamily.Monospace, - fontSize = 15.sp, - fontWeight = FontWeight.Bold, + fontSize = 13.sp, + fontWeight = FontWeight.SemiBold, + maxLines = 1, ) if (trailSubtitle != null) { - Text(trailSubtitle, color = DevConsoleTheme.colors.text3, fontSize = 11.5.sp, maxLines = 1) + Text(" · ", color = DevConsoleTheme.colors.muted, fontSize = 12.5.sp, maxLines = 1) + Text(trailSubtitle, color = DevConsoleTheme.colors.muted, fontSize = 12.5.sp, maxLines = 1) } } trailContent?.invoke() @@ -221,7 +227,7 @@ internal fun TonalRowExpandChevron( ) } -/** Warning-tinted note row: alert icon + 13sp muted text on a warn-soft block. */ +/** Quiet grouped notice with a warning dot and ink text. */ @Composable internal fun WarnNote( text: String, @@ -231,19 +237,18 @@ internal fun WarnNote( modifier = modifier .fillMaxWidth() - .clip(MaterialTheme.shapes.large) - .background(DevConsoleTheme.colors.warnSoft) + .groupedPanelItem(GroupPosition.Single) .padding(16.dp), horizontalArrangement = Arrangement.spacedBy(12.dp), ) { - InspectorGlyphIcon( - InspectorGlyph.Alert, - contentDescription = null, - tint = DevConsoleTheme.colors.warn, - size = 18.dp, - modifier = Modifier.padding(top = 1.dp), + Box( + Modifier + .padding(top = 5.dp) + .size(8.dp) + .clip(CircleShape) + .background(DevConsoleTheme.colors.warn), ) - Text(text, color = DevConsoleTheme.colors.muted, fontSize = 13.sp) + Text(text, color = DevConsoleTheme.colors.ink, fontSize = 13.sp) } } @@ -256,10 +261,8 @@ internal data class InspectorFilterChip( ) /** - * Horizontally scrolling filter chips on the shared 16dp gutter. Each chip is a stock M3 - * [FilterChip] -- outlined on transparent when unselected, signal-tinted with a signal border when - * selected -- so it inherits Material's own height, shape ([DevConsoleShapes]' `small`) and 48dp - * touch target rather than restating them here. + * Horizontally scrolling quiet filter chips on the shared 16dp gutter. Material retains the + * minimum touch target around each 32dp chip; selection uses a neutral fill without an icon. */ @Composable internal fun FilterChipRow( @@ -299,32 +302,32 @@ private fun InspectorChip( } } }, + modifier = Modifier.minimumInteractiveComponentSize().height(32.dp), + shape = RoundedCornerShape(8.dp), colors = FilterChipDefaults.filterChipColors( containerColor = Color.Transparent, - labelColor = DevConsoleTheme.colors.ink, - // signalSoft, not an ad-hoc alpha: the token is 0.13 in dark and 0.10 in light, so a - // literal .copy(alpha = ...) here would drift from every other signal-tinted surface - // in exactly one theme. - selectedContainerColor = DevConsoleTheme.colors.signalSoft, - selectedLabelColor = DevConsoleTheme.colors.signal, - selectedLeadingIconColor = DevConsoleTheme.colors.signal, + labelColor = DevConsoleTheme.colors.muted, + selectedContainerColor = DevConsoleTheme.colors.surface3, + selectedLabelColor = DevConsoleTheme.colors.ink, ), border = - FilterChipDefaults.filterChipBorder( - enabled = true, - selected = chip.selected, - borderColor = DevConsoleTheme.colors.line, - selectedBorderColor = DevConsoleTheme.colors.signal, - ), + if (chip.selected) { + null + } else { + FilterChipDefaults.filterChipBorder( + enabled = true, + selected = false, + borderColor = DevConsoleTheme.colors.line, + borderWidth = 1.dp, + ) + }, ) } /** - * The design system's segmented control (DESIGN.md §Components): one joined 32dp group, 8dp on the - * outer corners and square inside, mono labels, active segment filled with signal. Use it for a - * view switch over 2-3 mutually exclusive representations of the *same* content -- a filter chip - * row says "narrow this set", a segment says "show me this side of it". + * A joined 32dp view switch with a neutral selected segment on a surface-2 container. + * Use it for mutually exclusive representations of the same content. */ @Composable internal fun InspectorSegmentedControl( @@ -334,34 +337,32 @@ internal fun InspectorSegmentedControl( modifier: Modifier = Modifier, ) { val colors = DevConsoleTheme.colors - val shape = RoundedCornerShape(8.dp) + val shape = RoundedCornerShape(10.dp) Row( modifier = modifier .height(32.dp) .clip(shape) - .border(1.dp, colors.line, shape) + .background(colors.surface2) .semantics { role = Role.RadioButton }, verticalAlignment = Alignment.CenterVertically, ) { options.forEachIndexed { index, option -> val selected = index == selectedIndex - if (index > 0) { - Box(Modifier.fillMaxHeight().width(1.dp).background(colors.line)) - } Box( modifier = Modifier .fillMaxHeight() .widthIn(min = 42.dp) - .background(if (selected) colors.signal else Color.Transparent) + .clip(shape) + .background(if (selected) colors.surface3 else colors.surface2) .selectable(selected = selected, role = Role.RadioButton) { onSelect(index) } .padding(horizontal = 12.dp), contentAlignment = Alignment.Center, ) { Text( option, - color = if (selected) colors.signalInk else colors.muted, + color = if (selected) colors.ink else colors.muted, fontFamily = FontFamily.Monospace, fontSize = 11.5.sp, fontWeight = if (selected) FontWeight.Bold else FontWeight.Medium, diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMockRuleEditor.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMockRuleEditor.kt index 4d9ebff..277f18c 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMockRuleEditor.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMockRuleEditor.kt @@ -13,7 +13,9 @@ package io.devconsole.ui.compose import android.content.res.Configuration import androidx.activity.compose.BackHandler import androidx.compose.foundation.background +import androidx.compose.foundation.border import androidx.compose.foundation.clickable +import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Arrangement @@ -234,6 +236,7 @@ internal fun MockRuleEditorScreen( onSave: (InspectorMockRuleUi) -> Unit, onCancel: () -> Unit, modifier: Modifier = Modifier, + onDelete: (() -> Unit)? = null, ) { val initial = when (target) { @@ -313,6 +316,28 @@ internal fun MockRuleEditorScreen( headersExpanded = headersExpanded, onHeadersExpandedChange = { headersExpanded = it }, ) + if (!isNew && onDelete != null) { + Box( + modifier = + Modifier + .fillMaxWidth() + .padding(top = 16.dp, bottom = 24.dp), + contentAlignment = Alignment.Center, + ) { + Text( + text = "Delete rule", + color = colors.error, + fontSize = 14.sp, + fontWeight = FontWeight.SemiBold, + modifier = + Modifier + .clickable(onClick = onDelete, role = Role.Button) + .semantics { contentDescription = "Delete mock rule ${initial.id}" } + .heightIn(min = 48.dp) + .padding(horizontal = 16.dp, vertical = 14.dp), + ) + } + } } // Sibling of the scaffold, not a child: it covers the form while open, and the form keeps its // scroll position and every other field's state underneath. @@ -360,8 +385,9 @@ private fun MockRuleEditorFooter( label = "Cancel", onClick = onCancel, weight = 1f, - containerColor = colors.surface3, + containerColor = colors.panel, contentColor = colors.ink, + outlined = true, ), InspectorFooterAction(label = "Save rule", onClick = onSaveClick, weight = 2f), ), @@ -407,10 +433,11 @@ private fun MockRuleEditorPrimaryFields( errorText = if (showErrors) errors.id else null, ) MockRuleFieldLabel("Method", colors) - FilterChipRow( - chips = form.methodChips.map { method -> InspectorFilterChip(method, method, form.method.value == method) }, - onChipClick = { chip -> form.method.value = chip.id }, - modifier = Modifier.padding(bottom = 16.dp), + InspectorSegmentedControl( + options = form.methodChips, + selectedIndex = form.methodChips.indexOf(form.method.value), + onSelect = { form.method.value = form.methodChips[it] }, + modifier = Modifier.padding(bottom = 16.dp).horizontalScroll(rememberScrollState()), ) MockRuleTextField("Path regex", form.pathPattern.value, { form.pathPattern.value = it }, colors, placeholder = ".*") MockRuleTextField( @@ -477,10 +504,11 @@ private fun MockRuleAdvancedFields( colors, ) MockRuleFieldLabel("Scope", colors) - FilterChipRow( - chips = form.scopeChips.map { s -> InspectorFilterChip(s, s, form.scope.value == s) }, - onChipClick = { chip -> form.scope.value = chip.id }, - modifier = Modifier.padding(bottom = 16.dp), + InspectorSegmentedControl( + options = form.scopeChips, + selectedIndex = form.scopeChips.indexOf(form.scope.value), + onSelect = { form.scope.value = form.scopeChips[it] }, + modifier = Modifier.padding(bottom = 16.dp).horizontalScroll(rememberScrollState()), ) MockRuleTextField("Scheme", form.scheme.value, { form.scheme.value = it }, colors, placeholder = "https") MockRuleTextField("Host", form.host.value, { form.host.value = it }, colors, placeholder = "api.example.test") @@ -550,8 +578,8 @@ private fun MockRuleFieldLabel( colors: DevConsoleColors, ) { Text( - text.uppercase(Locale.US), - color = colors.text3, + text, + color = colors.muted, style = DevConsoleType.groupLabel, modifier = Modifier.padding(start = 4.dp, bottom = 6.dp), ) @@ -572,6 +600,7 @@ private fun MockRuleTextField( // The field's own accessible name, announced on the actual editable/value node (not merged with // the sibling label Text) so its edit action stays reachable. val fieldDescription = if (errorText != null) "$label, error: $errorText" else label + var focused by remember { mutableStateOf(false) } Column(modifier = modifier.fillMaxWidth().padding(bottom = 16.dp)) { MockRuleFieldLabel(label, colors) Row( @@ -579,8 +608,10 @@ private fun MockRuleTextField( Modifier .fillMaxWidth() .heightIn(min = 48.dp) - .clip(RoundedCornerShape(50)) - .background(if (enabled) colors.surface2 else colors.surface3) + .onFocusChanged { focused = it.hasFocus } + .clip(RoundedCornerShape(12.dp)) + .border(1.dp, if (focused) colors.signal else colors.line, RoundedCornerShape(12.dp)) + .background(if (enabled) colors.panel else colors.surface3) .padding(horizontal = 16.dp) .semantics(mergeDescendants = true) { contentDescription = fieldDescription }, verticalAlignment = Alignment.CenterVertically, @@ -621,6 +652,7 @@ private fun MockRuleHeadersSection( onToggle: () -> Unit, ) { val parsed = remember(form.headersText.value) { parseMockRuleHeaderLines(form.headersText.value) } + var focused by remember { mutableStateOf(false) } CollapsibleSection( label = "Response headers", expanded = expanded, @@ -635,8 +667,10 @@ private fun MockRuleHeadersSection( .fillMaxWidth() .padding(bottom = 12.dp) .heightIn(min = 90.dp) - .clip(RoundedCornerShape(16.dp)) - .background(colors.surface2) + .onFocusChanged { focused = it.hasFocus } + .clip(RoundedCornerShape(12.dp)) + .border(1.dp, if (focused) colors.signal else colors.line, RoundedCornerShape(12.dp)) + .background(colors.panel) .padding(horizontal = 16.dp, vertical = 12.dp) .semantics(mergeDescendants = true) { contentDescription = "Response headers" }, ) { @@ -929,8 +963,9 @@ private fun MockRuleBodyTextArea( modifier = modifier .fillMaxWidth() - .clip(RoundedCornerShape(16.dp)) - .background(colors.codeBg) + .clip(RoundedCornerShape(12.dp)) + .border(1.dp, if (state.bodyFocused) colors.signal else colors.line, RoundedCornerShape(12.dp)) + .background(colors.panel) .clickable( interactionSource = remember { MutableInteractionSource() }, // No ripple: this is a text field's dead space, not a button. @@ -1015,22 +1050,22 @@ private fun MockRuleBodyActions( FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { MockRuleBodyAction( label = "FIND", - color = if (searchExpanded) colors.signalInk else colors.signal, - container = if (searchExpanded) colors.signal else colors.signalSoft, + color = if (searchExpanded) colors.ink else colors.muted, + container = if (searchExpanded) colors.surface3 else colors.panel, description = if (searchExpanded) "Hide body search" else "Search response body", onClick = onToggleSearch, ) MockRuleBodyAction( label = "FORMAT", - color = colors.put, - container = colors.putSoft, + color = colors.muted, + container = colors.panel, description = "Format response body as JSON", onClick = onFormat, ) MockRuleBodyAction( label = expandLabel, color = colors.muted, - container = colors.surface2, + container = colors.panel, description = expandDescription, onClick = onToggleFullScreen, ) @@ -1055,6 +1090,7 @@ private fun MockRuleBodyAction( description: String, onClick: () -> Unit, ) { + val colors = DevConsoleTheme.colors Text( label, color = color, @@ -1064,7 +1100,8 @@ private fun MockRuleBodyAction( modifier = Modifier .minimumInteractiveComponentSize() - .clip(RoundedCornerShape(6.dp)) + .clip(RoundedCornerShape(50)) + .border(1.dp, if (container == colors.signal) colors.signal else colors.line, RoundedCornerShape(50)) .background(container) .clickable(onClick = onClick, role = Role.Button) .padding(horizontal = 10.dp, vertical = 6.dp) diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMoreScreen.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMoreScreen.kt index 0056638..4b7476e 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMoreScreen.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMoreScreen.kt @@ -7,22 +7,27 @@ package io.devconsole.ui.compose import android.content.res.Configuration +import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.background +import androidx.compose.foundation.clickable import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.AlertDialog -import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Button +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.OutlinedButton import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Text @@ -32,6 +37,7 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment @@ -40,19 +46,29 @@ import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.ClipboardManager import androidx.compose.ui.platform.LocalClipboardManager +import androidx.compose.ui.platform.LocalUriHandler +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.SpanStyle +import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.withStyle import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.compose.LocalLifecycleOwner import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.compose.currentStateAsState +import androidx.lifecycle.repeatOnLifecycle import androidx.lifecycle.viewmodel.compose.viewModel import io.devconsole.api.ScreenshotResult import io.devconsole.ui.compose.qr.ConnectUrlQrCode import kotlinx.coroutines.delay import kotlinx.coroutines.launch -import java.util.Locale /** * The empty-selection ("export everything") HAR/Postman subtitle. This in-app export path never @@ -74,7 +90,6 @@ private const val LAN_BINDING = "LAN" private const val LOCAL_NETWORK_PERMISSION = "android.permission.ACCESS_LOCAL_NETWORK" private const val SERVER_STATE_RUNNING = "Running" private const val SERVER_STATE_PERMISSION_REQUIRED = "PermissionRequired" -private const val ACTIVE_SESSION_STATUS = "ACTIVE" // Byte-size and MS_PER_* constants live in InspectorObserveFormat.kt (formatByteSize/MS_PER_SECOND // etc.) -- this file used to duplicate both; see that file's own doc. @@ -90,22 +105,23 @@ internal fun MoreRoute( ) { val state by viewModel.state.collectAsStateWithLifecycle() val pendingServerStartPermission by viewModel.serverStartPermission.collectAsStateWithLifecycle() + val lifecycle = LocalLifecycleOwner.current.lifecycle + val lifecycleState by lifecycle.currentStateAsState() val clipboard = LocalClipboardManager.current val snackbarHostState = remember { SnackbarHostState() } val scope = rememberCoroutineScope() - var heroCollapsed by rememberSaveable { mutableStateOf(true) } var qrUrl by remember { mutableStateOf(null) } val showMessage: (String) -> Unit = { message -> scope.launch { snackbarHostState.showSnackbar(message) } } - LaunchedEffect(Unit) { viewModel.dispatch(InspectorAction.Refresh) } - // A one-shot Refresh above leaves the URL card and uptime frozen at whatever they were the - // moment this screen opened. Session codes expire on their own (shorter) TTL and the bind - // address can change independently of this screen -- poll while visible so both stay live - // instead of silently going stale for as long as the operator stays here. - LaunchedEffect(Unit) { - while (true) { - delay(MORE_SCREEN_REFRESH_INTERVAL_MS) + // Session codes expire and the bind address can change independently of this screen. Refresh + // on each show and poll only while started so a hidden keep-alive destination stays idle. + LaunchedEffect(lifecycle) { + lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { viewModel.dispatch(InspectorAction.Refresh) + while (true) { + delay(MORE_SCREEN_REFRESH_INTERVAL_MS) + viewModel.dispatch(InspectorAction.Refresh) + } } } LaunchedEffect(state.lastCommandResult) { @@ -125,7 +141,7 @@ internal fun MoreRoute( // the background at all -- and this is the screen someone is on when they start it and go // looking for that notification. The prompt is a no-op on any screen once granted or dismissed. KeepAliveNotificationPromptEffect( - promptNeeded = state.keepAlivePromptNeeded, + promptNeeded = state.keepAlivePromptNeeded && lifecycleState.isAtLeast(Lifecycle.State.STARTED), snackbarHostState = snackbarHostState, onPermissionResult = { viewModel.dispatch(InspectorAction.NotificationPermissionGranted) }, ) @@ -133,7 +149,7 @@ internal fun MoreRoute( val serverStartPermission = pendingServerStartPermission ?: LOCAL_NETWORK_PERMISSION.takeIf { legacyPermissionRequired } ServerPermissionPromptEffect( - permission = serverStartPermission, + permission = serverStartPermission.takeIf { lifecycleState.isAtLeast(Lifecycle.State.STARTED) }, snackbarHostState = snackbarHostState, onPermissionResult = { granted -> if (pendingServerStartPermission != null) { @@ -151,19 +167,22 @@ internal fun MoreRoute( Box(modifier = modifier.fillMaxSize()) { MoreScreen( state = state, - heroCollapsed = heroCollapsed, - onToggleHero = { heroCollapsed = !heroCollapsed }, + heroCollapsed = true, + onToggleHero = {}, onToggleTheme = onToggleTheme, actions = rememberMoreActions(viewModel, clipboard, showMessage) { url -> qrUrl = url }, ) SnackbarHost(hostState = snackbarHostState, modifier = Modifier.align(Alignment.BottomCenter).padding(16.dp)) } - qrUrl?.let { url -> QrDialog(url, onDismiss = { qrUrl = null }) } + // Dialogs own a separate window, so unplacing the destination alone cannot hide them. + qrUrl?.takeIf { lifecycleState.isAtLeast(Lifecycle.State.STARTED) }?.let { url -> + QrDialog(url, onDismiss = { qrUrl = null }) + } } /** * Grouped callbacks [MoreScreen] dispatches. [onSetServerRunning] takes the *desired* next state - * (the hero's CTA already knows the current one) rather than a bare toggle, since the CTA's own + * (the server button already knows the current one) rather than a bare toggle, since its own * label/icon already flip on [InspectorHealthUi.state] -- this just carries the CTA's intent. */ @Suppress("LongParameterList") // One real interaction per field; see doc above. @@ -186,25 +205,30 @@ private fun rememberMoreActions( clipboard: ClipboardManager, showMessage: (String) -> Unit, onShowQr: (String) -> Unit, -): MoreActions = - MoreActions( - onSetServerRunning = { running -> viewModel.dispatch(InspectorAction.SetServerRunning(running)) }, - onCopyUrl = { url -> - clipboard.setText(AnnotatedString(url)) - showMessage("$url copied") - }, - onCopyCode = { code -> - clipboard.setText(AnnotatedString(code)) - showMessage("Session code $code copied") - }, - onShowQr = onShowQr, - onExportHar = { viewModel.dispatch(InspectorAction.ExportHar) }, - onExportPostman = { viewModel.dispatch(InspectorAction.ExportPostman) }, - onExportSessionZip = { viewModel.dispatch(InspectorAction.ExportSessionZip) }, - onCaptureScreenshot = { viewModel.dispatch(InspectorAction.CaptureScreenshot) }, - onRevoke = { id -> viewModel.dispatch(InspectorAction.RevokePrincipal(id)) }, - onSelectSession = { id -> viewModel.dispatch(InspectorAction.SelectSession(id)) }, - ) +): MoreActions { + val currentShowMessage by rememberUpdatedState(showMessage) + val currentOnShowQr by rememberUpdatedState(onShowQr) + return remember(viewModel, clipboard) { + MoreActions( + onSetServerRunning = { running -> viewModel.dispatch(InspectorAction.SetServerRunning(running)) }, + onCopyUrl = { url -> + clipboard.setText(AnnotatedString(url)) + currentShowMessage("$url copied") + }, + onCopyCode = { code -> + clipboard.setText(AnnotatedString(code)) + currentShowMessage("Session code $code copied") + }, + onShowQr = { url -> currentOnShowQr(url) }, + onExportHar = { viewModel.dispatch(InspectorAction.ExportHar) }, + onExportPostman = { viewModel.dispatch(InspectorAction.ExportPostman) }, + onExportSessionZip = { viewModel.dispatch(InspectorAction.ExportSessionZip) }, + onCaptureScreenshot = { viewModel.dispatch(InspectorAction.CaptureScreenshot) }, + onRevoke = { id -> viewModel.dispatch(InspectorAction.RevokePrincipal(id)) }, + onSelectSession = { id -> viewModel.dispatch(InspectorAction.SelectSession(id)) }, + ) + } +} /** * The QR is a fixed-size square and the dialog is wider than it, so it needs to be told to centre: @@ -239,13 +263,8 @@ private fun QrDialog( private val QR_DIALOG_TOP_PADDING = 24.dp private val QR_DIALOG_BOTTOM_PADDING = 12.dp -/** - * Stateless, previewable More surface: hero, [InspectorUrlCard], and Export rows. Session/browser/ - * retention detail -- real capability the old screen had that the compact row list has no room - * for -- lives behind the RUN/WEB/KEEP rows as inline `rememberSaveable` expand-in-place sections - * rather than being dropped. - */ -@Suppress("LongParameterList") // One callback group + hero-collapse state; see doc above. +/** Grouped More surface with expandable session, retention and SDK health details. */ +@Suppress("LongParameterList", "UNUSED_PARAMETER") // Preserve the destination signature. @Composable internal fun MoreScreen( state: InspectorState, @@ -256,359 +275,315 @@ internal fun MoreScreen( modifier: Modifier = Modifier, ) { val colors = DevConsoleTheme.colors - // A ticking clock, not a snapshot re-read on screen entry -- otherwise the uptime value freezes - // at whatever it was the moment this screen last (re)opened instead of counting up live. - var nowEpochMs by remember { mutableStateOf(System.currentTimeMillis()) } - LaunchedEffect(Unit) { - while (true) { - delay(1_000) - nowEpochMs = System.currentTimeMillis() - } - } - val hero = rememberMoreHero(state, nowEpochMs) + val running = state.health?.state == SERVER_STATE_RUNNING Column(modifier = modifier.fillMaxSize().background(colors.ground)) { InspectorTopArea( - subLine = "Server, session and export", + subLine = "", title = "More", actions = listOf(themeToggleTopAction(onToggleTheme)), ) LazyColumn( modifier = Modifier.weight(1f), - contentPadding = PaddingValues(start = 16.dp, top = 4.dp, end = 16.dp, bottom = 16.dp), + contentPadding = PaddingValues(top = 16.dp, bottom = 16.dp), + verticalArrangement = Arrangement.spacedBy(16.dp), ) { - if (state.serverControlSupported) { - item { ServerControlCard(hero.running, actions.onSetServerRunning, colors) } - item { Spacer(Modifier.height(16.dp)) } + item(key = "more_browser_dashboard", contentType = "browser_dashboard") { + BrowserDashboardPanel(state, running, actions, colors) } - item { - MoreHero( - info = hero, - collapsed = heroCollapsed, - onToggleCollapse = onToggleHero, - colors = colors, - ) + item(key = "more_export_title", contentType = "panel_title") { + MorePanelTitle("Export") } - item { Spacer(Modifier.height(16.dp)) } - item { MoreUrlCard(state, hero.running, actions, colors) } - if (!hero.running) { - item { Spacer(Modifier.height(16.dp)) } - item { - WarnNote( - "Captures are paused while the server is stopped — the SDK keeps its retained " + - "buffer but publishes nothing.", - ) - } + item(key = "more_export_har", contentType = "export_row") { + ExportHarRow(state, actions) + } + item(key = "more_export_div_1", contentType = "divider") { + GroupedPanelDivider() + } + item(key = "more_export_postman", contentType = "export_row") { + ExportPostmanRow(state, actions) + } + item(key = "more_export_div_2", contentType = "divider") { + GroupedPanelDivider() + } + item(key = "more_export_zip", contentType = "export_row") { + ExportZipRow(state, actions) + } + item(key = "more_export_div_3", contentType = "divider") { + GroupedPanelDivider() + } + item(key = "more_export_screenshot", contentType = "export_row") { + CaptureScreenshotRow(actions) + } + item(key = "more_export_div_4", contentType = "divider") { + GroupedPanelDivider() + } + item(key = "more_export_runs", contentType = "export_row") { + RetainedRunsRow(state, actions, colors) + } + item(key = "more_settings_title", contentType = "panel_title") { + MorePanelTitle("Settings") + } + item(key = "more_settings_health", contentType = "settings_row") { + SdkHealthRow(state.health) + } + item(key = "more_settings_div_1", contentType = "divider") { + GroupedPanelDivider() + } + item(key = "more_settings_retention", contentType = "settings_row") { + RetentionRow(state, colors) + } + item(key = "more_settings_div_2", contentType = "divider") { + GroupedPanelDivider() + } + item(key = "more_settings_sessions", contentType = "settings_row") { + BrowserSessionsRow(state, actions, colors) } - item { Spacer(Modifier.height(16.dp)) } - item { LanWarningBanner(state.browser) } - item { GroupLabel("Export") } - item { ExportHarRow(state, actions, colors) } - item { ExportPostmanRow(state, actions, colors) } - item { ExportZipRow(state, colors, actions) } - item { CaptureScreenshotRow(colors, actions) } - item { RetainedRunsRow(state, actions, colors) } - item { BrowserSessionsRow(state, actions, colors) } - item { RetentionRow(state, colors) } - item { Spacer(Modifier.height(8.dp)) } - item { GroupLabel("SDK health") } - sdkHealthRows(state.health, colors) } } } -/** - * Real, computed More hero: [InspectorHealthUi.state] for running/stopped, active session uptime, - * real browser count. - */ -private data class MoreHeroInfo( - val running: Boolean, - val value: String, - val of: String, - val sub: String, - val bar: String, -) - -/** Not `remember`-memoized: [nowEpochMs] ticks every second (see [MoreScreen]) so uptime counts up live. */ @Composable -private fun rememberMoreHero( - state: InspectorState, - nowEpochMs: Long, -): MoreHeroInfo { - val running = state.health?.state == SERVER_STATE_RUNNING - return if (running) moreHeroRunning(state, nowEpochMs) else moreHeroStopped() -} - -private fun moreHeroRunning( - state: InspectorState, - nowEpochMs: Long, -): MoreHeroInfo { - val active = state.sessions.firstOrNull { it.status == ACTIVE_SESSION_STATUS } - val uptime = active?.let { formatUptime(nowEpochMs - it.startedAtEpochMs) } ?: "—" - val attached = state.browser?.principals?.size ?: 0 - val sub = - "Accepting browser connections on this Wi-Fi network. " + - "$attached browser${if (attached == 1) "" else "s"} attached." - return MoreHeroInfo(true, uptime, "uptime", sub, "uptime · server running") -} - -private fun moreHeroStopped(): MoreHeroInfo = - MoreHeroInfo( - running = false, - value = "—", - of = "not listening", - sub = "No port is open and nothing is being captured. Start the server to attach a browser.", - bar = "server stopped", - ) - -@Composable -private fun MoreHero( - info: MoreHeroInfo, - collapsed: Boolean, - onToggleCollapse: () -> Unit, - colors: DevConsoleColors, -) { - val accentColor = if (info.running) colors.signal else colors.text3 - val valueColor = if (info.running) colors.signal else colors.muted - if (collapsed) { - HeroBar( - value = info.value, - label = info.bar, - onExpand = onToggleCollapse, - valueColor = valueColor, - labelColor = accentColor, - ) - return - } - HeroCard( - label = if (info.running) "Server running" else "Server stopped", - value = info.value, - valueSuffix = info.of, - subtitle = info.sub, - labelColor = accentColor, - valueColor = valueColor, - valueFontFamily = FontFamily.Monospace, - onCollapse = onToggleCollapse, - // Start/Stop lives in the dedicated ServerControlCard above this hero, not in a hero CTA. +private fun MorePanelTitle(title: String) { + Text( + title, + modifier = Modifier.padding(start = 16.dp, end = 16.dp, top = 16.dp, bottom = 12.dp), + color = DevConsoleTheme.colors.ink, + fontSize = 17.sp, + fontWeight = FontWeight.SemiBold, ) } -/** - * The dedicated Start/Stop pair at the top of More -- the same affordance the sample apps put on - * their home screens, on the SDK's own surface. Rendered only when this build actually wires - * [InspectorDataSource.setServerRunning]; a control that can never do anything is worse than none - * (same honesty rule as the push Replay toast). - */ +/** Plain grouped row with a readable label and a muted mono value. */ @Composable -private fun ServerControlCard( - running: Boolean, - onSetServerRunning: (Boolean) -> Unit, - colors: DevConsoleColors, +private fun MorePanelRow( + title: String, + meta: String = "", + description: String = "", + onClick: (() -> Unit)? = null, + metaContent: (@Composable () -> Unit)? = null, ) { - Column( + val colors = DevConsoleTheme.colors + Row( modifier = Modifier .fillMaxWidth() - .clip(MaterialTheme.shapes.large) - .background(if (running) colors.signalSoft else colors.surface2) - .padding(16.dp), - verticalArrangement = Arrangement.spacedBy(12.dp), + .heightIn(min = 56.dp) + .semantics(mergeDescendants = true) { + if (description.isNotBlank()) contentDescription = "$title. $description" + }.then(if (onClick != null) Modifier.clickable(onClick = onClick) else Modifier) + .padding(horizontal = 16.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), ) { - Text( - if (running) "Server is running" else "Server is stopped", - color = colors.ink, - fontSize = 15.sp, - fontWeight = FontWeight.SemiBold, - ) - Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) { - // No per-state color swaps: InspectorPillButton owns the disabled treatment now, and - // dimming an already-muted color twice pushed these below the contrast floor. - InspectorPillButton( - label = "Start server", - onClick = { onSetServerRunning(true) }, - modifier = Modifier.weight(1f), - enabled = !running, - ) - InspectorPillButton( - label = "Stop", - onClick = { onSetServerRunning(false) }, - modifier = Modifier.weight(1f), - enabled = running, - outlined = true, - contentColor = colors.ink, - ) + Text(title, modifier = Modifier.weight(1f), color = colors.ink, fontSize = 16.sp) + if (metaContent != null) { + metaContent() + } else if (meta.isNotBlank()) { + Text(meta, color = colors.muted, fontFamily = FontFamily.Monospace, fontSize = 12.sp) + } + if (onClick != null) { + DevConsoleIcon(R.drawable.devconsole_ic_chevron_right, null, Modifier, colors.muted, 18.dp) } } } -/** The URL card: running vs. stopped variants. */ @Composable -private fun MoreUrlCard( +private fun BrowserDashboardPanel( state: InspectorState, running: Boolean, actions: MoreActions, colors: DevConsoleColors, ) { val browser = state.browser - when { - // The device's live address no longer matches what the server bound to -- the URL - // is dead either way, so say so honestly instead of showing it as if still connectable. - running && browser?.bindAddressChanged == true -> - StaleAddressUrlCard(state.serverControlSupported, actions, colors) - running && browser?.sessionCodeUrl != null && browser.sessionCode != null -> - if (browser.sessionCode.isBlank()) { - RunningOpenUrlCard(browser.sessionCodeUrl, actions, colors) - } else { - RunningUrlCard( - browser.sessionCodeUrl, - browser.sessionCode, - browser.sessionCodeRemainingTtlMs, - actions, - colors, + val stale = running && browser?.bindAddressChanged == true + val url = browser?.sessionCodeUrl?.takeIf { running && !stale && browser.sessionCode != null } + GroupedPanel { + MorePanelTitle("Browser dashboard") + Column( + modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 16.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + ServerStatusLine(running, browser?.endpoint, colors) + if (stale) { + WarnNote( + "The device's network address changed while the server was running. Stop the " + + "server, then start it again to reconnect at the new address.", ) } - else -> StoppedUrlCard(state.serverControlSupported, actions, colors) + if (url != null) { + val uriHandler = LocalUriHandler.current + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + ConnectUrlQrCode( + url, + modifier = + Modifier + .size(96.dp) + .clickable(onClickLabel = "QR", role = Role.Button) { actions.onShowQr(url) } + .semantics { contentDescription = "QR" }, + ) + Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) { + InspectorUrlCard( + dotColor = colors.signal, + label = "", + url = url, + subtitle = "", + actions = + listOf( + InspectorUrlAction( + "Copy URL", + { actions.onCopyUrl(url) }, + colors.panel, + colors.muted, + icon = { UrlActionCopyIcon(colors.muted) }, + ), + InspectorUrlAction( + "Open URL", + { uriHandler.openUri(url) }, + colors.panel, + colors.muted, + icon = { + DevConsoleIcon( + R.drawable.devconsole_ic_open_external, + null, + Modifier, + colors.muted, + 18.dp, + ) + }, + ), + ), + ) + if (state.serverControlSupported) ServerControlButton(true, actions) + } + } + browser?.let { SessionCodeLine(it, actions, colors) } + } else { + if (!stale) { + Text( + if (running) { + "Waiting for a browser URL." + } else { + "The URL appears here once the server is running." + }, + color = colors.muted, + fontSize = 13.sp, + ) + } + if (state.serverControlSupported) ServerControlButton(running, actions) + } + LanWarningBanner(browser) + } } } @Composable -private fun StaleAddressUrlCard( - serverControlSupported: Boolean, - actions: MoreActions, +private fun ServerStatusLine( + running: Boolean, + endpoint: String?, colors: DevConsoleColors, ) { - InspectorUrlCard( - dotColor = colors.warn, - dotPulsing = true, - label = "Server address changed", - url = "—", - subtitle = - "The device's network address changed while the server was running. Stop the " + - "server, then start it again to reconnect at the new address.", - actions = - if (serverControlSupported) { - listOf( - InspectorUrlAction( - "Stop server", - { actions.onSetServerRunning(false) }, - colors.surface3, - colors.warn, - ), - ) - } else { - emptyList() + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Box(Modifier.size(8.dp).clip(CircleShape).background(if (running) colors.signal else colors.muted)) + Text( + buildAnnotatedString { + append(if (running) "Running" else "Stopped") + endpoint?.takeIf { running }?.let { + append(" on ") + withStyle(SpanStyle(fontFamily = FontFamily.Monospace)) { append(it) } + } }, - ) + color = colors.muted, + fontSize = 14.sp, + ) + } } @Composable -private fun RunningUrlCard( - url: String, - code: String, - remainingTtlMs: Long?, +private fun SessionCodeLine( + browser: InspectorBrowserUi, actions: MoreActions, colors: DevConsoleColors, ) { - val rotation = remainingTtlMs?.let { " · rotates in ${formatDuration(it)}" }.orEmpty() - InspectorUrlCard( - dotColor = colors.signal, - dotPulsing = true, - label = "Open in a browser", - url = url, - subtitle = "Session code $code$rotation. Plaintext on your LAN — debug builds only.", - actions = runningUrlCardActions(url, code, actions, colors), + val code = browser.sessionCode?.takeIf { it.isNotBlank() } ?: return + val rotation = browser.sessionCodeRemainingTtlMs?.let { " · rotates in ${formatDuration(it)}" }.orEmpty() + Text( + "Session code $code$rotation", + modifier = Modifier.clickable(onClickLabel = "Code") { actions.onCopyCode(code) }, + color = colors.muted, + fontFamily = FontFamily.Monospace, + fontSize = 12.sp, ) } @Composable -private fun RunningOpenUrlCard( - url: String, +private fun ServerControlButton( + running: Boolean, actions: MoreActions, - colors: DevConsoleColors, ) { - InspectorUrlCard( - dotColor = colors.signal, - dotPulsing = true, - label = "Open in a browser", - url = url, - subtitle = "No session code required. Plaintext on your LAN — use SESSION_CODE on shared networks.", - actions = - listOf( - InspectorUrlAction( - "Copy URL", - { actions.onCopyUrl(url) }, - colors.signal, - colors.signalInk, - flex = 1.5f, - icon = { UrlActionCopyIcon(colors.signalInk) }, - ), - InspectorUrlAction( - "QR", - { actions.onShowQr(url) }, - colors.surface3, - colors.ink, - icon = { UrlActionEyeIcon(colors.ink) }, - ), - ), - ) + val colors = DevConsoleTheme.colors + if (running) { + OutlinedButton( + onClick = { actions.onSetServerRunning(false) }, + shape = RoundedCornerShape(8.dp), + border = BorderStroke(1.dp, colors.signal), + colors = ButtonDefaults.outlinedButtonColors(contentColor = colors.signal), + ) { + Text("Stop server", fontSize = 14.sp) + } + } else { + Button( + onClick = { actions.onSetServerRunning(true) }, + shape = RoundedCornerShape(8.dp), + colors = ButtonDefaults.buttonColors(containerColor = colors.signal, contentColor = colors.signalInk), + ) { + Text("Start server", fontSize = 14.sp) + } + } } -private fun runningUrlCardActions( - url: String, - code: String, - actions: MoreActions, - colors: DevConsoleColors, -): List = - listOf( - InspectorUrlAction( - "Copy URL", - { actions.onCopyUrl(url) }, - colors.signal, - colors.signalInk, - // 2f squeezed the secondary pills until their labels clipped. - flex = 1.5f, - icon = { UrlActionCopyIcon(colors.signalInk) }, - ), - InspectorUrlAction( - "Code", - { actions.onCopyCode(code) }, - colors.surface3, - colors.ink, - icon = { UrlActionCopyIcon(colors.ink) }, - ), - InspectorUrlAction( - "QR", - { actions.onShowQr(url) }, - colors.surface3, - colors.ink, - icon = { UrlActionEyeIcon(colors.ink) }, - ), - ) - @Composable -private fun StoppedUrlCard( - serverControlSupported: Boolean, - actions: MoreActions, - colors: DevConsoleColors, -) { - InspectorUrlCard( - dotColor = colors.borderStrong, - label = "No address", - url = "—", - subtitle = "The URL appears here once the server is running.", - actions = - if (serverControlSupported) { - listOf( - InspectorUrlAction( - "Start server to get a URL", - { actions.onSetServerRunning(true) }, - colors.surface3, - colors.muted, - ), +private fun SdkHealthRow(health: InspectorHealthUi?) { + val colors = DevConsoleTheme.colors + var expanded by rememberSaveable { mutableStateOf(false) } + MorePanelRow( + "SDK health", + onClick = { expanded = !expanded }, + metaContent = { + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + health?.state ?: "Unavailable", + color = if (health?.state == SERVER_STATE_RUNNING) colors.signal else colors.muted, + fontFamily = FontFamily.Monospace, + fontSize = 12.sp, ) - } else { - emptyList() - }, + health?.let { + Text( + " · ${it.droppedEventCount} dropped", + color = colors.muted, + fontFamily = FontFamily.Monospace, + fontSize = 12.sp, + ) + } + } + }, ) + if (expanded) { + if (health == null) { + MorePanelRow("SDK health is unavailable.") + } else { + GroupedPanelDivider() + HealthTonalRow("State", health.state) + GroupedPanelDivider() + HealthTonalRow("Initializations", health.initializationCount.toString()) + GroupedPanelDivider() + HealthTonalRow("Published events", health.publishedEventCount.toString()) + GroupedPanelDivider() + HealthTonalRow("Dropped events", health.droppedEventCount.toString()) + } + } } @Composable @@ -616,54 +591,15 @@ private fun UrlActionCopyIcon(tint: Color) { InspectorGlyphIcon(InspectorGlyph.Copy, contentDescription = null, tint = tint, size = 15.dp) } -@Composable -private fun UrlActionEyeIcon(tint: Color) { - ControlGlyphIcon(ControlGlyph.Eye, contentDescription = null, tint = tint, size = 15.dp) -} - -/** - * Prominent, non-dismissible warning shown only when the server is bound to LAN rather than - * loopback -- see docs/THREAT_MODEL.md: the dashboard is plaintext HTTP, and on LAN anyone sharing - * the network can observe the bearer token and every captured request. Restyled onto the token - * palette (error-soft, same shape as [WarnNote]) rather than dropped -- this is a real safety - * signal the app still needs. - */ +/** Preserve the LAN-only caveat without introducing another panel. */ @Composable private fun LanWarningBanner(browser: InspectorBrowserUi?) { if (browser?.binding != LAN_BINDING) return - val colors = DevConsoleTheme.colors - Column( - modifier = - Modifier - .fillMaxWidth() - .padding(bottom = 16.dp) - .clip(MaterialTheme.shapes.large) - .background(colors.errorSoft) - .padding(16.dp), - ) { - Text( - "LAN MODE — UNENCRYPTED", - color = colors.error, - fontFamily = FontFamily.Monospace, - fontWeight = FontWeight.Bold, - fontSize = 12.5.sp, - ) - Text( - LOCAL_NETWORK_HTTP_WARNING, - color = colors.muted, - fontSize = 13.sp, - modifier = Modifier.padding(top = 6.dp), - ) - browser.endpoint?.let { endpoint -> - Text( - "Bound at $endpoint", - color = colors.muted, - fontFamily = FontFamily.Monospace, - fontSize = 11.5.sp, - modifier = Modifier.padding(top = 4.dp), - ) - } - } + Text( + "Plain HTTP on your Wi-Fi. Use loopback on shared networks.", + color = DevConsoleTheme.colors.muted, + fontSize = 13.sp, + ) } /** HAR/ZIP: real, direct export actions -- trail uses real counts (transactions/sessions), never a fabricated size. */ @@ -671,7 +607,6 @@ private fun LanWarningBanner(browser: InspectorBrowserUi?) { private fun ExportHarRow( state: InspectorState, actions: MoreActions, - colors: DevConsoleColors, ) { val selection = state.selectedTransactionIds val subtitle = @@ -680,15 +615,10 @@ private fun ExportHarRow( } else { "Redacted · ${selection.size} selected transaction(s)" } - TonalListRow( - leadText = "HAR", - leadColor = colors.put, - leadContainerColor = colors.putSoft, - title = "Export HAR", - subtitle = subtitle, - trailValue = state.transactions.size.toString(), - trailValueColor = colors.ink, - trailSubtitle = "txns", + MorePanelRow( + title = "HAR", + description = subtitle, + meta = if (selection.isEmpty()) "${state.transactions.size} txns" else "${selection.size} selected", onClick = actions.onExportHar, ) } @@ -698,7 +628,6 @@ private fun ExportHarRow( private fun ExportPostmanRow( state: InspectorState, actions: MoreActions, - colors: DevConsoleColors, ) { val selection = state.selectedTransactionIds val subtitle = @@ -707,15 +636,10 @@ private fun ExportPostmanRow( } else { "Redacted · ${selection.size} selected transaction(s)" } - TonalListRow( - leadText = "PM", - leadColor = colors.put, - leadContainerColor = colors.putSoft, - title = "Export Postman collection", - subtitle = subtitle, - trailValue = state.transactions.size.toString(), - trailValueColor = colors.ink, - trailSubtitle = "txns", + MorePanelRow( + title = "Postman collection", + description = subtitle, + meta = if (selection.isEmpty()) "${state.transactions.size} txns" else "${selection.size} selected", onClick = actions.onExportPostman, ) } @@ -723,18 +647,12 @@ private fun ExportPostmanRow( @Composable private fun ExportZipRow( state: InspectorState, - colors: DevConsoleColors, actions: MoreActions, ) { - TonalListRow( - leadText = "ZIP", - leadColor = colors.put, - leadContainerColor = colors.putSoft, - title = "Export session", - subtitle = "Timeline, captures, health snapshot", - trailValue = state.sessions.size.toString(), - trailValueColor = colors.ink, - trailSubtitle = if (state.sessions.size == 1) "session" else "sessions", + MorePanelRow( + title = "Session ZIP", + description = "Timeline, captures, health snapshot", + meta = "${state.sessions.size} ${if (state.sessions.size == 1) "session" else "sessions"}", onClick = actions.onExportSessionZip, ) } @@ -750,18 +668,10 @@ private fun ExportZipRow( * gated control in this product. */ @Composable -private fun CaptureScreenshotRow( - colors: DevConsoleColors, - actions: MoreActions, -) { - TonalListRow( - leadText = "SHOT", - leadColor = colors.put, - leadContainerColor = colors.putSoft, +private fun CaptureScreenshotRow(actions: MoreActions) { + MorePanelRow( title = "Capture screenshot", - subtitle = "The foreground screen, unredacted — off by default", - trailValue = "Capture", - trailValueColor = colors.put, + description = "The foreground screen, unredacted — off by default", onClick = actions.onCaptureScreenshot, ) } @@ -782,30 +692,41 @@ private fun RetainedRunsRow( val plural = if (state.sessions.size == 1) "" else "s" "${state.sessions.size} run$plural · oldest ${formatCaptureClockTime(oldest.startedAtEpochMs)}" } - TonalListRow( - leadText = "RUN", - leadColor = colors.muted, - leadContainerColor = colors.surface3, + MorePanelRow( title = "Retained runs", - subtitle = subtitle, - trailValue = "", - trailValueColor = colors.muted, - trailContent = { TonalRowExpandChevron(expanded) }, + description = subtitle, + meta = state.sessions.size.toString(), onClick = { expanded = !expanded }, ) if (expanded) { Column(modifier = Modifier.padding(bottom = 8.dp)) { state.sessions.forEach { session -> + GroupedPanelDivider() TonalListRow( - leadText = session.status.take(3), - leadColor = if (session.id == state.selectedSessionId) colors.signal else colors.muted, - leadContainerColor = - if (session.id == state.selectedSessionId) colors.signalSoft else colors.surface3, + leadText = "", + leadColor = colors.muted, + leadContainerColor = colors.panel, title = session.label, - subtitle = "${session.recordCount} records · ${formatByteSize(session.estimatedBytes)}", + subtitle = "${session.status} · ${session.recordCount} records · ${formatByteSize( + session.estimatedBytes, + )}", trailValue = formatCaptureClockTime(session.startedAtEpochMs), trailValueColor = colors.muted, - containerColor = colors.surface3, + trailContent = + if (session.id == state.selectedSessionId) { + ( + { + InspectorGlyphIcon( + InspectorGlyph.Check, + "Selected", + tint = colors.ink, + size = 18.dp, + ) + } + ) + } else { + null + }, onClick = { actions.onSelectSession(session.id) }, ) } @@ -828,29 +749,24 @@ private fun BrowserSessionsRow( } else { "${principals.size} connected · ${principals.take(2).joinToString { it.label }}" } - TonalListRow( - leadText = "WEB", - leadColor = colors.muted, - leadContainerColor = colors.surface3, + MorePanelRow( title = "Browser sessions", - subtitle = subtitle, - trailValue = "", - trailValueColor = colors.muted, - trailContent = { TonalRowExpandChevron(expanded) }, + description = subtitle, + meta = "${principals.size} connected", onClick = { expanded = !expanded }, ) if (expanded) { Column(modifier = Modifier.padding(bottom = 8.dp)) { principals.forEach { principal -> + GroupedPanelDivider() TonalListRow( - leadText = "REV", - leadColor = colors.error, - leadContainerColor = colors.errorSoft, + leadText = "", + leadColor = colors.muted, + leadContainerColor = colors.panel, title = principal.label, subtitle = "${principal.sourceIp} · expires ${formatCaptureClockTime(principal.expiresAtEpochMs)}", trailValue = "revoke", trailValueColor = colors.error, - containerColor = colors.surface3, onClick = { actions.onRevoke(principal.id) }, ) } @@ -874,83 +790,48 @@ private fun RetentionRow( val age = formatDuration(retention.maxAgeMs) "${retention.maxSessions} sessions · $bytes · $age" } - TonalListRow( - leadText = "KEEP", - leadColor = colors.muted, - leadContainerColor = colors.surface3, + MorePanelRow( title = "Retention", - subtitle = subtitle, - trailValue = "", - trailValueColor = colors.muted, - trailContent = if (retention != null) ({ TonalRowExpandChevron(expanded) }) else null, + description = subtitle, + meta = retention?.let { formatDuration(it.maxAgeMs) }.orEmpty(), onClick = if (retention != null) ({ expanded = !expanded }) else null, ) if (expanded && retention != null) { val used = state.sessions.sumOf { it.estimatedBytes } Column(modifier = Modifier.padding(bottom = 8.dp)) { + GroupedPanelDivider() + MorePanelRow("Session limit", retention.maxSessions.toString()) + GroupedPanelDivider() + MorePanelRow("Storage limit", formatByteSize(retention.maxBytes)) + GroupedPanelDivider() TonalListRow( - leadText = "USE", + leadText = "", leadColor = colors.muted, - leadContainerColor = colors.surface3, + leadContainerColor = colors.panel, title = "Storage used", subtitle = "${state.sessions.size} of ${retention.maxSessions} sessions", trailValue = formatByteSize(used), trailValueColor = colors.ink, - containerColor = colors.surface3, ) } } } -/** Read-only mirror of the dashboard's SDK Health view, restyled as [TonalListRow]s. */ -private fun LazyListScope.sdkHealthRows( - health: InspectorHealthUi?, - colors: DevConsoleColors, -) { - if (health == null) { - item { SectionEmptyText("SDK health is unavailable.") } - return - } - item { HealthTonalRow("State", health.state, colors) } - item { HealthTonalRow("Initializations", health.initializationCount.toString(), colors) } - item { HealthTonalRow("Published events", health.publishedEventCount.toString(), colors) } - item { HealthTonalRow("Dropped events", health.droppedEventCount.toString(), colors) } -} - @Composable private fun HealthTonalRow( label: String, value: String, - colors: DevConsoleColors, ) { - TonalListRow( - leadText = label.take(3).uppercase(Locale.US), - leadColor = colors.muted, - leadContainerColor = colors.surface3, - title = label, - subtitle = "SDK health counter", - trailValue = value, - trailValueColor = colors.ink, - ) + MorePanelRow(title = label, meta = value) } private fun formatDuration(ms: Long): String = when { - ms >= MS_PER_DAY -> "${ms / MS_PER_DAY}d" - ms >= MS_PER_HOUR -> "${ms / MS_PER_HOUR}h" + ms >= MS_PER_HOUR -> "${ms / MS_PER_HOUR} h" ms >= MS_PER_MINUTE -> "${ms / MS_PER_MINUTE}m" else -> "${ms / MS_PER_SECOND}s" } -/** `HH:MM:SS` uptime clock, computed from the active session's real start time. */ -private fun formatUptime(elapsedMs: Long): String { - val totalSeconds = elapsedMs / MS_PER_SECOND - val hours = totalSeconds / (MS_PER_HOUR / MS_PER_SECOND) - val minutes = (totalSeconds % (MS_PER_HOUR / MS_PER_SECOND)) / (MS_PER_MINUTE / MS_PER_SECOND) - val seconds = totalSeconds % (MS_PER_MINUTE / MS_PER_SECOND) - return "%02d:%02d:%02d".format(Locale.US, hours, minutes, seconds) -} - /** Hand-built fixture for [MoreScreenPreview]. */ private fun moreScreenPreviewState() = InspectorState( @@ -977,12 +858,12 @@ private fun moreScreenPreviewState() = browser = InspectorBrowserUi( binding = LAN_BINDING, - endpoint = "192.168.1.42:8787", + endpoint = "192.168.0.104:8080", principals = listOf(InspectorBrowserPrincipalUi("p-1", "Chrome on Mac", "192.168.1.10", 0)), - sessionCodeUrl = "http://192.168.1.42:8787/#s=ABCD1234", + sessionCodeUrl = "http://192.168.0.104:8080/#s=ABCD1234", sessionCode = "ABCD1234", ), - retention = InspectorRetentionUi(maxSessions = 5, maxAgeMs = MS_PER_DAY * 7, maxBytes = 50_000_000), + retention = InspectorRetentionUi(maxSessions = 5, maxAgeMs = MS_PER_DAY, maxBytes = 50_000_000), ) private fun moreScreenPreviewActions() = 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 f47898d..48751d6 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 @@ -9,43 +9,56 @@ package io.devconsole.ui.compose import androidx.compose.animation.animateColorAsState import androidx.compose.animation.core.Animatable import androidx.compose.foundation.background +import androidx.compose.foundation.border import androidx.compose.foundation.clickable +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.indication +import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.width -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.IconButton +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.windowInsetsPadding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.selection.selectableGroup +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.LocalContentColor import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.NavigationBar -import androidx.compose.material3.NavigationBarItem -import androidx.compose.material3.NavigationBarItemDefaults +import androidx.compose.material3.NavigationBarDefaults import androidx.compose.material3.NavigationRail import androidx.compose.material3.NavigationRailItem import androidx.compose.material3.NavigationRailItemDefaults import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.OutlinedTextFieldDefaults import androidx.compose.material3.Text -import androidx.compose.material3.TextFieldDefaults -import androidx.compose.material3.TopAppBar -import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.material3.ripple import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.mutableStateMapOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.drawBehind -import androidx.compose.ui.draw.shadow +import androidx.compose.ui.draw.drawWithContent +import androidx.compose.ui.geometry.CornerRadius import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.RoundRect import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.StrokeCap +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.layout.positionInParent import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.selected import androidx.compose.ui.semantics.semantics @@ -63,43 +76,53 @@ internal data class InspectorTopAction( ) /** - * The Android inspector's screen head: a muted 13sp sub-line, trailing 48dp round icon actions, - * and a large 27sp title below. + * Large screen title, optional live indicator and quiet 48dp actions, with a muted sub-line below. */ -@OptIn(ExperimentalMaterial3Api::class) @Composable internal fun InspectorTopArea( subLine: String, title: String, modifier: Modifier = Modifier, actions: List = emptyList(), + live: Boolean = true, ) { + val colors = DevConsoleTheme.colors Column(modifier = modifier) { - TopAppBar( - title = { Text(title) }, - actions = { - actions.forEach { action -> - IconButton(onClick = action.onClick) { - action.icon() - } + Row( + modifier = Modifier.fillMaxWidth().padding(start = 16.dp, end = 4.dp, top = 12.dp, bottom = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text(title, color = colors.ink, style = MaterialTheme.typography.headlineSmall) + if (live) { + Row( + modifier = Modifier.padding(start = 12.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Box(Modifier.size(8.dp).clip(CircleShape).background(colors.signal)) + Text("Live", color = colors.signal, fontSize = 13.sp) } - }, - colors = - TopAppBarDefaults.topAppBarColors( - containerColor = Color.Transparent, - titleContentColor = DevConsoleTheme.colors.ink, - actionIconContentColor = DevConsoleTheme.colors.muted, - ), - windowInsets = - androidx.compose.foundation.layout - .WindowInsets(0.dp), - ) + } + Spacer(Modifier.weight(1f)) + actions.forEach { action -> + InspectorRoundIconButton( + contentDescription = action.contentDescription, + onClick = action.onClick, + size = 48.dp, + icon = { + CompositionLocalProvider(LocalContentColor provides colors.muted) { + action.icon() + } + }, + ) + } + } if (subLine.isNotEmpty()) { Text( text = subLine, - modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 8.dp), + modifier = Modifier.padding(start = 20.dp, end = 20.dp, bottom = 8.dp), color = DevConsoleTheme.colors.muted, - style = MaterialTheme.typography.bodySmall, + fontSize = 13.sp, maxLines = 1, overflow = TextOverflow.Ellipsis, ) @@ -115,16 +138,14 @@ internal fun InspectorTopArea( */ @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. + * The Traffic tab's quiet "clear captures" action. */ internal fun clearCapturesTopAction(onClear: () -> Unit): InspectorTopAction = InspectorTopAction( contentDescription = "Clear captured requests", onClick = onClear, icon = { - ObserveGlyphIcon(ObserveGlyph.Trash, contentDescription = null, tint = DevConsoleTheme.colors.error) + ObserveGlyphIcon(ObserveGlyph.Trash, contentDescription = null, tint = DevConsoleTheme.colors.muted) }, ) @@ -145,17 +166,8 @@ internal data class InspectorTab( ) /** - * 52dp underline tabs: one 2dp round-capped indicator inset 14% each side, over a 1dp hairline. - * - * The indicator is a single bar that *travels* between tabs rather than one bar per tab flicking - * between signal and transparent. Material tabs slide, and the slide is what carries the meaning: - * it says which direction you moved through an ordered set, which a cut cannot. Drawn in - * [drawBehind] from an animated index, so the travel costs a redraw per frame and not a - * recomposition of five tabs. - * - * The dashboard's own `.detail-tab` keeps a static `border-bottom` here. That is a web idiom, not a - * shared decision -- on a native surface the platform's tab behaviour wins, the same way the nav - * bar and chips are real Material components rather than ports of the dashboard's rail. + * Scrollable, label-width tabs with a travelling 3dp signal indicator and a 1dp baseline. + * Measured tab bounds let the indicator interpolate across labels of different widths. */ @Composable internal fun InspectorTabRow( @@ -164,6 +176,7 @@ internal fun InspectorTabRow( ) { val colors = DevConsoleTheme.colors val selectedIndex = tabs.indexOfFirst { it.selected } + val tabBounds = remember { mutableStateMapOf>() } // Held at the last real selection while nothing is selected, so the bar never flies to tab 0 // and back during the frame a gated tab is being swapped out from under it. val travel = remember { Animatable(selectedIndex.coerceAtLeast(0).toFloat()) } @@ -171,60 +184,82 @@ internal fun InspectorTabRow( LaunchedEffect(selectedIndex, travelSpec) { if (selectedIndex >= 0) travel.animateTo(selectedIndex.toFloat(), travelSpec) } - Row( + Box( modifier = modifier.fillMaxWidth().drawBehind { val strokeWidth = 1.dp.toPx() val hairlineY = size.height - strokeWidth / 2 drawLine(colors.line, Offset(0f, hairlineY), Offset(size.width, hairlineY), strokeWidth) - if (selectedIndex < 0 || tabs.isEmpty()) return@drawBehind - val tabWidth = size.width / tabs.size - val indicatorWidth = tabWidth * TAB_INDICATOR_FRACTION - val centerX = tabWidth * travel.value + tabWidth / 2 - val indicatorHeight = 2.dp.toPx() - val indicatorY = size.height - indicatorHeight / 2 - drawLine( - color = colors.signal, - start = Offset(centerX - indicatorWidth / 2, indicatorY), - end = Offset(centerX + indicatorWidth / 2, indicatorY), - strokeWidth = indicatorHeight, - cap = StrokeCap.Round, - ) }, ) { - tabs.forEach { tab -> - // Animated so the label meets the bar rather than snapping ahead of it. - val labelColor by - animateColorAsState( - targetValue = if (tab.selected) colors.signal else colors.muted, - animationSpec = feedbackSpec(), - label = "tabLabel", - ) - Box( - modifier = - Modifier - .weight(1f) - .height(52.dp) - .clickable(onClick = tab.onClick, role = Role.Tab) - .semantics(mergeDescendants = true) { selected = tab.selected }, - contentAlignment = Alignment.Center, - ) { - Text( - tab.label, - color = labelColor, - style = MaterialTheme.typography.titleSmall, - ) + // Padding before the draw: tab bounds come from positionInParent, which is measured + // inside this padding, so the indicator must draw in the same space or it lands 16dp left. + Row( + modifier = + Modifier + .horizontalScroll(rememberScrollState()) + .padding(start = 16.dp, end = 16.dp) + .drawWithContent { + drawContent() + if (selectedIndex < 0 || tabs.isEmpty()) return@drawWithContent + val index = travel.value.coerceIn(0f, tabs.lastIndex.toFloat()) + val fromIndex = index.toInt() + val from = tabBounds[fromIndex] ?: return@drawWithContent + val to = tabBounds[(fromIndex + 1).coerceAtMost(tabs.lastIndex)] ?: from + val fraction = index - fromIndex + val left = from.first + (to.first - from.first) * fraction + val width = from.second + (to.second - from.second) * fraction + val radius = CornerRadius(2.dp.toPx()) + val path = + Path().apply { + addRoundRect( + RoundRect( + left = left, + top = size.height - 3.dp.toPx(), + right = left + width, + bottom = size.height, + topLeftCornerRadius = radius, + topRightCornerRadius = radius, + ), + ) + } + drawPath(path, colors.signal) + }, + horizontalArrangement = Arrangement.spacedBy(22.dp), + ) { + tabs.forEachIndexed { index, tab -> + // Animated so the label meets the bar rather than snapping ahead of it. + val labelColor by + animateColorAsState( + targetValue = if (tab.selected) colors.signal else colors.muted, + animationSpec = feedbackSpec(), + label = "tabLabel", + ) + Box( + modifier = + Modifier + .height(48.dp) + .onGloballyPositioned { + tabBounds[index] = it.positionInParent().x to it.size.width.toFloat() + }.clickable(onClick = tab.onClick, role = Role.Tab) + .semantics(mergeDescendants = true) { selected = tab.selected }, + contentAlignment = Alignment.Center, + ) { + Text( + tab.label, + color = labelColor, + fontSize = 14.sp, + fontWeight = if (tab.selected) FontWeight.SemiBold else FontWeight.Normal, + maxLines = 1, + ) + } } } } } -/** Indicator width as a share of one tab's width -- the 14%-a-side inset the mock specifies. */ -private const val TAB_INDICATOR_FRACTION = 0.72f - /** - * Search field on the shared 16dp gutter: a surface-2 [OutlinedTextField] with its indicator lines - * suppressed, shaped by [DevConsoleShapes]' `medium`. Callers wrap it in + * Panel search field on the shared 16dp gutter, with a signal outline when focused. Callers use * `LazyListScope.stickyHeader` when it needs to stick to the top of a scrolling list -- this * component is scroll-container agnostic. */ @@ -238,7 +273,7 @@ internal fun InspectorSearchBar( OutlinedTextField( value = query, onValueChange = onQueryChange, - modifier = modifier.fillMaxWidth().padding(horizontal = 16.dp), + modifier = modifier.fillMaxWidth().padding(horizontal = 16.dp).height(52.dp), placeholder = { Text(placeholder) }, leadingIcon = { InspectorGlyphIcon( @@ -249,22 +284,23 @@ internal fun InspectorSearchBar( ) }, singleLine = true, - shape = MaterialTheme.shapes.medium, + shape = RoundedCornerShape(12.dp), colors = - TextFieldDefaults.colors( - focusedContainerColor = DevConsoleTheme.colors.surface2, - unfocusedContainerColor = DevConsoleTheme.colors.surface2, - focusedIndicatorColor = Color.Transparent, - unfocusedIndicatorColor = Color.Transparent, + OutlinedTextFieldDefaults.colors( + focusedContainerColor = DevConsoleTheme.colors.panel, + unfocusedContainerColor = DevConsoleTheme.colors.panel, + focusedBorderColor = DevConsoleTheme.colors.signal, + unfocusedBorderColor = DevConsoleTheme.colors.line, focusedTextColor = DevConsoleTheme.colors.ink, unfocusedTextColor = DevConsoleTheme.colors.ink, - focusedPlaceholderColor = DevConsoleTheme.colors.text3, - unfocusedPlaceholderColor = DevConsoleTheme.colors.text3, + focusedPlaceholderColor = DevConsoleTheme.colors.muted, + unfocusedPlaceholderColor = DevConsoleTheme.colors.muted, + cursorColor = DevConsoleTheme.colors.signal, ), ) } -/** Extended FAB: flag icon + bold label. Pair with [EvidenceFabScrollClearance]. */ +/** Quiet surface pill with a flag icon. Pair with [EvidenceFabScrollClearance]. */ @Composable internal fun EvidenceFab( label: String, @@ -274,10 +310,10 @@ internal fun EvidenceFab( Row( modifier = modifier - .height(56.dp) - .shadow(DevConsoleElevation.level3, MaterialTheme.shapes.extraLarge) - .clip(MaterialTheme.shapes.extraLarge) - .background(DevConsoleTheme.colors.signal) + .height(48.dp) + .clip(RoundedCornerShape(24.dp)) + .background(DevConsoleTheme.colors.panel) + .border(1.dp, DevConsoleTheme.colors.line, RoundedCornerShape(24.dp)) .clickable(onClick = onClick, role = Role.Button) .padding(horizontal = 20.dp), verticalAlignment = Alignment.CenterVertically, @@ -286,10 +322,10 @@ internal fun EvidenceFab( InspectorGlyphIcon( InspectorGlyph.Flag, contentDescription = null, - tint = DevConsoleTheme.colors.signalInk, + tint = DevConsoleTheme.colors.ink, size = 19.dp, ) - Text(label, color = DevConsoleTheme.colors.signalInk, fontSize = 14.5.sp, fontWeight = FontWeight.Bold) + Text(label, color = DevConsoleTheme.colors.ink, fontSize = 14.5.sp, fontWeight = FontWeight.SemiBold) } } @@ -297,13 +333,11 @@ internal fun EvidenceFab( internal val EvidenceFabScrollClearance = 104.dp /** - * Icon tint for a nav destination. The selected item sits on a signal-filled indicator pill, so its - * icon takes `signalInk` (the on-signal role) rather than `signal` itself -- shared by the bar and - * the rail so the two can never drift apart. + * Signal marks the selected nav destination on both the bar and rail. */ @Composable private fun navItemIconColor(selected: Boolean): Color = - if (selected) DevConsoleTheme.colors.signalInk else DevConsoleTheme.colors.muted + if (selected) DevConsoleTheme.colors.signal else DevConsoleTheme.colors.muted /** One destination in [InspectorBottomNav]. */ internal data class InspectorNavItem( @@ -313,35 +347,79 @@ internal data class InspectorNavItem( val icon: @Composable () -> Unit, ) +/** + * The bottom bar, drawn by hand rather than with Material's NavigationBar: that one animates every + * item's colours through composition, recomposing the whole bar on each frame of a switch. Here the + * pill fades in the draw phase and only the two items whose selection changed recompose. + */ @Composable internal fun InspectorNavigationBar( items: List, modifier: Modifier = Modifier, ) { - NavigationBar( - modifier = modifier, - containerColor = DevConsoleTheme.colors.panel, + val colors = DevConsoleTheme.colors + Row( + modifier = + modifier + .fillMaxWidth() + .background(colors.panel) + .drawWithContent { + drawContent() + val strokeWidth = 1.dp.toPx() + drawLine(colors.line, Offset(0f, strokeWidth / 2), Offset(size.width, strokeWidth / 2), strokeWidth) + }.windowInsetsPadding(NavigationBarDefaults.windowInsets) + .height(80.dp) + .selectableGroup(), + verticalAlignment = Alignment.CenterVertically, ) { - items.forEach { item -> - NavigationBarItem( - selected = item.selected, - onClick = item.onClick, - icon = { - CompositionLocalProvider(LocalContentColor provides navItemIconColor(item.selected)) { - item.icon() - } - }, - label = { Text(item.label) }, - colors = - NavigationBarItemDefaults.colors( - indicatorColor = DevConsoleTheme.colors.signal, - selectedIconColor = DevConsoleTheme.colors.signalInk, - selectedTextColor = DevConsoleTheme.colors.ink, - unselectedIconColor = DevConsoleTheme.colors.muted, - unselectedTextColor = DevConsoleTheme.colors.muted, - ), - ) + items.forEach { item -> key(item.label) { InspectorNavBarItem(item, Modifier.weight(1f)) } } + } +} + +@Composable +private fun InspectorNavBarItem( + item: InspectorNavItem, + modifier: Modifier = Modifier, +) { + val colors = DevConsoleTheme.colors + val pillAlpha = remember { Animatable(if (item.selected) 1f else 0f) } + val pillSpec = feedbackSpec() + LaunchedEffect(item.selected) { pillAlpha.animateTo(if (item.selected) 1f else 0f, pillSpec) } + val interactionSource = remember { MutableInteractionSource() } + Column( + modifier = + modifier + .fillMaxHeight() + .selectable( + selected = item.selected, + onClick = item.onClick, + role = Role.Tab, + interactionSource = interactionSource, + indication = null, + ), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center, + ) { + Box( + modifier = + Modifier + .size(width = 64.dp, height = 32.dp) + .clip(RoundedCornerShape(16.dp)) + .drawBehind { drawRect(colors.signalSoft, alpha = pillAlpha.value) } + .indication(interactionSource, ripple()), + contentAlignment = Alignment.Center, + ) { + CompositionLocalProvider(LocalContentColor provides navItemIconColor(item.selected)) { item.icon() } } + Spacer(Modifier.height(4.dp)) + Text( + item.label, + color = if (item.selected) colors.signal else colors.muted, + fontSize = 12.sp, + lineHeight = 16.sp, + fontWeight = if (item.selected) FontWeight.SemiBold else FontWeight.Medium, + maxLines = 1, + ) } } @@ -363,12 +441,17 @@ internal fun InspectorNavigationRail( item.icon() } }, - label = { Text(item.label) }, + label = { + Text( + item.label, + fontWeight = if (item.selected) FontWeight.SemiBold else FontWeight.Normal, + ) + }, colors = NavigationRailItemDefaults.colors( - indicatorColor = DevConsoleTheme.colors.signal, - selectedIconColor = DevConsoleTheme.colors.signalInk, - selectedTextColor = DevConsoleTheme.colors.ink, + indicatorColor = DevConsoleTheme.colors.signalSoft, + selectedIconColor = DevConsoleTheme.colors.signal, + selectedTextColor = DevConsoleTheme.colors.signal, unselectedIconColor = DevConsoleTheme.colors.muted, unselectedTextColor = DevConsoleTheme.colors.muted, ), diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorNavGlyphs.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorNavGlyphs.kt index 22fc4e5..56ceecd 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorNavGlyphs.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorNavGlyphs.kt @@ -3,36 +3,19 @@ * @since 04/08/26 */ @file:Suppress("FunctionNaming", "MagicNumber", "MatchingDeclarationName") -@file:OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class) package io.devconsole.ui.compose -import androidx.compose.foundation.Canvas import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier -import androidx.compose.ui.geometry.Offset -import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.Path -import androidx.compose.ui.graphics.StrokeCap -import androidx.compose.ui.graphics.StrokeJoin -import androidx.compose.ui.graphics.drawscope.DrawScope -import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.semantics.contentDescription -import androidx.compose.ui.semantics.invisibleToUser -import androidx.compose.ui.semantics.semantics import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp -/** - * [InspectorBottomNav]'s destination icons: Observe reuses [ObserveGlyph.Activity]; - * Control/Data/More need their own icons, which live here. - */ -internal enum class NavGlyph { Send, Db, Grid } - -private const val GLYPH_VIEWBOX = 16f -private const val GLYPH_STROKE_WIDTH = 1.4f +/** [InspectorNavigationBar]'s destination icons: eye, sliders, database and an ellipsis. */ +internal enum class NavGlyph { Observe, Control, Data, More } /** Renders one [NavGlyph]; same contract as [InspectorGlyphIcon] (null description = decorative). */ @Composable @@ -43,84 +26,13 @@ internal fun NavGlyphIcon( tint: Color = DevConsoleTheme.colors.ink, size: Dp = 18.dp, ) { - Canvas( - modifier = - modifier - .size(size) - .then( - if (contentDescription != null) { - Modifier.semantics { this.contentDescription = contentDescription } - } else { - Modifier.semantics { invisibleToUser() } - }, - ), - ) { - drawNavGlyph(glyph, tint) - } + DevConsoleIcon(glyph.drawableRes(), contentDescription, modifier, tint, size) } -private fun DrawScope.drawNavGlyph( - glyph: NavGlyph, - tint: Color, -) { - val scale = size.width / GLYPH_VIEWBOX - val stroke = - Stroke( - width = size.width * (GLYPH_STROKE_WIDTH / GLYPH_VIEWBOX), - cap = StrokeCap.Round, - join = StrokeJoin.Round, - ) - when (glyph) { - NavGlyph.Send -> drawSend(scale, stroke, tint) - NavGlyph.Db -> drawDb(scale, stroke, tint) - NavGlyph.Grid -> drawGrid(scale, stroke, tint) +private fun NavGlyph.drawableRes(): Int = + when (this) { + NavGlyph.Observe -> R.drawable.devconsole_ic_overview + NavGlyph.Control -> R.drawable.devconsole_ic_preferences + NavGlyph.Data -> R.drawable.devconsole_ic_database + NavGlyph.More -> R.drawable.devconsole_ic_more_horizontal } -} - -/** M14 2 2 7l4.5 1.5L8 14l6-12ZM6.5 8.5 14 2 -- paper-airplane outline + the fold line. */ -private fun DrawScope.drawSend( - scale: Float, - stroke: Stroke, - tint: Color, -) { - val path = Path() - path.moveTo(14f * scale, 2f * scale) - path.lineTo(2f * scale, 7f * scale) - path.lineTo(6.5f * scale, 8.5f * scale) - path.lineTo(8f * scale, 14f * scale) - path.close() - path.moveTo(6.5f * scale, 8.5f * scale) - path.lineTo(14f * scale, 2f * scale) - drawPath(path, color = tint, style = stroke) -} - -/** M8 2c3 0 5.5.9 5.5 2s... -- a cylinder: top ellipse + two side lines + a mid ellipse arc. */ -private fun DrawScope.drawDb( - scale: Float, - stroke: Stroke, - tint: Color, -) { - val topLeft = Offset(2.5f * scale, 2f * scale) - val ellipseSize = Size(11f * scale, 4f * scale) - drawOval(color = tint, topLeft = topLeft, size = ellipseSize, style = stroke) - val leftX = 2.5f * scale - val rightX = 13.5f * scale - drawLine(tint, Offset(leftX, 4f * scale), Offset(leftX, 12f * scale), strokeWidth = stroke.width) - drawLine(tint, Offset(rightX, 4f * scale), Offset(rightX, 12f * scale), strokeWidth = stroke.width) - val arc = { midY: Float -> Offset(leftX, midY * scale) } - drawArc(tint, 0f, 180f, useCenter = false, topLeft = arc(6f), size = ellipseSize, style = stroke) - drawArc(tint, 0f, 180f, useCenter = false, topLeft = arc(10f), size = ellipseSize, style = stroke) -} - -/** M2 2h5v5H2zM9 2h5v5H9zM2 9h5v5H2zM9 9h5v5H9z -- a 2x2 grid of small squares. */ -private fun DrawScope.drawGrid( - scale: Float, - stroke: Stroke, - tint: Color, -) { - val squareSize = Size(5f * scale, 5f * scale) - drawRect(color = tint, topLeft = Offset(2f * scale, 2f * scale), size = squareSize, style = stroke) - drawRect(color = tint, topLeft = Offset(9f * scale, 2f * scale), size = squareSize, style = stroke) - drawRect(color = tint, topLeft = Offset(2f * scale, 9f * scale), size = squareSize, style = stroke) - drawRect(color = tint, topLeft = Offset(9f * scale, 9f * scale), size = squareSize, style = stroke) -} diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveCrashDetail.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveCrashDetail.kt index 47b1a05..7302b62 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveCrashDetail.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveCrashDetail.kt @@ -79,29 +79,17 @@ private fun crashSections( dumpBody, copyDescription = "Copy stack trace", onCopy = dumpCopy, + tab = InspectorDetailTab.STACK_TRACE, ), ) } private fun crashFooterActions( colors: DevConsoleColors, - isFlagged: Boolean, - onToggleFlag: () -> Unit, copyPayload: String, copyText: (String) -> Unit, ): List = listOf( - InspectorFooterAction( - label = if (isFlagged) "Flagged as evidence" else "Flag as evidence", - onClick = onToggleFlag, - weight = 2f, - icon = { - val tint = if (isFlagged) colors.signal else colors.signalInk - InspectorGlyphIcon(InspectorGlyph.Flag, contentDescription = null, tint = tint, size = 18.dp) - }, - containerColor = if (isFlagged) colors.signalSoft else colors.signal, - contentColor = if (isFlagged) colors.signal else colors.signalInk, - ), InspectorFooterAction( label = "Copy", onClick = { copyText(copyPayload) }, @@ -144,15 +132,22 @@ internal fun crashDetailContent( leadColor = leadColor, leadContainerColor = leadBg, title = crash.summary, - subtitle = "$threadLabel · $kindLabel", - status = formatCaptureClockTime(crash.timestampEpochMs), + subtitle = "$kindLabel · $threadLabel · ${formatCaptureClockTime(crash.timestampEpochMs)}", + status = "", statusColor = colors.muted, actions = listOf( InspectorTopAction( - contentDescription = "Copy crash report", - onClick = { copyText(copyPayload) }, - icon = copyIconAction(colors.muted), + contentDescription = if (isFlagged) "Flagged as evidence" else "Flag as evidence", + onClick = onToggleFlag, + icon = { + InspectorGlyphIcon( + InspectorGlyph.Flag, + null, + tint = if (isFlagged) colors.ink else colors.muted, + size = 20.dp, + ) + }, ), InspectorTopAction( contentDescription = "Share crash report", @@ -165,6 +160,6 @@ internal fun crashDetailContent( // General, breadcrumbs and the dump all open by default -- this screen exists to answer "what // happened and what led up to it" at a glance, not to require expanding every section first. initiallyOpenSectionKeys = setOf("general", "crumbs", "dump"), - footerActions = crashFooterActions(colors, isFlagged, onToggleFlag, copyPayload, copyText), + footerActions = crashFooterActions(colors, copyPayload, copyText), ) } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveCrashesTab.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveCrashesTab.kt index 051b315..39c87c2 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveCrashesTab.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveCrashesTab.kt @@ -36,8 +36,8 @@ internal fun CrashesTabContent( actions: ObserveActions, ) { val colors = DevConsoleTheme.colors - if (state.crashes.isEmpty()) { - ObserveTabEmptyState("No crashes or ANRs captured yet.") + if (state.crashes.isEmpty() && !ui.searchOpen) { + ObserveTabEmptyState("No crashes or ANRs captured yet.", EmptySpot.CrashesClear) return } val searched = @@ -58,27 +58,29 @@ internal fun CrashesTabContent( val arrivals = rememberArrivals(rowsNewestFirst.map { it.id }) LazyColumn( modifier = Modifier.fillMaxSize(), - // 16dp side / 12dp top padding with FAB clearance at the bottom, like every Observe tab's - // scroll container. - contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = 12.dp, bottom = EvidenceFabScrollClearance), + contentPadding = PaddingValues(top = 12.dp, bottom = 24.dp), ) { - stickyHeader { - InspectorSearchBar( - query = ui.crashesSearch, - onQueryChange = actions.onCrashesSearchChange, - placeholder = "Search summary, thread or dump", - ) + if (ui.searchOpen) { + stickyHeader { + InspectorSearchBar( + query = ui.crashesSearch, + onQueryChange = actions.onCrashesSearchChange, + placeholder = "Search summary, thread or dump", + modifier = Modifier.padding(horizontal = 16.dp), + ) + } } - item { Spacer(Modifier.height(16.dp)) } - item { CrashesHero(state.crashes, ui, actions, colors) } - item { Spacer(Modifier.height(16.dp)) } - item { GroupLabel("Newest first") } - itemsIndexed(rowsNewestFirst, key = { _, crash -> crash.id }) { _, crash -> + if (state.crashes.isNotEmpty()) { + item { CrashesHero(state.crashes, ui, actions, colors) } + item { Spacer(Modifier.height(12.dp)) } + } + if (rowsNewestFirst.isEmpty()) item { ObserveTabEmptyState("No matching crashes.", EmptySpot.Search) } + itemsIndexed(rowsNewestFirst, key = { _, crash -> crash.id }) { index, crash -> CrashRow( crash = crash, isFlagged = crash.id in ui.flaggedCrashIds, colors = colors, - modifier = Modifier.animateItem(), + modifier = Modifier.animateItem().groupedPanelItem(GroupPosition.of(index, rowsNewestFirst.size)), isArrival = crash.id in arrivals, onClick = { actions.onOpenCrashDetail(crash.id) }, ) @@ -128,25 +130,20 @@ private fun CrashRow( modifier: Modifier = Modifier, isArrival: Boolean = false, ) { - val (leadColor, leadBg) = logLevelTint(crash.kind, colors) val crumbCount = crash.breadcrumbs.size val crumbNoun = if (crumbCount == 1) "breadcrumb" else "breadcrumbs" Column(modifier = modifier.fillMaxWidth()) { TonalListRow( isArrival = isArrival, - leadText = logLevelShortLabel(crash.kind), - leadColor = leadColor, - leadContainerColor = leadBg, + leadText = if (crash.kind.equals("ANR", ignoreCase = true)) "ANR" else "CRASH", + leadColor = colors.muted, + leadContainerColor = Color.Transparent, title = if (crash.summary.length > 40) crash.summary.take(40) + "…" else crash.summary, subtitle = "${crash.thread.ifBlank { "unknown thread" }} · $crumbCount $crumbNoun", trailValue = formatCaptureClockTime(crash.timestampEpochMs), trailValueColor = colors.muted, - containerColor = if (isFlagged) colors.signalSoft else Color.Transparent, + containerColor = if (isFlagged) colors.surface2 else Color.Transparent, onClick = onClick, ) - androidx.compose.material3.HorizontalDivider( - modifier = Modifier.padding(start = 76.dp), - color = colors.line, - ) } } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt index 74af394..9c4c908 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt @@ -7,16 +7,24 @@ package io.devconsole.ui.compose import androidx.activity.compose.BackHandler +import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.Surface import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue +import androidx.compose.runtime.key import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateMapOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshots.SnapshotStateMap import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp @@ -65,6 +73,19 @@ internal sealed interface InspectorDetailSectionBody { ) : InspectorDetailSectionBody } +/** Display order also determines the default tab; sections without an assignment go to Overview. */ +internal enum class InspectorDetailTab( + val label: String, +) { + RESPONSE("Response"), + REQUEST("Request"), + STACK_TRACE("Stack trace"), + PAYLOAD("Payload"), + VALUE("Value"), + OVERVIEW("Overview"), + TIMING("Timing"), +} + /** One section of a capture detail screen, mirroring one `aSec(key, label, body, copyAs)` call. */ internal data class InspectorDetailSectionSpec( val key: String, @@ -72,6 +93,7 @@ internal data class InspectorDetailSectionSpec( val body: InspectorDetailSectionBody, val copyDescription: String? = null, val onCopy: (() -> Unit)? = null, + val tab: InspectorDetailTab = InspectorDetailTab.OVERVIEW, ) /** Bundles [InspectorDetailHeader]'s payload so [InspectorObserveDetailScreen] stays under the param-count limit. */ @@ -85,6 +107,7 @@ internal data class InspectorObserveDetailHeaderSpec( val status: String, val statusColor: Color, val actions: List = emptyList(), + val notices: List = emptyList(), ) private data class ResolvedDetailSection( @@ -370,7 +393,7 @@ private fun ObserveDetailSearchBar( null }, navigationEnabled = matchCount > 0, - onOpenOptions = if (searching) onOpenOptions else null, + onOpenOptions = if (searching && scopeLabel != null) onOpenOptions else null, scopeLabel = scopeLabel, modifier = modifier, placeholder = placeholder, @@ -476,14 +499,12 @@ private fun InspectorDetailSectionCard( onToggle: () -> Unit, onExpandCodeFullScreen: (String) -> Unit, ) { - // 12dp bottom margin per card, including the last one -- - // InspectorDetailScaffold's own 100dp bottom content padding covers the footer clearance on top. - CollapsibleSection( + ObserveDetailPanel( label = spec.label, + keyValueGroup = spec.body is InspectorDetailSectionBody.KeyValues, expanded = resolved.expanded, onToggle = onToggle, - modifier = Modifier.padding(bottom = 12.dp), - meta = resolved.meta.ifEmpty { null }, + meta = resolved.meta.takeIf { "match" in it }, metaColor = resolved.metaColor, onCopy = spec.onCopy, copyContentDescription = spec.copyDescription ?: "Copy ${spec.label}", @@ -503,6 +524,7 @@ private fun InspectorDetailSectionCard( is InspectorDetailSectionBody.Code -> InspectorCodeBlock( lines = body.lines, + modifier = Modifier.padding(horizontal = 16.dp), sectionKey = spec.key, searchMatches = resolved.searchMatches, currentMatchOrdinal = currentMatchOrdinal, @@ -511,6 +533,7 @@ private fun InspectorDetailSectionCard( is InspectorDetailSectionBody.Formattable -> InspectorFormattableBody( body = body, + modifier = Modifier.padding(horizontal = 16.dp), showRaw = formattableShowRaw, onShowRawChange = onFormattableShowRawChange, sectionKey = spec.key, @@ -518,7 +541,7 @@ private fun InspectorDetailSectionCard( currentMatchOrdinal = currentMatchOrdinal, onExpandFullScreen = { onExpandCodeFullScreen(spec.key) }, ) - is InspectorDetailSectionBody.Bars -> InspectorProgressBars(body.stats) + is InspectorDetailSectionBody.Bars -> ObserveDetailTiming(body.stats) is InspectorDetailSectionBody.Empty, null -> InspectorDetailEmptyText("Nothing captured.") } } @@ -526,11 +549,10 @@ private fun InspectorDetailSectionCard( } /** - * The full-screen capture detail overlay for all four capture kinds: header + live find field, - * [sections] as [CollapsibleSection]s with search-driven expand/highlight behavior, and a footer - * action bar. [resetKey] identifies which capture is open (e.g. a transaction id) so the find query - * and each section's manual open/closed state reset when a different capture is opened. Both the - * header's back button and the system back gesture close it via [onBack]. + * Capture detail overlay: fixed header, tabs and find field above scrolling grouped sections. + * Search resolves all [sections] before selecting the visible tab. [resetKey] identifies the item + * so its tab and search state reset when opening another capture. Both the header's back button + * and the system back gesture close it via [onBack]. */ @Composable internal fun InspectorObserveDetailScreen( @@ -544,29 +566,38 @@ internal fun InspectorObserveDetailScreen( searchPlaceholder: String = DEFAULT_DETAIL_SEARCH_PLACEHOLDER, searchOptions: InspectorDetailSearchOptions? = null, ) { + val tabs = remember(sections) { sections.map { it.tab }.distinct().sortedBy { it.ordinal } } + val showTabs = tabs.size > 1 + var selectedTab by + rememberSaveable(resetKey) { + mutableStateOf(tabs.firstOrNull() ?: InspectorDetailTab.OVERVIEW) + } + // Kinds that previously searched their whole document still do so, now with match navigation. + // Network keeps its existing body/header scopes and Raw/Formatted search options. + val availableSearchOptions = + remember(sections, searchOptions, showTabs) { searchOptions ?: documentSearchOptions(sections, showTabs) } var query by rememberSaveable(resetKey) { mutableStateOf("") } + var searchVisible by rememberSaveable(resetKey) { mutableStateOf(false) } var selectedSectionKeys by rememberSaveable(resetKey) { - mutableStateOf(searchOptions?.defaultSectionKeys?.toList().orEmpty()) + mutableStateOf(availableSearchOptions?.defaultSectionKeys?.toList().orEmpty()) } // Enums are Serializable, so the mode survives process death without a name round-trip. var searchMode by rememberSaveable(resetKey) { - mutableStateOf(searchOptions?.defaultMode ?: InspectorSearchMode.KEYS_AND_VALUES) + mutableStateOf(availableSearchOptions?.defaultMode ?: InspectorSearchMode.KEYS_AND_VALUES) } var currentMatchOrdinal by rememberSaveable(resetKey) { mutableIntStateOf(0) } + var lastFocusedMatch by rememberSaveable(resetKey) { mutableStateOf?>(null) } var rawFormattableSectionKeys by rememberSaveable(resetKey) { mutableStateOf(emptyList()) } var searchOptionsVisible by remember(resetKey) { mutableStateOf(false) } - val openState = - remember(resetKey) { - mutableStateMapOf().apply { initiallyOpenSectionKeys.forEach { key -> this[key] = true } } - } + val openState = remember(resetKey) { openSectionState(initiallyOpenSectionKeys) } val colors = DevConsoleTheme.colors val selectedKeys = remember(selectedSectionKeys) { selectedSectionKeys.toSet() } val rawSectionKeys = remember(rawFormattableSectionKeys) { rawFormattableSectionKeys.toSet() } - val searchableSectionKeys = remember(searchOptions) { searchOptions.searchableSectionKeys() } + val searchableSectionKeys = remember(availableSearchOptions) { availableSearchOptions.searchableSectionKeys() } val searchableSectionBodies = inspectorSearchSectionBodies(sections, searchableSectionKeys) - val searching = searchOptions != null + val searching = availableSearchOptions != null // Formattable bodies only offer the raw/formatted toggle on the kinds that carry search options. val onShowRawChange: ((String, Boolean) -> Unit)? = if (searching) { @@ -591,24 +622,34 @@ internal fun InspectorObserveDetailScreen( openState = openState, colors = colors, ) - val networkMatches = search.matches + val matches = search.matches val activeMatchOrdinal = search.activeMatchOrdinal val resolved = search.resolved val totalHits = search.totalHits + // Resolve matches against every section before filtering the rendered tab. Changing the tab + // mounts its body first; that body's existing BringIntoViewRequester then scrolls to the hit. + // Remember the focused occurrence too, so recreation preserves a manually selected tab even + // when the current search hit belongs to another tab. + val activeMatch = matches.getOrNull(activeMatchOrdinal) + val focusedMatch = activeMatch?.focusKey(query) + LaunchedEffect(resetKey, focusedMatch) { + if (focusedMatch != lastFocusedMatch) { + selectedTab = sections.tabOf(activeMatch) ?: selectedTab + lastFocusedMatch = focusedMatch + } + } + // Which section's code block (if any) is showing full-screen. // Bundle-safe on its own (a String key), and the lines it needs are re-derived from `resolved` // above on recreation rather than saved themselves -- InspectorCodeLine carries a Color, which // isn't a Saveable type. var fullScreenSectionKey by rememberSaveable(resetKey) { mutableStateOf(null) } - val fullScreenSection = - fullScreenSectionKey?.let { key -> - resolved.firstOrNull { (spec, _) -> spec.key == key } - } + val fullScreenSection = resolved.fullScreenSection(fullScreenSectionKey) BackHandler(onBack = onBack) - if (fullScreenSection != null && fullScreenSection.second.body.isFullScreenCapable()) { + if (fullScreenSection != null) { val (spec, section) = fullScreenSection ObserveDetailFullScreenOverlay( spec = spec, @@ -622,9 +663,8 @@ internal fun InspectorObserveDetailScreen( return } - InspectorDetailScaffold( - modifier = modifier.fillMaxSize(), - header = { + Surface(modifier = modifier.fillMaxSize(), color = colors.ground) { + Column(modifier = Modifier.fillMaxSize().imePadding()) { InspectorDetailHeader( kindLabel = header.kindLabel, leadText = header.leadText, @@ -635,42 +675,58 @@ internal fun InspectorObserveDetailScreen( status = header.status, statusColor = header.statusColor, onBack = onBack, - actions = header.actions, - ) - ObserveDetailSearchBar( - query = query, - onQueryChange = { - query = it - currentMatchOrdinal = 0 - }, - searching = searching, - matchCount = networkMatches.size, - activeMatchOrdinal = activeMatchOrdinal, - totalHits = totalHits, - onOrdinalChange = { currentMatchOrdinal = it }, - onOpenOptions = { searchOptionsVisible = true }, - scopeLabel = searchOptions?.let { inspectorSearchScopeSummary(it, selectedKeys) }, - placeholder = searchPlaceholder, - modifier = Modifier.padding(top = 12.dp), - ) - }, - footer = { InspectorDetailFooterBar(footerActions) }, - ) { - resolved.forEach { (spec, section) -> - InspectorDetailSectionCard( - spec = spec, - resolved = section, - currentMatchOrdinal = if (searching) activeMatchOrdinal else null, - formattableShowRaw = formattableShowRaw(spec, searching, rawSectionKeys), - onFormattableShowRawChange = - onShowRawChange?.let { change -> { showRaw -> change(spec.key, showRaw) } }, - onToggle = { openState[spec.key] = !section.expanded }, - onExpandCodeFullScreen = { key -> fullScreenSectionKey = key }, + actions = + header.actions + + detailSearchToggleAction(searchVisible, colors) { + searchVisible = !searchVisible + if (!searchVisible) { + query = "" + currentMatchOrdinal = 0 + } + }, ) + ObserveDetailTabs(tabs, selectedTab) { selectedTab = it } + if (searchVisible) { + ObserveDetailSearchBar( + query = query, + onQueryChange = { + query = it + currentMatchOrdinal = 0 + }, + searching = searching, + matchCount = matches.size, + activeMatchOrdinal = activeMatchOrdinal, + totalHits = totalHits, + onOrdinalChange = { + currentMatchOrdinal = it + // Explicitly focus even when next/previous wraps through a single match. + selectedTab = sections.tabOf(matches.getOrNull(it)) ?: selectedTab + }, + onOpenOptions = { searchOptionsVisible = true }, + scopeLabel = searchOptions?.let { inspectorSearchScopeSummary(it, selectedKeys) }, + placeholder = searchPlaceholder, + modifier = Modifier.padding(top = 12.dp), + ) + } + key(resetKey, selectedTab) { + ObserveDetailTabBody( + showTabs = showTabs, + selectedTab = selectedTab, + notices = header.notices, + resolved = resolved, + currentMatchOrdinal = if (searching) activeMatchOrdinal else null, + showRawOf = { spec -> formattableShowRaw(spec, searching, rawSectionKeys) }, + onShowRawChange = onShowRawChange, + onToggleSection = { key, expanded -> openState[key] = !expanded }, + onExpandCodeFullScreen = { key -> fullScreenSectionKey = key }, + footerActions = footerActions, + modifier = Modifier.weight(1f), + ) + } } } ObserveDetailSearchOptionsSheet( - options = searchOptions.takeIf { searchOptionsVisible }, + options = availableSearchOptions.takeIf { searchOptionsVisible }, selectedSectionKeys = selectedKeys, mode = searchMode, onDismiss = { searchOptionsVisible = false }, @@ -683,6 +739,111 @@ internal fun InspectorObserveDetailScreen( ) } +private fun openSectionState(initiallyOpenSectionKeys: Set): SnapshotStateMap = + mutableStateMapOf().apply { initiallyOpenSectionKeys.forEach { key -> this[key] = true } } + +/** The section showing its code full-screen, while its body can still be shown that way. */ +private fun List>.fullScreenSection( + key: String?, +): Pair? = + key + ?.let { + firstOrNull { (spec, _) -> + spec.key == it + } + }?.takeIf { (_, section) -> section.body.isFullScreenCapable() } + +/** The tab strip appears only once a kind has more than one tab. */ +@Composable +private fun ObserveDetailTabs( + tabs: List, + selectedTab: InspectorDetailTab, + onSelect: (InspectorDetailTab) -> Unit, +) { + if (tabs.size <= 1) return + InspectorTabRow(tabs = tabs.map { tab -> InspectorTab(tab.label, tab == selectedTab, onClick = { onSelect(tab) }) }) +} + +/** Kinds without their own search options search their whole document once they have tabs. */ +private fun documentSearchOptions( + sections: List, + showTabs: Boolean, +): InspectorDetailSearchOptions? = + if (showTabs) { + InspectorDetailSearchOptions( + sections = sections.map { InspectorDetailSearchSection(it.key, it.label) }, + defaultSectionKeys = sections.mapTo(mutableSetOf()) { it.key }, + ) + } else { + null + } + +/** Identifies one focused occurrence, so recreation can tell a new hit from the one already shown. */ +private fun InspectorDetailSearchMatch.focusKey(query: String): List = + listOf(query, sectionKey, itemId, field.name, start.toString(), ordinal.toString()) + +private fun List.tabOf(match: InspectorDetailSearchMatch?): InspectorDetailTab? = + match?.let { hit -> firstOrNull { it.key == hit.sectionKey }?.tab } + +private fun detailSearchToggleAction( + searchVisible: Boolean, + colors: DevConsoleColors, + onToggle: () -> Unit, +): InspectorTopAction = + InspectorTopAction( + contentDescription = if (searchVisible) "Close detail search" else "Search detail", + onClick = onToggle, + icon = { InspectorGlyphIcon(InspectorGlyph.Search, null, tint = colors.muted, size = 20.dp) }, + ) + +@Composable +private fun ObserveDetailTabBody( + showTabs: Boolean, + selectedTab: InspectorDetailTab, + notices: List, + resolved: List>, + currentMatchOrdinal: Int?, + showRawOf: (InspectorDetailSectionSpec) -> Boolean?, + onShowRawChange: ((String, Boolean) -> Unit)?, + onToggleSection: (String, Boolean) -> Unit, + onExpandCodeFullScreen: (String) -> Unit, + footerActions: List, + modifier: Modifier = Modifier, +) { + Column( + modifier = + modifier + .verticalScroll(rememberScrollState()) + .padding(top = if (showTabs) 8.dp else 12.dp, bottom = 24.dp), + ) { + val overviewVisible = !showTabs || selectedTab == InspectorDetailTab.OVERVIEW + if (overviewVisible && notices.isNotEmpty()) { + WarnNote(notices.joinToString(" · "), Modifier.padding(bottom = 16.dp)) + } + resolved.filter { (spec, _) -> !showTabs || spec.tab == selectedTab }.forEach { (spec, section) -> + key(spec.key) { + if (spec.tab == InspectorDetailTab.TIMING && + spec.body is InspectorDetailSectionBody.Empty + ) { + ObserveDetailNoTiming() + } else { + InspectorDetailSectionCard( + spec = spec, + resolved = section, + currentMatchOrdinal = currentMatchOrdinal, + formattableShowRaw = showRawOf(spec), + onFormattableShowRawChange = + onShowRawChange?.let { change -> { showRaw -> change(spec.key, showRaw) } }, + onToggle = { onToggleSection(spec.key, section.expanded) }, + onExpandCodeFullScreen = onExpandCodeFullScreen, + ) + } + } + } + if (overviewVisible) ObserveDetailActionRows(footerActions) + } +} + /** Renders the scope/mode sheet only while [options] is non-null, i.e. while the chip has it open. */ @Composable private fun ObserveDetailSearchOptionsSheet( @@ -744,7 +905,7 @@ internal fun copyIconAction(tint: Color): @Composable () -> Unit = { InspectorGlyphIcon(InspectorGlyph.Copy, contentDescription = null, tint = tint, size = 19.dp) } internal fun shareIconAction(tint: Color): @Composable () -> Unit = - { ObserveGlyphIcon(ObserveGlyph.Download, contentDescription = null, tint = tint, size = 19.dp) } + { DevConsoleIcon(R.drawable.devconsole_ic_share_nodes, null, Modifier, tint, 20.dp) } /** * A flat captured body preview rendered as an unadorned code block, one real line per line. Shared diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetailPanels.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetailPanels.kt new file mode 100644 index 0000000..50a2022 --- /dev/null +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetailPanels.kt @@ -0,0 +1,197 @@ +/** + * @author Shakib + * @since 19/10/26 + */ +@file:Suppress("FunctionNaming", "MagicNumber") + +package io.devconsole.ui.compose + +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.animation.expandVertically +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.shrinkVertically +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.IconButton +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp + +/** Detail-only collapsible panels; the mock editor keeps its shared section layout. */ +@Suppress("LongParameterList") +@Composable +internal fun ObserveDetailPanel( + label: String, + keyValueGroup: Boolean, + expanded: Boolean, + onToggle: () -> Unit, + meta: String?, + metaColor: Color, + onCopy: (() -> Unit)?, + copyContentDescription: String, + content: @Composable ColumnScope.() -> Unit, +) { + val rotation by animateFloatAsState( + targetValue = if (expanded) 0f else -90f, + animationSpec = chevronSpec(), + label = "sectionChevron", + ) + val heading: @Composable () -> Unit = { + Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Row( + modifier = + Modifier + .weight(1f) + .heightIn(min = 48.dp) + .clickable(role = Role.Button, onClick = onToggle), + verticalAlignment = Alignment.CenterVertically, + ) { + if (keyValueGroup) { + GroupLabel(label, Modifier.weight(1f)) + } else { + Text( + label, + modifier = Modifier.weight(1f).padding(start = 16.dp), + color = DevConsoleTheme.colors.ink, + fontSize = 14.sp, + fontWeight = FontWeight.SemiBold, + ) + } + if (meta != null) { + Text(meta, color = metaColor, fontFamily = FontFamily.Monospace, fontSize = 12.sp) + } + InspectorGlyphIcon( + InspectorGlyph.ChevronDown, + null, + modifier = Modifier.padding(horizontal = 12.dp), + tint = DevConsoleTheme.colors.muted, + size = 16.dp, + rotationDegrees = rotation, + ) + } + if (onCopy != null) { + IconButton(onClick = onCopy, modifier = Modifier.size(48.dp)) { + InspectorGlyphIcon( + InspectorGlyph.Copy, + copyContentDescription, + tint = DevConsoleTheme.colors.muted, + size = 18.dp, + ) + } + } + } + } + Column(modifier = Modifier.padding(bottom = 16.dp)) { + if (keyValueGroup) heading() + GroupedPanel { + if (!keyValueGroup) heading() + AnimatedVisibility( + visible = expanded, + enter = expandVertically(feedbackSpec(InspectorMotion.EXPAND_MS)) + fadeIn(feedbackSpec()), + exit = shrinkVertically(feedbackSpec()) + fadeOut(feedbackSpec()), + ) { + Column(content = content) + } + } + } +} + +/** The empty Timing tab has no collapsible heading or fabricated duration bars. */ +@Composable +internal fun ObserveDetailNoTiming() { + Text( + "No timing captured", + modifier = Modifier.fillMaxWidth().padding(16.dp), + color = DevConsoleTheme.colors.muted, + fontSize = 13.sp, + textAlign = TextAlign.Center, + ) +} + +/** One neutral phase bar, with measured values and labels below. */ +@Composable +internal fun ObserveDetailTiming(stats: List) { + val colors = DevConsoleTheme.colors + Column(modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 20.dp)) { + Row( + modifier = + Modifier + .fillMaxWidth() + .height(24.dp) + .clip(RoundedCornerShape(4.dp)) + .background(colors.surface3), + ) { + stats.forEach { stat -> + if (stat.fraction > 0f) { + Box(Modifier.weight(stat.fraction).height(24.dp).background(stat.color)) + } + } + } + Row( + modifier = Modifier.fillMaxWidth().padding(top = 12.dp), + horizontalArrangement = Arrangement.spacedBy(4.dp), + ) { + stats.forEach { stat -> + Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) { + Text(stat.valueText, color = colors.ink, fontFamily = FontFamily.Monospace, fontSize = 11.sp) + Text(stat.label, color = colors.muted, fontSize = 11.sp) + } + } + } + } +} + +/** Footer operations scroll with the capture as plain panel rows. */ +@Composable +internal fun ObserveDetailActionRows(actions: List) { + if (actions.isEmpty()) return + val colors = DevConsoleTheme.colors + GroupedPanel(modifier = Modifier.padding(bottom = 16.dp)) { + actions.forEachIndexed { index, action -> + if (index > 0) GroupedPanelDivider() + Row( + modifier = + Modifier + .fillMaxWidth() + .heightIn(min = 52.dp) + .clickable(enabled = action.enabled, role = Role.Button, onClick = action.onClick) + .padding(horizontal = 16.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(modifier = Modifier.weight(1f)) { + Text( + action.label, + color = if (action.enabled) colors.ink else colors.muted, + fontFamily = FontFamily.Monospace, + fontSize = 14.sp, + ) + action.supportingText?.let { Text(it, color = colors.muted, fontSize = 12.sp) } + } + DevConsoleIcon(R.drawable.devconsole_ic_chevron_right, null, Modifier, colors.muted, 20.dp) + } + } + } +} diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveFrameDetail.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveFrameDetail.kt index 886b41c..ded68dc 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveFrameDetail.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveFrameDetail.kt @@ -53,7 +53,7 @@ private fun frameSections( sizeLabel: String, copyText: (String) -> Unit, ): List { - val leadColor = if (frame.direction == "RECEIVED") colors.put else colors.signal + val leadColor = colors.ink val generalEntries = buildList { add(InspectorKeyValue("direction", frame.direction, leadColor)) @@ -70,7 +70,7 @@ private fun frameSections( listOf( InspectorKeyValue("protocol", socket.protocolLabel()), InspectorKeyValue("url", socket.url), - InspectorKeyValue("state", socket.state, if (socket.state == "OPEN") colors.signal else colors.muted), + InspectorKeyValue("state", socket.state), InspectorKeyValue("opened", formatCaptureClockTime(socket.openedAtEpochMs)), InspectorKeyValue("frames", "${socket.sentCount} sent · ${socket.receivedCount} received"), ) @@ -91,7 +91,7 @@ private fun frameSections( colors = colors, copyText = copyText, copyDescription = "Copy payload", - ), + ).copy(tab = InspectorDetailTab.PAYLOAD), InspectorDetailSectionSpec( InspectorExchangeSection.SECONDARY_HEADERS.key, "Connection", @@ -143,7 +143,7 @@ internal fun frameDetailContent( shareText: (String, String) -> Unit, ): ObserveDetailContent { val received = frame.direction == "RECEIVED" - val leadColor = if (received) colors.put else colors.signal + val leadColor = colors.ink val leadBg = if (received) colors.putSoft else colors.signalSoft val sizeLabel = socketFrameSizeLabel(frame) val frameJson = frameToJsonSnippet(socket, frame) @@ -159,16 +159,13 @@ internal fun frameDetailContent( leadColor = leadColor, leadContainerColor = leadBg, title = title, - subtitle = "${formatCaptureClockTime(frame.timestampEpochMs)} · ${frame.frameType} · $sizeLabel", - status = sizeLabel, + subtitle = "${frame.direction} · ${frame.frameType} · $sizeLabel · ${formatCaptureClockTime( + frame.timestampEpochMs, + )}", + status = "", statusColor = colors.ink, actions = listOf( - InspectorTopAction( - contentDescription = "Copy frame payload", - onClick = { copyText(frame.preview.orEmpty()) }, - icon = copyIconAction(colors.muted), - ), InspectorTopAction( contentDescription = "Share frame as JSON", onClick = { shareText(frameJson, "Share frame JSON") }, @@ -177,7 +174,8 @@ internal fun frameDetailContent( ), ), sections = frameSections(socket, frame, colors, sizeLabel, copyText), - initiallyOpenSectionKeys = setOf(InspectorExchangeSection.PRIMARY_BODY.key), + initiallyOpenSectionKeys = + setOf("general", InspectorExchangeSection.PRIMARY_BODY.key, InspectorExchangeSection.SECONDARY_HEADERS.key), footerActions = frameFooterActions(socket, frame, colors, copyText, shareText), ) } 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 ede094a..f151217 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 @@ -3,40 +3,24 @@ * @since 04/08/26 */ @file:Suppress("FunctionNaming", "MagicNumber", "MatchingDeclarationName") -@file:OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class) package io.devconsole.ui.compose -import androidx.compose.foundation.Canvas import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier -import androidx.compose.ui.geometry.Offset -import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.Path -import androidx.compose.ui.graphics.StrokeCap -import androidx.compose.ui.graphics.StrokeJoin -import androidx.compose.ui.graphics.drawscope.DrawScope -import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.semantics.contentDescription -import androidx.compose.ui.semantics.invisibleToUser -import androidx.compose.ui.semantics.semantics import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp /** * Observe-screen-only glyphs. Kept out of the shared [InspectorGlyph] set: shared components take * icons as caller-supplied `@Composable` slots so a screen can wire in whatever icon set it needs - * without touching shared-component files. Hand-drawn at 16x16 path coordinates (not pixel-perfect - * bezier replication of arcs -- the design spec's pixel-authoritative language covers - * sizes/spacing/radii/colors/typography/states, not icon vector art). + * without touching shared-component files. */ 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 - /** Renders one [ObserveGlyph]; same contract as [InspectorGlyphIcon] (null description = decorative). */ @Composable internal fun ObserveGlyphIcon( @@ -46,170 +30,17 @@ internal fun ObserveGlyphIcon( tint: Color = DevConsoleTheme.colors.ink, size: Dp = 18.dp, ) { - Canvas( - modifier = - modifier - .size(size) - .then( - if (contentDescription != null) { - Modifier.semantics { this.contentDescription = contentDescription } - } else { - Modifier.semantics { invisibleToUser() } - }, - ), - ) { - drawObserveGlyph(glyph, tint) - } + DevConsoleIcon(glyph.drawableRes(), contentDescription, modifier, tint, size) } -@Suppress("CyclomaticComplexMethod", "LongMethod") // One draw routine per glyph shape, all in one when. -private fun DrawScope.drawObserveGlyph( - glyph: ObserveGlyph, - tint: Color, -) { - val scale = size.width / GLYPH_VIEWBOX - val stroke = - Stroke( - width = size.width * (GLYPH_STROKE_WIDTH / GLYPH_VIEWBOX), - cap = StrokeCap.Round, - join = StrokeJoin.Round, - ) - val path = Path() - when (glyph) { - ObserveGlyph.Filter -> { - // M2 3h12l-4.5 5.5V13L6.5 11V8.5L2 3Z -- straight-edged funnel, no arcs. - path.moveTo(2f * scale, 3f * scale) - path.lineTo(14f * scale, 3f * scale) - path.lineTo(9.5f * scale, 8.5f * scale) - path.lineTo(9.5f * scale, 13f * scale) - path.lineTo(6.5f * scale, 11f * scale) - path.lineTo(6.5f * scale, 8.5f * scale) - path.close() - } - ObserveGlyph.Download -> { - // M8 2v8m0 0 3-3m-3 3L5 7M2.5 13h11 -- stem + chevron head + base line. - path.moveTo(8f * scale, 2f * scale) - path.lineTo(8f * scale, 10f * scale) - path.moveTo(8f * scale, 10f * scale) - path.lineTo(11f * scale, 7f * scale) - path.moveTo(8f * scale, 10f * scale) - path.lineTo(5f * scale, 7f * scale) - path.moveTo(2.5f * scale, 13f * scale) - path.lineTo(13.5f * scale, 13f * scale) - } - ObserveGlyph.Activity -> { - // M1.5 8h3L6 4.5 8.5 12l2-4h3.5 -- pulse zigzag, no arcs. - path.moveTo(1.5f * scale, 8f * scale) - path.lineTo(4.5f * scale, 8f * scale) - path.lineTo(6f * scale, 4.5f * scale) - path.lineTo(8.5f * scale, 12f * scale) - 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) - path.lineTo(7.5f * scale, 3f * scale) - path.lineTo(13f * scale, 3f * scale) - path.lineTo(13f * scale, 8.5f * scale) - path.lineTo(7.5f * scale, 14f * scale) - path.close() - } - ObserveGlyph.Plug -> drawPlug(path, scale, stroke, tint) - ObserveGlyph.Refresh -> drawRefresh(scale, stroke, tint) - ObserveGlyph.Sun -> drawSun(scale, stroke, tint) - } - if (glyph == ObserveGlyph.Tag) { - drawCircle(color = tint, radius = 1f * scale, center = Offset(10.5f * scale, 5.5f * scale), style = stroke) +private fun ObserveGlyph.drawableRes(): Int = + when (this) { + ObserveGlyph.Plug -> R.drawable.devconsole_ic_websockets + ObserveGlyph.Activity -> R.drawable.devconsole_ic_activity + ObserveGlyph.Filter -> R.drawable.devconsole_ic_filter_lines + ObserveGlyph.Refresh -> R.drawable.devconsole_ic_refresh + ObserveGlyph.Download -> R.drawable.devconsole_ic_download + ObserveGlyph.Sun -> R.drawable.devconsole_ic_sun + ObserveGlyph.Tag -> R.drawable.devconsole_ic_tag + ObserveGlyph.Trash -> R.drawable.devconsole_ic_trash } - if (glyph != ObserveGlyph.Refresh && glyph != ObserveGlyph.Sun) { - drawPath(path, color = tint, style = stroke) - } -} - -/** Center disc with 8 short rays. */ -private fun DrawScope.drawSun( - scale: Float, - stroke: Stroke, - tint: Color, -) { - drawCircle(color = tint, radius = 3f * scale, center = Offset(8f * scale, 8f * scale), style = stroke) - val rayInner = 5.4f * scale - val rayOuter = 7.5f * scale - val center = Offset(8f * scale, 8f * scale) - for (i in 0 until 8) { - val angle = (i * 45f) * (Math.PI / 180.0) - val dx = kotlin.math.cos(angle).toFloat() - val dy = kotlin.math.sin(angle).toFloat() - drawLine( - color = tint, - start = Offset(center.x + dx * rayInner, center.y + dy * rayInner), - end = Offset(center.x + dx * rayOuter, center.y + dy * rayOuter), - strokeWidth = stroke.width, - cap = StrokeCap.Round, - ) - } -} - -/** M6 2v4M10 2v4M4 6h8v2a4 4 0 0 1-4 4 4 4 0 0 1-4-4V6ZM8 12v2.5, approximated: two prongs + a cup + a stem. */ -private fun DrawScope.drawPlug( - path: Path, - scale: Float, - stroke: Stroke, - tint: Color, -) { - path.moveTo(6f * scale, 2f * scale) - path.lineTo(6f * scale, 6f * scale) - path.moveTo(10f * scale, 2f * scale) - path.lineTo(10f * scale, 6f * scale) - path.moveTo(4f * scale, 6f * scale) - path.lineTo(12f * scale, 6f * scale) - path.moveTo(8f * scale, 12f * scale) - path.lineTo(8f * scale, 14.5f * scale) - drawPath(path, color = tint, style = stroke) - // The cup's rounded underside as one shallow arc across the same span, instead of two quarter-arcs. - drawArc( - color = tint, - startAngle = 0f, - sweepAngle = 180f, - useCenter = false, - topLeft = Offset(4f * scale, 6f * scale), - size = Size(8f * scale, 6f * scale), - style = stroke, - ) -} - -/** M13.5 8a5.5 5.5 0 1 1-1.9-4.2M13.5 2v3h-3 -- circular sweep (drawArc) + a small arrowhead. */ -private fun DrawScope.drawRefresh( - scale: Float, - stroke: Stroke, - tint: Color, -) { - drawArc( - color = tint, - startAngle = -20f, - sweepAngle = 290f, - useCenter = false, - topLeft = Offset(2.5f * scale, 2.5f * scale), - size = Size(11f * scale, 11f * scale), - style = stroke, - ) - val head = Path() - head.moveTo(13.5f * scale, 2f * scale) - head.lineTo(13.5f * scale, 5f * scale) - head.lineTo(10.5f * scale, 5f * scale) - drawPath(head, color = tint, style = stroke) -} diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveHttpFormat.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveHttpFormat.kt index 7fa85f7..0d3722b 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveHttpFormat.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveHttpFormat.kt @@ -6,7 +6,6 @@ package io.devconsole.ui.compose import androidx.compose.ui.graphics.Color -private const val HTTP_REDIRECT_START = 300 private const val HTTP_CLIENT_ERROR_START = 400 private const val HTTP_SERVER_ERROR_START = 500 @@ -22,8 +21,7 @@ internal fun statusTint( statusCode == null -> colors.error statusCode >= HTTP_SERVER_ERROR_START -> colors.error statusCode >= HTTP_CLIENT_ERROR_START -> colors.warn - statusCode >= HTTP_REDIRECT_START -> colors.put - else -> colors.signal + else -> colors.ink } /** Matches the design spec's method-color scheme: (lead text color, lead badge background). */ @@ -41,3 +39,36 @@ internal fun methodTint( /** Abbreviates only DELETE; every other method passes through unchanged. */ internal fun methodLeadText(method: String): String = if (method == "DELETE") "DEL" else method + +/** Standard reason phrases, keyed by the code's text; unknown codes keep their captured numeric identity. */ +private val HTTP_REASON_PHRASES = + mapOf( + "200" to "OK", + "201" to "Created", + "202" to "Accepted", + "204" to "No Content", + "206" to "Partial Content", + "301" to "Moved Permanently", + "302" to "Found", + "304" to "Not Modified", + "307" to "Temporary Redirect", + "308" to "Permanent Redirect", + "400" to "Bad Request", + "401" to "Unauthorized", + "403" to "Forbidden", + "404" to "Not Found", + "405" to "Method Not Allowed", + "408" to "Request Timeout", + "409" to "Conflict", + "410" to "Gone", + "422" to "Unprocessable Content", + "429" to "Too Many Requests", + "500" to "Internal Server Error", + "501" to "Not Implemented", + "502" to "Bad Gateway", + "503" to "Service Unavailable", + "504" to "Gateway Timeout", + ) + +internal fun httpStatusDescription(code: Int?): String = + if (code == null) "No response received" else HTTP_REASON_PHRASES[code.toString()].orEmpty() diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveNetDetail.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveNetDetail.kt index bffdc7a..44d0a4c 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveNetDetail.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveNetDetail.kt @@ -7,27 +7,7 @@ package io.devconsole.ui.compose import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp -/** - * Share-as-JSON and flag-as-evidence header actions. - * - * Evidence flagging sits here and mocking sits in the footer ([netFooterActions]) -- the reverse of - * every other detail screen, and deliberate: mocking is the consequential act on this screen, since - * it changes what the host app receives on the next call, while flagging only files the capture for - * a report. The footer's labelled primary slot goes to the one with consequences. - * - * The flag still reads its armed state at a glance: signal on a signal-soft container once flagged, - * muted on transparent before, with the same wording the footer button used carried on the content - * description so TalkBack announces the state rather than just "flag". - * - * Copy-as-cURL is deliberately *not* here, though every other detail screen does put a copy action - * in the header: this one already carries a labelled "cURL" button in its footer bar running the - * identical `copyText(transaction.toCurlCommand())`. Two controls, same Copy glyph, same effect, - * one of them unlabelled -- so the header icon goes and the footer button, which says what it - * copies, stays. - * - * "Pin as diff baseline" is dropped for the same no-dead-chrome reason: nothing in [InspectorState] - * tracks a pinned baseline or renders a diff view. - */ +/** Evidence and sharing stay available as quiet header icons. */ private fun netHeaderActions( transaction: InspectorTransactionUi, colors: DevConsoleColors, @@ -36,19 +16,18 @@ private fun netHeaderActions( onToggleFlag: () -> Unit, ): List = listOf( - InspectorTopAction( - contentDescription = "Share transaction as JSON", - onClick = { shareText(transaction.toJsonSnippet(), "Share transaction JSON") }, - icon = shareIconAction(colors.muted), - ), InspectorTopAction( contentDescription = if (isFlagged) "Flagged as evidence" else "Flag as evidence", onClick = onToggleFlag, icon = { - val tint = if (isFlagged) colors.signal else colors.muted + val tint = if (isFlagged) colors.ink else colors.muted InspectorGlyphIcon(InspectorGlyph.Flag, contentDescription = null, tint = tint, size = 18.dp) }, - containerColor = if (isFlagged) colors.signalSoft else Color.Transparent, + ), + InspectorTopAction( + contentDescription = "Share transaction as JSON", + onClick = { shareText(transaction.toJsonSnippet(), "Share transaction JSON") }, + icon = shareIconAction(colors.muted), ), ) @@ -67,19 +46,19 @@ private fun timingPhaseStats( listOfNotNull( phases.dnsMs?.let { "DNS" to it }, phases.connectMs?.let { "Connect" to it }, - phases.tlsMs?.let { "TLS handshake" to it }, + phases.tlsMs?.let { "TLS" to it }, phases.sendMs?.let { "Send" to it }, - phases.waitMs?.let { "Waiting (TTFB)" to it }, + phases.waitMs?.let { "Wait" to it }, phases.receiveMs?.let { "Receive" to it }, ) val colorsByLabel = mapOf( "DNS" to colors.borderStrong, "Connect" to colors.muted, - "TLS handshake" to colors.put, + "TLS" to colors.text3, "Send" to colors.text3, - "Waiting (TTFB)" to colors.signal, - "Receive" to colors.warn, + "Wait" to colors.ink.copy(alpha = 0.55f), + "Receive" to colors.borderStrong, ) val total = present.sumOf { (_, ms) -> ms } return present.map { (label, ms) -> @@ -93,29 +72,20 @@ private fun timingPhaseStats( } /** - * Per-phase bars when the transport captured [InspectorTransactionUi.timingPhases]; otherwise the - * total-duration text this section has always shown -- a transaction with no phase data at all - * (most transports, or a timed-out request) must never be presented as a zero-length breakdown. + * Per-phase bars when captured; the Timing tab shows a single empty line otherwise. The header + * retains the total duration and response status even when no phase breakdown was captured. */ private fun netTimingSection( transaction: InspectorTransactionUi, colors: DevConsoleColors, copyText: (String) -> Unit, ): InspectorDetailSectionSpec { - val duration = transaction.durationMs val phaseStats = timingPhaseStats(transaction.timingPhases, colors) val body = - when { - phaseStats.isNotEmpty() -> InspectorDetailSectionBody.Bars(phaseStats) - transaction.statusCode == null && duration != null -> - InspectorDetailSectionBody.Empty("Timed out after $duration ms with no response.") - transaction.statusCode == null -> - InspectorDetailSectionBody.Empty("Timed out — no response received.") - duration != null -> - InspectorDetailSectionBody.Empty( - "Per-phase timing is not captured on device. Total duration: $duration ms.", - ) - else -> InspectorDetailSectionBody.Empty("Per-phase timing is not captured on device.") + if (phaseStats.isNotEmpty()) { + InspectorDetailSectionBody.Bars(phaseStats) + } else { + InspectorDetailSectionBody.Empty("No timing captured") } val onCopy = phaseStats.takeIf { it.isNotEmpty() }?.let { stats -> @@ -127,6 +97,7 @@ private fun netTimingSection( body, copyDescription = "Copy timing breakdown", onCopy = onCopy, + tab = InspectorDetailTab.TIMING, ) } @@ -175,13 +146,19 @@ private fun netGeneralEntries( ): List = buildList { val url = transaction.url.ifBlank { "https://${transaction.host}${transaction.pathWithQuery()}" } - add(InspectorKeyValue("url", url)) - add(InspectorKeyValue("method", transaction.method)) - add(InspectorKeyValue("status", transaction.statusCode?.toString() ?: "no response received", statusColor)) + add(InspectorKeyValue("URL", url)) + add(InspectorKeyValue("Host", transaction.host)) + add(InspectorKeyValue("Method", transaction.method)) + add(InspectorKeyValue("Status", transaction.statusCode?.toString() ?: "no response received", statusColor)) + transaction.responseHeaders.entries + .firstOrNull { it.key.equals("content-length", ignoreCase = true) } + ?.value + ?.toLongOrNull() + ?.let { add(InspectorKeyValue("Size", formatByteSize(it))) } if (transaction.isMocked) { val ruleId = transaction.mockRuleId ?: "unknown" val diffSuffix = mockDiffNoticeSuffix(mockDiff).orEmpty() - add(InspectorKeyValue("source", "mock rule $ruleId$diffSuffix", colors.put)) + add(InspectorKeyValue("source", "mock rule $ruleId$diffSuffix", colors.warn)) } transaction.error?.let { add(InspectorKeyValue("error", it, colors.error)) } } @@ -211,7 +188,7 @@ private fun netBodySections( colors, copyText, "Copy request payload", - ), + ).copy(tab = InspectorDetailTab.REQUEST), textPreviewSection( InspectorExchangeSection.SECONDARY_BODY.key, "Response body", @@ -225,7 +202,7 @@ private fun netBodySections( // exists to compare what a mock *served* against what the transaction it was created // from originally returned (contract: "response-body JSON viewer"). jsonHighlightPaths = mockDiff?.highlightedPaths ?: emptySet(), - ), + ).copy(tab = InspectorDetailTab.RESPONSE), ) } @@ -241,49 +218,37 @@ private fun netSections( val requestHeadersBody = headerRowsBody(transaction.requestHeaders, colors) val responseHeadersBody = headerRowsBody(transaction.responseHeaders, colors) return listOf( + responseSection, InspectorDetailSectionSpec( - "general", - "General", - InspectorDetailSectionBody.KeyValues(generalEntries), - copyDescription = "Copy general info", - onCopy = { copyText(generalEntries.toCopyText()) }, + InspectorExchangeSection.SECONDARY_HEADERS.key, + InspectorExchangeSection.SECONDARY_HEADERS.networkLabel, + responseHeadersBody, + copyDescription = "Copy response headers", + onCopy = keyValuesCopyAction(responseHeadersBody.entries, copyText), + tab = InspectorDetailTab.RESPONSE, ), + requestSection, InspectorDetailSectionSpec( InspectorExchangeSection.PRIMARY_HEADERS.key, InspectorExchangeSection.PRIMARY_HEADERS.networkLabel, requestHeadersBody, copyDescription = "Copy request headers", onCopy = keyValuesCopyAction(requestHeadersBody.entries, copyText), + tab = InspectorDetailTab.REQUEST, ), - requestSection, InspectorDetailSectionSpec( - InspectorExchangeSection.SECONDARY_HEADERS.key, - InspectorExchangeSection.SECONDARY_HEADERS.networkLabel, - responseHeadersBody, - copyDescription = "Copy response headers", - onCopy = keyValuesCopyAction(responseHeadersBody.entries, copyText), + "general", + "General", + InspectorDetailSectionBody.KeyValues(generalEntries), + copyDescription = "Copy general info", + onCopy = { copyText(generalEntries.toCopyText()) }, ), - responseSection, - netTimingSection(transaction, colors, copyText), netRedactionsSection(transaction, colors, copyText), + netTimingSection(transaction, colors, copyText), ) } -/** - * Mock-from-capture as the primary action, cURL beside it. - * - * Mocking takes the labelled 2:1 slot because it is the one action here that changes what the host - * app receives on its next call; flagging, which only files the capture, moved to the header. An - * already-mocked transaction shows the armed treatment (signal-soft on signal, "Unmock this - * response") the flag button used to carry, so the state stays readable from the button itself. - * - * "Mock this response" is shown regardless of the mocks capability for an unmocked transaction -- - * Save on the sheet it opens dispatches UpsertMockRule, which already gates and shows a blocked - * toast, the same pattern the Control screen's own mock affordances use. [onMockAction] is `null` - * entirely when this transaction is already mocked but its rule id is unknown: a mock/unmock button - * with no rule to act on would be dead chrome, and the footer falls back to cURL alone rather than - * showing a disabled primary. - */ +/** Mock/unmock and cURL retain their callbacks in the detail action panel. */ private fun netFooterActions( transaction: InspectorTransactionUi, colors: DevConsoleColors, @@ -308,7 +273,7 @@ private fun netFooterActions( } add( InspectorFooterAction( - label = "cURL", + label = "Copy as cURL", onClick = { copyText(transaction.toCurlCommand()) }, weight = 1f, icon = { @@ -350,19 +315,22 @@ internal fun netDetailContent( } val (leadColor, leadBg) = methodTint(transaction.method, colors) val statusColor = statusTint(transaction.statusCode, colors) - val timingSubtitle = - when { - transaction.statusCode == null -> "timeout" - transaction.durationMs != null -> "${transaction.durationMs} ms" - else -> transaction.host - } - // Promoted to the header rather than requiring "General" to be expanded to notice a capture was - // mocked -- parity with the web dashboard's header-level "MOCK RULE …". val subtitle = - if (transaction.isMocked) { - "$timingSubtitle · MOCK RULE ${transaction.mockRuleId ?: "unknown"}" - } else { - timingSubtitle + buildList { + httpStatusDescription(transaction.statusCode).takeIf { it.isNotEmpty() }?.let { add(it) } + transaction.durationMs?.let { add("$it ms") } + if (transaction.startedAtEpochMs > 0) add(formatCaptureClockTime(transaction.startedAtEpochMs)) + }.joinToString(" · ") + val notices = + buildList { + if (transaction.isMocked) { + add("Mock rule ${transaction.mockRuleId ?: "unknown"}${mockDiffNoticeSuffix(mockDiff).orEmpty()}") + } + val redactedCount = + (transaction.requestHeaders.values + transaction.responseHeaders.values).count { + it.looksRedacted() + } + if (redactedCount > 0) add("$redactedCount header fields masked on device") } return ObserveDetailContent( header = @@ -371,16 +339,18 @@ internal fun netDetailContent( leadText = methodLeadText(transaction.method), leadColor = leadColor, leadContainerColor = leadBg, - title = transaction.host + transaction.path, + title = "${transaction.method} ${transaction.pathWithQuery()}", subtitle = subtitle, status = transaction.statusCode?.toString() ?: "ERR", statusColor = statusColor, actions = netHeaderActions(transaction, colors, shareText, isFlagged, onToggleFlag), + notices = notices, ), sections = netSections(transaction, colors, statusColor, copyText, mockDiff), - // Request payload + Response body both open by default -- - // an operator debugging a transaction usually needs to compare both sides at a glance. - initiallyOpenSectionKeys = InspectorExchangeSection.keysOf(InspectorExchangeSection.defaultSearchScope), + // Both bodies stay expanded when moving between Response and Request. + initiallyOpenSectionKeys = + InspectorExchangeSection.keysOf(InspectorExchangeSection.defaultSearchScope) + + setOf("general", "timing"), footerActions = netFooterActions(transaction, colors, onMockAction, copyText), searchOptions = NetworkDetailSearchOptions, ) diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObservePushDetail.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObservePushDetail.kt index 528cf20..27d8982 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObservePushDetail.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObservePushDetail.kt @@ -59,6 +59,7 @@ private fun pushSections( payloadBody, copyDescription = "Copy payload", onCopy = keyValuesCopyAction(payloadEntries.orEmpty(), copyText), + tab = InspectorDetailTab.PAYLOAD, ), InspectorDetailSectionSpec( InspectorExchangeSection.SECONDARY_HEADERS.key, @@ -111,7 +112,7 @@ internal fun pushDetailContent( copyText: (String) -> Unit, shareText: (String, String) -> Unit, ): ObserveDetailContent { - val leadColor = if (push.simulated) colors.warn else colors.signal + val leadColor = if (push.simulated) colors.warn else colors.ink val leadBg = if (push.simulated) colors.warnSoft else colors.signalSoft val title = push.dataPreview["title"] ?: push.messageId ?: "Push notification" val pushJson = pushToJsonSnippet(push) @@ -125,16 +126,11 @@ internal fun pushDetailContent( leadColor = leadColor, leadContainerColor = leadBg, title = title, - subtitle = "${push.messageId ?: "no id"} · $whenLabel", - status = pushLifecycleShortLabel(push.lifecycle), + subtitle = "${push.provider} · $whenLabel", + status = "", statusColor = colors.muted, actions = listOf( - InspectorTopAction( - contentDescription = "Copy push payload", - onClick = { copyText(payloadText) }, - icon = copyIconAction(colors.muted), - ), InspectorTopAction( contentDescription = "Share push as JSON", onClick = { shareText(pushJson, "Share push JSON") }, @@ -143,7 +139,8 @@ internal fun pushDetailContent( ), ), sections = pushSections(push, colors, copyText), - initiallyOpenSectionKeys = setOf(InspectorExchangeSection.PRIMARY_BODY.key), + initiallyOpenSectionKeys = + setOf("general", InspectorExchangeSection.PRIMARY_BODY.key, InspectorExchangeSection.SECONDARY_HEADERS.key), footerActions = pushFooterActions(colors, payloadText, copyText), ) } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveRemoteConfigDetail.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveRemoteConfigDetail.kt index 2fdd000..3a21b65 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveRemoteConfigDetail.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveRemoteConfigDetail.kt @@ -43,6 +43,7 @@ internal fun remoteConfigDetailContent( valueBody, copyDescription = "Copy value", onCopy = if (entry.redacted) null else ({ copyText(entry.value) }), + tab = InspectorDetailTab.VALUE, ), InspectorDetailSectionSpec( "details", diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveRemoteConfigTab.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveRemoteConfigTab.kt index 7e8c058..c407547 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveRemoteConfigTab.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveRemoteConfigTab.kt @@ -10,15 +10,19 @@ package io.devconsole.ui.compose import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp import java.util.Locale /** @@ -41,23 +45,33 @@ internal fun RemoteConfigTabContent( actions: ObserveActions, ) { val colors = DevConsoleTheme.colors - if (state.remoteConfig.isEmpty()) { - ObserveTabEmptyState("No Remote Config provider is registered for this session.") + if (state.remoteConfig.isEmpty() && !ui.searchOpen) { + ObserveTabEmptyState("No Remote Config provider is registered for this session.", EmptySpot.RemoteConfig) return } val query = ui.remoteConfigSearch.trim().lowercase(Locale.US) LazyColumn( modifier = Modifier.fillMaxSize(), - contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = 12.dp, bottom = EvidenceFabScrollClearance), + contentPadding = PaddingValues(top = 12.dp, bottom = 24.dp), ) { - stickyHeader { - InspectorSearchBar( - query = ui.remoteConfigSearch, - onQueryChange = actions.onRemoteConfigSearchChange, - placeholder = "Search key or value", - ) + if (ui.searchOpen) { + stickyHeader { + InspectorSearchBar( + query = ui.remoteConfigSearch, + onQueryChange = actions.onRemoteConfigSearchChange, + placeholder = "Search key or value", + modifier = Modifier.padding(horizontal = 16.dp), + ) + } + } + if (state.remoteConfig.isEmpty()) { + item { + ObserveTabEmptyState( + "No Remote Config provider is registered for this session.", + EmptySpot.RemoteConfig, + ) + } } - item { Spacer(Modifier.height(16.dp)) } state.remoteConfig.forEach { provider -> item(key = "rc-head-${provider.id}") { RemoteConfigHeader(provider, colors) } val shown = provider.entries.filter { it.matches(query) } @@ -69,10 +83,14 @@ internal fun RemoteConfigTabContent( provider.entries.isEmpty() -> item(key = "rc-empty-${provider.id}") { RemoteConfigEmptyNote(provider, colors) } shown.isEmpty() -> - item(key = "rc-nomatch-${provider.id}") { RemoteConfigNoMatchNote(colors) } + item(key = "rc-nomatch-${provider.id}") { RemoteConfigNoMatchNote() } else -> - items(shown, key = { "rc-${provider.id}-${it.key}" }) { entry -> - RemoteConfigRow(entry, colors) { actions.onOpenRemoteConfigDetail(provider.id, entry.key) } + itemsIndexed(shown, key = { _, entry -> "rc-${provider.id}-${entry.key}" }) { index, entry -> + RemoteConfigRow( + entry, + colors, + Modifier.groupedPanelItem(GroupPosition.of(index, shown.size)), + ) { actions.onOpenRemoteConfigDetail(provider.id, entry.key) } } } item(key = "rc-space-${provider.id}") { Spacer(Modifier.height(16.dp)) } @@ -94,8 +112,8 @@ private fun RemoteConfigHeader( Text( text = remoteConfigFetchLine(provider), modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 8.dp), - color = colors.text3, - style = MaterialTheme.typography.bodySmall, + color = colors.muted, + fontSize = 12.5.sp, ) } @@ -115,27 +133,24 @@ private fun RemoteConfigEmptyNote( } else { "No values returned by the last fetch." }, - modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 8.dp), + modifier = Modifier.fillMaxWidth().padding(start = 16.dp, end = 16.dp, bottom = 8.dp), color = colors.muted, + textAlign = TextAlign.Center, style = MaterialTheme.typography.bodySmall, ) } /** Distinct from [RemoteConfigEmptyNote]: the provider has values, the search just excluded them all. */ @Composable -private fun RemoteConfigNoMatchNote(colors: DevConsoleColors) { - Text( - text = "No key matches the current search.", - modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 8.dp), - color = colors.muted, - style = MaterialTheme.typography.bodySmall, - ) +private fun RemoteConfigNoMatchNote() { + InspectorEmptyState(EmptySpot.Search, "No key matches the current search.", spotSize = 64.dp) } @Composable private fun RemoteConfigRow( entry: InspectorRemoteConfigEntryUi, colors: DevConsoleColors, + modifier: Modifier = Modifier, onClick: () -> Unit, ) { // Only ever a preview -- a config value is a string of any length, and the full text is one tap @@ -147,13 +162,24 @@ private fun RemoteConfigRow( if (entry.truncated) append(" · truncated") } TonalListRow( - leadText = remoteConfigLeadText(entry.source), - leadColor = remoteConfigLeadColor(entry.source, colors), - leadContainerColor = remoteConfigLeadContainerColor(entry.source, colors), + leadText = entry.source, + leadColor = colors.muted, + leadContainerColor = Color.Transparent, title = entry.key, subtitle = sub, - trailValue = entry.source, - trailValueColor = if (entry.source == "remote") colors.signal else colors.muted, + trailValue = + if (entry.redacted) { + "" + } else { + formatByteSize( + entry.value + .toByteArray() + .size + .toLong(), + ) + }, + trailValueColor = colors.muted, + modifier = modifier, onClick = onClick, ) } 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 07b598c..567b843 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 @@ -20,6 +20,8 @@ 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.DropdownMenu +import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Text @@ -46,7 +48,11 @@ 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.Lifecycle +import androidx.lifecycle.compose.LifecycleStartEffect +import androidx.lifecycle.compose.LocalLifecycleOwner import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.compose.currentStateAsState import androidx.lifecycle.viewmodel.compose.viewModel import kotlinx.coroutines.launch @@ -117,6 +123,8 @@ internal data class ObserveUiState( val pushHeroCollapsed: Boolean = true, val logsHeroCollapsed: Boolean = true, val crashesHeroCollapsed: Boolean = true, + val searchOpen: Boolean = false, + val trafficFiltersOpen: Boolean = false, ) // One callback per distinct Observe interaction; bundling further would just hide the count. @@ -332,9 +340,12 @@ internal fun ObserveRoute( state.mockRules.mapTo(mutableSetOf()) { it.id }, state.flaggedTransactionIds, ) - // Live tail: re-read the capture store whenever Observe (re)enters composition; tab switches + // Live tail: re-read the capture store whenever Observe becomes started; tab switches // refresh again via the ViewModel (see selectObserveTab). - LaunchedEffect(Unit) { viewModel.dispatch(InspectorAction.Refresh) } + LifecycleStartEffect(Unit) { + viewModel.dispatch(InspectorAction.Refresh) + onStopOrDispose { } + } LaunchedEffect(ui.detailTarget, ui.mockDraft) { onDetailOverlayOpen(ui.detailTarget != null || ui.mockDraft != null) } @@ -557,8 +568,7 @@ private fun ObserveTab.title(): String = ObserveTab.PUSH -> "Push" ObserveTab.LOGS -> "Logs" ObserveTab.CRASHES -> "Crashes" - // One word, like every other tab: the row divides its width equally, so "Remote Config" - // would wrap or truncate on a phone. + // Keep the provider category short enough to scan alongside the other tabs. ObserveTab.REMOTE_CONFIG -> "Config" } @@ -576,34 +586,80 @@ internal fun ObserveScreen( modifier: Modifier = Modifier, ) { val colors = DevConsoleTheme.colors + val lifecycleState by LocalLifecycleOwner.current.lifecycle.currentStateAsState() + var searchOpenTabs by rememberSaveable { mutableStateOf(emptyList()) } + val searchOpen = state.observeTab.name in searchOpenTabs + var filtersOpen by rememberSaveable { mutableStateOf(false) } + var moreOpen by remember { mutableStateOf(false) } + val tabUi = ui.copy(searchOpen = searchOpen, trafficFiltersOpen = filtersOpen) Box(modifier = modifier.background(colors.ground)) { Column(Modifier.fillMaxSize()) { InspectorTopArea( - subLine = ui.appIdentity, + subLine = "", title = state.observeTab.title(), - // 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. - // - // 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( + InspectorTopAction( + contentDescription = "Search", + onClick = { + if (searchOpen) clearObserveSearch(state.observeTab, actions) + searchOpenTabs = + if (searchOpen) { + searchOpenTabs - state.observeTab.name + } else { + searchOpenTabs + state.observeTab.name + } + }, + icon = { InspectorGlyphIcon(InspectorGlyph.Search, null, tint = colors.muted) }, + ), + ) + if (state.observeTab == ObserveTab.TRAFFIC) { + add( + InspectorTopAction( + contentDescription = "Filter", + onClick = { filtersOpen = !filtersOpen }, + icon = { + ObserveGlyphIcon( + ObserveGlyph.Filter, + null, + tint = + if (filtersOpen || + ui.trafficChip != "all" + ) { + colors.signal + } else { + colors.muted + }, + ) + }, + ), + ) } - add(themeToggleTopAction(actions.onToggleTheme)) + add( + InspectorTopAction( + contentDescription = "More options", + onClick = { moreOpen = true }, + icon = { + Box { + DevConsoleIcon( + R.drawable.devconsole_ic_more_horizontal, + contentDescription = null, + modifier = Modifier, + tint = colors.muted, + size = 20.dp, + ) + ObserveOverflowMenu(state, ui, actions, moreOpen) { moreOpen = false } + } + }, + ), + ) }, ) previousCrashedSession(state.sessions)?.let { session -> PreviousRunCrashedBanner(session = session, onViewCrash = { actions.onViewPreviousCrash(session.id) }) } - // Only categories the host enabled at init get a tab at all -- see - // InspectorState.visibleObserveTabs for the gating rule (SOCKETS covers both plain - // WebSocket and MQTT capture). - val visibleTabs = state.visibleObserveTabs() + val visibleTabs = ObserveTab.entries.toList() InspectorTabRow( tabs = visibleTabs.map { tab -> @@ -613,16 +669,11 @@ internal fun ObserveScreen( Box(Modifier.weight(1f)) { when { !state.available -> ObserveUnavailableNotice() - // Defensive: InspectorViewModel.applySnapshot already snaps observeTab back onto - // a visible tab the moment its category is disabled, but a stray selection this - // screen didn't cause (e.g. a `SelectObserveTab` dispatched before that snap runs) - // must render nothing rather than a hidden tab's content. - state.observeTab !in visibleTabs -> ObserveTabEmptyState("This section is not available.") - else -> ObserveTabPager(state.observeTab, visibleTabs, state, ui, actions) + else -> ObserveTabPager(state.observeTab, visibleTabs, state, tabUi, actions) } } } - if (ui.clearTransactionsPending) { + if (ui.clearTransactionsPending && lifecycleState.isAtLeast(Lifecycle.State.STARTED)) { ClearTransactionsConfirmDialog( captureCount = state.transactions.size, onConfirm = actions.onConfirmClearTransactions, @@ -640,6 +691,63 @@ internal fun ObserveScreen( } } +private fun clearObserveSearch( + tab: ObserveTab, + actions: ObserveActions, +) { + when (tab) { + ObserveTab.TRAFFIC -> actions.onTrafficSearchChange("") + ObserveTab.SOCKETS -> actions.onSocketsSearchChange("") + ObserveTab.PUSH -> actions.onPushSearchChange("") + ObserveTab.LOGS -> actions.onLogsSearchChange("") + ObserveTab.CRASHES -> actions.onCrashesSearchChange("") + ObserveTab.REMOTE_CONFIG -> actions.onRemoteConfigSearchChange("") + } +} + +@Composable +private fun ObserveOverflowMenu( + state: InspectorState, + ui: ObserveUiState, + actions: ObserveActions, + expanded: Boolean, + onDismiss: () -> Unit, +) { + val lifecycleState by LocalLifecycleOwner.current.lifecycle.currentStateAsState() + val evidenceCount = ui.flaggedTransactionIds.size + ui.flaggedCrashIds.size + DropdownMenu( + expanded = expanded && lifecycleState.isAtLeast(Lifecycle.State.STARTED), + onDismissRequest = onDismiss, + ) { + DropdownMenuItem( + text = { Text(if (evidenceCount == 0) "Evidence tray" else "Evidence · $evidenceCount") }, + onClick = { + onDismiss() + actions.onOpenEvidenceTray() + }, + ) + if (state.observeTab == ObserveTab.TRAFFIC) { + DropdownMenuItem( + text = { Text("Clear captures") }, + onClick = { + onDismiss() + actions.onRequestClearTransactions() + }, + enabled = state.transactions.isNotEmpty(), + modifier = Modifier.semantics { contentDescription = "Clear captured requests" }, + ) + } + DropdownMenuItem( + text = { Text("Switch theme") }, + onClick = { + onDismiss() + actions.onToggleTheme() + }, + modifier = Modifier.semantics { contentDescription = "Toggle theme" }, + ) + } +} + /** * 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 diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveSignals.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveSignals.kt index 24fa3ec..9580e78 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveSignals.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveSignals.kt @@ -30,7 +30,7 @@ import androidx.compose.ui.unit.dp import io.devconsole.api.CaptureCategory import java.util.Locale -/** Sockets tab: open-connection hero + a flattened, newest-first "Recent frames" list. */ +/** Sockets tab: an error notice and frames in one grouped panel. */ @Composable internal fun SocketsTabContent( state: InspectorState, @@ -38,8 +38,8 @@ internal fun SocketsTabContent( actions: ObserveActions, ) { val colors = DevConsoleTheme.colors - if (state.sockets.isEmpty()) { - ObserveTabEmptyState(state.socketsEmptyStateMessage()) + if (state.sockets.isEmpty() && !ui.searchOpen) { + ObserveTabEmptyState(state.socketsEmptyStateMessage(), EmptySpot.Sockets) return } val recentFrames = rememberRecentFrames(state.sockets) @@ -67,27 +67,30 @@ internal fun SocketsTabContent( LazyColumn( modifier = Modifier.fillMaxSize(), - // 16dp start/end, 12dp top, extra bottom clearance for every Observe tab's scroll container. - contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = 12.dp, bottom = EvidenceFabScrollClearance), + contentPadding = PaddingValues(top = 12.dp, bottom = 24.dp), ) { - stickyHeader { - InspectorSearchBar( - query = ui.socketsSearch, - onQueryChange = actions.onSocketsSearchChange, - placeholder = "Search host, path or frames", - ) + if (ui.searchOpen) { + stickyHeader { + InspectorSearchBar( + query = ui.socketsSearch, + onQueryChange = actions.onSocketsSearchChange, + placeholder = "Search host, path or frames", + modifier = Modifier.padding(horizontal = 16.dp), + ) + } + } + if (state.sockets.any { it.error != null }) { + item { SocketsHero(state.sockets, ui, actions, colors) } + item { Spacer(Modifier.height(12.dp)) } } - item { Spacer(Modifier.height(16.dp)) } - item { SocketsHero(state.sockets, ui, actions, colors) } - item { Spacer(Modifier.height(16.dp)) } - item { GroupLabel("Recent frames") } - itemsIndexed(searchedIndices, key = { _, index -> frameKeys[index] }) { _, index -> + if (searchedIndices.isEmpty()) item { ObserveTabEmptyState("No matching frames.", EmptySpot.Search) } + itemsIndexed(searchedIndices, key = { _, index -> frameKeys[index] }) { rowIndex, index -> val (socket, frame) = recentFrames[index] SocketFrameRow( socket = socket, frame = frame, colors = colors, - modifier = Modifier.animateItem(), + modifier = Modifier.animateItem().groupedPanelItem(GroupPosition.of(rowIndex, searchedIndices.size)), isArrival = frameKeys[index] in arrivals, onClick = { actions.onOpenFrameDetail(socket, frame) }, ) @@ -102,19 +105,18 @@ private fun SocketsHero( actions: ObserveActions, colors: DevConsoleColors, ) { - val openCount = sockets.count { it.state == "OPEN" } + val errorCount = sockets.count { it.error != null } if (ui.socketsHeroCollapsed) { HeroBar( - value = openCount.toString(), - label = "of ${sockets.size} connections open", + value = errorCount.toString(), + label = "connections in error", onExpand = actions.onToggleSocketsHero, - valueColor = colors.signal, - labelColor = colors.text3, + valueColor = colors.error, + labelColor = colors.error, ) return } val loudest = sockets.maxByOrNull { it.receivedCount } - val errorCount = sockets.count { it.error != null } val sub = buildString { if (loudest != null && loudest.receivedCount > 0) { @@ -128,12 +130,12 @@ private fun SocketsHero( } } HeroCard( - label = "Open connections", - value = openCount.toString(), + label = "Connections in error", + value = errorCount.toString(), valueSuffix = "of ${sockets.size}", subtitle = sub, labelColor = colors.text3, - valueColor = colors.signal, + valueColor = colors.error, onCollapse = actions.onToggleSocketsHero, ) } @@ -149,8 +151,6 @@ private fun SocketFrameRow( isArrival: Boolean = false, ) { val received = frame.direction == "RECEIVED" - val leadColor = if (received) colors.put else colors.signal - val leadBg = if (received) colors.putSoft else colors.signalSoft val protocolBadge = socket.protocolBadge() val path = socket.url.replace(Regex("^wss?://[^/]+"), "").ifEmpty { socket.url } // An MQTT frame's topic is what an operator scanning this list actually wants to see -- the @@ -159,9 +159,9 @@ private fun SocketFrameRow( Column(modifier = modifier.fillMaxWidth()) { TonalListRow( isArrival = isArrival, - leadText = if (received) "↓" else "↑", - leadColor = leadColor, - leadContainerColor = leadBg, + leadText = if (received) "RECV" else "SEND", + leadColor = colors.muted, + leadContainerColor = Color.Transparent, title = title, subtitle = "$protocolBadge · ${frame.frameType} · ${frame.preview.orEmpty().take(34)}", trailValue = socketFrameSizeLabel(frame), @@ -170,10 +170,6 @@ private fun SocketFrameRow( containerColor = Color.Transparent, onClick = onClick, ) - androidx.compose.material3.HorizontalDivider( - modifier = Modifier.padding(start = 76.dp), - color = colors.line, - ) } } @@ -192,7 +188,7 @@ private fun InspectorState.socketsEmptyStateMessage(): String = "No WebSocket connections captured yet." } -/** Push tab: delivered-count hero + a lifecycle-ordered event list. */ +/** Push tab: a failure notice and delivery events in one grouped panel. */ @Composable internal fun PushTabContent( state: InspectorState, @@ -200,8 +196,8 @@ internal fun PushTabContent( actions: ObserveActions, ) { val colors = DevConsoleTheme.colors - if (state.pushEvents.isEmpty()) { - ObserveTabEmptyState("No push events captured yet.") + if (state.pushEvents.isEmpty() && !ui.searchOpen) { + ObserveTabEmptyState("No push events captured yet.", EmptySpot.Push) return } // Push events have no id of their own either -- key on (messageId or "no-id", receivedAt), same @@ -228,26 +224,29 @@ internal fun PushTabContent( LazyColumn( modifier = Modifier.fillMaxSize(), - // 16dp start/end, 12dp top, extra bottom clearance for every Observe tab's scroll container. - contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = 12.dp, bottom = EvidenceFabScrollClearance), + contentPadding = PaddingValues(top = 12.dp, bottom = 24.dp), ) { - stickyHeader { - InspectorSearchBar( - query = ui.pushSearch, - onQueryChange = actions.onPushSearchChange, - placeholder = "Search provider, message id or data", - ) + if (ui.searchOpen) { + stickyHeader { + InspectorSearchBar( + query = ui.pushSearch, + onQueryChange = actions.onPushSearchChange, + placeholder = "Search provider, message id or data", + modifier = Modifier.padding(horizontal = 16.dp), + ) + } + } + if (state.pushEvents.any { it.hasPushFailure() }) { + item { PushHero(state.pushEvents, ui, actions, colors) } + item { Spacer(Modifier.height(12.dp)) } } - item { Spacer(Modifier.height(16.dp)) } - item { PushHero(state.pushEvents, ui, actions, colors) } - item { Spacer(Modifier.height(16.dp)) } - item { GroupLabel("Lifecycle") } - itemsIndexed(searchedIndices, key = { _, index -> pushKeys[index] }) { _, index -> + if (searchedIndices.isEmpty()) item { ObserveTabEmptyState("No matching push events.", EmptySpot.Search) } + itemsIndexed(searchedIndices, key = { _, index -> pushKeys[index] }) { rowIndex, index -> val push = state.pushEvents[index] PushRow( push = push, colors = colors, - modifier = Modifier.animateItem(), + modifier = Modifier.animateItem().groupedPanelItem(GroupPosition.of(rowIndex, searchedIndices.size)), isArrival = pushKeys[index] in arrivals, onClick = { actions.onOpenPushDetail(push) }, ) @@ -262,35 +261,31 @@ private fun PushHero( actions: ObserveActions, colors: DevConsoleColors, ) { + val failedCount = pushEvents.count { it.hasPushFailure() } if (ui.pushHeroCollapsed) { HeroBar( - value = pushEvents.size.toString(), - label = "push events delivered", + value = failedCount.toString(), + label = "push events failed", onExpand = actions.onTogglePushHero, - valueColor = colors.ink, - labelColor = colors.text3, + valueColor = colors.error, + labelColor = colors.error, ) return } - val simulatedCount = pushEvents.count { it.simulated } - val sub = - if (simulatedCount > 0) { - val pronoun = if (simulatedCount == 1) "it appears" else "they appear" - "$simulatedCount simulated from the dashboard — labelled everywhere $pronoun." - } else { - "All delivered from a real push provider this session." - } HeroCard( - label = "Delivered this session", - value = pushEvents.size.toString(), + label = "Push failures", + value = failedCount.toString(), valueSuffix = "events", - subtitle = sub, - labelColor = colors.text3, - valueColor = colors.ink, + subtitle = "push events failed", + labelColor = colors.error, + valueColor = colors.error, onCollapse = actions.onTogglePushHero, ) } +private fun InspectorPushUi.hasPushFailure(): Boolean = + lifecycle.contains("ERROR", ignoreCase = true) || lifecycle.contains("FAIL", ignoreCase = true) + @Composable private fun PushRow( push: InspectorPushUi, @@ -299,27 +294,22 @@ private fun PushRow( modifier: Modifier = Modifier, isArrival: Boolean = false, ) { - val leadColor = if (push.simulated) colors.warn else colors.signal - val leadBg = if (push.simulated) colors.warnSoft else colors.signalSoft val title = push.dataPreview["title"] ?: push.messageId ?: "Push notification" Column(modifier = modifier.fillMaxWidth()) { TonalListRow( isArrival = isArrival, - leadText = push.provider.uppercase(Locale.US), - leadColor = leadColor, - leadContainerColor = leadBg, + leadText = "MSG", + leadColor = colors.muted, + leadContainerColor = Color.Transparent, title = title, - subtitle = "${push.messageId ?: "no id"} · ${if (push.simulated) "simulated" else "captured"}", - trailValue = pushLifecycleShortLabel(push.lifecycle), - trailValueColor = colors.muted, - trailSubtitle = formatCaptureClockTimeShort(push.receivedAtEpochMs), + subtitle = + "${push.provider} · ${pushLifecycleShortLabel(push.lifecycle)}" + + if (push.simulated) " · simulated" else "", + trailValue = formatCaptureClockTimeShort(push.receivedAtEpochMs), + trailValueColor = if (push.hasPushFailure()) colors.error else colors.muted, containerColor = Color.Transparent, onClick = onClick, ) - androidx.compose.material3.HorizontalDivider( - modifier = Modifier.padding(start = 76.dp), - color = colors.line, - ) } } @@ -331,8 +321,8 @@ internal fun LogsTabContent( actions: ObserveActions, ) { val colors = DevConsoleTheme.colors - if (state.logs.isEmpty()) { - ObserveTabEmptyState("No logs, crashes, or ANRs captured yet.") + if (state.logs.isEmpty() && !ui.searchOpen) { + ObserveTabEmptyState("No logs captured yet.", EmptySpot.Logs) return } val searched = @@ -353,25 +343,28 @@ internal fun LogsTabContent( LazyColumn( modifier = Modifier.fillMaxSize(), - // 16dp start/end, 12dp top, extra bottom clearance for every Observe tab's scroll container. - contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = 12.dp, bottom = EvidenceFabScrollClearance), + contentPadding = PaddingValues(top = 12.dp, bottom = 24.dp), ) { - stickyHeader { - InspectorSearchBar( - query = ui.logsSearch, - onQueryChange = actions.onLogsSearchChange, - placeholder = "Search message, source or detail", - ) + if (ui.searchOpen) { + stickyHeader { + InspectorSearchBar( + query = ui.logsSearch, + onQueryChange = actions.onLogsSearchChange, + placeholder = "Search message, source or detail", + modifier = Modifier.padding(horizontal = 16.dp), + ) + } + } + if (state.logs.any { isWarnOrErrorLevel(it.kind) }) { + item { LogsHero(state.logs, ui, actions, colors) } + item { Spacer(Modifier.height(12.dp)) } } - item { Spacer(Modifier.height(16.dp)) } - item { LogsHero(state.logs, ui, actions, colors) } - item { Spacer(Modifier.height(16.dp)) } - item { GroupLabel("Newest first") } - itemsIndexed(rowsNewestFirst, key = { _, log -> log.id }) { _, log -> + if (rowsNewestFirst.isEmpty()) item { ObserveTabEmptyState("No matching logs.", EmptySpot.Search) } + itemsIndexed(rowsNewestFirst, key = { _, log -> log.id }) { index, log -> LogRow( log = log, colors = colors, - modifier = Modifier.animateItem(), + modifier = Modifier.animateItem().groupedPanelItem(GroupPosition.of(index, rowsNewestFirst.size)), isArrival = log.id in arrivals, onClick = { actions.onOpenLogDetail(log.id) }, ) @@ -430,30 +423,28 @@ private fun LogRow( modifier: Modifier = Modifier, isArrival: Boolean = false, ) { - val (leadColor, leadBg) = logLevelTint(log.kind, colors) Column(modifier = modifier.fillMaxWidth()) { TonalListRow( isArrival = isArrival, - leadText = logLevelShortLabel(log.kind), - leadColor = leadColor, - leadContainerColor = leadBg, + leadText = log.kind.take(1).uppercase(Locale.US), + leadColor = colors.muted, + leadContainerColor = Color.Transparent, title = if (log.summary.length > 40) log.summary.take(40) + "…" else log.summary, subtitle = "${log.source} · ${log.kind}", trailValue = formatCaptureClockTime(log.timestampEpochMs), - trailValueColor = colors.muted, + trailValueColor = if (isWarnOrErrorLevel(log.kind)) logLevelTint(log.kind, colors).first else colors.muted, containerColor = Color.Transparent, onClick = onClick, ) - androidx.compose.material3.HorizontalDivider( - modifier = Modifier.padding(start = 76.dp), - color = colors.line, - ) } } @Composable -internal fun ObserveTabEmptyState(message: String) { +internal fun ObserveTabEmptyState( + message: String, + spot: EmptySpot? = null, +) { Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { - Text(message, color = DevConsoleTheme.colors.muted) + if (spot != null) InspectorEmptyState(spot, message) else Text(message, color = DevConsoleTheme.colors.muted) } } 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 8fcc60e..3945770 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 @@ -23,7 +23,7 @@ import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.selection.toggleable import androidx.compose.foundation.shape.CircleShape @@ -108,7 +108,7 @@ internal fun TrafficTabContent( ui: ObserveUiState, actions: ObserveActions, ) { - if (state.transactions.isEmpty()) { + if (state.transactions.isEmpty() && !ui.searchOpen && !ui.trafficFiltersOpen) { TrafficEmptyState() return } @@ -121,15 +121,7 @@ internal fun TrafficTabContent( val selectionModeActive = state.selectedTransactionIds.isNotEmpty() BackHandler(enabled = selectionModeActive, onBack = actions.onClearTransactionSelection) - Box(Modifier.fillMaxSize()) { - TrafficList(stats, ui, actions, colors, TrafficSelection(state.selectedTransactionIds, selectionModeActive)) - EvidenceFab( - label = - if (ui.flaggedTransactionIds.isEmpty()) "Flag" else "Evidence · ${ui.flaggedTransactionIds.size}", - onClick = actions.onOpenEvidenceTray, - modifier = Modifier.align(Alignment.BottomEnd).padding(end = 16.dp, bottom = 16.dp), - ) - } + TrafficList(stats, ui, actions, colors, TrafficSelection(state.selectedTransactionIds, selectionModeActive)) } /** The traffic tab's selection state, bundled so [TrafficList] doesn't grow a parameter per field. */ @@ -149,43 +141,48 @@ private fun TrafficList( val arrivals = rememberArrivals(stats.rowsNewestFirst.map { it.id }) LazyColumn( modifier = Modifier.fillMaxSize(), - contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = 12.dp, bottom = EvidenceFabScrollClearance), + contentPadding = PaddingValues(top = 12.dp, bottom = 24.dp), ) { - stickyHeader { - if (selection.modeActive) { - TrafficSelectionBar( - selectedCount = selection.ids.size, - actions = - TrafficSelectionActions( - onSelectAllFiltered = { - actions.onSelectAllFilteredTransactions( - stats.rowsNewestFirst.mapTo(mutableSetOf()) { it.id }, - ) - }, - onExportHar = actions.onExportHar, - onExportPostman = actions.onExportPostman, - onClear = actions.onClearTransactionSelection, - ), - colors = colors, - ) - } else { - InspectorSearchBar( - query = ui.trafficSearch, - onQueryChange = actions.onTrafficSearchChange, - placeholder = "Search path, host or payload", - ) + if (selection.modeActive || ui.searchOpen) { + stickyHeader { + Column(Modifier.padding(horizontal = 16.dp)) { + if (selection.modeActive) { + TrafficSelectionBar( + selectedCount = selection.ids.size, + actions = + TrafficSelectionActions( + onSelectAllFiltered = { + actions.onSelectAllFilteredTransactions( + stats.rowsNewestFirst.mapTo(mutableSetOf()) { it.id }, + ) + }, + onExportHar = actions.onExportHar, + onExportPostman = actions.onExportPostman, + onClear = actions.onClearTransactionSelection, + ), + colors = colors, + ) + } + if (ui.searchOpen) { + InspectorSearchBar( + query = ui.trafficSearch, + onQueryChange = actions.onTrafficSearchChange, + placeholder = "Search path, host or payload", + ) + } + } } } - item { Spacer(Modifier.height(16.dp)) } - item { TrafficHero(stats, ui, colors, actions) } - item { Spacer(Modifier.height(16.dp)) } - item { TrafficChips(stats, ui.trafficChip, actions) } - item { Spacer(Modifier.height(16.dp)) } - item { - val suffix = if (ui.trafficChip == "all") " captures · newest first" else " matching · newest first" - GroupLabel("${stats.rowsNewestFirst.size}$suffix") + if (stats.failCount > 0) { + item { TrafficHero(stats, ui, colors, actions) } + item { Spacer(Modifier.height(12.dp)) } + } + if (ui.trafficFiltersOpen) { + item { TrafficChips(stats, ui.trafficChip, actions) } + item { Spacer(Modifier.height(12.dp)) } } - items(stats.rowsNewestFirst, key = { it.id }) { transaction -> + if (stats.rowsNewestFirst.isEmpty()) item { ObserveTabEmptyState("No matching captures.", EmptySpot.Search) } + itemsIndexed(stats.rowsNewestFirst, key = { _, transaction -> transaction.id }) { index, transaction -> TrafficRow( transaction = transaction, isFlagged = transaction.id in ui.flaggedTransactionIds, @@ -194,7 +191,7 @@ private fun TrafficList( colors = colors, actions = actions, isArrival = transaction.id in arrivals, - modifier = Modifier.animateItem(), + modifier = Modifier.animateItem().groupedPanelItem(GroupPosition.of(index, stats.rowsNewestFirst.size)), ) } } @@ -273,7 +270,7 @@ private fun TrafficSelectionActionRow( InspectorPillButton( label = "HAR", onClick = actions.onExportHar, - containerColor = colors.put, + containerColor = colors.signal, contentColor = colors.ground, labelFontSize = 12.5.sp, icon = { ExportPillIcon(colors) }, @@ -281,7 +278,7 @@ private fun TrafficSelectionActionRow( InspectorPillButton( label = "Postman", onClick = actions.onExportPostman, - containerColor = colors.put, + containerColor = colors.signal, contentColor = colors.ground, labelFontSize = 12.5.sp, icon = { ExportPillIcon(colors) }, @@ -324,7 +321,7 @@ private fun TrafficHero( if (ui.trafficHeroCollapsed) { HeroBar( value = stats.failCount.toString(), - label = "of ${stats.total} requests failing", + label = "requests failing", onExpand = actions.onToggleTrafficHero, valueColor = if (failing) colors.error else colors.ink, labelColor = if (failing) colors.error else colors.text3, @@ -371,14 +368,12 @@ private fun TrafficRow( modifier: Modifier = Modifier, isArrival: Boolean = false, ) { - val (leadColor, leadBg) = methodTint(transaction.method, colors) - val mockedSuffix = if (transaction.isMocked) " · mocked" else "" Column(modifier = modifier.fillMaxWidth()) { TonalListRow( isArrival = isArrival, - leadText = methodLeadText(transaction.method), - leadColor = leadColor, - leadContainerColor = leadBg, + leadText = transaction.method, + leadColor = colors.muted, + leadContainerColor = Color.Transparent, // breakingAnywhere: without it the line breaker leaves the first line half empty and // moves the whole query down (see the helper's own note). title = transaction.pathWithQuery().breakingAnywhere(), @@ -386,12 +381,11 @@ private fun TrafficRow( // runs past two on a phone, and the part that gets cut is the query -- the very thing // that tells two captures of the same endpoint apart. titleMaxLines = 4, - subtitle = "${transaction.host} · ${formatCaptureClockTime(transaction.startedAtEpochMs)}$mockedSuffix", + subtitle = if (transaction.isMocked) "mocked" else "", trailValue = transaction.statusCode?.toString() ?: "ERR", trailValueColor = statusTint(transaction.statusCode, colors), trailSubtitle = when { - transaction.statusCode == null -> "timeout" transaction.durationMs != null -> "${transaction.durationMs} ms" else -> null }, @@ -399,7 +393,7 @@ private fun TrafficRow( if (isSelected) { colors.surface2 } else if (isFlagged) { - colors.signalSoft + colors.surface2 } else { Color.Transparent }, @@ -431,10 +425,6 @@ private fun TrafficRow( // tap/long-press action and the checkbox's toggle independently. mergeDescendants = !selectionModeActive, ) - androidx.compose.material3.HorizontalDivider( - modifier = Modifier.padding(start = 76.dp), - color = colors.line, - ) } } @@ -470,9 +460,6 @@ private fun TrafficRowSelectionCheckbox( @Composable private fun TrafficEmptyState() { Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { - Text( - "No traffic captured yet.", - color = DevConsoleTheme.colors.muted, - ) + InspectorEmptyState(EmptySpot.Traffic, "No traffic captured yet.") } } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorState.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorState.kt index fa04948..e6549c4 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorState.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorState.kt @@ -71,6 +71,8 @@ data class InspectorState( * caller (tab row, bottom nav, section gating) reads the same gate instead of re-deriving it. */ val captureCategories: Set = CaptureCategory.all(), + /** Mirrors [InspectorSnapshot.redactionEnabled]. */ + val redactionEnabled: Boolean = false, ) /** True when [category] is enabled for this session; the one-line building block every gate below composes. */ diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorUrlCard.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorUrlCard.kt index 63d3458..de81e6f 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorUrlCard.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorUrlCard.kt @@ -13,6 +13,7 @@ import androidx.compose.animation.core.infiniteRepeatable import androidx.compose.animation.core.rememberInfiniteTransition import androidx.compose.animation.core.tween import androidx.compose.foundation.background +import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column @@ -20,9 +21,9 @@ import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.CircleShape -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Surface +import androidx.compose.material3.IconButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue @@ -33,14 +34,15 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp /** - * One 48dp pill action in an [InspectorUrlCard]'s action row. [flex] defaults to 1f. - * Colors have no default: a data class constructor is not `@Composable`, so it cannot read - * [DevConsoleTheme.colors] itself -- every call site supplies its own tint. + * One labelled URL action. The legacy color and flex fields preserve the shared caller contract; + * grouped panels render these actions as compact icon buttons. */ internal data class InspectorUrlAction( val label: String, @@ -52,13 +54,8 @@ internal data class InspectorUrlAction( ) /** - * A surface-2 block with a status dot + uppercase label, a mono 16sp URL, a muted sub line, and a - * row of 48dp pill actions. - * - * The one place a filled container survives the flat redesign, and deliberately: this is the - * dashboard address a QA engineer is meant to read off the device and type into a laptop, so it - * earns a surface of its own instead of dissolving into the rules around it. Shaped by - * [DevConsoleShapes]' `large` like every other filled block on the surface. + * Inline URL readout and compact icon actions, suitable for embedding in a grouped panel. + * The optional label and subtitle preserve existing callers, without introducing a nested card. */ @Suppress("LongParameterList") // Every field varies per screen. @Composable @@ -74,52 +71,47 @@ internal fun InspectorUrlCard( /** `true` while the session this card describes is live or still settling -- see [Box8Dot]. */ dotPulsing: Boolean = false, ) { - Surface( - modifier = modifier.fillMaxWidth(), - shape = MaterialTheme.shapes.large, - color = DevConsoleTheme.colors.surface2, - ) { - Column(modifier = Modifier.padding(16.dp)) { + Column(modifier = modifier.fillMaxWidth()) { + if (label.isNotBlank()) { Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { Box8Dot(dotColor, dotPulsing) Text( - label.uppercase(), + label, color = labelColor, style = DevConsoleType.groupLabel, modifier = Modifier.weight(1f), ) } + } + Row(verticalAlignment = Alignment.CenterVertically) { Text( url, - modifier = Modifier.padding(top = 8.dp), + modifier = Modifier.weight(1f).horizontalScroll(rememberScrollState()), color = urlColor, fontFamily = FontFamily.Monospace, - fontSize = 16.sp, + fontSize = 14.sp, + maxLines = 1, ) + actions.forEach { action -> + IconButton( + onClick = action.onClick, + modifier = Modifier.size(40.dp).semantics { contentDescription = action.label }, + ) { + if (action.icon != null) { + action.icon.invoke() + } else { + Text(action.label, color = DevConsoleTheme.colors.muted, fontSize = 12.sp) + } + } + } + } + if (subtitle.isNotBlank()) { Text( subtitle, - modifier = Modifier.padding(top = 8.dp), + modifier = Modifier.padding(top = 4.dp), color = DevConsoleTheme.colors.muted, - fontSize = 12.5.sp, + fontSize = 13.sp, ) - Row( - modifier = Modifier.fillMaxWidth().padding(top = 12.dp), - horizontalArrangement = Arrangement.spacedBy(8.dp), - ) { - actions.forEach { action -> - InspectorPillButton( - label = action.label, - onClick = action.onClick, - modifier = Modifier.weight(action.flex), - containerColor = action.containerColor, - contentColor = action.contentColor, - icon = action.icon, - // URL-card action labels run 13.5sp, smaller than the button's own - // 14.5sp default. - labelFontSize = 13.5.sp, - ) - } - } } } } 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 b5f1aaf..46c536b 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 @@ -268,6 +268,7 @@ class InspectorViewModel browser = snapshot.browser, retention = snapshot.retention, captureCategories = snapshot.captureCategories, + redactionEnabled = snapshot.redactionEnabled, ) // A category disabled mid-session (or a filter change while a now-hidden tab stayed // selected) must not strand the Observe tab row on a tab [visibleObserveTabs] no diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/qr/QrCodeView.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/qr/QrCodeView.kt index b1f498d..904feca 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/qr/QrCodeView.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/qr/QrCodeView.kt @@ -9,12 +9,18 @@ package io.devconsole.ui.compose.qr import androidx.compose.foundation.Canvas import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable -import androidx.compose.runtime.remember +import androidx.compose.runtime.getValue +import androidx.compose.runtime.produceState import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.drawWithCache import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Rect import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Path import androidx.compose.ui.unit.dp +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext private val DEFAULT_QR_SIZE = 176.dp private const val QUIET_ZONE_MODULES = 4 @@ -31,30 +37,54 @@ internal fun ConnectUrlQrCode( url: String, modifier: Modifier = Modifier, ) { - val matrix = remember(url) { QrCodeEncoder.encode(url) } ?: return - Canvas(modifier = modifier.size(DEFAULT_QR_SIZE)) { - val totalModules = matrix.size + QUIET_ZONE_MODULES * 2 - val moduleSize = minOf(size.width, size.height) / totalModules - val quietZoneOffset = moduleSize * QUIET_ZONE_MODULES - val boardSize = moduleSize * totalModules - val originX = (size.width - boardSize) / 2f + quietZoneOffset - val originY = (size.height - boardSize) / 2f + quietZoneOffset + val matrix by produceState(initialValue = null, url) { + value = withContext(Dispatchers.Default) { QrCodeEncoder.encode(url) } + } + Canvas( + modifier = + modifier + .size(DEFAULT_QR_SIZE) + .drawWithCache { + val m = matrix + if (m == null) { + onDrawBehind { } + } else { + val totalModules = m.size + QUIET_ZONE_MODULES * 2 + val moduleSize = minOf(size.width, size.height) / totalModules + val quietZoneOffset = moduleSize * QUIET_ZONE_MODULES + val boardSize = moduleSize * totalModules + val originX = (size.width - boardSize) / 2f + quietZoneOffset + val originY = (size.height - boardSize) / 2f + quietZoneOffset - drawRect( - color = Color.White, - topLeft = Offset(originX - quietZoneOffset, originY - quietZoneOffset), - size = Size(boardSize, boardSize), - ) - for (row in 0 until matrix.size) { - for (col in 0 until matrix.size) { - if (matrix[row, col]) { - drawRect( - color = Color.Black, - topLeft = Offset(originX + col * moduleSize, originY + row * moduleSize), - size = Size(moduleSize, moduleSize), - ) - } - } - } + val path = + Path().apply { + for (row in 0 until m.size) { + for (col in 0 until m.size) { + if (m[row, col]) { + addRect( + Rect( + offset = + Offset( + originX + col * moduleSize, + originY + row * moduleSize, + ), + size = Size(moduleSize, moduleSize), + ), + ) + } + } + } + } + onDrawBehind { + drawRect( + color = Color.White, + topLeft = Offset(originX - quietZoneOffset, originY - quietZoneOffset), + size = Size(boardSize, boardSize), + ) + drawPath(path, Color.Black) + } + } + }, + ) { } } diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_ic_activity.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_activity.xml new file mode 100644 index 0000000..e6ac159 --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_activity.xml @@ -0,0 +1,13 @@ + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_ic_arrow_back.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_arrow_back.xml new file mode 100644 index 0000000..5291af3 --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_arrow_back.xml @@ -0,0 +1,13 @@ + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_ic_check.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_check.xml new file mode 100644 index 0000000..a1aac74 --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_check.xml @@ -0,0 +1,13 @@ + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_ic_chevron_down.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_chevron_down.xml new file mode 100644 index 0000000..b72acb3 --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_chevron_down.xml @@ -0,0 +1,13 @@ + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_ic_chevron_right.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_chevron_right.xml new file mode 100644 index 0000000..2d3008f --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_chevron_right.xml @@ -0,0 +1,13 @@ + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_ic_close.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_close.xml new file mode 100644 index 0000000..67f43bd --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_close.xml @@ -0,0 +1,13 @@ + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_ic_composer.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_composer.xml new file mode 100644 index 0000000..5852c12 --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_composer.xml @@ -0,0 +1,19 @@ + + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_ic_copy.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_copy.xml new file mode 100644 index 0000000..d8a1a2c --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_copy.xml @@ -0,0 +1,19 @@ + + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_ic_crashes.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_crashes.xml new file mode 100644 index 0000000..fc81abe --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_crashes.xml @@ -0,0 +1,21 @@ + + + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_ic_database.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_database.xml new file mode 100644 index 0000000..b1c8a79 --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_database.xml @@ -0,0 +1,19 @@ + + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_ic_download.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_download.xml new file mode 100644 index 0000000..535da9d --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_download.xml @@ -0,0 +1,13 @@ + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_ic_evidence.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_evidence.xml new file mode 100644 index 0000000..3e88252 --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_evidence.xml @@ -0,0 +1,13 @@ + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_ic_expand.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_expand.xml new file mode 100644 index 0000000..ad2d68e --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_expand.xml @@ -0,0 +1,31 @@ + + + + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_ic_export.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_export.xml new file mode 100644 index 0000000..1f78509 --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_export.xml @@ -0,0 +1,13 @@ + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_ic_files.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_files.xml new file mode 100644 index 0000000..46d3b63 --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_files.xml @@ -0,0 +1,19 @@ + + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_ic_filter_lines.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_filter_lines.xml new file mode 100644 index 0000000..ff2d885 --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_filter_lines.xml @@ -0,0 +1,13 @@ + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_ic_folder.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_folder.xml new file mode 100644 index 0000000..a591c0a --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_folder.xml @@ -0,0 +1,13 @@ + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_ic_link.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_link.xml new file mode 100644 index 0000000..e80321f --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_link.xml @@ -0,0 +1,13 @@ + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_ic_mocks.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_mocks.xml new file mode 100644 index 0000000..756652c --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_mocks.xml @@ -0,0 +1,19 @@ + + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_ic_more_horizontal.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_more_horizontal.xml new file mode 100644 index 0000000..9a2f8fe --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_more_horizontal.xml @@ -0,0 +1,16 @@ + + + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_ic_network.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_network.xml new file mode 100644 index 0000000..37ad95a --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_network.xml @@ -0,0 +1,13 @@ + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_ic_open_external.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_open_external.xml new file mode 100644 index 0000000..fdf7d96 --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_open_external.xml @@ -0,0 +1,13 @@ + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_ic_overview.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_overview.xml new file mode 100644 index 0000000..e0f4cf2 --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_overview.xml @@ -0,0 +1,17 @@ + + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_ic_preferences.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_preferences.xml new file mode 100644 index 0000000..2d5d470 --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_preferences.xml @@ -0,0 +1,37 @@ + + + + + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_ic_push.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_push.xml new file mode 100644 index 0000000..655d969 --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_push.xml @@ -0,0 +1,13 @@ + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_ic_qr_code.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_qr_code.xml new file mode 100644 index 0000000..adc17ed --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_qr_code.xml @@ -0,0 +1,40 @@ + + + + + + + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_ic_refresh.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_refresh.xml new file mode 100644 index 0000000..0d96f7c --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_refresh.xml @@ -0,0 +1,19 @@ + + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_ic_search.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_search.xml new file mode 100644 index 0000000..ad9ccbf --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_search.xml @@ -0,0 +1,19 @@ + + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_ic_settings_gear.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_settings_gear.xml new file mode 100644 index 0000000..f871c49 --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_settings_gear.xml @@ -0,0 +1,19 @@ + + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_ic_share_nodes.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_share_nodes.xml new file mode 100644 index 0000000..573779c --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_share_nodes.xml @@ -0,0 +1,31 @@ + + + + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_ic_state_flags.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_state_flags.xml new file mode 100644 index 0000000..fb53fb7 --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_state_flags.xml @@ -0,0 +1,14 @@ + + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_ic_sun.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_sun.xml new file mode 100644 index 0000000..f2e7821 --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_sun.xml @@ -0,0 +1,19 @@ + + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_ic_tag.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_tag.xml new file mode 100644 index 0000000..1653f96 --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_tag.xml @@ -0,0 +1,19 @@ + + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_ic_theme_dark.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_theme_dark.xml new file mode 100644 index 0000000..4df2c71 --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_theme_dark.xml @@ -0,0 +1,13 @@ + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_ic_timeline.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_timeline.xml new file mode 100644 index 0000000..3d3bb58 --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_timeline.xml @@ -0,0 +1,17 @@ + + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_ic_trash.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_trash.xml new file mode 100644 index 0000000..e2c0f90 --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_trash.xml @@ -0,0 +1,37 @@ + + + + + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_ic_websockets.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_websockets.xml new file mode 100644 index 0000000..af140a3 --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_ic_websockets.xml @@ -0,0 +1,13 @@ + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_spot_connect.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_connect.xml new file mode 100644 index 0000000..7b2d32b --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_connect.xml @@ -0,0 +1,31 @@ + + + + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_spot_connect_accent.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_connect_accent.xml new file mode 100644 index 0000000..96a4cad --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_connect_accent.xml @@ -0,0 +1,19 @@ + + + + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_spot_crashes.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_crashes.xml new file mode 100644 index 0000000..dc2c57d --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_crashes.xml @@ -0,0 +1,13 @@ + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_spot_crashes_accent.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_crashes_accent.xml new file mode 100644 index 0000000..3e346f9 --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_crashes_accent.xml @@ -0,0 +1,13 @@ + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_spot_database.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_database.xml new file mode 100644 index 0000000..09e36c0 --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_database.xml @@ -0,0 +1,19 @@ + + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_spot_database_accent.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_database_accent.xml new file mode 100644 index 0000000..5f40fba --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_database_accent.xml @@ -0,0 +1,13 @@ + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_spot_folder.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_folder.xml new file mode 100644 index 0000000..2a9cfc6 --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_folder.xml @@ -0,0 +1,13 @@ + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_spot_folder_accent.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_folder_accent.xml new file mode 100644 index 0000000..3a9f321 --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_folder_accent.xml @@ -0,0 +1,16 @@ + + + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_spot_logs.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_logs.xml new file mode 100644 index 0000000..ea9b891 --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_logs.xml @@ -0,0 +1,37 @@ + + + + + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_spot_logs_accent.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_logs_accent.xml new file mode 100644 index 0000000..296b144 --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_logs_accent.xml @@ -0,0 +1,19 @@ + + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_spot_mocks.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_mocks.xml new file mode 100644 index 0000000..063251b --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_mocks.xml @@ -0,0 +1,25 @@ + + + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_spot_mocks_accent.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_mocks_accent.xml new file mode 100644 index 0000000..425f803 --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_mocks_accent.xml @@ -0,0 +1,19 @@ + + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_spot_push.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_push.xml new file mode 100644 index 0000000..bac0373 --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_push.xml @@ -0,0 +1,25 @@ + + + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_spot_push_accent.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_push_accent.xml new file mode 100644 index 0000000..3b60f3f --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_push_accent.xml @@ -0,0 +1,13 @@ + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_spot_remote_config.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_remote_config.xml new file mode 100644 index 0000000..c94d1ba --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_remote_config.xml @@ -0,0 +1,13 @@ + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_spot_remote_config_accent.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_remote_config_accent.xml new file mode 100644 index 0000000..b8ce534 --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_remote_config_accent.xml @@ -0,0 +1,19 @@ + + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_spot_search.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_search.xml new file mode 100644 index 0000000..0d0f2fd --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_search.xml @@ -0,0 +1,19 @@ + + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_spot_search_accent.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_search_accent.xml new file mode 100644 index 0000000..f805233 --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_search_accent.xml @@ -0,0 +1,13 @@ + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_spot_select.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_select.xml new file mode 100644 index 0000000..96fdbf0 --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_select.xml @@ -0,0 +1,26 @@ + + + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_spot_select_accent.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_select_accent.xml new file mode 100644 index 0000000..6bb0bf0 --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_select_accent.xml @@ -0,0 +1,13 @@ + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_spot_sockets.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_sockets.xml new file mode 100644 index 0000000..7b70c20 --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_sockets.xml @@ -0,0 +1,49 @@ + + + + + + + + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_spot_sockets_accent.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_sockets_accent.xml new file mode 100644 index 0000000..37522d6 --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_sockets_accent.xml @@ -0,0 +1,13 @@ + + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_spot_traffic.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_traffic.xml new file mode 100644 index 0000000..15a7742 --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_traffic.xml @@ -0,0 +1,64 @@ + + + + + + + + + + + + diff --git a/sdk/ui-compose/src/main/res/drawable/devconsole_spot_traffic_accent.xml b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_traffic_accent.xml new file mode 100644 index 0000000..f4db0fd --- /dev/null +++ b/sdk/ui-compose/src/main/res/drawable/devconsole_spot_traffic_accent.xml @@ -0,0 +1,17 @@ + + + + +