thndrs 0.1.0

Terminal AI pair programmer with local tools, sessions, MCP, and ACP support
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
//! First-run provider setup, authentication, and credential recovery.
//!
//! This module handles the setup flow for a selected model:
//!
//! 1. choosing a provider
//! 2. selecting credential and model-config scope
//! 3. collecting an API key
//! 4. writing or removing the resulting credential.
//!
//! ChatGPT Codex uses browser-first PKCE OAuth instead of API-key entry. Device
//! code remains an explicit headless/remote alternative.
//!
//! API-key input stays in [`FirstRunRecovery::secret_input`] until it is
//! written to the provider credential store.
//!
//! It is not copied into transcript, prompt, or session metadata.

use std::io;

use super::*;

/// Focused first-run and credential recovery surface.
#[derive(Clone, Eq, PartialEq)]
pub struct FirstRunRecovery {
    /// Provider being configured or diagnosed.
    pub provider: Option<SetupProviderArg>,
    /// Current recovery step.
    pub stage: RecoveryStage,
    /// Whether a prompt submit is waiting on this recovery.
    pub pending_provider_prompt: bool,
    /// Selected action row.
    pub selected: usize,
    /// Hidden API-key buffer. This is never rendered or written to transcripts.
    pub secret_input: String,
    /// ChatGPT OAuth state. Token material is never rendered.
    pub chatgpt_oauth: Option<ChatGptOAuthRecovery>,
}

impl std::fmt::Debug for FirstRunRecovery {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("FirstRunRecovery")
            .field("provider", &self.provider)
            .field("stage", &self.stage)
            .field("pending_provider_prompt", &self.pending_provider_prompt)
            .field("selected", &self.selected)
            .field(
                "secret_input",
                &if self.secret_input.is_empty() { "<empty>" } else { "[redacted]" },
            )
            .field("chatgpt_oauth", &self.chatgpt_oauth)
            .finish()
    }
}

impl FirstRunRecovery {
    pub fn missing_label(&self) -> &'static str {
        match self.stage {
            RecoveryStage::ChooseProvider | RecoveryStage::ModelSelection | RecoveryStage::ModelConfigScope => "none",
            _ => match self.provider {
                Some(crate::cli::commands::setup::SetupProviderArg::ChatgptCodex) => "ChatGPT OAuth credential",
                Some(provider) => provider.api_key_env_var().unwrap_or("credential"),
                None => "ACP agent config",
            },
        }
    }

    pub fn setup(default_provider: SetupProviderArg) -> Self {
        let selected = match default_provider {
            SetupProviderArg::ChatgptCodex => 0,
            SetupProviderArg::Umans => 1,
            SetupProviderArg::OpencodeGo | SetupProviderArg::OpencodeZen => 2,
        };
        Self {
            provider: Some(default_provider),
            stage: RecoveryStage::ChooseProvider,
            pending_provider_prompt: false,
            selected,
            secret_input: String::new(),
            chatgpt_oauth: None,
        }
    }

    pub fn missing_provider(provider: SetupProviderArg, pending_provider_prompt: bool) -> Self {
        Self {
            provider: Some(provider),
            stage: RecoveryStage::MissingCredential,
            pending_provider_prompt,
            selected: 0,
            secret_input: String::new(),
            chatgpt_oauth: None,
        }
    }

    pub fn acp_missing(pending_provider_prompt: bool) -> Self {
        Self {
            provider: None,
            stage: RecoveryStage::AcpMissing,
            pending_provider_prompt,
            selected: 0,
            secret_input: String::new(),
            chatgpt_oauth: None,
        }
    }

    pub fn login(provider: SetupProviderArg) -> Self {
        Self {
            provider: Some(provider),
            stage: if provider == SetupProviderArg::ChatgptCodex {
                RecoveryStage::MissingCredential
            } else {
                RecoveryStage::EnterKey
            },
            pending_provider_prompt: false,
            selected: 0,
            secret_input: String::new(),
            chatgpt_oauth: None,
        }
    }

    pub fn logout(provider: SetupProviderArg) -> Self {
        Self {
            provider: Some(provider),
            stage: RecoveryStage::LogoutConfirm,
            pending_provider_prompt: false,
            selected: 0,
            secret_input: String::new(),
            chatgpt_oauth: None,
        }
    }

    pub fn action_count(&self) -> usize {
        match self.stage {
            RecoveryStage::ChooseProvider => 3,
            RecoveryStage::ModelSelection => self.app_model_selection_count(),
            RecoveryStage::ModelConfigScope => 4,
            RecoveryStage::MissingCredential => {
                if self.provider == Some(SetupProviderArg::ChatgptCodex) {
                    6
                } else {
                    5
                }
            }
            RecoveryStage::EnterKey => 1,
            RecoveryStage::ConfirmStore | RecoveryStage::LogoutConfirm => 3,
            RecoveryStage::Instructions => 2,
            RecoveryStage::ChatGptOAuthRequesting | RecoveryStage::ChatGptOAuthPasteRedirect => 1,
            RecoveryStage::ChatGptOAuthPolling => self
                .chatgpt_oauth
                .as_ref()
                .filter(|oauth| oauth.method == ChatGptOAuthMethod::Browser)
                .map_or(1, |_| 2),
            RecoveryStage::ChatGptOAuthFailed => 3,
            RecoveryStage::AcpMissing => 4,
        }
    }

    fn app_model_selection_count(&self) -> usize {
        self.provider
            .map(setup_model_options)
            .map(|options| options.len())
            .unwrap_or(0)
    }
}

