webui: implement explicit initial render detection using State.message_count

Add explicit initial load completion detection to SketchTimeline component using
State.message_count to determine when all existing messages have been loaded
and the timeline is ready for initial render.

Implementation Changes:

1. DataManager Enhancement (data.ts):
   - Add expectedMessageCount and isInitialLoadComplete state tracking
   - Add 'initialLoadComplete' event type to DataManagerEventType union
   - Add checkInitialLoadComplete() method to validate completion state
   - Add handleInitialLoadComplete() event emission with message counts
   - Handle empty conversation edge case (message_count: 0) with immediate completion
   - Reset initial load state on connection establishment to handle reconnection
   - Add getIsInitialLoadComplete() and getExpectedMessageCount() getters

2. Timeline Component Enhancement (sketch-timeline.ts):
   - Add isInitialLoadComplete state property for render control
   - Add dataManager property reference for event listener setup
   - Add handleInitialLoadComplete() event handler with console logging
   - Update render logic to show loading indicator until initial load complete
   - Apply 'view-initialized' CSS class when initial load completes
   - Only render messages and thinking indicator after initial load completion
   - Set up DataManager event listeners in updated() lifecycle hook
   - Clean up event listeners in disconnectedCallback() lifecycle hook

3. App Shell Integration (sketch-app-shell.ts):
   - Pass dataManager reference to sketch-timeline component property
   - Enable timeline component to receive initial load completion events
   - Maintain existing data flow while adding explicit completion detection

4. Demo Mock Enhancement (handlers.ts):
   - Initialize currentState with correct message_count based on initial messages
   - Ensure proper message_count synchronization in SSE stream simulation
   - Handle empty conversation demo scenario with accurate state

5. Enhanced CSS Styling (sketch-timeline.ts):
   - Add opacity-based transitions for message appearance
   - Show loading indicator before initial completion
   - Hide message content until view-initialized class is applied
   - Smooth transition from loading to content display

Technical Benefits:
- Eliminates reliance on implicit 'first message means streaming started' detection
- Provides explicit completion signal when all existing messages are loaded
- Handles edge cases like empty conversations (0 messages) immediately
- Prevents flash of incomplete content during initial load
- Enables proper loading states and smooth transitions
- Supports reconnection scenarios with state reset

User Experience Improvements:
- Clear loading indicator until conversation is fully loaded
- Smooth transition from loading to content display
- No flash of partial message lists during initial load
- Consistent behavior across different conversation sizes
- Better feedback during network delays or large conversation loads

Edge Case Handling:
- Empty conversations (message_count: 0) marked complete immediately
- Messages arriving before state handled gracefully
- Reconnection scenarios reset initial load detection
- Race conditions between state and message delivery resolved

This replaces the implicit initial load detection with explicit State.message_count
based completion detection, providing more reliable initial render timing and
better user experience during conversation loading.

Co-Authored-By: sketch <hello@sketch.dev>
Change-ID: s5126c2705d6ad6bak
diff --git a/webui/src/web-components/sketch-timeline.ts b/webui/src/web-components/sketch-timeline.ts
index 5dae38a..2f8e5e3 100644
--- a/webui/src/web-components/sketch-timeline.ts
+++ b/webui/src/web-components/sketch-timeline.ts
@@ -51,6 +51,13 @@
   @property({ attribute: false })
   state: State | null = null;
 
+  // Track initial load completion for better rendering control
+  @state()
+  private isInitialLoadComplete: boolean = false;
+
+  @property({ attribute: false })
+  dataManager: any = null; // Reference to DataManager for event listening
+
   // Viewport rendering properties
   @property({ attribute: false })
   initialMessageCount: number = 30;
