stuckbar 0.1.7

A straightforward CLI tool & MCP server for restarting Windows Explorer when the taskbar gets stuck
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
//! # stuckbar
//!
//! A CLI tool for restarting Windows Explorer when the taskbar gets stuck.
//!
//! This crate provides functionality to kill, start, and restart the Windows Explorer
//! process, which is useful when the Windows taskbar becomes unresponsive.
//!
//! ## Features
//!
//! - `mcp` - Enable Model Context Protocol (MCP) server support for AI agent integration
//!
//! ## Platform Support
//!
//! This tool is Windows-only. Running on other platforms will result in an error.

use colored::Colorize;
use std::process::Command;

/// Delay in milliseconds before starting explorer.exe after termination
pub const RESTART_DELAY_MS: u64 = 500;

/// Result of a process operation
#[derive(Debug, PartialEq, Clone)]
pub struct ProcessResult {
    pub success: bool,
    pub message: String,
}

impl ProcessResult {
    pub fn success(message: impl Into<String>) -> Self {
        Self {
            success: true,
            message: message.into(),
        }
    }

    pub fn failure(message: impl Into<String>) -> Self {
        Self {
            success: false,
            message: message.into(),
        }
    }
}

/// Trait for abstracting process operations (enables testing)
pub trait ProcessRunner {
    fn kill_process(&self, process_name: &str) -> ProcessResult;
    fn start_process(&self, process_name: &str) -> ProcessResult;
    fn sleep_ms(&self, ms: u64);
}

/// Real implementation that interacts with the system
pub struct SystemProcessRunner;

impl ProcessRunner for SystemProcessRunner {
    fn kill_process(&self, process_name: &str) -> ProcessResult {
        let result = Command::new("taskkill")
            .args(["/F", "/IM", process_name])
            .output();

        match result {
            Ok(output) => {
                if output.status.success() {
                    ProcessResult::success(format!("Successfully terminated {}", process_name))
                } else {
                    let stderr = String::from_utf8_lossy(&output.stderr);
                    ProcessResult::failure(format!(
                        "Failed to terminate {}: {}",
                        process_name, stderr
                    ))
                }
            }
            Err(e) => ProcessResult::failure(format!("Error executing taskkill: {}", e)),
        }
    }

    fn start_process(&self, process_name: &str) -> ProcessResult {
        let result = Command::new(process_name).spawn();

        match result {
            Ok(_) => ProcessResult::success(format!("Successfully started {}", process_name)),
            Err(e) => ProcessResult::failure(format!("Error starting {}: {}", process_name, e)),
        }
    }

    fn sleep_ms(&self, ms: u64) {
        std::thread::sleep(std::time::Duration::from_millis(ms));
    }
}

/// Explorer manager that handles explorer.exe operations
pub struct ExplorerManager<R: ProcessRunner> {
    pub runner: R,
    pub restart_delay_ms: u64,
}

impl<R: ProcessRunner> ExplorerManager<R> {
    pub fn new(runner: R) -> Self {
        Self {
            runner,
            restart_delay_ms: RESTART_DELAY_MS,
        }
    }

    pub fn with_restart_delay(mut self, delay_ms: u64) -> Self {
        self.restart_delay_ms = delay_ms;
        self
    }

    /// Kill explorer.exe process
    pub fn kill(&self) -> bool {
        println!("{}", "Terminating explorer.exe...".yellow());
        let result = self.runner.kill_process("explorer.exe");

        if result.success {
            println!("{}", result.message.green());
        } else {
            eprintln!("{}", result.message.red());
        }

        result.success
    }

    /// Start explorer.exe process
    pub fn start(&self) -> bool {
        println!("{}", "Starting explorer.exe...".yellow());
        let result = self.runner.start_process("explorer.exe");

        if result.success {
            println!("{}", result.message.green());
        } else {
            eprintln!("{}", result.message.red());
        }

        result.success
    }

    /// Restart explorer.exe (kill then start)
    pub fn restart(&self) -> bool {
        println!("{}", "Restarting explorer.exe...".cyan().bold());

        if !self.kill() {
            return false;
        }

        // Small delay to ensure explorer is fully terminated
        self.runner.sleep_ms(self.restart_delay_ms);

        if !self.start() {
            return false;
        }

        println!("{}", "Explorer.exe restarted successfully!".green().bold());
        true
    }

    /// Kill explorer.exe without printing (for MCP/programmatic use)
    pub fn kill_silent(&self) -> ProcessResult {
        self.runner.kill_process("explorer.exe")
    }

    /// Start explorer.exe without printing (for MCP/programmatic use)
    pub fn start_silent(&self) -> ProcessResult {
        self.runner.start_process("explorer.exe")
    }