/// ChatGPT OAuth method selected by the user.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ChatGptOAuthMethod {
    /// Browser PKCE with a loopback callback.
    Browser,
    /// Device code for headless or remote environments.
    DeviceCode,
}

/// ChatGPT OAuth state shown in the focused recovery surface.
#[derive(Clone, Eq, PartialEq)]
pub struct ChatGptOAuthRecovery {
    /// OAuth method selected by the user.
    pub method: ChatGptOAuthMethod,
    /// Browser authorization URL, when browser PKCE is active.
    pub authorization_url: Option<String>,
    /// Device-code response used for polling, when device code is active. Its
    /// debug output redacts the device token.
    pub code: Option<auth::ChatGptCodexDeviceCode>,
    /// UI tick when the next single device-code poll is allowed.
    pub next_poll_tick: u64,
    /// OAuth expiry tick.
    pub expires_at_tick: u64,
    /// Redacted status text for the recovery surface.
    pub status: String,
}

impl std::fmt::Debug for ChatGptOAuthRecovery {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("ChatGptOAuthRecovery")
            .field("method", &self.method)
            .field(
                "authorization_url",
                &self.authorization_url.as_ref().map(|_| "[redacted]"),
            )
            .field("code", &self.code)
            .field("next_poll_tick", &self.next_poll_tick)
            .field("expires_at_tick", &self.expires_at_tick)
            .field("status", &self.status)
            .finish()
    }
}

/// Step within the first-run recovery surface.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RecoveryStage {
    /// Choose which built-in provider to configure.
    ChooseProvider,
    /// Choose whether and where to persist the selected provider's default model.
    ModelConfigScope,
    /// Choose a model after provider authentication succeeds.
    ModelSelection,
    /// Selected provider is missing an API-key credential.
    MissingCredential,
    /// Hidden API-key entry is active.
    EnterKey,
    /// Select global/project storage before writing the key.
    ConfirmStore,
    /// Show setup instructions in a focused surface.
    Instructions,
    /// Starting a ChatGPT OAuth method.
    ChatGptOAuthRequesting,
    /// Waiting for browser callback or device-code authorization.
    ChatGptOAuthPolling,
    /// Pasting the full browser redirect URL into a hidden input.
    ChatGptOAuthPasteRedirect,
    /// ChatGPT OAuth failed with a redacted, user-readable error.
    ChatGptOAuthFailed,
    /// Confirm logout and storage scope.
    LogoutConfirm,
    /// ACP model recovery, separate from provider API-key setup.
    AcpMissing,
}

impl RecoveryStage {
    pub fn label(self) -> &'static str {
        match self {
            RecoveryStage::ChooseProvider => "choose provider",
            RecoveryStage::ModelSelection => "choose model",
            RecoveryStage::ModelConfigScope => "model scope",
            RecoveryStage::MissingCredential => "authentication required",
            RecoveryStage::EnterKey => "credential entry",
            RecoveryStage::ConfirmStore => "credential scope",
            RecoveryStage::Instructions => "setup instructions",
            RecoveryStage::ChatGptOAuthRequesting => "starting OAuth",
            RecoveryStage::ChatGptOAuthPolling => "OAuth in progress",
            RecoveryStage::ChatGptOAuthPasteRedirect => "paste redirect",
            RecoveryStage::ChatGptOAuthFailed => "OAuth failed",
            RecoveryStage::LogoutConfirm => "remove credential",
            RecoveryStage::AcpMissing => "ACP setup required",
        }
    }
}

/// Small seam for testing TUI OAuth without real network calls.
///
/// FIXME: what on earth is this
#[derive(Clone, Copy, Debug)]
pub struct ChatGptOAuthDriver {
    pub start_browser_login: fn() -> Result<auth::ChatGptCodexBrowserLogin, auth::AuthError>,
    pub open_browser: fn(&str) -> Result<(), auth::AuthError>,
    pub poll_browser_login:
        fn(&mut auth::ChatGptCodexBrowserLogin) -> Result<auth::ChatGptCodexBrowserPoll, auth::AuthError>,
    pub complete_browser_redirect:
        fn(&auth::ChatGptCodexBrowserLogin, &str) -> Result<auth::ChatGptCodexCredentials, auth::AuthError>,
    pub request_device_code: fn() -> Result<auth::ChatGptCodexDeviceCode, auth::AuthError>,
    pub poll_device_code_once:
        fn(&auth::ChatGptCodexDeviceCode) -> Result<auth::ChatGptCodexDevicePoll, auth::AuthError>,
    pub write_credentials: fn(&auth::ChatGptCodexCredentials) -> Result<(), auth::AuthError>,
}

impl Default for ChatGptOAuthDriver {
    fn default() -> Self {
        Self {
            start_browser_login: auth::start_chatgpt_codex_browser_login,
            open_browser: auth::open_chatgpt_codex_authorization_url,
            poll_browser_login: auth::poll_chatgpt_codex_browser_login_once,
            complete_browser_redirect: auth::ChatGptCodexBrowserLogin::complete_redirect,
            request_device_code: auth::request_chatgpt_codex_device_code,
            poll_device_code_once: auth::poll_chatgpt_codex_device_code_once,
            write_credentials: auth::write_chatgpt_codex_credentials,
        }
    }
}

