| 1 | import type { ChatHistoryItem } from "core/index.js"; |
| 2 | |
| 3 | import { services } from "../../services/index.js"; |
| 4 | import { posthogService } from "../../telemetry/posthogService.js"; |
| 5 | import { logger } from "../../util/logger.js"; |
| 6 | |
| 7 | import { RemoteServerState } from "./useChat.types.js"; |
| 8 | |
| 9 | function historiesEqual(a: ChatHistoryItem[], b: ChatHistoryItem[]): boolean { |
| 10 | if (a.length !== b.length) return false; |
| 11 | for (let i = 0; i < a.length; i++) { |
| 12 | if (JSON.stringify(a[i]) !== JSON.stringify(b[i])) return false; |
| 13 | } |
| 14 | return true; |
| 15 | } |
| 16 | |
| 17 | /** |
| 18 | * Poll remote server for state updates |
| 19 | */ |
| 20 | async function pollRemoteServerState( |
| 21 | remoteUrl: string, |
| 22 | ): Promise<RemoteServerState | null> { |
| 23 | try { |
| 24 | const response = await fetch(`${remoteUrl}/state`); |
| 25 | if (!response.ok) { |
| 26 | throw new Error(`Failed to fetch state: ${response.statusText}`); |
| 27 | } |
| 28 | return await response.json(); |
| 29 | } catch (error) { |
| 30 | logger.error("Failed to poll server state:", error); |
| 31 | return null; |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | interface SetupRemotePollingOptions { |
| 36 | remoteUrl: string; |
| 37 | setIsWaitingForResponse: React.Dispatch<React.SetStateAction<boolean>>; |
| 38 | responseStartTime: number | null; |
| 39 | setResponseStartTime: React.Dispatch<React.SetStateAction<number | null>>; |
| 40 | } |
| 41 | |
| 42 | /** |
| 43 | * Setup remote mode polling |
| 44 | */ |
| 45 | export function setupRemotePolling({ |
| 46 | remoteUrl, |
| 47 | setIsWaitingForResponse, |
| 48 | responseStartTime, |
| 49 | setResponseStartTime, |
| 50 | }: SetupRemotePollingOptions): () => void { |
| 51 | let pollInterval: NodeJS.Timeout | null = null; |
| 52 | let isPolling = false; |
| 53 | let isMounted = true; |
| 54 | |
| 55 | const pollServerState = async () => { |
| 56 | if (!isMounted || isPolling) return; |
| 57 | isPolling = true; |
| 58 | |
| 59 | try { |
| 60 | const state = await pollRemoteServerState(remoteUrl); |
| 61 | if (state && isMounted) { |
| 62 | updateStateFromRemote({ |
| 63 | state, |
| 64 | setIsWaitingForResponse, |
| 65 | responseStartTime, |
| 66 | setResponseStartTime, |
| 67 | }); |
| 68 | } |
| 69 | } finally { |
| 70 | isPolling = false; |
| 71 | } |
| 72 | }; |
| 73 | |
| 74 | // Start polling immediately |
| 75 | pollServerState(); |
| 76 | |
| 77 | // Set up interval for continuous polling |
| 78 | pollInterval = setInterval(pollServerState, 500); |
| 79 | |
| 80 | return () => { |
| 81 | isMounted = false; |
| 82 | if (pollInterval !== null) { |
| 83 | clearInterval(pollInterval); |
| 84 | } |
| 85 | }; |
| 86 | } |
| 87 | |
| 88 | interface UpdateStateFromRemoteOptions { |
| 89 | state: RemoteServerState; |
| 90 | setIsWaitingForResponse: React.Dispatch<React.SetStateAction<boolean>>; |
| 91 | responseStartTime: number | null; |
| 92 | setResponseStartTime: React.Dispatch<React.SetStateAction<number | null>>; |
| 93 | } |
| 94 | |
| 95 | /** |
| 96 | * Update local state from remote server state |
| 97 | */ |
| 98 | function updateStateFromRemote({ |
| 99 | state, |
| 100 | setIsWaitingForResponse, |
| 101 | responseStartTime, |
| 102 | setResponseStartTime, |
| 103 | }: UpdateStateFromRemoteOptions): void { |
| 104 | // Update chat history from server - now using session.history directly |
| 105 | if (state.session && state.session.history) { |
| 106 | const newHistory = state.session.history as ChatHistoryItem[]; |
| 107 | // Let ChatHistoryService own the history and emit updates to UI |
| 108 | if (!services.chatHistory.isRemoteMode()) { |
| 109 | services.chatHistory.setRemoteMode(true); |
| 110 | } |
| 111 | // Avoid redundant updates: only set when history actually changed |
| 112 | try { |
| 113 | const current = services.chatHistory.getHistory(); |
| 114 | const changed = !historiesEqual(current, newHistory); |
| 115 | if (changed) services.chatHistory.setHistory(newHistory); |
| 116 | } catch { |
| 117 | // As a fallback, attempt to set history (service may handle no-op) |
| 118 | services.chatHistory.setHistory(newHistory); |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | // Update processing state |
| 123 | setIsWaitingForResponse(state.isProcessing || false); |
| 124 | if (state.isProcessing && !responseStartTime) { |
| 125 | setResponseStartTime(Date.now()); |
| 126 | } else if (!state.isProcessing && responseStartTime) { |
| 127 | setResponseStartTime(null); |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | /** |
| 132 | * Handle /exit command in remote mode |
| 133 | */ |
| 134 | export async function handleRemoteExit( |
| 135 | remoteUrl: string, |
| 136 | exit: () => void, |
| 137 | ): Promise<void> { |
| 138 | posthogService.capture("useSlashCommand", { |
| 139 | name: "exit", |
| 140 | }); |
| 141 | |
| 142 | try { |
| 143 | const response = await fetch(`${remoteUrl}/exit`, { |
| 144 | method: "POST", |
| 145 | }); |
| 146 | |
| 147 | if (response.ok) { |
| 148 | try { |
| 149 | services.chatHistory.addSystemMessage( |
| 150 | "Remote environment is shutting down...", |
| 151 | ); |
| 152 | } catch (err) { |
| 153 | logger.error("Failed to add system message", err); |
| 154 | } |
| 155 | setTimeout(() => exit(), 1000); |
| 156 | } else { |
| 157 | const text = await response.text(); |
| 158 | logger.error("Remote shutdown failed:", text); |
| 159 | try { |
| 160 | services.chatHistory.addSystemMessage( |
| 161 | "Failed to shutdown remote environment", |
| 162 | ); |
| 163 | } catch {} |
| 164 | } |
| 165 | } catch (error) { |
| 166 | logger.error("Failed to send exit request to remote server:", error); |
| 167 | try { |
| 168 | services.chatHistory.addSystemMessage( |
| 169 | "Error: Failed to connect to remote server for shutdown", |
| 170 | ); |
| 171 | } catch {} |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | interface HandleRemoteMessageOptions { |
| 176 | remoteUrl: string; |
| 177 | messageContent: string; |
| 178 | } |
| 179 | |
| 180 | /** |
| 181 | * Send message to remote server |
| 182 | */ |
| 183 | export async function handleRemoteMessage({ |
| 184 | remoteUrl, |
| 185 | messageContent, |
| 186 | }: HandleRemoteMessageOptions): Promise<void> { |
| 187 | try { |
| 188 | const response = await fetch(`${remoteUrl}/message`, { |
| 189 | method: "POST", |
| 190 | headers: { |
| 191 | "Content-Type": "application/json", |
| 192 | }, |
| 193 | body: JSON.stringify({ message: messageContent }), |
| 194 | }); |
| 195 | |
| 196 | if (!response.ok) { |
| 197 | const error = await response.json(); |
| 198 | try { |
| 199 | services.chatHistory.addSystemMessage( |
| 200 | `Error: ${error.error || "Failed to send message"}`, |
| 201 | ); |
| 202 | } catch {} |
| 203 | } |
| 204 | // State will be updated by polling |
| 205 | } catch (error) { |
| 206 | logger.error("Failed to send message to remote server:", error); |
| 207 | try { |
| 208 | services.chatHistory.addSystemMessage( |
| 209 | "Error: Failed to connect to remote server", |
| 210 | ); |
| 211 | } catch {} |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | /** |
| 216 | * Handle /diff command in remote mode |
| 217 | */ |
| 218 | export async function handleRemoteDiff(remoteUrl: string): Promise<void> { |
| 219 | try { |
| 220 | const response = await fetch(`${remoteUrl}/diff`); |
| 221 | if (!response.ok) { |
| 222 | throw new Error(`Failed to fetch diff: ${response.statusText}`); |
| 223 | } |
| 224 | |
| 225 | const responseData = await response.json(); |
| 226 | const diffContent = responseData.diff || ""; |
| 227 | |
| 228 | if (!diffContent || diffContent.trim() === "") { |
| 229 | try { |
| 230 | services.chatHistory.addSystemMessage("No changes to display"); |
| 231 | } catch {} |
| 232 | return; |
| 233 | } |
| 234 | |
| 235 | try { |
| 236 | services.chatHistory.addSystemMessage(`Diff:\n${diffContent}`); |
| 237 | } catch {} |
| 238 | } catch (error: any) { |
| 239 | logger.error("Failed to fetch diff from remote server:", error); |
| 240 | try { |
| 241 | services.chatHistory.addSystemMessage( |
| 242 | `Failed to fetch diff: ${error.message}`, |
| 243 | ); |
| 244 | } catch {} |
| 245 | } |
| 246 | } |
| 247 | |
| 248 | /** |
| 249 | * Handle /apply command in remote mode |
| 250 | */ |
| 251 | export async function handleRemoteApply(remoteUrl: string): Promise<void> { |
| 252 | try { |
| 253 | const response = await fetch(`${remoteUrl}/diff`); |
| 254 | if (!response.ok) { |
| 255 | throw new Error(`Failed to fetch diff: ${response.statusText}`); |
| 256 | } |
| 257 | |
| 258 | const responseData = await response.json(); |
| 259 | const diffContent = responseData.diff || ""; |
| 260 | |
| 261 | if (!diffContent || diffContent.trim() === "") { |
| 262 | try { |
| 263 | services.chatHistory.addSystemMessage("No changes to apply"); |
| 264 | } catch {} |
| 265 | return; |
| 266 | } |
| 267 | |
| 268 | // Apply the diff using git apply |
| 269 | const { execFileSync } = await import("child_process"); |
| 270 | |
| 271 | try { |
| 272 | execFileSync("git", ["apply"], { |
| 273 | input: diffContent, |
| 274 | stdio: ["pipe", "pipe", "pipe"], |
| 275 | }); |
| 276 | |
| 277 | try { |
| 278 | services.chatHistory.addSystemMessage( |
| 279 | "Successfully applied diff to local working tree", |
| 280 | ); |
| 281 | } catch {} |
| 282 | } catch (gitError: any) { |
| 283 | try { |
| 284 | services.chatHistory.addSystemMessage( |
| 285 | `Failed to apply diff: ${gitError.message}`, |
| 286 | ); |
| 287 | } catch {} |
| 288 | } |
| 289 | } catch (error: any) { |
| 290 | logger.error("Failed to fetch diff from remote server:", error); |
| 291 | try { |
| 292 | services.chatHistory.addSystemMessage( |
| 293 | `Failed to fetch diff: ${error.message}`, |
| 294 | ); |
| 295 | } catch {} |
| 296 | } |
| 297 | } |