add debug

This commit is contained in:
Josh at WLTechBlog
2025-08-15 16:29:57 -05:00
parent 4ade9ebafe
commit cf34368901
4 changed files with 49 additions and 645 deletions

View File

@@ -14,13 +14,16 @@ import (
var (
daemonHost = flag.String("listen", "localhost", "Listen address")
port = flag.Int("port", 8989, "Listen port")
debug = flag.Bool("debug", false, "Enable debug logging")
)
func main() {
flag.Parse()
log.Printf("Starting cremote daemon on %s:%d (debug: %v)", *daemonHost, *port, *debug)
// Create and start the daemon
d, err := daemon.NewDaemon(*daemonHost, *port)
d, err := daemon.NewDaemon(*daemonHost, *port, *debug)
if err != nil {
log.Fatalf("Failed to create daemon: %v", err)
}

View File

@@ -26,6 +26,7 @@ type Daemon struct {
currentTab string // ID of the current/last used tab
tabHistory []string // Stack of tab IDs in order of activation (LIFO)
consoleLogs map[string][]ConsoleLog // Maps tab ID to console logs
debug bool // Enable debug logging
mu sync.Mutex
server *http.Server
}
@@ -71,11 +72,26 @@ func checkChromeDevTools(port int) bool {
return resp.StatusCode == 200
}
// debugLog logs a message only if debug mode is enabled
func (d *Daemon) debugLog(format string, args ...interface{}) {
if d.debug {
log.Printf("[DEBUG] "+format, args...)
}
}
// NewDaemon creates a new daemon instance
func NewDaemon(host string, port int) (*Daemon, error) {
func NewDaemon(host string, port int, debug bool) (*Daemon, error) {
if debug {
log.Printf("[DEBUG] Creating new daemon on %s:%d", host, port)
}
// Check if Chrome is running on the debug port
chromePort := 9222 // Default Chrome debug port
if debug {
log.Printf("[DEBUG] Checking if Chrome is running on port %d", chromePort)
}
if !checkChromeRunning(chromePort) {
return nil, fmt.Errorf("Chromium is not running with remote debugging enabled on port %d.\n\nTo start Chromium with remote debugging:\n chromium --remote-debugging-port=%d --user-data-dir=/tmp/chromium-debug &\n # or\n google-chrome --remote-debugging-port=%d --user-data-dir=/tmp/chrome-debug &\n\nNote: The --user-data-dir flag is required to avoid conflicts with existing browser instances.", chromePort, chromePort, chromePort)
}
@@ -94,15 +110,23 @@ func NewDaemon(host string, port int) (*Daemon, error) {
return nil, fmt.Errorf("Chromium DevTools is responding on port %d but rod connection failed: %w\n\nThis is unexpected. Try restarting Chromium with:\n chromium --remote-debugging-port=%d --user-data-dir=/tmp/chromium-debug &", chromePort, err, chromePort)
}
if debug {
log.Printf("[DEBUG] Successfully connected to browser via rod")
}
daemon := &Daemon{
browser: browser,
tabs: make(map[string]*rod.Page),
iframePages: make(map[string]*rod.Page),
tabHistory: make([]string, 0),
consoleLogs: make(map[string][]ConsoleLog),
debug: debug,
}
daemon.debugLog("Daemon struct initialized")
// Create HTTP server
daemon.debugLog("Setting up HTTP server")
mux := http.NewServeMux()
mux.HandleFunc("/command", daemon.handleCommand)
mux.HandleFunc("/status", daemon.handleStatus)
@@ -114,13 +138,18 @@ func NewDaemon(host string, port int) (*Daemon, error) {
Handler: mux,
}
daemon.debugLog("HTTP server configured on %s:%d", host, port)
return daemon, nil
}
// Start starts the daemon server
func (d *Daemon) Start() error {
log.Printf("Starting daemon server on %s", d.server.Addr)
return d.server.ListenAndServe()
d.debugLog("About to call ListenAndServe()")
err := d.server.ListenAndServe()
d.debugLog("ListenAndServe() returned with error: %v", err)
return err
}
// Stop stops the daemon server
@@ -173,7 +202,10 @@ func (d *Daemon) handleStatus(w http.ResponseWriter, r *http.Request) {
// handleCommand handles command requests
func (d *Daemon) handleCommand(w http.ResponseWriter, r *http.Request) {
d.debugLog("Received HTTP request: %s %s", r.Method, r.URL.Path)
if r.Method != http.MethodPost {
d.debugLog("Invalid method: %s", r.Method)
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
@@ -181,10 +213,13 @@ func (d *Daemon) handleCommand(w http.ResponseWriter, r *http.Request) {
var cmd Command
err := json.NewDecoder(r.Body).Decode(&cmd)
if err != nil {
d.debugLog("Failed to decode JSON: %v", err)
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
d.debugLog("Processing command: %s with params: %+v", cmd.Action, cmd.Params)
var response Response
switch cmd.Action {
@@ -510,20 +545,25 @@ func (d *Daemon) handleCommand(w http.ResponseWriter, r *http.Request) {
}
default:
d.debugLog("Unknown action: %s", cmd.Action)
response = Response{Success: false, Error: "Unknown action"}
}
d.debugLog("Command %s completed, sending response: success=%v", cmd.Action, response.Success)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
d.debugLog("Response sent for command: %s", cmd.Action)
}
// openTab opens a new tab and returns its ID
func (d *Daemon) openTab(timeout int) (string, error) {
d.debugLog("Opening new tab with timeout: %d", timeout)
d.mu.Lock()
defer d.mu.Unlock()
// Create a context with timeout if specified
if timeout > 0 {
d.debugLog("Using timeout context: %d seconds", timeout)
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
defer cancel()
@@ -768,10 +808,13 @@ func (d *Daemon) closeTab(tabID string, timeout int) error {
// loadURL loads a URL in a tab
func (d *Daemon) loadURL(tabID, url string, timeout int) error {
d.debugLog("Loading URL: %s in tab: %s with timeout: %d", url, tabID, timeout)
page, err := d.getTab(tabID)
if err != nil {
d.debugLog("Failed to get tab %s: %v", tabID, err)
return err
}
d.debugLog("Got tab %s, starting navigation", tabID)
if timeout > 0 {
// Use timeout for the URL loading