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