File size: 45,183 Bytes
cef9371
a8f5a2f
 
d2880ff
0e56f1a
fbefec9
a8f5a2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff322b9
 
 
 
 
 
 
a8f5a2f
 
 
 
 
 
 
 
 
d2880ff
7b2f9d8
 
d2880ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46d9e41
 
 
 
d2880ff
 
40a5fbc
d2880ff
 
 
ff322b9
d2880ff
 
ff322b9
 
 
d2880ff
 
 
 
 
 
 
 
 
 
 
 
 
7b2f9d8
d2880ff
 
a8f5a2f
 
 
 
 
 
 
 
fbefec9
 
 
 
 
d83db09
fbefec9
 
d83db09
 
 
a8f5a2f
7b2f9d8
a8f5a2f
 
 
 
 
 
 
 
 
6b1f716
 
 
 
 
d2880ff
 
a8f5a2f
d2880ff
a8f5a2f
0d56bc3
 
 
 
 
 
 
 
 
 
 
92ed407
 
 
 
 
 
d2880ff
a8f5a2f
 
0d56bc3
d83db09
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d56bc3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8f5a2f
 
 
 
 
 
d2880ff
a8f5a2f
 
 
 
cef9371
 
 
 
 
 
 
a8f5a2f
 
 
d2880ff
 
cef9371
 
d2880ff
a8f5a2f
 
 
d2880ff
0d56bc3
 
a8f5a2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d2880ff
a8f5a2f
 
 
 
 
 
0d56bc3
a8f5a2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d2880ff
0d56bc3
 
d2880ff
 
 
a8f5a2f
 
 
 
 
 
 
 
 
 
 
7b2f9d8
 
 
a8f5a2f
 
 
 
 
 
 
cef9371
a8f5a2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d2880ff
a8f5a2f
 
 
 
 
 
 
 
 
 
 
f4e16d6
a8f5a2f
 
 
 
 
 
 
 
 
 
 
 
 
 
f4e16d6
d2880ff
 
f4e16d6
 
 
 
 
 
 
 
a8f5a2f
 
 
f4e16d6
 
7b2f9d8
 
 
 
 
d2880ff
 
 
 
7b2f9d8
d2880ff
 
 
 
 
 
 
 
 
7b2f9d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d56bc3
7b2f9d8
0d56bc3
7b2f9d8
 
 
 
 
 
 
 
 
 
 
 
 
 
d2880ff
7b2f9d8
d2880ff
7b2f9d8
 
 
 
 
 
 
d2880ff
7b2f9d8
cef9371
d2880ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b2f9d8
 
 
 
 
d2880ff
7b2f9d8
 
 
 
 
 
0e56f1a
 
d2880ff
 
f4e16d6
 
a8f5a2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b2f9d8
d2880ff
 
7b2f9d8
a8f5a2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d2880ff
40a5fbc
d2880ff
40a5fbc
a8f5a2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d2880ff
a8f5a2f
 
 
 
ff322b9
 
 
 
 
a8f5a2f
 
 
 
 
 
 
ff322b9
 
 
 
 
 
 
a8f5a2f
 
 
 
d2880ff
 
 
 
0e56f1a
d2880ff
 
 
cef9371
 
 
 
7b2f9d8
d2880ff
 
a8f5a2f
 
 
 
 
 
d2880ff
a8f5a2f
 
 
 
 
92ed407
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8f5a2f
 
 
 
 
 
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
import { DEFAULTS, MODEL_DEVICE, APP_VERSION, LOCAL_MODELS, findModel, setShaderF16, effectiveModel, modelRunsHere } from "./config.js";
import * as setup from "./setup.js";
import { LLM } from "./llm.js";
import { RemoteLLM, findPreset, loadApiKey, migrateLegacyKey } from "./remote-llm.js";
import { createModelManager, avatarTile } from "./model-manager.js";
import { freshAccessToken, embedded, standaloneUrl } from "./hf-auth.js";
import { VM } from "./vm.js";
import { Agent } from "./agent.js";
import { renderMarkdown } from "./markdown.js";
import { FileBrowser } from "./files.js";

// ---------- helpers ----------
const $ = (s, el = document) => el.querySelector(s);
const h = (tag, attrs = {}, ...kids) => {
  const el = document.createElement(tag);
  for (const [k, v] of Object.entries(attrs)) {
    if (k === "class") el.className = v;
    else if (k.startsWith("on")) el.addEventListener(k.slice(2), v);
    else if (v !== false && v != null) el.setAttribute(k, v === true ? "" : v);
  }
  for (const kid of kids.flat()) if (kid != null) el.append(kid);
  return el;
};
const SVG_NS = "http://www.w3.org/2000/svg";
const icon = (name, cls) => {
  const s = document.createElementNS(SVG_NS, "svg");
  if (cls) s.setAttribute("class", cls);
  const u = document.createElementNS(SVG_NS, "use");
  u.setAttribute("href", "#i-" + name);
  s.append(u);
  return s;
};
const fmtBytes = (n) => (n >= 1e9 ? (n / 1e9).toFixed(2) + " GB" : n >= 1e6 ? Math.round(n / 1e6) + " MB" : Math.round(n / 1e3) + " KB");
const fmtSecs = (ms) => (ms < 1000 ? `${Math.max(0.1, ms / 1000).toFixed(1)}s` : ms < 60000 ? `${(ms / 1000).toFixed(1)}s` : `${Math.floor(ms / 60000)}m ${Math.round((ms % 60000) / 1000)}s`);
const plural = (n, w) => `${n} ${w}${n === 1 ? "" : "s"}`;

// ---------- settings ----------
const settings = { ...DEFAULTS };
try { Object.assign(settings, JSON.parse(localStorage.getItem("lwa-settings") || "{}")); } catch {}
// Older versions saved the active budget (14000) with everything else; the per-backend
// values replace it, so drop it to let the new defaults apply.
delete settings.contextBudgetTokens;
const saveSettings = () => {
  const { contextBudgetTokens, ...persist } = settings; // derived, never stored
  try { localStorage.setItem("lwa-settings", JSON.stringify(persist)); } catch {}
};

// ---------- status ----------
function status(name, state, text) {
  const el = $(`[data-status="${name}"]`);
  el.dataset.state = state;
  $(".status-text", el).textContent = text;
  el.title = text;
}

