chromedp

package
v0.13.21 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 18, 2026 License: Apache-2.0 Imports: 14 Imported by: 0

Documentation

Index

Constants

View Source
const ScreenshotDirName = "screenshots"

ScreenshotDirName is the subdirectory for screenshots within the audit directory.

Variables

View Source
var (
	// ErrSessionExists is returned when trying to create a session with an existing ID.
	ErrSessionExists = errors.New("session already exists")
	// ErrSessionNotFound is returned when a session ID is not found.
	ErrSessionNotFound = errors.New("session not found")
	// ErrSessionAmbiguous is returned when a fuzzy lookup matches multiple sessions.
	ErrSessionAmbiguous = errors.New("session ID is ambiguous - multiple matches")
)
View Source
var DefaultViewports = []ViewportPreset{
	{
		Name:   "mobile-portrait",
		Width:  375,
		Height: 667,
		Scale:  2.0,
		Mobile: true,
		Touch:  true,
	},
	{
		Name:   "mobile-landscape",
		Width:  667,
		Height: 375,
		Scale:  2.0,
		Mobile: true,
		Touch:  true,
	},
	{
		Name:   "tablet-portrait",
		Width:  768,
		Height: 1024,
		Scale:  2.0,
		Mobile: true,
		Touch:  true,
	},
	{
		Name:   "tablet-landscape",
		Width:  1024,
		Height: 768,
		Scale:  2.0,
		Mobile: true,
		Touch:  true,
	},
	{
		Name:   "desktop",
		Width:  1280,
		Height: 800,
		Scale:  1.0,
		Mobile: false,
		Touch:  false,
	},
	{
		Name:   "desktop-large",
		Width:  1920,
		Height: 1080,
		Scale:  1.0,
		Mobile: false,
		Touch:  false,
	},
}

DefaultViewports contains the 6 standard viewport presets for responsive testing.

Functions

func GetScreenshotDir

func GetScreenshotDir() (string, error)

GetScreenshotDir returns the screenshots directory path within .agnt/audit/. Creates the directory if it doesn't exist.

func ListViewportNames

func ListViewportNames() []string

ListViewportNames returns the names of all available viewport presets.

Types

type AutomationSession

type AutomationSession struct {
	// contains filtered or unexported fields
}

AutomationSession represents a chromedp-controlled browser session. It wraps chromedp contexts with atomic state management for safe concurrent access.

func NewSession

func NewSession(config SessionConfig) *AutomationSession

NewSession creates a new automation session with the given configuration.

func (*AutomationSession) CompareAndSwapState

func (s *AutomationSession) CompareAndSwapState(old, new State) bool

CompareAndSwapState atomically compares and swaps the session state. Returns true if the swap was successful.

func (*AutomationSession) Config

func (s *AutomationSession) Config() SessionConfig

Config returns the session configuration.

func (*AutomationSession) Context

func (s *AutomationSession) Context() context.Context

Context returns the chromedp task context for advanced usage. Returns nil if session is not running.

func (*AutomationSession) Done

func (s *AutomationSession) Done() <-chan struct{}

Done returns a channel that's closed when the session exits.

func (*AutomationSession) Error

func (s *AutomationSession) Error() error

Error returns the last error if any.

func (*AutomationSession) ID

func (s *AutomationSession) ID() string

ID returns the session ID.

func (*AutomationSession) Info

func (s *AutomationSession) Info() SessionInfo

Info returns information about the session.

func (*AutomationSession) Path

func (s *AutomationSession) Path() string

Path returns the project path for this session.

func (*AutomationSession) Run

func (s *AutomationSession) Run(actions ...chromedp.Action) error

Run executes chromedp actions within the session. Returns error if session is not running.

func (*AutomationSession) RunWithTimeout

func (s *AutomationSession) RunWithTimeout(timeout time.Duration, actions ...chromedp.Action) error

RunWithTimeout executes chromedp actions with a custom timeout.

func (*AutomationSession) Start

