blob: 1dd3b6f6370d030cba9b9f569e07064e980b006f [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()
Sean McCullough86b56862025-04-18 13:04:03 -0700178 title: string = "";
179
180 private dataManager = new DataManager();
181
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100182 @property({ attribute: false })
Sean McCulloughd9f13372025-04-21 15:08:49 -0700183 containerState: State = {
184 title: "",
185 os: "",
186 message_count: 0,
187 hostname: "",
188 working_dir: "",
189 initial_commit: "",
190 };
Sean McCullough86b56862025-04-18 13:04:03 -0700191
Sean McCullough86b56862025-04-18 13:04:03 -0700192 // Mutation observer to detect when new messages are added
193 private mutationObserver: MutationObserver | null = null;
194
195 constructor() {
196 super();
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100197 console.log("Hello!");
Sean McCullough86b56862025-04-18 13:04:03 -0700198
199 // Binding methods to this
200 this._handleViewModeSelect = this._handleViewModeSelect.bind(this);
Sean McCullough86b56862025-04-18 13:04:03 -0700201 this._handleShowCommitDiff = this._handleShowCommitDiff.bind(this);
202 this._handlePopState = this._handlePopState.bind(this);
203 }
204
205 // See https://lit.dev/docs/components/lifecycle/
206 connectedCallback() {
207 super.connectedCallback();
208
209 // Initialize client-side nav history.
210 const url = new URL(window.location.href);
211 const mode = url.searchParams.get("view") || "chat";
212 window.history.replaceState({ mode }, "", url.toString());
213
214 this.toggleViewMode(mode as ViewMode, false);
215 // Add popstate event listener to handle browser back/forward navigation
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100216 window.addEventListener("popstate", this._handlePopState);
Sean McCullough86b56862025-04-18 13:04:03 -0700217
218 // Add event listeners
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100219 window.addEventListener("view-mode-select", this._handleViewModeSelect);
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100220 window.addEventListener("show-commit-diff", this._handleShowCommitDiff);
Sean McCullough86b56862025-04-18 13:04:03 -0700221
222 // register event listeners
223 this.dataManager.addEventListener(
224 "dataChanged",
Philip Zeyliger72682df2025-04-23 13:09:46 -0700225 this.handleDataChanged.bind(this),
Sean McCullough86b56862025-04-18 13:04:03 -0700226 );
227 this.dataManager.addEventListener(
228 "connectionStatusChanged",
Philip Zeyliger72682df2025-04-23 13:09:46 -0700229 this.handleConnectionStatusChanged.bind(this),
Sean McCullough86b56862025-04-18 13:04:03 -0700230 );
231
232 // Initialize the data manager
233 this.dataManager.initialize();
234 }
235
236 // See https://lit.dev/docs/components/lifecycle/
237 disconnectedCallback() {
238 super.disconnectedCallback();
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100239 window.removeEventListener("popstate", this._handlePopState);
Sean McCullough86b56862025-04-18 13:04:03 -0700240
241 // Remove event listeners
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100242 window.removeEventListener("view-mode-select", this._handleViewModeSelect);
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100243 window.removeEventListener("show-commit-diff", this._handleShowCommitDiff);
Sean McCullough86b56862025-04-18 13:04:03 -0700244
245 // unregister data manager event listeners
246 this.dataManager.removeEventListener(
247 "dataChanged",
Philip Zeyliger72682df2025-04-23 13:09:46 -0700248 this.handleDataChanged.bind(this),
Sean McCullough86b56862025-04-18 13:04:03 -0700249 );
250 this.dataManager.removeEventListener(
251 "connectionStatusChanged",
Philip Zeyliger72682df2025-04-23 13:09:46 -0700252 this.handleConnectionStatusChanged.bind(this),
Sean McCullough86b56862025-04-18 13:04:03 -0700253 );
254
255 // Disconnect mutation observer if it exists
256 if (this.mutationObserver) {
257 console.log("Auto-scroll: Disconnecting mutation observer");
258 this.mutationObserver.disconnect();
259 this.mutationObserver = null;
260 }
261 }
262
Sean McCullough71941bd2025-04-18 13:31:48 -0700263 updateUrlForViewMode(mode: "chat" | "diff" | "charts" | "terminal"): void {
Sean McCullough86b56862025-04-18 13:04:03 -0700264 // Get the current URL without search parameters
265 const url = new URL(window.location.href);
266
267 // Clear existing parameters
268 url.search = "";
269
270 // Only add view parameter if not in default chat view
271 if (mode !== "chat") {
272 url.searchParams.set("view", mode);
Sean McCullough71941bd2025-04-18 13:31:48 -0700273 const diffView = this.shadowRoot?.querySelector(
Philip Zeyliger72682df2025-04-23 13:09:46 -0700274 ".diff-view",
Sean McCullough71941bd2025-04-18 13:31:48 -0700275 ) as SketchDiffView;
Sean McCullough86b56862025-04-18 13:04:03 -0700276
277 // If in diff view and there's a commit hash, include that too
278 if (mode === "diff" && diffView.commitHash) {
279 url.searchParams.set("commit", diffView.commitHash);
280 }
281 }
282
283 // Update the browser history without reloading the page
284 window.history.pushState({ mode }, "", url.toString());
285 }
286
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100287 private _handlePopState(event: PopStateEvent) {
Sean McCullough86b56862025-04-18 13:04:03 -0700288 if (event.state && event.state.mode) {
289 this.toggleViewMode(event.state.mode, false);
290 } else {
291 this.toggleViewMode("chat", false);
292 }
293 }
294
295 /**
296 * Handle view mode selection event
297 */
298 private _handleViewModeSelect(event: CustomEvent) {
299 const mode = event.detail.mode as "chat" | "diff" | "charts" | "terminal";
300 this.toggleViewMode(mode, true);
301 }
302
303 /**
304 * Handle show commit diff event
305 */
306 private _handleShowCommitDiff(event: CustomEvent) {
307 const { commitHash } = event.detail;
308 if (commitHash) {
309 this.showCommitDiff(commitHash);
310 }
311 }
312
313 /**
Sean McCullough86b56862025-04-18 13:04:03 -0700314 * Listen for commit diff event
315 * @param commitHash The commit hash to show diff for
316 */
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100317 private showCommitDiff(commitHash: string): void {
Sean McCullough86b56862025-04-18 13:04:03 -0700318 // Store the commit hash
319 this.currentCommitHash = commitHash;
320
321 // Switch to diff view
Sean McCullough71941bd2025-04-18 13:31:48 -0700322 this.toggleViewMode("diff", true);
Sean McCullough86b56862025-04-18 13:04:03 -0700323
324 // Wait for DOM update to complete
325 this.updateComplete.then(() => {
326 // Get the diff view component
327 const diffView = this.shadowRoot?.querySelector("sketch-diff-view");
328 if (diffView) {
329 // Call the showCommitDiff method
330 (diffView as any).showCommitDiff(commitHash);
331 }
332 });
333 }
334
335 /**
336 * Toggle between different view modes: chat, diff, charts, terminal
337 */
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100338 private toggleViewMode(mode: ViewMode, updateHistory: boolean): void {
Sean McCullough86b56862025-04-18 13:04:03 -0700339 // Don't do anything if the mode is already active
340 if (this.viewMode === mode) return;
341
342 // Update the view mode
343 this.viewMode = mode;
344
345 if (updateHistory) {
346 // Update URL with the current view mode
347 this.updateUrlForViewMode(mode);
348 }
349
350 // Wait for DOM update to complete
351 this.updateComplete.then(() => {
352 // Update active view
353 const viewContainer = this.shadowRoot?.querySelector(".view-container");
354 const chatView = this.shadowRoot?.querySelector(".chat-view");
355 const diffView = this.shadowRoot?.querySelector(".diff-view");
356 const chartView = this.shadowRoot?.querySelector(".chart-view");
357 const terminalView = this.shadowRoot?.querySelector(".terminal-view");
358
359 // Remove active class from all views
360 chatView?.classList.remove("view-active");
361 diffView?.classList.remove("view-active");
362 chartView?.classList.remove("view-active");
363 terminalView?.classList.remove("view-active");
364
365 // Add/remove diff-active class on view container
366 if (mode === "diff") {
367 viewContainer?.classList.add("diff-active");
368 } else {
369 viewContainer?.classList.remove("diff-active");
370 }
371
372 // Add active class to the selected view
373 switch (mode) {
374 case "chat":
375 chatView?.classList.add("view-active");
376 break;
377 case "diff":
378 diffView?.classList.add("view-active");
379 // Load diff content if we have a diff view
380 const diffViewComp =
381 this.shadowRoot?.querySelector("sketch-diff-view");
382 if (diffViewComp && this.currentCommitHash) {
383 (diffViewComp as any).showCommitDiff(this.currentCommitHash);
384 } else if (diffViewComp) {
385 (diffViewComp as any).loadDiffContent();
386 }
387 break;
388 case "charts":
389 chartView?.classList.add("view-active");
390 break;
391 case "terminal":
392 terminalView?.classList.add("view-active");
393 break;
394 }
395
396 // Update view mode buttons
397 const viewModeSelect = this.shadowRoot?.querySelector(
Philip Zeyliger72682df2025-04-23 13:09:46 -0700398 "sketch-view-mode-select",
Sean McCullough86b56862025-04-18 13:04:03 -0700399 );
400 if (viewModeSelect) {
401 const event = new CustomEvent("update-active-mode", {
402 detail: { mode },
403 bubbles: true,
404 composed: true,
405 });
406 viewModeSelect.dispatchEvent(event);
407 }
408
409 // FIXME: This is a hack to get vega chart in sketch-charts.ts to work properly
410 // When the chart is in the background, its container has a width of 0, so vega
411 // renders width 0 and only changes that width on a resize event.
412 // See https://github.com/vega/react-vega/issues/85#issuecomment-1826421132
413 window.dispatchEvent(new Event("resize"));
414 });
415 }
416
Sean McCullough86b56862025-04-18 13:04:03 -0700417 private handleDataChanged(eventData: {
418 state: State;
Sean McCulloughd9f13372025-04-21 15:08:49 -0700419 newMessages: AgentMessage[];
Sean McCullough86b56862025-04-18 13:04:03 -0700420 isFirstFetch?: boolean;
421 }): void {
422 const { state, newMessages, isFirstFetch } = eventData;
423
424 // Check if this is the first data fetch or if there are new messages
425 if (isFirstFetch) {
Sean McCullough86b56862025-04-18 13:04:03 -0700426 this.messageStatus = "Initial messages loaded";
427 } else if (newMessages && newMessages.length > 0) {
Sean McCullough86b56862025-04-18 13:04:03 -0700428 this.messageStatus = "Updated just now";
Sean McCullough86b56862025-04-18 13:04:03 -0700429 } else {
430 this.messageStatus = "No new messages";
431 }
432
433 // Update state if we received it
434 if (state) {
435 this.containerState = state;
436 this.title = state.title;
437 }
438
439 // Create a copy of the current messages before updating
440 const oldMessageCount = this.messages.length;
441
442 // Update messages
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100443 this.messages = aggregateAgentMessages(this.messages, newMessages);
Sean McCullough86b56862025-04-18 13:04:03 -0700444
445 // Log information about the message update
446 if (this.messages.length > oldMessageCount) {
447 console.log(
Philip Zeyliger72682df2025-04-23 13:09:46 -0700448 `Auto-scroll: Messages updated from ${oldMessageCount} to ${this.messages.length}`,
Sean McCullough86b56862025-04-18 13:04:03 -0700449 );
450 }
451 }
452
453 private handleConnectionStatusChanged(
454 status: ConnectionStatus,
Philip Zeyliger72682df2025-04-23 13:09:46 -0700455 errorMessage?: string,
Sean McCullough86b56862025-04-18 13:04:03 -0700456 ): void {
457 this.connectionStatus = status;
458 this.connectionErrorMessage = errorMessage || "";
459 }
460
461 async _sendChat(e: CustomEvent) {
462 console.log("app shell: _sendChat", e);
463 const message = e.detail.message?.trim();
464 if (message == "") {
465 return;
466 }
467 try {
468 // Send the message to the server
469 const response = await fetch("chat", {
470 method: "POST",
471 headers: {
472 "Content-Type": "application/json",
473 },
474 body: JSON.stringify({ message }),
475 });
476
477 if (!response.ok) {
478 const errorData = await response.text();
479 throw new Error(`Server error: ${response.status} - ${errorData}`);
480 }
Sean McCullough86b56862025-04-18 13:04:03 -0700481
Philip Zeyliger73db6052025-04-23 13:09:07 -0700482 // TOOD(philip): If the data manager is getting messages out of order, there's a bug?
Sean McCullough86b56862025-04-18 13:04:03 -0700483 // Reset data manager state to force a full refresh after sending a message
484 // This ensures we get all messages in the correct order
485 // Use private API for now - TODO: add a resetState() method to DataManager
486 (this.dataManager as any).nextFetchIndex = 0;
487 (this.dataManager as any).currentFetchStartIndex = 0;
488
Sean McCullough86b56862025-04-18 13:04:03 -0700489 // // If in diff view, switch to conversation view
490 // if (this.viewMode === "diff") {
491 // await this.toggleViewMode("chat");
492 // }
493
494 // Refresh the timeline data to show the new message
495 await this.dataManager.fetchData();
Sean McCullough86b56862025-04-18 13:04:03 -0700496 } catch (error) {
497 console.error("Error sending chat message:", error);
498 const statusText = document.getElementById("statusText");
499 if (statusText) {
500 statusText.textContent = "Error sending message";
501 }
502 }
503 }
504
505 render() {
506 return html`
507 <div class="top-banner">
508 <div class="title-container">
509 <h1 class="banner-title">sketch</h1>
510 <h2 id="chatTitle" class="chat-title">${this.title}</h2>
511 </div>
512
513 <sketch-container-status
514 .state=${this.containerState}
515 ></sketch-container-status>
516
517 <div class="refresh-control">
518 <sketch-view-mode-select></sketch-view-mode-select>
519
520 <button id="stopButton" class="refresh-button stop-button">
521 Stop
522 </button>
523
524 <div class="poll-updates">
525 <input type="checkbox" id="pollToggle" checked />
526 <label for="pollToggle">Poll</label>
527 </div>
528
529 <sketch-network-status
530 message=${this.messageStatus}
531 connection=${this.connectionStatus}
532 error=${this.connectionErrorMessage}
533 ></sketch-network-status>
534 </div>
535 </div>
536
537 <div class="view-container">
538 <div class="chat-view ${this.viewMode === "chat" ? "view-active" : ""}">
Sean McCullough2c5bba42025-04-20 19:33:17 -0700539 <sketch-timeline
540 .messages=${this.messages}
541 .scrollContainer=${this}
542 ></sketch-timeline>
Sean McCullough86b56862025-04-18 13:04:03 -0700543 </div>
544
545 <div class="diff-view ${this.viewMode === "diff" ? "view-active" : ""}">
546 <sketch-diff-view
547 .commitHash=${this.currentCommitHash}
548 ></sketch-diff-view>
549 </div>
550
551 <div
552 class="chart-view ${this.viewMode === "charts" ? "view-active" : ""}"
553 >
554 <sketch-charts .messages=${this.messages}></sketch-charts>
555 </div>
556
557 <div
558 class="terminal-view ${this.viewMode === "terminal"
559 ? "view-active"
560 : ""}"
561 >
562 <sketch-terminal></sketch-terminal>
563 </div>
564 </div>
565
Philip Zeyliger73db6052025-04-23 13:09:07 -0700566 <sketch-chat-input @send-chat="${this._sendChat}"></sketch-chat-input>
Sean McCullough86b56862025-04-18 13:04:03 -0700567 `;
568 }
569
570 /**
Sean McCullough86b56862025-04-18 13:04:03 -0700571 * Lifecycle callback when component is first connected to DOM
572 */
573 firstUpdated(): void {
574 if (this.viewMode !== "chat") {
575 return;
576 }
577
578 // Initial scroll to bottom when component is first rendered
579 setTimeout(
580 () => this.scrollTo({ top: this.scrollHeight, behavior: "smooth" }),
Philip Zeyliger72682df2025-04-23 13:09:46 -0700581 50,
Sean McCullough86b56862025-04-18 13:04:03 -0700582 );
583
Sean McCullough71941bd2025-04-18 13:31:48 -0700584 const pollToggleCheckbox = this.renderRoot?.querySelector(
Philip Zeyliger72682df2025-04-23 13:09:46 -0700585 "#pollToggle",
Sean McCullough71941bd2025-04-18 13:31:48 -0700586 ) as HTMLInputElement;
Sean McCullough86b56862025-04-18 13:04:03 -0700587 pollToggleCheckbox?.addEventListener("change", () => {
588 this.dataManager.setPollingEnabled(pollToggleCheckbox.checked);
589 if (!pollToggleCheckbox.checked) {
590 this.connectionStatus = "disabled";
591 this.messageStatus = "Polling stopped";
592 } else {
593 this.messageStatus = "Polling for updates...";
594 }
595 });
596 }
597}
598
599declare global {
600 interface HTMLElementTagNameMap {
601 "sketch-app-shell": SketchAppShell;
602 }
603}