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
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
import { MantineProvider } from "@mantine/core";
import { act, render } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
  chatGenerationStatePubSub,
  chatInputPubSub,
  chatMessagesPubSub,
  followUpQuestionPubSub,
  getSuppressNextFollowUp,
  suppressNextFollowUpPubSub,
} from "@/modules/pubSub";
import {
  getLatestSearchAttempt,
  recordSearchAttempt,
} from "@/modules/searchAttempts";
import type { ChatMessage } from "@/modules/types";
import ChatInterface from "./ChatInterface";

const [updateChatGenerationState, , getChatGenerationState] =
  chatGenerationStatePubSub;
const [updateChatInput] = chatInputPubSub;
const [updateFollowUpQuestion, , getFollowUpQuestion] = followUpQuestionPubSub;
const [updateSuppressNextFollowUp] = suppressNextFollowUpPubSub;
const [updateChatMessages, , getChatMessages] = chatMessagesPubSub;

vi.mock("@/modules/textGeneration", () => ({
  generateChatResponse: vi.fn(),
}));

vi.mock("@/modules/followUpQuestions", () => ({
  generateFollowUpQuestion: vi.fn(),
}));

vi.mock("@/modules/chatHelpers", () => ({
  persistChatConversation: vi.fn(() => Promise.resolve()),
  runFollowUpSearch: vi.fn(() => Promise.resolve()),
}));

/** The search run the chat belongs to; a test changes it to start a new search. */
let currentSearchRunId = "run-1";
vi.mock("@/modules/history", () => ({
  getCurrentSearchRunId: vi.fn(() => currentSearchRunId),
}));

vi.mock("@/modules/notifications", () => ({
  showAiCompleteNotification: vi.fn(),
}));

vi.mock("@/modules/logEntries", () => ({ addLogEntry: vi.fn() }));

vi.mock("@mantine/notifications", () => ({
  notifications: { show: vi.fn() },
}));

vi.mock("./ChatHeader", () => ({ default: () => null }));

let sendMessage: (textToSend?: string) => Promise<void>;
let regenerateResponse: () => Promise<void>;
let editMessage: (absoluteIndex: number) => void;
let messageListMessages: ChatMessage[] = [];
let messageListIsGenerating = false;
let messageListFollowUpStartIndex: number | undefined;

vi.mock("./ChatInputArea", () => ({
  default: (props: { handleSend: (textToSend?: string) => Promise<void> }) => {
    sendMessage = props.handleSend;
    return null;
  },
}));

vi.mock("./MessageList", () => ({
  default: (props: {
    messages: ChatMessage[];
    followUpStartIndex: number;
    isGenerating: boolean;
    onRegenerate: () => Promise<void>;
    onEditMessage: (absoluteIndex: number) => void;
  }) => {
    regenerateResponse = props.onRegenerate;
    editMessage = props.onEditMessage;
    messageListMessages = props.messages;
    messageListFollowUpStartIndex = props.followUpStartIndex;
    messageListIsGenerating = props.isGenerating;
    return null;
  },
}));

const { generateChatResponse } = await import("@/modules/textGeneration");
const { generateFollowUpQuestion } = await import(
  "@/modules/followUpQuestions"
);
const { persistChatConversation, runFollowUpSearch } = await import(
  "@/modules/chatHelpers"
);
const { getCurrentSearchRunId } = await import("@/modules/history");
const { addLogEntry } = await import("@/modules/logEntries");
const { notifications } = await import("@mantine/notifications");

/** A promise plus the handle to settle it, so a test can hold a call open. */
function deferred<T>() {
  let resolve: (value: T) => void = () => undefined;
  let reject: (reason: Error) => void = () => undefined;
  const promise = new Promise<T>((resolvePromise, rejectPromise) => {
    resolve = resolvePromise;
    reject = rejectPromise;
  });
  return { promise, resolve, reject };
}

const initialQuery = "What is a wake lock?";
const initialResponse = "An API that keeps the screen on.";

function renderChatInterface({ suppressInitialFollowUp = true } = {}) {
  return render(
    <MantineProvider>
      <ChatInterface
        initialQuery={initialQuery}
        initialResponse={initialResponse}
        suppressInitialFollowUp={suppressInitialFollowUp}
      />
    </MantineProvider>,
  );
}

/**
 * Mounts the chat with one follow-up question in flight. Returns the deferred
 * that settles the question, plus the render's `unmount`.
 */
async function mountWithFollowUpInFlight() {
  const question = deferred<string>();
  vi.mocked(generateFollowUpQuestion).mockReturnValueOnce(question.promise);

  const view = renderChatInterface({ suppressInitialFollowUp: false });

  await act(async () => {});

  expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(true);
  return { question, unmount: view.unmount };
}

/**
 * Mounts the chat with two follow-up questions in flight, oldest first, and
 * returns both deferreds.
 */
