All files / src extension.ts

88.15% Statements 67/76
64% Branches 16/25
63.63% Functions 7/11
88.15% Lines 67/76

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 2031x 1x                         1x 1x 1x 1x 1x 1x   1x     8x 8x         7x       7x   1x 1x       1x                   17x 17x 10x     7x 7x 6x   7x                               17x   3x 3x                   3x     3x 1x 1x     1x 1x   2x 2x 2x   2x 2x       17x   6x                     17x   1x 1x 1x 1x 1x 1x           17x               1x 17x     17x 17x 17x 17x     17x 17x 17x           17x 17x             17x   17x               17x               17x 17x     17x 17x     17x     1x        
import * as vscode from "vscode";
import {
  DEBUG_ENV_VAR,
  DEBUG_STATE_KEY,
  EXTENSION_VERSION,
  MANAGE_COMMAND_ID,
  MIGRATION_DONE_KEY,
  OPEN_DEBUG_LOG_COMMAND_ID,
  PROVIDER_DISPLAY_NAME,
  PROVIDER_VENDOR,
  REFRESH_MODELS_COMMAND_ID,
  SECRET_STORAGE_KEY,
  TOGGLE_DEBUG_LOGGING_COMMAND_ID,
} from "./shared/constants";
import { debugLog, getOutputChannel, outputLog } from "./shared/logging";
import { StatusBarManager } from "./shared/status-bar";
import { NimChatModelProvider } from "./provider/chat-provider";
import { registerNimTools } from "./tools/vision";
import { refreshModelsFromApi, resetRefreshQueue } from "./models/refresh";
import { NvidiaApiKeyResolver } from "./api/key-resolver";
 
let _provider: NimChatModelProvider | null = null;
 
async function migrateLanguageModelProviderGroup(apiKey: string): Promise<boolean> {
  try {
    await vscode.commands.executeCommand("lm.migrateLanguageModelsProviderGroup", {
      vendor: PROVIDER_VENDOR,
      name: PROVIDER_DISPLAY_NAME,
      apiKey,
    });
    outputLog(
      "languageModelGroup",
      `Configured ${PROVIDER_DISPLAY_NAME} language model group from stored API key.`,
    );
    return true;
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    outputLog(
      "languageModelGroup",
      `Could not configure VS Code language model group automatically: ${message}`,
    );
    return /already exists/i.test(message);
  }
}
 
async function initializeStoredApiKey(
  context: vscode.ExtensionContext,
  ua: string,
  statusBar: StatusBarManager,
  keyResolver: NvidiaApiKeyResolver,
): Promise<void> {
  const apiKey = await context.secrets.get(SECRET_STORAGE_KEY);
  if (!apiKey) {
    return;
  }
 
  const migrationDone = context.globalState.get<boolean>(MIGRATION_DONE_KEY, false);
  if (!migrationDone && (await migrateLanguageModelProviderGroup(apiKey))) {
    await context.globalState.update(MIGRATION_DONE_KEY, true);
  }
  await refreshModelsFromApi(
    context,
    ua,
    { showMessages: false, apiKey },
    _provider,
    statusBar,
    keyResolver,
  );
}
 