// ---------- language model: none, local (WebGPU) or one of the saved API models ----------
const isMobile = () => !!navigator.userAgentData?.mobile || /Android|iPhone|iPad|Mobile/i.test(navigator.userAgent);

// Before the Model Manager (v0.5 and older) there was one API model and one local choice.
(function migrateModelSettings() {
  if (Array.isArray(settings.apiModels) && "activeModel" in settings) return;
  let hadSettings = false;
  try { hadSettings = localStorage.getItem("lwa-settings") != null; } catch {}
  settings.apiModels = Array.isArray(settings.apiModels) ? settings.apiModels : [];
  if (settings.api?.baseUrl && settings.api?.model && !settings.apiModels.length) {
    settings.apiModels.push({ id: "api-1", name: settings.api.model, preset: settings.api.preset ?? "custom", baseUrl: settings.api.baseUrl, model: settings.api.model });
    migrateLegacyKey("api-1");
  }
  if (!("activeModel" in settings)) {
    settings.activeModel = settings.backend === "api" && settings.apiModels.length ? { kind: "api", id: settings.apiModels[0].id }
      : hadSettings ? { kind: "local", id: findModel(settings.localModel).id } // they had a local model installed
      : null;
  }
  delete settings.backend; delete settings.api; delete settings.localModel;
  saveSettings();
})();

const activeKind = () => settings.activeModel?.kind ?? null;
const activeLocal = () => (activeKind() === "local" ? LOCAL_MODELS.find((m) => m.id === settings.activeModel.id) ?? null : null);
const activeApi = () => (activeKind() === "api" ? settings.apiModels.find((a) => a.id === settings.activeModel.id) ?? null : null);
const usingApi = () => !!activeApi();
const isActive = (sel) => !!sel && settings.activeModel?.kind === sel.kind && settings.activeModel?.id === sel.id;
const apiConfigFor = (a) => a.auth === "hf-oauth"
  // Signed in with Hugging Face: the session's token, refreshed when it is about to expire.
  ? { baseUrl: a.baseUrl, model: a.model, headers: findPreset(a.preset).headers, getKey: () => freshAccessToken(a.id) }
  : { baseUrl: a.baseUrl, model: a.model, key: loadApiKey(a.id), headers: findPreset(a.preset).headers };
const apiHost = () => { try { return new URL(activeApi().baseUrl).host; } catch { return activeApi()?.baseUrl ?? ""; } };
const activeLabel = () => activeApi()?.name ?? activeLocal()?.label ?? "No model";
const smallestModel = () => LOCAL_MODELS.reduce((a, b) => (b.bytes < a.bytes ? b : a));
if (settings.activeModel && !activeLocal() && !activeApi()) settings.activeModel = null; // points at something deleted

// The active context budget follows the model.
const syncContextBudget = () => {
  settings.contextBudgetTokens = usingApi() ? settings.contextApiTokens
    : Math.min(settings.contextLocalTokens, (activeLocal() ?? LOCAL_MODELS[0]).contextMax);
};
syncContextBudget();

// Stand-in while no model is chosen.
const noModel = () => ({
  none: true, ready: false, async load() {}, stop() {}, resetCache() {}, dispose() {},
  generate() { return Promise.reject(new Error("No model selected. Open the Model Manager to choose one.")); },
});
function createLlm() {
  const a = activeApi();
  if (a) return new RemoteLLM(apiConfigFor(a));
  const m = activeLocal();
  return m ? new LLM(m) : noModel();
}

let llm = createLlm();
let modelError = null; // why the local model failed to load, if it did
let gpuCheck = null; // result of the WebGPU check, for the Model Manager
let started = false;
const vm = new VM();
let agent = null;
let diskManifest = null;
let vmReady = false;
let files = null;

// ---------- boot ----------
async function init() {
  // Inside the Space page on huggingface.co (an iframe) the app gets separate, partitioned
  // storage and sign-in can't work, so send people to its own page instead of starting.
  if (embedded()) {
    $("#embed-gate-link").href = standaloneUrl();
    $("#embed-gate").hidden = false;
    wipeEmbeddedStorage();
    return;
  }
  // Mark this browser's first-party storage, so an embedded copy can tell whether it sees
  // the same storage (and must not wipe it) or its own partitioned copy.
  try { localStorage.setItem(FIRST_PARTY_MARK, "1"); } catch {}
  $("#version").textContent = "v" + APP_VERSION;
  setBackendLabels();
  syncToggles();

  const checks = await environmentChecks();
  renderChecks(checks);
  if (!checks.isolated.ok || !checks.sw.ok) return showSetup(false);

  try { await setup.ensureServiceWorker(); }
  catch (err) { checks.sw = { ok: false, text: err.message }; renderChecks(checks); return showSetup(false); }

  // Free the space of models that were dropped from the catalog (e.g. Qwen3 4B in v0.7).
  setup.removeOrphanedModels(LOCAL_MODELS.map((m) => m.repo))
    .then((freed) => { if (freed > 1e6) console.info(`Removed ${fmtBytes(freed)} of files from models no longer in the list.`); })
    .catch((err) => console.warn("cleanup:", err));

  // Setup installs only Linux; models are added later in the Model Manager.
  const [cx, disk] = await Promise.all([setup.cheerpxStatus(), setup.installedDisk()]);
  diskManifest = disk;
  const installed = { cx: cx.ready, disk: !!disk };
  for (const k of Object.keys(installed)) if (installed[k]) setRow(k, 1, "Installed");
  // "Update now" on the new-Linux callout reloads into this: setup screen, download the
  // new image, drop the old machine's storage, boot.
  const updating = sessionStorage.getItem(UPDATE_FLAG);
  if (updating) {
    sessionStorage.removeItem(UPDATE_FLAG);
    setRow("disk", 0, "Update available");
    showSetup(true);
    $("#install").textContent = "Update Linux";
    $("#setup-note").textContent = "Downloading the new Linux machine. Keep this tab open.";
    return install({ replacing: disk?.id });
  }
  const openModels = new URLSearchParams(location.search).get("open") === "models";
  if (installed.cx && installed.disk) {
    updateOfflineStatus();
    if (openModels) models.open();
    start().then(checkForNewImage);
  }
  else { status("offline", "warn", "Not installed"); showSetup(true); }
}

const UPDATE_FLAG = "lwa-update-linux";
const FIRST_PARTY_MARK = "lwa-first-party";

