@weiping/mbridge-page 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/page/view.js CHANGED
@@ -1,197 +1,584 @@
1
- // view.js is what the page shows, worked out from usage:summary without
2
- // the DOM, so a test can check it.
3
- //
4
- // It is a classic script, not a module: a magpie page runs in a sandbox
5
- // whose CSP serves the plugin's own files, and the community's usage
6
- // page does it this way too (globalThis.UsageView). A module script
7
- // would be a different thing to load, and the test below loads this file
8
- // the same way the page does.
1
+ // view.js provides the complete status UI renderer for the magpie plugin page.
2
+ // It shares the exact visual design and data representation with the mbridge /status page.
9
3
 
10
4
  (() => {
11
- const TEXT = {
12
- en: {
13
- title: "mbridge",
14
- subtitle: "what magpie's ledger recorded",
15
- today: "today",
16
- "7d": "7 days",
17
- "30d": "30 days",
18
- status: "mbridge's own status:",
19
- restart: "restart it with",
20
- mbridge: "mbridge",
21
- mbridgeNone: "mbridge has not published anything yet",
22
- mbridgeAge: "published",
23
- mbridgeLive: "sessions running now",
24
- mbridgeNoLive: "no session is going through mbridge right now",
25
- mbridgeDecisions: "recent decisions",
26
- mbridgeWindow: "the last",
27
- mbridgeTurns: "turns",
28
- mbridgeCoverage: "asked the classifier",
29
- mbridgeFailures: "failures",
30
- mbridgeAsk: "ask for fresh numbers",
31
- mbridgeAsking: "asking…",
32
- mbridgeRestart: "restart mbridge",
33
- mbridgeRestarting: "restarting…",
34
- mbridgeRestartAsked: "restart asked for",
35
- mbridgeRestartRefused: "refused",
36
- tier: "tier",
37
- advised: "advised",
38
- reason: "reason",
39
- conf: "confidence",
40
- unknown: "unknown",
41
- running: "running",
42
- notRunning: "installed, not running",
43
- notInstalled: "not installed",
44
- tools: "tools",
45
- noDecisions: "no decision yet",
46
- },
47
- zh: {
48
- title: "mbridge",
49
- subtitle: "magpie 记下的全部用量",
50
- today: "今天",
51
- "7d": "7 天",
52
- "30d": "30 天",
53
- status: "mbridge 自己的状态:",
54
- restart: "重启用",
55
- mbridge: "mbridge",
56
- mbridgeNone: "mbridge 还没有发布过任何东西",
57
- mbridgeAge: "发布于",
58
- mbridgeLive: "正在选档的会话",
59
- mbridgeNoLive: "现在没有会话在走 mbridge",
60
- mbridgeDecisions: "最近判档",
61
- mbridgeWindow: "最近",
62
- mbridgeTurns: "轮",
63
- mbridgeCoverage: "问了分类器",
64
- mbridgeFailures: "失败",
65
- mbridgeAsk: "要最新数字",
66
- mbridgeAsking: "正在要…",
67
- mbridgeRestart: "重启 mbridge",
68
- mbridgeRestarting: "正在重启…",
69
- mbridgeRestartAsked: "已发出重启指令",
70
- mbridgeRestartRefused: "被拒绝",
71
- tier: "档",
72
- advised: "建议",
73
- reason: "reason",
74
- conf: "置信度",
75
- unknown: "未知",
76
- running: "在跑",
77
- notRunning: "装了,没在跑",
78
- notInstalled: "没装",
79
- tools: "工具",
80
- noDecisions: "还没有判档",
81
- },
5
+ "use strict";
6
+
7
+ const REFRESH_MS = 5000;
8
+
9
+ const TEXT = {
10
+ en: {
11
+ title: "mbridge",
12
+ subtitle: "per-turn model routing, on this machine",
13
+ window: "window",
14
+ unknown: "unknown",
15
+ listenPending: "the listen in router.json takes effect only after a restart",
16
+ turns: "turns",
17
+ coverage: "asked the classifier",
18
+ failures: "failures",
19
+ cost: "cost",
20
+ topReason: "most common reason",
21
+ process: "process",
22
+ pid: "pid", uptime: "uptime", listen: "listen", magpie: "magpie",
23
+ service: "service", running: "running", notRunning: "installed, not running",
24
+ notInstalled: "not installed",
25
+ live: "sessions running now",
26
+ noLive: "no session is going through mbridge right now",
27
+ justWent: "the last turns that went through it",
28
+ decisions: "recent decisions",
29
+ noDecisions: "no decision yet",
30
+ classifier: "classifier",
31
+ distributions: "distributions",
32
+ arms: "two arms, and the calibration",
33
+ config: "configuration in force",
34
+ configNote: "a project-level .mbridge/router.json may override each tier's criteria",
35
+ since: "since",
36
+ tier: "tier", advised: "advised", reason: "reason", harness: "harness",
37
+ agent: "agent", source: "source", conf: "confidence", ms: "ms",
38
+ tierConf: "tier confidence", dissatisfied: "dissatisfied", compact: "compact",
39
+ classifyMs: "classifier", latency: "decision (includes classification)",
40
+ notAsked: "not asked", notMeasured: "—", failed: "failed",
41
+ askHint: "not every turn asks it: pinned agents, plan mode and compaction never do, so a coverage below 100% is normal.",
42
+ failureFix: { timeout: "raise classify_timeout_ms",
43
+ canceled: "the client gave up first: lower the timeout or use a faster classifier",
44
+ magpie: "magpie's own words; no fix is suggested" },
45
+ sampleShort: "too few samples",
46
+ feedbackOnly: "from feedback only, not gh",
47
+ unpriced: "requests magpie has no price for",
48
+ cacheWrite: "cache write (estimated)",
49
+ merged: "merged PR", manual: "manual switch", sessions: "sessions",
50
+ median: "median", p90: "p90",
51
+ restart: "restart mbridge",
52
+ restarting: "restarting…",
53
+ restartAsked: "restart asked for — the pid changes when it comes back",
54
+ restartRefused: "refused (not same-origin?)",
55
+ foot: [
56
+ "the harness is whatever the client says it is; mbridge does not check it, and an unknown one is shown as it came",
57
+ "the session list is what mbridge still remembers: it is memory, and a restart empties it",
58
+ "a project-level .mbridge/router.json may override each tier's criteria; which one a session used is not recorded",
59
+ "the merged-PR rate here comes from the sessions' own feedback, not from gh: mbridge router report runs gh",
60
+ "the tier on a card is where that turn went, not where it should have gone; the classifier's advice is shown next to it",
61
+ ],
62
+ },
63
+ zh: {
64
+ title: "鹊桥",
65
+ subtitle: "本机的逐轮选档",
66
+ window: "区间",
67
+ unknown: "未知",
68
+ listenPending: "router.json 里的 listen 要重启才生效",
69
+ turns: "轮",
70
+ coverage: "问了分类器",
71
+ failures: "失败",
72
+ cost: "成本",
73
+ topReason: "最常见的 reason",
74
+ process: "进程",
75
+ pid: "pid", uptime: "运行时长", listen: "listen", magpie: "magpie",
76
+ service: "service", running: "在跑", notRunning: "装了,没在跑",
77
+ notInstalled: "没装",
78
+ live: "正在选档的会话",
79
+ noLive: "现在没有会话在走 mbridge",
80
+ justWent: "刚刚走过的几轮",
81
+ decisions: "最近判档",
82
+ noDecisions: "还没有判档",
83
+ classifier: "分类器",
84
+ distributions: "分布",
85
+ arms: "两臂与校准",
86
+ config: "生效中的配置",
87
+ configNote: "项目级 .mbridge/router.json 可以覆盖每档的 criteria",
88
+ since: "起",
89
+ tier: "档", advised: "建议", reason: "reason", harness: "harness",
90
+ agent: "agent", source: "来源", conf: "置信度", ms: "ms",
91
+ tierConf: "档位置信度", dissatisfied: "不满意", compact: "压缩",
92
+ classifyMs: "分类耗时", latency: "判档(含分类)",
93
+ notAsked: "没问", notMeasured: "—", failed: "失败",
94
+ askHint: "不是每一轮都问:被钉死的 agent、计划模式和压缩轮次都不问,所以覆盖率低于 100% 是正常的。",
95
+ failureFix: { timeout: "调大 classify_timeout_ms",
96
+ canceled: "客户端先放弃了:调小超时,或换更快的分类器",
97
+ magpie: "这是 magpie 自己报的原文,不给建议" },
98
+ sampleShort: "样本不足",
99
+ feedbackOnly: "只来自会话自报的 feedback,不含 gh",
100
+ unpriced: "magpie 没有价的请求",
101
+ cacheWrite: "cache write(估算)",
102
+ merged: "PR 合并", manual: "手动切模型", sessions: "会话数",
103
+ median: "中位数", p90: "p90",
104
+ restart: "重启 mbridge",
105
+ restarting: "正在重启…",
106
+ restartAsked: "已发出重启指令 —— pid 变了就是回来了",
107
+ restartRefused: "被拒绝(不是同源?)",
108
+ foot: [
109
+ "harness 是客户端自报的,mbridge 不校验;没见过的值照原样显示",
110
+ "会话列表只到 mbridge 记得住的为止:它在内存里,重启即空",
111
+ "项目级 .mbridge/router.json 可以覆盖每档的 criteria;某个会话当时用的是哪一份,没有记录",
112
+ "这里的 PR 合并率来自会话自报的 feedback,不是 gh:mbridge router report 才跑 gh",
113
+ "卡片上的档是「这一轮送去了哪」,不是「该用哪」;分类器的建议就显示在旁边",
114
+ ],
115
+ },
116
+ };
117
+
118
+ const REASONS = {
119
+ "R1-fixed": ["that agent is pinned by fixed_agents", "该 agent 被 fixed_agents 钉死"],
120
+ "R2-plan-mode": ["plan mode: performance directly", "计划模式,直接 performance"],
121
+ "R9-compact": ["a compaction or summary turn", "压缩 / 摘要轮次"],
122
+ "R3-escalate": ["the last turn was judged unsatisfying: one tier up", "上一轮被判不满意 → 升一档"],
123
+ "R3-tools": ["3+ tool calls, half of them failing: one tier up", "上一轮至少 3 次工具调用、一半以上失败 → 升一档"],
124
+ "R3-review": ["the review said it was not resolved: one tier up", "复核说上一轮没解决 → 升一档"],
125
+ "R4-escalation-hold": ["holding the escalated tier", "升档后保持"],
126
+ "R6-adopt": ["took the classifier's answer", "采用分类结果"],
127
+ "R6-lower": ["lower tier (cache expired, or lowered twice)", "降档(缓存过期,或连降两次)"],
128
+ "R6-keep": ["not lowered", "不降档"],
129
+ "R7-carry": ["classification failed or was unsure: kept the last tier", "分类失败或置信度不够,沿用上一档"],
130
+ "R8-default": ["no last turn: the default tier", "没有上一轮,用 default_tier"],
131
+ "hint": ["a tier a /turn stored", "用了 /turn 存下的判档"],
132
+ "R-held": ["kept the tier the turn began with", "本轮内沿用开轮时那一档"],
133
+ "codex-title": ["Codex naming the thread, not a turn", "Codex 给线程起标题,不是真的一轮"],
134
+ };
135
+
136
+ const TIERS = ["fast", "balanced", "performance"];
137
+
138
+ let lang = (navigator.language || "en").toLowerCase().startsWith("zh") ? "zh" : "en";
139
+ const T = () => TEXT[lang];
140
+
141
+ function el(tag, attrs, kids) {
142
+ const n = document.createElement(tag);
143
+ for (const [k, v] of Object.entries(attrs || {})) {
144
+ if (v === undefined || v === null || v === false) continue;
145
+ if (k === "text") n.textContent = v;
146
+ else if (k === "class") n.className = v;
147
+ else n.setAttribute(k, v);
148
+ }
149
+ for (const kid of [].concat(kids || [])) {
150
+ if (kid === undefined || kid === null || kid === false) continue;
151
+ n.appendChild(typeof kid === "object" ? kid : document.createTextNode(String(kid)));
152
+ }
153
+ return n;
154
+ }
155
+
156
+ function kv(rows) {
157
+ const box = el("div", { class: "kv" });
158
+ for (const [k, v] of rows) {
159
+ if (v === undefined || v === null) continue;
160
+ box.appendChild(el("div", { text: k }));
161
+ box.appendChild(typeof v === "object" ? el("div", {}, v) : el("div", { text: String(v) }));
162
+ }
163
+ return box;
164
+ }
165
+
166
+ function pct(part, whole) {
167
+ if (!whole) return "0%";
168
+ const v = (100 * part) / whole;
169
+ return (Math.round(v * 10) / 10).toString() + "%";
170
+ }
171
+
172
+ function money(v) {
173
+ v = Number(v) || 0;
174
+ if (v === 0) return "$0";
175
+ if (v > 0 && v < 0.01) return "<$0.01";
176
+ if (v < 10) return "$" + v.toFixed(4).replace(/0+$/, "").replace(/\.$/, "");
177
+ if (v < 1000) return "$" + v.toFixed(2);
178
+ return "$" + v.toFixed(0);
179
+ }
180
+
181
+ function ago(iso) {
182
+ if (!iso) return "";
183
+ const t = new Date(iso);
184
+ if (isNaN(t)) return "";
185
+ const s = Math.max(0, Math.round((Date.now() - t) / 1000));
186
+ if (s < 60) return s + "s";
187
+ if (s < 3600) return Math.round(s / 60) + "m";
188
+ if (s < 86400) return Math.round(s / 3600) + "h";
189
+ return Math.round(s / 86400) + "d";
190
+ }
191
+
192
+ function clock(iso) {
193
+ if (!iso) return "";
194
+ const t = new Date(iso);
195
+ if (isNaN(t)) return "";
196
+ return t.toLocaleTimeString(lang === "zh" ? "zh-CN" : "en-GB", { hour12: false });
197
+ }
198
+
199
+ function reasonText(r) {
200
+ const both = REASONS[r];
201
+ if (!both) return r || "";
202
+ return lang === "zh" ? both[1] : both[0];
203
+ }
204
+
205
+ function tierChip(tier) {
206
+ return el("span", { class: "chip tier-" + tier, text: tier });
207
+ }
208
+
209
+ /* The turns to show: the window's last ones, plus the ones this process
210
+ decided since it started, newest first. Without the window's turns a
211
+ fresh process would show an empty page. */
212
+ function turnsOf(data) {
213
+ const out = [];
214
+ const seen = new Set();
215
+ const push = (ev) => {
216
+ if (!ev || (ev.kind !== "decide" && ev.kind !== "shadow")) return;
217
+ const id = ev.turn_id || (ev.t + "|" + ev.session + "|" + ev.reason);
218
+ if (seen.has(id)) return;
219
+ seen.add(id);
220
+ out.push(ev);
82
221
  };
222
+ for (const ev of (data.window && data.window.turns) || []) push(ev);
223
+ for (const ev of data.decisions || []) push(ev);
224
+ out.sort((a, b) => String(b.t || "").localeCompare(String(a.t || "")));
225
+ return out;
226
+ }
227
+
228
+ function scoreCell(value, asked) {
229
+ if (!asked) return el("div", { class: "off", text: T().notAsked });
230
+ if (value === undefined || value === null) return el("div", { text: T().notMeasured });
231
+ return el("div", {}, [bar(value), el("div", { class: "muted", text: value.toFixed(2) })]);
232
+ }
233
+
234
+ function bar(v) {
235
+ const b = el("div", { class: "bar" });
236
+ b.appendChild(el("i", { style: "width:" + Math.max(0, Math.min(1, v)) * 100 + "%" }));
237
+ return b;
238
+ }
239
+
240
+ function liveCard(c) {
241
+ const bits = [];
242
+ if (c.harness) bits.push(c.harness);
243
+ if (c.agent) bits.push(c.agent);
244
+ const row2 = el("div", { class: "row2", text: (c.session || "").slice(0, 8) + " · " + (bits.join(" · ") || T().unknown) });
245
+ const row3 = [];
246
+ if (c.reason) row3.push(reasonText(c.reason));
247
+ if (c.tier_confidence !== undefined && c.tier_confidence !== null) {
248
+ row3.push("conf " + c.tier_confidence.toFixed(2));
249
+ }
250
+ row3.push(ago(c.last_at));
251
+ const row4 = [];
252
+ if (c.turns) row4.push(c.turns + " " + T().turns);
253
+ row4.push(T().tools + " " + (c.agent === "gateway" ? (c.tools || 0) + "/" + (c.tool_failures || 0) : "—"));
254
+ if (c.escalated_left) row4.push("↑" + c.escalated_left);
255
+ if (c.lower_streak) row4.push("↓" + c.lower_streak);
256
+ if (c.pinned) row4.push("📌");
257
+ return el("div", { class: "card" }, [
258
+ el("div", { class: "row1" }, [
259
+ el("span", { text: (c.harness || T().unknown) + " · " + (c.agent || "") }),
260
+ el("span", {}, [c.tier, " ", tierChip(c.tier)]),
261
+ ]),
262
+ row2,
263
+ el("div", { class: "row3 muted", text: row3.join(" · ") }),
264
+ el("div", { class: "row3 muted", text: row4.join(" · ") }),
265
+ ]);
266
+ }
83
267
 
84
- const STATUS_URL = "http://127.0.0.1:3426/status";
85
-
86
- // text is the words for a language: zh for anything that starts with zh.
87
- function text(lang) {
88
- return String(lang || "").toLowerCase().startsWith("zh") ? TEXT.zh : TEXT.en;
89
- }
90
-
91
- // count is a number a person reads: 1,234 or 1.23M.
92
- function count(n) {
93
- n = Number(n) || 0;
94
- const a = Math.abs(n);
95
- if (a >= 1e9) return (n / 1e9).toFixed(2) + "B";
96
- if (a >= 1e6) return (n / 1e6).toFixed(2) + "M";
97
- if (a >= 1e3) return n.toLocaleString("en-US");
98
- return String(n);
99
- }
100
-
101
- // money is a price, never NaN, and never "$0.00" for something real.
102
- function money(n) {
103
- n = Number(n);
104
- if (!isFinite(n)) return "$0";
105
- if (n === 0) return "$0";
106
- if (n > 0 && n < 0.01) return "<$0.01";
107
- if (n < 10) return "$" + n.toFixed(4).replace(/0+$/, "").replace(/\.$/, "");
108
- if (n < 1000) return "$" + n.toFixed(2);
109
- return "$" + n.toFixed(0);
110
- }
111
-
112
- // share is a percentage, and never NaN.
113
- function pct(part, whole) {
114
- const p = Number(part) || 0;
115
- const w = Number(whole) || 0;
116
- if (w <= 0) return "0%";
117
- const v = (100 * p) / w;
118
- if (!isFinite(v)) return "0%";
119
- return (Math.round(v * 10) / 10).toString() + "%";
120
- }
121
-
122
- // mbridgeView is what the page shows of mbridge, from the snapshot
123
- // mbridge published into the plugin's options (SP14 §7).
124
- function mbridgeView(snapshot, lang) {
125
- const t = text(lang);
126
- // nothing published, or an object that is not a snapshot: an empty
127
- // options object is not a snapshot, it is no snapshot
128
- if (!snapshot || (!snapshot.seq && !snapshot.version)) {
129
- return { none: true, text: t.mbridgeNone };
268
+ function decisionTable(turns) {
269
+ const t = el("table", { class: "wide" });
270
+ t.appendChild(el("thead", {}, el("tr", {}, [
271
+ el("th", { text: "" }), el("th", { text: T().harness }), el("th", { text: T().agent }),
272
+ el("th", { text: T().tier }), el("th", { text: T().advised }), el("th", { text: T().reason }),
273
+ el("th", { text: T().source }), el("th", { class: "num", text: T().conf }),
274
+ el("th", { class: "num", text: T().latency }),
275
+ ])));
276
+ const body = el("tbody");
277
+ for (const ev of turns.slice(0, 20)) {
278
+ const differs = ev.classified_tier && ev.classified_tier !== ev.tier;
279
+ body.appendChild(el("tr", {}, [
280
+ el("td", { class: "muted", text: clock(ev.t) }),
281
+ el("td", { text: ev.harness || T().unknown }),
282
+ el("td", { text: ev.agent || "" }),
283
+ el("td", {}, tierChip(ev.tier || "?")),
284
+ el("td", { class: differs ? "chip differs" : "muted",
285
+ text: differs ? ev.classified_tier : (ev.classified_tier || T().notMeasured) }),
286
+ el("td", { class: "reason", title: reasonText(ev.reason), text: ev.reason || "" }),
287
+ el("td", { class: "muted", text: ev.classifier || ev.source || "" }),
288
+ el("td", { class: "num", text: ev.tier_confidence !== undefined && ev.tier_confidence !== null ?
289
+ ev.tier_confidence.toFixed(2) : T().notMeasured }),
290
+ el("td", { class: "num", text: ev.latency_ms ? ev.latency_ms + "ms" : T().notMeasured }),
291
+ ]));
292
+ }
293
+ t.appendChild(body);
294
+ return t;
295
+ }
296
+
297
+ function distribution(title, counts, total) {
298
+ const keys = Object.keys(counts || {}).sort((a, b) => counts[b] - counts[a]);
299
+ const box = el("div", { class: "dist" });
300
+ box.appendChild(el("h3", { text: title }));
301
+ if (!keys.length) {
302
+ box.appendChild(el("div", { class: "muted", text: "—" }));
303
+ return box;
304
+ }
305
+ for (const k of keys) {
306
+ box.appendChild(el("div", { class: "distrow" }, [
307
+ el("span", { class: "distname", text: k }),
308
+ el("span", { class: "distbar" }, bar(counts[k] / (total || 1))),
309
+ el("span", { class: "num distnum", text: counts[k] + " · " + pct(counts[k], total) }),
310
+ ]));
311
+ }
312
+ return box;
313
+ }
314
+
315
+ function calibrationTable(c) {
316
+ const t = el("table");
317
+ t.appendChild(el("thead", {}, el("tr", {}, [
318
+ el("th", { text: "score" }), el("th", { class: "num", text: "n" }),
319
+ el("th", { class: "num", text: "share" }), el("th", { class: "num", text: "under-tier" }),
320
+ ])));
321
+ const body = el("tbody");
322
+ const total = (c.bands || []).reduce((a, b) => a + b.n, 0);
323
+ for (const b of c.bands || []) {
324
+ body.appendChild(el("tr", {}, [
325
+ el("td", { text: "[" + b.lo + ", " + b.hi + ")" }),
326
+ el("td", { class: "num", text: String(b.n) }),
327
+ el("td", { class: "num", text: pct(b.n, total) }),
328
+ // an empty band is "—", never 0%: no samples is not "never under-tier"
329
+ el("td", { class: "num", text: b.n ? pct(b.under_rate * 100, 100) : T().notMeasured }),
330
+ ]));
331
+ }
332
+ t.appendChild(body);
333
+ const foot = [c.current !== undefined ? "current " + c.current : null,
334
+ c.suggested !== undefined && c.suggested !== null ? "suggested " + c.suggested : null,
335
+ c.sample_short ? T().sampleShort : null].filter(Boolean).join(" · ");
336
+ return el("div", { class: "cal" }, [t, el("div", { class: "muted", text: foot })]);
337
+ }
338
+
339
+ function render(data) {
340
+ const root = document.getElementById("root");
341
+ root.textContent = "";
342
+ const t = T();
343
+ const w = data.window || {};
344
+ const turns = turnsOf(data);
345
+ const turnsCount = Object.values(w.tiers || {}).reduce((a, b) => a + b, 0);
346
+ const cov = w.coverage || { asked: 0, total: 0 };
347
+ const reasons = w.reasons || {};
348
+ const topReason = Object.keys(reasons).sort((a, b) => reasons[b] - reasons[a])[0] || "";
349
+ const cost = (w.report && w.report.router && w.report.router.total_cost) || 0;
350
+
351
+ // the headline: mbridge's own numbers, not the process table
352
+ root.appendChild(el("header", { class: "head" }, [
353
+ el("h1", {}, [el("span", { text: "mbridge" }),
354
+ el("span", { class: "version", text: " " + (data.version || "") })]),
355
+ el("p", { class: "sub", text: t.subtitle }),
356
+ ]));
357
+
358
+ const tabs = el("div", { class: "tabs" });
359
+ for (const kind of ["1d", "7d", "30d"]) {
360
+ tabs.appendChild(el("button", { type: "button", "aria-pressed": String(w.kind === kind),
361
+ text: kind, onclick: () => { current.window = kind; load(); } }));
362
+ }
363
+ tabs.appendChild(el("span", { class: "muted", text: t.window }));
364
+
365
+ root.appendChild(el("div", { class: "pulse" }, [
366
+ el("div", { class: "stat" }, [el("b", { text: String(turnsCount) }), el("span", { text: " " + t.turns })]),
367
+ el("div", { class: "stat" }, [el("b", { text: pct(cov.asked, cov.total) }),
368
+ el("span", { text: " " + t.coverage })]),
369
+ el("div", { class: "stat" }, [el("b", { text: String((w.classify || {}).failures || 0) }),
370
+ el("span", { text: " " + t.failures })]),
371
+ el("div", { class: "stat" }, [el("b", { text: money(cost) }), el("span", { text: " " + t.cost })]),
372
+ topReason ? el("div", { class: "stat" }, [el("b", { text: topReason }),
373
+ el("span", { text: " " + t.topReason })]) : null,
374
+ el("div", { class: "tabs" }, tabs),
375
+ ]));
376
+
377
+ if (data.listen_pending) {
378
+ root.appendChild(el("div", { class: "banner", text: t.listenPending || "the listen in router.json takes effect only after a restart" }));
379
+ }
380
+ if (data.config_error) {
381
+ root.appendChild(el("div", { class: "banner bad", text: "router.json: " + data.config_error }));
382
+ }
383
+
384
+ // the process, one line
385
+ const svc = data.service || {};
386
+ root.appendChild(el("div", { class: "procline" }, [
387
+ el("span", { text: "pid " + (data.pid || "") }),
388
+ el("span", { text: "↑ " + Math.round((data.uptime_s || 0) / 60) + "m" }),
389
+ el("span", { text: data.listen || "" }),
390
+ el("span", { text: (data.magpie_ok ? "magpie " + (data.magpie_version || "") : "magpie —") }),
391
+ el("span", { text: "service " + (svc.installed ? (svc.running ? t.running : t.notRunning) : t.notInstalled) }),
392
+ ]));
393
+
394
+ // the sessions that are running now
395
+ root.appendChild(el("h2", { text: t.live }));
396
+ const live = data.live || [];
397
+ if (live.length) {
398
+ const cards = el("div", { class: "cards" });
399
+ for (const c of live) cards.appendChild(liveCard(c));
400
+ root.appendChild(cards);
401
+ const extra = (data.live_total || 0) - live.length;
402
+ if (extra > 0) root.appendChild(el("div", { class: "muted", text: "+" + extra }));
403
+ } else {
404
+ root.appendChild(el("div", { class: "muted", text: t.noLive }));
405
+ // nothing is running: show the turns that just went through, so the
406
+ // section is not empty
407
+ if (turns.length) {
408
+ root.appendChild(el("h3", { class: "muted", text: t.justWent }));
409
+ const cards = el("div", { class: "cards" });
410
+ for (const ev of turns.slice(0, 4)) {
411
+ cards.appendChild(el("div", { class: "card" }, [
412
+ el("div", { class: "row1" }, [
413
+ el("span", { text: (ev.harness || t.unknown) + " · " + (ev.agent || "") }),
414
+ el("span", {}, [ev.tier, " ", tierChip(ev.tier || "?")]),
415
+ ]),
416
+ el("div", { class: "row2", text: clock(ev.t) + " · " + (ev.session || "").slice(0, 8) }),
417
+ el("div", { class: "row3 muted", text: reasonText(ev.reason) }),
418
+ ]));
419
+ }
420
+ root.appendChild(cards);
421
+ }
422
+ }
423
+
424
+ // the decisions
425
+ root.appendChild(el("h2", { text: t.decisions }));
426
+ if (!turns.length) {
427
+ root.appendChild(el("div", { class: "muted", text: t.noDecisions }));
428
+ } else {
429
+ root.appendChild(decisionTable(turns));
430
+ }
431
+
432
+ // the classifier
433
+ root.appendChild(el("h2", { text: t.classifier }));
434
+ const cl = w.classify || { asked: 0, failures: 0, error_kinds: {} };
435
+ root.appendChild(kv([
436
+ [t.coverage, pct(cov.asked, cov.total) + " (" + cov.asked + "/" + cov.total + ")"],
437
+ [t.failures, cl.failures + " / " + cl.asked],
438
+ ["", el("span", { class: "muted", text: t.askHint })],
439
+ ]));
440
+ if (cl.failures) {
441
+ const ul = el("ul", { class: "fixes" });
442
+ for (const [kind, n] of Object.entries(cl.error_kinds || {})) {
443
+ ul.appendChild(el("li", { text: kind + " × " + n + " — " + ((t.failureFix || {})[kind] || "") }));
444
+ }
445
+ root.appendChild(ul);
446
+ }
447
+ if (turns.length) {
448
+ const gt = el("table", { class: "wide" });
449
+ gt.appendChild(el("thead", {}, el("tr", {}, [
450
+ el("th", { text: "" }), el("th", { text: t.harness }),
451
+ el("th", { text: t.tierConf }), el("th", { text: t.dissatisfied }), el("th", { text: t.compact }),
452
+ el("th", { class: "num", text: t.classifyMs }), el("th", { class: "num", text: t.latency }),
453
+ ])));
454
+ const body = el("tbody");
455
+ for (const ev of turns.slice(0, 10)) {
456
+ const asked = !!ev.classifier || !!ev.classify_error;
457
+ body.appendChild(el("tr", { class: asked ? "" : "off" }, [
458
+ el("td", { class: "muted", text: clock(ev.t) }),
459
+ el("td", { text: ev.harness || t.unknown }),
460
+ el("td", {}, scoreCell(ev.tier_confidence, asked)),
461
+ el("td", {}, scoreCell(ev.dissatisfied, asked)),
462
+ el("td", {}, scoreCell(ev.compact, asked)),
463
+ el("td", { class: "num", text: asked && ev.classify_ms ? ev.classify_ms + "ms" :
464
+ (ev.classify_error ? t.failed : t.notMeasured) }),
465
+ el("td", { class: "num", text: ev.latency_ms ? ev.latency_ms + "ms" : t.notMeasured }),
466
+ ]));
130
467
  }
131
- const s = snapshot;
132
- const cov = s.window && s.window.coverage ? s.window.coverage : { asked: 0, total: 0 };
133
- const tiers = (s.window && s.window.tiers) || {};
134
- const reasons = (s.window && s.window.reasons) || {};
135
- const turnCount = Object.keys(tiers).reduce((a, k) => a + tiers[k], 0);
136
- const topReason = Object.keys(reasons).sort((a, b) => reasons[b] - reasons[a])[0] || "";
137
- const live = s.live || [];
138
- // the decisions this process made are in memory (a restart empties
139
- // them): the window's turns are the fallback
140
- const decisions = (s.decisions && s.decisions.length)
141
- ? s.decisions
142
- : ((s.window && s.window.turns) || []);
143
- const at = s.at ? new Date(s.at) : null;
144
- const age = at && !isNaN(at)
145
- ? Math.max(0, Math.round((Date.now() - at.getTime()) / 1000))
146
- : null;
147
- return {
148
- none: false,
149
- version: s.version || "",
150
- pid: s.pid || 0,
151
- uptime: s.uptime_s || 0,
152
- listen: s.listen || "",
153
- service: (s.service && s.service.running) ? t.running : ((s.service && s.service.installed) ? t.notRunning : t.notInstalled),
154
- magpie: s.magpie_ok ? (s.magpie_version || "") : "—",
155
- turnCount: turnCount,
156
- coverage: cov.total ? Math.round((100 * cov.asked) / cov.total) + "%" : "—",
157
- failures: (s.window && s.window.classify && s.window.classify.failures) || 0,
158
- topReason: topReason,
159
- age: age,
160
- ageText: age === null ? "" : (age < 60 ? age + "s" : (age < 3600 ? Math.round(age / 60) + "m" : Math.round(age / 3600) + "h")),
161
- live: live.map((c) => ({
162
- session: (c.session || "").slice(0, 8),
163
- harness: c.harness || t.unknown,
164
- agent: c.agent || "",
165
- tier: c.tier || "",
166
- group: c.group || "",
167
- reason: c.reason || "",
168
- conf: c.tier_confidence,
169
- turns: c.turns || 0,
170
- tools: c.agent === "gateway" ? (c.tools || 0) + "/" + (c.tool_failures || 0) : null,
171
- last: c.last_at || "",
172
- })),
173
- decisions: decisions.slice(0, 12).map((ev) => ({
174
- time: ev.t || "",
175
- clock: ev.t ? ev.t.slice(11, 19) : "",
176
- harness: ev.harness || t.unknown,
177
- agent: ev.agent || "",
178
- tier: ev.tier || "",
179
- advised: ev.classified_tier || "",
180
- differs: !!(ev.classified_tier && ev.classified_tier !== ev.tier),
181
- reason: ev.reason || "",
182
- source: ev.classifier || ev.source || "",
183
- conf: ev.tier_confidence,
184
- ms: ev.latency_ms || 0,
185
- })),
186
- emptyLive: live.length === 0,
187
- noDecisions: decisions.length === 0,
188
- };
468
+ gt.appendChild(body);
469
+ root.appendChild(gt);
470
+ }
471
+
472
+ // the distributions
473
+ root.appendChild(el("h2", { text: t.distributions }));
474
+ const dists = el("div", { class: "dists" });
475
+ dists.appendChild(distribution("tier", w.tiers, turnsCount));
476
+ dists.appendChild(distribution("reason", w.reasons, turnsCount));
477
+ dists.appendChild(distribution("harness", w.harnesses, turnsCount));
478
+ dists.appendChild(distribution("arm", w.arms, Object.values(w.arms || {}).reduce((a, b) => a + b, 0)));
479
+ root.appendChild(dists);
480
+
481
+ // the two arms
482
+ root.appendChild(el("h2", { text: t.arms }));
483
+ const rep = w.report || {};
484
+ const rows = [];
485
+ for (const arm of ["router", "control"]) {
486
+ const a = rep[arm];
487
+ if (!a || !a.sessions) continue; // an arm with nothing in it is not drawn
488
+ rows.push([arm, String(a.sessions), money(a.cost_median || 0), money(a.cost_p90 || 0),
489
+ String(a.merged_sessions || 0), String(a.manual_switch_sessions || 0)]);
189
490
  }
491
+ if (rows.length) {
492
+ const at = el("table");
493
+ at.appendChild(el("thead", {}, el("tr", {}, [
494
+ el("th", { text: "arm" }), el("th", { class: "num", text: t.sessions }),
495
+ el("th", { class: "num", text: t.median }), el("th", { class: "num", text: t.p90 }),
496
+ el("th", { class: "num", text: t.merged }), el("th", { class: "num", text: t.manual }),
497
+ ])));
498
+ const body = el("tbody");
499
+ for (const r of rows) {
500
+ body.appendChild(el("tr", {}, r.map((cell, i) => el("td", { class: i ? "num" : "", text: cell }))));
501
+ }
502
+ at.appendChild(body);
503
+ root.appendChild(at);
504
+ } else {
505
+ root.appendChild(el("div", { class: "muted", text: "—" }));
506
+ }
507
+ const notes = [t.feedbackOnly,
508
+ t.unpriced + ": " + ((rep.router || {}).unpriced_requests || 0),
509
+ t.cacheWrite + ": " + money((rep.router || {}).cache_write_cost || 0)];
510
+ if (rep.sample_short) notes.push(t.sampleShort);
511
+ root.appendChild(el("div", { class: "muted", text: notes.join(" · ") }));
512
+ for (const c of w.calibrate || []) root.appendChild(calibrationTable(c));
513
+
514
+ // the configuration, last: it is reference, not the story
515
+ const cfg = data.config || {};
516
+ const th = cfg.thresholds || {};
517
+ const details = el("details", { class: "cfg" });
518
+ details.appendChild(el("summary", { text: t.config }));
519
+ details.appendChild(kv([
520
+ ["router_group", cfg.router_group],
521
+ ["default_tier", cfg.default_tier],
522
+ ["classifier", cfg.classifier],
523
+ ["classify_timeout_ms", String(cfg.classify_timeout_ms || "")],
524
+ ["escalate_turns", String(cfg.escalate_turns || "")],
525
+ ["cache_ttl_seconds", String(cfg.cache_ttl_seconds || "")],
526
+ ["thresholds", "tier_min " + th.tier_min + " · dissatisfied " + th.dissatisfied_min +
527
+ " · review " + th.review_min + " · compact " + th.compact_min],
528
+ ["review", (cfg.review || {}).mode + " · " + (cfg.review || {}).timeout_ms + "ms"],
529
+ ["experiment", ((cfg.experiment || {}).enabled ? "on " : "off ") +
530
+ (cfg.experiment || {}).router_percent + "% → " + (cfg.experiment || {}).control_tier],
531
+ ["fixed_agents", Object.entries(cfg.fixed_agents || {}).map(([a, tier]) => a + " → " + tier).join(", ")],
532
+ ["tiers", TIERS.map((name) => {
533
+ const tc = (cfg.tiers || {})[name] || {};
534
+ return name + " → " + (tc.group || "?") + " (" + (tc.claude_alias || "?") + ")";
535
+ }).join(" · ")],
536
+ ["", el("span", { class: "muted", text: t.configNote })],
537
+ ]));
538
+ root.appendChild(details);
539
+
540
+ // the restart button
541
+ const btn = el("button", { type: "button", class: "restart", text: t.restart });
542
+ btn.addEventListener("click", async () => {
543
+ btn.disabled = true;
544
+ btn.textContent = t.restarting;
545
+ try {
546
+ const res = await fetch("/v1/bridge/restart", { method: "POST" });
547
+ // the instruction is out, not the restart: the pid tells us when
548
+ btn.textContent = res.status === 202 ? t.restartAsked : t.restartRefused;
549
+ if (res.status !== 202) btn.disabled = false;
550
+ } catch (err) {
551
+ btn.textContent = String((err && err.message) || err);
552
+ btn.disabled = false;
553
+ }
554
+ });
555
+ root.appendChild(el("div", { class: "restartrow" }, btn));
556
+
557
+ // the honest boundaries
558
+ const foot = el("div", { class: "foot" });
559
+ foot.appendChild(el("ul", {}, t.foot.map((line) => el("li", { text: line }))));
560
+ root.appendChild(foot);
561
+ }
190
562
 
191
563
  globalThis.MbridgeView = {
192
564
  TEXT,
193
- STATUS_URL,
194
- text,
195
- mbridgeView,
565
+ REASONS,
566
+ TIERS,
567
+ el,
568
+ kv,
569
+ pct,
570
+ money,
571
+ ago,
572
+ clock,
573
+ reasonText,
574
+ tierChip,
575
+ turnsOf,
576
+ scoreCell,
577
+ bar,
578
+ liveCard,
579
+ decisionTable,
580
+ distribution,
581
+ calibrationTable,
582
+ render,
196
583
  };
197
584
  })();