Elffuss BraidHub

kikocis/continue public

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