All files / src/ui ChatPanel.ts

0% Statements 0/90
0% Branches 0/28
0% Functions 0/23
0% Lines 0/89

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
import * as vscode from 'vscode';
import * as path from 'path';
import { IExtensionContext } from '../interfaces/IExtensionContext';
import { Message, OperationMode, AgentStatus } from '../types';
 
export class ChatPanel {
    private static currentPanel: ChatPanel | undefined;
    private readonly panel: vscode.WebviewPanel;
    private disposables: vscode.Disposable[] = [];
 
    private constructor(
        panel: vscode.WebviewPanel,
        private readonly extensionContext: IExtensionContext
    ) {
        this.panel = panel;
        this.setupWebview();
        this.setupEventListeners();
    }
 
    public static createOrShow(extensionContext: IExtensionContext): ChatPanel {
        const column = vscode.window.activeTextEditor
            ? vscode.window.activeTextEditor.viewColumn
            : undefined;
 
        if (ChatPanel.currentPanel) {
            ChatPanel.currentPanel.panel.reveal(column);
            return ChatPanel.currentPanel;
        }
 
        const panel = vscode.window.createWebviewPanel(
            'claudeFlowChat',
            'Claude Flow Chat',
            column || vscode.ViewColumn.One,
            {
                enableScripts: true,
                retainContextWhenHidden: true,
                localResourceRoots: [
                    vscode.Uri.joinPath(extensionContext.vscodeContext.extensionUri, 'media'),
                    vscode.Uri.joinPath(extensionContext.vscodeContext.extensionUri, 'out', 'webview')
                ]
            }
        );
 
        ChatPanel.currentPanel = new ChatPanel(panel, extensionContext);
        return ChatPanel.currentPanel;
    }
 
    private setupWebview(): void {
        this.panel.webview.html = this.getWebviewContent();
        this.panel.iconPath = vscode.Uri.joinPath(
            this.extensionContext.vscodeContext.extensionUri,
            'media',
            'icon.png'
        );
    }
 
    private setupEventListeners(): void {
        // Handle messages from webview
        this.panel.webview.onDidReceiveMessage(
            async (message) => {
                await this.handleWebviewMessage(message);
            },
            null,
            this.disposables
        );
 
        // Handle panel disposal
        this.panel.onDidDispose(
            () => this.dispose(),
            null,
            this.disposables
        );
 
        // Setup chat manager listeners
        this.extensionContext.chatManager.on('user-message', (message: Message) => {
            this.sendToWebview({
                type: 'user-message',
                payload: message
            });
        });
 
        this.extensionContext.chatManager.on('assistant-message-start', (message: Message) => {
            this.sendToWebview({
                type: 'assistant-message-start',
                payload: message
            });
        });
 
        this.extensionContext.chatManager.on('stream-chunk', (chunk: string) => {
            this.sendToWebview({
                type: 'stream-chunk',
                payload: chunk
            });
        });
 
        this.extensionContext.chatManager.on('assistant-message-complete', (message: Message) => {
            this.sendToWebview({
                type: 'assistant-message-complete',
                payload: message
            });
        });
 
        // Setup orchestrator listeners
        this.extensionContext.orchestratorManager.on('agent-update', (agents: AgentStatus[]) => {
            this.sendToWebview({
                type: 'agent-update',
                payload: agents
            });
        });
 
        this.extensionContext.orchestratorManager.on('task-update', (tasks: any[]) => {
            this.sendToWebview({
                type: 'task-update',
                payload: tasks
            });
        });
 
        this.extensionContext.orchestratorManager.on('error', (error: Error) => {
            this.sendToWebview({
                type: 'error',
                payload: error.message
            });
        });
    }
 
    private async handleWebviewMessage(message: any): Promise<void> {
        switch (message.type) {
            case 'user-message':
                await this.handleUserMessage(message.payload);
                break;
            case 'mode-change':
                await this.handleModeChange(message.payload);
                break;
            case 'apply-code':
                await this.handleApplyCode(message.payload);
                break;
            case 'stop-execution':
                await this.handleStopExecution();
                break;
            case 'ready':
                await this.handleWebviewReady();
                break;
            default:
                console.warn('Unknown message type:', message.type);
        }
    }
 
