blob: 0b58a10d5bfc3cd4c9eda4a0ae24cec1551e76d2 [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 = {
Philip Zeyligerd03318d2025-05-08 13:09:12 -0700334 state_version: 2,
Sean McCulloughd9f13372025-04-21 15:08:49 -0700335 title: "",
336 os: "",
337 message_count: 0,
338 hostname: "",
339 working_dir: "",
340 initial_commit: "",
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000341 outstanding_llm_calls: 0,
342 outstanding_tool_calls: [],
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000343 session_id: "",
344 ssh_available: false,
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700345 ssh_error: "",
346 in_container: false,
347 first_message_index: 0,
Sean McCulloughd9f13372025-04-21 15:08:49 -0700348 };
Sean McCullough86b56862025-04-18 13:04:03 -0700349
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700350 @state()
351 private restartModalOpen = false;
352
Sean McCullough86b56862025-04-18 13:04:03 -0700353 // Mutation observer to detect when new messages are added
354 private mutationObserver: MutationObserver | null = null;
355
356 constructor() {
357 super();
358
Philip Zeyliger16fa8b42025-05-02 04:28:16 +0000359 // Reference to the container status element
360 this.containerStatusElement = null;
361
Sean McCullough86b56862025-04-18 13:04:03 -0700362 // Binding methods to this
363 this._handleViewModeSelect = this._handleViewModeSelect.bind(this);
Sean McCullough86b56862025-04-18 13:04:03 -0700364 this._handleShowCommitDiff = this._handleShowCommitDiff.bind(this);
Sean McCullough485afc62025-04-28 14:28:39 -0700365 this._handleMutlipleChoiceSelected =
366 this._handleMutlipleChoiceSelected.bind(this);
Sean McCulloughd3906e22025-04-29 17:32:14 +0000367 this._handleStopClick = this._handleStopClick.bind(this);
Philip Zeyligerbc6b6292025-04-30 18:00:15 +0000368 this._handleNotificationsToggle =
369 this._handleNotificationsToggle.bind(this);
Philip Zeyligerdb5e9b42025-04-30 19:58:13 +0000370 this._handleWindowFocus = this._handleWindowFocus.bind(this);
371 this._handleWindowBlur = this._handleWindowBlur.bind(this);
Philip Zeyligerbc6b6292025-04-30 18:00:15 +0000372
373 // Load notification preference from localStorage
374 try {
375 const savedPref = localStorage.getItem("sketch-notifications-enabled");
376 if (savedPref !== null) {
377 this.notificationsEnabled = savedPref === "true";
378 }
379 } catch (error) {
380 console.error("Error loading notification preference:", error);
381 }
Sean McCullough86b56862025-04-18 13:04:03 -0700382 }
383
384 // See https://lit.dev/docs/components/lifecycle/
385 connectedCallback() {
386 super.connectedCallback();
387
Philip Zeyliger16fa8b42025-05-02 04:28:16 +0000388 // Get reference to the container status element
389 setTimeout(() => {
390 this.containerStatusElement =
391 this.shadowRoot?.getElementById("container-status");
392 }, 0);
393
Sean McCullough86b56862025-04-18 13:04:03 -0700394 // Initialize client-side nav history.
395 const url = new URL(window.location.href);
396 const mode = url.searchParams.get("view") || "chat";
397 window.history.replaceState({ mode }, "", url.toString());
398
399 this.toggleViewMode(mode as ViewMode, false);
400 // Add popstate event listener to handle browser back/forward navigation
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100401 window.addEventListener("popstate", this._handlePopState);
Sean McCullough86b56862025-04-18 13:04:03 -0700402
403 // Add event listeners
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100404 window.addEventListener("view-mode-select", this._handleViewModeSelect);
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100405 window.addEventListener("show-commit-diff", this._handleShowCommitDiff);
Sean McCullough86b56862025-04-18 13:04:03 -0700406
Philip Zeyligerdb5e9b42025-04-30 19:58:13 +0000407 // Add window focus/blur listeners for controlling notifications
408 window.addEventListener("focus", this._handleWindowFocus);
409 window.addEventListener("blur", this._handleWindowBlur);
Sean McCullough485afc62025-04-28 14:28:39 -0700410 window.addEventListener(
411 "multiple-choice-selected",
412 this._handleMutlipleChoiceSelected,
413 );
Philip Zeyligerdb5e9b42025-04-30 19:58:13 +0000414
Sean McCullough86b56862025-04-18 13:04:03 -0700415 // register event listeners
416 this.dataManager.addEventListener(
417 "dataChanged",
Philip Zeyliger72682df2025-04-23 13:09:46 -0700418 this.handleDataChanged.bind(this),
Sean McCullough86b56862025-04-18 13:04:03 -0700419 );
420 this.dataManager.addEventListener(
421 "connectionStatusChanged",
Philip Zeyliger72682df2025-04-23 13:09:46 -0700422 this.handleConnectionStatusChanged.bind(this),
Sean McCullough86b56862025-04-18 13:04:03 -0700423 );
424
Philip Zeyliger9b999b02025-04-25 16:31:50 +0000425 // Set initial document title
426 this.updateDocumentTitle();
427
Sean McCullough86b56862025-04-18 13:04:03 -0700428 // Initialize the data manager
429 this.dataManager.initialize();
Autoformattercf570962025-04-30 17:27:39 +0000430
Philip Zeyliger47b71c92025-04-30 15:43:39 +0000431 // Process existing messages for commit info
432 if (this.messages && this.messages.length > 0) {
Philip Zeyliger16fa8b42025-05-02 04:28:16 +0000433 // Update last commit info via container status component
434 setTimeout(() => {
435 if (this.containerStatusElement) {
436 this.containerStatusElement.updateLastCommitInfo(this.messages);
437 }
438 }, 100);
Philip Zeyliger47b71c92025-04-30 15:43:39 +0000439 }
Sean McCullough86b56862025-04-18 13:04:03 -0700440 }
441
442 // See https://lit.dev/docs/components/lifecycle/
443 disconnectedCallback() {
444 super.disconnectedCallback();
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100445 window.removeEventListener("popstate", this._handlePopState);
Sean McCullough86b56862025-04-18 13:04:03 -0700446
447 // Remove event listeners
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100448 window.removeEventListener("view-mode-select", this._handleViewModeSelect);
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100449 window.removeEventListener("show-commit-diff", this._handleShowCommitDiff);
Philip Zeyligerdb5e9b42025-04-30 19:58:13 +0000450 window.removeEventListener("focus", this._handleWindowFocus);
451 window.removeEventListener("blur", this._handleWindowBlur);
Sean McCullough485afc62025-04-28 14:28:39 -0700452 window.removeEventListener(
453 "multiple-choice-selected",
454 this._handleMutlipleChoiceSelected,
455 );
Sean McCullough86b56862025-04-18 13:04:03 -0700456
457 // unregister data manager event listeners
458 this.dataManager.removeEventListener(
459 "dataChanged",
Philip Zeyliger72682df2025-04-23 13:09:46 -0700460 this.handleDataChanged.bind(this),
Sean McCullough86b56862025-04-18 13:04:03 -0700461 );
462 this.dataManager.removeEventListener(
463 "connectionStatusChanged",
Philip Zeyliger72682df2025-04-23 13:09:46 -0700464 this.handleConnectionStatusChanged.bind(this),
Sean McCullough86b56862025-04-18 13:04:03 -0700465 );
466
467 // Disconnect mutation observer if it exists
468 if (this.mutationObserver) {
Sean McCullough86b56862025-04-18 13:04:03 -0700469 this.mutationObserver.disconnect();
470 this.mutationObserver = null;
471 }
472 }
473
Philip Zeyliger2d4c48f2025-05-02 23:35:03 +0000474 updateUrlForViewMode(mode: "chat" | "diff" | "terminal"): void {
Sean McCullough86b56862025-04-18 13:04:03 -0700475 // Get the current URL without search parameters
476 const url = new URL(window.location.href);
477
478 // Clear existing parameters
479 url.search = "";
480
481 // Only add view parameter if not in default chat view
482 if (mode !== "chat") {
483 url.searchParams.set("view", mode);
Sean McCullough71941bd2025-04-18 13:31:48 -0700484 const diffView = this.shadowRoot?.querySelector(
Philip Zeyliger72682df2025-04-23 13:09:46 -0700485 ".diff-view",
Sean McCullough71941bd2025-04-18 13:31:48 -0700486 ) as SketchDiffView;
Sean McCullough86b56862025-04-18 13:04:03 -0700487
488 // If in diff view and there's a commit hash, include that too
489 if (mode === "diff" && diffView.commitHash) {
490 url.searchParams.set("commit", diffView.commitHash);
491 }
492 }
493
494 // Update the browser history without reloading the page
495 window.history.pushState({ mode }, "", url.toString());
496 }
497
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100498 private _handlePopState(event: PopStateEvent) {
Sean McCullough86b56862025-04-18 13:04:03 -0700499 if (event.state && event.state.mode) {
500 this.toggleViewMode(event.state.mode, false);
501 } else {
502 this.toggleViewMode("chat", false);
503 }
504 }
505
506 /**
507 * Handle view mode selection event
508 */
509 private _handleViewModeSelect(event: CustomEvent) {
Philip Zeyliger2d4c48f2025-05-02 23:35:03 +0000510 const mode = event.detail.mode as "chat" | "diff" | "terminal";
Sean McCullough86b56862025-04-18 13:04:03 -0700511 this.toggleViewMode(mode, true);
512 }
513
514 /**
515 * Handle show commit diff event
516 */
517 private _handleShowCommitDiff(event: CustomEvent) {
518 const { commitHash } = event.detail;
519 if (commitHash) {
520 this.showCommitDiff(commitHash);
521 }
522 }
523
Sean McCullough485afc62025-04-28 14:28:39 -0700524 private _handleMultipleChoice(event: CustomEvent) {
525 window.console.log("_handleMultipleChoice", event);
526 this._sendChat;
527 }
Sean McCullough86b56862025-04-18 13:04:03 -0700528 /**
Sean McCullough86b56862025-04-18 13:04:03 -0700529 * Listen for commit diff event
530 * @param commitHash The commit hash to show diff for
531 */
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100532 private showCommitDiff(commitHash: string): void {
Sean McCullough86b56862025-04-18 13:04:03 -0700533 // Store the commit hash
534 this.currentCommitHash = commitHash;
535
536 // Switch to diff view
Sean McCullough71941bd2025-04-18 13:31:48 -0700537 this.toggleViewMode("diff", true);
Sean McCullough86b56862025-04-18 13:04:03 -0700538
539 // Wait for DOM update to complete
540 this.updateComplete.then(() => {
541 // Get the diff view component
542 const diffView = this.shadowRoot?.querySelector("sketch-diff-view");
543 if (diffView) {
544 // Call the showCommitDiff method
545 (diffView as any).showCommitDiff(commitHash);
546 }
547 });
548 }
549
550 /**
Philip Zeyliger2d4c48f2025-05-02 23:35:03 +0000551 * Toggle between different view modes: chat, diff, terminal
Sean McCullough86b56862025-04-18 13:04:03 -0700552 */
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100553 private toggleViewMode(mode: ViewMode, updateHistory: boolean): void {
Sean McCullough86b56862025-04-18 13:04:03 -0700554 // Don't do anything if the mode is already active
555 if (this.viewMode === mode) return;
556
557 // Update the view mode
558 this.viewMode = mode;
559
560 if (updateHistory) {
561 // Update URL with the current view mode
562 this.updateUrlForViewMode(mode);
563 }
564
565 // Wait for DOM update to complete
566 this.updateComplete.then(() => {
567 // Update active view
Pokey Rule46fff972025-04-25 14:57:44 +0100568 const viewContainerInner = this.shadowRoot?.querySelector(
569 "#view-container-inner",
570 );
Sean McCullough86b56862025-04-18 13:04:03 -0700571 const chatView = this.shadowRoot?.querySelector(".chat-view");
572 const diffView = this.shadowRoot?.querySelector(".diff-view");
Philip Zeyliger2d4c48f2025-05-02 23:35:03 +0000573
Sean McCullough86b56862025-04-18 13:04:03 -0700574 const terminalView = this.shadowRoot?.querySelector(".terminal-view");
575
576 // Remove active class from all views
577 chatView?.classList.remove("view-active");
578 diffView?.classList.remove("view-active");
Sean McCullough86b56862025-04-18 13:04:03 -0700579 terminalView?.classList.remove("view-active");
580
581 // Add/remove diff-active class on view container
582 if (mode === "diff") {
Pokey Rule46fff972025-04-25 14:57:44 +0100583 viewContainerInner?.classList.add("diff-active");
Sean McCullough86b56862025-04-18 13:04:03 -0700584 } else {
Pokey Rule46fff972025-04-25 14:57:44 +0100585 viewContainerInner?.classList.remove("diff-active");
Sean McCullough86b56862025-04-18 13:04:03 -0700586 }
587
588 // Add active class to the selected view
589 switch (mode) {
590 case "chat":
591 chatView?.classList.add("view-active");
592 break;
593 case "diff":
594 diffView?.classList.add("view-active");
595 // Load diff content if we have a diff view
596 const diffViewComp =
597 this.shadowRoot?.querySelector("sketch-diff-view");
598 if (diffViewComp && this.currentCommitHash) {
599 (diffViewComp as any).showCommitDiff(this.currentCommitHash);
600 } else if (diffViewComp) {
601 (diffViewComp as any).loadDiffContent();
602 }
603 break;
Philip Zeyliger2d4c48f2025-05-02 23:35:03 +0000604
Sean McCullough86b56862025-04-18 13:04:03 -0700605 case "terminal":
606 terminalView?.classList.add("view-active");
607 break;
608 }
609
610 // Update view mode buttons
611 const viewModeSelect = this.shadowRoot?.querySelector(
Philip Zeyliger72682df2025-04-23 13:09:46 -0700612 "sketch-view-mode-select",
Sean McCullough86b56862025-04-18 13:04:03 -0700613 );
614 if (viewModeSelect) {
615 const event = new CustomEvent("update-active-mode", {
616 detail: { mode },
617 bubbles: true,
618 composed: true,
619 });
620 viewModeSelect.dispatchEvent(event);
621 }
Sean McCullough86b56862025-04-18 13:04:03 -0700622 });
623 }
624
Philip Zeyliger9b999b02025-04-25 16:31:50 +0000625 /**
626 * Updates the document title based on current title and connection status
627 */
628 private updateDocumentTitle(): void {
629 let docTitle = `sk: ${this.title || "untitled"}`;
630
631 // Add red circle emoji if disconnected
632 if (this.connectionStatus === "disconnected") {
633 docTitle += " 🔴";
634 }
635
636 document.title = docTitle;
637 }
638
Philip Zeyligerbc6b6292025-04-30 18:00:15 +0000639 // Check and request notification permission if needed
640 private async checkNotificationPermission(): Promise<boolean> {
641 // Check if the Notification API is supported
642 if (!("Notification" in window)) {
643 console.log("This browser does not support notifications");
644 return false;
645 }
646
647 // Check if permission is already granted
648 if (Notification.permission === "granted") {
649 return true;
650 }
651
652 // If permission is not denied, request it
653 if (Notification.permission !== "denied") {
654 const permission = await Notification.requestPermission();
655 return permission === "granted";
656 }
657
658 return false;
659 }
660
Philip Zeyligerdb5e9b42025-04-30 19:58:13 +0000661 // Handle notifications toggle click
662 private _handleNotificationsToggle(): void {
663 this.notificationsEnabled = !this.notificationsEnabled;
Philip Zeyligerbc6b6292025-04-30 18:00:15 +0000664
665 // If enabling notifications, check permissions
666 if (this.notificationsEnabled) {
667 this.checkNotificationPermission();
668 }
669
670 // Save preference to localStorage
671 try {
672 localStorage.setItem(
673 "sketch-notifications-enabled",
674 String(this.notificationsEnabled),
675 );
676 } catch (error) {
677 console.error("Error saving notification preference:", error);
678 }
679 }
680
Philip Zeyligerdb5e9b42025-04-30 19:58:13 +0000681 // Handle window focus event
682 private _handleWindowFocus(): void {
683 this._windowFocused = true;
684 }
685
686 // Handle window blur event
687 private _handleWindowBlur(): void {
688 this._windowFocused = false;
689 }
690
Philip Zeyligerbc6b6292025-04-30 18:00:15 +0000691 // Show notification for message with EndOfTurn=true
692 private async showEndOfTurnNotification(
693 message: AgentMessage,
694 ): Promise<void> {
695 // Don't show notifications if they're disabled
696 if (!this.notificationsEnabled) return;
697
Philip Zeyligerdb5e9b42025-04-30 19:58:13 +0000698 // Don't show notifications if the window is focused
699 if (this._windowFocused) return;
700
Philip Zeyligerbc6b6292025-04-30 18:00:15 +0000701 // Check if we have permission to show notifications
702 const hasPermission = await this.checkNotificationPermission();
703 if (!hasPermission) return;
704
Philip Zeyliger32011332025-04-30 20:59:40 +0000705 // Only show notifications for agent messages with end_of_turn=true and no parent_conversation_id
706 if (
707 message.type !== "agent" ||
708 !message.end_of_turn ||
709 message.parent_conversation_id
710 )
711 return;
Philip Zeyligerbc6b6292025-04-30 18:00:15 +0000712
713 // Create a title that includes the sketch title
714 const notificationTitle = `Sketch: ${this.title || "untitled"}`;
715
716 // Extract the beginning of the message content (first 100 chars)
717 const messagePreview = message.content
718 ? message.content.substring(0, 100) +
719 (message.content.length > 100 ? "..." : "")
720 : "Agent has completed its turn";
721
722 // Create and show the notification
723 try {
724 new Notification(notificationTitle, {
725 body: messagePreview,
Philip Zeyligerdb5e9b42025-04-30 19:58:13 +0000726 icon: "https://sketch.dev/favicon.ico", // Use sketch.dev favicon for notification
Philip Zeyligerbc6b6292025-04-30 18:00:15 +0000727 });
728 } catch (error) {
729 console.error("Error showing notification:", error);
730 }
731 }
732
Sean McCullough86b56862025-04-18 13:04:03 -0700733 private handleDataChanged(eventData: {
734 state: State;
Sean McCulloughd9f13372025-04-21 15:08:49 -0700735 newMessages: AgentMessage[];
Sean McCullough86b56862025-04-18 13:04:03 -0700736 }): void {
Philip Zeyligerbce3a132025-04-30 22:03:39 +0000737 const { state, newMessages } = eventData;
Sean McCullough86b56862025-04-18 13:04:03 -0700738
739 // Update state if we received it
740 if (state) {
Josh Bleecher Snydere81233f2025-04-30 04:05:41 +0000741 // Ensure we're using the latest call status to prevent indicators from being stuck
Autoformatterf830c9d2025-04-30 18:16:01 +0000742 if (
743 state.outstanding_llm_calls === 0 &&
744 state.outstanding_tool_calls.length === 0
745 ) {
Josh Bleecher Snydere81233f2025-04-30 04:05:41 +0000746 // Force reset containerState calls when nothing is reported as in progress
747 state.outstanding_llm_calls = 0;
748 state.outstanding_tool_calls = [];
749 }
Autoformatterf830c9d2025-04-30 18:16:01 +0000750
Sean McCullough86b56862025-04-18 13:04:03 -0700751 this.containerState = state;
752 this.title = state.title;
Philip Zeyliger9b999b02025-04-25 16:31:50 +0000753
754 // Update document title when sketch title changes
755 this.updateDocumentTitle();
Sean McCullough86b56862025-04-18 13:04:03 -0700756 }
757
Sean McCullough86b56862025-04-18 13:04:03 -0700758 // Update messages
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100759 this.messages = aggregateAgentMessages(this.messages, newMessages);
Autoformattercf570962025-04-30 17:27:39 +0000760
Philip Zeyliger47b71c92025-04-30 15:43:39 +0000761 // Process new messages to find commit messages
Philip Zeyliger16fa8b42025-05-02 04:28:16 +0000762 // Update last commit info via container status component
763 if (this.containerStatusElement) {
764 this.containerStatusElement.updateLastCommitInfo(newMessages);
765 }
Philip Zeyligerbc6b6292025-04-30 18:00:15 +0000766
767 // Check for agent messages with end_of_turn=true and show notifications
Philip Zeyligerbce3a132025-04-30 22:03:39 +0000768 if (newMessages && newMessages.length > 0) {
Philip Zeyligerbc6b6292025-04-30 18:00:15 +0000769 for (const message of newMessages) {
Philip Zeyliger32011332025-04-30 20:59:40 +0000770 if (
771 message.type === "agent" &&
772 message.end_of_turn &&
773 !message.parent_conversation_id
774 ) {
Philip Zeyligerbc6b6292025-04-30 18:00:15 +0000775 this.showEndOfTurnNotification(message);
776 break; // Only show one notification per batch of messages
777 }
778 }
779 }
Sean McCullough86b56862025-04-18 13:04:03 -0700780 }
781
782 private handleConnectionStatusChanged(
783 status: ConnectionStatus,
Philip Zeyliger72682df2025-04-23 13:09:46 -0700784 errorMessage?: string,
Sean McCullough86b56862025-04-18 13:04:03 -0700785 ): void {
786 this.connectionStatus = status;
787 this.connectionErrorMessage = errorMessage || "";
Philip Zeyliger9b999b02025-04-25 16:31:50 +0000788
789 // Update document title when connection status changes
790 this.updateDocumentTitle();
Sean McCullough86b56862025-04-18 13:04:03 -0700791 }
792
Sean McCulloughd3906e22025-04-29 17:32:14 +0000793 private async _handleStopClick(): Promise<void> {
794 try {
795 const response = await fetch("cancel", {
796 method: "POST",
797 headers: {
798 "Content-Type": "application/json",
799 },
800 body: JSON.stringify({ reason: "user requested cancellation" }),
801 });
802
803 if (!response.ok) {
804 const errorData = await response.text();
805 throw new Error(
806 `Failed to stop operation: ${response.status} - ${errorData}`,
807 );
808 }
809
Philip Zeyligerbce3a132025-04-30 22:03:39 +0000810 // Stop request sent
Sean McCulloughd3906e22025-04-29 17:32:14 +0000811 } catch (error) {
812 console.error("Error stopping operation:", error);
Sean McCulloughd3906e22025-04-29 17:32:14 +0000813 }
814 }
815
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700816 openRestartModal() {
817 this.restartModalOpen = true;
818 }
819
820 handleRestartModalClose() {
821 this.restartModalOpen = false;
822 }
823
Sean McCullough485afc62025-04-28 14:28:39 -0700824 async _handleMutlipleChoiceSelected(e: CustomEvent) {
825 const chatInput = this.shadowRoot?.querySelector(
826 "sketch-chat-input",
827 ) as SketchChatInput;
828 if (chatInput) {
829 chatInput.content = e.detail.responseText;
830 chatInput.focus();
831 }
832 }
833
Sean McCullough86b56862025-04-18 13:04:03 -0700834 async _sendChat(e: CustomEvent) {
835 console.log("app shell: _sendChat", e);
Sean McCullough485afc62025-04-28 14:28:39 -0700836 e.preventDefault();
837 e.stopPropagation();
Sean McCullough86b56862025-04-18 13:04:03 -0700838 const message = e.detail.message?.trim();
839 if (message == "") {
840 return;
841 }
842 try {
843 // Send the message to the server
844 const response = await fetch("chat", {
845 method: "POST",
846 headers: {
847 "Content-Type": "application/json",
848 },
849 body: JSON.stringify({ message }),
850 });
851
852 if (!response.ok) {
853 const errorData = await response.text();
854 throw new Error(`Server error: ${response.status} - ${errorData}`);
855 }
Sean McCullough86b56862025-04-18 13:04:03 -0700856 } catch (error) {
857 console.error("Error sending chat message:", error);
858 const statusText = document.getElementById("statusText");
859 if (statusText) {
860 statusText.textContent = "Error sending message";
861 }
862 }
863 }
864
Pokey Rule4097e532025-04-24 18:55:28 +0100865 private scrollContainerRef = createRef<HTMLElement>();
866
Sean McCullough86b56862025-04-18 13:04:03 -0700867 render() {
868 return html`
Pokey Rule4097e532025-04-24 18:55:28 +0100869 <div id="top-banner">
Sean McCullough86b56862025-04-18 13:04:03 -0700870 <div class="title-container">
871 <h1 class="banner-title">sketch</h1>
872 <h2 id="chatTitle" class="chat-title">${this.title}</h2>
873 </div>
874
Philip Zeyligerbce3a132025-04-30 22:03:39 +0000875 <!-- Container status info moved above tabs -->
Sean McCullough86b56862025-04-18 13:04:03 -0700876 <sketch-container-status
877 .state=${this.containerState}
Philip Zeyliger16fa8b42025-05-02 04:28:16 +0000878 id="container-status"
Sean McCullough86b56862025-04-18 13:04:03 -0700879 ></sketch-container-status>
Autoformattercf570962025-04-30 17:27:39 +0000880
Philip Zeyliger16fa8b42025-05-02 04:28:16 +0000881 <!-- Last Commit section moved to sketch-container-status -->
Philip Zeyligerbce3a132025-04-30 22:03:39 +0000882
Philip Zeyliger16fa8b42025-05-02 04:28:16 +0000883 <!-- Views section with tabs -->
884 <sketch-view-mode-select></sketch-view-mode-select>
Sean McCullough86b56862025-04-18 13:04:03 -0700885
886 <div class="refresh-control">
Sean McCulloughd3906e22025-04-29 17:32:14 +0000887 <button
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700888 id="restartButton"
889 class="restart-button"
890 ?disabled=${this.containerState.message_count === 0}
891 @click=${this.openRestartModal}
Sean McCulloughd3906e22025-04-29 17:32:14 +0000892 >
Philip Zeyligerbce3a132025-04-30 22:03:39 +0000893 <svg
894 class="button-icon"
895 xmlns="http://www.w3.org/2000/svg"
896 viewBox="0 0 24 24"
897 fill="none"
898 stroke="currentColor"
899 stroke-width="2"
900 stroke-linecap="round"
901 stroke-linejoin="round"
902 >
903 <path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" />
904 <path d="M3 3v5h5" />
905 </svg>
906 <span class="button-text">Restart</span>
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700907 </button>
Philip Zeyligerbce3a132025-04-30 22:03:39 +0000908 <button
909 id="stopButton"
910 class="stop-button"
911 ?disabled=${(this.containerState?.outstanding_llm_calls || 0) ===
912 0 &&
913 (this.containerState?.outstanding_tool_calls || []).length === 0}
914 >
915 <svg
916 class="button-icon"
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>
927 <span class="button-text">Stop</span>
Sean McCullough86b56862025-04-18 13:04:03 -0700928 </button>
929
Philip Zeyligerdb5e9b42025-04-30 19:58:13 +0000930 <div
931 class="notifications-toggle"
932 @click=${this._handleNotificationsToggle}
933 title="${this.notificationsEnabled
934 ? "Disable"
Philip Zeyligerbce3a132025-04-30 22:03:39 +0000935 : "Enable"} notifications when the agent completes its turn"
Philip Zeyligerdb5e9b42025-04-30 19:58:13 +0000936 >
937 <div
938 class="bell-icon ${!this.notificationsEnabled
939 ? "bell-disabled"
940 : ""}"
941 >
942 <!-- Bell SVG icon -->
943 <svg
944 xmlns="http://www.w3.org/2000/svg"
945 width="16"
946 height="16"
947 fill="currentColor"
948 viewBox="0 0 16 16"
949 >
950 <path
951 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"
952 />
953 </svg>
954 </div>
Philip Zeyligerbc6b6292025-04-30 18:00:15 +0000955 </div>
956
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000957 <sketch-call-status
Sean McCulloughd9d45812025-04-30 16:53:41 -0700958 .agentState=${this.containerState?.agent_state}
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000959 .llmCalls=${this.containerState?.outstanding_llm_calls || 0}
960 .toolCalls=${this.containerState?.outstanding_tool_calls || []}
961 ></sketch-call-status>
Philip Zeyliger25f6ff12025-05-02 04:24:10 +0000962
963 <sketch-network-status
964 connection=${this.connectionStatus}
965 error=${this.connectionErrorMessage}
966 ></sketch-network-status>
Sean McCullough86b56862025-04-18 13:04:03 -0700967 </div>
968 </div>
969
Pokey Rule4097e532025-04-24 18:55:28 +0100970 <div id="view-container" ${ref(this.scrollContainerRef)}>
971 <div id="view-container-inner">
972 <div
973 class="chat-view ${this.viewMode === "chat" ? "view-active" : ""}"
974 >
975 <sketch-timeline
976 .messages=${this.messages}
977 .scrollContainer=${this.scrollContainerRef}
Philip Zeyliger16fa8b42025-05-02 04:28:16 +0000978 .agentState=${this.containerState?.agent_state}
979 .llmCalls=${this.containerState?.outstanding_llm_calls || 0}
980 .toolCalls=${this.containerState?.outstanding_tool_calls || []}
Pokey Rule4097e532025-04-24 18:55:28 +0100981 ></sketch-timeline>
982 </div>
983 <div
984 class="diff-view ${this.viewMode === "diff" ? "view-active" : ""}"
985 >
986 <sketch-diff-view
987 .commitHash=${this.currentCommitHash}
988 ></sketch-diff-view>
989 </div>
Philip Zeyliger2d4c48f2025-05-02 23:35:03 +0000990
Pokey Rule4097e532025-04-24 18:55:28 +0100991 <div
992 class="terminal-view ${this.viewMode === "terminal"
993 ? "view-active"
994 : ""}"
995 >
996 <sketch-terminal></sketch-terminal>
997 </div>
Sean McCullough86b56862025-04-18 13:04:03 -0700998 </div>
999 </div>
1000
Pokey Rule4097e532025-04-24 18:55:28 +01001001 <div id="chat-input">
1002 <sketch-chat-input @send-chat="${this._sendChat}"></sketch-chat-input>
1003 </div>
Philip Zeyliger2c4db092025-04-28 16:57:50 -07001004
1005 <sketch-restart-modal
1006 ?open=${this.restartModalOpen}
1007 @close=${this.handleRestartModalClose}
1008 .containerState=${this.containerState}
1009 .messages=${this.messages}
1010 ></sketch-restart-modal>
Sean McCullough86b56862025-04-18 13:04:03 -07001011 `;
1012 }
1013
1014 /**
Sean McCullough86b56862025-04-18 13:04:03 -07001015 * Lifecycle callback when component is first connected to DOM
1016 */
1017 firstUpdated(): void {
1018 if (this.viewMode !== "chat") {
1019 return;
1020 }
1021
1022 // Initial scroll to bottom when component is first rendered
1023 setTimeout(
1024 () => this.scrollTo({ top: this.scrollHeight, behavior: "smooth" }),
Philip Zeyliger72682df2025-04-23 13:09:46 -07001025 50,
Sean McCullough86b56862025-04-18 13:04:03 -07001026 );
1027
Philip Zeyliger2c4db092025-04-28 16:57:50 -07001028 // Setup stop button
1029 const stopButton = this.renderRoot?.querySelector(
1030 "#stopButton",
1031 ) as HTMLButtonElement;
1032 stopButton?.addEventListener("click", async () => {
1033 try {
Sean McCullough495cb962025-05-01 16:25:53 -07001034 const response = await fetch("cancel", {
Philip Zeyliger2c4db092025-04-28 16:57:50 -07001035 method: "POST",
1036 headers: {
1037 "Content-Type": "application/json",
1038 },
1039 body: JSON.stringify({ reason: "User clicked stop button" }),
1040 });
1041 if (!response.ok) {
1042 console.error("Failed to cancel:", await response.text());
1043 }
1044 } catch (error) {
1045 console.error("Error cancelling operation:", error);
1046 }
1047 });
1048
Philip Zeyliger47b71c92025-04-30 15:43:39 +00001049 // Process any existing messages to find commit information
1050 if (this.messages && this.messages.length > 0) {
Philip Zeyliger16fa8b42025-05-02 04:28:16 +00001051 // Update last commit info via container status component
1052 if (this.containerStatusElement) {
1053 this.containerStatusElement.updateLastCommitInfo(this.messages);
1054 }
Philip Zeyliger47b71c92025-04-30 15:43:39 +00001055 }
Sean McCullough86b56862025-04-18 13:04:03 -07001056 }
1057}
1058
1059declare global {
1060 interface HTMLElementTagNameMap {
1061 "sketch-app-shell": SketchAppShell;
1062 }
1063}