@ai-devkit/agent-manager 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,790 @@
1
+ /**
2
+ * Tests for GeminiCliAdapter
3
+ */
4
+
5
+ import * as fs from 'fs';
6
+ import * as os from 'os';
7
+ import * as path from 'path';
8
+ import { beforeEach, afterEach, describe, expect, it, jest } from '@jest/globals';
9
+ import { GeminiCliAdapter } from '../../adapters/GeminiCliAdapter';
10
+ import type { ProcessInfo } from '../../adapters/AgentAdapter';
11
+ import { AgentStatus } from '../../adapters/AgentAdapter';
12
+ import { listAgentProcesses, enrichProcesses } from '../../utils/process';
13
+ import { matchProcessesToSessions, generateAgentName } from '../../utils/matching';
14
+
15
+ jest.mock('../../utils/process', () => ({
16
+ listAgentProcesses: jest.fn(),
17
+ enrichProcesses: jest.fn(),
18
+ }));
19
+
20
+ jest.mock('../../utils/matching', () => ({
21
+ matchProcessesToSessions: jest.fn(),
22
+ generateAgentName: jest.fn(),
23
+ }));
24
+
25
+ const mockedListAgentProcesses = listAgentProcesses as jest.MockedFunction<typeof listAgentProcesses>;
26
+ const mockedEnrichProcesses = enrichProcesses as jest.MockedFunction<typeof enrichProcesses>;
27
+ const mockedMatchProcessesToSessions = matchProcessesToSessions as jest.MockedFunction<typeof matchProcessesToSessions>;
28
+ const mockedGenerateAgentName = generateAgentName as jest.MockedFunction<typeof generateAgentName>;
29
+
30
+ describe('GeminiCliAdapter', () => {
31
+ let adapter: GeminiCliAdapter;
32
+ let tmpHome: string;
33
+
34
+ beforeEach(() => {
35
+ tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'gemini-adapter-test-'));
36
+ process.env.HOME = tmpHome;
37
+
38
+ adapter = new GeminiCliAdapter();
39
+ mockedListAgentProcesses.mockReset();
40
+ mockedEnrichProcesses.mockReset();
41
+ mockedMatchProcessesToSessions.mockReset();
42
+ mockedGenerateAgentName.mockReset();
43
+
44
+ mockedEnrichProcesses.mockImplementation((procs) => procs);
45
+ mockedMatchProcessesToSessions.mockReturnValue([]);
46
+ mockedGenerateAgentName.mockImplementation((cwd: string, pid: number) => {
47
+ const folder = path.basename(cwd) || 'unknown';
48
+ return `${folder} (${pid})`;
49
+ });
50
+ });
51
+
52
+ afterEach(() => {
53
+ fs.rmSync(tmpHome, { recursive: true, force: true });
54
+ });
55
+
56
+ describe('initialization', () => {
57
+ it('should expose gemini_cli type', () => {
58
+ expect(adapter.type).toBe('gemini_cli');
59
+ });
60
+ });
61
+
62
+ describe('canHandle', () => {
63
+ it('should return true for plain gemini command', () => {
64
+ expect(adapter.canHandle({ pid: 1, command: 'gemini', cwd: '/repo', tty: 'ttys001' })).toBe(true);
65
+ });
66
+
67
+ it('should return true for gemini with full path (case-insensitive)', () => {
68
+ expect(adapter.canHandle({
69
+ pid: 2,
70
+ command: '/usr/local/bin/GEMINI --yolo',
71
+ cwd: '/repo',
72
+ tty: 'ttys002',
73
+ })).toBe(true);
74
+ });
75
+
76
+ it('should return false for non-gemini processes', () => {
77
+ expect(adapter.canHandle({ pid: 3, command: 'node app.js', cwd: '/repo', tty: 'ttys003' })).toBe(false);
78
+ });
79
+
80
+ it('should return false when "gemini" appears only in path arguments', () => {
81
+ expect(adapter.canHandle({
82
+ pid: 4,
83
+ command: 'node /path/to/gemini-runner.js',
84
+ cwd: '/repo',
85
+ tty: 'ttys004',
86
+ })).toBe(false);
87
+ });
88
+
89
+ it('should return true for Node-invoked gemini script (real install layout)', () => {
90
+ expect(adapter.canHandle({
91
+ pid: 5,
92
+ command: 'node /Users/foo/.volta/tools/image/node/24.14.0/bin/gemini --help',
93
+ cwd: '/repo',
94
+ tty: 'ttys005',
95
+ })).toBe(true);
96
+ });
97
+
98
+ it('should return true for Node-invoked gemini.js bundle entrypoint', () => {
99
+ expect(adapter.canHandle({
100
+ pid: 6,
101
+ command: 'node /opt/homebrew/lib/node_modules/@google/gemini-cli/bundle/gemini.js',
102
+ cwd: '/repo',
103
+ tty: 'ttys006',
104
+ })).toBe(true);
105
+ });
106
+ });
107
+
108
+ describe('detectAgents', () => {
109
+ it('should return empty array when no gemini processes are running', async () => {
110
+ mockedListAgentProcesses.mockReturnValue([]);
111
+ const agents = await adapter.detectAgents();
112
+ expect(agents).toEqual([]);
113
+ });
114
+
115
+ it('should filter non-gemini Node processes out of the node process pool', async () => {
116
+ const geminiProc: ProcessInfo = {
117
+ pid: 100,
118
+ command: 'node /Users/foo/.volta/tools/image/node/24.14.0/bin/gemini --help',
119
+ cwd: '/repo',
120
+ tty: 'ttys001',
121
+ startTime: new Date('2026-04-18T00:00:00Z'),
122
+ };
123
+ const unrelatedNodeProc: ProcessInfo = {
124
+ pid: 200,
125
+ command: 'node /usr/local/bin/eslint src/',
126
+ cwd: '/other-repo',
127
+ tty: 'ttys002',
128
+ startTime: new Date('2026-04-18T00:00:00Z'),
129
+ };
130
+ mockedListAgentProcesses.mockReturnValue([geminiProc, unrelatedNodeProc]);
131
+
132
+ const agents = await adapter.detectAgents();
133
+ expect(agents).toHaveLength(1);
134
+ expect(agents[0].pid).toBe(100);
135
+ });
136
+
137
+ it('should return process-only agents when no session files exist for the process', async () => {
138
+ const proc: ProcessInfo = {
139
+ pid: 1234,
140
+ command: 'gemini',
141
+ cwd: '/repo',
142
+ tty: 'ttys001',
143
+ startTime: new Date('2026-04-18T00:00:00Z'),
144
+ };
145
+ mockedListAgentProcesses.mockReturnValue([proc]);
146
+
147
+ const agents = await adapter.detectAgents();
148
+ expect(agents).toHaveLength(1);
149
+ expect(agents[0]).toMatchObject({
150
+ type: 'gemini_cli',
151
+ pid: 1234,
152
+ projectPath: '/repo',
153
+ status: AgentStatus.RUNNING,
154
+ sessionId: 'pid-1234',
155
+ });
156
+ });
157
+
158
+ it('should map a process to its matching session file via projectHash', async () => {
159
+ const cwd = '/repo/project-a';
160
+ const projectHash = hashProjectRoot(cwd);
161
+ const shortId = 'abc123';
162
+ const chatsDir = path.join(tmpHome, '.gemini', 'tmp', shortId, 'chats');
163
+ fs.mkdirSync(chatsDir, { recursive: true });
164
+ const sessionPath = path.join(chatsDir, 'session-2026-04-18T00-00-session1.json');
165
+ const sessionStart = new Date('2026-04-18T00:00:00Z').toISOString();
166
+ fs.writeFileSync(
167
+ sessionPath,
168
+ JSON.stringify({
169
+ sessionId: 'session1',
170
+ projectHash,
171
+ startTime: sessionStart,
172
+ lastUpdated: sessionStart,
173
+ kind: 'main',
174
+ messages: [
175
+ { id: 'm1', timestamp: sessionStart, type: 'user', content: 'hello gemini' },
176
+ ],
177
+ }),
178
+ );
179
+
180
+ const proc: ProcessInfo = {
181
+ pid: 42,
182
+ command: 'gemini',
183
+ cwd,
184
+ tty: 'ttys001',
185
+ startTime: new Date('2026-04-18T00:00:00Z'),
186
+ };
187
+ mockedListAgentProcesses.mockReturnValue([proc]);
188
+ mockedMatchProcessesToSessions.mockReturnValue([
189
+ {
190
+ process: proc,
191
+ session: {
192
+ sessionId: 'session1',
193
+ filePath: sessionPath,
194
+ projectDir: chatsDir,
195
+ birthtimeMs: Date.now(),
196
+ resolvedCwd: cwd,
197
+ },
198
+ deltaMs: 0,
199
+ },
200
+ ]);
201
+
202
+ const agents = await adapter.detectAgents();
203
+ expect(agents).toHaveLength(1);
204
+ expect(agents[0]).toMatchObject({
205
+ type: 'gemini_cli',
206
+ pid: 42,
207
+ projectPath: cwd,
208
+ sessionId: 'session1',
209
+ sessionFilePath: sessionPath,
210
+ });
211
+ expect(agents[0].summary).toContain('hello gemini');
212
+ });
213
+
214
+ it('should not match sessions from other projects', async () => {
215
+ const procCwd = '/repo/project-a';
216
+ const otherCwd = '/repo/project-b';
217
+ const otherHash = hashProjectRoot(otherCwd);
218
+ const chatsDir = path.join(tmpHome, '.gemini', 'tmp', 'other', 'chats');
219
+ fs.mkdirSync(chatsDir, { recursive: true });
220
+ const sessionPath = path.join(chatsDir, 'session-2026-04-18T00-00-other.json');
221
+ fs.writeFileSync(
222
+ sessionPath,
223
+ JSON.stringify({
224
+ sessionId: 'other-session',
225
+ projectHash: otherHash,
226
+ startTime: new Date().toISOString(),
227
+ lastUpdated: new Date().toISOString(),
228
+ kind: 'main',
229
+ messages: [],
230
+ }),
231
+ );
232
+
233
+ const proc: ProcessInfo = {
234
+ pid: 7,
235
+ command: 'gemini',
236
+ cwd: procCwd,
237
+ tty: 'ttys001',
238
+ startTime: new Date(),
239
+ };
240
+ mockedListAgentProcesses.mockReturnValue([proc]);
241
+
242
+ const agents = await adapter.detectAgents();
243
+
244
+ const candidateSessions = mockedMatchProcessesToSessions.mock.calls[0]?.[1] ?? [];
245
+ expect(candidateSessions).toHaveLength(0);
246
+
247
+ expect(agents).toHaveLength(1);
248
+ expect(agents[0].sessionId).toBe(`pid-${proc.pid}`);
249
+ });
250
+ });
251
+
252
+ describe('discoverSessions', () => {
253
+ it('should return empty when ~/.gemini/tmp does not exist', () => {
254
+ const proc: ProcessInfo = {
255
+ pid: 1,
256
+ command: 'gemini',
257
+ cwd: '/repo',
258
+ tty: 'ttys001',
259
+ startTime: new Date(),
260
+ };
261
+ // tmp dir absent by default
262
+ const result = (adapter as any).discoverSessions([proc]);
263
+ expect(result.sessions).toEqual([]);
264
+ expect(result.contentCache.size).toBe(0);
265
+ });
266
+
267
+ it('should skip processes with empty cwd when building the hash map', () => {
268
+ const proc: ProcessInfo = {
269
+ pid: 1,
270
+ command: 'gemini',
271
+ cwd: '',
272
+ tty: 'ttys001',
273
+ startTime: new Date(),
274
+ };
275
+ writeSession(tmpHome, 'abc', 'session-x', {
276
+ sessionId: 's1',
277
+ projectHash: hashProjectRoot('/some/where'),
278
+ startTime: new Date().toISOString(),
279
+ lastUpdated: new Date().toISOString(),
280
+ kind: 'main',
281
+ messages: [],
282
+ });
283
+
284
+ const result = (adapter as any).discoverSessions([proc]);
285
+ expect(result.sessions).toEqual([]);
286
+ });
287
+
288
+ it('should ignore sessions whose projectHash does not match any process cwd', () => {
289
+ const proc: ProcessInfo = {
290
+ pid: 1,
291
+ command: 'gemini',
292
+ cwd: '/repo/a',
293
+ tty: 'ttys001',
294
+ startTime: new Date(),
295
+ };
296
+ writeSession(tmpHome, 'other', 'session-other', {
297
+ sessionId: 's-other',
298
+ projectHash: hashProjectRoot('/repo/different'),
299
+ startTime: new Date().toISOString(),
300
+ lastUpdated: new Date().toISOString(),
301
+ kind: 'main',
302
+ messages: [],
303
+ });
304
+
305
+ const result = (adapter as any).discoverSessions([proc]);
306
+ expect(result.sessions).toEqual([]);
307
+ });
308
+
309
+ it('should skip malformed JSON files and still return valid ones', () => {
310
+ const cwd = '/repo/valid';
311
+ const proc: ProcessInfo = {
312
+ pid: 1,
313
+ command: 'gemini',
314
+ cwd,
315
+ tty: 'ttys001',
316
+ startTime: new Date(),
317
+ };
318
+
319
+ const chatsDir = path.join(tmpHome, '.gemini', 'tmp', 'abc', 'chats');
320
+ fs.mkdirSync(chatsDir, { recursive: true });
321
+ fs.writeFileSync(path.join(chatsDir, 'session-bad.json'), '{ not valid');
322
+ writeSession(tmpHome, 'abc', 'session-good', {
323
+ sessionId: 's-good',
324
+ projectHash: hashProjectRoot(cwd),
325
+ startTime: new Date().toISOString(),
326
+ lastUpdated: new Date().toISOString(),
327
+ kind: 'main',
328
+ messages: [],
329
+ });
330
+
331
+ const result = (adapter as any).discoverSessions([proc]);
332
+ expect(result.sessions).toHaveLength(1);
333
+ expect(result.sessions[0].sessionId).toBe('s-good');
334
+ });
335
+
336
+ it('should match sessions whose projectHash is a parent of the process cwd (git root case)', () => {
337
+ const gitRoot = '/repo/monorepo';
338
+ const procCwd = '/repo/monorepo/packages/inner';
339
+ const proc: ProcessInfo = {
340
+ pid: 1,
341
+ command: 'gemini',
342
+ cwd: procCwd,
343
+ tty: 'ttys001',
344
+ startTime: new Date(),
345
+ };
346
+ writeSession(tmpHome, 'abc', 'session-rootmatch', {
347
+ sessionId: 's-root',
348
+ // Gemini CLI stores the hash of the walked-up project root,
349
+ // not the process CWD.
350
+ projectHash: hashProjectRoot(gitRoot),
351
+ startTime: new Date().toISOString(),
352
+ lastUpdated: new Date().toISOString(),
353
+ kind: 'main',
354
+ messages: [],
355
+ });
356
+
357
+ const result = (adapter as any).discoverSessions([proc]);
358
+ expect(result.sessions).toHaveLength(1);
359
+ expect(result.sessions[0].resolvedCwd).toBe(procCwd);
360
+ });
361
+
362
+ it('should skip files that do not start with "session-"', () => {
363
+ const cwd = '/repo/keep';
364
+ const proc: ProcessInfo = {
365
+ pid: 1,
366
+ command: 'gemini',
367
+ cwd,
368
+ tty: 'ttys001',
369
+ startTime: new Date(),
370
+ };
371
+
372
+ const chatsDir = path.join(tmpHome, '.gemini', 'tmp', 'abc', 'chats');
373
+ fs.mkdirSync(chatsDir, { recursive: true });
374
+ fs.writeFileSync(
375
+ path.join(chatsDir, 'notsession.json'),
376
+ JSON.stringify({
377
+ sessionId: 'skip',
378
+ projectHash: hashProjectRoot(cwd),
379
+ messages: [],
380
+ }),
381
+ );
382
+
383
+ const result = (adapter as any).discoverSessions([proc]);
384
+ expect(result.sessions).toEqual([]);
385
+ });
386
+ });
387
+
388
+ describe('helper methods', () => {
389
+ describe('determineStatus', () => {
390
+ it('should return "waiting" when the last message is from gemini', () => {
391
+ const session = {
392
+ sessionId: 's', projectPath: '', summary: '',
393
+ sessionStart: new Date(), lastActive: new Date(),
394
+ lastMessageType: 'gemini',
395
+ };
396
+ expect((adapter as any).determineStatus(session)).toBe(AgentStatus.WAITING);
397
+ });
398
+
399
+ it('should return "waiting" when the last message is from assistant', () => {
400
+ const session = {
401
+ sessionId: 's', projectPath: '', summary: '',
402
+ sessionStart: new Date(), lastActive: new Date(),
403
+ lastMessageType: 'assistant',
404
+ };
405
+ expect((adapter as any).determineStatus(session)).toBe(AgentStatus.WAITING);
406
+ });
407
+
408
+ it('should return "running" when the last message is from the user', () => {
409
+ const session = {
410
+ sessionId: 's', projectPath: '', summary: '',
411
+ sessionStart: new Date(), lastActive: new Date(),
412
+ lastMessageType: 'user',
413
+ };
414
+ expect((adapter as any).determineStatus(session)).toBe(AgentStatus.RUNNING);
415
+ });
416
+
417
+ it('should return "idle" when last activity is older than the threshold', () => {
418
+ const session = {
419
+ sessionId: 's', projectPath: '', summary: '',
420
+ sessionStart: new Date(),
421
+ lastActive: new Date(Date.now() - 10 * 60 * 1000),
422
+ lastMessageType: 'gemini',
423
+ };
424
+ expect((adapter as any).determineStatus(session)).toBe(AgentStatus.IDLE);
425
+ });
426
+ });
427
+
428
+ describe('parseSession', () => {
429
+ it('should parse a valid session file', () => {
430
+ const filePath = writeSession(tmpHome, 'p', 'session-a', {
431
+ sessionId: 's1',
432
+ projectHash: 'h',
433
+ startTime: '2026-04-18T00:00:00Z',
434
+ lastUpdated: '2026-04-18T00:05:00Z',
435
+ kind: 'main',
436
+ directories: ['/repo'],
437
+ messages: [
438
+ { id: 'm1', timestamp: '2026-04-18T00:00:01Z', type: 'user', content: 'hello' },
439
+ ],
440
+ });
441
+
442
+ const result = (adapter as any).parseSession(undefined, filePath);
443
+ expect(result).toMatchObject({
444
+ sessionId: 's1',
445
+ projectPath: '/repo',
446
+ summary: 'hello',
447
+ });
448
+ });
449
+
450
+ it('should parse from cached content without reading disk', () => {
451
+ const content = JSON.stringify({
452
+ sessionId: 's2',
453
+ projectHash: 'h',
454
+ startTime: '2026-04-18T00:00:00Z',
455
+ lastUpdated: '2026-04-18T00:00:00Z',
456
+ messages: [],
457
+ });
458
+
459
+ const result = (adapter as any).parseSession(content, '/does/not/exist.json');
460
+ expect(result?.sessionId).toBe('s2');
461
+ });
462
+
463
+ it('should return null for a missing file with no cached content', () => {
464
+ expect((adapter as any).parseSession(undefined, '/missing.json')).toBeNull();
465
+ });
466
+
467
+ it('should return null when the file is not valid JSON', () => {
468
+ const filePath = path.join(tmpHome, 'broken.json');
469
+ fs.writeFileSync(filePath, 'not json');
470
+ expect((adapter as any).parseSession(undefined, filePath)).toBeNull();
471
+ });
472
+
473
+ it('should return null when sessionId is missing', () => {
474
+ const filePath = path.join(tmpHome, 'no-id.json');
475
+ fs.writeFileSync(filePath, JSON.stringify({ messages: [] }));
476
+ expect((adapter as any).parseSession(undefined, filePath)).toBeNull();
477
+ });
478
+
479
+ it('should default the summary when no user message has content', () => {
480
+ const filePath = writeSession(tmpHome, 'p', 'session-empty', {
481
+ sessionId: 's3',
482
+ projectHash: 'h',
483
+ startTime: '2026-04-18T00:00:00Z',
484
+ lastUpdated: '2026-04-18T00:00:00Z',
485
+ messages: [
486
+ { id: 'm1', timestamp: '2026-04-18T00:00:01Z', type: 'gemini', content: 'only assistant' },
487
+ ],
488
+ });
489
+
490
+ const result = (adapter as any).parseSession(undefined, filePath);
491
+ expect(result?.summary).toBe('Gemini CLI session active');
492
+ });
493
+
494
+ it('should truncate long summaries to 120 characters', () => {
495
+ const longContent = 'x'.repeat(200);
496
+ const filePath = writeSession(tmpHome, 'p', 'session-long', {
497
+ sessionId: 's4',
498
+ projectHash: 'h',
499
+ startTime: '2026-04-18T00:00:00Z',
500
+ lastUpdated: '2026-04-18T00:00:00Z',
501
+ messages: [
502
+ { id: 'm1', timestamp: '2026-04-18T00:00:01Z', type: 'user', content: longContent },
503
+ ],
504
+ });
505
+
506
+ const result = (adapter as any).parseSession(undefined, filePath);
507
+ expect(result?.summary.length).toBe(120);
508
+ expect(result?.summary.endsWith('...')).toBe(true);
509
+ });
510
+
511
+ it('should extract summary when user content is an array of parts (real Gemini shape)', () => {
512
+ const filePath = writeSession(tmpHome, 'p', 'session-parts', {
513
+ sessionId: 's-parts',
514
+ projectHash: 'h',
515
+ startTime: '2026-04-18T00:00:00Z',
516
+ lastUpdated: '2026-04-18T00:00:00Z',
517
+ messages: [
518
+ {
519
+ id: 'm1',
520
+ timestamp: '2026-04-18T00:00:01Z',
521
+ type: 'user',
522
+ content: [{ text: 'hello from part' }, { text: ' continued' }],
523
+ },
524
+ ],
525
+ });
526
+
527
+ const result = (adapter as any).parseSession(undefined, filePath);
528
+ expect(result?.summary).toBe('hello from part continued');
529
+ });
530
+
531
+ it('should not throw when user content is an array and there is no displayContent', () => {
532
+ const filePath = writeSession(tmpHome, 'p', 'session-parts-only', {
533
+ sessionId: 's-parts-only',
534
+ projectHash: 'h',
535
+ startTime: '2026-04-18T00:00:00Z',
536
+ lastUpdated: '2026-04-18T00:00:00Z',
537
+ messages: [
538
+ {
539
+ id: 'm1',
540
+ timestamp: '2026-04-18T00:00:01Z',
541
+ type: 'user',
542
+ content: [{ text: 'only via parts' }],
543
+ },
544
+ ],
545
+ });
546
+
547
+ expect(() => (adapter as any).parseSession(undefined, filePath)).not.toThrow();
548
+ });
549
+
550
+ it('should drop non-text parts (data/file) when resolving user content', () => {
551
+ const filePath = writeSession(tmpHome, 'p', 'session-mixed-parts', {
552
+ sessionId: 's-mixed',
553
+ projectHash: 'h',
554
+ startTime: '2026-04-18T00:00:00Z',
555
+ lastUpdated: '2026-04-18T00:00:00Z',
556
+ messages: [
557
+ {
558
+ id: 'm1',
559
+ timestamp: '2026-04-18T00:00:01Z',
560
+ type: 'user',
561
+ content: [
562
+ { text: 'readable text' },
563
+ { inlineData: { mimeType: 'image/png', data: 'base64...' } },
564
+ { text: ' + more' },
565
+ ],
566
+ },
567
+ ],
568
+ });
569
+
570
+ const result = (adapter as any).parseSession(undefined, filePath);
571
+ expect(result?.summary).toBe('readable text + more');
572
+ });
573
+
574
+ it('should prefer lastUpdated over entry timestamp for lastActive', () => {
575
+ const filePath = writeSession(tmpHome, 'p', 'session-last', {
576
+ sessionId: 's5',
577
+ projectHash: 'h',
578
+ startTime: '2026-04-18T00:00:00Z',
579
+ lastUpdated: '2026-04-18T00:10:00Z',
580
+ messages: [
581
+ { id: 'm1', timestamp: '2026-04-18T00:00:01Z', type: 'user', content: 'hi' },
582
+ ],
583
+ });
584
+
585
+ const result = (adapter as any).parseSession(undefined, filePath);
586
+ expect(result?.lastActive.toISOString()).toBe('2026-04-18T00:10:00.000Z');
587
+ });
588
+ });
589
+ });
590
+
591
+ describe('getConversation', () => {
592
+ it('should return messages from a valid Gemini session file', () => {
593
+ const sessionPath = path.join(tmpHome, 'session-2026-04-18T00-00-id.json');
594
+ fs.writeFileSync(
595
+ sessionPath,
596
+ JSON.stringify({
597
+ sessionId: 'abc',
598
+ projectHash: 'hash',
599
+ startTime: '2026-04-18T00:00:00Z',
600
+ lastUpdated: '2026-04-18T00:00:00Z',
601
+ kind: 'main',
602
+ messages: [
603
+ { id: 'm1', timestamp: '2026-04-18T00:00:01Z', type: 'user', content: 'hi' },
604
+ { id: 'm2', timestamp: '2026-04-18T00:00:02Z', type: 'gemini', content: 'hello' },
605
+ { id: 'm3', timestamp: '2026-04-18T00:00:03Z', type: 'tool', content: 'unused' },
606
+ ],
607
+ }),
608
+ );
609
+
610
+ const messages = adapter.getConversation(sessionPath);
611
+ expect(messages).toEqual([
612
+ { role: 'user', content: 'hi', timestamp: '2026-04-18T00:00:01Z' },
613
+ { role: 'assistant', content: 'hello', timestamp: '2026-04-18T00:00:02Z' },
614
+ ]);
615
+ });
616
+
617
+ it('should include tool entries when verbose is true', () => {
618
+ const sessionPath = path.join(tmpHome, 'session-verbose.json');
619
+ fs.writeFileSync(
620
+ sessionPath,
621
+ JSON.stringify({
622
+ sessionId: 'abc',
623
+ projectHash: 'hash',
624
+ startTime: '2026-04-18T00:00:00Z',
625
+ lastUpdated: '2026-04-18T00:00:00Z',
626
+ kind: 'main',
627
+ messages: [
628
+ { id: 'm1', timestamp: '2026-04-18T00:00:01Z', type: 'tool', content: 'tool call' },
629
+ ],
630
+ }),
631
+ );
632
+
633
+ const messages = adapter.getConversation(sessionPath, { verbose: true });
634
+ expect(messages).toEqual([
635
+ { role: 'system', content: 'tool call', timestamp: '2026-04-18T00:00:01Z' },
636
+ ]);
637
+ });
638
+
639
+ it('should return empty array for missing or malformed files', () => {
640
+ expect(adapter.getConversation('/nonexistent/file.json')).toEqual([]);
641
+
642
+ const brokenPath = path.join(tmpHome, 'broken.json');
643
+ fs.writeFileSync(brokenPath, '{ not valid json');
644
+ expect(adapter.getConversation(brokenPath)).toEqual([]);
645
+ });
646
+
647
+ it('should prefer displayContent over content when both are present', () => {
648
+ const sessionPath = path.join(tmpHome, 'session-display.json');
649
+ fs.writeFileSync(
650
+ sessionPath,
651
+ JSON.stringify({
652
+ sessionId: 'abc',
653
+ messages: [
654
+ {
655
+ id: 'm1',
656
+ timestamp: '2026-04-18T00:00:01Z',
657
+ type: 'user',
658
+ content: 'raw',
659
+ displayContent: 'rendered',
660
+ },
661
+ ],
662
+ }),
663
+ );
664
+
665
+ const messages = adapter.getConversation(sessionPath);
666
+ expect(messages[0].content).toBe('rendered');
667
+ });
668
+
669
+ it('should skip entries with empty content', () => {
670
+ const sessionPath = path.join(tmpHome, 'session-empty.json');
671
+ fs.writeFileSync(
672
+ sessionPath,
673
+ JSON.stringify({
674
+ sessionId: 'abc',
675
+ messages: [
676
+ { id: 'm1', timestamp: '2026-04-18T00:00:01Z', type: 'user', content: '' },
677
+ { id: 'm2', timestamp: '2026-04-18T00:00:02Z', type: 'user', content: 'real' },
678
+ ],
679
+ }),
680
+ );
681
+
682
+ const messages = adapter.getConversation(sessionPath);
683
+ expect(messages).toHaveLength(1);
684
+ expect(messages[0].content).toBe('real');
685
+ });
686
+
687
+ it('should skip entries without a type', () => {
688
+ const sessionPath = path.join(tmpHome, 'session-no-type.json');
689
+ fs.writeFileSync(
690
+ sessionPath,
691
+ JSON.stringify({
692
+ sessionId: 'abc',
693
+ messages: [
694
+ { id: 'm1', timestamp: '2026-04-18T00:00:01Z', content: 'typeless' },
695
+ ],
696
+ }),
697
+ );
698
+
699
+ expect(adapter.getConversation(sessionPath)).toEqual([]);
700
+ });
701
+
702
+ it('should resolve user messages whose content is an array of text parts', () => {
703
+ const sessionPath = path.join(tmpHome, 'session-user-parts.json');
704
+ fs.writeFileSync(
705
+ sessionPath,
706
+ JSON.stringify({
707
+ sessionId: 'abc',
708
+ messages: [
709
+ {
710
+ id: 'm1',
711
+ timestamp: '2026-04-18T00:00:01Z',
712
+ type: 'user',
713
+ content: [{ text: 'hello' }, { text: ' world' }],
714
+ },
715
+ {
716
+ id: 'm2',
717
+ timestamp: '2026-04-18T00:00:02Z',
718
+ type: 'gemini',
719
+ content: 'hi there',
720
+ },
721
+ ],
722
+ }),
723
+ );
724
+
725
+ const messages = adapter.getConversation(sessionPath);
726
+ expect(messages).toEqual([
727
+ { role: 'user', content: 'hello world', timestamp: '2026-04-18T00:00:01Z' },
728
+ { role: 'assistant', content: 'hi there', timestamp: '2026-04-18T00:00:02Z' },
729
+ ]);
730
+ });
731
+
732
+ it('should not throw when content is an array but no part carries text', () => {
733
+ const sessionPath = path.join(tmpHome, 'session-no-text-parts.json');
734
+ fs.writeFileSync(
735
+ sessionPath,
736
+ JSON.stringify({
737
+ sessionId: 'abc',
738
+ messages: [
739
+ {
740
+ id: 'm1',
741
+ timestamp: '2026-04-18T00:00:01Z',
742
+ type: 'user',
743
+ content: [{ inlineData: { mimeType: 'image/png' } }],
744
+ },
745
+ ],
746
+ }),
747
+ );
748
+
749
+ expect(() => adapter.getConversation(sessionPath)).not.toThrow();
750
+ expect(adapter.getConversation(sessionPath)).toEqual([]);
751
+ });
752
+
753
+ it('should return empty array when messages is not an array', () => {
754
+ const sessionPath = path.join(tmpHome, 'session-bad-messages.json');
755
+ fs.writeFileSync(
756
+ sessionPath,
757
+ JSON.stringify({ sessionId: 'abc', messages: 'not-an-array' }),
758
+ );
759
+
760
+ expect(adapter.getConversation(sessionPath)).toEqual([]);
761
+ });
762
+ });
763
+ });
764
+
765
+ /**
766
+ * Write a Gemini session JSON to the temporary home under the expected
767
+ * ~/.gemini/tmp/<shortId>/chats/<fileName>.json layout. Returns the full path.
768
+ */
769
+ function writeSession(
770
+ home: string,
771
+ shortId: string,
772
+ fileName: string,
773
+ body: Record<string, unknown>,
774
+ ): string {
775
+ const chatsDir = path.join(home, '.gemini', 'tmp', shortId, 'chats');
776
+ fs.mkdirSync(chatsDir, { recursive: true });
777
+ const filePath = path.join(chatsDir, `${fileName}.json`);
778
+ fs.writeFileSync(filePath, JSON.stringify(body));
779
+ return filePath;
780
+ }
781
+
782
+ /**
783
+ * Mirror the projectHash algo used by Gemini CLI:
784
+ * sha256(projectRoot) as hex.
785
+ */
786
+ function hashProjectRoot(projectRoot: string): string {
787
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
788
+ const crypto = require('crypto');
789
+ return crypto.createHash('sha256').update(projectRoot).digest('hex');
790
+ }