function registerCommands(
  context: vscode.ExtensionContext,
  ua: string,
  statusBar: StatusBarManager,
  keyResolver: NvidiaApiKeyResolver,
): void {
  context.subscriptions.push(
    vscode.commands.registerCommand(MANAGE_COMMAND_ID, async () => {
      const existing = await context.secrets.get(SECRET_STORAGE_KEY);
      const apiKey = await vscode.window.showInputBox({
        title: `${PROVIDER_DISPLAY_NAME} API Key`,
        prompt: existing
          ? `Update your ${PROVIDER_DISPLAY_NAME} API key`
          : `Enter your ${PROVIDER_DISPLAY_NAME} API key`,
        ignoreFocusOut: true,
        password: true,
        value: existing ?? "",
        placeHolder: `Enter your ${PROVIDER_DISPLAY_NAME} API key...`,
      });
      Iif (apiKey === undefined) {
        return;
      }
      if (!apiKey.trim()) {
        await context.secrets.delete(SECRET_STORAGE_KEY);
        vscode.window.showInformationMessage(
          `${PROVIDER_DISPLAY_NAME} legacy API key cleared. If ${PROVIDER_DISPLAY_NAME} still appears in Copilot Chat, remove its model group from Manage Models.`,
        );
        _provider?.fireModelInfoChanged();
        return;
      }
      await context.secrets.store(SECRET_STORAGE_KEY, apiKey.trim());
      if (await migrateLanguageModelProviderGroup(apiKey.trim())) {
        await context.globalState.update(MIGRATION_DONE_KEY, true);
      }
      vscode.window.showInformationMessage(`${PROVIDER_DISPLAY_NAME} API key saved.`);
      _provider?.fireModelInfoChanged();
    }),
  );
 
  context.subscriptions.push(
    vscode.commands.registerCommand(REFRESH_MODELS_COMMAND_ID, async () => {
      await refreshModelsFromApi(
        context,
        ua,
        { showMessages: true },
        _provider,
        statusBar,
        keyResolver,
      );
    }),
  );
 
  context.subscriptions.push(
    vscode.commands.registerCommand(TOGGLE_DEBUG_LOGGING_COMMAND_ID, async () => {
      const current = context.globalState.get<boolean>(DEBUG_STATE_KEY, false);
      const next = !current;
      await context.globalState.update(DEBUG_STATE_KEY, next);
      process.env[DEBUG_ENV_VAR] = next ? "1" : "0";
      debugLog("toggleDebug", `Debug logging ${next ? "enabled" : "disabled"}.`);
      vscode.window.showInformationMessage(
        `${PROVIDER_DISPLAY_NAME} debug logging ${next ? "enabled" : "disabled"}.`,
      );
    }),
  );
 
  context.subscriptions.push(
    vscode.commands.registerCommand(OPEN_DEBUG_LOG_COMMAND_ID, () => {
      const output = getOutputChannel();
      output.show(true);
    }),
  );
}
 
export function activate(context: vscode.ExtensionContext) {
  const ua = `nvidia-nim-provider/${EXTENSION_VERSION} VSCode/${vscode.version}`;
 
  // Initialize output channel and status bar
  const channel = getOutputChannel();
  context.subscriptions.push(channel);
  const statusBar = new StatusBarManager();
  context.subscriptions.push(statusBar);
 
  // Initialize debug logging
  const debugEnabled = context.globalState.get<boolean>(DEBUG_STATE_KEY, false);
  process.env[DEBUG_ENV_VAR] = debugEnabled ? "1" : "0";
  debugLog(
    "activate",
    `Extension activated. Debug logging ${debugEnabled ? "enabled" : "disabled"}.`,
  );
 
  // Create and register provider
  const keyResolver = new NvidiaApiKeyResolver(context.secrets);
  const provider = new NimChatModelProvider(
    context.secrets,
    ua,
    context.globalState,
    statusBar,
    keyResolver,
  );
  _provider = provider;
 
  context.subscriptions.push(
    context.secrets.onDidChange((e) => {
      Iif (e.key === SECRET_STORAGE_KEY) {
        _provider?.fireModelInfoChanged();
      }
    }),
  );
 
  context.subscriptions.push(
    vscode.workspace.onDidChangeConfiguration((e) => {
      Iif (e.affectsConfiguration("nvidia-nim.ui.showStatusBarItem")) {
        statusBar.updateVisibility();
      }
    }),
  );
 
  const registration = vscode.lm.registerLanguageModelChatProvider(PROVIDER_VENDOR, provider);
  context.subscriptions.push(registration);
 
  // Register tools and commands
  context.subscriptions.push(registerNimTools(context.secrets, context.globalState, keyResolver));
  registerCommands(context, ua, statusBar, keyResolver);
 
  // Initialize stored API key (async, fire-and-forget)
  void initializeStoredApiKey(context, ua, statusBar, keyResolver);
}
 
export function deactivate() {
  _provider = null;
  resetRefreshQueue();
}