From afb364200c7bfcd4da8a32d6bf9609251fd045da Mon Sep 17 00:00:00 2001 From: shakibuzzaman Date: Mon, 17 Aug 2026 10:10:41 +0600 Subject: [PATCH 01/20] docs: specify LAN and mock defaults --- ...2026-08-17-default-lan-and-mocks-design.md | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 docs/superpowers/specs/2026-08-17-default-lan-and-mocks-design.md diff --git a/docs/superpowers/specs/2026-08-17-default-lan-and-mocks-design.md b/docs/superpowers/specs/2026-08-17-default-lan-and-mocks-design.md new file mode 100644 index 0000000..a20e5d5 --- /dev/null +++ b/docs/superpowers/specs/2026-08-17-default-lan-and-mocks-design.md @@ -0,0 +1,33 @@ +# Default LAN and Mock Behavior + +## Summary + +Make LAN the primary server-binding default across the library while retaining loopback as an explicit secondary choice. Preserve the full/debug runtime's enabled mock engine by default and keep the noop/release artifact's mock engine disabled for production safety. + +## Behavior and interfaces + +- `BrowserConfig()` defaults to `BrowserBinding.LAN`, affecting the in-app inspector More-screen Start action. +- `StartRequest()` defaults to `BindingMode.LAN`, affecting programmatic `DevConsole.startBrowser()` calls. +- The lower-level `sdk:server-api` `StartRequest()` default is aligned to LAN so its published abstraction has no conflicting default. +- Hosts can explicitly select `BrowserBinding.LOOPBACK` or `BindingMode.LOOPBACK`; all existing LAN permission and eligible-interface checks remain unchanged. +- The full/debug `MockEngine` remains enabled by default. The noop/release `MockEngine` remains disabled, and explicit capture-category gating still takes precedence. + +## Implementation and documentation + +- Change the existing constructor defaults and stale KDoc/comments in `sdk:api` and `sdk:server-api`. +- Update README, setup, and threat-model guidance to describe LAN as the default and loopback as the explicit safer override. +- Do not add a new configuration field or alter permission handling, capture-category semantics, mock kill-switch behavior, or UI loading-state defaults. + +## Tests and acceptance + +- API tests assert LAN defaults for `BrowserConfig()` and public `StartRequest()`. +- Server-API tests assert the aligned lower-level `StartRequest()` default. +- Full-runtime tests assert default More-screen LAN binding, explicit loopback binding, and enabled full-runtime mocks. +- Noop tests assert mocks remain disabled. +- Run affected API, server, mocks, and full unit tests plus compilation/API checks; confirm no documentation or comments still claim loopback is the default. + +## Assumptions + +- “Default mock enabled” means the real/debug library runtime only; the noop artifact is intentionally excluded. +- “Default LAN enabled” applies to both existing start entry points, not just the in-app More screen. +- Loopback remains available and is never selected automatically as a fallback when LAN was requested. From 2e8940b127aaa0ee8f341559ef80a37d00ea016f Mon Sep 17 00:00:00 2001 From: shakibuzzaman Date: Mon, 17 Aug 2026 10:20:37 +0600 Subject: [PATCH 02/20] docs: add LAN defaults implementation plan --- .../2026-08-17-default-lan-and-mocks-plan.md | 398 ++++++++++++++++++ 1 file changed, 398 insertions(+) create mode 100644 docs/superpowers/plans/2026-08-17-default-lan-and-mocks-plan.md diff --git a/docs/superpowers/plans/2026-08-17-default-lan-and-mocks-plan.md b/docs/superpowers/plans/2026-08-17-default-lan-and-mocks-plan.md new file mode 100644 index 0000000..9ab69ea --- /dev/null +++ b/docs/superpowers/plans/2026-08-17-default-lan-and-mocks-plan.md @@ -0,0 +1,398 @@ +# Default LAN and Mock Behavior 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 LAN the default for both existing server-start APIs, preserve explicit loopback opt-out behavior, and lock the full/noop mock defaults with regression tests. + +**Architecture:** Change the defaults at the existing public constructor boundaries rather than adding a new policy field. The full runtime already constructs its `MockEngine` enabled and the noop runtime constructs it disabled; tests will make those contracts explicit. Runtime permission checks, capture-category gating, and explicit binding branches remain unchanged. + +**Tech Stack:** Kotlin/JVM and Kotlin Android libraries, JUnit 4, Robolectric, Gradle, Markdown documentation. + +--- + +### Task 1: Lock the public and lower-level LAN defaults with failing tests + +**Files:** +- Modify: `sdk/api/src/test/kotlin/io/devconsole/api/FocusedConfigurationTest.kt` +- Modify: `sdk/api/src/test/kotlin/io/devconsole/api/DevConsoleContractTest.kt` +- Create: `sdk/server-api/src/test/kotlin/io/devconsole/server/api/StartRequestDefaultsTest.kt` + +- [ ] **Step 1: Change the focused API default assertion** + +In `FocusedConfigurationTest`, rename the test to `focused policies use persistent sessions and LAN defaults` and change the binding assertion to: + +```kotlin +assertEquals(BrowserBinding.LAN, browser.binding) +``` + +- [ ] **Step 2: Add the public `StartRequest` default assertion** + +In `DevConsoleContractTest`, add this test next to the existing `StartRequest` validation test: + +```kotlin +@Test +fun `default start request uses LAN binding`() { + assertEquals(BindingMode.LAN, StartRequest().bindingMode) +} +``` + +The file already lives in `io.devconsole.api`, so no new imports are needed. + +- [ ] **Step 3: Add the server-api default assertion** + +Create `StartRequestDefaultsTest.kt` with: + +```kotlin +package io.devconsole.server.api + +import org.junit.Assert.assertEquals +import org.junit.Test + +class StartRequestDefaultsTest { + @Test + fun `default server start request uses LAN binding`() { + assertEquals(BindingMode.LAN, StartRequest().bindingMode) + } +} +``` + +- [ ] **Step 4: Run the focused tests and verify they fail for the old defaults** + +Run: + +```bash +./gradlew :sdk:api:test --tests io.devconsole.api.FocusedConfigurationTest --tests io.devconsole.api.DevConsoleContractTest :sdk:server-api:test --tests io.devconsole.server.api.StartRequestDefaultsTest +``` + +Expected: the new/changed assertions fail because the current defaults are `LOOPBACK`. + +- [ ] **Step 5: Commit the failing contract tests** + +```bash +git add sdk/api/src/test/kotlin/io/devconsole/api/FocusedConfigurationTest.kt \ + sdk/api/src/test/kotlin/io/devconsole/api/DevConsoleContractTest.kt \ + sdk/server-api/src/test/kotlin/io/devconsole/server/api/StartRequestDefaultsTest.kt +git commit -m "test: define LAN binding defaults" +``` + +### Task 2: Lock full-runtime, noop, and mock-engine behavior with failing tests + +**Files:** +- Modify: `sdk/mocks/src/test/kotlin/io/devconsole/mocks/MockEngineTest.kt` +- Modify: `sdk/full/src/test/kotlin/io/devconsole/FullFacadeTest.kt` +- Modify: `sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderMoreScreenBindingTest.kt` +- Modify: `sdk/noop/src/test/kotlin/io/devconsole/NoopFacadeTest.kt` + +- [ ] **Step 1: Add the direct mock-engine default test** + +In `MockEngineTest`, add: + +```kotlin +@Test +fun `mock engine is enabled by default`() { + assertTrue(MockEngine(emptyList()).isEnabled()) +} +``` + +Use the file’s existing `assertTrue` import. + +- [ ] **Step 2: Update the full facade’s default-start expectation and assert the full mock default** + +In `FullFacadeTest`’s `FR-BUILD-002 full facade initializes the enabled runtime` test, keep the existing `StartRequest()` call, change: + +```kotlin +assertEquals(BindingMode.LAN, started.endpoint.bindingMode) +``` + +and add this assertion after initialization, before starting the server: + +```kotlin +assertTrue(provider.mockEngine().isEnabled()) +``` + +- [ ] **Step 3: Change the More-screen default test into a LAN assertion and add an explicit loopback test** + +In `PlatformFacadeProviderMoreScreenBindingTest`: + +1. Update the class KDoc so it says the default config binds LAN and loopback is the explicit secondary choice. +2. Rename `More screen start still binds loopback under the default config` to `More screen start binds LAN under the default config` and change its assertion to: + +```kotlin +assertEquals(BindingMode.LAN, provider.startFromMoreScreen().bindingMode) +``` + +3. Add this explicit opt-out test: + +```kotlin +@Test +fun `More screen start binds loopback when the host explicitly configures loopback`() = + runTest { + val provider = PlatformFacadeProvider() + provider.initialize( + ApplicationProvider.getApplicationContext(), + DevConsoleConfig.default().withBrowserConfig( + BrowserConfig(binding = BrowserBinding.LOOPBACK, portRange = 8640..8659), + ), + ) + + assertEquals(BindingMode.LOOPBACK, provider.startFromMoreScreen().bindingMode) + + provider.stop(StopReason.UserRequested) + } +``` + +- [ ] **Step 4: Assert noop mocks remain disabled** + +In `NoopFacadeTest`, add to the existing disabled-facade test or create a separate test with the same initialization setup: + +```kotlin +assertTrue(!DevConsole.mockEngine().isEnabled()) +``` + +- [ ] **Step 5: Run the focused runtime tests and verify they fail only on the changed default expectations** + +Run: + +```bash +./gradlew :sdk:mocks:test --tests io.devconsole.mocks.MockEngineTest \ + :sdk:full:testDebugUnitTest --tests io.devconsole.FullFacadeTest --tests io.devconsole.PlatformFacadeProviderMoreScreenBindingTest \ + :sdk:noop:testDebugUnitTest --tests io.devconsole.NoopFacadeTest +``` + +Expected: the full/default LAN assertions and the noop/mock assertions identify the old behavior; existing explicit loopback/LAN tests continue to pass. + +- [ ] **Step 6: Commit the runtime contract tests** + +```bash +git add sdk/mocks/src/test/kotlin/io/devconsole/mocks/MockEngineTest.kt \ + sdk/full/src/test/kotlin/io/devconsole/FullFacadeTest.kt \ + sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderMoreScreenBindingTest.kt \ + sdk/noop/src/test/kotlin/io/devconsole/NoopFacadeTest.kt +git commit -m "test: cover full and noop default behavior" +``` + +### Task 3: Implement LAN defaults and update runtime KDoc + +**Files:** +- Modify: `sdk/api/src/main/kotlin/io/devconsole/api/FocusedPolicies.kt` +- Modify: `sdk/api/src/main/kotlin/io/devconsole/api/StartRequest.kt` +- Modify: `sdk/server-api/src/main/kotlin/io/devconsole/server/api/LocalServerEngine.kt` +- Modify: `sdk/facade-shared/src/main/kotlin/io/devconsole/DevConsole.kt` +- Modify: `sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt` + +- [ ] **Step 1: Make `BrowserConfig` default to LAN** + +In `FocusedPolicies.kt`, change: + +```kotlin +val binding: BrowserBinding = BrowserBinding.LOOPBACK, +``` + +to: + +```kotlin +val binding: BrowserBinding = BrowserBinding.LAN, +``` + +Rewrite the surrounding KDoc so it says LAN is the default for the More-screen start and loopback is the explicit safer choice; retain the warning that the dashboard uses plaintext HTTP and cite `docs/THREAT_MODEL.md`. + +- [ ] **Step 2: Make public `StartRequest` default to LAN** + +In `sdk/api/.../StartRequest.kt`, change: + +```kotlin +val bindingMode: BindingMode = BindingMode.LOOPBACK, +``` + +to: + +```kotlin +val bindingMode: BindingMode = BindingMode.LAN, +``` + +Update the enum and data-class KDoc to say programmatic starts default to LAN, while callers can explicitly pass `BindingMode.LOOPBACK`; remove claims that loopback is the default. + +- [ ] **Step 3: Align `sdk:server-api`’s lower-level default** + +In `sdk/server-api/src/main/kotlin/io/devconsole/server/api/LocalServerEngine.kt`, change the lower-level `StartRequest` constructor default to: + +```kotlin +val bindingMode: BindingMode = BindingMode.LAN, +``` + +Do not change `SessionCodeAuthority`’s placeholder `lastEndpoint`, which is an internal pre-start URL fallback rather than a server-start binding default. + +- [ ] **Step 4: Update facade and provider KDoc** + +In `sdk/facade-shared/src/main/kotlin/io/devconsole/DevConsole.kt`, change the `startBrowser` documentation to describe `StartRequest()` as LAN by default, and show explicit `BindingMode.LOOPBACK` as the safer choice for trusted USB/ADB-only use. + +In `sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt`, update `configuredStartRequest()`’s comment so it no longer says the default remains loopback. Keep the mapping of explicit `BrowserBinding.LOOPBACK` and `BrowserBinding.LAN` unchanged. + +- [ ] **Step 5: Run the focused tests and compile the changed modules** + +Run: + +```bash +./gradlew :sdk:api:test --tests io.devconsole.api.FocusedConfigurationTest --tests io.devconsole.api.DevConsoleContractTest \ + :sdk:server-api:test --tests io.devconsole.server.api.StartRequestDefaultsTest \ + :sdk:mocks:test --tests io.devconsole.mocks.MockEngineTest \ + :sdk:full:testDebugUnitTest --tests io.devconsole.FullFacadeTest --tests io.devconsole.PlatformFacadeProviderMoreScreenBindingTest \ + :sdk:noop:testDebugUnitTest --tests io.devconsole.NoopFacadeTest +``` + +Expected: all focused tests pass, including the explicit loopback and noop-disabled assertions. + +- [ ] **Step 6: Commit the implementation and KDoc changes** + +```bash +git add sdk/api/src/main/kotlin/io/devconsole/api/FocusedPolicies.kt \ + sdk/api/src/main/kotlin/io/devconsole/api/StartRequest.kt \ + sdk/server-api/src/main/kotlin/io/devconsole/server/api/LocalServerEngine.kt \ + sdk/facade-shared/src/main/kotlin/io/devconsole/DevConsole.kt \ + sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt +git commit -m "feat: default dashboard binding to LAN" +``` + +### Task 4: Refresh user-facing LAN guidance + +**Files:** +- Modify: `README.md` +- Modify: `docs/THREAT_MODEL.md` +- Modify: `docs/LAN_PERMISSION_AND_TROUBLESHOOTING.md` + +- [ ] **Step 1: Update README setup examples** + +Replace the quick-start programmatic example with the default call and an explicit loopback alternative: + +```kotlin +val result = DevConsole.startBrowser() // LAN by default +// For USB/ADB-only access instead: +val loopbackResult = DevConsole.startBrowser( + StartRequest(bindingMode = BindingMode.LOOPBACK), +) +``` + +Replace the More-screen paragraph and sample with: + +```markdown +That button binds **LAN** by default, so its QR code is reachable from another device on the same +network. For the safer USB/ADB-only mode, configure loopback explicitly; the button issues no +`StartRequest` of its own: +``` + +```kotlin +DevConsoleConfig.default().withBrowserConfig( + BrowserConfig(binding = BrowserBinding.LOOPBACK), +) +``` + +Update the regular code sample to call `DevConsole.startBrowser(StartRequest())`, annotate it as +the LAN default, and retain the existing explicit `StartRequest(bindingMode = BindingMode.LOOPBACK)` +snippet as the loopback opt-out. + +Change the connect-method bullets to identify LAN as the default and loopback as the explicit secondary option. Keep the existing warning that LAN is plaintext and never silently falls back to loopback. + +Use: + +```markdown +- **LAN (default):** open the URL from another device on the same network. Read + [the threat model](docs/THREAT_MODEL.md) first because the dashboard speaks plaintext HTTP. +- **Loopback (explicit):** run `adb forward tcp: tcp:`, then open the connect URL. +``` + +- [ ] **Step 2: Update README security language** + +Replace the security-model introduction and first network bullet with: + +```markdown +DevConsole deliberately exposes your app's internals to a browser. LAN is the default to make +cross-device debugging work immediately, while loopback remains the safer explicit choice on +untrusted or shared networks. + +- **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. Use + `BindingMode.LOOPBACK` with `adb forward` when the network is not trusted. +``` + +- [ ] **Step 3: Update the threat model** + +In the Safe defaults section, explain: + +```kotlin +DevConsole.startBrowser(StartRequest()) // LAN default +DevConsole.startBrowser(StartRequest(bindingMode = BindingMode.LOOPBACK)) // explicit safer mode +``` + +Precede the examples with: “LAN is the primary default for both existing start entry points so +cross-device debugging works without extra configuration. Use the explicit loopback form on an +untrusted/shared network.” Change the More-screen explanation to say `BrowserConfig()` defaults to +LAN and that `BrowserConfig(binding = BrowserBinding.LOOPBACK)` is the explicit secondary choice. +Preserve all threat warnings, permission behavior, and the statement that the two entry points +remain independently configurable. + +- [ ] **Step 4: Update LAN troubleshooting wording** + +Rename the loopback section’s posture from “safer default” to “explicit loopback / ADB mode” and leave its command and `adb forward` instructions intact. + +- [ ] **Step 5: Search for stale default claims and commit documentation** + +Run: + +```bash +rg -n "loopback.*default|default.*loopback|LAN mode is always an explicit opt-in|LAN.*explicit opt-in|BrowserBinding\.LOOPBACK.*default|StartRequest\(\).*loopback" README.md docs sdk -g '*.md' -g '*.kt' +``` + +The remaining matches must be explicit loopback examples, fallback/error guidance, or the internal session-code placeholder—not claims about the public server-start defaults. + +Then commit: + +```bash +git add README.md docs/THREAT_MODEL.md docs/LAN_PERMISSION_AND_TROUBLESHOOTING.md +git commit -m "docs: describe LAN as the default binding" +``` + +### Task 5: Run the complete verification set and review the final diff + +**Files:** +- Test: `sdk/api`, `sdk/server-api`, `sdk/mocks`, `sdk/full`, `sdk/noop` +- Review: all files changed by Tasks 1–4 + +- [ ] **Step 1: Run all affected unit tests** + +```bash +./gradlew :sdk:api:test :sdk:server-api:test :sdk:mocks:test \ + :sdk:full:testDebugUnitTest :sdk:noop:testDebugUnitTest +``` + +Expected: every task completes successfully with no failed tests. + +- [ ] **Step 2: Compile the public/full/noop artifacts** + +```bash +./gradlew :sdk:api:compileKotlin :sdk:server-api:compileDebugKotlin \ + :sdk:full:compileDebugKotlin :sdk:noop:compileDebugKotlin +``` + +Expected: all compile tasks pass without API or Kotlin errors. + +- [ ] **Step 3: Check formatting and inspect the diff** + +```bash +git diff --check HEAD~4..HEAD +git status --short +git log --oneline -6 +``` + +Review that only the approved design spec, default values, tests, KDoc, and LAN guidance changed; verify noop construction remains `MockEngine(emptyList(), enabled = false)` and no permission/fallback logic was altered. + +- [ ] **Step 4: Run the repository check task** + +```bash +./gradlew check +``` + +Expected: the repository-wide quality and test checks pass. If the check task reports only an expected API-dump or documentation artifact difference, inspect it and include the generated tracked artifact only if the build explicitly requires it. + +- [ ] **Step 5: Report completion with evidence** + +Summarize the public defaults, explicit loopback override, preserved noop safety, documentation updates, and the exact Gradle commands that passed. Link the key changed files and mention any environment-specific test limitation rather than claiming unverified success. From 24444f5fcf67a266f2b73fdda1f184713d2f36c8 Mon Sep 17 00:00:00 2001 From: shakibuzzaman Date: Mon, 17 Aug 2026 10:28:22 +0600 Subject: [PATCH 03/20] test: define LAN and mock defaults --- .../devconsole/api/DevConsoleContractTest.kt | 5 +++++ .../api/FocusedConfigurationTest.kt | 4 ++-- .../kotlin/io/devconsole/FullFacadeTest.kt | 3 ++- ...formFacadeProviderMoreScreenBindingTest.kt | 22 ++++++++++++++++--- .../io/devconsole/mocks/MockEngineTest.kt | 5 +++++ .../kotlin/io/devconsole/NoopFacadeTest.kt | 1 + .../server/api/StartRequestDefaultsTest.kt | 11 ++++++++++ 7 files changed, 45 insertions(+), 6 deletions(-) create mode 100644 sdk/server-api/src/test/kotlin/io/devconsole/server/api/StartRequestDefaultsTest.kt diff --git a/sdk/api/src/test/kotlin/io/devconsole/api/DevConsoleContractTest.kt b/sdk/api/src/test/kotlin/io/devconsole/api/DevConsoleContractTest.kt index d97e865..96bbddb 100644 --- a/sdk/api/src/test/kotlin/io/devconsole/api/DevConsoleContractTest.kt +++ b/sdk/api/src/test/kotlin/io/devconsole/api/DevConsoleContractTest.kt @@ -49,6 +49,11 @@ class DevConsoleContractTest { assertEquals(listOf(ConfigValidationCode.INVALID_PORT_RANGE), errors.map { it.code }) } + @Test + fun `default start request uses LAN binding`() { + assertEquals(BindingMode.LAN, StartRequest().bindingMode) + } + @Test fun `default configuration is valid and uses documented session and storage limits`() { val config = DevConsoleConfig.default() diff --git a/sdk/api/src/test/kotlin/io/devconsole/api/FocusedConfigurationTest.kt b/sdk/api/src/test/kotlin/io/devconsole/api/FocusedConfigurationTest.kt index e4dc19f..e98147f 100644 --- a/sdk/api/src/test/kotlin/io/devconsole/api/FocusedConfigurationTest.kt +++ b/sdk/api/src/test/kotlin/io/devconsole/api/FocusedConfigurationTest.kt @@ -36,14 +36,14 @@ class FocusedConfigurationTest { } @Test - fun `focused policies use persistent sessions and direct loopback defaults`() { + fun `focused policies use persistent sessions and LAN defaults`() { val retention = RetentionPolicy() val browser = BrowserConfig() assertEquals(10, retention.maxSessions) assertEquals(7L * 24L * 60L * 60L * 1000L, retention.maxAgeMs) assertEquals(100L * 1024L * 1024L, retention.maxBytes) - assertEquals(BrowserBinding.LOOPBACK, browser.binding) + assertEquals(BrowserBinding.LAN, browser.binding) assertEquals(8080..8099, browser.portRange) } diff --git a/sdk/full/src/test/kotlin/io/devconsole/FullFacadeTest.kt b/sdk/full/src/test/kotlin/io/devconsole/FullFacadeTest.kt index 21b9690..7d969e6 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/FullFacadeTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/FullFacadeTest.kt @@ -93,10 +93,11 @@ class FullFacadeTest { provider.initialize(ApplicationProvider.getApplicationContext(), DevConsoleConfig.default()), ) assertEquals(DevConsoleState.Initialized, provider.state().value) + assertTrue(provider.mockEngine().isEnabled()) val started = provider.startBrowser(StartRequest()) assertTrue(started is StartResult.Started) started as StartResult.Started - assertEquals(BindingMode.LOOPBACK, started.endpoint.bindingMode) + assertEquals(BindingMode.LAN, started.endpoint.bindingMode) assertTrue(started.endpoint.port in 8080..8099) assertTrue(started.access.connectUrl.contains("#code=")) assertEquals(DevConsoleState.Running, provider.state().value) diff --git a/sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderMoreScreenBindingTest.kt b/sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderMoreScreenBindingTest.kt index bdc6097..3417a79 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderMoreScreenBindingTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderMoreScreenBindingTest.kt @@ -29,8 +29,8 @@ import org.robolectric.annotation.Config * always bound loopback, which meant a host configured for LAN still got a `127.0.0.1` connect URL * whenever the start came from the device rather than from its own code. * - * Both directions are asserted: the default config must still bind loopback (the safe default is the - * whole reason LAN is opt-in), and a LAN-configured host must actually reach LAN. + * Both directions are asserted: the default config binds LAN, and a host can explicitly select + * loopback as the secondary safer choice. */ @RunWith(RobolectricTestRunner::class) @Config(sdk = [34]) @@ -52,11 +52,27 @@ class PlatformFacadeProviderMoreScreenBindingTest { } @Test - fun `More screen start still binds loopback under the default config`() = + fun `More screen start binds LAN under the default config`() = runTest { val provider = PlatformFacadeProvider() provider.initialize(ApplicationProvider.getApplicationContext(), DevConsoleConfig.default()) + assertEquals(BindingMode.LAN, provider.startFromMoreScreen().bindingMode) + + provider.stop(StopReason.UserRequested) + } + + @Test + fun `More screen start binds loopback when the host explicitly configures loopback`() = + runTest { + val provider = PlatformFacadeProvider() + provider.initialize( + ApplicationProvider.getApplicationContext(), + DevConsoleConfig.default().withBrowserConfig( + BrowserConfig(binding = BrowserBinding.LOOPBACK, portRange = 8640..8659), + ), + ) + assertEquals(BindingMode.LOOPBACK, provider.startFromMoreScreen().bindingMode) provider.stop(StopReason.UserRequested) diff --git a/sdk/mocks/src/test/kotlin/io/devconsole/mocks/MockEngineTest.kt b/sdk/mocks/src/test/kotlin/io/devconsole/mocks/MockEngineTest.kt index 6ddbcd0..8c80cd0 100644 --- a/sdk/mocks/src/test/kotlin/io/devconsole/mocks/MockEngineTest.kt +++ b/sdk/mocks/src/test/kotlin/io/devconsole/mocks/MockEngineTest.kt @@ -5,6 +5,11 @@ import org.junit.Assert.assertTrue import org.junit.Test class MockEngineTest { + @Test + fun `mock engine is enabled by default`() { + assertTrue(MockEngine(emptyList()).isEnabled()) + } + @Test fun `chooses exact-path rule over wildcard at equal priority`() { val engine = MockEngine(listOf(MockRule("wild", 1, path = "/.*"), MockRule("exact", 1, path = "/orders"))) assertEquals( diff --git a/sdk/noop/src/test/kotlin/io/devconsole/NoopFacadeTest.kt b/sdk/noop/src/test/kotlin/io/devconsole/NoopFacadeTest.kt index 7a6384f..57093d2 100644 --- a/sdk/noop/src/test/kotlin/io/devconsole/NoopFacadeTest.kt +++ b/sdk/noop/src/test/kotlin/io/devconsole/NoopFacadeTest.kt @@ -20,6 +20,7 @@ class NoopFacadeTest { assertEquals(InitResult.Disabled, DevConsole.initialize(Application(), DevConsoleConfig.default())) assertEquals(DevConsoleState.DisabledForBuild, DevConsole.state().value) assertEquals(StartResult.DisabledForBuild, DevConsole.startBrowser()) + assertTrue(!DevConsole.mockEngine().isEnabled()) } @Test diff --git a/sdk/server-api/src/test/kotlin/io/devconsole/server/api/StartRequestDefaultsTest.kt b/sdk/server-api/src/test/kotlin/io/devconsole/server/api/StartRequestDefaultsTest.kt new file mode 100644 index 0000000..92a6740 --- /dev/null +++ b/sdk/server-api/src/test/kotlin/io/devconsole/server/api/StartRequestDefaultsTest.kt @@ -0,0 +1,11 @@ +package io.devconsole.server.api + +import org.junit.Assert.assertEquals +import org.junit.Test + +class StartRequestDefaultsTest { + @Test + fun `default server start request uses LAN binding`() { + assertEquals(BindingMode.LAN, StartRequest().bindingMode) + } +} From 8745c46e9c450aa185ae3ba6eaf3f38e0eefe9c3 Mon Sep 17 00:00:00 2001 From: shakibuzzaman Date: Mon, 17 Aug 2026 10:30:42 +0600 Subject: [PATCH 04/20] feat: default dashboard binding to LAN --- .../kotlin/io/devconsole/api/FocusedPolicies.kt | 9 +++++---- .../main/kotlin/io/devconsole/api/StartRequest.kt | 12 ++++++------ .../src/main/kotlin/io/devconsole/DevConsole.kt | 10 +++++----- .../io/devconsole/PlatformFacadeProvider.kt | 15 +++++++-------- .../io/devconsole/server/api/LocalServerEngine.kt | 4 ++-- 5 files changed, 25 insertions(+), 25 deletions(-) diff --git a/sdk/api/src/main/kotlin/io/devconsole/api/FocusedPolicies.kt b/sdk/api/src/main/kotlin/io/devconsole/api/FocusedPolicies.kt index ff03280..7d3a50a 100644 --- a/sdk/api/src/main/kotlin/io/devconsole/api/FocusedPolicies.kt +++ b/sdk/api/src/main/kotlin/io/devconsole/api/FocusedPolicies.kt @@ -16,9 +16,10 @@ private const val DEFAULT_PORT_RANGE_END = 8099 * binds what this field says. Configure this when you want an on-device start to reach the browser * over the network; pass [StartRequest.bindingMode] when your own code is doing the starting. * - * [LOOPBACK] is the default here for the same reason it is on [BindingMode]: the dashboard speaks - * plaintext HTTP, so [LAN] is an explicit decision to expose captured headers, tokens, and bodies to - * anyone who can see the traffic. See the KDoc on [BindingMode] and `docs/THREAT_MODEL.md`. + * [LAN] is the default here so the dashboard can be reached from another device during debugging. + * The dashboard speaks plaintext HTTP, so choose [LOOPBACK] explicitly when the device is on an + * untrusted network and use ADB forwarding instead. See the KDoc on [BindingMode] and + * `docs/THREAT_MODEL.md`. */ enum class BrowserBinding { LOOPBACK, LAN } @@ -49,7 +50,7 @@ data class RetentionPolicy( /** SESSION_CODE is the only browser-access flow; there is no longer an access-mode field to set. */ data class BrowserConfig( - val binding: BrowserBinding = BrowserBinding.LOOPBACK, + val binding: BrowserBinding = BrowserBinding.LAN, val portRange: IntRange = DEFAULT_PORT_RANGE_START..DEFAULT_PORT_RANGE_END, val sessionCodeTtlMs: Long = DEFAULT_SESSION_CODE_TTL_MS, ) { diff --git a/sdk/api/src/main/kotlin/io/devconsole/api/StartRequest.kt b/sdk/api/src/main/kotlin/io/devconsole/api/StartRequest.kt index 9108097..65dd511 100644 --- a/sdk/api/src/main/kotlin/io/devconsole/api/StartRequest.kt +++ b/sdk/api/src/main/kotlin/io/devconsole/api/StartRequest.kt @@ -6,15 +6,15 @@ private const val DEFAULT_PORT_RANGE_START = 8080 private const val DEFAULT_PORT_RANGE_END = 8099 /** - * Network exposure requested by the host, passed per-call as [StartRequest.bindingMode]. Loopback - * is the safe default -- the dashboard speaks plaintext HTTP, and `LAN` exposes that traffic to - * anyone else on the local network; see `docs/THREAT_MODEL.md` at the repository root before ever - * passing `LAN`. + * Network exposure requested by the host, passed per-call as [StartRequest.bindingMode]. LAN is the + * default so a host-issued start can be reached from another device during debugging. The dashboard + * speaks plaintext HTTP, so pass [BindingMode.LOOPBACK] explicitly on an untrusted network and use + * ADB forwarding; see `docs/THREAT_MODEL.md` at the repository root. * * This is a distinct type from [BrowserBinding] on [BrowserConfig] (`DevConsoleConfig.browserConfig`), * and the two are **not** layered as "config provides a default, [StartRequest] overrides it". They * answer for different callers: this type decides a start the host issues itself, where the request - * is right there at the call site and defaults to [BindingMode.LOOPBACK] regardless of what any + * is right there at the call site and defaults to [BindingMode.LAN] regardless of what any * [DevConsoleConfig] says; [BrowserConfig.binding] decides a start the host does not issue -- the * in-app inspector's More-screen Start button, which has no [StartRequest] to carry. Neither reads * the other. See the KDoc on [BrowserBinding] for that side. @@ -23,7 +23,7 @@ enum class BindingMode { LOOPBACK, LAN } /** Stable host-facing server start options. */ data class StartRequest( - val bindingMode: BindingMode = BindingMode.LOOPBACK, + val bindingMode: BindingMode = BindingMode.LAN, val portRange: IntRange = DEFAULT_PORT_RANGE_START..DEFAULT_PORT_RANGE_END, ) { fun validationErrors(): List { diff --git a/sdk/facade-shared/src/main/kotlin/io/devconsole/DevConsole.kt b/sdk/facade-shared/src/main/kotlin/io/devconsole/DevConsole.kt index 84beae7..0baad30 100644 --- a/sdk/facade-shared/src/main/kotlin/io/devconsole/DevConsole.kt +++ b/sdk/facade-shared/src/main/kotlin/io/devconsole/DevConsole.kt @@ -109,12 +109,12 @@ object DevConsole { * [StartRequest.bindingMode] decides loopback-vs-LAN for *this call*, and no [DevConsoleConfig] * value provides a default for it: `DevConsoleConfig.browserConfig.binding` governs only the * starts this method is not making -- the in-app inspector's More-screen Start button -- so a - * host that wants LAN from both surfaces sets both. See the KDoc on - * [io.devconsole.api.BindingMode] and [io.devconsole.api.BrowserBinding]. The default - * `StartRequest()` binds loopback, which is the safe choice -- see `docs/THREAT_MODEL.md` at - * the repository root before ever passing `bindingMode = BindingMode.LAN`. + * host can configure each surface independently. See the KDoc on [io.devconsole.api.BindingMode] + * and [io.devconsole.api.BrowserBinding]. The default `StartRequest()` binds LAN; pass + * `bindingMode = BindingMode.LOOPBACK` explicitly for the safer ADB-only choice on an untrusted + * network. See `docs/THREAT_MODEL.md` at the repository root. * - * @param request binding mode and port range for this start attempt. Defaults to loopback on + * @param request binding mode and port range for this start attempt. Defaults to LAN on * `8080..8099`. * @return a [StartResult] -- [StartResult.Started] carries the bound [io.devconsole.api.BrowserEndpoint] * and the session [io.devconsole.api.AccessInfo] (the connect URL/code); every other variant is a diff --git a/sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt b/sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt index 4dbec8b..7fce1c3 100644 --- a/sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt +++ b/sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt @@ -831,11 +831,10 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { * what [io.devconsole.api.BrowserConfig.binding] is for, and it is now the field that decides: * an on-device start binds what the host asked for, and uses the port range it asked for too. * - * Nothing here loosens the default. [BrowserBinding.LOOPBACK] remains the default on - * [io.devconsole.api.BrowserConfig], so LAN is still reached only by a host that explicitly asks - * for it, and a LAN start still passes through the same [rejectUnpermittedLan] gate as any - * other -- returning [StartResult.PermissionRequired] rather than binding, which the More screen - * surfaces through its normal state polling. + * [io.devconsole.api.BrowserConfig] defaults to [BrowserBinding.LAN], and an explicit + * [BrowserBinding.LOOPBACK] still maps to loopback. Every LAN start passes through the same + * [rejectUnpermittedLan] gate as any other -- returning [StartResult.PermissionRequired] rather + * than binding, which the More screen surfaces through its normal state polling. */ private fun configuredStartRequest(): StartRequest { val browser = activeConfig?.browserConfig ?: return StartRequest() @@ -1203,9 +1202,9 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { /** * The session code has its own TTL, shorter than the server's lifetime -- if it has expired * while the server keeps running, re-issue automatically (reusing the real bind address, not the - * loopback default) so both the host app's connect-URL card ([accessInfo]) and the SDK's own More - * screen ([browserSupplier] above) keep advertising something connectable instead of a dead, - * already-expired code. Null while the server isn't running. + * initial placeholder endpoint) so both the host app's connect-URL card ([accessInfo]) and the + * SDK's own More screen ([browserSupplier] above) keep advertising something connectable instead + * of a dead, already-expired code. Null while the server isn't running. */ private fun liveSessionCodeInfo(): SessionCodeInfo? { lastStarted ?: return null diff --git a/sdk/server-api/src/main/kotlin/io/devconsole/server/api/LocalServerEngine.kt b/sdk/server-api/src/main/kotlin/io/devconsole/server/api/LocalServerEngine.kt index e679e0a..5194df5 100644 --- a/sdk/server-api/src/main/kotlin/io/devconsole/server/api/LocalServerEngine.kt +++ b/sdk/server-api/src/main/kotlin/io/devconsole/server/api/LocalServerEngine.kt @@ -23,7 +23,7 @@ data class SessionPolicy( } data class StartRequest( - val bindingMode: BindingMode = BindingMode.LOOPBACK, + val bindingMode: BindingMode = BindingMode.LAN, val portRange: IntRange = 8080..8099, val sessionCodeTtlMs: Long = SessionCodeAuthority.DEFAULT_SESSION_CODE_TTL_MS, ) @@ -383,7 +383,7 @@ class SessionCodeAuthority( /** * The endpoint/TTL from the most recent [issueCode] call -- reused by a caller that re-issues * with no arguments (e.g. [currentInfo]'s auto re-mint) so a fresh code still points at the - * real bind address instead of falling back to the loopback default. + * real bind address instead of falling back to the initial placeholder endpoint. */ private var lastEndpoint: Endpoint = Endpoint(DEFAULT_LOOPBACK_HOST, DEFAULT_LOOPBACK_PORT, BindingMode.LOOPBACK) private var lastTtlMs: Long = codeTtlMs From cfe1d73dedc28f86b9f4c1340a8d79a79bf8b5ad Mon Sep 17 00:00:00 2001 From: shakibuzzaman Date: Mon, 17 Aug 2026 10:32:48 +0600 Subject: [PATCH 05/20] docs: describe LAN as the default binding --- README.md | 47 ++++++++++++------- docs/LAN_PERMISSION_AND_TROUBLESHOOTING.md | 5 +- docs/THREAT_MODEL.md | 28 +++++------ .../2026-08-17-default-lan-and-mocks-plan.md | 5 +- 4 files changed, 49 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index fec99b4..ffd1606 100644 --- a/README.md +++ b/README.md @@ -76,14 +76,20 @@ 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 - val result = DevConsole.startBrowser(StartRequest(bindingMode = BindingMode.LOOPBACK)) + val result = DevConsole.startBrowser() // LAN by default val connectUrl = (result as? StartResult.Started)?.access?.connectUrl - // e.g. http://127.0.0.1:8080/#code=B7KQ2XWZ — surface this in your debug UI + // e.g. http://192.168.1.42:8080/#code=B7KQ2XWZ — surface this in your debug UI } ``` +For USB/ADB-only access, choose loopback explicitly: + +```kotlin +val result = DevConsole.startBrowser(StartRequest(bindingMode = BindingMode.LOOPBACK)) +``` + ```bash -adb forward tcp:8080 tcp:8080 # use the port from the DevConsole log line +adb forward tcp:8080 tcp:8080 # use the port from the loopback start's log line ``` Then open the **whole URL**. The `#code=` fragment is the credential, so a bare `http://host:port/` @@ -165,16 +171,19 @@ scan from another machine.

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 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: +That button binds **LAN** by default, so its QR code is reachable from another device on the same +network. For the safer USB/ADB-only mode, configure loopback explicitly; the button issues no +`StartRequest` of its own: ```kotlin -DevConsoleConfig.default().withBrowserConfig(BrowserConfig(binding = BrowserBinding.LAN)) +DevConsoleConfig.default().withBrowserConfig( + BrowserConfig(binding = BrowserBinding.LOOPBACK), +) ``` -This is independent of the `bindingMode` you pass to `startBrowser` yourself; set both if you start -the server from your own UI too. Read [the threat model](docs/THREAT_MODEL.md) before choosing LAN. +This is independent of the `bindingMode` you pass to `startBrowser` yourself; both existing entry +points default to LAN, and each can explicitly select loopback. Read [the threat model](docs/THREAT_MODEL.md) +before using LAN on a network you do not administer. From code: @@ -183,7 +192,7 @@ From code: DevConsole.initialize(application, DevConsoleConfig.default()) // startBrowser and stop are suspend functions — call them from a coroutine: -val result = DevConsole.startBrowser(StartRequest(bindingMode = BindingMode.LOOPBACK)) +val result = DevConsole.startBrowser(StartRequest()) // LAN by default when (result) { is StartResult.Started -> { result.endpoint // host + port actually bound @@ -214,7 +223,7 @@ DevConsole.startBrowserAsync(request, result -> runOnUiThread(() -> { After `startBrowser`, filter Logcat on the `DevConsole` tag: ```text -I/DevConsole: Dashboard available at: http://127.0.0.1:8080/ (access link available through the DevConsole API/launcher; binding: LOOPBACK) +I/DevConsole: Dashboard available at: http://192.168.1.42:8080/ (access link available through the DevConsole API/launcher; binding: LAN) ``` **The session code is deliberately absent from Logcat.** The full URL, with its `#code= tcp:`, then open the connect URL. -- **LAN:** pass `BindingMode.LAN` and open the URL from any device on the same network. Read +- **LAN (default):** open the URL from another 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. + never quietly falls back to loopback. +- **Loopback (explicit):** run `adb forward tcp: tcp:`, then open the connect URL. The + server never silently changes an explicit loopback request to LAN. 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 @@ -425,12 +435,13 @@ resolved runtime classpath, and the final APK/AAB bytes. See ## 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: +DevConsole deliberately exposes your app's internals to a browser. LAN is the default to make +cross-device debugging work immediately, while loopback remains the safer explicit choice on +untrusted or shared networks: - **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. + network packets can read everything it shows: headers, tokens, bodies, exports. Use + `BindingMode.LOOPBACK` with `adb forward` when the network is not trusted. - **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. diff --git a/docs/LAN_PERMISSION_AND_TROUBLESHOOTING.md b/docs/LAN_PERMISSION_AND_TROUBLESHOOTING.md index 918b578..e96d9ce 100644 --- a/docs/LAN_PERMISSION_AND_TROUBLESHOOTING.md +++ b/docs/LAN_PERMISSION_AND_TROUBLESHOOTING.md @@ -53,9 +53,10 @@ Requesting it at runtime is still your app's job — use `ActivityResultContract with `StartResult.PermissionRequired.permission` when you get that result back, exactly as all three samples do. -## Loopback / ADB reverse mode +## Explicit loopback / ADB mode -Still the safer default when you don't need cross-device access: +Use this explicit secondary mode when you don't need cross-device access or the current network is +not trusted: ```kotlin DevConsole.startBrowser(StartRequest(bindingMode = BindingMode.LOOPBACK, portRange = 8080..8099)) diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index d1add8d..ea2e80f 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -173,11 +173,13 @@ Bodies are also truncated to 64 KiB before storage. That is a resource bound, no ## Safe defaults -**Untrusted or shared network — use loopback.** This is the recommended posture and the SDK's own -default binding mode: +LAN is the primary default for both existing start entry points so cross-device debugging works +without extra configuration. On an untrusted or shared network, use the explicit loopback form +below instead: ```kotlin -DevConsole.startBrowser(StartRequest(bindingMode = BindingMode.LOOPBACK)) +DevConsole.startBrowser(StartRequest()) // LAN default +DevConsole.startBrowser(StartRequest(bindingMode = BindingMode.LOOPBACK)) // explicit safer mode ``` ```bash @@ -193,19 +195,17 @@ reasonable place for LAN mode. A conference Wi-Fi, a hotel, a café, or any netw administer is not. Note that LAN mode binds one specific interface address, never `0.0.0.0`, which limits reach but does not make the traffic private. -**LAN mode is always an explicit opt-in.** `startBrowser()` never picks a binding mode for you -- -the default `StartRequest()` binds loopback, and LAN only happens when you pass -`bindingMode = BindingMode.LAN` yourself. So on a network you do not trust, simply don't ask for -LAN: -`DevConsole.startBrowser(StartRequest(bindingMode = BindingMode.LOOPBACK))`. +**Loopback is the explicit safer choice.** `startBrowser()` uses LAN when its request is omitted, +so on a network you do not trust, pass +`DevConsole.startBrowser(StartRequest(bindingMode = BindingMode.LOOPBACK))` and use `adb forward`. +LAN never quietly falls back to loopback, and loopback never quietly changes to LAN. -There is a second way to start the server, and it has its own opt-in: the **Start button on the +There is a second way to start the server: the **Start button on the in-app inspector's More screen**, which issues no `StartRequest` and instead binds whatever -`DevConsoleConfig.browserConfig.binding` declares. That field also defaults to `LOOPBACK`, so an -on-device start is loopback unless a host explicitly configures -`BrowserConfig(binding = BrowserBinding.LAN)`. The two settings are independent and neither -overrides the other -- a host that wants LAN from both surfaces has to say so twice, and a host that -sets only `StartRequest(bindingMode = LAN)` leaves the on-device button on loopback. +`DevConsoleConfig.browserConfig.binding` declares. That field defaults to `LAN`, so an on-device +start defaults to LAN; configure +`BrowserConfig(binding = BrowserBinding.LOOPBACK)` for explicit loopback. The two settings remain +independent and neither overrides the other, even though both defaults are now LAN. **Stop the server when you are done.** `DevConsole.stop(...)` revokes browser sessions immediately and unbinds the port. A dashboard left running on a desk overnight is an open dashboard. diff --git a/docs/superpowers/plans/2026-08-17-default-lan-and-mocks-plan.md b/docs/superpowers/plans/2026-08-17-default-lan-and-mocks-plan.md index 9ab69ea..022d02e 100644 --- a/docs/superpowers/plans/2026-08-17-default-lan-and-mocks-plan.md +++ b/docs/superpowers/plans/2026-08-17-default-lan-and-mocks-plan.md @@ -61,7 +61,8 @@ class StartRequestDefaultsTest { Run: ```bash -./gradlew :sdk:api:test --tests io.devconsole.api.FocusedConfigurationTest --tests io.devconsole.api.DevConsoleContractTest :sdk:server-api:test --tests io.devconsole.server.api.StartRequestDefaultsTest +./gradlew :sdk:api:test --tests io.devconsole.api.FocusedConfigurationTest --tests io.devconsole.api.DevConsoleContractTest +./gradlew :sdk:server-api:testDebugUnitTest --tests io.devconsole.server.api.StartRequestDefaultsTest ``` Expected: the new/changed assertions fail because the current defaults are `LOOPBACK`. @@ -234,7 +235,7 @@ Run: ```bash ./gradlew :sdk:api:test --tests io.devconsole.api.FocusedConfigurationTest --tests io.devconsole.api.DevConsoleContractTest \ - :sdk:server-api:test --tests io.devconsole.server.api.StartRequestDefaultsTest \ + :sdk:server-api:testDebugUnitTest --tests io.devconsole.server.api.StartRequestDefaultsTest \ :sdk:mocks:test --tests io.devconsole.mocks.MockEngineTest \ :sdk:full:testDebugUnitTest --tests io.devconsole.FullFacadeTest --tests io.devconsole.PlatformFacadeProviderMoreScreenBindingTest \ :sdk:noop:testDebugUnitTest --tests io.devconsole.NoopFacadeTest From 8760db65dc145c675cdc308140e6dc6223f71dc1 Mon Sep 17 00:00:00 2001 From: shakibuzzaman Date: Mon, 17 Aug 2026 12:26:11 +0600 Subject: [PATCH 06/20] docs: specify network detail search --- .../specs/2026-08-17-network-search-design.md | 103 ++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 docs/superpowers/specs/2026-08-17-network-search-design.md diff --git a/docs/superpowers/specs/2026-08-17-network-search-design.md b/docs/superpowers/specs/2026-08-17-network-search-design.md new file mode 100644 index 0000000..1036f5e --- /dev/null +++ b/docs/superpowers/specs/2026-08-17-network-search-design.md @@ -0,0 +1,103 @@ +# Network Detail Search Design + +**Date:** 2026-08-17 +**Scope:** Android Compose Network detail search + +## Goal + +Make Network detail search useful for inspecting request and response data without flattening formatted response bodies. Search must support multi-section scope selection, key/value selection, exact highlighting, and next/previous match navigation. + +## User behavior + +The detail search field searches only the selected network sections: + +- Request headers +- Request body +- Response headers +- Response body + +All four sections are selected by default. General metadata, timing, and redaction sections are never included in this search. + +The search options control opens as a modal bottom sheet. It contains: + +- A multi-select list for the four request/response sections. +- Select all and clear all actions. +- A match mode choice: Keys, Values, or Keys + values. +- Apply and Cancel actions. + +At least one section must be selected before Apply is enabled. The search toolbar summarizes the current scope, for example `All request + response`, `Response body`, or `2 sections`. + +Keys is the default match mode. Matching is case-insensitive substring matching. Applying a changed scope or match mode rebuilds the match index and selects the first result. Clearing the query removes search highlighting and restores the normal detail rendering. + +Matches are ordered by document order: request headers, request body, response headers, response body, with unselected sections omitted. Next and previous controls cycle through this ordered list. The current match is visually stronger than the other matches and is brought into view; its section and any required structured-data ancestors are expanded. + +## Rendering requirements + +Search must preserve the existing representation of each body: + +- Formatted JSON remains a JSON tree while searching. +- Formatted XML remains formatted while searching. +- Raw mode remains raw. +- Header key/value rows remain key/value rows. + +Highlighting is applied to exact matched character ranges with `AnnotatedString` spans. A row-level background alone is insufficient. Structured JSON matches retain their node/path identity so a key match can highlight a property name and a value match can highlight the scalar value. + +Raw or otherwise unstructured content has no semantic key field; it is searched as value text without changing its presentation. + +## Architecture + +Keep this feature in the Compose presentation layer. The detail screen owns query, selected sections, match mode, and current match index with saveable local state. No capture-state or repository changes are needed. + +Introduce a pure Kotlin search model/helper that: + +1. Accepts the network detail sections and search configuration. +2. Produces ordered matches containing section identity, item/path identity, field type, and exact text range. +3. Produces section-level match counts and target metadata for scrolling/expansion. + +The existing detail resolver should enrich sections with match metadata while preserving `Formattable`, `KeyValues`, and `Code` body types. It must not convert a `Formattable` body to a flat `Code` body merely because a query is active. + +The search options bottom sheet edits a draft selection and only changes active search state after Apply. Cancel leaves the current search configuration untouched. + +## Accessibility and interaction + +- Every scope checkbox, match mode option, and navigation button has a meaningful content description or visible label. +- Navigation buttons use at least 48dp touch targets and are disabled when there are no matches. +- The match label communicates `current / total`; no-match state is explicit. +- The bottom sheet has a clear title and an obvious Apply action. + +## Testing + +Add pure unit coverage for: + +- Default all-section scope. +- Excluding general/timing/redaction sections. +- Each multi-select combination. +- Keys, Values, and Keys + values behavior for headers and structured bodies. +- Case-insensitive substring matching and exact ranges. +- Stable document ordering and next/previous wrap-around. +- Nested JSON match identity and ancestor expansion metadata. + +Add Compose/UI coverage for: + +- Opening the options sheet, changing multiple sections, applying, and cancelling. +- Navigation button enabled/disabled states and match count. +- Formatted response bodies remaining formatted while a query is active. + +Verify the feature on the Android emulator in light and dark themes, including a response with nested JSON and multiple matches. + +## Out of scope + +- Regex or query-language search. +- Changes to the traffic-list filter. +- Visual identity/token cleanup unrelated to search. +- Persistence of search options across different network requests or app restarts. + +## Acceptance criteria + +- Search never reports or highlights matches from General, Timing, or Redactions. +- Users can select any combination of the four request/response sections. +- Keys is the default match mode and Values/Keys + values work correctly. +- Next and previous navigate through all selected matches and bring the current match into view. +- Matched text is highlighted precisely. +- Searching a formatted response never converts it into a single-line or flat representation. +- Targeted unit/UI tests and the relevant Android build pass. From 98d54b99e6f00189c157dfd613799515f054e532 Mon Sep 17 00:00:00 2001 From: shakibuzzaman Date: Mon, 17 Aug 2026 12:34:03 +0600 Subject: [PATCH 07/20] docs: plan network detail search --- .../plans/2026-08-17-network-detail-search.md | 262 ++++++++++++++++++ 1 file changed, 262 insertions(+) create mode 100644 docs/superpowers/plans/2026-08-17-network-detail-search.md diff --git a/docs/superpowers/plans/2026-08-17-network-detail-search.md b/docs/superpowers/plans/2026-08-17-network-detail-search.md new file mode 100644 index 0000000..ce21c1b --- /dev/null +++ b/docs/superpowers/plans/2026-08-17-network-detail-search.md @@ -0,0 +1,262 @@ +# Network Detail Search 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:** Add scoped, multi-select request/response search to the Android Compose Network detail screen with key/value modes, exact highlighting, match navigation, and preserved formatted bodies. + +**Architecture:** Keep query, scope, mode, and current-match state in `InspectorObserveDetailScreen`. Add a pure candidate/match model for deterministic matching and document ordering. Pass matches as rendering metadata so existing `Formattable`, JSON-tree, raw, code, and key/value body types remain intact. + +**Tech Stack:** Kotlin, Jetpack Compose Material 3, existing DevConsole Compose primitives, JUnit4. + +--- + +### Task 1: Add the pure search model and red tests + +**Files:** +- Create: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearch.kt` +- Create: `sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorDetailSearchTest.kt` + +- [ ] **Step 1: Define the search API and tests first** + +Create `InspectorSearchField`, `InspectorSearchMode`, `InspectorDetailSearchSection`, `InspectorSearchCandidate`, and `InspectorDetailSearchMatch`. The matcher API must accept candidates, a query, a selected-section key set, and a mode, then return ordered matches with zero-based `ordinal`, `start`, and exclusive `end` offsets. + +Write tests covering: + +```kotlin +@Test +fun `keys mode matches keys but not values and keeps exact ranges`() { + val candidates = listOf( + InspectorSearchCandidate("reqh", "row:0", InspectorSearchField.KEY, "Content-Type"), + InspectorSearchCandidate("reqh", "row:0", InspectorSearchField.VALUE, "application/json"), + ) + + val matches = searchInspectorCandidates(candidates, "content", setOf("reqh"), InspectorSearchMode.KEYS) + + assertEquals(1, matches.size) + assertEquals(0, matches.single().start) + assertEquals(7, matches.single().endExclusive) +} + +@Test +fun `multi section matching follows candidate order and values mode`() { + val candidates = listOf( + InspectorSearchCandidate("req", "line:0", InspectorSearchField.VALUE, "userId: 1"), + InspectorSearchCandidate("res", "line:0", InspectorSearchField.VALUE, "userId: 1"), + InspectorSearchCandidate("general", "row:0", InspectorSearchField.VALUE, "userId: 1"), + ) + + val matches = searchInspectorCandidates( + candidates, + "userid", + setOf("req", "res"), + InspectorSearchMode.VALUES, + ) + + assertEquals(listOf("req", "res"), matches.map { it.sectionKey }) + assertEquals(listOf(0, 1), matches.map { it.ordinal }) +} + +@Test +fun `previous and next navigation wrap around`() { + assertEquals(0, nextInspectorMatchIndex(current = 2, total = 3)) + assertEquals(2, previousInspectorMatchIndex(current = 0, total = 3)) +} +``` + +- [ ] **Step 2: Run the focused test and verify it fails for the missing API** + +Run: + +```bash +./gradlew :sdk:ui-compose:testDebugUnitTest --tests io.devconsole.ui.compose.InspectorDetailSearchTest --no-daemon +``` + +Expected: compilation/test failure because the matcher and navigation helpers do not exist yet. + +- [ ] **Step 3: Implement the minimal pure matcher** + +Implement case-insensitive, non-overlapping substring ranges using `regionMatches`, filter by selected section and field mode, assign ordinals after filtering, and return an empty list for blank queries. Add wrap-around helpers that return `0` for next/`total - 1` for previous when the list is non-empty. + +- [ ] **Step 4: Re-run the focused test and verify it passes** + +Run the same Gradle command. Expected: all focused tests pass. + +- [ ] **Step 5: Commit the pure search model** + +```bash +git add sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearch.kt sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorDetailSearchTest.kt +git commit -m "feat: add network detail search matcher" +``` + +### Task 2: Build candidates from detail bodies and integrate Network-only search state + +**Files:** +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearch.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveNetDetail.kt` +- Modify: `sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorDetailSearchTest.kt` + +- [ ] **Step 1: Add failing candidate-extraction tests** + +Test that headers produce `row:` key/value candidates, code/raw lines produce `line:` value candidates, and nested JSON produces a key candidate for an object property plus a scalar-value candidate with the property path and ancestor paths. Test that a formatted body remains an `InspectorDetailSectionBody.Formattable` body after search resolution. + +- [ ] **Step 2: Run the focused test and verify the new extraction assertions fail** + +Run: + +```bash +./gradlew :sdk:ui-compose:testDebugUnitTest --tests io.devconsole.ui.compose.InspectorDetailSearchTest --no-daemon +``` + +- [ ] **Step 3: Implement body candidate extraction** + +Traverse `KeyValues`, `Code`, and `Formattable` bodies in display order. For JSON, emit quoted object keys and rendered scalar values while retaining each row path and ancestor paths. Treat XML/plain raw lines as value candidates. Add the four network scope options and a `searchOptions` field to `ObserveDetailContent`; set it only in `netDetailContent` with all four sections selected and `KEYS` as the default mode. + +- [ ] **Step 4: Split Network search resolution from legacy non-Network resolution** + +Keep existing search behavior for other capture detail kinds. For Network detail, resolve only configured sections, keep all original rows/lines, attach ordered `InspectorDetailSearchMatch` lists, auto-expand matching sections, and never replace `Formattable` with `Code`. Excluded sections must retain their normal display and must not show `no match` metadata. + +- [ ] **Step 5: Wire saveable state and navigation** + +Add saveable selected-section keys, match mode, current-match index, and bottom-sheet visibility to `InspectorObserveDetailScreen` when `content.searchOptions` is present. Reset the current index when query, scope, or mode changes. Use `nextInspectorMatchIndex` and `previousInspectorMatchIndex` for wrap-around navigation. Keep the existing legacy query path for content without Network search options. + +- [ ] **Step 6: Re-run tests and commit the state/resolution integration** + +Run the focused test command and then: + +```bash +./gradlew :sdk:ui-compose:testDebugUnitTest --no-daemon +``` + +Commit the verified integration: + +```bash +git add sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearch.kt sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveNetDetail.kt sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorDetailSearchTest.kt +git commit -m "feat: scope network detail search" +``` + +### Task 3: Add the options bottom sheet and search navigation controls + +**Files:** +- Create: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearchOptionsSheet.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearchField.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt` + +- [ ] **Step 1: Add the bottom-sheet composable** + +Use `ModalBottomSheet` with a draft `Set` and draft `InspectorSearchMode`. Render four 48dp-minimum checkbox rows, Select all/Clear all actions, three mutually exclusive mode chips, and Cancel/Apply actions. Disable Apply when no section is selected. Apply must return both draft values; Cancel must only dismiss. + +- [ ] **Step 2: Add search-field controls** + +Keep the existing search input. For Network detail, add 48dp previous and next icon buttons, disabled when no matches, plus a scope filter chip that opens the bottom sheet. Show `current/total`, `0/0` for no matches, and a scope summary such as `All request + response`, `Response body`, or `2 sections`. Use rotated existing chevron glyphs for arrows so no icon dependency is added. + +- [ ] **Step 3: Render and connect the sheet** + +Open the sheet from the scope chip, pass the current active configuration, and on Apply update the saveable state, reset the current match, and dismiss the sheet. Add accessible labels/content descriptions for scope, previous, next, checkboxes, modes, Cancel, and Apply. + +- [ ] **Step 4: Build and run the existing unit suite** + +```bash +./gradlew :sdk:ui-compose:testDebugUnitTest --no-daemon +``` + +Commit the verified controls: + +```bash +git add sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearchOptionsSheet.kt sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearchField.kt sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt +git commit -m "feat: add network search controls" +``` + +### Task 4: Add exact highlighting and preserve formatted bodies + +**Files:** +- Create: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorSearchHighlight.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorKeyValueList.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeBlock.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeFullScreenOverlay.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorFormattableBody.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorBodyFormat.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt` + +- [ ] **Step 1: Add failing rendering-model tests** + +Test that search metadata for a formatted JSON response remains `InspectorDetailSectionBody.Formattable`, that a key match targets the JSON row key text, and that a value match targets the scalar text with exact offsets. + +- [ ] **Step 2: Run the focused test and verify it fails against the current flat-search behavior** + +Run: + +```bash +./gradlew :sdk:ui-compose:testDebugUnitTest --tests io.devconsole.ui.compose.InspectorDetailSearchTest --no-daemon +``` + +- [ ] **Step 3: Implement reusable exact-range highlighting** + +Add `InspectorSearchHighlight(start, endExclusive, active)` and a monospace `AnnotatedString` renderer that applies a signal-soft background to inactive matches and a stronger signal background to the active match. Clamp invalid ranges and leave text unchanged when there are no highlights. + +- [ ] **Step 4: Apply highlights without changing body shape** + +Pass match metadata and current ordinal into key/value, code, and formattable renderers. Highlight key and value spans separately. Extend `JsonTreeRow` with key/value search highlight ranges, preserve existing mock-diff row highlighting, and apply search highlights to JSON tree key/value text. Search-driven matches must not set the old row-only `highlighted` flag or replace a Formattable body with Code. + +- [ ] **Step 5: Keep raw/XML/JSON views usable** + +For XML and raw lines, decorate the existing code lines. For JSON formatted mode, decorate the existing tree rows. Keep the Raw/Formatted toggle and its selected state intact while the query is active; the response must never collapse to a one-line or flat representation as a side effect of searching. + +- [ ] **Step 6: Re-run the full unit suite and commit the rendering fix** + +```bash +./gradlew :sdk:ui-compose:testDebugUnitTest --no-daemon +``` + +Commit after the output reports success: + +```bash +git add sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorSearchHighlight.kt sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorKeyValueList.kt sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeBlock.kt sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeFullScreenOverlay.kt sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorFormattableBody.kt sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorBodyFormat.kt sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt +git commit -m "fix: preserve formatted network search results" +``` + +### Task 5: Bring the active match into view and verify the Android UI + +**Files:** +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorKeyValueList.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeBlock.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorFormattableBody.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailPreviews.kt` + +- [ ] **Step 1: Add target scrolling** + +Use `LazyListState` for code and formatted body lists. When the active ordinal changes, locate its `line:` or JSON path target and animate that row into view. Use `BringIntoViewRequester` for key/value rows in the outer detail scroll. Force-expand JSON ancestor paths for selected matches while retaining user expansion overrides otherwise. + +- [ ] **Step 2: Add realistic preview data** + +Update the detail preview with nested request/response JSON and repeated matches so the formatted tree, exact highlights, active match, and navigation controls are visible in previews. + +- [ ] **Step 3: Run targeted unit/build verification** + +```bash +./gradlew :sdk:ui-compose:testDebugUnitTest :samples:compose-app:assembleDebug --no-daemon +``` + +Expected: BUILD SUCCESSFUL and zero failed tests. + +- [ ] **Step 4: Install and verify the sample on the running emulator** + +Install the debug APK, open the Network tab and a transaction detail, then verify: + +- default scope is all four request/response sections; +- bottom sheet supports selecting multiple sections and cancelling without changes; +- Keys is selected by default and Values/Keys + values change matches; +- previous/next update the current match and scroll to it; +- exact text is highlighted; +- General/Timing/Redactions never contribute matches; +- formatted JSON remains a tree after searching. + +- [ ] **Step 5: Inspect the final diff and commit verification-safe changes** + +```bash +git status --short +git diff --check +git diff --stat +``` + +Commit any final source/preview fixes only after the targeted build and tests pass. From c461273dede2b2d1b37b74dcb7df83e9f3fe731f Mon Sep 17 00:00:00 2001 From: shakibuzzaman Date: Mon, 17 Aug 2026 12:35:26 +0600 Subject: [PATCH 08/20] feat: add network detail search matcher --- .../ui/compose/InspectorDetailSearch.kt | 110 ++++++++++++++++++ .../ui/compose/InspectorDetailSearchTest.kt | 76 ++++++++++++ 2 files changed, 186 insertions(+) create mode 100644 sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearch.kt create mode 100644 sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorDetailSearchTest.kt diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearch.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearch.kt new file mode 100644 index 0000000..7dfcd10 --- /dev/null +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearch.kt @@ -0,0 +1,110 @@ +/** + * @author Shakib + * @since 17/08/26 + */ +package io.devconsole.ui.compose + +/** Whether a search candidate represents a field name or its associated content. */ +internal enum class InspectorSearchField { + KEY, + VALUE, +} + +/** Search fields enabled by the Network detail search options sheet. */ +internal enum class InspectorSearchMode( + val label: String, +) { + KEYS("Keys"), + VALUES("Values"), + KEYS_AND_VALUES("Keys + values"), +} + +/** One searchable piece of rendered detail content. */ +internal data class InspectorSearchCandidate( + val sectionKey: String, + val itemId: String, + val field: InspectorSearchField, + val text: String, + val path: String? = null, + val ancestorPaths: List = emptyList(), +) + +/** One exact query occurrence in a searchable candidate. */ +internal data class InspectorDetailSearchMatch( + val ordinal: Int, + val sectionKey: String, + val itemId: String, + val field: InspectorSearchField, + val start: Int, + val endExclusive: Int, + val path: String? = null, + val ancestorPaths: List = emptyList(), +) + +/** Returns all non-overlapping, case-insensitive occurrences of [query] in [text]. */ +private fun findInspectorQueryRanges( + text: String, + query: String, +): List { + if (query.isEmpty() || query.length > text.length) return emptyList() + val ranges = mutableListOf() + var start = 0 + while (start <= text.length - query.length) { + val matchAt = + (start..text.length - query.length).firstOrNull { index -> + text.regionMatches(index, query, 0, query.length, ignoreCase = true) + } + ?: break + ranges += matchAt until (matchAt + query.length) + start = matchAt + query.length + } + return ranges +} + +private fun InspectorSearchMode.includes(field: InspectorSearchField): Boolean = + when (this) { + InspectorSearchMode.KEYS -> field == InspectorSearchField.KEY + InspectorSearchMode.VALUES -> field == InspectorSearchField.VALUE + InspectorSearchMode.KEYS_AND_VALUES -> true + } + +/** Matches selected candidates in their supplied document order. */ +internal fun searchInspectorCandidates( + candidates: List, + query: String, + selectedSectionKeys: Set, + mode: InspectorSearchMode, +): List { + val trimmedQuery = query.trim() + if (trimmedQuery.isEmpty()) return emptyList() + + return buildList { + candidates.forEach { candidate -> + if (candidate.sectionKey !in selectedSectionKeys || !mode.includes(candidate.field)) return@forEach + findInspectorQueryRanges(candidate.text, trimmedQuery).forEach { range -> + add( + InspectorDetailSearchMatch( + ordinal = size, + sectionKey = candidate.sectionKey, + itemId = candidate.itemId, + field = candidate.field, + start = range.first, + endExclusive = range.last + 1, + path = candidate.path, + ancestorPaths = candidate.ancestorPaths, + ), + ) + } + } + } +} + +internal fun nextInspectorMatchIndex( + current: Int, + total: Int, +): Int = if (total <= 0) 0 else (current.coerceIn(0, total - 1) + 1) % total + +internal fun previousInspectorMatchIndex( + current: Int, + total: Int, +): Int = if (total <= 0) 0 else (current.coerceIn(0, total - 1) - 1 + total) % total diff --git a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorDetailSearchTest.kt b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorDetailSearchTest.kt new file mode 100644 index 0000000..0e1a46d --- /dev/null +++ b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorDetailSearchTest.kt @@ -0,0 +1,76 @@ +/** + * @author Shakib + * @since 17/08/26 + */ +package io.devconsole.ui.compose + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class InspectorDetailSearchTest { + @Test + fun `keys mode matches keys but not values and keeps exact ranges`() { + val candidates = + listOf( + InspectorSearchCandidate("reqh", "row:0", InspectorSearchField.KEY, "Content-Type"), + InspectorSearchCandidate("reqh", "row:0", InspectorSearchField.VALUE, "application/json"), + ) + + val matches = + searchInspectorCandidates( + candidates, + "content", + setOf("reqh"), + InspectorSearchMode.KEYS, + ) + + assertEquals(1, matches.size) + assertEquals(0, matches.single().start) + assertEquals(7, matches.single().endExclusive) + } + + @Test + fun `multi section matching follows candidate order and values mode`() { + val candidates = + listOf( + InspectorSearchCandidate("req", "line:0", InspectorSearchField.VALUE, "userId: 1"), + InspectorSearchCandidate("res", "line:0", InspectorSearchField.VALUE, "userId: 1"), + InspectorSearchCandidate("general", "row:0", InspectorSearchField.VALUE, "userId: 1"), + ) + + val matches = + searchInspectorCandidates( + candidates, + "userid", + setOf("req", "res"), + InspectorSearchMode.VALUES, + ) + + assertEquals(listOf("req", "res"), matches.map { it.sectionKey }) + assertEquals(listOf(0, 1), matches.map { it.ordinal }) + } + + @Test + fun `previous and next navigation wrap around`() { + assertEquals(0, nextInspectorMatchIndex(current = 2, total = 3)) + assertEquals(2, previousInspectorMatchIndex(current = 0, total = 3)) + assertEquals(0, nextInspectorMatchIndex(current = 0, total = 0)) + assertEquals(0, previousInspectorMatchIndex(current = 0, total = 0)) + } + + @Test + fun `blank query produces no matches`() { + val candidates = + listOf(InspectorSearchCandidate("res", "line:0", InspectorSearchField.VALUE, "userId: 1")) + + assertTrue( + searchInspectorCandidates( + candidates, + " ", + setOf("res"), + InspectorSearchMode.VALUES, + ).isEmpty(), + ) + } +} From 71ed9fda42bd1e17fd6b5b961053417fa916b45c Mon Sep 17 00:00:00 2001 From: shakibuzzaman Date: Mon, 17 Aug 2026 13:39:17 +0600 Subject: [PATCH 09/20] feat: improve network detail search --- .../ui/compose/InspectorBodyFormat.kt | 2 + .../ui/compose/InspectorCodeBlock.kt | 51 ++++- .../compose/InspectorCodeFullScreenOverlay.kt | 15 +- .../ui/compose/InspectorDetailSearch.kt | 175 +++++++++++++++++ .../ui/compose/InspectorDetailSearchField.kt | 105 +++++++--- .../InspectorDetailSearchOptionsSheet.kt | 125 ++++++++++++ .../ui/compose/InspectorFormattableBody.kt | 181 ++++++++++++++--- .../devconsole/ui/compose/InspectorGlyphs.kt | 5 +- .../ui/compose/InspectorKeyValueList.kt | 35 +++- .../ui/compose/InspectorObserveDetail.kt | 182 +++++++++++++++++- .../ui/compose/InspectorObserveNetDetail.kt | 1 + .../ui/compose/InspectorObserveScreen.kt | 1 + .../ui/compose/InspectorSearchHighlight.kt | 51 +++++ .../ui/compose/InspectorDetailSearchTest.kt | 67 +++++++ 14 files changed, 923 insertions(+), 73 deletions(-) create mode 100644 sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearchOptionsSheet.kt create mode 100644 sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorSearchHighlight.kt diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorBodyFormat.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorBodyFormat.kt index 6b7b5f7..c1e2168 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorBodyFormat.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorBodyFormat.kt @@ -190,6 +190,8 @@ internal data class JsonTreeRow( val content: JsonTreeRowContent, val trailingComma: Boolean, val highlighted: Boolean = false, + val searchKeyHighlights: List = emptyList(), + val searchValueHighlights: List = emptyList(), ) /** diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeBlock.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeBlock.kt index 52fd0bb..fd7f71e 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeBlock.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeBlock.kt @@ -3,6 +3,7 @@ * @since 04/08/26 */ @file:Suppress("FunctionNaming", "MagicNumber", "MatchingDeclarationName") +@file:OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class) package io.devconsole.ui.compose @@ -14,12 +15,17 @@ import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.relocation.BringIntoViewRequester +import androidx.compose.foundation.relocation.bringIntoViewRequester import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape 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.clip @@ -60,11 +66,30 @@ internal val InlineCodeBlockMaxHeight = 420.dp internal fun InspectorCodeBlock( lines: List, modifier: Modifier = Modifier, + sectionKey: String = "", + searchMatches: List = emptyList(), + currentMatchOrdinal: Int? = null, onExpandFullScreen: (() -> Unit)? = null, ) { val colors = DevConsoleTheme.colors - Box(modifier = modifier.fillMaxWidth()) { + val sectionMatches = searchMatches.filter { it.sectionKey == sectionKey || sectionKey.isEmpty() } + val listState = rememberLazyListState() + val bringIntoViewRequester = remember { BringIntoViewRequester() } + val activeLineIndex = + sectionMatches + .firstOrNull { it.ordinal == currentMatchOrdinal } + ?.itemId + ?.substringAfter("line:", "") + ?.toIntOrNull() + LaunchedEffect(activeLineIndex, currentMatchOrdinal) { + activeLineIndex?.let { index -> + if (lines.isNotEmpty()) listState.animateScrollToItem(index.coerceIn(0, lines.lastIndex)) + } + if (activeLineIndex != null) bringIntoViewRequester.bringIntoView() + } + Box(modifier = modifier.fillMaxWidth().bringIntoViewRequester(bringIntoViewRequester)) { LazyColumn( + state = listState, modifier = Modifier .fillMaxWidth() @@ -84,7 +109,14 @@ internal fun InspectorCodeBlock( .horizontalScroll(rememberScrollState()) .padding(horizontal = 16.dp, vertical = 12.dp), ) { - itemsIndexed(lines, key = { index, _ -> index }) { _, line -> CodeLineRow(line) } + itemsIndexed(lines, key = { index, _ -> index }) { index, line -> + val itemId = "line:$index" + CodeLineRow( + line = line, + keyHighlights = sectionMatches.highlightsFor(itemId, InspectorSearchField.KEY, currentMatchOrdinal), + valueHighlights = sectionMatches.highlightsFor(itemId, InspectorSearchField.VALUE, currentMatchOrdinal), + ) + } } if (onExpandFullScreen != null) { InspectorCodeBlockExpandButton(onExpandFullScreen) @@ -119,13 +151,15 @@ internal fun CodeLineRow( line: InspectorCodeLine, fontSize: TextUnit = 13.sp, lineHeight: TextUnit = 22.1.sp, + keyHighlights: List = emptyList(), + valueHighlights: List = emptyList(), ) { val colors = DevConsoleTheme.colors val rowBg = if (line.highlighted) colors.signalSoft else Color.Transparent Row(modifier = Modifier.background(rowBg)) { CodeSpan(line.indent, colors.text3, fontSize, lineHeight) - CodeSpan(line.key, colors.jsonKey, fontSize, lineHeight) - CodeSpan(line.value, line.valueColor, fontSize, lineHeight) + CodeSpan(line.key, colors.jsonKey, fontSize, lineHeight, keyHighlights) + CodeSpan(line.value, line.valueColor, fontSize, lineHeight, valueHighlights) } } @@ -135,6 +169,13 @@ private fun CodeSpan( color: Color, fontSize: TextUnit, lineHeight: TextUnit, + highlights: List = emptyList(), ) { - Text(text, color = color, fontFamily = FontFamily.Monospace, fontSize = fontSize, lineHeight = lineHeight) + Text( + inspectorHighlightedText(text, highlights, DevConsoleTheme.colors), + color = color, + fontFamily = FontFamily.Monospace, + fontSize = fontSize, + lineHeight = lineHeight, + ) } 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 75eb5e6..7f29334 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 @@ -49,10 +49,21 @@ internal fun InspectorCodeFullScreenOverlay( lines: List, onDismiss: () -> Unit, modifier: Modifier = Modifier, + sectionKey: String = "", + searchMatches: List = emptyList(), + currentMatchOrdinal: Int? = null, ) { + val sectionMatches = searchMatches.filter { it.sectionKey == sectionKey || sectionKey.isEmpty() } InspectorCodeFullScreenOverlay(title = title, onDismiss = onDismiss, modifier = modifier) { - itemsIndexed(lines, key = { index, _ -> index }) { _, line -> - CodeLineRow(line, fontSize = 14.sp, lineHeight = 23.8.sp) + itemsIndexed(lines, key = { index, _ -> index }) { index, line -> + val itemId = "line:$index" + CodeLineRow( + line = line, + fontSize = 14.sp, + lineHeight = 23.8.sp, + keyHighlights = sectionMatches.highlightsFor(itemId, InspectorSearchField.KEY, currentMatchOrdinal), + valueHighlights = sectionMatches.highlightsFor(itemId, InspectorSearchField.VALUE, currentMatchOrdinal), + ) } } } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearch.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearch.kt index 7dfcd10..674c5ef 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearch.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearch.kt @@ -41,6 +41,55 @@ internal data class InspectorDetailSearchMatch( val ancestorPaths: List = emptyList(), ) +internal data class InspectorDetailSearchSection( + val key: String, + val label: String, +) + +internal data class InspectorDetailSearchOptions( + val sections: List, + val defaultSectionKeys: Set, + val defaultMode: InspectorSearchMode = InspectorSearchMode.KEYS, +) + +internal val NetworkDetailSearchOptions = + InspectorDetailSearchOptions( + sections = + listOf( + InspectorDetailSearchSection("reqh", "Request headers"), + InspectorDetailSearchSection("req", "Request body"), + InspectorDetailSearchSection("resh", "Response headers"), + InspectorDetailSearchSection("res", "Response body"), + ), + defaultSectionKeys = setOf("reqh", "req", "resh", "res"), + ) + +internal fun searchInspectorSections( + sections: List, + query: String, + selectedSectionKeys: Set, + mode: InspectorSearchMode, +): List = + searchInspectorCandidates( + candidates = sections.flatMap { spec -> searchInspectorBodyCandidates(spec.key, spec.body) }, + query = query, + selectedSectionKeys = selectedSectionKeys, + mode = mode, + ) + +internal fun inspectorSearchScopeSummary( + options: InspectorDetailSearchOptions, + selectedSectionKeys: Set, +): String { + val selected = options.sections.filter { it.key in selectedSectionKeys } + return when { + selected.size == options.sections.size -> "All request + response" + selected.size == 1 -> selected.single().label + selected.isEmpty() -> "No sections" + else -> "${selected.size} sections" + } +} + /** Returns all non-overlapping, case-insensitive occurrences of [query] in [text]. */ private fun findInspectorQueryRanges( text: String, @@ -108,3 +157,129 @@ internal fun previousInspectorMatchIndex( current: Int, total: Int, ): Int = if (total <= 0) 0 else (current.coerceIn(0, total - 1) - 1 + total) % total + +/** Extracts candidates in the same order that a detail body presents them. */ +internal fun searchInspectorBodyCandidates( + sectionKey: String, + body: InspectorDetailSectionBody, +): List = + when (body) { + is InspectorDetailSectionBody.KeyValues -> + buildList { + body.entries.forEachIndexed { index, entry -> + add(InspectorSearchCandidate(sectionKey, "row:$index", InspectorSearchField.KEY, entry.key)) + add(InspectorSearchCandidate(sectionKey, "row:$index", InspectorSearchField.VALUE, entry.value)) + } + } + is InspectorDetailSectionBody.Code -> + buildList { + body.lines.forEachIndexed { index, line -> + if (line.key.isNotEmpty()) { + add(InspectorSearchCandidate(sectionKey, "line:$index", InspectorSearchField.KEY, line.key)) + } + if (line.value.isNotEmpty()) { + add(InspectorSearchCandidate(sectionKey, "line:$index", InspectorSearchField.VALUE, line.value)) + } + } + } + is InspectorDetailSectionBody.Formattable -> + when (val formatted = body.formatted) { + is FormattedBody.Json -> jsonSearchCandidates(sectionKey, formatted.root) + is FormattedBody.Xml -> + formatted.text.lines().mapIndexed { index, line -> + InspectorSearchCandidate(sectionKey, "line:$index", InspectorSearchField.VALUE, line) + } + null -> + body.rawLines.mapIndexed { index, line -> + InspectorSearchCandidate(sectionKey, "line:$index", InspectorSearchField.VALUE, line.value) + } + } + is InspectorDetailSectionBody.Bars, is InspectorDetailSectionBody.Empty -> emptyList() + } + +private fun jsonSearchCandidates( + sectionKey: String, + root: JsonValue, +): List = buildList { + appendJsonSearchCandidates(this, sectionKey, root, path = "$") +} + +private fun appendJsonSearchCandidates( + candidates: MutableList, + sectionKey: String, + value: JsonValue, + path: String, +) { + when (value) { + is JsonValue.Obj -> + value.entries.forEachIndexed { index, (key, child) -> + val childPath = "$path/$index:$key" + candidates += + InspectorSearchCandidate( + sectionKey = sectionKey, + itemId = childPath, + field = InspectorSearchField.KEY, + text = key.jsonQuoted(), + path = childPath, + ancestorPaths = jsonAncestorPaths(childPath), + ) + appendJsonSearchCandidates(candidates, sectionKey, child, childPath) + } + is JsonValue.Arr -> + value.items.forEachIndexed { index, child -> + appendJsonSearchCandidates(candidates, sectionKey, child, "$path[$index]") + } + is JsonValue.Str -> + candidates += + InspectorSearchCandidate( + sectionKey = sectionKey, + itemId = path, + field = InspectorSearchField.VALUE, + text = value.value.jsonQuoted(), + path = path, + ancestorPaths = jsonAncestorPaths(path), + ) + is JsonValue.Num -> + candidates += + InspectorSearchCandidate( + sectionKey = sectionKey, + itemId = path, + field = InspectorSearchField.VALUE, + text = value.raw, + path = path, + ancestorPaths = jsonAncestorPaths(path), + ) + is JsonValue.Bool -> + candidates += + InspectorSearchCandidate( + sectionKey = sectionKey, + itemId = path, + field = InspectorSearchField.VALUE, + text = value.value.toString(), + path = path, + ancestorPaths = jsonAncestorPaths(path), + ) + JsonValue.Null -> + candidates += + InspectorSearchCandidate( + sectionKey = sectionKey, + itemId = path, + field = InspectorSearchField.VALUE, + text = "null", + path = path, + ancestorPaths = jsonAncestorPaths(path), + ) + } +} + +private fun jsonAncestorPaths(path: String): List { + if (path == "$") return emptyList() + val ancestors = mutableListOf() + var cursor = path + while (cursor != "$") { + val separator = maxOf(cursor.lastIndexOf('/'), cursor.lastIndexOf('[')) + cursor = if (separator <= 0) "$" else cursor.substring(0, separator) + ancestors += cursor + } + return ancestors.asReversed() +} diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearchField.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearchField.kt index 47f4d2f..29745b5 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearchField.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearchField.kt @@ -9,6 +9,7 @@ package io.devconsole.ui.compose import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height @@ -35,41 +36,91 @@ internal fun InspectorDetailSearchField( onQueryChange: (String) -> Unit, matchLabel: String, modifier: Modifier = Modifier, + onPrevious: (() -> Unit)? = null, + onNext: (() -> Unit)? = null, + navigationEnabled: Boolean = false, + onOpenOptions: (() -> Unit)? = null, + scopeLabel: String? = null, placeholder: String = DEFAULT_DETAIL_SEARCH_PLACEHOLDER, matchColor: Color = DevConsoleTheme.colors.muted, ) { - Row( + Column( modifier = modifier.fillMaxWidth().padding(start = 8.dp, end = 8.dp, bottom = 12.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(12.dp), ) { - Box(modifier = Modifier.weight(1f)) { - Row( - modifier = - Modifier - .fillMaxWidth() - .height(48.dp) - .clip(RoundedCornerShape(50)) - .background(DevConsoleTheme.colors.surface2) - .padding(start = 40.dp, end = 16.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - InspectorPlainTextField( - value = query, - onValueChange = onQueryChange, - placeholder = placeholder, - textColor = DevConsoleTheme.colors.ink, - placeholderColor = DevConsoleTheme.colors.muted, + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Box(modifier = Modifier.weight(1f)) { + Row( + modifier = + Modifier + .fillMaxWidth() + .height(48.dp) + .clip(RoundedCornerShape(50)) + .background(DevConsoleTheme.colors.surface2) + .padding(start = 40.dp, end = 16.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + InspectorPlainTextField( + value = query, + onValueChange = onQueryChange, + placeholder = placeholder, + textColor = DevConsoleTheme.colors.ink, + placeholderColor = DevConsoleTheme.colors.muted, + ) + } + InspectorGlyphIcon( + InspectorGlyph.Search, + contentDescription = null, + tint = DevConsoleTheme.colors.muted, + size = 17.dp, + modifier = Modifier.align(Alignment.CenterStart).padding(start = 14.dp), ) } - InspectorGlyphIcon( - InspectorGlyph.Search, - contentDescription = null, - tint = DevConsoleTheme.colors.muted, - size = 17.dp, - modifier = Modifier.align(Alignment.CenterStart).padding(start = 14.dp), + Text(matchLabel, color = matchColor, fontFamily = FontFamily.Monospace, fontSize = 12.sp, maxLines = 1) + if (onPrevious != null) { + InspectorRoundIconButton( + contentDescription = "Previous match", + onClick = onPrevious, + enabled = navigationEnabled, + size = 44.dp, + icon = { + InspectorGlyphIcon( + InspectorGlyph.ChevronDown, + contentDescription = null, + tint = if (navigationEnabled) DevConsoleTheme.colors.ink else DevConsoleTheme.colors.text3, + size = 16.dp, + rotationDegrees = 90f, + ) + }, + ) + } + if (onNext != null) { + InspectorRoundIconButton( + contentDescription = "Next match", + onClick = onNext, + enabled = navigationEnabled, + size = 44.dp, + icon = { + InspectorGlyphIcon( + InspectorGlyph.ChevronDown, + contentDescription = null, + tint = if (navigationEnabled) DevConsoleTheme.colors.ink else DevConsoleTheme.colors.text3, + size = 16.dp, + rotationDegrees = -90f, + ) + }, + ) + } + } + if (onOpenOptions != null && scopeLabel != null) { + FilterChipRow( + chips = listOf(InspectorFilterChip("search-scope", "Search in: $scopeLabel", selected = true)), + onChipClick = { onOpenOptions() }, + modifier = Modifier.padding(top = 0.dp), ) } - Text(matchLabel, color = matchColor, fontFamily = FontFamily.Monospace, fontSize = 12.sp, maxLines = 1) } } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearchOptionsSheet.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearchOptionsSheet.kt new file mode 100644 index 0000000..1ed68e6 --- /dev/null +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearchOptionsSheet.kt @@ -0,0 +1,125 @@ +/** + * @author Shakib + * @since 17/08/26 + */ +@file:Suppress("FunctionNaming", "MagicNumber") +@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class) + +package io.devconsole.ui.compose + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.Checkbox +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp + +@Composable +internal fun InspectorDetailSearchOptionsSheet( + options: InspectorDetailSearchOptions, + selectedSectionKeys: Set, + mode: InspectorSearchMode, + onDismiss: () -> Unit, + onApply: (Set, InspectorSearchMode) -> Unit, +) { + var draftSectionKeys by remember(selectedSectionKeys) { mutableStateOf(selectedSectionKeys) } + var draftMode by remember(mode) { mutableStateOf(mode) } + val colors = DevConsoleTheme.colors + + ModalBottomSheet(onDismissRequest = onDismiss, containerColor = colors.panel) { + Column( + modifier = + Modifier + .fillMaxWidth() + .fillMaxHeight(0.8f) + .navigationBarsPadding(), + ) { + Row( + modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text("Search options", color = colors.ink, fontSize = 20.sp, modifier = Modifier.weight(1f)) + TextButton(onClick = onDismiss) { Text("Cancel") } + InspectorPillButton( + label = "Apply", + onClick = { onApply(draftSectionKeys, draftMode) }, + enabled = draftSectionKeys.isNotEmpty(), + modifier = Modifier.padding(start = 8.dp), + ) + } + Column( + modifier = + Modifier + .weight(1f) + .verticalScroll(rememberScrollState()) + .padding(horizontal = 20.dp, vertical = 8.dp), + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { + Text("Search in", color = colors.text3, fontSize = 12.sp, modifier = Modifier.padding(top = 12.dp)) + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + TextButton(onClick = { draftSectionKeys = options.sections.map { it.key }.toSet() }) { + Text("Select all") + } + TextButton(onClick = { draftSectionKeys = emptySet() }) { + Text("Clear all") + } + } + options.sections.forEach { section -> + val checked = section.key in draftSectionKeys + Row( + modifier = + Modifier + .fillMaxWidth() + .heightIn(min = 48.dp) + .clickable( + role = Role.Checkbox, + onClick = { + draftSectionKeys = + if (checked) draftSectionKeys - section.key else draftSectionKeys + section.key + }, + ) + .semantics(mergeDescendants = true) {}, + verticalAlignment = Alignment.CenterVertically, + ) { + Checkbox(checked = checked, onCheckedChange = null) + Text(section.label, color = colors.ink, fontSize = 14.sp) + } + } + Text("Match", color = colors.text3, fontSize = 12.sp, modifier = Modifier.padding(top = 12.dp)) + FilterChipRow( + chips = + InspectorSearchMode.values().map { candidate -> + InspectorFilterChip(candidate.name, candidate.label, selected = candidate == draftMode) + }, + onChipClick = { chip -> + draftMode = InspectorSearchMode.values().first { it.name == chip.id } + }, + modifier = Modifier.padding(horizontal = 0.dp), + ) + } + } + } +} diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorFormattableBody.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorFormattableBody.kt index e2082fa..8258b13 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorFormattableBody.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorFormattableBody.kt @@ -3,6 +3,7 @@ * @since 05/08/26 */ @file:Suppress("FunctionNaming", "MagicNumber") +@file:OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class) package io.devconsole.ui.compose @@ -18,14 +19,18 @@ import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width +import androidx.compose.foundation.relocation.BringIntoViewRequester +import androidx.compose.foundation.relocation.bringIntoViewRequester import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListScope import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateMapOf @@ -54,12 +59,33 @@ import androidx.compose.ui.unit.sp internal fun InspectorFormattableBody( body: InspectorDetailSectionBody.Formattable, modifier: Modifier = Modifier, + sectionKey: String = "", + searchMatches: List = emptyList(), + currentMatchOrdinal: Int? = null, onExpandFullScreen: (() -> Unit)? = null, ) { val colors = DevConsoleTheme.colors var showRaw by rememberSaveable(body.rawText) { mutableStateOf(body.formatted == null) } - val precomputed = rememberFormattableContent(body, showRaw) - Column(modifier = modifier.fillMaxWidth()) { + val precomputed = + rememberFormattableContent( + body = body, + showRaw = showRaw, + sectionKey = sectionKey, + searchMatches = searchMatches, + currentMatchOrdinal = currentMatchOrdinal, + ) + val listState = rememberLazyListState() + val sectionMatches = searchMatches.filter { it.sectionKey == sectionKey || sectionKey.isEmpty() } + val bringIntoViewRequester = remember { BringIntoViewRequester() } + LaunchedEffect(precomputed.targetIndex, currentMatchOrdinal) { + precomputed.targetIndex?.let { index -> + listState.animateScrollToItem(index.coerceAtLeast(0)) + } + if (sectionMatches.any { it.ordinal == currentMatchOrdinal }) { + bringIntoViewRequester.bringIntoView() + } + } + Column(modifier = modifier.fillMaxWidth().bringIntoViewRequester(bringIntoViewRequester)) { if (body.formatted != null) { RawFormattedToggle( showRaw = showRaw, @@ -86,6 +112,7 @@ internal fun InspectorFormattableBody( } Box(modifier = Modifier.fillMaxWidth()) { LazyColumn( + state = listState, modifier = Modifier .fillMaxWidth() @@ -98,7 +125,7 @@ internal fun InspectorFormattableBody( // only visible for tall bodies with progressively wider lines, not a bug. .horizontalScroll(rememberScrollState()) .padding(horizontal = 16.dp, vertical = 12.dp), - content = precomputed, + content = precomputed.content, ) if (onExpandFullScreen != null) { InspectorCodeBlockExpandButton(onExpandFullScreen) @@ -114,9 +141,21 @@ internal fun InspectorFormattableFullScreenOverlay( body: InspectorDetailSectionBody.Formattable, onDismiss: () -> Unit, modifier: Modifier = Modifier, + sectionKey: String = "", + searchMatches: List = emptyList(), + currentMatchOrdinal: Int? = null, ) { var showRaw by rememberSaveable(body.rawText) { mutableStateOf(body.formatted == null) } - val precomputed = rememberFormattableContent(body, showRaw, fontSize = 14.sp, lineHeight = 23.8.sp) + val precomputed = + rememberFormattableContent( + body = body, + showRaw = showRaw, + fontSize = 14.sp, + lineHeight = 23.8.sp, + sectionKey = sectionKey, + searchMatches = searchMatches, + currentMatchOrdinal = currentMatchOrdinal, + ) InspectorCodeFullScreenOverlay( title = title, onDismiss = onDismiss, @@ -127,7 +166,7 @@ internal fun InspectorFormattableFullScreenOverlay( } else { null }, - content = precomputed, + content = precomputed.content, ) } @@ -138,14 +177,23 @@ internal fun InspectorFormattableFullScreenOverlay( * `content: LazyListScope.() -> Unit` lambda itself -- that lambda type isn't `@Composable`, so * `remember`/[rememberJsonTreeRows] can't be called from inside it directly. */ +private data class FormattableRenderContent( + val content: LazyListScope.() -> Unit, + val targetIndex: Int?, +) + @Composable private fun rememberFormattableContent( body: InspectorDetailSectionBody.Formattable, showRaw: Boolean, fontSize: TextUnit = 13.sp, lineHeight: TextUnit = 22.1.sp, -): LazyListScope.() -> Unit { + sectionKey: String = "", + searchMatches: List = emptyList(), + currentMatchOrdinal: Int? = null, +): FormattableRenderContent { val colors = DevConsoleTheme.colors + val sectionMatches = searchMatches.filter { it.sectionKey == sectionKey || sectionKey.isEmpty() } val formatted = body.formatted val useRaw = showRaw || formatted == null @@ -157,27 +205,71 @@ private fun rememberFormattableContent( } val jsonTree: Pair, (String) -> Unit>? = if (!useRaw && formatted is FormattedBody.Json) { - rememberJsonTreeRows(formatted.root, body.jsonHighlightPaths) + rememberJsonTreeRows( + root = formatted.root, + highlightedPaths = body.jsonHighlightPaths, + searchMatches = sectionMatches, + currentMatchOrdinal = currentMatchOrdinal, + forcedExpandedPaths = sectionMatches.flatMap { it.ancestorPaths }.toSet(), + ) } else { null } - return { - when { - xmlLines != null -> - itemsIndexed(xmlLines, key = { index, _ -> index }) { _, line -> - CodeLineRow(line, fontSize, lineHeight) + val activeMatch = sectionMatches.firstOrNull { it.ordinal == currentMatchOrdinal } + val targetIndex = + if (jsonTree != null) { + val rows = jsonTree.first + activeMatch?.path?.let { path -> rows.indexOfFirst { row -> row.path == path }.takeIf { it >= 0 } } + } else { + activeMatch + ?.itemId + ?.substringAfter("line:", "") + ?.toIntOrNull() + } + return FormattableRenderContent( + content = { + when { + xmlLines != null -> + itemsIndexed(xmlLines, key = { index, _ -> index }) { index, line -> + val itemId = "line:$index" + CodeLineRow( + line = line, + fontSize = fontSize, + lineHeight = lineHeight, + valueHighlights = + sectionMatches.highlightsFor( + itemId, + InspectorSearchField.VALUE, + currentMatchOrdinal, + ), + ) + } + jsonTree != null -> { + val (rows, onToggle) = jsonTree + items(rows, key = { it.lazyKey() }) { row -> + JsonTreeRowView(row, onToggle, fontSize, lineHeight) + } } - jsonTree != null -> { - val (rows, onToggle) = jsonTree - items(rows, key = { it.lazyKey() }) { row -> JsonTreeRowView(row, onToggle, fontSize, lineHeight) } + else -> + itemsIndexed(body.rawLines, key = { index, _ -> index }) { index, line -> + val itemId = "line:$index" + CodeLineRow( + line = line, + fontSize = fontSize, + lineHeight = lineHeight, + valueHighlights = + sectionMatches.highlightsFor( + itemId, + InspectorSearchField.VALUE, + currentMatchOrdinal, + ), + ) + } } - else -> - itemsIndexed(body.rawLines, key = { index, _ -> index }) { _, line -> - CodeLineRow(line, fontSize, lineHeight) - } - } - } + }, + targetIndex = targetIndex, + ) } /** @@ -191,19 +283,29 @@ private fun rememberFormattableContent( private fun rememberJsonTreeRows( root: JsonValue, highlightedPaths: Set, + searchMatches: List = emptyList(), + currentMatchOrdinal: Int? = null, + forcedExpandedPaths: Set = emptySet(), ): Pair, (String) -> Unit> { val expandedOverrides = remember(root) { mutableStateMapOf() } - val rows by remember(root, highlightedPaths) { + val rows by remember(root, highlightedPaths, forcedExpandedPaths) { derivedStateOf { flattenJsonTree( root, - isExpanded = { path -> expandedOverrides[path] ?: true }, + isExpanded = { path -> path in forcedExpandedPaths || expandedOverrides[path] ?: true }, highlightedPaths = highlightedPaths, ) } } + val searchRows = + rows.map { row -> + row.copy( + searchKeyHighlights = searchMatches.highlightsFor(row.path, InspectorSearchField.KEY, currentMatchOrdinal), + searchValueHighlights = searchMatches.highlightsFor(row.path, InspectorSearchField.VALUE, currentMatchOrdinal), + ) + } val onToggle: (String) -> Unit = { path -> expandedOverrides[path] = !(expandedOverrides[path] ?: true) } - return rows to onToggle + return searchRows to onToggle } /** A two-chip Raw/Formatted switcher, built from the same [FilterChipRow] every other filter row uses. */ @@ -276,8 +378,23 @@ private fun JsonTreeRowView( } else { Spacer(Modifier.width(JsonTreeChevronSlot)) } - row.keyLabel?.let { key -> JsonTreeMono("${key.jsonQuoted()}: ", colors.jsonKey, fontSize, lineHeight) } - JsonTreeValueSpan(row.content, row.depth, colors, fontSize, lineHeight) + row.keyLabel?.let { key -> + JsonTreeMono( + text = "${key.jsonQuoted()}: ", + color = colors.jsonKey, + fontSize = fontSize, + lineHeight = lineHeight, + highlights = row.searchKeyHighlights, + ) + } + JsonTreeValueSpan( + content = row.content, + depth = row.depth, + colors = colors, + fontSize = fontSize, + lineHeight = lineHeight, + highlights = row.searchValueHighlights, + ) if (row.trailingComma) JsonTreeMono(",", colors.text3, fontSize, lineHeight) } } @@ -289,10 +406,11 @@ private fun JsonTreeValueSpan( colors: DevConsoleColors, fontSize: TextUnit, lineHeight: TextUnit, + highlights: List = emptyList(), ) { when (content) { is JsonTreeRowContent.Scalar -> - JsonTreeMono(content.text, content.type.color(colors), fontSize, lineHeight) + JsonTreeMono(content.text, content.type.color(colors), fontSize, lineHeight, highlights) is JsonTreeRowContent.ContainerStart -> JsonTreeMono(if (content.isArray) "[" else "{", colors.jsonBraceAt(depth), fontSize, lineHeight) is JsonTreeRowContent.ContainerEnd -> @@ -327,6 +445,13 @@ private fun JsonTreeMono( color: Color, fontSize: TextUnit, lineHeight: TextUnit, + highlights: List = emptyList(), ) { - Text(text, color = color, fontFamily = FontFamily.Monospace, fontSize = fontSize, lineHeight = lineHeight) + Text( + inspectorHighlightedText(text, highlights, DevConsoleTheme.colors), + color = color, + fontFamily = FontFamily.Monospace, + fontSize = fontSize, + lineHeight = lineHeight, + ) } 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 ebc495b..283728b 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 @@ -24,6 +24,7 @@ import androidx.compose.material3.minimumInteractiveComponentSize import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.rotate import androidx.compose.ui.geometry.Offset @@ -172,6 +173,7 @@ internal fun InspectorRoundIconButton( onClick: () -> Unit, modifier: Modifier = Modifier, size: Dp = 48.dp, + enabled: Boolean = true, containerColor: Color = Color.Transparent, icon: @Composable () -> Unit, ) { @@ -180,9 +182,10 @@ internal fun InspectorRoundIconButton( modifier .minimumInteractiveComponentSize() .size(size) + .alpha(if (enabled) 1f else 0.45f) .clip(CircleShape) .background(containerColor) - .clickable(onClick = onClick, role = Role.Button) + .clickable(enabled = enabled, onClick = onClick, role = Role.Button) .semantics { this.contentDescription = contentDescription }, contentAlignment = Alignment.Center, ) { icon() } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorKeyValueList.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorKeyValueList.kt index d25749e..b4d0f6d 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorKeyValueList.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorKeyValueList.kt @@ -3,6 +3,7 @@ * @since 04/08/26 */ @file:Suppress("FunctionNaming", "MagicNumber", "MatchingDeclarationName") +@file:OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class) package io.devconsole.ui.compose @@ -10,8 +11,12 @@ import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.relocation.bringIntoViewRequester +import androidx.compose.foundation.relocation.BringIntoViewRequester import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.geometry.Offset @@ -35,25 +40,49 @@ internal data class InspectorKeyValue( internal fun InspectorKeyValueList( entries: List, modifier: Modifier = Modifier, + sectionKey: String = "", + searchMatches: List = emptyList(), + currentMatchOrdinal: Int? = null, ) { val colors = DevConsoleTheme.colors val lineColor = colors.line + val sectionMatches = searchMatches.filter { it.sectionKey == sectionKey || sectionKey.isEmpty() } // No top inset on this padding, so the first divider sits flush under the section header // instead of 8dp below it. Column(modifier = modifier.fillMaxWidth().padding(start = 16.dp, end = 16.dp, bottom = 8.dp)) { - entries.forEach { entry -> + entries.forEachIndexed { index, entry -> + val itemId = "row:$index" + val bringIntoViewRequester = remember { BringIntoViewRequester() } + val isActive = sectionMatches.any { it.ordinal == currentMatchOrdinal && it.itemId == itemId } + LaunchedEffect(isActive, currentMatchOrdinal) { + if (isActive) bringIntoViewRequester.bringIntoView() + } Column( modifier = Modifier .fillMaxWidth() + .bringIntoViewRequester(bringIntoViewRequester) .drawBehind { drawLine(lineColor, Offset(0f, 0f), Offset(size.width, 0f), 1.dp.toPx()) }.padding(vertical = 12.dp), verticalArrangement = Arrangement.spacedBy(4.dp), ) { - Text(entry.key, color = colors.jsonKey, fontFamily = FontFamily.Monospace, fontSize = 12.sp) Text( - entry.value, + inspectorHighlightedText( + text = entry.key, + highlights = sectionMatches.highlightsFor(itemId, InspectorSearchField.KEY, currentMatchOrdinal), + colors = colors, + ), + color = colors.jsonKey, + fontFamily = FontFamily.Monospace, + fontSize = 12.sp, + ) + Text( + inspectorHighlightedText( + text = entry.value, + highlights = sectionMatches.highlightsFor(itemId, InspectorSearchField.VALUE, currentMatchOrdinal), + colors = colors, + ), color = entry.valueColor ?: colors.ink, fontFamily = FontFamily.Monospace, fontSize = 13.5.sp, diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt index 836ec04..e0e1531 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt @@ -11,6 +11,7 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateMapOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember @@ -93,6 +94,7 @@ private data class ResolvedDetailSection( val metaColor: Color, val body: InspectorDetailSectionBody?, val emptyMessage: String?, + val searchMatches: List = emptyList(), ) private fun matchesQuery( @@ -208,10 +210,72 @@ private fun resolveDetailSection( ) } +/** Network detail resolver: preserves every original body shape and decorates it with match metadata. */ +private fun resolveNetworkDetailSection( + spec: InspectorDetailSectionSpec, + query: String, + openState: Map, + colors: DevConsoleColors, + matches: List, + searchable: Boolean, +): ResolvedDetailSection { + val hasQuery = query.trim().isNotEmpty() + val total = detailBodyItemCount(spec.body) + val expanded = if (hasQuery && matches.isNotEmpty()) true else openState[spec.key] == true + val meta = + when { + hasQuery && searchable -> + if (matches.isNotEmpty()) { + "${matches.size} match${if (matches.size == 1) "" else "es"}" + } else { + "no match" + } + expanded -> if (total > 0) total.toString() else "" + else -> if (total > 0) "$total line${if (total == 1) "" else "s"}" else "" + } + val metaColor = + if (hasQuery && searchable) { + if (matches.isNotEmpty()) colors.signal else colors.text3 + } else { + colors.text3 + } + if (!expanded) { + return ResolvedDetailSection( + expanded = false, + hits = matches.size, + meta = meta, + metaColor = metaColor, + body = null, + emptyMessage = null, + searchMatches = matches, + ) + } + val emptyMessage = (spec.body as? InspectorDetailSectionBody.Empty)?.text + return ResolvedDetailSection( + expanded = true, + hits = matches.size, + meta = meta, + metaColor = metaColor, + body = if (emptyMessage == null) spec.body else null, + emptyMessage = emptyMessage, + searchMatches = matches, + ) +} + +private fun detailBodyItemCount(body: InspectorDetailSectionBody): Int = + when (body) { + is InspectorDetailSectionBody.KeyValues -> body.entries.size + is InspectorDetailSectionBody.Code -> body.lines.size + is InspectorDetailSectionBody.Formattable -> body.rawLines.size + is InspectorDetailSectionBody.Bars -> body.stats.size + is InspectorDetailSectionBody.Empty -> 0 + } + @Composable private fun InspectorDetailSectionCard( spec: InspectorDetailSectionSpec, resolved: ResolvedDetailSection, + currentMatchOrdinal: Int?, onToggle: () -> Unit, onExpandCodeFullScreen: (String) -> Unit, ) { @@ -232,11 +296,29 @@ private fun InspectorDetailSectionCard( emptyMessage != null -> InspectorDetailEmptyText(emptyMessage) else -> when (val body = resolved.body) { - is InspectorDetailSectionBody.KeyValues -> InspectorKeyValueList(body.entries) + is InspectorDetailSectionBody.KeyValues -> + InspectorKeyValueList( + entries = body.entries, + sectionKey = spec.key, + searchMatches = resolved.searchMatches, + currentMatchOrdinal = currentMatchOrdinal, + ) is InspectorDetailSectionBody.Code -> - InspectorCodeBlock(body.lines, onExpandFullScreen = { onExpandCodeFullScreen(spec.key) }) + InspectorCodeBlock( + lines = body.lines, + sectionKey = spec.key, + searchMatches = resolved.searchMatches, + currentMatchOrdinal = currentMatchOrdinal, + onExpandFullScreen = { onExpandCodeFullScreen(spec.key) }, + ) is InspectorDetailSectionBody.Formattable -> - InspectorFormattableBody(body, onExpandFullScreen = { onExpandCodeFullScreen(spec.key) }) + InspectorFormattableBody( + body = body, + sectionKey = spec.key, + searchMatches = resolved.searchMatches, + currentMatchOrdinal = currentMatchOrdinal, + onExpandFullScreen = { onExpandCodeFullScreen(spec.key) }, + ) is InspectorDetailSectionBody.Bars -> InspectorProgressBars(body.stats) is InspectorDetailSectionBody.Empty, null -> InspectorDetailEmptyText("Nothing captured.") } @@ -264,15 +346,54 @@ internal fun InspectorObserveDetailScreen( onBack: () -> Unit, modifier: Modifier = Modifier, searchPlaceholder: String = DEFAULT_DETAIL_SEARCH_PLACEHOLDER, + searchOptions: InspectorDetailSearchOptions? = null, ) { var query by rememberSaveable(resetKey) { mutableStateOf("") } + var selectedSectionKeys by + rememberSaveable(resetKey) { + mutableStateOf(searchOptions?.defaultSectionKeys?.toList().orEmpty()) + } + var searchModeName by + rememberSaveable(resetKey) { + mutableStateOf((searchOptions?.defaultMode ?: InspectorSearchMode.KEYS_AND_VALUES).name) + } + var currentMatchOrdinal by rememberSaveable(resetKey) { mutableIntStateOf(0) } + var searchOptionsVisible by remember(resetKey) { mutableStateOf(false) } val openState = remember(resetKey) { mutableStateMapOf().apply { initiallyOpenSectionKeys.forEach { key -> this[key] = true } } } val colors = DevConsoleTheme.colors - val resolved = sections.map { spec -> spec to resolveDetailSection(spec, query, openState, colors) } - val totalHits = resolved.sumOf { (_, section) -> section.hits } + val selectedKeys = selectedSectionKeys.toSet() + val searchMode = + InspectorSearchMode.values().firstOrNull { it.name == searchModeName } + ?: InspectorSearchMode.KEYS + val networkMatches = + if (searchOptions != null) { + searchInspectorSections(sections, query, selectedKeys, searchMode) + } else { + emptyList() + } + val activeMatchOrdinal = + if (networkMatches.isEmpty()) 0 else currentMatchOrdinal.coerceIn(0, networkMatches.lastIndex) + val resolved = + sections.map { spec -> + if (searchOptions != null) { + val sectionMatches = networkMatches.filter { it.sectionKey == spec.key } + spec to + resolveNetworkDetailSection( + spec = spec, + query = query, + openState = openState, + colors = colors, + matches = sectionMatches, + searchable = spec.key in searchOptions.sections.map { it.key }, + ) + } else { + spec to resolveDetailSection(spec, query, openState, colors) + } + } + val totalHits = if (searchOptions != null) networkMatches.size else resolved.sumOf { (_, section) -> section.hits } // Which section's code block (if any) is showing full-screen. // Bundle-safe on its own (a String key), and the lines it needs are re-derived from `resolved` @@ -295,6 +416,9 @@ internal fun InspectorObserveDetailScreen( lines = body.lines, onDismiss = { fullScreenSectionKey = null }, modifier = modifier.fillMaxSize(), + sectionKey = spec.key, + searchMatches = section.searchMatches, + currentMatchOrdinal = activeMatchOrdinal, ) return } @@ -304,6 +428,9 @@ internal fun InspectorObserveDetailScreen( body = body, onDismiss = { fullScreenSectionKey = null }, modifier = modifier.fillMaxSize(), + sectionKey = spec.key, + searchMatches = section.searchMatches, + currentMatchOrdinal = activeMatchOrdinal, ) return } @@ -326,8 +453,33 @@ internal fun InspectorObserveDetailScreen( ) InspectorDetailSearchField( query = query, - onQueryChange = { query = it }, - matchLabel = if (query.isBlank()) "" else "$totalHits match${if (totalHits == 1) "" else "es"}", + onQueryChange = { + query = it + currentMatchOrdinal = 0 + }, + matchLabel = + if (query.isBlank()) { + "" + } else if (searchOptions != null) { + "${if (networkMatches.isEmpty()) 0 else activeMatchOrdinal + 1}/$totalHits" + } else { + "$totalHits match${if (totalHits == 1) "" else "es"}" + }, + onPrevious = + if (searchOptions != null) { + { currentMatchOrdinal = previousInspectorMatchIndex(activeMatchOrdinal, networkMatches.size) } + } else { + null + }, + onNext = + if (searchOptions != null) { + { currentMatchOrdinal = nextInspectorMatchIndex(activeMatchOrdinal, networkMatches.size) } + } else { + null + }, + navigationEnabled = networkMatches.isNotEmpty(), + onOpenOptions = if (searchOptions != null) ({ searchOptionsVisible = true }) else null, + scopeLabel = searchOptions?.let { inspectorSearchScopeSummary(it, selectedKeys) }, modifier = Modifier.padding(top = 12.dp), placeholder = searchPlaceholder, ) @@ -338,11 +490,26 @@ internal fun InspectorObserveDetailScreen( InspectorDetailSectionCard( spec = spec, resolved = section, + currentMatchOrdinal = if (searchOptions != null) activeMatchOrdinal else null, onToggle = { openState[spec.key] = !section.expanded }, onExpandCodeFullScreen = { key -> fullScreenSectionKey = key }, ) } } + if (searchOptionsVisible && searchOptions != null) { + InspectorDetailSearchOptionsSheet( + options = searchOptions, + selectedSectionKeys = selectedKeys, + mode = searchMode, + onDismiss = { searchOptionsVisible = false }, + onApply = { newKeys, newMode -> + selectedSectionKeys = newKeys.toList() + searchModeName = newMode.name + currentMatchOrdinal = 0 + searchOptionsVisible = false + }, + ) + } } /** Everything [InspectorObserveDetailScreen] needs for one capture, built by the per-kind `*DetailContent` builders. */ @@ -357,6 +524,7 @@ internal data class ObserveDetailContent( * one value, and offering to search its "headers" would be describing a screen that isn't there. */ val searchPlaceholder: String = DEFAULT_DETAIL_SEARCH_PLACEHOLDER, + val searchOptions: InspectorDetailSearchOptions? = null, ) /** Matches [InspectorDetailSearchField]'s own default; named here so callers can opt out of it. */ 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 99a2019..f0f08ea 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 @@ -382,5 +382,6 @@ internal fun netDetailContent( // an operator debugging a transaction usually needs to compare both sides at a glance. initiallyOpenSectionKeys = setOf("req", "res"), footerActions = netFooterActions(transaction, colors, onMockAction, copyText), + searchOptions = NetworkDetailSearchOptions, ) } 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 0fce8aa..926e0b7 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 @@ -828,6 +828,7 @@ private fun ObserveDetailFromContent( footerActions = content.footerActions, onBack = onBack, searchPlaceholder = content.searchPlaceholder, + searchOptions = content.searchOptions, ) } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorSearchHighlight.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorSearchHighlight.kt new file mode 100644 index 0000000..58d7fb1 --- /dev/null +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorSearchHighlight.kt @@ -0,0 +1,51 @@ +/** + * @author Shakib + * @since 17/08/26 + */ +package io.devconsole.ui.compose + +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.buildAnnotatedString + +internal data class InspectorSearchHighlight( + val start: Int, + val endExclusive: Int, + val active: Boolean, +) + +internal fun List.highlightsFor( + itemId: String, + field: InspectorSearchField, + currentMatchOrdinal: Int?, +): List = + filter { match -> match.itemId == itemId && match.field == field } + .map { match -> + InspectorSearchHighlight( + start = match.start, + endExclusive = match.endExclusive, + active = match.ordinal == currentMatchOrdinal, + ) + } + +internal fun inspectorHighlightedText( + text: String, + highlights: List, + colors: DevConsoleColors, +): AnnotatedString = + buildAnnotatedString { + append(text) + highlights.forEach { highlight -> + val start = highlight.start.coerceIn(0, text.length) + val end = highlight.endExclusive.coerceIn(start, text.length) + if (start < end) { + addStyle( + SpanStyle( + background = if (highlight.active) colors.signal else colors.signalSoft, + ), + start, + end, + ) + } + } + } diff --git a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorDetailSearchTest.kt b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorDetailSearchTest.kt index 0e1a46d..cd63ba5 100644 --- a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorDetailSearchTest.kt +++ b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorDetailSearchTest.kt @@ -4,7 +4,9 @@ */ package io.devconsole.ui.compose +import androidx.compose.ui.graphics.Color import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull import org.junit.Assert.assertTrue import org.junit.Test @@ -73,4 +75,69 @@ class InspectorDetailSearchTest { ).isEmpty(), ) } + + @Test + fun `key value bodies produce stable row candidates`() { + val body = + InspectorDetailSectionBody.KeyValues( + listOf(InspectorKeyValue("Content-Type", "application/json")), + ) + + val candidates = searchInspectorBodyCandidates("reqh", body) + + assertEquals(listOf(InspectorSearchField.KEY, InspectorSearchField.VALUE), candidates.map { it.field }) + assertEquals(listOf("row:0", "row:0"), candidates.map { it.itemId }) + } + + @Test + fun `nested json candidates retain property path and ancestor paths`() { + val root = MinimalJsonParser("""{"user":{"id":1}}""").parseDocument() + val body = + InspectorDetailSectionBody.Formattable( + rawText = """{"user":{"id":1}}""", + rawLines = listOf(InspectorCodeLine(value = "{\"user\":{\"id\":1}}", valueColor = Color.White)), + formatted = FormattedBody.Json(root), + ) + + val candidates = searchInspectorBodyCandidates("res", body) + val idValue = candidates.firstOrNull { it.path == "$/0:user/0:id" && it.field == InspectorSearchField.VALUE } + + assertNotNull(idValue) + assertEquals(listOf("$", "$/0:user"), idValue!!.ancestorPaths) + assertEquals("1", idValue.text) + } + + @Test + fun `json key and value modes select different fields`() { + val root = MinimalJsonParser("""{"userId":1}""").parseDocument() + val body = + InspectorDetailSectionBody.Formattable( + rawText = """{"userId":1}""", + rawLines = listOf(InspectorCodeLine(value = "{\"userId\":1}", valueColor = Color.White)), + formatted = FormattedBody.Json(root), + ) + val candidates = searchInspectorBodyCandidates("res", body) + + assertEquals( + 1, + searchInspectorCandidates(candidates, "userid", setOf("res"), InspectorSearchMode.KEYS).size, + ) + assertEquals( + 1, + searchInspectorCandidates(candidates, "1", setOf("res"), InspectorSearchMode.VALUES).size, + ) + } + + @Test + fun `scope summary reflects multi section selection`() { + assertEquals( + "All request + response", + inspectorSearchScopeSummary(NetworkDetailSearchOptions, NetworkDetailSearchOptions.defaultSectionKeys), + ) + assertEquals( + "Response body", + inspectorSearchScopeSummary(NetworkDetailSearchOptions, setOf("res")), + ) + assertEquals("2 sections", inspectorSearchScopeSummary(NetworkDetailSearchOptions, setOf("reqh", "res"))) + } } From e69c74822b99b20342a47f68e8f873df02128f47 Mon Sep 17 00:00:00 2001 From: shakibuzzaman Date: Mon, 17 Aug 2026 23:47:47 +0600 Subject: [PATCH 10/20] chore: drop Maven Central, distribute via JitPack only, bump to 1.2.2 Library artifacts move to com.github.devconsole-android.DevConsole; the Gradle plugin stays on the Plugin Portal and now matches both groups. --- .github/ISSUE_TEMPLATE/bug_report.md | 2 +- .github/workflows/publish.yml | 31 ----- CHANGELOG.md | 16 +++ README.md | 78 +++++------ .../buildlogic/PublishingConventionPlugin.kt | 20 +-- build.gradle.kts | 4 +- docs/BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md | 17 ++- docs/GETTING_STARTED_COMPOSE.md | 29 +++-- docs/GETTING_STARTED_XML_JAVA.md | 9 +- docs/GETTING_STARTED_XML_KOTLIN.md | 29 +++-- docs/MAVEN_PUBLISHING.md | 122 ------------------ docs/MIGRATION.md | 32 +++++ docs/PUBLISHING.md | 83 ++++++++++++ docs/README.md | 2 +- docs/RELEASE_CHECKLIST.md | 7 +- docs/REMOTE_CONFIG.md | 4 +- gradle-plugin/build.gradle.kts | 2 +- .../gradle/DevConsoleVariantPolicyPlugin.kt | 15 ++- ...onsoleVariantPolicyPluginFunctionalTest.kt | 17 ++- samples/compose-app/build.gradle.kts | 2 +- samples/foundation-app/build.gradle.kts | 2 +- samples/views-java-app/build.gradle.kts | 2 +- sdk/storage-room/README.md | 2 +- 23 files changed, 259 insertions(+), 268 deletions(-) delete mode 100644 .github/workflows/publish.yml delete mode 100644 docs/MAVEN_PUBLISHING.md create mode 100644 docs/PUBLISHING.md diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 2e060c8..0f286c9 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -31,7 +31,7 @@ Ideally as a diff against one of the sample apps (`samples/compose-app`, `sample - DevConsole module(s) and version(s) affected (e.g. `devconsole:0.1.0-SNAPSHOT`, `devconsole-network-okhttp:0.1.0-SNAPSHOT`): -- Integration path: Maven Central coordinates, or built from source +- Integration path: JitPack coordinates, or built from source (`./gradlew publishToMavenLocal`)? - Android Gradle Plugin / Kotlin versions in the consuming project: - Device/emulator API level and manufacturer: diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml deleted file mode 100644 index 7b3a180..0000000 --- a/.github/workflows/publish.yml +++ /dev/null @@ -1,31 +0,0 @@ -name: Publish to Maven Central - -# Deliberately workflow_dispatch only: publishing to Central is effectively irreversible for a -# given coordinate + version, so it must be a conscious action, never a side effect of tagging a -# release or pushing to main. -on: - workflow_dispatch: - -permissions: - contents: read - -jobs: - publish: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v7 - - uses: actions/setup-java@v5 - with: - distribution: temurin - java-version: '17' - - uses: gradle/actions/setup-gradle@v6 - - run: ./gradlew testDebugUnitTest test --stacktrace - # Uploads a validated deployment to the Central Portal but does NOT release it — the final - # "Publish" click happens in the central.sonatype.com UI so a human reviews the deployment. - - run: ./gradlew publishToMavenCentral --no-configuration-cache --stacktrace - env: - ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.MAVEN_CENTRAL_USERNAME }} - ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.MAVEN_CENTRAL_PASSWORD }} - ORG_GRADLE_PROJECT_signingInMemoryKey: ${{ secrets.SIGNING_IN_MEMORY_KEY }} - ORG_GRADLE_PROJECT_signingInMemoryKeyId: ${{ secrets.SIGNING_IN_MEMORY_KEY_ID }} - ORG_GRADLE_PROJECT_signingInMemoryKeyPassword: ${{ secrets.SIGNING_IN_MEMORY_KEY_PASSWORD }} diff --git a/CHANGELOG.md b/CHANGELOG.md index b25d59b..0cf0e85 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,22 @@ before it can reach a release. (There was briefly a separate `sdk:plugin-api` mo third-party plugin framework; it was removed before ever shipping — see Removed, below — so it never joined this list.) +## 1.2.2 — 2026-08-17 + +### Changed + +- **JitPack is now the only distribution channel for the library artifacts.** Maven Central + publishing is removed: no `publishToMavenCentral`, no GPG signing, and no "Publish to Maven + Central" workflow. Consumers add `maven { url = uri("https://jitpack.io") }` to + `dependencyResolutionManagement` and switch the group from `io.github.devconsole-android` to + **`com.github.devconsole-android.DevConsole`**; artifact IDs and versions are unchanged. + Releasing is now just pushing a tag — JitPack builds the ref on first request. +- **The Gradle plugin still comes from the Gradle Plugin Portal** as `io.github.devconsole-android`, + because the `plugins { }` DSL cannot resolve a plugin marker from JitPack. Its variant-policy + check now recognises both the JitPack group and the old Central group, so an existing host that + still names `io.github.devconsole-android:devconsole` keeps its release-build protection; the + coordinate the plugin auto-wires is the JitPack one. + ## 1.2.1 — 2026-08-17 Three default changes, aimed at the same complaint: a fresh integration showed a `127.0.0.1` URL diff --git a/README.md b/README.md index ea386d5..3518c1a 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ **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) +[![JitPack](https://jitpack.io/v/devconsole-android/DevConsole.svg)](https://jitpack.io/#devconsole-android/DevConsole) [![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE) [![minSdk 23](https://img.shields.io/badge/minSdk-23-3DDC84?logo=android&logoColor=white)](#compatibility) [![CI](https://github.com/devconsole-android/DevConsole/actions/workflows/verify.yml/badge.svg)](https://github.com/devconsole-android/DevConsole/actions/workflows/verify.yml) @@ -33,21 +33,34 @@ links no server code, and the Gradle plugin fails the build if the real runtime ## Quick start -**1. Add the plugin and two dependencies** to your app's `build.gradle.kts`: +**1. Add the JitPack repository** to your `settings.gradle.kts` — DevConsole is distributed through +[JitPack](https://jitpack.io/#devconsole-android/DevConsole): + +```kotlin +dependencyResolutionManagement { + repositories { + google() + mavenCentral() + maven { url = uri("https://jitpack.io") } + } +} +``` + +**2. 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.2.1" + id("io.github.devconsole-android") version "1.2.2" } dependencies { - debugImplementation("io.github.devconsole-android:devconsole:1.2.1") - releaseImplementation("io.github.devconsole-android:devconsole-noop:1.2.1") + debugImplementation("com.github.devconsole-android.DevConsole:devconsole:1.2.2") + releaseImplementation("com.github.devconsole-android.DevConsole:devconsole-noop:1.2.2") } ``` -**2. Open the inspector on the device.** The SDK auto-initializes on debuggable builds, so this +**3. Open the inspector on the device.** The SDK auto-initializes on debuggable builds, so this works right away from any button in your debug UI: ```kotlin @@ -70,7 +83,7 @@ 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.** Tap **Start server** on the inspector's +**4. 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: @@ -316,8 +329,8 @@ Add the adapter — it is not part of the `devconsole` umbrella, so that Firebas classpath of an app that doesn't use it: ```kotlin -debugImplementation("io.github.devconsole-android:devconsole-remote-config-firebase:1.2.1") -releaseImplementation("io.github.devconsole-android:devconsole-remote-config-firebase-noop:1.2.1") +debugImplementation("com.github.devconsole-android.DevConsole:devconsole-remote-config-firebase:1.2.2") +releaseImplementation("com.github.devconsole-android.DevConsole:devconsole-remote-config-firebase-noop:1.2.2") ``` > These two artifacts first ship in `1.2.0`; earlier versions do not have them. @@ -367,8 +380,8 @@ anything sensitive in Remote Config. ## Artifacts -Group `io.github.devconsole-android`, one version for everything. There is deliberately no BOM, and -two coordinates cover a normal integration: +Group `com.github.devconsole-android.DevConsole`, one version for everything. There is deliberately +no BOM, and two coordinates cover a normal integration: | Coordinate | Scope | What it is | |---|---|---| @@ -387,41 +400,20 @@ Opt-in add-ons (each `-noop` twin is the matching `releaseImplementation`): | `devconsole-remote-config-firebase` | `devconsole-remote-config-firebase-noop` | Firebase Remote Config adapter (reflection-based; see [Remote Config](docs/REMOTE_CONFIG.md)) | 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. +You never name those. Every module publishes sources, javadoc, and a 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.2.1") - releaseImplementation("com.github.devconsole-android.DevConsole:devconsole-noop:1.2.1") -} -``` +### Versions and unreleased code -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: +All 34 library artifacts come from [JitPack](https://jitpack.io/#devconsole-android/DevConsole), +which builds a ref on demand — so the version is a git ref. A release tag works as the bare tag, as +in the tables above. Any branch works as `-SNAPSHOT`, with `/` written as `~`, so a +`feature/x` branch is `feature~x-SNAPSHOT` — that is how you try an unreleased fix before it ships. +JitPack support starts at **1.1.1**; earlier tags do not build there. Two things to know: -- **The Gradle plugin is not on JitPack.** Only the 34 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. +- **The Gradle plugin comes from the Gradle Plugin Portal, not JitPack**, because the `plugins { }` + DSL cannot resolve a plugin marker from JitPack. That is why the quick start adds JitPack for + dependencies only; `plugins { id("io.github.devconsole-android") version "…" }` resolves from the + Portal with no extra repository configuration. - **Snapshots move.** `-SNAPSHOT` follows the branch, so a build that worked can change under you. Pin a tag for anything you keep. 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 9e1212c..7b94242 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 @@ -13,15 +13,10 @@ import org.gradle.kotlin.dsl.configure /** * Applies to every publishable SDK module. Wires the Vanniktech Maven Publish plugin, which picks * the right publication shape (`KotlinJvm` vs `AndroidSingleVariantLibrary`) from the plugins the - * module already applies, attaches sources plus a Dokka-generated javadoc jar, and targets the - * Sonatype Central Portal. + * module already applies and attaches sources plus a Dokka-generated javadoc jar. * - * `publishToMavenLocal` works with no credentials. A real `publishToMavenCentral` additionally - * needs the Central Portal user token (`mavenCentralUsername`/`mavenCentralPassword`) and the - * signing key (`signingInMemoryKey`/`signingInMemoryKeyId`/`signingInMemoryKeyPassword`) — via - * `ORG_GRADLE_PROJECT_`-prefixed env vars or `~/.gradle/gradle.properties`, never committed. - * Signing no-ops locally when no key is configured. See docs/MAVEN_PUBLISHING.md for the full - * release runbook. + * Distribution is JitPack, which builds a ref on demand and runs `publishToMavenLocal` — so no + * remote repository, credentials, or signing is configured here. See docs/PUBLISHING.md. */ class PublishingConventionPlugin : Plugin { override fun apply(target: Project) { @@ -48,10 +43,6 @@ class PublishingConventionPlugin : Plugin { // AndroidLibraryConventionPlugin on Android ones), so the javadoc jar packs that // module's own generated HTML instead of shipping empty. configureBasedOnAppliedPlugins(JavadocJar.Dokka("dokkaGeneratePublicationHtml")) - publishToMavenCentral() - // 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}") @@ -79,12 +70,9 @@ 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.2.1" + const val SDK_VERSION = "1.2.2" const val PROJECT_URL = "https://github.com/devconsole-android/DevConsole" } } diff --git a/build.gradle.kts b/build.gradle.kts index 68ea6c0..1c8ed85 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -4,9 +4,7 @@ plugins { alias(libs.plugins.kotlin.jvm) apply false alias(libs.plugins.binary.compatibility.validator) alias(libs.plugins.dokka) - // Loaded (not applied) here so every sdk module shares one classloader copy of the plugin — - // its MavenCentralBuildService is a shared build service, and per-module loading puts the - // service class in sibling classloaders that cannot exchange it. + // Loaded (not applied) here so every sdk module shares one classloader copy of the plugin. alias(libs.plugins.vanniktech.maven.publish) apply false } diff --git a/docs/BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md b/docs/BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md index 4d02fa3..9491d00 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.2.1") // default; the plugin's own version + sdkVersion.set("1.2.2") // default; the plugin's own version } ``` @@ -48,7 +48,7 @@ patterns with `.*` (as `(?i).*release` above does) so they match regardless of w prefixes onto the build type. **A variant that already names a DevConsole dependency is left alone.** Auto-wiring only fills a -gap, so an explicit `debugImplementation("io.github.devconsole-android:devconsole:...")` — or a +gap, so an explicit `debugImplementation("com.github.devconsole-android.DevConsole:devconsole:...")` — or a `project(":sdk:full")` dependency inside this repository — wins over anything the plugin would have added. @@ -140,11 +140,10 @@ only `INTERNET` (the sample's own) and the auto-generated dynamic-receiver permi ## Publication status -The artifacts are `io.github.devconsole-android:devconsole` (the full runtime, from `:sdk:full`) and -`io.github.devconsole-android:devconsole-noop` (from `:sdk:noop`); there is no BOM and never was a -`-full` coordinate. The publishing pipeline is wired — every publishable module produces a POM with -license/developer/SCM metadata, a sources jar, a javadoc jar, and a signature when a key is provided -— but nothing is on Maven Central yet: the version is a pre-1.0 `-SNAPSHOT`, and a release still -needs a signing key and a Central account (see [RELEASE_CHECKLIST.md](RELEASE_CHECKLIST.md)). Within -this repository the samples depend on the SDK from source via `project(":sdk:full")` / +The artifacts are `com.github.devconsole-android.DevConsole:devconsole` (the full runtime, from `:sdk:full`) and +`com.github.devconsole-android.DevConsole:devconsole-noop` (from `:sdk:noop`); there is no BOM and +never was a `-full` coordinate. They are served by [JitPack](https://jitpack.io/#devconsole-android/DevConsole), +which builds a ref on demand — every publishable module produces a POM with license/developer/SCM +metadata, a sources jar, and a javadoc jar (see [PUBLISHING.md](PUBLISHING.md)). Within this +repository the samples depend on the SDK from source via `project(":sdk:full")` / `project(":sdk:noop")`. diff --git a/docs/GETTING_STARTED_COMPOSE.md b/docs/GETTING_STARTED_COMPOSE.md index e652d62..b968436 100644 --- a/docs/GETTING_STARTED_COMPOSE.md +++ b/docs/GETTING_STARTED_COMPOSE.md @@ -3,7 +3,20 @@ 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. +1. Add the JitPack repository to `settings.gradle.kts` — that is where the library artifacts live + (the Gradle plugin comes from the Gradle Plugin Portal and needs nothing extra). + +```kotlin +dependencyResolutionManagement { + repositories { + google() + mavenCentral() + maven { url = uri("https://jitpack.io") } + } +} +``` + +2. Apply the production-safety plugin and split the dependency by variant. ```kotlin plugins { @@ -11,9 +24,9 @@ plugins { } dependencies { - debugImplementation("io.github.devconsole-android:devconsole:") - releaseImplementation("io.github.devconsole-android:devconsole-noop:") - debugImplementation("io.github.devconsole-android:devconsole-ui-compose:") // optional, only for the launcher panel + debugImplementation("com.github.devconsole-android.DevConsole:devconsole:") + releaseImplementation("com.github.devconsole-android.DevConsole:devconsole-noop:") + debugImplementation("com.github.devconsole-android.DevConsole:devconsole-ui-compose:") // optional, only for the launcher panel } devConsole { @@ -31,7 +44,7 @@ release no-op counterpart and merges `DevConsoleActivity` into your manifest, so into your release build with no build-time warning. The Gradle plugin's variant protection does not cover this module today; it is your responsibility to scope it to `debugImplementation` yourself. -2. Add `INTERNET` to your own app's manifest. The SDK's manifests auto-merge +3. Add `INTERNET` to your own app's manifest. The SDK's manifests auto-merge `ACCESS_LOCAL_NETWORK`/`ACCESS_NETWORK_STATE`, but not `INTERNET` — without it, the embedded server fails with an opaque socket error instead of a clear permission message: @@ -39,7 +52,7 @@ cover this module today; it is your responsibility to scope it to `debugImplemen ``` -3. On a debuggable build you can skip explicit `initialize` entirely — the SDK auto-initializes, so +4. On a debuggable build you can skip explicit `initialize` entirely — the SDK auto-initializes, so state/timeline/capture are ready without any `Application.onCreate` boilerplate. The browser server itself is never auto-started; call `DevConsole.startBrowser()` yourself (step 4) and read the connect URL from the returned `StartResult.Started.access` (or the device's More screen — the @@ -56,7 +69,7 @@ DevConsole.initialize( ) ``` -4. Drop in the optional Compose launcher panel, or build your own with `DevConsole.state()`. +5. Drop in the optional Compose launcher panel, or build your own with `DevConsole.state()`. `DevConsoleState.Running` carries no payload, so capture the endpoint from `onStart`'s own `StartResult` and pass it to the panel if you want the running address displayed: @@ -86,7 +99,7 @@ setContent { } ``` -5. Tap Start. The panel shows the bound address, something like `DevConsole server is running at +6. 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. diff --git a/docs/GETTING_STARTED_XML_JAVA.md b/docs/GETTING_STARTED_XML_JAVA.md index a951bc7..a884021 100644 --- a/docs/GETTING_STARTED_XML_JAVA.md +++ b/docs/GETTING_STARTED_XML_JAVA.md @@ -4,10 +4,11 @@ DevConsole's public facade is a Kotlin `object`, but every method carries `@JvmS 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) - step 1). The two coordinates are `io.github.devconsole-android:devconsole` for debug and - `io.github.devconsole-android:devconsole-noop` for release; there is no BOM. +1. Add the JitPack repository, then apply the production-safety plugin and split the dependency by + variant (same `settings.gradle.kts` / `build.gradle.kts` shape as the Kotlin guide — see + [GETTING_STARTED_XML_KOTLIN.md](GETTING_STARTED_XML_KOTLIN.md) steps 1–2). + The two coordinates are `com.github.devconsole-android.DevConsole:devconsole` for debug and + `com.github.devconsole-android.DevConsole:devconsole-noop` for release; there is no BOM. 2. Add `INTERNET` to your own app's manifest. The SDK's manifests auto-merge `ACCESS_LOCAL_NETWORK`/`ACCESS_NETWORK_STATE`, but not `INTERNET` — without it, the embedded diff --git a/docs/GETTING_STARTED_XML_KOTLIN.md b/docs/GETTING_STARTED_XML_KOTLIN.md index 52d31b9..ba58465 100644 --- a/docs/GETTING_STARTED_XML_KOTLIN.md +++ b/docs/GETTING_STARTED_XML_KOTLIN.md @@ -3,7 +3,20 @@ 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. +1. Add the JitPack repository to `settings.gradle.kts` — that is where the library artifacts live + (the Gradle plugin comes from the Gradle Plugin Portal and needs nothing extra). + +```kotlin +dependencyResolutionManagement { + repositories { + google() + mavenCentral() + maven { url = uri("https://jitpack.io") } + } +} +``` + +2. Apply the production-safety plugin and split the dependency by variant. ```kotlin plugins { @@ -11,9 +24,9 @@ plugins { } dependencies { - debugImplementation("io.github.devconsole-android:devconsole:") - releaseImplementation("io.github.devconsole-android:devconsole-noop:") - debugImplementation("io.github.devconsole-android:devconsole-ui-views:") // optional, only for the launcher panel + debugImplementation("com.github.devconsole-android.DevConsole:devconsole:") + releaseImplementation("com.github.devconsole-android.DevConsole:devconsole-noop:") + debugImplementation("com.github.devconsole-android.DevConsole:devconsole-ui-views:") // optional, only for the launcher panel } devConsole { @@ -30,7 +43,7 @@ release no-op counterpart, so a plain `implementation` dependency ships the laun release build with no build-time warning. The Gradle plugin's variant protection does not cover this module today; it is your responsibility to scope it to `debugImplementation` yourself. -2. Add `INTERNET` to your own app's manifest. The SDK's manifests auto-merge +3. Add `INTERNET` to your own app's manifest. The SDK's manifests auto-merge `ACCESS_LOCAL_NETWORK`/`ACCESS_NETWORK_STATE`, but not `INTERNET` — without it, the embedded server fails with an opaque socket error instead of a clear permission message: @@ -38,7 +51,7 @@ module today; it is your responsibility to scope it to `debugImplementation` you ``` -3. Add the optional launcher view to a debug-only layout: +4. Add the optional launcher view to a debug-only layout: ```xml ``` -4. Initialize and bind the panel. On a debuggable build the SDK has already auto-initialized by +5. Initialize and bind the panel. On a debuggable build the SDK has already auto-initialized by this point, so `initialize` is only needed when you have configuration to pass (state providers, flags, open triggers). The panel starts out showing "not running" either way -- the browser server is never auto-started, so `onStart` below is what actually opens it. `DevConsoleState.Running` carries no @@ -78,7 +91,7 @@ panel.bind( ) ``` -5. Tap Start — the panel now shows the bound address (e.g. `DevConsole server is running at 192.168.0.15:8080`) +6. 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 with its `#code=` fragment) in a browser on the same machine (or `adb forward tcp:8080 tcp:8080` first if the device isn't local). diff --git a/docs/MAVEN_PUBLISHING.md b/docs/MAVEN_PUBLISHING.md deleted file mode 100644 index f9695af..0000000 --- a/docs/MAVEN_PUBLISHING.md +++ /dev/null @@ -1,122 +0,0 @@ -# Publishing to Maven Central - -All 34 modules under `sdk/` are wired with the -[Vanniktech Maven Publish plugin](https://github.com/vanniktech/gradle-maven-publish-plugin) -(via the `devconsole.publishing` convention), targeting the Sonatype **Central Portal** under the -group `io.github.devconsole-android`. Artifact IDs follow the mapping in -`PublishingConventionPlugin`: `:sdk:full` → `devconsole`, `:sdk:noop` → `devconsole-noop`, -everything else → `devconsole-`. Each publication carries sources, a Dokka-generated -javadoc jar, and a signed POM. - -`./gradlew publishToMavenLocal` verifies the whole pipeline locally with no credentials — signing -no-ops when no key is configured. A real publish needs the three things below. - -## 1. Verify the namespace (browser, one-time) - -`io.github.devconsole-android` is a GitHub-verified namespace tied to the `devconsole-android` -GitHub **organization** — no domain or DNS needed: - -1. Go to [central.sonatype.com](https://central.sonatype.com), sign in, and under **Namespaces** - add `io.github.devconsole-android`. The portal shows a short **verification key**. -2. Create a public repository named exactly that key under the org - (`github.com/devconsole-android/`), click **Verify Namespace**, then delete the - temporary repository. -3. Under your account icon → **View Account** → **Generate User Token**. The token is a - username/password pair — this is `mavenCentralUsername` / `mavenCentralPassword`. It is *not* - your Sonatype login password. - -## 2. Generate a signing key (terminal, one-time) - -Central requires every artifact to be GPG-signed. - -```bash -gpg --full-generate-key # RSA 4096, no expiration is fine for a personal signing key -gpg --list-secret-keys --keyid-format LONG # note the key ID (the part after rsa4096/) -gpg --keyserver keyserver.ubuntu.com --send-keys # publish so Central can verify it -gpg --export-secret-keys --armor > private-key.asc -``` - -- `signingInMemoryKey` = the full contents of `private-key.asc` (ASCII armor, newlines and all) -- `signingInMemoryKeyId` = the **last 8 hex characters** of the key ID -- `signingInMemoryKeyPassword` = the passphrase you set (blank if none) - -**Never commit `private-key.asc`** or paste it anywhere other than a GitHub Actions secret or -your local `~/.gradle/gradle.properties`. - -## 3. Bump the version and publish - -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.2.1`. - -**Locally:** - -```bash -ORG_GRADLE_PROJECT_mavenCentralUsername=... \ -ORG_GRADLE_PROJECT_mavenCentralPassword=... \ -ORG_GRADLE_PROJECT_signingInMemoryKey="$(cat private-key.asc)" \ -ORG_GRADLE_PROJECT_signingInMemoryKeyId=... \ -ORG_GRADLE_PROJECT_signingInMemoryKeyPassword=... \ -./gradlew publishToMavenCentral --no-configuration-cache -``` - -**Or via CI:** add the five values as repo secrets (Settings → Secrets and variables → Actions): -`MAVEN_CENTRAL_USERNAME`, `MAVEN_CENTRAL_PASSWORD`, `SIGNING_IN_MEMORY_KEY`, -`SIGNING_IN_MEMORY_KEY_ID`, `SIGNING_IN_MEMORY_KEY_PASSWORD` — then run the **Publish to Maven -Central** workflow from the Actions tab (`workflow_dispatch` only; it never fires automatically). - -Either way, `publishToMavenCentral` **uploads and validates** a deployment but does not release -it. Go to central.sonatype.com → **Deployments**, wait for validation to pass, review the -contents, and press **Publish**. That last click is the irreversible step: a released -coordinate + version can never be replaced or deleted. (To skip the manual click on future -releases, use `./gradlew publishAndReleaseToMavenCentral` instead.) - -Artifacts appear on `repo1.maven.org` within roughly 15–30 minutes of release, and on -search.maven.org within a few hours. - -## The Gradle plugin is published separately - -`io.github.devconsole-android` lives in the `gradle-plugin` included build and goes to the -**Gradle Plugin Portal**, not Central. One-time: create an account at -[plugins.gradle.org](https://plugins.gradle.org), generate an API key, and put -`gradle.publish.key` / `gradle.publish.secret` in `~/.gradle/gradle.properties`. Then: - -```bash -./gradlew -p gradle-plugin publishPlugins -``` - -First-time publication of a new plugin ID may sit in a short manual approval queue on the -Portal side. - -## Consuming a published release - -```kotlin -plugins { - id("io.github.devconsole-android") version "" -} -dependencies { - debugImplementation("io.github.devconsole-android:devconsole:") - releaseImplementation("io.github.devconsole-android:devconsole-noop:") -} -``` - -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 34 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/MIGRATION.md b/docs/MIGRATION.md index a549117..fa79959 100644 --- a/docs/MIGRATION.md +++ b/docs/MIGRATION.md @@ -9,6 +9,38 @@ Validate each debug and release variant with `verifyDevConsoleProtectedArtifacts` before rollout. +## Upgrading from 1.2.1 + +**The library artifacts moved from Maven Central to JitPack.** No API changed; the coordinates did. + +1. Add JitPack to `settings.gradle.kts`: + +```kotlin +dependencyResolutionManagement { + repositories { + google() + mavenCentral() + maven { url = uri("https://jitpack.io") } + } +} +``` + +2. Change the group on every DevConsole dependency from `io.github.devconsole-android` to + `com.github.devconsole-android.DevConsole`. Artifact IDs and versions are unchanged: + +```kotlin +debugImplementation("com.github.devconsole-android.DevConsole:devconsole:1.2.2") +releaseImplementation("com.github.devconsole-android.DevConsole:devconsole-noop:1.2.2") +``` + +If you rely on the plugin's `autoWireDependencies` (the default), step 2 is done for you — you only +need step 1, because the coordinate the plugin declares now resolves from JitPack. + +The Gradle plugin itself is unaffected: it still comes from the Gradle Plugin Portal as +`io.github.devconsole-android`, and its variant-policy check still recognises the old +`io.github.devconsole-android` library group, so a module you have not migrated yet keeps its +release-build protection. + ## Upgrading from 1.2.0 Three defaults changed. No API was removed and nothing has to be rewritten — but two of these change diff --git a/docs/PUBLISHING.md b/docs/PUBLISHING.md new file mode 100644 index 0000000..ea81229 --- /dev/null +++ b/docs/PUBLISHING.md @@ -0,0 +1,83 @@ +# Publishing + +DevConsole is distributed through **[JitPack](https://jitpack.io/#devconsole-android/DevConsole)**. +The Gradle plugin is the one exception: it lives in the `gradle-plugin` included build and goes to +the **Gradle Plugin Portal**, because the `plugins { }` DSL cannot resolve a plugin marker from +JitPack. + +## The 34 library modules → JitPack + +All 34 modules under `sdk/` are wired with the +[Vanniktech Maven Publish plugin](https://github.com/vanniktech/gradle-maven-publish-plugin) +(via the `devconsole.publishing` convention). Artifact IDs follow the mapping in +`PublishingConventionPlugin`: `:sdk:full` → `devconsole`, `:sdk:noop` → `devconsole-noop`, +everything else → `devconsole-`. Each publication carries sources, a Dokka-generated +javadoc jar, and a POM with license/developer/SCM metadata. + +**There is nothing to run to release.** JitPack builds a ref the first time someone asks for it and +serves the result under the group `com.github.devconsole-android.DevConsole`. Cutting a release is +just pushing a tag; the first consumer request triggers the build. + +`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. + +To verify the whole pipeline locally before tagging: + +```bash +./gradlew publishToMavenLocal +``` + +That produces exactly what JitPack produces. Check a real JitPack build at +`https://jitpack.io/api/builds/com.github.devconsole-android/DevConsole`. + +### Bumping the version + +`SDK_VERSION` in +`build-logic/convention-publishing/src/main/kotlin/io/devconsole/buildlogic/PublishingConventionPlugin.kt` +and `version` in `gradle-plugin/build.gradle.kts` are kept in step. JitPack derives the consumer- +facing version from the tag or branch rather than from `SDK_VERSION`, but the two should match so +`publishToMavenLocal` output and the tag agree. + +## The Gradle plugin → Gradle Plugin Portal + +One-time: create an account at [plugins.gradle.org](https://plugins.gradle.org), generate an API +key, and put `gradle.publish.key` / `gradle.publish.secret` in `~/.gradle/gradle.properties`. Then: + +```bash +./gradlew -p gradle-plugin publishPlugins +``` + +First-time publication of a new plugin ID may sit in a short manual approval queue on the Portal +side. + +## Consuming a release + +Add JitPack to the **settings** file, not the module: + +```kotlin +dependencyResolutionManagement { + repositories { + google() + mavenCentral() + maven { url = uri("https://jitpack.io") } + } +} +``` + +```kotlin +plugins { + id("io.github.devconsole-android") version "" +} +dependencies { + debugImplementation("com.github.devconsole-android.DevConsole:devconsole:") + releaseImplementation("com.github.devconsole-android.DevConsole:devconsole-noop:") +} +``` + +A release tag works as the bare tag. 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. + +See [BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md](BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md) for what the +plugin enforces about the debug/release split. diff --git a/docs/README.md b/docs/README.md index 94c7a7d..a3dc393 100644 --- a/docs/README.md +++ b/docs/README.md @@ -55,4 +55,4 @@ read one page here, make it the threat model, especially before you put the dash **Contributing / releasing** - [Migration guide](MIGRATION.md) - [Release checklist](RELEASE_CHECKLIST.md) -- [Publishing to Maven Central](MAVEN_PUBLISHING.md) +- [Publishing](PUBLISHING.md) diff --git a/docs/RELEASE_CHECKLIST.md b/docs/RELEASE_CHECKLIST.md index 36c94c6..048f775 100644 --- a/docs/RELEASE_CHECKLIST.md +++ b/docs/RELEASE_CHECKLIST.md @@ -3,8 +3,9 @@ - [ ] Version, changelog, and public API change assessment are complete. - [ ] Unit, server-contract, sample debug/release, and protected-artifact checks pass. - [ ] Security suites cover redaction, CSRF/origin, session-code exchange throttling, and authorization. -- [ ] Dependency lock/SBOM and provenance are attached to the signed release artifacts. +- [ ] Dependency lock/SBOM and provenance are attached to the release artifacts. - [ ] No critical or high unresolved vulnerability remains. - [ ] Documentation and samples are validated from a clean checkout. -- [ ] Maven Central publish (see [MAVEN_PUBLISHING.md](MAVEN_PUBLISHING.md)), consumer smoke test, - signed tag, and release notes are complete. +- [ ] `./gradlew publishToMavenLocal` passes from a clean checkout (this is what JitPack runs). +- [ ] Signed tag pushed, JitPack build green for that tag (see [PUBLISHING.md](PUBLISHING.md)), + consumer smoke test and release notes are complete. diff --git a/docs/REMOTE_CONFIG.md b/docs/REMOTE_CONFIG.md index 72e3fe2..b0a1a7e 100644 --- a/docs/REMOTE_CONFIG.md +++ b/docs/REMOTE_CONFIG.md @@ -25,8 +25,8 @@ Cloud Messaging. Add the adapter coordinate yourself; it is deliberately not re- `devconsole` umbrella. ```kotlin -debugImplementation("io.github.devconsole-android:devconsole-remote-config-firebase:") -releaseImplementation("io.github.devconsole-android:devconsole-remote-config-firebase-noop:") +debugImplementation("com.github.devconsole-android.DevConsole:devconsole-remote-config-firebase:") +releaseImplementation("com.github.devconsole-android.DevConsole:devconsole-remote-config-firebase-noop:") ``` A provider constructed later — through DI, or after a first fetch completes — can register itself: diff --git a/gradle-plugin/build.gradle.kts b/gradle-plugin/build.gradle.kts index 4442241..733241b 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.2.1" +version = "1.2.2" // 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 64be54e..b9a0b22 100644 --- a/gradle-plugin/src/main/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPlugin.kt +++ b/gradle-plugin/src/main/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPlugin.kt @@ -151,7 +151,7 @@ abstract class VerifyDevConsoleProtectedArtifactsTask : DefaultTask() { /** Enabled runtime/adapters that must never reach a protected variant. */ val FULL_RUNTIME_COORDINATE = Regex( - "^io\\.github\\.devconsole-android:" + + "^(?:com\\.github\\.devconsole-android\\.DevConsole|io\\.github\\.devconsole-android):" + "(?:devconsole|devconsole-network-okhttp|devconsole-mocks-okhttp|" + "devconsole-socket-okhttp|devconsole-socket-paho|devconsole-push-firebase|" + "devconsole-remote-config-firebase):.+", @@ -397,8 +397,13 @@ abstract class VerifyDevConsolePackagedArtifactTask : DefaultTask() { } } -private const val DEFAULT_SDK_VERSION = "1.2.1" -private const val DEVCONSOLE_GROUP = "io.github.devconsole-android" +private const val DEFAULT_SDK_VERSION = "1.2.2" + +/** JitPack's group for this repo — what auto-wiring declares. */ +private const val DEVCONSOLE_GROUP = "com.github.devconsole-android.DevConsole" + +/** Recognised on a host's classpath: the JitPack group, plus the Maven Central group used up to 1.2.1. */ +private val DEVCONSOLE_GROUPS = setOf(DEVCONSOLE_GROUP, "io.github.devconsole-android") /** * Core runtime coordinate names whose presence means a host already declared the DevConsole runtime, @@ -661,7 +666,7 @@ class DevConsoleVariantPolicyPlugin : Plugin { // Only the core runtime coordinates count as "already declared" for the purpose of skipping // core auto-wire. Declaring only an add-on (devconsole-ui-compose / devconsole-ui-views / // devconsole-network-ktor) in the same group must NOT suppress wiring the core runtime. - else -> group == DEVCONSOLE_GROUP && name in CORE_RUNTIME_COORDINATE_NAMES + else -> group in DEVCONSOLE_GROUPS && name in CORE_RUNTIME_COORDINATE_NAMES } private fun Project.registerProtectedVerifier( @@ -682,7 +687,7 @@ class DevConsoleVariantPolicyPlugin : Plugin { val path = dep.projectPathCompat() if (path in protectedPaths) "$variant -> $path" else null } - dep is org.gradle.api.artifacts.ExternalModuleDependency && dep.group == DEVCONSOLE_GROUP && dep.name == "devconsole" -> "$variant -> ${dep.group}:${dep.name}" + dep is org.gradle.api.artifacts.ExternalModuleDependency && dep.group in DEVCONSOLE_GROUPS && dep.name == "devconsole" -> "$variant -> ${dep.group}:${dep.name}" else -> null } } 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 328f8d9..64b840b 100644 --- a/gradle-plugin/src/test/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPluginFunctionalTest.kt +++ b/gradle-plugin/src/test/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPluginFunctionalTest.kt @@ -40,7 +40,9 @@ class DevConsoleVariantPolicyPluginFunctionalTest { repositories { google(); mavenCentral(); gradlePluginPortal() } } dependencyResolutionManagement { - repositories { google(); mavenCentral() } + // jitpack.io serves the auto-wired devconsole coordinates, so any fixture that + // resolves a runtime classpath needs it -- same as a real consumer. + repositories { google(); mavenCentral(); maven { url = uri("https://jitpack.io") } } } rootProject.name = "fixture" """.trimIndent(), @@ -683,7 +685,7 @@ class DevConsoleVariantPolicyPluginFunctionalTest { assertTrue(result.output, result.output.contains("BUILD SUCCESSFUL")) assertTrue(result.output, result.output.contains(":stub-full")) - assertTrue(result.output, !result.output.contains("io.github.devconsole-android:devconsole")) + assertTrue(result.output, !result.output.contains("com.github.devconsole-android.DevConsole:devconsole")) } @Test @@ -837,12 +839,12 @@ class DevConsoleVariantPolicyPluginFunctionalTest { ) // release is PROTECTED by default, so auto-wire adds the noop core coordinate. The published - // coordinate is 1.2.1 -- the DEFAULT_SDK_VERSION must not point at a 1.2.1-SNAPSHOT that was + // coordinate is 1.2.2 -- the DEFAULT_SDK_VERSION must not point at a 1.2.2-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.2.1")) - assertTrue(result.output, !result.output.contains("1.2.1-SNAPSHOT")) + assertTrue(result.output, result.output.contains("com.github.devconsole-android.DevConsole:devconsole-noop:1.2.2")) + assertTrue(result.output, !result.output.contains("1.2.2-SNAPSHOT")) } @Test @@ -873,8 +875,9 @@ class DevConsoleVariantPolicyPluginFunctionalTest { applicationId = "io.devconsole.fixture" versionCode = 1 """.trimIndent(), - // An add-on coordinate in the DevConsole group but NOT the core runtime. It must not be + // An add-on coordinate in a DevConsole group but NOT the core runtime. It must not be // mistaken for "the core runtime is already declared" and suppress core auto-wire. + // Deliberately the pre-JitPack group, which also covers that it is still recognised. extraBuildScript = """ dependencies { @@ -887,7 +890,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.2.1")) + assertTrue(result.output, result.output.contains("com.github.devconsole-android.DevConsole:devconsole:1.2.2")) assertTrue(result.output, result.output.contains("io.github.devconsole-android:devconsole-ui-compose")) } } diff --git a/samples/compose-app/build.gradle.kts b/samples/compose-app/build.gradle.kts index 20c858b..599ba2a 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.2.1-SNAPSHOT" + versionName = "1.2.2-SNAPSHOT" } } diff --git a/samples/foundation-app/build.gradle.kts b/samples/foundation-app/build.gradle.kts index d25e673..b450fa0 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.2.1-SNAPSHOT" + versionName = "1.2.2-SNAPSHOT" } } diff --git a/samples/views-java-app/build.gradle.kts b/samples/views-java-app/build.gradle.kts index d6ca3fe..b4e93a8 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.2.1-SNAPSHOT" + versionName = "1.2.2-SNAPSHOT" } } diff --git a/sdk/storage-room/README.md b/sdk/storage-room/README.md index c2dcd9f..8ee82c9 100644 --- a/sdk/storage-room/README.md +++ b/sdk/storage-room/README.md @@ -6,7 +6,7 @@ 1. Add dependency to your build file: ```kotlin -debugImplementation("io.github.devconsole-android:devconsole-storage-room:") +debugImplementation("com.github.devconsole-android.DevConsole:devconsole-storage-room:") ``` `sdk:full` wires this module in automatically for durable timeline storage — no additional From 26dd74b9337f572b863a074b3d81e56373557b9c Mon Sep 17 00:00:00 2001 From: shakibuzzaman Date: Mon, 17 Aug 2026 23:48:14 +0600 Subject: [PATCH 11/20] feat: scope, step through, and expand matches in capture detail search Adds a search-options sheet (sections, names/values), a hit counter with stepping, and a full-screen body viewer; drops the one-off update.py script. --- README.md | 26 +- .../resources/devconsole-web/dashboard.css | 2 +- .../ui/compose/InspectorCodeBlock.kt | 15 +- .../compose/InspectorCodeFullScreenOverlay.kt | 149 ++++++++-- .../ui/compose/InspectorDetailSearch.kt | 113 +++++-- .../InspectorDetailSearchOptionsSheet.kt | 278 +++++++++++++----- .../ui/compose/InspectorFormattableBody.kt | 73 +++-- .../devconsole/ui/compose/InspectorGlyphs.kt | 8 +- .../ui/compose/InspectorKeyValueList.kt | 8 +- .../ui/compose/InspectorListComponents.kt | 69 ++++- .../ui/compose/InspectorMoreScreen.kt | 6 +- .../ui/compose/InspectorObserveDetail.kt | 98 +++++- .../ui/compose/InspectorObserveFrameDetail.kt | 6 +- .../ui/compose/InspectorObserveLogDetail.kt | 4 +- .../ui/compose/InspectorObserveNetDetail.kt | 14 +- .../ui/compose/InspectorObservePushDetail.kt | 6 +- .../ui/compose/InspectorSearchHighlight.kt | 32 +- .../ui/compose/InspectorDetailSearchTest.kt | 109 ++++++- update.py | 14 - 19 files changed, 806 insertions(+), 224 deletions(-) delete mode 100644 update.py diff --git a/README.md b/README.md index 3518c1a..ee044d2 100644 --- a/README.md +++ b/README.md @@ -118,6 +118,7 @@ gets you nothing. |---|---| | **In-app inspector** | `DevConsole.open(context)` shows every inspector below as an on-device screen (included with `devconsole`), plus a QR code for pairing the browser. Opens by shake (adjustable intensity) or draggable floating button via the opt-in `DevConsoleConfig.openTriggers` flags. Its More screen can also start and stop the dashboard server. | | **Network inspector** | Every HTTP call with headers, bodies, and a DNS/TCP/TLS/send/wait/receive timing bar. Live-tails as traffic happens. | +| **Find in a capture** | Every detail screen has a find field that filters and highlights as you type. Network captures go further: step through hits with a counter and arrows, scope the search to the sections you choose, and match field names, values, or both. Any body can be expanded full-screen to read or copy. | | **WebSocket & MQTT inspectors** | Connection lifecycles and every frame, inbound and outbound. MQTT rides the Eclipse Paho adapter. | | **Mock rules** | Serve canned responses for matching requests (OkHttp), toggled from the dashboard, with deterministic priority matching. Wired by `installDevConsole` and editable out of the box. | | **Request composer** | Make the device issue ad-hoc HTTP requests from the dashboard. Off by default, host-allowlist confinable. | @@ -200,7 +201,7 @@ DevConsoleConfig.default().withBrowserConfig(BrowserConfig(binding = BrowserBind // Require the network — fails loudly instead of falling back, and surfaces the // ACCESS_LOCAL_NETWORK prompt on API 37+ devices: DevConsoleConfig.default().withBrowserConfig( - BrowserConfig(binding = BrowserBinding.LOOPBACK), + BrowserConfig(binding = BrowserBinding.LAN), ) ``` @@ -323,6 +324,29 @@ 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

