Skip to main content

agentmux_srv/server/
identity_auth_spawn_steps.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The steps of `spawn_auth_cli`: one login session's state (`Login`), the piped-stdio run and the PTY run of the
5//! provider CLI, and how each ends the session (success saved, failure, or ended meanwhile).
6
7#[cfg(windows)]
8use agentmux_common::win32::NoWindow;
9use std::collections::HashMap;
10use std::sync::atomic::{AtomicBool, Ordering};
11use tokio::sync::mpsc::{Receiver, Sender};
12
13use super::*;
14use crate::identity::auth_session::AuthSessionManager;
15use crate::server::identity_auth_persist::persist_oauth_success;
16
17/// One login session: where it is recorded, where it saves, and the CLI that runs it and checks it.
18pub(super) struct Login {
19    pub(super) mgr: Arc<AuthSessionManager>,
20    pub(super) mstore: Arc<Store>,
21    pub(super) identity_store: Arc<Store>,
22    pub(super) broker: Arc<Broker>,
23    pub(super) session_id: String,
24    pub(super) provider_id: String,
25    pub(super) into_bundle_id: Option<String>,
26    pub(super) bundle_dir: Option<String>,
27    pub(super) direct_account: bool,
28    pub(super) account_id: String,
29    pub(super) cli_path: String,
30    pub(super) auth_login_args: Vec<String>,
31    pub(super) auth_check_args: Vec<String>,
32    pub(super) auth_env: HashMap<String, String>,
33}
34
35/// The session ended (replaced, cancelled, timed out) before its login could be saved.
36struct Ended;
37
38impl Login {
39    /// Whether the provider's auth check passes now (`confirm_authenticated`).
40    async fn confirmed(&self) -> bool {
41        confirm_authenticated(&self.cli_path, &self.auth_check_args, &self.auth_env).await
42    }
43
44    /// Save the account and finish the session as a success. `false` when the session ended first: nothing is saved.
45    fn save_success(&self) -> bool {
46        // Persist the standalone OAuthConfigDir account
47        // (always direct-account mode now). If `bundle_dir`
48        // (the account's own isolation dir) failed to
49        // resolve at spawn, persist_oauth_success skips
50        // persistence and the session still succeeds.
51        // Read the email BEFORE finish_success consumes the
52        // session — see AuthSessionManager::captured_email.
53        // Ended meanwhile (replaced, cancelled, timed out): a newer sign-in
54        // may own the directory, so this login is not saved.
55        if self.mgr.ended(&self.session_id) {
56            tracing::info!(session_id = %self.session_id, "auth.spawn: session ended before its login was saved; not saving it");
57            return false;
58        }
59        let login_email = self.mgr.captured_email(&self.session_id);
60        let (bundle_id, account_id) = persist_oauth_success(
61            &self.mstore,
62            &self.identity_store,
63            &self.broker,
64            self.direct_account,
65            &self.account_id,
66            self.into_bundle_id.as_deref(),
67            &self.provider_id,
68            self.bundle_dir.as_deref(),
69            &self.session_id,
70            login_email.as_deref(),
71        );
72        self.mgr.finish_success(&self.session_id, bundle_id, account_id);
73        true
74    }
75}
76
77/// The piped-stdio run: the task is attached to the session so cancelling it aborts the CLI.
78pub(super) fn spawn_piped(login: Arc<Login>, stdin_tx: Sender<String>, stdin_rx: Receiver<String>) {
79    let handle = tokio::spawn(run_piped(login.clone(), stdin_rx));
80    login.mgr.attach_process(&login.session_id, handle, stdin_tx);
81}
82
83async fn run_piped(login: Arc<Login>, stdin_rx: Receiver<String>) {
84    let (mgr, session_id) = (&login.mgr, &login.session_id);
85    tracing::info!(
86        session_id = %session_id,
87        provider_id = %login.provider_id,
88        cli_path = %login.cli_path,
89        auth_login_args = ?login.auth_login_args,
90        "auth.spawn: launching provider CLI"
91    );
92
93    let Some(mut child) = spawn_piped_child(&login) else {
94        return;
95    };
96
97    let stdout = child
98        .stdout
99        .take()
100        .expect("piped stdout");
101    let stderr = child
102        .stderr
103        .take()
104        .expect("piped stderr");
105    let stdin = child
106        .stdin
107        .take()
108        .expect("piped stdin");
109
110    let stdin_writer = forward_stdin(stdin, stdin_rx);
111
112    // Shared between drain + post-exit. The drain sets it after
113    // persisting on a LoginSuccess match; the post-exit transition
114    // block (`settle_piped_exit`) checks it and skips its entire success path if
115    // already transitioned — without this guard the drain's
116    // persist + post-exit's persist both ran on every successful
117    // OAuth, producing orphan IdentityAccount rows (each `Uuid::new_v4`)
118    // and duplicate `identityaccounts:changed` publishes.
119    // Reagent P1 on #981.
120    let success_transitioned = Arc::new(AtomicBool::new(false));
121    let stdout_drain = drain_stdout(login.clone(), stdout, Arc::clone(&success_transitioned));
122    let stderr_drain = drain_stderr(login.clone(), stderr);
123
124    // Wait for the child to exit (or for our task to be aborted
125    // by cancel_session — in which case kill_on_drop handles the
126    // child).
127    let exit = child.wait().await;
128    tracing::info!(session_id = %session_id, exit = ?exit, "auth.spawn: child exited");
129
130    // Let stdout/stderr drains catch any final lines.
131    let _ = stdout_drain.await;
132    let _ = stderr_drain.await;
133    // Stdin writer exits when the tx side is dropped (after this
134    // task ends) — abort defensively in case it's blocked on a
135    // pending receive.
136    stdin_writer.abort();
137
138    // Final transition if we haven't already hit Success on the
139    // login-pattern path. Re-run authCheck because some CLIs exit
140    // cleanly without printing a "logged in as" line.
141    //
142    // Skip the entire block when the drain has already transitioned
143    // (LoginSuccess pattern matched + confirm_authenticated + persist
144    // ran). Without this guard, persist_oauth_success would fire a
145    // second time on every successful OAuth — a fresh IdentityAccount
146    // UUID would be upserted and the broker would re-publish the
147    // accounts-changed event. Reagent P1 on #981.
148    if !success_transitioned.load(Ordering::Acquire) && settle_piped_exit(&login, exit).await.is_err() {
149        return;
150    }
151
152    mgr.detach_process(session_id);
153}
154
155/// Spawn the provider CLI with piped stdio. `None` (the session already failed) when it cannot be started.
156fn spawn_piped_child(login: &Login) -> Option<tokio::process::Child> {
157    use std::process::Stdio;
158    use tokio::process::Command;
159    let (mgr, session_id, cli_path) = (&login.mgr, &login.session_id, &login.cli_path);
160
161    // Spawn the CLI. kill_on_drop guarantees cleanup if our
162    // task is aborted (cancel path).
163    let mut cmd = Command::new(cli_path);
164    // A provider OAuth CLI is a third-party, network-connected binary.
165    // Without this it inherits srv's whole AGENTMUX_* environment — channel,
166    // data dir, cache dir, and this instance's API endpoint. Stricter than
167    // the pane policy: not even the in-pane helper keep-set applies here.
168    // (ReAgent P0, round 2, on PR #3326.)
169    crate::backend::pane_env::sanitize_external_command(&mut cmd);
170    cmd.args(&login.auth_login_args)
171        .envs(&login.auth_env)
172        .stdin(Stdio::piped())
173        .stdout(Stdio::piped())
174        .stderr(Stdio::piped())
175        .kill_on_drop(true);
176    // CREATE_NO_WINDOW: console-flash suppression, see crates/common/src/cli.rs
177    #[cfg(windows)]
178    {
179        cmd.no_window();
180    }
181    let child = match cmd.spawn()
182    {
183        Ok(c) => {
184            tracing::info!(
185                session_id = %session_id,
186                pid = ?c.id(),
187                "auth.spawn: child started"
188            );
189            c
190        }
191        Err(e) => {
192            tracing::error!(
193                session_id = %session_id,
194                error = %e,
195                "auth.spawn: Command::spawn failed"
196            );
197            mgr.finish_failure(
198                session_id,
199                format!("spawn `{cli_path}` failed: {e}"),
200            );
201            mgr.detach_process(session_id);
202            return None;
203        }
204    };
205    Some(child)
206}
207
208/// Forward pasted callback URLs to the CLI's stdin until the sender is dropped.
209fn forward_stdin(mut stdin: tokio::process::ChildStdin, mut stdin_rx: Receiver<String>) -> tokio::task::JoinHandle<()> {
210    use tokio::io::AsyncWriteExt;
211    // Stdin writer — forwards callback URLs (pasted back by the
212    // user when browser auto-open failed) into the CLI process.
213    tokio::spawn(async move {
214        while let Some(line) = stdin_rx.recv().await {
215            if stdin.write_all(line.as_bytes()).await.is_err() {
216                break;
217            }
218            if stdin.write_all(b"\n").await.is_err() {
219                break;
220            }
221            let _ = stdin.flush().await;
222        }
223    })
224}
225
226/// Feed stdout into the session; on a login-success line that the auth check confirms, save the account.
227fn drain_stdout(login: Arc<Login>, stdout: tokio::process::ChildStdout, success_transitioned: Arc<AtomicBool>) -> tokio::task::JoinHandle<()> {
228    use tokio::io::{AsyncBufReadExt, BufReader};
229    // Stdout drain — line-by-line into the session manager. When
230    // we see a login-success pattern, confirm via authCheckCommand
231    // and transition to Success. Don't break the loop — some CLIs
232    // continue printing after the success line.
233    tokio::spawn(async move {
234        let mut lines = BufReader::new(stdout).lines();
235        while let Ok(Some(line)) = lines.next_line().await {
236            // NOT logging the raw line — OAuth providers print
237            // auth URLs / callback codes / device codes on stdout
238            // and even debug-level logs would persist those into
239            // ~/.agentmux/logs/. Length-only is enough for "the
240            // CLI emitted something" diagnostics. Reagent P2 on #847.
241            tracing::debug!(session_id = %login.session_id, bytes = line.len(), "auth.spawn: stdout line");
242            let m = login.mgr.record_line(&login.session_id, &line);
243            if !success_transitioned.load(Ordering::Acquire)
244                && matches!(
245                    m,
246                    Some(crate::identity::auth_patterns::AuthPatternMatch::LoginSuccess { .. })
247                )
248                && login.confirmed().await
249            {
250                if !login.save_success() {
251                    return;
252                }
253                success_transitioned.store(true, Ordering::Release);
254            }
255        }
256    })
257}
258
259/// Feed stderr into the session: some CLIs print the OAuth URL there.
260fn drain_stderr(login: Arc<Login>, stderr: tokio::process::ChildStderr) -> tokio::task::JoinHandle<()> {
261    use tokio::io::{AsyncBufReadExt, BufReader};
262    // Stderr drain — same matcher path. Some CLIs emit the OAuth
263    // URL on stderr (verbose logging style).
264    tokio::spawn(async move {
265        let mut lines = BufReader::new(stderr).lines();
266        while let Ok(Some(line)) = lines.next_line().await {
267            // Same redaction rationale as `drain_stdout`.
268            tracing::debug!(session_id = %login.session_id, bytes = line.len(), "auth.spawn: stderr line");
269            let _ = login.mgr.record_line(&login.session_id, &line);
270        }
271    })
272}
273
274/// End the session by how the CLI exited, when its output did not already: `Err` when the session ended first.
275async fn settle_piped_exit(login: &Login, exit: std::io::Result<std::process::ExitStatus>) -> Result<(), Ended> {
276    let (mgr, session_id) = (&login.mgr, &login.session_id);
277    match exit {
278        Ok(s) if s.success() => {
279            if login.confirmed().await {
280                if !login.save_success() {
281                    return Err(Ended);
282                }
283            } else {
284                mgr.finish_failure(session_id, "CLI exited 0 but authentication check failed".to_string());
285            }
286        }
287        Ok(s) => {
288            mgr.finish_failure(session_id, format!("CLI exited with status {s}"));
289        }
290        Err(e) => {
291            mgr.finish_failure(session_id, format!("wait error: {e}"));
292        }
293    }
294    Ok(())
295}
296
297/// PTY-backed variant of spawn_auth_cli. Used for providers whose auth
298/// subcommand bails on `isatty()==0` (currently OpenClaw). Mirrors the
299/// pipes path's lifecycle: spawn → drain → confirm → finish_success or
300/// finish_failure → detach. Stdout+stderr are merged on the PTY side;
301/// `record_line` doesn't care which stream a line came from.
302///
303/// Same OAuth-success invariant as the pipes path — once `bundle_dir`
304/// (the account's own isolation dir) resolves and `confirm_authenticated`
305/// returns true, persists a standalone `SecretRef::OAuthConfigDir`
306/// account before `finish_success` — see `spawn_auth_cli`'s doc comment.
307pub(super) fn spawn_auth_cli_pty(login: Arc<Login>, stdin_tx: Sender<String>, stdin_rx: Receiver<String>) {
308    tracing::info!(
309        session_id = %login.session_id,
310        provider_id = %login.provider_id,
311        cli_path = %login.cli_path,
312        auth_login_args = ?login.auth_login_args,
313        "auth.spawn (PTY): launching provider CLI"
314    );
315
316    let Some(started) = start_pty(&login) else {
317        return;
318    };
319    let handle = tokio::spawn(run_pty(login.clone(), started, stdin_rx));
320    login.mgr.attach_process(&login.session_id, handle, stdin_tx);
321}
322
323/// The PTY, the child on it, and the ends of the PTY the run reads and writes.
324struct Started {
325    child: Box<dyn portable_pty::Child + Send + Sync>,
326    pair: portable_pty::PtyPair,
327    reader: Box<dyn std::io::Read + Send>,
328    writer: Arc<std::sync::Mutex<Box<dyn std::io::Write + Send>>>,
329}
330
331/// Allocate the PTY, spawn the provider CLI on it and register its PID. `None` (the session already failed) when
332/// any of that cannot be done.
333fn start_pty(login: &Login) -> Option<Started> {
334    use portable_pty::CommandBuilder;
335    let (mgr, session_id, cli_path) = (&login.mgr, &login.session_id, &login.cli_path);
336
337    // Allocate the PTY, build the command, spawn the child, and
338    // register the PID — all synchronously, BEFORE the async drain/
339    // wait task and BEFORE `attach_process`. That way no
340    // `cancel_session` racing with the spawn can find a registered
341    // handle but a missing PID; either the PID is registered first
342    // (cancel can kill), or the early-return path fired and there
343    // is no child to kill.
344    let pair = open_pty(login)?;
345
346    // On Windows, resolve past the npm `.cmd`/`.bat` shim: CommandBuilder on the
347    // raw shim path goes through `cmd.exe /c`, which hangs under a real ConPTY
348    // (the desktop host's login PTY found this first). `None` means the shim
349    // matched no known npm shape: fail rather than fall back to the same hang.
350    #[cfg(windows)]
351    let (spawn_program, spawn_prefix_args) = match agentmux_common::resolve_cli_spawn_target(&cli_path) {
352        Some(target) => target,
353        None => {
354            mgr.finish_failure(session_id, format!("could not resolve .cmd/.bat shim for spawn: {cli_path}"));
355            mgr.detach_process(session_id);
356            return None;
357        }
358    };
359    #[cfg(not(windows))]
360    let (spawn_program, spawn_prefix_args) = (cli_path.clone(), Vec::<String>::new());
361    let mut cmd = CommandBuilder::new(&spawn_program);
362    // Same as the non-PTY path (`spawn_piped_child`): CommandBuilder seeds from vars_os(), so
363    // without this the provider CLI inherits the full instance identity.
364    crate::backend::pane_env::sanitize_external_pty_command(&mut cmd);
365    for a in &spawn_prefix_args {
366        cmd.arg(a);
367    }
368    for a in &login.auth_login_args {
369        cmd.arg(a);
370    }
371    for (k, v) in &login.auth_env {
372        cmd.env(k, v);
373    }
374    if let Ok(cwd) = std::env::current_dir() {
375        cmd.cwd(cwd);
376    }
377
378    let child = match pair.slave.spawn_command(cmd) {
379        Ok(c) => c,
380        Err(e) => {
381            tracing::error!(
382                session_id = %session_id,
383                error = %e,
384                "auth.spawn (PTY): spawn_command failed"
385            );
386            mgr.finish_failure(session_id, format!("PTY spawn `{cli_path}` failed: {e}"));
387            mgr.detach_process(session_id);
388            return None;
389        }
390    };
391
392    if let Some(pid) = child.process_id() {
393        mgr.attach_pty_pid(session_id, pid);
394    }
395
396    let reader = match pair.master.try_clone_reader() {
397        Ok(r) => r,
398        Err(e) => {
399            tracing::error!(session_id = %session_id, error = %e, "auth.spawn (PTY): try_clone_reader failed");
400            mgr.finish_failure(session_id, format!("PTY reader: {e}"));
401            mgr.detach_process(session_id);
402            return None;
403        }
404    };
405    let writer = match pair.master.take_writer() {
406        Ok(w) => Arc::new(std::sync::Mutex::new(w)),
407        Err(e) => {
408            tracing::error!(session_id = %session_id, error = %e, "auth.spawn (PTY): take_writer failed");
409            mgr.finish_failure(session_id, format!("PTY writer: {e}"));
410            mgr.detach_process(session_id);
411            return None;
412        }
413    };
414    Some(Started { child, pair, reader, writer })
415}
416
417async fn run_pty(login: Arc<Login>, started: Started, mut stdin_rx: Receiver<String>) {
418    let Started { child, pair, reader, writer } = started;
419    // Stdin writer: forward callback URLs from the manager into
420    // the child's PTY input. portable_pty's master writer is sync;
421    // wrap each write in `block_in_place` so the blocking IO
422    // doesn't starve the tokio reactor when the PTY input buffer
423    // is full.
424    // Answers the cursor-position query (`ESC[6n`) Claude blocks on (issue
425    // #2429) through the same writer, from the drain's thread.
426    let dsr_writer = Arc::clone(&writer);
427    let answer_dsr = move || {
428        use std::io::Write;
429        if let Ok(mut w) = dsr_writer.lock() {
430            let _ = w.write_all(agentmux_common::login_pty::DSR_CURSOR_POSITION_REPLY);
431            let _ = w.flush();
432        }
433    };
434    let stdin_writer_handle = tokio::spawn(async move {
435        while let Some(line) = stdin_rx.recv().await {
436            let res = tokio::task::block_in_place(|| {
437                use std::io::Write;
438                let Ok(mut writer) = writer.lock() else {
439                    return Err(std::io::Error::other("PTY writer lock poisoned"));
440                };
441                writer
442                    .write_all(line.as_bytes())
443                    .and_then(|_| writer.write_all(b"\n"))
444                    .and_then(|_| writer.flush())
445            });
446            if res.is_err() {
447                break;
448            }
449        }
450    });
451
452    // Shared with the post-exit fallback block below — same pattern
453    // as the pipes path. Drain's detached `Handle::current().spawn`
454    // task does the persist + finish_success; the drain sets this
455    // atomic BEFORE returning so the outer's check sees it. The
456    // detached task may still be in flight when the outer checks
457    // (PTY drain returns on EOF, the persist task runs async) — that
458    // is fine because the OUTER would only re-persist if the atomic
459    // is false, which it never is once the drain matched the
460    // LoginSuccess pattern. Reagent P1 on #981.
461    let success_transitioned = Arc::new(AtomicBool::new(false));
462    let drain_handle = pty_drain(login.clone(), reader, answer_dsr, Arc::clone(&success_transitioned));
463
464    // Wait for the child in a blocking task. pair (master + slave)
465    // moves into the closure so its destructor runs AFTER
466    // child.wait() — ConPTY contract on Windows.
467    let wait_handle = tokio::task::spawn_blocking(move || {
468        let mut child = child;
469        let exit = child.wait();
470        drop(pair);
471        exit
472    });
473
474    let exit = wait_handle.await;
475    tracing::info!(session_id = %login.session_id, exit = ?exit, "auth.spawn (PTY): child exited");
476
477    // Await the drain itself, THEN its optional detached
478    // confirm/persist task. Both have to complete before the
479    // post-exit check — otherwise outer might see atomic=false
480    // (detached still confirming), run its fallback persist, AND
481    // the detached's persist also runs → the original double-
482    // persist race re-opens. Reagent P1 follow-up on #981.
483    let detached = drain_handle.await.ok().flatten();
484    if let Some(h) = detached {
485        let _ = h.await;
486    }
487    stdin_writer_handle.abort();
488
489    // Final transition fallback — some CLIs exit cleanly without
490    // emitting a login-success line that record_line recognizes.
491    //
492    // Skip the whole block when the drain already transitioned —
493    // same double-persist guard as the pipes path. Reagent P1 on
494    // #981.
495    if !success_transitioned.load(Ordering::Acquire) && settle_pty_exit(&login, exit).await.is_err() {
496        return;
497    }
498
499    login.mgr.detach_process(&login.session_id);
500}
501
502/// Read the PTY line by line into the session. Returns the detached confirm-and-save task of a login-success line.
503fn pty_drain(
504    login: Arc<Login>,
505    reader: Box<dyn std::io::Read + Send>,
506    answer_dsr: impl FnMut() + Send + 'static,
507    success_transitioned: Arc<AtomicBool>,
508) -> tokio::task::JoinHandle<Option<tokio::task::JoinHandle<()>>> {
509    // Drain: synchronous line reader from PTY master, feeds into
510    // the same record_line matcher the pipes path uses. Runs in a
511    // blocking thread; sends parsed events through a oneshot when
512    // we hit a login-success pattern (so the async task can run
513    // confirm_authenticated without crossing the blocking thread).
514    tokio::task::spawn_blocking(move || {
515        use std::io::BufRead;
516        let mut reader = std::io::BufReader::new(agentmux_common::login_pty::DsrRespondingReader::new(
517            reader, answer_dsr,
518        ));
519        let mut line = String::new();
520        // The detached confirm/persist task's JoinHandle, populated
521        // when the drain matches LoginSuccess. Returned to outer so
522        // it can await completion before its post-exit check —
523        // without that wait, outer would race the detached and
524        // either skip too soon (if it sets the atomic eagerly) or
525        // double-persist. Reagent P1 follow-up on #981.
526        let mut maybe_detached: Option<tokio::task::JoinHandle<()>> = None;
527        loop {
528            line.clear();
529            match reader.read_line(&mut line) {
530                Ok(0) => break, // EOF
531                Ok(_) => {
532                    // Same redaction policy as the pipes path —
533                    // OAuth URLs / codes can be in here.
534                    tracing::debug!(session_id = %login.session_id, bytes = line.len(), "auth.spawn (PTY): line");
535                    let m = login.mgr.record_line(&login.session_id, &line);
536                    if maybe_detached.is_none()
537                        && matches!(
538                            m,
539                            Some(crate::identity::auth_patterns::AuthPatternMatch::LoginSuccess { .. })
540                        )
541                    {
542                        // Hand off to async to call confirm_authenticated.
543                        // The detached task OWNS the transition —
544                        // it calls finish_success on confirm-OK and
545                        // finish_failure on confirm-NOT-OK, AND
546                        // sets the shared atomic in BOTH cases. The
547                        // drain only captures the JoinHandle here
548                        // and returns it; outer awaits both drain
549                        // and the inner handle before its check, so
550                        // the atomic is correctly settled by then.
551                        let handle = tokio::runtime::Handle::current()
552                            .spawn(save_when_confirmed(login.clone(), Arc::clone(&success_transitioned)));
553                        maybe_detached = Some(handle);
554                    }
555                }
556                Err(_) => break,
557            }
558        }
559        maybe_detached
560    })
561}
562
563/// The detached half of a PTY login-success line: confirm it, save the account, and mark the success transitioned.
564async fn save_when_confirmed(login: Arc<Login>, success_for_detached: Arc<AtomicBool>) {
565    if login.confirmed().await {
566        if !login.save_success() {
567            return;
568        }
569        // Atomic set ONLY on confirm-success
570        // — mirrors the pipes path. On
571        // confirm-miss the detached does
572        // nothing (atomic stays false),
573        // outer's post-exit fallback gets
574        // another shot at confirm by the
575        // time creds are fully written.
576        // Outer awaits this handle first,
577        // so the atomic is correctly
578        // reflected by the time it checks.
579        // codex P1 follow-up on #981.
580        success_for_detached.store(true, Ordering::Release);
581    }
582}
583
584/// End the session by how the PTY child exited, when its output did not already: `Err` when the session ended first.
585async fn settle_pty_exit(
586    login: &Login,
587    exit: Result<std::io::Result<portable_pty::ExitStatus>, tokio::task::JoinError>,
588) -> Result<(), Ended> {
589    let (mgr, session_id) = (&login.mgr, &login.session_id);
590    match exit {
591        Ok(Ok(s)) if s.success() => {
592            if login.confirmed().await {
593                if !login.save_success() {
594                    return Err(Ended);
595                }
596            } else {
597                mgr.finish_failure(session_id, "CLI exited cleanly but auth-check still failed".to_string());
598            }
599        }
600        Ok(Ok(s)) => {
601            mgr.finish_failure(session_id, format!("CLI exited with code {:?}", s.exit_code()));
602        }
603        Ok(Err(e)) => {
604            mgr.finish_failure(session_id, format!("PTY wait error: {e}"));
605        }
606        Err(e) => {
607            mgr.finish_failure(session_id, format!("PTY wait task join error: {e}"));
608        }
609    }
610    Ok(())
611}
612
613/// Allocate the PTY. `None` (the session already failed) when the OS cannot give one.
614fn open_pty(login: &Login) -> Option<portable_pty::PtyPair> {
615    use portable_pty::{native_pty_system, PtySize};
616    let (mgr, session_id, provider_id) = (&login.mgr, &login.session_id, &login.provider_id);
617    let pty_system = native_pty_system();
618    let pair = match pty_system.openpty(PtySize {
619        rows: 24,
620        // Wide enough that the CLI never wraps its OAuth URL (`LOGIN_PTY_COLS`).
621        cols: agentmux_common::login_pty::LOGIN_PTY_COLS,
622        pixel_width: 0,
623        pixel_height: 0,
624    }) {
625        Ok(p) => p,
626        Err(e) => {
627            // PTY allocation failure means the provider's auth
628            // subprocess can't get the interactive TTY it requires
629            // (openclaw `models auth login`). Surface as the typed
630            // `AMX-AUTH-001` so the FailedBanner shows the friendly
631            // recovery hint instead of "openpty failed: <e>".
632            let mux = agentmux_common::AgentMuxError::AuthRequiresTty {
633                provider: provider_id.clone(),
634            };
635            tracing::error!(
636                target: "amx::error",
637                session_id = %session_id,
638                amx_code = %mux.code(),
639                error = %e,
640                "auth.spawn (PTY): openpty failed"
641            );
642            mgr.finish_failure(session_id, mux.to_wire().to_string());
643            mgr.detach_process(session_id);
644            return None;
645        }
646    };
647    Some(pair)
648}