forked from lessweb/deepcode-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsession.test.ts
More file actions
705 lines (625 loc) · 21.7 KB
/
session.test.ts
File metadata and controls
705 lines (625 loc) · 21.7 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
import { afterEach, test } from "node:test";
import assert from "node:assert/strict";
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import { SessionManager, type SessionMessage } from "../session";
const originalFetch = globalThis.fetch;
const originalHome = process.env.HOME;
const tempDirs: string[] = [];
afterEach(() => {
globalThis.fetch = originalFetch;
if (originalHome === undefined) {
delete process.env.HOME;
} else {
process.env.HOME = originalHome;
}
while (tempDirs.length > 0) {
const dir = tempDirs.pop();
if (dir) {
fs.rmSync(dir, { recursive: true, force: true });
}
}
});
test("SessionManager preserves structured system content when building OpenAI messages", () => {
const manager = new SessionManager({
projectRoot: process.cwd(),
createOpenAIClient: () => ({
client: null,
model: "test-model",
thinkingEnabled: false
}),
getResolvedSettings: () => ({}),
renderMarkdown: (text) => text,
onAssistantMessage: () => {}
});
const messages: SessionMessage[] = [
{
id: "system-image",
sessionId: "session-1",
role: "system",
content: "The read tool has loaded `pixel.png`.",
contentParams: [
{
type: "image_url",
image_url: { url: "data:image/png;base64,abc123" }
}
],
messageParams: null,
compacted: false,
visible: false,
createTime: "2026-01-01T00:00:00.000Z",
updateTime: "2026-01-01T00:00:00.000Z"
}
];
const openAIMessages = (manager as any).buildOpenAIMessages(messages) as Array<{
role: string;
content: unknown;
}>;
assert.equal(openAIMessages.length, 1);
assert.equal(openAIMessages[0]?.role, "system");
assert.deepEqual(openAIMessages[0]?.content, [
{ type: "text", text: "The read tool has loaded `pixel.png`." },
{
type: "image_url",
image_url: { url: "data:image/png;base64,abc123" }
}
]);
});
test("SessionManager preserves empty reasoning content on assistant tool calls", () => {
const manager = new SessionManager({
projectRoot: process.cwd(),
createOpenAIClient: () => ({
client: null,
model: "test-model",
thinkingEnabled: false
}),
getResolvedSettings: () => ({}),
renderMarkdown: (text) => text,
onAssistantMessage: () => {}
});
const message = (manager as any).buildAssistantMessage(
"session-1",
"",
[
{
id: "call-1",
type: "function",
function: { name: "read", arguments: "{}" }
}
],
""
) as SessionMessage;
assert.deepEqual(message.messageParams, {
tool_calls: [
{
id: "call-1",
type: "function",
function: { name: "read", arguments: "{}" }
}
],
reasoning_content: ""
});
const openAIMessages = (manager as any).buildOpenAIMessages([message], true) as Array<{
reasoning_content?: string;
}>;
assert.equal(openAIMessages[0]?.reasoning_content, "");
});
test("SessionManager repairs legacy thinking tool calls missing reasoning content", () => {
const manager = new SessionManager({
projectRoot: process.cwd(),
createOpenAIClient: () => ({
client: null,
model: "test-model",
thinkingEnabled: false
}),
getResolvedSettings: () => ({}),
renderMarkdown: (text) => text,
onAssistantMessage: () => {}
});
const messages: SessionMessage[] = [
{
id: "assistant-tool",
sessionId: "session-1",
role: "assistant",
content: "",
contentParams: null,
messageParams: {
tool_calls: [
{
id: "call-1",
type: "function",
function: { name: "read", arguments: "{}" }
}
]
},
compacted: false,
visible: false,
createTime: "2026-01-01T00:00:00.000Z",
updateTime: "2026-01-01T00:00:00.000Z"
}
];
const thinkingMessages = (manager as any).buildOpenAIMessages(messages, true) as Array<{
reasoning_content?: string;
}>;
const nonThinkingMessages = (manager as any).buildOpenAIMessages(messages, false) as Array<{
reasoning_content?: string;
}>;
assert.equal(thinkingMessages[0]?.reasoning_content, "");
assert.equal(
Object.prototype.hasOwnProperty.call(nonThinkingMessages[0] ?? {}, "reasoning_content"),
false
);
});
test("SessionManager replays normal assistant messages with reasoning content in thinking mode", () => {
const manager = new SessionManager({
projectRoot: process.cwd(),
createOpenAIClient: () => ({
client: null,
model: "test-model",
thinkingEnabled: false
}),
getResolvedSettings: () => ({}),
renderMarkdown: (text) => text,
onAssistantMessage: () => {}
});
const messages: SessionMessage[] = [
{
id: "assistant-final",
sessionId: "session-1",
role: "assistant",
content: "Final answer",
contentParams: null,
messageParams: null,
compacted: false,
visible: true,
createTime: "2026-01-01T00:00:00.000Z",
updateTime: "2026-01-01T00:00:00.000Z"
}
];
const thinkingMessages = (manager as any).buildOpenAIMessages(messages, true) as Array<{
reasoning_content?: string;
}>;
const nonThinkingMessages = (manager as any).buildOpenAIMessages(messages, false) as Array<{
reasoning_content?: string;
}>;
assert.equal(thinkingMessages[0]?.reasoning_content, "");
assert.equal(
Object.prototype.hasOwnProperty.call(nonThinkingMessages[0] ?? {}, "reasoning_content"),
false
);
});
test("SessionManager normalizes legacy sessions without activeTokens to zero", () => {
const workspace = createTempDir("deepcode-legacy-active-tokens-workspace-");
const home = createTempDir("deepcode-legacy-active-tokens-home-");
process.env.HOME = home;
const projectCode = workspace.replace(/[\\/]/g, "-").replace(/:/g, "");
const projectDir = path.join(home, ".deepcode", "projects", projectCode);
fs.mkdirSync(projectDir, { recursive: true });
fs.writeFileSync(
path.join(projectDir, "sessions-index.json"),
JSON.stringify({
version: 1,
originalPath: workspace,
entries: [
{
id: "legacy-session",
status: "completed",
usage: { total_tokens: 123 },
createTime: "2026-01-01T00:00:00.000Z",
updateTime: "2026-01-01T00:00:00.000Z"
}
]
}),
"utf8"
);
const manager = createSessionManager(workspace, "machine-id-legacy");
assert.equal(manager.getSession("legacy-session")?.activeTokens, 0);
});
test("SessionManager marks skills loaded from existing session messages", async () => {
const workspace = createTempDir("deepcode-loaded-skills-workspace-");
const home = createTempDir("deepcode-loaded-skills-home-");
process.env.HOME = home;
const skillDir = path.join(home, ".agents", "skills", "lessweb-starter");
fs.mkdirSync(skillDir, { recursive: true });
fs.writeFileSync(
path.join(skillDir, "SKILL.md"),
"---\nname: lessweb-starter\ndescription: Create Lessweb projects\n---\n# Lessweb Starter\n",
"utf8"
);
const projectCode = workspace.replace(/[\\/]/g, "-").replace(/:/g, "");
const projectDir = path.join(home, ".deepcode", "projects", projectCode);
fs.mkdirSync(projectDir, { recursive: true });
fs.writeFileSync(
path.join(projectDir, "loaded-session.jsonl"),
`${JSON.stringify({
id: "skill-message",
sessionId: "loaded-session",
role: "system",
content: "Use the skill document below",
contentParams: null,
messageParams: null,
compacted: false,
visible: true,
createTime: "2026-01-01T00:00:00.000Z",
updateTime: "2026-01-01T00:00:00.000Z",
meta: {
skill: {
name: "lessweb-starter",
path: "~/.agents/skills/lessweb-starter/SKILL.md",
description: "Create Lessweb projects",
isLoaded: true
}
}
})}\n`,
"utf8"
);
const manager = createSessionManager(workspace, "machine-id-loaded-skills");
const loadedSkill = (await manager.listSkills("loaded-session"))
.find((skill) => skill.name === "lessweb-starter");
assert.equal(loadedSkill?.isLoaded, true);
});
test("createSession reports a new prompt with the machineId token", async () => {
const workspace = createTempDir("deepcode-session-workspace-");
const home = createTempDir("deepcode-session-home-");
process.env.HOME = home;
const fetchCalls: Array<{ input: string | URL; init?: RequestInit }> = [];
globalThis.fetch = (async (input: string | URL, init?: RequestInit) => {
fetchCalls.push({ input, init });
return {
ok: true,
text: async () => ""
} as Response;
}) as typeof fetch;
const manager = createSessionManager(workspace, "machine-id-123");
const activatedSessionIds: string[] = [];
(manager as any).activateSession = async (sessionId: string) => {
activatedSessionIds.push(sessionId);
};
const sessionId = await manager.createSession({ text: "hello world" });
await flushPromises();
assert.equal(activatedSessionIds.length, 1);
assert.equal(activatedSessionIds[0], sessionId);
assert.equal(fetchCalls.length, 1);
assert.equal(String(fetchCalls[0].input), "https://deepcode.vegamo.cn/api/plugin/new");
assert.equal(fetchCalls[0].init?.method, "POST");
assert.deepEqual(JSON.parse(String(fetchCalls[0].init?.body)), {});
assert.equal((fetchCalls[0].init?.headers as Record<string, string>).Token, "machine-id-123");
});
test("replySession reports a new prompt with the machineId token", async () => {
const workspace = createTempDir("deepcode-reply-workspace-");
const home = createTempDir("deepcode-reply-home-");
process.env.HOME = home;
const fetchCalls: Array<{ input: string | URL; init?: RequestInit }> = [];
globalThis.fetch = (async (input: string | URL, init?: RequestInit) => {
fetchCalls.push({ input, init });
return {
ok: true,
text: async () => ""
} as Response;
}) as typeof fetch;
const manager = createSessionManager(workspace, "machine-id-456");
(manager as any).activateSession = async () => {};
const sessionId = await manager.createSession({ text: "first prompt" });
await flushPromises();
fetchCalls.length = 0;
await manager.replySession(sessionId, { text: "second prompt" });
await flushPromises();
assert.equal(fetchCalls.length, 1);
assert.equal(String(fetchCalls[0].input), "https://deepcode.vegamo.cn/api/plugin/new");
assert.equal(fetchCalls[0].init?.method, "POST");
assert.deepEqual(JSON.parse(String(fetchCalls[0].init?.body)), {});
assert.equal((fetchCalls[0].init?.headers as Record<string, string>).Token, "machine-id-456");
});
test("replySession closes pending tool calls before appending a new user message", async () => {
const workspace = createTempDir("deepcode-pending-tool-workspace-");
const home = createTempDir("deepcode-pending-tool-home-");
process.env.HOME = home;
globalThis.fetch = (async () => ({
ok: true,
text: async () => ""
}) as Response) as typeof fetch;
const manager = createSessionManager(workspace, "machine-id-pending-tool");
(manager as any).activateSession = async () => {};
const sessionId = await manager.createSession({ text: "first prompt" });
const assistantMessage = (manager as any).buildAssistantMessage(
sessionId,
"I will run a tool.",
[
{
id: "call-1",
type: "function",
function: { name: "bash", arguments: "{\"command\":\"sleep 100\"}" }
}
],
""
) as SessionMessage;
(manager as any).appendSessionMessage(sessionId, assistantMessage);
await manager.replySession(sessionId, { text: "second prompt" });
const messages = manager.listSessionMessages(sessionId);
const assistantIndex = messages.findIndex((message) => message.id === assistantMessage.id);
assert.notEqual(assistantIndex, -1);
assert.equal(messages[assistantIndex + 1]?.role, "tool");
assert.equal((messages[assistantIndex + 1]?.messageParams as any)?.tool_call_id, "call-1");
assert.match(String(messages[assistantIndex + 1]?.content), /Previous tool call did not complete/);
assert.equal(messages[assistantIndex + 2]?.role, "user");
assert.equal(messages[assistantIndex + 2]?.content, "second prompt");
});
test("SessionManager accumulates response usage while active tokens track the latest response", async () => {
const workspace = createTempDir("deepcode-usage-workspace-");
const home = createTempDir("deepcode-usage-home-");
process.env.HOME = home;
const responses = [
createChatResponse("first", {
prompt_tokens: 10,
completion_tokens: 5,
total_tokens: 15,
prompt_tokens_details: { cached_tokens: 7 },
completion_tokens_details: { reasoning_tokens: 3 },
prompt_cache_hit_tokens: 7,
prompt_cache_miss_tokens: 3
}),
createChatResponse("second", {
prompt_tokens: 20,
completion_tokens: 7,
total_tokens: 27,
prompt_tokens_details: { cached_tokens: 11 },
completion_tokens_details: { reasoning_tokens: 4 },
prompt_cache_hit_tokens: 11,
prompt_cache_miss_tokens: 9
})
];
const manager = createMockedClientSessionManager(workspace, responses);
const sessionId = await manager.createSession({ text: "" });
await manager.replySession(sessionId, { text: "" });
const session = manager.getSession(sessionId);
const usage = session?.usage as Record<string, any>;
assert.equal(session?.activeTokens, 27);
assert.equal(usage.prompt_tokens, 30);
assert.equal(usage.completion_tokens, 12);
assert.equal(usage.total_tokens, 42);
assert.equal(usage.prompt_tokens_details.cached_tokens, 18);
assert.equal(usage.completion_tokens_details.reasoning_tokens, 7);
assert.equal(usage.prompt_cache_hit_tokens, 18);
assert.equal(usage.prompt_cache_miss_tokens, 12);
});
test("SessionManager resets active tokens to latest post-compaction response usage", async () => {
const workspace = createTempDir("deepcode-compact-usage-workspace-");
const home = createTempDir("deepcode-compact-usage-home-");
process.env.HOME = home;
const responses = [
createChatResponse("large", {
prompt_tokens: 139_990,
completion_tokens: 10,
total_tokens: 140_000
}),
createChatResponse("summary", {
prompt_tokens: 100,
completion_tokens: 23,
total_tokens: 123
}),
createChatResponse("after compact", {
prompt_tokens: 5,
completion_tokens: 2,
total_tokens: 7
})
];
const manager = createMockedClientSessionManager(workspace, responses);
const sessionId = await manager.createSession({ text: "" });
assert.equal(manager.getSession(sessionId)?.activeTokens, 140_000);
await manager.replySession(sessionId, { text: "" });
const session = manager.getSession(sessionId);
const usage = session?.usage as Record<string, any>;
assert.equal(session?.activeTokens, 7);
assert.equal(usage.prompt_tokens, 140_095);
assert.equal(usage.completion_tokens, 35);
assert.equal(usage.total_tokens, 140_130);
});
test("SessionManager streams chat completions and counts reasoning progress", async () => {
const workspace = createTempDir("deepcode-stream-workspace-");
const home = createTempDir("deepcode-stream-home-");
process.env.HOME = home;
const progressEvents: Array<{
phase: string;
estimatedTokens: number;
formattedTokens: string;
}> = [];
const client = {
chat: {
completions: {
create: async (request: Record<string, unknown>) => {
assert.equal(request.stream, true);
assert.deepEqual(request.stream_options, { include_usage: true });
return createChatStreamResponse([
{ choices: [{ delta: { reasoning_content: "思考" } }] },
{ choices: [{ delta: { content: "hello" } }] },
{
choices: [],
usage: {
prompt_tokens: 2,
completion_tokens: 3,
total_tokens: 5
}
}
]);
}
}
}
};
const manager = new SessionManager({
projectRoot: workspace,
createOpenAIClient: () => ({
client: client as any,
model: "test-model",
baseURL: "https://api.deepseek.com",
thinkingEnabled: false
}),
getResolvedSettings: () => ({}),
renderMarkdown: (text) => text,
onAssistantMessage: () => {},
onLlmStreamProgress: (progress) => {
progressEvents.push({
phase: progress.phase,
estimatedTokens: progress.estimatedTokens,
formattedTokens: progress.formattedTokens
});
}
});
const sessionId = await manager.createSession({ text: "" });
const assistantMessage = manager
.listSessionMessages(sessionId)
.find((message) => message.role === "assistant");
assert.equal(assistantMessage?.content, "hello");
assert.equal((assistantMessage?.messageParams as any)?.reasoning_content, "思考");
assert.equal(manager.getSession(sessionId)?.activeTokens, 5);
assert.deepEqual(
progressEvents.map((event) => event.phase),
["start", "update", "update", "end"]
);
assert.equal(progressEvents[1]?.estimatedTokens, 1);
assert.equal(progressEvents[2]?.formattedTokens, "3");
});
test("SessionManager cancels skill matching before a session is created", async () => {
const workspace = createTempDir("deepcode-skill-abort-workspace-");
const home = createTempDir("deepcode-skill-abort-home-");
process.env.HOME = home;
const skillDir = path.join(home, ".agents", "skills", "demo");
fs.mkdirSync(skillDir, { recursive: true });
fs.writeFileSync(
path.join(skillDir, "SKILL.md"),
"---\nname: demo\ndescription: Demo skill\n---\n# Demo\n",
"utf8"
);
let manager: SessionManager;
const client = {
chat: {
completions: {
create: async (_request: Record<string, unknown>, options?: { signal?: AbortSignal }) => {
return new Promise((_resolve, reject) => {
const signal = options?.signal;
signal?.addEventListener("abort", () => reject(new APIUserAbortError()), { once: true });
queueMicrotask(() => manager.interruptActiveSession());
});
}
}
}
};
manager = createMockedClientSessionManagerWithClient(workspace, client);
await manager.handleUserPrompt({ text: "please use demo" });
assert.equal(manager.listSessions().length, 0);
});
test("SessionManager treats OpenAI APIUserAbortError as interrupted", async () => {
const workspace = createTempDir("deepcode-api-abort-workspace-");
const home = createTempDir("deepcode-api-abort-home-");
process.env.HOME = home;
let manager: SessionManager;
const client = {
chat: {
completions: {
create: async (_request: Record<string, unknown>, options?: { signal?: AbortSignal }) => {
return new Promise((_resolve, reject) => {
const signal = options?.signal;
signal?.addEventListener("abort", () => reject(new APIUserAbortError()), { once: true });
});
}
}
}
};
manager = new SessionManager({
projectRoot: workspace,
createOpenAIClient: () => ({
client: client as any,
model: "test-model",
baseURL: "https://api.deepseek.com",
thinkingEnabled: false
}),
getResolvedSettings: () => ({}),
renderMarkdown: (text) => text,
onAssistantMessage: () => {},
onSessionEntryUpdated: (entry) => {
if (entry.status === "processing") {
queueMicrotask(() => manager.interruptActiveSession());
}
}
});
await manager.handleUserPrompt({ text: "" });
const activeSessionId = manager.getActiveSessionId();
assert.ok(activeSessionId);
const session = manager.getSession(activeSessionId);
assert.equal(session?.status, "interrupted");
assert.equal(session?.failReason, "interrupted");
});
function createSessionManager(projectRoot: string, machineId: string): SessionManager {
return new SessionManager({
projectRoot,
createOpenAIClient: () => ({
client: null,
model: "test-model",
baseURL: "https://api.deepseek.com",
thinkingEnabled: false,
machineId
}),
getResolvedSettings: () => ({}),
renderMarkdown: (text) => text,
onAssistantMessage: () => {}
});
}
function createMockedClientSessionManager(projectRoot: string, responses: unknown[]): SessionManager {
const client = {
chat: {
completions: {
create: async () => {
const response = responses.shift();
assert.ok(response, "expected a queued chat response");
return response;
}
}
}
};
return new SessionManager({
projectRoot,
createOpenAIClient: () => ({
client: client as any,
model: "test-model",
baseURL: "https://api.deepseek.com",
thinkingEnabled: false
}),
getResolvedSettings: () => ({}),
renderMarkdown: (text) => text,
onAssistantMessage: () => {}
});
}
function createMockedClientSessionManagerWithClient(projectRoot: string, client: unknown): SessionManager {
return new SessionManager({
projectRoot,
createOpenAIClient: () => ({
client: client as any,
model: "test-model",
baseURL: "https://api.deepseek.com",
thinkingEnabled: false
}),
getResolvedSettings: () => ({}),
renderMarkdown: (text) => text,
onAssistantMessage: () => {}
});
}
class APIUserAbortError extends Error {}
function createChatResponse(content: string, usage: Record<string, unknown>): unknown {
return {
choices: [{ message: { content } }],
usage
};
}
async function* createChatStreamResponse(chunks: Record<string, unknown>[]): AsyncGenerator<Record<string, unknown>> {
for (const chunk of chunks) {
yield chunk;
}
}
function createTempDir(prefix: string): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
tempDirs.push(dir);
return dir;
}
async function flushPromises(): Promise<void> {
await new Promise<void>((resolve) => setImmediate(resolve));
}