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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
|
import type { StepId } from "@dispatch/wire";
import { render, screen, within } from "@testing-library/svelte";
import userEvent from "@testing-library/user-event";
import { describe, expect, it, vi } from "vitest";
import type { RenderedChunk } from "../../core/chunks";
import type { TurnMetricsEntry } from "../../core/metrics";
import type { ConvertedJpeg } from "./adapter/image-encode";
import ChatView from "./ui/ChatView.svelte";
import Composer from "./ui/Composer.svelte";
import ModelSelector from "./ui/ModelSelector.svelte";
import ReasoningEffortSelector from "./ui/ReasoningEffortSelector.svelte";
/** Collapsed card bodies render lazily — open every card so its body mounts. */
async function openAllCollapses(container: HTMLElement): Promise<void> {
const boxes = container.querySelectorAll<HTMLInputElement>('.collapse > input[type="checkbox"]');
for (const box of boxes) {
if (!box.checked) await userEvent.click(box);
}
}
describe("ChatView", () => {
it("renders a message's text chunk", () => {
const chunks: RenderedChunk[] = [
{
seq: 1,
role: "assistant",
chunk: { type: "text", text: "Hello world" },
provisional: false,
},
];
render(ChatView, { props: { chunks } });
expect(screen.getByText("Hello world")).toBeInTheDocument();
});
it("renders multiple chunks", () => {
const chunks: RenderedChunk[] = [
{ seq: 1, role: "user", chunk: { type: "text", text: "Hi there" }, provisional: false },
{
seq: 2,
role: "assistant",
chunk: { type: "text", text: "Hello!" },
provisional: false,
},
];
render(ChatView, { props: { chunks } });
expect(screen.getByText("Hi there")).toBeInTheDocument();
expect(screen.getByText("Hello!")).toBeInTheDocument();
});
it("shows the show-earlier button only when earlier history is unloaded, and pages it in", async () => {
const chunks: RenderedChunk[] = [
{ seq: 26, role: "user", chunk: { type: "text", text: "later" }, provisional: false },
];
let resolveEarlier: (() => void) | undefined;
const onShowEarlier = vi.fn(
() =>
new Promise<void>((resolve) => {
resolveEarlier = resolve;
}),
);
render(ChatView, { props: { chunks, hasEarlier: true, onShowEarlier } });
const button = screen.getByRole("button", { name: /show earlier messages/i });
const user = userEvent.setup();
await user.click(button);
expect(onShowEarlier).toHaveBeenCalledTimes(1);
// While the page-in is awaited the button is disabled (no double-fire).
expect(screen.getByRole("button", { name: /loading earlier messages/i })).toBeDisabled();
resolveEarlier?.();
await vi.waitFor(() => {
expect(screen.getByRole("button", { name: /show earlier messages/i })).toBeEnabled();
});
});
it("hides the show-earlier button when nothing is unloaded", () => {
const chunks: RenderedChunk[] = [
{ seq: 1, role: "user", chunk: { type: "text", text: "all here" }, provisional: false },
];
render(ChatView, { props: { chunks, hasEarlier: false, onShowEarlier: vi.fn() } });
expect(screen.queryByRole("button", { name: /show earlier/i })).not.toBeInTheDocument();
});
it("renders tool-call chunks", async () => {
const chunks: RenderedChunk[] = [
{
seq: 1,
role: "assistant",
chunk: {
type: "tool-call",
toolCallId: "tc1",
toolName: "read_file",
input: { path: "/tmp/test.txt" },
},
provisional: false,
},
];
const { container } = render(ChatView, { props: { chunks } });
await openAllCollapses(container);
expect(screen.getByText("Read file")).toBeInTheDocument();
const pre = screen.getByText((content, element) => {
return element?.tagName === "PRE" && content.includes("/tmp/test.txt");
});
expect(pre).toBeInTheDocument();
});
it("renders tool-result chunks", async () => {
const chunks: RenderedChunk[] = [
{
seq: 1,
role: "tool",
chunk: {
type: "tool-result",
toolCallId: "tc1",
toolName: "read_file",
content: "file contents here",
isError: false,
},
provisional: false,
},
];
const { container } = render(ChatView, { props: { chunks } });
await openAllCollapses(container);
expect(screen.getByText("Read file")).toBeInTheDocument();
expect(screen.getByText("file contents here")).toBeInTheDocument();
});
it("renders error chunks with alert role", () => {
const chunks: RenderedChunk[] = [
{
seq: 1,
role: "assistant",
chunk: { type: "error", message: "Something failed" },
provisional: false,
},
];
render(ChatView, { props: { chunks } });
const alert = screen.getByRole("alert");
expect(alert).toHaveTextContent("Something failed");
});
it("renders error chunks with code", () => {
const chunks: RenderedChunk[] = [
{
seq: 1,
role: "assistant",
chunk: { type: "error", message: "Rate limited", code: "RATE_LIMIT" },
provisional: false,
},
];
render(ChatView, { props: { chunks } });
expect(screen.getByText("Rate limited")).toBeInTheDocument();
expect(screen.getByText("[RATE_LIMIT]")).toBeInTheDocument();
});
it("renders system chunks", () => {
const chunks: RenderedChunk[] = [
{
seq: 1,
role: "system",
chunk: { type: "system", text: "System context loaded" },
provisional: false,
},
];
render(ChatView, { props: { chunks } });
expect(screen.getByText("System context loaded")).toBeInTheDocument();
});
it("renders provisional (in-flight) chunks without any dimming", () => {
const chunks: RenderedChunk[] = [
{
seq: null,
role: "assistant",
chunk: { type: "text", text: "Streaming..." },
provisional: true,
},
];
render(ChatView, { props: { chunks } });
// In-flight chunks render at full opacity (no faded "disabled" look).
const wrapper = screen.getByText("Streaming...").closest("div");
expect(wrapper).not.toHaveClass("opacity-50");
});
it("renders empty transcript", () => {
render(ChatView, { props: { chunks: [] } });
const log = screen.getByRole("log");
expect(log).toBeInTheDocument();
expect(log.children).toHaveLength(0);
});
it("renders parallel tool calls (shared stepId) as separate bubbles", async () => {
const chunks: RenderedChunk[] = [
{
seq: 1,
role: "assistant",
chunk: {
type: "tool-call",
toolCallId: "a",
toolName: "read_file",
input: { path: "/a" },
stepId: "t1#0" as StepId,
},
provisional: false,
},
{
seq: 2,
role: "assistant",
chunk: {
type: "tool-call",
toolCallId: "b",
toolName: "list_dir",
input: { path: "/b" },
stepId: "t1#0" as StepId,
},
provisional: false,
},
{
seq: 3,
role: "tool",
chunk: {
type: "tool-result",
toolCallId: "a",
toolName: "read_file",
content: "contents-of-a",
isError: false,
stepId: "t1#0" as StepId,
},
provisional: false,
},
];
const { container } = render(ChatView, { props: { chunks } });
await openAllCollapses(container);
// Parallel calls render as independent collapsible cards (one per bubble).
const collapses = container.querySelectorAll(".collapse");
expect(collapses).toHaveLength(2);
expect(container.querySelectorAll(".chat-bubble")).toHaveLength(2);
// Both call names + the available result are shown; the result is absorbed
// (no standalone tool-result card).
expect(screen.getByText("Read file")).toBeInTheDocument();
expect(screen.getByText("List dir")).toBeInTheDocument();
expect(screen.getByText("contents-of-a")).toBeInTheDocument();
});
it("thinking is a checkbox collapse (no arrow) inside a visible bubble", () => {
const chunks: RenderedChunk[] = [
{
seq: null,
role: "assistant",
chunk: { type: "thinking", text: "Let me think..." },
provisional: true,
streaming: true,
},
];
const { container } = render(ChatView, { props: { chunks } });
const collapse = container.querySelector(".collapse");
expect(collapse).not.toBeNull();
expect(collapse).not.toHaveClass("collapse-arrow"); // no indicator icon
expect(collapse).not.toHaveClass("collapse-plus");
// Visible bubble, like tool cards.
expect(collapse).toHaveClass("bg-base-200");
expect(collapse).toHaveClass("rounded-box");
expect(screen.getByRole("checkbox", { name: "Toggle thoughts" })).toBeInTheDocument();
});
it("title is 'Thinking' + dots while streaming, then 'Thoughts' with no dots once complete; open state persists", async () => {
const streaming: RenderedChunk[] = [
{
seq: null,
role: "assistant",
chunk: { type: "thinking", text: "hmm" },
provisional: true,
streaming: true,
},
];
const { container, rerender } = render(ChatView, { props: { chunks: streaming } });
// Streaming: "Thinking" + loading dots.
expect(screen.getByText("Thinking")).toBeInTheDocument();
expect(screen.queryByText("Thoughts")).toBeNull();
expect(container.querySelector(".loading")).not.toBeNull();
// Open it.
const checkbox = screen.getByRole("checkbox", { name: "Toggle thoughts" });
await userEvent.click(checkbox);
expect(checkbox).toBeChecked();
// Transition generating → completed/committed (seq assigned, no longer streaming).
await rerender({
chunks: [
{
seq: 1,
role: "assistant",
chunk: { type: "thinking", text: "hmm, all done" },
provisional: false,
},
],
});
// Completed: "Thoughts", no dots — and the open state survived the transition.
expect(screen.getByText("Thoughts")).toBeInTheDocument();
expect(screen.queryByText("Thinking")).toBeNull();
expect(container.querySelector(".loading")).toBeNull();
expect(screen.getByRole("checkbox", { name: "Toggle thoughts" })).toBeChecked();
expect(container).toHaveTextContent("hmm, all done");
});
it("renders step and turn metrics as separate rows", () => {
const chunks: RenderedChunk[] = [
{ seq: 1, role: "user", chunk: { type: "text", text: "Hi" }, provisional: false },
{
seq: 2,
role: "assistant",
chunk: { type: "text", text: "Hello!" },
provisional: false,
},
{
seq: 3,
role: "assistant",
chunk: {
type: "tool-call",
toolCallId: "tc1",
toolName: "test",
input: {},
stepId: "t1#0" as StepId,
},
provisional: false,
},
];
const turnMetrics: TurnMetricsEntry[] = [
{
turnId: "t1",
steps: [
{
stepId: "t1#0" as StepId,
usage: { inputTokens: 100, outputTokens: 50 },
genTotalMs: 800,
},
],
total: {
turnId: "t1",
usage: { inputTokens: 100, outputTokens: 50 },
durationMs: 1200,
steps: [
{
stepId: "t1#0" as StepId,
usage: { inputTokens: 100, outputTokens: 50 },
genTotalMs: 800,
},
],
},
},
];
render(ChatView, { props: { chunks, turnMetrics } });
expect(screen.getByText("Hi")).toBeInTheDocument();
expect(screen.getByText("Hello!")).toBeInTheDocument();
expect(screen.getByText(/step 1/)).toBeInTheDocument();
expect(screen.getByText(/step 1 · 100 in \/ 50 out/)).toBeInTheDocument();
expect(screen.getByText(/turn 1 · 50 tok out · 100 in/)).toBeInTheDocument();
expect(screen.getByText(/1\.2s/)).toBeInTheDocument();
});
it("renders a per-step cache hit badge coloured by level", () => {
const step = {
stepId: "t1#0" as StepId,
usage: { inputTokens: 1000, outputTokens: 10, cacheReadTokens: 750 },
decodeMs: 100,
};
const chunks: RenderedChunk[] = [
{ seq: 1, role: "user", chunk: { type: "text", text: "Hi" }, provisional: false },
{
seq: 2,
role: "assistant",
chunk: {
type: "tool-call",
toolCallId: "tc1",
toolName: "t",
input: {},
stepId: step.stepId,
},
provisional: false,
},
];
const turnMetrics: TurnMetricsEntry[] = [{ turnId: "t1", steps: [step], total: null }];
render(ChatView, { props: { chunks, turnMetrics } });
const badge = screen.getByTestId("step-cache-badge");
expect(badge).toHaveTextContent("75%");
expect(badge).toHaveClass("badge-success");
});
it("renders cache hit-rate badges (Last turn + Chat Total) coloured by level", () => {
const chunks: RenderedChunk[] = [
{ seq: 1, role: "user", chunk: { type: "text", text: "Hi" }, provisional: false },
{
seq: 2,
role: "assistant",
chunk: { type: "text", text: "Hello!" },
provisional: false,
},
];
const turnMetrics: TurnMetricsEntry[] = [
{
turnId: "t1",
steps: [],
total: {
turnId: "t1",
usage: { inputTokens: 100, outputTokens: 10, cacheReadTokens: 93 },
steps: [],
},
},
];
const { container } = render(ChatView, { props: { chunks, turnMetrics } });
expect(screen.getByText("Last turn:")).toBeInTheDocument();
expect(screen.getByText("Chat Total:")).toBeInTheDocument();
// single turn ⇒ both the turn rate and the cumulative are 93% ⇒ success badge
const badges = container.querySelectorAll(".badge");
expect(badges).toHaveLength(2);
for (const b of badges) {
expect(b.textContent).toBe("93%");
expect(b.classList.contains("badge-success")).toBe(true);
}
});
it("renders step-metrics inline after tool group", () => {
const chunks: RenderedChunk[] = [
{ seq: 1, role: "user", chunk: { type: "text", text: "Run it" }, provisional: false },
{
seq: 2,
role: "assistant",
chunk: {
type: "tool-call",
toolCallId: "tc1",
toolName: "bash",
input: { command: "ls" },
stepId: "t1#0" as StepId,
},
provisional: false,
},
{
seq: 3,
role: "tool",
chunk: {
type: "tool-result",
toolCallId: "tc1",
toolName: "bash",
content: "file.txt",
isError: false,
stepId: "t1#0" as StepId,
},
provisional: false,
},
{
seq: 4,
role: "assistant",
chunk: { type: "text", text: "Done!" },
provisional: false,
},
];
const turnMetrics: TurnMetricsEntry[] = [
{
turnId: "t1",
steps: [
{
stepId: "t1#0" as StepId,
usage: { inputTokens: 80, outputTokens: 20 },
genTotalMs: 300,
},
],
total: {
turnId: "t1",
usage: { inputTokens: 80, outputTokens: 20 },
durationMs: 500,
steps: [
{
stepId: "t1#0" as StepId,
usage: { inputTokens: 80, outputTokens: 20 },
genTotalMs: 300,
},
],
},
},
];
render(ChatView, { props: { chunks, turnMetrics } });
// Both step-metrics and turn-metrics render
expect(screen.getByText(/step 1/)).toBeInTheDocument();
expect(screen.getByText(/turn 1 · 20 tok out/)).toBeInTheDocument();
// They are in separate elements (different rows)
const stepEl = screen.getByText(/step 1 · 80 in \/ 20 out/).closest("div");
const turnEl = screen.getByText(/turn 1 · 20 tok out/).closest("div");
expect(stepEl).not.toBe(turnEl);
});
it("renders no metrics bubble when turnMetrics is empty", () => {
const chunks: RenderedChunk[] = [
{ seq: 1, role: "user", chunk: { type: "text", text: "Hi" }, provisional: false },
{
seq: 2,
role: "assistant",
chunk: { type: "text", text: "Hello!" },
provisional: false,
},
];
render(ChatView, { props: { chunks, turnMetrics: [] } });
expect(screen.getByText("Hi")).toBeInTheDocument();
expect(screen.getByText("Hello!")).toBeInTheDocument();
expect(screen.queryByText(/step 1/)).toBeNull();
expect(screen.queryByText(/^turn/)).toBeNull();
});
it("omits null view values from metrics bubbles", () => {
const chunks: RenderedChunk[] = [
{ seq: 1, role: "user", chunk: { type: "text", text: "Test" }, provisional: false },
{
seq: 2,
role: "assistant",
chunk: { type: "text", text: "Response" },
provisional: false,
},
{
seq: 3,
role: "assistant",
chunk: {
type: "tool-call",
toolCallId: "tc1",
toolName: "test",
input: {},
stepId: "t1#0" as StepId,
},
provisional: false,
},
];
const turnMetrics: TurnMetricsEntry[] = [
{
turnId: "t1",
steps: [
{
stepId: "t1#0" as StepId,
usage: { inputTokens: 10, outputTokens: 5 },
},
],
total: {
turnId: "t1",
usage: { inputTokens: 10, outputTokens: 5 },
steps: [
{
stepId: "t1#0" as StepId,
usage: { inputTokens: 10, outputTokens: 5 },
},
],
},
},
];
render(ChatView, { props: { chunks, turnMetrics } });
// Step metrics rendered
expect(screen.getByText(/step 1/)).toBeInTheDocument();
expect(screen.getByText(/step 1 · 10 in \/ 5 out/)).toBeInTheDocument();
// Turn metrics rendered
expect(screen.getByText(/turn 1 · 5 tok out · 10 in/)).toBeInTheDocument();
// No "null" or "undefined" in the DOM
expect(screen.queryByText("null")).toBeNull();
expect(screen.queryByText("undefined")).toBeNull();
});
it("renders step text but no turn total for a progressive turn (total: null)", () => {
const chunks: RenderedChunk[] = [
{ seq: 1, role: "user", chunk: { type: "text", text: "Hi" }, provisional: false },
{
seq: 2,
role: "assistant",
chunk: { type: "text", text: "Hello!" },
provisional: false,
},
{
seq: 3,
role: "assistant",
chunk: {
type: "tool-call",
toolCallId: "tc1",
toolName: "test",
input: {},
stepId: "t1#0" as StepId,
},
provisional: false,
},
];
const turnMetrics: TurnMetricsEntry[] = [
{
turnId: "t1",
steps: [
{
stepId: "t1#0" as StepId,
usage: { inputTokens: 100, outputTokens: 50 },
genTotalMs: 800,
},
],
total: null,
},
];
render(ChatView, { props: { chunks, turnMetrics } });
// Step metrics should render
expect(screen.getByText(/step 1 · 100 in \/ 50 out/)).toBeInTheDocument();
// Turn total should NOT render (total is null — turn still in progress)
expect(screen.queryByText(/^turn/)).toBeNull();
});
it("renders a user image chunk as an <img> with the chunk's url", () => {
const url = "data:image/png;base64,AAAA";
const chunks: RenderedChunk[] = [
{
seq: 1,
role: "user",
chunk: { type: "image", url, mimeType: "image/png" },
provisional: false,
},
];
const { container } = render(ChatView, { props: { chunks } });
const img = container.querySelector("img");
expect(img).not.toBeNull();
expect(img?.getAttribute("src")).toBe(url);
expect(img?.getAttribute("alt")).toBe("image/png");
expect(img?.getAttribute("loading")).toBe("lazy");
});
it("resolves a persisted image chunk's relative url against apiBaseUrl", () => {
// Persisted image chunks now carry a compact relative path (`/images/…`)
// served by the backend — prepend the API base to render them.
const chunks: RenderedChunk[] = [
{
seq: 1,
role: "user",
chunk: { type: "image", url: "/images/conv-123/abc-456.png", mimeType: "image/png" },
provisional: false,
},
];
const { container } = render(ChatView, {
props: { chunks, apiBaseUrl: "http://localhost:24203" },
});
expect(container.querySelector("img")?.getAttribute("src")).toBe(
"http://localhost:24203/images/conv-123/abc-456.png",
);
});
it("passes a data URL through unchanged even with apiBaseUrl set (optimistic echo)", () => {
// The optimistic echo (what the FE just sent) is still a data URL; it must
// NOT be mangled by the base-URL prepend.
const dataUrl = "data:image/png;base64,iVBOR=";
const chunks: RenderedChunk[] = [
{ seq: null, role: "user", chunk: { type: "image", url: dataUrl }, provisional: true },
];
const { container } = render(ChatView, {
props: { chunks, apiBaseUrl: "http://localhost:24203" },
});
expect(container.querySelector("img")?.getAttribute("src")).toBe(dataUrl);
});
it("leaves a relative image url root-relative when apiBaseUrl is absent", () => {
// No apiBaseUrl → a browser resolves `/images/…` against the document origin.
const chunks: RenderedChunk[] = [
{
seq: 1,
role: "user",
chunk: { type: "image", url: "/images/conv-1/x.png" },
provisional: false,
},
];
const { container } = render(ChatView, { props: { chunks } });
expect(container.querySelector("img")?.getAttribute("src")).toBe("/images/conv-1/x.png");
});
it("renders a multi-chunk user message [text, image] and a transcription text", () => {
// A non-vision model: the server persists the original image chunk AND a
// transcription text chunk in the SAME user message — render both.
const url = "data:image/png;base64,BBQ=";
const chunks: RenderedChunk[] = [
{ seq: 1, role: "user", chunk: { type: "text", text: "describe this" }, provisional: false },
{
seq: 2,
role: "user",
chunk: { type: "image", url, mimeType: "image/png" },
provisional: false,
},
{
seq: 3,
role: "user",
chunk: { type: "text", text: "[Image analysis (via kimi/k2)]: a red square" },
provisional: false,
},
];
const { container } = render(ChatView, { props: { chunks } });
expect(screen.getByText("describe this")).toBeInTheDocument();
expect(screen.getByText(/\[Image analysis/)).toBeInTheDocument();
expect(container.querySelector("img")?.getAttribute("src")).toBe(url);
});
it("renders a consult_vision tool call/result like any other tool", async () => {
// read_image is GONE — replaced by consult_vision (opens a vision-model
// conversation, attaches the image + question, returns the answer). It is
// a normal tool call: rendered generically by toolName.
const chunks: RenderedChunk[] = [
{
seq: 1,
role: "assistant",
chunk: {
type: "tool-call",
toolCallId: "tc1",
toolName: "consult_vision",
input: { question: "what is in this image?", imageIds: [1] },
},
provisional: false,
},
{
seq: 2,
role: "tool",
chunk: {
type: "tool-result",
toolCallId: "tc1",
toolName: "consult_vision",
content: "a red square on a white background",
isError: false,
},
provisional: false,
},
];
const { container } = render(ChatView, { props: { chunks } });
await openAllCollapses(container);
expect(screen.getAllByText("Ask vision model").length).toBeGreaterThan(0);
expect(screen.getByText("a red square on a white background")).toBeInTheDocument();
});
it("renders a non-vision placeholder text chunk as-is", () => {
// A non-vision model gets a numbered placeholder (a regular text chunk)
// instead of an auto-transcription. Renders like any text chunk.
const chunks: RenderedChunk[] = [
{
seq: 1,
role: "user",
chunk: {
type: "text",
text: "[Image 1 attached — call consult_vision with imageIds=[1] and a specific question to analyze it]",
},
provisional: false,
},
];
render(ChatView, { props: { chunks } });
expect(screen.getByText(/\[Image 1 attached/)).toBeInTheDocument();
expect(screen.getByText(/consult_vision with imageIds/)).toBeInTheDocument();
});
it("renders a compacted-image text chunk as-is", () => {
// Image compaction transcribes old images to [Compacted image]: <desc>.
// Regular text chunk — render as-is.
const chunks: RenderedChunk[] = [
{
seq: 1,
role: "user",
chunk: { type: "text", text: "[Compacted image]: a chart showing rising sales" },
provisional: false,
},
];
render(ChatView, { props: { chunks } });
expect(screen.getByText(/\[Compacted image\]/)).toBeInTheDocument();
expect(screen.getByText(/rising sales/)).toBeInTheDocument();
});
});
describe("Composer", () => {
it("calls onSend with the typed text and clears", async () => {
const onSend = vi.fn();
const user = userEvent.setup();
render(Composer, { props: { onSend } });
const textarea = screen.getByRole("textbox", { name: "Message input" });
await user.type(textarea, "Hello world");
const sendButton = screen.getByRole("button", { name: "Send" });
await user.click(sendButton);
expect(onSend).toHaveBeenCalledTimes(1);
expect(onSend).toHaveBeenCalledWith("Hello world", undefined);
expect(textarea).toHaveValue("");
});
it("does not call onSend with empty text", async () => {
const onSend = vi.fn();
const _user = userEvent.setup();
render(Composer, { props: { onSend } });
const sendButton = screen.getByRole("button", { name: "Send" });
expect(sendButton).toBeDisabled();
expect(onSend).not.toHaveBeenCalled();
});
it("trims whitespace before sending", async () => {
const onSend = vi.fn();
const user = userEvent.setup();
render(Composer, { props: { onSend } });
const textarea = screen.getByRole("textbox", { name: "Message input" });
await user.type(textarea, " hello ");
const sendButton = screen.getByRole("button", { name: "Send" });
await user.click(sendButton);
expect(onSend).toHaveBeenCalledWith("hello", undefined);
});
it("sends on Enter key (without Shift)", async () => {
const onSend = vi.fn();
const user = userEvent.setup();
render(Composer, { props: { onSend } });
const textarea = screen.getByRole("textbox", { name: "Message input" });
await user.type(textarea, "Test message{Enter}");
expect(onSend).toHaveBeenCalledWith("Test message", undefined);
});
it("does not send on Shift+Enter", async () => {
const onSend = vi.fn();
const user = userEvent.setup();
render(Composer, { props: { onSend } });
const textarea = screen.getByRole("textbox", { name: "Message input" });
await user.type(textarea, "Line 1{Shift>}{Enter}{/Shift}Line 2");
expect(onSend).not.toHaveBeenCalled();
});
it("stages a pasted image and forwards it on send", async () => {
const onSend = vi.fn();
const user = userEvent.setup();
const { container } = render(Composer, { props: { onSend } });
const textarea = screen.getByRole("textbox", { name: "Message input" });
await user.type(textarea, "look at this");
// jsdom has no ClipboardEvent/DataTransfer: dispatch a plain paste event
// carrying a mock clipboardData whose only item is an image File.
const file = new File(["PNG"], "shot.png", { type: "image/png" });
const paste = new Event("paste", { bubbles: true });
Object.defineProperty(paste, "clipboardData", {
value: {
items: [{ kind: "file", type: "image/png", getAsFile: () => file }],
},
});
container.querySelector("textarea")?.dispatchEvent(paste);
await vi.waitFor(() => {
expect(screen.getByRole("button", { name: "Remove image" })).toBeInTheDocument();
});
await user.click(screen.getByRole("button", { name: "Send" }));
expect(onSend).toHaveBeenCalledTimes(1);
const [, images] = onSend.mock.calls[0] ?? [];
expect(images).toHaveLength(1);
expect(images[0]?.url).toMatch(/^data:image\/png;base64,/);
expect(images[0]?.mimeType).toBe("image/png");
});
it("lets a text paste proceed when no image is on the clipboard", async () => {
const onSend = vi.fn();
const user = userEvent.setup();
const { container } = render(Composer, { props: { onSend } });
const textarea = screen.getByRole("textbox", { name: "Message input" });
await user.type(textarea, "hello");
// A text-only paste: no file items → the component must NOT preventDefault,
// so the default text paste path is unaffected (no image staged).
const paste = new Event("paste", { bubbles: true });
Object.defineProperty(paste, "clipboardData", {
value: { items: [{ kind: "string", type: "text/plain" }] },
});
container.querySelector("textarea")?.dispatchEvent(paste);
await new Promise((r) => setTimeout(r, 0));
expect(screen.queryByRole("button", { name: "Remove image" })).not.toBeInTheDocument();
});
it("stages an image via the attach button's file picker", async () => {
const onSend = vi.fn();
const user = userEvent.setup();
const { container } = render(Composer, { props: { onSend } });
const file = new File(["JPG"], "photo.jpg", { type: "image/jpeg" });
const input = container.querySelector('input[type="file"]') as HTMLInputElement;
Object.defineProperty(input, "files", { value: [file], writable: false });
input.dispatchEvent(new Event("change", { bubbles: true }));
await vi.waitFor(() => {
expect(screen.getByRole("button", { name: "Remove image" })).toBeInTheDocument();
});
// Image-only send (no text): the Send button is enabled.
const send = screen.getByRole("button", { name: "Send" });
expect(send).not.toBeDisabled();
await user.click(send);
expect(onSend).toHaveBeenCalledTimes(1);
const [text, images] = onSend.mock.calls[0] ?? [];
expect(text).toBe("");
expect(images).toHaveLength(1);
expect(images[0]?.mimeType).toBe("image/jpeg");
});
it("removes a staged image via the remove button", async () => {
const onSend = vi.fn();
const user = userEvent.setup();
const { container } = render(Composer, { props: { onSend } });
const file = new File(["PNG"], "shot.png", { type: "image/png" });
const input = container.querySelector('input[type="file"]') as HTMLInputElement;
Object.defineProperty(input, "files", { value: [file], writable: false });
input.dispatchEvent(new Event("change", { bubbles: true }));
await vi.waitFor(() => {
expect(screen.getByRole("button", { name: "Remove image" })).toBeInTheDocument();
});
await user.click(screen.getByRole("button", { name: "Remove image" }));
expect(screen.queryByRole("button", { name: "Remove image" })).not.toBeInTheDocument();
// With no text and no images, Send is disabled again.
expect(screen.getByRole("button", { name: "Send" })).toBeDisabled();
});
it("ignores a non-image file chosen via the picker", async () => {
const onSend = vi.fn();
const { container } = render(Composer, { props: { onSend } });
const file = new File(["TXT"], "notes.txt", { type: "text/plain" });
const input = container.querySelector('input[type="file"]') as HTMLInputElement;
Object.defineProperty(input, "files", { value: [file], writable: false });
input.dispatchEvent(new Event("change", { bubbles: true }));
// Give the async staging a chance; a non-image is skipped.
await new Promise((r) => setTimeout(r, 0));
expect(screen.queryByRole("button", { name: "Remove image" })).not.toBeInTheDocument();
});
it("queues (steers) text-only and never forwards images", async () => {
// While running, the Send button becomes "Queue"; steering is text-only.
const onQueue = vi.fn();
const onSend = vi.fn();
const user = userEvent.setup();
const { container } = render(Composer, { props: { onSend, onQueue, status: "running" } });
const textarea = screen.getByRole("textbox", { name: "Message input" });
await user.type(textarea, "steer here");
// Also stage an image — it must NOT be forwarded on a queue.
const file = new File(["PNG"], "shot.png", { type: "image/png" });
const input = container.querySelector('input[type="file"]') as HTMLInputElement;
Object.defineProperty(input, "files", { value: [file], writable: false });
input.dispatchEvent(new Event("change", { bubbles: true }));
await vi.waitFor(() => {
expect(screen.getByRole("button", { name: "Remove image" })).toBeInTheDocument();
});
await user.click(screen.getByRole("button", { name: "Queue" }));
expect(onQueue).toHaveBeenCalledWith("steer here");
expect(onSend).not.toHaveBeenCalled();
});
});
describe("Composer image compression", () => {
/** Stage a PNG through the file picker and wait for the thumbnail. */
async function stagePng(container: HTMLElement, content = "PNGDATA"): Promise<void> {
const file = new File([content], "shot.png", { type: "image/png" });
const input = container.querySelector('input[type="file"]') as HTMLInputElement;
Object.defineProperty(input, "files", { value: [file], writable: false });
input.dispatchEvent(new Event("change", { bubbles: true }));
await vi.waitFor(() => {
expect(screen.getByRole("button", { name: "Remove image" })).toBeInTheDocument();
});
}
/** A fake converted JPEG (the outermost-edge stub — no canvas involved). */
function fakeJpeg(): ConvertedJpeg {
return { blob: new Blob(["SMALLJPEG"], { type: "image/jpeg" }), mimeType: "image/jpeg" };
}
it("shows the compress toggle CHECKED by default for a staged PNG", async () => {
const { container } = render(Composer, {
props: { onSend: vi.fn(), encodeJpeg: vi.fn(async () => null) },
});
await stagePng(container);
const toggle = screen.getByRole("checkbox", { name: "Compress image" });
expect(toggle).toBeChecked();
});
it("hides the compress toggle for already-lossy formats (JPEG)", async () => {
const { container } = render(Composer, {
props: { onSend: vi.fn(), encodeJpeg: vi.fn(async () => null) },
});
const file = new File(["JPG"], "photo.jpg", { type: "image/jpeg" });
const input = container.querySelector('input[type="file"]') as HTMLInputElement;
Object.defineProperty(input, "files", { value: [file], writable: false });
input.dispatchEvent(new Event("change", { bubbles: true }));
await vi.waitFor(() => {
expect(screen.getByRole("button", { name: "Remove image" })).toBeInTheDocument();
});
expect(screen.queryByRole("checkbox", { name: "Compress image" })).not.toBeInTheDocument();
});
it("sends the converted JPEG (image/jpeg) when compress is on, encoding exactly once", async () => {
const encodeJpeg = vi.fn(async () => fakeJpeg());
const onSend = vi.fn();
const user = userEvent.setup();
const { container } = render(Composer, { props: { onSend, encodeJpeg } });
await stagePng(container);
// The async conversion lands and the staged URL reflects what will be sent.
await vi.waitFor(() => {
expect(encodeJpeg).toHaveBeenCalledTimes(1);
});
await vi.waitFor(() => {
const thumb = container.querySelector("img[alt='image/jpeg']");
expect(thumb).not.toBeNull();
expect(thumb?.getAttribute("src")).toMatch(/^data:image\/jpeg;base64,/);
});
await user.click(screen.getByRole("button", { name: "Send" }));
expect(onSend).toHaveBeenCalledTimes(1);
const [, images] = onSend.mock.calls[0] ?? [];
expect(images).toHaveLength(1);
expect(images[0]?.mimeType).toBe("image/jpeg");
expect(images[0]?.url).toMatch(/^data:image\/jpeg;base64,/);
});
it("sends the ORIGINAL untouched bytes when the toggle is unchecked", async () => {
const encodeJpeg = vi.fn(async () => fakeJpeg());
const onSend = vi.fn();
const user = userEvent.setup();
const { container } = render(Composer, { props: { onSend, encodeJpeg } });
await stagePng(container);
await vi.waitFor(() => expect(encodeJpeg).toHaveBeenCalledTimes(1));
await user.click(screen.getByRole("checkbox", { name: "Compress image" }));
expect(screen.getByRole("checkbox", { name: "Compress image" })).not.toBeChecked();
await user.click(screen.getByRole("button", { name: "Send" }));
expect(onSend).toHaveBeenCalledTimes(1);
const [, images] = onSend.mock.calls[0] ?? [];
expect(images[0]?.mimeType).toBe("image/png");
expect(images[0]?.url).toMatch(/^data:image\/png;base64,/);
});
it("re-checking uses the CACHED conversion — no second encode", async () => {
const encodeJpeg = vi.fn(async () => fakeJpeg());
const onSend = vi.fn();
const user = userEvent.setup();
const { container } = render(Composer, { props: { onSend, encodeJpeg } });
await stagePng(container);
await vi.waitFor(() => expect(encodeJpeg).toHaveBeenCalledTimes(1));
const toggle = screen.getByRole("checkbox", { name: "Compress image" });
await user.click(toggle); // OFF → original
await user.click(toggle); // ON again → must reuse the cached JPEG
await user.click(screen.getByRole("button", { name: "Send" }));
expect(encodeJpeg).toHaveBeenCalledTimes(1); // still exactly one encode
const [, images] = onSend.mock.calls[0] ?? [];
expect(images[0]?.mimeType).toBe("image/jpeg");
expect(images[0]?.url).toMatch(/^data:image\/jpeg;base64,/);
});
it("falls back to the original image when conversion fails", async () => {
const encodeJpeg = vi.fn(async () => {
throw new Error("decode exploded");
});
const onSend = vi.fn();
const user = userEvent.setup();
const { container } = render(Composer, { props: { onSend, encodeJpeg } });
await stagePng(container);
await vi.waitFor(() => expect(encodeJpeg).toHaveBeenCalledTimes(1));
await user.click(screen.getByRole("button", { name: "Send" }));
const [, images] = onSend.mock.calls[0] ?? [];
expect(images[0]?.mimeType).toBe("image/png");
expect(images[0]?.url).toMatch(/^data:image\/png;base64,/);
});
});
describe("ModelSelector", () => {
const optionValues = (el: HTMLElement): string[] =>
within(el)
.getAllByRole("option")
.map((o) => (o as HTMLOptionElement).value);
it("renders a key selector (distinct keys) and a model selector (models for the current key)", () => {
const models = ["openai/gpt-4", "openai/gpt-4o", "anthropic/claude-3", "google/gemini"];
render(ModelSelector, {
props: { models, selected: "anthropic/claude-3", onSelect: vi.fn() },
});
const keySelect = screen.getByRole("combobox", { name: "Key selector" });
const modelSelect = screen.getByRole("combobox", { name: "Model selector" });
expect(keySelect).toHaveValue("anthropic");
expect(modelSelect).toHaveValue("claude-3");
// The synthetic "Named Agents" provider is ALWAYS first (plan §6), even with
// zero configured agents.
expect(optionValues(keySelect)).toEqual(["__named_agents__", "openai", "anthropic", "google"]);
// only the models under the selected key
expect(optionValues(modelSelect)).toEqual(["claude-3"]);
});
it("selecting a key switches to the first model under it", async () => {
const onSelect = vi.fn();
const user = userEvent.setup();
const models = ["openai/gpt-4", "openai/gpt-4o", "anthropic/claude-3"];
render(ModelSelector, {
props: { models, selected: "openai/gpt-4o", onSelect },
});
await user.selectOptions(screen.getByRole("combobox", { name: "Key selector" }), "anthropic");
expect(onSelect).toHaveBeenCalledTimes(1);
expect(onSelect).toHaveBeenCalledWith("anthropic/claude-3");
});
it("selecting a model keeps the current key", async () => {
const onSelect = vi.fn();
const user = userEvent.setup();
const models = ["openai/gpt-4", "openai/gpt-4o"];
render(ModelSelector, {
props: { models, selected: "openai/gpt-4", onSelect },
});
await user.selectOptions(screen.getByRole("combobox", { name: "Model selector" }), "gpt-4o");
expect(onSelect).toHaveBeenCalledTimes(1);
expect(onSelect).toHaveBeenCalledWith("openai/gpt-4o");
});
it("lists Named Agents under the synthetic provider and resolves a selection to a snapshot", async () => {
const onSelectNamedAgent = vi.fn();
const user = userEvent.setup();
const models = ["openai/gpt-4"];
const namedAgents = [
{ id: "a1", name: "Coding Agent", model: "opencode-1/claude-sonnet-4.5" },
{ id: "a2", name: "Research Agent", model: "umans/umans-glm-5.2" },
];
const { rerender } = render(ModelSelector, {
props: {
models,
selected: "openai/gpt-4",
onSelect: vi.fn(),
namedAgents,
onSelectNamedAgent,
},
});
// Switching the provider to "Named Agents" jumps to the first agent (mirrors
// a raw provider jumping to its first model).
await user.selectOptions(
screen.getByRole("combobox", { name: "Key selector" }),
"__named_agents__",
);
expect(onSelectNamedAgent).toHaveBeenCalledWith({
namedAgentId: "a1",
namedAgentName: "Coding Agent",
model: "opencode-1/claude-sonnet-4.5",
});
// The parent (store) applies the selection → re-render with the resolved raw
// model + snapshot, exactly as `selectModel(model, snapshot)` would do.
const codingAgent = namedAgents[0];
await rerender({
models,
selected: codingAgent?.model ?? "",
onSelect: vi.fn(),
namedAgents,
namedAgentSnapshot: {
namedAgentId: "a1",
namedAgentName: "Coding Agent",
model: "opencode-1/claude-sonnet-4.5",
},
onSelectNamedAgent,
});
// The model dropdown now lists the named agents; pick a different one.
await user.selectOptions(
screen.getByRole("combobox", { name: "Model selector" }),
"Research Agent",
);
expect(onSelectNamedAgent).toHaveBeenLastCalledWith({
namedAgentId: "a2",
namedAgentName: "Research Agent",
model: "umans/umans-glm-5.2",
});
});
it("shows a disabled placeholder when the synthetic provider has no configured agents", () => {
render(ModelSelector, {
props: { models: ["openai/gpt-4"], selected: "openai/gpt-4", onSelect: vi.fn() },
});
const modelSelect = screen.getByRole("combobox", { name: "Model selector" });
const options = within(modelSelect).getAllByRole("option");
// With the raw openai provider selected the model dropdown lists gpt-4; the
// "No named agents configured" placeholder appears only under the synthetic
// provider (which we'd select to see it). Assert the disabled/empty handling
// by checking the synthetic provider is present in the key selector.
const keySelect = screen.getByRole("combobox", { name: "Key selector" });
expect(optionValues(keySelect)).toContain("__named_agents__");
// Switch to the (empty) synthetic provider → disabled "No named agents configured".
expect(() => screen.getByRole("option", { name: /No named agents configured/ })).toThrow();
expect(options).toHaveLength(1);
});
it("keeps showing a snapshot of a renamed/removed Named Agent (unavailable)", () => {
// A conversation selected via a Named Agent retains its snapshot even after
// the agent is gone from the current list (plan §7).
const namedAgentSnapshot = {
namedAgentId: "gone",
namedAgentName: "Old Agent",
model: "opencode-1/claude-sonnet-4.5",
};
render(ModelSelector, {
props: {
models: [],
selected: "opencode-1/claude-sonnet-4.5",
onSelect: vi.fn(),
namedAgents: [],
namedAgentSnapshot,
},
});
const keySelect = screen.getByRole("combobox", { name: "Key selector" });
expect(keySelect).toHaveValue("__named_agents__");
const modelSelect = screen.getByRole("combobox", { name: "Model selector" });
expect(modelSelect).toHaveValue("Old Agent");
expect(screen.getByRole("option", { name: /Old Agent.*unavailable/ })).toBeInTheDocument();
});
it("selecting a raw model from a Named Agent conversation clears the snapshot via onSelect", async () => {
const onSelect = vi.fn();
const onSelectNamedAgent = vi.fn();
const user = userEvent.setup();
const namedAgentSnapshot = {
namedAgentId: "a1",
namedAgentName: "Coding Agent",
model: "opencode-1/claude-sonnet-4.5",
};
render(ModelSelector, {
props: {
models: ["openai/gpt-4"],
selected: "opencode-1/claude-sonnet-4.5",
onSelect,
namedAgents: [{ id: "a1", name: "Coding Agent", model: "opencode-1/claude-sonnet-4.5" }],
namedAgentSnapshot,
onSelectNamedAgent,
},
});
// Switch from Named Agents to a raw provider → raw model selection clears the snapshot.
await user.selectOptions(screen.getByRole("combobox", { name: "Key selector" }), "openai");
expect(onSelect).toHaveBeenCalledWith("openai/gpt-4");
expect(onSelectNamedAgent).not.toHaveBeenCalled();
});
it("marks vision-capable models in the model dropdown", () => {
const models = ["kimi/k2", "kimi/k1.5"];
const modelInfo = {
"kimi/k2": { vision: true },
"kimi/k1.5": { vision: false },
};
render(ModelSelector, {
props: { models, selected: "kimi/k2", onSelect: vi.fn(), modelInfo },
});
const modelSelect = screen.getByRole("combobox", { name: "Model selector" });
const options = within(modelSelect).getAllByRole("option");
expect(options).toHaveLength(2);
expect(options[0]?.textContent).toContain("vision");
expect(options[1]?.textContent).not.toContain("vision");
});
it("shows the vision indicator when the selected model is vision-capable", () => {
render(ModelSelector, {
props: {
models: ["kimi/k2"],
selected: "kimi/k2",
onSelect: vi.fn(),
modelInfo: { "kimi/k2": { vision: true } },
},
});
expect(screen.getByText(/sees images natively/)).toBeInTheDocument();
});
it("shows the vision-handoff hint when the selected model is non-vision", () => {
render(ModelSelector, {
props: {
models: ["umans/glm-5.2"],
selected: "umans/glm-5.2",
onSelect: vi.fn(),
modelInfo: { "umans/glm-5.2": { vision: false } },
},
});
expect(screen.getByText(/auto-described/i)).toBeInTheDocument();
expect(screen.queryByText(/sees images natively/)).not.toBeInTheDocument();
});
it("shows the handoff hint when modelInfo is absent", () => {
render(ModelSelector, {
props: { models: ["openai/gpt-4"], selected: "openai/gpt-4", onSelect: vi.fn() },
});
expect(screen.getByText(/auto-described/i)).toBeInTheDocument();
});
it("labels numbered OpenCode keys as OpenCode #N and sorts them numerically", () => {
const models = ["opencode-10/m1", "opencode-2/m2", "opencode-1/m3"];
const onSelect = vi.fn();
render(ModelSelector, {
props: { models, selected: "opencode-2/m2", onSelect },
});
const keySelect = screen.getByRole("combobox", { name: "Key selector" });
const options = within(keySelect).getAllByRole("option");
// Numeric order: #1 < #2 < #10 (after the always-first synthetic provider),
// and values stay RAW (opencode-N).
expect(options.map((o) => (o as HTMLOptionElement).value)).toEqual([
"__named_agents__",
"opencode-1",
"opencode-2",
"opencode-10",
]);
expect(options[1]?.textContent).toContain("OpenCode #1");
expect(options[2]?.textContent).toContain("OpenCode #2");
expect(options[3]?.textContent).toContain("OpenCode #10");
});
it("shows a disappeared saved credential as unavailable without silently falling back", () => {
// Saved selection references opencode-5, but the catalog no longer has it.
const models = ["opencode-1/deepseek-v4-flash"];
const onSelect = vi.fn();
render(ModelSelector, {
props: { models, selected: "opencode-5/deepseek-v4-flash", onSelect },
});
// The unavailable key is surfaced as an explicit (disabled) option + notice.
const keySelect = screen.getByRole("combobox", { name: "Key selector" });
const unavailable = within(keySelect).getByText(/OpenCode #5 \(unavailable\)/i);
expect(unavailable).toBeInTheDocument();
expect(screen.getByText(/Selected model .* unavailable/)).toBeInTheDocument();
// No silent switch is attempted.
expect(onSelect).not.toHaveBeenCalled();
});
});
describe("ReasoningEffortSelector", () => {
it("renders null effort + null thinking (never set) as the default level, marked '(default)'", () => {
render(ReasoningEffortSelector, {
props: { persistedEffort: null, persistedThinking: null, save: vi.fn() },
});
const select = screen.getByRole("combobox", { name: "Reasoning effort" });
expect(select).toHaveValue("high");
expect(within(select).getByRole("option", { name: "high (default)" })).toBeInTheDocument();
// "Off" first, then the five ladder levels.
const options = within(select).getAllByRole("option");
expect(options).toHaveLength(6);
expect(options[0]).toHaveValue("off");
expect(within(select).getByRole("option", { name: "Off" })).toBeInTheDocument();
});
it("renders a persisted level as selected when thinking is on", () => {
render(ReasoningEffortSelector, {
props: { persistedEffort: "xhigh", persistedThinking: null, save: vi.fn() },
});
expect(screen.getByRole("combobox", { name: "Reasoning effort" })).toHaveValue("xhigh");
});
it("renders 'off' as selected when thinking is disabled (effort level is preserved but hidden)", () => {
// thinking off is a SEPARATE axis: even with a persisted effort level, the
// selector shows "off" while thinking is disabled.
render(ReasoningEffortSelector, {
props: { persistedEffort: "xhigh", persistedThinking: false, save: vi.fn() },
});
expect(screen.getByRole("combobox", { name: "Reasoning effort" })).toHaveValue("off");
// the level option is still present (restored on an off→on toggle)
expect(
within(screen.getByRole("combobox")).getByRole("option", { name: "xhigh" }),
).toBeInTheDocument();
});
it("selecting a level saves it via the injected port and confirms", async () => {
const save = vi.fn(async (selection: "off" | "low" | "medium" | "high" | "xhigh" | "max") => ({
ok: true as const,
selection,
}));
const user = userEvent.setup();
render(ReasoningEffortSelector, {
props: { persistedEffort: null, persistedThinking: null, save },
});
await user.selectOptions(screen.getByRole("combobox", { name: "Reasoning effort" }), "max");
expect(save).toHaveBeenCalledTimes(1);
expect(save).toHaveBeenCalledWith("max");
await vi.waitFor(() => {
expect(screen.getByText(/applies from the next turn/i)).toBeInTheDocument();
});
expect(screen.getByRole("combobox", { name: "Reasoning effort" })).toHaveValue("max");
});
it("selecting 'off' saves the separate disable signal (not a level)", async () => {
const save = vi.fn(async (selection: "off" | "low" | "medium" | "high" | "xhigh" | "max") => ({
ok: true as const,
selection,
}));
const user = userEvent.setup();
render(ReasoningEffortSelector, {
props: { persistedEffort: "high", persistedThinking: null, save },
});
await user.selectOptions(screen.getByRole("combobox", { name: "Reasoning effort" }), "off");
expect(save).toHaveBeenCalledTimes(1);
// "off" is the separate thinking-disable signal — NOT a zero-effort level.
expect(save).toHaveBeenCalledWith("off");
await vi.waitFor(() => {
expect(screen.getByText(/applies from the next turn/i)).toBeInTheDocument();
});
expect(screen.getByRole("combobox", { name: "Reasoning effort" })).toHaveValue("off");
});
it("a failed save shows the error and reverts to the persisted selection", async () => {
const save = vi.fn(async () => ({ ok: false as const, error: "nope" }));
const user = userEvent.setup();
render(ReasoningEffortSelector, {
props: { persistedEffort: "low", persistedThinking: null, save },
});
await user.selectOptions(screen.getByRole("combobox", { name: "Reasoning effort" }), "max");
await vi.waitFor(() => {
expect(screen.getByText("nope")).toBeInTheDocument();
});
expect(screen.getByRole("combobox", { name: "Reasoning effort" })).toHaveValue("low");
});
it("disables the select while a save is in flight (no double-fire)", async () => {
let resolveSave: ((r: { ok: true; selection: "max" }) => void) | undefined;
const save = vi.fn(
() =>
new Promise<{ ok: true; selection: "max" }>((resolve) => {
resolveSave = resolve;
}),
);
const user = userEvent.setup();
render(ReasoningEffortSelector, {
props: { persistedEffort: null, persistedThinking: null, save },
});
await user.selectOptions(screen.getByRole("combobox", { name: "Reasoning effort" }), "max");
expect(screen.getByRole("combobox", { name: "Reasoning effort" })).toBeDisabled();
resolveSave?.({ ok: true, selection: "max" });
await vi.waitFor(() => {
expect(screen.getByRole("combobox", { name: "Reasoning effort" })).toBeEnabled();
});
});
});
|