    private async handleUserMessage(payload: { content: string; mode: OperationMode }): Promise<void> {
        try {
            await this.extensionContext.chatManager.sendMessage(payload.content, payload.mode);
        } catch (error) {
            vscode.window.showErrorMessage(
                `Failed to send message: ${error instanceof Error ? error.message : 'Unknown error'}`
            );
        }
    }
 
    private async handleModeChange(payload: { mode: OperationMode }): Promise<void> {
        try {
            await this.extensionContext.orchestratorManager.switchMode(payload.mode);
            this.sendToWebview({
                type: 'mode-changed',
                payload: payload.mode
            });
        } catch (error) {
            vscode.window.showErrorMessage(
                `Failed to switch mode: ${error instanceof Error ? error.message : 'Unknown error'}`
            );
        }
    }
 
    private async handleApplyCode(payload: { code: string; file?: string }): Promise<void> {
        try {
            const editor = vscode.window.activeTextEditor;
            if (!editor) {
                vscode.window.showErrorMessage('No active editor to apply code');
                return;
            }
 
            const edit = new vscode.WorkspaceEdit();
            if (payload.file) {
                // Apply to specific file
                const uri = vscode.Uri.file(payload.file);
                edit.replace(uri, new vscode.Range(0, 0, editor.document.lineCount, 0), payload.code);
            } else {
                // Apply to active editor
                const fullRange = new vscode.Range(
                    editor.document.positionAt(0),
                    editor.document.positionAt(editor.document.getText().length)
                );
                edit.replace(editor.document.uri, fullRange, payload.code);
            }
 
            await vscode.workspace.applyEdit(edit);
            vscode.window.showInformationMessage('Code applied successfully');
        } catch (error) {
            vscode.window.showErrorMessage(
                `Failed to apply code: ${error instanceof Error ? error.message : 'Unknown error'}`
            );
        }
    }
 
    private async handleStopExecution(): Promise<void> {
        try {
            await this.extensionContext.orchestratorManager.stopExecution();
            this.sendToWebview({
                type: 'execution-stopped',
                payload: null
            });
        } catch (error) {
            vscode.window.showErrorMessage(
                `Failed to stop execution: ${error instanceof Error ? error.message : 'Unknown error'}`
            );
        }
    }
 
    private async handleWebviewReady(): Promise<void> {
        // Initialize webview with current state
        const sessionId = this.extensionContext.chatManager.getActiveSession();
        if (sessionId) {
            const history = this.extensionContext.chatManager.getHistory(sessionId);
            this.sendToWebview({
                type: 'initialize',
                payload: {
                    messages: history,
                    mode: this.extensionContext.orchestratorManager.getCurrentMode(),
                    agents: this.extensionContext.orchestratorManager.getActiveAgents()
                }
            });
        }
    }
 
    private sendToWebview(message: any): void {
        this.panel.webview.postMessage(message);
    }
 
    private getWebviewContent(): string {
        const webviewPath = vscode.Uri.joinPath(
            this.extensionContext.vscodeContext.extensionUri,
            'out',
            'webview'
        );
 
        const scriptUri = this.panel.webview.asWebviewUri(
            vscode.Uri.joinPath(webviewPath, 'main.js')
        );
        const styleUri = this.panel.webview.asWebviewUri(
            vscode.Uri.joinPath(webviewPath, 'style.css')
        );
 
        const nonce = this.getNonce();
 
        return `<!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src ${this.panel.webview.cspSource} 'unsafe-inline'; script-src 'nonce-${nonce}';">
            <link href="${styleUri}" rel="stylesheet">
            <title>Claude Flow Chat</title>
        </head>
        <body>
            <div id="root"></div>
            <script nonce="${nonce}" src="${scriptUri}"></script>
        </body>
        </html>`;
    }
 
    private getNonce(): string {
        let text = '';
        const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        for (let i = 0; i < 32; i++) {
            text += possible.charAt(Math.floor(Math.random() * possible.length));
        }
        return text;
    }
 
    public dispose(): void {
        ChatPanel.currentPanel = undefined;
 
        this.panel.dispose();
 
        while (this.disposables.length) {
            const disposable = this.disposables.pop();
            if (disposable) {
                disposable.dispose();
            }
        }
    }
}