All files chat-view.ts

86.15% Statements 168/195
76.92% Branches 50/65
76.92% Functions 20/26
88.95% Lines 161/181

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 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 4331x             1x 1x                 1x 1x 1x 1x   1x   31x       31x 31x 31x 31x 31x 31x 31x 31x 31x     31x 31x 31x 31x 31x       1x       1x       5x 5x 5x       3x 3x 3x 3x 3x 3x 3x         15x 8x 8x           27x 27x   27x     27x 4x   27x 4x     4x     27x   18x   18x     18x 18x       27x     254x     27x 128x   27x 243x     243x 104x   139x     139x 139x         27x 128x 3656x 24x         254x 27x                     5x     5x 5x             5x 5x                 5x 5x 5x 5x 5x   5x         5x       8x 2x         8x 2x         8x 2x         8x                       138x 9x 9x         9x       146x 13x 9x     9x   13x 13x         12x 12x   12x   12x 12x     10x 10x     10x 10x       10x       10x         10x       120x                 10x                                   10x   10x 10x     10x             10x                 10x   10x   10x 10x 10x 10x 10x 10x   10x 10x 12x 12x       12x 12x     12x 1x     12x       10x       8x                   8x   1x 1x         1x 1x     1x 1x 1x       1x         1x                 1x 1x 1x     1x       8x 7x 7x 7x 7x         8x 2x   8x     2x 2x   12x 12x          
import { ItemView, WorkspaceLeaf, Notice, TFile } from 'obsidian';
/// <reference lib="dom" />
// Use global types from JSDOM setup
type KeyboardEvent = globalThis.KeyboardEvent;
type HTMLTextAreaElement = globalThis.HTMLTextAreaElement;
type HTMLButtonElement = globalThis.HTMLButtonElement;
 
const DEFAULT_VAULT_SEARCH_LIMIT = 3;
const MAX_MESSAGE_HISTORY = 50;
import {
  PluginSettings,
  OllamaMessage,
  ChatMessage,
  OllamaTool,
  ToolCall,
  ToolResult,
} from './types';
import { OllamaClient } from './ollama-client';
import { VaultIndexer } from './vault-indexer';
import { ToolExecutor } from './tool-executor';
import { ErrorHandler } from './error-handler';
 
export class ChatView extends ItemView {
  private settings: PluginSettings;
  private messages: ChatMessage[] = [];
  private ollamaClient: OllamaClient;
  private vaultIndexer: VaultIndexer;
  private toolExecutor: ToolExecutor;
  private lastMessageEl: HTMLElement | null = null;
  private newChatButton: HTMLElement | null = null;
  private sendButton: HTMLElement | null = null;
  private inputEl: HTMLElement | null = null;
  private chatContainer: HTMLElement | null = null;
  private sendButtonClickHandler: (() => Promise<void>) | null = null;
  private inputKeyDownHandler: ((e: KeyboardEvent) => Promise<void>) | null = null;
  private newChatButtonClickHandler: (() => void) | null = null;
  private listenersAttached = false;
 
  constructor(leaf: WorkspaceLeaf, settings: PluginSettings) {
    super(leaf);
    this.settings = settings;
    this.ollamaClient = new OllamaClient(settings.ollamaUrl, settings.model);
    this.vaultIndexer = new VaultIndexer(this.app.vault);
    this.toolExecutor = new ToolExecutor(this.app.vault, this.app);
  }
 
  getViewType(): string {
    return 'ollama-chat-view';
  }
 
  getDisplayText(): string {
    return 'Ollama Chat';
  }
 
  async onOpen() {
    await this.render();
    this.removeEventListeners(); // Clean up any existing listeners before reattaching
    this.setupEventListeners();
  }
 
  async onClose() {
    this.ollamaClient.cancelStream();
    this.removeEventListeners();
    this.cleanupStreamingResources();
    this.lastMessageEl = null;
    this.sendButton = null;
    this.inputEl = null;
    this.chatContainer = null;
  }
 
