use async_trait::async_trait;
use std::time::Duration;
use crate::config::GrokConfig;
use crate::error::{Error, Result};
use crate::providers::{Provider, ProviderCapabilities, ProviderTrait};
use crate::puppet::{PromptRequest, PromptResponse};
use crate::session::Session;
pub struct GrokProvider {
config: GrokConfig,
}
impl GrokProvider {
pub fn new() -> Self {
Self {
config: GrokConfig::default(),
}
}
pub fn with_config(config: GrokConfig) -> Self {
Self { config }
}
async fn navigate_to_chat(&self, session: &Session) -> Result<()> {
session
.navigate(&self.config.chat_url)
.await
.map_err(|e| Error::Navigation(e.to_string()))
}
async fn wait_for_response(&self, session: &Session) -> Result<()> {
session
.wait_for_element_hidden(
r#"div[data-testid="grokTypingIndicator"]"#,
Duration::from_secs(120),
)
.await
.map_err(|_| Error::Timeout(120_000))?;
tokio::time::sleep(Duration::from_millis(500)).await;
Ok(())
}
}
impl Default for GrokProvider {
fn default() -> Self {
Self::new()
}
}
#[async_trait]
impl ProviderTrait for GrokProvider {
fn provider(&self) -> Provider {
Provider::Grok
}
fn capabilities(&self) -> ProviderCapabilities {
ProviderCapabilities {
conversation: true,
vision: true,
file_upload: true, code_execution: false,
web_search: true, max_context: Some(128_000), models: vec!["grok-2".into(), "grok-2-mini".into()],
}
}
async fn is_authenticated(&self, session: &Session) -> Result<bool> {
let url = session.current_url().await?;
if url.contains("/login") || url.contains("/i/flow/login") {
return Ok(false);
}
session.element_exists(&self.config.input_selector).await
}
async fn authenticate(&self, session: &mut Session) -> Result<()> {
session
.navigate(&self.config.login_url)
.await
.map_err(|e| Error::Navigation(e.to_string()))?;
if self.is_authenticated(session).await? {
tracing::info!("Already authenticated to Grok");
return Ok(());
}
tracing::info!("Waiting for manual authentication to X/Grok...");
tracing::info!("Please complete the login in the browser window.");
tracing::info!("If you have 2FA enabled, you'll need to approve it.");
session
.wait_for_url_contains("/i/grok", Duration::from_secs(300))
.await
.map_err(|_| Error::AuthenticationFailed {
provider: "grok".into(),
reason: "Login timeout - please complete authentication manually".into(),
})?;
tokio::time::sleep(Duration::from_secs(2)).await;
if !self.is_authenticated(session).await? {
return Err(Error::AuthenticationFailed {
provider: "grok".into(),
reason: "Authentication verification failed".into(),
});
}
session.save_cookies().await?;
tracing::info!("Successfully authenticated to Grok");
Ok(())
}
async fn send_prompt(
&self,
session: &Session,
request: &PromptRequest,
) -> Result<PromptResponse> {
self.navigate_to_chat(session).await?;
self.wait_ready(session).await?;
session
.click(&self.config.input_selector)
.await
.map_err(|_| Error::ElementNotFound {
selector: self.config.input_selector.clone(),
})?;
session
.type_text(&self.config.input_selector, &request.message)
.await
.map_err(|e| Error::Browser(e.to_string()))?;
if !request.attachments.is_empty() {
if let Some(ref selector) = self.config.file_input_selector {
let mut paths = Vec::new();
for attachment in &request.attachments {
let temp_dir = std::env::temp_dir().join("webpuppet_uploads_grok");
std::fs::create_dir_all(&temp_dir)
.map_err(|e| Error::Browser(e.to_string()))?;
let file_path = temp_dir.join(&attachment.name);
std::fs::write(&file_path, &attachment.data)
.map_err(|e| Error::Browser(e.to_string()))?;
paths.push(file_path);
}
session.upload_files(selector, &paths).await?;
tokio::time::sleep(Duration::from_secs(2)).await;
} else {
tracing::warn!("Grok provider does not have a file input selector configured");
}
}
tokio::time::sleep(Duration::from_millis(100)).await;
session
.click(&self.config.submit_selector)
.await
.map_err(|_| Error::ElementNotFound {
selector: self.config.submit_selector.clone(),
})?;
self.wait_for_response(session).await?;
let response_text = self.extract_response(session).await?;
Ok(PromptResponse {
text: response_text,
provider: Provider::Grok,
conversation_id: session.conversation_id().cloned(),
timestamp: chrono::Utc::now(),
tokens_used: None,
metadata: Default::default(),
})
}
async fn new_conversation(&self, session: &Session) -> Result<String> {
session
.navigate(&self.config.chat_url)
.await
.map_err(|e| Error::Navigation(e.to_string()))?;
self.wait_ready(session).await?;
let conversation_id = uuid::Uuid::new_v4().to_string();
Ok(conversation_id)
}
async fn continue_conversation(
&self,
session: &Session,
_conversation_id: &str,
request: &PromptRequest,
) -> Result<PromptResponse> {
self.send_prompt(session, request).await
}
async fn current_url(&self, session: &Session) -> Result<String> {
session.current_url().await
}
async fn wait_ready(&self, session: &Session) -> Result<()> {
session
.wait_for_element(&self.config.input_selector, Duration::from_secs(30))
.await
.map_err(|_| Error::Timeout(30_000))?;
Ok(())
}
async fn extract_response(&self, session: &Session) -> Result<String> {
let responses = session
.query_all(&self.config.response_selector)
.await
.map_err(|e| Error::ExtractionFailed(e.to_string()))?;
if responses.is_empty() {
return Err(Error::ExtractionFailed("No response found".into()));
}
let last_response = responses.last().unwrap();
let text = session
.get_text_content(last_response)
.await
.map_err(|e| Error::ExtractionFailed(e.to_string()))?;
Ok(text)
}
async fn check_rate_limit(&self, session: &Session) -> Result<Option<Duration>> {
let rate_limit_selectors = [
"div[data-testid='rate-limit']",
"span:contains('rate limit')",
"div.rate-limit-warning",
];
for selector in &rate_limit_selectors {
if session.element_exists(selector).await.unwrap_or(false) {
return Ok(Some(Duration::from_secs(900)));
}
}
Ok(None)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_grok_capabilities() {
let provider = GrokProvider::new();
let caps = provider.capabilities();
assert!(caps.conversation);
assert!(caps.vision);
assert!(caps.web_search); assert!(caps.file_upload); assert_eq!(caps.max_context, Some(128_000));
}
#[test]
fn test_grok_provider_id() {
let provider = GrokProvider::new();
assert_eq!(provider.provider(), Provider::Grok);
}
}