From da880f04aad0fc76abef81682c8ce247d2798749 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Wed, 7 Oct 2026 02:05:08 +0800 Subject: [PATCH] fix: dsh settings panel follows the live proxy origin instead of freezing on the boot snapshot (#2288) --- src/agent/dsh-native-client-react-shim.d.ts | 4 +- src/agent/dsh-native-client.ts | 57 +++++---- tests/dsh-settings-ui.test.ts | 125 +++++++++++++++++--- 3 files changed, 147 insertions(+), 39 deletions(-) diff --git a/src/agent/dsh-native-client-react-shim.d.ts b/src/agent/dsh-native-client-react-shim.d.ts index 91c908eaa3..520cd93129 100644 --- a/src/agent/dsh-native-client-react-shim.d.ts +++ b/src/agent/dsh-native-client-react-shim.d.ts @@ -4,8 +4,8 @@ // in the client tsup build — no react devDependency is installed. declare module "react" { export function createElement(type: string, props: Record | null, ...children: unknown[]): unknown; - // #1809: hooks used by the settings entry to upgrade in place once the - // live /bili/origin probe resolves. + // #1809/#2288: hooks used by the settings entry to track the live + // /bili/origin route in place (the boot snapshot is only a first-paint hint). export function useState(initial: T | (() => T)): [T, (value: T | ((prev: T) => T)) => void]; export function useEffect(effect: () => void | (() => void), deps?: readonly unknown[]): void; } diff --git a/src/agent/dsh-native-client.ts b/src/agent/dsh-native-client.ts index 5beb155b0e..7859024576 100644 --- a/src/agent/dsh-native-client.ts +++ b/src/agent/dsh-native-client.ts @@ -8,10 +8,16 @@ // injects globalThis.__BILI__ = {origin} into the web index at render time — // a boot-time snapshot that a page loaded before spawn-mode bootstrap (or a // desktop boot payload, captured once per app launch) never carries — and it -// serves the live origin at GET /bili/origin on the dsh webserver; this -// section polls that route while unresolved so the entry upgrades without a -// reload or app restart. Neither source known ⇒ degrade to a hint instead of -// a dead link. The same panel is mounted at two slots (#2125): settings.section +// serves the live origin at GET /bili/origin on the dsh webserver. The +// snapshot is only a FIRST-PAINT HINT (#2288): attach-mode presets publish +// the env origin at startup while the host re-binds it at runtime (dead-attach +// fallback spawn, routed-origin convergence), so freezing on whatever the page +// captured left the button pointing at a dead URL for the whole session. This +// section therefore keeps polling the live route for the whole mount (fast +// until the first resolution, slow after) and the entry follows wherever the +// proxy actually listens — no reload or app restart. Neither source known ⇒ +// degrade to a hint instead of a dead link. 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 @@ -41,12 +47,15 @@ export const inject = ["slots", "locale"]; const NS = "bili"; -// #1809/#2187: live-origin probe cadence — first attempt immediate, then a -// retry every POLL_INTERVAL_MS for POLL_MAX_ATTEMPTS total (~30s), after -// which probing CONTINUES at SLOW_POLL_INTERVAL_MS until the origin arrives -// or the page unmounts. #2187: the server side now heals a failed spawn-mode -// bootstrap in the background and a slow Windows boot can take minutes, so -// stopping at ~30s stranded the entry on "not bound" for the whole session. +// #1809/#2187/#2288: live-origin probe cadence — first attempt immediate, +// then a retry every POLL_INTERVAL_MS for POLL_MAX_ATTEMPTS total (~30s), +// after which probing CONTINUES at SLOW_POLL_INTERVAL_MS until the page +// unmounts. #2187: the server side now heals a failed spawn-mode bootstrap +// in the background and a slow Windows boot can take minutes, so stopping at +// ~30s stranded the entry on "not bound" for the whole session. #2288: the +// slow phase also runs AFTER the first resolution — the host re-binds the +// origin mid-session (runtime re-spawn, routed-origin convergence), so the +// entry keeps following the live route instead of freezing on the first value. const ORIGIN_PATH = "/bili/origin"; const POLL_INTERVAL_MS = 3000; const POLL_MAX_ATTEMPTS = 10; @@ -79,33 +88,36 @@ function openExternal(url: string): void { if (typeof w.open === "function") w.open(url, "_blank", "noopener,noreferrer"); } -/** #1809/#2187: poll the host's live origin route until one arrives; returns - * the cancel used as the effect cleanup (no fetch ⇒ no-op, older hosts - * without the route simply stay degraded). */ +/** #1809/#2187/#2288: follow the host's live origin route for the lifetime + * 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 { if (typeof fetch !== "function") return () => {}; let cancelled = false; + let settled = false; let timer: ReturnType | undefined; let attempts = 0; const poll = async (): Promise => { - let resolved = false; try { const res = await fetch(ORIGIN_PATH); if (res.ok) { const data = (await res.json()) as { origin?: unknown }; if (typeof data.origin === "string" && data.origin.length > 0 && !cancelled) { onOrigin(data.origin); - resolved = true; + settled = true; } } } catch { // host without the route (older builds) or transient error: retry below } - if (resolved) return; + if (cancelled) return; attempts += 1; - // #2187: fast phase for the first POLL_MAX_ATTEMPTS, then an endless - // slow phase — the origin can land at any time (background heal). - const delay = attempts < POLL_MAX_ATTEMPTS ? POLL_INTERVAL_MS : SLOW_POLL_INTERVAL_MS; + // #2187/#2288: fast phase until the first resolution, then an endless + // slow phase — the origin can land (background heal) or move + // (runtime re-bind) at any time. + const delay = !settled && attempts < POLL_MAX_ATTEMPTS ? POLL_INTERVAL_MS : SLOW_POLL_INTERVAL_MS; if (!cancelled) timer = setTimeout(() => void poll(), delay); }; void poll(); @@ -125,10 +137,9 @@ export function apply(ctx: ClientContext): void { const t = ctx.locale.bind(NS); const panel = (titled: boolean): ((props: Record) => unknown) => () => { const [origin, setOrigin] = useState(readOrigin()); - useEffect(() => { - if (origin !== undefined) return; - return probeOrigin(setOrigin); - }, [origin]); + // #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), []); return createElement( "div", { style: { display: "flex", flexDirection: "column", gap: 12, padding: "20px 8px" } }, diff --git a/tests/dsh-settings-ui.test.ts b/tests/dsh-settings-ui.test.ts index 815015e2bd..0433fba687 100644 --- a/tests/dsh-settings-ui.test.ts +++ b/tests/dsh-settings-ui.test.ts @@ -289,14 +289,18 @@ test("#1590/#2125: client bundle registers the settings.section entry bili AND t const calls: ElementNode[] = []; // Minimal hook emulation (#1809): per-mount state persisting across - // component() re-renders; effects run synchronously, cleanups collected. + // component() re-renders; effects follow React semantics (#2288) — run on + // mount, re-run only when their deps change (prior cleanup first). The old + // run-on-every-render stub masked the removed snapshot guard by silently + // starting duplicate probes on each re-render. + type EffectSlot = { deps: readonly unknown[] | undefined; cleanup: (() => void) | undefined }; let hookStates: unknown[] = []; let hookIndex = 0; - const cleanups: Array<() => void> = []; + let effectSlots: EffectSlot[] = []; const resetHooks = (): void => { hookStates = []; hookIndex = 0; - cleanups.length = 0; + effectSlots = []; }; const reactStub = { createElement: (type: string, props: Record | null, ...children: unknown[]): ElementNode => { @@ -309,10 +313,16 @@ test("#1590/#2125: client bundle registers the settings.section entry bili AND t if (!(i in hookStates)) hookStates[i] = typeof init === "function" ? (init as () => unknown)() : init; return [hookStates[i], (v: unknown) => { hookStates[i] = v; }]; }, - useEffect: (fn: () => unknown | (() => void)): void => { - hookIndex++; + useEffect: (fn: () => unknown | (() => void), deps?: readonly unknown[]): void => { + const i = hookIndex++; + const prev = effectSlots[i]; + const prevDeps = prev?.deps; + const unchanged = prevDeps !== undefined && deps !== undefined && + deps.length === prevDeps.length && deps.every((d, j) => Object.is(d, prevDeps[j])); + if (unchanged) return; + prev?.cleanup?.(); const r = fn(); - if (typeof r === "function") cleanups.push(r as () => void); + effectSlots[i] = { deps, cleanup: typeof r === "function" ? (r as () => void) : undefined }; }, }; const requireStub = (spec: string): unknown => { @@ -427,7 +437,7 @@ test("#1590/#2125: client bundle registers the settings.section entry bili AND t assert.ok(degBundleTexts.some((t) => t.includes("/acp")), "the bundle degraded hint points at /acp"); }); -test("#1809/#2125: client polls /bili/origin while unresolved — upgrades on success, stays degraded and cancels when absent (both slots); #2187 keeps probing in a slow phase past the fast attempts", async () => { +test("#1809/#2125/#2187: client polls /bili/origin while unresolved — upgrades on success, stays degraded and cancels when absent (both slots); slow phase continues past the fast attempts; #2288 corrects a stale boot snapshot and follows mid-session re-binds", async () => { const { build } = await import("esbuild"); const configs = ((await import("../tsup.config.ts")).default) as unknown as Array<{ entry: Record; @@ -462,9 +472,10 @@ test("#1809/#2125: client polls /bili/origin while unresolved — upgrades on su vm.runInContext(code, sandbox, { filename: "dsh-native-client.bundle.js" }); assert.equal(registrations.length, 1); const calls: ElementNode[] = []; + type EffectSlot = { deps: readonly unknown[] | undefined; cleanup: (() => void) | undefined }; let hookStates: unknown[] = []; let hookIndex = 0; - const cleanups: Array<() => void> = []; + let effectSlots: EffectSlot[] = []; const reactStub = { createElement: (type: string, props: Record | null, ...children: unknown[]): ElementNode => { const el = { type, props, children }; @@ -476,10 +487,17 @@ test("#1809/#2125: client polls /bili/origin while unresolved — upgrades on su if (!(i in hookStates)) hookStates[i] = typeof init === "function" ? (init as () => unknown)() : init; return [hookStates[i], (v: unknown) => { hookStates[i] = v; }]; }, - useEffect: (fn: () => unknown | (() => void)): void => { - hookIndex++; + // React semantics (#2288): run on mount, re-run only on dep change. + useEffect: (fn: () => unknown | (() => void), deps?: readonly unknown[]): void => { + const i = hookIndex++; + const prev = effectSlots[i]; + const prevDeps = prev?.deps; + const unchanged = prevDeps !== undefined && deps !== undefined && + deps.length === prevDeps.length && deps.every((d, j) => Object.is(d, prevDeps[j])); + if (unchanged) return; + prev?.cleanup?.(); const r = fn(); - if (typeof r === "function") cleanups.push(r as () => void); + effectSlots[i] = { deps, cleanup: typeof r === "function" ? (r as () => void) : undefined }; }, }; const requireStub = (spec: string): unknown => { @@ -516,10 +534,11 @@ test("#1809/#2125: client polls /bili/origin while unresolved — upgrades on su resetHooks: () => { hookStates = []; hookIndex = 0; - cleanups.length = 0; + effectSlots = []; }, runCleanups: () => { - for (const c of cleanups.splice(0)) c(); + // Positions held by non-effect hooks (useState) stay as holes. + for (const slot of effectSlots.splice(0)) slot?.cleanup?.(); }, }; }; @@ -547,7 +566,85 @@ test("#1809/#2125: client polls /bili/origin while unresolved — upgrades on su assert.ok(button !== undefined, "resolved origin upgrades the entry without a reload"); (button.props!.onClick as () => void)(); assert.deepEqual(opened, ["http://127.0.0.1:9999/__bili/"]); - assert.deepEqual(fetched, ["/bili/origin"], "one probe suffices once the origin arrives"); + // #2288: resolution no longer STOPs the probe — exactly one fast probe + // ran so far; the slow follow-up is still pending and gets cancelled + // by runCleanups below. + assert.equal(fetched.length, 1, "resolution took exactly the initial fast probe (slow follow-up still pending)"); + m.runCleanups(); + } + + { + // #2288 regression core: a stale boot snapshot (the attach-mode env + // origin published at page render, before the host re-bound the proxy) + // must be corrected in place by the live route — the old guard froze + // it for the whole session. + const opened: string[] = []; + const m = mount({ + __BILI__: { origin: "http://127.0.0.1:8787" }, + open: (url: string) => opened.push(url), + fetch: async () => ({ ok: true, json: async () => ({ origin: "http://127.0.0.1:18798" }) }), + setTimeout, + clearTimeout, + }); + m.resetHooks(); + const first = m.component() as ElementNode; + const firstTexts: string[] = []; + collectText(first, firstTexts); + assert.ok(firstTexts.some((x) => x.includes("http://127.0.0.1:8787")), "the snapshot paints immediately (first-paint hint)"); + await tick(); + const second = m.component() as ElementNode; + const texts: string[] = []; + collectText(second, texts); + assert.ok(texts.some((x) => x.includes("http://127.0.0.1:18798")), `stale snapshot upgraded to the live origin: ${JSON.stringify(texts)}`); + assert.ok(!texts.some((x) => x.includes(":8787")), "the stale origin is gone from the label"); + const button = findButton(second); + assert.ok(button !== undefined, "the upgraded entry keeps its button"); + (button.props!.onClick as () => void)(); + assert.deepEqual(opened, ["http://127.0.0.1:18798/__bili/"]); + m.runCleanups(); + } + + { + // #2288: after the first resolution the slow phase KEEPS following the + // live route — a mid-session re-bind (runtime re-spawn, routed-origin + // convergence) moves the button without a reload. Manual clock as in + // the #2187 blocks below. + const pending: Array<{ id: number; delay: number; fn: () => void }> = []; + let nextId = 1; + let polls = 0; + const fakeSetTimeout = ((fn: () => void, delay?: number): unknown => { + const id = nextId++; + pending.push({ id, delay: delay ?? 0, fn }); + return id; + }) as unknown as typeof setTimeout; + const fakeClearTimeout = ((id: unknown): void => { + const i = pending.findIndex((p) => p.id === id); + if (i >= 0) pending.splice(i, 1); + }) as unknown as typeof clearTimeout; + const m = mount({ + fetch: async () => { + polls += 1; + return { ok: true, json: async () => ({ origin: polls < 4 ? "http://127.0.0.1:18798" : "http://127.0.0.1:18800" }) }; + }, + setTimeout: fakeSetTimeout, + clearTimeout: fakeClearTimeout, + }); + m.resetHooks(); + m.component(); + await tick(); + for (let i = 0; i < 3; i++) { + await tick(); + if (pending.length === 0) throw new Error("polling stopped after resolution — the entry would freeze on a stale origin"); + const t = pending.shift()!; + assert.equal(t.delay, 10000, "post-resolution follow-ups use the slow cadence"); + t.fn(); + } + await tick(); + const tree = m.component() as ElementNode; + const texts: string[] = []; + collectText(tree, texts); + assert.ok(texts.some((x) => x.includes("http://127.0.0.1:18800")), `mid-session re-bind follows the live origin: ${JSON.stringify(texts)}`); + assert.ok(!texts.some((x) => x.includes(":18798")), "the pre-re-bind origin is gone from the label"); m.runCleanups(); }