  private cleanupStreamingResources(): void {
    // Ensure any ongoing streaming is properly cleaned up
    if (this.lastMessageEl && this.lastMessageEl.parentElement) {
      this.lastMessageEl.parentElement.removeChild(this.lastMessageEl);
      this.lastMessageEl = null;
    }
  }
 
  async render() {
    const container =
      this.chatContainer || this.contentEl.createEl('div', { cls: 'ollama-chat-container' });
    this.chatContainer = container;
    const inputContainer =
      this.contentEl.querySelector('.ollama-input-container') ||
      this.contentEl.createEl('div', { cls: 'ollama-input-container' });
 
    if (!this.inputEl) {
      this.inputEl = inputContainer.createEl('textarea', { cls: 'ollama-input' });
    }
    if (!this.sendButton) {
      this.sendButton = inputContainer.createEl('button', {
        cls: 'ollama-send-button',
      }) as HTMLButtonElement;
      (this.sendButton as HTMLButtonElement).textContent = 'Send';
    }
 
    if (!this.newChatButton) {
      const newChatContainer =
        this.contentEl.querySelector('.ollama-new-chat') ||
        this.contentEl.createEl('div', { cls: 'ollama-new-chat' });
      this.newChatButton = newChatContainer.createEl('button', {
        cls: 'ollama-new-chat-button',
      }) as HTMLButtonElement;
      (this.newChatButton as HTMLButtonElement).textContent = '🔄 New Chat';
      (this.newChatButton as HTMLButtonElement).title = 'Start a new conversation';
    }
 
    // Create immutable snapshot for rendering
    const messagesSnapshot = [...this.messages];
 
    // Only render messages that are not currently streaming
    const nonStreamingMessages = messagesSnapshot.filter((msg) => !msg.isStreaming);
 
    // Differential update: only update messages that have changed
    const existingMessages = container.querySelectorAll('.ollama-message');
    const existingIds = Array.from(existingMessages).map((el) => el.getAttribute('data-msg-id'));
 
    for (const msg of nonStreamingMessages) {
      const existingEl = container.querySelector(
        `.ollama-message[data-msg-id="${msg.id}"]`
      ) as HTMLElement | null;
      if (existingEl) {
        existingEl.textContent = msg.content;
      } else {
        const messageEl = container.createEl('div', {
          cls: `ollama-message ${msg.role}`,
        }) as HTMLElement;
        messageEl.setAttribute('data-msg-id', msg.id);
        messageEl.textContent = msg.content;
      }
    }
 
    // Remove messages that are no longer in the array
    for (const el of Array.from(existingMessages)) {
      const id = el.getAttribute('data-msg-id');
      if (!id || !nonStreamingMessages.some((m) => m.id === id)) {
        el.remove();
      }
    }
 
    // Re-attach streaming message if it exists
    const streamingMessage = messagesSnapshot.find((msg) => msg.isStreaming);
    Iif (streamingMessage && this.lastMessageEl) {
      const existingStreamingEl = container.querySelector(
        `.ollama-message[data-msg-id="${streamingMessage.id}"]`
      );
      Iif (!existingStreamingEl) {
        container.appendChild(this.lastMessageEl);
      }
    }
  }
 
  private setupEventListeners(): void {
    Iif (!this.sendButton || !this.inputEl || this.listenersAttached) return;
 
    // Create handlers if they don't exist
    if (!this.sendButtonClickHandler) {
      this.sendButtonClickHandler = async () => {
        Iif (!this.inputEl) return;
        await this.handleUserInput((this.inputEl as HTMLTextAreaElement).value);
        (this.inputEl as HTMLTextAreaElement).value = '';
      };
    }
 
    if (!this.inputKeyDownHandler) {
      this.inputKeyDownHandler = async (e: KeyboardEvent) => {
        Iif (!this.inputEl || e.key !== 'Enter' || e.shiftKey) return;
        e.preventDefault();
        await this.handleUserInput((this.inputEl as HTMLTextAreaElement).value);
        (this.inputEl as HTMLTextAreaElement).value = '';
      };
    }
 
    // Add event listeners
    (this.sendButton as HTMLButtonElement).addEventListener('click', this.sendButtonClickHandler!);
    (this.inputEl as HTMLTextAreaElement).addEventListener('keydown', this.inputKeyDownHandler!);
    if (this.newChatButton) {
      if (!this.newChatButtonClickHandler) {
        this.newChatButtonClickHandler = () => this.clearConversation();
      }
      (this.newChatButton as HTMLButtonElement).addEventListener(
        'click',
        this.newChatButtonClickHandler!
      );
    }
    this.listenersAttached = true;
  }
 
  private removeEventListeners(): void {
    if (this.sendButton && this.sendButtonClickHandler) {
      (this.sendButton as HTMLButtonElement).removeEventListener(
        'click',
        this.sendButtonClickHandler!
      );
    }
    if (this.inputEl && this.inputKeyDownHandler) {
      (this.inputEl as HTMLTextAreaElement).removeEventListener(
        'keydown',
        this.inputKeyDownHandler!
      );
    }
    if (this.newChatButton && this.newChatButtonClickHandler) {
      (this.newChatButton as HTMLButtonElement).removeEventListener(
        'click',
        this.newChatButtonClickHandler!
      );
    }
    this.listenersAttached = false;
  }
 
  private clearConversation(): void {
    // Create new array to ensure immutability
    this.messages = [];
    this.lastMessageEl = null;
    this.render();
    new Notice('Conversation cleared');
  }
 
  private updateMessageById(id: string, partial: Partial<ChatMessage>): boolean {
    const index = this.messages.findIndex((m) => m.id === id);
    Iif (index < 0) return false;
    this.messages = [
      ...this.messages.slice(0, index),
      { ...this.messages[index], ...partial },
      ...this.messages.slice(index + 1),
    ];
    return true;
  }
 
  private async updateLastMessage(content: string) {
    const streamingMessage = this.messages.find((msg) => msg.isStreaming);
    if (streamingMessage && !this.lastMessageEl) {
      this.lastMessageEl = this.contentEl.createEl('div', {
        cls: `ollama-message assistant`,
      }) as HTMLElement;
      this.lastMessageEl.setAttribute('data-msg-id', streamingMessage.id);
    }
    if (this.lastMessageEl) {
      this.lastMessageEl.textContent = content;
    }
  }
 
  private async handleUserInput(content: string) {
    Iif (!this.sendButton || !this.inputEl) return;
    (this.sendButton as HTMLButtonElement).disabled = true;
 
    try {
      // Guard against empty messages
      const userMessage = content.trim();
      if (!userMessage) return;
 
      // Search vault using user message as query
      const entries = await this.vaultIndexer.searchVault(userMessage, DEFAULT_VAULT_SEARCH_LIMIT);
      let context = entries.map((e) => `### ${e.title}\n${e.content}`).join('\n\n');
 
      // Cap context size to prevent prompt bloat with large vaults
      const MAX_CONTEXT_LENGTH = 4000;
      Iif (context.length > MAX_CONTEXT_LENGTH) {
        context = context.substring(0, MAX_CONTEXT_LENGTH) + '\n\n... (truncated)';
      }
 
      const systemMessage: OllamaMessage = {
        role: 'system',
        content: 'You are a helpful assistant.',
      };
      const userMessageWithContext: OllamaMessage = {
        role: 'user',
        content: `${context}\n\n${userMessage}`,
      };
 
      const messages: OllamaMessage[] = [
        systemMessage,
        ...this.messages.map(
          (m) =>
            ({
              role: m.role,
              content: m.content,
              tool_calls: m.tool_calls,
            }) as OllamaMessage
        ),
        userMessageWithContext,
      ];
 
      const tools: OllamaTool[] = [
        {
          type: 'function',
          function: {
            name: 'create_file',
            description: 'Create a new file in the vault',
            parameters: {
              type: 'object' as const,
              properties: {
                path: { type: 'string' as const },
                content: { type: 'string' as const },
              },
              required: ['path', 'content'],
            },
          },
        },
      ];
 
      const messageId = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
 
      const userMessageId = messageId;
      const assistantMessageId = `${messageId}-assistant`;
 
      // Store user message in conversation history
      const userChatMessage: ChatMessage = {
        id: userMessageId,
        role: 'user' as const,
        content: userMessage,
        timestamp: Date.now(),
      };
 
      const assistantMessage: ChatMessage = {
        id: assistantMessageId,
        role: 'assistant' as const,
        content: '',
        timestamp: Date.now(),
        isStreaming: true,
      };
 
      // Update messages immutably
      this.messages = [...this.messages, userChatMessage, assistantMessage];
 
      await this.render();
 
      const stream = await this.ollamaClient.streamChat(messages, tools);
      let fullResponse = '';
      let toolCalls: ToolCall[] = [];
      let chunkCount = 0;
      const MAX_STREAM_CHUNKS = 1000;
      const maxChunks = MAX_STREAM_CHUNKS;
 
      try {
        for await (const chunk of stream) {
          chunkCount++;
          Iif (chunkCount > maxChunks) {
            throw new Error('Response too long, stopped streaming');
          }
 
          if (chunk.content) {
            fullResponse += chunk.content;
          }
 
          if (chunk.tool_calls) {
            toolCalls = toolCalls.concat(chunk.tool_calls);
          }
 
          await this.updateLastMessage(fullResponse);
        }
      } finally {
        // Clean up streaming resources regardless of outcome
        this.cleanupStreamingResources();
      }
 
      // Update the assistant message with the full response immutably
      Iif (
        !this.updateMessageById(assistantMessageId, {
          content: fullResponse,
          tool_calls: toolCalls,
        })
      ) {
        throw new Error('Assistant message not found');
      }
 
      // Process tool calls with proper follow-up context
      if (toolCalls.length > 0) {
        // Validate tool calls before processing
        const MAX_TOOL_CALLS = 10;
        Iif (toolCalls.length > MAX_TOOL_CALLS) {
          throw new Error(`Too many tool calls (max ${MAX_TOOL_CALLS})`);
        }
 
        // Collect all tool results using allSettled to support partial results
        const settledResults = await Promise.allSettled(
          toolCalls.map((call) => this.toolExecutor.handleToolCall(call))
        );
 
        let toolResults: ToolResult[] = [];
        for (const result of settledResults) {
          Iif (result.status === 'fulfilled') {
            toolResults.push(result.value);
          } else {
            // Use centralized error handler for tool errors
            ErrorHandler.handleError(result.reason, 'ChatView.handleUserInput');
          }
        }
 
        // Create follow-up messages including the assistant's tool calls and results
        const followUpMessages: OllamaMessage[] = [
          ...messages,
          { role: 'assistant' as const, content: fullResponse, tool_calls: toolCalls },
          ...toolResults.map((result) => ({
            role: 'tool' as const,
            content: JSON.stringify(result),
          })),
        ];
 
        const followUp = await this.ollamaClient.chat(followUpMessages, tools);
        fullResponse += followUp.content;
        await this.updateLastMessage(fullResponse);
 
        // Update the assistant message with the final response immutably
        this.updateMessageById(assistantMessageId, { content: fullResponse, isStreaming: false });
      }
 
      // Update last message immutably — only if no tool calls were processed
      if (toolCalls.length === 0) {
        const lastMessageIndex = this.messages.length - 1;
        if (lastMessageIndex >= 0) {
          const lastMessage = { ...this.messages[lastMessageIndex], isStreaming: false };
          this.messages = [...this.messages.slice(0, lastMessageIndex), lastMessage];
        }
      }
 
      // Limit conversation history to prevent memory issues
      if (this.messages.length > MAX_MESSAGE_HISTORY) {
        this.messages = this.messages.slice(-MAX_MESSAGE_HISTORY);
      }
      await this.render();
    } catch (error) {
      // Use centralized error handler
      ErrorHandler.handleError(error, 'ChatView.handleUserInput');
      this.cleanupStreamingResources();
    } finally {
      if (this.sendButton) {
        (this.sendButton as HTMLButtonElement).disabled = false;
      }
    }
  }
}