File size: 5,332 Bytes
82be208
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Tests for the memoized parseToolCalls and O(1) tool message lookup in
// deriveAgenticSections. These were added to prevent regressions where
// streaming text tokens trigger redundant JSON.parse calls on unchanged
// tool call data.

import { AgenticSectionType, MessageRole } from '$lib/enums';
import type { ApiChatCompletionToolCall } from '$lib/types/api';
import type { DatabaseMessage } from '$lib/types/database';
import { deriveAgenticSections } from '$lib/utils/agentic';
import { describe, expect, it, vi } from 'vitest';

function makeMessage(overrides: Partial<DatabaseMessage>): DatabaseMessage {
	return {
		children: [],
		content: '',
		convId: 'c1',
		id: 'm1',
		parent: null,
		role: MessageRole.ASSISTANT,
		timestamp: 0,
		type: 'text',
		...overrides
	} as DatabaseMessage;
}

describe('parseToolCalls memoization', () => {
	it('returns the same array reference for the same JSON string', () => {
		// parseToolCalls is not exported, but deriveAgenticSections uses it
		// internally. We verify memoization through behavior: calling
		// deriveAgenticSections twice with the same toolCalls should not
		// re-parse (which we verify by checking the returned sections
		// are equivalent).
		const toolCallsJson = JSON.stringify([
			{ function: { arguments: '{}', name: 'test' }, id: 'call_1', type: 'function' }
		]);
		const msg = makeMessage({ content: 'hello', toolCalls: toolCallsJson });
		const sections1 = deriveAgenticSections(msg, [], [], false);
		const sections2 = deriveAgenticSections(msg, [], [], false);

		expect(sections1).toHaveLength(sections2.length);
		expect(sections1[0].type).toBe(sections2[0].type);
	});

	it('does not re-parse JSON on cache hit', () => {
		const toolCallsJson = JSON.stringify([
			{ function: { arguments: '{}', name: 'test' }, id: 'call_1', type: 'function' }
		]);
		const msg = makeMessage({ content: 'hello', toolCalls: toolCallsJson });
		const spy = vi.spyOn(JSON, 'parse');

		deriveAgenticSections(msg, [], [], false);
		const callsAfterFirst = spy.mock.calls.length;

		deriveAgenticSections(msg, [], [], false);
		expect(spy.mock.calls.length).toBe(callsAfterFirst);

		spy.mockRestore();
	});

	it('handles empty/undefined toolCalls without error', () => {
		const msg = makeMessage({ content: 'hello' });
		const sections = deriveAgenticSections(msg, [], [], false);

		expect(sections).toHaveLength(1);
		expect(sections[0].type).toBe(AgenticSectionType.TEXT);
	});

	it('handles invalid JSON gracefully', () => {
		const msg = makeMessage({ content: 'hello', toolCalls: '{invalid' });
		const sections = deriveAgenticSections(msg, [], [], false);

		// Should return just the text section, no tool call sections
		expect(sections).toHaveLength(1);
		expect(sections[0].type).toBe(AgenticSectionType.TEXT);
	});
});

describe('deriveAgenticSections O(1) tool message lookup', () => {
	it('matches tool messages to tool calls by toolCallId', () => {
		const toolCallsJson = JSON.stringify([
			{ function: { arguments: '{}', name: 'test_1' }, id: 'call_1', type: 'function' },
			{ function: { arguments: '{}', name: 'test_2' }, id: 'call_2', type: 'function' }
		]);
		const toolMessages = [
			makeMessage({ content: 'result_1', role: MessageRole.TOOL, toolCallId: 'call_1' }),
			makeMessage({ content: 'result_2', role: MessageRole.TOOL, toolCallId: 'call_2' })
		];
		const msg = makeMessage({ content: 'hello', toolCalls: toolCallsJson });
		const sections = deriveAgenticSections(msg, toolMessages, [], false);
		// Expect: TEXT + 2 TOOL_CALL sections
		const toolCallSections = sections.filter((s) => s.type === AgenticSectionType.TOOL_CALL);

		expect(toolCallSections).toHaveLength(2);
		expect(toolCallSections[0].toolResult).toBe('result_1');
		expect(toolCallSections[1].toolResult).toBe('result_2');
	});

	it('handles missing tool messages (pending calls during streaming)', () => {
		const toolCallsJson = JSON.stringify([
			{ function: { arguments: '{}', name: 'test' }, id: 'call_1', type: 'function' }
		]);
		const msg = makeMessage({ content: '', toolCalls: toolCallsJson });
		const sections = deriveAgenticSections(msg, [], [], true);
		const toolCallSection = sections.find((s) => s.type === AgenticSectionType.TOOL_CALL_PENDING);

		expect(toolCallSection).toBeDefined();
		expect(toolCallSection?.content).toBe('');
	});

	it('scales with many tool calls (no O(n^2) blowup)', () => {
		const N = 100;
		const toolCalls = Array.from(
			{ length: N },
			(_, i): ApiChatCompletionToolCall => ({
				function: { arguments: '{}', name: `tool_${i}` },
				id: `call_${i}`,
				type: 'function'
			})
		);
		const toolCallsJson = JSON.stringify(toolCalls);
		const toolMessages = Array.from({ length: N }, (_, i) =>
			makeMessage({
				content: `result_${i}`,
				role: MessageRole.TOOL,
				toolCallId: `call_${i}`
			})
		);
		const msg = makeMessage({ content: 'hello', toolCalls: toolCallsJson });
		// If the lookup were still O(n^2), this would be noticeably slow
		const start = Date.now();
		const sections = deriveAgenticSections(msg, toolMessages, [], false);
		const elapsed = Date.now() - start;
		const toolCallSections = sections.filter((s) => s.type === AgenticSectionType.TOOL_CALL);

		expect(toolCallSections).toHaveLength(N);
		expect(elapsed).toBeLessThan(100); // Should be fast with O(1) lookup
	});
});