@@ -32,6 +32,17 @@ use model::{
3232 progress_event_record, progress_wait_reason, push_task_event, task_dir, terminal_event_record,
3333} ;
3434
35+ /// Own an adopted task rather than detaching it when its wrapper is aborted.
36+ /// Construct before the first await, including before spawning the wrapper, so
37+ /// cancellation during registration or before its first poll is also safe.
38+ struct AbortAdoptedTask < T > ( JoinHandle < T > ) ;
39+
40+ impl < T > Drop for AbortAdoptedTask < T > {
41+ fn drop ( & mut self ) {
42+ self . 0 . abort ( ) ;
43+ }
44+ }
45+
3546/// Manages background task execution
3647pub struct BackgroundTaskManager {
3748 tasks : Arc < RwLock < HashMap < String , RunningTask > > > ,
@@ -648,6 +659,7 @@ impl BackgroundTaskManager {
648659 wake : bool ,
649660 handle : JoinHandle < Result < jcode_tool_types:: ToolOutput > > ,
650661 ) -> BackgroundTaskInfo {
662+ let mut handle = AbortAdoptedTask ( handle) ;
651663 // Reserve before the foreground caller can release its turn/tool guard.
652664 let runtime_activity = crate :: runtime_activity:: global ( ) . enter ( ) . await ;
653665 let ( notify, wake) = normalize_delivery ( notify, wake) ;
@@ -707,7 +719,7 @@ impl BackgroundTaskManager {
707719
708720 let wrapper_handle = tokio:: spawn ( async move {
709721 let _runtime_activity = runtime_activity;
710- let tool_result = handle. await ;
722+ let tool_result = ( & mut handle. 0 ) . await ;
711723 let duration_secs = started_at. elapsed ( ) . as_secs_f64 ( ) ;
712724
713725 let ( status, exit_code, error, output_text) = match tool_result {
0 commit comments