Press n or j to go to the next uncovered block, b, p or k for the previous block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 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x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | import * as vscode from "vscode"; import { SuggestionContext } from "../api/types/suggestion"; import { fetchSuggestions, refinePrompt } from "../api/suggestion-api"; import { getAuthContext } from "./auth-service"; import { getUserStatus } from "../api/user-api"; import { User, UserStatus } from "../api/types/user"; import { handleSignIn } from "./auth-service"; import { getHint, getExplanation } from "../api/suggestion-api"; import { createCodeCorrectionWebview } from "../views/CodeCorrectionView"; import { createCodeComparisonWebview } from "../views/CodeComparisonView"; import { HintRequest } from "../api/types/suggestion"; import { getSettings, hasBugRandomly } from "../utils"; import { getUserSection } from "../api/user-api"; import { saveSuggestionToDatabase } from "../api/suggestion-api"; import { Suggestion } from "../api/types/suggestion"; import { authNotification, errorNotification } from "../views/notifications"; import { getSelectedClass } from "../utils/userClass"; /** * Represents a suggestion choice for users to select during suspended states. */ export type SuggestionChoice = { text: string; isCorrect: boolean; index: number; }; export let currentChoices: SuggestionChoice[] = []; /** * Stores buggy suggestions that the user needs to review. */ export let suggestionsToReview: string[] = []; /** * Timeout reference used for debouncing typing activity. */ let debounceTimer: NodeJS.Timeout | null = null; /** * Time (ms) to wait after typing stops before triggering a suggestion request. */ const TYPING_PAUSE_THRESHOLD = 500; /** * Represents the most recent text document and cursor information for generating suggestions. */ type LastRequest = { document: vscode.TextDocument; position: vscode.Position; context: vscode.InlineCompletionContext; token: vscode.CancellationToken; } | null; let lastRequest: LastRequest = null; /** * Contextual metadata for the currently active suggestion flow. */ export let suggestionContext: SuggestionContext = { prompt: "", suggestions: [] as string[], suggestionId: "", hasBug: false, startTime: 0, }; export let isSuspended: boolean; /** * Extracts the prompt text from the start of the document up to the cursor position. * * @param document - The active text document. * @param position - The current cursor position. * @returns The extracted prompt text including the programming language. */ export const getPromptText = ( document: vscode.TextDocument, position: vscode.Position ): string => { // Get text from the start of the document to the cursor position const startPos = new vscode.Position(0, 0); const range = new vscode.Range(startPos, position); const text = document.getText(range); const language = document.languageId; return `Language ${language}. Prompt: ${text}`; }; /** * Resets the suggestion context and clears any pending review suggestions. */ export const resetSuggestionContext = () => { suggestionContext = { prompt: "", suggestions: [], suggestionId: "", hasBug: false, startTime: 0, }; suggestionsToReview = []; }; /** * Clears the active debounce timer, if it exists. */ export const resetDebounceTimeout = () => { if (debounceTimer) { clearTimeout(debounceTimer); debounceTimer = null; } }; /** * Sets a new debounce timer to trigger an inline suggestion request after user pauses typing. * * @param resolve - Function to resolve with generated InlineCompletionItems. */ export const setDebounceTimeout = ( resolve: (items: vscode.InlineCompletionItem[]) => void ) => { debounceTimer = setTimeout(async () => { if (shouldSkipSuggestion()) { return; } const user = await getAuthenticatedUser(); if (!user) { await authNotification(); return; } const status = await getAndHandleUserStatus(user.id); if (status === null) { return; } isSuspended = status === UserStatus.SUSPENDED; if (lastRequest) { await handleSuggestionRequest(user, lastRequest, isSuspended, resolve); } }, TYPING_PAUSE_THRESHOLD); }; /** * Stores the latest document, position, and request context. * * @param document - The active text document. * @param position - The cursor position within the document. * @param context - Inline suggestion request context. * @param token - Cancellation token for the request. */ export const setLastRequest = ( document: vscode.TextDocument, position: vscode.Position, context: vscode.InlineCompletionContext, token: vscode.CancellationToken ) => { lastRequest = { document, position, context, token }; }; /** * Checks if suggestions should be skipped due to pending review. * * @returns `true` if there are suggestions to review; otherwise, `false`. */ function shouldSkipSuggestion(): boolean { return suggestionsToReview.length > 0; } /** * Retrieves the currently authenticated user, triggering sign-in if necessary. * * @returns The authenticated user object, or `null` if authentication fails. */ async function getAuthenticatedUser(): Promise<any | null> { const { context: user, error } = await getAuthContext(); if (error || user === undefined) { await errorNotification(`Failed to get user context: ${error}`); return null; } if (!user.isAuthenticated) { const selection = await vscode.window.showInformationMessage( "You are not authenticated. Please sign in to track your progress!", "Sign In" ); if (selection === "Sign In") { handleSignIn(); } return null; } return user; } /** * Retrieves and handles the user's current suggestion status (e.g., LOCKED or ACTIVE). * * @param userId - The user's unique ID. * @returns The user's status or `null` if retrieval fails. */ async function getAndHandleUserStatus( userId: string ): Promise<UserStatus | null> { const selectedClass = getSelectedClass(); const { data: userStatus, error: statusError } = await getUserStatus( userId, selectedClass?.id ); if (statusError) { await errorNotification(`Failed to get user status: ${statusError}`); return null; } const { context: user, error: authError } = await getAuthContext(); if (authError || user === undefined) { await errorNotification(`Failed to get user context: ${authError}`); return null; } if (!user.settings.enable_quiz) { return UserStatus.ACTIVE; } const status = userStatus ?? user.userStatus; if (status === UserStatus.LOCKED) { if (user.settings.show_notifications) { const selection = await vscode.window.showInformationMessage( "Your suggestions are locked. Please review your progress to unlock it.", "Review", "Ignore" ); if (selection === "Review") { vscode.env.openExternal( vscode.Uri.parse("https://clover.nickrucinski.com/") ); } } } if (status !== undefined) { return status; } return null; } /** * Handles fetching and processing a suggestion request, updating the suggestion context. * * @param user - The authenticated user. * @param request - The last typing request context. * @param isSuspended - Whether the user is currently suspended. * @param resolve - Function to resolve with InlineCompletionItems. */ export async function handleSuggestionRequest( user: User, request: LastRequest, isSuspended: boolean, resolve: (items: vscode.InlineCompletionItem[]) => void ) { if (!request) { return; } const prompt = getPromptText(request.document, request.position); if (!prompt || prompt.trim() === "") { return; } const { suggestions, error } = await fetchSuggestions(prompt); if (error || !suggestions) { await errorNotification(`Failed to get suggestions: ${error}`); return; } const hasBug = hasBugRandomly(user.settings.bug_percentage); const selectedClass = getSelectedClass(); const userSection = await getUserSection(user.id, selectedClass?.id); const { refinedPrompt } = await refinePrompt(prompt); const suggestion: Suggestion = { id: "", prompt: refinedPrompt ? refinedPrompt : prompt, suggestionArray: suggestions, hasBug, model: getSettings()["model"], vendor: getSettings()["vendor"], userSectionId: userSection.userSectionId, }; const result = await saveSuggestionToDatabase(suggestion); const suggestionId = result.success ? result.data : ""; suggestionContext = { prompt, suggestions, suggestionId, hasBug, startTime: Date.now(), }; const completionItems = await buildCompletionItems( suggestions, hasBug, isSuspended ); resolve(completionItems); } /** * Builds the inline completion items based on fetched suggestions. * * @param suggestions - List of generated suggestions. * @param hasBug - Whether the suggestion intentionally contains a bug. * @param isSuspended - Whether the user is suspended and requires manual review. * @returns An array of InlineCompletionItems for VS Code. */ export async function buildCompletionItems( suggestions: string[], hasBug: boolean, isSuspended: boolean ): Promise<vscode.InlineCompletionItem[]> { const items: vscode.InlineCompletionItem[] = []; if (isSuspended) { const instructionItem = new vscode.InlineCompletionItem( "⚠️ Please hover and select the correct answer below" ); items.push(instructionItem); const correctChoice = { text: suggestions[0], isCorrect: true, index: 0 }; const incorrectChoice = { text: suggestions[1], isCorrect: false, index: 1, }; currentChoices = [correctChoice, incorrectChoice]; const shuffled = [correctChoice, incorrectChoice].sort( () => Math.random() - 0.5 ); shuffled.forEach((choice) => { const item = new vscode.InlineCompletionItem(choice.text); item.command = { command: "clover.suggestionSelected", title: "Track Suggestion Selection", arguments: [choice], }; items.push(item); }); } else { const selected = hasBug ? suggestions[1] : suggestions[0]; items.push(new vscode.InlineCompletionItem(selected)); // const selected = hasBug ? suggestions[1] : suggestions[0]; // // Split the suggestion into lines // const lines = selected.split("\n"); // // Create incremental completion items // let cumulativeText = ""; // for (const line of lines) { // cumulativeText += (cumulativeText ? "\n" : "") + line; // const item = new vscode.InlineCompletionItem(cumulativeText); // // Add slight delay between lines (optional) // item.range = new vscode.Range( // lastRequest?.position || new vscode.Position(0, 0), // lastRequest?.position || new vscode.Position(0, 0) // ); // items.push(item); // } } return items; } /** * Handles prompting the user to review buggy suggestions and opens appropriate review views. * * @param prompt - The original prompt text. * @param suggestions - The list of suggestions returned. * @param context - Contextual metadata for the suggestion. */ export async function handleBuggedSuggestionReview( prompt: string, suggestions: string[], context: SuggestionContext ) { suggestionsToReview = suggestions; const rightCode = suggestions[0]; const wrongCode = suggestions[1]; const { context: user, error } = await getAuthContext(); if (error || user === undefined) { await errorNotification(`Failed to get user context: ${error}`); return; } if (!user.settings.show_notifications) { return; } const selection = await vscode.window.showWarningMessage( "Warning: The accepted suggestion may contain a bug. Please review the code carefully.", { modal: false }, "Review Code", "Correct Code", "Ignore" ); const request: HintRequest = { prompt, wrongCode, rightCode, }; if (selection === "Review Code") { const result = await getExplanation(request); if (!result.success) { await errorNotification("Failed to get explanation from backend."); return; } createCodeComparisonWebview(rightCode, wrongCode, result.data); } else if (selection === "Correct Code") { const result = await getHint(request); const hint = result.success && result.data; if (!hint) { await errorNotification("Failed to get hint from backend."); return; } createCodeCorrectionWebview(wrongCode, hint, context); } } /** * Handles user selections that may indicate an incorrect suggestion was chosen. * * @param prompt - The original user prompt. * @param wrongCode - The incorrect suggestion chosen. * @param rightCode - The correct suggestion. */ export async function handleIncorrectSuggestionSelection( prompt: string, wrongCode: string, rightCode: string ) { const { context: user, error } = await getAuthContext(); if (error || user === undefined) { await errorNotification(`Failed to get user context: ${error}`); return; } if (!user.settings.show_notifications) { return; } const selection = await vscode.window.showWarningMessage( "That might not be the best solution. Consider reviewing the alternatives.", "Show Explanation" ); if (selection === "Show Explanation") { const request: HintRequest = { prompt, wrongCode, rightCode }; const result = await getExplanation(request); if (result.success) { createCodeComparisonWebview(rightCode, wrongCode, result.data); } else { await errorNotification("Failed to get explanation from backend."); } } } |