-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcase-lens.html
More file actions
1152 lines (1037 loc) · 53.6 KB
/
Copy pathcase-lens.html
File metadata and controls
1152 lines (1037 loc) · 53.6 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vibe Rounds - Case Lens — 8-Lens Critical Thinking Audit</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=IBM+Plex+Mono:wght@400;500;600&display=swap" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mammoth/1.6.0/mammoth.browser.min.js"></script>
<style>
:root{
--paper:#F7FAFB;
--card:#FFFFFF;
--ink:#0B2530;
--line:#DCE7EA;
--line-soft:#E9F1F3;
--accent:#0891B2;
--accent-dark:#0A6E85;
--accent-soft:#E3F4F8;
--alert:#C2410C;
--alert-soft:#FCE9DD;
--muted:#5B7480;
--tab-inactive:#EEF4F6;
--radius:10px;
--body-font:'Inter',sans-serif;
--mono:'IBM Plex Mono',monospace;
}
*{box-sizing:border-box;}
html,body{margin:0;padding:0;}
body{
background:var(--paper);
color:var(--ink);
font-family:var(--body-font);
font-size:15px;
line-height:1.5;
-webkit-font-smoothing:antialiased;
}
::selection{background:var(--accent-soft);}
a{color:var(--accent-dark);}
.wrap{max-width:960px;margin:0 auto;padding:28px 20px 80px;}
/* header */
header.top{
display:flex;align-items:center;justify-content:space-between;
padding-bottom:18px;margin-bottom:26px;border-bottom:1px solid var(--line-soft);
flex-wrap:wrap;gap:10px;
}
header.top .brand{display:flex;align-items:center;gap:10px;flex-wrap:wrap;}
header.top h1{font-weight:800;font-size:22px;margin:0;letter-spacing:-0.02em;color:var(--ink);}
header.top .rx{
font-weight:600;font-size:11.5px;color:#fff;
background:var(--accent);border-radius:20px;padding:4px 11px;letter-spacing:.01em;
}
header.top .top-right{display:flex;flex-direction:column;align-items:flex-end;gap:8px;}
header.top .tagline{font-size:12.5px;color:var(--muted);font-weight:500;}
.top-links{display:flex;gap:8px;flex-wrap:wrap;justify-content:flex-end;}
.top-links a{
display:inline-flex;align-items:center;gap:5px;font-size:12px;font-weight:700;
color:var(--accent-dark);background:var(--accent-soft);border:1px solid var(--line);
border-radius:999px;padding:6px 12px;text-decoration:none;
}
.top-links a:hover{background:var(--accent);color:#fff;border-color:var(--accent);}
.banner{
font-size:12.5px;color:var(--ink);border:1px solid var(--line-soft);
background:var(--accent-soft);padding:11px 14px;border-radius:var(--radius);margin-bottom:14px;
}
.banner strong{color:var(--accent-dark);}
.banner.warn{background:var(--alert-soft);border-color:#f0c8ac;}
.banner.warn strong{color:var(--alert);}
/* section labels — merged "block" look, collapsed by default */
.step{margin-bottom:20px;}
.step-label{
font-size:12.5px;letter-spacing:.08em;text-transform:uppercase;color:var(--ink);font-weight:700;
display:flex;align-items:center;gap:10px;margin-bottom:0;cursor:pointer;user-select:none;
background:var(--card);border:1px solid var(--line);border-radius:var(--radius) var(--radius) 0 0;
padding:14px 20px;transition:box-shadow .15s ease,border-color .15s ease,color .15s ease;
}
.step-label.collapsed{border-radius:var(--radius);}
.step-label:hover{color:var(--accent-dark);box-shadow:0 6px 16px -10px rgba(11,37,48,.3);}
.step-label .num{
width:24px;height:24px;border-radius:50%;background:var(--accent);color:#fff;
display:inline-flex;align-items:center;justify-content:center;font-size:12px;flex-shrink:0;font-weight:700;
}
.collapse-arrow{font-size:11px;margin-left:auto;transition:transform .15s ease;color:var(--muted);padding-left:8px;}
.step-label.collapsed .collapse-arrow{transform:rotate(-90deg);}
.card.collapsed{display:none;}
.card{
background:var(--card);
border:1px solid var(--line);border-top:none;
border-radius:0 0 var(--radius) var(--radius);
padding:22px 22px 20px;
box-shadow:0 1px 2px rgba(11,37,48,.04), 0 8px 24px -16px rgba(11,37,48,.08);
}
label{font-size:12.5px;color:var(--muted);display:block;margin-bottom:4px;font-weight:500;}
textarea, input[type=text], input[type=password], select{
width:100%;font-family:var(--body-font);font-size:14px;
background:var(--card);border:1px solid var(--line);border-radius:var(--radius);
padding:9px 11px;color:var(--ink);margin-bottom:12px;
}
textarea:focus, input:focus, select:focus, button:focus-visible{
outline:2px solid var(--accent);outline-offset:1px;
}
textarea{resize:vertical;min-height:110px;line-height:1.5;}
.hint{font-size:12px;color:var(--muted);margin-top:-6px;margin-bottom:10px;}
.hint.error{color:var(--alert);}
.hint.ok{color:var(--accent-dark);}
.case-input-row{margin-bottom:6px;padding:14px 14px 4px;background:var(--paper);border:1px solid var(--line-soft);border-radius:var(--radius);}
.case-input-col label{margin-bottom:6px;}
.link-detect{
display:flex;align-items:center;gap:10px;flex-wrap:wrap;
background:var(--accent-soft);border:1px solid var(--line);border-radius:var(--radius);
padding:9px 12px;margin:-4px 0 12px;font-size:12.5px;color:var(--accent-dark);font-weight:600;
}
.file-picker{display:flex;align-items:center;gap:10px;margin-bottom:12px;flex-wrap:wrap;}
.file-picker-name{font-size:12.5px;color:var(--muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:100%;}
.file-picker-name.set{color:var(--ink);font-weight:500;}
.spinner{
display:inline-block;width:11px;height:11px;border-radius:50%;
border:2px solid var(--line);border-top-color:var(--accent);
animation:spin .7s linear infinite;vertical-align:middle;margin-right:5px;
}
@keyframes spin{to{transform:rotate(360deg);}}
.row{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:0;}
@media(max-width:600px){.row{grid-template-columns:1fr;}}
/* provider tabs — segmented pill control */
.tabrow{display:flex;gap:4px;background:var(--tab-inactive);padding:4px;border-radius:999px;margin-bottom:16px;width:fit-content;flex-wrap:wrap;}
.tabrow .tab{
font-family:var(--body-font);font-weight:600;font-size:12.5px;
padding:7px 16px;background:transparent;border:none;border-radius:999px;
cursor:pointer;color:var(--muted);transition:background .12s,color .12s;
}
.tabrow .tab.active{background:var(--accent);color:#fff;}
.key-status{font-size:12px;font-weight:500;margin-top:4px;margin-bottom:14px;}
.key-status.ok{color:var(--accent-dark);}
.key-status.empty{color:var(--muted);}
details.settings{margin-top:2px;margin-bottom:2px;}
details.settings summary{
cursor:pointer;font-size:12.5px;color:var(--accent-dark);font-weight:600;
list-style:none;display:flex;align-items:center;gap:6px;
}
details.settings summary::-webkit-details-marker{display:none;}
details.settings summary::before{content:"▸";font-size:10px;}
details.settings[open] summary::before{content:"▾";}
button{
font-family:var(--body-font);font-weight:700;font-size:13px;
background:var(--accent);color:#fff;border:none;
border-radius:999px;padding:10px 18px;cursor:pointer;
transition:background .12s, transform .06s;
}
button:hover{background:var(--accent-dark);}
button.secondary{background:transparent;color:var(--muted);border:1.5px solid var(--line);}
button.secondary:hover{background:var(--tab-inactive);color:var(--ink);border-color:var(--line);}
button.small{padding:7px 14px;font-size:12px;}
button.danger{background:transparent;color:var(--alert);border:1.5px solid var(--alert-soft);}
button.danger:hover{background:var(--alert);color:#fff;border-color:var(--alert);}
button:disabled{opacity:.5;cursor:not-allowed;}
.field-actions{display:flex;gap:10px;flex-wrap:wrap;margin-bottom:4px;}
.select-all-row{display:flex;align-items:center;gap:10px;margin-bottom:16px;font-size:13px;color:var(--muted);flex-wrap:wrap;}
.select-all-row label{margin:0;text-transform:none;font-size:13px;color:var(--muted);display:flex;align-items:center;gap:6px;font-weight:500;}
.checkbox-inline{display:flex;align-items:center;gap:6px;font-size:12.5px;color:var(--muted);}
.checkbox-inline input{width:auto;margin:0;}
.badge-count{
display:inline-block;background:var(--accent);color:#fff;border-radius:999px;
padding:2px 9px;font-size:11px;margin-left:2px;font-weight:600;text-transform:none;letter-spacing:0;
}
/* lens grid */
.lens-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(270px,1fr));gap:12px;}
.lens-card{
border:1.5px solid var(--line);border-radius:var(--radius);padding:14px 15px;background:var(--card);
display:flex;flex-direction:column;gap:10px;transition:border-color .12s, box-shadow .12s;
box-shadow:0 1px 2px rgba(11,37,48,.04);
}
.lens-card.done{border-color:var(--accent);background:var(--accent-soft);}
.lens-card.running{border-color:var(--accent);}
.lens-card .lens-head{display:flex;align-items:flex-start;gap:9px;}
.lens-card .lens-num{
width:22px;height:22px;flex:none;border-radius:50%;background:var(--accent);color:#fff;
display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:700;
}
.lens-card .lens-name{font-size:13.5px;color:var(--ink);font-weight:700;}
.lens-card .lens-focus{font-size:11.5px;color:var(--muted);line-height:1.4;}
.lens-card .lens-actions{display:flex;gap:8px;align-items:center;margin-top:auto;}
.lens-card .status-dot{width:7px;height:7px;border-radius:50%;background:var(--line);flex:none;}
.lens-card.done .status-dot{background:var(--accent-dark);}
.lens-card.running .status-dot{background:var(--alert);animation:pulse 1s infinite;}
@keyframes pulse{0%{opacity:.3}50%{opacity:1}100%{opacity:.3}}
.divider{border:none;border-top:1px dashed var(--line);margin:28px 0;}
.phase3-buttons{display:flex;gap:10px;flex-wrap:wrap;}
/* results header + toolbar (sits below step 4) */
.results-header{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px;margin-bottom:16px;}
.results-header h2{font-size:16px;margin:0;color:var(--ink);font-weight:800;}
.results-actions{display:flex;gap:8px;flex-wrap:wrap;}
/* output blocks */
.output-block{
border:1px solid var(--line);border-left:3px solid var(--accent);
border-radius:0 var(--radius) var(--radius) 0;
padding:16px 18px;margin-bottom:14px;background:var(--card);
box-shadow:0 1px 2px rgba(11,37,48,.04);
}
.output-block h3{margin:0 0 8px;font-size:14px;color:var(--accent-dark);font-weight:700;display:flex;align-items:center;gap:8px;flex-wrap:wrap;}
.output-block h3 .lens-id{color:var(--muted);font-weight:500;font-size:11.5px;}
.output-block h3 .spacer{margin-left:auto;display:flex;gap:6px;}
.tts-btn{
display:inline-flex;align-items:center;justify-content:center;flex-shrink:0;
width:24px;height:24px;padding:0;
background:transparent;color:var(--muted);
border:1px solid var(--line);border-radius:50%;
cursor:pointer;transition:background .12s ease,color .12s ease;
}
.tts-btn:hover{background:var(--accent-soft);color:var(--accent-dark);}
.tts-btn svg{width:13px;height:13px;display:block;}
.tts-btn.speaking{background:var(--accent-soft);color:var(--accent-dark);border-color:var(--accent);}
.tts-btn.speaking .tts-wave-1{animation:ttsPulse 1s ease-in-out infinite;}
.tts-btn.speaking .tts-wave-2{animation:ttsPulse 1s ease-in-out infinite .18s;}
@keyframes ttsPulse{0%,100%{opacity:.3;}50%{opacity:1;}}
@media(prefers-reduced-motion:reduce){
.tts-btn.speaking .tts-wave-1,.tts-btn.speaking .tts-wave-2{animation:none;opacity:1;}
}
.output-body{white-space:pre-wrap;font-size:13.5px;color:var(--ink);line-height:1.6;}
.empty-note{color:var(--muted);font-size:13px;font-style:italic;padding:20px 0;text-align:center;}
.loading-line{display:flex;align-items:center;gap:8px;color:var(--muted);font-size:12.5px;}
.dots span{animation:blink 1.4s infinite;}
.dots span:nth-child(2){animation-delay:0.2s;}
.dots span:nth-child(3){animation-delay:0.4s;}
@keyframes blink{0%,80%,100%{opacity:0.2}40%{opacity:1}}
footer{margin-top:50px;font-size:11.5px;color:var(--muted);text-align:center;font-weight:500;}
footer a{color:var(--muted);}
code.inline{background:var(--tab-inactive);border:1px solid var(--line);padding:1px 6px;border-radius:4px;color:var(--accent-dark);font-family:var(--mono);font-size:12px;}
@media (max-width:600px){
header.top{flex-direction:column;align-items:flex-start;}
header.top .top-right{align-items:flex-start;}
.top-links{justify-content:flex-start;}
}
</style>
<!-- ===== VibeRounds Suite Bar ===== -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600;700&family=DM+Mono:wght@400;500&display=swap" rel="stylesheet">
<style>
.vr-suitebar{
background: linear-gradient(160deg, #EFF6FF 0%, #F0FDFA 65%);
border-bottom: 1px solid #E2E8F0;
padding: 12px 20px;
display: flex; align-items: center; justify-content: space-between;
flex-wrap: wrap; gap: 10px 16px;
}
.vr-suitebar .vr-brand{
font-family: 'DM Mono','IBM Plex Mono',monospace;
font-weight: 700; font-size: 14px; letter-spacing: -0.01em;
color: #0F172A; text-decoration: none; display:flex; align-items:center; gap:0;
}
.vr-suitebar .vr-brand span{ color: #0891B2; }
.vr-suitebar .vr-nav{ display:flex; gap:6px; flex-wrap:wrap; }
.vr-suitebar .vr-nav a{
font-family:'DM Mono','IBM Plex Mono',monospace; font-size:11px; letter-spacing:.04em; text-transform:uppercase;
color:#475569; text-decoration:none; padding:6px 10px; border-radius:999px;
border:1px solid #E2E8F0; background:#FFFFFF; transition:.15s ease;
}
.vr-suitebar .vr-nav a:hover{ color:#fff; background:#0891B2; border-color:#0891B2; }
.vr-suitebar .vr-nav a.active{ color:#fff; background:#0E7490; border-color:#0E7490; }
@media (max-width:640px){
.vr-suitebar{ padding:10px 14px; }
.vr-suitebar .vr-nav a{ padding:5px 8px; font-size:10px; }
}
</style>
</head>
<body>
<header class="vr-suitebar">
<a class="vr-brand" href="https://avi33tbtt.github.io/">Vibe<span>Rounds</span></a>
<nav class="vr-nav">
<a href="https://avi33tbtt.github.io/home.html">Home</a>
<a href="https://avi33tbtt.github.io/bench.html">Case Bench</a>
<a href="https://avi33tbtt.github.io/bench_lite.html">Bench Lite</a>
<a href="https://avi33tbtt.github.io/case-simulator.html">Case Simulator</a>
<a href="https://avi33tbtt.github.io/case-practice.html">Clinical Practice</a>
<a href="https://avi33tbtt.github.io/clinical-polemos.html">Clinical Polemos</a>
<a href="https://avi33tbtt.github.io/case-lens.html" class="active">Case Lens</a>
<a href="https://avi33tbtt.github.io/sdm-lens.html">SDM Lens</a>
<a href="https://avi33tbtt.github.io/ebm.html">EBM Query Generator</a>
<a href="https://avi33tbtt.github.io/ccos-builder.html">CCOS Builder</a>
</nav>
</header>
<div class="wrap">
<header class="top">
<div class="brand">
<h1>Vibe Rounds - Case Lens</h1>
<span class="rx">8-Lens Critical Thinking Audit</span>
</div>
<div class="top-right">
<div class="tagline">clinical reasoning aid · not for patient care</div>
<div class="top-links">
<a href="https://avi33tbtt.github.io/" target="_blank" rel="noopener">Project website</a>
<a href="https://www.linkedin.com/in/dravinashkumargupta/" target="_blank" rel="noopener">Dr. Avinash — LinkedIn</a>
</div>
</div>
</header>
<div class="banner">Not a diagnosis tool. This runs the Case Lens module from the Vibe Rounds prompt library: load a case once, then fire each lens (or all eight) to generate case-specific, impact-scored questions — followed by a Phase 3 roll-up and reflection debrief.</div>
<div class="banner warn"><strong>Educational use only.</strong> To be used on personal responsibility and only for learning — not for clinical decision-making. Your API key is stored only in this browser's local storage and sent directly from your browser to your chosen provider — never through any server of ours.</div>
<!-- STEP 1 — MODEL -->
<div class="step">
<div class="step-label collapsed" id="label-model"><span class="num">1</span>Model<span class="collapse-arrow" id="arrow-model">▾</span></div>
<div class="card collapsed" id="card-model">
<div class="tabrow" id="providerTabs">
<div class="tab active" data-p="claude">Claude</div>
<div class="tab" data-p="gemini">Gemini</div>
<div class="tab" data-p="openai">ChatGPT</div>
<div class="tab" data-p="other">Other</div>
</div>
<div id="providerFields"></div>
<div class="key-status empty" id="keyStatus">No key saved for this provider yet.</div>
<div class="field-actions">
<button id="saveKeyBtn" type="button">Save key (this browser only)</button>
<button class="secondary" id="clearKeyBtn" type="button">Clear saved key</button>
</div>
<details class="settings">
<summary>Where do I get a key?</summary>
<div class="hint" style="margin-top:8px;margin-bottom:0;">Claude → <a href="https://console.anthropic.com/settings/keys" target="_blank">console.anthropic.com</a> · Gemini → <a href="https://aistudio.google.com/apikey" target="_blank">aistudio.google.com</a> · OpenAI → <a href="https://platform.openai.com/api-keys" target="_blank">platform.openai.com</a></div>
</details>
</div>
</div>
<!-- STEP 2 — CASE -->
<div class="step">
<div class="step-label collapsed" id="label-case"><span class="num">2</span>Case<span class="collapse-arrow" id="arrow-case">▾</span></div>
<div class="card collapsed" id="card-case">
<label for="caseText">Paste the case — vignette, summary, discharge note, or paste a link to fetch it from</label>
<textarea id="caseText" placeholder="Paste the case here, or paste a link (e.g. https://example.com/case-report) and click Fetch below — the more specific (actual values, timing, meds), the sharper the questions each lens will generate."></textarea>
<div class="link-detect" id="linkDetectRow" style="display:none;">
<span id="linkDetectText">Link detected —</span>
<button class="secondary small" id="fetchUrlBtn" type="button">Fetch case text from this link</button>
</div>
<div class="hint" id="urlFetchNote"></div>
<div class="case-input-row">
<div class="case-input-col">
<label for="caseFile">...or upload a file (.txt, .pdf, .docx — max 10 MB)</label>
<div class="file-picker">
<input type="file" id="caseFile" accept=".txt,.md,.pdf,.docx" hidden>
<button type="button" class="secondary small" id="caseFileBtn">Choose file</button>
<span class="file-picker-name" id="caseFileName">No file selected</span>
</div>
<div class="hint" id="fileUploadNote"></div>
</div>
</div>
<div class="field-actions">
<button class="secondary small" id="sampleCaseBtn" type="button">Load sample case</button>
<button class="secondary small" id="clearCaseBtn" type="button">Clear case</button>
</div>
<div class="hint" id="caseSetNote"></div>
</div>
</div>
<!-- STEP 3 — LENSES -->
<div class="step">
<div class="step-label collapsed" id="label-lenses"><span class="num">3</span>Lenses <span class="badge-count" id="lensDoneCount">0 / 8 run</span><span class="collapse-arrow" id="arrow-lenses">▾</span></div>
<div class="card collapsed" id="card-lenses">
<div class="select-all-row">
<label><input type="checkbox" id="selectAll"> Select all 8 lenses</label>
<button id="runSelectedBtn" type="button">▶ Run selected lenses</button>
<button class="secondary small" id="resetLensesBtn" type="button">Reset lens outputs</button>
</div>
<div class="lens-grid" id="lensGrid"></div>
</div>
</div>
<!-- STEP 4 — CLOSURE / REVIEW -->
<div class="step">
<div class="step-label collapsed" id="label-phase3"><span class="num">4</span>Closure / Review<span class="collapse-arrow" id="arrow-phase3">▾</span></div>
<div class="card collapsed" id="card-phase3">
<div class="hint" style="margin-top:0;">Run after at least one lens has produced output — these consolidate everything generated so far.</div>
<div class="phase3-buttons">
<button id="rollupBtn" type="button">▶ Key Questions Roll-Up</button>
<button id="reflectionBtn" type="button">▶ Reflection Debrief</button>
</div>
</div>
</div>
<hr class="divider">
<!-- RESULTS — toolbar + combined outputs, below step 4 -->
<div class="results-header">
<h2>Results</h2>
<div class="results-actions">
<button class="secondary small" id="speakAllBtn" type="button">🔊 Read all aloud</button>
<button class="secondary small" id="stopSpeakBtn" type="button">⏹ Stop reading</button>
<button class="secondary small" id="downloadTxtBtn" type="button">Download .txt</button>
<button class="danger small" id="resetAllBtn" type="button">Reset run</button>
</div>
</div>
<div id="lensOutputs"></div>
<div id="phase3Outputs"></div>
<div class="empty-note" id="emptyResultsNote">No outputs yet — run a lens or a Phase 3 step above to see results here.</div>
</div>
<footer>
Case Lens is a Vibe Rounds tool · Dr. Avinash Kumar Gupta · CC BY 4.0 · runs entirely in your browser · bring your own key.<br>
All outputs require independent clinical verification. Not a diagnostic tool. See <a href="https://avi33tbtt.github.io/" target="_blank">avi33tbtt.github.io</a> for the full module library.
</footer>
<script>
/* ---------------- Lens definitions (from the Case Lens module) ---------------- */
const LENSES = [
{
id: 1, key:"framing", name:"Framing the Problem",
focus:"Differential completeness, can't-miss diagnoses, Occam vs. Hickam, history reliability",
prompt:`Apply Lens 1 — Framing the Problem — to this case. Generate 2-4 questions covering: whether the differential is complete (use a systematic sieve, not just pattern recognition), whether any "can't-miss" diagnosis has been adequately excluded, whether one unifying diagnosis truly fits or multiple concurrent problems are being forced into one story (Occam vs. Hickam), and whether the history itself is reliable given who gave it and how.`
},
{
id: 2, key:"uncertainty", name:"Reasoning Under Uncertainty",
focus:"Pre-test probability, Bayesian updating, base rates, absolute vs. relative risk",
prompt:`Apply Lens 2 — Reasoning Under Uncertainty — to this case. Generate 2-4 questions covering: whether the pre-test probability actually justifies the tests ordered or planned, whether a negative/positive result is being over- or under-interpreted given the prior probability, whether a rare diagnosis is being chased ahead of common ones, and whether any risk being discussed with the patient is absolute or just relative.`
},
{
id: 3, key:"bias", name:"Cognitive Biases",
focus:"Anchoring, premature closure, availability, confirmation bias, diagnostic momentum",
prompt:`Apply Lens 3 — Cognitive Biases — to this case. Scan the case narrative itself for signs of anchoring, premature closure, availability bias, confirmation bias, diagnostic momentum (a label passed uncritically between notes/providers), or framing effects in how risk was presented. Generate 2-4 questions that would expose whether any of these are currently shaping the plan.`
},
{
id: 4, key:"evidence", name:"Evaluating Evidence",
focus:"Guideline strength, statistical vs. clinical significance, surrogate endpoints, generalizability",
prompt:`Apply Lens 4 — Evaluating Evidence — to this case. Generate 2-4 questions covering: whether any guideline being applied here is backed by strong evidence or expert opinion, whether a treatment's benefit is statistically significant but clinically marginal, whether any endpoint being chased is a surrogate rather than a hard outcome, and whether the evidence being relied on actually generalizes to this patient's age/comorbidity profile.`
},
{
id: 5, key:"testing", name:"Testing & Diagnostic Strategy",
focus:"Test sequencing, serial data, discordant results, sensitivity/specificity purpose",
prompt:`Apply Lens 5 — Testing & Diagnostic Strategy — to this case. Generate 2-4 questions covering: whether the next test actually changes management, whether any result is being trusted as a snapshot when a trend would be more informative, whether a discordant result has been chased down or dismissed, and whether a "normal" result is being treated as more reassuring than its sensitivity actually justifies.`
},
{
id: 6, key:"treatment", name:"Treatment & Response Reasoning",
focus:"Risk/benefit under uncertainty, therapeutic-trial interpretation, non-response workup",
prompt:`Apply Lens 6 — Treatment & Response Reasoning — to this case. Generate 2-4 questions covering: whether a symptom improvement is being credited to treatment when natural history or placebo response could explain it, whether non-response has been worked through systematically (wrong diagnosis / wrong dose / non-adherence / true resistance) rather than jumped to "resistant disease," whether a new symptom could be iatrogenic, and whether timing/delay itself matters for this condition.`
},
{
id: 7, key:"individualizing", name:"Individualizing Care",
focus:"Guideline vs. patient fit, patient values, explanatory models, social contributors",
prompt:`Apply Lens 7 — Individualizing Care — to this case. Generate 2-4 questions covering: whether the standard guideline plan actually fits this patient's comorbidities, frailty, or stated goals, whether the patient's own explanatory model of their illness has been incorporated or dismissed, and whether a social or systemic factor (cost, access, literacy) could be masquerading as "non-adherence."`
},
{
id: 8, key:"systems", name:"Systems, Communication & Self-Monitoring",
focus:"Handoff clarity, cross-checking automation, self-audit, post-hoc reflection",
prompt:`Apply Lens 8 — Systems, Communication & Self-Monitoring — to this case. Generate 2-4 questions covering: whether the current plan and its uncertainty have been communicated clearly enough for the next clinician to re-evaluate rather than anchor, whether any automated output (EHR alert, auto-read) is being trusted without a manual check, and what a structured post-hoc review of this case would flag if the outcome were bad.`
},
];
const AUDITOR_SYSTEM = `You are a clinical reasoning auditor. You will be given a case (paste, summary, or excerpt) and asked to apply an 8-lens critical thinking framework to it. Your job is not to diagnose or manage the patient — it is to generate sharp, case-specific questions the user should be asking themselves, tied to actual details in the case, not generic textbook questions. Format each lens response as a numbered list of questions. Do not add unrelated commentary. This is a learning/reasoning-audit tool, not a diagnostic or treatment tool.`;
const ROLLUP_PROMPT = `Collect the most important questions generated across all 8 lenses. Present them as a single prioritized list, with the lens each came from. For each, state in one line what answering it would change about the current plan.`;
const REFLECTION_PROMPT = `Now step back. Of everything generated across all 8 lenses: (1) which single question, if you only had time to answer one, would most change management for this patient? (2) which lens surfaced the least for this particular case, and is that because the case genuinely doesn't have much exposure there, or because the case as written doesn't give you enough to probe it? (3) what is one thing about the reasoning on this case — not the patient — that this audit revealed?`;
const SAMPLE_CASE = `62F, 3 days of worsening dyspnea and bilateral leg swelling. History of hypertension, no known cardiac disease. On exam: O2 sat 91% on room air, JVP raised, bibasal crackles, pitting oedema to the knees. No chest pain. Started on furosemide 40mg by her GP two days ago with mild improvement in swelling but dyspnea unchanged. No echo yet ordered. Labs: creatinine 1.3 (baseline unknown), BNP pending.`;
/* ---------------- State ---------------- */
let lensState = {}; // key -> {status:'idle'|'running'|'done', output:string}
LENSES.forEach(l => lensState[l.key] = {status:'idle', output:''});
let conversationLog = []; // {lens, id, output} entries in run order, for phase3 context
/* ---------------- Collapsible sections ---------------- */
function setupCollapse(labelId, cardId){
const label = document.getElementById(labelId);
const card = document.getElementById(cardId);
label.addEventListener('click', ()=>{
const nowCollapsed = !card.classList.contains('collapsed');
card.classList.toggle('collapsed', nowCollapsed);
label.classList.toggle('collapsed', nowCollapsed);
});
}
setupCollapse('label-model', 'card-model');
setupCollapse('label-case', 'card-case');
setupCollapse('label-lenses', 'card-lenses');
setupCollapse('label-phase3', 'card-phase3');
/* ---------------- Provider config ---------------- */
const PROVIDER_DEFAULTS = {
claude: {label:"Claude", keyLabel:"Claude API key", modelDefault:"claude-sonnet-4-5-20250929", showEndpoint:false},
gemini: {label:"Gemini", keyLabel:"Gemini API key", modelDefault:"gemini-2.5-flash", showEndpoint:false},
openai: {label:"ChatGPT", keyLabel:"OpenAI API key", modelDefault:"gpt-4o", showEndpoint:false},
other: {label:"Other", keyLabel:"API key", modelDefault:"", showEndpoint:true}
};
let currentProvider = "claude";
function renderProviderFields(){
const cfg = PROVIDER_DEFAULTS[currentProvider];
const saved = JSON.parse(localStorage.getItem('caselens_'+currentProvider) || '{}');
const container = document.getElementById('providerFields');
container.innerHTML = `
${cfg.showEndpoint ? `
<div>
<label>API endpoint (OpenAI-compatible chat/completions URL)</label>
<input type="text" id="endpointInput" placeholder="https://your-endpoint.example.com/v1/chat/completions" value="${saved.endpoint||''}">
</div>
` : ''}
<div class="row">
<div>
<label>${cfg.keyLabel}</label>
<input type="password" id="apiKeyInput" placeholder="sk-..." value="${saved.key||''}">
</div>
<div>
<label>Model name</label>
<input type="text" id="modelInput" placeholder="${cfg.modelDefault}" value="${saved.model||cfg.modelDefault}">
</div>
</div>
`;
updateKeyStatus();
}
function updateKeyStatus(){
const saved = JSON.parse(localStorage.getItem('caselens_'+currentProvider) || '{}');
const el = document.getElementById('keyStatus');
if(saved.key){
el.textContent = `Key saved locally for ${PROVIDER_DEFAULTS[currentProvider].label}.`;
el.className = 'key-status ok';
} else {
el.textContent = `No key saved for this provider yet.`;
el.className = 'key-status empty';
}
}
document.getElementById('providerTabs').addEventListener('click', (e)=>{
const tab = e.target.closest('.tab[data-p]');
if(!tab) return;
document.querySelectorAll('#providerTabs .tab').forEach(t=>t.classList.remove('active'));
tab.classList.add('active');
currentProvider = tab.dataset.p;
renderProviderFields();
});
document.getElementById('saveKeyBtn').addEventListener('click', ()=>{
const key = document.getElementById('apiKeyInput').value.trim();
const model = document.getElementById('modelInput').value.trim() || PROVIDER_DEFAULTS[currentProvider].modelDefault;
const endpointEl = document.getElementById('endpointInput');
const endpoint = endpointEl ? endpointEl.value.trim() : '';
localStorage.setItem('caselens_'+currentProvider, JSON.stringify({key, model, endpoint}));
updateKeyStatus();
});
document.getElementById('clearKeyBtn').addEventListener('click', ()=>{
localStorage.removeItem('caselens_'+currentProvider);
renderProviderFields();
});
renderProviderFields();
/* ---------------- Case handling ---------------- */
document.getElementById('sampleCaseBtn').addEventListener('click', ()=>{
document.getElementById('caseText').value = SAMPLE_CASE;
document.getElementById('caseSetNote').textContent = "Sample dummy case loaded — replace with your own case before relying on this run.";
updateLinkDetect();
});
document.getElementById('clearCaseBtn').addEventListener('click', ()=>{
document.getElementById('caseText').value = '';
document.getElementById('caseSetNote').textContent = '';
document.getElementById('caseFile').value = '';
document.getElementById('urlFetchNote').textContent = '';
document.getElementById('fileUploadNote').textContent = '';
setFileName('No file selected', false);
updateLinkDetect();
});
const MAX_FILE_BYTES = 10 * 1024 * 1024; // 10 MB
if(window.pdfjsLib){
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';
}
function setNote(id, text, cls){
const el = document.getElementById(id);
el.textContent = text;
el.className = 'hint' + (cls ? ' '+cls : '');
}
function appendToCaseText(text, sourceLabel){
const ta = document.getElementById('caseText');
const existing = ta.value.trim();
ta.value = existing ? existing + '\n\n---\n\n' + text.trim() : text.trim();
document.getElementById('caseSetNote').textContent = sourceLabel;
}
async function extractPdfText(arrayBuffer){
if(!window.pdfjsLib) throw new Error('PDF library failed to load.');
const pdf = await pdfjsLib.getDocument({data: arrayBuffer}).promise;
let text = '';
for(let i=1; i<=pdf.numPages; i++){
const page = await pdf.getPage(i);
const content = await page.getTextContent();
text += content.items.map(it=>it.str).join(' ') + '\n\n';
}
return text.trim();
}
async function extractDocxText(arrayBuffer){
if(!window.mammoth) throw new Error('DOCX library failed to load.');
const result = await mammoth.extractRawText({arrayBuffer});
return result.value.trim();
}
/* ---- Link detection inside the case textarea ---- */
const URL_ONLY_RE = /^(https?:\/\/[^\s]+|www\.[^\s]+|[a-z0-9-]+\.[a-z]{2,}(\/[^\s]*)?)$/i;
function looksLikeUrlOnly(text){
const t = text.trim();
if(!t || /\s/.test(t)) return false; // multi-word case text, not a bare link
return URL_ONLY_RE.test(t);
}
function updateLinkDetect(){
const ta = document.getElementById('caseText');
const row = document.getElementById('linkDetectRow');
const isUrl = looksLikeUrlOnly(ta.value);
row.style.display = isUrl ? 'flex' : 'none';
if(!isUrl){
document.getElementById('urlFetchNote').textContent = '';
}
}
document.getElementById('caseText').addEventListener('input', updateLinkDetect);
/* ---- File upload ---- */
document.getElementById('caseFileBtn').addEventListener('click', ()=>{
document.getElementById('caseFile').click();
});
function setFileName(text, isSet){
const el = document.getElementById('caseFileName');
el.textContent = text;
el.className = 'file-picker-name' + (isSet ? ' set' : '');
}
document.getElementById('caseFile').addEventListener('change', async (e)=>{
const file = e.target.files[0];
if(!file){ setFileName('No file selected', false); return; }
const noteId = 'fileUploadNote';
setFileName(file.name, true);
if(file.size > MAX_FILE_BYTES){
setNote(noteId, `"${file.name}" is ${(file.size/1024/1024).toFixed(1)} MB — max allowed is 10 MB.`, 'error');
e.target.value = '';
setFileName('No file selected', false);
return;
}
const ext = file.name.split('.').pop().toLowerCase();
setNote(noteId, `Reading "${file.name}"…`);
try{
let text = '';
if(ext === 'txt' || ext === 'md'){
text = await file.text();
} else if(ext === 'pdf'){
const buf = await file.arrayBuffer();
text = await extractPdfText(buf);
} else if(ext === 'docx'){
const buf = await file.arrayBuffer();
text = await extractDocxText(buf);
} else {
setNote(noteId, `Unsupported file type ".${ext}". Use .txt, .md, .pdf, or .docx.`, 'error');
e.target.value = '';
setFileName('No file selected', false);
return;
}
if(!text || !text.trim()){
setNote(noteId, `Couldn't find any readable text in "${file.name}" — it may be a scanned/image-only file. Try pasting the text directly.`, 'error');
e.target.value = '';
return;
}
appendToCaseText(text, `Loaded from file: ${file.name}`);
setNote(noteId, `Loaded ${text.length.toLocaleString()} characters from "${file.name}".`, 'ok');
updateLinkDetect();
} catch(err){
console.error(err);
setNote(noteId, `Couldn't read "${file.name}": ${err.message || err}. Try converting it to .txt or pasting the text directly.`, 'error');
} finally {
e.target.value = '';
}
});
/* ---- URL fetch (link pasted directly into the case textarea) ---- */
document.getElementById('fetchUrlBtn').addEventListener('click', async ()=>{
const noteId = 'urlFetchNote';
const ta = document.getElementById('caseText');
const btn = document.getElementById('fetchUrlBtn');
let url = ta.value.trim();
if(!url || !looksLikeUrlOnly(url)){
setNote(noteId, 'Paste a link into the box above first.', 'error');
return;
}
if(!/^https?:\/\//i.test(url)) url = 'https://' + url;
btn.disabled = true;
setNote(noteId, 'Fetching…');
try{
const res = await fetch(url, {mode:'cors'});
if(!res.ok) throw new Error(`Server responded ${res.status}`);
const contentType = res.headers.get('content-type') || '';
let text = '';
if(contentType.includes('application/pdf') || url.toLowerCase().endsWith('.pdf')){
const buf = await res.arrayBuffer();
text = await extractPdfText(buf);
} else {
const raw = await res.text();
// Strip tags for HTML pages to get plain-ish text
if(contentType.includes('html')){
const doc = new DOMParser().parseFromString(raw, 'text/html');
doc.querySelectorAll('script,style,nav,header,footer,noscript').forEach(n=>n.remove());
text = (doc.body ? doc.body.innerText : raw).replace(/\n{3,}/g,'\n\n').trim();
} else {
text = raw;
}
}
if(!text || !text.trim()){
setNote(noteId, `Fetched the page but couldn't extract readable text. Try copying the case text manually.`, 'error');
return;
}
ta.value = text.trim();
document.getElementById('caseSetNote').textContent = `Loaded from URL: ${url}`;
setNote(noteId, `Loaded ${text.length.toLocaleString()} characters from the link.`, 'ok');
updateLinkDetect();
} catch(err){
console.error(err);
setNote(noteId, `Couldn't fetch that URL directly (often blocked by the site's CORS policy). Try opening the link and pasting the case text instead.`, 'error');
} finally {
btn.disabled = false;
}
});
/* ---------------- Render lens grid ---------------- */
function renderLensGrid(){
const grid = document.getElementById('lensGrid');
grid.innerHTML = LENSES.map(l => `
<div class="lens-card ${lensState[l.key].status==='done'?'done':''} ${lensState[l.key].status==='running'?'running':''}" id="card-${l.key}">
<div class="lens-head">
<div class="lens-num">${l.id}</div>
<div>
<div class="lens-name">${l.name}</div>
<div class="lens-focus">${l.focus}</div>
</div>
</div>
<div class="lens-actions">
<label class="checkbox-inline"><input type="checkbox" class="lensCheckbox" data-key="${l.key}"> select</label>
<button class="small" data-run="${l.key}" type="button">▶ Run lens</button>
<span class="status-dot" id="dot-${l.key}"></span>
</div>
</div>
`).join('');
grid.querySelectorAll('button[data-run]').forEach(btn=>{
btn.addEventListener('click', ()=> runLens(btn.dataset.run));
});
updateDoneCount();
}
renderLensGrid();
document.getElementById('selectAll').addEventListener('change', (e)=>{
document.querySelectorAll('.lensCheckbox').forEach(cb => cb.checked = e.target.checked);
});
document.getElementById('runSelectedBtn').addEventListener('click', async ()=>{
const keys = Array.from(document.querySelectorAll('.lensCheckbox:checked')).map(cb=>cb.dataset.key);
const toRun = keys.length ? keys : LENSES.map(l=>l.key);
if(typeof trackEvent === 'function') trackEvent('run_selected_lenses', {count: toRun.length, lenses: toRun});
for(const k of toRun){
await runLens(k);
}
});
document.getElementById('resetLensesBtn').addEventListener('click', ()=>{
LENSES.forEach(l => lensState[l.key] = {status:'idle', output:''});
conversationLog = [];
document.getElementById('lensOutputs').innerHTML = '';
document.getElementById('phase3Outputs').innerHTML = '';
renderLensGrid();
updateEmptyResultsNote();
});
function updateDoneCount(){
const done = Object.values(lensState).filter(s=>s.status==='done').length;
document.getElementById('lensDoneCount').textContent = `${done} / 8 run`;
}
/* ---------------- Output rendering ---------------- */
function escapeHtml(str){
if(str === null || str === undefined) return '';
return String(str)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function formatOutput(text){
return escapeHtml(text);
}
const TTS_ICON = `<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 9v6h4l5 5V4L8 9H4z" fill="currentColor"/><path class="tts-wave tts-wave-1" d="M15.3 8.5a5 5 0 0 1 0 7" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/><path class="tts-wave tts-wave-2" d="M18.2 5.5a9 9 0 0 1 0 13" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>`;
function updateEmptyResultsNote(){
const hasOutputs = document.getElementById('lensOutputs').children.length > 0
|| document.getElementById('phase3Outputs').children.length > 0;
document.getElementById('emptyResultsNote').style.display = hasOutputs ? 'none' : '';
}
function ensureOutputBlock(id, title, subtitle){
let el = document.getElementById('out-'+id);
if(!el){
el = document.createElement('div');
el.className = 'output-block';
el.id = 'out-'+id;
el.innerHTML = `<h3>${title} <span class="lens-id">${subtitle||''}</span><span class="spacer"><button type="button" class="tts-btn" data-speak="${id}" aria-label="Read aloud" title="Read aloud">${TTS_ICON}</button></span></h3><div class="output-body" id="body-${id}"><div class="loading-line">running<span class="dots"><span>.</span><span>.</span><span>.</span></span></div></div>`;
document.getElementById('lensOutputs').appendChild(el);
el.querySelector('[data-speak]').addEventListener('click', ()=> toggleSpeak(id, el.querySelector('[data-speak]')));
updateEmptyResultsNote();
}
return el;
}
/* ---------------- API calls ---------------- */
async function callModel(systemPrompt, messages){
const cfg = JSON.parse(localStorage.getItem('caselens_'+currentProvider) || '{}');
if(!cfg.key){
throw new Error(`No API key saved for ${PROVIDER_DEFAULTS[currentProvider].label}. Set it in Step 1.`);
}
const model = cfg.model || PROVIDER_DEFAULTS[currentProvider].modelDefault;
if(currentProvider === 'claude'){
const resp = await fetch('https://api.anthropic.com/v1/messages', {
method:'POST',
headers:{
'Content-Type':'application/json',
'x-api-key': cfg.key,
'anthropic-version':'2023-06-01',
'anthropic-dangerous-direct-browser-access':'true'
},
body: JSON.stringify({
model: model,
max_tokens: 4096,
system: systemPrompt,
messages: messages.map(m=>({role:m.role==='assistant'?'assistant':'user', content:m.content}))
})
});
const data = await resp.json();
if(data.error) throw new Error(data.error.message || JSON.stringify(data.error));
return (data.content||[]).map(c=>c.text||'').join('\n');
}
if(currentProvider === 'gemini'){
const url = `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${cfg.key}`;
const contents = messages.map(m=>({role: m.role==='assistant'?'model':'user', parts:[{text:m.content}]}));
const resp = await fetch(url, {
method:'POST',
headers:{'Content-Type':'application/json'},
body: JSON.stringify({
systemInstruction: {parts:[{text:systemPrompt}]},
contents
})
});
const data = await resp.json();
if(data.error) throw new Error(data.error.message || JSON.stringify(data.error));
const parts = data.candidates?.[0]?.content?.parts;
if(!parts || !parts.length){
const reason = data.promptFeedback?.blockReason || data.candidates?.[0]?.finishReason;
throw new Error(reason ? `Gemini returned no content (${reason}).` : 'Gemini returned no content.');
}
return parts.map(p=>p.text||'').join('\n');
}
// openai + other (OpenAI-compatible chat/completions)
const endpoint = currentProvider === 'openai'
? 'https://api.openai.com/v1/chat/completions'
: cfg.endpoint;
if(!endpoint) throw new Error('No API endpoint set for this provider.');
const resp = await fetch(endpoint, {
method:'POST',
headers:{
'Content-Type':'application/json',
'Authorization': 'Bearer ' + cfg.key
},
body: JSON.stringify({
model: model,
messages: [{role:'system', content:systemPrompt}, ...messages],
max_tokens: 4096
})
});
const data = await resp.json();
if(data.error) throw new Error(data.error.message || JSON.stringify(data.error));
return data.choices?.[0]?.message?.content || '';
}
/* ---------------- Lens run ---------------- */
async function runLens(key){
const lens = LENSES.find(l=>l.key===key);
const caseText = document.getElementById('caseText').value.trim();
if(!caseText){
alert('Paste a case first (Step 2).');
return;
}
lensState[key].status = 'running';
document.getElementById('card-'+key).classList.add('running');
const block = ensureOutputBlock(key, `Lens ${lens.id} — ${lens.name}`, lens.focus);
document.getElementById('body-'+key).innerHTML = `<div class="loading-line">running<span class="dots"><span>.</span><span>.</span><span>.</span></span></div>`;
const userMsg = `CASE:\n${caseText}\n\n${lens.prompt}`;
try{
const output = await callModel(AUDITOR_SYSTEM, [{role:'user', content: userMsg}]);
lensState[key] = {status:'done', output};
conversationLog.push({lens: lens.name, id: lens.id, output});
document.getElementById('body-'+key).innerHTML = formatOutput(output);
document.getElementById('card-'+key).classList.remove('running');
document.getElementById('card-'+key).classList.add('done');
}catch(err){
lensState[key].status = 'idle';
document.getElementById('card-'+key).classList.remove('running');
document.getElementById('body-'+key).innerHTML = `<span style="color:var(--alert)">Error: ${err.message}</span>`;
}
updateDoneCount();
}
/* ---------------- Phase 3 ---------------- */
function buildPhase3Context(){
if(conversationLog.length === 0) return null;
const caseText = document.getElementById('caseText').value.trim();
let ctx = `CASE:\n${caseText}\n\nOutputs generated so far across the 8 lenses:\n\n`;
conversationLog.forEach(c => {
ctx += `--- Lens ${c.id} — ${c.lens} ---\n${c.output}\n\n`;
});
return ctx;
}
async function runPhase3(promptText, title, targetId){
const ctx = buildPhase3Context();
if(!ctx){
alert('Run at least one lens first — Phase 3 consolidates what the lenses generated.');
return;
}
let el = document.getElementById('out-'+targetId);
if(!el){
el = document.createElement('div');
el.className = 'output-block';
el.id = 'out-'+targetId;
el.innerHTML = `<h3>${title}<span class="spacer"><button type="button" class="tts-btn" data-speak="${targetId}" aria-label="Read aloud" title="Read aloud">${TTS_ICON}</button></span></h3><div class="output-body" id="body-${targetId}"><div class="loading-line">running<span class="dots"><span>.</span><span>.</span><span>.</span></span></div></div>`;
document.getElementById('phase3Outputs').appendChild(el);
el.querySelector('[data-speak]').addEventListener('click', ()=> toggleSpeak(targetId, el.querySelector('[data-speak]')));
updateEmptyResultsNote();
} else {
document.getElementById('body-'+targetId).innerHTML = `<div class="loading-line">running<span class="dots"><span>.</span><span>.</span><span>.</span></span></div>`;
}
try{
const output = await callModel(AUDITOR_SYSTEM, [{role:'user', content: ctx + '\n\n' + promptText}]);
document.getElementById('body-'+targetId).innerHTML = formatOutput(output);
}catch(err){
document.getElementById('body-'+targetId).innerHTML = `<span style="color:var(--alert)">Error: ${err.message}</span>`;
}
}
document.getElementById('rollupBtn').addEventListener('click', ()=>{
runPhase3(ROLLUP_PROMPT, 'Phase 3 · Key Questions Roll-Up', 'rollup');
});
document.getElementById('reflectionBtn').addEventListener('click', ()=>{
runPhase3(REFLECTION_PROMPT, 'Phase 3 · Reflection Debrief', 'reflection');
});