blob: b356535260779fae1fac0fcbac5b192e2e1d653a [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";
Pokey Rule4097e532025-04-24 18:55:28 +01006import "./sketch-charts";
7import "./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";
16
17import { createRef, ref } from "lit/directives/ref.js";
Sean McCullough86b56862025-04-18 13:04:03 -070018
19type ViewMode = "chat" | "diff" | "charts" | "terminal";
20
21@customElement("sketch-app-shell")
22export class SketchAppShell extends LitElement {
23 // Current view mode (chat, diff, charts, terminal)
24 @state()
25 viewMode: "chat" | "diff" | "charts" | "terminal" = "chat";
26
27 // Current commit hash for diff view
28 @state()
29 currentCommitHash: string = "";
30
Philip Zeyliger47b71c92025-04-30 15:43:39 +000031 // Last commit information
32 @state()
33 lastCommit: { hash: string; pushedBranch?: string } | null = null;
34
Sean McCullough86b56862025-04-18 13:04:03 -070035 // See https://lit.dev/docs/components/styles/ for how lit-element handles CSS.
36 // Note that these styles only apply to the scope of this web component's
37 // shadow DOM node, so they won't leak out or collide with CSS declared in
38 // other components or the containing web page (...unless you want it to do that).
39 static styles = css`
Philip Zeyliger47b71c92025-04-30 15:43:39 +000040 /* Last commit display styling */
41 .last-commit {
42 display: flex;
43 align-items: center;
44 padding: 3px 8px;
45 background: #f0f7ff;
46 border: 1px solid #c8e1ff;
47 border-radius: 4px;
48 font-family: monospace;
49 font-size: 12px;
50 color: #0366d6;
51 cursor: pointer;
52 position: relative;
53 margin: 0 10px;
54 white-space: nowrap;
55 overflow: hidden;
56 text-overflow: ellipsis;
57 max-width: 180px;
58 transition: background-color 0.2s ease;
59 }
Autoformattercf570962025-04-30 17:27:39 +000060
Philip Zeyliger47b71c92025-04-30 15:43:39 +000061 .last-commit:hover {
62 background-color: #dbedff;
63 }
Autoformattercf570962025-04-30 17:27:39 +000064
Philip Zeyliger47b71c92025-04-30 15:43:39 +000065 .last-commit::before {
66 content: "Last Commit: ";
67 color: #666;
68 margin-right: 4px;
69 font-family: system-ui, sans-serif;
70 font-size: 11px;
71 }
Autoformattercf570962025-04-30 17:27:39 +000072
Philip Zeyliger47b71c92025-04-30 15:43:39 +000073 .copied-indicator {
74 position: absolute;
75 top: -20px;
76 left: 50%;
77 transform: translateX(-50%);
78 background: rgba(40, 167, 69, 0.9);
79 color: white;
80 padding: 2px 6px;
81 border-radius: 3px;
82 font-size: 10px;
83 font-family: system-ui, sans-serif;
84 animation: fadeInOut 2s ease;
85 pointer-events: none;
86 }
Autoformattercf570962025-04-30 17:27:39 +000087
Philip Zeyliger47b71c92025-04-30 15:43:39 +000088 @keyframes fadeInOut {
Autoformattercf570962025-04-30 17:27:39 +000089 0% {
90 opacity: 0;
91 }
92 20% {
93 opacity: 1;
94 }
95 80% {
96 opacity: 1;
97 }
98 100% {
99 opacity: 0;
100 }
Philip Zeyliger47b71c92025-04-30 15:43:39 +0000101 }
Autoformattercf570962025-04-30 17:27:39 +0000102
Philip Zeyliger47b71c92025-04-30 15:43:39 +0000103 .commit-branch-indicator {
104 color: #28a745;
105 }
Autoformattercf570962025-04-30 17:27:39 +0000106
Philip Zeyliger47b71c92025-04-30 15:43:39 +0000107 .commit-hash-indicator {
108 color: #0366d6;
109 }
Sean McCullough86b56862025-04-18 13:04:03 -0700110 :host {
111 display: block;
Sean McCullough71941bd2025-04-18 13:31:48 -0700112 font-family:
113 system-ui,
114 -apple-system,
115 BlinkMacSystemFont,
116 "Segoe UI",
117 Roboto,
118 sans-serif;
Sean McCullough86b56862025-04-18 13:04:03 -0700119 color: #333;
120 line-height: 1.4;
Pokey Rule4097e532025-04-24 18:55:28 +0100121 height: 100vh;
Sean McCullough86b56862025-04-18 13:04:03 -0700122 width: 100%;
123 position: relative;
124 overflow-x: hidden;
Pokey Rule4097e532025-04-24 18:55:28 +0100125 display: flex;
126 flex-direction: column;
Sean McCullough86b56862025-04-18 13:04:03 -0700127 }
128
129 /* Top banner with combined elements */
Pokey Rule4097e532025-04-24 18:55:28 +0100130 #top-banner {
Sean McCullough86b56862025-04-18 13:04:03 -0700131 display: flex;
Philip Zeyligere66db3e2025-04-27 15:40:39 +0000132 align-self: stretch;
Sean McCullough86b56862025-04-18 13:04:03 -0700133 justify-content: space-between;
134 align-items: center;
Philip Zeyligere66db3e2025-04-27 15:40:39 +0000135 padding: 0 20px;
Sean McCullough86b56862025-04-18 13:04:03 -0700136 margin-bottom: 0;
137 border-bottom: 1px solid #eee;
Philip Zeyligere66db3e2025-04-27 15:40:39 +0000138 gap: 20px;
Sean McCullough86b56862025-04-18 13:04:03 -0700139 background: white;
Sean McCullough86b56862025-04-18 13:04:03 -0700140 box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
Philip Zeyligere66db3e2025-04-27 15:40:39 +0000141 width: 100%;
142 height: 48px;
143 padding-right: 30px; /* Extra padding on the right to prevent elements from hitting the edge */
Sean McCullough86b56862025-04-18 13:04:03 -0700144 }
145
Pokey Rule4097e532025-04-24 18:55:28 +0100146 /* View mode container styles - mirroring timeline.css structure */
147 #view-container {
148 align-self: stretch;
149 overflow-y: auto;
150 flex: 1;
151 }
152
153 #view-container-inner {
154 max-width: 1200px;
155 margin: 0 auto;
156 position: relative;
157 padding-bottom: 10px;
158 padding-top: 10px;
159 }
160
161 #chat-input {
162 align-self: flex-end;
163 width: 100%;
164 box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
165 }
166
Sean McCullough86b56862025-04-18 13:04:03 -0700167 .banner-title {
168 font-size: 18px;
169 font-weight: 600;
170 margin: 0;
171 min-width: 6em;
172 white-space: nowrap;
173 overflow: hidden;
174 text-overflow: ellipsis;
175 }
176
177 .chat-title {
178 margin: 0;
179 padding: 0;
180 color: rgba(82, 82, 82, 0.85);
Josh Bleecher Snydereb5166a2025-04-30 17:04:20 +0000181 font-size: 14px;
Sean McCullough86b56862025-04-18 13:04:03 -0700182 font-weight: normal;
183 font-style: italic;
184 white-space: nowrap;
185 overflow: hidden;
186 text-overflow: ellipsis;
187 }
188
Sean McCullough86b56862025-04-18 13:04:03 -0700189 /* Allow the container to expand to full width in diff mode */
Pokey Rule46fff972025-04-25 14:57:44 +0100190 #view-container-inner.diff-active {
Sean McCullough86b56862025-04-18 13:04:03 -0700191 max-width: 100%;
Pokey Rule46fff972025-04-25 14:57:44 +0100192 width: 100%;
Sean McCullough86b56862025-04-18 13:04:03 -0700193 }
194
195 /* Individual view styles */
196 .chat-view,
197 .diff-view,
198 .chart-view,
199 .terminal-view {
200 display: none; /* Hidden by default */
201 width: 100%;
202 }
203
204 /* Active view styles - these will be applied via JavaScript */
205 .view-active {
206 display: flex;
207 flex-direction: column;
208 }
209
210 .title-container {
211 display: flex;
212 flex-direction: column;
213 white-space: nowrap;
214 overflow: hidden;
215 text-overflow: ellipsis;
Josh Bleecher Snydereb5166a2025-04-30 17:04:20 +0000216 max-width: 30%;
Philip Zeyligere66db3e2025-04-27 15:40:39 +0000217 padding: 6px 0;
Sean McCullough86b56862025-04-18 13:04:03 -0700218 }
219
220 .refresh-control {
221 display: flex;
222 align-items: center;
223 margin-bottom: 0;
224 flex-wrap: nowrap;
225 white-space: nowrap;
226 flex-shrink: 0;
Philip Zeyligere66db3e2025-04-27 15:40:39 +0000227 gap: 15px;
228 padding-left: 15px;
229 margin-right: 50px;
Sean McCullough86b56862025-04-18 13:04:03 -0700230 }
231
232 .refresh-button {
233 background: #4caf50;
234 color: white;
235 border: none;
236 padding: 4px 10px;
237 border-radius: 4px;
238 cursor: pointer;
239 font-size: 12px;
240 margin-right: 5px;
241 }
242
243 .stop-button:hover {
244 background-color: #c82333 !important;
245 }
246
247 .poll-updates {
248 display: flex;
249 align-items: center;
Sean McCullough86b56862025-04-18 13:04:03 -0700250 font-size: 12px;
251 }
252 `;
253
254 // Header bar: Network connection status details
255 @property()
256 connectionStatus: ConnectionStatus = "disconnected";
Autoformattercf570962025-04-30 17:27:39 +0000257
Philip Zeyliger47b71c92025-04-30 15:43:39 +0000258 // Track if the last commit info has been copied
259 @state()
260 lastCommitCopied: boolean = false;
Sean McCullough86b56862025-04-18 13:04:03 -0700261
262 @property()
263 connectionErrorMessage: string = "";
264
265 @property()
266 messageStatus: string = "";
267
268 // Chat messages
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100269 @property({ attribute: false })
Sean McCulloughd9f13372025-04-21 15:08:49 -0700270 messages: AgentMessage[] = [];
Sean McCullough86b56862025-04-18 13:04:03 -0700271
272 @property()
Philip Zeyliger9b999b02025-04-25 16:31:50 +0000273 set title(value: string) {
274 const oldValue = this._title;
275 this._title = value;
276 this.requestUpdate("title", oldValue);
277 // Update document title when title property changes
278 this.updateDocumentTitle();
279 }
280
281 get title(): string {
282 return this._title;
283 }
284
285 private _title: string = "";
Sean McCullough86b56862025-04-18 13:04:03 -0700286
287 private dataManager = new DataManager();
288
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100289 @property({ attribute: false })
Sean McCulloughd9f13372025-04-21 15:08:49 -0700290 containerState: State = {
291 title: "",
292 os: "",
293 message_count: 0,
294 hostname: "",
295 working_dir: "",
296 initial_commit: "",
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000297 outstanding_llm_calls: 0,
298 outstanding_tool_calls: [],
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000299 session_id: "",
300 ssh_available: false,
Sean McCulloughd9f13372025-04-21 15:08:49 -0700301 };
Sean McCullough86b56862025-04-18 13:04:03 -0700302
Sean McCullough86b56862025-04-18 13:04:03 -0700303 // Mutation observer to detect when new messages are added
304 private mutationObserver: MutationObserver | null = null;
305
306 constructor() {
307 super();
308
309 // Binding methods to this
310 this._handleViewModeSelect = this._handleViewModeSelect.bind(this);
Sean McCullough86b56862025-04-18 13:04:03 -0700311 this._handleShowCommitDiff = this._handleShowCommitDiff.bind(this);
312 this._handlePopState = this._handlePopState.bind(this);
Sean McCulloughd3906e22025-04-29 17:32:14 +0000313 this._handleStopClick = this._handleStopClick.bind(this);
Sean McCullough86b56862025-04-18 13:04:03 -0700314 }
315
316 // See https://lit.dev/docs/components/lifecycle/
317 connectedCallback() {
318 super.connectedCallback();
319
320 // Initialize client-side nav history.
321 const url = new URL(window.location.href);
322 const mode = url.searchParams.get("view") || "chat";
323 window.history.replaceState({ mode }, "", url.toString());
324
325 this.toggleViewMode(mode as ViewMode, false);
326 // Add popstate event listener to handle browser back/forward navigation
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100327 window.addEventListener("popstate", this._handlePopState);
Sean McCullough86b56862025-04-18 13:04:03 -0700328
329 // Add event listeners
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100330 window.addEventListener("view-mode-select", this._handleViewModeSelect);
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100331 window.addEventListener("show-commit-diff", this._handleShowCommitDiff);
Sean McCullough86b56862025-04-18 13:04:03 -0700332
333 // register event listeners
334 this.dataManager.addEventListener(
335 "dataChanged",
Philip Zeyliger72682df2025-04-23 13:09:46 -0700336 this.handleDataChanged.bind(this),
Sean McCullough86b56862025-04-18 13:04:03 -0700337 );
338 this.dataManager.addEventListener(
339 "connectionStatusChanged",
Philip Zeyliger72682df2025-04-23 13:09:46 -0700340 this.handleConnectionStatusChanged.bind(this),
Sean McCullough86b56862025-04-18 13:04:03 -0700341 );
342
Philip Zeyliger9b999b02025-04-25 16:31:50 +0000343 // Set initial document title
344 this.updateDocumentTitle();
345
Sean McCullough86b56862025-04-18 13:04:03 -0700346 // Initialize the data manager
347 this.dataManager.initialize();
Autoformattercf570962025-04-30 17:27:39 +0000348
Philip Zeyliger47b71c92025-04-30 15:43:39 +0000349 // Process existing messages for commit info
350 if (this.messages && this.messages.length > 0) {
351 this.updateLastCommitInfo(this.messages);
352 }
Sean McCullough86b56862025-04-18 13:04:03 -0700353 }
354
355 // See https://lit.dev/docs/components/lifecycle/
356 disconnectedCallback() {
357 super.disconnectedCallback();
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100358 window.removeEventListener("popstate", this._handlePopState);
Sean McCullough86b56862025-04-18 13:04:03 -0700359
360 // Remove event listeners
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100361 window.removeEventListener("view-mode-select", this._handleViewModeSelect);
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100362 window.removeEventListener("show-commit-diff", this._handleShowCommitDiff);
Sean McCullough86b56862025-04-18 13:04:03 -0700363
364 // unregister data manager event listeners
365 this.dataManager.removeEventListener(
366 "dataChanged",
Philip Zeyliger72682df2025-04-23 13:09:46 -0700367 this.handleDataChanged.bind(this),
Sean McCullough86b56862025-04-18 13:04:03 -0700368 );
369 this.dataManager.removeEventListener(
370 "connectionStatusChanged",
Philip Zeyliger72682df2025-04-23 13:09:46 -0700371 this.handleConnectionStatusChanged.bind(this),
Sean McCullough86b56862025-04-18 13:04:03 -0700372 );
373
374 // Disconnect mutation observer if it exists
375 if (this.mutationObserver) {
Sean McCullough86b56862025-04-18 13:04:03 -0700376 this.mutationObserver.disconnect();
377 this.mutationObserver = null;
378 }
379 }
380
Sean McCullough71941bd2025-04-18 13:31:48 -0700381 updateUrlForViewMode(mode: "chat" | "diff" | "charts" | "terminal"): void {
Sean McCullough86b56862025-04-18 13:04:03 -0700382 // Get the current URL without search parameters
383 const url = new URL(window.location.href);
384
385 // Clear existing parameters
386 url.search = "";
387
388 // Only add view parameter if not in default chat view
389 if (mode !== "chat") {
390 url.searchParams.set("view", mode);
Sean McCullough71941bd2025-04-18 13:31:48 -0700391 const diffView = this.shadowRoot?.querySelector(
Philip Zeyliger72682df2025-04-23 13:09:46 -0700392 ".diff-view",
Sean McCullough71941bd2025-04-18 13:31:48 -0700393 ) as SketchDiffView;
Sean McCullough86b56862025-04-18 13:04:03 -0700394
395 // If in diff view and there's a commit hash, include that too
396 if (mode === "diff" && diffView.commitHash) {
397 url.searchParams.set("commit", diffView.commitHash);
398 }
399 }
400
401 // Update the browser history without reloading the page
402 window.history.pushState({ mode }, "", url.toString());
403 }
404
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100405 private _handlePopState(event: PopStateEvent) {
Sean McCullough86b56862025-04-18 13:04:03 -0700406 if (event.state && event.state.mode) {
407 this.toggleViewMode(event.state.mode, false);
408 } else {
409 this.toggleViewMode("chat", false);
410 }
411 }
412
413 /**
414 * Handle view mode selection event
415 */
416 private _handleViewModeSelect(event: CustomEvent) {
417 const mode = event.detail.mode as "chat" | "diff" | "charts" | "terminal";
418 this.toggleViewMode(mode, true);
419 }
420
421 /**
422 * Handle show commit diff event
423 */
424 private _handleShowCommitDiff(event: CustomEvent) {
425 const { commitHash } = event.detail;
426 if (commitHash) {
427 this.showCommitDiff(commitHash);
428 }
429 }
430
431 /**
Sean McCullough86b56862025-04-18 13:04:03 -0700432 * Listen for commit diff event
433 * @param commitHash The commit hash to show diff for
434 */
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100435 private showCommitDiff(commitHash: string): void {
Sean McCullough86b56862025-04-18 13:04:03 -0700436 // Store the commit hash
437 this.currentCommitHash = commitHash;
438
439 // Switch to diff view
Sean McCullough71941bd2025-04-18 13:31:48 -0700440 this.toggleViewMode("diff", true);
Sean McCullough86b56862025-04-18 13:04:03 -0700441
442 // Wait for DOM update to complete
443 this.updateComplete.then(() => {
444 // Get the diff view component
445 const diffView = this.shadowRoot?.querySelector("sketch-diff-view");
446 if (diffView) {
447 // Call the showCommitDiff method
448 (diffView as any).showCommitDiff(commitHash);
449 }
450 });
451 }
452
453 /**
454 * Toggle between different view modes: chat, diff, charts, terminal
455 */
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100456 private toggleViewMode(mode: ViewMode, updateHistory: boolean): void {
Sean McCullough86b56862025-04-18 13:04:03 -0700457 // Don't do anything if the mode is already active
458 if (this.viewMode === mode) return;
459
460 // Update the view mode
461 this.viewMode = mode;
462
463 if (updateHistory) {
464 // Update URL with the current view mode
465 this.updateUrlForViewMode(mode);
466 }
467
468 // Wait for DOM update to complete
469 this.updateComplete.then(() => {
470 // Update active view
Pokey Rule46fff972025-04-25 14:57:44 +0100471 const viewContainerInner = this.shadowRoot?.querySelector(
472 "#view-container-inner",
473 );
Sean McCullough86b56862025-04-18 13:04:03 -0700474 const chatView = this.shadowRoot?.querySelector(".chat-view");
475 const diffView = this.shadowRoot?.querySelector(".diff-view");
476 const chartView = this.shadowRoot?.querySelector(".chart-view");
477 const terminalView = this.shadowRoot?.querySelector(".terminal-view");
478
479 // Remove active class from all views
480 chatView?.classList.remove("view-active");
481 diffView?.classList.remove("view-active");
482 chartView?.classList.remove("view-active");
483 terminalView?.classList.remove("view-active");
484
485 // Add/remove diff-active class on view container
486 if (mode === "diff") {
Pokey Rule46fff972025-04-25 14:57:44 +0100487 viewContainerInner?.classList.add("diff-active");
Sean McCullough86b56862025-04-18 13:04:03 -0700488 } else {
Pokey Rule46fff972025-04-25 14:57:44 +0100489 viewContainerInner?.classList.remove("diff-active");
Sean McCullough86b56862025-04-18 13:04:03 -0700490 }
491
492 // Add active class to the selected view
493 switch (mode) {
494 case "chat":
495 chatView?.classList.add("view-active");
496 break;
497 case "diff":
498 diffView?.classList.add("view-active");
499 // Load diff content if we have a diff view
500 const diffViewComp =
501 this.shadowRoot?.querySelector("sketch-diff-view");
502 if (diffViewComp && this.currentCommitHash) {
503 (diffViewComp as any).showCommitDiff(this.currentCommitHash);
504 } else if (diffViewComp) {
505 (diffViewComp as any).loadDiffContent();
506 }
507 break;
508 case "charts":
509 chartView?.classList.add("view-active");
510 break;
511 case "terminal":
512 terminalView?.classList.add("view-active");
513 break;
514 }
515
516 // Update view mode buttons
517 const viewModeSelect = this.shadowRoot?.querySelector(
Philip Zeyliger72682df2025-04-23 13:09:46 -0700518 "sketch-view-mode-select",
Sean McCullough86b56862025-04-18 13:04:03 -0700519 );
520 if (viewModeSelect) {
521 const event = new CustomEvent("update-active-mode", {
522 detail: { mode },
523 bubbles: true,
524 composed: true,
525 });
526 viewModeSelect.dispatchEvent(event);
527 }
528
529 // FIXME: This is a hack to get vega chart in sketch-charts.ts to work properly
530 // When the chart is in the background, its container has a width of 0, so vega
531 // renders width 0 and only changes that width on a resize event.
532 // See https://github.com/vega/react-vega/issues/85#issuecomment-1826421132
533 window.dispatchEvent(new Event("resize"));
534 });
535 }
536
Philip Zeyliger9b999b02025-04-25 16:31:50 +0000537 /**
538 * Updates the document title based on current title and connection status
539 */
540 private updateDocumentTitle(): void {
541 let docTitle = `sk: ${this.title || "untitled"}`;
542
543 // Add red circle emoji if disconnected
544 if (this.connectionStatus === "disconnected") {
545 docTitle += " 🔴";
546 }
547
548 document.title = docTitle;
549 }
550
Sean McCullough86b56862025-04-18 13:04:03 -0700551 private handleDataChanged(eventData: {
552 state: State;
Sean McCulloughd9f13372025-04-21 15:08:49 -0700553 newMessages: AgentMessage[];
Sean McCullough86b56862025-04-18 13:04:03 -0700554 isFirstFetch?: boolean;
555 }): void {
556 const { state, newMessages, isFirstFetch } = eventData;
557
558 // Check if this is the first data fetch or if there are new messages
559 if (isFirstFetch) {
Sean McCullough86b56862025-04-18 13:04:03 -0700560 this.messageStatus = "Initial messages loaded";
561 } else if (newMessages && newMessages.length > 0) {
Sean McCullough86b56862025-04-18 13:04:03 -0700562 this.messageStatus = "Updated just now";
Sean McCullough86b56862025-04-18 13:04:03 -0700563 } else {
564 this.messageStatus = "No new messages";
565 }
566
567 // Update state if we received it
568 if (state) {
Josh Bleecher Snydere81233f2025-04-30 04:05:41 +0000569 // Ensure we're using the latest call status to prevent indicators from being stuck
570 if (state.outstanding_llm_calls === 0 && state.outstanding_tool_calls.length === 0) {
571 // Force reset containerState calls when nothing is reported as in progress
572 state.outstanding_llm_calls = 0;
573 state.outstanding_tool_calls = [];
574 }
575
Sean McCullough86b56862025-04-18 13:04:03 -0700576 this.containerState = state;
577 this.title = state.title;
Philip Zeyliger9b999b02025-04-25 16:31:50 +0000578
579 // Update document title when sketch title changes
580 this.updateDocumentTitle();
Sean McCullough86b56862025-04-18 13:04:03 -0700581 }
582
Sean McCullough86b56862025-04-18 13:04:03 -0700583 // Update messages
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100584 this.messages = aggregateAgentMessages(this.messages, newMessages);
Autoformattercf570962025-04-30 17:27:39 +0000585
Philip Zeyliger47b71c92025-04-30 15:43:39 +0000586 // Process new messages to find commit messages
587 this.updateLastCommitInfo(newMessages);
Sean McCullough86b56862025-04-18 13:04:03 -0700588 }
589
590 private handleConnectionStatusChanged(
591 status: ConnectionStatus,
Philip Zeyliger72682df2025-04-23 13:09:46 -0700592 errorMessage?: string,
Sean McCullough86b56862025-04-18 13:04:03 -0700593 ): void {
594 this.connectionStatus = status;
595 this.connectionErrorMessage = errorMessage || "";
Philip Zeyliger9b999b02025-04-25 16:31:50 +0000596
597 // Update document title when connection status changes
598 this.updateDocumentTitle();
Sean McCullough86b56862025-04-18 13:04:03 -0700599 }
600
Sean McCulloughd3906e22025-04-29 17:32:14 +0000601 /**
602 * Handle stop button click
603 * Sends a request to the server to stop the current operation
604 */
Philip Zeyliger47b71c92025-04-30 15:43:39 +0000605 // Update last commit information when new messages arrive
606 private updateLastCommitInfo(newMessages: AgentMessage[]): void {
607 if (!newMessages || newMessages.length === 0) return;
Autoformattercf570962025-04-30 17:27:39 +0000608
Philip Zeyliger47b71c92025-04-30 15:43:39 +0000609 // Process messages in chronological order (latest last)
610 for (const message of newMessages) {
Autoformattercf570962025-04-30 17:27:39 +0000611 if (
612 message.type === "commit" &&
613 message.commits &&
614 message.commits.length > 0
615 ) {
Philip Zeyliger47b71c92025-04-30 15:43:39 +0000616 // Get the first commit from the list
617 const commit = message.commits[0];
618 if (commit) {
619 this.lastCommit = {
620 hash: commit.hash,
Autoformattercf570962025-04-30 17:27:39 +0000621 pushedBranch: commit.pushed_branch,
Philip Zeyliger47b71c92025-04-30 15:43:39 +0000622 };
623 this.lastCommitCopied = false;
624 }
625 }
626 }
627 }
628
629 // Copy commit info to clipboard
630 private copyCommitInfo(event: MouseEvent): void {
631 event.preventDefault();
632 event.stopPropagation();
Autoformattercf570962025-04-30 17:27:39 +0000633
Philip Zeyliger47b71c92025-04-30 15:43:39 +0000634 if (!this.lastCommit) return;
Autoformattercf570962025-04-30 17:27:39 +0000635
636 const textToCopy =
637 this.lastCommit.pushedBranch || this.lastCommit.hash.substring(0, 8);
638
639 navigator.clipboard
640 .writeText(textToCopy)
Philip Zeyliger47b71c92025-04-30 15:43:39 +0000641 .then(() => {
642 this.lastCommitCopied = true;
643 // Reset the copied state after 2 seconds
644 setTimeout(() => {
645 this.lastCommitCopied = false;
646 }, 2000);
647 })
Autoformattercf570962025-04-30 17:27:39 +0000648 .catch((err) => {
649 console.error("Failed to copy commit info:", err);
Philip Zeyliger47b71c92025-04-30 15:43:39 +0000650 });
651 }
Autoformattercf570962025-04-30 17:27:39 +0000652
Sean McCulloughd3906e22025-04-29 17:32:14 +0000653 private async _handleStopClick(): Promise<void> {
654 try {
655 const response = await fetch("cancel", {
656 method: "POST",
657 headers: {
658 "Content-Type": "application/json",
659 },
660 body: JSON.stringify({ reason: "user requested cancellation" }),
661 });
662
663 if (!response.ok) {
664 const errorData = await response.text();
665 throw new Error(
666 `Failed to stop operation: ${response.status} - ${errorData}`,
667 );
668 }
669
670 this.messageStatus = "Stop request sent";
671 } catch (error) {
672 console.error("Error stopping operation:", error);
673 this.messageStatus = "Failed to stop operation";
674 }
675 }
676
Sean McCullough86b56862025-04-18 13:04:03 -0700677 async _sendChat(e: CustomEvent) {
678 console.log("app shell: _sendChat", e);
679 const message = e.detail.message?.trim();
680 if (message == "") {
681 return;
682 }
683 try {
684 // Send the message to the server
685 const response = await fetch("chat", {
686 method: "POST",
687 headers: {
688 "Content-Type": "application/json",
689 },
690 body: JSON.stringify({ message }),
691 });
692
693 if (!response.ok) {
694 const errorData = await response.text();
695 throw new Error(`Server error: ${response.status} - ${errorData}`);
696 }
Sean McCullough86b56862025-04-18 13:04:03 -0700697
Philip Zeyliger73db6052025-04-23 13:09:07 -0700698 // TOOD(philip): If the data manager is getting messages out of order, there's a bug?
Sean McCullough86b56862025-04-18 13:04:03 -0700699 // Reset data manager state to force a full refresh after sending a message
700 // This ensures we get all messages in the correct order
701 // Use private API for now - TODO: add a resetState() method to DataManager
702 (this.dataManager as any).nextFetchIndex = 0;
703 (this.dataManager as any).currentFetchStartIndex = 0;
704
Sean McCullough86b56862025-04-18 13:04:03 -0700705 // // If in diff view, switch to conversation view
706 // if (this.viewMode === "diff") {
707 // await this.toggleViewMode("chat");
708 // }
709
710 // Refresh the timeline data to show the new message
711 await this.dataManager.fetchData();
Sean McCullough86b56862025-04-18 13:04:03 -0700712 } catch (error) {
713 console.error("Error sending chat message:", error);
714 const statusText = document.getElementById("statusText");
715 if (statusText) {
716 statusText.textContent = "Error sending message";
717 }
718 }
719 }
720
Pokey Rule4097e532025-04-24 18:55:28 +0100721 private scrollContainerRef = createRef<HTMLElement>();
722
Sean McCullough86b56862025-04-18 13:04:03 -0700723 render() {
724 return html`
Pokey Rule4097e532025-04-24 18:55:28 +0100725 <div id="top-banner">
Sean McCullough86b56862025-04-18 13:04:03 -0700726 <div class="title-container">
727 <h1 class="banner-title">sketch</h1>
728 <h2 id="chatTitle" class="chat-title">${this.title}</h2>
729 </div>
730
Philip Zeyligere66db3e2025-04-27 15:40:39 +0000731 <!-- Views section with tabs -->
732 <sketch-view-mode-select></sketch-view-mode-select>
733
734 <!-- Container status info -->
Sean McCullough86b56862025-04-18 13:04:03 -0700735 <sketch-container-status
736 .state=${this.containerState}
737 ></sketch-container-status>
Autoformattercf570962025-04-30 17:27:39 +0000738
739 ${this.lastCommit
740 ? html`
741 <div
742 class="last-commit"
743 @click=${(e: MouseEvent) => this.copyCommitInfo(e)}
744 title="Click to copy"
745 >
746 ${this.lastCommitCopied
747 ? html`<span class="copied-indicator">Copied!</span>`
748 : ""}
749 ${this.lastCommit.pushedBranch
750 ? html`<span class="commit-branch-indicator"
751 >${this.lastCommit.pushedBranch}</span
752 >`
753 : html`<span class="commit-hash-indicator"
754 >${this.lastCommit.hash.substring(0, 8)}</span
755 >`}
756 </div>
757 `
758 : ""}
Sean McCullough86b56862025-04-18 13:04:03 -0700759
760 <div class="refresh-control">
Sean McCulloughd3906e22025-04-29 17:32:14 +0000761 <button
762 id="stopButton"
763 class="refresh-button stop-button"
764 @click="${this._handleStopClick}"
765 >
Sean McCullough86b56862025-04-18 13:04:03 -0700766 Stop
767 </button>
768
769 <div class="poll-updates">
770 <input type="checkbox" id="pollToggle" checked />
771 <label for="pollToggle">Poll</label>
772 </div>
773
774 <sketch-network-status
775 message=${this.messageStatus}
776 connection=${this.connectionStatus}
777 error=${this.connectionErrorMessage}
778 ></sketch-network-status>
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000779
780 <sketch-call-status
781 .llmCalls=${this.containerState?.outstanding_llm_calls || 0}
782 .toolCalls=${this.containerState?.outstanding_tool_calls || []}
783 ></sketch-call-status>
Sean McCullough86b56862025-04-18 13:04:03 -0700784 </div>
785 </div>
786
Pokey Rule4097e532025-04-24 18:55:28 +0100787 <div id="view-container" ${ref(this.scrollContainerRef)}>
788 <div id="view-container-inner">
789 <div
790 class="chat-view ${this.viewMode === "chat" ? "view-active" : ""}"
791 >
792 <sketch-timeline
793 .messages=${this.messages}
794 .scrollContainer=${this.scrollContainerRef}
795 ></sketch-timeline>
796 </div>
797 <div
798 class="diff-view ${this.viewMode === "diff" ? "view-active" : ""}"
799 >
800 <sketch-diff-view
801 .commitHash=${this.currentCommitHash}
802 ></sketch-diff-view>
803 </div>
804 <div
805 class="chart-view ${this.viewMode === "charts"
806 ? "view-active"
807 : ""}"
808 >
809 <sketch-charts .messages=${this.messages}></sketch-charts>
810 </div>
811 <div
812 class="terminal-view ${this.viewMode === "terminal"
813 ? "view-active"
814 : ""}"
815 >
816 <sketch-terminal></sketch-terminal>
817 </div>
Sean McCullough86b56862025-04-18 13:04:03 -0700818 </div>
819 </div>
820
Pokey Rule4097e532025-04-24 18:55:28 +0100821 <div id="chat-input">
822 <sketch-chat-input @send-chat="${this._sendChat}"></sketch-chat-input>
823 </div>
Sean McCullough86b56862025-04-18 13:04:03 -0700824 `;
825 }
826
827 /**
Sean McCullough86b56862025-04-18 13:04:03 -0700828 * Lifecycle callback when component is first connected to DOM
829 */
830 firstUpdated(): void {
831 if (this.viewMode !== "chat") {
832 return;
833 }
834
835 // Initial scroll to bottom when component is first rendered
836 setTimeout(
837 () => this.scrollTo({ top: this.scrollHeight, behavior: "smooth" }),
Philip Zeyliger72682df2025-04-23 13:09:46 -0700838 50,
Sean McCullough86b56862025-04-18 13:04:03 -0700839 );
840
Sean McCullough71941bd2025-04-18 13:31:48 -0700841 const pollToggleCheckbox = this.renderRoot?.querySelector(
Philip Zeyliger72682df2025-04-23 13:09:46 -0700842 "#pollToggle",
Sean McCullough71941bd2025-04-18 13:31:48 -0700843 ) as HTMLInputElement;
Sean McCullough86b56862025-04-18 13:04:03 -0700844 pollToggleCheckbox?.addEventListener("change", () => {
845 this.dataManager.setPollingEnabled(pollToggleCheckbox.checked);
846 if (!pollToggleCheckbox.checked) {
847 this.connectionStatus = "disabled";
848 this.messageStatus = "Polling stopped";
849 } else {
850 this.messageStatus = "Polling for updates...";
851 }
852 });
Autoformattercf570962025-04-30 17:27:39 +0000853
Philip Zeyliger47b71c92025-04-30 15:43:39 +0000854 // Process any existing messages to find commit information
855 if (this.messages && this.messages.length > 0) {
856 this.updateLastCommitInfo(this.messages);
857 }
Sean McCullough86b56862025-04-18 13:04:03 -0700858 }
859}
860
861declare global {
862 interface HTMLElementTagNameMap {
863 "sketch-app-shell": SketchAppShell;
864 }
865}