summaryrefslogtreecommitdiffhomepage
path: root/src/chat-view.ts
blob: 526a6c138b7d500bb59d0156095c2d0746d29a0e (plain)
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
import { ItemView, MarkdownRenderer, Notice, WorkspaceLeaf, setIcon } from "obsidian";
import type AIOrganizer from "./main";
import type { ChatMessage, ToolCallEvent, ApprovalRequestEvent } from "./ollama-client";
import { sendChatMessageStreaming } from "./ollama-client";
import { SettingsModal } from "./settings-modal";
import { ToolModal } from "./tool-modal";
import { TOOL_REGISTRY } from "./tools";
import type { OllamaToolDefinition } from "./tools";

export const VIEW_TYPE_CHAT = "ai-organizer-chat";

export class ChatView extends ItemView {
	private plugin: AIOrganizer;
	private messages: ChatMessage[] = [];
	private messageContainer: HTMLDivElement | null = null;
	private textarea: HTMLTextAreaElement | null = null;
	private sendButton: HTMLButtonElement | null = null;
	private toolsButton: HTMLButtonElement | null = null;
	private abortController: AbortController | null = null;
	private scrollDebounceTimer: ReturnType<typeof setTimeout> | null = null;
	private bubbleContent: Map<HTMLDivElement, string> = new Map();

	constructor(leaf: WorkspaceLeaf, plugin: AIOrganizer) {
		super(leaf);
		this.plugin = plugin;
	}

	getViewType(): string {
		return VIEW_TYPE_CHAT;
	}

	getDisplayText(): string {
		return "AI Chat";
	}

	getIcon(): string {
		return "message-square";
	}

	async onOpen(): Promise<void> {
		const { contentEl } = this;
		contentEl.empty();
		contentEl.addClass("ai-organizer-chat-container");

		// --- Top region: Chat area ---
		const messagesArea = contentEl.createDiv({ cls: "ai-organizer-messages-area" });
		this.messageContainer = messagesArea.createDiv({ cls: "ai-organizer-messages" });

		// --- FAB Speed Dial ---
		const fab = messagesArea.createDiv({ cls: "ai-organizer-fab" });

		// Main FAB trigger button (first child)
		const fabTrigger = fab.createEl("button", {
			cls: "ai-organizer-fab-trigger",
			attr: { "aria-label": "Actions", tabindex: "0" },
		});
		setIcon(fabTrigger, "settings");

		// Speed dial actions (revealed on focus-within)
		const settingsAction = fab.createDiv({ cls: "ai-organizer-fab-action" });
		const settingsLabel = settingsAction.createSpan({ cls: "ai-organizer-fab-label", text: "AI Settings" });
		void settingsLabel;
		const settingsBtn = settingsAction.createEl("button", {
			cls: "ai-organizer-fab-btn",
			attr: { "aria-label": "Settings" },
		});
		setIcon(settingsBtn, "sliders-horizontal");
		settingsBtn.addEventListener("click", () => {
			new SettingsModal(this.plugin).open();
			// Blur to close the FAB
			(document.activeElement as HTMLElement)?.blur();
		});

		const toolsAction = fab.createDiv({ cls: "ai-organizer-fab-action" });
		const toolsLabel = toolsAction.createSpan({ cls: "ai-organizer-fab-label", text: "Tools" });
		void toolsLabel;
		this.toolsButton = toolsAction.createEl("button", {
			cls: "ai-organizer-fab-btn",
			attr: { "aria-label": "Tools" },
		});
		setIcon(this.toolsButton, "wrench");
		this.updateToolsButtonState();
		this.toolsButton.addEventListener("click", () => {
			const modal = new ToolModal(this.plugin);
			modal.onClose = () => {
				this.updateToolsButtonState();
			};
			modal.open();
			(document.activeElement as HTMLElement)?.blur();
		});

		const clearAction = fab.createDiv({ cls: "ai-organizer-fab-action" });
		const clearLabel = clearAction.createSpan({ cls: "ai-organizer-fab-label", text: "Clear Chat" });
		void clearLabel;
		const clearBtn = clearAction.createEl("button", {
			cls: "ai-organizer-fab-btn",
			attr: { "aria-label": "Clear Chat" },
		});
		setIcon(clearBtn, "trash-2");
		clearBtn.addEventListener("click", () => {
			this.messages = [];
			this.bubbleContent.clear();
			if (this.messageContainer !== null) {
				this.messageContainer.empty();
			}
			(document.activeElement as HTMLElement)?.blur();
		});

		const inputRow = messagesArea.createDiv({ cls: "ai-organizer-input-row" });
		this.textarea = inputRow.createEl("textarea", {
			attr: { placeholder: "Type a message...", rows: "2" },
		});

		// Send button
		this.sendButton = inputRow.createEl("button", { text: "Send" });

		this.textarea.addEventListener("keydown", (e: KeyboardEvent) => {
			if (e.key === "Enter" && !e.shiftKey) {
				e.preventDefault();
				void this.handleSend();
			}
		});

		this.sendButton.addEventListener("click", () => {
			if (this.abortController !== null) {
				// Currently streaming — abort
				this.abortController.abort();
				return;
			}
			void this.handleSend();
		});

		// Auto-connect on open
		void this.plugin.connect();
	}

