File size: 75,482 Bytes
ce9586e
4cfab62
c1fc133
4cfab62
89af3b2
 
816fa8a
ce9586e
816fa8a
 
4cfab62
816fa8a
 
4cfab62
dec006b
 
816fa8a
1d4419b
 
ce9586e
89af3b2
 
 
 
 
 
 
816fa8a
 
 
 
 
 
 
4cfab62
19b91ce
816fa8a
 
dec006b
4cfab62
ce9586e
4cfab62
816fa8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfab62
 
c1fc133
816fa8a
c1fc133
 
 
 
 
 
 
 
 
 
816fa8a
 
 
 
 
c1fc133
 
816fa8a
 
 
 
 
 
89af3b2
 
 
 
 
 
 
 
 
 
ce9586e
 
 
 
 
 
 
 
 
 
816fa8a
 
89af3b2
 
ce9586e
dec006b
 
 
 
 
 
 
 
 
ce9586e
 
89af3b2
ce9586e
dec006b
89af3b2
816fa8a
ce9586e
816fa8a
 
 
 
ce9586e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89af3b2
 
 
 
 
 
 
ce9586e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
 
ce9586e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
 
 
ce9586e
816fa8a
ce9586e
 
 
 
 
 
89af3b2
ce9586e
 
dec006b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cbc29f
 
dec006b
 
 
 
ce9586e
 
 
 
 
 
dec006b
ce9586e
dec006b
ce9586e
 
dec006b
 
89af3b2
816fa8a
ce9586e
 
 
 
c1fc133
 
 
 
 
 
 
 
 
 
 
 
 
ce9586e
4cfab62
ce9586e
4cfab62
 
816fa8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfab62
ce9586e
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19b91ce
 
 
 
 
 
 
ce9586e
 
19b91ce
ce9586e
4cfab62
 
19b91ce
ce9586e
 
4cfab62
816fa8a
 
 
 
 
4cfab62
 
 
19b91ce
 
 
1d4419b
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
89af3b2
 
 
 
 
 
c1fc133
 
816fa8a
ce9586e
89af3b2
 
ce9586e
c1fc133
 
e174d2c
 
4cfab62
 
 
816fa8a
ce9586e
89af3b2
 
ce9586e
19b91ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
19b91ce
 
 
 
 
1d4419b
 
19b91ce
 
 
 
 
 
 
 
 
 
816fa8a
19b91ce
 
 
 
 
 
 
4cfab62
 
 
 
 
 
 
816fa8a
4cfab62
 
 
 
ce9586e
4cfab62
 
816fa8a
 
 
 
 
 
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
4cfab62
 
 
 
 
 
 
 
 
 
816fa8a
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
ce9586e
4cfab62
89af3b2
4cfab62
ce9586e
 
 
 
 
 
 
4cfab62
 
 
89af3b2
 
4cfab62
 
19b91ce
 
 
 
c1fc133
 
19b91ce
 
c1fc133
 
 
 
 
 
89af3b2
 
c1fc133
 
 
 
 
 
 
4cfab62
ce9586e
 
 
 
 
89af3b2
ce9586e
 
4cfab62
 
 
 
 
74f72af
 
 
 
 
 
4cfab62
 
 
 
 
 
816fa8a
4cfab62
 
ce9586e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89af3b2
ce9586e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89af3b2
 
 
 
ce9586e
 
 
 
 
 
 
 
 
 
 
 
 
89af3b2
ce9586e
 
 
 
 
 
89af3b2
 
 
 
 
ce9586e
 
 
 
4cfab62
 
816fa8a
 
4cfab62
 
74f72af
4cfab62
74f72af
 
19b91ce
74f72af
19b91ce
 
 
74f72af
4cfab62
c1fc133
 
ce9586e
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1fc133
 
 
 
ce9586e
816fa8a
 
89af3b2
 
 
 
 
 
 
 
 
 
c1fc133
89af3b2
 
c1fc133
 
 
4cfab62
89af3b2
 
ce9586e
 
89af3b2
816fa8a
ce9586e
89af3b2
 
 
 
 
 
 
 
 
 
816fa8a
 
 
 
 
 
 
 
 
89af3b2
 
 
 
 
 
19b91ce
ce9586e
89af3b2
ce9586e
89af3b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
89af3b2
816fa8a
 
 
 
 
89af3b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
 
89af3b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
89af3b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
89af3b2
 
 
 
816fa8a
89af3b2
 
 
 
 
816fa8a
89af3b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1fc133
816fa8a
89af3b2
 
 
 
 
ce9586e
89af3b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
89af3b2
 
816fa8a
c1fc133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
ce9586e
 
4cfab62
 
 
ce9586e
 
 
4cfab62
ce9586e
89af3b2
4cfab62
 
c1fc133
 
 
 
 
 
 
19b91ce
c1fc133
 
 
 
19b91ce
 
c1fc133
 
 
 
 
 
 
 
19b91ce
c1fc133
 
 
 
 
 
 
 
19b91ce
4cfab62
 
c1fc133
4cfab62
 
 
816fa8a
4cfab62
 
 
 
 
 
 
816fa8a
89af3b2
816fa8a
 
89af3b2
 
816fa8a
4cfab62
816fa8a
4cfab62
 
 
 
 
 
74f72af
 
 
 
4cfab62
74f72af
 
4cfab62
 
 
 
 
 
 
 
816fa8a
4cfab62
 
ce9586e
 
 
816fa8a
ce9586e
 
 
 
89af3b2
 
816fa8a
89af3b2
816fa8a
ce9586e
 
 
 
 
 
 
 
 
 
 
 
89af3b2
ce9586e
 
 
 
 
 
 
 
 
4cfab62
ce9586e
4cfab62
ce9586e
4cfab62
89af3b2
4cfab62
816fa8a
4cfab62
 
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
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";

import { API_V1, CREDENTIALS, checkTenant, QUERY_OPEN_EVENT, signal, UNAUTHORIZED_EVENT } from "../apiContract";
import { queryCitationLabel } from "../customer-grid/queryPreview";
import { retryEmit } from "../shell/targetRoute";
import type { NotificationTarget } from "../alerts/alertsModel";
import { dataAddressHash, databaseEntries, fetchNav, QUERY_ROUTE, routeKeyOf, shapeNav, splitChrome } from "../shell/nav";
import { sheetAddressHash } from "../sheet";
import type { NavEntry, NavResult } from "../shell/nav";
import { persistQueryArtifacts, runQueryTool, type QueryToolArtifacts } from "../automation/automationApi";
import {
  answerSourceFooter, call as queryRequest, fetchArtifacts, fetchQueries, rateMessage, refusalSentence, type ArtifactIndex,
  type Result, type QueryCitation, type QueryIndex, type QueryMessage, type SavedQuery,
} from "../query/queryApi";
import { artifactFileHref, worklistText } from "../artifacts/worklistApi";
import { worklistFigure } from "../artifacts/WorklistTable";
import SnapshotTable from "../artifacts/SnapshotTable";
// W51-T31 — the ONE Escape arbiter (C8). See the registration in `AssistantMessage`.
import { useEscapeClose } from "../ui/useEscapeClose";
import { PingCard } from "./PingCard";
import { NoticeCard } from "./NoticeCard";
import { TypingIndicator } from "./TypingIndicator";
import { canFallback, ChatStreamFailure, streamChat, streamDelta } from "./streamClient";
import { stopTurn, submitChat } from "./turnClient";
import { SuggestionChips } from "./SuggestionChips";
import { takePendingAsk } from "./askPending";
import { MemoryPanel } from "./MemoryPanel";
import { ModuleHomeHead } from "../home/ModuleHomeHead";
import {
  addressFromHash, interceptOpen, LinkedText, LOAD_FAILED, NOT_AVAILABLE, OpenInPlaceContext, OpenInPlaceHost,
  useOpenInPlace,
} from "./OpenInPlace";
import type { InPlaceModules, InPlaceTarget, OpenInPlaceApi } from "./OpenInPlace";
import type { ReactNode } from "react";
import "./assistant.css";
import "../styles/wave45/agent-operator.css";
// The pop-up's stylesheet loads with its host, never from OpenInPlace.tsx (see the note there).
import "../styles/sdlc72/open-in-place.css";
import "../styles/sdlc74/assistant.css";

const useConversationLayoutEffect = typeof window === "undefined" ? useEffect : useLayoutEffect;

// S72-T12: the dock reaches these through `AssistantPanel.tsx::loadRenderers`, never a static import.
export { SuggestionChips, TypingIndicator };

// One `/nav` read per page session, on the first dock link outside the dock's own databases.
// A failed read clears the cache, so the next click retries.
let dockGrant: Promise<NavEntry[]> | undefined;
export function loadDockGrant(read: () => Promise<NavResult> = fetchNav): Promise<NavEntry[]> {
  return dockGrant ||= read().then((result) => {
    if (!result.ok) throw new Error("The database list could not be read.");
    return shapeNav(splitChrome(result.pages).main, "");
  }).catch((error: unknown) => { dockGrant = undefined; throw error; });
}

function DockGrantLoading() {
  return <div className="oip-loading"><span className="lp-spin lp-spin--lg" role="status" aria-label="Loading" /></div>;
}
function DockGrantFailed() {
  return <p className="oip-sentence" role="status">{LOAD_FAILED}</p>;
}

// The Data dock holds the grid scope, and a link carries the nav key. This inverts `shell/dbFrame.tsx::gridScopeFor`.
const NAV_KEY_OF_SCOPE: Record<string, string> = { customer: "customer_data", product: "product_data" };

