ricecoder-execution 0.1.71

Execution engine for workflows and agent tasks
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//! Progress tracking and reporting for execution plans
//!
//! Tracks execution progress and provides callbacks for UI updates.
//! Supports reporting:
//! - Current step and total steps
//! - Overall progress percentage
//! - Estimated time remaining
//! - Progress callbacks for real-time UI updates

use crate::models::ExecutionPlan;
use serde::{Deserialize, Serialize};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use tracing::{debug, info};

/// Progress update event
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProgressUpdate {
    /// Current step index (0-based)
    pub current_step: usize,
    /// Total number of steps
    pub total_steps: usize,
    /// Overall progress percentage (0-100)
    pub progress_percentage: f32,
    /// Estimated time remaining
    pub estimated_time_remaining: Duration,
    /// Timestamp of this update
    pub timestamp: chrono::DateTime<chrono::Utc>,
}

/// Callback function for progress updates
pub type ProgressCallback = Box<dyn Fn(ProgressUpdate) + Send + Sync>;

/// Tracks execution progress and provides real-time updates
///
/// Maintains:
/// - Current step index
/// - Completed steps count
/// - Execution start time
/// - Step durations for time estimation
/// - Progress callbacks for UI updates
pub struct ProgressTracker {
    /// Total number of steps in the plan
    total_steps: usize,
    /// Current step index (0-based)
    current_step: usize,
    /// Number of completed steps
    completed_steps: usize,
    /// Execution start time
    start_time: Instant,
    /// Step durations for time estimation
    step_durations: Vec<Duration>,
    /// Progress callbacks
    callbacks: Arc<Mutex<Vec<ProgressCallback>>>,
}

impl ProgressTracker {
    /// Create a new progress tracker for a plan
    ///
    /// # Arguments
    /// * `plan` - The execution plan to track
    ///
    /// # Returns
    /// A new ProgressTracker initialized for the plan
    pub fn new(plan: &ExecutionPlan) -> Self {
        let total_steps = plan.steps.len();

        info!(total_steps = total_steps, "Creating progress tracker");

        Self {
            total_steps,
            current_step: 0,
            completed_steps: 0,
            start_time: Instant::now(),
            step_durations: Vec::new(),
            callbacks: Arc::new(Mutex::new(Vec::new())),
        }
    }

    /// Register a progress callback
    ///
    /// Callbacks are called whenever progress is updated.
    ///
    /// # Arguments
    /// * `callback` - Function to call on progress updates
    pub fn on_progress<F>(&self, callback: F)
    where
        F: Fn(ProgressUpdate) + Send + Sync + 'static,
    {
        let mut callbacks = self.callbacks.lock().unwrap();
        callbacks.push(Box::new(callback));

        debug!(
            callback_count = callbacks.len(),
            "Progress callback registered"
        );
    }

    /// Update progress to the next step
    ///
    /// Increments the current step and records the duration of the previous step.
    ///
    /// # Arguments
    /// * `step_duration` - Duration of the completed step
    pub fn step_completed(&mut self, step_duration: Duration) {
        self.step_durations.push(step_duration);
        self.completed_steps += 1;
        self.current_step += 1;

        debug!(
            current_step = self.current_step,
            completed_steps = self.completed_steps,
            step_duration_ms = step_duration.as_millis(),
            "Step completed"
        );

        self.notify_progress();
    }

    /// Skip a step
    ///
    /// Marks a step as skipped without recording a duration.
    pub fn step_skipped(&mut self) {
        self.step_durations.push(Duration::from_secs(0));
        self.current_step += 1;

        debug!(current_step = self.current_step, "Step skipped");

        self.notify_progress();
    }

    /// Get the current progress update
    ///
    /// # Returns
    /// A ProgressUpdate containing current progress information
    pub fn get_progress(&self) -> ProgressUpdate {
        let progress_percentage = if self.total_steps > 0 {
            (self.completed_steps as f32 / self.total_steps as f32) * 100.0
        } else {
            0.0
        };

        let estimated_time_remaining = self.estimated_time_remaining();

        ProgressUpdate {
            current_step: self.current_step,
            total_steps: self.total_steps,
            progress_percentage,
            estimated_time_remaining,
            timestamp: chrono::Utc::now(),
        }
    }

