返回 CodeWhale
background_host.rs
根目录 / crates / tui / src / commands / background_host.rs
1 use std::collections::HashMap;
2 use std::path::PathBuf;
3 use std::sync::atomic::Ordering;
4 use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError};
5
6 use codewhale_command_contract::facets::{
7 BackgroundCancel, BackgroundJob, BackgroundRequest, CommandBackgroundContext,
8 };
9 use codewhale_command_contract::handler::CommandCapabilities;
10 use codewhale_command_contract::outcome::{BackgroundAction, BackgroundCommandResult};
11 use codewhale_localization::{Locale, MessageId, tr};
12
13 use crate::commands::CommandResult;
14 use crate::tui::app::{App, AppAction, DispatchApplyFn};
15
16 struct Running {
17 id: u64,
18 cancel: BackgroundCancel,
19 }
20
21 #[derive(Default)]
22 struct State {
23 next_id: u64,
24 running: HashMap<&'static str, Running>,
25 ready: Vec<BackgroundCommandResult>,
26 }
27
28 #[derive(Clone, Default)]
29 struct BackgroundCommands {
30 state: Arc<Mutex<State>>,
31 }
32
33 impl BackgroundCommands {
34 fn lock(&self) -> MutexGuard<'_, State> {
35 self.state.lock().unwrap_or_else(PoisonError::into_inner)
36 }
37
38 fn finish(&self, command: &'static str, id: u64) -> bool {
39 let mut state = self.lock();
40 if state
41 .running
42 .get(command)
43 .is_some_and(|running| running.id == id)
44 {
45 state.running.remove(command);
46 true
47 } else {
48 false
49 }
50 }
51
52 fn cancel(&self, command: &'static str) -> bool {
53 let running = self.lock().running.remove(command);
54 match running {
55 Some(running) => {
56 running.cancel.store(true, Ordering::SeqCst);
57 true
58 }
59 None => false,
60 }
61 }
62
63 fn cancel_all(&self) -> Vec<&'static str> {
64 let mut cancelled: Vec<&'static str> = self
65 .lock()
66 .running
67 .drain()
68 .map(|(command, running)| {
69 running.cancel.store(true, Ordering::SeqCst);
70 command
71 })
72 .collect();
73 cancelled.sort_unstable();
74 cancelled
75 }
76
77 fn running(&self) -> Vec<&'static str> {
78 let mut running: Vec<&'static str> = self.lock().running.keys().copied().collect();
79 running.sort_unstable();
80 running
81 }
82
83 fn push_ready(&self, result: BackgroundCommandResult) {
84 self.lock().ready.push(result);
85 }
86
87 fn take_ready(&self) -> Vec<CommandResult> {
88 let ready = std::mem::take(&mut self.lock().ready);
89 ready.into_iter().map(host_result).collect()
90 }
91 }
92
93 fn shared() -> &'static BackgroundCommands {
94 static SHARED: OnceLock<BackgroundCommands> = OnceLock::new();
95 SHARED.get_or_init(BackgroundCommands::default)
96 }
97
98 fn host_result(result: BackgroundCommandResult) -> CommandResult {
99 CommandResult {
100 message: result.message,
101 action: result.action.map(|action| match action {
102 BackgroundAction::SendMessage(content) => AppAction::SendMessage(content),
103 }),
104 is_error: result.is_error,
105 }
106 }
107
108 pub(crate) fn take_ready() -> Vec<CommandResult> {
109 shared().take_ready()
110 }
111
112 pub(crate) fn running() -> Vec<&'static str> {
113 shared().running()
114 }
115
116 pub(crate) fn cancel_all() -> Vec<&'static str> {
117 shared().cancel_all()
118 }
119
120 pub(crate) fn line(locale: Locale, id: MessageId, command: &str) -> String {
121 tr(locale, id).replace("{command}", command)
122 }
123
124 pub(in crate::commands) struct BackgroundHost {
125 commands: BackgroundCommands,
126 completion: tokio::sync::mpsc::Sender<DispatchApplyFn>,
127 runtime: tokio::runtime::Handle,
128 locale: Locale,
129 workspace: PathBuf,
130 }
131
132 pub(in crate::commands) fn host(
133 app: &App,
134 capabilities: CommandCapabilities,
135 ) -> Option<BackgroundHost> {
136 if !capabilities.contains(CommandCapabilities::BACKGROUND) {
137 return None;
138 }
139 Some(BackgroundHost {
140 commands: shared().clone(),
141 completion: app.dispatch_completion_tx.clone()?,
142 runtime: tokio::runtime::Handle::try_current().ok()?,
143 locale: app.ui_locale,
144 workspace: app.workspace.clone(),
145 })
146 }
147
148 impl BackgroundHost {
149 fn line(&self, id: MessageId, command: &str) -> String {
150 line(self.locale, id, command)
151 }
152 }
153
154 impl CommandBackgroundContext for BackgroundHost {
155 fn start(
156 &mut self,
157 command: &'static str,
158 job: BackgroundJob,
159 request: BackgroundRequest,
160 ) -> Result<String, String> {
161 let mut state = self.commands.lock();
162 if state.running.contains_key(command) {
163 return Err(self.line(MessageId::CmdBackgroundAlreadyRunning, command));
164 }
165 state.next_id += 1;
166 let id = state.next_id;
167 let cancel = BackgroundCancel::default();
168 state.running.insert(
169 command,
170 Running {
171 id,
172 cancel: cancel.clone(),
173 },
174 );
175 drop(state);
176 let job_cancel = cancel.clone();
177 let task = self
178 .runtime
179 .spawn_blocking(move || job(request, job_cancel));
180 self.runtime.spawn(supervise(
181 Supervised {
182 commands: self.commands.clone(),
183 command,
184 id,
185 cancel,
186 },
187 task,
188 self.completion.clone(),
189 Delivery {
190 workspace: self.workspace.clone(),
191 failed: self.line(MessageId::CmdBackgroundFailed, command),
192 stale: self.line(MessageId::CmdBackgroundStale, command),
193 },
194 ));
195 Ok(self.line(MessageId::CmdBackgroundStarted, command))
196 }
197
198 fn cancel(&mut self, command: &'static str) -> Result<String, String> {
199 if self.commands.cancel(command) {
200 Ok(self.line(MessageId::CmdBackgroundCancelled, command))
201 } else {
202 Err(self.line(MessageId::CmdBackgroundNotRunning, command))
203 }
204 }
205 }
206
207 struct Delivery {
208 workspace: PathBuf,
209 failed: String,
210 stale: String,
211 }
212
213 struct Supervised {
214 commands: BackgroundCommands,
215 command: &'static str,
216 id: u64,
217 cancel: BackgroundCancel,
218 }
219
220 async fn supervise(
221 supervised: Supervised,
222 mut task: tokio::task::JoinHandle<BackgroundCommandResult>,
223 completion: tokio::sync::mpsc::Sender<DispatchApplyFn>,
224 delivery: Delivery,
225 ) {
226 let Supervised {
227 commands,
228 command,
229 id,
230 cancel,
231 } = supervised;
232 let Delivery {
233 workspace,
234 failed,
235 stale,
236 } = delivery;
237 let joined = tokio::select! {
238 joined = &mut task => Some(joined),
239 () = completion.closed() => None,
240 };
241 let current = commands.finish(command, id) && !cancel.load(Ordering::SeqCst);
242 let result = match joined {
243 None => {
244 cancel.store(true, Ordering::SeqCst);
245 return;
246 }
247 Some(Ok(result)) => result,
248 Some(Err(error)) if error.is_cancelled() => return,
249 Some(Err(_)) => BackgroundCommandResult::error(failed),
250 };
251 if !current {
252 return;
253 }
254 let apply: DispatchApplyFn = Box::new(move |app: &mut App, _, _| {
255 let result = if result.action.is_some() && app.workspace != workspace {
256 BackgroundCommandResult::message(stale)
257 } else {
258 result
259 };
260 commands.push_ready(result);
261 app.needs_redraw = true;
262 Ok(())
263 });
264 let _ = completion.send(apply).await;
265 }
266
267 #[cfg(test)]
268 mod tests {
269 use super::*;
270 use std::time::{Duration, Instant};
271
272 use codewhale_engine::core::engine::mock_engine_handle;
273 use codewhale_runtime::config::Config;
274
275 type Mailbox = tokio::sync::mpsc::Receiver<DispatchApplyFn>;
276
277 fn test_host(workspace: &std::path::Path) -> (BackgroundHost, Mailbox) {
278 let (completion, mailbox) = tokio::sync::mpsc::channel::<DispatchApplyFn>(2);
279 let host = BackgroundHost {
280 commands: BackgroundCommands::default(),
281 completion,
282 runtime: tokio::runtime::Handle::current(),
283 locale: Locale::En,
284 workspace: workspace.to_path_buf(),
285 };
286 (host, mailbox)
287 }
288
289 fn test_app(workspace: &std::path::Path) -> (App, Config) {
290 let config = Config::default();
291 let app = App::new(
292 crate::tui::test_support::test_tui_options(workspace),
293 &config,
294 );
295 (app, config)
296 }
297
298 fn held(_request: BackgroundRequest, cancel: BackgroundCancel) -> BackgroundCommandResult {
299 let deadline = Instant::now() + Duration::from_secs(10);
300 while !cancel.load(Ordering::SeqCst) && Instant::now() < deadline {
301 std::thread::sleep(Duration::from_millis(1));
302 }
303 BackgroundCommandResult::message("held job returned")
304 }
305
306 fn init_done(
307 _request: BackgroundRequest,
308 _cancel: BackgroundCancel,
309 ) -> BackgroundCommandResult {
310 BackgroundCommandResult::with_message_and_action(
311 "Creating AGENTS.md",
312 BackgroundAction::SendMessage("prompt".to_string()),
313 )
314 }
315
316 fn update_failed(
317 _request: BackgroundRequest,
318 _cancel: BackgroundCancel,
319 ) -> BackgroundCommandResult {
320 BackgroundCommandResult::error("updater failed")
321 }
322
323 fn running_flag(commands: &BackgroundCommands, command: &str) -> BackgroundCancel {
324 commands
325 .lock()
326 .running
327 .get(command)
328 .expect("running command")
329 .cancel
330 .clone()
331 }
332
333 async fn stopped(flag: &BackgroundCancel) -> bool {
334 for _ in 0..400 {
335 if flag.load(Ordering::SeqCst) && Arc::strong_count(flag) == 1 {
336 return true;
337 }
338 tokio::time::sleep(Duration::from_millis(5)).await;
339 }
340 false
341 }
342
343 async fn delivered(mailbox: &mut Mailbox) -> DispatchApplyFn {
344 tokio::time::timeout(Duration::from_secs(5), mailbox.recv())
345 .await
346 .expect("background completion timeout")
347 .expect("background completion")
348 }
349
350 fn line(id: MessageId, command: &str) -> String {
351 tr(Locale::En, id).replace("{command}", command)
352 }
353
354 #[tokio::test]
355 async fn a_finished_command_delivers_its_result_and_action_through_the_mailbox() {
356 let tmp = tempfile::tempdir().unwrap();
357 let (mut host, mut mailbox) = test_host(tmp.path());
358 let (mut app, config) = test_app(tmp.path());
359 app.workspace = tmp.path().to_path_buf();
360 let engine = mock_engine_handle();
361
362 let started = host.start("init", init_done, BackgroundRequest::default());
363 assert_eq!(started, Ok(line(MessageId::CmdBackgroundStarted, "init")));
364 assert!(
365 host.commands.take_ready().is_empty(),
366 "starting returns before any result exists"
367 );
368
369 let apply = delivered(&mut mailbox).await;
370 app.needs_redraw = false;
371 apply(&mut app, &engine.handle, &config).expect("apply completion");
372 assert!(app.needs_redraw);
373
374 let ready = host.commands.take_ready();
375 assert_eq!(ready.len(), 1);
376 assert_eq!(ready[0].message.as_deref(), Some("Creating AGENTS.md"));
377 assert!(
378 matches!(&ready[0].action, Some(AppAction::SendMessage(prompt)) if prompt == "prompt")
379 );
380 assert!(!ready[0].is_error);
381 assert!(
382 host.commands.take_ready().is_empty(),
383 "a result is applied once"
384 );
385
386 assert!(
387 host.start("init", held, BackgroundRequest::default())
388 .is_ok(),
389 "a finished command can be started again"
390 );
391 let flag = running_flag(&host.commands, "init");
392 host.commands.cancel_all();
393 assert!(stopped(&flag).await);
394 }
395
396 #[tokio::test]
397 async fn a_running_command_shows_a_notice_and_an_interrupt_cancels_it() {
398 let tmp = tempfile::tempdir().unwrap();
399 let (mut app, _config) = test_app(tmp.path());
400 let (completion, _mailbox) = tokio::sync::mpsc::channel::<DispatchApplyFn>(2);
401 app.dispatch_completion_tx = Some(completion);
402 let mut background = host(&app, CommandCapabilities::BACKGROUND).expect("background host");
403 assert!(
404 background
405 .start("update", held, BackgroundRequest::default())
406 .is_ok()
407 );
408 let flag = running_flag(&background.commands, "update");
409
410 let working = super::line(app.ui_locale, MessageId::CmdBackgroundWorking, "update");
411 let mut shown = Vec::new();
412 crate::tui::ui::sync_background_command_notices(&mut app, &mut shown);
413 assert_eq!(shown, ["update"]);
414 assert!(app.status_toasts.iter().any(|toast| toast.text == working));
415
416 assert!(crate::tui::ui::cancel_background_commands(&mut app));
417 assert_eq!(
418 app.visible_notice_text(),
419 Some(super::line(
420 app.ui_locale,
421 MessageId::CmdBackgroundCancelled,
422 "update"
423 ))
424 );
425 assert!(stopped(&flag).await, "the cancelled job returns");
426 crate::tui::ui::sync_background_command_notices(&mut app, &mut shown);
427 assert!(shown.is_empty());
428 assert!(!app.status_toasts.iter().any(|toast| toast.text == working));
429 assert!(!crate::tui::ui::cancel_background_commands(&mut app));
430 }
431
432 #[tokio::test]
433 async fn an_error_result_is_delivered_as_an_error() {
434 let tmp = tempfile::tempdir().unwrap();
435 let (mut host, mut mailbox) = test_host(tmp.path());
436 let (mut app, config) = test_app(tmp.path());
437 let engine = mock_engine_handle();
438
439 host.start("update", update_failed, BackgroundRequest::default())
440 .expect("start");
441 let apply = delivered(&mut mailbox).await;
442 apply(&mut app, &engine.handle, &config).expect("apply completion");
443
444 let ready = host.commands.take_ready();
445 assert_eq!(ready.len(), 1);
446 assert!(ready[0].is_error);
447 assert_eq!(ready[0].message.as_deref(), Some("Error: updater failed"));
448 assert!(ready[0].action.is_none());
449 }
450
451 #[tokio::test]
452 async fn a_second_run_of_the_same_command_is_refused_while_the_first_is_running() {
453 let tmp = tempfile::tempdir().unwrap();
454 let (mut host, mut mailbox) = test_host(tmp.path());
455
456 assert!(
457 host.start("update", held, BackgroundRequest::default())
458 .is_ok()
459 );
460 let first = running_flag(&host.commands, "update");
461 assert_eq!(
462 host.start("update", init_done, BackgroundRequest::default()),
463 Err(line(MessageId::CmdBackgroundAlreadyRunning, "update"))
464 );
465 assert!(
466 Arc::ptr_eq(&first, &running_flag(&host.commands, "update")),
467 "the first run is untouched"
468 );
469 assert!(!first.load(Ordering::SeqCst));
470
471 assert!(
472 host.start("init", held, BackgroundRequest::default())
473 .is_ok(),
474 "a different command is independent"
475 );
476 let other = running_flag(&host.commands, "init");
477 tokio::time::sleep(Duration::from_millis(20)).await;
478 assert!(mailbox.try_recv().is_err(), "nothing has finished");
479 host.commands.cancel_all();
480 assert!(stopped(&first).await);
481 assert!(stopped(&other).await);
482 }
483
484 #[tokio::test]
485 async fn cancelling_stops_the_job_and_delivers_nothing() {
486 let tmp = tempfile::tempdir().unwrap();
487 let (mut host, mut mailbox) = test_host(tmp.path());
488
489 assert_eq!(
490 host.cancel("update"),
491 Err(line(MessageId::CmdBackgroundNotRunning, "update"))
492 );
493 assert!(
494 host.start("update", held, BackgroundRequest::default())
495 .is_ok()
496 );
497 let flag = running_flag(&host.commands, "update");
498 assert_eq!(
499 host.cancel("update"),
500 Ok(line(MessageId::CmdBackgroundCancelled, "update"))
501 );
502 assert!(stopped(&flag).await, "the cancelled job returns");
503 tokio::time::sleep(Duration::from_millis(20)).await;
504 assert!(
505 mailbox.try_recv().is_err(),
506 "a cancelled run reports nothing"
507 );
508 assert!(host.commands.take_ready().is_empty());
509 assert_eq!(
510 host.cancel("update"),
511 Err(line(MessageId::CmdBackgroundNotRunning, "update"))
512 );
513
514 assert!(
515 host.start("update", held, BackgroundRequest::default())
516 .is_ok(),
517 "a cancelled command can be started again"
518 );
519 let again = running_flag(&host.commands, "update");
520 host.commands.cancel_all();
521 assert!(stopped(&again).await);
522 }
523
524 #[tokio::test]
525 async fn quitting_closes_the_mailbox_and_cancels_running_work() {
526 let tmp = tempfile::tempdir().unwrap();
527 let (mut host, mailbox) = test_host(tmp.path());
528
529 assert!(
530 host.start("update", held, BackgroundRequest::default())
531 .is_ok()
532 );
533 let flag = running_flag(&host.commands, "update");
534 drop(mailbox);
535 assert!(
536 stopped(&flag).await,
537 "the job stops when the event loop is gone"
538 );
539 assert!(host.commands.lock().running.is_empty());
540 assert!(host.commands.take_ready().is_empty());
541 }
542
543 #[tokio::test]
544 async fn a_follow_up_action_is_dropped_when_the_workspace_changed() {
545 let tmp = tempfile::tempdir().unwrap();
546 let (mut host, mut mailbox) = test_host(tmp.path());
547 let (mut app, config) = test_app(tmp.path());
548 app.workspace = tmp.path().join("elsewhere");
549 let engine = mock_engine_handle();
550
551 host.start("init", init_done, BackgroundRequest::default())
552 .expect("start");
553 let apply = delivered(&mut mailbox).await;
554 apply(&mut app, &engine.handle, &config).expect("apply completion");
555
556 let ready = host.commands.take_ready();
557 assert_eq!(ready.len(), 1);
558 assert_eq!(
559 ready[0].message,
560 Some(line(MessageId::CmdBackgroundStale, "init"))
561 );
562 assert!(ready[0].action.is_none());
563 }
564
565 #[test]
566 fn the_facet_is_offered_only_to_commands_that_declare_it_with_a_live_mailbox() {
567 let tmp = tempfile::tempdir().unwrap();
568 let (mut app, _config) = test_app(tmp.path());
569 assert!(host(&app, CommandCapabilities::BACKGROUND).is_none());
570
571 let runtime = tokio::runtime::Builder::new_current_thread()
572 .build()
573 .unwrap();
574 let _guard = runtime.enter();
575 assert!(host(&app, CommandCapabilities::BACKGROUND).is_none());
576 let (completion, _mailbox) = tokio::sync::mpsc::channel::<DispatchApplyFn>(2);
577 app.dispatch_completion_tx = Some(completion);
578 assert!(host(&app, CommandCapabilities::WORKSPACE).is_none());
579 assert!(
580 host(
581 &app,
582 CommandCapabilities::BACKGROUND | CommandCapabilities::WORKSPACE
583 )
584 .is_some()
585 );
586 }
587 }
588
588 lines RUST