Repository navigation
Description
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:
- Long Conversations: Handle extended debugging sessions or complex feature development
- Token Management: Proactively manage context before hitting limits
- Context Preservation: Maintain important information while compressing less critical parts
- Performance: Reduce redundant calculations through intelligent caching
- User Visibility: Provide clear understanding of context composition and usage
Proposed Solution
Phase 1: Core Context Management Enhancements (High Priority)
-
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
-
Enhanced Token Warnings - Add more granular warning levels
- 70%: Informational warning
- 85%: Auto-compaction trigger
- 95%: Critical warning
-
Context Cache - Basic caching for conversation state
- Cache context generation and token calculations
- Implement cache invalidation strategies
-
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)
-
Smart Compression - LLM-based context summarization
- Generate comprehensive summaries of older messages
- Preserve conversation flow and important details
-
Multiple Retention Strategies - Add preserve_important strategy
- Identify and preserve critical conversation elements
- Use semantic analysis to determine importance
-
Adaptive Thresholds - Dynamic compaction based on task type
- Adjust thresholds based on conversation complexity
- Different strategies for different development modes
-
Context Validation - Ensure context quality before preservation
- Validate compressed context maintains coherence
- Quality checks for summary accuracy
Phase 3: Integration and Optimization (Low Priority)
-
Preferences Integration - User-configurable context strategies
- Allow users to choose preferred strategies
- Customizable thresholds and behaviors
-
Performance Optimization - Fine-tune caching and compression
- Optimize for local LLM performance
- Background processing where appropriate
-
Advanced Visualization - Interactive context exploration
- Clickable components to view details
- Timeline view of context evolution
-
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
ConversationStateManagerinsource/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 implementationssource/app/utils/conversation-state.ts(modify) - Integrate strategiessource/hooks/chat-handler/utils/context-checker.tsx(modify) - Auto-compactionsource/components/usage/usage-display.tsx(enhance) - Enhanced visualizationsource/components/usage/context-breakdown-table.tsx(new) - Detailed breakdownsource/components/usage/conversation-progress-display.tsx(new) - Progress displaysource/app/utils/context-cache.ts(new) - Context caching systemsource/constants.ts(modify) - Add auto-compaction constants
Alternatives Considered
- Simple Sliding Window: Considered but rejected for losing important early context
- Aggressive Pruning: Rejected for potentially removing critical information
- No Auto-compaction: Rejected as it leads to hard token limit failures
- 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
/usagecommand 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
will-lamerton commentedon May 18, 2026
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 :)