blob: 07ce713def211608e5ed957b73e2fdd95ae23350 [file] [log] [blame]
David Crawshaw77358442025-06-25 00:26:08 +00001import { css, html, LitElement } from "lit";
2import { customElement, property, state } from "lit/decorators.js";
3import { ConnectionStatus, DataManager } from "../data";
4import { AgentMessage, GitLogEntry, State } from "../types";
5import { aggregateAgentMessages } from "./aggregateAgentMessages";
6import { SketchTailwindElement } from "./sketch-tailwind-element";
7
8import "./sketch-chat-input";
9import "./sketch-container-status";
10
11import "./sketch-diff2-view";
12import { SketchDiff2View } from "./sketch-diff2-view";
13import { DefaultGitDataService } from "./git-data-service";
14import "./sketch-monaco-view";
15import "./sketch-network-status";
16import "./sketch-call-status";
17import "./sketch-terminal";
18import "./sketch-timeline";
19import "./sketch-view-mode-select";
20import "./sketch-todo-panel";
21
22import { createRef, ref } from "lit/directives/ref.js";
23import { SketchChatInput } from "./sketch-chat-input";
24
25type ViewMode = "chat" | "diff2" | "terminal";
26
27// Base class for sketch app shells - contains shared logic
28export abstract class SketchAppShellBase extends SketchTailwindElement {
29 // Current view mode (chat, diff, terminal)
30 @state()
31 viewMode: ViewMode = "chat";
32
33 // Current commit hash for diff view
34 @state()
35 currentCommitHash: string = "";
36
37 // Last commit information
38 @state()
39
40 // Reference to the container status element
41 containerStatusElement: any = null;
42
43 // Note: CSS styles have been converted to Tailwind classes applied directly to HTML elements
44 // since this component now extends SketchTailwindElement which disables shadow DOM
45
46 // Override createRenderRoot to apply host styles for proper sizing while still using light DOM
47 createRenderRoot() {
48 // Use light DOM like SketchTailwindElement but still apply host styles
49 const style = document.createElement("style");
50 style.textContent = `
51 sketch-app-shell {
52 display: block;
53 width: 100%;
54 height: 100vh;
55 max-width: 100%;
56 box-sizing: border-box;
57 overflow: hidden;
58 }
59 `;
60
61 // Add the style to the document head if not already present
62 if (!document.head.querySelector("style[data-sketch-app-shell]")) {
63 style.setAttribute("data-sketch-app-shell", "");
64 document.head.appendChild(style);
65 }
66
67 return this;
68 }
69
70 // Header bar: Network connection status details
71 @property()
72 connectionStatus: ConnectionStatus = "disconnected";
73
74 // Track if the last commit info has been copied
75 @state()
76 // lastCommitCopied moved to sketch-container-status
77
78 // Track notification preferences
79 @state()
80 notificationsEnabled: boolean = false;
81
82 // Track if the window is focused to control notifications
83 @state()
84 private _windowFocused: boolean = document.hasFocus();
85
86 // Track if the todo panel should be visible
87 @state()
88 protected _todoPanelVisible: boolean = false;
89
90 // Store scroll position for the chat view to preserve it when switching tabs
91 @state()
92 private _chatScrollPosition: number = 0;
93
94 // ResizeObserver for tracking chat input height changes
95 private chatInputResizeObserver: ResizeObserver | null = null;
96
97 @property()
98 connectionErrorMessage: string = "";
99
100 // Chat messages
101 @property({ attribute: false })
102 messages: AgentMessage[] = [];
103
104 @property()
105 set slug(value: string) {
106 const oldValue = this._slug;
107 this._slug = value;
108 this.requestUpdate("slug", oldValue);
109 // Update document title when slug property changes
110 this.updateDocumentTitle();
111 }
112
113 get slug(): string {
114 return this._slug;
115 }
116
117 private _slug: string = "";
118
119 private dataManager = new DataManager();
120
121 @property({ attribute: false })
122 containerState: State = {
123 state_version: 2,
124 slug: "",
125 os: "",
126 message_count: 0,
127 hostname: "",
128 working_dir: "",
129 initial_commit: "",
130 outstanding_llm_calls: 0,
131 outstanding_tool_calls: [],
132 session_id: "",
133 ssh_available: false,
134 ssh_error: "",
135 in_container: false,
136 first_message_index: 0,
137 diff_lines_added: 0,
138 diff_lines_removed: 0,
139 };
140
141 // Mutation observer to detect when new messages are added
142 private mutationObserver: MutationObserver | null = null;
143
144 constructor() {
145 super();
146
147 // Reference to the container status element
148 this.containerStatusElement = null;
149
150 // Binding methods to this
151 this._handleViewModeSelect = this._handleViewModeSelect.bind(this);
152 this._handlePopState = this._handlePopState.bind(this);
153 this._handleShowCommitDiff = this._handleShowCommitDiff.bind(this);
154 this._handleMutlipleChoiceSelected =
155 this._handleMutlipleChoiceSelected.bind(this);
156 this._handleStopClick = this._handleStopClick.bind(this);
157 this._handleEndClick = this._handleEndClick.bind(this);
158 this._handleNotificationsToggle =
159 this._handleNotificationsToggle.bind(this);
160 this._handleWindowFocus = this._handleWindowFocus.bind(this);
161 this._handleWindowBlur = this._handleWindowBlur.bind(this);
162
163 // Load notification preference from localStorage
164 try {
165 const savedPref = localStorage.getItem("sketch-notifications-enabled");
166 if (savedPref !== null) {
167 this.notificationsEnabled = savedPref === "true";
168 }
169 } catch (error) {
170 console.error("Error loading notification preference:", error);
171 }
172 }
173
174 // See https://lit.dev/docs/components/lifecycle/
175 connectedCallback() {
176 super.connectedCallback();
177
178 // Get reference to the container status element
179 setTimeout(() => {
180 this.containerStatusElement =
181 this.shadowRoot?.getElementById("container-status");
182 }, 0);
183
184 // Initialize client-side nav history.
185 const url = new URL(window.location.href);
186 const mode = url.searchParams.get("view") || "chat";
187 window.history.replaceState({ mode }, "", url.toString());
188
189 this.toggleViewMode(mode as ViewMode, false);
190 // Add popstate event listener to handle browser back/forward navigation
191 window.addEventListener("popstate", this._handlePopState);
192
193 // Add event listeners
194 window.addEventListener("view-mode-select", this._handleViewModeSelect);
195 window.addEventListener("show-commit-diff", this._handleShowCommitDiff);
196
197 // Add window focus/blur listeners for controlling notifications
198 window.addEventListener("focus", this._handleWindowFocus);
199 window.addEventListener("blur", this._handleWindowBlur);
200 window.addEventListener(
201 "multiple-choice-selected",
202 this._handleMutlipleChoiceSelected,
203 );
204
205 // register event listeners
206 this.dataManager.addEventListener(
207 "dataChanged",
208 this.handleDataChanged.bind(this),
209 );
210 this.dataManager.addEventListener(
211 "connectionStatusChanged",
212 this.handleConnectionStatusChanged.bind(this),
213 );
214
215 // Set initial document title
216 this.updateDocumentTitle();
217
218 // Initialize the data manager
219 this.dataManager.initialize();
220
221 // Process existing messages for commit info
222 if (this.messages && this.messages.length > 0) {
223 // Update last commit info via container status component
224 setTimeout(() => {
225 if (this.containerStatusElement) {
226 this.containerStatusElement.updateLastCommitInfo(this.messages);
227 }
228 }, 100);
229 }
230
231 // Check if todo panel should be visible on initial load
232 this.checkTodoPanelVisibility();
233
234 // Set up ResizeObserver for chat input to update todo panel height
235 this.setupChatInputObserver();
236 }
237
238 // See https://lit.dev/docs/components/lifecycle/
239 disconnectedCallback() {
240 super.disconnectedCallback();
241 window.removeEventListener("popstate", this._handlePopState);
242
243 // Remove event listeners
244 window.removeEventListener("view-mode-select", this._handleViewModeSelect);
245 window.removeEventListener("show-commit-diff", this._handleShowCommitDiff);
246 window.removeEventListener("focus", this._handleWindowFocus);
247 window.removeEventListener("blur", this._handleWindowBlur);
248 window.removeEventListener(
249 "multiple-choice-selected",
250 this._handleMutlipleChoiceSelected,
251 );
252
253 // unregister data manager event listeners
254 this.dataManager.removeEventListener(
255 "dataChanged",
256 this.handleDataChanged.bind(this),
257 );
258 this.dataManager.removeEventListener(
259 "connectionStatusChanged",
260 this.handleConnectionStatusChanged.bind(this),
261 );
262
263 // Disconnect mutation observer if it exists
264 if (this.mutationObserver) {
265 this.mutationObserver.disconnect();
266 this.mutationObserver = null;
267 }
268
269 // Disconnect chat input resize observer if it exists
270 if (this.chatInputResizeObserver) {
271 this.chatInputResizeObserver.disconnect();
272 this.chatInputResizeObserver = null;
273 }
274 }
275
276 updateUrlForViewMode(mode: ViewMode): void {
277 // Get the current URL without search parameters
278 const url = new URL(window.location.href);
279
280 // Clear existing parameters
281 url.search = "";
282
283 // Only add view parameter if not in default chat view
284 if (mode !== "chat") {
285 url.searchParams.set("view", mode);
286 const diff2View = this.shadowRoot?.querySelector(
287 "sketch-diff2-view",
288 ) as SketchDiff2View;
289
290 // If in diff2 view and there's a commit hash, include that too
291 if (mode === "diff2" && diff2View?.commit) {
292 url.searchParams.set("commit", diff2View.commit);
293 }
294 }
295
296 // Update the browser history without reloading the page
297 window.history.pushState({ mode }, "", url.toString());
298 }
299
300 private _handlePopState(event: PopStateEvent) {
301 if (event.state && event.state.mode) {
302 this.toggleViewMode(event.state.mode, false);
303 } else {
304 this.toggleViewMode("chat", false);
305 }
306 }
307
308 /**
309 * Handle view mode selection event
310 */
311 private _handleViewModeSelect(event: CustomEvent) {
312 const mode = event.detail.mode as "chat" | "diff2" | "terminal";
313 this.toggleViewMode(mode, true);
314 }
315
316 /**
317 * Handle show commit diff event
318 */
319 private _handleShowCommitDiff(event: CustomEvent) {
320 const { commitHash } = event.detail;
321 if (commitHash) {
322 this.showCommitDiff(commitHash);
323 }
324 }
325
326 private _handleMultipleChoice(event: CustomEvent) {
327 window.console.log("_handleMultipleChoice", event);
328 this._sendChat;
329 }
330
331 private _handleDiffComment(event: CustomEvent) {
332 // Empty stub required by the event binding in the template
333 // Actual handling occurs at global level in sketch-chat-input component
334 }
335 /**
336 * Listen for commit diff event
337 * @param commitHash The commit hash to show diff for
338 */
339 private showCommitDiff(commitHash: string): void {
340 // Store the commit hash
341 this.currentCommitHash = commitHash;
342
343 this.toggleViewMode("diff2", true);
344
345 this.updateComplete.then(() => {
346 const diff2View = this.shadowRoot?.querySelector("sketch-diff2-view");
347 if (diff2View) {
348 (diff2View as SketchDiff2View).refreshDiffView();
349 }
350 });
351 }
352
353 /**
354 * Toggle between different view modes: chat, diff2, terminal
355 */
356 private toggleViewMode(mode: ViewMode, updateHistory: boolean): void {
357 // Don't do anything if the mode is already active
358 if (this.viewMode === mode) return;
359
360 // Store scroll position if we're leaving the chat view
361 if (this.viewMode === "chat" && this.scrollContainerRef.value) {
362 // Only store scroll position if we actually have meaningful content
363 const scrollTop = this.scrollContainerRef.value.scrollTop;
364 const scrollHeight = this.scrollContainerRef.value.scrollHeight;
365 const clientHeight = this.scrollContainerRef.value.clientHeight;
366
367 // Store position only if we have scrollable content and have actually scrolled
368 if (scrollHeight > clientHeight && scrollTop > 0) {
369 this._chatScrollPosition = scrollTop;
370 }
371 }
372
373 // Update the view mode
374 this.viewMode = mode;
375
376 if (updateHistory) {
377 // Update URL with the current view mode
378 this.updateUrlForViewMode(mode);
379 }
380
381 // Wait for DOM update to complete
382 this.updateComplete.then(() => {
383 // Handle scroll position restoration for chat view
384 if (
385 mode === "chat" &&
386 this.scrollContainerRef.value &&
387 this._chatScrollPosition > 0
388 ) {
389 // Use requestAnimationFrame to ensure DOM is ready
390 requestAnimationFrame(() => {
391 if (this.scrollContainerRef.value) {
392 // Double-check that we're still in chat mode and the container is available
393 if (
394 this.viewMode === "chat" &&
395 this.scrollContainerRef.value.isConnected
396 ) {
397 this.scrollContainerRef.value.scrollTop =
398 this._chatScrollPosition;
399 }
400 }
401 });
402 }
403
404 // Handle diff2 view specific logic
405 if (mode === "diff2") {
406 // Refresh git/recentlog when Monaco diff view is opened
407 // This ensures branch information is always up-to-date, as branches can change frequently
408 const diff2ViewComp = this.querySelector("sketch-diff2-view");
409 if (diff2ViewComp) {
410 (diff2ViewComp as SketchDiff2View).refreshDiffView();
411 }
412 }
413
414 // Update view mode buttons
415 const viewModeSelect = this.querySelector("sketch-view-mode-select");
416 if (viewModeSelect) {
417 const event = new CustomEvent("update-active-mode", {
418 detail: { mode },
419 bubbles: true,
420 composed: true,
421 });
422 viewModeSelect.dispatchEvent(event);
423 }
424 });
425 }
426
427 /**
428 * Updates the document title based on current slug and connection status
429 */
430 private updateDocumentTitle(): void {
431 let docTitle = `sk: ${this.slug || "untitled"}`;
432
433 // Add red circle emoji if disconnected
434 if (this.connectionStatus === "disconnected") {
435 docTitle += " 🔴";
436 }
437
438 document.title = docTitle;
439 }
440
441 // Check and request notification permission if needed
442 private async checkNotificationPermission(): Promise<boolean> {
443 // Check if the Notification API is supported
444 if (!("Notification" in window)) {
445 console.log("This browser does not support notifications");
446 return false;
447 }
448
449 // Check if permission is already granted
450 if (Notification.permission === "granted") {
451 return true;
452 }
453
454 // If permission is not denied, request it
455 if (Notification.permission !== "denied") {
456 const permission = await Notification.requestPermission();
457 return permission === "granted";
458 }
459
460 return false;
461 }
462
463 // Handle notifications toggle click
464 private _handleNotificationsToggle(): void {
465 this.notificationsEnabled = !this.notificationsEnabled;
466
467 // If enabling notifications, check permissions
468 if (this.notificationsEnabled) {
469 this.checkNotificationPermission();
470 }
471
472 // Save preference to localStorage
473 try {
474 localStorage.setItem(
475 "sketch-notifications-enabled",
476 String(this.notificationsEnabled),
477 );
478 } catch (error) {
479 console.error("Error saving notification preference:", error);
480 }
481 }
482
483 // Handle window focus event
484 private _handleWindowFocus(): void {
485 this._windowFocused = true;
486 }
487
488 // Handle window blur event
489 private _handleWindowBlur(): void {
490 this._windowFocused = false;
491 }
492
493 // Get the last user or agent message (ignore system messages like commit, error, etc.)
494 // For example, when Sketch notices a new commit, it'll send a message,
495 // but it's still idle!
496 private getLastUserOrAgentMessage(): AgentMessage | null {
497 for (let i = this.messages.length - 1; i >= 0; i--) {
498 const message = this.messages[i];
499 if (message.type === "user" || message.type === "agent") {
500 return message;
501 }
502 }
503 return null;
504 }
505
506 // Show notification for message with EndOfTurn=true
507 private async showEndOfTurnNotification(
508 message: AgentMessage,
509 ): Promise<void> {
510 // Don't show notifications if they're disabled
511 if (!this.notificationsEnabled) return;
512
513 // Don't show notifications if the window is focused
514 if (this._windowFocused) return;
515
516 // Check if we have permission to show notifications
517 const hasPermission = await this.checkNotificationPermission();
518 if (!hasPermission) return;
519
520 // Only show notifications for agent messages with end_of_turn=true and no parent_conversation_id
521 if (
522 message.type !== "agent" ||
523 !message.end_of_turn ||
524 message.parent_conversation_id
525 )
526 return;
527
528 // Create a title that includes the sketch slug
529 const notificationTitle = `Sketch: ${this.slug || "untitled"}`;
530
531 // Extract the beginning of the message content (first 100 chars)
532 const messagePreview = message.content
533 ? message.content.substring(0, 100) +
534 (message.content.length > 100 ? "..." : "")
535 : "Agent has completed its turn";
536
537 // Create and show the notification
538 try {
539 new Notification(notificationTitle, {
540 body: messagePreview,
541 icon: "https://sketch.dev/favicon.ico", // Use sketch.dev favicon for notification
542 });
543 } catch (error) {
544 console.error("Error showing notification:", error);
545 }
546 }
547
548 // Check if todo panel should be visible based on latest todo content from messages or state
549 private checkTodoPanelVisibility(): void {
550 // Find the latest todo content from messages first
551 let latestTodoContent = "";
552 for (let i = this.messages.length - 1; i >= 0; i--) {
553 const message = this.messages[i];
554 if (message.todo_content !== undefined) {
555 latestTodoContent = message.todo_content || "";
556 break;
557 }
558 }
559
560 // If no todo content found in messages, check the current state
561 if (latestTodoContent === "" && this.containerState?.todo_content) {
562 latestTodoContent = this.containerState.todo_content;
563 }
564
565 // Parse the todo data to check if there are any actual todos
566 let hasTodos = false;
567 if (latestTodoContent.trim()) {
568 try {
569 const todoData = JSON.parse(latestTodoContent);
570 hasTodos = todoData.items && todoData.items.length > 0;
571 } catch (error) {
572 // Invalid JSON, treat as no todos
573 hasTodos = false;
574 }
575 }
576
577 this._todoPanelVisible = hasTodos;
578
579 // Update todo panel content if visible
580 if (hasTodos) {
581 const todoPanel = this.shadowRoot?.querySelector(
582 "sketch-todo-panel",
583 ) as any;
584 if (todoPanel && todoPanel.updateTodoContent) {
585 todoPanel.updateTodoContent(latestTodoContent);
586 }
587 }
588 }
589
590 private handleDataChanged(eventData: {
591 state: State;
592 newMessages: AgentMessage[];
593 }): void {
594 const { state, newMessages } = eventData;
595
596 // Update state if we received it
597 if (state) {
598 // Ensure we're using the latest call status to prevent indicators from being stuck
599 if (
600 state.outstanding_llm_calls === 0 &&
601 state.outstanding_tool_calls.length === 0
602 ) {
603 // Force reset containerState calls when nothing is reported as in progress
604 state.outstanding_llm_calls = 0;
605 state.outstanding_tool_calls = [];
606 }
607
608 this.containerState = state;
609 this.slug = state.slug || "";
610
611 // Update document title when sketch slug changes
612 this.updateDocumentTitle();
613 }
614
615 // Update messages
616 const oldMessageCount = this.messages.length;
617 this.messages = aggregateAgentMessages(this.messages, newMessages);
618
619 // If new messages were added and we're in chat view, reset stored scroll position
620 // so the timeline can auto-scroll to bottom for new content
621 if (this.messages.length > oldMessageCount && this.viewMode === "chat") {
622 // Only reset if we were near the bottom (indicating user wants to follow new messages)
623 if (this.scrollContainerRef.value) {
624 const scrollTop = this.scrollContainerRef.value.scrollTop;
625 const scrollHeight = this.scrollContainerRef.value.scrollHeight;
626 const clientHeight = this.scrollContainerRef.value.clientHeight;
627 const isNearBottom = scrollTop + clientHeight >= scrollHeight - 50; // 50px tolerance
628
629 if (isNearBottom) {
630 this._chatScrollPosition = 0; // Reset stored position to allow auto-scroll
631 }
632 }
633 }
634
635 // Process new messages to find commit messages
636 // Update last commit info via container status component
637 if (this.containerStatusElement) {
638 this.containerStatusElement.updateLastCommitInfo(newMessages);
639 }
640
641 // Check for agent messages with end_of_turn=true and show notifications
642 if (newMessages && newMessages.length > 0) {
643 for (const message of newMessages) {
644 if (
645 message.type === "agent" &&
646 message.end_of_turn &&
647 !message.parent_conversation_id
648 ) {
649 this.showEndOfTurnNotification(message);
650 break; // Only show one notification per batch of messages
651 }
652 }
653 }
654
655 // Check if todo panel should be visible after agent loop iteration
656 this.checkTodoPanelVisibility();
657
658 // Ensure chat input observer is set up when new data comes in
659 if (!this.chatInputResizeObserver) {
660 this.setupChatInputObserver();
661 }
662 }
663
664 private handleConnectionStatusChanged(
665 status: ConnectionStatus,
666 errorMessage?: string,
667 ): void {
668 this.connectionStatus = status;
669 this.connectionErrorMessage = errorMessage || "";
670
671 // Update document title when connection status changes
672 this.updateDocumentTitle();
673 }
674
675 private async _handleStopClick(): Promise<void> {
676 try {
677 const response = await fetch("cancel", {
678 method: "POST",
679 headers: {
680 "Content-Type": "application/json",
681 },
682 body: JSON.stringify({ reason: "user requested cancellation" }),
683 });
684
685 if (!response.ok) {
686 const errorData = await response.text();
687 throw new Error(
688 `Failed to stop operation: ${response.status} - ${errorData}`,
689 );
690 }
691
692 // Stop request sent
693 } catch (error) {
694 console.error("Error stopping operation:", error);
695 }
696 }
697
698 private async _handleEndClick(event?: Event): Promise<void> {
699 if (event) {
700 event.preventDefault();
701 event.stopPropagation();
702 }
703
704 // Show confirmation dialog
705 const confirmed = window.confirm(
706 "Ending the session will shut down the underlying container. Are you sure?",
707 );
708 if (!confirmed) return;
709
710 try {
711 const response = await fetch("end", {
712 method: "POST",
713 headers: {
714 "Content-Type": "application/json",
715 },
716 body: JSON.stringify({ reason: "user requested end of session" }),
717 });
718
719 if (!response.ok) {
720 const errorData = await response.text();
721 throw new Error(
722 `Failed to end session: ${response.status} - ${errorData}`,
723 );
724 }
725
726 // After successful response, redirect to messages view
727 // Extract the session ID from the URL
728 const currentUrl = window.location.href;
729 // The URL pattern should be like https://sketch.dev/s/cs71-8qa6-1124-aw79/
730 const urlParts = currentUrl.split("/");
731 let sessionId = "";
732
733 // Find the session ID in the URL (should be after /s/)
734 for (let i = 0; i < urlParts.length; i++) {
735 if (urlParts[i] === "s" && i + 1 < urlParts.length) {
736 sessionId = urlParts[i + 1];
737 break;
738 }
739 }
740
741 if (sessionId) {
742 // Create the messages URL
743 const messagesUrl = `/messages/${sessionId}`;
744 // Redirect to messages view
745 window.location.href = messagesUrl;
746 }
747
748 // End request sent - connection will be closed by server
749 } catch (error) {
750 console.error("Error ending session:", error);
751 }
752 }
753
754 async _handleMutlipleChoiceSelected(e: CustomEvent) {
755 const chatInput = this.shadowRoot?.querySelector(
756 "sketch-chat-input",
757 ) as SketchChatInput;
758 if (chatInput) {
759 if (chatInput.content && chatInput.content.trim() !== "") {
760 chatInput.content += "\n\n";
761 }
762 chatInput.content += e.detail.responseText;
763 chatInput.focus();
764 // Adjust textarea height to accommodate new content
765 requestAnimationFrame(() => {
766 if (chatInput.adjustChatSpacing) {
767 chatInput.adjustChatSpacing();
768 }
769 });
770 }
771 }
772
773 async _sendChat(e: CustomEvent) {
774 console.log("app shell: _sendChat", e);
775 e.preventDefault();
776 e.stopPropagation();
777 const message = e.detail.message?.trim();
778 if (message == "") {
779 return;
780 }
781 try {
782 // Always switch to chat view when sending a message so user can see processing
783 if (this.viewMode !== "chat") {
784 this.toggleViewMode("chat", true);
785 }
786
787 // Send the message to the server
788 const response = await fetch("chat", {
789 method: "POST",
790 headers: {
791 "Content-Type": "application/json",
792 },
793 body: JSON.stringify({ message }),
794 });
795
796 if (!response.ok) {
797 const errorData = await response.text();
798 throw new Error(`Server error: ${response.status} - ${errorData}`);
799 }
800 } catch (error) {
801 console.error("Error sending chat message:", error);
802 const statusText = document.getElementById("statusText");
803 if (statusText) {
804 statusText.textContent = "Error sending message";
805 }
806 }
807 }
808
809 protected scrollContainerRef = createRef<HTMLElement>();
810
811 /**
812 * Set up ResizeObserver to monitor chat input height changes
813 */
814 private setupChatInputObserver(): void {
815 // Wait for DOM to be ready
816 this.updateComplete.then(() => {
817 const chatInputElement = this.shadowRoot?.querySelector("#chat-input");
818 if (chatInputElement && !this.chatInputResizeObserver) {
819 this.chatInputResizeObserver = new ResizeObserver((entries) => {
820 for (const entry of entries) {
821 this.updateTodoPanelHeight(entry.contentRect.height);
822 }
823 });
824
825 this.chatInputResizeObserver.observe(chatInputElement);
826
827 // Initial height calculation
828 const rect = chatInputElement.getBoundingClientRect();
829 this.updateTodoPanelHeight(rect.height);
830 }
831 });
832 }
833
834 /**
835 * Update the CSS custom property that controls todo panel bottom position
836 */
837 private updateTodoPanelHeight(chatInputHeight: number): void {
838 // Add some padding (20px) between todo panel and chat input
839 const bottomOffset = chatInputHeight;
840
841 // Update the CSS custom property on the host element
842 this.style.setProperty("--chat-input-height", `${bottomOffset}px`);
843 }
844
845 // Abstract method to be implemented by subclasses
846 abstract render(): any;
847
848 // Protected helper methods for subclasses to render common UI elements
849 protected renderTopBanner() {
850 return html`
851 <!-- Top banner: flex row, space between, border bottom, shadow -->
852 <div
853 id="top-banner"
854 class="flex self-stretch justify-between items-center px-5 pr-8 mb-0 border-b border-gray-200 gap-5 bg-white shadow-md w-full h-12"
855 >
856 <!-- Title container -->
857 <div
858 class="flex flex-col whitespace-nowrap overflow-hidden text-ellipsis max-w-[30%] md:max-w-1/2 sm:max-w-[60%] py-1.5"
859 >
860 <h1
861 class="text-lg md:text-base sm:text-sm font-semibold m-0 min-w-24 whitespace-nowrap overflow-hidden text-ellipsis"
862 >
863 ${this.containerState?.skaband_addr
864 ? html`<a
865 href="${this.containerState.skaband_addr}"
866 target="_blank"
867 rel="noopener noreferrer"
868 class="text-inherit no-underline transition-opacity duration-200 ease-in-out flex items-center gap-2 hover:opacity-80 hover:underline"
869 >
870 <img
871 src="${this.containerState.skaband_addr}/sketch.dev.png"
872 alt="sketch"
873 class="w-5 h-5 md:w-[18px] md:h-[18px] sm:w-4 sm:h-4 rounded-sm"
874 />
875 sketch
876 </a>`
877 : html`sketch`}
878 </h1>
879 <h2
880 class="m-0 p-0 text-gray-600 text-sm font-normal italic whitespace-nowrap overflow-hidden text-ellipsis"
881 >
882 ${this.slug}
883 </h2>
884 </div>
885
886 <!-- Container status info moved above tabs -->
887 <sketch-container-status
888 .state=${this.containerState}
889 id="container-status"
890 ></sketch-container-status>
891
892 <!-- Last Commit section moved to sketch-container-status -->
893
894 <!-- Views section with tabs -->
895 <sketch-view-mode-select
896 .diffLinesAdded=${this.containerState?.diff_lines_added || 0}
897 .diffLinesRemoved=${this.containerState?.diff_lines_removed || 0}
898 ></sketch-view-mode-select>
899
900 <!-- Control buttons and status -->
901 <div
902 class="flex items-center mb-0 flex-nowrap whitespace-nowrap flex-shrink-0 gap-4 pl-4 mr-12"
903 >
904 <button
905 id="stopButton"
906 class="bg-red-600 hover:bg-red-700 disabled:bg-red-300 disabled:cursor-not-allowed disabled:opacity-70 text-white border-none px-2.5 py-1 xl:px-1.5 rounded cursor-pointer text-xs mr-1.5 flex items-center gap-1.5 transition-colors"
907 ?disabled=${(this.containerState?.outstanding_llm_calls || 0) ===
908 0 &&
909 (this.containerState?.outstanding_tool_calls || []).length === 0}
910 >
911 <svg
912 class="w-4 h-4"
913 xmlns="http://www.w3.org/2000/svg"
914 viewBox="0 0 24 24"
915 fill="none"
916 stroke="currentColor"
917 stroke-width="2"
918 stroke-linecap="round"
919 stroke-linejoin="round"
920 >
921 <rect x="6" y="6" width="12" height="12" />
922 </svg>
923 <span class="xl:hidden">Stop</span>
924 </button>
925 <button
926 id="endButton"
927 class="bg-gray-600 hover:bg-gray-700 disabled:bg-gray-400 disabled:cursor-not-allowed disabled:opacity-70 text-white border-none px-2.5 py-1 xl:px-1.5 rounded cursor-pointer text-xs mr-1.5 flex items-center gap-1.5 transition-colors"
928 @click=${this._handleEndClick}
929 >
930 <svg
931 class="w-4 h-4"
932 xmlns="http://www.w3.org/2000/svg"
933 viewBox="0 0 24 24"
934 fill="none"
935 stroke="currentColor"
936 stroke-width="2"
937 stroke-linecap="round"
938 stroke-linejoin="round"
939 >
940 <path d="M18 6L6 18" />
941 <path d="M6 6l12 12" />
942 </svg>
943 <span class="xl:hidden">End</span>
944 </button>
945
946 <div
947 class="flex items-center text-xs mr-2.5 cursor-pointer"
948 @click=${this._handleNotificationsToggle}
949 title="${this.notificationsEnabled
950 ? "Disable"
951 : "Enable"} notifications when the agent completes its turn"
952 >
953 <div
954 class="w-5 h-5 relative inline-flex items-center justify-center"
955 >
956 <!-- Bell SVG icon -->
957 <svg
958 xmlns="http://www.w3.org/2000/svg"
959 width="16"
960 height="16"
961 fill="currentColor"
962 viewBox="0 0 16 16"
963 class="${!this.notificationsEnabled ? "relative z-10" : ""}"
964 >
965 <path
966 d="M8 16a2 2 0 0 0 2-2H6a2 2 0 0 0 2 2zM8 1.918l-.797.161A4.002 4.002 0 0 0 4 6c0 .628-.134 2.197-.459 3.742-.16.767-.376 1.566-.663 2.258h10.244c-.287-.692-.502-1.49-.663-2.258C12.134 8.197 12 6.628 12 6a4.002 4.002 0 0 0-3.203-3.92L8 1.917zM14.22 12c.223.447.481.801.78 1H1c.299-.199.557-.553.78-1C2.68 10.2 3 6.88 3 6c0-2.42 1.72-4.44 4.005-4.901a1 1 0 1 1 1.99 0A5.002 5.002 0 0 1 13 6c0 .88.32 4.2 1.22 6z"
967 />
968 </svg>
969 ${!this.notificationsEnabled
970 ? html`<div
971 class="absolute w-0.5 h-6 bg-red-600 rotate-45 origin-center"
972 ></div>`
973 : ""}
974 </div>
975 </div>
976
977 <sketch-call-status
978 .agentState=${this.containerState?.agent_state}
979 .llmCalls=${this.containerState?.outstanding_llm_calls || 0}
980 .toolCalls=${this.containerState?.outstanding_tool_calls || []}
981 .isIdle=${(() => {
982 const lastUserOrAgentMessage = this.getLastUserOrAgentMessage();
983 return lastUserOrAgentMessage
984 ? lastUserOrAgentMessage.end_of_turn &&
985 !lastUserOrAgentMessage.parent_conversation_id
986 : true;
987 })()}
988 .isDisconnected=${this.connectionStatus === "disconnected"}
989 ></sketch-call-status>
990
991 <sketch-network-status
992 connection=${this.connectionStatus}
993 error=${this.connectionErrorMessage}
994 ></sketch-network-status>
995 </div>
996 </div>
997 `;
998 }
999
1000 protected renderMainViews() {
1001 return html`
1002 <!-- Chat View -->
1003 <div
1004 class="chat-view ${this.viewMode === "chat"
1005 ? "view-active flex flex-col"
1006 : "hidden"} w-full h-full"
1007 >
1008 <div
1009 class="${this._todoPanelVisible && this.viewMode === "chat"
1010 ? "mr-[400px] xl:mr-[350px] lg:mr-[300px] md:mr-0 w-[calc(100%-400px)] xl:w-[calc(100%-350px)] lg:w-[calc(100%-300px)] md:w-full"
1011 : "mr-0"} flex-1 flex flex-col w-full h-full transition-[margin-right] duration-200 ease-in-out"
1012 >
1013 <sketch-timeline
1014 .messages=${this.messages}
1015 .scrollContainer=${this.scrollContainerRef}
1016 .agentState=${this.containerState?.agent_state}
1017 .llmCalls=${this.containerState?.outstanding_llm_calls || 0}
1018 .toolCalls=${this.containerState?.outstanding_tool_calls || []}
1019 .firstMessageIndex=${this.containerState?.first_message_index || 0}
1020 .state=${this.containerState}
1021 .dataManager=${this.dataManager}
1022 ></sketch-timeline>
1023 </div>
1024 </div>
1025
1026 <!-- Todo panel positioned outside the main flow - only visible in chat view -->
1027 <div
1028 class="${this._todoPanelVisible && this.viewMode === "chat"
1029 ? "block"
1030 : "hidden"} fixed top-12 right-4 w-[400px] xl:w-[350px] lg:w-[300px] md:hidden z-[100] transition-[bottom] duration-200 ease-in-out"
1031 style="bottom: var(--chat-input-height, 90px); background: linear-gradient(to bottom, #fafafa 0%, #fafafa 90%, rgba(250, 250, 250, 0.5) 95%, rgba(250, 250, 250, 0.2) 100%); border-left: 1px solid #e0e0e0;"
1032 >
1033 <sketch-todo-panel
1034 .visible=${this._todoPanelVisible && this.viewMode === "chat"}
1035 ></sketch-todo-panel>
1036 </div>
1037 <!-- Diff2 View -->
1038 <div
1039 class="diff2-view ${this.viewMode === "diff2"
1040 ? "view-active flex-1 overflow-hidden min-h-0 flex flex-col h-full"
1041 : "hidden"} w-full h-full"
1042 >
1043 <sketch-diff2-view
1044 .commit=${this.currentCommitHash}
1045 .gitService=${new DefaultGitDataService()}
1046 @diff-comment="${this._handleDiffComment}"
1047 ></sketch-diff2-view>
1048 </div>
1049
1050 <!-- Terminal View -->
1051 <div
1052 class="terminal-view ${this.viewMode === "terminal"
1053 ? "view-active flex flex-col"
1054 : "hidden"} w-full h-full"
1055 >
1056 <sketch-terminal></sketch-terminal>
1057 </div>
1058 `;
1059 }
1060
1061 protected renderChatInput() {
1062 return html`
1063 <!-- Chat input fixed at bottom -->
1064 <div
1065 id="chat-input"
1066 class="self-end w-full shadow-[0_-2px_10px_rgba(0,0,0,0.1)]"
1067 >
1068 <sketch-chat-input @send-chat="${this._sendChat}"></sketch-chat-input>
1069 </div>
1070 `;
1071 }
1072
1073 /**
1074 * Lifecycle callback when component is first connected to DOM
1075 */
1076 firstUpdated(): void {
1077 if (this.viewMode !== "chat") {
1078 return;
1079 }
1080
1081 // Initial scroll to bottom when component is first rendered
1082 setTimeout(
1083 () => this.scrollTo({ top: this.scrollHeight, behavior: "smooth" }),
1084 50,
1085 );
1086
1087 // Setup stop button
1088 const stopButton = this.renderRoot?.querySelector(
1089 "#stopButton",
1090 ) as HTMLButtonElement;
1091 stopButton?.addEventListener("click", async () => {
1092 try {
1093 const response = await fetch("cancel", {
1094 method: "POST",
1095 headers: {
1096 "Content-Type": "application/json",
1097 },
1098 body: JSON.stringify({ reason: "User clicked stop button" }),
1099 });
1100 if (!response.ok) {
1101 console.error("Failed to cancel:", await response.text());
1102 }
1103 } catch (error) {
1104 console.error("Error cancelling operation:", error);
1105 }
1106 });
1107
1108 // Setup end button
1109 const endButton = this.renderRoot?.querySelector(
1110 "#endButton",
1111 ) as HTMLButtonElement;
1112 // We're already using the @click binding in the HTML, so manual event listener not needed here
1113
1114 // Process any existing messages to find commit information
1115 if (this.messages && this.messages.length > 0) {
1116 // Update last commit info via container status component
1117 if (this.containerStatusElement) {
1118 this.containerStatusElement.updateLastCommitInfo(this.messages);
1119 }
1120 }
1121
1122 // Set up chat input height observer for todo panel
1123 this.setupChatInputObserver();
1124 }
1125}
1126
1127// Export the ViewMode type for use in subclasses
1128export type { ViewMode };