	async onClose(): Promise<void> {
		if (this.abortController !== null) {
			this.abortController.abort();
		}
		this.contentEl.empty();
		this.messages = [];
		this.bubbleContent.clear();
		this.messageContainer = null;
		this.textarea = null;
		this.sendButton = null;
		this.toolsButton = null;
		this.abortController = null;
	}

	private getEnabledTools(): OllamaToolDefinition[] {
		const tools: OllamaToolDefinition[] = [];
		for (const tool of TOOL_REGISTRY) {
			if (this.plugin.settings.enabledTools[tool.id] === true) {
				tools.push(tool.definition);
			}
		}
		return tools;
	}

	private hasAnyToolEnabled(): boolean {
		return TOOL_REGISTRY.some(
			(tool) => this.plugin.settings.enabledTools[tool.id] === true,
		);
	}

	private updateToolsButtonState(): void {
		if (this.toolsButton === null) return;
		this.toolsButton.toggleClass("ai-organizer-tools-active", this.hasAnyToolEnabled());
	}

	private async handleSend(): Promise<void> {
		if (this.textarea === null || this.sendButton === null || this.messageContainer === null) {
			return;
		}

		const text = this.textarea.value.trim();
		if (text === "") {
			return;
		}

		if (this.plugin.settings.model === "") {
			new Notice("Select a model first.");
			return;
		}

		// Append user message
		this.appendMessage("user", text);
		this.textarea.value = "";
		this.scrollToBottom();

		// Track in message history
		this.messages.push({ role: "user", content: text });

		// Switch to streaming state
		this.abortController = new AbortController();
		this.setStreamingState(true);

		let currentBubble: HTMLDivElement | null = null;

		try {
			const enabledTools = this.getEnabledTools();
			const hasTools = enabledTools.length > 0;

			const onToolCall = (event: ToolCallEvent): void => {
				this.appendToolCall(event);
				this.scrollToBottom();
			};

			const onApprovalRequest = (event: ApprovalRequestEvent): Promise<boolean> => {
				// Remove the empty streaming bubble since the approval
				// prompt is now the active UI element
				if (currentBubble !== null && currentBubble.textContent?.trim() === "") {
					this.bubbleContent.delete(currentBubble);
					currentBubble.remove();
					currentBubble = null;
				}
				return this.showApprovalRequest(event);
			};

			const onCreateBubble = (): void => {
				// Finalize any previous bubble before creating a new one
				if (currentBubble !== null) {
					void this.finalizeBubble(currentBubble);
				}
				currentBubble = this.createStreamingBubble();
			};

			const onChunk = (chunk: string): void => {
				if (currentBubble !== null) {
					// Remove the loading indicator on first chunk
					const loadingIcon = currentBubble.querySelector(".ai-organizer-loading-icon");
					if (loadingIcon !== null) {
						loadingIcon.remove();
					}
					// Accumulate raw text for later markdown rendering
					const prev = this.bubbleContent.get(currentBubble) ?? "";
					this.bubbleContent.set(currentBubble, prev + chunk);
					currentBubble.appendText(chunk);
					this.debouncedScrollToBottom();
				}
			};

			const response = await sendChatMessageStreaming({
				ollamaUrl: this.plugin.settings.ollamaUrl,
				model: this.plugin.settings.model,
				messages: this.messages,
				tools: hasTools ? enabledTools : undefined,
				app: hasTools ? this.plugin.app : undefined,
				options: {
					temperature: this.plugin.settings.temperature,
					num_ctx: this.plugin.settings.numCtx,
					num_predict: this.plugin.settings.numPredict,
				},
				onChunk,
				onToolCall: hasTools ? onToolCall : undefined,
				onApprovalRequest: hasTools ? onApprovalRequest : undefined,
				onCreateBubble,
				abortSignal: this.abortController.signal,
			});

			// Finalize the last streaming bubble
			if (currentBubble !== null) {
				await this.finalizeBubble(currentBubble as HTMLDivElement);
			}
			this.messages.push({ role: "assistant", content: response });
			this.scrollToBottom();
		} catch (err: unknown) {
			// Finalize bubble even on error
			if (currentBubble !== null) {
				(currentBubble as HTMLDivElement).removeClass("ai-organizer-streaming");
				const errorIcon = (currentBubble as HTMLDivElement).querySelector(".ai-organizer-loading-icon");
				if (errorIcon !== null) {
					errorIcon.remove();
				}
				// Remove empty bubble on error
				if ((currentBubble as HTMLDivElement).textContent?.trim() === "") {
					(currentBubble as HTMLDivElement).remove();
				}
				this.bubbleContent.delete(currentBubble as HTMLDivElement);
			}

			const errMsg = err instanceof Error ? err.message : "Unknown error.";
			new Notice(errMsg);
			this.appendMessage("error", `Error: ${errMsg}`);
			this.scrollToBottom();
		}

		// Restore normal state
		this.abortController = null;
		this.setStreamingState(false);
		this.textarea.focus();
	}

	private createStreamingBubble(): HTMLDivElement {
		if (this.messageContainer === null) {
			// Should not happen, but satisfy TS
			throw new Error("Message container not initialized.");
		}
		const bubble = this.messageContainer.createDiv({
			cls: "ai-organizer-message assistant ai-organizer-streaming",
		});
		// Add a loading indicator icon
		const iconSpan = bubble.createSpan({ cls: "ai-organizer-loading-icon" });
		setIcon(iconSpan, "more-horizontal");
		return bubble;
	}

	/**
	 * Finalize a streaming bubble: remove streaming state, render markdown,
	 * and clean up the accumulated content tracker.
	 */
	private async finalizeBubble(bubble: HTMLDivElement): Promise<void> {
		bubble.removeClass("ai-organizer-streaming");

		// Remove loading icon if still present
		const loadingIcon = bubble.querySelector(".ai-organizer-loading-icon");
		if (loadingIcon !== null) {
			loadingIcon.remove();
		}

		const rawText = this.bubbleContent.get(bubble) ?? "";
		this.bubbleContent.delete(bubble);

		// Remove empty bubbles (e.g., tool-only rounds with no content)
		if (rawText.trim() === "") {
			bubble.remove();
			return;
		}

		// Replace plain text with rendered markdown
		bubble.empty();
		bubble.removeClass("ai-organizer-streaming-text");
		bubble.addClass("ai-organizer-markdown");
		await MarkdownRenderer.render(
			this.plugin.app,
			rawText,
			bubble,
			"",
			this,
		);
		this.scrollToBottom();
	}

	private appendMessage(role: "user" | "assistant" | "error", content: string): void {
		if (this.messageContainer === null) {
			return;
		}

		const cls =
			role === "error"
				? "ai-organizer-message assistant error"
				: `ai-organizer-message ${role}`;

		this.messageContainer.createDiv({ cls, text: content });
	}

	private appendToolCall(event: ToolCallEvent): void {
		if (this.messageContainer === null) {
			return;
		}

		const container = this.messageContainer.createDiv({ cls: "ai-organizer-tool-call" });

		const header = container.createDiv({ cls: "ai-organizer-tool-call-header" });
		setIcon(header.createSpan({ cls: "ai-organizer-tool-call-icon" }), "wrench");
		header.createSpan({ text: event.friendlyName, cls: "ai-organizer-tool-call-name" });

		container.createDiv({ text: event.summary, cls: "ai-organizer-tool-call-summary" });
		container.createDiv({ text: event.resultSummary, cls: "ai-organizer-tool-call-result-summary" });

		// DaisyUI-style collapse with checkbox
		const collapse = container.createDiv({ cls: "ai-organizer-collapse ai-organizer-collapse-arrow" });
		const collapseId = `tool-collapse-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
		const checkbox = collapse.createEl("input", {
			type: "checkbox",
			attr: { id: collapseId },
		});
		checkbox.addClass("ai-organizer-collapse-toggle");
		const titleEl = collapse.createEl("label", {
			cls: "ai-organizer-collapse-title",
			attr: { for: collapseId },
			text: "Details",
		});
		void titleEl; // suppress unused warning

		const collapseContent = collapse.createDiv({ cls: "ai-organizer-collapse-content" });
		const contentInner = collapseContent.createDiv({ cls: "ai-organizer-collapse-content-inner" });

		if (event.toolName === "edit_file") {
			// For edit_file, show old_text / new_text in dedicated labeled blocks
			const filePath = typeof event.args.file_path === "string" ? event.args.file_path : "";
			const oldText = typeof event.args.old_text === "string" ? event.args.old_text : "";
			const newText = typeof event.args.new_text === "string" ? event.args.new_text : "";

			if (filePath !== "") {
				contentInner.createEl("div", { text: `File: ${filePath}`, cls: "ai-organizer-tool-call-label" });
			}

			contentInner.createEl("div", { text: "Old text:", cls: "ai-organizer-tool-call-label" });
			contentInner.createEl("pre", {
				text: oldText === "" ? "(empty — new file)" : oldText,
				cls: "ai-organizer-tool-call-args",
			});

			contentInner.createEl("div", { text: "New text:", cls: "ai-organizer-tool-call-label" });
			contentInner.createEl("pre", {
				text: newText,
				cls: "ai-organizer-tool-call-result",
			});
		} else {
			const argsStr = JSON.stringify(event.args, null, 2);
			contentInner.createEl("pre", { text: argsStr, cls: "ai-organizer-tool-call-args" });

			const resultPreview = event.result.length > 500
				? event.result.substring(0, 500) + "..."
				: event.result;
			contentInner.createEl("pre", { text: resultPreview, cls: "ai-organizer-tool-call-result" });
		}
	}

	private showApprovalRequest(event: ApprovalRequestEvent): Promise<boolean> {
		return new Promise<boolean>((resolve) => {
			if (this.messageContainer === null) {
				resolve(false);
				return;
			}

			const container = this.messageContainer.createDiv({ cls: "ai-organizer-approval" });

			const header = container.createDiv({ cls: "ai-organizer-approval-header" });
			setIcon(header.createSpan({ cls: "ai-organizer-approval-icon" }), "shield-alert");
			header.createSpan({ text: event.friendlyName, cls: "ai-organizer-approval-name" });

			container.createDiv({ text: event.message, cls: "ai-organizer-approval-message" });

			// Show details for edit_file so the user can review the change
			if (event.toolName === "edit_file") {
				const oldText = typeof event.args.old_text === "string" ? event.args.old_text : "";
				const newText = typeof event.args.new_text === "string" ? event.args.new_text : "";

				const collapse = container.createDiv({ cls: "ai-organizer-collapse ai-organizer-collapse-arrow" });
				const collapseId = `approval-collapse-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
				const checkbox = collapse.createEl("input", {
					type: "checkbox",
					attr: { id: collapseId, checked: "" },
				});
				checkbox.addClass("ai-organizer-collapse-toggle");
				checkbox.checked = true;
				const titleEl = collapse.createEl("label", {
					cls: "ai-organizer-collapse-title",
					attr: { for: collapseId },
					text: "Review changes",
				});
				void titleEl;

				const collapseContent = collapse.createDiv({ cls: "ai-organizer-collapse-content" });
				const contentInner = collapseContent.createDiv({ cls: "ai-organizer-collapse-content-inner" });

				contentInner.createEl("div", { text: "Old text:", cls: "ai-organizer-tool-call-label" });
				contentInner.createEl("pre", {
					text: oldText === "" ? "(empty \u2014 new file)" : oldText,
					cls: "ai-organizer-tool-call-args",
				});

				contentInner.createEl("div", { text: "New text:", cls: "ai-organizer-tool-call-label" });
				contentInner.createEl("pre", {
					text: newText,
					cls: "ai-organizer-tool-call-result",
				});
			}

			const buttonRow = container.createDiv({ cls: "ai-organizer-approval-buttons" });

			const approveBtn = buttonRow.createEl("button", {
				text: "Approve",
				cls: "ai-organizer-approval-approve",
			});

			const declineBtn = buttonRow.createEl("button", {
				text: "Decline",
				cls: "ai-organizer-approval-decline",
			});

			const finalize = (approved: boolean): void => {
				approveBtn.disabled = true;
				declineBtn.disabled = true;
				container.addClass(approved ? "ai-organizer-approval-approved" : "ai-organizer-approval-declined");
				const statusEl = container.createDiv({ cls: "ai-organizer-approval-status" });
				statusEl.setText(approved ? "Approved" : "Declined");
				this.scrollToBottom();
				resolve(approved);
			};

			approveBtn.addEventListener("click", () => finalize(true));
			declineBtn.addEventListener("click", () => finalize(false));

			this.scrollToBottom();
		});
	}

	private scrollToBottom(): void {
		if (this.messageContainer !== null) {
			this.messageContainer.scrollTop = this.messageContainer.scrollHeight;
		}
	}

	private debouncedScrollToBottom(): void {
		if (this.scrollDebounceTimer !== null) return;
		this.scrollDebounceTimer = setTimeout(() => {
			this.scrollDebounceTimer = null;
			this.scrollToBottom();
		}, 50);
	}

	private setStreamingState(streaming: boolean): void {
		if (this.textarea !== null) {
			this.textarea.disabled = streaming;
		}
		if (this.sendButton !== null) {
			this.sendButton.textContent = streaming ? "Stop" : "Send";
			this.sendButton.toggleClass("ai-organizer-stop-btn", streaming);
		}
	}
}