Skip to main content

agentmux_srv_core/identity/
auth_session.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! In-memory manager for pre-launch OAuth sessions.
5//!
6//! See `docs/specs/SPEC_PRE_LAUNCH_OAUTH_FLOW_2026_05_14.md` §7.
7//!
8//! Each session represents one user-initiated "Connect with OAuth"
9//! attempt. The frontend creates a session via `start_session`,
10//! polls via `poll_session`, optionally pastes a callback URL (the
11//! `auth.submitcallback` handler forwards it via `send_to_stdin`),
12//! and cancels via `cancel_session`.
13//!
14//! PR A scope: the session-state machine + per-line stdout
15//! interpretation + lifecycle (timeout, cancel, cleanup). The
16//! actual CLI spawn lives in the handler (`server/identity_auth_spawn.rs`,
17//! so it can use AppState's CLI resolver) but emits frames into this
18//! module via `record_line` / `finish_success` / `finish_failure`.
19//! That keeps this module pure and testable.
20
21use std::collections::HashMap;
22use std::sync::{Arc, Mutex};
23use std::time::{Duration, Instant};
24
25use serde::{Deserialize, Serialize};
26
27use super::auth_patterns::{match_line, AuthPatternMatch};
28
29/// Wall-clock cap on a single auth session. Past this, the session
30/// transitions to `Failed` and its CLI is killed, whether or not anyone is
31/// polling it (`sweep`).
32const SESSION_TIMEOUT_SECS: u64 = 600;
33
34/// How long a finished session stays pollable before `sweep` drops it. The
35/// UI stops polling once it sees the terminal state, so this only has to
36/// outlast one poll interval; it's generous.
37const FINISHED_RETENTION_SECS: u64 = 300;
38
39/// How often the sweeper runs (`spawn_sweeper`).
40const SWEEP_INTERVAL_SECS: u64 = 30;
41
42#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ts_rs::TS)]
43#[ts(export, export_to = "../../../frontend/types/rpc/")]
44#[serde(
45    tag = "status",
46    rename_all = "kebab-case",
47    rename_all_fields = "camelCase"
48)]
49pub enum AuthSessionStatus {
50    /// CLI is spawned, we're waiting for it to emit either a URL,
51    /// a device code, or a success line.
52    Pending,
53    /// CLI emitted an OAuth URL. Frontend surfaces this to the user
54    /// for paste-into-browser if auto-open failed.
55    UrlAvailable { auth_url: String },
56    /// CLI emitted a device code. Frontend renders it prominently.
57    CodeEmitted {
58        device_code: String,
59        verification_url: String,
60    },
61    /// CLI authenticated successfully. The handler captured the
62    /// credentials and created the bundle.
63    Success {
64        bundle_id: String,
65        /// Best-effort — extracted from the CLI's "logged in as..."
66        /// line. Used by the frontend to name the bundle.
67        email: Option<String>,
68        /// Set only for a direct-account session (issue #1624 PR-C
69        /// Part B) — the newly-minted or reused `IdentityAccount` id,
70        /// with no bundle involved. `bundle_id` is an empty string in
71        /// that mode; existing bundle-mode callers never populate
72        /// this field, so it's skipped on the wire when absent.
73        #[serde(skip_serializing_if = "Option::is_none")]
74        #[ts(optional)]
75        account_id: Option<String>,
76    },
77    /// Auth attempt failed. `error` is a short human-readable phrase
78    /// suitable to render inline.
79    Failed { error: String },
80}
81
82impl AuthSessionStatus {
83    pub fn is_terminal(&self) -> bool {
84        matches!(self, Self::Success { .. } | Self::Failed { .. })
85    }
86}
87
88#[derive(Debug)]
89struct Session {
90    provider_id: String,
91    status: AuthSessionStatus,
92    /// Last URL or code we surfaced — kept across polls so the
93    /// frontend can repaint without re-receiving on every tick.
94    captured_url: Option<String>,
95    captured_device_code: Option<(String, String)>,
96    captured_email: Option<String>,
97    started_at: Instant,
98    /// When the session reached a terminal state; `sweep` drops it
99    /// `FINISHED_RETENTION_SECS` later.
100    finished_at: Option<Instant>,
101    /// The account directory this login writes to. Only one live login per
102    /// directory: starting another cancels this one (`start_session`).
103    exclusive_key: Option<String>,
104    /// All stdout/stderr lines we've seen, in order. Used for the
105    /// diagnostic "show me what the CLI said" panel and the
106    /// integration tests.
107    transcript: Vec<String>,
108}
109
110impl Session {
111    fn new(provider_id: String, exclusive_key: Option<String>) -> Self {
112        Self {
113            provider_id,
114            status: AuthSessionStatus::Pending,
115            captured_url: None,
116            captured_device_code: None,
117            captured_email: None,
118            started_at: Instant::now(),
119            finished_at: None,
120            exclusive_key,
121            transcript: Vec::new(),
122        }
123    }
124
125    /// Move to a terminal state, unless already in one. True if it moved.
126    fn finish(&mut self, status: AuthSessionStatus) -> bool {
127        if self.status.is_terminal() {
128            return false;
129        }
130        self.status = status;
131        self.finished_at = Some(Instant::now());
132        true
133    }
134
135    fn timed_out(&self) -> bool {
136        self.started_at.elapsed() > Duration::from_secs(SESSION_TIMEOUT_SECS)
137    }
138}
139
140/// Public-facing handle returned by `start_session`. The handler
141/// owns the spawned CLI's child handle (so it can stdin-inject the
142/// pasted callback URL and kill on cancel); this manager owns the
143/// session state.
144#[derive(Debug, Clone, Serialize, ts_rs::TS)]
145#[ts(export, export_to = "../../../frontend/types/rpc/")]
146#[serde(rename_all = "camelCase")]
147pub struct StartSessionResult {
148    pub session_id: String,
149    /// If the CLI emitted the URL synchronously (before this call
150    /// returns) — rare but happens for fast providers. Usually
151    /// `None`; the frontend polls and picks it up on the first tick.
152    pub auth_url: Option<String>,
153}
154
155/// Snapshot returned by `poll_session`. Mirrors `AuthSessionStatus`
156/// plus the provider id for renderer dispatch.
157#[derive(Debug, Clone, Serialize, ts_rs::TS)]
158#[ts(export, export_to = "../../../frontend/types/rpc/")]
159#[serde(rename_all = "camelCase")]
160pub struct PollSessionResult {
161    pub provider_id: String,
162    #[serde(flatten)]
163    pub status: AuthSessionStatus,
164}
165
166/// Per-session "process refs" — the join handle for the drain task
167/// and the stdin sender for the callback-paste-back path. Held
168/// outside the `sessions` Mutex so cancellation can `.abort()` /
169/// drop without holding the state lock across an await.
170#[derive(Default)]
171struct ProcessRefs {
172    drain_tasks: HashMap<String, tokio::task::JoinHandle<()>>,
173    stdin_senders: HashMap<String, tokio::sync::mpsc::Sender<String>>,
174    /// PID of a PTY-backed auth subprocess. Aborting `drain_tasks`
175    /// can't reach into a `spawn_blocking` wait task, so cancel_session
176    /// kills the child by PID for PTY transports.
177    pty_pids: HashMap<String, u32>,
178}
179
180#[derive(Default)]
181pub struct AuthSessionManager {
182    sessions: Arc<Mutex<HashMap<String, Session>>>,
183    process_refs: Arc<Mutex<ProcessRefs>>,
184}
185
186impl AuthSessionManager {
187    pub fn new() -> Self {
188        Self::default()
189    }
190
191    /// Allocate a new session id and store the initial Pending state.
192    /// The caller (handler) is responsible for spawning the CLI and
193    /// feeding stdout lines into `record_line`.
194    ///
195    /// `exclusive_key` is the account directory the login writes to. A live
196    /// session for the same directory is cancelled first: two CLIs logging
197    /// in to one directory at once race on its credential files (the
198    /// desktop host's single login slot has the same rule).
199    pub fn start_session(&self, provider_id: String, exclusive_key: Option<String>) -> StartSessionResult {
200        let session_id = format!("auth-{}", uuid::Uuid::new_v4());
201        // Replacing the live session and inserting this one happen under one
202        // lock, so two concurrent starts for the same directory can't both
203        // find nothing to replace. The replaced CLIs are stopped after it.
204        let superseded: Vec<String> = {
205            let mut sessions = self.sessions.lock().unwrap();
206            // Every session for the directory: one already finished (say a
207            // success line was seen) can still have its CLI running.
208            let superseded: Vec<String> = match exclusive_key.as_deref() {
209                Some(key) => sessions
210                    .iter_mut()
211                    .filter(|(_, s)| s.exclusive_key.as_deref() == Some(key))
212                    .map(|(id, s)| {
213                        s.finish(AuthSessionStatus::Failed {
214                            error: "replaced by a newer sign-in for the same account".to_string(),
215                        });
216                        id.clone()
217                    })
218                    .collect(),
219                None => Vec::new(),
220            };
221            sessions.insert(session_id.clone(), Session::new(provider_id, exclusive_key));
222            superseded
223        };
224        for id in &superseded {
225            self.stop_process(id);
226        }
227        StartSessionResult {
228            session_id,
229            auth_url: None,
230        }
231    }
232
233    /// Feed a single line of CLI stdout/stderr into the session.
234    /// Returns the pattern match (if any) so the handler can decide
235    /// to forward the URL elsewhere (e.g. broker event).
236    pub fn record_line(&self, session_id: &str, line: &str) -> Option<AuthPatternMatch> {
237        let mut sessions = self.sessions.lock().unwrap();
238        let session = sessions.get_mut(session_id)?;
239        session.transcript.push(line.to_string());
240        let m = match_line(&session.provider_id, line)?;
241        match &m {
242            AuthPatternMatch::OAuthUrl(url) => {
243                if session.captured_url.is_none() {
244                    session.captured_url = Some(url.clone());
245                    if matches!(session.status, AuthSessionStatus::Pending) {
246                        session.status = AuthSessionStatus::UrlAvailable {
247                            auth_url: url.clone(),
248                        };
249                    }
250                }
251            }
252            AuthPatternMatch::DeviceCode {
253                code,
254                verification_url,
255            } => {
256                // A CLI that prints the code on its own line (codex) leaves the link to the line before.
257                let verification_url = if verification_url.is_empty() { session.captured_url.clone().unwrap_or_default() } else { verification_url.clone() };
258                if session.captured_device_code.is_none() && !verification_url.is_empty() {
259                    session.captured_device_code =
260                        Some((code.clone(), verification_url.clone()));
261                    if matches!(
262                        session.status,
263                        AuthSessionStatus::Pending | AuthSessionStatus::UrlAvailable { .. }
264                    ) {
265                        session.status = AuthSessionStatus::CodeEmitted {
266                            device_code: code.clone(),
267                            verification_url: verification_url.clone(),
268                        };
269                    }
270                }
271            }
272            AuthPatternMatch::LoginSuccess { email } => {
273                // Don't transition to Success here — the handler is
274                // responsible for confirming with authCheckCommand
275                // AND persisting the bundle row before declaring
276                // success. We just record the email for later.
277                if session.captured_email.is_none() {
278                    session.captured_email = email.clone();
279                }
280            }
281        }
282        Some(m)
283    }
284
285    /// Handler-side completion hook. Called when the CLI exits or
286    /// auth check confirms success. Transitions the session to a
287    /// terminal state. `account_id` is `None` for the legacy
288    /// bundle-mode path; `Some(id)` for a direct-account session
289    /// (issue #1624 PR-C Part B) — see `AuthSessionStatus::Success`.
290    pub fn finish_success(
291        &self,
292        session_id: &str,
293        bundle_id: String,
294        account_id: Option<String>,
295    ) -> bool {
296        let mut sessions = self.sessions.lock().unwrap();
297        let Some(session) = sessions.get_mut(session_id) else {
298            return false;
299        };
300        let email = session.captured_email.clone();
301        session.finish(AuthSessionStatus::Success {
302            bundle_id,
303            email,
304            account_id,
305        })
306    }
307
308    pub fn finish_failure(&self, session_id: &str, error: String) -> bool {
309        let mut sessions = self.sessions.lock().unwrap();
310        let Some(session) = sessions.get_mut(session_id) else {
311            return false;
312        };
313        session.finish(AuthSessionStatus::Failed { error })
314    }
315
316    /// Poll a session's current status. A session past
317    /// SESSION_TIMEOUT_SECS is ended first (Failed, CLI killed).
318    pub fn poll_session(&self, session_id: &str) -> Option<PollSessionResult> {
319        let timed_out = {
320            let sessions = self.sessions.lock().unwrap();
321            let session = sessions.get(session_id)?;
322            !session.status.is_terminal() && session.timed_out()
323        };
324        if timed_out {
325            self.end_session(session_id, timeout_error());
326        }
327        let sessions = self.sessions.lock().unwrap();
328        let session = sessions.get(session_id)?;
329        Some(PollSessionResult {
330            provider_id: session.provider_id.clone(),
331            status: session.status.clone(),
332        })
333    }
334
335    /// End sessions past their timeout (Failed, CLI killed) and drop
336    /// finished ones nobody has polled for FINISHED_RETENTION_SECS. Runs
337    /// every SWEEP_INTERVAL_SECS (`spawn_sweeper`), so a login whose UI went
338    /// away doesn't leave its CLI running or its session behind.
339    pub fn sweep(&self) {
340        let (expired, stale): (Vec<String>, Vec<String>) = {
341            let sessions = self.sessions.lock().unwrap();
342            let expired = sessions
343                .iter()
344                .filter(|(_, s)| !s.status.is_terminal() && s.timed_out())
345                .map(|(id, _)| id.clone())
346                .collect();
347            let stale = sessions
348                .iter()
349                .filter(|(_, s)| {
350                    s.finished_at
351                        .is_some_and(|t| t.elapsed() > Duration::from_secs(FINISHED_RETENTION_SECS))
352                })
353                .map(|(id, _)| id.clone())
354                .collect();
355            (expired, stale)
356        };
357        for id in &expired {
358            tracing::info!(session_id = %id, "auth session timed out: ending it");
359            self.end_session(id, timeout_error());
360        }
361        if !stale.is_empty() {
362            // A finished session's CLI can still be running (a success line
363            // seen, no exit yet): stop it before its session, and with it the
364            // directory key a later sign-in would find it by, goes.
365            for id in &stale {
366                self.stop_process(id);
367            }
368            let mut sessions = self.sessions.lock().unwrap();
369            for id in &stale {
370                sessions.remove(id);
371            }
372        }
373    }
374
375    /// Run `sweep` every SWEEP_INTERVAL_SECS for as long as srv runs.
376    pub fn spawn_sweeper(self: &Arc<Self>) {
377        let mgr = Arc::clone(self);
378        tokio::spawn(async move {
379            let mut tick = tokio::time::interval(Duration::from_secs(SWEEP_INTERVAL_SECS));
380            loop {
381                tick.tick().await;
382                mgr.sweep();
383            }
384        });
385    }
386
387    /// Cancel a session: transition state to Failed + abort the
388    /// spawned drain task (which kills the child via kill_on_drop).
389    /// Returns true if the state transition happened (false on
390    /// unknown / already-terminal session — the process refs are
391    /// torn down either way so a re-fired cancel is a no-op).
392    pub fn cancel_session(&self, session_id: &str) -> bool {
393        self.end_session(session_id, "cancelled by user".to_string())
394    }
395
396    /// Fail a session with `error` and stop its CLI: abort the drain task
397    /// (the pipe path's child goes with it, `kill_on_drop`), drop its stdin,
398    /// and kill a PTY child by PID. True if the state changed; the process
399    /// refs go either way, so ending a session twice is harmless.
400    fn end_session(&self, session_id: &str, error: String) -> bool {
401        let transitioned = self.finish_failure(session_id, error);
402        self.stop_process(session_id);
403        transitioned
404    }
405
406    /// Stop a session's CLI and drop its process refs: abort the drain task
407    /// (the pipe path's child goes with it, `kill_on_drop`), drop its stdin,
408    /// and kill a PTY child by PID.
409    fn stop_process(&self, session_id: &str) {
410        let mut refs = self.process_refs.lock().unwrap();
411        if let Some(handle) = refs.drain_tasks.remove(session_id) {
412            handle.abort();
413        }
414        refs.stdin_senders.remove(session_id);
415        // PTY transport: abort() doesn't reach the spawn_blocking
416        // wait task, so kill the child by PID. Pipes path doesn't
417        // need this — its tokio Child uses kill_on_drop.
418        if let Some(pid) = refs.pty_pids.remove(session_id) {
419            if let Err(e) = kill_pid(pid) {
420                tracing::warn!(pid, session_id, error = %e, "end_session: kill_pid failed");
421            } else {
422                tracing::info!(pid, session_id, "end_session: PTY child killed");
423            }
424        }
425    }
426
427    /// Has this session ended (or gone)? A login confirmed after its session
428    /// was replaced, cancelled or timed out must not be saved: a newer
429    /// sign-in owns the directory now.
430    pub fn ended(&self, session_id: &str) -> bool {
431        self.is_terminal(session_id)
432    }
433
434    fn is_terminal(&self, session_id: &str) -> bool {
435        self.sessions
436            .lock()
437            .unwrap()
438            .get(session_id)
439            .is_none_or(|s| s.status.is_terminal())
440    }
441
442    /// Register the PID of a PTY-backed auth subprocess so
443    /// `cancel_session` can terminate it. Called by `auth.start`
444    /// after spawning a PTY login (in addition to `attach_process`).
445    pub fn attach_pty_pid(&self, session_id: &str, pid: u32) {
446        self.process_refs.lock().unwrap().pty_pids.insert(session_id.to_string(), pid);
447        // Registered first, checked second: a session ended (replaced,
448        // cancelled, timed out) before this, whose end found nothing to stop,
449        // has its CLI stopped here; one ended after finds it registered.
450        if self.is_terminal(session_id) {
451            self.stop_process(session_id);
452        }
453    }
454
455    /// Register the drain task + stdin sender for a session. Called
456    /// by the handler immediately after spawning the CLI.
457    pub fn attach_process(
458        &self,
459        session_id: &str,
460        drain_task: tokio::task::JoinHandle<()>,
461        stdin_sender: tokio::sync::mpsc::Sender<String>,
462    ) {
463        {
464            let mut refs = self.process_refs.lock().unwrap();
465            refs.drain_tasks.insert(session_id.to_string(), drain_task);
466            refs.stdin_senders.insert(session_id.to_string(), stdin_sender);
467        }
468        // As in `attach_pty_pid`: a session that already ended stops now.
469        if self.is_terminal(session_id) {
470            self.stop_process(session_id);
471        }
472    }
473
474    /// Forward a pasted callback URL to the spawned CLI's stdin.
475    /// Returns true if the session has an attached stdin sender;
476    /// false if the session never spawned a CLI or the sender's
477    /// receiver was dropped.
478    pub async fn send_to_stdin(&self, session_id: &str, line: String) -> bool {
479        let sender = {
480            let refs = self.process_refs.lock().unwrap();
481            refs.stdin_senders.get(session_id).cloned()
482        };
483        match sender {
484            Some(s) => s.send(line).await.is_ok(),
485            None => false,
486        }
487    }
488
489    /// Drop a session's process refs without aborting them. Called
490    /// by the drain task itself when it exits normally so terminal
491    /// state lookups still work but the resources are reclaimed.
492    pub fn detach_process(&self, session_id: &str) {
493        let mut refs = self.process_refs.lock().unwrap();
494        refs.drain_tasks.remove(session_id);
495        refs.stdin_senders.remove(session_id);
496        refs.pty_pids.remove(session_id);
497    }
498
499    /// The account email scraped from this session's login transcript, if the
500    /// provider printed one.
501    ///
502    /// Read *before* `finish_success`, which consumes the session — the
503    /// account is persisted first (`identity_auth_spawn`) and needs the email
504    /// at that point to record it on the account
505    /// (`SPEC_ACCOUNT_EMAIL_IN_ARMORY_2026_09_23.md`). `None` when the
506    /// provider reported no email, which is not an error: providers whose CLI
507    /// does not surface one simply have no email to show.
508    pub fn captured_email(&self, session_id: &str) -> Option<String> {
509        self.sessions
510            .lock()
511            .unwrap()
512            .get(session_id)
513            .and_then(|s| s.captured_email.clone())
514    }
515
516    /// Read the full transcript of captured stdout/stderr lines.
517    /// Used by integration tests; exposed for completeness even
518    /// though no production caller currently reads it.
519    #[allow(dead_code)]
520    pub fn transcript(&self, session_id: &str) -> Option<Vec<String>> {
521        self.sessions
522            .lock()
523            .unwrap()
524            .get(session_id)
525            .map(|s| s.transcript.clone())
526    }
527
528    /// Inject a force-elapsed `started_at` for the given session —
529    /// test helper so we can exercise the timeout transition without
530    /// actually waiting SESSION_TIMEOUT_SECS.
531    #[cfg(test)]
532    fn force_age(&self, session_id: &str) {
533        if let Some(s) = self.sessions.lock().unwrap().get_mut(session_id) {
534            s.started_at = Instant::now() - Duration::from_secs(SESSION_TIMEOUT_SECS + 1);
535        }
536    }
537
538    /// Test helper: make a finished session look FINISHED_RETENTION_SECS old.
539    #[cfg(test)]
540    fn force_finished_long_ago(&self, session_id: &str) {
541        if let Some(s) = self.sessions.lock().unwrap().get_mut(session_id) {
542            s.finished_at = Some(Instant::now() - Duration::from_secs(FINISHED_RETENTION_SECS + 1));
543        }
544    }
545}
546
547fn timeout_error() -> String {
548    format!("auth session timed out after {SESSION_TIMEOUT_SECS}s")
549}
550
551/// Best-effort kill of a child process by PID — `SIGTERM` on Unix,
552/// `taskkill /F /T /PID` on Windows. This used to be a private copy that
553/// described itself as a "mirror of the cef-side helper"; both now share
554/// `agentmux_common::process::kill_pid`.
555use agentmux_common::process::kill_pid;
556
557#[cfg(test)]
558mod tests {
559    use super::*;
560
561    fn mgr() -> AuthSessionManager {
562        AuthSessionManager::new()
563    }
564
565    #[test]
566    fn start_creates_pending_session() {
567        let m = mgr();
568        let r = m.start_session("claude".to_string(), None);
569        assert!(!r.session_id.is_empty());
570        assert!(r.auth_url.is_none());
571        let p = m.poll_session(&r.session_id).expect("session exists");
572        assert_eq!(p.provider_id, "claude");
573        assert!(matches!(p.status, AuthSessionStatus::Pending));
574    }
575
576    #[test]
577    fn url_line_transitions_to_url_available() {
578        let m = mgr();
579        let r = m.start_session("claude".to_string(), None);
580        let _ = m.record_line(
581            &r.session_id,
582            "Open https://console.anthropic.com/oauth/authorize?state=xyz",
583        );
584        let p = m.poll_session(&r.session_id).unwrap();
585        match p.status {
586            AuthSessionStatus::UrlAvailable { auth_url } => {
587                assert!(auth_url.contains("anthropic.com/oauth"));
588            }
589            other => panic!("expected UrlAvailable, got {other:?}"),
590        }
591    }
592
593    #[test]
594    fn device_code_line_transitions_to_code_emitted() {
595        let m = mgr();
596        let r = m.start_session("copilot".to_string(), None);
597        let _ = m.record_line(&r.session_id, "! Copy your one-time code: ABCD-1234");
598        let p = m.poll_session(&r.session_id).unwrap();
599        match p.status {
600            AuthSessionStatus::CodeEmitted {
601                device_code,
602                verification_url,
603            } => {
604                assert_eq!(device_code, "ABCD-1234");
605                assert_eq!(verification_url, "https://github.com/login/device");
606            }
607            other => panic!("expected CodeEmitted, got {other:?}"),
608        }
609    }
610
611    #[test]
612    fn login_success_line_does_not_transition_state_alone() {
613        // The CLI saying "logged in" isn't enough — the handler
614        // confirms via authCheck before declaring Success.
615        let m = mgr();
616        let r = m.start_session("claude".to_string(), None);
617        let _ = m.record_line(&r.session_id, "Successfully logged in as asaf@example.com");
618        let p = m.poll_session(&r.session_id).unwrap();
619        // Still pending — handler hasn't called finish_success yet.
620        assert!(matches!(p.status, AuthSessionStatus::Pending));
621    }
622
623    #[test]
624    fn finish_success_carries_email_from_transcript() {
625        let m = mgr();
626        let r = m.start_session("claude".to_string(), None);
627        let _ = m.record_line(&r.session_id, "Successfully logged in as asaf@example.com");
628        assert!(m.finish_success(&r.session_id, "bundle-1".to_string(), None));
629        let p = m.poll_session(&r.session_id).unwrap();
630        match p.status {
631            AuthSessionStatus::Success { bundle_id, email, account_id } => {
632                assert_eq!(bundle_id, "bundle-1");
633                assert_eq!(email.as_deref(), Some("asaf@example.com"));
634                assert_eq!(account_id, None);
635            }
636            other => panic!("expected Success, got {other:?}"),
637        }
638    }
639
640    #[test]
641    fn cancel_transitions_to_failed() {
642        let m = mgr();
643        let r = m.start_session("claude".to_string(), None);
644        assert!(m.cancel_session(&r.session_id));
645        let p = m.poll_session(&r.session_id).unwrap();
646        match p.status {
647            AuthSessionStatus::Failed { error } => assert!(error.contains("cancelled")),
648            other => panic!("expected Failed, got {other:?}"),
649        }
650    }
651
652    #[test]
653    // FLAKY on low-uptime machines (CI runners): force_age does
654    // `Instant::now() - Duration::from_secs(SESSION_TIMEOUT_SECS + 1)`, which
655    // PANICS when monotonic uptime is less than the timeout (can't construct an
656    // Instant that far in the past). Passes locally (high uptime), fails on a
657    // freshly-booted CI runner. Production is unaffected — it never subtracts from
658    // Instant. Ignored to unblock CI; fix = make the timeout mockable (deadline
659    // model / injectable clock) so force_age doesn't underflow.
660    // SPEC_CI_TEST_RUNNER_2026_06_22.md §6.4.
661    #[ignore = "force_age underflows Instant on low-uptime CI runners; make the timeout mockable, then un-ignore"]
662    fn timeout_transitions_pending_to_failed_on_poll() {
663        let m = mgr();
664        let r = m.start_session("claude".to_string(), None);
665        m.force_age(&r.session_id);
666        let p = m.poll_session(&r.session_id).unwrap();
667        match p.status {
668            AuthSessionStatus::Failed { error } => assert!(error.contains("timed out")),
669            other => panic!("expected timeout Failed, got {other:?}"),
670        }
671    }
672
673    #[test]
674    fn terminal_states_cannot_be_re_transitioned() {
675        let m = mgr();
676        let r = m.start_session("claude".to_string(), None);
677        assert!(m.finish_success(&r.session_id, "bundle-1".to_string(), None));
678        // Second finish_failure is a no-op.
679        assert!(!m.finish_failure(&r.session_id, "should be ignored".to_string()));
680        let p = m.poll_session(&r.session_id).unwrap();
681        assert!(matches!(p.status, AuthSessionStatus::Success { .. }));
682    }
683
684    #[test]
685    fn multiple_url_lines_keep_the_first_url() {
686        // If the CLI emits the URL again later (some do), we don't
687        // overwrite — the first URL is what the user saw + pasted.
688        let m = mgr();
689        let r = m.start_session("claude".to_string(), None);
690        let _ = m.record_line(
691            &r.session_id,
692            "Open https://console.anthropic.com/oauth/authorize?state=first",
693        );
694        let _ = m.record_line(
695            &r.session_id,
696            "Open https://console.anthropic.com/oauth/authorize?state=second",
697        );
698        let p = m.poll_session(&r.session_id).unwrap();
699        match p.status {
700            AuthSessionStatus::UrlAvailable { auth_url } => {
701                assert!(auth_url.contains("state=first"));
702            }
703            _ => panic!("expected UrlAvailable"),
704        }
705    }
706
707    #[test]
708    fn status_serializes_with_camelcase_field_names() {
709        // Codex P2 on PR #840: the per-variant fields used to
710        // serialize as auth_url / device_code / etc. (snake_case)
711        // while the rest of the wire is camelCase. Now uniformly
712        // camelCase via rename_all_fields.
713        let s = AuthSessionStatus::UrlAvailable {
714            auth_url: "https://example.com/oauth".to_string(),
715        };
716        let v = serde_json::to_value(&s).unwrap();
717        assert_eq!(
718            v,
719            serde_json::json!({
720                "status": "url-available",
721                "authUrl": "https://example.com/oauth"
722            })
723        );
724
725        let s = AuthSessionStatus::CodeEmitted {
726            device_code: "ABCD-1234".to_string(),
727            verification_url: "https://github.com/login/device".to_string(),
728        };
729        let v = serde_json::to_value(&s).unwrap();
730        assert_eq!(
731            v,
732            serde_json::json!({
733                "status": "code-emitted",
734                "deviceCode": "ABCD-1234",
735                "verificationUrl": "https://github.com/login/device"
736            })
737        );
738
739        let s = AuthSessionStatus::Success {
740            bundle_id: "bundle-1".to_string(),
741            email: Some("asaf@example.com".to_string()),
742            account_id: None,
743        };
744        let v = serde_json::to_value(&s).unwrap();
745        assert_eq!(
746            v,
747            serde_json::json!({
748                "status": "success",
749                "bundleId": "bundle-1",
750                "email": "asaf@example.com"
751            })
752        );
753
754        // Direct-account mode (issue #1624 PR-C Part B) — accountId
755        // appears on the wire; bundleId is present but empty.
756        let s = AuthSessionStatus::Success {
757            bundle_id: String::new(),
758            email: Some("asaf@example.com".to_string()),
759            account_id: Some("acc-1".to_string()),
760        };
761        let v = serde_json::to_value(&s).unwrap();
762        assert_eq!(
763            v,
764            serde_json::json!({
765                "status": "success",
766                "bundleId": "",
767                "email": "asaf@example.com",
768                "accountId": "acc-1"
769            })
770        );
771    }
772
773    #[test]
774    fn unknown_session_polls_to_none() {
775        let m = mgr();
776        assert!(m.poll_session("does-not-exist").is_none());
777    }
778
779    #[test]
780    fn transcript_records_all_lines_including_non_matching() {
781        let m = mgr();
782        let r = m.start_session("claude".to_string(), None);
783        let _ = m.record_line(&r.session_id, "Starting auth flow...");
784        let _ = m.record_line(&r.session_id, "Open https://console.anthropic.com/oauth/authorize");
785        let _ = m.record_line(&r.session_id, "Waiting for callback...");
786        let t = m.transcript(&r.session_id).unwrap();
787        assert_eq!(t.len(), 3);
788        assert_eq!(t[0], "Starting auth flow...");
789        assert!(t[1].contains("anthropic.com/oauth"));
790        assert_eq!(t[2], "Waiting for callback...");
791    }
792
793    #[tokio::test]
794    async fn sweep_ends_a_timed_out_session_nobody_polls_and_drops_its_stdin() {
795        let m = mgr();
796        let r = m.start_session("claude".to_string(), None);
797        let (tx, _rx) = tokio::sync::mpsc::channel::<String>(1);
798        m.attach_process(&r.session_id, tokio::spawn(async {}), tx);
799        m.force_age(&r.session_id);
800
801        m.sweep();
802
803        let status = m.sessions.lock().unwrap().get(&r.session_id).unwrap().status.clone();
804        assert!(matches!(status, AuthSessionStatus::Failed { ref error } if error.contains("timed out")), "{status:?}");
805        assert!(!m.send_to_stdin(&r.session_id, "code".to_string()).await, "stdin should be gone");
806    }
807
808    #[test]
809    fn sweep_drops_a_session_finished_long_ago_and_keeps_a_recent_one() {
810        let m = mgr();
811        let old = m.start_session("claude".to_string(), None);
812        let recent = m.start_session("claude".to_string(), None);
813        m.finish_failure(&old.session_id, "x".to_string());
814        m.finish_failure(&recent.session_id, "x".to_string());
815        m.force_finished_long_ago(&old.session_id);
816
817        m.sweep();
818
819        assert!(m.poll_session(&old.session_id).is_none());
820        assert!(m.poll_session(&recent.session_id).is_some());
821    }
822
823    #[test]
824    fn a_new_login_for_the_same_account_dir_replaces_the_live_one() {
825        let m = mgr();
826        let dir = Some("/home/u/.agentmux/accounts/claude-1".to_string());
827        let first = m.start_session("claude".to_string(), dir.clone());
828        let other = m.start_session("claude".to_string(), Some("/elsewhere".to_string()));
829        let second = m.start_session("claude".to_string(), dir);
830
831        let first_status = m.poll_session(&first.session_id).unwrap().status;
832        assert!(
833            matches!(first_status, AuthSessionStatus::Failed { ref error } if error.contains("replaced")),
834            "{first_status:?}"
835        );
836        assert_eq!(m.poll_session(&second.session_id).unwrap().status, AuthSessionStatus::Pending);
837        assert_eq!(m.poll_session(&other.session_id).unwrap().status, AuthSessionStatus::Pending);
838    }
839
840    #[tokio::test]
841    async fn a_cli_attached_after_its_session_was_replaced_is_stopped_at_once() {
842        let m = mgr();
843        let dir = Some("/home/u/.agentmux/accounts/claude-1".to_string());
844        let older = m.start_session("claude".to_string(), dir.clone());
845        // The newer start replaces the older session before its CLI exists.
846        let _newer = m.start_session("claude".to_string(), dir);
847        // The older request's CLI arrives afterwards.
848        let (tx, _rx) = tokio::sync::mpsc::channel::<String>(1);
849        m.attach_process(&older.session_id, tokio::spawn(std::future::pending::<()>()), tx);
850
851        assert!(!m.send_to_stdin(&older.session_id, "code".to_string()).await, "the replaced CLI keeps no stdin");
852        assert!(m.process_refs.lock().unwrap().drain_tasks.get(&older.session_id).is_none());
853    }
854
855    #[tokio::test]
856    async fn a_new_login_stops_the_cli_of_a_finished_session_for_the_same_dir() {
857        let m = mgr();
858        let dir = Some("/home/u/.agentmux/accounts/claude-1".to_string());
859        let done = m.start_session("claude".to_string(), dir.clone());
860        let (tx, _rx) = tokio::sync::mpsc::channel::<String>(1);
861        m.attach_process(&done.session_id, tokio::spawn(std::future::pending::<()>()), tx);
862        // Success was recorded, but its CLI hasn't exited yet.
863        m.finish_success(&done.session_id, String::new(), Some("acct".to_string()));
864
865        let _newer = m.start_session("claude".to_string(), dir);
866
867        assert!(m.process_refs.lock().unwrap().drain_tasks.get(&done.session_id).is_none(), "its CLI was stopped");
868        assert!(matches!(m.poll_session(&done.session_id).unwrap().status, AuthSessionStatus::Success { .. }), "a finished session keeps its result");
869    }
870
871    #[tokio::test]
872    async fn sweep_stops_a_still_running_cli_before_dropping_its_finished_session() {
873        let m = mgr();
874        let r = m.start_session("claude".to_string(), Some("/d".to_string()));
875        let (tx, _rx) = tokio::sync::mpsc::channel::<String>(1);
876        m.attach_process(&r.session_id, tokio::spawn(std::future::pending::<()>()), tx);
877        m.finish_success(&r.session_id, String::new(), None);
878        m.force_finished_long_ago(&r.session_id);
879
880        m.sweep();
881
882        assert!(m.poll_session(&r.session_id).is_none());
883        assert!(m.process_refs.lock().unwrap().drain_tasks.get(&r.session_id).is_none(), "its CLI was stopped");
884    }
885
886    #[test]
887    fn ended_is_true_once_replaced_and_for_an_unknown_session() {
888        let m = mgr();
889        let first = m.start_session("claude".to_string(), Some("/d".to_string()));
890        assert!(!m.ended(&first.session_id));
891        let _second = m.start_session("claude".to_string(), Some("/d".to_string()));
892        assert!(m.ended(&first.session_id));
893        assert!(m.ended("auth-nope"));
894    }
895
896    /// Codex prints the link and, on the next line, the code: the session reports both together.
897    #[test]
898    fn a_device_code_on_its_own_line_takes_the_link_from_the_line_before() {
899        let m = AuthSessionManager::new();
900        let id = m.start_session("codex".into(), None).session_id;
901        // A code with no link yet is not a device code.
902        m.record_line(&id, "RC63-52E85");
903        assert_eq!(m.poll_session(&id).unwrap().status, AuthSessionStatus::Pending);
904        m.record_line(&id, "   https://auth.openai.com/codex/device");
905        assert!(matches!(m.poll_session(&id).unwrap().status, AuthSessionStatus::UrlAvailable { .. }));
906        m.record_line(&id, "   RC63-52E85");
907        assert_eq!(
908            m.poll_session(&id).unwrap().status,
909            AuthSessionStatus::CodeEmitted { device_code: "RC63-52E85".into(), verification_url: "https://auth.openai.com/codex/device".into() }
910        );
911    }
912}