async function mountWithTwoFollowUpsInFlight() {
  const earlierQuestion = deferred<string>();
  const newerQuestion = deferred<string>();
  vi.mocked(generateFollowUpQuestion)
    .mockReturnValueOnce(earlierQuestion.promise)
    .mockReturnValueOnce(newerQuestion.promise);

  renderChatInterface({ suppressInitialFollowUp: false });
  await act(async () => {});

  expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(true);
  return { earlierQuestion, newerQuestion };
}

/**
 * Mounts the chat with two follow-up questions in flight, then sends a message,
 * which orphans the older call. Returns both deferreds and the send promise.
 */
async function sendDuringTwoFollowUpsInFlight() {
  const { earlierQuestion, newerQuestion } =
    await mountWithTwoFollowUpsInFlight();

  let send: Promise<void> = Promise.resolve();
  await act(async () => {
    send = sendMessage("And how do I use it?");
  });
  return { earlierQuestion, newerQuestion, send };
}

/** Settles the newer question and waits for the send still running beside it. */
async function settleNewestQuestion(
  newerQuestion: ReturnType<typeof deferred<string>>,
  send: Promise<void>,
) {
  await act(async () => {
    newerQuestion.resolve("The newest question?");
    await send;
  });
}

/**
 * Unmounts the first chat inside `act`, then mounts the second one with no
 * `act` around the render. The caller sends the second chat's own message
 * right after, in its own `act`.
 */
async function remountChatMidGeneration(first: { unmount: () => void }) {
  await act(async () => {
    first.unmount();
  });

  renderChatInterface();
}

/** Settles the live answer and expects the response flag to clear with it. */
async function settleLiveAnswer(
  secondResponse: ReturnType<typeof deferred<string>>,
  secondSend: Promise<void>,
) {
  await act(async () => {
    secondResponse.resolve("The live answer.");
    await secondSend;
  });

  expect(getChatGenerationState().isGeneratingResponse).toBe(false);
}

/** Lets an earlier follow-up question land while the answer is still running. */
async function settleEarlierQuestionMidResponse(
  followUpQuestion: ReturnType<typeof deferred<string>>,
) {
  expect(getChatGenerationState().isGeneratingResponse).toBe(true);

  await act(async () => {
    followUpQuestion.resolve("An earlier question?");
  });

  expect(getChatGenerationState().isGeneratingResponse).toBe(true);
}

/** Checks the second mount's own generation started, and is not a stale flag. */
function expectLiveGenerationStarted(calls: number) {
  expect(getChatGenerationState().isGeneratingResponse).toBe(true);
  expect(generateChatResponse).toHaveBeenCalledTimes(calls);
}

function stubWakeLockApi() {
  const release = vi.fn(() => Promise.resolve());
  const request = vi.fn(() =>
    Promise.resolve({ released: false, release, addEventListener: vi.fn() }),
  );

  Object.defineProperty(navigator, "wakeLock", {
    value: { request },
    configurable: true,
  });

  return { request, release };
}

beforeEach(() => {
  updateChatGenerationState({
    isGeneratingResponse: false,
    isGeneratingFollowUpQuestion: false,
  });
  updateChatInput("");
  updateFollowUpQuestion("");
  updateSuppressNextFollowUp(false);
  messageListMessages = [];
  messageListIsGenerating = false;
  messageListFollowUpStartIndex = undefined;
  vi.mocked(generateChatResponse).mockResolvedValue("An answer.");
  vi.mocked(generateFollowUpQuestion).mockResolvedValue("A question?");
  vi.mocked(persistChatConversation).mockResolvedValue(undefined);
  currentSearchRunId = "run-1";
  vi.mocked(getCurrentSearchRunId).mockImplementation(() => currentSearchRunId);
  updateChatMessages([]);
});

afterEach(() => {
  Reflect.deleteProperty(navigator, "wakeLock");
  vi.resetAllMocks();
});

