quantcheck 0.0.1__py3-none-any.whl

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.
Files changed (79) hide show
  1. quantcheck/__init__.py +3 -0
  2. quantcheck/auth/__init__.py +6 -0
  3. quantcheck/auth/base.py +74 -0
  4. quantcheck/auth/callback.py +73 -0
  5. quantcheck/auth/fake.py +40 -0
  6. quantcheck/auth/service.py +49 -0
  7. quantcheck/auth/store.py +63 -0
  8. quantcheck/auth/supabase.py +168 -0
  9. quantcheck/bench.py +38 -0
  10. quantcheck/candidates.py +138 -0
  11. quantcheck/cli.py +251 -0
  12. quantcheck/config.py +63 -0
  13. quantcheck/executors/__init__.py +0 -0
  14. quantcheck/hardware.py +52 -0
  15. quantcheck/limits.py +19 -0
  16. quantcheck/pipeline.py +172 -0
  17. quantcheck/prompt.py +67 -0
  18. quantcheck/recommend.py +131 -0
  19. quantcheck/report/__init__.py +0 -0
  20. quantcheck/report/html.py +38 -0
  21. quantcheck/report/templates/report.html.j2 +272 -0
  22. quantcheck/report/terminal.py +90 -0
  23. quantcheck/report/tokens.py +41 -0
  24. quantcheck/report/view.py +161 -0
  25. quantcheck/runners/__init__.py +3 -0
  26. quantcheck/runners/base.py +87 -0
  27. quantcheck/runners/fake.py +68 -0
  28. quantcheck/runners/llamacpp_runner.py +185 -0
  29. quantcheck/runners/mlx_runner.py +153 -0
  30. quantcheck/runners/toolparse.py +107 -0
  31. quantcheck/scoring/__init__.py +0 -0
  32. quantcheck/scoring/checks.py +342 -0
  33. quantcheck/scoring/fake_judge.py +50 -0
  34. quantcheck/scoring/judge.py +171 -0
  35. quantcheck/scoring/language.py +99 -0
  36. quantcheck/scoring/models.py +92 -0
  37. quantcheck/scoring/score.py +167 -0
  38. quantcheck/scoring/stats.py +60 -0
  39. quantcheck/settings.py +14 -0
  40. quantcheck/store.py +88 -0
  41. quantcheck/tests_io.py +169 -0
  42. quantcheck/ui/__init__.py +1 -0
  43. quantcheck/ui/app.py +534 -0
  44. quantcheck/ui/catalog.py +47 -0
  45. quantcheck/ui/chat.py +211 -0
  46. quantcheck/ui/compare.py +63 -0
  47. quantcheck/ui/downloads.py +172 -0
  48. quantcheck/ui/jobs.py +173 -0
  49. quantcheck/ui/modeldetail.py +97 -0
  50. quantcheck/ui/reviews.py +59 -0
  51. quantcheck/ui/security.py +45 -0
  52. quantcheck/ui/static/chat.js +312 -0
  53. quantcheck/ui/static/fonts/JetBrainsMono-latin-b87346.woff2 +0 -0
  54. quantcheck/ui/static/fonts/JetBrainsMono-latin-ext-9326b4.woff2 +0 -0
  55. quantcheck/ui/static/fonts/NotoSansDevanagari-devanagari-3819bb.woff2 +0 -0
  56. quantcheck/ui/static/fonts/NotoSansDevanagari-latin-ext-542103.woff2 +0 -0
  57. quantcheck/ui/static/fonts/NotoSansDevanagari-latin-f3aaed.woff2 +0 -0
  58. quantcheck/ui/static/fonts/NotoSansTamil-latin-17e6dc.woff2 +0 -0
  59. quantcheck/ui/static/fonts/NotoSansTamil-latin-ext-027c12.woff2 +0 -0
  60. quantcheck/ui/static/fonts/NotoSansTamil-tamil-a57d5e.woff2 +0 -0
  61. quantcheck/ui/static/fonts/Outfit-latin-ebadd8.woff2 +0 -0
  62. quantcheck/ui/static/fonts/Outfit-latin-ext-744997.woff2 +0 -0
  63. quantcheck/ui/static/fonts/README.md +14 -0
  64. quantcheck/ui/static/fonts.css +228 -0
  65. quantcheck/ui/static/index.html +24 -0
  66. quantcheck/ui/static/lab.css +768 -0
  67. quantcheck/ui/static/lab.js +896 -0
  68. quantcheck/ui/static/logo.svg +5 -0
  69. quantcheck/ui/static/review.js +127 -0
  70. quantcheck/ui/static/setup.js +132 -0
  71. quantcheck/ui/static/testsets.js +527 -0
  72. quantcheck/ui/summary.py +104 -0
  73. quantcheck/ui/system.py +101 -0
  74. quantcheck/ui/testsets.py +243 -0
  75. quantcheck-0.0.1.dist-info/METADATA +115 -0
  76. quantcheck-0.0.1.dist-info/RECORD +79 -0
  77. quantcheck-0.0.1.dist-info/WHEEL +4 -0
  78. quantcheck-0.0.1.dist-info/entry_points.txt +2 -0
  79. quantcheck-0.0.1.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,97 @@
