Elffuss BraidHub

kikocis/continue public

dfc814e4318e · 6.4 KiBRawPermalink
1import { ChatMessage, IDE, PromptLog } from "core";
2import { AuthType } from "core/control-plane/AuthTypes";
3import {
4 FromWebviewProtocol,
5 ToCoreProtocol,
6 ToWebviewProtocol,
7} from "core/protocol";
8import { Message } from "core/protocol/messenger";
9import { MessageIde } from "core/protocol/messenger/messageIde";
10import {
11 GeneratorReturnType,
12 GeneratorYieldType,
13 WebviewSingleProtocolMessage,
14} from "core/protocol/util";
15import { IIdeMessenger } from "./IdeMessenger";
16
17type MockResponses = Partial<{
18 [K in keyof FromWebviewProtocol]: FromWebviewProtocol[K][1];
19}>;
20
21export type MockResponseHandler<T extends keyof FromWebviewProtocol> = (
22 input: FromWebviewProtocol[T][0],
23) => Promise<FromWebviewProtocol[T][1]>;
24
25type MockResponseHandlers = Partial<{
26 [K in keyof FromWebviewProtocol]: MockResponseHandler<K>;
27}>;
28
29const DEFAULT_MOCK_CORE_RESPONSES: MockResponses = {
30 fileExists: true,
31 getCurrentFile: {
32 isUntitled: false,
33 contents: "Current file contents",
34 path: "file:///Users/user/workspace1/current_file.py",
35 },
36 "controlPlane/getFreeTrialStatus": {
37 autocompleteLimit: 1000,
38 optedInToFreeTrial: false,
39 chatLimit: 1000,
40 autocompleteCount: 0,
41 chatCount: 0,
42 },
43 getWorkspaceDirs: [
44 "file:///Users/user/workspace1",
45 "file:///Users/user/workspace2",
46 ],
47 "history/list": [
48 {
49 title: "Session 1",
50 sessionId: "session-1",
51 dateCreated: new Date().toString(),
52 workspaceDirectory: "/tmp",
53 },
54 ],
55 "history/save": undefined,
56 getControlPlaneSessionInfo: {
57 AUTH_TYPE: AuthType.WorkOsStaging,
58 accessToken: "",
59 account: {
60 label: "",
61 id: "",
62 },
63 },
64 "config/getSerializedProfileInfo": {
65 organizations: [],
66 profileId: "test-profile",
67 result: {
68 config: undefined,
69 errors: [],
70 configLoadInterrupted: false,
71 },
72 selectedOrgId: "local",
73 },
74 "chatDescriber/describe": "Session summary",
75 applyToFile: undefined,
76 acceptDiff: undefined,
77 readFile: "File contents",
78 "tools/call": {
79 contextItems: [
80 {
81 content: "Tool call executed successfully",
82 name: "Tool Result",
83 description: "Mock tool result",
84 },
85 ],
86 },
87 "llm/compileChat": {
88 compiledChatMessages: [],
89 didPrune: false,
90 contextPercentage: 0.5,
91 },
92 "context/getContextItems": [
93 {
94 id: {
95 providerTitle: "mock",
96 itemId: "mock",
97 },
98 content: "Mock current file content",
99 name: "Mock File",
100 description: "Mock file for testing",
101 uri: {
102 type: "file",
103 value: "file:///Users/test/mock-file.ts",
104 },
105 },
106 ],
107};
108
109const DEFAULT_CHAT_RESPONSE: ChatMessage[] = [
110 {
111 role: "assistant",
112 content: "This is a test",
113 },
114];
115export class MockIdeMessenger implements IIdeMessenger {
116 ide: IDE;
117
118 constructor() {
119 this.ide = new MessageIde(
120 async (messageType, data) => {
121 const response = await this.request.bind(this)(messageType, data);
122 if (response.status === "error") {
123 throw new Error(response.error);
124 } else {
125 return response.content;
126 }
127 },
128 (messageType, callback) => {
129 return;
130 },
131 );
132 }
133
134 /**
135 * Simulates a message being sent from the IDE to the webview
136 * @param messageType The type of message to send
137 * @param data The data to send with the message
138 */
139 mockMessageToWebview<T extends keyof ToWebviewProtocol>(
140 messageType: T,
141 data: ToWebviewProtocol[T][0],
142 ): void {
143 // Create a message object that matches what the useWebviewListener hook expects
144 const messageData: Message<ToWebviewProtocol[T][0]> = {
145 messageType,
146 data,
147 messageId: `mock-${Date.now()}-${Math.random().toString(36).substring(2)}`,
148 };
149
150 // Dispatch a custom message event that the window event listener will pick up
151 window.dispatchEvent(
152 new MessageEvent("message", {
153 data: messageData,
154 origin: window.location.origin,
155 }),
156 );
157 }
158
159 responses: MockResponses = { ...DEFAULT_MOCK_CORE_RESPONSES };
160 responseHandlers: MockResponseHandlers = {};
161 chatResponse: ChatMessage[] = DEFAULT_CHAT_RESPONSE;
162 chatStreamDelay: number = 0;
163 setChatResponseText(text: string): void {
164 this.chatResponse = [
165 {
166 role: "assistant",
167 content: text,
168 },
169 ];
170 }
171
172 async *llmStreamChat(
173 msg: ToCoreProtocol["llm/streamChat"][0],
174 cancelToken: AbortSignal,
175 ): AsyncGenerator<ChatMessage[], PromptLog | undefined> {
176 for (const response of this.chatResponse) {
177 if (cancelToken.aborted) {
178 console.log("MockIdeMessenger: Stream aborted");
179 return undefined;
180 }
181 console.log(
182 "MockIdeMessenger: Yielding chunk",
183 JSON.stringify(response, null, 2),
184 );
185 yield [response];
186 if (this.chatStreamDelay > 0) {
187 await new Promise((resolve) =>
188 setTimeout(resolve, this.chatStreamDelay),
189 );
190 }
191 }
192 return undefined;
193 }
194
195 post<T extends keyof FromWebviewProtocol>(
196 messageType: T,
197 data: FromWebviewProtocol[T][0],
198 messageId?: string,
199 attempt?: number,
200 ): void {}
201
202 async request<T extends keyof FromWebviewProtocol>(
203 messageType: T,
204 data: FromWebviewProtocol[T][0],
205 ): Promise<WebviewSingleProtocolMessage<T>> {
206 if (this.responseHandlers[messageType]) {
207 const content = await this.responseHandlers[messageType](data);
208 return {
209 status: "success",
210 content,
211 done: true,
212 };
213 }
214 if (messageType in this.responses) {
215 const content = this.responses[messageType];
216 return {
217 status: "success",
218 content,
219 done: true,
220 };
221 }
222 console.error(messageType);
223 throw new Error(
224 "MockIdeMessenger: No response handler or response defined for " +
225 messageType,
226 );
227 }
228
229 respond<T extends keyof ToWebviewProtocol>(
230 messageType: T,
231 data: ToWebviewProtocol[T][1],
232 messageId: string,
233 ): void {}
234
235 async *streamRequest<T extends keyof FromWebviewProtocol>(
236 messageType: T,
237 data: FromWebviewProtocol[T][0],
238 cancelToken?: AbortSignal,
239 ): AsyncGenerator<
240 GeneratorYieldType<FromWebviewProtocol[T][1]>[],
241 GeneratorReturnType<FromWebviewProtocol[T][1]> | undefined
242 > {
243 return undefined;
244 }
245
246 resetMocks(): void {
247 this.responses = { ...DEFAULT_MOCK_CORE_RESPONSES };
248 this.responseHandlers = {};
249 this.chatResponse = DEFAULT_CHAT_RESPONSE;
250 this.chatStreamDelay = 0;
251 }
252}