Elffuss BraidHub

kikocis/continue public

073baedf8ebe · 5.2 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
21const DEFAULT_MOCK_CORE_RESPONSES: MockResponses = {
22 fileExists: true,
23 getCurrentFile: {
24 isUntitled: false,
25 contents: "Current file contents",
26 path: "file:///Users/user/workspace1/current_file.py",
27 },
28 "controlPlane/getFreeTrialStatus": {
29 autocompleteLimit: 1000,
30 optedInToFreeTrial: false,
31 chatLimit: 1000,
32 autocompleteCount: 0,
33 chatCount: 0,
34 },
35 getWorkspaceDirs: [
36 "file:///Users/user/workspace1",
37 "file:///Users/user/workspace2",
38 ],
39 "history/list": [
40 {
41 title: "Session 1",
42 sessionId: "session-1",
43 dateCreated: new Date().toString(),
44 workspaceDirectory: "/tmp",
45 },
46 ],
47 "history/save": undefined,
48 getControlPlaneSessionInfo: {
49 AUTH_TYPE: AuthType.WorkOsStaging,
50 accessToken: "",
51 account: {
52 label: "",
53 id: "",
54 },
55 },
56 "config/getSerializedProfileInfo": {
57 organizations: [],
58 profileId: "test-profile",
59 result: {
60 config: undefined,
61 errors: [],
62 configLoadInterrupted: false,
63 },
64 selectedOrgId: "local",
65 },
66 "chatDescriber/describe": "Session summary",
67 applyToFile: undefined,
68 acceptDiff: undefined,
69};
70
71const DEFAULT_CHAT_RESPONSE: ChatMessage[] = [
72 {
73 role: "assistant",
74 content: "This is a test",
75 },
76];
77export class MockIdeMessenger implements IIdeMessenger {
78 ide: IDE;
79
80 constructor() {
81 this.ide = new MessageIde(
82 async (messageType, data) => {
83 const response = await this.request.bind(this)(messageType, data);
84 if (response.status === "error") {
85 throw new Error(response.error);
86 } else {
87 return response.content;
88 }
89 },
90 (messageType, callback) => {
91 return;
92 },
93 );
94 }
95
96 /**
97 * Simulates a message being sent from the IDE to the webview
98 * @param messageType The type of message to send
99 * @param data The data to send with the message
100 */
101 mockMessageToWebview<T extends keyof ToWebviewProtocol>(
102 messageType: T,
103 data: ToWebviewProtocol[T][0],
104 ): void {
105 // Create a message object that matches what the useWebviewListener hook expects
106 const messageData: Message<ToWebviewProtocol[T][0]> = {
107 messageType,
108 data,
109 messageId: `mock-${Date.now()}-${Math.random().toString(36).substring(2)}`,
110 };
111
112 // Dispatch a custom message event that the window event listener will pick up
113 window.dispatchEvent(
114 new MessageEvent("message", {
115 data: messageData,
116 origin: window.location.origin,
117 }),
118 );
119 }
120
121 responses: MockResponses = { ...DEFAULT_MOCK_CORE_RESPONSES };
122 chatResponse: ChatMessage[] = DEFAULT_CHAT_RESPONSE;
123 chatStreamDelay: number = 0;
124 setChatResponseText(text: string): void {
125 this.chatResponse = [
126 {
127 role: "assistant",
128 content: text,
129 },
130 ];
131 }
132
133 async *llmStreamChat(
134 msg: ToCoreProtocol["llm/streamChat"][0],
135 cancelToken: AbortSignal,
136 ): AsyncGenerator<ChatMessage[], PromptLog | undefined> {
137 for (const response of this.chatResponse) {
138 if (cancelToken.aborted) {
139 console.log("MockIdeMessenger: Stream aborted");
140 return undefined;
141 }
142 console.log(
143 "MockIdeMessenger: Yielding chunk",
144 JSON.stringify(response, null, 2),
145 );
146 yield [response];
147 if (this.chatStreamDelay > 0) {
148 await new Promise((resolve) =>
149 setTimeout(resolve, this.chatStreamDelay),
150 );
151 }
152 }
153 return undefined;
154 }
155
156 post<T extends keyof FromWebviewProtocol>(
157 messageType: T,
158 data: FromWebviewProtocol[T][0],
159 messageId?: string,
160 attempt?: number,
161 ): void {}
162
163 async request<T extends keyof FromWebviewProtocol>(
164 messageType: T,
165 data: FromWebviewProtocol[T][0],
166 ): Promise<WebviewSingleProtocolMessage<T>> {
167 if (messageType in this.responses) {
168 const content = this.responses[messageType];
169 return {
170 status: "success",
171 content,
172 done: true,
173 };
174 }
175 console.error(messageType);
176 throw new Error("MockIdeMessenger: No response defined for " + messageType);
177 }
178
179 respond<T extends keyof ToWebviewProtocol>(
180 messageType: T,
181 data: ToWebviewProtocol[T][1],
182 messageId: string,
183 ): void {}
184
185 async *streamRequest<T extends keyof FromWebviewProtocol>(
186 messageType: T,
187 data: FromWebviewProtocol[T][0],
188 cancelToken?: AbortSignal,
189 ): AsyncGenerator<
190 GeneratorYieldType<FromWebviewProtocol[T][1]>[],
191 GeneratorReturnType<FromWebviewProtocol[T][1]> | undefined
192 > {
193 return undefined;
194 }
195
196 resetMocks(): void {
197 this.responses = { ...DEFAULT_MOCK_CORE_RESPONSES };
198 this.chatResponse = DEFAULT_CHAT_RESPONSE;
199 this.chatStreamDelay = 0;
200 }
201}