Skip to main content

aft/commands/
bash_orchestrate.rs

1use std::path::Path;
2use std::time::{Duration, Instant};
3
4use serde::Deserialize;
5use serde_json::{json, Value};
6
7use crate::bash_background::registry::BgTaskSnapshot;
8use crate::bash_background::BgTaskStatus;
9use crate::context::AppContext;
10use crate::protocol::{RawRequest, Response};
11use crate::response_finalize::{DispatchOutcome, PendingResponse, PendingResponsePoll};
12
13const TEST_FOREGROUND_WAIT_ENV: &str = "AFT_TEST_FOREGROUND_WAIT_MS";
14const DEFAULT_FOREGROUND_WAIT_TIMEOUT_MS: u64 = 30 * 60 * 1000;
15
16#[derive(Debug, Default, Deserialize)]
17#[serde(default)]
18struct BashOrchestrateParams {
19    foreground_orchestrate: bool,
20    block_to_completion: bool,
21    wait: bool,
22    background: bool,
23    pty: bool,
24    timeout: Option<u64>,
25}
26
27/// Port of `packages/aft-bridge/src/bash-format.ts` `formatForegroundResult` (lines 8-25).
28pub fn format_foreground_result(snapshot: &BgTaskSnapshot) -> String {
29    let mut rendered = snapshot.output_preview.clone();
30    if snapshot.output_truncated {
31        if let Some(output_path) = snapshot.output_path.as_deref() {
32            rendered.push_str(&format!(
33                "\n[output truncated; full output at {output_path}]"
34            ));
35        }
36    }
37    if snapshot.info.status == BgTaskStatus::TimedOut {
38        rendered.push_str("\n[command timed out]");
39    }
40    if let Some(exit) = snapshot.exit_code.filter(|exit| *exit != 0) {
41        rendered.push_str(&format!("\n[exit code: {exit}]"));
42    }
43    rendered
44}
45
46/// Port of `packages/aft-bridge/src/bash-format.ts` `formatSeconds` (lines 3-6).
47pub fn format_seconds(ms: u64) -> String {
48    let mut seconds = format!("{:.1}", ms as f64 / 1000.0);
49    if seconds.ends_with(".0") {
50        seconds.truncate(seconds.len() - 2);
51    }
52    format!("{seconds}s")
53}
54
55fn format_background_handoff_tail(task_id: &str) -> String {
56    format!(
57        "{task_id}. A completion reminder will be delivered automatically; use bash_status({{ taskId: \"{task_id}\" }}) to inspect output or bash_kill({{ taskId: \"{task_id}\" }}) to terminate."
58    )
59}
60
61/// Port of OpenCode `packages/opencode-plugin/src/tools/bash.ts` `formatPromotionMessage` (lines 603-614).
62pub fn format_promotion_message(
63    task_id: &str,
64    timeout: Option<u64>,
65    wait_window_ms: u64,
66) -> String {
67    let waited = timeout
68        .map(|timeout| timeout.min(wait_window_ms))
69        .unwrap_or(wait_window_ms);
70    format!(
71        "Foreground bash didn't finish within {} and was promoted to background: {}",
72        format_seconds(waited),
73        format_background_handoff_tail(task_id)
74    )
75}
76
77pub fn format_wait_detach_message(task_id: &str) -> String {
78    format!(
79        "Foreground bash is running in background as {}\nDetached because a user message arrived.",
80        format_background_handoff_tail(task_id)
81    )
82}
83
84/// Port of OpenCode `packages/opencode-plugin/src/tools/bash.ts` `formatBackgroundLaunch` (lines 593-601).
85pub fn format_background_launch(task_id: &str, pty: bool) -> String {
86    if pty {
87        return format!(
88            "PTY task started: {task_id}. Use bash_status({{ taskId: \"{task_id}\", outputMode: \"screen\" }}) to see the visible terminal, bash_write({{ taskId: \"{task_id}\", input: ... }}) to send keystrokes. A completion reminder fires automatically when the task exits."
89        );
90    }
91    format!(
92        "Background task started: {task_id}. A completion reminder will be delivered automatically; don't poll bash_status."
93    )
94}
95
96pub fn foreground_orchestrate_enabled(req: &RawRequest) -> bool {
97    parse_params(req)
98        .map(|params| params.foreground_orchestrate)
99        .unwrap_or(false)
100}
101
102pub fn build_bash_outcome(
103    req: &RawRequest,
104    ctx: &AppContext,
105    spawn_response: Response,
106) -> DispatchOutcome {
107    if !spawn_response.success {
108        return DispatchOutcome::Immediate(spawn_response);
109    }
110
111    let params = parse_params(req).unwrap_or_default();
112    let Some(task_id) = spawn_response
113        .data
114        .get("task_id")
115        .and_then(Value::as_str)
116        .map(str::to_owned)
117    else {
118        return DispatchOutcome::Immediate(spawn_response);
119    };
120    if spawn_response.data.get("status").and_then(Value::as_str) != Some("running") {
121        return DispatchOutcome::Immediate(spawn_response);
122    }
123
124    let mode = spawn_response
125        .data
126        .get("mode")
127        .and_then(Value::as_str)
128        .unwrap_or("pipes");
129    let is_pty = mode == "pty" || params.pty;
130    if is_pty || params.background {
131        return DispatchOutcome::Immediate(background_launch_response(&req.id, &task_id, is_pty));
132    }
133
134    let request_id = req.id.clone();
135    let session_id = req.session().to_string();
136    let attach_command = "bash".to_string();
137    let detach_on_user_message = params.wait;
138    ctx.bash_background()
139        .register_foreground_task(&session_id, &task_id);
140    if detach_on_user_message {
141        ctx.bash_background()
142            .begin_wait_mode_session(&session_id, &task_id);
143    }
144    let wait_window_ms = select_foreground_wait_window_ms(
145        ctx.config().foreground_wait_window_ms,
146        params.timeout,
147        params.wait,
148    );
149    let deadline = Instant::now() + Duration::from_millis(wait_window_ms);
150    let block_to_completion = params.block_to_completion || params.wait;
151    let timeout = params.timeout;
152    let storage_dir = crate::bash_background::storage_dir(ctx.config().storage_dir.as_deref());
153    let project_root = ctx.config().project_root.clone();
154    let task_id_for_poll = task_id.clone();
155    let request_id_for_poll = request_id.clone();
156    let session_id_for_poll = session_id.clone();
157    let session_id_for_cleanup = session_id.clone();
158
159    let mut poll: PendingResponsePoll = Box::new(move |ctx| {
160        // Foreground polls only need task state. Terminal snapshots still
161        // return cached output.
162        let response = if let Some(snapshot) = poll_bash_status(
163            ctx,
164            &task_id_for_poll,
165            &session_id_for_poll,
166            project_root.as_deref(),
167            &storage_dir,
168            0,
169        ) {
170            if snapshot.info.status.is_terminal() {
171                Some(foreground_result_response(&request_id_for_poll, snapshot))
172            } else if detach_on_user_message
173                && ctx
174                    .bash_background()
175                    .take_wait_mode_detach(&session_id_for_poll)
176            {
177                Some(detach_wait_mode_bash(
178                    ctx,
179                    &task_id_for_poll,
180                    &session_id_for_poll,
181                    &request_id_for_poll,
182                ))
183            } else {
184                match decide_bash_step(
185                    snapshot,
186                    deadline,
187                    block_to_completion,
188                    Instant::now(),
189                    &request_id_for_poll,
190                ) {
191                    BashStep::Done(response) => Some(response),
192                    BashStep::Promote => Some(promote_bash(
193                        ctx,
194                        &task_id_for_poll,
195                        &session_id_for_poll,
196                        timeout,
197                        wait_window_ms,
198                        &request_id_for_poll,
199                    )),
200                    BashStep::Wait => None,
201                }
202            }
203        } else {
204            Some(task_not_found_response(
205                &request_id_for_poll,
206                &task_id_for_poll,
207            ))
208        };
209
210        if response.is_some() {
211            if detach_on_user_message {
212                ctx.bash_background()
213                    .end_wait_mode_session(&session_id_for_cleanup, &task_id_for_poll);
214            } else {
215                ctx.bash_background()
216                    .unregister_foreground_task(&session_id_for_cleanup, &task_id_for_poll);
217            }
218        }
219        response
220    });
221
222    if let Some(response) = poll(ctx) {
223        return DispatchOutcome::Immediate(response);
224    }
225
226    DispatchOutcome::Deferred(PendingResponse {
227        request_id,
228        session_id,
229        attach_command,
230        poll,
231        cancellation: None,
232        on_shutdown: None,
233    })
234}
235
236pub(crate) fn poll_bash_status(
237    ctx: &AppContext,
238    task_id: &str,
239    session_id: &str,
240    project_root: Option<&Path>,
241    storage_dir: &Path,
242    preview_bytes: usize,
243) -> Option<BgTaskSnapshot> {
244    ctx.bash_background().status(
245        task_id,
246        session_id,
247        project_root,
248        Some(storage_dir),
249        preview_bytes,
250    )
251}
252
253pub(crate) enum BashStep {
254    Done(Response),
255    Promote,
256    Wait,
257}
258
259pub(crate) fn task_not_found_response(request_id: &str, task_id: &str) -> Response {
260    Response::error(
261        request_id,
262        "task_not_found",
263        crate::commands::bash_status::format_unknown_task_message(task_id),
264    )
265}
266
267pub(crate) fn decide_bash_step(
268    snapshot: BgTaskSnapshot,
269    deadline: Instant,
270    block_to_completion: bool,
271    now: Instant,
272    request_id: &str,
273) -> BashStep {
274    if snapshot.info.status.is_terminal() {
275        BashStep::Done(foreground_result_response(request_id, snapshot))
276    } else if !block_to_completion && now >= deadline {
277        BashStep::Promote
278    } else {
279        BashStep::Wait
280    }
281}
282
283pub(crate) fn promote_bash(
284    ctx: &AppContext,
285    task_id: &str,
286    session_id: &str,
287    timeout: Option<u64>,
288    wait_window_ms: u64,
289    request_id: &str,
290) -> Response {
291    match ctx.bash_background().promote(task_id, session_id) {
292        Ok(_) => promotion_response(request_id, task_id, timeout, wait_window_ms),
293        Err(message) if message.contains("not found") => Response::error(
294            request_id,
295            "task_not_found",
296            crate::commands::bash_status::format_unknown_task_message(task_id),
297        ),
298        Err(message) => Response::error(request_id, "execution_failed", message),
299    }
300}
301
302pub(crate) fn detach_wait_mode_bash(
303    ctx: &AppContext,
304    task_id: &str,
305    session_id: &str,
306    request_id: &str,
307) -> Response {
308    match ctx.bash_background().promote(task_id, session_id) {
309        Ok(_) => wait_detach_response(request_id, task_id),
310        Err(message) if message.contains("not found") => Response::error(
311            request_id,
312            "task_not_found",
313            crate::commands::bash_status::format_unknown_task_message(task_id),
314        ),
315        Err(message) => Response::error(request_id, "execution_failed", message),
316    }
317}
318
319fn foreground_result_response(request_id: &str, snapshot: BgTaskSnapshot) -> Response {
320    let output = format_foreground_result(&snapshot);
321    if snapshot.sandbox_native
322        && snapshot.sandbox_unavailable
323        && snapshot.exit_code == Some(crate::sandbox_spawn::SANDBOX_UNAVAILABLE_EXIT_CODE)
324    {
325        return Response::error_with_data(
326            request_id,
327            "sandbox_unavailable",
328            "native sandbox failed before the command could run; set sandbox.enabled=false to disable native sandboxing",
329            json!({
330                "task_id": snapshot.info.task_id,
331                "exit_code": snapshot.exit_code,
332                "output": output,
333            }),
334        );
335    }
336    let timed_out = snapshot.info.status == BgTaskStatus::TimedOut;
337    Response::success(
338        request_id,
339        json!({
340            "output": output,
341            "task_id": snapshot.info.task_id,
342            "status": snapshot.info.status,
343            "mode": snapshot.info.mode,
344            "exit_code": snapshot.exit_code,
345            "output_preview": snapshot.output_preview,
346            "output_truncated": snapshot.output_truncated,
347            "truncated": snapshot.output_truncated,
348            "output_path": snapshot.output_path,
349            "timed_out": timed_out,
350            "duration_ms": snapshot.info.duration_ms,
351        }),
352    )
353}
354
355fn background_launch_response(request_id: &str, task_id: &str, is_pty: bool) -> Response {
356    Response::success(
357        request_id,
358        json!({
359            "output": format_background_launch(task_id, is_pty),
360            "task_id": task_id,
361            "status": "running",
362            "mode": if is_pty { "pty" } else { "pipes" },
363        }),
364    )
365}
366
367fn promotion_response(
368    request_id: &str,
369    task_id: &str,
370    timeout: Option<u64>,
371    wait_window_ms: u64,
372) -> Response {
373    Response::success(
374        request_id,
375        json!({
376            "output": format_promotion_message(task_id, timeout, wait_window_ms),
377            "task_id": task_id,
378            "status": "running",
379        }),
380    )
381}
382
383fn wait_detach_response(request_id: &str, task_id: &str) -> Response {
384    Response::success(
385        request_id,
386        json!({
387            "output": format_wait_detach_message(task_id),
388            "task_id": task_id,
389            "status": "running",
390        }),
391    )
392}
393
394fn parse_params(req: &RawRequest) -> Option<BashOrchestrateParams> {
395    let raw_params = req
396        .params
397        .get("params")
398        .cloned()
399        .unwrap_or_else(|| req.params.clone());
400    serde_json::from_value::<BashOrchestrateParams>(raw_params).ok()
401}
402
403pub(crate) fn resolve_foreground_wait_window_ms(configured: u64) -> u64 {
404    std::env::var(TEST_FOREGROUND_WAIT_ENV)
405        .ok()
406        .and_then(|raw| raw.parse::<u64>().ok())
407        .unwrap_or(configured)
408}
409
410pub(crate) fn select_foreground_wait_window_ms(
411    configured: u64,
412    timeout: Option<u64>,
413    wait: bool,
414) -> u64 {
415    if wait {
416        timeout.unwrap_or(DEFAULT_FOREGROUND_WAIT_TIMEOUT_MS)
417    } else {
418        resolve_foreground_wait_window_ms(configured)
419    }
420}
421
422#[cfg(test)]
423mod tests {
424    use super::*;
425    use crate::bash_background::persistence::BgMode;
426    use crate::bash_background::registry::BgTaskSnapshot;
427    use crate::bash_background::BgTaskInfo;
428
429    fn snapshot(
430        output_preview: &str,
431        output_truncated: bool,
432        output_path: Option<&str>,
433        status: BgTaskStatus,
434        exit_code: Option<i32>,
435    ) -> BgTaskSnapshot {
436        BgTaskSnapshot {
437            info: BgTaskInfo {
438                task_id: "bash-test".to_string(),
439                status,
440                command: "echo test".to_string(),
441                mode: BgMode::Pipes,
442                started_at: 0,
443                duration_ms: Some(1),
444                status_reason: None,
445            },
446            exit_code,
447            child_pid: None,
448            workdir: "/tmp".to_string(),
449            output_preview: output_preview.to_string(),
450            output_truncated,
451            output_path: output_path.map(str::to_string),
452            stderr_path: None,
453            pty_rows: None,
454            pty_cols: None,
455            pty_screen: None,
456            scanner_report: Vec::new(),
457            sandbox_native: false,
458            sandbox_unavailable: false,
459        }
460    }
461
462    #[test]
463    fn native_launcher_exit_78_is_a_structured_sandbox_error() {
464        let mut snapshot = snapshot(
465            "sandbox_unavailable: backend failed",
466            false,
467            None,
468            BgTaskStatus::Failed,
469            Some(crate::sandbox_spawn::SANDBOX_UNAVAILABLE_EXIT_CODE),
470        );
471        snapshot.sandbox_native = true;
472        snapshot.sandbox_unavailable = true;
473
474        let response = foreground_result_response("sandbox-failed", snapshot);
475        assert!(!response.success);
476        assert_eq!(
477            response
478                .data
479                .get("code")
480                .and_then(serde_json::Value::as_str),
481            Some("sandbox_unavailable")
482        );
483        assert!(response
484            .data
485            .get("message")
486            .and_then(serde_json::Value::as_str)
487            .is_some_and(|message| message.contains("sandbox.enabled=false")));
488    }
489
490    #[test]
491    fn native_command_exit_78_is_not_misreported_as_launcher_failure() {
492        let mut snapshot = snapshot(
493            "command selected exit 78",
494            false,
495            None,
496            BgTaskStatus::Failed,
497            Some(crate::sandbox_spawn::SANDBOX_UNAVAILABLE_EXIT_CODE),
498        );
499        snapshot.sandbox_native = true;
500
501        let response = foreground_result_response("command-exit-78", snapshot);
502        assert!(response.success);
503        assert_eq!(
504            response
505                .data
506                .get("exit_code")
507                .and_then(serde_json::Value::as_i64),
508            Some(i64::from(
509                crate::sandbox_spawn::SANDBOX_UNAVAILABLE_EXIT_CODE
510            ))
511        );
512    }
513
514    #[test]
515    fn decide_bash_step_returns_done_for_terminal_snapshot_even_at_deadline() {
516        let snapshot = snapshot("done", false, None, BgTaskStatus::Completed, Some(0));
517        let now = Instant::now();
518
519        match decide_bash_step(snapshot, now, false, now, "req-terminal") {
520            BashStep::Done(response) => {
521                assert_eq!(response.id, "req-terminal");
522                assert!(response.success);
523                assert_eq!(response.data["status"], json!("completed"));
524                assert_eq!(response.data["output"], json!("done"));
525            }
526            BashStep::Promote => panic!("terminal snapshot should not promote"),
527            BashStep::Wait => panic!("terminal snapshot should not wait"),
528        }
529    }
530
531    #[test]
532    fn decide_bash_step_promotes_at_deadline_when_not_blocking() {
533        let snapshot = snapshot("running", false, None, BgTaskStatus::Running, None);
534        let now = Instant::now();
535
536        match decide_bash_step(snapshot, now, false, now, "req-promote") {
537            BashStep::Promote => {}
538            BashStep::Done(_) => panic!("running snapshot should not finish"),
539            BashStep::Wait => panic!("deadline should promote when not blocking"),
540        }
541    }
542
543    #[test]
544    fn decide_bash_step_waits_before_deadline() {
545        let snapshot = snapshot("running", false, None, BgTaskStatus::Running, None);
546        let now = Instant::now();
547
548        match decide_bash_step(
549            snapshot,
550            now + Duration::from_millis(1),
551            false,
552            now,
553            "req-wait",
554        ) {
555            BashStep::Wait => {}
556            BashStep::Done(_) => panic!("running snapshot should not finish"),
557            BashStep::Promote => panic!("snapshot should wait before the deadline"),
558        }
559    }
560
561    #[test]
562    fn decide_bash_step_never_promotes_when_blocking_to_completion() {
563        let snapshot = snapshot("running", false, None, BgTaskStatus::Running, None);
564        let now = Instant::now();
565
566        match decide_bash_step(snapshot, now, true, now, "req-block") {
567            BashStep::Wait => {}
568            BashStep::Done(_) => panic!("running snapshot should not finish"),
569            BashStep::Promote => panic!("block_to_completion should suppress promotion"),
570        }
571    }
572
573    #[test]
574    fn select_foreground_wait_window_uses_timeout_budget_for_wait_true() {
575        assert_eq!(
576            select_foreground_wait_window_ms(8_000, Some(250), true),
577            250
578        );
579        assert_eq!(
580            select_foreground_wait_window_ms(8_000, None, true),
581            DEFAULT_FOREGROUND_WAIT_TIMEOUT_MS
582        );
583    }
584
585    #[test]
586    fn foreground_result_format_matches_typescript_order() {
587        let snapshot = snapshot(
588            "hello",
589            true,
590            Some("/tmp/aft-output.txt"),
591            BgTaskStatus::TimedOut,
592            Some(124),
593        );
594
595        assert_eq!(
596            format_foreground_result(&snapshot),
597            "hello\n[output truncated; full output at /tmp/aft-output.txt]\n[command timed out]\n[exit code: 124]"
598        );
599    }
600
601    #[test]
602    fn format_seconds_strips_integer_decimal_and_keeps_tenths() {
603        assert_eq!(format_seconds(8_000), "8s");
604        assert_eq!(format_seconds(5_500), "5.5s");
605        assert_eq!(format_seconds(14_999), "15s");
606    }
607
608    #[test]
609    fn promotion_message_matches_opencode_copy() {
610        assert_eq!(
611            format_promotion_message("bash-123", Some(5_500), 8_000),
612            "Foreground bash didn't finish within 5.5s and was promoted to background: bash-123. A completion reminder will be delivered automatically; use bash_status({ taskId: \"bash-123\" }) to inspect output or bash_kill({ taskId: \"bash-123\" }) to terminate."
613        );
614    }
615
616    #[test]
617    fn wait_detach_message_mentions_user_message() {
618        assert_eq!(
619            format_wait_detach_message("bash-123"),
620            "Foreground bash is running in background as bash-123. A completion reminder will be delivered automatically; use bash_status({ taskId: \"bash-123\" }) to inspect output or bash_kill({ taskId: \"bash-123\" }) to terminate.\nDetached because a user message arrived."
621        );
622    }
623
624    #[test]
625    fn background_launch_messages_match_opencode_copy() {
626        assert_eq!(
627            format_background_launch("bash-bg", false),
628            "Background task started: bash-bg. A completion reminder will be delivered automatically; don't poll bash_status."
629        );
630        assert_eq!(
631            format_background_launch("bash-pty", true),
632            "PTY task started: bash-pty. Use bash_status({ taskId: \"bash-pty\", outputMode: \"screen\" }) to see the visible terminal, bash_write({ taskId: \"bash-pty\", input: ... }) to send keystrokes. A completion reminder fires automatically when the task exits."
633        );
634    }
635}