Skip to content

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

feat: add GET /timing endpoint with navigation timing and core web vitals

Luigi Agosti460e85063e9d
diff --git a/internal/bridge/observe/timing.go b/internal/bridge/observe/timing.go
new file mode 100644
index 00000000..45b554d5
--- /dev/null
+++ b/internal/bridge/observe/timing.go
@@ -0,0 +1,104 @@
+package observe
+
+// TimingMetrics holds navigation timing, Core Web Vitals, and the resource
+// loading breakdown for a page. All durations are milliseconds relative to
+// navigation start.
+type TimingMetrics struct {
+ TTFBMs float64 `json:"ttfbMs"`
+ FCPMs float64 `json:"fcpMs"`
+ LCPMs float64 `json:"lcpMs"`
+ CLS float64 `json:"cls"`
+ DOMContentLoadedMs float64 `json:"domContentLoadedMs"`
+ LoadMs float64 `json:"loadMs"`
+ ResourceCount int `json:"resourceCount"`
+ TransferSizeBytes int64 `json:"transferSizeBytes"`
+}
+
+// rawTiming is the JSON shape TimingScript resolves to.
+type rawTiming struct {
+ TTFB float64 `json:"ttfb"`
+ FCP float64 `json:"fcp"`
+ LCP float64 `json:"lcp"`
+ CLS float64 `json:"cls"`
+ DOMContentLoaded float64 `json:"domContentLoaded"`
+ Load float64 `json:"load"`
+ ResourceCount float64 `json:"resourceCount"`
+ TransferSize float64 `json:"transferSize"`
+}
+
+// TimingScript gathers performance data in the page and resolves to the
+// rawTiming shape. It waits for the load event when the page is still
+// loading and for the first paint entry (paint metrics only fire on visible
+// pages — the caller must bring the tab to front first), then reads
+// navigation/paint/resource entries plus buffered largest-contentful-paint
+// and layout-shift observer entries. Evaluate it with AwaitPromise.
+const TimingScript = `(() => {
+ const whenLoaded = document.readyState === 'complete'
+ ? Promise.resolve()
+ : new Promise((resolve) => window.addEventListener('load', resolve, { once: true }));
+ const whenPainted = () => new Promise((resolve) => {
+ try {
+ const po = new PerformanceObserver(() => { po.disconnect(); resolve(); });
+ po.observe({ type: 'paint', buffered: true });
+ setTimeout(() => { po.disconnect(); resolve(); }, 1500);
+ } catch (err) { resolve(); }
+ });
+ const collect = (type) => new Promise((resolve) => {
+ const entries = [];
+ try {
+ const po = new PerformanceObserver((list) => entries.push(...list.getEntries()));
+ po.observe({ type, buffered: true });
+ setTimeout(() => { entries.push(...po.takeRecords()); po.disconnect(); resolve(entries); }, 60);
+ } catch (err) { resolve(entries); }
+ });
+ return whenLoaded
+ .then(whenPainted)
+ .then(() => new Promise((resolve) => setTimeout(resolve, 60)))
+ .then(() => Promise.all([collect('largest-contentful-paint'), collect('layout-shift')]))
+ .then(([lcps, shifts]) => {
+ const nav = performance.getEntriesByType('navigation')[0];
+ const fcp = performance.getEntriesByType('paint').find((e) => e.name === 'first-contentful-paint');
+ const resources = performance.getEntriesByType('resource');
+ return {
+ ttfb: nav ? nav.responseStart : 0,
+ domContentLoaded: nav ? nav.domContentLoadedEventEnd : 0,
+ load: nav ? nav.loadEventEnd : 0,
+ fcp: fcp ? fcp.startTime : 0,
+ lcp: lcps.length ? lcps[lcps.length - 1].startTime : 0,
+ cls: shifts.reduce((sum, e) => (e.hadRecentInput ? sum : sum + e.value), 0),
+ resourceCount: resources.length,
+ transferSize: (nav ? nav.transferSize || 0 : 0) + resources.reduce((s, e) => s + (e.transferSize || 0), 0),
+ };
+ });
+})()`
+
+// toTimingMetrics maps the raw in-page payload to the public metric shape,
+// clamping nonsensical negative values to zero.
+func toTimingMetrics(raw rawTiming) *TimingMetrics {
+ clamp := func(v float64) float64 {
+ if v < 0 {
+ return 0
+ }
+ return v
+ }
+ return &TimingMetrics{
+ TTFBMs: clamp(raw.TTFB),
+ FCPMs: clamp(raw.FCP),
+ LCPMs: clamp(raw.LCP),
+ CLS: clamp(raw.CLS),
+ DOMContentLoadedMs: clamp(raw.DOMContentLoaded),
+ LoadMs: clamp(raw.Load),
+ ResourceCount: int(clamp(raw.ResourceCount)),
+ TransferSizeBytes: int64(clamp(raw.TransferSize)),
+ }
+}
+
+// CollectTiming evaluates TimingScript through eval (a bridge Evaluate bound
+// to a tab context with AwaitPromise) and maps the result.
+func CollectTiming(eval func(expression string, result any) error) (*TimingMetrics, error) {
+ var raw rawTiming
+ if err := eval(TimingScript, &raw); err != nil {
+ return nil, err
+ }
+ return toTimingMetrics(raw), nil
+}
diff --git a/internal/bridge/observe/timing_test.go b/internal/bridge/observe/timing_test.go
new file mode 100644
index 00000000..81582a0a
--- /dev/null
+++ b/internal/bridge/observe/timing_test.go
@@ -0,0 +1,103 @@
+package observe
+
+import (
+ "encoding/json"
+ "errors"
+ "testing"
+)
+
+func TestToTimingMetricsMapsFields(t *testing.T) {
+ payload := `{
+ "ttfb": 12.5,
+ "fcp": 240.2,
+ "lcp": 850.7,
+ "cls": 0.031,
+ "domContentLoaded": 310.1,
+ "load": 905.9,
+ "resourceCount": 7,
+ "transferSize": 20480
+ }`
+ var raw rawTiming
+ if err := json.Unmarshal([]byte(payload), &raw); err != nil {
+ t.Fatalf("unmarshal: %v", err)
+ }
+
+ m := toTimingMetrics(raw)
+ if m.TTFBMs != 12.5 {
+ t.Errorf("TTFBMs = %v, want 12.5", m.TTFBMs)
+ }
+ if m.FCPMs != 240.2 {
+ t.Errorf("FCPMs = %v, want 240.2", m.FCPMs)
+ }
+ if m.LCPMs != 850.7 {
+ t.Errorf("LCPMs = %v, want 850.7", m.LCPMs)
+ }
+ if m.CLS != 0.031 {
+ t.Errorf("CLS = %v, want 0.031", m.CLS)
+ }
+ if m.DOMContentLoadedMs != 310.1 {
+ t.Errorf("DOMContentLoadedMs = %v, want 310.1", m.DOMContentLoadedMs)
+ }
+ if m.LoadMs != 905.9 {
+ t.Errorf("LoadMs = %v, want 905.9", m.LoadMs)
+ }
+ if m.ResourceCount != 7 {
+ t.Errorf("ResourceCount = %d, want 7", m.ResourceCount)
+ }
+ if m.TransferSizeBytes != 20480 {
+ t.Errorf("TransferSizeBytes = %d, want 20480", m.TransferSizeBytes)
+ }
+}
+
+func TestToTimingMetricsClampsNegatives(t *testing.T) {
+ m := toTimingMetrics(rawTiming{TTFB: -1, FCP: -2, LCP: -3, CLS: -0.5, DOMContentLoaded: -4, Load: -5, ResourceCount: -6, TransferSize: -7})
+ if m.TTFBMs != 0 || m.FCPMs != 0 || m.LCPMs != 0 || m.CLS != 0 || m.DOMContentLoadedMs != 0 || m.LoadMs != 0 {
+ t.Errorf("negative durations not clamped: %+v", m)
+ }
+ if m.ResourceCount != 0 || m.TransferSizeBytes != 0 {
+ t.Errorf("negative counts not clamped: %+v", m)
+ }
+}
+
+func TestToTimingMetricsZeroValue(t *testing.T) {
+ m := toTimingMetrics(rawTiming{})
+ if *m != (TimingMetrics{}) {
+ t.Errorf("zero raw payload should map to zero metrics, got %+v", m)
+ }
+}
+
+func TestTimingMetricsJSONFieldNames(t *testing.T) {
+ data, err := json.Marshal(TimingMetrics{})
+ if err != nil {
+ t.Fatalf("marshal: %v", err)
+ }
+ var fields map[string]any
+ if err := json.Unmarshal(data, &fields); err != nil {
+ t.Fatalf("unmarshal: %v", err)
+ }
+ for _, name := range []string{"ttfbMs", "fcpMs", "lcpMs", "cls", "domContentLoadedMs", "loadMs", "resourceCount", "transferSizeBytes"} {
+ if _, ok := fields[name]; !ok {
+ t.Errorf("missing JSON field %q in %s", name, data)
+ }
+ }
+}
+
+func TestCollectTiming(t *testing.T) {
+ m, err := CollectTiming(func(expression string, result any) error {
+ if expression != TimingScript {
+ t.Errorf("unexpected expression evaluated")
+ }
+ return json.Unmarshal([]byte(`{"ttfb":3.2,"load":120.5,"resourceCount":2}`), result)
+ })
+ if err != nil {
+ t.Fatalf("CollectTiming: %v", err)
+ }
+ if m.TTFBMs != 3.2 || m.LoadMs != 120.5 || m.ResourceCount != 2 {
+ t.Errorf("unexpected metrics: %+v", m)
+ }
+
+ wantErr := errors.New("eval failed")
+ if _, err := CollectTiming(func(string, any) error { return wantErr }); !errors.Is(err, wantErr) {
+ t.Errorf("CollectTiming error = %v, want %v", err, wantErr)
+ }
+}
diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.go
index 67e3802f..779182ea 100644
--- a/internal/handlers/handlers.go
+++ b/internal/handlers/handlers.go
@@ -320,6 +320,7 @@ func (h *Handlers) bridgeBindings() []routeBinding {
{pattern: "POST /cookies", root: h.HandleSetCookies, tab: h.HandleTabSetCookies},
{pattern: "DELETE /cookies", root: h.HandleClearCookies, tab: h.HandleTabClearCookies},
{pattern: "GET /metrics", root: h.HandleMetrics, tab: h.HandleTabMetrics},
+ {pattern: "GET /timing", root: h.HandleTiming, tab: h.HandleTabTiming},
{pattern: "GET /network", root: h.HandleNetwork, tab: h.HandleTabNetwork},
{pattern: "GET /network/stream", root: h.HandleNetworkStream, tab: h.HandleTabNetworkStream},
{pattern: "GET /network/export", root: h.HandleNetworkExport, tab: h.HandleTabNetworkExport},
diff --git a/internal/handlers/timing.go b/internal/handlers/timing.go
new file mode 100644
index 00000000..43f519a5
--- /dev/null
+++ b/internal/handlers/timing.go
@@ -0,0 +1,49 @@
+package handlers
+
+import (
+ "fmt"
+ "net/http"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/bridge/observe"
+ "github.com/pinchtab/pinchtab/internal/httpx"
+)
+
+// @Endpoint GET /timing
+func (h *Handlers) HandleTiming(w http.ResponseWriter, r *http.Request) {
+ tabID := r.URL.Query().Get("tabId")
+
+ if !h.ensureBrowserOrRespond(w, h.Config) {
+ return
+ }
+ h.recordReadRequest(r, "timing", tabID)
+
+ resolvedTabID, tCtx, cancel, ok := h.resolveReadContext(w, r, tabID, h.Config.ActionTimeout)
+ if !ok {
+ return
+ }
+ defer h.armAutoCloseIfEnabled(resolvedTabID)
+ defer cancel()
+
+ // Paint metrics (FCP/LCP) only fire on visible pages; background tabs
+ // stay hidden in headless Chrome, so surface the tab before measuring.
+ _ = h.Bridge.FocusTab(resolvedTabID)
+
+ metrics, err := observe.CollectTiming(func(expression string, result any) error {
+ return h.Bridge.Evaluate(tCtx, expression, result, bridge.EvalOpts{AwaitPromise: true})
+ })
+ if err != nil {
+ httpx.Error(w, 500, fmt.Errorf("collect timing: %w", err))
+ return
+ }
+
+ httpx.JSON(w, 200, struct {
+ TabID string `json:"tabId"`
+ *observe.TimingMetrics
+ }{resolvedTabID, metrics})
+}
+
+// @Endpoint GET /tabs/{id}/timing
+func (h *Handlers) HandleTabTiming(w http.ResponseWriter, r *http.Request) {
+ h.withPathTabID(w, r, h.HandleTiming)
+}
diff --git a/internal/routes/routes.go b/internal/routes/routes.go
index 5ef98468..dd6273c0 100644
--- a/internal/routes/routes.go
+++ b/internal/routes/routes.go
@@ -122,6 +122,7 @@ var coreEndpoints = []Endpoint{
{"DELETE", "/cookies", "Clear all cookies", CapCookies, true},
{"GET", "/metrics", "Runtime metrics", CapNone, true},
+ {"GET", "/timing", "Page timing and Core Web Vitals", CapNone, true},
{"GET", "/network", "Network log", CapNone, true},
{"GET", "/network/stream", "Network SSE stream", CapNone, true},
diff --git a/tests/e2e/scenarios/api/timing-basic.sh b/tests/e2e/scenarios/api/timing-basic.sh
new file mode 100755
index 00000000..313a03ed
--- /dev/null
+++ b/tests/e2e/scenarios/api/timing-basic.sh
@@ -0,0 +1,73 @@
+#!/bin/bash
+# timing-basic.sh — GET /timing navigation timing and Core Web Vitals tests.
+
+GROUP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+source "${GROUP_DIR}/../../helpers/api.sh"
+
+assert_json_number_gt() {
+ local json="$1"
+ local path="$2"
+ local floor="$3"
+ local desc="${4:-$path > $floor}"
+ local actual
+ actual=$(echo "$json" | jq "$path")
+ if echo "$json" | jq -e "($path | type == \"number\") and ($path > $floor)" >/dev/null 2>&1; then
+ pass_assert "$desc (got: $actual)"
+ else
+ fail_assert "$desc (got: $actual)"
+ fi
+}
+
+TIMING_FIELDS=(ttfbMs fcpMs lcpMs cls domContentLoadedMs loadMs resourceCount transferSizeBytes)
+
+# ─────────────────────────────────────────────────────────────────
+start_test "GET /timing returns all metric fields after navigation"
+
+pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/audit-site/clean.html\"}"
+assert_ok "navigate to clean.html"
+
+pt_get /timing
+assert_ok "get timing"
+assert_json_exists "$RESULT" '.tabId' "has tabId"
+for field in "${TIMING_FIELDS[@]}"; do
+ assert_json_exists "$RESULT" ".${field}" "has ${field}"
+done
+
+assert_json_number_gt "$RESULT" '.ttfbMs' 0 "ttfbMs > 0"
+assert_json_number_gt "$RESULT" '.loadMs' 0 "loadMs > 0"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "GET /timing on a page with an image reports paint metrics"
+
+pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/audit-site/a11y-issues.html\"}"
+assert_ok "navigate to a11y-issues.html"
+
+pt_get /timing
+assert_ok "get timing"
+assert_json_number_gt "$RESULT" '.lcpMs' 0 "lcpMs > 0"
+assert_json_exists "$RESULT" '.cls' "cls present"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "GET /timing with tabId parameter"
+
+pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/audit-site/clean.html\",\"newTab\":true}"
+assert_ok "create new tab"
+TAB_ID=$(echo "$RESULT" | jq -r '.tabId')
+
+pt_get "/timing?tabId=${TAB_ID}"
+assert_ok "get timing for specific tab"
+assert_json_contains "$RESULT" '.tabId' "$TAB_ID" "returns correct tabId"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "GET /timing for nonexistent tab → error"
+
+pt_get "/timing?tabId=nonexistent_xyz_999"
+assert_not_ok "rejects bad tab"
+
+end_test