/** The dock's link host. Its own databases and workbooks open at once. Any other link reads the grant once, then opens. */
export function DockOpenInPlace({ sources, children, modules, readGrant = loadDockGrant }: {
  sources: NavEntry[]; children?: ReactNode; modules?: InPlaceModules; readGrant?: () => Promise<NavEntry[]>;
}) {
  const [grant, setGrant] = useState<NavEntry[] | null>(null);
  const [waiting, setWaiting] = useState<{ target: InPlaceTarget; failed: boolean } | null>(null);
  const own = sources.map((entry) => ({ ...entry, key: NAV_KEY_OF_SCOPE[entry.key] || entry.key }));
  // A known target clears any wait, so a stale loader or failure never covers it.
  const foreign = useCallback((target: InPlaceTarget | null) => {
    if (!target) { setWaiting(null); return; }
    setWaiting({ target, failed: false });
    readGrant().then((list) => { setGrant(list); setWaiting(null); },
      () => setWaiting((current) => current && current.target === target ? { target, failed: true } : current));
  }, [readGrant]);
  let granted = grant ? [...grant, ...own.filter((entry) => !grant.some((row) => row.key === entry.key))] : own;
  let hostModules: InPlaceModules = { artifact: ArtifactItemView, ...modules };
  if (waiting) {
    // Until the grant arrives the pop-up shows the loader, or one sentence if the read failed.
    const body = waiting.failed ? DockGrantFailed : DockGrantLoading;
    hostModules = { ...hostModules, data: body, query: body };
    if (waiting.target.kind === "data") granted = [...own, { key: waiting.target.database, label: "", kind: "native", depth: 0 }];
  }
  return <OpenInPlaceHost granted={granted} modules={hostModules}>
    <DockLinkScope own={own} ready={grant !== null} onForeign={foreign}>{children}</DockLinkScope>
  </OpenInPlaceHost>;
}

function DockLinkScope({ own, ready, onForeign, children }: {
  own: NavEntry[]; ready: boolean; onForeign: (target: InPlaceTarget | null) => void; children?: ReactNode;
}) {
  const host = useOpenInPlace();
  const api = useMemo<OpenInPlaceApi | null>(() => host && { open: (href: string) => {
    const target = addressFromHash(href);
    if (!target) return false;
    // A workbook and an artifact record read no grant. The record list is the caller's own.
    const known = target.kind === "sheet" || target.kind === "artifact"
      || (target.kind === "data" && own.some((entry) => entry.key === target.database));
    if (known || ready) onForeign(null);
    else onForeign(target);
    return host.open(href);
  } }, [host, own, ready, onForeign]);
  return <OpenInPlaceContext.Provider value={api}>{children}</OpenInPlaceContext.Provider>;
}

export interface AssistantPageProps { granted: NavEntry[]; }

/** Routing rides on /query/tool. Its shared result union belongs to another lane, so keep
 * the routing and refusal extension local and read it through the single cast in ask(). */
type RoutedTo = { database: string; label: string; reason: string; auto: boolean;
  alternatives: Array<{ database: string; label: string }> };
// W61-T30: the drafting extension stays local while the shared API union belongs to another lane.
type SemanticDraft = {
  database: string; label: string; canApprove: boolean; sentToAdmins: boolean;
  state: "pending" | "approved"; requestedBy: string;
  approvedBy?: string | null; approvedAt?: string | null; approvalLine?: string; sentMessage: string;
  fields: Array<{ field: string; label: string; why: string; role: string; dataType: string;
    sensitivity: string; sample: { redacted: boolean; values: string[]; sample: string[] } }>;
};
type AssistantChatContinuation = {
  status: "continue_chat"; routedTo: RoutedTo & { database: ""; auto: false };
};
type RoutedQueryResult = (Awaited<ReturnType<typeof runQueryTool>> | AssistantChatContinuation | {
  status: "refused"; wording: string; speakable: string; artifacts: null; code?: string;
}) & { routedTo?: RoutedTo; draft?: SemanticDraft };

/** C2: the server's code on a thrown request, read without importing the error class. */
function failureCode(error: unknown): string | undefined {
  const code = (error as { code?: unknown } | null)?.code;
  return typeof code === "string" ? code : undefined;
}

type ChatRouting = { governed: RoutedQueryResult; database: string; routed?: RoutedTo };
type ChatBatch = {
  requests: Map<string, { controller: AbortController; answerId: string; text: string }>;
  joined: Set<string>;
  restored: Set<string>;
  routingReady: boolean;
  ready: Promise<ChatRouting | null>;
  resolve: (routing: ChatRouting | null) => void;
};

type PendingDelete = { id: string; summary: string; expiresAt: string | number };
type ToolCall = {
  name: string; args: Record<string, unknown>; effect: "read" | "write" | "delete";
  ok: boolean; ref: string | null;
};
type AgentTurnResult = {
  reply: string; toolCalls: ToolCall[]; pendingDelete: PendingDelete | null;
  artifacts: string[]; refused: string | null;
};
type AssistantChatMessage = QueryMessage & {
  // S72-T16: an id, or a C7 record when the turn carries the record itself.
  toolCalls?: ToolCall[]; pendingDelete?: PendingDelete | null; artifacts?: Array<string | Record<string, unknown>>;
  pendingResolved?: string;
  streaming?: boolean; toolStep?: string;
};
type ScheduledField = { key: string; label: string; type: string; currency?: string | null };
export type ScheduledResultEnvelope = {
  version: number; kind: "scheduled_result" | "reminder"; id: string; scheduleId: string;
  words: string; request: Record<string, unknown>; runAt: string; ok: boolean; message?: string;
  sourceSyncedAt?: string | null; rowCount?: number; fields?: ScheduledField[];
  totals?: Array<{ fn: string; field?: string; value: unknown }>;
  table?: { header: ScheduledField[]; rows: unknown[][]; total: number; unit: "rows" | "groups" };
  dataLink?: string;
};
export type AssistantLogTurn = {
  id: string; seq?: number; role: "user" | "assistant" | "system";
  door: "app" | "whatsapp" | "wake"; kind: "text" | "ping" | "notice" | "confirm" | "divider";
  text: string; at: string;
  payload?: Partial<AssistantChatMessage> & Partial<Omit<PingPayload, "reason">> & Partial<ScheduledResultEnvelope> & {
    title?: string; body?: string; link?: string | null; source?: string;
    subject?: string; target?: NotificationTarget | null;
    governedArtifacts?: QueryToolArtifacts;
    // A feed notice names its sender as a string. A C6 inbox notice sends an object.
    sender?: string | { username?: string; name?: string };
    // C6 inbox fields. `NoticeCard.readInboxNotice` guards each one.
    type?: string; request_id?: string; text?: string; actions?: string[]; state?: string;
  };
};
/** C22: what a `kind: "ping"` turn carries. `PingCard` reads nothing else. */
export type PingPayload = {
  ticketId: string; checkId: string; title: string; reason: string; action: string; recordLink: string;
  amount?: number; daysOverdue?: number; assignedBy: string[];
  digest?: Array<string | { ticketId?: string; id?: string; title?: string; recordLink?: string }>;
};
type ConversationPage = { turns: AssistantLogTurn[]; hasMore: boolean };

// Reuse Query's transport so cookies and server error sentences follow the same path.
function fetchConversation(before?: string): Promise<Result<ConversationPage>> {
  const query = new URLSearchParams({ limit: "50" });
  if (before) query.set("before", before);
  return queryRequest(`/assistant/log?${query.toString()}`, {}, (body: unknown) => body as ConversationPage);
}

function answerDelete(id: string, decision: "delete" | "keep"): Promise<Result<AgentTurnResult | { kept: boolean }>> {
  return queryRequest("/assistant/confirm", {
    method: "POST", headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ id, decision }),
  }, (body: unknown) => body as AgentTurnResult | { kept: boolean });
}

// The transport's legacy message reader omits agent fields. The log is authoritative for those.
function localTurn(message: AssistantChatMessage): AssistantLogTurn {
  return { id: message.id, role: message.role, door: "app", kind: "text",
    text: message.content, at: message.createdAt, payload: message };
}

function turnMessage(turn: AssistantLogTurn): AssistantChatMessage {
  return { ...turn.payload, id: turn.payload?.id || turn.id,
    role: turn.role === "user" ? "user" : "assistant", content: turn.text,
    createdAt: turn.at } as AssistantChatMessage;
}

function mergeTurns(older: AssistantLogTurn[], newer: AssistantLogTurn[]): AssistantLogTurn[] {
  const keys = new Set(newer.map((turn) => turn.payload?.id || turn.id));
  const knownStops = new Set(older.filter((turn) => turn.text === "Stopped." && !turn.id.startsWith("stopped_"))
    .map((turn) => turn.payload?.id || turn.id));
  const savedStops = newer.filter((turn) => turn.role !== "user" && turn.text === "Stopped."
    && !turn.id.startsWith("stopped_") && !knownStops.has(turn.payload?.id || turn.id)).length;
  const reconciled = new Set(older.filter((turn) => turn.id.startsWith("stopped_")).slice(0, savedStops)
    .map((turn) => turn.id));
  return [...older.filter((turn) => !keys.has(turn.payload?.id || turn.id) && !reconciled.has(turn.id)), ...newer];
}