func (s *AutomationSession) Start(ctx context.Context) error

Start initializes the chromedp session with the allocator configured to route through the agnt proxy.

func (*AutomationSession) State

func (s *AutomationSession) State() State

State returns the current session state.

func (*AutomationSession) Stop

func (s *AutomationSession) Stop(ctx context.Context) error

Stop gracefully stops the automation session.

type ManagerStats

type ManagerStats struct {
	ActiveSessions int   `json:"active_sessions"`
	TotalStarted   int64 `json:"total_started"`
	TotalFailed    int64 `json:"total_failed"`
	ShuttingDown   bool  `json:"shutting_down"`
}

Stats returns manager statistics.

type ScreenshotOptions

type ScreenshotOptions struct {
	Label    string          // Optional label for the filename
	Viewport *ViewportPreset // Viewport preset to use (applies emulation)
	Quality  int             // JPEG quality (0-100, 0 = PNG)
	Scale    float64         // Scale factor for capture (default 1.0)
}

ScreenshotOptions configures screenshot capture behavior.

type ScreenshotResult

type ScreenshotResult struct {
	Path      string `json:"path"`      // Full path to the screenshot file
	Filename  string `json:"filename"`  // Just the filename
	Width     int64  `json:"width"`     // Viewport/capture width
	Height    int64  `json:"height"`    // Viewport/capture height
	Viewport  string `json:"viewport"`  // Viewport preset name (if used)
	Timestamp string `json:"timestamp"` // ISO timestamp of capture
}

ScreenshotResult contains information about a captured screenshot.

func CaptureAllViewports

func CaptureAllViewports(session *AutomationSession, label string, fullPage bool) ([]*ScreenshotResult, error)

CaptureAllViewports captures screenshots at all default viewport sizes. Returns a slice of results for each viewport.

func CaptureElement

func CaptureElement(session *AutomationSession, selector string, opts ScreenshotOptions) (*ScreenshotResult, error)

CaptureElement captures a screenshot of a specific element by CSS selector.

func CaptureFullPage

func CaptureFullPage(session *AutomationSession, opts ScreenshotOptions) (*ScreenshotResult, error)

CaptureFullPage captures a full-page screenshot (scrolls to capture entire page). If opts.Viewport is set, it first applies the viewport emulation.

func CaptureViewport

func CaptureViewport(session *AutomationSession, opts ScreenshotOptions) (*ScreenshotResult, error)

CaptureViewport captures a screenshot of the current viewport. If opts.Viewport is set, it first applies the viewport emulation.

func CaptureWithClip

func CaptureWithClip(session *AutomationSession, x, y, width, height float64, opts ScreenshotOptions) (*ScreenshotResult, error)

CaptureWithClip captures a screenshot of a specific region defined by clip bounds.

type SessionConfig

type SessionConfig struct {
	ID         string        // Session instance ID
	URL        string        // Initial URL to navigate to
	Headless   bool          // Run in headless mode (default: true)
	ProxyURL   string        // Proxy server URL (required for agnt integration)
	Path       string        // Project path for session scoping
	WindowSize string        // Window size as "width,height" (default: "1920,1080")
	Timeout    time.Duration // Default action timeout (default: 30s)
}

SessionConfig holds automation session configuration.

type SessionInfo

type SessionInfo struct {
	ID        string `json:"id"`
	State     string `json:"state"`
	URL       string `json:"url,omitempty"`
	Headless  bool   `json:"headless"`
	ProxyURL  string `json:"proxy_url,omitempty"`
	Path      string `json:"path,omitempty"`
	StartedAt string `json:"started_at,omitempty"`
	Error     string `json:"error,omitempty"`
}

SessionInfo contains information about an automation session.

type SessionManager

type SessionManager struct {
	// contains filtered or unexported fields
}

SessionManager manages chromedp automation sessions. It uses lock-free sync.Map for the session registry and atomic counters for metrics, following the same patterns as browser.Manager.

