diff --git a/docs/DESIGN_SPEC.md b/docs/DESIGN_SPEC.md index 9d00310..c7c4b50 100644 --- a/docs/DESIGN_SPEC.md +++ b/docs/DESIGN_SPEC.md @@ -232,6 +232,63 @@ must recompute mid-scroll rather than assume) — see §9. - **Toolbar** (`.toolbar`): flex row, wraps, `align-items: flex-end` so label-stacked fields (uppercase label over input) share a bottom baseline with bare buttons. (This was a bug — see §9.) +## 4a. Detail pane anatomy (split views) + +Four of the five split views build their right-hand pane from one shared helper (`detailHeadHtml`) — +Network, WebSockets, Push and Crashes. Timeline hand-rolls its own head from the same classes and +is the odd one out; folding it into the helper is an open item (§9). + +``` +┌ .detail-head ────────────────────────────────────────────────┐ +│ [BADGE] [MOCK] title (mono, ellipsis) STATUS [⤢] [⋮] │ head row +│ ‹facts strip — see table below› │ .detail-facts +│ ‹actions row — see table below› │ .detail-actions-row +│ Summary │ Request & response │ Headers │ … [Stacked] │ .detail-tabs +├ .detail-find (compare/diff tabs only) ───────────────────────┤ +│ Find in headers, payload and response… N matches │ +├ .detail-body (scrolls) ──────────────────────────────────────┤ +│ ┌ .sbs-pane ────────┐ ┌ .sbs-pane ────────┐ │ .sbs-grid +│ │ ● Request [Copy] │ │ ● Response [Copy] │ │ +│ │ › Request headers │ │ › Response headers│ │ collapsed +│ │ ⌄ Payload │ │ ⌄ Body │ │ expanded +│ └───────────────────┘ └───────────────────┘ │ +│ redaction footnote │ +└──────────────────────────────────────────────────────────────┘ +``` + +**Two variants of the head's middle band.** The facts strip and the actions row are per-pane +choices, not fixed furniture: + +| Pane | Facts strip | Actions | +|---|---|---| +| **Network** | none — folded into the Summary tab | kebab **⋮** menu, right of the expand button | +| WebSockets, Push, Crashes | `.detail-facts` row under the title | flat `.detail-actions-row` | + +The kebab is opt-in via `detailHeadHtml`'s `actionsMenu` flag. Network carries up to seven actions +(flag, pin, resend, clone, mock *or* unmock, cURL, fetch) — a full row of buttons for controls +used occasionally, not per-capture. The other panes carry two or three, where a row costs nothing +and a menu would only add a click. Menu items keep the same `data-detail-action` ids as row +buttons, so a pane's delegated click handler is identical either way. The panel is +`position: fixed` (placed by `positionDetailMenuPanel()`) because `.detail-pane-v2` is +`overflow: hidden` and an absolutely positioned popup clips at the pane edge — the same trade +`.drop-panel` makes. It closes on pick, outside click, and Escape (returning focus to its button). + +**Network's tab order** is `Summary · Request & response · [Diff vs baseline] · Headers · Timing · +Related events`. Summary leads because it absorbed the head's old facts strip and is the "what is +this capture" view: time, duration, request url/method, response status, `response.error` on a +failure, content type, correlation id, mock rule (a link into Mocks), vs-original field count, and +tags. Diff only appears once a baseline is pinned. **Default selection is Request & response**, not +the first tab — the body is what an engineer opens a capture to read. + +Consequently Network's two compare panes hold only headers and body; they have no "General" group, +because everything it used to duplicate now lives one tab left. Group collapse defaults come from +`detailGroupHtml`: `Payload`/`Body` open, everything else collapsed, an explicit user toggle always +winning over the default. + +**Simple mode** hides the Headers/Timing/Related tabs outright, and hides individual actions that +carry `hideInSimple` (`fetch` always; `pin` only while no baseline is pinned, so a pinned baseline +can never be stranded behind a mode switch). + ## 4b. Layout (Android in-app inspector) - **Bottom nav, 4 destinations:** `01 Observe · 02 Control · 03 Data · 04 More` (numbered + label, @@ -300,7 +357,9 @@ tray screen becomes a natural addition, just not one this pass builds. - **Segmented control** (`.seg`): joined buttons, one active (signal). - **Chips / chip-row** (`.chip-row`): wrapping pill filters. - **Cards** (`.card`): panel surface, 1px `--line`, 16px pad, `h2` with small leading icon. -- **Split panes:** `.list` (rows) + `.splitter` + `.detail-pane` (min-width 300px). +- **Split panes:** `.list-pane` (rows) + `.splitter` (5px) + `.detail-pane-v2`, inside `.split-shell` + (min 360px per column). Detail-pane anatomy — head, facts/actions variants, tabs, find bar, + side-by-side groups — is specified in §4a. - **Data table** (`.db-table`): real ``, `
`, truncation via `.db-truncated`, horizontal scroll in `.db-table-wrap`. - **Empty states** (`.empty-state`): centered icon + title + sub. Used widely — design these well; @@ -317,9 +376,10 @@ tray screen becomes a natural addition, just not one this pass builds. 1. **Overview** — landing / status summary, connect prompt when unauthenticated, and the previous-run-crashed banner (see [CRASH_AND_ANR.md](CRASH_AND_ANR.md#the-previous-run-crashed-banner)). -2. **Network** — captured HTTP list + detail; toolbar (search, status seg, method seg, Apply, Clear, - HAR, Postman); detail action row (Clone to composer, cURL, fetch, JSON, Related events); redacted - metadata pane. +2. **Network** — captured HTTP list + detail; toolbar (search, status seg, method seg, service drop, + HAR, Postman, Clear) over a "More filters" disclosure; redacted metadata pane whose actions + (flag, pin, resend, clone, mock/unmock, cURL, fetch) live in the head's **⋮ menu** and whose tabs + lead with Summary — see §4a. 3. **WebSockets** — socket sessions (URL, STATE/SENT/RECV), frame list per socket. 4. **Timeline** — unified event timeline (search). 5. **Crashes** — crash/ANR list + detail: kind/thread badges, breadcrumb strip, the all-thread dump @@ -427,6 +487,10 @@ The final web visual contract relies on a rigid separation of concerns. `dashboa next step: the device's More screen, the `adb forward tcp:8080 tcp:8080` command (with its caveat that 8080 is only the first port tried), and the two browser access modes: a bare URL by default or the `#code=` credential when SESSION_CODE is selected. +- **Network's detail head carried three stacked strips** (facts, actions, tabs) before the panes + even started, each duplicating something already on screen — the facts repeated the compare + panes' "General" groups. Facts moved into the Summary tab, the General groups went away, the + actions row became a ⋮ menu, and Summary was ordered first. See §4a. - **Cross-surface parity was undecided** — resolved and documented in §4c, with a full 16-row table of which web views the Android inspector mirrors, which it deliberately doesn't (Composer, capture rules, Overview), and one open naming mismatch (Timeline / Logs) left as a documented gap rather @@ -435,6 +499,8 @@ The final web visual contract relies on a rigid separation of concerns. `dashboa **Open / worth a design eye:** - **Table/detail density** on Network/Database detail panes — readability at scale — is still unaddressed by this pass. +- **Timeline's detail head is hand-rolled** rather than built from `detailHeadHtml` like the other + three split views (§4a), so it drifts from them silently whenever the shared helper changes. - **The Timeline / Logs naming mismatch** (§4c) — same underlying event stream, different name on each surface. Documented, not fixed; fixing it is a code change (renaming `ObserveTab.LOGS` or the web view, or both to a shared name), out of scope for a documentation-only pass. diff --git a/samples/compose-app/src/main/kotlin/io/devconsole/sample/compose/MainActivity.kt b/samples/compose-app/src/main/kotlin/io/devconsole/sample/compose/MainActivity.kt index f2bbf48..484ed4e 100644 --- a/samples/compose-app/src/main/kotlin/io/devconsole/sample/compose/MainActivity.kt +++ b/samples/compose-app/src/main/kotlin/io/devconsole/sample/compose/MainActivity.kt @@ -112,14 +112,33 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext +import okhttp3.MediaType.Companion.toMediaType import okhttp3.OkHttpClient import okhttp3.Request +import okhttp3.RequestBody.Companion.toRequestBody import org.eclipse.paho.client.mqttv3.MqttAsyncClient import org.eclipse.paho.client.mqttv3.MqttConnectOptions import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence import java.io.File import java.util.concurrent.atomic.AtomicInteger +/** Public read endpoint: answers gzipped and chunked, which is what the capture tee is built for. */ +private const val SAMPLE_GET_URL = "https://jsonplaceholder.typicode.com/todos/1" + +/** + * Public write endpoint. It echoes the posted object back with an `id`, so one tap produces a + * capture carrying a real request body *and* a real response body -- the pair every other sample + * action leaves half empty, and the only way to exercise the request side of the inspector + * (payload viewer, cURL/fetch reproduction, mock-from-request) against live traffic. + * + * Nothing is persisted: jsonplaceholder fakes the write and always answers 201 with id 101. + */ +private const val SAMPLE_POST_URL = "https://jsonplaceholder.typicode.com/posts" + +/** Sent by [SampleActivity.sendJsonPost]; small enough to read whole in either inspector. */ +private const val SAMPLE_POST_BODY = + """{"title":"DevConsole sample","body":"Posted from the compose sample app","userId":9912837}""" + private const val SHOW_ORDER_HISTORY_FLAG = "compose_sample.show_order_history" private const val MOCK_RULE_ID = "compose-sample-orders" @@ -251,7 +270,12 @@ private fun devConsoleStatusText( * owns the server lifecycle and builds its own launch surface on top of [DevConsole.state], but can * also drop into the SDK's own in-app inspector (More screen QR, Data rail, exports) via * [DevConsole.open]. + * + * Carries one private method per capability it demonstrates (GET, POST, Ktor, MQTT, screenshot, + * push, ...), which is what the `TooManyFunctions` suppression below covers: splitting them across + * helper classes would put each demonstration somewhere other than the screen that offers it. */ +@Suppress("TooManyFunctions") // One private method per capability demonstrated; see the class doc. class MainActivity : ComponentActivity() { private val socketClient = OkHttpClient() @@ -274,9 +298,14 @@ class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) DevConsole.initialize(application, buildConfig()) - // Mock rules are SESSION-scoped and dropped whenever the embedded server restarts (fresh - // session), so the rule is (re)installed from the Running-state observer below rather than - // once here -- a one-shot install here would silently stop mocking after any restart. + // Installed here AND re-installed from the Running-state observer below. Both are needed: + // mock rules are SESSION-scoped and DevConsole's stop sequence calls clearSessionRules(), + // so a one-shot install would silently stop mocking after any restart -- but installing + // *only* on Running left the rule missing until the embedded server was first started, + // which made a fresh launch show an empty Mocks list and send "Send mocked request" + // to the real network. Mocking is in-process and needs no server, so it should not wait + // for one. + installMockRule() seedSampleData(applicationContext) setContent { @@ -399,7 +428,7 @@ class MainActivity : ComponentActivity() { if (state is DevConsoleState.Running) { endpoint = DevConsole.endpoint() // Re-seed on every Running transition (first start AND every restart) -- see the - // comment in onCreate for why a one-shot install at init isn't enough. + // comment in onCreate for why the install there isn't enough on its own. installMockRule() // Poll while running so either access mode updates the displayed URL after a restart; // SESSION_CODE also re-issues the code after a browser consumes it. @@ -505,16 +534,20 @@ class MainActivity : ComponentActivity() { SectionLabel("Exercise the SDK") CapabilityCard( - title = "Send network request", + title = "Send GET request", subtitle = "OkHttp interceptor -- chunked response, body captured via the tee", onClick = { scope.launch { - lastResponse = - sendRequest("https://jsonplaceholder.typicode.com/todos/1", "Network response") + lastResponse = sendRequest(SAMPLE_GET_URL, "GET response") showOrderHistory = DevConsole.featureFlagValue(SHOW_ORDER_HISTORY_FLAG) } }, ) + CapabilityCard( + title = "Send POST request", + subtitle = "JSON request body and JSON response body -- both captured on the same transaction", + onClick = { scope.launch { lastResponse = sendJsonPost() } }, + ) CapabilityCard( title = "Send Ktor request", subtitle = "Ktor plugin on the CIO engine -- request and response bodies, no OkHttp involved", @@ -630,6 +663,37 @@ class MainActivity : ComponentActivity() { } } + /** + * Posts [SAMPLE_POST_BODY] to [SAMPLE_POST_URL] through the same instrumented client the GET + * card uses, so the capture carries both bodies. + * + * The request body goes through OkHttp's own `RequestBody`, not a pre-serialized string handed + * to the recorder: the capture interceptor reads what OkHttp actually writes to the wire, so + * what the inspector shows is the request as sent rather than as intended. `Content-Type` comes + * from the media type here (not a manual header) for the same reason -- it is the one the call + * really carries. + */ + private suspend fun sendJsonPost(): String = + withContext(Dispatchers.IO) { + requestCount.incrementAndGet() + try { + val request = + Request + .Builder() + .url(SAMPLE_POST_URL) + .post(SAMPLE_POST_BODY.toRequestBody("application/json; charset=utf-8".toMediaType())) + .build() + instrumentedClient.newCall(request).execute().use { response -> + val body = response.body?.string().orEmpty() + "POST response: ${response.code} (${body.length} chars)" + } + } catch (cancellation: kotlinx.coroutines.CancellationException) { + throw cancellation + } catch (error: Exception) { + "POST failed: ${error.message ?: error.javaClass.simpleName}" + } + } + /** * Issues one request through the sample's Ktor client, whose debug build installs * `DevConsoleKtorClientPlugin` (see `SampleKtorClient` in `src/debug`). 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 4a23a99..1bcd2f2 100644 --- a/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css +++ b/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css @@ -741,6 +741,8 @@ body.detail-zoom .split-shell.collapse-detail { grid-template-columns: 1fr; } .col-status { flex: 0 0 62px; text-align: right; } .col-flag { flex: 0 0 24px; text-align: right; } @media (max-width: 620px) { .col-duration { display: none; } } +/* The stacked pair keeps both values at every width — it costs one column, not two, and Network's + list head is sr-only anyway, so there is no header to drift out of step with it. */ /* Export-selection checkbox (Network list only): header "select all visible" + one per row. Same 24x24/6px-radius footprint as .row-flag so the row height and header never shift when a @@ -765,9 +767,14 @@ body.detail-zoom .split-shell.collapse-detail { grid-template-columns: 1fr; } .detail-pane-v2 { min-width: 0; display: flex; flex-direction: column; overflow: hidden; background: var(--ground); } /* ---- List rows ---- */ +/* `min-height`, not `height`: a row with a path too long for one line grows to fit it (up to the + four-line clamp on .row-main-text below). The virtualizer measures each painted row rather than + multiplying by --d-row-h, so a taller row costs nothing but its own pixels — see + createVirtualList's `heights` cache. Vertical padding is what keeps a grown row off its own + borders; a one-line row still lands on exactly --d-row-h. */ .row { - position: relative; display: flex; align-items: center; gap: 8px; width: 100%; height: var(--d-row-h); - padding: 0 8px 0 12px; text-align: left; cursor: pointer; border-radius: 0; border-inline: 0; border-top: 0; border-bottom: 1px solid var(--line); + position: relative; display: flex; align-items: center; gap: 8px; width: 100%; min-height: var(--d-row-h); + padding: 4px 8px 4px 12px; text-align: left; cursor: pointer; border-radius: 0; border-inline: 0; border-top: 0; border-bottom: 1px solid var(--line); background: transparent; color: var(--ink); font: inherit; font-size: var(--d-row-font); } .row:hover { background: var(--surface-2); } @@ -781,12 +788,38 @@ body.detail-zoom .split-shell.collapse-detail { grid-template-columns: 1fr; } font-family: var(--font-mono); font-size: var(--d-row-main-font); color: var(--ink); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +/* Opt-in (rowHtml's `wrapMain`, Network only): a long path wraps instead of being cut at the first + line, then ellipsises once past four — enough for the query-string-heavy endpoints that were + losing everything after the host, without letting one pathological URL own the whole viewport. + `word-break: break-all`, not `overflow-wrap`: a query string is one unbreakable token, and + overflow-wrap only breaks a token that cannot fit on a line of its own, so it pushed the whole + query to line two and left the rest of line one blank. break-all fills every line to the edge, + which is what a URL wants — and what prose does not, which is why this is opt-in rather than the + rule for every list. The line clamp supplies its own ellipsis, so the single-line + `text-overflow` above is turned back off here. */ +.row-main-text.row-main-wrap { + display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 4; line-clamp: 4; + white-space: normal; text-overflow: clip; word-break: break-all; +} /* Query string trailing a Network row's path: present and readable, but never louder than the endpoint. */ .row-main-sub { color: var(--text-3); } .row-tag { flex: 0 0 auto; font-family: var(--font-mono); font-size: 9.5px; font-weight: 700; letter-spacing: 0.06em; padding: 1px 4px; border-radius: 99px; border: 1px solid var(--border-strong); } +/* Network stacks its status over its duration in one column (rowHtml's `stackMetrics`), the way + the Android row reads them; the widths below still apply to the side-by-side lists. Right- + aligned and baseline-free so the pair reads as one block however tall the path beside it is. */ +/* `line-height: 1` on the pair, not the default ~1.2: stacked, the two values would otherwise + total more than --d-row-h and push every Network row ~12px taller than the other lists' — the + opposite of the space this layout is meant to hand back. At 1 they fit the plain row height, and + only a wrapped path grows the row. */ +/* `flex: 0 0 auto`, not the 74px the side-by-side lists reserve: stacked, the pair is at most as + wide as "1931 ms", and a fixed track just parked that slack to the left of a short "200" — read + as a gap between the path and the status roughly four times the row's own 8px one. Auto-sizing + hands those pixels back to the path and leaves exactly that 8px. */ +.row-metrics { flex: 0 0 auto; display: flex; flex-direction: column; align-items: flex-end; justify-content: center; gap: 2px; line-height: 1; } +.row-metrics .row-duration, .row-metrics .row-status { flex: 0 0 auto; } /* Sized for the longest consumers: Timeline puts an event type here, not Network's "198 ms". */ .row-duration { flex: 0 0 74px; font-family: var(--font-mono); font-size: 11.5px; font-variant-numeric: tabular-nums; text-align: right; color: var(--text-3); } .row-status { flex: 0 0 62px; font-family: var(--font-mono); font-size: 12.5px; font-weight: 600; font-variant-numeric: tabular-nums; text-align: right; } @@ -853,6 +886,30 @@ body.detail-zoom .split-shell.collapse-detail { grid-template-columns: 1fr; } .detail-head-status { font-family: var(--font-mono); font-size: 13px; font-weight: 700; } .detail-expand { display: grid; place-items: center; width: 26px; height: 26px; padding: 0; flex: 0 0 auto; border: 1px solid var(--line); border-radius: 8px; background: var(--surface-2); color: var(--muted); } .detail-expand.active { border-color: var(--signal); background: var(--signal-soft); color: var(--signal); } + +/* Kebab (⋮) actions menu, sitting immediately right of .detail-expand — same 26px footprint, so + the head row's right edge reads as one pair of controls rather than two sizes. */ +.detail-menu-btn { display: grid; place-items: center; width: 26px; height: 26px; padding: 0; flex: 0 0 auto; border: 1px solid var(--line); border-radius: 8px; background: var(--surface-2); color: var(--muted); } +.detail-menu-btn:hover { color: var(--ink); border-color: var(--border-strong); } +.detail-menu-btn.active { border-color: var(--signal); background: var(--signal-soft); color: var(--signal); } +/* position: fixed, not absolute: .detail-pane-v2 is overflow: hidden, so an absolutely positioned + popup would be clipped at the pane's edge. Placed by positionDetailMenuPanel(), same contract + as the toolbar dropdowns' .drop-panel. */ +.detail-menu-panel { + position: fixed; z-index: 200; min-width: 200px; max-width: min(92vw, 320px); + display: grid; gap: 1px; padding: 4px; + background: var(--panel); border: 1px solid var(--border-strong); border-radius: 8px; box-shadow: var(--elev-3); +} +.detail-menu-item { + display: flex; align-items: center; gap: 8px; width: 100%; height: 30px; padding: 0 8px; + border: none; border-radius: 6px; background: transparent; text-align: left; color: var(--muted); font-size: 12.5px; +} +.detail-menu-item .ic { flex: 0 0 auto; color: var(--text-3); } +.detail-menu-item:hover:not(:disabled) { background: var(--surface-2); color: var(--ink); } +.detail-menu-item:hover:not(:disabled) .ic { color: inherit; } +.detail-menu-item.on { color: var(--signal); background: var(--signal-soft); } +.detail-menu-item.on .ic { color: var(--signal); } +.detail-menu-item:disabled { opacity: 0.5; cursor: not-allowed; } .detail-facts { display: flex; flex-wrap: wrap; gap: 16px; margin-top: 8px; } .detail-fact { display: flex; align-items: baseline; gap: 8px; font-size: 11.5px; } .detail-fact-k { font-size: 10.5px; font-weight: 600; color: var(--text-3); } @@ -922,6 +979,10 @@ body.detail-zoom .split-shell.collapse-detail { grid-template-columns: 1fr; } /* Find-highlight must win over both grid sizes' background overrides above — same (0,3,0) specificity as `.kv-grid.kv-grid-lg .kv-v` but declared after it, so source order decides. */ .kv-grid .kv-k.hit, .kv-grid .kv-v.hit { background: var(--signal-soft); } +/* Clickable kv value (Network summary's "mock rule: " → Mocks). A ` + : esc(r.v); + return `${esc(r.k)}${v}`; + }) .join('')}`; } function barsHtml(bars) { @@ -1361,31 +1484,110 @@ // overlay clones the already-escaped .code-block markup rather than re-deriving it from data. // ================================================================ let codeFullscreenOpenerEl = null; - // Only ever one focusable in this modal (the close button — the cloned .code-block markup - // carries no interactive elements), so the trap just keeps Tab/Shift+Tab pinned there instead - // of leaking out to the page underneath. + // The body a fullscreen view was opened for, so its Pretty/Raw toggle can rebuild either mode + // without reaching back into the pane underneath (which a re-render may have replaced). + let codeFullscreenBody = null; + // The raw block's markup, captured when the overlay opens. Raw mode clones what the pane is + // already showing rather than re-deriving it, so the two can never disagree. + let codeFullscreenRawHtml = ''; + // The modal used to hold exactly one focusable (close), because it only ever showed cloned + // .code-block markup. A body opens with a Pretty/Raw toggle too, so the trap now cycles the + // real focusables instead of pinning Tab to one button. function codeFullscreenKeydown(e) { if (e.key !== 'Tab') return; + const focusables = [...$('codeFullscreenModal').querySelectorAll('button:not([hidden])')].filter( + (el) => el.offsetParent !== null, + ); + if (!focusables.length) return; e.preventDefault(); - $('codeFullscreenClose').focus(); + const at = focusables.indexOf(document.activeElement); + const next = e.shiftKey ? at - 1 : at + 1; + focusables[(next + focusables.length) % focusables.length].focus(); } function openCodeFullscreen(sourceBlock, title) { const overlay = $('codeFullscreenModal'); if (!overlay || !sourceBlock) return; $('codeFullscreenTitle').textContent = title || 'JSON body'; + codeFullscreenBody = null; + $('codeFullscreenSeg').hidden = true; // Clones the already-escaped markup rather than re-deriving it from data, so this cannot // disagree with what the page underneath is showing. $('codeFullscreenBody').innerHTML = `
${sourceBlock.innerHTML}
`; + showCodeFullscreen(overlay); + } + + /** + * Fullscreen for a body viewer, which unlike a plain code block has both renderings available: + * the collapsible tree and the raw text. The expand button used to hand the overlay the *raw* + * block unconditionally, so a body being read as a tree lost its structure — and its collapse + * arrows — at exactly the size where they matter most. + * + * `mode` is whatever the inline viewer was showing, so expanding enlarges what you were already + * reading instead of switching the view under you. + */ + function openBodyFullscreen(mountKey, title, mode, rawBlock) { + const overlay = $('codeFullscreenModal'); + const entry = pendingBodyViewers.get(mountKey); + if (!overlay || !entry) return; + $('codeFullscreenTitle').textContent = title || 'JSON body'; + codeFullscreenBody = entry; + codeFullscreenRawHtml = rawBlock?.innerHTML || ''; + // Raw is always available; Pretty only for something the tree can actually be built from. + const canPretty = entry.kind === 'json' || entry.kind === 'xml'; + $('codeFullscreenSeg').hidden = !canPretty; + renderCodeFullscreenBody(canPretty ? mode || 'pretty' : 'raw'); + showCodeFullscreen(overlay); + } + + function showCodeFullscreen(overlay) { codeFullscreenOpenerEl = document.activeElement; overlay.hidden = false; document.addEventListener('keydown', codeFullscreenKeydown); $('codeFullscreenClose').focus(); } + + /** Paints one mode into the overlay from `codeFullscreenBody`'s original raw text. */ + function renderCodeFullscreenBody(mode) { + const entry = codeFullscreenBody; + const host = $('codeFullscreenBody'); + if (!entry || !host) return; + $('codeFullscreenSeg') + .querySelectorAll('[data-fs-mode]') + .forEach((b) => b.classList.toggle('active', b.dataset.fsMode === mode)); + host.innerHTML = ''; + if (mode === 'raw') { + host.innerHTML = `
${codeFullscreenRawHtml}
`; + return; + } + // Its own cache key ('fs:'): a cached tree is a live DOM node, and reusing the inline one + // would MOVE it out of the pane underneath, leaving that body blank once the overlay closes. + try { + const built = buildOrReuseBodyViewerTree('fs:' + entry.groupKey, entry.kind, entry.raw, entry.diffSig, () => { + if (entry.kind === 'xml') { + const pre = document.createElement('pre'); + pre.className = 'body-viewer-xml'; + pre.textContent = prettyPrintXml(entry.raw) ?? entry.raw; + return pre; + } + const w = document.createElement('div'); + w.className = 'json-tree'; + w.appendChild(jsonNode(JSON.parse(entry.raw), 0, entry.diffInfo)); + return w; + }); + host.appendChild(built); + } catch { + // Same fallback the inline mount makes: a body that no longer parses shows as its own text + // rather than an empty pane. + host.textContent = entry.raw; + } + } function closeCodeFullscreen() { const overlay = $('codeFullscreenModal'); if (!overlay || overlay.hidden) return; overlay.hidden = true; $('codeFullscreenBody').innerHTML = ''; + codeFullscreenBody = null; + codeFullscreenRawHtml = ''; document.removeEventListener('keydown', codeFullscreenKeydown); codeFullscreenOpenerEl?.focus?.(); codeFullscreenOpenerEl = null; @@ -1875,9 +2077,16 @@ for (let index = from; index < upto; index++) { const [key, val] = entries[index]; const line = document.createElement('div'); - const keySpan = document.createElement('span'); - keySpan.className = 'json-key'; - keySpan.textContent = JSON.stringify(key) + ': '; + // An array child's `key` is its index (jsonNode hands entries over as `[String(i), v]`), + // carried only so diff paths stay addressable — it is a position, not a field name, so it + // is never printed. Rendering it the object way put `"0": ` in front of every element, + // which reads as an object whose key happens to be the string "0". The Compose tree makes + // the same distinction by passing `keyLabel = null` for array items (InspectorBodyFormat). + const keySpan = isArray ? null : document.createElement('span'); + if (keySpan) { + keySpan.className = 'json-key'; + keySpan.textContent = JSON.stringify(key) + ': '; + } // diffInfo is only ever set for the one mocked-response body viewer that requests it // (see diffMockBody) — every other jsonNode/jsonContainer call in the app passes nothing, // so childPath stays undefined and this is just an extra falsy check per row. @@ -1890,7 +2099,8 @@ // subtree, so it keeps the row-level highlight on `line` itself. const isContainerVal = val !== null && typeof val === 'object'; if (diffInfo && !isContainerVal && diffInfo.hits.has(pathKey(childPath))) line.classList.add('json-diff-hit'); - line.append(keySpan, jsonNode(val, depth + 1, diffInfo, childPath)); + if (keySpan) line.append(keySpan); + line.append(jsonNode(val, depth + 1, diffInfo, childPath)); if (index < entries.length - 1) line.append(document.createTextNode(',')); children.append(line); } @@ -3469,6 +3679,7 @@ tagTone: 'put', duration: t.durationMs != null ? t.durationMs + ' ms' : t.error ? 'failed' : '—', statusText: t.status != null ? String(t.status) : t.error ? 'ERR' : '—', sTone: statusTone(t.status), + stackMetrics: true, wrapMain: true, flagKind: 'network', flagLabel: t.method + ' ' + t.path, posinset: i + 1, setsize: total, }); @@ -3689,6 +3900,10 @@ const inside = (id) => path.some((el) => el.id === id); if (networkHostDropOpen && !inside('networkHostDrop')) { networkHostDropOpen = false; renderNetworkHostDrop(); } if (socketConnDropOpen && !inside('socketConnDrop')) { socketConnDropOpen = false; renderSocketConnDrop(); } + // The detail pane's kebab menu closes on the same rule. Its own button and items are handled + // in wireNetworkDetailPane (which runs first, on the pane), so by the time this fires they + // have already cleared the flag — this only catches genuine outside clicks. + if (networkActionsMenuOpen && !inside('detailActionsMenuPanel') && !inside('detailActionsMenuBtn')) { networkActionsMenuOpen = false; renderNetworkDetail(); } } function renderNetworkHostDrop() { @@ -6581,8 +6796,15 @@ * inside `.detail-head` instead, where `flex`/`min-height`/`overflow` mean nothing — so a body * taller than the pane grew the head past it and `.detail-pane-v2`'s `overflow: hidden` simply * cut it off, with nothing anywhere able to scroll to the rest. */ - function detailHeadHtml({ badgeText, badgeTone, title, statusText, sTone, mocked, extraBadge, facts, actions, tabs, layoutToggle }) { + /** `actionsMenu` opts a pane out of the flat `.detail-actions-row` and into a kebab (⋮) menu + * beside the expand button — same `actions` model, same `data-detail-action` ids, so a pane's + * existing delegated click handler covers the items unchanged. Opt-in per pane (Network only + * today) rather than a blanket switch: the other detail panes carry two or three actions each, + * where a row costs nothing and a menu would only add a click. `menuOpen` is the caller's own + * state, since these panes re-render wholesale and the flag has to outlive the innerHTML swap. */ + function detailHeadHtml({ badgeText, badgeTone, title, statusText, sTone, mocked, extraBadge, facts, actions, tabs, layoutToggle, actionsMenu, menuOpen }) { const zoom = document.body.classList.contains('detail-zoom'); + const hasActions = actions && actions.length; return `
${esc(badgeText)} @@ -6591,6 +6813,25 @@ ${esc(title)} ${esc(statusText || '')} + ${ + actionsMenu && hasActions + ? ` + ${ + menuOpen + ? `` + : '' + }` + : '' + }
${ facts && facts.length @@ -6603,7 +6844,7 @@ .join('')}
` : '' } - ${actions && actions.length ? `
${actions.map((a) => ``).join('')}
` : ''} + ${hasActions && !actionsMenu ? `
${actions.map((a) => ``).join('')}
` : ''} ${ tabs && tabs.length ? `
${tabs.map((t) => ``).join('')}${ @@ -6781,8 +7022,9 @@ const reqPane = { side: 'Request', dotTone: 'put', meta: detail.method + (detail.request?.contentType ? ' · ' + detail.request.contentType : ''), metaTone: 'muted', actions: [{ id: 'copy-request', label: 'Copy', icon: 'copy', title: 'Copy the whole request (line, headers, payload)' }], + // No 'General' group: url/method/sent-at are the Summary tab's job now (see + // networkSummaryKvs), and this tab is for the headers and the body. groups: [ - { label: 'General', copyLabel: 'request line', kvs: markKvHits([{ k: 'url', v: detail.request?.url || '' }, { k: 'method', v: detail.method }, { k: 'sent at', v: time(detail.startedAtEpochMs) }], query) }, { label: 'Request headers', copyLabel: 'request headers', meta: String(headerRows(detail.request?.headers).length), kvs: markKvHits(headerRows(detail.request?.headers), query) }, reqBody ? { label: 'Payload', copyLabel: 'request payload', meta: detail.request?.contentType || '', code: reqBody, body: { raw: bodyRawText(detail.request?.body), contentType: detail.request?.contentType } } @@ -6797,16 +7039,16 @@ actions: hasResponse ? [{ id: 'copy-response', label: 'Copy', icon: 'copy', title: 'Copy the whole response (status, headers, body)' }] : [{ id: 'copy-error', label: 'Copy error', icon: 'copy' }], + // Same as the request pane: no 'General' group — status/duration/content type (and, on the + // failure branch, the error string) live in the Summary tab. groups: hasResponse ? [ - { label: 'General', copyLabel: 'status line', kvs: markKvHits([{ k: 'status', v: String(detail.status) }, { k: 'duration', v: (detail.durationMs ?? '—') + ' ms' }, { k: 'content type', v: detail.response.contentType || '—' }], query) }, { label: 'Response headers', copyLabel: 'response headers', meta: String(headerRows(detail.response.headers).length), kvs: markKvHits(headerRows(detail.response.headers), query) }, resBody ? { label: 'Body', copyLabel: 'response body', meta: detail.response.contentType || '', code: resBody, body: { raw: bodyRawText(detail.response.body), contentType: detail.response.contentType, diffInfo, diffSig } } : { label: 'Body', empty: 'No body.' }, ] : [ - { label: 'General', copyLabel: 'failure detail', kvs: markKvHits([{ k: 'status', v: '— no response' }, { k: 'error', v: detail.error || 'unknown' }], query) }, { label: 'Response headers', empty: 'Connection failed before headers arrived.' }, { label: 'Body', empty: 'No body.' }, ], @@ -6861,14 +7103,26 @@ }; } - function networkSummaryKvs(detail) { + /** The detail head used to repeat time/duration/content type/correlation/mock rule as a facts + * strip under the title; they live here now (one place, one format) so the head stays title + + * actions + tabs. `mockRuleId`/`mockDiffTotal` are computed in renderNetworkDetail (they need + * mockRulesCache) and passed down rather than recomputed. */ + function networkSummaryKvs(detail, { mockRuleId, mockDiffTotal } = {}) { const rows = [ + { k: 'time', v: time(detail.startedAtEpochMs) }, + { k: 'duration', v: detail.durationMs != null ? detail.durationMs + ' ms' : '—' }, { k: 'request.url', v: detail.request?.url || '' }, { k: 'request.method', v: detail.method }, - { k: 'response.status', v: detail.status != null ? String(detail.status) : detail.error ? '— (' + detail.error + ')' : '—', tone: statusTone(detail.status) }, + { k: 'response.status', v: detail.status != null ? String(detail.status) : detail.error ? '— no response' : '—', tone: statusTone(detail.status) }, ]; + // The error string used to be parenthesised into response.status above, and to double as the + // compare tab's failure "General" group. Both are gone: this is its one home, on its own row + // so a long exception message isn't buried inside another value. + if (detail.error) rows.push({ k: 'response.error', v: detail.error, tone: 'error' }); if (detail.response?.contentType) rows.push({ k: 'response.contentType', v: detail.response.contentType }); if (detail.correlationId) rows.push({ k: 'correlationId', v: detail.correlationId }); + if (mockRuleId) rows.push({ k: 'mock rule', v: mockRuleId, mockRuleLink: true }); + if (mockDiffTotal > 0) rows.push({ k: 'vs original', v: mockDiffTotal + (mockDiffTotal === 1 ? ' field differs' : ' fields differ') + ' from original', tone: 'warn' }); const tags = Object.entries(detail.tags || {}); if (tags.length) rows.push({ k: 'tags', v: tags.map(([k, v]) => k + '=' + v).join(', ') }); return rows; @@ -6920,10 +7174,12 @@ if (networkTab === 'diff' && !pinId) networkTab = 'compare'; const diffCount = hasPin ? diffHeaderStats(networkDetailCache.get(pinId), detail) : null; const relatedFresh = networkRelatedEventsForId === detail.id; - const tabs = [{ id: 'compare', label: 'Request & response' }] + // Summary leads: it absorbed the head's old facts strip (time/duration/content type/ + // correlation/mock rule/error), so it is the "what is this capture" tab and reads first. + // `networkTab` still defaults to 'compare' — order here, not which tab opens selected. + const tabs = [{ id: 'summary', label: 'Summary' }, { id: 'compare', label: 'Request & response' }] .concat(pinId ? [{ id: 'diff', label: 'Diff vs baseline', count: hasPin ? String(diffCount.changed + diffCount.added) : 'pick one' }] : []) .concat([ - { id: 'summary', label: 'Summary' }, { id: 'headers', label: 'Headers', count: String(headerRows(detail.request?.headers).length + headerRows(detail.response?.headers).length) }, { id: 'timing', label: 'Timing' }, { id: 'related', label: 'Related events', count: relatedFresh ? String(networkRelatedEvents.length) : undefined }, @@ -6970,12 +7226,10 @@ badgeText: detail.method, badgeTone: methodTone(detail.method), title: detail.host + detail.path, statusText: detail.status != null ? String(detail.status) : detail.error ? 'FAILED' : '—', sTone: statusTone(detail.status), mocked: isMocked, - facts: [{ k: 'time', v: time(detail.startedAtEpochMs) }, { k: 'duration', v: detail.durationMs != null ? detail.durationMs + ' ms' : '—' }] - .concat(detail.response?.contentType ? [{ k: 'content type', v: detail.response.contentType }] : []) - .concat(detail.correlationId ? [{ k: 'correlation', v: detail.correlationId }] : []) - .concat(mockRuleId ? [{ k: 'mock rule', v: mockRuleId, link: true }] : []) - .concat(mockDiffTotal > 0 ? [{ k: 'vs original', v: mockDiffTotal + (mockDiffTotal === 1 ? ' field differs' : ' fields differ') + ' from original' }] : []), + // No facts strip: time/duration/content type/correlation/mock rule now live in the Summary + // tab (see networkSummaryKvs) instead of being repeated under the title. actions, tabs, layoutToggle, + actionsMenu: true, menuOpen: networkActionsMenuOpen, }); let findBar = ''; let bodyHtml; @@ -6997,7 +7251,7 @@ bodyHtml = `
${panes.map(sbsPaneHtml).join('')}
`; } } else if (networkTab === 'summary') { - bodyHtml = kvGridHtml(networkSummaryKvs(detail), true); + bodyHtml = kvGridHtml(networkSummaryKvs(detail, { mockRuleId, mockDiffTotal }), true); } else if (networkTab === 'headers') { bodyHtml = kvGridHtml(networkHeadersKvs(detail), true); } else if (networkTab === 'timing') { @@ -7026,9 +7280,28 @@ bodyHtml += `
${icon('lock', 'ic-sm')}Headers and bodies are redacted by the on-device allowlist before they reach this browser. Values shown as •••• never left the app.
`; pane.innerHTML = head + findBar + `
${bodyHtml}
`; mountBodyViewers(pane); + // The menu panel is position: fixed (the detail pane is overflow: hidden, so an absolutely + // positioned popup would be clipped at the pane edge) — same trade the toolbar dropdowns make. + if (networkActionsMenuOpen) positionDetailMenuPanel(); restoreFocus(focusSnap, pane); } + /** Right-aligns the actions menu under its kebab button, flipping above when there isn't room + * below — the .drop-panel contract in positionDropPanel, minus the multi-select chrome. */ + function positionDetailMenuPanel() { + requestAnimationFrame(() => { + const btn = $('detailActionsMenuBtn'), panel = $('detailActionsMenuPanel'); + if (!btn || !panel) return; + const rc = btn.getBoundingClientRect(); + const vh = window.innerHeight; + const below = vh - rc.bottom - 16; + const useBelow = below >= 200 || below >= rc.top - 16; + panel.style.left = Math.max(8, rc.right - panel.offsetWidth) + 'px'; + if (useBelow) { panel.style.top = rc.bottom + 5 + 'px'; panel.style.bottom = 'auto'; } + else { panel.style.bottom = vh - rc.top + 5 + 'px'; panel.style.top = 'auto'; } + }); + } + function detailActionText(id, detail) { if (id === 'copy-request') { const lines = ['Method: ' + detail.method, 'URL: ' + (detail.request?.url || ''), ...headerRows(detail.request?.headers).map((h) => h.k + ': ' + h.v)]; @@ -7051,6 +7324,7 @@ function wireNetworkDetailPane() { const pane = $('networkDetailPane'); pane.addEventListener('click', (e) => { + if (e.target.closest('[data-action="toggle-actions-menu"]')) { networkActionsMenuOpen = !networkActionsMenuOpen; renderNetworkDetail(); return; } if (e.target.closest('[data-action="toggle-zoom"]')) { toggleDetailZoom(); return; } const mockLink = e.target.closest('[data-open-mock-rule]'); if (mockLink) { openMockRuleFromNetwork(mockLink.dataset.openMockRule); return; } @@ -7085,6 +7359,11 @@ const actionBtn = e.target.closest('[data-detail-action]'); if (!actionBtn || !selectedTransactionDetail) return; const id = actionBtn.dataset.detailAction; + // Picking an item dismisses the menu, the way a menu is expected to behave — repainted here + // rather than per branch, because most branches (copy, cURL, clone-to-composer) don't + // re-render this pane themselves and would leave the popup hanging open over it. `id` is + // read first since the repaint detaches `actionBtn` from the tree. + if (networkActionsMenuOpen) { networkActionsMenuOpen = false; renderNetworkDetail(); } if (id === 'flag') { const d = selectedTransactionDetail; toggleEvidenceFlag('network', d.id, d.method + ' ' + d.host + d.path); renderNetworkDetail(); } else if (id === 'pin') pinNetworkBaseline(selectedTransactionId); else if (id === 'resend') resendCapturedRequest(); @@ -7563,10 +7842,18 @@ if (entry) copyToClipboard(entry.raw, 'Body'); return; } + const fsModeBtn = e.target.closest('[data-fs-mode]'); + if (fsModeBtn) { + renderCodeFullscreenBody(fsModeBtn.dataset.fsMode); + return; + } const fsBtn = e.target.closest('[data-body-fullscreen]'); if (fsBtn) { - const rawBlock = fsBtn.closest('.body-viewer')?.querySelector('.body-viewer-raw .code-block'); - openCodeFullscreen(rawBlock, fsBtn.dataset.bodyTitle); + const viewer = fsBtn.closest('.body-viewer'); + const rawBlock = viewer?.querySelector('.body-viewer-raw .code-block'); + // Open in whichever mode the pane is showing, so expanding never switches the view. + const mode = viewer?.querySelector('[data-body-mode].active')?.dataset.bodyMode || 'pretty'; + openBodyFullscreen(fsBtn.dataset.bodyFullscreen, fsBtn.dataset.bodyTitle, mode, rawBlock); return; } }); @@ -7843,6 +8130,7 @@ // existing composedPath-based outside-click closer instead of replacing it. if (e.key === 'Escape' && networkHostDropOpen) { networkHostDropOpen = false; renderNetworkHostDrop(); $('networkHostDropBtn')?.focus(); return; } if (e.key === 'Escape' && socketConnDropOpen) { socketConnDropOpen = false; renderSocketConnDrop(); $('socketConnDropBtn')?.focus(); return; } + if (e.key === 'Escape' && networkActionsMenuOpen) { networkActionsMenuOpen = false; renderNetworkDetail(); $('detailActionsMenuBtn')?.focus(); return; } if (typing || dialogOpen || e.metaKey || e.ctrlKey || e.altKey) return; if (e.key === '/') { const id = viewFilterInput[currentView]; if (id && $(id)) { e.preventDefault(); $(id).focus(); } } else if (e.key === '?') { e.preventDefault(); toggleShortcuts(); } diff --git a/sdk/server-ktor/src/main/resources/devconsole-web/index.html b/sdk/server-ktor/src/main/resources/devconsole-web/index.html index 1a8c1cc..f2070ff 100644 --- a/sdk/server-ktor/src/main/resources/devconsole-web/index.html +++ b/sdk/server-ktor/src/main/resources/devconsole-web/index.html @@ -57,6 +57,7 @@ + @@ -738,6 +739,12 @@