    /// Restart explorer.exe without printing (for MCP/programmatic use)
    pub fn restart_silent(&self) -> ProcessResult {
        let kill_result = self.runner.kill_process("explorer.exe");
        if !kill_result.success {
            return kill_result;
        }

        self.runner.sleep_ms(self.restart_delay_ms);

        let start_result = self.runner.start_process("explorer.exe");
        if !start_result.success {
            return start_result;
        }

        ProcessResult::success("Explorer.exe restarted successfully")
    }
}

/// Check if the current platform is Windows
pub fn is_windows() -> bool {
    cfg!(target_os = "windows")
}

/// Check platform and return an error message if not Windows
pub fn check_platform() -> Result<(), String> {
    if !is_windows() {
        Err(format!(
            "stuckbar is a Windows-only tool.\n\
            Current platform '{}' is not supported.\n\
            This tool restarts explorer.exe which only exists on Windows.",
            std::env::consts::OS
        ))
    } else {
        Ok(())
    }
}

#[cfg(feature = "mcp")]
pub mod mcp;

#[cfg(test)]
mod tests {
    use super::*;
    use std::cell::RefCell;

    /// Mock process runner for testing
    pub struct MockProcessRunner {
        kill_results: RefCell<Vec<ProcessResult>>,
        start_results: RefCell<Vec<ProcessResult>>,
        sleep_calls: RefCell<Vec<u64>>,
    }

    impl MockProcessRunner {
        pub fn new() -> Self {
            Self {
                kill_results: RefCell::new(Vec::new()),
                start_results: RefCell::new(Vec::new()),
                sleep_calls: RefCell::new(Vec::new()),
            }
        }

        pub fn with_kill_result(self, result: ProcessResult) -> Self {
            self.kill_results.borrow_mut().push(result);
            self
        }

        pub fn with_start_result(self, result: ProcessResult) -> Self {
            self.start_results.borrow_mut().push(result);
            self
        }

        pub fn get_sleep_calls(&self) -> Vec<u64> {
            self.sleep_calls.borrow().clone()
        }
    }

    impl Default for MockProcessRunner {
        fn default() -> Self {
            Self::new()
        }
    }

    impl ProcessRunner for MockProcessRunner {
        fn kill_process(&self, _process_name: &str) -> ProcessResult {
            self.kill_results
                .borrow_mut()
                .pop()
                .unwrap_or_else(|| ProcessResult::failure("No mock result configured"))
        }

        fn start_process(&self, _process_name: &str) -> ProcessResult {
            self.start_results
                .borrow_mut()
                .pop()
                .unwrap_or_else(|| ProcessResult::failure("No mock result configured"))
        }

        fn sleep_ms(&self, ms: u64) {
            self.sleep_calls.borrow_mut().push(ms);
        }
    }

    // ProcessResult tests
    #[test]
    fn test_process_result_success() {
        let result = ProcessResult::success("test message");
        assert!(result.success);
        assert_eq!(result.message, "test message");
    }

    #[test]
    fn test_process_result_failure() {
        let result = ProcessResult::failure("error message");
        assert!(!result.success);
        assert_eq!(result.message, "error message");
    }

    #[test]
    fn test_process_result_clone() {
        let result = ProcessResult::success("test");
        let cloned = result.clone();
        assert_eq!(result, cloned);
    }

    // ExplorerManager::kill tests
    #[test]
    fn test_kill_success() {
        let runner = MockProcessRunner::new().with_kill_result(ProcessResult::success("Killed"));
        let manager = ExplorerManager::new(runner);

        assert!(manager.kill());
    }

    #[test]
    fn test_kill_failure() {
        let runner =
            MockProcessRunner::new().with_kill_result(ProcessResult::failure("Failed to kill"));
        let manager = ExplorerManager::new(runner);

        assert!(!manager.kill());
    }

    // ExplorerManager::start tests
    #[test]
    fn test_start_success() {
        let runner = MockProcessRunner::new().with_start_result(ProcessResult::success("Started"));
        let manager = ExplorerManager::new(runner);

        assert!(manager.start());
    }

    #[test]
    fn test_start_failure() {
        let runner =
            MockProcessRunner::new().with_start_result(ProcessResult::failure("Failed to start"));
        let manager = ExplorerManager::new(runner);

        assert!(!manager.start());
    }

    // ExplorerManager::restart tests
    #[test]
    fn test_restart_success() {
        let runner = MockProcessRunner::new()
            .with_kill_result(ProcessResult::success("Killed"))
            .with_start_result(ProcessResult::success("Started"));
        let manager = ExplorerManager::new(runner).with_restart_delay(100);

        assert!(manager.restart());
    }