func NewSessionManager

func NewSessionManager() *SessionManager

NewSessionManager creates a new session manager.

func (*SessionManager) ActiveCount

func (m *SessionManager) ActiveCount() int

ActiveCount returns the number of active sessions.

func (*SessionManager) Get

Get returns a session by ID with fuzzy matching support. First tries exact match, then looks for sessions where the ID contains the search string as a component (for compound IDs).

func (*SessionManager) GetWithPathFilter

func (m *SessionManager) GetWithPathFilter(id, pathFilter string) (*AutomationSession, error)

GetWithPathFilter retrieves a session by ID with fuzzy matching, filtered by path. If pathFilter is non-empty, only sessions with matching Path are considered for fuzzy lookup. Exact matches are always returned regardless of path filter.

func (*SessionManager) IsShuttingDown

func (m *SessionManager) IsShuttingDown() bool

IsShuttingDown returns true if the manager is shutting down.

func (*SessionManager) List

func (m *SessionManager) List() []SessionInfo

List returns information about all sessions.

func (*SessionManager) ListByPath

func (m *SessionManager) ListByPath(pathFilter string) []SessionInfo

ListByPath returns sessions filtered by project path. If pathFilter is empty, returns all sessions.

func (*SessionManager) Shutdown

func (m *SessionManager) Shutdown(ctx context.Context) error

Shutdown stops all sessions and prevents new ones from starting.

func (*SessionManager) Start

Start starts an automation session with the given configuration.

func (*SessionManager) Stats

func (m *SessionManager) Stats() ManagerStats

Stats returns current manager statistics.

func (*SessionManager) Stop

func (m *SessionManager) Stop(ctx context.Context, id string) error

Stop stops a session by ID.

func (*SessionManager) StopAll

func (m *SessionManager) StopAll(ctx context.Context) ([]string, error)

StopAll stops all running sessions. Unlike Shutdown, this does NOT set shuttingDown flag, allowing new sessions to be started afterward. This is used for cleanup when the last client disconnects.

func (*SessionManager) StopByProjectPath

func (m *SessionManager) StopByProjectPath(ctx context.Context, projectPath string) ([]string, error)

StopByProjectPath stops all sessions for a specific project path. This is used for session-scoped cleanup when a client disconnects. Returns the list of stopped session IDs.

func (*SessionManager) TotalFailed

func (m *SessionManager) TotalFailed() int64

TotalFailed returns the total number of sessions that failed to start.

func (*SessionManager) TotalStarted

func (m *SessionManager) TotalStarted() int64

TotalStarted returns the total number of sessions started.

type State

type State uint32

State represents the automation session state.

const (
	StateIdle State = iota
	StateStarting
	StateRunning
	StateStopping
	StateStopped
	StateFailed
)

func (State) String

func (s State) String() string

type ViewportPreset

type ViewportPreset struct {
	Name   string  // Preset name (e.g., "mobile-portrait")
	Width  int64   // Viewport width in pixels
	Height int64   // Viewport height in pixels
	Scale  float64 // Device scale factor (e.g., 2.0 for retina)
	Mobile bool    // Emulate mobile device
	Touch  bool    // Enable touch events
}

ViewportPreset defines a standard viewport configuration for responsive testing.

func GetViewport

func GetViewport(name string) *ViewportPreset

GetViewport retrieves a viewport preset by name with fuzzy matching. It supports exact matches, partial matches, and common aliases. Returns nil if no matching preset is found.

func GetViewportByDimensions

func GetViewportByDimensions(width, height int64) *ViewportPreset

GetViewportByDimensions finds a preset closest to the given dimensions. Returns nil if no reasonably close preset is found.

func (*ViewportPreset) ToEmulateActions

func (v *ViewportPreset) ToEmulateActions() chromedp.Tasks

ToEmulateActions converts a ViewportPreset to chromedp emulation actions. It uses CDP commands directly to properly set mobile and touch emulation.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL