blob: c9553b424722d09b9f0eb529d8370f73e17bc0a9 [file] [log] [blame]
Sean McCullough86b56862025-04-18 13:04:03 -07001import { css, html, LitElement } from "lit";
2import { customElement, property, state } from "lit/decorators.js";
Pokey Rule4097e532025-04-24 18:55:28 +01003import { ConnectionStatus, DataManager } from "../data";
Philip Zeyliger47b71c92025-04-30 15:43:39 +00004import { AgentMessage, GitCommit, State } from "../types";
Pokey Rulee2a8c2f2025-04-23 15:09:25 +01005import { aggregateAgentMessages } from "./aggregateAgentMessages";
Philip Zeyliger2d4c48f2025-05-02 23:35:03 +00006
Pokey Rule4097e532025-04-24 18:55:28 +01007import "./sketch-chat-input";
8import "./sketch-container-status";
9import "./sketch-diff-view";
10import { SketchDiffView } from "./sketch-diff-view";
11import "./sketch-network-status";
Philip Zeyliger99a9a022025-04-27 15:15:25 +000012import "./sketch-call-status";
Pokey Rule4097e532025-04-24 18:55:28 +010013import "./sketch-terminal";
14import "./sketch-timeline";
15import "./sketch-view-mode-select";
Philip Zeyliger2c4db092025-04-28 16:57:50 -070016import "./sketch-restart-modal";
Pokey Rule4097e532025-04-24 18:55:28 +010017
18import { createRef, ref } from "lit/directives/ref.js";
Sean McCullough485afc62025-04-28 14:28:39 -070019import { SketchChatInput } from "./sketch-chat-input";
Sean McCullough86b56862025-04-18 13:04:03 -070020
Philip Zeyliger2d4c48f2025-05-02 23:35:03 +000021type ViewMode = "chat" | "diff" | "terminal";
Sean McCullough86b56862025-04-18 13:04:03 -070022
23@customElement("sketch-app-shell")
24export class SketchAppShell extends LitElement {
Philip Zeyliger2d4c48f2025-05-02 23:35:03 +000025 // Current view mode (chat, diff, terminal)
Sean McCullough86b56862025-04-18 13:04:03 -070026 @state()
Philip Zeyliger2d4c48f2025-05-02 23:35:03 +000027 viewMode: "chat" | "diff" | "terminal" = "chat";
Sean McCullough86b56862025-04-18 13:04:03 -070028
29 // Current commit hash for diff view
30 @state()
31 currentCommitHash: string = "";
32
Philip Zeyliger47b71c92025-04-30 15:43:39 +000033 // Last commit information
34 @state()
Philip Zeyliger16fa8b42025-05-02 04:28:16 +000035
36 // Reference to the container status element
37 containerStatusElement: any = null;
Philip Zeyliger47b71c92025-04-30 15:43:39 +000038
Sean McCullough86b56862025-04-18 13:04:03 -070039 // See https://lit.dev/docs/components/styles/ for how lit-element handles CSS.
40 // Note that these styles only apply to the scope of this web component's
41 // shadow DOM node, so they won't leak out or collide with CSS declared in
42 // other components or the containing web page (...unless you want it to do that).
43 static styles = css`
Philip Zeyliger47b71c92025-04-30 15:43:39 +000044 .copied-indicator {
45 position: absolute;
46 top: -20px;
47 left: 50%;
48 transform: translateX(-50%);
49 background: rgba(40, 167, 69, 0.9);
50 color: white;
51 padding: 2px 6px;
52 border-radius: 3px;
53 font-size: 10px;
54 font-family: system-ui, sans-serif;
55 animation: fadeInOut 2s ease;
56 pointer-events: none;
57 }
Autoformattercf570962025-04-30 17:27:39 +000058
Philip Zeyliger47b71c92025-04-30 15:43:39 +000059 @keyframes fadeInOut {
Autoformattercf570962025-04-30 17:27:39 +000060 0% {
61 opacity: 0;
62 }
63 20% {
64 opacity: 1;
65 }
66 80% {
67 opacity: 1;
68 }
69 100% {
70 opacity: 0;
71 }
Philip Zeyliger47b71c92025-04-30 15:43:39 +000072 }
Autoformattercf570962025-04-30 17:27:39 +000073
Philip Zeyliger47b71c92025-04-30 15:43:39 +000074 .commit-branch-indicator {
75 color: #28a745;
76 }
Autoformattercf570962025-04-30 17:27:39 +000077
Philip Zeyliger47b71c92025-04-30 15:43:39 +000078 .commit-hash-indicator {
79 color: #0366d6;
80 }
Sean McCullough86b56862025-04-18 13:04:03 -070081 :host {
82 display: block;
Sean McCullough71941bd2025-04-18 13:31:48 -070083 font-family:
84 system-ui,
85 -apple-system,
86 BlinkMacSystemFont,
87 "Segoe UI",
88 Roboto,
89 sans-serif;
Sean McCullough86b56862025-04-18 13:04:03 -070090 color: #333;
91 line-height: 1.4;
Pokey Rule4097e532025-04-24 18:55:28 +010092 height: 100vh;
Sean McCullough86b56862025-04-18 13:04:03 -070093 width: 100%;
94 position: relative;
95 overflow-x: hidden;
Pokey Rule4097e532025-04-24 18:55:28 +010096 display: flex;
97 flex-direction: column;
Sean McCullough86b56862025-04-18 13:04:03 -070098 }
99
100 /* Top banner with combined elements */
Pokey Rule4097e532025-04-24 18:55:28 +0100101 #top-banner {
Sean McCullough86b56862025-04-18 13:04:03 -0700102 display: flex;
Philip Zeyligere66db3e2025-04-27 15:40:39 +0000103 align-self: stretch;
Sean McCullough86b56862025-04-18 13:04:03 -0700104 justify-content: space-between;
105 align-items: center;
Philip Zeyligere66db3e2025-04-27 15:40:39 +0000106 padding: 0 20px;
Sean McCullough86b56862025-04-18 13:04:03 -0700107 margin-bottom: 0;
108 border-bottom: 1px solid #eee;
Philip Zeyligere66db3e2025-04-27 15:40:39 +0000109 gap: 20px;
Sean McCullough86b56862025-04-18 13:04:03 -0700110 background: white;
Sean McCullough86b56862025-04-18 13:04:03 -0700111 box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
Philip Zeyligere66db3e2025-04-27 15:40:39 +0000112 width: 100%;
113 height: 48px;
114 padding-right: 30px; /* Extra padding on the right to prevent elements from hitting the edge */
Sean McCullough86b56862025-04-18 13:04:03 -0700115 }
116
Pokey Rule4097e532025-04-24 18:55:28 +0100117 /* View mode container styles - mirroring timeline.css structure */
118 #view-container {
119 align-self: stretch;
120 overflow-y: auto;
121 flex: 1;
122 }
123
124 #view-container-inner {
125 max-width: 1200px;
126 margin: 0 auto;
127 position: relative;
128 padding-bottom: 10px;
129 padding-top: 10px;
130 }
131
132 #chat-input {
133 align-self: flex-end;
134 width: 100%;
135 box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
136 }
137
Sean McCullough86b56862025-04-18 13:04:03 -0700138 .banner-title {
139 font-size: 18px;
140 font-weight: 600;
141 margin: 0;
142 min-width: 6em;
143 white-space: nowrap;
144 overflow: hidden;
145 text-overflow: ellipsis;
146 }
147
148 .chat-title {
149 margin: 0;
150 padding: 0;
151 color: rgba(82, 82, 82, 0.85);
Josh Bleecher Snydereb5166a2025-04-30 17:04:20 +0000152 font-size: 14px;
Sean McCullough86b56862025-04-18 13:04:03 -0700153 font-weight: normal;
154 font-style: italic;
155 white-space: nowrap;
156 overflow: hidden;
157 text-overflow: ellipsis;
158 }
159
Sean McCullough86b56862025-04-18 13:04:03 -0700160 /* Allow the container to expand to full width in diff mode */
Pokey Rule46fff972025-04-25 14:57:44 +0100161 #view-container-inner.diff-active {
Sean McCullough86b56862025-04-18 13:04:03 -0700162 max-width: 100%;
Pokey Rule46fff972025-04-25 14:57:44 +0100163 width: 100%;
Sean McCullough86b56862025-04-18 13:04:03 -0700164 }
165
166 /* Individual view styles */
167 .chat-view,
168 .diff-view,
Sean McCullough86b56862025-04-18 13:04:03 -0700169 .terminal-view {
170 display: none; /* Hidden by default */
171 width: 100%;
172 }
173
174 /* Active view styles - these will be applied via JavaScript */
175 .view-active {
176 display: flex;
177 flex-direction: column;
178 }
179
180 .title-container {
181 display: flex;
182 flex-direction: column;
183 white-space: nowrap;
184 overflow: hidden;
185 text-overflow: ellipsis;
Josh Bleecher Snydereb5166a2025-04-30 17:04:20 +0000186 max-width: 30%;
Philip Zeyligere66db3e2025-04-27 15:40:39 +0000187 padding: 6px 0;
Sean McCullough86b56862025-04-18 13:04:03 -0700188 }
189
190 .refresh-control {
191 display: flex;
192 align-items: center;
193 margin-bottom: 0;
194 flex-wrap: nowrap;
195 white-space: nowrap;
196 flex-shrink: 0;
Philip Zeyligere66db3e2025-04-27 15:40:39 +0000197 gap: 15px;
198 padding-left: 15px;
199 margin-right: 50px;
Sean McCullough86b56862025-04-18 13:04:03 -0700200 }
201
Philip Zeyligerbce3a132025-04-30 22:03:39 +0000202 .restart-button,
203 .stop-button {
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700204 background: #2196f3;
205 color: white;
206 border: none;
207 padding: 4px 10px;
208 border-radius: 4px;
209 cursor: pointer;
210 font-size: 12px;
211 margin-right: 5px;
Philip Zeyligerbce3a132025-04-30 22:03:39 +0000212 display: flex;
213 align-items: center;
214 gap: 6px;
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700215 }
216
217 .restart-button:hover {
218 background-color: #0b7dda;
219 }
220
221 .restart-button:disabled {
222 background-color: #ccc;
223 cursor: not-allowed;
224 opacity: 0.6;
225 }
226
Philip Zeyligerbce3a132025-04-30 22:03:39 +0000227 .stop-button {
228 background: #dc3545;
Sean McCullough86b56862025-04-18 13:04:03 -0700229 color: white;
Sean McCullough86b56862025-04-18 13:04:03 -0700230 }
231
Philip Zeyligerbce3a132025-04-30 22:03:39 +0000232 .stop-button:hover:not(:disabled) {
233 background-color: #c82333;
Sean McCullough86b56862025-04-18 13:04:03 -0700234 }
235
Philip Zeyligerbce3a132025-04-30 22:03:39 +0000236 .stop-button:disabled {
237 background-color: #e9a8ad;
238 cursor: not-allowed;
239 opacity: 0.7;
Philip Zeyligerdb5e9b42025-04-30 19:58:13 +0000240 }
241
Philip Zeyligerbce3a132025-04-30 22:03:39 +0000242 .stop-button:disabled:hover {
243 background-color: #e9a8ad;
244 }
245
246 .button-icon {
247 width: 16px;
248 height: 16px;
249 }
250
251 @media (max-width: 1400px) {
252 .button-text {
253 display: none;
254 }
255
256 .restart-button,
257 .stop-button {
258 padding: 6px;
259 }
260 }
261
262 /* Removed poll-updates class */
263
Philip Zeyligerbc6b6292025-04-30 18:00:15 +0000264 .notifications-toggle {
Sean McCullough86b56862025-04-18 13:04:03 -0700265 display: flex;
266 align-items: center;
Sean McCullough86b56862025-04-18 13:04:03 -0700267 font-size: 12px;
Philip Zeyligerbc6b6292025-04-30 18:00:15 +0000268 margin-right: 10px;
Philip Zeyligerdb5e9b42025-04-30 19:58:13 +0000269 cursor: pointer;
270 }
271
272 .bell-icon {
273 width: 20px;
274 height: 20px;
275 position: relative;
276 display: inline-flex;
277 align-items: center;
278 justify-content: center;
279 }
280
281 .bell-disabled::before {
282 content: "";
283 position: absolute;
284 width: 2px;
285 height: 24px;
286 background-color: #dc3545;
287 transform: rotate(45deg);
288 transform-origin: center center;
Sean McCullough86b56862025-04-18 13:04:03 -0700289 }
290 `;
291
292 // Header bar: Network connection status details
293 @property()
294 connectionStatus: ConnectionStatus = "disconnected";
Autoformattercf570962025-04-30 17:27:39 +0000295
Philip Zeyliger47b71c92025-04-30 15:43:39 +0000296 // Track if the last commit info has been copied
297 @state()
Philip Zeyliger16fa8b42025-05-02 04:28:16 +0000298 // lastCommitCopied moved to sketch-container-status
Sean McCullough86b56862025-04-18 13:04:03 -0700299
Philip Zeyligerbc6b6292025-04-30 18:00:15 +0000300 // Track notification preferences
301 @state()
Philip Zeyligerdb5e9b42025-04-30 19:58:13 +0000302 notificationsEnabled: boolean = false;
303
304 // Track if the window is focused to control notifications
305 @state()
306 private _windowFocused: boolean = document.hasFocus();
Philip Zeyligerbc6b6292025-04-30 18:00:15 +0000307
Sean McCullough86b56862025-04-18 13:04:03 -0700308 @property()
309 connectionErrorMessage: string = "";
310
Sean McCullough86b56862025-04-18 13:04:03 -0700311 // Chat messages
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100312 @property({ attribute: false })
Sean McCulloughd9f13372025-04-21 15:08:49 -0700313 messages: AgentMessage[] = [];
Sean McCullough86b56862025-04-18 13:04:03 -0700314
315 @property()
Philip Zeyliger9b999b02025-04-25 16:31:50 +0000316 set title(value: string) {
317 const oldValue = this._title;
318 this._title = value;
319 this.requestUpdate("title", oldValue);
320 // Update document title when title property changes
321 this.updateDocumentTitle();
322 }
323
324 get title(): string {
325 return this._title;
326 }
327
328 private _title: string = "";
Sean McCullough86b56862025-04-18 13:04:03 -0700329
330 private dataManager = new DataManager();
331
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100332 @property({ attribute: false })
Sean McCulloughd9f13372025-04-21 15:08:49 -0700333 containerState: State = {
334 title: "",
335 os: "",
336 message_count: 0,
337 hostname: "",
338 working_dir: "",
339 initial_commit: "",
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000340 outstanding_llm_calls: 0,
341 outstanding_tool_calls: [],
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000342 session_id: "",
343 ssh_available: false,
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700344 ssh_error: "",
345 in_container: false,
346 first_message_index: 0,
Sean McCulloughd9f13372025-04-21 15:08:49 -0700347 };
Sean McCullough86b56862025-04-18 13:04:03 -0700348
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700349 @state()
350 private restartModalOpen = false;
351
Sean McCullough86b56862025-04-18 13:04:03 -0700352 // Mutation observer to detect when new messages are added
353 private mutationObserver: MutationObserver | null = null;
354
355 constructor() {
356 super();
357
Philip Zeyliger16fa8b42025-05-02 04:28:16 +0000358 // Reference to the container status element
359 this.containerStatusElement = null;
360
Sean McCullough86b56862025-04-18 13:04:03 -0700361 // Binding methods to this
362 this._handleViewModeSelect = this._handleViewModeSelect.bind(this);
Sean McCullough86b56862025-04-18 13:04:03 -0700363 this._handleShowCommitDiff = this._handleShowCommitDiff.bind(this);
Sean McCullough485afc62025-04-28 14:28:39 -0700364 this._handleMutlipleChoiceSelected =
365 this._handleMutlipleChoiceSelected.bind(this);
Sean McCulloughd3906e22025-04-29 17:32:14 +0000366 this._handleStopClick = this._handleStopClick.bind(this);
Philip Zeyligerbc6b6292025-04-30 18:00:15 +0000367 this._handleNotificationsToggle =
368 this._handleNotificationsToggle.bind(this);
Philip Zeyligerdb5e9b42025-04-30 19:58:13 +0000369 this._handleWindowFocus = this._handleWindowFocus.bind(this);
370 this._handleWindowBlur = this._handleWindowBlur.bind(this);
Philip Zeyligerbc6b6292025-04-30 18:00:15 +0000371
372 // Load notification preference from localStorage
373 try {
374 const savedPref = localStorage.getItem("sketch-notifications-enabled");
375 if (savedPref !== null) {
376 this.notificationsEnabled = savedPref === "true";
377 }
378 } catch (error) {
379 console.error("Error loading notification preference:", error);
380 }
Sean McCullough86b56862025-04-18 13:04:03 -0700381 }
382
383 // See https://lit.dev/docs/components/lifecycle/
384 connectedCallback() {
385 super.connectedCallback();
386
Philip Zeyliger16fa8b42025-05-02 04:28:16 +0000387 // Get reference to the container status element
388 setTimeout(() => {
389 this.containerStatusElement =
390 this.shadowRoot?.getElementById("container-status");
391 }, 0);
392
Sean McCullough86b56862025-04-18 13:04:03 -0700393 // Initialize client-side nav history.
394 const url = new URL(window.location.href);
395 const mode = url.searchParams.get("view") || "chat";
396 window.history.replaceState({ mode }, "", url.toString());
397
398 this.toggleViewMode(mode as ViewMode, false);
399 // Add popstate event listener to handle browser back/forward navigation
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100400 window.addEventListener("popstate", this._handlePopState);
Sean McCullough86b56862025-04-18 13:04:03 -0700401
402 // Add event listeners
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100403 window.addEventListener("view-mode-select", this._handleViewModeSelect);
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100404 window.addEventListener("show-commit-diff", this._handleShowCommitDiff);
Sean McCullough86b56862025-04-18 13:04:03 -0700405
Philip Zeyligerdb5e9b42025-04-30 19:58:13 +0000406 // Add window focus/blur listeners for controlling notifications
407 window.addEventListener("focus", this._handleWindowFocus);
408 window.addEventListener("blur", this._handleWindowBlur);
Sean McCullough485afc62025-04-28 14:28:39 -0700409 window.addEventListener(
410 "multiple-choice-selected",
411 this._handleMutlipleChoiceSelected,
412 );
Philip Zeyligerdb5e9b42025-04-30 19:58:13 +0000413
Sean McCullough86b56862025-04-18 13:04:03 -0700414 // register event listeners
415 this.dataManager.addEventListener(
416 "dataChanged",
Philip Zeyliger72682df2025-04-23 13:09:46 -0700417 this.handleDataChanged.bind(this),
Sean McCullough86b56862025-04-18 13:04:03 -0700418 );
419 this.dataManager.addEventListener(
420 "connectionStatusChanged",
Philip Zeyliger72682df2025-04-23 13:09:46 -0700421 this.handleConnectionStatusChanged.bind(this),
Sean McCullough86b56862025-04-18 13:04:03 -0700422 );
423
Philip Zeyliger9b999b02025-04-25 16:31:50 +0000424 // Set initial document title
425 this.updateDocumentTitle();
426
Sean McCullough86b56862025-04-18 13:04:03 -0700427 // Initialize the data manager
428 this.dataManager.initialize();
Autoformattercf570962025-04-30 17:27:39 +0000429
Philip Zeyliger47b71c92025-04-30 15:43:39 +0000430 // Process existing messages for commit info
431 if (this.messages && this.messages.length > 0) {
Philip Zeyliger16fa8b42025-05-02 04:28:16 +0000432 // Update last commit info via container status component
433 setTimeout(() => {
434 if (this.containerStatusElement) {
435 this.containerStatusElement.updateLastCommitInfo(this.messages);
436 }
437 }, 100);
Philip Zeyliger47b71c92025-04-30 15:43:39 +0000438 }
Sean McCullough86b56862025-04-18 13:04:03 -0700439 }
440
441 // See https://lit.dev/docs/components/lifecycle/
442 disconnectedCallback() {
443 super.disconnectedCallback();
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100444 window.removeEventListener("popstate", this._handlePopState);
Sean McCullough86b56862025-04-18 13:04:03 -0700445
446 // Remove event listeners
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100447 window.removeEventListener("view-mode-select", this._handleViewModeSelect);
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100448 window.removeEventListener("show-commit-diff", this._handleShowCommitDiff);
Philip Zeyligerdb5e9b42025-04-30 19:58:13 +0000449 window.removeEventListener("focus", this._handleWindowFocus);
450 window.removeEventListener("blur", this._handleWindowBlur);
Sean McCullough485afc62025-04-28 14:28:39 -0700451 window.removeEventListener(
452 "multiple-choice-selected",
453 this._handleMutlipleChoiceSelected,
454 );
Sean McCullough86b56862025-04-18 13:04:03 -0700455
456 // unregister data manager event listeners
457 this.dataManager.removeEventListener(
458 "dataChanged",
Philip Zeyliger72682df2025-04-23 13:09:46 -0700459 this.handleDataChanged.bind(this),
Sean McCullough86b56862025-04-18 13:04:03 -0700460 );
461 this.dataManager.removeEventListener(
462 "connectionStatusChanged",
Philip Zeyliger72682df2025-04-23 13:09:46 -0700463 this.handleConnectionStatusChanged.bind(this),
Sean McCullough86b56862025-04-18 13:04:03 -0700464 );
465
466 // Disconnect mutation observer if it exists
467 if (this.mutationObserver) {
Sean McCullough86b56862025-04-18 13:04:03 -0700468 this.mutationObserver.disconnect();
469 this.mutationObserver = null;
470 }
471 }
472
Philip Zeyliger2d4c48f2025-05-02 23:35:03 +0000473 updateUrlForViewMode(mode: "chat" | "diff" | "terminal"): void {
Sean McCullough86b56862025-04-18 13:04:03 -0700474 // Get the current URL without search parameters
475 const url = new URL(window.location.href);
476
477 // Clear existing parameters
478 url.search = "";
479
480 // Only add view parameter if not in default chat view
481 if (mode !== "chat") {
482 url.searchParams.set("view", mode);
Sean McCullough71941bd2025-04-18 13:31:48 -0700483 const diffView = this.shadowRoot?.querySelector(
Philip Zeyliger72682df2025-04-23 13:09:46 -0700484 ".diff-view",
Sean McCullough71941bd2025-04-18 13:31:48 -0700485 ) as SketchDiffView;
Sean McCullough86b56862025-04-18 13:04:03 -0700486
487 // If in diff view and there's a commit hash, include that too
488 if (mode === "diff" && diffView.commitHash) {
489 url.searchParams.set("commit", diffView.commitHash);
490 }
491 }
492
493 // Update the browser history without reloading the page
494 window.history.pushState({ mode }, "", url.toString());
495 }
496
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100497 private _handlePopState(event: PopStateEvent) {
Sean McCullough86b56862025-04-18 13:04:03 -0700498 if (event.state && event.state.mode) {
499 this.toggleViewMode(event.state.mode, false);
500 } else {
501 this.toggleViewMode("chat", false);
502 }
503 }
504
505 /**
506 * Handle view mode selection event
507 */
508 private _handleViewModeSelect(event: CustomEvent) {
Philip Zeyliger2d4c48f2025-05-02 23:35:03 +0000509 const mode = event.detail.mode as "chat" | "diff" | "terminal";
Sean McCullough86b56862025-04-18 13:04:03 -0700510 this.toggleViewMode(mode, true);
511 }
512
513 /**
514 * Handle show commit diff event
515 */
516 private _handleShowCommitDiff(event: CustomEvent) {
517 const { commitHash } = event.detail;
518 if (commitHash) {
519 this.showCommitDiff(commitHash);
520 }
521 }
522
Sean McCullough485afc62025-04-28 14:28:39 -0700523 private _handleMultipleChoice(event: CustomEvent) {
524 window.console.log("_handleMultipleChoice", event);
525 this._sendChat;
526 }
Sean McCullough86b56862025-04-18 13:04:03 -0700527 /**
Sean McCullough86b56862025-04-18 13:04:03 -0700528 * Listen for commit diff event
529 * @param commitHash The commit hash to show diff for
530 */
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100531 private showCommitDiff(commitHash: string): void {
Sean McCullough86b56862025-04-18 13:04:03 -0700532 // Store the commit hash
533 this.currentCommitHash = commitHash;
534
535 // Switch to diff view
Sean McCullough71941bd2025-04-18 13:31:48 -0700536 this.toggleViewMode("diff", true);
Sean McCullough86b56862025-04-18 13:04:03 -0700537
538 // Wait for DOM update to complete
539 this.updateComplete.then(() => {
540 // Get the diff view component
541 const diffView = this.shadowRoot?.querySelector("sketch-diff-view");
542 if (diffView) {
543 // Call the showCommitDiff method
544 (diffView as any).showCommitDiff(commitHash);
545 }
546 });
547 }
548
549 /**
Philip Zeyliger2d4c48f2025-05-02 23:35:03 +0000550 * Toggle between different view modes: chat, diff, terminal
Sean McCullough86b56862025-04-18 13:04:03 -0700551 */
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100552 private toggleViewMode(mode: ViewMode, updateHistory: boolean): void {
Sean McCullough86b56862025-04-18 13:04:03 -0700553 // Don't do anything if the mode is already active
554 if (this.viewMode === mode) return;
555
556 // Update the view mode
557 this.viewMode = mode;
558
559 if (updateHistory) {
560 // Update URL with the current view mode
561 this.updateUrlForViewMode(mode);
562 }
563
564 // Wait for DOM update to complete
565 this.updateComplete.then(() => {
566 // Update active view
Pokey Rule46fff972025-04-25 14:57:44 +0100567 const viewContainerInner = this.shadowRoot?.querySelector(
568 "#view-container-inner",
569 );
Sean McCullough86b56862025-04-18 13:04:03 -0700570 const chatView = this.shadowRoot?.querySelector(".chat-view");
571 const diffView = this.shadowRoot?.querySelector(".diff-view");
Philip Zeyliger2d4c48f2025-05-02 23:35:03 +0000572
Sean McCullough86b56862025-04-18 13:04:03 -0700573 const terminalView = this.shadowRoot?.querySelector(".terminal-view");
574
575 // Remove active class from all views
576 chatView?.classList.remove("view-active");
577 diffView?.classList.remove("view-active");
Sean McCullough86b56862025-04-18 13:04:03 -0700578 terminalView?.classList.remove("view-active");
579
580 // Add/remove diff-active class on view container
581 if (mode === "diff") {
Pokey Rule46fff972025-04-25 14:57:44 +0100582 viewContainerInner?.classList.add("diff-active");
Sean McCullough86b56862025-04-18 13:04:03 -0700583 } else {
Pokey Rule46fff972025-04-25 14:57:44 +0100584 viewContainerInner?.classList.remove("diff-active");
Sean McCullough86b56862025-04-18 13:04:03 -0700585 }
586
587 // Add active class to the selected view
588 switch (mode) {
589 case "chat":
590 chatView?.classList.add("view-active");
591 break;
592 case "diff":
593 diffView?.classList.add("view-active");
594 // Load diff content if we have a diff view
595 const diffViewComp =
596 this.shadowRoot?.querySelector("sketch-diff-view");
597 if (diffViewComp && this.currentCommitHash) {
598 (diffViewComp as any).showCommitDiff(this.currentCommitHash);
599 } else if (diffViewComp) {
600 (diffViewComp as any).loadDiffContent();
601 }
602 break;
Philip Zeyliger2d4c48f2025-05-02 23:35:03 +0000603
Sean McCullough86b56862025-04-18 13:04:03 -0700604 case "terminal":
605 terminalView?.classList.add("view-active");
606 break;
607 }
608
609 // Update view mode buttons
610 const viewModeSelect = this.shadowRoot?.querySelector(
Philip Zeyliger72682df2025-04-23 13:09:46 -0700611 "sketch-view-mode-select",
Sean McCullough86b56862025-04-18 13:04:03 -0700612 );
613 if (viewModeSelect) {
614 const event = new CustomEvent("update-active-mode", {
615 detail: { mode },
616 bubbles: true,
617 composed: true,
618 });
619 viewModeSelect.dispatchEvent(event);
620 }
Sean McCullough86b56862025-04-18 13:04:03 -0700621 });
622 }
623
Philip Zeyliger9b999b02025-04-25 16:31:50 +0000624 /**
625 * Updates the document title based on current title and connection status
626 */
627 private updateDocumentTitle(): void {
628 let docTitle = `sk: ${this.title || "untitled"}`;
629
630 // Add red circle emoji if disconnected
631 if (this.connectionStatus === "disconnected") {
632 docTitle += " 🔴";
633 }
634
635 document.title = docTitle;
636 }
637
Philip Zeyligerbc6b6292025-04-30 18:00:15 +0000638 // Check and request notification permission if needed
639 private async checkNotificationPermission(): Promise<boolean> {
640 // Check if the Notification API is supported
641 if (!("Notification" in window)) {
642 console.log("This browser does not support notifications");
643 return false;
644 }
645
646 // Check if permission is already granted
647 if (Notification.permission === "granted") {
648 return true;
649 }
650
651 // If permission is not denied, request it
652 if (Notification.permission !== "denied") {
653 const permission = await Notification.requestPermission();
654 return permission === "granted";
655 }
656
657 return false;
658 }
659
Philip Zeyligerdb5e9b42025-04-30 19:58:13 +0000660 // Handle notifications toggle click
661 private _handleNotificationsToggle(): void {
662 this.notificationsEnabled = !this.notificationsEnabled;
Philip Zeyligerbc6b6292025-04-30 18:00:15 +0000663
664 // If enabling notifications, check permissions
665 if (this.notificationsEnabled) {
666 this.checkNotificationPermission();
667 }
668
669 // Save preference to localStorage
670 try {
671 localStorage.setItem(
672 "sketch-notifications-enabled",
673 String(this.notificationsEnabled),
674 );
675 } catch (error) {
676 console.error("Error saving notification preference:", error);
677 }
678 }
679
Philip Zeyligerdb5e9b42025-04-30 19:58:13 +0000680 // Handle window focus event
681 private _handleWindowFocus(): void {
682 this._windowFocused = true;
683 }
684
685 // Handle window blur event
686 private _handleWindowBlur(): void {
687 this._windowFocused = false;
688 }
689
Philip Zeyligerbc6b6292025-04-30 18:00:15 +0000690 // Show notification for message with EndOfTurn=true
691 private async showEndOfTurnNotification(
692 message: AgentMessage,
693 ): Promise<void> {
694 // Don't show notifications if they're disabled
695 if (!this.notificationsEnabled) return;
696
Philip Zeyligerdb5e9b42025-04-30 19:58:13 +0000697 // Don't show notifications if the window is focused
698 if (this._windowFocused) return;
699
Philip Zeyligerbc6b6292025-04-30 18:00:15 +0000700 // Check if we have permission to show notifications
701 const hasPermission = await this.checkNotificationPermission();
702 if (!hasPermission) return;
703
Philip Zeyliger32011332025-04-30 20:59:40 +0000704 // Only show notifications for agent messages with end_of_turn=true and no parent_conversation_id
705 if (
706 message.type !== "agent" ||
707 !message.end_of_turn ||
708 message.parent_conversation_id
709 )
710 return;
Philip Zeyligerbc6b6292025-04-30 18:00:15 +0000711
712 // Create a title that includes the sketch title
713 const notificationTitle = `Sketch: ${this.title || "untitled"}`;
714
715 // Extract the beginning of the message content (first 100 chars)
716 const messagePreview = message.content
717 ? message.content.substring(0, 100) +
718 (message.content.length > 100 ? "..." : "")
719 : "Agent has completed its turn";
720
721 // Create and show the notification
722 try {
723 new Notification(notificationTitle, {
724 body: messagePreview,
Philip Zeyligerdb5e9b42025-04-30 19:58:13 +0000725 icon: "https://sketch.dev/favicon.ico", // Use sketch.dev favicon for notification
Philip Zeyligerbc6b6292025-04-30 18:00:15 +0000726 });
727 } catch (error) {
728 console.error("Error showing notification:", error);
729 }
730 }
731
Sean McCullough86b56862025-04-18 13:04:03 -0700732 private handleDataChanged(eventData: {
733 state: State;
Sean McCulloughd9f13372025-04-21 15:08:49 -0700734 newMessages: AgentMessage[];
Sean McCullough86b56862025-04-18 13:04:03 -0700735 }): void {
Philip Zeyligerbce3a132025-04-30 22:03:39 +0000736 const { state, newMessages } = eventData;
Sean McCullough86b56862025-04-18 13:04:03 -0700737
738 // Update state if we received it
739 if (state) {
Josh Bleecher Snydere81233f2025-04-30 04:05:41 +0000740 // Ensure we're using the latest call status to prevent indicators from being stuck
Autoformatterf830c9d2025-04-30 18:16:01 +0000741 if (
742 state.outstanding_llm_calls === 0 &&
743 state.outstanding_tool_calls.length === 0
744 ) {
Josh Bleecher Snydere81233f2025-04-30 04:05:41 +0000745 // Force reset containerState calls when nothing is reported as in progress
746 state.outstanding_llm_calls = 0;
747 state.outstanding_tool_calls = [];
748 }
Autoformatterf830c9d2025-04-30 18:16:01 +0000749
Sean McCullough86b56862025-04-18 13:04:03 -0700750 this.containerState = state;
751 this.title = state.title;
Philip Zeyliger9b999b02025-04-25 16:31:50 +0000752
753 // Update document title when sketch title changes
754 this.updateDocumentTitle();
Sean McCullough86b56862025-04-18 13:04:03 -0700755 }
756
Sean McCullough86b56862025-04-18 13:04:03 -0700757 // Update messages
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100758 this.messages = aggregateAgentMessages(this.messages, newMessages);
Autoformattercf570962025-04-30 17:27:39 +0000759
Philip Zeyliger47b71c92025-04-30 15:43:39 +0000760 // Process new messages to find commit messages
Philip Zeyliger16fa8b42025-05-02 04:28:16 +0000761 // Update last commit info via container status component
762 if (this.containerStatusElement) {
763 this.containerStatusElement.updateLastCommitInfo(newMessages);
764 }
Philip Zeyligerbc6b6292025-04-30 18:00:15 +0000765
766 // Check for agent messages with end_of_turn=true and show notifications
Philip Zeyligerbce3a132025-04-30 22:03:39 +0000767 if (newMessages && newMessages.length > 0) {
Philip Zeyligerbc6b6292025-04-30 18:00:15 +0000768 for (const message of newMessages) {
Philip Zeyliger32011332025-04-30 20:59:40 +0000769 if (
770 message.type === "agent" &&
771 message.end_of_turn &&
772 !message.parent_conversation_id
773 ) {
Philip Zeyligerbc6b6292025-04-30 18:00:15 +0000774 this.showEndOfTurnNotification(message);
775 break; // Only show one notification per batch of messages
776 }
777 }
778 }
Sean McCullough86b56862025-04-18 13:04:03 -0700779 }
780
781 private handleConnectionStatusChanged(
782 status: ConnectionStatus,
Philip Zeyliger72682df2025-04-23 13:09:46 -0700783 errorMessage?: string,
Sean McCullough86b56862025-04-18 13:04:03 -0700784 ): void {
785 this.connectionStatus = status;
786 this.connectionErrorMessage = errorMessage || "";
Philip Zeyliger9b999b02025-04-25 16:31:50 +0000787
788 // Update document title when connection status changes
789 this.updateDocumentTitle();
Sean McCullough86b56862025-04-18 13:04:03 -0700790 }
791
Sean McCulloughd3906e22025-04-29 17:32:14 +0000792 private async _handleStopClick(): Promise<void> {
793 try {
794 const response = await fetch("cancel", {
795 method: "POST",
796 headers: {
797 "Content-Type": "application/json",
798 },
799 body: JSON.stringify({ reason: "user requested cancellation" }),
800 });
801
802 if (!response.ok) {
803 const errorData = await response.text();
804 throw new Error(
805 `Failed to stop operation: ${response.status} - ${errorData}`,
806 );
807 }
808
Philip Zeyligerbce3a132025-04-30 22:03:39 +0000809 // Stop request sent
Sean McCulloughd3906e22025-04-29 17:32:14 +0000810 } catch (error) {
811 console.error("Error stopping operation:", error);
Sean McCulloughd3906e22025-04-29 17:32:14 +0000812 }
813 }
814
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700815 openRestartModal() {
816 this.restartModalOpen = true;
817 }
818
819 handleRestartModalClose() {
820 this.restartModalOpen = false;
821 }
822
Sean McCullough485afc62025-04-28 14:28:39 -0700823 async _handleMutlipleChoiceSelected(e: CustomEvent) {
824 const chatInput = this.shadowRoot?.querySelector(
825 "sketch-chat-input",
826 ) as SketchChatInput;
827 if (chatInput) {
828 chatInput.content = e.detail.responseText;
829 chatInput.focus();
830 }
831 }
832
Sean McCullough86b56862025-04-18 13:04:03 -0700833 async _sendChat(e: CustomEvent) {
834 console.log("app shell: _sendChat", e);
Sean McCullough485afc62025-04-28 14:28:39 -0700835 e.preventDefault();
836 e.stopPropagation();
Sean McCullough86b56862025-04-18 13:04:03 -0700837 const message = e.detail.message?.trim();
838 if (message == "") {
839 return;
840 }
841 try {
842 // Send the message to the server
843 const response = await fetch("chat", {
844 method: "POST",
845 headers: {
846 "Content-Type": "application/json",
847 },
848 body: JSON.stringify({ message }),
849 });
850
851 if (!response.ok) {
852 const errorData = await response.text();
853 throw new Error(`Server error: ${response.status} - ${errorData}`);
854 }
Sean McCullough86b56862025-04-18 13:04:03 -0700855 } catch (error) {
856 console.error("Error sending chat message:", error);
857 const statusText = document.getElementById("statusText");
858 if (statusText) {
859 statusText.textContent = "Error sending message";
860 }
861 }
862 }
863
Pokey Rule4097e532025-04-24 18:55:28 +0100864 private scrollContainerRef = createRef<HTMLElement>();
865
Sean McCullough86b56862025-04-18 13:04:03 -0700866 render() {
867 return html`
Pokey Rule4097e532025-04-24 18:55:28 +0100868 <div id="top-banner">
Sean McCullough86b56862025-04-18 13:04:03 -0700869 <div class="title-container">
870 <h1 class="banner-title">sketch</h1>
871 <h2 id="chatTitle" class="chat-title">${this.title}</h2>
872 </div>
873
Philip Zeyligerbce3a132025-04-30 22:03:39 +0000874 <!-- Container status info moved above tabs -->
Sean McCullough86b56862025-04-18 13:04:03 -0700875 <sketch-container-status
876 .state=${this.containerState}
Philip Zeyliger16fa8b42025-05-02 04:28:16 +0000877 id="container-status"
Sean McCullough86b56862025-04-18 13:04:03 -0700878 ></sketch-container-status>
Autoformattercf570962025-04-30 17:27:39 +0000879
Philip Zeyliger16fa8b42025-05-02 04:28:16 +0000880 <!-- Last Commit section moved to sketch-container-status -->
Philip Zeyligerbce3a132025-04-30 22:03:39 +0000881
Philip Zeyliger16fa8b42025-05-02 04:28:16 +0000882 <!-- Views section with tabs -->
883 <sketch-view-mode-select></sketch-view-mode-select>
Sean McCullough86b56862025-04-18 13:04:03 -0700884
885 <div class="refresh-control">
Sean McCulloughd3906e22025-04-29 17:32:14 +0000886 <button
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700887 id="restartButton"
888 class="restart-button"
889 ?disabled=${this.containerState.message_count === 0}
890 @click=${this.openRestartModal}
Sean McCulloughd3906e22025-04-29 17:32:14 +0000891 >
Philip Zeyligerbce3a132025-04-30 22:03:39 +0000892 <svg
893 class="button-icon"
894 xmlns="http://www.w3.org/2000/svg"
895 viewBox="0 0 24 24"
896 fill="none"
897 stroke="currentColor"
898 stroke-width="2"
899 stroke-linecap="round"
900 stroke-linejoin="round"
901 >
902 <path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" />
903 <path d="M3 3v5h5" />
904 </svg>
905 <span class="button-text">Restart</span>
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700906 </button>
Philip Zeyligerbce3a132025-04-30 22:03:39 +0000907 <button
908 id="stopButton"
909 class="stop-button"
910 ?disabled=${(this.containerState?.outstanding_llm_calls || 0) ===
911 0 &&
912 (this.containerState?.outstanding_tool_calls || []).length === 0}
913 >
914 <svg
915 class="button-icon"
916 xmlns="http://www.w3.org/2000/svg"
917 viewBox="0 0 24 24"
918 fill="none"
919 stroke="currentColor"
920 stroke-width="2"
921 stroke-linecap="round"
922 stroke-linejoin="round"
923 >
924 <rect x="6" y="6" width="12" height="12" />
925 </svg>
926 <span class="button-text">Stop</span>
Sean McCullough86b56862025-04-18 13:04:03 -0700927 </button>
928
Philip Zeyligerdb5e9b42025-04-30 19:58:13 +0000929 <div
930 class="notifications-toggle"
931 @click=${this._handleNotificationsToggle}
932 title="${this.notificationsEnabled
933 ? "Disable"
Philip Zeyligerbce3a132025-04-30 22:03:39 +0000934 : "Enable"} notifications when the agent completes its turn"
Philip Zeyligerdb5e9b42025-04-30 19:58:13 +0000935 >
936 <div
937 class="bell-icon ${!this.notificationsEnabled
938 ? "bell-disabled"
939 : ""}"
940 >
941 <!-- Bell SVG icon -->
942 <svg
943 xmlns="http://www.w3.org/2000/svg"
944 width="16"
945 height="16"
946 fill="currentColor"
947 viewBox="0 0 16 16"
948 >
949 <path
950 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"
951 />
952 </svg>
953 </div>
Philip Zeyligerbc6b6292025-04-30 18:00:15 +0000954 </div>
955
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000956 <sketch-call-status
Sean McCulloughd9d45812025-04-30 16:53:41 -0700957 .agentState=${this.containerState?.agent_state}
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000958 .llmCalls=${this.containerState?.outstanding_llm_calls || 0}
959 .toolCalls=${this.containerState?.outstanding_tool_calls || []}
960 ></sketch-call-status>
Philip Zeyliger25f6ff12025-05-02 04:24:10 +0000961
962 <sketch-network-status
963 connection=${this.connectionStatus}
964 error=${this.connectionErrorMessage}
965 ></sketch-network-status>
Sean McCullough86b56862025-04-18 13:04:03 -0700966 </div>
967 </div>
968
Pokey Rule4097e532025-04-24 18:55:28 +0100969 <div id="view-container" ${ref(this.scrollContainerRef)}>
970 <div id="view-container-inner">
971 <div
972 class="chat-view ${this.viewMode === "chat" ? "view-active" : ""}"
973 >
974 <sketch-timeline
975 .messages=${this.messages}
976 .scrollContainer=${this.scrollContainerRef}
Philip Zeyliger16fa8b42025-05-02 04:28:16 +0000977 .agentState=${this.containerState?.agent_state}
978 .llmCalls=${this.containerState?.outstanding_llm_calls || 0}
979 .toolCalls=${this.containerState?.outstanding_tool_calls || []}
Pokey Rule4097e532025-04-24 18:55:28 +0100980 ></sketch-timeline>
981 </div>
982 <div
983 class="diff-view ${this.viewMode === "diff" ? "view-active" : ""}"
984 >
985 <sketch-diff-view
986 .commitHash=${this.currentCommitHash}
987 ></sketch-diff-view>
988 </div>
Philip Zeyliger2d4c48f2025-05-02 23:35:03 +0000989
Pokey Rule4097e532025-04-24 18:55:28 +0100990 <div
991 class="terminal-view ${this.viewMode === "terminal"
992 ? "view-active"
993 : ""}"
994 >
995 <sketch-terminal></sketch-terminal>
996 </div>
Sean McCullough86b56862025-04-18 13:04:03 -0700997 </div>
998 </div>
999
Pokey Rule4097e532025-04-24 18:55:28 +01001000 <div id="chat-input">
1001 <sketch-chat-input @send-chat="${this._sendChat}"></sketch-chat-input>
1002 </div>
Philip Zeyliger2c4db092025-04-28 16:57:50 -07001003
1004 <sketch-restart-modal
1005 ?open=${this.restartModalOpen}
1006 @close=${this.handleRestartModalClose}
1007 .containerState=${this.containerState}
1008 .messages=${this.messages}
1009 ></sketch-restart-modal>
Sean McCullough86b56862025-04-18 13:04:03 -07001010 `;
1011 }
1012
1013 /**
Sean McCullough86b56862025-04-18 13:04:03 -07001014 * Lifecycle callback when component is first connected to DOM
1015 */
1016 firstUpdated(): void {
1017 if (this.viewMode !== "chat") {
1018 return;
1019 }
1020
1021 // Initial scroll to bottom when component is first rendered
1022 setTimeout(
1023 () => this.scrollTo({ top: this.scrollHeight, behavior: "smooth" }),
Philip Zeyliger72682df2025-04-23 13:09:46 -07001024 50,
Sean McCullough86b56862025-04-18 13:04:03 -07001025 );
1026
Philip Zeyliger2c4db092025-04-28 16:57:50 -07001027 // Setup stop button
1028 const stopButton = this.renderRoot?.querySelector(
1029 "#stopButton",
1030 ) as HTMLButtonElement;
1031 stopButton?.addEventListener("click", async () => {
1032 try {
Sean McCullough495cb962025-05-01 16:25:53 -07001033 const response = await fetch("cancel", {
Philip Zeyliger2c4db092025-04-28 16:57:50 -07001034 method: "POST",
1035 headers: {
1036 "Content-Type": "application/json",
1037 },
1038 body: JSON.stringify({ reason: "User clicked stop button" }),
1039 });
1040 if (!response.ok) {
1041 console.error("Failed to cancel:", await response.text());
1042 }
1043 } catch (error) {
1044 console.error("Error cancelling operation:", error);
1045 }
1046 });
1047
Philip Zeyliger47b71c92025-04-30 15:43:39 +00001048 // Process any existing messages to find commit information
1049 if (this.messages && this.messages.length > 0) {
Philip Zeyliger16fa8b42025-05-02 04:28:16 +00001050 // Update last commit info via container status component
1051 if (this.containerStatusElement) {
1052 this.containerStatusElement.updateLastCommitInfo(this.messages);
1053 }
Philip Zeyliger47b71c92025-04-30 15:43:39 +00001054 }
Sean McCullough86b56862025-04-18 13:04:03 -07001055 }
1056}
1057
1058declare global {
1059 interface HTMLElementTagNameMap {
1060 "sketch-app-shell": SketchAppShell;
1061 }
1062}