Skip to content
Open
Show file tree
Hide file tree
Changes from 2 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
17 changes: 15 additions & 2 deletions src/agent/dsh-native-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -505,6 +505,7 @@ const zh: Dict = {
"upstreams_down_one": "1 个上游不可用",
"upstreams_down_many": "{n} 个上游不可用",
"upstream_retry_hint": "约 {s}s 后重试",
"upstreams_dismiss": "关闭横幅(故障集合变化时重新出现)",
"probe_error": "连接 bili 代理失败——最近一次探测报出的错误(可复制,便于反馈):",
"copy": "复制",
"copied": "已复制",
Expand Down Expand Up @@ -534,6 +535,7 @@ const en: Dict = {
"upstreams_down_one": "1 upstream unavailable",
"upstreams_down_many": "{n} upstreams unavailable",
"upstream_retry_hint": "~{s}s until retry",
"upstreams_dismiss": "Dismiss banner (reappears when the failing set changes)",
"probe_error": "Failed to reach the bili proxy — last probe error (copyable for reporting):",
"copy": "Copy",
"copied": "Copied",
Expand Down Expand Up @@ -1072,9 +1074,15 @@ export function apply(ctx: ClientContext): void {
// 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.
// #5701: the ✕ dismisses until the FAILING SET changes (host+kind+code per
// row). Count ticks and retry-ETA churn of the same set do NOT re-show it,
// so an acknowledged ongoing outage stays quiet while any new or changed
// failure surfaces again. The chrome is deliberately low-saturation and the
// text keeps inheriting the host's own color tokens.
const upstreamBanner = (): ((props?: Record<string, unknown>) => unknown) => () => {
const [origin, setOrigin] = useState<string | undefined>(readOrigin());
const [rows, setRows] = useState<UpstreamRow[]>([]);
const [dismissedSig, setDismissedSig] = useState<string | undefined>(undefined);
useEffect(() => probeOrigin((o) => setOrigin(o)), []);
useEffect(() => {
if (origin === undefined) return;
Expand All @@ -1090,11 +1098,16 @@ export function apply(ctx: ClientContext): void {
return () => { cancelled = true; clearInterval(timer); };
}, [origin]);
if (rows.length === 0) return null;
const sig = rows.map((r) => `${r.host}\u0000${r.kind}\u0000${r.code ?? ""}`).sort().join("\u0001");
if (dismissedSig === sig) 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),
{ role: "status", style: { display: "flex", flexDirection: "column", gap: 4, maxWidth: 520, padding: "10px 14px", borderRadius: 10, border: "1px solid rgba(217,63,11,0.35)", background: "rgba(217,63,11,0.08)", boxShadow: "0 2px 8px rgba(0,0,0,0.15)" } },
createElement("div", { style: { display: "flex", alignItems: "center", gap: 8 } },
createElement("div", { style: { flex: 1, fontSize: 13, fontWeight: 600 } }, header),
createElement("button", { type: "button", title: t("upstreams_dismiss"), "aria-label": t("upstreams_dismiss"), onClick: () => setDismissedSig(sig), style: { cursor: "pointer", border: "none", background: "transparent", color: "inherit", fontFamily: "inherit", fontSize: 14, lineHeight: 1, padding: 0, opacity: 0.6 } }, "✕"),
),
...rows.map((r) => {
const code = r.code !== undefined ? ` ${r.code}` : "";
const s = r.nextProbeInMs !== undefined ? Math.max(1, Math.ceil(r.nextProbeInMs / 1000)) : undefined;
Expand Down
18 changes: 16 additions & 2 deletions src/upstream-alerts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -359,7 +359,10 @@ export function getOpenUpstreamCircuits(): UpstreamCircuit[] {
// conversations point at. Merges the two existing tables into one stable
// shape: the open circuit is the authoritative "currently down" signal
// (fail-fast stops minting new alerts once open), while the alert rows carry
// the actionable hint and cover the pre-circuit window.
// the actionable hint and cover the pre-circuit window. Both sources share one
// staleness rule (#5572/#5701): anything whose last activity predates
// ALERT_STALE_MS drops out — a host that stopped being hit is not evidence of
// a CURRENT outage, however loudly it failed when it was hit.

export interface UpstreamHealthEntry {
/** Host[:port] the failing traffic targeted — raw (endpoint is loopback-gated). */
Expand Down Expand Up @@ -401,7 +404,18 @@ export function getUpstreamHealthReport(now: number = Date.now()): UpstreamHealt
};
for (const a of alerts.values()) touch(a.host).alerts.push(a);
for (const e of circuits.values()) {
if (e.state.openedAt !== null) touch(e.state.host).circuit = e.state;
if (e.state.openedAt === null) continue;
// #5701: an open circuit with no fresh failures past the SAME staleness
// window as the alert rows is not evidence of a CURRENT outage — the host
// simply stopped being hit, and the alert rows behind it already aged out.
// Left unfiltered it pinned the DSH banner forever (rows with firstSeen/
// lastSeen synthesized from openedAt/lastFailure.at). Filter the PROJECTION
// only, mirroring pruneStaleAlerts above: the state machine keeps the entry,
// so traffic resuming into it still fails fast / probes, and a fresh failure
// re-surfaces the row on the very next read.
const lastActivity = e.state.lastFailure?.at ?? e.state.openedAt;
if (lastActivity < now - ALERT_STALE_MS) continue;
touch(e.state.host).circuit = e.state;
}
const upstreams: UpstreamHealthEntry[] = [];
for (const [host, { alerts: hostAlerts, circuit }] of byHost.entries()) {
Expand Down
76 changes: 74 additions & 2 deletions tests/dsh-settings-ui.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1985,8 +1985,10 @@ test("#4237: contextTab=false hides the Context tab; absent field fails open to
clearTimeout,
});
const hidden = await mountClient({ ...baseExtra(), __BILI__: { origin: "http://127.0.0.1:8787", contextTab: false } });
// #4254: the shell.overlay availability pill is NOT user-hidable — it rides along
// even when the Context tab is hidden (it is an error surface, not a preference).
// #4254/#5701: the shell.overlay pill's REGISTRATION is NOT user-hidable — it rides
// along even when the Context tab is hidden (it is an error surface, not a
// preference). #5701 makes the rendered banner dismissible via ✕ until the failing
// set changes; the slot itself stays registered either way.
assert.deepEqual(hidden.slotsOrder, ["settings.section", "plugins.bundle.config", "shell.overlay"]);
assert.equal(hidden.optionsBySlot.size, 3);
assert.ok(!hidden.optionsBySlot.has("conversation.view"), "hidden tab registers nothing");
Expand Down Expand Up @@ -2146,3 +2148,73 @@ test("#4254: shell.overlay upstream-unavailable pill polls /__bili/upstreams, re
assert.ok(gt.includes("1 个上游不可用"), "header counts only surviving rows");
g.runCleanups();
});

test("#5701: shell.overlay upstream pill — softened chrome; ✕ dismisses until the failing set changes", 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(" ");
};
let served: unknown = [{ host: "127.0.0.1:7864", kind: "connect-refused", code: "ECONNREFUSED", count: 9, circuit: { state: "open", nextProbeInMs: 60000 } }];
const m = await 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: served }) };
throw new Error(`unexpected fetch: ${u}`);
},
setTimeout,
clearTimeout,
setInterval: fakeSetInterval,
clearInterval: fakeClearInterval,
}, "shell.overlay");
m.resetHooks();
m.component();
await tick();
const tree = m.component() as ElementNode;
assert.ok(textOf(tree).includes("127.0.0.1:7864"), "banner renders before dismissal");
// The old hard-saturation chrome is gone (#5701): softer border/background,
// larger radius and padding, a subtle shadow — text color stays inherited.
assert.ok(tree.props !== null, "banner root carries props");
const st = tree.props.style as Record<string, unknown>;
assert.equal(st.borderRadius, 10, "radius raised to 10px");
assert.equal(st.padding, "10px 14px", "padding per #5701");
assert.ok(String(st.border).includes("rgba(217,63,11,0.35)"), "border saturation lowered from 0.5");
assert.ok(String(st.background).includes("rgba(217,63,11,0.08)"), "background saturation lowered from 0.1");
assert.ok(st.boxShadow !== undefined, "subtle shadow present");
// ✕ dismisses ...
const btn = findButton(tree);
assert.ok(btn !== undefined, "the dismiss control exists");
assert.ok(btn.props !== null, "dismiss control carries props");
(btn.props.onClick as () => void)();
assert.equal(m.component(), null, "...the identical failing set renders null");
// ...and count/ETA churn of that same set never re-shows it.
served = [{ host: "127.0.0.1:7864", kind: "connect-refused", code: "ECONNREFUSED", count: 10, circuit: { state: "open", nextProbeInMs: 30000 } }];
intervals[0].fn();
await tick();
assert.equal(m.component(), null, "count/ETA churn of the dismissed set stays hidden");
// A CHANGED failing set re-surfaces the banner.
served = [
{ host: "127.0.0.1:7864", kind: "connect-refused", code: "ECONNREFUSED", count: 10, circuit: null },
{ host: "10.0.0.5:9000", kind: "connect-timeout", count: 1, circuit: null },
];
intervals[0].fn();
await tick();
const t2 = textOf(m.component());
assert.ok(t2.includes("10.0.0.5:9000") && t2.includes("2 个上游不可用"), "changed failing set re-opens the banner");
m.runCleanups();
assert.deepEqual(intervals, [], "unmount cancels the poll loop");
});
58 changes: 58 additions & 0 deletions tests/upstream-alerts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ import {
clearUpstreamAlertsForHost,
getUpstreamAlerts,
getUpstreamHealthReport,
recordUpstreamCircuitFailure,
getOpenUpstreamCircuits,
_resetUpstreamAlertsForTest,
_resetUpstreamCircuitsForTest,
type UpstreamAlert,
Expand Down Expand Up @@ -191,6 +193,62 @@ test("health report: /__bili/upstreams projection also drops stale rows (#5572 D
}
});