/// Setup state held while the reasoning picker is open.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct PendingSetupReasoningEffort {
    pub provider: SetupProviderArg,
    pub scope: CredentialScope,
}

pub fn provider_for_model(model: &str) -> SetupProviderArg {
    if opencode::is_zen_model_id(model) {
        SetupProviderArg::OpencodeZen
    } else if opencode::is_go_model_id(model) {
        SetupProviderArg::OpencodeGo
    } else if codex::is_model_id(model) {
        SetupProviderArg::ChatgptCodex
    } else {
        SetupProviderArg::Umans
    }
}

pub fn provider_authenticated(provider: SetupProviderArg, cwd: &std::path::Path) -> bool {
    match provider {
        SetupProviderArg::ChatgptCodex => chatgpt_codex_auth_available_locally(),
        _ => match provider.api_key_env_var() {
            Some(env_var) => auth::credential_source(env_var, cwd).is_some(),
            _ => false,
        },
    }
}

pub fn chatgpt_codex_auth_available_locally() -> bool {
    if let Ok(token) = std::env::var(auth::CHATGPT_CODEX_ACCESS_TOKEN_ENV)
        && !token.trim().is_empty()
    {
        return auth::chatgpt_account_id_from_jwt(&token).is_ok();
    }

    matches!(
        auth::read_chatgpt_codex_credentials(),
        Ok(Some(credentials))
            if !credentials.access_token.trim().is_empty()
                && !credentials.refresh_token.trim().is_empty()
                && !credentials.account_id.trim().is_empty()
    )
}

pub fn selected_provider_missing(app: &App) -> Option<FirstRunRecovery> {
    if app.model.trim().is_empty() {
        return Some(FirstRunRecovery::setup(SetupProviderArg::ChatgptCodex));
    }

    if let Some(acp_name) = crate::acp::config::parse_model_id(&app.model) {
        if app.cli.acp_agents.contains_key(acp_name) {
            return None;
        }
        return Some(FirstRunRecovery::acp_missing(true));
    }

    let provider = provider_for_model(&app.model);
    if !provider_authenticated(provider, &app.cwd) {
        Some(FirstRunRecovery::missing_provider(provider, true))
    } else {
        None
    }
}

pub fn handle_first_run_key(app: &mut App, key: KeyEvent) -> Option<Msg> {
    let recovery = app.first_run_recovery.as_mut()?;

    if recovery.stage == RecoveryStage::EnterKey || recovery.stage == RecoveryStage::ChatGptOAuthPasteRedirect {
        match key.code {
            KeyCode::Esc => {
                recovery.secret_input.clear();
                recovery.stage = if recovery.stage == RecoveryStage::ChatGptOAuthPasteRedirect {
                    RecoveryStage::ChatGptOAuthPolling
                } else {
                    RecoveryStage::MissingCredential
                };
                recovery.selected = 0;
            }
            KeyCode::Backspace => {
                recovery.secret_input.pop();
            }
            KeyCode::Enter => {
                if recovery.secret_input.trim().is_empty() {
                    app.transcript.push(Entry::Error {
                        text: if recovery.stage == RecoveryStage::ChatGptOAuthPasteRedirect {
                            String::from("paste the full ChatGPT redirect URL or press Esc to cancel")
                        } else {
                            String::from("API key cannot be empty")
                        },
                    });
                } else if recovery.stage == RecoveryStage::ChatGptOAuthPasteRedirect {
                    let redirect = recovery.secret_input.clone();
                    recovery.secret_input.clear();
                    complete_chatgpt_oauth_redirect(app, &redirect);
                } else {
                    recovery.stage = RecoveryStage::ConfirmStore;
                    recovery.selected = 0;
                }
            }
            KeyCode::Char(ch) => recovery.secret_input.push(ch),
            _ => {}
        }
        return None;
    }

    if matches!(
        recovery.stage,
        RecoveryStage::ChatGptOAuthRequesting | RecoveryStage::ChatGptOAuthPolling
    ) && key.code == KeyCode::Esc
    {
        recovery.stage = RecoveryStage::MissingCredential;
        recovery.selected = 0;
        recovery.chatgpt_oauth = None;
        app.chatgpt_browser_login = None;
        return None;
    }

    match key.code {
        KeyCode::Esc => {
            app.first_run_recovery = None;
            None
        }
        KeyCode::Up => {
            recovery.selected = recovery.selected.saturating_sub(1);
            None
        }
        KeyCode::Down => {
            let max = recovery.action_count().saturating_sub(1);
            recovery.selected = (recovery.selected + 1).min(max);
            None
        }
        KeyCode::Enter => accept_recovery_action(app),
        _ => None,
    }
}

