blob: 8f57d75ee087798ec65528ee55f14ffd5e9626b6 [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",
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100230 this.handleDataChanged.bind(this)
Sean McCullough86b56862025-04-18 13:04:03 -0700231 );
232 this.dataManager.addEventListener(
233 "connectionStatusChanged",
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100234 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",
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100254 this.handleDataChanged.bind(this)
Sean McCullough86b56862025-04-18 13:04:03 -0700255 );
256 this.dataManager.removeEventListener(
257 "connectionStatusChanged",
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100258 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(
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100280 ".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
326 // Find the chat input textarea
327 const chatInput = this.shadowRoot?.querySelector("sketch-chat-input");
328 if (chatInput) {
329 // Update the chat input content using property
330 const currentContent = chatInput.getAttribute("content") || "";
331 const newContent = currentContent
332 ? `${currentContent}\n\n${comment}`
333 : comment;
334 chatInput.setAttribute("content", newContent);
335
336 // Dispatch an event to update the textarea value in the chat input component
337 const updateEvent = new CustomEvent("update-content", {
338 detail: { content: newContent },
339 bubbles: true,
340 composed: true,
341 });
342 chatInput.dispatchEvent(updateEvent);
343
344 // Switch back to chat view
345 this.toggleViewMode("chat", true);
346 }
347 }
348
349 /**
350 * Listen for commit diff event
351 * @param commitHash The commit hash to show diff for
352 */
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100353 private showCommitDiff(commitHash: string): void {
Sean McCullough86b56862025-04-18 13:04:03 -0700354 // Store the commit hash
355 this.currentCommitHash = commitHash;
356
357 // Switch to diff view
Sean McCullough71941bd2025-04-18 13:31:48 -0700358 this.toggleViewMode("diff", true);
Sean McCullough86b56862025-04-18 13:04:03 -0700359
360 // Wait for DOM update to complete
361 this.updateComplete.then(() => {
362 // Get the diff view component
363 const diffView = this.shadowRoot?.querySelector("sketch-diff-view");
364 if (diffView) {
365 // Call the showCommitDiff method
366 (diffView as any).showCommitDiff(commitHash);
367 }
368 });
369 }
370
371 /**
372 * Toggle between different view modes: chat, diff, charts, terminal
373 */
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100374 private toggleViewMode(mode: ViewMode, updateHistory: boolean): void {
Sean McCullough86b56862025-04-18 13:04:03 -0700375 // Don't do anything if the mode is already active
376 if (this.viewMode === mode) return;
377
378 // Update the view mode
379 this.viewMode = mode;
380
381 if (updateHistory) {
382 // Update URL with the current view mode
383 this.updateUrlForViewMode(mode);
384 }
385
386 // Wait for DOM update to complete
387 this.updateComplete.then(() => {
388 // Update active view
389 const viewContainer = this.shadowRoot?.querySelector(".view-container");
390 const chatView = this.shadowRoot?.querySelector(".chat-view");
391 const diffView = this.shadowRoot?.querySelector(".diff-view");
392 const chartView = this.shadowRoot?.querySelector(".chart-view");
393 const terminalView = this.shadowRoot?.querySelector(".terminal-view");
394
395 // Remove active class from all views
396 chatView?.classList.remove("view-active");
397 diffView?.classList.remove("view-active");
398 chartView?.classList.remove("view-active");
399 terminalView?.classList.remove("view-active");
400
401 // Add/remove diff-active class on view container
402 if (mode === "diff") {
403 viewContainer?.classList.add("diff-active");
404 } else {
405 viewContainer?.classList.remove("diff-active");
406 }
407
408 // Add active class to the selected view
409 switch (mode) {
410 case "chat":
411 chatView?.classList.add("view-active");
412 break;
413 case "diff":
414 diffView?.classList.add("view-active");
415 // Load diff content if we have a diff view
416 const diffViewComp =
417 this.shadowRoot?.querySelector("sketch-diff-view");
418 if (diffViewComp && this.currentCommitHash) {
419 (diffViewComp as any).showCommitDiff(this.currentCommitHash);
420 } else if (diffViewComp) {
421 (diffViewComp as any).loadDiffContent();
422 }
423 break;
424 case "charts":
425 chartView?.classList.add("view-active");
426 break;
427 case "terminal":
428 terminalView?.classList.add("view-active");
429 break;
430 }
431
432 // Update view mode buttons
433 const viewModeSelect = this.shadowRoot?.querySelector(
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100434 "sketch-view-mode-select"
Sean McCullough86b56862025-04-18 13:04:03 -0700435 );
436 if (viewModeSelect) {
437 const event = new CustomEvent("update-active-mode", {
438 detail: { mode },
439 bubbles: true,
440 composed: true,
441 });
442 viewModeSelect.dispatchEvent(event);
443 }
444
445 // FIXME: This is a hack to get vega chart in sketch-charts.ts to work properly
446 // When the chart is in the background, its container has a width of 0, so vega
447 // renders width 0 and only changes that width on a resize event.
448 // See https://github.com/vega/react-vega/issues/85#issuecomment-1826421132
449 window.dispatchEvent(new Event("resize"));
450 });
451 }
452
Sean McCullough86b56862025-04-18 13:04:03 -0700453 private handleDataChanged(eventData: {
454 state: State;
Sean McCulloughd9f13372025-04-21 15:08:49 -0700455 newMessages: AgentMessage[];
Sean McCullough86b56862025-04-18 13:04:03 -0700456 isFirstFetch?: boolean;
457 }): void {
458 const { state, newMessages, isFirstFetch } = eventData;
459
460 // Check if this is the first data fetch or if there are new messages
461 if (isFirstFetch) {
Sean McCullough86b56862025-04-18 13:04:03 -0700462 this.messageStatus = "Initial messages loaded";
463 } else if (newMessages && newMessages.length > 0) {
Sean McCullough86b56862025-04-18 13:04:03 -0700464 this.messageStatus = "Updated just now";
Sean McCullough86b56862025-04-18 13:04:03 -0700465 } else {
466 this.messageStatus = "No new messages";
467 }
468
469 // Update state if we received it
470 if (state) {
471 this.containerState = state;
472 this.title = state.title;
473 }
474
475 // Create a copy of the current messages before updating
476 const oldMessageCount = this.messages.length;
477
478 // Update messages
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100479 this.messages = aggregateAgentMessages(this.messages, newMessages);
Sean McCullough86b56862025-04-18 13:04:03 -0700480
481 // Log information about the message update
482 if (this.messages.length > oldMessageCount) {
483 console.log(
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100484 `Auto-scroll: Messages updated from ${oldMessageCount} to ${this.messages.length}`
Sean McCullough86b56862025-04-18 13:04:03 -0700485 );
486 }
487 }
488
489 private handleConnectionStatusChanged(
490 status: ConnectionStatus,
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100491 errorMessage?: string
Sean McCullough86b56862025-04-18 13:04:03 -0700492 ): void {
493 this.connectionStatus = status;
494 this.connectionErrorMessage = errorMessage || "";
495 }
496
497 async _sendChat(e: CustomEvent) {
498 console.log("app shell: _sendChat", e);
499 const message = e.detail.message?.trim();
500 if (message == "") {
501 return;
502 }
503 try {
504 // Send the message to the server
505 const response = await fetch("chat", {
506 method: "POST",
507 headers: {
508 "Content-Type": "application/json",
509 },
510 body: JSON.stringify({ message }),
511 });
512
513 if (!response.ok) {
514 const errorData = await response.text();
515 throw new Error(`Server error: ${response.status} - ${errorData}`);
516 }
517 // Clear the input after successfully sending the message.
518 this.chatMessageText = "";
519
520 // Reset data manager state to force a full refresh after sending a message
521 // This ensures we get all messages in the correct order
522 // Use private API for now - TODO: add a resetState() method to DataManager
523 (this.dataManager as any).nextFetchIndex = 0;
524 (this.dataManager as any).currentFetchStartIndex = 0;
525
Sean McCullough86b56862025-04-18 13:04:03 -0700526 // // If in diff view, switch to conversation view
527 // if (this.viewMode === "diff") {
528 // await this.toggleViewMode("chat");
529 // }
530
531 // Refresh the timeline data to show the new message
532 await this.dataManager.fetchData();
Sean McCullough86b56862025-04-18 13:04:03 -0700533 } catch (error) {
534 console.error("Error sending chat message:", error);
535 const statusText = document.getElementById("statusText");
536 if (statusText) {
537 statusText.textContent = "Error sending message";
538 }
539 }
540 }
541
542 render() {
543 return html`
544 <div class="top-banner">
545 <div class="title-container">
546 <h1 class="banner-title">sketch</h1>
547 <h2 id="chatTitle" class="chat-title">${this.title}</h2>
548 </div>
549
550 <sketch-container-status
551 .state=${this.containerState}
552 ></sketch-container-status>
553
554 <div class="refresh-control">
555 <sketch-view-mode-select></sketch-view-mode-select>
556
557 <button id="stopButton" class="refresh-button stop-button">
558 Stop
559 </button>
560
561 <div class="poll-updates">
562 <input type="checkbox" id="pollToggle" checked />
563 <label for="pollToggle">Poll</label>
564 </div>
565
566 <sketch-network-status
567 message=${this.messageStatus}
568 connection=${this.connectionStatus}
569 error=${this.connectionErrorMessage}
570 ></sketch-network-status>
571 </div>
572 </div>
573
574 <div class="view-container">
575 <div class="chat-view ${this.viewMode === "chat" ? "view-active" : ""}">
Sean McCullough2c5bba42025-04-20 19:33:17 -0700576 <sketch-timeline
577 .messages=${this.messages}
578 .scrollContainer=${this}
579 ></sketch-timeline>
Sean McCullough86b56862025-04-18 13:04:03 -0700580 </div>
581
582 <div class="diff-view ${this.viewMode === "diff" ? "view-active" : ""}">
583 <sketch-diff-view
584 .commitHash=${this.currentCommitHash}
585 ></sketch-diff-view>
586 </div>
587
588 <div
589 class="chart-view ${this.viewMode === "charts" ? "view-active" : ""}"
590 >
591 <sketch-charts .messages=${this.messages}></sketch-charts>
592 </div>
593
594 <div
595 class="terminal-view ${this.viewMode === "terminal"
596 ? "view-active"
597 : ""}"
598 >
599 <sketch-terminal></sketch-terminal>
600 </div>
601 </div>
602
603 <sketch-chat-input
604 .content=${this.chatMessageText}
605 @send-chat="${this._sendChat}"
606 ></sketch-chat-input>
607 `;
608 }
609
610 /**
Sean McCullough86b56862025-04-18 13:04:03 -0700611 * Lifecycle callback when component is first connected to DOM
612 */
613 firstUpdated(): void {
614 if (this.viewMode !== "chat") {
615 return;
616 }
617
618 // Initial scroll to bottom when component is first rendered
619 setTimeout(
620 () => this.scrollTo({ top: this.scrollHeight, behavior: "smooth" }),
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100621 50
Sean McCullough86b56862025-04-18 13:04:03 -0700622 );
623
Sean McCullough71941bd2025-04-18 13:31:48 -0700624 const pollToggleCheckbox = this.renderRoot?.querySelector(
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100625 "#pollToggle"
Sean McCullough71941bd2025-04-18 13:31:48 -0700626 ) as HTMLInputElement;
Sean McCullough86b56862025-04-18 13:04:03 -0700627 pollToggleCheckbox?.addEventListener("change", () => {
628 this.dataManager.setPollingEnabled(pollToggleCheckbox.checked);
629 if (!pollToggleCheckbox.checked) {
630 this.connectionStatus = "disabled";
631 this.messageStatus = "Polling stopped";
632 } else {
633 this.messageStatus = "Polling for updates...";
634 }
635 });
636 }
637}
638
639declare global {
640 interface HTMLElementTagNameMap {
641 "sketch-app-shell": SketchAppShell;
642 }
643}