|
| 1 | +// kilocode_change - AI Code Review Service (Async Pattern) |
| 2 | +import { getKiloUrlFromToken } from "@roo-code/types" |
| 3 | +import axios from "axios" |
| 4 | +import { CodeReviewResultsPayload } from "../../../shared/WebviewMessage" |
| 5 | + |
| 6 | +export interface CodeReviewRequest { |
| 7 | + git_diff: string |
| 8 | + git_owner: string |
| 9 | + git_repo: string |
| 10 | + git_branch: string |
| 11 | + git_user: string |
| 12 | +} |
| 13 | + |
| 14 | +export interface CodeReviewStartResponse { |
| 15 | + requestId: string |
| 16 | + status: "pending" |
| 17 | + message: string |
| 18 | +} |
| 19 | + |
| 20 | +export interface CodeReviewStatusResponse { |
| 21 | + status: "pending" | "processing" | "completed" | "failed" |
| 22 | + result?: any |
| 23 | + error?: string |
| 24 | + createdAt: string |
| 25 | + updatedAt: string |
| 26 | +} |
| 27 | + |
| 28 | +export class CodeReviewService { |
| 29 | + private readonly POLLING_INTERVAL = 2000 // 2 seconds |
| 30 | + private readonly MAX_POLLING_DURATION = 5 * 60 * 1000 // 5 minutes |
| 31 | + private readonly REQUEST_TIMEOUT = 30 * 1000 // 30 seconds |
| 32 | + |
| 33 | + constructor(private kilocodeToken: string) {} |
| 34 | + |
| 35 | + async requestCodeReview(request: CodeReviewRequest): Promise<CodeReviewResultsPayload> { |
| 36 | + return this.requestCodeReviewWithRetry(request, 3) // Max 3 retries for initial request |
| 37 | + } |
| 38 | + |
| 39 | + private async requestCodeReviewWithRetry( |
| 40 | + request: CodeReviewRequest, |
| 41 | + maxRetries: number, |
| 42 | + ): Promise<CodeReviewResultsPayload> { |
| 43 | + const headers: Record<string, string> = { |
| 44 | + Authorization: `Bearer ${this.kilocodeToken}`, |
| 45 | + "Content-Type": "application/json", |
| 46 | + } |
| 47 | + |
| 48 | + try { |
| 49 | + // Step 1: Start the async code review |
| 50 | + const startResponse = await this.startCodeReview(request, headers) |
| 51 | + |
| 52 | + // Step 2: Poll for results |
| 53 | + const result = await this.pollForResults(startResponse.requestId, headers) |
| 54 | + return result |
| 55 | + } catch (error) { |
| 56 | + // Check if this is a retryable error (timeout, network, 524, etc.) |
| 57 | + const isRetryable = this.isRetryableError(error) |
| 58 | + |
| 59 | + if (isRetryable && maxRetries > 0) { |
| 60 | + // Exponential backoff: 1s, 2s, 4s |
| 61 | + const delay = Math.pow(2, 3 - maxRetries) * 1000 |
| 62 | + |
| 63 | + await new Promise((resolve) => setTimeout(resolve, delay)) |
| 64 | + return this.requestCodeReviewWithRetry(request, maxRetries - 1) |
| 65 | + } |
| 66 | + |
| 67 | + throw new Error(`Code review failed: ${this.getErrorMessage(error)}`) |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + private async startCodeReview( |
| 72 | + request: CodeReviewRequest, |
| 73 | + headers: Record<string, string>, |
| 74 | + ): Promise<CodeReviewStartResponse> { |
| 75 | + const url = getKiloUrlFromToken("https://api.matterai.so/codereview", this.kilocodeToken) |
| 76 | + |
| 77 | + const response = await axios.post<CodeReviewStartResponse>(url, request, { |
| 78 | + headers, |
| 79 | + timeout: this.REQUEST_TIMEOUT, |
| 80 | + }) |
| 81 | + |
| 82 | + return response.data |
| 83 | + } |
| 84 | + |
| 85 | + private async pollForResults( |
| 86 | + requestId: string, |
| 87 | + headers: Record<string, string>, |
| 88 | + ): Promise<CodeReviewResultsPayload> { |
| 89 | + const startTime = Date.now() |
| 90 | + let attempt = 0 |
| 91 | + |
| 92 | + while (Date.now() - startTime < this.MAX_POLLING_DURATION) { |
| 93 | + attempt++ |
| 94 | + |
| 95 | + try { |
| 96 | + const statusResponse = await this.getCodeReviewStatus(requestId, headers) |
| 97 | + |
| 98 | + switch (statusResponse.status) { |
| 99 | + case "pending": |
| 100 | + break |
| 101 | + |
| 102 | + case "processing": |
| 103 | + break |
| 104 | + |
| 105 | + case "completed": |
| 106 | + return this.extractResults(statusResponse.result) |
| 107 | + |
| 108 | + case "failed": |
| 109 | + throw new Error(`Code review failed: ${statusResponse.error || "Unknown error"}`) |
| 110 | + |
| 111 | + default: |
| 112 | + throw new Error(`Unknown status: ${statusResponse.status}`) |
| 113 | + } |
| 114 | + |
| 115 | + // Wait before next poll |
| 116 | + await new Promise((resolve) => setTimeout(resolve, this.POLLING_INTERVAL)) |
| 117 | + } catch (error) { |
| 118 | + // If it's the final polling attempt, throw the error |
| 119 | + if (Date.now() - startTime >= this.MAX_POLLING_DURATION) { |
| 120 | + throw new Error( |
| 121 | + `Code review polling timed out after ${this.MAX_POLLING_DURATION / 1000} seconds: ${this.getErrorMessage(error)}`, |
| 122 | + ) |
| 123 | + } |
| 124 | + |
| 125 | + // For network errors during polling, wait a bit longer before retry |
| 126 | + if (this.isRetryableError(error)) { |
| 127 | + await new Promise((resolve) => setTimeout(resolve, 3000)) |
| 128 | + } else { |
| 129 | + // For non-retryable errors, don't retry |
| 130 | + throw error |
| 131 | + } |
| 132 | + } |
| 133 | + } |
| 134 | + |
| 135 | + throw new Error(`Code review polling timed out after ${this.MAX_POLLING_DURATION / 1000} seconds`) |
| 136 | + } |
| 137 | + |
| 138 | + private async getCodeReviewStatus( |
| 139 | + requestId: string, |
| 140 | + headers: Record<string, string>, |
| 141 | + ): Promise<CodeReviewStatusResponse> { |
| 142 | + const url = getKiloUrlFromToken(`https://api.matterai.so/codereview/${requestId}`, this.kilocodeToken) |
| 143 | + |
| 144 | + const response = await axios.get<CodeReviewStatusResponse>(url, { |
| 145 | + headers, |
| 146 | + timeout: this.REQUEST_TIMEOUT, |
| 147 | + }) |
| 148 | + |
| 149 | + return response.data |
| 150 | + } |
| 151 | + |
| 152 | + private extractResults(result: any): CodeReviewResultsPayload { |
| 153 | + // Handle the new async response format |
| 154 | + if (result?.codeChangeGeneration) { |
| 155 | + return { |
| 156 | + reviewBody: result.codeChangeGeneration.reviewBody, |
| 157 | + reviewComments: result.codeChangeGeneration.reviewComments || [], |
| 158 | + } |
| 159 | + } |
| 160 | + |
| 161 | + // Fallback if structure matches CodeReviewResultsPayload directly |
| 162 | + return { |
| 163 | + reviewBody: result?.reviewBody || "", |
| 164 | + reviewComments: result?.reviewComments || [], |
| 165 | + } |
| 166 | + } |
| 167 | + |
| 168 | + private isRetryableError(error: any): boolean { |
| 169 | + // Check for timeout errors |
| 170 | + if (axios.isAxiosError(error)) { |
| 171 | + // ECONNABORTED = timeout |
| 172 | + if (error.code === "ECONNABORTED") { |
| 173 | + return true |
| 174 | + } |
| 175 | + |
| 176 | + // 524 = Cloudflare timeout |
| 177 | + if (error.response?.status === 524) { |
| 178 | + return true |
| 179 | + } |
| 180 | + |
| 181 | + // Network errors |
| 182 | + if (error.code === "ENOTFOUND" || error.code === "ECONNREFUSED" || error.code === "ETIMEDOUT") { |
| 183 | + return true |
| 184 | + } |
| 185 | + } |
| 186 | + |
| 187 | + // Check for timeout in error message |
| 188 | + const errorMessage = error instanceof Error ? error.message : String(error) |
| 189 | + if (errorMessage.includes("timeout") || errorMessage.includes("524")) { |
| 190 | + return true |
| 191 | + } |
| 192 | + |
| 193 | + return false |
| 194 | + } |
| 195 | + |
| 196 | + private getErrorMessage(error: any): string { |
| 197 | + if (axios.isAxiosError(error)) { |
| 198 | + if (error.response?.status === 524) { |
| 199 | + return "Cloudflare timeout (524) - backend took too long to respond" |
| 200 | + } |
| 201 | + if (error.code === "ECONNABORTED") { |
| 202 | + return "Request timeout" |
| 203 | + } |
| 204 | + if (error.response?.status) { |
| 205 | + return `HTTP ${error.response.status}: ${error.response.statusText || "Unknown error"}` |
| 206 | + } |
| 207 | + if (error.code) { |
| 208 | + return `Network error: ${error.code}` |
| 209 | + } |
| 210 | + } |
| 211 | + |
| 212 | + return error instanceof Error ? error.message : String(error) |
| 213 | + } |
| 214 | +} |
0 commit comments