pub fn accept_recovery_action(app: &mut App) -> Option<Msg> {
    let recovery = app.first_run_recovery.clone()?;

    match recovery.stage {
        RecoveryStage::ChooseProvider => {
            let Some(provider) = first_run_provider(recovery.selected) else {
                app.first_run_recovery = Some(FirstRunRecovery {
                    provider: None,
                    stage: RecoveryStage::Instructions,
                    pending_provider_prompt: recovery.pending_provider_prompt,
                    selected: 0,
                    secret_input: String::new(),
                    chatgpt_oauth: None,
                });
                return None;
            };
            let stage = if provider_authenticated(provider, &app.cwd) {
                RecoveryStage::ModelSelection
            } else {
                RecoveryStage::MissingCredential
            };
            app.first_run_recovery = Some(FirstRunRecovery {
                provider: Some(provider),
                stage,
                pending_provider_prompt: recovery.pending_provider_prompt,
                selected: 0,
                secret_input: String::new(),
                chatgpt_oauth: None,
            });
        }
        RecoveryStage::ModelSelection => select_setup_model(app, &recovery),
        RecoveryStage::ModelConfigScope => configure_setup_model_scope(app, &recovery),
        RecoveryStage::MissingCredential if recovery.provider == Some(SetupProviderArg::ChatgptCodex) => {
            match recovery.selected {
                0 => start_chatgpt_browser_oauth_recovery(app),
                1 => start_chatgpt_device_oauth_recovery(app),
                2 => {
                    app.first_run_recovery = None;
                    open_model_picker(app);
                }
                3 => {
                    if let Some(active) = app.first_run_recovery.as_mut() {
                        active.stage = RecoveryStage::Instructions;
                        active.selected = 0;
                        active.chatgpt_oauth = None;
                    }
                }
                4 => {
                    if recovery.pending_provider_prompt {
                        app.transcript.push(Entry::Status {
                            text: String::from(
                                "setup required before submitting this ChatGPT Codex prompt; start OAuth login or switch model",
                            ),
                        });
                    } else {
                        app.first_run_recovery = None;
                        app.transcript
                            .push(Entry::Status { text: String::from("setup skipped") });
                    }
                }
                5 => {
                    app.quit = true;
                    return Some(Msg::Quit);
                }
                _ => {}
            }
        }
        RecoveryStage::MissingCredential => match recovery.selected {
            0 => {
                if let Some(active) = app.first_run_recovery.as_mut() {
                    active.stage = RecoveryStage::EnterKey;
                    active.selected = 0;
                    active.secret_input.clear();
                }
            }
            1 => {
                if recovery.provider == Some(SetupProviderArg::ChatgptCodex) {
                    if let Some(active) = app.first_run_recovery.as_mut() {
                        active.stage = RecoveryStage::Instructions;
                        active.selected = 0;
                    }
                    return None;
                }
                app.first_run_recovery = None;
                open_model_picker(app);
            }
            2 => {
                if recovery.provider == Some(SetupProviderArg::ChatgptCodex) {
                    if recovery.pending_provider_prompt {
                        app.transcript.push(Entry::Status {
                            text: String::from(
                                "setup required before submitting this ChatGPT Codex prompt; start ChatGPT OAuth login or switch model",
                            ),
                        });
                    } else {
                        app.first_run_recovery = None;
                        app.transcript
                            .push(Entry::Status { text: String::from("setup skipped") });
                    }
                    return None;
                }
                if let Some(active) = app.first_run_recovery.as_mut() {
                    active.stage = RecoveryStage::Instructions;
                    active.selected = 0;
                }
            }
            3 => {
                if recovery.provider == Some(SetupProviderArg::ChatgptCodex) {
                    app.quit = true;
                    return Some(Msg::Quit);
                }
                if recovery.pending_provider_prompt {
                    app.transcript.push(Entry::Status {
                        text: String::from(
                            "setup required before submitting this provider-backed prompt; enter a key or switch model",
                        ),
                    });
                } else {
                    app.first_run_recovery = None;
                    app.transcript
                        .push(Entry::Status { text: String::from("setup skipped") });
                }
            }
            4 => {
                app.quit = true;
                return Some(Msg::Quit);
            }
            _ => {}
        },
        RecoveryStage::ConfirmStore => store_recovery_credential(app, &recovery),
        RecoveryStage::Instructions => match recovery.selected {
            0 => {
                if let Some(active) = app.first_run_recovery.as_mut() {
                    active.stage = if active.provider.is_none() {
                        RecoveryStage::ChooseProvider
                    } else {
                        RecoveryStage::MissingCredential
                    };
                    active.selected = 0;
                }
            }
            1 => app.first_run_recovery = None,
            _ => {}
        },
        RecoveryStage::ChatGptOAuthRequesting => {}
        RecoveryStage::ChatGptOAuthPolling => {
            if recovery
                .chatgpt_oauth
                .as_ref()
                .is_some_and(|oauth| oauth.method == ChatGptOAuthMethod::Browser && recovery.selected == 1)
            {
                if let Some(active) = app.first_run_recovery.as_mut() {
                    active.stage = RecoveryStage::ChatGptOAuthPasteRedirect;
                    active.selected = 0;
                    active.secret_input.clear();
                }
            } else if let Some(active) = app.first_run_recovery.as_mut() {
                active.stage = RecoveryStage::MissingCredential;
                active.selected = 0;
                active.chatgpt_oauth = None;
                app.chatgpt_browser_login = None;
            }
        }
        RecoveryStage::ChatGptOAuthPasteRedirect => {}
        RecoveryStage::ChatGptOAuthFailed => match recovery.selected {
            0 => match recovery.chatgpt_oauth.as_ref().map(|oauth| oauth.method) {
                Some(ChatGptOAuthMethod::DeviceCode) => start_chatgpt_device_oauth_recovery(app),
                _ => start_chatgpt_browser_oauth_recovery(app),
            },
            1 => {
                start_chatgpt_device_oauth_recovery(app);
            }
            2 => {
                if let Some(active) = app.first_run_recovery.as_mut() {
                    active.stage = RecoveryStage::MissingCredential;
                    active.selected = 0;
                    active.chatgpt_oauth = None;
                }
                app.chatgpt_browser_login = None;
            }
            _ => {}
        },
        RecoveryStage::LogoutConfirm => remove_recovery_credential(app, &recovery),
        RecoveryStage::AcpMissing => match recovery.selected {
            0 => {
                app.first_run_recovery = None;
                open_model_picker(app);
            }
            1 => {
                app.transcript.push(Entry::Status {
                    text: String::from("ACP setup: run `thndrs acp list` or `thndrs acp registry` outside the TUI"),
                });
            }
            2 => {
                if recovery.pending_provider_prompt {
                    app.transcript.push(Entry::Status {
                        text: String::from(
                            "ACP agent config is required before submitting this prompt; switch model or configure ACP",
                        ),
                    });
                } else {
                    app.first_run_recovery = None;
                }
            }
            3 => {
                app.quit = true;
                return Some(Msg::Quit);
            }
            _ => {}
        },
        RecoveryStage::EnterKey => {}
    }

    None
}

