Skip to content
Closed
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
88 changes: 88 additions & 0 deletions src/agent/dsh-native-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,10 @@ const ctxStatusPathFor = (hostSessionId: string | undefined): string =>
? CTX_STATUS_PATH
: `/__bili/plugin/status?conversationId=${encodeURIComponent(hostSessionId)}&fallback=latest`;
const CTX_POLL_MS = 10000;
// #4254: frame-level upstream-unavailable pill (shell.overlay) — same slow cadence
// as the per-session Context tab. A dead circuit retries on its own ~60s probe, so
// 10s keeps the "retry in ~Ns" hint fresh and clears the banner within one tick.
const UPSTREAM_POLL_MS = 10000;

type CtxStatus = {
ok: boolean;
Expand Down Expand Up @@ -362,6 +366,10 @@ const zh: Dict = {
"ctx_waiting": "等待首个模型请求…",
"ctx_nodata": "暂无上下文数据——完成一次模型请求后自动刷新。",
"ctx_refresh": "刷新",
"upstreams_label": "bili 上游状态",
"upstreams_down_one": "1 个上游不可用",
"upstreams_down_many": "{n} 个上游不可用",
"upstream_retry_hint": "约 {s}s 后重试",
};

const en: Dict = {
Expand All @@ -382,6 +390,10 @@ const en: Dict = {
"ctx_waiting": "Waiting for the first model request…",
"ctx_nodata": "No context data yet — refreshes automatically after the first model request.",
"ctx_refresh": "Refresh",
"upstreams_label": "bili upstream status",
"upstreams_down_one": "1 upstream unavailable",
"upstreams_down_many": "{n} upstreams unavailable",
"upstream_retry_hint": "~{s}s until retry",
};

function readOrigin(): string | undefined {
Expand Down Expand Up @@ -442,6 +454,37 @@ function remoteMismatch(origin: string | undefined): boolean {
return pageHost.length > 0 && !isLoopbackHost(pageHost);
}

// #4254: one row of GET /__bili/upstreams as consumed by the shell.overlay pill.
// host already carries the port ("127.0.0.1:7864"); code is the errno token
// (ECONNREFUSED/...), count the consecutive-failure tally, nextProbeInMs only
// exists while that host's circuit is OPEN (it is the "retry in ~Ns" ETA).
type UpstreamRow = { host: string; kind: string; code?: string; count: number; nextProbeInMs?: number };

/** #4254: defensively parse the /__bili/upstreams report into render rows —
* a malformed or partial payload yields fewer rows, never a throw, so a broken
* health report can never break the DSH client. */
function parseUpstreamHealth(raw: unknown): UpstreamRow[] {
if (typeof raw !== "object" || raw === null) return [];
const list = (raw as { upstreams?: unknown }).upstreams;
if (!Array.isArray(list)) return [];
const rows: UpstreamRow[] = [];
for (const item of list) {
if (typeof item !== "object" || item === null) continue;
const o = item as Record<string, unknown>;
const host = typeof o.host === "string" && o.host.length > 0 ? o.host : undefined;
if (host === undefined) continue;
const kind = typeof o.kind === "string" && o.kind.length > 0 ? o.kind : "unknown";
const code = typeof o.code === "string" && o.code.length > 0 ? o.code : undefined;
const count = typeof o.count === "number" && Number.isFinite(o.count) ? Math.max(0, Math.round(o.count)) : 0;
const circuit = (typeof o.circuit === "object" && o.circuit !== null ? o.circuit : undefined) as { state?: unknown; nextProbeInMs?: unknown } | undefined;
const probe = circuit !== undefined && circuit.state === "open" && typeof circuit.nextProbeInMs === "number" && Number.isFinite(circuit.nextProbeInMs)
? Math.max(0, circuit.nextProbeInMs)
: undefined;
rows.push({ host, kind, code, count, ...(probe !== undefined ? { nextProbeInMs: probe } : {}) });
}
return rows;
}

// #3373: gateways that mount dsh web under a path prefix re-map every URL
// the index references, so the absolute probe path misses. Probe relative to
// the page's own base as a second form; the last form that answered wins the
Expand Down Expand Up @@ -801,6 +844,44 @@ export function apply(ctx: ClientContext): void {
),
);
};
// #4254 defect ②: frame-level upstream-unavailable pill (shell.overlay slot).
// Polls the loopback-gated GET /__bili/upstreams read surface (#4257) and
// renders one row per unreachable upstream; returns null while every upstream
// is reachable, so the banner auto-dismisses when circuits close + alerts clear.
// Purely additive UI — no request path changes. Display identity is the
// forwarded host:port (bili is a transparent pipe); provider/model reverse
// lookup stays host-side.
const upstreamBanner = (): ((props?: Record<string, unknown>) => unknown) => () => {
const [origin, setOrigin] = useState<string | undefined>(readOrigin());
const [rows, setRows] = useState<UpstreamRow[]>([]);
useEffect(() => probeOrigin((o) => setOrigin(o)), []);
useEffect(() => {
if (origin === undefined) return;
let cancelled = false;
const load = (): void => {
void fetch(`${origin}/__bili/upstreams`)
.then((res) => res.json() as Promise<unknown>)
.then((raw) => { if (!cancelled) setRows(parseUpstreamHealth(raw)); })
.catch(() => { if (!cancelled) setRows([]); });
};
load();
const timer: ReturnType<typeof setInterval> = setInterval(load, UPSTREAM_POLL_MS);
return () => { cancelled = true; clearInterval(timer); };
}, [origin]);
if (rows.length === 0) return null;
const header = rows.length === 1 ? t("upstreams_down_one") : t("upstreams_down_many").replace("{n}", String(rows.length));
return createElement(
"div",
{ role: "status", style: { display: "flex", flexDirection: "column", gap: 4, maxWidth: 520, padding: "8px 12px", borderRadius: 8, border: "1px solid rgba(217,63,11,0.5)", background: "rgba(217,63,11,0.1)" } },
createElement("div", { style: { fontSize: 13, fontWeight: 600 } }, header),
...rows.map((r) => {
const code = r.code !== undefined ? ` ${r.code}` : "";
const s = r.nextProbeInMs !== undefined ? Math.max(1, Math.ceil(r.nextProbeInMs / 1000)) : undefined;
const eta = s !== undefined ? ` · ${t("upstream_retry_hint").replace("{s}", String(s))}` : "";
return createElement("div", { key: r.host, style: { fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace", fontSize: 12, lineHeight: 1.5 } }, `${r.host} · ${r.kind}${code} ×${r.count}${eta}`);
}),
);
};
ctx.slots.inject(
"settings.section",
() => ctx.slots.register({ name: "settings.section", id: "bili", order: 100, label: () => t("nav"), locale: NS }, panel(true)),
Expand All @@ -817,4 +898,11 @@ export function apply(ctx: ClientContext): void {
"conversation.view",
() => ctx.slots.register({ name: "conversation.view", id: "bili-context", order: 30, label: () => t("tab_ctx"), locale: NS }, contextPanel()),
);
// #4254 defect ②: frame-level upstream-unavailable pill. Deferred injection
// is fail-open on hosts whose build lacks the shell.overlay slot (same
// discipline as the session Context tab above).
ctx.slots.inject(
"shell.overlay",
() => ctx.slots.register({ name: "shell.overlay", id: "bili-upstreams", order: 100, label: () => t("upstreams_label"), locale: NS }, upstreamBanner()),
);
}
99 changes: 97 additions & 2 deletions tests/dsh-settings-ui.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -509,8 +509,8 @@ test("#1590/#2125: client bundle registers the settings.section entry bili AND t

const m = await mountClient(extra);
assert.deepEqual(Array.from(m.inject), ["slots", "locale"]);
assert.deepEqual(m.slotsOrder, ["settings.section", "plugins.bundle.config", "conversation.view"]);
assert.equal(m.optionsBySlot.size, 3);
assert.deepEqual(m.slotsOrder, ["settings.section", "plugins.bundle.config", "conversation.view", "shell.overlay"]);
assert.equal(m.optionsBySlot.size, 4);
// #3862: the per-session Context tab sits right of the built-in chat (0) /
// trajectory (10) faces and any third-party context tab (dsh-context: 20).
const viewSlot = m.optionsBySlot.get("conversation.view")!;
Expand Down Expand Up @@ -1664,3 +1664,98 @@ test("#3862: conversation.view Context tab embeds the web UI session page, polls
dm.runCleanups();
}
});

test("#4254: shell.overlay upstream-unavailable pill polls /__bili/upstreams, renders per-host rows, auto-dismisses when healthy", async () => {
const ORIGIN = "http://127.0.0.1:8787";
const intervals: Array<{ id: number; delay: number; fn: () => void }> = [];
let nextId = 1;
const fakeSetInterval = ((fn: () => void, delay?: number): unknown => {
const id = nextId++;
intervals.push({ id, delay: delay ?? 0, fn });
return id;
}) as unknown as typeof setInterval;
const fakeClearInterval = ((id: unknown): void => {
const i = intervals.findIndex((p) => p.id === id);
if (i >= 0) intervals.splice(i, 1);
}) as unknown as typeof clearInterval;
const textOf = (node: unknown): string => {
const out: string[] = [];
collectText(node, out);
return out.join(" ");
};
const mountOverlay = async (upstreams: unknown): Promise<Awaited<ReturnType<typeof mountClient>>> =>
mountClient({
__BILI__: { origin: ORIGIN },
fetch: async (url: string) => {
const u = String(url);
if (u.endsWith("/bili/origin")) return { ok: true, json: async () => ({ origin: ORIGIN }) };
if (u.endsWith("/__bili/upstreams")) return { ok: true, json: async () => ({ upstreams }) };
throw new Error(`unexpected fetch: ${u}`);
},
setTimeout,
clearTimeout,
setInterval: fakeSetInterval,
clearInterval: fakeClearInterval,
}, "shell.overlay");

// Populated: one unreachable upstream with an OPEN circuit (retry ETA present).
const m = await mountOverlay([{ host: "127.0.0.1:7864", kind: "connect-refused", code: "ECONNREFUSED", count: 9, firstSeen: 0, lastSeen: 0, circuit: { state: "open", nextProbeInMs: 60000 } }]);
m.resetHooks();
m.component();
assert.equal(m.component(), null, "first paint is empty until the health report resolves");
await tick();
const txt = textOf(m.component());
assert.ok(txt.includes("127.0.0.1:7864"), "row shows the forwarded host:port");
assert.ok(txt.includes("connect-refused"), "row shows the failure kind");
assert.ok(txt.includes("ECONNREFUSED"), "row shows the errno code");
assert.ok(txt.includes("×9"), "row shows the consecutive-failure tally");
assert.ok(txt.includes("约 60s 后重试"), "open circuit surfaces the retry ETA (zh)");
assert.ok(txt.includes("1 个上游不可用"), "singular header for one upstream");
assert.equal(intervals.length, 1, "one poll loop while mounted");
assert.equal(intervals[0].delay, 10000, "poll cadence is 10s");
m.runCleanups();
assert.deepEqual(intervals, [], "unmount cancels the poll loop");

// Healthy: empty report ⇒ the banner dismisses (renders null).
const h = await mountOverlay([]);
h.resetHooks();
h.component();
await tick();
assert.equal(h.component(), null, "no unreachable upstreams ⇒ no banner");
h.runCleanups();

// Multiple: header pluralizes, one row per host, and only the OPEN-circuit
// host carries a retry ETA (an alert-only host has circuit:null).
const mm = await mountOverlay([
{ host: "127.0.0.1:7864", kind: "connect-refused", code: "ECONNREFUSED", count: 3, circuit: { state: "open", nextProbeInMs: 30000 } },
{ host: "10.0.0.5:9000", kind: "connect-timeout", count: 2, circuit: null },
]);
mm.resetHooks();
mm.component();
await tick();
const mt = textOf(mm.component());
assert.ok(mt.includes("2 个上游不可用"), "plural header for two upstreams");
assert.ok(mt.includes("127.0.0.1:7864") && mt.includes("10.0.0.5:9000"), "one row per unreachable host");
assert.ok(mt.includes("connect-timeout") && mt.includes("×2"), "alert-only host still lists kind + tally");
assert.ok(mt.includes("约 30s 后重试"), "open-circuit host surfaces its own retry ETA");
assert.ok(!mt.includes("×2 · 约"), "alert-only (circuit-null) host carries no retry ETA");
mm.runCleanups();

// Defensive parse: malformed entries degrade to fewer rows and never throw —
// only the well-formed host survives into the banner.
const g = await mountOverlay([
{ host: "192.168.1.20:8080", kind: "connect-refused", code: "ECONNREFUSED", count: 2 },
"not-an-object",
{ kind: "no-host-entry" },
{ host: "", code: 42 },
]);
g.resetHooks();
g.component();
await tick();
const gt = textOf(g.component());
assert.ok(gt.includes("192.168.1.20:8080"), "well-formed entry still renders");
assert.ok(gt.includes("×2"), "the survivor keeps its tally");
assert.ok(!gt.includes("no-host-entry") && !gt.includes("not-an-object"), "malformed entries are dropped");
assert.ok(gt.includes("1 个上游不可用"), "header counts only surviving rows");
g.runCleanups();
});
Loading