updated for wsl windows login features

This commit is contained in:
jettythek
2025-12-07 11:29:45 -08:00
parent cf3cfd02ed
commit 3e779340ec
7 changed files with 206 additions and 404 deletions

View File

@@ -1,5 +1,4 @@
# tito/commands/login.py
import webbrowser
import time
import json
import urllib.parse
@@ -8,6 +7,7 @@ from argparse import ArgumentParser, Namespace
from rich.prompt import Confirm
from tito.commands.base import BaseCommand
from tito.core.auth import AuthReceiver, save_credentials, delete_credentials, ENDPOINTS, is_logged_in
from tito.core.browser import open_url
class LoginCommand(BaseCommand):
@property
@@ -73,9 +73,10 @@ class LoginCommand(BaseCommand):
query_string = urllib.parse.urlencode(params)
target_url = f"{ENDPOINTS['cli_login']}?{query_string}"
self.console.print(f"Opening browser to: [cyan]{target_url}[/cyan]")
self.console.print("Waiting for authentication...")
webbrowser.open(target_url)
# Use cross-platform browser opener
open_url(target_url, self.console, show_manual_fallback=True)
self.console.print("\n[dim]Waiting for authentication...[/dim]")
tokens = receiver.wait_for_tokens()
if tokens:
save_credentials(tokens)
@@ -110,7 +111,7 @@ class LogoutCommand(BaseCommand):
# Open browser to local logout endpoint
logout_url = f"http://127.0.0.1:{port}/logout"
self.console.print(f"Opening browser to complete logout...")
webbrowser.open(logout_url)
open_url(logout_url, self.console, show_manual_fallback=False)
# Give browser time to redirect and close
time.sleep(2.0)

View File

@@ -13,7 +13,6 @@ import sys
import os
import platform
import datetime
import webbrowser
from pathlib import Path
from argparse import ArgumentParser, Namespace
from typing import Dict, Any, Optional
@@ -28,6 +27,7 @@ from .base import BaseCommand
from .login import LoginCommand
from ..core.console import get_console
from ..core.auth import is_logged_in
from ..core.browser import open_url
def _print_file_update(console, file_path: Path) -> None:
"""Print a notification when a file is created or updated."""
@@ -402,7 +402,7 @@ class SetupCommand(BaseCommand):
))
if Confirm.ask("[bold]Update your community profile?[/bold]", default=True):
self.console.print("[dim]Opening profile editor...[/dim]")
webbrowser.open("https://tinytorch.ai/community/?action=profile")
open_url("https://tinytorch.ai/community/?action=profile", self.console, show_manual_fallback=True)
else:
self.console.print("[yellow]⚠️ Community connection failed or was cancelled. You can try again later with 'tito login'.[/yellow]")
except Exception as e:

110
tito/core/browser.py Normal file
View File

@@ -0,0 +1,110 @@
"""
Cross-platform browser opening utility for TinyTorch CLI.
Handles WSL, macOS, Linux, and Windows environments gracefully.
"""
import webbrowser
import subprocess
import platform
from typing import Optional
from rich.console import Console
from rich.panel import Panel
def is_wsl() -> bool:
"""Check if running in WSL (Windows Subsystem for Linux) environment."""
try:
with open('/proc/version', 'r') as f:
return 'microsoft' in f.read().lower()
except:
return False
def open_url(url: str, console: Optional[Console] = None, show_manual_fallback: bool = True) -> bool:
"""
Open URL in browser with cross-platform support.
Args:
url: The URL to open
console: Optional Rich console for output
show_manual_fallback: Whether to show manual instructions if browser fails
Returns:
True if browser was opened successfully, False otherwise
"""
if console is None:
console = Console()
browser_opened = False
system = platform.system()
# Try WSL-specific approach first
if is_wsl():
console.print("[cyan]Detected WSL environment - opening Windows browser...[/cyan]")
browser_opened = _open_url_wsl(url)
# Try macOS-specific approach
elif system == "Darwin":
browser_opened = _open_url_macos(url)
# Try standard webbrowser module
if not browser_opened:
try:
browser_opened = webbrowser.open(url)
except Exception:
pass
# Handle success/failure
if browser_opened:
console.print(f"[green]✓[/green] Browser opened to: [cyan]{url}[/cyan]")
else:
if show_manual_fallback:
console.print()
console.print(Panel(
f"[yellow]⚠️ Could not open browser automatically[/yellow]\n\n"
f"Please manually open this URL in your browser:\n\n"
f"[cyan]{url}[/cyan]\n\n"
f"Copy and paste this link into your browser to continue.",
title="Manual Browser Access Required",
border_style="yellow"
))
console.print()
else:
console.print(f"[yellow]⚠️ Could not open browser. Please manually visit:[/yellow] [cyan]{url}[/cyan]")
return browser_opened
def _open_url_wsl(url: str) -> bool:
"""Try to open URL in Windows browser from WSL."""
try:
# Method 1: Use cmd.exe to start default browser
result = subprocess.run(
['cmd.exe', '/c', 'start', url],
capture_output=True,
timeout=5
)
if result.returncode == 0:
return True
# Method 2: Try powershell.exe
result = subprocess.run(
['powershell.exe', '-Command', f'Start-Process "{url}"'],
capture_output=True,
timeout=5
)
return result.returncode == 0
except Exception:
return False
def _open_url_macos(url: str) -> bool:
"""Try to open URL in macOS default browser."""
try:
result = subprocess.run(
['open', url],
capture_output=True,
timeout=5
)
return result.returncode == 0
except Exception:
return False