forked from sailay1996/cursor-agent-mcp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.integration.test.js
More file actions
949 lines (757 loc) · 34.5 KB
/
server.integration.test.js
File metadata and controls
949 lines (757 loc) · 34.5 KB
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
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { spawn } from 'node:child_process';
import path from 'node:path';
import fs from 'node:fs';
import { invokeCursorAgent, runCursorAgent } from './server.js';
import { createMockChildProcess } from './test/utils.js';
// Mock child_process.spawn
vi.mock('node:child_process', () => {
return {
spawn: vi.fn(),
};
});
describe('invokeCursorAgent', () => {
const originalEnv = { ...process.env };
beforeEach(() => {
vi.clearAllMocks();
// Reset environment
for (const key in process.env) {
if (key.startsWith('CURSOR_AGENT_') || key === 'DEBUG_CURSOR_MCP') {
delete process.env[key];
}
}
});
afterEach(() => {
process.env = originalEnv;
vi.useRealTimers();
});
it('should spawn cursor-agent with correct arguments', async () => {
const mockProcess = createMockChildProcess({ stdout: 'test output', exitCode: 0 });
vi.mocked(spawn).mockReturnValue(mockProcess);
await invokeCursorAgent({ argv: ['test prompt'], output_format: 'text' });
expect(spawn).toHaveBeenCalledWith(
'cursor-agent',
expect.arrayContaining(['--print', '--output-format', 'text', 'test prompt']),
expect.objectContaining({
shell: false,
cwd: expect.any(String),
env: expect.any(Object),
}),
);
});
it('should handle different output formats', async () => {
const mockProcess = createMockChildProcess({ stdout: 'json output', exitCode: 0 });
vi.mocked(spawn).mockReturnValue(mockProcess);
await invokeCursorAgent({ argv: ['test'], output_format: 'json' });
expect(spawn).toHaveBeenCalledWith(
'cursor-agent',
expect.arrayContaining(['--output-format', 'json']),
expect.any(Object),
);
});
it('should include model flag when provided', async () => {
const mockProcess = createMockChildProcess({ stdout: 'output', exitCode: 0 });
vi.mocked(spawn).mockReturnValue(mockProcess);
await invokeCursorAgent({ argv: ['test'], model: 'gpt-4' });
expect(spawn).toHaveBeenCalledWith(
'cursor-agent',
expect.arrayContaining(['--model', 'gpt-4']),
expect.any(Object),
);
});
it('should include force flag when provided', async () => {
const mockProcess = createMockChildProcess({ stdout: 'output', exitCode: 0 });
vi.mocked(spawn).mockReturnValue(mockProcess);
await invokeCursorAgent({ argv: ['test'], force: true });
expect(spawn).toHaveBeenCalledWith(
'cursor-agent',
expect.arrayContaining(['-f']),
expect.any(Object),
);
});
it('should use model from environment when not provided in args', async () => {
process.env.CURSOR_AGENT_MODEL = 'gpt-3.5-turbo';
const mockProcess = createMockChildProcess({ stdout: 'output', exitCode: 0 });
vi.mocked(spawn).mockReturnValue(mockProcess);
await invokeCursorAgent({ argv: ['test'] });
expect(spawn).toHaveBeenCalledWith(
'cursor-agent',
expect.arrayContaining(['--model', 'gpt-3.5-turbo']),
expect.any(Object),
);
});
it('should use force from environment when not provided in args', async () => {
process.env.CURSOR_AGENT_FORCE = 'true';
const mockProcess = createMockChildProcess({ stdout: 'output', exitCode: 0 });
vi.mocked(spawn).mockReturnValue(mockProcess);
await invokeCursorAgent({ argv: ['test'] });
expect(spawn).toHaveBeenCalledWith(
'cursor-agent',
expect.arrayContaining(['-f']),
expect.any(Object),
);
});
it('should not add model flag if already present in argv', async () => {
const mockProcess = createMockChildProcess({ stdout: 'output', exitCode: 0 });
vi.mocked(spawn).mockReturnValue(mockProcess);
await invokeCursorAgent({ argv: ['-m', 'gpt-4', 'test'] });
const callArgs = vi.mocked(spawn).mock.calls[0][1];
const modelFlags = callArgs.filter((arg, i) => arg === '-m' || arg === '--model' || callArgs[i - 1] === '-m' || callArgs[i - 1] === '--model');
expect(modelFlags.length).toBe(2); // -m and gpt-4
});
it('should not add force flag if already present in argv', async () => {
const mockProcess = createMockChildProcess({ stdout: 'output', exitCode: 0 });
vi.mocked(spawn).mockReturnValue(mockProcess);
await invokeCursorAgent({ argv: ['-f', 'test'] });
const callArgs = vi.mocked(spawn).mock.calls[0][1];
const forceCount = callArgs.filter(arg => arg === '-f' || arg === '--force').length;
expect(forceCount).toBe(1);
});
it('should not add --print when print is false', async () => {
const mockProcess = createMockChildProcess({ stdout: 'output', exitCode: 0 });
vi.mocked(spawn).mockReturnValue(mockProcess);
await invokeCursorAgent({ argv: ['test'], print: false });
const callArgs = vi.mocked(spawn).mock.calls[0][1];
expect(callArgs).not.toContain('--print');
});
it('should return successful output', async () => {
const mockProcess = createMockChildProcess({ stdout: 'successful output', exitCode: 0 });
vi.mocked(spawn).mockReturnValue(mockProcess);
const result = await invokeCursorAgent({ argv: ['test'] });
expect(result.content[0].type).toBe('text');
expect(result.content[0].text).toContain('successful output');
expect(result.isError).toBeUndefined();
// No stream log for non-streaming output format
});
it('should return error when process exits with non-zero code', async () => {
const mockProcess = createMockChildProcess({ stdout: 'output', stderr: 'error message', exitCode: 1 });
vi.mocked(spawn).mockReturnValue(mockProcess);
const result = await invokeCursorAgent({ argv: ['test'] });
expect(result.isError).toBe(true);
expect(result.content[0].text).toContain('exited with code 1');
});
it('should handle process errors', async () => {
const mockProcess = createMockChildProcess({ shouldError: true, errorMessage: 'Process failed to start' });
vi.mocked(spawn).mockReturnValue(mockProcess);
const result = await invokeCursorAgent({ argv: ['test'] });
expect(result.isError).toBe(true);
expect(result.content[0].text).toContain('Failed to start');
});
it('should handle timeout', async () => {
vi.useFakeTimers();
process.env.CURSOR_AGENT_TIMEOUT_MS = '100';
const mockProcess = createMockChildProcess({ stdout: '', exitCode: 0, delay: 200 });
vi.mocked(spawn).mockReturnValue(mockProcess);
const resultPromise = invokeCursorAgent({ argv: ['test'] });
vi.advanceTimersByTime(150);
const result = await resultPromise;
expect(result.isError).toBe(true);
expect(result.content[0].text).toContain('timed out');
});
it('should handle idle kill when configured', async () => {
vi.useFakeTimers();
process.env.CURSOR_AGENT_IDLE_EXIT_MS = '100';
const mockProcess = createMockChildProcess({ stdout: 'partial', exitCode: 0 });
vi.mocked(spawn).mockReturnValue(mockProcess);
const resultPromise = invokeCursorAgent({ argv: ['test'] });
// Simulate data arriving, then idle timeout
setTimeout(() => {
mockProcess.stdout.emit('data', Buffer.from('data'));
}, 50);
vi.advanceTimersByTime(200);
const result = await resultPromise;
// Should complete with output even if killed by idle
expect(result.content).toBeDefined();
});
it('should validate working directory', async () => {
const mockProcess = createMockChildProcess({ stdout: 'output', exitCode: 0 });
vi.mocked(spawn).mockReturnValue(mockProcess);
await invokeCursorAgent({ argv: ['test'], cwd: './test' });
const callOptions = vi.mocked(spawn).mock.calls[0][2];
expect(callOptions.cwd).toBeDefined();
});
it('should use safe environment variables', async () => {
process.env.SECRET_KEY = 'should-not-appear';
process.env.CURSOR_AGENT_MODEL = 'gpt-4';
const mockProcess = createMockChildProcess({ stdout: 'output', exitCode: 0 });
vi.mocked(spawn).mockReturnValue(mockProcess);
await invokeCursorAgent({ argv: ['test'] });
const callOptions = vi.mocked(spawn).mock.calls[0][2];
expect(callOptions.env.SECRET_KEY).toBeUndefined();
expect(callOptions.env.CURSOR_AGENT_MODEL).toBe('gpt-4');
});
});
describe('runCursorAgent', () => {
beforeEach(() => {
vi.clearAllMocks();
delete process.env.CURSOR_AGENT_ECHO_PROMPT;
delete process.env.DEBUG_CURSOR_MCP;
});
it('should call invokeCursorAgent with correct arguments', async () => {
const mockProcess = createMockChildProcess({ stdout: 'output', exitCode: 0, force: true, model: 'gpt-5.1' });
vi.mocked(spawn).mockReturnValue(mockProcess);
await runCursorAgent({ prompt: 'test prompt', output_format: 'text' });
expect(spawn).toHaveBeenCalledWith(
'cursor-agent',
expect.arrayContaining(['test prompt']),
expect.any(Object),
);
});
it('should handle extra_args', async () => {
const mockProcess = createMockChildProcess({ stdout: 'output', exitCode: 0 });
vi.mocked(spawn).mockReturnValue(mockProcess);
await runCursorAgent({ prompt: 'test', extra_args: ['--flag', 'value'] });
const callArgs = vi.mocked(spawn).mock.calls[0][1];
expect(callArgs).toContain('--flag');
expect(callArgs).toContain('value');
expect(callArgs).toContain('test');
});
it('should echo prompt when echo_prompt is true', async () => {
const mockProcess = createMockChildProcess({ stdout: 'output', exitCode: 0 });
vi.mocked(spawn).mockReturnValue(mockProcess);
const result = await runCursorAgent({ prompt: 'test prompt', echo_prompt: true });
expect(result.content[0].text).toContain('Prompt used:');
expect(result.content[0].text).toContain('test prompt');
});
it('should echo prompt when CURSOR_AGENT_ECHO_PROMPT is set', async () => {
process.env.CURSOR_AGENT_ECHO_PROMPT = '1';
const mockProcess = createMockChildProcess({ stdout: 'output', exitCode: 0 });
vi.mocked(spawn).mockReturnValue(mockProcess);
const result = await runCursorAgent({ prompt: 'test prompt' });
expect(result.content[0].text).toContain('Prompt used:');
});
it('should handle nested arguments object', async () => {
const mockProcess = createMockChildProcess({ stdout: 'output', exitCode: 0 });
vi.mocked(spawn).mockReturnValue(mockProcess);
await runCursorAgent({ arguments: { prompt: 'test prompt' } });
expect(spawn).toHaveBeenCalledWith(
'cursor-agent',
expect.arrayContaining(['test prompt']),
expect.any(Object),
);
});
it('should handle different output formats', async () => {
const mockProcess = createMockChildProcess({ stdout: 'output', exitCode: 0 });
vi.mocked(spawn).mockReturnValue(mockProcess);
await runCursorAgent({ prompt: 'test', output_format: 'markdown' });
const callArgs = vi.mocked(spawn).mock.calls[0][1];
expect(callArgs).toContain('--output-format');
expect(callArgs).toContain('markdown');
});
});
// Test tool handler logic through runCursorAgent calls
// Since tools call runCursorAgent/invokeCursorAgent, we test the composition logic
describe('Tool handler composition logic', () => {
beforeEach(() => {
vi.clearAllMocks();
delete process.env.EXECUTING_CLIENT;
});
it('should compose edit_file prompt correctly', async () => {
const mockProcess = createMockChildProcess({ stdout: 'output', exitCode: 0 });
vi.mocked(spawn).mockReturnValue(mockProcess);
// Simulate cursor_agent_edit_file tool handler logic
const file = './test/file.txt';
const instruction = 'Add a comment';
const validatedFile = path.resolve(file);
const composedPrompt = `Edit the repository file:\n- File: ${validatedFile}\n- Instruction: ${instruction}\n- Propose a patch/diff without applying.\n`;
await runCursorAgent({ prompt: composedPrompt });
const callArgs = vi.mocked(spawn).mock.calls[0][1];
// Find the prompt argument (it's the last non-flag argument before model/force flags)
const promptArg = callArgs.find((arg, i) => {
const prev = callArgs[i - 1];
return arg && arg !== '-m' && arg !== '--model' && arg !== '-f' && arg !== '--force' &&
prev !== '-m' && prev !== '--model' && !arg.startsWith('--output-format') &&
!arg.startsWith('--print') && i > 2; // Skip initial flags
});
expect(promptArg).toContain('Edit the repository file');
expect(promptArg).toContain(instruction);
});
it('should compose analyze_files prompt with array of paths', async () => {
const mockProcess = createMockChildProcess({ stdout: 'output', exitCode: 0 });
vi.mocked(spawn).mockReturnValue(mockProcess);
// Simulate cursor_agent_analyze_files tool handler logic
const paths = ['./test/file1.txt', './test/file2.txt'];
const validatedPaths = paths.map(p => path.resolve(p));
const composedPrompt = `Analyze the following paths in the repository:\n${validatedPaths.map(p => `- ${p}`).join('\n')}\n`;
await runCursorAgent({ prompt: composedPrompt });
const callArgs = vi.mocked(spawn).mock.calls[0][1];
// Find the prompt argument
const promptArg = callArgs.find((arg, i) => {
const prev = callArgs[i - 1];
return arg && arg !== '-m' && arg !== '--model' && arg !== '-f' && arg !== '--force' &&
prev !== '-m' && prev !== '--model' && !arg.startsWith('--output-format') &&
!arg.startsWith('--print') && i > 2;
});
expect(promptArg).toContain('Analyze the following paths');
expect(promptArg).toContain('file1.txt');
expect(promptArg).toContain('file2.txt');
});
it('should compose search_repo prompt with include/exclude globs', async () => {
const mockProcess = createMockChildProcess({ stdout: 'output', exitCode: 0 });
vi.mocked(spawn).mockReturnValue(mockProcess);
// Simulate cursor_agent_search_repo tool handler logic
const query = 'function test';
const include = ['src/**/*.ts'];
const exclude = ['node_modules/**'];
const composedPrompt = `Search the repository for occurrences relevant to:\n- Query: ${query}\n- Include globs:\n - ${include[0]}\n- Exclude globs:\n - ${exclude[0]}\nReturn concise findings with file paths and line references.`;
await runCursorAgent({ prompt: composedPrompt });
const callArgs = vi.mocked(spawn).mock.calls[0][1];
// Find the prompt argument
const promptArg = callArgs.find((arg, i) => {
const prev = callArgs[i - 1];
return arg && arg !== '-m' && arg !== '--model' && arg !== '-f' && arg !== '--force' &&
prev !== '-m' && prev !== '--model' && !arg.startsWith('--output-format') &&
!arg.startsWith('--print') && i > 2;
});
expect(promptArg).toContain('Search the repository');
expect(promptArg).toContain(query);
expect(promptArg).toContain('Include globs');
expect(promptArg).toContain('Exclude globs');
});
it('should compose plan_task prompt with constraints', async () => {
const mockProcess = createMockChildProcess({ stdout: 'output', exitCode: 0 });
vi.mocked(spawn).mockReturnValue(mockProcess);
// Simulate cursor_agent_plan_task tool handler logic
const goal = 'Set up CI';
const constraints = ['GitHub Actions', 'Node 18'];
const composedPrompt = `Create a step-by-step plan to accomplish the following goal:\n- Goal: ${goal}\n- Constraints:\n - ${constraints[0]}\n - ${constraints[1]}\nProvide a numbered list of actions.`;
await runCursorAgent({ prompt: composedPrompt });
const callArgs = vi.mocked(spawn).mock.calls[0][1];
// Find the prompt argument
const promptArg = callArgs.find((arg, i) => {
const prev = callArgs[i - 1];
return arg && arg !== '-m' && arg !== '--model' && arg !== '-f' && arg !== '--force' &&
prev !== '-m' && prev !== '--model' && !arg.startsWith('--output-format') &&
!arg.startsWith('--print') && i > 2;
});
expect(promptArg).toContain('Create a step-by-step plan');
expect(promptArg).toContain(goal);
expect(promptArg).toContain('Constraints');
});
it('should handle raw tool with print=false', async () => {
const mockProcess = createMockChildProcess({ stdout: 'help output', exitCode: 0 });
vi.mocked(spawn).mockReturnValue(mockProcess);
// Simulate cursor_agent_raw tool handler logic
await invokeCursorAgent({ argv: ['--help'], print: false });
const callArgs = vi.mocked(spawn).mock.calls[0][1];
expect(callArgs).not.toContain('--print');
expect(callArgs).toContain('--help');
});
});
describe('Stream log and accumulated text', () => {
beforeEach(() => {
vi.clearAllMocks();
delete process.env.CURSOR_AGENT_ECHO_PROMPT;
delete process.env.DEBUG_CURSOR_MCP;
});
afterEach(() => {
vi.useRealTimers();
});
it('should return accumulated text from stream-json events', async () => {
const streamJsonEvents = [
JSON.stringify({ type: 'system', subtype: 'init', model: 'gpt-4' }) + '\n',
JSON.stringify({ type: 'assistant', message: { content: [{ text: 'Hello' }] } }) + '\n',
JSON.stringify({ type: 'assistant', message: { content: [{ text: ' world' }] } }) + '\n',
JSON.stringify({ type: 'result', duration_ms: 100 }) + '\n',
];
const mockProcess = createMockChildProcess({ stdout: streamJsonEvents.join(''), exitCode: 0 });
vi.mocked(spawn).mockReturnValue(mockProcess);
const onProgress = vi.fn();
const result = await invokeCursorAgent({
argv: ['test'],
output_format: 'text',
onProgress
});
// Should return accumulated text, not raw JSON
expect(result.content[0].text).toContain('Hello world');
expect(result.content[0].text).toContain('Full stream log:');
expect(result.streamLogFile).toBeDefined();
expect(fs.existsSync(result.streamLogFile)).toBe(true);
// Stream log should contain raw JSON events
const logContent = fs.readFileSync(result.streamLogFile, 'utf8');
const lines = logContent.trim().split('\n');
expect(lines.length).toBe(4);
expect(JSON.parse(lines[0]).type).toBe('system');
expect(JSON.parse(lines[1]).type).toBe('assistant');
// Clean up
if (fs.existsSync(result.streamLogFile)) {
fs.unlinkSync(result.streamLogFile);
}
});
it('should save all event types to stream log', async () => {
const streamJsonEvents = [
JSON.stringify({ type: 'system', subtype: 'init', model: 'gpt-4' }) + '\n',
JSON.stringify({
type: 'tool_call',
subtype: 'started',
tool_call: { writeToolCall: { args: { path: '/test/file.js' } } }
}) + '\n',
JSON.stringify({
type: 'tool_call',
subtype: 'completed',
tool_call: {
writeToolCall: {
result: { success: { linesCreated: 10, fileSize: 200 } }
}
}
}) + '\n',
JSON.stringify({ type: 'result', duration_ms: 150 }) + '\n',
];
const mockProcess = createMockChildProcess({ stdout: streamJsonEvents.join(''), exitCode: 0 });
vi.mocked(spawn).mockReturnValue(mockProcess);
const onProgress = vi.fn();
const result = await invokeCursorAgent({
argv: ['test'],
output_format: 'text',
onProgress
});
expect(result.streamLogFile).toBeDefined();
const logContent = fs.readFileSync(result.streamLogFile, 'utf8');
const lines = logContent.trim().split('\n');
// All events should be in the log as JSON
expect(lines.length).toBe(4);
const events = lines.map(line => JSON.parse(line));
expect(events[0].type).toBe('system');
expect(events[1].type).toBe('tool_call');
expect(events[1].subtype).toBe('started');
expect(events[2].type).toBe('tool_call');
expect(events[2].subtype).toBe('completed');
expect(events[3].type).toBe('result');
// Clean up
if (fs.existsSync(result.streamLogFile)) {
fs.unlinkSync(result.streamLogFile);
}
});
it('should handle partial JSON lines gracefully', async () => {
const completeEvent = JSON.stringify({ type: 'system', subtype: 'init', model: 'gpt-4' }) + '\n';
const partialEvent = JSON.stringify({ type: 'assistant', message: { content: [{ text: 'Hello' }] } }).slice(0, 20);
const mockProcess = createMockChildProcess({
stdout: completeEvent + partialEvent,
exitCode: 0
});
vi.mocked(spawn).mockReturnValue(mockProcess);
const onProgress = vi.fn();
const result = await invokeCursorAgent({
argv: ['test'],
output_format: 'text',
onProgress
});
// Should have stream log with at least the complete event
expect(result.streamLogFile).toBeDefined();
const logContent = fs.readFileSync(result.streamLogFile, 'utf8');
expect(logContent).toContain('"type":"system"');
// Clean up
if (fs.existsSync(result.streamLogFile)) {
fs.unlinkSync(result.streamLogFile);
}
});
it('should not create stream log for non-streaming output', async () => {
const mockProcess = createMockChildProcess({ stdout: 'plain output', exitCode: 0 });
vi.mocked(spawn).mockReturnValue(mockProcess);
const result = await invokeCursorAgent({ argv: ['test'], output_format: 'text' });
// No onProgress = no streaming = no stream log
expect(result.streamLogFile).toBeUndefined();
expect(result.content[0].text).toBe('plain output');
});
it('should include streamLogFile in error results when streaming', async () => {
const streamJsonEvents = [
JSON.stringify({ type: 'system', subtype: 'init', model: 'gpt-4' }) + '\n',
];
const mockProcess = createMockChildProcess({ stdout: streamJsonEvents.join(''), stderr: 'error', exitCode: 1 });
vi.mocked(spawn).mockReturnValue(mockProcess);
const onProgress = vi.fn();
const result = await invokeCursorAgent({ argv: ['test'], onProgress });
expect(result.isError).toBe(true);
expect(result.streamLogFile).toBeDefined();
expect(result.content[0].text).toContain('Full stream log:');
// Clean up
if (result.streamLogFile && fs.existsSync(result.streamLogFile)) {
fs.unlinkSync(result.streamLogFile);
}
});
it('should handle timeout gracefully with no events processed', async () => {
vi.useFakeTimers();
process.env.CURSOR_AGENT_TIMEOUT_MS = '100';
const mockProcess = createMockChildProcess({ stdout: '', exitCode: 0, delay: 200 });
vi.mocked(spawn).mockReturnValue(mockProcess);
const onProgress = vi.fn();
const resultPromise = invokeCursorAgent({ argv: ['test'], onProgress });
vi.advanceTimersByTime(150);
const result = await resultPromise;
expect(result.isError).toBe(true);
expect(result.content[0].text).toContain('timed out');
// No stream log when no events were processed before timeout
expect(result.streamLogFile).toBeUndefined();
});
it('should accumulate text deltas correctly', async () => {
const streamJsonEvents = [
JSON.stringify({ type: 'assistant', message: { content: [{ text: 'Hello' }] } }) + '\n',
JSON.stringify({ type: 'assistant', message: { content: [{ text: ' world' }] } }) + '\n',
JSON.stringify({ type: 'assistant', message: { content: [{ text: '!' }] } }) + '\n',
];
const mockProcess = createMockChildProcess({ stdout: streamJsonEvents.join(''), exitCode: 0 });
vi.mocked(spawn).mockReturnValue(mockProcess);
const onProgress = vi.fn();
const result = await invokeCursorAgent({
argv: ['test'],
output_format: 'text',
onProgress
});
// Response should contain accumulated text
expect(result.content[0].text).toContain('Hello world!');
// Clean up
if (result.streamLogFile && fs.existsSync(result.streamLogFile)) {
fs.unlinkSync(result.streamLogFile);
}
});
});
describe('Stream log path appending', () => {
beforeEach(() => {
vi.clearAllMocks();
delete process.env.CURSOR_AGENT_ECHO_PROMPT;
delete process.env.DEBUG_CURSOR_MCP;
});
afterEach(() => {
vi.useRealTimers();
});
it('should append stream log path to success result when streaming', async () => {
const streamJsonEvents = [
JSON.stringify({ type: 'assistant', message: { content: [{ text: 'test output' }] } }) + '\n',
];
const mockProcess = createMockChildProcess({ stdout: streamJsonEvents.join(''), exitCode: 0 });
vi.mocked(spawn).mockReturnValue(mockProcess);
const onProgress = vi.fn();
const result = await invokeCursorAgent({ argv: ['test'], output_format: 'text', onProgress });
expect(result.streamLogFile).toBeDefined();
expect(result.content).toBeDefined();
expect(result.content[0].type).toBe('text');
expect(result.content[0].text).toContain('test output');
expect(result.content[0].text).toContain('Full stream log:');
expect(result.content[0].text).toContain(result.streamLogFile);
// Clean up
if (fs.existsSync(result.streamLogFile)) {
fs.unlinkSync(result.streamLogFile);
}
});
it('should not append stream log path for non-streaming calls', async () => {
const mockProcess = createMockChildProcess({ stdout: 'test output', exitCode: 0 });
vi.mocked(spawn).mockReturnValue(mockProcess);
const result = await invokeCursorAgent({ argv: ['test'] });
expect(result.streamLogFile).toBeUndefined();
expect(result.content[0].text).toBe('test output');
expect(result.content[0].text).not.toContain('Full stream log:');
});
it('should append stream log path to error result when streaming', async () => {
const streamJsonEvents = [
JSON.stringify({ type: 'assistant', message: { content: [{ text: 'output' }] } }) + '\n',
];
const mockProcess = createMockChildProcess({ stdout: streamJsonEvents.join(''), stderr: 'error', exitCode: 1 });
vi.mocked(spawn).mockReturnValue(mockProcess);
const onProgress = vi.fn();
const result = await invokeCursorAgent({ argv: ['test'], onProgress });
expect(result.isError).toBe(true);
expect(result.streamLogFile).toBeDefined();
expect(result.content[0].text).toContain('cursor-agent exited with code 1');
expect(result.content[0].text).toContain('Full stream log:');
// Clean up
if (result.streamLogFile && fs.existsSync(result.streamLogFile)) {
fs.unlinkSync(result.streamLogFile);
}
});
it('should handle timeout without stream log when no events processed', async () => {
vi.useFakeTimers();
process.env.CURSOR_AGENT_TIMEOUT_MS = '100';
const mockProcess = createMockChildProcess({ stdout: '', exitCode: 0, delay: 200 });
vi.mocked(spawn).mockReturnValue(mockProcess);
const onProgress = vi.fn();
const resultPromise = invokeCursorAgent({ argv: ['test'], onProgress });
vi.advanceTimersByTime(150);
const result = await resultPromise;
expect(result.isError).toBe(true);
expect(result.content[0].text).toContain('cursor-agent timed out after 100ms');
// No stream log or partial response when timeout occurs before any events
expect(result.streamLogFile).toBeUndefined();
expect(result.content[0].text).not.toContain('Full stream log:');
});
it('should not append stream log path when writeStreamLog fails', async () => {
const originalWriteFileSync = fs.writeFileSync;
vi.spyOn(fs, 'writeFileSync').mockImplementation(() => {
throw new Error('Cannot write to file');
});
const streamJsonEvents = [
JSON.stringify({ type: 'assistant', message: { content: [{ text: 'test output' }] } }) + '\n',
];
const mockProcess = createMockChildProcess({ stdout: streamJsonEvents.join(''), exitCode: 0 });
vi.mocked(spawn).mockReturnValue(mockProcess);
const onProgress = vi.fn();
const result = await invokeCursorAgent({ argv: ['test'], onProgress });
expect(result.streamLogFile).toBeUndefined();
expect(result.content[0].text).toBe('test output');
expect(result.content[0].text).not.toContain('Full stream log:');
fs.writeFileSync = originalWriteFileSync;
});
it('should use system temp directory for stream log path', async () => {
const streamJsonEvents = [
JSON.stringify({ type: 'assistant', message: { content: [{ text: 'test' }] } }) + '\n',
];
const mockProcess = createMockChildProcess({ stdout: streamJsonEvents.join(''), exitCode: 0 });
vi.mocked(spawn).mockReturnValue(mockProcess);
const onProgress = vi.fn();
const result = await invokeCursorAgent({ argv: ['test'], onProgress });
expect(result.streamLogFile).toBeDefined();
const os = require('node:os');
const tempDir = os.tmpdir();
expect(result.streamLogFile).toMatch(new RegExp(`^${tempDir.replace(/\\/g, '\\\\')}`));
expect(result.streamLogFile).toMatch(/cursor-agent-stream-/);
// Clean up
if (fs.existsSync(result.streamLogFile)) {
fs.unlinkSync(result.streamLogFile);
}
});
it('should format stream log path correctly with separator', async () => {
const streamJsonEvents = [
JSON.stringify({ type: 'assistant', message: { content: [{ text: 'test output' }] } }) + '\n',
];
const mockProcess = createMockChildProcess({ stdout: streamJsonEvents.join(''), exitCode: 0 });
vi.mocked(spawn).mockReturnValue(mockProcess);
const onProgress = vi.fn();
const result = await invokeCursorAgent({ argv: ['test'], onProgress });
expect(result.content[0].text).toMatch(/test output\n\n---\nFull stream log: /);
// Format is now: path (N events, X.XKB)
expect(result.content[0].text).toContain(result.streamLogFile);
expect(result.content[0].text).toMatch(/\(1 events?, \d+\.\d+KB\)/);
// Clean up
if (fs.existsSync(result.streamLogFile)) {
fs.unlinkSync(result.streamLogFile);
}
});
it('should show warning for large stream logs', async () => {
// Create enough events to trigger the "large" threshold (>50 events)
const streamJsonEvents = [];
for (let i = 0; i < 55; i++) {
streamJsonEvents.push(JSON.stringify({ type: 'assistant', message: { content: [{ text: `chunk ${i}` }] } }) + '\n');
}
const mockProcess = createMockChildProcess({ stdout: streamJsonEvents.join(''), exitCode: 0 });
vi.mocked(spawn).mockReturnValue(mockProcess);
const onProgress = vi.fn();
const result = await invokeCursorAgent({ argv: ['test'], onProgress });
expect(result.content[0].text).toContain('Full stream log:');
expect(result.content[0].text).toMatch(/\(55 events, \d+\.\d+KB\)/);
expect(result.content[0].text).toContain('⚠️ Large log - use semantic search or grep instead of reading entire file if more details are needed');
// Clean up
if (fs.existsSync(result.streamLogFile)) {
fs.unlinkSync(result.streamLogFile);
}
});
it('should not show warning for small stream logs', async () => {
const streamJsonEvents = [
JSON.stringify({ type: 'assistant', message: { content: [{ text: 'small output' }] } }) + '\n',
];
const mockProcess = createMockChildProcess({ stdout: streamJsonEvents.join(''), exitCode: 0 });
vi.mocked(spawn).mockReturnValue(mockProcess);
const onProgress = vi.fn();
const result = await invokeCursorAgent({ argv: ['test'], onProgress });
expect(result.content[0].text).toContain('Full stream log:');
expect(result.content[0].text).toMatch(/\(1 events?, \d+\.\d+KB\)/);
expect(result.content[0].text).not.toContain('⚠️');
// Clean up
if (fs.existsSync(result.streamLogFile)) {
fs.unlinkSync(result.streamLogFile);
}
});
});
describe('Cancellation support', () => {
beforeEach(() => {
vi.clearAllMocks();
});
afterEach(() => {
vi.useRealTimers();
});
it('should handle cancellation when signal is already aborted', async () => {
const abortController = new AbortController();
abortController.abort('Test cancellation');
const result = await invokeCursorAgent({
argv: ['test'],
signal: abortController.signal,
});
expect(result.isError).toBe(true);
expect(result.content[0].text).toContain('cancelled');
// No stream log for non-streaming cancellation
});
it('should handle cancellation with streaming when no events processed yet', async () => {
const abortController = new AbortController();
const mockProcess = createMockChildProcess({
stdout: '',
exitCode: 0,
delay: 100,
});
vi.mocked(spawn).mockReturnValue(mockProcess);
const onProgress = vi.fn();
const promise = invokeCursorAgent({
argv: ['test'],
signal: abortController.signal,
onProgress,
});
await Promise.resolve();
abortController.abort('User cancelled');
const result = await promise;
expect(result.isError).toBe(true);
expect(result.content[0].text).toContain('cancelled');
expect(result.content[0].text).toContain('User cancelled');
// No stream log or partial response when cancelled before any events
expect(result.streamLogFile).toBeUndefined();
});
it('should kill child process when signal is aborted', async () => {
const abortController = new AbortController();
const mockProcess = createMockChildProcess({
stdout: 'partial output',
exitCode: 0,
delay: 100,
});
const killSpy = vi.spyOn(mockProcess, 'kill');
vi.mocked(spawn).mockReturnValue(mockProcess);
const promise = invokeCursorAgent({
argv: ['test'],
signal: abortController.signal,
});
await Promise.resolve();
abortController.abort('User cancelled');
const result = await promise;
expect(result.isError).toBe(true);
expect(result.content[0].text).toContain('cancelled');
expect(killSpy).toHaveBeenCalledWith('SIGKILL');
});
it('should clean up abort listener on completion', async () => {
const abortController = new AbortController();
const mockProcess = createMockChildProcess({ stdout: 'output', exitCode: 0 });
vi.mocked(spawn).mockReturnValue(mockProcess);
const removeEventListenerSpy = vi.spyOn(abortController.signal, 'removeEventListener');
await invokeCursorAgent({
argv: ['test'],
signal: abortController.signal,
});
expect(removeEventListenerSpy).toHaveBeenCalled();
});
it('should handle cancellation gracefully without signal', async () => {
const mockProcess = createMockChildProcess({ stdout: 'output', exitCode: 0 });
vi.mocked(spawn).mockReturnValue(mockProcess);
const result = await invokeCursorAgent({
argv: ['test'],
signal: undefined,
});
expect(result.isError).toBeUndefined();
expect(result.content[0].text).toContain('output');
// No stream log for non-streaming calls
expect(result.streamLogFile).toBeUndefined();
});
it('should include cancellation reason in error message', async () => {
const abortController = new AbortController();
abortController.abort('Custom cancellation reason');
const result = await invokeCursorAgent({
argv: ['test'],
signal: abortController.signal,
});
expect(result.isError).toBe(true);
expect(result.content[0].text).toContain('Custom cancellation reason');
});
});