Elffuss BraidHub

kikocis/continue public

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