File size: 11,170 Bytes
391c43e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { describe, it, expect, vi } from 'vitest';
import { ContextManagerImpl } from '../core/context-manager';
import type { ProviderAdapter, ParsedResponse, Message } from '../core/types';

function mockProvider(summaryText: string): ProviderAdapter {
  return {
    call: vi.fn().mockResolvedValue({ content: summaryText }),
    getModel: () => 'test-model',
    getProvider: () => 'test',
    supportsTools: () => true,
  };
}

const defaultConfig = {
  contextLength: 100000,
  threshold: 60000,
  recentKeepRatio: 0.2,
  summaryTokenRatio: 0.1,
  buildCompactionPrompt: (prev?: string) => prev ? `prev: ${prev}\nsummarize` : 'summarize',
};

// Config with small context for testing compaction triggers
const smallConfig = {
  contextLength: 1000,
  threshold: 500,
  recentKeepRatio: 0.2,
  summaryTokenRatio: 0.1,
  buildCompactionPrompt: (prev?: string) => prev ? `prev: ${prev}\nsummarize` : 'summarize',
};

describe('ContextManagerImpl', () => {
  it('adds user message', () => {
    const cm = new ContextManagerImpl(defaultConfig);
    cm.addUserMessage('hello');
    const msgs = cm.getMessages();
    expect(msgs).toHaveLength(1);
    expect(msgs[0].role).toBe('user');
    expect(msgs[0].content).toBe('hello');
  });

  it('adds assistant turn with tool calls', () => {
    const cm = new ContextManagerImpl(defaultConfig);
    const response: ParsedResponse = {
      content: 'I will help',
      toolCalls: [{ id: 'tc1', type: 'function', function: { name: 'bash', arguments: '{"command":"ls"}' } }],
    };
    cm.addAssistantTurn(response);
    const msgs = cm.getMessages();
    expect(msgs[0].role).toBe('assistant');
    expect(msgs[0].tool_calls).toHaveLength(1);
  });

  it('adds tool results', () => {
    const cm = new ContextManagerImpl(defaultConfig);
    cm.addToolResults([{ tool_call_id: 'tc1', content: 'file.txt', success: true }]);
    const msgs = cm.getMessages();
    expect(msgs[0].role).toBe('tool');
    expect(msgs[0].tool_call_id).toBe('tc1');
  });

  it('imports messages', () => {
    const cm = new ContextManagerImpl(defaultConfig);
    cm.addUserMessage('old message');
    const imported: Message[] = [
      { role: 'system', content: 'sys' },
      { role: 'user', content: 'imported' },
    ];
    cm.importMessages(imported);
    expect(cm.getMessages()).toHaveLength(2);
    expect(cm.getMessages()[1].content).toBe('imported');
  });

  it('sets system prompt', () => {
    const cm = new ContextManagerImpl(defaultConfig);
    cm.setSystemPrompt('you are helpful');
    expect(cm.getMessages()[0]).toEqual({ role: 'system', content: 'you are helpful' });
    cm.setSystemPrompt('updated');
    expect(cm.getMessages()[0].content).toBe('updated');
    expect(cm.getMessages()).toHaveLength(1);
  });

  it('reports needsCompaction correctly', () => {
    const cm = new ContextManagerImpl(defaultConfig);
    expect(cm.needsCompaction(50000)).toBe(false);
    expect(cm.needsCompaction(60000)).toBe(true);
    expect(cm.needsCompaction(70000)).toBe(true);
  });

  it('calls onMessageAdded hook', () => {
    const cm = new ContextManagerImpl(defaultConfig);
    const hook = vi.fn();
    cm.onMessageAdded = hook;
    cm.addUserMessage('test');
    expect(hook).toHaveBeenCalledWith(expect.objectContaining({ role: 'user', content: 'test' }));
  });

  it('estimates token count', () => {
    const cm = new ContextManagerImpl(defaultConfig);
    cm.addUserMessage('hello world'); // 11 chars -> ~3 tokens
    const estimate = cm.getTokenEstimate();
    expect(estimate).toBeGreaterThan(0);
    expect(estimate).toBe(Math.round(11 / 3.5));
  });

  it('estimates tokens for tool calls', () => {
    const cm = new ContextManagerImpl(defaultConfig);
    cm.addAssistantTurn({
      content: 'ok',
      toolCalls: [{ id: 'tc1', type: 'function', function: { name: 'bash', arguments: '{"command":"ls -la"}' } }],
    });
    const estimate = cm.getTokenEstimate();
    // content "ok" (2 chars) + args '{"command":"ls -la"}' (20 chars) = 22 / 3.5 ~ 6
    expect(estimate).toBe(Math.round(22 / 3.5));
  });

  it('compacts conversation via provider', async () => {
    const cm = new ContextManagerImpl(smallConfig);
    cm.setSystemPrompt('system prompt');
    // Add enough messages so there's something to compact (needs to exceed recent budget)
    for (let i = 0; i < 10; i++) {
      cm.addUserMessage(`user msg ${i} - ${'x'.repeat(200)}`);
      cm.addAssistantTurn({ content: `response ${i} - ${'y'.repeat(200)}` });
    }
    const provider = mockProvider('Summary of conversation');
    await cm.compact(provider, { freshSystemPrompt: 'fresh system prompt' });
    const msgs = cm.getMessages();
    // First message should be the fresh system prompt
    expect(msgs[0].role).toBe('system');
    expect(msgs[0].content).toBe('fresh system prompt');
    // Should contain the summary somewhere
    expect(msgs.some(m => typeof m.content === 'string' && m.content.includes('Summary of conversation'))).toBe(true);
    // Should have called the provider
    expect(provider.call).toHaveBeenCalled();
  });

  it('uses config.getFreshContext when compact() is called without explicit opts', async () => {
    const cm = new ContextManagerImpl({
      ...smallConfig,
      getFreshContext: async () => ({ systemPrompt: 'FRESH SYSTEM', projectContext: 'FRESH PROJECT CONTEXT' }),
    });
    cm.setSystemPrompt('stale system prompt');
    for (let i = 0; i < 10; i++) {
      cm.addUserMessage(`user msg ${i} - ${'x'.repeat(200)}`);
      cm.addAssistantTurn({ content: `response ${i} - ${'y'.repeat(200)}` });
    }
    const provider = mockProvider('Summary of conversation');
    await cm.compact(provider);
    const msgs = cm.getMessages();
    expect(msgs[0].content).toBe('FRESH SYSTEM');
    expect(typeof msgs[1].content === 'string' && msgs[1].content.includes('FRESH PROJECT CONTEXT')).toBe(true);
  });

  it('compaction skips when too few messages', async () => {
    const cm = new ContextManagerImpl(defaultConfig);
    cm.setSystemPrompt('system');
    cm.addUserMessage('only message');
    const provider = mockProvider('should not be called');
    await cm.compact(provider, { freshSystemPrompt: 'fresh' });
    // Provider should not be called
    expect(provider.call).not.toHaveBeenCalled();
    // Messages unchanged
    expect(cm.getMessages()).toHaveLength(2);
  });

  it('compaction includes project context when provided', async () => {
    const cm = new ContextManagerImpl(smallConfig);
    cm.setSystemPrompt('system');
    for (let i = 0; i < 10; i++) {
      cm.addUserMessage(`user msg ${i} - ${'x'.repeat(200)}`);
      cm.addAssistantTurn({ content: `response ${i} - ${'y'.repeat(200)}` });
    }
    const provider = mockProvider('Summary');
    await cm.compact(provider, { freshSystemPrompt: 'fresh', projectContext: 'file tree here' });
    const msgs = cm.getMessages();
    // Second message (user) should reference project context
    const contextMsg = msgs.find(m => m.role === 'user' && typeof m.content === 'string' && m.content.includes('file tree here'));
    expect(contextMsg).toBeDefined();
  });

  it('compaction increments count', async () => {
    const cm = new ContextManagerImpl(smallConfig);
    cm.setSystemPrompt('system');
    for (let i = 0; i < 10; i++) {
      cm.addUserMessage(`user msg ${i} - ${'x'.repeat(200)}`);
      cm.addAssistantTurn({ content: `response ${i} - ${'y'.repeat(200)}` });
    }
    const provider = mockProvider('Summary');
    expect(cm.getCompactionCount()).toBe(0);
    await cm.compact(provider, { freshSystemPrompt: 'fresh' });
    expect(cm.getCompactionCount()).toBe(1);
  });

  it('compaction fails gracefully on empty provider response', async () => {
    const cm = new ContextManagerImpl(smallConfig);
    cm.setSystemPrompt('system');
    for (let i = 0; i < 10; i++) {
      cm.addUserMessage(`user msg ${i} - ${'x'.repeat(200)}`);
      cm.addAssistantTurn({ content: `response ${i} - ${'y'.repeat(200)}` });
    }
    const provider = mockProvider('');
    const msgsBefore = cm.getMessages().length;
    await cm.compact(provider, { freshSystemPrompt: 'fresh' });
    // Messages should be unchanged (graceful failure)
    expect(cm.getMessages().length).toBe(msgsBefore);
  });

  it('repairs orphan tool calls', () => {
    const cm = new ContextManagerImpl(defaultConfig);
    // Assistant with tool call but no matching tool result
    cm.addAssistantTurn({
      content: 'let me check',
      toolCalls: [{ id: 'tc1', type: 'function', function: { name: 'bash', arguments: '{"command":"ls"}' } }],
    });
    // No tool result added for tc1
    cm.addUserMessage('next message');

    const sanitized = cm.getSanitizedMessages();
    // Should have: assistant, synthetic tool result for tc1, user
    const toolMsg = sanitized.find(m => m.role === 'tool' && m.tool_call_id === 'tc1');
    expect(toolMsg).toBeDefined();
    expect(toolMsg!.content).toContain('cancelled');
  });

  it('repairs tool calls with empty arguments', () => {
    const cm = new ContextManagerImpl(defaultConfig);
    cm.addAssistantTurn({
      content: 'text content',
      toolCalls: [
        { id: 'tc1', type: 'function', function: { name: 'bash', arguments: '' } },
        { id: 'tc2', type: 'function', function: { name: 'bash', arguments: '{"command":"ls"}' } },
      ],
    });
    cm.addToolResults([{ tool_call_id: 'tc2', content: 'result', success: true }]);

    const sanitized = cm.getSanitizedMessages();
    // tc1 should be filtered out (empty args), tc2 kept
    const assistantMsg = sanitized.find(m => m.role === 'assistant');
    expect(assistantMsg?.tool_calls).toHaveLength(1);
    expect(assistantMsg?.tool_calls![0].id).toBe('tc2');
  });

  it('drops assistant message entirely when all tool calls have empty args and no content', () => {
    const cm = new ContextManagerImpl(defaultConfig);
    cm.addAssistantTurn({
      content: '',
      toolCalls: [{ id: 'tc1', type: 'function', function: { name: 'bash', arguments: '' } }],
    });
    cm.addUserMessage('next');

    const sanitized = cm.getSanitizedMessages();
    // The empty assistant message should be dropped
    expect(sanitized.find(m => m.role === 'assistant')).toBeUndefined();
    expect(sanitized).toHaveLength(1);
    expect(sanitized[0].role).toBe('user');
  });

  it('handles multimodal content blocks in user message', () => {
    const cm = new ContextManagerImpl(defaultConfig);
    const blocks = [
      { type: 'text' as const, text: 'describe this' },
      { type: 'image_url' as const, image_url: { url: 'data:image/png;base64,abc' } },
    ];
    cm.addUserMessage(blocks);
    const msgs = cm.getMessages();
    expect(msgs[0].content).toEqual(blocks);
  });

  it('preserves reasoning_details on assistant turns', () => {
    const cm = new ContextManagerImpl(defaultConfig);
    cm.addAssistantTurn({
      content: 'thought about it',
      reasoningDetails: [{ type: 'thinking', text: 'internal reasoning' }],
    });
    const msgs = cm.getMessages();
    expect(msgs[0].reasoning_details).toHaveLength(1);
    expect(msgs[0].reasoning_details![0].text).toBe('internal reasoning');
  });
});