Elffuss BraidHub

kikocis/continue public

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