Skip to main content

ag_agent/agent/
submission.rs

1//! One-shot agent prompt execution helpers.
2//!
3//! These helpers run isolated utility prompts outside the long-lived session
4//! turn flow. They require the shared structured response protocol on every
5//! transport so one-shot callers enforce the same schema contract as normal
6//! session turns.
7
8use std::path::PathBuf;
9use std::sync::{Arc, Mutex};
10
11use ag_protocol::{
12    AgentResponse, ProtocolRequestProfile, build_protocol_repair_prompt,
13    format_protocol_parse_debug_details, parse_protocol_response_strict,
14};
15use async_trait::async_trait;
16
17use super::backend::{AgentBackend, BuildCommandRequest};
18use super::cli::error;
19use super::cli::execution::{self, CliExecutionError, CliExecutionObserver, CliExitStatus};
20use super::{
21    ParsedResponse, create_app_server_client, create_backend, parse_response, transport_mode,
22};
23use crate::app_server::{AppServerClient, AppServerTurnRequest};
24use crate::channel::AgentRequestKind;
25use crate::model::agent::{AgentKind, AgentModel, ReasoningLevel};
26use crate::model::permission::PermissionMode;
27use crate::model::session::{SessionDiffState, SessionStats, SpeedMode};
28
29/// Input payload for one isolated prompt that prefers structured protocol
30/// output.
31#[derive(Clone, Debug)]
32pub struct OneShotRequest {
33    /// Provider backend used for command construction, stdin shaping, and
34    /// response parsing.
35    pub agent_kind: AgentKind,
36    /// Optional PID slot used by cancel/stop flows to terminate the spawned
37    /// subprocess while a one-shot prompt is running.
38    pub child_pid: Option<Arc<Mutex<Option<u32>>>>,
39    /// Working directory where the prompt command runs.
40    pub folder: PathBuf,
41    /// Provider-specific model used for command construction and parsing.
42    pub model: AgentModel,
43    /// Filesystem and command permission policy for this isolated prompt.
44    pub permission_mode: PermissionMode,
45    /// Prompt text submitted to the agent.
46    pub prompt: String,
47    /// Canonical request kind for this isolated prompt.
48    pub request_kind: AgentRequestKind,
49    /// Reasoning effort preference for the one-shot prompt.
50    pub reasoning_level: ReasoningLevel,
51    /// Response-speed preference for the one-shot prompt.
52    pub speed_mode: SpeedMode,
53}
54
55/// Parsed result returned by one isolated prompt execution.
56#[derive(Clone, Debug, PartialEq)]
57pub struct OneShotSubmission {
58    /// Structured protocol response parsed from the final successful attempt.
59    pub response: AgentResponse,
60    /// Aggregated token usage for the one-shot prompt execution.
61    pub stats: SessionStats,
62}
63
64/// Typed failure returned by [`OneShotClient`] submissions.
65///
66/// The concrete transport, protocol-repair, and provider diagnostics remain
67/// available through [`std::fmt::Display`] without exposing transport-specific
68/// variants to callers.
69#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
70#[error("{message}")]
71pub struct OneShotError {
72    message: String,
73}
74
75impl OneShotError {
76    /// Creates an error from one already formatted submission diagnostic.
77    pub fn new(message: impl Into<String>) -> Self {
78        Self {
79            message: message.into(),
80        }
81    }
82}
83
84/// Provider-neutral boundary for isolated structured agent prompts.
85///
86/// Implementations own transport selection, protocol repair, temporary
87/// app-server lifecycle, and usage aggregation so callers submit one request
88/// without selecting a CLI or app-server execution helper.
89#[cfg_attr(any(test, feature = "test-utils"), mockall::automock)]
90#[async_trait]
91pub trait OneShotClient: Send + Sync {
92    /// Executes one isolated prompt and returns its parsed response and usage.
93    async fn submit(&self, request: OneShotRequest) -> Result<OneShotSubmission, OneShotError>;
94}
95
96/// Production [`OneShotClient`] that routes through the selected provider.
97pub struct RealOneShotClient {
98    app_server_client_override: Option<Arc<dyn AppServerClient>>,
99}
100
101impl RealOneShotClient {
102    /// Creates a client with an optional app-server override.
103    ///
104    /// Production passes `None` so each provider supplies its native client;
105    /// deterministic environments may inject a shared app-server boundary.
106    pub fn new(app_server_client_override: Option<Arc<dyn AppServerClient>>) -> Self {
107        Self {
108            app_server_client_override,
109        }
110    }
111}
112
113#[async_trait]
114impl OneShotClient for RealOneShotClient {
115    async fn submit(&self, request: OneShotRequest) -> Result<OneShotSubmission, OneShotError> {
116        let app_server_client_override = self.app_server_client_override.as_ref().map(Arc::clone);
117
118        submit_one_shot_with_stats_and_app_server_client(request, app_server_client_override)
119            .await
120            .map_err(OneShotError::new)
121    }
122}
123
124/// Executes one isolated prompt and returns the parsed response plus
125/// aggregated usage statistics, optionally overriding the backend-owned
126/// app-server client.
127///
128/// # Errors
129/// Returns an error when command construction fails, process execution fails,
130/// or the final output is empty or otherwise unusable.
131async fn submit_one_shot_with_stats_and_app_server_client(
132    request: OneShotRequest,
133    app_server_client_override: Option<Arc<dyn AppServerClient>>,
134) -> Result<OneShotSubmission, String> {
135    let backend = create_backend(request.agent_kind);
136
137    if transport_mode(request.agent_kind).uses_app_server() {
138        let app_server_client =
139            create_app_server_client(request.agent_kind, app_server_client_override).ok_or_else(
140                || {
141                    format!(
142                        "{} provider did not provide an app-server client",
143                        request.agent_kind
144                    )
145                },
146            )?;
147
148        return submit_one_shot_with_app_server_client(app_server_client.as_ref(), request).await;
149    }
150
151    submit_one_shot_with_backend(backend.as_ref(), request).await
152}
153
154/// Executes one isolated prompt through the shared app-server transport.
155///
156/// The temporary app-server session is shut down after the utility prompt
157/// finishes so one-shot helpers do not keep a provider runtime alive after the
158/// result has been parsed.
159///
160/// # Errors
161/// Returns an error when app-server turn execution fails or the final output
162/// is empty or otherwise unusable.
163async fn submit_one_shot_with_app_server_client(
164    app_server_client: &dyn AppServerClient,
165    request: OneShotRequest,
166) -> Result<OneShotSubmission, String> {
167    clear_child_pid_slot(request.child_pid.as_deref());
168
169    let session_id = format!("one-shot-{}", uuid::Uuid::new_v4());
170    let protocol_profile = request.request_kind.protocol_profile();
171    let (stream_tx, _stream_rx) = tokio::sync::mpsc::unbounded_channel();
172    let turn_request = AppServerTurnRequest {
173        folder: request.folder.clone(),
174        live_transcript: None,
175        main_checkout_root: None,
176        model: request.model.provider_model_str().to_string(),
177        permission_mode: request.permission_mode,
178        personality: crate::channel::PersonalityPrompt::default(),
179        prompt: ag_protocol::TurnPrompt::from_agent_data(request.prompt.clone()),
180        request_kind: request.request_kind.clone(),
181        replay_transcript: None,
182        provider_conversation_id: None,
183        persisted_instruction_conversation_id: None,
184        reasoning_level: request.reasoning_level,
185        session_id: session_id.clone(),
186        speed_mode: request.speed_mode,
187    };
188
189    let turn_result = app_server_client.run_turn(turn_request, stream_tx).await;
190
191    let child_pid = request.child_pid.as_ref().map(Arc::clone);
192
193    let turn_result = match turn_result {
194        Ok(result) => result,
195        Err(error) => {
196            app_server_client.shutdown_session(session_id).await;
197            clear_child_pid_slot(child_pid.as_deref());
198
199            return Err(format!(
200                "Failed to execute one-shot app-server turn: {error}"
201            ));
202        }
203    };
204
205    let parse_result =
206        match parse_one_shot_response(&turn_result.assistant_message, protocol_profile) {
207            Ok(response) => Ok((response, 0, 0)),
208            Err(parse_error) => {
209                attempt_one_shot_app_server_repair(
210                    app_server_client,
211                    &parse_error,
212                    &turn_result.assistant_message,
213                    request,
214                    &session_id,
215                    turn_result.provider_conversation_id.as_deref(),
216                )
217                .await
218            }
219        };
220
221    app_server_client.shutdown_session(session_id).await;
222    clear_child_pid_slot(child_pid.as_deref());
223
224    let (response, repair_input_tokens, repair_output_tokens) = parse_result?;
225
226    Ok(OneShotSubmission {
227        response,
228        stats: SessionStats {
229            added_lines: 0,
230            deleted_lines: 0,
231            diff_state: SessionDiffState::Unknown,
232            input_tokens: turn_result.input_tokens + repair_input_tokens,
233            output_tokens: turn_result.output_tokens + repair_output_tokens,
234        },
235    })
236}
237
238/// Executes one isolated prompt using the provided backend.
239///
240/// This shared helper keeps process execution behind the existing
241/// `AgentBackend` trait boundary so production callers and tests can reuse
242/// the same one-shot parsing path.
243///
244/// # Errors
245/// Returns an error when command construction fails, process execution fails,
246/// or the final output is empty or otherwise unusable.
247async fn submit_one_shot_with_backend(
248    backend: &dyn AgentBackend,
249    request: OneShotRequest,
250) -> Result<OneShotSubmission, String> {
251    let protocol_profile = request.request_kind.protocol_profile();
252    let parsed_response =
253        execute_one_shot_command(backend, &request.prompt, request.clone()).await?;
254    let (agent_response, repair_stats) =
255        match parse_one_shot_response(&parsed_response.content, protocol_profile) {
256            Ok(response) => (response, None),
257            Err(parse_error) => {
258                let repair_prompt =
259                    build_protocol_repair_prompt(&parse_error, &parsed_response.content)?;
260                let request = OneShotRequest {
261                    permission_mode: PermissionMode::ReadOnly,
262                    ..request
263                };
264                let repair_response = execute_one_shot_command(backend, &repair_prompt, request)
265                    .await
266                    .map_err(|error| format!("{parse_error}\nrepair transport failed: {error}"))?;
267
268                let response = parse_one_shot_response(&repair_response.content, protocol_profile)
269                    .map_err(|error| {
270                        format!(
271                            "{parse_error}\nrepair retry also failed: \
272                             {error}\nrepair_response:\n{}",
273                            repair_response.content
274                        )
275                    })?;
276
277                (response, Some(repair_response.stats))
278            }
279        };
280
281    let mut stats = parsed_response.stats;
282    if let Some(repair) = repair_stats {
283        stats.input_tokens += repair.input_tokens;
284        stats.output_tokens += repair.output_tokens;
285    }
286
287    Ok(OneShotSubmission {
288        response: agent_response,
289        stats,
290    })
291}
292
293/// Parses one one-shot response strictly against the shared protocol schema.
294///
295/// # Errors
296/// Returns an error when the response is empty or not valid protocol JSON. The
297/// error carries the parse reason and derived diagnostics only, never the
298/// provider payload itself.
299fn parse_one_shot_response(
300    content: &str,
301    protocol_profile: ProtocolRequestProfile,
302) -> Result<AgentResponse, String> {
303    parse_protocol_response_strict(content, protocol_profile).map_err(|error| {
304        format!(
305            "One-shot agent output did not match the required JSON schema: \
306             {error}\ndebug_details:\n{}",
307            format_protocol_parse_debug_details(content)
308        )
309    })
310}
311
312/// Attempts one protocol-repair retry through the app-server transport for
313/// a one-shot prompt whose initial response failed schema validation.
314///
315/// The repair prompt is sent as a follow-up turn on the same session so the
316/// agent retains the original conversation context. The initial turn's
317/// `provider_conversation_id` is threaded through so providers that depend
318/// on conversation state can continue the same thread.
319///
320/// Returns the parsed response together with the repair turn's token usage
321/// so the caller can aggregate stats across both attempts.
322///
323/// # Errors
324/// Returns the combined original and repair error when the retry fails.
325async fn attempt_one_shot_app_server_repair(
326    app_server_client: &dyn AppServerClient,
327    parse_error: &str,
328    malformed_response: &str,
329    request: OneShotRequest,
330    session_id: &str,
331    provider_conversation_id: Option<&str>,
332) -> Result<(AgentResponse, u64, u64), String> {
333    let protocol_profile = request.request_kind.protocol_profile();
334    let repair_prompt = build_protocol_repair_prompt(parse_error, malformed_response)?;
335
336    let (repair_stream_tx, _repair_stream_rx) = tokio::sync::mpsc::unbounded_channel();
337    let repair_turn_request = AppServerTurnRequest {
338        folder: request.folder,
339        live_transcript: None,
340        main_checkout_root: None,
341        model: request.model.provider_model_str().to_string(),
342        permission_mode: request.permission_mode,
343        personality: crate::channel::PersonalityPrompt::default(),
344        prompt: ag_protocol::TurnPrompt::from_agent_data(repair_prompt),
345        request_kind: request.request_kind,
346        replay_transcript: None,
347        provider_conversation_id: provider_conversation_id.map(String::from),
348        persisted_instruction_conversation_id: None,
349        reasoning_level: request.reasoning_level,
350        session_id: session_id.to_string(),
351        speed_mode: request.speed_mode,
352    };
353    let repair_result = app_server_client
354        .run_turn(repair_turn_request, repair_stream_tx)
355        .await
356        .map_err(|error| format!("{parse_error}\nrepair transport failed: {error}"))?;
357
358    let response = parse_one_shot_response(&repair_result.assistant_message, protocol_profile)
359        .map_err(|error| {
360            format!(
361                "{parse_error}\nrepair retry also failed: {error}\nrepair_response:\n{}",
362                repair_result.assistant_message
363            )
364        })?;
365
366    Ok((
367        response,
368        repair_result.input_tokens,
369        repair_result.output_tokens,
370    ))
371}
372
373/// Runs one one-shot backend command and returns the parsed provider content.
374///
375/// The spawned child is configured with `kill_on_drop(true)` so timeout-driven
376/// callers do not leave orphaned agent CLI processes behind when the future is
377/// canceled before completion.
378///
379/// # Errors
380/// Returns an error when the command cannot be built, run, or exits
381/// unsuccessfully.
382async fn execute_one_shot_command(
383    backend: &dyn AgentBackend,
384    prompt: &str,
385    request: OneShotRequest,
386) -> Result<ParsedResponse, String> {
387    let prompt_payload = ag_protocol::TurnPrompt::from_agent_data(prompt.to_string());
388    let build_request = BuildCommandRequest {
389        attachments: &prompt_payload.attachments,
390        folder: &request.folder,
391        main_checkout_root: None,
392        replay_transcript: None,
393        model: request.model.provider_model_str(),
394        permission_mode: request.permission_mode,
395        personality_prompt: None,
396        prompt,
397        reasoning_level: request.reasoning_level,
398        request_kind: &request.request_kind,
399        speed_mode: request.speed_mode,
400    };
401    let observer = OneShotCliObserver {
402        child_pid: request.child_pid,
403    };
404    let output =
405        execution::execute_cli_command(backend, request.agent_kind, build_request, &observer, None)
406            .await
407            .map_err(format_one_shot_execution_error)?;
408
409    match output.exit_status {
410        CliExitStatus::Signaled(_) => {
411            return Err("One-shot agent command was interrupted".to_string());
412        }
413        CliExitStatus::NonZero(exit_code) => {
414            return Err(format_one_shot_exit_error(
415                request.agent_kind,
416                exit_code,
417                &output.stdout,
418                &output.stderr,
419            ));
420        }
421        CliExitStatus::Success => {}
422    }
423
424    let parsed_response = parse_response(request.agent_kind, &output.stdout, &output.stderr);
425
426    Ok(parsed_response)
427}
428
429/// Preserves the established one-shot context around shared execution errors.
430fn format_one_shot_execution_error(error: CliExecutionError) -> String {
431    match error {
432        CliExecutionError::CommandBuild(error) => {
433            format!("Failed to build one-shot agent command: {error}")
434        }
435        CliExecutionError::StdinBuild(error) => {
436            format!("Failed to build one-shot agent stdin payload: {error}")
437        }
438        error => format!("Failed to execute one-shot agent command: {error}"),
439    }
440}
441
442/// Formats one non-zero one-shot command exit into a user-facing error.
443fn format_one_shot_exit_error(
444    agent_kind: AgentKind,
445    exit_code: Option<i32>,
446    stdout: &str,
447    stderr: &str,
448) -> String {
449    error::format_agent_cli_exit_error(
450        agent_kind,
451        "One-shot agent command",
452        exit_code,
453        stdout,
454        stderr,
455    )
456}
457
458/// Clears the shared one-shot child PID slot when one exists.
459fn clear_child_pid_slot(child_pid: Option<&Mutex<Option<u32>>>) {
460    let Some(child_pid) = child_pid else {
461        return;
462    };
463
464    if let Ok(mut guard) = child_pid.lock() {
465        *guard = None;
466    }
467}
468
469/// Bridges shared CLI PID observations into the one-shot cancellation slot.
470struct OneShotCliObserver {
471    child_pid: Option<Arc<Mutex<Option<u32>>>>,
472}
473
474impl CliExecutionObserver for OneShotCliObserver {
475    fn pid_updated(&self, active_child_pid: Option<u32>) {
476        let Some(child_pid_slot) = self.child_pid.as_deref() else {
477            return;
478        };
479
480        if let Ok(mut guard) = child_pid_slot.lock() {
481            *guard = active_child_pid;
482        }
483    }
484
485    fn stdout_line(&self, _line: &str) {}
486}
487
488#[cfg(test)]
489mod tests {
490    use std::path::Path;
491    use std::process::Command;
492    use std::time::Duration;
493
494    use tempfile::tempdir;
495
496    use super::*;
497    use crate::MockAgentBackend;
498    use crate::app_server::{AppServerError, AppServerTurnResponse, MockAppServerClient};
499
500    /// Builds one shell command that emits controlled stdout/stderr and exits.
501    fn mock_shell_command(stdout: &str, stderr: &str, exit_code: i32) -> Command {
502        let mut command = Command::new("sh");
503        command.arg("-c").arg(
504            "printf '%s' \"$ONE_SHOT_STDOUT\"; printf '%s' \"$ONE_SHOT_STDERR\" >&2; exit \
505             \"$ONE_SHOT_EXIT\"",
506        );
507        command.env("ONE_SHOT_STDOUT", stdout);
508        command.env("ONE_SHOT_STDERR", stderr);
509        command.env("ONE_SHOT_EXIT", exit_code.to_string());
510        command.stdout(std::process::Stdio::piped());
511        command.stderr(std::process::Stdio::piped());
512
513        command
514    }
515
516    /// Builds one shell command that captures stdin before returning JSON.
517    fn stdin_capture_shell_command(capture_path: &Path) -> Command {
518        let mut command = Command::new("sh");
519        command.arg("-c").arg(
520            "cat > \"$ONE_SHOT_CAPTURE_PATH\"; printf '%s' \
521             '{\"answer\":\"captured\",\"questions\":[]}'",
522        );
523        command.env("ONE_SHOT_CAPTURE_PATH", capture_path);
524        command.stdout(std::process::Stdio::piped());
525        command.stderr(std::process::Stdio::piped());
526
527        command
528    }
529
530    #[test]
531    fn test_format_one_shot_execution_error_preserves_build_context() {
532        // Arrange
533        let command_error = CliExecutionError::CommandBuild(
534            crate::agent::AgentBackendError::CommandBuild("command".to_string()),
535        );
536        let stdin_error = CliExecutionError::StdinBuild(
537            crate::agent::AgentBackendError::CommandBuild("stdin".to_string()),
538        );
539        let execution_error = CliExecutionError::StdinWrite("write".to_string());
540
541        // Act
542        let command_message = format_one_shot_execution_error(command_error);
543        let stdin_message = format_one_shot_execution_error(stdin_error);
544        let execution_message = format_one_shot_execution_error(execution_error);
545
546        // Assert
547        assert_eq!(
548            command_message,
549            "Failed to build one-shot agent command: command"
550        );
551        assert_eq!(
552            stdin_message,
553            "Failed to build one-shot agent stdin payload: stdin"
554        );
555        assert_eq!(
556            execution_message,
557            "Failed to execute one-shot agent command: stdin delivery failed: write"
558        );
559    }
560
561    #[test]
562    fn test_one_shot_cli_observer_updates_child_pid_slot() {
563        // Arrange
564        let child_pid = Arc::new(Mutex::new(None));
565        let observer = OneShotCliObserver {
566            child_pid: Some(Arc::clone(&child_pid)),
567        };
568
569        // Act
570        observer.pid_updated(Some(42));
571        let active_pid = *child_pid.lock().expect("PID lock should be available");
572        observer.stdout_line("collected output");
573        observer.pid_updated(None);
574        let cleared_pid = *child_pid.lock().expect("PID lock should be available");
575
576        // Assert
577        assert_eq!(active_pid, Some(42));
578        assert_eq!(cleared_pid, None);
579    }
580
581    #[tokio::test]
582    async fn oversized_one_shot_responses_do_not_launch_repair() {
583        // Arrange
584        let folder = tempdir().expect("workspace");
585        let oversized = "x".repeat(128 * 1024 + 1);
586        let response_path = folder.path().join("response.txt");
587        std::fs::write(&response_path, &oversized).expect("response fixture");
588        let mut backend = MockAgentBackend::new();
589        backend.expect_build_command().times(1).returning(move |_| {
590            let mut command = Command::new("cat");
591            command.arg(&response_path);
592
593            Ok(command)
594        });
595        let client = MockAppServerClient::new();
596        let request = OneShotRequest {
597            agent_kind: AgentKind::Claude,
598            child_pid: None,
599            folder: folder.path().to_owned(),
600            model: AgentModel::ClaudeSonnet5,
601            permission_mode: PermissionMode::AutoEdit,
602            prompt: "Generate title".into(),
603            request_kind: AgentRequestKind::UtilityPrompt,
604            reasoning_level: ReasoningLevel::default(),
605            speed_mode: SpeedMode::Normal,
606        };
607
608        // Act
609        let cli_error = submit_one_shot_with_backend(&backend, request.clone())
610            .await
611            .expect_err("oversized CLI response");
612        let native_error = attempt_one_shot_app_server_repair(
613            &client,
614            "bad JSON",
615            &oversized,
616            request,
617            "repair-limit",
618            None,
619        )
620        .await
621        .expect_err("oversized native response");
622
623        // Assert
624        assert!(cli_error.contains("lossless repair limit"));
625        assert!(native_error.contains("lossless repair limit"));
626    }
627
628    #[tokio::test]
629    async fn test_submit_one_shot_with_backend_reports_signal_interruption() {
630        // Arrange
631        let temp_directory = tempdir().expect("failed to create temp dir");
632        let mut backend = MockAgentBackend::new();
633        backend.expect_build_command().returning(|_| {
634            let mut command = Command::new("sh");
635            command.arg("-c").arg("kill -9 $$");
636
637            Ok(command)
638        });
639
640        // Act
641        let error = submit_one_shot_with_backend(
642            &backend,
643            OneShotRequest {
644                agent_kind: AgentKind::Codex,
645                child_pid: None,
646                folder: temp_directory.path().to_path_buf(),
647                model: AgentModel::Gpt56Sol,
648                permission_mode: PermissionMode::AutoEdit,
649                prompt: "Generate title".to_string(),
650                request_kind: AgentRequestKind::UtilityPrompt,
651                reasoning_level: ReasoningLevel::default(),
652                speed_mode: SpeedMode::Normal,
653            },
654        )
655        .await
656        .expect_err("signal termination should interrupt the one-shot command");
657
658        // Assert
659        assert_eq!(error, "One-shot agent command was interrupted");
660    }
661
662    #[tokio::test]
663    /// Verifies one-shot execution returns the parsed structured answer.
664    async fn test_submit_one_shot_with_backend_returns_protocol_response() {
665        // Arrange
666        let temp_directory = tempdir().expect("failed to create temp dir");
667        let mut backend = MockAgentBackend::new();
668        backend.expect_build_command().returning(|request| {
669            assert!(matches!(
670                request.request_kind,
671                AgentRequestKind::UtilityPrompt
672            ));
673            assert_eq!(request.permission_mode, PermissionMode::ReadOnly);
674            assert_eq!(request.prompt, "Generate title");
675
676            Ok(mock_shell_command(
677                r#"{"answer":"Generated title","questions":[]}"#,
678                "",
679                0,
680            ))
681        });
682
683        // Act
684        let response = submit_one_shot_with_backend(
685            &backend,
686            OneShotRequest {
687                agent_kind: AgentKind::Claude,
688                child_pid: None,
689                folder: temp_directory.path().to_path_buf(),
690                model: AgentModel::ClaudeSonnet5,
691                permission_mode: PermissionMode::ReadOnly,
692                prompt: "Generate title".to_string(),
693                request_kind: AgentRequestKind::UtilityPrompt,
694                reasoning_level: ReasoningLevel::default(),
695                speed_mode: SpeedMode::Normal,
696            },
697        )
698        .await
699        .expect("one-shot prompt should succeed");
700
701        // Assert
702        assert_eq!(
703            response.response.answers(),
704            vec!["Generated title".to_string()]
705        );
706    }
707
708    #[tokio::test]
709    /// Verifies one-shot execution rejects plain-text utility output after
710    /// both the original parse and the protocol-repair retry fail.
711    async fn test_submit_one_shot_with_backend_rejects_plain_text_utility_output() {
712        // Arrange
713        let temp_directory = tempdir().expect("failed to create temp dir");
714        let mut backend = MockAgentBackend::new();
715        backend
716            .expect_build_command()
717            .times(2)
718            .returning(|request| {
719                assert!(matches!(
720                    request.request_kind,
721                    AgentRequestKind::UtilityPrompt
722                ));
723
724                Ok(mock_shell_command("plain text", "", 0))
725            });
726
727        // Act
728        let error = submit_one_shot_with_backend(
729            &backend,
730            OneShotRequest {
731                agent_kind: AgentKind::Codex,
732                child_pid: None,
733                folder: temp_directory.path().to_path_buf(),
734                model: AgentModel::Gpt56Sol,
735                permission_mode: PermissionMode::AutoEdit,
736                prompt: "Generate title".to_string(),
737                request_kind: AgentRequestKind::UtilityPrompt,
738                reasoning_level: ReasoningLevel::default(),
739                speed_mode: SpeedMode::Normal,
740            },
741        )
742        .await
743        .expect_err("plain-text utility output should fail");
744
745        // Assert
746        assert!(error.contains("did not match the required JSON schema"));
747        assert!(error.contains("debug_details:"));
748        assert!(error.contains("direct_json_error_location: line 1, column 1"));
749        assert!(error.contains("response:\nplain text"));
750    }
751
752    #[tokio::test]
753    /// Verifies one-shot execution rejects wrapped non-schema utility output
754    /// after both the original parse and the protocol-repair retry fail.
755    async fn test_submit_one_shot_with_backend_rejects_wrapped_plain_text_utility_output() {
756        // Arrange
757        let temp_directory = tempdir().expect("failed to create temp dir");
758        let mut backend = MockAgentBackend::new();
759        backend
760            .expect_build_command()
761            .times(2)
762            .returning(|request| {
763                assert!(matches!(
764                    request.request_kind,
765                    AgentRequestKind::UtilityPrompt
766                ));
767
768                Ok(mock_shell_command(
769                    r#"{"result":"plain text","usage":{"input_tokens":2,"output_tokens":1}}"#,
770                    "",
771                    0,
772                ))
773            });
774
775        // Act
776        let error = submit_one_shot_with_backend(
777            &backend,
778            OneShotRequest {
779                agent_kind: AgentKind::Claude,
780                child_pid: None,
781                folder: temp_directory.path().to_path_buf(),
782                model: AgentModel::ClaudeSonnet5,
783                permission_mode: PermissionMode::AutoEdit,
784                prompt: "Generate title".to_string(),
785                request_kind: AgentRequestKind::UtilityPrompt,
786                reasoning_level: ReasoningLevel::default(),
787                speed_mode: SpeedMode::Normal,
788            },
789        )
790        .await
791        .expect_err("wrapped plain-text utility output should fail");
792
793        // Assert — the provider parser extracts "plain text" from the
794        // `result` wrapper, so the protocol parser sees raw text, not JSON
795        // keys.
796        assert!(error.contains("did not match the required JSON schema"));
797        assert!(error.contains("direct_json_error:"));
798        assert!(error.contains("response:\nplain text"));
799    }
800
801    #[tokio::test]
802    /// Verifies one-shot execution recovers a trailing protocol payload when
803    /// the provider prepends extra prose before the final JSON object.
804    async fn test_submit_one_shot_with_backend_recovers_wrapped_protocol_output() {
805        // Arrange
806        let temp_directory = tempdir().expect("failed to create temp dir");
807        let mut backend = MockAgentBackend::new();
808        backend
809            .expect_build_command()
810            .times(1)
811            .returning(|request| {
812                assert!(matches!(
813                    request.request_kind,
814                    AgentRequestKind::UtilityPrompt
815                ));
816                assert_eq!(request.prompt, "Generate title");
817
818                Ok(mock_shell_command(
819                    concat!(
820                        "Now I have full context.\n",
821                        r#"{"answer":"Generated title","questions":[]}"#
822                    ),
823                    "",
824                    0,
825                ))
826            });
827
828        // Act
829        let response = submit_one_shot_with_backend(
830            &backend,
831            OneShotRequest {
832                agent_kind: AgentKind::Claude,
833                child_pid: None,
834                folder: temp_directory.path().to_path_buf(),
835                model: AgentModel::ClaudeSonnet5,
836                permission_mode: PermissionMode::AutoEdit,
837                prompt: "Generate title".to_string(),
838                request_kind: AgentRequestKind::UtilityPrompt,
839                reasoning_level: ReasoningLevel::default(),
840                speed_mode: SpeedMode::Normal,
841            },
842        )
843        .await
844        .expect("wrapped protocol output should succeed");
845
846        // Assert
847        assert_eq!(
848            response.response.answers(),
849            vec!["Generated title".to_string()]
850        );
851    }
852
853    #[tokio::test]
854    /// Verifies one-shot execution recovers valid output when the initial
855    /// parse fails but the protocol-repair retry returns valid protocol JSON.
856    async fn test_submit_one_shot_with_backend_recovers_via_protocol_repair() {
857        // Arrange
858        let temp_directory = tempdir().expect("failed to create temp dir");
859        let call_counter = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
860        let mut backend = MockAgentBackend::new();
861        backend.expect_build_command().times(2).returning({
862            let counter = std::sync::Arc::clone(&call_counter);
863
864            move |request| {
865                assert_eq!(request.speed_mode, SpeedMode::Fast);
866                let call_number = counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
867
868                if call_number == 0 {
869                    Ok(mock_shell_command("plain text", "", 0))
870                } else {
871                    Ok(mock_shell_command(
872                        r#"{"answer":"Repaired title","questions":[]}"#,
873                        "",
874                        0,
875                    ))
876                }
877            }
878        });
879
880        // Act
881        let response = submit_one_shot_with_backend(
882            &backend,
883            OneShotRequest {
884                agent_kind: AgentKind::Codex,
885                child_pid: None,
886                folder: temp_directory.path().to_path_buf(),
887                model: AgentModel::Gpt56Sol,
888                permission_mode: PermissionMode::AutoEdit,
889                prompt: "Generate title".to_string(),
890                request_kind: AgentRequestKind::UtilityPrompt,
891                reasoning_level: ReasoningLevel::default(),
892                speed_mode: SpeedMode::Fast,
893            },
894        )
895        .await
896        .expect("repair retry should succeed");
897
898        // Assert
899        assert_eq!(
900            response.response.answers(),
901            vec!["Repaired title".to_string()]
902        );
903    }
904
905    #[tokio::test]
906    async fn focused_review_repairs_trailing_text_with_direct_review_schema() {
907        // Arrange
908        let temp_directory = tempdir().expect("failed to create temp dir");
909        let call_counter = Arc::new(std::sync::atomic::AtomicUsize::new(0));
910        let mut backend = MockAgentBackend::new();
911        backend.expect_build_command().times(2).returning({
912            let counter = Arc::clone(&call_counter);
913
914            move |request| {
915                assert_eq!(request.request_kind, &AgentRequestKind::FocusedReview);
916                let call_number = counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
917
918                if call_number == 0 {
919                    return Ok(mock_shell_command(
920                        r#"{"project_impact":[],"suggestions":[]} trailing text"#,
921                        "",
922                        0,
923                    ));
924                }
925
926                assert!(request.prompt.contains("Complete malformed response:"));
927                let prompt = crate::agent::prompt::build_cli_prompt_text(
928                    request,
929                    ag_protocol::ProtocolSchemaInstructionMode::PromptSchema,
930                    "Gemini",
931                )
932                .expect("repair envelope");
933                assert!(prompt.contains("\"title\": \"FocusedReview\""));
934                assert_eq!(prompt.matches("Authoritative JSON Schema:").count(), 1);
935                assert!(!prompt.contains("\"answer\""));
936
937                Ok(mock_shell_command(
938                    r#"{"project_impact":["Review repaired."],"suggestions":[]}"#,
939                    "",
940                    0,
941                ))
942            }
943        });
944
945        // Act
946        let response = submit_one_shot_with_backend(
947            &backend,
948            OneShotRequest {
949                agent_kind: AgentKind::Claude,
950                child_pid: None,
951                folder: temp_directory.path().to_path_buf(),
952                model: AgentModel::ClaudeSonnet5,
953                permission_mode: PermissionMode::ReadOnly,
954                prompt: "Review the diff".to_string(),
955                request_kind: AgentRequestKind::FocusedReview,
956                reasoning_level: ReasoningLevel::default(),
957                speed_mode: SpeedMode::Normal,
958            },
959        )
960        .await
961        .expect("focused review repair should succeed");
962
963        // Assert
964        assert_eq!(
965            response.response.answer,
966            r#"{"project_impact":["Review repaired."],"suggestions":[]}"#
967        );
968    }
969
970    #[tokio::test]
971    /// Verifies one-shot execution still rejects blank utility responses
972    /// after both the original parse and the protocol-repair retry fail.
973    async fn test_submit_one_shot_with_backend_rejects_blank_utility_output() {
974        // Arrange
975        let temp_directory = tempdir().expect("failed to create temp dir");
976        let mut backend = MockAgentBackend::new();
977        backend.expect_build_command().returning(|request| {
978            assert!(matches!(
979                request.request_kind,
980                AgentRequestKind::UtilityPrompt
981            ));
982
983            Ok(mock_shell_command("   ", "", 0))
984        });
985
986        // Act
987        let error = submit_one_shot_with_backend(
988            &backend,
989            OneShotRequest {
990                agent_kind: AgentKind::Codex,
991                child_pid: None,
992                folder: temp_directory.path().to_path_buf(),
993                model: AgentModel::Gpt56Sol,
994                permission_mode: PermissionMode::AutoEdit,
995                prompt: "Generate title".to_string(),
996                request_kind: AgentRequestKind::UtilityPrompt,
997                reasoning_level: ReasoningLevel::default(),
998                speed_mode: SpeedMode::Normal,
999            },
1000        )
1001        .await
1002        .expect_err("blank utility output should fail");
1003
1004        // Assert
1005        assert!(error.contains("did not match the required JSON schema"));
1006        assert!(error.contains("trimmed_len: 0 chars"));
1007        assert!(error.contains("response:\n"));
1008    }
1009
1010    #[tokio::test]
1011    /// Verifies one-shot execution does not deadlock when the child delays
1012    /// reading stdin until after it emits early stderr output.
1013    async fn test_submit_one_shot_with_backend_writes_large_stdin_concurrently() {
1014        // Arrange
1015        let temp_directory = tempdir().expect("failed to create temp dir");
1016        let large_prompt = "x".repeat(512 * 1024);
1017        let mut backend = MockAgentBackend::new();
1018        backend.expect_build_command().returning(|_| {
1019            let mut command = Command::new("sh");
1020            command.arg("-c").arg(
1021                "printf 'warming up\\n' >&2; sleep 0.1; cat >/dev/null; printf '%s' \
1022                 '{\"answer\":\"done\",\"questions\":[]}'",
1023            );
1024            command.stdout(std::process::Stdio::piped());
1025            command.stderr(std::process::Stdio::piped());
1026
1027            Ok(command)
1028        });
1029
1030        // Act
1031        let response = tokio::time::timeout(
1032            Duration::from_secs(5),
1033            submit_one_shot_with_backend(
1034                &backend,
1035                OneShotRequest {
1036                    agent_kind: AgentKind::Claude,
1037                    child_pid: None,
1038                    folder: temp_directory.path().to_path_buf(),
1039                    model: AgentModel::ClaudeSonnet5,
1040                    permission_mode: PermissionMode::AutoEdit,
1041                    prompt: large_prompt.clone(),
1042                    request_kind: AgentRequestKind::UtilityPrompt,
1043                    reasoning_level: ReasoningLevel::default(),
1044                    speed_mode: SpeedMode::Normal,
1045                },
1046            ),
1047        )
1048        .await
1049        .expect("one-shot prompt should not deadlock")
1050        .expect("one-shot prompt should succeed");
1051
1052        // Assert
1053        assert_eq!(response.response.answers(), vec!["done".to_string()]);
1054    }
1055
1056    #[tokio::test]
1057    /// Verifies one-shot execution streams Claude prompts through stdin so
1058    /// large review requests avoid argv length limits.
1059    async fn test_submit_one_shot_with_backend_writes_prompt_to_stdin() {
1060        // Arrange
1061        let temp_directory = tempdir().expect("failed to create temp dir");
1062        let capture_path = temp_directory.path().join("stdin.txt");
1063        let mut backend = MockAgentBackend::new();
1064        backend.expect_build_command().returning({
1065            let capture_path = capture_path.clone();
1066
1067            move |_| Ok(stdin_capture_shell_command(&capture_path))
1068        });
1069
1070        // Act
1071        let response = submit_one_shot_with_backend(
1072            &backend,
1073            OneShotRequest {
1074                agent_kind: AgentKind::Claude,
1075                child_pid: None,
1076                folder: temp_directory.path().to_path_buf(),
1077                model: AgentModel::ClaudeSonnet5,
1078                permission_mode: PermissionMode::AutoEdit,
1079                prompt: "Generate title".to_string(),
1080                request_kind: AgentRequestKind::UtilityPrompt,
1081                reasoning_level: ReasoningLevel::default(),
1082                speed_mode: SpeedMode::Normal,
1083            },
1084        )
1085        .await
1086        .expect("one-shot prompt should succeed");
1087        let captured_prompt =
1088            std::fs::read_to_string(&capture_path).expect("captured stdin payload should exist");
1089
1090        // Assert
1091        assert_eq!(response.response.answers(), vec!["captured".to_string()]);
1092        assert!(captured_prompt.contains("Structured response protocol:"));
1093        assert!(captured_prompt.contains("Generate title"));
1094    }
1095
1096    #[tokio::test]
1097    /// Verifies a broken stdin pipe does not hide the child exit status or
1098    /// stderr when the backend exits before reading the full prompt.
1099    async fn test_submit_one_shot_with_backend_preserves_exit_error_after_broken_pipe() {
1100        // Arrange
1101        let temp_directory = tempdir().expect("failed to create temp dir");
1102        let large_prompt = "x".repeat(512 * 1024);
1103        let mut backend = MockAgentBackend::new();
1104        backend.expect_build_command().returning(|_| {
1105            let mut command = Command::new("sh");
1106            command.arg("-c").arg("printf 'auth failed' >&2; exit 7");
1107            command.stdout(std::process::Stdio::piped());
1108            command.stderr(std::process::Stdio::piped());
1109
1110            Ok(command)
1111        });
1112
1113        // Act
1114        let error = submit_one_shot_with_backend(
1115            &backend,
1116            OneShotRequest {
1117                agent_kind: AgentKind::Claude,
1118                child_pid: None,
1119                folder: temp_directory.path().to_path_buf(),
1120                model: AgentModel::ClaudeSonnet5,
1121                permission_mode: PermissionMode::AutoEdit,
1122                prompt: large_prompt,
1123                request_kind: AgentRequestKind::UtilityPrompt,
1124                reasoning_level: ReasoningLevel::default(),
1125                speed_mode: SpeedMode::Normal,
1126            },
1127        )
1128        .await
1129        .expect_err("one-shot prompt should surface the child exit");
1130
1131        // Assert
1132        assert!(error.contains("exit code 7"), "error was: {error}");
1133        assert!(error.contains("auth failed"), "error was: {error}");
1134        assert!(
1135            !error.contains("stdin payload"),
1136            "stdin write error should not mask child failure: {error}"
1137        );
1138    }
1139
1140    #[tokio::test]
1141    /// Verifies Claude authentication failures return actionable re-login
1142    /// guidance instead of raw transport output.
1143    async fn test_submit_one_shot_with_backend_surfaces_claude_auth_guidance() {
1144        // Arrange
1145        let temp_directory = tempdir().expect("failed to create temp dir");
1146        let mut backend = MockAgentBackend::new();
1147        backend.expect_build_command().returning(|_| {
1148            Ok(mock_shell_command(
1149                r#"{"type":"error","error":{"type":"authentication_error","message":"OAuth token has expired. Please obtain a new token or refresh your existing token."}}"#,
1150                "",
1151                1,
1152            ))
1153        });
1154
1155        // Act
1156        let error = submit_one_shot_with_backend(
1157            &backend,
1158            OneShotRequest {
1159                agent_kind: AgentKind::Claude,
1160                child_pid: None,
1161                folder: temp_directory.path().to_path_buf(),
1162                model: AgentModel::ClaudeSonnet5,
1163                permission_mode: PermissionMode::AutoEdit,
1164                prompt: "Generate title".to_string(),
1165                request_kind: AgentRequestKind::UtilityPrompt,
1166                reasoning_level: ReasoningLevel::default(),
1167                speed_mode: SpeedMode::Normal,
1168            },
1169        )
1170        .await
1171        .expect_err("expired Claude auth should fail");
1172
1173        // Assert
1174        assert!(
1175            error.contains("One-shot agent command failed because Claude authentication expired")
1176        );
1177        assert!(error.contains("`claude auth login`"));
1178        assert!(error.contains("`claude auth status`"));
1179    }
1180
1181    #[tokio::test]
1182    /// Verifies app-server-backed one-shot execution returns the parsed
1183    /// structured answer and usage totals.
1184    async fn test_submit_one_shot_with_app_server_client_returns_protocol_response() {
1185        // Arrange
1186        let temp_directory = tempdir().expect("failed to create temp dir");
1187        let mut app_server_client = MockAppServerClient::new();
1188        app_server_client
1189            .expect_run_turn()
1190            .times(1)
1191            .returning(|request, _| {
1192                assert_eq!(request.model, AgentModel::Gpt56Sol.as_str());
1193                assert!(matches!(
1194                    request.request_kind,
1195                    AgentRequestKind::UtilityPrompt
1196                ));
1197                assert_eq!(request.permission_mode, PermissionMode::ReadOnly);
1198                assert_eq!(request.prompt.text, "Generate title");
1199                assert_eq!(request.speed_mode, SpeedMode::Fast);
1200
1201                Box::pin(async {
1202                    Ok(AppServerTurnResponse {
1203                        assistant_message: r#"{"answer":"Generated title","questions":[]}"#
1204                            .to_string(),
1205                        context_reset: false,
1206                        input_tokens: 11,
1207                        output_tokens: 7,
1208                        pid: Some(42),
1209                        provider_conversation_id: Some("thread-1".to_string()),
1210                    })
1211                })
1212            });
1213        app_server_client
1214            .expect_shutdown_session()
1215            .times(1)
1216            .returning(|_| Box::pin(async {}));
1217
1218        // Act
1219        let response = submit_one_shot_with_app_server_client(
1220            &app_server_client,
1221            OneShotRequest {
1222                agent_kind: AgentKind::Codex,
1223                child_pid: None,
1224                folder: temp_directory.path().to_path_buf(),
1225                model: AgentModel::Gpt56Sol,
1226                permission_mode: PermissionMode::ReadOnly,
1227                prompt: "Generate title".to_string(),
1228                request_kind: AgentRequestKind::UtilityPrompt,
1229                reasoning_level: ReasoningLevel::default(),
1230                speed_mode: SpeedMode::Fast,
1231            },
1232        )
1233        .await
1234        .expect("one-shot prompt should succeed");
1235
1236        // Assert
1237        assert_eq!(
1238            response.response.answers(),
1239            vec!["Generated title".to_string()]
1240        );
1241        assert_eq!(response.stats.input_tokens, 11);
1242        assert_eq!(response.stats.output_tokens, 7);
1243    }
1244
1245    #[tokio::test]
1246    /// Verifies app-server turn failures shut down the temporary session and
1247    /// clear the caller's shared child-process slot.
1248    async fn test_submit_one_shot_with_app_server_client_clears_pid_after_turn_failure() {
1249        // Arrange
1250        let temp_directory = tempdir().expect("failed to create temp dir");
1251        let child_pid = Arc::new(Mutex::new(Some(42)));
1252        let mut app_server_client = MockAppServerClient::new();
1253        app_server_client
1254            .expect_run_turn()
1255            .times(1)
1256            .returning(|_, _| {
1257                Box::pin(async {
1258                    Err(AppServerError::Provider(
1259                        "app-server turn failed".to_string(),
1260                    ))
1261                })
1262            });
1263        app_server_client
1264            .expect_shutdown_session()
1265            .times(1)
1266            .returning(|_| Box::pin(async {}));
1267
1268        // Act
1269        let error = submit_one_shot_with_app_server_client(
1270            &app_server_client,
1271            OneShotRequest {
1272                agent_kind: AgentKind::Codex,
1273                child_pid: Some(Arc::clone(&child_pid)),
1274                folder: temp_directory.path().to_path_buf(),
1275                model: AgentModel::Gpt56Sol,
1276                permission_mode: PermissionMode::AutoEdit,
1277                prompt: "Generate title".to_string(),
1278                request_kind: AgentRequestKind::UtilityPrompt,
1279                reasoning_level: ReasoningLevel::default(),
1280                speed_mode: SpeedMode::Normal,
1281            },
1282        )
1283        .await
1284        .expect_err("app-server turn failure should surface");
1285
1286        // Assert
1287        assert!(error.contains("app-server turn failed"));
1288        assert_eq!(
1289            *child_pid.lock().expect("child pid lock should succeed"),
1290            None
1291        );
1292    }
1293
1294    #[tokio::test]
1295    async fn one_shot_app_server_repair_preserves_permissions_and_conversation() {
1296        for permission_mode in PermissionMode::ALL {
1297            // Arrange
1298            let folder = tempdir().expect("workspace");
1299            let mut client = MockAppServerClient::new();
1300            client
1301                .expect_run_turn()
1302                .times(1)
1303                .returning(move |request, _| {
1304                    assert_eq!(request.permission_mode, permission_mode);
1305                    assert_eq!(request.session_id, "one-shot-session");
1306                    assert_eq!(
1307                        request.provider_conversation_id.as_deref(),
1308                        Some("native-session")
1309                    );
1310
1311                    Box::pin(async {
1312                        Ok(AppServerTurnResponse {
1313                            assistant_message: r#"{"answer":"Repaired","questions":[]}"#.into(),
1314                            context_reset: false,
1315                            input_tokens: 2,
1316                            output_tokens: 1,
1317                            pid: None,
1318                            provider_conversation_id: Some("native-session".into()),
1319                        })
1320                    })
1321                });
1322            let request = OneShotRequest {
1323                agent_kind: AgentKind::Gemini,
1324                child_pid: None,
1325                folder: folder.path().to_owned(),
1326                model: AgentModel::Gemini31Pro,
1327                permission_mode,
1328                prompt: "Generate title".into(),
1329                request_kind: AgentRequestKind::UtilityPrompt,
1330                reasoning_level: ReasoningLevel::default(),
1331                speed_mode: SpeedMode::Normal,
1332            };
1333
1334            // Act
1335            let (response, input_tokens, output_tokens) = attempt_one_shot_app_server_repair(
1336                &client,
1337                "invalid JSON",
1338                "malformed",
1339                request,
1340                "one-shot-session",
1341                Some("native-session"),
1342            )
1343            .await
1344            .expect("repair succeeds");
1345
1346            // Assert
1347            assert_eq!(response.to_display_text(), "Repaired");
1348            assert_eq!((input_tokens, output_tokens), (2, 1));
1349        }
1350    }
1351
1352    #[tokio::test]
1353    /// Verifies app-server-backed one-shot execution rejects plain-text
1354    /// utility output after both the original parse and the protocol-repair
1355    /// retry fail.
1356    async fn test_submit_one_shot_with_app_server_client_rejects_plain_text_utility_output() {
1357        // Arrange
1358        let temp_directory = tempdir().expect("failed to create temp dir");
1359        let mut app_server_client = MockAppServerClient::new();
1360        app_server_client
1361            .expect_run_turn()
1362            .times(2)
1363            .returning(|request, _| {
1364                assert_eq!(request.model, AgentModel::Gpt56Sol.as_str());
1365                assert_eq!(request.permission_mode, PermissionMode::ReadOnly);
1366                assert_eq!(request.speed_mode, SpeedMode::Fast);
1367
1368                Box::pin(async {
1369                    Ok(AppServerTurnResponse {
1370                        assistant_message: "plain text".to_string(),
1371                        context_reset: false,
1372                        input_tokens: 2,
1373                        output_tokens: 1,
1374                        pid: None,
1375                        provider_conversation_id: None,
1376                    })
1377                })
1378            });
1379        app_server_client
1380            .expect_shutdown_session()
1381            .times(1)
1382            .returning(|_| Box::pin(async {}));
1383
1384        // Act
1385        let error = submit_one_shot_with_app_server_client(
1386            &app_server_client,
1387            OneShotRequest {
1388                agent_kind: AgentKind::Codex,
1389                child_pid: None,
1390                folder: temp_directory.path().to_path_buf(),
1391                model: AgentModel::Gpt56Sol,
1392                permission_mode: PermissionMode::ReadOnly,
1393                prompt: "Generate title".to_string(),
1394                request_kind: AgentRequestKind::UtilityPrompt,
1395                reasoning_level: ReasoningLevel::default(),
1396                speed_mode: SpeedMode::Fast,
1397            },
1398        )
1399        .await
1400        .expect_err("plain-text utility output should fail");
1401
1402        // Assert
1403        assert!(error.contains("did not match the required JSON schema"));
1404        assert!(error.contains("debug_details:"));
1405        assert!(error.contains("response:\nplain text"));
1406    }
1407
1408    #[tokio::test]
1409    /// Verifies app-server-backed non-utility one-shot execution still
1410    /// rejects plain-text output after both the original parse and the
1411    /// protocol-repair retry fail.
1412    async fn test_submit_one_shot_with_app_server_client_rejects_plain_text_non_utility_output() {
1413        // Arrange
1414        let temp_directory = tempdir().expect("failed to create temp dir");
1415        let mut app_server_client = MockAppServerClient::new();
1416        app_server_client
1417            .expect_run_turn()
1418            .times(2)
1419            .returning(|request, _| {
1420                assert!(matches!(
1421                    request.request_kind,
1422                    AgentRequestKind::SessionStart
1423                ));
1424
1425                Box::pin(async {
1426                    Ok(AppServerTurnResponse {
1427                        assistant_message: "plain text".to_string(),
1428                        context_reset: false,
1429                        input_tokens: 2,
1430                        output_tokens: 1,
1431                        pid: None,
1432                        provider_conversation_id: None,
1433                    })
1434                })
1435            });
1436        app_server_client
1437            .expect_shutdown_session()
1438            .times(1)
1439            .returning(|_| Box::pin(async {}));
1440
1441        // Act
1442        let error = submit_one_shot_with_app_server_client(
1443            &app_server_client,
1444            OneShotRequest {
1445                agent_kind: AgentKind::Codex,
1446                child_pid: None,
1447                folder: temp_directory.path().to_path_buf(),
1448                model: AgentModel::Gpt56Sol,
1449                permission_mode: PermissionMode::AutoEdit,
1450                prompt: "Generate title".to_string(),
1451                request_kind: AgentRequestKind::SessionStart,
1452                reasoning_level: ReasoningLevel::default(),
1453                speed_mode: SpeedMode::Normal,
1454            },
1455        )
1456        .await
1457        .expect_err("invalid non-utility output should fail");
1458
1459        // Assert
1460        assert!(error.contains("did not match the required JSON schema"));
1461        assert!(error.contains("debug_details:"));
1462        assert!(error.contains("response:\nplain text"));
1463    }
1464}