diff --git a/.gitignore b/.gitignore index 4323ba4..55e0483 100644 --- a/.gitignore +++ b/.gitignore @@ -20,3 +20,6 @@ captures/ # macOS .DS_Store + +# Local feature worktrees +.worktrees/ diff --git a/CHANGELOG.md b/CHANGELOG.md index ff0c0d6..0349546 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,135 @@ joined this list.) ## Unreleased +## 1.1.1 — 2026-08-12 + +A build-and-distribution patch: no SDK code changed, and the public API is byte-for-byte the +1.1.0 surface. It exists because 1.1.0 could not be built by anything that lacks the maintainer's +signing key — including JitPack, which this release adds as a channel. + +### Added + +- **JitPack as a secondary channel, for unreleased code.** Maven Central remains the supported + one; JitPack covers trying a branch or an unmerged fix. Artifacts resolve under the group + `com.github.devconsole-android.DevConsole` with the same artifact ids + (`com.github.devconsole-android.DevConsole:devconsole:1.1.1`), and any branch resolves as + `-SNAPSHOT` (a `/` in the branch name is written `~`). Two limits worth knowing: the + Gradle plugin is **not** served there — it lives in an `includeBuild` and JitPack lists only the + 31 library modules, so JitPack consumers name coordinates directly and give up the plugin's + variant-policy enforcement — and JitPack artifacts are unsigned. + +### Fixed + +- **`./gradlew publishToMavenLocal` failed for anyone without the maintainer's signing key.** + `signAllPublications()` registers a signing task *and* the resulting `.asc` files as publication + artifacts. With no key the task fails outright ("no configured signatory") rather than skipping, + and even when the task is explicitly excluded the publication still demands `.asc` files nothing + produced ("artifact file does not exist: …-release.aar.asc"). Both shapes broke the same three + audiences: contributors running the exact command `CONTRIBUTING.md` asks for, CI building from a + clean checkout, and JitPack. Publications are now signed only when a key is actually configured — + the key itself, not the id/password a maintainer's machine keeps between releases. Release + signing is unchanged and verified both ways: five signatures with the key present, none and a + green build without. `docs/MAVEN_PUBLISHING.md` has claimed since 1.0.0 that signing "no-ops when + no key is configured"; that is now true rather than aspirational. + +- **`docs/COMPOSER_AND_MOCKS.md` described re-enabling mocks without saying how**, from before + [1.1.0](#110--2026-08-12) added `POST /api/v1/mocks/enabled` — until then the browser genuinely + could not. Now documents both directions and why turning mocking on is capability-gated while + turning it off is not. + +## 1.1.0 — 2026-08-12 + +A minor in the strict sense the [policy](#versioning-and-stability-policy) commits to: two additive +methods on `DevConsoleRuntime`, one new REST route, and no change to any existing surface. Most of +the release is the native-siblings UI pass across both surfaces, plus four defects a full +feature sweep of the shipped build turned up. + +### Added + +- **`POST /api/v1/mocks/enabled` — the way back from the mock kill switch.** The browser could + disable all mocking (`POST /api/v1/mocks/disable-all`) but had no route to turn it back on, so + the only way to resume mocking was to restart the host app — while the Android in-app inspector + had a two-way toggle the whole time. The dashboard's "Disable all mocks" button is now a two-way + switch that reads its label from the engine's live state. The two directions gate differently and + deliberately: turning mocking *off* stays ungated (falling back to real traffic is always + allowed), while turning it back *on* requires the host's `mocks` editing capability, since it + changes how the app behaves. + +- **`DevConsoleRuntime.recordPublishedEvent()` / `recordDroppedEvents(count)`**, the counters behind + the fix below. + +### Fixed + +- **Every list row in the dashboard rendered without its path or summary.** `.row-main` is the + flexible column between a row's fixed ones, and those fixed columns — checkbox 24px, method badge + 54px, duration 74px, status 62px, flag 24px, five 12px gaps, 20px padding — added up to 318px + inside a list pane whose default width was 320px. The path text was laid out into the leftover + 2px and clipped to nothing, so Network, Timeline, WebSockets, Push, and Crashes all showed rows + identifiable only by their method badge and duration; on the two-column rows a sliver of the + leading `/` survived and read as a stray comma. The detail pane had the full URL all along, which + is what kept this from being obvious. The row gap is now 8px and the list column defaults to + 440px with a 360px floor (it stays drag-resizable), leaving the main text 142px at the default. + The `.col-*` header cells were re-aligned to match, including `.col-flag`, which had been 34px + against the 24px flag button it labels. + +- **The SDK-health card reported "0 published events" no matter how much the SDK captured.** + `publishedEventCount` and `droppedEventCount` are surfaced on the dashboard's SDK Health screen + and the Android More screen's health rows, and both were hardcoded 0 in every shipping build: + the counters live on `EventPipeline`, which nothing in the runtime ever instantiates — real + captures funnel through `CaptureTimelineBridge.emit()` instead, and `DevConsoleRuntime`'s own + `SdkHealth` only ever tracked `initializationCount` and `state`. A dropped-event count that can + never rise is the more consequential half: it is the SDK's only signal that capture lost data to + buffer overflow. `emit()` now counts each published event and the persistence queue's existing + `onDrop` hook counts each dropped one. + +- **A malformed request answered `500 INTERNAL_ERROR`.** Routes that read a form body — `POST + /api/v1/push/simulate`, the `POST` halves of the HAR and Postman exports, `POST /api/v1/exports`, + and the rest — call `receiveParameters()`, which throws when handed JSON or no `Content-Type` at + all. That landed on the module's catch-all boundary and came back as a server error, sending + anyone writing a third-party client hunting a bug in the SDK for what was their own malformed + request. Content-transformation failures now answer `400 VALIDATION_FAILED` and the typed + media-type rejection answers `415 UNSUPPORTED_MEDIA_TYPE`, so an `INTERNAL_ERROR` from this + server once again means only a genuine server-side fault. The dashboard was never affected — it + sets the right content type on every one of these calls. + +- **A pill button clipped its own label.** `InspectorPillButton` laid its label out with `maxLines = + 1` and the default clip overflow, so the More screen's "Code" action — squeezed by the "Copy URL" + pill's 2f weight — rendered as "Cod". The label now ellipsizes rather than silently dropping a + glyph, the pill's horizontal padding is 12dp, and the URL card's primary action takes 1.5f. + +- **Starting the server on a port that was taken between the availability probe and the real bind + could crash the host app.** `KtorLocalServerEngine.start` preflights each candidate port with + `isPortAvailable`, then calls `embeddedServer(CIO, ...).start(wait = false)` — which returns + *before* CIO's accept loop has actually bound. Losing that race throws `BindException` inside + Ktor's own accept coroutine, long after the `runCatching` around `start()` has returned, and with + nothing on the server's parent context it reached the thread's default uncaught handler: on + Android, the host application's crash handler. A debug console taking down the app it exists to + observe, for a condition it already handles — `isServerBound` sees the failure and the loop falls + forward to the next port exactly as intended. The embedded server now runs in an engine-owned + `SupervisorJob` scope carrying a `CoroutineExceptionHandler`, so a detected-and-recovered bind + failure stays the SDK's business. Surfaced by a flaky test rather than a report: Gradle runs + `testDebugUnitTest` and `testReleaseUnitTest` in parallel, both binding this module's fixed + `8400..8419` range, and the loser's escaped exception landed on whichever unrelated test called + `runTest` next as `UncaughtExceptionsBeforeTest` — roughly two failures in every five suite runs, + on two tests that had nothing to do with it. + +- **OkHttp responses without a `Content-Length` showed a blank response body unless the host read + the whole thing.** Those responses — `Transfer-Encoding: chunked`, and every transparently + gzipped response, which is most of them — are captured by the tee, which copies bytes *as the + host reads them*. A call site that reads only the status code and closes (`execute().use { + it.code }`, the shape all three samples had), or a parser that stops at the end of the value it + wanted, therefore left nothing to capture: the transaction was recorded with an empty body and + `bodyOmittedReason = "partial"`. The same response *with* a `Content-Length` was captured whole + by the eager `peekBody`, and the Ktor plugin — which drains its own half of the split channel — + was never affected, so identical app code showed the body on one client and a blank pane on the + other. `TeeCapturingSource.close()` now drains whatever the host left behind before completing + the close, bounded by the existing 512 KiB cap and a 300 ms deadline (the same + bounded-drain-on-close OkHttp itself performs for connection reuse). A body that runs out of that + budget is still recorded `"partial"`, and one no bytes were recovered from is now recorded with + no body instead of an empty one — an empty preview beside a 200 reads as "the server sent + nothing", which is a different claim. The compose sample's OkHttp card now reads its response + body, like its Ktor card already did. + ## 1.0.1 — 2026-08-08 A patch in the strict sense the [policy](#versioning-and-stability-policy) now commits to: one diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index efe8586..eaf9c2c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,8 +1,9 @@ # Contributing to DevConsole -Thanks for taking a look. This project is a 25-module Android SDK plus two included Gradle -builds (`build-logic`, `gradle-plugin`), so the fastest way in is to lean on the same commands CI -runs — see [Verify](.github/workflows/verify.yml). +Thanks for taking a look. This is a 31-module Android SDK plus two included Gradle builds +(`build-logic` and `gradle-plugin`), which sounds like a lot until you realise you rarely touch more +than one at a time. The quickest way in is to run the same commands CI runs, listed below and in +[Verify](.github/workflows/verify.yml). ## Prerequisites @@ -10,9 +11,8 @@ runs — see [Verify](.github/workflows/verify.yml). included builds target the same toolchain). - Android SDK with `compileSdk`/`targetSdk` 35 installed (Android Gradle Plugin 8.13.0, `minSdk` 23). See the [compatibility table](README.md#compatibility) in the README for the full matrix. -- No emulator or device is required to build, run unit tests, or lint — only the three sample - apps' instrumented tests would need one, and those aren't part of the default `build`/`test` - path below. +- No emulator or device needed to build, test, or lint. Only the sample apps' instrumented tests + want one, and those sit outside the default `build` and `test` paths below. ## Building and testing @@ -54,48 +54,50 @@ All commands run from the repository root. ./gradlew :samples:views-java-app:assembleDebug :samples:views-java-app:assembleRelease :samples:views-java-app:verifyDevConsoleProtectedArtifacts ``` -If you only touched one module, scope any of the above to it, e.g. +Touched one module? Scope the command to it and save yourself the wait: `./gradlew :sdk:network-okhttp:test :sdk:network-okhttp:ktlintCheck`. ## Making a change -- Public API changes to a module that carries `org.jetbrains.kotlinx.binary-compatibility-validator` - (anything with a committed `api/*.api` file, e.g. `sdk:api`) need `./gradlew apiDump` committed - alongside the change — `apiCheck` in CI fails otherwise. -- Kotlin file header, view-id naming, and general style conventions used throughout this codebase - are documented informally by example — match the surrounding file. New Kotlin files start with: +- Changing public API on a module with a committed `api/*.api` baseline means committing a + `./gradlew apiDump` alongside it. `apiCheck` fails in CI otherwise, which is the point. +- Style is documented by example rather than by rule, so match the file you're in. New Kotlin files + start with: ```kotlin /** * @author * @since DD/MM/YY */ ``` -- Capture code (`sdk:network*`, `sdk:socket*`, `sdk:push*`) must never throw into the host app — - wrap recording paths defensively, matching the existing `runCatching`/`onFailure { logcatInfo(...) }` - pattern used throughout those modules. -- Redaction happens at capture time (`RedactionEngine`, applied via `config.redactionPolicy`); code - that formats or displays already-captured text (dashboard JSON/XML rendering, Compose/Views - detail screens) must not need to know about redaction — if you're adding a redaction concern to a - formatter, something further upstream is probably the better place for it. -- If your change touches a protected-variant boundary (a module with a release no-op counterpart, - or the Gradle plugin's variant-policy enforcement), run the sample assemble/verify commands above - for all three samples — that's what actually exercises the debug/release split. +- Capture code (`sdk:network*`, `sdk:socket*`, `sdk:push*`) must never throw into the host app. A + debugging tool that crashes the app it exists to observe is worse than no tool. Wrap recording + paths defensively, following the `runCatching` / `onFailure { logcatInfo(...) }` pattern already + in those modules. +- Redaction happens at capture time, in `RedactionEngine` via `config.redactionPolicy`. Code that + formats or displays already-captured text (dashboard JSON/XML rendering, the Compose and Views + detail screens) should never need to know redaction exists. If you find yourself adding a + redaction concern to a formatter, the fix probably belongs further upstream. +- If your change touches a protected-variant boundary (a module with a release no-op twin, or the + Gradle plugin's variant-policy enforcement), run the sample assemble and verify commands above for + all three samples. That is what actually exercises the debug/release split. ## Opening a pull request -- Keep PRs scoped to one logical change; the commit message should explain *why*, not just *what*. +- Keep a PR to one logical change, and let the commit message explain *why* rather than *what*. The + diff already says what. - Include the specific `./gradlew` commands you ran to verify the change in the PR description. - If you changed public API, confirm `apiDump` is included in the diff. -- If you changed anything security- or redaction-adjacent, call it out explicitly in the PR - description — see [SECURITY.md](SECURITY.md) for how to report a vulnerability privately instead - of through a public PR/issue. -- No DCO or commit-sign-off is currently required or enforced by this repository (no `DCO` check - or commit-signing requirement is configured in CI) — standard `git commit` is fine. This may - change; check [.github/workflows](.github/workflows) if you're unsure what's currently enforced. +- Changed anything security- or redaction-adjacent? Say so plainly in the PR description. If you're + reporting a vulnerability rather than fixing one, [SECURITY.md](SECURITY.md) explains how to do + that privately instead of in a public PR or issue. +- No DCO or sign-off is required; a plain `git commit` is fine. That could change, so check + [.github/workflows](.github/workflows) if you want to be sure what's enforced today. ## Reporting bugs / requesting features Use the issue templates: [Bug report](.github/ISSUE_TEMPLATE/bug_report.md) or -[Feature request](.github/ISSUE_TEMPLATE/feature_request.md). Do **not** file a public issue for a -suspected credential exposure, production inclusion, authentication bypass, or remote code -execution — see [SECURITY.md](SECURITY.md) for private reporting instead. +[Feature request](.github/ISSUE_TEMPLATE/feature_request.md). + +One exception. Never open a public issue for a suspected credential exposure, an accidental +production inclusion, an authentication bypass, or remote code execution. +[SECURITY.md](SECURITY.md) has the private reporting route for those. diff --git a/README.md b/README.md index 743a4f2..ac72de3 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ # DevConsole -**Debug your Android app from inside the app — or from any browser.** +**An in-app debugger for Android, with a browser dashboard for when you want a bigger screen.** [![Maven Central](https://img.shields.io/maven-central/v/io.github.devconsole-android/devconsole)](https://central.sonatype.com/artifact/io.github.devconsole-android/devconsole) [![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE) @@ -13,46 +13,49 @@
-In-app inspector — live traffic on the device  Web dashboard — overview with traffic health and signals +In-app inspector showing live network traffic on the device  Web dashboard overview with traffic health and the latest signals -An on-device developer console for Android. Open a full inspector — network traffic, crashes, -storage, feature flags, exports — right inside your **debug** app, by shake, floating button, or -one line of code. When you want a bigger screen, the same data streams to any browser through an -embedded web dashboard. Release builds compile against a no-op twin artifact, so none of this -code ever ships to production, and the Gradle plugin fails the build if it would. +Shake your debug build and DevConsole opens on top of it. Network traffic, crashes and ANRs, +feature flags, SharedPreferences, SQLite, files — all of it on the device, no cable required. -**1.0 is out, and the public API is stable.** From here, breaking changes to `sdk:api` need a -major version, new API a minor, everything else a patch — enforced, not just promised: every -published module carries a committed ABI baseline that fails the build on an unintended change. -See the [changelog](CHANGELOG.md) for the full policy. +When a phone screen isn't enough, start the embedded server and the same data live-tails into any +browser, where you can also edit mock rules and export HAR, Postman, or a whole bug report. -## TL;DR +Your release build never sees any of it. It compiles against a no-op twin that records nothing and +links no server code, and the Gradle plugin fails the build if the real runtime ever slips in. + +**Contents** · [Quick start](#quick-start) · [What you get](#what-you-get) · +[How it works](#how-it-works) · [Guide](#step-by-step-guide) · [Artifacts](#artifacts) · +[Permissions](#permissions) · [Security](#security-model) · [Samples](#sample-apps) · +[Docs](#documentation) + +## Quick start **1. Add the plugin and two dependencies** to your app's `build.gradle.kts`: ```kotlin plugins { id("com.android.application") - id("io.github.devconsole-android") version "1.0.1" + id("io.github.devconsole-android") version "1.1.1" } dependencies { - debugImplementation("io.github.devconsole-android:devconsole:1.0.1") - releaseImplementation("io.github.devconsole-android:devconsole-noop:1.0.1") + debugImplementation("io.github.devconsole-android:devconsole:1.1.1") + releaseImplementation("io.github.devconsole-android:devconsole-noop:1.1.1") } ``` **2. Open the inspector on the device.** The SDK auto-initializes on debuggable builds, so this -works immediately — from any button in your debug UI: +works right away from any button in your debug UI: ```kotlin DevConsole.open(context) ``` -or hands-free, by opting into the built-in triggers — shake the device (intensity adjustable) or -tap a draggable floating button: +Or go hands-free. Opt into the built-in triggers and shake the device, or tap a draggable floating +button: ```kotlin DevConsole.initialize( @@ -62,15 +65,14 @@ DevConsole.initialize( ) ``` -That's the setup. The inspector shows crash/ANR reports, feature flags, and inspectors for -SharedPreferences, SQLite, and files (read-only by default); wire your HTTP client with one line -(["Wire up your network stack"](#wire-up-your-network-stack) below) and network, WebSocket, and -MQTT traffic appears too. +That's the setup. You now have crash and ANR reports, feature flags, and read-only 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. -**3. Want a bigger screen? Start the browser dashboard** — the same data live-tailing in any -browser, plus mock-rule editing and one-click HAR / Postman / bug-report exports. The easiest way: -tap **Start server** on the inspector's **More** screen, which then shows the connect URL and a QR -code. Or from code (either way, make sure your manifest has `INTERNET` — most apps already do): +**3. Want a bigger screen? Start the browser dashboard.** Tap **Start server** on the inspector's +**More** screen and it hands you a connect URL and a QR code. You can also do it from code. Either +way your manifest needs `INTERNET`, which most apps already declare: ```kotlin lifecycleScope.launch { // startBrowser is a suspend function; the server never starts on its own @@ -84,7 +86,8 @@ lifecycleScope.launch { // startBrowser is a suspend function; the server never adb forward tcp:8080 tcp:8080 # use the port from the DevConsole log line ``` -then open the **whole URL** — the `#code=` fragment is the credential. +Then open the **whole URL**. The `#code=` fragment is the credential, so a bare `http://host:port/` +gets you nothing. ## What you get @@ -102,30 +105,32 @@ then open the **whole URL** — the `#code=` fragment is the credential. | **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** | Opt-in foreground service that keeps the server alive while your app is backgrounded. Manifest-only opt-in, zero SDK-declared permissions. | -Capture is category-scoped: `DevConsoleConfig.withCaptureCategories(...)` narrows what's recorded -(`NETWORK`, `SOCKET`, `MQTT`, `PUSH`, `LOGS`, `CRASHES`, `STATE`, `INSPECTION`, `MOCKS` — default -is all). Events persist in a Room database bounded by a retention policy (7 days / 100 MB by -default). +Capture is category-scoped. `DevConsoleConfig.withCaptureCategories(...)` narrows what gets +recorded to any of `NETWORK`, `SOCKET`, `MQTT`, `PUSH`, `LOGS`, `CRASHES`, `STATE`, `INSPECTION`, +and `MOCKS`. All of them are on by default. Events land in a Room database with a retention policy +that defaults to 7 days or 100 MB, whichever comes first. ## How it works -`devconsole` (debug) and `devconsole-noop` (release) expose the **same public API**. The no-op -twin records nothing, serves nothing, and links no server code — production safety comes from -dependency selection, not a runtime flag. The Gradle plugin -(`io.github.devconsole-android`) auto-wires the debug/release split if you omit the -dependencies, and verifies — declared dependencies, resolved runtime classpath, and final -APK/AAB bytes — that the full runtime never reaches a protected variant. +`devconsole` (debug) and `devconsole-noop` (release) expose the **same public API**. The no-op twin +records nothing, serves nothing, and links no server code. Production safety comes from which +artifact you depend on, not from a runtime flag someone can forget to set. + +The Gradle plugin (`io.github.devconsole-android`) wires that debug/release split for you if you +omit the dependencies. It then checks three things: your declared dependencies, the resolved runtime +classpath, and the bytes in the final APK or AAB. If the full runtime reaches a protected variant, +the build fails. -On debuggable builds the SDK auto-initializes from its own `ContentProvider`; no -`Application.onCreate` boilerplate needed. The server itself **never auto-starts** — you always -call `startBrowser(...)` explicitly. +On debuggable builds the SDK initializes itself from its own `ContentProvider`, so there is no +`Application.onCreate` boilerplate. The server is the exception: it never auto-starts. You always +call `startBrowser(...)` yourself. ## Step-by-step guide ### Open the in-app inspector `DevConsole.open(context)` opens the inspector from any trigger you like and returns an -`InspectorOpenResult`. To let the SDK open it without host code, opt into the triggers — both are +`InspectorOpenResult`. If you'd rather not write that call, opt into the built-in triggers. Both are off by default, and neither ever starts the server: ```kotlin @@ -138,29 +143,30 @@ DevConsoleConfig.default().withOpenTriggers( ) ``` -The floating button is **draggable** — press and move it anywhere on screen, and it stays put across -Activity changes and rotation (it re-clamps into the window so it can never be stranded off-screen). -It rests at 65% opacity so it doesn't hide the UI underneath, and goes fully opaque while you're -touching it. A drag never counts as a tap, so moving it won't open the inspector. +The floating button is **draggable**. Press and move it anywhere on screen and it stays there across +Activity changes and rotation, re-clamping into the window so it can never strand itself off-screen. +It sits at 65% opacity so it doesn't hide your UI, and goes fully opaque while you touch it. A drag +never counts as a tap, so moving it won't open the inspector. -Both triggers are **UI-framework agnostic**: the button is a plain `ImageView` added to the -Activity's decor view and the shake detector is a sensor listener, so an XML/Views or Java host gets -exactly the same behaviour as a Compose one — no `ui-compose` or `ui-views` dependency involved. -Java: `OpenTriggers.builder().shakeToOpen(true).floatingButton(true).build()`, as +Both triggers are **UI-framework agnostic**. The button is a plain `ImageView` on the Activity's +decor view and the shake detector is a sensor listener, so an XML/Views or Java host behaves exactly +like a Compose one, with no `ui-compose` or `ui-views` dependency involved. In Java that reads +`OpenTriggers.builder().shakeToOpen(true).floatingButton(true).build()`, as [`views-java-app`](samples/views-java-app) does. Java: `DevConsoleConfig.builder().openTriggers(OpenTriggers.builder().shakeToOpen(true).build())`. ### Start and stop the dashboard server -No code required: the inspector's **More** screen has Start/Stop buttons, and once running it -shows the live connect URL — as text, a copy button, and a QR code to scan from another machine. +No code required. The inspector's **More** screen has Start and Stop buttons, and once the server is +up it shows the live connect URL three ways: as text, behind a copy button, and as a QR code you can +scan from another machine. -

More screen — server started from the device, showing the connect URL

+

More screen with the server started, showing the connect URL and QR code

-That button binds **loopback** by default, so the URL it shows needs `adb forward`. To make it bind -LAN instead — so the QR code is scannable from another machine with no forwarding — declare it on -the config, since the button issues no `StartRequest` of its own: +That button binds **loopback** by default, so the URL it shows needs `adb forward`. To bind LAN +instead, which is what makes the QR code scannable from another machine, declare it on the config. +The button issues no `StartRequest` of its own: ```kotlin DevConsoleConfig.default().withBrowserConfig(BrowserConfig(binding = BrowserBinding.LAN)) @@ -210,23 +216,22 @@ After `startBrowser`, filter Logcat on the `DevConsole` tag: I/DevConsole: Dashboard available at: http://127.0.0.1:8080/ (access link available through the DevConsole API/launcher; binding: LOOPBACK) ``` -**The session code is deliberately absent from Logcat.** The full URL — with its -`#code=` credential fragment — is available only from -`StartResult.Started.access.connectUrl`, `DevConsole.accessInfo()`, and the device's More screen -(as text and QR code). The port is the **first free one in 8080–8099**, so read it from the log -rather than assuming 8080. +**The session code is deliberately absent from Logcat.** The full URL, with its `#code=` credential fragment, comes from only three places: `StartResult.Started.access.connectUrl`, +`DevConsole.accessInfo()`, and the device's More screen as text or a QR code. The port is the first +free one in **8080–8099**, so read it from the log rather than assuming 8080. ### Connect from your browser - **Loopback (default):** run `adb forward tcp: tcp:`, then open the connect URL. -- **LAN:** pass `BindingMode.LAN` and open the URL from any device on the same network — read - [the threat model](docs/THREAT_MODEL.md) first; the dashboard speaks plaintext HTTP. A LAN start - that finds no eligible network interface returns `StartResult.NoEligibleNetwork` — it never - silently falls back to loopback (or vice versa). +- **LAN:** pass `BindingMode.LAN` and open the URL from any device on the same network. Read + [the threat model](docs/THREAT_MODEL.md) first, because the dashboard speaks plaintext HTTP. A + LAN start that finds no eligible network interface returns `StartResult.NoEligibleNetwork`. It + never quietly falls back to loopback, or the other way around. -Open the **whole URL**. The `#code=` fragment is the credential: single-use, expires in five -minutes, creates a session immediately with no approval step. Bare `http://host:port/` sits -unauthenticated forever. Issue a fresh code from the device if one lapses. +Open the **whole URL**. The `#code=` fragment is the credential. It is single-use, expires in five +minutes, and creates a session immediately with no approval step. A bare `http://host:port/` sits +unauthenticated forever. If a code lapses, issue a fresh one from the device. ### Wire up your network stack @@ -260,21 +265,26 @@ DevConsole.recordPush(FirebaseRemoteMessageAdapter().toPushInput(remoteMessage)) DevConsole.networkRecorder().record(requestInput, responseInput, startedAtMs, completedAtMs) ``` -One capture bound worth knowing up front: response bodies are captured up to a cap — 512 KiB on -OkHttp (chunked/unknown-length bodies via a non-blocking tee, recorded at EOF or close), 256 KiB on -Ktor. `text/event-stream` and known-binary bodies stay metadata-only on both, since a live SSE feed -is for all practical purposes endless. See +One limit worth knowing up front: response bodies are captured up to a cap. That's 512 KiB on +OkHttp, where chunked and unknown-length bodies go through a tee and get recorded at EOF or close, +and 256 KiB on Ktor. On both adapters, `text/event-stream` and known-binary bodies stay +metadata-only, since a live SSE feed is endless for all practical purposes. See [Chunked and streaming responses](docs/NETWORK_ADAPTERS.md#chunked-and-streaming-responses) for how the OkHttp tee works. -Java equivalents exist throughout (e.g. `DevConsoleOkHttp.install(builder, recorder)`). Details: -[docs/NETWORK_ADAPTERS.md](docs/NETWORK_ADAPTERS.md), [docs/MQTT_CAPTURE.md](docs/MQTT_CAPTURE.md), -[docs/PUSH.md](docs/PUSH.md). +Java equivalents exist throughout, such as `DevConsoleOkHttp.install(builder, recorder)`. For the +details see [docs/NETWORK_ADAPTERS.md](docs/NETWORK_ADAPTERS.md), +[docs/MQTT_CAPTURE.md](docs/MQTT_CAPTURE.md), and [docs/PUSH.md](docs/PUSH.md). + +Once traffic is flowing, every call shows up with its headers, payload, and body side by side, and +you can replay it, clone it into the composer, or flag it into a bug report: + +

Network inspector in the browser dashboard, showing a captured request and response side by side

## Artifacts -Group `io.github.devconsole-android`, one version for everything. Two coordinates cover a normal -integration (there is deliberately no BOM): +Group `io.github.devconsole-android`, one version for everything. There is deliberately no BOM, and +two coordinates cover a normal integration: | Coordinate | Scope | What it is | |---|---|---| @@ -291,15 +301,51 @@ Opt-in add-ons (each `-noop` twin is the matching `releaseImplementation`): | `devconsole-socket-paho` | `devconsole-socket-paho-noop` | MQTT capture via Eclipse Paho | | `devconsole-push-firebase` | `devconsole-push-firebase-noop` | FCM push adapter (reflection-based) | -Every other module (`devconsole-core`, `devconsole-storage-room`, …) arrives transitively — you -never name it. All modules publish sources, javadoc, and signed POMs. +Everything else (`devconsole-core`, `devconsole-storage-room`, and the rest) arrives transitively. +You never name those. Every module publishes sources, javadoc, and a signed POM. + +### JitPack (for unreleased code) + +Maven Central is the supported channel: signed, versioned, and what the Gradle plugin resolves. +[JitPack](https://jitpack.io/#devconsole-android/DevConsole) sits alongside it for one job, which is +trying a branch or an unreleased fix before it ships. Add the repository to your **settings** file, +not the module: + +```kotlin +dependencyResolutionManagement { + repositories { + mavenCentral() + maven { url = uri("https://jitpack.io") } + } +} +``` + +```kotlin +dependencies { + // Group is com.github.devconsole-android.DevConsole; artifact ids match the tables above. + debugImplementation("com.github.devconsole-android.DevConsole:devconsole:1.1.1") + releaseImplementation("com.github.devconsole-android.DevConsole:devconsole-noop:1.1.1") +} +``` -## Permissions — and why none of them ship +A release tag works as the bare tag, as above. Any branch works as `-SNAPSHOT`, with `/` +written as `~`, so a `feature/x` branch is `feature~x-SNAPSHOT`. JitPack support starts at +**1.1.1**; earlier tags do not build there. Three things to know before you rely on it: -Short version: **nothing DevConsole needs reaches your release build**, so there is nothing to -declare to Google Play and nothing for a store reviewer to ask about. The permissions live in -`devconsole` (a `debugImplementation`); `devconsole-noop`, which is what your release variant -compiles and ships against, declares none at all. +- **The Gradle plugin is not on JitPack.** Only the 31 library artifacts are, so the + `plugins { id("io.github.devconsole-android") … }` block above does not apply. Name the + `debugImplementation` and `releaseImplementation` coordinates yourself. You also give up the + plugin's variant-policy check, which is the thing that keeps the full SDK out of release builds. +- **JitPack artifacts are unsigned.** Central's are signed; these are built on demand from a commit. +- **Snapshots move.** `-SNAPSHOT` follows the branch, so a build that worked can change under you. + Pin a tag for anything you keep. + +## Permissions + +**Nothing DevConsole needs reaches your release build.** There is nothing to declare to Google Play +and nothing for a store reviewer to ask about. The permissions live in `devconsole`, which is a +`debugImplementation`. Your release variant compiles against `devconsole-noop`, and that declares +none at all. | Permission | Declared by | Why it exists | In your release build? | |---|---|---|---| @@ -309,43 +355,43 @@ compiles and ships against, declares none at all. | `POST_NOTIFICATIONS` | **You**, in `src/debug` | Optional. Only decides whether the keep-alive notification is *visible* — the service runs either way. DevConsole never requests it unprompted; the inspector offers it. | **No** (same) | | `INTERNET` | **You**, in `src/main` | Binding the dashboard's TCP socket needs it. Not DevConsole-specific — most apps already declare it for their own networking, which is why DevConsole doesn't add it for you. | Yes — but it's yours, and almost certainly already there | -Verify it yourself on any build, rather than taking the table's word for it: +Don't take the table's word for it. Check any build yourself: ```bash aapt2 dump permissions app/build/outputs/apk/release/app-release.apk ``` -The Gradle plugin also enforces the split mechanically: `verifyDevConsoleProtectedArtifacts` fails +The Gradle plugin enforces the same split mechanically. `verifyDevConsoleProtectedArtifacts` fails the build if the full runtime reaches a protected variant, checking declared dependencies, the resolved runtime classpath, and the final APK/AAB bytes. See [Build variants and production safety](docs/BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md). -## Security model — read this - -DevConsole is a debugging tool that intentionally exposes your app's internals to a browser. -The design keeps that safe by default, but you should know exactly where the edges are: - -- **The dashboard speaks plaintext HTTP.** There is no TLS. In LAN mode, anyone who can observe - your network packets can read everything the dashboard shows — headers, tokens, bodies, exports. - Loopback + `adb forward` is the default for this reason; LAN is always an explicit opt-in. -- **The connect URL is a credential.** Possession of a live `#code=` fragment creates a session — - no on-device approval step. Codes are single-use with a five-minute TTL; sessions last 30 - minutes. Treat the URL like a password; the device's More screen can revoke sessions. -- **Redaction is an allowlist.** ~25 well-known field names (plus `Bearer` tokens) are masked. - Custom header names, signed-URL query params, and PII inside bodies pass through verbatim. - See [docs/SECURITY_AND_REDACTION.md](docs/SECURITY_AND_REDACTION.md). -- **Screenshots cannot be redacted** — pixels don't have field names. Screenshot capture is **off - by default** and everything it produces is marked `UNREDACTED`. +## Security model + +DevConsole deliberately exposes your app's internals to a browser. It defaults to the safe end of +every choice, but you should know where the edges are: + +- **The dashboard speaks plaintext HTTP.** There is no TLS. In LAN mode, anyone who can watch your + network packets can read everything it shows: headers, tokens, bodies, exports. That is why + loopback plus `adb forward` is the default and LAN is always an explicit opt-in. +- **The connect URL is a credential.** 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 the 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 + [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** + and everything it produces is marked `UNREDACTED`. - **Editing is off by default.** Preferences/database/file writes, mock editing, and capture-rule editing are each gated per surface via `EditingCapabilities`; the composer and state mutation have their own `DevConsoleConfig` flags. Everything defaults to off/read-only. -The full analysis, including what a malicious network peer or co-installed app can and cannot do: -[docs/THREAT_MODEL.md](docs/THREAT_MODEL.md). +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). ## Sample apps -Three runnable samples under [`samples/`](samples/) cover every integration style: +Three runnable samples under [`samples/`](samples/), one per integration style: | Sample | Stack | Posture | |---|---|---| @@ -357,8 +403,8 @@ Three runnable samples under [`samples/`](samples/) cover every integration styl ./gradlew :samples:compose-app:assembleDebug ``` -Each sample seeds preferences, a SQLite table, and files so the inspectors have real content, and -includes a hazard section that triggers a real crash and a real ANR. +Each one seeds preferences, a SQLite table, and files so the inspectors have something real to +show, and each has a hazard section that triggers a genuine crash and a genuine ANR. ## Compatibility @@ -370,11 +416,20 @@ includes a hazard section that triggers a real crash and a real ANR. | Gradle | 8.9+ (including 9.x) | | Kotlin | 2.2.20 | +## Versioning + +1.0 shipped, and the public API is stable. Breaking changes to `sdk:api` need a major version, new +API needs a minor, and everything else is a patch. + +That is enforced rather than promised. Every published module carries a committed ABI baseline, and +an unintended change to any public surface fails the build before it can reach a release. The +[changelog](CHANGELOG.md) has the full policy. + ## Documentation Full index: [docs/README.md](docs/README.md). Highlights: -- [Threat model and safe operation](docs/THREAT_MODEL.md) — **start here before LAN mode** +- [Threat model and safe operation](docs/THREAT_MODEL.md) — **read this before using LAN mode** - Getting started: [Compose](docs/GETTING_STARTED_COMPOSE.md) · [XML/Kotlin](docs/GETTING_STARTED_XML_KOTLIN.md) · [XML/Java](docs/GETTING_STARTED_XML_JAVA.md) - [Build variants and production safety](docs/BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md) @@ -388,8 +443,8 @@ Full index: [docs/README.md](docs/README.md). Highlights: ## Contributing -See [CONTRIBUTING.md](CONTRIBUTING.md) for build prerequisites and the test/lint/API-check -commands. CI runs the same `./gradlew` tasks on every PR. +[CONTRIBUTING.md](CONTRIBUTING.md) has the build prerequisites and the test, lint, and API-check +commands. CI runs those same `./gradlew` tasks on every PR, so if it passes locally it passes there. ## License diff --git a/build-logic/convention-publishing/src/main/kotlin/io/devconsole/buildlogic/PublishingConventionPlugin.kt b/build-logic/convention-publishing/src/main/kotlin/io/devconsole/buildlogic/PublishingConventionPlugin.kt index 0be67af..6dfb4f3 100644 --- a/build-logic/convention-publishing/src/main/kotlin/io/devconsole/buildlogic/PublishingConventionPlugin.kt +++ b/build-logic/convention-publishing/src/main/kotlin/io/devconsole/buildlogic/PublishingConventionPlugin.kt @@ -49,7 +49,9 @@ class PublishingConventionPlugin : Plugin { // module's own generated HTML instead of shipping empty. configureBasedOnAppliedPlugins(JavadocJar.Dokka("dokkaGeneratePublicationHtml")) publishToMavenCentral() - signAllPublications() + // Unconditional signing fails with "no configured signatory" on any build without + // the key -- contributors and CI included. + if (hasSigningKey()) signAllPublications() pom { name.set("DevConsole ${target.name}") description.set("DevConsole SDK module: ${target.name}") @@ -77,9 +79,12 @@ class PublishingConventionPlugin : Plugin { } } + /** The key itself, not the id/password a machine may keep between releases. */ + private fun Project.hasSigningKey(): Boolean = !(findProperty("signingInMemoryKey") as? String).isNullOrBlank() + private companion object { const val MAVEN_GROUP = "io.github.devconsole-android" - const val SDK_VERSION = "1.0.1" + const val SDK_VERSION = "1.1.1" const val PROJECT_URL = "https://github.com/devconsole-android/DevConsole" } } diff --git a/docs/BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md b/docs/BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md index ed90ae4..d2a1ec2 100644 --- a/docs/BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md +++ b/docs/BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md @@ -37,7 +37,7 @@ devConsole { protectedDependencyPaths.set(setOf(":sdk:full")) // default; override for a differently-pathed module failBuildOnUnsafeVariant.set(true) // default; false downgrades to a warning autoWireDependencies.set(true) // default; false to declare coordinates yourself - sdkVersion.set("1.0.1") // default; the plugin's own version + sdkVersion.set("1.1.1") // default; the plugin's own version } ``` diff --git a/docs/COMPOSER_AND_MOCKS.md b/docs/COMPOSER_AND_MOCKS.md index 4a7570d..c8ff893 100644 --- a/docs/COMPOSER_AND_MOCKS.md +++ b/docs/COMPOSER_AND_MOCKS.md @@ -55,6 +55,16 @@ in-flight and future `decide()` call returns `Passthrough` until re-enabled. A r (a bad template, a malformed regex) fails open to passthrough and records an error event — it never crashes the host request. +The same dashboard button turns mocking back on (it reads its label from the engine's live state), +as does the Android inspector's Control screen. The two directions gate differently on purpose: +turning mocking *off* needs only an authenticated session, since falling back to real traffic is +always a safe thing to allow, while turning it back *on* also needs the host's `mocks` editing +capability, because it changes how the app behaves. A host that publishes rules read-only +(`EditingCapabilities(mocks = false)`) can therefore disable mocking from the browser but not +re-enable it — the engine is still switchable in-process through `DevConsole.mockEngine()`. +Individual rules toggle independently of this switch; with the engine off, no rule applies +regardless of its own state. + ## No production capture `sdk:noop`'s `MockEngine` is constructed with `enabled = false`: `decide()` always returns diff --git a/docs/DESIGN_SPEC.md b/docs/DESIGN_SPEC.md index 5d6d5b7..2fcb189 100644 --- a/docs/DESIGN_SPEC.md +++ b/docs/DESIGN_SPEC.md @@ -394,7 +394,7 @@ carries `topic`/`qos`. A redesign should surface the protocol as a small badge/l The goal is reference-app-quality **presentation** applied to DevConsole **without** changing its identity. Decisions locked in: -- **Palette:** keep DevConsole green. +- **Palette:** The graphite-and-cobalt token set drives native and web rendering uniformly. - **Nav:** keep the rail; add polish (spacing, hierarchy, active-state clarity, group rhythm). - **Scope:** willing to do a full pass in one go. @@ -402,6 +402,9 @@ So: this is a **polish/representation upgrade on a fixed skeleton**, not a rebra information hierarchy, density balance, empty states, table/detail readability, responsive behavior, and cross-surface consistency (web ↔ Android) — inside the tokens and constraints above. +**Web Visual Contract** +The final web visual contract relies on a rigid separation of concerns. `dashboard.css` establishes the `.metric`, `.row`, and `.card-shell` foundation so JavaScript dynamically constructs the views without embedded styles. This ensures that dynamic view rendering relies purely on semantic class names and the provided design system tokens. + --- ## 9. Known-fixed issues + open items (context for validation) diff --git a/docs/FAQ_TROUBLESHOOTING.md b/docs/FAQ_TROUBLESHOOTING.md index 064d56e..0be1a59 100644 --- a/docs/FAQ_TROUBLESHOOTING.md +++ b/docs/FAQ_TROUBLESHOOTING.md @@ -1,9 +1,9 @@ # FAQ / troubleshooting -**Can I connect from another machine on the same network?** Yes — pass -`BindingMode.LAN` to `startBrowser(...)` and open the connect URL (or scan the QR code) from -another device on the same network. Loopback + `adb forward` is still the safer default; only use -LAN mode on a network you trust, since the dashboard speaks plaintext HTTP. See +**Can I connect from another machine on the same network?** Yes. Pass `BindingMode.LAN` to +`startBrowser(...)`, then open the connect URL or scan the QR code from the other device. Loopback +plus `adb forward` is still the safer default. Only reach for LAN on a network you trust, because +the dashboard speaks plaintext HTTP. See [LAN_PERMISSION_AND_TROUBLESHOOTING.md](LAN_PERMISSION_AND_TROUBLESHOOTING.md) and [THREAT_MODEL.md](THREAT_MODEL.md). @@ -16,42 +16,43 @@ dashboard assets, and storage layer live only in `sdk:full`, and `verifyDevConso checks specifically for a dependency on that module, not for the absence of every DevConsole class. See [BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md](BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md). -**I toggled a feature flag in the dashboard but my app didn't change.** Flags are read, not pushed -— call `DevConsole.featureFlagValue(key)` from your own code at the point you'd otherwise check a -local flag. There's no change notification; re-check after whatever user action would plausibly -follow a QA override. See [STATE_AND_FLAGS.md](STATE_AND_FLAGS.md). +**I toggled a feature flag in the dashboard but my app didn't change.** Flags are pulled, not +pushed. Call `DevConsole.featureFlagValue(key)` wherever you'd otherwise check a local flag. There +is no change notification, so re-check after whatever user action would plausibly follow a QA +override. See [STATE_AND_FLAGS.md](STATE_AND_FLAGS.md). -**Can I register a state provider or feature flag after `initialize()`?** No, by design — both are -declared once via `DevConsoleConfig` at `initialize()` time, to avoid a race between a late -registration and the dashboard having already read an earlier snapshot. +**Can I register a state provider or feature flag after `initialize()`?** No, and that's deliberate. +Both are declared once through `DevConsoleConfig` at `initialize()` time, which avoids a race +between a late registration and a dashboard that already read an earlier snapshot. -**Shaking the device does nothing, and there's no floating button.** Both triggers are opt-in via -`DevConsoleConfig.openTriggers` and off by default — pass +**Shaking the device does nothing, and there's no floating button.** Both triggers are off by +default. Turn them on with `withOpenTriggers(OpenTriggers(shakeToOpen = true, floatingButton = true))` at `initialize()` time, -and tune how hard a shake must be with `ShakeIntensity` (`LIGHT`/`MEDIUM`/`FIRM`). Either trigger -only opens the in-app inspector; neither ever starts the server. - -**A mock rule isn't matching.** Check the Mocks page's conflict detector first — a -higher-priority or more-specific rule may be winning instead. Matching is deterministic: highest -priority wins, ties broken by specificity, then by creation order. See -[COMPOSER_AND_MOCKS.md](COMPOSER_AND_MOCKS.md). - -**My WebSocket/mock/network interceptor doesn't do anything in release builds.** That's correct — -it's still wired in your `OkHttpClient.Builder`, but every recorder/engine behind it is -`enabled = false` in `devconsole-noop`, so it becomes a fast no-op rather than something you need to -conditionally remove. - -**My session code says expired or invalid, and a second browser can't join.** Codes are single-use -and one is live at a time with a 5-minute TTL — there is no on-device approval step and no automatic -regeneration, so issue a fresh code from the device (More screen) for each new browser. See +and tune how hard a shake has to be with `ShakeIntensity` (`LIGHT`, `MEDIUM`, or `FIRM`). Either +trigger only opens the in-app inspector. Neither ever starts the server. + +**A mock rule isn't matching.** Check the Mocks page's conflict detector first, since a +higher-priority or more specific rule may be winning. Matching is deterministic: highest priority +wins, ties break by specificity, then by creation order. Also check that the global switch is on; +it and the per-rule toggles are independent. See [COMPOSER_AND_MOCKS.md](COMPOSER_AND_MOCKS.md). + +**My WebSocket, mock, or network interceptor does nothing in release builds.** That's the intent. +It's still wired into your `OkHttpClient.Builder`, but every recorder and engine behind it is +`enabled = false` in `devconsole-noop`. It becomes a fast no-op, so you never have to strip it out +conditionally. + +**My session code says expired or invalid, and a second browser can't join.** Codes are single-use, +only one is live at a time, and each lasts five minutes. There's no approval step on the device and +no automatic regeneration, so issue a fresh code from the More screen for each new browser. See [LAN_PERMISSION_AND_TROUBLESHOOTING.md](LAN_PERMISSION_AND_TROUBLESHOOTING.md#session-codes-session_code_expired--session_code_invalid). -**Where do I report a security issue?** Not in a public issue — see [SECURITY.md](../SECURITY.md). +**Where do I report a security issue?** Privately, never in a public issue. +[SECURITY.md](../SECURITY.md) has the details. **Something else is broken.** Check the module-specific guide first ( [NETWORK_INSPECTOR.md](NETWORK_INSPECTOR.md), [WEBSOCKET_INSPECTOR.md](WEBSOCKET_INSPECTOR.md), [PUSH.md](PUSH.md), [COMPOSER_AND_MOCKS.md](COMPOSER_AND_MOCKS.md), -[STATE_AND_FLAGS.md](STATE_AND_FLAGS.md)) — each documents the exact capture/redaction bounds and -known gaps for that feature. +[STATE_AND_FLAGS.md](STATE_AND_FLAGS.md)). Each one spells out the exact capture and redaction +bounds for that feature, plus its known gaps. diff --git a/docs/GETTING_STARTED_COMPOSE.md b/docs/GETTING_STARTED_COMPOSE.md index ee02fdf..e652d62 100644 --- a/docs/GETTING_STARTED_COMPOSE.md +++ b/docs/GETTING_STARTED_COMPOSE.md @@ -1,6 +1,9 @@ -# Getting started - Compose +# Getting started: Compose -1. Apply the production-safety plugin and split the dependency by variant. +About five minutes, most of it waiting for Gradle. By the end you'll have the inspector opening on +your device and the dashboard reachable from a browser. + +1. Apply the production-safety plugin and split the dependency by variant. ```kotlin plugins { @@ -83,8 +86,15 @@ setContent { } ``` -5. Tap Start — the panel now shows the bound address (e.g. `DevConsole server is running at 192.168.0.15:8080`) - — then open that address (or the connect URL from `StartResult.Started.access.connectUrl`) in a - browser on the same machine (or `adb forward tcp:8080 tcp:8080` first if the device isn't local). +5. Tap Start. The panel shows the bound address, something like `DevConsole server is running at + 192.168.0.15:8080`. Open that address in a browser, or use the connect URL from + `StartResult.Started.access.connectUrl`. If the device isn't local, run + `adb forward tcp:8080 tcp:8080` first. + +For a full working example, [`samples/compose-app`](../samples/compose-app/src/main/kotlin/io/devconsole/sample/compose/MainActivity.kt) +has one button per capability: network and WebSocket capture, mocks, push simulation, a feature +flag, and a state provider. -The full working example — network and WebSocket capture, mocks, push simulation, a feature flag, and a state provider, one button per capability — is [`samples/compose-app`](../samples/compose-app/src/main/kotlin/io/devconsole/sample/compose/MainActivity.kt). See [NETWORK_INSPECTOR.md](NETWORK_INSPECTOR.md), [WEBSOCKET_INSPECTOR.md](WEBSOCKET_INSPECTOR.md), [COMPOSER_AND_MOCKS.md](COMPOSER_AND_MOCKS.md), [PUSH.md](PUSH.md), and [STATE_AND_FLAGS.md](STATE_AND_FLAGS.md) for how each piece works. +For how each piece works, see [NETWORK_INSPECTOR.md](NETWORK_INSPECTOR.md), +[WEBSOCKET_INSPECTOR.md](WEBSOCKET_INSPECTOR.md), [COMPOSER_AND_MOCKS.md](COMPOSER_AND_MOCKS.md), +[PUSH.md](PUSH.md), and [STATE_AND_FLAGS.md](STATE_AND_FLAGS.md). diff --git a/docs/GETTING_STARTED_XML_JAVA.md b/docs/GETTING_STARTED_XML_JAVA.md index 49fda02..a951bc7 100644 --- a/docs/GETTING_STARTED_XML_JAVA.md +++ b/docs/GETTING_STARTED_XML_JAVA.md @@ -1,7 +1,8 @@ -# Getting started - XML/Java +# Getting started: XML / Java -DevConsole's public facade is a Kotlin `object`, but every method is annotated `@JvmStatic` (and the -async variants are `@JvmOverloads`), so it reads like a plain Java utility class from Java code. +DevConsole's public facade is a Kotlin `object`, but every method carries `@JvmStatic` and the async +variants carry `@JvmOverloads`. From Java it reads like an ordinary utility class, and you never +touch a coroutine: the `...Async` variants take a callback instead. 1. Apply the production-safety plugin and split the dependency by variant (same `build.gradle.kts` shape as the Kotlin guide — see [GETTING_STARTED_XML_KOTLIN.md](GETTING_STARTED_XML_KOTLIN.md) diff --git a/docs/GETTING_STARTED_XML_KOTLIN.md b/docs/GETTING_STARTED_XML_KOTLIN.md index d3986a8..52d31b9 100644 --- a/docs/GETTING_STARTED_XML_KOTLIN.md +++ b/docs/GETTING_STARTED_XML_KOTLIN.md @@ -1,6 +1,9 @@ -# Getting started - XML/Kotlin +# Getting started: XML / Kotlin -1. Apply the production-safety plugin and split the dependency by variant. +No Compose required. The inspector ships as an Activity, and the launcher panel is a plain `View`, +so a Views-based host gets exactly what a Compose one does. + +1. Apply the production-safety plugin and split the dependency by variant. ```kotlin plugins { diff --git a/docs/MAVEN_PUBLISHING.md b/docs/MAVEN_PUBLISHING.md index 384b696..cf7b052 100644 --- a/docs/MAVEN_PUBLISHING.md +++ b/docs/MAVEN_PUBLISHING.md @@ -48,7 +48,7 @@ your local `~/.gradle/gradle.properties`. Central's release path does **not** accept `-SNAPSHOT` versions. Before the first real publish, change `SDK_VERSION` in `build-logic/convention-publishing/src/main/kotlin/io/devconsole/buildlogic/PublishingConventionPlugin.kt` -(and `version` in `gradle-plugin/build.gradle.kts`) to a real version, e.g. `1.0.1`. +(and `version` in `gradle-plugin/build.gradle.kts`) to a real version, e.g. `1.1.1`. **Locally:** @@ -103,3 +103,20 @@ dependencies { See [BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md](BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md) for what the plugin enforces about that split. + +## JitPack + +Nothing to run: JitPack builds a ref on first request and serves the result under the group +`com.github.devconsole-android.DevConsole`. `jitpack.yml` pins the JDK to 17 and otherwise leaves +JitPack's default command alone — that default already passes `-xtest -xlint +-xsignMavenPublication`, so overriding it with an `install:` block would silently start running the +full unit suite on every consumer-triggered build. + +Because JitPack skips the signing *task* but Gradle still validates the publication, a publication +that registers `.asc` artifacts fails there with "artifact file does not exist". That is why +`PublishingConventionPlugin` calls `signAllPublications()` only when a key is configured — the same +condition that lets a contributor run `publishToMavenLocal` without one. + +Only the 31 library modules are served; `gradle-plugin` is an `includeBuild` and is not among them, +so JitPack consumers use plain coordinates rather than the plugin. Check a build at +`https://jitpack.io/api/builds/com.github.devconsole-android/DevConsole`. diff --git a/docs/NETWORK_ADAPTERS.md b/docs/NETWORK_ADAPTERS.md index 5e09794..235883e 100644 --- a/docs/NETWORK_ADAPTERS.md +++ b/docs/NETWORK_ADAPTERS.md @@ -91,8 +91,19 @@ against a 512 KiB cap: - Fully delivered under the cap → recorded complete, `bodyOmittedReason = null`. - Still flowing past the cap → the first 512 KiB is recorded, `bodyOmittedReason = "truncated"`, and `bodyLength` carries the true total the host received, not just the captured prefix. -- Closed by the host before EOF (an early `response.close()`, a cancelled call) → whatever was - delivered by then is recorded, `bodyOmittedReason = "partial"`. +- Closed by the host before EOF (an early `response.close()`, a call site that reads only the + status code, a parser that stops at the end of the value it wanted) → the tee **drains what the + host left behind** before completing the close, so the body is still recorded whole with + `bodyOmittedReason = null`. The drain is bounded twice over: it stops at the same 512 KiB cap, + and it holds `close()` for at most 300 ms — the same bounded-drain-on-close OkHttp itself + performs to decide whether an abandoned connection is worth reusing. Only when that budget runs + out (a live stream abandoned mid-flight, a read failure) is the fragment recorded with + `bodyOmittedReason = "partial"`, and a body no bytes at all were recovered from is recorded with + no body rather than an empty one. + +That drain is what keeps capture independent of how much of the body the host wanted: a response +with a `Content-Length` is captured whole whether or not the host reads it, and one without a +`Content-Length` now behaves the same way. `text/event-stream` responses are the one exception: they're still recorded metadata-only (`bodyOmittedReason = "streaming"`) immediately, without teeing — a real SSE feed is for all diff --git a/docs/PROTOCOL_REFERENCE.md b/docs/PROTOCOL_REFERENCE.md index fe0b5c1..ed63770 100644 --- a/docs/PROTOCOL_REFERENCE.md +++ b/docs/PROTOCOL_REFERENCE.md @@ -25,6 +25,15 @@ protocol change. - **Access levels:** none. Every authenticated session is equivalent (`auth` in the tables below means "any live session"); mutating routes additionally gate on the host's `EditingCapabilities` flags (`mocks`, `captureRules`, `preferences`, `database`, `files`), not on a session-level role. +- **Request-body content types.** Routes that read a form body (`POST /api/v1/push/simulate`, the + `POST` halves of `/api/v1/network/har` and `/api/v1/network/postman`, `POST /api/v1/exports`, + `POST /api/v1/preferences/{file}`, …) need + `Content-Type: application/x-www-form-urlencoded`; routes that read a raw scalar + (`POST /api/v1/flags/{key}`, the `/enabled` toggles) read the body as text. A form route sent the + wrong media type — JSON, or no `Content-Type` at all — answers `400 VALIDATION_FAILED` (Ktor + reports it as a failed content transformation); the rarer typed media-type rejection answers `415 + UNSUPPORTED_MEDIA_TYPE`. Neither is reported as a `500`, so an `INTERNAL_ERROR` from this server + always means a genuine server-side fault worth reporting. ## 1. Host allowlist and rate limiting @@ -176,7 +185,9 @@ actually end up in the Postman collection body. ### Mocks -`GET /api/v1/mocks` (enabled flag), `POST /api/v1/mocks/disable-all` (auth), `GET +`GET /api/v1/mocks` (enabled flag), `POST /api/v1/mocks/disable-all` (auth), `POST +/api/v1/mocks/enabled` (auth + `mocks` capability — raw-text `"true"`/`"false"` body, returns the +resulting `{"enabled":…}`), `GET /api/v1/mocks/rules`, `GET /api/v1/mocks/conflicts`, `POST /api/v1/mocks/rules` (auth — id must match `[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}`, status `100..599`), `DELETE /api/v1/mocks/rules/{id}` (auth). **Quirk:** `POST /api/v1/mocks/rules` can only ever create a @@ -185,6 +196,11 @@ override, template response, connection failure, passthrough) but they're only r app registering rules directly against the engine, not over HTTP. `GET .../rules`'s `statusCode` field is `null` for any rule that isn't a `StaticResponse`. +`disable-all` and `enabled` differ in more than direction: turning mocking *off* never needs the +`mocks` editing capability (falling back to real traffic is always allowed), while turning it back +*on* does, since it changes how the host app behaves. A host that publishes rules read-only can +therefore disable mocking from the browser but not re-enable it. + ### Feature flags `GET /api/v1/flags` (adds `type` — `BOOLEAN` or `STRING` — and `allowedValues` per flag), `POST diff --git a/docs/README.md b/docs/README.md index d672960..c7fc3b0 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,5 +1,8 @@ # Documentation +Everything below assumes you've already done the [README](../README.md) quick start. If you only +read one page here, make it the threat model, especially before you put the dashboard on your LAN. + **Start here** - [Threat model and safe operation](THREAT_MODEL.md) — read before turning on LAN mode diff --git a/docs/images/dashboard-network.png b/docs/images/dashboard-network.png new file mode 100644 index 0000000..1196406 Binary files /dev/null and b/docs/images/dashboard-network.png differ diff --git a/docs/images/dashboard-web.png b/docs/images/dashboard-web.png index 8a8ad57..c6820f5 100644 Binary files a/docs/images/dashboard-web.png and b/docs/images/dashboard-web.png differ diff --git a/docs/images/inspector-android.png b/docs/images/inspector-android.png index 1b14f7a..6fe4654 100644 Binary files a/docs/images/inspector-android.png and b/docs/images/inspector-android.png differ diff --git a/docs/images/inspector-more-server.png b/docs/images/inspector-more-server.png index 44d224e..24ab6f1 100644 Binary files a/docs/images/inspector-more-server.png and b/docs/images/inspector-more-server.png differ diff --git a/docs/superpowers/plans/2026-08-11-android-inspector-redesign.md b/docs/superpowers/plans/2026-08-11-android-inspector-redesign.md new file mode 100644 index 0000000..0601978 --- /dev/null +++ b/docs/superpowers/plans/2026-08-11-android-inspector-redesign.md @@ -0,0 +1,446 @@ +# Android Inspector Redesign Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Make the Compose inspector a native, adaptive Material 3 sibling of the redesigned web workbench using graphite/cobalt roles and platform-aware theming. + +**Architecture:** Keep `InspectorViewModel`, `InspectorState`, and `InspectorAction` unchanged. Add a small theme-preference boundary, move the custom theme onto the approved Material roles, make the workspace choose navigation bar or rail from available width, and replace card-shaped shared primitives with standard list/section composition. + +**Tech Stack:** Kotlin, Jetpack Compose, Material 3, Android `SharedPreferences`, JUnit, Gradle Android library build. + +--- + +## File map + +- Create `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorThemePreference.kt`: persisted explicit theme override. +- Create `sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorThemePreferenceTest.kt`: pure store/selection tests. +- Create `sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorAdaptiveLayoutTest.kt`: width-to-navigation contract. +- Modify `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/DevConsoleTheme.kt`: graphite/cobalt roles and Material typography/shapes. +- Modify `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/DevConsoleWorkspace.kt`: system theme, persisted override, adaptive navigation shell. +- Modify `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorNavComponents.kt`: Material top app bar, search, filters, navigation bar/rail. +- Modify `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorUiComponents.kt`: replace terminal-card primitives with flat sections. +- Modify `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorListComponents.kt`: edge-to-edge rows and sentence-case labels. +- Modify `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorHeroComponents.kt`: convert oversized heroes to compact summaries. +- Modify `InspectorObserveScreen.kt`, `InspectorControlScreen.kt`, `InspectorDataScreen.kt`, and `InspectorMoreScreen.kt`: adopt native shared primitives. +- Modify detail/editor files under `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/`: standard app bars, sheets, dialogs, and lists. +- Modify `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDesignSystemPreviews.kt`: compact/expanded and dark/light preview matrix. +- Modify `sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/DevConsoleWorkspaceTest.kt`: navigation and destination regression coverage. +- Modify `DESIGN.md` and regenerate `.impeccable/design.json` after both platform plans pass. + +### Task 1: Add a persisted theme-preference boundary + +**Files:** +- Create: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorThemePreference.kt` +- Create: `sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorThemePreferenceTest.kt` + +- [ ] **Step 1: Write the failing pure preference tests** + +```kotlin +package io.devconsole.ui.compose + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class InspectorThemePreferenceTest { + @Test + fun `missing override delegates to system theme`() { + val store = FakeThemePreferenceStore() + assertNull(store.readOverride()) + assertEquals(true, resolveDarkTheme(store.readOverride(), systemDark = true)) + assertEquals(false, resolveDarkTheme(store.readOverride(), systemDark = false)) + } + + @Test + fun `explicit override wins and survives a new store read`() { + val values = mutableMapOf() + val store = FakeThemePreferenceStore(values) + store.writeOverride(true) + + assertEquals(true, FakeThemePreferenceStore(values).readOverride()) + assertEquals(true, resolveDarkTheme(store.readOverride(), systemDark = false)) + } +} + +private class FakeThemePreferenceStore( + private val values: MutableMap = mutableMapOf(), +) : InspectorThemePreferenceStore { + override fun readOverride(): Boolean? = values["dark"] + override fun writeOverride(dark: Boolean) { values["dark"] = dark } +} +``` + +- [ ] **Step 2: Run the test and verify it fails** + +```bash +./gradlew :sdk:ui-compose:testDebugUnitTest --tests io.devconsole.ui.compose.InspectorThemePreferenceTest +``` + +Expected: FAIL because `InspectorThemePreferenceStore` and `resolveDarkTheme` do not exist. + +- [ ] **Step 3: Implement the preference boundary** + +```kotlin +package io.devconsole.ui.compose + +import android.content.Context + +internal interface InspectorThemePreferenceStore { + fun readOverride(): Boolean? + fun writeOverride(dark: Boolean) +} + +internal class SharedPreferencesInspectorThemeStore( + context: Context, +) : InspectorThemePreferenceStore { + private val preferences = + context.getSharedPreferences("devconsole.ui", Context.MODE_PRIVATE) + + override fun readOverride(): Boolean? = + if (preferences.contains(KEY_DARK_THEME)) preferences.getBoolean(KEY_DARK_THEME, false) else null + + override fun writeOverride(dark: Boolean) { + preferences.edit().putBoolean(KEY_DARK_THEME, dark).apply() + } + + private companion object { + const val KEY_DARK_THEME = "dark_theme_override" + } +} + +internal fun resolveDarkTheme( + override: Boolean?, + systemDark: Boolean, +): Boolean = override ?: systemDark +``` + +- [ ] **Step 4: Run the test and commit** + +Expected: PASS. + +```bash +git add sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorThemePreference.kt sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorThemePreferenceTest.kt +git commit -m "feat(compose): persist explicit theme choice" +``` + +### Task 2: Replace the Compose theme foundation + +**Files:** +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/DevConsoleTheme.kt` +- Test: `sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorThemePreferenceTest.kt` + +- [ ] **Step 1: Replace the old signal palette** + +Use the approved dark roles: + +```kotlin +private val DarkPrimary = Color(0xFF72A7FF) +private val DarkError = Color(0xFFFF7B72) +private val DarkWarning = Color(0xFFF2B66D) +private val DarkSecondary = Color(0xFF72C4CE) + +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), + signal = DarkPrimary, + signalInk = Color(0xFF0E1624), + warn = DarkWarning, + error = DarkError, + errorInk = Color(0xFF0E1624), + 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), + jsonNumber = DarkWarning, + jsonBoolean = Color(0xFFC7A7FF), + jsonNull = Color(0xFF969DA8), + jsonBraces = listOf(DarkPrimary, DarkWarning, DarkSecondary, Color(0xFFECEEF2), Color(0xFFC7A7FF)), + ) +``` + +Use the exact light roles from the approved spec: background `0xFFF7F8FA`, panel `0xFFFFFFFF`, raised `0xFFEEF1F5`, pressed `0xFFE4E8EE`, ink `0xFF1C1F24`, muted `0xFF68707B`, outline `0xFFD5D9E0`, strong outline `0xFFAAB1BC`, and primary `0xFF245DA8`. + +- [ ] **Step 2: Move bespoke type sizes onto Material roles** + +Pass a `Typography` to `MaterialTheme`. Map screen titles to `headlineSmall`, row titles to `bodyLarge` with monospace only where data-driven, subtitles to `bodySmall`, and structural labels to `labelMedium`. Remove `DevConsoleType.title`, `groupLabel`, and `heroValue` after all call sites migrate. + +Change `DevConsoleTheme`'s default to `isSystemInDarkTheme()` so isolated previews and direct component hosts also respect the platform when the workspace does not pass an explicit value. + +- [ ] **Step 3: Add restrained Material shapes** + +Pass: + +```kotlin +val DevConsoleShapes = Shapes( + extraSmall = RoundedCornerShape(4.dp), + small = RoundedCornerShape(6.dp), + medium = RoundedCornerShape(8.dp), + large = RoundedCornerShape(12.dp), + extraLarge = RoundedCornerShape(16.dp), +) +``` + +- [ ] **Step 4: Compile and commit** + +```bash +./gradlew :sdk:ui-compose:compileDebugKotlin +git add sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/DevConsoleTheme.kt +git commit -m "style(compose): adopt graphite cobalt theme" +``` + +Expected: compilation may still report removed `DevConsoleType` call sites; keep compatibility aliases until Tasks 5–7 migrate them, then remove the aliases. + +### Task 3: Define and test adaptive navigation selection + +**Files:** +- Create: `sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorAdaptiveLayoutTest.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/DevConsoleWorkspace.kt` + +- [ ] **Step 1: Write the failing width contract test** + +```kotlin +package io.devconsole.ui.compose + +import androidx.compose.ui.unit.dp +import org.junit.Assert.assertEquals +import org.junit.Test + +class InspectorAdaptiveLayoutTest { + @Test fun `compact width uses navigation bar`() { + assertEquals(InspectorNavigationLayout.Bar, inspectorNavigationLayout(599.dp)) + } + + @Test fun `expanded width uses navigation rail`() { + assertEquals(InspectorNavigationLayout.Rail, inspectorNavigationLayout(600.dp)) + } +} +``` + +- [ ] **Step 2: Run and verify failure** + +Run the focused `testDebugUnitTest` command with `InspectorAdaptiveLayoutTest`. + +Expected: FAIL because the layout type and resolver do not exist. + +- [ ] **Step 3: Add the pure layout resolver** + +```kotlin +internal enum class InspectorNavigationLayout { Bar, Rail } + +internal fun inspectorNavigationLayout(width: Dp): InspectorNavigationLayout = + if (width < 600.dp) InspectorNavigationLayout.Bar else InspectorNavigationLayout.Rail +``` + +- [ ] **Step 4: Run the focused test and commit** + +Expected: PASS. + +```bash +git add sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/DevConsoleWorkspace.kt sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorAdaptiveLayoutTest.kt +git commit -m "test(compose): define adaptive navigation boundary" +``` + +### Task 4: Build the platform-aware adaptive workspace shell + +**Files:** +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/DevConsoleWorkspace.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorNavComponents.kt` +- Modify: `sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/DevConsoleWorkspaceTest.kt` + +- [ ] **Step 1: Wire system theme and persisted override** + +In the public `DevConsoleWorkspace`, create `SharedPreferencesInspectorThemeStore(LocalContext.current.applicationContext)`, read the nullable override once, use `isSystemInDarkTheme()` as fallback, and persist the opposite of the resolved theme when the existing theme action is tapped. Hoist the resolved Boolean into `DevConsoleTheme`. + +- [ ] **Step 2: Replace the custom bottom row with Material navigation components** + +Implement `InspectorNavigationBar(items)` with `NavigationBar`/`NavigationBarItem` and `InspectorNavigationRail(items)` with `NavigationRail`/`NavigationRailItem`. Use Material selected state and cobalt `NavigationBarItemDefaults.colors`; do not paint a custom 64×32 pill. + +- [ ] **Step 3: Choose bar or rail from available width** + +Wrap the shell in `BoxWithConstraints`. Compact uses `Scaffold(bottomBar = ...)`; expanded uses a `Row` containing `InspectorNavigationRail` and `WorkspaceContent(Modifier.weight(1f))`. Continue hiding navigation while a full-screen detail overlay is open. + +- [ ] **Step 4: Extend the workspace regression test** + +Keep the four destination assertion and add: + +```kotlin +@Test +fun `adaptive boundary does not change destination order`() { + assertEquals( + listOf("Observe", "Control", "Data", "More"), + InspectorDestination.entries.map(InspectorDestination::label), + ) + assertEquals(InspectorNavigationLayout.Bar, inspectorNavigationLayout(360.dp)) + assertEquals(InspectorNavigationLayout.Rail, inspectorNavigationLayout(840.dp)) +} +``` + +- [ ] **Step 5: Run tests, compile, and commit** + +```bash +./gradlew :sdk:ui-compose:testDebugUnitTest :sdk:ui-compose:compileDebugKotlin +git add sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/DevConsoleWorkspace.kt sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorNavComponents.kt sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/DevConsoleWorkspaceTest.kt +git commit -m "feat(compose): add adaptive native navigation" +``` + +### Task 5: Replace custom navigation and shared UI primitives + +**Files:** +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorNavComponents.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorUiComponents.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorListComponents.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorHeroComponents.kt` + +- [ ] **Step 1: Replace `InspectorTopArea` with a Material top app bar composition** + +Keep the function signature temporarily to avoid a broad screen rewrite. Render `TopAppBar(title = { Text(title) }, actions = ...)`; move `subLine` to a single `bodySmall` line immediately below the bar only when non-empty. Use `IconButton` for actions and Material minimum interactive sizing. + +- [ ] **Step 2: Replace the pill search field** + +Render `InspectorSearchBar` as `OutlinedTextField` with `singleLine = true`, a leading search icon, Material `shape = MaterialTheme.shapes.medium`, and `TextFieldDefaults.colors` mapped from the theme. Keep its current state and callback API. + +- [ ] **Step 3: Replace terminal cards and uppercase labels** + +Rename `TerminalCard` to `InspectorSection` and implement it as a plain `Column` with optional top/bottom divider; migrate call sites before deleting the old name. Change `TerminalSectionLabel` and `GroupLabel` to sentence case and `MaterialTheme.typography.labelMedium`. + +- [ ] **Step 4: Flatten list rows** + +Remove rounded row containers and per-row shadows. Use `ListItem`, `HorizontalDivider`, or an equivalent `Row` with 48dp minimum height. Preserve semantic roles, selected state, click behavior, trailing actions, and monospaced data fields. + +- [ ] **Step 5: Compact hero components** + +Replace 40sp hero values and rounded hero cards with a `SummaryStrip` composed of aligned values and dividers. Preserve collapse/expand actions only where they reveal real additional data. + +- [ ] **Step 6: Compile and commit** + +```bash +./gradlew :sdk:ui-compose:compileDebugKotlin +git add sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorNavComponents.kt sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorUiComponents.kt sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorListComponents.kt sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorHeroComponents.kt +git commit -m "style(compose): replace terminal UI primitives" +``` + +### Task 6: Migrate Observe and Control + +**Files:** +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveScreen.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveTrafficTab.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveCrashesTab.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorControlScreen.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMockRuleEditor.kt` +- Test: `sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorCaptureCategoryGatingTest.kt` +- Test: `sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorMockRuleEditorTest.kt` + +- [ ] **Step 1: Convert Observe tabs and filters to Material roles** + +Keep Traffic, Sockets, Push, Logs, and Crashes gating and selection logic. Use `PrimaryTabRow` or the existing row with Material typography and a 2dp cobalt indicator. Replace oversized filter pills with compact `FilterChip` components. + +- [ ] **Step 2: Convert capture rows to edge-to-edge lists** + +Keep stable keys, selection, bookmarking, evidence actions, status codes, timestamps, and durations. Use dividers between rows and a quiet `surface2` selected background with a cobalt leading indicator. + +- [ ] **Step 3: Convert the evidence action to a standard extended FAB** + +Use Material `ExtendedFloatingActionButton`; show one FAB only when the current route has a valid evidence action. Preserve `EvidenceFabScrollClearance` based on the Material FAB height plus scaffold inset. + +- [ ] **Step 4: Convert Control sections and editor modality** + +Keep snackbar result handling, capability gating, toggle actions, delete confirmation, and editor draft preservation. Use `ModalBottomSheet` for the mock-rule editor when the form fits; use the existing full-screen editor on compact height or when IME pressure requires it. + +- [ ] **Step 5: Run affected tests and commit** + +```bash +./gradlew :sdk:ui-compose:testDebugUnitTest --tests io.devconsole.ui.compose.InspectorCaptureCategoryGatingTest --tests io.devconsole.ui.compose.InspectorMockRuleEditorTest +git add sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveScreen.kt sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveTrafficTab.kt sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveCrashesTab.kt sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorControlScreen.kt sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMockRuleEditor.kt +git commit -m "style(compose): rebuild observe and control" +``` + +### Task 7: Migrate Data, More, and detail surfaces + +**Files:** +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDataScreen.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMoreScreen.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorFilesSection.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDatabaseSection.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailScaffold.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailHeader.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailFooterBar.kt` + +- [ ] **Step 1: Convert Data to native sections and drill-ins** + +Use sentence-case section headings, `ListItem` rows, dividers, and standard trailing icons. Preserve inspection gating, file/database actions, IME padding, sharing, SQL execution, redaction, and read-only messaging. + +- [ ] **Step 2: Convert More to settings-shaped content** + +Use top-level server status as a compact summary, standard filled/outlined buttons for Start/Stop, `ListItem` export rows, and grouped sections for browser access, exports, retention, sessions, and SDK health. Remove rounded hero cards and decorative metric circles. + +- [ ] **Step 3: Standardize detail headers, footers, and predictive Back** + +Use `TopAppBar` with a navigation icon that calls the existing close/back callback. Keep code formatting, search, copy, share, pin, compare, and evidence actions. Replace the plain detail-overlay `BackHandler` with `androidx.activity.compose.PredictiveBackHandler`; collect its progress flow, keep the visual transition a reduced-motion-safe fade, and invoke the same close callback when the gesture completes. Nested text/code scroll remains independent. + +- [ ] **Step 4: Remove obsolete terminal types and card primitives** + +After all call sites compile, delete `TerminalType`, `DevConsoleType.title`, `DevConsoleType.groupLabel`, `DevConsoleType.heroValue`, and the compatibility `TerminalCard` wrapper. Keep `rowTitle` monospace only where the title is captured data. + +- [ ] **Step 5: Compile and commit** + +```bash +./gradlew :sdk:ui-compose:compileDebugKotlin +git add sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose +git commit -m "style(compose): migrate data more and details" +``` + +### Task 8: Add preview coverage and verify Android behavior + +**Files:** +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDesignSystemPreviews.kt` +- Modify: `sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/DevConsoleWorkspaceTest.kt` +- Modify: `DESIGN.md` +- Regenerate: `.impeccable/design.json` + +- [ ] **Step 1: Add bounded preview variants** + +Add dark/light compact previews for Observe, Control, Data, and More. Add at least one expanded-width workspace preview that shows the navigation rail and list/detail arrangement. Use representative populated, empty, error, and disabled-capability states already available in preview factories. + +- [ ] **Step 2: Run the complete UI module test and compile suite** + +```bash +./gradlew :sdk:ui-compose:testDebugUnitTest :sdk:ui-compose:compileDebugKotlin +``` + +Expected: BUILD SUCCESSFUL. + +- [ ] **Step 3: Run static legacy-style checks** + +```bash +git diff --check +rg -n 'B7ED65|427526|TerminalCard|TerminalType|RoundedCornerShape\(50\)|RoundedCornerShape\(99' sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose +``` + +Expected: no old green constants, obsolete terminal primitives, or percentage/pill corners remain except genuine status/filter chips documented inline. + +- [ ] **Step 4: Refresh the durable design artifacts** + +Replace `DESIGN.md` with the approved graphite/cobalt native-siblings design. Run Impeccable’s `document` workflow to regenerate `.impeccable/design.json` from the updated source of truth; verify the sidecar is no longer reported stale. + +- [ ] **Step 5: Capture the bounded Android visual set** + +Capture compact phone and expanded-width layouts in dark and light themes. Cover Observe list/detail, Control editor, Data drill-in, More server state, empty, error, and disabled-capability states. Perform one batched defect correction and at most one confirmation capture. + +- [ ] **Step 6: Commit documentation and final Android verification changes** + +```bash +git add DESIGN.md .impeccable/design.json sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDesignSystemPreviews.kt sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/DevConsoleWorkspaceTest.kt +git commit -m "docs: publish graphite cobalt design system" +``` diff --git a/docs/superpowers/plans/2026-08-11-web-dashboard-redesign.md b/docs/superpowers/plans/2026-08-11-web-dashboard-redesign.md new file mode 100644 index 0000000..a3a2e62 --- /dev/null +++ b/docs/superpowers/plans/2026-08-11-web-dashboard-redesign.md @@ -0,0 +1,471 @@ +# Web Dashboard Redesign Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Replace the terminal-green, card-heavy browser dashboard with the approved graphite-and-cobalt desktop workbench while preserving every dashboard behavior. + +**Architecture:** Keep the existing self-contained HTML/CSS/JavaScript delivery model and all functional element IDs. Establish the new visual contract in CSS custom properties, then migrate the shell and the three existing view archetypes: overview, split inspection, and form/configuration. Theme initialization becomes system-aware while explicit choices remain in `localStorage`. + +**Tech Stack:** Static HTML, CSS custom properties, vanilla JavaScript, Kotlin/JUnit asset-contract tests, Gradle Android library build. + +--- + +## File map + +- Modify `sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css`: graphite/cobalt tokens, flatter component rules, responsive behavior, accessibility states. +- Modify `sdk/server-ktor/src/main/resources/devconsole-web/index.html`: semantic shell and section classes while preserving IDs used by JavaScript. +- Modify `sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js`: system-aware theme initialization and accessible theme state; no API/data-flow changes. +- Modify `sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DashboardAssetsTest.kt`: static design, theme, CSP, and semantic contract tests. +- Modify `docs/DESIGN_SPEC.md`: replace web-facing green instrument-panel rules with the approved native-siblings web contract. +- Modify `DESIGN.md`: replace the obsolete shared visual system after both web and Android plans are complete. +- Regenerate `.impeccable/design.json`: refresh the sidecar from the final `DESIGN.md` after both plans are complete. + +### Task 1: Lock the new web contract with failing tests + +**Files:** +- Modify: `sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DashboardAssetsTest.kt` +- Test: `sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DashboardAssetsTest.kt` + +- [ ] **Step 1: Add palette and anti-slop asset assertions** + +Add these tests inside `DashboardAssetsTest`: + +```kotlin +@Test +fun `dashboard uses the graphite cobalt design tokens`() { + val css = DashboardAssets.css().lowercase() + + listOf( + "--ground: #111317", + "--panel: #171a20", + "--surface-2: #1d2129", + "--ink: #eceef2", + "--signal: #72a7ff", + ).forEach { token -> assertTrue("missing $token", css.contains(token)) } + + listOf("#b7ed65", "#427526", "terminal-green", "instrument panel").forEach { legacy -> + assertFalse("legacy design value remains: $legacy", css.contains(legacy)) + } +} + +@Test +fun `dashboard defaults to system theme and persists only explicit choice`() { + val script = DashboardAssets.js() + + assertTrue(script.contains("matchMedia('(prefers-color-scheme: dark)')")) + assertTrue(script.contains("devconsole-theme")) + assertTrue(script.contains("media.addEventListener('change'")) +} + +@Test +fun `dashboard shell keeps stable functional ids and semantic landmarks`() { + val dashboard = DashboardAssets.index() + + assertTrue(dashboard.contains("
{ + if (!storedTheme()) applyTheme(event.matches ? 'dark' : 'light'); + }); + } + + function toggleTheme() { + const next = currentTheme() === 'dark' ? 'light' : 'dark'; + try { + localStorage.setItem(THEME_STORAGE_KEY, next); + } catch { + /* storage unavailable */ + } + applyTheme(next); + } +``` + +- [ ] **Step 2: Make the HTML theme metadata neutral** + +Keep `` and do not add a hard-coded `data-theme` to ``. This prevents the document from claiming a fixed default before JavaScript resolves the system preference. + +- [ ] **Step 3: Run the focused tests** + +Run the Task 1 command. + +Expected: the system-theme test passes; the palette test still fails. + +- [ ] **Step 4: Commit the theme behavior** + +```bash +git add sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js sdk/server-ktor/src/main/resources/devconsole-web/index.html +git commit -m "feat(dashboard): follow system theme by default" +``` + +### Task 3: Replace the web token and type foundation + +**Files:** +- Modify: `sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css:1-180` +- Test: `sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DashboardAssetsTest.kt` + +- [ ] **Step 1: Replace the dark and light token blocks** + +Use these exact core roles; keep existing semantic variable names so downstream JavaScript-generated markup requires no color changes: + +```css +:root { + --font-ui: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; + --font-mono: ui-monospace, "SF Mono", Menlo, Consolas, monospace; + --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; + --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); + --json-key: #8cb8ff; + --json-string: #a9d6b9; + --json-number: #f2b66d; + --json-boolean: #c7a7ff; + --json-null: #969da8; + --json-brace-0: #72a7ff; + --json-brace-1: #f2b66d; + --json-brace-2: #72c4ce; + --json-brace-3: #eceef2; + --json-brace-4: #c7a7ff; + --elev-3: 0 8px 24px rgba(0, 0, 0, 0.28); +} + +:root[data-theme="light"] { + --ground: #f7f8fa; + --panel: #ffffff; + --surface-2: #eef1f5; + --surface-3: #e4e8ee; + --code-bg: #f2f4f7; + --ink: #1c1f24; + --muted: #68707b; + --text-3: #5f6874; + --line: #d5d9e0; + --border-strong: #aab1bc; + --signal: #245da8; + --signal-ink: #ffffff; + --warn: #8a5a12; + --error: #b33a31; + --put: #1e6d76; + --success: #2f7255; + --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); + --json-key: #245da8; + --json-string: #2f7255; + --json-number: #8a5a12; + --json-boolean: #6a46a5; + --json-null: #68707b; + --json-brace-0: #245da8; + --json-brace-1: #8a5a12; + --json-brace-2: #1e6d76; + --json-brace-3: #1c1f24; + --json-brace-4: #6a46a5; +} +``` + +- [ ] **Step 2: Normalize typography and motion** + +Set the body to `13px/1.5`, remove global letter spacing, change structural labels from forced uppercase to sentence case, and replace `fadein` translation with opacity-only `150ms`. Add: + +```css +@media (prefers-reduced-motion: reduce) { + *, *::before, *::after { + animation-duration: 0.01ms !important; + animation-iteration-count: 1 !important; + transition-duration: 0.01ms !important; + scroll-behavior: auto !important; + } +} +``` + +- [ ] **Step 3: Run the focused asset tests** + +Expected: all Task 1 tests pass. + +- [ ] **Step 4: Commit the token foundation** + +```bash +git add sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css +git commit -m "style(dashboard): adopt graphite cobalt foundation" +``` + +### Task 4: Simplify the web shell and rail + +**Files:** +- Modify: `sdk/server-ktor/src/main/resources/devconsole-web/index.html:60-139` +- Modify: `sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css:180-410` +- Test: `sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DashboardAssetsTest.kt` + +- [ ] **Step 1: Preserve shell IDs while simplifying visible copy** + +Keep `railToggle`, `themeToggle`, `modeToggle`, `viewNav`, every `view*` button ID, and every `navCount*` ID. Change group labels to sentence case and reduce topbar content to brand, device/build line, session status, live/pause control, and global actions. Do not remove the connection instruction carried by `sessionPill` on narrow widths. + +- [ ] **Step 2: Replace rail selection and shell styling** + +Implement the approved selection treatment: + +```css +.rail { flex-basis: 216px; width: 216px; padding: 10px 8px 24px; background: var(--panel); } +.rail-group { margin-top: 14px; } +.rail-group-label { padding: 0 10px 5px; color: var(--text-3); font-size: 11px; font-weight: 600; } +.rail-group-label .text { text-transform: none; letter-spacing: 0; } +.rail-group-label .rule { display: none; } +.rail button { height: 34px; border-radius: 6px; padding: 0 10px; } +.rail button.active, +.rail button[aria-current="page"] { background: var(--surface-2); color: var(--ink); } +.rail button.active::before, +.rail button[aria-current="page"]::before { top: 7px; bottom: 7px; background: var(--signal); } +``` + +Remove the dashed shortcut card border; render shortcuts as muted footer text. Keep the `<780px` icon-rail behavior and `rail-hidden` behavior. + +- [ ] **Step 3: Run `DashboardAssetsTest` and `git diff --check`** + +Expected: PASS; no whitespace errors. + +- [ ] **Step 4: Commit the shell migration** + +```bash +git add sdk/server-ktor/src/main/resources/devconsole-web/index.html sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css +git commit -m "style(dashboard): simplify shell and navigation" +``` + +### Task 5: Flatten overview and shared content primitives + +**Files:** +- Modify: `sdk/server-ktor/src/main/resources/devconsole-web/index.html:141-176` +- Modify: `sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css` +- Test: `sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DashboardAssetsTest.kt` + +- [ ] **Step 1: Convert overview metric cards into a shared strip** + +Retain all dynamic IDs. Wrap metrics in `.metric-strip`; each `.metric-card` becomes a separator-based `.metric` without a resting border, radius, or shadow. + +```css +.metric-strip { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); border-block: 1px solid var(--line); } +.metric-strip .metric { min-width: 0; padding: 12px 14px; border-right: 1px solid var(--line); } +.metric-strip .metric:last-child { border-right: 0; } +.metric-strip .metric-value { font: 600 20px/1.2 var(--font-mono); } +.metric-strip .metric-label { margin-top: 3px; color: var(--muted); font-size: 11px; } +``` + +- [ ] **Step 2: Make headings and status copy human** + +Use sentence-case headings in static HTML. Preserve server-provided values verbatim. Replace decorative section icons where the heading remains unambiguous without them; keep icons on actions and status where they improve scanning. + +- [ ] **Step 3: Flatten shared row and section rules** + +Use separators and selected-row backgrounds for `.row`, `.trace-row`, `.overview-*`, `.kv-row`, and `.metric-row`. Keep `data-id`, `role`, `tabindex`, selection, checkbox, and flag controls unchanged. + +- [ ] **Step 4: Run focused tests and commit** + +```bash +./gradlew :sdk:server-ktor:testDebugUnitTest --tests io.devconsole.server.ktor.DashboardAssetsTest +git add sdk/server-ktor/src/main/resources/devconsole-web/index.html sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css +git commit -m "style(dashboard): flatten overview hierarchy" +``` + +### Task 6: Migrate split inspection views + +**Files:** +- Modify: `sdk/server-ktor/src/main/resources/devconsole-web/index.html:177-456` +- Modify: `sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css` +- Verify: `sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js:2020-2210` + +- [ ] **Step 1: Preserve the split-view behavioral contract** + +Do not rename `.split-shell`, `.list-pane`, `.detail-pane`, `.splitter`, or any list/detail IDs. Keep separator ARIA, keyboard resizing, pointer capture, double-click reset, hidden-pane restoration, and detail scroll ownership intact. + +- [ ] **Step 2: Restyle split shells as workbench panes** + +```css +.split-shell { border: 1px solid var(--line); border-radius: 10px; background: var(--panel); } +.list-pane { background: var(--panel); } +.detail-pane { background: var(--ground); } +.splitter { width: 5px; background: var(--line); } +.splitter:hover, +.splitter:focus-visible, +.splitter.dragging { background: var(--signal); } +.row, .trace-row { border-radius: 0; border-inline: 0; border-top: 0; border-bottom: 1px solid var(--line); } +.row.selected, .trace-row.selected { background: var(--surface-2); box-shadow: inset 2px 0 var(--signal); } +``` + +- [ ] **Step 3: Normalize toolbars, filters, and search fields** + +Use 32–36px controls, 6px corners, and sentence-case labels. Restrict pill geometry to status/count chips. Keep the simple/advanced visibility contract and every filter ID. + +- [ ] **Step 4: Compress the Network request list into inline rows** + +Remove the visible Method, Path, Duration, and Status column-title strip from the left Network pane while retaining accessible context for assistive technology. Render each transaction as one compact scanning line: method, path (flexing), duration, status, and evidence action. Do not stack field titles above values. Preserve selection, checkboxes, flags, host visibility, virtualized list behavior, and the detail-pane contract. Let the left pane start narrower so the request inspector receives more space. + +- [ ] **Step 5: Exercise each split view manually** + +Open Timeline, Network, WebSockets, Push, and Crashes. For each: select a row, scroll long detail content, drag the splitter, resize with arrows, double-click reset, hide each pane with Home/End, and restore it. + +Expected: behavior matches the pre-redesign dashboard; only presentation changes. + +- [ ] **Step 6: Commit split views** + +```bash +git add sdk/server-ktor/src/main/resources/devconsole-web/index.html sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css +git commit -m "style(dashboard): rebuild inspection workbench" +``` + +### Task 7: Migrate form, configuration, and overlay surfaces + +**Files:** +- Modify: `sdk/server-ktor/src/main/resources/devconsole-web/index.html:457-719` +- Modify: `sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css` + +- [ ] **Step 1: Replace generic card-grid styling with semantic sections** + +Keep `.cards-grid`, `.card-shell`, `.card-shell-head`, and `.card-shell-body` as compatibility hooks, but restyle them so borders appear only around meaningful grouped tasks: + +```css +.cards-grid { gap: 18px 24px; } +.card-shell { border: 0; border-radius: 0; background: transparent; overflow: visible; } +.card-shell-head { min-height: 36px; padding: 0 0 8px; border-bottom: 1px solid var(--line); } +.card-shell-title { font-size: 14px; text-transform: none; letter-spacing: 0; } +.card-shell-body { padding: 14px 0 0; } +.card-shell[data-contained="true"] { padding: 16px; border: 1px solid var(--line); border-radius: 10px; background: var(--panel); } +``` + +Add `data-contained="true"` only to sections that form one bounded task, such as the request composer and modal-like editors. + +- [ ] **Step 2: Normalize inputs, dialogs, menus, banners, toasts, and empty states** + +Inputs use `code-bg`, a 6px radius, and cobalt focus. Dialogs and menus keep `--elev-3`; resting sections do not. Empty states use one icon, a sentence-case title, a concise explanation, and one next action. Error/warn banners keep semantic left accents without tinted full-card decoration. + +- [ ] **Step 3: Verify responsive and coarse-pointer rules** + +At 1180, 960, 780, 620, and 480px, verify every action remains reachable. Under `@media (pointer: coarse)`, ensure interactive targets reach at least 44 CSS px without increasing desktop row density. + +- [ ] **Step 4: Commit remaining surfaces** + +```bash +git add sdk/server-ktor/src/main/resources/devconsole-web/index.html sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css +git commit -m "style(dashboard): refine forms and state surfaces" +``` + +### Task 8: Document and verify the web redesign + +**Files:** +- Modify: `docs/DESIGN_SPEC.md` +- Test: `sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DashboardAssetsTest.kt` + +- [ ] **Step 1: Update the binding web design rules** + +Replace phosphor-green, forced-uppercase, card-grid, and dark-default statements with the approved graphite/cobalt roles, sentence-case hierarchy, flat sections, and system-aware theme behavior. Preserve CSP, stable-ID, split-pane, density, accessibility, and breakpoint constraints. + +- [ ] **Step 2: Run the complete server module verification** + +```bash +./gradlew :sdk:server-ktor:testDebugUnitTest :sdk:server-ktor:verifyDashboardAssets +``` + +Expected: BUILD SUCCESSFUL. + +- [ ] **Step 3: Run static checks** + +```bash +git diff --check +rg -n '#b7ed65|#427526|terminal-green|instrument panel' sdk/server-ktor/src/main/resources/devconsole-web docs/DESIGN_SPEC.md +``` + +Expected: `git diff --check` is silent; the legacy-design search returns no matches except historical migration text intentionally retained in changelog material outside these paths. + +- [ ] **Step 4: Capture the bounded web visual set** + +Capture desktop and narrow screenshots in dark and light themes, covering Overview, Network list/detail, Composer, an empty state, an error state, and a modal. Perform one batched defect correction and at most one confirmation capture. + +- [ ] **Step 5: Commit documentation and web verification changes** + +```bash +git add docs/DESIGN_SPEC.md sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DashboardAssetsTest.kt +git commit -m "docs(dashboard): record native sibling design" +``` diff --git a/docs/superpowers/specs/2026-08-11-cross-platform-ui-redesign-design.md b/docs/superpowers/specs/2026-08-11-cross-platform-ui-redesign-design.md new file mode 100644 index 0000000..b1287d2 --- /dev/null +++ b/docs/superpowers/specs/2026-08-11-cross-platform-ui-redesign-design.md @@ -0,0 +1,253 @@ +# DevConsole Cross-Platform UI Redesign + +Date: 2026-08-11 +Status: Approved design + +## Summary + +Redesign the browser dashboard and Jetpack Compose inspector as **native siblings**: they share a restrained visual identity, color roles, data typography, and interaction principles, while each follows the conventions of its platform. + +The browser remains a dense desktop workbench with rail navigation, tables, and resizable detail panes. Android becomes a clearly native Material 3 application with adaptive navigation, top app bars, edge-to-edge lists, system Back behavior, and platform-sized controls. The redesign preserves every existing capability and data flow. + +## Problem + +The current interfaces are internally consistent but feel synthetic and over-authored. Repeated rounded containers, pills, uppercase micro-labels, green-tinted surfaces, and decorative “instrument panel” language make ordinary controls look themed rather than natural. Android inherits too much of that desktop visual grammar, which makes it feel like a website compressed onto a phone. + +The redesign must remove those signals without making DevConsole generic, sparse, or consumer-oriented. + +## Goals + +- Make both surfaces feel designed by a product team rather than generated from a theme prompt. +- Preserve expert density, fast scanning, and the existing evidence-first workflow. +- Give web and Android a shared character without forcing identical layouts or components. +- Replace the phosphor-green identity with a neutral graphite and cobalt system. +- Follow the system light or dark preference initially and remember an explicit user override. +- Preserve all existing capture, filtering, detail, server, evidence, export, and persistence behavior. +- Meet WCAG 2.2 AA on web and Android accessibility conventions. + +## Non-goals + +- No backend, protocol, storage, capture, or export behavior changes. +- No navigation destination changes or feature removals. +- No external fonts, icon services, remote assets, inline scripts, or CSP changes. +- No large-scale rewrite of the dashboard JavaScript or Compose state management. +- No adoption of Android wallpaper-derived Dynamic Color; the fixed cobalt roles keep the product recognizable across devices. + +## Approved Direction + +### Native siblings + +The two surfaces share: + +- graphite neutral ramps; +- cobalt interaction color; +- restrained semantic status colors; +- system UI typography plus monospace for captured data; +- sentence-case labels; +- compact spacing and direct hierarchy; +- limited container shapes; +- clear empty, loading, error, and disabled states. + +They differ where platform convention demands it: + +- Web uses a persistent rail, toolbars, data tables, keyboard focus, hover, and a resizable split view. +- Android uses Material top app bars, navigation bar or navigation rail according to width, edge-to-edge content, list rows, system Back, and Android-native transient feedback. + +## Visual System + +### Color roles + +The palette is neutral first. Cobalt is rare and functional: selected, focused, live, linked, and primary. It is not used as decoration. + +Dark roles: + +- Background: `#111317` +- Panel: `#171A20` +- Raised surface: `#1D2129` +- Hover/pressed surface: `#242A34` +- Primary text: `#ECEEF2` +- Secondary text: `#969DA8` +- Outline: `#343A45` +- Strong outline: `#4A5260` +- Primary cobalt: `#72A7FF` +- On-primary: `#0E1624` + +Light roles: + +- Background: `#F7F8FA` +- Panel: `#FFFFFF` +- Raised surface: `#EEF1F5` +- Hover/pressed surface: `#E4E8EE` +- Primary text: `#1C1F24` +- Secondary text: `#68707B` +- Outline: `#D5D9E0` +- Strong outline: `#AAB1BC` +- Primary cobalt: `#245DA8` +- On-primary: `#FFFFFF` + +Semantic roles remain independent of the accent: + +- Error: coral red, never cobalt. +- Warning: amber, never cobalt. +- Success: muted green, used only when success itself matters. +- Informational and syntax colors may use teal, violet, or amber when their meaning is stable and accessible. + +All component colors must use web custom properties or Compose theme roles. Raw colors remain limited to the theme definitions and test fixtures. + +### Typography + +- Use the system UI stack on web and Material typography roles on Android. +- Use monospace only for captured or generated data: URLs, methods, status codes, timestamps, durations, payloads, file paths, IDs, and counters. +- Use sentence case for navigation, headings, field labels, buttons, and state messages. +- Reserve uppercase for genuinely conventional short data labels such as HTTP methods and compact table column headers. +- Use weight and spacing for hierarchy before increasing size. +- Android text must scale with user font settings; fixed custom sizes are replaced with Material roles wherever possible. + +### Shape and elevation + +- Inline controls use 6–8px corners on web and the nearest restrained Material shape on Android. +- Outer grouped containers may use 10–12px corners. +- Pills are reserved for compact filters or status chips whose content benefits from the shape. +- List rows, metrics, toolbar groups, and ordinary sections are not cards by default. +- Resting surfaces rely on tonal contrast and separators. Shadows are limited to detached overlays such as menus, dialogs, and sheets. + +### Spacing and density + +- Keep a 4px base rhythm on web. +- Preserve expert information density without crowding interactive controls. +- Use 48dp minimum Android touch targets and at least 8dp separation where adjacent actions could be confused. +- Remove decorative padding that exists only to make a container look card-like. + +## Web Dashboard + +### Shell and navigation + +- Keep the left rail and current destination hierarchy. +- Retain a compact desktop rail with sentence-case group and item labels. +- Active navigation uses a quiet raised surface plus a 2px cobalt indicator; it does not use a glowing green pill. +- Preserve compact-width rail collapse and keyboard navigation. +- Keep the top session bar, but simplify it to product identity, connected device/build context, session status, and global actions. + +### Content hierarchy + +- Each view begins with a title, a concise state summary, and view-level actions. +- Metrics are presented as a shared strip or aligned values rather than independent cards. +- Inspection views use data tables or aligned rows with stable columns. +- Form and configuration views use sections with headings and separators. A border surrounds a section only when it materially explains grouping. +- The current split-view behavior remains: list, draggable splitter, and detail pane on desktop; vertical stacking at narrower widths. + +### Controls + +- Search fields use normal compact input geometry rather than oversized rounded capsules. +- Filter chips remain only where quick toggling matters. They use restrained rounded rectangles and clear selected states. +- Buttons use filled, outlined, or text hierarchy. Only the primary action receives a cobalt fill. +- Badges are limited to status, method, count, or capability metadata. +- Focus is visible on every interactive element and never depends on color alone. + +## Android Inspector + +### Shell and navigation + +- Follow the system light or dark theme on first launch. Persist an explicit in-product override. +- Use Material `NavigationBar` for compact widths and `NavigationRail` for expanded widths. +- Preserve the four destinations and all capture-category gating. +- Use a Material top app bar for screen context and overflow actions. +- Honor status/navigation bar insets, IME insets, predictive Back, and system Back. + +### Content + +- Replace large nested rounded panels with edge-to-edge or lightly inset Material lists. +- Use list rows for traffic, sockets, logs, crashes, exports, database entries, and files. +- Use section headings and dividers for configuration and server state. +- Use standard Material controls for switches, segmented choices, buttons, dialogs, sheets, menus, and snackbars. +- Use a full-screen detail route only for information-heavy inspection. Use a sheet for focused, dismissible tasks such as editing a rule when the content fits. +- Preserve 48dp touch targets even when visible rows remain compact. + +### Responsive behavior + +- Compact phone widths use the navigation bar and single-pane routes. +- Expanded widths use a navigation rail and may show list/detail side by side where existing state supports it. +- Content never hides under system bars, cutouts, the keyboard, or navigation components. + +## Interaction and State Behavior + +- Existing view-model actions, dashboard event handlers, APIs, and stored state remain the source of truth. +- Theme initialization reads the platform preference; an explicit choice is stored and wins on later launches. +- Web selection opens the existing detail pane and preserves splitter behavior. +- Android selection navigates to a detail route or appropriate sheet and returns through system Back. +- Loading uses one restrained progress treatment at the affected scope; decorative skeleton card grids are not introduced. +- Empty states name what is absent and the next concrete action. +- Persistent errors appear beside the affected content. Android snackbars and web toasts are reserved for transient results. +- Disabled actions explain which capability, connection, or permission is missing. +- Destructive actions keep explicit confirmation where the current product requires it. +- Motion is short and functional, and honors reduced-motion or disabled-animation settings. + +## Data Flow and Architecture + +The redesign changes composition and styling, not business logic. + +- Dashboard DOM structure may be simplified to support tables, flatter sections, and semantic landmarks, but existing IDs/data attributes used by JavaScript remain stable or are migrated with corresponding tests. +- Dashboard API requests, WebSocket updates, selection state, filters, evidence tray operations, and exports remain unchanged. +- Compose routes continue to consume `InspectorState` and dispatch `InspectorAction` through `InspectorViewModel`. +- Reusable visual primitives belong in the existing design-system/theme and component files, not in screen-specific duplicates. +- Web custom properties and Compose color/typography/shape roles remain the single visual sources of truth for their platforms. + +## Accessibility + +Web requirements: + +- WCAG 2.2 AA color contrast. +- Visible 2px focus indicators with sufficient contrast. +- Keyboard access to navigation, filters, table rows, detail actions, dialogs, and menus. +- Semantic landmarks, headings, labels, table structure, and live regions where status changes require announcement. +- Coarse-pointer media rules for larger targets. + +Android requirements: + +- 48dp minimum touch targets. +- Material typography roles that follow font scaling. +- Meaningful content descriptions; decorative icons remain excluded from accessibility. +- Predictive Back and standard focus traversal. +- Correct semantics for navigation selection, filters, switches, expandable sections, and status. +- Reduced motion and adequate contrast in both themes. + +## Verification + +### Visual QA + +Capture and compare bounded screenshot sets after implementation: + +- Web: desktop and narrow widths, dark and light. +- Android: compact phone and expanded width, dark and light. +- Representative states: populated, empty, loading, error, disabled capability, selected row/detail, and overlay. + +Perform one batched defect pass, apply one batched correction, then run at most one confirmation pass. + +### Automated checks + +- Existing dashboard CSP and asset tests continue to pass. +- Existing dashboard interaction tests continue to pass, with selectors updated only where required by the approved structure. +- Add focused tests for system-theme initialization and explicit-theme persistence. +- Add or update Compose UI tests for adaptive navigation, Back behavior, target semantics, and primary list/detail interactions. +- Run affected Gradle unit tests and UI module compilation. +- Verify color contrast for the finalized role pairs. + +## Migration Plan + +1. Replace the existing instrument-panel design documentation with the approved native-siblings system and regenerate its Impeccable sidecar. +2. Update shared web tokens and shell primitives before migrating individual views. +3. Migrate representative web archetypes first: overview, split inspection, and configuration/card-grid views. Apply their shared patterns to remaining views. +4. Update the Compose theme and workspace shell, including platform-aware theme initialization and adaptive navigation. +5. Migrate representative Android archetypes, then apply shared rows, sections, filters, and details across remaining routes. +6. Run automated checks and the bounded cross-platform visual QA pass. + +## Success Criteria + +- Neither surface relies on repeated rounded cards, decorative uppercase labels, or green-tinted panels for hierarchy. +- Web reads as a purpose-built desktop debugging tool and keeps its rail, density, and split-pane productivity. +- Android reads as a native Material application at compact and expanded widths. +- Graphite surfaces dominate; cobalt is limited to interactive and live states. +- System theme is honored initially and an explicit override persists. +- Existing features and data behavior remain intact. +- Required contrast, focus, touch target, font scaling, Back, and reduced-motion behavior are verified. +- Dark/light screenshots for both platforms show a coherent family without forcing pixel-identical composition. diff --git a/gradle-plugin/build.gradle.kts b/gradle-plugin/build.gradle.kts index 3a3df7b..7fdce77 100644 --- a/gradle-plugin/build.gradle.kts +++ b/gradle-plugin/build.gradle.kts @@ -9,7 +9,7 @@ plugins { // Must share a top-level namespace with the plugin ID (a Plugin Portal requirement) and match // the SDK's Maven group. group = "io.github.devconsole-android" -version = "1.0.1" +version = "1.1.1" // Targets Java 17: this plugin JAR runs inside the Gradle daemon (AGP 8.13.0 // requires JDK 17) and compiles against com.android.tools.build:gradle:8.13.0, diff --git a/gradle-plugin/src/main/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPlugin.kt b/gradle-plugin/src/main/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPlugin.kt index 4b897a5..688336f 100644 --- a/gradle-plugin/src/main/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPlugin.kt +++ b/gradle-plugin/src/main/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPlugin.kt @@ -395,7 +395,7 @@ abstract class VerifyDevConsolePackagedArtifactTask : DefaultTask() { } } -private const val DEFAULT_SDK_VERSION = "1.0.1" +private const val DEFAULT_SDK_VERSION = "1.1.1" private const val DEVCONSOLE_GROUP = "io.github.devconsole-android" /** diff --git a/gradle-plugin/src/test/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPluginFunctionalTest.kt b/gradle-plugin/src/test/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPluginFunctionalTest.kt index 202d660..44fc621 100644 --- a/gradle-plugin/src/test/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPluginFunctionalTest.kt +++ b/gradle-plugin/src/test/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPluginFunctionalTest.kt @@ -837,12 +837,12 @@ class DevConsoleVariantPolicyPluginFunctionalTest { ) // release is PROTECTED by default, so auto-wire adds the noop core coordinate. The published - // coordinate is 1.0.1 -- the DEFAULT_SDK_VERSION must not point at a 1.0.1-SNAPSHOT that was + // coordinate is 1.1.1 -- the DEFAULT_SDK_VERSION must not point at a 1.1.1-SNAPSHOT that was // never published, which would make every zero-config release build fail to resolve. val result = runner("dependencies", "--configuration", "releaseImplementation").build() - assertTrue(result.output, result.output.contains("io.github.devconsole-android:devconsole-noop:1.0.1")) - assertTrue(result.output, !result.output.contains("1.0.1-SNAPSHOT")) + assertTrue(result.output, result.output.contains("io.github.devconsole-android:devconsole-noop:1.1.1")) + assertTrue(result.output, !result.output.contains("1.1.1-SNAPSHOT")) } @Test @@ -878,7 +878,7 @@ class DevConsoleVariantPolicyPluginFunctionalTest { extraBuildScript = """ dependencies { - add("debugImplementation", "io.github.devconsole-android:devconsole-ui-compose:1.0.1") + add("debugImplementation", "io.github.devconsole-android:devconsole-ui-compose:1.1.1") } """.trimIndent(), ) @@ -887,7 +887,7 @@ class DevConsoleVariantPolicyPluginFunctionalTest { // debug is ENABLED, so the core runtime ("devconsole") must still be auto-wired alongside the // host's add-on declaration -- the add-on alone does not count as declaring the core runtime. - assertTrue(result.output, result.output.contains("io.github.devconsole-android:devconsole:1.0.1")) + assertTrue(result.output, result.output.contains("io.github.devconsole-android:devconsole:1.1.1")) assertTrue(result.output, result.output.contains("io.github.devconsole-android:devconsole-ui-compose")) } } diff --git a/jitpack.yml b/jitpack.yml new file mode 100644 index 0000000..138f316 --- /dev/null +++ b/jitpack.yml @@ -0,0 +1,4 @@ +# JitPack's own default command already excludes tests, lint, and signing; only the JDK is pinned +# here, so its defaults keep applying. AGP 8.13 and jvmToolchain(17) both need 17. +jdk: + - openjdk17 diff --git a/samples/compose-app/build.gradle.kts b/samples/compose-app/build.gradle.kts index ee1a115..e206c4f 100644 --- a/samples/compose-app/build.gradle.kts +++ b/samples/compose-app/build.gradle.kts @@ -12,7 +12,7 @@ android { defaultConfig { applicationId = "io.devconsole.sample.compose" versionCode = 1 - versionName = "1.0.1-SNAPSHOT" + versionName = "1.1.1-SNAPSHOT" } } 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 3bb869a..80e96a1 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 @@ -542,6 +542,16 @@ class MainActivity : ComponentActivity() { } } + /** + * Issues one request through the sample's instrumented OkHttp client. + * + * The response body is read here rather than discarded, for the same reason the Ktor call below + * reads its own: reading it is what the card demonstrates. These endpoints answer without a + * `Content-Length` (gzipped, chunked), so the interceptor captures the body through its tee as + * this call consumes it -- the same bytes, counted once. Abandoning the body would still be + * captured (the tee drains what is left on close), but a sample that shows the body it received + * is the honest demonstration. + */ private suspend fun sendRequest( url: String, successLabel: String, @@ -550,7 +560,10 @@ class MainActivity : ComponentActivity() { requestCount.incrementAndGet() try { val request = Request.Builder().url(url).build() - instrumentedClient.newCall(request).execute().use { "$successLabel: ${it.code}" } + instrumentedClient.newCall(request).execute().use { response -> + val body = response.body?.string().orEmpty() + "$successLabel: ${response.code} (${body.length} chars)" + } } catch (cancellation: kotlinx.coroutines.CancellationException) { throw cancellation } catch (error: Exception) { diff --git a/samples/foundation-app/build.gradle.kts b/samples/foundation-app/build.gradle.kts index 7cd3fc5..4953b0d 100644 --- a/samples/foundation-app/build.gradle.kts +++ b/samples/foundation-app/build.gradle.kts @@ -31,6 +31,6 @@ android { defaultConfig { applicationId = "io.devconsole.sample" versionCode = 1 - versionName = "1.0.1-SNAPSHOT" + versionName = "1.1.1-SNAPSHOT" } } diff --git a/samples/views-java-app/build.gradle.kts b/samples/views-java-app/build.gradle.kts index 79e1d03..d5ccf05 100644 --- a/samples/views-java-app/build.gradle.kts +++ b/samples/views-java-app/build.gradle.kts @@ -9,7 +9,7 @@ android { defaultConfig { applicationId = "io.devconsole.sample.viewsjava" versionCode = 1 - versionName = "1.0.1-SNAPSHOT" + versionName = "1.1.1-SNAPSHOT" } } diff --git a/sdk/core/api/core.api b/sdk/core/api/core.api index 27cfec2..913495d 100644 --- a/sdk/core/api/core.api +++ b/sdk/core/api/core.api @@ -7,6 +7,8 @@ public final class io/devconsole/core/DevConsoleRuntime { public final fun initialize (Lio/devconsole/api/DevConsoleConfig;)Lio/devconsole/api/InitResult; public final fun initialize (Lio/devconsole/api/DevConsoleConfig;Z)Lio/devconsole/api/InitResult; public static synthetic fun initialize$default (Lio/devconsole/core/DevConsoleRuntime;Lio/devconsole/api/DevConsoleConfig;ZILjava/lang/Object;)Lio/devconsole/api/InitResult; + public final fun recordDroppedEvents (J)V + public final fun recordPublishedEvent ()V public final fun serverFailed (Ljava/lang/String;)V public final fun serverRequiresPermission ()V public final fun serverStarted ()V diff --git a/sdk/core/src/main/kotlin/io/devconsole/core/DevConsoleRuntime.kt b/sdk/core/src/main/kotlin/io/devconsole/core/DevConsoleRuntime.kt index f639e02..1ba00fa 100644 --- a/sdk/core/src/main/kotlin/io/devconsole/core/DevConsoleRuntime.kt +++ b/sdk/core/src/main/kotlin/io/devconsole/core/DevConsoleRuntime.kt @@ -112,6 +112,21 @@ class DevConsoleRuntime( if (state.value == DevConsoleState.Starting) transitionTo(DevConsoleState.Failed(message)) } + /** Counts one captured event onto [health]; platform capture funnels every emission through here. */ + @Synchronized + fun recordPublishedEvent() { + mutableHealth.value = + mutableHealth.value.copy(publishedEventCount = mutableHealth.value.publishedEventCount + 1) + } + + /** Counts events lost before reaching durable storage. */ + @Synchronized + fun recordDroppedEvents(count: Long) { + if (count <= 0) return + mutableHealth.value = + mutableHealth.value.copy(droppedEventCount = mutableHealth.value.droppedEventCount + count) + } + @Synchronized fun stop(reason: StopReason) { if (state.value == DevConsoleState.Stopped || state.value == DevConsoleState.Uninitialized) return diff --git a/sdk/core/src/test/kotlin/io/devconsole/core/DevConsoleRuntimeTest.kt b/sdk/core/src/test/kotlin/io/devconsole/core/DevConsoleRuntimeTest.kt index 10b9b26..3cc6068 100644 --- a/sdk/core/src/test/kotlin/io/devconsole/core/DevConsoleRuntimeTest.kt +++ b/sdk/core/src/test/kotlin/io/devconsole/core/DevConsoleRuntimeTest.kt @@ -110,4 +110,27 @@ class DevConsoleRuntimeTest { val result = runtime.initialize(DevConsoleConfig(eventBufferCapacity = 64)) assertTrue("expected Conflict, got $result", result is InitResult.Conflict) } + + /** Both surfaces reported a permanent 0 because nothing incremented these. */ + @Test + fun `published and dropped events accumulate onto health`() { + val runtime = enabledRuntime() + runtime.initialize(DevConsoleConfig.default()) + assertEquals(0L, runtime.health.value.publishedEventCount) + + repeat(3) { runtime.recordPublishedEvent() } + runtime.recordDroppedEvents(2) + + assertEquals(3L, runtime.health.value.publishedEventCount) + assertEquals(2L, runtime.health.value.droppedEventCount) + } + + @Test + fun `a non-positive drop count leaves health untouched`() { + val runtime = enabledRuntime() + runtime.recordDroppedEvents(0) + runtime.recordDroppedEvents(-5) + + assertEquals(0L, runtime.health.value.droppedEventCount) + } } diff --git a/sdk/full/src/main/kotlin/io/devconsole/CaptureTimeline.kt b/sdk/full/src/main/kotlin/io/devconsole/CaptureTimeline.kt index 53a92f0..0a02362 100644 --- a/sdk/full/src/main/kotlin/io/devconsole/CaptureTimeline.kt +++ b/sdk/full/src/main/kotlin/io/devconsole/CaptureTimeline.kt @@ -38,6 +38,8 @@ internal class CaptureTimelineBridge( private val streamHub: () -> EventStreamHub?, private val nextSequence: () -> Long, private val breadcrumbs: BreadcrumbRingBuffer? = null, + /** Counts the emission onto SDK health. */ + private val onPublished: () -> Unit = {}, ) { constructor( sessionId: String, @@ -108,6 +110,7 @@ internal class CaptureTimelineBridge( ), ) breadcrumbs?.record(Breadcrumb(wallTimeMs, pluginId, type, severity.ordinal, summary)) + onPublished() return id.toString() } } diff --git a/sdk/full/src/main/kotlin/io/devconsole/CrashCapture.kt b/sdk/full/src/main/kotlin/io/devconsole/CrashCapture.kt index 73c519a..208fe61 100644 --- a/sdk/full/src/main/kotlin/io/devconsole/CrashCapture.kt +++ b/sdk/full/src/main/kotlin/io/devconsole/CrashCapture.kt @@ -56,7 +56,7 @@ internal class CrashCapture( /** [CrashPolicy.maxStackChars] governs both kinds so an ANR dump is never re-truncated shorter. */ private val policy: () -> CrashPolicy = { CrashPolicy() }, /** - * D4's auto-flag: every crash and ANR is flagged into the evidence tray server-side at insert + * Auto-flag: every crash and ANR is flagged into the evidence tray server-side at insert * time, kind CRASH -- the one thing nobody should have to remember to click. Read inside * [persistNow]'s own timeout window, after the crash record's own insert, and failure-tolerant * on its own (see [autoFlagCrash]), so a missing/unavailable/over-quota evidence store can never diff --git a/sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt b/sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt index 6c771d1..8bf606b 100644 --- a/sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt +++ b/sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt @@ -149,6 +149,7 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { streamHub = { if (::serverEngine.isInitialized) serverEngine.streamHub else null }, nextSequence = timelineSequence::incrementAndGet, breadcrumbs = breadcrumbs, + onPublished = runtime::recordPublishedEvent, ) private val sessionMarkerRecorder = SessionMarkerRecorder(captureBridge) private var sessionMarkerMonitor: AndroidSessionMarkerMonitor? = null @@ -475,6 +476,7 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { scope = lifecycleScope, capacity = capacity, onDrop = { event, _ -> + runtime.recordDroppedEvents(1) if (reportingPersistenceDrop.compareAndSet(false, true)) { try { sessionMarkerMonitor?.dataDropped(event.pluginId, 1) diff --git a/sdk/network-okhttp/src/main/kotlin/io/devconsole/network/okhttp/DeferredResponseBodyCapture.kt b/sdk/network-okhttp/src/main/kotlin/io/devconsole/network/okhttp/DeferredResponseBodyCapture.kt index c41726f..8313e33 100644 --- a/sdk/network-okhttp/src/main/kotlin/io/devconsole/network/okhttp/DeferredResponseBodyCapture.kt +++ b/sdk/network-okhttp/src/main/kotlin/io/devconsole/network/okhttp/DeferredResponseBodyCapture.kt @@ -43,10 +43,13 @@ import java.util.concurrent.atomic.AtomicBoolean * The final record is emitted exactly once -- [recorded] is an atomic guard because a `close()` on * one thread can race the read that hits EOF on another -- and both record paths enqueue under * [lock] so the provisional record can never be enqueued after (and thus clobber) the final one. - * A close *before* EOF means the host abandoned the body mid-stream: the recorded body is only - * what was delivered up to that point, and is marked `bodyOmittedReason = "partial"` so a - * fragment is never presented as the complete response. All work is wrapped in `runCatching`, so - * nothing here can ever throw into the host's reads. + * A close *before* EOF means the host abandoned the body mid-stream; [TeeCapturingSource.close] + * first drains what is left within a bounded budget, so an abandoned body is normally still + * recorded whole. Only when that drain cannot finish -- deadline, read failure, or the capture cap + * -- is the record marked `bodyOmittedReason = "partial"` so a fragment is never presented as the + * complete response, and a body no bytes at all were recovered from is recorded with no body + * rather than an empty one. All work is wrapped in `runCatching`, so nothing here can ever throw + * into the host's reads. * * [phaseTimestamps] is the *live* per-call timing state handed out by * [DevConsoleOkHttpEventListenerFactory.phaseTimestampsFor], not a snapshot: by the time the body @@ -100,6 +103,14 @@ internal class DeferredResponseBodyCapture( fun onBodyClosed() = recordFinalTransactionOnce(reachedEndOfBody = false) + /** + * Whether pulling more bytes out of the body could still add anything to the capture: nothing + * has been recorded yet and the bounded buffer has room left. [TeeCapturingSource.close] asks + * before -- and between -- its drain reads, so a body the host abandoned is never read past + * what the capture can actually keep. + */ + fun wantsMoreBytes(): Boolean = !recorded.get() && synchronized(lock) { captured.size < maxCapturedBytes } + /** * Schedules the provisional `"streaming"` record described in the class kdoc. Called by the * interceptor right before it hands the teed response to the host; scheduling failures are @@ -145,9 +156,13 @@ internal class DeferredResponseBodyCapture( synchronized(lock) { val bodyBytes = captured.readByteArray() val capturedWasCapped = totalBytesDelivered > bodyBytes.size + // An abandoned body no bytes were recovered from is recorded as *no* body, not as a + // zero-length one: an empty preview alongside a 200 reads as "the server sent + // nothing", which is a different -- and wrong -- claim than "nothing was captured". + val recoveredNothing = !reachedEndOfBody && bodyBytes.isEmpty() val responseInput = responseTemplate - .copy(body = bodyBytes) + .copy(body = bodyBytes.takeUnless { recoveredNothing }) .withMetadata( responseTemplate.metadata.copy( bodyLength = totalBytesDelivered, @@ -191,6 +206,14 @@ internal class DeferredResponseBodyCapture( * first delivered untouched into the host's own sink by the delegate, then copied (bounded) as a * side effect. EOF and close each notify the capture so it can record at whichever happens first. * + * Capture must not depend on how much of the body the host happens to read. A host that reads only + * the status code and closes -- or a parser that stops at the end of the JSON value it wanted -- + * would otherwise leave DevConsole showing a blank or truncated body for exactly the responses + * OkHttp reports no `Content-Length` for (chunked, and every transparently-gzipped response), while + * the same response *with* a `Content-Length` is captured whole by the interceptor's eager + * `peekBody`. [close] closes that gap: whatever the host left behind is drained here first, within + * a bounded budget, so the recorded body is the whole response in every ordinary case. + * * A delegate read that throws propagates unchanged and notifies nothing -- the host's subsequent * `close()` (every well-behaved consumer closes a failed body) is what records the transaction with * whatever bytes had been delivered by then. [close] notifies in a `finally` so even a close failure @@ -215,9 +238,62 @@ internal class TeeCapturingSource( override fun close() { try { + // Isolated from the close itself: a drain that fails must still leave the host with the + // close it asked for, and still record whatever was captured before it failed. + runCatching { drainRemainderWithinBudget() } super.close() } finally { capture.onBodyClosed() } } + + /** + * Reads whatever the host left unread through this tee -- discarding the bytes, since only the + * capture still wants them -- so an abandoned body is recorded whole instead of as the fragment + * the host happened to consume. Doubly bounded: it stops as soon as the capture has no room + * left ([DeferredResponseBodyCapture.wantsMoreBytes], i.e. the same 512KB cap the tee already + * enforces) and it borrows OkHttp's own `Util.skipAll` deadline idiom -- tighten the source's + * deadline to at most [DRAIN_DEADLINE_MS], restore it afterwards -- so a body that is a live + * stream rather than a finished response cannot block the host's `close()` for longer than + * that. Overshooting the deadline surfaces as an `InterruptedIOException` from [read], caught by + * [close]'s `runCatching`, and the transaction is recorded `"partial"`. + * + * This is the same bounded-drain-on-close that OkHttp itself performs to decide whether an + * abandoned connection is worth reusing (`AbstractSource.discard`, 100ms), so on the common + * finite-response path these bytes were already going to be read off the socket regardless. + */ + private fun drainRemainderWithinBudget() { + if (!capture.wantsMoreBytes()) return + val timeout = timeout() + val startNs = System.nanoTime() + val originalRemainingNs = + if (timeout.hasDeadline()) timeout.deadlineNanoTime() - startNs else NO_DEADLINE + timeout.deadlineNanoTime(startNs + minOf(originalRemainingNs, DRAIN_DEADLINE_NS)) + try { + val discarded = Buffer() + while (capture.wantsMoreBytes() && read(discarded, DRAIN_SEGMENT_BYTES) != -1L) { + discarded.clear() + } + } finally { + if (originalRemainingNs == NO_DEADLINE) { + timeout.clearDeadline() + } else { + timeout.deadlineNanoTime(startNs + originalRemainingNs) + } + } + } + + private companion object { + /** + * Ceiling on how long a host `close()` may be held while the rest of an abandoned body is + * drained. Generous for a finite response still in flight on a slow connection, short + * enough that abandoning a long-lived stream stays effectively instant. + */ + const val DRAIN_DEADLINE_MS = 300L + const val DRAIN_DEADLINE_NS = DRAIN_DEADLINE_MS * 1_000_000L + const val DRAIN_SEGMENT_BYTES = 8L * 1024L + + /** Sentinel for "the source had no deadline of its own to preserve". */ + const val NO_DEADLINE = Long.MAX_VALUE + } } diff --git a/sdk/network-okhttp/src/main/kotlin/io/devconsole/network/okhttp/DevConsoleOkHttpInterceptor.kt b/sdk/network-okhttp/src/main/kotlin/io/devconsole/network/okhttp/DevConsoleOkHttpInterceptor.kt index b9af7fe..18aacb8 100644 --- a/sdk/network-okhttp/src/main/kotlin/io/devconsole/network/okhttp/DevConsoleOkHttpInterceptor.kt +++ b/sdk/network-okhttp/src/main/kotlin/io/devconsole/network/okhttp/DevConsoleOkHttpInterceptor.kt @@ -30,7 +30,10 @@ import okio.buffer * with its body wrapped in a bounded tee ([TeeCapturingSource]): bytes are copied as the host * consumes them -- up to [MAX_RESPONSE_PEEK_BYTES], pass-through-only past it -- and the transaction * is recorded once the body reaches EOF or is closed, whichever comes first, with `completedAt` set - * to that moment. INVARIANT: every response `chain.proceed` returns is recorded. The tee upholds it + * to that moment. A host that closes the body without draining it (reading only the status code, or + * a parser that stops at the end of the value it wanted) does not get a truncated capture: the tee + * drains what is left within a bounded budget on close, so a recorded body does not depend on how + * much of it the host read. INVARIANT: every response `chain.proceed` returns is recorded. The tee upholds it * for bodies that stay open past a short grace period -- a long-lived stream (NDJSON, long-poll) or * a body the host never reads and never closes -- with a provisional metadata-only `"streaming"` * record that the completion record later replaces in place; see [DeferredResponseBodyCapture]. 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 d599927..2fe5c28 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 @@ -344,7 +344,7 @@ class DevConsoleOkHttpInterceptorTest { } @Test - fun `records exactly once with a partial body when the host closes the teed body early`() { + fun `records exactly once with the whole body when the host closes the teed body early`() { val server = MockWebServer() server.start() try { @@ -369,18 +369,15 @@ class DevConsoleOkHttpInterceptorTest { .singleOrNull() ?.capture ?.response - ?.metadata - ?.body - ?.omittedReason == "partial" + ?.body is BodyPreview.Text }.single() val recordedResponse = transaction.capture.response!! assertEquals(200, recordedResponse.statusCode) - val capturedText = (recordedResponse.body as BodyPreview.Text).value - assertTrue("only bytes actually delivered to the host can be captured", capturedText.isNotEmpty()) - assertTrue(fullBody.startsWith(capturedText)) - // Closed before EOF: whatever fragment was delivered must never masquerade as the - // complete response body. - assertEquals("partial", recordedResponse.metadata.body.omittedReason) + // The host walked away after 5 bytes; the close-time drain must still recover the rest, + // so what DevConsole shows never depends on how much of the body the host wanted. + assertEquals(fullBody, (recordedResponse.body as BodyPreview.Text).value) + assertNull(recordedResponse.metadata.body.omittedReason) + assertEquals(fullBody.length.toLong(), recordedResponse.metadata.body.declaredLength) // Close raced EOF on nothing here, but the once-guard must still have recorded a single // transaction; give the async recorder a beat to surface any duplicate before asserting. Thread.sleep(100) @@ -390,6 +387,92 @@ class DevConsoleOkHttpInterceptorTest { } } + @Test + fun `captures the whole body of a response the host closes without reading at all`() { + val server = MockWebServer() + server.start() + try { + // The shape every sample and plenty of real call sites have: read the status code, + // close, never touch the body. Before the close-time drain this recorded an empty body + // for exactly the responses OkHttp reports no Content-Length for -- chunked, and every + // transparently-gzipped response -- while the same body *with* a Content-Length was + // captured whole by the eager peek. + val json = "{\"userId\":1,\"id\":1,\"title\":\"delectus aut autem\"}" + server.enqueue( + MockResponse() + .setChunkedBody(json, 16) + .addHeader("Content-Type", "application/json; charset=utf-8"), + ) + val transactions = + InMemoryNetworkTransactionStore(NetworkCursorCodec("network-cursor-key".encodeToByteArray())) + val client = clientRecordingTo(transactions) + + client.newCall(Request.Builder().url(server.url("/todos/1")).build()).execute().use { it.code } + + val transaction = + awaitTransactions(transactions) { list -> + list + .singleOrNull() + ?.capture + ?.response + ?.body is BodyPreview.Text + }.single() + val recordedResponse = transaction.capture.response!! + assertEquals(json, (recordedResponse.body as BodyPreview.Text).value) + assertNull(recordedResponse.metadata.body.omittedReason) + assertEquals(json.length.toLong(), recordedResponse.metadata.body.declaredLength) + assertNotNull(transaction.completedAtEpochMs) + } finally { + server.close() + } + } + + @Test + fun `bounds the drain so abandoning a live stream never stalls the host's close`() { + val server = MockWebServer() + server.start() + try { + // 8 bytes per 400ms: a stream that could never be drained inside the 300ms budget. + server.enqueue( + MockResponse() + .setChunkedBody("x".repeat(64 * 1024), 8) + .throttleBody(8, 400, TimeUnit.MILLISECONDS) + .addHeader("Content-Type", "application/x-ndjson"), + ) + val transactions = + InMemoryNetworkTransactionStore(NetworkCursorCodec("network-cursor-key".encodeToByteArray())) + val client = clientRecordingTo(transactions) + + val response = client.newCall(Request.Builder().url(server.url("/live")).build()).execute() + val closeStartedAtMs = System.currentTimeMillis() + response.close() + val closeDurationMs = System.currentTimeMillis() - closeStartedAtMs + + assertTrue( + "close() must return on the drain budget, not on the stream's own pace: ${closeDurationMs}ms", + closeDurationMs < 3_000L, + ) + val transaction = + awaitTransactions(transactions) { list -> + list + .singleOrNull() + ?.capture + ?.response + ?.metadata + ?.body + ?.omittedReason == "partial" + }.single() + // A drain that ran out of budget must never present its fragment as the whole response. + assertEquals( + "partial", + transaction.capture.response!! + .metadata.body.omittedReason, + ) + } finally { + server.close() + } + } + @Test fun `records a long-lived teed stream provisionally while it is still open`() { val server = MockWebServer() 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 b32e095..2b77233 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 @@ -126,6 +126,9 @@ import io.ktor.server.application.install import io.ktor.server.cio.CIO import io.ktor.server.engine.EmbeddedServer import io.ktor.server.engine.embeddedServer +import io.ktor.server.plugins.BadRequestException +import io.ktor.server.plugins.ContentTransformationException +import io.ktor.server.plugins.UnsupportedMediaTypeException import io.ktor.server.plugins.origin import io.ktor.server.request.httpMethod import io.ktor.server.request.receiveParameters @@ -148,7 +151,10 @@ import io.ktor.websocket.CloseReason import io.ktor.websocket.Frame import io.ktor.websocket.close import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineExceptionHandler +import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.delay import kotlinx.coroutines.flow.collect import kotlinx.coroutines.isActive @@ -532,6 +538,13 @@ fun Application.devConsoleModule( proceed() } catch (cancelled: CancellationException) { throw cancelled + } catch (mediaType: UnsupportedMediaTypeException) { + // A malformed request is the caller's mistake; answering 500 sends them hunting a server bug. + call.respondClientError(HttpStatusCode.UnsupportedMediaType, "UNSUPPORTED_MEDIA_TYPE", mediaType) + } catch (malformed: ContentTransformationException) { + call.respondClientError(HttpStatusCode.BadRequest, "VALIDATION_FAILED", malformed) + } catch (badRequest: BadRequestException) { + call.respondClientError(HttpStatusCode.BadRequest, "VALIDATION_FAILED", badRequest) } catch (throwable: Throwable) { call.application.environment.log.error( "Unhandled exception handling ${call.request.httpMethod.value} ${call.request.uri}", @@ -793,7 +806,7 @@ fun Application.devConsoleModule( contentType = io.ktor.http.ContentType.Application.Json, ) } - // Retained app-run history (D4's "previous-run banner": the Overview needs the most recent + // Retained app-run history (the "previous-run banner": the Overview needs the most recent // *non-active* run's StoredSessionStatus to know whether it CRASHED). Named "runs" rather // than reusing "session" -- that word is already spoken for by this dashboard's own bearer // session (see GET /api/v1/session just above) and would be ambiguous here. Read-only, bearer @@ -1284,6 +1297,45 @@ fun Application.devConsoleModule( commandAuditLog.recordControlSuccess(session.id, "mock.disable_all", "mocks") call.respondText("{\"enabled\":false}", contentType = io.ktor.http.ContentType.Application.Json) } + // The way back from `disable-all`. Capability-gated, unlike it: turning mocking ON changes + // how the app behaves. + post("/api/v1/mocks/enabled") { + val session = + call.mockRuleControlSession( + sessionAuthority, + commandAuditLog, + mocksEditable, + "mock.enabled", + "mocks", + ) ?: return@post + if (!categoryEnabled("mocks")) { + commandAuditLog.recordControlFailure(session.id, "mock.enabled", "mocks") + call.respondCategoryDisabled("mocks") + return@post + } + val enabled = + call + .receiveText() + .trim() + .trim('"') + .toBooleanStrictOrNull() + if (enabled == null) { + commandAuditLog.recordControlFailure(session.id, "mock.enabled", "mocks") + call.respondText("{\"code\":\"VALIDATION_FAILED\"}", status = HttpStatusCode.BadRequest) + return@post + } + mockEngine.setEnabled(enabled) + commandAuditLog.recordControlSuccess( + session.id, + "mock.enabled", + "mocks", + mapOf("enabled" to enabled.toString()), + ) + call.respondText( + "{\"enabled\":${mockEngine.isEnabled()}}", + contentType = io.ktor.http.ContentType.Application.Json, + ) + } get("/api/v1/mocks/rules") { if (sessionAuthority.bearerSession(call.request.headers[HttpHeaders.Authorization]) == null) { call.respondText("{\"code\":\"AUTH_REQUIRED\"}", status = HttpStatusCode.Unauthorized) @@ -3404,6 +3456,15 @@ class KtorLocalServerEngine( /** Public so the host facade can publish captured events into the live dashboard stream. */ val streamHub: EventStreamHub = EventStreamHub() + /** + * Container for the embedded server's own coroutines, carrying [asyncBindFailureHandler] so a + * failed asynchronous bind is handled instead of reaching the host app's crash handler. + * `SupervisorJob` so one server's failure never cancels a later one started after a fall-forward. + * Deliberately never cancelled -- [stop] tears the server down through Ktor's own lifecycle, and + * cancelling this scope instead would make a stopped engine unable to start again. + */ + private val serverScope = CoroutineScope(SupervisorJob() + asyncBindFailureHandler) + @Volatile private var engine: EmbeddedServer<*, *>? = null @@ -3521,49 +3582,55 @@ class KtorLocalServerEngine( val configuration = runtimeConfiguration val candidate = runCatching { - embeddedServer(CIO, host = endpoint.host, port = endpoint.port) { - devConsoleModule(sessionAuthority, sessionCodeAuthority) { - allowedHosts = setOf("localhost", endpoint.host) - this.networkTransactions = this@KtorLocalServerEngine.networkTransactions - this.socketStore = this@KtorLocalServerEngine.socketStore - this.pushStore = this@KtorLocalServerEngine.pushStore - this.stateRegistry = this@KtorLocalServerEngine.stateRegistry - this.featureFlags = configuration.featureFlags - this.featureFlagsEditable = configuration.featureFlagsEditable - this.mockEngine = this@KtorLocalServerEngine.mockEngine - this.mocksEditable = configuration.mocksEditable - this.captureRules = this@KtorLocalServerEngine.captureRules - this.captureRulesEditable = configuration.captureRulesEditable - this.preferencesInspector = this@KtorLocalServerEngine.preferencesInspector - this.preferencesEditable = configuration.preferencesEditable - this.databaseInspector = this@KtorLocalServerEngine.databaseInspector - this.databaseEditable = configuration.databaseEditable - this.fileInspector = this@KtorLocalServerEngine.fileInspector - this.filesEditable = configuration.filesEditable - this.timeline = this@KtorLocalServerEngine.timeline - this.metadata = this@KtorLocalServerEngine.metadata() - this.sdkHealth = this@KtorLocalServerEngine.sdkHealth - this.streamHub = this@KtorLocalServerEngine.streamHub - this.annotations = this@KtorLocalServerEngine.annotations - this.stateMutationsEnabled = configuration.stateMutationsEnabled - this.composerEnabled = configuration.composerEnabled - this.composerAllowedHosts = configuration.composerAllowedHosts - this.composerExecutor = this@KtorLocalServerEngine.composerExecutor - this.composerCollections = this@KtorLocalServerEngine.composerCollections - this.pushSimulator = this@KtorLocalServerEngine.pushSimulator - this.commandAuditLog = this@KtorLocalServerEngine.commandAuditLog - this.redactionPolicy = configuration.redactionPolicy - this.attachmentReader = this@KtorLocalServerEngine.attachmentReader - this.attachmentMetadataReader = this@KtorLocalServerEngine.attachmentMetadataReader - this.retainedCaptures = this@KtorLocalServerEngine.retainedCaptures - this.evidenceStore = this@KtorLocalServerEngine.evidenceStore - this.currentSessionId = this@KtorLocalServerEngine.currentSessionId - this.sessionSnapshotProvider = this@KtorLocalServerEngine.sessionSnapshotProvider - this.sessionsProvider = this@KtorLocalServerEngine.sessionsProvider - this.screenshotCapture = this@KtorLocalServerEngine.screenshotCapture - boundEndpoint = { currentEndpoint } - } - }.start(wait = false) + serverScope + .embeddedServer( + CIO, + host = endpoint.host, + port = endpoint.port, + parentCoroutineContext = asyncBindFailureHandler, + ) { + devConsoleModule(sessionAuthority, sessionCodeAuthority) { + allowedHosts = setOf("localhost", endpoint.host) + this.networkTransactions = this@KtorLocalServerEngine.networkTransactions + this.socketStore = this@KtorLocalServerEngine.socketStore + this.pushStore = this@KtorLocalServerEngine.pushStore + this.stateRegistry = this@KtorLocalServerEngine.stateRegistry + this.featureFlags = configuration.featureFlags + this.featureFlagsEditable = configuration.featureFlagsEditable + this.mockEngine = this@KtorLocalServerEngine.mockEngine + this.mocksEditable = configuration.mocksEditable + this.captureRules = this@KtorLocalServerEngine.captureRules + this.captureRulesEditable = configuration.captureRulesEditable + this.preferencesInspector = this@KtorLocalServerEngine.preferencesInspector + this.preferencesEditable = configuration.preferencesEditable + this.databaseInspector = this@KtorLocalServerEngine.databaseInspector + this.databaseEditable = configuration.databaseEditable + this.fileInspector = this@KtorLocalServerEngine.fileInspector + this.filesEditable = configuration.filesEditable + this.timeline = this@KtorLocalServerEngine.timeline + this.metadata = this@KtorLocalServerEngine.metadata() + this.sdkHealth = this@KtorLocalServerEngine.sdkHealth + this.streamHub = this@KtorLocalServerEngine.streamHub + this.annotations = this@KtorLocalServerEngine.annotations + this.stateMutationsEnabled = configuration.stateMutationsEnabled + this.composerEnabled = configuration.composerEnabled + this.composerAllowedHosts = configuration.composerAllowedHosts + this.composerExecutor = this@KtorLocalServerEngine.composerExecutor + this.composerCollections = this@KtorLocalServerEngine.composerCollections + this.pushSimulator = this@KtorLocalServerEngine.pushSimulator + this.commandAuditLog = this@KtorLocalServerEngine.commandAuditLog + this.redactionPolicy = configuration.redactionPolicy + this.attachmentReader = this@KtorLocalServerEngine.attachmentReader + this.attachmentMetadataReader = this@KtorLocalServerEngine.attachmentMetadataReader + this.retainedCaptures = this@KtorLocalServerEngine.retainedCaptures + this.evidenceStore = this@KtorLocalServerEngine.evidenceStore + this.currentSessionId = this@KtorLocalServerEngine.currentSessionId + this.sessionSnapshotProvider = this@KtorLocalServerEngine.sessionSnapshotProvider + this.sessionsProvider = this@KtorLocalServerEngine.sessionsProvider + this.screenshotCapture = this@KtorLocalServerEngine.screenshotCapture + boundEndpoint = { currentEndpoint } + } + }.start(wait = false) }.getOrNull() ?: return@forEach if (!isServerBound(endpoint.host, endpoint.port)) { @@ -3729,7 +3796,30 @@ private class SlidingWindowRateLimiter( } } +/** + * Keeps a *detected and recovered* bind failure from being reported as an unhandled crash. + * + * CIO binds asynchronously: `start(wait = false)` returns before the accept loop has the port, so + * losing the race between [isPortAvailable]'s probe and the real bind throws inside Ktor's own + * `httpServer` accept coroutine -- long after the `runCatching` around `start()` has returned. + * With nothing on the server's parent context that exception reaches the thread's default uncaught + * handler, which on Android is the *host app's* crash handler: a debug console taking down the app + * it exists to observe, for a condition it already handles correctly. + * + * [KtorLocalServerEngine.start] notices the failure the honest way -- `isServerBound` returns false + * and the loop falls forward to the next port -- so nothing is being hidden here that the engine + * does not already act on. The handler is deliberately silent rather than logging: this runs inside + * a host application, and the SDK's contract is that its own recovery is never the host's problem. + * + * Found via a flaky test: Gradle runs `testDebugUnitTest` and `testReleaseUnitTest` in parallel + * (`org.gradle.parallel=true`), both binding this module's fixed 8400..8419 range, and the loser's + * escaped BindException was landing on whichever unrelated test called `runTest` next as + * `UncaughtExceptionsBeforeTest`. + */ +private val asyncBindFailureHandler = CoroutineExceptionHandler { _, _ -> } + /** A best-effort preflight lets the engine advance over occupied ports before CIO starts its async bind. */ + private fun isPortAvailable( host: String, port: Int, @@ -3985,6 +4075,7 @@ private fun String.commandAuditIdentity(method: String): Pair? = "capture.rule.enabled" to removePrefix("/api/v1/capture-rules/").removeSuffix("/enabled") startsWith("/api/v1/capture-rules/") && method == "DELETE" -> "capture.rule.delete" to substringAfterLast('/') this == "/api/v1/mocks/disable-all" -> "mock.disable_all" to "mocks" + this == "/api/v1/mocks/enabled" -> "mock.enabled" to "mocks" this == "/api/v1/mocks/rules" && method == "POST" -> "mock.rule.upsert" to "rule" startsWith("/api/v1/mocks/rules/") && endsWith("/enabled") -> "mock.rule.enabled" to removePrefix("/api/v1/mocks/rules/").removeSuffix("/enabled") @@ -4963,6 +5054,20 @@ private suspend fun io.ktor.server.application.ApplicationCall.authorizeNetworkE return resolveNetworkExportTransactions(networkTransactions, bodyIds = ids) } +/** Answers a malformed request with the JSON envelope at a 4xx. Debug-logged: rejections are routine. */ +private suspend fun io.ktor.server.application.ApplicationCall.respondClientError( + status: HttpStatusCode, + code: String, + cause: Throwable, +) { + application.environment.log.debug( + "Rejected ${request.httpMethod.value} ${request.uri} as $code: ${cause.message}", + ) + if (!response.isCommitted) { + respondText("{\"code\":\"$code\"}", status = status, contentType = ContentType.Application.Json) + } +} + private fun io.ktor.server.application.ApplicationCall.networkTransactionQuery( defaultLimit: Int = NetworkTransactionQuery.DEFAULT_PAGE_LIMIT, ): NetworkTransactionQuery? { 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 5f6e220..d915e63 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 — terminal-green instrument panel. + DevConsole dashboard — graphite/cobalt diagnostic workbench. Dual theme via [data-theme] on ; dark is the default. ============================================================ */ @@ -7,82 +7,80 @@ --font-ui: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; --font-mono: ui-monospace, "SF Mono", Menlo, Consolas, monospace; - /* Dark terminal-green (default) */ - --ground: #0b0e0d; - --panel: #151a18; - --surface-2: #1b231e; - --surface-3: #212b24; - --code-bg: #10140f; - --ink: #e7e5d8; - --muted: #92968e; - --text-3: #7d8479; - --line: #344039; - --border-strong: #4a5a4f; - --signal: #b7ed65; - --signal-ink: #0b0e0d; - --warn: #f0b45c; - --error: #ff715e; - --put: #7fd0c9; - - --signal-soft: rgba(183, 237, 101, 0.11); - --error-soft: rgba(255, 113, 94, 0.13); - --warn-soft: rgba(240, 180, 92, 0.13); - --put-soft: rgba(127, 208, 201, 0.13); - - /* One Material elevation folded into a local token (constraints #2) — same in both themes. */ - --elev-3: 0 4px 8px 3px rgba(0, 0, 0, 0.15), 0 1px 3px rgba(0, 0, 0, 0.3); - - --json-key: #8fd6c4; - --json-string: #cfd8a6; - --json-number: #f0b45c; - --json-boolean: #b7ed65; - --json-null: #92968e; - --json-brace-0: #b7ed65; - --json-brace-1: #f0b45c; - --json-brace-2: #7fd0c9; - --json-brace-3: #e7e5d8; - --json-brace-4: #92968e; + /* 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); + + --elev-3: 0 8px 24px rgba(0, 0, 0, 0.28); + + --json-key: #8cb8ff; + --json-string: #a9d6b9; + --json-number: var(--warn); + --json-boolean: #c7a7ff; + --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; } :root[data-theme="light"] { - --ground: #f3f6ee; + --ground: #f7f8fa; --panel: #ffffff; - --surface-2: #eef2e6; - --surface-3: #e3e9d7; - --code-bg: #f6f8f1; - --ink: #182018; - --muted: #5b6459; - --text-3: #656c5f; - --line: #dde3d1; - --border-strong: #c3cdb4; - --signal: #427526; + --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; --signal-ink: #ffffff; - --warn: #93630a; - --error: #b6392a; - --put: #1f7a6c; - - --signal-soft: rgba(66, 117, 38, 0.1); - --error-soft: rgba(182, 57, 42, 0.1); - --warn-soft: rgba(147, 99, 10, 0.1); - --put-soft: rgba(31, 122, 108, 0.1); - - --json-key: #1f7a6c; - --json-string: #4a5b1f; - --json-number: #93630a; - /* Boolean + brace-0 track the light --signal, which was darkened #4f8f28 -> #427526 for AA - (the old hex measures 3.97:1 on #ffffff / 3.71:1 on --code-bg -- see §3.2's "do not lighten - back" note in docs/DESIGN_SPEC.md). */ - --json-boolean: #427526; - --json-null: #656c5f; - --json-brace-0: #427526; - --json-brace-1: #93630a; - --json-brace-2: #1f7a6c; - --json-brace-3: #182018; - /* --json-brace-4 was the missing step in the light ladder and fell through to the DARK theme's - value (#92968e, ~2.9:1 on white -- fails AA). Plum, not a tint of any tone already in the - ladder above: ~6.9:1 on #ffffff and ~6.4:1 on --code-bg (#f6f8f1), both comfortably past the - 4.5:1 AA floor the rest of this block is held to. See docs/DESIGN_SPEC.md §3.3. */ - --json-brace-4: #6a4c93; + --warn: #8a5a12; + --error: #b33a31; + --put: #1e6d76; + --success: #2f7255; + + --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); + + --json-key: var(--signal); + --json-string: var(--success); + --json-number: var(--warn); + --json-boolean: #6a46a5; + --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: #6a46a5; } * { box-sizing: border-box; } @@ -95,10 +93,10 @@ html { color-scheme: dark; } :root[data-theme="light"] { color-scheme: light; } -/* ---------------- Density tokens (task E6: Simple/Advanced mode) ---------------- +/* ---------------- Density tokens (Simple/Advanced mode) ---------------- Advanced keeps today's numbers byte-for-byte (that's the whole point: density is a feature for developers). Simple overrides the same four tokens under body.mode-simple so every consumer - below reads through a variable instead of a per-component override — E1's breakpoints and E6's + below reads through a variable instead of a per-component override — the responsive breakpoints and the density density then compose instead of fighting, since neither ever hard-codes the other's concern. Colour is untouched by either mode, so the AA contrast ratios in §3.1/3.2 apply unchanged. */ :root { @@ -122,8 +120,48 @@ body.mode-simple { --d-card-gap: 16px; } +/* ---------------- Spacing scale ---------------- + 4-unit base with 6 and 10 as the half-steps an 8-only scale misses: 2 4 6 8 10 12 16 20 24. + Everything below picks from it; 5px and 18px were the only strays and are gone. + + Deliberately a documented contract rather than a --sp-* token layer. The density block directly + above is the cautionary tale: --d-card-pad and --d-card-gap sat here declared and unread for + their whole life, so the mode they belong to only half worked. A spacing token nobody reads is + worse than a literal, because it reads as wired. Tokens here would need all ~120 spacing + declarations converted in one pass to be honest, and that buys no visual change -- so the scale + is enforced by review against this comment, and only the two tokens that already had a real + job (density, which genuinely varies at runtime) stay variables. + + Vertical rhythm inside a view: 16 above the title (.main-inner), 20 below it (.view-head), + 12 below the toolbar. The one generous interval is under the title, on purpose. */ + +/* ---------------- Type ramp ---------------- + Eight roles, smallest to largest. Each step is >=8% from its neighbour, which is the point: + the ramp used to carry eleven sizes, and three of them were the same role split across a + half-pixel -- .toolbar > button at 12px beside the base button rule at 12.5px, .stream-seg + button at 11px beside .seg button at 11.5px, .detail-group-label at 10px beside + .card-shell-badge at 10.5px. A half-pixel cannot express hierarchy; it only records that two + people sized the same thing on different days. + + 9.5 tag micro badge; always 700, almost always mono (.row-tag, .badge-pill) + 10.5 label uppercase structural label, column key, count (.list-head span, .row-badge) + 11.5 meta supporting text, small controls, kv data (.detail-fact, .seg button) + 12.5 body prose, form controls, code, mono payloads (.card-lede, input, .code-line) + 13 item entity names and detail titles, separated from body by weight not size; + also --d-body-font's advanced value, so it moves with density + 14 heading card and section headings (.card-shell-title, 700) + 17 metric the single large number on a card (.card-metric-val) + 20 title the view h1 (.view-title) + + 13 sits close to 12.5 on purpose and is the one pair left standing: one side is a runtime + density token (13 -> 14.5 in Simple mode), so folding it into the static ramp would decalibrate + the density feature to buy a cosmetic gap. The roles are held apart by weight (500-700) instead. + + Sizes stay in px, not rem: browser zoom scales px fine, and the density tokens above are the + deliberate user-facing size control on this surface. */ + /* height: 100vh (not min-height) pins the whole app to one viewport-tall flex column: .topbar - takes its fixed 52px and .workspace below it gets the rest via flex — the chain that lets + takes its fixed 48px and .workspace below it gets the rest via flex — the chain that lets `main` (see below) resolve "100% - the real chrome above it" without guessing at a pixel number. Views that don't need a filled/bounded height (everything except the five .split-shell ones) are untouched by this — they still just size to content and `main`'s own overflow-y:auto @@ -141,7 +179,6 @@ body { font-family: var(--font-ui); font-size: var(--d-body-font); line-height: var(--d-body-lh); - letter-spacing: 0.005em; font-feature-settings: "tnum"; -webkit-font-smoothing: antialiased; } @@ -187,8 +224,8 @@ div::-webkit-scrollbar-track, nav::-webkit-scrollbar-track { background: transpa /* ---------------- Topbar ---------------- */ .topbar { - display: flex; align-items: center; gap: 16px; - height: 52px; flex: 0 0 52px; padding: 0 16px; + display: flex; align-items: center; gap: 10px; + height: 48px; flex: 0 0 48px; padding: 0 12px; background: var(--panel); border-bottom: 1px solid var(--line); position: sticky; top: 0; z-index: 60; @@ -197,15 +234,14 @@ div::-webkit-scrollbar-track, nav::-webkit-scrollbar-track { background: transpa display: grid; place-items: center; flex: 0 0 auto; /* padding: 0 overrides the generic button padding (9px 11px), which shrank this 30px box's content area below the icon size and pinned the icon to the content top -- visibly low. */ - width: 30px; height: 30px; padding: 0; border: 1px solid var(--line); border-radius: 8px; + 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); } .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-name { font-size: 13px; font-weight: 700; letter-spacing: 0.15em; white-space: nowrap; } -.topbar-divider { width: 1px; height: 22px; background: var(--line); flex: 0 0 auto; } +.brand-name { font-size: 13px; font-weight: 650; letter-spacing: -0.01em; white-space: nowrap; } .session-pill { /* flex: 0 1 auto + min-width: 0 (not the old 0 0 auto) so the pill can actually shrink at @@ -224,18 +260,18 @@ div::-webkit-scrollbar-track, nav::-webkit-scrollbar-track { background: transpa dot so it reads as distinct from the ordinary "reconnecting" warn-pulse below. */ .session-pill .dot.expired { background: var(--error); animation: none; } .session-pill .label { - min-width: 0; font-size: 10.5px; font-weight: 600; letter-spacing: 0.06em; text-transform: uppercase; + min-width: 0; font-size: 10.5px; font-weight: 600; color: var(--muted); overflow: hidden; text-overflow: ellipsis; } .stream-seg { display: flex; align-items: center; flex: 0 0 auto; - border: 1px solid var(--line); border-radius: 8px; overflow: hidden; height: 26px; + border: 1px solid var(--control-outline); border-radius: 6px; overflow: hidden; height: 26px; } .stream-seg button { position: relative; display: flex; align-items: center; gap: 8px; padding: 0 12px; height: 24px; border: none; border-right: 1px solid var(--line); - border-radius: 0; font-size: 11px; font-weight: 600; letter-spacing: 0.06em; + border-radius: 0; font-size: 11.5px; font-weight: 600; color: var(--muted); background: transparent; cursor: pointer; } .stream-seg button:last-child { border-right: none; } @@ -243,16 +279,16 @@ div::-webkit-scrollbar-track, nav::-webkit-scrollbar-track { background: transpa .stream-seg button.active { color: var(--signal-ink); background: var(--signal); } .host-line { - flex: 0 1 auto; min-width: 0; font-family: var(--font-mono); font-size: 11px; color: var(--text-3); + flex: 0 1 auto; min-width: 0; font-family: var(--font-mono); font-size: 11.5px; color: var(--text-3); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .topbar-spacer { flex: 1; } -.topbar-actions { display: flex; align-items: center; gap: 8px; flex: 0 0 auto; } +.topbar-actions { display: flex; align-items: center; gap: 6px; flex: 0 0 auto; } .icon-btn { - border: 1px solid var(--line); background: var(--surface-2); color: var(--muted); - width: 32px; height: 32px; padding: 0; border-radius: 8px; cursor: pointer; + border: 1px solid var(--control-outline); background: var(--surface-2); color: var(--muted); + width: 30px; height: 30px; padding: 0; border-radius: 6px; cursor: pointer; display: inline-flex; align-items: center; justify-content: center; transition: color 0.15s, border-color 0.15s, background 0.15s; } @@ -269,13 +305,12 @@ div::-webkit-scrollbar-track, nav::-webkit-scrollbar-track { background: transpa @media (max-width: 560px) { .stream-seg .stream-seg-label { display: none; } .stream-seg button { padding: 0 9px; } } @media (max-width: 480px) { .session-pill { max-width: 108px; } - /* Task E1: below ~480px the topbar's non-shrinkable groups (rail-toggle 30px + brand ~110px + - stream-seg ~62px icon-only + topbar-actions' four 32px icon buttons = 152px, fixed — nothing - here is ever hidden, per §2's "never imply a control doesn't exist") add up to more than a - 375px viewport even with the session pill collapsed to nothing. Wrapping to a second row (via + /* Below ~480px the topbar's non-shrinkable groups (rail toggle + brand + stream control + + five global actions) no longer fit on one line even with the session pill compressed. Nothing + here is ever hidden, per §2's "never imply a control doesn't exist". Wrapping to a second row (via a full-width spacer, which forces a break right before .topbar-actions without touching source order) keeps every control reachable instead of clipping the row or hiding a button. */ - .topbar { flex-wrap: wrap; height: auto; min-height: 52px; padding: 8px 10px; gap: 8px; row-gap: 8px; } + .topbar { flex: 0 0 auto; flex-wrap: wrap; height: auto; min-height: 48px; padding: 6px 10px; gap: 8px; row-gap: 6px; } .topbar-spacer { flex-basis: 100%; height: 0; } } @@ -286,35 +321,35 @@ div::-webkit-scrollbar-track, nav::-webkit-scrollbar-track { background: transpa position: sticky/max-height/overflow-y still governs its own scroll, so it looks identical. */ .workspace { display: flex; align-items: stretch; flex: 1 1 auto; min-height: 0; } .rail { - flex: 0 0 232px; width: 232px; padding: 8px 12px 28px; + flex: 0 0 216px; width: 216px; padding: 10px 8px 24px; border-right: 1px solid var(--line); background: var(--panel); - position: sticky; top: 52px; align-self: flex-start; - max-height: calc(100vh - 52px); overflow-y: auto; + position: sticky; top: 48px; align-self: flex-start; + max-height: calc(100vh - 48px); overflow-y: auto; } body.rail-hidden .rail { display: none; } -.rail-group { margin-top: 16px; } -.rail-group-label { display: flex; align-items: center; gap: 8px; padding: 0 8px 8px; } +.rail-group { margin-top: 14px; } +.rail-group-label { display: flex; align-items: center; gap: 8px; padding: 0 10px 5px; color: var(--text-3); font-size: 11.5px; font-weight: 600; } .rail-group-label .text { - font-size: 10.5px; font-weight: 700; letter-spacing: 0.09em; text-transform: uppercase; color: var(--text-3); + font-size: inherit; font-weight: inherit; color: inherit; text-transform: none; letter-spacing: 0; white-space: nowrap; } -.rail-group-label .rule { flex: 1; height: 1px; background: var(--line); } +.rail-group-label .rule { display: none; } .rail button { position: relative; display: grid; grid-template-columns: 17px 1fr auto; align-items: center; gap: 12px; - width: 100%; height: 32px; margin-bottom: 2px; padding: 0 8px; border: none; border-radius: 8px; + width: 100%; height: 34px; margin-bottom: 2px; padding: 0 10px; border: none; border-radius: 6px; text-align: left; background: transparent; color: var(--muted); cursor: pointer; font: inherit; transition: background 0.12s, color 0.12s; } .rail button .ic { width: 16px; height: 16px; opacity: 0.9; color: inherit; } .rail button:hover { background: var(--surface-2); color: var(--ink); } .rail button.active, .rail button[aria-current="page"] { - background: var(--signal-soft); color: var(--ink); font-weight: 600; + 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: 5px; bottom: 5px; width: 2px; border-radius: 99px; background: var(--signal); + content: ""; position: absolute; left: 0; top: 7px; bottom: 7px; width: 2px; border-radius: 99px; background: var(--signal); } .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; } @@ -326,13 +361,13 @@ body.rail-hidden .rail { display: none; } .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-shortcuts { margin-top: 24px; padding: 8px 12px; border: 1px dashed var(--line); border-radius: 8px; } +.rail-shortcuts { margin-top: 24px; padding: 0 10px; color: var(--text-3); } .rail-shortcuts-title { - font-size: 10.5px; font-weight: 700; letter-spacing: 0.06em; text-transform: uppercase; color: var(--text-3); + font-size: 11.5px; font-weight: 600; color: inherit; margin-bottom: 4px; } -.rail-shortcuts-grid { display: grid; gap: 4px; font-size: 11px; color: var(--muted); } -.rail-shortcuts-grid .key { font-family: var(--font-mono); color: var(--ink); } +.rail-shortcuts-grid { display: grid; gap: 2px; font-size: 10.5px; line-height: 1.5; color: inherit; } +.rail-shortcuts-grid .key { font-family: var(--font-mono); color: inherit; } /* <780px: rail collapses to an icon-only strip; \\ / the topbar toggle hides it entirely. */ @media (max-width: 780px) { @@ -356,7 +391,7 @@ main { flex: 1 1 0%; min-width: 0; min-height: 0; display: flex; flex-direction: built around a filled .split-shell below -- up to that content height instead of staying pinned to main's actual available space. */ .main-inner { flex: 1; min-height: 0; display: flex; flex-direction: column; padding: 16px 24px 0; max-width: 1560px; width: 100%; margin: 0 auto; } -.view { display: none; animation: fadein 0.18s ease; } +.view { display: none; animation: fadein 0.15s ease; } .view.active { display: block; padding-bottom: 20px; } /* The five views built around a .split-shell (Timeline/Network/Sockets/Push/Crashes) need a real, filled height instead of every other view's auto/content height -- flex: 1 1 0% (grow to claim @@ -378,28 +413,33 @@ main { flex: 1 1 0%; min-width: 0; min-height: 0; display: flex; flex-direction: flex: 1 1 0%; min-height: 0; } -@keyframes fadein { from { opacity: 0; transform: translateY(3px); } to { opacity: 1; transform: none; } } +@keyframes fadein { from { opacity: 0; } to { opacity: 1; } } /* View head */ -.view-head { display: flex; align-items: flex-end; justify-content: space-between; gap: 20px; padding-bottom: 12px; } +/* padding-bottom is the view's one generous interval, and it is deliberately larger than the + .toolbar margin below it (20 vs 12). Both were 12px, which gave the h1 exactly as much room as a + filter row and flattened the page into one undifferentiated stack -- with 8 of the 16 views + carrying no toolbar at all, the title simply ran into its own content. 20/12 reads as + "title band, then the working area" at a glance without spending height a dense tool needs. */ +.view-head { display: flex; align-items: flex-end; justify-content: space-between; gap: 20px; padding-bottom: 20px; } .view-title { margin: 0; font-size: 20px; font-weight: 600; letter-spacing: -0.01em; white-space: nowrap; } .view-badge { - flex: 0 0 auto; font-family: var(--font-mono); font-size: 11px; padding: 2px 8px; border-radius: 99px; + flex: 0 0 auto; font-family: var(--font-mono); font-size: 11.5px; padding: 2px 8px; border-radius: 99px; border: 1px solid var(--line); color: var(--text-3); white-space: nowrap; } @media (max-width: 1000px) { .view-badge { display: none; } } -.view-hint { margin: 0; flex: 0 1 auto; min-width: 0; font-size: 12px; color: var(--muted); text-align: right; max-width: 520px; } +.view-hint { margin: 0; flex: 0 1 auto; min-width: 0; font-size: 12.5px; color: var(--muted); text-align: right; max-width: 520px; } /* 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; } /* ---------------- Toolbar / inputs ---------------- */ .toolbar { display: flex; align-items: flex-end; gap: 12px; flex-wrap: wrap; margin-bottom: 12px; } label.field { display: grid; gap: 4px; color: var(--muted); font-size: 11.5px; } -label.field > span { text-transform: uppercase; letter-spacing: 0.07em; font-size: 10.5px; font-weight: 600; color: var(--text-3); } +label.field > span { font-size: 10.5px; font-weight: 600; color: var(--text-3); } input, select, textarea, button { min-width: 0; color: var(--ink); background: var(--code-bg); - border: 1px solid var(--line); border-radius: 8px; + border: 1px solid var(--line); border-radius: 6px; padding: 9px 11px; font: inherit; font-size: 12.5px; transition: border-color 0.15s, box-shadow 0.15s; } @@ -429,22 +469,22 @@ button.primary { background: var(--signal); color: var(--signal-ink); border-col button.primary:hover { background: color-mix(in srgb, var(--signal) 85%, black); color: var(--signal-ink); } 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); } -button.xs { padding: 5px 9px; font-size: 11px; } +button.xs { padding: 5px 9px; font-size: 11.5px; } button.ghost { background: transparent; } .toolbar > button, .toolbar .filter-actions > button { - height: 32px; border-radius: 8px; padding: 0 12px; font-size: 12px; + height: 32px; border-radius: 8px; padding: 0 12px; font-size: 12.5px; } -.card-buttons > button { height: 31px; border-radius: 8px; padding: 0 12px; font-size: 12px; } +.card-buttons > button { height: 32px; border-radius: 8px; padding: 0 12px; font-size: 12.5px; } /* Search field with a leading icon */ .search-wrap { position: relative; display: flex; flex: 1 1 220px; min-width: 180px; } -/* Uppercase label stacked over the search input, sharing the toolbar's flex-end baseline. */ +/* Label stacked over the search input, sharing the toolbar's flex-end baseline. */ .search-field { flex: 1 1 260px; min-width: 200px; } .search-field .search-wrap { flex: 1 1 auto; min-width: 0; width: 100%; } .search-wrap .search-lead { position: absolute; left: 9px; top: 50%; transform: translateY(-50%); color: var(--text-3); } .search-wrap input { flex: 1; height: 32px; padding: 0 12px 0 28px; border-radius: 8px; - font-family: var(--font-mono); font-size: 12px; + font-family: var(--font-mono); font-size: 12.5px; } /* Segmented control */ @@ -474,7 +514,7 @@ button.ghost { background: transparent; } } .drop-btn.has-selection .drop-summary { color: var(--ink); } .drop-count { - font-family: var(--font-mono); font-size: 10px; font-weight: 700; padding: 1px 8px; + 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); } .drop-btn .ic-chevron { flex: 0 0 auto; color: var(--text-3); transform: rotate(-90deg); transition: transform 0.12s ease; } @@ -493,7 +533,7 @@ button.ghost { background: transparent; } .drop-item[aria-checked="true"] { background: var(--signal-soft); color: var(--ink); } .drop-box { display: grid; place-items: center; flex: 0 0 auto; width: 15px; height: 15px; - border: 1px solid var(--border-strong); border-radius: 6px; background: transparent; color: var(--signal-ink); + border: 1px solid var(--control-outline); border-radius: 6px; background: transparent; color: var(--signal-ink); } .drop-item[aria-checked="true"] .drop-box { border-color: var(--signal); background: var(--signal); } .drop-dot { flex: 0 0 auto; width: 6px; height: 6px; border-radius: 99px; } @@ -505,23 +545,23 @@ button.ghost { background: transparent; } .drop-footer { display: flex; gap: 4px; margin-top: 4px; padding-top: 4px; border-top: 1px solid var(--line); } .drop-footer button { flex: 1; height: 26px; padding: 0; border: 1px solid var(--line); border-radius: 6px; - font-size: 11px; font-weight: 600; color: var(--muted); background: var(--surface-2); justify-content: center; + font-size: 11.5px; font-weight: 600; color: var(--muted); background: var(--surface-2); justify-content: center; } /* Applied-filters strip — scaffolding for result-count chips with a remove (×) action. */ .applied-filters { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-bottom: 12px; } -.applied-filters-label { font-size: 10.5px; font-weight: 600; letter-spacing: 0.07em; text-transform: uppercase; color: var(--text-3); } +.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; } -.applied-filter-label { font-family: var(--font-mono); font-size: 11px; white-space: nowrap; } +.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: 11px; line-height: 1; + background: var(--signal); color: var(--signal-ink); font-size: 11.5px; line-height: 1; } .applied-filters-reset { - height: 24px; padding: 0 8px; font-size: 11px; font-weight: 600; color: var(--muted); + height: 24px; padding: 0 8px; font-size: 11.5px; font-weight: 600; color: var(--muted); background: none; border: none; border-bottom: 1px solid var(--line); border-radius: 0; } @@ -535,7 +575,7 @@ button.ghost { background: transparent; } .selection-count { font-family: var(--font-mono); font-size: 11.5px; font-weight: 700; color: var(--ink); white-space: nowrap; } .selection-spacer { flex: 1; } .selection-bar button { - height: 26px; padding: 0 10px; border-radius: 6px; font-size: 11px; font-weight: 600; + height: 26px; padding: 0 10px; border-radius: 6px; font-size: 11.5px; font-weight: 600; display: inline-flex; align-items: center; gap: 6px; background: var(--panel); } .selection-bar button[data-sel-action="clear"] { color: var(--muted); background: transparent; border-color: transparent; } @@ -546,20 +586,27 @@ button.ghost { background: transparent; } already-audited signal/put/warn/muted combinations rather than a new color pairing. */ /* Metrics strip — scaffolding for per-view summary rows. */ -.metrics-strip { display: flex; flex-wrap: wrap; flex-shrink: 0; background: var(--panel); border: 1px solid var(--line); border-radius: 8px; margin-bottom: 12px; overflow: hidden; } -.metric { flex: 1 1 130px; min-width: 130px; padding: 8px 16px 12px; border-left: 1px solid var(--line); } -.metric-label { font-size: 10.5px; font-weight: 600; letter-spacing: 0.07em; text-transform: uppercase; color: var(--text-3); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } -.metric-value-row { display: flex; align-items: baseline; gap: 8px; margin-top: 4px; } -.metric-value { font-family: var(--font-mono); font-size: 19px; line-height: 1.1; font-variant-numeric: tabular-nums; white-space: nowrap; } -.metric-sub { font-family: var(--font-mono); font-size: 11px; color: var(--text-3); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.metric-strip { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); border-block: 1px solid var(--line); } +.metric-strip .metric { min-width: 0; padding: 12px 14px; border-right: 1px solid var(--line); } +.metric-strip .metric:last-child { border-right: 0; } +.metric-strip .metric-value { font: 600 20px/1.2 var(--font-mono); } +.metric-strip .metric-label { margin-top: 3px; color: var(--muted); font-size: 11.5px; } +/* metricHtml() has wrapped the value and its qualifier in .metric-value-row since the first + release, and neither that row nor .metric-sub ever had a rule -- so the qualifier ran straight + into the number on every metrics strip in the app: "8sample", "00%", "0.55s", "0as evidence". + Baseline, not center: the qualifier is a unit hanging off a 20px mono figure, and centering it + would float it against the digits' x-height. Same treatment the native HeroCard gives + `valueSuffix` -- muted, one step down, baseline-aligned -- so the two surfaces read alike. */ +.metric-strip .metric-value-row { display: flex; align-items: baseline; gap: 6px; min-width: 0; } +.metric-strip .metric-sub { color: var(--muted); font-size: 11.5px; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } /* Gate banner — capability/host-gate explanation scaffolding. */ .gate-banner { display: flex; align-items: flex-start; gap: 12px; padding: 12px; margin-bottom: 12px; - border: 1px solid var(--border-strong); border-left: 2px solid var(--warn); border-radius: 8px; background: var(--warn-soft); + border: 1px solid var(--line); border-left: 3px solid var(--warn); border-radius: 6px; background: transparent; } .gate-banner .ic { color: var(--warn); flex: 0 0 auto; margin-top: 1px; } -.gate-banner-title { font-size: 12px; font-weight: 600; color: var(--ink); } +.gate-banner-title { font-size: 12.5px; font-weight: 600; color: var(--ink); } .gate-banner-body { font-size: 11.5px; color: var(--muted); margin-top: 2px; } /* Same visual as .gate-banner but a real - - ${findBarHtml(query, countPaneHits([{ groups: [{ kvs }] }]), 'eventDetailFindInput')}
${screenshotHtml} @@ -2486,15 +2510,6 @@ restoreFocus(focusSnap, pane); // toggle-zoom is handled by the delegated listener wired once in wireEvents (`$('eventDetail') // .addEventListener('click', ...)`), not rebound here on every render. - pane.querySelector('[data-action="bookmark"]').onclick = () => toggleBookmark(event.id); - const openNetworkBtn = pane.querySelector('[data-action="open-network"]'); - if (linked) - openNetworkBtn.onclick = async () => { - await show('network'); - const match = networkPage.find((t) => t.correlationId === event.correlationId); - if (match) showTransaction(match.id); - else toast('No matching transaction is currently loaded.', 'error'); - }; $('eventNoteSaveBtn').onclick = saveNote; if (screenshotAttachmentId) { mountEvidenceThumbnails(pane); @@ -2503,7 +2518,7 @@ } // Client-side ceiling on the accumulated `events` array — was 500 (== the old per-request - // limit), raised to 5,000 (E4: matches the acceptance scenario's session size) now that DOM + // limit), raised to 5,000 (a realistic full-session size) now that DOM // size is decoupled from array size by the Timeline virtualizer below. Applied both to live-tail // merges (mergeEvents) and to scroll-triggered "load more" (loadMoreEventsIfPossible) so neither // path can grow the in-memory array past what a long unattended session should reasonably hold. @@ -2843,9 +2858,9 @@ fetch('/api/v1/meta', { headers: auth() }), fetch('/api/v1/network/transactions?limit=100', { headers: auth() }), fetch('/api/v1/events?limit=6&sort=DESC', { headers: auth() }), - // D4's "previous-run-crashed banner": GET /api/v1/runs (added in 7ef109d) reports every + // 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" the spec means. + // *non-active* run is the "previous run". fetch('/api/v1/runs', { headers: auth() }), ]); if (!overviewRes.ok) return; @@ -2913,14 +2928,13 @@ // so every row's flag button and the rail count are already correct across every view. loadEvidenceFlags(); } - /** D4's previous-run-crashed banner, driven by GET /api/v1/runs (7ef109d) — `previousRun` is + /** The previous-run-crashed banner, driven by GET /api/v1/runs — `previousRun` is * already "the most recent non-active run" by the time it gets here (see loadOverview). Shown * only when that run's real StoredSessionStatus is CRASHED; a COMPLETED (or any other) previous * run shows nothing. Now that crashes are addressable per run (GET /api/v1/retained-events? * pluginId=crash carries sessionId — see the Crashes module doc), the click handler below jumps * straight to that run's crash via focusCrashesOnRun() instead of just opening the Crashes view - * in general, which is all a plain `show('crashes')` used to be able to do (see commit 9315533's - * note, no longer accurate). */ + * in general, which is all a plain `show('crashes')` used to be able to do. */ function renderOverviewCrashBanner(previousRun) { const el = $('overviewCrashBanner'); if (!el) return; @@ -2940,7 +2954,7 @@ { 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 the / markup task E2 asks for (device path, the + // 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). @@ -3255,7 +3269,7 @@ 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.
'; function renderNetwork() { - $('networkMainColLabel').textContent = networkShowHost ? 'Host / path' : 'Path'; + $('networkMainColLabel').textContent = 'Path'; // 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. @@ -3269,13 +3283,13 @@ id: t.id, selected: selectedTransactionId === t.id, checkbox: true, checked: networkSelectedIds.has(t.id), badgeText: t.method, badgeTone: methodTone(t.method), - mainText: networkShowHost ? t.host + t.path : t.path, + mainText: t.path, // 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, 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), - flagKind: 'network', flagLabel: t.method + ' ' + t.host + t.path, + flagKind: 'network', flagLabel: t.method + ' ' + t.path, posinset: i + 1, setsize: total, }); }, @@ -3970,7 +3984,7 @@ } // ================================================================ - // Crashes (D4/D7) — uncaught exceptions and ANRs from the `crash` plugin, read cross-session via + // Crashes — uncaught exceptions and ANRs from the `crash` plugin, read cross-session via // GET /api/v1/retained-events?pluginId=crash (no sessionId). A crash's process dies right after // CrashCapture writes it to Room, so by the time a developer reopens the app and connects the // dashboard, the session that recorded it is no longer current — the live in-memory timeline @@ -4132,7 +4146,7 @@ }; /** Target of the Overview "previous run crashed" banner (renderOverviewCrashBanner) — landing on * the general Crashes view was the best that banner could do before crashes were addressable per - * run (see commit 9315533's note); now that every row carries sessionId, it can select the exact + * run; now that every row carries sessionId, it can select the exact * crash instead. Clears any leftover kind/search filter that would otherwise hide the target row * — the banner's whole job is to land the developer on this crash, not on "no rows match your * leftover filter" — then reuses the same select()+focusSelectedRow() path the j/k keyboard @@ -5442,9 +5456,9 @@ const r = await fetch('/api/v1/attachments/' + encodeURIComponent(attachmentId), { headers: auth() }); if (!(await downloadBlobResponse(r, attachmentId))) toast('Attachment download failed: ' + r.status, 'error'); } - /** C: the evidence bundle -- `POST /api/v1/exports` with `scope=EVIDENCE`, the existing export + /** The evidence bundle -- `POST /api/v1/exports` with `scope=EVIDENCE`, the existing export * route (CSRF, size limits, truncation reporting, stale-export pruning all come for free). No - * `X-DevConsole-Export-Truncated` header is set on this branch (unlike the HAR/Postman bulk + * `X-DevConsole-Export-Truncated` header is set on this route (unlike the HAR/Postman bulk * routes), so truncation can only be read from the ZIP's own manifest.json -- same "verify * manifest.json" guidance the whole-session export already gives. */ async function downloadEvidenceBundle() { @@ -5741,7 +5755,7 @@ $('composerImport').disabled = !enabled; $('composerCollectionSave').disabled = !enabled; $('pushSimulate').disabled = !enabled; - $('mockDisable').disabled = !enabled; + syncMockEngineButton(); syncMockRuleDialogGate(); $('captureRuleSave').disabled = !enabled || !captureRulesEditable; $('fileCreate').disabled = !enabled || !filesEditable; @@ -5749,8 +5763,8 @@ // (renderEventDetail) with their disabled state set directly from `token` at render time, // since they only exist in the DOM once an event is selected. $('quickExport').disabled = !token; - // Capture is off by default on the host (ScreenshotPolicy.enabled = false) and there is no - // route that reports that ahead of time (see the verification report) — this button is only + // Capture is off by default on the host (ScreenshotPolicy.enabled = false) and no route + // reports that ahead of time — this button is only // ever gated on "is a session connected", exactly like Export; SCREENSHOT_DISABLED is // surfaced as a toast naming the config property once a capture is actually attempted. $('captureScreenshot').disabled = !token; @@ -5998,14 +6012,42 @@ if (!token) return; const r = await fetch('/api/v1/mocks', { headers: auth() }); mocksGloballyEnabled = r.ok ? (await r.json()).enabled === true : true; + syncMockEngineButton(); loadMockRules(); } - async function disableMocks() { + /** 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 + * capability-gated `/enabled` route, because that one changes how the app behaves. */ + async function toggleMockEngine() { if (!hasSession()) return; - const r = await fetch('/api/v1/mocks/disable-all', { method: 'POST', headers: controlHeaders() }); - toast(r.ok ? 'All mocks disabled.' : 'Disable failed: ' + r.status, r.ok ? undefined : 'error'); + const turningOn = !mocksGloballyEnabled; + if (turningOn && !canEditMocks()) return; + const r = turningOn + ? await fetch('/api/v1/mocks/enabled', { + method: 'POST', + headers: { ...controlHeaders(), 'Content-Type': 'text/plain' }, + body: 'true', + }) + : await fetch('/api/v1/mocks/disable-all', { method: 'POST', headers: controlHeaders() }); + const verb = turningOn ? 'enabled' : 'disabled'; + toast(r.ok ? 'Mocking ' + verb + '.' : (turningOn ? 'Enable' : 'Disable') + ' failed: ' + r.status, r.ok ? undefined : 'error'); if (r.ok) loadMocks(); } + /** Keeps the single mock-engine button describing what it will do next. */ + function syncMockEngineButton() { + const btn = $('mockDisable'); + if (!btn) return; + const on = mocksGloballyEnabled; + btn.classList.toggle('danger', on); + btn.querySelector('use').setAttribute('href', on ? '#dc-close' : '#dc-check'); + btn.lastChild.textContent = on ? 'Disable all mocks' : 'Enable mocking'; + btn.disabled = !hasSession() || (!on && !canEditMocks()); + btn.title = btn.disabled + ? (hasSession() ? 'The host app publishes mock rules as read-only' : 'Sign-in required') + : on + ? 'Stop serving every mock rule — requests go to the real network' + : 'Serve matching requests from the enabled mock rules again'; + } async function deleteMockRule(id) { if (!canEditMocks()) return; const r = await fetch('/api/v1/mocks/rules/' + encodeURIComponent(id), { method: 'DELETE', headers: controlHeaders() }); @@ -7081,13 +7123,6 @@ // ---- Network ----------------------------------------------------------------- wireSeg($('networkStatusSeg'), (value) => { networkStatusFilter = value; applyNetworkFilters(); }); wireSeg($('networkMethodSeg'), (value) => { networkMethodFilter = value; applyNetworkFilters(); }); - $('networkToggleHost').onclick = () => { - networkShowHost = !networkShowHost; - $('networkToggleHostLabel').textContent = networkShowHost ? 'Base URL shown' : 'Base URL hidden'; - $('networkToggleHost').querySelector('.ic use').setAttribute('href', networkShowHost ? '#dc-eye' : '#dc-lock'); - $('networkToggleHost').setAttribute('aria-pressed', String(!networkShowHost)); - renderNetwork(); - }; $('networkRefresh').onclick = () => loadNetwork(); $('networkNewest').onclick = () => loadNetwork(); $('networkOlder').onclick = () => networkCursor && loadNetwork(networkCursor); @@ -7196,7 +7231,7 @@ $('composerCollectionSave').onclick = saveComposerCollection; $('composerCollections').onclick = loadComposerCollections; - $('mockDisable').onclick = disableMocks; + $('mockDisable').onclick = toggleMockEngine; $('mockNewRule').onclick = () => openMockRuleDialog(null); $('mockRuleModalClose').onclick = closeMockRuleDialog; $('mockRuleCancel').onclick = closeMockRuleDialog; 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 9e10fbc..19cae9a 100644 --- a/sdk/server-ktor/src/main/resources/devconsole-web/index.html +++ b/sdk/server-ktor/src/main/resources/devconsole-web/index.html @@ -8,7 +8,14 @@ - +
- DEVCONSOLE + DevConsole
-
+ Not connected — see the device's More screen for the connect QR
Open DevConsole on device → More → scan the QR
- - + +
- Not connected — see the device's More screen for the connect QR
@@ -99,7 +105,7 @@ - +
Control
@@ -109,7 +115,7 @@
Data
- + @@ -117,7 +123,7 @@
Report
- +
-
Shortcuts
+
Keyboard shortcuts
-
/ filter  p pause
-
t theme  ? all shortcuts
+
/ Filter  p Pause
+
t Theme  ? All shortcuts
@@ -143,7 +149,7 @@