pub fn configure_setup_model_scope(app: &mut App, recovery: &FirstRunRecovery) {
    let Some(provider) = recovery.provider else {
        app.first_run_recovery = None;
        return;
    };

    match recovery.selected {
        0 => {
            if write_setup_model_config(app, provider, CredentialScope::Project).is_ok() {
                after_setup_model_config(app, provider, CredentialScope::Project);
            }
        }
        1 => {
            if write_setup_model_config(app, provider, CredentialScope::Global).is_ok() {
                after_setup_model_config(app, provider, CredentialScope::Global);
            }
        }
        2 => {
            app.transcript
                .push(Entry::Status { text: String::from("model config skipped") });
            advance_after_setup_model_config(app, provider);
        }
        _ => {
            app.first_run_recovery = None;
            app.transcript
                .push(Entry::Status { text: String::from("setup skipped") });
        }
    }
}

pub fn after_setup_model_config(app: &mut App, provider: SetupProviderArg, scope: CredentialScope) {
    if codex::supports_reasoning_effort(&app.model) {
        app.first_run_recovery = None;
        app.pending_setup_reasoning_effort = Some(PendingSetupReasoningEffort { provider, scope });
        open_reasoning_effort_picker(app);
    } else {
        advance_after_setup_model_config(app, provider);
    }
}

pub fn write_setup_model_config(app: &mut App, _provider: SetupProviderArg, scope: CredentialScope) -> io::Result<()> {
    let model = app.model.trim();
    if model.is_empty() {
        let err = io::Error::new(io::ErrorKind::InvalidInput, "choose a model before saving setup");
        app.transcript
            .push(Entry::Error { text: format!("failed to save selected model to config: {err}") });
        return Err(err);
    }
    let path = match scope {
        CredentialScope::Global => match config::global_config_path() {
            Some(path) => path,
            None => {
                let err = io::Error::new(io::ErrorKind::NotFound, "HOME is not available");
                app.transcript
                    .push(Entry::Error { text: format!("failed to save selected model to global config: {err}") });
                return Err(err);
            }
        },
        CredentialScope::Project => config::project_config_path(&app.cwd),
    };

    match config::write_model_config(&path, model) {
        Ok(()) => {
            let display = match scope {
                CredentialScope::Global => config::global_config_path_display(&path),
                CredentialScope::Project => config::project_config_path_display(&path, &app.cwd),
            };
            app.transcript
                .push(Entry::Status { text: format!("model: {model} (saved to {display})") });
            Ok(())
        }
        Err(err) => {
            app.transcript.push(Entry::Error {
                text: format!("failed to save selected model to {} config: {err}", scope.label()),
            });
            Err(err)
        }
    }
}

pub fn advance_after_setup_model_config(app: &mut App, provider: SetupProviderArg) {
    if provider_authenticated(provider, &app.cwd) {
        app.first_run_recovery = None;
        app.transcript.push(Entry::Status {
            text: format!(
                "setup saved for {}; thndrs will verify the credential on the first provider request",
                provider.label()
            ),
        });
    } else if provider == SetupProviderArg::ChatgptCodex {
        app.first_run_recovery = Some(FirstRunRecovery::missing_provider(provider, false));
    } else {
        app.first_run_recovery = Some(FirstRunRecovery::login(provider));
    }
}

pub fn setup_model_options(provider: SetupProviderArg) -> Vec<PickerItem> {
    let mut options: Vec<PickerItem> = offline_model_picker_items()
        .into_iter()
        .filter(|item| provider_for_model(&item.label) == provider)
        .collect();
    if !options.iter().any(|item| item.label == provider.default_model()) {
        options.insert(0, PickerItem::new(provider.default_model(), "provider setup model"));
    }
    options
}

