@ai-devkit/agent-manager 0.16.0 → 0.17.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.
Files changed (97) hide show
  1. package/.swcrc +27 -0
  2. package/dist/AgentManager.js +72 -74
  3. package/dist/AgentManager.js.map +1 -1
  4. package/dist/__tests__/AgentManager.test.js +564 -0
  5. package/dist/__tests__/AgentManager.test.js.map +1 -0
  6. package/dist/__tests__/adapters/ClaudeCodeAdapter.test.js +2157 -0
  7. package/dist/__tests__/adapters/ClaudeCodeAdapter.test.js.map +1 -0
  8. package/dist/__tests__/adapters/CodexAdapter.test.js +1354 -0
  9. package/dist/__tests__/adapters/CodexAdapter.test.js.map +1 -0
  10. package/dist/__tests__/adapters/CopilotAdapter.test.js +500 -0
  11. package/dist/__tests__/adapters/CopilotAdapter.test.js.map +1 -0
  12. package/dist/__tests__/adapters/GeminiCliAdapter.test.js +1229 -0
  13. package/dist/__tests__/adapters/GeminiCliAdapter.test.js.map +1 -0
  14. package/dist/__tests__/adapters/OpenCodeAdapter.test.js +626 -0
  15. package/dist/__tests__/adapters/OpenCodeAdapter.test.js.map +1 -0
  16. package/dist/__tests__/terminal/TmuxManager.test.js +159 -0
  17. package/dist/__tests__/terminal/TmuxManager.test.js.map +1 -0
  18. package/dist/__tests__/terminal/TtyWriter.test.js +162 -0
  19. package/dist/__tests__/terminal/TtyWriter.test.js.map +1 -0
  20. package/dist/__tests__/utils/AgentRegistry.test.js +282 -0
  21. package/dist/__tests__/utils/AgentRegistry.test.js.map +1 -0
  22. package/dist/__tests__/utils/ClaudeSessionParser.test.js +312 -0
  23. package/dist/__tests__/utils/ClaudeSessionParser.test.js.map +1 -0
  24. package/dist/__tests__/utils/matching.test.js +324 -0
  25. package/dist/__tests__/utils/matching.test.js.map +1 -0
  26. package/dist/__tests__/utils/process.test.js +177 -0
  27. package/dist/__tests__/utils/process.test.js.map +1 -0
  28. package/dist/__tests__/utils/session.test.js +158 -0
  29. package/dist/__tests__/utils/session.test.js.map +1 -0
  30. package/dist/adapters/AgentAdapter.d.ts +1 -1
  31. package/dist/adapters/AgentAdapter.d.ts.map +1 -1
  32. package/dist/adapters/AgentAdapter.js +8 -7
  33. package/dist/adapters/AgentAdapter.js.map +1 -1
  34. package/dist/adapters/ClaudeCodeAdapter.js +66 -77
  35. package/dist/adapters/ClaudeCodeAdapter.js.map +1 -1
  36. package/dist/adapters/CodexAdapter.d.ts +9 -0
  37. package/dist/adapters/CodexAdapter.d.ts.map +1 -1
  38. package/dist/adapters/CodexAdapter.js +188 -141
  39. package/dist/adapters/CodexAdapter.js.map +1 -1
  40. package/dist/adapters/CopilotAdapter.d.ts +44 -0
  41. package/dist/adapters/CopilotAdapter.d.ts.map +1 -0
  42. package/dist/adapters/CopilotAdapter.js +314 -0
  43. package/dist/adapters/CopilotAdapter.js.map +1 -0
  44. package/dist/adapters/GeminiCliAdapter.d.ts +2 -0
  45. package/dist/adapters/GeminiCliAdapter.d.ts.map +1 -1
  46. package/dist/adapters/GeminiCliAdapter.js +138 -156
  47. package/dist/adapters/GeminiCliAdapter.js.map +1 -1
  48. package/dist/adapters/OpenCodeAdapter.js +60 -69
  49. package/dist/adapters/OpenCodeAdapter.js.map +1 -1
  50. package/dist/adapters/index.d.ts +1 -0
  51. package/dist/adapters/index.d.ts.map +1 -1
  52. package/dist/adapters/index.js +2 -0
  53. package/dist/adapters/index.js.map +1 -1
  54. package/dist/index.d.ts +1 -0
  55. package/dist/index.d.ts.map +1 -1
  56. package/dist/index.js +2 -0
  57. package/dist/index.js.map +1 -1
  58. package/dist/terminal/TerminalFocusManager.js +62 -49
  59. package/dist/terminal/TerminalFocusManager.js.map +1 -1
  60. package/dist/terminal/TmuxManager.js +59 -34
  61. package/dist/terminal/TmuxManager.js.map +1 -1
  62. package/dist/terminal/TtyWriter.js +37 -16
  63. package/dist/terminal/TtyWriter.js.map +1 -1
  64. package/dist/terminal/index.js +1 -0
  65. package/dist/terminal/index.js.map +1 -1
  66. package/dist/utils/AgentRegistry.js +41 -32
  67. package/dist/utils/AgentRegistry.js.map +1 -1
  68. package/dist/utils/ClaudeSessionParser.js +46 -87
  69. package/dist/utils/ClaudeSessionParser.js.map +1 -1
  70. package/dist/utils/agents.d.ts +1 -1
  71. package/dist/utils/agents.d.ts.map +1 -1
  72. package/dist/utils/agents.js +22 -11
  73. package/dist/utils/agents.js.map +1 -1
  74. package/dist/utils/applescript.js +3 -6
  75. package/dist/utils/applescript.js.map +1 -1
  76. package/dist/utils/index.js +1 -0
  77. package/dist/utils/index.js.map +1 -1
  78. package/dist/utils/matching.js +21 -29
  79. package/dist/utils/matching.js.map +1 -1
  80. package/dist/utils/process.js +77 -56
  81. package/dist/utils/process.js.map +1 -1
  82. package/dist/utils/session.js +20 -34
  83. package/dist/utils/session.js.map +1 -1
  84. package/dist/utils/sortAgents.js +6 -8
  85. package/dist/utils/sortAgents.js.map +1 -1
  86. package/package.json +11 -7
  87. package/src/__tests__/adapters/ClaudeCodeAdapter.test.ts +2 -0
  88. package/src/__tests__/adapters/CodexAdapter.test.ts +94 -0
  89. package/src/__tests__/adapters/CopilotAdapter.test.ts +411 -0
  90. package/src/__tests__/adapters/GeminiCliAdapter.test.ts +74 -1
  91. package/src/adapters/AgentAdapter.ts +1 -1
  92. package/src/adapters/CodexAdapter.ts +114 -6
  93. package/src/adapters/CopilotAdapter.ts +453 -0
  94. package/src/adapters/GeminiCliAdapter.ts +42 -3
  95. package/src/adapters/index.ts +1 -0
  96. package/src/index.ts +1 -0
  97. package/src/utils/agents.ts +1 -1