/**
 * In the Space embed, deletes everything this app stored there (models, Linux disk and
 * files, settings, keys, service worker) so it only lives on the dedicated page. Browsers
 * partition an iframe's storage by the top-level site, so this is the embed's own copy;
 * if the dedicated page's marker is visible, storage is shared and nothing is deleted.
 */
async function wipeEmbeddedStorage() {
  const note = $("#embed-gate-clean");
  let shared = false;
  try { shared = localStorage.getItem(FIRST_PARTY_MARK) === "1"; } catch {}
  if (shared) { note.textContent = ""; return; } // not partitioned: this is the real app's data
  const before = (await navigator.storage?.estimate?.().catch(() => null))?.usage ?? 0;
  note.textContent = "Clearing data stored by this embedded view…";
  const tasks = [];
  tasks.push((async () => {
    for (const r of (await navigator.serviceWorker?.getRegistrations?.()) ?? []) await r.unregister();
  })());
  tasks.push((async () => { for (const k of await caches.keys()) await caches.delete(k); })());
  tasks.push((async () => {
    for (const db of (await indexedDB.databases?.()) ?? []) {
      if (!db.name) continue;
      await new Promise((resolve) => {
        const req = indexedDB.deleteDatabase(db.name);
        req.onsuccess = req.onerror = req.onblocked = () => resolve();
      });
    }
  })());
  tasks.push((async () => {
    const root = await navigator.storage?.getDirectory?.();
    if (root) for await (const name of root.keys()) await root.removeEntry(name, { recursive: true });
  })());
  await Promise.allSettled(tasks);
  try { localStorage.clear(); sessionStorage.clear(); } catch {}
  // An unregistered service worker keeps controlling open pages until they close and can
  // re-cache files they load, so sweep the caches once more shortly after.
  setTimeout(async () => { try { for (const k of await caches.keys()) await caches.delete(k); } catch {} }, 3000);
  const after = (await navigator.storage?.estimate?.().catch(() => null))?.usage ?? 0;
  const freed = Math.max(0, before - after);
  note.textContent = freed > 1e6 ? `Cleared ${fmtBytes(freed)} this embedded view had stored. Your data on LocalWebAgent's own page is untouched.` : "";
}

/** After boot: if the server has a newer Linux image than the installed one, offer it. */
async function checkForNewImage() {
  if (!navigator.onLine || !diskManifest) return;
  let remote;
  try { remote = await setup.fetchRemoteManifest(); } catch { return; }
  if (!remote?.id || remote.id === diskManifest.id) return;
  const el = callout("info", "A new Linux machine is available",
    `Debian 12 with Python 3.11 (numpy, pandas, matplotlib, scipy), Node 18 and TypeScript, PHP, Lua, CMake, ImageMagick and more than 450 packages. Updating downloads ${fmtBytes(remote.downloadBytes)} and starts a fresh machine: files you created in the current one will be gone, so download anything you want to keep from the Files view first.`,
    [
      h("button", { class: "btn primary small", type: "button", onclick: () => {
        if (agent?.running) return alert("Stop the agent before updating.");
        if (!confirm("Replace the Linux machine with the new version? Files you created in the current machine will be deleted.")) return;
        sessionStorage.setItem(UPDATE_FLAG, "1");
        location.reload();
      } }, "Update now"),
      h("button", { class: "btn small", type: "button", onclick: () => el.remove() }, "Not now"),
    ], null, "update");
}

async function environmentChecks() {
  const c = {};
  c.isolated = crossOriginIsolated
    ? { ok: true, text: "Cross-origin isolation" }
    : { ok: false, text: window.top !== window ? "The embedded view can't run the VM. Open the app in its own tab." : "Cross-origin isolation is off (COOP/COEP headers missing)" };
  c.sw = "serviceWorker" in navigator ? { ok: true, text: "Offline storage" } : { ok: false, text: "Offline storage unavailable (private window?)" };
  if (MODEL_DEVICE !== "webgpu") c.gpu = { ok: true, warn: true, text: `Model runs on ${MODEL_DEVICE} (slow; for testing)` };
  else if (!navigator.gpu) c.gpu = { ok: false, text: "WebGPU unavailable. Use desktop Chrome or Edge." };
  else {
    try {
      const a = await navigator.gpu.requestAdapter({ powerPreference: "high-performance" });
      if (!a) c.gpu = { ok: false, text: /Linux/.test(navigator.userAgent) ? "No WebGPU adapter found (on Linux, Chrome may need chrome://flags/#enable-vulkan and #enable-unsafe-webgpu)" : "No WebGPU adapter found" };
      else if (!a.features.has("shader-f16")) {
        // Common with Chrome on Linux (Vulkan), even on GPUs that have f16 on Windows.
        // Local models then use their q4 builds (4-bit weights, fp32 math).
        setShaderF16(false);
        c.gpu = { ok: true, noF16: true, text: "WebGPU without f16 shaders" + (a.info?.vendor ? ` · ${a.info.vendor}` : "") };
      }
      else c.gpu = { ok: true, text: "WebGPU with f16 shaders" + (a.info?.vendor ? ` · ${a.info.vendor}` : "") };
    } catch (e) { c.gpu = { ok: false, text: "WebGPU error: " + e.message }; }
  }
  // WebGPU only matters for local models, which are optional: report it, don't block setup.
  gpuCheck = c.gpu;
  c.gpu = c.gpu.noF16 ? { ok: true, warn: true, text: c.gpu.text + ": local models use their larger q4 builds" }
    : c.gpu.ok ? { ok: true, text: c.gpu.text + ": local models can run" }
    : { ok: true, warn: true, text: `${c.gpu.text}. Local models won't run here; API models will.` };
  const est = await setup.storageEstimate();
  const free = est ? est.quota - est.usage : null;
  c.storage = free == null ? { ok: true, text: "Storage space unknown" }
    : free > 3e9 ? { ok: true, text: `${fmtBytes(free)} of browser storage available` }
    : free > 0.8e9 ? { ok: true, warn: true, text: `${fmtBytes(free)} of browser storage available: enough for Linux, maybe not for local models (0.5 to 3 GB each)` }
    : { ok: false, text: `Only ${fmtBytes(free)} of browser storage available; Linux needs about 700 MB` };
  return c;
}

