src — tasks

Module: src-tasks Cohesion: 0.80 Members: 0

src — tasks

The src/tasks module provides a robust system for managing long-running, asynchronous AI tasks in the background. Inspired by cloud-based task runners, it allows the application to initiate AI operations (like code generation or refactoring) without blocking the main thread, persist their state across restarts, and notify users upon completion or failure.

Module Overview

The primary goal of this module is to enable "fire-and-forget" execution of AI prompts. When a user issues a command that might take a significant amount of time, it can be offloaded to the BackgroundTaskManager. This manager handles:

Core Concepts

BackgroundTask

The central data structure representing an AI task.

export interface BackgroundTask {
  id: string; class="hl-cmt">// Unique identifier
  prompt: string; class="hl-cmt">// The AI prompt to execute
  status: TaskStatus; class="hl-cmt">// Current status (pending, running, completed, failed, cancelled)
  priority: TaskPriority; class="hl-cmt">// Execution priority (low, normal, high)
  createdAt: Date;
  startedAt?: Date;
  completedAt?: Date;
  result?: TaskResult; class="hl-cmt">// Outcome of the task
  workingDirectory: string; class="hl-cmt">// Directory where the task should run
  model?: string; class="hl-cmt">// Specific AI model to use
  maxToolRounds?: number; class="hl-cmt">// Max tool calls for the AI
  tags?: string[]; class="hl-cmt">// Optional tags for categorization
  notifyOn?: ('completed' | 'failed')[]; class="hl-cmt">// Events to trigger notifications
  notifyChannel?: string; class="hl-cmt">// Channel identifier for notifications (e.g., "telegram:chat-123")
}

TaskStatus

Defines the possible states a task can be in: 'pending', 'running', 'completed', 'failed', 'cancelled'.

TaskPriority

Influences the order in which pending tasks are picked up: 'low', 'normal', 'high'.

TaskResult

Captures the outcome of a completed or failed task:

export interface TaskResult {
  success: boolean;
  output?: string; class="hl-cmt">// Standard output from the task
  error?: string; class="hl-cmt">// Error message if failed
  filesModified?: string[]; class="hl-cmt">// (Future use) List of files modified
  duration?: number; class="hl-cmt">// Execution time in milliseconds
}

BackgroundTaskManager Class

This class is the core of the module, responsible for all task management operations. It extends EventEmitter to allow other parts of the application to subscribe to task lifecycle events.

Initialization and Persistence

The BackgroundTaskManager is initialized with a maxConcurrent limit (defaulting to 3).

Task Lifecycle Management

The manager provides methods to control the entire lifecycle of a task.

createTask(prompt: string, options: { ... })

runTask(taskId: string)

This is the core execution method.

  1. Validation: Checks if the task exists, is not already running, and if the maxConcurrent limit has not been reached.
  2. State Update: Sets task.status = 'running', records startedAt, and calls saveTask().
  3. Event Emission: Emits a 'task-started' event.
  4. Child Process Execution:

  1. Output Handling:

  1. Completion/Failure:

cancelTask(taskId: string)

retryTask(taskId: string)

deleteTask(taskId: string)

clearCompleted()

Task State and Querying

Notifications

Concurrency Control

The maxConcurrent property, set in the constructor, limits how many tasks can be in the 'running' state simultaneously. runTask() enforces this limit, throwing an error if exceeded.

Display Utilities

Event Emitter

BackgroundTaskManager extends EventEmitter and emits the following events:

Resource Cleanup

Task Status Lifecycle

The following diagram illustrates the transitions between different TaskStatus states:

stateDiagram
    direction LR
    [*] --> pending
    pending --> running : runTask()
    running --> completed : Child process exits (code 0)
    running --> failed : Child process exits (code != 0)
    running --> failed : Child process error
    running --> cancelled : cancelTask()
    pending --> cancelled : cancelTask()
    completed --> [*] : deleteTask() / clearCompleted()
    failed --> [*] : deleteTask() / clearCompleted()
    cancelled --> [*] : deleteTask() / clearCompleted()
    failed --> pending : retryTask() (creates new task)

Usage and Integration

Singleton Access

The module provides a singleton instance of BackgroundTaskManager to ensure consistent state across the application:

CLI Integration

The runTask method's use of spawn('node', [codebuddyPath, ...args]) indicates that this module is designed to integrate directly with the main grok CLI. When a background task is initiated, it essentially re-invokes the grok command-line tool in a separate process, passing the prompt and other parameters. This allows the background tasks to leverage the full capabilities of the grok CLI without needing to duplicate its logic.

Channels Module Integration

The notifyTaskEvent method demonstrates a clear integration point with the src/channels module. By dynamically importing getChannelManager, the tasks module can send notifications to various communication channels (e.g., Telegram, Slack) based on the notifyChannel and notifyOn properties defined in the BackgroundTask. This decouples notification logic from task execution.

Developer Notes