Skip to content

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

feat: add dom-overlay screenshot annotations

Luigi Agostia963b2655133
diff --git a/cmd/pinchtab/cmd_cli_register.go b/cmd/pinchtab/cmd_cli_register.go
index 8fbb0ae3..8be704aa 100644
--- a/cmd/pinchtab/cmd_cli_register.go
+++ b/cmd/pinchtab/cmd_cli_register.go
@@ -236,6 +236,8 @@ func configureBrowserFlags() {
screenshotCmd.Flags().StringP("quality", "q", "", "JPEG quality (0-100)")
screenshotCmd.Flags().StringP("selector", "s", "", "Element selector to capture (ref/CSS/XPath/text)")
screenshotCmd.Flags().Bool("css-1x", false, "When used with --selector, output image at CSS pixel size instead of device pixels")
+ screenshotCmd.Flags().Bool("annotate", false, "Overlay numbered ref boxes on interactive elements (or on --selector matches). Prints a [n] ref legend to stdout.")
+ screenshotCmd.Flags().String("format", "", "Image format: 'jpeg' (default) or 'png'")
pdfCmd.Flags().StringP("output", "o", "", "Save PDF to file path")
pdfCmd.Flags().Bool("landscape", false, "Landscape orientation")
diff --git a/go.mod b/go.mod
index 9f8f120a..bc8cb34d 100644
--- a/go.mod
+++ b/go.mod
@@ -36,5 +36,5 @@ require (
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
golang.org/x/sys v0.43.0 // indirect
- golang.org/x/text v0.36.0 // indirect
+ golang.org/x/text v0.37.0 // indirect
)
diff --git a/go.sum b/go.sum
index 486db32f..4cab02e5 100644
--- a/go.sum
+++ b/go.sum
@@ -93,8 +93,8 @@ golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI=
golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
-golang.org/x/text v0.36.0 h1:JfKh3XmcRPqZPKevfXVpI1wXPTqbkE5f7JA92a55Yxg=
-golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164=
+golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
+golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
diff --git a/internal/cli/actions/actions_screenshot.go b/internal/cli/actions/actions_screenshot.go
index 8ba39c23..4673b6d4 100644
--- a/internal/cli/actions/actions_screenshot.go
+++ b/internal/cli/actions/actions_screenshot.go
@@ -1,21 +1,46 @@
package actions
import (
+ "encoding/base64"
+ "encoding/json"
"fmt"
- "github.com/pinchtab/pinchtab/internal/cli"
- "github.com/pinchtab/pinchtab/internal/cli/apiclient"
- "github.com/spf13/cobra"
"net/http"
"net/url"
"os"
"time"
+
+ "github.com/pinchtab/pinchtab/internal/cli"
+ "github.com/pinchtab/pinchtab/internal/cli/apiclient"
+ "github.com/spf13/cobra"
)
+// refLabelDigits extracts the numeric suffix the overlay renders (e.g.
+// "e7" -> "7"). Falls back to the whole ref when there are no digits.
+func refLabelDigits(ref string) string {
+ out := make([]byte, 0, len(ref))
+ for i := 0; i < len(ref); i++ {
+ c := ref[i]
+ if c >= '0' && c <= '9' {
+ out = append(out, c)
+ } else if len(out) > 0 {
+ break
+ }
+ }
+ if len(out) == 0 {
+ return ref
+ }
+ return string(out)
+}
+
func Screenshot(client *http.Client, base, token string, cmd *cobra.Command) {
params := url.Values{}
- params.Set("raw", "true")
outFile, _ := cmd.Flags().GetString("output")
+ annotate, _ := cmd.Flags().GetBool("annotate")
+ format, _ := cmd.Flags().GetString("format")
+ if format == "" {
+ format = "jpeg"
+ }
if v, _ := cmd.Flags().GetString("quality"); v != "" {
params.Set("quality", v)
}
@@ -28,11 +53,68 @@ func Screenshot(client *http.Client, base, token string, cmd *cobra.Command) {
if v, _ := cmd.Flags().GetString("tab"); v != "" {
params.Set("tabId", v)
}
+ if format != "" && format != "jpeg" {
+ params.Set("format", format)
+ }
- if outFile == "" {
- outFile = fmt.Sprintf("screenshot-%s.jpg", time.Now().Format("20060102-150405"))
+ ext := ".jpg"
+ if format == "png" {
+ ext = ".png"
+ }
+
+ if annotate {
+ params.Set("annotate", "true")
+ raw := apiclient.DoGetRaw(client, base, token, "/screenshot", params)
+ if raw == nil {
+ return
+ }
+ var envelope struct {
+ Format string `json:"format"`
+ Base64 string `json:"base64"`
+ Annotations []struct {
+ Ref string `json:"ref"`
+ Role string `json:"role"`
+ Name string `json:"name"`
+ Tag string `json:"tag"`
+ } `json:"annotations"`
+ }
+ if err := json.Unmarshal(raw, &envelope); err != nil {
+ cli.Fatal("Decode failed: %v", err)
+ }
+ img, err := base64.StdEncoding.DecodeString(envelope.Base64)
+ if err != nil {
+ cli.Fatal("Decode image: %v", err)
+ }
+ if outFile == "" {
+ outFile = fmt.Sprintf("screenshot-%s%s", time.Now().Format("20060102-150405"), ext)
+ }
+ if err := os.WriteFile(outFile, img, 0600); err != nil {
+ cli.Fatal("Write failed: %v", err)
+ }
+ fmt.Println(cli.StyleStdout(cli.SuccessStyle, fmt.Sprintf("Saved %s (%d bytes)", outFile, len(img))))
+ // Print a human-readable legend so the operator can correlate visual
+ // labels with refs at a glance. The bracketed number must match what
+ // the overlay draws (the numeric portion of the ref) — using i+1
+ // here would drift when refs start above e0 or filtering skips refs.
+ for _, a := range envelope.Annotations {
+ line := fmt.Sprintf("[%s] %s", refLabelDigits(a.Ref), a.Ref)
+ if a.Role != "" {
+ line += " " + a.Role
+ }
+ if a.Name != "" {
+ line += " \"" + a.Name + "\""
+ } else if a.Tag != "" {
+ line += " <" + a.Tag + ">"
+ }
+ fmt.Println(line)
+ }
+ return
}
+ params.Set("raw", "true")
+ if outFile == "" {
+ outFile = fmt.Sprintf("screenshot-%s%s", time.Now().Format("20060102-150405"), ext)
+ }
data := apiclient.DoGetRaw(client, base, token, "/screenshot", params)
if data == nil {
return
diff --git a/internal/handlers/screenshot.go b/internal/handlers/screenshot.go
index 618ba92d..33fc68b5 100644
--- a/internal/handlers/screenshot.go
+++ b/internal/handlers/screenshot.go
@@ -36,6 +36,7 @@ func (h *Handlers) HandleScreenshot(w http.ResponseWriter, r *http.Request) {
selector := r.URL.Query().Get("selector")
css1x := r.URL.Query().Get("css1x") == "true"
reqNoAnim := r.URL.Query().Get("noAnimations") == "true"
+ annotate := r.URL.Query().Get("annotate") == "true" || r.URL.Query().Get("annotate") == "1"
ctx, resolvedTabID, err := h.tabContext(r, tabID)
if err != nil {
@@ -57,6 +58,41 @@ func (h *Handlers) HandleScreenshot(w http.ResponseWriter, r *http.Request) {
}
}
+ if annotate {
+ quality := 80
+ if q := r.URL.Query().Get("quality"); q != "" {
+ if qn, err := strconv.Atoi(q); err == nil {
+ quality = qn
+ }
+ }
+ fmtStr := "jpeg"
+ if r.URL.Query().Get("format") == "png" {
+ fmtStr = "png"
+ }
+ img, items, outFormat, err := h.captureAnnotatedScreenshot(tCtx, resolvedTabID, selector, fmtStr, quality)
+ if err != nil {
+ httpx.Error(w, 500, fmt.Errorf("annotate: %w", err))
+ return
+ }
+ contentType := "image/jpeg"
+ if outFormat == "png" {
+ contentType = "image/png"
+ }
+ if r.URL.Query().Get("raw") == "true" {
+ w.Header().Set("Content-Type", contentType)
+ if _, err := w.Write(img); err != nil {
+ slog.Error("annotated screenshot write", "err", err)
+ }
+ return
+ }
+ httpx.JSON(w, 200, map[string]any{
+ "format": outFormat,
+ "base64": base64.StdEncoding.EncodeToString(img),
+ "annotations": items,
+ })
+ return
+ }
+
var clip *page.Viewport
if selector != "" {
nodeID, err := h.resolveSelectorNodeID(tCtx, resolvedTabID, selector)
diff --git a/internal/handlers/screenshot_annotate.go b/internal/handlers/screenshot_annotate.go
new file mode 100644
index 00000000..b1a63b39
--- /dev/null
+++ b/internal/handlers/screenshot_annotate.go
@@ -0,0 +1,608 @@
+package handlers
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "sort"
+ "time"
+
+ "github.com/chromedp/cdproto/page"
+ "github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/bridge"
+)
+
+// maxAnnotations bounds how many overlay rectangles we render per screenshot.
+// Caps payload size and overlay-render cost on dense pages.
+const maxAnnotations = 200
+
+// overlayRootID is the stable DOM id for the injected annotation layer. We
+// look for it before injection so a stale overlay from a previous failed
+// capture is removed first.
+const overlayRootID = "__pinchtab_annotations__"
+
+// captureMode selects how returned annotation boxes are projected.
+type captureMode int
+
+const (
+ modeViewport captureMode = iota
+ modeSelectorClip
+)
+
+type annotationItem struct {
+ Ref string `json:"ref"`
+ Role string `json:"role,omitempty"`
+ Name string `json:"name,omitempty"`
+ Tag string `json:"tag,omitempty"`
+ Box annotationRect `json:"box"`
+}
+
+type annotationRect struct {
+ X float64 `json:"x"`
+ Y float64 `json:"y"`
+ W float64 `json:"w"`
+ H float64 `json:"h"`
+}
+
+// collectScreenshotAnnotations builds the candidate annotation set from the
+// current accessibility tree (interactive filter), records the refs in the
+// tab's ref cache so follow-up actions can target them, and returns
+// viewport-relative rects for each candidate. If `selector` is non-empty, the
+// selector's own viewport rect is returned as `target` so callers can clip
+// and project against it later.
+func (h *Handlers) collectScreenshotAnnotations(
+ ctx context.Context,
+ tabID, selector string,
+) (items []annotationItem, target *annotationRect, err error) {
+ rawNodes, err := bridge.FetchAXTree(ctx)
+ if err != nil {
+ return nil, nil, fmt.Errorf("a11y tree: %w", err)
+ }
+ rawNodes = h.scopeSnapshotNodesByFrame(rawNodes, h.selectorFrameID(tabID))
+
+ // Selector narrows both the screenshot clip (handled by caller) and the
+ // candidate set. Resolve the target node and constrain the AX subtree to
+ // it so refs reflect only what the agent will see in the clip.
+ if selector != "" {
+ scopeID, scopeErr := h.resolveSelectorNodeID(ctx, tabID, selector)
+ if scopeErr != nil {
+ return nil, nil, fmt.Errorf("annotate selector: %w", scopeErr)
+ }
+ rawNodes = bridge.FilterSubtree(rawNodes, scopeID)
+ // Bring the target into the viewport before computing rects, otherwise
+ // an offscreen selector produces a blank/wrong clip and all candidate
+ // rects are read in pre-scroll positions.
+ if err := scrollNodeIntoView(ctx, scopeID); err != nil {
+ return nil, nil, fmt.Errorf("annotate scroll: %w", err)
+ }
+ rect, rectErr := annotationRectForNode(ctx, scopeID)
+ if rectErr != nil {
+ return nil, nil, fmt.Errorf("annotate selector rect: %w", rectErr)
+ }
+ if rect == nil {
+ // nil with no error means cross-origin frame projection blocked the
+ // rect read. We'd otherwise silently fall back to a full-viewport
+ // capture, which is a different scope than the caller asked for.
+ return nil, nil, fmt.Errorf("annotate selector %q: target rect unavailable (cross-origin frame?)", selector)
+ }
+ target = rect
+ }
+
+ flat, refs := bridge.BuildSnapshot(rawNodes, "interactive", -1)
+ if len(flat) == 0 && selector == "" {
+ // Pages with no AX-interactive content (canvas-heavy fixtures, etc.)
+ // fall back to the unfiltered tree so the agent still gets a layout.
+ flat, refs = bridge.BuildSnapshot(rawNodes, "", -1)
+ }
+
+ // Record refs so a subsequent click/fill on `e5` resolves the same node.
+ h.Bridge.SetRefCache(tabID, &bridge.RefCache{
+ Refs: refs,
+ Targets: bridge.RefTargetsFromNodes(flat),
+ Nodes: flat,
+ })
+
+ items = make([]annotationItem, 0, len(flat))
+ for _, n := range flat {
+ if n.NodeID == 0 || n.Ref == "" {
+ continue
+ }
+ rect, rectErr := annotationRectForNode(ctx, n.NodeID)
+ if rectErr != nil || rect == nil {
+ continue
+ }
+ if rect.W <= 0 || rect.H <= 0 {
+ continue
+ }
+ items = append(items, annotationItem{
+ Ref: n.Ref,
+ Role: n.Role,
+ Name: n.Name,
+ Tag: n.Tag,
+ Box: *rect,
+ })
+ }
+
+ // Stable order keeps overlay rendering and JSON output deterministic, and
+ // makes the post-cap truncation predictable.
+ sort.SliceStable(items, func(i, j int) bool { return refLess(items[i].Ref, items[j].Ref) })
+ if len(items) > maxAnnotations {
+ items = items[:maxAnnotations]
+ }
+ return items, target, nil
+}
+
+// scrollNodeIntoView ensures the target backend node is visible before we
+// read its rect. Mirrors what the non-annotated selector path does in
+// screenshotClipForNode.
+func scrollNodeIntoView(ctx context.Context, nodeID int64) error {
+ return chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.scrollIntoViewIfNeeded", map[string]any{
+ "backendNodeId": nodeID,
+ }, nil)
+ }))
+}
+
+// annotationRectForNode returns the viewport-relative CSS-pixel rect for a
+// backend node id. Document scroll is intentionally NOT added; the overlay
+// injector adds scrollX/scrollY when placing absolute-positioned boxes.
+func annotationRectForNode(ctx context.Context, nodeID int64) (*annotationRect, error) {
+ var resolveResult json.RawMessage
+ if err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.resolveNode", map[string]any{
+ "backendNodeId": nodeID,
+ }, &resolveResult)
+ })); err != nil {
+ return nil, err
+ }
+ var resolved struct {
+ Object struct {
+ ObjectID string `json:"objectId"`
+ } `json:"object"`
+ }
+ if err := json.Unmarshal(resolveResult, &resolved); err != nil {
+ return nil, err
+ }
+ if resolved.Object.ObjectID == "" {
+ return nil, fmt.Errorf("element not found (backendNodeId=%d)", nodeID)
+ }
+
+ // boxFn returns top-level viewport-relative rects so the overlay (which we
+ // always inject into the top document) can place boxes correctly even for
+ // iframe-owned nodes. Frame ancestors are walked and their iframe-element
+ // bounding rects (already in their parent's viewport) are added. Cross-
+ // origin frames throw on access; in that case we mark the rect as
+ // unprojectable so the caller can drop it.
+ // boxFn returns top-level viewport-relative rects. Walks frame ancestors,
+ // adding each iframe-element's bounding rect (already in its parent's
+ // viewport). If we hit a null frameElement before reaching the top window
+ // — typical cross-origin barrier — we flag the rect unprojectable rather
+ // than emitting partial frame-local coordinates.
+ const boxFn = `function() {
+ const rect = this.getBoundingClientRect();
+ let x = rect.x;
+ let y = rect.y;
+ let frameError = false;
+ try {
+ let cur = window;
+ while (cur && cur.parent && cur !== cur.parent) {
+ const frameEl = cur.frameElement;
+ if (!frameEl) {
+ // We are still inside a nested frame (cur !== cur.parent)
+ // but cannot reach the host iframe element. Treat the rect
+ // as unprojectable so the caller drops it.
+ frameError = true;
+ break;
+ }
+ const frameRect = frameEl.getBoundingClientRect();
+ x += frameRect.left;
+ y += frameRect.top;
+ cur = cur.parent;
+ }
+ } catch (e) {
+ frameError = true;
+ }
+ return { x: x, y: y, w: rect.width, h: rect.height, frameError: frameError };
+ }`
+
+ var callResult json.RawMessage
+ if err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.callFunctionOn", map[string]any{
+ "functionDeclaration": boxFn,
+ "objectId": resolved.Object.ObjectID,
+ "returnByValue": true,
+ }, &callResult)
+ })); err != nil {
+ return nil, err
+ }
+ var box struct {
+ Result struct {
+ Value struct {
+ X float64 `json:"x"`
+ Y float64 `json:"y"`
+ W float64 `json:"w"`
+ H float64 `json:"h"`
+ FrameError bool `json:"frameError"`
+ } `json:"value"`
+ } `json:"result"`
+ }
+ if err := json.Unmarshal(callResult, &box); err != nil {
+ return nil, err
+ }
+ if box.Result.Value.FrameError {
+ // Cross-origin ancestor frame blocked coordinate projection. Skip the
+ // node rather than emitting wrong coordinates.
+ return nil, nil
+ }
+ return &annotationRect{
+ X: box.Result.Value.X,
+ Y: box.Result.Value.Y,
+ W: box.Result.Value.W,
+ H: box.Result.Value.H,
+ }, nil
+}
+
+// filterAnnotationItems keeps only items whose viewport rect overlaps the
+// active capture region. For viewport mode `target` is nil and `viewport`
+// is used; for selector-clip mode the selector rect is used instead.
+func filterAnnotationItems(items []annotationItem, target *annotationRect, viewport annotationRect) []annotationItem {
+ region := viewport
+ if target != nil {
+ region = *target
+ }
+ out := items[:0]
+ for _, it := range items {
+ if rectsOverlap(it.Box, region) {
+ out = append(out, it)
+ }
+ }
+ return out
+}
+
+func rectsOverlap(a, b annotationRect) bool {
+ if a.W <= 0 || a.H <= 0 || b.W <= 0 || b.H <= 0 {
+ return false
+ }
+ return a.X < b.X+b.W && a.X+a.W > b.X && a.Y < b.Y+b.H && a.Y+a.H > b.Y
+}
+
+// projectAnnotationBoxes returns boxes in the coordinate space of the
+// returned screenshot. Viewport mode passes the rects through unchanged;
+// selector-clip mode subtracts the target origin so boxes are relative to
+// the clipped image.
+func projectAnnotationBoxes(items []annotationItem, target *annotationRect, mode captureMode) []annotationItem {
+ out := make([]annotationItem, len(items))
+ for i, it := range items {
+ out[i] = it
+ if mode == modeSelectorClip && target != nil {
+ out[i].Box = annotationRect{
+ X: roundFloat(it.Box.X - target.X),
+ Y: roundFloat(it.Box.Y - target.Y),
+ W: roundFloat(it.Box.W),
+ H: roundFloat(it.Box.H),
+ }
+ continue
+ }
+ out[i].Box = annotationRect{
+ X: roundFloat(it.Box.X),
+ Y: roundFloat(it.Box.Y),
+ W: roundFloat(it.Box.W),
+ H: roundFloat(it.Box.H),
+ }
+ }
+ return out
+}
+
+// roundFloat returns the float rounded to the nearest integer (still as
+// float64). Spec asks for integer values in the public box payload.
+func roundFloat(f float64) float64 {
+ if f >= 0 {
+ return float64(int64(f + 0.5))
+ }
+ return float64(int64(f - 0.5))
+}
+
+// injectAnnotationOverlay paints an absolute-positioned overlay div on top
+// of the page. Viewport-relative rects are converted to document
+// coordinates inside the page so the overlay tracks the document during
+// capture, regardless of scroll state.
+//
+// clipTopY is the y coordinate of the captured region's top edge, in the
+// same viewport-relative space as item rects. For viewport mode it is 0;
+// for selector clip it is the target rect's y. The overlay JS uses it to
+// decide whether the label has room above the box in the *captured image*
+// (not just in the live viewport) — selector-clipped boxes near the clip's
+// top would otherwise place their label above the cropped image and lose
+// the visible label.
+func injectAnnotationOverlay(ctx context.Context, items []annotationItem, clipTopY float64) error {
+ if len(items) == 0 {
+ return nil
+ }
+ // Strip projection-only fields the page does not need.
+ type overlayItem struct {
+ Ref string `json:"ref"`
+ X float64 `json:"x"`
+ Y float64 `json:"y"`
+ W float64 `json:"w"`
+ H float64 `json:"h"`
+ }
+ payload := make([]overlayItem, len(items))
+ for i, it := range items {
+ payload[i] = overlayItem{Ref: it.Ref, X: it.Box.X, Y: it.Box.Y, W: it.Box.W, H: it.Box.H}
+ }
+ encoded, err := json.Marshal(payload)
+ if err != nil {
+ return err
+ }
+
+ // JS: removes any prior overlay, builds a new layer with one div per
+ // annotation. Labels show the numeric portion of the ref ("e5" -> "5")
+ // so dense pages stay readable; the response payload still uses "e5".
+ script := fmt.Sprintf(`(function(items, rootId, clipTopY) {
+ var prev = document.getElementById(rootId);
+ if (prev) prev.remove();
+ var root = document.createElement('div');
+ root.id = rootId;
+ root.style.position = 'absolute';
+ root.style.top = '0';
+ root.style.left = '0';
+ root.style.pointerEvents = 'none';
+ root.style.zIndex = '2147483646';
+ var sx = window.scrollX || window.pageXOffset || 0;
+ var sy = window.scrollY || window.pageYOffset || 0;
+ for (var i = 0; i < items.length; i++) {
+ var it = items[i];
+ var box = document.createElement('div');
+ box.style.position = 'absolute';
+ box.style.left = (it.x + sx) + 'px';
+ box.style.top = (it.y + sy) + 'px';
+ box.style.width = it.w + 'px';
+ box.style.height = it.h + 'px';
+ box.style.boxSizing = 'border-box';
+ box.style.border = '2px solid rgba(255, 51, 102, 0.95)';
+ box.style.borderRadius = '2px';
+ box.style.pointerEvents = 'none';
+ var label = document.createElement('div');
+ label.textContent = String(it.ref).replace(/^[^0-9]+/, '') || it.ref;
+ label.style.position = 'absolute';
+ label.style.left = '0';
+ // Place label above the box by default; flip inside the box when
+ // there isn't enough room above the *captured region's* top edge,
+ // not just the viewport's. For viewport capture clipTopY is 0 so
+ // this collapses to the simple case; for selector clips it is the
+ // target rect's y, so labels near the top of the clip stay
+ // visible in the cropped image.
+ var labelHeight = 16;
+ if ((it.y - clipTopY) < labelHeight) {
+ label.style.top = '1px';
+ } else {
+ label.style.top = '-18px';
+ }
+ label.style.padding = '1px 4px';
+ label.style.background = 'rgba(255, 51, 102, 0.95)';
+ label.style.color = '#fff';
+ label.style.font = '600 11px/1 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif';
+ label.style.borderRadius = '2px';
+ label.style.whiteSpace = 'nowrap';
+ label.style.pointerEvents = 'none';
+ box.appendChild(label);
+ root.appendChild(box);
+ }
+ document.documentElement.appendChild(root);
+ return items.length;
+ })(%s, %q, %v)`, string(encoded), overlayRootID, clipTopY)
+
+ return chromedp.Run(ctx, chromedp.Evaluate(script, nil))
+}
+
+// removeAnnotationOverlay removes the overlay div if present. Safe to call
+// multiple times and after a failed inject.
+func removeAnnotationOverlay(ctx context.Context) error {
+ const script = `(function(rootId) {
+ var el = document.getElementById(rootId);
+ if (el) el.remove();
+ return true;
+ })("` + overlayRootID + `")`
+ return chromedp.Run(ctx, chromedp.Evaluate(script, nil))
+}
+
+// viewportRect reports the current CSS-pixel viewport size. Used to filter
+// out annotations that fall entirely outside the visible window.
+func viewportRect(ctx context.Context) (annotationRect, error) {
+ const fn = `(() => ({ x: 0, y: 0, w: window.innerWidth, h: window.innerHeight }))()`
+ var raw json.RawMessage
+ if err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.evaluate", map[string]any{
+ "expression": fn,
+ "returnByValue": true,
+ }, &raw)
+ })); err != nil {
+ return annotationRect{}, err
+ }
+ var resp struct {
+ Result struct {
+ Value annotationRect `json:"value"`
+ } `json:"result"`
+ }
+ if err := json.Unmarshal(raw, &resp); err != nil {
+ return annotationRect{}, err
+ }
+ return resp.Result.Value, nil
+}
+
+// captureAnnotatedScreenshot orchestrates the annotated-screenshot pipeline.
+// It collects refs, injects a DOM overlay, calls the existing CDP capture
+// path, removes the overlay, and projects the returned boxes into the
+// coordinate space of the resulting image.
+func (h *Handlers) captureAnnotatedScreenshot(
+ ctx context.Context,
+ tabID, selector, format string,
+ quality int,
+) (img []byte, projected []annotationItem, outFormat string, err error) {
+ items, target, err := h.collectScreenshotAnnotations(ctx, tabID, selector)
+ if err != nil {
+ return nil, nil, "", err
+ }
+
+ mode := modeViewport
+ if target != nil {
+ mode = modeSelectorClip
+ }
+
+ region := annotationRect{}
+ if mode == modeViewport {
+ region, err = viewportRect(ctx)
+ if err != nil {
+ return nil, nil, "", err
+ }
+ }
+ items = filterAnnotationItems(items, target, region)
+
+ // Always clear stale overlay state before capture, regardless of whether
+ // we have items to draw — protects against leftovers from a prior
+ // crashed run.
+ _ = removeAnnotationOverlay(ctx)
+ overlayInjected := false
+ if len(items) > 0 {
+ clipTopY := 0.0
+ if mode == modeSelectorClip && target != nil {
+ clipTopY = target.Y
+ }
+ if err := injectAnnotationOverlay(ctx, items, clipTopY); err != nil {
+ return nil, nil, "", fmt.Errorf("inject overlay: %w", err)
+ }
+ overlayInjected = true
+ }
+ defer func() {
+ if !overlayInjected {
+ return
+ }
+ // Capture-time deadlines or client cancellation cancel `ctx`, which
+ // would skip the cleanup CDP call and leave the overlay in the live
+ // page. Use a detached context with its own short deadline so cleanup
+ // runs even after the parent is cancelled.
+ cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 2*time.Second)
+ defer cancel()
+ _ = removeAnnotationOverlay(cleanupCtx)
+ }()
+
+ cdpFormat := page.CaptureScreenshotFormatJpeg
+ outFormat = "jpeg"
+ if format == "png" {
+ cdpFormat = page.CaptureScreenshotFormatPng
+ outFormat = "png"
+ }
+
+ var clip *page.Viewport
+ if mode == modeSelectorClip && target != nil {
+ // Translate viewport rect into page coords for CDP clip.
+ dpr, _ := devicePixelRatioForAnnotation(ctx)
+ _ = dpr // CDP clip uses CSS pixels with `scale: 1`.
+ offsetX, offsetY, scrollErr := pageScroll(ctx)
+ if scrollErr != nil {
+ offsetX, offsetY = 0, 0
+ }
+ clip = &page.Viewport{
+ X: target.X + offsetX,
+ Y: target.Y + offsetY,
+ Width: target.W,
+ Height: target.H,
+ Scale: 1,
+ }
+ }
+
+ if err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ shot := page.CaptureScreenshot().WithFormat(cdpFormat)
+ if clip != nil {
+ shot = shot.WithClip(clip)
+ }
+ if cdpFormat == page.CaptureScreenshotFormatJpeg {
+ shot = shot.WithQuality(int64(quality))
+ }
+ var captureErr error
+ img, captureErr = shot.Do(ctx)
+ return captureErr
+ })); err != nil {
+ return nil, nil, "", fmt.Errorf("capture: %w", err)
+ }
+
+ projected = projectAnnotationBoxes(items, target, mode)
+ return img, projected, outFormat, nil
+}
+
+// pageScroll returns the document's current scroll offsets in CSS pixels.
+func pageScroll(ctx context.Context) (float64, float64, error) {
+ const fn = `(() => ({ x: window.scrollX || window.pageXOffset || 0, y: window.scrollY || window.pageYOffset || 0 }))()`
+ var raw json.RawMessage
+ if err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.evaluate", map[string]any{
+ "expression": fn,
+ "returnByValue": true,
+ }, &raw)
+ })); err != nil {
+ return 0, 0, err
+ }
+ var resp struct {
+ Result struct {
+ Value struct {
+ X float64 `json:"x"`
+ Y float64 `json:"y"`
+ } `json:"value"`
+ } `json:"result"`
+ }
+ if err := json.Unmarshal(raw, &resp); err != nil {
+ return 0, 0, err
+ }
+ return resp.Result.Value.X, resp.Result.Value.Y, nil
+}
+
+// devicePixelRatioForAnnotation kept as a small helper in case callers want
+// to scale to image pixels. Annotation boxes themselves stay in CSS pixels.
+func devicePixelRatioForAnnotation(ctx context.Context) (float64, error) {
+ const fn = `(() => window.devicePixelRatio || 1)()`
+ var raw json.RawMessage
+ if err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.evaluate", map[string]any{
+ "expression": fn,
+ "returnByValue": true,
+ }, &raw)
+ })); err != nil {
+ return 1, err
+ }
+ var resp struct {
+ Result struct {
+ Value float64 `json:"value"`
+ } `json:"result"`
+ }
+ if err := json.Unmarshal(raw, &resp); err != nil {
+ return 1, err
+ }
+ if resp.Result.Value <= 0 {
+ return 1, nil
+ }
+ return resp.Result.Value, nil
+}
+
+// refLess sorts refs like e1 < e2 < e10 by their numeric suffix.
+func refLess(a, b string) bool {
+ an := refNumber(a)
+ bn := refNumber(b)
+ if an != bn {
+ return an < bn
+ }
+ return a < b
+}
+
+func refNumber(ref string) int {
+ n := 0
+ started := false
+ for _, c := range ref {
+ if c >= '0' && c <= '9' {
+ n = n*10 + int(c-'0')
+ started = true
+ } else if started {
+ break
+ }
+ }
+ return n
+}
diff --git a/internal/handlers/screenshot_annotate_test.go b/internal/handlers/screenshot_annotate_test.go
new file mode 100644
index 00000000..9e1d907d
--- /dev/null
+++ b/internal/handlers/screenshot_annotate_test.go
@@ -0,0 +1,92 @@
+package handlers
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestFilterAnnotationItems_Viewport(t *testing.T) {
+ viewport := annotationRect{X: 0, Y: 0, W: 800, H: 600}
+ items := []annotationItem{
+ {Ref: "e1", Box: annotationRect{X: 10, Y: 10, W: 100, H: 30}}, // inside
+ {Ref: "e2", Box: annotationRect{X: 750, Y: 580, W: 100, H: 30}}, // partial overlap (bottom-right)
+ {Ref: "e3", Box: annotationRect{X: 1000, Y: 10, W: 100, H: 30}}, // off-screen right
+ {Ref: "e4", Box: annotationRect{X: 10, Y: 700, W: 100, H: 30}}, // off-screen below
+ }
+ got := filterAnnotationItems(items, nil, viewport)
+ if len(got) != 2 || got[0].Ref != "e1" || got[1].Ref != "e2" {
+ t.Fatalf("filterAnnotationItems viewport = %+v, want e1+e2", got)
+ }
+}
+
+func TestFilterAnnotationItems_SelectorClip(t *testing.T) {
+ target := annotationRect{X: 100, Y: 100, W: 200, H: 200}
+ items := []annotationItem{
+ {Ref: "e1", Box: annotationRect{X: 110, Y: 110, W: 50, H: 20}}, // inside target
+ {Ref: "e2", Box: annotationRect{X: 0, Y: 0, W: 50, H: 50}}, // outside (top-left)
+ {Ref: "e3", Box: annotationRect{X: 290, Y: 290, W: 30, H: 30}}, // partial overlap with target bottom-right
+ }
+ // filterAnnotationItems mutates the underlying slice; copy first.
+ src := append([]annotationItem(nil), items...)
+ got := filterAnnotationItems(src, &target, annotationRect{})
+ if len(got) != 2 || got[0].Ref != "e1" || got[1].Ref != "e3" {
+ t.Fatalf("filterAnnotationItems selector = %+v, want e1+e3", got)
+ }
+}
+
+func TestProjectAnnotationBoxes_Viewport(t *testing.T) {
+ items := []annotationItem{
+ {Ref: "e1", Box: annotationRect{X: 12.4, Y: 33.6, W: 100, H: 32}},
+ }
+ got := projectAnnotationBoxes(items, nil, modeViewport)
+ want := annotationRect{X: 12, Y: 34, W: 100, H: 32}
+ if !reflect.DeepEqual(got[0].Box, want) {
+ t.Fatalf("viewport projection = %+v, want %+v", got[0].Box, want)
+ }
+}
+
+func TestProjectAnnotationBoxes_SelectorClipSubtractsOrigin(t *testing.T) {
+ target := annotationRect{X: 100, Y: 100, W: 200, H: 200}
+ items := []annotationItem{
+ {Ref: "e1", Box: annotationRect{X: 110, Y: 130, W: 50, H: 20}},
+ }
+ got := projectAnnotationBoxes(items, &target, modeSelectorClip)
+ want := annotationRect{X: 10, Y: 30, W: 50, H: 20}
+ if !reflect.DeepEqual(got[0].Box, want) {
+ t.Fatalf("selector projection = %+v, want %+v", got[0].Box, want)
+ }
+ // Source item should not be mutated.
+ if items[0].Box.X != 110 {
+ t.Fatalf("source mutated: %+v", items[0].Box)
+ }
+}
+
+func TestRefLessOrdersByNumber(t *testing.T) {
+ cases := []struct {
+ a, b string
+ want bool
+ }{
+ {"e1", "e2", true},
+ {"e2", "e10", true}, // numeric, not lexicographic
+ {"e10", "e2", false}, // reverse direction
+ {"e1", "e1", false},
+ }
+ for _, c := range cases {
+ if got := refLess(c.a, c.b); got != c.want {
+ t.Errorf("refLess(%q, %q) = %v, want %v", c.a, c.b, got, c.want)
+ }
+ }
+}
+
+func TestRectsOverlapEdgeCases(t *testing.T) {
+ a := annotationRect{X: 0, Y: 0, W: 10, H: 10}
+ // Touching but not overlapping (right edge meets left edge).
+ b := annotationRect{X: 10, Y: 0, W: 10, H: 10}
+ if rectsOverlap(a, b) {
+ t.Errorf("touching rects should not overlap")
+ }
+ // Zero-size rect never overlaps.
+ if rectsOverlap(a, annotationRect{X: 5, Y: 5, W: 0, H: 0}) {
+ t.Errorf("zero-size rect should not overlap")
+ }
+}
diff --git a/internal/mcp/handlers_navigation.go b/internal/mcp/handlers_navigation.go
index 097ac214..e8f1a93d 100644
--- a/internal/mcp/handlers_navigation.go
+++ b/internal/mcp/handlers_navigation.go
@@ -146,6 +146,9 @@ func handleScreenshot(c *Client) func(context.Context, mcp.CallToolRequest) (*mc
if v, ok := optBool(r, "css1x"); ok && v {
q.Set("css1x", "true")
}
+ if v, ok := optBool(r, "annotate"); ok && v {
+ q.Set("annotate", "true")
+ }
if quality, ok := optFloat(r, "quality"); ok {
q.Set("quality", fmt.Sprintf("%d", int(quality)))
}
diff --git a/internal/mcp/tools.go b/internal/mcp/tools.go
index 04ac9038..243266e2 100644
--- a/internal/mcp/tools.go
+++ b/internal/mcp/tools.go
@@ -30,12 +30,13 @@ func allTools() []mcp.Tool {
mcp.WithString("target", mcp.Description("Frame target: 'main', a snapshot ref, a selector for an iframe element, or a frame name/URL")),
),
mcp.NewTool("pinchtab_screenshot",
- mcp.WithDescription("Take a screenshot of the current page"),
+ mcp.WithDescription("Take a screenshot of the current page. With annotate=true, the response is a JSON envelope with the image plus a list of {ref, role, name, box} so the model can label elements visually and act on the same refs."),
mcp.WithString("tabId", mcp.Description("Target tab ID")),
- mcp.WithString("selector", mcp.Description("Unified selector to capture a specific element (ref, CSS, XPath, text, find, role, label, placeholder, alt, title, testid, first/last/nth). Selectors resolve in the current frame scope.")),
+ mcp.WithString("selector", mcp.Description("Unified selector. Without annotate it clips the screenshot to the element. With annotate=true it narrows which elements receive overlay boxes (default: all interactive elements).")),
mcp.WithString("format", mcp.Description("Image format: 'jpeg' (default) or 'png'")),
mcp.WithNumber("quality", mcp.Description("JPEG quality 0-100 (only for JPEG format)")),
- mcp.WithBoolean("css1x", mcp.Description("When selector is set, return element screenshot at CSS pixel size (1x) instead of device pixels")),
+ mcp.WithBoolean("css1x", mcp.Description("When selector is set (without annotate), return element screenshot at CSS pixel size (1x) instead of device pixels")),
+ mcp.WithBoolean("annotate", mcp.Description("Overlay numbered ref boxes on interactive elements (or on selector matches). Returns the image plus a structured list of {ref, role, name, box}.")),
),
mcp.NewTool("pinchtab_get_text",
mcp.WithDescription("Extract readable text content from the current page. Inherits the current frame scope for the tab unless no frame is selected."),
diff --git a/tests/e2e/scenarios/api/screenshot-annotate-basic.sh b/tests/e2e/scenarios/api/screenshot-annotate-basic.sh
new file mode 100755
index 00000000..7f85b394
--- /dev/null
+++ b/tests/e2e/scenarios/api/screenshot-annotate-basic.sh
@@ -0,0 +1,130 @@
+#!/bin/bash
+# screenshot-annotate-basic.sh — annotated screenshot pipeline.
+#
+# Covers the public contract of /screenshot?annotate=true:
+# - JSON envelope shape (format/base64/annotations)
+# - per-annotation fields (ref, role, box.x/y/w/h with positive size)
+# - selector clip projection (boxes are clip-relative, not viewport)
+# - cleanup of the in-page __pinchtab_annotations__ overlay
+# - returned ref is usable for follow-up actions in the same tab
+
+GROUP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+source "${GROUP_DIR}/../../helpers/api.sh"
+
+# ─────────────────────────────────────────────────────────────────
+start_test "screenshot annotate: JSON envelope shape"
+
+pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/form.html\"}"
+
+pt_get "/screenshot?annotate=true&format=png"
+assert_ok "annotated screenshot"
+
+assert_result_eq '.format' 'png' 'envelope.format = "png"'
+assert_result_exists '.base64' 'envelope.base64 present'
+assert_result_exists '.annotations' 'envelope.annotations present'
+assert_json_length_gte "$RESULT" '.annotations' 1 'has at least one annotation'
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "screenshot annotate: annotation fields"
+
+# Re-use the form fixture from the previous step.
+pt_get "/screenshot?annotate=true&format=png"
+assert_ok "annotated screenshot for field check"
+
+FIRST_REF=$(echo "$RESULT" | jq -r '.annotations[0].ref')
+
+assert_result_jq \
+ '.annotations[0].ref | test("^[a-z]+[0-9]+$")' \
+ 'annotations[0].ref looks like e<digits>' \
+ 'annotations[0].ref is malformed'
+
+# Every box must have positive width and height; otherwise the agent has no
+# usable target. Stricter than "field present".
+assert_result_jq \
+ 'all(.annotations[]; .box.w > 0 and .box.h > 0)' \
+ 'all annotation boxes have positive size' \
+ 'at least one annotation has zero/negative box size'
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "screenshot annotate: overlay node removed after capture"
+
+# The injector adds a single id="__pinchtab_annotations__" root and the
+# orchestrator removes it on the way out. After a successful capture the
+# node must not be present in the live DOM, otherwise it would leak ink
+# into subsequent (non-annotated) screenshots and clicks.
+pt_post /evaluate -d '{"expression":"document.getElementById(\"__pinchtab_annotations__\") === null"}'
+assert_ok "evaluate overlay-removed probe"
+assert_result_eq '.result' 'true' 'overlay node removed after capture'
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "screenshot annotate: returned ref is clickable"
+
+# A non-annotated snapshot is intentionally NOT taken between the annotate
+# call and the click — annotated capture should refresh the tab's ref map
+# itself so follow-up actions resolve immediately.
+pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/form.html\"}"
+pt_get "/screenshot?annotate=true&format=png"
+assert_ok "annotated screenshot before click"
+
+# Pick the first annotation that points at an interactive button or link;
+# fall back to the first ref if none qualify.
+TARGET_REF=$(echo "$RESULT" | jq -r '
+ (.annotations[] | select(.role == "button" or .role == "link") | .ref) // .annotations[0].ref
+' | head -n1)
+
+if [ -n "$TARGET_REF" ] && [ "$TARGET_REF" != "null" ]; then
+ pt_post /action -d "{\"kind\":\"click\",\"ref\":\"${TARGET_REF}\"}"
+ # Some refs may target submit-only elements that error out for benign
+ # reasons; we only require that the ref itself was recognised, i.e. the
+ # response is not "ref not found".
+ if echo "$RESULT" | grep -qi "ref.*not.*found\|unknown.*ref"; then
+ fail_assert "ref ${TARGET_REF} not recognised after annotate"
+ else
+ pass_assert "ref ${TARGET_REF} resolved by click handler"
+ fi
+else
+ fail_assert "no annotations returned to click"
+fi
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "screenshot annotate: selector clip projects boxes to clip origin"
+
+pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/form.html\"}"
+
+# The fixture form has id="test-form" (see tests/e2e/fixtures/form.html).
+# Selector + annotate must clip the screenshot AND narrow the annotation
+# set to refs whose rect overlaps that clip. We assert this directly:
+# the call must succeed, must return at least one annotation, and every
+# returned box must be clip-relative (x >= 0 and y >= 0).
+SELECTOR_ENC='%23test-form'
+pt_get "/screenshot?annotate=true&format=png&selector=${SELECTOR_ENC}"
+assert_ok "annotated selector screenshot"
+
+assert_result_exists '.annotations' 'envelope.annotations present (selector mode)'
+assert_json_length_gte "$RESULT" '.annotations' 1 'selector returned at least one annotation'
+
+# Clip-relative invariant: after subtracting target origin, every box must
+# start at non-negative coords. A regression that left boxes in viewport
+# space would surface here as negative or far-from-zero values.
+assert_result_jq \
+ 'all(.annotations[]; .box.x >= 0 and .box.y >= 0)' \
+ 'selector annotations are clip-relative (all x,y >= 0)' \
+ 'selector annotation projection emitted negative coords'
+
+# Sanity: at least one annotation must sit close to the clip origin
+# (within 200px). If projection were skipped, the smallest box origin
+# would still be at the form's viewport y, well above 200.
+assert_result_jq \
+ '[.annotations[] | select(.box.y < 200)] | length > 0' \
+ 'at least one annotation near clip origin' \
+ 'no annotation near clip origin — projection looks unprojected'
+
+end_test