describe("ChatInterface generation state", () => {
  it("leaves the follow-up question flag off after sending during its generation", async () => {
    const { question: earlierQuestion } = await mountWithFollowUpInFlight();

    await act(async () => {
      await sendMessage("And how do I use it?");
    });

    expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(false);

    await act(async () => {
      earlierQuestion.resolve("An earlier question?");
    });
  });

  it("keeps the response flag on when an earlier follow-up question completes mid-response", async () => {
    const followUpQuestion = deferred<string>();
    vi.mocked(generateFollowUpQuestion).mockReturnValueOnce(
      followUpQuestion.promise,
    );
    const chatResponse = deferred<string>();
    vi.mocked(generateChatResponse).mockReturnValueOnce(chatResponse.promise);

    renderChatInterface({ suppressInitialFollowUp: false });

    await act(async () => {});

    expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(true);

    let send: Promise<void> = Promise.resolve();

    await act(async () => {
      send = sendMessage("And how do I use it?");
    });

    await settleEarlierQuestionMidResponse(followUpQuestion);

    await act(async () => {
      chatResponse.resolve("An answer.");
      await send;
    });
  });

  it("leaves a concurrent follow-up question flag alone when the response fails", async () => {
    const followUpQuestion = deferred<string>();
    vi.mocked(generateFollowUpQuestion).mockReturnValueOnce(
      followUpQuestion.promise,
    );
    vi.mocked(generateChatResponse).mockRejectedValueOnce(
      new Error("no model"),
    );

    renderChatInterface({ suppressInitialFollowUp: false });

    await act(async () => {});

    await act(async () => {
      await sendMessage("And how do I use it?");
    });

    expect(getChatGenerationState()).toEqual({
      isGeneratingResponse: false,
      isGeneratingFollowUpQuestion: true,
    });

    await act(async () => {
      followUpQuestion.resolve("An earlier question?");
    });
  });

  it("starts one generation when two sends land in the same task", async () => {
    renderChatInterface();

    await act(async () => {
      await Promise.all([
        sendMessage("And how do I use it?"),
        sendMessage("Does it work offline?"),
      ]);
    });

    expect(generateChatResponse).toHaveBeenCalledTimes(1);
  });

  it("accepts a send while the follow-up question is still being generated", async () => {
    const followUpQuestion = deferred<string>();
    vi.mocked(generateFollowUpQuestion).mockReturnValueOnce(
      followUpQuestion.promise,
    );
    // Streams the answer, so the placeholder row holds it the way it does in
    // the app and a leftover copy would be visible.
    vi.mocked(generateChatResponse).mockImplementationOnce(
      async (_messages, onUpdate) => {
        onUpdate("An answer.");
        return "An answer.";
      },
    );

    renderChatInterface();

    let send: Promise<void> = Promise.resolve();

    await act(async () => {
      send = sendMessage("And how do I use it?");
    });

    expect(getChatGenerationState()).toEqual({
      isGeneratingResponse: false,
      isGeneratingFollowUpQuestion: true,
    });

    // The input stays enabled through this window, so the guard has to accept
    // the send rather than refuse it silently, and the streamed placeholder
    // must not leave a second copy of the answer in the list.
    expect(messageListIsGenerating).toBe(false);
    expect(
      messageListMessages.filter((message) => message.content === "An answer."),
    ).toHaveLength(1);

    await act(async () => {
      await sendMessage("Does it work offline?");
    });

    expect(generateChatResponse).toHaveBeenCalledTimes(2);

    await act(async () => {
      followUpQuestion.resolve("An earlier question?");
      await send;
    });
  });

  it("regenerates without clobbering a follow-up question in flight", async () => {
    const followUpQuestion = deferred<string>();
    vi.mocked(generateFollowUpQuestion).mockReturnValueOnce(
      followUpQuestion.promise,
    );
    const regeneratedQuestion = deferred<string>();
    vi.mocked(generateFollowUpQuestion).mockReturnValueOnce(
      regeneratedQuestion.promise,
    );
    const chatResponse = deferred<string>();
    vi.mocked(generateChatResponse)
      .mockResolvedValueOnce("An answer.")
      .mockReturnValueOnce(chatResponse.promise);

    renderChatInterface();

    let send: Promise<void> = Promise.resolve();

    await act(async () => {
      send = sendMessage("And how do I use it?");
    });

    let regenerate: Promise<void> = Promise.resolve();

    await act(async () => {
      regenerate = regenerateResponse();
    });

    expect(getChatGenerationState().isGeneratingResponse).toBe(true);
    expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(true);

    await act(async () => {
      followUpQuestion.resolve("An earlier question?");
    });

    expect(getChatGenerationState().isGeneratingResponse).toBe(true);

    await act(async () => {
      chatResponse.resolve("A regenerated answer.");
    });

    // The regenerate hands the lock over the way the send does: it must not
    // stay in the response phase while its own question is still coming.
    expect(getChatGenerationState()).toEqual({
      isGeneratingResponse: false,
      isGeneratingFollowUpQuestion: true,
    });

    await act(async () => {
      regeneratedQuestion.resolve("A later question?");
      await Promise.all([send, regenerate]);
    });
  });

  it("keeps the follow-up question flag on until the newest call finishes", async () => {
    const { earlierQuestion, newerQuestion } =
      await mountWithTwoFollowUpsInFlight();

    let send: Promise<void> = Promise.resolve();
    await act(async () => {
      send = sendMessage("And how do I use it?");
    });

    // The orphaned call settles first. Its completion must write nothing.
    await act(async () => {
      earlierQuestion.resolve("The previous answer's question?");
    });

    expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(true);
    expect(getFollowUpQuestion()).toBe("");

    await settleNewestQuestion(newerQuestion, send);

    expect(getFollowUpQuestion()).toBe("The newest question?");
    expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(false);
  });

  it("leaves both generation flags off after unmounting mid-generation", async () => {
    const { question: heldQuestion, unmount } =
      await mountWithFollowUpInFlight();

    await act(async () => {
      unmount();
    });

    expect(getChatGenerationState()).toEqual({
      isGeneratingResponse: false,
      isGeneratingFollowUpQuestion: false,
    });

    // The orphaned call lands after the unmount; it must not write into what
    // is now the next mount's state.
    await act(async () => {
      heldQuestion.resolve("A question nobody asked for?");
    });

    expect(getChatGenerationState()).toEqual({
      isGeneratingResponse: false,
      isGeneratingFollowUpQuestion: false,
    });
    expect(getFollowUpQuestion()).toBe("");
  });

  it("leaves an in-flight call valid when a later one returns early", async () => {
    const heldQuestion = deferred<string>();
    vi.mocked(generateFollowUpQuestion).mockReturnValueOnce(
      heldQuestion.promise,
    );
    // An empty answer makes the send's own follow-up call return at the
    // `!currentResponse` guard, without ever reaching the request.
    vi.mocked(generateChatResponse).mockResolvedValueOnce("");

    renderChatInterface({ suppressInitialFollowUp: false });
    await act(async () => {});

    expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(true);

    await act(async () => {
      await sendMessage("And how do I use it?");
    });

    expect(generateFollowUpQuestion).toHaveBeenCalledTimes(1);

    await act(async () => {
      heldQuestion.resolve("The original question?");
    });

    // The early return bumped nothing, so the in-flight call is still the
    // current one and clears the flag. Bumping before the guards would have
    // orphaned it and left the flag, and the wake lock, held until unmount.
    expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(false);
  });

  it("blanks nothing when an orphaned call rejects after a newer one started", async () => {
    const { earlierQuestion, newerQuestion, send } =
      await sendDuringTwoFollowUpsInFlight();

    // The orphaned call fails. Its catch must not blank the newer one's work.
    await act(async () => {
      earlierQuestion.reject(new Error("no model"));
    });

    expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(true);

    await settleNewestQuestion(newerQuestion, send);

    expect(getFollowUpQuestion()).toBe("The newest question?");
    expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(false);
  });

  it("aborts the chat answer when the chat unmounts", async () => {
    let signal: AbortSignal | undefined;
    vi.mocked(generateChatResponse).mockImplementationOnce(
      (_messages, _onUpdate, chatSignal) => {
        signal = chatSignal;
        return new Promise((_resolve, reject) => {
          chatSignal?.addEventListener("abort", () =>
            reject(new Error("Chat generation interrupted")),
          );
        });
      },
    );

    const { unmount } = renderChatInterface();

    let send: Promise<void> = Promise.resolve();
    await act(async () => {
      send = sendMessage("And how do I use it?");
    });

    expect(signal?.aborted).toBe(false);

    await act(async () => {
      unmount();
      await send;
    });

    expect(signal?.aborted).toBe(true);
    // The question is kept, so a restore shows it and a regenerate can
    // replace the interrupted answer.
    expect(persistChatConversation).toHaveBeenLastCalledWith("run-1", [
      { role: "user", content: "And how do I use it?" },
      { role: "assistant", content: "The answer was interrupted." },
    ]);
  });

  it("starts no follow-up question for a send that settles after unmount", async () => {
    const chatResponse = deferred<string>();
    vi.mocked(generateChatResponse).mockReturnValueOnce(chatResponse.promise);

    const { unmount } = renderChatInterface();

    let send: Promise<void> = Promise.resolve();
    await act(async () => {
      send = sendMessage("And how do I use it?");
    });

    await act(async () => {
      unmount();
    });

    // The send closure runs to the end regardless, and asks for a question the
    // dead instance's token would have accepted.
    await act(async () => {
      chatResponse.resolve("An answer.");
      await send;
    });

    expect(generateFollowUpQuestion).not.toHaveBeenCalled();
    expect(getFollowUpQuestion()).toBe("");
    expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(false);
  });

  it("leaves the next mount's response flag alone when an orphaned send settles", async () => {
    const firstResponse = deferred<string>();
    const secondResponse = deferred<string>();
    vi.mocked(generateChatResponse)
      .mockReturnValueOnce(firstResponse.promise)
      .mockReturnValueOnce(secondResponse.promise);

    const first = renderChatInterface();

    let firstSend: Promise<void> = Promise.resolve();
    await act(async () => {
      firstSend = sendMessage("And how do I use it?");
    });

    await remountChatMidGeneration(first);

    let secondSend: Promise<void> = Promise.resolve();
    await act(async () => {
      secondSend = sendMessage("Does it work offline?");
    });

    expectLiveGenerationStarted(2);

    // The orphan's `finally` must not clear the live generation's flag, which
    // would drop the spinner and let a third send start alongside it.
    await act(async () => {
      firstResponse.resolve("The orphaned answer.");
      await firstSend;
    });

    expect(getChatGenerationState().isGeneratingResponse).toBe(true);

    await settleLiveAnswer(secondResponse, secondSend);
  });

  it("leaves the next mount's response flag alone when an orphaned regenerate settles", async () => {
    const firstResponse = deferred<string>();
    const secondResponse = deferred<string>();
    vi.mocked(generateChatResponse)
      .mockResolvedValueOnce("An answer.")
      .mockReturnValueOnce(firstResponse.promise)
      .mockReturnValueOnce(secondResponse.promise);

    const first = renderChatInterface();

    await act(async () => {
      await sendMessage("And how do I use it?");
    });

    let firstRegenerate: Promise<void> = Promise.resolve();
    await act(async () => {
      firstRegenerate = regenerateResponse();
    });

    await remountChatMidGeneration(first);

    let secondSend: Promise<void> = Promise.resolve();
    await act(async () => {
      secondSend = sendMessage("Does it work offline?");
    });

    expectLiveGenerationStarted(3);

    await act(async () => {
      firstResponse.resolve("The orphaned regeneration.");
      await firstRegenerate;
    });

    expect(getChatGenerationState().isGeneratingResponse).toBe(true);

    await settleLiveAnswer(secondResponse, secondSend);
  });

  it("starts one re-generation when two regenerates land in the same task", async () => {
    renderChatInterface();

    await act(async () => {
      await sendMessage("And how do I use it?");
    });

    await act(async () => {
      await Promise.all([regenerateResponse(), regenerateResponse()]);
    });

    expect(generateChatResponse).toHaveBeenCalledTimes(2);
  });

  it("keeps the response flag on when a follow-up question fails mid-response", async () => {
    const earlierQuestion = deferred<string>();
    vi.mocked(generateFollowUpQuestion).mockReturnValueOnce(
      earlierQuestion.promise,
    );
    const chatResponse = deferred<string>();
    vi.mocked(generateChatResponse).mockReturnValueOnce(chatResponse.promise);

    renderChatInterface({ suppressInitialFollowUp: false });

    await act(async () => {});

    let send: Promise<void> = Promise.resolve();

    await act(async () => {
      send = sendMessage("And how do I use it?");
    });

    await act(async () => {
      earlierQuestion.reject(new Error("no model"));
    });

    expect(getChatGenerationState()).toEqual({
      isGeneratingResponse: true,
      isGeneratingFollowUpQuestion: false,
    });

    await act(async () => {
      chatResponse.resolve("An answer.");
      await send;
    });
  });

  it("holds the screen wake lock from the response through the follow-up question", async () => {
    const { request, release } = stubWakeLockApi();
    const followUpQuestion = deferred<string>();
    vi.mocked(generateFollowUpQuestion).mockReturnValueOnce(
      followUpQuestion.promise,
    );

    renderChatInterface();

    let send: Promise<void> = Promise.resolve();

    await act(async () => {
      send = sendMessage("And how do I use it?");
    });

    expect(request).toHaveBeenCalledExactlyOnceWith("screen");
    expect(release).not.toHaveBeenCalled();

    await act(async () => {
      followUpQuestion.resolve("An earlier question?");
      await send;
    });

    expect(release).toHaveBeenCalled();
  });

  it("logs the failure when the initial follow-up question generation fails", async () => {
    vi.mocked(generateFollowUpQuestion).mockRejectedValueOnce(
      new Error("boom"),
    );

    renderChatInterface({ suppressInitialFollowUp: false });

    await act(async () => {});

    expect(addLogEntry).toHaveBeenCalledWith(
      expect.stringContaining("Error generating follow-up question"),
    );
    expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(false);
  });

  it("keeps the answer and the follow-up question when persisting fails", async () => {
    vi.mocked(persistChatConversation).mockRejectedValueOnce(
      new Error("disk full"),
    );

    renderChatInterface();

    await act(async () => {
      await sendMessage("And how do I use it?");
    });

    expect(
      messageListMessages.filter((message) => message.content === "An answer."),
    ).toHaveLength(1);
    expect(
      messageListMessages.some((message) =>
        message.content.includes("Sorry, I encountered an error"),
      ),
    ).toBe(false);
    await vi.waitFor(() =>
      expect(addLogEntry).toHaveBeenCalledWith(
        expect.stringContaining("Error persisting chat messages"),
      ),
    );
    expect(generateFollowUpQuestion).toHaveBeenCalled();
  });

  it("clears suppressNextFollowUp after skipping the restored answer's follow-up so later sends generate one", async () => {
    updateSuppressNextFollowUp(true);

    renderChatInterface({ suppressInitialFollowUp: false });

    await act(async () => {});

    expect(generateFollowUpQuestion).not.toHaveBeenCalled();
    expect(getSuppressNextFollowUp()).toBe(false);

    await act(async () => {
      await sendMessage("Tell me more about wake locks");
    });

    expect(generateFollowUpQuestion).toHaveBeenCalledTimes(1);
    expect(getFollowUpQuestion()).toBe("A question?");
  });

  it("drops an in-flight follow-up question when a restore suppresses follow-ups", async () => {
    const inFlightQuestion = deferred<string>();
    vi.mocked(generateFollowUpQuestion).mockReturnValueOnce(
      inFlightQuestion.promise,
    );

    renderChatInterface({ suppressInitialFollowUp: false });

    await act(async () => {});

    expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(true);

    await act(async () => {
      updateSuppressNextFollowUp(true);
    });

    expect(getSuppressNextFollowUp()).toBe(false);
    expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(false);
    expect(getFollowUpQuestion()).toBe("");

    await act(async () => {
      inFlightQuestion.resolve("Question from the previous search?");
    });

    expect(getFollowUpQuestion()).toBe("");
    expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(false);
  });
});

