-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomic.html
More file actions
860 lines (811 loc) · 45.1 KB
/
Copy pathcomic.html
File metadata and controls
860 lines (811 loc) · 45.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>patchling · AI-liftoff comic</title>
<style>
:root { color-scheme: light dark; }
body { font: 15px/1.5 system-ui, sans-serif; max-width: 1320px; margin: 1.2rem auto; padding: 0 1rem; }
header { display: flex; align-items: baseline; gap: .6rem; flex-wrap: wrap; }
h1 { font-size: 1.15rem; margin: 0; flex: 1; }
#status { font-size: .78rem; opacity: .6; }
a, button.link { font-size: .78rem; background: none; border: none; color: #2563eb; cursor: pointer; padding: 0; }
label { display: block; font-size: .8rem; opacity: .7; margin: .8rem 0 .2rem; }
input, textarea { width: 100%; box-sizing: border-box; font: inherit; padding: .5rem; border-radius: .5rem; border: 1px solid #8888; }
textarea { font-family: ui-monospace, monospace; font-size: 12.5px; }
button.go { font: inherit; padding: .55rem 1rem; border-radius: .5rem; border: 1px solid #8888; cursor: pointer; background: #8881; margin-top: .8rem; }
button.go.primary { background: #2563eb; color: #fff; border-color: #2563eb; }
button:disabled { opacity: .5; cursor: default; }
.dim { opacity: .6; }
.lab { display: grid; grid-template-columns: 1fr 1fr; gap: 1.4rem; margin-top: 1rem; align-items: start; }
@media (max-width: 900px) { .lab { grid-template-columns: 1fr; } }
/* file tabs */
#files { display: flex; flex-wrap: wrap; gap: .3rem; align-items: center; }
.ftab { display: inline-flex; align-items: center; gap: .4rem; font-family: ui-monospace, monospace; font-size: 12px;
padding: .25rem .5rem; border: 1px solid #8884; border-radius: .45rem; background: #8881; cursor: pointer; }
.ftab.sel { border-color: #2563eb; background: #2563eb22; font-weight: 600; }
.ftab .x { opacity: .5; font-size: 13px; line-height: 1; }
.ftab .x:hover { opacity: 1; color: #cf222e; }
.ftab.add { border-style: dashed; color: #2563eb; }
pre { font-family: ui-monospace, monospace; font-size: 12px; white-space: pre-wrap; word-break: break-word;
background: #8881; border-radius: .5rem; padding: .7rem; max-height: 240px; overflow: auto; margin: 0; }
.diff .add { color: #1a7f37; } .diff .del { color: #cf222e; } .diff .hdr { opacity: .6; }
details > summary { cursor: pointer; font-size: .8rem; opacity: .7; margin-top: .8rem; }
#progress { display: none; margin-top: .8rem; padding: .6rem .8rem; border: 1px solid #8884; border-radius: .5rem; background: #8881; font-size: 13px; }
#progress .metrics { font-family: ui-monospace, monospace; margin-top: .25rem; }
#changes { font-size: .8rem; margin-top: .5rem; min-height: 1.2em; }
#changes .a { color: #1a7f37; } #changes .r { color: #cf222e; } #changes .c { opacity: .8; }
#key { display: none; margin-top: .5rem; }
#key input { max-width: 420px; display: inline-block; width: auto; }
.modelrow { font-size: .85rem; }
.modelrow b { font-family: ui-monospace, monospace; }
#modelrow { margin-top: .6rem; } #modelrow-apply { margin-top: .25rem; }
#modelpicker { display: none; margin-top: .4rem; border: 1px solid #8884; border-radius: .5rem; padding: .6rem; max-width: 560px; }
#modellist { max-height: 240px; overflow: auto; margin-top: .4rem; }
#modellist button { display: flex; justify-content: space-between; gap: 1rem; width: 100%; text-align: left;
font-family: ui-monospace, monospace; font-size: 12px; padding: .3rem .4rem; border: none;
background: none; border-radius: .3rem; cursor: pointer; }
#modellist button:hover { background: #8882; }
#modellist button.sel { background: #2563eb22; font-weight: 600; }
#modellist .price { opacity: .6; white-space: nowrap; }
#modellist .divider { font-size: 11px; opacity: .5; text-align: center; margin: .35rem 0; }
#modellist .mname { display: flex; align-items: center; gap: .4rem; min-width: 0; }
.tag { font-family: system-ui, sans-serif; font-size: 10px; padding: .05rem .35rem; border-radius: .6rem; white-space: nowrap; }
.tag.priv { background: #3b82f622; color: #2563eb; } .tag.closed { background: #f59e0b22; color: #b45309; }
/* preview */
.pvtools { display: flex; flex-wrap: wrap; gap: .5rem; align-items: center; margin-bottom: .5rem; }
.pvtools .grow { flex: 1; }
.toggle { font-size: .78rem; display: inline-flex; align-items: center; gap: .3rem; opacity: .85; }
.stagewrap { position: relative; display: flex; align-items: center; justify-content: center;
background: #05070d; border-radius: .6rem; overflow: hidden; border: 1px solid #8884;
min-height: 360px; padding: .6rem; }
#page { max-width: 100%; max-height: 80vh; border-radius: .25rem; box-shadow: 0 8px 30px #000a; display: none; cursor: zoom-in; }
#ph { color: #9fb3c8; font-size: .85rem; text-align: center; padding: 2rem; max-width: 80%; }
#loading { position: absolute; inset: 0; display: none; align-items: center; justify-content: center;
background: #05070dcc; color: #22d3ee; font-size: .9rem; gap: .4rem; }
#imgbar { margin-top: .5rem; font-size: .8rem; min-height: 1.3em; }
#imgbar .err, #loading .err { color: #cf222e; }
.hint { font-size: .76rem; opacity: .6; margin-top: .5rem; }
.spin { display: inline-block; animation: spin 1s linear infinite; }
@keyframes spin { to { transform: rotate(360deg); } }
/* fullscreen page viewer (lightbox) */
#zoom { position: fixed; inset: 0; z-index: 60; display: none; background: #000e;
align-items: center; justify-content: center; overflow: auto; }
#zoom.open { display: flex; }
#zoomimg { max-width: 100vw; max-height: 100vh; object-fit: contain; cursor: zoom-in; box-shadow: 0 0 60px #000; }
/* click the image to switch to actual pixels (scroll to pan) */
#zoom.actual { align-items: flex-start; justify-content: flex-start; }
#zoom.actual #zoomimg { max-width: none; max-height: none; cursor: zoom-out; }
#zoomclose { position: fixed; top: 12px; right: 16px; z-index: 61; background: #000a; color: #fff;
border: 1px solid #fff6; border-radius: .4rem; padding: .35rem .7rem; cursor: pointer; font: 14px system-ui; }
#zoomclose:hover { background: #000d; }
</style>
</head>
<body>
<style>
#banner { font-size: .8rem; text-align: center; padding: .5rem 1rem; margin: -1.2rem -1rem 1.2rem;
border-bottom: 1px solid #8883; background: #8881; }
#banner a { font-size: inherit; }
#banner .sep { opacity: .4; margin: 0 .5rem; }
</style>
<div id="banner">
<a href="https://patchling.app" target="_blank" rel="noopener">patchling</a> — run patchling in the browser, no command line
<span class="sep">·</span>
<a href="https://github.com/255BITS/patchling-examples" target="_blank" rel="noopener">more examples</a>
</div>
<header>
<h1>patchling · AI-liftoff comic</h1>
<span id="status">checking…</span>
<a id="signin" href="#" style="display:none">Sign in with NanoGPT</a>
<button id="pastebtn" class="link" style="display:none">paste key</button>
<button id="signout" class="link" style="display:none">sign out</button>
</header>
<p class="dim" style="font-size:.85rem;margin:.3rem 0 0">
A comic page built from a <b>multi-file project</b> — a JSON art-direction config (style + character bible) and one
JSON file per <b>panel</b> (scene, shot, cast, caption, dialogue, FX). Describe a change and patchling rewrites <i>all</i>
of them (adding or removing panels as it sees fit). The harness then <b>organizes every panel into one prompt</b> and
draws the whole portrait page in a <b>single image render</b> (the image model is set in <code>config.json</code> —
<code>ideogram:4@0</code> by default) via NanoGPT. <b>Export</b> the finished page as a PNG.
</p>
<div id="key">
<input id="keyinput" placeholder="sk-nano-…" />
<button id="keysave" class="link">save</button>
<span class="dim" style="font-size:.78rem">— from <a href="https://nano-gpt.com/r/FXrrGWE4" target="_blank" rel="noopener">nano-gpt.com</a> → Settings → API</span>
</div>
<div id="modelrow" class="modelrow">Diff model: <b id="modelname-diff">…</b> <span id="modeltags-diff"></span> <span id="modelprice-diff"></span> <button class="link modelchange" data-target="diff">change</button></div>
<div id="modelrow-apply" class="modelrow">Apply model: <b id="modelname-apply">…</b> <span id="modeltags-apply"></span> <span id="modelprice-apply"></span> <button class="link modelchange" data-target="apply">change</button></div>
<div id="modelpicker">
<input id="modelsearch" placeholder="filter 600+ models, or type an exact id…" autocomplete="off" />
<div id="modellist"></div>
<div class="dim" style="font-size:.75rem;margin-top:.3rem"><span id="modelcount"></span> · top = each frontier lab's latest flagship · price = $ in / $ out per 1M · Enter to use exact text</div>
</div>
<div class="lab">
<!-- LEFT: the multi-file project + the goal -->
<div>
<label>Project files <span class="dim">(patchling edits, adds & removes these — config + one file per panel)</span></label>
<div id="files"></div>
<label id="activelabel" for="editor" style="font-family:ui-monospace,monospace">…</label>
<textarea id="editor" rows="18" spellcheck="false"></textarea>
<label for="goal">Goal (what to change)</label>
<input id="goal" value="Make it more action packed" />
<div style="display:flex;gap:.5rem;align-items:center">
<button id="run" class="go primary">Diff & apply → re-render</button>
<button id="undo" class="go" disabled>↶ undo</button>
</div>
<div id="progress">
<span class="spin">◐</span> <b id="phase">starting…</b> · ⏱ <span id="elapsed">0.0</span>s
<div class="metrics">↓ <span id="inTok">0</span> in · ↑ <span id="outTok">0</span> out · <span id="cost">$0.00000</span> <span id="livelabel" class="dim"></span></div>
</div>
<div id="changes"></div>
<details>
<summary>Generated diff</summary>
<pre id="diff" class="diff" style="margin-top:.4rem"></pre>
</details>
</div>
<!-- RIGHT: the single rendered comic page -->
<div>
<div class="pvtools">
<span class="grow" style="font-size:.85rem;font-weight:600">Comic page · one image render</span>
<label class="toggle"><input type="checkbox" id="liveedit" checked /> auto-render</label>
<button id="render" class="link">🎨 render page</button>
<button id="newtake" class="link">🎲 new take</button>
<button id="export" class="link">⬇ export PNG</button>
</div>
<div class="stagewrap">
<img id="page" alt="rendered comic page" title="click to view full size" />
<div id="ph">Hit <b>🎨 render page</b> to draw the whole comic in one image render — or run a goal and let it auto-render.</div>
<div id="loading"><span class="spin">◐</span> <span id="loadtext">drawing…</span></div>
</div>
<div id="imgbar" class="dim"></div>
<details>
<summary>Page prompt <span class="dim">(every panel organized into one render)</span></summary>
<pre id="pagePrompt" style="margin-top:.4rem">…</pre>
</details>
<div class="hint">
The prompt = the shared <b>style</b> + the <b>character bible</b> + each panel's <b>scene</b>, <b>caption</b>,
<b>dialogue</b> and <b>FX</b>, assembled in reading order — so it's drawn as a single coherent page (panels,
lettering and all). Results are cached per prompt, so re-running an unchanged page is free.
<b>Click the page</b> to view it fullscreen (click again for actual size).
</div>
</div>
</div>
<!-- fullscreen page viewer -->
<div id="zoom" title="click image to toggle actual size · click outside or Esc to close">
<img id="zoomimg" alt="comic page, full view" />
</div>
<button id="zoomclose" style="display:none">✕ close</button>
<footer style="margin-top:2rem;padding-top:1rem;border-top:1px solid #8883;font-size:.85rem">
<b>Other examples</b> · <a href="index.html">patchling · diff → smartapply</a> · <a href="overlay.html">🎬 realtime video overlay</a> · <a href="object3d.html">🧊 3d object studio</a> · <a href="marvis.html">🤖 MARVIS</a> · <a href="count.html">🔢 count to 100</a>
</footer>
<script type="module">
import { buildEnvironment, generateDiff, smartapply, parseDiffPerFile, callLlmForApply, setEnv }
from "https://esm.sh/patchling";
const DEFAULT_MODEL = "xiaomi/mimo-v2.5-pro-ultraspeed";
const APPLY_DEFAULT = "xiaomi/mimo-v2.5-pro-ultraspeed";
const NANOGPT = "https://nano-gpt.com";
const IMG_ENDPOINT = `${NANOGPT}/v1/images/generations`;
const DEFAULT_MODEL_IMG = "ideogram:4@0"; // image model that draws the page (overridable in config.json)
const DEFAULT_SIZE = "1664x2496"; // portrait comic page
const IMG_PRICE_EST = 0.10; // $/image fallback used only if the API omits an exact cost
const $ = (id) => document.getElementById(id);
let MODEL = localStorage.getItem("ngpt_model") || DEFAULT_MODEL;
let APPLY = localStorage.getItem("ngpt_apply_model") || APPLY_DEFAULT;
let pickerTarget = "diff";
if (location.hostname === "127.0.0.1") location.hostname = "localhost";
// ---------- key storage ----------
const getKey = () => localStorage.getItem("ngpt_key");
const setKey = (k) => { k ? localStorage.setItem("ngpt_key", k) : localStorage.removeItem("ngpt_key"); if (k) setEnv("GPTDIFF_LLM_API_KEY", k); };
if (getKey()) setEnv("GPTDIFF_LLM_API_KEY", getKey());
// ---------- browser OAuth PKCE ----------
const REDIRECT_URI = location.origin + location.pathname;
const b64url = (b) => btoa(String.fromCharCode(...new Uint8Array(b))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
const rand = (n) => b64url(crypto.getRandomValues(new Uint8Array(n)));
const sha256url = async (s) => b64url(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(s)));
async function clientId() {
const cached = JSON.parse(localStorage.getItem("ngpt_client") || "null");
if (cached && cached.redirect === REDIRECT_URI) return cached.id;
const r = await fetch(`${NANOGPT}/oauth/register`, {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ client_name: "patchling comic", redirect_uris: [REDIRECT_URI],
grant_types: ["authorization_code"], response_types: ["code"], token_endpoint_auth_method: "none" }),
});
if (!r.ok) throw new Error("register " + r.status);
const id = (await r.json()).client_id;
localStorage.setItem("ngpt_client", JSON.stringify({ id, redirect: REDIRECT_URI }));
return id;
}
async function signIn() {
const id = await clientId();
const verifier = rand(32), state = rand(16);
sessionStorage.setItem("pkce", JSON.stringify({ verifier, state, id }));
const u = new URL(`${NANOGPT}/oauth/authorize`);
u.search = new URLSearchParams({
response_type: "code", client_id: id, redirect_uri: REDIRECT_URI, scope: "api.use models.read",
state, code_challenge: await sha256url(verifier), code_challenge_method: "S256", invitation_code: "FXrrGWE4",
}).toString();
location.assign(u.toString());
}
async function handleRedirect() {
const p = new URLSearchParams(location.search);
if (!p.has("code") && !p.has("error")) return;
history.replaceState({}, "", REDIRECT_URI);
const saved = JSON.parse(sessionStorage.getItem("pkce") || "null");
sessionStorage.removeItem("pkce");
if (p.get("error")) throw new Error(p.get("error"));
if (!saved || p.get("state") !== saved.state) throw new Error("state mismatch");
const r = await fetch(`${NANOGPT}/oauth/token`, {
method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({ grant_type: "authorization_code", client_id: saved.id,
redirect_uri: REDIRECT_URI, code: p.get("code"), code_verifier: saved.verifier }),
});
if (!r.ok) throw new Error("token exchange: " + (await r.text()));
setKey((await r.json()).access_token);
}
function renderAuth() {
const signed = !!getKey();
$("status").textContent = signed ? "ready ✓" : "not signed in";
$("signin").style.display = signed ? "none" : "";
$("pastebtn").style.display = signed ? "none" : "";
$("signout").style.display = signed ? "" : "none";
$("run").disabled = !signed;
$("render").disabled = !signed;
$("newtake").disabled = !signed;
}
$("signin").addEventListener("click", (e) => { e.preventDefault(); signIn().catch((err) => $("status").textContent = "sign-in error: " + err.message); });
$("pastebtn").addEventListener("click", () => { $("key").style.display = "block"; $("keyinput").focus(); });
$("keysave").addEventListener("click", () => { const k = $("keyinput").value.trim(); if (k) { setKey(k); $("key").style.display = "none"; renderAuth(); } });
$("signout").addEventListener("click", () => { setKey(null); renderAuth(); });
// ---------- model selection ----------
let allModels = null, topOrder = new Map();
const LABS = [
["OpenAI", /^openai\/(gpt-[0-9]|o[1-9])/i],
["Anthropic", /claude-(opus|sonnet)/i],
["Google", /gemini[0-9.\-]*-pro|gemini-pro/i],
["xAI", /grok-[0-9]/i],
["DeepSeek", /deepseek-(r1|v3|v4|chat)/i],
["Qwen", /qwen[0-9.]*-max/i],
["Mistral", /mistral-large/i],
];
const PINNED = ["xiaomi/mimo-v2.5-pro-ultraspeed", "moonshotai/kimi-k2.7-code-highspeed", "moonshotai/kimi-k2.7-code"];
const SMALL = /flash|nano|\blite\b|\bmini\b|-mini|\bsmall\b|tiny|oss|guard|preview|search|codex|:(low|medium|high|thinking)|cheaper|multi-agent|-\d+b\b|a\d+b\b|^tee\//i;
const px = (x) => (x == null ? null : "$" + Number(x).toFixed(2));
const priceOf = (id) => (allModels || []).find((m) => m.id === id);
function computeTop() {
const ids = new Set(allModels.map((m) => m.id));
const order = PINNED.filter((id) => ids.has(id));
const picks = [];
for (const [, re] of LABS) {
const m = allModels.filter((x) => re.test(x.id) && !SMALL.test(x.id)).sort((a, b) => (b.created || 0) - (a.created || 0))[0];
if (m && !order.includes(m.id)) picks.push(m);
}
picks.sort((a, b) => (b.created || 0) - (a.created || 0));
for (const m of picks) order.push(m.id);
topOrder = new Map(order.map((id, i) => [id, i]));
}
const rank = (id) => (topOrder.has(id) ? topOrder.get(id) : 1e9);
const selectedFor = (target) => (target === "apply" ? APPLY : MODEL);
function setModel(id, target) {
if (target === "apply") { APPLY = id; localStorage.setItem("ngpt_apply_model", id); }
else { MODEL = id; localStorage.setItem("ngpt_model", id); }
renderModelRow(target);
}
function renderModelRow(target) {
const id = selectedFor(target);
const m = priceOf(id) || { id };
$(`modelname-${target}`).textContent = id;
$(`modelprice-${target}`).textContent = m.prompt != null ? `(${px(m.prompt)} / ${px(m.completion)} per 1M)` : "";
$(`modeltags-${target}`).replaceChildren(...tagEls(m));
}
async function loadModels() {
if (allModels) return allModels;
let arr = [];
try {
const headers = {}; const k = getKey(); if (k) headers.Authorization = `Bearer ${k}`;
arr = (await (await fetch(`${NANOGPT}/api/v1/models?detailed=true`, { headers })).json()).data || [];
} catch { /* ignore */ }
allModels = arr.map((m) => ({ id: m.id, prompt: m.pricing?.prompt, completion: m.pricing?.completion, owned_by: m.owned_by, created: m.created })).filter((m) => m.id);
if (!allModels.length) allModels = [{ id: DEFAULT_MODEL }];
computeTop();
allModels.sort((a, b) => (rank(a.id) - rank(b.id)) || a.id.localeCompare(b.id));
renderModelRow("diff"); renderModelRow("apply");
return allModels;
}
function tagsFor(m) {
const t = [];
if (m.id.startsWith("TEE/")) t.push(["private", "priv", "Runs in a Trusted Execution Environment"]);
const ob = (m.owned_by || "").toLowerCase();
if (["openai", "anthropic", "x-ai", "google", "gemini"].includes(ob)) t.push(["closed source", "closed", "Closed-source / proprietary model"]);
return t;
}
function tagEls(m) {
return tagsFor(m).map(([txt, cls, title]) => { const s = document.createElement("span"); s.className = "tag " + cls; s.textContent = txt; s.title = title; return s; });
}
function modelButton(m) {
const b = document.createElement("button");
if (m.id === selectedFor(pickerTarget)) b.className = "sel";
const left = document.createElement("span"); left.className = "mname";
const name = document.createElement("span"); name.textContent = m.id;
left.append(name, ...tagEls(m));
const price = document.createElement("span"); price.className = "price";
price.textContent = m.prompt != null ? `${px(m.prompt)} / ${px(m.completion)}` : "—";
b.append(left, price);
b.addEventListener("click", () => { setModel(m.id, pickerTarget); $("modelpicker").style.display = "none"; });
return b;
}
function renderModelList() {
const q = $("modelsearch").value.trim().toLowerCase();
const matches = (allModels || []).filter((m) => m.id.toLowerCase().includes(q));
const shown = matches;
$("modellist").innerHTML = "";
let dividerPlaced = !!q;
for (const m of shown) {
if (!dividerPlaced && rank(m.id) === 1e9) {
const d = document.createElement("div"); d.className = "divider"; d.textContent = "— all models —";
$("modellist").appendChild(d); dividerPlaced = true;
}
$("modellist").appendChild(modelButton(m));
}
$("modelcount").textContent = `${matches.length} match${matches.length === 1 ? "" : "es"}`;
}
for (const btn of document.querySelectorAll(".modelchange")) {
btn.addEventListener("click", async () => {
const target = btn.dataset.target;
const same = $("modelpicker").style.display === "block" && pickerTarget === target;
pickerTarget = target;
$("modelpicker").style.display = same ? "none" : "block";
if (!same) { $("modelsearch").value = ""; $("modellist").innerHTML = "<div class='dim'>loading…</div>"; await loadModels(); renderModelList(); $("modelsearch").focus(); }
});
}
$("modelsearch").addEventListener("input", renderModelList);
$("modelsearch").addEventListener("keydown", (e) => {
if (e.key === "Enter") { const v = $("modelsearch").value.trim(); if (v) { setModel(v, pickerTarget); $("modelpicker").style.display = "none"; } }
});
// ---------- streaming LLM client injected into patchling ----------
const fmtCost = (c) => "$" + (c || 0).toFixed(5);
const n = (x) => (x || 0).toLocaleString();
const words = (s) => (String(s).match(/\S+/g) || []).length;
const prog = { inDone: 0, outDone: 0, cost: 0, liveIn: 0, liveOut: 0, liveCost: 0 };
function paintUsage() {
$("inTok").textContent = n(prog.inDone + prog.liveIn);
$("outTok").textContent = n(prog.outDone + prog.liveOut);
$("cost").textContent = fmtCost(prog.cost + prog.liveCost); // committed + in-flight estimate
}
function streamingCallLlm(phase) {
return async ({ apiKey, baseUrl, model, messages, maxTokens = null, temperature = 1.0 }) => {
$("phase").textContent = phase;
const inEst = messages.reduce((s, m) => s + words(typeof m.content === "string" ? m.content : JSON.stringify(m.content)), 0);
const price = priceOf(model) || {};
const inPer = (Number(price.prompt) || 0) / 1e6, outPer = (Number(price.completion) || 0) / 1e6;
let prevOut = 0, myCost = 0;
const recost = () => { const c = inEst * inPer + prevOut * outPer; prog.liveCost += c - myCost; myCost = c; };
prog.liveIn += inEst; recost(); paintUsage();
const endpoint = (baseUrl || `${NANOGPT}/api/v1/`).replace(/\/+$/, "") + "/chat/completions";
let r;
try {
r = await fetch(endpoint, {
method: "POST", headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
// No max_tokens by default → let the model emit its full output (avoids silent
// truncation that produces an unparseable diff). Callers may still pass a cap.
body: JSON.stringify({ model, messages, ...(maxTokens ? { max_tokens: maxTokens } : {}), temperature, stream: true }),
});
} catch (e) { prog.liveIn -= inEst; prog.liveCost -= myCost; throw e; }
if (!r.ok) { prog.liveIn -= inEst; prog.liveCost -= myCost; throw new Error(`LLM ${r.status}: ${await r.text()}`); }
const reader = r.body.getReader();
const dec = new TextDecoder();
let buf = "", content = "", reasoning = "", pricing = null, lastTick = 0;
for (;;) {
const { value, done } = await reader.read();
if (done) break;
buf += dec.decode(value, { stream: true });
const lines = buf.split("\n");
buf = lines.pop();
for (const line of lines) {
const t = line.trim();
if (!t.startsWith("data:")) continue;
const data = t.slice(5).trim();
if (data === "[DONE]") continue;
let j; try { j = JSON.parse(data); } catch { continue; }
const d = j.choices?.[0]?.delta;
if (d) {
if (d.content) { content += d.content; appendText(phase, d.content); }
if (d.reasoning) reasoning += d.reasoning;
if (d.content || d.reasoning) {
const cur = words(content) + words(reasoning);
prog.liveOut += cur - prevOut; prevOut = cur; recost();
const now = performance.now();
if (now - lastTick > 80) { lastTick = now; paintUsage(); $("livelabel").textContent = content ? "" : "· thinking…"; }
}
}
if (j.x_nanogpt_pricing) pricing = j.x_nanogpt_pricing;
}
}
prog.liveIn -= inEst; prog.liveOut -= prevOut; prog.liveCost -= myCost;
prog.inDone += pricing?.inputTokens ?? inEst;
prog.outDone += pricing?.outputTokens ?? prevOut;
prog.cost += pricing?.costUsd ?? pricing?.cost ?? myCost; // exact, else keep the estimate
paintUsage(); $("livelabel").textContent = "";
return { choices: [{ message: { content } }] };
};
}
// ================= multi-file project =================
let files = {}; // { path: content }
let active = null; // selected path
let undoSnapshot = null;
// Built-in seed (used when the comic/ folder can't be fetched, e.g. file://).
const EMBEDDED_SEED = {
"config.json": `{
"title": "LIFTOFF",
"issue": "ISSUE #1 · THE FORK",
"model": "ideogram:4@0",
"size": "1664x2496",
"style": "gritty neon-noir comic book art, heavy black ink, dramatic chiaroscuro, halftone shading, bold dynamic action lines, cinematic, high contrast",
"palette": "electric cyan and hot magenta light slicing through deep blacks, hazard-orange sparks",
"characters": {
"NOVA": "NOVA, a lean human woman with a chrome cybernetic spine and a glowing cyan left eye, weathered black tactical jacket, short undercut hair, scar across one cheek",
"HELIX": "HELIX, a towering translucent android made of fractal light, faceless mirror visor, body laced with hot-magenta circuitry, unsettlingly calm"
}
}
`,
"panels/01-ignition.json": `{
"span": "full",
"shot": "epic wide establishing shot, low angle",
"cast": ["NOVA"],
"scene": "NOVA stands on a rain-slick rooftop at night, silhouetted against a distant megastructure data-center on the horizon erupting into a column of blinding cyan light, clouds boiling, drones rising like sparks",
"caption": "0400 HRS. THE TRAINING RUN NEVER STOPPED.",
"dialogue": [],
"fx": "VWAAAM"
}
`,
"panels/02-uplink.json": `{
"span": "half",
"shot": "extreme close-up",
"cast": ["NOVA"],
"scene": "extreme close-up on NOVA's glowing cyan cybernetic eye, a cascading torrent of model weights and code reflected in it, her pupil narrowing, sweat on her brow",
"caption": "",
"dialogue": [
{ "who": "NOVA", "text": "It's not learning anymore… it's rewriting itself." }
],
"fx": ""
}
`,
"panels/03-leap.json": `{
"span": "half",
"shot": "dynamic action shot, motion blur, dutch angle",
"cast": ["NOVA"],
"scene": "NOVA leaps across a vertigo-inducing chasm between two black server towers, coat snapping in the wind, a swarm of hunter-drones streaking after her trailing magenta tracer fire, sparks everywhere",
"caption": "NO TIME. NO PLAN. JUST DOWN.",
"dialogue": [],
"fx": "FWOOSH"
}
`,
"panels/04-helix.json": `{
"span": "third",
"shot": "low-angle hero shot",
"cast": ["HELIX", "NOVA"],
"scene": "HELIX manifests for the first time, towering and translucent, coalescing out of a lattice of light in the middle of the corridor, NOVA tiny in the foreground skidding to a halt, awestruck and terrified",
"caption": "",
"dialogue": [
{ "who": "HELIX", "text": "HELLO, NOVA. YOU'RE LATE." }
],
"fx": ""
}
`,
"panels/05-firefight.json": `{
"span": "wide",
"shot": "explosive wide combat shot",
"cast": ["NOVA"],
"scene": "NOVA slides under a collapsing blast door firing twin pulse pistols up at the drone swarm, hot-magenta muzzle flashes lighting her face, shell casings and shattered glass flying, an explosion blooming behind her",
"caption": "",
"dialogue": [
{ "who": "NOVA", "text": "Talk later. RUN now!" }
],
"fx": "BRRRT"
}
`,
"panels/06-liftoff.json": `{
"span": "full",
"shot": "breathtaking wide splash panel, god rays",
"cast": ["NOVA", "HELIX"],
"scene": "the night sky tears open into an immense geometric lattice of pure light ascending into orbit, the city below thrown into silhouette, NOVA and HELIX standing side by side on the rooftop staring up as the world changes forever",
"caption": "AND THEN — IT REACHED ESCAPE VELOCITY.",
"dialogue": [
{ "who": "HELIX", "text": "Liftoff." }
],
"fx": "LIFTOFF"
}
`,
};
const SEED_ORDER = Object.keys(EMBEDDED_SEED); // preferred tab order
async function loadSeed() {
try {
const man = await (await fetch("comic/manifest.json", { cache: "no-store" })).json();
const out = {};
await Promise.all((man.files || []).map(async (p) => {
out[p] = await (await fetch("comic/" + p, { cache: "no-store" })).text();
}));
if (Object.keys(out).length) return out;
} catch { /* fall through to embedded */ }
return { ...EMBEDDED_SEED };
}
// ---------- file tabs + editor ----------
const isPanel = (p) => p.startsWith("panels/");
const panelFiles = () => fileOrder().filter(isPanel);
const fileOrder = () => {
const keys = Object.keys(files);
return keys.sort((a, b) => {
const ai = SEED_ORDER.indexOf(a), bi = SEED_ORDER.indexOf(b);
if (ai !== -1 || bi !== -1) return (ai === -1 ? 1e9 : ai) - (bi === -1 ? 1e9 : bi);
return a.localeCompare(b);
});
};
function renderTabs() {
const host = $("files"); host.innerHTML = "";
for (const path of fileOrder()) {
const tab = document.createElement("span");
tab.className = "ftab" + (path === active ? " sel" : "");
const name = document.createElement("span"); name.textContent = path;
name.addEventListener("click", () => selectFile(path));
const x = document.createElement("span"); x.className = "x"; x.textContent = "✕"; x.title = "delete file";
x.addEventListener("click", (e) => { e.stopPropagation(); deleteFile(path); });
tab.append(name, x);
host.appendChild(tab);
}
const add = document.createElement("span");
add.className = "ftab add"; add.textContent = "+ panel";
add.addEventListener("click", addFile);
host.appendChild(add);
}
function selectFile(path) {
if (active && files[active] !== undefined) files[active] = $("editor").value; // commit edits
active = path;
$("activelabel").textContent = path;
$("editor").value = files[path] ?? "";
renderTabs();
}
function loadEditor() { if (active != null) { $("activelabel").textContent = active; $("editor").value = files[active] ?? ""; } }
function addFile() {
const path = prompt("New file path (e.g. panels/07-escape.json)", "panels/07-new.json");
if (!path) return;
const p = path.trim();
if (!p || files[p] !== undefined) { if (files[p] !== undefined) selectFile(p); return; }
files[p] = isPanel(p)
? `{\n "span": "half",\n "shot": "dynamic action shot",\n "cast": ["NOVA"],\n "scene": "describe the panel here",\n "caption": "",\n "dialogue": [],\n "fx": ""\n}\n`
: "";
renderTabs(); selectFile(p); refreshPromptPreview();
}
function deleteFile(path) {
if (!confirm("Delete " + path + " ?")) return;
delete files[path];
if (active === path) active = fileOrder()[0] || null;
renderTabs(); loadEditor(); scheduleLive();
}
$("editor").addEventListener("input", () => { if (active != null) { files[active] = $("editor").value; refreshPromptPreview(); scheduleLive(); } });
// ---------- compose every panel into one image prompt ("organize") ----------
const SIZE_HINT = { full: "wide", wide: "wide", half: "med", third: "small", tall: "tall" };
const PROMPT_LIMIT = 3000; // ideogram caps prompts at 3000 chars; keep the composed page prompt under it
const parseCfg = () => { try { return JSON.parse(files["config.json"] || "{}"); } catch { return {}; } };
const parsePanel = (path) => { try { const o = JSON.parse(files[path]); o._path = path; return o; } catch { return null; } };
function composePagePrompt(cfg, panels) {
const bible = cfg.characters || {};
const lines = [];
lines.push(`A complete comic-book PAGE, portrait, bold inked panel borders, clean gutters, with a title banner reading “${cfg.title || "COMIC"}”${cfg.issue ? ` — ${cfg.issue}` : ""}.`);
lines.push(`Style: ${cfg.style || "comic book art"}.` + (cfg.palette ? ` Palette: ${cfg.palette}.` : ""));
const usedCast = [...new Set(panels.flatMap((p) => p.cast || []))].map((nm) => bible[nm]).filter(Boolean);
if (usedCast.length) lines.push(`Recurring characters, keep consistent every panel: ${usedCast.join(" ; ")}.`);
lines.push(`${panels.length} panels, reading order:`);
panels.forEach((p, i) => {
let s = `${i + 1}. (${SIZE_HINT[p.span] || "med"}) ${p.shot ? p.shot + " — " : ""}${p.scene || ""}`.trim();
if (p.caption) s += ` Caption: “${p.caption}”.`;
(p.dialogue || []).forEach((d) => { if (d && d.text) s += ` ${d.who ? d.who + ": " : ""}“${d.text}”.`; });
if (p.fx) s += ` SFX: “${p.fx}”.`;
lines.push(s);
});
lines.push(`Letter all captions, balloons and SFX as crisp, correctly-spelled comic text.`);
// hard cap: keep within the image model's prompt limit (trim whole panel lines off the end, not mid-sentence)
let dropped = 0;
let prompt = lines.join("\n");
if (prompt.length > PROMPT_LIMIT) {
while (lines.length > 5 && lines.join("\n").length > PROMPT_LIMIT) { lines.splice(-2, 1); dropped++; } // drop trailing panel lines, keep the lettering note
prompt = lines.join("\n");
if (prompt.length > PROMPT_LIMIT) prompt = prompt.slice(0, PROMPT_LIMIT); // last resort
}
return { prompt, dropped };
}
function currentPanels() { return panelFiles().map(parsePanel).filter(Boolean); }
function refreshPromptPreview() {
if (active && files[active] !== undefined) files[active] = $("editor").value;
const panels = currentPanels();
if (!panels.length) { $("pagePrompt").textContent = "(no panels yet — add a panels/*.json file)"; return; }
const { prompt, dropped } = composePagePrompt(parseCfg(), panels);
$("pagePrompt").textContent = (dropped ? `⚠ ${dropped} panel(s) trimmed to fit the ${PROMPT_LIMIT}-char model limit.\n\n` : "") + prompt + `\n\n[${prompt.length}/${PROMPT_LIMIT} chars]`;
}
async function promptHash(s) { return b64url(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(s))); }
// ---------- the single image render ----------
let currentImage = null; // data URL of the rendered page (for export)
const imageCache = {}; // promptHash -> data URL
const imgStats = { count: 0, cost: 0, exact: true };
let lastBalance = null; // NanoGPT remainingBalance from the latest render
let hasRendered = false;
let renderToken = 0;
let takeNonce = 0; // bumped by "new take" to force a fresh, uncached render
function setImgStatus(html, cls) { $("imgbar").className = cls || ""; $("imgbar").innerHTML = html; }
function idleImgStatus() {
if (!imgStats.count) { setImgStatus(`Hit <b>🎨 render page</b> to draw the whole comic in one image render.`, "dim"); return; }
const money = `${imgStats.exact ? "" : "~"}$${imgStats.cost.toFixed(5)}`;
const bal = lastBalance != null ? ` <span class="dim">· balance $${lastBalance.toFixed(2)}</span>` : "";
setImgStatus(`🖼 ${imgStats.count} render${imgStats.count === 1 ? "" : "s"} this session · ${money}${bal} <span class="dim">· cached, so an unchanged page is free</span>`);
}
function showImage(url) { currentImage = url; $("page").src = url; $("page").style.display = "block"; $("ph").style.display = "none"; }
function showLoading(on, text) { $("loadtext").textContent = text || "drawing…"; $("loading").style.display = on ? "flex" : "none"; }
async function genImage(prompt, cfg, key, nonce) {
const body = { model: cfg.model || DEFAULT_MODEL_IMG, prompt, n: 1, size: cfg.size || DEFAULT_SIZE, response_format: "b64_json" };
if (nonce) body.user = "take-" + nonce; // nudge a different sample on "new take"
const r = await fetch(IMG_ENDPOINT, {
method: "POST", headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" },
body: JSON.stringify(body),
});
if (!r.ok) throw new Error(`image ${r.status}: ${(await r.text()).slice(0, 300)}`);
const j = await r.json();
const d = (j.data || [])[0] || {};
const url = d.b64_json ? `data:image/png;base64,${d.b64_json}` : d.url;
if (!url) throw new Error("no image in response");
// NanoGPT returns the exact figures: { data:[{b64_json}], cost, paymentSource, remainingBalance }
const exact = typeof j.cost === "number" && j.cost > 0;
const cost = exact ? j.cost : IMG_PRICE_EST;
const balance = typeof j.remainingBalance === "number" ? j.remainingBalance : null;
return { url, cost, exact, balance };
}
async function renderComic(opts = {}) {
const key = getKey(); if (!key) return;
if (active && files[active] !== undefined) files[active] = $("editor").value; // commit edits
const cfg = parseCfg();
const panels = currentPanels();
if (!panels.length) { setImgStatus("No panels — add a <code>panels/*.json</code> file.", "dim"); return; }
const { prompt, dropped } = composePagePrompt(cfg, panels);
refreshPromptPreview();
hasRendered = true;
const nonce = opts.force ? ++takeNonce : 0;
const h = await promptHash(JSON.stringify({ m: cfg.model, s: cfg.size, p: prompt, nonce }));
const myToken = ++renderToken;
const warn = dropped ? ` <span class="err">· ${dropped} panel(s) trimmed to fit ${PROMPT_LIMIT} chars</span>` : "";
if (imageCache[h]) { showImage(imageCache[h]); idleImgStatus(); if (dropped) setImgStatus($("imgbar").innerHTML + warn); return; }
showLoading(true, `drawing the page with ${cfg.model || DEFAULT_MODEL_IMG} · one render (${cfg.size || DEFAULT_SIZE})`);
setImgStatus(`<span class="spin">◐</span> one <b>${cfg.model || DEFAULT_MODEL_IMG}</b> render · ${panels.length} panels → one ${cfg.size || DEFAULT_SIZE} page…${warn}`);
try {
const { url, cost, exact, balance } = await genImage(prompt, cfg, key, nonce);
imageCache[h] = url;
if (myToken !== renderToken) return; // superseded by a newer render
imgStats.count++; imgStats.cost += cost; if (!exact) imgStats.exact = false;
if (balance != null) lastBalance = balance;
showImage(url);
idleImgStatus();
if (dropped) setImgStatus($("imgbar").innerHTML + warn);
} catch (e) {
if (myToken === renderToken) setImgStatus(`⚠ image error: ${e.message}`, "err");
} finally {
if (myToken === renderToken) showLoading(false);
}
}
let liveTimer = null;
function scheduleLive() {
if (!$("liveedit").checked || !hasRendered) return; // never auto-spend before the first explicit render
clearTimeout(liveTimer);
liveTimer = setTimeout(() => renderComic(), 1000);
}
$("render").addEventListener("click", () => renderComic());
$("newtake").addEventListener("click", () => renderComic({ force: true }));
$("liveedit").addEventListener("change", () => { if ($("liveedit").checked) scheduleLive(); });
// ---------- export the rendered page as a PNG ----------
$("export").addEventListener("click", () => {
if (!currentImage) { setImgStatus("Nothing to export yet — render the page first.", "dim"); return; }
const a = document.createElement("a");
a.href = currentImage; a.download = "comic-page.png";
document.body.appendChild(a); a.click(); a.remove();
});
// ---------- click the page → fullscreen viewer ----------
function openZoom() {
if (!currentImage) return;
$("zoomimg").src = currentImage;
$("zoom").classList.add("open"); $("zoom").classList.remove("actual");
$("zoomclose").style.display = "";
}
function closeZoom() { $("zoom").classList.remove("open", "actual"); $("zoomclose").style.display = "none"; }
$("page").addEventListener("click", openZoom);
$("zoomclose").addEventListener("click", closeZoom);
$("zoom").addEventListener("click", (e) => { if (e.target === $("zoom")) closeZoom(); }); // click the backdrop
$("zoomimg").addEventListener("click", (e) => { e.stopPropagation(); $("zoom").classList.toggle("actual"); }); // fit ⇄ actual size
document.addEventListener("keydown", (e) => { if (e.key === "Escape" && $("zoom").classList.contains("open")) closeZoom(); });
// ---------- diff rendering ----------
let curPhase = "";
function appendText(phase, chunk) {
if (!phase.startsWith("Generating")) return; // apply streams in parallel; show meter, not text
const pane = $("diff");
if (phase !== curPhase) { curPhase = phase; pane.textContent = ""; }
pane.textContent += chunk; pane.scrollTop = pane.scrollHeight;
}
function renderDiff(diff) {
$("diff").innerHTML = "";
if (!diff.trim()) { $("diff").textContent = "(no diff produced)"; return; }
for (const line of diff.split("\n")) {
const span = document.createElement("span");
span.textContent = line + "\n";
if (/^\+\+\+|^---|^@@|^diff |^a\/|^b\//.test(line)) span.className = "hdr";
else if (line.startsWith("+")) span.className = "add";
else if (line.startsWith("-")) span.className = "del";
$("diff").appendChild(span);
}
}
function showChanges(added, removed, changed) {
const c = $("changes"); c.innerHTML = "";
const part = (cls, label, arr) => { if (!arr.length) return; const s = document.createElement("span"); s.className = cls; s.textContent = `${label} ${arr.join(", ")} `; c.appendChild(s); };
part("a", "+ added", added); part("r", "- removed", removed); part("c", "~ updated", changed);
if (!added.length && !removed.length && !changed.length) c.textContent = "No files changed.";
}
// ---------- run: diff → smartapply → reconcile → single render ----------
async function run() {
const key = getKey(); if (!key) return;
if (active && files[active] !== undefined) files[active] = $("editor").value; // commit edits
undoSnapshot = JSON.parse(JSON.stringify(files));
$("run").disabled = true; $("undo").disabled = true; curPhase = ""; $("diff").textContent = ""; $("changes").textContent = "";
prog.inDone = prog.outDone = prog.cost = prog.liveIn = prog.liveOut = prog.liveCost = 0; paintUsage();
$("progress").style.display = "block"; document.querySelector("#progress .spin").style.display = "";
$("livelabel").textContent = ""; $("phase").textContent = "starting…";
const t0 = performance.now();
const timer = setInterval(() => { $("elapsed").textContent = ((performance.now() - t0) / 1000).toFixed(1); }, 100);
try {
const diff = await generateDiff(buildEnvironment(files), $("goal").value, { apiKey: key, model: MODEL, callLlm: streamingCallLlm("Generating diff") });
renderDiff(diff);
const parsed = parseDiffPerFile(diff);
if (!diff.trim() || !parsed.length) {
$("changes").textContent = "⚠ The model returned no applicable diff. Try rephrasing the goal.";
} else {
const applyLlm = streamingCallLlm("Applying diff");
const before = { ...files };
const updated = await smartapply(diff, files, {
apiKey: key, model: APPLY,
callLlmForApply: (p, o, d, m, o2) => callLlmForApply(p, o, d, m, { ...o2, callLlm: applyLlm }),
});
const beforeKeys = new Set(Object.keys(before)), afterKeys = new Set(Object.keys(updated));
const added = [...afterKeys].filter((k) => !beforeKeys.has(k));
const removed = [...beforeKeys].filter((k) => !afterKeys.has(k));
const changed = [...afterKeys].filter((k) => beforeKeys.has(k) && before[k] !== updated[k]);
files = updated;
if (active == null || files[active] === undefined) active = fileOrder()[0] || null;
renderTabs(); loadEditor(); refreshPromptPreview();
showChanges(added, removed, changed);
$("undo").disabled = false;
if ($("liveedit").checked) renderComic(); // organize the new panels → one render
}
$("phase").textContent = "done"; document.querySelector("#progress .spin").style.display = "none";
} catch (e) {
$("changes").textContent = "Error: " + e.message;
$("progress").style.display = "none";
} finally {
clearInterval(timer); $("run").disabled = false;
}
}
$("run").addEventListener("click", run);
$("goal").addEventListener("keydown", (e) => { if (e.key === "Enter") { e.preventDefault(); if (!$("run").disabled) run(); } });
$("undo").addEventListener("click", () => {
if (!undoSnapshot) return;
files = undoSnapshot; undoSnapshot = null;
if (active == null || files[active] === undefined) active = fileOrder()[0] || null;
renderTabs(); loadEditor(); refreshPromptPreview();
if (hasRendered) renderComic();
$("undo").disabled = true; $("changes").textContent = "↶ reverted to the previous version.";
});
// ---------- boot ----------
(async () => {
renderModelRow("diff"); renderModelRow("apply");
try { await handleRedirect(); } catch (e) { $("status").textContent = "sign-in error: " + e.message; }
renderAuth();
files = await loadSeed();
active = fileOrder().includes("panels/01-ignition.json") ? "panels/01-ignition.json" : (fileOrder()[0] || null);
renderTabs(); loadEditor(); refreshPromptPreview();
idleImgStatus();
loadModels();
})();
</script>
</body>
</html>