All files / src/highlights ai-assistant-opener.ts

1.01% Statements 2/198
100% Branches 0/0
0% Functions 0/6
1.01% Lines 2/198

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              1x 1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
/**
 * AI Assistant Opener - DRY utility for opening AI chat interfaces
 *
 * Extracts the common logic for opening various AI assistants
 * (Cursor Composer, VS Code Copilot, Inline Chat, Clipboard fallback)
 */
 
import * as vscode from "vscode";
import { Logger } from "../logger";
 
export interface OpenAIAssistantOptions {
    /** The prompt text to send to the AI assistant */
    promptText: string;
    /** File path for navigation (used by inline chat and clipboard fallback) */
    filePath?: string;
    /** Line number (1-indexed) for navigation */
    codeLine?: number;
    /** Label for logging (e.g., "fix intent", "explain intent") */
    intentLabel: string;
    /** Message shown when copying to clipboard */
    clipboardMessage?: string;
}
 
/**
 * Check if a VS Code command exists
 */
async function commandExists(commandId: string): Promise<boolean> {
    const commands = await vscode.commands.getCommands(true);
    return commands.includes(commandId);
}
 
/**
 * Try to open an AI assistant with the given prompt.
 * Falls back through multiple options: Cursor Composer → VS Code Chat → Inline Chat → Clipboard
 *
 * @returns true if successfully opened an AI interface, false if fell back to clipboard
 */
export async function openAIAssistantWithPrompt(
    options: OpenAIAssistantOptions
): Promise<boolean> {
    const { promptText, filePath, codeLine, intentLabel, clipboardMessage } =
        options;
 
    try {
        // Try Cursor-specific commands first
        if (await tryCursorCommands(promptText, intentLabel)) {
            return true;
        }
 
        // Try VS Code Copilot Chat
        if (await tryVSCodeChat(promptText, intentLabel)) {
            return true;
        }
 
        // Try Inline Chat (requires file navigation)
        if (
            filePath &&
            codeLine &&
            (await tryInlineChat(promptText, filePath, codeLine, intentLabel))
        ) {
            return true;
        }
 
        // Final fallback: clipboard
        await fallbackToClipboard(
            promptText,
            filePath,
            codeLine,
            intentLabel,
            clipboardMessage
        );
        return false;
    } catch (error) {
        Logger.getInstance().error(
            `Error opening AI assistant for ${intentLabel}`,
            error
        );
        vscode.window.showErrorMessage(`Failed to open AI assistant: ${error}`);
        return false;
    }
}
 
/**
 * Try multiple Cursor-specific commands to open the AI composer/chat with the prompt
 */
async function tryCursorCommands(
    promptText: string,
    intentLabel: string
): Promise<boolean> {
    const logger = Logger.getInstance();
 
    // First, copy the prompt to clipboard - we'll need it for pasting
    await vscode.env.clipboard.writeText(promptText);
    logger.debug("Prompt copied to clipboard");
 
    // List of Cursor commands to try (in order of preference)
    // We'll open the chat/composer and then the user can paste
    const cursorCommands = [
        "aichat.newchataction", // Opens AI chat panel
        "composer.newSession", // Opens new composer session
        "aipopup.action.modal.generate", // Opens AI popup modal
        "workbench.action.chat.open", // VS Code chat
    ];
 
    for (const cmdId of cursorCommands) {
        try {
            const exists = await commandExists(cmdId);
            if (!exists) {
                logger.debug(`Command ${cmdId} not found, skipping`);
                continue;
            }
 
            logger.debug(`Trying command: ${cmdId}`);
            await vscode.commands.executeCommand(cmdId);
 
            // Small delay to let the UI open
            await new Promise((resolve) => setTimeout(resolve, 100));
 
            // Try to paste the text automatically using the editor's paste command
            try {
                await vscode.commands.executeCommand(
                    "editor.action.clipboardPasteAction"
                );
                logger.info(`Opened and pasted ${intentLabel} via ${cmdId}`);
                return true;
            } catch {
                // Paste didn't work, show notification
                logger.info(
                    `Opened ${cmdId} with ${intentLabel} - prompt in clipboard`
                );
                vscode.window.showInformationMessage(
                    `${intentLabel} ready! Press Cmd+V to paste the prompt.`,
                    "OK"
                );
                return true;
            }
        } catch (error) {
            logger.debug(`Command ${cmdId} failed: ${error}`);
            continue;
        }
    }
 
    logger.debug("No Cursor-specific commands worked, trying alternatives");
    return false;
}
 
