multiple agents
This commit is contained in:
1 parent
ec391bd7ed
commit
a399e1f365
6 files changed
+499
-658
No files matched your search
+173
-352
@@ -25,16 +25,26 @@ import (
|
||||
|
||||
const Version = "2.2.1-contrast-detection-fix"
|
||||
|
||||
// Daemon is the main server that manages browser connections
|
||||
// Daemon is the main server that manages browser connections.
|
||||
//
|
||||
// Concurrency model: the daemon is stateless with respect to "current tab".
|
||||
// Every operation requires an explicit tab id, which makes it safe for multiple
|
||||
// clients (e.g. one MCP server process per agent, or multiple CLI invocations)
|
||||
// to share a single daemon without interfering with each other. Per-tab state
|
||||
// (cached page, iframe context, console logs) is keyed by the globally-unique
|
||||
// Chrome TargetID, so distinct tabs never collide.
|
||||
//
|
||||
// stateMu guards ONLY the maps below. It must never be held while performing
|
||||
// Chrome DevTools Protocol calls that can block (navigation, element waits,
|
||||
// iframe resolution, etc.) - those run lock-free so clients on different tabs
|
||||
// do not serialize each other.
|
||||
type Daemon struct {
|
||||
browser *rod.Browser
|
||||
tabs map[string]*rod.Page
|
||||
iframePages map[string]*rod.Page // Maps tab ID to iframe page context
|
||||
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
|
||||
stateMu sync.Mutex // Guards tabs, iframePages, consoleLogs only
|
||||
server *http.Server
|
||||
}
|
||||
|
||||
@@ -125,7 +135,6 @@ func NewDaemon(host string, port int, debug bool) (*Daemon, error) {
|
||||
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,
|
||||
}
|
||||
@@ -172,12 +181,9 @@ func (d *Daemon) handleStatus(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
d.mu.Lock()
|
||||
d.stateMu.Lock()
|
||||
tabCount := len(d.tabs)
|
||||
tabs := make(map[string]string)
|
||||
currentTab := d.currentTab
|
||||
tabHistory := make([]string, len(d.tabHistory))
|
||||
copy(tabHistory, d.tabHistory)
|
||||
|
||||
// Get info about each tab
|
||||
for id, page := range d.tabs {
|
||||
@@ -190,16 +196,14 @@ func (d *Daemon) handleStatus(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
tabs[id] = try()
|
||||
}
|
||||
d.mu.Unlock()
|
||||
d.stateMu.Unlock()
|
||||
|
||||
response := Response{
|
||||
Success: true,
|
||||
Data: map[string]interface{}{
|
||||
"status": "running",
|
||||
"tab_count": tabCount,
|
||||
"tabs": tabs,
|
||||
"current_tab": currentTab,
|
||||
"tab_history": tabHistory,
|
||||
"status": "running",
|
||||
"tab_count": tabCount,
|
||||
"tabs": tabs,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -2311,113 +2315,66 @@ func (d *Daemon) handleCommand(w http.ResponseWriter, r *http.Request) {
|
||||
// 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
|
||||
// createPage performs the CDP round-trip to create a new tab. It runs
|
||||
// lock-free so that concurrent openTab calls from different clients do not
|
||||
// serialize on stateMu (and do not block other clients' getTab lookups).
|
||||
createPage := func() (*rod.Page, string, error) {
|
||||
page, err := d.browser.Page(proto.TargetCreateTarget{URL: "about:blank"})
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("failed to create new tab: %w", err)
|
||||
}
|
||||
return page, string(page.TargetID), nil
|
||||
}
|
||||
|
||||
var page *rod.Page
|
||||
var tabID string
|
||||
var err error
|
||||
|
||||
if timeout > 0 {
|
||||
d.debugLog("Using timeout context: %d seconds", timeout)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Create a channel to signal completion
|
||||
done := make(chan struct {
|
||||
page *rod.Page
|
||||
tabID string
|
||||
err error
|
||||
}, 1)
|
||||
|
||||
// Execute the tab creation in a goroutine
|
||||
go func() {
|
||||
page, err := d.browser.Page(proto.TargetCreateTarget{URL: "about:blank"})
|
||||
var tabID string
|
||||
if err == nil {
|
||||
tabID = string(page.TargetID)
|
||||
}
|
||||
p, id, e := createPage()
|
||||
done <- struct {
|
||||
page *rod.Page
|
||||
tabID string
|
||||
err error
|
||||
}{page, tabID, err}
|
||||
}{p, id, e}
|
||||
}()
|
||||
|
||||
// Wait for either completion or timeout
|
||||
select {
|
||||
case res := <-done:
|
||||
if res.err != nil {
|
||||
return "", fmt.Errorf("failed to create new tab: %w", res.err)
|
||||
}
|
||||
|
||||
// Store the tab and update history
|
||||
d.tabs[res.tabID] = res.page
|
||||
d.tabHistory = append(d.tabHistory, res.tabID)
|
||||
d.currentTab = res.tabID
|
||||
|
||||
// Set up console logging for this tab
|
||||
d.setupConsoleLogging(res.tabID, res.page)
|
||||
|
||||
return res.tabID, nil
|
||||
page, tabID, err = res.page, res.tabID, res.err
|
||||
case <-ctx.Done():
|
||||
return "", fmt.Errorf("opening tab timed out after %d seconds", timeout)
|
||||
}
|
||||
} else {
|
||||
// No timeout
|
||||
page, err := d.browser.Page(proto.TargetCreateTarget{URL: "about:blank"})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to create new tab: %w", err)
|
||||
}
|
||||
|
||||
// Use the page ID as the tab ID
|
||||
tabID := string(page.TargetID)
|
||||
d.tabs[tabID] = page
|
||||
|
||||
// Add to tab history stack and set as current tab
|
||||
d.tabHistory = append(d.tabHistory, tabID)
|
||||
d.currentTab = tabID
|
||||
|
||||
// Set up console logging for this tab
|
||||
d.setupConsoleLogging(tabID, page)
|
||||
|
||||
return tabID, nil
|
||||
}
|
||||
}
|
||||
|
||||
// getTabID returns the tab ID to use, falling back to the current tab if none is provided
|
||||
func (d *Daemon) getTabID(tabID string) (string, error) {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
|
||||
// If no tab ID is provided, use the current tab
|
||||
if tabID == "" {
|
||||
if d.currentTab == "" {
|
||||
return "", fmt.Errorf("no current tab available, please open a tab first")
|
||||
}
|
||||
return d.currentTab, nil
|
||||
page, tabID, err = createPage()
|
||||
}
|
||||
|
||||
// Otherwise, use the provided tab ID
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// Register the tab. setupConsoleLogging touches consoleLogs and must be
|
||||
// called with stateMu held.
|
||||
d.stateMu.Lock()
|
||||
defer d.stateMu.Unlock()
|
||||
d.tabs[tabID] = page
|
||||
d.setupConsoleLogging(tabID, page)
|
||||
return tabID, nil
|
||||
}
|
||||
|
||||
// updateTabHistory updates the tab history stack when a tab is activated
|
||||
func (d *Daemon) updateTabHistory(tabID string) {
|
||||
// Set as current tab
|
||||
d.currentTab = tabID
|
||||
|
||||
// Remove the tab from history if it's already there
|
||||
for i, id := range d.tabHistory {
|
||||
if id == tabID {
|
||||
// Remove this tab from history
|
||||
d.tabHistory = append(d.tabHistory[:i], d.tabHistory[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Add the tab to the end of history (most recent)
|
||||
d.tabHistory = append(d.tabHistory, tabID)
|
||||
}
|
||||
|
||||
// findPageByID finds a page by its ID without updating the current tab or cache
|
||||
// findPageByID finds a page by its ID without updating the cache
|
||||
func (d *Daemon) findPageByID(tabID string) (*rod.Page, error) {
|
||||
// If not in memory, try to get the page from the browser
|
||||
pages, err := d.browser.Pages()
|
||||
@@ -2456,134 +2413,105 @@ func (d *Daemon) findPageByID(tabID string) (*rod.Page, error) {
|
||||
return nil, fmt.Errorf("tab not found: %s", tabID)
|
||||
}
|
||||
|
||||
// getTab returns a tab by its ID, checking for iframe context first
|
||||
// getTab returns the page for a tab, checking for an iframe context first.
|
||||
// tabID is required; the daemon no longer tracks a "current tab" because that
|
||||
// state cannot be shared safely across multiple concurrent clients.
|
||||
func (d *Daemon) getTab(tabID string) (*rod.Page, error) {
|
||||
// Get the tab ID to use (may be the current tab)
|
||||
actualTabID, err := d.getTabID(tabID)
|
||||
if tabID == "" {
|
||||
return nil, fmt.Errorf("tab id is required")
|
||||
}
|
||||
|
||||
// Fast path: serve from cached iframe context or main-page cache. Only the
|
||||
// map lookups happen under stateMu, so this never blocks on Chrome.
|
||||
d.stateMu.Lock()
|
||||
if p, ok := d.iframePages[tabID]; ok {
|
||||
d.stateMu.Unlock()
|
||||
return p, nil
|
||||
}
|
||||
if p, ok := d.tabs[tabID]; ok {
|
||||
d.stateMu.Unlock()
|
||||
return p, nil
|
||||
}
|
||||
d.stateMu.Unlock()
|
||||
|
||||
// Slow path: the tab exists in Chrome but isn't cached yet (e.g. the daemon
|
||||
// was restarted while the browser kept running, or the tab was opened
|
||||
// outside the daemon). findPageByID does a CDP round-trip and runs lock-free
|
||||
// so it does not block other clients.
|
||||
page, err := d.findPageByID(tabID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
|
||||
// First check if we have an iframe context for this tab
|
||||
if iframePage, exists := d.iframePages[actualTabID]; exists {
|
||||
// Update tab history and current tab
|
||||
d.updateTabHistory(actualTabID)
|
||||
return iframePage, nil
|
||||
d.stateMu.Lock()
|
||||
defer d.stateMu.Unlock()
|
||||
// Another goroutine may have cached the same tab in the meantime.
|
||||
if cached, ok := d.tabs[tabID]; ok {
|
||||
return cached, nil
|
||||
}
|
||||
|
||||
// Check in-memory cache for main page
|
||||
page, exists := d.tabs[actualTabID]
|
||||
if exists {
|
||||
// Update tab history and current tab
|
||||
d.updateTabHistory(actualTabID)
|
||||
return page, nil
|
||||
}
|
||||
|
||||
// If not in memory, try to find it
|
||||
// Note: This can happen if the daemon was restarted but the browser is still running,
|
||||
// or if a tab was created outside of the daemon. Pages retrieved this way may have
|
||||
// initialization issues (see findPageByID for details).
|
||||
page, err = d.findPageByID(actualTabID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// If found, cache it for future use and set up console logging
|
||||
if page != nil {
|
||||
d.tabs[actualTabID] = page
|
||||
// Set up console logging for this tab since it wasn't created through openTab
|
||||
d.setupConsoleLogging(actualTabID, page)
|
||||
// Update tab history and current tab
|
||||
d.updateTabHistory(actualTabID)
|
||||
d.debugLog("Found and cached existing tab %s from browser", actualTabID)
|
||||
return page, nil
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("tab not found: %s", actualTabID)
|
||||
d.tabs[tabID] = page
|
||||
d.setupConsoleLogging(tabID, page)
|
||||
d.debugLog("Found and cached existing tab %s from browser", tabID)
|
||||
return page, nil
|
||||
}
|
||||
|
||||
// closeTab closes a tab by its ID
|
||||
// closeTab closes a tab by its ID. tabID is required.
|
||||
func (d *Daemon) closeTab(tabID string, timeout int) error {
|
||||
// Get the tab ID to use (may be the current tab)
|
||||
actualTabID, err := d.getTabID(tabID)
|
||||
if err != nil {
|
||||
return err
|
||||
if tabID == "" {
|
||||
return fmt.Errorf("tab id is required")
|
||||
}
|
||||
|
||||
// First remove from our internal map to avoid future references
|
||||
d.mu.Lock()
|
||||
page, exists := d.tabs[actualTabID]
|
||||
delete(d.tabs, actualTabID)
|
||||
// Remove from our internal maps first to avoid future references.
|
||||
d.stateMu.Lock()
|
||||
page, exists := d.tabs[tabID]
|
||||
delete(d.tabs, tabID)
|
||||
delete(d.iframePages, tabID)
|
||||
delete(d.consoleLogs, tabID)
|
||||
d.stateMu.Unlock()
|
||||
|
||||
// Remove the tab from history
|
||||
for i, id := range d.tabHistory {
|
||||
if id == actualTabID {
|
||||
// Remove this tab from history
|
||||
d.tabHistory = append(d.tabHistory[:i], d.tabHistory[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// If we closed the current tab, set it to the previous tab in history
|
||||
if d.currentTab == actualTabID {
|
||||
if len(d.tabHistory) > 0 {
|
||||
// Set current tab to the most recent tab in history
|
||||
d.currentTab = d.tabHistory[len(d.tabHistory)-1]
|
||||
} else {
|
||||
// No tabs left in history, clear the current tab
|
||||
d.currentTab = ""
|
||||
}
|
||||
}
|
||||
d.mu.Unlock()
|
||||
|
||||
// If the page doesn't exist in our cache, try to find it
|
||||
// If the page isn't in our cache, try to resolve it (it may still be open in
|
||||
// the browser). This runs lock-free.
|
||||
if !exists {
|
||||
var err error
|
||||
page, err = d.findPageByID(actualTabID)
|
||||
page, err = d.findPageByID(tabID)
|
||||
if err != nil {
|
||||
// If we can't find the page, it might already be closed
|
||||
// If we can't find the page, it might already be closed.
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
if page == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
if timeout > 0 {
|
||||
// Use timeout for closing the tab
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Create a channel to signal completion
|
||||
done := make(chan error, 1)
|
||||
|
||||
// Execute the close in a goroutine
|
||||
go func() {
|
||||
err := page.Close()
|
||||
done <- err
|
||||
done <- page.Close()
|
||||
}()
|
||||
|
||||
// Wait for either completion or timeout
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
// Log the error but don't return it, as we've already removed it from our map
|
||||
fmt.Printf("Warning: failed to close tab %s: %v\n", actualTabID, err)
|
||||
fmt.Printf("Warning: failed to close tab %s: %v\n", tabID, err)
|
||||
}
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
return fmt.Errorf("closing tab timed out after %d seconds", timeout)
|
||||
}
|
||||
} else {
|
||||
// No timeout - try to close the page, but don't fail if it's already closed
|
||||
err = page.Close()
|
||||
if err != nil {
|
||||
// Log the error but don't return it, as we've already removed it from our map
|
||||
fmt.Printf("Warning: failed to close tab %s: %v\n", actualTabID, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// No timeout - try to close the page, but don't fail if it's already closed
|
||||
if err := page.Close(); err != nil {
|
||||
fmt.Printf("Warning: failed to close tab %s: %v\n", tabID, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// loadURL loads a URL in a tab
|
||||
@@ -3669,49 +3597,52 @@ func (d *Daemon) takeScreenshotEnhanced(tabID, outputPath string, fullPage bool,
|
||||
func (d *Daemon) switchToIframe(tabID, selector string, timeout int) error {
|
||||
d.debugLog("Switching to iframe: selector=%s, tab=%s, timeout=%d", selector, tabID, timeout)
|
||||
|
||||
// Get the main page first (not iframe context)
|
||||
actualTabID, err := d.getTabID(tabID)
|
||||
if err != nil {
|
||||
d.debugLog("Failed to get tab ID: %v", err)
|
||||
return err
|
||||
if tabID == "" {
|
||||
return fmt.Errorf("tab id is required")
|
||||
}
|
||||
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
// Resolve the MAIN page (bypassing any existing iframe context). Only the
|
||||
// cache lookup is done under stateMu; the findPageByID fallback (a CDP
|
||||
// round-trip) runs lock-free.
|
||||
d.stateMu.Lock()
|
||||
mainPage, exists := d.tabs[tabID]
|
||||
d.stateMu.Unlock()
|
||||
|
||||
// Get the main page (bypass iframe context)
|
||||
mainPage, exists := d.tabs[actualTabID]
|
||||
if !exists {
|
||||
d.debugLog("Tab %s not in cache, trying to find it", actualTabID)
|
||||
// Try to find it
|
||||
mainPage, err = d.findPageByID(actualTabID)
|
||||
d.debugLog("Tab %s not in cache, trying to find it", tabID)
|
||||
var err error
|
||||
mainPage, err = d.findPageByID(tabID)
|
||||
if err != nil {
|
||||
d.debugLog("Failed to find tab %s: %v", actualTabID, err)
|
||||
d.debugLog("Failed to find tab %s: %v", tabID, err)
|
||||
return err
|
||||
}
|
||||
if mainPage == nil {
|
||||
d.debugLog("Tab %s not found", actualTabID)
|
||||
return fmt.Errorf("tab not found: %s", actualTabID)
|
||||
d.debugLog("Tab %s not found", tabID)
|
||||
return fmt.Errorf("tab not found: %s", tabID)
|
||||
}
|
||||
d.tabs[actualTabID] = mainPage
|
||||
d.stateMu.Lock()
|
||||
if _, ok := d.tabs[tabID]; !ok {
|
||||
d.tabs[tabID] = mainPage
|
||||
}
|
||||
d.stateMu.Unlock()
|
||||
}
|
||||
|
||||
d.debugLog("Found main page for tab %s, looking for iframe element", actualTabID)
|
||||
d.debugLog("Found main page for tab %s, looking for iframe element", tabID)
|
||||
|
||||
// Find the iframe element with timeout
|
||||
// Find the iframe element. This is a potentially long CDP operation and is
|
||||
// performed WITHOUT holding stateMu so that clients operating on other tabs
|
||||
// are not blocked while we wait.
|
||||
var iframeElement *rod.Element
|
||||
var err error
|
||||
if timeout > 0 {
|
||||
// Use timeout context for finding the iframe element
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Create a channel to signal completion
|
||||
done := make(chan struct {
|
||||
element *rod.Element
|
||||
err error
|
||||
}, 1)
|
||||
|
||||
// Execute the element search in a goroutine
|
||||
go func() {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
@@ -3729,7 +3660,6 @@ func (d *Daemon) switchToIframe(tabID, selector string, timeout int) error {
|
||||
}{element, err}
|
||||
}()
|
||||
|
||||
// Wait for either completion or timeout
|
||||
select {
|
||||
case result := <-done:
|
||||
iframeElement = result.element
|
||||
@@ -3739,7 +3669,6 @@ func (d *Daemon) switchToIframe(tabID, selector string, timeout int) error {
|
||||
return fmt.Errorf("failed to find iframe element (timeout after %ds): %s", timeout, selector)
|
||||
}
|
||||
} else {
|
||||
// No timeout
|
||||
iframeElement, err = mainPage.Element(selector)
|
||||
}
|
||||
|
||||
@@ -3750,20 +3679,17 @@ func (d *Daemon) switchToIframe(tabID, selector string, timeout int) error {
|
||||
|
||||
d.debugLog("Found iframe element, getting frame context")
|
||||
|
||||
// Get the iframe's page context with timeout
|
||||
// Get the iframe's page context. Also a long CDP operation; runs lock-free.
|
||||
var iframePage *rod.Page
|
||||
if timeout > 0 {
|
||||
// Use timeout context for getting the frame
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Create a channel to signal completion
|
||||
done := make(chan struct {
|
||||
page *rod.Page
|
||||
err error
|
||||
}, 1)
|
||||
|
||||
// Execute the frame access in a goroutine
|
||||
go func() {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
@@ -3781,7 +3707,6 @@ func (d *Daemon) switchToIframe(tabID, selector string, timeout int) error {
|
||||
}{page, err}
|
||||
}()
|
||||
|
||||
// Wait for either completion or timeout
|
||||
select {
|
||||
case result := <-done:
|
||||
iframePage = result.page
|
||||
@@ -3791,7 +3716,6 @@ func (d *Daemon) switchToIframe(tabID, selector string, timeout int) error {
|
||||
return fmt.Errorf("failed to get iframe context (timeout after %ds)", timeout)
|
||||
}
|
||||
} else {
|
||||
// No timeout
|
||||
iframePage, err = iframeElement.Frame()
|
||||
}
|
||||
|
||||
@@ -3800,37 +3724,34 @@ func (d *Daemon) switchToIframe(tabID, selector string, timeout int) error {
|
||||
return fmt.Errorf("failed to get iframe context: %w", err)
|
||||
}
|
||||
|
||||
// Store the iframe page context
|
||||
d.iframePages[actualTabID] = iframePage
|
||||
d.debugLog("Successfully switched to iframe context for tab %s", actualTabID)
|
||||
// Store the iframe page context (brief critical section).
|
||||
d.stateMu.Lock()
|
||||
d.iframePages[tabID] = iframePage
|
||||
d.stateMu.Unlock()
|
||||
d.debugLog("Successfully switched to iframe context for tab %s", tabID)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// switchToMain switches back to the main page context
|
||||
// switchToMain switches back to the main page context. tabID is required.
|
||||
func (d *Daemon) switchToMain(tabID string) error {
|
||||
d.debugLog("Switching back to main context: tab=%s", tabID)
|
||||
|
||||
// Get the tab ID to use (may be the current tab)
|
||||
actualTabID, err := d.getTabID(tabID)
|
||||
if err != nil {
|
||||
d.debugLog("Failed to get tab ID: %v", err)
|
||||
return err
|
||||
if tabID == "" {
|
||||
return fmt.Errorf("tab id is required")
|
||||
}
|
||||
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
d.stateMu.Lock()
|
||||
defer d.stateMu.Unlock()
|
||||
|
||||
// Check if there was an iframe context to remove
|
||||
if _, exists := d.iframePages[actualTabID]; exists {
|
||||
d.debugLog("Removing iframe context for tab %s", actualTabID)
|
||||
// Remove the iframe context for this tab
|
||||
delete(d.iframePages, actualTabID)
|
||||
if _, exists := d.iframePages[tabID]; exists {
|
||||
d.debugLog("Removing iframe context for tab %s", tabID)
|
||||
delete(d.iframePages, tabID)
|
||||
} else {
|
||||
d.debugLog("No iframe context found for tab %s", actualTabID)
|
||||
d.debugLog("No iframe context found for tab %s", tabID)
|
||||
}
|
||||
|
||||
d.debugLog("Successfully switched back to main context for tab %s", actualTabID)
|
||||
d.debugLog("Successfully switched back to main context for tab %s", tabID)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -3943,8 +3864,8 @@ func (d *Daemon) setupConsoleLogging(tabID string, page *rod.Page) {
|
||||
|
||||
// Listen for console events
|
||||
go page.EachEvent(func(e *proto.RuntimeConsoleAPICalled) {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
d.stateMu.Lock()
|
||||
defer d.stateMu.Unlock()
|
||||
|
||||
// Convert console level
|
||||
level := string(e.Type)
|
||||
@@ -3985,16 +3906,11 @@ func (d *Daemon) setupConsoleLogging(tabID string, page *rod.Page) {
|
||||
|
||||
// getConsoleLogs retrieves console logs for a tab
|
||||
func (d *Daemon) getConsoleLogs(tabID string, clear bool) ([]ConsoleLog, error) {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
|
||||
// Use current tab if not specified
|
||||
if tabID == "" {
|
||||
tabID = d.currentTab
|
||||
}
|
||||
d.stateMu.Lock()
|
||||
defer d.stateMu.Unlock()
|
||||
|
||||
if tabID == "" {
|
||||
return nil, fmt.Errorf("no tab specified and no current tab available")
|
||||
return nil, fmt.Errorf("tab id is required")
|
||||
}
|
||||
|
||||
// Check if tab exists
|
||||
@@ -4018,13 +3934,8 @@ func (d *Daemon) getConsoleLogs(tabID string, clear bool) ([]ConsoleLog, error)
|
||||
|
||||
// executeConsoleCommand executes a command in the browser console
|
||||
func (d *Daemon) executeConsoleCommand(tabID, command string, timeout int) (string, error) {
|
||||
// Use current tab if not specified
|
||||
if tabID == "" {
|
||||
tabID = d.currentTab
|
||||
}
|
||||
|
||||
if tabID == "" {
|
||||
return "", fmt.Errorf("no tab specified and no current tab available")
|
||||
return "", fmt.Errorf("tab id is required")
|
||||
}
|
||||
|
||||
// Execute the command as JavaScript and return the result
|
||||
@@ -4079,13 +3990,8 @@ type TextExtractionResult struct {
|
||||
|
||||
// checkElement checks various states of an element
|
||||
func (d *Daemon) checkElement(tabID, selector, checkType string, timeout int) (*ElementCheckResult, error) {
|
||||
// Use current tab if not specified
|
||||
if tabID == "" {
|
||||
tabID = d.currentTab
|
||||
}
|
||||
|
||||
if tabID == "" {
|
||||
return nil, fmt.Errorf("no tab specified and no current tab available")
|
||||
return nil, fmt.Errorf("tab id is required")
|
||||
}
|
||||
|
||||
page, exists := d.tabs[tabID]
|
||||
@@ -4187,13 +4093,8 @@ func (d *Daemon) checkElement(tabID, selector, checkType string, timeout int) (*
|
||||
|
||||
// getElementAttributes gets attributes, properties, and computed styles of an element
|
||||
func (d *Daemon) getElementAttributes(tabID, selector, attributes string, timeout int) (map[string]interface{}, error) {
|
||||
// Use current tab if not specified
|
||||
if tabID == "" {
|
||||
tabID = d.currentTab
|
||||
}
|
||||
|
||||
if tabID == "" {
|
||||
return nil, fmt.Errorf("no tab specified and no current tab available")
|
||||
return nil, fmt.Errorf("tab id is required")
|
||||
}
|
||||
|
||||
page, exists := d.tabs[tabID]
|
||||
@@ -4329,13 +4230,8 @@ func (d *Daemon) getElementAttributes(tabID, selector, attributes string, timeou
|
||||
|
||||
// countElements counts the number of elements matching a selector
|
||||
func (d *Daemon) countElements(tabID, selector string, timeout int) (int, error) {
|
||||
// Use current tab if not specified
|
||||
if tabID == "" {
|
||||
tabID = d.currentTab
|
||||
}
|
||||
|
||||
if tabID == "" {
|
||||
return 0, fmt.Errorf("no tab specified and no current tab available")
|
||||
return 0, fmt.Errorf("tab id is required")
|
||||
}
|
||||
|
||||
page, exists := d.tabs[tabID]
|
||||
@@ -4371,13 +4267,8 @@ func (d *Daemon) countElements(tabID, selector string, timeout int) (int, error)
|
||||
|
||||
// extractMultiple extracts data from multiple selectors in a single call
|
||||
func (d *Daemon) extractMultiple(tabID, selectorsJSON string, timeout int) (*MultipleExtractionResult, error) {
|
||||
// Use current tab if not specified
|
||||
if tabID == "" {
|
||||
tabID = d.currentTab
|
||||
}
|
||||
|
||||
if tabID == "" {
|
||||
return nil, fmt.Errorf("no tab specified and no current tab available")
|
||||
return nil, fmt.Errorf("tab id is required")
|
||||
}
|
||||
|
||||
page, exists := d.tabs[tabID]
|
||||
@@ -4466,13 +4357,8 @@ func (d *Daemon) extractMultiple(tabID, selectorsJSON string, timeout int) (*Mul
|
||||
|
||||
// extractLinks extracts all links from the page with optional filtering
|
||||
func (d *Daemon) extractLinks(tabID, containerSelector, hrefPattern, textPattern string, timeout int) (*LinksExtractionResult, error) {
|
||||
// Use current tab if not specified
|
||||
if tabID == "" {
|
||||
tabID = d.currentTab
|
||||
}
|
||||
|
||||
if tabID == "" {
|
||||
return nil, fmt.Errorf("no tab specified and no current tab available")
|
||||
return nil, fmt.Errorf("tab id is required")
|
||||
}
|
||||
|
||||
page, exists := d.tabs[tabID]
|
||||
@@ -4571,13 +4457,8 @@ func (d *Daemon) extractLinks(tabID, containerSelector, hrefPattern, textPattern
|
||||
|
||||
// extractTable extracts table data as structured JSON
|
||||
func (d *Daemon) extractTable(tabID, selector string, includeHeaders bool, timeout int) (*TableExtractionResult, error) {
|
||||
// Use current tab if not specified
|
||||
if tabID == "" {
|
||||
tabID = d.currentTab
|
||||
}
|
||||
|
||||
if tabID == "" {
|
||||
return nil, fmt.Errorf("no tab specified and no current tab available")
|
||||
return nil, fmt.Errorf("tab id is required")
|
||||
}
|
||||
|
||||
page, exists := d.tabs[tabID]
|
||||
@@ -4684,13 +4565,8 @@ func (d *Daemon) extractTable(tabID, selector string, includeHeaders bool, timeo
|
||||
|
||||
// extractText extracts text content with optional pattern matching
|
||||
func (d *Daemon) extractText(tabID, selector, pattern, extractType string, timeout int) (*TextExtractionResult, error) {
|
||||
// Use current tab if not specified
|
||||
if tabID == "" {
|
||||
tabID = d.currentTab
|
||||
}
|
||||
|
||||
if tabID == "" {
|
||||
return nil, fmt.Errorf("no tab specified and no current tab available")
|
||||
return nil, fmt.Errorf("tab id is required")
|
||||
}
|
||||
|
||||
page, exists := d.tabs[tabID]
|
||||
@@ -6416,13 +6292,8 @@ func (d *Daemon) getAccessibilityTree(tabID string, depth *int, timeout int) (*A
|
||||
func (d *Daemon) getAccessibilityTreeWithContrast(tabID string, depth *int, includeContrast bool, timeout int) (*AccessibilityTreeResult, error) {
|
||||
d.debugLog("Getting accessibility tree for tab: %s with depth: %v, includeContrast: %v, timeout: %d", tabID, depth, includeContrast, timeout)
|
||||
|
||||
// Use current tab if not specified
|
||||
if tabID == "" {
|
||||
tabID = d.currentTab
|
||||
}
|
||||
|
||||
if tabID == "" {
|
||||
return nil, fmt.Errorf("no tab specified and no current tab available")
|
||||
return nil, fmt.Errorf("tab id is required")
|
||||
}
|
||||
|
||||
page, err := d.getTab(tabID)
|
||||
@@ -6596,13 +6467,8 @@ func (d *Daemon) convertProtoAXValue(protoValue *proto.AccessibilityAXValue) *AX
|
||||
func (d *Daemon) getPartialAccessibilityTree(tabID, selector string, fetchRelatives bool, timeout int) (*AccessibilityTreeResult, error) {
|
||||
d.debugLog("Getting partial accessibility tree for tab: %s, selector: %s, fetchRelatives: %v, timeout: %d", tabID, selector, fetchRelatives, timeout)
|
||||
|
||||
// Use current tab if not specified
|
||||
if tabID == "" {
|
||||
tabID = d.currentTab
|
||||
}
|
||||
|
||||
if tabID == "" {
|
||||
return nil, fmt.Errorf("no tab specified and no current tab available")
|
||||
return nil, fmt.Errorf("tab id is required")
|
||||
}
|
||||
|
||||
page, err := d.getTab(tabID)
|
||||
@@ -6657,13 +6523,8 @@ func (d *Daemon) getPartialAccessibilityTree(tabID, selector string, fetchRelati
|
||||
func (d *Daemon) queryAccessibilityTree(tabID, selector, accessibleName, role string, timeout int) (*AccessibilityQueryResult, error) {
|
||||
d.debugLog("Querying accessibility tree for tab: %s, selector: %s, name: %s, role: %s, timeout: %d", tabID, selector, accessibleName, role, timeout)
|
||||
|
||||
// Use current tab if not specified
|
||||
if tabID == "" {
|
||||
tabID = d.currentTab
|
||||
}
|
||||
|
||||
if tabID == "" {
|
||||
return nil, fmt.Errorf("no tab specified and no current tab available")
|
||||
return nil, fmt.Errorf("tab id is required")
|
||||
}
|
||||
|
||||
page, err := d.getTab(tabID)
|
||||
@@ -6731,13 +6592,8 @@ func (d *Daemon) queryAccessibilityTree(tabID, selector, accessibleName, role st
|
||||
func (d *Daemon) setCacheDisabled(tabID string, disabled bool, timeout int) error {
|
||||
d.debugLog("Setting cache disabled=%v for tab: %s with timeout: %d", disabled, tabID, timeout)
|
||||
|
||||
// Use current tab if not specified
|
||||
if tabID == "" {
|
||||
tabID = d.currentTab
|
||||
}
|
||||
|
||||
if tabID == "" {
|
||||
return fmt.Errorf("no tab specified and no current tab available")
|
||||
return fmt.Errorf("tab id is required")
|
||||
}
|
||||
|
||||
page, err := d.getTab(tabID)
|
||||
@@ -6784,13 +6640,8 @@ func (d *Daemon) setCacheDisabled(tabID string, disabled bool, timeout int) erro
|
||||
func (d *Daemon) clearBrowserCache(tabID string, timeout int) error {
|
||||
d.debugLog("Clearing browser cache for tab: %s with timeout: %d", tabID, timeout)
|
||||
|
||||
// Use current tab if not specified
|
||||
if tabID == "" {
|
||||
tabID = d.currentTab
|
||||
}
|
||||
|
||||
if tabID == "" {
|
||||
return fmt.Errorf("no tab specified and no current tab available")
|
||||
return fmt.Errorf("tab id is required")
|
||||
}
|
||||
|
||||
page, err := d.getTab(tabID)
|
||||
@@ -6837,13 +6688,8 @@ func (d *Daemon) clearBrowserCache(tabID string, timeout int) error {
|
||||
func (d *Daemon) clearAllSiteData(tabID string, timeout int) error {
|
||||
d.debugLog("Clearing all site data for tab: %s with timeout: %d", tabID, timeout)
|
||||
|
||||
// Use current tab if not specified
|
||||
if tabID == "" {
|
||||
tabID = d.currentTab
|
||||
}
|
||||
|
||||
if tabID == "" {
|
||||
return fmt.Errorf("no tab specified and no current tab available")
|
||||
return fmt.Errorf("tab id is required")
|
||||
}
|
||||
|
||||
page, err := d.getTab(tabID)
|
||||
@@ -6897,13 +6743,8 @@ func (d *Daemon) clearAllSiteData(tabID string, timeout int) error {
|
||||
func (d *Daemon) clearCookies(tabID string, timeout int) error {
|
||||
d.debugLog("Clearing cookies for tab: %s with timeout: %d", tabID, timeout)
|
||||
|
||||
// Use current tab if not specified
|
||||
if tabID == "" {
|
||||
tabID = d.currentTab
|
||||
}
|
||||
|
||||
if tabID == "" {
|
||||
return fmt.Errorf("no tab specified and no current tab available")
|
||||
return fmt.Errorf("tab id is required")
|
||||
}
|
||||
|
||||
page, err := d.getTab(tabID)
|
||||
@@ -6957,13 +6798,8 @@ func (d *Daemon) clearCookies(tabID string, timeout int) error {
|
||||
func (d *Daemon) clearStorage(tabID string, timeout int) error {
|
||||
d.debugLog("Clearing storage for tab: %s with timeout: %d", tabID, timeout)
|
||||
|
||||
// Use current tab if not specified
|
||||
if tabID == "" {
|
||||
tabID = d.currentTab
|
||||
}
|
||||
|
||||
if tabID == "" {
|
||||
return fmt.Errorf("no tab specified and no current tab available")
|
||||
return fmt.Errorf("tab id is required")
|
||||
}
|
||||
|
||||
page, err := d.getTab(tabID)
|
||||
@@ -7017,13 +6853,8 @@ func (d *Daemon) clearStorage(tabID string, timeout int) error {
|
||||
func (d *Daemon) dragAndDrop(tabID, sourceSelector, targetSelector string, timeout int) error {
|
||||
d.debugLog("Performing drag and drop from %s to %s for tab: %s with timeout: %d", sourceSelector, targetSelector, tabID, timeout)
|
||||
|
||||
// Use current tab if not specified
|
||||
if tabID == "" {
|
||||
tabID = d.currentTab
|
||||
}
|
||||
|
||||
if tabID == "" {
|
||||
return fmt.Errorf("no tab specified and no current tab available")
|
||||
return fmt.Errorf("tab id is required")
|
||||
}
|
||||
|
||||
page, err := d.getTab(tabID)
|
||||
@@ -7070,13 +6901,8 @@ func (d *Daemon) dragAndDrop(tabID, sourceSelector, targetSelector string, timeo
|
||||
func (d *Daemon) dragAndDropToCoordinates(tabID, sourceSelector string, targetX, targetY, timeout int) error {
|
||||
d.debugLog("Performing drag and drop from %s to coordinates (%d, %d) for tab: %s with timeout: %d", sourceSelector, targetX, targetY, tabID, timeout)
|
||||
|
||||
// Use current tab if not specified
|
||||
if tabID == "" {
|
||||
tabID = d.currentTab
|
||||
}
|
||||
|
||||
if tabID == "" {
|
||||
return fmt.Errorf("no tab specified and no current tab available")
|
||||
return fmt.Errorf("tab id is required")
|
||||
}
|
||||
|
||||
page, err := d.getTab(tabID)
|
||||
@@ -7123,13 +6949,8 @@ func (d *Daemon) dragAndDropToCoordinates(tabID, sourceSelector string, targetX,
|
||||
func (d *Daemon) dragAndDropByOffset(tabID, sourceSelector string, offsetX, offsetY, timeout int) error {
|
||||
d.debugLog("Performing drag and drop from %s by offset (%d, %d) for tab: %s with timeout: %d", sourceSelector, offsetX, offsetY, tabID, timeout)
|
||||
|
||||
// Use current tab if not specified
|
||||
if tabID == "" {
|
||||
tabID = d.currentTab
|
||||
}
|
||||
|
||||
if tabID == "" {
|
||||
return fmt.Errorf("no tab specified and no current tab available")
|
||||
return fmt.Errorf("tab id is required")
|
||||
}
|
||||
|
||||
page, err := d.getTab(tabID)
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/go-rod/rod"
|
||||
)
|
||||
|
||||
// newZeroDaemon builds a Daemon with only the in-memory maps initialized and no
|
||||
// browser connection. It is sufficient to exercise the entry points that
|
||||
// validate their tab id before any Chrome DevTools Protocol call.
|
||||
func newZeroDaemon() *Daemon {
|
||||
return &Daemon{
|
||||
tabs: make(map[string]*rod.Page),
|
||||
iframePages: make(map[string]*rod.Page),
|
||||
consoleLogs: make(map[string][]ConsoleLog),
|
||||
}
|
||||
}
|
||||
|
||||
// TestTabRequired verifies the core multi-agent invariant: the daemon no longer
|
||||
// keeps a "current tab", so every operation that takes a tab id must reject an
|
||||
// empty one up front instead of silently falling back to shared state. Each of
|
||||
// these returns before touching the browser, so they can be tested without
|
||||
// Chrome.
|
||||
func TestTabRequired(t *testing.T) {
|
||||
d := newZeroDaemon()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
fn func() error
|
||||
}{
|
||||
{"getTab", func() error { _, err := d.getTab(""); return err }},
|
||||
{"closeTab", func() error { return d.closeTab("", 0) }},
|
||||
{"switchToMain", func() error { return d.switchToMain("") }},
|
||||
{"switchToIframe", func() error { return d.switchToIframe("", "#i", 0) }},
|
||||
{"getConsoleLogs", func() error { _, err := d.getConsoleLogs("", false); return err }},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
err := tc.fn()
|
||||
if err == nil {
|
||||
t.Fatalf("%s: expected an error for empty tab id, got nil", tc.name)
|
||||
}
|
||||
if !strings.Contains(strings.ToLower(err.Error()), "required") {
|
||||
t.Fatalf("%s: error should mention 'required', got: %v", tc.name, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestConsoleLogsConcurrent hammers getConsoleLogs from many goroutines (some
|
||||
// clearing, some reading) to confirm the per-tab log storage is race-free under
|
||||
// the stateMu discipline. Run with -race to catch any unprotected access.
|
||||
func TestConsoleLogsConcurrent(t *testing.T) {
|
||||
d := newZeroDaemon()
|
||||
const tabs = 8
|
||||
for i := 0; i < tabs; i++ {
|
||||
id := fmt.Sprintf("tab-%d", i)
|
||||
// getConsoleLogs only checks tab existence via d.tabs, so a nil page
|
||||
// entry is enough to let it reach the consoleLogs storage.
|
||||
d.tabs[id] = nil
|
||||
logs := make([]ConsoleLog, 0, 64)
|
||||
for j := 0; j < 64; j++ {
|
||||
logs = append(logs, ConsoleLog{Level: "info", Message: fmt.Sprintf("m-%d-%d", i, j)})
|
||||
}
|
||||
d.consoleLogs[id] = logs
|
||||
}
|
||||
|
||||
const goroutines = 64
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(goroutines)
|
||||
for g := 0; g < goroutines; g++ {
|
||||
go func(g int) {
|
||||
defer wg.Done()
|
||||
id := fmt.Sprintf("tab-%d", g%tabs)
|
||||
_, err := d.getConsoleLogs(id, g%2 == 0) // every other call clears
|
||||
if err != nil {
|
||||
t.Errorf("getConsoleLogs(%q): %v", id, err)
|
||||
}
|
||||
}(g)
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
// TestMultiAgentIsolation is an integration test that requires a Chrome running
|
||||
// with remote debugging on port 9222. It is gated behind CREMOTE_INTEGRATION=1
|
||||
// so that `go test` does not open tabs in the host browser by default. When
|
||||
// enabled, run with -race to verify concurrent multi-agent access is race-free
|
||||
// and that each agent's tab content is isolated:
|
||||
//
|
||||
// CREMOTE_INTEGRATION=1 go test -race -run TestMultiAgentIsolation ./daemon/...
|
||||
func TestMultiAgentIsolation(t *testing.T) {
|
||||
if os.Getenv("CREMOTE_INTEGRATION") != "1" {
|
||||
t.Skip("set CREMOTE_INTEGRATION=1 to run the Chrome-backed integration test")
|
||||
}
|
||||
if !checkChromeDevTools(9222) {
|
||||
t.Skip("chrome remote debugging not available on :9222")
|
||||
}
|
||||
|
||||
d, err := NewDaemon("127.0.0.1", freePort(t), false)
|
||||
if err != nil {
|
||||
t.Fatalf("NewDaemon: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = d.Stop() })
|
||||
go func() { _ = d.Start() }()
|
||||
|
||||
const agents = 6
|
||||
var wg sync.WaitGroup
|
||||
errs := make([]error, agents)
|
||||
tabs := make([]string, agents)
|
||||
wg.Add(agents)
|
||||
for a := 0; a < agents; a++ {
|
||||
go func(agent int) {
|
||||
defer wg.Done()
|
||||
tab, err := d.openTab(30)
|
||||
if err != nil {
|
||||
errs[agent] = fmt.Errorf("openTab: %w", err)
|
||||
return
|
||||
}
|
||||
tabs[agent] = tab
|
||||
|
||||
marker := fmt.Sprintf("AGENT-MARKER-%d", agent)
|
||||
url := "data:text/html,<html><body><h1>" + marker + "</h1></body></html>"
|
||||
if err := d.loadURL(tab, url, 30); err != nil {
|
||||
errs[agent] = fmt.Errorf("loadURL: %w", err)
|
||||
return
|
||||
}
|
||||
src, err := d.getPageSource(tab, 30)
|
||||
if err != nil {
|
||||
errs[agent] = fmt.Errorf("getPageSource: %w", err)
|
||||
return
|
||||
}
|
||||
if !strings.Contains(src, marker) {
|
||||
errs[agent] = fmt.Errorf("agent %d: page source missing %q (possible cross-agent leak)", agent, marker)
|
||||
}
|
||||
}(a)
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
// Clean up any tabs that were opened.
|
||||
for _, tab := range tabs {
|
||||
if tab != "" {
|
||||
_ = d.closeTab(tab, 30)
|
||||
}
|
||||
}
|
||||
|
||||
for i, err := range errs {
|
||||
if err != nil {
|
||||
t.Errorf("agent %d failed: %v", i, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// freePort returns an available TCP port for the daemon HTTP listener.
|
||||
func freePort(t *testing.T) int {
|
||||
t.Helper()
|
||||
l, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
port := l.Addr().(*net.TCPAddr).Port
|
||||
l.Close()
|
||||
return port
|
||||
}
|
||||
Reference in new issue
Block a user