@@ -0,0 +1,1229 @@
1
+ /**
2
+ * Tests for GeminiCliAdapter
3
+ */ import * as fs from 'fs';
4
+ import * as os from 'os';
5
+ import * as path from 'path';
6
+ import { GeminiCliAdapter } from '../../adapters/GeminiCliAdapter.js';
7
+ import { AgentStatus } from '../../adapters/AgentAdapter.js';
8
+ import { AgentRegistry } from '../../utils/AgentRegistry.js';
9
+ import { listAgentProcesses, enrichProcesses } from '../../utils/process.js';
10
+ import { matchProcessesToSessions, generateAgentName } from '../../utils/matching.js';
11
+ import * as crypto from 'crypto';
12
+ vi.mock('../../utils/process.js', ()=>({
13
+ listAgentProcesses: vi.fn(),
14
+ enrichProcesses: vi.fn()
15
+ }));
16
+ vi.mock('../../utils/matching.js', ()=>({
17
+ matchProcessesToSessions: vi.fn(),
18
+ generateAgentName: vi.fn()
19
+ }));
20
+ const mockedListAgentProcesses = listAgentProcesses;
21
+ const mockedEnrichProcesses = enrichProcesses;
22
+ const mockedMatchProcessesToSessions = matchProcessesToSessions;
23
+ const mockedGenerateAgentName = generateAgentName;
24
+ describe('GeminiCliAdapter', ()=>{
25
+ let adapter;
26
+ let tmpHome;
27
+ beforeEach(()=>{
28
+ tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'gemini-adapter-test-'));
29
+ process.env.HOME = tmpHome;
30
+ adapter = new GeminiCliAdapter(new AgentRegistry(path.join(tmpHome, 'agents.json')));
31
+ mockedListAgentProcesses.mockReset();
32
+ mockedEnrichProcesses.mockReset();
33
+ mockedMatchProcessesToSessions.mockReset();
34
+ mockedGenerateAgentName.mockReset();
35
+ mockedEnrichProcesses.mockImplementation((procs)=>procs);
36
+ mockedMatchProcessesToSessions.mockReturnValue([]);
37
+ mockedGenerateAgentName.mockImplementation((cwd, pid)=>{
38
+ const folder = path.basename(cwd) || 'unknown';
39
+ return `${folder} (${pid})`;
40
+ });
41
+ });
42
+ afterEach(()=>{
43
+ fs.rmSync(tmpHome, {
44
+ recursive: true,
45
+ force: true
46
+ });
47
+ });
48
+ describe('initialization', ()=>{
49
+ it('should expose gemini_cli type', ()=>{
50
+ expect(adapter.type).toBe('gemini_cli');
51
+ });
52
+ });
53
+ describe('canHandle', ()=>{
54
+ it('should return true for plain gemini command', ()=>{
55
+ expect(adapter.canHandle({
56
+ pid: 1,
57
+ command: 'gemini',
58
+ cwd: '/repo',
59
+ tty: 'ttys001'
60
+ })).toBe(true);
61
+ });
62
+ it('should return true for gemini with full path (case-insensitive)', ()=>{
63
+ expect(adapter.canHandle({
64
+ pid: 2,
65
+ command: '/usr/local/bin/GEMINI --yolo',
66
+ cwd: '/repo',
67
+ tty: 'ttys002'
68
+ })).toBe(true);
69
+ });
70
+ it('should return false for non-gemini processes', ()=>{
71
+ expect(adapter.canHandle({
72
+ pid: 3,
73
+ command: 'node app.js',
74
+ cwd: '/repo',
75
+ tty: 'ttys003'
76
+ })).toBe(false);
77
+ });
78
+ it('should return false when "gemini" appears only in path arguments', ()=>{
79
+ expect(adapter.canHandle({
80
+ pid: 4,
81
+ command: 'node /path/to/gemini-runner.js',
82
+ cwd: '/repo',
83
+ tty: 'ttys004'
84
+ })).toBe(false);
85
+ });
86
+ it('should return true for Node-invoked gemini script (real install layout)', ()=>{
87
+ expect(adapter.canHandle({
88
+ pid: 5,
89
+ command: 'node /Users/foo/.volta/tools/image/node/24.14.0/bin/gemini --help',
90
+ cwd: '/repo',
91
+ tty: 'ttys005'
92
+ })).toBe(true);
93
+ });
94
+ it('should return true for Node-invoked gemini.js bundle entrypoint', ()=>{
95
+ expect(adapter.canHandle({
96
+ pid: 6,
97
+ command: 'node /opt/homebrew/lib/node_modules/@google/gemini-cli/bundle/gemini.js',
98
+ cwd: '/repo',
99
+ tty: 'ttys006'
100
+ })).toBe(true);
101
+ });
102
+ });
103
+ describe('detectAgents', ()=>{
104
+ it('should return empty array when no gemini processes are running', async ()=>{
105
+ mockedListAgentProcesses.mockReturnValue([]);
106
+ const agents = await adapter.detectAgents();
107
+ expect(agents).toEqual([]);
108
+ });
109
+ it('should filter non-gemini Node processes out of the node process pool', async ()=>{
110
+ const geminiProc = {
111
+ pid: 100,
112
+ command: 'node /Users/foo/.volta/tools/image/node/24.14.0/bin/gemini --help',
113
+ cwd: '/repo',
114
+ tty: 'ttys001',
115
+ startTime: new Date('2026-04-18T00:00:00Z')
116
+ };
117
+ const unrelatedNodeProc = {
118
+ pid: 200,
119
+ command: 'node /usr/local/bin/eslint src/',
120
+ cwd: '/other-repo',
121
+ tty: 'ttys002',
122
+ startTime: new Date('2026-04-18T00:00:00Z')
123
+ };
124
+ mockedListAgentProcesses.mockReturnValue([
125
+ geminiProc,
126
+ unrelatedNodeProc
127
+ ]);
128
+ const agents = await adapter.detectAgents();
129
+ expect(agents).toHaveLength(1);
130
+ expect(agents[0].pid).toBe(100);
131
+ });
132
+ it('should return process-only agents when no session files exist for the process', async ()=>{
133
+ const proc = {
134
+ pid: 1234,
135
+ command: 'gemini',
136
+ cwd: '/repo',
137
+ tty: 'ttys001',
138
+ startTime: new Date('2026-04-18T00:00:00Z')
139
+ };
140
+ mockedListAgentProcesses.mockReturnValue([
141
+ proc
142
+ ]);
143
+ const agents = await adapter.detectAgents();
144
+ expect(agents).toHaveLength(1);
145
+ expect(agents[0]).toMatchObject({
146
+ type: 'gemini_cli',
147
+ pid: 1234,
148
+ projectPath: '/repo',
149
+ status: AgentStatus.RUNNING,
150
+ sessionId: 'pid-1234'
151
+ });
152
+ });
153
+ it('should map a process to its matching session file via projectHash', async ()=>{
154
+ const cwd = '/repo/project-a';
155
+ const projectHash = hashProjectRoot(cwd);
156
+ const shortId = 'abc123';
157
+ const chatsDir = path.join(tmpHome, '.gemini', 'tmp', shortId, 'chats');
158
+ fs.mkdirSync(chatsDir, {
159
+ recursive: true
160
+ });
161
+ const sessionPath = path.join(chatsDir, 'session-2026-04-18T00-00-session1.json');
162
+ const sessionStart = new Date('2026-04-18T00:00:00Z').toISOString();
163
+ fs.writeFileSync(sessionPath, JSON.stringify({
164
+ sessionId: 'session1',
165
+ projectHash,
166
+ startTime: sessionStart,
167
+ lastUpdated: sessionStart,
168
+ kind: 'main',
169
+ messages: [
170
+ {
171
+ id: 'm1',
172
+ timestamp: sessionStart,
173
+ type: 'user',
174
+ content: 'hello gemini'
175
+ }
176
+ ]
177
+ }));
178
+ const proc = {
179
+ pid: 42,
180
+ command: 'gemini',
181
+ cwd,
182
+ tty: 'ttys001',
183
+ startTime: new Date('2026-04-18T00:00:00Z')
184
+ };
185
+ mockedListAgentProcesses.mockReturnValue([
186
+ proc
187
+ ]);
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
+ const agents = await adapter.detectAgents();
202
+ expect(agents).toHaveLength(1);
203
+ expect(agents[0]).toMatchObject({
204
+ type: 'gemini_cli',
205
+ pid: 42,
206
+ projectPath: cwd,
207
+ sessionId: 'session1',
208
+ sessionFilePath: sessionPath
209
+ });
210
+ expect(agents[0].summary).toContain('hello gemini');
211
+ });
212
+ it('should collapse Gemini wrapper and child processes matched to the same session', async ()=>{
213
+ const cwd = '/repo/project-a';
214
+ const projectHash = hashProjectRoot(cwd);
215
+ const shortId = 'abc123';
216
+ const chatsDir = path.join(tmpHome, '.gemini', 'tmp', shortId, 'chats');
217
+ fs.mkdirSync(chatsDir, {
218
+ recursive: true
219
+ });
220
+ const sessionPath = path.join(chatsDir, 'session-2026-04-18T00-00-session1.json');
221
+ const sessionStart = new Date('2026-04-18T00:00:00Z').toISOString();
222
+ fs.writeFileSync(sessionPath, JSON.stringify({
223
+ sessionId: 'session1',
224
+ projectHash,
225
+ startTime: sessionStart,
226
+ lastUpdated: sessionStart,
227
+ kind: 'main',
228
+ directories: [
229
+ cwd
230
+ ],
231
+ messages: [
232
+ {
233
+ id: 'm1',
234
+ timestamp: sessionStart,
235
+ type: 'user',
236
+ content: 'hello gemini'
237
+ }
238
+ ]
239
+ }));
240
+ const wrapperProc = {
241
+ pid: 88394,
242
+ command: 'node /Users/foo/.nvm/versions/node/v23.9.0/bin/gemini',
243
+ cwd,
244
+ tty: 'ttys015',
245
+ startTime: new Date('2026-04-18T00:00:00Z')
246
+ };
247
+ const childProc = {
248
+ pid: 88460,
249
+ command: '/Users/foo/.nvm/versions/node/v24.13.1/bin/node /Users/foo/.nvm/versions/node/v23.9.0/bin/gemini',
250
+ cwd,
251
+ tty: 'ttys015',
252
+ startTime: new Date('2026-04-18T00:00:01Z')
253
+ };
254
+ mockedListAgentProcesses.mockReturnValue([
255
+ wrapperProc,
256
+ childProc
257
+ ]);
258
+ mockedMatchProcessesToSessions.mockReturnValue([
259
+ {
260
+ process: wrapperProc,
261
+ session: {
262
+ sessionId: 'session1',
263
+ filePath: sessionPath,
264
+ projectDir: chatsDir,
265
+ birthtimeMs: Date.now(),
266
+ resolvedCwd: cwd
267
+ },
268
+ deltaMs: 0
269
+ },
270
+ {
271
+ process: childProc,
272
+ session: {
273
+ sessionId: 'session1',
274
+ filePath: sessionPath,
275
+ projectDir: chatsDir,
276
+ birthtimeMs: Date.now(),
277
+ resolvedCwd: cwd
278
+ },
279
+ deltaMs: 0
280
+ }
281
+ ]);
282
+ const agents = await adapter.detectAgents();
283
+ expect(agents).toHaveLength(1);
284
+ expect(agents[0]).toMatchObject({
285
+ pid: 88460,
286
+ sessionId: 'session1',
287
+ sessionFilePath: sessionPath
288
+ });
289
+ });
290
+ it('should not match sessions from other projects', async ()=>{
291
+ const procCwd = '/repo/project-a';
292
+ const otherCwd = '/repo/project-b';
293
+ const otherHash = hashProjectRoot(otherCwd);
294
+ const chatsDir = path.join(tmpHome, '.gemini', 'tmp', 'other', 'chats');
295
+ fs.mkdirSync(chatsDir, {
296
+ recursive: true
297
+ });
298
+ const sessionPath = path.join(chatsDir, 'session-2026-04-18T00-00-other.json');
299
+ fs.writeFileSync(sessionPath, JSON.stringify({
300
+ sessionId: 'other-session',
301
+ projectHash: otherHash,
302
+ startTime: new Date().toISOString(),
303
+ lastUpdated: new Date().toISOString(),
304
+ kind: 'main',
305
+ messages: []
306
+ }));
307
+ const proc = {
308
+ pid: 7,
309
+ command: 'gemini',
310
+ cwd: procCwd,
311
+ tty: 'ttys001',
312
+ startTime: new Date()
313
+ };
314
+ mockedListAgentProcesses.mockReturnValue([
315
+ proc
316
+ ]);
317
+ const agents = await adapter.detectAgents();
318
+ const candidateSessions = mockedMatchProcessesToSessions.mock.calls[0]?.[1] ?? [];
319
+ expect(candidateSessions).toHaveLength(0);
320
+ expect(agents).toHaveLength(1);
321
+ expect(agents[0].sessionId).toBe(`pid-${proc.pid}`);
322
+ });
323
+ });
324
+ describe('detectAgents — registry cache short-circuit', ()=>{
325
+ let regPath;
326
+ let registry;
327
+ let cachedAdapter;
328
+ let sessionFilePath;
329
+ function registerEntry(over = {}) {
330
+ registry.register({
331
+ name: 'gemini-100',
332
+ type: 'gemini_cli',
333
+ pid: 100,
334
+ tmuxSession: '',
335
+ cwd: '/repo-a',
336
+ startedAt: '2026-05-30T00:00:00.000Z',
337
+ sessionId: 's-cached',
338
+ sessionFilePath,
339
+ ...over
340
+ });
341
+ }
342
+ beforeEach(()=>{
343
+ regPath = path.join(tmpHome, 'agents.json');
344
+ registry = new AgentRegistry(regPath);
345
+ cachedAdapter = new GeminiCliAdapter(registry);
346
+ const now = new Date().toISOString();
347
+ sessionFilePath = path.join(tmpHome, 'gemini-session.json');
348
+ fs.writeFileSync(sessionFilePath, JSON.stringify({
349
+ sessionId: 's-cached',
350
+ projectHash: 'h',
351
+ startTime: now,
352
+ lastUpdated: now,
353
+ directories: [
354
+ '/repo-a'
355
+ ],
356
+ messages: [
357
+ {
358
+ id: 'm1',
359
+ timestamp: now,
360
+ type: 'user',
361
+ content: 'Hello from gemini cache'
362
+ }
363
+ ]
364
+ }));
365
+ });
366
+ it('short-circuits matching when registry has a valid entry', async ()=>{
367
+ registerEntry();
368
+ const proc = {
369
+ pid: 100,
370
+ command: 'node /path/to/gemini --help',
371
+ cwd: '/repo-a',
372
+ tty: 'ttys001',
373
+ startTime: new Date()
374
+ };
375
+ mockedListAgentProcesses.mockReturnValue([
376
+ proc
377
+ ]);
378
+ const agents = await cachedAdapter.detectAgents();
379
+ expect(agents).toHaveLength(1);
380
+ expect(agents[0]).toMatchObject({
381
+ type: 'gemini_cli',
382
+ pid: 100,
383
+ sessionId: 's-cached',
384
+ summary: 'Hello from gemini cache'
385
+ });
386
+ expect(mockedMatchProcessesToSessions).not.toHaveBeenCalled();
387
+ });
388
+ it('falls through when no registry entry exists for the pid', async ()=>{
389
+ const proc = {
390
+ pid: 100,
391
+ command: 'node /path/to/gemini --help',
392
+ cwd: '/repo-a',
393
+ tty: 'ttys001',
394
+ startTime: new Date()
395
+ };
396
+ mockedListAgentProcesses.mockReturnValue([
397
+ proc
398
+ ]);
399
+ const agents = await cachedAdapter.detectAgents();
400
+ expect(agents[0].sessionId).toBe('pid-100');
401
+ });
402
+ it('falls through when registry entry type does not match', async ()=>{
403
+ registerEntry({
404
+ type: 'claude'
405
+ });
406
+ const proc = {
407
+ pid: 100,
408
+ command: 'node /path/to/gemini --help',
409
+ cwd: '/repo-a',
410
+ tty: 'ttys001',
411
+ startTime: new Date()
412
+ };
413
+ mockedListAgentProcesses.mockReturnValue([
414
+ proc
415
+ ]);
416
+ const agents = await cachedAdapter.detectAgents();
417
+ expect(agents[0].sessionId).toBe('pid-100');
418
+ });
419
+ it('falls through when the cached session file no longer exists', async ()=>{
420
+ registerEntry({
421
+ sessionFilePath: path.join(tmpHome, 'deleted.json')
422
+ });
423
+ const proc = {
424
+ pid: 100,
425
+ command: 'node /path/to/gemini --help',
426
+ cwd: '/repo-a',
427
+ tty: 'ttys001',
428
+ startTime: new Date()
429
+ };
430
+ mockedListAgentProcesses.mockReturnValue([
431
+ proc
432
+ ]);
433
+ const agents = await cachedAdapter.detectAgents();
434
+ expect(agents[0].sessionId).toBe('pid-100');
435
+ });
436
+ });
437
+ describe('discoverSessions', ()=>{
438
+ it('should return empty when ~/.gemini/tmp does not exist', ()=>{
439
+ const proc = {
440
+ pid: 1,
441
+ command: 'gemini',
442
+ cwd: '/repo',
443
+ tty: 'ttys001',
444
+ startTime: new Date()
445
+ };
446
+ // tmp dir absent by default
447
+ const result = adapter.discoverSessions([
448
+ proc
449
+ ]);
450
+ expect(result.sessions).toEqual([]);
451
+ expect(result.contentCache.size).toBe(0);
452
+ });
453
+ it('should skip processes with empty cwd when building the hash map', ()=>{
454
+ const proc = {
455
+ pid: 1,
456
+ command: 'gemini',
457
+ cwd: '',
458
+ tty: 'ttys001',
459
+ startTime: new Date()
460
+ };
461
+ writeSession(tmpHome, 'abc', 'session-x', {
462
+ sessionId: 's1',
463
+ projectHash: hashProjectRoot('/some/where'),
464
+ startTime: new Date().toISOString(),
465
+ lastUpdated: new Date().toISOString(),
466
+ kind: 'main',
467
+ messages: []
468
+ });
469
+ const result = adapter.discoverSessions([
470
+ proc
471
+ ]);
472
+ expect(result.sessions).toEqual([]);
473
+ });
474
+ it('should ignore sessions whose projectHash does not match any process cwd', ()=>{
475
+ const proc = {
476
+ pid: 1,
477
+ command: 'gemini',
478
+ cwd: '/repo/a',
479
+ tty: 'ttys001',
480
+ startTime: new Date()
481
+ };
482
+ writeSession(tmpHome, 'other', 'session-other', {
483
+ sessionId: 's-other',
484
+ projectHash: hashProjectRoot('/repo/different'),
485
+ startTime: new Date().toISOString(),
486
+ lastUpdated: new Date().toISOString(),
487
+ kind: 'main',
488
+ messages: []
489
+ });
490
+ const result = adapter.discoverSessions([
491
+ proc
492
+ ]);
493
+ expect(result.sessions).toEqual([]);
494
+ });
495
+ it('should skip malformed JSON files and still return valid ones', ()=>{
496
+ const cwd = '/repo/valid';
497
+ const proc = {
498
+ pid: 1,
499
+ command: 'gemini',
500
+ cwd,
501
+ tty: 'ttys001',
502
+ startTime: new Date()
503
+ };
504
+ const chatsDir = path.join(tmpHome, '.gemini', 'tmp', 'abc', 'chats');
505
+ fs.mkdirSync(chatsDir, {
506
+ recursive: true
507
+ });
508
+ fs.writeFileSync(path.join(chatsDir, 'session-bad.json'), '{ not valid');
509
+ writeSession(tmpHome, 'abc', 'session-good', {
510
+ sessionId: 's-good',
511
+ projectHash: hashProjectRoot(cwd),
512
+ startTime: new Date().toISOString(),
513
+ lastUpdated: new Date().toISOString(),
514
+ kind: 'main',
515
+ messages: []
516
+ });
517
+ const result = adapter.discoverSessions([
518
+ proc
519
+ ]);
520
+ expect(result.sessions).toHaveLength(1);
521
+ expect(result.sessions[0].sessionId).toBe('s-good');
522
+ });
523
+ it('should match sessions whose projectHash is a parent of the process cwd (git root case)', ()=>{
524
+ const gitRoot = '/repo/monorepo';
525
+ const procCwd = '/repo/monorepo/packages/inner';
526
+ const proc = {
527
+ pid: 1,
528
+ command: 'gemini',
529
+ cwd: procCwd,
530
+ tty: 'ttys001',
531
+ startTime: new Date()
532
+ };
533
+ writeSession(tmpHome, 'abc', 'session-rootmatch', {
534
+ sessionId: 's-root',
535
+ // Gemini CLI stores the hash of the walked-up project root,
536
+ // not the process CWD.
537
+ projectHash: hashProjectRoot(gitRoot),
538
+ startTime: new Date().toISOString(),
539
+ lastUpdated: new Date().toISOString(),
540
+ kind: 'main',
541
+ messages: []
542
+ });
543
+ const result = adapter.discoverSessions([
544
+ proc
545
+ ]);
546
+ expect(result.sessions).toHaveLength(1);
547
+ expect(result.sessions[0].resolvedCwd).toBe(procCwd);
548
+ });
549
+ it('should skip files that do not start with "session-"', ()=>{
550
+ const cwd = '/repo/keep';
551
+ const proc = {
552
+ pid: 1,
553
+ command: 'gemini',
554
+ cwd,
555
+ tty: 'ttys001',
556
+ startTime: new Date()
557
+ };
558
+ const chatsDir = path.join(tmpHome, '.gemini', 'tmp', 'abc', 'chats');
559
+ fs.mkdirSync(chatsDir, {
560
+ recursive: true
561
+ });
562
+ fs.writeFileSync(path.join(chatsDir, 'notsession.json'), JSON.stringify({
563
+ sessionId: 'skip',
564
+ projectHash: hashProjectRoot(cwd),
565
+ messages: []
566
+ }));
567
+ const result = adapter.discoverSessions([
568
+ proc
569
+ ]);
570
+ expect(result.sessions).toEqual([]);
571
+ });
572
+ });
573
+ describe('helper methods', ()=>{
574
+ describe('determineStatus', ()=>{
575
+ it('should return "waiting" when the last message is from gemini', ()=>{
576
+ const session = {
577
+ sessionId: 's',
578
+ projectPath: '',
579
+ summary: '',
580
+ sessionStart: new Date(),
581
+ lastActive: new Date(),
582
+ lastMessageType: 'gemini'
583
+ };
584
+ expect(adapter.determineStatus(session)).toBe(AgentStatus.WAITING);
585
+ });
586
+ it('should return "waiting" when the last message is from assistant', ()=>{
587
+ const session = {
588
+ sessionId: 's',
589
+ projectPath: '',
590
+ summary: '',
591
+ sessionStart: new Date(),
592
+ lastActive: new Date(),
593
+ lastMessageType: 'assistant'
594
+ };
595
+ expect(adapter.determineStatus(session)).toBe(AgentStatus.WAITING);
596
+ });
597
+ it('should return "running" when the last message is from the user', ()=>{
598
+ const session = {
599
+ sessionId: 's',
600
+ projectPath: '',
601
+ summary: '',
602
+ sessionStart: new Date(),
603
+ lastActive: new Date(),
604
+ lastMessageType: 'user'
605
+ };
606
+ expect(adapter.determineStatus(session)).toBe(AgentStatus.RUNNING);
607
+ });
608
+ it('should return "idle" when last activity is older than the threshold', ()=>{
609
+ const session = {
610
+ sessionId: 's',
611
+ projectPath: '',
612
+ summary: '',
613
+ sessionStart: new Date(),
614
+ lastActive: new Date(Date.now() - 10 * 60 * 1000),
615
+ lastMessageType: 'gemini'
616
+ };
617
+ expect(adapter.determineStatus(session)).toBe(AgentStatus.IDLE);
618
+ });
619
+ });
620
+ describe('parseSession', ()=>{
621
+ it('should parse a valid session file', ()=>{
622
+ const filePath = writeSession(tmpHome, 'p', 'session-a', {
623
+ sessionId: 's1',
624
+ projectHash: 'h',
625
+ startTime: '2026-04-18T00:00:00Z',
626
+ lastUpdated: '2026-04-18T00:05:00Z',
627
+ kind: 'main',
628
+ directories: [
629
+ '/repo'
630
+ ],
631
+ messages: [
632
+ {
633
+ id: 'm1',
634
+ timestamp: '2026-04-18T00:00:01Z',
635
+ type: 'user',
636
+ content: 'hello'
637
+ }
638
+ ]
639
+ });
640
+ const result = adapter.parseSession(undefined, filePath);
641
+ expect(result).toMatchObject({
642
+ sessionId: 's1',
643
+ projectPath: '/repo',
644
+ summary: 'hello'
645
+ });
646
+ });
647
+ it('should parse from cached content without reading disk', ()=>{
648
+ const content = JSON.stringify({
649
+ sessionId: 's2',
650
+ projectHash: 'h',
651
+ startTime: '2026-04-18T00:00:00Z',
652
+ lastUpdated: '2026-04-18T00:00:00Z',
653
+ messages: []
654
+ });
655
+ const result = adapter.parseSession(content, '/does/not/exist.json');
656
+ expect(result?.sessionId).toBe('s2');
657
+ });
658
+ it('should return null for a missing file with no cached content', ()=>{
659
+ expect(adapter.parseSession(undefined, '/missing.json')).toBeNull();
660
+ });
661
+ it('should return null when the file is not valid JSON', ()=>{
662
+ const filePath = path.join(tmpHome, 'broken.json');
663
+ fs.writeFileSync(filePath, 'not json');
664
+ expect(adapter.parseSession(undefined, filePath)).toBeNull();
665
+ });
666
+ it('should return null when sessionId is missing', ()=>{
667
+ const filePath = path.join(tmpHome, 'no-id.json');
668
+ fs.writeFileSync(filePath, JSON.stringify({
669
+ messages: []
670
+ }));
671
+ expect(adapter.parseSession(undefined, filePath)).toBeNull();
672
+ });
673
+ it('should default the summary when no user message has content', ()=>{
674
+ const filePath = writeSession(tmpHome, 'p', 'session-empty', {
675
+ sessionId: 's3',
676
+ projectHash: 'h',
677
+ startTime: '2026-04-18T00:00:00Z',
678
+ lastUpdated: '2026-04-18T00:00:00Z',
679
+ messages: [
680
+ {
681
+ id: 'm1',
682
+ timestamp: '2026-04-18T00:00:01Z',
683
+ type: 'gemini',
684
+ content: 'only assistant'
685
+ }
686
+ ]
687
+ });
688
+ const result = adapter.parseSession(undefined, filePath);
689
+ expect(result?.summary).toBe('Gemini CLI session active');
690
+ });
691
+ it('should truncate long summaries to 120 characters', ()=>{
692
+ const longContent = 'x'.repeat(200);
693
+ const filePath = writeSession(tmpHome, 'p', 'session-long', {
694
+ sessionId: 's4',
695
+ projectHash: 'h',
696
+ startTime: '2026-04-18T00:00:00Z',
697
+ lastUpdated: '2026-04-18T00:00:00Z',
698
+ messages: [
699
+ {
700
+ id: 'm1',
701
+ timestamp: '2026-04-18T00:00:01Z',
702
+ type: 'user',
703
+ content: longContent
704
+ }
705
+ ]
706
+ });
707
+ const result = adapter.parseSession(undefined, filePath);
708
+ expect(result?.summary.length).toBe(120);
709
+ expect(result?.summary.endsWith('...')).toBe(true);
710
+ });
711
+ it('should extract summary when user content is an array of parts (real Gemini shape)', ()=>{
712
+ const filePath = writeSession(tmpHome, 'p', 'session-parts', {
713
+ sessionId: 's-parts',
714
+ projectHash: 'h',
715
+ startTime: '2026-04-18T00:00:00Z',
716
+ lastUpdated: '2026-04-18T00:00:00Z',
717
+ messages: [
718
+ {
719
+ id: 'm1',
720
+ timestamp: '2026-04-18T00:00:01Z',
721
+ type: 'user',
722
+ content: [
723
+ {
724
+ text: 'hello from part'
725
+ },
726
+ {
727
+ text: ' continued'
728
+ }
729
+ ]
730
+ }
731
+ ]
732
+ });
733
+ const result = adapter.parseSession(undefined, filePath);
734
+ expect(result?.summary).toBe('hello from part continued');
735
+ });
736
+ it('should not throw when user content is an array and there is no displayContent', ()=>{
737
+ const filePath = writeSession(tmpHome, 'p', 'session-parts-only', {
738
+ sessionId: 's-parts-only',
739
+ projectHash: 'h',
740
+ startTime: '2026-04-18T00:00:00Z',
741
+ lastUpdated: '2026-04-18T00:00:00Z',
742
+ messages: [
743
+ {
744
+ id: 'm1',
745
+ timestamp: '2026-04-18T00:00:01Z',
746
+ type: 'user',
747
+ content: [
748
+ {
749
+ text: 'only via parts'
750
+ }
751
+ ]
752
+ }
753
+ ]
754
+ });
755
+ expect(()=>adapter.parseSession(undefined, filePath)).not.toThrow();
756
+ });
757
+ it('should drop non-text parts (data/file) when resolving user content', ()=>{
758
+ const filePath = writeSession(tmpHome, 'p', 'session-mixed-parts', {
759
+ sessionId: 's-mixed',
760
+ projectHash: 'h',
761
+ startTime: '2026-04-18T00:00:00Z',
762
+ lastUpdated: '2026-04-18T00:00:00Z',
763
+ messages: [
764
+ {
765
+ id: 'm1',
766
+ timestamp: '2026-04-18T00:00:01Z',
767
+ type: 'user',
768
+ content: [
769
+ {
770
+ text: 'readable text'
771
+ },
772
+ {
773
+ inlineData: {
774
+ mimeType: 'image/png',
775
+ data: 'base64...'
776
+ }
777
+ },
778
+ {
779
+ text: ' + more'
780
+ }
781
+ ]
782
+ }
783
+ ]
784
+ });
785
+ const result = adapter.parseSession(undefined, filePath);
786
+ expect(result?.summary).toBe('readable text + more');
787
+ });
788
+ it('should prefer lastUpdated over entry timestamp for lastActive', ()=>{
789
+ const filePath = writeSession(tmpHome, 'p', 'session-last', {
790
+ sessionId: 's5',
791
+ projectHash: 'h',
792
+ startTime: '2026-04-18T00:00:00Z',
793
+ lastUpdated: '2026-04-18T00:10:00Z',
794
+ messages: [
795
+ {
796
+ id: 'm1',
797
+ timestamp: '2026-04-18T00:00:01Z',
798
+ type: 'user',
799
+ content: 'hi'
800
+ }
801
+ ]
802
+ });
803
+ const result = adapter.parseSession(undefined, filePath);
804
+ expect(result?.lastActive.toISOString()).toBe('2026-04-18T00:10:00.000Z');
805
+ });
806
+ });
807
+ });
808
+ describe('getConversation', ()=>{
809
+ it('should return messages from a valid Gemini session file', ()=>{
810
+ const sessionPath = path.join(tmpHome, 'session-2026-04-18T00-00-id.json');
811
+ fs.writeFileSync(sessionPath, JSON.stringify({
812
+ sessionId: 'abc',
813
+ projectHash: 'hash',
814
+ startTime: '2026-04-18T00:00:00Z',
815
+ lastUpdated: '2026-04-18T00:00:00Z',
816
+ kind: 'main',
817
+ messages: [
818
+ {
819
+ id: 'm1',
820
+ timestamp: '2026-04-18T00:00:01Z',
821
+ type: 'user',
822
+ content: 'hi'
823
+ },
824
+ {
825
+ id: 'm2',
826
+ timestamp: '2026-04-18T00:00:02Z',
827
+ type: 'gemini',
828
+ content: 'hello'
829
+ },
830
+ {
831
+ id: 'm3',
832
+ timestamp: '2026-04-18T00:00:03Z',
833
+ type: 'tool',
834
+ content: 'unused'
835
+ }
836
+ ]
837
+ }));
838
+ const messages = adapter.getConversation(sessionPath);
839
+ expect(messages).toEqual([
840
+ {
841
+ role: 'user',
842
+ content: 'hi',
843
+ timestamp: '2026-04-18T00:00:01Z'
844
+ },
845
+ {
846
+ role: 'assistant',
847
+ content: 'hello',
848
+ timestamp: '2026-04-18T00:00:02Z'
849
+ }
850
+ ]);
851
+ });
852
+ it('should include tool entries when verbose is true', ()=>{
853
+ const sessionPath = path.join(tmpHome, 'session-verbose.json');
854
+ fs.writeFileSync(sessionPath, JSON.stringify({
855
+ sessionId: 'abc',
856
+ projectHash: 'hash',
857
+ startTime: '2026-04-18T00:00:00Z',
858
+ lastUpdated: '2026-04-18T00:00:00Z',
859
+ kind: 'main',
860
+ messages: [
861
+ {
862
+ id: 'm1',
863
+ timestamp: '2026-04-18T00:00:01Z',
864
+ type: 'tool',
865
+ content: 'tool call'
866
+ }
867
+ ]
868
+ }));
869
+ const messages = adapter.getConversation(sessionPath, {
870
+ verbose: true
871
+ });
872
+ expect(messages).toEqual([
873
+ {
874
+ role: 'system',
875
+ content: 'tool call',
876
+ timestamp: '2026-04-18T00:00:01Z'
877
+ }
878
+ ]);
879
+ });
880
+ it('should return empty array for missing or malformed files', ()=>{
881
+ expect(adapter.getConversation('/nonexistent/file.json')).toEqual([]);
882
+ const brokenPath = path.join(tmpHome, 'broken.json');
883
+ fs.writeFileSync(brokenPath, '{ not valid json');
884
+ expect(adapter.getConversation(brokenPath)).toEqual([]);
885
+ });
886
+ it('should prefer displayContent over content when both are present', ()=>{
887
+ const sessionPath = path.join(tmpHome, 'session-display.json');
888
+ fs.writeFileSync(sessionPath, JSON.stringify({
889
+ sessionId: 'abc',
890
+ messages: [
891
+ {
892
+ id: 'm1',
893
+ timestamp: '2026-04-18T00:00:01Z',
894
+ type: 'user',
895
+ content: 'raw',
896
+ displayContent: 'rendered'
897
+ }
898
+ ]
899
+ }));
900
+ const messages = adapter.getConversation(sessionPath);
901
+ expect(messages[0].content).toBe('rendered');
902
+ });
903
+ it('should skip entries with empty content', ()=>{
904
+ const sessionPath = path.join(tmpHome, 'session-empty.json');
905
+ fs.writeFileSync(sessionPath, JSON.stringify({
906
+ sessionId: 'abc',
907
+ messages: [
908
+ {
909
+ id: 'm1',
910
+ timestamp: '2026-04-18T00:00:01Z',
911
+ type: 'user',
912
+ content: ''
913
+ },
914
+ {
915
+ id: 'm2',
916
+ timestamp: '2026-04-18T00:00:02Z',
917
+ type: 'user',
918
+ content: 'real'
919
+ }
920
+ ]
921
+ }));
922
+ const messages = adapter.getConversation(sessionPath);
923
+ expect(messages).toHaveLength(1);
924
+ expect(messages[0].content).toBe('real');
925
+ });
926
+ it('should skip entries without a type', ()=>{
927
+ const sessionPath = path.join(tmpHome, 'session-no-type.json');
928
+ fs.writeFileSync(sessionPath, JSON.stringify({
929
+ sessionId: 'abc',
930
+ messages: [
931
+ {
932
+ id: 'm1',
933
+ timestamp: '2026-04-18T00:00:01Z',
934
+ content: 'typeless'
935
+ }
936
+ ]
937
+ }));
938
+ expect(adapter.getConversation(sessionPath)).toEqual([]);
939
+ });
940
+ it('should resolve user messages whose content is an array of text parts', ()=>{
941
+ const sessionPath = path.join(tmpHome, 'session-user-parts.json');
942
+ fs.writeFileSync(sessionPath, JSON.stringify({
943
+ sessionId: 'abc',
944
+ messages: [
945
+ {
946
+ id: 'm1',
947
+ timestamp: '2026-04-18T00:00:01Z',
948
+ type: 'user',
949
+ content: [
950
+ {
951
+ text: 'hello'
952
+ },
953
+ {
954
+ text: ' world'
955
+ }
956
+ ]
957
+ },
958
+ {
959
+ id: 'm2',
960
+ timestamp: '2026-04-18T00:00:02Z',
961
+ type: 'gemini',
962
+ content: 'hi there'
963
+ }
964
+ ]
965
+ }));
966
+ const messages = adapter.getConversation(sessionPath);
967
+ expect(messages).toEqual([
968
+ {
969
+ role: 'user',
970
+ content: 'hello world',
971
+ timestamp: '2026-04-18T00:00:01Z'
972
+ },
973
+ {
974
+ role: 'assistant',
975
+ content: 'hi there',
976
+ timestamp: '2026-04-18T00:00:02Z'
977
+ }
978
+ ]);
979
+ });
980
+ it('should not throw when content is an array but no part carries text', ()=>{
981
+ const sessionPath = path.join(tmpHome, 'session-no-text-parts.json');
982
+ fs.writeFileSync(sessionPath, JSON.stringify({
983
+ sessionId: 'abc',
984
+ messages: [
985
+ {
986
+ id: 'm1',
987
+ timestamp: '2026-04-18T00:00:01Z',
988
+ type: 'user',
989
+ content: [
990
+ {
991
+ inlineData: {
992
+ mimeType: 'image/png'
993
+ }
994
+ }
995
+ ]
996
+ }
997
+ ]
998
+ }));
999
+ expect(()=>adapter.getConversation(sessionPath)).not.toThrow();
1000
+ expect(adapter.getConversation(sessionPath)).toEqual([]);
1001
+ });
1002
+ it('should return empty array when messages is not an array', ()=>{
1003
+ const sessionPath = path.join(tmpHome, 'session-bad-messages.json');
1004
+ fs.writeFileSync(sessionPath, JSON.stringify({
1005
+ sessionId: 'abc',
1006
+ messages: 'not-an-array'
1007
+ }));
1008
+ expect(adapter.getConversation(sessionPath)).toEqual([]);
1009
+ });
1010
+ });
1011
+ describe('listSessions', ()=>{
1012
+ it('returns empty when ~/.gemini/tmp does not exist', async ()=>{
1013
+ // tmpHome has no .gemini dir by default
1014
+ const result = await adapter.listSessions();
1015
+ expect(result).toEqual([]);
1016
+ });
1017
+ it('walks every shortId/chats dir and returns sessions', async ()=>{
1018
+ writeSession(tmpHome, 'aaa', 'session-1', {
1019
+ sessionId: 's-1',
1020
+ projectHash: hashProjectRoot('/repo-a'),
1021
+ startTime: '2025-01-01T00:00:00Z',
1022
+ lastUpdated: '2025-01-01T00:01:00Z',
1023
+ directories: [
1024
+ '/repo-a'
1025
+ ],
1026
+ messages: [
1027
+ {
1028
+ type: 'user',
1029
+ timestamp: '2025-01-01T00:00:00Z',
1030
+ content: [
1031
+ {
1032
+ text: 'hello a'
1033
+ }
1034
+ ]
1035
+ }
1036
+ ]
1037
+ });
1038
+ writeSession(tmpHome, 'bbb', 'session-2', {
1039
+ sessionId: 's-2',
1040
+ projectHash: hashProjectRoot('/repo-b'),
1041
+ startTime: '2025-01-02T00:00:00Z',
1042
+ lastUpdated: '2025-01-02T00:01:00Z',
1043
+ directories: [
1044
+ '/repo-b'
1045
+ ],
1046
+ messages: [
1047
+ {
1048
+ type: 'user',
1049
+ timestamp: '2025-01-02T00:00:00Z',
1050
+ content: [
1051
+ {
1052
+ text: 'hello b'
1053
+ }
1054
+ ]
1055
+ }
1056
+ ]
1057
+ });
1058
+ const result = await adapter.listSessions();
1059
+ expect(result).toHaveLength(2);
1060
+ const byId = Object.fromEntries(result.map((r)=>[
1061
+ r.sessionId,
1062
+ r
1063
+ ]));
1064
+ expect(byId['s-1']).toMatchObject({
1065
+ type: 'gemini_cli',
1066
+ cwd: '/repo-a',
1067
+ firstUserMessage: 'hello a'
1068
+ });
1069
+ expect(byId['s-2']).toMatchObject({
1070
+ type: 'gemini_cli',
1071
+ cwd: '/repo-b',
1072
+ firstUserMessage: 'hello b'
1073
+ });
1074
+ });
1075
+ it('applies strict-equality cwd filter against directories[0]', async ()=>{
1076
+ writeSession(tmpHome, 'aaa', 'session-keep', {
1077
+ sessionId: 'keep',
1078
+ projectHash: hashProjectRoot('/repo'),
1079
+ startTime: '2025-01-01T00:00:00Z',
1080
+ directories: [
1081
+ '/repo'
1082
+ ],
1083
+ messages: [
1084
+ {
1085
+ type: 'user',
1086
+ timestamp: '2025-01-01T00:00:00Z',
1087
+ content: 'yes'
1088
+ }
1089
+ ]
1090
+ });
1091
+ writeSession(tmpHome, 'bbb', 'session-drop', {
1092
+ sessionId: 'drop',
1093
+ projectHash: hashProjectRoot('/other'),
1094
+ startTime: '2025-01-01T00:00:00Z',
1095
+ directories: [
1096
+ '/other'
1097
+ ],
1098
+ messages: [
1099
+ {
1100
+ type: 'user',
1101
+ timestamp: '2025-01-01T00:00:00Z',
1102
+ content: 'no'
1103
+ }
1104
+ ]
1105
+ });
1106
+ const result = await adapter.listSessions({
1107
+ cwd: '/repo'
1108
+ });
1109
+ expect(result).toHaveLength(1);
1110
+ expect(result[0].sessionId).toBe('keep');
1111
+ });
1112
+ it('skips malformed JSON files', async ()=>{
1113
+ const chatsDir = path.join(tmpHome, '.gemini', 'tmp', 'aaa', 'chats');
1114
+ fs.mkdirSync(chatsDir, {
1115
+ recursive: true
1116
+ });
1117
+ fs.writeFileSync(path.join(chatsDir, 'session-bad.json'), '{ not json');
1118
+ writeSession(tmpHome, 'aaa', 'session-good', {
1119
+ sessionId: 'good',
1120
+ projectHash: hashProjectRoot('/repo'),
1121
+ startTime: '2025-01-01T00:00:00Z',
1122
+ directories: [
1123
+ '/repo'
1124
+ ],
1125
+ messages: [
1126
+ {
1127
+ type: 'user',
1128
+ timestamp: '2025-01-01T00:00:00Z',
1129
+ content: 'ok'
1130
+ }
1131
+ ]
1132
+ });
1133
+ const result = await adapter.listSessions();
1134
+ expect(result).toHaveLength(1);
1135
+ expect(result[0].sessionId).toBe('good');
1136
+ });
1137
+ it('skips files missing sessionId', async ()=>{
1138
+ writeSession(tmpHome, 'aaa', 'session-no-id', {
1139
+ projectHash: hashProjectRoot('/repo'),
1140
+ startTime: '2025-01-01T00:00:00Z',
1141
+ directories: [
1142
+ '/repo'
1143
+ ],
1144
+ messages: []
1145
+ });
1146
+ const result = await adapter.listSessions();
1147
+ expect(result).toEqual([]);
1148
+ });
1149
+ it('captures the first user-typed message as firstUserMessage', async ()=>{
1150
+ writeSession(tmpHome, 'aaa', 'session-x', {
1151
+ sessionId: 's',
1152
+ projectHash: hashProjectRoot('/repo'),
1153
+ startTime: '2025-01-01T00:00:00Z',
1154
+ directories: [
1155
+ '/repo'
1156
+ ],
1157
+ messages: [
1158
+ {
1159
+ type: 'gemini',
1160
+ timestamp: '2025-01-01T00:00:00Z',
1161
+ content: 'preamble'
1162
+ },
1163
+ {
1164
+ type: 'user',
1165
+ timestamp: '2025-01-01T00:00:01Z',
1166
+ content: [
1167
+ {
1168
+ text: 'first user'
1169
+ }
1170
+ ]
1171
+ },
1172
+ {
1173
+ type: 'user',
1174
+ timestamp: '2025-01-01T00:00:02Z',
1175
+ content: 'second user'
1176
+ }
1177
+ ]
1178
+ });
1179
+ const result = await adapter.listSessions({
1180
+ cwd: '/repo'
1181
+ });
1182
+ expect(result).toHaveLength(1);
1183
+ expect(result[0].firstUserMessage).toBe('first user');
1184
+ });
1185
+ it('returns empty firstUserMessage when no user message exists', async ()=>{
1186
+ writeSession(tmpHome, 'aaa', 'session-x', {
1187
+ sessionId: 's',
1188
+ projectHash: hashProjectRoot('/repo'),
1189
+ startTime: '2025-01-01T00:00:00Z',
1190
+ directories: [
1191
+ '/repo'
1192
+ ],
1193
+ messages: [
1194
+ {
1195
+ type: 'gemini',
1196
+ timestamp: '2025-01-01T00:00:00Z',
1197
+ content: 'agent only'
1198
+ }
1199
+ ]
1200
+ });
1201
+ const result = await adapter.listSessions({
1202
+ cwd: '/repo'
1203
+ });
1204
+ expect(result).toHaveLength(1);
1205
+ expect(result[0].firstUserMessage).toBe('');
1206
+ });
1207
+ });
1208
+ });
1209
+ /**
1210
+ * Write a Gemini session JSON to the temporary home under the expected
1211
+ * ~/.gemini/tmp/<shortId>/chats/<fileName>.json layout. Returns the full path.
1212
+ */ function writeSession(home, shortId, fileName, body) {
1213
+ const chatsDir = path.join(home, '.gemini', 'tmp', shortId, 'chats');
1214
+ fs.mkdirSync(chatsDir, {
1215
+ recursive: true
1216
+ });
1217
+ const filePath = path.join(chatsDir, `${fileName}.json`);
1218
+ fs.writeFileSync(filePath, JSON.stringify(body));
1219
+ return filePath;
1220
+ }
1221
+ /**
1222
+ * Mirror the projectHash algo used by Gemini CLI:
1223
+ * sha256(projectRoot) as hex.
1224
+ */ function hashProjectRoot(projectRoot) {
1225
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
1226
+ return crypto.createHash('sha256').update(projectRoot).digest('hex');
1227
+ }
1228
+
1229
+ //# sourceMappingURL=GeminiCliAdapter.test.js.map