All files / src/commands chatCommands.ts

14.35% Statements 28/195
100% Branches 1/1
20% Functions 1/5
14.35% Lines 28/195

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 1961x 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 { ChatPanel } from '../chatPanel';
import { Logger } from '../logger';
import { OllamaChatItem, OllamaInstanceItem, OllamaProvider } from '../ollamaProvider';
import { ChatOrchestrator } from '../services/chatOrchestrator';
import { ChatService } from '../services/chatService';
import { FramingService } from '../services/framingService';
import { ModelService } from '../services/modelService';
 
export class ChatCommands {
    constructor(
        private chatService: ChatService,
        private modelService: ModelService,
        private framingService: FramingService,
        private chatOrchestrator: ChatOrchestrator,
        private ollamaProvider: OllamaProvider,
        private extensionUri: vscode.Uri,
    ) {}
 
    async createChat(node?: OllamaInstanceItem) {
        if (!node) {
            return;
        }

        // 1. Create Chat (immediate)
        const chat = await this.chatService.createChat(node.instance.id);

        // 2. Open Chat Panel (immediate)
        const panel = ChatPanel.createOrShow(
            this.extensionUri,
            chat,
            this.chatService,
            this.ollamaProvider,
            this.modelService,
            this.framingService,
            this.chatOrchestrator,
            () => this.ollamaProvider.refresh(),
        );

        // 3. Start model if not running (async)
        if (!node.isRunning) {
            // Signal loading in UI
            panel.postMessage({ command: 'setLoading', loading: true });

            vscode.window.withProgress(
                {
                    location: vscode.ProgressLocation.Notification,
                    title: `Starting ${node.instance.modelName}...`,
                    cancellable: false,
                },
                async () => {
                    try {
                        await this.ollamaProvider.startModel(node.instance.modelName);
                        this.ollamaProvider.refresh();
                    } catch (err: unknown) {
                        const error = err as Error;
                        Logger.error(`Failed to start model ${node.instance.modelName}`, error);
                        panel.postMessage({
                            command: 'addErrorMessage',
                            content: `Failed to start model: ${error.message}`,
                        });
                    } finally {
                        this.ollamaProvider.setStarting(node.instance.modelName, false);
                        panel.postMessage({ command: 'setLoading', loading: false });
                    }
                },
            );
        } else {
            this.ollamaProvider.refresh();
        }
    }
 
    async startChat() {
        const api = this.ollamaProvider.getApi();
        const allModels = await api.listModels();
        if (allModels.length === 0) {
            vscode.window.showInformationMessage('No models found. Please pull a model first.');
            return;
        }

        const modelName = await vscode.window.showQuickPick(
            allModels.map((m) => m.name),
            { placeHolder: 'Select a model to chat with' },
        );
        if (!modelName) {
            return;
        }

        const instances = this.modelService.getInstancesForModel(modelName);
        let instanceId = modelName;

        if (instances.length > 1) {
            const selectedInst = await vscode.window.showQuickPick(
                instances.map((i) => ({ label: i.name, id: i.id })),
                { placeHolder: `Select an instance of ${modelName}` },
            );
            if (!selectedInst) {
                return;
            }
            instanceId = selectedInst.id;
        }

        const prompt = await vscode.window.showInputBox({
            placeHolder: 'Enter your message',
            prompt: 'What would you like to ask?',
        });
        if (!prompt) {
            return;
        }

        const chat = await this.chatService.createChat(instanceId);
        this.ollamaProvider.refresh();

        const panel = ChatPanel.createOrShow(
            this.extensionUri,
            chat,
            this.chatService,
            this.ollamaProvider,
            this.modelService,
            this.framingService,
            this.chatOrchestrator,
            () => this.ollamaProvider.refresh(),
        );

        const runningModels = await api.listRunning();
        const isRunning = runningModels.some((r) => r.model === modelName);

        if (!isRunning) {
            panel.postMessage({ command: 'setLoading', loading: true });

            vscode.window.withProgress(
                {
                    location: vscode.ProgressLocation.Notification,
                    title: `Starting ${modelName}...`,
                    cancellable: false,
                },
                async () => {
                    try {
                        await this.ollamaProvider.startModel(modelName);
                        this.ollamaProvider.refresh();
                        await panel.handleUserMessage(prompt);
                    } catch (err: unknown) {
                        const error = err as Error;
                        Logger.error(`Failed to start model ${modelName}`, error);
                        panel.postMessage({
                            command: 'addErrorMessage',
                            content: `Failed to start model: ${error.message}`,
                        });
                    } finally {
                        panel.postMessage({ command: 'setLoading', loading: false });
                    }
                },
            );
        } else {
            await panel.handleUserMessage(prompt);
        }
    }
 
    async deleteChat(node: OllamaChatItem) {
        if (!node) {
            return;
        }
        const confirm = await vscode.window.showWarningMessage(
            `Delete chat "${node.chat.name || 'New Chat'}"? This action cannot be undone.`,
            { modal: true },
            'Delete',
        );
        if (confirm === 'Delete') {
            const panel = ChatPanel.panels.get(node.chat.id);
            if (panel) {
                panel.dispose();
            }

            await this.chatService.deleteChat(node.chat.id);
            this.ollamaProvider.refresh();
        }
    }
 
    openChat(node: OllamaChatItem) {
        if (!node) {
            return;
        }
        ChatPanel.createOrShow(
            this.extensionUri,
            node.chat,
            this.chatService,
            this.ollamaProvider,
            this.modelService,
            this.framingService,
            this.chatOrchestrator,
            () => this.ollamaProvider.refresh(),
        );
    }
}