/// Start the browser-first ChatGPT Codex OAuth recovery.
pub fn start_chatgpt_browser_oauth_recovery(app: &mut App) {
    let pending_provider_prompt = app
        .first_run_recovery
        .as_ref()
        .is_some_and(|recovery| recovery.pending_provider_prompt);
    if let Some(active) = app.first_run_recovery.as_mut() {
        active.stage = RecoveryStage::ChatGptOAuthRequesting;
        active.selected = 0;
        active.chatgpt_oauth = None;
    }
    app.chatgpt_browser_login = None;

    match (app.chatgpt_oauth_driver.start_browser_login)() {
        Ok(login) => {
            let authorization_url = login.authorization_url().to_string();
            let status = match (app.chatgpt_oauth_driver.open_browser)(&authorization_url) {
                Ok(()) => String::from("Browser opened. Waiting for the ChatGPT callback."),
                Err(_) => String::from("Browser did not open; copy the authorization URL below."),
            };
            let expires_at_tick = app.ui_tick.wrapping_add(seconds_to_ticks(app, 5 * 60));
            app.chatgpt_browser_login = Some(login);
            app.first_run_recovery = Some(FirstRunRecovery {
                provider: Some(SetupProviderArg::ChatgptCodex),
                stage: RecoveryStage::ChatGptOAuthPolling,
                pending_provider_prompt,
                selected: 0,
                secret_input: String::new(),
                chatgpt_oauth: Some(ChatGptOAuthRecovery {
                    method: ChatGptOAuthMethod::Browser,
                    authorization_url: Some(authorization_url),
                    code: None,
                    next_poll_tick: app.ui_tick,
                    expires_at_tick,
                    status,
                }),
            });
        }
        Err(err) => set_chatgpt_oauth_failure(
            app,
            ChatGptOAuthMethod::Browser,
            pending_provider_prompt,
            format!(
                "ChatGPT browser OAuth could not start: {}",
                redact_auth_error(&err.to_string())
            ),
        ),
    }
}

/// Start the explicitly selected headless ChatGPT Codex device-code recovery.
pub fn start_chatgpt_device_oauth_recovery(app: &mut App) {
    let pending_provider_prompt = app
        .first_run_recovery
        .as_ref()
        .is_some_and(|recovery| recovery.pending_provider_prompt);
    if let Some(active) = app.first_run_recovery.as_mut() {
        active.stage = RecoveryStage::ChatGptOAuthRequesting;
        active.selected = 0;
        active.chatgpt_oauth = None;
    }
    app.chatgpt_browser_login = None;

    match (app.chatgpt_oauth_driver.request_device_code)() {
        Ok(code) => {
            let next_poll_tick = app
                .ui_tick
                .wrapping_add(seconds_to_ticks(app, code.interval.unwrap_or(5).max(1)));
            let expires_at_tick = app
                .ui_tick
                .wrapping_add(seconds_to_ticks(app, code.expires_in.unwrap_or(900).max(1)));
            app.first_run_recovery = Some(FirstRunRecovery {
                provider: Some(SetupProviderArg::ChatgptCodex),
                stage: RecoveryStage::ChatGptOAuthPolling,
                pending_provider_prompt,
                selected: 0,
                secret_input: String::new(),
                chatgpt_oauth: Some(ChatGptOAuthRecovery {
                    method: ChatGptOAuthMethod::DeviceCode,
                    authorization_url: None,
                    code: Some(code),
                    next_poll_tick,
                    expires_at_tick,
                    status: String::from("Waiting for ChatGPT authorization."),
                }),
            });
        }
        Err(err) => {
            set_chatgpt_oauth_failure(
                app,
                ChatGptOAuthMethod::DeviceCode,
                pending_provider_prompt,
                format!(
                    "ChatGPT device-code login could not start: {}",
                    redact_auth_error(&err.to_string())
                ),
            );
        }
    }
}

fn set_chatgpt_oauth_failure(app: &mut App, method: ChatGptOAuthMethod, pending_provider_prompt: bool, status: String) {
    app.chatgpt_browser_login = None;
    app.first_run_recovery = Some(FirstRunRecovery {
        provider: Some(SetupProviderArg::ChatgptCodex),
        stage: RecoveryStage::ChatGptOAuthFailed,
        pending_provider_prompt,
        selected: 0,
        secret_input: String::new(),
        chatgpt_oauth: Some(ChatGptOAuthRecovery {
            method,
            authorization_url: None,
            code: None,
            next_poll_tick: app.ui_tick,
            expires_at_tick: app.ui_tick,
            status: status.clone(),
        }),
    });
    app.transcript.push(Entry::Error { text: status });
}

fn finish_chatgpt_oauth(
    app: &mut App, credentials: &auth::ChatGptCodexCredentials, pending_provider_prompt: bool,
    method: ChatGptOAuthMethod,
) {
    match (app.chatgpt_oauth_driver.write_credentials)(credentials) {
        Ok(()) => {
            app.chatgpt_browser_login = None;
            let needs_model = app.model.trim().is_empty();
            app.transcript.push(Entry::Status {
                text: String::from("chatgpt-codex OAuth credential stored in global auth store"),
            });
            if needs_model {
                app.first_run_recovery = Some(FirstRunRecovery {
                    provider: Some(SetupProviderArg::ChatgptCodex),
                    stage: RecoveryStage::ModelSelection,
                    pending_provider_prompt,
                    selected: 0,
                    secret_input: String::new(),
                    chatgpt_oauth: None,
                });
            } else {
                app.first_run_recovery = None;
            }
        }
        Err(err) => set_chatgpt_oauth_failure(
            app,
            method,
            pending_provider_prompt,
            format!(
                "ChatGPT OAuth credential write failed: {}",
                redact_auth_error(&err.to_string())
            ),
        ),
    }
}