    /// Get the current step index (0-based)
    pub fn current_step(&self) -> usize {
        self.current_step
    }

    /// Get the total number of steps
    pub fn total_steps(&self) -> usize {
        self.total_steps
    }

    /// Get the number of completed steps
    pub fn completed_steps(&self) -> usize {
        self.completed_steps
    }

    /// Get the overall progress percentage (0-100)
    pub fn progress_percentage(&self) -> f32 {
        if self.total_steps > 0 {
            (self.completed_steps as f32 / self.total_steps as f32) * 100.0
        } else {
            0.0
        }
    }

    /// Get the estimated time remaining
    pub fn estimated_time_remaining(&self) -> Duration {
        if self.step_durations.is_empty() || self.completed_steps == 0 {
            // No data yet, estimate based on total steps
            return Duration::from_secs(0);
        }

        // Calculate average step duration
        let total_duration: Duration = self.step_durations.iter().sum();
        let average_duration = total_duration / self.step_durations.len() as u32;

        // Estimate remaining time
        let remaining_steps = self.total_steps.saturating_sub(self.completed_steps);
        average_duration * remaining_steps as u32
    }

    /// Get the total elapsed time
    pub fn elapsed_time(&self) -> Duration {
        self.start_time.elapsed()
    }

    /// Get the average step duration
    pub fn average_step_duration(&self) -> Duration {
        if self.step_durations.is_empty() {
            return Duration::from_secs(0);
        }

        let total_duration: Duration = self.step_durations.iter().sum();
        total_duration / self.step_durations.len() as u32
    }

    /// Notify all registered callbacks of progress update
    fn notify_progress(&self) {
        let progress = self.get_progress();

        let callbacks = self.callbacks.lock().unwrap();
        for callback in callbacks.iter() {
            callback(progress.clone());
        }
    }

    /// Reset the progress tracker
    ///
    /// Clears all progress data and resets to initial state.
    pub fn reset(&mut self) {
        self.current_step = 0;
        self.completed_steps = 0;
        self.start_time = Instant::now();
        self.step_durations.clear();

        debug!("Progress tracker reset");
    }
}