function DeleteConfirmCard({ pending, resolved, onResolved }: {
  pending: PendingDelete; resolved?: string; onResolved?: (id: string, line: string) => void;
}) {
  const [line, setLine] = useState("");
  const [busy, setBusy] = useState(false);
  const [problem, setProblem] = useState("");
  const inFlight = useRef(false);
  const decide = async (decision: "delete" | "keep") => {
    if (inFlight.current || resolved || line) return;
    inFlight.current = true; setBusy(true); setProblem("");
    try {
      const result = await answerDelete(pending.id, decision);
      if (!result.ok) { setProblem("This choice could not be saved. Try again."); return; }
      let reply: string;
      if (decision === "keep") {
        if (!("kept" in result.value) || !result.value.kept) {
          setProblem("This choice could not be saved. Try again."); return;
        }
        reply = "Kept. Nothing was removed.";
      } else {
        const turn = result.value as AgentTurnResult;
        reply = turn.refused || turn.reply;
        if (!reply) { setProblem("This choice could not be saved. Try again."); return; }
      }
      setLine(reply); onResolved?.(pending.id, reply);
    } catch {
      setProblem("This choice could not be saved. Try again.");
    } finally {
      inFlight.current = false; setBusy(false);
    }
  };
  if (resolved || line) return <p className="as-confirm-result" role="status">{resolved || line}</p>;
  return <section className="as-confirm" aria-label="Confirm deletion">
    <p>{pending.summary}</p>
    <div className="as-confirm-actions">
      <button type="button" className="as-confirm-button as-confirm-delete" disabled={busy}
        onClick={() => void decide("delete")}>Delete</button>
      <button type="button" className="as-confirm-button" disabled={busy}
        onClick={() => void decide("keep")}>Keep</button>
    </div>
    {problem ? <p className="as-problem" role="status">{problem}</p> : null}
  </section>;
}

const WRITE_LABELS: Record<string, string> = {
  sheet_create_workbook: "Created a workbook", sheet_update_workbook: "Updated a workbook",
  sheet_write_cells: "Updated cells", view_upsert: "Saved a view", build_view: "Built a view",
};
export function WriteReport({ calls, onPreview }: { calls?: ToolCall[]; onPreview: (id: string) => void }) {
  const inPlace = useOpenInPlace();
  return <>{calls?.filter((call) => call.effect === "write" && call.ok).map((call, position) => {
    const args = call.args || {};
    const viewArgs = args.view && typeof args.view === "object" ? args.view as Record<string, unknown> : {};
    // The reader recognises what was made by its name; the id is the fallback, never the headline.
    const target = String(args.title || args.name || viewArgs.name || "") || call.ref || "";
    const workbook = call.name.startsWith("sheet_");
    // A saved grid View lives in Data under its database; only a built Query answer opens in Query.
    const gridView = call.name === "view_upsert" && typeof args.database === "string" && Boolean(args.database);
    const built = call.name === "build_view";
    const href = call.ref && (workbook ? sheetAddressHash({ wb: call.ref })
      : gridView ? dataAddressHash({ database: String(args.database), view: call.ref })
      : built ? `#/${QUERY_ROUTE}?view=${encodeURIComponent(call.ref)}` : "");
    return <p className="as-write-report" key={`${call.name}-${position}`}>
      <span title={call.name}>{WRITE_LABELS[call.name] || call.name}</span>
      {target ? <span className="as-write-target">{target}</span> : null}
      {href ? <a href={href} onClick={(event) => {
        // S72-T14: a mounted host opens every Open here in its pop-up. Without one, only a built view is routed.
        if (interceptOpen(inPlace, href, event) || !built) return;
        event.preventDefault(); onPreview(call.ref!);
      }}>Open</a> : null}
    </p>;
  })}</>;
}

export function AssistantGreeting({ loaded, turnCount }: { loaded: boolean; turnCount: number }) {
  if (!loaded || turnCount) return null;
  return <p className="as-opening-p">ask me anything about your data</p>;
}

function scheduledEnvelope(turn: AssistantLogTurn): ScheduledResultEnvelope | null {
  const payload = turn.payload;
  if (turn.role !== "assistant" || turn.kind !== "text" || payload?.kind !== "scheduled_result"
    || !/^sr_[a-f0-9]{32}$/.test(payload.id || "") || typeof payload.words !== "string"
    || typeof payload.ok !== "boolean") return null;
  if (payload.ok && (!payload.table || !Array.isArray(payload.table.header)
    || !Array.isArray(payload.table.rows) || !Array.isArray(payload.totals)
    || typeof payload.rowCount !== "number" || typeof payload.table.total !== "number")) return null;
  return payload as ScheduledResultEnvelope;
}

async function markScheduledRead(id: string): Promise<boolean> {
  const result = await queryRequest(`/schedules/results/${encodeURIComponent(id)}/read`, { method: "POST" },
    (body: unknown) => body as { id: string; read: boolean });
  return result.ok && result.value.read === true && result.value.id === id;
}

/** A visible request acknowledges its result once, including after a hidden tab becomes visible. */
export function observeScheduledResult(element: HTMLElement, id: string,
  acknowledge: (id: string) => Promise<boolean> = markScheduledRead): () => void {
  if (typeof IntersectionObserver === "undefined") return () => {};
  let stopped = false;
  let pending = false;
  let read = false;
  const root = element.closest(".as-stream");
  const visible = () => {
    if (document.visibilityState !== "visible") return false;
    const box = element.getBoundingClientRect();
    const clip = root?.getBoundingClientRect();
    return box.width > 0 && box.height > 0
      && Math.min(box.bottom, clip?.bottom ?? window.innerHeight, window.innerHeight)
        > Math.max(box.top, clip?.top ?? 0, 0)
      && Math.min(box.right, clip?.right ?? window.innerWidth, window.innerWidth)
        > Math.max(box.left, clip?.left ?? 0, 0);
  };
  const mark = () => {
    if (stopped || pending || read || !visible()) return;
    pending = true;
    void acknowledge(id).then((ok) => { read = ok; if (ok) observer.disconnect(); })
      .catch(() => {}).finally(() => { pending = false; });
  };
  const observer = new IntersectionObserver((entries) => {
    if (entries.some((entry) => entry.target === element && entry.isIntersecting)) mark();
  }, { root, threshold: 0 });
  observer.observe(element);
  document.addEventListener("visibilitychange", mark);
  return () => { stopped = true; observer.disconnect(); document.removeEventListener("visibilitychange", mark); };
}

function scheduledFigure(value: unknown, field?: ScheduledField): string {
  const formatted = worklistFigure(value, Boolean(field?.currency));
  return typeof value === "number" && field?.currency ? `${formatted} ${worklistText(field.currency)}` : formatted;
}

export function ScheduledResult({ result }: { result: ScheduledResultEnvelope }) {
  const heading = useRef<HTMLDivElement | null>(null);
  useEffect(() => {
    if (heading.current) return observeScheduledResult(heading.current, result.id);
  }, [result.id]);
  const table = result.table;
  const operations: Record<string, string> = {
    sum: "Total", avg: "Average", min: "Minimum", max: "Maximum", count: "Count", count_distinct: "Distinct",
  };
  const numeric = (field: ScheduledField) => Boolean(field.currency)
    || ["number", "money", "currency", "integer", "float", "decimal", "id"].includes(field.type);
  return <section className="as-scheduled-result" aria-label="Scheduled result" data-result-id={result.id}>
    <div className="as-scheduled-head" ref={heading}>
      <p className="as-door">Scheduled</p>
      <p className="as-message-text">{worklistText(result.words)}</p>
    </div>
    {result.ok && table ? <>
      <p className="as-scheduled-meta">{result.sourceSyncedAt ? <>Last synced{" "}
        <time dateTime={result.sourceSyncedAt}>{new Date(result.sourceSyncedAt).toLocaleString()}</time>
      </> : "Sync time unavailable"}</p>
      <dl className="as-scheduled-totals" aria-label="Scheduled totals">
        <div><dt>Records</dt><dd>{worklistFigure(result.rowCount)}</dd></div>
        {result.totals?.filter((item) => item.fn !== "count" || item.field).map((item, index) => {
          const field = result.fields?.find((field) => field.key === item.field);
          const label = field?.label || item.field || "";
          return <div key={index}>
            <dt>{worklistText(`${operations[item.fn] || item.fn} ${label ? label[0].toLowerCase() + label.slice(1) : ""}`.trim())}</dt>
            <dd>{scheduledFigure(item.value, ["sum", "avg", "min", "max"].includes(item.fn) ? field : undefined)}</dd>
          </div>;
        })}
      </dl>
      <p className="as-scheduled-count">{`${Math.min(20, table.rows.length).toLocaleString()} of ${table.total.toLocaleString()} shown`}
        {table.unit === "groups" ? " (groups)" : null}</p>
      <div className="as-scheduled-scroll" tabIndex={0} role="region" aria-label="Scheduled table">
        <table className="as-scheduled-table" aria-label="Scheduled rows">
          <thead><tr>{table.header.map((field) => <th scope="col" key={field.key}
            className={numeric(field) ? "as-scheduled-number" : undefined}>{worklistText(field.label)}</th>)}</tr></thead>
          <tbody>{table.rows.slice(0, 20).map((row, index) => <tr key={index}>
            {table.header.map((field, column) => <td key={field.key}
              className={numeric(field) ? "as-scheduled-number" : undefined}>{scheduledFigure(row[column], field)}</td>)}
          </tr>)}</tbody>
        </table>
      </div>
      {result.dataLink?.startsWith("#/table?") || result.dataLink?.startsWith("#/data?")
        ? <a className="as-scheduled-link" href={result.dataLink}>Open in Table</a> : null}
    </> : <p className="as-scheduled-meta" role="status">{worklistText(result.message || "The saved query could not run.")}</p>}
  </section>;
}

export function AssistantTurn({ turn, ...props }: {
  turn: AssistantLogTurn;
  fresh?: boolean;
} & Omit<Parameters<typeof AssistantMessage>[0], "message">) {
  if (turn.kind === "divider") return <div className="as-divider">{turn.text}</div>;
  const { fresh, ...messageProps } = props;
  const scheduled = scheduledEnvelope(turn);
  return <div className={`as-turn${fresh ? " is-new" : ""}`}>
    {scheduled ? null : turn.door === "whatsapp" ? <p className="as-door">From WhatsApp</p>
      // A ping card carries its own "Wake-up" label; the door marker would say it twice.
      : turn.door === "wake" && turn.kind !== "ping" ? <p className="as-door">Wake-up</p> : null}
    {scheduled ? <ScheduledResult result={scheduled} />
      : turn.kind === "ping" ? <PingCard turn={turn} />
      : turn.kind === "notice" ? <NoticeCard turn={turn} />
      : turn.role === "system" ? <p className="as-message-text"><LinkedText text={turn.text} /></p>
      : <AssistantMessage message={turnMessage(turn)} {...messageProps} />}
  </div>;
}

