Skip to content

Conversation

romio1225
Copy link

@romio1225 romio1225 commented Aug 4, 2025

🔧 Fix: Session Management Issues in ADK Web UI

📋 Overview

This PR addresses multiple session management issues in the ADK Web UI that were causing poor user experience, including duplicate session creation, invalid session handling, and inconsistent session state management across components.

🐛 Issues Fixed

1. Agent Selection Creates New Sessions Instead of Reusing Existing Sessions

Problem: When switching between agents, new sessions were always created even when existing sessions were available.

Solution: Modified selectApp() method in chat.component.ts to:

  • Check for existing sessions before creating new ones
  • Automatically select the most recent session based on lastUpdateTime
  • Only create new sessions when no existing sessions are found

Files Changed: src/app/components/chat/chat.component.ts

2. Invalid Session URL Handling

Problem: When URL contained invalid session IDs, the system would create new sessions instead of redirecting to valid ones.

Solution: Enhanced error handling in session retrieval to:

  • Attempt to find existing sessions when specified session is not found
  • Redirect to the most recent valid session
  • Fallback to new session creation only when no sessions exist

Files Changed: src/app/components/chat/chat.component.ts

3. Session Tab Not Updating on Agent Change

Problem: When switching agents, the Sessions tab would not refresh to show sessions for the newly selected agent.

Solution: Implemented OnChanges lifecycle hook in SessionTabComponent:

  • Added ngOnChanges() method to detect appName and userId changes
  • Automatically refresh session list when agent changes
  • Added proper logging for debugging

Files Changed: src/app/components/session-tab/session-tab.component.ts

4. Page Load Session Validation Missing

Problem: When loading pages with invalid session IDs in URL, no validation occurred, leading to broken states.

Solution: Added validateAndFixSessionUrl() method:

  • Validates session ID on page load
  • Automatically redirects to most recent valid session if current session is invalid
  • Ensures consistent session state across page refreshes

Files Changed: src/app/components/chat/chat.component.ts

5. Duplicate Session Creation on Session Deletion

Problem: When deleting the last session, multiple new sessions were created due to window.location.reload() triggering multiple components.

Solution: Replaced window.location.reload() with createSessionAndReset():

  • Ensures only one new session is created
  • Maintains proper component state
  • Prevents race conditions between components

Files Changed: src/app/components/chat/chat.component.ts

6. Backend URL Configuration

Problem: Runtime configuration pointed to wrong port (8000 instead of 8080).

Solution: Updated runtime configuration:

  • Changed backendUrl from http://localhost:8000 to http://localhost:8080

Files Changed: src/assets/config/runtime-config.json

🔄 Technical Details

Session Reuse Logic

// Before: Always create new session
this.createSessionAndReset();

// After: Check existing sessions first
this.sessionService.listSessions(this.userId, this.appName)
  .subscribe((sessions) => {
    if (sessions && sessions.length > 0) {
      const latestSession = sessions.reduce((latest, current) => 
        current.lastUpdateTime > latest.lastUpdateTime ? current : latest
      );
      this.updateWithSelectedSession(latestSession);
    } else {
      this.createSessionAndReset();
    }
  });

Session Validation on Page Load

private validateAndFixSessionUrl() {
  combineLatest([this.agentService.getApp(), this.router.events])
    .pipe(
      filter(([appName, params]) => !!appName && !!params['session']),
      switchMap(([appName, params]) => {
        return this.sessionService.getSession(this.userId, appName, params['session'])
          .pipe(
            catchError(() => {
              // If session not found, try to use latest existing session
              return this.sessionService.listSessions(this.userId, appName)
                .pipe(switchMap(sessions => /* redirect to latest session */));
            })
          );
      })
    ).subscribe();
}

Sessions Tab Auto-Update

ngOnChanges(changes: SimpleChanges): void {
  if ((changes['appName'] && !changes['appName'].firstChange) || 
      (changes['userId'] && !changes['userId'].firstChange)) {
    this.refreshSessionsSubject.next();
  }
}

🧪 Testing

Manual Testing Scenarios

  1. Agent Switching: Switch between agents → Existing sessions are reused
  2. Invalid URL: Access URL with invalid session ID → Redirects to valid session
  3. Session Deletion: Delete last session → Only one new session created
  4. Page Refresh: Refresh with invalid session → Auto-corrects to valid session
  5. Sessions Tab: Change agent → Sessions list updates automatically

Expected Behavior

  • ✅ No unnecessary session creation
  • ✅ Intelligent session reuse
  • ✅ Consistent UI state across components
  • ✅ Proper error handling for invalid sessions
  • ✅ Single session creation on deletion

📊 Impact

Before

  • 🔴 Multiple sessions created unnecessarily
  • 🔴 Broken state with invalid session URLs
  • 🔴 Inconsistent Sessions tab behavior
  • 🔴 Poor user experience with session management

After

  • ✅ Intelligent session reuse
  • ✅ Automatic session validation and correction
  • ✅ Consistent UI behavior across all components
  • ✅ Improved user experience with seamless session management

🚨 Breaking Changes

None. All changes are backward compatible and improve existing functionality without changing public APIs.

📝 Additional Notes

Logging Added

  • Session validation attempts
  • Session reuse decisions
  • Agent change detections
  • Error scenarios for easier debugging

Error Handling Improved

  • Graceful fallback when sessions are not found
  • Better error messages in console
  • Consistent error recovery patterns

🔗 Related Issues

This PR addresses user experience issues related to:

  • Session lifecycle management
  • Agent switching workflow
  • URL state consistency
  • Component synchronization

✅ Checklist

  • Code follows project style guidelines
  • Self-review completed
  • Manual testing performed
  • No breaking changes introduced
  • All scenarios tested and working
  • Console logs added for debugging support
  • Error handling improved
  • Component lifecycle properly managed

Summary: This PR significantly improves the ADK Web UI session management system by implementing intelligent session reuse, proper validation, and consistent component behavior, resulting in a much better user experience.

@wyf7107
Copy link
Collaborator

wyf7107 commented Sep 15, 2025

Hi @romio1225 Thank you for making such detailed fixes, some feedback for the issues mentioned here:

  1. and 2) are expected at this point, we can research into if creating a new session is better or loading an existing one
  2. and 4) are bugs that need to be fixed.
  3. When I delete the last session, only one new session was created for me
  4. Please do not update this, this is supposed to be modified on the fly for developers using different port, not used in production

Do you mind resolve your conflicts and only fix 3) and 4) at this point? That would be awesome thanks!

@romio1225
Copy link
Author

romio1225 commented Sep 17, 2025 via email

ilteris pushed a commit to ilteris/adk-web that referenced this pull request Oct 4, 2025
…lteris

feat: preserve canvas layout and update sub-agent UI
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants