-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathagent-interface.test.ts
More file actions
446 lines (380 loc) · 13.2 KB
/
agent-interface.test.ts
File metadata and controls
446 lines (380 loc) · 13.2 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
import { runAgent, createStopHook } from '../agent-interface';
import type { WizardOptions } from '../../utils/types';
import type { SpinnerHandle } from '../../ui';
import {
AdditionalFeature,
ADDITIONAL_FEATURE_PROMPTS,
} from '../wizard-session';
// Mock dependencies
jest.mock('../../utils/analytics');
jest.mock('../../utils/debug');
// Mock the SDK module
const mockQuery = jest.fn();
jest.mock('@anthropic-ai/claude-agent-sdk', () => ({
query: (...args: unknown[]) => mockQuery(...args),
}));
// Mock the UI layer
const mockUIInstance = {
log: {
step: jest.fn(),
success: jest.fn(),
error: jest.fn(),
warn: jest.fn(),
info: jest.fn(),
},
spinner: jest.fn(),
select: jest.fn(),
confirm: jest.fn(),
text: jest.fn(),
intro: jest.fn(),
outro: jest.fn(),
cancel: jest.fn(),
note: jest.fn(),
isCancel: jest.fn(),
setDetectedFramework: jest.fn(),
setCredentials: jest.fn(),
pushStatus: jest.fn(),
setLoginUrl: jest.fn(),
showBlockingOutage: jest.fn(),
setReadinessWarnings: jest.fn(),
showSettingsOverride: jest.fn(),
startRun: jest.fn(),
syncTodos: jest.fn(),
groupMultiselect: jest.fn(),
multiselect: jest.fn(),
};
jest.mock('../../ui', () => ({
getUI: () => mockUIInstance,
}));
describe('runAgent', () => {
let mockSpinner: {
start: jest.Mock;
stop: jest.Mock;
message: jest.Mock;
};
const defaultOptions: WizardOptions = {
debug: false,
installDir: '/test/dir',
forceInstall: false,
default: false,
signup: false,
localMcp: false,
ci: false,
menu: false,
benchmark: false,
yaraReport: false,
};
const defaultAgentConfig = {
workingDirectory: '/test/dir',
mcpServers: {},
model: 'claude-opus-4-5-20251101',
};
beforeEach(() => {
jest.clearAllMocks();
mockSpinner = {
start: jest.fn(),
stop: jest.fn(),
message: jest.fn(),
};
mockUIInstance.spinner.mockReturnValue(mockSpinner);
// Reset log mocks
Object.values(mockUIInstance.log).forEach((fn) => fn.mockReset());
});
describe('race condition handling', () => {
it('should return success when agent completes successfully then SDK cleanup fails', async () => {
// This simulates the race condition:
// 1. Agent completes with success result
// 2. signalDone() is called, completing the prompt generator
// 3. SDK tries to send cleanup command while streaming is active
// 4. SDK throws an error
// The fix should recognize we already got a success and return success anyway
function* mockGeneratorWithCleanupError() {
yield {
type: 'system',
subtype: 'init',
model: 'claude-opus-4-5-20251101',
tools: [],
mcp_servers: [],
};
yield {
type: 'result',
subtype: 'success',
is_error: false,
result: 'Agent completed successfully',
};
// Simulate the SDK cleanup error that occurs after success
throw new Error('only prompt commands are supported in streaming mode');
}
mockQuery.mockReturnValue(mockGeneratorWithCleanupError());
const result = await runAgent(
defaultAgentConfig,
'test prompt',
defaultOptions,
mockSpinner as unknown as SpinnerHandle,
{
successMessage: 'Test success',
errorMessage: 'Test error',
},
);
// Should return success (empty object), not throw
expect(result).toEqual({});
expect(mockSpinner.stop).toHaveBeenCalledWith('Test success');
});
it('should still throw when no success result was received before error', async () => {
// If we never got a success result, errors should propagate normally
function* mockGeneratorWithOnlyError() {
yield {
type: 'system',
subtype: 'init',
model: 'claude-opus-4-5-20251101',
tools: [],
mcp_servers: [],
};
// No success result, just an error
throw new Error('Actual SDK error');
}
mockQuery.mockReturnValue(mockGeneratorWithOnlyError());
await expect(
runAgent(
defaultAgentConfig,
'test prompt',
defaultOptions,
mockSpinner as unknown as SpinnerHandle,
{
successMessage: 'Test success',
errorMessage: 'Test error',
},
),
).rejects.toThrow('Actual SDK error');
expect(mockSpinner.stop).toHaveBeenCalledWith('Test error');
});
it('should not treat error results as success', async () => {
// A result with is_error: true should not count as success
// Even if subtype is 'success', the is_error flag takes precedence
function* mockGeneratorWithErrorResult() {
yield {
type: 'system',
subtype: 'init',
model: 'claude-opus-4-5-20251101',
tools: [],
mcp_servers: [],
};
yield {
type: 'result',
subtype: 'success', // subtype can be success but is_error true
is_error: true,
result: 'API Error: 500 Internal Server Error',
};
throw new Error('Process exited with code 1');
}
mockQuery.mockReturnValue(mockGeneratorWithErrorResult());
const result = await runAgent(
defaultAgentConfig,
'test prompt',
defaultOptions,
mockSpinner as unknown as SpinnerHandle,
{
successMessage: 'Test success',
errorMessage: 'Test error',
},
);
// Should return API error, not success
expect(result.error).toBe('WIZARD_API_ERROR');
expect(result.message).toContain('API Error');
});
it('should suppress user-facing errors when SDK yields error result after success', async () => {
// This test models actual SDK behavior where the SDK emits TWO result messages:
// 1. SDK yields success result (num_turns: 105, is_error: false)
// 2. SDK yields a SECOND result with is_error: true containing
// accumulated cleanup/telemetry errors
// 3. The errors should be logged to file but NOT shown to the user
//
// This differs from the thrown exception test above - here the SDK YIELDS
// an error result message instead of THROWING an exception.
function* mockGeneratorWithYieldedErrorAfterSuccess() {
yield {
type: 'system',
subtype: 'init',
model: 'claude-opus-4-5-20251101',
tools: [],
mcp_servers: [],
};
// First result: success (this is the real completion)
yield {
type: 'result',
subtype: 'success',
is_error: false,
num_turns: 105,
result: '[WIZARD-REMARK] Integration completed successfully',
session_id: '2ce14bda-6d86-4220-b5bb-ab24f7004290',
total_cost_usd: 5.83,
};
// Second result: error (SDK cleanup noise - yielded, not thrown)
yield {
type: 'result',
subtype: 'error_during_execution',
is_error: true,
num_turns: 0,
session_id: '2ce14bda-6d86-4220-b5bb-ab24f7004290',
total_cost_usd: 0,
errors: [
'only prompt commands are supported in streaming mode',
'Error: 1P event logging: 14 events failed to export',
'Error: 1P event logging: 13 events failed to export',
'Error: Failed to export 14 events',
],
};
}
mockQuery.mockReturnValue(mockGeneratorWithYieldedErrorAfterSuccess());
const result = await runAgent(
defaultAgentConfig,
'test prompt',
defaultOptions,
mockSpinner as unknown as SpinnerHandle,
{
successMessage: 'Test success',
errorMessage: 'Test error',
},
);
// Should return success (empty object), not error
expect(result).toEqual({});
expect(mockSpinner.stop).toHaveBeenCalledWith('Test success');
// ui.log.error should NOT have been called (errors suppressed for user)
expect(mockUIInstance.log.error).not.toHaveBeenCalled();
});
it('passes resume to the SDK and returns the active session id', async () => {
function* mockGeneratorWithSessionId() {
yield {
type: 'system',
subtype: 'init',
model: 'claude-opus-4-5-20251101',
tools: [],
mcp_servers: [],
session_id: 'session-123',
};
yield {
type: 'assistant',
session_id: 'session-123',
message: {
content: [{ type: 'text', text: '[STATUS] Working through queue' }],
},
};
yield {
type: 'result',
subtype: 'success',
is_error: false,
session_id: 'session-123',
result: 'Queued step complete',
};
}
mockQuery.mockReturnValue(mockGeneratorWithSessionId());
const result = await runAgent(
defaultAgentConfig,
'queued prompt',
defaultOptions,
mockSpinner as unknown as SpinnerHandle,
{
successMessage: 'Queued success',
resumeSessionId: 'session-123',
requestRemark: false,
captureOutputText: true,
captureSessionId: true,
},
);
expect(mockQuery).toHaveBeenCalledWith(
expect.objectContaining({
options: expect.objectContaining({
resume: 'session-123',
}),
}),
);
expect(result.sessionId).toBe('session-123');
expect(result.outputText).toContain('Queued step complete');
});
});
});
describe('createStopHook', () => {
const hookInput = { stop_hook_active: false };
it('empty queue: first call blocks for remark, second allows stop', () => {
const hook = createStopHook([]);
// First call → remark prompt
const first = hook(hookInput);
expect(first).toHaveProperty('decision', 'block');
expect((first as { reason: string }).reason).toContain('WIZARD-REMARK');
// Second call → allow stop
const second = hook(hookInput);
expect(second).toEqual({});
});
it('single feature: feature prompt, then remark, then allow stop', () => {
const hook = createStopHook([AdditionalFeature.LLM]);
// First call → LLM feature prompt
const first = hook(hookInput);
expect(first).toHaveProperty('decision', 'block');
expect((first as { reason: string }).reason).toBe(
ADDITIONAL_FEATURE_PROMPTS[AdditionalFeature.LLM],
);
// Second call → remark prompt
const second = hook(hookInput);
expect(second).toHaveProperty('decision', 'block');
expect((second as { reason: string }).reason).toContain('WIZARD-REMARK');
// Third call → allow stop
const third = hook(hookInput);
expect(third).toEqual({});
});
it('multiple queue entries: drains all, then remark, then allow stop', () => {
// Queue the same feature twice to exercise multi-item draining
const hook = createStopHook([AdditionalFeature.LLM, AdditionalFeature.LLM]);
// First call → LLM prompt
const first = hook(hookInput);
expect(first).toHaveProperty('decision', 'block');
expect((first as { reason: string }).reason).toBe(
ADDITIONAL_FEATURE_PROMPTS[AdditionalFeature.LLM],
);
// Second call → LLM prompt again
const second = hook(hookInput);
expect(second).toHaveProperty('decision', 'block');
expect((second as { reason: string }).reason).toBe(
ADDITIONAL_FEATURE_PROMPTS[AdditionalFeature.LLM],
);
// Third call → remark prompt
const third = hook(hookInput);
expect(third).toHaveProperty('decision', 'block');
expect((third as { reason: string }).reason).toContain('WIZARD-REMARK');
// Fourth call → allow stop
const fourth = hook(hookInput);
expect(fourth).toEqual({});
});
it('allow stop is idempotent after all phases complete', () => {
const hook = createStopHook([]);
hook(hookInput); // remark
hook(hookInput); // allow
const extra = hook(hookInput); // still allow
expect(extra).toEqual({});
});
it('allows stop immediately on API error (401)', () => {
const collectedText = [
'Failed to authenticate. API Error: 401 {"detail":"Authentication required"}',
];
const hook = createStopHook([AdditionalFeature.LLM], collectedText);
const result = hook(hookInput);
expect(result).toEqual({});
});
it('allows stop immediately on generic API error', () => {
const collectedText = ['API Error: 500 Internal Server Error'];
const hook = createStopHook([AdditionalFeature.LLM], collectedText);
const result = hook(hookInput);
expect(result).toEqual({});
});
it('proceeds normally when collectedText has no API error', () => {
const collectedText = ['Some normal agent output'];
const hook = createStopHook([], collectedText);
// First call → remark prompt (normal behavior)
const first = hook(hookInput);
expect(first).toHaveProperty('decision', 'block');
expect((first as { reason: string }).reason).toContain('WIZARD-REMARK');
});
it('can skip the remark collection phase for intermediate queued steps', () => {
const hook = createStopHook([], [], { requestRemark: false });
expect(hook(hookInput)).toEqual({});
});
});