Session, traffic health, and the latest signals for this debug build.

-
+
Not connected yet
Open DevConsole on the device → More → scan the QR, or paste the session code below to inspect this session.
@@ -153,7 +159,7 @@

Timeline

Unified event tail across network, sockets, push, mocks, and system signals.

-
+
@@ -205,7 +211,7 @@

Network

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

-
+
@@ -232,7 +238,6 @@
-
@@ -259,7 +264,7 @@
-
+
MethodPathDurationStatus
@@ -289,7 +294,7 @@

WebSockets

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

-
+
@@ -367,7 +372,7 @@

Push

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

-
+
@@ -414,7 +419,7 @@

Crashes

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

-
+
@@ -501,7 +506,7 @@

SDK Health

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

-
+
Not connected yet
Open DevConsole on the device → More → scan the QR or paste the code in Overview to inspect SDK health.
@@ -511,14 +516,14 @@

Evidence tray

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

-
+

Session & Security

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

-
+
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.
@@ -527,7 +532,7 @@

Composer

Execute requests with the SDK-owned client, import cURL, and save ephemeral collections.

-
+

Request

@@ -548,7 +553,7 @@
-
+

cURL import

@@ -584,7 +589,7 @@

Mocks

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

-
+
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 1afe647..cac7f17 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 @@ -94,4 +94,40 @@ class DashboardAssetsTest { assertTrue(css.contains(".rail")) assertFalse(dashboard.contains("color-scheme: dark")) } + + @Test + fun `dashboard uses the graphite cobalt design tokens`() { + val css = DashboardAssets.css().lowercase() + + listOf( + "--ground: #111317", + "--panel: #171a20", + "--surface-2: #1d2129", + "--ink: #eceef2", + "--signal: #72a7ff", + ).forEach { token -> assertTrue("missing $token", css.contains(token)) } + + listOf("#b7ed65", "#427526", "terminal-green", "instrument panel").forEach { legacy -> + assertFalse("legacy design value remains: $legacy", css.contains(legacy)) + } + } + + @Test + fun `dashboard defaults to system theme and persists only explicit choice`() { + val script = DashboardAssets.js() + + assertTrue(script.contains("matchMedia('(prefers-color-scheme: dark)')")) + assertTrue(script.contains("devconsole-theme")) + assertTrue(script.contains("media.addEventListener('change'")) + } + + @Test + fun `dashboard shell keeps stable functional ids and semantic landmarks`() { + val dashboard = DashboardAssets.index() + + assertTrue(dashboard.contains("
()V + public final fun getLambda$-1348228066$ui_compose_release ()Lkotlin/jvm/functions/Function2; public final fun getLambda$1070396343$ui_compose_release ()Lkotlin/jvm/functions/Function2; } 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 97ceafa..3a0c564 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 @@ -6,8 +6,12 @@ package io.devconsole.ui.compose +import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.core.animateFloatAsState -import androidx.compose.animation.core.tween +import androidx.compose.animation.expandVertically +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.shrinkVertically import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column @@ -16,8 +20,7 @@ import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.Surface +import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue @@ -31,13 +34,16 @@ import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp -private const val CHEVRON_ROTATION_DURATION_MS = 140 - /** - * A collapsible detail card: 56dp header row with an animated chevron, a 14sp label, an optional - * mono meta string, and an optional 44dp copy button; [content] renders only while [expanded]. - * Nest [InspectorKeyValueList], [InspectorCodeBlock], [InspectorProgressBars] or + * A collapsible detail section: a rule, then a 56dp header row with an animated chevron, a 14sp + * label, an optional mono meta string, and an optional 44dp copy button; [content] renders only + * while [expanded]. Nest [InspectorKeyValueList], [InspectorCodeBlock], [InspectorProgressBars] or * [InspectorDetailEmptyText] inside it. + * + * Flat and rule-separated rather than a filled card, matching [HeroCard], [TerminalCard] and the + * dashboard's `.card-shell`. The chevron sits on the shared 16dp gutter so the header lines up with + * the [InspectorKeyValueList] rows underneath it and with every [TonalListRow] and [GroupLabel] + * elsewhere in the app. */ @Suppress("LongParameterList") // Label, meta, copy button, and content. @Composable @@ -56,19 +62,22 @@ internal fun CollapsibleSection( val rotation by animateFloatAsState( targetValue = if (expanded) 0f else -90f, - animationSpec = tween(CHEVRON_ROTATION_DURATION_MS), + animationSpec = chevronSpec(), label = "sectionChevron", ) - Surface( - modifier = modifier.fillMaxWidth(), - shape = RoundedCornerShape(22.dp), - color = DevConsoleTheme.colors.surface2, - ) { - Column { - CollapsibleSectionHeader(label, onToggle, rotation, meta, metaColor, onCopy, copyContentDescription) - if (expanded) { - Column(content = content) - } + Column(modifier = modifier.fillMaxWidth()) { + 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: + // the section grows out of the header the chevron just turned on. + AnimatedVisibility( + visible = expanded, + enter = expandVertically(feedbackSpec(InspectorMotion.EXPAND_MS)) + fadeIn(feedbackSpec()), + // Exit faster than entrance -- collapsing is a dismissal, not an arrival. + exit = shrinkVertically(feedbackSpec()) + fadeOut(feedbackSpec()), + ) { + Column(content = content) } } } @@ -84,7 +93,9 @@ private fun CollapsibleSectionHeader( onCopy: (() -> Unit)?, copyContentDescription: String, ) { - Row(modifier = Modifier.padding(start = 4.dp, end = 8.dp), verticalAlignment = Alignment.CenterVertically) { + // start 8 + the inner row's own 8 puts the chevron on the shared 16dp gutter; end 4 optically + // lands the copy glyph on the same gutter, since it is centred in a 44dp round button. + Row(modifier = Modifier.padding(start = 8.dp, end = 4.dp), verticalAlignment = Alignment.CenterVertically) { Row( modifier = Modifier 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 1be0dab..68803ee 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 @@ -6,7 +6,11 @@ package io.devconsole.ui.compose +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Shapes +import androidx.compose.material3.Typography import androidx.compose.material3.darkColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable @@ -70,96 +74,79 @@ internal data class DevConsoleColors( val jsonBraces: List, ) -private val DarkSignal = Color(0xFFB7ED65) -private val DarkError = Color(0xFFFF715E) -private val DarkWarn = Color(0xFFF0B45C) -private val DarkPut = Color(0xFF7FD0C9) -private val DarkMuted = Color(0xFF92968E) +private val DarkPrimary = Color(0xFF72A7FF) +private val DarkError = Color(0xFFFF7B72) +private val DarkWarning = Color(0xFFF2B66D) +private val DarkSecondary = Color(0xFF72C4CE) internal val DevConsoleDarkColors = DevConsoleColors( - ground = Color(0xFF0B0E0D), - panel = Color(0xFF151A18), - surface2 = Color(0xFF1B231E), - surface3 = Color(0xFF212B24), - codeBg = Color(0xFF10140F), - ink = Color(0xFFE7E5D8), - muted = DarkMuted, - text3 = Color(0xFF7D8479), - line = Color(0xFF344039), - borderStrong = Color(0xFF4A5A4F), - signal = DarkSignal, - signalInk = Color(0xFF0B0E0D), - warn = DarkWarn, + 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), + signal = DarkPrimary, + signalInk = Color(0xFF0E1624), + warn = DarkWarning, error = DarkError, - errorInk = Color(0xFF0B0E0D), // not #fff: 4.5:1 AA gate fails on #FF715E in dark - put = DarkPut, - signalSoft = DarkSignal.copy(alpha = 0.11f), + errorInk = Color(0xFF0E1624), + put = DarkSecondary, + signalSoft = DarkPrimary.copy(alpha = 0.13f), errorSoft = DarkError.copy(alpha = 0.13f), - warnSoft = DarkWarn.copy(alpha = 0.13f), - putSoft = DarkPut.copy(alpha = 0.13f), - jsonKey = Color(0xFF8FD6C4), - jsonString = Color(0xFFCFD8A6), - jsonNumber = Color(0xFFF0B45C), - jsonBoolean = Color(0xFFB7ED65), - jsonNull = Color(0xFF92968E), - jsonBraces = - listOf( - Color(0xFFB7ED65), - Color(0xFFF0B45C), - Color(0xFF7FD0C9), - Color(0xFFE7E5D8), - Color(0xFF92968E), - ), + warnSoft = DarkWarning.copy(alpha = 0.13f), + putSoft = DarkSecondary.copy(alpha = 0.13f), + jsonKey = Color(0xFF8CB8FF), + jsonString = Color(0xFFA9D6B9), + jsonNumber = DarkWarning, + jsonBoolean = Color(0xFFC7A7FF), + jsonNull = Color(0xFF969DA8), + jsonBraces = listOf(DarkPrimary, DarkWarning, DarkSecondary, Color(0xFFECEEF2), Color(0xFFC7A7FF)), ) -// #427526, not the older #4F8F28: the light signal was darkened for WCAG AA (the old hex measures -// 3.97:1 on white -- see docs/DESIGN_SPEC.md §3.2 "do not lighten back"). Mirrors the web -// dashboard's light --signal. -private val LightSignal = Color(0xFF427526) +private val LightPrimary = Color(0xFF245DA8) private val LightError = Color(0xFFB6392A) private val LightWarn = Color(0xFF93630A) private val LightPut = Color(0xFF1F7A6C) -private val LightMuted = Color(0xFF5B6459) internal val DevConsoleLightColors = DevConsoleColors( - ground = Color(0xFFF3F6EE), + ground = Color(0xFFF7F8FA), panel = Color(0xFFFFFFFF), - surface2 = Color(0xFFEEF2E6), - surface3 = Color(0xFFE3E9D7), - codeBg = Color(0xFFF6F8F1), - ink = Color(0xFF182018), - muted = LightMuted, - text3 = Color(0xFF656C5F), - line = Color(0xFFDDE3D1), - borderStrong = Color(0xFFC3CDB4), - signal = LightSignal, + surface2 = Color(0xFFEEF1F5), + surface3 = Color(0xFFE4E8EE), + codeBg = Color(0xFFF7F8FA), + ink = Color(0xFF1C1F24), + muted = Color(0xFF68707B), + text3 = Color(0xFF68707B), + line = Color(0xFFD5D9E0), + borderStrong = Color(0xFFAAB1BC), + signal = LightPrimary, signalInk = Color(0xFFFFFFFF), warn = LightWarn, error = LightError, errorInk = Color(0xFFFFFFFF), put = LightPut, - signalSoft = LightSignal.copy(alpha = 0.10f), + signalSoft = LightPrimary.copy(alpha = 0.10f), errorSoft = LightError.copy(alpha = 0.10f), warnSoft = LightWarn.copy(alpha = 0.10f), putSoft = LightPut.copy(alpha = 0.10f), jsonKey = Color(0xFF1F7A6C), jsonString = Color(0xFF4A5B1F), - jsonNumber = Color(0xFF93630A), - jsonBoolean = LightSignal, - jsonNull = Color(0xFF656C5F), - // brace-4 deliberately isn't a restatement of --muted (#656C5F) sitting right next to it in - // the same tree -- plum, not a tint of any tone already in the ladder above, mirroring the - // web palette's own brace-4 pick (dashboard.css) at ~6.9:1 on white / ~6.4:1 on codeBg, both - // past the 4.5:1 AA floor the rest of this block is held to (brace-0 tracks [LightSignal] - // for exactly that reason). + jsonNumber = LightWarn, + jsonBoolean = LightPrimary, + jsonNull = Color(0xFF68707B), jsonBraces = listOf( - LightSignal, - Color(0xFF93630A), - Color(0xFF1F7A6C), - Color(0xFF182018), + LightPrimary, + LightWarn, + LightPut, + Color(0xFF1C1F24), Color(0xFF6A4C93), ), ) @@ -175,15 +162,29 @@ internal object DevConsoleElevation { * they're used instead of centralized here. */ internal object DevConsoleType { - val title = - TextStyle(fontSize = 27.sp, fontWeight = FontWeight.Medium, letterSpacing = (-0.02).em, lineHeight = 31.sp) val rowTitle = TextStyle(fontFamily = FontFamily.Monospace, fontSize = 14.5.sp) val rowSub = TextStyle(fontSize = 12.5.sp) val groupLabel = TextStyle(fontSize = 12.5.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.04.em) - val heroValue = - TextStyle(fontSize = 40.sp, fontWeight = FontWeight.Medium, letterSpacing = (-0.03).em, lineHeight = 40.sp) } +internal val DevConsoleShapes = + Shapes( + extraSmall = RoundedCornerShape(4.dp), + small = RoundedCornerShape(6.dp), + medium = RoundedCornerShape(8.dp), + large = RoundedCornerShape(12.dp), + extraLarge = RoundedCornerShape(16.dp), + ) + +internal val DevConsoleTypography = + Typography( + headlineSmall = + TextStyle(fontSize = 27.sp, fontWeight = FontWeight.Medium, letterSpacing = (-0.02).em, lineHeight = 31.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), + ) + internal val LocalDevConsoleColors = staticCompositionLocalOf { DevConsoleDarkColors } /** Reads [DevConsoleColors] the same way `MaterialTheme.colorScheme` reads the M3 scheme. */ @@ -199,13 +200,21 @@ internal object DevConsoleTheme { */ @Composable internal fun DevConsoleTheme( - darkTheme: Boolean = true, + darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit, ) { val colors = if (darkTheme) DevConsoleDarkColors else DevConsoleLightColors val colorScheme = if (darkTheme) darkDevConsoleColorScheme(colors) else lightDevConsoleColorScheme(colors) - CompositionLocalProvider(LocalDevConsoleColors provides colors) { - MaterialTheme(colorScheme = colorScheme, content = content) + CompositionLocalProvider( + LocalDevConsoleColors provides colors, + LocalReduceMotion provides rememberReduceMotion(), + ) { + MaterialTheme( + colorScheme = colorScheme, + shapes = DevConsoleShapes, + typography = DevConsoleTypography, + content = content, + ) } } 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 d1080a5..f960e4c 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,6 +6,10 @@ package io.devconsole.ui.compose +import androidx.compose.animation.Crossfade +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.LocalContentColor @@ -14,12 +18,14 @@ 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.saveable.rememberSaveableStateHolder import androidx.compose.runtime.setValue 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 @@ -39,13 +45,21 @@ fun DevConsoleWorkspace() { * console, not just whichever screen last owned it, and hides the bottom nav entirely while a detail * overlay covers the screen. Every route now owns its mock-accurate `InspectorTopArea` directly. */ +internal enum class InspectorNavigationLayout { Bar, Rail } + +internal fun inspectorNavigationLayout(width: androidx.compose.ui.unit.Dp): InspectorNavigationLayout = + if (width < 600.dp) InspectorNavigationLayout.Bar else InspectorNavigationLayout.Rail + @Composable internal fun DevConsoleWorkspace( selected: InspectorDestination, onDestinationSelected: (InspectorDestination) -> Unit, viewModel: InspectorViewModel = viewModel(), ) { - var darkTheme by rememberSaveable { mutableStateOf(true) } + val context = LocalContext.current + 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() // A capture category disabled at init (or, dynamically, mid-session) can take the currently @@ -59,21 +73,47 @@ internal fun DevConsoleWorkspace( if (selected !in visible) onDestinationSelected(visible.first()) } DevConsoleTheme(darkTheme = darkTheme) { - Scaffold( - containerColor = DevConsoleTheme.colors.ground, - bottomBar = { - if (!detailOverlayOpen) { - InspectorBottomNav(items = workspaceNavItems(selected, state, onDestinationSelected)) + 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, + ) } - }, - ) { padding -> - WorkspaceContent( - selected = selected, - onToggleTheme = { darkTheme = !darkTheme }, - onDetailOverlayOpen = { open -> detailOverlayOpen = open }, - modifier = Modifier.fillMaxSize().padding(padding), - viewModel = viewModel, - ) + } } } } @@ -148,31 +188,36 @@ private fun WorkspaceContent( // the newly active route's own LaunchedEffect asserts the correct value right after. LaunchedEffect(selected) { onDetailOverlayOpen(false) } val stateHolder = rememberSaveableStateHolder() - when (selected) { - InspectorDestination.OBSERVE -> - stateHolder.SaveableStateProvider(InspectorDestination.OBSERVE.name) { - ObserveRoute( - onToggleTheme = onToggleTheme, - onDetailOverlayOpen = onDetailOverlayOpen, - modifier = modifier, - ) - } - InspectorDestination.CONTROL -> - stateHolder.SaveableStateProvider(InspectorDestination.CONTROL.name) { - ControlRoute( - onToggleTheme = onToggleTheme, - onDetailOverlayOpen = onDetailOverlayOpen, - modifier = modifier, - ) - } - InspectorDestination.DATA -> - stateHolder.SaveableStateProvider(InspectorDestination.DATA.name) { - DataRoute(onToggleTheme = onToggleTheme, modifier = modifier) - } - InspectorDestination.MORE -> - stateHolder.SaveableStateProvider(InspectorDestination.MORE.name) { - MoreRoute(onToggleTheme = onToggleTheme, modifier = modifier) - } + // 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, + ) + } + InspectorDestination.CONTROL -> + stateHolder.SaveableStateProvider(InspectorDestination.CONTROL.name) { + ControlRoute( + onToggleTheme = onToggleTheme, + onDetailOverlayOpen = onDetailOverlayOpen, + modifier = modifier, + ) + } + InspectorDestination.DATA -> + stateHolder.SaveableStateProvider(InspectorDestination.DATA.name) { + DataRoute(onToggleTheme = onToggleTheme, modifier = modifier) + } + InspectorDestination.MORE -> + stateHolder.SaveableStateProvider(InspectorDestination.MORE.name) { + MoreRoute(onToggleTheme = onToggleTheme, modifier = modifier) + } + } } } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorArrivalFlash.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorArrivalFlash.kt new file mode 100644 index 0000000..5325b95 --- /dev/null +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorArrivalFlash.kt @@ -0,0 +1,90 @@ +/** + * @author Shakib + * @since 11/08/26 + */ +package io.devconsole.ui.compose + +import androidx.compose.animation.core.Animatable +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.drawBehind +import androidx.compose.ui.graphics.Color +import kotlinx.coroutines.delay + +/** + * The ids that appeared in [ids] since the previous composition of this list -- the rows a live + * capture just added. + * + * The first snapshot primes silently and returns nothing: a screen opening onto two hundred + * retained captures must not flash two hundred rows. Only what lands while the operator is + * watching counts as an arrival, which is the same rule the dashboard follows by flashing on its + * live socket event rather than on render. + * + * Keyed on the caller's own remember scope, so each list (traffic, logs, crashes) tracks its own + * arrivals and a destination switch that disposes the list starts over. + */ +@Composable +internal fun rememberArrivals(ids: List): Set { + val tracker = remember { ArrivalTracker() } + return remember(ids) { tracker.accept(ids) } +} + +/** + * The arrival rule of [rememberArrivals], as plain Kotlin so it can be tested without a Compose + * harness -- the same split [inspectorNavigationLayout] uses for the layout breakpoint. + */ +internal class ArrivalTracker { + private val seen = mutableSetOf() + private var primed = false + + /** The ids in [ids] not present at the previous call; always empty for the very first call. */ + fun accept(ids: List): Set { + val fresh = if (primed) ids.filterNotTo(mutableSetOf()) { it in seen } else emptySet() + // Retained-buffer eviction and filtering both shrink the list; dropping what left keeps an + // id that comes back (a filter cleared, say) from being mistaken for a fresh capture only + // for as long as it is genuinely gone, and stops the set growing without bound. + seen.retainAll(ids.toSet()) + seen.addAll(ids) + primed = true + return fresh + } +} + +/** + * The dashboard's `dcRowFlash` for a Compose row: a signal-soft wash that decays to nothing over + * [InspectorMotion.ROW_FLASH_MS], marking the row a live capture just put there. + * + * Drawn in [drawBehind] rather than as a background color so the decay runs entirely in the draw + * phase -- a list taking rows at socket speed never recomposes for the fade -- and so it composites + * *over* whatever container color the row already carries (flagged, selected) instead of replacing + * it. + * + * Reduced motion removes the fade, not the fact. The wash is the only thing that says "this row + * just arrived", so dropping it outright would delete information rather than motion -- it would + * leave an operator who turned animations off unable to tell a new capture from an old one at all. + * Instead the wash is held flat for the same [InspectorMotion.ROW_FLASH_MS] and then cleared: a + * state change, which is what the setting asks for, rather than a transition, which is what it asks + * to be spared. Same treatment the dashboard's `dcRowFlash` gets under `prefers-reduced-motion`. + */ +@Composable +internal fun Modifier.arrivalFlash(isArrival: Boolean): Modifier { + val reduceMotion = LocalReduceMotion.current + val wash = DevConsoleTheme.colors.signalSoft + val decay = remember { Animatable(0f) } + LaunchedEffect(isArrival, reduceMotion) { + if (!isArrival) return@LaunchedEffect + decay.snapTo(1f) + if (reduceMotion) { + delay(InspectorMotion.ROW_FLASH_MS.toLong()) + decay.snapTo(0f) + } else { + decay.animateTo(0f, InspectorMotion.decay()) + } + } + return drawBehind { + val progress = decay.value + if (progress > 0f) drawRect(Color(wash.red, wash.green, wash.blue, wash.alpha * progress)) + } +} diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeFullScreenOverlay.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeFullScreenOverlay.kt index 9b3659e..75eb5e6 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeFullScreenOverlay.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeFullScreenOverlay.kt @@ -7,6 +7,7 @@ package io.devconsole.ui.compose import androidx.activity.compose.BackHandler +import androidx.compose.animation.core.Animatable import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row @@ -20,10 +21,13 @@ import androidx.compose.foundation.rememberScrollState import androidx.compose.material3.Surface 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.graphicsLayer import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow @@ -70,7 +74,23 @@ internal fun InspectorCodeFullScreenOverlay( ) { BackHandler(onBack = onDismiss) val colors = DevConsoleTheme.colors - Surface(modifier = modifier.fillMaxSize(), color = colors.ground) { + // The dashboard's `modalpop`: rise 10px, scale up from 0.98, fade in, over OVERLAY_MS on the + // emphasized curve. Owned here rather than at the four call sites so every overlay arrives the + // same way, and driven from one Animatable so the whole entrance runs in the draw phase. + val entranceSpec = feedbackSpec(InspectorMotion.OVERLAY_MS) + val entrance = remember { Animatable(0f) } + LaunchedEffect(Unit) { entrance.animateTo(1f, entranceSpec) } + Surface( + modifier = + modifier.fillMaxSize().graphicsLayer { + val progress = entrance.value + alpha = progress + scaleX = OVERLAY_ENTRY_SCALE + (1f - OVERLAY_ENTRY_SCALE) * progress + scaleY = scaleX + translationY = (1f - progress) * OVERLAY_ENTRY_RISE.toPx() + }, + color = colors.ground, + ) { Column(modifier = Modifier.fillMaxSize()) { CodeFullScreenHeader(title, onDismiss, headerTrailing) LazyColumn( @@ -132,3 +152,9 @@ private fun CodeFullScreenHeader( trailing?.invoke() } } + +/** `modalpop`'s starting scale: near-full, so the overlay grows into place instead of zooming. */ +private const val OVERLAY_ENTRY_SCALE = 0.98f + +/** `modalpop`'s starting offset: a short rise, matching `translateY(10px)` on the dashboard. */ +private val OVERLAY_ENTRY_RISE = 10.dp 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 86561ef..e14e445 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 @@ -26,7 +26,6 @@ import androidx.compose.material3.AlertDialog import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Switch -import androidx.compose.material3.SwitchDefaults import androidx.compose.material3.Text import androidx.compose.material3.minimumInteractiveComponentSize import androidx.compose.runtime.Composable @@ -274,7 +273,6 @@ private fun ControlHero( value = overrides.activeCount.toString(), label = "of ${overrides.total} overrides active", onExpand = onToggleCollapse, - containerColor = colors.putSoft, valueColor = colors.put, labelColor = colors.put, ) @@ -284,7 +282,6 @@ private fun ControlHero( value = overrides.activeCount.toString(), valueSuffix = "of ${overrides.total}", subtitle = overrides.sub, - containerColor = colors.putSoft, labelColor = colors.put, valueColor = colors.put, onCollapse = onToggleCollapse, @@ -303,11 +300,11 @@ private fun MockRulesHeader( verticalAlignment = Alignment.CenterVertically, ) { GroupLabel("Mock rules", modifier = Modifier.weight(1f)) - InspectorPillButton( - label = "New rule", + androidx.compose.material3.OutlinedButton( onClick = onNewRule, - labelFontSize = 13.sp, - ) + ) { + Text("New rule", fontSize = 13.sp, color = colors.ink) + } } } @@ -363,11 +360,6 @@ private fun MockRuleRow( Switch( checked = rule.enabled, onCheckedChange = { checked -> onToggle(rule.id, checked) }, - colors = - SwitchDefaults.colors( - checkedTrackColor = colors.signal, - checkedThumbColor = colors.signalInk, - ), modifier = Modifier.semantics { contentDescription = @@ -511,7 +503,7 @@ private fun FlagRow( ) } -/** Hand-built fixture for [ControlScreenPreview] -- previews are the only visual check on this branch. */ +/** Hand-built fixture for [ControlScreenPreview]. */ private fun controlScreenPreviewState() = InspectorState( available = true, 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 19250a1..43e68d6 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 @@ -299,7 +299,6 @@ private fun DataHero( onToggleCollapse: () -> Unit, colors: DevConsoleColors, ) { - val containerColor = if (info.blindSpot) colors.errorSoft else colors.surface2 val accentColor = if (info.blindSpot) colors.error else colors.text3 val valueColor = if (info.blindSpot) colors.error else colors.ink val barLabel = if (info.blindSpot) "key${if (info.value == "1") "" else "s"} exposed by the allowlist" else info.of @@ -308,7 +307,6 @@ private fun DataHero( value = info.value, label = barLabel, onExpand = onToggleCollapse, - containerColor = containerColor, valueColor = valueColor, labelColor = accentColor, ) @@ -318,7 +316,6 @@ private fun DataHero( value = info.value, valueSuffix = info.of, subtitle = info.sub, - containerColor = containerColor, labelColor = accentColor, valueColor = valueColor, onCollapse = onToggleCollapse, @@ -362,7 +359,7 @@ private fun StateEntryTonalRow( ) } -/** Hand-built fixture for [DataScreenPreview] -- A2: previews are the only visual check on this branch. */ +/** Hand-built fixture for [DataScreenPreview]. */ private fun dataScreenPreviewState() = InspectorState( available = true, 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 cc2a301..87134e3 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 @@ -151,17 +151,24 @@ private fun DatabaseTableRow( onOpenTable: (String, String) -> Unit, ) { val colors = DevConsoleTheme.colors - TonalListRow( - leadText = "TBL", - 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", - onClick = { onOpenTable(database, table.name) }, - ) + Column(modifier = Modifier.fillMaxWidth()) { + TonalListRow( + leadText = "TBL", + 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, + onClick = { onOpenTable(database, table.name) }, + ) + androidx.compose.material3.HorizontalDivider( + modifier = Modifier.padding(start = 76.dp), + color = colors.line, + ) + } } @Composable diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDesignSystemPreviews.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDesignSystemPreviews.kt index 0730ccc..7db91f2 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDesignSystemPreviews.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDesignSystemPreviews.kt @@ -75,7 +75,6 @@ private fun HeroCardPreview() { value = "4", valueSuffix = "of 15", subtitle = "2 client, 2 server, 1 timeout.", - containerColor = DevConsoleTheme.colors.errorSoft, labelColor = DevConsoleTheme.colors.error, valueColor = DevConsoleTheme.colors.error, onCollapse = {}, @@ -162,7 +161,7 @@ private fun InspectorBottomNavPreview() { var selected by remember { mutableStateOf(0) } val destinations = listOf("Observe", "Control", "Data", "More") DevConsoleTheme(darkTheme = isSystemInDarkTheme()) { - InspectorBottomNav( + InspectorNavigationBar( destinations.mapIndexed { index, label -> InspectorNavItem(label, index == selected, { selected = index }) { InspectorGlyphIcon(InspectorGlyph.Check, contentDescription = null, size = 20.dp) 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 fedc949..25c22bc 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 @@ -147,7 +147,7 @@ private fun FileEntryRow( actions: FileBrowserActions, ) { val colors = DevConsoleTheme.colors - Column { + Column(modifier = Modifier.fillMaxWidth()) { TonalListRow( leadText = if (entry.isDirectory) "DIR" else "FILE", leadColor = if (entry.isDirectory) colors.signal else colors.put, @@ -156,6 +156,7 @@ private fun FileEntryRow( subtitle = if (entry.isDirectory) "directory" else "${entry.sizeBytes} B", trailValue = if (entry.isDirectory) "›" else "", trailValueColor = colors.muted, + containerColor = androidx.compose.ui.graphics.Color.Transparent, onClick = { if (entry.isDirectory) { actions.onOpenPath(root, entry.relativePath) @@ -165,6 +166,10 @@ private fun FileEntryRow( }, ) if (canEdit && !entry.isDirectory) FileEntryActions(root, entry, actions) + 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/InspectorGlyphs.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorGlyphs.kt index fafbab7..ebc495b 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 @@ -39,6 +39,7 @@ 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 import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.dp @@ -221,13 +222,21 @@ internal fun InspectorPillButton( .then(outlineModifier) .background(resolvedContainer) .clickable(onClick = onClick, enabled = enabled, role = Role.Button) - .padding(horizontal = 16.dp), + .padding(horizontal = 12.dp), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically, ) { Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) { icon?.invoke() - Text(label, color = contentColor, fontSize = labelFontSize, fontWeight = FontWeight.SemiBold, maxLines = 1) + // Ellipsis, not the default clip: weighted pills used to drop a label's last glyph. + Text( + label, + color = contentColor, + fontSize = labelFontSize, + fontWeight = FontWeight.SemiBold, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) } } } 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 8f38d29..bafa8af 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,27 +6,22 @@ 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.Box import androidx.compose.foundation.layout.Column 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.foundation.layout.size -import androidx.compose.foundation.shape.CircleShape -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.Surface +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.MaterialTheme 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.contentDescription import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight @@ -35,10 +30,16 @@ import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp /** - * A tinted verdict card with a big value, an optional trailing icon OR a collapse chevron (never - * both -- the Android state always ends up collapsible), and an optional full-width pill CTA. + * 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. */ -@Suppress("LongParameterList") // Every field varies per screen. +@Suppress("LongParameterList") // Label, value, subtitle, collapse, and the optional CTA's five knobs. @Composable internal fun HeroCard( label: String, @@ -46,14 +47,10 @@ internal fun HeroCard( subtitle: String, modifier: Modifier = Modifier, valueSuffix: String? = null, - containerColor: Color = DevConsoleTheme.colors.surface2, labelColor: Color = DevConsoleTheme.colors.text3, valueColor: Color = DevConsoleTheme.colors.ink, - icon: (@Composable () -> Unit)? = null, - iconContainerColor: Color = DevConsoleTheme.colors.panel, onCollapse: (() -> Unit)? = null, collapseContentDescription: String = "Collapse this summary to one line", - /** More's uptime clock reads best in mono digits; every other screen leaves this null. */ valueFontFamily: FontFamily? = null, ctaLabel: String? = null, ctaIcon: (@Composable () -> Unit)? = null, @@ -61,83 +58,75 @@ internal fun HeroCard( ctaContentColor: Color = DevConsoleTheme.colors.signalInk, onCtaClick: (() -> Unit)? = null, ) { - Surface(modifier = modifier.fillMaxWidth(), shape = RoundedCornerShape(26.dp), color = containerColor) { - Column(modifier = Modifier.padding(start = 20.dp, top = 20.dp, end = 20.dp, bottom = 16.dp)) { - Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) { - Column(modifier = Modifier.weight(1f)) { - Text(label.uppercase(), color = labelColor, style = DevConsoleType.groupLabel) - Row( - modifier = Modifier.padding(top = 8.dp), - horizontalArrangement = Arrangement.spacedBy(8.dp), - ) { - Text( - value, - modifier = Modifier.alignByBaseline(), - color = valueColor, - style = DevConsoleType.heroValue.copy(fontFamily = valueFontFamily), + 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 (valueSuffix != null) { - Text( - valueSuffix, - modifier = Modifier.alignByBaseline(), - color = DevConsoleTheme.colors.muted, - fontSize = 14.sp, - ) - } - } - Text( - subtitle, - modifier = Modifier.padding(top = 8.dp), - color = DevConsoleTheme.colors.muted, - fontSize = 13.5.sp, - ) - } - HeroTrailing(icon, iconContainerColor, onCollapse, collapseContentDescription, labelColor) - } - if (ctaLabel != null && onCtaClick != null) { - InspectorPillButton( - label = ctaLabel, - onClick = onCtaClick, - modifier = Modifier.fillMaxWidth().padding(top = 16.dp), - containerColor = ctaContainerColor, - contentColor = ctaContentColor, - icon = ctaIcon, + }, ) } } + 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 HeroTrailing( - icon: (@Composable () -> Unit)?, - iconContainerColor: Color, - onCollapse: (() -> Unit)?, - collapseContentDescription: String, - chevronTint: Color, +private fun RowScope.HeroReadout( + label: String, + value: String, + subtitle: String, + valueSuffix: String?, + labelColor: Color, + valueColor: Color, + valueFontFamily: FontFamily?, ) { - when { - onCollapse != null -> - InspectorRoundIconButton( - contentDescription = collapseContentDescription, - onClick = onCollapse, - size = 44.dp, - containerColor = DevConsoleTheme.colors.panel, - icon = { - InspectorGlyphIcon( - InspectorGlyph.ChevronDown, - contentDescription = null, - tint = chevronTint, - size = 18.dp, - rotationDegrees = 180f, - ) - }, + 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), ) - icon != null -> - Box( - modifier = Modifier.size(44.dp).clip(CircleShape).background(iconContainerColor), - contentAlignment = Alignment.Center, - ) { icon() } + 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) } } @@ -152,7 +141,6 @@ internal fun HeroBar( label: String, onExpand: () -> Unit, modifier: Modifier = Modifier, - containerColor: Color = DevConsoleTheme.colors.surface2, valueColor: Color = DevConsoleTheme.colors.ink, labelColor: Color = DevConsoleTheme.colors.text3, expandContentDescription: String = "Expand the summary", @@ -161,9 +149,7 @@ internal fun HeroBar( modifier = modifier .fillMaxWidth() - .heightIn(min = 56.dp) - .clip(RoundedCornerShape(20.dp)) - .background(containerColor) + .heightIn(min = 48.dp) .clickable(onClick = onExpand, onClickLabel = expandContentDescription, role = Role.Button) .semantics(mergeDescendants = true) {} .padding(horizontal = 16.dp), @@ -174,15 +160,14 @@ internal fun HeroBar( value, color = valueColor, fontFamily = FontFamily.Monospace, - fontSize = 19.sp, + fontSize = 15.sp, fontWeight = FontWeight.Bold, ) Text( label, modifier = Modifier.weight(1f), color = labelColor, - fontSize = 13.sp, - fontWeight = FontWeight.SemiBold, + style = MaterialTheme.typography.bodySmall, maxLines = 1, overflow = TextOverflow.Ellipsis, ) 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 db7c011..7572511 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 @@ -8,9 +8,7 @@ package io.devconsole.ui.compose import androidx.compose.animation.core.animateFloatAsState -import androidx.compose.animation.core.tween 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 @@ -19,16 +17,15 @@ import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column 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.rememberScrollState -import androidx.compose.foundation.selection.toggleable 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 @@ -50,13 +47,11 @@ internal fun GroupLabel( text: String, modifier: Modifier = Modifier, ) { - // The 8dp horizontal inset lines this up with the list rows below it, which the bare bottom - // padding was missing. Text( - text.uppercase(), - modifier = modifier.padding(start = 8.dp, top = 2.dp, end = 8.dp, bottom = 8.dp), + text, + modifier = modifier.padding(start = 16.dp, top = 16.dp, end = 16.dp, bottom = 8.dp), color = DevConsoleTheme.colors.text3, - style = DevConsoleType.groupLabel, + style = MaterialTheme.typography.labelMedium, ) } @@ -89,7 +84,9 @@ private fun Modifier.tonalRowClickable( /** * A tonal list row: round mono lead badge, mono title + muted sub, trailing mono value + sub. - * `min 74dp`, whole row clickable, `8dp` bottom margin baked in on every row (including the last). + * `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. */ @Suppress("LongParameterList") // One row primitive covers every Observe/Control/Data list item shape. @Composable @@ -103,7 +100,7 @@ internal fun TonalListRow( modifier: Modifier = Modifier, trailValueColor: Color = DevConsoleTheme.colors.ink, trailSubtitle: String? = null, - containerColor: Color = DevConsoleTheme.colors.surface2, + containerColor: Color = Color.Transparent, /** Real composable trailing content (e.g. [TonalRowExpandChevron]) rendered after [trailValue]'s column. */ trailContent: (@Composable () -> Unit)? = null, /** Optional composable rendered before the lead badge -- e.g. the traffic tab's selection checkbox. */ @@ -116,17 +113,22 @@ internal fun TonalListRow( * click action instead of folding both into one merged node. */ mergeDescendants: Boolean = true, + /** + * `true` for a row a live capture just added, which washes it in signal for + * [InspectorMotion.ROW_FLASH_MS] -- see [arrivalFlash]. Feed it from [rememberArrivals] at the + * list level; a row can never work out on its own whether it is new or merely re-composed. + */ + isArrival: Boolean = false, ) { Row( modifier = modifier .fillMaxWidth() - .padding(bottom = 8.dp) - .heightIn(min = 74.dp) - .clip(RoundedCornerShape(20.dp)) + .heightIn(min = 48.dp) .background(containerColor) + .arrivalFlash(isArrival) .tonalRowClickable(onClick, onLongClick, mergeDescendants) - .padding(start = 12.dp, top = 12.dp, end = 16.dp, bottom = 12.dp), + .padding(start = 16.dp, top = 8.dp, end = 16.dp, bottom = 8.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(16.dp), ) { @@ -180,7 +182,7 @@ internal fun TonalListRow( * A real rotating chevron glyph for a [TonalListRow]'s expand/collapse affordance, replacing the * CJK presentation-form `︿` (U+FE3F) hack -- font-coverage dependent and announced as a symbol by * TalkBack. Same rotation convention [CollapsibleSection] uses: open -> 0deg (points down), - * collapsed -> -90deg (points right), animated with the same 140ms tween. + * collapsed -> -90deg (points right), on the shared [chevronSpec] spring. */ @Composable internal fun TonalRowExpandChevron( @@ -190,7 +192,7 @@ internal fun TonalRowExpandChevron( val rotation by animateFloatAsState( targetValue = if (expanded) 0f else -90f, - animationSpec = tween(140), + animationSpec = chevronSpec(), label = "tonalRowExpandChevron", ) InspectorGlyphIcon( @@ -203,7 +205,7 @@ internal fun TonalRowExpandChevron( ) } -/** Warning-tinted note row: alert icon + 13sp muted text on a warn-soft card. */ +/** Warning-tinted note row: alert icon + 13sp muted text on a warn-soft block. */ @Composable internal fun WarnNote( text: String, @@ -213,7 +215,7 @@ internal fun WarnNote( modifier = modifier .fillMaxWidth() - .clip(RoundedCornerShape(20.dp)) + .clip(MaterialTheme.shapes.large) .background(DevConsoleTheme.colors.warnSoft) .padding(16.dp), horizontalArrangement = Arrangement.spacedBy(12.dp), @@ -238,9 +240,10 @@ internal data class InspectorFilterChip( ) /** - * Horizontally scrolling filter chips: 44dp visual height, 12dp corners, selected = signal fill + - * leading check. Each chip reserves a real 48dp touch target via [minimumInteractiveComponentSize] - * even though it draws at 44dp. + * 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. */ @Composable internal fun FilterChipRow( @@ -249,7 +252,11 @@ internal fun FilterChipRow( modifier: Modifier = Modifier, ) { Row( - modifier = modifier.fillMaxWidth().horizontalScroll(rememberScrollState()), + modifier = + modifier + .fillMaxWidth() + .horizontalScroll(rememberScrollState()) + .padding(horizontal = 16.dp, vertical = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp), ) { chips.forEach { chip -> InspectorChip(chip, onClick = { onChipClick(chip) }) } @@ -261,37 +268,34 @@ private fun InspectorChip( chip: InspectorFilterChip, onClick: () -> Unit, ) { - val colors = DevConsoleTheme.colors - val borderColor = if (chip.selected) colors.signal else colors.line - val containerColor = if (chip.selected) colors.signal else Color.Transparent - val contentColor = if (chip.selected) colors.signalInk else colors.ink - Row( - modifier = - Modifier - .minimumInteractiveComponentSize() - .height(44.dp) - .border(1.dp, borderColor, RoundedCornerShape(12.dp)) - .clip(RoundedCornerShape(12.dp)) - .background(containerColor) - // toggleable (not a bare clickable+Role.Checkbox) so TalkBack announces the real checked state. - .toggleable(value = chip.selected, onValueChange = { onClick() }, role = Role.Checkbox) - .padding(horizontal = 16.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(8.dp), - ) { - if (chip.selected) { - InspectorGlyphIcon(InspectorGlyph.Check, contentDescription = null, tint = contentColor, size = 15.dp) - } - Text( - chip.label, - color = contentColor, - fontSize = 13.5.sp, - fontWeight = FontWeight.SemiBold, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - if (chip.count != null) { - Text(chip.count, color = if (chip.selected) contentColor else colors.text3, fontSize = 12.sp) - } - } + FilterChip( + selected = chip.selected, + onClick = onClick, + label = { + Row(horizontalArrangement = Arrangement.spacedBy(4.dp), verticalAlignment = Alignment.CenterVertically) { + Text(chip.label) + if (chip.count != null) { + Text(chip.count) + } + } + }, + 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, + ), + border = + FilterChipDefaults.filterChipBorder( + enabled = true, + selected = chip.selected, + borderColor = DevConsoleTheme.colors.line, + selectedBorderColor = DevConsoleTheme.colors.signal, + ), + ) } 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 1902a5f..a18f53d 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 @@ -33,8 +33,7 @@ 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.draw.drawBehind -import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics @@ -406,6 +405,7 @@ private fun MockRuleAdvancedFields( } } +@OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class) @Composable private fun MockRuleEditorHeader( title: String, @@ -413,36 +413,38 @@ private fun MockRuleEditorHeader( onBack: () -> Unit, colors: DevConsoleColors, ) { - val lineColor = colors.line - Row( - modifier = - Modifier - .fillMaxWidth() - .drawBehind { - 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 = 12.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - InspectorRoundIconButton( - contentDescription = "Cancel", - onClick = onBack, - icon = { + androidx.compose.material3.TopAppBar( + title = { + Column { + Text( + text = title, + style = androidx.compose.material3.MaterialTheme.typography.titleMedium, + color = colors.ink, + ) + Text( + text = subtitle, + style = androidx.compose.material3.MaterialTheme.typography.bodySmall, + color = colors.muted, + maxLines = 1, + ) + } + }, + navigationIcon = { + androidx.compose.material3.IconButton(onClick = onBack) { InspectorGlyphIcon( InspectorGlyph.ChevronDown, - contentDescription = null, + contentDescription = "Cancel", tint = colors.ink, size = 20.dp, rotationDegrees = 90f, ) - }, - ) - Column(Modifier.weight(1f).padding(start = 4.dp)) { - Text(title, color = colors.ink, fontSize = 17.sp, fontWeight = FontWeight.SemiBold) - Text(subtitle, color = colors.muted, fontSize = 12.5.sp, maxLines = 1) - } - } + } + }, + colors = + androidx.compose.material3.TopAppBarDefaults.topAppBarColors( + containerColor = Color.Transparent, + ), + ) } @Composable 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 62bbd3e..875f55b 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 @@ -21,8 +21,8 @@ import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListScope -import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.AlertDialog +import androidx.compose.material3.MaterialTheme import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Text @@ -346,7 +346,6 @@ private fun MoreHero( onToggleCollapse: () -> Unit, colors: DevConsoleColors, ) { - val containerColor = if (info.running) colors.signalSoft else colors.surface2 val accentColor = if (info.running) colors.signal else colors.text3 val valueColor = if (info.running) colors.signal else colors.muted if (collapsed) { @@ -354,7 +353,6 @@ private fun MoreHero( value = info.value, label = info.bar, onExpand = onToggleCollapse, - containerColor = containerColor, valueColor = valueColor, labelColor = accentColor, ) @@ -365,7 +363,6 @@ private fun MoreHero( value = info.value, valueSuffix = info.of, subtitle = info.sub, - containerColor = containerColor, labelColor = accentColor, valueColor = valueColor, valueFontFamily = FontFamily.Monospace, @@ -390,7 +387,7 @@ private fun ServerControlCard( modifier = Modifier .fillMaxWidth() - .clip(RoundedCornerShape(20.dp)) + .clip(MaterialTheme.shapes.large) .background(if (running) colors.signalSoft else colors.surface2) .padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp), @@ -456,6 +453,7 @@ private fun StaleAddressUrlCard( ) { InspectorUrlCard( dotColor = colors.warn, + dotPulsing = true, label = "Server address changed", url = "—", subtitle = @@ -488,6 +486,7 @@ private fun RunningUrlCard( 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.", @@ -507,7 +506,8 @@ private fun runningUrlCardActions( { actions.onCopyUrl(url) }, colors.signal, colors.signalInk, - flex = 2f, + // 2f squeezed the secondary pills until their labels clipped. + flex = 1.5f, icon = { UrlActionCopyIcon(colors.signalInk) }, ), InspectorUrlAction( @@ -579,7 +579,7 @@ private fun LanWarningBanner(browser: InspectorBrowserUi?) { Modifier .fillMaxWidth() .padding(bottom = 16.dp) - .clip(RoundedCornerShape(20.dp)) + .clip(MaterialTheme.shapes.large) .background(colors.errorSoft) .padding(16.dp), ) { @@ -893,7 +893,7 @@ private fun formatUptime(elapsedMs: Long): String { return "%02d:%02d:%02d".format(Locale.US, hours, minutes, seconds) } -/** Hand-built fixture for [MoreScreenPreview] -- previews are the only visual check on this branch. */ +/** Hand-built fixture for [MoreScreenPreview]. */ private fun moreScreenPreviewState() = InspectorState( available = true, diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMotion.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMotion.kt new file mode 100644 index 0000000..d94e129 --- /dev/null +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMotion.kt @@ -0,0 +1,142 @@ +/** + * @author Shakib + * @since 11/08/26 + */ +@file:Suppress("MagicNumber") + +package io.devconsole.ui.compose + +import android.provider.Settings +import androidx.compose.animation.core.CubicBezierEasing +import androidx.compose.animation.core.Easing +import androidx.compose.animation.core.FiniteAnimationSpec +import androidx.compose.animation.core.LinearEasing +import androidx.compose.animation.core.Spring +import androidx.compose.animation.core.snap +import androidx.compose.animation.core.spring +import androidx.compose.animation.core.tween +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.runtime.staticCompositionLocalOf +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.unit.dp + +/** + * The inspector's motion vocabulary, ported from the dashboard's own keyframes (dashboard.css) so + * the two surfaces move alike rather than each inventing a house style: + * + * | Dashboard | Here | Job | + * |---|---|---| + * | `fadein 0.15s` | [FEEDBACK_MS] | acknowledge a switch or a toggle | + * | `modalpop 0.18s cubic-bezier(0.2, 0.9, 0.3, 1)` | [OVERLAY_MS] + [emphasized] | an overlay arriving over content | + * | `dcRowFlash 900ms` | [ROW_FLASH_MS] | a row worth finding again after the list moved | + * | `dcPulse 2.4s infinite` | [PULSE_PERIOD_MS] | a session that is live, not settled | + * + * Everything here sits inside the 150-300ms band for state changes. The two + * outliers are deliberate and match the web: the row flash is a decay the eye reads *after* the + * fact rather than a transition anyone waits on, and the pulse is a status indicator, not a + * transition at all. + */ +internal object InspectorMotion { + /** `fadein 0.15s` -- routine acknowledgement: view switches, toggles, chevrons. */ + const val FEEDBACK_MS = 150 + + /** `modalpop 0.18s` -- an overlay taking the screen. */ + const val OVERLAY_MS = 180 + + /** Expand/collapse of a section's own content. Longer than feedback because real height moves. */ + const val EXPAND_MS = 220 + + /** + * `dcRowFlash 900ms` -- a signal-soft wash that marks one row for as long as it takes to find + * it. The dashboard spends it on the row a save just produced, right after scrolling the list + * to it; here the same wash and duration mark a row a live capture just added. Different + * trigger, same job: the list changed under you, and this is which row is the reason. + */ + const val ROW_FLASH_MS = 900 + + /** `dcPulse 2.4s` -- one full breath of the live-session dot. */ + const val PULSE_PERIOD_MS = 2400 + + /** + * Travel distance for a shared-axis-X tab change. Deliberately a short nudge rather than a + * full-width slide: the offset only has to say "this content came from that side", and a + * screen-width translation of two live lists is both slower to read and more expensive to + * composite on the low-end hardware a debug console has to stay honest on. + */ + val sharedAxisOffset = 30.dp + + /** Alpha floor of that breath, straight from the `dcPulse` 50% stop. */ + const val PULSE_MIN_ALPHA = 0.35f + + /** `modalpop`'s curve: a confident arrival that settles without bouncing. */ + val emphasized: Easing = CubicBezierEasing(0.2f, 0.9f, 0.3f, 1f) + + /** Linear on purpose: a decay should read as an even fade-out, not as an easing gesture. */ + fun decay(durationMs: Int = ROW_FLASH_MS) = tween(durationMs, easing = LinearEasing) +} + +/** + * Routine state change; the default for anything that is not an arrival or a decay. + * + * Composable so it can collapse to zero under [LocalReduceMotion] -- the equivalent of the + * dashboard's `animation-duration: 0.01ms !important` override. Every spec in the inspector should + * come from here or from a sibling helper, so that "remove animations" is one switch rather than a + * promise each call site has to remember to keep. + */ +@Composable +internal fun feedbackSpec(durationMs: Int = InspectorMotion.FEEDBACK_MS): FiniteAnimationSpec = + tween(if (LocalReduceMotion.current) 0 else durationMs, easing = InspectorMotion.emphasized) + +/** The chevron spring the collapse affordances share, stilled to a cut under reduced motion. */ +@Composable +internal fun chevronSpec(): FiniteAnimationSpec = + if (LocalReduceMotion.current) snap() else spring(stiffness = Spring.StiffnessMediumLow) + +/** + * Whether the operator has asked the system to remove animations -- Android's counterpart to the + * dashboard's `@media (prefers-reduced-motion: reduce)` block, which flattens every duration there. + * + * Defaults to `false` so previews and tests animate; [DevConsoleTheme] provides the real value. + */ +internal val LocalReduceMotion = staticCompositionLocalOf { false } + +/** + * Reads (and keeps watching) `Settings.Global.ANIMATOR_DURATION_SCALE`, which is what Android's + * "Remove animations" accessibility setting and the developer-options animation scales both write. + * A scale of exactly `0` is the platform's own signal that animations should not play -- honoring + * it is why this console can add motion without taking the setting away from anyone who needs it. + * + * Observed rather than sampled once: the developer options that write this scale are exactly the + * ones an operator running a debug console is likely to toggle mid-session, and a stale read would + * leave the console animating after the rest of the system stopped. + */ +@Composable +internal fun rememberReduceMotion(): Boolean { + val context = LocalContext.current + val resolver = context.contentResolver + var reduceMotion by remember(resolver) { mutableStateOf(animationsRemoved(resolver)) } + DisposableEffect(resolver) { + val uri = Settings.Global.getUriFor(Settings.Global.ANIMATOR_DURATION_SCALE) + val observer = + object : android.database.ContentObserver(android.os.Handler(android.os.Looper.getMainLooper())) { + override fun onChange(selfChange: Boolean) { + reduceMotion = animationsRemoved(resolver) + } + } + // Registration is best-effort: a host that restricts settings reads must not crash the + // console, it must just animate as if the setting were unset. + runCatching { resolver.registerContentObserver(uri, false, observer) } + onDispose { runCatching { resolver.unregisterContentObserver(observer) } } + } + return reduceMotion +} + +private fun animationsRemoved(resolver: android.content.ContentResolver): Boolean = + runCatching { + Settings.Global.getFloat(resolver, Settings.Global.ANIMATOR_DURATION_SCALE, 1f) == 0f + }.getOrDefault(false) 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 16070f3..7bedd29 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 @@ -6,6 +6,8 @@ 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.clickable import androidx.compose.foundation.layout.Arrangement @@ -14,14 +16,28 @@ import androidx.compose.foundation.layout.Column 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.width -import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.IconButton 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.NavigationRail +import androidx.compose.material3.NavigationRailItem +import androidx.compose.material3.NavigationRailItemDefaults +import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text +import androidx.compose.material3.TextFieldDefaults +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip @@ -29,6 +45,7 @@ import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.draw.shadow import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.selected import androidx.compose.ui.semantics.semantics @@ -49,6 +66,7 @@ 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. */ +@OptIn(ExperimentalMaterial3Api::class) @Composable internal fun InspectorTopArea( subLine: String, @@ -56,32 +74,36 @@ internal fun InspectorTopArea( modifier: Modifier = Modifier, actions: List = emptyList(), ) { - Column(modifier = modifier.padding(top = 12.dp, start = 8.dp, end = 8.dp, bottom = 8.dp)) { - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) { + Column(modifier = modifier) { + TopAppBar( + title = { Text(title) }, + actions = { + actions.forEach { action -> + IconButton(onClick = action.onClick) { + action.icon() + } + } + }, + colors = + TopAppBarDefaults.topAppBarColors( + containerColor = Color.Transparent, + titleContentColor = DevConsoleTheme.colors.ink, + actionIconContentColor = DevConsoleTheme.colors.muted, + ), + windowInsets = + androidx.compose.foundation.layout + .WindowInsets(0.dp), + ) + if (subLine.isNotEmpty()) { Text( - subLine, - modifier = Modifier.weight(1f).padding(start = 8.dp), + text = subLine, + modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 8.dp), color = DevConsoleTheme.colors.muted, + style = MaterialTheme.typography.bodySmall, maxLines = 1, overflow = TextOverflow.Ellipsis, - fontSize = 13.sp, - fontWeight = FontWeight.SemiBold, ) - actions.forEach { action -> - InspectorRoundIconButton( - contentDescription = action.contentDescription, - onClick = action.onClick, - containerColor = action.containerColor, - icon = action.icon, - ) - } } - Text( - title, - modifier = Modifier.padding(top = 2.dp, start = 8.dp, end = 8.dp, bottom = 8.dp), - color = DevConsoleTheme.colors.ink, - style = DevConsoleType.title, - ) } } @@ -108,60 +130,89 @@ internal data class InspectorTab( val onClick: () -> Unit, ) -/** 52dp underline tabs: 3dp rounded-top indicator inset 14% each side. */ +/** + * 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. + */ @Composable internal fun InspectorTabRow( tabs: List, modifier: Modifier = Modifier, ) { - val lineColor = DevConsoleTheme.colors.line + val colors = DevConsoleTheme.colors + val selectedIndex = tabs.indexOfFirst { it.selected } + // 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()) } + val travelSpec = feedbackSpec() + LaunchedEffect(selectedIndex, travelSpec) { + if (selectedIndex >= 0) travel.animateTo(selectedIndex.toFloat(), travelSpec) + } Row( 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) + 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 -> - val indicatorColor = if (tab.selected) DevConsoleTheme.colors.signal else Color.Transparent - val labelColor = if (tab.selected) DevConsoleTheme.colors.signal else DevConsoleTheme.colors.muted + // 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) - // mergeDescendants: without it TalkBack reads the label text as a node - // separate from the tab's own click target. .semantics(mergeDescendants = true) { selected = tab.selected }, contentAlignment = Alignment.Center, ) { Text( tab.label, color = labelColor, - fontSize = 13.sp, - fontWeight = if (tab.selected) FontWeight.SemiBold else FontWeight.Medium, - ) - Box( - modifier = - Modifier - .align(Alignment.BottomCenter) - .fillMaxWidth(0.72f) - .height(3.dp) - .clip(RoundedCornerShape(topStart = 99.dp, topEnd = 99.dp)) - .background(indicatorColor), + style = MaterialTheme.typography.titleSmall, ) } } } } +/** 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 + /** - * 52dp pill search field. Callers wrap it in `LazyListScope.stickyHeader` when it needs to stick - * to the top of a scrolling list -- this component is scroll-container agnostic. + * Search field on the shared 16dp gutter: a surface-2 [OutlinedTextField] with its indicator lines + * suppressed, shaped by [DevConsoleShapes]' `medium`. Callers wrap it in + * `LazyListScope.stickyHeader` when it needs to stick to the top of a scrolling list -- this + * component is scroll-container agnostic. */ @Composable internal fun InspectorSearchBar( @@ -170,33 +221,33 @@ internal fun InspectorSearchBar( modifier: Modifier = Modifier, placeholder: String = "Search", ) { - Row( - modifier = - modifier - .fillMaxWidth() - .heightIn(min = 52.dp) - .clip(RoundedCornerShape(50)) - .background(DevConsoleTheme.colors.surface2) - .padding(horizontal = 16.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(12.dp), - ) { - InspectorGlyphIcon( - InspectorGlyph.Search, - contentDescription = null, - tint = DevConsoleTheme.colors.muted, - size = 18.dp, - ) - Box(modifier = Modifier.weight(1f)) { - InspectorPlainTextField( - value = query, - onValueChange = onQueryChange, - placeholder = placeholder, - textColor = DevConsoleTheme.colors.ink, - placeholderColor = DevConsoleTheme.colors.text3, + OutlinedTextField( + value = query, + onValueChange = onQueryChange, + modifier = modifier.fillMaxWidth().padding(horizontal = 16.dp), + placeholder = { Text(placeholder) }, + leadingIcon = { + InspectorGlyphIcon( + InspectorGlyph.Search, + contentDescription = null, + tint = DevConsoleTheme.colors.muted, + size = 18.dp, ) - } - } + }, + singleLine = true, + shape = MaterialTheme.shapes.medium, + colors = + TextFieldDefaults.colors( + focusedContainerColor = DevConsoleTheme.colors.surface2, + unfocusedContainerColor = DevConsoleTheme.colors.surface2, + focusedIndicatorColor = Color.Transparent, + unfocusedIndicatorColor = Color.Transparent, + focusedTextColor = DevConsoleTheme.colors.ink, + unfocusedTextColor = DevConsoleTheme.colors.ink, + focusedPlaceholderColor = DevConsoleTheme.colors.text3, + unfocusedPlaceholderColor = DevConsoleTheme.colors.text3, + ), + ) } /** Extended FAB: flag icon + bold label. Pair with [EvidenceFabScrollClearance]. */ @@ -210,8 +261,8 @@ internal fun EvidenceFab( modifier = modifier .height(56.dp) - .shadow(DevConsoleElevation.level3, RoundedCornerShape(18.dp)) - .clip(RoundedCornerShape(18.dp)) + .shadow(DevConsoleElevation.level3, MaterialTheme.shapes.extraLarge) + .clip(MaterialTheme.shapes.extraLarge) .background(DevConsoleTheme.colors.signal) .clickable(onClick = onClick, role = Role.Button) .padding(horizontal = 20.dp), @@ -231,6 +282,15 @@ internal fun EvidenceFab( /** Bottom content padding a scrolling list needs so its last row clears an [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. + */ +@Composable +private fun navItemIconColor(selected: Boolean): Color = + if (selected) DevConsoleTheme.colors.signalInk else DevConsoleTheme.colors.muted + /** One destination in [InspectorBottomNav]. */ internal data class InspectorNavItem( val label: String, @@ -239,61 +299,66 @@ internal data class InspectorNavItem( val icon: @Composable () -> Unit, ) -/** 4-destination bottom nav: 64x32dp pill indicator, 12sp labels. */ @Composable -internal fun InspectorBottomNav( +internal fun InspectorNavigationBar( items: List, modifier: Modifier = Modifier, ) { - Row( - modifier = - modifier - .fillMaxWidth() - .background(DevConsoleTheme.colors.panel) - .padding(top = 12.dp, start = 4.dp, end = 4.dp, bottom = 16.dp), + NavigationBar( + modifier = modifier, + containerColor = DevConsoleTheme.colors.panel, ) { - items.forEach { item -> InspectorNavDestination(item, modifier = Modifier.weight(1f)) } + 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, + ), + ) + } } } @Composable -private fun InspectorNavDestination( - item: InspectorNavItem, +internal fun InspectorNavigationRail( + items: List, modifier: Modifier = Modifier, ) { - val colors = DevConsoleTheme.colors - val pillColor = if (item.selected) colors.signal else Color.Transparent - val labelColor = if (item.selected) colors.ink else colors.muted - val iconColor = if (item.selected) colors.signalInk else colors.muted - Column( - modifier = - modifier - .heightIn(min = 56.dp) - .clickable(onClick = item.onClick, role = Role.Tab) - // mergeDescendants: without it TalkBack reads the icon and label text as nodes - // separate from the destination's own click target. See InspectorTabRow above - // for the same fix. - .semantics(mergeDescendants = true) { selected = item.selected } - .padding(2.dp), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(4.dp), + NavigationRail( + modifier = modifier, + containerColor = DevConsoleTheme.colors.panel, ) { - Box( - modifier = - Modifier - .width(64.dp) - .height(32.dp) - .clip(RoundedCornerShape(50)) - .background(pillColor), - contentAlignment = Alignment.Center, - ) { - CompositionLocalProvider(LocalContentColor provides iconColor) { item.icon() } + items.forEach { item -> + NavigationRailItem( + selected = item.selected, + onClick = item.onClick, + icon = { + CompositionLocalProvider(LocalContentColor provides navItemIconColor(item.selected)) { + item.icon() + } + }, + label = { Text(item.label) }, + colors = + NavigationRailItemDefaults.colors( + indicatorColor = DevConsoleTheme.colors.signal, + selectedIconColor = DevConsoleTheme.colors.signalInk, + selectedTextColor = DevConsoleTheme.colors.ink, + unselectedIconColor = DevConsoleTheme.colors.muted, + unselectedTextColor = DevConsoleTheme.colors.muted, + ), + ) } - Text( - item.label, - color = labelColor, - fontSize = 12.sp, - fontWeight = if (item.selected) FontWeight.SemiBold else FontWeight.Medium, - ) } } 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 5bef218..051b315 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 @@ -7,15 +7,19 @@ package io.devconsole.ui.compose +import androidx.compose.foundation.layout.Column 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.itemsIndexed import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import java.util.Locale @@ -51,10 +55,12 @@ internal fun CrashesTabContent( } val rowsNewestFirst = remember(searched) { searched.sortedByDescending { it.timestampEpochMs } } + val arrivals = rememberArrivals(rowsNewestFirst.map { it.id }) LazyColumn( modifier = Modifier.fillMaxSize(), - // 12px side/top padding with FAB clearance at the bottom, like every Observe tab's scroll container. - contentPadding = PaddingValues(start = 12.dp, end = 12.dp, top = 12.dp, bottom = EvidenceFabScrollClearance), + // 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), ) { stickyHeader { InspectorSearchBar( @@ -68,7 +74,14 @@ internal fun CrashesTabContent( item { Spacer(Modifier.height(16.dp)) } item { GroupLabel("Newest first") } itemsIndexed(rowsNewestFirst, key = { _, crash -> crash.id }) { _, crash -> - CrashRow(crash, crash.id in ui.flaggedCrashIds, colors) { actions.onOpenCrashDetail(crash.id) } + CrashRow( + crash = crash, + isFlagged = crash.id in ui.flaggedCrashIds, + colors = colors, + modifier = Modifier.animateItem(), + isArrival = crash.id in arrivals, + onClick = { actions.onOpenCrashDetail(crash.id) }, + ) } } } @@ -85,7 +98,6 @@ private fun CrashesHero( value = crashes.size.toString(), label = "crashes and ANRs this session", onExpand = actions.onToggleCrashesHero, - containerColor = colors.errorSoft, valueColor = colors.error, labelColor = colors.error, ) @@ -99,7 +111,6 @@ private fun CrashesHero( subtitle = "$crashCount crash${if (crashCount == 1) "" else "es"}, " + "$anrCount ANR${if (anrCount == 1) "" else "s"} this session.", - containerColor = colors.errorSoft, labelColor = colors.error, valueColor = colors.error, onCollapse = actions.onToggleCrashesHero, @@ -107,25 +118,35 @@ private fun CrashesHero( } /** Container tint mirrors [TrafficRow]'s flagged/unflagged pattern: evidence status surfaces in the row itself. */ +@Suppress("LongParameterList") // Row content, evidence state, and the live-arrival flash. @Composable private fun CrashRow( crash: InspectorCrashUi, isFlagged: Boolean, colors: DevConsoleColors, onClick: () -> Unit, + 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" - TonalListRow( - leadText = logLevelShortLabel(crash.kind), - leadColor = leadColor, - leadContainerColor = leadBg, - 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 colors.surface2, - onClick = onClick, - ) + Column(modifier = modifier.fillMaxWidth()) { + TonalListRow( + isArrival = isArrival, + leadText = logLevelShortLabel(crash.kind), + leadColor = leadColor, + leadContainerColor = leadBg, + 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, + 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/InspectorObserveNetDetail.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveNetDetail.kt index c0c7a26..99a2019 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 @@ -8,49 +8,49 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp /** - * Copy-as-cURL, share-as-JSON, and mock-from-capture header actions. "Pin as diff baseline" is - * dropped: nothing in [InspectorState] tracks a pinned baseline or renders a diff view, so a Pin - * button here would be a no-op affordance -- only header actions with real behavior are included. - * "Mock this response" is always 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. + * 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. */ private fun netHeaderActions( transaction: InspectorTransactionUi, colors: DevConsoleColors, - copyText: (String) -> Unit, shareText: (String, String) -> Unit, - onMockAction: (() -> Unit)?, + isFlagged: Boolean, + onToggleFlag: () -> Unit, ): List = - buildList { - add( - InspectorTopAction( - contentDescription = "Copy as cURL", - onClick = { copyText(transaction.toCurlCommand()) }, - icon = copyIconAction(colors.muted), - ), - ) - add( - InspectorTopAction( - contentDescription = "Share transaction as JSON", - onClick = { shareText(transaction.toJsonSnippet(), "Share transaction JSON") }, - icon = shareIconAction(colors.muted), - ), - ) - if (onMockAction != null) { - add( - InspectorTopAction( - contentDescription = if (transaction.isMocked) "Unmock this response" else "Mock this response", - onClick = onMockAction, - icon = { - ObserveGlyphIcon(ObserveGlyph.Tag, contentDescription = null, tint = colors.muted, size = 18.dp) - }, - ), - ) - } - } + 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 + InspectorGlyphIcon(InspectorGlyph.Flag, contentDescription = null, tint = tint, size = 18.dp) + }, + containerColor = if (isFlagged) colors.signalSoft else Color.Transparent, + ), + ) /** * One [InspectorProgressStat] per captured phase, in wire order. A null phase is legitimately @@ -269,36 +269,56 @@ private fun netSections( ) } +/** + * 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. + */ private fun netFooterActions( transaction: InspectorTransactionUi, colors: DevConsoleColors, - isFlagged: Boolean, - onToggleFlag: () -> Unit, + onMockAction: (() -> Unit)?, 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 = "cURL", - onClick = { copyText(transaction.toCurlCommand()) }, - weight = 1f, - icon = { - InspectorGlyphIcon(InspectorGlyph.Copy, contentDescription = null, tint = colors.ink, size = 18.dp) - }, - containerColor = colors.surface3, - contentColor = colors.ink, - ), - ) + buildList { + if (onMockAction != null) { + add( + InspectorFooterAction( + label = if (transaction.isMocked) "Unmock this response" else "Mock this response", + onClick = onMockAction, + weight = 2f, + icon = { + val tint = if (transaction.isMocked) colors.signal else colors.signalInk + ObserveGlyphIcon(ObserveGlyph.Tag, contentDescription = null, tint = tint, size = 18.dp) + }, + containerColor = if (transaction.isMocked) colors.signalSoft else colors.signal, + contentColor = if (transaction.isMocked) colors.signal else colors.signalInk, + ), + ) + } + add( + InspectorFooterAction( + label = "cURL", + onClick = { copyText(transaction.toCurlCommand()) }, + weight = 1f, + icon = { + InspectorGlyphIcon(InspectorGlyph.Copy, contentDescription = null, tint = colors.ink, size = 18.dp) + }, + containerColor = colors.surface3, + contentColor = colors.ink, + ), + ) + } /** * Builds the full net (HTTP transaction) capture detail, degraded to real fields only. [mockDiff] is @@ -355,12 +375,12 @@ internal fun netDetailContent( subtitle = subtitle, status = transaction.statusCode?.toString() ?: "ERR", statusColor = statusColor, - actions = netHeaderActions(transaction, colors, copyText, shareText, onMockAction), + actions = netHeaderActions(transaction, colors, shareText, isFlagged, onToggleFlag), ), 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 = setOf("req", "res"), - footerActions = netFooterActions(transaction, colors, isFlagged, onToggleFlag, copyText), + footerActions = netFooterActions(transaction, colors, onMockAction, copyText), ) } 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 89be27a..2fad82f 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 @@ -7,6 +7,12 @@ package io.devconsole.ui.compose import android.content.Context +import androidx.compose.animation.AnimatedContent +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.slideInHorizontally +import androidx.compose.animation.slideOutHorizontally +import androidx.compose.animation.togetherWith import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column @@ -29,9 +35,11 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.platform.ClipboardManager import androidx.compose.ui.platform.LocalClipboardManager import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewmodel.compose.viewModel @@ -443,6 +451,58 @@ private fun rememberAppIdentitySubtitle(): String { } } +/** + * The selected tab's content, entering along the axis the tabs themselves run on -- Material's + * shared-axis-X. Moving right slides the incoming content in from the right; moving left reverses + * it, so the transition agrees with the indicator travelling under the tab row and with the + * operator's own sense of where they are in an ordered set. + * + * The offset is [InspectorMotion.sharedAxisOffset], not a screen width: two live capture lists are + * composed at once for the length of this transition, and a short nudge keeps that window brief on + * the low-end hardware this console has to stay honest on. Under reduced motion [feedbackSpec] + * flattens the whole thing to a cut. + * + * Keyed on the tab itself, so each tab's content keeps being a fresh composition on switch exactly + * as the plain `when` made it -- the transition changes how it arrives, never what it holds. + */ +@Composable +private fun ObserveTabPager( + selected: ObserveTab, + visibleTabs: List, + state: InspectorState, + ui: ObserveUiState, + actions: ObserveActions, +) { + // Hoisted out of transitionSpec: that lambda is neither a composable nor a density scope, so + // the gated specs and the dp->px conversion have to be resolved here and captured. + val slideSpec = feedbackSpec() + val fadeSpec = feedbackSpec() + val offsetPx = with(LocalDensity.current) { InspectorMotion.sharedAxisOffset.roundToPx() } + AnimatedContent( + targetState = selected, + transitionSpec = { + val forward = visibleTabs.indexOf(targetState) >= visibleTabs.indexOf(initialState) + val enterFrom = if (forward) 1 else -1 + ( + slideInHorizontally(slideSpec) { width -> enterFrom * minOf(width, offsetPx) } + + fadeIn(fadeSpec) + ) togetherWith ( + slideOutHorizontally(slideSpec) { width -> -enterFrom * minOf(width, offsetPx) } + + fadeOut(fadeSpec) + ) + }, + label = "observeTab", + ) { tab -> + when (tab) { + ObserveTab.TRAFFIC -> TrafficTabContent(state, ui, actions) + ObserveTab.SOCKETS -> SocketsTabContent(state, ui, actions) + ObserveTab.PUSH -> PushTabContent(state, ui, actions) + ObserveTab.LOGS -> LogsTabContent(state, ui, actions) + ObserveTab.CRASHES -> CrashesTabContent(state, ui, actions) + } + } +} + private fun ObserveTab.title(): String = when (this) { ObserveTab.TRAFFIC -> "Traffic" @@ -497,14 +557,7 @@ internal fun ObserveScreen( // 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 -> - when (state.observeTab) { - ObserveTab.TRAFFIC -> TrafficTabContent(state, ui, actions) - ObserveTab.SOCKETS -> SocketsTabContent(state, ui, actions) - ObserveTab.PUSH -> PushTabContent(state, ui, actions) - ObserveTab.LOGS -> LogsTabContent(state, ui, actions) - ObserveTab.CRASHES -> CrashesTabContent(state, ui, actions) - } + else -> ObserveTabPager(state.observeTab, visibleTabs, state, ui, actions) } } } @@ -520,7 +573,7 @@ internal fun ObserveScreen( } /** - * D4's previous-run-crashed marker: the most recent *non-active* session (i.e. not the one + * The previous-run-crashed marker: the most recent *non-active* session (i.e. not the one * currently capturing) whose [InspectorSessionUi.status] is `"CRASHED"` -- mirroring * `StoredSessionStatus.CRASHED`, which `io.devconsole.CrashCapture.markCrashed` writes on every * uncaught exception, and which session bootstrap writes for a run that died before that could 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 35bebd4..24fa3ec 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 @@ -11,10 +11,13 @@ package io.devconsole.ui.compose import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column 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.itemsIndexed import androidx.compose.material3.Text @@ -22,6 +25,7 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import io.devconsole.api.CaptureCategory import java.util.Locale @@ -59,11 +63,12 @@ internal fun SocketsTabContent( } } } + val arrivals = rememberArrivals(searchedIndices.map { frameKeys[it] }) LazyColumn( modifier = Modifier.fillMaxSize(), - // 12dp start/end/top padding, extra bottom clearance for every Observe tab's scroll container. - contentPadding = PaddingValues(start = 12.dp, end = 12.dp, top = 12.dp, bottom = EvidenceFabScrollClearance), + // 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), ) { stickyHeader { InspectorSearchBar( @@ -78,7 +83,14 @@ internal fun SocketsTabContent( item { GroupLabel("Recent frames") } itemsIndexed(searchedIndices, key = { _, index -> frameKeys[index] }) { _, index -> val (socket, frame) = recentFrames[index] - SocketFrameRow(socket, frame, colors) { actions.onOpenFrameDetail(socket, frame) } + SocketFrameRow( + socket = socket, + frame = frame, + colors = colors, + modifier = Modifier.animateItem(), + isArrival = frameKeys[index] in arrivals, + onClick = { actions.onOpenFrameDetail(socket, frame) }, + ) } } } @@ -96,7 +108,6 @@ private fun SocketsHero( value = openCount.toString(), label = "of ${sockets.size} connections open", onExpand = actions.onToggleSocketsHero, - containerColor = colors.surface2, valueColor = colors.signal, labelColor = colors.text3, ) @@ -121,19 +132,21 @@ private fun SocketsHero( value = openCount.toString(), valueSuffix = "of ${sockets.size}", subtitle = sub, - containerColor = colors.surface2, labelColor = colors.text3, valueColor = colors.signal, onCollapse = actions.onToggleSocketsHero, ) } +@Suppress("LongParameterList") // Row content, its socket, and the live-arrival flash. @Composable private fun SocketFrameRow( socket: InspectorSocketUi, frame: InspectorSocketFrameUi, colors: DevConsoleColors, onClick: () -> Unit, + modifier: Modifier = Modifier, + isArrival: Boolean = false, ) { val received = frame.direction == "RECEIVED" val leadColor = if (received) colors.put else colors.signal @@ -143,18 +156,25 @@ private fun SocketFrameRow( // An MQTT frame's topic is what an operator scanning this list actually wants to see -- the // socket's own URL is just the broker address, identical across every message on the connection. val title = frame.topic ?: path - TonalListRow( - leadText = if (received) "↓" else "↑", - leadColor = leadColor, - leadContainerColor = leadBg, - title = title, - subtitle = "$protocolBadge · ${frame.frameType} · ${frame.preview.orEmpty().take(34)}", - trailValue = socketFrameSizeLabel(frame), - trailValueColor = colors.ink, - trailSubtitle = formatCaptureClockTime(frame.timestampEpochMs), - containerColor = colors.surface2, - onClick = onClick, - ) + Column(modifier = modifier.fillMaxWidth()) { + TonalListRow( + isArrival = isArrival, + leadText = if (received) "↓" else "↑", + leadColor = leadColor, + leadContainerColor = leadBg, + title = title, + subtitle = "$protocolBadge · ${frame.frameType} · ${frame.preview.orEmpty().take(34)}", + trailValue = socketFrameSizeLabel(frame), + trailValueColor = colors.ink, + trailSubtitle = formatCaptureClockTime(frame.timestampEpochMs), + containerColor = Color.Transparent, + onClick = onClick, + ) + androidx.compose.material3.HorizontalDivider( + modifier = Modifier.padding(start = 76.dp), + color = colors.line, + ) + } } /** "MQTT" for an MQTT-protocol connection, "WS" otherwise -- shown as a prefix in [SocketFrameRow]'s subtitle. */ @@ -204,11 +224,12 @@ internal fun PushTabContent( } } } + val arrivals = rememberArrivals(searchedIndices.map { pushKeys[it] }) LazyColumn( modifier = Modifier.fillMaxSize(), - // 12dp start/end/top padding, extra bottom clearance for every Observe tab's scroll container. - contentPadding = PaddingValues(start = 12.dp, end = 12.dp, top = 12.dp, bottom = EvidenceFabScrollClearance), + // 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), ) { stickyHeader { InspectorSearchBar( @@ -223,7 +244,13 @@ internal fun PushTabContent( item { GroupLabel("Lifecycle") } itemsIndexed(searchedIndices, key = { _, index -> pushKeys[index] }) { _, index -> val push = state.pushEvents[index] - PushRow(push, colors) { actions.onOpenPushDetail(push) } + PushRow( + push = push, + colors = colors, + modifier = Modifier.animateItem(), + isArrival = pushKeys[index] in arrivals, + onClick = { actions.onOpenPushDetail(push) }, + ) } } } @@ -240,7 +267,6 @@ private fun PushHero( value = pushEvents.size.toString(), label = "push events delivered", onExpand = actions.onTogglePushHero, - containerColor = colors.surface2, valueColor = colors.ink, labelColor = colors.text3, ) @@ -259,7 +285,6 @@ private fun PushHero( value = pushEvents.size.toString(), valueSuffix = "events", subtitle = sub, - containerColor = colors.surface2, labelColor = colors.text3, valueColor = colors.ink, onCollapse = actions.onTogglePushHero, @@ -271,22 +296,31 @@ private fun PushRow( push: InspectorPushUi, colors: DevConsoleColors, onClick: () -> Unit, + 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" - TonalListRow( - leadText = push.provider.uppercase(Locale.US), - leadColor = leadColor, - leadContainerColor = leadBg, - title = title, - subtitle = "${push.messageId ?: "no id"} · ${if (push.simulated) "simulated" else "captured"}", - trailValue = pushLifecycleShortLabel(push.lifecycle), - trailValueColor = colors.muted, - trailSubtitle = formatCaptureClockTimeShort(push.receivedAtEpochMs), - containerColor = colors.surface2, - onClick = onClick, - ) + Column(modifier = modifier.fillMaxWidth()) { + TonalListRow( + isArrival = isArrival, + leadText = push.provider.uppercase(Locale.US), + leadColor = leadColor, + leadContainerColor = leadBg, + title = title, + subtitle = "${push.messageId ?: "no id"} · ${if (push.simulated) "simulated" else "captured"}", + trailValue = pushLifecycleShortLabel(push.lifecycle), + trailValueColor = colors.muted, + trailSubtitle = formatCaptureClockTimeShort(push.receivedAtEpochMs), + containerColor = Color.Transparent, + onClick = onClick, + ) + androidx.compose.material3.HorizontalDivider( + modifier = Modifier.padding(start = 76.dp), + color = colors.line, + ) + } } /** Logs tab: warnings+errors hero + a newest-first event list. */ @@ -315,11 +349,12 @@ internal fun LogsTabContent( } } val rowsNewestFirst = searched.asReversed() + val arrivals = rememberArrivals(rowsNewestFirst.map { it.id }) LazyColumn( modifier = Modifier.fillMaxSize(), - // 12dp start/end/top padding, extra bottom clearance for every Observe tab's scroll container. - contentPadding = PaddingValues(start = 12.dp, end = 12.dp, top = 12.dp, bottom = EvidenceFabScrollClearance), + // 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), ) { stickyHeader { InspectorSearchBar( @@ -333,7 +368,13 @@ internal fun LogsTabContent( item { Spacer(Modifier.height(16.dp)) } item { GroupLabel("Newest first") } itemsIndexed(rowsNewestFirst, key = { _, log -> log.id }) { _, log -> - LogRow(log, colors) { actions.onOpenLogDetail(log.id) } + LogRow( + log = log, + colors = colors, + modifier = Modifier.animateItem(), + isArrival = log.id in arrivals, + onClick = { actions.onOpenLogDetail(log.id) }, + ) } } } @@ -351,7 +392,6 @@ private fun LogsHero( value = flagged.size.toString(), label = "of ${logs.size} events need attention", onExpand = actions.onToggleLogsHero, - containerColor = colors.warnSoft, valueColor = colors.warn, labelColor = colors.warn, ) @@ -376,7 +416,6 @@ private fun LogsHero( value = flagged.size.toString(), valueSuffix = "of ${logs.size}", subtitle = sub, - containerColor = colors.warnSoft, labelColor = colors.warn, valueColor = colors.warn, onCollapse = actions.onToggleLogsHero, @@ -388,19 +427,28 @@ private fun LogRow( log: InspectorLogUi, colors: DevConsoleColors, onClick: () -> Unit, + modifier: Modifier = Modifier, + isArrival: Boolean = false, ) { val (leadColor, leadBg) = logLevelTint(log.kind, colors) - TonalListRow( - leadText = logLevelShortLabel(log.kind), - leadColor = leadColor, - leadContainerColor = leadBg, - 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, - containerColor = colors.surface2, - onClick = onClick, - ) + Column(modifier = modifier.fillMaxWidth()) { + TonalListRow( + isArrival = isArrival, + leadText = logLevelShortLabel(log.kind), + leadColor = leadColor, + leadContainerColor = leadBg, + 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, + containerColor = Color.Transparent, + onClick = onClick, + ) + androidx.compose.material3.HorizontalDivider( + modifier = Modifier.padding(start = 76.dp), + color = colors.line, + ) + } } @Composable 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 13328f2..6559f0e 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 @@ -27,7 +27,7 @@ import androidx.compose.foundation.lazy.items import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.selection.toggleable import androidx.compose.foundation.shape.CircleShape -import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.minimumInteractiveComponentSize import androidx.compose.runtime.Composable @@ -145,9 +145,10 @@ private fun TrafficList( colors: DevConsoleColors, selection: TrafficSelection, ) { + val arrivals = rememberArrivals(stats.rowsNewestFirst.map { it.id }) LazyColumn( modifier = Modifier.fillMaxSize(), - contentPadding = PaddingValues(start = 12.dp, end = 12.dp, top = 12.dp, bottom = EvidenceFabScrollClearance), + contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = 12.dp, bottom = EvidenceFabScrollClearance), ) { stickyHeader { if (selection.modeActive) { @@ -191,6 +192,8 @@ private fun TrafficList( selectionModeActive = selection.modeActive, colors = colors, actions = actions, + isArrival = transaction.id in arrivals, + modifier = Modifier.animateItem(), ) } } @@ -223,7 +226,7 @@ private fun TrafficSelectionBar( modifier = Modifier .fillMaxWidth() - .clip(RoundedCornerShape(20.dp)) + .clip(MaterialTheme.shapes.large) .background(colors.surface2) .padding(horizontal = 12.dp, vertical = 10.dp), ) { @@ -322,7 +325,6 @@ private fun TrafficHero( value = stats.failCount.toString(), label = "of ${stats.total} requests failing", onExpand = actions.onToggleTrafficHero, - containerColor = if (failing) colors.errorSoft else colors.surface2, valueColor = if (failing) colors.error else colors.ink, labelColor = if (failing) colors.error else colors.text3, ) @@ -338,7 +340,6 @@ private fun TrafficHero( } else { "No failing requests out of ${stats.total} captured." }, - containerColor = if (failing) colors.errorSoft else colors.surface2, labelColor = if (failing) colors.error else colors.text3, valueColor = if (failing) colors.error else colors.ink, onCollapse = actions.onToggleTrafficHero, @@ -366,59 +367,68 @@ private fun TrafficRow( selectionModeActive: Boolean, colors: DevConsoleColors, actions: ObserveActions, + modifier: Modifier = Modifier, + isArrival: Boolean = false, ) { val (leadColor, leadBg) = methodTint(transaction.method, colors) val mockedSuffix = if (transaction.isMocked) " · mocked" else "" - TonalListRow( - leadText = methodLeadText(transaction.method), - leadColor = leadColor, - leadContainerColor = leadBg, - title = transaction.path.substringBefore('?'), - subtitle = "${transaction.host} · ${formatCaptureClockTime(transaction.startedAtEpochMs)}$mockedSuffix", - trailValue = transaction.statusCode?.toString() ?: "ERR", - trailValueColor = statusTint(transaction.statusCode, colors), - trailSubtitle = - when { - transaction.statusCode == null -> "timeout" - transaction.durationMs != null -> "${transaction.durationMs} ms" - else -> null - }, - containerColor = - if (isSelected) { - colors.putSoft - } else if (isFlagged) { - colors.signalSoft - } else { - colors.surface2 - }, - leading = - if (selectionModeActive) { - { - TrafficRowSelectionCheckbox( - checked = isSelected, - onToggle = { actions.onToggleTransactionSelection(transaction.id) }, - ) + Column(modifier = modifier.fillMaxWidth()) { + TonalListRow( + isArrival = isArrival, + leadText = methodLeadText(transaction.method), + leadColor = leadColor, + leadContainerColor = leadBg, + title = transaction.path.substringBefore('?'), + subtitle = "${transaction.host} · ${formatCaptureClockTime(transaction.startedAtEpochMs)}$mockedSuffix", + trailValue = transaction.statusCode?.toString() ?: "ERR", + trailValueColor = statusTint(transaction.statusCode, colors), + trailSubtitle = + when { + transaction.statusCode == null -> "timeout" + transaction.durationMs != null -> "${transaction.durationMs} ms" + else -> null + }, + containerColor = + if (isSelected) { + colors.surface2 + } else if (isFlagged) { + colors.signalSoft + } else { + Color.Transparent + }, + leading = + if (selectionModeActive) { + { + TrafficRowSelectionCheckbox( + checked = isSelected, + onToggle = { actions.onToggleTransactionSelection(transaction.id) }, + ) + } + } else { + null + }, + // Long-press always toggles (entering selection mode on the first hit, since a non-empty + // selection *is* selection mode -- see TrafficTabContent). A plain tap opens the detail + // overlay normally, and instead toggles once selection mode is already active, matching the + // standard Android "long-press to start selecting, tap to extend" idiom. + onClick = { + if (selectionModeActive) { + actions.onToggleTransactionSelection(transaction.id) + } else { + actions.onOpenNetDetail(transaction.id) } - } else { - null }, - // Long-press always toggles (entering selection mode on the first hit, since a non-empty - // selection *is* selection mode -- see TrafficTabContent). A plain tap opens the detail - // overlay normally, and instead toggles once selection mode is already active, matching the - // standard Android "long-press to start selecting, tap to extend" idiom. - onClick = { - if (selectionModeActive) { - actions.onToggleTransactionSelection(transaction.id) - } else { - actions.onOpenNetDetail(transaction.id) - } - }, - onLongClick = { actions.onToggleTransactionSelection(transaction.id) }, - // The leading checkbox only exists once selection mode is active -- only then does it need - // to stay out of the row's merged semantics node so TalkBack exposes both the row's - // tap/long-press action and the checkbox's toggle independently. - mergeDescendants = !selectionModeActive, - ) + onLongClick = { actions.onToggleTransactionSelection(transaction.id) }, + // The leading checkbox only exists once selection mode is active -- only then does it need + // to stay out of the row's merged semantics node so TalkBack exposes both the row's + // 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, + ) + } } /** Circular selection-mode checkbox (mirrors [InspectorChip]'s filled/outline convention for the checked state). */ diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorThemePreference.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorThemePreference.kt new file mode 100644 index 0000000..a14bb2d --- /dev/null +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorThemePreference.kt @@ -0,0 +1,32 @@ +package io.devconsole.ui.compose + +import android.content.Context + +internal interface InspectorThemePreferenceStore { + fun readOverride(): Boolean? + + fun writeOverride(dark: Boolean) +} + +internal class SharedPreferencesInspectorThemeStore( + context: Context, +) : InspectorThemePreferenceStore { + private val preferences = + context.getSharedPreferences("devconsole.ui", Context.MODE_PRIVATE) + + override fun readOverride(): Boolean? = + if (preferences.contains(KEY_DARK_THEME)) preferences.getBoolean(KEY_DARK_THEME, false) else null + + override fun writeOverride(dark: Boolean) { + preferences.edit().putBoolean(KEY_DARK_THEME, dark).apply() + } + + private companion object { + const val KEY_DARK_THEME = "dark_theme_override" + } +} + +internal fun resolveDarkTheme( + override: Boolean?, + systemDark: Boolean, +): Boolean = override ?: systemDark diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorUiComponents.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorUiComponents.kt index ba40320..cc4d5dc 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorUiComponents.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorUiComponents.kt @@ -6,13 +6,11 @@ package io.devconsole.ui.compose -import androidx.compose.foundation.border 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.Surface +import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier @@ -61,34 +59,24 @@ internal object TerminalType { lineHeight = 16.sp, lineHeightStyle = m3SlotLineHeightStyle, ) - - // letterSpacing 0.2 (not 0.25): m3 1.4.0's BodyMediumTracking, which this slot replaces. - val bodyMedium = - TextStyle( - fontSize = 14.sp, - letterSpacing = 0.2.sp, - lineHeight = 20.sp, - lineHeightStyle = m3SlotLineHeightStyle, - ) } -/** Shared bordered panel used by the Observe and Control surfaces to match the workspace shell. */ +/** + * Shared section container for the Data screen's Files and Database blocks: a rule, then content. + * + * Flat on purpose, like [CollapsibleSection] and [HeroCard] and like the dashboard's own + * `.card-shell` (`border: 0; border-radius: 0; background: transparent`). It used to be a 14dp + * bordered panel, which left the Data screen wearing card chrome after every sibling surface had + * dropped it -- the same list could show a bordered card directly above a flat [TonalListRow]. + */ @Composable internal fun TerminalCard( modifier: Modifier = Modifier, content: @Composable ColumnScope.() -> Unit, ) { - val colors = DevConsoleTheme.colors - Surface( - modifier = - modifier - .fillMaxWidth() - .border(1.dp, colors.borderStrong, RoundedCornerShape(14.dp)), - shape = RoundedCornerShape(14.dp), - color = colors.ground, - tonalElevation = 0.dp, - ) { - Column(modifier = Modifier.padding(16.dp), content = content) + Column(modifier = modifier.fillMaxWidth()) { + HorizontalDivider(color = DevConsoleTheme.colors.line) + Column(modifier = Modifier.padding(vertical = 12.dp), content = content) } } @@ -121,17 +109,6 @@ internal fun CapabilityDisabledNotice( ) } -@Composable -internal fun DetailStat( - label: String, - value: String, -) { - Column { - TerminalSectionLabel(label) - Text(value, color = DevConsoleTheme.colors.ink, style = TerminalType.bodyMedium) - } -} - /** Muted single-line notice used when a Data section has nothing to show. */ @Composable internal fun SectionEmptyText(message: String) { 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 05b2cf0..63d3458 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 @@ -6,6 +6,12 @@ package io.devconsole.ui.compose +import androidx.compose.animation.core.FastOutSlowInEasing +import androidx.compose.animation.core.RepeatMode +import androidx.compose.animation.core.animateFloat +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.layout.Arrangement import androidx.compose.foundation.layout.Box @@ -15,14 +21,18 @@ 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.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf +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.graphics.graphicsLayer import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp @@ -42,8 +52,13 @@ internal data class InspectorUrlAction( ) /** - * A surface-2 card with a status dot + uppercase label, a mono 16sp URL, a muted sub line, and a + * 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. */ @Suppress("LongParameterList") // Every field varies per screen. @Composable @@ -56,15 +71,17 @@ internal fun InspectorUrlCard( modifier: Modifier = Modifier, labelColor: Color = DevConsoleTheme.colors.text3, urlColor: Color = DevConsoleTheme.colors.ink, + /** `true` while the session this card describes is live or still settling -- see [Box8Dot]. */ + dotPulsing: Boolean = false, ) { Surface( modifier = modifier.fillMaxWidth(), - shape = RoundedCornerShape(24.dp), + shape = MaterialTheme.shapes.large, color = DevConsoleTheme.colors.surface2, ) { Column(modifier = Modifier.padding(16.dp)) { Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { - Box8Dot(dotColor) + Box8Dot(dotColor, dotPulsing) Text( label.uppercase(), color = labelColor, @@ -107,7 +124,42 @@ internal fun InspectorUrlCard( } } +/** + * The status dot of the URL card's signature readout, with the dashboard's `dcPulse` breath: + * opacity 1 -> [InspectorMotion.PULSE_MIN_ALPHA] -> 1 over [InspectorMotion.PULSE_PERIOD_MS]. + * + * [pulsing] is state, not decoration -- a live session and a session waiting to reconnect breathe; + * a stopped one holds steady, exactly as the dashboard stills the dot with `animation: none` once + * the session is expired. Reduced motion stills it too: the dot's color already carries the state, + * so nothing is lost when the breath is taken away. + */ @Composable -private fun Box8Dot(color: Color) { - Box(modifier = Modifier.size(8.dp).clip(CircleShape).background(color)) +private fun Box8Dot( + color: Color, + pulsing: Boolean, +) { + val transition = rememberInfiniteTransition(label = "statusDot") + val alpha by + if (pulsing && !LocalReduceMotion.current) { + transition.animateFloat( + initialValue = 1f, + targetValue = InspectorMotion.PULSE_MIN_ALPHA, + animationSpec = + infiniteRepeatable( + animation = tween(InspectorMotion.PULSE_PERIOD_MS / 2, easing = FastOutSlowInEasing), + repeatMode = RepeatMode.Reverse, + ), + label = "statusDotAlpha", + ) + } else { + remember { mutableFloatStateOf(1f) } + } + Box( + modifier = + Modifier + .size(8.dp) + .graphicsLayer { this.alpha = alpha } + .clip(CircleShape) + .background(color), + ) } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/KeepAliveNotificationPrompt.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/KeepAliveNotificationPrompt.kt index ffbd194..2df0d45 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/KeepAliveNotificationPrompt.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/KeepAliveNotificationPrompt.kt @@ -15,14 +15,12 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect /** - * Process-scoped dismissal: closing the snackbar silences it until the next app run, matching the - * spec ("in-memory, reappears next app run") without any persistence. + * Process-scoped dismissal: closing the snackbar silences it until the next app run, with no + * persistence. * - * Kept as a top-level property rather than the brief's `object KeepAlivePromptState` wrapper -- - * detekt's `MatchingDeclarationName` flags a lone top-level object whose name doesn't match the - * file name (`KeepAliveNotificationPrompt.kt`), and this file's name is fixed by the task spec. - * A private top-level `var` is JVM-static-backed, so it's the same process-scoped storage with - * one fewer top-level type for the rule to trip on. + * A top-level property rather than an enclosing object: detekt's `MatchingDeclarationName` flags a + * lone top-level object whose name doesn't match the file name. A private top-level `var` is + * JVM-static-backed, so it's the same process-scoped storage with one fewer type to name. */ private var keepAlivePromptDismissedThisProcess: Boolean = false diff --git a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/ArrivalTrackerTest.kt b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/ArrivalTrackerTest.kt new file mode 100644 index 0000000..b9c0535 --- /dev/null +++ b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/ArrivalTrackerTest.kt @@ -0,0 +1,59 @@ +/** + * @author Shakib + * @since 11/08/26 + */ +package io.devconsole.ui.compose + +import org.junit.Assert.assertEquals +import org.junit.Test + +class ArrivalTrackerTest { + @Test + fun `the first snapshot never flashes`() { + val tracker = ArrivalTracker() + + // A screen opening onto a session's worth of retained captures must not wash every row in + // signal -- only what lands while the operator is watching counts as an arrival. + assertEquals(emptySet(), tracker.accept(listOf("a", "b", "c"))) + } + + @Test + fun `reports only the ids added since the previous snapshot`() { + val tracker = ArrivalTracker() + tracker.accept(listOf("a", "b")) + + assertEquals(setOf("c"), tracker.accept(listOf("c", "a", "b"))) + assertEquals(setOf("d", "e"), tracker.accept(listOf("e", "d", "c", "a", "b"))) + } + + @Test + fun `an unchanged snapshot reports nothing`() { + val tracker = ArrivalTracker() + tracker.accept(listOf("a", "b")) + + assertEquals(emptySet(), tracker.accept(listOf("a", "b"))) + assertEquals(emptySet(), tracker.accept(listOf("b", "a"))) + } + + @Test + fun `an id that leaves and returns counts as a new arrival`() { + val tracker = ArrivalTracker() + tracker.accept(listOf("a", "b")) + + // "b" drops out -- a search filter narrowing, or the retained buffer evicting it. + assertEquals(emptySet(), tracker.accept(listOf("a"))) + // Coming back is a genuine arrival on screen, and is flashed as one. + assertEquals(setOf("b"), tracker.accept(listOf("a", "b"))) + } + + @Test + fun `forgets ids that leave so the seen set cannot grow without bound`() { + val tracker = ArrivalTracker() + tracker.accept(List(1_000) { "id-$it" }) + + // The whole first batch has been evicted; a single retained row is not an arrival, and the + // tracker is not still holding the thousand ids that scrolled out of the buffer. + assertEquals(emptySet(), tracker.accept(listOf("id-999"))) + assertEquals(setOf("id-0"), tracker.accept(listOf("id-999", "id-0"))) + } +} diff --git a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/DevConsoleWorkspaceTest.kt b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/DevConsoleWorkspaceTest.kt index 1c32236..27419d1 100644 --- a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/DevConsoleWorkspaceTest.kt +++ b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/DevConsoleWorkspaceTest.kt @@ -1,5 +1,6 @@ package io.devconsole.ui.compose +import androidx.compose.ui.unit.dp import org.junit.Assert.assertEquals import org.junit.Test @@ -11,4 +12,14 @@ class DevConsoleWorkspaceTest { InspectorDestination.entries.map { it.label }, ) } + + @Test + fun `adaptive boundary does not change destination order`() { + assertEquals( + listOf("Observe", "Control", "Data", "More"), + InspectorDestination.entries.map(InspectorDestination::label), + ) + assertEquals(InspectorNavigationLayout.Bar, inspectorNavigationLayout(360.dp)) + assertEquals(InspectorNavigationLayout.Rail, inspectorNavigationLayout(840.dp)) + } } diff --git a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorAdaptiveLayoutTest.kt b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorAdaptiveLayoutTest.kt new file mode 100644 index 0000000..f1703bc --- /dev/null +++ b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorAdaptiveLayoutTest.kt @@ -0,0 +1,15 @@ +package io.devconsole.ui.compose + +import androidx.compose.ui.unit.dp +import org.junit.Assert.assertEquals +import org.junit.Test + +class InspectorAdaptiveLayoutTest { + @Test fun `compact width uses navigation bar`() { + assertEquals(InspectorNavigationLayout.Bar, inspectorNavigationLayout(599.dp)) + } + + @Test fun `expanded width uses navigation rail`() { + assertEquals(InspectorNavigationLayout.Rail, inspectorNavigationLayout(600.dp)) + } +} diff --git a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorThemePreferenceTest.kt b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorThemePreferenceTest.kt new file mode 100644 index 0000000..3110c95 --- /dev/null +++ b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorThemePreferenceTest.kt @@ -0,0 +1,35 @@ +package io.devconsole.ui.compose + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class InspectorThemePreferenceTest { + @Test + fun `missing override delegates to system theme`() { + val store = FakeThemePreferenceStore() + assertNull(store.readOverride()) + assertEquals(true, resolveDarkTheme(store.readOverride(), systemDark = true)) + assertEquals(false, resolveDarkTheme(store.readOverride(), systemDark = false)) + } + + @Test + fun `explicit override wins and survives a new store read`() { + val values = mutableMapOf() + val store = FakeThemePreferenceStore(values) + store.writeOverride(true) + + assertEquals(true, FakeThemePreferenceStore(values).readOverride()) + assertEquals(true, resolveDarkTheme(store.readOverride(), systemDark = false)) + } +} + +private class FakeThemePreferenceStore( + private val values: MutableMap = mutableMapOf(), +) : InspectorThemePreferenceStore { + override fun readOverride(): Boolean? = values["dark"] + + override fun writeOverride(dark: Boolean) { + values["dark"] = dark + } +} diff --git a/update.py b/update.py new file mode 100644 index 0000000..c2bad70 --- /dev/null +++ b/update.py @@ -0,0 +1,14 @@ +import re +import os + +html_path = 'sdk/server-ktor/src/main/resources/devconsole-web/index.html' +css_path = 'sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css' + +with open(html_path, 'r') as f: + html = f.read() + +# Replace metrics-strip with metric-strip +html = html.replace('metrics-strip', 'metric-strip') + +with open(html_path, 'w') as f: + f.write(html)