@@ -71,20 +78,20 @@
   private loadingTimeoutId: number | null = null;
 
   static styles = css`
-    /* Hide views initially to prevent flash of content */
-    .timeline-container .timeline,
-    .timeline-container .diff-view,
-    .timeline-container .chart-view,
-    .timeline-container .terminal-view {
-      visibility: hidden;
+    /* Hide message content initially to prevent flash of incomplete content */
+    .timeline-container:not(.view-initialized) sketch-timeline-message {
+      opacity: 0;
+      transition: opacity 0.2s ease-in;
     }
 
-    /* Will be set by JavaScript once we know which view to display */
-    .timeline-container.view-initialized .timeline,
-    .timeline-container.view-initialized .diff-view,
-    .timeline-container.view-initialized .chart-view,
-    .timeline-container.view-initialized .terminal-view {
-      visibility: visible;
+    /* Show content once initial load is complete */
+    .timeline-container.view-initialized sketch-timeline-message {
+      opacity: 1;
+    }
+
+    /* Always show loading indicators */
+    .timeline-container .loading-indicator {
+      opacity: 1;
     }
 
     .timeline-container {
@@ -96,6 +103,7 @@
       box-sizing: border-box;
       overflow-x: hidden;
       flex: 1;
+      min-height: 100px; /* Ensure container has height for loading indicator */
     }
 
     /* Chat-like timeline styles */
@@ -693,6 +701,35 @@
    * Called after the component's properties have been updated
    */
   updated(changedProperties: PropertyValues): void {
+    // Handle DataManager changes to set up event listeners
+    if (changedProperties.has("dataManager")) {
+      const oldDataManager = changedProperties.get("dataManager");
+
+      // Remove old event listener if it exists
+      if (oldDataManager) {
+        oldDataManager.removeEventListener(
+          "initialLoadComplete",
+          this.handleInitialLoadComplete,
+        );
+      }
+
+      // Add new event listener if dataManager is available
+      if (this.dataManager) {
+        this.dataManager.addEventListener(
+          "initialLoadComplete",
+          this.handleInitialLoadComplete,
+        );
+
+        // Check if initial load is already complete
+        if (
+          this.dataManager.getIsInitialLoadComplete &&
+          this.dataManager.getIsInitialLoadComplete()
+        ) {
+          this.isInitialLoadComplete = true;
+        }
+      }
+    }
+
     // Handle scroll container changes first to prevent race conditions
     if (changedProperties.has("scrollContainer")) {
       // Cancel any ongoing loading operations since container is changing
@@ -813,6 +850,20 @@
   }
 
   /**
+   * Handle initial load completion from DataManager
+   */
+  private handleInitialLoadComplete = (eventData: {
+    messageCount: number;
+    expectedCount: number;
+  }): void => {
+    console.log(
+      `Timeline: Initial load complete - ${eventData.messageCount}/${eventData.expectedCount} messages`,
+    );
+    this.isInitialLoadComplete = true;
+    this.requestUpdate();
+  };
+
+  /**
    * Set up observers for event-driven DOM monitoring
    */
   private setupObservers(): void {
@@ -834,6 +885,14 @@
       this._handleShowCommitDiff as EventListener,
     );
 
+    // Remove DataManager event listener if connected
+    if (this.dataManager) {
+      this.dataManager.removeEventListener(
+        "initialLoadComplete",
+        this.handleInitialLoadComplete,
+      );
+    }
+
     // Use our safe cleanup method
     this.removeScrollListener();
   }
@@ -888,10 +947,23 @@
     const isThinking =
       this.llmCalls > 0 || (this.toolCalls && this.toolCalls.length > 0);
 
+    // Apply view-initialized class when initial load is complete
+    const containerClass = this.isInitialLoadComplete
+      ? "timeline-container view-initialized"
+      : "timeline-container";
+
     return html`
       <div style="position: relative; height: 100%;">
         <div id="scroll-container">
-          <div class="timeline-container">
+          <div class="${containerClass}">
+            ${!this.isInitialLoadComplete
+              ? html`
+                  <div class="loading-indicator">
+                    <div class="loading-spinner"></div>
+                    <span>Loading conversation...</span>
+                  </div>
+                `
+              : ""}
             ${this.isLoadingOlderMessages
               ? html`
                   <div class="loading-indicator">
@@ -900,30 +972,32 @@
                   </div>
                 `
               : ""}
-            ${repeat(
-              this.visibleMessages,
-              this.messageKey,
-              (message, index) => {
-                // Find the previous message in the full filtered messages array
-                const filteredMessages = this.filteredMessages;
-                const messageIndex = filteredMessages.findIndex(
-                  (m) => m === message,
-                );
-                let previousMessage =
-                  messageIndex > 0
-                    ? filteredMessages[messageIndex - 1]
-                    : undefined;
+            ${this.isInitialLoadComplete
+              ? repeat(
+                  this.visibleMessages,
+                  this.messageKey,
+                  (message, index) => {
+                    // Find the previous message in the full filtered messages array
+                    const filteredMessages = this.filteredMessages;
+                    const messageIndex = filteredMessages.findIndex(
+                      (m) => m === message,
+                    );
+                    let previousMessage =
+                      messageIndex > 0
+                        ? filteredMessages[messageIndex - 1]
+                        : undefined;
 
-                return html`<sketch-timeline-message
-                  .message=${message}
-                  .previousMessage=${previousMessage}
-                  .open=${false}
-                  .firstMessageIndex=${this.firstMessageIndex}
-                  .state=${this.state}
-                ></sketch-timeline-message>`;
-              },
-            )}
-            ${isThinking
+                    return html`<sketch-timeline-message
+                      .message=${message}
+                      .previousMessage=${previousMessage}
+                      .open=${false}
+                      .firstMessageIndex=${this.firstMessageIndex}
+                      .state=${this.state}
+                    ></sketch-timeline-message>`;
+                  },
+                )
+              : ""}
+            ${isThinking && this.isInitialLoadComplete
               ? html`
                   <div class="thinking-indicator">
                     <div class="thinking-bubble">