Skip to content

Core: Implement Activity-Based Polling via Local Log Monitoring #70

Closed

Description

@propr-dev

Context

Instead of polling usage limits on a strict interval (which can consume unnecessary resources and CPU), we can monitor the local log directories of the AI CLIs (like ~/.config/claude/projects/, ~/.codex/sessions/, or Gemini logs). When new entries are written to these logs, it indicates the user is actively consuming tokens, and we should trigger a usage refresh. We want the user to be able to configure this effectively via a 3-modality mode selection.

Requirements

  1. Introduce an autoRefreshMode configuration that accepts 'none', 'interval', or 'activity' (defaulting to 'activity').
  2. Create an ActivityMonitor utility that watches known log directories for Claude, Codex, and Gemini using fs.watch.
  3. Make the activity debounce interval configurable.
  4. In 'activity' mode, the polling operates like an on-demand interval: it wakes up and starts its refresh cycle when activity is detected in the logs (delaying the first pull by the configured debounce), and goes back to an idle/disabled state when no further log activity is detected since the last check.
  5. Update CLI args in bin/agent-tank.js with --auto-refresh-mode and --activity-debounce and document the feature in README.md.

Acceptance Criteria

  • autoRefreshMode logic safely handles the three options (none, interval, activity), defaulting to activity.
  • ActivityMonitor successfully detects changes in target directories for Claude, Codex, and Gemini, triggering refreshes based on the provided debounce interval.
  • During active usage, polling functions as an interval loop; during idle periods, polling is disabled to save resources.
  • CLI and README are updated with these configurations.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Mar 16, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    We will use Node's native fs.watch to monitor the typical log paths for Claude, Codex, and Gemini. By tracking the activity state, we can simulate an on-demand interval loop: when log changes are detected, we fire the refresh callback (debounced to avoid hammering during token streaming) and keep the cycle alive. If no activity happens within the window, the cycle sleeps. Documentation is updated iteratively as required.

    File: src/activity-monitor.js

    Why this file: Encapsulates file system watching logic away from the main agent lifecycle, ensuring clean architecture.

    const fs = require('fs');
    const path = require('path');
    const os = require('os');
    
    class ActivityMonitor {
      constructor(refreshCallback, debounceMs = 60000) {
        this.refreshCallback = refreshCallback;
        this.debounceMs = debounceMs;
        this.timeout = null;
        this.watchers = [];
    
        // Standard paths for Codex, Claude, and Gemini logs
        this.targetDirs = [
          path.join(os.homedir(), '.codex', 'sessions'),
          path.join(os.homedir(), '.config', 'claude', 'projects'),
          path.join(os.homedir(), '.claude', 'projects'),
          path.join(os.homedir(), '.config', 'gemini'),
          path.join(os.homedir(), '.gemini')
        ];
      }
    
      start() {
        console.log('[ActivityMonitor] Starting to watch log directories for activity...');
        this.targetDirs.forEach(dir => {
          if (fs.existsSync(dir)) {
            try {
              const watcher = fs.watch(dir, { recursive: true }, (eventType, filename) => {
                // Triggers on any file change in the directory
                if (filename && !filename.startsWith('.')) {
                  this._onActivityDetected(dir, filename);
                }
              });
              this.watchers.push(watcher);
              console.log(`[ActivityMonitor] Watching directory: ${dir}`);
            } catch (err) {
              console.error(`[ActivityMonitor] Failed to watch ${dir}:`, err.message);
            }
          }
        });
      }
    
      stop() {
        this.watchers.forEach(w => w.close());
        this.watchers = [];
        if (this.timeout) {
          clearTimeout(this.timeout);
          this.timeout = null;
        }
      }
    
      _onActivityDetected(dir, filename) {
        // Debounce the refresh so we don't trigger it continuously during streaming.
        // Once triggered, if no more logs are written, the cycle automatically goes idle.
        if (this.timeout) {
          clearTimeout(this.timeout);
        }
        this.timeout = setTimeout(() => {
          console.log(`[ActivityMonitor] Activity settled (detected in ${filename}). Triggering refresh.`);
          this.refreshCallback();
        }, this.debounceMs);
      }
    }
    
    module.exports = { ActivityMonitor };

    File: src/index.js

    Why this file: We need to hook the ActivityMonitor into the main application lifecycle and respect the new autoRefreshMode (none, interval, or activity), providing it the refreshAll function as a callback.

    --- src/index.js
    +++ src/index.js
     @@ -4,6 +4,7 @@
     const { CodexAgent } = require('./agents/codex.js');
     const { discoverAgents } = require('./discovery.js');
     const { KeepaliveManager } = require('./keepalive-manager.js');
    +const { ActivityMonitor } = require('./activity-monitor.js');
     const { statusPage } = require('./status-page.js');
     
     class AgentTank {
     @@ -16,8 +17,11 @@
         this.agents = new Map();
         this.server = null;
     
    +    // Modality: 'none' | 'interval' | 'activity'
    +    this.autoRefreshMode = options.autoRefreshMode || (options.autoRefreshEnabled === false ? 'none' : 'activity');
    +
         // Auto-refresh configuration (backend periodic refresh)
         this.autoRefresh = {
    -      enabled: options.autoRefreshEnabled !== false, // Default: true
    +      enabled: this.autoRefreshMode === 'interval',
           interval: options.autoRefreshInterval ?? 60,   // Default: 60 seconds, 0 = disabled
         };
     @@ -22,6 +26,9 @@
         };
         
         // Instantiate the keepalive manager with a 30 min default
         this.keepaliveManager = new KeepaliveManager(options.keepaliveInterval || 1800000);
    +    
    +    // Instantiate the activity monitor with the configured interval acting as the debounce
    +    this.activityMonitor = new ActivityMonitor(() => this.refreshAll(), this.autoRefresh.interval * 1000);
         this.autoRefreshTimer = null;
         this.agentRefreshTimers = new Map(); // Per-agent timers for custom intervals
     @@ -83,7 +90,11 @@
     
    -    // Start backend auto-refresh if enabled
    -    this.startAutoRefresh();
    +    // Handle auto refresh modality
    +    if (this.autoRefreshMode === 'interval') {
    +      this.startAutoRefresh();
    +    } else if (this.autoRefreshMode === 'activity') {
    +      this.activityMonitor.start();
    +    }
         
         // Start session keepalive loop
         this.keepaliveManager.start();
       }
     
       startAutoRefresh() {
     @@ -318,6 +329,7 @@
     
       stop() {
         this.stopAutoRefresh();
         this.keepaliveManager.stop();
    +    this.activityMonitor.stop();
         for (const agent of this.agents.values()) {
           agent.killProcess();
         }

    File: bin/agent-tank.js

    Why this file: Expose the CLI configuration.

    --- bin/agent-tank.js
    +++ bin/agent-tank.js
     @@ -17,6 +17,8 @@
       'auto-discover': { type: 'boolean', default: true },
       'auto-refresh': { type: 'boolean', default: true },
       'auto-refresh-interval': { type: 'string', default: '60' },
    +  'auto-refresh-mode': { type: 'string', default: 'activity' },
    +  'activity-debounce': { type: 'string', default: '60000' },
     };

    File: README.md

    Why this file: Keep the documentation up to date.

    --- README.md
    +++ README.md
     @@ -12,6 +12,7 @@
     - **Lightweight** - Single dependency (node-pty)
     - **Multi-agent** - Monitor Claude, Gemini, and Codex simultaneously
     - **Secure by design** - No browser cookies, web scraping, or credential access
    +- **Activity-Based Polling** - Uses local log monitoring to only fetch data when you're actively generating tokens.
     
     ## Usage
     
     @@ -33,6 +34,8 @@
       --auto-discover       Auto-discover available agents (default: true)
       --auto-refresh        Enable/disable background auto-refresh (default: true)
       --auto-refresh-interval <seconds>  Auto-refresh interval in seconds (default: 60)
    +  --auto-refresh-mode <mode>         Refresh modality: 'none', 'interval', or 'activity' (default: activity)
    +  --activity-debounce <ms>           Debounce time for activity-based polling in ms (default: 60000)
       --help, -h            Show this help message
  2. propr-dev commented on Mar 17, 2026

    @propr-dev
    ContributorAuthor

    🤖 AI processing has started for this issue using claude agent with claude-opus-4-5-20251101 model.

    I'll analyze the problem and work on a solution. This may take a few minutes.

    Processing Details:

    • Agent: claude
    • Model: claude-opus-4-5-20251101
    • Branch: 70/claude-opus-4-5-20251101-core-implement-activity-b-20260317-0003-om7
    • Base Branch: 65-epic-implement-json-ctn
    • Worktree: issue-70-20260317-0003-claude-opus-4-5-20251101-om7

    🔍 Track Task Execution

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions