Repository navigation
Expand file tree
/
Copy pathpage-pcb.js
More file actions
3112 lines (2898 loc) · 145 KB
/
Copy pathpage-pcb.js
File metadata and controls
3112 lines (2898 loc) · 145 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
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
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { initNav, renderSourcesFooter, loadMeta } from './common.js?v=47'
// Fuse.js is loaded LAZILY (see ensureFuse) instead of a top-level CDN import.
// A static `import ... from <CDN>` that fails to fetch kills the ENTIRE module
// (page goes blank). Lazy + try/catch keeps the tool working if the CDN is
// unreachable — only fuzzy chip-search degrades.
initNav('pcb') // no-op: app shell has no #nav
renderSourcesFooter() // no-op: app shell has no footer
loadMeta() // best-effort metadata fetch
// ── App shell wiring (modal / drawer / banner / first-run) ────────
const shell = {
modal: document.getElementById('modal-settings'),
modalBackdrop: document.getElementById('modal-backdrop'),
btnSettings: document.getElementById('btn-settings'),
btnCloseSet: document.getElementById('btn-close-settings'),
drawer: document.getElementById('drawer-help'),
btnHelp: document.getElementById('btn-help'),
btnCloseHelp: document.getElementById('btn-close-help'),
banner: document.getElementById('banner-quality'),
btnDismissBan: document.getElementById('btn-dismiss-banner'),
modelLabel: document.getElementById('app-model-label'),
fileLabel: document.getElementById('app-file-label'),
imagePane: document.querySelector('.app-image-pane'),
detCount: document.getElementById('det-count'),
}
function openModal() { if (shell.modal) shell.modal.style.display = 'flex' }
function closeModal() { if (shell.modal) shell.modal.style.display = 'none' }
shell.btnSettings?.addEventListener('click', openModal)
shell.btnCloseSet?.addEventListener('click', closeModal)
shell.modalBackdrop?.addEventListener('click', closeModal)
window.addEventListener('keydown', e => {
if (e.key === 'Escape' && shell.modal?.style.display === 'flex') closeModal()
})
function openDrawer() { if (shell.drawer) shell.drawer.style.display = '' }
function closeDrawer() { if (shell.drawer) shell.drawer.style.display = 'none' }
shell.btnHelp?.addEventListener('click', openDrawer)
shell.btnCloseHelp?.addEventListener('click', closeDrawer)
// One-time image-quality banner — appears unless previously dismissed.
const BANNER_LS = 'eol-pcb-banner-dismissed-v1'
if (shell.banner) {
try {
if (!localStorage.getItem(BANNER_LS)) shell.banner.style.display = ''
} catch { shell.banner.style.display = '' }
}
shell.btnDismissBan?.addEventListener('click', () => {
if (shell.banner) shell.banner.style.display = 'none'
try { localStorage.setItem(BANNER_LS, '1') } catch {}
})
function updateModelLabel() {
if (!shell.modelLabel) return
const p = PROVIDERS?.[state.provider]
if (!p) return
if (p.needsKey && !state.apiKey) {
shell.modelLabel.textContent = 'Set up'
shell.btnSettings?.classList.add('app-iconbtn--attention')
} else {
shell.modelLabel.textContent = `${p.label} · ${state.model || p.defaultModel}`
shell.btnSettings?.classList.remove('app-iconbtn--attention')
}
}
function updateFileLabel(name, w, h) {
if (!shell.fileLabel) return
if (!name) { shell.fileLabel.textContent = ''; return }
shell.fileLabel.textContent = w && h ? `${name} · ${w}×${h}` : name
}
// ── Providers ────────────────────────────────────────────────────────
const PROVIDERS = {
anthropic: {
label: 'Anthropic',
keyLabel: 'sk-ant-…',
needsKey: true,
help: 'Get a key at <a href="https://console.anthropic.com/" target="_blank" rel="noopener">console.anthropic.com</a>. Sent to <code>api.anthropic.com</code>. Paid per request.',
models: [
{ id: 'claude-opus-4-7', label: 'Opus 4.7 (best accuracy)' },
{ id: 'claude-sonnet-4-6', label: 'Sonnet 4.6 (faster, cheaper)' },
{ id: 'claude-haiku-4-5-20251001', label: 'Haiku 4.5 (fastest)' },
],
defaultModel: 'claude-sonnet-4-6',
},
gemini: {
label: 'Google Gemini',
keyLabel: 'AIza…',
needsKey: true,
help: 'Free key at <a href="https://aistudio.google.com/app/apikey" target="_blank" rel="noopener">aistudio.google.com/app/apikey</a>. Sent to <code>generativelanguage.googleapis.com</code>. Free tier: ~15 req/min on Flash.',
models: [
{ id: 'gemini-2.5-pro', label: 'Gemini 2.5 Pro (best)' },
{ id: 'gemini-2.5-flash', label: 'Gemini 2.5 Flash (fast, free)' },
{ id: 'gemini-2.0-flash', label: 'Gemini 2.0 Flash (cheapest)' },
],
defaultModel: 'gemini-2.5-flash',
},
ollama: {
label: 'Ollama',
keyLabel: 'http://localhost:11434',
needsKey: false,
help: 'Install <a href="https://ollama.com/" target="_blank" rel="noopener">Ollama</a>, then <code>ollama pull llama3.2-vision</code>. Start with <code>OLLAMA_ORIGINS="*" ollama serve</code> so the browser can reach it. Override the host below if not on localhost.',
models: [
{ id: 'llama3.2-vision', label: 'llama3.2-vision (11B)' },
{ id: 'llama3.2-vision:90b', label: 'llama3.2-vision:90b (huge)' },
{ id: 'llava', label: 'llava (older, lighter)' },
{ id: 'moondream', label: 'moondream (tiny, fast)' },
],
defaultModel: 'llama3.2-vision',
},
}
// ── State ─────────────────────────────────────────────────────────────
const state = {
provider: 'gemini',
apiKey: '',
model: '',
ollamaHost: 'http://localhost:11434',
imageDataUrl: null,
imageMime: 'image/png',
detections: [],
imgNatural: { w: 0, h: 0 },
pdfDoc: null, // pdf.js document if user uploaded a PDF
pdfPage: 1, // currently rendered page (1-indexed)
pdfPageCount: 0,
lastRun: null, // {provider, model, when, durationMs, tokensIn, tokensOut, cost} for reproducibility stamp
rawModelText: '', // last raw model response text
palette: 'default', // 'default' | 'cb' (colour-blind safe)
selectedDetectionId: null, // for keyboard nav
view: { x: 0, y: 0, scale: 1 }, // pan/zoom transform on the image
editMode: false, // when true, dragging a handle resizes bbox
extraImages: [], // additional images (top + bottom + close-ups) [{dataUrl, mime, label}]
ocrHint: null, // text returned by the OCR pre-pass, fed into the main prompt
}
const els = {
provRadios: [...document.querySelectorAll('input[name="provider"]')],
provHelp: document.getElementById('provider-help'),
apiKey: document.getElementById('api-key'),
modelSel: document.getElementById('model-select'),
saveKey: document.getElementById('save-key'),
clearKey: document.getElementById('clear-key'),
keyStatus: document.getElementById('key-status'),
drop: document.getElementById('drop-zone'),
file: document.getElementById('file-input'),
controls: document.getElementById('pcb-controls'),
analyze: document.getElementById('analyze-btn'),
reset: document.getElementById('reset-btn'),
optPins: document.getElementById('opt-pins'),
optAttacks: document.getElementById('opt-attacks'),
optSchem: document.getElementById('opt-schematic'),
optConf: document.getElementById('opt-conf'),
optConfVal: document.getElementById('opt-conf-val'),
pdfPages: document.getElementById('pdf-pages'),
pdfPrev: document.getElementById('pdf-prev'),
pdfNext: document.getElementById('pdf-next'),
pdfPageNum: document.getElementById('pdf-page-num'),
resultSec: document.getElementById('pcb-result-section'),
image: document.getElementById('pcb-image'),
canvas: document.getElementById('pcb-canvas'),
status: document.getElementById('pcb-status'),
panel: document.getElementById('pcb-panel'),
}
// ── Provider + key handling ─────────────────────────────────────────
const PROVIDER_LS = 'eol-pcb-provider'
const SESSION_ONLY_LS = 'eol-pcb-session-only' // flag stays in localStorage
const keyLsFor = p => `eol-pcb-key-${p}`
const modelLsFor = p => `eol-pcb-model-${p}`
const OLLAMA_HOST_LS = 'eol-pcb-ollama-host'
// Pick the storage backend for KEYS based on the session-only toggle.
// Everything else (provider preference, model selection, palette) stays in
// localStorage — those aren't secrets.
function keyStore() {
try { return localStorage.getItem(SESSION_ONLY_LS) === '1' ? sessionStorage : localStorage }
catch { return localStorage }
}
function getKey(p) { try { return keyStore().getItem(keyLsFor(p)) || '' } catch { return '' } }
function setKey(p, v) {
try {
// Always clear from the OTHER store so switching modes doesn't leave a stale key behind.
localStorage.removeItem(keyLsFor(p))
sessionStorage.removeItem(keyLsFor(p))
if (v) keyStore().setItem(keyLsFor(p), v)
} catch {}
}
function setModelOptions(models, selected) {
// Escape model id+label — Ollama models come from /api/tags response and
// could in principle contain HTML/quote characters.
els.modelSel.innerHTML = models.map(m =>
`<option value="${escapeHtmlAttr(m.id)}">${escapeHtml(m.label)}</option>`).join('')
if (selected && models.some(m => m.id === selected)) els.modelSel.value = selected
else if (models.length) els.modelSel.value = models[0].id
}
function applyProviderUI() {
const p = PROVIDERS[state.provider]
els.provHelp.innerHTML = p.help
setModelOptions(p.models, state.model || p.defaultModel)
// Key input behavior
if (p.needsKey) {
els.apiKey.type = 'password'
els.apiKey.placeholder = p.keyLabel
els.apiKey.value = state.apiKey
els.apiKey.disabled = false
} else {
// Ollama: reuse the input for the host URL instead.
els.apiKey.type = 'text'
els.apiKey.placeholder = p.keyLabel
els.apiKey.value = state.ollamaHost
els.apiKey.disabled = false
}
// Status line
if (p.needsKey) {
if (state.apiKey) {
els.keyStatus.textContent = `Key loaded (${state.apiKey.slice(0, 10)}…) for ${p.label}. Saved in this browser only.`
els.keyStatus.className = 'pcb-keystatus pcb-keystatus--ok'
} else {
els.keyStatus.textContent = `No ${p.label} key set. Analysis will fail until you save one.`
els.keyStatus.className = 'pcb-keystatus'
}
} else {
els.keyStatus.textContent = `Ollama host: ${state.ollamaHost}. Probing for installed models…`
els.keyStatus.className = 'pcb-keystatus'
refreshOllamaModels()
}
// Reflect provider+model in the header
updateModelLabel()
// Enable/disable Analyze button based on whether we now have an image AND key
refreshAnalyzeEnabled()
}
function refreshAnalyzeEnabled() {
const p = PROVIDERS[state.provider]
const haveKey = !p.needsKey || !!state.apiKey
const haveImg = !!state.imageDataUrl
if (els.analyze) els.analyze.disabled = !(haveKey && haveImg)
}
async function refreshOllamaModels() {
const host = (state.ollamaHost || 'http://localhost:11434').replace(/\/+$/, '')
const fallback = PROVIDERS.ollama.models
try {
const res = await fetch(host + '/api/tags', { method: 'GET' })
if (!res.ok) throw new Error(`HTTP ${res.status}`)
const data = await res.json()
const installed = (data.models || []).map(m => ({ id: m.name, label: m.name + (m.size ? ` (${(m.size / 1e9).toFixed(1)} GB)` : '') }))
if (!installed.length) {
els.keyStatus.innerHTML = `Connected to <code>${escapeHtml(host)}</code> but no models installed. Run: <code>ollama pull llama3.2-vision</code>`
els.keyStatus.className = 'pcb-keystatus'
setModelOptions(fallback, state.model)
return
}
setModelOptions(installed, state.model)
els.keyStatus.innerHTML = `Connected to <code>${escapeHtml(host)}</code> · ${installed.length} model${installed.length === 1 ? '' : 's'} installed. (Use a vision model like <code>llama3.2-vision</code> for PCB analysis.)`
els.keyStatus.className = 'pcb-keystatus pcb-keystatus--ok'
} catch (e) {
setModelOptions(fallback, state.model)
const origin = location.origin
const cmd = `OLLAMA_ORIGINS="${origin},http://localhost:*" ollama serve`
els.keyStatus.innerHTML = `Cannot reach Ollama at <code>${escapeHtml(host)}</code>. Likely either not running, or CORS is blocking this origin. Restart Ollama with:<br><code>${escapeHtml(cmd)}</code>`
els.keyStatus.className = 'pcb-keystatus pcb-keystatus--err'
}
}
function loadProviderState() {
try {
state.provider = localStorage.getItem(PROVIDER_LS) || 'gemini'
if (!PROVIDERS[state.provider]) state.provider = 'gemini'
state.apiKey = getKey(state.provider)
state.model = localStorage.getItem(modelLsFor(state.provider)) || PROVIDERS[state.provider].defaultModel
state.ollamaHost = localStorage.getItem(OLLAMA_HOST_LS) || 'http://localhost:11434'
} catch {}
// Reflect the radio
for (const r of els.provRadios) r.checked = (r.value === state.provider)
// Reflect the session-only checkbox
const sessOpt = document.getElementById('opt-session-only')
if (sessOpt) sessOpt.checked = (() => { try { return localStorage.getItem(SESSION_ONLY_LS) === '1' } catch { return false } })()
applyProviderUI()
}
for (const r of els.provRadios) {
r.addEventListener('change', () => {
if (!r.checked) return
state.provider = r.value
try { localStorage.setItem(PROVIDER_LS, state.provider) } catch {}
// Reload per-provider key + model from storage
state.apiKey = getKey(state.provider)
state.model = localStorage.getItem(modelLsFor(state.provider)) || PROVIDERS[state.provider].defaultModel
applyProviderUI()
})
}
els.saveKey.addEventListener('click', () => {
const v = els.apiKey.value.trim()
const p = PROVIDERS[state.provider]
state.model = els.modelSel.value
try {
if (p.needsKey) {
state.apiKey = v
setKey(state.provider, v)
} else {
state.ollamaHost = v || 'http://localhost:11434'
localStorage.setItem(OLLAMA_HOST_LS, state.ollamaHost)
}
localStorage.setItem(modelLsFor(state.provider), state.model)
} catch {}
applyProviderUI()
})
els.clearKey.addEventListener('click', () => {
const p = PROVIDERS[state.provider]
if (p.needsKey) {
state.apiKey = ''
setKey(state.provider, '')
} else {
state.ollamaHost = 'http://localhost:11434'
try { localStorage.removeItem(OLLAMA_HOST_LS) } catch {}
}
applyProviderUI()
})
els.modelSel.addEventListener('change', () => {
state.model = els.modelSel.value
try { localStorage.setItem(modelLsFor(state.provider), state.model) } catch {}
updateCostPreview()
})
loadProviderState()
// Reflect provider/model in the header label, and open Settings on first
// run if no key is saved for any cloud provider.
queueMicrotask(() => {
updateModelLabel()
try {
const anyKey = ['anthropic', 'gemini'].some(p => !!getKey(p))
if (!anyKey && state.provider !== 'ollama') openModal()
} catch {}
})
// Session-only toggle: when enabled, keys move to sessionStorage and are
// gone when the tab closes. When disabled, keys move back to localStorage.
const sessionOpt = document.getElementById('opt-session-only')
sessionOpt?.addEventListener('change', () => {
const want = sessionOpt.checked
// Capture current keys, flip the flag, write keys back through the new
// backend (so we don't lose data when switching modes).
const snap = {}
for (const p of Object.keys(PROVIDERS)) snap[p] = getKey(p)
try { localStorage.setItem(SESSION_ONLY_LS, want ? '1' : '0') } catch {}
for (const [p, v] of Object.entries(snap)) setKey(p, v)
state.apiKey = getKey(state.provider)
applyProviderUI()
const msg = want
? 'Keys moved to sessionStorage — they will be cleared when you close this tab.'
: 'Keys moved back to localStorage — persist across tabs/sessions.'
if (els.keyStatus) {
els.keyStatus.textContent = msg
els.keyStatus.className = 'pcb-keystatus pcb-keystatus--ok'
}
})
// "Clear all stored keys" — wipes every eol-pcb-* entry, useful as a
// concrete demonstration that the only place keys exist is this browser.
const clearAllBtn = document.getElementById('clear-all-keys')
if (clearAllBtn) {
clearAllBtn.addEventListener('click', () => {
try {
let total = 0
for (const store of [localStorage, sessionStorage]) {
const toRemove = []
for (let i = 0; i < store.length; i++) {
const k = store.key(i)
if (k && k.startsWith('eol-pcb-')) toRemove.push(k)
}
toRemove.forEach(k => store.removeItem(k))
total += toRemove.length
}
state.apiKey = ''
state.ollamaHost = 'http://localhost:11434'
applyProviderUI()
els.keyStatus.textContent = `Cleared ${total} stored item${total === 1 ? '' : 's'} from both localStorage and sessionStorage. Nothing left for this site.`
els.keyStatus.className = 'pcb-keystatus pcb-keystatus--ok'
} catch (e) {
els.keyStatus.textContent = 'Failed to clear: ' + (e.message || e)
els.keyStatus.className = 'pcb-keystatus pcb-keystatus--err'
}
})
}
// ── Image upload (file picker, drag-drop, paste) ─────────────────────
els.drop.addEventListener('click', () => els.file.click())
els.file.addEventListener('change', e => {
const files = [...(e.target.files || [])]
if (files.length) handleMultipleFiles(files)
})
els.drop.addEventListener('dragover', e => { e.preventDefault(); els.drop.classList.add('pcb-drop--hover') })
els.drop.addEventListener('dragleave', () => els.drop.classList.remove('pcb-drop--hover'))
els.drop.addEventListener('drop', e => {
e.preventDefault()
els.drop.classList.remove('pcb-drop--hover')
const files = [...(e.dataTransfer.files || [])]
if (files.length) handleMultipleFiles(files)
})
async function handleMultipleFiles(files) {
// First file becomes the primary image; the rest are stashed as extra
// context images to be sent alongside in the main analyze call.
state.extraImages = []
await handleFile(files[0])
for (let i = 1; i < files.length; i++) {
const f = files[i]
if (!f.type.startsWith('image/')) continue
const r = await resizeImage(f, 1568)
state.extraImages.push({ dataUrl: r.dataUrl, mime: r.mime, label: f.name, w: r.w, h: r.h })
}
renderMultiStrip()
}
function renderMultiStrip() {
const strip = document.getElementById('multi-image-strip')
if (!strip) return
if (!state.imageDataUrl && !state.extraImages.length) {
strip.style.display = 'none'; strip.innerHTML = ''; return
}
const primary = state.imageDataUrl
? `<div class="pcb-multi-item pcb-multi-primary" title="Primary image (analysis runs on this)">
<img src="${primary_thumb_or_dataurl(state.imageDataUrl)}" alt="">
<span class="pcb-multi-label">primary</span>
</div>` : ''
const extras = state.extraImages.map((e, i) => `
<div class="pcb-multi-item" data-idx="${i}" title="${escapeHtml(e.label)} (context image)">
<img src="${e.dataUrl}" alt="">
<span class="pcb-multi-label">${escapeHtml(e.label)}</span>
<button class="pcb-multi-remove" data-idx="${i}" title="Remove">×</button>
</div>`).join('')
strip.innerHTML = primary + extras
strip.style.display = ''
strip.querySelectorAll('.pcb-multi-remove').forEach(btn => {
btn.addEventListener('click', e => {
const i = parseInt(btn.dataset.idx, 10)
state.extraImages.splice(i, 1)
renderMultiStrip()
})
})
}
function primary_thumb_or_dataurl(u) {
// We'd ideally generate a small thumb; for simplicity just reuse the original.
return u
}
window.addEventListener('paste', e => {
const items = e.clipboardData && e.clipboardData.items
if (!items) return
for (const it of items) {
if (it.type.startsWith('image/')) {
const f = it.getAsFile()
if (f) { handleFile(f); break }
}
}
})
async function handleFile(file) {
const isPdf = file.type === 'application/pdf' || /\.pdf$/i.test(file.name)
if (!file.type.startsWith('image/') && !isPdf) {
setStatus('error', `Unsupported file type: ${file.type || 'unknown'}. Use an image or PDF.`)
return
}
// Reset prior PDF state
state.pdfDoc = null
state.pdfPage = 1
state.pdfPageCount = 0
els.pdfPages.style.display = 'none'
setStatus('info', `Loading ${file.name} (${(file.size / 1024).toFixed(0)} KB)…`)
let dataUrl, mime, w, h
if (isPdf) {
try {
const rendered = await loadAndRenderPdf(file, 1)
dataUrl = rendered.dataUrl; mime = rendered.mime; w = rendered.w; h = rendered.h
} catch (e) {
setStatus('error', 'PDF render failed: ' + (e.message || e))
return
}
} else {
const r = await resizeImage(file, 1568)
dataUrl = r.dataUrl; mime = r.mime; w = r.w; h = r.h
}
state.imageDataUrl = dataUrl
state.imageMime = mime
state.imgNatural = { w, h }
els.image.src = dataUrl
els.resultSec.style.display = ''
state.detections = []
state.view = { x: 0, y: 0, scale: 1 } // fresh view per image
applyView()
renderPanel()
await new Promise(r => { els.image.onload = r })
// Wait one extra frame so CSS layout settles before we measure.
await new Promise(r => requestAnimationFrame(r))
fitCanvas()
drawOverlay()
const suffix = isPdf && state.pdfPageCount > 1
? ` (PDF page ${state.pdfPage} of ${state.pdfPageCount})`
: isPdf ? ' (PDF)' : ''
setStatus('ok', `Loaded ${w}×${h}${suffix}. Click "Analyze image" to run detection.`)
updateCostPreview()
updateFileLabel(file.name, w, h)
shell.imagePane?.classList.add('has-image')
refreshAnalyzeEnabled()
// Reset size slider to fit
if (sizeSlider) { sizeSlider.value = 100; if (sizeLabel) sizeLabel.textContent = '100%' }
els.image.style.width = ''
els.image.style.height = ''
}
function updateCostPreview() {
const est = estimateUpcomingCost()
if (!est) { els.analyze.textContent = 'Analyze image'; return }
if (state.provider === 'ollama') {
els.analyze.textContent = 'Analyze image (local · free)'
} else if (est.cost != null) {
els.analyze.textContent = `Analyze image (~$${est.cost.toFixed(4)}, ~${est.tokensIn} tokens in)`
} else {
els.analyze.textContent = 'Analyze image'
}
}
// ── PDF support ──────────────────────────────────────────────────────
let pdfjsLib = null
async function ensurePdfJs() {
if (pdfjsLib) return pdfjsLib
const mod = await import('https://cdn.jsdelivr.net/npm/pdfjs-dist@4.7.76/build/pdf.min.mjs')
mod.GlobalWorkerOptions.workerSrc = 'https://cdn.jsdelivr.net/npm/pdfjs-dist@4.7.76/build/pdf.worker.min.mjs'
pdfjsLib = mod
return mod
}
// Fuse.js (fuzzy chip-name search) — lazy + non-fatal, mirrors ensurePdfJs.
let FuseLib = null
async function ensureFuse() {
if (FuseLib) return FuseLib
const mod = await import('https://cdn.jsdelivr.net/npm/fuse.js@7/dist/fuse.mjs')
FuseLib = mod.default || mod.Fuse || mod
return FuseLib
}
async function loadAndRenderPdf(file, pageNum) {
const lib = await ensurePdfJs()
const buf = await file.arrayBuffer()
const doc = await lib.getDocument({ data: buf }).promise
state.pdfDoc = doc
state.pdfPageCount = doc.numPages
return renderPdfPage(pageNum)
}
async function renderPdfPage(pageNum) {
const doc = state.pdfDoc
if (!doc) throw new Error('No PDF loaded')
const n = Math.max(1, Math.min(doc.numPages, pageNum))
state.pdfPage = n
const page = await doc.getPage(n)
// Target ~1568px on the long edge for parity with image path.
const baseVp = page.getViewport({ scale: 1 })
const longEdge = Math.max(baseVp.width, baseVp.height)
const scale = Math.min(3, 1568 / longEdge) // cap 3x to avoid huge memory
const vp = page.getViewport({ scale })
const c = document.createElement('canvas')
c.width = Math.round(vp.width)
c.height = Math.round(vp.height)
const ctx = c.getContext('2d')
// White background — many PDF schematics use transparent backgrounds.
ctx.fillStyle = '#fff'
ctx.fillRect(0, 0, c.width, c.height)
await page.render({ canvasContext: ctx, viewport: vp }).promise
let mime = 'image/png'
let dataUrl = c.toDataURL(mime)
if (dataUrl.length > 4_500_000) {
mime = 'image/jpeg'
dataUrl = c.toDataURL(mime, 0.9)
}
// Update page picker UI
if (doc.numPages > 1) {
els.pdfPages.style.display = ''
els.pdfPageNum.textContent = `${n} / ${doc.numPages}`
els.pdfPrev.disabled = n <= 1
els.pdfNext.disabled = n >= doc.numPages
} else {
els.pdfPages.style.display = 'none'
}
return { dataUrl, mime, w: c.width, h: c.height }
}
async function switchPdfPage(delta) {
if (!state.pdfDoc) return
const next = state.pdfPage + delta
if (next < 1 || next > state.pdfPageCount) return
setStatus('info', `Rendering page ${next}…`)
try {
const { dataUrl, mime, w, h } = await renderPdfPage(next)
state.imageDataUrl = dataUrl
state.imageMime = mime
state.imgNatural = { w, h }
els.image.src = dataUrl
state.detections = []
renderPanel()
await new Promise(r => { els.image.onload = r })
fitCanvas()
drawOverlay()
setStatus('ok', `Loaded page ${next}/${state.pdfPageCount} (${w}×${h}). Click "Analyze image" to run detection on this page.`)
} catch (e) {
setStatus('error', 'Render failed: ' + (e.message || e))
}
}
els.pdfPrev.addEventListener('click', () => switchPdfPage(-1))
els.pdfNext.addEventListener('click', () => switchPdfPage(+1))
function resizeImage(file, maxEdge) {
return new Promise((resolve, reject) => {
const img = new Image()
const reader = new FileReader()
reader.onload = () => { img.src = reader.result }
reader.onerror = reject
img.onload = () => {
const longest = Math.max(img.width, img.height)
const scale = longest > maxEdge ? maxEdge / longest : 1
const w = Math.round(img.width * scale)
const h = Math.round(img.height * scale)
const c = document.createElement('canvas')
c.width = w; c.height = h
const ctx = c.getContext('2d')
ctx.drawImage(img, 0, 0, w, h)
// PNG keeps text sharper; cap with JPEG if huge.
let mime = 'image/png'
let dataUrl = c.toDataURL(mime)
if (dataUrl.length > 4_500_000) {
mime = 'image/jpeg'
dataUrl = c.toDataURL(mime, 0.88)
}
resolve({ dataUrl, mime, w, h })
}
img.onerror = reject
reader.readAsDataURL(file)
})
}
// ── Confidence filter ────────────────────────────────────────────────
function confThreshold() {
const v = parseInt(els.optConf.value, 10)
return isNaN(v) ? 0 : v / 100
}
function visibleDetections() {
const t = confThreshold()
return state.detections.filter(d => (d.confidence == null ? 1 : d.confidence) >= t)
}
els.optConf.addEventListener('input', () => {
els.optConfVal.textContent = els.optConf.value + '%'
if (state.detections.length) { drawOverlay(); renderPanel() }
})
// ── Canvas overlay ───────────────────────────────────────────────────
function fitCanvas() {
// Critical: use offsetWidth/offsetHeight (layout box, NOT transformed)
// rather than getBoundingClientRect (which INCLUDES the container's CSS
// transform). Otherwise canvas size grows by scale-factor while sitting
// inside the same transformed container → markings drift off-image.
const w = els.image.offsetWidth || els.image.naturalWidth
const h = els.image.offsetHeight || els.image.naturalHeight
if (!w || !h) return
els.canvas.width = w
els.canvas.height = h
els.canvas.style.width = w + 'px'
els.canvas.style.height = h + 'px'
}
window.addEventListener('resize', () => { if (state.imageDataUrl) { fitCanvas(); drawOverlay() } })
// RGB tuples so rgba() composes cleanly. Avoid CSS hex+alpha — Canvas
// silently keeps the previous fillStyle on invalid strings.
const PALETTES = {
default: [
[221, 51, 51], [ 10, 168, 136], [ 51, 102, 204], [255, 102, 0],
[102, 51, 153], [196, 68, 102], [ 0, 136, 170], [136, 68, 102],
[179, 36, 36], [ 20, 134, 109],
],
// Wong palette — 8-colour set designed to be distinguishable for the
// common forms of colour-vision deficiency.
cb: [
[ 0, 114, 178], [213, 94, 0], [ 0, 158, 115], [204, 121, 167],
[ 86, 180, 233], [240, 228, 66], [230, 159, 0], [ 0, 0, 0],
],
}
const palette = () => PALETTES[state.palette] || PALETTES.default
const rgba = ([r, g, b], a) => `rgba(${r},${g},${b},${a})`
let drawOverlay = function (hoverId = null) {
const c = els.canvas
const ctx = c.getContext('2d')
ctx.clearRect(0, 0, c.width, c.height)
const W = c.width, H = c.height
ctx.font = '600 12px -apple-system,Segoe UI,sans-serif'
const vis = visibleDetections()
// If the model's bboxes are clearly garbage, don't draw them — overlay a
// clear explanation so the user understands the side-panel cards aren't
// tied to any real region.
if (vis.length >= 2 && bboxesAreBogus(vis)) {
const msg = 'Model returned invalid bounding boxes — see warning in the side panel. The cards on the right are still shown but cannot be located on the image.'
const padX = 14, padY = 12
const maxW = Math.min(W - 20, 520)
ctx.font = '600 13px -apple-system,Segoe UI,sans-serif'
// Word-wrap
const words = msg.split(' ')
const lines = []
let line = ''
for (const w of words) {
const test = line ? line + ' ' + w : w
if (ctx.measureText(test).width + padX * 2 > maxW) { lines.push(line); line = w }
else line = test
}
if (line) lines.push(line)
const lh = 18
const boxH = lines.length * lh + padY * 2
const boxW = Math.max(...lines.map(l => ctx.measureText(l).width)) + padX * 2
const x = (W - boxW) / 2
const y = (H - boxH) / 2
ctx.fillStyle = 'rgba(198, 40, 40, 0.92)'
ctx.fillRect(x, y, boxW, boxH)
ctx.fillStyle = '#fff'
lines.forEach((l, i) => ctx.fillText(l, x + padX, y + padY + lh * (i + 1) - 4))
return
}
vis.forEach((d, i) => {
const pal = palette()
const isEmpty = d.category === 'empty_footprint'
// Empty footprints always render in amber regardless of palette index —
// they are security warnings, not just another detection.
const rgb = isEmpty ? [245, 158, 11] : pal[i % pal.length]
const hovered = hoverId === d.id
const [x1, y1, x2, y2] = d.bbox
const x = x1 * W, y = y1 * H, w = (x2 - x1) * W, h = (y2 - y1) * H
// Attack-surface highlight: when a class is selected in the panel,
// emphasize its boxes and dim the rest so the class stands out.
const hlSet = state.surfaceHighlightIds
const emphasized = !!(hlSet && hlSet.has(d.id))
const dimmed = !!(hlSet && hlSet.size && !hlSet.has(d.id))
// Only tint on hover (~10% alpha) or emphasis. Default = stroke-only so the
// chip stays visible. Empty footprints always tint lightly to flag absence.
if (hovered || emphasized) {
ctx.fillStyle = rgba(rgb, emphasized ? 0.26 : (isEmpty ? 0.28 : 0.18))
ctx.fillRect(x, y, w, h)
} else if (isEmpty && !dimmed) {
ctx.fillStyle = rgba(rgb, 0.10)
ctx.fillRect(x, y, w, h)
}
ctx.strokeStyle = rgba(rgb, dimmed ? 0.18 : (hovered || emphasized ? 1 : 0.95))
ctx.lineWidth = emphasized ? 6 : (hovered ? 5 : 3)
if (isEmpty) ctx.setLineDash([10, 6])
ctx.strokeRect(x, y, w, h)
if (isEmpty) ctx.setLineDash([])
// Warning glyph in the top-right corner of an empty-footprint box
if (isEmpty) {
const glyph = '⚠'
ctx.font = 'bold 18px system-ui, sans-serif'
const gw = ctx.measureText(glyph).width + 8
const gh = 22
ctx.fillStyle = rgba(rgb, 1)
ctx.fillRect(x + w - gw, y, gw, gh)
ctx.fillStyle = '#fff'
ctx.fillText(glyph, x + w - gw + 4, y + gh - 5)
ctx.font = '13px system-ui, sans-serif'
}
// Small number badge in the top-left corner of the box. Clamp so it
// never exceeds 1/3 of the box, otherwise tiny detections get covered.
const num = String(i + 1)
const baseW = Math.max(18, ctx.measureText(num).width + 8)
const baseH = 16
const nw = Math.min(baseW, Math.max(10, w / 3))
const nh = Math.min(baseH, Math.max(10, h / 3))
ctx.fillStyle = rgba(rgb, 1)
ctx.fillRect(x, y, nw, nh)
if (nw >= 14 && nh >= 12) {
ctx.fillStyle = '#fff'
ctx.fillText(num, x + (nw - ctx.measureText(num).width) / 2, y + nh - 3)
}
// Full label only on hover, placed outside the box so it never covers
// the part. Fall back to inside if outside would clip.
if (hovered) {
const label = d.label || d.part_number || 'unknown'
const lw = ctx.measureText(label).width + 10
const lh = 18
const ly = y - lh - 2 < 0 ? (y + h + 2) : (y - lh - 2)
const lx = Math.min(x, W - lw - 2)
ctx.fillStyle = rgba(rgb, 0.95)
ctx.fillRect(lx, ly, lw, lh)
ctx.fillStyle = '#fff'
ctx.fillText(label, lx + 5, ly + 13)
}
})
}
els.canvas.addEventListener('mousemove', e => {
if (!state.detections.length) return
const rect = els.canvas.getBoundingClientRect()
const x = (e.clientX - rect.left) / rect.width
const y = (e.clientY - rect.top) / rect.height
const hit = visibleDetections().find(d => {
const [x1, y1, x2, y2] = d.bbox
return x >= x1 && x <= x2 && y >= y1 && y <= y2
})
drawOverlay(hit ? hit.id : null)
els.canvas.style.cursor = hit ? 'pointer' : 'default'
})
els.canvas.addEventListener('click', e => {
const rect = els.canvas.getBoundingClientRect()
const x = (e.clientX - rect.left) / rect.width
const y = (e.clientY - rect.top) / rect.height
const hit = visibleDetections().find(d => {
const [x1, y1, x2, y2] = d.bbox
return x >= x1 && x <= x2 && y >= y1 && y <= y2
})
if (hit) {
const card = document.getElementById('det-' + hit.id)
if (card) card.scrollIntoView({ behavior: 'smooth', block: 'center' })
highlightCard(hit.id)
}
})
function highlightCard(id) {
document.querySelectorAll('.det-row-card').forEach(el => el.classList.remove('det-row-card--active'))
const card = document.getElementById('det-' + id)
if (card) card.classList.add('det-row-card--active')
}
// ── Reset / status ───────────────────────────────────────────────────
els.reset.addEventListener('click', () => {
state.imageDataUrl = null
state.detections = []
els.image.src = ''
els.resultSec.style.display = 'none'
els.controls.style.display = 'none'
els.panel.innerHTML = '<div class="pcb-panel-empty">Detections will appear here once analysis completes.</div>'
setStatus('info', 'Idle.')
})
function setStatus(kind, msg) {
els.status.textContent = msg
els.status.className = 'pcb-canvas-status pcb-canvas-status--' + kind
}
// ── Analysis call ────────────────────────────────────────────────────
els.analyze.addEventListener('click', analyze)
async function analyze() {
const p = PROVIDERS[state.provider]
if (p.needsKey && !state.apiKey) {
setStatus('error', `No ${p.label} key. Paste one in step 1 and click Save.`)
return
}
if (!state.imageDataUrl) {
setStatus('error', 'No image loaded.')
return
}
els.analyze.disabled = true
// OCR pre-pass (optional)
const wantOcr = document.getElementById('opt-ocr')?.checked
if (wantOcr) {
setStatus('info', `OCR pre-pass: extracting silkscreen text…`)
state.ocrHint = await runOcrPrepass().catch(e => { console.warn('OCR pre-pass failed', e); return null })
if (state.ocrHint) setStatus('info', `OCR pre-pass returned ${state.ocrHint.split('\n').length} strings. Running main analysis…`)
} else {
state.ocrHint = null
}
setStatus('info', `Calling ${p.label} (${state.model})… vision analysis usually takes 10–40s.`)
const startedAt = Date.now()
// Token-saving optimization: downscale the image to 1024px on the long
// edge for the INITIAL detection pass. Bounding boxes don't suffer at
// this resolution; per-chip OCR is handled by re-OCR at native res
// later. Cuts image tokens ~50% on the most expensive call.
const fullImage = state.imageDataUrl
const fullMime = state.imageMime
try {
const srcImg = await loadImage(state.imageDataUrl)
const small = cropToDataUrl(srcImg, 0, 0, 1, 1, 1024)
state.imageDataUrl = small
state.imageMime = small.startsWith('data:image/png') ? 'image/png' : 'image/jpeg'
} catch (e) {
console.warn('Initial-pass downscale failed; using full-res:', e)
}
try {
let result
if (state.provider === 'anthropic') result = await callAnthropic()
else if (state.provider === 'gemini') result = await callGemini()
else result = await callOllama()
// Each callX returns either an array (legacy) or {detections, usage}.
const detections = Array.isArray(result) ? result : result.detections
const usage = Array.isArray(result) ? null : result.usage
state.detections = detections.map((d, i) => ({ ...d, id: i + 1 }))
state.lastRun = {
provider: state.provider,
providerLabel: p.label,
model: state.model,
when: new Date().toISOString(),
durationMs: Date.now() - startedAt,
tokensIn: usage?.input_tokens ?? null,
tokensOut: usage?.output_tokens ?? null,
cost: usage?.estimated_cost ?? null,
}
saveToHistory()
fitCanvas()
drawOverlay()
await renderPanel()
showToolbar()
setStatus('ok', `Done. ${state.detections.length} detection${state.detections.length === 1 ? '' : 's'} in ${((state.lastRun.durationMs)/1000).toFixed(1)}s${state.lastRun.cost ? ` · est. $${state.lastRun.cost.toFixed(4)}` : ''}.`)
// Optional accuracy boosters — opt-in checkboxes in Settings.
// Order matters: consensus replaces, tile pass adds, auto-re-OCR refines.
if (document.getElementById('opt-consensus')?.checked) {
await consensusPass()
}
if (document.getElementById('opt-tile-pass')?.checked) {
await tilePass()
}
if (document.getElementById('opt-auto-reocr')?.checked) {
await autoReOcrAll()
}
} catch (err) {
console.error(err)
setStatus('error', 'Failed: ' + (err.message || err))
} finally {
// Always restore full-res so subsequent boosters (re-OCR, tile pass,
// correction) work against the original detail.
state.imageDataUrl = fullImage
state.imageMime = fullMime
els.analyze.disabled = false
}
}
function buildPrompt() {
if (state._oneShotPrompt) return state._oneShotPrompt
const wantPins = els.optPins.checked
const wantAtk = els.optAttacks.checked
const isSchem = els.optSchem.checked
const wantValues = document.getElementById('opt-values')?.checked
const target = isSchem
? 'a schematic diagram (symbols, nets, reference designators)'
: 'a top-down photo of a populated printed circuit board'
const extraNote = (state.extraImages && state.extraImages.length)
? `\nNOTE: You have been given ${state.extraImages.length + 1} images of the same board (the first is the primary view, the rest are additional angles or close-ups labelled ${state.extraImages.map(e => `"${e.label}"`).join(', ')}). Use all of them together — a marking might be readable in only one view. All bboxes you return must be in coordinates of the PRIMARY (first) image.\n`
: ''
const ocrHintNote = state.ocrHint
? `\nHINT — OCR pre-pass extracted the following visible text strings from the primary image. Use these as ground-truth markings rather than guessing:\n${state.ocrHint}\n`
: ''
return `You are a hardware security analyst examining ${target}.${extraNote}${ocrHintNote}
Your job is to identify ONLY physical objects you can clearly SEE in the image:
- Integrated circuits (ICs) with a visible package outline
- Pin headers and connector blocks with visible pins
- Major connectors (USB, HDMI, Ethernet, etc.)
- Crystals / oscillator cans
- Visible debug pads or labelled test-point arrays (only if you can actually see and read the labels)
- SECURITY-RELEVANT DISCRETES (transistors, MOSFETs, diodes, crystals, inductors, key RC networks) — see explicit list below
- EMPTY / UNPOPULATED FOOTPRINTS — see dedicated section below (HIGH security priority)
BOUNDING BOX PRECISION — this is critical. Each bbox MUST tightly enclose the physical part:
- x1,y1 = top-left corner of the package outline (NOT including pin tails extending outside)
- x2,y2 = bottom-right corner of the package outline
- Tolerance: ±2% of image width on each edge. Boxes wandering off the chip by 10–15% are unacceptable.
- For ICs: enclose the dark plastic body, not the pin halo. For headers: enclose the plastic shroud + pins. For passives: tight 0402/0603 footprint only.
- Before emitting each bbox, mentally re-check: "does the rectangle I'm outputting actually contain the centre of this specific part?" If unsure, lower confidence rather than emit a sloppy box.
EMPTY / UNPOPULATED FOOTPRINTS — these are HIGH-VALUE hardware-security targets and MUST be flagged. An empty footprint = silkscreen outline + visible pads + NO component soldered on. Signatures to look for:
- A rectangular silkscreen outline (white box on green) with bare copper pads inside, no chip body.
- A row of through-holes silkscreened with a part designator (e.g. "J5", "JTAG", "DEBUG", "CN3") but no header soldered in.
- A footprint adjacent to a populated chip that was clearly intended to hold a sibling component (DNP — Do Not Populate).
- Test-point pads (labelled TP## or unlabelled gold dots) — list these as a cluster, not individually.
- A pair of unpopulated SOIC-8 pads near SPI flash → likely an alternate flash, secure element, or auth IC the manufacturer omitted.
- An empty crystal footprint near a populated SoC → suggests alternate clock-source configuration possible.
For each unpopulated footprint emit a detection with:
- category: "empty_footprint"
- label: descriptive guess (e.g. "Unpopulated debug header (probable UART)", "Unpopulated SOIC-8 (probable alternate flash)", "Unpopulated 2×5 header (probable JTAG)")
- part_number: any visible silkscreen designator (e.g. "J5", "U7", "DBG1") or ""
- confidence: typical 0.5–0.8 (you can SEE the footprint, but the intended part is a guess)
- attack_vectors: tailored to footprint type:
* Unpopulated debug header → "Solder a header here → likely yields UART/JTAG/SWD console (manufacturer depopulated for production)"
* Empty SOIC-8 near SPI flash → "Plant point: attacker could solder a malicious flash here, MITM the bus, or add a logic bomb"
* Empty SOT-23 footprint on signal line → "Plant point: implant a transistor or MOSFET for active fault injection / signal manipulation"
* Empty footprint with no obvious purpose → "Plant point: physical-implant attack surface — verify against BOM whether intentional DNP"