mlx-bun 0.0.10 → 0.0.12

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 (216) hide show
  1. package/README.md +107 -32
  2. package/THIRD_PARTY_LICENSES.md +10 -0
  3. package/docs/archive/mlx-bun-lab-report.html +275 -0
  4. package/docs/archive/wwdc-mlx-bun.html +848 -0
  5. package/docs/design/audio-input-plan.md +356 -0
  6. package/docs/design/batching-perf-path.md +58 -35
  7. package/docs/design/batching-v2-plan.md +23 -9
  8. package/docs/design/bucketing-stage.md +2 -1
  9. package/docs/design/colibri-glm52-port.md +1479 -0
  10. package/docs/design/compat-cli-surface-design.md +4 -3
  11. package/docs/design/decode-speed-program.md +172 -0
  12. package/docs/design/docs-reorg-plan.md +1 -1
  13. package/docs/design/dspark-serving-program.md +371 -0
  14. package/docs/design/dspark-speculative-decoding.md +167 -5
  15. package/docs/design/faithful-l1-consolidation.md +310 -0
  16. package/docs/design/generic-model-support.md +8 -5
  17. package/docs/design/grammar-spec-batching-integration.md +301 -0
  18. package/docs/design/minicpm5-decode-megakernel.md +16 -11
  19. package/docs/design/mlx-lm-tool-parity-plan.md +11 -1
  20. package/docs/design/omlx-adoption-map.md +14 -6
  21. package/docs/design/orpo-training.md +34 -30
  22. package/docs/design/paged-kv-cache.md +214 -0
  23. package/docs/design/parallel-slots.md +82 -49
  24. package/docs/design/parity-tier-dag.md +43 -33
  25. package/docs/design/pre-colibri-stabilization.md +329 -0
  26. package/docs/design/repo-cleanup-plan.md +189 -0
  27. package/docs/design/runtime-isolation.md +19 -3
  28. package/docs/design/segmented-backward-training.md +3 -2
  29. package/docs/design/ssd-kv-cold-tier.md +130 -0
  30. package/docs/design/structured-output.md +484 -0
  31. package/docs/design/the-dreaming-master-plan.md +2 -3
  32. package/docs/design/turboquant-kv.md +235 -0
  33. package/docs/design/unified-engine-frontier-plan.md +774 -0
  34. package/docs/design/web-chat-beat-matrix.md +315 -0
  35. package/docs/design/web-chat-redesign.md +1112 -0
  36. package/docs/investigations/colibri-oracle-pin.md +1284 -0
  37. package/docs/investigations/dspark-handoff.md +182 -16
  38. package/docs/investigations/indexshare-performance-spike.md +357 -0
  39. package/docs/investigations/lab-build-journal.md +2 -2
  40. package/docs/investigations/openwiki-evaluation.md +249 -0
  41. package/docs/planning/IDEAS.md +14 -0
  42. package/docs/planning/PRODUCT_ROADMAP.md +2 -3
  43. package/docs/planning/chat-ui-vision-memory-first.md +199 -0
  44. package/docs/planning/chat-ui-vision.md +50 -0
  45. package/docs/planning/memory-docs-and-dag-plan.md +15 -6
  46. package/docs/planning/release-notes-v0.0.11.md +239 -0
  47. package/docs/planning/release-notes-v0.0.12.md +80 -0
  48. package/docs/reference/cli.md +63 -18
  49. package/docs/reference/distribution.md +37 -6
  50. package/docs/reference/embedding.md +40 -16
  51. package/docs/reference/features-matrix.md +99 -0
  52. package/docs/reference/library-api.md +69 -20
  53. package/docs/reference/memory.md +26 -6
  54. package/docs/reference/models.md +60 -3
  55. package/docs/reference/orpo-quickstart.md +3 -4
  56. package/docs/reference/server-api.md +717 -24
  57. package/docs/reference/server-config.md +265 -129
  58. package/docs/reference/training.md +24 -16
  59. package/package.json +5 -3
  60. package/src/anthropic.ts +67 -44
  61. package/src/audio/conformer.ts +647 -0
  62. package/src/audio/decode.ts +133 -0
  63. package/src/audio/features.ts +202 -0
  64. package/src/audio/transcode.ts +67 -0
  65. package/src/chat-template.ts +155 -10
  66. package/src/cli.ts +483 -113
  67. package/src/config.ts +116 -24
  68. package/src/diffusion/diffusion-generate.ts +14 -8
  69. package/src/download.ts +143 -12
  70. package/src/eval/README.md +7 -6
  71. package/src/eval/ifeval.ts +63 -120
  72. package/src/eval/kl.ts +59 -3
  73. package/src/eval/quality-db.ts +2 -2
  74. package/src/eval/runner.ts +17 -8
  75. package/src/eval/tasks/ifeval.ts +167 -31
  76. package/src/expert-io.ts +391 -0
  77. package/src/expert-offload.ts +15 -2
  78. package/src/expert-residency.ts +1134 -0
  79. package/src/expert-usage.ts +415 -0
  80. package/src/flags.ts +13 -0
  81. package/src/generate.ts +438 -35
  82. package/src/grammar.ts +585 -0
  83. package/src/hf-push.ts +1 -1
  84. package/src/hub-rest.ts +242 -0
  85. package/src/index.ts +14 -2
  86. package/src/jobs/runner.ts +37 -18
  87. package/src/kv-store.ts +586 -93
  88. package/src/lora.ts +85 -14
  89. package/src/md-modules.d.ts +42 -0
  90. package/src/media-fetch.ts +426 -0
  91. package/src/memory/rest.ts +245 -0
  92. package/src/memory/vault.ts +74 -0
  93. package/src/mlx/array.ts +149 -19
  94. package/src/mlx/autograd.ts +53 -16
  95. package/src/mlx/checkpoint.ts +46 -13
  96. package/src/mlx/custom-vjp.ts +83 -35
  97. package/src/mlx/ffi.ts +27 -3
  98. package/src/mlx/metal-kernel.ts +7 -4
  99. package/src/mlx/ops.ts +153 -23
  100. package/src/mlx/turboquant-ops.ts +831 -0
  101. package/src/mlx/turboquant-tables.ts +237 -0
  102. package/src/model/batched-mask.ts +62 -1
  103. package/src/model/batched-quant.ts +206 -0
  104. package/src/model/batched-rotating-quant.ts +346 -0
  105. package/src/model/batched-rotating.ts +46 -1
  106. package/src/model/compiled-decode.ts +4 -15
  107. package/src/model/factory.ts +103 -6
  108. package/src/model/gemma4-base.ts +395 -39
  109. package/src/model/gemma4.ts +122 -33
  110. package/src/model/generated/gemma4-12b.ts +9 -13
  111. package/src/model/generated/gemma4-26b.ts +10 -5
  112. package/src/model/generated/gemma4-e4b.ts +14 -9
  113. package/src/model/glm52-atlas.ts +511 -0
  114. package/src/model/glm52-cache.ts +706 -0
  115. package/src/model/glm52-config.ts +262 -0
  116. package/src/model/glm52-container.ts +305 -0
  117. package/src/model/glm52-coupling.ts +388 -0
  118. package/src/model/glm52-dsa.ts +602 -0
  119. package/src/model/glm52-expert-layout.ts +253 -0
  120. package/src/model/glm52-layout.ts +152 -0
  121. package/src/model/glm52-memory.ts +473 -0
  122. package/src/model/glm52-mla.ts +786 -0
  123. package/src/model/glm52-moe.ts +223 -0
  124. package/src/model/glm52-pilot.ts +537 -0
  125. package/src/model/glm52-reference.ts +445 -0
  126. package/src/model/glm52-residency.ts +557 -0
  127. package/src/model/glm52-resident-weights.ts +135 -0
  128. package/src/model/glm52-streamed-experts.ts +453 -0
  129. package/src/model/glm52-streamed-metal.ts +610 -0
  130. package/src/model/glm52-weights.ts +503 -0
  131. package/src/model/glm52.ts +1153 -0
  132. package/src/model/minicpm5.ts +58 -102
  133. package/src/model/paged-kv.ts +253 -0
  134. package/src/model/qwen3-delta.ts +76 -15
  135. package/src/model/qwen3-moe.ts +404 -0
  136. package/src/model/qwen3.ts +9 -8
  137. package/src/model/qwen3_5.ts +88 -23
  138. package/src/model/support.ts +19 -1
  139. package/src/model/universal/dense.ts +40 -5
  140. package/src/model/universal/rope.ts +36 -21
  141. package/src/native/expert_io.c +523 -0
  142. package/src/native-pack.ts +6 -4
  143. package/src/pi-web.ts +1299 -82
  144. package/src/preflight.ts +27 -8
  145. package/src/prompt-cache.ts +293 -33
  146. package/src/quantize/quantizer.ts +16 -1
  147. package/src/registry.ts +57 -2
  148. package/src/responses.ts +62 -49
  149. package/src/serve/batch-scheduler.ts +1050 -78
  150. package/src/serve/generation-gateway.ts +252 -24
  151. package/src/serve/isolate.ts +417 -0
  152. package/src/serve/lane-registry.ts +44 -0
  153. package/src/serve/session-search.ts +326 -0
  154. package/src/server.ts +1701 -175
  155. package/src/spec/assistant-source.ts +150 -0
  156. package/src/spec/deepspec-source.ts +143 -0
  157. package/src/spec/dflash-source.ts +124 -0
  158. package/src/spec/dspark/ab-stats.ts +136 -0
  159. package/src/spec/dspark/calibration.ts +112 -0
  160. package/src/spec/dspark/deepspec-module.ts +801 -0
  161. package/src/spec/dspark/generate-dflash.ts +72 -20
  162. package/src/spec/dspark/loader.ts +23 -0
  163. package/src/spec/dspark/module-dflash.ts +278 -36
  164. package/src/spec/dspark/quantize-drafter.ts +91 -0
  165. package/src/spec/generate.ts +59 -25
  166. package/src/spec/glm52-mtp-source.ts +392 -0
  167. package/src/spec/ngram-source.ts +132 -0
  168. package/src/spec/serve-loop.ts +617 -0
  169. package/src/spec/source.ts +118 -0
  170. package/src/spec/two-model.ts +171 -0
  171. package/src/ssd-cache.ts +111 -35
  172. package/src/tokenizer.ts +288 -2
  173. package/src/tool-approvals.ts +131 -0
  174. package/src/tool-call.ts +438 -22
  175. package/src/train/flash-cce.ts +2 -2
  176. package/src/train/job.ts +0 -12
  177. package/src/train/lora-params.ts +17 -6
  178. package/src/train/trainer.ts +60 -30
  179. package/src/vision/prompt.ts +217 -48
  180. package/src/web/app.html +1197 -1791
  181. package/src/web/app.js +5694 -0
  182. package/src/web/icon.svg +13 -0
  183. package/src/web/manifest.webmanifest +24 -0
  184. package/src/web/src/adapters-panel.ts +288 -0
  185. package/src/web/src/api.ts +57 -0
  186. package/src/web/src/assistant.ts +485 -0
  187. package/src/web/src/chat.ts +1050 -0
  188. package/src/web/src/composer.ts +959 -0
  189. package/src/web/src/dataset.ts +132 -0
  190. package/src/web/src/finetune.ts +267 -0
  191. package/src/web/src/hub.ts +428 -0
  192. package/src/web/src/main.ts +98 -0
  193. package/src/web/src/markdown.ts +0 -0
  194. package/src/web/src/memory-panel.ts +572 -0
  195. package/src/web/src/model-picker.ts +159 -0
  196. package/src/web/src/palette.ts +346 -0
  197. package/src/web/src/protocol.ts +62 -0
  198. package/src/web/src/quantize.ts +167 -0
  199. package/src/web/src/rag.ts +274 -0
  200. package/src/web/src/sessions.ts +469 -0
  201. package/src/web/src/shell.ts +804 -0
  202. package/src/web/src/status.ts +300 -0
  203. package/src/web/src/ui-catalog.ts +92 -0
  204. package/src/web/sw.js +71 -0
  205. package/src/web/vendor/README.md +61 -0
  206. package/src/web/vendor/hljs-LICENSE +29 -0
  207. package/src/web/vendor/hljs-theme.css +59 -0
  208. package/src/web/vendor/hljs.js +26 -0
  209. package/src/web-tools.ts +54 -2
  210. package/src/weights.ts +82 -19
  211. package/src/model/fused-decode-kernel.ts +0 -312
  212. package/src/model/fused-geglu-kernel.ts +0 -198
  213. package/src/model/fused-mlp-kernel.ts +0 -169
  214. package/src/model/fused-swiglu-kernel.ts +0 -240
  215. package/src/model/steel-linear-kernel.ts +0 -96
  216. package/src/status-page.html +0 -497
