tokmesh-cli 0.1.1

CLI and TUI for tokmesh — AI token usage analytics
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
use anyhow::Result;

#[derive(Debug, Clone)]
pub(crate) enum CodexLoginOutcome {
    Imported(crate::commands::usage::codex::CodexAccountInfo),
    Failed(String),
}

#[derive(Debug)]
pub(crate) enum CodexLoginEvent {
    Output(String),
    Finished(CodexLoginOutcome),
}

/// Shared handle to the spawned `codex login` child process. The login worker
/// polls it via `try_wait`; the TUI marks the slot cancelled and takes the
/// child out to kill it on dismiss or exit.
pub(crate) type CodexLoginChildSlot = std::sync::Arc<std::sync::Mutex<CodexLoginChildState>>;

#[derive(Default)]
pub(crate) struct CodexLoginChildState {
    child: Option<std::process::Child>,
    cancelled: bool,
}

pub(crate) fn cancel_codex_login_child(slot: &CodexLoginChildSlot) {
    let child = slot.lock().ok().and_then(|mut state| {
        state.cancelled = true;
        state.child.take()
    });
    if let Some(mut child) = child {
        let _ = child.kill();
        let _ = child.wait();
    }
}

pub(crate) fn run_codex_login_worker(
    tx: std::sync::mpsc::Sender<CodexLoginEvent>,
    child_slot: CodexLoginChildSlot,
) {
    let result = run_codex_login_worker_inner(tx.clone(), child_slot);
    let outcome = match result {
        Ok(info) => CodexLoginOutcome::Imported(info),
        Err(e) => CodexLoginOutcome::Failed(e.to_string()),
    };
    let _ = tx.send(CodexLoginEvent::Finished(outcome));
}

fn run_codex_login_worker_inner(
    tx: std::sync::mpsc::Sender<CodexLoginEvent>,
    child_slot: CodexLoginChildSlot,
) -> Result<crate::commands::usage::codex::CodexAccountInfo> {
    let codex_home =
        std::env::temp_dir().join(format!("tokmesh-codex-login-{}", uuid::Uuid::new_v4()));
    std::fs::create_dir_all(&codex_home)
        .map_err(|e| anyhow::anyhow!("failed to create temporary Codex home: {e}"))?;

    let result = run_codex_login_in_home(&codex_home, tx, child_slot);
    let _ = std::fs::remove_dir_all(&codex_home);
    result
}

fn run_codex_login_in_home(
    codex_home: &std::path::Path,
    tx: std::sync::mpsc::Sender<CodexLoginEvent>,
    child_slot: CodexLoginChildSlot,
) -> Result<crate::commands::usage::codex::CodexAccountInfo> {
    let _ = tx.send(CodexLoginEvent::Output(
        "Starting Codex browser login".to_string(),
    ));

    let mut child = std::process::Command::new("codex")
        .arg("login")
        .env("CODEX_HOME", codex_home)
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .map_err(|e| anyhow::anyhow!("failed to start codex login: {e}"))?;

    let output_lines = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
    let mut readers = Vec::new();
    if let Some(stdout) = child.stdout.take() {
        readers.push(spawn_codex_login_output_reader(
            stdout,
            tx.clone(),
            std::sync::Arc::clone(&output_lines),
        ));
    }
    if let Some(stderr) = child.stderr.take() {
        readers.push(spawn_codex_login_output_reader(
            stderr,
            tx.clone(),
            std::sync::Arc::clone(&output_lines),
        ));
    }

    if let Some(mut cancelled_child) = put_codex_login_child(&child_slot, child)? {
        let _ = cancelled_child.kill();
        let _ = cancelled_child.wait();
        for reader in readers {
            let _ = reader.join();
        }
        anyhow::bail!("Codex login cancelled");
    }

    let status = wait_for_codex_login_child(&child_slot);
    for reader in readers {
        let _ = reader.join();
    }
    let Some(status) = status? else {
        // The TUI emptied the slot: the login was dismissed or the app exited.
        anyhow::bail!("Codex login cancelled");
    };

    if !status.success() {
        let output_lines = output_lines
            .lock()
            .map(|lines| lines.clone())
            .unwrap_or_default();
        anyhow::bail!("{}", codex_login_failure_message(&status, &output_lines));
    }

    // `wait_for_codex_login_child` only observes cancellation while the child
    // is still running. If the child exited successfully in the same tick the
    // user dismissed, the import must not persist the account. The cancelled
    // check and the import run under the same lock so a concurrent dismiss
    // cannot slip between the check and the persistent save: either the cancel
    // wins (we bail before importing) or the import wins (the dismiss blocks
    // until the save completes, and a successful login is kept).
    let auth_path = codex_home.join("auth.json");
    let Some(import) = import_unless_cancelled(&child_slot, &auth_path)? else {
        anyhow::bail!("Codex login cancelled");
    };
    if let Some(warning) = import.warning {
        let _ = tx.send(CodexLoginEvent::Output(warning));
    }
    Ok(import.info)
}