async function draftRequest(database: string, fields?: string[], question?: string): Promise<{
  state?: "pending" | "approved"; draft?: SemanticDraft; approvalLine?: string; sentMessage?: string;
}> {
  const response = await fetch(`${API_V1}/query/semantics/${encodeURIComponent(database)}/${fields ? "approve" : "draft"}`, {
    credentials: CREDENTIALS, method: fields ? "POST" : "GET",
    ...(fields ? { headers: { "Content-Type": "application/json" }, body: JSON.stringify({ fields, question }) } : {}),
  });
  if (checkTenant(response)) throw new Error("The workspace changed. Open this chat again.");
  if (response.status === 401) signal(UNAUTHORIZED_EVENT);
  if (!response.ok) throw new Error("The field request could not be completed, so please try again.");
  return response.json();
}

// R13 (moved from S68-T45): Time-series is retired, so it has no label here.
const KIND_LABEL: Record<string, string> = {
  grid: "table", list: "list", chart: "chart", kanban: "board", calendar: "calendar", map: "map",
};

/** S72-T16 (C7, R98): the made-file kinds an answer shows as a chip. Any other kind keeps today's answer. */
export const ARTIFACT_KIND_LABEL: Record<string, string> = { xlsx: "Excel file", image: "Image", snapshot: "Snapshot" };
// The pop-up also names a PDF, because its record carries a file the same way.
const ITEM_KIND_LABEL: Record<string, string> = { ...ARTIFACT_KIND_LABEL, pdf: "PDF file" };

export type ArtifactRecord = { id: string; kind: string; title: string; fileId?: string; mime?: string };

/** A C7 record, or a stored record of today's shape. Null when it has no id or kind. */
export function readArtifactRecord(value: unknown): ArtifactRecord | null {
  if (!value || typeof value !== "object" || Array.isArray(value)) return null;
  const row = value as Record<string, unknown>;
  const text = (key: string) => typeof row[key] === "string" ? (row[key] as string).trim() : "";
  const id = text("id");
  const kind = text("kind");
  if (!id || !kind) return null;
  // C7 names `file_id`. Today's PDF record keeps its file id in `ref`.
  const fileId = text("file_id") || text("fileId") || text("ref");
  const mime = text("mime");
  return { id, kind, title: text("title") || ITEM_KIND_LABEL[kind] || "Artifact",
    ...(fileId ? { fileId } : {}), ...(mime ? { mime } : {}) };
}

/** C7: the in-app link of one artifact record. */
export function artifactItemHash(id: string): string {
  return `#/artifacts?item=${encodeURIComponent(id)}`;
}

export type ArtifactReader = () => Promise<Result<ArtifactIndex>>;
const readArtifactIndex: ArtifactReader = () => fetchArtifacts();

// One shared `/artifacts` read per page session. A failed read clears it, so the next use retries.
let artifactRead: Promise<Map<string, ArtifactRecord>> | undefined;
let artifactReadGeneration = 0;
export function loadArtifactRecords(read: ArtifactReader = readArtifactIndex, fresh = false): Promise<Map<string, ArtifactRecord>> {
  if (fresh) artifactRead = undefined;
  if (!artifactRead) artifactReadGeneration += 1;
  return artifactRead ||= read().then((result) => {
    if (!result.ok) throw new Error("The artifact list could not be read.");
    const records = new Map<string, ArtifactRecord>();
    for (const item of result.value.items) {
      const record = readArtifactRecord(item);
      if (record) records.set(record.id, record);
    }
    return records;
  }).catch((error: unknown) => { artifactRead = undefined; throw error; });
}

/** True when an image file can show inline. A record with no mime is trusted by its kind. */
function picturable(record: ArtifactRecord): boolean {
  return Boolean(record.fileId) && record.kind === "image"
    && (!record.mime || record.mime.startsWith("image/"));
}

/** One made file under an answer: the chip opens the pop-up, an image shows inline, Excel offers a download. */
export function ArtifactChip({ record }: { record: ArtifactRecord }) {
  const inPlace = useOpenInPlace();
  const [broken, setBroken] = useState(false);
  const href = artifactItemHash(record.id);
  const file = record.fileId ? artifactFileHref(record.fileId) : "";
  return <div className="as-artifact">
    <div className="as-artifact-row">
      <a className="as-artifact-open" href={href} onClick={(event) => { interceptOpen(inPlace, href, event); }}>
        <span className="as-preview-name">{record.title}</span>
        <span className="as-preview-meta">{ARTIFACT_KIND_LABEL[record.kind]}</span>
      </a>
      {record.kind === "xlsx" && file ? <a className="as-artifact-download" href={file} download>Download</a> : null}
    </div>
    {/* A failed load leaves the chip alone, never a broken image. */}
    {picturable(record) && !broken ? <img className="as-artifact-image" src={file} alt={record.title}
      loading="lazy" onError={() => setBroken(true)} /> : null}
  </div>;
}

/** The chips for an answer's artifacts. Ids read the shared list. A message with none reads nothing. */
export function ArtifactChips({ entries, read = readArtifactIndex }: { entries?: unknown[]; read?: ArtifactReader }) {
  const list = Array.isArray(entries) ? entries : [];
  const key = list.filter((entry): entry is string => typeof entry === "string" && Boolean(entry)).join("\n");
  const [found, setFound] = useState<Map<string, ArtifactRecord> | null>(null);
  // A list read before this answer existed may miss its new id. That miss reads once more.
  const seenGeneration = useRef(artifactReadGeneration);
  useEffect(() => {
    if (!key) return;
    let live = true;
    const wanted = key.split("\n");
    loadArtifactRecords(read).then((records) => wanted.every((id) => records.has(id))
      || artifactReadGeneration > seenGeneration.current ? records : loadArtifactRecords(read, true))
      .then((records) => { if (live) setFound(records); }, () => {});
    return () => { live = false; };
  }, [key, read]);
  const records = list.map((entry) => typeof entry === "string" ? found?.get(entry) ?? null : readArtifactRecord(entry))
    .filter((record): record is ArtifactRecord => Boolean(record && ARTIFACT_KIND_LABEL[record.kind]));
  if (!records.length) return null;
  return <div className="as-artifacts">{records.map((record) => <ArtifactChip key={record.id} record={record} />)}</div>;
}

/** The selected artifact opens as stored content, an image, a download or one refusal. */
export function ArtifactItemView({ id, read = readArtifactIndex }: { id: string; read?: ArtifactReader }) {
  const [state, setState] = useState<{ record: ArtifactRecord | null } | "loading" | "failed">("loading");
  useEffect(() => {
    let live = true;
    loadArtifactRecords(read).then((records) => records.has(id) ? records : loadArtifactRecords(read, true))
      .then((records) => { if (live) setState({ record: records.get(id) ?? null }); },
        () => { if (live) setState("failed"); });
    return () => { live = false; };
  }, [id, read]);
  if (state === "loading") return <DockGrantLoading />;
  if (state === "failed") return <DockGrantFailed />;
  const record = state.record;
  if (!record) return <p className="oip-sentence" role="status">{NOT_AVAILABLE}</p>;
  const file = record.fileId ? artifactFileHref(record.fileId) : "";
  return <section className="oip-artifact" aria-label={record.title}>
    <h3 className="oip-artifact-title">{record.title}</h3>
    {ITEM_KIND_LABEL[record.kind] ? <p className="oip-artifact-kind">{ITEM_KIND_LABEL[record.kind]}</p> : null}
    {record.kind === "snapshot" ? <SnapshotTable id={record.id} /> : null}
    {picturable(record) ? <img className="oip-artifact-image" src={file} alt={record.title} /> : null}
    {(record.kind === "xlsx" || record.kind === "pdf") && file
      ? <a className="oip-artifact-download" href={file} download>Download</a> : null}
  </section>;
}

const PAGE_MODULES: InPlaceModules = { artifact: ArtifactItemView };

/** Route to the exact Query-owned artifact, preserving the public hosted variant. */
export function openBuiltView(qid: string, hosted = false): () => void {
  if (typeof window === "undefined") return () => {};
  if (!hosted && routeKeyOf(window.location.hash) !== QUERY_ROUTE) {
    window.location.hash = `#/${QUERY_ROUTE}`;
  }
  return retryEmit(() => signal(QUERY_OPEN_EVENT, { qid }));
}

/**
 * R9's provenance, as a DISCLOSURE. Every clause the ruling requires is present — sources,
 * fields, filters, aggregation, contributing record count, retrieval time, each a link to the
 * exact artefact — but shut by default, because a chat that prints its own audit trail under
 * every sentence is not the "plain look" the owner asked for and is not readable as an answer.
 */
export function CitationLine({ citation }: { citation: QueryCitation }) {
  return <a className="as-citation" href={citation.href}>{queryCitationLabel(citation)}</a>;
}

/** One glyph, drawn once and turned over for the other. R20 asked for thumbs; these are thumbs. */
function ThumbIcon({ down = false }: { down?: boolean }) {
  return (
    <svg viewBox="0 0 16 16" aria-hidden="true" width="13" height="13"
      {...(down ? { transform: "rotate(180)" } : {})}>
      <path d="M5.6 14.2V6.9h1.5l2.2-4.3a1 1 0 0 1 1.8.9l-.7 2.6h2.4a1 1 0 0 1 1 1.3l-1.1 4.6a1.5 1.5 0 0 1-1.5 1.1H5.6z" />
      <path d="M5.6 6.9H2.6v7.3h3" />
    </svg>
  );
}

