blob: b3f2d099bb83b3eda9cffa3718ad6537d5961279 [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);
181 font-size: 16px;
182 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;
Philip Zeyligere66db3e2025-04-27 15:40:39 +0000216 max-width: 25%;
217 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) {
569 this.containerState = state;
570 this.title = state.title;
Philip Zeyliger9b999b02025-04-25 16:31:50 +0000571
572 // Update document title when sketch title changes
573 this.updateDocumentTitle();
Sean McCullough86b56862025-04-18 13:04:03 -0700574 }
575
Sean McCullough86b56862025-04-18 13:04:03 -0700576 // Update messages
Pokey Rulee2a8c2f2025-04-23 15:09:25 +0100577 this.messages = aggregateAgentMessages(this.messages, newMessages);
Autoformattercf570962025-04-30 17:27:39 +0000578
Philip Zeyliger47b71c92025-04-30 15:43:39 +0000579 // Process new messages to find commit messages
580 this.updateLastCommitInfo(newMessages);
Sean McCullough86b56862025-04-18 13:04:03 -0700581 }
582
583 private handleConnectionStatusChanged(
584 status: ConnectionStatus,
Philip Zeyliger72682df2025-04-23 13:09:46 -0700585 errorMessage?: string,
Sean McCullough86b56862025-04-18 13:04:03 -0700586 ): void {
587 this.connectionStatus = status;
588 this.connectionErrorMessage = errorMessage || "";
Philip Zeyliger9b999b02025-04-25 16:31:50 +0000589
590 // Update document title when connection status changes
591 this.updateDocumentTitle();
Sean McCullough86b56862025-04-18 13:04:03 -0700592 }
593
Sean McCulloughd3906e22025-04-29 17:32:14 +0000594 /**
595 * Handle stop button click
596 * Sends a request to the server to stop the current operation
597 */
Philip Zeyliger47b71c92025-04-30 15:43:39 +0000598 // Update last commit information when new messages arrive
599 private updateLastCommitInfo(newMessages: AgentMessage[]): void {
600 if (!newMessages || newMessages.length === 0) return;
Autoformattercf570962025-04-30 17:27:39 +0000601
Philip Zeyliger47b71c92025-04-30 15:43:39 +0000602 // Process messages in chronological order (latest last)
603 for (const message of newMessages) {
Autoformattercf570962025-04-30 17:27:39 +0000604 if (
605 message.type === "commit" &&
606 message.commits &&
607 message.commits.length > 0
608 ) {
Philip Zeyliger47b71c92025-04-30 15:43:39 +0000609 // Get the first commit from the list
610 const commit = message.commits[0];
611 if (commit) {
612 this.lastCommit = {
613 hash: commit.hash,
Autoformattercf570962025-04-30 17:27:39 +0000614 pushedBranch: commit.pushed_branch,
Philip Zeyliger47b71c92025-04-30 15:43:39 +0000615 };
616 this.lastCommitCopied = false;
617 }
618 }
619 }
620 }
621
622 // Copy commit info to clipboard
623 private copyCommitInfo(event: MouseEvent): void {
624 event.preventDefault();
625 event.stopPropagation();
Autoformattercf570962025-04-30 17:27:39 +0000626
Philip Zeyliger47b71c92025-04-30 15:43:39 +0000627 if (!this.lastCommit) return;
Autoformattercf570962025-04-30 17:27:39 +0000628
629 const textToCopy =
630 this.lastCommit.pushedBranch || this.lastCommit.hash.substring(0, 8);
631
632 navigator.clipboard
633 .writeText(textToCopy)
Philip Zeyliger47b71c92025-04-30 15:43:39 +0000634 .then(() => {
635 this.lastCommitCopied = true;
636 // Reset the copied state after 2 seconds
637 setTimeout(() => {
638 this.lastCommitCopied = false;
639 }, 2000);
640 })
Autoformattercf570962025-04-30 17:27:39 +0000641 .catch((err) => {
642 console.error("Failed to copy commit info:", err);
Philip Zeyliger47b71c92025-04-30 15:43:39 +0000643 });
644 }
Autoformattercf570962025-04-30 17:27:39 +0000645
Sean McCulloughd3906e22025-04-29 17:32:14 +0000646 private async _handleStopClick(): Promise<void> {
647 try {
648 const response = await fetch("cancel", {
649 method: "POST",
650 headers: {
651 "Content-Type": "application/json",
652 },
653 body: JSON.stringify({ reason: "user requested cancellation" }),
654 });
655
656 if (!response.ok) {
657 const errorData = await response.text();
658 throw new Error(
659 `Failed to stop operation: ${response.status} - ${errorData}`,
660 );
661 }
662
663 this.messageStatus = "Stop request sent";
664 } catch (error) {
665 console.error("Error stopping operation:", error);
666 this.messageStatus = "Failed to stop operation";
667 }
668 }
669
Sean McCullough86b56862025-04-18 13:04:03 -0700670 async _sendChat(e: CustomEvent) {
671 console.log("app shell: _sendChat", e);
672 const message = e.detail.message?.trim();
673 if (message == "") {
674 return;
675 }
676 try {
677 // Send the message to the server
678 const response = await fetch("chat", {
679 method: "POST",
680 headers: {
681 "Content-Type": "application/json",
682 },
683 body: JSON.stringify({ message }),
684 });
685
686 if (!response.ok) {
687 const errorData = await response.text();
688 throw new Error(`Server error: ${response.status} - ${errorData}`);
689 }
Sean McCullough86b56862025-04-18 13:04:03 -0700690
Philip Zeyliger73db6052025-04-23 13:09:07 -0700691 // TOOD(philip): If the data manager is getting messages out of order, there's a bug?
Sean McCullough86b56862025-04-18 13:04:03 -0700692 // Reset data manager state to force a full refresh after sending a message
693 // This ensures we get all messages in the correct order
694 // Use private API for now - TODO: add a resetState() method to DataManager
695 (this.dataManager as any).nextFetchIndex = 0;
696 (this.dataManager as any).currentFetchStartIndex = 0;
697
Sean McCullough86b56862025-04-18 13:04:03 -0700698 // // If in diff view, switch to conversation view
699 // if (this.viewMode === "diff") {
700 // await this.toggleViewMode("chat");
701 // }
702
703 // Refresh the timeline data to show the new message
704 await this.dataManager.fetchData();
Sean McCullough86b56862025-04-18 13:04:03 -0700705 } catch (error) {
706 console.error("Error sending chat message:", error);
707 const statusText = document.getElementById("statusText");
708 if (statusText) {
709 statusText.textContent = "Error sending message";
710 }
711 }
712 }
713
Pokey Rule4097e532025-04-24 18:55:28 +0100714 private scrollContainerRef = createRef<HTMLElement>();
715
Sean McCullough86b56862025-04-18 13:04:03 -0700716 render() {
717 return html`
Pokey Rule4097e532025-04-24 18:55:28 +0100718 <div id="top-banner">
Sean McCullough86b56862025-04-18 13:04:03 -0700719 <div class="title-container">
720 <h1 class="banner-title">sketch</h1>
721 <h2 id="chatTitle" class="chat-title">${this.title}</h2>
722 </div>
723
Philip Zeyligere66db3e2025-04-27 15:40:39 +0000724 <!-- Views section with tabs -->
725 <sketch-view-mode-select></sketch-view-mode-select>
726
727 <!-- Container status info -->
Sean McCullough86b56862025-04-18 13:04:03 -0700728 <sketch-container-status
729 .state=${this.containerState}
730 ></sketch-container-status>
Autoformattercf570962025-04-30 17:27:39 +0000731
732 ${this.lastCommit
733 ? html`
734 <div
735 class="last-commit"
736 @click=${(e: MouseEvent) => this.copyCommitInfo(e)}
737 title="Click to copy"
738 >
739 ${this.lastCommitCopied
740 ? html`<span class="copied-indicator">Copied!</span>`
741 : ""}
742 ${this.lastCommit.pushedBranch
743 ? html`<span class="commit-branch-indicator"
744 >${this.lastCommit.pushedBranch}</span
745 >`
746 : html`<span class="commit-hash-indicator"
747 >${this.lastCommit.hash.substring(0, 8)}</span
748 >`}
749 </div>
750 `
751 : ""}
Sean McCullough86b56862025-04-18 13:04:03 -0700752
753 <div class="refresh-control">
Sean McCulloughd3906e22025-04-29 17:32:14 +0000754 <button
755 id="stopButton"
756 class="refresh-button stop-button"
757 @click="${this._handleStopClick}"
758 >
Sean McCullough86b56862025-04-18 13:04:03 -0700759 Stop
760 </button>
761
762 <div class="poll-updates">
763 <input type="checkbox" id="pollToggle" checked />
764 <label for="pollToggle">Poll</label>
765 </div>
766
767 <sketch-network-status
768 message=${this.messageStatus}
769 connection=${this.connectionStatus}
770 error=${this.connectionErrorMessage}
771 ></sketch-network-status>
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000772
773 <sketch-call-status
774 .llmCalls=${this.containerState?.outstanding_llm_calls || 0}
775 .toolCalls=${this.containerState?.outstanding_tool_calls || []}
776 ></sketch-call-status>
Sean McCullough86b56862025-04-18 13:04:03 -0700777 </div>
778 </div>
779
Pokey Rule4097e532025-04-24 18:55:28 +0100780 <div id="view-container" ${ref(this.scrollContainerRef)}>
781 <div id="view-container-inner">
782 <div
783 class="chat-view ${this.viewMode === "chat" ? "view-active" : ""}"
784 >
785 <sketch-timeline
786 .messages=${this.messages}
787 .scrollContainer=${this.scrollContainerRef}
788 ></sketch-timeline>
789 </div>
790 <div
791 class="diff-view ${this.viewMode === "diff" ? "view-active" : ""}"
792 >
793 <sketch-diff-view
794 .commitHash=${this.currentCommitHash}
795 ></sketch-diff-view>
796 </div>
797 <div
798 class="chart-view ${this.viewMode === "charts"
799 ? "view-active"
800 : ""}"
801 >
802 <sketch-charts .messages=${this.messages}></sketch-charts>
803 </div>
804 <div
805 class="terminal-view ${this.viewMode === "terminal"
806 ? "view-active"
807 : ""}"
808 >
809 <sketch-terminal></sketch-terminal>
810 </div>
Sean McCullough86b56862025-04-18 13:04:03 -0700811 </div>
812 </div>
813
Pokey Rule4097e532025-04-24 18:55:28 +0100814 <div id="chat-input">
815 <sketch-chat-input @send-chat="${this._sendChat}"></sketch-chat-input>
816 </div>
Sean McCullough86b56862025-04-18 13:04:03 -0700817 `;
818 }
819
820 /**
Sean McCullough86b56862025-04-18 13:04:03 -0700821 * Lifecycle callback when component is first connected to DOM
822 */
823 firstUpdated(): void {
824 if (this.viewMode !== "chat") {
825 return;
826 }
827
828 // Initial scroll to bottom when component is first rendered
829 setTimeout(
830 () => this.scrollTo({ top: this.scrollHeight, behavior: "smooth" }),
Philip Zeyliger72682df2025-04-23 13:09:46 -0700831 50,
Sean McCullough86b56862025-04-18 13:04:03 -0700832 );
833
Sean McCullough71941bd2025-04-18 13:31:48 -0700834 const pollToggleCheckbox = this.renderRoot?.querySelector(
Philip Zeyliger72682df2025-04-23 13:09:46 -0700835 "#pollToggle",
Sean McCullough71941bd2025-04-18 13:31:48 -0700836 ) as HTMLInputElement;
Sean McCullough86b56862025-04-18 13:04:03 -0700837 pollToggleCheckbox?.addEventListener("change", () => {
838 this.dataManager.setPollingEnabled(pollToggleCheckbox.checked);
839 if (!pollToggleCheckbox.checked) {
840 this.connectionStatus = "disabled";
841 this.messageStatus = "Polling stopped";
842 } else {
843 this.messageStatus = "Polling for updates...";
844 }
845 });
Autoformattercf570962025-04-30 17:27:39 +0000846
Philip Zeyliger47b71c92025-04-30 15:43:39 +0000847 // Process any existing messages to find commit information
848 if (this.messages && this.messages.length > 0) {
849 this.updateLastCommitInfo(this.messages);
850 }
Sean McCullough86b56862025-04-18 13:04:03 -0700851 }
852}
853
854declare global {
855 interface HTMLElementTagNameMap {
856 "sketch-app-shell": SketchAppShell;
857 }
858}