blob: 7560bd629ef6d9405a8d56348b2ca9d1d607c429 [file] [log] [blame]
Sean McCullough86b56862025-04-18 13:04:03 -07001import { css, html, LitElement } from "lit";
2import { customElement, property, state } from "lit/decorators.js";
Sean McCullough86b56862025-04-18 13:04:03 -07003import { DataManager, ConnectionStatus } from "../data";
Sean McCulloughd9f13372025-04-21 15:08:49 -07004import { State, AgentMessage } from "../types";
Sean McCullough86b56862025-04-18 13:04:03 -07005import "./sketch-container-status";
6import "./sketch-view-mode-select";
7import "./sketch-network-status";
8import "./sketch-timeline";
9import "./sketch-chat-input";
10import "./sketch-diff-view";
11import "./sketch-charts";
12import "./sketch-terminal";
13import { SketchDiffView } from "./sketch-diff-view";
Pokey Rulee2a8c2f2025-04-23 15:09:25 +010014import { aggregateAgentMessages } from "./aggregateAgentMessages";
Sean McCullough86b56862025-04-18 13:04:03 -070015
16type ViewMode = "chat" | "diff" | "charts" | "terminal";
17
18@customElement("sketch-app-shell")
19export class SketchAppShell extends LitElement {
20 // Current view mode (chat, diff, charts, terminal)
21 @state()
22 viewMode: "chat" | "diff" | "charts" | "terminal" = "chat";
23
24 // Current commit hash for diff view
25 @state()
26 currentCommitHash: string = "";
27
Sean McCullough86b56862025-04-18 13:04:03 -070028 // See https://lit.dev/docs/components/styles/ for how lit-element handles CSS.
29 // Note that these styles only apply to the scope of this web component's
30 // shadow DOM node, so they won't leak out or collide with CSS declared in
31 // other components or the containing web page (...unless you want it to do that).
32 static styles = css`
33 :host {
34 display: block;
Sean McCullough71941bd2025-04-18 13:31:48 -070035 font-family:
36 system-ui,
37 -apple-system,
38 BlinkMacSystemFont,
39 "Segoe UI",
40 Roboto,
41 sans-serif;
Sean McCullough86b56862025-04-18 13:04:03 -070042 color: #333;
43 line-height: 1.4;
44 min-height: 100vh;
45 width: 100%;
46 position: relative;
47 overflow-x: hidden;
48 }
49
50 /* Top banner with combined elements */
51 .top-banner {
52 display: flex;
53 justify-content: space-between;
54 align-items: center;
55 padding: 5px 20px;
56 margin-bottom: 0;
57 border-bottom: 1px solid #eee;
58 gap: 10px;
59 position: fixed;
60 top: 0;
61 left: 0;
62 right: 0;
63 background: white;
64 z-index: 100;
65 box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
66 max-width: 100%;
67 }
68
69 .banner-title {
70 font-size: 18px;
71 font-weight: 600;
72 margin: 0;
73 min-width: 6em;
74 white-space: nowrap;
75 overflow: hidden;
76 text-overflow: ellipsis;
77 }
78
79 .chat-title {
80 margin: 0;
81 padding: 0;
82 color: rgba(82, 82, 82, 0.85);
83 font-size: 16px;
84 font-weight: normal;
85 font-style: italic;
86 white-space: nowrap;
87 overflow: hidden;
88 text-overflow: ellipsis;
89 }
90
91 /* View mode container styles - mirroring timeline.css structure */
92 .view-container {
93 max-width: 1200px;
94 margin: 0 auto;
95 margin-top: 65px; /* Space for the top banner */
96 margin-bottom: 90px; /* Increased space for the chat input */
97 position: relative;
98 padding-bottom: 15px; /* Additional padding to prevent clipping */
99 padding-top: 15px; /* Add padding at top to prevent content touching the header */
100 }
101
102 /* Allow the container to expand to full width in diff mode */
103 .view-container.diff-active {
104 max-width: 100%;
105 }
106
107 /* Individual view styles */
108 .chat-view,
109 .diff-view,
110 .chart-view,
111 .terminal-view {
112 display: none; /* Hidden by default */
113 width: 100%;
114 }
115
116 /* Active view styles - these will be applied via JavaScript */
117 .view-active {
118 display: flex;
119 flex-direction: column;
120 }
121
122 .title-container {
123 display: flex;
124 flex-direction: column;
125 white-space: nowrap;
126 overflow: hidden;
127 text-overflow: ellipsis;
128 max-width: 33%;
129 }
130
131 .refresh-control {
132 display: flex;
133 align-items: center;
134 margin-bottom: 0;
135 flex-wrap: nowrap;
136 white-space: nowrap;
137 flex-shrink: 0;
138 }
139
140 .refresh-button {
141 background: #4caf50;
142 color: white;
143 border: none;
144 padding: 4px 10px;
145 border-radius: 4px;
146 cursor: pointer;
147 font-size: 12px;
148 margin-right: 5px;
149 }
150
151 .stop-button:hover {
152 background-color: #c82333 !important;
153 }
154
155 .poll-updates {
156 display: flex;
157 align-items: center;
158 margin: 0 5px;
159 font-size: 12px;
160 }
161 `;
162
163 // Header bar: Network connection status details
164 @property()
165 connectionStatus: ConnectionStatus = "disconnected";
166
167 @property()
168 connectionErrorMessage: string = "";
169
170 @property()
171 messageStatus: string = "";
172
173 // Chat messages
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100174 @property({ attribute: false })
Sean McCulloughd9f13372025-04-21 15:08:49 -0700175 messages: AgentMessage[] = [];
Sean McCullough86b56862025-04-18 13:04:03 -0700176
177 @property()
178 chatMessageText: string = "";
179
180 @property()
181 title: string = "";
182
183 private dataManager = new DataManager();
184
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100185 @property({ attribute: false })
Sean McCulloughd9f13372025-04-21 15:08:49 -0700186 containerState: State = {
187 title: "",
188 os: "",
189 message_count: 0,
190 hostname: "",
191 working_dir: "",
192 initial_commit: "",
193 };
Sean McCullough86b56862025-04-18 13:04:03 -0700194
Sean McCullough86b56862025-04-18 13:04:03 -0700195 // Mutation observer to detect when new messages are added
196 private mutationObserver: MutationObserver | null = null;
197
198 constructor() {
199 super();
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100200 console.log("Hello!");
Sean McCullough86b56862025-04-18 13:04:03 -0700201
202 // Binding methods to this
203 this._handleViewModeSelect = this._handleViewModeSelect.bind(this);
204 this._handleDiffComment = this._handleDiffComment.bind(this);
205 this._handleShowCommitDiff = this._handleShowCommitDiff.bind(this);
206 this._handlePopState = this._handlePopState.bind(this);
207 }
208
209 // See https://lit.dev/docs/components/lifecycle/
210 connectedCallback() {
211 super.connectedCallback();
212
213 // Initialize client-side nav history.
214 const url = new URL(window.location.href);
215 const mode = url.searchParams.get("view") || "chat";
216 window.history.replaceState({ mode }, "", url.toString());
217
218 this.toggleViewMode(mode as ViewMode, false);
219 // Add popstate event listener to handle browser back/forward navigation
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100220 window.addEventListener("popstate", this._handlePopState);
Sean McCullough86b56862025-04-18 13:04:03 -0700221
222 // Add event listeners
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100223 window.addEventListener("view-mode-select", this._handleViewModeSelect);
224 window.addEventListener("diff-comment", this._handleDiffComment);
225 window.addEventListener("show-commit-diff", this._handleShowCommitDiff);
Sean McCullough86b56862025-04-18 13:04:03 -0700226
227 // register event listeners
228 this.dataManager.addEventListener(
229 "dataChanged",
Philip Zeyliger72682df2025-04-23 13:09:46 -0700230 this.handleDataChanged.bind(this),
Sean McCullough86b56862025-04-18 13:04:03 -0700231 );
232 this.dataManager.addEventListener(
233 "connectionStatusChanged",
Philip Zeyliger72682df2025-04-23 13:09:46 -0700234 this.handleConnectionStatusChanged.bind(this),
Sean McCullough86b56862025-04-18 13:04:03 -0700235 );
236
237 // Initialize the data manager
238 this.dataManager.initialize();
239 }
240
241 // See https://lit.dev/docs/components/lifecycle/
242 disconnectedCallback() {
243 super.disconnectedCallback();
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100244 window.removeEventListener("popstate", this._handlePopState);
Sean McCullough86b56862025-04-18 13:04:03 -0700245
246 // Remove event listeners
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100247 window.removeEventListener("view-mode-select", this._handleViewModeSelect);
248 window.removeEventListener("diff-comment", this._handleDiffComment);
249 window.removeEventListener("show-commit-diff", this._handleShowCommitDiff);
Sean McCullough86b56862025-04-18 13:04:03 -0700250
251 // unregister data manager event listeners
252 this.dataManager.removeEventListener(
253 "dataChanged",
Philip Zeyliger72682df2025-04-23 13:09:46 -0700254 this.handleDataChanged.bind(this),
Sean McCullough86b56862025-04-18 13:04:03 -0700255 );
256 this.dataManager.removeEventListener(
257 "connectionStatusChanged",
Philip Zeyliger72682df2025-04-23 13:09:46 -0700258 this.handleConnectionStatusChanged.bind(this),
Sean McCullough86b56862025-04-18 13:04:03 -0700259 );
260
261 // Disconnect mutation observer if it exists
262 if (this.mutationObserver) {
263 console.log("Auto-scroll: Disconnecting mutation observer");
264 this.mutationObserver.disconnect();
265 this.mutationObserver = null;
266 }
267 }
268
Sean McCullough71941bd2025-04-18 13:31:48 -0700269 updateUrlForViewMode(mode: "chat" | "diff" | "charts" | "terminal"): void {
Sean McCullough86b56862025-04-18 13:04:03 -0700270 // Get the current URL without search parameters
271 const url = new URL(window.location.href);
272
273 // Clear existing parameters
274 url.search = "";
275
276 // Only add view parameter if not in default chat view
277 if (mode !== "chat") {
278 url.searchParams.set("view", mode);
Sean McCullough71941bd2025-04-18 13:31:48 -0700279 const diffView = this.shadowRoot?.querySelector(
Philip Zeyliger72682df2025-04-23 13:09:46 -0700280 ".diff-view",
Sean McCullough71941bd2025-04-18 13:31:48 -0700281 ) as SketchDiffView;
Sean McCullough86b56862025-04-18 13:04:03 -0700282
283 // If in diff view and there's a commit hash, include that too
284 if (mode === "diff" && diffView.commitHash) {
285 url.searchParams.set("commit", diffView.commitHash);
286 }
287 }
288
289 // Update the browser history without reloading the page
290 window.history.pushState({ mode }, "", url.toString());
291 }
292
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100293 private _handlePopState(event: PopStateEvent) {
Sean McCullough86b56862025-04-18 13:04:03 -0700294 if (event.state && event.state.mode) {
295 this.toggleViewMode(event.state.mode, false);
296 } else {
297 this.toggleViewMode("chat", false);
298 }
299 }
300
301 /**
302 * Handle view mode selection event
303 */
304 private _handleViewModeSelect(event: CustomEvent) {
305 const mode = event.detail.mode as "chat" | "diff" | "charts" | "terminal";
306 this.toggleViewMode(mode, true);
307 }
308
309 /**
310 * Handle show commit diff event
311 */
312 private _handleShowCommitDiff(event: CustomEvent) {
313 const { commitHash } = event.detail;
314 if (commitHash) {
315 this.showCommitDiff(commitHash);
316 }
317 }
318
319 /**
320 * Handle diff comment event
321 */
322 private _handleDiffComment(event: CustomEvent) {
323 const { comment } = event.detail;
324 if (!comment) return;
325
Philip Zeyliger9a66cad2025-04-23 12:21:40 -0700326 if (this.chatMessageText.length > 0) {
327 this.chatMessageText += "\n\n";
Sean McCullough86b56862025-04-18 13:04:03 -0700328 }
Philip Zeyliger9a66cad2025-04-23 12:21:40 -0700329 this.chatMessageText += comment;
Sean McCullough86b56862025-04-18 13:04:03 -0700330 }
331
332 /**
333 * Listen for commit diff event
334 * @param commitHash The commit hash to show diff for
335 */
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100336 private showCommitDiff(commitHash: string): void {
Sean McCullough86b56862025-04-18 13:04:03 -0700337 // Store the commit hash
338 this.currentCommitHash = commitHash;
339
340 // Switch to diff view
Sean McCullough71941bd2025-04-18 13:31:48 -0700341 this.toggleViewMode("diff", true);
Sean McCullough86b56862025-04-18 13:04:03 -0700342
343 // Wait for DOM update to complete
344 this.updateComplete.then(() => {
345 // Get the diff view component
346 const diffView = this.shadowRoot?.querySelector("sketch-diff-view");
347 if (diffView) {
348 // Call the showCommitDiff method
349 (diffView as any).showCommitDiff(commitHash);
350 }
351 });
352 }
353
354 /**
355 * Toggle between different view modes: chat, diff, charts, terminal
356 */
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100357 private toggleViewMode(mode: ViewMode, updateHistory: boolean): void {
Sean McCullough86b56862025-04-18 13:04:03 -0700358 // Don't do anything if the mode is already active
359 if (this.viewMode === mode) return;
360
361 // Update the view mode
362 this.viewMode = mode;
363
364 if (updateHistory) {
365 // Update URL with the current view mode
366 this.updateUrlForViewMode(mode);
367 }
368
369 // Wait for DOM update to complete
370 this.updateComplete.then(() => {
371 // Update active view
372 const viewContainer = this.shadowRoot?.querySelector(".view-container");
373 const chatView = this.shadowRoot?.querySelector(".chat-view");
374 const diffView = this.shadowRoot?.querySelector(".diff-view");
375 const chartView = this.shadowRoot?.querySelector(".chart-view");
376 const terminalView = this.shadowRoot?.querySelector(".terminal-view");
377
378 // Remove active class from all views
379 chatView?.classList.remove("view-active");
380 diffView?.classList.remove("view-active");
381 chartView?.classList.remove("view-active");
382 terminalView?.classList.remove("view-active");
383
384 // Add/remove diff-active class on view container
385 if (mode === "diff") {
386 viewContainer?.classList.add("diff-active");
387 } else {
388 viewContainer?.classList.remove("diff-active");
389 }
390
391 // Add active class to the selected view
392 switch (mode) {
393 case "chat":
394 chatView?.classList.add("view-active");
395 break;
396 case "diff":
397 diffView?.classList.add("view-active");
398 // Load diff content if we have a diff view
399 const diffViewComp =
400 this.shadowRoot?.querySelector("sketch-diff-view");
401 if (diffViewComp && this.currentCommitHash) {
402 (diffViewComp as any).showCommitDiff(this.currentCommitHash);
403 } else if (diffViewComp) {
404 (diffViewComp as any).loadDiffContent();
405 }
406 break;
407 case "charts":
408 chartView?.classList.add("view-active");
409 break;
410 case "terminal":
411 terminalView?.classList.add("view-active");
412 break;
413 }
414
415 // Update view mode buttons
416 const viewModeSelect = this.shadowRoot?.querySelector(
Philip Zeyliger72682df2025-04-23 13:09:46 -0700417 "sketch-view-mode-select",
Sean McCullough86b56862025-04-18 13:04:03 -0700418 );
419 if (viewModeSelect) {
420 const event = new CustomEvent("update-active-mode", {
421 detail: { mode },
422 bubbles: true,
423 composed: true,
424 });
425 viewModeSelect.dispatchEvent(event);
426 }
427
428 // FIXME: This is a hack to get vega chart in sketch-charts.ts to work properly
429 // When the chart is in the background, its container has a width of 0, so vega
430 // renders width 0 and only changes that width on a resize event.
431 // See https://github.com/vega/react-vega/issues/85#issuecomment-1826421132
432 window.dispatchEvent(new Event("resize"));
433 });
434 }
435
Sean McCullough86b56862025-04-18 13:04:03 -0700436 private handleDataChanged(eventData: {
437 state: State;
Sean McCulloughd9f13372025-04-21 15:08:49 -0700438 newMessages: AgentMessage[];
Sean McCullough86b56862025-04-18 13:04:03 -0700439 isFirstFetch?: boolean;
440 }): void {
441 const { state, newMessages, isFirstFetch } = eventData;
442
443 // Check if this is the first data fetch or if there are new messages
444 if (isFirstFetch) {
Sean McCullough86b56862025-04-18 13:04:03 -0700445 this.messageStatus = "Initial messages loaded";
446 } else if (newMessages && newMessages.length > 0) {
Sean McCullough86b56862025-04-18 13:04:03 -0700447 this.messageStatus = "Updated just now";
Sean McCullough86b56862025-04-18 13:04:03 -0700448 } else {
449 this.messageStatus = "No new messages";
450 }
451
452 // Update state if we received it
453 if (state) {
454 this.containerState = state;
455 this.title = state.title;
456 }
457
458 // Create a copy of the current messages before updating
459 const oldMessageCount = this.messages.length;
460
461 // Update messages
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100462 this.messages = aggregateAgentMessages(this.messages, newMessages);
Sean McCullough86b56862025-04-18 13:04:03 -0700463
464 // Log information about the message update
465 if (this.messages.length > oldMessageCount) {
466 console.log(
Philip Zeyliger72682df2025-04-23 13:09:46 -0700467 `Auto-scroll: Messages updated from ${oldMessageCount} to ${this.messages.length}`,
Sean McCullough86b56862025-04-18 13:04:03 -0700468 );
469 }
470 }
471
472 private handleConnectionStatusChanged(
473 status: ConnectionStatus,
Philip Zeyliger72682df2025-04-23 13:09:46 -0700474 errorMessage?: string,
Sean McCullough86b56862025-04-18 13:04:03 -0700475 ): void {
476 this.connectionStatus = status;
477 this.connectionErrorMessage = errorMessage || "";
478 }
479
480 async _sendChat(e: CustomEvent) {
481 console.log("app shell: _sendChat", e);
482 const message = e.detail.message?.trim();
483 if (message == "") {
484 return;
485 }
486 try {
487 // Send the message to the server
488 const response = await fetch("chat", {
489 method: "POST",
490 headers: {
491 "Content-Type": "application/json",
492 },
493 body: JSON.stringify({ message }),
494 });
495
496 if (!response.ok) {
497 const errorData = await response.text();
498 throw new Error(`Server error: ${response.status} - ${errorData}`);
499 }
500 // Clear the input after successfully sending the message.
501 this.chatMessageText = "";
502
503 // Reset data manager state to force a full refresh after sending a message
504 // This ensures we get all messages in the correct order
505 // Use private API for now - TODO: add a resetState() method to DataManager
506 (this.dataManager as any).nextFetchIndex = 0;
507 (this.dataManager as any).currentFetchStartIndex = 0;
508
Sean McCullough86b56862025-04-18 13:04:03 -0700509 // // If in diff view, switch to conversation view
510 // if (this.viewMode === "diff") {
511 // await this.toggleViewMode("chat");
512 // }
513
514 // Refresh the timeline data to show the new message
515 await this.dataManager.fetchData();
Sean McCullough86b56862025-04-18 13:04:03 -0700516 } catch (error) {
517 console.error("Error sending chat message:", error);
518 const statusText = document.getElementById("statusText");
519 if (statusText) {
520 statusText.textContent = "Error sending message";
521 }
522 }
523 }
524
525 render() {
526 return html`
527 <div class="top-banner">
528 <div class="title-container">
529 <h1 class="banner-title">sketch</h1>
530 <h2 id="chatTitle" class="chat-title">${this.title}</h2>
531 </div>
532
533 <sketch-container-status
534 .state=${this.containerState}
535 ></sketch-container-status>
536
537 <div class="refresh-control">
538 <sketch-view-mode-select></sketch-view-mode-select>
539
540 <button id="stopButton" class="refresh-button stop-button">
541 Stop
542 </button>
543
544 <div class="poll-updates">
545 <input type="checkbox" id="pollToggle" checked />
546 <label for="pollToggle">Poll</label>
547 </div>
548
549 <sketch-network-status
550 message=${this.messageStatus}
551 connection=${this.connectionStatus}
552 error=${this.connectionErrorMessage}
553 ></sketch-network-status>
554 </div>
555 </div>
556
557 <div class="view-container">
558 <div class="chat-view ${this.viewMode === "chat" ? "view-active" : ""}">
Sean McCullough2c5bba42025-04-20 19:33:17 -0700559 <sketch-timeline
560 .messages=${this.messages}
561 .scrollContainer=${this}
562 ></sketch-timeline>
Sean McCullough86b56862025-04-18 13:04:03 -0700563 </div>
564
565 <div class="diff-view ${this.viewMode === "diff" ? "view-active" : ""}">
566 <sketch-diff-view
567 .commitHash=${this.currentCommitHash}
568 ></sketch-diff-view>
569 </div>
570
571 <div
572 class="chart-view ${this.viewMode === "charts" ? "view-active" : ""}"
573 >
574 <sketch-charts .messages=${this.messages}></sketch-charts>
575 </div>
576
577 <div
578 class="terminal-view ${this.viewMode === "terminal"
579 ? "view-active"
580 : ""}"
581 >
582 <sketch-terminal></sketch-terminal>
583 </div>
584 </div>
585
586 <sketch-chat-input
587 .content=${this.chatMessageText}
588 @send-chat="${this._sendChat}"
589 ></sketch-chat-input>
590 `;
591 }
592
593 /**
Sean McCullough86b56862025-04-18 13:04:03 -0700594 * Lifecycle callback when component is first connected to DOM
595 */
596 firstUpdated(): void {
597 if (this.viewMode !== "chat") {
598 return;
599 }
600
601 // Initial scroll to bottom when component is first rendered
602 setTimeout(
603 () => this.scrollTo({ top: this.scrollHeight, behavior: "smooth" }),
Philip Zeyliger72682df2025-04-23 13:09:46 -0700604 50,
Sean McCullough86b56862025-04-18 13:04:03 -0700605 );
606
Sean McCullough71941bd2025-04-18 13:31:48 -0700607 const pollToggleCheckbox = this.renderRoot?.querySelector(
Philip Zeyliger72682df2025-04-23 13:09:46 -0700608 "#pollToggle",
Sean McCullough71941bd2025-04-18 13:31:48 -0700609 ) as HTMLInputElement;
Sean McCullough86b56862025-04-18 13:04:03 -0700610 pollToggleCheckbox?.addEventListener("change", () => {
611 this.dataManager.setPollingEnabled(pollToggleCheckbox.checked);
612 if (!pollToggleCheckbox.checked) {
613 this.connectionStatus = "disabled";
614 this.messageStatus = "Polling stopped";
615 } else {
616 this.messageStatus = "Polling for updates...";
617 }
618 });
619 }
620}
621
622declare global {
623 interface HTMLElementTagNameMap {
624 "sketch-app-shell": SketchAppShell;
625 }
626}