High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
feat(screenshot): add selector css-1x mode
zzerdb3428e56681e
diff --git a/cmd/pinchtab/cmd_cli_register.go b/cmd/pinchtab/cmd_cli_register.goindex a1c1bd22..0bbc5fa9 100644--- a/cmd/pinchtab/cmd_cli_register.go+++ b/cmd/pinchtab/cmd_cli_register.go@@ -169,6 +169,8 @@ func configureBrowserFlags() {screenshotCmd.Flags().StringP("output", "o", "", "Save screenshot to file path")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")pdfCmd.Flags().StringP("output", "o", "", "Save PDF to file path")pdfCmd.Flags().Bool("landscape", false, "Landscape orientation")diff --git a/docs/commands.md b/docs/commands.mdindex b56c1157..2fd14fab 100644--- a/docs/commands.md+++ b/docs/commands.md@@ -183,6 +183,8 @@ curl -X POST "$PINCHTAB_SERVER/tabs/<tabId>/resume"pinchtab screenshot # Save a screenshot to a generated .jpg pathpinchtab screenshot -o <path> # Save screenshot to a chosen pathpinchtab screenshot -q <0-100> # JPEG quality+pinchtab screenshot -s <selector> # Capture a specific element by selector+pinchtab screenshot -s <selector> --css-1x # Export selector screenshot at CSS pixel sizepinchtab pdf # Export the active page as PDFpinchtab pdf -o <path> # Save PDF to a chosen pathpinchtab pdf --landscape # Landscape orientationdiff --git a/docs/reference/cli.md b/docs/reference/cli.mdindex a8e7d4f9..4d6756e6 100644--- a/docs/reference/cli.md+++ b/docs/reference/cli.md@@ -102,7 +102,7 @@ Common commands:| `pinchtab fill <selector> <text>` | Fill directly || `pinchtab text` | Extract page text (`--full`, `--raw`, `--frame <frameId>`) || `pinchtab find <query>` | Semantic element search |-| `pinchtab screenshot` | Save a screenshot |+| `pinchtab screenshot` | Save a screenshot (`-s/--selector` captures a specific element, `--css-1x` exports selector shots at CSS size) || `pinchtab pdf` | Export the page as PDF || `pinchtab network` | Inspect captured network requests || `pinchtab wait ...` | Wait for selector, text, URL, JS, or time |diff --git a/docs/reference/mcp-tools.md b/docs/reference/mcp-tools.mdindex 919660e9..2eb6199e 100644--- a/docs/reference/mcp-tools.md+++ b/docs/reference/mcp-tools.md@@ -20,7 +20,7 @@ Selector forms include:| --- | --- | --- || `pinchtab_navigate` | `url` required, `tabId` optional | Uses `/navigate`; omitting `tabId` opens a new tab || `pinchtab_snapshot` | `tabId`, `interactive`, `compact`, `format`, `diff`, `selector`, `maxTokens`, `depth`, `noAnimations` | `selector` scopes the snapshot; `format` is limited to `compact` or `text` |-| `pinchtab_screenshot` | `tabId`, `format`, `quality` | `format` is `jpeg` or `png` |+| `pinchtab_screenshot` | `tabId`, `selector`, `css1x`, `format`, `quality` | `selector` captures a specific element in current frame scope; `css1x=true` exports selector shots at CSS pixel size; `format` is `jpeg` or `png` || `pinchtab_get_text` | `tabId`, `raw`, `format`, `maxChars` | `raw=true` maps to `/text?mode=raw`; `format=text/plain` returns plain text; inherits the current `pinchtab_frame` scope for that tab |## Interactiondiff --git a/docs/reference/screenshot.md b/docs/reference/screenshot.mdindex 9ffed9b9..c4393a0e 100644--- a/docs/reference/screenshot.md+++ b/docs/reference/screenshot.md@@ -6,6 +6,12 @@ Capture the current page as an image. Defaults to **JPEG** format.# Get raw PNG bytescurl "http://localhost:9867/screenshot?format=png&raw=true" > page.png+# Capture a specific element (selector supports ref/CSS/XPath/text)+curl "http://localhost:9867/screenshot?selector=%23checkout-button&raw=true" > button.jpg++# Capture element at CSS 1x size (instead of device pixels)+curl "http://localhost:9867/screenshot?selector=%23checkout-button&css1x=true&raw=true" > button-1x.jpg+# Get JSON with base64 JPEG (default)curl "http://localhost:9867/screenshot"@@ -30,6 +36,8 @@ curl "http://localhost:9867/screenshot?output=file"- `format`: `jpeg` (default) or `png`.- `quality`: JPEG quality `0-100` (default: `80`). Ignored for PNG.+- `selector`: Unified selector to capture one element (e.g. `e5`, `#id`, `xpath://...`, `text:Submit`).+- `css1x`: `true` to output selector screenshots at CSS pixel size (1x). Ignored when `selector` is omitted.- `raw`: `true` to return image bytes directly instead of JSON.- `output`: `file` to save to state directory.- `tabId`: Target a specific tab.@@ -38,6 +46,8 @@ curl "http://localhost:9867/screenshot?output=file"- `-o <path>`: Save to specific path.- `-q <0-100>`: Set JPEG quality.+- `-s <selector>`: Capture a specific element.+- `--css-1x`: With `-s/--selector`, export at CSS 1x size.- `--tab <id>`: Target a specific tab.## Related Pagesdiff --git a/internal/cli/actions/actions_screenshot.go b/internal/cli/actions/actions_screenshot.goindex 20091411..8ba39c23 100644--- a/internal/cli/actions/actions_screenshot.go+++ b/internal/cli/actions/actions_screenshot.go@@ -19,6 +19,12 @@ func Screenshot(client *http.Client, base, token string, cmd *cobra.Command) {if v, _ := cmd.Flags().GetString("quality"); v != "" {params.Set("quality", v)}+ if v, _ := cmd.Flags().GetString("selector"); v != "" {+ params.Set("selector", v)+ }+ if v, _ := cmd.Flags().GetBool("css-1x"); v {+ params.Set("css1x", "true")+ }if v, _ := cmd.Flags().GetString("tab"); v != "" {params.Set("tabId", v)}diff --git a/internal/cli/actions/actions_screenshot_test.go b/internal/cli/actions/actions_screenshot_test.goindex bec0a036..c98a4afc 100644--- a/internal/cli/actions/actions_screenshot_test.go+++ b/internal/cli/actions/actions_screenshot_test.go@@ -19,6 +19,8 @@ func TestScreenshot(t *testing.T) {cmd := &cobra.Command{}cmd.Flags().String("output", outFile, "")cmd.Flags().String("quality", "50", "")+ cmd.Flags().String("selector", "#target", "")+ cmd.Flags().Bool("css-1x", true, "")cmd.Flags().String("tab", "", "")Screenshot(client, m.base(), "", cmd)if m.lastPath != "/screenshot" {@@ -27,6 +29,12 @@ func TestScreenshot(t *testing.T) {if !strings.Contains(m.lastQuery, "quality=50") {t.Errorf("expected quality=50, got %s", m.lastQuery)}+ if !strings.Contains(m.lastQuery, "selector=%23target") {+ t.Errorf("expected selector query, got %s", m.lastQuery)+ }+ if !strings.Contains(m.lastQuery, "css1x=true") {+ t.Errorf("expected css1x=true, got %s", m.lastQuery)+ }data, err := os.ReadFile(outFile)if err != nil {t.Fatalf("file not written: %v", err)diff --git a/internal/handlers/screenshot.go b/internal/handlers/screenshot.goindex 54957084..227599ea 100644--- a/internal/handlers/screenshot.go+++ b/internal/handlers/screenshot.go@@ -3,6 +3,7 @@ package handlersimport ("context""encoding/base64"+ "encoding/json""fmt""log/slog""net/http"@@ -32,6 +33,8 @@ func (h *Handlers) HandleScreenshot(w http.ResponseWriter, r *http.Request) {tabID := r.URL.Query().Get("tabId")output := r.URL.Query().Get("output")+ selector := r.URL.Query().Get("selector")+ css1x := r.URL.Query().Get("css1x") == "true"reqNoAnim := r.URL.Query().Get("noAnimations") == "true"ctx, resolvedTabID, err := h.tabContext(r, tabID)@@ -54,6 +57,20 @@ func (h *Handlers) HandleScreenshot(w http.ResponseWriter, r *http.Request) {}}+ var clip *page.Viewport+ if selector != "" {+ nodeID, err := h.resolveSelectorNodeID(tCtx, resolvedTabID, selector)+ if err != nil {+ httpx.Error(w, 400, frameScopedSelectorError("selector", err))+ return+ }+ clip, err = screenshotClipForNode(tCtx, nodeID, css1x)+ if err != nil {+ httpx.Error(w, 500, fmt.Errorf("selector screenshot: %w", err))+ return+ }+ }+var buf []bytequality := 80if q := r.URL.Query().Get("quality"); q != "" {@@ -76,6 +93,9 @@ func (h *Handlers) HandleScreenshot(w http.ResponseWriter, r *http.Request) {chromedp.ActionFunc(func(ctx context.Context) error {var err errorshot := page.CaptureScreenshot().WithFormat(format)+ if clip != nil {+ shot = shot.WithClip(clip)+ }if format == page.CaptureScreenshotFormatJpeg {shot = shot.WithQuality(int64(quality))}@@ -146,3 +166,112 @@ func (h *Handlers) HandleTabScreenshot(w http.ResponseWriter, r *http.Request) {h.HandleScreenshot(w, req)}++func screenshotClipForNode(ctx context.Context, nodeID int64, css1x bool) (*page.Viewport, error) {+ // Bring target element into view before computing clip coordinates.+ if err := 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)+ })); err != nil {+ return nil, fmt.Errorf("scroll into view: %w", err)+ }++ 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, fmt.Errorf("resolve node: %w", err)+ }++ var resolved struct {+ Object struct {+ ObjectID string `json:"objectId"`+ } `json:"object"`+ }+ if err := json.Unmarshal(resolveResult, &resolved); err != nil {+ return nil, fmt.Errorf("parse resolved node: %w", err)+ }+ if resolved.Object.ObjectID == "" {+ return nil, fmt.Errorf("element not found in DOM (backendNodeId=%d)", nodeID)+ }++ // Translate the element box into top-level viewport coordinates by walking+ // up frameElement bounds when inside same-origin iframes.+ const boxFn = `function() {+ const rect = this.getBoundingClientRect();+ let x = rect.left;+ let y = rect.top;+ try {+ let current = window;+ while (current && current.parent && current !== current.parent) {+ const frameEl = current.frameElement;+ if (!frameEl) {+ break;+ }+ const frameRect = frameEl.getBoundingClientRect();+ x += frameRect.left;+ y += frameRect.top;+ current = current.parent;+ }+ } catch (e) {+ // Cross-origin ancestors can block frame traversal. Keep local-frame+ // coordinates in that case; callers can still use frame scoping.+ }+ return {+ x,+ y,+ width: rect.width,+ height: rect.height,+ dpr: window.devicePixelRatio || 1+ };+ }`++ 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, fmt.Errorf("read element box: %w", err)+ }++ var boxCall struct {+ Result struct {+ Value struct {+ X float64 `json:"x"`+ Y float64 `json:"y"`+ Width float64 `json:"width"`+ Height float64 `json:"height"`+ DPR float64 `json:"dpr"`+ } `json:"value"`+ } `json:"result"`+ }+ if err := json.Unmarshal(callResult, &boxCall); err != nil {+ return nil, fmt.Errorf("parse element box: %w", err)+ }++ box := boxCall.Result.Value+ if box.Width <= 0 || box.Height <= 0 {+ return nil, fmt.Errorf("element box is empty (width=%.2f height=%.2f)", box.Width, box.Height)+ }+ scale := 1.0+ if css1x {+ if box.DPR <= 0 {+ box.DPR = 1+ }+ scale = 1 / box.DPR+ }++ return &page.Viewport{+ X: box.X,+ Y: box.Y,+ Width: box.Width,+ Height: box.Height,+ Scale: scale,+ }, nil+}diff --git a/internal/mcp/handlers_navigation.go b/internal/mcp/handlers_navigation.goindex c5ec6020..364f61f5 100644--- a/internal/mcp/handlers_navigation.go+++ b/internal/mcp/handlers_navigation.go@@ -121,6 +121,12 @@ func handleScreenshot(c *Client) func(context.Context, mcp.CallToolRequest) (*mcif format := optString(r, "format"); format != "" {q.Set("format", format)}+ if selector := optString(r, "selector"); selector != "" {+ q.Set("selector", selector)+ }+ if v, ok := optBool(r, "css1x"); ok && v {+ q.Set("css1x", "true")+ }if quality, ok := optFloat(r, "quality"); ok {q.Set("quality", fmt.Sprintf("%d", int(quality)))}diff --git a/internal/mcp/handlers_navigation_test.go b/internal/mcp/handlers_navigation_test.goindex 9b5cd501..5fa7a01d 100644--- a/internal/mcp/handlers_navigation_test.go+++ b/internal/mcp/handlers_navigation_test.go@@ -186,13 +186,21 @@ func TestHandleScreenshot(t *testing.T) {defer srv.Close()r := callTool(t, "pinchtab_screenshot", map[string]any{- "quality": float64(90),+ "quality": float64(90),+ "selector": "#hero",+ "css1x": true,}, srv)text := resultText(t, r)if !strings.Contains(text, "/screenshot") {t.Errorf("expected /screenshot, got %s", text)}+ if !strings.Contains(text, `"selector"`) {+ t.Errorf("expected selector query param, got %s", text)+ }+ if !strings.Contains(text, `"css1x"`) {+ t.Errorf("expected css1x query param, got %s", text)+ }}func TestHandleGetText(t *testing.T) {diff --git a/internal/mcp/tools.go b/internal/mcp/tools.goindex 2dd17e1c..570c5e1e 100644--- a/internal/mcp/tools.go+++ b/internal/mcp/tools.go@@ -31,8 +31,10 @@ func allTools() []mcp.Tool {mcp.NewTool("pinchtab_screenshot",mcp.WithDescription("Take a screenshot of the current page"),mcp.WithString("tabId", mcp.Description("Target tab ID")),+ mcp.WithString("selector", mcp.Description("Unified selector to capture a specific element (CSS, XPath, text, or ref). Selectors resolve in the current frame scope.")),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.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."),