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        on_shutdown: None,
232    })
233}
234
235pub(crate) fn poll_bash_status(
236    ctx: &AppContext,
237    task_id: &str,
238    session_id: &str,
239    project_root: Option<&Path>,
240    storage_dir: &Path,
241    preview_bytes: usize,
242) -> Option<BgTaskSnapshot> {
243    ctx.bash_background().status(
244        task_id,
245        session_id,
246        project_root,
247        Some(storage_dir),
248        preview_bytes,
249    )
250}
251
252pub(crate) enum BashStep {
253    Done(Response),
254    Promote,
255    Wait,
256}
257
258pub(crate) fn task_not_found_response(request_id: &str, task_id: &str) -> Response {
259    Response::error(
260        request_id,
261        "task_not_found",
262        crate::commands::bash_status::format_unknown_task_message(task_id),
263    )
264}
265
266pub(crate) fn decide_bash_step(
267    snapshot: BgTaskSnapshot,
268    deadline: Instant,
269    block_to_completion: bool,
270    now: Instant,
271    request_id: &str,
272) -> BashStep {
273    if snapshot.info.status.is_terminal() {
274        BashStep::Done(foreground_result_response(request_id, snapshot))
275    } else if !block_to_completion && now >= deadline {
276        BashStep::Promote
277    } else {
278        BashStep::Wait
279    }
280}
281
282pub(crate) fn promote_bash(
283    ctx: &AppContext,
284    task_id: &str,
285    session_id: &str,
286    timeout: Option<u64>,
287    wait_window_ms: u64,
288    request_id: &str,
289) -> Response {
290    match ctx.bash_background().promote(task_id, session_id) {
291        Ok(_) => promotion_response(request_id, task_id, timeout, wait_window_ms),
292        Err(message) if message.contains("not found") => Response::error(
293            request_id,
294            "task_not_found",
295            crate::commands::bash_status::format_unknown_task_message(task_id),
296        ),
297        Err(message) => Response::error(request_id, "execution_failed", message),
298    }
299}
300
301pub(crate) fn detach_wait_mode_bash(
302    ctx: &AppContext,
303    task_id: &str,
304    session_id: &str,
305    request_id: &str,
306) -> Response {
307    match ctx.bash_background().promote(task_id, session_id) {
308        Ok(_) => wait_detach_response(request_id, task_id),
309        Err(message) if message.contains("not found") => Response::error(
310            request_id,
311            "task_not_found",
312            crate::commands::bash_status::format_unknown_task_message(task_id),
313        ),
314        Err(message) => Response::error(request_id, "execution_failed", message),
315    }
316}
317
318fn foreground_result_response(request_id: &str, snapshot: BgTaskSnapshot) -> Response {
319    let output = format_foreground_result(&snapshot);
320    if snapshot.sandbox_native
321        && snapshot.sandbox_unavailable
322        && snapshot.exit_code == Some(crate::sandbox_spawn::SANDBOX_UNAVAILABLE_EXIT_CODE)
323    {
324        return Response::error_with_data(
325            request_id,
326            "sandbox_unavailable",
327            "native sandbox failed before the command could run; set sandbox.enabled=false to disable native sandboxing",
328            json!({
329                "task_id": snapshot.info.task_id,
330                "exit_code": snapshot.exit_code,
331                "output": output,
332            }),
333        );
334    }
335    let timed_out = snapshot.info.status == BgTaskStatus::TimedOut;
336    Response::success(
337        request_id,
338        json!({
339            "output": output,
340            "task_id": snapshot.info.task_id,
341            "status": snapshot.info.status,
342            "mode": snapshot.info.mode,
343            "exit_code": snapshot.exit_code,
344            "output_preview": snapshot.output_preview,
345            "output_truncated": snapshot.output_truncated,
346            "truncated": snapshot.output_truncated,
347            "output_path": snapshot.output_path,
348            "timed_out": timed_out,
349            "duration_ms": snapshot.info.duration_ms,
350        }),
351    )
352}
353
354fn background_launch_response(request_id: &str, task_id: &str, is_pty: bool) -> Response {
355    Response::success(
356        request_id,
357        json!({
358            "output": format_background_launch(task_id, is_pty),
359            "task_id": task_id,
360            "status": "running",
361            "mode": if is_pty { "pty" } else { "pipes" },
362        }),
363    )
364}
365
366fn promotion_response(
367    request_id: &str,
368    task_id: &str,
369    timeout: Option<u64>,
370    wait_window_ms: u64,
371) -> Response {
372    Response::success(
373        request_id,
374        json!({
375            "output": format_promotion_message(task_id, timeout, wait_window_ms),
376            "task_id": task_id,
377            "status": "running",
378        }),
379    )
380}
381
382fn wait_detach_response(request_id: &str, task_id: &str) -> Response {
383    Response::success(
384        request_id,
385        json!({
386            "output": format_wait_detach_message(task_id),
387            "task_id": task_id,
388            "status": "running",
389        }),
390    )
391}
392
393fn parse_params(req: &RawRequest) -> Option<BashOrchestrateParams> {
394    let raw_params = req
395        .params
396        .get("params")
397        .cloned()
398        .unwrap_or_else(|| req.params.clone());
399    serde_json::from_value::<BashOrchestrateParams>(raw_params).ok()
400}
401
402pub(crate) fn resolve_foreground_wait_window_ms(configured: u64) -> u64 {
403    std::env::var(TEST_FOREGROUND_WAIT_ENV)
404        .ok()
405        .and_then(|raw| raw.parse::<u64>().ok())
406        .unwrap_or(configured)
407}
408
409pub(crate) fn select_foreground_wait_window_ms(
410    configured: u64,
411    timeout: Option<u64>,
412    wait: bool,
413) -> u64 {
414    if wait {
415        timeout.unwrap_or(DEFAULT_FOREGROUND_WAIT_TIMEOUT_MS)
416    } else {
417        resolve_foreground_wait_window_ms(configured)
418    }
419}
420
421#[cfg(test)]
422mod tests {
423    use super::*;
424    use crate::bash_background::persistence::BgMode;
425    use crate::bash_background::registry::BgTaskSnapshot;
426    use crate::bash_background::BgTaskInfo;
427
428    fn snapshot(
429        output_preview: &str,
430        output_truncated: bool,
431        output_path: Option<&str>,
432        status: BgTaskStatus,
433        exit_code: Option<i32>,
434    ) -> BgTaskSnapshot {
435        BgTaskSnapshot {
436            info: BgTaskInfo {
437                task_id: "bash-test".to_string(),
438                status,
439                command: "echo test".to_string(),
440                mode: BgMode::Pipes,
441                started_at: 0,
442                duration_ms: Some(1),
443                status_reason: None,
444            },
445            exit_code,
446            child_pid: None,
447            workdir: "/tmp".to_string(),
448            output_preview: output_preview.to_string(),
449            output_truncated,
450            output_path: output_path.map(str::to_string),
451            stderr_path: None,
452            pty_rows: None,
453            pty_cols: None,
454            pty_screen: None,
455            scanner_report: Vec::new(),
456            sandbox_native: false,
457            sandbox_unavailable: false,
458        }
459    }
460
461    #[test]
462    fn native_launcher_exit_78_is_a_structured_sandbox_error() {
463        let mut snapshot = snapshot(
464            "sandbox_unavailable: backend failed",
465            false,
466            None,
467            BgTaskStatus::Failed,
468            Some(crate::sandbox_spawn::SANDBOX_UNAVAILABLE_EXIT_CODE),
469        );
470        snapshot.sandbox_native = true;
471        snapshot.sandbox_unavailable = true;
472
473        let response = foreground_result_response("sandbox-failed", snapshot);
474        assert!(!response.success);
475        assert_eq!(
476            response
477                .data
478                .get("code")
479                .and_then(serde_json::Value::as_str),
480            Some("sandbox_unavailable")
481        );
482        assert!(response
483            .data
484            .get("message")
485            .and_then(serde_json::Value::as_str)
486            .is_some_and(|message| message.contains("sandbox.enabled=false")));
487    }
488
489    #[test]
490    fn native_command_exit_78_is_not_misreported_as_launcher_failure() {
491        let mut snapshot = snapshot(
492            "command selected exit 78",
493            false,
494            None,
495            BgTaskStatus::Failed,
496            Some(crate::sandbox_spawn::SANDBOX_UNAVAILABLE_EXIT_CODE),
497        );
498        snapshot.sandbox_native = true;
499
500        let response = foreground_result_response("command-exit-78", snapshot);
501        assert!(response.success);
502        assert_eq!(
503            response
504                .data
505                .get("exit_code")
506                .and_then(serde_json::Value::as_i64),
507            Some(i64::from(
508                crate::sandbox_spawn::SANDBOX_UNAVAILABLE_EXIT_CODE
509            ))
510        );
511    }
512
513    #[test]
514    fn decide_bash_step_returns_done_for_terminal_snapshot_even_at_deadline() {
515        let snapshot = snapshot("done", false, None, BgTaskStatus::Completed, Some(0));
516        let now = Instant::now();
517
518        match decide_bash_step(snapshot, now, false, now, "req-terminal") {
519            BashStep::Done(response) => {
520                assert_eq!(response.id, "req-terminal");
521                assert!(response.success);
522                assert_eq!(response.data["status"], json!("completed"));
523                assert_eq!(response.data["output"], json!("done"));
524            }
525            BashStep::Promote => panic!("terminal snapshot should not promote"),
526            BashStep::Wait => panic!("terminal snapshot should not wait"),
527        }
528    }
529
530    #[test]
531    fn decide_bash_step_promotes_at_deadline_when_not_blocking() {
532        let snapshot = snapshot("running", false, None, BgTaskStatus::Running, None);
533        let now = Instant::now();
534
535        match decide_bash_step(snapshot, now, false, now, "req-promote") {
536            BashStep::Promote => {}
537            BashStep::Done(_) => panic!("running snapshot should not finish"),
538            BashStep::Wait => panic!("deadline should promote when not blocking"),
539        }
540    }
541
542    #[test]
543    fn decide_bash_step_waits_before_deadline() {
544        let snapshot = snapshot("running", false, None, BgTaskStatus::Running, None);
545        let now = Instant::now();
546
547        match decide_bash_step(
548            snapshot,
549            now + Duration::from_millis(1),
550            false,
551            now,
552            "req-wait",
553        ) {
554            BashStep::Wait => {}
555            BashStep::Done(_) => panic!("running snapshot should not finish"),
556            BashStep::Promote => panic!("snapshot should wait before the deadline"),
557        }
558    }
559
560    #[test]
561    fn decide_bash_step_never_promotes_when_blocking_to_completion() {
562        let snapshot = snapshot("running", false, None, BgTaskStatus::Running, None);
563        let now = Instant::now();
564
565        match decide_bash_step(snapshot, now, true, now, "req-block") {
566            BashStep::Wait => {}
567            BashStep::Done(_) => panic!("running snapshot should not finish"),
568            BashStep::Promote => panic!("block_to_completion should suppress promotion"),
569        }
570    }
571
572    #[test]
573    fn select_foreground_wait_window_uses_timeout_budget_for_wait_true() {
574        assert_eq!(
575            select_foreground_wait_window_ms(8_000, Some(250), true),
576            250
577        );
578        assert_eq!(
579            select_foreground_wait_window_ms(8_000, None, true),
580            DEFAULT_FOREGROUND_WAIT_TIMEOUT_MS
581        );
582    }
583
584    #[test]
585    fn foreground_result_format_matches_typescript_order() {
586        let snapshot = snapshot(
587            "hello",
588            true,
589            Some("/tmp/aft-output.txt"),
590            BgTaskStatus::TimedOut,
591            Some(124),
592        );
593
594        assert_eq!(
595            format_foreground_result(&snapshot),
596            "hello\n[output truncated; full output at /tmp/aft-output.txt]\n[command timed out]\n[exit code: 124]"
597        );
598    }
599
600    #[test]
601    fn format_seconds_strips_integer_decimal_and_keeps_tenths() {
602        assert_eq!(format_seconds(8_000), "8s");
603        assert_eq!(format_seconds(5_500), "5.5s");
604        assert_eq!(format_seconds(14_999), "15s");
605    }
606
607    #[test]
608    fn promotion_message_matches_opencode_copy() {
609        assert_eq!(
610            format_promotion_message("bash-123", Some(5_500), 8_000),
611            "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."
612        );
613    }
614
615    #[test]
616    fn wait_detach_message_mentions_user_message() {
617        assert_eq!(
618            format_wait_detach_message("bash-123"),
619            "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."
620        );
621    }
622
623    #[test]
624    fn background_launch_messages_match_opencode_copy() {
625        assert_eq!(
626            format_background_launch("bash-bg", false),
627            "Background task started: bash-bg. A completion reminder will be delivered automatically; don't poll bash_status."
628        );
629        assert_eq!(
630            format_background_launch("bash-pty", true),
631            "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."
632        );
633    }
634}