fn complete_chatgpt_oauth_redirect(app: &mut App, redirect: &str) {
    let pending_provider_prompt = app
        .first_run_recovery
        .as_ref()
        .is_some_and(|recovery| recovery.pending_provider_prompt);
    let result = app
        .chatgpt_browser_login
        .as_ref()
        .ok_or_else(|| auth::AuthError::ChatGptCodex("browser OAuth session is no longer active".to_string()))
        .and_then(|login| (app.chatgpt_oauth_driver.complete_browser_redirect)(login, redirect));
    match result {
        Ok(credentials) => {
            finish_chatgpt_oauth(app, &credentials, pending_provider_prompt, ChatGptOAuthMethod::Browser)
        }
        Err(err) => {
            let status = format!("ChatGPT redirect was rejected: {}", redact_auth_error(&err.to_string()));
            if let Some(recovery) = app.first_run_recovery.as_mut() {
                recovery.stage = RecoveryStage::ChatGptOAuthPolling;
                recovery.selected = 0;
                if let Some(oauth) = recovery.chatgpt_oauth.as_mut() {
                    oauth.status = status.clone();
                }
            }
            app.transcript.push(Entry::Error { text: status });
        }
    }
}

pub fn poll_chatgpt_oauth_on_tick(app: &mut App) {
    let tick_ms = app.cli.tick_rate_ms.max(1);
    let Some(recovery) = app.first_run_recovery.as_ref() else {
        return;
    };
    if recovery.stage != RecoveryStage::ChatGptOAuthPolling {
        return;
    }
    let Some(oauth) = recovery.chatgpt_oauth.as_ref() else {
        return;
    };
    let method = oauth.method;
    let pending_provider_prompt = recovery.pending_provider_prompt;
    let expires_at_tick = oauth.expires_at_tick;
    let next_poll_tick = oauth.next_poll_tick;
    if super::agent_lifecycle::now_or_after_deadline(app.ui_tick, expires_at_tick) {
        set_chatgpt_oauth_failure(
            app,
            method,
            pending_provider_prompt,
            match method {
                ChatGptOAuthMethod::Browser => String::from("ChatGPT browser OAuth callback expired."),
                ChatGptOAuthMethod::DeviceCode => String::from("ChatGPT device-code login expired."),
            },
        );
        return;
    }
    if method == ChatGptOAuthMethod::DeviceCode
        && !super::agent_lifecycle::now_or_after_deadline(app.ui_tick, next_poll_tick)
    {
        return;
    }

    match method {
        ChatGptOAuthMethod::Browser => {
            let result = app
                .chatgpt_browser_login
                .as_mut()
                .ok_or_else(|| auth::AuthError::ChatGptCodex("browser OAuth session is no longer active".to_string()))
                .and_then(|login| (app.chatgpt_oauth_driver.poll_browser_login)(login));
            match result {
                Ok(auth::ChatGptCodexBrowserPoll::Pending) => {}
                Ok(auth::ChatGptCodexBrowserPoll::Authorized(credentials)) => {
                    finish_chatgpt_oauth(app, &credentials, pending_provider_prompt, method);
                }
                Err(err) => set_chatgpt_oauth_failure(
                    app,
                    method,
                    pending_provider_prompt,
                    format!("ChatGPT browser OAuth failed: {}", redact_auth_error(&err.to_string())),
                ),
            }
        }
        ChatGptOAuthMethod::DeviceCode => {
            let Some(code) = app
                .first_run_recovery
                .as_ref()
                .and_then(|recovery| recovery.chatgpt_oauth.as_ref())
                .and_then(|oauth| oauth.code.as_ref())
                .cloned()
            else {
                set_chatgpt_oauth_failure(
                    app,
                    method,
                    pending_provider_prompt,
                    String::from("ChatGPT device-code state is unavailable."),
                );
                return;
            };
            match (app.chatgpt_oauth_driver.poll_device_code_once)(&code) {
                Ok(auth::ChatGptCodexDevicePoll::Pending) => {
                    if let Some(oauth) = app
                        .first_run_recovery
                        .as_mut()
                        .and_then(|recovery| recovery.chatgpt_oauth.as_mut())
                    {
                        oauth.status = String::from("Waiting for ChatGPT authorization.");
                        oauth.next_poll_tick = app
                            .ui_tick
                            .wrapping_add(seconds_to_ticks_for_ms(tick_ms, code.interval.unwrap_or(5).max(1)));
                    }
                }
                Ok(auth::ChatGptCodexDevicePoll::SlowDown) => {
                    if let Some(oauth) = app
                        .first_run_recovery
                        .as_mut()
                        .and_then(|recovery| recovery.chatgpt_oauth.as_mut())
                    {
                        oauth.status = String::from("ChatGPT asked the client to slow down; waiting.");
                        oauth.next_poll_tick = app.ui_tick.wrapping_add(seconds_to_ticks_for_ms(
                            tick_ms,
                            code.interval.unwrap_or(5).max(1).saturating_add(5),
                        ));
                    }
                }
                Ok(auth::ChatGptCodexDevicePoll::Authorized(credentials)) => {
                    finish_chatgpt_oauth(app, &credentials, pending_provider_prompt, method);
                }
                Err(err) => set_chatgpt_oauth_failure(
                    app,
                    method,
                    pending_provider_prompt,
                    format!(
                        "ChatGPT device-code polling failed: {}",
                        redact_auth_error(&err.to_string())
                    ),
                ),
            }
        }
    }
}

