From 4ffde8471a80155512947b5be640e2d24a01fb3e Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Sat, 10 Oct 2026 00:39:22 +0800 Subject: [PATCH 1/3] fix: embed face follows the dsh host theme; frame breathing room (#2559 #2560) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #2559 Closes #2560 Dark readability (#2559): the embed face sits in an iframe whose prefers-color-scheme tracks the OS, not the host app — so a dark dsh panel with an OS-level light preference rendered the light palette onto the host's dark ground and the text went unreadable. The client now samples its own page ground at panel mount (opaque background luminance vote over documentElement/body/main/#root/#app, matchMedia fallback, all failure paths → unpinned) and pins the result on the iframe URL as &theme=light|dark. /__bili/ whitelists the param onto , which carries the existing dark palette verbatim plus a matching color-scheme declaration; the OS-signal media block narrows to :not([data-theme]) so the two palettes never fight (explicit pin always wins). Live theme toggles piggyback the existing origin probe tick (<=10s lag) — no new timer, no postMessage channel. Frame padding (#2560): .embed main gains 8px/10px/16px padding instead of hugging the frame edge on all four sides. --- src/agent/dsh-native-client.ts | 87 ++++++++++++++++++++++++++++++++-- src/server/admin.ts | 7 ++- src/web/index.ts | 7 ++- src/web/page.ts | 6 ++- src/web/styles.ts | 36 +++++++++++++- tests/dsh-settings-ui.test.ts | 61 ++++++++++++++++++++++++ tests/web-i18n.test.ts | 15 ++++++ 7 files changed, 207 insertions(+), 12 deletions(-) diff --git a/src/agent/dsh-native-client.ts b/src/agent/dsh-native-client.ts index 95cd492d46..d041928869 100644 --- a/src/agent/dsh-native-client.ts +++ b/src/agent/dsh-native-client.ts @@ -28,7 +28,11 @@ // and the frame height follows the host viewport. lang mirrors the host // locale: bind() resolves against the live dsh locale, and comparing the // resolved nav label with the registered zh value is the only locale signal -// the client contract exposes. The same panel is mounted at two slots (#2125): settings.section +// the client contract exposes. #2559: theme follows the HOST page too — +// an app-level dsh dark setting is invisible to the framed document's +// prefers-color-scheme, so we sample the actual on-screen ground of this page +// (same-origin) and pin the face via &theme=light|dark; first paint reads it +// synchronously, later probe ticks pick up mid-session toggles. The same panel is mounted at two slots (#2125): settings.section // (always present — the launcher posture has no bundle page) and // plugins.bundle.config (keyed by package name; the plugin detail page renders // it only when this package is installed as a profile bundle and draws the @@ -86,6 +90,68 @@ const PAGE_KEYS: Record = { }; const EMBED_HEIGHT = "min(640px, 78vh)"; +/** #2559: classify the host page's actual ground as light/dark. The framed + * bili face is a separate document — it only sees the browser/OS + * color-scheme, while dsh's dark theme is app-level. Same origin lets us + * sample what the user actually sees: walk the usual ground candidates, + * read each opaque background-color, vote by simple weighted luminance + * (near-black app grounds < 0.4, near-white > 0.4). No readable signal at + * all ⇒ fall back to the OS signal; nothing even for that ⇒ undefined and + * the frame stays OS-driven. Every read is guard-wrapped: older hosts or + * minimal DOMs must degrade to "no pin", never crash the panel. */ +type ThemeDom = { + document?: { documentElement?: unknown; body?: { querySelector?: (sel: string) => unknown } & Record }; + getComputedStyle?: (el: unknown) => { backgroundColor?: unknown }; + matchMedia?: (q: string) => { matches: boolean }; +}; +function detectHostTheme(): "light" | "dark" | undefined { + const g = globalThis as ThemeDom; + try { + const doc = g.document; + if (!doc || typeof g.getComputedStyle !== "function") return undefined; + const candidates: unknown[] = []; + if (doc.documentElement) candidates.push(doc.documentElement); + if (doc.body) candidates.push(doc.body); + try { + for (const sel of ["main", "[role=main]", "#root", "#app"]) { + const el = doc.body?.querySelector?.(sel); + if (typeof el === "object" && el !== null) candidates.push(el); + } + } catch { + // non-DOM harness: ground sampling below just yields no votes + } + let lightVotes = 0; + let darkVotes = 0; + for (const c of candidates) { + let bg: string; + try { + const v = g.getComputedStyle!(c).backgroundColor; + if (typeof v !== "string") continue; + bg = v; + } catch { + continue; + } + const m = /rgba?\(([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)(?:[,\/\s]+([\d.]+))?\)/.exec(bg); + if (!m) continue; // transparent / named / unparsable → no vote + const alpha = m[4] !== undefined ? Number(m[4]) : 1; + if (alpha <= 0.5) continue; + const luma = (0.2126 * Number(m[1]) + 0.7152 * Number(m[2]) + 0.0722 * Number(m[3])) / 255; + if (luma <= 0.4) darkVotes += 1; + else lightVotes += 1; + } + if (darkVotes !== lightVotes && (darkVotes > 0 || lightVotes > 0)) return darkVotes > lightVotes ? "dark" : "light"; + } catch { + return undefined; + } + try { + const mq = g.matchMedia?.("(prefers-color-scheme: dark)"); + if (mq) return mq.matches ? "dark" : "light"; + } catch { + // no media support either — leave the face OS-driven + } + return undefined; +} + const zh: Dict = { "nav": "bili设置", "title": "billion-context 压缩代理", @@ -125,8 +191,12 @@ function openExternal(url: string): void { * of the mount; returns the cancel used as the effect cleanup (no fetch ⇒ * no-op, older hosts without the route simply stay on the snapshot or * degrade). The snapshot is only a first-paint hint — the host re-binds the - * origin at runtime, so polling never stops after a resolution. */ -function probeOrigin(onOrigin: (origin: string) => void): () => void { + * origin at runtime, so polling never stops after a resolution. + * #2559: every successful tick also re-classifies the host ground and pushes + * a fresh theme pin — mid-session theme toggles land within one slow phase. + * No extra timers are scheduled here (the test pins in tests/dsh-settings-ui + * count every delay on this queue). */ +function probeOrigin(onOrigin: (origin: string) => void, onTheme?: (theme: "light" | "dark") => void): () => void { if (typeof fetch !== "function") return () => {}; let cancelled = false; let settled = false; @@ -141,6 +211,10 @@ function probeOrigin(onOrigin: (origin: string) => void): () => void { onOrigin(data.origin); settled = true; } + if (onTheme) { + const theme = detectHostTheme(); + if (theme !== undefined) onTheme(theme); + } } } catch { // host without the route (older builds) or transient error: retry below @@ -171,9 +245,12 @@ export function apply(ctx: ClientContext): void { const panel = (titled: boolean): ((props: Record) => unknown) => () => { const [origin, setOrigin] = useState(readOrigin()); const [page, setPage] = useState("overview"); + // #2559: synchronous first paint — the very first render already pins + // the palette to the host's current ground (no wrong-scheme flash). + const [theme, setTheme] = useState<("light" | "dark") | undefined>(detectHostTheme); // #2288: no guard on the snapshot — the live route is authoritative // for the whole mount, so a stale boot value is corrected in place. - useEffect(() => probeOrigin(setOrigin), []); + useEffect(() => probeOrigin(setOrigin, setTheme), []); const lang = t("nav") === zhDict.nav ? "zh" : "en"; return createElement( "div", @@ -212,7 +289,7 @@ export function apply(ctx: ClientContext): void { ), ), createElement("iframe", { - src: `${origin}/__bili/?embed=1&lang=${lang}#/${page}`, + src: `${origin}/__bili/?embed=1&lang=${lang}${theme ? `&theme=${theme}` : ""}#/${page}`, title: t("title"), style: { display: "block", diff --git a/src/server/admin.ts b/src/server/admin.ts index 75e46f51c4..6a6e0cfa98 100644 --- a/src/server/admin.ts +++ b/src/server/admin.ts @@ -182,8 +182,13 @@ export async function handleAdminRoute(req: http.IncomingMessage, res: http.Serv if (req.method === "GET" && req.url !== undefined && (req.url === "/__bili/" || req.url.startsWith("/__bili/?"))) { const u = new URL(req.url, "http://localhost"); const origin = `http://${opts.host === "0.0.0.0" ? "localhost" : opts.host}:${opts.port}`; + // #2559: embedding hosts pin the face's palette explicitly (?theme= + // light|dark) because app-level host themes are invisible to the + // framed document's prefers-color-scheme. + const rawTheme = u.searchParams.get("theme"); + const theme = rawTheme === "light" || rawTheme === "dark" ? rawTheme : undefined; res.writeHead(200, { "content-type": "text/html; charset=utf-8" }); - res.end(renderUI(origin, { embed: u.searchParams.get("embed") === "1" })); + res.end(renderUI(origin, { embed: u.searchParams.get("embed") === "1", theme })); return; } if (req.method === "GET" && req.url === "/__bili/config") return handleConfigGet(res); diff --git a/src/web/index.ts b/src/web/index.ts index a620eaf576..708dd5475b 100644 --- a/src/web/index.ts +++ b/src/web/index.ts @@ -11,11 +11,14 @@ export { export { buildOverview, buildSessionList, buildSessionPage, buildSessionDetail, hiddenEmptyCount } from "./sessions-data.js"; -export function renderUI(origin: string, opts?: { embed?: boolean }): string { +export function renderUI(origin: string, opts?: { embed?: boolean; theme?: "light" | "dark" }): string { // #1426 fix: reuse the bundle-safe VERSION from src/version.ts — resolving // package.json relative to import.meta.url broke once tsup bundles this // module into dist/index.js (two levels up from dist/ misses the repo). // #2321: opts.embed renders the frameless face for hosts that embed the UI // in an iframe (the dsh settings panel). - return renderPage(origin, `${VERSION} (${BUILD_COMMIT})`, opts?.embed === true); + // #2559: opts.theme pins the palette for hosts whose app-level theme is + // invisible to the framed document's prefers-color-scheme. + const theme = opts?.theme === "light" || opts?.theme === "dark" ? opts.theme : undefined; + return renderPage(origin, `${VERSION} (${BUILD_COMMIT})`, opts?.embed === true, theme); } diff --git a/src/web/page.ts b/src/web/page.ts index 23c3a089c1..4802d0448b 100644 --- a/src/web/page.ts +++ b/src/web/page.ts @@ -11,12 +11,14 @@ function escapeHtml(value: string): string { char === "&" ? "&" : char === "<" ? "<" : char === ">" ? ">" : char === '"' ? """ : "'"); } -export function renderPage(origin: string, version: string, embed = false): string { +// #2559: theme pins the face's palette explicitly for embedding hosts (?theme= +// light|dark → ); see the #2559 note in styles.ts. +export function renderPage(origin: string, version: string, embed = false, theme?: "light" | "dark"): string { const o = escapeHtml(origin); const caPath = rootCaPath(); const caPathEsc = escapeHtml(caPath); const caReady = existsSync(caPath); - return `billion-context + return `billion-context
billion-contextv${version}
diff --git a/src/web/styles.ts b/src/web/styles.ts index 346cd10433..e6c616b169 100644 --- a/src/web/styles.ts +++ b/src/web/styles.ts @@ -26,8 +26,14 @@ export const WEB_STYLES = String.raw` --radius: 10px; --mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace; } +/* #2559: an embedding host can pin the face explicitly (?theme=light|dark → + ) because a host APP-level theme is invisible to the + framed document's prefers-color-scheme. An explicit pin outranks the OS + signal, so the media query below is narrowed to documents WITHOUT one; + the pinned palette repeats the same list (CSS cannot share declarations + across media boundaries — keep the two lists in sync). */ @media (prefers-color-scheme: dark) { - :root { + :root:not([data-theme]) { --bg: #0d1117; --bg-elev: #161b22; --bg-muted: #1c2129; @@ -48,6 +54,30 @@ export const WEB_STYLES = String.raw` --shadow: 0 1px 3px rgba(0, 0, 0, 0.4); } } +:root[data-theme="dark"] { + color-scheme: dark; + --bg: #0d1117; + --bg-elev: #161b22; + --bg-muted: #1c2129; + --border: #30363d; + --border-soft: #21262d; + --text: #e6edf3; + --text-muted: #8b949e; + --text-faint: #6e7681; + --accent: #4493f8; + --accent-soft: rgba(68, 147, 248, 0.14); + --green: #3fb950; + --green-soft: rgba(63, 185, 80, 0.14); + --red: #f85149; + --red-soft: rgba(248, 81, 46, 0.12); + --amber: #d29922; + --amber-soft: rgba(210, 153, 34, 0.14); + --purple: #a371f7; + --shadow: 0 1px 3px rgba(0, 0, 0, 0.4); +} +:root[data-theme="light"] { + color-scheme: light; +} * { box-sizing: border-box; } html, body { margin: 0; padding: 0; } body { @@ -386,6 +416,8 @@ pre.tool-args, pre.tool-out { margin: 6px 0 0; padding: 8px; background: var(--b collapses and rows render double-exposed. */ .embed table.data colgroup col:nth-child(n + 6) { width: 0 !important; } .embed .twide table.data th, .embed .twide table.data td { padding-left: 5px; padding-right: 5px; } -.embed main { max-width: none; padding: 4px 0 12px; } +/* #2560: the frame hugs its edges hard at narrow panel widths — give the + embed face a little breathing room instead of zero gutter. */ +.embed main { max-width: none; padding: 8px 10px 16px; } .embed .banner { margin: 8px 0 0; } `; diff --git a/tests/dsh-settings-ui.test.ts b/tests/dsh-settings-ui.test.ts index 5450646a3c..2c77c2c78f 100644 --- a/tests/dsh-settings-ui.test.ts +++ b/tests/dsh-settings-ui.test.ts @@ -860,6 +860,67 @@ test("#1809/#2125/#2187: client polls /bili/origin while unresolved — upgrades assert.ok(cleared >= 1, "the pending retry is cancelled on unmount"); assert.equal(pending.length, 0, "no timers survive unmount"); } + + { + // #2559: the host page's actual ground drives the face's palette. + // A dark ground pins &theme=dark ALREADY ON FIRST PAINT (synchronous + // sample — fed here through the __BILI__ origin snapshot so no probe + // round-trip stands between render and frame) and a light ground pins + // &theme=light; unpinned sandboxes (all earlier scenarios) keep the + // old exact srcs above, proving a DOM-less host stays OS-driven. + const mkDom = (bg: string): Record => ({ + __BILI__: { origin: "http://127.0.0.1:9998" }, + document: { + documentElement: {}, + body: { querySelector: (_sel: string): unknown => undefined }, + }, + getComputedStyle: (_el: unknown): unknown => ({ backgroundColor: bg }), + }); + for (const [bg, theme] of [ + ["rgb(13,17,23)", "dark"], + ["rgba(22,27,34,0.98)", "dark"], + ["rgb(247,248,250)", "light"], + ] as Array<[string, string]>) { + const m = mount({ + fetch: async () => ({ ok: true, json: async () => ({ origin: "http://127.0.0.1:9998" }) }), + setTimeout, + clearTimeout, + ...mkDom(bg), + }); + m.resetHooks(); + const painted = m.component() as ElementNode; + const frame = findTag(painted, "iframe"); + assert.ok(frame !== undefined, `ground ${bg} still upgrades on first paint`); + assert.equal( + frame.props?.src, + `http://127.0.0.1:9998/__bili/?embed=1&lang=zh&theme=${theme}#/overview`, + `ground ${bg} classifies ${theme} on the very first paint`, + ); + m.runCleanups(); + } + } +}); + +test("#2559: explicit host theme pin overrides the OS palette; #2560 embed frame padding", () => { + // A framed document only sees the browser/OS color-scheme, while dsh's + // dark theme is app-level — the host client samples its real ground and + // pins the face via ?theme= (renderPage → ). An + // explicit pin must OUTRANK the media query, so the OS-driven block + // narrows to :not([data-theme]) while the pinned palette repeats it. + const styles = fs.readFileSync(new URL("../src/web/styles.ts", import.meta.url), "utf8"); + assert.ok( + styles.includes("@media (prefers-color-scheme: dark) {\n :root:not([data-theme]) {"), + "the OS-driven dark palette stays out of explicitly pinned documents", + ); + assert.ok(styles.includes(':root[data-theme="dark"] {'), "an explicit dark pin carries the full dark palette"); + assert.ok( + styles.includes(':root[data-theme="light"] {\n color-scheme: light;\n}'), + "an explicit light pin rebinds the canvas over a dark OS", + ); + assert.ok( + styles.includes(".embed main { max-width: none; padding: 8px 10px 16px; }"), + "the embed face keeps a breathing gutter around the frame edge", + ); }); test("#2125: the manifest declares no dsh.client.inject (pre-0.2 dsh compat)", () => { diff --git a/tests/web-i18n.test.ts b/tests/web-i18n.test.ts index 7773f2b1c0..3f4f708277 100644 --- a/tests/web-i18n.test.ts +++ b/tests/web-i18n.test.ts @@ -162,6 +162,21 @@ test("#2321: embed mode marks the body for chrome-less framing", () => { assert.ok(embedded.includes(''), "embed flag marks the body"); }); +test("#2559: renderPage pins an explicit theme on only when given", () => { + // The dsh client appends &theme=light|dark when its own page ground + // disagrees with (or pre-empts) the OS signal; the pin rides on + // so styles.ts can scope both the palette and color-scheme to it. + const dark = renderPage("http://127.0.0.1:8787", "0.0.0-test", true, "dark"); + assert.ok(dark.includes(''), "dark pin lands on "); + const light = renderPage("http://127.0.0.1:8787", "0.0.0-test", false, "light"); + assert.ok(light.includes(''), "light pin lands on "); + const unpinned = renderPage("http://127.0.0.1:8787", "0.0.0-test", true); + assert.ok( + unpinned.startsWith(''), + "no pin keeps the plain element (CSS may mention data-theme)", + ); +}); + test("#1024: embedded client parses and persists the language choice", () => { assert.doesNotThrow(() => new Function(WEB_CLIENT)); assert.match(WEB_CLIENT, /bili-language/); From 5cbdc55021e9bfeaa79119a228da4017e112bcea Mon Sep 17 00:00:00 2001 From: awork Date: Sat, 10 Oct 2026 00:50:54 +0800 Subject: [PATCH 2/3] fix(web): align pinned dark --red-soft with the OS-driven palette; pin palette sync (#2564 review) Review finding: the :root[data-theme="dark"] block repeated the OS-driven dark list with --red-soft green channel drifted 73 -> 46 (rgba(248,81,46,.12) vs the #f85149-consistent rgba(248,81,73,.12)), contradicting the verbatim-carry intent. Restore 73 and add a bidirectional set-equality guard between the two lists (color-scheme aside) so future drift fails CI. --- src/web/styles.ts | 2 +- tests/dsh-settings-ui.test.ts | 25 +++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/web/styles.ts b/src/web/styles.ts index e6c616b169..7c680d408e 100644 --- a/src/web/styles.ts +++ b/src/web/styles.ts @@ -69,7 +69,7 @@ export const WEB_STYLES = String.raw` --green: #3fb950; --green-soft: rgba(63, 185, 80, 0.14); --red: #f85149; - --red-soft: rgba(248, 81, 46, 0.12); + --red-soft: rgba(248, 81, 73, 0.12); --amber: #d29922; --amber-soft: rgba(210, 153, 34, 0.14); --purple: #a371f7; diff --git a/tests/dsh-settings-ui.test.ts b/tests/dsh-settings-ui.test.ts index 2c77c2c78f..13f7b97c63 100644 --- a/tests/dsh-settings-ui.test.ts +++ b/tests/dsh-settings-ui.test.ts @@ -913,6 +913,31 @@ test("#2559: explicit host theme pin overrides the OS palette; #2560 embed frame "the OS-driven dark palette stays out of explicitly pinned documents", ); assert.ok(styles.includes(':root[data-theme="dark"] {'), "an explicit dark pin carries the full dark palette"); + { + // Review finding on #2564: the pinned list had drifted from the + // OS-driven one (--red-soft green channel 73→46) — CSS cannot share + // declarations across the media boundary, so drift stays silent. + // Pin SET-EQUALITY (color-scheme aside): both lists must carry the + // same declarations verbatim. + const grab = (open: string): string => { + const i = styles.indexOf(open); + assert.ok(i >= 0, `${open} present`); + return styles.slice(i + open.length, styles.indexOf("}", i)); + }; + const decls = (block: string): string[] => + block.split("\n") + .map((l) => l.trim().replace(/;\s*$/, "")) + .filter((l) => l !== "" && !l.startsWith("*")); + const pinned = decls(grab(':root[data-theme="dark"] {')); + const osDriven = decls(grab(":root:not([data-theme]) {")); + for (const d of pinned) { + if (d.startsWith("color-scheme")) continue; + assert.ok(osDriven.includes(d), `pinned dark declaration missing from the OS-driven list: ${d}`); + } + for (const d of osDriven) { + assert.ok(pinned.includes(d), `OS-driven dark declaration missing from the pin: ${d}`); + } + } assert.ok( styles.includes(':root[data-theme="light"] {\n color-scheme: light;\n}'), "an explicit light pin rebinds the canvas over a dark OS", From e8affd1aac0a002d668effd0599d1cde503c22d4 Mon Sep 17 00:00:00 2001 From: awork Date: Sat, 10 Oct 2026 01:11:00 +0800 Subject: [PATCH 3/3] fix(tests): CRLF-normalize styles.ts read in the #2559 CSS-pin test (#2564 review) Git-for-Windows checks .ts out with \r\n (autocrlf default; .gitattributes pins only tests/golden/** to LF), so the mid-string "\n" literal in the OS-driven-palette assertion fails on every windows-latest CI run. Verified: reproduced locally by converting src/web/styles.ts to CRLF (test red on the exact assertion), green after normalization under both CRLF and LF. --- tests/dsh-settings-ui.test.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/dsh-settings-ui.test.ts b/tests/dsh-settings-ui.test.ts index 13f7b97c63..51d0ca724a 100644 --- a/tests/dsh-settings-ui.test.ts +++ b/tests/dsh-settings-ui.test.ts @@ -907,7 +907,10 @@ test("#2559: explicit host theme pin overrides the OS palette; #2560 embed frame // pins the face via ?theme= (renderPage → ). An // explicit pin must OUTRANK the media query, so the OS-driven block // narrows to :not([data-theme]) while the pinned palette repeats it. - const styles = fs.readFileSync(new URL("../src/web/styles.ts", import.meta.url), "utf8"); + // Normalize CRLF first: Git-for-Windows checks .ts out with \r\n (autocrlf + // default; .gitattributes pins only tests/golden/** to LF), which breaks + // every mid-string "\n" literal below on Windows CI runs. + const styles = fs.readFileSync(new URL("../src/web/styles.ts", import.meta.url), "utf8").replace(/\r\n/g, "\n"); assert.ok( styles.includes("@media (prefers-color-scheme: dark) {\n :root:not([data-theme]) {"), "the OS-driven dark palette stays out of explicitly pinned documents",