File size: 24,220 Bytes
52efc7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest';

import type { SlashCommand, CommandContext } from './types.js';
import { createMockCommandContext } from '../../test-utils/mockCommandContext.js';
import type { Content } from '@google/genai';
import { AuthType, type GeminiClient } from '@google/gemini-cli-core';

import * as fsPromises from 'node:fs/promises';
import { chatCommand, debugCommand } from './chatCommand.js';
import {
  serializeHistoryToMarkdown,
  exportHistoryToFile,
} from '../utils/historyExportUtils.js';
import type { Stats } from 'node:fs';
import type { HistoryItemWithoutId } from '../types.js';
import path from 'node:path';

vi.mock('fs/promises', () => ({
  stat: vi.fn(),
  readdir: vi.fn().mockResolvedValue(['file1.txt', 'file2.txt'] as string[]),
  writeFile: vi.fn(),
}));

vi.mock('../utils/historyExportUtils.js', async (importOriginal) => {
  const actual =
    await importOriginal<typeof import('../utils/historyExportUtils.js')>();
  return {
    ...actual,
    exportHistoryToFile: vi.fn(),
  };
});

describe('chatCommand', () => {
  const mockFs = vi.mocked(fsPromises);
  const mockExport = vi.mocked(exportHistoryToFile);

  let mockContext: CommandContext;
  let mockGetChat: ReturnType<typeof vi.fn>;
  let mockSaveCheckpoint: ReturnType<typeof vi.fn>;
  let mockLoadCheckpoint: ReturnType<typeof vi.fn>;
  let mockDeleteCheckpoint: ReturnType<typeof vi.fn>;
  let mockGetHistory: ReturnType<typeof vi.fn>;

  const getSubCommand = (
    name: 'list' | 'save' | 'resume' | 'delete' | 'share',
  ): SlashCommand => {
    const subCommand = chatCommand.subCommands?.find(
      (cmd) => cmd.name === name,
    );
    if (!subCommand) {
      throw new Error(`/chat ${name} command not found.`);
    }
    return subCommand;
  };

  beforeEach(() => {
    mockGetHistory = vi.fn().mockReturnValue([]);
    mockGetChat = vi.fn().mockReturnValue({
      getHistory: mockGetHistory,
    });
    mockSaveCheckpoint = vi.fn().mockResolvedValue(undefined);
    mockLoadCheckpoint = vi.fn().mockResolvedValue({ history: [] });
    mockDeleteCheckpoint = vi.fn().mockResolvedValue(true);

    mockContext = createMockCommandContext({
      services: {
        agentContext: {
          config: {
            getProjectRoot: () => '/project/root',
            getContentGeneratorConfig: () => ({
              authType: AuthType.LOGIN_WITH_GOOGLE,
            }),
            storage: {
              getProjectTempDir: () => '/project/root/.gemini/tmp/mockhash',
            },
          },
          geminiClient: {
            getChat: mockGetChat,
          } as unknown as GeminiClient,
        },
        logger: {
          saveCheckpoint: mockSaveCheckpoint,
          loadCheckpoint: mockLoadCheckpoint,
          deleteCheckpoint: mockDeleteCheckpoint,
          initialize: vi.fn().mockResolvedValue(undefined),
        },
      },
    });
  });

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

  it('should have the correct main command definition', () => {
    expect(chatCommand.name).toBe('chat');
    expect(chatCommand.description).toBe(
      'Browse auto-saved conversations and manage chat checkpoints',
    );
    expect(chatCommand.autoExecute).toBe(true);
    expect(chatCommand.subCommands).toHaveLength(6);
  });

  describe('list subcommand', () => {
    let listCommand: SlashCommand;

    beforeEach(() => {
      listCommand = getSubCommand('list');
    });

    it('should add a chat_list item to the UI', async () => {
      const fakeFiles = ['checkpoint-test1.json', 'checkpoint-test2.json'];
      const date1 = new Date();
      const date2 = new Date(date1.getTime() + 1000);

      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      mockFs.readdir.mockResolvedValue(fakeFiles as any);
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      mockFs.stat.mockImplementation(async (path: any): Promise<Stats> => {
        if (path.endsWith('test1.json')) {
          return { mtime: date1 } as Stats;
        }
        return { mtime: date2 } as Stats;
      });

      await listCommand?.action?.(mockContext, '');

      expect(mockContext.ui.addItem).toHaveBeenCalledWith({
        type: 'chat_list',
        chats: [
          {
            name: 'test1',
            mtime: date1.toISOString(),
          },
          {
            name: 'test2',
            mtime: date2.toISOString(),
          },
        ],
      });
    });
  });
  describe('save subcommand', () => {
    let saveCommand: SlashCommand;
    const tag = 'my-tag';
    let mockCheckpointExists: ReturnType<typeof vi.fn>;

    beforeEach(() => {
      saveCommand = getSubCommand('save');
      mockCheckpointExists = vi.fn().mockResolvedValue(false);
      mockContext.services.logger.checkpointExists = mockCheckpointExists;
    });

    it('should return an error if tag is missing', async () => {
      const result = await saveCommand?.action?.(mockContext, '  ');
      expect(result).toEqual({
        type: 'message',
        messageType: 'error',
        content: 'Missing tag. Usage: /resume save <tag>',
      });
    });

    it('should inform if conversation history is empty or only contains system context', async () => {
      mockGetHistory.mockReturnValue([]);
      let result = await saveCommand?.action?.(mockContext, tag);
      expect(result).toEqual({
        type: 'message',
        messageType: 'info',
        content: 'No conversation found to save.',
      });

      mockGetHistory.mockReturnValue([
        { role: 'user', parts: [{ text: 'context for our chat' }] },
      ]);
      result = await saveCommand?.action?.(mockContext, tag);
      expect(result).toEqual({
        type: 'message',
        messageType: 'info',
        content: 'No conversation found to save.',
      });

      mockGetHistory.mockReturnValue([
        { role: 'user', parts: [{ text: 'context for our chat' }] },
        { role: 'model', parts: [{ text: 'Got it. Thanks for the context!' }] },
        { role: 'user', parts: [{ text: 'Hello, how are you?' }] },
      ]);
      result = await saveCommand?.action?.(mockContext, tag);
      expect(result).toEqual({
        type: 'message',
        messageType: 'info',
        content: `Conversation checkpoint saved with tag: ${tag}.`,
      });
    });

    it('should return confirm_action if checkpoint already exists', async () => {
      mockCheckpointExists.mockResolvedValue(true);
      mockContext.invocation = {
        raw: `/chat save ${tag}`,
        name: 'save',
        args: tag,
      };

      const result = await saveCommand?.action?.(mockContext, tag);

      expect(mockCheckpointExists).toHaveBeenCalledWith(tag);
      expect(mockSaveCheckpoint).not.toHaveBeenCalled();
      expect(result).toMatchObject({
        type: 'confirm_action',
        originalInvocation: { raw: `/chat save ${tag}` },
      });
      // Check that prompt is a React element
      expect(result).toHaveProperty('prompt');
    });

    it('should save the conversation if overwrite is confirmed', async () => {
      const history: Content[] = [
        { role: 'user', parts: [{ text: 'context for our chat' }] },
        { role: 'user', parts: [{ text: 'hello' }] },
      ];
      mockGetHistory.mockReturnValue(history);
      mockContext.overwriteConfirmed = true;

      const result = await saveCommand?.action?.(mockContext, tag);

      expect(mockCheckpointExists).not.toHaveBeenCalled(); // Should skip existence check
      expect(mockSaveCheckpoint).toHaveBeenCalledWith(
        { history, authType: AuthType.LOGIN_WITH_GOOGLE },
        tag,
      );
      expect(result).toEqual({
        type: 'message',
        messageType: 'info',
        content: `Conversation checkpoint saved with tag: ${tag}.`,
      });
    });
  });

  describe('resume subcommand', () => {
    const goodTag = 'good-tag';
    const badTag = 'bad-tag';

    let resumeCommand: SlashCommand;
    beforeEach(() => {
      resumeCommand = getSubCommand('resume');
    });

    it('should return an error if tag is missing', async () => {
      const result = await resumeCommand?.action?.(mockContext, '');

      expect(result).toEqual({
        type: 'message',
        messageType: 'error',
        content: 'Missing tag. Usage: /resume resume <tag>',
      });
    });

    it('should inform if checkpoint is not found', async () => {
      mockLoadCheckpoint.mockResolvedValue({ history: [] });

      const result = await resumeCommand?.action?.(mockContext, badTag);

      expect(result).toEqual({
        type: 'message',
        messageType: 'info',
        content: `No saved checkpoint found with tag: ${badTag}.`,
      });
    });

    it('should resume a conversation with matching authType', async () => {
      const conversation: Content[] = [
        { role: 'user', parts: [{ text: 'system setup' }] },
        { role: 'user', parts: [{ text: 'hello gemini' }] },
        { role: 'model', parts: [{ text: 'hello world' }] },
      ];
      mockLoadCheckpoint.mockResolvedValue({
        history: conversation,
        authType: AuthType.LOGIN_WITH_GOOGLE,
      });

      const result = await resumeCommand?.action?.(mockContext, goodTag);

      expect(result).toEqual({
        type: 'load_history',
        history: [
          { type: 'user', text: 'hello gemini' },
          { type: 'gemini', text: 'hello world' },
        ] as HistoryItemWithoutId[],
        clientHistory: conversation,
      });
    });

    it('should block resuming a conversation with mismatched authType', async () => {
      const conversation: Content[] = [
        { role: 'user', parts: [{ text: 'system setup' }] },
        { role: 'user', parts: [{ text: 'hello gemini' }] },
        { role: 'model', parts: [{ text: 'hello world' }] },
      ];
      mockLoadCheckpoint.mockResolvedValue({
        history: conversation,
        authType: AuthType.USE_GEMINI,
      });

      const result = await resumeCommand?.action?.(mockContext, goodTag);

      expect(result).toEqual({
        type: 'message',
        messageType: 'error',
        content: `Cannot resume chat. It was saved with a different authentication method (${AuthType.USE_GEMINI}) than the current one (${AuthType.LOGIN_WITH_GOOGLE}).`,
      });
    });

    it('should resume a legacy conversation without authType', async () => {
      const conversation: Content[] = [
        { role: 'user', parts: [{ text: 'system setup' }] },
        { role: 'user', parts: [{ text: 'hello gemini' }] },
        { role: 'model', parts: [{ text: 'hello world' }] },
      ];
      mockLoadCheckpoint.mockResolvedValue({ history: conversation });

      const result = await resumeCommand?.action?.(mockContext, goodTag);

      expect(result).toEqual({
        type: 'load_history',
        history: [
          { type: 'user', text: 'hello gemini' },
          { type: 'gemini', text: 'hello world' },
        ] as HistoryItemWithoutId[],
        clientHistory: conversation,
      });
    });

    describe('completion', () => {
      it('should provide completion suggestions', async () => {
        const fakeFiles = ['checkpoint-alpha.json', 'checkpoint-beta.json'];
        mockFs.readdir.mockImplementation(
          (async (_: string): Promise<string[]> =>
            fakeFiles) as unknown as typeof fsPromises.readdir,
        );

        mockFs.stat.mockImplementation(
          (async (_: string): Promise<Stats> =>
            ({
              mtime: new Date(),
            }) as Stats) as unknown as typeof fsPromises.stat,
        );

        const result = await resumeCommand?.completion?.(mockContext, 'a');

        expect(result).toEqual(['alpha']);
      });

      it('should suggest filenames sorted by modified time (newest first)', async () => {
        const fakeFiles = ['checkpoint-test1.json', 'checkpoint-test2.json'];
        const date = new Date();
        mockFs.readdir.mockImplementation(
          (async (_: string): Promise<string[]> =>
            fakeFiles) as unknown as typeof fsPromises.readdir,
        );
        mockFs.stat.mockImplementation((async (
          path: string,
        ): Promise<Stats> => {
          if (path.endsWith('test1.json')) {
            return { mtime: date } as Stats;
          }
          return { mtime: new Date(date.getTime() + 1000) } as Stats;
        }) as unknown as typeof fsPromises.stat);

        const result = await resumeCommand?.completion?.(mockContext, '');
        // Sort items by last modified time (newest first)
        expect(result).toEqual(['test2', 'test1']);
      });
    });
  });

  describe('delete subcommand', () => {
    let deleteCommand: SlashCommand;
    const tag = 'my-tag';
    beforeEach(() => {
      deleteCommand = getSubCommand('delete');
    });

    it('should return an error if tag is missing', async () => {
      const result = await deleteCommand?.action?.(mockContext, '  ');
      expect(result).toEqual({
        type: 'message',
        messageType: 'error',
        content: 'Missing tag. Usage: /resume delete <tag>',
      });
    });

    it('should return an error if checkpoint is not found', async () => {
      mockDeleteCheckpoint.mockResolvedValue(false);
      const result = await deleteCommand?.action?.(mockContext, tag);
      expect(result).toEqual({
        type: 'message',
        messageType: 'error',
        content: `Error: No checkpoint found with tag '${tag}'.`,
      });
    });

    it('should delete the conversation', async () => {
      const result = await deleteCommand?.action?.(mockContext, tag);

      expect(mockDeleteCheckpoint).toHaveBeenCalledWith(tag);
      expect(result).toEqual({
        type: 'message',
        messageType: 'info',
        content: `Conversation checkpoint '${tag}' has been deleted.`,
      });
    });

    describe('completion', () => {
      it('should provide completion suggestions', async () => {
        const fakeFiles = ['checkpoint-alpha.json', 'checkpoint-beta.json'];
        mockFs.readdir.mockImplementation(
          (async (_: string): Promise<string[]> =>
            fakeFiles) as unknown as typeof fsPromises.readdir,
        );

        mockFs.stat.mockImplementation(
          (async (_: string): Promise<Stats> =>
            ({
              mtime: new Date(),
            }) as Stats) as unknown as typeof fsPromises.stat,
        );

        const result = await deleteCommand?.completion?.(mockContext, 'a');

        expect(result).toEqual(['alpha']);
      });
    });
  });

  describe('share subcommand', () => {
    let shareCommand: SlashCommand;
    const mockHistory = [
      { role: 'user', parts: [{ text: 'context' }] },
      { role: 'model', parts: [{ text: 'context response' }] },
      { role: 'user', parts: [{ text: 'Hello' }] },
      { role: 'model', parts: [{ text: 'Hi there!' }] },
    ];

    beforeEach(() => {
      shareCommand = getSubCommand('share');
      vi.spyOn(process, 'cwd').mockReturnValue(
        path.resolve('/usr/local/google/home/myuser/gemini-cli'),
      );
      vi.spyOn(Date, 'now').mockReturnValue(1234567890);
      mockGetHistory.mockReturnValue(mockHistory);
      mockFs.writeFile.mockClear();
    });

    it('should default to a json file if no path is provided', async () => {
      const result = await shareCommand?.action?.(mockContext, '');
      const expectedPath = path.join(
        process.cwd(),
        'gemini-conversation-1234567890.json',
      );
      expect(mockExport).toHaveBeenCalledWith({
        history: mockHistory,
        filePath: expectedPath,
      });
      expect(result).toEqual({
        type: 'message',
        messageType: 'info',
        content: `Conversation shared to ${expectedPath}`,
      });
    });

    it('should share the conversation to a JSON file', async () => {
      const filePath = 'my-chat.json';
      const result = await shareCommand?.action?.(mockContext, filePath);
      const expectedPath = path.join(process.cwd(), 'my-chat.json');
      expect(mockExport).toHaveBeenCalledWith({
        history: mockHistory,
        filePath: expectedPath,
      });
      expect(result).toEqual({
        type: 'message',
        messageType: 'info',
        content: `Conversation shared to ${expectedPath}`,
      });
    });

    it('should share the conversation to a Markdown file', async () => {
      const filePath = 'my-chat.md';
      const result = await shareCommand?.action?.(mockContext, filePath);
      const expectedPath = path.join(process.cwd(), 'my-chat.md');
      expect(mockExport).toHaveBeenCalledWith({
        history: mockHistory,
        filePath: expectedPath,
      });
      expect(result).toEqual({
        type: 'message',
        messageType: 'info',
        content: `Conversation shared to ${expectedPath}`,
      });
    });

    it('should return an error for unsupported file extensions', async () => {
      const filePath = 'my-chat.txt';
      const result = await shareCommand?.action?.(mockContext, filePath);
      expect(mockExport).not.toHaveBeenCalled();
      expect(result).toEqual({
        type: 'message',
        messageType: 'error',
        content: 'Invalid file format. Only .md and .json are supported.',
      });
    });

    it('should inform if there is no conversation to share', async () => {
      mockGetHistory.mockReturnValue([
        { role: 'user', parts: [{ text: 'context' }] },
      ]);
      const result = await shareCommand?.action?.(mockContext, 'my-chat.json');
      expect(mockExport).not.toHaveBeenCalled();
      expect(result).toEqual({
        type: 'message',
        messageType: 'info',
        content: 'No conversation found to share.',
      });
    });

    it('should handle errors during file writing', async () => {
      const error = new Error('Permission denied');
      mockExport.mockRejectedValue(error);
      const result = await shareCommand?.action?.(mockContext, 'my-chat.json');
      expect(result).toEqual({
        type: 'message',
        messageType: 'error',
        content: `Error sharing conversation: ${error.message}`,
      });
    });

    it('should output valid JSON schema', async () => {
      const filePath = 'my-chat.json';
      await shareCommand?.action?.(mockContext, filePath);
      const expectedPath = path.join(process.cwd(), 'my-chat.json');
      expect(mockExport).toHaveBeenCalledWith({
        history: mockHistory,
        filePath: expectedPath,
      });
    });

    it('should output correct markdown format', async () => {
      const filePath = 'my-chat.md';
      await shareCommand?.action?.(mockContext, filePath);
      const expectedPath = path.join(process.cwd(), 'my-chat.md');
      expect(mockExport).toHaveBeenCalledWith({
        history: mockHistory,
        filePath: expectedPath,
      });
    });
  });

  describe('serializeHistoryToMarkdown', () => {
    it('should correctly serialize chat history to Markdown with icons', () => {
      const history: Content[] = [
        { role: 'user', parts: [{ text: 'Hello' }] },
        { role: 'model', parts: [{ text: 'Hi there!' }] },
        { role: 'user', parts: [{ text: 'How are you?' }] },
      ];

      const expectedMarkdown =
        '## USER πŸ§‘β€πŸ’»\n\nHello\n\n---\n\n' +
        '## MODEL ✨\n\nHi there!\n\n---\n\n' +
        '## USER πŸ§‘β€πŸ’»\n\nHow are you?';

      const result = serializeHistoryToMarkdown(history);
      expect(result).toBe(expectedMarkdown);
    });

    it('should handle empty history', () => {
      const history: Content[] = [];
      const result = serializeHistoryToMarkdown(history);
      expect(result).toBe('');
    });

    it('should handle items with no text parts', () => {
      const history: Content[] = [
        { role: 'user', parts: [{ text: 'Hello' }] },
        { role: 'model', parts: [] },
        { role: 'user', parts: [{ text: 'How are you?' }] },
      ];

      const expectedMarkdown = `## USER πŸ§‘β€πŸ’»

Hello

---

## MODEL ✨



---

## USER πŸ§‘β€πŸ’»

How are you?`;

      const result = serializeHistoryToMarkdown(history);
      expect(result).toBe(expectedMarkdown);
    });

    it('should correctly serialize function calls and responses', () => {
      const history: Content[] = [
        {
          role: 'user',
          parts: [{ text: 'Please call a function.' }],
        },
        {
          role: 'model',
          parts: [
            {
              functionCall: {
                name: 'my-function',
                args: { arg1: 'value1' },
              },
            },
          ],
        },
        {
          role: 'user',
          parts: [
            {
              functionResponse: {
                name: 'my-function',
                response: { result: 'success' },
              },
            },
          ],
        },
      ];

      const expectedMarkdown = `## USER πŸ§‘β€πŸ’»

Please call a function.

---

## MODEL ✨

**Tool Command**:
\`\`\`json
{
  "name": "my-function",
  "args": {
    "arg1": "value1"
  }
}
\`\`\`

---

## USER πŸ§‘β€πŸ’»

**Tool Response**:
\`\`\`json
{
  "name": "my-function",
  "response": {
    "result": "success"
  }
}
\`\`\``;

      const result = serializeHistoryToMarkdown(history);
      expect(result).toBe(expectedMarkdown);
    });

    it('should handle items with undefined role', () => {
      const history: Array<Partial<Content>> = [
        { role: 'user', parts: [{ text: 'Hello' }] },
        { parts: [{ text: 'Hi there!' }] },
      ];

      const expectedMarkdown = `## USER πŸ§‘β€πŸ’»

Hello

---

## MODEL ✨

Hi there!`;

      const result = serializeHistoryToMarkdown(history as Content[]);
      expect(result).toBe(expectedMarkdown);
    });
    describe('debug subcommand', () => {
      let mockGetLatestApiRequest: ReturnType<typeof vi.fn>;

      beforeEach(() => {
        mockGetLatestApiRequest = vi.fn();
        if (!mockContext.services.agentContext!.config) {
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          (mockContext.services.agentContext!.config as any) = {};
        }
        mockContext.services.agentContext!.config.getLatestApiRequest =
          mockGetLatestApiRequest;
        vi.spyOn(process, 'cwd').mockReturnValue('/project/root');
        vi.spyOn(Date, 'now').mockReturnValue(1234567890);
        mockFs.writeFile.mockClear();
      });

      it('should return an error if no API request is found', async () => {
        mockGetLatestApiRequest.mockReturnValue(undefined);

        const result = await debugCommand.action?.(mockContext, '');

        expect(result).toEqual({
          type: 'message',
          messageType: 'error',
          content: 'No recent API request found to export.',
        });
        expect(mockFs.writeFile).not.toHaveBeenCalled();
      });

      it('should convert and write the API request to a json file', async () => {
        const mockRequest = {
          contents: [{ role: 'user', parts: [{ text: 'test' }] }],
        };
        mockGetLatestApiRequest.mockReturnValue(mockRequest);

        const result = await debugCommand.action?.(mockContext, '');

        const expectedFilename = 'gcli-request-1234567890.json';
        const expectedPath = path.join('/project/root', expectedFilename);

        expect(mockFs.writeFile).toHaveBeenCalledWith(
          expectedPath,
          expect.stringContaining('"role": "user"'),
        );
        expect(result).toEqual({
          type: 'message',
          messageType: 'info',
          content: `Debug API request saved to ${expectedFilename}`,
        });
      });

      it('should handle errors during file write', async () => {
        const mockRequest = { contents: [] };
        mockGetLatestApiRequest.mockReturnValue(mockRequest);
        mockFs.writeFile.mockRejectedValue(new Error('Write failed'));

        const result = await debugCommand.action?.(mockContext, '');

        expect(result).toEqual({
          type: 'message',
          messageType: 'error',
          content: 'Error saving debug request: Write failed',
        });
      });
    });
  });
});