Skip to content

🚀 Feature Request: Smart Session Management with Idle Detection #149

@synthanai

Description

@synthanai

🚀 Feature Request: Smart Session Management with Idle Detection

💡 Problem Statement

Long Claude Code sessions currently face several critical issues:

  • Context Loss on Crashes: Hours of work lost if VS Code or system crashes
  • No Periodic Backups: Unlike the existing checkpoint system which is manual, there’s no automatic context preservation during long sessions
  • Task Interruption Risk: Manual session closes can happen mid-task, leaving code in broken states
  • Context Window Bloat: Long sessions accumulate context that degrades Claude’s performance without intervention
  • Forgotten Manual Checkpoints: Developers get into flow state and forget to create checkpoints

🎯 Proposed Solution

Add Smart Session Management that monitors Claude’s activity state and performs actions only during idle periods to avoid interrupting active work.

✨ Core Features

1. 🟢 Idle State Detection

Monitor Claude’s activity to determine safe moments for intervention:

  • Activity Indicators:
    • API call activity (streaming responses)
    • Token generation status
    • Response completion events
    • File operation in progress
  • Visual Feedback:
    • 🟢 Idle - Waiting for input (safe for checkpoint)
    • 🟡 Thinking - Processing request (wait)
    • 🔴 Executing - Running tools/modifying files (wait)
  • Threshold: Mark as idle after 10-15 seconds of no activity

2. 💾 Smart Auto-Checkpoints

Automatic periodic backups that respect Claude’s workflow:

Configuration:

{
  "claudeCodeChat.smartSession.checkpointInterval": 20,  // minutes
  "claudeCodeChat.smartSession.checkpointPrompt": true,  // ask for user note
  "claudeCodeChat.smartSession.maxWaitTime": 5           // max minutes to wait for idle
}

Behavior:

  1. ⏰ Timer triggers every N minutes (default: 20)
  2. ⏳ Wait for Claude to become idle
  3. 📢 Show non-intrusive notification: “Safe checkpoint moment detected”
  4. 💬 Optional: Prompt user for quick status (30 second timeout)
  5. 💾 Auto-save checkpoint with:
  • Timestamped file in docs/checkpoints/checkpoint-YYYYMMDD-HHMMSS.md
  • Conversation summary
  • Files modified since last checkpoint
  • Current task context
  • Token/cost stats
  1. ✅ Continue session seamlessly

Timeout Handling:

  • If Claude stays busy for >5 minutes after checkpoint trigger, skip and reschedule
  • Log: “Checkpoint skipped - Claude busy”

3. ⏰ Smart Session Timeout

Graceful session closure that waits for safe moments:

Configuration:

{
  "claudeCodeChat.smartSession.sessionTimeout": 90,     // minutes
  "claudeCodeChat.smartSession.gracePeriod": 10,        // max minutes to wait
  "claudeCodeChat.smartSession.autoSummary": true       // generate final summary
}

Behavior:

  1. ⏱️ Track session duration
  2. ⏰ When timeout reached, wait for idle state
  3. 📢 Notification: “Session timeout - will close at next safe moment”
  4. ⏳ Grace period: up to 10 minutes to wait for idle
  5. 📝 Generate final summary via headless mode
  6. 🛑 Close session gracefully
  7. 🚨 Fallback: Force close after grace period expires (with warning)

4. 📊 Auto-Context Preservation

Each checkpoint automatically captures:

  • Conversation Summary: Key decisions and progress
  • Modified Files: List with timestamps
  • Current Task: What Claude was working on
  • Pending Work: TODOs and next steps
  • Session Stats: Tokens used, cost, duration
  • User Notes: Optional quick status updates

🎨 UI/UX Design

Status Bar Integration

💾 Last checkpoint: 15m ago | 🟢 Idle | ⏱️ 45m/90m
  • Click to manually trigger checkpoint
  • Shows time until next auto-checkpoint
  • Current session duration vs. timeout

Checkpoint Notification

┌────────────────────────────────────────────────┐
│ 💾 Safe Checkpoint #3 - 14:30:15               │
│                                                 │
│ Quick status update? (optional, 30s timeout)   │
│ ┌────────────────────────────────────────────┐ │
│ │ Implemented auth, testing API endpoints   │ │
│ └────────────────────────────────────────────┘ │
│                                                 │
│ [Save] [Skip]                                  │
└────────────────────────────────────────────────┘

Session Timeout Warning

┌────────────────────────────────────────────────┐
│ ⏰ Session Timeout Approaching                  │
│                                                 │
│ Session will close at next safe moment         │
│ (waiting for Claude to finish current task)    │
│                                                 │
│ Elapsed: 90/90 minutes                         │
│ Grace period: 2/10 minutes used                │
│                                                 │
│ [Extend Session] [Close Now]                   │
└────────────────────────────────────────────────┘

⚙️ Configuration Settings

interface SmartSessionConfig {
  // Enable/disable feature
  enabled: boolean;  // default: true
  
  // Checkpoint settings
  checkpointInterval: number;      // minutes, default: 20
  checkpointPrompt: boolean;       // ask for user note, default: true
  checkpointMaxWait: number;       // max minutes to wait for idle, default: 5
  
  // Timeout settings
  sessionTimeout: number;          // minutes, 0 = disabled, default: 90
  gracePeriod: number;             // max minutes to wait for safe close, default: 10
  autoSummary: boolean;            // generate summary on close, default: true
  
