Skip to content

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

feat(memory): add /memory usage, heap snapshot to file, and a top-retainers summary behind a memory capability (PIN-398)

Luigi Agosti02c720f84395
diff --git a/cmd/pinchtab/cmd_cli_memory.go b/cmd/pinchtab/cmd_cli_memory.go
new file mode 100644
index 00000000..2944763c
--- /dev/null
+++ b/cmd/pinchtab/cmd_cli_memory.go
@@ -0,0 +1,60 @@
+package main
+
+import (
+ browseractions "github.com/pinchtab/pinchtab/internal/cli/actions"
+ "github.com/spf13/cobra"
+)
+
+var memoryCmd = &cobra.Command{
+ Use: "memory",
+ Short: "JavaScript heap usage, heap snapshots and their summaries",
+ Long: `Read the tab's JavaScript heap usage and DOM counters.
+
+Pass --gc to run a garbage collection first so two reads compare live memory only.
+Subcommands: snapshot writes a V8 heap snapshot to a server-side file, and summary
+lists its top constructors and duplicate strings. Both need security.allowMemory,
+because a heap snapshot holds every string on the page, tokens included.`,
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.Memory(rt.client, rt.base, rt.token, cmd)
+ })
+ },
+}
+
+var memorySnapshotCmd = &cobra.Command{
+ Use: "snapshot",
+ Short: "Take a V8 heap snapshot to a server-side file",
+ Long: `Take a V8 heap snapshot of the tab. The server streams it to its own
+heapsnapshots directory and prints the id, path, size and node count; pass the id
+to 'pinchtab memory summary'. --out copies the file to a local path when the server
+shares this machine's filesystem. The file loads in Chrome DevTools (Memory panel).`,
+ Args: cobra.NoArgs,
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.MemorySnapshot(rt.client, rt.base, rt.token, cmd)
+ })
+ },
+}
+
+var memorySummaryCmd = &cobra.Command{
+ Use: "summary <id>",
+ Short: "Summarize a saved heap snapshot",
+ Long: "Summarize a saved heap snapshot: top constructors by self size and by count, total node and edge counts, and the largest duplicate strings.",
+ Args: cobra.ExactArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.MemorySummary(rt.client, rt.base, rt.token, cmd, args[0])
+ })
+ },
+}
+
+func configureMemoryFlags() {
+ memoryCmd.Flags().Bool("gc", false, "Collect garbage before reading")
+ memoryCmd.Flags().String("tab", "", "Target tab ID")
+ memoryCmd.Flags().Bool("json", false, "Output raw JSON")
+ memorySnapshotCmd.Flags().String("tab", "", "Target tab ID")
+ memorySnapshotCmd.Flags().String("out", "", "Copy the snapshot to this local path")
+ memorySnapshotCmd.Flags().Bool("json", false, "Output raw JSON")
+ memorySummaryCmd.Flags().Int("top", 20, "Rows per table (max 200)")
+ memorySummaryCmd.Flags().Bool("json", false, "Output raw JSON")
+}
diff --git a/cmd/pinchtab/cmd_cli_memory_test.go b/cmd/pinchtab/cmd_cli_memory_test.go
new file mode 100644
index 00000000..f7ebf308
--- /dev/null
+++ b/cmd/pinchtab/cmd_cli_memory_test.go
@@ -0,0 +1,33 @@
+package main
+
+import "testing"
+
+func TestMemoryCommandsAreRegisteredWithTheirFlags(t *testing.T) {
+ want := map[string][]string{
+ "snapshot": {"tab", "out", "json"},
+ "summary": {"top", "json"},
+ }
+ for _, sub := range memoryCmd.Commands() {
+ flags, ok := want[sub.Name()]
+ if !ok {
+ continue
+ }
+ for _, name := range flags {
+ if sub.Flags().Lookup(name) == nil {
+ t.Errorf("memory %s missing --%s", sub.Name(), name)
+ }
+ }
+ delete(want, sub.Name())
+ }
+ for name := range want {
+ t.Errorf("memory %s is not registered under memoryCmd", name)
+ }
+ for _, name := range []string{"gc", "tab", "json"} {
+ if memoryCmd.Flags().Lookup(name) == nil {
+ t.Errorf("memory missing --%s", name)
+ }
+ }
+ if def := memorySummaryCmd.Flags().Lookup("top").DefValue; def != "20" {
+ t.Errorf("summary --top default = %s, want 20", def)
+ }
+}
diff --git a/cmd/pinchtab/cmd_cli_register.go b/cmd/pinchtab/cmd_cli_register.go
index 945442e2..de12de6a 100644
--- a/cmd/pinchtab/cmd_cli_register.go
+++ b/cmd/pinchtab/cmd_cli_register.go
@@ -27,7 +27,7 @@ func browserRootCommands() []*cobra.Command {
downloadCmd, uploadCmd, findCmd, selectCmd, checkCmd, uncheckCmd, networkCmd, waitCmd,
keyboardCmd, keydownCmd, keyupCmd, scrollintoviewCmd, dialogCmd, consoleCmd, errorsCmd,
clipboardCmd, cacheCmd, cookiesCmd, setCmd, storageCmd, stateCmd, closeCmd, handoffCmd,
- resumeCmd, handoffStatusCmd, recordCmd, auditCmd, compareCmd, scrapeCmd, a11yCmd,
+ resumeCmd, handoffStatusCmd, recordCmd, auditCmd, compareCmd, scrapeCmd, a11yCmd, memoryCmd,
}
}
@@ -47,9 +47,11 @@ func registerBrowserCommands() {
networkCmd.AddCommand(networkRouteCmd, networkUnrouteCmd, networkRulesCmd)
recordCmd.AddCommand(recordStartCmd, recordStopCmd, recordStatusCmd)
a11yCmd.AddCommand(a11yAuditCmd)
+ memoryCmd.AddCommand(memorySnapshotCmd, memorySummaryCmd)
configureBrowserFlags()
configureA11yFlags()
+ configureMemoryFlags()
addRootCommands(rootCmds...)
}
diff --git a/docs/commands.md b/docs/commands.md
index 07d44336..9941ff45 100644
--- a/docs/commands.md
+++ b/docs/commands.md
@@ -210,8 +210,17 @@ pinchtab a11y audit --axe # Run axe-core in the page (industry rul
pinchtab a11y audit --axe --tags wcag2a,wcag2aa # axe: filter by WCAG tags
pinchtab a11y audit --axe --rules image-alt,label # axe: run only these rule ids
pinchtab a11y audit --axe --json # Full JSON envelope with per-node refs
+pinchtab memory # JS heap usage and DOM counters for the tab
+pinchtab memory --gc --json # Collect garbage first, raw JSON
+pinchtab memory snapshot # V8 heap snapshot to a server-side file (security.allowMemory)
+pinchtab memory snapshot --out app.heapsnapshot # Also copy it to a local path
+pinchtab memory summary <id> --top 5 # Top constructors and duplicate strings of a snapshot
```
+`pinchtab memory snapshot` and `pinchtab memory summary` need
+`security.allowMemory`, because a heap snapshot holds every string on the page.
+See [reference/memory.md](reference/memory.md).
+
`pinchtab a11y audit --axe` runs the vendored axe-core engine (see
[reference/a11y.md](reference/a11y.md)) in the page's isolated world, so page
script cannot tamper with the result. Each violation node that maps to a
diff --git a/docs/endpoints.md b/docs/endpoints.md
index d4147fe9..d4e4e1c4 100644
--- a/docs/endpoints.md
+++ b/docs/endpoints.md
@@ -95,6 +95,8 @@ POST /tab
POST /close
POST /tabs/{id}/close
GET /tabs/{id}/metrics
+GET /tabs/{id}/memory
+POST /tabs/{id}/memory/snapshot
POST /tabs/{id}/handoff
GET /tabs/{id}/handoff
POST /tabs/{id}/resume
@@ -178,8 +180,14 @@ POST /extract
POST /tabs/{id}/extract
POST /evaluate
POST /tabs/{id}/evaluate
+GET /memory
+POST /memory/snapshot
+GET /memory/snapshot/{snapshotId}/summary
```
+`/memory` reads the tab's JavaScript heap and DOM counters; the snapshot and summary
+routes need `security.allowMemory` — see [reference/memory.md](reference/memory.md).
+
`POST /actions` and `POST /macro` answer **200 whatever their steps did**: the envelope
reports the run, and each step's outcome is its own entry — `{"index", "success", "code",
"error"}` — beside the top-level `total`, `successful` and `failed` counts. Read `failed`
diff --git a/docs/mcp.md b/docs/mcp.md
index bde82a30..49b6eefd 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -114,7 +114,7 @@ PINCHTAB_TOKEN=<that-host-token> pinchtab --server http://remote:9867 mcp
## Available Tools
-PinchTab currently exposes 43 tools:
+PinchTab currently exposes 45 tools:
- Navigation: 9
- Interaction: 8
@@ -126,7 +126,7 @@ PinchTab currently exposes 43 tools:
- Human handoff: 3
- Wait utilities: 1
- Network: 5
-- Diagnostics: 3
+- Diagnostics: 5
- Dialog: 1
### Navigation
@@ -203,6 +203,8 @@ PinchTab currently exposes 43 tools:
- `pinchtab_console` — read (or `clear`) the tab's browser console logs
- `pinchtab_errors` — read (or `clear`) the tab's uncaught JavaScript exceptions; check this when a snapshot looks healthy but actions do nothing
- `pinchtab_a11y_audit` — accessibility audit; `engine=axe` runs vendored axe-core in the isolated world and returns ref-mapped violations with WCAG tags and help URLs
+- `pinchtab_memory` — JavaScript heap usage and DOM counters for the tab; `gc=true` collects garbage first so two reads compare retained memory
+- `pinchtab_memory_snapshot` — take a V8 heap snapshot to a server-side file and return only its path and a summary (top constructors, duplicate strings); needs `security.allowMemory`. See [Memory](reference/memory.md)
### Dialog
diff --git a/docs/reference/config.md b/docs/reference/config.md
index ea2eaf48..0f0f1f90 100644
--- a/docs/reference/config.md
+++ b/docs/reference/config.md
@@ -240,10 +240,12 @@ Current nested file-config shape:
"allowScreencast": false,
"allowDownload": false,
"allowCookies": false,
+ "allowMemory": false,
"allowFileScheme": false,
"allowedDomains": ["127.0.0.1", "localhost", "::1"],
"downloadAllowedDomains": [],
"downloadMaxBytes": 20971520,
+ "memorySnapshotMaxBytes": 536870912,
"allowUpload": false,
"allowClipboard": false,
"uploadMaxRequestBytes": 10485760,
@@ -603,6 +605,20 @@ either way, but it only raises the level when neither `--log-level` nor
`--log-level debug` is how you override it for one run. `pinchtab bridge` reads the
same key and accepts the same flag.
+### Memory Diagnostics
+
+| Setting | Default | Effect |
+| --- | --- | --- |
+| `security.allowMemory` | `false` | Enables `POST /memory/snapshot` and `GET /memory/snapshot/{snapshotId}/summary` (code `memory_disabled` when off). `GET /memory` needs no capability. |
+| `security.memorySnapshotMaxBytes` | `536870912` (512 MB) | Size cap for one heap snapshot, max 4 GB; a larger snapshot is aborted with `memory_snapshot_too_large` and no file is left behind |
+
+A heap snapshot contains every string on the page, tokens included, which is why
+it sits behind its own capability. See [memory.md](memory.md).
+
+```bash
+pinchtab config set security.allowMemory true
+```
+
### Network Bind With Token
```bash
diff --git a/internal/bridge/observe/memory.go b/internal/bridge/observe/memory.go
new file mode 100644
index 00000000..ebdf5c71
--- /dev/null
+++ b/internal/bridge/observe/memory.go
@@ -0,0 +1,162 @@
+package observe
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "sync"
+
+ "github.com/chromedp/cdproto/heapprofiler"
+ "github.com/chromedp/cdproto/performance"
+ "github.com/chromedp/cdproto/runtime"
+ "github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/cdptk"
+)
+
+type HeapUsage struct {
+ UsedJSHeapSize int64 `json:"usedJSHeapSize"`
+ TotalJSHeapSize int64 `json:"totalJSHeapSize"`
+ JSHeapSizeLimit int64 `json:"jsHeapSizeLimit"`
+ Documents int `json:"documents"`
+ Nodes int `json:"nodes"`
+ Listeners int `json:"listeners"`
+ Frames int `json:"frames"`
+ GC bool `json:"gc"`
+}
+
+const heapLimitExpression = `(() => { const m = globalThis.performance && performance.memory; return m ? m.jsHeapSizeLimit : 0; })()`
+
+func ReadHeapUsage(ctx context.Context, collectGarbage bool) (*HeapUsage, error) {
+ usage := &HeapUsage{GC: collectGarbage}
+ if collectGarbage {
+ if err := CollectGarbage(ctx); err != nil {
+ return nil, err
+ }
+ }
+ err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ used, total, _, _, err := runtime.GetHeapUsage().Do(ctx)
+ if err != nil {
+ return fmt.Errorf("runtime.getHeapUsage: %w", err)
+ }
+ usage.UsedJSHeapSize = int64(used)
+ usage.TotalJSHeapSize = int64(total)
+
+ if err := performance.Enable().Do(ctx); err != nil {
+ return fmt.Errorf("performance.enable: %w", err)
+ }
+ metrics, err := performance.GetMetrics().Do(ctx)
+ if err != nil {
+ return fmt.Errorf("performance.getMetrics: %w", err)
+ }
+ for _, m := range metrics {
+ switch m.Name {
+ case "Documents":
+ usage.Documents = int(m.Value)
+ case "Nodes":
+ usage.Nodes = int(m.Value)
+ case "JSEventListeners":
+ usage.Listeners = int(m.Value)
+ case "Frames":
+ usage.Frames = int(m.Value)
+ }
+ }
+ return nil
+ }))
+ if err != nil {
+ return nil, err
+ }
+ limit, err := readHeapLimit(ctx)
+ if err != nil {
+ return nil, err
+ }
+ usage.JSHeapSizeLimit = limit
+ return usage, nil
+}
+
+func readHeapLimit(ctx context.Context) (int64, error) {
+ contextID, err := cdptk.IsolatedContextID(ctx, "")
+ if err != nil {
+ return 0, fmt.Errorf("isolated context for heap limit: %w", err)
+ }
+ var limit int64
+ err = chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ res, exc, err := runtime.Evaluate(heapLimitExpression).
+ WithContextID(runtime.ExecutionContextID(contextID)).
+ WithReturnByValue(true).
+ Do(ctx)
+ if err != nil {
+ return err
+ }
+ if exc != nil {
+ return fmt.Errorf("evaluate heap limit: %s", exc.Text)
+ }
+ if res == nil || len(res.Value) == 0 {
+ return nil
+ }
+ var v float64
+ if err := json.Unmarshal(res.Value, &v); err != nil {
+ return fmt.Errorf("decode heap limit: %w", err)
+ }
+ limit = int64(v)
+ return nil
+ }))
+ if err != nil {
+ return 0, fmt.Errorf("read heap limit: %w", err)
+ }
+ return limit, nil
+}
+
+func CollectGarbage(ctx context.Context) error {
+ return chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ if err := heapprofiler.Enable().Do(ctx); err != nil {
+ return fmt.Errorf("heapprofiler.enable: %w", err)
+ }
+ if err := heapprofiler.CollectGarbage().Do(ctx); err != nil {
+ return fmt.Errorf("heapprofiler.collectGarbage: %w", err)
+ }
+ return nil
+ }))
+}
+
+func TakeHeapSnapshot(ctx context.Context, write func(chunk string) error) error {
+ if c := chromedp.FromContext(ctx); c == nil || c.Target == nil {
+ return chromedp.ErrInvalidContext
+ }
+ runCtx, cancelRun := context.WithCancel(ctx)
+ defer cancelRun()
+
+ var mu sync.Mutex
+ var writeErr error
+ chromedp.ListenTarget(runCtx, func(ev any) {
+ chunk, ok := ev.(*heapprofiler.EventAddHeapSnapshotChunk)
+ if !ok {
+ return
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ if writeErr != nil {
+ return
+ }
+ if err := write(chunk.Chunk); err != nil {
+ writeErr = err
+ cancelRun()
+ }
+ })
+
+ runErr := chromedp.Run(runCtx, chromedp.ActionFunc(func(ctx context.Context) error {
+ if err := heapprofiler.Enable().Do(ctx); err != nil {
+ return fmt.Errorf("heapprofiler.enable: %w", err)
+ }
+ if err := heapprofiler.TakeHeapSnapshot().WithReportProgress(false).Do(ctx); err != nil {
+ return fmt.Errorf("heapprofiler.takeHeapSnapshot: %w", err)
+ }
+ return nil
+ }))
+
+ mu.Lock()
+ defer mu.Unlock()
+ if writeErr != nil {
+ return writeErr
+ }
+ return runErr
+}
diff --git a/internal/bridge/observe/memory_browser_test.go b/internal/bridge/observe/memory_browser_test.go
new file mode 100644
index 00000000..c19cb97b
--- /dev/null
+++ b/internal/bridge/observe/memory_browser_test.go
@@ -0,0 +1,120 @@
+package observe
+
+import (
+ "errors"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/heapsnap"
+)
+
+const leakPage = `<html><body><script>window.leak = []; function grow(){ window.leak.push(Array.from({length: 1500000}, (_, i) => i + 0.5)); }</script></body></html>`
+
+func TestGarbageCollectionReclaimsADroppedArray(t *testing.T) {
+ tab := openTab(t, launchBrowser(t), leakPage)
+ baseline, err := ReadHeapUsage(tab, true)
+ if err != nil {
+ t.Fatalf("baseline: %v", err)
+ }
+ if err := chromedp.Run(tab, chromedp.Evaluate(`grow(); grow(); true`, nil)); err != nil {
+ t.Fatal(err)
+ }
+ grown, err := ReadHeapUsage(tab, false)
+ if err != nil {
+ t.Fatalf("grown: %v", err)
+ }
+ if grown.UsedJSHeapSize < baseline.UsedJSHeapSize+16<<20 {
+ t.Fatalf("used heap %d after two 12MB arrays, baseline %d: the leak did not show", grown.UsedJSHeapSize, baseline.UsedJSHeapSize)
+ }
+ if err := chromedp.Run(tab, chromedp.Evaluate(`window.leak = null; true`, nil)); err != nil {
+ t.Fatal(err)
+ }
+ collected, err := ReadHeapUsage(tab, true)
+ if err != nil {
+ t.Fatalf("collected: %v", err)
+ }
+ if !collected.GC || grown.GC {
+ t.Fatalf("gc flags = %v/%v, want the reading to say whether it collected first", grown.GC, collected.GC)
+ }
+ if collected.UsedJSHeapSize > grown.UsedJSHeapSize-16<<20 {
+ t.Fatalf("used heap %d after release and gc, %d before: gc did not reclaim the dropped arrays", collected.UsedJSHeapSize, grown.UsedJSHeapSize)
+ }
+ if collected.TotalJSHeapSize < collected.UsedJSHeapSize || collected.JSHeapSizeLimit <= collected.TotalJSHeapSize {
+ t.Errorf("heap sizes used=%d total=%d limit=%d, want used <= total < limit", collected.UsedJSHeapSize, collected.TotalJSHeapSize, collected.JSHeapSizeLimit)
+ }
+ if collected.Documents < 1 || collected.Frames < 1 || collected.Nodes < 1 {
+ t.Errorf("counters = %+v, want a live document, frame and nodes", collected)
+ }
+}
+
+func TestHeapSnapshotStreamsAValidV8Snapshot(t *testing.T) {
+ tab := openTab(t, launchBrowser(t), `<html><body><script>window.keep = Array.from({length: 50}, () => [1, 2, 3]);</script></body></html>`)
+ path := filepath.Join(t.TempDir(), "tab"+heapsnap.Ext)
+ f, err := os.Create(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ chunks := 0
+ sink := heapsnap.NewSink(f, 0)
+ err = TakeHeapSnapshot(tab, func(chunk string) error {
+ chunks++
+ return sink.WriteChunk(chunk)
+ })
+ if cerr := f.Close(); cerr != nil {
+ t.Fatal(cerr)
+ }
+ if err != nil {
+ t.Fatalf("snapshot: %v", err)
+ }
+ info, err := os.Stat(path)
+ if err != nil || info.Size() != sink.Bytes() || chunks < 2 {
+ t.Fatalf("file %v size vs sink %d over %d chunks: %v", info, sink.Bytes(), chunks, err)
+ }
+
+ raw, err := os.Open(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ header, err := heapsnap.ReadHeader(raw)
+ _ = raw.Close()
+ if err != nil {
+ t.Fatalf("header: %v", err)
+ }
+ if len(header.Meta.NodeFields) == 0 || header.NodeCount == 0 {
+ t.Fatalf("header = %+v, want snapshot.meta with node fields and a node count", header)
+ }
+ agg, err := heapsnap.ParseFile(path)
+ if err != nil {
+ t.Fatalf("parse: %v", err)
+ }
+ if agg.NodeCount != header.NodeCount {
+ t.Fatalf("nodes array holds %d nodes, node_count says %d", agg.NodeCount, header.NodeCount)
+ }
+ found := false
+ for _, c := range agg.Summary(heapsnap.MaxTop).TopByCount {
+ if c.Name == "Array" {
+ found = true
+ }
+ }
+ if !found {
+ t.Fatalf("Array missing from the constructors of a page holding 51 arrays")
+ }
+}
+
+func TestHeapSnapshotStopsAtTheSinkRefusalAndLeavesTheTabUsable(t *testing.T) {
+ tab := openTab(t, launchBrowser(t), "<html><body>hi</body></html>")
+ sink := heapsnap.NewSink(discard{}, 1024)
+ err := TakeHeapSnapshot(tab, sink.WriteChunk)
+ if !errors.Is(err, heapsnap.ErrTooLarge) {
+ t.Fatalf("err = %v, want ErrTooLarge", err)
+ }
+ if _, err := ReadHeapUsage(tab, false); err != nil {
+ t.Fatalf("tab unusable after an aborted snapshot: %v", err)
+ }
+}
+
+type discard struct{}
+
+func (discard) Write(p []byte) (int, error) { return len(p), nil }
diff --git a/internal/cli/actions/actions_memory.go b/internal/cli/actions/actions_memory.go
new file mode 100644
index 00000000..f9bd68a7
--- /dev/null
+++ b/internal/cli/actions/actions_memory.go
@@ -0,0 +1,158 @@
+package actions
+
+import (
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "os"
+ "strconv"
+
+ "github.com/pinchtab/pinchtab/internal/cli"
+ "github.com/pinchtab/pinchtab/internal/cli/apiclient"
+ "github.com/pinchtab/pinchtab/internal/heapsnap"
+ "github.com/spf13/cobra"
+)
+
+type memoryUsage struct {
+ TabID string `json:"tabId"`
+ UsedJSHeapSize int64 `json:"usedJSHeapSize"`
+ TotalJSHeapSize int64 `json:"totalJSHeapSize"`
+ JSHeapSizeLimit int64 `json:"jsHeapSizeLimit"`
+ Documents int `json:"documents"`
+ Nodes int `json:"nodes"`
+ Listeners int `json:"listeners"`
+ Frames int `json:"frames"`
+ GC bool `json:"gc"`
+}
+
+type memorySnapshot struct {
+ ID string `json:"id"`
+ Path string `json:"path"`
+ Bytes int64 `json:"bytes"`
+ NodeCount int `json:"nodeCount"`
+ DurationMs int64 `json:"durationMs"`
+ TabID string `json:"tabId"`
+}
+
+type memorySummary struct {
+ ID string `json:"id"`
+ heapsnap.Summary
+}
+
+func Memory(client *http.Client, base, token string, cmd *cobra.Command) {
+ params := url.Values{}
+ if v, _ := cmd.Flags().GetString("tab"); v != "" {
+ params.Set("tabId", v)
+ }
+ if gc, _ := cmd.Flags().GetBool("gc"); gc {
+ params.Set("gc", "true")
+ }
+ if jsonOutput, _ := cmd.Flags().GetBool("json"); jsonOutput {
+ apiclient.DoGet(client, base, token, "/memory", params)
+ return
+ }
+ body := apiclient.DoGetRaw(client, base, token, "/memory", params)
+ var usage memoryUsage
+ if err := json.Unmarshal(body, &usage); err != nil {
+ fmt.Println(string(body))
+ return
+ }
+ fmt.Print(formatMemoryUsage(usage))
+}
+
+func formatMemoryUsage(u memoryUsage) string {
+ gc := ""
+ if u.GC {
+ gc = " (after gc)"
+ }
+ return fmt.Sprintf("heap used %s of %s (limit %s)%s\ndocuments=%d nodes=%d listeners=%d frames=%d\n",
+ formatBytes(u.UsedJSHeapSize), formatBytes(u.TotalJSHeapSize), formatBytes(u.JSHeapSizeLimit), gc,
+ u.Documents, u.Nodes, u.Listeners, u.Frames)
+}
+
+func MemorySnapshot(client *http.Client, base, token string, cmd *cobra.Command) {
+ body := map[string]any{}
+ if v, _ := cmd.Flags().GetString("tab"); v != "" {
+ body["tabId"] = v
+ }
+ raw := apiclient.DoPostRaw(client, base, token, "/memory/snapshot", body)
+ var snap memorySnapshot
+ if err := json.Unmarshal(raw, &snap); err != nil {
+ cli.Fatal("Decode heap snapshot response: %v", err)
+ }
+ if out, _ := cmd.Flags().GetString("out"); out != "" {
+ if err := copyLocalFile(snap.Path, out); err != nil {
+ cli.Fatal("Copy %s → %s: %v (the file stays on the server at %s)", snap.Path, out, err, snap.Path)
+ }
+ snap.Path = out
+ }
+ if jsonOutput, _ := cmd.Flags().GetBool("json"); jsonOutput {
+ encoded, _ := json.MarshalIndent(snap, "", " ")
+ fmt.Println(string(encoded))
+ return
+ }
+ fmt.Println(cli.StyleStdout(cli.SuccessStyle, fmt.Sprintf("Heap snapshot %s → %s", snap.ID, snap.Path)))
+ fmt.Printf("%s, %d nodes, %d ms\n", formatBytes(snap.Bytes), snap.NodeCount, snap.DurationMs)
+ fmt.Printf("Summarize with: pinchtab memory summary %s\n", snap.ID)
+}
+
+func copyLocalFile(src, dst string) error {
+ in, err := os.Open(src)
+ if err != nil {
+ return err
+ }
+ defer func() { _ = in.Close() }()
+ out, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
+ if err != nil {
+ return err
+ }
+ if _, err := io.Copy(out, in); err != nil {
+ _ = out.Close()
+ return err
+ }
+ return out.Close()
+}
+
+func MemorySummary(client *http.Client, base, token string, cmd *cobra.Command, id string) {
+ params := url.Values{}
+ if top, _ := cmd.Flags().GetInt("top"); top > 0 {
+ params.Set("top", strconv.Itoa(top))
+ }
+ path := "/memory/snapshot/" + url.PathEscape(id) + "/summary"
+ if jsonOutput, _ := cmd.Flags().GetBool("json"); jsonOutput {
+ apiclient.DoGet(client, base, token, path, params)
+ return
+ }
+ body := apiclient.DoGetRaw(client, base, token, path, params)
+ var summary memorySummary
+ if err := json.Unmarshal(body, &summary); err != nil {
+ fmt.Println(string(body))
+ return
+ }
+ fmt.Print(formatMemorySummary(summary))
+}
+
+func formatMemorySummary(s memorySummary) string {
+ out := fmt.Sprintf("%s: %d nodes, %d edges, %s self size\n", s.ID, s.NodeCount, s.EdgeCount, formatBytes(s.TotalSelfSize))
+ out += "\nTop constructors by self size\n" + constructorTable(s.TopBySize)
+ out += "\nTop constructors by count\n" + constructorTable(s.TopByCount)
+ out += "\nDuplicate strings\n"
+ if len(s.DuplicateStrings) == 0 {
+ return out + " (none)\n"
+ }
+ out += fmt.Sprintf(" %8s %10s %s\n", "COUNT", "SELF SIZE", "VALUE")
+ for _, d := range s.DuplicateStrings {
+ out += fmt.Sprintf(" %8d %10s %q\n", d.Count, formatBytes(d.SelfSize), d.Value)
+ }
+ return out
+}
+
+func constructorTable(rows []heapsnap.Constructor) string {
+ out := fmt.Sprintf(" %-32s %8s %10s\n", "CONSTRUCTOR", "COUNT", "SELF SIZE")
+ for _, c := range rows {
+ out += fmt.Sprintf(" %-32s %8d %10s\n", c.Name, c.Count, formatBytes(c.SelfSize))
+ }
+ return out
+}
diff --git a/internal/cli/actions/actions_memory_test.go b/internal/cli/actions/actions_memory_test.go
new file mode 100644
index 00000000..faea2455
--- /dev/null
+++ b/internal/cli/actions/actions_memory_test.go
@@ -0,0 +1,105 @@
+package actions
+
+import (
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/spf13/cobra"
+)
+
+func memoryCommand(t *testing.T, args ...string) *cobra.Command {
+ t.Helper()
+ cmd := &cobra.Command{Use: "memory"}
+ cmd.Flags().Bool("gc", false, "")
+ cmd.Flags().Bool("json", false, "")
+ cmd.Flags().String("tab", "", "")
+ cmd.Flags().String("out", "", "")
+ cmd.Flags().Int("top", 0, "")
+ if err := cmd.Flags().Parse(args); err != nil {
+ t.Fatalf("parse flags: %v", err)
+ }
+ return cmd
+}
+
+func TestMemoryUsageSendsGCAndTabAndPrintsTheCounters(t *testing.T) {
+ var got string
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ got = r.Method + " " + r.URL.RequestURI()
+ _, _ = io.WriteString(w, `{"tabId":"t1","usedJSHeapSize":2097152,"totalJSHeapSize":4194304,"jsHeapSizeLimit":4294967296,"documents":1,"nodes":42,"listeners":3,"frames":1,"gc":true}`)
+ }))
+ defer srv.Close()
+
+ out := captureStdout(t, func() {
+ Memory(srv.Client(), srv.URL, "", memoryCommand(t, "--gc", "--tab", "t1"))
+ })
+ if got != "GET /memory?gc=true&tabId=t1" {
+ t.Fatalf("request = %q", got)
+ }
+ for _, want := range []string{"heap used 2.0 MB of 4.0 MB", "(after gc)", "nodes=42", "listeners=3"} {
+ if !strings.Contains(out, want) {
+ t.Errorf("output lacks %q:\n%s", want, out)
+ }
+ }
+}
+
+func TestMemorySnapshotCopiesToOutAndReportsTheLocalPath(t *testing.T) {
+ serverFile := filepath.Join(t.TempDir(), "heap_1.heapsnapshot")
+ if err := os.WriteFile(serverFile, []byte(`{"snapshot":{}}`), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ var body map[string]any
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost || r.URL.Path != "/memory/snapshot" {
+ t.Errorf("request = %s %s", r.Method, r.URL.Path)
+ }
+ _ = json.NewDecoder(r.Body).Decode(&body)
+ encoded, _ := json.Marshal(map[string]any{"id": "heap_1", "path": serverFile, "bytes": 15, "nodeCount": 9, "durationMs": 12, "tabId": "t1"})
+ _, _ = w.Write(encoded)
+ }))
+ defer srv.Close()
+
+ local := filepath.Join(t.TempDir(), "copy.heapsnapshot")
+ out := captureStdout(t, func() {
+ MemorySnapshot(srv.Client(), srv.URL, "", memoryCommand(t, "--tab", "t1", "--out", local))
+ })
+ if body["tabId"] != "t1" {
+ t.Fatalf("body = %v, want the tab forwarded", body)
+ }
+ copied, err := os.ReadFile(local)
+ if err != nil || string(copied) != `{"snapshot":{}}` {
+ t.Fatalf("copy = %q, %v", copied, err)
+ }
+ if !strings.Contains(out, "heap_1 → "+local) || !strings.Contains(out, "pinchtab memory summary heap_1") {
+ t.Fatalf("output = %s", out)
+ }
+}
+
+func TestMemorySummaryPrintsTheConstructorTable(t *testing.T) {
+ var got string
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ got = r.URL.RequestURI()
+ _, _ = io.WriteString(w, `{"id":"heap_1","nodeCount":20,"edgeCount":6,"totalSelfSize":3536,
+ "topBySize":[{"name":"Array","count":3,"selfSize":1664}],
+ "topByCount":[{"name":"(string)","count":8,"selfSize":228}],
+ "duplicateStrings":[{"value":"secret","length":6,"count":3,"selfSize":120}]}`)
+ }))
+ defer srv.Close()
+
+ out := captureStdout(t, func() {
+ MemorySummary(srv.Client(), srv.URL, "", memoryCommand(t, "--top", "5"), "heap_1")
+ })
+ if got != "/memory/snapshot/heap_1/summary?top=5" {
+ t.Fatalf("request = %q", got)
+ }
+ for _, want := range []string{"heap_1: 20 nodes, 6 edges", "CONSTRUCTOR", "Array", "(string)", `"secret"`} {
+ if !strings.Contains(out, want) {
+ t.Errorf("output lacks %q:\n%s", want, out)
+ }
+ }
+}
diff --git a/internal/config/config_file.go b/internal/config/config_file.go
index 09fc2bfc..83cf507b 100644
--- a/internal/config/config_file.go
+++ b/internal/config/config_file.go
@@ -124,7 +124,9 @@ func DefaultFileConfig() FileConfig {
allowDownload := false
allowCookies := false
allowNetworkIntercept := false
+ allowMemory := false
downloadMaxBytes := DefaultDownloadMaxBytes
+ memorySnapshotMaxBytes := DefaultMemorySnapshotMaxBytes
allowUpload := false
allowClipboard := false
allowStateExport := false
@@ -186,8 +188,10 @@ func DefaultFileConfig() FileConfig {
AllowDownload: &allowDownload,
AllowCookies: &allowCookies,
AllowNetworkIntercept: &allowNetworkIntercept,
+ AllowMemory: &allowMemory,
DownloadAllowedDomains: []string{},
DownloadMaxBytes: &downloadMaxBytes,
+ MemorySnapshotMaxBytes: &memorySnapshotMaxBytes,
AllowUpload: &allowUpload,
AllowClipboard: &allowClipboard,
AllowStateExport: &allowStateExport,
diff --git a/internal/config/config_file_json.go b/internal/config/config_file_json.go
index 0845b470..fb544840 100644
--- a/internal/config/config_file_json.go
+++ b/internal/config/config_file_json.go
@@ -88,10 +88,12 @@ type securityConfigJSON struct {
AllowDownload *bool `json:"allowDownload"`
AllowCookies *bool `json:"allowCookies"`
AllowNetworkIntercept *bool `json:"allowNetworkIntercept"`
+ AllowMemory *bool `json:"allowMemory"`
AllowFileScheme *bool `json:"allowFileScheme"`
AllowedDomains []string `json:"allowedDomains"`
DownloadAllowedDomains []string `json:"downloadAllowedDomains"`
DownloadMaxBytes *int `json:"downloadMaxBytes"`
+ MemorySnapshotMaxBytes *int `json:"memorySnapshotMaxBytes"`
AllowUpload *bool `json:"allowUpload"`
AllowClipboard *bool `json:"allowClipboard"`
AllowStateExport *bool `json:"allowStateExport"`
diff --git a/internal/config/config_file_marshal.go b/internal/config/config_file_marshal.go
index e4150a45..553f657b 100644
--- a/internal/config/config_file_marshal.go
+++ b/internal/config/config_file_marshal.go
@@ -326,10 +326,12 @@ func (s SecurityConfig) wire() securityConfigJSON {
AllowDownload: s.AllowDownload,
AllowCookies: s.AllowCookies,
AllowNetworkIntercept: s.AllowNetworkIntercept,
+ AllowMemory: s.AllowMemory,
AllowFileScheme: s.AllowFileScheme,
AllowedDomains: effectiveSecurityAllowedDomains(s),
DownloadAllowedDomains: copyStringSlice(s.DownloadAllowedDomains),
DownloadMaxBytes: s.DownloadMaxBytes,
+ MemorySnapshotMaxBytes: s.MemorySnapshotMaxBytes,
AllowUpload: s.AllowUpload,
AllowClipboard: s.AllowClipboard,
AllowStateExport: s.AllowStateExport,
@@ -469,10 +471,12 @@ func securityConfigFromRuntime(cfg *RuntimeConfig) SecurityConfig {
AllowDownload: ptr(cfg.AllowDownload),
AllowCookies: ptr(cfg.AllowCookies),
AllowNetworkIntercept: ptr(cfg.AllowNetworkIntercept),
+ AllowMemory: ptr(cfg.AllowMemory),
AllowFileScheme: ptr(cfg.AllowFileScheme),
AllowedDomains: cloneStringSlice(cfg.AllowedDomains),
DownloadAllowedDomains: cloneStringSlice(cfg.DownloadAllowedDomains),
DownloadMaxBytes: ptr(cfg.EffectiveDownloadMaxBytes()),
+ MemorySnapshotMaxBytes: ptr(cfg.EffectiveMemorySnapshotMaxBytes()),
AllowUpload: ptr(cfg.AllowUpload),
AllowClipboard: ptr(cfg.AllowClipboard),
AllowStateExport: ptr(cfg.AllowStateExport),
diff --git a/internal/config/config_load.go b/internal/config/config_load.go
index 53f860bf..e034bfcb 100644
--- a/internal/config/config_load.go
+++ b/internal/config/config_load.go
@@ -193,12 +193,14 @@ func LoadConfig() (*RuntimeConfig, []LoadDiagnostic, error) {
AllowDownload: false,
AllowCookies: false,
AllowNetworkIntercept: false,
+ AllowMemory: false,
AllowFileScheme: false,
RetainNetworkBodies: false,
RetainNetworkBodyMaxBytes: 256 * 1024,
AllowedDomains: nil,
DownloadAllowedDomains: nil,
DownloadMaxBytes: DefaultDownloadMaxBytes,
+ MemorySnapshotMaxBytes: DefaultMemorySnapshotMaxBytes,
AllowUpload: false,
AllowClipboard: false,
AllowStateExport: false,
@@ -457,6 +459,9 @@ func applySecurityConfig(cfg *RuntimeConfig, s SecurityConfig) {
if s.AllowNetworkIntercept != nil {
cfg.AllowNetworkIntercept = *s.AllowNetworkIntercept
}
+ if s.AllowMemory != nil {
+ cfg.AllowMemory = *s.AllowMemory
+ }
if s.AllowFileScheme != nil {
cfg.AllowFileScheme = *s.AllowFileScheme
}
@@ -464,6 +469,9 @@ func applySecurityConfig(cfg *RuntimeConfig, s SecurityConfig) {
if s.DownloadMaxBytes != nil {
cfg.DownloadMaxBytes = clampPositiveLimit(*s.DownloadMaxBytes, DefaultDownloadMaxBytes, MaxDownloadMaxBytes)
}
+ if s.MemorySnapshotMaxBytes != nil {
+ cfg.MemorySnapshotMaxBytes = clampPositiveLimit(*s.MemorySnapshotMaxBytes, DefaultMemorySnapshotMaxBytes, MaxMemorySnapshotMaxBytes)
+ }
if s.AllowUpload != nil {
cfg.AllowUpload = *s.AllowUpload
}
diff --git a/internal/config/config_types.go b/internal/config/config_types.go
index 2005fc4e..f483eb9b 100644
--- a/internal/config/config_types.go
+++ b/internal/config/config_types.go
@@ -30,12 +30,14 @@ type RuntimeConfig struct {
AllowDownload bool
AllowCookies bool
AllowNetworkIntercept bool
+ AllowMemory bool
AllowFileScheme bool
// AllowedDomains is the unified per-instance allowlist sourced from
// security.allowedDomains in the file config.
AllowedDomains []string
DownloadAllowedDomains []string
DownloadMaxBytes int
+ MemorySnapshotMaxBytes int
AllowUpload bool
AllowClipboard bool
AllowStateExport bool
@@ -458,10 +460,12 @@ type SecurityConfig struct {
AllowDownload *bool `json:"allowDownload,omitempty"`
AllowCookies *bool `json:"allowCookies,omitempty"`
AllowNetworkIntercept *bool `json:"allowNetworkIntercept,omitempty"`
+ AllowMemory *bool `json:"allowMemory,omitempty"`
AllowFileScheme *bool `json:"allowFileScheme,omitempty"`
AllowedDomains []string `json:"allowedDomains,omitempty"`
DownloadAllowedDomains []string `json:"downloadAllowedDomains,omitempty"`
DownloadMaxBytes *int `json:"downloadMaxBytes,omitempty"`
+ MemorySnapshotMaxBytes *int `json:"memorySnapshotMaxBytes,omitempty"`
AllowUpload *bool `json:"allowUpload,omitempty"`
AllowClipboard *bool `json:"allowClipboard,omitempty"`
AllowStateExport *bool `json:"allowStateExport,omitempty"`
diff --git a/internal/config/editor_get.go b/internal/config/editor_get.go
index 99e2f17b..dc833e38 100644
--- a/internal/config/editor_get.go
+++ b/internal/config/editor_get.go
@@ -357,6 +357,8 @@ func getSecurityField(s *SecurityConfig, field string) (string, error) {
return formatStringPtr(s.StateEncryptionKey), nil
case "allowNetworkIntercept":
return formatBoolPtr(s.AllowNetworkIntercept), nil
+ case "allowMemory":
+ return formatBoolPtr(s.AllowMemory), nil
case "allowFileScheme":
return formatBoolPtr(s.AllowFileScheme), nil
case "allowedDomains":
@@ -365,6 +367,8 @@ func getSecurityField(s *SecurityConfig, field string) (string, error) {
return strings.Join(s.DownloadAllowedDomains, ","), nil
case "downloadMaxBytes":
return formatIntPtr(s.DownloadMaxBytes), nil
+ case "memorySnapshotMaxBytes":
+ return formatIntPtr(s.MemorySnapshotMaxBytes), nil
case "allowUpload":
return formatBoolPtr(s.AllowUpload), nil
case "uploadMaxRequestBytes":
diff --git a/internal/config/editor_set.go b/internal/config/editor_set.go
index faf7a106..67cca69f 100644
--- a/internal/config/editor_set.go
+++ b/internal/config/editor_set.go
@@ -503,6 +503,7 @@ var securityBoolFields = map[string]func(*SecurityConfig) **bool{
"allowStateExport": func(s *SecurityConfig) **bool { return &s.AllowStateExport },
"allowUpload": func(s *SecurityConfig) **bool { return &s.AllowUpload },
"allowNetworkIntercept": func(s *SecurityConfig) **bool { return &s.AllowNetworkIntercept },
+ "allowMemory": func(s *SecurityConfig) **bool { return &s.AllowMemory },
"allowFileScheme": func(s *SecurityConfig) **bool { return &s.AllowFileScheme },
"trustLoopbackProxy": func(s *SecurityConfig) **bool { return &s.TrustLoopbackProxy },
}
@@ -542,6 +543,13 @@ func setSecurityField(s *SecurityConfig, field, value string) error {
}
s.DownloadMaxBytes = &n
return nil
+ case "memorySnapshotMaxBytes":
+ n, err := strconv.Atoi(value)
+ if err != nil {
+ return fmt.Errorf("security.memorySnapshotMaxBytes must be a number: %w", err)
+ }
+ s.MemorySnapshotMaxBytes = &n
+ return nil
case "uploadMaxRequestBytes":
n, err := strconv.Atoi(value)
if err != nil {
diff --git a/internal/config/file_config_from_runtime_golden_test.go b/internal/config/file_config_from_runtime_golden_test.go
index 07a95eb1..64f2c5c4 100644
--- a/internal/config/file_config_from_runtime_golden_test.go
+++ b/internal/config/file_config_from_runtime_golden_test.go
@@ -28,8 +28,8 @@ const populatedFileConfigJSON = `{
"stealthLevel": "max", "tabEvictionPolicy": "reject", "dialogAutoAccept": true,
"tabPolicy": {"allowedDomains": ["a.example"], "blockedDomains": ["b.example"]}},
"security": {"allowEvaluate": true, "allowMacro": true, "allowScreencast": true, "allowDownload": true,
- "allowCookies": true, "allowNetworkIntercept": true, "allowFileScheme": true,
- "allowedDomains": [], "downloadAllowedDomains": ["dl.example"], "downloadMaxBytes": 123456,
+ "allowCookies": true, "allowNetworkIntercept": true, "allowMemory": true, "allowFileScheme": true,
+ "allowedDomains": [], "downloadAllowedDomains": ["dl.example"], "downloadMaxBytes": 123456, "memorySnapshotMaxBytes": 654321,
"allowUpload": true, "allowClipboard": true, "allowStateExport": true,
"uploadMaxRequestBytes": 1000, "uploadMaxFiles": 4, "uploadMaxFileBytes": 500, "uploadMaxTotalBytes": 900,
"maxRedirects": 9, "trustedProxyCIDRs": ["10.0.0.0/8"], "trustedResolveCIDRs": ["192.168.0.0/16"],
diff --git a/internal/config/testdata/file_config_from_runtime.golden.json b/internal/config/testdata/file_config_from_runtime.golden.json
index 0985275b..70570d98 100644
--- a/internal/config/testdata/file_config_from_runtime.golden.json
+++ b/internal/config/testdata/file_config_from_runtime.golden.json
@@ -78,12 +78,14 @@
"allowDownload": true,
"allowCookies": true,
"allowNetworkIntercept": true,
+ "allowMemory": true,
"allowFileScheme": true,
"allowedDomains": null,
"downloadAllowedDomains": [
"dl.example"
],
"downloadMaxBytes": 123456,
+ "memorySnapshotMaxBytes": 654321,
"allowUpload": true,
"allowClipboard": true,
"allowStateExport": true,
diff --git a/internal/config/transfer_limits.go b/internal/config/transfer_limits.go
index 8f6ef1f4..5e16dc25 100644
--- a/internal/config/transfer_limits.go
+++ b/internal/config/transfer_limits.go
@@ -1,17 +1,19 @@
package config
const (
- DefaultDownloadMaxBytes = 20 << 20
- MaxDownloadMaxBytes = 100 << 20
- MaxRetainNetworkBodyMaxBytes = 10 << 20
- DefaultUploadMaxRequestBytes = 10 << 20
- MaxUploadMaxRequestBytes = 100 << 20
- DefaultUploadMaxFiles = 8
- MaxUploadMaxFiles = 32
- DefaultUploadMaxFileBytes = 5 << 20
- MaxUploadMaxFileBytes = 25 << 20
- DefaultUploadMaxTotalBytes = 10 << 20
- MaxUploadMaxTotalBytes = 100 << 20
+ DefaultDownloadMaxBytes = 20 << 20
+ MaxDownloadMaxBytes = 100 << 20
+ MaxRetainNetworkBodyMaxBytes = 10 << 20
+ DefaultUploadMaxRequestBytes = 10 << 20
+ MaxUploadMaxRequestBytes = 100 << 20
+ DefaultUploadMaxFiles = 8
+ MaxUploadMaxFiles = 32
+ DefaultUploadMaxFileBytes = 5 << 20
+ MaxUploadMaxFileBytes = 25 << 20
+ DefaultUploadMaxTotalBytes = 10 << 20
+ MaxUploadMaxTotalBytes = 100 << 20
+ DefaultMemorySnapshotMaxBytes = 512 << 20
+ MaxMemorySnapshotMaxBytes = 4 << 30
)
func clampPositiveLimit(value, fallback, max int) int {
@@ -58,3 +60,10 @@ func (cfg *RuntimeConfig) EffectiveUploadMaxTotalBytes() int {
}
return clampPositiveLimit(cfg.UploadMaxTotalBytes, DefaultUploadMaxTotalBytes, MaxUploadMaxTotalBytes)
}
+
+func (cfg *RuntimeConfig) EffectiveMemorySnapshotMaxBytes() int {
+ if cfg == nil {
+ return DefaultMemorySnapshotMaxBytes
+ }
+ return clampPositiveLimit(cfg.MemorySnapshotMaxBytes, DefaultMemorySnapshotMaxBytes, MaxMemorySnapshotMaxBytes)
+}
diff --git a/internal/config/validate.go b/internal/config/validate.go
index 2688e05f..74e9b1f3 100644
--- a/internal/config/validate.go
+++ b/internal/config/validate.go
@@ -258,6 +258,7 @@ func ValidateFileConfig(fc *FileConfig) []error {
errs = append(errs, validateTrustedCIDRList("security.trustedProxyCIDRs", fc.Security.TrustedProxyCIDRs)...)
errs = append(errs, validateTrustedCIDRList("security.trustedResolveCIDRs", fc.Security.TrustedResolveCIDRs)...)
errs = append(errs, validatePositiveIntLimit("security.downloadMaxBytes", fc.Security.DownloadMaxBytes, MaxDownloadMaxBytes)...)
+ errs = append(errs, validatePositiveIntLimit("security.memorySnapshotMaxBytes", fc.Security.MemorySnapshotMaxBytes, MaxMemorySnapshotMaxBytes)...)
errs = append(errs, validatePositiveIntLimit("security.uploadMaxRequestBytes", fc.Security.UploadMaxRequestBytes, MaxUploadMaxRequestBytes)...)
errs = append(errs, validatePositiveIntLimit("security.uploadMaxFiles", fc.Security.UploadMaxFiles, MaxUploadMaxFiles)...)
errs = append(errs, validatePositiveIntLimit("security.uploadMaxFileBytes", fc.Security.UploadMaxFileBytes, MaxUploadMaxFileBytes)...)
diff --git a/internal/config/workflow/security.go b/internal/config/workflow/security.go
index b0b8758d..2b1d4c3a 100644
--- a/internal/config/workflow/security.go
+++ b/internal/config/workflow/security.go
@@ -180,21 +180,23 @@ type securityDefaultsState struct {
}
type securityConfigValues struct {
- AllowEvaluate bool
- AllowMacro bool
- AllowScreencast bool
- AllowDownload bool
- AllowCookies bool
- AllowNetworkIntercept bool
- DownloadMaxBytes int
- AllowUpload bool
- UploadMaxRequestBytes int
- UploadMaxFiles int
- UploadMaxFileBytes int
- UploadMaxTotalBytes int
- MaxRedirects int
- AttachEnabled bool
- IDPI config.IDPIConfig
+ AllowEvaluate bool
+ AllowMacro bool
+ AllowScreencast bool
+ AllowDownload bool
+ AllowCookies bool
+ AllowNetworkIntercept bool
+ AllowMemory bool
+ DownloadMaxBytes int
+ MemorySnapshotMaxBytes int
+ AllowUpload bool
+ UploadMaxRequestBytes int
+ UploadMaxFiles int
+ UploadMaxFileBytes int
+ UploadMaxTotalBytes int
+ MaxRedirects int
+ AttachEnabled bool
+ IDPI config.IDPIConfig
}
func securityDefaultsSnapshot(fc *config.FileConfig) securityDefaultsState {
@@ -226,9 +228,15 @@ func securityDefaultsSnapshot(fc *config.FileConfig) securityDefaultsState {
if fc.Security.AllowNetworkIntercept != nil {
s.Security.AllowNetworkIntercept = *fc.Security.AllowNetworkIntercept
}
+ if fc.Security.AllowMemory != nil {
+ s.Security.AllowMemory = *fc.Security.AllowMemory
+ }
if fc.Security.DownloadMaxBytes != nil {
s.Security.DownloadMaxBytes = *fc.Security.DownloadMaxBytes
}
+ if fc.Security.MemorySnapshotMaxBytes != nil {
+ s.Security.MemorySnapshotMaxBytes = *fc.Security.MemorySnapshotMaxBytes
+ }
if fc.Security.AllowUpload != nil {
s.Security.AllowUpload = *fc.Security.AllowUpload
}
diff --git a/internal/dashboard/config_health.go b/internal/dashboard/config_health.go
index 346cc7d2..f071cd4a 100644
--- a/internal/dashboard/config_health.go
+++ b/internal/dashboard/config_health.go
@@ -181,6 +181,7 @@ func isGuardsDownPosture(cfg *config.RuntimeConfig) bool {
cfg.AllowCookies &&
cfg.AllowUpload &&
cfg.AllowNetworkIntercept &&
+ cfg.AllowMemory &&
cfg.AttachEnabled &&
!cfg.IDPI.Enabled
}
diff --git a/internal/fileout/autonaming_census_test.go b/internal/fileout/autonaming_census_test.go
index 881dda89..f476ef33 100644
--- a/internal/fileout/autonaming_census_test.go
+++ b/internal/fileout/autonaming_census_test.go
@@ -48,6 +48,7 @@ var autoNamingSites = map[string]string{
"internal/handlers/binary_export.go": "exportTimestamp only builds the base name; fileout.WriteUnique reserves the path and writes it",
"internal/handlers/record_handlers.go": "the recording base name is reserved by " +
"fileout.ReserveUnique before it is returned",
+ "internal/handlers/memory.go": "the heap snapshot path is reserved by fileout.ReserveUnique before the stream writes it",
"internal/cli/actions/actions_capture.go": "writeOutputFile with autoNamed",
"internal/cli/actions/actions_pdf.go": "writeOutputFile with autoNamed",
"internal/cli/actions/actions_screenshot.go": "writeOutputFile with autoNamed",
diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.go
index 4917d22f..e674342a 100644
--- a/internal/handlers/handlers.go
+++ b/internal/handlers/handlers.go
@@ -376,6 +376,9 @@ func (h *Handlers) bridgeBindings() []routeBinding {
{pattern: "DELETE /cookies", root: h.HandleClearCookies, tab: h.HandleTabClearCookies, guards: guardNone},
{pattern: "GET /metrics", root: h.HandleMetrics, tab: h.HandleTabMetrics, guards: guardNone},
{pattern: "GET /timing", root: h.HandleTiming, tab: h.HandleTabTiming, guards: guardDialogBlocked | guardDomainPolicy},
+ {pattern: "GET /memory", root: h.HandleMemory, tab: h.HandleTabMemory, guards: guardDialogBlocked | guardDomainPolicy},
+ {pattern: "POST /memory/snapshot", root: h.HandleMemorySnapshot, tab: h.HandleTabMemorySnapshot, guards: guardDialogBlocked | guardDomainPolicy},
+ {pattern: "GET /memory/snapshot/{snapshotId}/summary", root: h.HandleMemorySnapshotSummary, guards: guardNone},
{pattern: "GET /a11y/audit", root: h.HandleA11yAudit, tab: h.HandleTabA11yAudit, guards: guardDialogBlocked | guardDomainPolicy},
{pattern: "POST /audit/page", root: h.HandleAuditPage, guards: guardNone},
{pattern: "POST /audit", root: h.HandleAudit, guards: guardNone},
diff --git a/internal/handlers/handlers_routes_test.go b/internal/handlers/handlers_routes_test.go
index 3477405c..6f4d0b38 100644
--- a/internal/handlers/handlers_routes_test.go
+++ b/internal/handlers/handlers_routes_test.go
@@ -321,6 +321,7 @@ func TestEveryCapabilityGatedRouteRefusesOnTheBridgeFrontWhenDisabled(t *testing
// is not a failure.
func TestNoCapabilityGatedRouteRefusesWhenTheCapabilityIsEnabled(t *testing.T) {
enabled := &config.RuntimeConfig{
+ StateDir: t.TempDir(),
AllowEvaluate: true,
AllowMacro: true,
AllowScreencast: true,
@@ -329,6 +330,7 @@ func TestNoCapabilityGatedRouteRefusesWhenTheCapabilityIsEnabled(t *testing.T) {
AllowNetworkIntercept: true,
AllowUpload: true,
AllowStateExport: true,
+ AllowMemory: true,
}
for _, ep := range gatedCatalogRoutes(t) {
diff --git a/internal/handlers/memory.go b/internal/handlers/memory.go
new file mode 100644
index 00000000..129fc8df
--- /dev/null
+++ b/internal/handlers/memory.go
@@ -0,0 +1,234 @@
+package handlers
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/http"
+ "os"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/bridge/observe"
+ "github.com/pinchtab/pinchtab/internal/fileout"
+ "github.com/pinchtab/pinchtab/internal/heapsnap"
+ "github.com/pinchtab/pinchtab/internal/httpx"
+ "github.com/pinchtab/pinchtab/internal/routes"
+)
+
+const (
+ memorySnapshotTimeout = 2 * time.Minute
+ memorySnapshotTooLargeCode = "memory_snapshot_too_large"
+ memorySnapshotNotFoundCode = "memory_snapshot_not_found"
+ memorySnapshotInvalidCode = "memory_snapshot_invalid"
+ memorySnapshotMaxSetting = "security.memorySnapshotMaxBytes"
+)
+
+type memoryUsageResponse struct {
+ TabID string `json:"tabId"`
+ *observe.HeapUsage
+}
+
+type memorySnapshotResponse struct {
+ ID string `json:"id"`
+ Path string `json:"path"`
+ Bytes int64 `json:"bytes"`
+ NodeCount int `json:"nodeCount"`
+ DurationMs int64 `json:"durationMs"`
+ TabID string `json:"tabId"`
+}
+
+type memorySummaryResponse struct {
+ ID string `json:"id"`
+ Path string `json:"path"`
+ Top int `json:"top"`
+ heapsnap.Summary
+}
+
+func (h *Handlers) memorySnapshotDir() string {
+ return heapsnap.Dir(h.Config.StateDir)
+}
+
+func (h *Handlers) HandleMemory(w http.ResponseWriter, r *http.Request) {
+ q := r.URL.Query()
+ tabID := q.Get("tabId")
+ gc := false
+ if raw := strings.TrimSpace(q.Get("gc")); raw != "" {
+ parsed, err := strconv.ParseBool(raw)
+ if err != nil {
+ httpx.ErrorCode(w, 400, "bad_gc", fmt.Sprintf("gc must be true or false, got %q", raw), false, nil)
+ return
+ }
+ gc = parsed
+ }
+
+ if !h.ensureBrowserOrRespond(w, h.Config) {
+ return
+ }
+ h.recordReadRequest(r, "memory", tabID)
+
+ resolvedTabID, tCtx, cancel, ok := h.resolveReadContext(w, r, tabID, h.Config.ActionTimeout)
+ if !ok {
+ return
+ }
+ defer h.armIdleLifecycle(resolvedTabID)
+ defer cancel()
+
+ usage, err := observe.ReadHeapUsage(tCtx, gc)
+ if err != nil {
+ httpx.Error(w, 500, fmt.Errorf("read heap usage: %w", err))
+ return
+ }
+ httpx.JSON(w, 200, memoryUsageResponse{TabID: resolvedTabID, HeapUsage: usage})
+}
+
+func (h *Handlers) HandleTabMemory(w http.ResponseWriter, r *http.Request) {
+ h.withPathTabID(w, r, h.HandleMemory)
+}
+
+func (h *Handlers) HandleMemorySnapshot(w http.ResponseWriter, r *http.Request) {
+ if !h.memoryEnabled() {
+ h.writeCapabilityDisabled(w, routes.CapMemory)
+ return
+ }
+
+ var req struct {
+ TabID string `json:"tabId"`
+ }
+ if err := httpx.DecodeOptionalJSONBody(w, r, 0, &req); err != nil {
+ httpx.Error(w, httpx.StatusForJSONDecodeError(err), err)
+ return
+ }
+
+ if !h.ensureBrowserOrRespond(w, h.Config) {
+ return
+ }
+ h.recordReadRequest(r, "memory-snapshot", req.TabID)
+
+ resolvedTabID, tCtx, cancel, ok := h.resolveReadContext(w, r, req.TabID, memorySnapshotTimeout)
+ if !ok {
+ return
+ }
+ defer h.armIdleLifecycle(resolvedTabID)
+ defer cancel()
+
+ dir := h.memorySnapshotDir()
+ if err := os.MkdirAll(dir, 0700); err != nil {
+ httpx.Error(w, 500, fmt.Errorf("create heap snapshot dir: %w", err))
+ return
+ }
+ path, err := fileout.ReserveUnique(dir, heapsnap.IDPrefix+time.Now().Format("20060102_150405"), heapsnap.Ext)
+ if err != nil {
+ httpx.Error(w, 500, fmt.Errorf("reserve heap snapshot path: %w", err))
+ return
+ }
+ kept := false
+ defer func() {
+ if !kept {
+ _ = os.Remove(path)
+ }
+ }()
+
+ maxBytes := h.Config.EffectiveMemorySnapshotMaxBytes()
+ start := time.Now()
+ written, err := streamHeapSnapshot(tCtx, path, int64(maxBytes))
+ if err != nil {
+ if errors.Is(err, heapsnap.ErrTooLarge) {
+ httpx.ErrorCode(w, http.StatusRequestEntityTooLarge, memorySnapshotTooLargeCode,
+ fmt.Sprintf("heap snapshot exceeded %d bytes and was discarded; raise %s to allow larger snapshots", maxBytes, memorySnapshotMaxSetting),
+ false, map[string]any{"maxBytes": maxBytes})
+ return
+ }
+ httpx.Error(w, 500, fmt.Errorf("take heap snapshot: %w", err))
+ return
+ }
+ duration := time.Since(start)
+
+ header, err := readSnapshotHeader(path)
+ if err != nil {
+ httpx.ErrorCode(w, 500, memorySnapshotInvalidCode, err.Error(), false, nil)
+ return
+ }
+
+ kept = true
+ httpx.JSON(w, 200, memorySnapshotResponse{
+ ID: heapsnap.IDFromPath(path),
+ Path: path,
+ Bytes: written,
+ NodeCount: header.NodeCount,
+ DurationMs: duration.Milliseconds(),
+ TabID: resolvedTabID,
+ })
+}
+
+func (h *Handlers) HandleTabMemorySnapshot(w http.ResponseWriter, r *http.Request) {
+ h.withPathTabIDBody(w, r, h.HandleMemorySnapshot)
+}
+
+func streamHeapSnapshot(ctx context.Context, path string, maxBytes int64) (int64, error) {
+ f, err := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC, 0600)
+ if err != nil {
+ return 0, fmt.Errorf("open heap snapshot: %w", err)
+ }
+ sink := heapsnap.NewSink(f, maxBytes)
+ err = observe.TakeHeapSnapshot(ctx, sink.WriteChunk)
+ if closeErr := f.Close(); err == nil && closeErr != nil {
+ err = fmt.Errorf("close heap snapshot: %w", closeErr)
+ }
+ return sink.Bytes(), err
+}
+
+func readSnapshotHeader(path string) (*heapsnap.Header, error) {
+ f, err := os.Open(path)
+ if err != nil {
+ return nil, fmt.Errorf("open heap snapshot: %w", err)
+ }
+ defer func() { _ = f.Close() }()
+ return heapsnap.ReadHeader(f)
+}
+
+func (h *Handlers) HandleMemorySnapshotSummary(w http.ResponseWriter, r *http.Request) {
+ if !h.memoryEnabled() {
+ h.writeCapabilityDisabled(w, routes.CapMemory)
+ return
+ }
+
+ id := strings.TrimSpace(r.PathValue("snapshotId"))
+ path, err := heapsnap.PathForID(h.memorySnapshotDir(), id)
+ if err != nil {
+ httpx.ErrorCode(w, 400, "bad_snapshot_id", err.Error(), false, nil)
+ return
+ }
+
+ top := heapsnap.DefaultTop
+ if raw := strings.TrimSpace(r.URL.Query().Get("top")); raw != "" {
+ n, err := strconv.Atoi(raw)
+ if err != nil || n <= 0 {
+ httpx.ErrorCode(w, 400, "bad_top", fmt.Sprintf("top must be a positive integer, got %q", raw), false, nil)
+ return
+ }
+ top = heapsnap.ClampTop(n)
+ }
+
+ if _, err := os.Stat(path); err != nil {
+ if errors.Is(err, os.ErrNotExist) {
+ httpx.ErrorCode(w, 404, memorySnapshotNotFoundCode, fmt.Sprintf("no heap snapshot with id %q", id), false, nil)
+ return
+ }
+ httpx.Error(w, 500, fmt.Errorf("stat heap snapshot: %w", err))
+ return
+ }
+
+ summary, err := heapsnap.SummarizeFile(path, top)
+ if err != nil {
+ var parseErr *heapsnap.ParseError
+ if errors.As(err, &parseErr) {
+ httpx.ErrorCode(w, 422, memorySnapshotInvalidCode, err.Error(), false, map[string]any{"section": parseErr.Section})
+ return
+ }
+ httpx.Error(w, 500, fmt.Errorf("summarize heap snapshot: %w", err))
+ return
+ }
+ httpx.JSON(w, 200, memorySummaryResponse{ID: id, Path: path, Top: top, Summary: summary})
+}
diff --git a/internal/handlers/memory_test.go b/internal/handlers/memory_test.go
new file mode 100644
index 00000000..1a829d96
--- /dev/null
+++ b/internal/handlers/memory_test.go
@@ -0,0 +1,254 @@
+package handlers
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/heapsnap"
+ "github.com/pinchtab/pinchtab/internal/testbrowser"
+)
+
+func memoryHandlers(t *testing.T, allow bool) (*Handlers, string) {
+ t.Helper()
+ stateDir := t.TempDir()
+ cfg := &config.RuntimeConfig{StateDir: stateDir, AllowMemory: allow, ActionTimeout: time.Second}
+ return New(&mockBridge{}, cfg, nil, nil, nil), stateDir
+}
+
+func seedSnapshot(t *testing.T, stateDir, id, body string) {
+ t.Helper()
+ dir := heapsnap.Dir(stateDir)
+ if err := os.MkdirAll(dir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, id+heapsnap.Ext), []byte(body), 0o600); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func committedFixture(t *testing.T) string {
+ t.Helper()
+ raw, err := os.ReadFile(filepath.Join("..", "heapsnap", "testdata", "small.heapsnapshot"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(raw)
+}
+
+func summaryRequest(h *Handlers, id, query string) *httptest.ResponseRecorder {
+ req := httptest.NewRequest(http.MethodGet, "/memory/snapshot/"+id+"/summary"+query, nil)
+ req.SetPathValue("snapshotId", id)
+ w := httptest.NewRecorder()
+ h.HandleMemorySnapshotSummary(w, req)
+ return w
+}
+
+func errorCode(t *testing.T, w *httptest.ResponseRecorder) string {
+ t.Helper()
+ var body struct {
+ Code string `json:"code"`
+ }
+ _ = json.Unmarshal(w.Body.Bytes(), &body)
+ return body.Code
+}
+
+func TestMemoryCapabilityGatesSnapshotAndSummaryButNotUsage(t *testing.T) {
+ h, stateDir := memoryHandlers(t, false)
+ seedSnapshot(t, stateDir, "heap_seeded", committedFixture(t))
+
+ w := httptest.NewRecorder()
+ h.HandleMemorySnapshot(w, httptest.NewRequest(http.MethodPost, "/memory/snapshot", nil))
+ if w.Code != http.StatusForbidden || errorCode(t, w) != "memory_disabled" {
+ t.Fatalf("snapshot with allowMemory off = %d %s, want 403 memory_disabled", w.Code, w.Body.String())
+ }
+
+ w = summaryRequest(h, "heap_seeded", "")
+ if w.Code != http.StatusForbidden || errorCode(t, w) != "memory_disabled" {
+ t.Fatalf("summary with allowMemory off = %d %s, want 403 memory_disabled", w.Code, w.Body.String())
+ }
+
+ w = httptest.NewRecorder()
+ h.HandleMemory(w, httptest.NewRequest(http.MethodGet, "/memory", nil))
+ if errorCode(t, w) == "memory_disabled" {
+ t.Fatalf("GET /memory refused with the capability code: %s", w.Body.String())
+ }
+}
+
+func TestMemoryUsageRefusesAMalformedGC(t *testing.T) {
+ h, _ := memoryHandlers(t, false)
+ w := httptest.NewRecorder()
+ h.HandleMemory(w, httptest.NewRequest(http.MethodGet, "/memory?gc=maybe", nil))
+ if w.Code != http.StatusBadRequest || errorCode(t, w) != "bad_gc" {
+ t.Fatalf("gc=maybe = %d %s, want 400 bad_gc", w.Code, w.Body.String())
+ }
+}
+
+func TestMemorySummaryReadsASavedSnapshot(t *testing.T) {
+ h, stateDir := memoryHandlers(t, true)
+ seedSnapshot(t, stateDir, "heap_seeded", committedFixture(t))
+
+ w := summaryRequest(h, "heap_seeded", "?top=2")
+ if w.Code != http.StatusOK {
+ t.Fatalf("summary = %d %s", w.Code, w.Body.String())
+ }
+ var got memorySummaryResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
+ t.Fatal(err)
+ }
+ if got.ID != "heap_seeded" || got.Top != 2 || got.NodeCount != 20 || got.EdgeCount != 6 {
+ t.Fatalf("summary header = %+v", got)
+ }
+ if len(got.TopBySize) != 2 || got.TopBySize[0].Name != "Array" || len(got.DuplicateStrings) != 2 || got.DuplicateStrings[0].Value != "secret-token-abc" {
+ t.Fatalf("summary tables = %+v / %+v", got.TopBySize, got.DuplicateStrings)
+ }
+}
+
+func TestMemorySummaryRefusals(t *testing.T) {
+ h, stateDir := memoryHandlers(t, true)
+ seedSnapshot(t, stateDir, "heap_broken", strings.Replace(committedFixture(t), `"node_count":20`, `"node_count":3`, 1))
+
+ cases := []struct {
+ id, query string
+ status int
+ code string
+ }{
+ {"..", "", http.StatusBadRequest, "bad_snapshot_id"},
+ {"heap_missing", "", http.StatusNotFound, "memory_snapshot_not_found"},
+ {"heap_broken", "?top=0", http.StatusBadRequest, "bad_top"},
+ {"heap_broken", "", http.StatusUnprocessableEntity, "memory_snapshot_invalid"},
+ }
+ for _, tc := range cases {
+ w := summaryRequest(h, tc.id, tc.query)
+ if w.Code != tc.status || errorCode(t, w) != tc.code {
+ t.Errorf("%s%s = %d %s, want %d %s", tc.id, tc.query, w.Code, w.Body.String(), tc.status, tc.code)
+ }
+ }
+ w := summaryRequest(h, "heap_broken", "")
+ if !strings.Contains(w.Body.String(), `"section":"nodes"`) {
+ t.Errorf("malformed snapshot refusal does not name the section: %s", w.Body.String())
+ }
+}
+
+func TestAFailedMemorySnapshotLeavesNoFile(t *testing.T) {
+ h, stateDir := memoryHandlers(t, true)
+ w := httptest.NewRecorder()
+ h.HandleMemorySnapshot(w, httptest.NewRequest(http.MethodPost, "/memory/snapshot", strings.NewReader(`{"tabId":"tab1"}`)))
+ if w.Code != http.StatusInternalServerError {
+ t.Fatalf("snapshot on a tab with no CDP target = %d %s, want 500", w.Code, w.Body.String())
+ }
+ entries, err := os.ReadDir(heapsnap.Dir(stateDir))
+ if err != nil {
+ t.Fatalf("the snapshot never reserved a path, so this proves nothing: %v", err)
+ }
+ if len(entries) != 0 {
+ t.Fatalf("a failed snapshot left %d file(s) behind", len(entries))
+ }
+}
+
+func browserMemoryHandlers(t *testing.T, cfg *config.RuntimeConfig) *Handlers {
+ t.Helper()
+ alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
+ chromedp.DefaultExecAllocatorOptions[:],
+ chromedp.ExecPath(testbrowser.Path(t)),
+ chromedp.UserDataDir(testbrowser.ProfileDir(t)),
+ chromedp.Flag("headless", true),
+ chromedp.Flag("no-sandbox", true),
+ )...)
+ ctx, cancelBrowser := chromedp.NewContext(alloc)
+ t.Cleanup(func() {
+ cancelBrowser()
+ cancelAlloc()
+ })
+ page := `<html><body><script>window.keep = Array.from({length: 40}, () => [1, 2, 3]);</script></body></html>`
+ if err := chromedp.Run(ctx, chromedp.Navigate("data:text/html,"+page)); err != nil {
+ t.Fatal(err)
+ }
+ cfg.ActionTimeout = 10 * time.Second
+ cfg.DefaultBrowser = config.BrowserChrome
+ cfg.StateDir = t.TempDir()
+ b := bridge.New(context.Background(), ctx, cfg)
+ b.RegisterTab("tab-mem", ctx)
+ return New(b, cfg, nil, nil, nil)
+}
+
+func TestMemorySnapshotWritesAFileTheSummaryReads(t *testing.T) {
+ h := browserMemoryHandlers(t, &config.RuntimeConfig{AllowMemory: true})
+
+ w := httptest.NewRecorder()
+ h.HandleMemory(w, httptest.NewRequest(http.MethodGet, "/memory?tabId=tab-mem&gc=true", nil))
+ if w.Code != http.StatusOK {
+ t.Fatalf("usage = %d %s", w.Code, w.Body.String())
+ }
+ var usage map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &usage); err != nil {
+ t.Fatal(err)
+ }
+ for _, key := range []string{"usedJSHeapSize", "totalJSHeapSize", "jsHeapSizeLimit", "documents", "nodes", "listeners", "frames"} {
+ if _, ok := usage[key]; !ok {
+ t.Errorf("usage lacks %s: %s", key, w.Body.String())
+ }
+ }
+
+ w = httptest.NewRecorder()
+ h.HandleMemorySnapshot(w, httptest.NewRequest(http.MethodPost, "/memory/snapshot", strings.NewReader(`{"tabId":"tab-mem"}`)))
+ if w.Code != http.StatusOK {
+ t.Fatalf("snapshot = %d %s", w.Code, w.Body.String())
+ }
+ var snap memorySnapshotResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &snap); err != nil {
+ t.Fatal(err)
+ }
+ info, err := os.Stat(snap.Path)
+ if err != nil || info.Size() != snap.Bytes || snap.NodeCount == 0 || !strings.HasPrefix(snap.ID, heapsnap.IDPrefix) {
+ t.Fatalf("snapshot response %+v vs file %v (%v)", snap, info, err)
+ }
+ if filepath.Dir(snap.Path) != heapsnap.Dir(h.Config.StateDir) {
+ t.Fatalf("snapshot landed in %s, want the server-controlled %s", filepath.Dir(snap.Path), heapsnap.Dir(h.Config.StateDir))
+ }
+
+ w = summaryRequest(h, snap.ID, "?top=50")
+ if w.Code != http.StatusOK {
+ t.Fatalf("summary = %d %s", w.Code, w.Body.String())
+ }
+ var summary memorySummaryResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &summary); err != nil {
+ t.Fatal(err)
+ }
+ if summary.NodeCount != snap.NodeCount {
+ t.Fatalf("summary counted %d nodes, snapshot reported %d", summary.NodeCount, snap.NodeCount)
+ }
+ found := false
+ for _, c := range summary.TopByCount {
+ found = found || c.Name == "Array"
+ }
+ if !found {
+ t.Fatalf("Array missing from the top constructors: %+v", summary.TopByCount)
+ }
+}
+
+func TestMemorySnapshotOverTheCapLeavesNoFile(t *testing.T) {
+ h := browserMemoryHandlers(t, &config.RuntimeConfig{AllowMemory: true, MemorySnapshotMaxBytes: 4096})
+
+ w := httptest.NewRecorder()
+ h.HandleMemorySnapshot(w, httptest.NewRequest(http.MethodPost, "/memory/snapshot", strings.NewReader(`{"tabId":"tab-mem"}`)))
+ if w.Code != http.StatusRequestEntityTooLarge || errorCode(t, w) != memorySnapshotTooLargeCode {
+ t.Fatalf("capped snapshot = %d %s, want 413 %s", w.Code, w.Body.String(), memorySnapshotTooLargeCode)
+ }
+ entries, err := os.ReadDir(heapsnap.Dir(h.Config.StateDir))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(entries) != 0 {
+ t.Fatalf("an aborted snapshot left %d file(s) behind", len(entries))
+ }
+}
diff --git a/internal/handlers/middleware_session_grants.go b/internal/handlers/middleware_session_grants.go
index de44274b..0fb0ba4c 100644
--- a/internal/handlers/middleware_session_grants.go
+++ b/internal/handlers/middleware_session_grants.go
@@ -188,6 +188,7 @@ func sessionBrowseGrantAllows(method, path string) bool {
path == "/snapshot",
path == "/screenshot",
path == "/text",
+ path == "/memory",
path == "/openapi.json",
path == "/help",
path == "/health",
@@ -196,7 +197,8 @@ func sessionBrowseGrantAllows(method, path string) bool {
case tabRouteHasSuffix(path, "/snapshot"),
tabRouteHasSuffix(path, "/screenshot"),
tabRouteHasSuffix(path, "/text"),
- tabRouteHasSuffix(path, "/metrics"):
+ tabRouteHasSuffix(path, "/metrics"),
+ tabRouteHasSuffix(path, "/memory"):
return true
}
case http.MethodPost:
diff --git a/internal/handlers/openapi.go b/internal/handlers/openapi.go
index 502c5ec8..84951187 100644
--- a/internal/handlers/openapi.go
+++ b/internal/handlers/openapi.go
@@ -152,6 +152,19 @@ func (h *Handlers) openAPIDocument(description string) map[string]any {
{"name": "frameId", "in": "query", "schema": map[string]string{"type": "string"}},
}
}
+ for _, p := range []string{"/memory", "/tabs/{id}/memory"} {
+ if op, ok := paths[p]["get"].(map[string]any); ok {
+ op["parameters"] = []map[string]any{
+ {"name": "gc", "in": "query", "description": "Run HeapProfiler.collectGarbage before reading", "schema": map[string]string{"type": "boolean"}},
+ }
+ }
+ }
+ if op, ok := paths["/memory/snapshot/{snapshotId}/summary"]["get"].(map[string]any); ok {
+ op["parameters"] = []map[string]any{
+ {"name": "snapshotId", "in": "path", "required": true, "description": "The id POST /memory/snapshot returned", "schema": map[string]string{"type": "string"}},
+ {"name": "top", "in": "query", "description": "Rows per table (default 20, max 200)", "schema": map[string]string{"type": "integer"}},
+ }
+ }
info := map[string]any{
"title": "Pinchtab API",
diff --git a/internal/handlers/security.go b/internal/handlers/security.go
index 3930a131..4b5882ee 100644
--- a/internal/handlers/security.go
+++ b/internal/handlers/security.go
@@ -60,6 +60,10 @@ func (h *Handlers) networkInterceptEnabled() bool {
return h != nil && h.Config != nil && h.Config.AllowNetworkIntercept
}
+func (h *Handlers) memoryEnabled() bool {
+ return h != nil && h.Config != nil && h.Config.AllowMemory
+}
+
func (h *Handlers) endpointSecurityStates() map[string]endpointSecurityState {
return map[string]endpointSecurityState{
"evaluate": capState(routes.CapEvaluate, h.evaluateEnabled(),
@@ -94,5 +98,7 @@ func (h *Handlers) endpointSecurityStates() map[string]endpointSecurityState {
"GET /network/route", "POST /network/route", "DELETE /network/route",
"GET /tabs/{id}/network/route", "POST /tabs/{id}/network/route", "DELETE /tabs/{id}/network/route",
}),
+ "memory": capState(routes.CapMemory, h.memoryEnabled(),
+ []string{"POST /memory/snapshot", "POST /tabs/{id}/memory/snapshot", "GET /memory/snapshot/{snapshotId}/summary"}),
}
}
diff --git a/internal/handlers/tab_guards_test.go b/internal/handlers/tab_guards_test.go
index 90716559..a707ff4e 100644
--- a/internal/handlers/tab_guards_test.go
+++ b/internal/handlers/tab_guards_test.go
@@ -153,6 +153,7 @@ func allCapabilities(t *testing.T, tmpDir string) *config.RuntimeConfig {
AllowNetworkIntercept: true,
AllowUpload: true,
AllowStateExport: true,
+ AllowMemory: true,
DownloadAllowedDomains: []string{"example.com"},
}
@@ -520,7 +521,7 @@ var mustDeclareDialogGuard = []string{
"POST /navigate", "POST /back", "POST /forward", "POST /reload",
"GET /snapshot", "GET /screenshot", "GET /annotate", "GET /capture", "GET /text", "GET /title", "GET /url", "GET /html", "GET /styles",
"GET /value", "GET /attr", "GET /count", "GET /box", "GET /visible", "GET /enabled", "GET /checked",
- "GET /pdf", "POST /pdf", "GET /timing", "GET /a11y/audit",
+ "GET /pdf", "POST /pdf", "GET /timing", "GET /a11y/audit", "GET /memory", "POST /memory/snapshot",
"POST /action", "POST /actions", "POST /macro", "POST /wait", "POST /find", "POST /extract", "POST /evaluate",
"POST /upload", "POST /solve", "POST /solve/{name}", "GET /download",
"POST /emulation/viewport", "POST /emulation/geolocation", "POST /emulation/offline",
@@ -543,54 +544,55 @@ var dialogGuardAllowReasons = map[string]bool{
}
var dialogGuardAllowList = map[string]string{
- "POST /dialog": "dialog",
- "GET /frame": "frame",
- "POST /frame": "frame",
- "POST /tab": "tabs",
- "POST /close": "tabs",
- "POST /lock": "tabs",
- "POST /unlock": "tabs",
- "POST /handoff": "handoff",
- "POST /resume": "handoff",
- "GET /handoff": "handoff",
- "POST /audit/page": "own-tab",
- "POST /audit": "own-tab",
- "POST /scrape": "own-tab",
- "GET /cookies": "browser-side",
- "POST /cookies": "browser-side",
- "DELETE /cookies": "browser-side",
- "GET /metrics": "browser-side",
- "GET /network/route": "browser-side",
- "POST /network/route": "browser-side",
- "DELETE /network/route": "browser-side",
- "POST /cache/clear": "browser-side",
- "GET /cache/status": "browser-side",
- "GET /stealth/status": "browser-side",
- "GET /solvers": "browser-side",
- "GET /config/autosolver": "browser-side",
- "GET /screencast/tabs": "browser-side",
- "GET /record/status": "browser-side",
- "GET /state/list": "browser-side",
- "GET /state/show": "browser-side",
- "DELETE /state": "browser-side",
- "POST /state/clean": "browser-side",
- "GET /network": "buffer",
- "GET /network/stream": "buffer",
- "GET /network/export": "buffer",
- "GET /network/export/stream": "buffer",
- "GET /network/{requestId}": "buffer",
- "POST /network/clear": "buffer",
- "GET /console": "buffer",
- "POST /console/clear": "buffer",
- "GET /errors": "buffer",
- "POST /errors/clear": "buffer",
- "GET /clipboard/read": "server-side",
- "POST /clipboard/write": "server-side",
- "POST /clipboard/copy": "server-side",
- "GET /clipboard/paste": "server-side",
- "GET /screencast": "screencast",
- "POST /record/start": "screencast",
- "POST /record/stop": "screencast",
+ "POST /dialog": "dialog",
+ "GET /frame": "frame",
+ "POST /frame": "frame",
+ "POST /tab": "tabs",
+ "POST /close": "tabs",
+ "POST /lock": "tabs",
+ "POST /unlock": "tabs",
+ "POST /handoff": "handoff",
+ "POST /resume": "handoff",
+ "GET /handoff": "handoff",
+ "POST /audit/page": "own-tab",
+ "POST /audit": "own-tab",
+ "POST /scrape": "own-tab",
+ "GET /cookies": "browser-side",
+ "POST /cookies": "browser-side",
+ "DELETE /cookies": "browser-side",
+ "GET /metrics": "browser-side",
+ "GET /memory/snapshot/{snapshotId}/summary": "server-side",
+ "GET /network/route": "browser-side",
+ "POST /network/route": "browser-side",
+ "DELETE /network/route": "browser-side",
+ "POST /cache/clear": "browser-side",
+ "GET /cache/status": "browser-side",
+ "GET /stealth/status": "browser-side",
+ "GET /solvers": "browser-side",
+ "GET /config/autosolver": "browser-side",
+ "GET /screencast/tabs": "browser-side",
+ "GET /record/status": "browser-side",
+ "GET /state/list": "browser-side",
+ "GET /state/show": "browser-side",
+ "DELETE /state": "browser-side",
+ "POST /state/clean": "browser-side",
+ "GET /network": "buffer",
+ "GET /network/stream": "buffer",
+ "GET /network/export": "buffer",
+ "GET /network/export/stream": "buffer",
+ "GET /network/{requestId}": "buffer",
+ "POST /network/clear": "buffer",
+ "GET /console": "buffer",
+ "POST /console/clear": "buffer",
+ "GET /errors": "buffer",
+ "POST /errors/clear": "buffer",
+ "GET /clipboard/read": "server-side",
+ "POST /clipboard/write": "server-side",
+ "POST /clipboard/copy": "server-side",
+ "GET /clipboard/paste": "server-side",
+ "GET /screencast": "screencast",
+ "POST /record/start": "screencast",
+ "POST /record/stop": "screencast",
}
func TestEveryBindingIsPlacedForTheDialogGuard(t *testing.T) {
diff --git a/internal/heapsnap/heapsnap_test.go b/internal/heapsnap/heapsnap_test.go
new file mode 100644
index 00000000..5cea3e91
--- /dev/null
+++ b/internal/heapsnap/heapsnap_test.go
@@ -0,0 +1,201 @@
+package heapsnap
+
+import (
+ "bytes"
+ "errors"
+ "os"
+ "path/filepath"
+ "reflect"
+ "runtime"
+ "strings"
+ "testing"
+)
+
+const fixturePath = "testdata/small.heapsnapshot"
+
+func readFixture(t *testing.T) string {
+ t.Helper()
+ raw, err := os.ReadFile(fixturePath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(raw)
+}
+
+func TestSummaryOverTheFixtureIsDeterministic(t *testing.T) {
+ want := Summary{
+ NodeCount: 20,
+ EdgeCount: 6,
+ TotalSelfSize: 3536,
+ Constructors: 10,
+ TopBySize: []Constructor{
+ {Name: "Array", Count: 3, SelfSize: 1664},
+ {Name: "(array)", Count: 1, SelfSize: 800},
+ {Name: "(compiled code)", Count: 1, SelfSize: 300},
+ {Name: "(string)", Count: 8, SelfSize: 228},
+ },
+ TopByCount: []Constructor{
+ {Name: "(string)", Count: 8, SelfSize: 228},
+ {Name: "Array", Count: 3, SelfSize: 1664},
+ {Name: "Object", Count: 2, SelfSize: 112},
+ {Name: "(array)", Count: 1, SelfSize: 800},
+ },
+ DuplicateStrings: []DuplicateString{
+ {Value: "secret-token-abc", Length: 16, Count: 3, SelfSize: 120},
+ {Value: `a string with "escapes" é`, Length: 25, Count: 2, SelfSize: 48},
+ {Value: "hello", Length: 5, Count: 2, SelfSize: 40},
+ },
+ }
+ for i := 0; i < 5; i++ {
+ got, err := SummarizeFile(fixturePath, 4)
+ if err != nil {
+ t.Fatalf("summarize: %v", err)
+ }
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("run %d summary =\n%+v\nwant\n%+v", i, got, want)
+ }
+ }
+}
+
+func TestAggregateCarriesEveryConstructorSortedByName(t *testing.T) {
+ agg, err := ParseFile(fixturePath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var names []string
+ for _, c := range agg.Constructors {
+ names = append(names, c.Name)
+ }
+ want := []string{"(array)", "(closure)", "(compiled code)", "(string)", "(synthetic)", "(system)", "Array", "HTMLDivElement", "Object", "Window"}
+ if !reflect.DeepEqual(names, want) {
+ t.Fatalf("constructors = %v, want %v", names, want)
+ }
+}
+
+func TestReadHeaderReturnsMetaAndCounts(t *testing.T) {
+ h, err := ReadHeader(strings.NewReader(readFixture(t)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if h.NodeCount != 20 || h.EdgeCount != 6 {
+ t.Fatalf("header counts = %d/%d, want 20/6", h.NodeCount, h.EdgeCount)
+ }
+ if len(h.Meta.NodeFields) != 7 || h.Meta.NodeFields[3] != "self_size" {
+ t.Fatalf("node_fields = %v", h.Meta.NodeFields)
+ }
+}
+
+func TestClampTop(t *testing.T) {
+ for in, want := range map[int]int{0: DefaultTop, -3: DefaultTop, 5: 5, MaxTop + 1: MaxTop} {
+ if got := ClampTop(in); got != want {
+ t.Errorf("ClampTop(%d) = %d, want %d", in, got, want)
+ }
+ }
+}
+
+func TestMalformedSnapshotsNameTheSection(t *testing.T) {
+ fixture := readFixture(t)
+ cases := []struct {
+ name string
+ input string
+ section string
+ }{
+ {"empty", "", SectionDocument},
+ {"not an object", "[1,2]", SectionDocument},
+ {"no meta", strings.Replace(fixture, `"meta":{`, `"other":{`, 1), SectionMeta},
+ {"meta lacks self_size", strings.Replace(fixture, `"self_size"`, `"size"`, 1), SectionMeta},
+ {"node count disagrees", strings.Replace(fixture, `"node_count":20`, `"node_count":21`, 1), SectionNodes},
+ {"edge count disagrees", strings.Replace(fixture, `"edge_count":6`, `"edge_count":5`, 1), SectionEdges},
+ {"truncated nodes", fixture[:strings.Index(fixture, `,2,5,17`)], SectionNodes},
+ {"non-integer node", strings.Replace(fixture, `,3,4,11,56`, `,3,4,11,"x"`, 1), SectionNodes},
+ {"node type outside enum", strings.Replace(fixture, `,3,4,11,56`, `,99,4,11,56`, 1), SectionNodes},
+ {"no strings", strings.Replace(fixture, `"strings":`, `"other":`, 1), SectionStrings},
+ {"unterminated string table", fixture[:strings.Index(fixture, `"hello"`)+3], SectionStrings},
+ {"name index past the table", strings.Replace(fixture, `,3,4,13,56`, `,3,400,13,56`, 1), SectionStrings},
+ {"nodes before snapshot", `{"nodes":[1],` + fixture[1:], SectionNodes},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ _, err := Parse(strings.NewReader(tc.input))
+ var pe *ParseError
+ if !errors.As(err, &pe) {
+ t.Fatalf("err = %v, want a *ParseError", err)
+ }
+ if pe.Section != tc.section {
+ t.Fatalf("section = %q (%v), want %q", pe.Section, err, tc.section)
+ }
+ if !strings.Contains(err.Error(), tc.section) {
+ t.Fatalf("message %q does not name section %q", err.Error(), tc.section)
+ }
+ })
+ }
+}
+
+func TestSinkStreamsTwentyMegabytesWithBoundedAllocation(t *testing.T) {
+ const chunkSize = 256 << 10
+ const total = 20 << 20
+ chunk := strings.Repeat("7", chunkSize)
+ f, err := os.Create(filepath.Join(t.TempDir(), "stream"+Ext))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer func() { _ = f.Close() }()
+ sink := NewSink(f, 0)
+
+ runtime.GC()
+ var before, after runtime.MemStats
+ runtime.ReadMemStats(&before)
+ for written := 0; written < total; written += chunkSize {
+ if err := sink.WriteChunk(chunk); err != nil {
+ t.Fatal(err)
+ }
+ }
+ runtime.ReadMemStats(&after)
+
+ if sink.Bytes() != total {
+ t.Fatalf("sink wrote %d bytes, want %d", sink.Bytes(), total)
+ }
+ if grew := after.TotalAlloc - before.TotalAlloc; grew >= 2*chunkSize {
+ t.Fatalf("streaming %d bytes allocated %d, want under 2x the %d-byte chunk", total, grew, chunkSize)
+ }
+ info, err := f.Stat()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if info.Size() != total {
+ t.Fatalf("file holds %d bytes, want %d", info.Size(), total)
+ }
+}
+
+func TestSinkRefusesTheChunkThatCrossesTheCap(t *testing.T) {
+ var buf bytes.Buffer
+ sink := NewSink(&buf, 10)
+ if err := sink.WriteChunk("12345"); err != nil {
+ t.Fatal(err)
+ }
+ if err := sink.WriteChunk("123456"); !errors.Is(err, ErrTooLarge) {
+ t.Fatalf("err = %v, want ErrTooLarge", err)
+ }
+ if err := sink.WriteChunk("1"); !errors.Is(err, ErrTooLarge) {
+ t.Fatalf("a sink past its cap accepted more: %v", err)
+ }
+ if buf.String() != "12345" || sink.Bytes() != 5 {
+ t.Fatalf("sink wrote %q (%d), want only the chunk under the cap", buf.String(), sink.Bytes())
+ }
+}
+
+func TestPathForIDRefusesAnythingButAPlainName(t *testing.T) {
+ dir := t.TempDir()
+ got, err := PathForID(dir, "heap_20260913_101010-1")
+ if err != nil || got != filepath.Join(dir, "heap_20260913_101010-1"+Ext) {
+ t.Fatalf("PathForID = %q, %v", got, err)
+ }
+ if IDFromPath(got) != "heap_20260913_101010-1" {
+ t.Fatalf("IDFromPath(%q) = %q", got, IDFromPath(got))
+ }
+ for _, bad := range []string{"", "../etc/passwd", "a/b", ".hidden", "x.heapsnapshot", strings.Repeat("a", 200)} {
+ if _, err := PathForID(dir, bad); !errors.Is(err, ErrInvalidID) {
+ t.Errorf("PathForID(%q) err = %v, want ErrInvalidID", bad, err)
+ }
+ }
+}
diff --git a/internal/heapsnap/parse.go b/internal/heapsnap/parse.go
new file mode 100644
index 00000000..e4d66982
--- /dev/null
+++ b/internal/heapsnap/parse.go
@@ -0,0 +1,475 @@
+package heapsnap
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "sort"
+ "unicode/utf8"
+)
+
+const (
+ SectionDocument = "document"
+ SectionSnapshot = "snapshot"
+ SectionMeta = "snapshot.meta"
+ SectionNodes = "nodes"
+ SectionEdges = "edges"
+ SectionStrings = "strings"
+)
+
+var ErrMissingSection = errors.New("section missing")
+
+type ParseError struct {
+ Section string
+ Err error
+}
+
+func (e *ParseError) Error() string {
+ return fmt.Sprintf("heap snapshot %s: %v", e.Section, e.Err)
+}
+
+func (e *ParseError) Unwrap() error { return e.Err }
+
+func sectionError(section string, err error) error {
+ var pe *ParseError
+ if errors.As(err, &pe) {
+ return err
+ }
+ return &ParseError{Section: section, Err: err}
+}
+
+type Meta struct {
+ NodeFields []string `json:"node_fields"`
+ NodeTypes []json.RawMessage `json:"node_types"`
+ EdgeFields []string `json:"edge_fields"`
+ EdgeTypes []json.RawMessage `json:"edge_types"`
+}
+
+type Header struct {
+ Meta Meta `json:"meta"`
+ NodeCount int `json:"node_count"`
+ EdgeCount int `json:"edge_count"`
+}
+
+type nodeLayout struct {
+ fields int
+ typeAt int
+ nameAt int
+ sizeAt int
+ typeName []string
+}
+
+func (h *Header) layout() (nodeLayout, error) {
+ l := nodeLayout{fields: len(h.Meta.NodeFields), typeAt: -1, nameAt: -1, sizeAt: -1}
+ for i, f := range h.Meta.NodeFields {
+ switch f {
+ case "type":
+ l.typeAt = i
+ case "name":
+ l.nameAt = i
+ case "self_size":
+ l.sizeAt = i
+ }
+ }
+ if l.typeAt < 0 || l.nameAt < 0 || l.sizeAt < 0 {
+ return l, &ParseError{Section: SectionMeta, Err: fmt.Errorf("node_fields %v lack type, name or self_size", h.Meta.NodeFields)}
+ }
+ if len(h.Meta.NodeTypes) <= l.typeAt {
+ return l, &ParseError{Section: SectionMeta, Err: errors.New("node_types has no entry for the type field")}
+ }
+ if err := json.Unmarshal(h.Meta.NodeTypes[l.typeAt], &l.typeName); err != nil {
+ return l, &ParseError{Section: SectionMeta, Err: fmt.Errorf("node_types type enum: %w", err)}
+ }
+ if len(h.Meta.EdgeFields) == 0 {
+ return l, &ParseError{Section: SectionMeta, Err: errors.New("edge_fields is empty")}
+ }
+ return l, nil
+}
+
+func decodeHeader(raw []byte) (*Header, nodeLayout, error) {
+ var h struct {
+ Meta *Meta `json:"meta"`
+ NodeCount *int `json:"node_count"`
+ EdgeCount *int `json:"edge_count"`
+ }
+ if err := json.Unmarshal(raw, &h); err != nil {
+ return nil, nodeLayout{}, &ParseError{Section: SectionSnapshot, Err: err}
+ }
+ if h.Meta == nil {
+ return nil, nodeLayout{}, &ParseError{Section: SectionMeta, Err: ErrMissingSection}
+ }
+ if h.NodeCount == nil || h.EdgeCount == nil {
+ return nil, nodeLayout{}, &ParseError{Section: SectionSnapshot, Err: errors.New("node_count or edge_count missing")}
+ }
+ header := &Header{Meta: *h.Meta, NodeCount: *h.NodeCount, EdgeCount: *h.EdgeCount}
+ l, err := header.layout()
+ if err != nil {
+ return nil, l, err
+ }
+ return header, l, nil
+}
+
+func ReadHeader(r io.Reader) (*Header, error) {
+ s := newScanner(r)
+ if err := s.expect('{'); err != nil {
+ return nil, &ParseError{Section: SectionDocument, Err: err}
+ }
+ for {
+ c, err := s.peek()
+ if err != nil {
+ return nil, &ParseError{Section: SectionDocument, Err: err}
+ }
+ if c == '}' {
+ return nil, &ParseError{Section: SectionSnapshot, Err: ErrMissingSection}
+ }
+ key, err := s.readString(true)
+ if err != nil {
+ return nil, &ParseError{Section: SectionDocument, Err: err}
+ }
+ if err := s.expect(':'); err != nil {
+ return nil, &ParseError{Section: SectionDocument, Err: err}
+ }
+ if key == SectionSnapshot {
+ raw, err := s.captureValue()
+ if err != nil {
+ return nil, &ParseError{Section: SectionSnapshot, Err: err}
+ }
+ h, _, err := decodeHeader(raw)
+ return h, err
+ }
+ if err := s.skipValue(); err != nil {
+ return nil, &ParseError{Section: key, Err: err}
+ }
+ if c, err := s.next(); err != nil || c != ',' {
+ return nil, &ParseError{Section: SectionSnapshot, Err: ErrMissingSection}
+ }
+ }
+}
+
+type Constructor struct {
+ Name string `json:"name"`
+ Count int `json:"count"`
+ SelfSize int64 `json:"selfSize"`
+}
+
+type DuplicateString struct {
+ Value string `json:"value"`
+ Length int `json:"length"`
+ Count int `json:"count"`
+ SelfSize int64 `json:"selfSize"`
+}
+
+type Aggregate struct {
+ NodeCount int
+ EdgeCount int
+ TotalSelfSize int64
+ Constructors []Constructor
+ DuplicateStrings []DuplicateString
+}
+
+type bucket struct {
+ count int
+ size int64
+}
+
+type parser struct {
+ s *scanner
+ header *Header
+ layout nodeLayout
+ nodeValues int
+ edgeValues int
+ totalSize int64
+ byName map[int64]*bucket
+ byType map[string]*bucket
+ byString map[int64]*bucket
+ strings map[int64]string
+ seen map[string]bool
+}
+
+func Parse(r io.Reader) (*Aggregate, error) {
+ p := &parser{
+ s: newScanner(r),
+ byName: map[int64]*bucket{},
+ byType: map[string]*bucket{},
+ byString: map[int64]*bucket{},
+ strings: map[int64]string{},
+ seen: map[string]bool{},
+ }
+ if err := p.document(); err != nil {
+ return nil, err
+ }
+ return p.aggregate()
+}
+
+func ParseFile(path string) (*Aggregate, error) {
+ f, err := os.Open(path)
+ if err != nil {
+ return nil, fmt.Errorf("open heap snapshot: %w", err)
+ }
+ defer func() { _ = f.Close() }()
+ return Parse(f)
+}
+
+func (p *parser) document() error {
+ s := p.s
+ if err := s.expect('{'); err != nil {
+ return &ParseError{Section: SectionDocument, Err: err}
+ }
+ c, err := s.peek()
+ if err != nil {
+ return &ParseError{Section: SectionDocument, Err: err}
+ }
+ for c != '}' {
+ key, err := s.readString(true)
+ if err != nil {
+ return &ParseError{Section: SectionDocument, Err: err}
+ }
+ if err := s.expect(':'); err != nil {
+ return &ParseError{Section: SectionDocument, Err: err}
+ }
+ if err := p.section(key); err != nil {
+ return err
+ }
+ p.seen[key] = true
+ if c, err = s.next(); err != nil {
+ return &ParseError{Section: SectionDocument, Err: err}
+ }
+ if c != ',' && c != '}' {
+ return &ParseError{Section: SectionDocument, Err: fmt.Errorf("after %s: want ',' or '}', got %q", key, c)}
+ }
+ }
+ for _, name := range []string{SectionSnapshot, SectionNodes, SectionEdges, SectionStrings} {
+ if !p.seen[name] {
+ return &ParseError{Section: name, Err: ErrMissingSection}
+ }
+ }
+ return nil
+}
+
+func (p *parser) section(key string) error {
+ switch key {
+ case SectionSnapshot:
+ raw, err := p.s.captureValue()
+ if err != nil {
+ return &ParseError{Section: SectionSnapshot, Err: err}
+ }
+ p.header, p.layout, err = decodeHeader(raw)
+ return err
+ case SectionNodes:
+ return p.nodes()
+ case SectionEdges:
+ return p.edges()
+ case SectionStrings:
+ return p.stringTable()
+ default:
+ if err := p.s.skipValue(); err != nil {
+ return &ParseError{Section: key, Err: err}
+ }
+ return nil
+ }
+}
+
+func (p *parser) nodes() error {
+ if p.header == nil {
+ return &ParseError{Section: SectionNodes, Err: errors.New("appears before snapshot.meta")}
+ }
+ l := p.layout
+ var typ, name, size int64
+ field := 0
+ count, err := p.s.intArray(func(v int64) error {
+ switch field {
+ case l.typeAt:
+ typ = v
+ case l.nameAt:
+ name = v
+ case l.sizeAt:
+ size = v
+ }
+ field++
+ if field < l.fields {
+ return nil
+ }
+ field = 0
+ return p.node(typ, name, size)
+ })
+ if err != nil {
+ return sectionError(SectionNodes, err)
+ }
+ if count%l.fields != 0 {
+ return &ParseError{Section: SectionNodes, Err: fmt.Errorf("%d values is not a multiple of %d node fields", count, l.fields)}
+ }
+ p.nodeValues = count
+ if nodes := count / l.fields; nodes != p.header.NodeCount {
+ return &ParseError{Section: SectionNodes, Err: fmt.Errorf("holds %d nodes, snapshot.node_count says %d", nodes, p.header.NodeCount)}
+ }
+ return nil
+}
+
+func (p *parser) node(typ, name, size int64) error {
+ if typ < 0 || int(typ) >= len(p.layout.typeName) {
+ return &ParseError{Section: SectionNodes, Err: fmt.Errorf("node type %d outside node_types", typ)}
+ }
+ p.totalSize += size
+ kind := p.layout.typeName[typ]
+ switch kind {
+ case "object", "native":
+ add(p.byName, name, size)
+ default:
+ b := p.byType[kind]
+ if b == nil {
+ b = &bucket{}
+ p.byType[kind] = b
+ }
+ b.count++
+ b.size += size
+ }
+ if kind == "string" {
+ add(p.byString, name, size)
+ }
+ return nil
+}
+
+func add(m map[int64]*bucket, key, size int64) {
+ b := m[key]
+ if b == nil {
+ b = &bucket{}
+ m[key] = b
+ }
+ b.count++
+ b.size += size
+}
+
+func (p *parser) edges() error {
+ if p.header == nil {
+ return &ParseError{Section: SectionEdges, Err: errors.New("appears before snapshot.meta")}
+ }
+ count, err := p.s.intArray(func(int64) error { return nil })
+ if err != nil {
+ return sectionError(SectionEdges, err)
+ }
+ fields := len(p.header.Meta.EdgeFields)
+ if count%fields != 0 {
+ return &ParseError{Section: SectionEdges, Err: fmt.Errorf("%d values is not a multiple of %d edge fields", count, fields)}
+ }
+ p.edgeValues = count
+ if edges := count / fields; edges != p.header.EdgeCount {
+ return &ParseError{Section: SectionEdges, Err: fmt.Errorf("holds %d edges, snapshot.edge_count says %d", edges, p.header.EdgeCount)}
+ }
+ return nil
+}
+
+func (p *parser) stringTable() error {
+ keepAll := !p.seen[SectionNodes]
+ _, err := p.s.stringArray(func(i int) bool {
+ if keepAll {
+ return true
+ }
+ key := int64(i)
+ if _, ok := p.byName[key]; ok {
+ return true
+ }
+ b, ok := p.byString[key]
+ return ok && b.count > 1
+ }, func(i int, v string) {
+ p.strings[int64(i)] = v
+ })
+ if err != nil {
+ return sectionError(SectionStrings, err)
+ }
+ return nil
+}
+
+func (p *parser) lookup(index int64) (string, error) {
+ v, ok := p.strings[index]
+ if !ok {
+ return "", &ParseError{Section: SectionStrings, Err: fmt.Errorf("name index %d has no entry", index)}
+ }
+ return v, nil
+}
+
+func className(kind string) string {
+ switch kind {
+ case "hidden":
+ return "(system)"
+ case "code":
+ return "(compiled code)"
+ default:
+ return "(" + kind + ")"
+ }
+}
+
+func (p *parser) aggregate() (*Aggregate, error) {
+ classes := map[string]*bucket{}
+ merge := func(name string, b *bucket) {
+ c := classes[name]
+ if c == nil {
+ c = &bucket{}
+ classes[name] = c
+ }
+ c.count += b.count
+ c.size += b.size
+ }
+ for index, b := range p.byName {
+ name, err := p.lookup(index)
+ if err != nil {
+ return nil, err
+ }
+ merge(name, b)
+ }
+ for kind, b := range p.byType {
+ merge(className(kind), b)
+ }
+
+ agg := &Aggregate{
+ NodeCount: p.nodeValues / p.layout.fields,
+ EdgeCount: p.edgeValues / len(p.header.Meta.EdgeFields),
+ TotalSelfSize: p.totalSize,
+ Constructors: make([]Constructor, 0, len(classes)),
+ }
+ for name, b := range classes {
+ agg.Constructors = append(agg.Constructors, Constructor{Name: name, Count: b.count, SelfSize: b.size})
+ }
+ sort.Slice(agg.Constructors, func(i, j int) bool { return agg.Constructors[i].Name < agg.Constructors[j].Name })
+
+ for index, b := range p.byString {
+ if b.count < 2 {
+ continue
+ }
+ value, err := p.lookup(index)
+ if err != nil {
+ return nil, err
+ }
+ agg.DuplicateStrings = append(agg.DuplicateStrings, DuplicateString{
+ Value: truncateValue(value),
+ Length: utf8.RuneCountInString(value),
+ Count: b.count,
+ SelfSize: b.size,
+ })
+ }
+ sort.Slice(agg.DuplicateStrings, func(i, j int) bool {
+ return lessDuplicate(agg.DuplicateStrings[i], agg.DuplicateStrings[j])
+ })
+ return agg, nil
+}
+
+const MaxValueRunes = 120
+
+func truncateValue(v string) string {
+ if utf8.RuneCountInString(v) <= MaxValueRunes {
+ return v
+ }
+ runes := []rune(v)
+ return string(runes[:MaxValueRunes]) + "…"
+}
+
+func lessDuplicate(a, b DuplicateString) bool {
+ if a.SelfSize != b.SelfSize {
+ return a.SelfSize > b.SelfSize
+ }
+ if a.Count != b.Count {
+ return a.Count > b.Count
+ }
+ return a.Value < b.Value
+}
diff --git a/internal/heapsnap/scanner.go b/internal/heapsnap/scanner.go
new file mode 100644
index 00000000..051d3f5f
--- /dev/null
+++ b/internal/heapsnap/scanner.go
@@ -0,0 +1,321 @@
+package heapsnap
+
+import (
+ "bufio"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+)
+
+const readBufferSize = 256 << 10
+
+type scanner struct {
+ r *bufio.Reader
+ offset int64
+ recording bool
+ record []byte
+ text []byte
+}
+
+func newScanner(r io.Reader) *scanner {
+ return &scanner{r: bufio.NewReaderSize(r, readBufferSize)}
+}
+
+func (s *scanner) readByte() (byte, error) {
+ c, err := s.r.ReadByte()
+ if err != nil {
+ if errors.Is(err, io.EOF) {
+ return 0, io.ErrUnexpectedEOF
+ }
+ return 0, err
+ }
+ s.offset++
+ if s.recording {
+ s.record = append(s.record, c)
+ }
+ return c, nil
+}
+
+func (s *scanner) unreadByte() {
+ _ = s.r.UnreadByte()
+ s.offset--
+ if s.recording && len(s.record) > 0 {
+ s.record = s.record[:len(s.record)-1]
+ }
+}
+
+func isSpace(c byte) bool {
+ return c == ' ' || c == '\n' || c == '\r' || c == '\t'
+}
+
+func (s *scanner) next() (byte, error) {
+ for {
+ c, err := s.readByte()
+ if err != nil {
+ return 0, err
+ }
+ if !isSpace(c) {
+ return c, nil
+ }
+ }
+}
+
+func (s *scanner) peek() (byte, error) {
+ c, err := s.next()
+ if err != nil {
+ return 0, err
+ }
+ s.unreadByte()
+ return c, nil
+}
+
+func (s *scanner) expect(want byte) error {
+ c, err := s.next()
+ if err != nil {
+ return err
+ }
+ if c != want {
+ return fmt.Errorf("offset %d: want %q, got %q", s.offset-1, want, c)
+ }
+ return nil
+}
+
+func (s *scanner) readString(keep bool) (string, error) {
+ if err := s.expect('"'); err != nil {
+ return "", err
+ }
+ s.text = s.text[:0]
+ escaped := false
+ for {
+ c, err := s.readByte()
+ if err != nil {
+ return "", err
+ }
+ if c == '"' {
+ break
+ }
+ if keep {
+ s.text = append(s.text, c)
+ }
+ if c == '\\' {
+ escaped = true
+ n, err := s.readByte()
+ if err != nil {
+ return "", err
+ }
+ if keep {
+ s.text = append(s.text, n)
+ }
+ }
+ }
+ if !keep {
+ return "", nil
+ }
+ if !escaped {
+ return string(s.text), nil
+ }
+ quoted := make([]byte, 0, len(s.text)+2)
+ quoted = append(quoted, '"')
+ quoted = append(quoted, s.text...)
+ quoted = append(quoted, '"')
+ var out string
+ if err := json.Unmarshal(quoted, &out); err != nil {
+ return "", fmt.Errorf("offset %d: decode string: %w", s.offset, err)
+ }
+ return out, nil
+}
+
+func (s *scanner) readInt() (int64, error) {
+ c, err := s.next()
+ if err != nil {
+ return 0, err
+ }
+ negative := false
+ if c == '-' {
+ negative = true
+ if c, err = s.readByte(); err != nil {
+ return 0, err
+ }
+ }
+ if c < '0' || c > '9' {
+ return 0, fmt.Errorf("offset %d: want an integer, got %q", s.offset-1, c)
+ }
+ var v int64
+ for {
+ v = v*10 + int64(c-'0')
+ c, err = s.readByte()
+ if err != nil {
+ return 0, err
+ }
+ if c < '0' || c > '9' {
+ s.unreadByte()
+ break
+ }
+ }
+ if negative {
+ v = -v
+ }
+ return v, nil
+}
+
+func (s *scanner) intArray(fn func(int64) error) (int, error) {
+ if err := s.expect('['); err != nil {
+ return 0, err
+ }
+ c, err := s.peek()
+ if err != nil {
+ return 0, err
+ }
+ if c == ']' {
+ _, _ = s.next()
+ return 0, nil
+ }
+ count := 0
+ for {
+ v, err := s.readInt()
+ if err != nil {
+ return count, err
+ }
+ if err := fn(v); err != nil {
+ return count, err
+ }
+ count++
+ c, err := s.next()
+ if err != nil {
+ return count, err
+ }
+ switch c {
+ case ',':
+ case ']':
+ return count, nil
+ default:
+ return count, fmt.Errorf("offset %d: want ',' or ']', got %q", s.offset-1, c)
+ }
+ }
+}
+
+func (s *scanner) stringArray(fn func(index int) (keep bool), got func(index int, value string)) (int, error) {
+ if err := s.expect('['); err != nil {
+ return 0, err
+ }
+ c, err := s.peek()
+ if err != nil {
+ return 0, err
+ }
+ if c == ']' {
+ _, _ = s.next()
+ return 0, nil
+ }
+ index := 0
+ for {
+ keep := fn(index)
+ v, err := s.readString(keep)
+ if err != nil {
+ return index, err
+ }
+ if keep {
+ got(index, v)
+ }
+ index++
+ c, err := s.next()
+ if err != nil {
+ return index, err
+ }
+ switch c {
+ case ',':
+ case ']':
+ return index, nil
+ default:
+ return index, fmt.Errorf("offset %d: want ',' or ']', got %q", s.offset-1, c)
+ }
+ }
+}
+
+func (s *scanner) skipValue() error {
+ c, err := s.peek()
+ if err != nil {
+ return err
+ }
+ switch c {
+ case '"':
+ _, err := s.readString(false)
+ return err
+ case '{':
+ return s.skipContainer('{', '}', true)
+ case '[':
+ return s.skipContainer('[', ']', false)
+ default:
+ return s.skipLiteral()
+ }
+}
+
+func (s *scanner) skipContainer(open, closing byte, object bool) error {
+ if err := s.expect(open); err != nil {
+ return err
+ }
+ c, err := s.peek()
+ if err != nil {
+ return err
+ }
+ if c == closing {
+ _, _ = s.next()
+ return nil
+ }
+ for {
+ if object {
+ if _, err := s.readString(false); err != nil {
+ return err
+ }
+ if err := s.expect(':'); err != nil {
+ return err
+ }
+ }
+ if err := s.skipValue(); err != nil {
+ return err
+ }
+ c, err := s.next()
+ if err != nil {
+ return err
+ }
+ if c == closing {
+ return nil
+ }
+ if c != ',' {
+ return fmt.Errorf("offset %d: want ',' or %q, got %q", s.offset-1, closing, c)
+ }
+ }
+}
+
+func (s *scanner) skipLiteral() error {
+ read := 0
+ for {
+ c, err := s.readByte()
+ if err != nil {
+ return err
+ }
+ if isSpace(c) || c == ',' || c == ']' || c == '}' {
+ s.unreadByte()
+ break
+ }
+ read++
+ }
+ if read == 0 {
+ return fmt.Errorf("offset %d: want a value", s.offset)
+ }
+ return nil
+}
+
+func (s *scanner) captureValue() ([]byte, error) {
+ if _, err := s.peek(); err != nil {
+ return nil, err
+ }
+ s.recording = true
+ s.record = s.record[:0]
+ err := s.skipValue()
+ s.recording = false
+ if err != nil {
+ return nil, err
+ }
+ return append([]byte(nil), s.record...), nil
+}
diff --git a/internal/heapsnap/sink.go b/internal/heapsnap/sink.go
new file mode 100644
index 00000000..15fe4518
--- /dev/null
+++ b/internal/heapsnap/sink.go
@@ -0,0 +1,40 @@
+package heapsnap
+
+import (
+ "errors"
+ "fmt"
+ "io"
+)
+
+var ErrTooLarge = errors.New("heap snapshot exceeds the size cap")
+
+type Sink struct {
+ w io.Writer
+ max int64
+ bytes int64
+ err error
+}
+
+func NewSink(w io.Writer, maxBytes int64) *Sink {
+ return &Sink{w: w, max: maxBytes}
+}
+
+func (s *Sink) WriteChunk(chunk string) error {
+ if s.err != nil {
+ return s.err
+ }
+ if s.max > 0 && s.bytes+int64(len(chunk)) > s.max {
+ s.err = fmt.Errorf("%w (%d bytes)", ErrTooLarge, s.max)
+ return s.err
+ }
+ n, err := io.WriteString(s.w, chunk)
+ s.bytes += int64(n)
+ if err != nil {
+ s.err = fmt.Errorf("write heap snapshot chunk: %w", err)
+ }
+ return s.err
+}
+
+func (s *Sink) Bytes() int64 { return s.bytes }
+
+func (s *Sink) Err() error { return s.err }
diff --git a/internal/heapsnap/store.go b/internal/heapsnap/store.go
new file mode 100644
index 00000000..6e4843bb
--- /dev/null
+++ b/internal/heapsnap/store.go
@@ -0,0 +1,34 @@
+package heapsnap
+
+import (
+ "errors"
+ "fmt"
+ "path/filepath"
+ "regexp"
+ "strings"
+)
+
+const (
+ Ext = ".heapsnapshot"
+ DirName = "heapsnapshots"
+ IDPrefix = "heap_"
+)
+
+var ErrInvalidID = errors.New("invalid heap snapshot id")
+
+var validID = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$`)
+
+func Dir(stateDir string) string {
+ return filepath.Join(stateDir, DirName)
+}
+
+func IDFromPath(path string) string {
+ return strings.TrimSuffix(filepath.Base(path), Ext)
+}
+
+func PathForID(dir, id string) (string, error) {
+ if !validID.MatchString(id) {
+ return "", fmt.Errorf("%w: %q", ErrInvalidID, id)
+ }
+ return filepath.Join(dir, id+Ext), nil
+}
diff --git a/internal/heapsnap/summary.go b/internal/heapsnap/summary.go
new file mode 100644
index 00000000..90ea6706
--- /dev/null
+++ b/internal/heapsnap/summary.go
@@ -0,0 +1,89 @@
+package heapsnap
+
+import (
+ "io"
+ "sort"
+)
+
+const (
+ DefaultTop = 20
+ MaxTop = 200
+)
+
+type Summary struct {
+ NodeCount int `json:"nodeCount"`
+ EdgeCount int `json:"edgeCount"`
+ TotalSelfSize int64 `json:"totalSelfSize"`
+ Constructors int `json:"constructors"`
+ TopBySize []Constructor `json:"topBySize"`
+ TopByCount []Constructor `json:"topByCount"`
+ DuplicateStrings []DuplicateString `json:"duplicateStrings"`
+}
+
+func ClampTop(top int) int {
+ if top <= 0 {
+ return DefaultTop
+ }
+ if top > MaxTop {
+ return MaxTop
+ }
+ return top
+}
+
+func (a *Aggregate) Summary(top int) Summary {
+ top = ClampTop(top)
+ bySize := append([]Constructor(nil), a.Constructors...)
+ sort.SliceStable(bySize, func(i, j int) bool {
+ x, y := bySize[i], bySize[j]
+ if x.SelfSize != y.SelfSize {
+ return x.SelfSize > y.SelfSize
+ }
+ if x.Count != y.Count {
+ return x.Count > y.Count
+ }
+ return x.Name < y.Name
+ })
+ byCount := append([]Constructor(nil), a.Constructors...)
+ sort.SliceStable(byCount, func(i, j int) bool {
+ x, y := byCount[i], byCount[j]
+ if x.Count != y.Count {
+ return x.Count > y.Count
+ }
+ if x.SelfSize != y.SelfSize {
+ return x.SelfSize > y.SelfSize
+ }
+ return x.Name < y.Name
+ })
+ return Summary{
+ NodeCount: a.NodeCount,
+ EdgeCount: a.EdgeCount,
+ TotalSelfSize: a.TotalSelfSize,
+ Constructors: len(a.Constructors),
+ TopBySize: head(bySize, top),
+ TopByCount: head(byCount, top),
+ DuplicateStrings: head(a.DuplicateStrings, top),
+ }
+}
+
+func head[T any](items []T, n int) []T {
+ if len(items) > n {
+ items = items[:n]
+ }
+ return append(make([]T, 0, len(items)), items...)
+}
+
+func Summarize(r io.Reader, top int) (Summary, error) {
+ agg, err := Parse(r)
+ if err != nil {
+ return Summary{}, err
+ }
+ return agg.Summary(top), nil
+}
+
+func SummarizeFile(path string, top int) (Summary, error) {
+ agg, err := ParseFile(path)
+ if err != nil {
+ return Summary{}, err
+ }
+ return agg.Summary(top), nil
+}
diff --git a/internal/heapsnap/testdata/small.heapsnapshot b/internal/heapsnap/testdata/small.heapsnapshot
new file mode 100644
index 00000000..4ec492d8
--- /dev/null
+++ b/internal/heapsnap/testdata/small.heapsnapshot
@@ -0,0 +1,44 @@
+{"snapshot":{"meta":{"node_fields":["type","name","id","self_size","edge_count","trace_node_id","detachedness"],"node_types":[["hidden","array","string","object","code","closure","regexp","number","native","synthetic","concatenated string","sliced string","symbol","bigint","object shape"],"string","number","number","number","number","number"],"edge_fields":["type","name_or_index","to_node"],"edge_types":[["context","element","property","internal","hidden","shortcut","weak"],"string_or_number","node"],"trace_function_info_fields":["function_id","name","script_name","script_id","line","column"],"trace_node_fields":["id","function_info_index","count","size","children"],"sample_fields":["timestamp_us","last_assigned_id"],"location_fields":["object_index","script_id","line","column"]},"node_count":20,"edge_count":6,"trace_function_count":0},
+"nodes":[9,1,1,0,3,0,0
+,3,2,3,120,2,0,0
+,3,3,5,32,1,0,0
+,3,3,7,32,0,0,0
+,3,3,9,1600,0,0,0
+,3,4,11,56,0,0,0
+,3,4,13,56,0,0,0
+,2,5,15,40,0,0,0
+,2,5,17,40,0,0,0
+,2,5,19,40,0,0,0
+,2,6,21,20,0,0,0
+,2,6,23,20,0,0,0
+,2,7,25,20,0,0,0
+,1,8,27,800,0,0,0
+,5,10,29,64,0,0,0
+,8,11,31,200,0,0,0
+,0,9,33,48,0,0,0
+,4,6,35,300,0,0,0
+,2,12,37,24,0,0,0
+,2,12,39,24,0,0,0],
+"edges":[1,0,7
+,2,8,14
+,2,7,28
+,2,8,35
+,2,8,49
+,1,0,56],
+"trace_function_infos":[],
+"trace_tree":[],
+"samples":[],
+"locations":[],
+"strings":["<dummy>",
+"(GC roots)",
+"Window",
+"Array",
+"Object",
+"secret-token-abc",
+"hello",
+"leak",
+"items",
+"system / Context",
+"onClick",
+"HTMLDivElement",
+"a string with \"escapes\" é"]}
diff --git a/internal/mcp/handlers.go b/internal/mcp/handlers.go
index 7d95ac94..51488b7b 100644
--- a/internal/mcp/handlers.go
+++ b/internal/mcp/handlers.go
@@ -23,16 +23,18 @@ func handlerMap(c *Client) map[string]func(context.Context, mcp.CallToolRequest)
func rawHandlerMap(c *Client) map[string]func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
return map[string]func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error){
- "pinchtab_navigate": handleNavigate(c),
- "pinchtab_back": handleHistoryNav(c, "back"),
- "pinchtab_forward": handleHistoryNav(c, "forward"),
- "pinchtab_reload": handleHistoryNav(c, "reload"),
- "pinchtab_snapshot": handleSnapshot(c),
- "pinchtab_frame": handleFrame(c),
- "pinchtab_screenshot": handleScreenshot(c),
- "pinchtab_capture": handleCapture(c),
- "pinchtab_get_text": handleGetText(c),
- "pinchtab_a11y_audit": handleA11yAudit(c),
+ "pinchtab_navigate": handleNavigate(c),
+ "pinchtab_back": handleHistoryNav(c, "back"),
+ "pinchtab_forward": handleHistoryNav(c, "forward"),
+ "pinchtab_reload": handleHistoryNav(c, "reload"),
+ "pinchtab_snapshot": handleSnapshot(c),
+ "pinchtab_frame": handleFrame(c),
+ "pinchtab_screenshot": handleScreenshot(c),
+ "pinchtab_capture": handleCapture(c),
+ "pinchtab_get_text": handleGetText(c),
+ "pinchtab_a11y_audit": handleA11yAudit(c),
+ "pinchtab_memory": handleMemory(c),
+ "pinchtab_memory_snapshot": handleMemorySnapshot(c),
"pinchtab_click": handleAction(c, "click"),
"pinchtab_type": handleAction(c, "type"),
diff --git a/internal/mcp/routing_test.go b/internal/mcp/routing_test.go
index 1c030071..32ed7b93 100644
--- a/internal/mcp/routing_test.go
+++ b/internal/mcp/routing_test.go
@@ -24,6 +24,8 @@ var browserToolArgs = map[string]map[string]any{
"pinchtab_capture": {},
"pinchtab_get_text": {},
"pinchtab_a11y_audit": {},
+ "pinchtab_memory": {},
+ "pinchtab_memory_snapshot": {},
"pinchtab_click": {"selector": "#go"},
"pinchtab_type": {"selector": "#q", "text": "hello"},
"pinchtab_hover": {"selector": "#go"},
diff --git a/internal/mcp/server_test.go b/internal/mcp/server_test.go
index c60079f9..40ee9d56 100644
--- a/internal/mcp/server_test.go
+++ b/internal/mcp/server_test.go
@@ -19,8 +19,8 @@ func TestNewServer(t *testing.T) {
func TestNewServerRegistersAllTools(t *testing.T) {
_ = NewServer("http://localhost:9867", "")
tools := allTools()
- if len(tools) != 43 {
- t.Errorf("expected 43 tools, got %d — if a tool was added or removed, update this count and the totals in docs/mcp.md", len(tools))
+ if len(tools) != 45 {
+ t.Errorf("expected 45 tools, got %d — if a tool was added or removed, update this count and the totals in docs/mcp.md", len(tools))
}
}
diff --git a/internal/mcp/testdata/preamble_budget.json b/internal/mcp/testdata/preamble_budget.json
index 17dd9f6c..3897fd3c 100644
--- a/internal/mcp/testdata/preamble_budget.json
+++ b/internal/mcp/testdata/preamble_budget.json
@@ -2,7 +2,7 @@
{
"surface": "mcp:allTools",
"minBytes": 18092,
- "maxBytes": 44300,
+ "maxBytes": 45500,
"takenOn": "2026-09-13",
"commit": "52bcc08d"
},
diff --git a/internal/mcp/tools.go b/internal/mcp/tools.go
index a4472fc9..9e1f0cd9 100644
--- a/internal/mcp/tools.go
+++ b/internal/mcp/tools.go
@@ -378,5 +378,7 @@ func allTools() []mcp.Tool {
browserParam(),
),
a11yAuditTool(),
+ memoryTool(),
+ memorySnapshotTool(),
}
}
diff --git a/internal/mcp/tools_memory.go b/internal/mcp/tools_memory.go
new file mode 100644
index 00000000..b4201667
--- /dev/null
+++ b/internal/mcp/tools_memory.go
@@ -0,0 +1,87 @@
+package mcp
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/url"
+ "strconv"
+ "time"
+
+ "github.com/mark3labs/mcp-go/mcp"
+)
+
+const memorySnapshotMCPTimeout = 3 * time.Minute
+
+func memoryTool() mcp.Tool {
+ return mcp.NewTool("pinchtab_memory",
+ mcp.WithDescription("JavaScript heap usage and DOM counters (documents, nodes, listeners, frames) for the tab. gc=true collects garbage first, so reads around an action show retained memory."),
+ tabIDParam(),
+ mcp.WithBoolean("gc", mcp.Description("Run a garbage collection before reading")),
+ browserParam(),
+ )
+}
+
+func memorySnapshotTool() mcp.Tool {
+ return mcp.NewTool("pinchtab_memory_snapshot",
+ mcp.WithDescription("Take a V8 heap snapshot to a server-side file; returns its path and a summary (top constructors by size and count, duplicate strings). Needs security.allowMemory."),
+ tabIDParam(),
+ mcp.WithNumber("top", mcp.Description("Rows per table (default 20)")),
+ browserParam(),
+ )
+}
+
+func handleMemory(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ q := url.Values{}
+ if tabID := optString(r, "tabId"); tabID != "" {
+ q.Set("tabId", tabID)
+ }
+ if gc, ok := optBool(r, "gc"); ok && gc {
+ q.Set("gc", "true")
+ }
+ return toolResult(c.Get(ctx, "/memory", routedQuery(r, q)))
+ }
+}
+
+func handleMemorySnapshot(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ payload := map[string]any{}
+ if tabID := optString(r, "tabId"); tabID != "" {
+ payload["tabId"] = tabID
+ }
+ body, code, err := c.withTimeout(memorySnapshotMCPTimeout).Post(ctx, routedPath(r, "/memory/snapshot"), payload)
+ if err != nil || code >= 400 {
+ return toolResult(body, code, err)
+ }
+ var snap struct {
+ ID string `json:"id"`
+ Path string `json:"path"`
+ Bytes int64 `json:"bytes"`
+ }
+ if err := json.Unmarshal(body, &snap); err != nil || snap.ID == "" {
+ return mcp.NewToolResultError(fmt.Sprintf("heap snapshot response carried no id: %s", string(body))), nil
+ }
+
+ q := url.Values{}
+ if top, ok := optInt(r, "top"); ok && top > 0 {
+ q.Set("top", strconv.Itoa(top))
+ }
+ summaryBody, code, err := c.withTimeout(memorySnapshotMCPTimeout).Get(ctx, "/memory/snapshot/"+url.PathEscape(snap.ID)+"/summary", routedQuery(r, q))
+ if err != nil || code >= 400 {
+ return toolResult(summaryBody, code, err)
+ }
+ var summary map[string]any
+ if err := json.Unmarshal(summaryBody, &summary); err != nil {
+ return mcp.NewToolResultError(fmt.Sprintf("decode heap snapshot summary: %v", err)), nil
+ }
+ delete(summary, "id")
+ delete(summary, "path")
+ return jsonResult(map[string]any{
+ "id": snap.ID,
+ "path": snap.Path,
+ "bytes": snap.Bytes,
+ "summary": summary,
+ })
+ }
+}
diff --git a/internal/mcp/tools_memory_test.go b/internal/mcp/tools_memory_test.go
new file mode 100644
index 00000000..e15c9ef4
--- /dev/null
+++ b/internal/mcp/tools_memory_test.go
@@ -0,0 +1,89 @@
+package mcp
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+func memoryMockServer(t *testing.T, seen *[]string, snapshotStatus int) *httptest.Server {
+ t.Helper()
+ return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ *seen = append(*seen, r.Method+" "+r.URL.RequestURI())
+ w.Header().Set("Content-Type", "application/json")
+ switch r.URL.Path {
+ case "/memory":
+ _ = json.NewEncoder(w).Encode(map[string]any{"tabId": "t1", "usedJSHeapSize": 1024, "gc": r.URL.Query().Get("gc") == "true"})
+ case "/memory/snapshot":
+ w.WriteHeader(snapshotStatus)
+ if snapshotStatus != http.StatusOK {
+ _ = json.NewEncoder(w).Encode(map[string]any{"code": "memory_disabled", "error": "this endpoint requires the memory capability"})
+ return
+ }
+ _ = json.NewEncoder(w).Encode(map[string]any{"id": "heap_1", "path": "/state/heapsnapshots/heap_1.heapsnapshot", "bytes": 2048, "nodeCount": 20, "durationMs": 5})
+ case "/memory/snapshot/heap_1/summary":
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "id": "heap_1", "path": "/state/heapsnapshots/heap_1.heapsnapshot", "top": 5,
+ "nodeCount": 20, "edgeCount": 6,
+ "topBySize": []map[string]any{{"name": "Array", "count": 3, "selfSize": 1664}},
+ })
+ default:
+ w.WriteHeader(http.StatusNotFound)
+ }
+ }))
+}
+
+func TestMemoryToolForwardsGCAndTab(t *testing.T) {
+ var seen []string
+ srv := memoryMockServer(t, &seen, http.StatusOK)
+ defer srv.Close()
+
+ body := resultJSON(t, callSharedTool(t, NewClient(srv.URL, ""), "pinchtab_memory", map[string]any{"tabId": "t1", "gc": true}))
+ if len(seen) != 1 || seen[0] != "GET /memory?gc=true&tabId=t1" {
+ t.Fatalf("requests = %v", seen)
+ }
+ if body["gc"] != true {
+ t.Fatalf("result = %v", body)
+ }
+}
+
+func TestMemorySnapshotToolReturnsThePathAndTheSummaryOnly(t *testing.T) {
+ var seen []string
+ srv := memoryMockServer(t, &seen, http.StatusOK)
+ defer srv.Close()
+
+ body := resultJSON(t, callSharedTool(t, NewClient(srv.URL, ""), "pinchtab_memory_snapshot", map[string]any{"tabId": "t1", "top": float64(5)}))
+ if len(seen) != 2 || seen[0] != "POST /memory/snapshot" || seen[1] != "GET /memory/snapshot/heap_1/summary?top=5" {
+ t.Fatalf("requests = %v, want the snapshot then its summary", seen)
+ }
+ if body["id"] != "heap_1" || body["path"] != "/state/heapsnapshots/heap_1.heapsnapshot" {
+ t.Fatalf("result = %v", body)
+ }
+ summary, _ := body["summary"].(map[string]any)
+ rows, _ := summary["topBySize"].([]any)
+ if len(rows) != 1 || summary["nodeCount"] != float64(20) {
+ t.Fatalf("summary = %v", summary)
+ }
+ if _, dup := summary["path"]; dup {
+ t.Fatalf("summary repeats the path the result already carries: %v", summary)
+ }
+}
+
+func TestMemorySnapshotToolSurfacesTheCapabilityRefusal(t *testing.T) {
+ var seen []string
+ srv := memoryMockServer(t, &seen, http.StatusForbidden)
+ defer srv.Close()
+
+ result := callSharedTool(t, NewClient(srv.URL, ""), "pinchtab_memory_snapshot", map[string]any{})
+ if !result.IsError {
+ t.Fatal("a refused snapshot was reported as success")
+ }
+ if len(seen) != 1 {
+ t.Fatalf("requests = %v, want no summary call after a refusal", seen)
+ }
+ if text := resultText(t, result); !strings.Contains(text, "memory_disabled") {
+ t.Fatalf("refusal text = %q, want the capability code", text)
+ }
+}
diff --git a/internal/orchestrator/handlers.go b/internal/orchestrator/handlers.go
index d67e0696..5b843895 100644
--- a/internal/orchestrator/handlers.go
+++ b/internal/orchestrator/handlers.go
@@ -28,6 +28,8 @@ func (o *Orchestrator) Allows(cap routes.Capability) bool {
return o.AllowsStateExport()
case routes.CapNetworkIntercept:
return o.AllowsNetworkIntercept()
+ case routes.CapMemory:
+ return o.AllowsMemory()
default:
return false
}
diff --git a/internal/orchestrator/orchestrator.go b/internal/orchestrator/orchestrator.go
index a0168f18..4310861e 100644
--- a/internal/orchestrator/orchestrator.go
+++ b/internal/orchestrator/orchestrator.go
@@ -413,6 +413,11 @@ func (o *Orchestrator) AllowsNetworkIntercept() bool {
return cfg != nil && cfg.AllowNetworkIntercept
}
+func (o *Orchestrator) AllowsMemory() bool {
+ cfg := o.cfg()
+ return cfg != nil && cfg.AllowMemory
+}
+
func (o *Orchestrator) SetPortRange(start, end int) {
allocator := NewPortAllocator(start, end)
o.mu.Lock()
diff --git a/internal/routes/routes.go b/internal/routes/routes.go
index 9453338b..21efe901 100644
--- a/internal/routes/routes.go
+++ b/internal/routes/routes.go
@@ -21,6 +21,7 @@ const (
CapUpload Capability = "upload"
CapStateExport Capability = "stateExport"
CapNetworkIntercept Capability = "networkIntercept"
+ CapMemory Capability = "memory"
)
// CapabilityMeta is the single source of truth for a capability gate's
@@ -45,6 +46,7 @@ var capabilityMeta = map[Capability]CapabilityMeta{
CapUpload: {CapUpload, "upload", "security.allowUpload", "upload_disabled"},
CapStateExport: {CapStateExport, "stateExport", "security.allowStateExport", "state_export_disabled"},
CapNetworkIntercept: {CapNetworkIntercept, "networkIntercept", "security.allowNetworkIntercept", "network_intercept_disabled"},
+ CapMemory: {CapMemory, "memory", "security.allowMemory", "memory_disabled"},
}
// Capabilities lists every gated capability, ordered by label so a reporter
@@ -149,6 +151,9 @@ var coreEndpoints = []Endpoint{
{"GET", "/metrics", "Runtime metrics", CapNone, true},
{"GET", "/timing", "Page timing and Core Web Vitals", CapNone, true},
+ {"GET", "/memory", "JavaScript heap usage and DOM counters", CapNone, true},
+ {"POST", "/memory/snapshot", "Take a V8 heap snapshot to a server-side file", CapMemory, true},
+ {"GET", "/memory/snapshot/{snapshotId}/summary", "Summarize a saved heap snapshot", CapMemory, false},
{"GET", "/a11y/audit", "Accessibility findings and score", CapNone, true},
{"POST", "/audit/page", "Audit a single page with browser enrichment", CapNone, false},
{"POST", "/audit", "Run a multi-page site audit", CapNone, false},
diff --git a/internal/routes/routes_test.go b/internal/routes/routes_test.go
index 602712a8..fa2dfe44 100644
--- a/internal/routes/routes_test.go
+++ b/internal/routes/routes_test.go
@@ -241,6 +241,7 @@ func TestCapabilityMetaContract(t *testing.T) {
CapUpload: {CapUpload, "upload", "security.allowUpload", "upload_disabled"},
CapStateExport: {CapStateExport, "stateExport", "security.allowStateExport", "state_export_disabled"},
CapNetworkIntercept: {CapNetworkIntercept, "networkIntercept", "security.allowNetworkIntercept", "network_intercept_disabled"},
+ CapMemory: {CapMemory, "memory", "security.allowMemory", "memory_disabled"},
}
for cap, expected := range want {
got, ok := Meta(cap)
diff --git a/internal/schema/config.json b/internal/schema/config.json
index cc04fd2d..9becad82 100644
--- a/internal/schema/config.json
+++ b/internal/schema/config.json
@@ -473,6 +473,10 @@
"allowCookies": {
"$ref": "#/definitions/nullableBoolean"
},
+ "allowMemory": {
+ "$ref": "#/definitions/nullableBoolean",
+ "description": "Enables POST /memory/snapshot and GET /memory/snapshot/{id}/summary. A heap snapshot holds every string on the page, tokens included. GET /memory stays available."
+ },
"allowedDomains": {
"$ref": "#/definitions/domainPatternArray"
},
@@ -492,6 +496,19 @@
],
"default": 20971520
},
+ "memorySnapshotMaxBytes": {
+ "anyOf": [
+ {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 4294967296
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": 536870912
+ },
"allowUpload": {
"$ref": "#/definitions/nullableBoolean"
},
diff --git a/tests/e2e/config/pinchtab.json b/tests/e2e/config/pinchtab.json
index 842c2b59..131bbc5b 100644
--- a/tests/e2e/config/pinchtab.json
+++ b/tests/e2e/config/pinchtab.json
@@ -43,6 +43,7 @@
"allowUpload": true,
"allowClipboard": true,
"allowStateExport": true,
+ "allowMemory": true,
"allowedDomains": [
"localhost",
"127.0.0.1",
diff --git a/tests/e2e/fixtures/memory-leak.html b/tests/e2e/fixtures/memory-leak.html
new file mode 100644
index 00000000..83ac084e
--- /dev/null
+++ b/tests/e2e/fixtures/memory-leak.html
@@ -0,0 +1,26 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <meta charset="utf-8">
+ <title>Memory Leak Fixture</title>
+</head>
+<body>
+ <h1>Memory Leak Fixture</h1>
+ <p>Each Leak click appends a 5 MB array of doubles to <code>window.leaked</code>; Release drops them all.</p>
+ <button id="leak" type="button">Leak</button>
+ <button id="release" type="button">Release</button>
+ <p>Arrays held: <span id="count">0</span></p>
+ <script>
+ window.leaked = [];
+ const DOUBLES_PER_LEAK = 5 * 1024 * 1024 / 8;
+ document.getElementById("leak").addEventListener("click", () => {
+ window.leaked.push(Array.from({ length: DOUBLES_PER_LEAK }, (_, i) => i + 0.5));
+ document.getElementById("count").textContent = String(window.leaked.length);
+ });
+ document.getElementById("release").addEventListener("click", () => {
+ window.leaked = [];
+ document.getElementById("count").textContent = "0";
+ });
+ </script>
+</body>
+</html>
diff --git a/tests/e2e/scenarios/api/memory-basic.sh b/tests/e2e/scenarios/api/memory-basic.sh
new file mode 100644
index 00000000..5c511920
--- /dev/null
+++ b/tests/e2e/scenarios/api/memory-basic.sh
@@ -0,0 +1,85 @@
+#!/bin/bash
+# memory-basic.sh — GET /memory tracks a leak and its release; POST /memory/snapshot
+# writes a heap snapshot the summary endpoint reads. The default e2e server runs with
+# security.allowMemory on; memory-extended.sh covers the refusal on a server with it off.
+
+GROUP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+source "${GROUP_DIR}/../../helpers/api.sh"
+
+MB=$((1024 * 1024))
+
+# ─────────────────────────────────────────────────────────────────
+start_test "memory: usedJSHeapSize grows with three leaks and falls back after release + gc"
+
+pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/memory-leak.html\"}"
+assert_ok "navigate to memory-leak.html"
+TAB_ID=$(echo "$RESULT" | jq -r '.tabId')
+
+pt_get "/memory?tabId=${TAB_ID}&gc=true"
+assert_ok "baseline read with gc"
+for key in usedJSHeapSize totalJSHeapSize jsHeapSizeLimit documents nodes listeners frames; do
+ assert_json_exists "$RESULT" ".${key}" "usage reports ${key}"
+done
+BASELINE=$(echo "$RESULT" | jq -r '.usedJSHeapSize')
+
+for i in 1 2 3; do
+ pt_post /action -d "{\"tabId\":\"${TAB_ID}\",\"kind\":\"click\",\"selector\":\"#leak\"}"
+ assert_ok "leak click ${i}"
+done
+
+pt_get "/memory?tabId=${TAB_ID}"
+assert_ok "read after three leaks"
+LEAKED=$(echo "$RESULT" | jq -r '.usedJSHeapSize')
+if [ "$LEAKED" -ge $((BASELINE + 10 * MB)) ]; then
+ pass_assert "usedJSHeapSize grew by at least 10 MB ($BASELINE → $LEAKED)"
+else
+ fail_assert "usedJSHeapSize grew only from $BASELINE to $LEAKED, want at least +10 MB"
+fi
+
+pt_post /action -d "{\"tabId\":\"${TAB_ID}\",\"kind\":\"click\",\"selector\":\"#release\"}"
+assert_ok "release click"
+
+pt_get "/memory?tabId=${TAB_ID}&gc=true"
+assert_ok "read after release with gc"
+assert_json_eq "$RESULT" '.gc' 'true' "reading says it collected first"
+RELEASED=$(echo "$RESULT" | jq -r '.usedJSHeapSize')
+if [ "$RELEASED" -lt $((BASELINE + 2 * MB)) ]; then
+ pass_assert "usedJSHeapSize back under baseline + 2 MB ($RELEASED < $BASELINE + 2 MB)"
+else
+ fail_assert "usedJSHeapSize $RELEASED after release + gc, want under $((BASELINE + 2 * MB))"
+fi
+
+pt_get "/tabs/${TAB_ID}/memory"
+assert_ok "tab-scoped usage route"
+assert_json_eq "$RESULT" '.tabId' "$TAB_ID" "tab-scoped read names the tab"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "memory: snapshot writes a server-side file whose summary lists Array"
+
+pt_post /action -d "{\"tabId\":\"${TAB_ID}\",\"kind\":\"click\",\"selector\":\"#leak\"}"
+assert_ok "leak one array so the snapshot holds it"
+
+pt_post /memory/snapshot -d "{\"tabId\":\"${TAB_ID}\"}"
+assert_ok "take heap snapshot"
+SNAP_ID=$(echo "$RESULT" | jq -r '.id')
+assert_json_contains "$RESULT" '.path' '/heapsnapshots/' "path is under the server-controlled heapsnapshots dir"
+assert_json_contains "$RESULT" '.path' '.heapsnapshot' "path carries the .heapsnapshot extension"
+assert_json_jq "$RESULT" '.bytes > 0' "snapshot has bytes" "snapshot reported no bytes"
+assert_json_jq "$RESULT" '.nodeCount > 0' "snapshot reports a node count" "snapshot reported no nodes"
+assert_json_exists "$RESULT" '.durationMs' "snapshot reports its duration"
+
+pt_get "/memory/snapshot/${SNAP_ID}/summary?top=50"
+assert_ok "summary reads the file the snapshot wrote"
+assert_json_jq "$RESULT" '.nodeCount > 0 and .edgeCount > 0' "summary counts nodes and edges" "summary counted no nodes or edges"
+assert_json_jq "$RESULT" '([.topBySize[].name] + [.topByCount[].name]) | index("Array") != null' "Array is among the top constructors" "Array missing from the top constructors"
+assert_json_exists "$RESULT" '.duplicateStrings' "summary lists duplicate strings"
+
+pt_get "/memory/snapshot/heap_does_not_exist/summary"
+assert_http_status 404 "unknown snapshot id"
+assert_json_eq "$RESULT" '.code' 'memory_snapshot_not_found' "unknown id is memory_snapshot_not_found"
+
+pt_post /action -d "{\"tabId\":\"${TAB_ID}\",\"kind\":\"click\",\"selector\":\"#release\"}"
+
+end_test
diff --git a/tests/e2e/scenarios/api/memory-extended.sh b/tests/e2e/scenarios/api/memory-extended.sh
new file mode 100644
index 00000000..442cee07
--- /dev/null
+++ b/tests/e2e/scenarios/api/memory-extended.sh
@@ -0,0 +1,33 @@
+#!/bin/bash
+# memory-extended.sh — the memory capability refusal on a server whose config leaves
+# security.allowMemory off (pinchtab-secure). memory-basic.sh runs the enabled path on
+# the default server; the basic lane has one server, so the second config lives here.
+
+GROUP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+source "${GROUP_DIR}/../../helpers/api.sh"
+
+memory_disabled_tests() {
+ # ─────────────────────────────────────────────────────────────────
+ start_test "memory: allowMemory off refuses snapshot and summary, usage still answers"
+
+ pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/memory-leak.html\"}"
+ assert_ok "navigate to memory-leak.html"
+ TAB_ID=$(echo "$RESULT" | jq -r '.tabId')
+
+ pt_get "/memory?tabId=${TAB_ID}"
+ assert_ok "GET /memory is not capability-gated"
+ assert_json_exists "$RESULT" '.usedJSHeapSize' "usage reports usedJSHeapSize"
+
+ pt_post /memory/snapshot -d "{\"tabId\":\"${TAB_ID}\"}"
+ assert_http_status 403 "snapshot refused"
+ assert_json_eq "$RESULT" '.code' 'memory_disabled' "snapshot answers memory_disabled"
+ assert_json_eq "$RESULT" '.details.setting' 'security.allowMemory' "refusal names the setting"
+
+ pt_get "/memory/snapshot/heap_any/summary"
+ assert_http_status 403 "summary refused"
+ assert_json_eq "$RESULT" '.code' 'memory_disabled' "summary answers memory_disabled"
+
+ end_test
+}
+
+with_server "$E2E_SECURE_SERVER" memory_disabled_tests
diff --git a/tests/e2e/scenarios/cli/memory-basic.sh b/tests/e2e/scenarios/cli/memory-basic.sh
new file mode 100644
index 00000000..411b57bc
--- /dev/null
+++ b/tests/e2e/scenarios/cli/memory-basic.sh
@@ -0,0 +1,50 @@
+#!/bin/bash
+# memory-basic.sh — CLI: pinchtab memory reads heap usage, memory snapshot writes a
+# heap snapshot, and memory summary prints its constructor table. The default e2e
+# server runs with security.allowMemory on.
+
+GROUP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+source "${GROUP_DIR}/../../helpers/cli.sh"
+
+# ─────────────────────────────────────────────────────────────────
+start_test "pinchtab memory --json"
+
+pt_ok nav "${FIXTURES_URL}/memory-leak.html"
+
+pt_ok memory --json
+for key in usedJSHeapSize totalJSHeapSize jsHeapSizeLimit documents nodes listeners frames; do
+ assert_output_contains "\"$key\"" "usage reports $key"
+done
+
+pt_ok memory --gc
+assert_output_contains "heap used" "human summary line"
+assert_output_contains "(after gc)" "summary says it collected first"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "pinchtab memory snapshot + summary --top 5"
+
+pt_ok click "#leak"
+
+pt_ok memory snapshot
+assert_output_contains "Heap snapshot heap_" "snapshot prints its id"
+assert_output_contains ".heapsnapshot" "snapshot prints the file path"
+SNAP_ID=$(grep -o 'pinchtab memory summary [^ ]*' <<<"$PT_OUT" | awk '{print $4}')
+if [ -n "$SNAP_ID" ]; then
+ pass_assert "snapshot id parsed: $SNAP_ID"
+else
+ fail_assert "no snapshot id in the output"
+fi
+
+pt_ok memory summary "$SNAP_ID" --top 5
+assert_output_contains "CONSTRUCTOR" "summary prints the constructor table header"
+assert_output_contains "Top constructors by self size" "size table present"
+assert_output_contains "Top constructors by count" "count table present"
+
+pt_ok memory summary "$SNAP_ID" --top 5 --json
+assert_output_contains '"topBySize"' "json summary carries topBySize"
+
+pt_ok click "#release"
+
+end_test
diff --git a/tests/e2e/scenarios/manifest.json b/tests/e2e/scenarios/manifest.json
index 9d0f8ec6..6ceec8fa 100644
--- a/tests/e2e/scenarios/manifest.json
+++ b/tests/e2e/scenarios/manifest.json
@@ -566,6 +566,33 @@
"extract",
"corpus"
]
+ },
+ "api/memory-basic.sh": {
+ "tags": [
+ "memory",
+ "pr"
+ ]
+ },
+ "api/memory-extended.sh": {
+ "services": [
+ "pinchtab",
+ "pinchtab-secure",
+ "fixtures"
+ ],
+ "ready": [
+ "E2E_SERVER",
+ "E2E_SECURE_SERVER"
+ ],
+ "tags": [
+ "memory",
+ "secure"
+ ]
+ },
+ "cli/memory-basic.sh": {
+ "tags": [
+ "memory",
+ "pr"
+ ]
}
}
}