1
+ """Facts for one model's page: versions on disk and what the user's own tests found.
2
+
3
+ Everything comes from the local Hugging Face cache and saved runs. Nothing is fetched.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import re
9
+ from typing import Any
10
+
11
+ from quantcheck.report.view import build_view
12
+
13
+ OVERHEAD = 1.1 # memory when running is about file size plus 10%, until a run measures it
14
+ HEADROOM_GB = 2.0 # keep this much memory free for the system
15
+
16
+
17
+ def base_id(model_id: str) -> str:
18
+ """The model without its version suffix: ``org/Qwen3-4B-4bit`` -> ``org/Qwen3-4B``."""
19
+ return re.sub(r"-GGUF$", "", re.sub(r"-(\d+bit)$", "", model_id), flags=re.IGNORECASE)
20
+
21
+
22
+ def params_label(model_id: str) -> str | None:
23
+ """Parameter count when the name says it (``Qwen3-8B`` -> ``8B``), else None."""
24
+ m = re.search(
25
+ r"(?<![\d.])(\d+(?:\.\d+)?)B(?![a-z])", model_id.rsplit("/", 1)[-1], re.IGNORECASE
26
+ )
27
+ return f"{m.group(1)}B" if m else None
28
+
29
+
30
+ def _stem(run: Any) -> str:
31
+ return str(run.config.get("tests", "")).rsplit("/", 1)[-1].removesuffix(".jsonl")
32
+
33
+
34
+ def _versions_on_disk(model_id: str, cached: list[dict[str, Any]]) -> list[dict[str, Any]]:
35
+ want = base_id(model_id).lower()
36
+ out = []
37
+ for m in cached:
38
+ if base_id(m["id"]).lower() != want:
39
+ continue
40
+ bits = re.search(r"-(\d+)bit$", m["id"])
41
+ gguf = bool(re.search(r"gguf", m["id"], re.IGNORECASE))
42
+ if not bits and not gguf:
43
+ continue
44
+ out.append({
45
+ "label": f"{bits.group(1)}bit" if bits else "GGUF",
46
+ "format": "GGUF" if gguf else "MLX",
47
+ "repo": m["id"],
48
+ "size_gb": round(m["size_mb"] / 1000, 1),
49
+ }) # fmt: skip
50
+ return sorted(out, key=lambda v: (v["format"], -v["size_gb"]))
51
+
52
+
53
+ def detail(
54
+ model_id: str, cached: list[dict[str, Any]], runs: list[Any], ram_gb: float
55
+ ) -> dict[str, Any]:
56
+ """One model: versions on disk, the latest scored run's verdict per version, and fit."""
57
+ versions = _versions_on_disk(model_id, cached)
58
+ mine = [
59
+ r
60
+ for r in runs
61
+ if base_id(str(r.config.get("model", ""))).lower() == base_id(model_id).lower()
62
+ ]
63
+ latest = next((r for r in mine if r.candidates), None) # runs arrive newest first
64
+ view = build_view(latest) if latest and latest.candidates else None
65
+ rows = {r.label: r for r in view.rows} if view and view.scored else {}
66
+ rec = view.recommendation if view and view.scored else None
67
+ proven = bool(rec and rec.status == "recommended")
68
+ for v in versions:
69
+ r = rows.get(v["label"])
70
+ peak = r.bench.peak_memory_mb if r else None
71
+ v["memory_gb"] = round(peak / 1000, 1) if peak else round(v["size_gb"] * OVERHEAD, 1)
72
+ v["memory_measured"] = bool(peak)
73
+ v["fits"] = v["memory_gb"] < ram_gb - HEADROOM_GB
74
+ v["result"] = (
75
+ {"verdict": r.verdict, "n_worse": r.n_worse, "is_reference": r.is_reference,
76
+ "recommended": bool(proven and rec and rec.recommended == r.label)}
77
+ if r else None
78
+ ) # fmt: skip
79
+ fitting = [v for v in versions if v["fits"]]
80
+ biggest = max(fitting, key=lambda v: v["size_gb"], default=None)
81
+ return {
82
+ "id": base_id(model_id),
83
+ "name": base_id(model_id).rsplit("/", 1)[-1],
84
+ "params": params_label(model_id),
85
+ "versions": versions,
86
+ "total_gb": round(sum(v["size_gb"] for v in versions), 1),
87
+ "largest_fit": biggest["label"] if biggest else None,
88
+ "free_after_gb": round(ram_gb - biggest["memory_gb"], 1) if biggest else None,
89
+ "recommended": rec.recommended if proven and rec else None,
90
+ "reference": rec.reference_label if rec else None,
91
+ "status": rec.status if rec else None,
92
+ "from_test": _stem(latest) if latest else None,
93
+ "tests": sorted({_stem(r) for r in mine}),
94
+ "run_id": latest.run_id if latest else None,
95
+ "quality_limit": view.quality_limit if view else None,
96
+ "ram_gb": ram_gb,
97
+ } # fmt: skip
@@ -0,0 +1,59 @@
1
+ """Human verdicts on changed answers, saved next to a run as ``reviews.json``.
2
+
3
+ ``results.json`` is never edited, so a run stays reproducible. Format (schema_version 1)::
4
+
5
+ {"schema_version": 1,
6
+ "reviews": {"<version>": {"<case id>": {"verdict": "...", "note": "..."}}}}
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import threading
13
+ from pathlib import Path
14
+ from typing import Literal
15
+
16
+ from pydantic import BaseModel, Field
17
+
18
+ SCHEMA_VERSION = 1
19
+ Verdict = Literal["acceptable", "problem", "unsure"]
20
+ _lock = threading.Lock()
21
+
22
+
23
+ class ReviewIn(BaseModel):
24
+ """One verdict from the screen. ``verdict`` None clears it."""
25
+
26
+ version: str = Field(min_length=1, max_length=64)
27
+ case_id: str = Field(min_length=1, max_length=200)
28
+ verdict: Verdict | None = None
29
+ note: str = Field(default="", max_length=2000)
30
+
31
+
32
+ def load(run_dir: Path) -> dict[str, dict[str, dict[str, str]]]:
33
+ """Saved reviews, or empty. A damaged file is treated as empty, never a crash."""
34
+ path = run_dir / "reviews.json"
35
+ try:
36
+ data = json.loads(path.read_text(encoding="utf-8"))
37
+ reviews = data["reviews"]
38
+ return reviews if isinstance(reviews, dict) else {}
39
+ except (OSError, ValueError, KeyError, TypeError):
40
+ return {}
41
+
42
+
43
+ def save_one(run_dir: Path, item: ReviewIn) -> dict[str, dict[str, dict[str, str]]]:
44
+ """Set or clear one verdict and write the file atomically. Returns all reviews."""
45
+ with _lock:
46
+ reviews = load(run_dir)
47
+ per_version = reviews.setdefault(item.version, {})
48
+ if item.verdict is None and not item.note:
49
+ per_version.pop(item.case_id, None)
50
+ else:
51
+ per_version[item.case_id] = {"verdict": item.verdict or "", "note": item.note}
52
+ if not per_version:
53
+ reviews.pop(item.version, None)
54
+ path = run_dir / "reviews.json"
55
+ tmp = path.with_suffix(".json.tmp")
56
+ body = {"schema_version": SCHEMA_VERSION, "reviews": reviews}
57
+ tmp.write_text(json.dumps(body, ensure_ascii=False, indent=2), encoding="utf-8")
58
+ tmp.replace(path)
59
+ return reviews
@@ -0,0 +1,45 @@
1
+ """Protect the local server from web pages the user happens to visit.
2
+
3
+ A server on localhost can be reached by any website through the user's browser. Two checks:
4
+
5
+ * the ``Host`` header must be one we expect (stops DNS-rebinding attacks);
6
+ * anything that changes state (POST, PUT, DELETE) must carry ``X-QuantCheck: 1``, a header a
7
+ foreign web page cannot add without our permission, and a matching ``Origin`` if one is sent.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from collections.abc import Iterable
13
+
14
+ from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
15
+ from starlette.requests import Request
16
+ from starlette.responses import JSONResponse, Response
17
+
18
+ SAFE_METHODS = {"GET", "HEAD", "OPTIONS"}
19
+ CSRF_HEADER = "x-quantcheck"
20
+
21
+
22
+ def allowed_hosts(port: int, extra: Iterable[str] = ()) -> set[str]:
23
+ """Host header values that are accepted."""
24
+ base = {"localhost", "127.0.0.1", "[::1]", *extra}
25
+ return {f"{h}:{port}" for h in base}
26
+
27
+
28
+ class LocalOnlyGuard(BaseHTTPMiddleware):
29
+ """Reject requests with a foreign Host, or state-changing requests that look cross-site."""
30
+
31
+ def __init__(self, app, hosts: set[str]) -> None: # noqa: ANN001
32
+ super().__init__(app)
33
+ self.hosts = hosts
34
+
35
+ async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
36
+ host = request.headers.get("host", "")
37
+ if host not in self.hosts:
38
+ return JSONResponse({"error": "unexpected Host header"}, status_code=403)
39
+ if request.method not in SAFE_METHODS:
40
+ origin = request.headers.get("origin")
41
+ if origin and origin.removeprefix("http://") not in self.hosts:
42
+ return JSONResponse({"error": "cross-site request refused"}, status_code=403)
43
+ if request.headers.get(CSRF_HEADER) != "1":
44
+ return JSONResponse({"error": "missing X-QuantCheck header"}, status_code=403)
45
+ return await call_next(request)
@@ -0,0 +1,312 @@
1
+ /* Chat side by side (design: Lab-Chat). Uses helpers from lab.js (h, api, shell, mount, svgEl, emptyCard, alertCard).
2
+ Several versions are loaded at once; one question goes to each; differences from column A are highlighted.
3
+ Nothing here is invented: speed, memory and verdicts all come from the engine or are plain text comparisons. */
4
+ "use strict";
5
+
6
+ const CHAT_COLORS = ["#374151", "#047857", "#0E7490", "#4F46E5"];
7
+ const CHAT_LETTERS = "ABCD";
8
+ const CHAT_OVERHEAD = 1.1; // memory when running ≈ file size + 10%
9
+ const CHAT_HEADROOM_GB = 2; // kept free for the system
10
+ const CHAT_MAX_COLUMNS = 4;
11
+ const CHAT_ICON = ["M21 12a8 8 0 01-11.6 7.1L4 20l1-4.6A8 8 0 1121 12z"];
12
+
13
+ const chatUi = { mode: "sizes", picks: [], diff: true, pickFor: -1, error: null,
14
+ ctxOn: true, ctxSet: "", ctxData: null, docs: [], saveTo: "", newName: "", saved: {}, saveMsg: null };
15
+
16
+ /** Cached models that can be chatted with, grouped by model, biggest version first. */
17
+ function chatCatalog(cached, ramGb) {
18
+ const base = (id) => id.replace(/-(\d+bit)$/, "").replace(/-GGUF$/i, "");
19
+ const groups = new Map();
20
+ for (const m of cached) {
21
+ const bits = (m.id.match(/-(\d+bit)$/) || [])[1];
22
+ const gguf = /gguf/i.test(m.id);
23
+ if (!bits && !gguf) continue; // embeddings, speech and other non-chat downloads
24
+ const gb = m.size_mb / 1000, key = base(m.id);
25
+ const g = groups.get(key) || { model: key.split("/").pop(), id: key, items: [] };
26
+ g.items.push({ id: m.id, label: bits ? bits.replace("bit", "-bit") : "GGUF", bits: bits ? parseInt(bits, 10) : 0, runtime: gguf ? "llamacpp" : "mlx", gb, mem: gb * CHAT_OVERHEAD, fits: gb * CHAT_OVERHEAD <= ramGb - CHAT_HEADROOM_GB });
27
+ groups.set(key, g);
28
+ }
29
+ for (const g of groups.values()) g.items.sort((a, b) => b.bits - a.bits);
30
+ return [...groups.values()].sort((a, b) => b.items.length - a.items.length || a.model.localeCompare(b.model));
31
+ }
32
+
33
+ /** Word-level diff: which words of `text` are not in the longest common run of words with `ref`. */
34
+ function chatDiff(ref, text) {
35
+ const words = (s) => s.split(/(\s+)/);
36
+ const rw = ref.split(/\s+/).filter(Boolean), tokens = words(text);
37
+ const tw = tokens.filter((t) => t.trim());
38
+ if (rw.length > 500 || tw.length > 500) return tokens.map((t) => [t, false]); // too long to compare cheaply
39
+ const dp = Array.from({ length: rw.length + 1 }, () => new Uint16Array(tw.length + 1));
40
+ for (let i = rw.length - 1; i >= 0; i--) for (let j = tw.length - 1; j >= 0; j--) dp[i][j] = rw[i] === tw[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);
41
+ const keep = new Set();
42
+ for (let i = 0, j = 0; i < rw.length && j < tw.length;) {
43
+ if (rw[i] === tw[j]) { keep.add(j); i++; j++; } else if (dp[i + 1][j] >= dp[i][j + 1]) i++; else j++;
44
+ }
45
+ let wi = -1;
46
+ return tokens.map((t) => { if (!t.trim()) return [t, false]; wi++; return [t, !keep.has(wi)]; });
47
+ }
48
+
49
+ const chatNorm = (s) => (s || "").trim().replace(/\s+/g, " ");
50
+
51
+ async function screenChat() {
52
+ stopPolling();
53
+ const body = h("div", { class: "stack" }, h("p", { class: "muted", text: "Loading…" }));
54
+ mount(shell("Chat", body, "#/chat", h("a", { class: "btn", href: "#/new", text: "Run a full test" })));
55
+ let cached, sys, st, sets;
56
+ try {
57
+ [cached, sys, st, sets] = await Promise.all([api("/api/models"), api("/api/system"), api("/api/chat"), api("/api/testsets")]);
58
+ sets = sets.filter((x) => !x.error);
59
+ } catch (e) { body.replaceChildren(alertCard("fail", "Could not open Chat", e.message, [])); return; }
60
+ const ram = sys.hardware.ram_gb, freeGb = Math.max(0, sys.memory.total_gb - sys.memory.used_gb), catalog = chatCatalog(cached, ram);
61
+ const info = new Map(catalog.flatMap((g) => g.items.map((it) => [it.id, { ...it, model: g.model }])));
62
+ const head = h("div", { class: "nt-title" }, h("h2", { class: "nt-h1", text: "Chat side by side" }),
63
+ h("p", { class: "mu nt-sub", text: "Ask the same question to several versions at once and see where the answers differ. Quick checks only; a full test is what you can trust." }));
64
+ if (info.size < 2 && st.phase === "idle") {
65
+ body.replaceChildren(head, emptyCard(CHAT_ICON, "Load two versions to chat",
66
+ `Chat needs at least two downloaded versions to put side by side.${info.size === 1 ? " You have one so far." : ""} Add another size of the same model, or a different model.`,
67
+ [h("a", { class: "btn primary", href: "#/models", text: "Go to Models" })]));
68
+ return;
69
+ }
70
+ // Start with the biggest versions that fit together in memory (at least the two smallest if nothing else does).
71
+ const fitTogether = (items) => { const ok = items.filter((i) => i.fits); const out = []; let sum = 0; for (const i of ok) { if (out.length < 3 && sum + i.mem <= Math.min(ram - CHAT_HEADROOM_GB, freeGb)) { out.push(i.id); sum += i.mem; } } return out.length >= 2 ? out : ok.slice(-2).map((i) => i.id); };
72
+ const defaultPicks = () => { const g = catalog.find((x) => x.items.filter((i) => i.fits).length >= 2) || catalog[0]; return g ? fitTogether(g.items) : []; };
73
+ if (!chatUi.picks.length || chatUi.picks.some((id) => !info.has(id))) chatUi.picks = defaultPicks();
74
+ chatUi.pickFor = -1; chatUi.error = null; chatUi.saveMsg = null;
75
+ if (chatUi.ctxSet && !sets.some((x) => x.name === chatUi.ctxSet)) { chatUi.ctxSet = ""; chatUi.ctxData = null; }
76
+ if (chatUi.ctxSet && !chatUi.ctxData) { try { chatUi.ctxData = await api(`/api/testsets/${encodeURIComponent(chatUi.ctxSet)}`); } catch (e) { chatUi.ctxSet = ""; } }
77
+
78
+ const ctxEl = h("div", { class: "ch-ctx" }), sideEl = h("aside", { class: "card ch-side" }), suggEl = h("div", { class: "ch-sugg" }), lanesEl = h("div", { class: "ch-lanes" }), pickEl = h("div", { class: "ch-pick card", hidden: true }), alertEl = h("div", {}), turnsEl = h("div", { class: "ch-turns" });
79
+ const input = h("input", { type: "text", "aria-label": "Message to every column", placeholder: "Ask every column the same question, in any language…", autocomplete: "off", onkeydown: (e) => { if (e.key === "Enter") ask(); } });
80
+ const askBtn = h("button", { type: "button", class: "ch-send", onclick: () => ask() }, "Ask all ", svgEl(["M5 12h14M13 6l6 6-6 6"], "ico"));
81
+ const toolbar = h("div", { class: "ch-bar" });
82
+ const composer = h("div", { class: "ch-composer" },
83
+ suggEl, h("div", { class: "ch-box" }, input, h("div", { class: "ch-meta" }, h("span", { class: "chip plain", text: "Temperature 0 · same seed" }), askBtn)));
84
+ body.replaceChildren(head, h("div", { class: "ch-grid" }, h("div", { class: "ch-main" }, toolbar, lanesEl, pickEl, alertEl, ctxEl, turnsEl, composer), sideEl));
85
+
86
+ const active = () => st.phase !== "idle";
87
+ const picked = () => chatUi.picks.map((id) => info.get(id));
88
+ const totalGb = () => picked().reduce((a, p) => a + p.mem, 0);
89
+ const sysBudget = ram - CHAT_HEADROOM_GB, budget = () => Math.min(sysBudget, freeGb); // total RAM, and what other apps leave free
90
+ const nextFree = () => {
91
+ const first = picked()[0]; if (!first) return null;
92
+ const pool = chatUi.mode === "sizes" ? catalog.find((g) => g.model === first.model).items : catalog.flatMap((g) => g.items);
93
+ return pool.find((it) => it.fits && !chatUi.picks.includes(it.id)) || null;
94
+ };
95
+ const colName = (c) => { const label = c.label.replace(/^(\d+)bit$/, "$1-bit"); return chatUi.mode === "models" ? `${(info.get(c.model) || {}).model || c.model.split("/").pop()} · ${label}` : label; };
96
+
97
+ function renderToolbar() {
98
+ const seg = h("div", { class: "seg", role: "group", "aria-label": "Compare" },
99
+ ...[["sizes", "Sizes of one model"], ["models", "Different models"]].map(([m, label]) =>
100
+ h("button", { type: "button", text: label, disabled: active(), "aria-pressed": String(chatUi.mode === m), onclick: () => { chatUi.mode = m; if (m === "sizes") { const f = picked()[0]; const g = catalog.find((x) => f && x.model === f.model); chatUi.picks = fitTogether((g || catalog[0]).items); } else chatUi.picks = fitTogether(catalog.map((g) => g.items.find((i) => i.fits)).filter(Boolean)); chatUi.pickFor = -1; renderAll(); } })));
101
+ const sw = h("button", { type: "button", class: "ch-sw", role: "switch", "aria-checked": String(chatUi.diff), onclick: () => { chatUi.diff = !chatUi.diff; renderAll(); } }, h("span", { class: "ch-knob" }), "Highlight differences");
102
+ toolbar.replaceChildren(...[seg, active() ? h("button", { type: "button", class: "btn", disabled: st.phase !== "ready", onclick: closeChat, text: "Close and free memory" }) : null, sw].filter(Boolean));
103
+ }
104
+
105
+ function lastSpeed(letter) {
106
+ const t = st.turns[st.turns.length - 1]; const a = t && t.answers[letter];
107
+ return a && a.tok_s ? a.tok_s : null;
108
+ }
109
+ function renderLanes() {
110
+ const loaded = active() ? st.columns : null;
111
+ const items = loaded ? loaded.map((c) => ({ letter: c.letter, name: colName(c), sub: `${c.size_gb ? `${(c.size_gb * CHAT_OVERHEAD).toFixed(1)} GB` : "—"}`, state: c.state, error: c.error })) :
112
+ picked().map((p, i) => ({ letter: CHAT_LETTERS[i], name: chatUi.mode === "sizes" ? p.label : `${p.model} · ${p.label}`, sub: `${p.mem.toFixed(1)} GB est.`, state: "idle" }));
113
+ const refSpeed = items.length ? lastSpeed("A") : null;
114
+ lanesEl.style.gridTemplateColumns = `repeat(${items.length}, minmax(0, 1fr))`;
115
+ const lanes = items.map((c, i) => {
116
+ const sp = i > 0 && refSpeed && lastSpeed(c.letter) ? `${(lastSpeed(c.letter) / refSpeed).toFixed(1)}× speed` : "";
117
+ const status = { loading: "Loading…", warming: "Warming up…", ready: "Ready", error: "Failed", waiting: "Waiting" }[c.state] || "";
118
+ return h("div", { class: `ch-lane ${chatUi.pickFor === i ? "on" : ""}` },
119
+ h("span", { class: "ch-letter", style: `background:${CHAT_COLORS[i]}`, text: c.letter }),
120
+ h("button", { type: "button", class: "ch-lname", disabled: active(), "aria-label": `Change column ${c.letter}`, onclick: () => { chatUi.pickFor = chatUi.pickFor === i ? -1 : i; renderAll(); } },
121
+ h("b", {}, c.name, active() ? null : svgEl(["M6 9l6 6 6-6"], "ico ch-chev")),
122
+ h("small", { class: "mu" }, `${i === 0 ? "Reference · " : ""}${c.sub} `, status ? h("span", { class: c.state === "error" ? "ch-bad" : "ch-good", text: status }) : null, sp ? h("span", { class: "ch-good", text: sp }) : null)),
123
+ !active() && items.length > 2 && i > 0 ? h("button", { type: "button", class: "ch-x", "aria-label": `Remove column ${c.letter}`, onclick: () => { chatUi.picks.splice(i, 1); chatUi.pickFor = -1; renderAll(); } }, svgEl(["M6 6l12 12M18 6L6 18"], "ico")) : null);
124
+ });
125
+ const add = !active() && items.length < CHAT_MAX_COLUMNS && nextFree();
126
+ lanesEl.replaceChildren(...lanes, ...(add ? [h("button", { type: "button", class: "ch-add", onclick: () => { chatUi.picks.push(nextFree().id); renderAll(); } }, svgEl(["M12 5v14M5 12h14"], "ico"), "Add")] : []));
127
+ lanesEl.classList.toggle("has-add", Boolean(add));
128
+ }
129
+
130
+ function renderPicker() {
131
+ const pf = chatUi.pickFor;
132
+ pickEl.hidden = pf < 0 || active();
133
+ if (pickEl.hidden) { pickEl.replaceChildren(); return; }
134
+ const first = picked()[0];
135
+ const groups = catalog.filter((g) => chatUi.mode === "models" || (first && g.model === first.model));
136
+ pickEl.replaceChildren(
137
+ h("div", { class: "ch-pick-h" }, h("b", { text: `Choose column ${CHAT_LETTERS[pf]}${pf === 0 ? " (reference)" : ""}` }), h("span", { class: "mu", text: "Downloaded on this Mac" }),
138
+ h("button", { type: "button", class: "ch-x", "aria-label": "Close", onclick: () => { chatUi.pickFor = -1; renderAll(); } }, svgEl(["M6 6l12 12M18 6L6 18"], "ico"))),
139
+ ...groups.map((g) => h("div", { class: "ch-grp" }, h("span", { class: "lbl", text: g.model }),
140
+ h("div", { class: "ch-opts" }, g.items.map((it) => {
141
+ const used = chatUi.picks.includes(it.id);
142
+ return h("button", { type: "button", class: `ch-opt ${used ? "used" : ""}`, disabled: !it.fits, onclick: () => { chatUi.picks[pf] = it.id; chatUi.pickFor = -1; renderAll(); } },
143
+ h("span", { class: "ch-opt-t" }, h("b", { text: it.label }), used ? h("small", { text: "In use" }) : null),
144
+ h("span", { class: "mono mu", text: `${it.mem.toFixed(1)} GB RAM` }),
145
+ h("span", { class: it.fits ? "ch-good" : "ch-bad", text: it.fits ? "Fits" : `Too big for ${ram} GB` }));
146
+ })))));
147
+ }
148
+
149
+ function renderAlert() {
150
+ const nodes = [];
151
+ if (chatUi.error) nodes.push(alertCard("fail", "Could not do that", chatUi.error, []));
152
+ if (!active()) {
153
+ const t = totalGb();
154
+ const b = budget();
155
+ if (picked().length >= 2 && t > b) nodes.push(alertCard("fail", "These won't fit together", freeGb < sysBudget
156
+ ? `Together they need about ${t.toFixed(1)} GB, but only ${freeGb.toFixed(1)} GB is free right now because other apps are using memory. Close some apps, remove a column, or pick smaller versions.`
157
+ : `Together they need about ${t.toFixed(1)} GB and this Mac has ${sysBudget.toFixed(0)} GB to give (${ram} GB minus ${CHAT_HEADROOM_GB} GB for the system). Remove a column or pick smaller versions.`, []));
158
+ else nodes.push(h("div", { class: "ch-load card" }, h("div", { class: "ch-mem" }, h("span", { class: "lbl", text: "Memory for these columns" }), h("b", { class: "mono", text: `${t.toFixed(1)} GB` }), h("small", { class: "mu", text: `of ${b.toFixed(1)} GB free right now · loaded together, answers come in turn` })),
159
+ h("button", { type: "button", class: "btn primary", disabled: picked().length < 1, onclick: loadAll, text: `Load ${picked().length} version${picked().length === 1 ? "" : "s"}` })));
160
+ } else {
161
+ const bad = st.columns.filter((c) => c.state === "error");
162
+ for (const c of bad) nodes.push(alertCard("fail", `Column ${c.letter} could not load`, c.error || "Unknown error. The other columns still work.", []));
163
+ if (st.phase === "loading") nodes.push(alertCard("warn", "Loading versions", "Loading one after another. Each model also answers one test token first so your first question is quick. You can ask when they are all ready.", []));
164
+ }
165
+ alertEl.replaceChildren(...nodes);
166
+ }
167
+
168
+ function answerCard(turn, col, i) {
169
+ const a = turn.answers[col.letter], refCol = st.columns[0], ref = turn.answers[refCol.letter];
170
+ let verdict, tone, mark;
171
+ if (!a) { verdict = col.state === "error" ? "Did not load" : "No answer"; tone = "fail"; mark = "✕"; }
172
+ else if (a.state === "error") { verdict = `Error: ${a.error}`; tone = "fail"; mark = "✕"; }
173
+ else if (a.state === "waiting") { verdict = "Waiting for its turn"; tone = "plain"; mark = "…"; }
174
+ else if (a.state === "answering") { verdict = "Answering…"; tone = "plain"; mark = "…"; }
175
+ else if (i === 0) { verdict = "Reference"; tone = "plain"; mark = "★"; }
176
+ else if (!ref || ref.state !== "done") { verdict = "No reference answer to compare with"; tone = "plain"; mark = "–"; }
177
+ else if (chatNorm(a.text) === chatNorm(ref.text)) { verdict = "Same answer as A"; tone = "ok"; mark = "✓"; }
178
+ else { verdict = "Different from A"; tone = "warn"; mark = "!"; }
179
+ const done = a && a.state === "done", refDone = ref && ref.state === "done";
180
+ const segs = a && a.text ? (chatUi.diff && i > 0 && done && refDone && tone === "warn" ? chatDiff(ref.text, a.text) : [[a.text, false]]) : [];
181
+ const stats = a && a.tok_s ? `${a.tok_s} t/s${a.seconds ? ` · ${a.seconds}s` : ""}` : a && a.seconds ? `${a.seconds}s` : "";
182
+ const code = /^\s*[{[]/.test((a && a.text) || "") || /\w+\(\{/.test((a && a.text) || "");
183
+ return h("div", { class: "ch-ans card" },
184
+ h("div", { class: "ch-ans-h" }, h("span", { class: "ch-l", style: `background:${CHAT_COLORS[i]}`, text: col.letter }), h("b", { text: colName(col) }), h("span", { class: "mono mu", text: stats })),
185
+ h("div", { class: `ch-text ${code ? "code" : ""}`, lang: "und" }, segs.length ? segs.map(([t, d]) => (d ? h("mark", { text: t }) : t)) : h("span", { class: "mu", text: a && a.state === "answering" ? "…" : "" })),
186
+ h("div", { class: `ch-verdict ${tone}` }, h("span", { class: "ch-vi", text: mark }), h("span", { text: verdict })));
187
+ }
188
+
189
+ function renderTurns() {
190
+ const cols = st.columns;
191
+ const n = st.turns.length;
192
+ turnsEl.replaceChildren(...st.turns.map((t) => h("article", { class: "ch-turn" },
193
+ h("div", { class: "ch-q" }, h("span", { class: "avatar", text: ((account.name || account.email || "?")[0] || "?").toUpperCase() }),
194
+ h("div", {}, h("small", { class: "mu", text: "You" }), h("p", { text: t.question })),
195
+ saveBtn(st.turns.indexOf(t))),
196
+ h("div", { class: "ch-answers", style: `grid-template-columns:repeat(${cols.length}, minmax(0, 1fr))` }, cols.map((c, i) => answerCard(t, c, i))))));
197
+ if (n > (renderTurns.seen || 0)) composer.scrollIntoView({ block: "end", behavior: "smooth" });
198
+ renderTurns.seen = n;
199
+ }
200
+
201
+ function renderComposer() {
202
+ const can = st.phase === "ready";
203
+ input.disabled = !can; askBtn.disabled = !can;
204
+ input.placeholder = st.phase === "answering" ? "Answering…" : can ? "Ask every column the same question, in any language…" : "Load the versions first";
205
+ }
206
+
207
+ // ---- context, suggestions, saving, summary (slice 3) ----
208
+ const enc = encodeURIComponent;
209
+ const ctxOn = () => chatUi.ctxOn && Boolean(chatUi.ctxSet && chatUi.ctxData);
210
+ async function pickSet(name) {
211
+ chatUi.ctxSet = name; chatUi.ctxData = null; chatUi.docs = []; chatUi.error = null;
212
+ if (name) { try { chatUi.ctxData = await api(`/api/testsets/${enc(name)}`); chatUi.ctxOn = true; } catch (e) { chatUi.ctxSet = ""; chatUi.error = e.message; } }
213
+ renderAll();
214
+ }
215
+ function renderCtx() {
216
+ const d = chatUi.ctxData, on = ctxOn();
217
+ const sel = h("select", { "aria-label": "Test set to take context from", onchange: (e) => pickSet(e.target.value) },
218
+ h("option", { value: "", text: sets.length ? "No test set" : "No test sets yet" }),
219
+ ...sets.map((x) => h("option", { value: x.name, selected: x.name === chatUi.ctxSet, text: x.name })));
220
+ const sw = h("button", { type: "button", class: "ch-sw", role: "switch", "aria-checked": String(on), disabled: !chatUi.ctxSet, onclick: () => { chatUi.ctxOn = !chatUi.ctxOn; renderAll(); } }, h("span", { class: "ch-knob" }), on ? "Context on" : chatUi.ctxSet ? "Context off · bare questions only" : "Context off");
221
+ const cells = on ? h("div", { class: "ch-ctx-cells" },
222
+ h("div", {}, h("span", { class: "lbl", text: "Instructions" }), h("span", { class: "ch-clip", text: (d.header.system || "").trim() || "None in this set" })),
223
+ h("div", {}, h("span", { class: "lbl", text: "Documents" }), h("span", { text: chatUi.docs.length ? `${chatUi.docs.length} from the prompt you picked` : "Sent when you pick a prompt below" })),
224
+ h("div", {}, h("span", { class: "lbl", text: "Tools" }), h("span", { class: "mono ch-clip", text: (d.header.tools || []).map((x) => x.name).join(" · ") || "None in this set" }))) : null;
225
+ ctxEl.replaceChildren(h("div", { class: "ch-ctx-h" }, sw, h("span", { class: "mu", text: "Sent with every question, like your app does" }), h("span", { class: "ch-ctx-set" }, sel, h("a", { href: chatUi.ctxSet ? `#/sets/edit/${enc(chatUi.ctxSet)}` : "#/sets", text: chatUi.ctxSet ? "Edit context" : "Test sets" }))), cells);
226
+ }
227
+ function renderSugg() {
228
+ const cases = ctxOn() ? chatUi.ctxData.cases.filter((c) => c.prompt).slice(0, 4) : [];
229
+ suggEl.hidden = !cases.length;
230
+ suggEl.replaceChildren(...(cases.length ? [h("span", { class: "mu", text: "Try" }), ...cases.map((c) => h("button", { type: "button", class: "chip plain ch-try", title: c.prompt, disabled: st.phase !== "ready", onclick: () => { input.value = c.prompt; chatUi.docs = c.context || []; renderCtx(); input.focus(); } }, c.prompt.length > 44 ? `${c.prompt.slice(0, 42)}…` : c.prompt))] : []));
231
+ }
232
+ async function saveTurns(idxs) {
233
+ const target = chatUi.saveTo === "__new" ? chatUi.newName.trim().replace(/\.jsonl$/, "") : chatUi.saveTo;
234
+ if (!target) { chatUi.saveMsg = ["fail", "Pick a test set, or name a new one."]; renderSide(); return; }
235
+ try {
236
+ let header = {}, cases = [];
237
+ if (chatUi.saveTo !== "__new") { const cur = await api(`/api/testsets/${enc(target)}`); header = cur.header; cases = cur.cases; }
238
+ const have = new Set(cases.map((c) => c.prompt)), ids = new Set(cases.map((c) => c.id));
239
+ let added = 0, n = 0;
240
+ for (const i of idxs) {
241
+ const q = st.turns[i].question;
242
+ if (have.has(q)) { chatUi.saved[i] = target; continue; }
243
+ do { n++; } while (ids.has(`chat-${String(n).padStart(3, "0")}`));
244
+ const id = `chat-${String(n).padStart(3, "0")}`; ids.add(id);
245
+ cases.push({ id, prompt: q, tags: ["chat"] }); have.add(q); chatUi.saved[i] = target; added++;
246
+ }
247
+ await api(`/api/testsets/${enc(target)}`, { method: "PUT", body: { header, cases } });
248
+ if (!sets.some((x) => x.name === target)) sets.push({ name: target });
249
+ if (chatUi.saveTo === "__new") chatUi.saveTo = target;
250
+ chatUi.saveMsg = ["ok", `${added} prompt${added === 1 ? "" : "s"} added to ${target}${idxs.length - added ? ` (${idxs.length - added} already there)` : ""}.`];
251
+ } catch (e) { chatUi.saveMsg = ["fail", e.message]; }
252
+ renderAll();
253
+ }
254
+ function saveBtn(i) {
255
+ const to = chatUi.saved[i];
256
+ return h("button", { type: "button", class: `btn ch-save ${to ? "done" : ""}`, onclick: () => (to ? null : saveTurns([i])) }, svgEl(["M12 5v14M5 12h14"], "ico"), to ? `Saved to ${to}` : "Save as test prompt");
257
+ }
258
+ function renderSide() {
259
+ const rows = st.columns.map((c, i) => {
260
+ let same = 0, chg = 0, bad = 0;
261
+ for (const t of st.turns) {
262
+ const a = t.answers[c.letter], ref = t.answers[st.columns[0].letter];
263
+ if (!a || a.state === "error") { if (i > 0 || !a) bad++; continue; }
264
+ if (i === 0 || a.state !== "done" || !ref || ref.state !== "done") continue;
265
+ if (chatNorm(a.text) === chatNorm(ref.text)) same++; else chg++;
266
+ }
267
+ return [c, i, same, chg, bad];
268
+ });
269
+ const mem = st.columns.reduce((a, c) => a + (c.size_gb || 0) * CHAT_OVERHEAD, 0);
270
+ const target = chatUi.saveTo;
271
+ const saveSel = h("select", { "aria-label": "Save prompts to", onchange: (e) => { chatUi.saveTo = e.target.value; renderSide(); } },
272
+ h("option", { value: "", text: "Choose a test set…" }), ...sets.map((x) => h("option", { value: x.name, selected: x.name === target, text: x.name })), h("option", { value: "__new", selected: target === "__new", text: "New test set…" }));
273
+ sideEl.replaceChildren(h("h2", { text: "This session" }),
274
+ st.turns.length && st.columns.length ? h("div", { class: "ch-score" },
275
+ h("span", { class: "lbl", text: "vs column A" }), h("span", { class: "lbl ch-good", text: "Same" }), h("span", { class: "lbl", style: "color:var(--warn)", text: "Diff" }), h("span", { class: "lbl ch-bad", text: "Err" }),
276
+ ...rows.flatMap(([c, i, same, chg, bad]) => [h("span", { class: "ch-sn" }, h("span", { class: "ch-l", style: `background:${CHAT_COLORS[i]}`, text: c.letter }), colName(c)),
277
+ ...(i === 0 ? [h("span", { class: "mono", text: "—" }), h("span", { class: "mono", text: "—" }), h("span", { class: "mono", text: String(bad) })] : [h("span", { class: "mono", text: String(same) }), h("span", { class: "mono", text: String(chg) }), h("span", { class: "mono", text: String(bad) })])])) : h("p", { class: "mu ch-small", text: "Ask a question to see how the versions compare." }),
278
+ h("div", { class: "ch-memc" }, h("span", { class: "lbl", text: "Memory for these columns" }), h("b", { class: "mono", text: mem ? `${mem.toFixed(1)} GB` : "—" }), mem ? h("small", { class: mem <= sysBudget ? "ch-good" : "ch-bad", text: mem <= sysBudget ? "All loaded together" : "Over what this Mac can give" }) : null),
279
+ h("div", { class: "ch-save-box" }, saveSel, target === "__new" ? h("input", { type: "text", "aria-label": "New test set name", placeholder: "name, e.g. my-chat-prompts", value: chatUi.newName, oninput: (e) => { chatUi.newName = e.target.value; } }) : null,
280
+ h("button", { type: "button", class: "btn primary", disabled: !st.turns.length, onclick: () => saveTurns(st.turns.map((_, i) => i)), text: "Save all prompts to a test set" }),
281
+ chatUi.saveMsg ? h("p", { class: `ch-small ${chatUi.saveMsg[0] === "ok" ? "ch-good" : "ch-bad"}`, role: "status", text: chatUi.saveMsg[1] }) : null,
282
+ h("p", { class: "mu ch-small", text: "Saved as prompts only. The reference answer comes from the biggest version when you run the test." })),
283
+ h("p", { class: "mu ch-small" }, "Chat is for quick checks. For a decision you can trust, ", h("a", { href: "#/new", text: "run a full test" }), " on 100+ prompts."));
284
+ }
285
+
286
+ function renderAll() { renderToolbar(); renderLanes(); renderPicker(); renderAlert(); renderCtx(); renderSugg(); renderTurns(); renderComposer(); renderSide(); }
287
+
288
+ async function refresh() {
289
+ try { st = await api("/api/chat"); } catch (e) { return; }
290
+ renderAll();
291
+ if (location.hash.startsWith("#/chat") && (st.phase === "loading" || st.phase === "answering")) pollTimer = setTimeout(refresh, 350);
292
+ }
293
+ async function act(path, payload) {
294
+ chatUi.error = null;
295
+ try { st = await api(path, { method: "POST", body: payload || {} }); } catch (e) { chatUi.error = e.message; }
296
+ renderAll();
297
+ if (st.phase === "loading" || st.phase === "answering") { stopPolling(); pollTimer = setTimeout(refresh, 350); }
298
+ }
299
+ const loadAll = () => act("/api/chat/load", { columns: picked().map((p) => ({ model: p.id, runtime: p.runtime })) });
300
+ const closeChat = () => { renderTurns.seen = 0; return act("/api/chat/close"); };
301
+ function ask() {
302
+ const text = input.value.trim();
303
+ if (!text || st.phase !== "ready") return;
304
+ input.value = "";
305
+ const ctx = chatUi.ctxOn && chatUi.ctxSet ? { tests: chatUi.ctxSet, documents: chatUi.docs } : {};
306
+ chatUi.docs = [];
307
+ act("/api/chat/ask", { text, ...ctx });
308
+ }
309
+
310
+ renderAll();
311
+ if (st.phase === "loading" || st.phase === "answering") pollTimer = setTimeout(refresh, 350);
312
+ }
@@ -0,0 +1,14 @@
1
+ # Bundled fonts
2
+
3
+ Served from this folder so the lab makes no requests to Google. Downloaded 28 Nov 2026 from
4
+ Google Fonts (latin, latin-ext, devanagari and tamil subsets only).
5
+
6
+ | Font | Used for | Licence |
7
+ |---|---|---|
8
+ | Outfit | headings, interface | SIL Open Font License 1.1 |
9
+ | JetBrains Mono | commands, model names, numbers | SIL Open Font License 1.1 |
10
+ | Noto Sans Devanagari | Hindi, Marathi | SIL Open Font License 1.1 |
11
+ | Noto Sans Tamil | Tamil | SIL Open Font License 1.1 |
12
+
13
+ The OFL permits bundling and redistribution with software. Telugu and Bengali fall back to the
14
+ system font until their subsets are added.