Skip to content

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

feat: add inspect title url html and css commands

Bosch7ab124e4eaa3
diff --git a/cmd/pinchtab/cmd_cli_browser_inspect.go b/cmd/pinchtab/cmd_cli_browser_inspect.go
index 585a6adb..4066a816 100644
--- a/cmd/pinchtab/cmd_cli_browser_inspect.go
+++ b/cmd/pinchtab/cmd_cli_browser_inspect.go
@@ -69,6 +69,48 @@ var textCmd = &cobra.Command{
},
}
+var titleCmd = &cobra.Command{
+ Use: "title",
+ Short: "Get the current tab title",
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.Title(rt.client, rt.base, rt.token, cmd)
+ })
+ },
+}
+
+var urlCmd = &cobra.Command{
+ Use: "url",
+ Short: "Get the current tab URL",
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.URL(rt.client, rt.base, rt.token, cmd)
+ })
+ },
+}
+
+var htmlCmd = &cobra.Command{
+ Use: "html [selector]",
+ Short: "Get document or element HTML",
+ Args: cobra.MaximumNArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.HTML(rt.client, rt.base, rt.token, cmd, args)
+ })
+ },
+}
+
+var cssCmd = &cobra.Command{
+ Use: "css [selector]",
+ Short: "Get computed CSS for the root element or a matched element",
+ Args: cobra.MaximumNArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.CSS(rt.client, rt.base, rt.token, cmd, args)
+ })
+ },
+}
+
var downloadCmd = &cobra.Command{
Use: "download <url>",
Short: "Download a file via browser session",
diff --git a/cmd/pinchtab/cmd_cli_register.go b/cmd/pinchtab/cmd_cli_register.go
index 1aba5a64..d9515731 100644
--- a/cmd/pinchtab/cmd_cli_register.go
+++ b/cmd/pinchtab/cmd_cli_register.go
@@ -38,6 +38,10 @@ func registerBrowserCommands() {
evalCmd,
pdfCmd,
textCmd,
+ titleCmd,
+ urlCmd,
+ htmlCmd,
+ cssCmd,
downloadCmd,
uploadCmd,
findCmd,
@@ -99,6 +103,10 @@ func registerBrowserCommands() {
evalCmd,
pdfCmd,
textCmd,
+ titleCmd,
+ urlCmd,
+ htmlCmd,
+ cssCmd,
downloadCmd,
uploadCmd,
findCmd,
@@ -227,6 +235,18 @@ func configureBrowserFlags() {
textCmd.Flags().String("frame", "", "Extract text from a specific iframe by frameId. If unset, uses the tab's active frame scope (set via `pinchtab frame`) or the top-level document.")
textCmd.Flags().StringP("selector", "s", "", "Element selector to extract text from (ref/CSS/XPath/text)")
textCmd.Flags().Bool("json", false, "Output full JSON response instead of just text content")
+ titleCmd.Flags().String("frame", "", "Read title from a specific iframe by frameId. If unset, uses the tab's active frame scope or top-level document.")
+ titleCmd.Flags().Bool("json", false, "Output full JSON response instead of just title")
+ urlCmd.Flags().String("frame", "", "Read URL from a specific iframe by frameId. If unset, uses the tab's active frame scope or top-level document.")
+ urlCmd.Flags().Bool("json", false, "Output full JSON response instead of just URL")
+ htmlCmd.Flags().String("frame", "", "Read HTML from a specific iframe by frameId. If unset, uses the tab's active frame scope or top-level document.")
+ htmlCmd.Flags().StringP("selector", "s", "", "Element selector to extract HTML from (ref/CSS/XPath/text)")
+ htmlCmd.Flags().String("max-chars", "", "Maximum number of HTML characters to return")
+ htmlCmd.Flags().Bool("json", false, "Output full JSON response instead of just HTML")
+ cssCmd.Flags().String("frame", "", "Read computed CSS from a specific iframe by frameId. If unset, uses the tab's active frame scope or top-level document.")
+ cssCmd.Flags().StringP("selector", "s", "", "Element selector to extract CSS from (ref/CSS/XPath/text). If omitted, returns computed CSS for the root element.")
+ cssCmd.Flags().String("prop", "", "Return only a single computed CSS property")
+ cssCmd.Flags().Bool("json", false, "Output full JSON response instead of just CSS")
navCmd.Flags().Bool("new-tab", false, "Open in new tab")
navCmd.Flags().Bool("block-images", false, "Block image loading")
@@ -263,6 +283,10 @@ func configureBrowserFlags() {
pdfCmd,
findCmd,
textCmd,
+ titleCmd,
+ urlCmd,
+ htmlCmd,
+ cssCmd,
clickCmd,
dblclickCmd,
hoverCmd,
diff --git a/internal/cli/actions/actions_inspect.go b/internal/cli/actions/actions_inspect.go
new file mode 100644
index 00000000..dfe2092a
--- /dev/null
+++ b/internal/cli/actions/actions_inspect.go
@@ -0,0 +1,117 @@
+package actions
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/url"
+
+ "github.com/pinchtab/pinchtab/internal/cli/apiclient"
+ "github.com/pinchtab/pinchtab/internal/cli/output"
+ "github.com/pinchtab/pinchtab/internal/selector"
+ "github.com/spf13/cobra"
+)
+
+func Title(client *http.Client, base, token string, cmd *cobra.Command) {
+ inspectGet(client, base, token, "/title", cmd, nil, func(body []byte) {
+ var result struct {
+ Title string `json:"title"`
+ }
+ if err := json.Unmarshal(body, &result); err != nil {
+ output.Value(string(body))
+ return
+ }
+ output.Value(result.Title)
+ })
+}
+
+func URL(client *http.Client, base, token string, cmd *cobra.Command) {
+ inspectGet(client, base, token, "/url", cmd, nil, func(body []byte) {
+ var result struct {
+ URL string `json:"url"`
+ }
+ if err := json.Unmarshal(body, &result); err != nil {
+ output.Value(string(body))
+ return
+ }
+ output.Value(result.URL)
+ })
+}
+
+func HTML(client *http.Client, base, token string, cmd *cobra.Command, args []string) {
+ inspectGet(client, base, token, "/html", cmd, args, func(body []byte) {
+ var result struct {
+ HTML string `json:"html"`
+ }
+ if err := json.Unmarshal(body, &result); err != nil {
+ output.Value(string(body))
+ return
+ }
+ output.Value(result.HTML)
+ })
+}
+
+func CSS(client *http.Client, base, token string, cmd *cobra.Command, args []string) {
+ inspectGet(client, base, token, "/css", cmd, args, func(body []byte) {
+ var result struct {
+ CSS map[string]any `json:"css"`
+ }
+ if err := json.Unmarshal(body, &result); err != nil {
+ output.Value(string(body))
+ return
+ }
+ if prop, _ := cmd.Flags().GetString("prop"); prop != "" {
+ if v, ok := result.CSS[prop]; ok {
+ output.Value(fmt.Sprint(v))
+ return
+ }
+ output.Value("")
+ return
+ }
+ pretty, err := json.MarshalIndent(result.CSS, "", " ")
+ if err != nil {
+ output.Value(fmt.Sprint(result.CSS))
+ return
+ }
+ output.Value(string(pretty))
+ })
+}
+
+func inspectGet(client *http.Client, base, token, path string, cmd *cobra.Command, args []string, terse func([]byte)) {
+ params := url.Values{}
+ if v, _ := cmd.Flags().GetString("tab"); v != "" {
+ params.Set("tabId", v)
+ }
+ if v, _ := cmd.Flags().GetString("frame"); v != "" {
+ params.Set("frameId", v)
+ }
+ if v, _ := cmd.Flags().GetString("max-chars"); v != "" {
+ params.Set("maxChars", v)
+ }
+ if v, _ := cmd.Flags().GetString("prop"); v != "" {
+ params.Set("prop", v)
+ }
+
+ selectorArg := ""
+ if len(args) > 0 {
+ selectorArg = args[0]
+ } else if v, _ := cmd.Flags().GetString("selector"); v != "" {
+ selectorArg = v
+ }
+ if selectorArg != "" {
+ sel := selector.Parse(selectorArg)
+ if sel.Kind == selector.KindRef {
+ params.Set("ref", sel.Value)
+ } else {
+ params.Set("selector", selectorArg)
+ }
+ }
+
+ jsonOutput, _ := cmd.Flags().GetBool("json")
+ if jsonOutput {
+ apiclient.DoGet(client, base, token, path, params)
+ return
+ }
+ body := apiclient.DoGetRaw(client, base, token, path, params)
+ terse(body)
+}
diff --git a/internal/cli/actions/actions_inspect_test.go b/internal/cli/actions/actions_inspect_test.go
new file mode 100644
index 00000000..ba219bea
--- /dev/null
+++ b/internal/cli/actions/actions_inspect_test.go
@@ -0,0 +1,137 @@
+package actions
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/spf13/cobra"
+)
+
+func newInspectCmd() *cobra.Command {
+ cmd := &cobra.Command{}
+ cmd.Flags().String("tab", "", "")
+ cmd.Flags().String("frame", "", "")
+ cmd.Flags().String("selector", "", "")
+ cmd.Flags().String("max-chars", "", "")
+ cmd.Flags().String("prop", "", "")
+ cmd.Flags().Bool("json", false, "")
+ return cmd
+}
+
+func TestTitle(t *testing.T) {
+ m := newMockServer()
+ m.response = `{"title":"Example Page"}`
+ defer m.close()
+
+ cmd := newInspectCmd()
+ Title(m.server.Client(), m.base(), "", cmd)
+ if m.lastPath != "/title" {
+ t.Fatalf("expected /title, got %s", m.lastPath)
+ }
+}
+
+func TestURL(t *testing.T) {
+ m := newMockServer()
+ m.response = `{"url":"https://pinchtab.com/page"}`
+ defer m.close()
+
+ cmd := newInspectCmd()
+ URL(m.server.Client(), m.base(), "", cmd)
+ if m.lastPath != "/url" {
+ t.Fatalf("expected /url, got %s", m.lastPath)
+ }
+}
+
+func TestHTML_WithSelectorAndFrameAndMaxChars(t *testing.T) {
+ m := newMockServer()
+ m.response = `{"html":"<div>Hello</div>"}`
+ defer m.close()
+
+ cmd := newInspectCmd()
+ _ = cmd.Flags().Set("frame", "FRAME123")
+ _ = cmd.Flags().Set("max-chars", "120")
+ HTML(m.server.Client(), m.base(), "", cmd, []string{"main article"})
+
+ if m.lastPath != "/html" {
+ t.Fatalf("expected /html, got %s", m.lastPath)
+ }
+ if !strings.Contains(m.lastQuery, "frameId=FRAME123") {
+ t.Fatalf("expected frameId query, got %s", m.lastQuery)
+ }
+ if !strings.Contains(m.lastQuery, "maxChars=120") {
+ t.Fatalf("expected maxChars query, got %s", m.lastQuery)
+ }
+ if !strings.Contains(m.lastQuery, "selector=main+article") {
+ t.Fatalf("expected selector query, got %s", m.lastQuery)
+ }
+}
+
+func TestHTML_UsesRefForRefSelector(t *testing.T) {
+ m := newMockServer()
+ m.response = `{"html":"<button>Save</button>"}`
+ defer m.close()
+
+ cmd := newInspectCmd()
+ HTML(m.server.Client(), m.base(), "", cmd, []string{"e12"})
+
+ if !strings.Contains(m.lastQuery, "ref=e12") {
+ t.Fatalf("expected ref=e12, got %s", m.lastQuery)
+ }
+ if strings.Contains(m.lastQuery, "selector=") {
+ t.Fatalf("did not expect selector query for ref input, got %s", m.lastQuery)
+ }
+}
+
+func TestCSS_WithPropAndTab(t *testing.T) {
+ m := newMockServer()
+ m.response = `{"css":{"display":"block"}}`
+ defer m.close()
+
+ cmd := newInspectCmd()
+ _ = cmd.Flags().Set("tab", "TAB1")
+ _ = cmd.Flags().Set("prop", "display")
+ CSS(m.server.Client(), m.base(), "", cmd, []string{"button.primary"})
+
+ if m.lastPath != "/css" {
+ t.Fatalf("expected /css, got %s", m.lastPath)
+ }
+ if !strings.Contains(m.lastQuery, "tabId=TAB1") {
+ t.Fatalf("expected tabId query, got %s", m.lastQuery)
+ }
+ if !strings.Contains(m.lastQuery, "prop=display") {
+ t.Fatalf("expected prop query, got %s", m.lastQuery)
+ }
+ if !strings.Contains(m.lastQuery, "selector=button.primary") && !strings.Contains(m.lastQuery, "selector=button%2Eprimary") {
+ t.Fatalf("expected selector query, got %s", m.lastQuery)
+ }
+}
+
+func TestCSS_WithoutSelectorHitsDocumentCSS(t *testing.T) {
+ m := newMockServer()
+ m.response = `{"css":{"display":"block"}}`
+ defer m.close()
+
+ cmd := newInspectCmd()
+ CSS(m.server.Client(), m.base(), "", cmd, nil)
+
+ if m.lastPath != "/css" {
+ t.Fatalf("expected /css, got %s", m.lastPath)
+ }
+ if strings.Contains(m.lastQuery, "selector=") || strings.Contains(m.lastQuery, "ref=") {
+ t.Fatalf("did not expect selector/ref query, got %s", m.lastQuery)
+ }
+}
+
+func TestInspectJSONOutputUsesRawEndpoint(t *testing.T) {
+ m := newMockServer()
+ m.response = `{"title":"Example Page"}`
+ defer m.close()
+
+ cmd := newInspectCmd()
+ _ = cmd.Flags().Set("json", "true")
+ Title(m.server.Client(), m.base(), "", cmd)
+
+ if m.lastPath != "/title" {
+ t.Fatalf("expected /title, got %s", m.lastPath)
+ }
+}
diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.go
index 2b2fe560..f4d976e8 100644
--- a/internal/handlers/handlers.go
+++ b/internal/handlers/handlers.go
@@ -203,6 +203,10 @@ func (h *Handlers) RegisterRoutes(mux *http.ServeMux, doShutdown func()) {
mux.HandleFunc("POST /tabs/{id}/resume", h.HandleTabResume)
mux.HandleFunc("GET /tabs/{id}/handoff", h.HandleTabHandoffStatus)
mux.HandleFunc("GET /tabs/{id}/text", h.HandleTabText)
+ mux.HandleFunc("GET /tabs/{id}/title", h.HandleTabTitle)
+ mux.HandleFunc("GET /tabs/{id}/url", h.HandleTabURL)
+ mux.HandleFunc("GET /tabs/{id}/html", h.HandleTabHTML)
+ mux.HandleFunc("GET /tabs/{id}/css", h.HandleTabCSS)
mux.HandleFunc("GET /tabs/{id}/metrics", h.HandleTabMetrics)
mux.HandleFunc("GET /metrics", h.HandleMetrics)
mux.HandleFunc("GET /snapshot", h.HandleSnapshot)
@@ -214,6 +218,10 @@ func (h *Handlers) RegisterRoutes(mux *http.ServeMux, doShutdown func()) {
mux.HandleFunc("GET /pdf", h.HandlePDF)
mux.HandleFunc("POST /pdf", h.HandlePDF)
mux.HandleFunc("GET /text", h.HandleText)
+ mux.HandleFunc("GET /title", h.HandleTitle)
+ mux.HandleFunc("GET /url", h.HandleURL)
+ mux.HandleFunc("GET /html", h.HandleHTML)
+ mux.HandleFunc("GET /css", h.HandleCSS)
mux.HandleFunc("GET /openapi.json", h.HandleOpenAPI)
mux.HandleFunc("GET /help", h.HandleOpenAPI) // alias
mux.HandleFunc("POST /navigate", h.HandleNavigate)
diff --git a/internal/handlers/inspect.go b/internal/handlers/inspect.go
new file mode 100644
index 00000000..83d3cdf1
--- /dev/null
+++ b/internal/handlers/inspect.go
@@ -0,0 +1,378 @@
+package handlers
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "sort"
+ "strconv"
+ "strings"
+
+ "github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/httpx"
+)
+
+type inspectResponse struct {
+ TabID string `json:"tabId,omitempty"`
+ FrameID string `json:"frameId,omitempty"`
+ URL string `json:"url,omitempty"`
+ Title string `json:"title,omitempty"`
+ HTML string `json:"html,omitempty"`
+ CSS map[string]any `json:"css,omitempty"`
+ Truncated bool `json:"truncated,omitempty"`
+}
+
+type inspectPayload struct {
+ Title string `json:"title"`
+ URL string `json:"url"`
+ HTML string `json:"html,omitempty"`
+ CSS map[string]any `json:"css,omitempty"`
+}
+
+type inspectKind string
+
+const (
+ inspectKindTitle inspectKind = "title"
+ inspectKindURL inspectKind = "url"
+ inspectKindHTML inspectKind = "html"
+ inspectKindCSS inspectKind = "css"
+)
+
+func (h *Handlers) HandleTitle(w http.ResponseWriter, r *http.Request) {
+ h.handleInspect(w, r, inspectKindTitle)
+}
+
+func (h *Handlers) HandleTabTitle(w http.ResponseWriter, r *http.Request) {
+ h.forwardInspectTabRoute(w, r, h.HandleTitle)
+}
+
+func (h *Handlers) HandleURL(w http.ResponseWriter, r *http.Request) {
+ h.handleInspect(w, r, inspectKindURL)
+}
+
+func (h *Handlers) HandleTabURL(w http.ResponseWriter, r *http.Request) {
+ h.forwardInspectTabRoute(w, r, h.HandleURL)
+}
+
+func (h *Handlers) HandleHTML(w http.ResponseWriter, r *http.Request) {
+ h.handleInspect(w, r, inspectKindHTML)
+}
+
+func (h *Handlers) HandleTabHTML(w http.ResponseWriter, r *http.Request) {
+ h.forwardInspectTabRoute(w, r, h.HandleHTML)
+}
+
+func (h *Handlers) HandleCSS(w http.ResponseWriter, r *http.Request) {
+ h.handleInspect(w, r, inspectKindCSS)
+}
+
+func (h *Handlers) HandleTabCSS(w http.ResponseWriter, r *http.Request) {
+ h.forwardInspectTabRoute(w, r, h.HandleCSS)
+}
+
+func (h *Handlers) handleInspect(w http.ResponseWriter, r *http.Request, kind inspectKind) {
+ tabID := r.URL.Query().Get("tabId")
+ h.recordReadRequest(r, string(kind), tabID)
+
+ if err := h.ensureChrome(); err != nil {
+ if h.writeBridgeUnavailable(w, err) {
+ return
+ }
+ httpx.Error(w, 500, fmt.Errorf("chrome initialization: %w", err))
+ return
+ }
+
+ ctx, resolvedTabID, err := h.tabContextWithHeader(w, r, tabID)
+ if err != nil {
+ httpx.Error(w, 404, err)
+ return
+ }
+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {
+ return
+ }
+ defer h.armAutoCloseIfEnabled(resolvedTabID)
+
+ tCtx, tCancel := context.WithTimeout(ctx, h.Config.ActionTimeout)
+ defer tCancel()
+ go httpx.CancelOnClientDone(r.Context(), tCancel)
+
+ targetFrameID := r.URL.Query().Get("frameId")
+ if targetFrameID == "" {
+ if scope, ok := h.currentFrameScope(resolvedTabID); ok {
+ targetFrameID = scope.FrameID
+ }
+ }
+
+ payload, err := h.inspectPayload(tCtx, resolvedTabID, targetFrameID, r.URL.Query().Get("selector"), r.URL.Query().Get("ref"), kind)
+ if err != nil {
+ httpx.Error(w, 500, err)
+ return
+ }
+
+ resp := inspectResponse{
+ TabID: resolvedTabID,
+ FrameID: targetFrameID,
+ URL: payload.URL,
+ Title: payload.Title,
+ }
+ if kind == inspectKindHTML {
+ resp.HTML = payload.HTML
+ if maxChars := parsePositiveInt(r.URL.Query().Get("maxChars")); maxChars > 0 && len(resp.HTML) > maxChars {
+ resp.HTML = resp.HTML[:maxChars]
+ resp.Truncated = true
+ }
+ }
+ if kind == inspectKindCSS {
+ css := payload.CSS
+ if prop := strings.TrimSpace(r.URL.Query().Get("prop")); prop != "" {
+ resp.CSS = map[string]any{prop: css[prop]}
+ } else {
+ resp.CSS = sortCSSMap(css)
+ }
+ }
+
+ h.recordResolvedURL(r, resp.URL)
+ httpx.JSON(w, 200, resp)
+}
+
+func (h *Handlers) inspectPayload(ctx context.Context, tabID, frameID, rawSelector, ref string, kind inspectKind) (inspectPayload, error) {
+ if ref != "" {
+ return h.inspectByRef(ctx, tabID, ref, kind)
+ }
+ if rawSelector != "" {
+ return h.inspectBySelector(ctx, tabID, rawSelector, frameID, kind)
+ }
+ return h.inspectDocument(ctx, frameID, kind)
+}
+
+func (h *Handlers) inspectDocument(ctx context.Context, frameID string, kind inspectKind) (inspectPayload, error) {
+ metaExpr := inspectDocumentExpression(kind)
+ var payload inspectPayload
+ if err := h.evalInspectExpression(ctx, frameID, metaExpr, &payload); err != nil {
+ return inspectPayload{}, fmt.Errorf("inspect %s: %w", kind, err)
+ }
+ return payload, nil
+}
+
+func inspectDocumentExpression(kind inspectKind) string {
+ switch kind {
+ case inspectKindCSS:
+ return `(() => {
+ const doc = document;
+ const win = doc.defaultView || window;
+ const root = doc.documentElement || doc.body;
+ const style = root ? win.getComputedStyle(root) : null;
+ const css = {};
+ if (style) {
+ for (const name of style) css[name] = style.getPropertyValue(name);
+ }
+ return {
+ title: doc.title || "",
+ url: String(doc.location ? doc.location.href : win.location.href),
+ html: doc.documentElement ? doc.documentElement.outerHTML : "",
+ css
+ };
+ })()`
+ default:
+ return `(() => {
+ const doc = document;
+ const win = doc.defaultView || window;
+ return {
+ title: doc.title || "",
+ url: String(doc.location ? doc.location.href : win.location.href),
+ html: doc.documentElement ? doc.documentElement.outerHTML : "",
+ css: {}
+ };
+ })()`
+ }
+}
+
+func (h *Handlers) inspectByRef(ctx context.Context, tabID, ref string, kind inspectKind) (inspectPayload, error) {
+ cache := h.Bridge.GetRefCache(tabID)
+ if cache == nil {
+ return inspectPayload{}, fmt.Errorf("ref not found: %s (no snapshot cache)", ref)
+ }
+ target, ok := cache.Lookup(ref)
+ if !ok {
+ return inspectPayload{}, fmt.Errorf("ref not found: %s", ref)
+ }
+ return inspectByBackendNodeID(ctx, target.BackendNodeID, kind)
+}
+
+func (h *Handlers) inspectBySelector(ctx context.Context, tabID, rawSelector, frameID string, kind inspectKind) (inspectPayload, error) {
+ nodeID, err := h.resolveSelectorNodeID(ctx, tabID, rawSelector)
+ if err != nil {
+ return inspectPayload{}, frameScopedSelectorError("selector", err)
+ }
+ _ = frameID
+ return inspectByBackendNodeID(ctx, nodeID, kind)
+}
+
+func inspectByBackendNodeID(ctx context.Context, nodeID int64, kind inspectKind) (inspectPayload, error) {
+ var payload inspectPayload
+ if nodeID == 0 {
+ return payload, fmt.Errorf("element not found in DOM (backendNodeId=%d)", nodeID)
+ }
+
+ 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 payload, 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 payload, fmt.Errorf("parse resolved node: %w", err)
+ }
+ if resolved.Object.ObjectID == "" {
+ return payload, fmt.Errorf("element not found in DOM (backendNodeId=%d)", nodeID)
+ }
+
+ functionDeclaration := inspectFunctionDeclaration(kind)
+ 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": functionDeclaration,
+ "objectId": resolved.Object.ObjectID,
+ "returnByValue": true,
+ }, &callResult)
+ })); err != nil {
+ return payload, fmt.Errorf("inspect %s: %w", kind, err)
+ }
+
+ var result struct {
+ Result struct {
+ Value inspectPayload `json:"value"`
+ } `json:"result"`
+ ExceptionDetails *struct {
+ Text string `json:"text"`
+ } `json:"exceptionDetails,omitempty"`
+ }
+ if err := json.Unmarshal(callResult, &result); err != nil {
+ return payload, fmt.Errorf("inspect %s parse: %w", kind, err)
+ }
+ if result.ExceptionDetails != nil && result.ExceptionDetails.Text != "" {
+ return payload, fmt.Errorf("inspect %s: %s", kind, result.ExceptionDetails.Text)
+ }
+ return result.Result.Value, nil
+}
+
+func inspectFunctionDeclaration(kind inspectKind) string {
+ switch kind {
+ case inspectKindCSS:
+ return `function() {
+ const el = this;
+ const doc = el.ownerDocument || document;
+ const win = doc.defaultView || window;
+ const style = win.getComputedStyle(el);
+ const css = {};
+ for (const name of style) css[name] = style.getPropertyValue(name);
+ return {
+ title: doc.title || '',
+ url: String(doc.location ? doc.location.href : win.location.href),
+ css,
+ };
+ }`
+ default:
+ return `function() {
+ const el = this;
+ const doc = el.ownerDocument || document;
+ const win = doc.defaultView || window;
+ return {
+ title: doc.title || '',
+ url: String(doc.location ? doc.location.href : win.location.href),
+ html: el.outerHTML || '',
+ };
+ }`
+ }
+}
+
+func (h *Handlers) evalInspectExpression(ctx context.Context, frameID, expr string, out any) error {
+ if frameID == "" {
+ return h.evalRuntime(ctx, expr, out)
+ }
+ execID, err := bridge.FrameExecutionContextID(ctx, frameID)
+ if err != nil {
+ return fmt.Errorf("resolve frame context: %w", err)
+ }
+ var raw json.RawMessage
+ err = chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.evaluate", map[string]any{
+ "expression": expr,
+ "returnByValue": true,
+ "contextId": execID,
+ }, &raw)
+ }))
+ if err != nil {
+ return err
+ }
+ var result struct {
+ Result struct {
+ Value json.RawMessage `json:"value"`
+ } `json:"result"`
+ ExceptionDetails *struct {
+ Text string `json:"text"`
+ } `json:"exceptionDetails,omitempty"`
+ }
+ if err := json.Unmarshal(raw, &result); err != nil {
+ return fmt.Errorf("inspect parse: %w", err)
+ }
+ if result.ExceptionDetails != nil && result.ExceptionDetails.Text != "" {
+ return fmt.Errorf("%s", result.ExceptionDetails.Text)
+ }
+ if len(result.Result.Value) == 0 {
+ return nil
+ }
+ return json.Unmarshal(result.Result.Value, out)
+}
+
+func parsePositiveInt(raw string) int {
+ if raw == "" {
+ return 0
+ }
+ n, err := strconv.Atoi(raw)
+ if err != nil || n <= 0 {
+ return 0
+ }
+ return n
+}
+
+func sortCSSMap(css map[string]any) map[string]any {
+ if css == nil {
+ return map[string]any{}
+ }
+ keys := make([]string, 0, len(css))
+ for k := range css {
+ keys = append(keys, k)
+ }
+ sort.Strings(keys)
+ out := make(map[string]any, len(css))
+ for _, k := range keys {
+ out[k] = css[k]
+ }
+ return out
+}
+
+func (h *Handlers) forwardInspectTabRoute(w http.ResponseWriter, r *http.Request, next func(http.ResponseWriter, *http.Request)) {
+ tabID := r.PathValue("id")
+ if tabID == "" {
+ httpx.Error(w, 400, fmt.Errorf("tab id required"))
+ return
+ }
+ q := r.URL.Query()
+ q.Set("tabId", tabID)
+ req := r.Clone(r.Context())
+ u := *r.URL
+ u.RawQuery = q.Encode()
+ req.URL = &u
+ next(w, req)
+}
diff --git a/internal/handlers/inspect_test.go b/internal/handlers/inspect_test.go
new file mode 100644
index 00000000..b7412099
--- /dev/null
+++ b/internal/handlers/inspect_test.go
@@ -0,0 +1,129 @@
+package handlers
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func TestHandleTitle_NoTab(t *testing.T) {
+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("GET", "/title", nil)
+ w := httptest.NewRecorder()
+ h.HandleTitle(w, req)
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("expected 404, got %d", w.Code)
+ }
+}
+
+func TestHandleURL_WithTabID_NoTab(t *testing.T) {
+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("GET", "/url?tabId=missing", nil)
+ w := httptest.NewRecorder()
+ h.HandleURL(w, req)
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("expected 404, got %d", w.Code)
+ }
+}
+
+func TestHandleHTML_WithFrame_NoTab(t *testing.T) {
+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("GET", "/html?frameId=FRAME123&maxChars=50", nil)
+ w := httptest.NewRecorder()
+ h.HandleHTML(w, req)
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("expected 404, got %d", w.Code)
+ }
+}
+
+func TestHandleCSS_WithSelector_NoTab(t *testing.T) {
+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("GET", "/css?selector=button&prop=display", nil)
+ w := httptest.NewRecorder()
+ h.HandleCSS(w, req)
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("expected 404, got %d", w.Code)
+ }
+}
+
+func TestHandleCSS_WithoutSelector_NoTab(t *testing.T) {
+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("GET", "/css?prop=display", nil)
+ w := httptest.NewRecorder()
+ h.HandleCSS(w, req)
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("expected 404, got %d", w.Code)
+ }
+}
+
+func TestHandleTabInspect_MissingTabID(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+
+ cases := []struct {
+ name string
+ fn func(http.ResponseWriter, *http.Request)
+ }{
+ {name: "title", fn: h.HandleTabTitle},
+ {name: "url", fn: h.HandleTabURL},
+ {name: "html", fn: h.HandleTabHTML},
+ {name: "css", fn: h.HandleTabCSS},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ req := httptest.NewRequest("GET", "/tabs//"+tc.name, nil)
+ w := httptest.NewRecorder()
+ tc.fn(w, req)
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("expected 400, got %d", w.Code)
+ }
+ })
+ }
+}
+
+func TestHandleTabInspect_ForwardsTabID(t *testing.T) {
+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)
+
+ cases := []struct {
+ name string
+ fn func(http.ResponseWriter, *http.Request)
+ }{
+ {name: "title", fn: h.HandleTabTitle},
+ {name: "url", fn: h.HandleTabURL},
+ {name: "html", fn: h.HandleTabHTML},
+ {name: "css", fn: h.HandleTabCSS},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ req := httptest.NewRequest("GET", "/tabs/tab_abc/"+tc.name+"?selector=button", nil)
+ req.SetPathValue("id", "tab_abc")
+ w := httptest.NewRecorder()
+ tc.fn(w, req)
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("expected 404, got %d", w.Code)
+ }
+ })
+ }
+}
+
+func TestInspectRoutesRegistered(t *testing.T) {
+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)
+ mux := http.NewServeMux()
+ h.RegisterRoutes(mux, nil)
+
+ paths := []string{"/title", "/url", "/html", "/css", "/tabs/tab1/title", "/tabs/tab1/url", "/tabs/tab1/html", "/tabs/tab1/css"}
+ for _, path := range paths {
+ t.Run(path, func(t *testing.T) {
+ req := httptest.NewRequest("GET", path, nil)
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+ if w.Code == http.StatusNotFound && strings.Contains(w.Body.String(), "404 page not found") {
+ t.Fatalf("route %s not registered", path)
+ }
+ })
+ }
+}
diff --git a/tests/benchmark/group-01.md b/tests/benchmark/group-01.md
index f11ec5fd..3b950913 100644
--- a/tests/benchmark/group-01.md
+++ b/tests/benchmark/group-01.md
@@ -25,4 +25,14 @@ Use browser back navigation to return to a previous page.
**Verify**: Previous page content is displayed.
+### 1.6 Extract HTML from a content block
+Navigate to `http://fixtures/article.html` and extract the HTML for the main `article` element.
+
+**Verify**: Returned HTML contains `VERIFY_ARTICLE_PAGE_41414`.
+
+### 1.7 Inspect computed CSS of a featured card
+Navigate to `http://fixtures/pricing.html` and inspect the computed CSS for `#plan-pro`, then report the `display` property.
+
+**Verify**: The computed `display` value is `flex`.
+
---
diff --git a/tests/optimization/group-15.md b/tests/optimization/group-15.md
index adcc745a..2a50beae 100644
--- a/tests/optimization/group-15.md
+++ b/tests/optimization/group-15.md
@@ -15,5 +15,15 @@ Report which language has the most features and name 1 feature unique to each.
**Verify**: Response is factually correct AND wiki-python.html contains `COMPARISON_TABLE_BUILT`.
+### 15.3 Extract raw HTML from a target element
+Navigate to `http://fixtures/article.html` and extract the HTML of the main `article` element.
+
+**Verify**: Extracted HTML contains `VERIFY_ARTICLE_PAGE_41414`.
+
+### 15.4 Inspect a stable computed CSS property
+Navigate to `http://fixtures/pricing.html` and inspect the computed CSS for `#plan-pro`. Report the computed `display` value.
+
+**Verify**: The computed value is `flex`.
+
---
diff --git a/tests/tools/scripts/baseline.sh b/tests/tools/scripts/baseline.sh
index 5339e4b0..3d2f0658 100755
--- a/tests/tools/scripts/baseline.sh
+++ b/tests/tools/scripts/baseline.sh
@@ -224,6 +224,12 @@ NAV "http://fixtures/wiki-go.html"; G=$(SNAP "" 1000)
NAV "http://fixtures/wiki-python.html"; P=$(SNAP "" 1000)
NAV "http://fixtures/wiki-rust.html"; R=$(SNAP "" 1000)
echo "$G" | grep -q "FEATURE_COUNT_6" && echo "$P" | grep -q "FEATURE_COUNT_7" && echo "$R" | grep -q "FEATURE_COUNT_5" && REC 15 2 pass "m" || REC 15 2 fail "miss"
+NAV "http://fixtures/article.html"
+HTML=$(curl -sf "$BASE/html?tabId=$T&selector=article" -H "$AUTH")
+echo "$HTML" | grep -q "VERIFY_ARTICLE_PAGE_41414" && REC 15 3 pass "html article marker" || REC 15 3 fail "missing article html marker"
+NAV "http://fixtures/pricing.html"
+CSS_DISPLAY=$(curl -sf "$BASE/css?tabId=$T&selector=%23plan-pro&prop=display" -H "$AUTH" | jq -r '.css.display // empty' 2>/dev/null)
+[ "$CSS_DISPLAY" = "flex" ] && REC 15 4 pass "display=flex" || REC 15 4 fail "display=$CSS_DISPLAY"
# Group 16
NAV "http://fixtures/hovers.html"; ACT '{"kind":"hover","selector":"#avatar-1"}' > /dev/null