Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

refactor: split chrome instance and ghost-chrome adapter into focused files

Boschf0eb2dd46777
diff --git a/internal/browsers/browser.go b/internal/browsers/browser.go
index 52936368..dbcb8b7f 100644
--- a/internal/browsers/browser.go
+++ b/internal/browsers/browser.go
@@ -193,7 +193,7 @@ func sortedKeysLocked() []string {
return out
}
-// resetForTesting clears the global registry. Exported only for tests.
+// resetForTesting clears the global registry for this package's tests.
func resetForTesting() {
mu.Lock()
defer mu.Unlock()
diff --git a/internal/browsers/chrome/chrome.go b/internal/browsers/chrome/chrome.go
index 1ab697fe..973cedcc 100644
--- a/internal/browsers/chrome/chrome.go
+++ b/internal/browsers/chrome/chrome.go
@@ -149,9 +149,12 @@ func (Browser) BuildLaunchArgs(cfg browsers.LaunchConfig) ([]string, []string, e
)
if cfg.Headless {
+ // No --disable-gpu here: under --headless=new the compositor needs a
+ // GPU backend (swiftshader, enabled below); disabling the GPU process
+ // leaves Page.captureScreenshot/printToPDF with no backend and they
+ // hang past the action timeout.
args = append(args,
"--headless=new",
- "--disable-gpu",
"--disable-vulkan",
"--use-angle=swiftshader",
"--enable-unsafe-swiftshader",
diff --git a/internal/browsers/chrome/chrome_test.go b/internal/browsers/chrome/chrome_test.go
index f274f20d..fa611aff 100644
--- a/internal/browsers/chrome/chrome_test.go
+++ b/internal/browsers/chrome/chrome_test.go
@@ -210,7 +210,6 @@ func TestBuildLaunchArgsHeadlessAppendsFlags(t *testing.T) {
for _, want := range []string{
"--headless=new",
- "--disable-gpu",
"--disable-vulkan",
"--use-angle=swiftshader",
"--enable-unsafe-swiftshader",
@@ -220,8 +219,14 @@ func TestBuildLaunchArgsHeadlessAppendsFlags(t *testing.T) {
}
}
- if len(args) != 30 {
- t.Fatalf("expected 30 args (23 base + 5 headless + 1 --disable-extensions + 1 --window-size), got %d: %v", len(args), args)
+ // --disable-gpu must NOT appear: under --headless=new it removes the
+ // compositor's GPU backend and capture/print CDP calls hang.
+ if slices.Contains(args, "--disable-gpu") {
+ t.Error("headless args must not contain --disable-gpu")
+ }
+
+ if len(args) != 29 {
+ t.Fatalf("expected 29 args (23 base + 4 headless + 1 --disable-extensions + 1 --window-size), got %d: %v", len(args), args)
}
}
@@ -374,7 +379,6 @@ func TestBuildLaunchArgsParityWithRepresentativeConfigs(t *testing.T) {
"--disable-metrics-reporting",
"--password-store=basic",
"--headless=new",
- "--disable-gpu",
"--disable-vulkan",
"--use-angle=swiftshader",
"--enable-unsafe-swiftshader",
diff --git a/internal/browsers/chrome/instance.go b/internal/browsers/chrome/instance.go
index 17aca891..f51ab897 100644
--- a/internal/browsers/chrome/instance.go
+++ b/internal/browsers/chrome/instance.go
@@ -2,19 +2,14 @@ package chrome
import (
"context"
- "encoding/base64"
"encoding/json"
"fmt"
- "log/slog"
"strings"
- "sync"
- "sync/atomic"
"time"
"github.com/chromedp/cdproto/cdp"
"github.com/chromedp/cdproto/dom"
"github.com/chromedp/cdproto/emulation"
- "github.com/chromedp/cdproto/fetch"
"github.com/chromedp/cdproto/network"
"github.com/chromedp/cdproto/page"
"github.com/chromedp/cdproto/runtime"
@@ -90,187 +85,8 @@ func (i *Instance) CaptureScreenshot(ctx context.Context, format string, quality
return buf, nil
}
-// StartScreencast begins streaming screencast frames. The caller must call
-// Close on the returned ScreencastStream when done. The instance picks
-// event-driven (Page.startScreencast) or polling (CaptureScreenshot on a
-// ticker) based on the headless flag.
-func (i *Instance) StartScreencast(ctx context.Context, opts browsers.ScreencastOpts) (*browsers.ScreencastStream, error) {
- if i.headless {
- return i.startScreencastPolling(ctx, opts)
- }
- return i.startScreencastEventDriven(ctx, opts)
-}
-
-// startScreencastEventDriven uses CDP Page.startScreencast for headed browsers.
-func (i *Instance) startScreencastEventDriven(ctx context.Context, opts browsers.ScreencastOpts) (*browsers.ScreencastStream, error) {
- fps := opts.FPS
- if fps <= 0 {
- fps = 1
- }
- minFrameInterval := time.Second / time.Duration(fps)
-
- frameCh := make(chan []byte, 3)
- ackCh := make(chan int64, 128)
-
- stream := browsers.NewScreencastStream(frameCh, func() {
- _ = chromedp.Run(ctx,
- chromedp.ActionFunc(func(c context.Context) error {
- return page.StopScreencast().Do(c)
- }),
- )
- })
-
- go func() {
- for {
- select {
- case sessionID := <-ackCh:
- if err := chromedp.Run(ctx,
- chromedp.ActionFunc(func(c context.Context) error {
- return page.ScreencastFrameAck(sessionID).Do(c)
- }),
- ); err != nil && !isContextCanceled(err) {
- slog.Debug("screencast ack failed", "err", err)
- }
- case <-stream.Done():
- return
- }
- }
- }()
-
- // Listen for screencast frames with rate limiting
- var lastFrame time.Time
- chromedp.ListenTarget(ctx, func(ev interface{}) {
- switch e := ev.(type) {
- case *page.EventScreencastFrame:
- select {
- case ackCh <- e.SessionID:
- case <-stream.Done():
- return
- default:
- go func(sessionID int64) {
- if err := chromedp.Run(ctx,
- chromedp.ActionFunc(func(c context.Context) error {
- return page.ScreencastFrameAck(sessionID).Do(c)
- }),
- ); err != nil && !isContextCanceled(err) {
- slog.Debug("screencast ack fallback failed", "err", err)
- }
- }(e.SessionID)
- }
-
- now := time.Now()
- if now.Sub(lastFrame) < minFrameInterval {
- return
- }
- lastFrame = now
-
- data, err := base64.StdEncoding.DecodeString(e.Data)
- if err != nil {
- slog.Warn("screencast frame base64 decode failed", "error", err)
- return
- }
-
- select {
- case frameCh <- data:
- default:
- }
- }
- })
-
- err := chromedp.Run(ctx,
- chromedp.ActionFunc(func(c context.Context) error {
- return page.StartScreencast().
- WithFormat(page.ScreencastFormatJpeg).
- WithQuality(int64(opts.Quality)).
- WithMaxWidth(int64(opts.MaxWidth)).
- WithMaxHeight(int64(opts.MaxHeight)).
- WithEveryNthFrame(int64(opts.EveryNthFrame)).
- Do(c)
- }),
- )
- if err != nil {
- stream.Close()
- return nil, fmt.Errorf("start screencast: %w", err)
- }
-
- stopRepaintLoop := cdptk.StartRepaintLoop(ctx)
-
- // Wrap the closer to also stop the repaint loop.
- origStream := stream
- stream = browsers.NewScreencastStream(frameCh, func() {
- stopRepaintLoop()
- origStream.Close()
- })
-
- return stream, nil
-}
-
-// startScreencastPolling uses CaptureScreenshot on a ticker for headless browsers.
-func (i *Instance) startScreencastPolling(ctx context.Context, opts browsers.ScreencastOpts) (*browsers.ScreencastStream, error) {
- fps := opts.FPS
- if fps <= 0 {
- fps = 1
- }
- frameInterval := time.Second / time.Duration(fps)
- if frameInterval <= 0 {
- frameInterval = time.Second
- }
-
- frameCh := make(chan []byte, 2)
-
- stream := browsers.NewScreencastStream(frameCh, nil)
-
- go func() {
- defer close(frameCh)
-
- t0 := time.Now()
- frame, err := i.CaptureScreenshot(ctx, "jpeg", opts.Quality, nil)
- if err != nil {
- slog.Warn("screencast polling: initial CaptureScreenshot failed",
- "err", err, "elapsed", time.Since(t0))
- return
- }
- slog.Debug("screencast polling: initial frame captured",
- "bytes", len(frame), "elapsed", time.Since(t0))
-
- select {
- case frameCh <- frame:
- case <-stream.Done():
- return
- }
-
- ticker := time.NewTicker(frameInterval)
- defer ticker.Stop()
-
- var frames int
- for {
- select {
- case <-ticker.C:
- t1 := time.Now()
- frame, err := i.CaptureScreenshot(ctx, "jpeg", opts.Quality, nil)
- if err != nil {
- slog.Warn("screencast polling: CaptureScreenshot failed",
- "err", err, "frame", frames, "elapsed", time.Since(t1))
- return
- }
- frames++
- if frames <= 3 || frames%30 == 0 {
- slog.Debug("screencast polling: frame captured",
- "frame", frames, "bytes", len(frame), "elapsed", time.Since(t1))
- }
- select {
- case frameCh <- frame:
- case <-stream.Done():
- return
- }
- case <-stream.Done():
- return
- }
- }
- }()
-
- return stream, nil
-}
+// Screencast streaming (StartScreencast and its event-driven/polling
+// strategies) lives in instance_screencast.go.
// ---------------------------------------------------------------------------
// JavaScript evaluation
@@ -620,201 +436,6 @@ func (i *Instance) CurrentTitle(ctx context.Context) (string, error) {
return title, err
}
-// ---------------------------------------------------------------------------
-// Download
-// ---------------------------------------------------------------------------
-
-// DownloadURL downloads a URL using the browser's session (cookies, stealth).
-// It creates a temporary tab, enables fetch interception to validate requests,
-// navigates to the URL, and returns the response body.
-func (i *Instance) DownloadURL(ctx context.Context, dlURL string, opts browsers.DownloadOpts) (*browsers.DownloadResult, error) {
- tabCtx, tabCancel := chromedp.NewContext(i.browserCtx)
- defer tabCancel()
-
- tCtx, tCancel := context.WithCancel(ctx)
- defer tCancel()
-
- // Ensure tabCtx stays alive for the chromedp target.
- _ = tabCtx
-
- var requestID network.RequestID
- var responseMIME string
- var responseStatus int
- var mainFrameID cdp.FrameID
- done := make(chan struct{}, 1)
- var receivedBytes atomic.Int64
-
- var mu sync.Mutex
- var blockedErr error
-
- noteBlocked := func(err error) {
- mu.Lock()
- if blockedErr == nil {
- blockedErr = err
- }
- mu.Unlock()
- }
-
- getBlockedErr := func() error {
- mu.Lock()
- defer mu.Unlock()
- return blockedErr
- }
-
- if err := chromedp.Run(tabCtx, chromedp.ActionFunc(func(ctx context.Context) error {
- return fetch.Enable().Do(ctx)
- })); err != nil {
- return nil, fmt.Errorf("fetch enable: %w", err)
- }
- defer func() {
- _ = chromedp.Run(tabCtx, chromedp.ActionFunc(func(ctx context.Context) error {
- return fetch.Disable().Do(ctx)
- }))
- }()
-
- chromedp.ListenTarget(tabCtx, func(ev interface{}) {
- switch e := ev.(type) {
- case *fetch.EventRequestPaused:
- go func() {
- reqID := e.RequestID
- isRedirect := e.RedirectedRequestID != ""
- if opts.ValidateURL != nil {
- if err := opts.ValidateURL(e.Request.URL, isRedirect); err != nil {
- noteBlocked(err)
- select {
- case done <- struct{}{}:
- default:
- }
- _ = fetch.FailRequest(reqID, network.ErrorReasonBlockedByClient).Do(cdp.WithExecutor(tabCtx, chromedp.FromContext(tabCtx).Target))
- return
- }
- }
- _ = fetch.ContinueRequest(reqID).Do(cdp.WithExecutor(tabCtx, chromedp.FromContext(tabCtx).Target))
- }()
- case *network.EventRequestWillBeSent:
- if e.Type != network.ResourceTypeDocument {
- return
- }
- if mainFrameID == "" {
- mainFrameID = e.FrameID
- }
- if e.FrameID == mainFrameID {
- requestID = e.RequestID
- }
- case *network.EventResponseReceived:
- if e.RequestID == requestID && requestID != "" {
- requestID = e.RequestID
- responseMIME = e.Response.MimeType
- responseStatus = int(e.Response.Status)
- if opts.IsDomainAllowed != nil && !opts.IsDomainAllowed(e.Response.URL) {
- if opts.ValidateRemoteIP != nil {
- if err := opts.ValidateRemoteIP(e.Response.RemoteIPAddress); err != nil {
- noteBlocked(err)
- select {
- case done <- struct{}{}:
- default:
- }
- tCancel()
- return
- }
- }
- }
- if opts.MaxBytes > 0 && opts.ParseContentLength != nil {
- if contentLength, ok := opts.ParseContentLength(e.Response.Headers); ok && contentLength > int64(opts.MaxBytes) {
- noteBlocked(fmt.Errorf("download response too large: received %d bytes, max %d", contentLength, opts.MaxBytes))
- select {
- case done <- struct{}{}:
- default:
- }
- tCancel()
- return
- }
- }
- }
- case *network.EventDataReceived:
- if e.RequestID == requestID && requestID != "" {
- chunk := e.EncodedDataLength
- if chunk <= 0 {
- chunk = e.DataLength
- }
- if opts.MaxBytes > 0 && chunk > 0 && receivedBytes.Add(chunk) > int64(opts.MaxBytes) {
- noteBlocked(fmt.Errorf("download response too large: received %d bytes, max %d", receivedBytes.Load(), opts.MaxBytes))
- select {
- case done <- struct{}{}:
- default:
- }
- tCancel()
- return
- }
- }
- case *network.EventLoadingFinished:
- if e.RequestID == requestID && requestID != "" {
- select {
- case done <- struct{}{}:
- default:
- }
- }
- case *network.EventLoadingFailed:
- if e.RequestID == requestID && requestID != "" {
- select {
- case done <- struct{}{}:
- default:
- }
- }
- }
- })
-
- if err := chromedp.Run(tabCtx, network.Enable()); err != nil {
- return nil, fmt.Errorf("network enable: %w", err)
- }
-
- navErr := chromedp.Run(tabCtx, chromedp.Navigate(dlURL))
- if navErr != nil {
- if bErr := getBlockedErr(); bErr != nil {
- return nil, bErr
- }
- return nil, navErr
- }
-
- select {
- case <-done:
- case <-tCtx.Done():
- if bErr := getBlockedErr(); bErr != nil {
- return nil, bErr
- }
- return nil, fmt.Errorf("download timed out")
- }
-
- if bErr := getBlockedErr(); bErr != nil {
- return nil, bErr
- }
-
- if responseStatus >= 400 {
- return &browsers.DownloadResult{StatusCode: responseStatus, MIMEType: responseMIME}, fmt.Errorf("remote server returned HTTP %d", responseStatus)
- }
- if requestID == "" {
- return nil, fmt.Errorf("download response was not captured")
- }
-
- var body []byte
- if err := chromedp.Run(tabCtx, chromedp.ActionFunc(func(ctx context.Context) error {
- b, err := network.GetResponseBody(requestID).Do(ctx)
- if err != nil {
- return err
- }
- body = b
- return nil
- })); err != nil {
- return nil, fmt.Errorf("get response body: %w", err)
- }
-
- return &browsers.DownloadResult{
- Body: body,
- MIMEType: responseMIME,
- StatusCode: responseStatus,
- }, nil
-}
-
// ---------------------------------------------------------------------------
// PDF
// ---------------------------------------------------------------------------
diff --git a/internal/browsers/chrome/instance_download.go b/internal/browsers/chrome/instance_download.go
new file mode 100644
index 00000000..3f7fc84d
--- /dev/null
+++ b/internal/browsers/chrome/instance_download.go
@@ -0,0 +1,202 @@
+package chrome
+
+import (
+ "context"
+ "fmt"
+ "sync"
+ "sync/atomic"
+
+ "github.com/chromedp/cdproto/cdp"
+ "github.com/chromedp/cdproto/fetch"
+ "github.com/chromedp/cdproto/network"
+ "github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/browsers"
+)
+
+// DownloadURL downloads a URL using the browser's session (cookies, stealth).
+// It creates a temporary tab, enables fetch interception to validate requests,
+// navigates to the URL, and returns the response body.
+func (i *Instance) DownloadURL(ctx context.Context, dlURL string, opts browsers.DownloadOpts) (*browsers.DownloadResult, error) {
+ tabCtx, tabCancel := chromedp.NewContext(i.browserCtx)
+ defer tabCancel()
+
+ tCtx, tCancel := context.WithCancel(ctx)
+ defer tCancel()
+
+ var requestID network.RequestID
+ var responseMIME string
+ var responseStatus int
+ var mainFrameID cdp.FrameID
+ done := make(chan struct{}, 1)
+ var receivedBytes atomic.Int64
+
+ var mu sync.Mutex
+ var blockedErr error
+
+ noteBlocked := func(err error) {
+ mu.Lock()
+ if blockedErr == nil {
+ blockedErr = err
+ }
+ mu.Unlock()
+ }
+
+ getBlockedErr := func() error {
+ mu.Lock()
+ defer mu.Unlock()
+ return blockedErr
+ }
+
+ if err := chromedp.Run(tabCtx, chromedp.ActionFunc(func(ctx context.Context) error {
+ return fetch.Enable().Do(ctx)
+ })); err != nil {
+ return nil, fmt.Errorf("fetch enable: %w", err)
+ }
+ defer func() {
+ _ = chromedp.Run(tabCtx, chromedp.ActionFunc(func(ctx context.Context) error {
+ return fetch.Disable().Do(ctx)
+ }))
+ }()
+
+ chromedp.ListenTarget(tabCtx, func(ev interface{}) {
+ switch e := ev.(type) {
+ case *fetch.EventRequestPaused:
+ go func() {
+ reqID := e.RequestID
+ isRedirect := e.RedirectedRequestID != ""
+ if opts.ValidateURL != nil {
+ if err := opts.ValidateURL(e.Request.URL, isRedirect); err != nil {
+ noteBlocked(err)
+ select {
+ case done <- struct{}{}:
+ default:
+ }
+ _ = fetch.FailRequest(reqID, network.ErrorReasonBlockedByClient).Do(cdp.WithExecutor(tabCtx, chromedp.FromContext(tabCtx).Target))
+ return
+ }
+ }
+ _ = fetch.ContinueRequest(reqID).Do(cdp.WithExecutor(tabCtx, chromedp.FromContext(tabCtx).Target))
+ }()
+ case *network.EventRequestWillBeSent:
+ if e.Type != network.ResourceTypeDocument {
+ return
+ }
+ if mainFrameID == "" {
+ mainFrameID = e.FrameID
+ }
+ if e.FrameID == mainFrameID {
+ requestID = e.RequestID
+ }
+ case *network.EventResponseReceived:
+ if e.RequestID == requestID && requestID != "" {
+ requestID = e.RequestID
+ responseMIME = e.Response.MimeType
+ responseStatus = int(e.Response.Status)
+ if opts.IsDomainAllowed != nil && !opts.IsDomainAllowed(e.Response.URL) {
+ if opts.ValidateRemoteIP != nil {
+ if err := opts.ValidateRemoteIP(e.Response.RemoteIPAddress); err != nil {
+ noteBlocked(err)
+ select {
+ case done <- struct{}{}:
+ default:
+ }
+ tCancel()
+ return
+ }
+ }
+ }
+ if opts.MaxBytes > 0 && opts.ParseContentLength != nil {
+ if contentLength, ok := opts.ParseContentLength(e.Response.Headers); ok && contentLength > int64(opts.MaxBytes) {
+ noteBlocked(fmt.Errorf("download response too large: received %d bytes, max %d", contentLength, opts.MaxBytes))
+ select {
+ case done <- struct{}{}:
+ default:
+ }
+ tCancel()
+ return
+ }
+ }
+ }
+ case *network.EventDataReceived:
+ if e.RequestID == requestID && requestID != "" {
+ chunk := e.EncodedDataLength
+ if chunk <= 0 {
+ chunk = e.DataLength
+ }
+ if opts.MaxBytes > 0 && chunk > 0 && receivedBytes.Add(chunk) > int64(opts.MaxBytes) {
+ noteBlocked(fmt.Errorf("download response too large: received %d bytes, max %d", receivedBytes.Load(), opts.MaxBytes))
+ select {
+ case done <- struct{}{}:
+ default:
+ }
+ tCancel()
+ return
+ }
+ }
+ case *network.EventLoadingFinished:
+ if e.RequestID == requestID && requestID != "" {
+ select {
+ case done <- struct{}{}:
+ default:
+ }
+ }
+ case *network.EventLoadingFailed:
+ if e.RequestID == requestID && requestID != "" {
+ select {
+ case done <- struct{}{}:
+ default:
+ }
+ }
+ }
+ })
+
+ if err := chromedp.Run(tabCtx, network.Enable()); err != nil {
+ return nil, fmt.Errorf("network enable: %w", err)
+ }
+
+ navErr := chromedp.Run(tabCtx, chromedp.Navigate(dlURL))
+ if navErr != nil {
+ if bErr := getBlockedErr(); bErr != nil {
+ return nil, bErr
+ }
+ return nil, navErr
+ }
+
+ select {
+ case <-done:
+ case <-tCtx.Done():
+ if bErr := getBlockedErr(); bErr != nil {
+ return nil, bErr
+ }
+ return nil, fmt.Errorf("download timed out")
+ }
+
+ if bErr := getBlockedErr(); bErr != nil {
+ return nil, bErr
+ }
+
+ if responseStatus >= 400 {
+ return &browsers.DownloadResult{StatusCode: responseStatus, MIMEType: responseMIME}, fmt.Errorf("remote server returned HTTP %d", responseStatus)
+ }
+ if requestID == "" {
+ return nil, fmt.Errorf("download response was not captured")
+ }
+
+ var body []byte
+ if err := chromedp.Run(tabCtx, chromedp.ActionFunc(func(ctx context.Context) error {
+ b, err := network.GetResponseBody(requestID).Do(ctx)
+ if err != nil {
+ return err
+ }
+ body = b
+ return nil
+ })); err != nil {
+ return nil, fmt.Errorf("get response body: %w", err)
+ }
+
+ return &browsers.DownloadResult{
+ Body: body,
+ MIMEType: responseMIME,
+ StatusCode: responseStatus,
+ }, nil
+}
diff --git a/internal/browsers/chrome/instance_screencast.go b/internal/browsers/chrome/instance_screencast.go
new file mode 100644
index 00000000..25dd22d9
--- /dev/null
+++ b/internal/browsers/chrome/instance_screencast.go
@@ -0,0 +1,198 @@
+package chrome
+
+import (
+ "context"
+ "encoding/base64"
+ "fmt"
+ "log/slog"
+ "sync/atomic"
+ "time"
+
+ "github.com/chromedp/cdproto/page"
+ "github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/browsers"
+ "github.com/pinchtab/pinchtab/internal/cdptk"
+)
+
+// StartScreencast begins streaming screencast frames. The caller must call
+// Close on the returned ScreencastStream when done. The instance picks
+// event-driven (Page.startScreencast) or polling (CaptureScreenshot on a
+// ticker) based on the headless flag.
+func (i *Instance) StartScreencast(ctx context.Context, opts browsers.ScreencastOpts) (*browsers.ScreencastStream, error) {
+ if i.headless {
+ return i.startScreencastPolling(ctx, opts)
+ }
+ return i.startScreencastEventDriven(ctx, opts)
+}
+
+// startScreencastEventDriven uses CDP Page.startScreencast for headed browsers.
+func (i *Instance) startScreencastEventDriven(ctx context.Context, opts browsers.ScreencastOpts) (*browsers.ScreencastStream, error) {
+ fps := opts.FPS
+ if fps <= 0 {
+ fps = 1
+ }
+ minFrameInterval := time.Second / time.Duration(fps)
+
+ frameCh := make(chan []byte, 3)
+ ackCh := make(chan int64, 128)
+
+ // stream is captured by the ack goroutine and the ListenTarget callback
+ // below; it must never be reassigned (an unsynchronized write racing
+ // their reads). The repaint-loop stop only exists after StartScreencast
+ // succeeds, so the closer late-binds it through an atomic instead.
+ var stopRepaint atomic.Value // holds func()
+ stream := browsers.NewScreencastStream(frameCh, func() {
+ if f, ok := stopRepaint.Load().(func()); ok {
+ f()
+ }
+ _ = chromedp.Run(ctx,
+ chromedp.ActionFunc(func(c context.Context) error {
+ return page.StopScreencast().Do(c)
+ }),
+ )
+ })
+
+ go func() {
+ for {
+ select {
+ case sessionID := <-ackCh:
+ if err := chromedp.Run(ctx,
+ chromedp.ActionFunc(func(c context.Context) error {
+ return page.ScreencastFrameAck(sessionID).Do(c)
+ }),
+ ); err != nil && !isContextCanceled(err) {
+ slog.Debug("screencast ack failed", "err", err)
+ }
+ case <-stream.Done():
+ return
+ }
+ }
+ }()
+
+ // Listen for screencast frames with rate limiting
+ var lastFrame time.Time
+ chromedp.ListenTarget(ctx, func(ev interface{}) {
+ switch e := ev.(type) {
+ case *page.EventScreencastFrame:
+ select {
+ case ackCh <- e.SessionID:
+ case <-stream.Done():
+ return
+ default:
+ go func(sessionID int64) {
+ if err := chromedp.Run(ctx,
+ chromedp.ActionFunc(func(c context.Context) error {
+ return page.ScreencastFrameAck(sessionID).Do(c)
+ }),
+ ); err != nil && !isContextCanceled(err) {
+ slog.Debug("screencast ack fallback failed", "err", err)
+ }
+ }(e.SessionID)
+ }
+
+ now := time.Now()
+ if now.Sub(lastFrame) < minFrameInterval {
+ return
+ }
+ lastFrame = now
+
+ data, err := base64.StdEncoding.DecodeString(e.Data)
+ if err != nil {
+ slog.Warn("screencast frame base64 decode failed", "error", err)
+ return
+ }
+
+ select {
+ case frameCh <- data:
+ default:
+ }
+ }
+ })
+
+ err := chromedp.Run(ctx,
+ chromedp.ActionFunc(func(c context.Context) error {
+ return page.StartScreencast().
+ WithFormat(page.ScreencastFormatJpeg).
+ WithQuality(int64(opts.Quality)).
+ WithMaxWidth(int64(opts.MaxWidth)).
+ WithMaxHeight(int64(opts.MaxHeight)).
+ WithEveryNthFrame(int64(opts.EveryNthFrame)).
+ Do(c)
+ }),
+ )
+ if err != nil {
+ stream.Close()
+ return nil, fmt.Errorf("start screencast: %w", err)
+ }
+
+ stopRepaint.Store(cdptk.StartRepaintLoop(ctx))
+
+ return stream, nil
+}
+
+// startScreencastPolling uses CaptureScreenshot on a ticker for headless browsers.
+func (i *Instance) startScreencastPolling(ctx context.Context, opts browsers.ScreencastOpts) (*browsers.ScreencastStream, error) {
+ fps := opts.FPS
+ if fps <= 0 {
+ fps = 1
+ }
+ frameInterval := time.Second / time.Duration(fps)
+ if frameInterval <= 0 {
+ frameInterval = time.Second
+ }
+
+ frameCh := make(chan []byte, 2)
+
+ stream := browsers.NewScreencastStream(frameCh, nil)
+
+ go func() {
+ defer close(frameCh)
+
+ t0 := time.Now()
+ frame, err := i.CaptureScreenshot(ctx, "jpeg", opts.Quality, nil)
+ if err != nil {
+ slog.Warn("screencast polling: initial CaptureScreenshot failed",
+ "err", err, "elapsed", time.Since(t0))
+ return
+ }
+ slog.Debug("screencast polling: initial frame captured",
+ "bytes", len(frame), "elapsed", time.Since(t0))
+
+ select {
+ case frameCh <- frame:
+ case <-stream.Done():
+ return
+ }
+
+ ticker := time.NewTicker(frameInterval)
+ defer ticker.Stop()
+
+ var frames int
+ for {
+ select {
+ case <-ticker.C:
+ t1 := time.Now()
+ frame, err := i.CaptureScreenshot(ctx, "jpeg", opts.Quality, nil)
+ if err != nil {
+ slog.Warn("screencast polling: CaptureScreenshot failed",
+ "err", err, "frame", frames, "elapsed", time.Since(t1))
+ return
+ }
+ frames++
+ if frames <= 3 || frames%30 == 0 {
+ slog.Debug("screencast polling: frame captured",
+ "frame", frames, "bytes", len(frame), "elapsed", time.Since(t1))
+ }
+ select {
+ case frameCh <- frame:
+ case <-stream.Done():
+ return
+ }
+ case <-stream.Done():
+ return
+ }
+ }
+ }()
+
+ return stream, nil
+}
diff --git a/internal/browsers/cloak/doctor.go b/internal/browsers/cloak/doctor.go
index ad0fe6d4..1c4f7b35 100644
--- a/internal/browsers/cloak/doctor.go
+++ b/internal/browsers/cloak/doctor.go
@@ -145,7 +145,14 @@ func fingerprintFlagsCheck(ctx context.Context, cfg interface{}) browsers.Doctor
launchCfg := browsers.LaunchConfig{
Cloak: env.Cloak,
}
- allArgs, _, _ := Browser{}.BuildLaunchArgs(launchCfg)
+ allArgs, _, err := Browser{}.BuildLaunchArgs(launchCfg)
+ if err != nil {
+ return browsers.DoctorCheckResult{
+ Status: browsers.DoctorFail,
+ Detail: fmt.Sprintf("building fingerprint flags failed: %v", err),
+ Err: err,
+ }
+ }
// Extract only fingerprint flags.
var fpFlags []string
for _, a := range allArgs {
diff --git a/internal/browsers/ghostchrome/bridge_proxy.go b/internal/browsers/ghostchrome/bridge_proxy.go
index a024a60a..8a58a0b8 100644
--- a/internal/browsers/ghostchrome/bridge_proxy.go
+++ b/internal/browsers/ghostchrome/bridge_proxy.go
@@ -3,6 +3,7 @@ package ghostchrome
import (
"context"
"log/slog"
+ "sort"
"sync"
"github.com/pinchtab/pinchtab/internal/browserops"
@@ -156,10 +157,25 @@ func (p *BridgeProxy) ExecuteAction(ctx context.Context, kind string, req Action
return p.chrome.ExecuteAction(ctx, kind, req)
}
+// ReleaseTab scrubs all per-tab proxy state: the lite→Chrome mapping, the
+// escalation mutex, and the static tab itself. Deleting the escalation mutex
+// while another goroutine holds it is safe: the held mutex keeps working, and
+// a racing newcomer gets a fresh mutex, re-checks state under it, and finds
+// the tab gone (tab-not-found).
+func (p *BridgeProxy) ReleaseTab(tabID string) {
+ p.tabMap.clear(tabID)
+ p.escalationMu.Delete(tabID)
+ if p.lite != nil {
+ p.lite.CloseTab(tabID)
+ }
+}
+
// canHandleStaticAction returns true when a static browser action is
// feasible: the action kind is click or type/fill, the request targets
// an element by ref (not a CSS selector), AND the tab exists in the
-// static browser (not an escalated Chrome tab).
+// static browser. Escalated tabs are closed in the static browser once
+// their ref cache is built (see BridgeAdapter.TabContext), so they fail
+// the TabURL check and route to Chrome.
func (p *BridgeProxy) canHandleStaticAction(kind string, ref string, tabID string) bool {
if p.lite == nil || ref == "" {
return false
@@ -198,6 +214,9 @@ func (p *BridgeProxy) AvailableActions() []string {
for a := range set {
result = append(result, a)
}
+ // Deterministic order: handlers interpolate this into "valid values:"
+ // error messages, which must not vary per call.
+ sort.Strings(result)
return result
}
diff --git a/internal/browsers/ghostchrome/bridge_proxy_test.go b/internal/browsers/ghostchrome/bridge_proxy_test.go
index f9b22fcd..1c061690 100644
--- a/internal/browsers/ghostchrome/bridge_proxy_test.go
+++ b/internal/browsers/ghostchrome/bridge_proxy_test.go
@@ -5,6 +5,7 @@ import (
"fmt"
"net/http"
"net/http/httptest"
+ "sort"
"sync"
"testing"
@@ -451,3 +452,27 @@ func startTestHTTPServer(t *testing.T) *httptest.Server {
</html>`)
}))
}
+
+// L4 regression: the merged action set is map-built; its order must be
+// deterministic because handlers interpolate it into error messages.
+func TestAvailableActions_DeterministicSortedOrder(t *testing.T) {
+ mb := newMockChromeBridge()
+ mb.availableActions = []string{ActionScroll, ActionClick, ActionPress}
+ lite := staticfetch.NewBrowser()
+ defer func() { _ = lite.Close() }()
+ p := NewBridgeProxy(mb, lite, nil)
+
+ first := p.AvailableActions()
+ if !sort.StringsAreSorted(first) {
+ t.Fatalf("actions not sorted: %v", first)
+ }
+ second := p.AvailableActions()
+ if len(first) != len(second) {
+ t.Fatalf("lengths differ across calls: %v vs %v", first, second)
+ }
+ for i := range first {
+ if first[i] != second[i] {
+ t.Fatalf("order differs across calls: %v vs %v", first, second)
+ }
+ }
+}
diff --git a/internal/browsers/ghostchrome/bridgekit/bridge_adapter.go b/internal/browsers/ghostchrome/bridgekit/bridge_adapter.go
index ce33e66d..fa03aa5f 100644
--- a/internal/browsers/ghostchrome/bridgekit/bridge_adapter.go
+++ b/internal/browsers/ghostchrome/bridgekit/bridge_adapter.go
@@ -4,19 +4,21 @@
// It lives in a sub-package of ghostchrome to break the import cycle
// that would occur if ghostchrome imported bridge directly
// (bridge -> config -> browsers/all -> ghostchrome -> bridge).
+//
+// The adapter is split across files by responsibility:
+// - bridge_adapter.go — core wiring: types, construction, provider
+// registration, tab-context resolution, action dispatch.
+// - bridge_adapter_refmap.go — escalated ref-cache population.
+// - bridge_adapter_content.go — static-first Navigate/Snapshot/Text
+// routing and escalation helpers.
+// - bridge_adapter_passthrough.go — thin delegations to the embedded
+// Chrome bridge.
package bridgekit
import (
"context"
- "fmt"
- "log/slog"
- "net"
- "net/netip"
- "strings"
- "time"
"github.com/pinchtab/pinchtab/internal/bridge"
- "github.com/pinchtab/pinchtab/internal/browserops"
"github.com/pinchtab/pinchtab/internal/browsers/ghostchrome"
"github.com/pinchtab/pinchtab/internal/browsers/ghostchrome/staticfetch"
"github.com/pinchtab/pinchtab/internal/browsers/providerhooks"
@@ -99,6 +101,13 @@ func (a *BridgeAdapter) TabContext(tabID string) (*bridge.TabHandle, string, err
}
if resolvedID != tabID {
a.populateEscalatedRefCache(ctx, resolvedID, tabID)
+ // Escalation transfers ownership to Chrome: with the ref cache built,
+ // the static tab's only remaining effect would be serving stale-DOM
+ // reads/actions, so retire it. No-op for non-lite ID aliasing and on
+ // repeat calls (the mapping keeps resolving via tabMap).
+ if sb := a.StaticBrowser(); sb != nil {
+ sb.CloseTab(tabID)
+ }
}
// Wrap the context from the proxy in a TabHandle. The proxy's
// TabContext returns context.Context (from ChromeBridge interface),
@@ -110,78 +119,6 @@ func (a *BridgeAdapter) TabContext(tabID string) (*bridge.TabHandle, string, err
return bridge.NewTabHandle(ctx), resolvedID, nil
}
-// populateEscalatedRefCache builds a ref cache for a newly escalated Chrome
-// tab that maps the STATIC browser's ref names to Chrome's BackendNodeIDs.
-// This is necessary because Chrome and the static browser assign different
-// sequential ref numbers (e0, e1, ...) to the same page elements. We match
-// by (role, name) to bridge the two numbering schemes.
-func (a *BridgeAdapter) populateEscalatedRefCache(ctx context.Context, chromeTabID, liteTabID string) {
- if a.BridgeAPI.GetRefCache(chromeTabID) != nil {
- return
- }
-
- staticBrowser := a.proxy.StaticBrowser()
- if staticBrowser == nil {
- return
- }
- staticSnap, err := staticBrowser.Snapshot(context.Background(), liteTabID, "interactive")
- if err != nil || len(staticSnap.Nodes) == 0 {
- return
- }
-
- chromeNodes, err := bridge.FetchAXTree(ctx)
- if err != nil {
- return
- }
- flat, _ := bridge.BuildSnapshot(chromeNodes, bridge.FilterInteractive, -1)
- _ = bridge.EnrichA11yNodesWithDOMMetadata(ctx, flat)
-
- type chromeEntry struct {
- node bridge.A11yNode
- used bool
- }
- chromeByKey := map[string][]*chromeEntry{}
- for i := range flat {
- key := flat[i].Role + "\x00" + flat[i].Name
- chromeByKey[key] = append(chromeByKey[key], &chromeEntry{node: flat[i]})
- }
-
- refs := make(map[string]int64, len(staticSnap.Nodes))
- targets := make(map[string]bridge.RefTarget, len(staticSnap.Nodes))
- for _, sn := range staticSnap.Nodes {
- if sn.Ref == "" {
- continue
- }
- key := sn.Role + "\x00" + sn.Name
- for _, entry := range chromeByKey[key] {
- if !entry.used && entry.node.NodeID != 0 {
- entry.used = true
- refs[sn.Ref] = entry.node.NodeID
- targets[sn.Ref] = bridge.RefTarget{
- BackendNodeID: entry.node.NodeID,
- FrameID: entry.node.FrameID,
- FrameURL: entry.node.FrameURL,
- FrameName: entry.node.FrameName,
- ChildFrameID: entry.node.ChildFrameID,
- ChildFrameURL: entry.node.ChildFrameURL,
- ChildFrameName: entry.node.ChildFrameName,
- }
- break
- }
- }
- }
-
- slog.Debug("populated escalated ref cache",
- "chromeTab", chromeTabID, "liteTab", liteTabID,
- "staticRefs", len(staticSnap.Nodes), "mapped", len(refs))
-
- a.SetRefCache(chromeTabID, &bridge.RefCache{
- Refs: refs,
- Targets: targets,
- Nodes: flat,
- })
-}
-
func (a *BridgeAdapter) ExecuteAction(ctx context.Context, kind string, req bridge.ActionRequest) (map[string]any, error) {
return a.proxy.ExecuteAction(ctx, kind, ghostchrome.ActionRequest{
TabID: req.TabID,
@@ -194,34 +131,6 @@ func (a *BridgeAdapter) ExecuteAction(ctx context.Context, kind string, req brid
})
}
-func (a *BridgeAdapter) FocusTab(tabID string) error {
- if chromeID, ok := a.proxy.ChromeTabID(tabID); ok {
- return a.BridgeAPI.FocusTab(chromeID)
- }
- return a.BridgeAPI.FocusTab(tabID)
-}
-
-func (a *BridgeAdapter) CloseTab(tabID string) error {
- if chromeID, ok := a.proxy.ChromeTabID(tabID); ok {
- return a.BridgeAPI.CloseTab(chromeID)
- }
- return a.BridgeAPI.CloseTab(tabID)
-}
-
-func (a *BridgeAdapter) GetRefCache(tabID string) *bridge.RefCache {
- if cache := a.BridgeAPI.GetRefCache(tabID); cache != nil {
- return cache
- }
- if chromeID, ok := a.proxy.ChromeTabID(tabID); ok {
- return a.BridgeAPI.GetRefCache(chromeID)
- }
- return nil
-}
-
-func (a *BridgeAdapter) AvailableActions() []string {
- return a.proxy.AvailableActions()
-}
-
// StaticBrowser returns the underlying static fetch browser.
// Returns nil if no lite browser is configured.
func (a *BridgeAdapter) StaticBrowser() *staticfetch.Browser {
@@ -236,392 +145,3 @@ func (a *BridgeAdapter) StaticBrowser() *staticfetch.Browser {
}
return nil
}
-
-// Navigate implements the ghost-chrome "static first, assess quality, escalate
-// to Chrome" routing pattern for navigation. It tries the static browser first;
-// if the fetched content passes the quality gate it returns immediately.
-// Otherwise it falls through to the Chrome bridge.
-func (a *BridgeAdapter) Navigate(ctx context.Context, url string, params bridge.NavigateParams) (*bridge.NavigateResult, error) {
- staticBrowser := a.proxy.StaticBrowser()
- if staticBrowser != nil {
- // Attach network policy from NavigateParams so the static
- // browser enforces SSRF/redirect protections.
- ctx = staticfetch.WithNavigateNetworkPolicy(ctx, navigateParamsToPolicy(&params))
- navResult, err := staticBrowser.Navigate(ctx, url)
- if err == nil {
- // Assess content quality by extracting text from the static page.
- textResult, textErr := staticBrowser.Text(ctx, navResult.TabID)
- if textErr == nil {
- gr := ghostchrome.AssessContent(textResult.Text)
- if gr.ShouldAccept() {
- slog.Debug("ghost-chrome navigate: static accepted",
- "url", url, "quality", gr.Quality)
- return &bridge.NavigateResult{
- TabID: navResult.TabID,
- URL: navResult.URL,
- Title: navResult.Title,
- Route: &browserops.RouteMetadata{
- RequestedBrowser: "ghost-chrome",
- UsedBrowser: "ghost-chrome",
- Quality: gr.Quality,
- Attempts: []browserops.RouteAttempt{
- {Browser: "ghost-chrome", Accepted: true, Reason: gr.FormatReason()},
- },
- },
- }, nil
- }
- // Quality too low — escalate to Chrome.
- slog.Debug("ghost-chrome navigate: quality too low, escalating",
- "url", url, "quality", gr.Quality, "reason", gr.FormatReason())
- chromeResult, chromeErr := a.BridgeAPI.Navigate(ctx, url, params)
- if chromeErr != nil {
- return nil, chromeErr
- }
- chromeResult.Route = &browserops.RouteMetadata{
- RequestedBrowser: "ghost-chrome",
- UsedBrowser: "ghost-chrome",
- Escalated: true,
- Quality: gr.Quality,
- Attempts: []browserops.RouteAttempt{
- {Browser: "ghost-chrome", Accepted: false, Reason: gr.FormatReason()},
- {Browser: "chrome", Accepted: true, Reason: "escalated"},
- },
- }
- return chromeResult, nil
- }
- // Text extraction failed — escalate with zero quality.
- slog.Debug("ghost-chrome navigate: text extraction failed, escalating",
- "url", url, "err", textErr)
- } else {
- slog.Debug("ghost-chrome navigate: static navigate failed, escalating",
- "url", url, "err", err)
- }
- }
-
- // Static browser unavailable or failed — go straight to Chrome.
- chromeResult, chromeErr := a.BridgeAPI.Navigate(ctx, url, params)
- if chromeErr != nil {
- return nil, chromeErr
- }
- chromeResult.Route = &browserops.RouteMetadata{
- RequestedBrowser: "ghost-chrome",
- UsedBrowser: "ghost-chrome",
- Escalated: true,
- Quality: 0,
- Attempts: []browserops.RouteAttempt{
- {Browser: "ghost-chrome", Accepted: false, Reason: "static browser unavailable or failed"},
- {Browser: "chrome", Accepted: true, Reason: "escalated"},
- },
- }
- return chromeResult, nil
-}
-
-// Snapshot implements the ghost-chrome "static first, assess quality, escalate
-// to Chrome" routing pattern for snapshots. It tries reading the accessibility
-// tree from the static browser; if the snapshot passes the quality gate it
-// converts the nodes to bridge.A11yNode and returns. Otherwise it falls
-// through to Chrome.
-func (a *BridgeAdapter) Snapshot(ctx context.Context, tabID string, filter string, params bridge.ContentParams) (*bridge.SnapshotResult, error) {
- staticBrowser := a.proxy.StaticBrowser()
- if staticBrowser != nil {
- snapResult, err := staticBrowser.Snapshot(context.Background(), tabID, filter)
- if err == nil && len(snapResult.Nodes) > 0 {
- // Convert to ghostchrome.SnapshotNode for quality assessment.
- assessNodes := make([]ghostchrome.SnapshotNode, len(snapResult.Nodes))
- for i, n := range snapResult.Nodes {
- assessNodes[i] = ghostchrome.SnapshotNode{Role: n.Role, Name: n.Name}
- }
- if ghostchrome.AssessSnapshot(assessNodes) {
- // Convert browserops.SnapshotNode → bridge.A11yNode.
- flat := make([]bridge.A11yNode, len(snapResult.Nodes))
- refs := make(map[string]int64, len(snapResult.Nodes))
- targets := make(map[string]bridge.RefTarget, len(snapResult.Nodes))
- for i, n := range snapResult.Nodes {
- flat[i] = bridge.A11yNode{
- Ref: n.Ref,
- Role: n.Role,
- Name: n.Name,
- Tag: n.Tag,
- Value: n.Value,
- Depth: n.Depth,
- }
- if n.Ref != "" {
- refs[n.Ref] = 0
- targets[n.Ref] = bridge.RefTarget{}
- }
- }
-
- // IDPI: scan snapshot node names/values when ContentGuard is set.
- var idpiWarning string
- if params.ContentGuard != nil {
- var sb strings.Builder
- for _, n := range flat {
- if n.Name != "" || n.Value != "" {
- sb.WriteString(n.Name)
- if n.Name != "" && n.Value != "" {
- sb.WriteByte(' ')
- }
- sb.WriteString(n.Value)
- sb.WriteByte('\n')
- }
- }
- scanResult := params.ContentGuard.ScanOnly(sb.String())
- if scanResult.Blocked {
- return nil, fmt.Errorf("snapshot blocked by IDPI scanner: %s", scanResult.BlockReason)
- }
- if scanResult.Warning != "" {
- idpiWarning = scanResult.Warning
- }
- }
-
- slog.Debug("ghost-chrome snapshot: static accepted",
- "tabID", tabID, "nodes", len(flat))
- return &bridge.SnapshotResult{
- Nodes: flat,
- Refs: refs,
- Targets: targets,
- IDPIWarning: idpiWarning,
- Route: &browserops.RouteMetadata{
- RequestedBrowser: "ghost-chrome",
- UsedBrowser: "ghost-chrome",
- Attempts: []browserops.RouteAttempt{
- {Browser: "ghost-chrome", Accepted: true},
- },
- },
- }, nil
- }
- // Quality too low — fall through to Chrome.
- slog.Debug("ghost-chrome snapshot: quality too low, escalating", "tabID", tabID)
- }
- }
-
- // Escalate to Chrome. Resolve the tab ID for escalated tabs.
- resolvedTabID := tabID
- if chromeID, ok := a.proxy.ChromeTabID(tabID); ok {
- resolvedTabID = chromeID
- }
- chromeSnap, err := a.BridgeAPI.Snapshot(ctx, resolvedTabID, filter, params)
- if err != nil {
- return nil, err
- }
- chromeSnap.Route = &browserops.RouteMetadata{
- RequestedBrowser: "ghost-chrome",
- UsedBrowser: "ghost-chrome",
- Escalated: true,
- Attempts: []browserops.RouteAttempt{
- {Browser: "ghost-chrome", Accepted: false, Reason: "quality too low or static unavailable"},
- {Browser: "chrome", Accepted: true, Reason: "escalated"},
- },
- }
- return chromeSnap, nil
-}
-
-// Text implements the ghost-chrome "static first, assess quality, escalate to
-// Chrome" routing pattern for text extraction. It tries the static browser
-// first; if the text passes the quality gate it returns immediately. Otherwise
-// it falls through to Chrome.
-func (a *BridgeAdapter) Text(ctx context.Context, tabID string, params bridge.ContentParams) (*bridge.TextResult, error) {
- staticBrowser := a.proxy.StaticBrowser()
- if staticBrowser != nil {
- textResult, err := staticBrowser.Text(context.Background(), tabID)
- if err == nil && textResult.Text != "" {
- gr := ghostchrome.AssessContent(textResult.Text)
- if gr.ShouldAccept() {
- // IDPI: scan extracted text when ContentGuard is set.
- text := textResult.Text
- var idpiWarning string
- if params.ContentGuard != nil {
- scanResult := params.ContentGuard.Scan(text, textResult.URL)
- if scanResult.Blocked {
- return nil, fmt.Errorf("content blocked by IDPI scanner: %s", scanResult.BlockReason)
- }
- text = scanResult.Text
- if scanResult.Warning != "" {
- idpiWarning = scanResult.Warning
- }
- }
-
- slog.Debug("ghost-chrome text: static accepted",
- "tabID", tabID, "quality", gr.Quality)
- return &bridge.TextResult{
- Text: text,
- URL: textResult.URL,
- Title: textResult.Title,
- IDPIWarning: idpiWarning,
- Route: &browserops.RouteMetadata{
- RequestedBrowser: "ghost-chrome",
- UsedBrowser: "ghost-chrome",
- Quality: gr.Quality,
- Attempts: []browserops.RouteAttempt{
- {Browser: "ghost-chrome", Accepted: true, Reason: gr.FormatReason()},
- },
- },
- }, nil
- }
- // Quality too low — fall through to Chrome.
- slog.Debug("ghost-chrome text: quality too low, escalating",
- "tabID", tabID, "quality", gr.Quality, "reason", gr.FormatReason())
- }
- }
-
- // Escalate to Chrome. Resolve the tab ID for escalated tabs.
- resolvedTabID := tabID
- if chromeID, ok := a.proxy.ChromeTabID(tabID); ok {
- resolvedTabID = chromeID
- }
- chromeText, err := a.BridgeAPI.Text(ctx, resolvedTabID, params)
- if err != nil {
- return nil, err
- }
- chromeText.Route = &browserops.RouteMetadata{
- RequestedBrowser: "ghost-chrome",
- UsedBrowser: "ghost-chrome",
- Escalated: true,
- Attempts: []browserops.RouteAttempt{
- {Browser: "ghost-chrome", Accepted: false, Reason: "quality too low or static unavailable"},
- {Browser: "chrome", Accepted: true, Reason: "escalated"},
- },
- }
- return chromeText, nil
-}
-
-func (a *BridgeAdapter) GetDocumentReadyState(tabID string) (string, error) {
- type readyStater interface {
- GetDocumentReadyState(string) (string, error)
- }
- if rs, ok := a.BridgeAPI.(readyStater); ok {
- return rs.GetDocumentReadyState(tabID)
- }
- return "", nil
-}
-
-func (a *BridgeAdapter) IsNetworkIdle(tabID string) (bool, bool) {
- type idleChecker interface {
- IsNetworkIdle(string) (bool, bool)
- }
- if ic, ok := a.BridgeAPI.(idleChecker); ok {
- return ic.IsNetworkIdle(tabID)
- }
- return false, false
-}
-
-func (a *BridgeAdapter) SetFingerprintRotateActive(tabID string, active bool) {
- type setter interface {
- SetFingerprintRotateActive(string, bool)
- }
- if s, ok := a.BridgeAPI.(setter); ok {
- s.SetFingerprintRotateActive(tabID, active)
- }
-}
-
-func (a *BridgeAdapter) FingerprintRotateActive(tabID string) bool {
- type getter interface {
- FingerprintRotateActive(string) bool
- }
- g, ok := a.BridgeAPI.(getter)
- if !ok {
- return false
- }
- if g.FingerprintRotateActive(tabID) {
- return true
- }
- // The rotate handler stores the flag under the resolved Chrome tab ID,
- // but callers may query with the original lite tab ID.
- if chromeID, mapped := a.proxy.ChromeTabID(tabID); mapped {
- return g.FingerprintRotateActive(chromeID)
- }
- return false
-}
-
-func (a *BridgeAdapter) GetFrameScope(tabID string) (bridge.FrameScope, bool) {
- type frameScopeAPI interface {
- GetFrameScope(string) (bridge.FrameScope, bool)
- }
- if fs, ok := a.BridgeAPI.(frameScopeAPI); ok {
- return fs.GetFrameScope(tabID)
- }
- return bridge.FrameScope{}, false
-}
-
-func (a *BridgeAdapter) SetFrameScope(tabID string, scope bridge.FrameScope) {
- type frameScopeAPI interface {
- SetFrameScope(string, bridge.FrameScope)
- }
- if fs, ok := a.BridgeAPI.(frameScopeAPI); ok {
- fs.SetFrameScope(tabID, scope)
- }
-}
-
-func (a *BridgeAdapter) ClearFrameScope(tabID string) {
- type frameScopeAPI interface {
- ClearFrameScope(string)
- }
- if fs, ok := a.BridgeAPI.(frameScopeAPI); ok {
- fs.ClearFrameScope(tabID)
- }
-}
-
-func (a *BridgeAdapter) SetTabHandoff(tabID, reason string, timeout time.Duration) error {
- type handoffAPI interface {
- SetTabHandoff(string, string, time.Duration) error
- }
- if h, ok := a.BridgeAPI.(handoffAPI); ok {
- return h.SetTabHandoff(tabID, reason, timeout)
- }
- return fmt.Errorf("bridge does not support handoff state")
-}
-
-func (a *BridgeAdapter) ResumeTabHandoff(tabID string) error {
- type handoffAPI interface {
- ResumeTabHandoff(string) error
- }
- if h, ok := a.BridgeAPI.(handoffAPI); ok {
- return h.ResumeTabHandoff(tabID)
- }
- return fmt.Errorf("bridge does not support handoff state")
-}
-
-func (a *BridgeAdapter) TabHandoffState(tabID string) (bridge.TabHandoffState, bool) {
- type handoffAPI interface {
- TabHandoffState(string) (bridge.TabHandoffState, bool)
- }
- if h, ok := a.BridgeAPI.(handoffAPI); ok {
- return h.TabHandoffState(tabID)
- }
- return bridge.TabHandoffState{}, false
-}
-
-// navigateParamsToPolicy converts bridge.NavigateParams to a
-// staticfetch.NavigateNetworkPolicy so the static browser enforces the
-// same SSRF/redirect protections as the Chrome path.
-func navigateParamsToPolicy(p *bridge.NavigateParams) *staticfetch.NavigateNetworkPolicy {
- if p == nil {
- return nil
- }
-
- policy := &staticfetch.NavigateNetworkPolicy{
- AllowInternal: p.AllowInternal,
- MaxRedirects: p.MaxRedirects,
- }
-
- // []net.IPNet → []*net.IPNet
- if len(p.TrustedProxyCIDRs) > 0 {
- policy.TrustedProxyCIDRs = make([]*net.IPNet, len(p.TrustedProxyCIDRs))
- for i := range p.TrustedProxyCIDRs {
- policy.TrustedProxyCIDRs[i] = &p.TrustedProxyCIDRs[i]
- }
- }
-
- // []net.IP → []netip.Addr
- if len(p.TrustedResolvedIPs) > 0 {
- addrs := make([]netip.Addr, 0, len(p.TrustedResolvedIPs))
- for _, ip := range p.TrustedResolvedIPs {
- if addr, ok := netip.AddrFromSlice(ip); ok {
- addrs = append(addrs, addr.Unmap())
- }
- }
- policy.TrustedResolvedIP = addrs
- }
-
- return policy
-}
diff --git a/internal/browsers/ghostchrome/bridgekit/bridge_adapter_content.go b/internal/browsers/ghostchrome/bridgekit/bridge_adapter_content.go
new file mode 100644
index 00000000..87510cfb
--- /dev/null
+++ b/internal/browsers/ghostchrome/bridgekit/bridge_adapter_content.go
@@ -0,0 +1,312 @@
+package bridgekit
+
+import (
+ "context"
+ "fmt"
+ "log/slog"
+ "net"
+ "net/netip"
+ "strings"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/browserops"
+ "github.com/pinchtab/pinchtab/internal/browsers/ghostchrome"
+ "github.com/pinchtab/pinchtab/internal/browsers/ghostchrome/staticfetch"
+)
+
+// StaticFirstNavigate reports whether this bridge can attempt a navigate on
+// its static browser without Chrome. Handlers probe it to defer the Chrome
+// launch (NavigateParams.NoEscalate / SkipStatic two-phase protocol).
+func (a *BridgeAdapter) StaticFirstNavigate() bool {
+ return a.StaticBrowser() != nil
+}
+
+// escalateError builds the typed signal for NoEscalate mode, carrying the
+// static attempt's route metadata for the caller to merge.
+func staticEscalateError(quality int, reason string) *bridge.StaticEscalateError {
+ return &bridge.StaticEscalateError{
+ Quality: quality,
+ Reason: reason,
+ Route: staticAcceptedRoute(quality, reason, false),
+ }
+}
+
+// staticAcceptedRoute builds the RouteMetadata for a static attempt the
+// quality gate accepted (accepted=true) or rejected without a Chrome
+// fallthrough (accepted=false, used by staticEscalateError).
+func staticAcceptedRoute(quality int, reason string, accepted bool) *browserops.RouteMetadata {
+ return &browserops.RouteMetadata{
+ RequestedBrowser: "ghost-chrome",
+ UsedBrowser: "ghost-chrome",
+ Quality: quality,
+ Attempts: []browserops.RouteAttempt{
+ {Browser: "ghost-chrome", Accepted: accepted, Reason: reason},
+ },
+ }
+}
+
+// escalatedRoute builds the RouteMetadata for a static attempt that fell
+// through to Chrome.
+func escalatedRoute(quality int, reason string) *browserops.RouteMetadata {
+ return &browserops.RouteMetadata{
+ RequestedBrowser: "ghost-chrome",
+ UsedBrowser: "ghost-chrome",
+ Escalated: true,
+ Quality: quality,
+ Attempts: []browserops.RouteAttempt{
+ {Browser: "ghost-chrome", Accepted: false, Reason: reason},
+ {Browser: "chrome", Accepted: true, Reason: "escalated"},
+ },
+ }
+}
+
+// Navigate implements the ghost-chrome "static first, assess quality, escalate
+// to Chrome" routing pattern for navigation. It tries the static browser first;
+// if the fetched content passes the quality gate it returns immediately.
+// Otherwise it falls through to the Chrome bridge — or, in NoEscalate mode,
+// returns *bridge.StaticEscalateError so the handler can launch Chrome itself.
+func (a *BridgeAdapter) Navigate(ctx context.Context, url string, params bridge.NavigateParams) (*bridge.NavigateResult, error) {
+ if params.SkipStatic {
+ // The handler already ran the static phase and is escalating.
+ return a.BridgeAPI.Navigate(ctx, url, params)
+ }
+ // Concrete type needed: CloseTab is not part of browserops.BrowserRuntime.
+ staticBrowser := a.StaticBrowser()
+ if staticBrowser != nil {
+ // Attach network policy from NavigateParams so the static
+ // browser enforces SSRF/redirect protections.
+ ctx = staticfetch.WithNavigateNetworkPolicy(ctx, navigateParamsToPolicy(&params))
+ navResult, err := staticBrowser.Navigate(ctx, url)
+ if err == nil {
+ // Assess content quality by extracting text from the static page.
+ textResult, textErr := staticBrowser.Text(ctx, navResult.TabID)
+ if textErr == nil {
+ gr := ghostchrome.AssessContent(textResult.Text)
+ if gr.ShouldAccept() {
+ slog.Debug("ghost-chrome navigate: static accepted",
+ "url", url, "quality", gr.Quality)
+ return &bridge.NavigateResult{
+ TabID: navResult.TabID,
+ URL: navResult.URL,
+ Title: navResult.Title,
+ Route: staticAcceptedRoute(gr.Quality, gr.FormatReason(), true),
+ }, nil
+ }
+ // Quality too low — escalate to Chrome. The static tab was
+ // never exposed to the caller; release it.
+ slog.Debug("ghost-chrome navigate: quality too low, escalating",
+ "url", url, "quality", gr.Quality, "reason", gr.FormatReason())
+ staticBrowser.CloseTab(navResult.TabID)
+ if params.NoEscalate {
+ return nil, staticEscalateError(gr.Quality, gr.FormatReason())
+ }
+ chromeResult, chromeErr := a.BridgeAPI.Navigate(ctx, url, params)
+ if chromeErr != nil {
+ return nil, chromeErr
+ }
+ chromeResult.Route = escalatedRoute(gr.Quality, gr.FormatReason())
+ return chromeResult, nil
+ }
+ // Text extraction failed — escalate with zero quality. The static
+ // tab was never exposed to the caller; release it.
+ slog.Debug("ghost-chrome navigate: text extraction failed, escalating",
+ "url", url, "err", textErr)
+ staticBrowser.CloseTab(navResult.TabID)
+ if params.NoEscalate {
+ return nil, staticEscalateError(0, "text extraction failed: "+textErr.Error())
+ }
+ } else {
+ slog.Debug("ghost-chrome navigate: static navigate failed, escalating",
+ "url", url, "err", err)
+ if params.NoEscalate {
+ return nil, staticEscalateError(0, "static navigate failed: "+err.Error())
+ }
+ }
+ }
+ if params.NoEscalate {
+ return nil, staticEscalateError(0, "static browser unavailable")
+ }
+
+ // Static browser unavailable or failed — go straight to Chrome.
+ chromeResult, chromeErr := a.BridgeAPI.Navigate(ctx, url, params)
+ if chromeErr != nil {
+ return nil, chromeErr
+ }
+ chromeResult.Route = escalatedRoute(0, "static browser unavailable or failed")
+ return chromeResult, nil
+}
+
+// Snapshot implements the ghost-chrome "static first, assess quality, escalate
+// to Chrome" routing pattern for snapshots. It tries reading the accessibility
+// tree from the static browser; if the snapshot passes the quality gate it
+// converts the nodes to bridge.A11yNode and returns. Otherwise it falls
+// through to Chrome.
+func (a *BridgeAdapter) Snapshot(ctx context.Context, tabID string, filter string, params bridge.ContentParams) (*bridge.SnapshotResult, error) {
+ staticBrowser := a.proxy.StaticBrowser()
+ if staticBrowser != nil {
+ snapResult, err := staticBrowser.Snapshot(ctx, tabID, filter)
+ if err == nil && len(snapResult.Nodes) > 0 {
+ // Convert to ghostchrome.SnapshotNode for quality assessment.
+ assessNodes := make([]ghostchrome.SnapshotNode, len(snapResult.Nodes))
+ for i, n := range snapResult.Nodes {
+ assessNodes[i] = ghostchrome.SnapshotNode{Role: n.Role, Name: n.Name}
+ }
+ if ghostchrome.AssessSnapshot(assessNodes) {
+ // Convert browserops.SnapshotNode → bridge.A11yNode.
+ flat := make([]bridge.A11yNode, len(snapResult.Nodes))
+ refs := make(map[string]int64, len(snapResult.Nodes))
+ targets := make(map[string]bridge.RefTarget, len(snapResult.Nodes))
+ for i, n := range snapResult.Nodes {
+ flat[i] = bridge.A11yNode{
+ Ref: n.Ref,
+ Role: n.Role,
+ Name: n.Name,
+ Tag: n.Tag,
+ Value: n.Value,
+ Depth: n.Depth,
+ }
+ if n.Ref != "" {
+ refs[n.Ref] = 0
+ targets[n.Ref] = bridge.RefTarget{}
+ }
+ }
+
+ // IDPI: scan snapshot node names/values when ContentGuard is set.
+ var idpiWarning string
+ if params.ContentGuard != nil {
+ var sb strings.Builder
+ for _, n := range flat {
+ if n.Name != "" || n.Value != "" {
+ sb.WriteString(n.Name)
+ if n.Name != "" && n.Value != "" {
+ sb.WriteByte(' ')
+ }
+ sb.WriteString(n.Value)
+ sb.WriteByte('\n')
+ }
+ }
+ scanResult := params.ContentGuard.ScanOnly(sb.String())
+ if scanResult.Blocked {
+ return nil, fmt.Errorf("snapshot blocked by IDPI scanner: %s", scanResult.BlockReason)
+ }
+ if scanResult.Warning != "" {
+ idpiWarning = scanResult.Warning
+ }
+ }
+
+ slog.Debug("ghost-chrome snapshot: static accepted",
+ "tabID", tabID, "nodes", len(flat))
+ return &bridge.SnapshotResult{
+ Nodes: flat,
+ Refs: refs,
+ Targets: targets,
+ IDPIWarning: idpiWarning,
+ Route: staticAcceptedRoute(0, "", true),
+ }, nil
+ }
+ // Quality too low — fall through to Chrome.
+ slog.Debug("ghost-chrome snapshot: quality too low, escalating", "tabID", tabID)
+ }
+ }
+
+ // Escalate to Chrome. Resolve the tab ID for escalated tabs.
+ resolvedTabID := tabID
+ if chromeID, ok := a.proxy.ChromeTabID(tabID); ok {
+ resolvedTabID = chromeID
+ }
+ chromeSnap, err := a.BridgeAPI.Snapshot(ctx, resolvedTabID, filter, params)
+ if err != nil {
+ return nil, err
+ }
+ chromeSnap.Route = escalatedRoute(0, "quality too low or static unavailable")
+ return chromeSnap, nil
+}
+
+// Text implements the ghost-chrome "static first, assess quality, escalate to
+// Chrome" routing pattern for text extraction. It tries the static browser
+// first; if the text passes the quality gate it returns immediately. Otherwise
+// it falls through to Chrome.
+func (a *BridgeAdapter) Text(ctx context.Context, tabID string, params bridge.ContentParams) (*bridge.TextResult, error) {
+ staticBrowser := a.proxy.StaticBrowser()
+ if staticBrowser != nil {
+ textResult, err := staticBrowser.Text(ctx, tabID)
+ if err == nil && textResult.Text != "" {
+ gr := ghostchrome.AssessContent(textResult.Text)
+ if gr.ShouldAccept() {
+ // IDPI: scan extracted text when ContentGuard is set.
+ text := textResult.Text
+ var idpiWarning string
+ if params.ContentGuard != nil {
+ scanResult := params.ContentGuard.Scan(text, textResult.URL)
+ if scanResult.Blocked {
+ return nil, fmt.Errorf("content blocked by IDPI scanner: %s", scanResult.BlockReason)
+ }
+ text = scanResult.Text
+ if scanResult.Warning != "" {
+ idpiWarning = scanResult.Warning
+ }
+ }
+
+ slog.Debug("ghost-chrome text: static accepted",
+ "tabID", tabID, "quality", gr.Quality)
+ return &bridge.TextResult{
+ Text: text,
+ URL: textResult.URL,
+ Title: textResult.Title,
+ IDPIWarning: idpiWarning,
+ Route: staticAcceptedRoute(gr.Quality, gr.FormatReason(), true),
+ }, nil
+ }
+ // Quality too low — fall through to Chrome.
+ slog.Debug("ghost-chrome text: quality too low, escalating",
+ "tabID", tabID, "quality", gr.Quality, "reason", gr.FormatReason())
+ }
+ }
+
+ // Escalate to Chrome. Resolve the tab ID for escalated tabs.
+ resolvedTabID := tabID
+ if chromeID, ok := a.proxy.ChromeTabID(tabID); ok {
+ resolvedTabID = chromeID
+ }
+ chromeText, err := a.BridgeAPI.Text(ctx, resolvedTabID, params)
+ if err != nil {
+ return nil, err
+ }
+ chromeText.Route = escalatedRoute(0, "quality too low or static unavailable")
+ return chromeText, nil
+}
+
+// navigateParamsToPolicy converts bridge.NavigateParams to a
+// staticfetch.NavigateNetworkPolicy so the static browser enforces the
+// same SSRF/redirect protections as the Chrome path.
+func navigateParamsToPolicy(p *bridge.NavigateParams) *staticfetch.NavigateNetworkPolicy {
+ if p == nil {
+ return nil
+ }
+
+ policy := &staticfetch.NavigateNetworkPolicy{
+ AllowInternal: p.AllowInternal,
+ MaxRedirects: p.MaxRedirects,
+ }
+
+ // []net.IPNet → []*net.IPNet
+ if len(p.TrustedProxyCIDRs) > 0 {
+ policy.TrustedProxyCIDRs = make([]*net.IPNet, len(p.TrustedProxyCIDRs))
+ for i := range p.TrustedProxyCIDRs {
+ policy.TrustedProxyCIDRs[i] = &p.TrustedProxyCIDRs[i]
+ }
+ }
+
+ // []net.IP → []netip.Addr
+ if len(p.TrustedResolvedIPs) > 0 {
+ addrs := make([]netip.Addr, 0, len(p.TrustedResolvedIPs))
+ for _, ip := range p.TrustedResolvedIPs {
+ if addr, ok := netip.AddrFromSlice(ip); ok {
+ addrs = append(addrs, addr.Unmap())
+ }
+ }
+ policy.TrustedResolvedIP = addrs
+ }
+
+ return policy
+}
diff --git a/internal/browsers/ghostchrome/bridgekit/bridge_adapter_passthrough.go b/internal/browsers/ghostchrome/bridgekit/bridge_adapter_passthrough.go
new file mode 100644
index 00000000..0b962816
--- /dev/null
+++ b/internal/browsers/ghostchrome/bridgekit/bridge_adapter_passthrough.go
@@ -0,0 +1,141 @@
+package bridgekit
+
+import (
+ "fmt"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+)
+
+func (a *BridgeAdapter) FocusTab(tabID string) error {
+ if chromeID, ok := a.proxy.ChromeTabID(tabID); ok {
+ return a.BridgeAPI.FocusTab(chromeID)
+ }
+ return a.BridgeAPI.FocusTab(tabID)
+}
+
+func (a *BridgeAdapter) CloseTab(tabID string) error {
+ if chromeID, ok := a.proxy.ChromeTabID(tabID); ok {
+ err := a.BridgeAPI.CloseTab(chromeID)
+ // Scrub the mapping even if the Chrome close errored — the caller
+ // asked for the tab to be gone; a stale mapping would resurrect it
+ // on the next TabContext.
+ a.proxy.ReleaseTab(tabID)
+ return err
+ }
+ if sb := a.StaticBrowser(); sb != nil && sb.CloseTab(tabID) {
+ a.proxy.ReleaseTab(tabID)
+ return nil
+ }
+ return a.BridgeAPI.CloseTab(tabID)
+}
+
+func (a *BridgeAdapter) AvailableActions() []string {
+ return a.proxy.AvailableActions()
+}
+
+func (a *BridgeAdapter) GetDocumentReadyState(tabID string) (string, error) {
+ type readyStater interface {
+ GetDocumentReadyState(string) (string, error)
+ }
+ if rs, ok := a.BridgeAPI.(readyStater); ok {
+ return rs.GetDocumentReadyState(tabID)
+ }
+ return "", nil
+}
+
+func (a *BridgeAdapter) IsNetworkIdle(tabID string) (bool, bool) {
+ type idleChecker interface {
+ IsNetworkIdle(string) (bool, bool)
+ }
+ if ic, ok := a.BridgeAPI.(idleChecker); ok {
+ return ic.IsNetworkIdle(tabID)
+ }
+ return false, false
+}
+
+func (a *BridgeAdapter) SetFingerprintRotateActive(tabID string, active bool) {
+ type setter interface {
+ SetFingerprintRotateActive(string, bool)
+ }
+ if s, ok := a.BridgeAPI.(setter); ok {
+ s.SetFingerprintRotateActive(tabID, active)
+ }
+}
+
+func (a *BridgeAdapter) FingerprintRotateActive(tabID string) bool {
+ type getter interface {
+ FingerprintRotateActive(string) bool
+ }
+ g, ok := a.BridgeAPI.(getter)
+ if !ok {
+ return false
+ }
+ if g.FingerprintRotateActive(tabID) {
+ return true
+ }
+ // The rotate handler stores the flag under the resolved Chrome tab ID,
+ // but callers may query with the original lite tab ID.
+ if chromeID, mapped := a.proxy.ChromeTabID(tabID); mapped {
+ return g.FingerprintRotateActive(chromeID)
+ }
+ return false
+}
+
+func (a *BridgeAdapter) GetFrameScope(tabID string) (bridge.FrameScope, bool) {
+ type frameScopeAPI interface {
+ GetFrameScope(string) (bridge.FrameScope, bool)
+ }
+ if fs, ok := a.BridgeAPI.(frameScopeAPI); ok {
+ return fs.GetFrameScope(tabID)
+ }
+ return bridge.FrameScope{}, false
+}
+
+func (a *BridgeAdapter) SetFrameScope(tabID string, scope bridge.FrameScope) {
+ type frameScopeAPI interface {
+ SetFrameScope(string, bridge.FrameScope)
+ }
+ if fs, ok := a.BridgeAPI.(frameScopeAPI); ok {
+ fs.SetFrameScope(tabID, scope)
+ }
+}
+
+func (a *BridgeAdapter) ClearFrameScope(tabID string) {
+ type frameScopeAPI interface {
+ ClearFrameScope(string)
+ }
+ if fs, ok := a.BridgeAPI.(frameScopeAPI); ok {
+ fs.ClearFrameScope(tabID)
+ }
+}
+
+func (a *BridgeAdapter) SetTabHandoff(tabID, reason string, timeout time.Duration) error {
+ type handoffAPI interface {
+ SetTabHandoff(string, string, time.Duration) error
+ }
+ if h, ok := a.BridgeAPI.(handoffAPI); ok {
+ return h.SetTabHandoff(tabID, reason, timeout)
+ }
+ return fmt.Errorf("bridge does not support handoff state")
+}
+
+func (a *BridgeAdapter) ResumeTabHandoff(tabID string) error {
+ type handoffAPI interface {
+ ResumeTabHandoff(string) error
+ }
+ if h, ok := a.BridgeAPI.(handoffAPI); ok {
+ return h.ResumeTabHandoff(tabID)
+ }
+ return fmt.Errorf("bridge does not support handoff state")
+}
+
+func (a *BridgeAdapter) TabHandoffState(tabID string) (bridge.TabHandoffState, bool) {
+ type handoffAPI interface {
+ TabHandoffState(string) (bridge.TabHandoffState, bool)
+ }
+ if h, ok := a.BridgeAPI.(handoffAPI); ok {
+ return h.TabHandoffState(tabID)
+ }
+ return bridge.TabHandoffState{}, false
+}
diff --git a/internal/browsers/ghostchrome/bridgekit/bridge_adapter_refmap.go b/internal/browsers/ghostchrome/bridgekit/bridge_adapter_refmap.go
new file mode 100644
index 00000000..e478fb4a
--- /dev/null
+++ b/internal/browsers/ghostchrome/bridgekit/bridge_adapter_refmap.go
@@ -0,0 +1,94 @@
+package bridgekit
+
+import (
+ "context"
+ "log/slog"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+)
+
+// populateEscalatedRefCache builds a ref cache for a newly escalated Chrome
+// tab that maps the STATIC browser's ref names to Chrome's BackendNodeIDs.
+// This is necessary because Chrome and the static browser assign different
+// sequential ref numbers (e0, e1, ...) to the same page elements. We match
+// by (role, name) to bridge the two numbering schemes.
+func (a *BridgeAdapter) populateEscalatedRefCache(ctx context.Context, chromeTabID, liteTabID string) {
+ if a.BridgeAPI.GetRefCache(chromeTabID) != nil {
+ return
+ }
+
+ staticBrowser := a.proxy.StaticBrowser()
+ if staticBrowser == nil {
+ return
+ }
+ staticSnap, err := staticBrowser.Snapshot(ctx, liteTabID, "interactive")
+ if err != nil || len(staticSnap.Nodes) == 0 {
+ // Routine for non-lite ID aliasing; for real escalations a missing
+ // ref cache surfaces later as "ref not found" — leave a trail.
+ slog.Debug("escalated ref cache: static snapshot unavailable", "liteTab", liteTabID, "chromeTab", chromeTabID, "err", err)
+ return
+ }
+
+ chromeNodes, err := bridge.FetchAXTree(ctx)
+ if err != nil {
+ slog.Debug("escalated ref cache: chrome AX tree fetch failed", "liteTab", liteTabID, "chromeTab", chromeTabID, "err", err)
+ return
+ }
+ flat, _ := bridge.BuildSnapshot(chromeNodes, bridge.FilterInteractive, -1)
+ _ = bridge.EnrichA11yNodesWithDOMMetadata(ctx, flat)
+
+ type chromeEntry struct {
+ node bridge.A11yNode
+ used bool
+ }
+ chromeByKey := map[string][]*chromeEntry{}
+ for i := range flat {
+ key := flat[i].Role + "\x00" + flat[i].Name
+ chromeByKey[key] = append(chromeByKey[key], &chromeEntry{node: flat[i]})
+ }
+
+ refs := make(map[string]int64, len(staticSnap.Nodes))
+ targets := make(map[string]bridge.RefTarget, len(staticSnap.Nodes))
+ for _, sn := range staticSnap.Nodes {
+ if sn.Ref == "" {
+ continue
+ }
+ key := sn.Role + "\x00" + sn.Name
+ for _, entry := range chromeByKey[key] {
+ if !entry.used && entry.node.NodeID != 0 {
+ entry.used = true
+ refs[sn.Ref] = entry.node.NodeID
+ targets[sn.Ref] = bridge.RefTarget{
+ BackendNodeID: entry.node.NodeID,
+ FrameID: entry.node.FrameID,
+ FrameURL: entry.node.FrameURL,
+ FrameName: entry.node.FrameName,
+ ChildFrameID: entry.node.ChildFrameID,
+ ChildFrameURL: entry.node.ChildFrameURL,
+ ChildFrameName: entry.node.ChildFrameName,
+ }
+ break
+ }
+ }
+ }
+
+ slog.Debug("populated escalated ref cache",
+ "chromeTab", chromeTabID, "liteTab", liteTabID,
+ "staticRefs", len(staticSnap.Nodes), "mapped", len(refs))
+
+ a.SetRefCache(chromeTabID, &bridge.RefCache{
+ Refs: refs,
+ Targets: targets,
+ Nodes: flat,
+ })
+}
+
+func (a *BridgeAdapter) GetRefCache(tabID string) *bridge.RefCache {
+ if cache := a.BridgeAPI.GetRefCache(tabID); cache != nil {
+ return cache
+ }
+ if chromeID, ok := a.proxy.ChromeTabID(tabID); ok {
+ return a.BridgeAPI.GetRefCache(chromeID)
+ }
+ return nil
+}
diff --git a/internal/browsers/ghostchrome/bridgekit/bridge_adapter_test.go b/internal/browsers/ghostchrome/bridgekit/bridge_adapter_test.go
index 733addc2..e48599fa 100644
--- a/internal/browsers/ghostchrome/bridgekit/bridge_adapter_test.go
+++ b/internal/browsers/ghostchrome/bridgekit/bridge_adapter_test.go
@@ -2,6 +2,7 @@ package bridgekit
import (
"context"
+ "errors"
"fmt"
"net"
"net/http"
@@ -184,6 +185,9 @@ func TestAdapterNavigate_StaticAccepted(t *testing.T) {
if result.Route.Escalated {
t.Error("should not be escalated")
}
+ if _, ok := lite.TabURL(result.TabID); !ok {
+ t.Error("accepted static tab must stay alive — it is the response tab")
+ }
}
func TestAdapterNavigate_ThinContentEscalates(t *testing.T) {
@@ -223,6 +227,11 @@ func TestAdapterNavigate_ThinContentEscalates(t *testing.T) {
if len(result.Route.Attempts) < 2 {
t.Errorf("expected at least 2 attempts, got %d", len(result.Route.Attempts))
}
+ // The rejected static tab (first navigate → lite-1) was never exposed to
+ // the caller and must be released on escalation.
+ if _, ok := lite.TabURL("lite-1"); ok {
+ t.Error("escalation should close the rejected static tab")
+ }
}
func TestAdapterNavigate_StaticUnavailableEscalates(t *testing.T) {
@@ -799,3 +808,217 @@ func TestStaticSnapshotIDPIWarning(t *testing.T) {
t.Errorf("Warning = %q, want %q", result.Warning, "suspicious pattern in snapshot")
}
}
+
+// ---------- escalation lifecycle tests ----------
+
+// escalatingChromeBridge fails TabContext for unknown IDs, forcing the proxy
+// down the lite-escalation path; CreateTab registers the new Chrome tab.
+type escalatingChromeBridge struct {
+ knownTabs map[string]bool
+ actionCalled bool
+}
+
+func (m *escalatingChromeBridge) TabContext(tabID string) (context.Context, string, error) {
+ if m.knownTabs[tabID] {
+ return context.Background(), tabID, nil
+ }
+ return nil, "", fmt.Errorf("tab not found: %s", tabID)
+}
+
+func (m *escalatingChromeBridge) CreateTab(string) (string, context.Context, context.CancelFunc, error) {
+ if m.knownTabs == nil {
+ m.knownTabs = map[string]bool{}
+ }
+ m.knownTabs["chrome-tab"] = true
+ return "chrome-tab", context.Background(), func() {}, nil
+}
+
+func (m *escalatingChromeBridge) ExecuteAction(context.Context, string, ghostchrome.ActionRequest) (map[string]any, error) {
+ m.actionCalled = true
+ return map[string]any{"success": true}, nil
+}
+
+func (m *escalatingChromeBridge) AvailableActions() []string { return nil }
+
+// escalatingChromeAPI satisfies the bridge.BridgeAPI surface the adapter
+// touches during escalation, CloseTab, and action fallback.
+type escalatingChromeAPI struct {
+ bridge.BridgeAPI // nil — panics on unimplemented methods
+ esc *escalatingChromeBridge
+ closedTabs []string
+}
+
+func (c *escalatingChromeAPI) GetRefCache(string) *bridge.RefCache { return nil }
+func (c *escalatingChromeAPI) SetRefCache(string, *bridge.RefCache) {}
+
+func (c *escalatingChromeAPI) CloseTab(tabID string) error {
+ c.closedTabs = append(c.closedTabs, tabID)
+ delete(c.esc.knownTabs, tabID)
+ return nil
+}
+
+func (c *escalatingChromeAPI) ExecuteAction(ctx context.Context, kind string, req bridge.ActionRequest) (map[string]any, error) {
+ return c.esc.ExecuteAction(ctx, kind, ghostchrome.ActionRequest{})
+}
+
+func newEscalatingAdapter(t *testing.T, lite *staticfetch.Browser) (*BridgeAdapter, *escalatingChromeBridge, *escalatingChromeAPI) {
+ t.Helper()
+ esc := &escalatingChromeBridge{}
+ api := &escalatingChromeAPI{esc: esc}
+ proxy := ghostchrome.NewBridgeProxy(esc, lite, func() error { return nil })
+ return &BridgeAdapter{BridgeAPI: api, proxy: proxy}, esc, api
+}
+
+func TestAdapterTabContext_EscalationRetiresStaticTab(t *testing.T) {
+ ts := newRichTestServer()
+ defer ts.Close()
+
+ lite := staticfetch.NewBrowser()
+ defer func() { _ = lite.Close() }()
+ adapter, esc, _ := newEscalatingAdapter(t, lite)
+
+ res, err := lite.Navigate(context.Background(), ts.URL)
+ if err != nil {
+ t.Fatalf("static Navigate: %v", err)
+ }
+
+ _, resolvedID, err := adapter.TabContext(res.TabID)
+ if err != nil {
+ t.Fatalf("TabContext: %v", err)
+ }
+ if resolvedID != "chrome-tab" {
+ t.Fatalf("resolvedID = %q, want chrome-tab", resolvedID)
+ }
+ if _, ok := lite.TabURL(res.TabID); ok {
+ t.Fatal("escalated lite tab must be retired from the static browser")
+ }
+
+ // Post-escalation actions must hit Chrome, not the dead static DOM.
+ out, err := adapter.ExecuteAction(context.Background(), ghostchrome.ActionClick, bridge.ActionRequest{
+ TabID: res.TabID, Ref: "e1",
+ })
+ if err != nil {
+ t.Fatalf("ExecuteAction: %v", err)
+ }
+ if !esc.actionCalled {
+ t.Fatal("action should route to Chrome after escalation")
+ }
+ if clicked, ok := out["clicked"]; ok && clicked == true {
+ t.Fatal("action was served by the static DOM after escalation")
+ }
+}
+
+func TestAdapterCloseTab_EscalatedTab_NoResurrection(t *testing.T) {
+ ts := newRichTestServer()
+ defer ts.Close()
+
+ lite := staticfetch.NewBrowser()
+ defer func() { _ = lite.Close() }()
+ adapter, _, api := newEscalatingAdapter(t, lite)
+
+ res, err := lite.Navigate(context.Background(), ts.URL)
+ if err != nil {
+ t.Fatalf("static Navigate: %v", err)
+ }
+ if _, _, err := adapter.TabContext(res.TabID); err != nil {
+ t.Fatalf("TabContext (escalate): %v", err)
+ }
+
+ if err := adapter.CloseTab(res.TabID); err != nil {
+ t.Fatalf("CloseTab: %v", err)
+ }
+ if len(api.closedTabs) != 1 || api.closedTabs[0] != "chrome-tab" {
+ t.Fatalf("closedTabs = %v, want [chrome-tab]", api.closedTabs)
+ }
+
+ // The closed tab must stay closed: no re-escalation from stale state.
+ if _, _, err := adapter.TabContext(res.TabID); err == nil {
+ t.Fatal("closed escalated tab resurrected via stale mapping")
+ }
+}
+
+func TestAdapterCloseTab_UnescalatedLiteTab_NoChromeInvolved(t *testing.T) {
+ ts := newRichTestServer()
+ defer ts.Close()
+
+ lite := staticfetch.NewBrowser()
+ defer func() { _ = lite.Close() }()
+ adapter, _, api := newEscalatingAdapter(t, lite)
+
+ res, err := lite.Navigate(context.Background(), ts.URL)
+ if err != nil {
+ t.Fatalf("static Navigate: %v", err)
+ }
+
+ if err := adapter.CloseTab(res.TabID); err != nil {
+ t.Fatalf("CloseTab: %v", err)
+ }
+ if _, ok := lite.TabURL(res.TabID); ok {
+ t.Fatal("lite tab should be gone after CloseTab")
+ }
+ if len(api.closedTabs) != 0 {
+ t.Fatalf("Chrome CloseTab should not be called for unescalated lite tabs, got %v", api.closedTabs)
+ }
+}
+
+// H1b: NoEscalate returns the typed escalation signal instead of internally
+// falling through to Chrome, and releases the rejected static tab.
+func TestAdapterNavigate_NoEscalateReturnsTypedError(t *testing.T) {
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "text/html")
+ _, _ = w.Write([]byte(`<html><body>tiny</body></html>`))
+ }))
+ defer ts.Close()
+
+ lite := staticfetch.NewBrowser()
+ defer func() { _ = lite.Close() }()
+ mock := &mockChromeBridge{}
+ adapter := newTestAdapter(t, lite, mock)
+
+ _, err := adapter.Navigate(context.Background(), ts.URL, bridge.NavigateParams{
+ AllowInternal: true,
+ MaxRedirects: -1,
+ NoEscalate: true,
+ })
+ var esc *bridge.StaticEscalateError
+ if !errors.As(err, &esc) {
+ t.Fatalf("expected StaticEscalateError, got %v", err)
+ }
+ if esc.Route == nil || len(esc.Route.Attempts) != 1 || esc.Route.Attempts[0].Accepted {
+ t.Fatalf("escalation route should carry the rejected static attempt, got %+v", esc.Route)
+ }
+ if mock.navigateCalled {
+ t.Fatal("NoEscalate must not fall through to Chrome")
+ }
+ if _, ok := lite.TabURL("lite-1"); ok {
+ t.Fatal("rejected static tab must be released in NoEscalate mode")
+ }
+}
+
+// H1b: SkipStatic bypasses the static fetch entirely (the handler already
+// ran it) and goes straight to Chrome.
+func TestAdapterNavigate_SkipStaticGoesStraightToChrome(t *testing.T) {
+ ts := newRichTestServer() // would static-accept if the fetch ran
+ defer ts.Close()
+
+ lite := staticfetch.NewBrowser()
+ defer func() { _ = lite.Close() }()
+ mock := &mockChromeBridge{
+ navigateResult: &bridge.NavigateResult{URL: ts.URL, Title: "Chrome"},
+ }
+ adapter := newTestAdapter(t, lite, mock)
+
+ if _, err := adapter.Navigate(context.Background(), ts.URL, bridge.NavigateParams{
+ AllowInternal: true,
+ MaxRedirects: -1,
+ SkipStatic: true,
+ }); err != nil {
+ t.Fatalf("Navigate: %v", err)
+ }
+ if !mock.navigateCalled {
+ t.Fatal("SkipStatic should delegate to Chrome")
+ }
+ if _, ok := lite.TabURL("lite-1"); ok {
+ t.Fatal("SkipStatic must not run the static fetch")
+ }
+}
diff --git a/internal/browsers/ghostchrome/ghostchrome.go b/internal/browsers/ghostchrome/ghostchrome.go
index 881c77ae..880aae58 100644
--- a/internal/browsers/ghostchrome/ghostchrome.go
+++ b/internal/browsers/ghostchrome/ghostchrome.go
@@ -1,6 +1,8 @@
-// Package ghostchrome registers a Ghost+Chrome stub browser provider.
-// It delegates capability and discovery queries to the Chrome base but
-// refuses to launch, serving as a placeholder for future implementation.
+// Package ghostchrome registers the ghost-chrome browser provider: a
+// static-first browser that serves reads from a lightweight gost-dom fetcher
+// and escalates to Chrome when a page needs rendering. Launch args, binary
+// discovery, and capability queries delegate to the Chrome base; the
+// static-first routing lives in the bridgekit sub-package.
package ghostchrome
import (
diff --git a/internal/browsers/ghostchrome/staticfetch/staticfetch.go b/internal/browsers/ghostchrome/staticfetch/staticfetch.go
index 3aad2114..27936d01 100644
--- a/internal/browsers/ghostchrome/staticfetch/staticfetch.go
+++ b/internal/browsers/ghostchrome/staticfetch/staticfetch.go
@@ -244,6 +244,26 @@ func (l *Browser) TabURL(tabID string) (string, bool) {
return tab.url, true
}
+// CloseTab releases a single tab's window and bookkeeping. Unknown IDs are a
+// no-op so callers can close defensively; reports whether a tab was removed.
+func (l *Browser) CloseTab(tabID string) bool {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+
+ tab := l.tabs[tabID]
+ if tab == nil {
+ return false
+ }
+ if tab.window != nil {
+ tab.window.Close()
+ }
+ delete(l.tabs, tabID)
+ if l.current == tabID {
+ l.current = ""
+ }
+ return true
+}
+
// Close shuts down the static browser and releases resources.
func (l *Browser) Close() error {
l.mu.Lock()
@@ -497,6 +517,15 @@ func stripScripts(r io.Reader) (io.Reader, error) {
continue
}
buf.Write(z.Raw())
+ case nethtml.SelfClosingTagToken:
+ // `<script src="x"/>`: browsers don't honor self-closing script,
+ // but gost-dom's reader may — skip it so no script element can
+ // reach the JS-less DOM.
+ tn, _ := z.TagName()
+ if string(tn) == "script" {
+ continue
+ }
+ buf.Write(z.Raw())
default:
if !inScript {
buf.Write(z.Raw())
diff --git a/internal/browsers/ghostchrome/staticfetch/staticfetch_test.go b/internal/browsers/ghostchrome/staticfetch/staticfetch_test.go
index 944b317f..131603ff 100644
--- a/internal/browsers/ghostchrome/staticfetch/staticfetch_test.go
+++ b/internal/browsers/ghostchrome/staticfetch/staticfetch_test.go
@@ -419,3 +419,58 @@ func TestNormalizeWhitespace(t *testing.T) {
}
}
}
+
+func TestStaticBrowser_CloseTab(t *testing.T) {
+ ts := newTestServer(testPage)
+ defer ts.Close()
+
+ lite := NewBrowser()
+ defer func() { _ = lite.Close() }()
+
+ res, err := lite.Navigate(context.Background(), ts.URL)
+ if err != nil {
+ t.Fatalf("Navigate: %v", err)
+ }
+
+ if !lite.CloseTab(res.TabID) {
+ t.Fatal("CloseTab should report removal of an existing tab")
+ }
+ if _, ok := lite.TabURL(res.TabID); ok {
+ t.Fatal("tab should be gone after CloseTab")
+ }
+ if lite.CloseTab(res.TabID) {
+ t.Fatal("CloseTab should be a no-op for already-closed tabs")
+ }
+
+ // Closing the current tab clears the current pointer.
+ if _, err := lite.Text(context.Background(), ""); err == nil {
+ t.Fatal("expected error reading current tab after it was closed")
+ }
+}
+
+// L5 regression: self-closing script tags previously fell through the
+// tokenizer's default branch and reached gost-dom (no JS runtime).
+func TestStaticBrowser_SelfClosingScriptStripped(t *testing.T) {
+ page := `<!DOCTYPE html><html><head><title>SC</title><script src="/x.js"/></head>` +
+ `<body><p>visible content</p><br/></body></html>`
+ ts := newTestServer(page)
+ defer ts.Close()
+
+ lite := NewBrowser()
+ defer func() { _ = lite.Close() }()
+
+ res, err := lite.Navigate(context.Background(), ts.URL)
+ if err != nil {
+ t.Fatalf("Navigate with self-closing script: %v", err)
+ }
+ text, err := lite.Text(context.Background(), res.TabID)
+ if err != nil {
+ t.Fatalf("Text: %v", err)
+ }
+ if !strings.Contains(text.Text, "visible content") {
+ t.Fatalf("benign content (incl. after <br/>) should survive stripping, got %q", text.Text)
+ }
+ if strings.Contains(text.Text, "x.js") {
+ t.Fatalf("script content leaked into text: %q", text.Text)
+ }
+}
diff --git a/internal/browsers/providerhooks/hooks.go b/internal/browsers/providerhooks/hooks.go
index d962125f..13fc7a91 100644
--- a/internal/browsers/providerhooks/hooks.go
+++ b/internal/browsers/providerhooks/hooks.go
@@ -60,3 +60,22 @@ func Shutdown(browserID string) {
}
hooks.Shutdown()
}
+
+// ShutdownAll runs every registered provider's shutdown cleanup. Used at
+// signal time so no provider's browser processes can be orphaned regardless
+// of which browser is the configured default. Hooks are copied out under the
+// lock and invoked outside it; they must be idempotent (the built-in ones are
+// process sweeps).
+func ShutdownAll() {
+ mu.RLock()
+ fns := make([]func(), 0, len(registry))
+ for _, hooks := range registry {
+ if hooks.Shutdown != nil {
+ fns = append(fns, hooks.Shutdown)
+ }
+ }
+ mu.RUnlock()
+ for _, fn := range fns {
+ fn()
+ }
+}
diff --git a/internal/browsers/providerhooks/hooks_test.go b/internal/browsers/providerhooks/hooks_test.go
new file mode 100644
index 00000000..359f7d96
--- /dev/null
+++ b/internal/browsers/providerhooks/hooks_test.go
@@ -0,0 +1,29 @@
+package providerhooks
+
+import "testing"
+
+// ShutdownAll must invoke every registered provider's shutdown hook so no
+// provider's browsers survive a signal-time sweep (M4).
+func TestShutdownAllInvokesEveryRegisteredHook(t *testing.T) {
+ mu.Lock()
+ saved := registry
+ registry = map[string]Hooks{}
+ mu.Unlock()
+ t.Cleanup(func() {
+ mu.Lock()
+ registry = saved
+ mu.Unlock()
+ })
+
+ called := map[string]int{}
+ Register("alpha", Hooks{Shutdown: func() { called["alpha"]++ }})
+ Register("beta", Hooks{Shutdown: func() { called["beta"]++ }})
+ Register("no-shutdown-hook", Hooks{})
+
+ ShutdownAll()
+ ShutdownAll() // hooks are documented idempotent; calling twice must be safe
+
+ if called["alpha"] != 2 || called["beta"] != 2 {
+ t.Fatalf("expected both hooks called twice, got %v", called)
+ }
+}
diff --git a/internal/browsers/runtime.go b/internal/browsers/runtime.go
index 6ae0980e..023acad0 100644
--- a/internal/browsers/runtime.go
+++ b/internal/browsers/runtime.go
@@ -152,12 +152,9 @@ type PDFParams struct {
// RuntimeInstance defines post-launch browser operations. Each browser
// provider (chrome, cloak, ghost-chrome) implements this interface to
// own its runtime behavior. The Bridge delegates operations to the
-// active RuntimeInstance.
-//
-// Future implementations:
-//
-// var _ RuntimeInstance = (*chrome.Instance)(nil)
-// var _ RuntimeInstance = (*cloak.Instance)(nil)
+// active RuntimeInstance. Implementations live in the provider
+// sub-packages (chrome.Instance, cloak.Instance, ghostchrome.Instance);
+// compile-time assertions can't live here without inverting the imports.
type RuntimeInstance interface {
// Visual capture
CaptureScreenshot(ctx context.Context, format string, quality int, clip *cdptk.ScreenshotClip) ([]byte, error)
diff --git a/internal/browsers/runtimekit/runtimekit.go b/internal/browsers/runtimekit/runtimekit.go
index 5201ba96..6ec27098 100644
--- a/internal/browsers/runtimekit/runtimekit.go
+++ b/internal/browsers/runtimekit/runtimekit.go
@@ -1,6 +1,8 @@
package runtimekit
import (
+ "log/slog"
+ "os"
goruntime "runtime"
"strings"
@@ -92,18 +94,25 @@ func FindBrowserBinary(browserID string) string {
}
func BaseFlagArgs(browserID string, headless bool) []string {
- args, _, _ := browsers.MustGet(browserID).BuildLaunchArgs(browsers.LaunchConfig{Headless: headless})
+ args, _, err := browsers.MustGet(browserID).BuildLaunchArgs(browsers.LaunchConfig{Headless: headless})
+ if err != nil {
+ slog.Warn("base flag args build failed", "browser", browserID, "err", err)
+ }
return args
}
+// CloakBrowserFlagArgs extracts the --fingerprint* flags for the configured
+// cloak settings. Only fingerprint flags survive the filter below, so the
+// sandbox decision feeding BuildLaunchArgs never reaches the output.
func CloakBrowserFlagArgs(cfg *config.RuntimeConfig) []string {
if cfg == nil || !config.IsCloakBrowser(cfg.DefaultBrowser) {
return nil
}
args, _, err := browsers.MustGet(config.BrowserCloak).BuildLaunchArgs(
- LaunchConfigFromRuntime(cfg, "", 0, ChromeNeedsNoSandbox(goruntime.GOOS, 0, false)),
+ LaunchConfigFromRuntime(cfg, "", 0, ChromeNeedsNoSandbox(goruntime.GOOS, os.Geteuid(), false)),
)
if err != nil {
+ slog.Warn("cloak fingerprint flag build failed", "err", err)
return nil
}
out := make([]string, 0, len(args))
diff --git a/internal/browsers/runtimekit/runtimekit_test.go b/internal/browsers/runtimekit/runtimekit_test.go
new file mode 100644
index 00000000..8c62720d
--- /dev/null
+++ b/internal/browsers/runtimekit/runtimekit_test.go
@@ -0,0 +1,216 @@
+package runtimekit
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/browsers"
+ _ "github.com/pinchtab/pinchtab/internal/browsers/builtin"
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func TestRuntimeProxyConfig_NilConfig(t *testing.T) {
+ got := RuntimeProxyConfig(nil)
+ if got.Server != "" || got.Username != "" || got.Password != "" || got.BypassList != nil || got.Geo != nil {
+ t.Fatalf("RuntimeProxyConfig(nil) = %+v, want zero value", got)
+ }
+}
+
+func TestRuntimeProxyConfig_MapsFields(t *testing.T) {
+ cfg := &config.RuntimeConfig{
+ Proxy: config.BrowserProxyConfig{
+ Server: "http://proxy.example:8080",
+ Username: "user",
+ Password: "pw",
+ BypassList: []string{"*.internal", "localhost"},
+ Geo: &config.BrowserProxyGeoConfig{
+ Timezone: "Europe/Rome",
+ Locale: "it-IT",
+ WebRTCIP: "203.0.113.7",
+ CountryISO: "IT",
+ },
+ },
+ }
+ got := RuntimeProxyConfig(cfg)
+ if got.Server != "http://proxy.example:8080" || got.Username != "user" || got.Password != "pw" {
+ t.Fatalf("proxy fields not mapped: %+v", got)
+ }
+ if len(got.BypassList) != 2 || got.BypassList[0] != "*.internal" {
+ t.Fatalf("bypass list not mapped: %v", got.BypassList)
+ }
+ if got.Geo == nil || got.Geo.Timezone != "Europe/Rome" || got.Geo.Locale != "it-IT" ||
+ got.Geo.WebRTCIP != "203.0.113.7" || got.Geo.CountryISO != "IT" {
+ t.Fatalf("geo not mapped: %+v", got.Geo)
+ }
+}
+
+func TestRuntimeProxyConfig_CopiesBypassList(t *testing.T) {
+ cfg := &config.RuntimeConfig{
+ Proxy: config.BrowserProxyConfig{
+ Server: "http://proxy.example:8080",
+ BypassList: []string{"a.example"},
+ },
+ }
+ got := RuntimeProxyConfig(cfg)
+ cfg.Proxy.BypassList[0] = "mutated.example"
+ if got.BypassList[0] != "a.example" {
+ t.Fatalf("BypassList aliases the input slice; want an independent copy")
+ }
+}
+
+func TestRuntimeProxyConfig_NilGeoStaysNil(t *testing.T) {
+ cfg := &config.RuntimeConfig{
+ Proxy: config.BrowserProxyConfig{Server: "http://proxy.example:8080"},
+ }
+ if got := RuntimeProxyConfig(cfg); got.Geo != nil {
+ t.Fatalf("Geo = %+v, want nil when source geo is nil", got.Geo)
+ }
+}
+
+func TestLaunchConfigFromRuntime_MapsFields(t *testing.T) {
+ cfg := &config.RuntimeConfig{
+ DefaultBrowser: "chrome",
+ ProfileDir: "/tmp/profile",
+ Headless: true,
+ Timezone: "UTC",
+ ExtensionPaths: []string{"/ext/a"},
+ NoRestore: true,
+ UserAgent: "ua-test",
+ Cloak: config.CloakBrowserRuntimeConfig{
+ FingerprintSeed: "seed",
+ Platform: "macos",
+ Locale: "en-US",
+ Timezone: "Europe/Rome",
+ WebRTCIP: "203.0.113.7",
+ FontsDir: "/fonts",
+ StorageQuotaMB: 64,
+ },
+ }
+ got := LaunchConfigFromRuntime(cfg, "/bin/chrome", 9222, true)
+ if got.Binary != "/bin/chrome" || got.DebugPort != 9222 || !got.NoSandbox {
+ t.Fatalf("binary/port/sandbox not mapped: %+v", got)
+ }
+ if got.ProfileDir != "/tmp/profile" || !got.Headless || got.Timezone != "UTC" ||
+ got.NoRestore != true || got.UserAgent != "ua-test" {
+ t.Fatalf("runtime fields not mapped: %+v", got)
+ }
+ if len(got.ExtensionPaths) != 1 || got.ExtensionPaths[0] != "/ext/a" {
+ t.Fatalf("extension paths not mapped: %v", got.ExtensionPaths)
+ }
+ if got.Cloak.FingerprintSeed != "seed" || got.Cloak.Platform != "macos" ||
+ got.Cloak.FontsDir != "/fonts" || got.Cloak.StorageQuotaMB != 64 {
+ t.Fatalf("cloak fingerprint not mapped: %+v", got.Cloak)
+ }
+ if got.Mode != browsers.LaunchModeChrome {
+ t.Fatalf("Mode = %v, want LaunchModeChrome for chrome", got.Mode)
+ }
+}
+
+func TestLaunchConfigFromRuntime_GhostChromeUsesAutoMode(t *testing.T) {
+ cfg := &config.RuntimeConfig{DefaultBrowser: "ghost-chrome"}
+ if got := LaunchConfigFromRuntime(cfg, "", 0, false); got.Mode != browsers.LaunchModeAuto {
+ t.Fatalf("Mode = %v, want LaunchModeAuto for ghost-chrome", got.Mode)
+ }
+}
+
+func TestChromeNeedsNoSandbox(t *testing.T) {
+ cases := []struct {
+ name string
+ goos string
+ euid int
+ inContainer bool
+ want bool
+ }{
+ {name: "darwin never needs it", goos: "darwin", euid: 0, inContainer: true, want: false},
+ {name: "windows never needs it", goos: "windows", euid: 0, inContainer: true, want: false},
+ {name: "linux root", goos: "linux", euid: 0, inContainer: false, want: true},
+ {name: "linux non-root in container", goos: "linux", euid: 1000, inContainer: true, want: true},
+ {name: "linux non-root no container", goos: "linux", euid: 1000, inContainer: false, want: false},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := ChromeNeedsNoSandbox(tc.goos, tc.euid, tc.inContainer); got != tc.want {
+ t.Fatalf("ChromeNeedsNoSandbox(%q, %d, %v) = %v, want %v", tc.goos, tc.euid, tc.inContainer, got, tc.want)
+ }
+ })
+ }
+}
+
+func TestResolveProviderLaunchPlan_Chrome(t *testing.T) {
+ cfg := &config.RuntimeConfig{DefaultBrowser: "chrome"}
+ launchCfg := LaunchConfigFromRuntime(cfg, " /bin/chrome ", 0, false)
+ plan, err := ResolveProviderLaunchPlan(cfg, launchCfg)
+ if err != nil {
+ t.Fatalf("ResolveProviderLaunchPlan returned %v", err)
+ }
+ if plan.Browser == nil {
+ t.Fatal("plan.Browser is nil; expected the registered chrome provider")
+ }
+ if plan.Binary != "/bin/chrome" {
+ t.Fatalf("Binary = %q, want trimmed %q", plan.Binary, "/bin/chrome")
+ }
+ if len(plan.Args) == 0 {
+ t.Fatal("plan.Args is empty; expected chrome base flags")
+ }
+ found := false
+ for _, arg := range plan.Args {
+ if arg == "--disable-background-networking" {
+ found = true
+ break
+ }
+ }
+ if !found {
+ t.Fatalf("plan.Args missing a known chrome base flag: %v", plan.Args)
+ }
+}
+
+func TestFindBrowserBinary_UnknownProvider(t *testing.T) {
+ if got := FindBrowserBinary("no-such-browser"); got != "" {
+ t.Fatalf("FindBrowserBinary(unknown) = %q, want empty", got)
+ }
+}
+
+func TestBaseFlagArgs_Chrome(t *testing.T) {
+ args := BaseFlagArgs("chrome", false)
+ if len(args) == 0 {
+ t.Fatal("BaseFlagArgs(chrome, false) is empty")
+ }
+ for _, arg := range args {
+ if !strings.HasPrefix(arg, "--") {
+ t.Fatalf("unexpected non-flag arg %q in %v", arg, args)
+ }
+ }
+}
+
+func TestCloakBrowserFlagArgs_NilAndNonCloak(t *testing.T) {
+ if got := CloakBrowserFlagArgs(nil); got != nil {
+ t.Fatalf("CloakBrowserFlagArgs(nil) = %v, want nil", got)
+ }
+ cfg := &config.RuntimeConfig{DefaultBrowser: "chrome"}
+ if got := CloakBrowserFlagArgs(cfg); got != nil {
+ t.Fatalf("CloakBrowserFlagArgs(chrome cfg) = %v, want nil", got)
+ }
+}
+
+func TestCloakBrowserFlagArgs_OnlyFingerprintFlagsSurvive(t *testing.T) {
+ cfg := &config.RuntimeConfig{
+ DefaultBrowser: config.BrowserCloak,
+ Cloak: config.CloakBrowserRuntimeConfig{
+ FingerprintSeed: "seed-1",
+ Timezone: "Europe/Rome",
+ },
+ }
+ args := CloakBrowserFlagArgs(cfg)
+ if len(args) == 0 {
+ t.Fatal("expected fingerprint flags for cloak config, got none")
+ }
+ for _, arg := range args {
+ if !strings.HasPrefix(arg, "--fingerprint") {
+ t.Fatalf("non-fingerprint flag %q leaked into cloak flag args: %v", arg, args)
+ }
+ }
+ joined := strings.Join(args, " ")
+ if !strings.Contains(joined, "seed-1") || !strings.Contains(joined, "Europe/Rome") {
+ t.Fatalf("configured fingerprint values missing from args: %v", args)
+ }
+}