Elffuss BraidHub

kikocis/continue public

b334cb9dcd5e · 6.1 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};
93
94const DEFAULT_CHAT_RESPONSE: ChatMessage[] = [
95 {
96 role: "assistant",
97 content: "This is a test",
98 },
99];
100export class MockIdeMessenger implements IIdeMessenger {
101 ide: IDE;
102
103 constructor() {
104 this.ide = new MessageIde(
105 async (messageType, data) => {
106 const response = await this.request.bind(this)(messageType, data);
107 if (response.status === "error") {
108 throw new Error(response.error);
109 } else {
110 return response.content;
111 }
112 },
113 (messageType, callback) => {
114 return;
115 },
116 );
117 }
118
119 /**
120 * Simulates a message being sent from the IDE to the webview
121 * @param messageType The type of message to send
122 * @param data The data to send with the message
123 */
124 mockMessageToWebview<T extends keyof ToWebviewProtocol>(
125 messageType: T,
126 data: ToWebviewProtocol[T][0],
127 ): void {
128 // Create a message object that matches what the useWebviewListener hook expects
129 const messageData: Message<ToWebviewProtocol[T][0]> = {
130 messageType,
131 data,
132 messageId: `mock-${Date.now()}-${Math.random().toString(36).substring(2)}`,
133 };
134
135 // Dispatch a custom message event that the window event listener will pick up
136 window.dispatchEvent(
137 new MessageEvent("message", {
138 data: messageData,
139 origin: window.location.origin,
140 }),
141 );
142 }
143
144 responses: MockResponses = { ...DEFAULT_MOCK_CORE_RESPONSES };
145 responseHandlers: MockResponseHandlers = {};
146 chatResponse: ChatMessage[] = DEFAULT_CHAT_RESPONSE;
147 chatStreamDelay: number = 0;
148 setChatResponseText(text: string): void {
149 this.chatResponse = [
150 {
151 role: "assistant",
152 content: text,
153 },
154 ];
155 }
156
157 async *llmStreamChat(
158 msg: ToCoreProtocol["llm/streamChat"][0],
159 cancelToken: AbortSignal,
160 ): AsyncGenerator<ChatMessage[], PromptLog | undefined> {
161 for (const response of this.chatResponse) {
162 if (cancelToken.aborted) {
163 console.log("MockIdeMessenger: Stream aborted");
164 return undefined;
165 }
166 console.log(
167 "MockIdeMessenger: Yielding chunk",
168 JSON.stringify(response, null, 2),
169 );
170 yield [response];
171 if (this.chatStreamDelay > 0) {
172 await new Promise((resolve) =>
173 setTimeout(resolve, this.chatStreamDelay),
174 );
175 }
176 }
177 return undefined;
178 }
179
180 post<T extends keyof FromWebviewProtocol>(
181 messageType: T,
182 data: FromWebviewProtocol[T][0],
183 messageId?: string,
184 attempt?: number,
185 ): void {}
186
187 async request<T extends keyof FromWebviewProtocol>(
188 messageType: T,
189 data: FromWebviewProtocol[T][0],
190 ): Promise<WebviewSingleProtocolMessage<T>> {
191 if (this.responseHandlers[messageType]) {
192 const content = await this.responseHandlers[messageType](data);
193 return {
194 status: "success",
195 content,
196 done: true,
197 };
198 }
199 if (messageType in this.responses) {
200 const content = this.responses[messageType];
201 return {
202 status: "success",
203 content,
204 done: true,
205 };
206 }
207 console.error(messageType);
208 throw new Error(
209 "MockIdeMessenger: No response handler or response defined for " +
210 messageType,
211 );
212 }
213
214 respond<T extends keyof ToWebviewProtocol>(
215 messageType: T,
216 data: ToWebviewProtocol[T][1],
217 messageId: string,
218 ): void {}
219
220 async *streamRequest<T extends keyof FromWebviewProtocol>(
221 messageType: T,
222 data: FromWebviewProtocol[T][0],
223 cancelToken?: AbortSignal,
224 ): AsyncGenerator<
225 GeneratorYieldType<FromWebviewProtocol[T][1]>[],
226 GeneratorReturnType<FromWebviewProtocol[T][1]> | undefined
227 > {
228 return undefined;
229 }
230
231 resetMocks(): void {
232 this.responses = { ...DEFAULT_MOCK_CORE_RESPONSES };
233 this.responseHandlers = {};
234 this.chatResponse = DEFAULT_CHAT_RESPONSE;
235 this.chatStreamDelay = 0;
236 }
237}