All files / src/commands completion-provider.ts

100% Statements 57/57
100% Branches 7/7
100% Functions 1/1
100% Lines 57/57

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 581x 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 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 4x 1x 1x 1x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
import * as vscode from "vscode";
import {
  resetDebounceTimeout,
  setLastRequest,
  setDebounceTimeout,
} from "../services/suggestion-service";
import { getAuthContext } from "../services/auth-service";
import { errorNotification, authNotification } from "../views/notifications";
 
/**
 * Registers the inline completion provider for AI-generated code suggestions.
 *
 * This provider listens for typing events and supplies real-time code completions.
 */
export const inlineCompletionProvider =
  vscode.languages.registerInlineCompletionItemProvider(
    { scheme: "file" },
    {
      provideInlineCompletionItems,
    }
  );
 
/**
 * Provides inline completion suggestions based on the user's current typing context.
 * @param {vscode.TextDocument} document - The active text document.
 * @param {vscode.Position} position - The current cursor position.
 * @param {vscode.InlineCompletionContext} context - The inline completion context.
 * @param {vscode.CancellationToken} token - A cancellation token.
 * @returns {Promise<vscode.InlineCompletionList | vscode.InlineCompletionItem[]>}
 * A list of inline completion items.
 */
export async function provideInlineCompletionItems(
  document: vscode.TextDocument,
  position: vscode.Position,
  context: vscode.InlineCompletionContext,
  token: vscode.CancellationToken
): Promise<vscode.InlineCompletionList | vscode.InlineCompletionItem[]> {
  const { context: userContext, error } = await getAuthContext();
 
  if (error) {
    await errorNotification(`Failed to get user context: ${error}`);
    return [];
  }
  if (!userContext) {
    await authNotification();
    return [];
  }
  if (!userContext.settings.give_suggestions) {
    return [];
  }
  resetDebounceTimeout();
 
  // Store the latest request
  setLastRequest(document, position, context, token);
  // Wait for debounce to complete and return the suggestion
  return await new Promise((resolve) => setDebounceTimeout(resolve));
}