|
| 1 | +"""Existing Browser Manager - orchestrator for connecting to existing browsers.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | +import logging |
| 5 | +from typing import Any, Optional |
| 6 | + |
| 7 | +from .base import BrowserConfig, BrowserConnectionResult, ConnectionStatus |
| 8 | +from .cdp_detector import CdpDetector |
| 9 | +from .browser_connector import BrowserConnector |
| 10 | +from .token_navigator import TokenNavigator, NavigationStatus |
| 11 | + |
| 12 | +log = logging.getLogger("nlp2cmd.browser_manager.existing") |
| 13 | + |
| 14 | + |
| 15 | +class ExistingBrowserManager: |
| 16 | + """Orchestrator for connecting to existing browser via CDP. |
| 17 | + |
| 18 | + Coordinates CDP detection, browser connection, and navigation. |
| 19 | + """ |
| 20 | + |
| 21 | + def __init__(self, config: Optional[BrowserConfig] = None) -> None: |
| 22 | + self.config = config or BrowserConfig() |
| 23 | + self.cdp_detector = CdpDetector(self.config) |
| 24 | + self.browser_connector = BrowserConnector(self.config) |
| 25 | + self.token_navigator = TokenNavigator(self.config) |
| 26 | + |
| 27 | + def connect_and_navigate( |
| 28 | + self, |
| 29 | + verbose: bool = True, |
| 30 | + console: Optional[Any] = None, |
| 31 | + ) -> BrowserConnectionResult: |
| 32 | + """Find existing browser, connect, and navigate to token page. |
| 33 | + |
| 34 | + Args: |
| 35 | + verbose: Whether to log detailed output |
| 36 | + console: Optional Rich console for formatted output |
| 37 | + |
| 38 | + Returns: |
| 39 | + BrowserConnectionResult with connection details and page |
| 40 | + """ |
| 41 | + # Stage 1: Find CDP port |
| 42 | + port = self.cdp_detector.find_cdp_port(verbose=verbose, console=console) |
| 43 | + |
| 44 | + if not port: |
| 45 | + result = BrowserConnectionResult() |
| 46 | + result.status = ConnectionStatus.NO_CDP |
| 47 | + result.error = "No existing browser with CDP found" |
| 48 | + return result |
| 49 | + |
| 50 | + # Stage 2: Connect to browser |
| 51 | + result = self.browser_connector.connect(port, verbose=verbose, console=console) |
| 52 | + |
| 53 | + if not result.success: |
| 54 | + return result |
| 55 | + |
| 56 | + if not result.page: |
| 57 | + result.status = ConnectionStatus.CONTEXT_FAILED |
| 58 | + result.error = "Browser connected but page creation failed" |
| 59 | + return result |
| 60 | + |
| 61 | + # Stage 3: Navigate to tokens page |
| 62 | + nav_status, actual_url = self.token_navigator.navigate( |
| 63 | + result.page, verbose=verbose, console=console |
| 64 | + ) |
| 65 | + |
| 66 | + result.actual_url = actual_url |
| 67 | + |
| 68 | + if nav_status == NavigationStatus.FAILED: |
| 69 | + result.success = False |
| 70 | + result.error = f"Navigation failed, last URL: {actual_url}" |
| 71 | + elif nav_status == NavigationStatus.WRONG_PAGE: |
| 72 | + # Still proceed - user can navigate manually |
| 73 | + log.debug("Navigated to unexpected URL: %s", actual_url) |
| 74 | + |
| 75 | + return result |
| 76 | + |
| 77 | + def get_token_interactive( |
| 78 | + self, |
| 79 | + result: BrowserConnectionResult, |
| 80 | + verbose: bool = True, |
| 81 | + console: Optional[Any] = None, |
| 82 | + ) -> Optional[str]: |
| 83 | + """Get token from user via interactive prompt. |
| 84 | + |
| 85 | + Args: |
| 86 | + result: BrowserConnectionResult with connected page |
| 87 | + verbose: Whether to log detailed output |
| 88 | + console: Optional Rich console for formatted output |
| 89 | + |
| 90 | + Returns: |
| 91 | + Token string if entered, None otherwise |
| 92 | + """ |
| 93 | + if not result.page: |
| 94 | + return None |
| 95 | + |
| 96 | + if console and verbose: |
| 97 | + console.print(f"[dim] [Token Step 1/4] Navigated to: {result.actual_url}[/dim]") |
| 98 | + console.print(f"[cyan] [Token Step 2/4] Showing instructions:[/cyan]") |
| 99 | + console.print(" 1. Login to Hugging Face if needed") |
| 100 | + console.print(" 2. Click 'New token' button") |
| 101 | + console.print(" 3. Set name: 'nlp2cmd'") |
| 102 | + console.print(" 4. Select 'Read' role") |
| 103 | + console.print(" 5. Click 'Generate token'") |
| 104 | + console.print(" 6. Copy the token and paste it here") |
| 105 | + else: |
| 106 | + print("\n📋 Instructions:") |
| 107 | + print(" 1. Login to Hugging Face if needed") |
| 108 | + print(" 2. Click 'New token' button") |
| 109 | + print(" 3. Set name: 'nlp2cmd'") |
| 110 | + print(" 4. Select 'Read' role") |
| 111 | + print(" 5. Click 'Generate token'") |
| 112 | + print(" 6. Copy the token and paste it here") |
| 113 | + |
| 114 | + if console and verbose: |
| 115 | + console.print(f"[cyan] [Token Step 3/4] Waiting for user input...[/cyan]") |
| 116 | + console.print(f"[bold yellow] ⚠️ CHECK YOUR TERMINAL - waiting for token input![/bold yellow]") |
| 117 | + |
| 118 | + try: |
| 119 | + # Print visible separator |
| 120 | + print("\n" + "="*60) |
| 121 | + print("🔐 ENTER YOUR HF_TOKEN BELOW 🔐") |
| 122 | + print("="*60) |
| 123 | + |
| 124 | + token = input("🔑 Paste HF_TOKEN here: ").strip() |
| 125 | + |
| 126 | + print("="*60) |
| 127 | + |
| 128 | + if console and verbose: |
| 129 | + console.print(f"[dim] Input received: {'Yes' if token else 'No'}[/dim]") |
| 130 | + |
| 131 | + if token: |
| 132 | + if console and verbose: |
| 133 | + console.print(f"[cyan] [Token Step 4/4] Closing browser page...[/cyan]") |
| 134 | + |
| 135 | + try: |
| 136 | + result.close() |
| 137 | + if console and verbose: |
| 138 | + console.print(f"[green] ✓ Browser connection closed[/green]") |
| 139 | + except Exception as e: |
| 140 | + if console and verbose: |
| 141 | + console.print(f"[dim] Note: Could not close cleanly: {e}[/dim]") |
| 142 | + |
| 143 | + return token |
| 144 | + else: |
| 145 | + if console and verbose: |
| 146 | + console.print(f"[yellow] ⚠ No token entered[/yellow]") |
| 147 | + |
| 148 | + except EOFError: |
| 149 | + if console and verbose: |
| 150 | + console.print(f"[red] ✗ EOFError (no input available)[/red]") |
| 151 | + except KeyboardInterrupt: |
| 152 | + if console and verbose: |
| 153 | + console.print(f"[yellow] ⚠ User cancelled (KeyboardInterrupt)[/yellow]") |
| 154 | + except Exception as e: |
| 155 | + if console and verbose: |
| 156 | + console.print(f"[red] ✗ Error getting input: {e}[/red]") |
| 157 | + |
| 158 | + # Cleanup on failure |
| 159 | + result.close() |
| 160 | + return None |
0 commit comments