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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
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { SessionSummaryService } from './sessionSummaryService.js';
import type { BaseLlmClient } from '../core/baseLlmClient.js';
import type { MessageRecord } from './chatRecordingService.js';
import type { GenerateContentResponse } from '@google/genai';

describe('SessionSummaryService', () => {
  let service: SessionSummaryService;
  let mockBaseLlmClient: BaseLlmClient;
  let mockGenerateContent: ReturnType<typeof vi.fn>;

  beforeEach(() => {
    vi.clearAllMocks();
    vi.useFakeTimers();

    // Setup mock BaseLlmClient with generateContent
    mockGenerateContent = vi.fn().mockResolvedValue({
      candidates: [
        {
          content: {
            parts: [{ text: 'Add dark mode to the app' }],
          },
        },
      ],
    } as unknown as GenerateContentResponse);

    mockBaseLlmClient = {
      generateContent: mockGenerateContent,
    } as unknown as BaseLlmClient;

    service = new SessionSummaryService(mockBaseLlmClient);
  });

  afterEach(() => {
    vi.useRealTimers();
    vi.restoreAllMocks();
  });

  describe('Basic Functionality', () => {
    it('should generate summary for valid conversation', async () => {
      const messages: MessageRecord[] = [
        {
          id: '1',
          timestamp: '2025-12-03T00:00:00Z',
          type: 'user',
          content: [{ text: 'How do I add dark mode to my app?' }],
        },
        {
          id: '2',
          timestamp: '2025-12-03T00:01:00Z',
          type: 'gemini',
          content: [
            {
              text: 'To add dark mode, you need to create a theme provider and toggle state...',
            },
          ],
        },
      ];

      const summary = await service.generateSummary({ messages });

      expect(summary).toBe('Add dark mode to the app');
      expect(mockGenerateContent).toHaveBeenCalledTimes(1);
      expect(mockGenerateContent).toHaveBeenCalledWith(
        expect.objectContaining({
          modelConfigKey: { model: 'summarizer-default' },
          contents: expect.arrayContaining([
            expect.objectContaining({
              role: 'user',
              parts: expect.arrayContaining([
                expect.objectContaining({
                  text: expect.stringContaining('User: How do I add dark mode'),
                }),
              ]),
            }),
          ]),
          promptId: 'session-summary-generation',
        }),
      );
    });

    it('should return null for empty messages array', async () => {
      const summary = await service.generateSummary({ messages: [] });

      expect(summary).toBeNull();
      expect(mockGenerateContent).not.toHaveBeenCalled();
    });

    it('should return null when all messages have empty content', async () => {
      const messages: MessageRecord[] = [
        {
          id: '1',
          timestamp: '2025-12-03T00:00:00Z',
          type: 'user',
          content: [{ text: '   ' }],
        },
        {
          id: '2',
          timestamp: '2025-12-03T00:01:00Z',
          type: 'gemini',
          content: [{ text: '' }],
        },
      ];

      const summary = await service.generateSummary({ messages });

      expect(summary).toBeNull();
      expect(mockGenerateContent).not.toHaveBeenCalled();
    });

    it('should handle maxMessages limit correctly', async () => {
      const messages: MessageRecord[] = Array.from({ length: 30 }, (_, i) => ({
        id: `${i}`,
        timestamp: '2025-12-03T00:00:00Z',
        type: i % 2 === 0 ? ('user' as const) : ('gemini' as const),
        content: [{ text: `Message ${i}` }],
      }));

      await service.generateSummary({ messages, maxMessages: 10 });

      expect(mockGenerateContent).toHaveBeenCalledTimes(1);
      const callArgs = mockGenerateContent.mock.calls[0][0];
      const promptText = callArgs.contents[0].parts[0].text;

      // Count how many messages appear in the prompt (should be 10)
      const messageCount = (promptText.match(/Message \d+/g) || []).length;
      expect(messageCount).toBe(10);
    });
  });

  describe('Message Type Filtering', () => {
    it('should include only user and gemini messages', async () => {
      const messages: MessageRecord[] = [
        {
          id: '1',
          timestamp: '2025-12-03T00:00:00Z',
          type: 'user',
          content: [{ text: 'User message' }],
        },
        {
          id: '2',
          timestamp: '2025-12-03T00:01:00Z',
          type: 'gemini',
          content: [{ text: 'Gemini response' }],
        },
      ];

      await service.generateSummary({ messages });

      expect(mockGenerateContent).toHaveBeenCalledTimes(1);
      const callArgs = mockGenerateContent.mock.calls[0][0];
      const promptText = callArgs.contents[0].parts[0].text;

      expect(promptText).toContain('User: User message');
      expect(promptText).toContain('Assistant: Gemini response');
    });

    it('should exclude info messages', async () => {
      const messages: MessageRecord[] = [
        {
          id: '1',
          timestamp: '2025-12-03T00:00:00Z',
          type: 'user',
          content: [{ text: 'User message' }],
        },
        {
          id: '2',
          timestamp: '2025-12-03T00:01:00Z',
          type: 'info',
          content: [{ text: 'Info message should be excluded' }],
        },
        {
          id: '3',
          timestamp: '2025-12-03T00:02:00Z',
          type: 'gemini',
          content: [{ text: 'Gemini response' }],
        },
      ];

      await service.generateSummary({ messages });

      expect(mockGenerateContent).toHaveBeenCalledTimes(1);
      const callArgs = mockGenerateContent.mock.calls[0][0];
      const promptText = callArgs.contents[0].parts[0].text;

      expect(promptText).toContain('User: User message');
      expect(promptText).toContain('Assistant: Gemini response');
      expect(promptText).not.toContain('Info message');
    });

    it('should exclude error messages', async () => {
      const messages: MessageRecord[] = [
        {
          id: '1',
          timestamp: '2025-12-03T00:00:00Z',
          type: 'user',
          content: [{ text: 'User message' }],
        },
        {
          id: '2',
          timestamp: '2025-12-03T00:01:00Z',
          type: 'error',
          content: [{ text: 'Error: something went wrong' }],
        },
        {
          id: '3',
          timestamp: '2025-12-03T00:02:00Z',
          type: 'gemini',
          content: [{ text: 'Gemini response' }],
        },
      ];

      await service.generateSummary({ messages });

      expect(mockGenerateContent).toHaveBeenCalledTimes(1);
      const callArgs = mockGenerateContent.mock.calls[0][0];
      const promptText = callArgs.contents[0].parts[0].text;

      expect(promptText).not.toContain('Error: something went wrong');
    });

    it('should exclude warning messages', async () => {
      const messages: MessageRecord[] = [
        {
          id: '1',
          timestamp: '2025-12-03T00:00:00Z',
          type: 'user',
          content: [{ text: 'User message' }],
        },
        {
          id: '2',
          timestamp: '2025-12-03T00:01:00Z',
          type: 'warning',
          content: [{ text: 'Warning: deprecated API' }],
        },
        {
          id: '3',
          timestamp: '2025-12-03T00:02:00Z',
          type: 'gemini',
          content: [{ text: 'Gemini response' }],
        },
      ];

      await service.generateSummary({ messages });

      expect(mockGenerateContent).toHaveBeenCalledTimes(1);
      const callArgs = mockGenerateContent.mock.calls[0][0];
      const promptText = callArgs.contents[0].parts[0].text;

      expect(promptText).not.toContain('Warning: deprecated API');
    });

    it('should handle mixed message types correctly', async () => {
      const messages: MessageRecord[] = [
        {
          id: '1',
          timestamp: '2025-12-03T00:00:00Z',
          type: 'info',
          content: [{ text: 'System info' }],
        },
        {
          id: '2',
          timestamp: '2025-12-03T00:01:00Z',
          type: 'user',
          content: [{ text: 'User question' }],
        },
        {
          id: '3',
          timestamp: '2025-12-03T00:02:00Z',
          type: 'error',
          content: [{ text: 'Error occurred' }],
        },
        {
          id: '4',
          timestamp: '2025-12-03T00:03:00Z',
          type: 'gemini',
          content: [{ text: 'Gemini answer' }],
        },
        {
          id: '5',
          timestamp: '2025-12-03T00:04:00Z',
          type: 'warning',
          content: [{ text: 'Warning message' }],
        },
      ];

      await service.generateSummary({ messages });

      expect(mockGenerateContent).toHaveBeenCalledTimes(1);
      const callArgs = mockGenerateContent.mock.calls[0][0];
      const promptText = callArgs.contents[0].parts[0].text;

      expect(promptText).toContain('User: User question');
      expect(promptText).toContain('Assistant: Gemini answer');
      expect(promptText).not.toContain('System info');
      expect(promptText).not.toContain('Error occurred');
      expect(promptText).not.toContain('Warning message');
    });

    it('should return null when only system messages present', async () => {
      const messages: MessageRecord[] = [
        {
          id: '1',
          timestamp: '2025-12-03T00:00:00Z',
          type: 'info',
          content: [{ text: 'Info message' }],
        },
        {
          id: '2',
          timestamp: '2025-12-03T00:01:00Z',
          type: 'error',
          content: [{ text: 'Error message' }],
        },
        {
          id: '3',
          timestamp: '2025-12-03T00:02:00Z',
          type: 'warning',
          content: [{ text: 'Warning message' }],
        },
      ];

      const summary = await service.generateSummary({ messages });

      expect(summary).toBeNull();
      expect(mockGenerateContent).not.toHaveBeenCalled();
    });
  });

  describe('Timeout and Abort Handling', () => {
    it('should timeout after specified duration', async () => {
      // Mock implementation that respects abort signal
      mockGenerateContent.mockImplementation(
        ({ abortSignal }) =>
          new Promise((resolve, reject) => {
            const timeoutId = setTimeout(
              () =>
                resolve({
                  candidates: [{ content: { parts: [{ text: 'Summary' }] } }],
                }),
              10000,
            );

            abortSignal?.addEventListener(
              'abort',
              () => {
                clearTimeout(timeoutId);
                const abortError = new Error('This operation was aborted');
                abortError.name = 'AbortError';
                reject(abortError);
              },
              { once: true },
            );
          }),
      );

      const messages: MessageRecord[] = [
        {
          id: '1',
          timestamp: '2025-12-03T00:00:00Z',
          type: 'user',
          content: [{ text: 'Hello' }],
        },
      ];

      const summaryPromise = service.generateSummary({
        messages,
        timeout: 100,
      });

      // Advance timers past the timeout to trigger abort
      await vi.advanceTimersByTimeAsync(100);

      const summary = await summaryPromise;

      expect(summary).toBeNull();
    });

    it('should detect AbortError by name only (not message)', async () => {
      const abortError = new Error('Different abort message');
      abortError.name = 'AbortError';
      mockGenerateContent.mockRejectedValue(abortError);

      const messages: MessageRecord[] = [
        {
          id: '1',
          timestamp: '2025-12-03T00:00:00Z',
          type: 'user',
          content: [{ text: 'Hello' }],
        },
      ];

      const summary = await service.generateSummary({ messages });

      expect(summary).toBeNull();
      // Should handle it gracefully without throwing
    });

    it('should handle API errors gracefully', async () => {
      mockGenerateContent.mockRejectedValue(new Error('API Error'));

      const messages: MessageRecord[] = [
        {
          id: '1',
          timestamp: '2025-12-03T00:00:00Z',
          type: 'user',
          content: [{ text: 'Hello' }],
        },
      ];

      const summary = await service.generateSummary({ messages });

      expect(summary).toBeNull();
    });

    it('should handle empty response from LLM', async () => {
      mockGenerateContent.mockResolvedValue({
        candidates: [
          {
            content: {
              parts: [{ text: '' }],
            },
          },
        ],
      } as unknown as GenerateContentResponse);

      const messages: MessageRecord[] = [
        {
          id: '1',
          timestamp: '2025-12-03T00:00:00Z',
          type: 'user',
          content: [{ text: 'Hello' }],
        },
      ];

      const summary = await service.generateSummary({ messages });

      expect(summary).toBeNull();
    });
  });

  describe('Text Processing', () => {
    it('should clean newlines and extra whitespace', async () => {
      mockGenerateContent.mockResolvedValue({
        candidates: [
          {
            content: {
              parts: [
                {
                  text: 'Add dark mode\n\nto   the   app',
                },
              ],
            },
          },
        ],
      } as unknown as GenerateContentResponse);

      const messages: MessageRecord[] = [
        {
          id: '1',
          timestamp: '2025-12-03T00:00:00Z',
          type: 'user',
          content: [{ text: 'Hello' }],
        },
      ];

      const summary = await service.generateSummary({ messages });

      expect(summary).toBe('Add dark mode to the app');
    });

    it('should remove surrounding quotes', async () => {
      mockGenerateContent.mockResolvedValue({
        candidates: [
          {
            content: {
              parts: [{ text: '"Add dark mode to the app"' }],
            },
          },
        ],
      } as unknown as GenerateContentResponse);

      const messages: MessageRecord[] = [
        {
          id: '1',
          timestamp: '2025-12-03T00:00:00Z',
          type: 'user',
          content: [{ text: 'Hello' }],
        },
      ];

      const summary = await service.generateSummary({ messages });

      expect(summary).toBe('Add dark mode to the app');
    });

    it('should handle messages longer than 500 chars', async () => {
      const longMessage = 'a'.repeat(1000);
      const messages: MessageRecord[] = [
        {
          id: '1',
          timestamp: '2025-12-03T00:00:00Z',
          type: 'user',
          content: [{ text: longMessage }],
        },
        {
          id: '2',
          timestamp: '2025-12-03T00:01:00Z',
          type: 'gemini',
          content: [{ text: 'Response' }],
        },
      ];

      await service.generateSummary({ messages });

      expect(mockGenerateContent).toHaveBeenCalledTimes(1);
      const callArgs = mockGenerateContent.mock.calls[0][0];
      const promptText = callArgs.contents[0].parts[0].text;

      // Should be truncated to ~500 chars + "..."
      expect(promptText).toContain('...');
      expect(promptText).not.toContain('a'.repeat(600));
    });

    it('should preserve important content in truncation', async () => {
      const messages: MessageRecord[] = [
        {
          id: '1',
          timestamp: '2025-12-03T00:00:00Z',
          type: 'user',
          content: [{ text: 'How do I add dark mode?' }],
        },
        {
          id: '2',
          timestamp: '2025-12-03T00:01:00Z',
          type: 'gemini',
          content: [
            {
              text: 'Here is a detailed explanation...',
            },
          ],
        },
      ];

      await service.generateSummary({ messages });

      expect(mockGenerateContent).toHaveBeenCalledTimes(1);
      const callArgs = mockGenerateContent.mock.calls[0][0];
      const promptText = callArgs.contents[0].parts[0].text;

      // User question should be preserved
      expect(promptText).toContain('User: How do I add dark mode?');
      expect(promptText).toContain('Assistant: Here is a detailed explanation');
    });
  });

  describe('Sliding Window Message Selection', () => {
    it('should return all messages when fewer than 20 exist', async () => {
      const messages = Array.from({ length: 5 }, (_, i) => ({
        id: `${i}`,
        timestamp: '2025-12-03T00:00:00Z',
        type: i % 2 === 0 ? ('user' as const) : ('gemini' as const),
        content: [{ text: `Message ${i}` }],
      }));

      await service.generateSummary({ messages });

      const callArgs = mockGenerateContent.mock.calls[0][0];
      const promptText = callArgs.contents[0].parts[0].text;

      const messageCount = (promptText.match(/Message \d+/g) || []).length;
      expect(messageCount).toBe(5);
    });

    it('should select first 10 + last 10 from 50 messages', async () => {
      const messages = Array.from({ length: 50 }, (_, i) => ({
        id: `${i}`,
        timestamp: '2025-12-03T00:00:00Z',
        type: i % 2 === 0 ? ('user' as const) : ('gemini' as const),
        content: [{ text: `Message ${i}` }],
      }));

      await service.generateSummary({ messages });

      const callArgs = mockGenerateContent.mock.calls[0][0];
      const promptText = callArgs.contents[0].parts[0].text;

      // Should include first 10
      expect(promptText).toContain('Message 0');
      expect(promptText).toContain('Message 9');

      // Should skip middle
      expect(promptText).not.toContain('Message 25');

      // Should include last 10
      expect(promptText).toContain('Message 40');
      expect(promptText).toContain('Message 49');

      const messageCount = (promptText.match(/Message \d+/g) || []).length;
      expect(messageCount).toBe(20);
    });

    it('should return all messages when exactly 20 exist', async () => {
      const messages = Array.from({ length: 20 }, (_, i) => ({
        id: `${i}`,
        timestamp: '2025-12-03T00:00:00Z',
        type: i % 2 === 0 ? ('user' as const) : ('gemini' as const),
        content: [{ text: `Message ${i}` }],
      }));

      await service.generateSummary({ messages });

      const callArgs = mockGenerateContent.mock.calls[0][0];
      const promptText = callArgs.contents[0].parts[0].text;

      const messageCount = (promptText.match(/Message \d+/g) || []).length;
      expect(messageCount).toBe(20);
    });

    it('should preserve message ordering in sliding window', async () => {
      const messages = Array.from({ length: 30 }, (_, i) => ({
        id: `${i}`,
        timestamp: '2025-12-03T00:00:00Z',
        type: i % 2 === 0 ? ('user' as const) : ('gemini' as const),
        content: [{ text: `Message ${i}` }],
      }));

      await service.generateSummary({ messages });

      const callArgs = mockGenerateContent.mock.calls[0][0];
      const promptText = callArgs.contents[0].parts[0].text;

      const matches = promptText.match(/Message (\d+)/g) || [];
      const indices = matches.map((m: string) => parseInt(m.split(' ')[1], 10));

      // Verify ordering is preserved
      for (let i = 1; i < indices.length; i++) {
        expect(indices[i]).toBeGreaterThan(indices[i - 1]);
      }
    });

    it('should not count system messages when calculating window', async () => {
      const messages: MessageRecord[] = [
        // First 10 user/gemini messages
        ...Array.from({ length: 10 }, (_, i) => ({
          id: `${i}`,
          timestamp: '2025-12-03T00:00:00Z',
          type: i % 2 === 0 ? ('user' as const) : ('gemini' as const),
          content: [{ text: `Message ${i}` }],
        })),
        // System messages (should be filtered out)
        {
          id: 'info1',
          timestamp: '2025-12-03T00:10:00Z',
          type: 'info' as const,
          content: [{ text: 'Info' }],
        },
        {
          id: 'warn1',
          timestamp: '2025-12-03T00:11:00Z',
          type: 'warning' as const,
          content: [{ text: 'Warning' }],
        },
        // Last 40 user/gemini messages
        ...Array.from({ length: 40 }, (_, i) => ({
          id: `${i + 10}`,
          timestamp: '2025-12-03T00:12:00Z',
          type: i % 2 === 0 ? ('user' as const) : ('gemini' as const),
          content: [{ text: `Message ${i + 10}` }],
        })),
      ];

      await service.generateSummary({ messages });

      const callArgs = mockGenerateContent.mock.calls[0][0];
      const promptText = callArgs.contents[0].parts[0].text;

      // Should include early messages
      expect(promptText).toContain('Message 0');
      expect(promptText).toContain('Message 9');

      // Should include late messages
      expect(promptText).toContain('Message 40');
      expect(promptText).toContain('Message 49');

      // Should not include system messages
      expect(promptText).not.toContain('Info');
      expect(promptText).not.toContain('Warning');
    });
  });

  describe('Edge Cases', () => {
    it('should handle conversation with only user messages', async () => {
      const messages: MessageRecord[] = [
        {
          id: '1',
          timestamp: '2025-12-03T00:00:00Z',
          type: 'user',
          content: [{ text: 'First question' }],
        },
        {
          id: '2',
          timestamp: '2025-12-03T00:01:00Z',
          type: 'user',
          content: [{ text: 'Second question' }],
        },
      ];

      const summary = await service.generateSummary({ messages });

      expect(summary).not.toBeNull();
      expect(mockGenerateContent).toHaveBeenCalledTimes(1);
    });

    it('should handle conversation with only gemini messages', async () => {
      const messages: MessageRecord[] = [
        {
          id: '1',
          timestamp: '2025-12-03T00:00:00Z',
          type: 'gemini',
          content: [{ text: 'First response' }],
        },
        {
          id: '2',
          timestamp: '2025-12-03T00:01:00Z',
          type: 'gemini',
          content: [{ text: 'Second response' }],
        },
      ];

      const summary = await service.generateSummary({ messages });

      expect(summary).not.toBeNull();
      expect(mockGenerateContent).toHaveBeenCalledTimes(1);
    });

    it('should handle very long individual messages (>500 chars)', async () => {
      const longMessage =
        `This is a very long message that contains a lot of text and definitely exceeds the 500 character limit. `.repeat(
          10,
        );
      const messages: MessageRecord[] = [
        {
          id: '1',
          timestamp: '2025-12-03T00:00:00Z',
          type: 'user',
          content: [{ text: longMessage }],
        },
      ];

      await service.generateSummary({ messages });

      expect(mockGenerateContent).toHaveBeenCalledTimes(1);
      const callArgs = mockGenerateContent.mock.calls[0][0];
      const promptText = callArgs.contents[0].parts[0].text;

      // Should contain the truncation marker
      expect(promptText).toContain('...');
    });

    it('should handle messages with special characters', async () => {
      const messages: MessageRecord[] = [
        {
          id: '1',
          timestamp: '2025-12-03T00:00:00Z',
          type: 'user',
          content: [
            {
              text: 'How to use <Component> with props={value} & state?',
            },
          ],
        },
      ];

      const summary = await service.generateSummary({ messages });

      expect(summary).not.toBeNull();
      expect(mockGenerateContent).toHaveBeenCalledTimes(1);
    });

    it('should handle malformed message content', async () => {
      const messages: MessageRecord[] = [
        {
          id: '1',
          timestamp: '2025-12-03T00:00:00Z',
          type: 'user',
          content: [], // Empty parts array
        },
        {
          id: '2',
          timestamp: '2025-12-03T00:01:00Z',
          type: 'gemini',
          content: [{ text: 'Valid response' }],
        },
      ];

      await service.generateSummary({ messages });

      // Should handle gracefully and still process valid messages
      expect(mockGenerateContent).toHaveBeenCalled();
    });
  });

  describe('Internationalization Support', () => {
    it('should preserve international characters (Chinese)', async () => {
      mockGenerateContent.mockResolvedValue({
        candidates: [
          {
            content: {
              parts: [{ text: '添加深色模式到应用' }],
            },
          },
        ],
      } as unknown as GenerateContentResponse);

      const messages: MessageRecord[] = [
        {
          id: '1',
          timestamp: '2025-12-03T00:00:00Z',
          type: 'user',
          content: [{ text: 'How do I add dark mode?' }],
        },
      ];

      const summary = await service.generateSummary({ messages });

      expect(summary).toBe('添加深色模式到应用');
    });

    it('should preserve international characters (Arabic)', async () => {
      mockGenerateContent.mockResolvedValue({
        candidates: [
          {
            content: {
              parts: [{ text: 'إضافة الوضع الداكن' }],
            },
          },
        ],
      } as unknown as GenerateContentResponse);

      const messages: MessageRecord[] = [
        {
          id: '1',
          timestamp: '2025-12-03T00:00:00Z',
          type: 'user',
          content: [{ text: 'How do I add dark mode?' }],
        },
      ];

      const summary = await service.generateSummary({ messages });

      expect(summary).toBe('إضافة الوضع الداكن');
    });

    it('should preserve accented characters', async () => {
      mockGenerateContent.mockResolvedValue({
        candidates: [
          {
            content: {
              parts: [{ text: 'Añadir modo oscuro à la aplicación' }],
            },
          },
        ],
      } as unknown as GenerateContentResponse);

      const messages: MessageRecord[] = [
        {
          id: '1',
          timestamp: '2025-12-03T00:00:00Z',
          type: 'user',
          content: [{ text: 'How do I add dark mode?' }],
        },
      ];

      const summary = await service.generateSummary({ messages });

      expect(summary).toBe('Añadir modo oscuro à la aplicación');
    });

    it('should preserve emojis in summaries', async () => {
      mockGenerateContent.mockResolvedValue({
        candidates: [
          {
            content: {
              parts: [{ text: '🌙 Add dark mode 🎨 to the app ✨' }],
            },
          },
        ],
      } as unknown as GenerateContentResponse);

      const messages: MessageRecord[] = [
        {
          id: '1',
          timestamp: '2025-12-03T00:00:00Z',
          type: 'user',
          content: [{ text: 'How do I add dark mode?' }],
        },
      ];

      const summary = await service.generateSummary({ messages });

      // Emojis are preserved
      expect(summary).toBe('🌙 Add dark mode 🎨 to the app ✨');
      expect(summary).toContain('🌙');
      expect(summary).toContain('🎨');
      expect(summary).toContain('✨');
    });

    it('should preserve zero-width characters for language rendering', async () => {
      // Arabic with Zero-Width Joiner (ZWJ) for proper ligatures
      mockGenerateContent.mockResolvedValue({
        candidates: [
          {
            content: {
              parts: [{ text: 'كلمة\u200Dمتصلة' }], // Contains ZWJ
            },
          },
        ],
      } as unknown as GenerateContentResponse);

      const messages: MessageRecord[] = [
        {
          id: '1',
          timestamp: '2025-12-03T00:00:00Z',
          type: 'user',
          content: [{ text: 'Test' }],
        },
      ];

      const summary = await service.generateSummary({ messages });

      // ZWJ is preserved (it's not considered whitespace)
      expect(summary).toBe('كلمة\u200Dمتصلة');
      expect(summary).toContain('\u200D'); // ZWJ should be preserved
    });
  });
});