async function tryVSCodeChat(
    promptText: string,
    intentLabel: string
): Promise<boolean> {
    const logger = Logger.getInstance();
 
    // This is handled by tryCursorCommands now, which includes workbench.action.chat.open
    // Keep this as a fallback that tries alternative chat commands
    const chatCommands = [
        { id: "workbench.panel.chat.view.copilot.focus", useQuery: false },
        { id: "github.copilot.chat.focus", useQuery: false },
    ];
 
    for (const cmd of chatCommands) {
        try {
            const exists = await commandExists(cmd.id);
            if (!exists) {
                continue;
            }
 
            // Copy to clipboard first
            await vscode.env.clipboard.writeText(promptText);
 
            await vscode.commands.executeCommand(cmd.id);
            logger.info(
                `Opened chat with ${intentLabel} via ${cmd.id} - prompt in clipboard`
            );
            vscode.window.showInformationMessage(
                `${intentLabel} ready! Press Cmd+V to paste.`
            );
            return true;
        } catch {
            continue;
        }
    }
 
    logger.debug("VS Code chat commands not available");
    return false;
}
 
async function tryInlineChat(
    promptText: string,
    filePath: string,
    codeLine: number,
    intentLabel: string
): Promise<boolean> {
    const logger = Logger.getInstance();
 
    try {
        // Check if inline chat command exists
        const exists = await commandExists("inlineChat.start");
        if (!exists) {
            logger.debug("inlineChat.start command not found");
            return false;
        }
 
        // Navigate to the file and line
        const uri = vscode.Uri.file(filePath);
        const doc = await vscode.workspace.openTextDocument(uri);
        const editor = await vscode.window.showTextDocument(doc);
        const line = Math.max(0, codeLine - 1);
        const position = new vscode.Position(line, 0);
        editor.selection = new vscode.Selection(position, position);
        editor.revealRange(new vscode.Range(position, position));
 
        await vscode.commands.executeCommand("inlineChat.start", {
            message: promptText,
        });
        logger.info(`Opened inline chat with ${intentLabel}`);
        return true;
    } catch {
        logger.debug("Inline chat not available");
        return false;
    }
}
 
async function fallbackToClipboard(
    promptText: string,
    filePath?: string,
    codeLine?: number,
    intentLabel?: string,
    customMessage?: string
): Promise<void> {
    const logger = Logger.getInstance();
 
    await vscode.env.clipboard.writeText(promptText);
 
    const message =
        customMessage ||
        `${intentLabel || "Context"} copied to clipboard! Open AI chat (Cmd+L) and paste.`;
 
    const selection = await vscode.window.showInformationMessage(
        message,
        "Open AI Chat",
        "Open File"
    );
 
    if (selection === "Open AI Chat") {
        // Try to open any available AI chat
        const chatCommands = [
            "aichat.newchataction",
            "workbench.action.chat.open",
            "workbench.panel.chat.view.copilot.focus",
        ];
 
        for (const cmd of chatCommands) {
            try {
                const exists = await commandExists(cmd);
                if (exists) {
                    await vscode.commands.executeCommand(cmd);
                    logger.info(`Opened AI chat via ${cmd}`);
                    break;
                }
            } catch {
                continue;
            }
        }
    } else if (selection === "Open File" && filePath) {
        const uri = vscode.Uri.file(filePath);
        const doc = await vscode.workspace.openTextDocument(uri);
        const editor = await vscode.window.showTextDocument(doc);
        if (codeLine) {
            const line = Math.max(0, codeLine - 1);
            const position = new vscode.Position(line, 0);
            editor.selection = new vscode.Selection(position, position);
            editor.revealRange(new vscode.Range(position, position));
        }
    }
 
    logger.info(`Copied ${intentLabel || "context"} to clipboard`);
}