Skip to content

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

feat(metrics): read JS heap and DOM counters from Performance.getMetrics on every tracked tab and sum them beside the process-tree RSS, counting tabs that would not answer instead of reporting zeros (PIN-271)

Luigi Agosti8d66e9cc53d5
diff --git a/dashboard/src/components/molecules/InstanceStats.test.tsx b/dashboard/src/components/molecules/InstanceStats.test.tsx
index ca3c1eb1..1df45b3d 100644
--- a/dashboard/src/components/molecules/InstanceStats.test.tsx
+++ b/dashboard/src/components/molecules/InstanceStats.test.tsx
@@ -45,6 +45,56 @@ describe("InstanceStats", () => {
).toBeInTheDocument();
});
+ it("shows the summed page counters and the tabs that did not answer", () => {
+ render(
+ <InstanceStats
+ instance={instance}
+ metrics={{
+ instanceId: "inst_1",
+ profileName: "default",
+ memoryMB: 512,
+ renderers: 3,
+ unreadableTargets: 1,
+ page: {
+ targets: 2,
+ jsHeapUsedMB: 12.5,
+ jsHeapTotalMB: 20,
+ documents: 2,
+ frames: 3,
+ nodes: 6400,
+ jsEventListeners: 51,
+ },
+ }}
+ tabs={[]}
+ />,
+ );
+ expect(screen.getByText("12.5 / 20 MB")).toBeInTheDocument();
+ expect(
+ screen.getByText("used / total, summed over 2 tabs"),
+ ).toBeInTheDocument();
+ expect(screen.getByText("6,400")).toBeInTheDocument();
+ expect(screen.getByText("51")).toBeInTheDocument();
+ expect(screen.getByText("Unreadable")).toBeInTheDocument();
+ });
+
+ it("shows no page group when no tab could be read and none failed", () => {
+ render(
+ <InstanceStats
+ instance={instance}
+ metrics={{
+ instanceId: "inst_1",
+ profileName: "default",
+ memoryMB: 512,
+ renderers: 3,
+ unreadableTargets: 0,
+ }}
+ tabs={[]}
+ />,
+ );
+ expect(screen.queryByText("Pages")).not.toBeInTheDocument();
+ expect(screen.queryByText("Unreadable")).not.toBeInTheDocument();
+ });
+
it("stays silent about crashes for an instance that never crashed", () => {
render(<InstanceStats instance={instance} tabs={[]} />);
expect(screen.getByText("running")).toBeInTheDocument();
diff --git a/dashboard/src/components/molecules/InstanceStats.tsx b/dashboard/src/components/molecules/InstanceStats.tsx
index fad45908..d6378a17 100644
--- a/dashboard/src/components/molecules/InstanceStats.tsx
+++ b/dashboard/src/components/molecules/InstanceStats.tsx
@@ -127,6 +127,37 @@ export default function InstanceStats({ instance, metrics, tabs }: Props) {
<StatItem label="Renderers" value={fmt(metrics.renderers)} />
</StatGroup>
)}
+
+ {metrics && (metrics.page || metrics.unreadableTargets > 0) && (
+ <StatGroup title="Pages">
+ {metrics.page && (
+ <>
+ <StatItem
+ label="JS heap"
+ value={`${fmt(metrics.page.jsHeapUsedMB, 1)} / ${fmt(metrics.page.jsHeapTotalMB, 1)} MB`}
+ sub={`used / total, summed over ${fmt(metrics.page.targets)} tab${metrics.page.targets === 1 ? "" : "s"}`}
+ />
+ <StatItem label="DOM nodes" value={fmt(metrics.page.nodes)} />
+ <StatItem
+ label="Listeners"
+ value={fmt(metrics.page.jsEventListeners)}
+ />
+ <StatItem
+ label="Frames"
+ value={fmt(metrics.page.frames)}
+ sub={`${fmt(metrics.page.documents)} documents`}
+ />
+ </>
+ )}
+ {metrics.unreadableTargets > 0 && (
+ <StatItem
+ label="Unreadable"
+ value={fmt(metrics.unreadableTargets)}
+ sub="tabs that did not answer; not counted"
+ />
+ )}
+ </StatGroup>
+ )}
</div>
);
}
diff --git a/dashboard/src/generated/types.ts b/dashboard/src/generated/types.ts
index 66bb1caf..37cce480 100644
--- a/dashboard/src/generated/types.ts
+++ b/dashboard/src/generated/types.ts
@@ -189,6 +189,17 @@ export interface InstanceMetrics {
profileName: string;
memoryMB: number /* float64 */;
renderers: number /* int */;
+ page?: PageMetrics;
+ unreadableTargets: number /* int */;
+}
+export interface PageMetrics {
+ targets: number /* int */;
+ jsHeapUsedMB: number /* float64 */;
+ jsHeapTotalMB: number /* float64 */;
+ documents: number /* int */;
+ frames: number /* int */;
+ nodes: number /* int */;
+ jsEventListeners: number /* int */;
}
export interface LaunchInstanceRequest {
profileId?: string; // profile ID (prof_XXXXXXXX) or existing profile name
diff --git a/dashboard/src/pages/settings/DashboardSettingsSection.tsx b/dashboard/src/pages/settings/DashboardSettingsSection.tsx
index aeaeb485..688c95c0 100644
--- a/dashboard/src/pages/settings/DashboardSettingsSection.tsx
+++ b/dashboard/src/pages/settings/DashboardSettingsSection.tsx
@@ -94,7 +94,7 @@ export function DashboardSettingsSection({
</SettingRow>
<SettingRow
label="Memory metrics"
- description="Collect per-instance browser memory (RSS across the Chrome process tree) in the dashboard. Useful for debugging, but heavier."
+ description="Poll every running instance for browser memory on each monitoring tick: RSS across the Chrome process tree plus JS heap and DOM counters read from each open tab over CDP. Measured cost: about a millisecond per open tab plus a few tens of milliseconds for the process-tree walk, per instance per tick."
>
<label className="flex items-center justify-end gap-3 text-sm text-text-secondary">
<input
diff --git a/docs/guides/memory-monitoring.md b/docs/guides/memory-monitoring.md
index 4a5d0b67..c58b6966 100644
--- a/docs/guides/memory-monitoring.md
+++ b/docs/guides/memory-monitoring.md
@@ -1,17 +1,17 @@
# Memory Monitoring
-PinchTab exposes memory information for the Chrome processes it launches. The current implementation measures browser memory at the process level and reports browser-wide aggregates for each instance.
+PinchTab exposes memory information for the Chrome processes it launches. Each instance reports two measurements side by side: the OS view of its process tree, and the page counters Chrome itself reports for the tabs that instance tracks.
## What PinchTab Measures
-PinchTab walks the Chrome process tree for a running instance:
+For the process tree, PinchTab walks the running instance's Chrome processes:
1. find the main browser PID
2. enumerate child processes
3. sum RSS memory across the browser and its children
4. count renderer processes
-This gives you real OS-level memory usage for that instance's Chrome process tree.
+For the pages, PinchTab asks every tab the instance tracks for its own `Performance.getMetrics` reading over CDP and sums the answers.
## Memory Fields
@@ -19,12 +19,23 @@ This gives you real OS-level memory usage for that instance's Chrome process tre
| --- | --- |
| `memoryMB` | Real RSS memory across the browser process tree |
| `renderers` | Number of renderer processes in the browser process tree |
+| `page.targets` | Tabs whose reading is included in the `page` sums |
+| `page.jsHeapUsedMB` / `page.jsHeapTotalMB` | JavaScript heap used and reserved, summed over those tabs |
+| `page.documents` / `page.frames` / `page.nodes` / `page.jsEventListeners` | DOM counters summed over those tabs |
+| `unreadableTargets` | Tabs that did not answer within the read timeout; they contribute nothing |
-Both fields are measured. Neither is derived from the other, and PinchTab reports no JavaScript-heap or DOM-count figures: there is no CDP collection behind these endpoints.
+Every field is measured; none is derived from another field in the payload.
+
+## Aggregation Rule
+
+- **Which targets contribute:** every tab the instance tracks with a live context. Each is read separately with `Performance.getMetrics`, and the `page` block is the sum of the readings that arrived.
+- **Scope:** the instance. `memoryMB` is the whole process tree, which also holds the GPU and utility processes and the shared browser process; `page` covers only the tabs. The two describe different populations and are never combined or compared arithmetically.
+- **Absent versus unreadable:** `page` is omitted when no tab contributed. `unreadableTargets` says how many tabs were asked and did not answer (closed or crashed mid-collection, or a read timeout). No tab is ever reported as `0` heap or `0` nodes because it could not be read: `{"unreadableTargets":0}` with no `page` means no tabs, `{"unreadableTargets":2}` with no `page` means two tabs that would not answer.
+- **Cost (measured, five tabs open):** about 1 ms per tab read and about 30 ms for the process-tree walk, so a poll is a few tens of milliseconds per instance and grows by roughly a millisecond per open tab. The dashboard's **Memory metrics** toggle does not gate the CDP reads specifically: it gates whether the dashboard polls every running instance's `/metrics` on each monitoring tick at all. `GET /metrics` on an instance always collects both.
Important limitation:
-- `GET /tabs/{id}/metrics` returns the owning browser instance's aggregate memory, not isolated per-tab memory
+- `GET /tabs/{id}/metrics` returns the owning browser instance's aggregate, including the `page` sum over all its tabs, not isolated per-tab figures
## Instance Metrics
@@ -45,7 +56,17 @@ Example shape:
},
"memory": {
"memoryMB": 850.5,
- "renderers": 11
+ "renderers": 11,
+ "page": {
+ "targets": 3,
+ "jsHeapUsedMB": 41.2,
+ "jsHeapTotalMB": 64.0,
+ "documents": 4,
+ "frames": 5,
+ "nodes": 9120,
+ "jsEventListeners": 212
+ },
+ "unreadableTargets": 0
}
}
```
@@ -61,11 +82,13 @@ Example shape:
```json
{
"memoryMB": 850.5,
- "renderers": 11
+ "renderers": 11,
+ "page": { "targets": 3, "jsHeapUsedMB": 41.2, "jsHeapTotalMB": 64.0, "documents": 4, "frames": 5, "nodes": 9120, "jsEventListeners": 212 },
+ "unreadableTargets": 0
}
```
-Treat this as “memory for the browser instance that owns this tab”, not “memory for this tab alone”.
+Treat this as “memory for the browser instance that owns this tab”, not “memory for this tab alone”: the `page` block is summed over every tab of that instance.
## All Running Instances
@@ -75,7 +98,7 @@ In orchestrator mode:
curl http://localhost:9867/instances/metrics
```
-This returns one metrics object per running instance — `instanceId`, `profileName`, `memoryMB` and `renderers` — which is the best API for comparing memory across a fleet.
+This returns one metrics object per running instance — `instanceId`, `profileName`, `memoryMB`, `renderers`, `page` and `unreadableTargets` — which is the best API for comparing memory across a fleet.
## Dashboard Monitoring
diff --git a/internal/api/types/instance_metrics_parity_test.go b/internal/api/types/instance_metrics_parity_test.go
new file mode 100644
index 00000000..d0964007
--- /dev/null
+++ b/internal/api/types/instance_metrics_parity_test.go
@@ -0,0 +1,53 @@
+package types
+
+import (
+ "reflect"
+ "sort"
+ "strings"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/bridge/observe"
+)
+
+func jsonKeyPaths(typ reflect.Type, prefix string, into *[]string) {
+ if typ.Kind() == reflect.Ptr {
+ typ = typ.Elem()
+ }
+ for i := 0; i < typ.NumField(); i++ {
+ field := typ.Field(i)
+ key := strings.Split(field.Tag.Get("json"), ",")[0]
+ leaf := field.Type
+ if leaf.Kind() == reflect.Ptr {
+ leaf = leaf.Elem()
+ }
+ if leaf.Kind() == reflect.Struct {
+ jsonKeyPaths(leaf, prefix+key+".", into)
+ continue
+ }
+ *into = append(*into, prefix+key)
+ }
+}
+
+// InstanceMetrics is the hand-maintained wire twin of observe.MemoryMetrics plus the
+// instance identity. A key on one side and not the other is drift: a measured field
+// the dashboard never sees, or a field on the wire nothing measured.
+func TestInstanceMetricsMirrorsTheMeasuredMemoryMetricsKeyForKey(t *testing.T) {
+ var measured, wire []string
+ jsonKeyPaths(reflect.TypeOf(observe.MemoryMetrics{}), "", &measured)
+ jsonKeyPaths(reflect.TypeOf(InstanceMetrics{}), "", &wire)
+ identity := map[string]bool{"instanceId": true, "profileName": true}
+ var payload []string
+ for _, key := range wire {
+ if !identity[key] {
+ payload = append(payload, key)
+ }
+ }
+ sort.Strings(measured)
+ sort.Strings(payload)
+ if strings.Join(measured, ",") != strings.Join(payload, ",") {
+ t.Fatalf("InstanceMetrics keys %v, want the measured keys %v beside the instance identity", payload, measured)
+ }
+ if len(measured) < 4 {
+ t.Fatalf("only %d measured keys walked; the walk missed the nested page block", len(measured))
+ }
+}
diff --git a/internal/api/types/types.go b/internal/api/types/types.go
index 0682c4df..65df6f55 100644
--- a/internal/api/types/types.go
+++ b/internal/api/types/types.go
@@ -206,6 +206,19 @@ type InstanceMetrics struct {
ProfileName string `json:"profileName"`
MemoryMB float64 `json:"memoryMB"`
Renderers int `json:"renderers"`
+
+ Page *PageMetrics `json:"page,omitempty"`
+ UnreadableTargets int `json:"unreadableTargets"`
+}
+
+type PageMetrics struct {
+ Targets int `json:"targets"`
+ JSHeapUsedMB float64 `json:"jsHeapUsedMB"`
+ JSHeapTotalMB float64 `json:"jsHeapTotalMB"`
+ Documents int `json:"documents"`
+ Frames int `json:"frames"`
+ Nodes int `json:"nodes"`
+ JSEventListeners int `json:"jsEventListeners"`
}
type LaunchInstanceRequest struct {
diff --git a/internal/bridge/observe/metrics.go b/internal/bridge/observe/metrics.go
index a3ce120f..af6b5db2 100644
--- a/internal/bridge/observe/metrics.go
+++ b/internal/bridge/observe/metrics.go
@@ -3,29 +3,125 @@ package observe
import (
"context"
"strings"
+ "time"
+ "github.com/chromedp/cdproto/performance"
"github.com/chromedp/chromedp"
"github.com/shirou/gopsutil/v4/process"
)
-// MemoryMetrics holds what PinchTab measures: RSS across the browser process
-// tree and the renderer count. Every field is measured, never derived from
-// another field in the same payload.
+const targetReadTimeout = 2 * time.Second
+
+// MemoryMetrics holds what PinchTab measures for one browser instance: RSS across
+// the process tree, the renderer count, and the page counters summed over every
+// target that answered. Every field is measured, never derived from another field
+// in the same payload. Page is absent when no target contributed; a target that
+// could not be read is counted in UnreadableTargets and contributes nothing, so
+// "no tabs" and "tabs that would not answer" never share a representation.
type MemoryMetrics struct {
- MemoryMB float64 `json:"memoryMB"`
- Renderers int `json:"renderers"`
+ MemoryMB float64 `json:"memoryMB"`
+ Renderers int `json:"renderers"`
+ Page *PageMetrics `json:"page,omitempty"`
+ UnreadableTargets int `json:"unreadableTargets"`
+}
+
+// PageMetrics is Performance.getMetrics summed over Targets targets.
+type PageMetrics struct {
+ Targets int `json:"targets"`
+ JSHeapUsedMB float64 `json:"jsHeapUsedMB"`
+ JSHeapTotalMB float64 `json:"jsHeapTotalMB"`
+ Documents int `json:"documents"`
+ Frames int `json:"frames"`
+ Nodes int `json:"nodes"`
+ JSEventListeners int `json:"jsEventListeners"`
}
func newMemoryMetrics(totalBytes uint64, renderers int) *MemoryMetrics {
return &MemoryMetrics{MemoryMB: float64(totalBytes) / (1024 * 1024), Renderers: renderers}
}
-// GetAggregatedMemoryMetrics returns OS-level memory usage across the browser process tree.
-func GetAggregatedMemoryMetrics(browserCtx context.Context) (*MemoryMetrics, error) {
+// ReadTargetMetrics reads one target's own Performance.getMetrics.
+func ReadTargetMetrics(ctx context.Context) (*PageMetrics, error) {
+ var metrics []*performance.Metric
+ err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ if err := performance.Enable().Do(ctx); err != nil {
+ return err
+ }
+ var err error
+ metrics, err = performance.GetMetrics().Do(ctx)
+ return err
+ }))
+ if err != nil {
+ return nil, err
+ }
+ reading := &PageMetrics{Targets: 1}
+ for _, m := range metrics {
+ switch m.Name {
+ case "JSHeapUsedSize":
+ reading.JSHeapUsedMB = m.Value / (1024 * 1024)
+ case "JSHeapTotalSize":
+ reading.JSHeapTotalMB = m.Value / (1024 * 1024)
+ case "Documents":
+ reading.Documents = int(m.Value)
+ case "Frames":
+ reading.Frames = int(m.Value)
+ case "Nodes":
+ reading.Nodes = int(m.Value)
+ case "JSEventListeners":
+ reading.JSEventListeners = int(m.Value)
+ }
+ }
+ return reading, nil
+}
+
+func sumPageMetrics(readings []*PageMetrics) *PageMetrics {
+ if len(readings) == 0 {
+ return nil
+ }
+ sum := &PageMetrics{}
+ for _, r := range readings {
+ sum.Targets += r.Targets
+ sum.JSHeapUsedMB += r.JSHeapUsedMB
+ sum.JSHeapTotalMB += r.JSHeapTotalMB
+ sum.Documents += r.Documents
+ sum.Frames += r.Frames
+ sum.Nodes += r.Nodes
+ sum.JSEventListeners += r.JSEventListeners
+ }
+ return sum
+}
+
+func readTargets(targets map[string]context.Context) (*PageMetrics, int) {
+ readings := make([]*PageMetrics, 0, len(targets))
+ unreadable := 0
+ for _, targetCtx := range targets {
+ ctx, cancel := context.WithTimeout(targetCtx, targetReadTimeout)
+ reading, err := ReadTargetMetrics(ctx)
+ cancel()
+ if err != nil {
+ unreadable++
+ continue
+ }
+ readings = append(readings, reading)
+ }
+ return sumPageMetrics(readings), unreadable
+}
+
+// GetAggregatedMemoryMetrics returns OS-level memory usage across the browser
+// process tree plus the page counters summed over the given targets.
+func GetAggregatedMemoryMetrics(browserCtx context.Context, targets map[string]context.Context) (*MemoryMetrics, error) {
if browserCtx == nil {
return nil, nil
}
+ result, err := processTreeMemory(browserCtx)
+ if err != nil {
+ return result, err
+ }
+ result.Page, result.UnreadableTargets = readTargets(targets)
+ return result, nil
+}
+func processTreeMemory(browserCtx context.Context) (*MemoryMetrics, error) {
result := &MemoryMetrics{}
browser := chromedp.FromContext(browserCtx)
if browser == nil || browser.Browser == nil {
diff --git a/internal/bridge/observe/metrics_test.go b/internal/bridge/observe/metrics_test.go
index ef6633b9..ca1c4525 100644
--- a/internal/bridge/observe/metrics_test.go
+++ b/internal/bridge/observe/metrics_test.go
@@ -1,6 +1,7 @@
package observe
import (
+ "context"
"encoding/json"
"fmt"
"math"
@@ -8,6 +9,34 @@ import (
"testing"
)
+func flattenNumbers(t *testing.T, prefix string, value any, into map[string]float64) {
+ t.Helper()
+ switch v := value.(type) {
+ case float64:
+ into[prefix] = v
+ case map[string]any:
+ for name, child := range v {
+ flattenNumbers(t, prefix+"."+name, child, into)
+ }
+ default:
+ t.Fatalf("field %q is %T, not a number or an object; this walk would silently skip it", prefix, value)
+ }
+}
+
+func leafFieldCount(typ reflect.Type) int {
+ if typ.Kind() == reflect.Ptr {
+ typ = typ.Elem()
+ }
+ if typ.Kind() != reflect.Struct {
+ return 1
+ }
+ count := 0
+ for i := 0; i < typ.NumField(); i++ {
+ count += leafFieldCount(typ.Field(i).Type)
+ }
+ return count
+}
+
func numericFields(t *testing.T, m *MemoryMetrics) map[string]float64 {
t.Helper()
@@ -21,27 +50,32 @@ func numericFields(t *testing.T, m *MemoryMetrics) map[string]float64 {
}
values := map[string]float64{}
- for name, value := range decoded {
- number, ok := value.(float64)
- if !ok {
- t.Fatalf("field %q is %T, not a number; this walk would silently skip it", name, value)
- }
- values[name] = number
- }
- if len(values) < reflect.TypeOf(MemoryMetrics{}).NumField() {
+ flattenNumbers(t, "", decoded, values)
+ if m.Page != nil && len(values) < leafFieldCount(reflect.TypeOf(MemoryMetrics{})) {
t.Fatalf("walked %d serialized fields for %d struct fields; a field this guard cannot see is a field it cannot police",
- len(values), reflect.TypeOf(MemoryMetrics{}).NumField())
+ len(values), leafFieldCount(reflect.TypeOf(MemoryMetrics{})))
}
return values
}
+func sample(totalBytes uint64, renderers int, unreadable int, readings ...*PageMetrics) *MemoryMetrics {
+ m := newMemoryMetrics(totalBytes, renderers)
+ m.Page = sumPageMetrics(readings)
+ m.UnreadableTargets = unreadable
+ return m
+}
+
// The property the derived jsHeap fields violated: nothing a caller reads may be
// arithmetic on something else in the same payload. Two samples are the minimum
-// that can say so — any single pair of numbers has a ratio.
+// that can say so — any single pair of numbers has a ratio. The walk covers the
+// nested page block, so a derived counter added there reds like a top-level one.
func TestNoReportedFieldHoldsAConstantRatioToAnotherAcrossTwoSamples(t *testing.T) {
const mb = 1024 * 1024
- low := numericFields(t, newMemoryMetrics(100*mb, 3))
- high := numericFields(t, newMemoryMetrics(250*mb, 4))
+ low := numericFields(t, sample(100*mb, 3, 1,
+ &PageMetrics{Targets: 1, JSHeapUsedMB: 7, JSHeapTotalMB: 11, Documents: 2, Frames: 3, Nodes: 400, JSEventListeners: 5}))
+ high := numericFields(t, sample(250*mb, 4, 4,
+ &PageMetrics{Targets: 1, JSHeapUsedMB: 19, JSHeapTotalMB: 23, Documents: 5, Frames: 7, Nodes: 9000, JSEventListeners: 13},
+ &PageMetrics{Targets: 1, JSHeapUsedMB: 29, JSHeapTotalMB: 31, Documents: 1, Frames: 1, Nodes: 37, JSEventListeners: 41}))
for name := range low {
for other := range low {
@@ -62,8 +96,51 @@ func TestMemoryMetricsReportsMeasuredRSSAndRenderers(t *testing.T) {
const mb = 1024 * 1024
got := numericFields(t, newMemoryMetrics(250*mb, 4))
- want := map[string]float64{"memoryMB": 250, "renderers": 4}
+ want := map[string]float64{".memoryMB": 250, ".renderers": 4, ".unreadableTargets": 0}
if fmt.Sprint(got) != fmt.Sprint(want) {
t.Fatalf("MemoryMetrics = %v, want %v", got, want)
}
}
+
+// Absent and could-not-read never share a representation: no targets is an absent
+// page block with nothing unreadable; targets that would not answer is the same
+// absent block with the refusals counted; a partial read sums only the answers.
+func TestAnEmptyReadingAndAFailedReadAreDistinguishableInThePayload(t *testing.T) {
+ encode := func(m *MemoryMetrics) map[string]any {
+ raw, _ := json.Marshal(m)
+ var out map[string]any
+ _ = json.Unmarshal(raw, &out)
+ return out
+ }
+
+ empty := encode(sample(1, 1, 0))
+ if _, present := empty["page"]; present || empty["unreadableTargets"] != float64(0) {
+ t.Errorf("no targets = %v, want no page block and nothing unreadable", empty)
+ }
+
+ failed := encode(sample(1, 1, 2))
+ if _, present := failed["page"]; present || failed["unreadableTargets"] != float64(2) {
+ t.Errorf("all targets failed = %v, want no page block and two unreadable", failed)
+ }
+
+ partial := sample(1, 1, 1, &PageMetrics{Targets: 1, Nodes: 10, JSHeapUsedMB: 1}, &PageMetrics{Targets: 1, Nodes: 5, JSHeapUsedMB: 2})
+ if partial.Page == nil || partial.Page.Targets != 2 || partial.Page.Nodes != 15 || partial.Page.JSHeapUsedMB != 3 || partial.UnreadableTargets != 1 {
+ t.Errorf("partial = %+v / unreadable %d, want the two answers summed and one refusal counted", partial.Page, partial.UnreadableTargets)
+ }
+}
+
+func TestReadTargetsCountsATargetThatWouldNotAnswerWithoutContributingZeros(t *testing.T) {
+ page, unreadable := readTargets(map[string]context.Context{"dead": cancelledContext()})
+ if page != nil || unreadable != 1 {
+ t.Errorf("readTargets over a dead target = %+v / %d, want no page block and one unreadable", page, unreadable)
+ }
+ if page, unreadable := readTargets(nil); page != nil || unreadable != 0 {
+ t.Errorf("readTargets over nothing = %+v / %d, want absent and nothing unreadable", page, unreadable)
+ }
+}
+
+func cancelledContext() context.Context {
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ return ctx
+}
diff --git a/internal/bridge/observe/page_metrics_browser_test.go b/internal/bridge/observe/page_metrics_browser_test.go
new file mode 100644
index 00000000..3d042e0e
--- /dev/null
+++ b/internal/bridge/observe/page_metrics_browser_test.go
@@ -0,0 +1,126 @@
+package observe
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/testbrowser"
+)
+
+func launchBrowser(t *testing.T) context.Context {
+ t.Helper()
+ chromePath := testbrowser.Path(t)
+ profile := testbrowser.ProfileDir(t)
+ alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
+ chromedp.DefaultExecAllocatorOptions[:],
+ chromedp.ExecPath(chromePath),
+ chromedp.UserDataDir(profile),
+ chromedp.Flag("headless", true),
+ chromedp.Flag("no-sandbox", true),
+ )...)
+ ctx, cancelBrowser := chromedp.NewContext(alloc)
+ if err := chromedp.Run(ctx); err != nil {
+ cancelBrowser()
+ cancelAlloc()
+ t.Fatalf("launch browser: %v", err)
+ }
+ t.Cleanup(func() {
+ cancelBrowser()
+ cancelAlloc()
+ _ = os.RemoveAll(profile)
+ })
+ return ctx
+}
+
+func openTab(t *testing.T, browserCtx context.Context, html string) context.Context {
+ t.Helper()
+ ctx, cancel := chromedp.NewContext(browserCtx)
+ t.Cleanup(cancel)
+ if err := chromedp.Run(ctx, chromedp.Navigate("data:text/html,"+html)); err != nil {
+ t.Fatalf("open tab: %v", err)
+ }
+ return ctx
+}
+
+// Two page states the counters must tell apart, or nothing proves a reading was
+// taken from the target rather than invented.
+func TestPageCountersMoveBetweenATrivialAndADOMHeavyPage(t *testing.T) {
+ browser := launchBrowser(t)
+ trivial := openTab(t, browser, "<html><body>hi</body></html>")
+ heavy := openTab(t, browser, "<html><body>"+strings.Repeat("<div><span>x</span></div>", 3000)+"<script>for(let i=0;i<500;i++)document.addEventListener('x'+i,()=>{})</script></body></html>")
+
+ light, err := ReadTargetMetrics(trivial)
+ if err != nil {
+ t.Fatalf("read trivial: %v", err)
+ }
+ dense, err := ReadTargetMetrics(heavy)
+ if err != nil {
+ t.Fatalf("read heavy: %v", err)
+ }
+ if dense.Nodes < light.Nodes+5000 {
+ t.Errorf("nodes: heavy %d vs trivial %d, want the 6000 extra elements to show", dense.Nodes, light.Nodes)
+ }
+ if dense.JSEventListeners < light.JSEventListeners+500 {
+ t.Errorf("listeners: heavy %d vs trivial %d, want the 500 added listeners to show", dense.JSEventListeners, light.JSEventListeners)
+ }
+ if light.JSHeapUsedMB <= 0 || light.JSHeapTotalMB < light.JSHeapUsedMB || light.Documents < 1 || light.Frames < 1 {
+ t.Errorf("trivial reading = %+v, want a live heap and at least one document and frame", light)
+ }
+
+ aggregate, err := GetAggregatedMemoryMetrics(browser, map[string]context.Context{"a": trivial, "b": heavy, "dead": cancelledContext()})
+ if err != nil {
+ t.Fatalf("aggregate: %v", err)
+ }
+ if aggregate.Page == nil || aggregate.Page.Targets != 2 || aggregate.UnreadableTargets != 1 {
+ t.Fatalf("aggregate = %+v / unreadable %d, want two targets summed and the dead one counted", aggregate.Page, aggregate.UnreadableTargets)
+ }
+ if aggregate.Page.Nodes < light.Nodes+dense.Nodes-50 || aggregate.Page.Nodes > light.Nodes+dense.Nodes+50 {
+ t.Errorf("aggregate nodes %d, want about the sum of the two readings %d", aggregate.Page.Nodes, light.Nodes+dense.Nodes)
+ }
+ if aggregate.MemoryMB <= 0 {
+ t.Errorf("memoryMB = %v, want the process tree measured beside the page counters", aggregate.MemoryMB)
+ }
+}
+
+// The per-poll cost the Settings toggle gates, measured rather than asserted: the
+// figures are logged so the card can carry them, and the only bound pinned is
+// that one poll over several tabs stays under the dashboard's 5s emit interval.
+func TestPerPollCostAcrossSeveralTabsIsRecorded(t *testing.T) {
+ browser := launchBrowser(t)
+ const tabs = 5
+ targets := map[string]context.Context{}
+ for i := 0; i < tabs; i++ {
+ targets[fmt.Sprint(i)] = openTab(t, browser, "<html><body>"+strings.Repeat("<p>x</p>", 200)+"</body></html>")
+ }
+ const polls = 10
+ start := time.Now()
+ for i := 0; i < polls; i++ {
+ if _, err := processTreeMemory(browser); err != nil {
+ t.Fatal(err)
+ }
+ }
+ rssOnly := time.Since(start) / polls
+ start = time.Now()
+ for i := 0; i < polls; i++ {
+ if page, unreadable := readTargets(targets); page == nil || page.Targets != tabs || unreadable != 0 {
+ t.Fatalf("poll %d read %+v / %d unreadable, want all %d tabs", i, page, unreadable, tabs)
+ }
+ }
+ allTargets := time.Since(start) / polls
+ start = time.Now()
+ for i := 0; i < polls; i++ {
+ if _, err := GetAggregatedMemoryMetrics(browser, targets); err != nil {
+ t.Fatal(err)
+ }
+ }
+ full := time.Since(start) / polls
+ t.Logf("per poll with %d tabs: %v total = %v process-tree RSS walk + %v for all target reads (~%v per target)", tabs, full, rssOnly, allTargets, allTargets/tabs)
+ if full > 5*time.Second {
+ t.Errorf("one poll over %d tabs took %v, longer than the dashboard's 5s emit interval", tabs, full)
+ }
+}
diff --git a/internal/bridge/observe_facade.go b/internal/bridge/observe_facade.go
index d397db94..1ea0edcb 100644
--- a/internal/bridge/observe_facade.go
+++ b/internal/bridge/observe_facade.go
@@ -31,6 +31,8 @@ type NetworkFilter = bridgeobserve.NetworkFilter
type NetworkMonitor = bridgeobserve.NetworkMonitor
type MemoryMetrics = bridgeobserve.MemoryMetrics
+type PageMetrics = bridgeobserve.PageMetrics
+
func frameIDs(tree RawFrameTree) []string {
return bridgeobserve.FrameIDs(tree)
}
@@ -129,5 +131,9 @@ func GetResponseBody(ctx context.Context, requestID string) (string, bool, error
}
func (b *Bridge) GetAggregatedMemoryMetrics() (*MemoryMetrics, error) {
- return bridgeobserve.GetAggregatedMemoryMetrics(b.BrowserCtx)
+ var targets map[string]context.Context
+ if tm, err := b.tabManager(); err == nil {
+ targets = tm.LiveTabContexts()
+ }
+ return bridgeobserve.GetAggregatedMemoryMetrics(b.BrowserCtx, targets)
}
diff --git a/internal/bridge/tab_manager.go b/internal/bridge/tab_manager.go
index be314a5f..4b1ebd43 100644
--- a/internal/bridge/tab_manager.go
+++ b/internal/bridge/tab_manager.go
@@ -129,6 +129,18 @@ func browserExecutorContext(ctx context.Context) (context.Context, error) {
return cdp.WithExecutor(ctx, c.Browser), nil
}
+func (tm *TabManager) LiveTabContexts() map[string]context.Context {
+ tm.mu.RLock()
+ defer tm.mu.RUnlock()
+ out := make(map[string]context.Context, len(tm.tabs))
+ for id, entry := range tm.tabs {
+ if entry.Ctx != nil && entry.Ctx.Err() == nil {
+ out[id] = entry.Ctx
+ }
+ }
+ return out
+}
+
func (tm *TabManager) trackedTabIDs() []string {
tm.mu.RLock()
defer tm.mu.RUnlock()
diff --git a/internal/orchestrator/health_transport.go b/internal/orchestrator/health_transport.go
index 9ab27174..5fb1a027 100644
--- a/internal/orchestrator/health_transport.go
+++ b/internal/orchestrator/health_transport.go
@@ -28,8 +28,10 @@ type remoteHealth struct {
}
type memoryMetrics struct {
- MemoryMB float64 `json:"memoryMB"`
- Renderers int `json:"renderers"`
+ MemoryMB float64 `json:"memoryMB"`
+ Renderers int `json:"renderers"`
+ Page *bridge.PageMetrics `json:"page,omitempty"`
+ UnreadableTargets int `json:"unreadableTargets"`
}
func (o *Orchestrator) fetchTabs(inst *InstanceInternal) ([]remoteTab, error) {
diff --git a/internal/orchestrator/instance_query.go b/internal/orchestrator/instance_query.go
index 6c89c620..55225fd5 100644
--- a/internal/orchestrator/instance_query.go
+++ b/internal/orchestrator/instance_query.go
@@ -328,15 +328,32 @@ func (o *Orchestrator) AllMetrics() []types.InstanceMetrics {
continue
}
all = append(all, types.InstanceMetrics{
- InstanceID: inst.ID,
- ProfileName: inst.ProfileName,
- MemoryMB: mem.MemoryMB,
- Renderers: mem.Renderers,
+ InstanceID: inst.ID,
+ ProfileName: inst.ProfileName,
+ MemoryMB: mem.MemoryMB,
+ Renderers: mem.Renderers,
+ Page: pageMetricsDTO(mem.Page),
+ UnreadableTargets: mem.UnreadableTargets,
})
}
return all
}
+func pageMetricsDTO(page *bridge.PageMetrics) *types.PageMetrics {
+ if page == nil {
+ return nil
+ }
+ return &types.PageMetrics{
+ Targets: page.Targets,
+ JSHeapUsedMB: page.JSHeapUsedMB,
+ JSHeapTotalMB: page.JSHeapTotalMB,
+ Documents: page.Documents,
+ Frames: page.Frames,
+ Nodes: page.Nodes,
+ JSEventListeners: page.JSEventListeners,
+ }
+}
+
func (o *Orchestrator) ScreencastURL(instanceID, tabID string) string {
o.mu.RLock()
defer o.mu.RUnlock()
diff --git a/internal/orchestrator/memory_metrics_parity_test.go b/internal/orchestrator/memory_metrics_parity_test.go
new file mode 100644
index 00000000..0a50a65c
--- /dev/null
+++ b/internal/orchestrator/memory_metrics_parity_test.go
@@ -0,0 +1,42 @@
+package orchestrator
+
+import (
+ "reflect"
+ "sort"
+ "strings"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/bridge/observe"
+)
+
+func jsonKeyPaths(typ reflect.Type, prefix string, into *[]string) {
+ if typ.Kind() == reflect.Ptr {
+ typ = typ.Elem()
+ }
+ for i := 0; i < typ.NumField(); i++ {
+ field := typ.Field(i)
+ key := strings.Split(field.Tag.Get("json"), ",")[0]
+ leaf := field.Type
+ if leaf.Kind() == reflect.Ptr {
+ leaf = leaf.Elem()
+ }
+ if leaf.Kind() == reflect.Struct {
+ jsonKeyPaths(leaf, prefix+key+".", into)
+ continue
+ }
+ *into = append(*into, prefix+key)
+ }
+}
+
+// The orchestrator decodes an instance's /metrics memory block into its own DTO;
+// a key missing here is a measurement the front door silently drops.
+func TestTheOrchestratorMemoryDTOMirrorsTheMeasuredMemoryMetricsKeyForKey(t *testing.T) {
+ var measured, wire []string
+ jsonKeyPaths(reflect.TypeOf(observe.MemoryMetrics{}), "", &measured)
+ jsonKeyPaths(reflect.TypeOf(memoryMetrics{}), "", &wire)
+ sort.Strings(measured)
+ sort.Strings(wire)
+ if strings.Join(measured, ",") != strings.Join(wire, ",") {
+ t.Fatalf("memoryMetrics keys %v, want the measured keys %v", wire, measured)
+ }
+}