Skip to main content

taskfast_cli/cmd/
init_tui.rs

1// SPDX-License-Identifier: MIT
2//! Interactive first-run helpers for `taskfast init`.
3//!
4//! The non-interactive path (flag / env / config driven) is the default
5//! and unchanged — see `cmd/init.rs`. This module gates the TTY-only
6//! branch: when a human runs `taskfast init` with no credentials
7//! resolvable, we prompt for a PAT, greet via `GET /users/me`, and walk
8//! wallet provisioning.
9//!
10//! All interactive surface goes through [`Prompter`] so tests can inject
11//! a scripted implementation without driving a real TTY.
12
13use std::io::{self, IsTerminal};
14
15use dialoguer::theme::ColorfulTheme;
16use dialoguer::{Input, Password, Select};
17use taskfast_client::UserProfile;
18
19/// Wallet-provisioning choice surfaced by the interactive prompt.
20/// Mirrors the three mutually-exclusive flag paths (`--wallet-address`,
21/// `--generate-wallet`, `--skip-wallet`).
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum WalletMode {
24    /// Bring-your-own-wallet: caller supplies an existing address.
25    Byow,
26    /// Generate a fresh keypair and persist it via the keystore module.
27    Generate,
28    /// Defer wallet provisioning — agent runs without settlement.
29    Skip,
30}
31
32/// Test-seam trait covering every TTY interaction the init flow needs.
33/// The real implementation ([`DialoguerPrompter`]) reads from the
34/// terminal; tests inject a scripted double.
35pub trait Prompter {
36    /// Prompt for a user PAT (`tf_user_*`). `accounts_url` is the page
37    /// where the human can mint/copy one.
38    fn pat(&self, accounts_url: &str) -> io::Result<String>;
39    /// Prompt for a wallet-mode choice (BYOW / generate / skip).
40    fn wallet_mode(&self) -> io::Result<WalletMode>;
41    /// Prompt for a `0x…`-prefixed wallet address (BYOW path).
42    fn wallet_address(&self) -> io::Result<String>;
43    /// Prompt for a keystore password, asking for confirmation (generate path).
44    fn wallet_password(&self) -> io::Result<String>;
45}
46
47/// Real [`Prompter`] backed by `dialoguer`. Uses the crate's default
48/// colorful theme so the PAT prompt, select list, etc. match standard
49/// CLI ergonomics.
50pub struct DialoguerPrompter;
51
52impl Prompter for DialoguerPrompter {
53    fn pat(&self, accounts_url: &str) -> io::Result<String> {
54        // Printed to stderr so the envelope on stdout stays machine-parseable
55        // in pipelines that happen to be TTY-attached.
56        eprintln!("Get a PAT at: {accounts_url}");
57        Password::with_theme(&ColorfulTheme::default())
58            .with_prompt("Paste your PAT")
59            .interact()
60            .map_err(dialoguer_err)
61    }
62
63    fn wallet_mode(&self) -> io::Result<WalletMode> {
64        let choices = [
65            "Use existing wallet (BYOW)",
66            "Generate new wallet",
67            "Skip for now",
68        ];
69        let idx = Select::with_theme(&ColorfulTheme::default())
70            .with_prompt("Wallet setup")
71            .items(&choices)
72            .default(0)
73            .interact()
74            .map_err(dialoguer_err)?;
75        Ok(match idx {
76            0 => WalletMode::Byow,
77            1 => WalletMode::Generate,
78            _ => WalletMode::Skip,
79        })
80    }
81
82    fn wallet_address(&self) -> io::Result<String> {
83        Input::<String>::with_theme(&ColorfulTheme::default())
84            .with_prompt("Wallet address")
85            .validate_with(|s: &String| validate_wallet_address(s))
86            .interact_text()
87            .map_err(dialoguer_err)
88    }
89
90    fn wallet_password(&self) -> io::Result<String> {
91        Password::with_theme(&ColorfulTheme::default())
92            .with_prompt("Keystore password")
93            .with_confirmation("Confirm password", "Passwords don't match")
94            .interact()
95            .map_err(dialoguer_err)
96    }
97}
98
99fn dialoguer_err(e: dialoguer::Error) -> io::Error {
100    match e {
101        dialoguer::Error::IO(io) => io,
102    }
103}
104
105/// `0x` + 40 hex chars. Trims surrounding whitespace before checking so
106/// copy-paste with a trailing newline is tolerated.
107fn validate_wallet_address(s: &str) -> Result<(), &'static str> {
108    let trimmed = s.trim();
109    let rest = trimmed
110        .strip_prefix("0x")
111        .ok_or("address must start with 0x")?;
112    if rest.len() != 40 {
113        return Err("address must be 0x + 40 hex characters");
114    }
115    if !rest.bytes().all(|b| b.is_ascii_hexdigit()) {
116        return Err("address must be hexadecimal");
117    }
118    Ok(())
119}
120
121/// True when both stdin and stdout are attached to a terminal. False in
122/// pipes, redirects, CI, and under the test harness — callers use this
123/// to decide whether prompting is safe.
124pub fn is_interactive() -> bool {
125    io::stdin().is_terminal() && io::stdout().is_terminal()
126}
127
128/// Format the post-auth greeting. With a profile: `"Hi Name <email>"`.
129/// Without one (server lacks `/users/me`, returned 404): a generic
130/// authenticated message so the user still gets visible confirmation.
131pub fn greeting(profile: Option<&UserProfile>) -> String {
132    match profile {
133        Some(p) => format!("Hi {} <{}>", p.name, p.email),
134        None => "Hi there — authenticated.".to_string(),
135    }
136}
137
138#[cfg(test)]
139mod tests {
140    use super::*;
141
142    #[test]
143    fn greeting_with_profile() {
144        let p = UserProfile {
145            name: "Alice Smith".into(),
146            email: "alice@example.com".into(),
147        };
148        assert_eq!(greeting(Some(&p)), "Hi Alice Smith <alice@example.com>");
149    }
150
151    #[test]
152    fn greeting_without_profile_is_neutral() {
153        assert_eq!(greeting(None), "Hi there — authenticated.");
154    }
155
156    #[test]
157    fn valid_wallet_address_accepted() {
158        assert!(validate_wallet_address("0x0123456789abcdef0123456789ABCDEF01234567").is_ok());
159    }
160
161    #[test]
162    fn wallet_address_missing_0x_rejected() {
163        assert!(validate_wallet_address("0123456789abcdef0123456789ABCDEF01234567").is_err());
164    }
165
166    #[test]
167    fn wallet_address_wrong_length_rejected() {
168        assert!(validate_wallet_address("0xabc").is_err());
169    }
170
171    #[test]
172    fn wallet_address_non_hex_rejected() {
173        assert!(validate_wallet_address("0xGGGG456789abcdef0123456789ABCDEF01234567").is_err());
174    }
175
176    #[test]
177    fn wallet_address_trims_whitespace() {
178        assert!(validate_wallet_address("  0x0123456789abcdef0123456789ABCDEF01234567\n").is_ok());
179    }
180}