export function AssistantMessage({
  message,
  view,
  citations,
  onPreview,
  onRate,
  governedArtifacts,
  confirmation,
  onConfirmed,
}: {
  message: AssistantChatMessage; view?: SavedQuery; citations: QueryCitation[]; onPreview: (id: string) => void;
  /** Optional so the message can be rendered outside a live conversation without a rating door. */
  onRate?: (id: string, rating: "up" | "down" | null, reason?: string) => void;
  governedArtifacts?: QueryToolArtifacts;
  confirmation?: string;
  onConfirmed?: (id: string, line: string) => void;
}) {
  // S72-T14: a mounted host shows a built view in its pop-up. Without one, `onPreview` routes as before.
  const inPlace = useOpenInPlace();
  const openView = (id: string) => {
    if (!inPlace?.open(`#/${QUERY_ROUTE}?view=${encodeURIComponent(id)}`)) onPreview(id);
  };
  const [openSources, setOpenSources] = useState(false);
  const [askWhy, setAskWhy] = useState(false);
  const [why, setWhy] = useState("");
  const [slackOpen, setSlackOpen] = useState(false);
  const [artifacts, setArtifacts] = useState<QueryToolArtifacts | null>(governedArtifacts || null);
  const [artifactStatus, setArtifactStatus] = useState("");
  const slackRef = useRef<HTMLDivElement | null>(null);
  // W51-T31 — the Slack correction card calls itself a `role="dialog"`, so it owes a dialog's
  // dismissal: Escape closes it, through the ONE stack (C8 / DESIGN.md §4). Registered here at
  // the top level rather than beside the markup, because the markup sits behind a conditional
  // and the early return for a user message is two lines below.
  useEscapeClose(slackOpen, () => setSlackOpen(false), { container: () => slackRef.current });
  const matching = citations.filter((citation) => (message.citationIds || []).includes(citation.id));
  if (message.role === "user") {
    return (
      <article className="as-message as-message--user">
        <p className="as-bubble">{message.content}</p>
      </article>
    );
  }
  if (message.streaming) {
    return <article className="as-message as-message--assistant as-answer-pending" aria-live="off">
      {message.toolStep ? <p className="as-tool-step">{message.toolStep}</p> : null}
      {message.content ? <p className="as-message-text">{message.content}</p> : null}
    </article>;
  }
  if (message.reason === "query_no_source_matched") {
    return <article className="as-message as-message--assistant">
      <p className="as-message-text"><LinkedText text={message.content} /></p>
      <WriteReport calls={message.toolCalls} onPreview={onPreview} />
      {message.pendingResolved ? <p className="as-confirm-result" role="status">{message.pendingResolved}</p>
        : message.pendingDelete ? <DeleteConfirmCard pending={message.pendingDelete}
        resolved={confirmation} onResolved={onConfirmed} /> : null}
    </article>;
  }
  const provenance = message.provenance;
  const sourceFooter = answerSourceFooter(provenance, matching);
  const numeric = message.numeric;
  return (
    <article className={"as-message as-message--assistant" + (message.reason ? " is-refusal" : "")}>
      <p className="as-message-text"><LinkedText text={message.content} /></p>
      <WriteReport calls={message.toolCalls} onPreview={onPreview} />
      {message.pendingResolved ? <p className="as-confirm-result" role="status">{message.pendingResolved}</p>
        : message.pendingDelete ? <DeleteConfirmCard pending={message.pendingDelete}
        resolved={confirmation} onResolved={onConfirmed} /> : null}
      {view && artifacts ? (
        <section className="w45-contract-card" aria-labelledby={`query-artifacts-${message.id}`}>
          <h4 id={`query-artifacts-${message.id}`}>Query setup</h4>
          <div className="w45-artifacts">
            {(["filters", "sorts", "group", "hiddenFields", "source"] as const).map((key) => (
              <label className="w45-artifact" key={key}>
                <span>{key === "hiddenFields" ? "Hidden fields" : key[0].toUpperCase() + key.slice(1)}</span>
                <input
                  defaultValue={JSON.stringify(artifacts[key])}
                  onBlur={(event) => {
                    try { const value = JSON.parse(event.currentTarget.value) as never; setArtifacts((current) => ({ ...(current as QueryToolArtifacts), [key]: value })); }
                    catch { setArtifactStatus(`${key} must be valid JSON.`); }
                  }}
                />
              </label>
            ))}
          </div>
          <div className="w45-chip-row">
            <button type="button" className="w45-quiet" onClick={async () => {
              setArtifactStatus("");
              try { await persistQueryArtifacts(view.id, view.view, artifacts); setArtifactStatus("Query setup saved"); }
              catch (error) { setArtifactStatus(error instanceof Error ? error.message : "Query setup could not be saved."); }
            }}>Save Query setup</button>
            <button type="button" className="w45-quiet" onClick={() => setSlackOpen(true)}>
              Correct in Slack
            </button>
            <button type="button" className="w45-quiet" onClick={() => openView(view.id)}>
              Open in Loopable
            </button>
          </div>
          {artifactStatus ? <p className="w45-safe" role="status">{artifactStatus}</p> : null}
          {slackOpen ? (
            <div className="w45-contract-card" role="dialog" aria-label="Slack correction"
                 ref={slackRef}>
              <h4>Slack correction</h4>
              <p>Slack can correct Filter, Sort, and Group after the Query capability check. Complex edits open the exact server-returned Query in Loopable.</p>
              {(["filters", "sorts", "group"] as const).map((key) => <label className="w45-artifact" key={key}>
                <span>{key[0].toUpperCase() + key.slice(1)}</span>
                <input defaultValue={JSON.stringify(artifacts[key])} onBlur={(event) => {
                  try { const value = JSON.parse(event.currentTarget.value) as never; setArtifacts((current) => ({ ...(current as QueryToolArtifacts), [key]: value })); }
                  catch { setArtifactStatus(`${key} must be valid JSON.`); }
                }} />
              </label>)}
              <p className="w45-safe">Draft only. No Slack message was sent.</p>
              <button type="button" className="w45-quiet" onClick={() => openView(view.id)}>Open in Loopable</button>
              <button type="button" className="w45-quiet" onClick={() => setSlackOpen(false)}>
                Close
              </button>
            </div>
          ) : null}
        </section>
      ) : null}
      {numeric && numeric.value !== null && numeric.value !== undefined ? (
        <p className="as-numeric">
          <span className="as-numeric-label">{numeric.label}</span>
          <strong className="as-numeric-value">{numeric.value.toLocaleString()}</strong>
        </p>
      ) : null}
      {view ? (
        <button type="button" className="as-preview" onClick={() => openView(view.id)}>
          <span className="as-preview-name">{view.name}</span>
          {/* ⚠ ONE expression, not three text nodes. `Open the {x} in Query` renders under SSR as
              `Open the<!-- -->table<!-- --> in Query`, so a check reading the sentence back sees
              a string nobody wrote [[ui-invisible-to-assertions]]. */}
          <span className="as-preview-meta">{`Open the ${KIND_LABEL[view.kind] ?? view.kind} in Artifacts`}</span>
        </button>
      ) : null}
      <ArtifactChips entries={message.artifacts} />
      {/* R112: one quiet row, the sources line (only when a permitted citation backs the answer)
          and the two thumbs. The sentence is the disclosure that opens the citation links. The thumbs are NOT a survey: the server reads a thumbs-down back into
          the next turn of this thread, so a down asks for one short reason and both are clearable. */}
      {matching.length || onRate ? <div className="as-answer-foot">
      {matching.length ? (
        <footer className="as-citation" aria-label="Answer sources">
          <button type="button" className="as-sources-btn" aria-expanded={openSources}
            onClick={() => setOpenSources(!openSources)}>{sourceFooter}</button>
        </footer>
      ) : null}
      {onRate ? (
        <div className="as-rate">
          <button type="button" aria-label="Helpful" aria-pressed={message.rating === "up"}
            className={"as-rate-btn" + (message.rating === "up" ? " is-on" : "")}
            onClick={() => { setAskWhy(false); onRate(message.id, message.rating === "up" ? null : "up"); }}>
            <ThumbIcon />
          </button>
          <button type="button" aria-label="Not helpful" aria-pressed={message.rating === "down"}
            className={"as-rate-btn" + (message.rating === "down" ? " is-on" : "")}
            onClick={() => {
              if (message.rating === "down") { setAskWhy(false); onRate(message.id, null); return; }
              setAskWhy(true); onRate(message.id, "down");
            }}>
            <ThumbIcon down />
          </button>
          {message.rating === "down" && !askWhy && message.ratingReason ? (
            <span className="as-rate-why-said">{message.ratingReason}</span>
          ) : null}
        </div>
      ) : null}
      </div> : null}
      {onRate && askWhy && message.rating === "down" ? (
        <form className="as-rate-why" onSubmit={(event) => {
          event.preventDefault(); setAskWhy(false); onRate(message.id, "down", why.trim());
        }}>
          <input className="as-rate-input" value={why} aria-label="What was wrong"
            placeholder="What was wrong? Optional."
            onChange={(event) => setWhy(event.currentTarget.value)} />
          <button type="submit" className="as-rate-send">Send</button>
        </form>
      ) : null}
      {matching.length && openSources ? (
        <div className="as-sources-list">
          {matching.map((citation) => <CitationLine key={citation.id} citation={citation} />)}
        </div>
      ) : null}
    </article>
  );
}

function initialIndex(): QueryIndex {
  return { threads: [], messages: [], views: [], citations: [], models: ["auto"],
           modelStatus: [], sources: [] };
}

