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