Skip to content

[Feature] Advanced Context Management System with Retention Strategies and Visualization #279

Closed

Description

@Avtrkrb

Description

Enhance Nanocoder's context management system to include advanced retention strategies, auto-compaction, and detailed visualization. Currently, Nanocoder has basic context management with token tracking but lacks sophisticated strategies for handling long conversations and approaching token limits. The system needs intelligent context preservation, proactive compaction, and better user visibility into context usage.

The feature will implement:

  • Multiple context retention strategies (preserve recent, smart compression, preserve important)
  • Auto-compaction system that triggers before token limits
  • Enhanced context visualization with detailed breakdown
  • Context caching and memoization for performance
  • Adaptive thresholds based on conversation complexity

Use Case

Current Problem:

  • Conversations hit token limits without intelligent preservation of important context
  • No proactive management when approaching token limits
  • Basic token visualization without detailed component analysis
  • No context caching leading to repeated calculations
  • Limited ability to handle long, complex conversations

Target Scenarios:

  1. Long Conversations: Handle extended debugging sessions or complex feature development
  2. Token Management: Proactively manage context before hitting limits
  3. Context Preservation: Maintain important information while compressing less critical parts
  4. Performance: Reduce redundant calculations through intelligent caching
  5. User Visibility: Provide clear understanding of context composition and usage

Proposed Solution

Phase 1: Core Context Management Enhancements (High Priority)

  1. Auto-compaction System - Implement basic preserve_recent strategy

    • Trigger at 85% context usage threshold
    • Keep most recent messages that fit within context limit
    • Show user notification when compaction occurs
  2. Enhanced Token Warnings - Add more granular warning levels

    • 70%: Informational warning
    • 85%: Auto-compaction trigger
    • 95%: Critical warning
  3. Context Cache - Basic caching for conversation state

    • Cache context generation and token calculations
    • Implement cache invalidation strategies
  4. Improved Visualization - Enhanced token breakdown display

    • Detailed component analysis (system, user, assistant, tool messages)
    • Color-coded warnings and progress indicators

Phase 2: Advanced Context Strategies (Medium Priority)

  1. Smart Compression - LLM-based context summarization

    • Generate comprehensive summaries of older messages
    • Preserve conversation flow and important details
  2. Multiple Retention Strategies - Add preserve_important strategy

    • Identify and preserve critical conversation elements
    • Use semantic analysis to determine importance
  3. Adaptive Thresholds - Dynamic compaction based on task type

    • Adjust thresholds based on conversation complexity
    • Different strategies for different development modes
  4. Context Validation - Ensure context quality before preservation

    • Validate compressed context maintains coherence
    • Quality checks for summary accuracy

Phase 3: Integration and Optimization (Low Priority)

  1. Preferences Integration - User-configurable context strategies

    • Allow users to choose preferred strategies
    • Customizable thresholds and behaviors
  2. Performance Optimization - Fine-tune caching and compression

    • Optimize for local LLM performance
    • Background processing where appropriate
  3. Advanced Visualization - Interactive context exploration

    • Clickable components to view details
    • Timeline view of context evolution
  4. Cross-session Context - Persistent context across conversations

    • Save important context between sessions
    • Project-level context persistence

Technical Implementation

Core Components

// Context retention strategy interface
export interface ContextRetentionStrategy {
  name: string;
  apply(messages: Message[], contextLimit: number): Message[];
  isApplicable(messages: Message[], contextLimit: number): boolean;
}

// Strategy implementations
class PreserveRecentStrategy implements ContextRetentionStrategy {
  name = 'preserve_recent';

  isApplicable(messages: Message[], contextLimit: number): boolean {
    return messages.length > 10 && this.calculateTokenCount(messages) > contextLimit * 0.8;
  }

  apply(messages: Message[], contextLimit: number): Message[] {
    // Keep most recent messages that fit within context limit
    const recentMessages = [];
    let totalTokens = 0;

    for (let i = messages.length - 1; i >= 0; i--) {
      const messageTokens = this.countMessageTokens(messages[i]);
      if (totalTokens + messageTokens <= contextLimit * 0.9) {
        recentMessages.unshift(messages[i]);
        totalTokens += messageTokens;
      } else {
        break;
      }
    }

    return recentMessages;
  }
}

class SmartCompressionStrategy implements ContextRetentionStrategy {
  name = 'smart_compression';

  isApplicable(messages: Message[], contextLimit: number): boolean {
    return messages.length > 20 && this.calculateTokenCount(messages) > contextLimit * 0.9;
  }

  async apply(messages: Message[], contextLimit: number): Promise<Message[]> {
    // Use LLM to generate comprehensive summary of older messages
    const summary = await this.generateSummary(messages.slice(0, -5));

    // Return summary + recent messages
    return [
      { role: 'system', content: `[Context Summary]: ${summary}` },
      ...messages.slice(-5)
    ];
  }
}

// Auto-compaction thresholds
export const AUTO_COMPACT_THRESHOLD_RATIO = 0.85;