impl Default for ProgressTracker {
    fn default() -> Self {
        Self {
            total_steps: 0,
            current_step: 0,
            completed_steps: 0,
            start_time: Instant::now(),
            step_durations: Vec::new(),
            callbacks: Arc::new(Mutex::new(Vec::new())),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::models::{ExecutionPlan, ExecutionStep, RiskScore, StepAction, StepStatus};
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Arc as StdArc;

    fn create_test_plan(step_count: usize) -> ExecutionPlan {
        let steps = (0..step_count)
            .map(|i| ExecutionStep {
                id: format!("step-{}", i),
                description: format!("Step {}", i),
                action: StepAction::RunCommand {
                    command: "echo".to_string(),
                    args: vec![format!("step {}", i)],
                },
                risk_score: RiskScore::default(),
                dependencies: Vec::new(),
                rollback_action: None,
                status: StepStatus::Pending,
            })
            .collect();

        ExecutionPlan::new("Test Plan".to_string(), steps)
    }

    #[test]
    fn test_create_tracker() {
        let plan = create_test_plan(5);
        let tracker = ProgressTracker::new(&plan);

        assert_eq!(tracker.total_steps(), 5);
        assert_eq!(tracker.current_step(), 0);
        assert_eq!(tracker.completed_steps(), 0);
        assert_eq!(tracker.progress_percentage(), 0.0);
    }

    #[test]
    fn test_step_completed() {
        let plan = create_test_plan(5);
        let mut tracker = ProgressTracker::new(&plan);

        tracker.step_completed(Duration::from_secs(1));

        assert_eq!(tracker.completed_steps(), 1);
        assert_eq!(tracker.current_step(), 1);
        assert_eq!(tracker.progress_percentage(), 20.0);
    }

    #[test]
    fn test_multiple_steps_completed() {
        let plan = create_test_plan(5);
        let mut tracker = ProgressTracker::new(&plan);

        tracker.step_completed(Duration::from_secs(1));
        tracker.step_completed(Duration::from_secs(2));
        tracker.step_completed(Duration::from_secs(1));

        assert_eq!(tracker.completed_steps(), 3);
        assert!((tracker.progress_percentage() - 60.0).abs() < 0.01);
    }

    #[test]
    fn test_step_skipped() {
        let plan = create_test_plan(5);
        let mut tracker = ProgressTracker::new(&plan);

        tracker.step_completed(Duration::from_secs(1));
        tracker.step_skipped();

        assert_eq!(tracker.completed_steps(), 1);
        assert_eq!(tracker.current_step(), 2);
    }

    #[test]
    fn test_progress_percentage() {
        let plan = create_test_plan(10);
        let mut tracker = ProgressTracker::new(&plan);

        for _ in 0..5 {
            tracker.step_completed(Duration::from_secs(1));
        }

        assert_eq!(tracker.progress_percentage(), 50.0);
    }

    #[test]
    fn test_estimated_time_remaining() {
        let plan = create_test_plan(10);
        let mut tracker = ProgressTracker::new(&plan);

        // Complete 2 steps with 1 second each
        tracker.step_completed(Duration::from_secs(1));
        tracker.step_completed(Duration::from_secs(1));

        // Average is 1 second per step
        // 8 remaining steps should estimate to ~8 seconds
        let estimated = tracker.estimated_time_remaining();
        assert!(estimated.as_secs() >= 7 && estimated.as_secs() <= 9);
    }

    #[test]
    fn test_average_step_duration() {
        let plan = create_test_plan(5);
        let mut tracker = ProgressTracker::new(&plan);

        tracker.step_completed(Duration::from_secs(2));
        tracker.step_completed(Duration::from_secs(4));

        let average = tracker.average_step_duration();
        assert_eq!(average, Duration::from_secs(3));
    }

    #[test]
    fn test_elapsed_time() {
        let plan = create_test_plan(5);
        let tracker = ProgressTracker::new(&plan);

        let elapsed = tracker.elapsed_time();
        // Elapsed time should be recorded (even if very small)
        let _ = elapsed;
    }

    #[test]
    fn test_progress_callback() {
        let plan = create_test_plan(5);
        let mut tracker = ProgressTracker::new(&plan);

        let callback_count = StdArc::new(AtomicUsize::new(0));
        let callback_count_clone = callback_count.clone();

        tracker.on_progress(move |_progress| {
            callback_count_clone.fetch_add(1, Ordering::SeqCst);
        });

        tracker.step_completed(Duration::from_secs(1));
        tracker.step_completed(Duration::from_secs(1));

        assert_eq!(callback_count.load(Ordering::SeqCst), 2);
    }

    #[test]
    fn test_get_progress() {
        let plan = create_test_plan(5);
        let mut tracker = ProgressTracker::new(&plan);

        tracker.step_completed(Duration::from_secs(1));

        let progress = tracker.get_progress();
        assert_eq!(progress.current_step, 1);
        assert_eq!(progress.total_steps, 5);
        assert_eq!(progress.progress_percentage, 20.0);
    }

    #[test]
    fn test_reset() {
        let plan = create_test_plan(5);
        let mut tracker = ProgressTracker::new(&plan);

        tracker.step_completed(Duration::from_secs(1));
        tracker.step_completed(Duration::from_secs(1));

        tracker.reset();

        assert_eq!(tracker.completed_steps(), 0);
        assert_eq!(tracker.current_step(), 0);
        assert_eq!(tracker.progress_percentage(), 0.0);
    }

    #[test]
    fn test_empty_plan() {
        let plan = create_test_plan(0);
        let tracker = ProgressTracker::new(&plan);

        assert_eq!(tracker.total_steps(), 0);
        assert_eq!(tracker.progress_percentage(), 0.0);
    }

    #[test]
    fn test_progress_update_serialization() {
        let update = ProgressUpdate {
            current_step: 1,
            total_steps: 5,
            progress_percentage: 20.0,
            estimated_time_remaining: Duration::from_secs(4),
            timestamp: chrono::Utc::now(),
        };

        let json = serde_json::to_string(&update).unwrap();
        let deserialized: ProgressUpdate = serde_json::from_str(&json).unwrap();

        assert_eq!(deserialized.current_step, 1);
        assert_eq!(deserialized.total_steps, 5);
        assert_eq!(deserialized.progress_percentage, 20.0);
    }
}