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