pub fn seconds_to_ticks(app: &App, seconds: u64) -> u64 {
    seconds_to_ticks_for_ms(app.cli.tick_rate_ms.max(1), seconds)
}

pub fn seconds_to_ticks_for_ms(tick_ms: u64, seconds: u64) -> u64 {
    seconds.saturating_mul(1000).div_ceil(tick_ms).max(1)
}

pub fn redact_auth_error(message: &str) -> String {
    let mut redacted = Vec::new();
    for part in message.split_whitespace() {
        if part.len() >= 24
            || part.contains("access_token")
            || part.contains("refresh_token")
            || part.contains("device_auth_id")
            || part.contains("device_code")
        {
            redacted.push("[redacted]");
        } else {
            redacted.push(part);
        }
    }
    redacted.join(" ")
}

pub fn selected_scope(selected: usize) -> Option<CredentialScope> {
    match selected {
        0 => Some(CredentialScope::Global),
        1 => Some(CredentialScope::Project),
        _ => None,
    }
}

pub fn store_recovery_credential(app: &mut App, recovery: &FirstRunRecovery) {
    let Some(provider) = recovery.provider else {
        app.first_run_recovery = None;
        return;
    };
    let Some(scope) = selected_scope(recovery.selected) else {
        app.first_run_recovery = Some(FirstRunRecovery::missing_provider(
            provider,
            recovery.pending_provider_prompt,
        ));
        return;
    };

    let key = recovery.secret_input.trim();
    let path = match crate::cli::commands::auth::credential_path(scope, &app.cwd) {
        Ok(path) => path,
        Err(err) => {
            app.transcript
                .push(Entry::Error { text: format!("credential store unavailable: {err}") });
            return;
        }
    };

    let Some(env_var) = provider.api_key_env_var() else {
        app.first_run_recovery = Some(FirstRunRecovery::missing_provider(
            provider,
            recovery.pending_provider_prompt,
        ));
        app.transcript
            .push(Entry::Error { text: String::from("ChatGPT Codex uses OAuth login, not API-key storage") });
        return;
    };
    match auth::set_credential(&path, env_var, key) {
        Ok(()) => {
            if scope == CredentialScope::Project
                && let Err(err) = auth::ensure_git_exclude(&app.cwd)
            {
                app.transcript
                    .push(Entry::Error { text: format!("git exclude update failed: {err}") });
            }
            app.transcript
                .push(Entry::Status { text: format!("{} credential stored in {}", provider.label(), scope.label()) });
            if app.model.trim().is_empty() {
                app.first_run_recovery = Some(FirstRunRecovery {
                    provider: Some(provider),
                    stage: RecoveryStage::ModelSelection,
                    pending_provider_prompt: recovery.pending_provider_prompt,
                    selected: 0,
                    secret_input: String::new(),
                    chatgpt_oauth: None,
                });
            } else {
                app.first_run_recovery = None;
            }
        }
        Err(err) => app
            .transcript
            .push(Entry::Error { text: format!("credential write failed: {err}") }),
    }
}

pub fn remove_recovery_credential(app: &mut App, recovery: &FirstRunRecovery) {
    let Some(provider) = recovery.provider else {
        app.first_run_recovery = None;
        return;
    };
    let Some(scope) = selected_scope(recovery.selected) else {
        app.first_run_recovery = None;
        app.transcript
            .push(Entry::Status { text: String::from("logout cancelled") });
        return;
    };
    let path = match crate::cli::commands::auth::credential_path(scope, &app.cwd) {
        Ok(path) => path,
        Err(err) => {
            app.transcript
                .push(Entry::Error { text: format!("credential store unavailable: {err}") });
            return;
        }
    };
    let Some(env_var) = provider.api_key_env_var() else {
        app.first_run_recovery = None;
        app.transcript
            .push(Entry::Error { text: String::from("ChatGPT Codex credentials are stored in ~/.thndrs/auth.json") });
        return;
    };
    match auth::remove_credential(&path, env_var) {
        Ok(()) => {
            app.first_run_recovery = None;
            app.transcript.push(Entry::Status {
                text: format!("{} credential removed from {}", provider.label(), scope.label()),
            });
        }
        Err(err) => app
            .transcript
            .push(Entry::Error { text: format!("credential remove failed: {err}") }),
    }
}

fn select_setup_model(app: &mut App, recovery: &FirstRunRecovery) {
    let Some(provider) = recovery.provider else {
        app.first_run_recovery = Some(FirstRunRecovery::setup(SetupProviderArg::ChatgptCodex));
        return;
    };
    let options = setup_model_options(provider);
    let Some(model) = options.get(recovery.selected).map(|item| item.label.clone()) else {
        return;
    };
    app.model = model.clone();
    app.cli.model = model.clone();
    app.transcript
        .push(Entry::Status { text: format!("model selected: {model}") });
    app.first_run_recovery = Some(FirstRunRecovery {
        provider: Some(provider),
        stage: RecoveryStage::ModelConfigScope,
        pending_provider_prompt: recovery.pending_provider_prompt,
        selected: 0,
        secret_input: String::new(),
        chatgpt_oauth: None,
    });
}

fn first_run_provider(selected: usize) -> Option<SetupProviderArg> {
    match selected {
        0 => Some(SetupProviderArg::ChatgptCodex),
        1 => Some(SetupProviderArg::Umans),
        _ => None,
    }
}