fn put_codex_login_child(
    child_slot: &CodexLoginChildSlot,
    child: std::process::Child,
) -> Result<Option<std::process::Child>> {
    let mut state = child_slot
        .lock()
        .map_err(|_| anyhow::anyhow!("codex login state lock poisoned"))?;
    if state.cancelled {
        Ok(Some(child))
    } else {
        state.child = Some(child);
        Ok(None)
    }
}

/// Imports the login auth file unless the slot was cancelled, holding the slot
/// lock across the cancelled check and the persistent import so the two are
/// atomic with respect to [`cancel_codex_login_child`]. Returns `Ok(None)` when
/// the login was cancelled (so the caller bails without persisting an account);
/// a poisoned lock is treated as cancelled to err away from a side effect.
fn import_unless_cancelled(
    child_slot: &CodexLoginChildSlot,
    auth_path: &std::path::Path,
) -> Result<Option<crate::commands::usage::codex::CodexLoginImport>> {
    let Ok(state) = child_slot.lock() else {
        return Ok(None);
    };
    if state.cancelled {
        return Ok(None);
    }
    // Hold the guard across the import: a concurrent dismiss blocks on the lock
    // until the save completes, closing the check-then-save race window.
    let import = crate::commands::usage::codex::import_login_auth_file(auth_path)?;
    drop(state);
    Ok(Some(import))
}

/// Polls the login child until it exits. Returns `Ok(None)` when the TUI
/// cancelled the login on dismiss or app exit.
fn wait_for_codex_login_child(
    child_slot: &CodexLoginChildSlot,
) -> Result<Option<std::process::ExitStatus>> {
    loop {
        {
            let mut state = child_slot
                .lock()
                .map_err(|_| anyhow::anyhow!("codex login state lock poisoned"))?;
            if state.cancelled {
                return Ok(None);
            }
            let Some(child) = state.child.as_mut() else {
                return Ok(None);
            };
            match child.try_wait() {
                Ok(Some(status)) => {
                    state.child = None;
                    return Ok(Some(status));
                }
                Ok(None) => {}
                Err(e) => {
                    state.child = None;
                    return Err(anyhow::anyhow!("failed to wait for codex login: {e}"));
                }
            }
        }
        std::thread::sleep(std::time::Duration::from_millis(150));
    }
}

fn spawn_codex_login_output_reader<R>(
    reader: R,
    tx: std::sync::mpsc::Sender<CodexLoginEvent>,
    output_lines: std::sync::Arc<std::sync::Mutex<Vec<String>>>,
) -> std::thread::JoinHandle<()>
where
    R: std::io::Read + Send + 'static,
{
    std::thread::spawn(move || {
        let reader = std::io::BufReader::new(reader);
        for line in std::io::BufRead::lines(reader).map_while(std::result::Result::ok) {
            let line = sanitize_codex_login_line(&line);
            if !line.trim().is_empty() {
                if let Ok(mut output_lines) = output_lines.lock() {
                    output_lines.push(line.clone());
                }
                let _ = tx.send(CodexLoginEvent::Output(line));
            }
        }
    })
}

fn codex_login_failure_message(
    status: &std::process::ExitStatus,
    output_lines: &[String],
) -> String {
    codex_login_failure_message_from_output(&status.to_string(), output_lines)
}

fn codex_login_failure_message_from_output(status: &str, output_lines: &[String]) -> String {
    let output = output_lines.join("\n").to_lowercase();

    if output.contains("429") || output.contains("too many requests") {
        return "OpenAI login is rate-limited (429 Too Many Requests). Wait before trying Add Codex again.".to_string();
    }

    if output.contains("expired") {
        return "Codex device code expired. Start Add Codex again to get a new code.".to_string();
    }

    if output.contains("device auth failed") {
        return "Codex device login failed. Try Add Codex again later.".to_string();
    }

    format!("codex login exited with {status}")
}