function renderChecks(c) {
  $("#checks").replaceChildren(...Object.values(c).map((x) => {
    const cls = !x.ok ? "bad" : x.warn ? "warn" : "ok";
    return h("li", { class: cls }, icon(cls === "ok" ? "check" : "x"), h("span", {}, x.text));
  }));
  if (!c.isolated.ok && window.top !== window) {
    $("#checks").append(h("li", {}, h("a", { href: location.href, target: "_blank", rel: "noopener", class: "btn small" }, "Open in a new tab")));
  }
}

function setRow(k, frac, text) {
  const row = $(`[data-row="${k}"]`);
  row.dataset.state = frac >= 1 ? "done" : frac > 0 ? "busy" : "todo";
  $("progress", row).value = frac;
  $(".row-state", row).textContent = text;
}

function showSetup(canInstall) {
  $("#setup").hidden = false;
  $("#mobile-banner").hidden = !isMobile();
  const btn = $("#install");
  btn.disabled = !canInstall || !navigator.onLine;
  if (!navigator.onLine) $("#setup-note").textContent = "You're offline. Connect once to install; after that it works without internet.";
  btn.onclick = install;
}

async function install({ replacing } = {}) {
  const btn = $("#install");
  const note = $("#setup-note");
  btn.disabled = true;
  btn.textContent = "Installing";
  note.className = "note";
  note.textContent = "Keep this tab open. Interrupted downloads resume where they left off.";
  await setup.requestPersistence();
  try {
    const cxTask = setup.cheerpxStatus()
      .then((s) => s.ready || setup.downloadCheerpX((f) => setRow("cx", f, Math.round(f * 100) + "%")))
      .then(() => setRow("cx", 1, "Installed"));
    const diskTask = (async () => {
      const remote = await setup.fetchRemoteManifest();
      if (diskManifest?.id === remote.id) return setRow("disk", 1, "Installed");
      $("#disk-size").textContent = fmtBytes(remote.downloadBytes);
      diskManifest = await setup.downloadDisk((d, t) => setRow("disk", d / t, `${Math.round((d / t) * 100)}%`));
      setRow("disk", 1, "Installed");
    })();
    await Promise.all([cxTask, diskTask]);
    // An update replaces the machine: its writable layer belongs to the old image.
    if (replacing && replacing !== diskManifest.id) await setup.resetVmStorage("lwa-overlay-" + replacing).catch(() => {});
    updateOfflineStatus();
    await start();
    if (!settings.activeModel) models.open(); // next step: pick a model
  } catch (err) {
    console.error(err);
    note.className = "note error";
    note.textContent = "Installation failed: " + err.message;
    btn.disabled = false;
    btn.textContent = "Retry";
  }
}

// Aggregates transformers.js per-file progress into one number.
function loadModel(onProgress) {
  if (llm.remote) {
    return llm.load().then(() => status("model", "ok", "API ready"), (err) => { status("model", "bad", "API not set up"); throw err; });
  }
  const files = new Map();
  llm.onProgress = (p) => {
    if (!p.file) return;
    const prev = files.get(p.file);
    files.set(p.file, { loaded: p.status === "done" ? (prev?.total ?? p.loaded) : p.loaded, total: p.total || prev?.total || 0 });
    let loaded = 0, total = 0;
    for (const f of files.values()) { loaded += f.loaded; total += f.total; }
    total = Math.max(total, activeLocal() ? effectiveModel(activeLocal()).bytes : 0);
    const frac = Math.min(0.99, loaded / total);
    onProgress?.(frac, `${fmtBytes(loaded)} of ${fmtBytes(total)}`);
    status("model", "busy", `Loading ${Math.round(frac * 100)}%`);
  };
  llm.onStatus = (t) => {
    const warm = t.includes("Warming");
    status("model", "busy", warm ? "Compiling GPU kernels" : "Loading");
    onProgress?.(0.99, warm ? "Compiling GPU kernels" : "Loading");
  };
  llm.onGpu = (g) => { if (g.vendor) $("#gpu-name").title = [g.vendor, g.architecture, g.description].filter(Boolean).join(" · "); };
  status("model", "busy", "Loading");
  return llm.load().then(
    () => status("model", "ok", "Model ready"),
    (err) => { status("model", "bad", "Model failed"); throw err; },
  );
}

// Only one tab may run the VM: two VMs writing the same saved disk corrupt it.
function acquireVmLock() {
  if (!navigator.locks) return Promise.resolve(true);
  return new Promise((resolve) => {
    navigator.locks.request("lwa-vm", { ifAvailable: true }, (lock) => {
      resolve(!!lock);
      return lock ? new Promise(() => {}) : null; // held for the page's lifetime
    });
  });
}

async function start() {
  started = true;
  $("#setup").hidden = true;
  if (!(await acquireVmLock())) {
    status("vm", "bad", "Open in another tab");
    addNotice("LocalWebAgent is already running in another tab. Close it and reload this one; two copies at once would damage the machine's files.", "warn");
    return;
  }
  vm.mountTerminal($("#terminal"));
  vm.onActivity = (busy) => { $("#cpu-led").dataset.on = busy ? "1" : "0"; };
  agent = new Agent({ llm, vm, settings, ui: chatUI });
  setComposerEnabled();

  const bootVm = async () => {
    status("vm", "busy", "Booting");
    try {
      diskManifest ??= await setup.installedDisk();
      await vm.boot({ diskId: diskManifest.id, onStatus: (t) => t !== "Ready" && status("vm", "busy", t) });
      vmReady = true;
      status("vm", "ok", "Linux running");
      files = new FileBrowser({ vm, root: $("#files") });
      if (sideView === "files") files.navigate("/home/user");
    } catch (err) {
      console.error(err);
      status("vm", "bad", "Linux failed");
      vm.term?.writeln("\r\n\x1b[31mFailed to start Linux: " + err.message + "\x1b[0m");
    }
    setComposerEnabled();
  };
  if (isMobile() && activeLocal() && !llm.ready && !modelError) showMobileWarning();
  if (memoryConstrained() && activeLocal()) {
    // Upload the weights to the GPU before Linux takes its share of memory: on phones
    // the two together at peak are what makes the browser kill the GPU process.
    status("vm", "busy", "Waiting for the model");
    await loadModelOnce();
    await bootVm();
  } else {
    await Promise.all([bootVm(), loadModelOnce()]);
  }
  setComposerEnabled();
}

// Phones, tablets and machines reporting under 8 GB of RAM (Chrome caps deviceMemory at 8).
function memoryConstrained() {
  return isMobile() || (navigator.deviceMemory ?? 8) < 8;
}

// Loads the current backend unless it is ready or already failed. Never rejects: a
// local-model failure is shown as a callout with the API option.
async function loadModelOnce() {
  if (llm.ready) return;
  if (llm.none) { status("model", "warn", "No model"); showNoModel(); setComposerEnabled(); return; }
  if (modelError) { showModelFailure(modelError); return; }
  const mine = llm;
  const m = activeLocal();
  // Downloads happen only in the Model Manager, never implicitly here.
  if (m && !(await setup.modelStatus(m)).ready) {
    if (mine !== llm) return;
    status("model", "warn", "Not downloaded");
    showNoModel(`${m.label} isn't downloaded in this browser. `);
    setComposerEnabled();
    return;
  }
  return loadModel().catch((err) => {
    if (mine !== llm) return; // replaced (e.g. switched to an API model) while loading
    console.error(err);
    if (mine.remote) addNotice("The API model isn't set up: " + err.message, "error");
    else { modelError = err; showModelFailure(err); }
  }).finally(setComposerEnabled);
}

function friendlyModelError(err) {
  const m = String(err?.message ?? err);
  if (/Instance reference|device (was |is )?lost|DeviceLost|out of memory|OOM|allocat|Failed to create a WebGPU|OrtRun|createBuffer|mapAsync|Array buffer/i.test(m)) {
    return "Your device ran out of graphics memory while loading the model. This is common on phones and on computers with little RAM.";
  }
  if (/WebGPU is not available|shader-f16|No WebGPU|WebGPU/i.test(m)) return "This browser can't run the local model because it lacks the WebGPU support the model needs.";
  if (/fetch|network|download|Failed to load|Incomplete/i.test(m)) return "The model files couldn't be downloaded. Check your internet connection.";
  return "The local model hit an error while loading.";
}

function callout(kind, title, text, actions, details, tag = "model") {
  $("#empty")?.remove();
  const el = h("div", { class: `callout ${kind}`, "data-callout": tag },
    h("div", { class: "callout-title" }, icon("alert"), h("span", {}, title)),
    h("p", {}, text),
    h("div", { class: "callout-actions" }, actions),
    details ? h("details", { class: "callout-details" }, h("summary", {}, "Technical details"), h("pre", {}, details)) : null);
  thread().append(el);
  scrollChat(true);
  return el;
}
const clearModelCallouts = () => document.querySelectorAll('[data-callout="model"]').forEach((el) => el.remove());

function showModelFailure(err) {
  status("model", "bad", "Model failed");
  clearModelCallouts();
  const el = callout("error", "The model couldn't load",
    `${friendlyModelError(err)} Linux is still running on this device. In the Model Manager you can pick a smaller model${activeLocal() !== smallestModel() ? ` (${smallestModel().label} is the smallest)` : ""} or add an API model, and the agent will keep using this machine.`,
    [
      h("button", { class: "btn primary small", type: "button", onclick: () => models.open() }, "Open Model Manager"),
      h("button", { class: "btn small", type: "button", onclick: () => { el.remove(); retryLocalModel(); } }, "Try again"),
    ],
    String(err?.message ?? err));
  setComposerEnabled();
}

function showMobileWarning() {
  const m = activeLocal();
  callout("warn", "You're on a phone or tablet",
    `${m.label} needs about ${fmtBytes(effectiveModel(m).bytes)} of graphics memory, which most phones can't give a browser tab, so it may fail to load. Trying anyway. In the Model Manager you can switch to an API model (only the model moves to the provider, Linux keeps running here)${m !== smallestModel() ? ` or the smaller ${smallestModel().label}` : ""}.`,
    [h("button", { class: "btn primary small", type: "button", onclick: () => models.open() }, "Open Model Manager")]);
}

function showNoModel(prefix = "") {
  clearModelCallouts();
  callout("info", "Choose a language model",
    `${prefix}Linux is ready. Open the Model Manager to download a model that runs on your GPU, or to add an API model (OpenAI, Anthropic, Gemini, OpenRouter, Hugging Face and more).`,
    [h("button", { class: "btn primary small", type: "button", onclick: () => models.open() }, "Open Model Manager")]);
}

function updateOfflineStatus() {
  if (usingApi()) status("offline", "warn", "Model via API");
  else status("offline", "ok", "Available offline");
}

/** Switches the language model (null = none), unloading the previous one. */
async function activateModel(sel) {
  if (agent?.running) throw new Error("Stop the agent before switching models.");
  const old = llm;
  settings.activeModel = sel;
  saveSettings();
  llm = createLlm();
  old.dispose?.(); // frees a local model's GPU memory
  modelError = null;
  if (agent) agent.llm = llm;
  clearModelCallouts();
  syncContextBudget();
  setBackendLabels();
  syncToggles();
  updateOfflineStatus();
  setComposerEnabled();
  if (!started) return;
  await loadModelOnce();
  if (llm.ready) addNotice(usingApi() ? `Now using ${activeLabel()} through ${apiHost()}. Linux still runs on this device.` : `Now using ${activeLabel()} on this device.`);
}

function retryLocalModel() {
  modelError = null;
  llm.dispose?.();
  llm = createLlm();
  if (agent) agent.llm = llm;
  setComposerEnabled();
  loadModelOnce();
}

function setBackendLabels() {
  const av = activeApi() ? findPreset(activeApi().preset).avatar : activeLocal()?.avatar;
  $("#model-name").replaceChildren(...(settings.activeModel ? [avatarTile(av, "xs", icon("plus"))] : []), h("span", {}, activeLabel()));
  $("#gpu-name").textContent = usingApi() ? "API" : activeLocal() ? (MODEL_DEVICE === "webgpu" ? "WebGPU" : MODEL_DEVICE) : "";
  $("#gpu-name").hidden = !settings.activeModel;
}

// ---------- conversation rendering ----------
const thread = () => $("#messages");
const scroller = () => $("#scroller");
function scrollChat(force) {
  const el = scroller();
  if (force || el.scrollHeight - el.scrollTop - el.clientHeight < 140) el.scrollTop = el.scrollHeight;
}
function addNotice(text, kind = "") {
  $("#empty")?.remove();
  thread().append(h("div", { class: `notice center ${kind}` }, text));
  scrollChat(true);
}

let currentRun = null; // { el, t0, steps, genTokens, genMs }

