-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathruntime-executor.test.ts
More file actions
494 lines (464 loc) · 14.9 KB
/
Copy pathruntime-executor.test.ts
File metadata and controls
494 lines (464 loc) · 14.9 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
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import {
RuntimeHost,
RestoreReviewActionTool,
SessionManager,
ToolRegistry,
type AgentEvent,
type Provider,
type ProviderResult,
type ProviderRunOpts,
} from '@deepcode/core';
import type { ThreadSnapshot, TurnSnapshot } from '@deepcode/protocol';
import { describe, expect, it, vi } from 'vitest';
import {
RuntimeHostExecutor,
historyFromThread,
reviewFindingsFromEvents,
} from './runtime-executor.js';
function protocolCallbacks() {
return {
publishToolStarted: () => undefined,
publishToolCompleted: () => undefined,
publishUsage: () => undefined,
requestApproval: async () => 'deny' as const,
requestUserInput: async () => '',
};
}
const priorAssistant = {
role: 'assistant' as const,
content: [{ type: 'text' as const, text: 'prior answer' }],
};
const thread: ThreadSnapshot = {
id: 'thread-1',
cwd: '/workspace',
createdAt: '2026-08-01T00:00:00.000Z',
updatedAt: '2026-08-01T00:00:01.000Z',
turns: [
{
id: 'turn-prior',
threadId: 'thread-1',
status: 'completed',
startedAt: '2026-08-01T00:00:00.000Z',
completedAt: '2026-08-01T00:00:01.000Z',
items: [
{
id: 'item-user',
type: 'user_message',
payload: { text: 'prior question' },
completedAt: '2026-08-01T00:00:00.000Z',
},
{
id: 'item-assistant',
type: 'assistant_message',
payload: { message: priorAssistant },
completedAt: '2026-08-01T00:00:01.000Z',
},
],
},
],
};
class StreamingProvider implements Provider {
readonly name = 'streaming-test';
seenMessages: ProviderRunOpts['messages'] = [];
seenOptions?: ProviderRunOpts;
async runTurn(options: ProviderRunOpts): Promise<ProviderResult> {
this.seenOptions = options;
this.seenMessages = options.messages;
options.handlers?.onTextDelta?.('new ');
options.handlers?.onTextDelta?.('answer');
return {
content: [{ type: 'text', text: 'new answer' }],
stopReason: 'end_turn',
usage: { inputTokens: 1, outputTokens: 2, reasoningTokens: 0, cacheReadTokens: 0 },
};
}
}
class ToolProvider implements Provider {
readonly name = 'tool-test';
calls = 0;
async runTurn(options: ProviderRunOpts): Promise<ProviderResult> {
this.calls++;
if (this.calls === 1) {
return {
content: [{ type: 'tool_use', id: 'tool-1', name: 'WriteTest', input: { value: 'ok' } }],
stopReason: 'tool_use',
usage: { inputTokens: 3, outputTokens: 4, reasoningTokens: 1, cacheReadTokens: 2 },
};
}
options.handlers?.onTextDelta?.('done');
return {
content: [{ type: 'text', text: 'done' }],
stopReason: 'end_turn',
usage: { inputTokens: 5, outputTokens: 6, reasoningTokens: 0, cacheReadTokens: 0 },
};
}
}
describe('RuntimeHostExecutor', () => {
it('exposes only the restore tool to a canonical revert turn', async () => {
const provider = new StreamingProvider();
const tools = new ToolRegistry();
tools.register(RestoreReviewActionTool);
const host = new RuntimeHost({
provider,
tools,
cwd: '/workspace',
});
const executor = new RuntimeHostExecutor({ createHost: () => host });
await executor.execute({
thread,
turn: {
id: 'turn-revert',
threadId: thread.id,
status: 'in_progress',
startedAt: '2026-08-01T00:00:02.000Z',
items: [],
},
input: {
text: 'revert',
reviewAction: { kind: 'revert', sourceActionId: 'turn-apply', findingIds: ['finding-1'] },
},
signal: new AbortController().signal,
publishDelta: () => undefined,
...protocolCallbacks(),
});
expect(provider.seenOptions?.tools.map((tool) => tool.name)).toEqual(['RestoreReviewAction']);
});
it('projects validated review tool results into durable finding items', () => {
const events: AgentEvent[] = [
{
type: 'tool_use',
id: 'finding-1',
name: 'SubmitReviewFinding',
input: {},
},
{
type: 'tool_result',
id: 'finding-1',
result: {
content: 'recorded',
data: {
finding: {
title: 'Null crash',
body: 'This branch dereferences null.',
path: 'src/a.ts',
startLine: 4,
endLine: 4,
priority: 1,
},
},
},
},
];
expect(reviewFindingsFromEvents(events)).toEqual([
{
type: 'review_finding',
payload: expect.objectContaining({ findingId: 'finding-1', path: 'src/a.ts' }),
},
]);
});
it('reconstructs history and returns only messages created by the new turn', async () => {
const provider = new StreamingProvider();
const host = new RuntimeHost({
provider,
tools: new ToolRegistry(),
cwd: '/workspace',
});
const executor = new RuntimeHostExecutor({ createHost: () => host });
const turn: TurnSnapshot = {
id: 'turn-current',
threadId: thread.id,
status: 'in_progress',
startedAt: '2026-08-01T00:00:02.000Z',
items: [],
};
const deltas: string[] = [];
const result = await executor.execute({
thread,
turn,
input: { text: 'current question' },
signal: new AbortController().signal,
publishDelta: (_itemId, delta) => deltas.push(delta),
...protocolCallbacks(),
});
expect(provider.seenMessages).toEqual([
{ role: 'user', content: [{ type: 'text', text: 'prior question' }] },
priorAssistant,
expect.objectContaining({
role: 'user',
content: [{ type: 'text', text: 'current question' }],
}),
]);
expect(deltas).toEqual(['new ', 'answer']);
expect(result).toEqual({
status: 'completed',
items: [
{
type: 'assistant_message',
payload: {
message: expect.objectContaining({
role: 'assistant',
content: [{ type: 'text', text: 'new answer' }],
}),
},
},
],
});
});
it('uses per-turn composition defaults and always releases the host lease', async () => {
const provider = new StreamingProvider();
const close = vi.fn();
const prepareUserMessage = vi.fn(async () => ({
text: 'composed user message',
diagnostics: [
{
source: 'mcp',
code: 'mcp_resource_failed',
severity: 'warning' as const,
message: 'bad ref',
},
],
}));
const executor = new RuntimeHostExecutor({
createHost: () => ({
host: new RuntimeHost({ provider, tools: new ToolRegistry(), cwd: '/workspace' }),
systemPrompt: 'composed instructions',
model: 'deepseek-reasoner',
effort: 'low',
diagnostics: [
{ source: 'mcp', code: 'mcp_connect_failed', severity: 'warning', message: 'offline' },
],
prepareUserMessage,
close,
}),
});
const result = await executor.execute({
thread: { ...thread, turns: [] },
turn: {
id: 'turn-lease',
threadId: thread.id,
status: 'in_progress',
startedAt: '2026-08-01T00:00:02.000Z',
items: [],
},
input: { text: 'use composition' },
signal: new AbortController().signal,
publishDelta: () => undefined,
...protocolCallbacks(),
});
expect(provider.seenOptions).toEqual(
expect.objectContaining({
systemPrompt: 'composed instructions',
model: 'deepseek-reasoner',
maxTokens: 1_500,
}),
);
expect(provider.seenMessages.at(-1)).toEqual(
expect.objectContaining({
role: 'user',
content: [{ type: 'text', text: 'composed user message' }],
}),
);
expect(result.items.filter((item) => item.type === 'error')).toHaveLength(2);
expect(prepareUserMessage).toHaveBeenCalledWith('use composition');
expect(close).toHaveBeenCalledOnce();
});
it('does not let an invalid mode suppress the trusted composed default', async () => {
const createHost = vi.fn(
(_cwd: string, _mode: string) =>
new RuntimeHost({
provider: new StreamingProvider(),
tools: new ToolRegistry(),
cwd: '/workspace',
}),
);
const executor = new RuntimeHostExecutor({ createHost });
await executor.execute({
thread: { ...thread, turns: [] },
turn: {
id: 'turn-invalid-mode',
threadId: thread.id,
status: 'in_progress',
startedAt: '2026-08-01T00:00:02.000Z',
items: [],
},
input: { text: 'use defaults', mode: 'invalid' },
signal: new AbortController().signal,
publishDelta: () => undefined,
...protocolCallbacks(),
});
expect(createHost).toHaveBeenCalledWith(
'/workspace',
'default',
expect.objectContaining({ modeExplicit: false }),
);
});
it('releases the host lease when message preparation fails', async () => {
const close = vi.fn();
const executor = new RuntimeHostExecutor({
createHost: () => ({
host: new RuntimeHost({
provider: new StreamingProvider(),
tools: new ToolRegistry(),
cwd: '/workspace',
}),
prepareUserMessage: async () => {
throw new Error('resource expansion failed');
},
close,
}),
});
await expect(
executor.execute({
thread: { ...thread, turns: [] },
turn: {
id: 'turn-prepare-failure',
threadId: thread.id,
status: 'in_progress',
startedAt: '2026-08-01T00:00:02.000Z',
items: [],
},
input: { text: 'expand this' },
signal: new AbortController().signal,
publishDelta: () => undefined,
...protocolCallbacks(),
}),
).rejects.toThrow('resource expansion failed');
expect(close).toHaveBeenCalledOnce();
});
it('ignores non-message protocol items when rebuilding provider history', () => {
const withError: ThreadSnapshot = {
...thread,
turns: [
{
...thread.turns[0]!,
items: [
...thread.turns[0]!.items,
{
id: 'item-error',
type: 'error',
payload: { message: 'transport failed' },
completedAt: '2026-08-01T00:00:01.000Z',
},
],
},
],
};
expect(historyFromThread(withError)).toHaveLength(2);
});
it('projects tool, usage, and approval activity onto protocol callbacks', async () => {
const provider = new ToolProvider();
const tools = new ToolRegistry();
tools.register({
name: 'WriteTest',
definition: { name: 'WriteTest', description: 'test', inputSchema: { type: 'object' } },
execute: async () => ({ content: 'wrote test value' }),
});
const host = new RuntimeHost({ provider, tools, cwd: '/workspace', mode: 'default' });
const executor = new RuntimeHostExecutor({ createHost: () => host });
const turn: TurnSnapshot = {
id: 'turn-tool',
threadId: thread.id,
status: 'in_progress',
startedAt: '2026-08-01T00:00:02.000Z',
items: [],
};
const started: string[] = [];
const completed: string[] = [];
const usage: number[] = [];
const approvals: string[] = [];
const result = await executor.execute({
thread,
turn,
input: { text: 'write it', effort: 'low' },
signal: new AbortController().signal,
publishDelta: () => undefined,
publishToolStarted: (itemId) => started.push(itemId),
publishToolCompleted: (itemId) => completed.push(itemId),
publishUsage: (value) => usage.push(value.inputTokens),
requestApproval: async (toolName) => {
approvals.push(toolName);
return 'allow';
},
requestUserInput: async () => '',
});
expect(started).toEqual(['tool-1']);
expect(completed).toEqual(['tool-1']);
expect(usage).toEqual([3, 5]);
expect(approvals).toEqual(['WriteTest']);
expect(result.items).toEqual(
expect.arrayContaining([
expect.objectContaining({ type: 'approval' }),
expect.objectContaining({ type: 'assistant_message' }),
expect.objectContaining({ type: 'tool_result' }),
]),
);
});
it('keeps session snapshots without becoming a second message writer', async () => {
const root = await mkdtemp(join(tmpdir(), 'deepcode-executor-session-'));
try {
const workspace = join(root, 'workspace');
const filePath = join(workspace, 'file.txt');
await mkdir(workspace);
await writeFile(filePath, 'before');
const provider = new ToolProvider();
const tools = new ToolRegistry([]);
// The core snapshot pipeline recognizes canonical Write/Edit names.
provider.runTurn = async (options) => {
provider.calls++;
if (provider.calls === 1) {
return {
content: [
{ type: 'tool_use', id: 'tool-1', name: 'Write', input: { file_path: filePath } },
],
stopReason: 'tool_use',
usage: { inputTokens: 1, outputTokens: 1, reasoningTokens: 0, cacheReadTokens: 0 },
};
}
options.handlers?.onTextDelta?.('done');
return {
content: [{ type: 'text', text: 'done' }],
stopReason: 'end_turn',
usage: { inputTokens: 1, outputTokens: 1, reasoningTokens: 0, cacheReadTokens: 0 },
};
};
tools.register({
name: 'Write',
definition: { name: 'Write', description: 'write', inputSchema: { type: 'object' } },
execute: async () => {
await writeFile(filePath, 'after');
return { content: 'written' };
},
});
const sessions = new SessionManager({ root: join(root, 'sessions') });
const host = new RuntimeHost({ provider, tools, cwd: workspace, mode: 'default' });
const executor = new RuntimeHostExecutor({
createHost: () => host,
sessionManager: sessions,
});
await executor.execute({
thread: { ...thread, id: 'thread-snapshots', cwd: workspace, turns: [] },
turn: {
id: 'turn-snapshots',
threadId: 'thread-snapshots',
status: 'in_progress',
startedAt: '2026-08-01T00:00:00.000Z',
items: [],
},
input: { text: 'write' },
signal: new AbortController().signal,
publishDelta: () => undefined,
...protocolCallbacks(),
requestApproval: async () => 'allow',
});
await expect(sessions.load('thread-snapshots')).resolves.toBeNull();
const snapshots = await sessions.snapshots('thread-snapshots');
expect(snapshots).toHaveLength(2);
expect(snapshots.every((snapshot) => snapshot.turnId === 'turn-snapshots')).toBe(true);
} finally {
await rm(root, { recursive: true, force: true });
}
});
});