fn sanitize_codex_login_line(line: &str) -> String {
    let mut sanitized = String::with_capacity(line.len());
    let mut chars = line.chars().peekable();

    while let Some(ch) = chars.next() {
        if ch == '\x1b' {
            match chars.next() {
                Some('[') => {
                    for ch in chars.by_ref() {
                        if ('\u{40}'..='\u{7e}').contains(&ch) {
                            break;
                        }
                    }
                }
                Some(']') => {
                    while let Some(ch) = chars.next() {
                        if ch == '\x07' {
                            break;
                        }
                        if ch == '\x1b' && chars.peek() == Some(&'\\') {
                            let _ = chars.next();
                            break;
                        }
                    }
                }
                Some(_) | None => {}
            }
            continue;
        }

        if !ch.is_control() || ch == '\t' {
            sanitized.push(ch);
        }
    }

    sanitized
}

#[cfg(test)]
pub(crate) fn put_codex_login_child_for_test(
    child_slot: &CodexLoginChildSlot,
    child: std::process::Child,
) -> Result<Option<std::process::Child>> {
    put_codex_login_child(child_slot, child)
}

#[cfg(test)]
pub(crate) fn codex_login_slot_child_is_none_for_test(child_slot: &CodexLoginChildSlot) -> bool {
    child_slot
        .lock()
        .map(|state| state.child.is_none())
        .unwrap_or(false)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn wait_for_codex_login_child_returns_none_when_cancelled() {
        let slot = CodexLoginChildSlot::default();
        cancel_codex_login_child(&slot);
        let status = wait_for_codex_login_child(&slot).unwrap();
        assert!(status.is_none());
    }

    #[test]
    fn import_unless_cancelled_short_circuits_when_cancelled() {
        // When the slot is cancelled, the import must be skipped entirely — it
        // returns Ok(None) without touching the auth path (so no account is
        // persisted). A path that does not exist would error if read, proving
        // the cancelled check short-circuits before the import.
        let slot = CodexLoginChildSlot::default();
        cancel_codex_login_child(&slot);
        let missing = std::path::Path::new("/nonexistent/tokmesh-codex-login/auth.json");

        let result = import_unless_cancelled(&slot, missing).unwrap();

        assert!(
            result.is_none(),
            "cancelled slot must skip the import side effect"
        );
    }

    #[cfg(unix)]
    #[test]
    fn put_codex_login_child_returns_child_when_already_cancelled() {
        let slot = CodexLoginChildSlot::default();
        cancel_codex_login_child(&slot);
        let child = std::process::Command::new("true").spawn().unwrap();

        let mut child = put_codex_login_child(&slot, child)
            .unwrap()
            .expect("cancelled slot should return the child to be killed by caller");

        assert!(child.wait().unwrap().success());
    }

    #[cfg(unix)]
    #[test]
    fn wait_for_codex_login_child_reports_exit_status() {
        let child = std::process::Command::new("true").spawn().unwrap();
        let slot = CodexLoginChildSlot::default();
        put_codex_login_child(&slot, child).unwrap();

        let status = wait_for_codex_login_child(&slot).unwrap();

        assert!(status.unwrap().success());
        assert!(slot.lock().unwrap().child.is_none());
    }

    #[test]
    fn test_sanitize_codex_login_line_strips_ansi_sequences() {
        assert_eq!(
            sanitize_codex_login_line("\u{1b}[94mhttps://auth.openai.com/codex/device\u{1b}[0m"),
            "https://auth.openai.com/codex/device"
        );
        assert_eq!(
            sanitize_codex_login_line("\u{1b}[90mCAGW-LNUYX\u{1b}[0m"),
            "CAGW-LNUYX"
        );
    }

    #[test]
    fn test_codex_login_failure_message_identifies_rate_limit() {
        let message = codex_login_failure_message_from_output(
            "exit status: 1",
            &[
                "Device codes are a common phishing target. Never share this code.".to_string(),
                "Error logging in with device code: device auth failed with status 429 Too Many Requests"
                    .to_string(),
            ],
        );

        assert_eq!(
            message,
            "OpenAI login is rate-limited (429 Too Many Requests). Wait before trying Add Codex again."
        );
    }

    #[test]
    fn test_codex_login_failure_message_identifies_expired_code() {
        let message = codex_login_failure_message_from_output(
            "exit status: 1",
            &["Error logging in with device code: expired".to_string()],
        );

        assert_eq!(
            message,
            "Codex device code expired. Start Add Codex again to get a new code."
        );
    }
}