const chatUI = {
  startTurn(step) {
    const stepEl = h("div", { class: "step" });
    const rTime = h("span", { class: "r-time" });
    const rLabel = h("span", { class: "r-label" }, "Reasoning");
    const reasoning = h("details", { class: "reasoning", hidden: true },
      h("summary", {}, icon("chevron"), rLabel, rTime), h("div", { class: "r-body" }));
    const body = h("div", { class: "md" });
    const statusText = h("span", {}, step === 1 ? "Reading the task" : "Reading the result");
    const live = h("div", { class: "run-status" }, h("span", { class: "spinner" }), statusText);
    stepEl.append(reasoning, body, live);
    currentRun.el.append(stepEl);
    scrollChat(true);

    let thinkStart = 0, thinkMs = 0, timer = null;
    const tick = () => { rTime.textContent = ` · ${fmtSecs(performance.now() - thinkStart)}`; };
    return {
      prefill(done, total) { statusText.textContent = `Reading ${total.toLocaleString()} tokens · ${Math.round((done / total) * 100)}%`; },
      update(p, final) {
        if (p.thinking) {
          if (!thinkStart) { thinkStart = performance.now(); timer = setInterval(tick, 200); }
          reasoning.hidden = false;
          $(".r-body", reasoning).textContent = p.thinking;
          if (p.thinkingDone && !thinkMs) {
            thinkMs = performance.now() - thinkStart;
            clearInterval(timer);
            rLabel.textContent = "Reasoned";
            rTime.textContent = ` for ${fmtSecs(thinkMs)}`;
          }
        }
        body.innerHTML = p.content ? renderMarkdown(p.content) : "";
        const preparing = p.calls.find((c) => !c.complete);
        statusText.textContent = p.thinking && !p.thinkingDone ? "Reasoning"
          : preparing ? `Preparing ${TOOL_VERB[preparing.name]?.toLowerCase() ?? preparing.name}`
          : p.calls.length ? "Running" : "Writing";
        if (final) {
          clearInterval(timer);
          if (thinkStart && !thinkMs) { rLabel.textContent = "Reasoned"; rTime.textContent = ` for ${fmtSecs(performance.now() - thinkStart)}`; }
          live.remove();
        }
        scrollChat();
      },
      note(text) { stepEl.append(h("div", { class: "notice" }, text)); scrollChat(); },
    };
  },

  onToolStart(call) {
    const a = call.arguments;
    const verb = TOOL_VERB[call.name] ?? call.name;
    const target = call.name === "run_command" ? firstLine(a.command ?? "") : a.path ?? "";
    const t0 = performance.now();
    const statusEl = h("span", { class: "t-status" }, "running");
    const timeEl = h("span", {});
    const head = h("button", { class: "tool-head", type: "button" },
      icon("chevron", "chev"), icon(TOOL_ICON[call.name] ?? "terminal"),
      h("span", { class: "tool-label" }, call.name === "run_command" ? null : h("span", { class: "verb" }, verb), target),
      h("span", { class: "tool-meta" }, timeEl, statusEl, h("span", { class: "dot" })));
    const bodyEl = h("div", { class: "tool-body" });
    if (call.name === "run_command" && (a.command ?? "").includes("\n")) bodyEl.append(h("pre", {}, a.command));
    if (call.name === "write_file") {
      const content = a.content ?? "";
      bodyEl.append(h("div", { class: "sub" }, `${plural(content.replace(/\n$/, "").split("\n").length, "line")}`), h("pre", {}, content));
    }
    const card = h("div", { class: "tool", "data-state": "running" }, head, bodyEl);
    head.addEventListener("click", () => card.classList.toggle("open"));
    card._t0 = t0; card._status = statusEl; card._time = timeEl; card._body = bodyEl; card._name = call.name;
    currentRun.el.lastElementChild.append(card);
    scrollChat();
    return card;
  },

  onToolEnd(card, r) {
    const state = r.declined ? "declined" : r.error ? "error" : r.timedOut ? "timeout" : r.exitCode === 0 ? "ok" : r.exitCode === null ? "unknown" : "fail";
    card.dataset.state = state;
    card._status.textContent = r.declined ? "skipped" : r.error ? "error" : r.timedOut ? "timed out" : r.exitCode === null ? "done" : `exit ${r.exitCode}`;
    card._time.textContent = fmtSecs(performance.now() - card._t0);
    const out = (r.error ? r.text : r.output ?? "").trim();
    if (card._name !== "write_file" && !r.declined) {
      const lines = out ? out.split("\n").length : 0;
      card._body.append(h("div", { class: "sub" }, out ? plural(lines, "line") + " of output" : "No output"));
      if (out) card._body.append(h("pre", {}, out.length > 20000 ? out.slice(0, 20000) + "\n…" : out));
      if (out && lines <= 10 && card._name === "run_command") card.classList.add("open");
    }
    if (state === "fail" || state === "error" || state === "timeout") card.classList.add("open");
    const written = card._name === "write_file" && state === "ok" ? / to (\/.*)$/m.exec(r.output ?? "")?.[1] : null;
    if (written) {
      const openBtn = h("button", { class: "tool-open", type: "button", title: "Open in the file viewer" }, icon("open"), "Open");
      openBtn.addEventListener("click", (e) => { e.stopPropagation(); openFile(written); });
      $(".tool-meta", card).prepend(openBtn);
      files?.noteChanged(written);
      if (sideView !== "files") $("#files-badge").hidden = false;
    } else if (card._name === "run_command" && sideView === "files") files?.refresh();
    scrollChat();
  },

  confirmTool(call, card) {
    card.classList.add("open");
    return new Promise((resolve) => {
      const bar = h("div", { class: "confirm" },
        h("span", {}, call.name === "write_file" ? "Write this file?" : "Run this command?"),
        h("button", { class: "btn small", type: "button", onclick: () => { bar.remove(); resolve(false); } }, "Skip"),
        h("button", { class: "btn small primary", type: "button", onclick: () => { bar.remove(); resolve(true); } }, "Run"));
      card.append(bar);
      scrollChat(true);
    });
  },

  onStats(s) {
    currentRun.steps++;
    currentRun.genTokens += s.genTokens;
    currentRun.genMs += s.genMs;
    const tps = s.genTokens / Math.max(0.001, s.genMs / 1000);
    status("model", "ok", `${tps.toFixed(0)} tok/s`);
    const used = s.promptTokens + s.genTokens;
    $("#ctx").textContent = `${used.toLocaleString()} / ${settings.contextBudgetTokens.toLocaleString()} tokens`;
  },
};

