blob: 517ec5f30748a60d298cd35a91e86d4a48976966 [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
Autoformatterf830c9d2025-04-30 18:16:01 +0000570 if (
571 state.outstanding_llm_calls === 0 &&
572 state.outstanding_tool_calls.length === 0
573 ) {
Josh Bleecher Snydere81233f2025-04-30 04:05:41 +0000574 // Force reset containerState calls when nothing is reported as in progress
575 state.outstanding_llm_calls = 0;
576 state.outstanding_tool_calls = [];
577 }
Autoformatterf830c9d2025-04-30 18:16:01 +0000578
Sean McCullough86b56862025-04-18 13:04:03 -0700579 this.containerState = state;
580 this.title = state.title;
Philip Zeyliger9b999b02025-04-25 16:31:50 +0000581
582 // Update document title when sketch title changes
583 this.updateDocumentTitle();
Sean McCullough86b56862025-04-18 13:04:03 -0700584 }
585
Sean McCullough86b56862025-04-18 13:04:03 -0700586 // Update messages
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100587 this.messages = aggregateAgentMessages(this.messages, newMessages);
Autoformattercf570962025-04-30 17:27:39 +0000588
Philip Zeyliger47b71c92025-04-30 15:43:39 +0000589 // Process new messages to find commit messages
590 this.updateLastCommitInfo(newMessages);
Sean McCullough86b56862025-04-18 13:04:03 -0700591 }
592
593 private handleConnectionStatusChanged(
594 status: ConnectionStatus,
Philip Zeyliger72682df2025-04-23 13:09:46 -0700595 errorMessage?: string,
Sean McCullough86b56862025-04-18 13:04:03 -0700596 ): void {
597 this.connectionStatus = status;
598 this.connectionErrorMessage = errorMessage || "";
Philip Zeyliger9b999b02025-04-25 16:31:50 +0000599
600 // Update document title when connection status changes
601 this.updateDocumentTitle();
Sean McCullough86b56862025-04-18 13:04:03 -0700602 }
603
Sean McCulloughd3906e22025-04-29 17:32:14 +0000604 /**
605 * Handle stop button click
606 * Sends a request to the server to stop the current operation
607 */
Philip Zeyliger47b71c92025-04-30 15:43:39 +0000608 // Update last commit information when new messages arrive
609 private updateLastCommitInfo(newMessages: AgentMessage[]): void {
610 if (!newMessages || newMessages.length === 0) return;
Autoformattercf570962025-04-30 17:27:39 +0000611
Philip Zeyliger47b71c92025-04-30 15:43:39 +0000612 // Process messages in chronological order (latest last)
613 for (const message of newMessages) {
Autoformattercf570962025-04-30 17:27:39 +0000614 if (
615 message.type === "commit" &&
616 message.commits &&
617 message.commits.length > 0
618 ) {
Philip Zeyliger47b71c92025-04-30 15:43:39 +0000619 // Get the first commit from the list
620 const commit = message.commits[0];
621 if (commit) {
622 this.lastCommit = {
623 hash: commit.hash,
Autoformattercf570962025-04-30 17:27:39 +0000624 pushedBranch: commit.pushed_branch,
Philip Zeyliger47b71c92025-04-30 15:43:39 +0000625 };
626 this.lastCommitCopied = false;
627 }
628 }
629 }
630 }
631
632 // Copy commit info to clipboard
633 private copyCommitInfo(event: MouseEvent): void {
634 event.preventDefault();
635 event.stopPropagation();
Autoformattercf570962025-04-30 17:27:39 +0000636
Philip Zeyliger47b71c92025-04-30 15:43:39 +0000637 if (!this.lastCommit) return;
Autoformattercf570962025-04-30 17:27:39 +0000638
639 const textToCopy =
640 this.lastCommit.pushedBranch || this.lastCommit.hash.substring(0, 8);
641
642 navigator.clipboard
643 .writeText(textToCopy)
Philip Zeyliger47b71c92025-04-30 15:43:39 +0000644 .then(() => {
645 this.lastCommitCopied = true;
646 // Reset the copied state after 2 seconds
647 setTimeout(() => {
648 this.lastCommitCopied = false;
649 }, 2000);
650 })
Autoformattercf570962025-04-30 17:27:39 +0000651 .catch((err) => {
652 console.error("Failed to copy commit info:", err);
Philip Zeyliger47b71c92025-04-30 15:43:39 +0000653 });
654 }
Autoformattercf570962025-04-30 17:27:39 +0000655
Sean McCulloughd3906e22025-04-29 17:32:14 +0000656 private async _handleStopClick(): Promise<void> {
657 try {
658 const response = await fetch("cancel", {
659 method: "POST",
660 headers: {
661 "Content-Type": "application/json",
662 },
663 body: JSON.stringify({ reason: "user requested cancellation" }),
664 });
665
666 if (!response.ok) {
667 const errorData = await response.text();
668 throw new Error(
669 `Failed to stop operation: ${response.status} - ${errorData}`,
670 );
671 }
672
673 this.messageStatus = "Stop request sent";
674 } catch (error) {
675 console.error("Error stopping operation:", error);
676 this.messageStatus = "Failed to stop operation";
677 }
678 }
679
Sean McCullough86b56862025-04-18 13:04:03 -0700680 async _sendChat(e: CustomEvent) {
681 console.log("app shell: _sendChat", e);
682 const message = e.detail.message?.trim();
683 if (message == "") {
684 return;
685 }
686 try {
687 // Send the message to the server
688 const response = await fetch("chat", {
689 method: "POST",
690 headers: {
691 "Content-Type": "application/json",
692 },
693 body: JSON.stringify({ message }),
694 });
695
696 if (!response.ok) {
697 const errorData = await response.text();
698 throw new Error(`Server error: ${response.status} - ${errorData}`);
699 }
Sean McCullough86b56862025-04-18 13:04:03 -0700700
Philip Zeyliger73db6052025-04-23 13:09:07 -0700701 // TOOD(philip): If the data manager is getting messages out of order, there's a bug?
Sean McCullough86b56862025-04-18 13:04:03 -0700702 // Reset data manager state to force a full refresh after sending a message
703 // This ensures we get all messages in the correct order
704 // Use private API for now - TODO: add a resetState() method to DataManager
705 (this.dataManager as any).nextFetchIndex = 0;
706 (this.dataManager as any).currentFetchStartIndex = 0;
707
Sean McCullough86b56862025-04-18 13:04:03 -0700708 // // If in diff view, switch to conversation view
709 // if (this.viewMode === "diff") {
710 // await this.toggleViewMode("chat");
711 // }
712
713 // Refresh the timeline data to show the new message
714 await this.dataManager.fetchData();
Sean McCullough86b56862025-04-18 13:04:03 -0700715 } catch (error) {
716 console.error("Error sending chat message:", error);
717 const statusText = document.getElementById("statusText");
718 if (statusText) {
719 statusText.textContent = "Error sending message";
720 }
721 }
722 }
723
Pokey Rule4097e532025-04-24 18:55:28 +0100724 private scrollContainerRef = createRef<HTMLElement>();
725
Sean McCullough86b56862025-04-18 13:04:03 -0700726 render() {
727 return html`
Pokey Rule4097e532025-04-24 18:55:28 +0100728 <div id="top-banner">
Sean McCullough86b56862025-04-18 13:04:03 -0700729 <div class="title-container">
730 <h1 class="banner-title">sketch</h1>
731 <h2 id="chatTitle" class="chat-title">${this.title}</h2>
732 </div>
733
Philip Zeyligere66db3e2025-04-27 15:40:39 +0000734 <!-- Views section with tabs -->
735 <sketch-view-mode-select></sketch-view-mode-select>
736
737 <!-- Container status info -->
Sean McCullough86b56862025-04-18 13:04:03 -0700738 <sketch-container-status
739 .state=${this.containerState}
740 ></sketch-container-status>
Autoformattercf570962025-04-30 17:27:39 +0000741
742 ${this.lastCommit
743 ? html`
744 <div
745 class="last-commit"
746 @click=${(e: MouseEvent) => this.copyCommitInfo(e)}
747 title="Click to copy"
748 >
749 ${this.lastCommitCopied
750 ? html`<span class="copied-indicator">Copied!</span>`
751 : ""}
752 ${this.lastCommit.pushedBranch
753 ? html`<span class="commit-branch-indicator"
754 >${this.lastCommit.pushedBranch}</span
755 >`
756 : html`<span class="commit-hash-indicator"
757 >${this.lastCommit.hash.substring(0, 8)}</span
758 >`}
759 </div>
760 `
761 : ""}
Sean McCullough86b56862025-04-18 13:04:03 -0700762
763 <div class="refresh-control">
Sean McCulloughd3906e22025-04-29 17:32:14 +0000764 <button
765 id="stopButton"
766 class="refresh-button stop-button"
767 @click="${this._handleStopClick}"
768 >
Sean McCullough86b56862025-04-18 13:04:03 -0700769 Stop
770 </button>
771
772 <div class="poll-updates">
773 <input type="checkbox" id="pollToggle" checked />
774 <label for="pollToggle">Poll</label>
775 </div>
776
777 <sketch-network-status
778 message=${this.messageStatus}
779 connection=${this.connectionStatus}
780 error=${this.connectionErrorMessage}
781 ></sketch-network-status>
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000782
783 <sketch-call-status
784 .llmCalls=${this.containerState?.outstanding_llm_calls || 0}
785 .toolCalls=${this.containerState?.outstanding_tool_calls || []}
786 ></sketch-call-status>
Sean McCullough86b56862025-04-18 13:04:03 -0700787 </div>
788 </div>
789
Pokey Rule4097e532025-04-24 18:55:28 +0100790 <div id="view-container" ${ref(this.scrollContainerRef)}>
791 <div id="view-container-inner">
792 <div
793 class="chat-view ${this.viewMode === "chat" ? "view-active" : ""}"
794 >
795 <sketch-timeline
796 .messages=${this.messages}
797 .scrollContainer=${this.scrollContainerRef}
798 ></sketch-timeline>
799 </div>
800 <div
801 class="diff-view ${this.viewMode === "diff" ? "view-active" : ""}"
802 >
803 <sketch-diff-view
804 .commitHash=${this.currentCommitHash}
805 ></sketch-diff-view>
806 </div>
807 <div
808 class="chart-view ${this.viewMode === "charts"
809 ? "view-active"
810 : ""}"
811 >
812 <sketch-charts .messages=${this.messages}></sketch-charts>
813 </div>
814 <div
815 class="terminal-view ${this.viewMode === "terminal"
816 ? "view-active"
817 : ""}"
818 >
819 <sketch-terminal></sketch-terminal>
820 </div>
Sean McCullough86b56862025-04-18 13:04:03 -0700821 </div>
822 </div>
823
Pokey Rule4097e532025-04-24 18:55:28 +0100824 <div id="chat-input">
825 <sketch-chat-input @send-chat="${this._sendChat}"></sketch-chat-input>
826 </div>
Sean McCullough86b56862025-04-18 13:04:03 -0700827 `;
828 }
829
830 /**
Sean McCullough86b56862025-04-18 13:04:03 -0700831 * Lifecycle callback when component is first connected to DOM
832 */
833 firstUpdated(): void {
834 if (this.viewMode !== "chat") {
835 return;
836 }
837
838 // Initial scroll to bottom when component is first rendered
839 setTimeout(
840 () => this.scrollTo({ top: this.scrollHeight, behavior: "smooth" }),
Philip Zeyliger72682df2025-04-23 13:09:46 -0700841 50,
Sean McCullough86b56862025-04-18 13:04:03 -0700842 );
843
Sean McCullough71941bd2025-04-18 13:31:48 -0700844 const pollToggleCheckbox = this.renderRoot?.querySelector(
Philip Zeyliger72682df2025-04-23 13:09:46 -0700845 "#pollToggle",
Sean McCullough71941bd2025-04-18 13:31:48 -0700846 ) as HTMLInputElement;
Sean McCullough86b56862025-04-18 13:04:03 -0700847 pollToggleCheckbox?.addEventListener("change", () => {
848 this.dataManager.setPollingEnabled(pollToggleCheckbox.checked);
849 if (!pollToggleCheckbox.checked) {
850 this.connectionStatus = "disabled";
851 this.messageStatus = "Polling stopped";
852 } else {
853 this.messageStatus = "Polling for updates...";
854 }
855 });
Autoformattercf570962025-04-30 17:27:39 +0000856
Philip Zeyliger47b71c92025-04-30 15:43:39 +0000857 // Process any existing messages to find commit information
858 if (this.messages && this.messages.length > 0) {
859 this.updateLastCommitInfo(this.messages);
860 }
Sean McCullough86b56862025-04-18 13:04:03 -0700861 }
862}
863
864declare global {
865 interface HTMLElementTagNameMap {
866 "sketch-app-shell": SketchAppShell;
867 }
868}