+### Search inside a capture + +Every detail screen — a call, a frame, a push, a log line, a crash — has a find field at the top. +Type, and it filters the sections down to what matched and highlights the hits in place, with a +count so you know whether the thing you're looking for is here at all. + +On **network captures** it goes further, because that's where you usually arrive with a specific +token in hand. Arrows step you through the hits one at a time with a running `3/17` counter, the +same motion as find-in-page, so you can hold an ID in your head and walk every place it appears. + +Those captures also let you aim the search. Tap the **Search in** chip and you can pick which +sections to look at — it starts on the request and response bodies, since that's where most real +questions live — and choose whether to match field names, values, or both. + +One thing worth knowing, because it's the kind of thing that costs an afternoon: matching *names* +only works where the body has names to match. JSON has them. A raw or XML body doesn't — it's +text all the way down — so a names-only search skips it entirely and quietly reports nothing. +That's why the default matches both, and why the sheet spells out what each mode will and won't +find. + +Body too dense to read in a card? Expand it full-screen. You get the whole viewport, a +Formatted/Raw switch, a line count, and a copy button that puts the body on the clipboard. + ### Set up Remote Config Add the adapter — it is not part of the `devconsole` umbrella, so that Firebase never lands on the 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 8a416e8..d0f8af7 100644 --- a/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css +++ b/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css @@ -1430,7 +1430,7 @@ kbd { Trims are CSS-first: the underlying control/state is untouched, only its rail/toolbar/detail affordance is hidden in Simple mode, so switching back to Advanced never loses anything. ============================================================ */ -body.mode-simple .metrics-strip { display: none; } +body.mode-simple .metric-strip { display: none; } body.mode-simple #networkMethodGroup, body.mode-simple #networkHostDrop, body.mode-simple #networkToggleHost, diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeBlock.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeBlock.kt index fd7f71e..af3a3be 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeBlock.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeBlock.kt @@ -73,14 +73,13 @@ internal fun InspectorCodeBlock( ) { val colors = DevConsoleTheme.colors val sectionMatches = searchMatches.filter { it.sectionKey == sectionKey || sectionKey.isEmpty() } + val highlightIndex = + remember(sectionMatches, currentMatchOrdinal) { + indexInspectorSearchHighlights(sectionMatches, currentMatchOrdinal) + } val listState = rememberLazyListState() val bringIntoViewRequester = remember { BringIntoViewRequester() } - val activeLineIndex = - sectionMatches - .firstOrNull { it.ordinal == currentMatchOrdinal } - ?.itemId - ?.substringAfter("line:", "") - ?.toIntOrNull() + val activeLineIndex = activeInspectorLineIndex(sectionMatches, currentMatchOrdinal) LaunchedEffect(activeLineIndex, currentMatchOrdinal) { activeLineIndex?.let { index -> if (lines.isNotEmpty()) listState.animateScrollToItem(index.coerceIn(0, lines.lastIndex)) @@ -113,8 +112,8 @@ internal fun InspectorCodeBlock( val itemId = "line:$index" CodeLineRow( line = line, - keyHighlights = sectionMatches.highlightsFor(itemId, InspectorSearchField.KEY, currentMatchOrdinal), - valueHighlights = sectionMatches.highlightsFor(itemId, InspectorSearchField.VALUE, currentMatchOrdinal), + keyHighlights = highlightIndex.highlightsFor(itemId, InspectorSearchField.KEY), + valueHighlights = highlightIndex.highlightsFor(itemId, InspectorSearchField.VALUE), ) } } 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 7f29334..82ee685 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 @@ -11,12 +11,14 @@ import androidx.compose.animation.core.Animatable import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListScope import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.rememberScrollState import androidx.compose.material3.Surface import androidx.compose.material3.Text @@ -32,7 +34,9 @@ import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.em import androidx.compose.ui.unit.sp +import java.util.Locale /** * Full-screen overlay for a single [InspectorCodeBlock]'s content: @@ -43,6 +47,7 @@ import androidx.compose.ui.unit.sp * Convenience overload of the [content]-taking overload below, for the common case of one flat * [InspectorCodeLine] list; [InspectorFormattableBody] uses the general one to add a JSON tree. */ +@Suppress("LongParameterList") // Search/highlight inputs plus the section's own copy action. @Composable internal fun InspectorCodeFullScreenOverlay( title: String, @@ -52,22 +57,49 @@ internal fun InspectorCodeFullScreenOverlay( sectionKey: String = "", searchMatches: List = emptyList(), currentMatchOrdinal: Int? = null, + onCopy: (() -> Unit)? = null, + copyContentDescription: String = "Copy $title", ) { val sectionMatches = searchMatches.filter { it.sectionKey == sectionKey || sectionKey.isEmpty() } - InspectorCodeFullScreenOverlay(title = title, onDismiss = onDismiss, modifier = modifier) { + val highlightIndex = remember(sectionMatches, currentMatchOrdinal) { + indexInspectorSearchHighlights(sectionMatches, currentMatchOrdinal) + } + InspectorCodeFullScreenOverlay( + title = title, + onDismiss = onDismiss, + modifier = modifier, + targetIndex = activeInspectorLineIndex(sectionMatches, currentMatchOrdinal), + onCopy = onCopy, + copyContentDescription = copyContentDescription, + meta = inspectorLineCountMeta(lines.size), + ) { itemsIndexed(lines, key = { index, _ -> index }) { index, line -> val itemId = "line:$index" CodeLineRow( line = line, fontSize = 14.sp, lineHeight = 23.8.sp, - keyHighlights = sectionMatches.highlightsFor(itemId, InspectorSearchField.KEY, currentMatchOrdinal), - valueHighlights = sectionMatches.highlightsFor(itemId, InspectorSearchField.VALUE, currentMatchOrdinal), + keyHighlights = highlightIndex.highlightsFor(itemId, InspectorSearchField.KEY), + valueHighlights = highlightIndex.highlightsFor(itemId, InspectorSearchField.VALUE), ) } } } +/** "1 line" / "N lines" -- the same count the collapsed section card shows in its meta slot. */ +internal fun inspectorLineCountMeta(count: Int): String? = + if (count <= 0) null else "$count line${if (count == 1) "" else "s"}" + +internal fun activeInspectorLineIndex( + matches: List, + currentMatchOrdinal: Int?, +): Int? = + matches + .firstOrNull { it.ordinal == currentMatchOrdinal } + ?.itemId + ?.substringAfter("line:", "") + ?.toIntOrNull() + /** * General form: header + a both-axes-scrollable [LazyColumn] body. Unlike the inline * [InspectorCodeBlock], this owns the whole remaining viewport (via `weight(1f)` in a `fillMaxSize` @@ -75,12 +107,18 @@ internal fun InspectorCodeFullScreenOverlay( * thousands-of-lines body only composes the rows actually scrolled into view. [headerTrailing] is an * optional control (the Raw/Formatted toggle) rendered at the header's trailing edge. */ +@Suppress("LongParameterList") // Header slots (trailing control, copy action) plus scroll target. @Composable internal fun InspectorCodeFullScreenOverlay( title: String, onDismiss: () -> Unit, modifier: Modifier = Modifier, headerTrailing: (@Composable () -> Unit)? = null, + targetIndex: Int? = null, + onCopy: (() -> Unit)? = null, + copyContentDescription: String = "Copy $title", + /** Right-aligned readout under the title -- what is on screen, e.g. "6 lines". */ + meta: String? = null, content: LazyListScope.() -> Unit, ) { BackHandler(onBack = onDismiss) @@ -90,7 +128,11 @@ internal fun InspectorCodeFullScreenOverlay( // 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) } + val listState = rememberLazyListState(initialFirstVisibleItemIndex = targetIndex ?: 0) LaunchedEffect(Unit) { entrance.animateTo(1f, entranceSpec) } + LaunchedEffect(targetIndex) { + targetIndex?.let { index -> listState.scrollToItem(index.coerceAtLeast(0)) } + } Surface( modifier = modifier.fillMaxSize().graphicsLayer { @@ -103,8 +145,9 @@ internal fun InspectorCodeFullScreenOverlay( color = colors.ground, ) { Column(modifier = Modifier.fillMaxSize()) { - CodeFullScreenHeader(title, onDismiss, headerTrailing) + CodeFullScreenHeader(title, onDismiss, onCopy, copyContentDescription, meta, headerTrailing) LazyColumn( + state = listState, modifier = Modifier .weight(1f) @@ -117,14 +160,23 @@ internal fun InspectorCodeFullScreenOverlay( } } +/** + * Two bands, mirroring [InspectorDetailHeader]'s own structure so the overlay reads as a sibling of + * the detail screen rather than a bolted-on modal: the identity row (back, section name, copy) owns + * the full width so a long name is never truncated by a control sitting beside it, and the controls + * row underneath carries the view switch against a right-aligned mono readout of what is on screen. + */ @Composable private fun CodeFullScreenHeader( title: String, onDismiss: () -> Unit, + onCopy: (() -> Unit)?, + copyContentDescription: String, + meta: String?, trailing: (@Composable () -> Unit)? = null, ) { val colors = DevConsoleTheme.colors - Row( + Column( modifier = Modifier .fillMaxWidth() @@ -134,33 +186,70 @@ private fun CodeFullScreenHeader( val strokeWidth = 1.dp.toPx() val y = size.height - strokeWidth / 2 drawLine(colors.line, Offset(0f, y), Offset(size.width, y), strokeWidth) - }.padding(vertical = 8.dp, horizontal = 8.dp), - verticalAlignment = Alignment.CenterVertically, + }, ) { - InspectorRoundIconButton( - contentDescription = "Close full screen", - onClick = onDismiss, - icon = { - InspectorGlyphIcon( - InspectorGlyph.ChevronDown, - contentDescription = null, - tint = colors.ink, - size = 20.dp, - rotationDegrees = 90f, + Row( + modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + InspectorRoundIconButton( + contentDescription = "Close full screen", + onClick = onDismiss, + icon = { + InspectorGlyphIcon( + InspectorGlyph.ChevronDown, + contentDescription = null, + tint = colors.ink, + size = 20.dp, + rotationDegrees = 90f, + ) + }, + ) + // UI stack, not mono: this is the section's name, not captured data. Mono here would + // claim "Response body" came off the wire. + Text( + title, + modifier = Modifier.weight(1f).padding(start = 4.dp), + color = colors.ink, + fontWeight = FontWeight.SemiBold, + fontSize = 16.sp, + letterSpacing = (-0.01).em, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + if (onCopy != null) { + InspectorRoundIconButton( + contentDescription = copyContentDescription, + onClick = onCopy, + size = 44.dp, + icon = { + InspectorGlyphIcon( + InspectorGlyph.Copy, + contentDescription = null, + tint = colors.muted, + size = 17.dp, + ) + }, ) - }, - ) - Text( - title, - modifier = Modifier.weight(1f).padding(start = 4.dp), - color = colors.ink, - fontFamily = FontFamily.Monospace, - fontWeight = FontWeight.SemiBold, - fontSize = 14.sp, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - trailing?.invoke() + } + } + if (trailing != null || meta != null) { + Row( + modifier = Modifier.fillMaxWidth().padding(start = 16.dp, end = 16.dp, bottom = 12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + trailing?.invoke() + Spacer(Modifier.weight(1f)) + if (meta != null) { + Text( + meta.uppercase(Locale.US), + color = colors.text3, + fontFamily = FontFamily.Monospace, + style = DevConsoleType.groupLabel, + ) + } + } + } } } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearch.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearch.kt index 674c5ef..674e084 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearch.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearch.kt @@ -10,13 +10,21 @@ internal enum class InspectorSearchField { VALUE, } +/** Which side of a formattable body's Raw/Formatted toggle is currently rendered. */ +internal enum class InspectorBodySearchRepresentation { + RAW, + FORMATTED, +} + /** Search fields enabled by the Network detail search options sheet. */ internal enum class InspectorSearchMode( val label: String, + /** What this mode will and won't match, shown under the chips in the search options sheet. */ + val hint: String, ) { - KEYS("Keys"), - VALUES("Values"), - KEYS_AND_VALUES("Keys + values"), + KEYS("Keys", "Header names and JSON field names. Raw and XML bodies have none, so they never match."), + VALUES("Values", "Header values, JSON values, and raw or XML body text."), + KEYS_AND_VALUES("Keys + values", "Names and values together."), } /** One searchable piece of rendered detail content. */ @@ -46,36 +54,86 @@ internal data class InspectorDetailSearchSection( val label: String, ) +/** Callback-free section input suitable for use as a remembered candidate-cache key. */ +internal data class InspectorSearchSectionBody( + val sectionKey: String, + val body: InspectorDetailSectionBody, +) + internal data class InspectorDetailSearchOptions( val sections: List, val defaultSectionKeys: Set, - val defaultMode: InspectorSearchMode = InspectorSearchMode.KEYS, + /** + * Keys-only would silently miss raw and XML bodies, which carry no names to match, so a first + * search finds everything the query appears in and the sheet narrows from there. + */ + val defaultMode: InspectorSearchMode = InspectorSearchMode.KEYS_AND_VALUES, ) +/** + * The four detail slots every captured-exchange kind lays out, in render order. [key] is the stable + * id an [InspectorDetailSectionSpec] carries; the labels here are the network wording, and other + * kinds reuse the same slots under their own names (a socket frame's [PRIMARY_BODY] is "Payload"). + */ +internal enum class InspectorExchangeSection( + val key: String, + val networkLabel: String, +) { + PRIMARY_HEADERS("reqh", "Request headers"), + PRIMARY_BODY("req", "Request body"), + SECONDARY_HEADERS("resh", "Response headers"), + SECONDARY_BODY("res", "Response body"), + ; + + internal companion object { + /** The slots a first search covers: bodies carry the payload, headers are the noisy half. */ + val defaultSearchScope = setOf(PRIMARY_BODY, SECONDARY_BODY) + + fun keysOf(sections: Set): Set = sections.mapTo(mutableSetOf()) { it.key } + } +} + internal val NetworkDetailSearchOptions = InspectorDetailSearchOptions( sections = - listOf( - InspectorDetailSearchSection("reqh", "Request headers"), - InspectorDetailSearchSection("req", "Request body"), - InspectorDetailSearchSection("resh", "Response headers"), - InspectorDetailSearchSection("res", "Response body"), - ), - defaultSectionKeys = setOf("reqh", "req", "resh", "res"), + InspectorExchangeSection.entries.map { section -> + InspectorDetailSearchSection(section.key, section.networkLabel) + }, + defaultSectionKeys = InspectorExchangeSection.keysOf(InspectorExchangeSection.defaultSearchScope), ) +internal fun inspectorSearchSectionBodies( + sections: List, + searchableSectionKeys: Set, +): List = + sections.mapNotNull { spec -> + if (spec.key in searchableSectionKeys) InspectorSearchSectionBody(spec.key, spec.body) else null + } + internal fun searchInspectorSections( sections: List, query: String, selectedSectionKeys: Set, mode: InspectorSearchMode, -): List = - searchInspectorCandidates( - candidates = sections.flatMap { spec -> searchInspectorBodyCandidates(spec.key, spec.body) }, + representationForSection: (String) -> InspectorBodySearchRepresentation = { + InspectorBodySearchRepresentation.FORMATTED + }, +): List { + if (query.isBlank()) return emptyList() + return searchInspectorCandidates( + candidates = + sections.flatMap { spec -> + searchInspectorBodyCandidates( + sectionKey = spec.key, + body = spec.body, + representation = representationForSection(spec.key), + ) + }, query = query, selectedSectionKeys = selectedSectionKeys, mode = mode, ) +} internal fun inspectorSearchScopeSummary( options: InspectorDetailSearchOptions, @@ -83,9 +141,9 @@ internal fun inspectorSearchScopeSummary( ): String { val selected = options.sections.filter { it.key in selectedSectionKeys } return when { - selected.size == options.sections.size -> "All request + response" + selected.size == options.sections.size -> "All sections" selected.size == 1 -> selected.single().label - selected.isEmpty() -> "No sections" + selected.isEmpty() -> "Nothing selected" else -> "${selected.size} sections" } } @@ -162,6 +220,7 @@ internal fun previousInspectorMatchIndex( internal fun searchInspectorBodyCandidates( sectionKey: String, body: InspectorDetailSectionBody, + representation: InspectorBodySearchRepresentation = InspectorBodySearchRepresentation.FORMATTED, ): List = when (body) { is InspectorDetailSectionBody.KeyValues -> @@ -183,16 +242,18 @@ internal fun searchInspectorBodyCandidates( } } is InspectorDetailSectionBody.Formattable -> - when (val formatted = body.formatted) { - is FormattedBody.Json -> jsonSearchCandidates(sectionKey, formatted.root) - is FormattedBody.Xml -> - formatted.text.lines().mapIndexed { index, line -> - InspectorSearchCandidate(sectionKey, "line:$index", InspectorSearchField.VALUE, line) - } - null -> - body.rawLines.mapIndexed { index, line -> - InspectorSearchCandidate(sectionKey, "line:$index", InspectorSearchField.VALUE, line.value) - } + if (representation == InspectorBodySearchRepresentation.RAW || body.formatted == null) { + body.rawLines.mapIndexed { index, line -> + InspectorSearchCandidate(sectionKey, "line:$index", InspectorSearchField.VALUE, line.value) + } + } else { + when (val formatted = requireNotNull(body.formatted)) { + is FormattedBody.Json -> jsonSearchCandidates(sectionKey, formatted.root) + is FormattedBody.Xml -> + formatted.text.lines().mapIndexed { index, line -> + InspectorSearchCandidate(sectionKey, "line:$index", InspectorSearchField.VALUE, line) + } + } } is InspectorDetailSectionBody.Bars, is InspectorDetailSectionBody.Empty -> emptyList() } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearchOptionsSheet.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearchOptionsSheet.kt index 1ed68e6..fe25a1a 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearchOptionsSheet.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearchOptionsSheet.kt @@ -2,26 +2,33 @@ * @author Shakib * @since 17/08/26 */ -@file:Suppress("FunctionNaming", "MagicNumber") +@file:Suppress("FunctionNaming", "MagicNumber", "UnusedPrivateMember") @file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class) package io.devconsole.ui.compose -import androidx.compose.foundation.clickable +import android.content.res.Configuration +import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.selection.toggleable import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Checkbox +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.MaterialTheme import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextButton +import androidx.compose.material3.rememberModalBottomSheetState import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf @@ -30,9 +37,12 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.semantics.Role -import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.em import androidx.compose.ui.unit.sp +import java.util.Locale @Composable internal fun InspectorDetailSearchOptionsSheet( @@ -41,85 +51,207 @@ internal fun InspectorDetailSearchOptionsSheet( mode: InspectorSearchMode, onDismiss: () -> Unit, onApply: (Set, InspectorSearchMode) -> Unit, +) { + ModalBottomSheet( + onDismissRequest = onDismiss, + containerColor = DevConsoleTheme.colors.panel, + // A half-height first view would cut the section list and hide the mode chips entirely. + sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true), + ) { + InspectorDetailSearchOptionsSheetContent( + options = options, + selectedSectionKeys = selectedSectionKeys, + mode = mode, + onDismiss = onDismiss, + onApply = onApply, + ) + } +} + +@Composable +@Suppress("LongParameterList") // Mirrors the sheet's own signature, plus the conventional modifier. +private fun InspectorDetailSearchOptionsSheetContent( + options: InspectorDetailSearchOptions, + selectedSectionKeys: Set, + mode: InspectorSearchMode, + onDismiss: () -> Unit, + onApply: (Set, InspectorSearchMode) -> Unit, + modifier: Modifier = Modifier, ) { var draftSectionKeys by remember(selectedSectionKeys) { mutableStateOf(selectedSectionKeys) } var draftMode by remember(mode) { mutableStateOf(mode) } val colors = DevConsoleTheme.colors - ModalBottomSheet(onDismissRequest = onDismiss, containerColor = colors.panel) { + Column( + modifier = + modifier + .fillMaxWidth() + .navigationBarsPadding(), + ) { + SearchOptionsHeader( + applyEnabled = draftSectionKeys.isNotEmpty(), + onDismiss = onDismiss, + onApply = { onApply(draftSectionKeys, draftMode) }, + ) + HorizontalDivider(color = colors.line) + // No weight: the sheet sizes to its content, and this column only starts scrolling once the + // sections outgrow the height the sheet is allowed (short lists get a short sheet). Column( modifier = Modifier - .fillMaxWidth() - .fillMaxHeight(0.8f) - .navigationBarsPadding(), + .verticalScroll(rememberScrollState()) + .padding(horizontal = 20.dp, vertical = 8.dp), + verticalArrangement = Arrangement.spacedBy(4.dp), ) { - Row( - modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 8.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Text("Search options", color = colors.ink, fontSize = 20.sp, modifier = Modifier.weight(1f)) - TextButton(onClick = onDismiss) { Text("Cancel") } - InspectorPillButton( - label = "Apply", - onClick = { onApply(draftSectionKeys, draftMode) }, - enabled = draftSectionKeys.isNotEmpty(), - modifier = Modifier.padding(start = 8.dp), - ) - } - Column( - modifier = - Modifier - .weight(1f) - .verticalScroll(rememberScrollState()) - .padding(horizontal = 20.dp, vertical = 8.dp), - verticalArrangement = Arrangement.spacedBy(4.dp), - ) { - Text("Search in", color = colors.text3, fontSize = 12.sp, modifier = Modifier.padding(top = 12.dp)) - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.spacedBy(8.dp), - ) { - TextButton(onClick = { draftSectionKeys = options.sections.map { it.key }.toSet() }) { - Text("Select all") - } - TextButton(onClick = { draftSectionKeys = emptySet() }) { - Text("Clear all") - } - } - options.sections.forEach { section -> - val checked = section.key in draftSectionKeys - Row( - modifier = - Modifier - .fillMaxWidth() - .heightIn(min = 48.dp) - .clickable( - role = Role.Checkbox, - onClick = { - draftSectionKeys = - if (checked) draftSectionKeys - section.key else draftSectionKeys + section.key - }, - ) - .semantics(mergeDescendants = true) {}, - verticalAlignment = Alignment.CenterVertically, - ) { - Checkbox(checked = checked, onCheckedChange = null) - Text(section.label, color = colors.ink, fontSize = 14.sp) - } - } - Text("Match", color = colors.text3, fontSize = 12.sp, modifier = Modifier.padding(top = 12.dp)) - FilterChipRow( - chips = - InspectorSearchMode.values().map { candidate -> - InspectorFilterChip(candidate.name, candidate.label, selected = candidate == draftMode) - }, - onChipClick = { chip -> - draftMode = InspectorSearchMode.values().first { it.name == chip.id } + SearchSectionPicker( + sections = options.sections, + selectedKeys = draftSectionKeys, + onSelectionChange = { draftSectionKeys = it }, + ) + SearchOptionsGroupLabel("Match on") + FilterChipRow( + chips = + InspectorSearchMode.entries.map { candidate -> + InspectorFilterChip(candidate.name, candidate.label, selected = candidate == draftMode) }, - modifier = Modifier.padding(horizontal = 0.dp), - ) - } + onChipClick = { chip -> draftMode = InspectorSearchMode.valueOf(chip.id) }, + contentPadding = PaddingValues(vertical = 8.dp), + ) + Text(draftMode.hint, color = colors.text3, style = MaterialTheme.typography.bodySmall) } } } + +@Composable +private fun SearchOptionsHeader( + applyEnabled: Boolean, + onDismiss: () -> Unit, + onApply: () -> Unit, +) { + Row( + modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + "Search options", + color = DevConsoleTheme.colors.ink, + fontSize = 20.sp, + fontWeight = FontWeight.SemiBold, + letterSpacing = (-0.01).em, + modifier = Modifier.weight(1f), + ) + TextButton(onClick = onDismiss) { Text("Cancel") } + InspectorPillButton( + label = "Apply", + onClick = onApply, + enabled = applyEnabled, + modifier = Modifier.padding(start = 8.dp), + ) + } +} + +@Composable +private fun SearchSectionPicker( + sections: List, + selectedKeys: Set, + onSelectionChange: (Set) -> Unit, +) { + SearchOptionsGroupLabel("Search in") + Row( + // Cancels TextButtonHorizontalPadding so the labels sit on the column's own 20dp margin. + modifier = Modifier.fillMaxWidth().offset(x = (-12).dp), + ) { + TextButton(onClick = { onSelectionChange(sections.map { it.key }.toSet()) }) { Text("Select all") } + TextButton(onClick = { onSelectionChange(emptySet()) }) { Text("Clear all") } + } + sections.forEach { section -> + SearchSectionCheckboxRow( + label = section.label, + checked = section.key in selectedKeys, + onCheckedChange = { isChecked -> + onSelectionChange(if (isChecked) selectedKeys + section.key else selectedKeys - section.key) + }, + ) + } + if (selectedKeys.isEmpty()) { + Text( + "Pick at least one section before applying.", + color = DevConsoleTheme.colors.warn, + style = MaterialTheme.typography.bodySmall, + modifier = Modifier.padding(top = 4.dp), + ) + } +} + +/** The design system's Label voice: uppercase, tracked, tertiary -- the sheet's only wayfinding. */ +@Composable +private fun SearchOptionsGroupLabel(text: String) { + Text( + text.uppercase(Locale.US), + color = DevConsoleTheme.colors.text3, + style = DevConsoleType.groupLabel, + modifier = Modifier.padding(top = 16.dp), + ) +} + +/** + * One searchable section. The whole row is the toggle: [Checkbox] is passed a null callback so the + * row's `toggleable` owns both the click and the checked state TalkBack announces. + */ +@Composable +private fun SearchSectionCheckboxRow( + label: String, + checked: Boolean, + onCheckedChange: (Boolean) -> Unit, +) { + Row( + modifier = + Modifier + .fillMaxWidth() + .heightIn(min = 48.dp) + .toggleable(value = checked, role = Role.Checkbox, onValueChange = onCheckedChange), + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Checkbox(checked = checked, onCheckedChange = null) + Text(label, color = DevConsoleTheme.colors.ink, style = MaterialTheme.typography.bodyLarge) + } +} + +@Preview(name = "Dark", uiMode = Configuration.UI_MODE_NIGHT_YES, showBackground = true, backgroundColor = 0xFF0B0E0D) +@Preview(name = "Light", uiMode = Configuration.UI_MODE_NIGHT_NO, showBackground = true, backgroundColor = 0xFFF3F6EE) +@Preview(name = "Large font", fontScale = 1.5f, showBackground = true, backgroundColor = 0xFF0B0E0D) +@Composable +private fun InspectorDetailSearchOptionsSheetPreview() { + SearchOptionsSheetPreviewScaffold( + selectedSectionKeys = NetworkDetailSearchOptions.defaultSectionKeys, + ) +} + +/** The state that disables Apply: no section selected, so the warning and the gated action show. */ +@Preview( + name = "Nothing selected", + uiMode = Configuration.UI_MODE_NIGHT_YES, + showBackground = true, + backgroundColor = 0xFF0B0E0D, +) +@Composable +private fun InspectorDetailSearchOptionsSheetEmptyPreview() { + SearchOptionsSheetPreviewScaffold(selectedSectionKeys = emptySet()) +} + +@Composable +private fun SearchOptionsSheetPreviewScaffold(selectedSectionKeys: Set) { + DevConsoleTheme(darkTheme = isSystemInDarkTheme()) { + Surface(color = DevConsoleTheme.colors.panel) { + InspectorDetailSearchOptionsSheetContent( + options = NetworkDetailSearchOptions, + selectedSectionKeys = selectedSectionKeys, + mode = NetworkDetailSearchOptions.defaultMode, + onDismiss = {}, + onApply = { _, _ -> }, + ) + } + } +} + diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorFormattableBody.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorFormattableBody.kt index 8258b13..104cace 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorFormattableBody.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorFormattableBody.kt @@ -59,17 +59,23 @@ import androidx.compose.ui.unit.sp internal fun InspectorFormattableBody( body: InspectorDetailSectionBody.Formattable, modifier: Modifier = Modifier, + showRaw: Boolean? = null, + onShowRawChange: ((Boolean) -> Unit)? = null, sectionKey: String = "", searchMatches: List = emptyList(), currentMatchOrdinal: Int? = null, onExpandFullScreen: (() -> Unit)? = null, ) { val colors = DevConsoleTheme.colors - var showRaw by rememberSaveable(body.rawText) { mutableStateOf(body.formatted == null) } + var localShowRaw by rememberSaveable(body.rawText) { mutableStateOf(body.formatted == null) } + val renderedShowRaw = showRaw ?: localShowRaw + val updateShowRaw: (Boolean) -> Unit = { value -> + if (showRaw == null) localShowRaw = value else onShowRawChange?.invoke(value) + } val precomputed = rememberFormattableContent( body = body, - showRaw = showRaw, + showRaw = renderedShowRaw, sectionKey = sectionKey, searchMatches = searchMatches, currentMatchOrdinal = currentMatchOrdinal, @@ -88,8 +94,8 @@ internal fun InspectorFormattableBody( Column(modifier = modifier.fillMaxWidth().bringIntoViewRequester(bringIntoViewRequester)) { if (body.formatted != null) { RawFormattedToggle( - showRaw = showRaw, - onToggle = { showRaw = it }, + showRaw = renderedShowRaw, + onToggle = updateShowRaw, // Matches the 16dp horizontal inset InspectorKeyValueList/InspectorProgressBars/ // InspectorDetailEmptyText each apply themselves for a CollapsibleSection's content -- // FilterChipRow carries no inset of its own (its other callers sit inside a parent @@ -141,15 +147,23 @@ internal fun InspectorFormattableFullScreenOverlay( body: InspectorDetailSectionBody.Formattable, onDismiss: () -> Unit, modifier: Modifier = Modifier, + showRaw: Boolean? = null, + onShowRawChange: ((Boolean) -> Unit)? = null, sectionKey: String = "", searchMatches: List = emptyList(), currentMatchOrdinal: Int? = null, + onCopy: (() -> Unit)? = null, + copyContentDescription: String = "Copy $title", ) { - var showRaw by rememberSaveable(body.rawText) { mutableStateOf(body.formatted == null) } + var localShowRaw by rememberSaveable(body.rawText) { mutableStateOf(body.formatted == null) } + val renderedShowRaw = showRaw ?: localShowRaw + val updateShowRaw: (Boolean) -> Unit = { value -> + if (showRaw == null) localShowRaw = value else onShowRawChange?.invoke(value) + } val precomputed = rememberFormattableContent( body = body, - showRaw = showRaw, + showRaw = renderedShowRaw, fontSize = 14.sp, lineHeight = 23.8.sp, sectionKey = sectionKey, @@ -162,10 +176,14 @@ internal fun InspectorFormattableFullScreenOverlay( modifier = modifier, headerTrailing = if (body.formatted != null) { - { RawFormattedToggle(showRaw = showRaw, onToggle = { showRaw = it }, compact = true) } + { RawFormattedToggle(showRaw = renderedShowRaw, onToggle = updateShowRaw, compact = true) } } else { null }, + targetIndex = precomputed.targetIndex, + onCopy = onCopy, + copyContentDescription = copyContentDescription, + meta = inspectorLineCountMeta(body.rawLines.size), content = precomputed.content, ) } @@ -194,6 +212,10 @@ private fun rememberFormattableContent( ): FormattableRenderContent { val colors = DevConsoleTheme.colors val sectionMatches = searchMatches.filter { it.sectionKey == sectionKey || sectionKey.isEmpty() } + val highlightIndex = + remember(sectionMatches, currentMatchOrdinal) { + indexInspectorSearchHighlights(sectionMatches, currentMatchOrdinal) + } val formatted = body.formatted val useRaw = showRaw || formatted == null @@ -238,10 +260,9 @@ private fun rememberFormattableContent( fontSize = fontSize, lineHeight = lineHeight, valueHighlights = - sectionMatches.highlightsFor( + highlightIndex.highlightsFor( itemId, InspectorSearchField.VALUE, - currentMatchOrdinal, ), ) } @@ -259,10 +280,9 @@ private fun rememberFormattableContent( fontSize = fontSize, lineHeight = lineHeight, valueHighlights = - sectionMatches.highlightsFor( + highlightIndex.highlightsFor( itemId, InspectorSearchField.VALUE, - currentMatchOrdinal, ), ) } @@ -297,12 +317,18 @@ private fun rememberJsonTreeRows( ) } } + val highlightIndex = + remember(searchMatches, currentMatchOrdinal) { + indexInspectorSearchHighlights(searchMatches, currentMatchOrdinal) + } val searchRows = - rows.map { row -> - row.copy( - searchKeyHighlights = searchMatches.highlightsFor(row.path, InspectorSearchField.KEY, currentMatchOrdinal), - searchValueHighlights = searchMatches.highlightsFor(row.path, InspectorSearchField.VALUE, currentMatchOrdinal), - ) + remember(rows, highlightIndex) { + rows.map { row -> + row.copy( + searchKeyHighlights = highlightIndex.highlightsFor(row.path, InspectorSearchField.KEY), + searchValueHighlights = highlightIndex.highlightsFor(row.path, InspectorSearchField.VALUE), + ) + } } val onToggle: (String) -> Unit = { path -> expandedOverrides[path] = !(expandedOverrides[path] ?: true) } return searchRows to onToggle @@ -316,14 +342,13 @@ private fun RawFormattedToggle( modifier: Modifier = Modifier, compact: Boolean = false, ) { - FilterChipRow( - chips = - listOf( - InspectorFilterChip("formatted", "Formatted", !showRaw), - InspectorFilterChip("raw", "Raw", showRaw), - ), - onChipClick = { chip -> onToggle(chip.id == "raw") }, - modifier = if (compact) modifier.padding(end = 4.dp) else modifier, + // A segmented control, not chips: Formatted/Raw are two views of one body, not two filters over + // a set. See DESIGN.md's Components section. + InspectorSegmentedControl( + options = listOf("Formatted", "Raw"), + selectedIndex = if (showRaw) 1 else 0, + onSelect = { index -> onToggle(index == 1) }, + modifier = if (compact) modifier else modifier.padding(horizontal = 16.dp, vertical = 8.dp), ) } 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 283728b..e1ef1b7 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 @@ -53,6 +53,8 @@ import androidx.compose.ui.unit.sp */ internal enum class InspectorGlyph { Search, ChevronDown, Check, Alert, Flag, Copy, Expand } +/** DESIGN.md's disabled treatment: the whole control at half opacity, container and content alike. */ +private const val DISABLED_PILL_ALPHA = 0.5f private const val GLYPH_VIEWBOX = 16f private const val GLYPH_STROKE_WIDTH = 1.4f @@ -196,9 +198,8 @@ internal fun InspectorRoundIconButton( * [outlined] swaps the filled [containerColor] for a hairline border on transparent -- the "demoted, * can never succeed" affordance (e.g. the push detail's Replay button) that * still reads as a button but no longer competes visually with a real primary action. [enabled] - * disables the click target too; a caller that passes `enabled = false` is expected to also dim - * [contentColor]/the icon's own tint itself, since this composable never overrides a caller-chosen - * color. + * disables the click target and dims the whole pill to the design system's 0.5 disabled opacity, so + * a gated action never looks like it will still work. */ @Suppress("LongParameterList") // Colors/icon vary per call site (hero CTA vs. footer actions). @Composable @@ -221,6 +222,7 @@ internal fun InspectorPillButton( modifier = modifier .heightIn(min = 48.dp) + .alpha(if (enabled) 1f else DISABLED_PILL_ALPHA) .clip(RoundedCornerShape(50)) .then(outlineModifier) .background(resolvedContainer) diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorKeyValueList.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorKeyValueList.kt index b4d0f6d..7bae039 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorKeyValueList.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorKeyValueList.kt @@ -47,6 +47,10 @@ internal fun InspectorKeyValueList( val colors = DevConsoleTheme.colors val lineColor = colors.line val sectionMatches = searchMatches.filter { it.sectionKey == sectionKey || sectionKey.isEmpty() } + val highlightIndex = + remember(sectionMatches, currentMatchOrdinal) { + indexInspectorSearchHighlights(sectionMatches, currentMatchOrdinal) + } // No top inset on this padding, so the first divider sits flush under the section header // instead of 8dp below it. Column(modifier = modifier.fillMaxWidth().padding(start = 16.dp, end = 16.dp, bottom = 8.dp)) { @@ -70,7 +74,7 @@ internal fun InspectorKeyValueList( Text( inspectorHighlightedText( text = entry.key, - highlights = sectionMatches.highlightsFor(itemId, InspectorSearchField.KEY, currentMatchOrdinal), + highlights = highlightIndex.highlightsFor(itemId, InspectorSearchField.KEY), colors = colors, ), color = colors.jsonKey, @@ -80,7 +84,7 @@ internal fun InspectorKeyValueList( Text( inspectorHighlightedText( text = entry.value, - highlights = sectionMatches.highlightsFor(itemId, InspectorSearchField.VALUE, currentMatchOrdinal), + highlights = highlightIndex.highlightsFor(itemId, InspectorSearchField.VALUE), colors = colors, ), color = entry.valueColor ?: colors.ink, 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 7572511..ff289db 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorListComponents.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorListComponents.kt @@ -9,12 +9,21 @@ package io.devconsole.ui.compose import androidx.compose.animation.core.animateFloatAsState import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.ui.semantics.role import androidx.compose.foundation.clickable import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.heightIn @@ -250,13 +259,17 @@ internal fun FilterChipRow( chips: List, onChipClick: (InspectorFilterChip) -> Unit, modifier: Modifier = Modifier, + /** Overridable so a caller that already pads its column can align chips to its own margin. */ + contentPadding: PaddingValues = PaddingValues(horizontal = 16.dp, vertical = 8.dp), + /** False for a caller that places the chips beside other controls and must not have the row eat the width. */ + fillWidth: Boolean = true, ) { Row( modifier = modifier - .fillMaxWidth() + .then(if (fillWidth) Modifier.fillMaxWidth() else Modifier) .horizontalScroll(rememberScrollState()) - .padding(horizontal = 16.dp, vertical = 8.dp), + .padding(contentPadding), horizontalArrangement = Arrangement.spacedBy(8.dp), ) { chips.forEach { chip -> InspectorChip(chip, onClick = { onChipClick(chip) }) } @@ -299,3 +312,55 @@ private fun InspectorChip( ), ) } + +/** + * The design system's segmented control (DESIGN.md §Components): one joined 32dp group, 8dp on the + * outer corners and square inside, mono labels, active segment filled with signal. Use it for a + * view switch over 2-3 mutually exclusive representations of the *same* content -- a filter chip + * row says "narrow this set", a segment says "show me this side of it". + */ +@Composable +internal fun InspectorSegmentedControl( + options: List, + selectedIndex: Int, + onSelect: (Int) -> Unit, + modifier: Modifier = Modifier, +) { + val colors = DevConsoleTheme.colors + val shape = RoundedCornerShape(8.dp) + Row( + modifier = + modifier + .height(32.dp) + .clip(shape) + .border(1.dp, colors.line, shape) + .semantics { role = Role.RadioButton }, + verticalAlignment = Alignment.CenterVertically, + ) { + options.forEachIndexed { index, option -> + val selected = index == selectedIndex + if (index > 0) { + Box(Modifier.fillMaxHeight().width(1.dp).background(colors.line)) + } + Box( + modifier = + Modifier + .fillMaxHeight() + .widthIn(min = 42.dp) + .background(if (selected) colors.signal else Color.Transparent) + .selectable(selected = selected, role = Role.RadioButton) { onSelect(index) } + .padding(horizontal = 12.dp), + contentAlignment = Alignment.Center, + ) { + Text( + option, + color = if (selected) colors.signalInk else colors.muted, + fontFamily = FontFamily.Monospace, + fontSize = 11.5.sp, + fontWeight = if (selected) FontWeight.Bold else FontWeight.Medium, + maxLines = 1, + ) + } + } + } +} 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 875f55b..8a4eeaf 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 @@ -399,13 +399,13 @@ private fun ServerControlCard( fontWeight = FontWeight.SemiBold, ) Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) { + // No per-state color swaps: InspectorPillButton owns the disabled treatment now, and + // dimming an already-muted color twice pushed these below the contrast floor. InspectorPillButton( label = "Start server", onClick = { onSetServerRunning(true) }, modifier = Modifier.weight(1f), enabled = !running, - containerColor = if (running) colors.panel else colors.signal, - contentColor = if (running) colors.muted else colors.signalInk, ) InspectorPillButton( label = "Stop", @@ -413,7 +413,7 @@ private fun ServerControlCard( modifier = Modifier.weight(1f), enabled = running, outlined = true, - contentColor = if (running) colors.ink else colors.muted, + contentColor = colors.ink, ) } } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt index e0e1531..18774e7 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt @@ -276,6 +276,8 @@ private fun InspectorDetailSectionCard( spec: InspectorDetailSectionSpec, resolved: ResolvedDetailSection, currentMatchOrdinal: Int?, + formattableShowRaw: Boolean?, + onFormattableShowRawChange: ((Boolean) -> Unit)?, onToggle: () -> Unit, onExpandCodeFullScreen: (String) -> Unit, ) { @@ -314,6 +316,8 @@ private fun InspectorDetailSectionCard( is InspectorDetailSectionBody.Formattable -> InspectorFormattableBody( body = body, + showRaw = formattableShowRaw, + onShowRawChange = onFormattableShowRawChange, sectionKey = spec.key, searchMatches = resolved.searchMatches, currentMatchOrdinal = currentMatchOrdinal, @@ -353,26 +357,50 @@ internal fun InspectorObserveDetailScreen( rememberSaveable(resetKey) { mutableStateOf(searchOptions?.defaultSectionKeys?.toList().orEmpty()) } - var searchModeName by + // Enums are Serializable, so the mode survives process death without a name round-trip. + var searchMode by rememberSaveable(resetKey) { - mutableStateOf((searchOptions?.defaultMode ?: InspectorSearchMode.KEYS_AND_VALUES).name) + mutableStateOf(searchOptions?.defaultMode ?: InspectorSearchMode.KEYS_AND_VALUES) } var currentMatchOrdinal by rememberSaveable(resetKey) { mutableIntStateOf(0) } + var rawFormattableSectionKeys by rememberSaveable(resetKey) { mutableStateOf(emptyList()) } var searchOptionsVisible by remember(resetKey) { mutableStateOf(false) } val openState = remember(resetKey) { mutableStateMapOf().apply { initiallyOpenSectionKeys.forEach { key -> this[key] = true } } } val colors = DevConsoleTheme.colors - val selectedKeys = selectedSectionKeys.toSet() - val searchMode = - InspectorSearchMode.values().firstOrNull { it.name == searchModeName } - ?: InspectorSearchMode.KEYS + val selectedKeys = remember(selectedSectionKeys) { selectedSectionKeys.toSet() } + val rawSectionKeys = remember(rawFormattableSectionKeys) { rawFormattableSectionKeys.toSet() } + val searchableSectionKeys = remember(searchOptions) { searchOptions?.sections?.mapTo(mutableSetOf()) { it.key }.orEmpty() } + val searchableSectionBodies = inspectorSearchSectionBodies(sections, searchableSectionKeys) + val hasNetworkQuery = searchOptions != null && query.isNotBlank() + val networkSearchCandidates = + remember(searchableSectionBodies, rawSectionKeys, hasNetworkQuery) { + if (!hasNetworkQuery) { + emptyList() + } else { + searchableSectionBodies.flatMap { section -> + searchInspectorBodyCandidates( + sectionKey = section.sectionKey, + body = section.body, + representation = + if (section.sectionKey in rawSectionKeys) { + InspectorBodySearchRepresentation.RAW + } else { + InspectorBodySearchRepresentation.FORMATTED + }, + ) + } + } + } val networkMatches = - if (searchOptions != null) { - searchInspectorSections(sections, query, selectedKeys, searchMode) - } else { - emptyList() + remember(networkSearchCandidates, query, selectedKeys, searchMode, hasNetworkQuery) { + if (hasNetworkQuery) { + searchInspectorCandidates(networkSearchCandidates, query, selectedKeys, searchMode) + } else { + emptyList() + } } val activeMatchOrdinal = if (networkMatches.isEmpty()) 0 else currentMatchOrdinal.coerceIn(0, networkMatches.lastIndex) @@ -387,7 +415,7 @@ internal fun InspectorObserveDetailScreen( openState = openState, colors = colors, matches = sectionMatches, - searchable = spec.key in searchOptions.sections.map { it.key }, + searchable = spec.key in searchableSectionKeys, ) } else { spec to resolveDetailSection(spec, query, openState, colors) @@ -419,6 +447,8 @@ internal fun InspectorObserveDetailScreen( sectionKey = spec.key, searchMatches = section.searchMatches, currentMatchOrdinal = activeMatchOrdinal, + onCopy = spec.onCopy, + copyContentDescription = spec.copyDescription ?: "Copy ${spec.label}", ) return } @@ -427,10 +457,32 @@ internal fun InspectorObserveDetailScreen( title = spec.label, body = body, onDismiss = { fullScreenSectionKey = null }, + showRaw = + if (searchOptions != null) { + body.formatted == null || spec.key in rawSectionKeys + } else { + null + }, + onShowRawChange = + if (searchOptions != null) { + { showRaw -> + rawFormattableSectionKeys = + if (showRaw) { + (rawFormattableSectionKeys + spec.key).distinct() + } else { + rawFormattableSectionKeys.filterNot { it == spec.key } + } + currentMatchOrdinal = 0 + } + } else { + null + }, modifier = modifier.fillMaxSize(), sectionKey = spec.key, searchMatches = section.searchMatches, currentMatchOrdinal = activeMatchOrdinal, + onCopy = spec.onCopy, + copyContentDescription = spec.copyDescription ?: "Copy ${spec.label}", ) return } @@ -491,6 +543,28 @@ internal fun InspectorObserveDetailScreen( spec = spec, resolved = section, currentMatchOrdinal = if (searchOptions != null) activeMatchOrdinal else null, + formattableShowRaw = + if (searchOptions != null) { + (spec.body as? InspectorDetailSectionBody.Formattable)?.let { body -> + body.formatted == null || spec.key in rawSectionKeys + } + } else { + null + }, + onFormattableShowRawChange = + if (searchOptions != null) { + { showRaw -> + rawFormattableSectionKeys = + if (showRaw) { + (rawFormattableSectionKeys + spec.key).distinct() + } else { + rawFormattableSectionKeys.filterNot { it == spec.key } + } + currentMatchOrdinal = 0 + } + } else { + null + }, onToggle = { openState[spec.key] = !section.expanded }, onExpandCodeFullScreen = { key -> fullScreenSectionKey = key }, ) @@ -504,7 +578,7 @@ internal fun InspectorObserveDetailScreen( onDismiss = { searchOptionsVisible = false }, onApply = { newKeys, newMode -> selectedSectionKeys = newKeys.toList() - searchModeName = newMode.name + searchMode = newMode currentMatchOrdinal = 0 searchOptionsVisible = false }, diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveFrameDetail.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveFrameDetail.kt index 4dbe01e..78bced1 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveFrameDetail.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveFrameDetail.kt @@ -83,7 +83,7 @@ private fun frameSections( onCopy = { copyText(generalEntries.toCopyText()) }, ), textPreviewSection( - key = "req", + key = InspectorExchangeSection.PRIMARY_BODY.key, label = "Payload", preview = frame.preview, isBinaryPlaceholder = false, @@ -93,7 +93,7 @@ private fun frameSections( copyDescription = "Copy payload", ), InspectorDetailSectionSpec( - "resh", + InspectorExchangeSection.SECONDARY_HEADERS.key, "Connection", InspectorDetailSectionBody.KeyValues(connectionEntries), copyDescription = "Copy connection info", @@ -177,7 +177,7 @@ internal fun frameDetailContent( ), ), sections = frameSections(socket, frame, colors, sizeLabel, copyText), - initiallyOpenSectionKeys = setOf("req"), + initiallyOpenSectionKeys = setOf(InspectorExchangeSection.PRIMARY_BODY.key), footerActions = frameFooterActions(socket, frame, colors, copyText, shareText), ) } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveLogDetail.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveLogDetail.kt index ca4973c..7905a78 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveLogDetail.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveLogDetail.kt @@ -47,14 +47,14 @@ private fun logSections( onCopy = { copyText(generalEntries.toCopyText()) }, ), InspectorDetailSectionSpec( - "req", + InspectorExchangeSection.PRIMARY_BODY.key, "Context", contextBody, copyDescription = "Copy context", onCopy = contextCopy, ), InspectorDetailSectionSpec( - "resh", + InspectorExchangeSection.SECONDARY_HEADERS.key, "Related transaction", InspectorDetailSectionBody.Empty("This event is not linked to a transaction."), ), 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 f0f08ea..c08a686 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 @@ -203,7 +203,7 @@ private fun netBodySections( } return listOf( textPreviewSection( - "req", + InspectorExchangeSection.PRIMARY_BODY.key, "Request payload", transaction.requestPreview, requestBinary, @@ -213,7 +213,7 @@ private fun netBodySections( "Copy request payload", ), textPreviewSection( - "res", + InspectorExchangeSection.SECONDARY_BODY.key, "Response body", transaction.responsePreview, isBinaryPlaceholder = false, @@ -249,16 +249,16 @@ private fun netSections( onCopy = { copyText(generalEntries.toCopyText()) }, ), InspectorDetailSectionSpec( - "reqh", - "Request headers", + InspectorExchangeSection.PRIMARY_HEADERS.key, + InspectorExchangeSection.PRIMARY_HEADERS.networkLabel, requestHeadersBody, copyDescription = "Copy request headers", onCopy = keyValuesCopyAction(requestHeadersBody.entries, copyText), ), requestSection, InspectorDetailSectionSpec( - "resh", - "Response headers", + InspectorExchangeSection.SECONDARY_HEADERS.key, + InspectorExchangeSection.SECONDARY_HEADERS.networkLabel, responseHeadersBody, copyDescription = "Copy response headers", onCopy = keyValuesCopyAction(responseHeadersBody.entries, copyText), @@ -380,7 +380,7 @@ internal fun netDetailContent( 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"), + initiallyOpenSectionKeys = InspectorExchangeSection.keysOf(InspectorExchangeSection.defaultSearchScope), footerActions = netFooterActions(transaction, colors, onMockAction, copyText), searchOptions = NetworkDetailSearchOptions, ) diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObservePushDetail.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObservePushDetail.kt index 2215fbd..528cf20 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObservePushDetail.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObservePushDetail.kt @@ -54,14 +54,14 @@ private fun pushSections( onCopy = { copyText(generalEntries.toCopyText()) }, ), InspectorDetailSectionSpec( - "req", + InspectorExchangeSection.PRIMARY_BODY.key, "Payload", payloadBody, copyDescription = "Copy payload", onCopy = keyValuesCopyAction(payloadEntries.orEmpty(), copyText), ), InspectorDetailSectionSpec( - "resh", + InspectorExchangeSection.SECONDARY_HEADERS.key, "Lifecycle", InspectorDetailSectionBody.KeyValues(lifecycleEntries), copyDescription = "Copy lifecycle info", @@ -143,7 +143,7 @@ internal fun pushDetailContent( ), ), sections = pushSections(push, colors, copyText), - initiallyOpenSectionKeys = setOf("req"), + initiallyOpenSectionKeys = setOf(InspectorExchangeSection.PRIMARY_BODY.key), footerActions = pushFooterActions(colors, payloadText, copyText), ) } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorSearchHighlight.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorSearchHighlight.kt index 58d7fb1..5ce470b 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorSearchHighlight.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorSearchHighlight.kt @@ -14,19 +14,37 @@ internal data class InspectorSearchHighlight( val active: Boolean, ) -internal fun List.highlightsFor( - itemId: String, - field: InspectorSearchField, +internal data class InspectorSearchHighlightTarget( + val itemId: String, + val field: InspectorSearchField, +) + +internal class InspectorSearchHighlightIndex internal constructor( + private val highlights: Map>, +) { + fun highlightsFor( + itemId: String, + field: InspectorSearchField, + ): List = highlights[InspectorSearchHighlightTarget(itemId, field)].orEmpty() +} + +/** Groups matches once so each rendered field can retrieve its spans in constant time. */ +internal fun indexInspectorSearchHighlights( + matches: List, currentMatchOrdinal: Int?, -): List = - filter { match -> match.itemId == itemId && match.field == field } - .map { match -> +): InspectorSearchHighlightIndex { + val indexed = mutableMapOf>() + matches.forEach { match -> + val target = InspectorSearchHighlightTarget(match.itemId, match.field) + indexed.getOrPut(target, ::mutableListOf) += InspectorSearchHighlight( start = match.start, endExclusive = match.endExclusive, active = match.ordinal == currentMatchOrdinal, ) - } + } + return InspectorSearchHighlightIndex(indexed) +} internal fun inspectorHighlightedText( text: String, diff --git a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorDetailSearchTest.kt b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorDetailSearchTest.kt index cd63ba5..08143a3 100644 --- a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorDetailSearchTest.kt +++ b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorDetailSearchTest.kt @@ -128,16 +128,119 @@ class InspectorDetailSearchTest { ) } + @Test + fun `raw representation indexes rendered raw lines instead of formatted json nodes`() { + val rawText = """{"userId":1}""" + val body = + InspectorDetailSectionBody.Formattable( + rawText = rawText, + rawLines = listOf(InspectorCodeLine(value = rawText, valueColor = Color.White)), + formatted = FormattedBody.Json(MinimalJsonParser(rawText).parseDocument()), + ) + + val rawCandidates = + searchInspectorBodyCandidates( + sectionKey = "res", + body = body, + representation = InspectorBodySearchRepresentation.RAW, + ) + + assertEquals(listOf("line:0"), rawCandidates.map { it.itemId }) + assertEquals(listOf(InspectorSearchField.VALUE), rawCandidates.map { it.field }) + assertEquals(listOf(rawText), rawCandidates.map { it.text }) + assertTrue(rawCandidates.all { it.path == null }) + } + + @Test + fun `blank section query skips body candidate generation`() { + val body = + InspectorDetailSectionBody.Formattable( + rawText = "{}", + rawLines = listOf(InspectorCodeLine(value = "{}", valueColor = Color.White)), + formatted = FormattedBody.Json(MinimalJsonParser("{}").parseDocument()), + ) + var representationRequests = 0 + + val matches = + searchInspectorSections( + sections = listOf(InspectorDetailSectionSpec("res", "Response body", body)), + query = " ", + selectedSectionKeys = setOf("res"), + mode = InspectorSearchMode.VALUES, + representationForSection = { + representationRequests++ + InspectorBodySearchRepresentation.FORMATTED + }, + ) + + assertTrue(matches.isEmpty()) + assertEquals(0, representationRequests) + } + + @Test + fun `candidate cache input ignores changing section callbacks`() { + val body = InspectorDetailSectionBody.Code(listOf(InspectorCodeLine(value = "ok", valueColor = Color.White))) + val first = listOf(InspectorDetailSectionSpec("res", "Response", body, onCopy = {})) + val second = listOf(InspectorDetailSectionSpec("res", "Response", body, onCopy = {})) + + assertTrue(first != second) + assertEquals( + inspectorSearchSectionBodies(first, setOf("res")), + inspectorSearchSectionBodies(second, setOf("res")), + ) + } + + @Test + fun `highlight index groups targets and marks only active occurrence`() { + val matches = + listOf( + InspectorDetailSearchMatch(0, "res", "$/0:name", InspectorSearchField.KEY, 1, 5), + InspectorDetailSearchMatch(1, "res", "$/0:name", InspectorSearchField.KEY, 8, 12), + InspectorDetailSearchMatch(2, "res", "$/0:name", InspectorSearchField.VALUE, 0, 4), + ) + + val index = indexInspectorSearchHighlights(matches, currentMatchOrdinal = 1) + + assertEquals(2, index.highlightsFor("$/0:name", InspectorSearchField.KEY).size) + assertEquals(listOf(false, true), index.highlightsFor("$/0:name", InspectorSearchField.KEY).map { it.active }) + assertEquals(1, index.highlightsFor("$/0:name", InspectorSearchField.VALUE).size) + } + + @Test + fun `active line index resolves the full screen scroll target`() { + val matches = + listOf( + InspectorDetailSearchMatch(0, "res", "line:2", InspectorSearchField.VALUE, 0, 3), + InspectorDetailSearchMatch(1, "res", "line:42", InspectorSearchField.VALUE, 4, 7), + ) + + assertEquals(42, activeInspectorLineIndex(matches, currentMatchOrdinal = 1)) + assertEquals(null, activeInspectorLineIndex(matches, currentMatchOrdinal = 5)) + } + @Test fun `scope summary reflects multi section selection`() { assertEquals( - "All request + response", - inspectorSearchScopeSummary(NetworkDetailSearchOptions, NetworkDetailSearchOptions.defaultSectionKeys), + "All sections", + inspectorSearchScopeSummary( + NetworkDetailSearchOptions, + NetworkDetailSearchOptions.sections.mapTo(mutableSetOf()) { it.key }, + ), ) assertEquals( "Response body", - inspectorSearchScopeSummary(NetworkDetailSearchOptions, setOf("res")), + inspectorSearchScopeSummary(NetworkDetailSearchOptions, setOf(InspectorExchangeSection.SECONDARY_BODY.key)), ) assertEquals("2 sections", inspectorSearchScopeSummary(NetworkDetailSearchOptions, setOf("reqh", "res"))) + assertEquals("Nothing selected", inspectorSearchScopeSummary(NetworkDetailSearchOptions, emptySet())) + } + + @Test + fun `network search defaults to the two bodies and to keys plus values`() { + assertEquals( + InspectorExchangeSection.keysOf(setOf(InspectorExchangeSection.PRIMARY_BODY, InspectorExchangeSection.SECONDARY_BODY)), + NetworkDetailSearchOptions.defaultSectionKeys, + ) + assertEquals(InspectorSearchMode.KEYS_AND_VALUES, NetworkDetailSearchOptions.defaultMode) } } diff --git a/update.py b/update.py deleted file mode 100644 index c2bad70..0000000 --- a/update.py +++ /dev/null @@ -1,14 +0,0 @@ -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) From 2bf722eb1707a946e1abfaa3518b1bda3be4e945 Mon Sep 17 00:00:00 2001 From: shakibuzzaman Date: Mon, 17 Aug 2026 23:59:19 +0600 Subject: [PATCH 12/20] style: apply ktlintFormat and refresh the ui-compose API baseline Formatting only; the .api diff is Compose-generated ComposableSingletons lambda accessors, no public API surface change. --- sdk/ui-compose/api/ui-compose.api | 12 +++++++-- .../ui/compose/InspectorCodeBlock.kt | 4 +-- .../compose/InspectorCodeFullScreenOverlay.kt | 7 +++--- .../ui/compose/InspectorDetailSearch.kt | 7 +++--- .../InspectorDetailSearchOptionsSheet.kt | 1 - .../ui/compose/InspectorFormattableBody.kt | 4 +-- .../ui/compose/InspectorKeyValueList.kt | 2 +- .../ui/compose/InspectorListComponents.kt | 14 +++++------ .../ui/compose/InspectorObserveDetail.kt | 25 ++++++++++--------- .../ui/compose/InspectorDetailSearchTest.kt | 7 +++++- 10 files changed, 49 insertions(+), 34 deletions(-) diff --git a/sdk/ui-compose/api/ui-compose.api b/sdk/ui-compose/api/ui-compose.api index b10cd69..8cd66f7 100644 --- a/sdk/ui-compose/api/ui-compose.api +++ b/sdk/ui-compose/api/ui-compose.api @@ -1,7 +1,7 @@ public final class io/devconsole/ui/compose/ComposableSingletons$CollapsibleSectionKt { public static final field INSTANCE Lio/devconsole/ui/compose/ComposableSingletons$CollapsibleSectionKt; public fun ()V - public final fun getLambda$-1132852660$ui_compose_release ()Lkotlin/jvm/functions/Function2; + public final fun getLambda$-231784725$ui_compose_release ()Lkotlin/jvm/functions/Function2; } public final class io/devconsole/ui/compose/ComposableSingletons$DevConsoleActivityKt { @@ -65,7 +65,7 @@ public final class io/devconsole/ui/compose/ComposableSingletons$InspectorDesign public final class io/devconsole/ui/compose/ComposableSingletons$InspectorDetailHeaderKt { public static final field INSTANCE Lio/devconsole/ui/compose/ComposableSingletons$InspectorDetailHeaderKt; public fun ()V - public final fun getLambda$844457626$ui_compose_release ()Lkotlin/jvm/functions/Function2; + public final fun getLambda$520449243$ui_compose_release ()Lkotlin/jvm/functions/Function2; } public final class io/devconsole/ui/compose/ComposableSingletons$InspectorDetailPreviewsKt { @@ -80,6 +80,14 @@ public final class io/devconsole/ui/compose/ComposableSingletons$InspectorDetail public final fun getLambda$916258535$ui_compose_release ()Lkotlin/jvm/functions/Function2; } +public final class io/devconsole/ui/compose/ComposableSingletons$InspectorDetailSearchOptionsSheetKt { + public static final field INSTANCE Lio/devconsole/ui/compose/ComposableSingletons$InspectorDetailSearchOptionsSheetKt; + public fun ()V + public final fun getLambda$-592466661$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$1722714866$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$481453717$ui_compose_release ()Lkotlin/jvm/functions/Function3; +} + public final class io/devconsole/ui/compose/ComposableSingletons$InspectorFilesSectionKt { public static final field INSTANCE Lio/devconsole/ui/compose/ComposableSingletons$InspectorFilesSectionKt; public fun ()V diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeBlock.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeBlock.kt index af3a3be..08e7f7a 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeBlock.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeBlock.kt @@ -15,11 +15,11 @@ import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.relocation.BringIntoViewRequester -import androidx.compose.foundation.relocation.bringIntoViewRequester import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.relocation.BringIntoViewRequester +import androidx.compose.foundation.relocation.bringIntoViewRequester import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Text 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 82ee685..5fa8bb8 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 @@ -61,9 +61,10 @@ internal fun InspectorCodeFullScreenOverlay( copyContentDescription: String = "Copy $title", ) { val sectionMatches = searchMatches.filter { it.sectionKey == sectionKey || sectionKey.isEmpty() } - val highlightIndex = remember(sectionMatches, currentMatchOrdinal) { - indexInspectorSearchHighlights(sectionMatches, currentMatchOrdinal) - } + val highlightIndex = + remember(sectionMatches, currentMatchOrdinal) { + indexInspectorSearchHighlights(sectionMatches, currentMatchOrdinal) + } InspectorCodeFullScreenOverlay( title = title, onDismiss = onDismiss, diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearch.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearch.kt index 674e084..b068c1e 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearch.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearch.kt @@ -261,9 +261,10 @@ internal fun searchInspectorBodyCandidates( private fun jsonSearchCandidates( sectionKey: String, root: JsonValue, -): List = buildList { - appendJsonSearchCandidates(this, sectionKey, root, path = "$") -} +): List = + buildList { + appendJsonSearchCandidates(this, sectionKey, root, path = "$") + } private fun appendJsonSearchCandidates( candidates: MutableList, diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearchOptionsSheet.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearchOptionsSheet.kt index fe25a1a..a49065a 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearchOptionsSheet.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearchOptionsSheet.kt @@ -254,4 +254,3 @@ private fun SearchOptionsSheetPreviewScaffold(selectedSectionKeys: Set) } } } - diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorFormattableBody.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorFormattableBody.kt index 104cace..a8f5a15 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorFormattableBody.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorFormattableBody.kt @@ -19,13 +19,13 @@ import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width -import androidx.compose.foundation.relocation.BringIntoViewRequester -import androidx.compose.foundation.relocation.bringIntoViewRequester import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListScope import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.relocation.BringIntoViewRequester +import androidx.compose.foundation.relocation.bringIntoViewRequester import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Text diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorKeyValueList.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorKeyValueList.kt index 7bae039..37c07df 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorKeyValueList.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorKeyValueList.kt @@ -11,8 +11,8 @@ import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.relocation.bringIntoViewRequester import androidx.compose.foundation.relocation.BringIntoViewRequester +import androidx.compose.foundation.relocation.bringIntoViewRequester import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect 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 ff289db..cf99b64 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 @@ -10,13 +10,6 @@ package io.devconsole.ui.compose import androidx.compose.animation.core.animateFloatAsState import androidx.compose.foundation.background import androidx.compose.foundation.border -import androidx.compose.foundation.layout.fillMaxHeight -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.layout.widthIn -import androidx.compose.foundation.selection.selectable -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.ui.semantics.role import androidx.compose.foundation.clickable import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.horizontalScroll @@ -25,12 +18,18 @@ import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxHeight 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.layout.width +import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.selection.selectable 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 @@ -42,6 +41,7 @@ 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.role import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt index 18774e7..375f9e7 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt @@ -372,7 +372,8 @@ internal fun InspectorObserveDetailScreen( val colors = DevConsoleTheme.colors val selectedKeys = remember(selectedSectionKeys) { selectedSectionKeys.toSet() } val rawSectionKeys = remember(rawFormattableSectionKeys) { rawFormattableSectionKeys.toSet() } - val searchableSectionKeys = remember(searchOptions) { searchOptions?.sections?.mapTo(mutableSetOf()) { it.key }.orEmpty() } + val searchableSectionKeys = + remember(searchOptions) { searchOptions?.sections?.mapTo(mutableSetOf()) { it.key }.orEmpty() } val searchableSectionBodies = inspectorSearchSectionBodies(sections, searchableSectionKeys) val hasNetworkQuery = searchOptions != null && query.isNotBlank() val networkSearchCandidates = @@ -381,17 +382,17 @@ internal fun InspectorObserveDetailScreen( emptyList() } else { searchableSectionBodies.flatMap { section -> - searchInspectorBodyCandidates( - sectionKey = section.sectionKey, - body = section.body, - representation = - if (section.sectionKey in rawSectionKeys) { - InspectorBodySearchRepresentation.RAW - } else { - InspectorBodySearchRepresentation.FORMATTED - }, - ) - } + searchInspectorBodyCandidates( + sectionKey = section.sectionKey, + body = section.body, + representation = + if (section.sectionKey in rawSectionKeys) { + InspectorBodySearchRepresentation.RAW + } else { + InspectorBodySearchRepresentation.FORMATTED + }, + ) + } } } val networkMatches = diff --git a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorDetailSearchTest.kt b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorDetailSearchTest.kt index 08143a3..386ca47 100644 --- a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorDetailSearchTest.kt +++ b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorDetailSearchTest.kt @@ -238,7 +238,12 @@ class InspectorDetailSearchTest { @Test fun `network search defaults to the two bodies and to keys plus values`() { assertEquals( - InspectorExchangeSection.keysOf(setOf(InspectorExchangeSection.PRIMARY_BODY, InspectorExchangeSection.SECONDARY_BODY)), + InspectorExchangeSection.keysOf( + setOf( + InspectorExchangeSection.PRIMARY_BODY, + InspectorExchangeSection.SECONDARY_BODY, + ), + ), NetworkDetailSearchOptions.defaultSectionKeys, ) assertEquals(InspectorSearchMode.KEYS_AND_VALUES, NetworkDetailSearchOptions.defaultMode) From 1d1524698756f10af2ff1ea7af2e500de8a63686 Mon Sep 17 00:00:00 2001 From: shakibuzzaman Date: Tue, 18 Aug 2026 06:50:40 +0600 Subject: [PATCH 13/20] refactor: clear the detekt findings the search feature introduced Exempts @Composable from LongParameterList/LongMethod (Compose cannot satisfy either without hurting the code); the complexity rules stay on and the InspectorObserveDetailScreen/resolveNetworkDetailSection hot spots are split up. --- .../buildlogic/QualityConventionPlugin.kt | 3 + config/detekt/detekt.yml | 9 + .../ui/compose/InspectorDetailSearch.kt | 88 --- .../compose/InspectorJsonSearchCandidates.kt | 72 +++ .../ui/compose/InspectorObserveDetail.kt | 506 +++++++++++------- 5 files changed, 389 insertions(+), 289 deletions(-) create mode 100644 config/detekt/detekt.yml create mode 100644 sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorJsonSearchCandidates.kt diff --git a/build-logic/convention-quality/src/main/kotlin/io/devconsole/buildlogic/QualityConventionPlugin.kt b/build-logic/convention-quality/src/main/kotlin/io/devconsole/buildlogic/QualityConventionPlugin.kt index 0b35dfb..a48b702 100644 --- a/build-logic/convention-quality/src/main/kotlin/io/devconsole/buildlogic/QualityConventionPlugin.kt +++ b/build-logic/convention-quality/src/main/kotlin/io/devconsole/buildlogic/QualityConventionPlugin.kt @@ -26,6 +26,9 @@ class QualityConventionPlugin : Plugin { extensions.configure { buildUponDefaultConfig = true autoCorrect = false + // Supplements the defaults: exempts @Composable from the two size rules that + // Compose cannot satisfy without hurting the code. See the file for the reasoning. + config.setFrom(rootProject.file("config/detekt/detekt.yml")) // Modules had ~3000 pre-existing findings from before detekt was turned on. // The baseline freezes those as accepted debt so detekt only fails builds on // NEW findings introduced from here on; regenerate a module's baseline via diff --git a/config/detekt/detekt.yml b/config/detekt/detekt.yml new file mode 100644 index 0000000..49e9c2f --- /dev/null +++ b/config/detekt/detekt.yml @@ -0,0 +1,9 @@ +complexity: + LongParameterList: + # A composable receives its state and callbacks as parameters; bundling them into a + # parameter object costs recomposition stability, so this threshold does not fit Compose. + ignoreAnnotated: ['Composable'] + LongMethod: + # A composable body is a layout tree. Splitting one purely to hit a line count + # fragments the UI description without making it clearer. + ignoreAnnotated: ['Composable'] diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearch.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearch.kt index b068c1e..9434a94 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearch.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearch.kt @@ -257,91 +257,3 @@ internal fun searchInspectorBodyCandidates( } is InspectorDetailSectionBody.Bars, is InspectorDetailSectionBody.Empty -> emptyList() } - -private fun jsonSearchCandidates( - sectionKey: String, - root: JsonValue, -): List = - buildList { - appendJsonSearchCandidates(this, sectionKey, root, path = "$") - } - -private fun appendJsonSearchCandidates( - candidates: MutableList, - sectionKey: String, - value: JsonValue, - path: String, -) { - when (value) { - is JsonValue.Obj -> - value.entries.forEachIndexed { index, (key, child) -> - val childPath = "$path/$index:$key" - candidates += - InspectorSearchCandidate( - sectionKey = sectionKey, - itemId = childPath, - field = InspectorSearchField.KEY, - text = key.jsonQuoted(), - path = childPath, - ancestorPaths = jsonAncestorPaths(childPath), - ) - appendJsonSearchCandidates(candidates, sectionKey, child, childPath) - } - is JsonValue.Arr -> - value.items.forEachIndexed { index, child -> - appendJsonSearchCandidates(candidates, sectionKey, child, "$path[$index]") - } - is JsonValue.Str -> - candidates += - InspectorSearchCandidate( - sectionKey = sectionKey, - itemId = path, - field = InspectorSearchField.VALUE, - text = value.value.jsonQuoted(), - path = path, - ancestorPaths = jsonAncestorPaths(path), - ) - is JsonValue.Num -> - candidates += - InspectorSearchCandidate( - sectionKey = sectionKey, - itemId = path, - field = InspectorSearchField.VALUE, - text = value.raw, - path = path, - ancestorPaths = jsonAncestorPaths(path), - ) - is JsonValue.Bool -> - candidates += - InspectorSearchCandidate( - sectionKey = sectionKey, - itemId = path, - field = InspectorSearchField.VALUE, - text = value.value.toString(), - path = path, - ancestorPaths = jsonAncestorPaths(path), - ) - JsonValue.Null -> - candidates += - InspectorSearchCandidate( - sectionKey = sectionKey, - itemId = path, - field = InspectorSearchField.VALUE, - text = "null", - path = path, - ancestorPaths = jsonAncestorPaths(path), - ) - } -} - -private fun jsonAncestorPaths(path: String): List { - if (path == "$") return emptyList() - val ancestors = mutableListOf() - var cursor = path - while (cursor != "$") { - val separator = maxOf(cursor.lastIndexOf('/'), cursor.lastIndexOf('[')) - cursor = if (separator <= 0) "$" else cursor.substring(0, separator) - ancestors += cursor - } - return ancestors.asReversed() -} diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorJsonSearchCandidates.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorJsonSearchCandidates.kt new file mode 100644 index 0000000..8d46311 --- /dev/null +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorJsonSearchCandidates.kt @@ -0,0 +1,72 @@ +/** + * @author Shakib + * @since 18/08/26 + */ +package io.devconsole.ui.compose + +internal fun jsonSearchCandidates( + sectionKey: String, + root: JsonValue, +): List = + buildList { + appendJsonSearchCandidates(this, sectionKey, root, path = "$") + } + +private fun appendJsonSearchCandidates( + candidates: MutableList, + sectionKey: String, + value: JsonValue, + path: String, +) { + when (value) { + is JsonValue.Obj -> + value.entries.forEachIndexed { index, (key, child) -> + val childPath = "$path/$index:$key" + candidates += + InspectorSearchCandidate( + sectionKey = sectionKey, + itemId = childPath, + field = InspectorSearchField.KEY, + text = key.jsonQuoted(), + path = childPath, + ancestorPaths = jsonAncestorPaths(childPath), + ) + appendJsonSearchCandidates(candidates, sectionKey, child, childPath) + } + is JsonValue.Arr -> + value.items.forEachIndexed { index, child -> + appendJsonSearchCandidates(candidates, sectionKey, child, "$path[$index]") + } + is JsonValue.Str -> candidates += jsonLeafSearchCandidate(sectionKey, path, value.value.jsonQuoted()) + is JsonValue.Num -> candidates += jsonLeafSearchCandidate(sectionKey, path, value.raw) + is JsonValue.Bool -> candidates += jsonLeafSearchCandidate(sectionKey, path, value.value.toString()) + JsonValue.Null -> candidates += jsonLeafSearchCandidate(sectionKey, path, "null") + } +} + +/** Builds a VALUE candidate for a JSON scalar leaf at [path]. */ +private fun jsonLeafSearchCandidate( + sectionKey: String, + path: String, + text: String, +): InspectorSearchCandidate = + InspectorSearchCandidate( + sectionKey = sectionKey, + itemId = path, + field = InspectorSearchField.VALUE, + text = text, + path = path, + ancestorPaths = jsonAncestorPaths(path), + ) + +private fun jsonAncestorPaths(path: String): List { + if (path == "$") return emptyList() + val ancestors = mutableListOf() + var cursor = path + while (cursor != "$") { + val separator = maxOf(cursor.lastIndexOf('/'), cursor.lastIndexOf('[')) + cursor = if (separator <= 0) "$" else cursor.substring(0, separator) + ancestors += cursor + } + return ancestors.asReversed() +} diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt index 375f9e7..1b1260d 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt @@ -210,58 +210,242 @@ private fun resolveDetailSection( ) } +/** The per-section slice of the screen's search state that [resolveNetworkDetailSection] reads. */ +private data class NetworkSectionSearch( + val query: String, + val matches: List, + val searchable: Boolean, +) { + val hasQuery: Boolean get() = query.trim().isNotEmpty() + + val showsMatchCount: Boolean get() = hasQuery && searchable +} + +private fun networkSectionMeta( + search: NetworkSectionSearch, + expanded: Boolean, + total: Int, +): String = + when { + search.showsMatchCount && search.matches.isEmpty() -> "no match" + search.showsMatchCount -> "${search.matches.size} match${if (search.matches.size == 1) "" else "es"}" + total == 0 -> "" + expanded -> total.toString() + else -> "$total line${if (total == 1) "" else "s"}" + } + /** Network detail resolver: preserves every original body shape and decorates it with match metadata. */ private fun resolveNetworkDetailSection( spec: InspectorDetailSectionSpec, - query: String, + search: NetworkSectionSearch, openState: Map, colors: DevConsoleColors, - matches: List, - searchable: Boolean, ): ResolvedDetailSection { - val hasQuery = query.trim().isNotEmpty() - val total = detailBodyItemCount(spec.body) - val expanded = if (hasQuery && matches.isNotEmpty()) true else openState[spec.key] == true - val meta = - when { - hasQuery && searchable -> - if (matches.isNotEmpty()) { - "${matches.size} match${if (matches.size == 1) "" else "es"}" - } else { - "no match" + val expanded = if (search.hasQuery && search.matches.isNotEmpty()) true else openState[spec.key] == true + val emptyMessage = if (expanded) (spec.body as? InspectorDetailSectionBody.Empty)?.text else null + return ResolvedDetailSection( + expanded = expanded, + hits = search.matches.size, + meta = networkSectionMeta(search, expanded, detailBodyItemCount(spec.body)), + metaColor = if (search.showsMatchCount && search.matches.isNotEmpty()) colors.signal else colors.text3, + body = if (expanded && emptyMessage == null) spec.body else null, + emptyMessage = emptyMessage, + searchMatches = search.matches, + ) +} + +/** Everything the detail screen derives from the active query, resolved once per recomposition. */ +private data class ObserveDetailSearch( + val matches: List, + val activeMatchOrdinal: Int, + val resolved: List>, + val totalHits: Int, +) + +@Composable +private fun rememberObserveDetailSearch( + sections: List, + searchableSectionBodies: List, + searchableSectionKeys: Set, + rawSectionKeys: Set, + selectedKeys: Set, + searchMode: InspectorSearchMode, + query: String, + searching: Boolean, + currentMatchOrdinal: Int, + openState: Map, + colors: DevConsoleColors, +): ObserveDetailSearch { + val hasQuery = searching && query.isNotBlank() + val candidates = + remember(searchableSectionBodies, rawSectionKeys, hasQuery) { + if (!hasQuery) { + emptyList() + } else { + searchableSectionBodies.flatMap { section -> + searchInspectorBodyCandidates( + sectionKey = section.sectionKey, + body = section.body, + representation = bodySearchRepresentation(section.sectionKey in rawSectionKeys), + ) } - expanded -> if (total > 0) total.toString() else "" - else -> if (total > 0) "$total line${if (total == 1) "" else "s"}" else "" + } } - val metaColor = - if (hasQuery && searchable) { - if (matches.isNotEmpty()) colors.signal else colors.text3 - } else { - colors.text3 + val matches = + remember(candidates, query, selectedKeys, searchMode, hasQuery) { + if (hasQuery) searchInspectorCandidates(candidates, query, selectedKeys, searchMode) else emptyList() } - if (!expanded) { - return ResolvedDetailSection( - expanded = false, - hits = matches.size, - meta = meta, - metaColor = metaColor, - body = null, - emptyMessage = null, - searchMatches = matches, - ) - } - val emptyMessage = (spec.body as? InspectorDetailSectionBody.Empty)?.text - return ResolvedDetailSection( - expanded = true, - hits = matches.size, - meta = meta, - metaColor = metaColor, - body = if (emptyMessage == null) spec.body else null, - emptyMessage = emptyMessage, - searchMatches = matches, + val activeMatchOrdinal = if (matches.isEmpty()) 0 else currentMatchOrdinal.coerceIn(0, matches.lastIndex) + val resolved = + sections.map { spec -> + val resolvedSection = + if (searching) { + resolveNetworkDetailSection( + spec = spec, + search = + NetworkSectionSearch( + query = query, + matches = matches.filter { it.sectionKey == spec.key }, + searchable = spec.key in searchableSectionKeys, + ), + openState = openState, + colors = colors, + ) + } else { + resolveDetailSection(spec, query, openState, colors) + } + spec to resolvedSection + } + return ObserveDetailSearch( + matches = matches, + activeMatchOrdinal = activeMatchOrdinal, + resolved = resolved, + totalHits = if (searching) matches.size else resolved.sumOf { (_, section) -> section.hits }, + ) +} + +private fun bodySearchRepresentation(raw: Boolean): InspectorBodySearchRepresentation = + if (raw) InspectorBodySearchRepresentation.RAW else InspectorBodySearchRepresentation.FORMATTED + +/** The find field plus its match counter, stepping arrows, and scope chip. */ +@Composable +private fun ObserveDetailSearchBar( + query: String, + onQueryChange: (String) -> Unit, + searching: Boolean, + matchCount: Int, + activeMatchOrdinal: Int, + totalHits: Int, + onOrdinalChange: (Int) -> Unit, + onOpenOptions: () -> Unit, + scopeLabel: String?, + placeholder: String, + modifier: Modifier = Modifier, +) { + InspectorDetailSearchField( + query = query, + onQueryChange = onQueryChange, + matchLabel = detailSearchMatchLabel(query, searching, matchCount, activeMatchOrdinal, totalHits), + onPrevious = + if (searching) { + { onOrdinalChange(previousInspectorMatchIndex(activeMatchOrdinal, matchCount)) } + } else { + null + }, + onNext = + if (searching) { + { onOrdinalChange(nextInspectorMatchIndex(activeMatchOrdinal, matchCount)) } + } else { + null + }, + navigationEnabled = matchCount > 0, + onOpenOptions = if (searching) onOpenOptions else null, + scopeLabel = scopeLabel, + modifier = modifier, + placeholder = placeholder, ) } +/** The Raw/Formatted toggle only exists on kinds that carry search options. */ +private fun formattableShowRaw( + spec: InspectorDetailSectionSpec, + searching: Boolean, + rawSectionKeys: Set, +): Boolean? = + (spec.body as? InspectorDetailSectionBody.Formattable) + ?.takeIf { searching } + ?.let { body -> body.formatted == null || spec.key in rawSectionKeys } + +/** The section keys a kind declares as searchable; empty for kinds with no search options. */ +private fun InspectorDetailSearchOptions?.searchableSectionKeys(): Set = + this?.sections?.mapTo(mutableSetOf()) { it.key }.orEmpty() + +private fun toggledRawSectionKeys( + current: List, + key: String, + showRaw: Boolean, +): List = if (showRaw) (current + key).distinct() else current.filterNot { it == key } + +/** Only these two body shapes have a full-screen reader. */ +private fun InspectorDetailSectionBody?.isFullScreenCapable(): Boolean = + this is InspectorDetailSectionBody.Code || this is InspectorDetailSectionBody.Formattable + +private fun detailSearchMatchLabel( + query: String, + searching: Boolean, + matchCount: Int, + activeMatchOrdinal: Int, + totalHits: Int, +): String = + when { + query.isBlank() -> "" + searching -> "${if (matchCount == 0) 0 else activeMatchOrdinal + 1}/$totalHits" + else -> "$totalHits match${if (totalHits == 1) "" else "es"}" + } + +/** The full-screen reader for whichever section the user expanded, per its body shape. */ +@Composable +private fun ObserveDetailFullScreenOverlay( + spec: InspectorDetailSectionSpec, + section: ResolvedDetailSection, + showRaw: Boolean?, + onShowRawChange: ((Boolean) -> Unit)?, + activeMatchOrdinal: Int, + onDismiss: () -> Unit, + modifier: Modifier = Modifier, +) { + val copyDescription = spec.copyDescription ?: "Copy ${spec.label}" + when (val body = section.body) { + is InspectorDetailSectionBody.Code -> + InspectorCodeFullScreenOverlay( + title = spec.label, + lines = body.lines, + onDismiss = onDismiss, + modifier = modifier, + sectionKey = spec.key, + searchMatches = section.searchMatches, + currentMatchOrdinal = activeMatchOrdinal, + onCopy = spec.onCopy, + copyContentDescription = copyDescription, + ) + is InspectorDetailSectionBody.Formattable -> + InspectorFormattableFullScreenOverlay( + title = spec.label, + body = body, + onDismiss = onDismiss, + showRaw = showRaw, + onShowRawChange = onShowRawChange, + modifier = modifier, + sectionKey = spec.key, + searchMatches = section.searchMatches, + currentMatchOrdinal = activeMatchOrdinal, + onCopy = spec.onCopy, + copyContentDescription = copyDescription, + ) + else -> Unit + } +} + private fun detailBodyItemCount(body: InspectorDetailSectionBody): Int = when (body) { is InspectorDetailSectionBody.KeyValues -> body.entries.size @@ -336,10 +520,7 @@ private fun InspectorDetailSectionCard( * action bar. [resetKey] identifies which capture is open (e.g. a transaction id) so the find query * and each section's manual open/closed state reset when a different capture is opened. Both the * header's back button and the system back gesture close it via [onBack]. - * - * LongMethod: the full-screen code overlay branch pushed this a couple lines past the default budget. */ -@Suppress("LongParameterList", "LongMethod") @Composable internal fun InspectorObserveDetailScreen( resetKey: Any, @@ -372,57 +553,37 @@ internal fun InspectorObserveDetailScreen( val colors = DevConsoleTheme.colors val selectedKeys = remember(selectedSectionKeys) { selectedSectionKeys.toSet() } val rawSectionKeys = remember(rawFormattableSectionKeys) { rawFormattableSectionKeys.toSet() } - val searchableSectionKeys = - remember(searchOptions) { searchOptions?.sections?.mapTo(mutableSetOf()) { it.key }.orEmpty() } + val searchableSectionKeys = remember(searchOptions) { searchOptions.searchableSectionKeys() } val searchableSectionBodies = inspectorSearchSectionBodies(sections, searchableSectionKeys) - val hasNetworkQuery = searchOptions != null && query.isNotBlank() - val networkSearchCandidates = - remember(searchableSectionBodies, rawSectionKeys, hasNetworkQuery) { - if (!hasNetworkQuery) { - emptyList() - } else { - searchableSectionBodies.flatMap { section -> - searchInspectorBodyCandidates( - sectionKey = section.sectionKey, - body = section.body, - representation = - if (section.sectionKey in rawSectionKeys) { - InspectorBodySearchRepresentation.RAW - } else { - InspectorBodySearchRepresentation.FORMATTED - }, - ) - } - } - } - val networkMatches = - remember(networkSearchCandidates, query, selectedKeys, searchMode, hasNetworkQuery) { - if (hasNetworkQuery) { - searchInspectorCandidates(networkSearchCandidates, query, selectedKeys, searchMode) - } else { - emptyList() - } - } - val activeMatchOrdinal = - if (networkMatches.isEmpty()) 0 else currentMatchOrdinal.coerceIn(0, networkMatches.lastIndex) - val resolved = - sections.map { spec -> - if (searchOptions != null) { - val sectionMatches = networkMatches.filter { it.sectionKey == spec.key } - spec to - resolveNetworkDetailSection( - spec = spec, - query = query, - openState = openState, - colors = colors, - matches = sectionMatches, - searchable = spec.key in searchableSectionKeys, - ) - } else { - spec to resolveDetailSection(spec, query, openState, colors) + val searching = searchOptions != null + // Formattable bodies only offer the raw/formatted toggle on the kinds that carry search options. + val onShowRawChange: ((String, Boolean) -> Unit)? = + if (searching) { + { key, showRaw -> + rawFormattableSectionKeys = toggledRawSectionKeys(rawFormattableSectionKeys, key, showRaw) + currentMatchOrdinal = 0 } + } else { + null } - val totalHits = if (searchOptions != null) networkMatches.size else resolved.sumOf { (_, section) -> section.hits } + val search = + rememberObserveDetailSearch( + sections = sections, + searchableSectionBodies = searchableSectionBodies, + searchableSectionKeys = searchableSectionKeys, + rawSectionKeys = rawSectionKeys, + selectedKeys = selectedKeys, + searchMode = searchMode, + query = query, + searching = searching, + currentMatchOrdinal = currentMatchOrdinal, + openState = openState, + colors = colors, + ) + val networkMatches = search.matches + val activeMatchOrdinal = search.activeMatchOrdinal + val resolved = search.resolved + val totalHits = search.totalHits // Which section's code block (if any) is showing full-screen. // Bundle-safe on its own (a String key), and the lines it needs are re-derived from `resolved` @@ -436,57 +597,18 @@ internal fun InspectorObserveDetailScreen( BackHandler(onBack = onBack) - if (fullScreenSection != null) { + if (fullScreenSection != null && fullScreenSection.second.body.isFullScreenCapable()) { val (spec, section) = fullScreenSection - val body = section.body - if (body is InspectorDetailSectionBody.Code) { - InspectorCodeFullScreenOverlay( - title = spec.label, - lines = body.lines, - onDismiss = { fullScreenSectionKey = null }, - modifier = modifier.fillMaxSize(), - sectionKey = spec.key, - searchMatches = section.searchMatches, - currentMatchOrdinal = activeMatchOrdinal, - onCopy = spec.onCopy, - copyContentDescription = spec.copyDescription ?: "Copy ${spec.label}", - ) - return - } - if (body is InspectorDetailSectionBody.Formattable) { - InspectorFormattableFullScreenOverlay( - title = spec.label, - body = body, - onDismiss = { fullScreenSectionKey = null }, - showRaw = - if (searchOptions != null) { - body.formatted == null || spec.key in rawSectionKeys - } else { - null - }, - onShowRawChange = - if (searchOptions != null) { - { showRaw -> - rawFormattableSectionKeys = - if (showRaw) { - (rawFormattableSectionKeys + spec.key).distinct() - } else { - rawFormattableSectionKeys.filterNot { it == spec.key } - } - currentMatchOrdinal = 0 - } - } else { - null - }, - modifier = modifier.fillMaxSize(), - sectionKey = spec.key, - searchMatches = section.searchMatches, - currentMatchOrdinal = activeMatchOrdinal, - onCopy = spec.onCopy, - copyContentDescription = spec.copyDescription ?: "Copy ${spec.label}", - ) - return - } + ObserveDetailFullScreenOverlay( + spec = spec, + section = section, + showRaw = formattableShowRaw(spec, searching, rawSectionKeys), + onShowRawChange = onShowRawChange?.let { change -> { showRaw -> change(spec.key, showRaw) } }, + activeMatchOrdinal = activeMatchOrdinal, + onDismiss = { fullScreenSectionKey = null }, + modifier = modifier.fillMaxSize(), + ) + return } InspectorDetailScaffold( @@ -504,37 +626,21 @@ internal fun InspectorObserveDetailScreen( onBack = onBack, actions = header.actions, ) - InspectorDetailSearchField( + ObserveDetailSearchBar( query = query, onQueryChange = { query = it currentMatchOrdinal = 0 }, - matchLabel = - if (query.isBlank()) { - "" - } else if (searchOptions != null) { - "${if (networkMatches.isEmpty()) 0 else activeMatchOrdinal + 1}/$totalHits" - } else { - "$totalHits match${if (totalHits == 1) "" else "es"}" - }, - onPrevious = - if (searchOptions != null) { - { currentMatchOrdinal = previousInspectorMatchIndex(activeMatchOrdinal, networkMatches.size) } - } else { - null - }, - onNext = - if (searchOptions != null) { - { currentMatchOrdinal = nextInspectorMatchIndex(activeMatchOrdinal, networkMatches.size) } - } else { - null - }, - navigationEnabled = networkMatches.isNotEmpty(), - onOpenOptions = if (searchOptions != null) ({ searchOptionsVisible = true }) else null, + searching = searching, + matchCount = networkMatches.size, + activeMatchOrdinal = activeMatchOrdinal, + totalHits = totalHits, + onOrdinalChange = { currentMatchOrdinal = it }, + onOpenOptions = { searchOptionsVisible = true }, scopeLabel = searchOptions?.let { inspectorSearchScopeSummary(it, selectedKeys) }, - modifier = Modifier.padding(top = 12.dp), placeholder = searchPlaceholder, + modifier = Modifier.padding(top = 12.dp), ) }, footer = { InspectorDetailFooterBar(footerActions) }, @@ -543,48 +649,46 @@ internal fun InspectorObserveDetailScreen( InspectorDetailSectionCard( spec = spec, resolved = section, - currentMatchOrdinal = if (searchOptions != null) activeMatchOrdinal else null, - formattableShowRaw = - if (searchOptions != null) { - (spec.body as? InspectorDetailSectionBody.Formattable)?.let { body -> - body.formatted == null || spec.key in rawSectionKeys - } - } else { - null - }, + currentMatchOrdinal = if (searching) activeMatchOrdinal else null, + formattableShowRaw = formattableShowRaw(spec, searching, rawSectionKeys), onFormattableShowRawChange = - if (searchOptions != null) { - { showRaw -> - rawFormattableSectionKeys = - if (showRaw) { - (rawFormattableSectionKeys + spec.key).distinct() - } else { - rawFormattableSectionKeys.filterNot { it == spec.key } - } - currentMatchOrdinal = 0 - } - } else { - null - }, + onShowRawChange?.let { change -> { showRaw -> change(spec.key, showRaw) } }, onToggle = { openState[spec.key] = !section.expanded }, onExpandCodeFullScreen = { key -> fullScreenSectionKey = key }, ) } } - if (searchOptionsVisible && searchOptions != null) { - InspectorDetailSearchOptionsSheet( - options = searchOptions, - selectedSectionKeys = selectedKeys, - mode = searchMode, - onDismiss = { searchOptionsVisible = false }, - onApply = { newKeys, newMode -> - selectedSectionKeys = newKeys.toList() - searchMode = newMode - currentMatchOrdinal = 0 - searchOptionsVisible = false - }, - ) - } + ObserveDetailSearchOptionsSheet( + options = searchOptions.takeIf { searchOptionsVisible }, + selectedSectionKeys = selectedKeys, + mode = searchMode, + onDismiss = { searchOptionsVisible = false }, + onApply = { newKeys, newMode -> + selectedSectionKeys = newKeys.toList() + searchMode = newMode + currentMatchOrdinal = 0 + searchOptionsVisible = false + }, + ) +} + +/** Renders the scope/mode sheet only while [options] is non-null, i.e. while the chip has it open. */ +@Composable +private fun ObserveDetailSearchOptionsSheet( + options: InspectorDetailSearchOptions?, + selectedSectionKeys: Set, + mode: InspectorSearchMode, + onDismiss: () -> Unit, + onApply: (Set, InspectorSearchMode) -> Unit, +) { + if (options == null) return + InspectorDetailSearchOptionsSheet( + options = options, + selectedSectionKeys = selectedSectionKeys, + mode = mode, + onDismiss = onDismiss, + onApply = onApply, + ) } /** Everything [InspectorObserveDetailScreen] needs for one capture, built by the per-kind `*DetailContent` builders. */ From 6dc58582ef4d009ea2422e95e8d89fd4d5dfbee3 Mon Sep 17 00:00:00 2001 From: shakibuzzaman Date: Tue, 18 Aug 2026 07:14:32 +0600 Subject: [PATCH 14/20] fix: restore the AUTO binding default and cover the legacy coordinate A stale LAN assertion from before the 1.2.1 merge failed :sdk:api:test, and startBrowser's KDoc claimed a binding default the code has not used since 1.2.1. --- CHANGELOG.md | 17 ++++ .../buildlogic/PublishingConventionPlugin.kt | 2 + docs/PUBLISHING.md | 8 +- ...onsoleVariantPolicyPluginFunctionalTest.kt | 90 ++++++++++++++++++- .../devconsole/api/DevConsoleContractTest.kt | 5 -- .../main/kotlin/io/devconsole/DevConsole.kt | 9 +- .../ui/compose/InspectorObserveDetail.kt | 6 +- .../compose/InspectorObserveDetailMetaTest.kt | 81 +++++++++++++++++ 8 files changed, 204 insertions(+), 14 deletions(-) create mode 100644 sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorObserveDetailMetaTest.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 0cf0e85..1da2ddd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,23 @@ joined this list.) ## 1.2.2 — 2026-08-17 +### Added + +- **Search inside a capture got scoping, stepping, and a full-screen reader.** Every detail screen + already filtered and highlighted as you typed; network captures now add arrows that step through + hits one at a time with a running `3/17` counter, a **Search in** chip that picks which sections + to match (defaulting to the request and response bodies), and a choice of matching field names, + values, or both. Any body can be expanded full-screen with a Formatted/Raw switch, a line count, + and a copy button. Note that matching *names* only works where the body has names — JSON does, a + raw or XML body does not — which is why the default matches both. All of this is `internal`; no + public API was added. + +### Fixed + +- **Simple mode never actually hid the dashboard's metric strips.** The rule was written against + `.metrics-strip` while the markup has always emitted `.metric-strip`, so the selector matched + nothing and Simple mode showed the full metric row regardless. + ### Changed - **JitPack is now the only distribution channel for the library artifacts.** Maven Central 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 7b94242..8383315 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 @@ -71,6 +71,8 @@ class PublishingConventionPlugin : Plugin { } private companion object { + // The POM group. JitPack rewrites it to com.github.devconsole-android.DevConsole when it + // serves a build, so consumers name that group, not this one. const val MAVEN_GROUP = "io.github.devconsole-android" const val SDK_VERSION = "1.2.2" const val PROJECT_URL = "https://github.com/devconsole-android/DevConsole" diff --git a/docs/PUBLISHING.md b/docs/PUBLISHING.md index ea81229..2913f6e 100644 --- a/docs/PUBLISHING.md +++ b/docs/PUBLISHING.md @@ -28,7 +28,13 @@ To verify the whole pipeline locally before tagging: ./gradlew publishToMavenLocal ``` -That produces exactly what JitPack produces. Check a real JitPack build at +That produces the same artifacts JitPack does, with one difference that matters for a smoke test: +the POM group stays `io.github.devconsole-android`, because JitPack rewrites the group to +`com.github.devconsole-android.DevConsole` when it serves a build. So a local consumer test against +`mavenLocal()` must name `io.github.devconsole-android:devconsole:` — the +`com.github.…` coordinates in this document only resolve from jitpack.io. + +Check a real JitPack build at `https://jitpack.io/api/builds/com.github.devconsole-android/DevConsole`. ### Bumping the version 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 64b840b..aa92cdc 100644 --- a/gradle-plugin/src/test/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPluginFunctionalTest.kt +++ b/gradle-plugin/src/test/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPluginFunctionalTest.kt @@ -19,6 +19,31 @@ class DevConsoleVariantPolicyPluginFunctionalTest { System.getenv("ANDROID_HOME") ?: System.getenv("ANDROID_SDK_ROOT") ?: error("Set ANDROID_HOME or ANDROID_SDK_ROOT to run this functional test.") + /** + * Plants an empty jar + POM for [group]:[artifact]:[version] in a local repo the fixture reads, + * so a coordinate-matching test never depends on the real artifact existing remotely. + */ + private fun addStubCoordinate( + group: String, + artifact: String, + version: String, + ) { + val dir = File(projectDir.root, "stub-repo/${group.replace('.', '/')}/$artifact/$version") + dir.mkdirs() + File(dir, "$artifact-$version.jar").writeBytes(EMPTY_JAR_BYTES) + File(dir, "$artifact-$version.pom").writeText( + """ + + 4.0.0 + $group + $artifact + $version + jar + + """.trimIndent(), + ) + } + private fun writeFixture( devConsoleBlock: String, extraBuildScript: String = "", @@ -34,6 +59,7 @@ class DevConsoleVariantPolicyPluginFunctionalTest { ) { File(projectDir.root, "local.properties") .writeText("sdk.dir=${androidSdkDir().replace("\\", "\\\\")}\n") + File(projectDir.root, "gradle.properties").writeText("android.useAndroidX=true\n") File(projectDir.root, "settings.gradle.kts").writeText( """ pluginManagement { @@ -42,7 +68,12 @@ class DevConsoleVariantPolicyPluginFunctionalTest { dependencyResolutionManagement { // jitpack.io serves the auto-wired devconsole coordinates, so any fixture that // resolves a runtime classpath needs it -- same as a real consumer. - repositories { google(); mavenCentral(); maven { url = uri("https://jitpack.io") } } + repositories { + maven { url = uri("${'$'}{rootDir}/stub-repo") } + google() + mavenCentral() + maven { url = uri("https://jitpack.io") } + } } rootProject.name = "fixture" """.trimIndent(), @@ -865,6 +896,56 @@ class DevConsoleVariantPolicyPluginFunctionalTest { ) } + @Test + fun `a legacy Maven Central coordinate still trips the declared-dependency check`() { + addStubCoordinate("io.github.devconsole-android", "devconsole", "1.2.1") + writeFixture( + devConsoleBlock = "autoWireDependencies.set(false)", + extraBuildScript = + """ + dependencies { + add("releaseImplementation", "io.github.devconsole-android:devconsole:1.2.1") + } + """.trimIndent(), + ) + + val result = runner("verifyDevConsoleProtectedArtifacts").buildAndFail() + + // The pre-JitPack group must keep failing a protected variant: hosts that have not migrated + // their coordinates still depend on this check to keep the full runtime out of release. + assertTrue(result.output, result.output.contains("Protected variants contain the full DevConsole runtime")) + // The declared-dependency entry carries no version and no "(resolved)" suffix -- asserting it + // specifically keeps the transitive-regex path from satisfying this test on its own. + assertTrue( + result.output, + Regex("release -> io\\.github\\.devconsole-android:devconsole(,|\\s*$)", RegexOption.MULTILINE) + .containsMatchIn(result.output), + ) + } + + @Test + fun `the JitPack coordinate trips the declared-dependency check`() { + addStubCoordinate("com.github.devconsole-android.DevConsole", "devconsole", "1.2.2") + writeFixture( + devConsoleBlock = "autoWireDependencies.set(false)", + extraBuildScript = + """ + dependencies { + add("releaseImplementation", "com.github.devconsole-android.DevConsole:devconsole:1.2.2") + } + """.trimIndent(), + ) + + val result = runner("verifyDevConsoleProtectedArtifacts").buildAndFail() + + assertTrue(result.output, result.output.contains("Protected variants contain the full DevConsole runtime")) + assertTrue( + result.output, + Regex("release -> com\\.github\\.devconsole-android\\.DevConsole:devconsole(,|\\s*$)", RegexOption.MULTILINE) + .containsMatchIn(result.output), + ) + } + @Test fun `declaring only an add-on coordinate still auto-wires the core runtime`() { writeFixture( @@ -893,4 +974,11 @@ class DevConsoleVariantPolicyPluginFunctionalTest { assertTrue(result.output, result.output.contains("com.github.devconsole-android.DevConsole:devconsole:1.2.2")) assertTrue(result.output, result.output.contains("io.github.devconsole-android:devconsole-ui-compose")) } + + private companion object { + /** A valid, empty zip -- enough for Gradle to accept the stub as a jar artifact. */ + val EMPTY_JAR_BYTES = + byteArrayOf(0x50, 0x4B, 0x05, 0x06) + ByteArray(18) + } + } diff --git a/sdk/api/src/test/kotlin/io/devconsole/api/DevConsoleContractTest.kt b/sdk/api/src/test/kotlin/io/devconsole/api/DevConsoleContractTest.kt index 8764f2f..bcc6a04 100644 --- a/sdk/api/src/test/kotlin/io/devconsole/api/DevConsoleContractTest.kt +++ b/sdk/api/src/test/kotlin/io/devconsole/api/DevConsoleContractTest.kt @@ -61,11 +61,6 @@ class DevConsoleContractTest { assertEquals(BindingMode.LOOPBACK, StartRequest(bindingMode = BindingMode.LOOPBACK).bindingMode) } - @Test - fun `default start request uses LAN binding`() { - assertEquals(BindingMode.LAN, StartRequest().bindingMode) - } - @Test fun `default configuration is valid and uses documented session and storage limits`() { val config = DevConsoleConfig.default() diff --git a/sdk/facade-shared/src/main/kotlin/io/devconsole/DevConsole.kt b/sdk/facade-shared/src/main/kotlin/io/devconsole/DevConsole.kt index 0baad30..0fc5305 100644 --- a/sdk/facade-shared/src/main/kotlin/io/devconsole/DevConsole.kt +++ b/sdk/facade-shared/src/main/kotlin/io/devconsole/DevConsole.kt @@ -110,11 +110,12 @@ object DevConsole { * value provides a default for it: `DevConsoleConfig.browserConfig.binding` governs only the * starts this method is not making -- the in-app inspector's More-screen Start button -- so a * host can configure each surface independently. See the KDoc on [io.devconsole.api.BindingMode] - * and [io.devconsole.api.BrowserBinding]. The default `StartRequest()` binds LAN; pass - * `bindingMode = BindingMode.LOOPBACK` explicitly for the safer ADB-only choice on an untrusted - * network. See `docs/THREAT_MODEL.md` at the repository root. + * and [io.devconsole.api.BrowserBinding]. The default `StartRequest()` binds + * [io.devconsole.api.BindingMode.AUTO], which prefers the device's network address and degrades + * to loopback rather than failing; pass `bindingMode = BindingMode.LOOPBACK` explicitly for the + * safer ADB-only choice on an untrusted network. See `docs/THREAT_MODEL.md` at the repository root. * - * @param request binding mode and port range for this start attempt. Defaults to LAN on + * @param request binding mode and port range for this start attempt. Defaults to AUTO on * `8080..8099`. * @return a [StartResult] -- [StartResult.Started] carries the bound [io.devconsole.api.BrowserEndpoint] * and the session [io.devconsole.api.AccessInfo] (the connect URL/code); every other variant is a diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt index 1b1260d..5d40109 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt @@ -211,7 +211,7 @@ private fun resolveDetailSection( } /** The per-section slice of the screen's search state that [resolveNetworkDetailSection] reads. */ -private data class NetworkSectionSearch( +internal data class NetworkSectionSearch( val query: String, val matches: List, val searchable: Boolean, @@ -221,7 +221,7 @@ private data class NetworkSectionSearch( val showsMatchCount: Boolean get() = hasQuery && searchable } -private fun networkSectionMeta( +internal fun networkSectionMeta( search: NetworkSectionSearch, expanded: Boolean, total: Int, @@ -390,7 +390,7 @@ private fun toggledRawSectionKeys( private fun InspectorDetailSectionBody?.isFullScreenCapable(): Boolean = this is InspectorDetailSectionBody.Code || this is InspectorDetailSectionBody.Formattable -private fun detailSearchMatchLabel( +internal fun detailSearchMatchLabel( query: String, searching: Boolean, matchCount: Int, diff --git a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorObserveDetailMetaTest.kt b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorObserveDetailMetaTest.kt new file mode 100644 index 0000000..e4a8f50 --- /dev/null +++ b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorObserveDetailMetaTest.kt @@ -0,0 +1,81 @@ +/** + * @author Shakib + * @since 18/08/26 + */ +package io.devconsole.ui.compose + +import org.junit.Assert.assertEquals +import org.junit.Test + +/** + * Locks the section-meta and match-label strings that the detail screen shows, so the extraction + * that split them out of InspectorObserveDetailScreen cannot drift. + */ +class InspectorObserveDetailMetaTest { + private fun search( + query: String = "id", + matchCount: Int = 0, + searchable: Boolean = true, + ) = NetworkSectionSearch( + query = query, + matches = + List(matchCount) { index -> + InspectorDetailSearchMatch( + ordinal = index, + sectionKey = "body", + itemId = "item$index", + field = InspectorSearchField.VALUE, + start = 0, + endExclusive = 1, + ) + }, + searchable = searchable, + ) + + @Test + fun `a searchable section with an active query reports its match count`() { + assertEquals("1 match", networkSectionMeta(search(matchCount = 1), expanded = true, total = 9)) + assertEquals("3 matches", networkSectionMeta(search(matchCount = 3), expanded = true, total = 9)) + assertEquals("no match", networkSectionMeta(search(matchCount = 0), expanded = true, total = 9)) + } + + @Test + fun `a section outside the search scope falls back to its line count`() { + val outOfScope = search(matchCount = 0, searchable = false) + assertEquals("4", networkSectionMeta(outOfScope, expanded = true, total = 4)) + assertEquals("4 lines", networkSectionMeta(outOfScope, expanded = false, total = 4)) + assertEquals("1 line", networkSectionMeta(outOfScope, expanded = false, total = 1)) + } + + /** An empty body reports nothing at all, expanded or not -- never "0" or "0 lines". */ + @Test + fun `an empty section reports no meta in either state`() { + val blank = search(query = "", searchable = false) + assertEquals("", networkSectionMeta(blank, expanded = true, total = 0)) + assertEquals("", networkSectionMeta(blank, expanded = false, total = 0)) + } + + @Test + fun `the match label counts hits on plain kinds and steps through them on searchable ones`() { + assertEquals( + "", + detailSearchMatchLabel("", searching = true, matchCount = 5, activeMatchOrdinal = 0, totalHits = 5), + ) + assertEquals( + "3/17", + detailSearchMatchLabel("id", searching = true, matchCount = 17, activeMatchOrdinal = 2, totalHits = 17), + ) + assertEquals( + "0/0", + detailSearchMatchLabel("id", searching = true, matchCount = 0, activeMatchOrdinal = 0, totalHits = 0), + ) + assertEquals( + "1 match", + detailSearchMatchLabel("id", searching = false, matchCount = 0, activeMatchOrdinal = 0, totalHits = 1), + ) + assertEquals( + "2 matches", + detailSearchMatchLabel("id", searching = false, matchCount = 0, activeMatchOrdinal = 0, totalHits = 2), + ) + } +} From d85012231ea621373f5ae9034142ed5b07c9b372 Mon Sep 17 00:00:00 2001 From: shakibuzzaman Date: Tue, 18 Aug 2026 07:38:40 +0600 Subject: [PATCH 15/20] refactor: clear the review's minor findings Drops the test-only searchInspectorSections in favour of a helper the screen actually calls, and narrows a file-wide suppression to a @Preview exemption. --- config/detekt/detekt.yml | 6 ++++ docs/GETTING_STARTED_COMPOSE.md | 2 +- .../ui/compose/InspectorDetailSearch.kt | 32 ++----------------- .../InspectorDetailSearchOptionsSheet.kt | 2 +- .../devconsole/ui/compose/InspectorGlyphs.kt | 2 +- .../ui/compose/InspectorObserveDetail.kt | 31 ++++++++++++------ .../ui/compose/InspectorDetailSearchTest.kt | 23 ++++++------- 7 files changed, 42 insertions(+), 56 deletions(-) diff --git a/config/detekt/detekt.yml b/config/detekt/detekt.yml index 49e9c2f..8a43222 100644 --- a/config/detekt/detekt.yml +++ b/config/detekt/detekt.yml @@ -7,3 +7,9 @@ complexity: # A composable body is a layout tree. Splitting one purely to hit a line count # fragments the UI description without making it clearer. ignoreAnnotated: ['Composable'] + +style: + UnusedPrivateMember: + # @Preview functions are entry points for the IDE preview renderer; nothing in the source + # calls them, so the rule reports every one as dead. + ignoreAnnotated: ['Preview'] diff --git a/docs/GETTING_STARTED_COMPOSE.md b/docs/GETTING_STARTED_COMPOSE.md index b968436..93d202e 100644 --- a/docs/GETTING_STARTED_COMPOSE.md +++ b/docs/GETTING_STARTED_COMPOSE.md @@ -54,7 +54,7 @@ cover this module today; it is your responsibility to scope it to `debugImplemen 4. On a debuggable build you can skip explicit `initialize` entirely — the SDK auto-initializes, so state/timeline/capture are ready without any `Application.onCreate` boilerplate. The browser - server itself is never auto-started; call `DevConsole.startBrowser()` yourself (step 4) and read + server itself is never auto-started; call `DevConsole.startBrowser()` yourself (step 5) and read the connect URL from the returned `StartResult.Started.access` (or the device's More screen — the logged URL deliberately omits the credential fragment). Initialize explicitly when you need to pass configuration (state providers, flags, open triggers): diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearch.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearch.kt index 9434a94..5231a20 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearch.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearch.kt @@ -110,31 +110,6 @@ internal fun inspectorSearchSectionBodies( if (spec.key in searchableSectionKeys) InspectorSearchSectionBody(spec.key, spec.body) else null } -internal fun searchInspectorSections( - sections: List, - query: String, - selectedSectionKeys: Set, - mode: InspectorSearchMode, - representationForSection: (String) -> InspectorBodySearchRepresentation = { - InspectorBodySearchRepresentation.FORMATTED - }, -): List { - if (query.isBlank()) return emptyList() - return searchInspectorCandidates( - candidates = - sections.flatMap { spec -> - searchInspectorBodyCandidates( - sectionKey = spec.key, - body = spec.body, - representation = representationForSection(spec.key), - ) - }, - query = query, - selectedSectionKeys = selectedSectionKeys, - mode = mode, - ) -} - internal fun inspectorSearchScopeSummary( options: InspectorDetailSearchOptions, selectedSectionKeys: Set, @@ -157,11 +132,8 @@ private fun findInspectorQueryRanges( val ranges = mutableListOf() var start = 0 while (start <= text.length - query.length) { - val matchAt = - (start..text.length - query.length).firstOrNull { index -> - text.regionMatches(index, query, 0, query.length, ignoreCase = true) - } - ?: break + val matchAt = text.indexOf(query, start, ignoreCase = true) + if (matchAt < 0) break ranges += matchAt until (matchAt + query.length) start = matchAt + query.length } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearchOptionsSheet.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearchOptionsSheet.kt index a49065a..5f8286e 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearchOptionsSheet.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearchOptionsSheet.kt @@ -2,7 +2,7 @@ * @author Shakib * @since 17/08/26 */ -@file:Suppress("FunctionNaming", "MagicNumber", "UnusedPrivateMember") +@file:Suppress("FunctionNaming", "MagicNumber") @file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class) package io.devconsole.ui.compose 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 e1ef1b7..ce48adb 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 @@ -184,7 +184,7 @@ internal fun InspectorRoundIconButton( modifier .minimumInteractiveComponentSize() .size(size) - .alpha(if (enabled) 1f else 0.45f) + .alpha(if (enabled) 1f else DISABLED_PILL_ALPHA) .clip(CircleShape) .background(containerColor) .clickable(enabled = enabled, onClick = onClick, role = Role.Button) diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt index 5d40109..74af394 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt @@ -279,16 +279,8 @@ private fun rememberObserveDetailSearch( val hasQuery = searching && query.isNotBlank() val candidates = remember(searchableSectionBodies, rawSectionKeys, hasQuery) { - if (!hasQuery) { - emptyList() - } else { - searchableSectionBodies.flatMap { section -> - searchInspectorBodyCandidates( - sectionKey = section.sectionKey, - body = section.body, - representation = bodySearchRepresentation(section.sectionKey in rawSectionKeys), - ) - } + inspectorSearchCandidatesFor(searchableSectionBodies, hasQuery) { sectionKey -> + bodySearchRepresentation(sectionKey in rawSectionKeys) } } val matches = @@ -324,6 +316,25 @@ private fun rememberObserveDetailSearch( ) } +/** + * Collects the searchable bodies' candidates, short-circuiting before any body is walked when there + * is no query to match. + */ +internal fun inspectorSearchCandidatesFor( + sections: List, + hasQuery: Boolean, + representationForSection: (String) -> InspectorBodySearchRepresentation, +): List { + if (!hasQuery) return emptyList() + return sections.flatMap { section -> + searchInspectorBodyCandidates( + sectionKey = section.sectionKey, + body = section.body, + representation = representationForSection(section.sectionKey), + ) + } +} + private fun bodySearchRepresentation(raw: Boolean): InspectorBodySearchRepresentation = if (raw) InspectorBodySearchRepresentation.RAW else InspectorBodySearchRepresentation.FORMATTED diff --git a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorDetailSearchTest.kt b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorDetailSearchTest.kt index 386ca47..a7f396f 100644 --- a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorDetailSearchTest.kt +++ b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorDetailSearchTest.kt @@ -161,19 +161,16 @@ class InspectorDetailSearchTest { ) var representationRequests = 0 - val matches = - searchInspectorSections( - sections = listOf(InspectorDetailSectionSpec("res", "Response body", body)), - query = " ", - selectedSectionKeys = setOf("res"), - mode = InspectorSearchMode.VALUES, - representationForSection = { - representationRequests++ - InspectorBodySearchRepresentation.FORMATTED - }, - ) - - assertTrue(matches.isEmpty()) + val candidates = + inspectorSearchCandidatesFor( + sections = listOf(InspectorSearchSectionBody("res", body)), + hasQuery = " ".isNotBlank(), + ) { + representationRequests++ + InspectorBodySearchRepresentation.FORMATTED + } + + assertTrue(candidates.isEmpty()) assertEquals(0, representationRequests) } From 6891078851c62793fad9e00d7c7906d11c15fb31 Mon Sep 17 00:00:00 2001 From: shakibuzzaman Date: Tue, 18 Aug 2026 07:47:18 +0600 Subject: [PATCH 16/20] ci: publish the Gradle plugin from a tag, behind an approval gate The Portal is as irreversible as Central was, so the tag trigger is gated on a protected environment rather than publishing outright; guards tag vs version. --- .github/workflows/publish-plugin.yml | 47 ++++++++++++++++++++++++++++ docs/PUBLISHING.md | 18 +++++++++-- 2 files changed, 63 insertions(+), 2 deletions(-) create mode 100644 .github/workflows/publish-plugin.yml diff --git a/.github/workflows/publish-plugin.yml b/.github/workflows/publish-plugin.yml new file mode 100644 index 0000000..b2351a9 --- /dev/null +++ b/.github/workflows/publish-plugin.yml @@ -0,0 +1,47 @@ +name: Publish Gradle plugin + +# Tag-triggered but not automatic: the `plugin-portal` environment gates the publish behind a +# human approval, because a published Portal version can never be replaced or deleted. +on: + workflow_dispatch: + push: + tags: ['v*'] + +permissions: + contents: read + +jobs: + publish: + runs-on: ubuntu-latest + environment: plugin-portal + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: '17' + - uses: gradle/actions/setup-gradle@v6 + + # A tag that disagrees with the plugin's own version would publish the wrong coordinate, + # and the Portal will not let it be corrected afterwards. + - name: Tag matches the plugin version + if: startsWith(github.ref, 'refs/tags/') + run: | + tag_version="${GITHUB_REF_NAME#v}" + declared="$(sed -n 's/^version = "\(.*\)"$/\1/p' gradle-plugin/build.gradle.kts)" + if [ "$tag_version" != "$declared" ]; then + echo "Tag $GITHUB_REF_NAME implies $tag_version but gradle-plugin declares $declared." >&2 + exit 1 + fi + echo "Publishing io.github.devconsole-android $declared" + + - run: ./gradlew -p gradle-plugin test --stacktrace + + - name: Publish to the Gradle Plugin Portal + run: > + ./gradlew -p gradle-plugin publishPlugins --stacktrace + -Pgradle.publish.key="$GRADLE_PUBLISH_KEY" + -Pgradle.publish.secret="$GRADLE_PUBLISH_SECRET" + env: + GRADLE_PUBLISH_KEY: ${{ secrets.GRADLE_PUBLISH_KEY }} + GRADLE_PUBLISH_SECRET: ${{ secrets.GRADLE_PUBLISH_SECRET }} diff --git a/docs/PUBLISHING.md b/docs/PUBLISHING.md index 2913f6e..c08add2 100644 --- a/docs/PUBLISHING.md +++ b/docs/PUBLISHING.md @@ -47,8 +47,22 @@ facing version from the tag or branch rather than from `SDK_VERSION`, but the tw ## The Gradle plugin → Gradle Plugin Portal -One-time: create an account at [plugins.gradle.org](https://plugins.gradle.org), generate an API -key, and put `gradle.publish.key` / `gradle.publish.secret` in `~/.gradle/gradle.properties`. Then: +One-time: create an account at [plugins.gradle.org](https://plugins.gradle.org) and generate an API +key. Then either publish from CI (preferred) or locally. + +**From CI.** The **Publish Gradle plugin** workflow runs on a `v*` tag and on `workflow_dispatch`. +It checks the tag agrees with `gradle-plugin`'s declared `version`, runs the plugin's test suite, +and only then publishes. Two prerequisites, both one-time: + +1. Repo secrets `GRADLE_PUBLISH_KEY` and `GRADLE_PUBLISH_SECRET` (Settings → Secrets and variables + → Actions). +2. An environment named `plugin-portal` (Settings → Environments) **with a required reviewer**. + The workflow is tag-triggered, so this approval gate is the only thing standing between a tag + push and an irreversible publish — a Portal version can never be replaced or deleted. Without a + protection rule on that environment the job runs unattended, which is exactly what the gate + exists to prevent. + +**Locally.** Put `gradle.publish.key` / `gradle.publish.secret` in `~/.gradle/gradle.properties`: ```bash ./gradlew -p gradle-plugin publishPlugins From fa1c3a09b93b3c8d5ad8f4c6a143eb3c36b07b05 Mon Sep 17 00:00:00 2001 From: shakibuzzaman Date: Tue, 18 Aug 2026 07:48:50 +0600 Subject: [PATCH 17/20] ci: publish on the tag itself, and pin the Gradle action Pushing a v* tag is the release decision, so the approval gate was redundant. setup-gradle is pinned to a SHA since this job runs beside the Portal secrets. --- .github/workflows/publish-plugin.yml | 9 +++++---- docs/PUBLISHING.md | 20 ++++++++++---------- 2 files changed, 15 insertions(+), 14 deletions(-) diff --git a/.github/workflows/publish-plugin.yml b/.github/workflows/publish-plugin.yml index b2351a9..80c7092 100644 --- a/.github/workflows/publish-plugin.yml +++ b/.github/workflows/publish-plugin.yml @@ -1,7 +1,7 @@ name: Publish Gradle plugin -# Tag-triggered but not automatic: the `plugin-portal` environment gates the publish behind a -# human approval, because a published Portal version can never be replaced or deleted. +# A pushed `v*` tag is the release decision, so publishing follows it automatically. The guards +# below cover what a tag does not assert: that the version is the intended one and the suite passes. on: workflow_dispatch: push: @@ -13,14 +13,15 @@ permissions: jobs: publish: runs-on: ubuntu-latest - environment: plugin-portal steps: - uses: actions/checkout@v7 - uses: actions/setup-java@v5 with: distribution: temurin java-version: '17' - - uses: gradle/actions/setup-gradle@v6 + # Pinned: this workflow holds the Portal credentials, so a moved tag upstream would run + # unreviewed code next to them. Bump deliberately. + - uses: gradle/actions/setup-gradle@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0 # A tag that disagrees with the plugin's own version would publish the wrong coordinate, # and the Portal will not let it be corrected afterwards. diff --git a/docs/PUBLISHING.md b/docs/PUBLISHING.md index c08add2..2e1ceb5 100644 --- a/docs/PUBLISHING.md +++ b/docs/PUBLISHING.md @@ -51,16 +51,16 @@ One-time: create an account at [plugins.gradle.org](https://plugins.gradle.org) key. Then either publish from CI (preferred) or locally. **From CI.** The **Publish Gradle plugin** workflow runs on a `v*` tag and on `workflow_dispatch`. -It checks the tag agrees with `gradle-plugin`'s declared `version`, runs the plugin's test suite, -and only then publishes. Two prerequisites, both one-time: - -1. Repo secrets `GRADLE_PUBLISH_KEY` and `GRADLE_PUBLISH_SECRET` (Settings → Secrets and variables - → Actions). -2. An environment named `plugin-portal` (Settings → Environments) **with a required reviewer**. - The workflow is tag-triggered, so this approval gate is the only thing standing between a tag - push and an irreversible publish — a Portal version can never be replaced or deleted. Without a - protection rule on that environment the job runs unattended, which is exactly what the gate - exists to prevent. +Pushing the tag *is* the release decision, so it publishes without further confirmation. Before it +does, it checks the tag agrees with `gradle-plugin`'s declared `version` and runs the plugin's test +suite — a tag asserts the intent to release, not that the version string is right. + +One-time setup: add the repo secrets `GRADLE_PUBLISH_KEY` and `GRADLE_PUBLISH_SECRET` (Settings → +Secrets and variables → Actions). + +Because the publish is irreversible, two things are worth knowing: the version guard fails the run +rather than publishing a mismatched coordinate, and re-pushing an already-published version is +rejected by the Portal, so a deleted-and-recreated tag will fail rather than overwrite. **Locally.** Put `gradle.publish.key` / `gradle.publish.secret` in `~/.gradle/gradle.properties`: From 25eed33dc0a2b720e43c0072662e5f6688be50f5 Mon Sep 17 00:00:00 2001 From: shakibuzzaman Date: Tue, 18 Aug 2026 07:50:33 +0600 Subject: [PATCH 18/20] ci: drop the dependency-review workflow --- .github/workflows/dependency-review.yml | 16 ---------------- 1 file changed, 16 deletions(-) delete mode 100644 .github/workflows/dependency-review.yml diff --git a/.github/workflows/dependency-review.yml b/.github/workflows/dependency-review.yml deleted file mode 100644 index 14ed89b..0000000 --- a/.github/workflows/dependency-review.yml +++ /dev/null @@ -1,16 +0,0 @@ -name: Dependency Review - -on: - pull_request: - -permissions: - contents: read - -jobs: - dependency-review: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v7 - - uses: actions/dependency-review-action@v5 - with: - fail-on-severity: high From 08daa9994759eba2be0f9bb7889c80c70838aa85 Mon Sep 17 00:00:00 2001 From: shakibuzzaman Date: Tue, 18 Aug 2026 12:15:26 +0600 Subject: [PATCH 19/20] fix: JitPack versions carry the v prefix, auto-wire included Verified against the live registry: v1.2.1 resolves, 1.2.1 404s. The plugin was auto-wiring the bare form, so every zero-config consumer would have failed. --- CHANGELOG.md | 6 ++++-- README.md | 18 ++++++++++-------- docs/BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md | 2 +- docs/MIGRATION.md | 7 ++++--- docs/PUBLISHING.md | 7 +++++-- .../gradle/DevConsoleVariantPolicyPlugin.kt | 4 +++- ...ConsoleVariantPolicyPluginFunctionalTest.kt | 8 ++++---- 7 files changed, 31 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1da2ddd..5e4e96b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,7 +43,9 @@ joined this list.) publishing is removed: no `publishToMavenCentral`, no GPG signing, and no "Publish to Maven Central" workflow. Consumers add `maven { url = uri("https://jitpack.io") }` to `dependencyResolutionManagement` and switch the group from `io.github.devconsole-android` to - **`com.github.devconsole-android.DevConsole`**; artifact IDs and versions are unchanged. + **`com.github.devconsole-android.DevConsole`**, and prefix the version with `v` (`v1.2.2`) — + JitPack serves a build under its git ref name and releases are tagged `v*`, so the bare version + does not resolve. Artifact IDs are unchanged. Releasing is now just pushing a tag — JitPack builds the ref on first request. - **The Gradle plugin still comes from the Gradle Plugin Portal** as `io.github.devconsole-android`, because the `plugins { }` DSL cannot resolve a plugin marker from JitPack. Its variant-policy @@ -204,7 +206,7 @@ signing key — including JitPack, which this release adds as a channel. - **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 + (`com.github.devconsole-android.DevConsole:devconsole:v1.1.1` — the version is the git ref, so the `v` is part of it), 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 diff --git a/README.md b/README.md index ee044d2..0b6389f 100644 --- a/README.md +++ b/README.md @@ -55,8 +55,8 @@ plugins { } dependencies { - debugImplementation("com.github.devconsole-android.DevConsole:devconsole:1.2.2") - releaseImplementation("com.github.devconsole-android.DevConsole:devconsole-noop:1.2.2") + debugImplementation("com.github.devconsole-android.DevConsole:devconsole:v1.2.2") + releaseImplementation("com.github.devconsole-android.DevConsole:devconsole-noop:v1.2.2") } ``` @@ -353,8 +353,8 @@ Add the adapter — it is not part of the `devconsole` umbrella, so that Firebas classpath of an app that doesn't use it: ```kotlin -debugImplementation("com.github.devconsole-android.DevConsole:devconsole-remote-config-firebase:1.2.2") -releaseImplementation("com.github.devconsole-android.DevConsole:devconsole-remote-config-firebase-noop:1.2.2") +debugImplementation("com.github.devconsole-android.DevConsole:devconsole-remote-config-firebase:v1.2.2") +releaseImplementation("com.github.devconsole-android.DevConsole:devconsole-remote-config-firebase-noop:v1.2.2") ``` > These two artifacts first ship in `1.2.0`; earlier versions do not have them. @@ -429,10 +429,12 @@ You never name those. Every module publishes sources, javadoc, and a POM. ### Versions and unreleased code All 34 library artifacts come from [JitPack](https://jitpack.io/#devconsole-android/DevConsole), -which builds a ref on demand — so the version is a git ref. A release tag works as the bare tag, as -in the tables above. Any branch works as `-SNAPSHOT`, with `/` written as `~`, so a -`feature/x` branch is `feature~x-SNAPSHOT` — that is how you try an unreleased fix before it ships. -JitPack support starts at **1.1.1**; earlier tags do not build there. Two things to know: +which builds a ref on demand — so **the version is a git ref, spelled exactly as the ref is**. +Releases are tagged `v*`, which is why the coordinates above read `v1.2.2` and not `1.2.2`; the +bare form is a different ref and does not resolve. Any branch works as `-SNAPSHOT`, with +`/` written as `~`, so a `feature/x` branch is `feature~x-SNAPSHOT` — that is how you try an +unreleased fix before it ships. JitPack support starts at **v1.1.1**; earlier tags do not build +there. Two things to know: - **The Gradle plugin comes from the Gradle Plugin Portal, not JitPack**, because the `plugins { }` DSL cannot resolve a plugin marker from JitPack. That is why the quick start adds JitPack for diff --git a/docs/BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md b/docs/BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md index 9491d00..4f346eb 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.2.2") // default; the plugin's own version + sdkVersion.set("v1.2.2") // default; the JitPack tag to resolve } ``` diff --git a/docs/MIGRATION.md b/docs/MIGRATION.md index fa79959..1d9c22c 100644 --- a/docs/MIGRATION.md +++ b/docs/MIGRATION.md @@ -26,11 +26,12 @@ dependencyResolutionManagement { ``` 2. Change the group on every DevConsole dependency from `io.github.devconsole-android` to - `com.github.devconsole-android.DevConsole`. Artifact IDs and versions are unchanged: + `com.github.devconsole-android.DevConsole`, and prefix the version with `v` — JitPack serves a + build under its git ref name, and releases are tagged `v*`. Artifact IDs are unchanged: ```kotlin -debugImplementation("com.github.devconsole-android.DevConsole:devconsole:1.2.2") -releaseImplementation("com.github.devconsole-android.DevConsole:devconsole-noop:1.2.2") +debugImplementation("com.github.devconsole-android.DevConsole:devconsole:v1.2.2") +releaseImplementation("com.github.devconsole-android.DevConsole:devconsole-noop:v1.2.2") ``` If you rely on the plugin's `autoWireDependencies` (the default), step 2 is done for you — you only diff --git a/docs/PUBLISHING.md b/docs/PUBLISHING.md index 2e1ceb5..153a340 100644 --- a/docs/PUBLISHING.md +++ b/docs/PUBLISHING.md @@ -95,8 +95,11 @@ dependencies { } ``` -A release tag works as the bare tag. 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 +`` is the git ref verbatim, so for a release it is the **`v`-prefixed tag** (`v1.2.2`) — +JitPack does not strip the prefix, and the bare form 404s. Any branch works as +`-SNAPSHOT`, with `/` written as `~`, so a `feature/x` branch is `feature~x-SNAPSHOT`. +Note the Gradle plugin is the exception: it comes from the Portal, where its version is the bare +`1.2.2`. JitPack support starts at **v1.1.1**; earlier tags do not build there. See [BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md](BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md) for what the 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 b9a0b22..8a113c1 100644 --- a/gradle-plugin/src/main/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPlugin.kt +++ b/gradle-plugin/src/main/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPlugin.kt @@ -397,7 +397,9 @@ abstract class VerifyDevConsolePackagedArtifactTask : DefaultTask() { } } -private const val DEFAULT_SDK_VERSION = "1.2.2" +// JitPack serves a build under its git ref name, and this repo tags `v*` -- a bare "1.2.2" +// does not resolve. Keep the `v`. +private const val DEFAULT_SDK_VERSION = "v1.2.2" /** JitPack's group for this repo — what auto-wiring declares. */ private const val DEVCONSOLE_GROUP = "com.github.devconsole-android.DevConsole" 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 aa92cdc..a311c56 100644 --- a/gradle-plugin/src/test/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPluginFunctionalTest.kt +++ b/gradle-plugin/src/test/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPluginFunctionalTest.kt @@ -874,7 +874,7 @@ class DevConsoleVariantPolicyPluginFunctionalTest { // 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("com.github.devconsole-android.DevConsole:devconsole-noop:1.2.2")) + assertTrue(result.output, result.output.contains("com.github.devconsole-android.DevConsole:devconsole-noop:v1.2.2")) assertTrue(result.output, !result.output.contains("1.2.2-SNAPSHOT")) } @@ -925,13 +925,13 @@ class DevConsoleVariantPolicyPluginFunctionalTest { @Test fun `the JitPack coordinate trips the declared-dependency check`() { - addStubCoordinate("com.github.devconsole-android.DevConsole", "devconsole", "1.2.2") + addStubCoordinate("com.github.devconsole-android.DevConsole", "devconsole", "v1.2.2") writeFixture( devConsoleBlock = "autoWireDependencies.set(false)", extraBuildScript = """ dependencies { - add("releaseImplementation", "com.github.devconsole-android.DevConsole:devconsole:1.2.2") + add("releaseImplementation", "com.github.devconsole-android.DevConsole:devconsole:v1.2.2") } """.trimIndent(), ) @@ -971,7 +971,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("com.github.devconsole-android.DevConsole:devconsole:1.2.2")) + assertTrue(result.output, result.output.contains("com.github.devconsole-android.DevConsole:devconsole:v1.2.2")) assertTrue(result.output, result.output.contains("io.github.devconsole-android:devconsole-ui-compose")) } From 2573067645b2bebdbc55e1e6c02150617fbfcb75 Mon Sep 17 00:00:00 2001 From: shakibuzzaman Date: Tue, 18 Aug 2026 12:19:31 +0600 Subject: [PATCH 20/20] docs: spell the JitPack placeholder as v A bare reads as 1.2.2, which 404s; the tag prefix is part of the coordinate. The Portal-hosted plugin keeps its bare version. --- docs/GETTING_STARTED_COMPOSE.md | 10 +++++++--- docs/GETTING_STARTED_XML_KOTLIN.md | 10 +++++++--- docs/PUBLISHING.md | 4 ++-- docs/REMOTE_CONFIG.md | 8 ++++++-- sdk/storage-room/README.md | 6 +++++- 5 files changed, 27 insertions(+), 11 deletions(-) diff --git a/docs/GETTING_STARTED_COMPOSE.md b/docs/GETTING_STARTED_COMPOSE.md index 93d202e..abaea70 100644 --- a/docs/GETTING_STARTED_COMPOSE.md +++ b/docs/GETTING_STARTED_COMPOSE.md @@ -24,9 +24,9 @@ plugins { } dependencies { - debugImplementation("com.github.devconsole-android.DevConsole:devconsole:") - releaseImplementation("com.github.devconsole-android.DevConsole:devconsole-noop:") - debugImplementation("com.github.devconsole-android.DevConsole:devconsole-ui-compose:") // optional, only for the launcher panel + debugImplementation("com.github.devconsole-android.DevConsole:devconsole:v") + releaseImplementation("com.github.devconsole-android.DevConsole:devconsole-noop:v") + debugImplementation("com.github.devconsole-android.DevConsole:devconsole-ui-compose:v") // optional, only for the launcher panel } devConsole { @@ -35,6 +35,10 @@ devConsole { } ``` +`v` is a JitPack version, which is the git tag verbatim — releases are tagged `v*`, so +`v1.2.2`, not `1.2.2`. The plugin is the exception: it comes from the Gradle Plugin Portal, where +its version is bare. + There is no BOM. `devconsole` (the debug runtime) and `devconsole-noop` are the only two coordinates a normal integration names; everything else is `devconsole-`. diff --git a/docs/GETTING_STARTED_XML_KOTLIN.md b/docs/GETTING_STARTED_XML_KOTLIN.md index ba58465..da1b083 100644 --- a/docs/GETTING_STARTED_XML_KOTLIN.md +++ b/docs/GETTING_STARTED_XML_KOTLIN.md @@ -24,9 +24,9 @@ plugins { } dependencies { - debugImplementation("com.github.devconsole-android.DevConsole:devconsole:") - releaseImplementation("com.github.devconsole-android.DevConsole:devconsole-noop:") - debugImplementation("com.github.devconsole-android.DevConsole:devconsole-ui-views:") // optional, only for the launcher panel + debugImplementation("com.github.devconsole-android.DevConsole:devconsole:v") + releaseImplementation("com.github.devconsole-android.DevConsole:devconsole-noop:v") + debugImplementation("com.github.devconsole-android.DevConsole:devconsole-ui-views:v") // optional, only for the launcher panel } devConsole { @@ -35,6 +35,10 @@ devConsole { } ``` +`v` is a JitPack version, which is the git tag verbatim — releases are tagged `v*`, so +`v1.2.2`, not `1.2.2`. The plugin is the exception: it comes from the Gradle Plugin Portal, where +its version is bare. + There is no BOM. `devconsole` (the debug runtime) and `devconsole-noop` are the only two coordinates a normal integration names; everything else is `devconsole-`. diff --git a/docs/PUBLISHING.md b/docs/PUBLISHING.md index 153a340..5ef1303 100644 --- a/docs/PUBLISHING.md +++ b/docs/PUBLISHING.md @@ -90,8 +90,8 @@ plugins { id("io.github.devconsole-android") version "" } dependencies { - debugImplementation("com.github.devconsole-android.DevConsole:devconsole:") - releaseImplementation("com.github.devconsole-android.DevConsole:devconsole-noop:") + debugImplementation("com.github.devconsole-android.DevConsole:devconsole:v") + releaseImplementation("com.github.devconsole-android.DevConsole:devconsole-noop:v") } ``` diff --git a/docs/REMOTE_CONFIG.md b/docs/REMOTE_CONFIG.md index b0a1a7e..fec36b8 100644 --- a/docs/REMOTE_CONFIG.md +++ b/docs/REMOTE_CONFIG.md @@ -25,10 +25,14 @@ Cloud Messaging. Add the adapter coordinate yourself; it is deliberately not re- `devconsole` umbrella. ```kotlin -debugImplementation("com.github.devconsole-android.DevConsole:devconsole-remote-config-firebase:") -releaseImplementation("com.github.devconsole-android.DevConsole:devconsole-remote-config-firebase-noop:") +debugImplementation("com.github.devconsole-android.DevConsole:devconsole-remote-config-firebase:v") +releaseImplementation("com.github.devconsole-android.DevConsole:devconsole-remote-config-firebase-noop:v") ``` +`v` is a JitPack version, which is the git tag verbatim — releases are tagged `v*`, so +`v1.2.2`, not `1.2.2`. The plugin is the exception: it comes from the Gradle Plugin Portal, where +its version is bare. + A provider constructed later — through DI, or after a first fetch completes — can register itself: ```kotlin diff --git a/sdk/storage-room/README.md b/sdk/storage-room/README.md index 8ee82c9..54c9ec5 100644 --- a/sdk/storage-room/README.md +++ b/sdk/storage-room/README.md @@ -6,9 +6,13 @@ 1. Add dependency to your build file: ```kotlin -debugImplementation("com.github.devconsole-android.DevConsole:devconsole-storage-room:") +debugImplementation("com.github.devconsole-android.DevConsole:devconsole-storage-room:v") ``` +`v` is a JitPack version, which is the git tag verbatim — releases are tagged `v*`, so +`v1.2.2`, not `1.2.2`. The plugin is the exception: it comes from the Gradle Plugin Portal, where +its version is bare. + `sdk:full` wires this module in automatically for durable timeline storage — no additional registration is required. Scope it to `debugImplementation` (never plain `implementation`) yourself if you depend on it directly: it is not in the Gradle plugin's protected-artifact denylist, so