-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcase-simulator.html
More file actions
1092 lines (1006 loc) · 51.6 KB
/
Copy pathcase-simulator.html
File metadata and controls
1092 lines (1006 loc) · 51.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 Simulator</title>
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-541054383"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-541054383');
</script>
<!-- File-upload text extraction: pdf.js (PDF) and mammoth.js (Word .docx) -->
<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{
--bg:#F7FAFB;
--ink:#0B2530;
--dim:#5B7480;
--line:#DCE7EA;
--accent:#0891B2;
--accent-dark:#0A6E85;
--accent-dim:#E3F4F8;
--warn:#C2410C;
--warn-soft:#FCE9DD;
--panel:#FFFFFF;
--radius:10px;
--body-font:'Inter',sans-serif;
--mono: 'IBM Plex Mono','SFMono-Regular',Consolas,Menlo,monospace;
}
*{box-sizing:border-box;}
body{
margin:0; background:var(--bg); color:var(--ink);
font-family:var(--body-font); font-size:14.5px; line-height:1.55;
-webkit-font-smoothing:antialiased;
}
a{color:var(--accent-dark);}
.wrap{max-width:1180px; margin:0 auto; padding:28px 20px 80px;}
header.top{border-bottom:1px solid var(--line); padding-bottom:16px; margin-bottom:22px;}
.brandline{display:flex; align-items:baseline; gap:14px; flex-wrap:wrap;}
h1{font-size:22px; margin:0; letter-spacing:-0.01em; font-weight:800;}
.rx{color:#fff; font-size:11.5px; font-weight:600; background:var(--accent); border-radius:20px; padding:4px 11px; letter-spacing:.01em;}
.tags{margin-top:6px; display:flex; gap:8px; flex-wrap:wrap;}
.tag{border:1px solid var(--line); padding:2px 8px; font-size:11px; color:var(--dim); border-radius:20px; text-transform:uppercase; letter-spacing:.06em;}
.disclaimer{margin-top:12px; font-size:12.5px; color:var(--dim); border-left:3px solid var(--accent); padding:10px 14px; background:var(--accent-dim); border-radius:0 8px 8px 0;}
.disclaimer b{color:var(--ink);}
.top-links{display:flex;gap:8px;flex-wrap:wrap;margin-top:10px;}
.top-links a{
display:inline-flex;align-items:center;gap:5px;font-size:12px;font-weight:700;
color:var(--accent-dark);background:var(--accent-dim);border:1px solid var(--line);
border-radius:999px;padding:6px 12px;text-decoration:none;transition:background .12s,color .12s,border-color .12s;
}
.top-links a:hover{background:var(--accent);color:#fff;border-color:var(--accent);}
.step{margin-bottom:20px;}
.step-head{
display:flex; align-items:center; gap:10px; margin-bottom:0; cursor:pointer; user-select:none;
background:var(--panel); border:1px solid var(--line); border-radius:var(--radius) var(--radius) 0 0;
padding:14px 20px; transition:box-shadow .15s ease,color .15s ease;
}
.step-head:hover{color:var(--accent-dark); box-shadow:0 6px 16px -10px rgba(11,37,48,.3);}
.step.collapsed .step-head{border-radius:var(--radius);}
.num{width:24px; height:24px; background:var(--accent); color:#fff; border-radius:50%; display:flex; align-items:center; justify-content:center; font-size:12px; font-weight:700; flex:none;}
.step-title{font-weight:700; font-size:12.5px; letter-spacing:.08em; text-transform:uppercase; color:var(--ink);}
.step-arrow{margin-left:auto; font-size:11px; color:var(--dim); transition:transform .15s ease; padding-left:8px;}
.step.collapsed .step-arrow{transform:rotate(-90deg);}
.step.collapsed .step-body{display:none;}
.step-body{border:1px solid var(--line); border-top:none; background:var(--panel); border-radius:0 0 var(--radius) var(--radius); padding:20px 18px 18px; box-shadow:0 1px 2px rgba(11,37,48,.04), 0 8px 24px -16px rgba(11,37,48,.08);}
label.field-label{display:block; font-size:11.5px; text-transform:uppercase; letter-spacing:.05em; color:var(--dim); margin-bottom:5px; font-weight:600;}
input[type=text], input[type=password], select, textarea{
width:100%; font-family:var(--body-font); font-size:14px; padding:9px 11px;
border:1px solid var(--line); background:#fff; color:var(--ink); border-radius:8px;
}
input:focus, select:focus, textarea:focus{outline:2px solid var(--accent); outline-offset:1px;}
textarea{resize:vertical;}
.row{display:grid; gap:14px;}
.row.cols-2{grid-template-columns:1fr 1fr;}
.row.cols-3{grid-template-columns:1fr 1fr 1fr;}
@media (max-width:720px){ .row.cols-2, .row.cols-3{grid-template-columns:1fr;} }
button{
font-family:var(--body-font); font-weight:700; font-size:13px; cursor:pointer;
border:none; background:var(--accent); color:#fff;
padding:10px 18px; border-radius:999px; letter-spacing:.01em;
transition:background .12s, transform .06s;
}
button:hover:not(:disabled){background:var(--accent-dark);}
button.secondary{background:transparent; color:var(--dim); border:1.5px solid var(--line);}
button.secondary:hover:not(:disabled){background:var(--accent-dim); color:var(--ink); border-color:var(--line);}
button.peer{background:var(--accent-dim); color:var(--accent-dark); border:1.5px solid var(--accent);}
button.peer:hover:not(:disabled){background:var(--accent); color:#fff;}
button:disabled{opacity:.45; cursor:not-allowed;}
#specialtySelect{margin-bottom:14px;}
.hint{font-size:12px; color:var(--dim); margin-top:6px;}
.hint.ok{color:var(--accent-dark);}
.hint.err{color:var(--warn);}
.status-line{font-size:12px; color:var(--dim); margin-top:10px; min-height:14px;}
.status-line.err{color:var(--warn);}
.upload-row{margin-top:14px; padding-top:14px; border-top:1px dashed var(--line);}
.upload-row label{margin-bottom:6px;}
.upload-row input[type=file]{
width:100%; font-family:var(--body-font); font-size:12.5px; color:var(--dim);
border:1px dashed var(--line); border-radius:8px; padding:8px 10px; background:var(--bg);
}
.upload-row input[type=file]::file-selector-button{
font-family:var(--body-font); font-weight:600; font-size:12px; color:#fff;
background:var(--accent); border:none; border-radius:999px; padding:6px 13px; margin-right:10px; cursor:pointer;
}
.case-mode-note{font-size:12px; color:var(--dim); margin-bottom:10px; border-left:3px solid var(--accent); padding:8px 12px; background:var(--accent-dim); border-radius:0 8px 8px 0;}
/* Workspace */
#workspace{display:none;}
.case-banner{display:flex; justify-content:space-between; align-items:center; border:1px solid var(--line); background:var(--panel); border-radius:var(--radius); padding:12px 16px; margin-bottom:16px; flex-wrap:wrap; gap:10px;}
.case-banner .meta{font-size:12.5px; color:var(--dim);}
.case-banner .meta b{color:var(--ink);}
.case-status{font-size:11px; padding:3px 10px; border-radius:20px; border:1px solid var(--line); text-transform:uppercase; letter-spacing:.05em; font-weight:600;}
.case-status.ongoing{color:var(--accent-dark); border-color:var(--accent); background:var(--accent-dim);}
.case-status.complete{color:var(--warn); border-color:var(--warn); background:var(--warn-soft);}
.grid-main{display:grid; grid-template-columns:1.15fr 1fr; gap:18px;}
@media (max-width:960px){ .grid-main{grid-template-columns:1fr;} }
.panel{border:1px solid var(--line); background:var(--panel); border-radius:var(--radius); overflow:hidden;}
.panel-head{border-bottom:1px solid var(--line); padding:10px 14px; font-size:11.5px; text-transform:uppercase; letter-spacing:.05em; color:var(--dim); font-weight:600; display:flex; justify-content:space-between; align-items:center;}
.panel-body{padding:14px;}
/* console */
#console{height:420px; overflow-y:auto; padding:14px; font-size:13.5px;}
.msg{margin-bottom:14px; padding-bottom:12px; border-bottom:1px dashed var(--line);}
.msg:last-child{border-bottom:none;}
.msg .who{font-size:10.5px; text-transform:uppercase; letter-spacing:.06em; color:var(--dim); margin-bottom:4px; font-weight:600;}
.msg.user .who{color:var(--accent-dark);}
.msg.case .who{color:var(--ink);}
.msg .body{white-space:pre-wrap;}
.msg.peer{background:var(--accent-dim); border-radius:8px; padding:8px 10px;}
.msg.peer .who{color:var(--accent-dark);}
.composer{border-top:1px solid var(--line); padding:12px 14px;}
.composer-row{display:flex; gap:8px;}
.composer textarea{flex:1; min-height:52px;}
.composer-actions{display:flex; flex-direction:column; gap:6px;}
/* dashboard */
.vitals-grid{display:grid; grid-template-columns:repeat(3,1fr); gap:8px; margin-bottom:12px;}
.vital{border:1px solid var(--line); background:var(--accent-dim); padding:8px 10px; text-align:center; border-radius:8px;}
.vital .k{font-size:10px; color:var(--dim); text-transform:uppercase;}
.vital .v{font-size:15px; font-weight:700; margin-top:2px; color:var(--ink);}
.vital.flag-high .v, .vital.flag-low .v{color:var(--warn);}
table.labs{width:100%; border-collapse:collapse; font-size:12.5px; margin-bottom:4px;}
table.labs th, table.labs td{border-bottom:1px solid var(--line); padding:6px 6px; text-align:left;}
table.labs th{color:var(--dim); font-weight:600; text-transform:uppercase; font-size:10.5px;}
table.labs td.flag-high, table.labs td.flag-low{color:var(--warn); font-weight:700;}
.empty-note{color:var(--dim); font-size:12px; font-style:italic;}
.tabbar{display:flex; border-bottom:1px solid var(--line); background:var(--accent-dim);}
.tabbtn{flex:1; padding:10px 6px; font-size:11px; text-transform:uppercase; letter-spacing:.05em; text-align:center; color:var(--dim); border-right:1px solid var(--line); cursor:pointer; background:transparent; font-weight:600;}
.tabbtn:last-child{border-right:none;}
.tabbtn.active{color:#fff; font-weight:700; background:var(--accent);}
.tabpane{display:none; padding:14px; font-size:13px;}
.tabpane.active{display:block;}
.soap-block{margin-bottom:12px;}
.soap-block .lbl{font-size:10.5px; color:var(--dim); text-transform:uppercase; letter-spacing:.06em; margin-bottom:3px; display:block; font-weight:600;}
.soap-block .txt{white-space:pre-wrap;}
ol.ddx{margin:0; padding-left:18px;}
ol.ddx li{margin-bottom:6px;}
ul.pearls{margin:0; padding-left:18px;}
ul.pearls li{margin-bottom:8px;}
ul.pearls li::marker{color:var(--accent);}
.toolbar-row{display:flex; gap:8px; flex-wrap:wrap; align-items:center; margin-bottom:14px;}
.toolbar-row button{padding:8px 14px; font-size:12px;}
#voiceBtn.voice-on{background:var(--accent-dark); border-color:var(--accent-dark);}
#voiceBtn .dot{display:inline-block; width:7px; height:7px; border-radius:50%; background:rgba(255,255,255,.6); margin-right:6px; vertical-align:middle;}
#voiceBtn.voice-on .dot{background:#fff; animation:pulse 1s ease-in-out infinite;}
@keyframes pulse{0%,100%{opacity:1;}50%{opacity:.35;}}
.footer-note{margin-top:30px; text-align:center; font-size:11px; color:var(--dim);}
.spinner{display:inline-block; width:11px; height:11px; border:2px solid var(--line); border-top-color:var(--accent); border-radius:50%; animation:spin .7s linear infinite; vertical-align:middle; margin-right:6px;}
@keyframes spin{to{transform:rotate(360deg);}}
</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" class="active">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">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="brandline">
<h1>Vibe Rounds — Case Simulator</h1>
<span class="rx">Rx: cases, not answers</span>
</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 class="disclaimer">
<b>Educational use only.</b> All case content is LLM-generated and may contain errors. Not a diagnostic tool and not for real patient care. 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>
</header>
<!-- STEP 1: MODEL -->
<div class="step collapsed" id="step-model">
<div class="step-head" onclick="toggleStep('step-model')"><div class="num">1</div><div class="step-title">Model</div><span class="step-arrow">▾</span></div>
<div class="step-body">
<div class="row cols-3">
<div>
<label class="field-label">Provider</label>
<select id="provider">
<option value="anthropic">Claude</option>
<option value="openai">ChatGPT (OpenAI)</option>
<option value="gemini">Gemini</option>
<option value="other">Other (OpenAI-compatible)</option>
</select>
</div>
<div>
<label class="field-label">Model name</label>
<input type="text" id="modelName" value="claude-sonnet-4-5" placeholder="e.g. claude-sonnet-4-5">
</div>
<div id="endpointField" style="display:none;">
<label class="field-label">API endpoint</label>
<input type="text" id="endpoint" placeholder="https://.../chat/completions">
</div>
</div>
<div style="margin-top:12px;">
<label class="field-label">API key</label>
<input type="password" id="apiKey" placeholder="sk-ant-...">
</div>
<div class="hint" id="keyHelpHint">Key is saved to <code>localStorage</code> on this device only. <a href="https://console.anthropic.com/settings/keys" target="_blank">Get a Claude key →</a></div>
<div class="status-line" id="keyStatus"></div>
</div>
</div>
<!-- STEP 2: CASE (optional) -->
<div class="step collapsed" id="step-case">
<div class="step-head" onclick="toggleStep('step-case')"><div class="num">2</div><div class="step-title">Case (optional)</div><span class="step-arrow">▾</span></div>
<div class="step-body">
<label class="field-label">Paste a case, topic, or link — or leave blank for a random case</label>
<textarea id="caseText" rows="4" placeholder="Paste a vignette, a topic you want to practice (e.g. 'acute pancreatitis with a biliary cause'), or a link to a case. Leave blank and the simulator will invent a case for the specialty below."></textarea>
<div class="hint">If a link can't be fetched automatically, paste the case text itself for best results.</div>
<div class="upload-row">
<label for="caseFile">Or upload a case file — PDF, Word (.doc/.docx), or plain text (.txt), max 10MB</label>
<input type="file" id="caseFile" accept=".pdf,.doc,.docx,.txt,application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,text/plain">
<div class="hint" id="uploadStatus"></div>
</div>
</div>
</div>
<!-- STEP 3: SPECIALTY -->
<div class="step collapsed" id="step-specialty">
<div class="step-head" onclick="toggleStep('step-specialty')"><div class="num">3</div><div class="step-title">Specialty</div><span class="step-arrow">▾</span></div>
<div class="step-body">
<div class="case-mode-note" id="caseModeNote" style="display:none;">Using your supplied case — the specialty below is only used to set the tone/lens for how the case is run, a diagnosis won't be invented from scratch.</div>
<label class="field-label" id="specialtyLabel">Choose a specialty for the case</label>
<select id="specialtySelect">
<option value="" selected disabled>Select a specialty…</option>
</select>
<div class="row cols-2">
<div>
<label class="field-label">Difficulty</label>
<select id="difficulty">
<option value="foundational">Foundational</option>
<option value="intermediate" selected>Intermediate</option>
<option value="advanced">Advanced / atypical</option>
</select>
</div>
<div>
<label class="field-label">Setting</label>
<select id="setting">
<option value="emergency department">Emergency department</option>
<option value="general ward">General ward</option>
<option value="outpatient clinic">Outpatient clinic</option>
<option value="ICU">ICU</option>
</select>
</div>
</div>
<div style="margin-top:14px;">
<button id="startBtn" disabled>Start case</button>
<span class="status-line" id="startStatus"></span>
</div>
</div>
</div>
<!-- WORKSPACE -->
<div id="workspace">
<div class="case-banner">
<div class="meta">Case: <b id="bannerCaseSource">—</b> · Specialty: <b id="bannerSpecialty">—</b> · Setting: <b id="bannerSetting">—</b> · Difficulty: <b id="bannerDifficulty">—</b></div>
<div class="case-status ongoing" id="caseStatusPill">ongoing</div>
</div>
<div class="toolbar-row">
<button class="secondary" id="downloadTxtBtn">Download .txt</button>
<button class="secondary" id="voiceBtn"><span class="dot"></span>Voice: Off</button>
<select id="voiceSelect" class="secondary" style="max-width:220px; display:none; font-family:var(--mono); font-size:11.5px; padding:7px 10px; border:1px solid var(--line); border-radius:2px;"></select>
</div>
<div class="grid-main">
<!-- LEFT: console -->
<div class="panel">
<div class="panel-head">
<span>Console</span>
<span id="turnCount" style="text-transform:none; letter-spacing:0;">turn 0</span>
</div>
<div id="console"></div>
<div class="composer">
<div class="composer-row">
<textarea id="userInput" placeholder="Ask the patient a question, request an exam finding, order a test, or state your management plan..."></textarea>
<div class="composer-actions">
<button id="sendBtn">Send</button>
<button class="peer" id="peerBtn">Peer</button>
</div>
</div>
<div class="status-line" id="consoleStatus"></div>
</div>
</div>
<!-- RIGHT: dashboard + tabs -->
<div style="display:flex; flex-direction:column; gap:14px;">
<div class="panel">
<div class="panel-head"><span>Dashboard</span></div>
<div class="panel-body">
<div class="vitals-grid" id="vitalsGrid"></div>
<table class="labs" id="labsTable">
<thead><tr><th>Test</th><th>Value</th><th>Flag</th></tr></thead>
<tbody id="labsBody"></tbody>
</table>
<div class="empty-note" id="labsEmpty">No labs resulted yet.</div>
</div>
</div>
<div class="panel">
<div class="tabbar">
<div class="tabbtn active" data-tab="soap">SOAP</div>
<div class="tabbtn" data-tab="reasoning">Reasoning</div>
<div class="tabbtn" data-tab="pearls">Pearls</div>
</div>
<div class="tabpane active" id="tab-soap">
<div class="soap-block"><span class="lbl">S — Subjective</span><div class="txt" id="soapS">—</div></div>
<div class="soap-block"><span class="lbl">O — Objective</span><div class="txt" id="soapO">—</div></div>
<div class="soap-block"><span class="lbl">A — Assessment</span><div class="txt" id="soapA">—</div></div>
<div class="soap-block"><span class="lbl">P — Plan</span><div class="txt" id="soapP">—</div></div>
</div>
<div class="tabpane" id="tab-reasoning">
<span class="lbl" style="display:block; margin-bottom:8px;">Differential (ranked)</span>
<ol class="ddx" id="ddxList"><li class="empty-note" style="list-style:none; margin-left:-18px;">Not yet generated.</li></ol>
</div>
<div class="tabpane" id="tab-pearls">
<ul class="pearls" id="pearlsList"><li class="empty-note" style="list-style:none; margin-left:-18px;">Pearls will appear here as the case unfolds.</li></ul>
</div>
</div>
</div>
</div>
</div>
<div class="footer-note">Vibe Rounds - Case Simulator · runs entirely in your browser · bring your own key</div>
</div>
<script>
function toggleStep(id){
const el = document.getElementById(id);
if(el) el.classList.toggle('collapsed');
}
const SPECIALTY_GROUPS = [
{ group: "Internal Medicine & Subspecialties", items: [
"Cardiology","Respiratory / Pulmonology","Gastroenterology","Hepatology","Neurology","Endocrinology / Diabetes",
"Renal / Nephrology / Electrolyte","Infectious Disease","Hematology","Oncology","Rheumatology","Allergy / Immunology",
"Geriatric Medicine","General / Internal Medicine"
]},
{ group: "Surgical Specialties", items: [
"General Surgery","Orthopedics","Neurosurgery","Cardiothoracic Surgery","Vascular Surgery","Urology",
"Plastic / Reconstructive Surgery","ENT / Otolaryngology","Ophthalmology","Transplant Surgery","Pediatric Surgery"
]},
{ group: "Emergency & Critical Care", items: [
"Emergency Medicine / Trauma","Critical Care / ICU","Anesthesiology / Perioperative Medicine","Toxicology"
]},
{ group: "Women's & Children's Health", items: [
"Obstetrics & Gynecology","Pediatrics","Neonatology","Adolescent Medicine"
]},
{ group: "Mental Health & Neuro-behavioral", items: [
"Psychiatry","Child & Adolescent Psychiatry","Addiction Medicine","Behavioral / Developmental Pediatrics"
]},
{ group: "Primary Care & Community", items: [
"Family Medicine","Community / Public Health Medicine","Occupational Medicine","Sports Medicine",
"Palliative Care / Hospice"
]},
{ group: "Diagnostics & Imaging", items: [
"Radiology","Nuclear Medicine","Pathology","Clinical Genetics / Genomics"
]},
{ group: "Skin, Bone & Sensory", items: [
"Dermatology","Rheumatology / Musculoskeletal","Audiology / Otology"
]},
{ group: "Reproductive & Sexual Health", items: [
"Reproductive Endocrinology / Fertility","Sexual Health / Genitourinary Medicine"
]},
{ group: "Other", items: [
"Dentistry / Oral & Maxillofacial","Physical Medicine & Rehabilitation","Sleep Medicine","Travel / Tropical Medicine",
"Wilderness / Austere Medicine","Forensic Medicine","Medical Ethics / Bioethics Case"
]}
];
const specialtySelect = document.getElementById('specialtySelect');
let selectedSpecialty = null;
SPECIALTY_GROUPS.forEach(g=>{
const og = document.createElement('optgroup');
og.label = g.group;
g.items.forEach(s=>{
const opt = document.createElement('option');
opt.value = s; opt.textContent = s;
og.appendChild(opt);
});
specialtySelect.appendChild(og);
});
specialtySelect.addEventListener('change', ()=>{
selectedSpecialty = specialtySelect.value || null;
refreshStart();
if(typeof gtag==='function') gtag('event','specialty_selected',{specialty:selectedSpecialty});
});
// ---- provider / key persistence ----
const providerSel = document.getElementById('provider');
const endpointField = document.getElementById('endpointField');
const endpointInput = document.getElementById('endpoint');
const modelInput = document.getElementById('modelName');
const keyInput = document.getElementById('apiKey');
const keyStatus = document.getElementById('keyStatus');
function loadStored(){
try{
const s = JSON.parse(localStorage.getItem('vr_case_sim_cfg')||'{}');
if(s.provider) providerSel.value = s.provider;
if(s.model) modelInput.value = s.model;
if(s.endpoint) endpointInput.value = s.endpoint;
if(s.key) { keyInput.value = s.key; keyStatus.textContent = 'Key loaded from this browser.'; }
}catch(e){}
toggleEndpointField();
applyProviderDefaults();
}
function persist(){
localStorage.setItem('vr_case_sim_cfg', JSON.stringify({
provider: providerSel.value, model: modelInput.value,
endpoint: endpointInput.value, key: keyInput.value
}));
}
function toggleEndpointField(){
endpointField.style.display = providerSel.value === 'other' ? 'block' : 'none';
}
const PROVIDER_INFO = {
anthropic: { hint: 'Key is saved to <code>localStorage</code> on this device only. <a href="https://console.anthropic.com/settings/keys" target="_blank">Get a Claude key →</a>', placeholder:'sk-ant-...', defaultModel:'claude-sonnet-4-5' },
openai: { hint: 'Key is saved to <code>localStorage</code> on this device only. <a href="https://platform.openai.com/api-keys" target="_blank">Get an OpenAI key →</a>', placeholder:'sk-...', defaultModel:'gpt-4o' },
gemini: { hint: 'Key is saved to <code>localStorage</code> on this device only. <a href="https://aistudio.google.com/apikey" target="_blank">Get a Gemini key →</a>', placeholder:'AIza...', defaultModel:'gemini-2.0-flash' },
other: { hint: 'Key is saved to <code>localStorage</code> on this device only.', placeholder:'sk-...', defaultModel:'' }
};
function applyProviderDefaults(){
const info = PROVIDER_INFO[providerSel.value] || PROVIDER_INFO.other;
document.getElementById('keyHelpHint').innerHTML = info.hint;
keyInput.placeholder = info.placeholder;
if(!modelInput.value.trim() || Object.values(PROVIDER_INFO).some(i=>i.defaultModel===modelInput.value.trim())){
modelInput.value = info.defaultModel;
}
}
providerSel.addEventListener('change', ()=>{ toggleEndpointField(); applyProviderDefaults(); persist(); refreshStart(); });
[modelInput, endpointInput, keyInput].forEach(el=>el.addEventListener('input', ()=>{ persist(); refreshStart(); }));
loadStored();
// ---- case text / file (optional) ----
const caseTextEl = document.getElementById('caseText');
const caseModeNote = document.getElementById('caseModeNote');
const specialtyLabel = document.getElementById('specialtyLabel');
function loadStoredCase(){
try{ return localStorage.getItem('vr_case_sim_case') || ''; }catch(e){ return ''; }
}
function saveStoredCase(t){ try{ localStorage.setItem('vr_case_sim_case', t); }catch(e){} }
caseTextEl.value = loadStoredCase();
function updateCaseModeUI(){
const hasCase = caseTextEl.value.trim().length > 0;
caseModeNote.style.display = hasCase ? 'block' : 'none';
specialtyLabel.textContent = hasCase
? 'Specialty (optional — sets tone/lens for your supplied case)'
: 'Choose a specialty for the case';
}
caseTextEl.addEventListener('input', ()=>{
saveStoredCase(caseTextEl.value);
updateCaseModeUI();
refreshStart();
});
updateCaseModeUI();
/* ---------- case file upload (PDF / Word / text) ---------- */
const MAX_UPLOAD_BYTES = 10 * 1024 * 1024; // 10MB
if(typeof pdfjsLib !== 'undefined'){
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';
}
function setUploadStatus(msg, kind){
const el = document.getElementById('uploadStatus');
el.textContent = msg;
el.className = 'hint' + (kind ? ' ' + kind : '');
}
async function extractPdfText(file){
const buf = await file.arrayBuffer();
const pdf = await pdfjsLib.getDocument({data: buf}).promise;
let out = [];
for(let i = 1; i <= pdf.numPages; i++){
const page = await pdf.getPage(i);
const content = await page.getTextContent();
out.push(content.items.map(it => it.str).join(' '));
}
return out.join('\n\n').trim();
}
async function extractDocxText(file){
const buf = await file.arrayBuffer();
const result = await mammoth.extractRawText({arrayBuffer: buf});
return (result.value || '').trim();
}
function extractTxtText(file){
return file.text();
}
document.getElementById('caseFile').addEventListener('change', async (e)=>{
const file = e.target.files && e.target.files[0];
if(!file) return;
if(file.size > MAX_UPLOAD_BYTES){
setUploadStatus(`"${file.name}" is ${(file.size/1024/1024).toFixed(1)}MB — max allowed is 10MB.`, 'err');
e.target.value = '';
return;
}
const name = file.name.toLowerCase();
const isPdf = name.endsWith('.pdf') || file.type === 'application/pdf';
const isDocx = name.endsWith('.docx') || file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
const isDoc = name.endsWith('.doc') && !isDocx;
const isTxt = name.endsWith('.txt') || file.type === 'text/plain';
if(!isPdf && !isDocx && !isDoc && !isTxt){
setUploadStatus('Unsupported file type. Please upload a PDF, Word (.doc/.docx), or .txt file.', 'err');
e.target.value = '';
return;
}
setUploadStatus(`Reading "${file.name}"…`);
try{
let text = '';
if(isPdf){
text = await extractPdfText(file);
} else if(isDocx){
text = await extractDocxText(file);
} else if(isDoc){
setUploadStatus('Legacy .doc files can\'t be parsed in-browser — please save as .docx or .pdf and re-upload.', 'err');
e.target.value = '';
return;
} else {
text = await extractTxtText(file);
}
if(!text){
setUploadStatus(`Couldn't find any readable text in "${file.name}". Try a different file or paste the case manually.`, 'err');
e.target.value = '';
return;
}
const existing = caseTextEl.value.trim();
caseTextEl.value = existing ? existing + '\n\n' + text : text;
saveStoredCase(caseTextEl.value);
updateCaseModeUI();
refreshStart();
setUploadStatus(`Loaded case text from "${file.name}".`, 'ok');
if(typeof gtag==='function') gtag('event','upload_case_file', {fileType: isPdf ? 'pdf' : (isDocx ? 'docx' : 'txt')});
} catch(err){
setUploadStatus('Could not read that file: ' + err.message, 'err');
} finally {
e.target.value = '';
}
});
// ---- start gating ----
const startBtn = document.getElementById('startBtn');
const startStatus = document.getElementById('startStatus');
function refreshStart(){
const hasCase = caseTextEl.value.trim().length > 0;
const ok = (selectedSpecialty || hasCase) && keyInput.value.trim().length>0 && modelInput.value.trim().length>0
&& (providerSel.value!=='other' || endpointInput.value.trim().length>0);
startBtn.disabled = !ok;
}
refreshStart();
// ---- state ----
let history = []; // {role:'user'|'assistant', content:'...'} raw text turns for API
let turnCount = 0;
let caseComplete = false;
const SYSTEM_PROMPT_BASE = (specialty, setting, difficulty, caseSeed) => `You are the simulation engine for "Vibe Rounds Case Simulator," a clinical-reasoning training tool for medical learners. You play the roles of patient, nurse, and diagnostic results, and you track structured case state.
Case parameters:
- Specialty focus: ${specialty || 'Not specified — infer an appropriate specialty from the supplied case'}
- Setting: ${setting}
- Difficulty: ${difficulty}
${caseSeed ? `\nThe learner has supplied their own case material to run (this may be a full vignette, a topic/theme to build a case around, a link, or notes extracted from an uploaded file). Treat it as authoritative source material:\n"""\n${caseSeed}\n"""\n` : ''}
Rules:
- This is a simulation for educational reasoning practice only, never real patient care. Never break character to give real-world medical advice.
- On the FIRST turn (when the user message is exactly "__BEGIN__"):${caseSeed
? ` build the opening scenario from the supplied case material above. If it is already a full vignette, adapt it faithfully (you may lightly fill small gaps like initial vitals only if needed for the simulation to run, without contradicting anything given). If it is a topic, theme, or a link's context rather than a full vignette, invent a plausible, internally consistent case that fits that topic at the requested specialty/setting/difficulty. Do not reveal the diagnosis. Present the opening scenario as "message" and populate an initial differential and initial vitals.`
: ` invent a plausible, internally consistent case (chief complaint, brief history, initial vitals) appropriate to the specialty/setting/difficulty, and present the opening scenario as "message". Do not reveal the diagnosis. Also populate an initial differential and initial vitals.`}
- On every subsequent turn, respond to the learner's action (a question to the patient, an exam maneuver, an ordered test, or a management step) with what would realistically happen or be found, advancing the case coherently. Reveal new labs/vitals/exam findings only when the learner's action would elicit them.
- Keep the underlying case internally consistent turn to turn (same past history, same true diagnosis, same values already given).
- Continuously update: vitals (only include vitals that exist/are known so far), labs (append newly resulted labs; do not repeat old ones already sent unless they change), a cumulative SOAP note (subjective/objective/assessment/plan, each as a short running paragraph reflecting everything known so far), a ranked differential list (most to least likely, 3-6 items, each with a few-word rationale), and any NEW clinical pearls worth surfacing this turn (short, specific, non-repeating; can be empty array most turns).
- Mark caseStatus "complete" only once the learner has committed to a final diagnosis and management plan and you have delivered a brief closing debrief; otherwise "ongoing".
- Respond ONLY with a single valid JSON object, no markdown fences, no prose outside the JSON, matching exactly this shape:
{"message": "string, what the patient/environment says or shows this turn, 1-6 sentences",
"vitals": {"HR": "string or omit key", "BP": "string or omit key", "RR": "string or omit key", "Temp": "string or omit key", "SpO2": "string or omit key"},
"labs": [{"name":"string","value":"string","flag":"high|low|normal"}],
"soap": {"s":"string","o":"string","a":"string","p":"string"},
"differential": ["ranked item 1 with brief rationale", "..."],
"newPearls": ["string", "..."],
"caseStatus": "ongoing" or "complete"}
Only include lab/vital entries that are newly known or updated; omit unknown fields rather than inventing placeholders.`;
function currentSystemPrompt(){
return SYSTEM_PROMPT_BASE(selectedSpecialty, document.getElementById('setting').value, document.getElementById('difficulty').value, caseTextEl.value.trim());
}
// ---- API call ----
async function callModel(userText){
const provider = providerSel.value;
const model = modelInput.value.trim();
const key = keyInput.value.trim();
history.push({role:'user', content:userText});
if(provider === 'anthropic'){
const resp = await fetch('https://api.anthropic.com/v1/messages', {
method:'POST',
headers:{
'Content-Type':'application/json',
'x-api-key': key,
'anthropic-version':'2023-06-01',
'anthropic-dangerous-direct-browser-access':'true'
},
body: JSON.stringify({
model: model,
max_tokens: 4096,
system: currentSystemPrompt(),
messages: history
})
});
if(!resp.ok){
const t = await resp.text();
throw new Error('API error '+resp.status+': '+t.slice(0,300));
}
const data = await resp.json();
const text = (data.content||[]).map(b=>b.text||'').join('\n').trim();
history.push({role:'assistant', content:text});
return text;
} else if(provider === 'openai'){
const resp = await fetch('https://api.openai.com/v1/chat/completions', {
method:'POST',
headers:{ 'Content-Type':'application/json', 'Authorization':'Bearer '+key },
body: JSON.stringify({
model: model,
messages: [{role:'system', content: currentSystemPrompt()}, ...history]
})
});
if(!resp.ok){
const t = await resp.text();
throw new Error('API error '+resp.status+': '+t.slice(0,300));
}
const data = await resp.json();
const text = data.choices?.[0]?.message?.content?.trim() || '';
history.push({role:'assistant', content:text});
return text;
} else if(provider === 'gemini'){
const resp = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${encodeURIComponent(model)}:generateContent?key=${encodeURIComponent(key)}`, {
method:'POST',
headers:{ 'Content-Type':'application/json' },
body: JSON.stringify({
systemInstruction: { parts: [{ text: currentSystemPrompt() }] },
contents: history.map(h=>({
role: h.role === 'assistant' ? 'model' : 'user',
parts: [{ text: h.content }]
}))
})
});
if(!resp.ok){
const t = await resp.text();
throw new Error('API error '+resp.status+': '+t.slice(0,300));
}
const data = await resp.json();
const text = (data.candidates?.[0]?.content?.parts||[]).map(p=>p.text||'').join('\n').trim();
history.push({role:'assistant', content:text});
return text;
} else {
const endpoint = endpointInput.value.trim();
const resp = await fetch(endpoint, {
method:'POST',
headers:{ 'Content-Type':'application/json', 'Authorization':'Bearer '+key },
body: JSON.stringify({
model: model,
messages: [{role:'system', content: currentSystemPrompt()}, ...history]
})
});
if(!resp.ok){
const t = await resp.text();
throw new Error('API error '+resp.status+': '+t.slice(0,300));
}
const data = await resp.json();
const text = data.choices?.[0]?.message?.content?.trim() || '';
history.push({role:'assistant', content:text});
return text;
}
}
function parseJsonLoose(text){
let t = text.trim();
t = t.replace(/^```json/i,'').replace(/^```/,'').replace(/```$/,'').trim();
const start = t.indexOf('{'); const end = t.lastIndexOf('}');
if(start>=0 && end>start) t = t.slice(start, end+1);
return JSON.parse(t);
}
// ---- UI render helpers ----
const consoleEl = document.getElementById('console');
let transcriptLog = []; // {who, text, cls}
function appendMsg(who, text, cls){
const div = document.createElement('div');
div.className = 'msg ' + (cls||'');
div.innerHTML = `<div class="who">${who}</div><div class="body"></div>`;
div.querySelector('.body').textContent = text;
consoleEl.appendChild(div);
consoleEl.scrollTop = consoleEl.scrollHeight;
transcriptLog.push({who, text, cls: cls||''});
if((cls==='case' || cls==='peer') && voiceOn) speakText(text);
}
const vitalsGrid = document.getElementById('vitalsGrid');
let vitalsState = {};
function renderVitals(newVitals){
Object.assign(vitalsState, newVitals||{});
vitalsGrid.innerHTML = '';
const keys = Object.keys(vitalsState);
if(keys.length===0){ vitalsGrid.innerHTML = '<div class="empty-note">No vitals yet.</div>'; return; }
keys.forEach(k=>{
const v = document.createElement('div');
v.className = 'vital';
v.innerHTML = `<div class="k">${k}</div><div class="v">${vitalsState[k]}</div>`;
vitalsGrid.appendChild(v);
});
}
const labsBody = document.getElementById('labsBody');
const labsEmpty = document.getElementById('labsEmpty');
let labsState = [];
function renderLabs(newLabs){
if(newLabs && newLabs.length){
newLabs.forEach(nl=>{
const idx = labsState.findIndex(l=>l.name.toLowerCase()===nl.name.toLowerCase());
if(idx>=0) labsState[idx]=nl; else labsState.push(nl);
});
}
labsBody.innerHTML='';
labsEmpty.style.display = labsState.length ? 'none':'block';
labsState.forEach(l=>{
const tr = document.createElement('tr');
const flagCls = l.flag==='high'?'flag-high':(l.flag==='low'?'flag-low':'');
tr.innerHTML = `<td>${l.name}</td><td>${l.value}</td><td class="${flagCls}">${l.flag||'normal'}</td>`;
labsBody.appendChild(tr);
});
}
let soapState = {s:'',o:'',a:'',p:''};
let ddxState = [];
let pearlsState = [];
function renderSoap(soap){
if(!soap) return;
if(soap.s){ document.getElementById('soapS').textContent = soap.s; soapState.s = soap.s; }
if(soap.o){ document.getElementById('soapO').textContent = soap.o; soapState.o = soap.o; }
if(soap.a){ document.getElementById('soapA').textContent = soap.a; soapState.a = soap.a; }
if(soap.p){ document.getElementById('soapP').textContent = soap.p; soapState.p = soap.p; }
}
function renderDifferential(list){
if(!list || !list.length) return;
ddxState = list.slice();
const ol = document.getElementById('ddxList');
ol.innerHTML='';
list.forEach(item=>{
const li = document.createElement('li'); li.textContent = item; ol.appendChild(li);
});
}
function renderPearls(newPearls){
if(!newPearls || !newPearls.length) return;
pearlsState = pearlsState.concat(newPearls);
const ul = document.getElementById('pearlsList');
if(ul.querySelector('.empty-note')) ul.innerHTML='';
newPearls.forEach(p=>{
const li = document.createElement('li'); li.textContent = p; ul.appendChild(li);
});
}
function setCaseStatus(status){
const pill = document.getElementById('caseStatusPill');
caseComplete = status === 'complete';
pill.textContent = status;
pill.className = 'case-status ' + (caseComplete ? 'complete':'ongoing');
document.getElementById('sendBtn').disabled = caseComplete;
document.getElementById('peerBtn').disabled = caseComplete;
}
// tabs
document.querySelectorAll('.tabbtn').forEach(btn=>{
btn.addEventListener('click', ()=>{
document.querySelectorAll('.tabbtn').forEach(b=>b.classList.remove('active'));
document.querySelectorAll('.tabpane').forEach(p=>p.classList.remove('active'));
btn.classList.add('active');
document.getElementById('tab-'+btn.dataset.tab).classList.add('active');
});
});
// ---- start case ----
startBtn.addEventListener('click', async ()=>{
const hasCase = caseTextEl.value.trim().length > 0;
document.getElementById('bannerCaseSource').textContent = hasCase ? 'Your supplied case' : 'Random / generated';
document.getElementById('bannerSpecialty').textContent = selectedSpecialty || (hasCase ? 'Inferred from case' : '—');
document.getElementById('bannerSetting').textContent = document.getElementById('setting').value;
document.getElementById('bannerDifficulty').textContent = document.getElementById('difficulty').value;
document.getElementById('workspace').style.display = 'block';
document.getElementById('workspace').scrollIntoView({behavior:'smooth'});
startBtn.disabled = true; startStatus.innerHTML = '<span class="spinner"></span>Generating case...';
history = []; turnCount = 0; vitalsState = {}; labsState = [];
try{
const raw = await callModel('__BEGIN__');
const parsed = parseJsonLoose(raw);
applyTurn(parsed, 'case');
startStatus.textContent = '';
if(typeof gtag==='function') gtag('event','case_started',{
specialty: selectedSpecialty,
setting: document.getElementById('setting').value,
difficulty: document.getElementById('difficulty').value,
caseSource: hasCase ? 'custom' : 'random'
});
}catch(err){
startStatus.textContent = 'Failed to start: ' + err.message;
startStatus.classList.add('err');
}
startBtn.disabled = false;
});
function applyTurn(parsed, who){
appendMsg(who==='case' ? 'Case' : 'Case', parsed.message || '(no message returned)', 'case');
renderVitals(parsed.vitals);
renderLabs(parsed.labs);
renderSoap(parsed.soap);
renderDifferential(parsed.differential);
renderPearls(parsed.newPearls);
setCaseStatus(parsed.caseStatus || 'ongoing');
turnCount++;
document.getElementById('turnCount').textContent = 'turn ' + turnCount;
}
// ---- send / peer ----
const userInput = document.getElementById('userInput');
const sendBtn = document.getElementById('sendBtn');
const peerBtn = document.getElementById('peerBtn');
const consoleStatus = document.getElementById('consoleStatus');
async function sendTurn(){
const text = userInput.value.trim();
if(!text || caseComplete) return;
appendMsg('You', text, 'user');
userInput.value = '';
sendBtn.disabled = true; peerBtn.disabled = true;
consoleStatus.innerHTML = '<span class="spinner"></span>Working...';
consoleStatus.classList.remove('err');
try{
const raw = await callModel(text);
const parsed = parseJsonLoose(raw);
applyTurn(parsed, 'case');
consoleStatus.textContent = '';
if(typeof gtag==='function'){
gtag('event','turn_sent',{specialty: selectedSpecialty, turn: turnCount});
if((parsed.caseStatus||'ongoing')==='complete'){
gtag('event','case_completed',{specialty: selectedSpecialty, total_turns: turnCount});
}
}
}catch(err){
consoleStatus.textContent = 'Error: ' + err.message;
consoleStatus.classList.add('err');
}
sendBtn.disabled = caseComplete; peerBtn.disabled = caseComplete;
}
sendBtn.addEventListener('click', sendTurn);
userInput.addEventListener('keydown', (e)=>{
if(e.key==='Enter' && (e.metaKey||e.ctrlKey)){ sendTurn(); }
});
peerBtn.addEventListener('click', async ()=>{
if(caseComplete) return;
peerBtn.disabled = true; sendBtn.disabled = true;
consoleStatus.innerHTML = '<span class="spinner"></span>Asking a peer...';
consoleStatus.classList.remove('err');
const peerAsk = `__PEER_HELP__ The learner is stuck and has not typed a next step. Based on everything known about the case so far, suggest ONE concrete next question, exam maneuver, test order, or management step they could take, phrased as if a fellow resident were quietly coaching them (2-3 sentences, supportive, do not reveal the diagnosis outright). Respond ONLY with this JSON shape: {"suggestion":"string"} and do not advance the case state.`;
try{
// side-channel call: don't touch main history's case-state consistency expectations beyond an extra turn
const raw = await callModel(peerAsk);
let suggestion = '';
try{ suggestion = parseJsonLoose(raw).suggestion; }catch(e){ suggestion = raw; }
appendMsg('Peer', suggestion, 'peer');
userInput.value = suggestion;
consoleStatus.textContent = 'Peer suggestion loaded into the input — edit and send when ready.';
if(typeof gtag==='function') gtag('event','peer_used',{specialty: selectedSpecialty, turn: turnCount});
}catch(err){
consoleStatus.textContent = 'Error: ' + err.message;
consoleStatus.classList.add('err');
}
peerBtn.disabled = caseComplete; sendBtn.disabled = caseComplete;
});
// ---- text-to-speech voice reader ----
let voiceOn = false;
let voices = [];
const voiceBtn = document.getElementById('voiceBtn');
const voiceSelect = document.getElementById('voiceSelect');
function populateVoices(){
voices = window.speechSynthesis ? window.speechSynthesis.getVoices() : [];
if(!voices.length) return;
voiceSelect.innerHTML = '';
voices.filter(v=>v.lang.startsWith('en')).concat(voices.filter(v=>!v.lang.startsWith('en')))
.forEach(v=>{
const opt = document.createElement('option');
opt.value = v.name; opt.textContent = v.name + ' (' + v.lang + ')';
voiceSelect.appendChild(opt);
});
}
if('speechSynthesis' in window){
populateVoices();
window.speechSynthesis.onvoiceschanged = populateVoices;
}
function speakText(text){
if(!('speechSynthesis' in window) || !text) return;
window.speechSynthesis.cancel();