File size: 7,711 Bytes
7a1ad33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * @license
 * Copyright 2026 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import { vi, describe, it, expect, beforeEach, type Mock } from 'vitest';
import { ContextManager } from './contextManager.js';
import type { ContextProfile } from './config/profiles.js';
import type { ContextEnvironment } from './pipeline/environment.js';
import type { ContextTracer } from './tracer.js';
import type { PipelineOrchestrator } from './pipeline/orchestrator.js';
import type {
  AgentChatHistory,
  HistoryTurn,
} from '../core/agentChatHistory.js';
import type { AdvancedTokenCalculator } from './utils/contextTokenCalculator.js';
import { createMockEnvironment } from './testing/contextTestUtils.js';
import { ContextWorkingBufferImpl } from './pipeline/contextWorkingBuffer.js';
import { deriveStableId } from '../utils/cryptoUtils.js';

describe('ContextManager', () => {
  let mockSidecar: ContextProfile;
  let mockEnv: ContextEnvironment;
  let mockTracer: ContextTracer;
  let mockOrchestrator: PipelineOrchestrator;
  let mockChatHistory: AgentChatHistory;
  let mockAdvancedTokenCalculator: AdvancedTokenCalculator;

  beforeEach(() => {
    vi.resetAllMocks();

    mockSidecar = {
      name: 'test-profile',
      config: { budget: { retainedTokens: 1000, maxTokens: 2000 } },
      buildPipelines: vi.fn().mockReturnValue([]),
      buildAsyncPipelines: vi.fn().mockReturnValue([]),
    } as unknown as ContextProfile;

    mockEnv = createMockEnvironment();
    mockTracer = mockEnv.tracer;

    mockOrchestrator = {
      setNodeProvider: vi.fn(),
      waitForPipelines: vi.fn().mockResolvedValue(undefined),
      executeTriggerSync: vi
        .fn()
        .mockImplementation(async (trigger, buffer) => buffer),
      shutdown: vi.fn(),
    } as unknown as PipelineOrchestrator;

    mockChatHistory = {
      all: vi.fn().mockReturnValue([]),
      last: vi.fn(),
      getById: vi.fn(),
      getTurnById: vi.fn(),
      getTurnsByIds: vi.fn(),
      getNeighboringTurns: vi.fn(),
      getHistory: vi.fn().mockReturnValue([]),
      get: vi.fn().mockReturnValue([]),
      setHistory: vi.fn(),
      getHistoryTurns: vi.fn().mockReturnValue([]),
      getRawHistory: vi.fn().mockReturnValue([]),
      addTurn: vi.fn(),
      updateTurn: vi.fn(),
      addListener: vi.fn(),
      removeListener: vi.fn(),
      clear: vi.fn(),
      subscribe: vi.fn(),
    } as unknown as AgentChatHistory;

    mockAdvancedTokenCalculator = {
      getRawBaseUnits: vi.fn().mockReturnValue(0),
      getRawBaseUnitsForContent: vi.fn().mockReturnValue(0),
      calculateTokensAndBaseUnits: vi
        .fn()
        .mockReturnValue({ tokens: 0, baseUnits: 0 }),
    } as unknown as AdvancedTokenCalculator;
  });

  it('renderHistory should process pendingRequest via the new_message pipeline', async () => {
    const contextManager = new ContextManager(
      mockSidecar,
      mockEnv,
      mockTracer,
      mockOrchestrator,
      mockChatHistory,
      mockAdvancedTokenCalculator,
    );

    const largeToolOutput = 'a'.repeat(10000);
    const pendingRequest: HistoryTurn = {
      id: 'pending-turn-1',
      content: {
        role: 'user',
        parts: [
          {
            functionResponse: {
              name: 'run_shell_command',
              response: {
                output: largeToolOutput,
              },
            },
          },
        ],
      },
    };

    await contextManager.renderHistory(pendingRequest);

    expect(mockOrchestrator.executeTriggerSync).toHaveBeenCalledExactlyOnceWith(
      'new_message',
      expect.any(ContextWorkingBufferImpl),
      expect.any(Set),
    );

    // Check that the node passed to the orchestrator corresponds to our pendingRequest
    const call = (mockOrchestrator.executeTriggerSync as unknown as Mock).mock
      .calls[0];
    const passedBuffer = call[1];
    const passedNodes = passedBuffer.nodes;
    const passedNodeIds = call[2];

    expect(passedNodes).toHaveLength(1);
    expect(passedNodes[0].type).toBe('TOOL_EXECUTION');
    expect(passedNodes[0].payload.functionResponse.response.output).toBe(
      largeToolOutput,
    );
    expect(passedNodeIds.has(passedNodes[0].id)).toBe(true);
  });

  it('should correctly split historical context and pending prompt for late binding', async () => {
    const envContextId = deriveStableId(['environment-context']);
    const historicalTurn: HistoryTurn = {
      id: `turn_${envContextId}`, // Turn 0
      content: { role: 'user', parts: [{ text: 'System instruction' }] },
    };
    const organicTurn: HistoryTurn = {
      id: 'turn-1',
      content: { role: 'model', parts: [{ text: 'Previous model message' }] },
    };

    // Setup history with Turn 0 and Turn 1
    (mockChatHistory.get as Mock).mockReturnValue([
      historicalTurn,
      organicTurn,
    ]);

    const contextManager = new ContextManager(
      mockSidecar,
      mockEnv,
      mockTracer,
      mockOrchestrator,
      mockChatHistory,
      mockAdvancedTokenCalculator,
    );

    const pendingRequest: HistoryTurn = {
      id: 'pending-turn',
      content: { role: 'user', parts: [{ text: 'Active prompt' }] },
    };

    const { apiHistory, pendingApiHistory } =
      await contextManager.renderHistory(pendingRequest);

    // apiHistory should contain Turn 0 and the previous model message.
    // Note: hardenHistory may inject a sentinel user turn if the history segment
    // being hardened starts with a model turn.
    expect(apiHistory.length).toBeGreaterThanOrEqual(2);
    expect((apiHistory[0].parts![0] as unknown as { text: string }).text).toBe(
      'System instruction',
    );

    // pendingApiHistory should contain ONLY the pending request
    expect(pendingApiHistory).toHaveLength(1);
    expect(
      (pendingApiHistory[0].parts![0] as unknown as { text: string }).text,
    ).toBe('Active prompt');

    // The total combined history should be a valid alternating sequence
    const combined = [...apiHistory, ...pendingApiHistory];
    for (let i = 1; i < combined.length; i++) {
      expect(combined[i].role).not.toBe(combined[i - 1].role);
    }
  });

  it('renderHistory should exclude pendingRequest from the result (late binding)', async () => {
    const contextManager = new ContextManager(
      mockSidecar,
      mockEnv,
      mockTracer,
      mockOrchestrator,
      mockChatHistory,
      mockAdvancedTokenCalculator,
    );

    const pendingRequest: HistoryTurn = {
      id: 'pending-turn-1',
      content: { role: 'user', parts: [{ text: 'Active prompt' }] },
    };

    const { history, apiHistory } =
      await contextManager.renderHistory(pendingRequest);

    // Should be empty because mockChatHistory has no historical turns
    expect(history).toHaveLength(0);
    expect(apiHistory).toHaveLength(0);
  });

  it('renderHistory should correctly populate pendingApiHistory when pendingRequest contains <session_context>', async () => {
    const contextManager = new ContextManager(
      mockSidecar,
      mockEnv,
      mockTracer,
      mockOrchestrator,
      mockChatHistory,
      mockAdvancedTokenCalculator,
    );

    const pendingRequest: HistoryTurn = {
      id: 'pending-turn-session-context',
      content: {
        role: 'user',
        parts: [
          {
            text: '<session_context>\nSome environment details\n</session_context>\nActual user prompt',
          },
        ],
      },
    };

    const { pendingApiHistory } =
      await contextManager.renderHistory(pendingRequest);

    expect(pendingApiHistory).toHaveLength(1);
    expect(
      (pendingApiHistory[0].parts![0] as unknown as { text: string }).text,
    ).toContain('<session_context>');
  });
});