Elffuss BraidHub

kikocis/continue public

ee5deccdeded · 11.1 KiBSourceRawPermalink

ChatHistoryService Migration Plan

Overview

This document outlines a gradual migration plan to move from the current mixed state management approach (React state + direct mutations) to a centralized ChatHistoryService that acts as the single source of truth for chat history.

Current State Analysis

Problems

Affected Files

Migration Strategy

Phase 1: Create ChatHistoryService (Day 1)

Goal: Establish the service foundation without breaking existing code

1.1 Create Service Implementation

// src/services/ChatHistoryService.ts
export interface ChatHistoryState {
  history: ChatHistoryItem[];
  compactionIndex: number | null;
  sessionId: string;
  isRemoteMode: boolean;
}

export class ChatHistoryService extends BaseService<ChatHistoryState> {
  // Implementation details below
}

1.2 Service Methods to Implement

1.3 Register Service

1.4 Write Unit Tests

Deliverable: Working service with tests, no integration yet

Phase 2: Wrapper Integration (Day 1-2)

Goal: Wrap existing code to use service without changing behavior

2.1 Create Compatibility Layer

// src/services/ChatHistoryCompatibility.ts
export function createChatHistoryProxy(service: ChatHistoryService) {
  return new Proxy([], {
    get(target, prop) {
      if (prop === "push") {
        return (item) => service.addHistoryItem(item);
      }
      // Delegate reads to service.getHistory()
      const history = service.getHistory();
      return history[prop];
    },
  });
}

2.2 Update useChat Hook

// In useChat.ts
const chatHistoryService = useService<ChatHistoryState>("chatHistory");

useEffect(() => {
  if (chatHistoryService.state === "ready") {
    setChatHistory(chatHistoryService.value.history);
  }
}, [chatHistoryService]);

2.3 Add Service Methods to Mirror State Updates

Deliverable: Service running in parallel with existing state

Phase 3: Migrate Stream Processing (Day 2)

Goal: Update streaming functions to use service

3.1 Update handleToolCalls.ts

// Before:
chatHistory.push(createHistoryItem(...));

// After:
await chatHistoryService.addHistoryItem(createHistoryItem(...));

3.2 Update streamChatResponse.ts

3.3 Update Stream Callbacks

3.4 Test Streaming

Deliverable: All streaming using service, no direct mutations

Phase 4: Remove React State Duplication (Day 2-3)

Goal: Remove useState and rely solely on service

4.1 Update useChat to Use Service Directly

// Remove:
const [chatHistory, setChatHistory] = useState<ChatHistoryItem[]>(...);

// Replace with:
const { value: chatHistoryState, state } = useService<ChatHistoryState>('chatHistory');
const chatHistory = chatHistoryState?.history || [];

4.2 Update All Components

4.3 Remove Compatibility Layer

Deliverable: Single source of truth established

Phase 5: Optimize and Enhance (Day 3)

Goal: Add optimizations and missing features

5.1 Performance Optimizations

5.2 Add Advanced Features

5.3 Remote Mode Integration

5.4 Update Documentation

Deliverable: Optimized service with full feature set

Status: Completed

Notes: Further optimizations (batching/memoization) can be added if performance profiling indicates need with very large histories.

Phase 6: Validation and Cleanup (Day 3-4)

Goal: Ensure migration is complete and stable

6.1 Comprehensive Testing

6.2 Code Cleanup

6.3 Migration Verification Checklist

Rollback Plan

If issues arise during migration:

  1. Phase 1-2: No impact, service runs in parallel
  2. Phase 3: Revert stream processing changes, keep service
  3. Phase 4: Revert to dual state temporarily
  4. Phase 5-6: Feature flags for new capabilities

Testing Strategy

Unit Tests

Integration Tests

E2E Tests

Success Metrics

  1. No regressions: All existing functionality works
  2. Performance: No noticeable slowdown
  3. Maintainability: Cleaner, more testable code
  4. Reliability: No state inconsistencies
  5. Developer experience: Easier to understand and modify

Risk Mitigation

High Risk Areas

  1. Streaming integration: Most complex change

    • Mitigation: Extensive testing, gradual rollout
  2. Remote mode: Different state management

    • Mitigation: Test thoroughly, maintain compatibility
  3. Performance: Large histories might cause issues

    • Mitigation: Profiling, optimization, lazy loading

Monitoring

Timeline

Total: 4 days with buffer for issues

Implementation Checklist

Pre-Migration

Phase 1

Phase 2

Phase 3

Phase 4

Phase 5

Phase 6

Post-Migration

  1. Monitor for issues for 1 week
  2. Gather performance metrics
  3. Document lessons learned
  4. Plan future enhancements
  5. Knowledge transfer to team

Appendix: Code Examples

Service Method Example

class ChatHistoryService extends BaseService<ChatHistoryState> {
  addUserMessage(content: string, contextItems: any[] = []) {
    const newMessage: ChatHistoryItem = {
      message: { role: "user", content },
      contextItems,
    };

    const newHistory = [...this.currentState.history, newMessage];
    this.setState({
      ...this.currentState,
      history: newHistory,
    });

    // Auto-save to session
    updateSessionHistory(newHistory);

    return newMessage;
  }
}

React Integration Example

function ChatComponent() {
  const { value: chatState, state } = useService<ChatHistoryState>('chatHistory');

  if (state === 'loading') return <LoadingSpinner />;
  if (state === 'error') return <ErrorMessage />;

  const history = chatState?.history || [];

  return <ChatMessages history={history} />;
}

Migration Pattern Example

// Before:
chatHistory.push(newMessage);
setChatHistory([...chatHistory]);

// After:
chatHistoryService.addMessage(newMessage);
// React auto-updates via useService hook