// Enhanced context checker with auto-compaction
export const checkContextUsage = async (
  allMessages: Message[],
  systemMessage: Message,
  currentProvider: string,
  currentModel: string,
  addToChatQueue: (component: React.ReactNode) => void,
  getNextComponentKey: () => number,
  setMessages: (messages: Message[]) => void
): Promise<void> => {
  // ... existing token calculation logic ...

  // Add auto-compaction trigger
  if (percentUsed >= AUTO_COMPACT_THRESHOLD_RATIO * 100) {
    const strategy = selectBestStrategy(allMessages, contextLimit);
    if (strategy) {
      const compactedMessages = await strategy.apply(allMessages, contextLimit);
      setMessages(compactedMessages);

      addToChatQueue(
        <InfoMessage
          key={`auto-compact-${getNextComponentKey()}`}
          message={`Context auto-compacted to save space. ${allMessages.length} → ${compactedMessages.length} messages.`}
          hideBox={true}
        />
      );
    }
  }

  // ... existing warning logic ...
}

// Context cache manager
export class ContextCacheManager {
  private static instance: ContextCacheManager;
  private cache: Map<string, any> = new Map();
  private maxCacheSize = 100;

  private constructor() {}

  public static getInstance(): ContextCacheManager {
    if (!ContextCacheManager.instance) {
      ContextCacheManager.instance = new ContextCacheManager();
    }
    return ContextCacheManager.instance;
  }

  public getOrCreate<T>(key: string, creator: () => T): T {
    if (this.cache.has(key)) {
      return this.cache.get(key);
    }

    const value = creator();
    this.cache.set(key, value);

    // Enforce cache size limit
    if (this.cache.size > this.maxCacheSize) {
      const firstKey = this.cache.keys().next().value;
      this.cache.delete(firstKey);
    }

    return value;
  }

  public invalidate(key: string): void {
    this.cache.delete(key);
  }

  public clear(): void {
    this.cache.clear();
  }
}

Integration Points

  • Conversation State: Enhance ConversationStateManager in source/app/utils/conversation-state.ts
  • Context Checker: Modify source/hooks/chat-handler/utils/context-checker.tsx
  • Usage Display: Enhance source/components/usage/usage-display.tsx
  • Token Calculator: Update source/usage/calculator.ts

Files to Modify/Create

  • source/app/utils/context-strategies.ts (new) - Strategy implementations
  • source/app/utils/conversation-state.ts (modify) - Integrate strategies
  • source/hooks/chat-handler/utils/context-checker.tsx (modify) - Auto-compaction
  • source/components/usage/usage-display.tsx (enhance) - Enhanced visualization
  • source/components/usage/context-breakdown-table.tsx (new) - Detailed breakdown
  • source/components/usage/conversation-progress-display.tsx (new) - Progress display
  • source/app/utils/context-cache.ts (new) - Context caching system
  • source/constants.ts (modify) - Add auto-compaction constants

Alternatives Considered

  1. Simple Sliding Window: Considered but rejected for losing important early context
  2. Aggressive Pruning: Rejected for potentially removing critical information
  3. No Auto-compaction: Rejected as it leads to hard token limit failures
  4. Fixed Thresholds: Rejected for lack of adaptability to conversation complexity

Additional Context

  • I have searched existing issues to ensure this is not a duplicate
  • This feature aligns with the project's goals (local-first AI assistance)
  • The implementation considers local LLM performance constraints
  • Memory efficiency is prioritized for local usage

Performance Considerations

  • Streaming-friendly compression for local models
  • Lazy context loading to minimize memory usage
  • Background compression to avoid blocking conversations
  • Token-efficient summaries optimized for smaller models

Local LLM Adaptations

  • Model-specific strategies for different model sizes
  • Fallback mechanisms when compression fails
  • Token budgeting to reserve space for critical operations
  • Incremental processing to avoid memory spikes

Implementation Notes (optional)

Key Integration Points

  • Hook into existing ConversationStateManager
  • Integrate with token usage checking in context-checker.tsx
  • Add strategy selection to preferences system
  • Enhance existing /usage command with detailed breakdown

Testing Strategy

  • Unit tests for context retention strategies
  • Integration tests for auto-compaction system
  • Performance tests for caching mechanisms
  • Memory usage monitoring during long conversations
  • Token efficiency measurements

Migration Path

  • All new features will be optional and backward compatible
  • Existing context management remains as fallback
  • Gradual rollout with configurable thresholds
  • User preferences for strategy selection

Success Metrics

  • Context Utilization: Increase average context usage from 60% to 85%+ before compaction
  • Token Efficiency: Reduce token waste by 30% through smart compression
  • Performance Impact: Maintain <100ms overhead for context management operations
  • Memory Usage: Keep memory footprint increase under 15%
  • Compaction Effectiveness: Achieve 40%+ average token reduction when triggered
  • User Satisfaction: Positive feedback on context management transparency

Activity

  1. added
    enhancement
    performance
    on Jan 7, 2026
  2. added theissue type on Jan 7, 2026
  3. will-lamerton commented on May 18, 2026

    @will-lamerton
    Member

    Closing due to not much movement on the issue as well as partial implementation of the features described.

    In main we now have smart llm-based compression, auto-compaction has been introduced as well as various other features adjacent.

    Feel free to open new issues of missing features with smaller scopes :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:tuienhancementperformance

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions