1use 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
29const SESSION_TIMEOUT_SECS: u64 = 600;
33
34const FINISHED_RETENTION_SECS: u64 = 300;
38
39const 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 Pending,
53 UrlAvailable { auth_url: String },
56 CodeEmitted {
58 device_code: String,
59 verification_url: String,
60 },
61 Success {
64 bundle_id: String,
65 email: Option<String>,
68 #[serde(skip_serializing_if = "Option::is_none")]
74 #[ts(optional)]
75 account_id: Option<String>,
76 },
77 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 captured_url: Option<String>,
95 captured_device_code: Option<(String, String)>,
96 captured_email: Option<String>,
97 started_at: Instant,
98 finished_at: Option<Instant>,
101 exclusive_key: Option<String>,
104 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 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#[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 pub auth_url: Option<String>,
153}
154
155#[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#[derive(Default)]
171struct ProcessRefs {
172 drain_tasks: HashMap<String, tokio::task::JoinHandle<()>>,
173 stdin_senders: HashMap<String, tokio::sync::mpsc::Sender<String>>,
174 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 pub fn start_session(&self, provider_id: String, exclusive_key: Option<String>) -> StartSessionResult {
200 let session_id = format!("auth-{}", uuid::Uuid::new_v4());
201 let superseded: Vec<String> = {
205 let mut sessions = self.sessions.lock().unwrap();
206 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 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 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 if session.captured_email.is_none() {
278 session.captured_email = email.clone();
279 }
280 }
281 }
282 Some(m)
283 }
284
285 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 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 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 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 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 pub fn cancel_session(&self, session_id: &str) -> bool {
393 self.end_session(session_id, "cancelled by user".to_string())
394 }
395
396 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 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 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 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 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 if self.is_terminal(session_id) {
451 self.stop_process(session_id);
452 }
453 }
454
455 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 if self.is_terminal(session_id) {
470 self.stop_process(session_id);
471 }
472 }
473
474 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 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 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 #[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 #[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 #[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
551use 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 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 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 #[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 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 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 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 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 let _newer = m.start_session("claude".to_string(), dir);
847 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 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 #[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 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}