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
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
|
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
/** @vitest-environment jsdom */
import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
import { renderHook, act } from '@testing-library/react';
import { useCompletion } from './useCompletion.js';
import * as fs from 'fs/promises';
import * as path from 'path';
import * as os from 'os';
import { CommandContext, SlashCommand } from '../commands/types.js';
import { Config, FileDiscoveryService } from '@google/gemini-cli-core';
import { useTextBuffer, TextBuffer } from '../components/shared/text-buffer.js';
describe('useCompletion', () => {
let testRootDir: string;
let mockConfig: Config;
// A minimal mock is sufficient for these tests.
const mockCommandContext = {} as CommandContext;
async function createEmptyDir(...pathSegments: string[]) {
const fullPath = path.join(testRootDir, ...pathSegments);
await fs.mkdir(fullPath, { recursive: true });
return fullPath;
}
async function createTestFile(content: string, ...pathSegments: string[]) {
const fullPath = path.join(testRootDir, ...pathSegments);
await fs.mkdir(path.dirname(fullPath), { recursive: true });
await fs.writeFile(fullPath, content);
return fullPath;
}
// Helper to create real TextBuffer objects within renderHook
function useTextBufferForTest(text: string) {
return useTextBuffer({
initialText: text,
initialCursorOffset: text.length,
viewport: { width: 80, height: 20 },
isValidPath: () => false,
onChange: () => {},
});
}
beforeEach(async () => {
testRootDir = await fs.mkdtemp(
path.join(os.tmpdir(), 'completion-unit-test-'),
);
mockConfig = {
getTargetDir: () => testRootDir,
getProjectRoot: () => testRootDir,
getFileFilteringOptions: vi.fn(() => ({
respectGitIgnore: true,
respectGeminiIgnore: true,
})),
getEnableRecursiveFileSearch: vi.fn(() => true),
getFileService: vi.fn(() => new FileDiscoveryService(testRootDir)),
} as unknown as Config;
vi.clearAllMocks();
});
afterEach(async () => {
vi.restoreAllMocks();
await fs.rm(testRootDir, { recursive: true, force: true });
});
describe('Core Hook Behavior', () => {
describe('State Management', () => {
it('should initialize with default state', () => {
const slashCommands = [
{ name: 'dummy', description: 'dummy' },
] as unknown as SlashCommand[];
const { result } = renderHook(() =>
useCompletion(
useTextBufferForTest(''),
testRootDir,
slashCommands,
mockCommandContext,
mockConfig,
),
);
expect(result.current.suggestions).toEqual([]);
expect(result.current.activeSuggestionIndex).toBe(-1);
expect(result.current.visibleStartIndex).toBe(0);
expect(result.current.showSuggestions).toBe(false);
expect(result.current.isLoadingSuggestions).toBe(false);
});
it('should reset state when isActive becomes false', () => {
const slashCommands = [
{
name: 'help',
altNames: ['?'],
description: 'Show help',
action: vi.fn(),
},
] as unknown as SlashCommand[];
const { result, rerender } = renderHook(
({ text }) => {
const textBuffer = useTextBufferForTest(text);
return useCompletion(
textBuffer,
testRootDir,
slashCommands,
mockCommandContext,
mockConfig,
);
},
{ initialProps: { text: '/help' } },
);
// Inactive because of the leading space
rerender({ text: ' /help' });
expect(result.current.suggestions).toEqual([]);
expect(result.current.activeSuggestionIndex).toBe(-1);
expect(result.current.visibleStartIndex).toBe(0);
expect(result.current.showSuggestions).toBe(false);
expect(result.current.isLoadingSuggestions).toBe(false);
});
it('should reset all state to default values', () => {
const slashCommands = [
{
name: 'help',
description: 'Show help',
},
] as unknown as SlashCommand[];
const { result } = renderHook(() =>
useCompletion(
useTextBufferForTest('/help'),
testRootDir,
slashCommands,
mockCommandContext,
mockConfig,
),
);
act(() => {
result.current.setActiveSuggestionIndex(5);
result.current.setShowSuggestions(true);
});
act(() => {
result.current.resetCompletionState();
});
expect(result.current.suggestions).toEqual([]);
expect(result.current.activeSuggestionIndex).toBe(-1);
expect(result.current.visibleStartIndex).toBe(0);
expect(result.current.showSuggestions).toBe(false);
expect(result.current.isLoadingSuggestions).toBe(false);
});
});
describe('Navigation', () => {
it('should handle navigateUp with no suggestions', () => {
const slashCommands = [
{ name: 'dummy', description: 'dummy' },
] as unknown as SlashCommand[];
const { result } = renderHook(() =>
useCompletion(
useTextBufferForTest(''),
testRootDir,
slashCommands,
mockCommandContext,
mockConfig,
),
);
act(() => {
result.current.navigateUp();
});
expect(result.current.activeSuggestionIndex).toBe(-1);
});
it('should handle navigateDown with no suggestions', () => {
const slashCommands = [
{ name: 'dummy', description: 'dummy' },
] as unknown as SlashCommand[];
const { result } = renderHook(() =>
useCompletion(
useTextBufferForTest(''),
testRootDir,
slashCommands,
mockCommandContext,
mockConfig,
),
);
act(() => {
result.current.navigateDown();
});
expect(result.current.activeSuggestionIndex).toBe(-1);
});
it('should navigate up through suggestions with wrap-around', () => {
const slashCommands = [
{
name: 'help',
description: 'Show help',
},
] as unknown as SlashCommand[];
const { result } = renderHook(() =>
useCompletion(
useTextBufferForTest('/h'),
testRootDir,
slashCommands,
mockCommandContext,
mockConfig,
),
);
expect(result.current.suggestions.length).toBe(1);
expect(result.current.activeSuggestionIndex).toBe(0);
act(() => {
result.current.navigateUp();
});
expect(result.current.activeSuggestionIndex).toBe(0);
});
it('should navigate down through suggestions with wrap-around', () => {
const slashCommands = [
{
name: 'help',
description: 'Show help',
},
] as unknown as SlashCommand[];
const { result } = renderHook(() =>
useCompletion(
useTextBufferForTest('/h'),
testRootDir,
slashCommands,
mockCommandContext,
mockConfig,
),
);
expect(result.current.suggestions.length).toBe(1);
expect(result.current.activeSuggestionIndex).toBe(0);
act(() => {
result.current.navigateDown();
});
expect(result.current.activeSuggestionIndex).toBe(0);
});
it('should handle navigation with multiple suggestions', () => {
const slashCommands = [
{ name: 'help', description: 'Show help' },
{ name: 'stats', description: 'Show stats' },
{ name: 'clear', description: 'Clear screen' },
{ name: 'memory', description: 'Manage memory' },
{ name: 'chat', description: 'Manage chat' },
] as unknown as SlashCommand[];
const { result } = renderHook(() =>
useCompletion(
useTextBufferForTest('/'),
testRootDir,
slashCommands,
mockCommandContext,
mockConfig,
),
);
expect(result.current.suggestions.length).toBe(5);
expect(result.current.activeSuggestionIndex).toBe(0);
act(() => {
result.current.navigateDown();
});
expect(result.current.activeSuggestionIndex).toBe(1);
act(() => {
result.current.navigateDown();
});
expect(result.current.activeSuggestionIndex).toBe(2);
act(() => {
result.current.navigateUp();
});
expect(result.current.activeSuggestionIndex).toBe(1);
act(() => {
result.current.navigateUp();
});
expect(result.current.activeSuggestionIndex).toBe(0);
act(() => {
result.current.navigateUp();
});
expect(result.current.activeSuggestionIndex).toBe(4);
});
it('should handle navigation with large suggestion lists and scrolling', () => {
const largeMockCommands = Array.from({ length: 15 }, (_, i) => ({
name: `command${i}`,
description: `Command ${i}`,
})) as unknown as SlashCommand[];
const { result } = renderHook(() =>
useCompletion(
useTextBufferForTest('/command'),
testRootDir,
largeMockCommands,
mockCommandContext,
mockConfig,
),
);
expect(result.current.suggestions.length).toBe(15);
expect(result.current.activeSuggestionIndex).toBe(0);
expect(result.current.visibleStartIndex).toBe(0);
act(() => {
result.current.navigateUp();
});
expect(result.current.activeSuggestionIndex).toBe(14);
expect(result.current.visibleStartIndex).toBe(Math.max(0, 15 - 8));
});
});
});
describe('Slash Command Completion (`/`)', () => {
describe('Top-Level Commands', () => {
it('should suggest all top-level commands for the root slash', async () => {
const slashCommands = [
{
name: 'help',
altNames: ['?'],
description: 'Show help',
},
{
name: 'stats',
altNames: ['usage'],
description: 'check session stats. Usage: /stats [model|tools]',
},
{
name: 'clear',
description: 'Clear the screen',
},
{
name: 'memory',
description: 'Manage memory',
subCommands: [
{
name: 'show',
description: 'Show memory',
},
],
},
{
name: 'chat',
description: 'Manage chat history',
},
] as unknown as SlashCommand[];
const { result } = renderHook(() =>
useCompletion(
useTextBufferForTest('/'),
testRootDir,
slashCommands,
mockCommandContext,
),
);
expect(result.current.suggestions.length).toBe(slashCommands.length);
expect(result.current.suggestions.map((s) => s.label)).toEqual(
expect.arrayContaining(['help', 'clear', 'memory', 'chat', 'stats']),
);
});
it('should filter commands based on partial input', async () => {
const slashCommands = [
{
name: 'memory',
description: 'Manage memory',
},
] as unknown as SlashCommand[];
const { result } = renderHook(() =>
useCompletion(
useTextBufferForTest('/mem'),
testRootDir,
slashCommands,
mockCommandContext,
),
);
expect(result.current.suggestions).toEqual([
{ label: 'memory', value: 'memory', description: 'Manage memory' },
]);
expect(result.current.showSuggestions).toBe(true);
});
it('should suggest commands based on partial altNames', async () => {
const slashCommands = [
{
name: 'stats',
altNames: ['usage'],
description: 'check session stats. Usage: /stats [model|tools]',
},
] as unknown as SlashCommand[];
const { result } = renderHook(() =>
useCompletion(
useTextBufferForTest('/usag'), // part of the word "usage"
testRootDir,
slashCommands,
mockCommandContext,
),
);
expect(result.current.suggestions).toEqual([
{
label: 'stats',
value: 'stats',
description: 'check session stats. Usage: /stats [model|tools]',
},
]);
});
it('should NOT provide suggestions for a perfectly typed command that is a leaf node', async () => {
const slashCommands = [
{
name: 'clear',
description: 'Clear the screen',
action: vi.fn(),
},
] as unknown as SlashCommand[];
const { result } = renderHook(() =>
useCompletion(
useTextBufferForTest('/clear'), // No trailing space
testRootDir,
slashCommands,
mockCommandContext,
),
);
expect(result.current.suggestions).toHaveLength(0);
expect(result.current.showSuggestions).toBe(false);
});
it.each([['/?'], ['/usage']])(
'should not suggest commands when altNames is fully typed',
async (query) => {
const mockSlashCommands = [
{
name: 'help',
altNames: ['?'],
description: 'Show help',
action: vi.fn(),
},
{
name: 'stats',
altNames: ['usage'],
description: 'check session stats. Usage: /stats [model|tools]',
action: vi.fn(),
},
] as unknown as SlashCommand[];
const { result } = renderHook(() =>
useCompletion(
useTextBufferForTest(query),
testRootDir,
mockSlashCommands,
mockCommandContext,
),
);
expect(result.current.suggestions).toHaveLength(0);
},
);
it('should not provide suggestions for a fully typed command that has no sub-commands or argument completion', async () => {
const slashCommands = [
{
name: 'clear',
description: 'Clear the screen',
},
] as unknown as SlashCommand[];
const { result } = renderHook(() =>
useCompletion(
useTextBufferForTest('/clear '),
testRootDir,
slashCommands,
mockCommandContext,
),
);
expect(result.current.suggestions).toHaveLength(0);
expect(result.current.showSuggestions).toBe(false);
});
it('should not provide suggestions for an unknown command', async () => {
const slashCommands = [
{
name: 'help',
description: 'Show help',
},
] as unknown as SlashCommand[];
const { result } = renderHook(() =>
useCompletion(
useTextBufferForTest('/unknown-command'),
testRootDir,
slashCommands,
mockCommandContext,
),
);
expect(result.current.suggestions).toHaveLength(0);
expect(result.current.showSuggestions).toBe(false);
});
});
describe('Sub-Commands', () => {
it('should suggest sub-commands for a parent command', async () => {
const slashCommands = [
{
name: 'memory',
description: 'Manage memory',
subCommands: [
{
name: 'show',
description: 'Show memory',
},
{
name: 'add',
description: 'Add to memory',
},
],
},
] as unknown as SlashCommand[];
const { result } = renderHook(() =>
useCompletion(
useTextBufferForTest('/memory'), // Note: no trailing space
testRootDir,
slashCommands,
mockCommandContext,
),
);
// Assert that suggestions for sub-commands are shown immediately
expect(result.current.suggestions).toHaveLength(2);
expect(result.current.suggestions).toEqual(
expect.arrayContaining([
{ label: 'show', value: 'show', description: 'Show memory' },
{ label: 'add', value: 'add', description: 'Add to memory' },
]),
);
expect(result.current.showSuggestions).toBe(true);
});
it('should suggest all sub-commands when the query ends with the parent command and a space', async () => {
const slashCommands = [
{
name: 'memory',
description: 'Manage memory',
subCommands: [
{
name: 'show',
description: 'Show memory',
},
{
name: 'add',
description: 'Add to memory',
},
],
},
] as unknown as SlashCommand[];
const { result } = renderHook(() =>
useCompletion(
useTextBufferForTest('/memory'),
testRootDir,
slashCommands,
mockCommandContext,
),
);
expect(result.current.suggestions).toHaveLength(2);
expect(result.current.suggestions).toEqual(
expect.arrayContaining([
{ label: 'show', value: 'show', description: 'Show memory' },
{ label: 'add', value: 'add', description: 'Add to memory' },
]),
);
});
it('should filter sub-commands by prefix', async () => {
const slashCommands = [
{
name: 'memory',
description: 'Manage memory',
subCommands: [
{
name: 'show',
description: 'Show memory',
},
{
name: 'add',
description: 'Add to memory',
},
],
},
] as unknown as SlashCommand[];
const { result } = renderHook(() =>
useCompletion(
useTextBufferForTest('/memory a'),
testRootDir,
slashCommands,
mockCommandContext,
),
);
expect(result.current.suggestions).toEqual([
{ label: 'add', value: 'add', description: 'Add to memory' },
]);
});
it('should provide no suggestions for an invalid sub-command', async () => {
const slashCommands = [
{
name: 'memory',
description: 'Manage memory',
subCommands: [
{
name: 'show',
description: 'Show memory',
},
{
name: 'add',
description: 'Add to memory',
},
],
},
] as unknown as SlashCommand[];
const { result } = renderHook(() =>
useCompletion(
useTextBufferForTest('/memory dothisnow'),
testRootDir,
slashCommands,
mockCommandContext,
),
);
expect(result.current.suggestions).toHaveLength(0);
expect(result.current.showSuggestions).toBe(false);
});
});
describe('Argument Completion', () => {
it('should call the command.completion function for argument suggestions', async () => {
const availableTags = [
'my-chat-tag-1',
'my-chat-tag-2',
'another-channel',
];
const mockCompletionFn = vi
.fn()
.mockImplementation(
async (_context: CommandContext, partialArg: string) =>
availableTags.filter((tag) => tag.startsWith(partialArg)),
);
const slashCommands = [
{
name: 'chat',
description: 'Manage chat history',
subCommands: [
{
name: 'resume',
description: 'Resume a saved chat',
completion: mockCompletionFn,
},
],
},
] as unknown as SlashCommand[];
const { result } = renderHook(() =>
useCompletion(
useTextBufferForTest('/chat resume my-ch'),
testRootDir,
slashCommands,
mockCommandContext,
),
);
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 150));
});
expect(mockCompletionFn).toHaveBeenCalledWith(
mockCommandContext,
'my-ch',
);
expect(result.current.suggestions).toEqual([
{ label: 'my-chat-tag-1', value: 'my-chat-tag-1' },
{ label: 'my-chat-tag-2', value: 'my-chat-tag-2' },
]);
});
it('should call command.completion with an empty string when args start with a space', async () => {
const mockCompletionFn = vi
.fn()
.mockResolvedValue(['my-chat-tag-1', 'my-chat-tag-2', 'my-channel']);
const slashCommands = [
{
name: 'chat',
description: 'Manage chat history',
subCommands: [
{
name: 'resume',
description: 'Resume a saved chat',
completion: mockCompletionFn,
},
],
},
] as unknown as SlashCommand[];
const { result } = renderHook(() =>
useCompletion(
useTextBufferForTest('/chat resume '),
testRootDir,
slashCommands,
mockCommandContext,
),
);
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 150));
});
expect(mockCompletionFn).toHaveBeenCalledWith(mockCommandContext, '');
expect(result.current.suggestions).toHaveLength(3);
expect(result.current.showSuggestions).toBe(true);
});
it('should handle completion function that returns null', async () => {
const completionFn = vi.fn().mockResolvedValue(null);
const slashCommands = [
{
name: 'chat',
description: 'Manage chat history',
subCommands: [
{
name: 'resume',
description: 'Resume a saved chat',
completion: completionFn,
},
],
},
] as unknown as SlashCommand[];
const { result } = renderHook(() =>
useCompletion(
useTextBufferForTest('/chat resume '),
testRootDir,
slashCommands,
mockCommandContext,
mockConfig,
),
);
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 150));
});
expect(result.current.suggestions).toHaveLength(0);
expect(result.current.showSuggestions).toBe(false);
});
});
});
describe('File Path Completion (`@`)', () => {
describe('Basic Completion', () => {
it('should use glob for top-level @ completions when available', async () => {
await createTestFile('', 'src', 'index.ts');
await createTestFile('', 'derp', 'script.ts');
await createTestFile('', 'README.md');
const { result } = renderHook(() =>
useCompletion(
useTextBufferForTest('@s'),
testRootDir,
[],
mockCommandContext,
mockConfig,
),
);
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 150));
});
expect(result.current.suggestions).toHaveLength(2);
expect(result.current.suggestions).toEqual(
expect.arrayContaining([
{
label: 'derp/script.ts',
value: 'derp/script.ts',
},
{ label: 'src', value: 'src' },
]),
);
});
it('should handle directory-specific completions with git filtering', async () => {
await createEmptyDir('.git');
await createTestFile('*.log', '.gitignore');
await createTestFile('', 'src', 'component.tsx');
await createTestFile('', 'src', 'temp.log');
await createTestFile('', 'src', 'index.ts');
const { result } = renderHook(() =>
useCompletion(
useTextBufferForTest('@src/comp'),
testRootDir,
[],
mockCommandContext,
mockConfig,
),
);
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 150));
});
// Should filter out .log files but include matching .tsx files
expect(result.current.suggestions).toEqual([
{ label: 'component.tsx', value: 'component.tsx' },
]);
});
it('should include dotfiles in glob search when input starts with a dot', async () => {
await createTestFile('', '.env');
await createTestFile('', '.gitignore');
await createTestFile('', 'src', 'index.ts');
const { result } = renderHook(() =>
useCompletion(
useTextBufferForTest('@.'),
testRootDir,
[],
mockCommandContext,
mockConfig,
),
);
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 150));
});
expect(result.current.suggestions).toEqual([
{ label: '.env', value: '.env' },
{ label: '.gitignore', value: '.gitignore' },
]);
});
});
describe('Configuration-based Behavior', () => {
it('should not perform recursive search when disabled in config', async () => {
const mockConfigNoRecursive = {
...mockConfig,
getEnableRecursiveFileSearch: vi.fn(() => false),
} as unknown as Config;
await createEmptyDir('data');
await createEmptyDir('dist');
const { result } = renderHook(() =>
useCompletion(
useTextBufferForTest('@d'),
testRootDir,
[],
mockCommandContext,
mockConfigNoRecursive,
),
);
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 150));
});
expect(result.current.suggestions).toEqual([
{ label: 'data/', value: 'data/' },
{ label: 'dist/', value: 'dist/' },
]);
});
it('should work without config (fallback behavior)', async () => {
await createEmptyDir('src');
await createEmptyDir('node_modules');
await createTestFile('', 'README.md');
const { result } = renderHook(() =>
useCompletion(
useTextBufferForTest('@'),
testRootDir,
[],
mockCommandContext,
undefined,
),
);
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 150));
});
// Without config, should include all files
expect(result.current.suggestions).toHaveLength(3);
expect(result.current.suggestions).toEqual(
expect.arrayContaining([
{ label: 'src/', value: 'src/' },
{ label: 'node_modules/', value: 'node_modules/' },
{ label: 'README.md', value: 'README.md' },
]),
);
});
it('should handle git discovery service initialization failure gracefully', async () => {
// Intentionally don't create a .git directory to cause an initialization failure.
await createEmptyDir('src');
await createTestFile('', 'README.md');
const consoleSpy = vi
.spyOn(console, 'warn')
.mockImplementation(() => {});
const { result } = renderHook(() =>
useCompletion(
useTextBufferForTest('@'),
testRootDir,
[],
mockCommandContext,
mockConfig,
),
);
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 150));
});
// Since we use centralized service, initialization errors are handled at config level
// This test should verify graceful fallback behavior
expect(result.current.suggestions.length).toBeGreaterThanOrEqual(0);
// Should still show completions even if git discovery fails
expect(result.current.suggestions.length).toBeGreaterThan(0);
consoleSpy.mockRestore();
});
});
describe('Git-Aware Filtering', () => {
it('should filter git-ignored entries from @ completions', async () => {
await createEmptyDir('.git');
await createTestFile('dist', '.gitignore');
await createEmptyDir('data');
const { result } = renderHook(() =>
useCompletion(
useTextBufferForTest('@d'),
testRootDir,
[],
mockCommandContext,
mockConfig,
),
);
// Wait for async operations to complete
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 150)); // Account for debounce
});
expect(result.current.suggestions).toEqual(
expect.arrayContaining([{ label: 'data', value: 'data' }]),
);
expect(result.current.showSuggestions).toBe(true);
});
it('should filter git-ignored directories from @ completions', async () => {
await createEmptyDir('.git');
await createTestFile('node_modules\ndist\n.env', '.gitignore');
// gitignored entries
await createEmptyDir('node_modules');
await createEmptyDir('dist');
await createTestFile('', '.env');
// visible
await createEmptyDir('src');
await createTestFile('', 'README.md');
const { result } = renderHook(() =>
useCompletion(
useTextBufferForTest('@'),
testRootDir,
[],
mockCommandContext,
mockConfig,
),
);
// Wait for async operations to complete
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 150)); // Account for debounce
});
expect(result.current.suggestions).toEqual([
{ label: 'README.md', value: 'README.md' },
{ label: 'src/', value: 'src/' },
]);
expect(result.current.showSuggestions).toBe(true);
});
it('should handle recursive search with git-aware filtering', async () => {
await createEmptyDir('.git');
await createTestFile('node_modules/\ntemp/', '.gitignore');
await createTestFile('', 'data', 'test.txt');
await createEmptyDir('dist');
await createEmptyDir('node_modules');
await createTestFile('', 'src', 'index.ts');
await createEmptyDir('src', 'components');
await createTestFile('', 'temp', 'temp.log');
const { result } = renderHook(() =>
useCompletion(
useTextBufferForTest('@t'),
testRootDir,
[],
mockCommandContext,
mockConfig,
),
);
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 150));
});
// Should not include anything from node_modules or dist
const suggestionLabels = result.current.suggestions.map((s) => s.label);
expect(suggestionLabels).not.toContain('temp/');
expect(suggestionLabels).not.toContain('node_modules/');
});
});
});
describe('handleAutocomplete', () => {
it('should complete a partial command', () => {
const slashCommands = [
{
name: 'memory',
description: 'Manage memory',
subCommands: [
{
name: 'show',
description: 'Show memory',
},
{
name: 'add',
description: 'Add to memory',
},
],
},
] as unknown as SlashCommand[];
// Create a mock buffer that we can spy on directly
const mockBuffer = {
text: '/mem',
setText: vi.fn(),
} as unknown as TextBuffer;
const { result } = renderHook(() =>
useCompletion(
mockBuffer,
testRootDir,
slashCommands,
mockCommandContext,
mockConfig,
),
);
expect(result.current.suggestions.map((s) => s.value)).toEqual([
'memory',
]);
act(() => {
result.current.handleAutocomplete(0);
});
expect(mockBuffer.setText).toHaveBeenCalledWith('/memory ');
});
it('should append a sub-command when the parent is complete', () => {
const mockBuffer = {
text: '/memory',
setText: vi.fn(),
} as unknown as TextBuffer;
const slashCommands = [
{
name: 'memory',
description: 'Manage memory',
subCommands: [
{
name: 'show',
description: 'Show memory',
},
{
name: 'add',
description: 'Add to memory',
},
],
},
] as unknown as SlashCommand[];
const { result } = renderHook(() =>
useCompletion(
mockBuffer,
testRootDir,
slashCommands,
mockCommandContext,
mockConfig,
),
);
// Suggestions are populated by useEffect
expect(result.current.suggestions.map((s) => s.value)).toEqual([
'show',
'add',
]);
act(() => {
result.current.handleAutocomplete(1); // index 1 is 'add'
});
expect(mockBuffer.setText).toHaveBeenCalledWith('/memory add ');
});
it('should complete a command with an alternative name', () => {
const mockBuffer = {
text: '/?',
setText: vi.fn(),
} as unknown as TextBuffer;
const slashCommands = [
{
name: 'memory',
description: 'Manage memory',
subCommands: [
{
name: 'show',
description: 'Show memory',
},
{
name: 'add',
description: 'Add to memory',
},
],
},
] as unknown as SlashCommand[];
const { result } = renderHook(() =>
useCompletion(
mockBuffer,
testRootDir,
slashCommands,
mockCommandContext,
mockConfig,
),
);
result.current.suggestions.push({
label: 'help',
value: 'help',
description: 'Show help',
});
act(() => {
result.current.handleAutocomplete(0);
});
expect(mockBuffer.setText).toHaveBeenCalledWith('/help ');
});
it('should complete a file path', async () => {
const mockBuffer = {
text: '@src/fi',
lines: ['@src/fi'],
cursor: [0, 7],
setText: vi.fn(),
replaceRangeByOffset: vi.fn(),
} as unknown as TextBuffer;
const slashCommands = [
{
name: 'memory',
description: 'Manage memory',
subCommands: [
{
name: 'show',
description: 'Show memory',
},
{
name: 'add',
description: 'Add to memory',
},
],
},
] as unknown as SlashCommand[];
const { result } = renderHook(() =>
useCompletion(
mockBuffer,
testRootDir,
slashCommands,
mockCommandContext,
mockConfig,
),
);
result.current.suggestions.push({
label: 'file1.txt',
value: 'file1.txt',
});
act(() => {
result.current.handleAutocomplete(0);
});
expect(mockBuffer.replaceRangeByOffset).toHaveBeenCalledWith(
5, // after '@src/'
mockBuffer.text.length,
'file1.txt',
);
});
});
});
|