const TOOL_VERB = { run_command: "Run", write_file: "Write", read_file: "Read" };
const TOOL_ICON = { run_command: "terminal", write_file: "file-pen", read_file: "file" };
const firstLine = (s) => { const l = s.trim().split("\n"); return l[0] + (l.length > 1 ? " …" : ""); };

function setComposerEnabled() {
  const ready = llm.ready && vmReady;
  const running = !!agent?.running;
  $("#prompt").disabled = !ready;
  $("#send").hidden = running;
  $("#stop").hidden = !running;
  $("#send").disabled = !ready;
  $("#prompt").placeholder = ready ? "Describe a task for the agent"
    : llm.none ? "Choose a model in the Model Manager to start"
    : !llm.ready ? (modelError ? "No model loaded. Open the Model Manager or try again." : "Loading the model…")
    : "Starting Linux…";
}

async function send(text) {
  text = text.trim();
  if (!text || !agent || agent.running) return;
  $("#empty")?.remove();
  thread().append(h("div", { class: "msg user" }, text));
  currentRun = { el: h("div", { class: "msg agent" }), t0: performance.now(), steps: 0, genTokens: 0, genMs: 0 };
  thread().append(currentRun.el);
  scrollChat(true);
  $("#prompt").value = "";
  autoGrow();
  const run = currentRun;
  const p = agent.run(text);
  setComposerEnabled();
  try {
    await p;
  } catch (err) {
    console.error(err);
    run.el.querySelectorAll(".run-status").forEach((el) => el.remove());
    run.el.append(h("div", { class: "notice error" }, "Error: " + err.message));
  } finally {
    const tps = run.genTokens / Math.max(0.001, run.genMs / 1000);
    run.el.append(h("div", { class: "run-foot" },
      [plural(run.steps, "step"), fmtSecs(performance.now() - run.t0), run.genTokens ? `${tps.toFixed(0)} tok/s` : null].filter(Boolean).join("  ·  ")));
    setComposerEnabled();
    scrollChat();
    $("#prompt").focus();
  }
}

function autoGrow() {
  const t = $("#prompt");
  t.style.height = "auto";
  t.style.height = Math.min(220, t.scrollHeight) + "px";
}

function newConversation() {
  if (agent?.running) return;
  agent?.clear();
  $("#ctx").textContent = "";
  thread().replaceChildren();
  $("#prompt").focus();
}

// ---------- composer toggles ----------
function syncToggles() {
  const canThink = activeLocal()?.thinking ?? true;
  $("#tog-thinking").disabled = !canThink;
  $("#tog-thinking").title = canThink ? "Let the model reason before each step" : `${activeLocal().label} has no reasoning mode`;
  $("#tog-thinking").setAttribute("aria-pressed", String(!!settings.thinking && canThink));
  $("#tog-confirm").setAttribute("aria-pressed", String(!!settings.confirmCommands));
}
$("#tog-thinking").addEventListener("click", () => { settings.thinking = !settings.thinking; saveSettings(); syncToggles(); });
$("#tog-confirm").addEventListener("click", () => { settings.confirmCommands = !settings.confirmCommands; saveSettings(); syncToggles(); });

// ---------- side pane: terminal / files ----------
let sideView = "term";
function setSideView(view) {
  sideView = view;
  const side = $(".side");
  side.dataset.view = view;
  $(".view-term").hidden = view !== "term";
  $(".view-files").hidden = view !== "files";
  for (const b of document.querySelectorAll("[data-view]")) b.setAttribute("aria-selected", String(b.dataset.view === view));
  if (view === "files") {
    $("#files-badge").hidden = true;
    if (files && !files.entries.length) files.navigate(files.dir);
  } else setTimeout(() => { try { vm.fit?.fit(); } catch {} }, 30);
}
function openFile(path) {
  if (!files) return;
  if (window.matchMedia("(max-width: 900px)").matches) selectTab("files");
  setSideView("files");
  files.open(path);
}
for (const b of document.querySelectorAll("[data-view]")) b.addEventListener("click", () => setSideView(b.dataset.view));
$("#side-max").addEventListener("click", () => {
  const on = document.body.classList.toggle("side-max");
  $("#side-max").setAttribute("aria-pressed", String(on));
  $("#side-max").title = on ? "Restore" : "Maximize";
  $("#side-max use").setAttribute("href", on ? "#i-minimize" : "#i-maximize");
  setTimeout(() => { try { vm.fit?.fit(); } catch {} }, 30);
});
document.addEventListener("keydown", (e) => { if (e.key === "Escape" && document.body.classList.contains("side-max") && !$("#settings").open) $("#side-max").click(); });

// ---------- resizable split ----------
(() => {
  const ws = $("#workspace");
  const sp = $("#splitter");
  try { const w = localStorage.getItem("lwa-split"); if (w) ws.style.setProperty("--left", w); } catch {}
  const setFrac = (frac) => {
    const v = `${(Math.min(0.75, Math.max(0.25, frac)) * 100).toFixed(1)}%`;
    ws.style.setProperty("--left", v);
    try { localStorage.setItem("lwa-split", v); } catch {}
  };
  sp.addEventListener("pointerdown", (e) => {
    sp.setPointerCapture(e.pointerId);
    sp.classList.add("dragging");
    document.body.classList.add("resizing");
    const rect = ws.getBoundingClientRect();
    const move = (ev) => setFrac((ev.clientX - rect.left) / rect.width);
    const up = () => {
      sp.classList.remove("dragging");
      document.body.classList.remove("resizing");
      sp.removeEventListener("pointermove", move);
      try { vm.fit?.fit(); } catch {}
    };
    sp.addEventListener("pointermove", move);
    sp.addEventListener("pointerup", up, { once: true });
  });
  sp.addEventListener("keydown", (e) => {
    if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return;
    const cur = parseFloat(getComputedStyle(ws).getPropertyValue("--left")) / 100 || 0.46;
    setFrac(cur + (e.key === "ArrowLeft" ? -0.02 : 0.02));
  });
})();