/** One persistent conversation, with the composer anchored below its scrollable turns. */
export default function AssistantPage({ granted }: AssistantPageProps) {
  const [memoryOpen, setMemoryOpen] = useState(false);
  const [index, setIndex] = useState<QueryIndex>(initialIndex);
  const [turns, setTurns] = useState<AssistantLogTurn[]>([]);
  const [hasMore, setHasMore] = useState(false);
  const [conversationLoaded, setConversationLoaded] = useState(false);
  const [conversationLoading, setConversationLoading] = useState(true);
  const [conversationProblem, setConversationProblem] = useState("");
  const [confirmations, setConfirmations] = useState<Record<string, string>>({});
  const [freshMessageIds, setFreshMessageIds] = useState<string[]>([]);
  const [target, setTarget] = useState("");
  const [question, setQuestion] = useState("");
  const [busy, setBusy] = useState(false);
  const [answerStarted, setAnswerStarted] = useState(false);
  const [stopping, setStopping] = useState(false);
  const [problem, setProblem] = useState("");
  const [loaded, setLoaded] = useState(false);
  const [artifactByView, setArtifactByView] = useState<Record<string, QueryToolArtifacts>>({});
  const [alignment, setAlignment] = useState<null | {
    prompt: string; database: string; resumeToken: string;
    question: string; choices: Array<{ field: string; label: string }>; maxSelections: number;
    routed?: RoutedTo;
    draft?: SemanticDraft; sent?: boolean;
  }>(null);
  const [alignmentFields, setAlignmentFields] = useState<string[]>([]);
  const [draftBusy, setDraftBusy] = useState(false);
  const [draftProblem, setDraftProblem] = useState("");
  const [approvalLine, setApprovalLine] = useState("");
  const composerRef = useRef<HTMLTextAreaElement | null>(null);
  const alignmentRef = useRef<HTMLElement | null>(null);
  const requestInFlight = useRef(false);
  const activeChat = useRef<ChatBatch | null>(null);
  const stopInFlight = useRef(false);
  const alignmentGeneration = useRef(0);
  const lastDraftCheck = useRef(0);
  useEscapeClose(Boolean(alignment), () => {
    alignmentGeneration.current += 1;
    setAlignment(null); setAlignmentFields([]); setDraftProblem("");
    composerRef.current?.focus();
  }, { container: () => alignmentRef.current });
  const openCancel = useRef<(() => void) | null>(null);
  const streamRef = useRef<HTMLDivElement | null>(null);
  const conversationInFlight = useRef(false);
  const conversationGeneration = useRef(0);
  const scrollRestore = useRef<{ height: number; top: number } | null>(null);
  const scrollToNewest = useRef(false);
  const followsNewest = useRef(true);
  const retryBefore = useRef<string | undefined>(undefined);
  const olderPagesLoaded = useRef(false);
  /** A counter, not a random id: the optimistic message only has to be unique within this page. */
  const pending = useRef(0);

  const databases = useMemo(() => databaseEntries(granted).filter((entry) => entry.kind !== "group"), [granted]);
  /**
   * ⭐⭐ INSTRUCTION 12 / R11 — NO SOURCE PICKER AT ALL. Owner: *"the Assistant should always have
   * access to all database that the user have access to. So it doesn't need the database clicks
   * under the chat."* The chip row and the sentence explaining why some chips were grey are both
   * gone; the limit they explained is closed in the read boundary, not narrated to the reader.
   * `databases` above IS the answer to "what may the assistant read", and the server wall
   * (`deps.py::assistant_source_status`) remains the authority on every request.
   */
  const viewById = useMemo(() => new Map(index.views.map((view) => [view.id, view])), [index.views]);

  const reload = useCallback(async () => {
    const result = await fetchQueries();
    setLoaded(true);
    if (result.ok) setIndex(result.value);
  }, []);

  const loadConversation = useCallback(async (before?: string) => {
    if (conversationInFlight.current) return;
    conversationInFlight.current = true;
    const generation = conversationGeneration.current;
    retryBefore.current = before;
    setConversationLoading(true); setConversationProblem("");
    try {
      const result = await fetchConversation(before);
      if (generation !== conversationGeneration.current) return;
      if (!result.ok) {
        setConversationProblem("The conversation could not be loaded."); return;
      }
      if (before) {
        const stream = streamRef.current;
        if (stream) scrollRestore.current = { height: stream.scrollHeight, top: stream.scrollTop };
        setTurns((current) => mergeTurns(result.value.turns, current));
        olderPagesLoaded.current = true;
      } else {
        scrollToNewest.current = followsNewest.current;
        setTurns((current) => mergeTurns(current, result.value.turns));
      }
      if (before || !olderPagesLoaded.current) setHasMore(result.value.hasMore);
      setConversationLoaded(true);
    } catch {
      if (generation === conversationGeneration.current)
        setConversationProblem("The conversation could not be loaded.");
    } finally {
      if (generation === conversationGeneration.current) {
        conversationInFlight.current = false; setConversationLoading(false);
      }
    }
  }, []);

  useEffect(() => {
    void loadConversation();
    return () => {
      const chat = activeChat.current;
      activeChat.current = null;
      chat?.resolve(null);
      chat?.requests.forEach(({ controller }) => controller.abort());
      conversationGeneration.current += 1;
      conversationInFlight.current = false;
    };
  }, [loadConversation]);

  // Layout runs before paint: initial opens land at the bottom, prepends retain the read position.
  useConversationLayoutEffect(() => {
    const stream = streamRef.current;
    if (!stream) return;
    if (scrollRestore.current) {
      const previous = scrollRestore.current;
      stream.scrollTop = previous.top + stream.scrollHeight - previous.height;
      scrollRestore.current = null;
    } else if (scrollToNewest.current || (busy && followsNewest.current)) {
      stream.scrollTop = stream.scrollHeight;
      scrollToNewest.current = false;
    }
  }, [turns, busy, conversationLoading]);

  const onConversationScroll = () => {
    const stream = streamRef.current;
    if (stream) {
      followsNewest.current = stream.scrollHeight - stream.scrollTop - stream.clientHeight < 48;
      if (!followsNewest.current) scrollToNewest.current = false;
    }
    if (streamRef.current && streamRef.current.scrollTop < 200 && hasMore
      && conversationLoaded && !conversationProblem) void loadConversation(turns[0]?.id);
  };

  useEffect(() => { void reload(); }, [reload]);
  useEffect(() => () => openCancel.current?.(), []);
  // Keep source selection within the grant for clarification replays. A fresh question needs
  // no target: the server preflight decides whether to route Data or continue guarded chat.
  useEffect(() => {
    const permitted = databases.map((entry) => entry.key);
    setTarget((current) => permitted.includes(current) ? current : databases[0]?.key ?? "");
  }, [databases]);
  // A resume token is bound to the database that produced it. Changing the target invalidates the
  // clarification instead of replaying the token against a different database.
  useEffect(() => {
    if (alignment && alignment.database !== target) {
      setAlignment(null);
      setAlignmentFields([]);
    }
  }, [alignment, target]);
  useEffect(() => {
    alignmentGeneration.current += 1;
    setDraftProblem(""); setApprovalLine("");
  }, [target]);


  /**
   * ⭐⭐ R16 — ENTER GOES TO THE CHAT, NOT TO A WAIT. Owner: *"Pressing enter goes immediately to
   * the chat view showing that it is loading; there is a thinking animation."*
   *
   * This used to POST and only then touch `index`, so for the whole model call the reader sat on
   * the opening screen looking at their own unsent sentence with nothing moving. The message is
   * appended FIRST, which is what flips `empty` and hands the surface to the stream; `busy` then
   * draws the app's one loading mark under it.
   *
   * ⛔ THE INVERSE IS CAPTURED BEFORE THE WRITE. An optimistic append that is not reconciled on
   * failure leaves a message on screen the server never received, and the next turn replays it to
   * the model as if it had [[undo-capture-before-the-write]]. The typed text goes back in the
   * composer too: losing somebody's sentence to a failed request is the second injury.
   */
  const ask = useCallback(async (approvedFields?: string[], override?: { database: string; prompt: string }) => {
    const replayDraft = !override && alignment?.draft && (approvedFields || alignment.sent);
    const replay = (approvedFields || replayDraft) && alignment;
    const text = override?.prompt ?? (replay ? replay.prompt : question.trim());
    const selectedTarget = approvedFields && alignment ? alignment.database : target;
    const database = override?.database ?? (replay ? (approvedFields ? selectedTarget : replay.database) : "");
    if (!text || !conversationLoaded || draftBusy || stopInFlight.current
      || (requestInFlight.current && !activeChat.current)) return;
    const primary = !activeChat.current;
    if (primary) {
      let resolve!: ChatBatch["resolve"];
      const ready = new Promise<ChatRouting | null>((settle) => { resolve = settle; });
      activeChat.current = { requests: new Map(), joined: new Set(), restored: new Set(),
        routingReady: false, ready, resolve };
      setAnswerStarted(false);
    }
    const batch = activeChat.current!;
    requestInFlight.current = true;
    const controller = new AbortController();
    const isCurrent = () => activeChat.current === batch && !controller.signal.aborted;
    const generation = alignmentGeneration.current;
    setBusy(true); setProblem(""); setDraftProblem("");
    if (!replay) setApprovalLine("");
    const pendingId = `pending_${(pending.current += 1)}`;
    const answerId = `${pendingId}_answer`;
    batch.requests.set(pendingId, { controller, answerId, text });
    const optimistic = {
      id: pendingId, role: "user", content: text,
      createdAt: new Date().toISOString(), targetDatabase: database,
      sources: database ? [database] : [],
    } as AssistantChatMessage;
    const withoutPending = (rows: AssistantLogTurn[]) => rows.filter((row) => row.id !== pendingId && row.id !== answerId);
    const undoOptimistic = () => {
      const unsent = (primary && !batch.routingReady ? [...batch.requests.entries()]
        : [[pendingId, { answerId, text }] as const]).filter(([id]) => !batch.restored.has(id));
      if (!unsent.length) return;
      const ids = new Set(unsent.flatMap(([id, row]) => [id, row.answerId]));
      unsent.forEach(([id]) => batch.restored.add(id));
      setTurns((current) => current.filter((turn) => !ids.has(turn.id)));
      setQuestion((current) => [...unsent.map(([, row]) => row.text), current].filter(Boolean).join("\n"));
    };
    // R108: a refused or failed turn keeps the asked message on screen and says its cause once.
    // The local copy gives way only when the durable log already holds the same message.
    const keepAsked = (sentence: string) => {
      batch.restored.add(pendingId);
      setTurns((current) => current.filter((turn) => turn.id !== answerId && (turn.id !== pendingId
        || !current.some((row) => row.role === "user" && !row.id.startsWith("pending_")
          && row.text === text && row.at >= optimistic.createdAt))));
      setProblem(sentence);
    };
    const acknowledgeJoin = () => {
      batch.joined.add(pendingId);
      setTurns((current) => current.filter((turn) => turn.id !== answerId && (turn.id !== pendingId
        || !current.some((row) => row.role === "user" && !row.id.startsWith("pending_")
          && row.text === text && row.at >= optimistic.createdAt))));
    };
    setQuestion("");
    setFreshMessageIds([pendingId]);
    scrollToNewest.current = followsNewest.current;
    setTurns((current) => [...current, localTurn(optimistic)]);
    try {
      let governed: RoutedQueryResult;
      let routed: RoutedTo | undefined;
      let chosen: string;
      if (!primary) {
        const routing = await batch.ready;
        if (!isCurrent()) return;
        if (!routing) { undoOptimistic(); return; }
        governed = routing.governed;
        chosen = routing.database;
        routed = routing.routed;
      } else {
        try {
          // One narrow cast for routing and drafts; the shared result union stays in its owning lane.
          if (replayDraft) {
            const current = await draftRequest(database);
            if (!isCurrent()) return;
            if (generation !== alignmentGeneration.current) {
              undoOptimistic();
              return;
            }
            if (current.draft?.approvalLine) setApprovalLine(current.draft.approvalLine);
          }
          governed = await runQueryTool({ database, prompt: text,
            ...(approvedFields && !replayDraft ? { fieldKeys: approvedFields, resumeToken: alignment?.resumeToken } : {}) }) as RoutedQueryResult;
          if (!isCurrent()) return;
          if (replayDraft && governed.status === "clarification" && !governed.draft) {
            // Approval changes the choice set. Only this fresh clarification can authenticate resume.
            const choices = new Set(governed.alignmentQuestion.choices.map((choice) => choice.field));
            const fields = (approvedFields || alignmentFields).filter((field) => choices.has(field));
            if (fields.length) {
              const retry = { database, prompt: text, fieldKeys: fields, resumeToken: governed.resumeToken };
              governed = await runQueryTool(retry) as RoutedQueryResult;
            }
          }
        } catch (error) {
          if (!isCurrent()) return;
          if (generation !== alignmentGeneration.current) { undoOptimistic(); return; }
          if (alignment?.draft) {
            keepAsked("");
            setDraftProblem("The field request could not be completed, so please try again.");
          } else keepAsked(refusalSentence(failureCode(error)));
          return;
        }
        if (!isCurrent()) return;
        if (generation !== alignmentGeneration.current) {
          undoOptimistic();
          return;
        }
        routed = replay && alignment?.routed ? alignment.routed : governed.routedTo;
        chosen = governed.routedTo?.database ?? database;
        if (chosen) setTarget(chosen);
        if (governed.status === "clarification") {
          undoOptimistic();
          const sent = Boolean(replayDraft && alignment?.sent && governed.draft?.state === "pending");
          if (!sent) setAlignmentFields([]);
          setAlignment({ prompt: text, database: chosen, routed, draft: governed.draft, sent,
            resumeToken: governed.resumeToken, question: governed.alignmentQuestion.question,
            choices: governed.alignmentQuestion.choices, maxSelections: governed.alignmentQuestion.maxSelections });
          return;
        }
        setAlignment(null);
        composerRef.current?.focus();
        // C2: a coded refusal says its sentence and stops. An uncoded one still reaches chat's reply.
        if (governed.status === "refused" && governed.code) { keepAsked(refusalSentence(governed.code)); return; }
        if (governed.status === "refused") undoOptimistic();
        // Queue during routing. Clarification and refusal restore unsent follow-ups to the composer.
        batch.routingReady = governed.status !== "refused";
        batch.resolve(governed.status === "refused" ? null : { governed, database: chosen, routed });
      }
      setTurns((current) => [...current, localTurn({ ...optimistic, id: answerId,
        role: "assistant", content: "", streaming: true })]);
      // ⛔ THE TARGET, ALONE. `routes_query.py::_sources` runs EVERY key in this array through the
      // read scope with no try/except, so one refusal kills the whole request; and the model is only
      // ever handed the target's snapshot anyway. A wider array buys nothing and breaks the turn.
      // Automatic refusals go through chat's same routing branch, which saves a plain reply
      // without trying to read an unavailable database. Successful replies use the chosen target.
      const chatDatabase = governed.status === "refused" && routed?.auto ? "" : chosen;
      let result: Awaited<ReturnType<typeof submitChat>>;
      try {
        const streamed = await streamChat({ question: text, database: chatDatabase, sources: chosen ? [chosen] : [], model: "auto" },
          (event) => {
            if (!isCurrent()) return;
            if (event.type === "text_delta" || event.type === "tool_step" || event.type === "paused") {
              if (event.type === "text_delta" && streamDelta(event.data)) setAnswerStarted(true);
              setTurns((current) => current.map((turn) => turn.id !== answerId ? turn : event.type === "text_delta"
                ? { ...turn, text: turn.text + streamDelta(event.data) }
                : { ...turn, payload: { ...turn.payload, toolStep: event.type === "paused"
                  ? typeof event.data.message === "string" ? event.data.message : "Waiting to resume."
                  : event.data.label || event.data.message || "Working" } }));
            }
          }, controller.signal);
        if (!isCurrent()) return;
        if (streamed.type !== "done") {
          acknowledgeJoin();
          return;
        }
        result = { ok: true, value: streamed.data };
      } catch (error) {
        if (!isCurrent()) return;
        if (canFallback(error, controller.signal)) {
          result = await submitChat({ question: text, database: chatDatabase, sources: chosen ? [chosen] : [], model: "auto" }, controller.signal);
        } else {
          if (error instanceof ChatStreamFailure && error.admitted) {
            await loadConversation();
          }
          keepAsked(refusalSentence(failureCode(error)));
          return;
        }
      }
      if (!isCurrent()) return;
      if (!result.ok) {
        keepAsked(refusalSentence(result.code));
        return;
      }
      if ("status" in result.value && result.value.status === "joined") { acknowledgeJoin(); return; }
      if (!("message" in result.value)) return;
      const reply = result.value;
      setAnswerStarted(true);
      if (reply.view && governed.status === "answered") {
        setArtifactByView((current) => ({ ...current, [reply.view!.id]: governed.artifacts }));
      }
      setIndex((current) => ({
        ...current,
        views: reply.view ? [reply.view, ...current.views.filter((row) => row.id !== reply.view?.id)] : current.views,
        citations: [...current.citations, ...reply.citations],
      }));
      scrollToNewest.current = followsNewest.current;
      setFreshMessageIds([reply.userMessage.id]);
      setTurns((current) => mergeTurns(withoutPending(current),
        [localTurn(reply.userMessage), localTurn(reply.message)]));
      // Reconcile optimistic turns with the durable log's ids and agent fields.
      retryBefore.current = undefined;
      try {
        const conversation = await fetchConversation();
        if (!isCurrent()) return;
        if (conversation.ok) {
          scrollToNewest.current = followsNewest.current;
          setFreshMessageIds([]);
          setTurns((current) => mergeTurns(current.filter((turn) => !batch.joined.has(turn.id)
            || !conversation.value.turns.some((row) => row.role === "user" && row.text === turn.text
              && row.at >= turn.at)), conversation.value.turns));
        } else setConversationProblem("The latest turn details could not be loaded.");
      } catch { if (isCurrent()) setConversationProblem("The latest turn details could not be loaded."); }
    } finally {
      if (primary) batch.resolve(null);
      batch.requests.delete(pendingId);
      if (isCurrent() && !batch.requests.size) {
        activeChat.current = null;
        requestInFlight.current = false; setBusy(false);
      }
    }
  }, [alignment, alignmentFields, conversationLoaded, draftBusy, question, target, loadConversation]);

  const stop = async () => {
    const batch = activeChat.current;
    if (!batch || stopInFlight.current) return;
    stopInFlight.current = true; setStopping(true);
    try {
      const result = await stopTurn();
      if (activeChat.current !== batch) return;
      if (!result.ok) { setProblem("This turn could not be stopped. Try again."); return; }
      activeChat.current = null;
      batch.resolve(null);
      batch.requests.forEach(({ controller }) => controller.abort());
      conversationGeneration.current += 1;
      conversationInFlight.current = false; setConversationLoading(false);
      requestInFlight.current = false; setBusy(false); setAnswerStarted(false);
      setProblem(""); setAlignment(null); setAlignmentFields([]);
      const answers = new Set([...batch.requests.values()].map(({ answerId }) => answerId));
      setTurns((current) => [...current.filter((turn) => !answers.has(turn.id)), {
        id: `stopped_${(pending.current += 1)}`, role: "system", door: "app", kind: "text",
        text: "Stopped.", at: new Date().toISOString(),
      }]);
      scrollToNewest.current = followsNewest.current;
      composerRef.current?.focus();
    } catch {
      if (activeChat.current === batch) setProblem("This turn could not be stopped. Try again.");
    } finally {
      stopInFlight.current = false; setStopping(false);
    }
  };

  useEffect(() => {
    if (!conversationLoaded || busy || requestInFlight.current) return;
    const prompt = takePendingAsk();
    if (prompt) void ask(undefined, { database: "", prompt });
  }, [ask, busy, conversationLoaded]);

  const submitDraft = async () => {
    if (!alignment?.draft || !alignmentFields.length || busy || draftBusy || requestInFlight.current) return;
    const chosenFields = [...alignmentFields];
    const generation = alignmentGeneration.current;
    requestInFlight.current = true;
    setDraftBusy(true); setDraftProblem("");
    try {
      const result = await draftRequest(alignment.database, chosenFields, alignment.prompt);
      if (generation !== alignmentGeneration.current) return;
      if (result.state === "approved") {
        setApprovalLine(result.approvalLine || "");
        requestInFlight.current = false;
        await ask(chosenFields);
      } else if (result.state === "pending") {
        lastDraftCheck.current = Date.now();
        setAlignment((current) => current ? { ...current, sent: true } : null);
      } else {
        setDraftProblem("The field request could not be completed, so please try again.");
      }
    } catch {
      if (generation === alignmentGeneration.current)
        setDraftProblem("The field request could not be completed, so please try again.");
    } finally {
      requestInFlight.current = false;
      setDraftBusy(false);
    }
  };

  useEffect(() => {
    if (!alignment?.draft || !alignment.sent) return;
    const recheck = () => {
      if (busy || draftBusy || requestInFlight.current || Date.now() - lastDraftCheck.current < 10000) return;
      lastDraftCheck.current = Date.now();
      void ask();
    };
    window.addEventListener("focus", recheck);
    return () => window.removeEventListener("focus", recheck);
  }, [alignment, ask, busy, draftBusy]);


  /**
   * The rating goes to the server and the SERVER'S copy comes back, rather than the page patching
   * its own guess: the reason is normalised and cleared there, and a rating that only looked
   * applied is exactly the shape this module keeps being bitten by.
   */
  const rate = useCallback(async (id: string, rating: "up" | "down" | null, reason?: string) => {
    const result = await rateMessage(id, rating, reason);
    if (!result.ok) { setProblem(result.message); return; }
    setTurns((current) => current.map((turn) => (turn.payload?.id || turn.id) === id
      ? { ...turn, payload: { ...turn.payload, ...result.value } } : turn));
  }, []);

  const preview = useCallback((qid: string) => {
    openCancel.current?.();
    openCancel.current = openBuiltView(qid);
  }, []);

  const empty = turns.length === 0;
  const thinking = busy && !answerStarted;
  const composer = (
    <div className="as-composer">
      {approvalLine ? <p className="as-draft-state" role="status">{approvalLine}</p> : null}
      {alignment ? <section ref={alignmentRef} className={`w45-contract-card${alignment.draft ? " as-draft-card" : ""}`} aria-label="Alignment question">
        <h4>{alignment.draft ? "Database fields" : "Clarify"}</h4>
        <p className={alignment.sent ? "as-draft-state" : undefined} role={alignment.sent ? "status" : undefined}>
          {alignment.sent ? alignment.draft?.sentMessage : alignment.question}
        </p>
        <div className="w45-chip-row">{alignment.choices.filter((choice) => !alignment.sent || alignmentFields.includes(choice.field)).map((choice) => {
          const on = alignmentFields.includes(choice.field);
          const drafted = alignment.draft?.fields.find((field) => field.field === choice.field);
          const redacted = drafted && (drafted.sample.redacted || ["sensitive", "restricted"].includes(drafted.sensitivity));
          return <button type="button" className={`w45-chip ${on ? "is-on" : "is-off"}${drafted ? " as-draft-field" : ""}`} key={choice.field}
            title={drafted?.why} disabled={busy || draftBusy || alignment.sent}
            aria-pressed={on} onClick={() => setAlignmentFields((current) => on
              ? current.filter((field) => field !== choice.field)
              : current.length < alignment.maxSelections ? [...current, choice.field] : current)}>
            <span>{choice.label}</span>
            {drafted ? <>
              <span className="as-draft-detail">{drafted.role} · {drafted.dataType}</span>
              <span className="as-draft-detail">{redacted ? "Redacted"
                : [...drafted.sample.values, ...drafted.sample.sample].slice(0, 3).join(", ") || "No populated values"}</span>
            </> : null}
          </button>;
        })}</div>
        {draftProblem ? <p className="as-draft-state" role="status">{draftProblem}</p> : null}
        {alignment.sent ? <button type="button" className="w45-quiet" disabled={busy || draftBusy}
          onClick={() => { lastDraftCheck.current = Date.now(); void ask(); }}>Check again</button>
          : <button type="button" className="w45-quiet" disabled={!alignmentFields.length || busy || draftBusy}
            onClick={() => alignment.draft ? void submitDraft() : void ask(alignmentFields)}>
            {alignment.draft ? alignment.draft.canApprove ? "Approve and answer" : "Send to administrators"
              : "Resume with approved selection"}
          </button>}
      </section> : null}
      <div className="as-field">
        <textarea
          ref={composerRef}
          className="as-prompt"
          value={question}
          rows={1}
          placeholder="Ask the assistant…"
          aria-label="Ask the assistant"
          onChange={(event) => setQuestion(event.currentTarget.value)}
          onKeyDown={(event) => {
            if (event.key === "Enter" && !event.shiftKey) { event.preventDefault(); void ask(); }
          }}
        />
        <div className="as-field-foot">
          {/* R112: Memory is one small icon. The word stays as the accessible text, hidden by CSS. */}
          <button type="button" className="as-memory-button as-memory-open" aria-expanded={memoryOpen}
            aria-haspopup="dialog" aria-label="Memory" title="Memory"
            onClick={() => setMemoryOpen((value) => !value)}>Memory</button>
          {busy ? <button type="button" className="as-stop" disabled={stopping}
            onClick={() => void stop()}>Stop</button> : null}
          {/* R116: no model or database picker. The server routes the question and picks the model. */}
          <button type="button" className="as-send" aria-label="Send"
            disabled={stopping || draftBusy || !conversationLoaded || !question.trim()} onClick={() => void ask()}>
            <svg viewBox="0 0 16 16" aria-hidden="true" width="15" height="15">
              <path d="M8 13V3.6M4 7.4 8 3.4l4 4" />
            </svg>
          </button>
        </div>
      </div>
      {/* No source row: the assistant reads every database the caller can reach. What remains is
          the one case the reader still has to be told about, which is having none at all. */}
      {databases.length === 0 && loaded ? (
        <div className="as-chips">
          <p className="as-chips-empty">No databases are shared with your account yet.</p>
        </div>
      ) : null}
    </div>
  );

  // ⛔ `aria-label` is "Assistant", not "AI assistant" (W34-T13, corrected at QA 2026-08-17).
  // An aria-label IS a label — it is what a screen reader announces this region as — so the rail
  // reading Assistant while this said AI assistant left the rename half-done in the one place
  // sighted QA never looks.
  return (
    <OpenInPlaceHost granted={granted} modules={PAGE_MODULES}>
    <div className="as-chat" aria-label="Assistant">
      <main className="as-conversation">
        <div className="as-stream" ref={streamRef} onScroll={onConversationScroll}
          aria-busy={conversationLoading}>
          <div className="as-column">
            {empty && conversationLoaded ? <ModuleHomeHead title="Assistant" module="assistant" /> : null}
            <div className={`as-skeleton${conversationLoading ? "" : " as-skeleton--idle"}`}
              role={conversationLoading ? "status" : undefined} aria-hidden={!conversationLoading}
              aria-label={conversationLoading ? "Loading conversation" : undefined} />
            {empty ? <div className="as-opening"><AssistantGreeting loaded={conversationLoaded}
              turnCount={turns.length} />
              <SuggestionChips granted={granted} loaded={conversationLoaded} turnCount={turns.length}
                busy={busy} onAsk={(database, prompt) => void ask(undefined, { database, prompt })} />
            </div> : null}
            {turns.map((turn) => {
              const message = turnMessage(turn);
              return <AssistantTurn key={turn.id} turn={turn}
                fresh={freshMessageIds.includes(message.id)}
                view={message.viewId ? viewById.get(message.viewId) : undefined}
                citations={index.citations} onPreview={preview}
                governedArtifacts={turn.payload?.governedArtifacts ||
                  (message.viewId ? artifactByView[message.viewId] : undefined)}
                onRate={turn.role === "assistant" && turn.kind === "text" && !message.id.startsWith("pending_")
                  ? rate : undefined}
                confirmation={message.pendingDelete ? confirmations[message.pendingDelete.id] : undefined}
                onConfirmed={(id, line) => setConfirmations((current) => ({ ...current, [id]: line }))} />;
            })}
            {thinking ? <TypingIndicator /> : null}
          </div>
        </div>
        <div className="as-dock">
          <div className="as-column">
            {conversationProblem ? <p className="as-problem" role="status">
              {conversationProblem}{" "}
              <button type="button" className="as-retry" disabled={conversationLoading}
                onClick={() => void loadConversation(retryBefore.current)}>Try again</button>
            </p> : null}
            {problem ? <p className="as-problem" role="status">{problem}</p> : null}
            {composer}
          </div>
        </div>
      </main>
      {memoryOpen ? <MemoryPanel open={memoryOpen} onClose={() => setMemoryOpen(false)} granted={granted} /> : null}
    </div>
    </OpenInPlaceHost>
  );
}