blob: 61b14a82efce6dd425f97fe7696064db9c418b5e [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();
197
198 // Binding methods to this
199 this._handleViewModeSelect = this._handleViewModeSelect.bind(this);
Sean McCullough86b56862025-04-18 13:04:03 -0700200 this._handleShowCommitDiff = this._handleShowCommitDiff.bind(this);
201 this._handlePopState = this._handlePopState.bind(this);
202 }
203
204 // See https://lit.dev/docs/components/lifecycle/
205 connectedCallback() {
206 super.connectedCallback();
207
208 // Initialize client-side nav history.
209 const url = new URL(window.location.href);
210 const mode = url.searchParams.get("view") || "chat";
211 window.history.replaceState({ mode }, "", url.toString());
212
213 this.toggleViewMode(mode as ViewMode, false);
214 // Add popstate event listener to handle browser back/forward navigation
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100215 window.addEventListener("popstate", this._handlePopState);
Sean McCullough86b56862025-04-18 13:04:03 -0700216
217 // Add event listeners
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100218 window.addEventListener("view-mode-select", this._handleViewModeSelect);
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100219 window.addEventListener("show-commit-diff", this._handleShowCommitDiff);
Sean McCullough86b56862025-04-18 13:04:03 -0700220
221 // register event listeners
222 this.dataManager.addEventListener(
223 "dataChanged",
Philip Zeyliger72682df2025-04-23 13:09:46 -0700224 this.handleDataChanged.bind(this),
Sean McCullough86b56862025-04-18 13:04:03 -0700225 );
226 this.dataManager.addEventListener(
227 "connectionStatusChanged",
Philip Zeyliger72682df2025-04-23 13:09:46 -0700228 this.handleConnectionStatusChanged.bind(this),
Sean McCullough86b56862025-04-18 13:04:03 -0700229 );
230
231 // Initialize the data manager
232 this.dataManager.initialize();
233 }
234
235 // See https://lit.dev/docs/components/lifecycle/
236 disconnectedCallback() {
237 super.disconnectedCallback();
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100238 window.removeEventListener("popstate", this._handlePopState);
Sean McCullough86b56862025-04-18 13:04:03 -0700239
240 // Remove event listeners
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100241 window.removeEventListener("view-mode-select", this._handleViewModeSelect);
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100242 window.removeEventListener("show-commit-diff", this._handleShowCommitDiff);
Sean McCullough86b56862025-04-18 13:04:03 -0700243
244 // unregister data manager event listeners
245 this.dataManager.removeEventListener(
246 "dataChanged",
Philip Zeyliger72682df2025-04-23 13:09:46 -0700247 this.handleDataChanged.bind(this),
Sean McCullough86b56862025-04-18 13:04:03 -0700248 );
249 this.dataManager.removeEventListener(
250 "connectionStatusChanged",
Philip Zeyliger72682df2025-04-23 13:09:46 -0700251 this.handleConnectionStatusChanged.bind(this),
Sean McCullough86b56862025-04-18 13:04:03 -0700252 );
253
254 // Disconnect mutation observer if it exists
255 if (this.mutationObserver) {
Sean McCullough86b56862025-04-18 13:04:03 -0700256 this.mutationObserver.disconnect();
257 this.mutationObserver = null;
258 }
259 }
260
Sean McCullough71941bd2025-04-18 13:31:48 -0700261 updateUrlForViewMode(mode: "chat" | "diff" | "charts" | "terminal"): void {
Sean McCullough86b56862025-04-18 13:04:03 -0700262 // Get the current URL without search parameters
263 const url = new URL(window.location.href);
264
265 // Clear existing parameters
266 url.search = "";
267
268 // Only add view parameter if not in default chat view
269 if (mode !== "chat") {
270 url.searchParams.set("view", mode);
Sean McCullough71941bd2025-04-18 13:31:48 -0700271 const diffView = this.shadowRoot?.querySelector(
Philip Zeyliger72682df2025-04-23 13:09:46 -0700272 ".diff-view",
Sean McCullough71941bd2025-04-18 13:31:48 -0700273 ) as SketchDiffView;
Sean McCullough86b56862025-04-18 13:04:03 -0700274
275 // If in diff view and there's a commit hash, include that too
276 if (mode === "diff" && diffView.commitHash) {
277 url.searchParams.set("commit", diffView.commitHash);
278 }
279 }
280
281 // Update the browser history without reloading the page
282 window.history.pushState({ mode }, "", url.toString());
283 }
284
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100285 private _handlePopState(event: PopStateEvent) {
Sean McCullough86b56862025-04-18 13:04:03 -0700286 if (event.state && event.state.mode) {
287 this.toggleViewMode(event.state.mode, false);
288 } else {
289 this.toggleViewMode("chat", false);
290 }
291 }
292
293 /**
294 * Handle view mode selection event
295 */
296 private _handleViewModeSelect(event: CustomEvent) {
297 const mode = event.detail.mode as "chat" | "diff" | "charts" | "terminal";
298 this.toggleViewMode(mode, true);
299 }
300
301 /**
302 * Handle show commit diff event
303 */
304 private _handleShowCommitDiff(event: CustomEvent) {
305 const { commitHash } = event.detail;
306 if (commitHash) {
307 this.showCommitDiff(commitHash);
308 }
309 }
310
311 /**
Sean McCullough86b56862025-04-18 13:04:03 -0700312 * Listen for commit diff event
313 * @param commitHash The commit hash to show diff for
314 */
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100315 private showCommitDiff(commitHash: string): void {
Sean McCullough86b56862025-04-18 13:04:03 -0700316 // Store the commit hash
317 this.currentCommitHash = commitHash;
318
319 // Switch to diff view
Sean McCullough71941bd2025-04-18 13:31:48 -0700320 this.toggleViewMode("diff", true);
Sean McCullough86b56862025-04-18 13:04:03 -0700321
322 // Wait for DOM update to complete
323 this.updateComplete.then(() => {
324 // Get the diff view component
325 const diffView = this.shadowRoot?.querySelector("sketch-diff-view");
326 if (diffView) {
327 // Call the showCommitDiff method
328 (diffView as any).showCommitDiff(commitHash);
329 }
330 });
331 }
332
333 /**
334 * Toggle between different view modes: chat, diff, charts, terminal
335 */
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100336 private toggleViewMode(mode: ViewMode, updateHistory: boolean): void {
Sean McCullough86b56862025-04-18 13:04:03 -0700337 // Don't do anything if the mode is already active
338 if (this.viewMode === mode) return;
339
340 // Update the view mode
341 this.viewMode = mode;
342
343 if (updateHistory) {
344 // Update URL with the current view mode
345 this.updateUrlForViewMode(mode);
346 }
347
348 // Wait for DOM update to complete
349 this.updateComplete.then(() => {
350 // Update active view
351 const viewContainer = this.shadowRoot?.querySelector(".view-container");
352 const chatView = this.shadowRoot?.querySelector(".chat-view");
353 const diffView = this.shadowRoot?.querySelector(".diff-view");
354 const chartView = this.shadowRoot?.querySelector(".chart-view");
355 const terminalView = this.shadowRoot?.querySelector(".terminal-view");
356
357 // Remove active class from all views
358 chatView?.classList.remove("view-active");
359 diffView?.classList.remove("view-active");
360 chartView?.classList.remove("view-active");
361 terminalView?.classList.remove("view-active");
362
363 // Add/remove diff-active class on view container
364 if (mode === "diff") {
365 viewContainer?.classList.add("diff-active");
366 } else {
367 viewContainer?.classList.remove("diff-active");
368 }
369
370 // Add active class to the selected view
371 switch (mode) {
372 case "chat":
373 chatView?.classList.add("view-active");
374 break;
375 case "diff":
376 diffView?.classList.add("view-active");
377 // Load diff content if we have a diff view
378 const diffViewComp =
379 this.shadowRoot?.querySelector("sketch-diff-view");
380 if (diffViewComp && this.currentCommitHash) {
381 (diffViewComp as any).showCommitDiff(this.currentCommitHash);
382 } else if (diffViewComp) {
383 (diffViewComp as any).loadDiffContent();
384 }
385 break;
386 case "charts":
387 chartView?.classList.add("view-active");
388 break;
389 case "terminal":
390 terminalView?.classList.add("view-active");
391 break;
392 }
393
394 // Update view mode buttons
395 const viewModeSelect = this.shadowRoot?.querySelector(
Philip Zeyliger72682df2025-04-23 13:09:46 -0700396 "sketch-view-mode-select",
Sean McCullough86b56862025-04-18 13:04:03 -0700397 );
398 if (viewModeSelect) {
399 const event = new CustomEvent("update-active-mode", {
400 detail: { mode },
401 bubbles: true,
402 composed: true,
403 });
404 viewModeSelect.dispatchEvent(event);
405 }
406
407 // FIXME: This is a hack to get vega chart in sketch-charts.ts to work properly
408 // When the chart is in the background, its container has a width of 0, so vega
409 // renders width 0 and only changes that width on a resize event.
410 // See https://github.com/vega/react-vega/issues/85#issuecomment-1826421132
411 window.dispatchEvent(new Event("resize"));
412 });
413 }
414
Sean McCullough86b56862025-04-18 13:04:03 -0700415 private handleDataChanged(eventData: {
416 state: State;
Sean McCulloughd9f13372025-04-21 15:08:49 -0700417 newMessages: AgentMessage[];
Sean McCullough86b56862025-04-18 13:04:03 -0700418 isFirstFetch?: boolean;
419 }): void {
420 const { state, newMessages, isFirstFetch } = eventData;
421
422 // Check if this is the first data fetch or if there are new messages
423 if (isFirstFetch) {
Sean McCullough86b56862025-04-18 13:04:03 -0700424 this.messageStatus = "Initial messages loaded";
425 } else if (newMessages && newMessages.length > 0) {
Sean McCullough86b56862025-04-18 13:04:03 -0700426 this.messageStatus = "Updated just now";
Sean McCullough86b56862025-04-18 13:04:03 -0700427 } else {
428 this.messageStatus = "No new messages";
429 }
430
431 // Update state if we received it
432 if (state) {
433 this.containerState = state;
434 this.title = state.title;
435 }
436
Sean McCullough86b56862025-04-18 13:04:03 -0700437 // Update messages
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100438 this.messages = aggregateAgentMessages(this.messages, newMessages);
Sean McCullough86b56862025-04-18 13:04:03 -0700439 }
440
441 private handleConnectionStatusChanged(
442 status: ConnectionStatus,
Philip Zeyliger72682df2025-04-23 13:09:46 -0700443 errorMessage?: string,
Sean McCullough86b56862025-04-18 13:04:03 -0700444 ): void {
445 this.connectionStatus = status;
446 this.connectionErrorMessage = errorMessage || "";
447 }
448
449 async _sendChat(e: CustomEvent) {
450 console.log("app shell: _sendChat", e);
451 const message = e.detail.message?.trim();
452 if (message == "") {
453 return;
454 }
455 try {
456 // Send the message to the server
457 const response = await fetch("chat", {
458 method: "POST",
459 headers: {
460 "Content-Type": "application/json",
461 },
462 body: JSON.stringify({ message }),
463 });
464
465 if (!response.ok) {
466 const errorData = await response.text();
467 throw new Error(`Server error: ${response.status} - ${errorData}`);
468 }
Sean McCullough86b56862025-04-18 13:04:03 -0700469
Philip Zeyliger73db6052025-04-23 13:09:07 -0700470 // TOOD(philip): If the data manager is getting messages out of order, there's a bug?
Sean McCullough86b56862025-04-18 13:04:03 -0700471 // Reset data manager state to force a full refresh after sending a message
472 // This ensures we get all messages in the correct order
473 // Use private API for now - TODO: add a resetState() method to DataManager
474 (this.dataManager as any).nextFetchIndex = 0;
475 (this.dataManager as any).currentFetchStartIndex = 0;
476
Sean McCullough86b56862025-04-18 13:04:03 -0700477 // // If in diff view, switch to conversation view
478 // if (this.viewMode === "diff") {
479 // await this.toggleViewMode("chat");
480 // }
481
482 // Refresh the timeline data to show the new message
483 await this.dataManager.fetchData();
Sean McCullough86b56862025-04-18 13:04:03 -0700484 } catch (error) {
485 console.error("Error sending chat message:", error);
486 const statusText = document.getElementById("statusText");
487 if (statusText) {
488 statusText.textContent = "Error sending message";
489 }
490 }
491 }
492
493 render() {
494 return html`
495 <div class="top-banner">
496 <div class="title-container">
497 <h1 class="banner-title">sketch</h1>
498 <h2 id="chatTitle" class="chat-title">${this.title}</h2>
499 </div>
500
501 <sketch-container-status
502 .state=${this.containerState}
503 ></sketch-container-status>
504
505 <div class="refresh-control">
506 <sketch-view-mode-select></sketch-view-mode-select>
507
508 <button id="stopButton" class="refresh-button stop-button">
509 Stop
510 </button>
511
512 <div class="poll-updates">
513 <input type="checkbox" id="pollToggle" checked />
514 <label for="pollToggle">Poll</label>
515 </div>
516
517 <sketch-network-status
518 message=${this.messageStatus}
519 connection=${this.connectionStatus}
520 error=${this.connectionErrorMessage}
521 ></sketch-network-status>
522 </div>
523 </div>
524
525 <div class="view-container">
526 <div class="chat-view ${this.viewMode === "chat" ? "view-active" : ""}">
Sean McCullough2c5bba42025-04-20 19:33:17 -0700527 <sketch-timeline
528 .messages=${this.messages}
529 .scrollContainer=${this}
530 ></sketch-timeline>
Sean McCullough86b56862025-04-18 13:04:03 -0700531 </div>
532
533 <div class="diff-view ${this.viewMode === "diff" ? "view-active" : ""}">
534 <sketch-diff-view
535 .commitHash=${this.currentCommitHash}
536 ></sketch-diff-view>
537 </div>
538
539 <div
540 class="chart-view ${this.viewMode === "charts" ? "view-active" : ""}"
541 >
542 <sketch-charts .messages=${this.messages}></sketch-charts>
543 </div>
544
545 <div
546 class="terminal-view ${this.viewMode === "terminal"
547 ? "view-active"
548 : ""}"
549 >
550 <sketch-terminal></sketch-terminal>
551 </div>
552 </div>
553
Philip Zeyliger73db6052025-04-23 13:09:07 -0700554 <sketch-chat-input @send-chat="${this._sendChat}"></sketch-chat-input>
Sean McCullough86b56862025-04-18 13:04:03 -0700555 `;
556 }
557
558 /**
Sean McCullough86b56862025-04-18 13:04:03 -0700559 * Lifecycle callback when component is first connected to DOM
560 */
561 firstUpdated(): void {
562 if (this.viewMode !== "chat") {
563 return;
564 }
565
566 // Initial scroll to bottom when component is first rendered
567 setTimeout(
568 () => this.scrollTo({ top: this.scrollHeight, behavior: "smooth" }),
Philip Zeyliger72682df2025-04-23 13:09:46 -0700569 50,
Sean McCullough86b56862025-04-18 13:04:03 -0700570 );
571
Sean McCullough71941bd2025-04-18 13:31:48 -0700572 const pollToggleCheckbox = this.renderRoot?.querySelector(
Philip Zeyliger72682df2025-04-23 13:09:46 -0700573 "#pollToggle",
Sean McCullough71941bd2025-04-18 13:31:48 -0700574 ) as HTMLInputElement;
Sean McCullough86b56862025-04-18 13:04:03 -0700575 pollToggleCheckbox?.addEventListener("change", () => {
576 this.dataManager.setPollingEnabled(pollToggleCheckbox.checked);
577 if (!pollToggleCheckbox.checked) {
578 this.connectionStatus = "disabled";
579 this.messageStatus = "Polling stopped";
580 } else {
581 this.messageStatus = "Polling for updates...";
582 }
583 });
584 }
585}
586
587declare global {
588 interface HTMLElementTagNameMap {
589 "sketch-app-shell": SketchAppShell;
590 }
591}