-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.test.ts
More file actions
326 lines (301 loc) · 11.5 KB
/
Copy pathserver.test.ts
File metadata and controls
326 lines (301 loc) · 11.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
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { ProtocolEvent, ProtocolRequest } from '@deepcode/protocol';
import { afterEach, describe, expect, it } from 'vitest';
import { AppServer, type TurnExecutor } from './server.js';
import { FileThreadStore } from './store.js';
let temporaryRoots: string[] = [];
afterEach(async () => {
await Promise.all(temporaryRoots.map((root) => rm(root, { recursive: true, force: true })));
temporaryRoots = [];
});
function request(
id: number,
method: ProtocolRequest['method'],
params: Record<string, unknown> = {},
): ProtocolRequest {
return { id, method, params };
}
function deterministicOptions() {
let sequence = 0;
let tick = 0;
return {
now: () => `2026-08-01T00:00:0${tick++}.000Z`,
newId: (prefix: 'thread' | 'turn' | 'item') => `${prefix}-${++sequence}`,
};
}
describe('AppServer', () => {
it('advertises and returns value-free configuration diagnostics when provided', async () => {
const server = new AppServer({
executor: { execute: async () => ({}) },
configDiagnostics: async (cwd) => ({
cwd,
trustStatus: 'untrusted',
layers: [],
provenance: { '/model': { layer: 'user', path: '/home/.deepcode/settings.json' } },
gated: [],
issues: [],
}),
});
await expect(server.handle(request(1, 'initialize'))).resolves.toEqual({
id: 1,
result: expect.objectContaining({
capabilities: expect.objectContaining({ configDiagnostics: true }),
}),
});
await expect(
server.handle(request(2, 'config/diagnostics', { cwd: '/workspace' })),
).resolves.toEqual({
id: 2,
result: expect.objectContaining({
cwd: '/workspace',
provenance: expect.objectContaining({
'/model': expect.objectContaining({ layer: 'user' }),
}),
}),
});
});
it('does not advertise unavailable configuration diagnostics', async () => {
const server = new AppServer({ executor: { execute: async () => ({}) } });
const initialized = await server.handle(request(1, 'initialize'));
expect(initialized.result).toEqual(
expect.objectContaining({
capabilities: expect.objectContaining({ configDiagnostics: false }),
}),
);
await expect(
server.handle(request(2, 'config/diagnostics', { cwd: '/workspace' })),
).resolves.toEqual({
id: 2,
error: expect.objectContaining({ code: 'invalid_request' }),
});
});
it('routes initialization and thread lifecycle requests', async () => {
const server = new AppServer({
executor: { execute: async () => ({}) },
...deterministicOptions(),
});
await expect(server.handle(request(1, 'initialize'))).resolves.toEqual({
id: 1,
result: expect.objectContaining({ protocolVersion: 1 }),
});
const started = await server.handle(request(2, 'thread/start', { cwd: '/workspace' }));
expect(started).toEqual({
id: 2,
result: expect.objectContaining({ id: 'thread-1', cwd: '/workspace' }),
});
await expect(
server.handle(request(3, 'thread/read', { threadId: 'thread-1' })),
).resolves.toEqual(started.id === 2 ? { id: 3, result: started.result } : undefined);
});
it('persists completed items and terminal state while publishing deltas transiently', async () => {
const events: ProtocolEvent[] = [];
const executor: TurnExecutor = {
execute: async ({ publishDelta, publishToolStarted, publishToolCompleted, publishUsage }) => {
publishDelta('assistant-stream', 'hel');
publishToolStarted('tool-1', 'Read', { file_path: 'README.md' });
publishToolCompleted('tool-1', { content: 'contents' });
publishUsage({ inputTokens: 1, outputTokens: 2 });
return {
items: [{ type: 'assistant_message', payload: { text: 'hello' } }],
};
},
};
const server = new AppServer({
executor,
onEvent: (event) => events.push(event),
...deterministicOptions(),
});
await server.handle(request(1, 'thread/start', { cwd: '/workspace' }));
const started = await server.handle(
request(2, 'turn/start', { threadId: 'thread-1', input: { text: 'hello' } }),
);
expect(started).toEqual({
id: 2,
result: expect.objectContaining({ id: 'turn-3', status: 'in_progress' }),
});
await server.waitForIdle();
const read = await server.handle(request(3, 'thread/read', { threadId: 'thread-1' }));
expect(read).toEqual({
id: 3,
result: expect.objectContaining({
turns: [
expect.objectContaining({
status: 'completed',
items: [
expect.objectContaining({ type: 'user_message' }),
expect.objectContaining({ type: 'assistant_message', payload: { text: 'hello' } }),
],
}),
],
}),
});
expect(events.map((event) => event.type)).toContain('item.delta');
expect(events.map((event) => event.type)).toEqual(
expect.arrayContaining(['tool.started', 'tool.completed', 'usage.updated']),
);
expect((read.result as { turns: Array<{ items: unknown[] }> }).turns[0]?.items).toHaveLength(2);
});
it('interrupts the actual executor and emits one terminal event', async () => {
const events: ProtocolEvent[] = [];
let observedAbort!: () => void;
const aborted = new Promise<void>((resolve) => {
observedAbort = resolve;
});
const executor: TurnExecutor = {
execute: async ({ signal }) => {
await new Promise<never>((_resolve, reject) => {
signal.addEventListener(
'abort',
() => {
observedAbort();
reject(new DOMException('aborted', 'AbortError'));
},
{ once: true },
);
});
},
};
const server = new AppServer({
executor,
onEvent: (event) => events.push(event),
...deterministicOptions(),
});
await server.handle(request(1, 'thread/start', { cwd: '/workspace' }));
await server.handle(
request(2, 'turn/start', { threadId: 'thread-1', input: { text: 'wait' } }),
);
await expect(
server.handle(request(3, 'turn/interrupt', { threadId: 'thread-1', turnId: 'turn-3' })),
).resolves.toEqual({ id: 3, result: { interrupted: true } });
await aborted;
await server.waitForIdle();
expect(events.filter((event) => event.type === 'turn.interrupted')).toHaveLength(1);
expect(events.filter((event) => event.type === 'turn.completed')).toHaveLength(0);
});
it('round-trips approval and user-input requests through the active turn', async () => {
const events: ProtocolEvent[] = [];
const responses: string[] = [];
const executor: TurnExecutor = {
execute: async ({ requestApproval, requestUserInput }) => {
responses.push(await requestApproval('Bash', 'Run tests?'));
responses.push(
await requestUserInput({
question: 'Choose scope',
options: [{ label: 'All', description: 'Run every test' }],
}),
);
return {};
},
};
const server = new AppServer({ executor, onEvent: (event) => events.push(event) });
const thread = await server.handle(request(1, 'thread/start', { cwd: '/workspace' }));
const threadId = (thread.result as { id: string }).id;
const started = await server.handle(
request(2, 'turn/start', { threadId, input: { text: 'test' } }),
);
const turnId = (started.result as { id: string }).id;
const approval = events.find((event) => event.type === 'approval.requested');
expect(approval).toEqual(
expect.objectContaining({ type: 'approval.requested', threadId, turnId, toolName: 'Bash' }),
);
await expect(
server.handle(
request(3, 'approval/respond', {
threadId,
turnId,
requestId: approval?.type === 'approval.requested' ? approval.requestId : '',
decision: 'allow',
}),
),
).resolves.toEqual({ id: 3, result: { accepted: true } });
await Promise.resolve();
const question = events.find((event) => event.type === 'user-input.requested');
expect(question).toEqual(
expect.objectContaining({ type: 'user-input.requested', threadId, turnId }),
);
await server.handle(
request(4, 'user-input/respond', {
threadId,
turnId,
requestId: question?.type === 'user-input.requested' ? question.requestId : '',
answer: 'All',
}),
);
await server.waitForIdle();
expect(responses).toEqual(['allow', 'All']);
expect(events.filter((event) => event.type === 'turn.completed')).toHaveLength(1);
await expect(
server.handle(
request(5, 'approval/respond', {
threadId,
turnId,
requestId: approval?.type === 'approval.requested' ? approval.requestId : '',
decision: 'allow',
}),
),
).resolves.toEqual({
id: 5,
error: expect.objectContaining({ code: 'invalid_request' }),
});
});
it('releases a pending interaction when its turn is interrupted', async () => {
let decision: string | undefined;
const executor: TurnExecutor = {
execute: async ({ requestApproval }) => {
decision = await requestApproval('Bash', 'Run forever?');
return {};
},
};
const server = new AppServer({ executor });
const thread = await server.handle(request(1, 'thread/start', { cwd: '/workspace' }));
const threadId = (thread.result as { id: string }).id;
const started = await server.handle(
request(2, 'turn/start', { threadId, input: { text: 'wait' } }),
);
const turnId = (started.result as { id: string }).id;
await server.handle(request(3, 'turn/interrupt', { threadId, turnId }));
await server.waitForIdle();
expect(decision).toBe('deny');
const read = await server.handle(request(4, 'thread/read', { threadId }));
expect(read.result).toEqual(
expect.objectContaining({ turns: [expect.objectContaining({ status: 'interrupted' })] }),
);
});
it('marks an orphaned active turn interrupted when a new process resumes it', async () => {
const root = await mkdtemp(join(tmpdir(), 'deepcode-app-server-'));
temporaryRoots.push(root);
const store = new FileThreadStore(root);
const first = new AppServer({
store,
executor: { execute: () => new Promise(() => {}) },
...deterministicOptions(),
});
await first.handle(request(1, 'thread/start', { cwd: '/workspace' }));
await first.handle(
request(2, 'turn/start', { threadId: 'thread-1', input: { text: 'unfinished' } }),
);
const restarted = new AppServer({ store, executor: { execute: async () => ({}) } });
const response = await restarted.handle(request(3, 'thread/resume', { threadId: 'thread-1' }));
expect(response).toEqual({
id: 3,
result: expect.objectContaining({
turns: [expect.objectContaining({ status: 'interrupted' })],
}),
});
});
it('returns structured errors for invalid requests', async () => {
const server = new AppServer({ executor: { execute: async () => ({}) } });
await expect(server.handle(request(1, 'thread/start'))).resolves.toEqual({
id: 1,
error: { code: 'invalid_request', message: 'cwd is required' },
});
await expect(
server.handle(request(2, 'thread/read', { threadId: '../credentials' })),
).resolves.toEqual({
id: 2,
error: { code: 'invalid_request', message: 'threadId is invalid' },
});
});
});