// ---------- wiring ----------
$("#composer").addEventListener("submit", (e) => { e.preventDefault(); send($("#prompt").value); });
$("#prompt").addEventListener("keydown", (e) => {
  if (e.key === "Enter" && !e.shiftKey && !e.isComposing) { e.preventDefault(); send($("#prompt").value); }
});
$("#prompt").addEventListener("input", autoGrow);
$("#stop").addEventListener("click", () => agent?.stop());
for (const b of document.querySelectorAll("[data-suggest]")) b.addEventListener("click", () => send(b.textContent));
$("#ctrl-c").addEventListener("click", () => { vm.interrupt(); vm.term?.focus(); });
$("#term-clear").addEventListener("click", () => { vm.term?.clear(); vm.term?.focus(); });
$("#new-chat").addEventListener("click", newConversation);

function selectTab(name) {
  document.body.dataset.tab = name;
  for (const t of document.querySelectorAll("[data-tab]")) t.setAttribute("aria-selected", String(t.dataset.tab === name));
  if (name === "term" || name === "files") setSideView(name);
  if (name === "term") setTimeout(() => { try { vm.term?.focus(); } catch {} }, 50);
}
for (const tab of document.querySelectorAll("[data-tab]")) tab.addEventListener("click", () => selectTab(tab.dataset.tab));

const dlg = $("#settings");
$("#open-settings").addEventListener("click", () => {
  $("#set-model-desc").textContent = usingApi() ? `${activeLabel()} via ${apiHost()}` : activeLocal() ? `${activeLabel()} on this device (WebGPU)` : "None chosen yet";
  $("#set-thinking").checked = settings.thinking;
  $("#set-confirm").checked = settings.confirmCommands;
  $("#set-steps").value = settings.maxSteps;
  $("#set-timeout").value = settings.commandTimeoutSec;
  $("#set-context").value = Math.round(settings.contextBudgetTokens / 1000);
  $("#set-context").max = usingApi() ? 2000 : 256;
  $("#set-context-desc").textContent = usingApi()
    ? "How much of the conversation the API model sees, in thousands of tokens. Set it to your model's context window."
    : "How much of the conversation the local model sees, in thousands of tokens. Larger is slower and uses more GPU memory.";
  dlg.showModal();
});
dlg.addEventListener("close", () => {
  settings.thinking = $("#set-thinking").checked;
  settings.confirmCommands = $("#set-confirm").checked;
  settings.maxSteps = Math.min(50, Math.max(1, Number($("#set-steps").value) || DEFAULTS.maxSteps));
  settings.commandTimeoutSec = Math.min(600, Math.max(5, Number($("#set-timeout").value) || DEFAULTS.commandTimeoutSec));
  const k = Number($("#set-context").value);
  if (k && k !== Math.round(settings.contextBudgetTokens / 1000)) {
    const key = usingApi() ? "contextApiTokens" : "contextLocalTokens";
    settings[key] = Math.round(Math.min(usingApi() ? 2000 : 256, Math.max(4, k)) * 1000);
    syncContextBudget();
    $("#ctx").textContent = $("#ctx").textContent.replace(/\/ [\d,.\s]+ tokens/, `/ ${settings.contextBudgetTokens.toLocaleString()} tokens`);
  }
  saveSettings();
  syncToggles();
});
dlg.addEventListener("click", (e) => { if (e.target === dlg) dlg.close(); }); // click on backdrop
$("#set-model").addEventListener("click", () => { dlg.close(); models.open(); });

// ---------- Model Manager ----------
const models = createModelManager({
  settings, saveSettings, h, icon, fmtBytes, setup,
  activate: activateModel,
  isActive,
  isMobile,
  gpuNote: () => !gpuCheck ? null
    : !gpuCheck.ok ? { ok: false, text: `${gpuCheck.text}, so local models can't run in this browser. API models work.` }
    : gpuCheck.noF16 ? { ok: true, text: "This browser's WebGPU has no f16 shaders (common with Chrome on Linux, even on GPUs that have them on Windows). Local models use their q4 builds instead: 4-bit weights with full-precision math, so downloads are 15 to 40% larger and generation a bit slower. Models marked \"Needs f16\" can't run here." }
    : null,
});
$("#open-models").addEventListener("click", () => models.open());
$("#model-name").addEventListener("click", () => models.open());
$("#reset-vm").addEventListener("click", async () => {
  if (!confirm("Erase all files and changes made inside the Linux machine? The page will reload.")) return;
  if (vm.overlayName) await setup.resetVmStorage(vm.overlayName);
  location.reload();
});
$("#uninstall").addEventListener("click", async () => {
  if (!confirm("Remove the downloaded models, the Linux disk and all saved files from this browser? Reinstalling needs an internet connection.")) return;
  await setup.uninstallAll();
  location.reload();
});

window.addEventListener("online", () => { if (!$("#setup").hidden) showSetup(true); });

// ---------- install as an app (PWA) ----------
let installPrompt = null;
const runningAsApp = () => matchMedia("(display-mode: standalone)").matches || navigator.standalone === true;
function syncInstallUi() {
  const canPrompt = !!installPrompt && !runningAsApp();
  $("#install-app").hidden = !canPrompt;
  $("#setup-install-app").hidden = !canPrompt;
  $("#set-install").hidden = runningAsApp();
  $("#set-install-desc").textContent = runningAsApp()
    ? "Installed: you're using the app now."
    : canPrompt ? "Opens in its own window, with an icon in your launcher, and works offline."
    : /iPhone|iPad/.test(navigator.userAgent) ? "In Safari: Share, then Add to Home Screen."
    : "Use your browser's menu: Install app (or Add to Home Screen).";
  $("#set-install").disabled = !canPrompt;
}
async function promptInstall() {
  if (!installPrompt) return;
  installPrompt.prompt();
  await installPrompt.userChoice.catch(() => null);
  installPrompt = null; // a prompt can only be used once
  syncInstallUi();
}
window.addEventListener("beforeinstallprompt", (e) => {
  e.preventDefault(); // show our own button instead of the browser's mini-infobar
  installPrompt = e;
  syncInstallUi();
});
window.addEventListener("appinstalled", () => { installPrompt = null; syncInstallUi(); });
$("#install-app").addEventListener("click", promptInstall);
$("#setup-install-app").addEventListener("click", promptInstall);
$("#set-install").addEventListener("click", promptInstall);
syncInstallUi();
document.body.dataset.tab = "chat";
$(".side").dataset.view = "term";
init().catch((err) => {
  console.error(err);
  addNotice("Startup error: " + err.message, "error");
});