forked from Jason-Vaughan/TangleBrain
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
301 lines (286 loc) · 17.3 KB
/
Copy pathindex.html
File metadata and controls
301 lines (286 loc) · 17.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>TangleBrain — knob panel</title>
<link rel="icon" type="image/png" href="/logo.png">
<style>
:root {
--primary: #8BC34A; --primary-bright: #9CCC65; --primary-dark: #558B2F;
--bg: #000; --card-bg: #0D0D0D; --elevated-bg: #1A1A1A;
--text: #E8E8E8; --text-muted: #777; --danger: #EF5350; --amber: #FFA726;
--border: #222;
}
* { box-sizing: border-box; }
body {
margin: 0; background: var(--bg); color: var(--text);
font-family: -apple-system, BlinkMacSystemFont, 'SF Pro', system-ui, sans-serif;
line-height: 1.5; padding: 24px 16px 64px;
}
.wrap { max-width: 920px; margin: 0 auto; }
header { text-align: center; padding: 8px 0 20px; border-bottom: 1px solid var(--border); margin-bottom: 24px; }
header .logo { width: 72px; height: 72px; display: block; margin: 0 auto 10px; }
header h1 { margin: 0; font-size: 1.5rem; letter-spacing: .5px; }
header h1 .accent { color: var(--primary); }
header .sub { color: var(--text-muted); font-size: .8rem; margin-top: 4px; }
h2 { font-size: .95rem; text-transform: uppercase; letter-spacing: 1px; color: var(--text-muted); margin: 28px 0 10px; }
.card { background: var(--card-bg); border: 1px solid var(--border); border-radius: 10px; padding: 16px; }
table { width: 100%; border-collapse: collapse; font-size: .85rem; }
th, td { text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--border); vertical-align: top; }
th { color: var(--text-muted); font-weight: 600; text-transform: uppercase; font-size: .68rem; letter-spacing: .5px; }
td.mono, .mono { font-family: 'SF Mono', Menlo, monospace; font-size: .8rem; }
.pill { display: inline-block; padding: 2px 8px; border-radius: 999px; font-size: .7rem; border: 1px solid var(--border); margin: 1px 3px 1px 0; }
.pill.local { color: var(--primary); border-color: var(--primary-dark); }
.pill.sub { color: var(--primary-bright); }
.pill.api { color: var(--amber); }
.pill.orch { color: var(--primary); border-color: var(--primary-dark); }
.stat-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 12px; }
.stat { background: var(--elevated-bg); border-radius: 8px; padding: 12px 14px; }
.stat .label { color: var(--text-muted); font-size: .7rem; text-transform: uppercase; letter-spacing: .5px; }
.stat .value { font-size: 1.3rem; margin-top: 4px; }
.stat .value.big { color: var(--primary); }
.caveat { color: var(--amber); font-size: .78rem; margin-top: 10px; }
textarea, input[type=text] {
width: 100%; background: var(--elevated-bg); border: 1px solid var(--border); color: var(--text);
border-radius: 8px; padding: 10px; font-family: inherit; font-size: .9rem; resize: vertical;
}
textarea:focus, input:focus { outline: none; border-color: var(--primary-dark); }
.row { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; margin-top: 10px; }
label.chk { color: var(--text-muted); font-size: .82rem; display: flex; align-items: center; gap: 6px; }
button {
background: var(--card-bg); color: var(--primary); border: 1px solid var(--primary-dark);
border-radius: 8px; padding: 9px 18px; font-size: .9rem; cursor: pointer; font-family: inherit;
}
button:hover { background: var(--elevated-bg); }
button:disabled { color: var(--text-muted); border-color: var(--border); cursor: default; }
pre.out { background: var(--elevated-bg); border: 1px solid var(--border); border-radius: 8px;
padding: 12px; white-space: pre-wrap; word-break: break-word; margin-top: 12px; font-size: .85rem; }
.served { color: var(--text-muted); font-size: .78rem; margin-top: 8px; }
.served b { color: var(--primary); }
.err { color: var(--danger); }
.muted { color: var(--text-muted); }
</style>
</head>
<body>
<div class="wrap">
<header>
<img class="logo" src="/logo.png" alt="TangleBrain logo">
<h1>Tangle<span class="accent">Brain</span> · knob panel</h1>
<div class="sub">roster & pricing config · local spend-avoided rollup</div>
</header>
<h2>Run a prompt</h2>
<div class="card">
<textarea id="prompt" rows="3" placeholder="Ask the router something…"></textarea>
<div class="row">
<input type="text" id="task" placeholder="task hint (optional: code, reasoning, long-context)" style="flex:1; min-width:220px;">
<label class="chk"><input type="checkbox" id="local"> force local ($0)</label>
<button id="run">Run</button>
</div>
<div id="runResult"></div>
</div>
<h2>Spend avoided <span class="muted">(local rollup)</span></h2>
<div class="card" id="statsCard"><span class="muted">loading…</span></div>
<h2>Roster</h2>
<div class="card" id="rosterCard"><span class="muted">loading…</span></div>
<h2>Pricing reference</h2>
<div class="card" id="pricingCard"><span class="muted">loading…</span></div>
</div>
<script>
const $ = (id) => document.getElementById(id);
// Full 5-char HTML escape — values are inserted into both text nodes AND attribute contexts
// (e.g. the editable pricing inputs' value="..."), so quotes MUST be escaped too.
const esc = (s) => String(s == null ? "" : s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
async function getJSON(url) {
const r = await fetch(url);
return r.json();
}
function money(n) { return "$" + (Number(n) || 0).toFixed(2); }
async function loadStats() {
try {
const d = await getJSON("/api/stats");
const s = d.summary || {};
const tiers = Object.entries(s.by_tier || {}).map(([k, v]) => `${esc(k)} ${v}`).join(", ") || "—";
// Origin split (#74): shown only once some record is actually tagged — all-untagged history
// adds no signal (mirrors the CLI's format_rollup stance).
const byOrigin = s.by_origin || {};
const hasOrigin = Object.keys(byOrigin).some((k) => k !== "untagged");
const origins = Object.entries(byOrigin).map(([k, v]) => `${esc(k)} ${v}`).join(", ");
let html = `<div class="stat-grid">
<div class="stat"><div class="label">Tasks routed</div><div class="value">${s.tasks || 0}</div></div>
<div class="stat"><div class="label">Spend avoided</div><div class="value big">${money(s.spend_avoided_usd)}</div></div>
<div class="stat"><div class="label">By tier</div><div class="value mono" style="font-size:.95rem">${tiers}</div></div>
${hasOrigin ? `<div class="stat"><div class="label">By origin</div><div class="value mono" style="font-size:.95rem">${origins}</div></div>` : ""}
<div class="stat"><div class="label">Est. tokens (in / out)</div><div class="value mono" style="font-size:.95rem">${(s.in_tokens_est||0).toLocaleString()} / ${(s.out_tokens_est||0).toLocaleString()}</div></div>
</div>`;
if (d.is_placeholder) html += `<div class="caveat">⚠ pricing: PLACEHOLDER — figures illustrative until the anchor is ratified.</div>`;
const dg = s.delegates || {};
if (dg.count) {
const backends = Object.entries(dg.by_backend || {}).map(([k, v]) => `${esc(k)} ${v.count || 0}`).join(", ") || "—";
// Parent-task tree: how many top-level tasks the sub-calls link back to. Mirrors the CLI's
// "Linked to: N parent task(s)" line; sub-calls run outside a propagated task are "unlinked".
const byParent = dg.by_parent || {};
const linked = Object.keys(byParent).filter((k) => k !== "unlinked").length;
const unlinked = (byParent.unlinked || {}).count || 0;
let tree = linked ? `${linked} parent task(s)` : `${unlinked} unlinked`;
if (linked && unlinked) tree += `, ${unlinked} unlinked`;
html += `<h3 style="margin:1rem 0 .4rem">Delegated sub-tasks <span class="muted">(offloaded by orchestrators)</span></h3>
<div class="stat-grid">
<div class="stat"><div class="label">Sub-tasks</div><div class="value">${dg.count}</div></div>
<div class="stat"><div class="label">By backend</div><div class="value mono" style="font-size:.95rem">${backends}</div></div>
<div class="stat"><div class="label">Linked to</div><div class="value mono" style="font-size:.95rem">${esc(tree)}</div></div>
<div class="stat"><div class="label">Est. tokens (in / out)</div><div class="value mono" style="font-size:.95rem">${(dg.in_tokens_est||0).toLocaleString()} / ${(dg.out_tokens_est||0).toLocaleString()}</div></div>
<div class="stat"><div class="label">Cloud-equiv</div><div class="value mono" style="font-size:.95rem">${money(dg.cloud_equiv_usd)}</div></div>
</div>
<div class="caveat">Informational — delegate spend is already credited within its parent task's “spend avoided”.</div>`;
}
$("statsCard").innerHTML = html;
} catch (e) { $("statsCard").innerHTML = `<span class="err">failed to load stats</span>`; }
}
async function loadRoster() {
try {
const [d, settings] = await Promise.all([
getJSON("/api/roster"),
getJSON("/api/settings").catch(() => ({})),
]);
const billingOn = !!settings.api_billing_enabled;
const hasApi = (d.entries || []).some(e => e.tier === "api");
// Surface the paid-API billing gate so an operator never misreads a paid entry's own
// enabled flag as "live" — paid routing needs the global gate on too (issue #2).
const banner = hasApi
? (billingOn
? `<div class="caveat">Paid-API billing: <b>ON</b> — enabled <code>tier: api</code> entries are routable as the last resort. Real spend possible.</div>`
: `<div class="muted" style="margin-bottom:10px">Paid-API billing: <b>OFF</b> — every <code>tier: api</code> entry is inert regardless of its own <code>enabled</code> flag.</div>`)
: "";
const rows = (d.entries || []).map(e => {
const inv = e.invoke || {};
const ref = inv.key_ref ? `<div class="muted mono" style="font-size:.72rem">key: ${esc(inv.key_ref)}</div>` : "";
const enabled = e.enabled !== false; // view_roster always sends a bool; default on
const orch = !!e.can_orchestrate;
const goodat = (e.good_at || []).join(", ");
const budget = e.budget_usd_month != null ? e.budget_usd_month : "";
// Editable scalar fields only (enabled/can_orchestrate/good_at/budget_usd_month). Originals
// are stashed on the cell so saves send ONLY changed fields — no noisy default-value inserts.
return `<tr>
<td class="mono">${esc(e.id)}</td>
<td><span class="pill ${esc(e.tier)}">${esc(e.tier)}</span><div class="muted" style="font-size:.72rem">${esc(e.cost||"")}</div></td>
<td class="mono">${esc(inv.kind)}${inv.model ? " · " + esc(inv.model) : ""}${ref}</td>
<td class="cfg" data-id="${esc(e.id)}" data-enabled="${enabled}" data-orch="${orch}" data-budget="${esc(budget)}" data-goodat="${esc(goodat)}">
<label class="chk"><input type="checkbox" class="f-enabled" ${enabled ? "checked" : ""}> enabled</label>
<label class="chk"><input type="checkbox" class="f-orch" ${orch ? "checked" : ""}> orchestrator</label>
<div class="muted" style="font-size:.74rem;margin-top:4px">good at <input class="f-goodat" value="${esc(goodat)}" style="width:200px"></div>
<div class="muted" style="font-size:.74rem">budget $/mo <input class="f-budget" value="${esc(budget)}" placeholder="—" style="width:80px"></div>
<button class="rsave" style="margin-top:4px">Save</button> <span class="rmsg muted" style="font-size:.74rem"></span>
</td>
</tr>`;
}).join("");
$("rosterCard").innerHTML = banner + `<table><thead><tr><th>id</th><th>tier</th><th>invoke</th><th>config <span class="muted" style="font-weight:400">(editable)</span></th></tr></thead><tbody>${rows}</tbody></table>`;
} catch (e) { $("rosterCard").innerHTML = `<span class="err">failed to load roster</span>`; }
}
function renderPricing(p) {
const ph = p.is_placeholder ? "checked" : "";
$("pricingCard").innerHTML = `
<div class="row"><span class="muted" style="min-width:130px">reference model</span>
<input type="text" id="pRef" value="${esc(p.reference_model)}" style="flex:1; min-width:220px;"></div>
<div class="row"><span class="muted" style="min-width:130px">input $/MTok</span>
<input type="text" id="pIn" value="${esc(p.input_per_mtok)}" style="width:120px"></div>
<div class="row"><span class="muted" style="min-width:130px">output $/MTok</span>
<input type="text" id="pOut" value="${esc(p.output_per_mtok)}" style="width:120px"></div>
<div class="row"><label class="chk"><input type="checkbox" id="pPlaceholder" ${ph}> mark as placeholder (figures flagged illustrative)</label></div>
<div class="row"><button id="pSave">Save pricing</button><span id="pMsg" class="muted"></span></div>`;
$("pSave").addEventListener("click", savePricing);
}
async function loadPricing() {
try { renderPricing(await getJSON("/api/pricing")); }
catch (e) { $("pricingCard").innerHTML = `<span class="err">failed to load pricing</span>`; }
}
async function savePricing() {
if (!confirm("Overwrite config/pricing.yaml with these values? A backup is kept.")) return;
const msg = $("pMsg");
$("pSave").disabled = true; msg.textContent = "saving…"; msg.className = "muted";
const body = {
reference_model: $("pRef").value,
input_per_mtok: parseFloat($("pIn").value),
output_per_mtok: parseFloat($("pOut").value),
placeholder: $("pPlaceholder").checked,
};
try {
const r = await fetch("/api/pricing", { method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify(body) });
const d = await r.json();
if (d.ok) {
renderPricing(d.pricing);
$("pMsg").textContent = "saved ✓"; $("pMsg").className = "pill local";
loadStats(); // refresh the placeholder caveat / figures
} else {
$("pMsg").textContent = d.error || "save failed"; $("pMsg").className = "err";
}
} catch (e) {
$("pMsg").textContent = "request failed"; $("pMsg").className = "err";
} finally {
$("pSave").disabled = false;
}
}
async function saveRoster(cell, btn) {
const id = cell.getAttribute("data-id");
const msg = cell.querySelector(".rmsg");
// Current control values vs the originals stashed on the cell — send only what changed.
const enabled = cell.querySelector(".f-enabled").checked;
const orch = cell.querySelector(".f-orch").checked;
const goodat = cell.querySelector(".f-goodat").value.split(",").map(s => s.trim()).filter(Boolean);
const budgetRaw = cell.querySelector(".f-budget").value.trim();
const fields = {};
if (enabled !== (cell.getAttribute("data-enabled") === "true")) fields.enabled = enabled;
if (orch !== (cell.getAttribute("data-orch") === "true")) fields.can_orchestrate = orch;
if (goodat.join(", ") !== cell.getAttribute("data-goodat")) fields.good_at = goodat;
if (budgetRaw !== cell.getAttribute("data-budget")) fields.budget_usd_month = (budgetRaw === "" ? null : Number(budgetRaw));
if (Object.keys(fields).length === 0) { msg.textContent = "no changes"; msg.className = "rmsg muted"; return; }
if ("budget_usd_month" in fields && fields.budget_usd_month != null && !(fields.budget_usd_month > 0)) {
msg.textContent = "budget must be a positive number"; msg.className = "rmsg err"; return;
}
if (!confirm(`Overwrite config/roster.yaml — update '${id}' (${Object.keys(fields).join(", ")})? A backup is kept; commit the change in git.`)) return;
btn.disabled = true; msg.textContent = "saving…"; msg.className = "rmsg muted";
try {
const r = await fetch("/api/roster", { method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({ id, fields }) });
const d = await r.json();
if (d.ok) { loadRoster(); } // re-render from the persisted file (resets controls + originals)
else { msg.textContent = d.error || "save failed"; msg.className = "rmsg err"; btn.disabled = false; }
} catch (e) { msg.textContent = "request failed"; msg.className = "rmsg err"; btn.disabled = false; }
}
async function run() {
const prompt = $("prompt").value.trim();
const box = $("runResult");
if (!prompt) { box.innerHTML = `<div class="err" style="margin-top:10px">enter a prompt first</div>`; return; }
$("run").disabled = true; $("run").textContent = "Running…";
box.innerHTML = `<div class="muted" style="margin-top:10px">routing…</div>`;
try {
const r = await fetch("/api/run", {
method: "POST", headers: {"Content-Type": "application/json"},
body: JSON.stringify({ prompt, task: $("task").value.trim() || null, local: $("local").checked })
});
const d = await r.json();
if (d.ok) {
const s = d.served;
const served = s ? `<div class="served">served by <b>${esc(s.model)}</b> (${esc(s.tier)} · ${esc(s.path)})</div>` : "";
box.innerHTML = `<pre class="out">${esc(d.text)}</pre>${served}`;
loadStats();
} else {
box.innerHTML = `<pre class="out err">${esc(d.error)}</pre>`;
}
} catch (e) {
box.innerHTML = `<pre class="out err">request failed: ${esc(e)}</pre>`;
} finally {
$("run").disabled = false; $("run").textContent = "Run";
}
}
$("run").addEventListener("click", run);
// Delegated: the roster card is re-rendered on each refresh, so listen on the stable parent.
$("rosterCard").addEventListener("click", (ev) => {
const btn = ev.target.closest(".rsave");
if (!btn) return;
const cell = btn.closest(".cfg");
if (cell) saveRoster(cell, btn);
});
loadStats(); loadRoster(); loadPricing();
</script>
</body>
</html>