// #5701: the gap #5574 left behind — alerts expire after 5 min, but an OPEN
// circuit with no fresh failures behind it was merged into the report
// unconditionally, so a host that tripped its circuit and then stopped being
// hit rendered in the DSH banner forever (rows synthesized from
// openedAt/lastFailure.at). Same staleness bound as the alert rows, applied to
// the circuit's last activity; the state machine itself is untouched
// (fail-fast + half-open probes keep working), so both directions must hold:
// quiet-for-a-window drops out of the report, still-failing never does.

test("health report: a QUIET open circuit (no fresh failures past the window) drops out of the report (#5701)", () => {
_resetUpstreamAlertsForTest();
_resetUpstreamCircuitsForTest();
try {
withClock((advance) => {
const url = "http://10.0.0.5:9000/v1/chat/completions";
for (let i = 0; i < 3; i++) {
recordUpstreamCircuitFailure(url, netError("ECONNREFUSED"), false);
advance();
}
const fresh = getUpstreamHealthReport(Date.now()).upstreams;
assert.equal(fresh.length, 1, "open circuit present while fresh");
assert.equal(fresh[0].circuit?.state, "open");
for (let i = 0; i < 301; i++) advance(); // 301_000ms of silence > 5-min window
const stale = getUpstreamHealthReport(Date.now()).upstreams;
assert.equal(stale.length, 0, "quiet open circuit ages out of the banner source");
const open = getOpenUpstreamCircuits();
assert.equal(open.length, 1, "state machine kept the circuit OPEN — only the projection filtered it");
assert.equal(open[0].host, "10.0.0.5:9000");
});
} finally {
_resetUpstreamAlertsForTest();
_resetUpstreamCircuitsForTest();
}
});

test("health report: a circuit STILL failing stays in the report regardless of age (#5701)", () => {
_resetUpstreamAlertsForTest();
_resetUpstreamCircuitsForTest();
try {
withClock((advance) => {
const url = "http://10.0.0.6:9000/v1/chat/completions";
for (let i = 0; i < 3; i++) recordUpstreamCircuitFailure(url, netError("ECONNREFUSED"), false);
for (let i = 0; i < 301; i++) advance();
assert.equal(getUpstreamHealthReport(Date.now()).upstreams.length, 0, "quiet first");
recordUpstreamCircuitFailure(url, netError("ECONNREFUSED"), false); // fresh failure (half-open probe failed)
const [row] = getUpstreamHealthReport(Date.now()).upstreams;
assert.ok(row, "a fresh failure re-surfaces the row on the very next read");
assert.equal(row.circuit?.state, "open");
assert.equal(row.kind, "connect-refused");
});
} finally {
_resetUpstreamAlertsForTest();
_resetUpstreamCircuitsForTest();
}
});

test("alert table: bounded at 32 entries, evicts oldest lastSeen first", () => {
_resetUpstreamAlertsForTest();
try {
Expand Down
Loading