@@ -0,0 +1,428 @@
1
+ // GENERATED-ADJACENT source module — part of the src/web/src/* split (plan
2
+ // §7/§9 Phase 3). Built into src/web/app.js by scripts/build-web.ts.
3
+ //
4
+ // Model Hub panel (docs/design/web-chat-redesign.md §9 Phase 3, beat-matrix
5
+ // Axis 3 "Hub" row). Same overlay language/chrome as the Memory panel
6
+ // (mem-overlay/mem-panel/mem-head/mem-body): fixed right-side panel,
7
+ // scrimmed, focus-trapped, Escape closes, opened from the model picker
8
+ // popover's "Browse models…" action (and exported for palette use later).
9
+ //
10
+ // Three sections talking to src/hub-rest.ts's REST wrappers — no new WS
11
+ // frames:
12
+ // - Downloaded <- GET /api/hub/local (size/quant/capability chips, the
13
+ // /fit verdict as a green/yellow/red dot + predicted tok/s, a "serve"
14
+ // action).
15
+ // - Search Hugging Face <- debounced GET /api/hub/search (id/downloads/
16
+ // size, a Download action -> POST /api/hub/download, then live progress
17
+ // via polling GET /downloads while the panel stays open).
18
+ // - A quiet offline footer note when search/local fail to reach the
19
+ // network (never conflated with "no results").
20
+ //
21
+ // NEVER auto-downloads, NEVER auto-serves — every action is an explicit
22
+ // click. esc() every interpolation site: repo ids/model types are
23
+ // server-reported but ultimately HF-namespace strings, same hazard class
24
+ // model-picker.ts already treats as untrusted.
25
+
26
+ import { $, toast, trapFocus, setHubPanelClose, setOpenHubFromModelPicker, type FocusTrap } from "./shell";
27
+ import { api } from "./api";
28
+ import type { ApiEnvelope } from "./protocol";
29
+ import { esc } from "./markdown";
30
+
31
+ /* ────────────────────────────────────────────────────────────────────
32
+ REST response shapes (mirrors src/hub-rest.ts's jsonOk() bodies).
33
+ ──────────────────────────────────────────────────────────────────── */
34
+
35
+ export interface HubLocalRow {
36
+ repo_id: string;
37
+ model_type: string;
38
+ size_bytes: number;
39
+ quant_bits: number | null;
40
+ quant_group_size: number | null;
41
+ vision: boolean;
42
+ supported: boolean;
43
+ support_tier: "targeted" | "generic" | null;
44
+ assessment: { fits: boolean; max_safe_context: number; predicted_decode_tps: number } | null;
45
+ }
46
+ type LocalResp = ApiEnvelope & { models?: HubLocalRow[] };
47
+
48
+ export interface HubSearchRow {
49
+ id: string;
50
+ downloads: number;
51
+ likes: number;
52
+ size_estimate: number | null;
53
+ }
54
+ type SearchResp = ApiEnvelope & { offline?: boolean; results?: HubSearchRow[] };
55
+
56
+ interface DownloadInfo {
57
+ repoId: string;
58
+ state: "active" | "done" | "error";
59
+ currentFile: string | null;
60
+ receivedBytes: number;
61
+ totalBytes: number;
62
+ bytesPerSec?: number;
63
+ error?: string;
64
+ }
65
+ type DownloadsResp = { downloads?: DownloadInfo[] };
66
+
67
+ /* ────────────────────────────────────────────────────────────────────
68
+ Shared formatting (local copies — hub.ts has no import from
69
+ model-picker.ts to avoid a cross-popover coupling neither side needs).
70
+ ──────────────────────────────────────────────────────────────────── */
71
+
72
+ function gb(n: number): string { return (n / 2 ** 30).toFixed(1) + " GB"; }
73
+
74
+ /** Same three-tier convention as model-picker.ts's fitVerdict: green (fits
75
+ * with headroom, >=10 tok/s), yellow (fits but slow), red (doesn't fit),
76
+ * null (no assessment). Kept as a local copy rather than a shared import
77
+ * since the two modules' row shapes differ slightly (Hub's assessment is
78
+ * non-optional-null but otherwise identical) — duplicating one small pure
79
+ * function is cheaper than adding a cross-import for four lines of logic. */
80
+ function fitVerdict(a: HubLocalRow["assessment"]): "green" | "yellow" | "red" | null {
81
+ if (!a) return null;
82
+ if (!a.fits) return "red";
83
+ return a.predicted_decode_tps >= 10 ? "green" : "yellow";
84
+ }
85
+
86
+ function fitDotHtml(verdict: "green" | "yellow" | "red" | null): string {
87
+ return verdict
88
+ ? '<span class="hub-fit-dot ' + verdict + '" aria-hidden="true"></span>'
89
+ : '<span class="hub-fit-dot" aria-hidden="true" style="background:var(--dimmer)"></span>';
90
+ }
91
+
92
+ /* ────────────────────────────────────────────────────────────────────
93
+ Downloaded section
94
+ ──────────────────────────────────────────────────────────────────── */
95
+
96
+ function localRowHtml(m: HubLocalRow): string {
97
+ const verdict = fitVerdict(m.assessment);
98
+ const name = m.repo_id.split("/").pop() || m.repo_id;
99
+ const quant = m.quant_bits ? m.quant_bits + "-bit" : "unquantized";
100
+ const metaBits = [gb(m.size_bytes), quant];
101
+ if (m.vision) metaBits.push("vision");
102
+ if (!m.supported) metaBits.push("unsupported model family");
103
+ const tpsBit = m.assessment && m.assessment.fits
104
+ ? m.assessment.predicted_decode_tps.toFixed(0) + " tok/s predicted"
105
+ : m.assessment ? "doesn't fit this Mac's memory" : "fit unknown";
106
+ const serveBtn = m.supported
107
+ ? '<button type="button" class="hub-serve-btn" data-repo="' + esc(m.repo_id) + '">Serve</button>'
108
+ : "";
109
+ return (
110
+ '<div class="hub-row">' +
111
+ fitDotHtml(verdict) +
112
+ '<div class="hub-row-main">' +
113
+ '<div class="hub-row-name" title="' + esc(m.repo_id) + '">' + esc(name) + "</div>" +
114
+ '<div class="hub-row-meta">' + esc(metaBits.join(" · ")) + " · " + esc(tpsBit) + "</div>" +
115
+ "</div>" +
116
+ '<div class="hub-row-actions">' + serveBtn + "</div>" +
117
+ "</div>"
118
+ );
119
+ }
120
+
121
+ /** Pure render, exported for esc()-discipline + empty-state tests
122
+ * (tests/web-app.test.ts, mirroring renderModelPopBodyHtml's pattern). */
123
+ export function renderHubLocalHtml(models: HubLocalRow[]): string {
124
+ if (!models.length) {
125
+ return '<div class="hub-empty">No models downloaded yet — search Hugging Face below to get one.</div>';
126
+ }
127
+ return [...models]
128
+ .sort((a, b) => a.repo_id.localeCompare(b.repo_id))
129
+ .map(localRowHtml)
130
+ .join("");
131
+ }
132
+
133
+ async function loadLocal(): Promise<void> {
134
+ const body = $("hub-local-body");
135
+ if (!body) return;
136
+ body.innerHTML = '<div class="hub-empty"><span class="shimmer">loading…</span></div>';
137
+ try {
138
+ const d = await api<LocalResp>("/api/hub/local");
139
+ body.innerHTML = renderHubLocalHtml(d.models || []);
140
+ wireServeButtons(body);
141
+ } catch {
142
+ body.innerHTML = '<div class="hub-empty">Could not reach the server.</div>';
143
+ }
144
+ }
145
+
146
+ /* ────────────────────────────────────────────────────────────────────
147
+ Serve action — handles BOTH the live-swap outcome (if a future server
148
+ ever returns ok:true) and today's honest restart_required outcome,
149
+ rendered as a copy-able command. NEVER auto-serves — this is only
150
+ reachable from an explicit button click.
151
+ ──────────────────────────────────────────────────────────────────── */
152
+
153
+ function wireServeButtons(container: HTMLElement): void {
154
+ container.querySelectorAll<HTMLButtonElement>(".hub-serve-btn").forEach((btn) => {
155
+ btn.onclick = () => serveModel(btn.dataset.repo || "", btn);
156
+ });
157
+ }
158
+
159
+ type ServeResp = ApiEnvelope & { restart_required?: boolean; command?: string };
160
+
161
+ async function serveModel(repo: string, btn: HTMLButtonElement): Promise<void> {
162
+ if (!repo) return;
163
+ btn.disabled = true;
164
+ const prevText = btn.textContent;
165
+ btn.textContent = "Checking…";
166
+ const d = await api<ServeResp>("/api/hub/serve", { method: "POST", body: { model: repo } })
167
+ .catch((): ServeResp => ({ ok: false, error: "request failed" }));
168
+ btn.disabled = false;
169
+ btn.textContent = prevText;
170
+ if (d.ok) {
171
+ // Honest today-doesn't-happen branch, kept real rather than dead code:
172
+ // if the server ever reports a completed live swap, reflect it plainly.
173
+ toast("Now serving " + repo, "ok");
174
+ return;
175
+ }
176
+ if (d.restart_required && d.command) {
177
+ showRestartCommand(repo, d.command);
178
+ return;
179
+ }
180
+ toast("Couldn't switch models: " + (d.error || "unknown error"), "err");
181
+ }
182
+
183
+ /** Renders the restart command inline in the footer strip (not a toast —
184
+ * it needs to stay visible long enough to copy) with an honest note:
185
+ * restarting takes ~seconds and sessions are preserved on disk (chat
186
+ * history lives in local JSON regardless of which model process serves
187
+ * it — restarting the model doesn't touch it). */
188
+ function showRestartCommand(repo: string, command: string): void {
189
+ const strip = $("hub-restart-strip");
190
+ if (!strip) return;
191
+ strip.innerHTML =
192
+ '<div class="hub-restart-note">Switching to <strong>' + esc(repo) + '</strong> needs a restart — ' +
193
+ "there's no live in-process model swap on this path yet. Restarting takes about a second " +
194
+ "and your sessions are preserved on disk, exactly as they are now.</div>" +
195
+ '<div class="hub-cmd"><code>' + esc(command) + '</code>' +
196
+ '<button type="button" class="hub-copy-btn" data-cmd="' + esc(command) + '">Copy</button></div>';
197
+ strip.classList.add("show");
198
+ const copyBtn = strip.querySelector(".hub-copy-btn") as HTMLButtonElement | null;
199
+ if (copyBtn) {
200
+ copyBtn.onclick = () => {
201
+ const cmd = copyBtn.dataset.cmd || "";
202
+ if (navigator.clipboard) {
203
+ navigator.clipboard.writeText(cmd).then(() => {
204
+ const prev = copyBtn.textContent; copyBtn.textContent = "Copied";
205
+ setTimeout(() => { copyBtn.textContent = prev; }, 1200);
206
+ }).catch(() => {});
207
+ }
208
+ };
209
+ }
210
+ }
211
+
212
+ function hideRestartStrip(): void {
213
+ const strip = $("hub-restart-strip");
214
+ if (strip) { strip.classList.remove("show"); strip.innerHTML = ""; }
215
+ }
216
+
217
+ /* ────────────────────────────────────────────────────────────────────
218
+ Search Hugging Face section — debounced, offline-aware.
219
+ ──────────────────────────────────────────────────────────────────── */
220
+
221
+ function searchRowHtml(r: HubSearchRow, downloading: boolean): string {
222
+ const name = r.id.split("/").pop() || r.id;
223
+ const metaBits = [r.downloads.toLocaleString() + " downloads"];
224
+ if (r.size_estimate != null) metaBits.push(gb(r.size_estimate));
225
+ const action = downloading
226
+ ? '<span class="hub-dl-tag">downloading…</span>'
227
+ : '<button type="button" class="hub-download-btn" data-repo="' + esc(r.id) + '">Download</button>';
228
+ return (
229
+ '<div class="hub-row" data-search-repo="' + esc(r.id) + '">' +
230
+ '<div class="hub-row-main">' +
231
+ '<div class="hub-row-name" title="' + esc(r.id) + '">' + esc(name) + "</div>" +
232
+ '<div class="hub-row-meta">' + esc(r.id) + " · " + esc(metaBits.join(" · ")) + "</div>" +
233
+ "</div>" +
234
+ '<div class="hub-row-actions">' + action + "</div>" +
235
+ "</div>"
236
+ );
237
+ }
238
+
239
+ /** Pure render, exported for tests. `downloading` is the set of repo ids
240
+ * with an active download right now (from GET /downloads polling). */
241
+ export function renderHubSearchHtml(results: HubSearchRow[], offline: boolean, downloading: Set<string>): string {
242
+ if (offline) {
243
+ return '<div class="hub-empty">Can\'t reach Hugging Face right now — search needs a network connection.</div>';
244
+ }
245
+ if (!results.length) {
246
+ return '<div class="hub-empty">No matches.</div>';
247
+ }
248
+ return results.map((r) => searchRowHtml(r, downloading.has(r.id))).join("");
249
+ }
250
+
251
+ let searchDebounce: ReturnType<typeof setTimeout> | undefined;
252
+ let lastSearchQuery = "";
253
+ let inFlightDownloads = new Set<string>();
254
+
255
+ async function runSearch(query: string): Promise<void> {
256
+ const body = $("hub-search-body");
257
+ if (!body) return;
258
+ lastSearchQuery = query;
259
+ if (!query) { body.innerHTML = '<div class="hub-empty">Type to search Hugging Face for MLX models.</div>'; return; }
260
+ body.innerHTML = '<div class="hub-empty"><span class="shimmer">searching…</span></div>';
261
+ const d = await api<SearchResp>("/api/hub/search?q=" + encodeURIComponent(query))
262
+ .catch((): SearchResp => ({ ok: false, offline: true, results: [] }));
263
+ if (lastSearchQuery !== query) return; // a newer keystroke already superseded this response
264
+ const offline = !!d.offline;
265
+ body.innerHTML = renderHubSearchHtml(d.results || [], offline, inFlightDownloads);
266
+ wireDownloadButtons(body);
267
+ setOfflineFooter(offline);
268
+ }
269
+
270
+ function wireDownloadButtons(container: HTMLElement): void {
271
+ container.querySelectorAll<HTMLButtonElement>(".hub-download-btn").forEach((btn) => {
272
+ btn.onclick = () => startDownload(btn.dataset.repo || "", btn);
273
+ });
274
+ }
275
+
276
+ type DownloadStartResp = ApiEnvelope & { repo?: string; started?: boolean };
277
+
278
+ async function startDownload(repo: string, btn: HTMLButtonElement): Promise<void> {
279
+ if (!repo) return;
280
+ btn.disabled = true;
281
+ btn.textContent = "Starting…";
282
+ const d = await api<DownloadStartResp>("/api/hub/download", { method: "POST", body: { repo } })
283
+ .catch((): DownloadStartResp => ({ ok: false, error: "request failed" }));
284
+ if (!d.ok) {
285
+ btn.disabled = false;
286
+ btn.textContent = "Download";
287
+ toast("Couldn't start download: " + (d.error || "unknown error"), "err");
288
+ return;
289
+ }
290
+ inFlightDownloads.add(repo);
291
+ toast("Downloading " + repo, "ok");
292
+ const row = btn.closest(".hub-row");
293
+ const actions = row ? row.querySelector(".hub-row-actions") : null;
294
+ if (actions) actions.innerHTML = '<span class="hub-dl-tag">downloading…</span>';
295
+ ensureDownloadPolling();
296
+ }
297
+
298
+ /* ────────────────────────────────────────────────────────────────────
299
+ Live download progress — reuses the existing GET /downloads endpoint
300
+ (same source the nav download pill polls) so the Hub panel's own
301
+ in-flight rows show real progress without a second tracker. Only polls
302
+ while the panel is open (started on open, stopped on close).
303
+ ──────────────────────────────────────────────────────────────────── */
304
+
305
+ let downloadPollTimer: ReturnType<typeof setInterval> | undefined;
306
+
307
+ function ensureDownloadPolling(): void {
308
+ if (downloadPollTimer) return;
309
+ downloadPollTimer = setInterval(pollDownloads, 1500);
310
+ }
311
+
312
+ function stopDownloadPolling(): void {
313
+ if (downloadPollTimer) { clearInterval(downloadPollTimer); downloadPollTimer = undefined; }
314
+ }
315
+
316
+ async function pollDownloads(): Promise<void> {
317
+ let downloads: DownloadInfo[] = [];
318
+ try {
319
+ const r = await fetch("/downloads");
320
+ const d = (await r.json()) as DownloadsResp;
321
+ downloads = d.downloads || [];
322
+ } catch { return; }
323
+
324
+ let anyActive = false;
325
+ for (const dl of downloads) {
326
+ if (dl.state === "active") { anyActive = true; inFlightDownloads.add(dl.repoId); }
327
+ const row = document.querySelector<HTMLElement>('.hub-row[data-search-repo="' + cssEscape(dl.repoId) + '"]');
328
+ if (!row) continue;
329
+ const actions = row.querySelector(".hub-row-actions");
330
+ if (!actions) continue;
331
+ if (dl.state === "active") {
332
+ const pct = dl.totalBytes ? Math.floor((dl.receivedBytes / dl.totalBytes) * 100) : 0;
333
+ actions.innerHTML = '<span class="hub-dl-tag">' + pct + "%</span>";
334
+ } else if (dl.state === "done") {
335
+ inFlightDownloads.delete(dl.repoId);
336
+ actions.innerHTML = '<span class="hub-dl-tag done">done — reload to serve</span>';
337
+ } else if (dl.state === "error") {
338
+ inFlightDownloads.delete(dl.repoId);
339
+ actions.innerHTML = '<span class="hub-dl-tag error">' + esc(dl.error || "download failed") + "</span>";
340
+ }
341
+ }
342
+ // A download that finished/errored and dropped out of the tracker's
343
+ // rolling window entirely still needs its stale "downloading…" tag
344
+ // cleared — treat "not present anymore" the same as "not active".
345
+ for (const repo of [...inFlightDownloads]) {
346
+ if (!downloads.some((d) => d.repoId === repo && d.state === "active")) inFlightDownloads.delete(repo);
347
+ }
348
+ if (!anyActive) stopDownloadPolling();
349
+ }
350
+
351
+ /** Minimal CSS.escape polyfill-free helper for attribute-selector lookups —
352
+ * repo ids are `org/name` (slash + alnum/hyphen/underscore/dot), so a full
353
+ * CSS.escape isn't needed; this only guards the one character (`"`) that
354
+ * would break the quoted attribute selector above. HF repo ids can't
355
+ * contain quotes, but this stays defensive rather than assuming it. */
356
+ function cssEscape(s: string): string {
357
+ return s.replace(/"/g, '\\"');
358
+ }
359
+
360
+ /* ────────────────────────────────────────────────────────────────────
361
+ Panel chrome: open/close, focus trap, section wiring.
362
+ ──────────────────────────────────────────────────────────────────── */
363
+
364
+ let panelTrap: FocusTrap;
365
+
366
+ export function isHubPanelOpen(): boolean {
367
+ const ov = $("hub-overlay");
368
+ return !!ov && ov.classList.contains("open");
369
+ }
370
+
371
+ export function closeHubPanel(): void {
372
+ $("hub-overlay").classList.remove("open");
373
+ stopDownloadPolling();
374
+ panelTrap.restore();
375
+ }
376
+
377
+ export async function openHubPanel(): Promise<void> {
378
+ panelTrap.capture();
379
+ $("hub-overlay").classList.add("open");
380
+ hideRestartStrip();
381
+ const search = $("hub-search-input") as HTMLInputElement | null;
382
+ if (search) search.value = "";
383
+ const searchBody = $("hub-search-body");
384
+ if (searchBody) searchBody.innerHTML = '<div class="hub-empty">Type to search Hugging Face for MLX models.</div>';
385
+ setOfflineFooter(false);
386
+ await loadLocal();
387
+ if (inFlightDownloads.size) ensureDownloadPolling();
388
+ setTimeout(() => { const el2 = $("hub-search-input") as HTMLInputElement | null; if (el2) el2.focus(); }, 30);
389
+ }
390
+
391
+ function setOfflineFooter(offline: boolean): void {
392
+ const note = $("hub-offline-note");
393
+ if (!note) return;
394
+ note.style.display = offline ? "" : "none";
395
+ }
396
+
397
+ /** Wires the panel chrome + registers the open-from-model-picker callback.
398
+ * Call once at chat controller init, same lifecycle as initMemoryPanel().
399
+ * The model picker's "Browse models…" button is re-rendered via innerHTML
400
+ * on every popover open (model-picker.ts's refreshModelPop()), so it can't
401
+ * hold a handler bound once here — model-picker.ts calls
402
+ * openHubFromModelPicker() (shell.ts's registered-callback pattern)
403
+ * instead of a direct element lookup. */
404
+ export function initHubPanel(): void {
405
+ panelTrap = trapFocus($("hub-overlay"), isHubPanelOpen);
406
+ setHubPanelClose(closeHubPanel); // registers with shell.ts's global Escape sweep
407
+ setOpenHubFromModelPicker(() => { openHubPanel(); });
408
+
409
+ const closeBtn = $("hub-close") as HTMLButtonElement | null;
410
+ if (closeBtn) closeBtn.onclick = closeHubPanel;
411
+ const overlay = $("hub-overlay");
412
+ if (overlay) overlay.addEventListener("click", (e) => { if (e.target === overlay) closeHubPanel(); });
413
+
414
+ const search = $("hub-search-input") as HTMLInputElement | null;
415
+ if (search) {
416
+ search.addEventListener("input", () => {
417
+ clearTimeout(searchDebounce);
418
+ const q = search.value.trim();
419
+ searchDebounce = setTimeout(() => runSearch(q), 300);
420
+ });
421
+ }
422
+ }
423
+
424
+ // Exposed for tests that need to reset module-level state between cases.
425
+ export function _resetHubStateForTests(): void {
426
+ inFlightDownloads = new Set();
427
+ stopDownloadPolling();
428
+ }
@@ -0,0 +1,98 @@
1
+ // GENERATED-ADJACENT source module — part of the src/web/src/* split (plan
2
+ // §7/§9 Phase 2). Built by scripts/build-web.ts into src/web/app.js, which
3
+ // server.ts serves at GET /assets/app.js and app.html loads via
4
+ // <script defer src="/assets/app.js"></script>.
5
+ //
6
+ // Entrypoint: imports and initializes every module in the EXACT order the
7
+ // original monolithic inline <script> in app.html ran its top-level
8
+ // statements. This ordering is load-bearing — see the design doc
9
+ // (docs/design/web-chat-redesign.md §7) and the original file's own
10
+ // section comments for why (controllers object populated before router()
11
+ // can dispatch to it; updateTabFades() needs to run once at parse time so
12
+ // a tab row that's already overflowing on load gets its fade mask
13
+ // immediately, not just after the first scroll/resize event).
14
+
15
+ import {
16
+ controllers, initDeveloperToggle, initDrawer, initGlobalKeydown, initHfSettings,
17
+ initRouter, initRoutesProbe, initServiceWorker, initShortcutSheet, initTheme, pollIdentity, router,
18
+ } from "./shell";
19
+ import { createChatController } from "./chat";
20
+ import { createQuantizeController } from "./quantize";
21
+ import { createFinetuneController } from "./finetune";
22
+ import { createDatasetController } from "./dataset";
23
+ import { createStatusController } from "./status";
24
+ import { initModelPicker } from "./model-picker";
25
+ import { initHubPanel } from "./hub";
26
+ import { initPalette } from "./palette";
27
+
28
+ // — Hugging Face nav gear + push-to-hub modal (original: an IIFE right
29
+ // after mdToHtml/markdown helpers were declared) —
30
+ initHfSettings();
31
+
32
+ // — Theme: auto/dark/light, prefers-color-scheme —
33
+ initTheme();
34
+
35
+ // — PWA service worker (plan §9 Phase 3): shell-only cache-first, guarded
36
+ // to secure contexts / localhost. Registration is fire-and-forget and
37
+ // never blocks boot —
38
+ initServiceWorker();
39
+
40
+ // — Keyboard shortcut sheet (Cmd/Ctrl+/) —
41
+ initShortcutSheet();
42
+
43
+ // — Mobile drawer (chat sidebar slide-over) —
44
+ initDrawer();
45
+
46
+ // — Model picker (plan §5.6/§9 Phase 2): #nav-model click -> /library popover —
47
+ initModelPicker();
48
+
49
+ // — Model Hub (plan §9 Phase 3): panel chrome + the model picker's "Browse
50
+ // models…" entry. Registers its open callback before initModelPicker's
51
+ // popover is ever opened, so the first click already has a live target —
52
+ // order here doesn't actually matter (both are registered-callback
53
+ // indirections, not direct DOM lookups), but this keeps the two model-
54
+ // surface inits visually adjacent in the boot sequence. —
55
+ initHubPanel();
56
+
57
+ // — Command palette (plan §9 Phase 3): Cmd/Ctrl+K, registers its
58
+ // open/close/isOpen callbacks (shell.ts's registered-callback pattern)
59
+ // before initGlobalKeydown()'s binding below can ever fire —
60
+ initPalette();
61
+
62
+ // — Global Escape/shortcut keydown sweep (closeTopOverlay + shortcuts) —
63
+ initGlobalKeydown();
64
+
65
+ // — Router: hashchange listener + tab-fade scroll/resize listeners, and
66
+ // run updateTabFades() once immediately (original ran it at parse time,
67
+ // not just on first scroll/resize) —
68
+ initRouter();
69
+
70
+ // — Developer toggle (plan §8/§9 Phase 2): apply saved/first-run state to
71
+ // the tab row before router() below reads it for the deep-link check —
72
+ initDeveloperToggle();
73
+
74
+ // — Controller registration, in the original declaration order: chat,
75
+ // quantize, finetune, dataset, status. Each controller's own init() is
76
+ // still lazy (invoked by router() on first visit to that route) — only
77
+ // the outer factory call (equivalent to the original IIFE body running)
78
+ // happens here, matching the original's controllers.chat = (() => {...})()
79
+ // eager-closure-body / lazy-init() split exactly. —
80
+ controllers.chat = createChatController();
81
+ controllers.quantize = createQuantizeController();
82
+ controllers.finetune = createFinetuneController();
83
+ controllers.dataset = createDatasetController();
84
+ controllers.status = createStatusController();
85
+
86
+ /* ════════════════════════════════════════════════════════════════════
87
+ BOOT
88
+ ════════════════════════════════════════════════════════════════════ */
89
+ if (!location.hash) location.replace("#/chat");
90
+ router();
91
+ pollIdentity();
92
+ setInterval(pollIdentity, 4000);
93
+
94
+ // — Routes tab feature-detection (web-ui-pass-plan.md #17): probe /dag once;
95
+ // hides the tab (and bounces off #/routes if already there) on 404. Runs
96
+ // after the initial router() so a direct deep link to #/routes has
97
+ // already rendered its section before this decides whether to keep it. —
98
+ initRoutesProbe();
Binary file