    #[test]
    fn test_restart_kill_fails() {
        let runner =
            MockProcessRunner::new().with_kill_result(ProcessResult::failure("Failed to kill"));
        let manager = ExplorerManager::new(runner);

        assert!(!manager.restart());
    }

    #[test]
    fn test_restart_start_fails() {
        let runner = MockProcessRunner::new()
            .with_kill_result(ProcessResult::success("Killed"))
            .with_start_result(ProcessResult::failure("Failed to start"));
        let manager = ExplorerManager::new(runner);

        assert!(!manager.restart());
    }

    #[test]
    fn test_restart_sleeps_between_operations() {
        let runner = MockProcessRunner::new()
            .with_kill_result(ProcessResult::success("Killed"))
            .with_start_result(ProcessResult::success("Started"));
        let manager = ExplorerManager::new(runner).with_restart_delay(250);

        manager.restart();

        let sleep_calls = &manager.runner.get_sleep_calls();
        assert_eq!(sleep_calls.len(), 1);
        assert_eq!(sleep_calls[0], 250);
    }

    #[test]
    fn test_restart_uses_default_delay() {
        let runner = MockProcessRunner::new()
            .with_kill_result(ProcessResult::success("Killed"))
            .with_start_result(ProcessResult::success("Started"));
        let manager = ExplorerManager::new(runner);

        assert_eq!(manager.restart_delay_ms, RESTART_DELAY_MS);
    }

    // ExplorerManager builder pattern test
    #[test]
    fn test_explorer_manager_with_restart_delay() {
        let runner = MockProcessRunner::new();
        let manager = ExplorerManager::new(runner).with_restart_delay(1000);
        assert_eq!(manager.restart_delay_ms, 1000);
    }

    // Silent method tests
    #[test]
    fn test_kill_silent_success() {
        let runner = MockProcessRunner::new().with_kill_result(ProcessResult::success("Killed"));
        let manager = ExplorerManager::new(runner);

        let result = manager.kill_silent();
        assert!(result.success);
    }

    #[test]
    fn test_kill_silent_failure() {
        let runner = MockProcessRunner::new().with_kill_result(ProcessResult::failure("Error"));
        let manager = ExplorerManager::new(runner);

        let result = manager.kill_silent();
        assert!(!result.success);
    }

    #[test]
    fn test_start_silent_success() {
        let runner = MockProcessRunner::new().with_start_result(ProcessResult::success("Started"));
        let manager = ExplorerManager::new(runner);

        let result = manager.start_silent();
        assert!(result.success);
    }

    #[test]
    fn test_start_silent_failure() {
        let runner = MockProcessRunner::new().with_start_result(ProcessResult::failure("Error"));
        let manager = ExplorerManager::new(runner);

        let result = manager.start_silent();
        assert!(!result.success);
    }

    #[test]
    fn test_restart_silent_success() {
        let runner = MockProcessRunner::new()
            .with_kill_result(ProcessResult::success("Killed"))
            .with_start_result(ProcessResult::success("Started"));
        let manager = ExplorerManager::new(runner);

        let result = manager.restart_silent();
        assert!(result.success);
        assert_eq!(result.message, "Explorer.exe restarted successfully");
    }

    #[test]
    fn test_restart_silent_kill_fails() {
        let runner =
            MockProcessRunner::new().with_kill_result(ProcessResult::failure("Kill failed"));
        let manager = ExplorerManager::new(runner);

        let result = manager.restart_silent();
        assert!(!result.success);
        assert_eq!(result.message, "Kill failed");
    }

    #[test]
    fn test_restart_silent_start_fails() {
        let runner = MockProcessRunner::new()
            .with_kill_result(ProcessResult::success("Killed"))
            .with_start_result(ProcessResult::failure("Start failed"));
        let manager = ExplorerManager::new(runner);

        let result = manager.restart_silent();
        assert!(!result.success);
        assert_eq!(result.message, "Start failed");
    }

    // Platform check tests
    #[test]
    fn test_is_windows() {
        // This test verifies the function works, actual result depends on platform
        let result = is_windows();
        #[cfg(target_os = "windows")]
        assert!(result);
        #[cfg(not(target_os = "windows"))]
        assert!(!result);
    }

    #[test]
    fn test_check_platform() {
        let result = check_platform();
        #[cfg(target_os = "windows")]
        assert!(result.is_ok());
        #[cfg(not(target_os = "windows"))]
        {
            assert!(result.is_err());
            let err = result.unwrap_err();
            assert!(err.contains("Windows-only"));
            assert!(err.contains(std::env::consts::OS));
        }
    }
}