describe("ChatInterface follow-up start", () => {
  const followUps: ChatMessage[] = [
    { role: "user", content: "Q1" },
    { role: "assistant", content: "A1" },
  ];

  function renderWithoutMainAnswer() {
    return render(
      <MantineProvider>
        <ChatInterface
          initialQuery={initialQuery}
          initialResponse=""
          initialMessages={followUps}
          suppressInitialFollowUp
        />
      </MantineProvider>,
    );
  }

  it("starts the follow-ups after the main question and answer", () => {
    renderChatInterface();

    expect(messageListMessages).toEqual([
      { role: "user", content: initialQuery },
      { role: "assistant", content: initialResponse },
    ]);
    expect(messageListFollowUpStartIndex).toBe(2);
  });

  it("starts the follow-ups at the top when the main answer is empty", () => {
    renderWithoutMainAnswer();

    expect(messageListMessages).toEqual(followUps);
    expect(messageListFollowUpStartIndex).toBe(0);
  });

  it("regenerates the first follow-up when the main answer is empty", async () => {
    renderWithoutMainAnswer();
    vi.mocked(generateChatResponse).mockResolvedValueOnce("A1 again");

    await act(async () => {
      await regenerateResponse();
    });

    expect(generateChatResponse).toHaveBeenCalledTimes(1);
    expect(vi.mocked(generateChatResponse).mock.calls[0][0]).toEqual([
      followUps[0],
    ]);
    expect(messageListMessages.at(-1)).toEqual({
      role: "assistant",
      content: "A1 again",
    });
  });
});

describe("ChatInterface failed regeneration", () => {
  const nextQuestion = "And how do I use it?";

  async function sendThenFailRegenerate() {
    vi.mocked(generateChatResponse)
      .mockResolvedValueOnce("An answer.")
      .mockRejectedValueOnce(new Error("model crashed"));

    await act(async () => {
      await sendMessage(nextQuestion);
    });
    await act(async () => {
      await regenerateResponse();
    });
  }

  it("keeps the previous answer so it can be regenerated again", async () => {
    renderChatInterface();
    await sendThenFailRegenerate();

    expect(messageListMessages.at(-1)).toEqual({
      role: "assistant",
      content: "An answer.",
    });
    expect(messageListMessages).toHaveLength(4);
    expect(getChatGenerationState().isGeneratingResponse).toBe(false);

    vi.mocked(generateChatResponse).mockResolvedValueOnce("A second try.");
    await act(async () => {
      await regenerateResponse();
    });

    expect(generateChatResponse).toHaveBeenCalledTimes(3);
    expect(messageListMessages.at(-1)?.content).toBe("A second try.");
  });

  it("shows one red notification and still logs the error", async () => {
    renderChatInterface();
    await sendThenFailRegenerate();

    expect(notifications.show).toHaveBeenCalledTimes(1);
    expect(notifications.show).toHaveBeenCalledWith(
      expect.objectContaining({
        color: "red",
        message:
          "Couldn't re-generate the response. The previous answer has been kept.",
      }),
    );
    expect(addLogEntry).toHaveBeenCalledWith(
      expect.stringContaining("Error re-generating response"),
    );
  });

  it("brings back the follow-up question that was showing", async () => {
    renderChatInterface();
    await sendThenFailRegenerate();

    expect(getFollowUpQuestion()).toBe("A question?");
  });

  it("writes nothing and shows no notification after unmounting", async () => {
    const response = deferred<string>();
    vi.mocked(generateChatResponse)
      .mockResolvedValueOnce("An answer.")
      .mockReturnValueOnce(response.promise);

    const { unmount } = renderChatInterface();
    await act(async () => {
      await sendMessage(nextQuestion);
    });

    let regenerate: Promise<void> = Promise.resolve();
    await act(async () => {
      regenerate = regenerateResponse();
    });
    await act(async () => {
      unmount();
    });
    updateFollowUpQuestion("A question from the next chat?");

    await act(async () => {
      response.reject(new Error("model crashed"));
      await regenerate;
    });

    expect(notifications.show).not.toHaveBeenCalled();
    expect(getFollowUpQuestion()).toBe("A question from the next chat?");
  });

  it("shows no notification when the regeneration succeeds", async () => {
    vi.mocked(generateChatResponse)
      .mockResolvedValueOnce("An answer.")
      .mockResolvedValueOnce("A regenerated answer.");

    renderChatInterface();
    await act(async () => {
      await sendMessage(nextQuestion);
    });
    await act(async () => {
      await regenerateResponse();
    });

    expect(messageListMessages.at(-1)?.content).toBe("A regenerated answer.");
    expect(notifications.show).not.toHaveBeenCalled();
  });
});

describe("ChatInterface previous follow-up questions", () => {
  it("does not record an empty follow-up question", async () => {
    vi.mocked(generateFollowUpQuestion)
      .mockResolvedValueOnce("Is it supported in Safari?")
      .mockResolvedValueOnce("")
      .mockResolvedValueOnce("Does it drain the battery?");

    renderChatInterface({ suppressInitialFollowUp: false });
    await act(async () => {});

    await act(async () => {
      await sendMessage("And how do I use it?");
    });
    await act(async () => {
      await sendMessage("Does it work in the background?");
    });

    expect(generateFollowUpQuestion).toHaveBeenCalledTimes(3);
    expect(
      vi.mocked(generateFollowUpQuestion).mock.calls[2][0].previousQuestions,
    ).toEqual(["Is it supported in Safari?"]);
  });
});

describe("ChatInterface chat storage", () => {
  const followUps = (...pairs: [string, string][]): ChatMessage[] =>
    pairs.flatMap(([question, answer]) => [
      { role: "user" as const, content: question },
      { role: "assistant" as const, content: answer },
    ]);

  /** What the last write stored for a conversation. */
  function stored(conversationId = "run-1") {
    const calls = vi
      .mocked(persistChatConversation)
      .mock.calls.filter(([id]) => id === conversationId);
    return calls.at(-1)?.[1];
  }

  it("stores the regenerated answer in place of the one it replaced", async () => {
    vi.mocked(generateChatResponse)
      .mockResolvedValueOnce("First answer.")
      .mockResolvedValueOnce("Regenerated answer.");
    renderChatInterface();

    await act(async () => {
      await sendMessage("How do I use it?");
    });
    await act(async () => {
      await regenerateResponse();
    });

    expect(stored()).toEqual(
      followUps(["How do I use it?", "Regenerated answer."]),
    );
  });

  it("stores only the corrected pair after an edit and a resend", async () => {
    vi.mocked(generateChatResponse)
      .mockResolvedValueOnce("Answer to the typo.")
      .mockResolvedValueOnce("Answer to the fix.");
    renderChatInterface();

    await act(async () => {
      await sendMessage("How do I use iy?");
    });
    act(() => editMessage(2));
    await act(async () => {
      await sendMessage("How do I use it?");
    });

    expect(stored()).toEqual(
      followUps(["How do I use it?", "Answer to the fix."]),
    );
  });

  it("matches the screen after an edit that is never resent", async () => {
    renderChatInterface();

    await act(async () => {
      await sendMessage("How do I use it?");
    });
    act(() => editMessage(2));

    expect(stored()).toEqual([]);
    expect(messageListMessages).toHaveLength(2);
  });

  it("stores the question of a failed send, then the answer that regenerates it", async () => {
    vi.mocked(generateChatResponse)
      .mockRejectedValueOnce(new Error("offline"))
      .mockResolvedValueOnce("A good answer.");
    renderChatInterface();

    await act(async () => {
      await sendMessage("How do I use it?");
    });
    expect(stored()).toEqual(
      followUps([
        "How do I use it?",
        "Sorry, I encountered an error while generating a response.",
      ]),
    );

    await act(async () => {
      await regenerateResponse();
    });

    expect(stored()).toEqual(followUps(["How do I use it?", "A good answer."]));
  });

  it("saves an answer under its own search when a new search starts meanwhile", async () => {
    const answer = deferred<string>();
    vi.mocked(generateChatResponse).mockReturnValueOnce(answer.promise);
    renderChatInterface();

    let send: Promise<void> = Promise.resolve();
    await act(async () => {
      send = sendMessage("How do I use it?");
    });
    currentSearchRunId = "run-2";
    await act(async () => {
      answer.resolve("A late answer.");
      await send;
    });

    expect(stored("run-1")).toEqual(
      followUps(["How do I use it?", "A late answer."]),
    );
    expect(stored("run-2")).toBeUndefined();
    // Neither the screen nor the new search's copy gets the old search's turns.
    expect(messageListMessages.at(-1)?.content).toBe("How do I use it?");
    expect(getChatMessages()).toEqual([]);
  });

  it("keeps a late answer out of the chat that replaced it on the same search", async () => {
    const answer = deferred<string>();
    vi.mocked(generateChatResponse).mockReturnValueOnce(answer.promise);
    const view = renderChatInterface();

    let send: Promise<void> = Promise.resolve();
    await act(async () => {
      send = sendMessage("How do I use it?");
    });
    // Regenerating the main answer starts a new attempt on the same run (as
    // startTextSearch records it), unmounts the chat and clears its copy.
    recordSearchAttempt("run-1", (getLatestSearchAttempt("run-1") ?? 0) + 1);
    view.unmount();
    updateChatMessages([]);
    await act(async () => {
      answer.resolve("A late answer.");
      await send;
    });

    expect(getChatMessages()).toEqual([]);
  });

  /**
   * Sends a follow-up whose answer only ends when the chat aborts it, and
   * returns a function that unmounts the chat and waits for that abort.
   */
  async function sendFollowUpUntilUnmount() {
    vi.mocked(generateChatResponse).mockImplementationOnce(
      (_messages, _onUpdate, chatSignal) =>
        new Promise((_resolve, reject) => {
          chatSignal?.addEventListener("abort", () =>
            reject(new Error("Chat generation interrupted")),
          );
        }),
    );
    const view = renderChatInterface();
    let send: Promise<void> = Promise.resolve();
    await act(async () => {
      send = sendMessage("How do I use it?");
    });
    return async () => {
      await act(async () => {
        view.unmount();
        await send;
      });
    };
  }

  it("keeps an interrupted follow-up when the AI response is turned off and on", async () => {
    const unmountChat = await sendFollowUpUntilUnmount();
    vi.mocked(generateChatResponse).mockResolvedValueOnce("Next answer.");
    // Turning "AI response" off unmounts the chat on the same run and
    // attempt, which aborts the follow-up into its "interrupted" commit.
    await unmountChat();
    const interrupted = [
      { role: "user", content: "How do I use it?" },
      { role: "assistant", content: "The answer was interrupted." },
    ];
    expect(getChatMessages()).toEqual(interrupted);

    // Turning it back on mounts a new chat from that copy.
    render(
      <MantineProvider>
        <ChatInterface
          initialQuery={initialQuery}
          initialResponse={initialResponse}
          initialMessages={getChatMessages()}
          suppressInitialFollowUp
        />
      </MantineProvider>,
    );
    expect(messageListMessages.slice(2)).toEqual(interrupted);

    await act(async () => {
      await sendMessage("And then?");
    });
    expect(persistChatConversation).toHaveBeenLastCalledWith("run-1", [
      ...interrupted,
      { role: "user", content: "And then?" },
      { role: "assistant", content: "Next answer." },
    ]);
  });

  it("commits the interrupted turn at unmount even while the follow-up search runs", async () => {
    vi.mocked(runFollowUpSearch).mockReturnValueOnce(new Promise(() => {}));
    vi.mocked(generateChatResponse).mockImplementationOnce(
      async (_messages, _onUpdate, chatSignal) => {
        if (chatSignal?.aborted) throw new Error("Chat generation interrupted");
        return "An answer.";
      },
    );
    const view = renderChatInterface();
    let send: Promise<void> = Promise.resolve();
    await act(async () => {
      send = sendMessage("How do I use it?");
    });

    await act(async () => {
      view.unmount();
      await send;
    });

    expect(getChatMessages()).toEqual([
      { role: "user", content: "How do I use it?" },
      { role: "assistant", content: "The answer was interrupted." },
    ]);
  });

  it("stores nothing from a follow-up that started before the main answer was regenerated", async () => {
    const unmountChat = await sendFollowUpUntilUnmount();
    vi.mocked(persistChatConversation).mockClear();
    // Regenerating starts a new attempt on the same run and unmounts the chat,
    // which aborts the follow-up into its "interrupted" commit.
    recordSearchAttempt("run-1", (getLatestSearchAttempt("run-1") ?? 0) + 1);
    await unmountChat();

    expect(persistChatConversation).not.toHaveBeenCalled();
  });

  it("stores a follow-up sent after the main answer was regenerated", async () => {
    recordSearchAttempt("run-1", (getLatestSearchAttempt("run-1") ?? 0) + 1);
    vi.mocked(generateChatResponse).mockResolvedValueOnce("A new answer.");
    renderChatInterface();

    await act(async () => {
      await sendMessage("And now?");
    });

    expect(persistChatConversation).toHaveBeenLastCalledWith("run-1", [
      { role: "user", content: "And now?" },
      { role: "assistant", content: "A new answer." },
    ]);
  });

  it("keeps every turn on a remount without writing anything", async () => {
    vi.mocked(generateChatResponse)
      .mockResolvedValueOnce("One.")
      .mockResolvedValueOnce("Two.");
    const first = renderChatInterface();
    await act(async () => {
      await sendMessage("Q1");
    });
    await act(async () => {
      await sendMessage("Q2");
    });
    first.unmount();
    const writes = vi.mocked(persistChatConversation).mock.calls.length;

    render(
      <MantineProvider>
        <ChatInterface
          initialQuery={initialQuery}
          initialResponse={initialResponse}
          initialMessages={getChatMessages()}
          suppressInitialFollowUp
        />
      </MantineProvider>,
    );

    expect(messageListMessages.map((m) => m.content)).toEqual([
      initialQuery,
      initialResponse,
      "Q1",
      "One.",
      "Q2",
      "Two.",
    ]);
    expect(persistChatConversation).toHaveBeenCalledTimes(writes);
  });
});