Elffuss BraidHub

kikocis/continue public

99fe51849b68 · 6.2 KiBRawPermalink
1import { DevDataLogEvent } from "@continuedev/config-yaml";
2import fs from "fs";
3import path from "path";
4import {
5 afterAll,
6 beforeAll,
7 beforeEach,
8 describe,
9 expect,
10 it,
11 vi,
12} from "vitest";
13import { IdeInfo, IdeSettings } from "..";
14import { Core } from "../core";
15import { getDevDataFilePath } from "../util/paths";
16import { DataLogger } from "./log";
17
18// Only mock fetch, not fs
19vi.mock("@continuedev/fetch");
20
21const TEST_EVENT: DevDataLogEvent = {
22 name: "tokensGenerated",
23 data: {
24 generatedTokens: 100,
25 model: "gpt-4",
26 promptTokens: 50,
27 provider: "openai",
28 },
29};
30
31const TEST_AGENT_INTERACTION_EVENT: DevDataLogEvent = {
32 name: "chatInteraction",
33 data: {
34 prompt: "Hello, world!",
35 completion: "Hello, world!",
36 modelProvider: "openai",
37 modelTitle: "gpt-4",
38 sessionId: "1234",
39 tools: ["test-tool1"],
40 },
41};
42
43const SCHEMA = "0.2.0";
44
45describe("DataLogger", () => {
46 let dataLogger: DataLogger;
47 const tempDir = path.join(process.cwd(), "temp-test-data");
48 const testFilePath = path.join(tempDir, "tokensGenerated-test.jsonl");
49
50 // Create temp directory for test files
51 beforeAll(() => {
52 if (!fs.existsSync(tempDir)) {
53 fs.mkdirSync(tempDir, { recursive: true });
54 }
55 });
56
57 // Clean up temp directory after tests
58 afterAll(() => {
59 if (fs.existsSync(tempDir)) {
60 fs.rmSync(tempDir, { recursive: true, force: true });
61 }
62 });
63
64 beforeEach(() => {
65 // Reset mocks
66 vi.clearAllMocks();
67
68 // Remove test file if it exists
69 if (fs.existsSync(testFilePath)) {
70 fs.unlinkSync(testFilePath);
71 }
72
73 // Get singleton instance
74 dataLogger = DataLogger.getInstance();
75
76 // Mock core and required promises
77 dataLogger.core = {
78 configHandler: {
79 loadConfig: vi.fn().mockResolvedValue({
80 config: {
81 data: [],
82 },
83 }),
84 currentProfile: {
85 profileDescription: {
86 id: "test-profile-id",
87 },
88 },
89 controlPlaneClient: {
90 getAccessToken: vi.fn().mockResolvedValue("test-access-token"),
91 },
92 },
93 } as unknown as Core;
94
95 dataLogger.ideSettingsPromise = Promise.resolve({
96 userToken: "test-user-token",
97 } as IdeSettings);
98
99 dataLogger.ideInfoPromise = Promise.resolve({
100 name: "VSCode",
101 version: "1.0.0",
102 extensionVersion: "0.1.0",
103 } as IdeInfo);
104 });
105
106 describe("getInstance", () => {
107 it("should return the same instance when called multiple times", () => {
108 const instance1 = DataLogger.getInstance();
109 const instance2 = DataLogger.getInstance();
110 expect(instance1).toBe(instance2);
111 });
112 });
113
114 describe("addBaseValues", () => {
115 it("should add base values to event data based on schema", async () => {
116 const mockZodSchema = {
117 shape: {
118 eventName: true,
119 timestamp: true,
120 schema: true,
121 userAgent: true,
122 selectedProfileId: true,
123 userId: true,
124 },
125 };
126
127 const result = await dataLogger.addBaseValues(
128 { customField: "value" },
129 "testEvent",
130 SCHEMA,
131 mockZodSchema as any,
132 );
133
134 expect(result).toEqual({
135 customField: "value",
136 eventName: "testEvent",
137 timestamp: expect.any(String),
138 schema: SCHEMA,
139 userAgent: "VSCode/1.0.0 (Continue/0.1.0)",
140 selectedProfileId: "test-profile-id",
141 userId: "test-user-token",
142 });
143 });
144
145 it("should not add fields not present in schema shape", async () => {
146 const mockZodSchema = {
147 shape: {
148 eventName: true,
149 // No other fields
150 },
151 };
152
153 const result = await dataLogger.addBaseValues(
154 { customField: "value" },
155 "testEvent",
156 SCHEMA,
157 mockZodSchema as any,
158 );
159
160 expect(result).toEqual({
161 customField: "value",
162 eventName: "testEvent",
163 });
164 });
165 });
166
167 describe("logLocalData", () => {
168 it("should actually write data to the local file", async () => {
169 // Call the method to log data locally
170 await dataLogger.logLocalData(TEST_EVENT);
171
172 // Verify the file was created
173 const filepath = getDevDataFilePath(TEST_EVENT.name, SCHEMA);
174 expect(fs.existsSync(filepath)).toBe(true);
175
176 // Read file contents and verify
177 const fileContent = fs.readFileSync(filepath, "utf8");
178 expect(fileContent).toContain('"generatedTokens":100');
179 expect(fileContent).toContain('"model":"gpt-4"');
180 expect(fileContent).toContain('"eventName":"tokensGenerated"');
181 });
182
183 it("should write agent interaction data to local file", async () => {
184 // Call the method to log data locally
185 await dataLogger.logLocalData(TEST_AGENT_INTERACTION_EVENT);
186
187 // Verify the file was created
188 const filepath = getDevDataFilePath(
189 TEST_AGENT_INTERACTION_EVENT.name,
190 SCHEMA,
191 );
192 expect(fs.existsSync(filepath)).toBe(true);
193
194 // Read file contents and verify
195 const fileContent = fs.readFileSync(filepath, "utf8");
196 expect(fileContent).toContain('"eventName":"chatInteraction"');
197 expect(fileContent).toContain('"prompt":"Hello, world!"');
198 expect(fileContent).toContain('"completion":"Hello, world!"');
199 expect(fileContent).toContain('"tools":["test-tool1"]');
200 });
201 });
202
203 describe("logDevData", () => {
204 it("should log data locally and to configured destinations", async () => {
205 // Spy on logLocalData and logToOneDestination
206 const logLocalDataSpy = vi
207 .spyOn(dataLogger, "logLocalData")
208 .mockResolvedValue();
209 const logToOneDestinationSpy = vi
210 .spyOn(dataLogger, "logToOneDestination")
211 .mockResolvedValue();
212
213 // Mock config with multiple data destinations
214 const mockConfig = {
215 config: {
216 data: [
217 { destination: "https://example.com/logs", schema: SCHEMA },
218 { destination: "file:///logs", schema: SCHEMA },
219 ],
220 },
221 };
222
223 dataLogger.core!.configHandler.loadConfig = vi
224 .fn()
225 .mockResolvedValue(mockConfig);
226
227 await dataLogger.logDevData(TEST_EVENT);
228
229 expect(logLocalDataSpy).toHaveBeenCalledWith(TEST_EVENT);
230 expect(logToOneDestinationSpy).toHaveBeenCalledTimes(2);
231 });
232 });
233});