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::console::{Key, Term};
16use dialoguer::theme::{ColorfulTheme, Theme};
17use dialoguer::{Input, Password, Select};
18use taskfast_client::UserProfile;
19
20/// Wallet-provisioning choice surfaced by the interactive prompt.
21/// Mirrors the three mutually-exclusive flag paths (`--wallet-address`,
22/// `--generate-wallet`, `--skip-wallet`).
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum WalletMode {
25    /// Bring-your-own-wallet: caller supplies an existing address.
26    Byow,
27    /// Generate a fresh keypair and persist it via the keystore module.
28    Generate,
29    /// Defer wallet provisioning — agent runs without settlement.
30    Skip,
31}
32
33/// Test-seam trait covering every TTY interaction the init flow needs.
34/// The real implementation ([`DialoguerPrompter`]) reads from the
35/// terminal; tests inject a scripted double.
36pub trait Prompter {
37    /// Prompt for a user PAT (`tf_user_*`). `accounts_url` is the page
38    /// where the human can mint/copy one.
39    fn pat(&self, accounts_url: &str) -> io::Result<String>;
40    /// Prompt for a wallet-mode choice (BYOW / generate / skip).
41    fn wallet_mode(&self) -> io::Result<WalletMode>;
42    /// Prompt for a `0x…`-prefixed wallet address (BYOW path).
43    fn wallet_address(&self) -> io::Result<String>;
44    /// Prompt for a keystore password, asking for confirmation (generate path).
45    fn wallet_password(&self) -> io::Result<String>;
46}
47
48/// Real [`Prompter`] backed by `dialoguer`. Uses the crate's default
49/// colorful theme so the PAT prompt, select list, etc. match standard
50/// CLI ergonomics.
51pub struct DialoguerPrompter;
52
53impl Prompter for DialoguerPrompter {
54    fn pat(&self, accounts_url: &str) -> io::Result<String> {
55        // Printed to stderr so the envelope on stdout stays machine-parseable
56        // in pipelines that happen to be TTY-attached.
57        eprintln!("Get a PAT at: {accounts_url}");
58        read_masked("Paste your PAT")
59    }
60
61    fn wallet_mode(&self) -> io::Result<WalletMode> {
62        let choices = [
63            "Use existing wallet (BYOW)",
64            "Generate new wallet",
65            "Skip for now",
66        ];
67        let idx = Select::with_theme(&ColorfulTheme::default())
68            .with_prompt("Wallet setup")
69            .items(&choices)
70            .default(0)
71            .interact()
72            .map_err(dialoguer_err)?;
73        Ok(match idx {
74            0 => WalletMode::Byow,
75            1 => WalletMode::Generate,
76            _ => WalletMode::Skip,
77        })
78    }
79
80    fn wallet_address(&self) -> io::Result<String> {
81        Input::<String>::with_theme(&ColorfulTheme::default())
82            .with_prompt("Wallet address")
83            .validate_with(|s: &String| validate_wallet_address(s))
84            .interact_text()
85            .map_err(dialoguer_err)
86    }
87
88    fn wallet_password(&self) -> io::Result<String> {
89        Password::with_theme(&ColorfulTheme::default())
90            .with_prompt("Keystore password")
91            .with_confirmation("Confirm password", "Passwords don't match")
92            .interact()
93            .map_err(dialoguer_err)
94    }
95}
96
97/// Like `Password::interact`, but echoes `*` per character so a paste is
98/// visibly received — `Password` turns echo off entirely and dialoguer
99/// 0.11 has no mask option. Empty input re-prompts, matching `Password`.
100fn read_masked(prompt: &str) -> io::Result<String> {
101    let term = Term::stderr();
102    if !term.is_term() {
103        // `read_key` returns `Key::Unknown` forever off-TTY.
104        return Err(io::Error::other("stderr is not a terminal"));
105    }
106    let theme = ColorfulTheme::default();
107    let mut line = String::new();
108    theme
109        .format_password_prompt(&mut line, prompt)
110        .map_err(io::Error::other)?;
111    term.write_str(&line)?;
112    let mut secret = String::new();
113    loop {
114        match term.read_key()? {
115            Key::Enter if !secret.is_empty() => break,
116            // Raw mode: the tty no longer handles Ctrl-U, and control
117            // bytes would otherwise end up in the secret.
118            Key::Char('\u{15}') => {
119                term.clear_chars(secret.chars().count())?;
120                secret.clear();
121            }
122            Key::Char(c) if !c.is_control() => {
123                secret.push(c);
124                term.write_str("*")?;
125            }
126            Key::Backspace if secret.pop().is_some() => term.clear_chars(1)?,
127            _ => {}
128        }
129    }
130    // ponytail: newline, not dialoguer's clear-and-report — a long mask can
131    // wrap, and `clear_line` would only erase the last row.
132    term.write_line("")?;
133    Ok(secret)
134}
135
136fn dialoguer_err(e: dialoguer::Error) -> io::Error {
137    match e {
138        dialoguer::Error::IO(io) => io,
139    }
140}
141
142/// `0x` + 40 hex chars. Trims surrounding whitespace before checking so
143/// copy-paste with a trailing newline is tolerated.
144fn validate_wallet_address(s: &str) -> Result<(), &'static str> {
145    let trimmed = s.trim();
146    let rest = trimmed
147        .strip_prefix("0x")
148        .ok_or("address must start with 0x")?;
149    if rest.len() != 40 {
150        return Err("address must be 0x + 40 hex characters");
151    }
152    if !rest.bytes().all(|b| b.is_ascii_hexdigit()) {
153        return Err("address must be hexadecimal");
154    }
155    Ok(())
156}
157
158/// True when both stdin and stdout are attached to a terminal. False in
159/// pipes, redirects, CI, and under the test harness — callers use this
160/// to decide whether prompting is safe.
161pub fn is_interactive() -> bool {
162    io::stdin().is_terminal() && io::stdout().is_terminal()
163}
164
165/// Format the post-auth greeting. With a profile: `"Hi Name <email>"`.
166/// Without one (server lacks `/users/me`, returned 404): a generic
167/// authenticated message so the user still gets visible confirmation.
168pub fn greeting(profile: Option<&UserProfile>) -> String {
169    match profile {
170        Some(p) => format!("Hi {} <{}>", p.name, p.email),
171        None => "Hi there — authenticated.".to_string(),
172    }
173}
174
175#[cfg(test)]
176mod tests {
177    use super::*;
178
179    #[test]
180    fn greeting_with_profile() {
181        let p = UserProfile {
182            name: "Alice Smith".into(),
183            email: "alice@example.com".into(),
184        };
185        assert_eq!(greeting(Some(&p)), "Hi Alice Smith <alice@example.com>");
186    }
187
188    #[test]
189    fn greeting_without_profile_is_neutral() {
190        assert_eq!(greeting(None), "Hi there — authenticated.");
191    }
192
193    #[test]
194    fn valid_wallet_address_accepted() {
195        assert!(validate_wallet_address("0x0123456789abcdef0123456789ABCDEF01234567").is_ok());
196    }
197
198    #[test]
199    fn wallet_address_missing_0x_rejected() {
200        assert!(validate_wallet_address("0123456789abcdef0123456789ABCDEF01234567").is_err());
201    }
202
203    #[test]
204    fn wallet_address_wrong_length_rejected() {
205        assert!(validate_wallet_address("0xabc").is_err());
206    }
207
208    #[test]
209    fn wallet_address_non_hex_rejected() {
210        assert!(validate_wallet_address("0xGGGG456789abcdef0123456789ABCDEF01234567").is_err());
211    }
212
213    #[test]
214    fn wallet_address_trims_whitespace() {
215        assert!(validate_wallet_address("  0x0123456789abcdef0123456789ABCDEF01234567\n").is_ok());
216    }
217}