From 5b9b9c9b059bf301a8df960d14f1e225d64d262e Mon Sep 17 00:00:00 2001 From: yetone Date: Tue, 6 Oct 2026 22:41:28 +0800 Subject: [PATCH] =?UTF-8?q?gui:=20a=20call's=20JSON=20body=20in=20the=20Ga?= =?UTF-8?q?teway=20page's=20recent=20calls=20folds,=20is=20coloured=20and?= =?UTF-8?q?=20copies=20a=20key=20or=20a=20value=20(owner:=20=E8=BF=99?= =?UTF-8?q?=E9=87=8C=E5=BA=94=E8=AF=A5=E6=94=AF=E6=8C=81=20json=20?= =?UTF-8?q?=E5=AF=B9=E8=B1=A1=E6=8A=98=E5=8F=A0=E4=BB=A5=E5=8F=8A=E4=BB=A3?= =?UTF-8?q?=E7=A0=81=E9=AB=98=E4=BA=AE=E4=BB=A5=E5=8F=8A=E6=96=B9=E4=BE=BF?= =?UTF-8?q?=E5=A4=8D=E5=88=B6=E6=9F=90=E4=B8=AAkey/value)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Request and response bodies that are JSON, a stream's events and the reply put together are drawn as a tree: keys, strings, numbers and keywords in the code colours, an arrow before each object or array folds it to {…} with its count (lazily drawn on first unfold, folds kept across the list being redrawn), a copy button at the end of a line (on hover; faded rather than hidden so the pointer crossing to it keeps the line hovered) copies a string's text or an object's JSON, and a click on a key copies its name. The body's innerText stays the pretty-printed JSON (buttons are SVG only, 0 wide, nothing out of flow, which Chromium would break lines around). The {…} summary sits on the head's line, so a click on it holds that line, not the next one the unfolding pushes down. A cut or non-JSON body is as before. json-tree.test.cjs passes in Chromium and WebKit, en/zh/ja/de, 1000px and 440px; sse-body, recent-calls-more, request-archive, request-archive-usage, gateway-caller-keys, routing-side-calls, gui-ja, gui-de, i18n-keys and click-scroll pass in both engines. --- internal/gui/assets/app.css | 24 +++ internal/gui/assets/app.js | 118 ++++++++++-- internal/gui/assets/i18n.js | 18 ++ internal/gui/tests/README.md | 10 + internal/gui/tests/json-tree.test.cjs | 255 ++++++++++++++++++++++++++ 5 files changed, 411 insertions(+), 14 deletions(-) create mode 100644 internal/gui/tests/json-tree.test.cjs diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 9fd30f167..7c08ca27d 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -1778,6 +1778,30 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } .call-body .copy { width: 20px; height: 20px; } .call-body pre { margin: 0; padding: 9px 10px 11px; min-height: 54px; max-height: 280px; overflow: auto; border-top: 1px solid var(--line-2); background: var(--code-bg, var(--card-2)); } .call-body code { display: block; font: var(--code-style, normal) var(--code-weight, 400) 10.5px/1.5 var(--code-font, var(--code)); font-stretch: var(--code-stretch, 100%); color: var(--fg-2); white-space: pre-wrap; overflow-wrap: anywhere; user-select: text; -webkit-user-select: text; tab-size: 2; } +/* a JSON body's tree: the fold arrow sits in the indent before its line, + taking no width, so the text is the JSON as printed; a line's copy + button shows on its hover, after the value */ +.call-body code.jt { padding-left: 11px; } +.jt button { font: inherit; color: inherit; background: none; border: 0; padding: 0; cursor: pointer; } +/* no absolute positioning inside: Chromium's innerText would break the + line around a box taken out of the flow */ +.jt-fold { display: inline-block; width: 0; height: 1em; overflow: visible; white-space: nowrap; vertical-align: -.15em; } +.jt-fold svg { display: inline-block; margin-left: -12px; color: var(--faint); transition: transform .12s; } +.jt-fold.open svg { transform: rotate(90deg); } +.jt-fold:hover svg, .jt-fold:focus-visible svg { color: var(--fg); } +.jt-key { color: var(--tk-f); cursor: copy; } +.jt-key:hover { text-decoration: underline dotted; text-underline-offset: 2px; } +.jt-copy { display: inline-block; width: 0; height: 1em; overflow: visible; white-space: nowrap; vertical-align: -.2em; opacity: 0; } +.jt-copy svg { display: inline-block; margin-left: 5px; padding: 1px; width: 13px; height: 13px; border-radius: 3px; color: var(--muted); background: var(--code-bg, var(--card-2)); } +.jt-copy:hover svg { color: var(--fg); background: var(--pill-hover); } +.jt-copy.done svg { color: var(--green); } +/* faded, not hidden, so the pointer on its way across the gap to it still + finds it there */ +.jt-head:hover > .jt-copy, .jt-copy:focus-visible, .jt-copy.done { opacity: 1; } +.jt-kids[hidden], .jt-sum[hidden] { display: none; } +.jt-sum { color: var(--muted); border-radius: 3px; } +.jt-sum:hover { background: var(--pill-hover); color: var(--fg); } +.jt-sum::after { content: " " attr(data-n) " "; font-size: .9em; color: var(--faint); } .call-body code.empty { color: var(--faint); font-family: var(--ui-font, var(--font)); } :where(html[data-fonts]) .call-body code.empty { font-style: var(--ui-style, inherit); font-weight: var(--ui-weight, inherit); font-stretch: var(--ui-stretch, 100%); } @media (max-width: 760px) { .call-details { grid-template-columns: 1fr; } } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 0f2e5cd11..045770cc8 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -5688,6 +5688,90 @@ function formatWireBody(raw) { try { return JSON.stringify(JSON.parse(raw), null, 2); } catch { return raw; } } +// A JSON body as a tree: each object and array folds at its bracket, its +// parts in the snippets' colours; the copy button a line shows on hover +// copies its value, and a click on a key copies the key. The text is the +// JSON pretty-printed, as before, so what is selected and copied by hand +// still reads as JSON. What is folded is kept by the body's key and the +// node's path, across the redraws a new call brings. +const jsonFolds = new Set(); +function jsonTree(v, key) { + const code = el("code", "jt"); + code.append(jtNode(v, undefined, "", key + "|", "")); + return code; +} +function jtNode(v, k, indent, path, comma) { + const f = document.createDocumentFragment(); + const head = el("span", "jt-head"); + f.append(indent, head); + if (k !== undefined) { + const ks = el("span", "jt-key", JSON.stringify(k)); + ks.title = t("Click to copy the key"); + // a click copies; a drag selects, as in any text + ks.onclick = (ev) => { + ev.stopPropagation(); + if (!String(getSelection())) copy(String(k), String(k), null); + }; + head.append(ks, ": "); + } + const copyV = el("button", "jt-copy"); + copyV.type = "button"; + copyV.title = t("Copy value"); + copyV.append(svg(COPY_ICON, 11, 1.5)); + // a string's value is its text, not the JSON that quotes it + copyV.onclick = (ev) => { + ev.stopPropagation(); + copy(typeof v === "string" ? v : JSON.stringify(v, null, 2), k !== undefined ? String(k) : t("Value"), copyV); + }; + if (v === null || typeof v !== "object") { + head.append(el("span", typeof v === "string" ? "tk-s" : typeof v === "number" ? "tk-n" : "tk-k", JSON.stringify(v)), copyV); + f.append(comma); + return f; + } + const arr = Array.isArray(v); + const keys = arr ? v.map((_, i) => i) : Object.keys(v); + const [o, c] = arr ? ["[", "]"] : ["{", "}"]; + if (!keys.length) { + head.append(o + c, copyV); + f.append(comma); + return f; + } + const tog = el("button", "jt-fold"); + tog.type = "button"; + tog.append(svg(CHEV_R, 10, 1.6)); + const kids = el("span", "jt-kids"); + const sum = el("button", "jt-sum", "…"); + sum.type = "button"; + sum.title = t("Unfold"); + sum.dataset.n = t(keys.length === 1 ? "1 item" : "{n} items", { n: keys.length }); + // the summary is on the head's line: what a click on it holds in place is + // then its neighbours there, not the line after, which the unfolding pushes down + head.prepend(tog); + head.append(o, sum, copyV); + f.append(kids, c, comma); + let built = false; + const set = (folded) => { + if (!folded && !built) { // its insides are drawn the first time it opens + built = true; + keys.forEach((kk, i) => kids.append("\n", jtNode(v[kk], arr ? undefined : kk, indent + " ", path + "/" + kk, i < keys.length - 1 ? "," : ""))); + kids.append("\n" + indent); + } + kids.hidden = folded; + sum.hidden = !folded; + tog.classList.toggle("open", !folded); + tog.setAttribute("aria-expanded", String(!folded)); + tog.title = t(folded ? "Unfold" : "Fold"); + if (folded) jsonFolds.add(path); else jsonFolds.delete(path); + }; + // the box keeps its height across a fold, so what is below it, and the + // page, stay where they are + const keep = () => { const pre = tog.closest("pre"); if (pre) pre.style.minHeight = pre.offsetHeight + "px"; }; + tog.onclick = (ev) => { ev.stopPropagation(); keep(); set(!kids.hidden); }; + sum.onclick = (ev) => { ev.stopPropagation(); keep(); set(false); }; + set(jsonFolds.has(path)); + return f; +} + // A streamed body (server-sent events) as its events: each one's name and // its data, the data lines joined. Anything else is not one: null. function parseSSE(raw) { @@ -5833,10 +5917,11 @@ function sseReply(events) { } // The data of each event, as JSON where it is JSON, under its name. -function sseEventNode(e) { +function sseEventNode(e, key) { const box = el("span", "sse-ev"); if (e.event) box.append(el("span", "sse-name", "event: " + e.event + "\n")); - box.append(sseData(e.data)); + const d = jsonOr(e.data); + box.append(d !== null && typeof d === "object" ? jtNode(d, undefined, "", key + "|", "") : e.data); // [DONE] as it is return box; } function sseData(data) { @@ -5873,7 +5958,7 @@ function sseBodyPanel(label, raw, truncated, id) { let code = null, shown = 0; const more = () => { const upto = Math.min(events.length, Math.max(sseShown.get(id) || 0, shown + SSE_PAGE)); - for (; shown < upto; shown++) code.append(sseEventNode(events[shown])); + for (; shown < upto; shown++) code.append(sseEventNode(events[shown], id + "|ev" + shown)); if (shown > SSE_PAGE) sseShown.set(id, shown); foot.hidden = view !== "events" || shown >= events.length; shownNote.textContent = t("{n} of {total} events shown", { n: shown, total: events.length }); @@ -5884,12 +5969,11 @@ function sseBodyPanel(label, raw, truncated, id) { // the box keeps its height across a switch, so what is below it, and // the page, stay where they are if (pre.isConnected) pre.style.minHeight = pre.offsetHeight + "px"; - code = el("code"); + code = view === "reply" ? jsonTree(reply, id + "|reply") : el("code", view === "events" ? "jt" : ""); pre.replaceChildren(code); pre.scrollTop = 0; shown = 0; - if (view === "reply") code.textContent = JSON.stringify(reply, null, 2); - else if (view === "raw") code.textContent = raw; + if (view === "raw") code.textContent = raw; if (view === "events") more(); else foot.hidden = true; }; // what is copied is what is shown: the reply, every event, or the body @@ -5903,7 +5987,9 @@ function sseBodyPanel(label, raw, truncated, id) { return panel; } -function callBodyPanel(label, raw, truncated, id) { +// id, given, is a response's, whose stream reads as its events; key names +// the body for what is folded in it +function callBodyPanel(label, raw, truncated, id, key = id) { if (id) { const sse = sseBodyPanel(label, raw, truncated, id); if (sse) return sse; @@ -5916,9 +6002,13 @@ function callBodyPanel(label, raw, truncated, id) { if (formatted) head.append(el("span", "grow"), copyBtn(raw, t(label))); panel.append(head); const pre = el("pre"); - const code = el("code", "", formatted || t("No body captured")); - if (!formatted) code.classList.add("empty"); - pre.append(code); + const v = formatted ? jsonOr(raw) : undefined; + if (v !== null && typeof v === "object") pre.append(jsonTree(v, key)); + else { + const code = el("code", "", formatted || t("No body captured")); + if (!formatted) code.classList.add("empty"); + pre.append(code); + } panel.append(pre); return panel; } @@ -6014,7 +6104,7 @@ async function downloadArchive(name, b) { // one body read back from the archive: shown, or, past 256 KB, only its // size — the server leaves it out — for the file to be downloaded whole -function archiveBodyPanel(label, part, id) { +function archiveBodyPanel(label, part, id, key = id) { if (part.omitted) { const panel = el("section", "call-body"); const head = el("div", "call-body-head"); @@ -6024,7 +6114,7 @@ function archiveBodyPanel(label, part, id) { } // cut where the archive stops: its limit, or 256 KB in one from before #447 const cut = part.truncated && (part.size ? t("first {n} of {size}", { n: fmtBytes(new Blob([part.body]).size), size: fmtBytes(part.size) }) : true); - return callBodyPanel(label, part.body, cut, id); + return callBodyPanel(label, part.body, cut, id, key); } // A call the archive kept, by "/": read back when asked, and its @@ -6066,7 +6156,7 @@ function archivePanel(name, id, redraw) { grid.append( headersPanel(t("Request Headers"), `${got.request.method || ""} ${got.request.path || ""}`.trim(), got.request.headers), headersPanel(t("Response Headers"), got.response.status ? `HTTP ${got.response.status}` : "", got.response.headers), - archiveBodyPanel("Request Body", got.request), + archiveBodyPanel("Request Body", got.request, undefined, id + "|archive|req"), archiveBodyPanel("Response Body", got.response, id + "|archive"), ); box.append(grid); @@ -6113,7 +6203,7 @@ function renderActivity() { if (open) { const details = el("div", "call-details"); details.append( - callBodyPanel("Request Body", c.requestBody, c.requestTruncated), + callBodyPanel("Request Body", c.requestBody, c.requestTruncated, undefined, id + "|req"), callBodyPanel("Response Body", c.responseBody, c.responseTruncated, id), ); item.dataset.id = id; diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 7bd72d38b..68ada4fa8 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -1798,6 +1798,12 @@ const I18N = { "Raw": "原文", "1 event": "1 个事件", "{n} events": "{n} 个事件", + "Click to copy the key": "点击复制键名", + "Copy value": "复制值", + "Value": "值", + "Unfold": "展开", + "1 item": "1 项", + "{n} items": "{n} 项", "{n} of {total} events shown": "已显示 {n} / {total} 个事件", "Show {n} more events": "再显示 {n} 个事件", @@ -5346,6 +5352,12 @@ const I18N = { "Raw": "Raw", "1 event": "1 件のイベント", "{n} events": "{n} 件のイベント", + "Click to copy the key": "クリックでキーをコピー", + "Copy value": "値をコピー", + "Value": "値", + "Unfold": "展開", + "1 item": "1 件", + "{n} items": "{n} 件", "{n} of {total} events shown": "{total} 件中 {n} 件のイベントを表示", "Show {n} more events": "さらに {n} 件のイベントを表示", "Today": "今日", @@ -8885,6 +8897,12 @@ const I18N = { "Raw": "Roh", "1 event": "1 Ereignis", "{n} events": "{n} Ereignisse", + "Click to copy the key": "Klicken, um den Schlüssel zu kopieren", + "Copy value": "Wert kopieren", + "Value": "Wert", + "Unfold": "Aufklappen", + "1 item": "1 Eintrag", + "{n} items": "{n} Einträge", "{n} of {total} events shown": "{n} von {total} Ereignissen angezeigt", "Show {n} more events": "{n} weitere Ereignisse anzeigen", "Today": "Heute", diff --git a/internal/gui/tests/README.md b/internal/gui/tests/README.md index 8656cc32f..292244844 100644 --- a/internal/gui/tests/README.md +++ b/internal/gui/tests/README.md @@ -358,6 +358,16 @@ the pick remembered. A 450-event stream draws 200 at a time from a button under the box that stays where it is, the page too; a body that isn't a stream is as before. English and Chinese, Chromium and WebKit. +`json-tree.test.cjs` opens a JSON request and response in the Gateway page's +recent calls: keys, strings, numbers and keywords each have their colour, the +body's text is still the pretty-printed JSON, an object or array folds to +`{…}` with its count and unfolds from its arrow or that summary with the page +kept where it is, a fold outlives the list being drawn again, a value's copy +button (shown on hovering its line) copies a string's text or an object's +JSON, a click on a key copies its name, and a stream's events and its reply +fold the same way. English, Chinese, Japanese and German, 1000px and 440px, +Chromium and WebKit. + `routing-kind.test.cjs` lists calls Codex makes for itself (a guardian review, a title, memories, a turn on Luna Reserve, a kind it does not know yet): each has a grey tag by its model in the Requests list, in English and Chinese, the diff --git a/internal/gui/tests/json-tree.test.cjs b/internal/gui/tests/json-tree.test.cjs new file mode 100644 index 000000000..d06f41826 --- /dev/null +++ b/internal/gui/tests/json-tree.test.cjs @@ -0,0 +1,255 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A call's JSON body in the Gateway page's recent calls is a tree: its +// objects and arrays fold, its parts are coloured, a line's value copies from +// the button its hover shows and a key copies on a click, its text still the +// JSON as printed; what is folded stays folded as new calls come in, and no +// click moves the page. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const now = Date.now(); + +// the shape of a Codex call's bodies (#1033's screenshot) +const request = { + client_metadata: { + turn_id: "01a11181-1f12-7af1-b5d2-9a7099413ddd", + guardian_credits_requested: "true", + "x-codex-turn-metadata": "{\"installation_id\":\"519287e5\",\"request_kind\":\"turn\"}", + }, + model: "gpt-6-luna", + stream: true, + max_output_tokens: 32000, + store: false, + include: [], + tools: [{ type: "function", name: "shell", strict: false, parameters: { type: "object", properties: { cmd: { type: "string" } } } }], + previous_response_id: null, +}; +const response = { + id: "resp_06bc9d430c97ada1016ac4fe3ef55487d0aa948a5118e0509f", + model: "gpt-6-luna", + status: "completed", + output: [{ type: "message", text: "{\"exclude\":[]}" }], + usage: { input_tokens: 4453, cached_tokens: 0, output_tokens: 0 }, +}; +const stream = [ + ["response.created", { type: "response.created", response: { id: "resp_1", model: "gpt-6-luna", status: "in_progress" } }], + ["response.output_text.delta", { type: "response.output_text.delta", item_id: "m_1", delta: "Hi" }], +].map(([n, d]) => `event: ${n}\ndata: ${JSON.stringify(d)}\n\n`).join(""); + +const call = (i, model, requestBody, responseBody) => ({ + time: new Date(now - (i + 1) * 60e3).toISOString(), agent: "codex", model, from: "responses", to: "responses", status: 200, ms: 1800, ttft: 1600, + requestBody, responseBody, +}); +const calls = [ + call(0, "codex/gpt-6-luna", JSON.stringify(request), JSON.stringify(response)), + call(1, "codex/stream", JSON.stringify({ model: "gpt-6-luna", stream: true }), stream), + call(2, "codex/cut", "{\"model\":\"gpt-6-luna\",\"input\":[{\"role\":\"user\"", "not json"), +]; +const providers = { + providers: [{ id: "codex", name: "Codex", icon: "generic", models: [{ id: "gpt-6-luna", name: "gpt-6-luna", on: true }], agents: [] }], + gateway: { running: true, window: true, mine: true, url: "http://127.0.0.1:3999", calls, groups: [] }, +}; + +function serve(lang, copied) { + return async (route) => { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/copy") { copied.push(JSON.parse(route.request().postData()).text); return json({}); } + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } }); + if (url.pathname === "/api/providers") return json(providers); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/gateway/trace") { + if (url.searchParams.get("wait")) await new Promise((r) => setTimeout(r, 20e3)); + return json({ mine: true, now: new Date(now).toISOString(), seq: 1, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] }); + } + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + await route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +const words = { + en: { items: "4 items", one: "1 item", copyValue: "Copy value", copyKey: "Click to copy the key", fold: "Fold", unfold: "Unfold", events: "Events", reply: "Reply" }, + zh: { items: "4 项", one: "1 项", copyValue: "复制值", copyKey: "点击复制键名", fold: "收起", unfold: "展开", events: "事件", reply: "回复" }, + ja: { items: "4 件", one: "1 件", copyValue: "値をコピー", copyKey: "クリックでキーをコピー", fold: "折りたたむ", unfold: "展開", events: "イベント", reply: "返信" }, + de: { items: "4 Einträge", one: "1 Eintrag", copyValue: "Wert kopieren", copyKey: "Klicken, um den Schlüssel zu kopieren", fold: "Einklappen", unfold: "Aufklappen", events: "Ereignisse", reply: "Antwort" }, +}; +const view = "#view-gateway"; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh", "ja", "de"]) { + for (const width of [1000, 440]) { + test(`${engine} ${lang} ${width}px: a JSON body folds, is coloured and copies a key or a value`, async (t) => { + assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit"); + const w = words[lang]; + const copied = []; + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const context = await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" }); + const page = await context.newPage(); + page.setDefaultTimeout(5000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, copied)); + t.after(async () => { + if (process.env.ARTIFACT_DIR) { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-json-tree.png`) }); + } + await browser.close(); + }); + + await page.goto("http://magpie.test/?view=gateway"); + await page.locator("#foldConnect").click(); // Connect away, the calls in view + const rows = page.locator("#activity .call-item"); + await rows.first().waitFor(); + // what is clicked is brought into view by the wheel, as the reader + // would, and clicked where it is (the app puts back any other scroll) + const reach = async (loc) => { + const [dy, x, y] = await loc.evaluate((e) => { + const v = document.querySelector("#view-gateway").getBoundingClientRect(); + return [e.getBoundingClientRect().top - v.top - v.height / 2, v.left + 6, v.top + v.height / 2]; + }); + await page.mouse.move(x, y); + await page.mouse.wheel(0, dy); + let b = await loc.boundingBox(); + for (let i = 0; i < 20; i++) { + await page.waitForTimeout(120); + const n = await loc.boundingBox(); + if (n.y === b.y) break; + b = n; + } + return b; + }; + const press = async (loc) => { + const b = await reach(loc); + const at = await page.locator(view).evaluate((v) => v.scrollTop); + await page.mouse.click(b.x + b.width / 2, b.y + b.height / 2); + await page.waitForTimeout(150); + assert.equal(await page.locator(view).evaluate((v) => v.scrollTop), at, "a click leaves the page where it is"); + }; + const req = rows.nth(0).locator(".call-body").nth(0); + const res = rows.nth(0).locator(".call-body").nth(1); + // what was copied, once the copy's request is in + const got = async (n) => { + for (let i = 0; i < 40 && copied.length < n; i++) await page.waitForTimeout(50); + return copied; + }; + const text = async (body) => (await body.locator("pre").innerText()).replace(/\n$/, ""); + + await press(rows.nth(0).locator(".call")); + // the text is the JSON as printed, so a selection copies as JSON + assert.equal(await text(req), JSON.stringify(request, null, 2)); + assert.equal(await text(res), JSON.stringify(response, null, 2)); + + // coloured: keys, strings, numbers, and true, false and null + const tree = req.locator("code.jt"); + assert.equal(await tree.locator(".jt-key").first().innerText(), "\"client_metadata\""); + assert.equal(await tree.locator(".tk-s").first().innerText(), "\"01a11181-1f12-7af1-b5d2-9a7099413ddd\""); + assert.equal(await tree.locator(".tk-n").first().innerText(), "32000"); + assert.deepEqual(await tree.locator(".tk-k").allInnerTexts(), ["true", "false", "false", "null"]); + const colours = await tree.evaluate((c) => ["jt-key", "tk-s", "tk-n", "tk-k"].map((k) => getComputedStyle(c.querySelector("." + k)).color)); + assert.equal(new Set(colours).size, 4, "each part has its own colour"); + assert.notEqual(colours[0], await tree.evaluate((c) => getComputedStyle(c).color), "a key isn't the text's colour"); + + // the fold arrow sits in the indent, taking no width: the key starts + // where the JSON as printed has it + const meta = tree.locator(".jt-head").nth(1); + const fold = meta.locator(".jt-fold"); + assert.equal(await fold.getAttribute("title"), w.fold); + assert.equal(await fold.evaluate((b) => b.getBoundingClientRect().width), 0); + const arrow = await fold.locator("svg").boundingBox(); + const key = await meta.locator(".jt-key").boundingBox(); + assert(arrow.x + arrow.width <= key.x + 1, "the arrow is before the key, not on it"); + assert(arrow.x >= (await req.locator("pre").boundingBox()).x, "and inside the box"); + + // a fold closes the object to {…} and says how many it holds + await press(fold.locator("svg")); + assert.equal(await fold.getAttribute("aria-expanded"), "false"); + assert.equal(await fold.getAttribute("title"), w.unfold); + const folded = { ...request, client_metadata: "§" }; + assert.equal(await text(req), JSON.stringify(folded, null, 2).replace("\"§\"", "{…}")); + const sum = tree.locator(".jt-sum:not([hidden])").first(); + assert.equal(await sum.evaluate((s) => getComputedStyle(s, "::after").content.replace(/"/g, "").trim()), w.items.replace("4", "3")); + + // and stays so as a new call comes in and the list is drawn again + await page.evaluate(() => renderActivity()); + assert.equal(await text(req), JSON.stringify(folded, null, 2).replace("\"§\"", "{…}")); + assert.equal(await text(res), JSON.stringify(response, null, 2), "the other body is untouched"); + // a click on the … opens it again + await press(tree.locator(".jt-sum:not([hidden])").first()); + assert.equal(await text(req), JSON.stringify(request, null, 2)); + + // a line's copy button shows on its hover, after the value, and + // copies the value: a string's text, not its quotes; an object as JSON + const line = tree.locator(".jt-head").filter({ hasText: "x-codex-turn-metadata" }); + const copyB = line.locator(".jt-copy"); + assert.equal(await copyB.evaluate((b) => getComputedStyle(b).opacity), "0"); + await reach(line); + await line.locator(".jt-key").hover(); // the value wraps: its box's middle can be a gap + // the app's every transition takes a frame, even with motion reduced + await page.waitForFunction((b) => getComputedStyle(b).opacity === "1", await copyB.elementHandle()); + assert.equal(await copyB.getAttribute("title"), w.copyValue); + const v = await line.locator(".tk-s").boundingBox(); + const cb = await copyB.locator("svg").boundingBox(); + assert(cb.x >= v.x + v.width - 1 || cb.y > v.y, "the button is after the value, not over it"); + // the pointer crosses from the value to the button as a hand would + await page.mouse.move(v.x + v.width - 2, v.y + v.height - 4); + await page.mouse.move(cb.x + cb.width / 2, cb.y + cb.height / 2, { steps: 6 }); + await page.mouse.down(); + await page.mouse.up(); + assert.deepEqual(await got(1), [request.client_metadata["x-codex-turn-metadata"]]); + assert.equal(await text(req), JSON.stringify(request, null, 2), "the tick it shows adds no text"); + + const tools = tree.locator(".jt-head").filter({ has: page.locator(".jt-key", { hasText: /^"tools"$/ }) }); + await reach(tools); + await tools.locator(".jt-key").hover(); + const tb = await tools.locator(".jt-copy svg").boundingBox(); + await page.mouse.click(tb.x + tb.width / 2, tb.y + tb.height / 2); + assert.deepEqual(JSON.parse((await got(2))[1]), request.tools); + assert.equal(copied[1], JSON.stringify(request.tools, null, 2)); + + // a click on a key copies the key + const k = tree.locator(".jt-key", { hasText: /^"max_output_tokens"$/ }); + assert.equal(await k.getAttribute("title"), w.copyKey); + await press(k); + assert.equal((await got(3))[2], "max_output_tokens"); + + // an empty array has nothing to fold; a cut body is shown as it came + assert.equal(await tree.locator(".jt-head", { has: page.locator(".jt-key", { hasText: /^"include"$/ }) }).locator(".jt-fold").count(), 0); + await press(rows.nth(2).locator(".call")); + assert.equal(await rows.nth(2).locator("code.jt").count(), 0); + assert.equal(await rows.nth(2).locator(".call-body").nth(1).locator("pre").innerText(), "not json"); + + // a stream: each event's data, and the reply, fold the same way + await press(rows.nth(1).locator(".call")); + const sse = rows.nth(1).locator(".call-body").nth(1); + await press(sse.locator(".segs .opt", { hasText: w.events })); + const ev = sse.locator(".sse-ev").first(); + assert.match(await ev.innerText(), /^event: response\.created\n\{\n "type": "response\.created",\n "response": \{/); + await press(ev.locator(".jt-fold svg").nth(1)); + assert.equal(await ev.innerText(), "event: response.created\n{\n \"type\": \"response.created\",\n \"response\": {…}\n}"); + assert.equal(await ev.locator(".jt-sum:not([hidden])").evaluate((s) => getComputedStyle(s, "::after").content.replace(/"/g, "").trim()), w.items.replace("4", "3")); + await press(sse.locator(".segs .opt", { hasText: w.reply })); + assert.deepEqual(JSON.parse(await sse.locator("pre").innerText()), { id: "resp_1", model: "gpt-6-luna", status: "in_progress", output: [{ type: "message", text: "Hi" }] }); + const out = sse.locator(".jt-head").filter({ has: page.locator(".jt-key", { hasText: /^"output"$/ }) }); + await press(out.locator(".jt-fold svg")); + assert.equal(await sse.locator(".jt-sum:not([hidden])").first().evaluate((s) => getComputedStyle(s, "::after").content.replace(/"/g, "").trim()), w.one); + await press(sse.locator(".segs .opt", { hasText: w.events })); + assert.equal(await sse.locator(".sse-ev").first().innerText(), "event: response.created\n{\n \"type\": \"response.created\",\n \"response\": {…}\n}", "the event's fold is kept across a switch"); + + // nothing scrolls sideways + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true); + assert.equal(await req.locator("pre").evaluate((p) => p.scrollWidth <= p.clientWidth), true); + assert.deepEqual(errors, []); + }); + } + } +}