Skip to main content

agentmux_srv_core/backend/blockcontroller/
app_server_protocol.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Codex App Server's stable thread/turn adapter.
5//!
6//! The transport in [`super::app_server`] owns framing and request lifecycle.
7//! This module owns the first protocol-semantic layer: typed request shapes,
8//! thread identity, turn identity, and notification reconciliation. It is
9//! intentionally not registered as a production block controller yet.
10
11use std::collections::{HashMap, VecDeque};
12use std::sync::{Arc, Mutex};
13use std::time::Duration;
14
15use super::app_server_input::{turn_input, UserInput};
16use serde::Serialize;
17use serde_json::{json, Value};
18use thiserror::Error;
19
20use super::app_server::{
21    AppServerError, AppServerIncoming, AppServerTransport, RpcId, ServerResponseError,
22    WriteOutcomeTracker,
23};
24
25const MAX_RAW_EVENTS: usize = 128;
26const MAX_PENDING_SERVER_REQUESTS: usize = 64;
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum SessionPhase {
30    Idle,
31    Running,
32    Completed,
33    /// The turn ended via `TurnStatus::interrupted` (user cancellation) —
34    /// deliberately distinct from `Failed`, which was collapsing an
35    /// expected cancellation with a genuine provider/execution failure
36    /// (ReAgent P1, PR #3210). Consumers care about the difference: a
37    /// cancelled turn isn't an error to surface the same way.
38    Interrupted,
39    Failed,
40}
41
42impl Default for SessionPhase {
43    fn default() -> Self {
44        Self::Idle
45    }
46}
47
48#[derive(Debug, Clone, PartialEq)]
49pub struct ItemSnapshot {
50    pub id: String,
51    pub kind: String,
52    /// Preview text accumulated from delta notifications. This is cleared
53    /// when the authoritative item completion is observed.
54    pub preview: String,
55    pub completed: bool,
56    pub authoritative: Option<Value>,
57}
58
59#[derive(Debug, Clone, PartialEq)]
60pub struct SessionSnapshot {
61    pub thread_id: Option<String>,
62    pub turn_id: Option<String>,
63    pub phase: SessionPhase,
64    pub items: HashMap<String, ItemSnapshot>,
65    pub raw_unknown_events: Vec<Value>,
66}
67
68#[derive(Debug, Clone, PartialEq)]
69pub enum CodexAppServerEvent {
70    ThreadStarted {
71        thread_id: String,
72    },
73    TurnStarted {
74        thread_id: String,
75        turn_id: String,
76    },
77    AgentMessageDelta {
78        thread_id: String,
79        turn_id: String,
80        item_id: String,
81        delta: String,
82        preview: String,
83    },
84    ItemStarted {
85        thread_id: String,
86        turn_id: String,
87        item_id: String,
88        kind: String,
89    },
90    ItemCompleted {
91        thread_id: String,
92        turn_id: String,
93        item_id: String,
94        kind: String,
95        item: Value,
96    },
97    TurnCompleted {
98        thread_id: String,
99        turn_id: String,
100        status: String,
101    },
102    ThreadStatusChanged {
103        thread_id: String,
104        status: Value,
105    },
106    ServerRequestResolved {
107        thread_id: String,
108        request_id: RpcId,
109    },
110    AccountLoginCompleted {
111        login_id: Option<String>,
112        success: bool,
113        error: Option<String>,
114    },
115    UnknownNotification {
116        method: String,
117        params: Value,
118    },
119}
120
121#[derive(Debug, Clone, Copy, PartialEq, Eq)]
122pub enum ServerRequestKind {
123    CommandApproval,
124    FileChangeApproval,
125    PermissionsApproval,
126    UserInput,
127    McpElicitation,
128}
129
130#[derive(Debug, Clone, PartialEq)]
131pub struct PendingServerRequest {
132    pub id: RpcId,
133    pub kind: ServerRequestKind,
134    pub method: String,
135    pub params: Value,
136    pub thread_id: Option<String>,
137    pub turn_id: Option<String>,
138    pub item_id: Option<String>,
139}
140
141#[derive(Debug, Error, Clone, PartialEq)]
142pub enum CodexAppServerProtocolError {
143    #[error(transparent)]
144    Transport(#[from] AppServerError),
145    #[error("App Server response is missing a string field: {0}")]
146    MissingStringField(&'static str),
147    #[error("App Server response is missing an object field: {0}")]
148    MissingObjectField(&'static str),
149    #[error("App Server response is missing a boolean field: {0}")]
150    MissingBoolField(&'static str),
151    #[error("App Server event belongs to thread {actual}, but active thread is {expected}")]
152    ThreadScopeMismatch { expected: String, actual: String },
153    #[error("App Server event belongs to turn {actual}, but active turn is {expected}")]
154    TurnScopeMismatch { expected: String, actual: String },
155    #[error("cannot start a turn before a thread is loaded")]
156    ThreadNotLoaded,
157    #[error("cannot steer or interrupt without an active turn")]
158    TurnNotActive,
159    #[error("cannot start a second turn while turn {0} is active")]
160    TurnAlreadyActive(String),
161    #[error("resume response did not identify the requested thread")]
162    ResumeMissingThread,
163    #[error("unsupported or unsafe App Server request method: {0}")]
164    UnsupportedServerRequest(String),
165    #[error("no pending App Server request matches id")]
166    UnknownServerRequest,
167    #[error("App Server request id is already pending")]
168    DuplicateServerRequest,
169    #[error("too many App Server requests are pending a decision (max {0})")]
170    TooManyPendingRequests(usize),
171}
172
173#[derive(Debug, Clone, Serialize, Default)]
174#[serde(rename_all = "camelCase")]
175pub struct ThreadStartOptions {
176    #[serde(skip_serializing_if = "Option::is_none")]
177    pub model: Option<String>,
178    #[serde(skip_serializing_if = "Option::is_none")]
179    pub cwd: Option<String>,
180    #[serde(skip_serializing_if = "Option::is_none")]
181    pub developer_instructions: Option<String>,
182}
183
184#[derive(Debug, Clone, Serialize)]
185#[serde(rename_all = "camelCase")]
186struct ThreadResumeParams {
187    thread_id: String,
188    #[serde(skip_serializing_if = "Option::is_none")]
189    model: Option<String>,
190    #[serde(skip_serializing_if = "Option::is_none")]
191    cwd: Option<String>,
192}
193
194#[derive(Debug, Clone, Serialize)]
195#[serde(rename_all = "camelCase")]
196struct TurnStartParams {
197    thread_id: String,
198    input: Vec<UserInput>,
199}
200
201#[derive(Debug, Clone, Serialize)]
202#[serde(rename_all = "camelCase")]
203pub struct ThreadForkOptions {
204    pub thread_id: String,
205    #[serde(skip_serializing_if = "Option::is_none")]
206    pub model: Option<String>,
207    #[serde(skip_serializing_if = "Option::is_none")]
208    pub cwd: Option<String>,
209    #[serde(skip_serializing_if = "Option::is_none")]
210    pub last_turn_id: Option<String>,
211    #[serde(skip_serializing_if = "Option::is_none")]
212    pub exclude_turns: Option<bool>,
213}
214
215/// A thread/list cwd filter: either a single path or a set of paths, per the
216/// pinned schema's `ThreadListCwdFilter` (`string | string[]`).
217#[derive(Debug, Clone, Serialize)]
218#[serde(untagged)]
219#[allow(dead_code)] // Unwired until SPEC_CODEX_APP_SERVER_FIRST_CLASS_PROVIDER_2026_09_12.md §15 Slice 6.
220pub enum ThreadListCwdFilter {
221    Single(String),
222    Many(Vec<String>),
223}
224
225#[derive(Debug, Clone, Serialize, Default)]
226#[serde(rename_all = "camelCase")]
227pub struct ThreadListOptions {
228    #[serde(skip_serializing_if = "Option::is_none")]
229    pub archived: Option<bool>,
230    #[serde(skip_serializing_if = "Option::is_none")]
231    pub cursor: Option<String>,
232    #[serde(skip_serializing_if = "Option::is_none")]
233    pub cwd: Option<ThreadListCwdFilter>,
234    #[serde(skip_serializing_if = "Option::is_none")]
235    pub limit: Option<u32>,
236    #[serde(skip_serializing_if = "Option::is_none")]
237    pub search_term: Option<String>,
238}
239
240/// Login choices accepted by the pinned App Server schema. API keys are kept
241/// in this typed request only and are never included in protocol events/logs.
242#[derive(Debug, Clone, Serialize)]
243#[serde(tag = "type", rename_all_fields = "camelCase")]
244#[allow(dead_code)] // Unwired until SPEC_CODEX_APP_SERVER_FIRST_CLASS_PROVIDER_2026_09_12.md §15 Slice 4.
245pub enum AccountLoginOptions {
246    #[serde(rename = "chatgptDeviceCode")]
247    ChatgptDeviceCode,
248    #[serde(rename = "chatgpt")]
249    Chatgpt {
250        #[serde(skip_serializing_if = "Option::is_none")]
251        app_brand: Option<String>,
252        #[serde(skip_serializing_if = "Option::is_none")]
253        codex_streamlined_login: Option<bool>,
254        #[serde(skip_serializing_if = "Option::is_none")]
255        use_hosted_login_success_page: Option<bool>,
256    },
257    #[serde(rename = "apiKey")]
258    ApiKey { api_key: String },
259}
260
261
262pub struct CodexAppServerSession {
263    transport: Arc<AppServerTransport>,
264    state: Mutex<SessionState>,
265}
266
267#[derive(Default)]
268struct SessionState {
269    thread_id: Option<String>,
270    turn_id: Option<String>,
271    phase: SessionPhase,
272    items: HashMap<String, ItemSnapshot>,
273    raw_unknown_events: VecDeque<Value>,
274    /// The most recently `turn/completed`-notified turn id. `start_turn`
275    /// checks this after its own `turn/start` response resolves — the
276    /// response and the completion notification arrive on independent
277    /// channels (the request/response oneshot vs. run_reader's
278    /// notification stream), so a `turn/completed` for the SAME turn can
279    /// be applied before `start_turn`'s continuation resumes. Without this
280    /// check, `start_turn`'s unconditional post-await write would resurrect
281    /// an already-terminal turn as `Running`, permanently stuck (muxreview
282    /// P1, PR #3210). One id is enough, not a growing set: only one turn is
283    /// ever active at a time, so at most one termination can be "pending
284    /// recognition" by a not-yet-resumed `start_turn` call.
285    last_terminated_turn_id: Option<String>,
286    /// Reserved atomically under the same lock as the `turn_id.is_some()`
287    /// check, before the `turn/start` request is even sent. Without this,
288    /// two concurrent `start_turn` calls both observe `turn_id == None`
289    /// and both release the lock before either gets a response/notification
290    /// back — nothing was reserved under the lock, so both send `turn/start`
291    /// (ReAgent P1, PR #3210). Cleared once the response (or an error)
292    /// resolves.
293    turn_starting: bool,
294    pending_requests: HashMap<RpcId, PendingServerRequest>,
295}
296
297impl CodexAppServerSession {
298    pub fn new(transport: Arc<AppServerTransport>) -> Self {
299        Self {
300            transport,
301            state: Mutex::new(SessionState {
302                phase: SessionPhase::Idle,
303                ..SessionState::default()
304            }),
305        }
306    }
307
308    pub async fn start_thread(
309        &self,
310        options: ThreadStartOptions,
311        timeout: Duration,
312    ) -> Result<String, CodexAppServerProtocolError> {
313        let params = serde_json::to_value(options)
314            .map_err(|error| AppServerError::Protocol(error.to_string()))?;
315        let result = self
316            .transport
317            .request("thread/start", params, timeout)
318            .await?;
319        let thread_id = extract_thread_id(&result)?;
320        let mut state = self.state.lock().unwrap();
321        state.thread_id = Some(thread_id.clone());
322        state.turn_id = None;
323        state.phase = SessionPhase::Idle;
324        state.items.clear();
325        // A pending approval queued under a prior thread/turn must not
326        // remain answerable once that context is gone (ReAgent P1, PR
327        // #3212) -- only turn/completed cleared this before.
328        state.pending_requests.clear();
329        Ok(thread_id)
330    }
331
332    pub async fn resume_thread(
333        &self,
334        thread_id: String,
335        model: Option<String>,
336        cwd: Option<String>,
337        timeout: Duration,
338    ) -> Result<String, CodexAppServerProtocolError> {
339        let requested_id = thread_id.clone();
340        let result = self
341            .transport
342            .request(
343                "thread/resume",
344                serde_json::to_value(ThreadResumeParams {
345                    thread_id,
346                    model,
347                    cwd,
348                })
349                .map_err(|error| AppServerError::Protocol(error.to_string()))?,
350                timeout,
351            )
352            .await?;
353        let resumed_id = extract_thread_id(&result)?;
354        if resumed_id != requested_id {
355            return Err(CodexAppServerProtocolError::ResumeMissingThread);
356        }
357        // The 0.154.0 contract can resume a thread that has a turn already
358        // `inProgress` (ThreadResumeResponse's `thread.turns`, populated on
359        // resume specifically) — unconditionally clearing turn_id/phase
360        // here silently dropped that live turn state instead of deriving
361        // it from what the response actually reports (ReAgent P1, PR #3210).
362        let in_progress_turn_id = extract_in_progress_turn_id(&result);
363        let mut state = self.state.lock().unwrap();
364        state.thread_id = Some(resumed_id.clone());
365        state.turn_id = in_progress_turn_id.clone();
366        state.phase = if in_progress_turn_id.is_some() {
367            SessionPhase::Running
368        } else {
369            SessionPhase::Idle
370        };
371        state.items.clear();
372        // Same as start_thread: a pending approval from a prior thread/turn
373        // must not survive into this one (ReAgent P1, PR #3212).
374        state.pending_requests.clear();
375        Ok(resumed_id)
376    }
377
378    pub async fn start_turn(
379        &self,
380        text: String,
381        images: Vec<String>,
382        timeout: Duration,
383    ) -> Result<String, CodexAppServerProtocolError> {
384        let thread_id = {
385            let mut state = self.state.lock().unwrap();
386            if let Some(turn_id) = &state.turn_id {
387                return Err(CodexAppServerProtocolError::TurnAlreadyActive(
388                    turn_id.clone(),
389                ));
390            }
391            if state.turn_starting {
392                // A different start_turn call already reserved the slot and
393                // hasn't gotten its response/error back yet — reject this
394                // one the same way an already-active turn would be
395                // rejected, rather than also sending a second turn/start.
396                return Err(CodexAppServerProtocolError::TurnAlreadyActive(
397                    "(turn start already in flight)".to_string(),
398                ));
399            }
400            let thread_id = state
401                .thread_id
402                .clone()
403                .ok_or(CodexAppServerProtocolError::ThreadNotLoaded)?;
404            // Reserved under the SAME lock as the checks above, before the
405            // request is even sent — this is what makes the check-then-act
406            // atomic. Without it, two concurrent callers could both observe
407            // turn_id == None and turn_starting == false before either
408            // released the lock, and both would send turn/start (muxreview
409            // P1, PR #3210).
410            state.turn_starting = true;
411            thread_id
412        };
413
414        // Scoped so the fallible network round-trip is entirely separate
415        // from the state updates before/after it.
416        let turn_id_result: Result<String, CodexAppServerProtocolError> = async {
417            let result = self
418                .transport
419                .request(
420                    "turn/start",
421                    serde_json::to_value(TurnStartParams {
422                        thread_id,
423                        input: turn_input(text, images),
424                    })
425                    .map_err(|error| AppServerError::Protocol(error.to_string()))?,
426                    timeout,
427                )
428                .await?;
429            let turn = result
430                .get("turn")
431                .and_then(Value::as_object)
432                .ok_or(CodexAppServerProtocolError::MissingObjectField("turn"))?;
433            string_field(turn.get("id"), "turn.id")
434        }
435        .await;
436
437        let mut state = self.state.lock().unwrap();
438        state.turn_starting = false;
439        let turn_id = turn_id_result?;
440        if state.last_terminated_turn_id.as_deref() == Some(turn_id.as_str()) {
441            // A `turn/completed` notification for THIS turn already landed
442            // (on the independent notification channel) while we were
443            // awaiting this same turn's `turn/start` response. The turn is
444            // already terminal — don't resurrect it as Running.
445            return Ok(turn_id);
446        }
447        state.turn_id = Some(turn_id.clone());
448        state.phase = SessionPhase::Running;
449        Ok(turn_id)
450    }
451
452    /// Fork the active thread without changing this session's thread identity.
453    /// The returned id is independent and must be persisted by the caller that
454    /// creates the new AgentMux pane.
455    #[allow(dead_code)] // Unwired until SPEC_CODEX_APP_SERVER_FIRST_CLASS_PROVIDER_2026_09_12.md §15 Slice 6.
456    pub async fn fork_thread(
457        &self,
458        options: ThreadForkOptions,
459        timeout: Duration,
460    ) -> Result<String, CodexAppServerProtocolError> {
461        let active_thread = self
462            .state
463            .lock()
464            .unwrap()
465            .thread_id
466            .clone()
467            .ok_or(CodexAppServerProtocolError::ThreadNotLoaded)?;
468        if options.thread_id != active_thread {
469            return Err(CodexAppServerProtocolError::ThreadScopeMismatch {
470                expected: active_thread,
471                actual: options.thread_id,
472            });
473        }
474        let result = self
475            .transport
476            .request(
477                "thread/fork",
478                serde_json::to_value(options)
479                    .map_err(|error| AppServerError::Protocol(error.to_string()))?,
480                timeout,
481            )
482            .await?;
483        extract_thread_id(&result)
484    }
485
486    #[allow(dead_code)] // Unwired until SPEC_CODEX_APP_SERVER_FIRST_CLASS_PROVIDER_2026_09_12.md §15 Slice 6.
487    pub async fn read_thread(
488        &self,
489        include_turns: bool,
490        timeout: Duration,
491    ) -> Result<Value, CodexAppServerProtocolError> {
492        let thread_id = self
493            .state
494            .lock()
495            .unwrap()
496            .thread_id
497            .clone()
498            .ok_or(CodexAppServerProtocolError::ThreadNotLoaded)?;
499        Ok(self
500            .transport
501            .request(
502                "thread/read",
503                json!({"threadId": thread_id, "includeTurns": include_turns}),
504                timeout,
505            )
506            .await?)
507    }
508
509    #[allow(dead_code)] // Unwired until SPEC_CODEX_APP_SERVER_FIRST_CLASS_PROVIDER_2026_09_12.md §15 Slice 6.
510    pub async fn list_threads(
511        &self,
512        options: ThreadListOptions,
513        timeout: Duration,
514    ) -> Result<Value, CodexAppServerProtocolError> {
515        Ok(self
516            .transport
517            .request(
518                "thread/list",
519                serde_json::to_value(options)
520                    .map_err(|error| AppServerError::Protocol(error.to_string()))?,
521                timeout,
522            )
523            .await?)
524    }
525
526    #[allow(dead_code)] // Unwired until SPEC_CODEX_APP_SERVER_FIRST_CLASS_PROVIDER_2026_09_12.md §15 Slice 6.
527    pub async fn archive_thread(
528        &self,
529        timeout: Duration,
530    ) -> Result<Value, CodexAppServerProtocolError> {
531        let thread_id = self
532            .state
533            .lock()
534            .unwrap()
535            .thread_id
536            .clone()
537            .ok_or(CodexAppServerProtocolError::ThreadNotLoaded)?;
538        Ok(self
539            .transport
540            .request("thread/archive", json!({"threadId": thread_id}), timeout)
541            .await?)
542    }
543
544    /// Used by a Codex `/compact` (`subprocess/codex_compact.rs`).
545    pub async fn compact_thread(
546        &self,
547        timeout: Duration,
548    ) -> Result<Value, CodexAppServerProtocolError> {
549        let thread_id = self
550            .state
551            .lock()
552            .unwrap()
553            .thread_id
554            .clone()
555            .ok_or(CodexAppServerProtocolError::ThreadNotLoaded)?;
556        Ok(self
557            .transport
558            .request(
559                "thread/compact/start",
560                json!({"threadId": thread_id}),
561                timeout,
562            )
563            .await?)
564    }
565
566    /// Verify the account selected by the caller's isolated CODEX_HOME.
567    #[allow(dead_code)] // Unwired until SPEC_CODEX_APP_SERVER_FIRST_CLASS_PROVIDER_2026_09_12.md §15 Slice 4.
568    pub async fn read_account(
569        &self,
570        refresh_token: bool,
571        timeout: Duration,
572    ) -> Result<Value, CodexAppServerProtocolError> {
573        Ok(self
574            .transport
575            .request(
576                "account/read",
577                json!({"refreshToken": refresh_token}),
578                timeout,
579            )
580            .await?)
581    }
582
583    #[allow(dead_code)] // Unwired until SPEC_CODEX_APP_SERVER_FIRST_CLASS_PROVIDER_2026_09_12.md §15 Slice 4.
584    pub async fn logout_account(
585        &self,
586        timeout: Duration,
587    ) -> Result<Value, CodexAppServerProtocolError> {
588        Ok(self
589            .transport
590            .request("account/logout", Value::Null, timeout)
591            .await?)
592    }
593
594    #[allow(dead_code)] // Unwired until SPEC_CODEX_APP_SERVER_FIRST_CLASS_PROVIDER_2026_09_12.md §15 Slice 4.
595    pub async fn login_account(
596        &self,
597        options: AccountLoginOptions,
598        timeout: Duration,
599    ) -> Result<Value, CodexAppServerProtocolError> {
600        Ok(self
601            .transport
602            .request(
603                "account/login/start",
604                serde_json::to_value(options)
605                    .map_err(|error| AppServerError::Protocol(error.to_string()))?,
606                timeout,
607            )
608            .await?)
609    }
610
611    #[allow(dead_code)] // Unwired until SPEC_CODEX_APP_SERVER_FIRST_CLASS_PROVIDER_2026_09_12.md §15 Slice 4.
612    pub async fn cancel_login(
613        &self,
614        login_id: String,
615        timeout: Duration,
616    ) -> Result<Value, CodexAppServerProtocolError> {
617        Ok(self
618            .transport
619            .request(
620                "account/login/cancel",
621                json!({"loginId": login_id}),
622                timeout,
623            )
624            .await?)
625    }
626
627    /// Add input to the active turn only when the caller supplies the exact
628    /// turn precondition. Ordinary queued messages should not call this API.
629    #[allow(dead_code)] // Unwired until SPEC_CODEX_APP_SERVER_FIRST_CLASS_PROVIDER_2026_09_12.md §15 Slice 3.
630    pub async fn steer_turn(
631        &self,
632        text: String,
633        expected_turn_id: String,
634        timeout: Duration,
635    ) -> Result<Value, CodexAppServerProtocolError> {
636        let (thread_id, active_turn_id) = self.active_turn()?;
637        if active_turn_id != expected_turn_id {
638            return Err(CodexAppServerProtocolError::TurnScopeMismatch {
639                expected: active_turn_id,
640                actual: expected_turn_id,
641            });
642        }
643        Ok(self
644            .transport
645            .request(
646                "turn/steer",
647                json!({
648                    "threadId": thread_id,
649                    "expectedTurnId": expected_turn_id,
650                    "input": [{"type": "text", "text": text}],
651                }),
652                timeout,
653            )
654            .await?)
655    }
656
657    /// Interrupt the active turn. The turn remains active locally until its
658    /// authoritative `turn/completed` notification arrives.
659    #[allow(dead_code)] // Unwired until SPEC_CODEX_APP_SERVER_FIRST_CLASS_PROVIDER_2026_09_12.md §15 Slice 3.
660    pub async fn interrupt_turn(
661        &self,
662        timeout: Duration,
663    ) -> Result<Value, CodexAppServerProtocolError> {
664        let (thread_id, turn_id) = self.active_turn()?;
665        Ok(self
666            .transport
667            .request(
668                "turn/interrupt",
669                json!({"threadId": thread_id, "turnId": turn_id}),
670                timeout,
671            )
672            .await?)
673    }
674
675    fn active_turn(&self) -> Result<(String, String), CodexAppServerProtocolError> {
676        let state = self.state.lock().unwrap();
677        let thread_id = state
678            .thread_id
679            .clone()
680            .ok_or(CodexAppServerProtocolError::ThreadNotLoaded)?;
681        let turn_id = state
682            .turn_id
683            .clone()
684            .ok_or(CodexAppServerProtocolError::TurnNotActive)?;
685        Ok((thread_id, turn_id))
686    }
687
688    /// Validate and queue a server request for an explicit UI/policy decision.
689    /// No request is approved implicitly.
690    pub fn accept_server_request(
691        &self,
692        incoming: AppServerIncoming,
693    ) -> Result<PendingServerRequest, CodexAppServerProtocolError> {
694        let AppServerIncoming::Request { id, method, params } = incoming else {
695            return Err(CodexAppServerProtocolError::UnsupportedServerRequest(
696                "notifications cannot be queued as requests".to_string(),
697            ));
698        };
699        let kind = match method.as_str() {
700            "item/commandExecution/requestApproval" => ServerRequestKind::CommandApproval,
701            "item/fileChange/requestApproval" => ServerRequestKind::FileChangeApproval,
702            "item/permissions/requestApproval" => ServerRequestKind::PermissionsApproval,
703            "item/tool/requestUserInput" => ServerRequestKind::UserInput,
704            "mcpServer/elicitation/request" => ServerRequestKind::McpElicitation,
705            _ => {
706                return Err(CodexAppServerProtocolError::UnsupportedServerRequest(
707                    method,
708                ))
709            }
710        };
711        // Every kind except McpElicitation is item-scoped and MUST carry a
712        // threadId/turnId — silently treating an omitted field the same as
713        // "no scope claimed" (rather than erroring) contradicted this API's
714        // own "scoped to active thread/turn" fail-closed claim: a
715        // malformed/unexpected request missing these fields would have been
716        // queued unconditionally instead of rejected (ReAgent P1, PR #3212).
717        // McpElicitation genuinely has no thread/turn context (see its own
718        // test fixture), so it alone stays optional.
719        let (thread_id, turn_id) = if kind == ServerRequestKind::McpElicitation {
720            (
721                params.get("threadId").and_then(Value::as_str).map(str::to_string),
722                params.get("turnId").and_then(Value::as_str).map(str::to_string),
723            )
724        } else {
725            (
726                Some(string_field(params.get("threadId"), "threadId")?),
727                Some(string_field(params.get("turnId"), "turnId")?),
728            )
729        };
730        let item_id = params
731            .get("itemId")
732            .and_then(Value::as_str)
733            .map(str::to_string);
734        let mut state = self.state.lock().unwrap();
735        if state.pending_requests.contains_key(&id) {
736            return Err(CodexAppServerProtocolError::DuplicateServerRequest);
737        }
738        if state.pending_requests.len() >= MAX_PENDING_SERVER_REQUESTS {
739            return Err(CodexAppServerProtocolError::TooManyPendingRequests(
740                MAX_PENDING_SERVER_REQUESTS,
741            ));
742        }
743        // Strict, not the notification-reconciliation ensure_thread_scope/
744        // ensure_scopes: those trivially pass when state.thread_id/turn_id
745        // is None, which is correct for a notification establishing state
746        // (e.g. the first thread/started) but wrong here — a request
747        // claiming a threadId/turnId while no thread/turn is actually
748        // active must be rejected, not queued as if it were in scope
749        // (ReAgent P1, PR #3212 3rd review). Matched on both fields
750        // together, not two independent `if let Some`s: a request with
751        // turnId but no threadId is a real, distinct case (McpElicitation
752        // may carry either field alone) and must still validate the turn
753        // it claims — two independent checks silently skip it whenever
754        // thread_id is None, whatever turn_id says (ReAgent P1, PR #3212
755        // 4th review).
756        match (&thread_id, &turn_id) {
757            (Some(thread), Some(turn)) => ensure_active_scopes(&state, thread, turn)?,
758            (Some(thread), None) => ensure_active_thread_scope(&state, thread)?,
759            (None, Some(turn)) => ensure_active_turn_scope(&state, turn)?,
760            (None, None) => {}
761        }
762        let pending = PendingServerRequest {
763            id: id.clone(),
764            kind,
765            method,
766            params,
767            thread_id,
768            turn_id,
769            item_id,
770        };
771        state.pending_requests.insert(id, pending.clone());
772        Ok(pending)
773    }
774
775    /// Send a decision for a queued request. The request remains pending if the
776    /// transport write fails, allowing a retry; successful responses consume it.
777    #[allow(dead_code)] // Unwired until SPEC_CODEX_APP_SERVER_FIRST_CLASS_PROVIDER_2026_09_12.md §15 Slice 3.
778    pub async fn respond_server_request(
779        &self,
780        id: &RpcId,
781        result: Result<Value, ServerResponseError>,
782        timeout: Duration,
783    ) -> Result<(), CodexAppServerProtocolError> {
784        // Removed atomically (check-and-take in one lock acquisition)
785        // rather than checked-then-removed-later — the old
786        // check-then-await-then-remove sequence let two concurrent calls
787        // for the same id both pass the membership check before either
788        // removed it, so both would send a JSON-RPC response for the same
789        // id and both report success (ReAgent P2, PR #3212). Re-inserted
790        // below on a transport failure so the documented retry-on-failure
791        // behavior is preserved — only one caller can ever be "holding" the
792        // entry between the take and a possible reinsert.
793        let pending = self
794            .state
795            .lock()
796            .unwrap()
797            .pending_requests
798            .remove(id)
799            .ok_or(CodexAppServerProtocolError::UnknownServerRequest)?;
800
801        // RestoreOnDrop reinserts the removed entry (if still scoped to the
802        // active thread/turn AND the frame was never actually queued for
803        // delivery) whenever it is dropped still armed — which covers an
804        // explicit transport-write failure below AND this future being
805        // dropped/cancelled while still suspended at the `.await` (e.g. a
806        // caller-side select!/timeout racing the write). A plain
807        // check-then-await-then-reinsert-on-Err only runs that reinsert
808        // code if the future resolves; drop the future mid-await instead
809        // and Rust never runs it at all, silently stranding the entry with
810        // no response ever sent and no error surfaced to anyone (muxreview
811        // P1, PR #3212 5th review). Folding the ordinary failure path into
812        // the same Drop impl means both cases are handled by one piece of
813        // logic instead of two copies of it.
814        struct RestoreOnDrop<'a> {
815            state: &'a Mutex<SessionState>,
816            id: RpcId,
817            pending: Option<PendingServerRequest>,
818            // See WriteOutcomeTracker. A transport-level timeout/
819            // cancellation while waiting on the write-confirmation ack
820            // does not mean the frame was never sent — it may already be
821            // irrevocably queued for delivery — so reinserting on any
822            // non-success outcome (as a bare Result would suggest) risks
823            // a subsequent retry sending a second, duplicate response for
824            // the same id (ReAgent P1, PR #3212 6th review).
825            outcome: WriteOutcomeTracker,
826        }
827        impl Drop for RestoreOnDrop<'_> {
828            fn drop(&mut self) {
829                if !self.outcome.safe_to_retry() {
830                    return;
831                }
832                let Some(pending) = self.pending.take() else {
833                    return;
834                };
835                let mut state = self.state.lock().unwrap();
836                // Matched on both fields together, not `(None, _) =>
837                // true`: a pending entry with turn_id but no thread_id is
838                // still turn-scoped and must not be resurrected once that
839                // turn has ended, whatever thread_id says (ReAgent P1,
840                // PR #3212 4th review).
841                let still_current = match (&pending.thread_id, &pending.turn_id) {
842                    (Some(thread), Some(turn)) => {
843                        state.thread_id.as_deref() == Some(thread.as_str())
844                            && state.turn_id.as_deref() == Some(turn.as_str())
845                    }
846                    (Some(thread), None) => state.thread_id.as_deref() == Some(thread.as_str()),
847                    (None, Some(turn)) => state.turn_id.as_deref() == Some(turn.as_str()),
848                    (None, None) => true,
849                };
850                if still_current {
851                    state.pending_requests.insert(self.id.clone(), pending);
852                }
853            }
854        }
855
856        let guard = RestoreOnDrop {
857            state: &self.state,
858            id: id.clone(),
859            pending: Some(pending),
860            outcome: WriteOutcomeTracker::new(),
861        };
862        let outcome = self
863            .transport
864            .respond_tracked(id.clone(), result, timeout, &guard.outcome)
865            .await;
866        outcome.map_err(Into::into)
867    }
868
869    #[allow(dead_code)] // Unwired until SPEC_CODEX_APP_SERVER_FIRST_CLASS_PROVIDER_2026_09_12.md §15 Slice 3.
870    pub fn pending_server_requests(&self) -> Vec<PendingServerRequest> {
871        self.state
872            .lock()
873            .unwrap()
874            .pending_requests
875            .values()
876            .cloned()
877            .collect()
878    }
879
880    #[allow(dead_code)] // Unwired until SPEC_CODEX_APP_SERVER_FIRST_CLASS_PROVIDER_2026_09_12.md §15 Slice 6.
881    pub fn snapshot(&self) -> SessionSnapshot {
882        let state = self.state.lock().unwrap();
883        SessionSnapshot {
884            thread_id: state.thread_id.clone(),
885            turn_id: state.turn_id.clone(),
886            phase: state.phase,
887            items: state.items.clone(),
888            raw_unknown_events: state.raw_unknown_events.iter().cloned().collect(),
889        }
890    }
891
892    pub fn apply_incoming(
893        &self,
894        incoming: AppServerIncoming,
895    ) -> Result<CodexAppServerEvent, CodexAppServerProtocolError> {
896        let AppServerIncoming::Notification { method, params } = incoming else {
897            return Err(CodexAppServerProtocolError::Transport(
898                AppServerError::Protocol(
899                    "server request requires an explicit approval adapter".to_string(),
900                ),
901            ));
902        };
903        let mut state = self.state.lock().unwrap();
904        match method.as_str() {
905            "thread/started" => {
906                let thread = params
907                    .get("thread")
908                    .and_then(Value::as_object)
909                    .ok_or(CodexAppServerProtocolError::MissingObjectField("thread"))?;
910                let thread_id = string_field(thread.get("id"), "thread.id")?;
911                // Only reset turn state for a GENUINELY new thread. If this
912                // notification is for the thread we already have loaded, a
913                // turn may already be active on it (e.g. this notification
914                // was delayed and arrives after `start_turn` already ran) —
915                // resetting unconditionally would wipe that live state out
916                // from under it (ReAgent P1, PR #3210).
917                let is_new_thread = state.thread_id.as_deref() != Some(thread_id.as_str());
918                state.thread_id = Some(thread_id.clone());
919                if is_new_thread {
920                    state.turn_id = None;
921                    state.phase = SessionPhase::Idle;
922                    state.items.clear();
923                    // Same as start_thread/resume_thread: a pending
924                    // approval from the previous thread must not remain
925                    // answerable once it's been replaced (ReAgent P1, PR
926                    // #3212).
927                    state.pending_requests.clear();
928                }
929                Ok(CodexAppServerEvent::ThreadStarted { thread_id })
930            }
931            "turn/started" => {
932                let thread_id = string_field(params.get("threadId"), "threadId")?;
933                ensure_thread_scope(&state, &thread_id)?;
934                let turn = params
935                    .get("turn")
936                    .and_then(Value::as_object)
937                    .ok_or(CodexAppServerProtocolError::MissingObjectField("turn"))?;
938                let turn_id = string_field(turn.get("id"), "turn.id")?;
939                state.turn_id = Some(turn_id.clone());
940                state.phase = SessionPhase::Running;
941                Ok(CodexAppServerEvent::TurnStarted { thread_id, turn_id })
942            }
943            "item/agentMessage/delta" => {
944                let thread_id = string_field(params.get("threadId"), "threadId")?;
945                let turn_id = string_field(params.get("turnId"), "turnId")?;
946                ensure_scopes(&state, &thread_id, &turn_id)?;
947                let item_id = string_field(params.get("itemId"), "itemId")?;
948                let delta = string_field(params.get("delta"), "delta")?;
949                let item = state.items.entry(item_id.clone()).or_insert(ItemSnapshot {
950                    id: item_id.clone(),
951                    kind: "agentMessage".to_string(),
952                    preview: String::new(),
953                    completed: false,
954                    authoritative: None,
955                });
956                item.preview.push_str(&delta);
957                Ok(CodexAppServerEvent::AgentMessageDelta {
958                    thread_id,
959                    turn_id,
960                    item_id,
961                    delta,
962                    preview: item.preview.clone(),
963                })
964            }
965            "item/started" => {
966                let thread_id = string_field(params.get("threadId"), "threadId")?;
967                let turn_id = string_field(params.get("turnId"), "turnId")?;
968                ensure_scopes(&state, &thread_id, &turn_id)?;
969                let item = params
970                    .get("item")
971                    .and_then(Value::as_object)
972                    .ok_or(CodexAppServerProtocolError::MissingObjectField("item"))?;
973                let item_id = string_field(item.get("id"), "item.id")?;
974                let kind = string_field(item.get("type"), "item.type")?;
975                state.items.insert(
976                    item_id.clone(),
977                    ItemSnapshot {
978                        id: item_id.clone(),
979                        kind: kind.clone(),
980                        preview: String::new(),
981                        completed: false,
982                        authoritative: None,
983                    },
984                );
985                Ok(CodexAppServerEvent::ItemStarted {
986                    thread_id,
987                    turn_id,
988                    item_id,
989                    kind,
990                })
991            }
992            "item/completed" => {
993                let thread_id = string_field(params.get("threadId"), "threadId")?;
994                let turn_id = string_field(params.get("turnId"), "turnId")?;
995                ensure_scopes(&state, &thread_id, &turn_id)?;
996                let item = params
997                    .get("item")
998                    .and_then(Value::as_object)
999                    .ok_or(CodexAppServerProtocolError::MissingObjectField("item"))?;
1000                let item_id = string_field(item.get("id"), "item.id")?;
1001                let kind = string_field(item.get("type"), "item.type")?;
1002                state.items.insert(
1003                    item_id.clone(),
1004                    ItemSnapshot {
1005                        id: item_id.clone(),
1006                        kind: kind.clone(),
1007                        preview: String::new(),
1008                        completed: true,
1009                        authoritative: Some(Value::Object(item.clone())),
1010                    },
1011                );
1012                Ok(CodexAppServerEvent::ItemCompleted {
1013                    thread_id,
1014                    turn_id,
1015                    item_id,
1016                    kind,
1017                    item: Value::Object(item.clone()),
1018                })
1019            }
1020            "turn/completed" => {
1021                let thread_id = string_field(params.get("threadId"), "threadId")?;
1022                ensure_thread_scope(&state, &thread_id)?;
1023                let turn = params
1024                    .get("turn")
1025                    .and_then(Value::as_object)
1026                    .ok_or(CodexAppServerProtocolError::MissingObjectField("turn"))?;
1027                let turn_id = string_field(turn.get("id"), "turn.id")?;
1028                if let Some(expected) = &state.turn_id {
1029                    if expected != &turn_id {
1030                        return Err(CodexAppServerProtocolError::TurnScopeMismatch {
1031                            expected: expected.clone(),
1032                            actual: turn_id.clone(),
1033                        });
1034                    }
1035                }
1036                let status = string_field(turn.get("status"), "turn.status")?;
1037                state.turn_id = None;
1038                state.last_terminated_turn_id = Some(turn_id.clone());
1039                // TurnStatus's terminal values: "completed", "interrupted"
1040                // (user cancellation), "failed". Collapsing "interrupted"
1041                // into Failed hid an expected cancellation behind the same
1042                // signal as a genuine provider/execution failure (muxreview
1043                // P1, PR #3210). Anything else unrecognized still maps to
1044                // Failed rather than erroring — this notification has
1045                // already been accepted; the phase is best-effort.
1046                state.phase = match status.as_str() {
1047                    "completed" => SessionPhase::Completed,
1048                    "interrupted" => SessionPhase::Interrupted,
1049                    _ => SessionPhase::Failed,
1050                };
1051                state.pending_requests.clear();
1052                Ok(CodexAppServerEvent::TurnCompleted {
1053                    thread_id,
1054                    turn_id,
1055                    status,
1056                })
1057            }
1058            "thread/status/changed" => {
1059                let thread_id = string_field(params.get("threadId"), "threadId")?;
1060                ensure_thread_scope(&state, &thread_id)?;
1061                let status = params.get("status").cloned().unwrap_or(Value::Null);
1062                Ok(CodexAppServerEvent::ThreadStatusChanged { thread_id, status })
1063            }
1064            // The App Server can resolve/cancel an individual pending
1065            // request on its own (e.g. superseded by a newer one, or the
1066            // item it concerned went away) without ending the whole turn.
1067            // Previously only turn/completed or a thread transition ever
1068            // cleared pending_requests, so a request resolved this way
1069            // stayed in pending_server_requests() and answerable via
1070            // respond_server_request until the turn ended (ReAgent P2,
1071            // PR #3212). Removes only this one entry, not the whole map.
1072            "serverRequest/resolved" => {
1073                let thread_id = string_field(params.get("threadId"), "threadId")?;
1074                ensure_thread_scope(&state, &thread_id)?;
1075                let request_id = RpcId::from_value(params.get("requestId").ok_or_else(|| {
1076                    CodexAppServerProtocolError::Transport(AppServerError::Protocol(
1077                        "serverRequest/resolved notification is missing requestId".to_string(),
1078                    ))
1079                })?)?;
1080                state.pending_requests.remove(&request_id);
1081                Ok(CodexAppServerEvent::ServerRequestResolved {
1082                    thread_id,
1083                    request_id,
1084                })
1085            }
1086            "account/login/completed" => {
1087                let success = params
1088                    .get("success")
1089                    .and_then(Value::as_bool)
1090                    .ok_or(CodexAppServerProtocolError::MissingBoolField("success"))?;
1091                Ok(CodexAppServerEvent::AccountLoginCompleted {
1092                    login_id: params
1093                        .get("loginId")
1094                        .and_then(Value::as_str)
1095                        .map(str::to_string),
1096                    success,
1097                    error: params
1098                        .get("error")
1099                        .and_then(Value::as_str)
1100                        .map(str::to_string),
1101                })
1102            }
1103            _ => {
1104                let raw = json!({ "method": method, "params": params });
1105                if state.raw_unknown_events.len() == MAX_RAW_EVENTS {
1106                    state.raw_unknown_events.pop_front();
1107                }
1108                state.raw_unknown_events.push_back(raw.clone());
1109                Ok(CodexAppServerEvent::UnknownNotification {
1110                    method: raw["method"].as_str().unwrap_or_default().to_string(),
1111                    params: raw["params"].clone(),
1112                })
1113            }
1114        }
1115    }
1116}
1117
1118fn extract_thread_id(result: &Value) -> Result<String, CodexAppServerProtocolError> {
1119    let thread = result
1120        .get("thread")
1121        .and_then(Value::as_object)
1122        .ok_or(CodexAppServerProtocolError::MissingObjectField("thread"))?;
1123    string_field(thread.get("id"), "thread.id")
1124}
1125
1126/// The id of whichever turn in `thread.turns` (a `ThreadResumeResponse`
1127/// field, populated on `thread/resume`) has `status: "inProgress"`, if any.
1128/// `TurnStatus`'s only other values (`completed`/`interrupted`/`failed`)
1129/// are all terminal, so at most one entry can ever match. Malformed/missing
1130/// shapes intentionally fall through to `None` rather than erroring — this
1131/// is best-effort derivation of pre-existing state, not a required field.
1132fn extract_in_progress_turn_id(result: &Value) -> Option<String> {
1133    result
1134        .get("thread")?
1135        .get("turns")?
1136        .as_array()?
1137        .iter()
1138        .find(|turn| turn.get("status").and_then(Value::as_str) == Some("inProgress"))?
1139        .get("id")?
1140        .as_str()
1141        .map(str::to_string)
1142}
1143
1144fn string_field(
1145    value: Option<&Value>,
1146    field: &'static str,
1147) -> Result<String, CodexAppServerProtocolError> {
1148    value
1149        .and_then(Value::as_str)
1150        .map(str::to_string)
1151        .ok_or(CodexAppServerProtocolError::MissingStringField(field))
1152}
1153
1154fn ensure_thread_scope(
1155    state: &SessionState,
1156    actual: &str,
1157) -> Result<(), CodexAppServerProtocolError> {
1158    if let Some(expected) = &state.thread_id {
1159        if expected != actual {
1160            return Err(CodexAppServerProtocolError::ThreadScopeMismatch {
1161                expected: expected.clone(),
1162                actual: actual.to_string(),
1163            });
1164        }
1165    }
1166    Ok(())
1167}
1168
1169fn ensure_scopes(
1170    state: &SessionState,
1171    thread_id: &str,
1172    turn_id: &str,
1173) -> Result<(), CodexAppServerProtocolError> {
1174    ensure_thread_scope(state, thread_id)?;
1175    if let Some(expected) = &state.turn_id {
1176        if expected != turn_id {
1177            return Err(CodexAppServerProtocolError::TurnScopeMismatch {
1178                expected: expected.clone(),
1179                actual: turn_id.to_string(),
1180            });
1181        }
1182    }
1183    Ok(())
1184}
1185
1186/// Unlike ensure_thread_scope, fails closed when no thread is active — a
1187/// server request claiming a threadId must be scoped to a *real, active*
1188/// thread, not merely "no conflicting thread claimed yet" the way an
1189/// incoming notification establishing state is allowed to be.
1190fn ensure_active_thread_scope(
1191    state: &SessionState,
1192    actual: &str,
1193) -> Result<(), CodexAppServerProtocolError> {
1194    match &state.thread_id {
1195        Some(expected) if expected == actual => Ok(()),
1196        Some(expected) => Err(CodexAppServerProtocolError::ThreadScopeMismatch {
1197            expected: expected.clone(),
1198            actual: actual.to_string(),
1199        }),
1200        None => Err(CodexAppServerProtocolError::ThreadNotLoaded),
1201    }
1202}
1203
1204/// See ensure_active_thread_scope — fails closed when no turn is active.
1205fn ensure_active_scopes(
1206    state: &SessionState,
1207    thread_id: &str,
1208    turn_id: &str,
1209) -> Result<(), CodexAppServerProtocolError> {
1210    ensure_active_thread_scope(state, thread_id)?;
1211    ensure_active_turn_scope(state, turn_id)
1212}
1213
1214/// See ensure_active_thread_scope — fails closed when no turn is active.
1215/// Split out from ensure_active_scopes so a turn can be validated on its
1216/// own when a request carries a turnId without a threadId (ReAgent P1,
1217/// PR #3212 4th review).
1218fn ensure_active_turn_scope(
1219    state: &SessionState,
1220    actual: &str,
1221) -> Result<(), CodexAppServerProtocolError> {
1222    match &state.turn_id {
1223        Some(expected) if expected == actual => Ok(()),
1224        Some(expected) => Err(CodexAppServerProtocolError::TurnScopeMismatch {
1225            expected: expected.clone(),
1226            actual: actual.to_string(),
1227        }),
1228        None => Err(CodexAppServerProtocolError::TurnNotActive),
1229    }
1230}
1231
1232#[cfg(test)]
1233mod tests {
1234    use super::*;
1235    use tokio::io::{duplex, AsyncBufReadExt, AsyncWriteExt, BufReader};
1236
1237
1238    fn session() -> (
1239        Arc<CodexAppServerSession>,
1240        tokio::io::ReadHalf<tokio::io::DuplexStream>,
1241        tokio::io::WriteHalf<tokio::io::DuplexStream>,
1242    ) {
1243        let (client, server) = duplex(8192);
1244        let (client_reader, client_writer) = tokio::io::split(client);
1245        let (server_reader, server_writer) = tokio::io::split(server);
1246        let transport = Arc::new(AppServerTransport::new(
1247            client_reader,
1248            client_writer,
1249            Default::default(),
1250        ));
1251        (
1252            Arc::new(CodexAppServerSession::new(transport)),
1253            server_reader,
1254            server_writer,
1255        )
1256    }
1257
1258    #[tokio::test]
1259    async fn starts_thread_and_turn_with_schema_shaped_requests() {
1260        let (session, server_reader, mut server_writer) = session();
1261        let server = tokio::spawn(async move {
1262            let mut lines = BufReader::new(server_reader).lines();
1263            let start: Value =
1264                serde_json::from_str(&lines.next_line().await.unwrap().unwrap()).unwrap();
1265            assert_eq!(start["method"], "thread/start");
1266            assert_eq!(start["params"]["model"], "gpt-5-codex");
1267            server_writer
1268                .write_all(
1269                    br#"{"id":1,"result":{"thread":{"id":"thread-1"}}}
1270"#,
1271                )
1272                .await
1273                .unwrap();
1274            let turn: Value =
1275                serde_json::from_str(&lines.next_line().await.unwrap().unwrap()).unwrap();
1276            assert_eq!(turn["method"], "turn/start");
1277            assert_eq!(turn["params"]["threadId"], "thread-1");
1278            assert_eq!(
1279                turn["params"]["input"][0],
1280                json!({"type":"text","text":"hello"})
1281            );
1282            server_writer
1283                .write_all(
1284                    br#"{"id":2,"result":{"turn":{"id":"turn-1"}}}
1285"#,
1286                )
1287                .await
1288                .unwrap();
1289        });
1290
1291        assert_eq!(
1292            session
1293                .start_thread(
1294                    ThreadStartOptions {
1295                        model: Some("gpt-5-codex".to_string()),
1296                        ..Default::default()
1297                    },
1298                    Duration::from_secs(1),
1299                )
1300                .await
1301                .unwrap(),
1302            "thread-1"
1303        );
1304        assert_eq!(
1305            session
1306                .start_turn("hello".to_string(), Vec::new(), Duration::from_secs(1))
1307                .await
1308                .unwrap(),
1309            "turn-1"
1310        );
1311        assert_eq!(session.snapshot().phase, SessionPhase::Running);
1312        server.await.unwrap();
1313    }
1314
1315    #[tokio::test]
1316    async fn resumes_only_the_requested_thread() {
1317        let (session, server_reader, mut server_writer) = session();
1318        let server = tokio::spawn(async move {
1319            let mut lines = BufReader::new(server_reader).lines();
1320            let request: Value =
1321                serde_json::from_str(&lines.next_line().await.unwrap().unwrap()).unwrap();
1322            assert_eq!(request["method"], "thread/resume");
1323            assert_eq!(request["params"]["threadId"], "thread-2");
1324            server_writer
1325                .write_all(
1326                    br#"{"id":1,"result":{"thread":{"id":"thread-2"}}}
1327"#,
1328                )
1329                .await
1330                .unwrap();
1331        });
1332        assert_eq!(
1333            session
1334                .resume_thread(
1335                    "thread-2".to_string(),
1336                    None,
1337                    Some("C:\\workspace".to_string()),
1338                    Duration::from_secs(1),
1339                )
1340                .await
1341                .unwrap(),
1342            "thread-2"
1343        );
1344        assert_eq!(session.snapshot().thread_id.as_deref(), Some("thread-2"));
1345        server.await.unwrap();
1346    }
1347
1348    #[tokio::test]
1349    async fn builds_thread_lifecycle_and_account_requests_with_exact_shapes() {
1350        let (session, server_reader, mut server_writer) = session();
1351        session.state.lock().unwrap().thread_id = Some("thread-1".to_string());
1352        let server = tokio::spawn(async move {
1353            let mut lines = BufReader::new(server_reader).lines();
1354            let fork: Value =
1355                serde_json::from_str(&lines.next_line().await.unwrap().unwrap()).unwrap();
1356            assert_eq!(fork["method"], "thread/fork");
1357            assert_eq!(
1358                fork["params"],
1359                json!({"threadId":"thread-1","model":"gpt-5-codex","cwd":"C:\\workspace","lastTurnId":"turn-1","excludeTurns":true})
1360            );
1361            server_writer
1362                .write_all(
1363                    br#"{"id":1,"result":{"thread":{"id":"thread-2"}}}
1364"#,
1365                )
1366                .await
1367                .unwrap();
1368            let read: Value =
1369                serde_json::from_str(&lines.next_line().await.unwrap().unwrap()).unwrap();
1370            assert_eq!(read["method"], "thread/read");
1371            assert_eq!(
1372                read["params"],
1373                json!({"threadId":"thread-1","includeTurns":true})
1374            );
1375            server_writer
1376                .write_all(
1377                    br#"{"id":2,"result":{"thread":{"id":"thread-1"}}}
1378"#,
1379                )
1380                .await
1381                .unwrap();
1382            let list: Value =
1383                serde_json::from_str(&lines.next_line().await.unwrap().unwrap()).unwrap();
1384            assert_eq!(list["method"], "thread/list");
1385            assert_eq!(list["params"], json!({"limit":10,"searchTerm":"codex"}));
1386            server_writer
1387                .write_all(
1388                    br#"{"id":3,"result":{"data":[]}}
1389"#,
1390                )
1391                .await
1392                .unwrap();
1393            let archive: Value =
1394                serde_json::from_str(&lines.next_line().await.unwrap().unwrap()).unwrap();
1395            assert_eq!(archive["method"], "thread/archive");
1396            assert_eq!(archive["params"], json!({"threadId":"thread-1"}));
1397            server_writer
1398                .write_all(
1399                    br#"{"id":4,"result":{"archived":true}}
1400"#,
1401                )
1402                .await
1403                .unwrap();
1404            let compact: Value =
1405                serde_json::from_str(&lines.next_line().await.unwrap().unwrap()).unwrap();
1406            assert_eq!(compact["method"], "thread/compact/start");
1407            assert_eq!(compact["params"], json!({"threadId":"thread-1"}));
1408            server_writer
1409                .write_all(
1410                    br#"{"id":5,"result":{"turn":{"id":"compact-1"}}}
1411"#,
1412                )
1413                .await
1414                .unwrap();
1415            let account: Value =
1416                serde_json::from_str(&lines.next_line().await.unwrap().unwrap()).unwrap();
1417            assert_eq!(account["method"], "account/read");
1418            assert_eq!(account["params"], json!({"refreshToken":false}));
1419            server_writer
1420                .write_all(
1421                    br#"{"id":6,"result":{"type":"chatgpt","email":"a@example.com"}}
1422"#,
1423                )
1424                .await
1425                .unwrap();
1426            let logout: Value =
1427                serde_json::from_str(&lines.next_line().await.unwrap().unwrap()).unwrap();
1428            assert_eq!(logout["method"], "account/logout");
1429            assert_eq!(logout["params"], Value::Null);
1430            server_writer
1431                .write_all(
1432                    br#"{"id":7,"result":{}}
1433"#,
1434                )
1435                .await
1436                .unwrap();
1437            let login: Value =
1438                serde_json::from_str(&lines.next_line().await.unwrap().unwrap()).unwrap();
1439            assert_eq!(login["method"], "account/login/start");
1440            assert_eq!(login["params"], json!({"type":"chatgptDeviceCode"}));
1441            server_writer
1442                .write_all(
1443                    br#"{"id":8,"result":{"loginId":"login-1","userCode":"ABCD"}}
1444"#,
1445                )
1446                .await
1447                .unwrap();
1448            let cancel: Value =
1449                serde_json::from_str(&lines.next_line().await.unwrap().unwrap()).unwrap();
1450            assert_eq!(cancel["method"], "account/login/cancel");
1451            assert_eq!(cancel["params"], json!({"loginId":"login-1"}));
1452            server_writer
1453                .write_all(
1454                    br#"{"id":9,"result":{}}
1455"#,
1456                )
1457                .await
1458                .unwrap();
1459        });
1460        assert_eq!(
1461            session
1462                .fork_thread(
1463                    ThreadForkOptions {
1464                        thread_id: "thread-1".to_string(),
1465                        model: Some("gpt-5-codex".to_string()),
1466                        cwd: Some("C:\\workspace".to_string()),
1467                        last_turn_id: Some("turn-1".to_string()),
1468                        exclude_turns: Some(true)
1469                    },
1470                    Duration::from_secs(1)
1471                )
1472                .await
1473                .unwrap(),
1474            "thread-2"
1475        );
1476        session
1477            .read_thread(true, Duration::from_secs(1))
1478            .await
1479            .unwrap();
1480        session
1481            .list_threads(
1482                ThreadListOptions {
1483                    limit: Some(10),
1484                    search_term: Some("codex".to_string()),
1485                    ..Default::default()
1486                },
1487                Duration::from_secs(1),
1488            )
1489            .await
1490            .unwrap();
1491        session
1492            .archive_thread(Duration::from_secs(1))
1493            .await
1494            .unwrap();
1495        session
1496            .compact_thread(Duration::from_secs(1))
1497            .await
1498            .unwrap();
1499        session
1500            .read_account(false, Duration::from_secs(1))
1501            .await
1502            .unwrap();
1503        session
1504            .logout_account(Duration::from_secs(1))
1505            .await
1506            .unwrap();
1507        session
1508            .login_account(
1509                AccountLoginOptions::ChatgptDeviceCode,
1510                Duration::from_secs(1),
1511            )
1512            .await
1513            .unwrap();
1514        session
1515            .cancel_login("login-1".to_string(), Duration::from_secs(1))
1516            .await
1517            .unwrap();
1518        server.await.unwrap();
1519    }
1520
1521    #[tokio::test]
1522    async fn parses_account_login_completion_without_leaking_credentials() {
1523        let (session, _reader, _writer) = session();
1524        let event = session
1525            .apply_incoming(AppServerIncoming::Notification {
1526                method: "account/login/completed".to_string(),
1527                params: json!({"loginId":"login-1","success":false,"error":"cancelled"}),
1528            })
1529            .unwrap();
1530        assert!(matches!(
1531            event,
1532            CodexAppServerEvent::AccountLoginCompleted {
1533                login_id: Some(ref id),
1534                success: false,
1535                error: Some(ref error),
1536            } if id == "login-1" && error == "cancelled"
1537        ));
1538    }
1539
1540    /// ReAgent P2, PR #3214: a missing/wrong-typed `success` (a bool) was
1541    /// reported via MissingStringField, whose Display text ("...missing a
1542    /// string field: success") is inaccurate -- `success` is a bool, not a
1543    /// string, and every other use of that variant in this file is for an
1544    /// actual string field.
1545    #[tokio::test]
1546    async fn account_login_completed_missing_success_reports_the_right_field_type() {
1547        let (session, _reader, _writer) = session();
1548        let error = session
1549            .apply_incoming(AppServerIncoming::Notification {
1550                method: "account/login/completed".to_string(),
1551                params: json!({"loginId": "login-1"}),
1552            })
1553            .unwrap_err();
1554        assert!(matches!(
1555            error,
1556            CodexAppServerProtocolError::MissingBoolField("success")
1557        ));
1558    }
1559
1560    #[tokio::test]
1561    async fn fork_rejects_a_thread_id_that_is_not_the_active_thread() {
1562        let (session, _reader, _writer) = session();
1563        session.state.lock().unwrap().thread_id = Some("thread-1".to_string());
1564        let error = session
1565            .fork_thread(
1566                ThreadForkOptions {
1567                    thread_id: "thread-2".to_string(),
1568                    model: None,
1569                    cwd: None,
1570                    last_turn_id: None,
1571                    exclude_turns: None,
1572                },
1573                Duration::from_secs(1),
1574            )
1575            .await
1576            .unwrap_err();
1577        assert!(matches!(
1578            error,
1579            CodexAppServerProtocolError::ThreadScopeMismatch { .. }
1580        ));
1581    }
1582
1583    #[tokio::test]
1584    async fn steers_and_interrupts_only_the_active_turn() {
1585        let (session, server_reader, mut server_writer) = session();
1586        {
1587            let mut state = session.state.lock().unwrap();
1588            state.thread_id = Some("thread-1".to_string());
1589            state.turn_id = Some("turn-1".to_string());
1590        }
1591        let server = tokio::spawn(async move {
1592            let mut lines = BufReader::new(server_reader).lines();
1593            let steer: Value =
1594                serde_json::from_str(&lines.next_line().await.unwrap().unwrap()).unwrap();
1595            assert_eq!(steer["method"], "turn/steer");
1596            assert_eq!(steer["params"]["expectedTurnId"], "turn-1");
1597            server_writer
1598                .write_all(
1599                    br#"{"id":1,"result":{"accepted":true}}
1600"#,
1601                )
1602                .await
1603                .unwrap();
1604            let interrupt: Value =
1605                serde_json::from_str(&lines.next_line().await.unwrap().unwrap()).unwrap();
1606            assert_eq!(interrupt["method"], "turn/interrupt");
1607            assert_eq!(interrupt["params"]["turnId"], "turn-1");
1608            server_writer
1609                .write_all(
1610                    br#"{"id":2,"result":{"accepted":true}}
1611"#,
1612                )
1613                .await
1614                .unwrap();
1615        });
1616        assert_eq!(
1617            session
1618                .steer_turn(
1619                    "continue".to_string(),
1620                    "turn-1".to_string(),
1621                    Duration::from_secs(1)
1622                )
1623                .await
1624                .unwrap()["accepted"],
1625            true
1626        );
1627        assert_eq!(
1628            session
1629                .interrupt_turn(Duration::from_secs(1))
1630                .await
1631                .unwrap()["accepted"],
1632            true
1633        );
1634        assert!(matches!(
1635            session
1636                .steer_turn(
1637                    "stale".to_string(),
1638                    "turn-old".to_string(),
1639                    Duration::from_secs(1)
1640                )
1641                .await,
1642            Err(CodexAppServerProtocolError::TurnScopeMismatch { .. })
1643        ));
1644        server.await.unwrap();
1645    }
1646
1647    #[tokio::test]
1648    async fn reconciles_delta_preview_with_authoritative_completion() {
1649        let (session, _reader, _writer) = session();
1650        session.state.lock().unwrap().thread_id = Some("thread-1".to_string());
1651        session.state.lock().unwrap().turn_id = Some("turn-1".to_string());
1652
1653        let delta = session
1654            .apply_incoming(AppServerIncoming::Notification {
1655                method: "item/agentMessage/delta".to_string(),
1656                params: json!({"threadId":"thread-1","turnId":"turn-1","itemId":"item-1","delta":"hel"}),
1657            })
1658            .unwrap();
1659        assert!(
1660            matches!(delta, CodexAppServerEvent::AgentMessageDelta { ref preview, .. } if preview == "hel")
1661        );
1662        session
1663            .apply_incoming(AppServerIncoming::Notification {
1664                method: "item/agentMessage/delta".to_string(),
1665                params: json!({"threadId":"thread-1","turnId":"turn-1","itemId":"item-1","delta":"lo"}),
1666            })
1667            .unwrap();
1668        session
1669            .apply_incoming(AppServerIncoming::Notification {
1670                method: "item/completed".to_string(),
1671                params: json!({"threadId":"thread-1","turnId":"turn-1","item":{"id":"item-1","type":"agentMessage","text":"hello"}}),
1672            })
1673            .unwrap();
1674        let item = session.snapshot().items.remove("item-1").unwrap();
1675        assert_eq!(item.preview, "");
1676        assert!(item.completed);
1677        assert_eq!(item.authoritative.unwrap()["text"], "hello");
1678
1679        session
1680            .apply_incoming(AppServerIncoming::Notification {
1681                method: "turn/completed".to_string(),
1682                params: json!({"threadId":"thread-1","turn":{"id":"turn-1","status":"completed"}}),
1683            })
1684            .unwrap();
1685        let snapshot = session.snapshot();
1686        assert_eq!(snapshot.phase, SessionPhase::Completed);
1687        assert_eq!(snapshot.turn_id, None);
1688    }
1689
1690    #[tokio::test]
1691    async fn rejects_cross_thread_events_and_retains_unknown_notifications_bounded() {
1692        let (session, _reader, _writer) = session();
1693        session.state.lock().unwrap().thread_id = Some("thread-1".to_string());
1694        let error = session
1695            .apply_incoming(AppServerIncoming::Notification {
1696                method: "thread/status/changed".to_string(),
1697                params: json!({"threadId":"thread-2","status":{"type":"idle"}}),
1698            })
1699            .unwrap_err();
1700        assert!(matches!(
1701            error,
1702            CodexAppServerProtocolError::ThreadScopeMismatch { .. }
1703        ));
1704
1705        for _ in 0..(MAX_RAW_EVENTS + 7) {
1706            session
1707                .apply_incoming(AppServerIncoming::Notification {
1708                    method: "future/event".to_string(),
1709                    params: json!({"ok":true}),
1710                })
1711                .unwrap();
1712        }
1713        assert_eq!(session.snapshot().raw_unknown_events.len(), MAX_RAW_EVENTS);
1714    }
1715
1716    /// ReAgent P2, PR #3212: only turn/completed or a thread transition ever
1717    /// cleared pending_requests -- an individual request the App Server
1718    /// resolves/cancels on its own (serverRequest/resolved, real in the
1719    /// pinned 0.154.0 schema) stayed answerable via respond_server_request
1720    /// until the whole turn ended. Removes only the resolved entry, not
1721    /// every pending request for the turn.
1722    #[tokio::test]
1723    async fn server_request_resolved_clears_only_that_one_pending_request() {
1724        let (session, _reader, _writer) = session();
1725        {
1726            let mut state = session.state.lock().unwrap();
1727            state.thread_id = Some("thread-1".to_string());
1728            state.turn_id = Some("turn-1".to_string());
1729        }
1730        session
1731            .accept_server_request(AppServerIncoming::Request {
1732                id: RpcId::String("resolved-me".to_string()),
1733                method: "item/tool/requestUserInput".to_string(),
1734                params: json!({"threadId": "thread-1", "turnId": "turn-1", "itemId": "a"}),
1735            })
1736            .unwrap();
1737        session
1738            .accept_server_request(AppServerIncoming::Request {
1739                id: RpcId::String("still-pending".to_string()),
1740                method: "item/tool/requestUserInput".to_string(),
1741                params: json!({"threadId": "thread-1", "turnId": "turn-1", "itemId": "b"}),
1742            })
1743            .unwrap();
1744
1745        let event = session
1746            .apply_incoming(AppServerIncoming::Notification {
1747                method: "serverRequest/resolved".to_string(),
1748                params: json!({"threadId": "thread-1", "requestId": "resolved-me"}),
1749            })
1750            .unwrap();
1751        assert_eq!(
1752            event,
1753            CodexAppServerEvent::ServerRequestResolved {
1754                thread_id: "thread-1".to_string(),
1755                request_id: RpcId::String("resolved-me".to_string()),
1756            }
1757        );
1758
1759        let remaining = session.pending_server_requests();
1760        assert_eq!(remaining.len(), 1);
1761        assert_eq!(remaining[0].id, RpcId::String("still-pending".to_string()));
1762    }
1763
1764    /// ReAgent P1, PR #3210: the `turn/start` response and a `turn/completed`
1765    /// notification for the SAME turn arrive on independent channels (the
1766    /// request/response oneshot vs. run_reader's notification stream), so
1767    /// the notification can be applied before `start_turn`'s own
1768    /// continuation resumes. Before the fix, `start_turn`'s unconditional
1769    /// post-await write would resurrect the already-terminal turn as
1770    /// `Running`, permanently stuck (every later `start_turn` call would
1771    /// see a phantom `TurnAlreadyActive`).
1772    #[tokio::test]
1773    async fn a_turn_completed_notification_that_lands_before_the_turn_start_response_is_not_overwritten(
1774    ) {
1775        let (session, server_reader, mut server_writer) = session();
1776        let server = tokio::spawn(async move {
1777            let mut lines = BufReader::new(server_reader).lines();
1778            let _start: Value =
1779                serde_json::from_str(&lines.next_line().await.unwrap().unwrap()).unwrap();
1780            server_writer
1781                .write_all(br#"{"id":1,"result":{"thread":{"id":"thread-1"}}}
1782"#)
1783                .await
1784                .unwrap();
1785            let _turn: Value =
1786                serde_json::from_str(&lines.next_line().await.unwrap().unwrap()).unwrap();
1787            // Completion notification written and processed BEFORE the
1788            // turn/start response, on purpose.
1789            server_writer
1790                .write_all(
1791                    b"{\"method\":\"turn/completed\",\"params\":{\"threadId\":\"thread-1\",\"turn\":{\"id\":\"turn-1\",\"status\":\"completed\"}}}\n",
1792                )
1793                .await
1794                .unwrap();
1795            server_writer
1796                .write_all(br#"{"id":2,"result":{"turn":{"id":"turn-1"}}}
1797"#)
1798                .await
1799                .unwrap();
1800        });
1801
1802        session
1803            .start_thread(ThreadStartOptions::default(), Duration::from_secs(1))
1804            .await
1805            .unwrap();
1806
1807        let session_for_turn = session.clone();
1808        let start_turn_task = tokio::spawn(async move {
1809            session_for_turn
1810                .start_turn("hello".to_string(), Vec::new(), Duration::from_secs(1))
1811                .await
1812        });
1813
1814        // Drain and apply the notification BEFORE start_turn's own response
1815        // resolves — the reader processes frames in wire order, so this
1816        // happens-before the response gets processed.
1817        let notification = session.transport.next_incoming().await.unwrap();
1818        session.apply_incoming(notification).unwrap();
1819        assert_eq!(session.snapshot().phase, SessionPhase::Completed);
1820
1821        let turn_id = start_turn_task.await.unwrap().unwrap();
1822        assert_eq!(turn_id, "turn-1", "start_turn still reports success to its own caller");
1823
1824        let snapshot = session.snapshot();
1825        assert_eq!(
1826            snapshot.phase,
1827            SessionPhase::Completed,
1828            "a turn/completed that landed first must not be overwritten back to Running"
1829        );
1830        assert!(snapshot.turn_id.is_none());
1831
1832        server.await.unwrap();
1833    }
1834
1835    /// ReAgent P1, PR #3210: `resume_thread` used to unconditionally clear
1836    /// turn_id/phase/items, silently dropping a turn the 0.154.0 contract
1837    /// reports as still `inProgress` in `ThreadResumeResponse.thread.turns`.
1838    #[tokio::test]
1839    async fn resume_thread_derives_an_in_progress_turn_instead_of_dropping_it() {
1840        let (session, server_reader, mut server_writer) = session();
1841        let server = tokio::spawn(async move {
1842            let mut lines = BufReader::new(server_reader).lines();
1843            let _request: Value =
1844                serde_json::from_str(&lines.next_line().await.unwrap().unwrap()).unwrap();
1845            server_writer
1846                .write_all(
1847                    br#"{"id":1,"result":{"thread":{"id":"thread-1","turns":[{"id":"turn-old","status":"completed"},{"id":"turn-1","status":"inProgress"}]}}}
1848"#,
1849                )
1850                .await
1851                .unwrap();
1852        });
1853
1854        session
1855            .resume_thread("thread-1".to_string(), None, None, Duration::from_secs(1))
1856            .await
1857            .unwrap();
1858
1859        let snapshot = session.snapshot();
1860        assert_eq!(snapshot.phase, SessionPhase::Running);
1861        assert_eq!(snapshot.turn_id.as_deref(), Some("turn-1"));
1862
1863        server.await.unwrap();
1864    }
1865
1866    #[tokio::test]
1867    async fn resume_thread_with_no_in_progress_turn_still_resets_to_idle() {
1868        let (session, server_reader, mut server_writer) = session();
1869        let server = tokio::spawn(async move {
1870            let mut lines = BufReader::new(server_reader).lines();
1871            let _request: Value =
1872                serde_json::from_str(&lines.next_line().await.unwrap().unwrap()).unwrap();
1873            server_writer
1874                .write_all(
1875                    br#"{"id":1,"result":{"thread":{"id":"thread-1","turns":[{"id":"turn-old","status":"completed"}]}}}
1876"#,
1877                )
1878                .await
1879                .unwrap();
1880        });
1881
1882        session
1883            .resume_thread("thread-1".to_string(), None, None, Duration::from_secs(1))
1884            .await
1885            .unwrap();
1886
1887        let snapshot = session.snapshot();
1888        assert_eq!(snapshot.phase, SessionPhase::Idle);
1889        assert!(snapshot.turn_id.is_none());
1890
1891        server.await.unwrap();
1892    }
1893
1894    /// ReAgent P1, PR #3210: a delayed/redundant `thread/started` for a
1895    /// thread that's already loaded (and already has an active turn) must
1896    /// not wipe that turn state — only a genuinely NEW thread id should
1897    /// reset it.
1898    #[tokio::test]
1899    async fn a_redundant_thread_started_for_the_same_thread_does_not_wipe_an_active_turn() {
1900        let (session, server_reader, mut server_writer) = session();
1901        let server = tokio::spawn(async move {
1902            let mut lines = BufReader::new(server_reader).lines();
1903            let _start: Value =
1904                serde_json::from_str(&lines.next_line().await.unwrap().unwrap()).unwrap();
1905            server_writer
1906                .write_all(br#"{"id":1,"result":{"thread":{"id":"thread-1"}}}
1907"#)
1908                .await
1909                .unwrap();
1910            let _turn: Value =
1911                serde_json::from_str(&lines.next_line().await.unwrap().unwrap()).unwrap();
1912            server_writer
1913                .write_all(br#"{"id":2,"result":{"turn":{"id":"turn-1"}}}
1914"#)
1915                .await
1916                .unwrap();
1917        });
1918
1919        session
1920            .start_thread(ThreadStartOptions::default(), Duration::from_secs(1))
1921            .await
1922            .unwrap();
1923        session
1924            .start_turn("hello".to_string(), Vec::new(), Duration::from_secs(1))
1925            .await
1926            .unwrap();
1927        assert_eq!(session.snapshot().phase, SessionPhase::Running);
1928
1929        session
1930            .apply_incoming(AppServerIncoming::Notification {
1931                method: "thread/started".to_string(),
1932                params: json!({"thread": {"id": "thread-1"}}),
1933            })
1934            .unwrap();
1935
1936        let snapshot = session.snapshot();
1937        assert_eq!(
1938            snapshot.phase,
1939            SessionPhase::Running,
1940            "a redundant thread/started for the SAME thread must not wipe the active turn"
1941        );
1942        assert_eq!(snapshot.turn_id.as_deref(), Some("turn-1"));
1943
1944        server.await.unwrap();
1945    }
1946
1947    #[tokio::test]
1948    async fn a_thread_started_for_a_genuinely_new_thread_still_resets_turn_state() {
1949        let (session, _reader, _writer) = session();
1950        {
1951            let mut state = session.state.lock().unwrap();
1952            state.thread_id = Some("thread-1".to_string());
1953            state.turn_id = Some("turn-1".to_string());
1954            state.phase = SessionPhase::Running;
1955        }
1956
1957        session
1958            .apply_incoming(AppServerIncoming::Notification {
1959                method: "thread/started".to_string(),
1960                params: json!({"thread": {"id": "thread-2"}}),
1961            })
1962            .unwrap();
1963
1964        let snapshot = session.snapshot();
1965        assert_eq!(snapshot.thread_id.as_deref(), Some("thread-2"));
1966        assert_eq!(snapshot.phase, SessionPhase::Idle);
1967        assert!(snapshot.turn_id.is_none());
1968    }
1969
1970    /// ReAgent P1, PR #3210 (2nd review): collapsing "interrupted" (user
1971    /// cancellation) into the same `Failed` phase as a genuine
1972    /// provider/execution error hid an expected outcome behind an error
1973    /// signal.
1974    #[tokio::test]
1975    async fn turn_completed_with_interrupted_status_maps_to_its_own_phase() {
1976        let (session, _reader, _writer) = session();
1977        {
1978            let mut state = session.state.lock().unwrap();
1979            state.thread_id = Some("thread-1".to_string());
1980            state.turn_id = Some("turn-1".to_string());
1981            state.phase = SessionPhase::Running;
1982        }
1983
1984        session
1985            .apply_incoming(AppServerIncoming::Notification {
1986                method: "turn/completed".to_string(),
1987                params: json!({
1988                    "threadId": "thread-1",
1989                    "turn": {"id": "turn-1", "status": "interrupted"},
1990                }),
1991            })
1992            .unwrap();
1993
1994        let snapshot = session.snapshot();
1995        assert_eq!(
1996            snapshot.phase,
1997            SessionPhase::Interrupted,
1998            "an interrupted (cancelled) turn must not read the same as a genuine failure"
1999        );
2000        assert!(snapshot.turn_id.is_none());
2001    }
2002
2003    #[tokio::test]
2004    async fn turn_completed_with_a_genuine_failure_still_maps_to_failed() {
2005        let (session, _reader, _writer) = session();
2006        {
2007            let mut state = session.state.lock().unwrap();
2008            state.thread_id = Some("thread-1".to_string());
2009            state.turn_id = Some("turn-1".to_string());
2010            state.phase = SessionPhase::Running;
2011        }
2012
2013        session
2014            .apply_incoming(AppServerIncoming::Notification {
2015                method: "turn/completed".to_string(),
2016                params: json!({
2017                    "threadId": "thread-1",
2018                    "turn": {"id": "turn-1", "status": "failed"},
2019                }),
2020            })
2021            .unwrap();
2022
2023        assert_eq!(session.snapshot().phase, SessionPhase::Failed);
2024    }
2025
2026    /// ReAgent P1, PR #3210 (2nd review): start_turn's check-then-act
2027    /// (read turn_id, release the lock, THEN await the request) wasn't
2028    /// atomic — nothing was reserved under the lock, so two concurrent
2029    /// calls before either got a response could both observe turn_id ==
2030    /// None and both send turn/start. `tokio::join!` polls its futures in
2031    /// argument order on their first poll; neither future reaches an
2032    /// `.await` point before the synchronous turn_starting check/set, so
2033    /// this is deterministic, not timing-dependent: the first call's
2034    /// synchronous prefix runs to completion (reserving the slot) before
2035    /// the second call's synchronous prefix ever runs.
2036    #[tokio::test]
2037    async fn concurrent_start_turn_calls_do_not_both_send_turn_start() {
2038        let (session, server_reader, mut server_writer) = session();
2039        let server = tokio::spawn(async move {
2040            let mut lines = BufReader::new(server_reader).lines();
2041            let _start: Value =
2042                serde_json::from_str(&lines.next_line().await.unwrap().unwrap()).unwrap();
2043            server_writer
2044                .write_all(br#"{"id":1,"result":{"thread":{"id":"thread-1"}}}
2045"#)
2046                .await
2047                .unwrap();
2048
2049            // Exactly one turn/start line — if the fix regressed, a second
2050            // concurrent call would send a second one here.
2051            let turn: Value =
2052                serde_json::from_str(&lines.next_line().await.unwrap().unwrap()).unwrap();
2053            assert_eq!(turn["method"], "turn/start");
2054            server_writer
2055                .write_all(br#"{"id":2,"result":{"turn":{"id":"turn-1"}}}
2056"#)
2057                .await
2058                .unwrap();
2059
2060            // Confirm nothing further arrives — a regression would send a
2061            // second turn/start request here.
2062            let extra = tokio::time::timeout(Duration::from_millis(200), lines.next_line()).await;
2063            assert!(
2064                extra.is_err(),
2065                "a second concurrent start_turn call must be rejected locally, not also sent over the wire"
2066            );
2067        });
2068
2069        session
2070            .start_thread(ThreadStartOptions::default(), Duration::from_secs(1))
2071            .await
2072            .unwrap();
2073
2074        let session_a = session.clone();
2075        let session_b = session.clone();
2076        let (result_a, result_b) = tokio::join!(
2077            session_a.start_turn("hello".to_string(), Vec::new(), Duration::from_secs(1)),
2078            session_b.start_turn("world".to_string(), Vec::new(), Duration::from_secs(1)),
2079        );
2080
2081        let results = [result_a, result_b];
2082        let ok_count = results.iter().filter(|r| r.is_ok()).count();
2083        let rejected_count = results
2084            .iter()
2085            .filter(|r| matches!(r, Err(CodexAppServerProtocolError::TurnAlreadyActive(_))))
2086            .count();
2087        assert_eq!(ok_count, 1, "exactly one of the two concurrent calls should succeed");
2088        assert_eq!(
2089            rejected_count, 1,
2090            "the other must be rejected with TurnAlreadyActive, not also sent over the wire"
2091        );
2092
2093        server.await.unwrap();
2094    }
2095
2096    #[tokio::test]
2097    async fn routes_supported_requests_without_auto_approval_and_scopes_them() {
2098        let (session, _reader, _writer) = session();
2099        {
2100            let mut state = session.state.lock().unwrap();
2101            state.thread_id = Some("thread-1".to_string());
2102            state.turn_id = Some("turn-1".to_string());
2103        }
2104        for (id, method) in [
2105            ("command", "item/commandExecution/requestApproval"),
2106            ("file", "item/fileChange/requestApproval"),
2107            ("permissions", "item/permissions/requestApproval"),
2108            ("input", "item/tool/requestUserInput"),
2109        ] {
2110            let pending = session
2111                .accept_server_request(AppServerIncoming::Request {
2112                    id: RpcId::String(id.to_string()),
2113                    method: method.to_string(),
2114                    params: json!({"threadId":"thread-1","turnId":"turn-1","itemId":id}),
2115                })
2116                .unwrap();
2117            assert_eq!(pending.method, method);
2118        }
2119        let mcp = session
2120            .accept_server_request(AppServerIncoming::Request {
2121                id: RpcId::String("mcp".to_string()),
2122                method: "mcpServer/elicitation/request".to_string(),
2123                params: json!({"message":"confirm","mode":"form","requestedSchema":{}}),
2124            })
2125            .unwrap();
2126        assert_eq!(mcp.kind, ServerRequestKind::McpElicitation);
2127        assert_eq!(session.pending_server_requests().len(), 5);
2128        assert!(matches!(
2129            session.accept_server_request(AppServerIncoming::Request {
2130                id: RpcId::String("unknown".to_string()),
2131                method: "future/request".to_string(),
2132                params: json!({})
2133            }),
2134            Err(CodexAppServerProtocolError::UnsupportedServerRequest(_))
2135        ));
2136        assert!(matches!(
2137            session.accept_server_request(AppServerIncoming::Request {
2138                id: RpcId::String("cross".to_string()),
2139                method: "item/tool/requestUserInput".to_string(),
2140                params: json!({"threadId":"thread-2","turnId":"turn-1","itemId":"x"})
2141            }),
2142            Err(CodexAppServerProtocolError::ThreadScopeMismatch { .. })
2143        ));
2144    }
2145
2146    #[tokio::test]
2147    async fn rejects_duplicate_or_unknown_decisions_and_clears_on_turn_completion() {
2148        let (session, _reader, _writer) = session();
2149        {
2150            let mut state = session.state.lock().unwrap();
2151            state.thread_id = Some("thread-1".to_string());
2152            state.turn_id = Some("turn-1".to_string());
2153        }
2154        let id = RpcId::String("approval".to_string());
2155        let incoming = AppServerIncoming::Request {
2156            id: id.clone(),
2157            method: "item/tool/requestUserInput".to_string(),
2158            params: json!({"threadId":"thread-1","turnId":"turn-1","itemId":"item-1"}),
2159        };
2160        session.accept_server_request(incoming.clone()).unwrap();
2161        assert!(matches!(
2162            session.accept_server_request(incoming),
2163            Err(CodexAppServerProtocolError::DuplicateServerRequest)
2164        ));
2165        assert!(matches!(
2166            session
2167                .respond_server_request(
2168                    &RpcId::String("missing".to_string()),
2169                    Ok(json!({})),
2170                    Duration::from_millis(10)
2171                )
2172                .await,
2173            Err(CodexAppServerProtocolError::UnknownServerRequest)
2174        ));
2175        session
2176            .apply_incoming(AppServerIncoming::Notification {
2177                method: "turn/completed".to_string(),
2178                params: json!({"threadId":"thread-1","turn":{"id":"turn-1","status":"completed"}}),
2179            })
2180            .unwrap();
2181        assert!(session.pending_server_requests().is_empty());
2182    }
2183
2184    /// ReAgent P1, PR #3212 (2nd review): item-scoped kinds (everything
2185    /// except McpElicitation) must require threadId/turnId rather than
2186    /// silently treating an omitted field as "no scope claimed" -- that
2187    /// contradicted this API's own "scoped to active thread/turn"
2188    /// fail-closed claim.
2189    #[tokio::test]
2190    async fn an_item_scoped_request_missing_thread_id_is_rejected_not_silently_queued() {
2191        let (session, _reader, _writer) = session();
2192        {
2193            let mut state = session.state.lock().unwrap();
2194            state.thread_id = Some("thread-1".to_string());
2195            state.turn_id = Some("turn-1".to_string());
2196        }
2197        assert!(matches!(
2198            session.accept_server_request(AppServerIncoming::Request {
2199                id: RpcId::String("no-scope".to_string()),
2200                method: "item/tool/requestUserInput".to_string(),
2201                params: json!({"itemId": "item-1"}),
2202            }),
2203            Err(CodexAppServerProtocolError::MissingStringField("threadId"))
2204        ));
2205        assert!(session.pending_server_requests().is_empty());
2206
2207        // McpElicitation alone stays exempt -- it genuinely has no
2208        // thread/turn context.
2209        let mcp = session
2210            .accept_server_request(AppServerIncoming::Request {
2211                id: RpcId::String("mcp".to_string()),
2212                method: "mcpServer/elicitation/request".to_string(),
2213                params: json!({"message": "confirm"}),
2214            })
2215            .unwrap();
2216        assert!(mcp.thread_id.is_none());
2217    }
2218
2219    /// ReAgent P1, PR #3212 (2nd review): a pending approval queued under a
2220    /// prior thread/turn must not remain answerable after that thread has
2221    /// been replaced -- only turn/completed cleared pending_requests
2222    /// before; start_thread, resume_thread, and a genuinely-new
2223    /// thread/started notification did not.
2224    #[tokio::test]
2225    async fn thread_transitions_clear_stale_pending_requests() {
2226        let (session, server_reader, mut server_writer) = session();
2227        let server = tokio::spawn(async move {
2228            let mut lines = BufReader::new(server_reader).lines();
2229            let _start: Value =
2230                serde_json::from_str(&lines.next_line().await.unwrap().unwrap()).unwrap();
2231            server_writer
2232                .write_all(br#"{"id":1,"result":{"thread":{"id":"thread-2"}}}
2233"#)
2234                .await
2235                .unwrap();
2236        });
2237
2238        {
2239            let mut state = session.state.lock().unwrap();
2240            state.thread_id = Some("thread-1".to_string());
2241        }
2242        session
2243            .accept_server_request(AppServerIncoming::Request {
2244                id: RpcId::String("stale".to_string()),
2245                method: "mcpServer/elicitation/request".to_string(),
2246                params: json!({"message": "confirm"}),
2247            })
2248            .unwrap();
2249        assert_eq!(session.pending_server_requests().len(), 1);
2250
2251        session
2252            .start_thread(ThreadStartOptions::default(), Duration::from_secs(1))
2253            .await
2254            .unwrap();
2255        assert!(
2256            session.pending_server_requests().is_empty(),
2257            "start_thread must clear pending requests queued under the previous thread"
2258        );
2259
2260        server.await.unwrap();
2261    }
2262
2263    /// ReAgent P2, PR #3212 (2nd review): respond_server_request checked
2264    /// pending_requests membership, then awaited the transport write,
2265    /// THEN removed the entry -- two concurrent calls for the same id
2266    /// could both pass the membership check before either removed it, so
2267    /// both would send a response and both report success. Now removed
2268    /// atomically up front; deterministic via tokio::join! the same way
2269    /// the concurrent-start_turn test is (neither future reaches an
2270    /// await point before the synchronous remove).
2271    #[tokio::test]
2272    async fn concurrent_respond_calls_for_the_same_id_do_not_both_succeed() {
2273        let (session, server_reader, mut server_writer) = session();
2274        let server = tokio::spawn(async move {
2275            let mut lines = BufReader::new(server_reader).lines();
2276            // Exactly one respond frame should be written.
2277            let _line = lines.next_line().await.unwrap().unwrap();
2278            server_writer.write_all(b"ignored\n").await.ok();
2279            let extra = tokio::time::timeout(Duration::from_millis(200), lines.next_line()).await;
2280            assert!(extra.is_err(), "a second concurrent respond call must not also write a response");
2281        });
2282
2283        {
2284            let mut state = session.state.lock().unwrap();
2285            state.thread_id = Some("thread-1".to_string());
2286        }
2287        let id = RpcId::String("approval".to_string());
2288        session
2289            .accept_server_request(AppServerIncoming::Request {
2290                id: id.clone(),
2291                method: "mcpServer/elicitation/request".to_string(),
2292                params: json!({"message": "confirm"}),
2293            })
2294            .unwrap();
2295
2296        let session_a = session.clone();
2297        let session_b = session.clone();
2298        let id_a = id.clone();
2299        let id_b = id.clone();
2300        let (result_a, result_b) = tokio::join!(
2301            session_a.respond_server_request(&id_a, Ok(json!({"approved": true})), Duration::from_secs(1)),
2302            session_b.respond_server_request(&id_b, Ok(json!({"approved": true})), Duration::from_secs(1)),
2303        );
2304        let results = [result_a, result_b];
2305        let ok_count = results.iter().filter(|r| r.is_ok()).count();
2306        let unknown_count = results
2307            .iter()
2308            .filter(|r| matches!(r, Err(CodexAppServerProtocolError::UnknownServerRequest)))
2309            .count();
2310        assert_eq!(ok_count, 1, "exactly one of the two concurrent respond calls should succeed");
2311        assert_eq!(unknown_count, 1, "the other must see it already gone, not also send a response");
2312
2313        server.abort();
2314    }
2315
2316    /// ReAgent P1, PR #3212 (3rd review): before any turn had started (or
2317    /// after turn/completed cleared turn_id back to None), a request
2318    /// claiming an arbitrary/stale turnId passed the old ensure_scopes
2319    /// check trivially, since that helper only compares when state.turn_id
2320    /// is Some. accept_server_request must fail closed when there is no
2321    /// active thread/turn to scope the request to, not merely skip the
2322    /// check.
2323    #[tokio::test]
2324    async fn a_request_claiming_a_thread_or_turn_is_rejected_when_none_is_active() {
2325        let (session, _reader, _writer) = session();
2326        assert!(matches!(
2327            session.accept_server_request(AppServerIncoming::Request {
2328                id: RpcId::String("no-thread".to_string()),
2329                method: "item/tool/requestUserInput".to_string(),
2330                params: json!({"threadId": "thread-1", "turnId": "turn-1", "itemId": "x"}),
2331            }),
2332            Err(CodexAppServerProtocolError::ThreadNotLoaded)
2333        ));
2334
2335        {
2336            let mut state = session.state.lock().unwrap();
2337            state.thread_id = Some("thread-1".to_string());
2338        }
2339        assert!(matches!(
2340            session.accept_server_request(AppServerIncoming::Request {
2341                id: RpcId::String("no-turn".to_string()),
2342                method: "item/tool/requestUserInput".to_string(),
2343                params: json!({"threadId": "thread-1", "turnId": "turn-1", "itemId": "x"}),
2344            }),
2345            Err(CodexAppServerProtocolError::TurnNotActive)
2346        ));
2347        assert!(session.pending_server_requests().is_empty());
2348    }
2349
2350    /// ReAgent P1, PR #3212 (3rd review): respond_server_request's
2351    /// failure-path reinsert didn't check whether the thread/turn context
2352    /// was still current, so a stale approval could be resurrected into a
2353    /// brand-new session/turn after a transition raced the in-flight
2354    /// transport write.
2355    #[tokio::test]
2356    async fn a_failed_respond_is_not_resurrected_after_the_turn_it_was_queued_under_ends() {
2357        let (session, server_reader, server_writer) = session();
2358
2359        {
2360            let mut state = session.state.lock().unwrap();
2361            state.thread_id = Some("thread-1".to_string());
2362            state.turn_id = Some("turn-1".to_string());
2363        }
2364        let id = RpcId::String("approval".to_string());
2365        session
2366            .accept_server_request(AppServerIncoming::Request {
2367                id: id.clone(),
2368                method: "item/tool/requestUserInput".to_string(),
2369                params: json!({"threadId": "thread-1", "turnId": "turn-1", "itemId": "x"}),
2370            })
2371            .unwrap();
2372
2373        // Drop the entire peer side of the transport so the write inside
2374        // respond_server_request fails, standing in for "the transport
2375        // write raced a state transition and lost" without a timing-
2376        // dependent sleep.
2377        drop(server_reader);
2378        drop(server_writer);
2379
2380        // Simulate the turn ending while that write is in flight: clear
2381        // pending_requests and the active turn the same way turn/completed
2382        // does.
2383        session.state.lock().unwrap().pending_requests.clear();
2384        session.state.lock().unwrap().turn_id = None;
2385
2386        let result = session
2387            .respond_server_request(&id, Ok(json!({"approved": true})), Duration::from_secs(1))
2388            .await;
2389        assert!(result.is_err(), "the write should fail once the transport is closed");
2390        assert!(
2391            session.pending_server_requests().is_empty(),
2392            "a stale approval must not be resurrected once its turn has ended"
2393        );
2394    }
2395
2396    /// ReAgent P2, PR #3212 (3rd review): pending_requests had no size cap,
2397    /// so a buggy or adversarial App Server could grow it unboundedly by
2398    /// sending validly-scoped approval requests.
2399    #[tokio::test]
2400    async fn accept_server_request_rejects_once_the_pending_cap_is_reached() {
2401        let (session, _reader, _writer) = session();
2402        {
2403            let mut state = session.state.lock().unwrap();
2404            state.thread_id = Some("thread-1".to_string());
2405        }
2406        for i in 0..MAX_PENDING_SERVER_REQUESTS {
2407            session
2408                .accept_server_request(AppServerIncoming::Request {
2409                    id: RpcId::String(format!("mcp-{i}")),
2410                    method: "mcpServer/elicitation/request".to_string(),
2411                    params: json!({"message": "confirm"}),
2412                })
2413                .unwrap();
2414        }
2415        assert!(matches!(
2416            session.accept_server_request(AppServerIncoming::Request {
2417                id: RpcId::String("one-too-many".to_string()),
2418                method: "mcpServer/elicitation/request".to_string(),
2419                params: json!({"message": "confirm"}),
2420            }),
2421            Err(CodexAppServerProtocolError::TooManyPendingRequests(
2422                MAX_PENDING_SERVER_REQUESTS
2423            ))
2424        ));
2425    }
2426
2427    /// ReAgent P1, PR #3212 (4th review): a request carrying turnId but no
2428    /// threadId (McpElicitation may supply either field alone) fell through
2429    /// both `if let Some(thread) = &thread_id` and the `(Some, Some)` tuple
2430    /// match untouched, so a claimed-but-stale turnId was never validated
2431    /// and the request was queued unconditionally. Same asymmetry mirrored
2432    /// in respond_server_request's reinsert-on-failure check.
2433    #[tokio::test]
2434    async fn a_turn_only_request_is_still_scoped_to_the_active_turn() {
2435        let (session, _reader, _writer) = session();
2436        assert!(matches!(
2437            session.accept_server_request(AppServerIncoming::Request {
2438                id: RpcId::String("turn-only-no-turn".to_string()),
2439                method: "mcpServer/elicitation/request".to_string(),
2440                params: json!({"turnId": "turn-1"}),
2441            }),
2442            Err(CodexAppServerProtocolError::TurnNotActive)
2443        ));
2444
2445        {
2446            let mut state = session.state.lock().unwrap();
2447            state.turn_id = Some("turn-1".to_string());
2448        }
2449        assert!(matches!(
2450            session.accept_server_request(AppServerIncoming::Request {
2451                id: RpcId::String("turn-only-stale".to_string()),
2452                method: "mcpServer/elicitation/request".to_string(),
2453                params: json!({"turnId": "turn-stale"}),
2454            }),
2455            Err(CodexAppServerProtocolError::TurnScopeMismatch { .. })
2456        ));
2457        assert!(session.pending_server_requests().is_empty());
2458
2459        let pending = session
2460            .accept_server_request(AppServerIncoming::Request {
2461                id: RpcId::String("turn-only-current".to_string()),
2462                method: "mcpServer/elicitation/request".to_string(),
2463                params: json!({"turnId": "turn-1"}),
2464            })
2465            .unwrap();
2466        assert_eq!(pending.turn_id.as_deref(), Some("turn-1"));
2467    }
2468
2469    /// See a_turn_only_request_is_still_scoped_to_the_active_turn -- the
2470    /// same asymmetry existed on the reinsert side: a pending entry with
2471    /// turn_id but no thread_id was unconditionally resurrected on a
2472    /// transport-write failure (`(None, _) => true`) regardless of
2473    /// whether that turn was still active.
2474    #[tokio::test]
2475    async fn a_failed_turn_only_respond_is_not_resurrected_after_its_turn_ends() {
2476        let (session, server_reader, server_writer) = session();
2477        {
2478            let mut state = session.state.lock().unwrap();
2479            state.turn_id = Some("turn-1".to_string());
2480        }
2481        let id = RpcId::String("turn-only".to_string());
2482        session
2483            .accept_server_request(AppServerIncoming::Request {
2484                id: id.clone(),
2485                method: "mcpServer/elicitation/request".to_string(),
2486                params: json!({"turnId": "turn-1"}),
2487            })
2488            .unwrap();
2489
2490        drop(server_reader);
2491        drop(server_writer);
2492        session.state.lock().unwrap().pending_requests.clear();
2493        session.state.lock().unwrap().turn_id = None;
2494
2495        let result = session
2496            .respond_server_request(&id, Ok(json!({"approved": true})), Duration::from_secs(1))
2497            .await;
2498        assert!(result.is_err(), "the write should fail once the transport is closed");
2499        assert!(
2500            session.pending_server_requests().is_empty(),
2501            "a stale turn-only approval must not be resurrected once its turn has ended"
2502        );
2503    }
2504
2505    /// ReAgent P1, PR #3212 (5th review): respond_server_request removed the
2506    /// pending entry synchronously, then awaited the transport write. If
2507    /// the calling future were dropped/cancelled while suspended at that
2508    /// await (a caller-side select!/timeout racing the write), Rust never
2509    /// runs code after an await point that's never resumed -- neither the
2510    /// success path nor the old failure-path reinsert would run, silently
2511    /// stranding the entry with no response ever sent. A 1-byte duplex
2512    /// buffer with nothing reading the other side guarantees the write
2513    /// stays suspended, so aborting the task deterministically exercises
2514    /// the drop-mid-await path rather than racing a timing window.
2515    ///
2516    /// Superseded by the 6th review's WriteOutcomeTracker (see
2517    /// app_server.rs): by the time the write is stuck on this 1-byte
2518    /// buffer, the frame has already been handed to run_writer, which will
2519    /// deliver it regardless of the cancellation below -- so the correct
2520    /// behavior is now the opposite of what this test originally asserted:
2521    /// the entry must NOT be reinserted, or a retry could send a second,
2522    /// duplicate response for the same id. The pre-queue case (cancelled
2523    /// before the frame is ever handed to the writer, still genuinely safe
2524    /// to retry) is covered directly at the transport level by
2525    /// write_outcome_tracker_stays_safe_to_retry_when_the_write_never_starts
2526    /// in app_server.rs, since reaching it deterministically from here
2527    /// would require blocking the transport's internal outbound queue,
2528    /// which this layer has no access to.
2529    #[tokio::test]
2530    async fn a_respond_future_cancelled_after_the_write_is_queued_does_not_reinsert() {
2531        let (client, _server) = duplex(1);
2532        let (client_reader, client_writer) = tokio::io::split(client);
2533        let transport = Arc::new(AppServerTransport::new(
2534            client_reader,
2535            client_writer,
2536            Default::default(),
2537        ));
2538        let session = Arc::new(CodexAppServerSession::new(transport));
2539        {
2540            let mut state = session.state.lock().unwrap();
2541            state.thread_id = Some("thread-1".to_string());
2542            state.turn_id = Some("turn-1".to_string());
2543        }
2544        let id = RpcId::String("approval".to_string());
2545        session
2546            .accept_server_request(AppServerIncoming::Request {
2547                id: id.clone(),
2548                method: "item/tool/requestUserInput".to_string(),
2549                params: json!({"threadId": "thread-1", "turnId": "turn-1", "itemId": "x"}),
2550            })
2551            .unwrap();
2552
2553        let task_session = session.clone();
2554        let task_id = id.clone();
2555        let handle = tokio::spawn(async move {
2556            task_session
2557                .respond_server_request(
2558                    &task_id,
2559                    Ok(json!({"approved": true})),
2560                    Duration::from_secs(30),
2561                )
2562                .await
2563        });
2564
2565        // The synchronous remove() runs on the task's first poll, before
2566        // it ever reaches the write's await point -- give it a bounded
2567        // number of scheduling turns to get there rather than assuming
2568        // one yield is always enough.
2569        for _ in 0..100 {
2570            if session.pending_server_requests().is_empty() {
2571                break;
2572            }
2573            tokio::task::yield_now().await;
2574        }
2575        assert!(
2576            session.pending_server_requests().is_empty(),
2577            "the entry should already be removed while the write is in flight"
2578        );
2579
2580        handle.abort();
2581        let _ = handle.await;
2582
2583        assert!(
2584            session.pending_server_requests().is_empty(),
2585            "the frame was already queued for delivery before cancellation -- reinserting now \
2586             would risk a retry sending a second, duplicate response for the same id"
2587        );
2588    }
2589
2590    /// AccountLoginOptions lacked `rename_all_fields = "camelCase"`, so
2591    /// ApiKey and Chatgpt fields serialized as api_key/app_brand/etc
2592    /// instead of the pinned schema's apiKey/appBrand/etc -- API-key login
2593    /// was guaranteed to fail against the real App Server despite passing
2594    /// every existing test, since none of them inspected the serialized
2595    /// JSON shape.
2596    #[test]
2597    fn account_login_options_serialize_with_camel_case_fields() {
2598        assert_eq!(
2599            serde_json::to_value(AccountLoginOptions::ApiKey {
2600                api_key: "sk-test".to_string()
2601            })
2602            .unwrap(),
2603            json!({"type": "apiKey", "apiKey": "sk-test"})
2604        );
2605        assert_eq!(
2606            serde_json::to_value(AccountLoginOptions::Chatgpt {
2607                app_brand: Some("codex".to_string()),
2608                codex_streamlined_login: Some(true),
2609                use_hosted_login_success_page: Some(false),
2610            })
2611            .unwrap(),
2612            json!({
2613                "type": "chatgpt",
2614                "appBrand": "codex",
2615                "codexStreamlinedLogin": true,
2616                "useHostedLoginSuccessPage": false,
2617            })
2618        );
2619        assert_eq!(
2620            serde_json::to_value(AccountLoginOptions::ChatgptDeviceCode).unwrap(),
2621            json!({"type": "chatgptDeviceCode"})
2622        );
2623    }
2624
2625    /// The pinned schema's ThreadListCwdFilter is `string | string[]`, not
2626    /// an arbitrary JSON value -- typed as the actual union instead of a
2627    /// bare `Value` so a caller can't hand it something the App Server
2628    /// will reject.
2629    #[test]
2630    fn thread_list_cwd_filter_serializes_as_the_schema_s_string_or_array_union() {
2631        assert_eq!(
2632            serde_json::to_value(ThreadListCwdFilter::Single("C:\\work".to_string())).unwrap(),
2633            json!("C:\\work")
2634        );
2635        assert_eq!(
2636            serde_json::to_value(ThreadListCwdFilter::Many(vec![
2637                "C:\\work".to_string(),
2638                "C:\\other".to_string()
2639            ]))
2640            .unwrap(),
2641            json!(["C:\\work", "C:\\other"])
2642        );
2643    }
2644}