  // Idle detection
  idleThreshold: number;           // seconds of inactivity, default: 10
  
  // Storage
  checkpointDir: string;           // default: "docs/checkpoints"
  sessionLogDir: string;           // default: ".claude/sessions"
}

Settings UI Location

Add to existing Settings panel under new “Smart Session” tab

🔧 Technical Implementation Suggestions

Activity Detection

class ActivityMonitor {
  private lastActivityTime: number;
  private currentState: 'idle' | 'thinking' | 'executing';
  
  // Monitor API streaming events
  onStreamStart() { this.updateActivity('thinking'); }
  onStreamEnd() { this.checkIdleState(); }
  
  // Monitor tool execution
  onToolStart() { this.updateActivity('executing'); }
  onToolEnd() { this.checkIdleState(); }
  
  // Check if idle threshold reached
  isIdle(): boolean {
    const idleTime = Date.now() - this.lastActivityTime;
    return idleTime > this.config.idleThreshold * 1000;
  }
}

Checkpoint Manager

class CheckpointManager {
  private timer: NodeJS.Timer;
  
  async scheduleCheckpoint() {
    // Wait for idle state
    await this.waitForIdle({ maxWait: this.config.checkpointMaxWait });
    
    // Create checkpoint
    const checkpoint = await this.createCheckpoint({
      includeConversation: true,
      includeFileChanges: true,
      includeStats: true
    });
    
    // Optionally prompt user
    if (this.config.checkpointPrompt) {
      const userNote = await this.promptForNote({ timeout: 30 });
      checkpoint.userNote = userNote;
    }
    
    // Save to disk
    await this.saveCheckpoint(checkpoint);
  }
}

Integration Points

  • Hook into existing Git-based checkpoint system
  • Use VS Code’s window.withProgress for notifications
  • Store metadata in .claude/sessions/session-YYYYMMDD-HHMMSS.json
  • Integrate with existing cost/token tracking

🎁 Benefits

  1. 🛡️ Data Safety: Automatic backups prevent work loss from crashes
  2. 🎯 Task Protection: Never interrupts mid-task - respects developer flow
  3. 📈 Better Performance: Regular context pruning maintains Claude quality
  4. ⏱️ Time Savings: No manual checkpoint management needed
  5. 😌 Peace of Mind: Automatic safety nets for long sessions
  6. 🔄 Session Continuity: Easy to resume after interruptions with rich context

📚 Similar Features in Other Tools

  • JetBrains IDEs: Local History with idle detection
  • VS Code: Auto-save and hot exit with activity monitoring
  • tmux/screen: Session persistence with state preservation
  • Git: Auto-stash with working directory preservation

🎯 Priority Justification

HIGH PRIORITY - This addresses critical pain points:

  • ✅ Prevents data loss from crashes (common with VS Code extensions)
  • ✅ Solves context window bloat that degrades Claude performance
  • ✅ Eliminates forgotten manual checkpoints during deep work
  • ✅ Prevents destructive mid-task interruptions
  • ✅ Makes long coding sessions practical and safe

💭 Use Case Examples

Long Debugging Session

10:00 - Start debugging complex issue
10:20 - [Auto-checkpoint #1] "Found root cause in auth middleware"
10:40 - [Auto-checkpoint #2] "Implementing fix, added logging"
11:00 - [Auto-checkpoint #3] "Testing fix across edge cases"
11:20 - [Crash occurs]
11:21 - Restart VS Code
11:22 - Restore from checkpoint #3
11:23 - Continue testing with all context intact ✅

Feature Implementation

14:00 - Begin implementing payment integration
14:20 - [Auto-checkpoint #1] "Stripe API setup complete"
14:40 - [Auto-checkpoint #2] "Frontend form implemented"
15:00 - [Auto-checkpoint #3] "Backend webhook handlers done"
15:30 - [Session timeout warning - Claude idle]
15:31 - [Final summary generated]
15:32 - Session closes gracefully after completing current test ✅

🚀 Suggested Rollout

Phase 1: Basic Implementation

  • Idle detection system
  • Auto-checkpoint with fixed intervals
  • Simple notification system

Phase 2: Smart Features

  • Configurable intervals and thresholds
  • User prompt for checkpoint notes
  • Session timeout with grace period

Phase 3: Advanced Features

  • Activity-based checkpoints (trigger on significant changes)
  • Smart context pruning recommendations
  • Session analytics and insights

🔌 Alternative: Extension API

If full implementation is too complex, consider exposing hooks for community extensions:

// Extension API proposal
claudeCodeChat.onIdleStateChange((isIdle: boolean) => {
  // Community can implement custom checkpoint logic
});

claudeCodeChat.createCheckpoint({
  includeConversation: true,
  generateSummary: true,
  metadata: { custom: 'data' }
}): Promise<CheckpointId>;

claudeCodeChat.getActivityState(): 'idle' | 'thinking' | 'executing';

🤝 Offer to Help

I’m happy to:

  • Test beta versions and provide feedback
  • Contribute to implementation if needed
  • Help with documentation
  • Create demo videos showing the feature in action

Would love to see this feature! It would make Claude Code Chat even more robust for professional development workflows. Thank you for considering this request! 🙏

Related Issues: #15 (conversation memory) - this would complement that with persistent checkpoints

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions