Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 82 additions & 5 deletions src/agent/dsh-native-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -86,6 +90,68 @@ const PAGE_KEYS: Record<PageId, string> = {
};
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<string, unknown> };
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 压缩代理",
Expand Down Expand Up @@ -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;
Expand All @@ -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
Expand Down Expand Up @@ -171,9 +245,12 @@ export function apply(ctx: ClientContext): void {
const panel = (titled: boolean): ((props: Record<string, unknown>) => unknown) => () => {
const [origin, setOrigin] = useState<string | undefined>(readOrigin());
const [page, setPage] = useState<PageId>("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",
Expand Down Expand Up @@ -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",
Expand Down
7 changes: 6 additions & 1 deletion src/server/admin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
7 changes: 5 additions & 2 deletions src/web/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
6 changes: 4 additions & 2 deletions src/web/page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,14 @@ function escapeHtml(value: string): string {
char === "&" ? "&amp;" : char === "<" ? "&lt;" : char === ">" ? "&gt;" : char === '"' ? "&quot;" : "&#39;");
}

export function renderPage(origin: string, version: string, embed = false): string {
// #2559: theme pins the face's palette explicitly for embedding hosts (?theme=
// light|dark → <html data-theme=…>); 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 `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>billion-context</title><style>${WEB_STYLES}</style></head><body${embed ? ' class="embed"' : ""}>
return `<!doctype html><html lang="zh-CN"${theme ? ` data-theme="${theme}"` : ""}><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>billion-context</title><style>${WEB_STYLES}</style></head><body${embed ? ' class="embed"' : ""}>
<header class="topbar"><div class="brand"><span class="logo">∞</span>billion-context<span class="ver">v${version}</span></div><nav class="nav"><a href="#/overview" data-nav="overview" class="active" data-i18n="nav.overview">${zh("nav.overview")}</a><a href="#/sessions" data-nav="sessions" data-i18n="nav.sessions">${zh("nav.sessions")}</a><a href="#/config" data-nav="config" data-i18n="nav.config">${zh("nav.config")}</a><a href="#/connect" data-nav="connect" data-i18n="nav.connect">${zh("nav.connect")}</a><a href="#/logs" data-nav="logs" data-i18n="nav.logs">${zh("nav.logs")}</a></nav><div class="actions"><a class="fork-link" href="https://github.com/ranxianglei/billion-context" target="_blank" rel="noopener" data-i18n="fork.label">${zh("fork.label")}</a><button id="language-toggle" class="lang-btn">English</button></div></header>
<div id="passthrough-banner" class="banner warn" hidden></div>
<div id="stale-banner" class="banner warn" hidden></div>
Expand Down
36 changes: 34 additions & 2 deletions src/web/styles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 →
<html data-theme=…>) 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;
Expand All @@ -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, 73, 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 {
Expand Down Expand Up @@ -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; }
`;
89 changes: 89 additions & 0 deletions tests/dsh-settings-ui.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -860,6 +860,95 @@ 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<string, unknown> => ({
__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 → <html data-theme=…>). An
// explicit pin must OUTRANK the media query, so the OS-driven block
// narrows to :not([data-theme]) while the pinned palette repeats it.
// 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",
);
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",
);
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)", () => {
Expand Down
15 changes: 15 additions & 0 deletions tests/web-i18n.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,21 @@ test("#2321: embed mode marks the body for chrome-less framing", () => {
assert.ok(embedded.includes('<body class="embed">'), "embed flag marks the body");
});

test("#2559: renderPage pins an explicit theme on <html> 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 <html>
// 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('<html lang="zh-CN" data-theme="dark">'), "dark pin lands on <html>");
const light = renderPage("http://127.0.0.1:8787", "0.0.0-test", false, "light");
assert.ok(light.includes('<html lang="zh-CN" data-theme="light">'), "light pin lands on <html>");
const unpinned = renderPage("http://127.0.0.1:8787", "0.0.0-test", true);
assert.ok(
unpinned.startsWith('<!doctype html><html lang="zh-CN"><head>'),
"no pin keeps the plain <html> 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/);
Expand Down
Loading