High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
refactoring: srp
Luigi Agosti73cabd2df64a
diff --git a/README.md b/README.mdindex 9f961b58..da6fef7a 100644--- a/README.md+++ b/README.md@@ -75,6 +75,28 @@ go build -o pinchtab .BRIDGE_HEADLESS=true ./pinchtab```+### Run Modes++| Mode | Command | Notes |+|---|---|---|+| Headed (default) | `./pinchtab` | Launches managed Chrome with visible window |+| Headless | `BRIDGE_HEADLESS=true ./pinchtab` | Launches managed Chrome without UI |+| Remote CDP | `CDP_URL=http://localhost:9222 ./pinchtab` | Connects to an existing Chrome instead of launching one |+| Dashboard only | `./pinchtab dashboard` | Runs the dashboard/orchestrator entrypoint |++Common runtime options:++```bash+# Custom port+BRIDGE_PORT=9870 ./pinchtab++# Custom profile directory+BRIDGE_PROFILE=/path/to/profile ./pinchtab++# Enable API auth+BRIDGE_TOKEN=your-secret-token ./pinchtab+```+### Headless Mode (recommended)<img src="assets/pinchtab-headless.png" width="64" alt="Pinchtab" />@@ -336,4 +358,3 @@ Pinchtab is built to work seamlessly with [OpenClaw](https://openclaw.ai) — th<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=pinchtab/pinchtab&type=Date&v=20260219" /></picture></a>-diff --git a/bridge.go b/bridge.goindex f3eea998..44a294cf 100644--- a/bridge.go+++ b/bridge.go@@ -1,14 +1,4 @@-package // TabEntry holds a chromedp context for an open tab.-// Bridge is the central state holder for the Chrome connection, tab contexts, and per-tab snapshot caches.-// TabContext returns the chromedp context for a tab and the resolved tabID.-// CleanStaleTabs periodically removes tab entries whose Chrome targets no longer exist.-// GetRefCache returns the cached snapshot refs for a tab (nil if none).-// SetRefCache stores the snapshot ref cache for a tab.-// DeleteRefCache removes the snapshot ref cache for a tab.-// CreateTab opens a new tab, navigates to url, and returns its ID and context.-// CloseTab closes a tab by ID and cleans up caches.-// ListTargets returns all open page targets from Chrome.-main+package mainimport ("context"diff --git a/config.go b/config.goindex 33b0541b..cb947531 100644--- a/config.go+++ b/config.go@@ -1,5 +1,4 @@-package // Config represents the configuration file structure.-main+package mainimport (_ "embed"@@ -35,10 +34,13 @@ const (tabActionClose = "close")+//go:embed stealth.jsvar stealthScript string+//go:embed readability.jsvar readabilityJS string+//go:embed welcome.htmlvar welcomeHTML stringvar (diff --git a/dashboard.go b/dashboard.goindex ba5e81d1..b1b44a13 100644--- a/dashboard.go+++ b/dashboard.go@@ -1,9 +1,4 @@-package // DashboardConfig holds tunable timeouts for agent status transitions.-// Shutdown stops the reaper goroutine.-// RecordEvent processes an agent action and broadcasts to SSE subscribers.-// GetAgents returns current state of all agents.-// EventObserver receives agent events for additional processing (e.-main+package mainimport ("context"@@ -24,6 +19,7 @@ type DashboardConfig struct {SSEBufferSize int}+//go:embed dashboard/*var dashboardFS embed.FStype AgentActivity struct {diff --git a/handler_actions.go b/handler_actions.goindex 00052477..159c098b 100644--- a/handler_actions.go+++ b/handler_actions.go@@ -1,5 +1,4 @@-package // ActionFunc handles a single action kind.-main+package mainimport ("context"diff --git a/handler_health_tabs.go b/handler_health_tabs.gonew file mode 100644index 00000000..9c028e74--- /dev/null+++ b/handler_health_tabs.go@@ -0,0 +1,39 @@+package main++import (+ "net/http"+ "time"+)++func (b *Bridge) handleHealth(w http.ResponseWriter, r *http.Request) {+ targets, err := b.ListTargets()+ if err != nil {+ jsonResp(w, 200, map[string]any{"status": "disconnected", "error": err.Error(), "cdp": cdpURL})+ return+ }+ jsonResp(w, 200, map[string]any{"status": "ok", "tabs": len(targets), "cdp": cdpURL})+}++func (b *Bridge) handleTabs(w http.ResponseWriter, r *http.Request) {+ targets, err := b.ListTargets()+ if err != nil {+ jsonErr(w, 500, err)+ return+ }++ tabs := make([]map[string]any, 0, len(targets))+ for _, t := range targets {+ entry := map[string]any{+ "id": string(t.TargetID),+ "url": t.URL,+ "title": t.Title,+ "type": t.Type,+ }+ if lock := b.locks.Get(string(t.TargetID)); lock != nil {+ entry["owner"] = lock.Owner+ entry["lockedUntil"] = lock.ExpiresAt.Format(time.RFC3339)+ }+ tabs = append(tabs, entry)+ }+ jsonResp(w, 200, map[string]any{"tabs": tabs})+}diff --git a/handler_lock_shutdown.go b/handler_lock_shutdown.gonew file mode 100644index 00000000..5e0a80ff--- /dev/null+++ b/handler_lock_shutdown.go@@ -0,0 +1,76 @@+package main++import (+ "encoding/json"+ "fmt"+ "log/slog"+ "net/http"+ "time"+)++func (b *Bridge) handleTabLock(w http.ResponseWriter, r *http.Request) {+ var req struct {+ TabID string `json:"tabId"`+ Owner string `json:"owner"`+ TimeoutSec int `json:"timeoutSec"`+ }+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {+ jsonErr(w, 400, fmt.Errorf("decode: %w", err))+ return+ }+ if req.TabID == "" || req.Owner == "" {+ jsonErr(w, 400, fmt.Errorf("tabId and owner required"))+ return+ }++ timeout := defaultLockTimeout+ if req.TimeoutSec > 0 {+ timeout = time.Duration(req.TimeoutSec) * time.Second+ }++ if err := b.locks.Lock(req.TabID, req.Owner, timeout); err != nil {+ jsonErr(w, 409, err)+ return+ }++ lock := b.locks.Get(req.TabID)+ jsonResp(w, 200, map[string]any{+ "locked": true,+ "owner": lock.Owner,+ "expiresAt": lock.ExpiresAt.Format(time.RFC3339),+ })+}++func (b *Bridge) handleTabUnlock(w http.ResponseWriter, r *http.Request) {+ var req struct {+ TabID string `json:"tabId"`+ Owner string `json:"owner"`+ }+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {+ jsonErr(w, 400, fmt.Errorf("decode: %w", err))+ return+ }+ if req.TabID == "" || req.Owner == "" {+ jsonErr(w, 400, fmt.Errorf("tabId and owner required"))+ return+ }++ if err := b.locks.Unlock(req.TabID, req.Owner); err != nil {+ jsonErr(w, 409, err)+ return+ }++ jsonResp(w, 200, map[string]any{"unlocked": true})+}++func (b *Bridge) handleShutdown(shutdownFn func()) func(http.ResponseWriter, *http.Request) {+ return func(w http.ResponseWriter, r *http.Request) {+ slog.Info("shutdown requested via API")+ jsonResp(w, 200, map[string]any{"status": "shutting down"})++ go func() {+ time.Sleep(100 * time.Millisecond)+ shutdownFn()+ }()+ }+}diff --git a/handler_media.go b/handler_media.gonew file mode 100644index 00000000..33074a8c--- /dev/null+++ b/handler_media.go@@ -0,0 +1,140 @@+package main++import (+ "context"+ "encoding/base64"+ "fmt"+ "log/slog"+ "net/http"+ "os"+ "path/filepath"+ "strconv"+ "time"++ "github.com/chromedp/cdproto/page"+ "github.com/chromedp/chromedp"+)++func (b *Bridge) handleScreenshot(w http.ResponseWriter, r *http.Request) {+ tabID := r.URL.Query().Get("tabId")+ output := r.URL.Query().Get("output")+ reqNoAnim := r.URL.Query().Get("noAnimations") == "true"++ ctx, _, err := b.TabContext(tabID)+ if err != nil {+ jsonErr(w, 404, err)+ return+ }++ tCtx, tCancel := context.WithTimeout(ctx, actionTimeout)+ defer tCancel()+ go cancelOnClientDone(r.Context(), tCancel)++ if reqNoAnim && !noAnimations {+ disableAnimationsOnce(tCtx)+ }++ var buf []byte+ quality := 80+ if q := r.URL.Query().Get("quality"); q != "" {+ if qn, err := strconv.Atoi(q); err == nil {+ quality = qn+ }+ }++ if err := chromedp.Run(tCtx,+ chromedp.ActionFunc(func(ctx context.Context) error {+ var err error+ buf, err = page.CaptureScreenshot().+ WithFormat(page.CaptureScreenshotFormatJpeg).+ WithQuality(int64(quality)).+ Do(ctx)+ return err+ }),+ ); err != nil {+ jsonErr(w, 500, fmt.Errorf("screenshot: %w", err))+ return+ }++ if output == "file" {+ screenshotDir := filepath.Join(stateDir, "screenshots")+ if err := os.MkdirAll(screenshotDir, 0755); err != nil {+ jsonErr(w, 500, fmt.Errorf("create screenshot dir: %w", err))+ return+ }++ timestamp := time.Now().Format("20060102-150405")+ filename := fmt.Sprintf("screenshot-%s.jpg", timestamp)+ filePath := filepath.Join(screenshotDir, filename)++ if err := os.WriteFile(filePath, buf, 0644); err != nil {+ jsonErr(w, 500, fmt.Errorf("write screenshot: %w", err))+ return+ }++ jsonResp(w, 200, map[string]any{+ "path": filePath,+ "size": len(buf),+ "format": "jpeg",+ "timestamp": timestamp,+ })+ return+ }++ if r.URL.Query().Get("raw") == "true" {+ w.Header().Set("Content-Type", "image/jpeg")+ if _, err := w.Write(buf); err != nil {+ slog.Error("screenshot write", "err", err)+ }+ return+ }++ jsonResp(w, 200, map[string]any{+ "format": "jpeg",+ "base64": base64.StdEncoding.EncodeToString(buf),+ })+}++func (b *Bridge) handleText(w http.ResponseWriter, r *http.Request) {+ tabID := r.URL.Query().Get("tabId")+ mode := r.URL.Query().Get("mode")++ ctx, _, err := b.TabContext(tabID)+ if err != nil {+ jsonErr(w, 404, err)+ return+ }++ tCtx, tCancel := context.WithTimeout(ctx, actionTimeout)+ defer tCancel()+ go cancelOnClientDone(r.Context(), tCancel)++ var text string+ if mode == "raw" {+ if err := chromedp.Run(tCtx,+ chromedp.Evaluate(`document.body.innerText`, &text),+ ); err != nil {+ jsonErr(w, 500, fmt.Errorf("text extract: %w", err))+ return+ }+ } else {+ if err := chromedp.Run(tCtx,+ chromedp.Evaluate(readabilityJS, &text),+ ); err != nil {+ jsonErr(w, 500, fmt.Errorf("text extract: %w", err))+ return+ }+ }++ var url, title string+ _ = chromedp.Run(tCtx,+ chromedp.Location(&url),+ chromedp.Title(&title),+ )++ jsonResp(w, 200, map[string]any{+ "url": url,+ "title": title,+ "text": text,+ })+}diff --git a/handler_navigation.go b/handler_navigation.gonew file mode 100644index 00000000..4a504a2b--- /dev/null+++ b/handler_navigation.go@@ -0,0 +1,185 @@+package main++import (+ "context"+ "encoding/json"+ "fmt"+ "net/http"+ "time"++ "github.com/chromedp/chromedp"+)++func (b *Bridge) handleNavigate(w http.ResponseWriter, r *http.Request) {+ var req struct {+ TabID string `json:"tabId"`+ URL string `json:"url"`+ NewTab bool `json:"newTab"`+ WaitTitle float64 `json:"waitTitle"`+ Timeout float64 `json:"timeout"`+ BlockImages *bool `json:"blockImages"`+ BlockMedia *bool `json:"blockMedia"`+ }+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {+ jsonErr(w, 400, fmt.Errorf("decode: %w", err))+ return+ }+ if req.URL == "" {+ jsonErr(w, 400, fmt.Errorf("url required"))+ return+ }++ titleWait := time.Duration(0)+ if req.WaitTitle > 0 {+ if req.WaitTitle > 30 {+ req.WaitTitle = 30+ }+ titleWait = time.Duration(req.WaitTitle * float64(time.Second))+ }++ navTimeout := navigateTimeout+ if req.Timeout > 0 {+ if req.Timeout > 120 {+ req.Timeout = 120+ }+ navTimeout = time.Duration(req.Timeout * float64(time.Second))+ }++ var blockPatterns []string+ if req.BlockMedia != nil && *req.BlockMedia {+ blockPatterns = mediaBlockPatterns+ } else if req.BlockImages != nil && *req.BlockImages {+ blockPatterns = imageBlockPatterns+ } else if req.BlockImages != nil && !*req.BlockImages {+ blockPatterns = nil+ } else if blockMedia {+ blockPatterns = mediaBlockPatterns+ } else if blockImages {+ blockPatterns = imageBlockPatterns+ }++ if req.NewTab {+ newTargetID, newCtx, _, err := b.CreateTab(req.URL)+ if err != nil {+ jsonErr(w, 500, fmt.Errorf("new tab: %w", err))+ return+ }++ tCtx, tCancel := context.WithTimeout(newCtx, navTimeout)+ defer tCancel()+ go cancelOnClientDone(r.Context(), tCancel)++ if blockPatterns != nil {+ _ = setResourceBlocking(tCtx, blockPatterns)+ }++ var url, title string+ _ = chromedp.Run(tCtx, chromedp.Location(&url))+ title = waitForTitle(tCtx, titleWait)++ jsonResp(w, 200, map[string]any{"tabId": newTargetID, "url": url, "title": title})+ return+ }++ ctx, resolvedTabID, err := b.TabContext(req.TabID)+ if err != nil {+ jsonErr(w, 404, err)+ return+ }++ tCtx, tCancel := context.WithTimeout(ctx, navTimeout)+ defer tCancel()+ go cancelOnClientDone(r.Context(), tCancel)++ if blockPatterns != nil {+ _ = setResourceBlocking(tCtx, blockPatterns)+ } else if blockImages {+ _ = setResourceBlocking(tCtx, nil)+ }++ if err := navigatePage(tCtx, req.URL); err != nil {+ jsonErr(w, 500, fmt.Errorf("navigate: %w", err))+ return+ }++ b.DeleteRefCache(resolvedTabID)++ var url string+ _ = chromedp.Run(tCtx, chromedp.Location(&url))+ title := waitForTitle(tCtx, titleWait)++ jsonResp(w, 200, map[string]any{"url": url, "title": title})+}++func (b *Bridge) handleEvaluate(w http.ResponseWriter, r *http.Request) {+ var req struct {+ TabID string `json:"tabId"`+ Expression string `json:"expression"`+ }+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {+ jsonErr(w, 400, fmt.Errorf("decode: %w", err))+ return+ }+ if req.Expression == "" {+ jsonErr(w, 400, fmt.Errorf("expression required"))+ return+ }++ ctx, _, err := b.TabContext(req.TabID)+ if err != nil {+ jsonErr(w, 404, err)+ return+ }++ tCtx, tCancel := context.WithTimeout(ctx, actionTimeout)+ defer tCancel()+ go cancelOnClientDone(r.Context(), tCancel)++ var result any+ if err := chromedp.Run(tCtx, chromedp.Evaluate(req.Expression, &result)); err != nil {+ jsonErr(w, 500, fmt.Errorf("evaluate: %w", err))+ return+ }++ jsonResp(w, 200, map[string]any{"result": result})+}++func (b *Bridge) handleTab(w http.ResponseWriter, r *http.Request) {+ var req struct {+ Action string `json:"action"`+ TabID string `json:"tabId"`+ URL string `json:"url"`+ }+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {+ jsonErr(w, 400, fmt.Errorf("decode: %w", err))+ return+ }++ switch req.Action {+ case tabActionNew:+ newTargetID, ctx, _, err := b.CreateTab(req.URL)+ if err != nil {+ jsonErr(w, 500, err)+ return+ }++ var curURL, title string+ _ = chromedp.Run(ctx, chromedp.Location(&curURL), chromedp.Title(&title))+ jsonResp(w, 200, map[string]any{"tabId": newTargetID, "url": curURL, "title": title})++ case tabActionClose:+ if req.TabID == "" {+ jsonErr(w, 400, fmt.Errorf("tabId required"))+ return+ }++ if err := b.CloseTab(req.TabID); err != nil {+ jsonErr(w, 500, err)+ return+ }+ jsonResp(w, 200, map[string]any{"closed": true})++ default:+ jsonErr(w, 400, fmt.Errorf("action must be 'new' or 'close'"))+ }+}diff --git a/handlers.go b/handlers.godeleted file mode 100644index 3709b321..00000000--- a/handlers.go+++ /dev/null@@ -1,417 +0,0 @@-package main--import (- "context"- "encoding/base64"- "encoding/json"- "fmt"- "log/slog"- "net/http"- "os"- "path/filepath"- "strconv"- "time"-- "github.com/chromedp/cdproto/page"- "github.com/chromedp/chromedp"-)--func (b *Bridge) handleHealth(w http.ResponseWriter, r *http.Request) {- targets, err := b.ListTargets()- if err != nil {- jsonResp(w, 200, map[string]any{"status": "disconnected", "error": err.Error(), "cdp": cdpURL})- return- }- jsonResp(w, 200, map[string]any{"status": "ok", "tabs": len(targets), "cdp": cdpURL})-}--func (b *Bridge) handleTabs(w http.ResponseWriter, r *http.Request) {- targets, err := b.ListTargets()- if err != nil {- jsonErr(w, 500, err)- return- }-- tabs := make([]map[string]any, 0, len(targets))- for _, t := range targets {- entry := map[string]any{- "id": string(t.TargetID),- "url": t.URL,- "title": t.Title,- "type": t.Type,- }- if lock := b.locks.Get(string(t.TargetID)); lock != nil {- entry["owner"] = lock.Owner- entry["lockedUntil"] = lock.ExpiresAt.Format(time.RFC3339)- }- tabs = append(tabs, entry)- }- jsonResp(w, 200, map[string]any{"tabs": tabs})-}--func (b *Bridge) handleScreenshot(w http.ResponseWriter, r *http.Request) {- tabID := r.URL.Query().Get("tabId")- output := r.URL.Query().Get("output")- reqNoAnim := r.URL.Query().Get("noAnimations") == "true"-- ctx, _, err := b.TabContext(tabID)- if err != nil {- jsonErr(w, 404, err)- return- }-- tCtx, tCancel := context.WithTimeout(ctx, actionTimeout)- defer tCancel()- go cancelOnClientDone(r.Context(), tCancel)-- if reqNoAnim && !noAnimations {- disableAnimationsOnce(tCtx)- }-- var buf []byte- quality := 80- if q := r.URL.Query().Get("quality"); q != "" {- if qn, err := strconv.Atoi(q); err == nil {- quality = qn- }- }-- if err := chromedp.Run(tCtx,- chromedp.ActionFunc(func(ctx context.Context) error {- var err error- buf, err = page.CaptureScreenshot().- WithFormat(page.CaptureScreenshotFormatJpeg).- WithQuality(int64(quality)).- Do(ctx)- return err- }),- ); err != nil {- jsonErr(w, 500, fmt.Errorf("screenshot: %w", err))- return- }-- if output == "file" {- screenshotDir := filepath.Join(stateDir, "screenshots")- if err := os.MkdirAll(screenshotDir, 0755); err != nil {- jsonErr(w, 500, fmt.Errorf("create screenshot dir: %w", err))- return- }-- timestamp := time.Now().Format("20060102-150405")- filename := fmt.Sprintf("screenshot-%s.jpg", timestamp)- filePath := filepath.Join(screenshotDir, filename)-- if err := os.WriteFile(filePath, buf, 0644); err != nil {- jsonErr(w, 500, fmt.Errorf("write screenshot: %w", err))- return- }-- jsonResp(w, 200, map[string]any{- "path": filePath,- "size": len(buf),- "format": "jpeg",- "timestamp": timestamp,- })- return- }-- if r.URL.Query().Get("raw") == "true" {- w.Header().Set("Content-Type", "image/jpeg")- if _, err := w.Write(buf); err != nil {- slog.Error("screenshot write", "err", err)- }- return- }-- jsonResp(w, 200, map[string]any{- "format": "jpeg",- "base64": base64.StdEncoding.EncodeToString(buf),- })-}--func (b *Bridge) handleText(w http.ResponseWriter, r *http.Request) {- tabID := r.URL.Query().Get("tabId")- mode := r.URL.Query().Get("mode")-- ctx, _, err := b.TabContext(tabID)- if err != nil {- jsonErr(w, 404, err)- return- }-- tCtx, tCancel := context.WithTimeout(ctx, actionTimeout)- defer tCancel()- go cancelOnClientDone(r.Context(), tCancel)-- var text string- if mode == "raw" {- if err := chromedp.Run(tCtx,- chromedp.Evaluate(`document.body.innerText`, &text),- ); err != nil {- jsonErr(w, 500, fmt.Errorf("text extract: %w", err))- return- }- } else {- if err := chromedp.Run(tCtx,- chromedp.Evaluate(readabilityJS, &text),- ); err != nil {- jsonErr(w, 500, fmt.Errorf("text extract: %w", err))- return- }- }-- var url, title string- _ = chromedp.Run(tCtx,- chromedp.Location(&url),- chromedp.Title(&title),- )-- jsonResp(w, 200, map[string]any{- "url": url,- "title": title,- "text": text,- })-}--func (b *Bridge) handleNavigate(w http.ResponseWriter, r *http.Request) {- var req struct {- TabID string `json:"tabId"`- URL string `json:"url"`- NewTab bool `json:"newTab"`- WaitTitle float64 `json:"waitTitle"` // seconds to wait for title (default 2, max 30)- Timeout float64 `json:"timeout"` // per-request navigate timeout in seconds (default: BRIDGE_NAV_TIMEOUT)- BlockImages *bool `json:"blockImages"` // per-request override; nil = use global BRIDGE_BLOCK_IMAGES- BlockMedia *bool `json:"blockMedia"` // block images + fonts + CSS + video/audio- }- if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {- jsonErr(w, 400, fmt.Errorf("decode: %w", err))- return- }- if req.URL == "" {- jsonErr(w, 400, fmt.Errorf("url required"))- return- }-- titleWait := time.Duration(0)- if req.WaitTitle > 0 {- if req.WaitTitle > 30 {- req.WaitTitle = 30- }- titleWait = time.Duration(req.WaitTitle * float64(time.Second))- }-- navTimeout := navigateTimeout- if req.Timeout > 0 {- if req.Timeout > 120 {- req.Timeout = 120- }- navTimeout = time.Duration(req.Timeout * float64(time.Second))- }-- // Resolve resource blocking: per-request overrides global.- var blockPatterns []string- if req.BlockMedia != nil && *req.BlockMedia {- blockPatterns = mediaBlockPatterns- } else if req.BlockImages != nil && *req.BlockImages {- blockPatterns = imageBlockPatterns- } else if req.BlockImages != nil && !*req.BlockImages {- blockPatterns = nil- } else if blockMedia {- blockPatterns = mediaBlockPatterns- } else if blockImages {- blockPatterns = imageBlockPatterns- }-- if req.NewTab {- newTargetID, newCtx, _, err := b.CreateTab(req.URL)- if err != nil {- jsonErr(w, 500, fmt.Errorf("new tab: %w", err))- return- }-- tCtx, tCancel := context.WithTimeout(newCtx, navTimeout)- defer tCancel()- go cancelOnClientDone(r.Context(), tCancel)-- if blockPatterns != nil {- _ = setResourceBlocking(tCtx, blockPatterns)- }-- var url, title string- _ = chromedp.Run(tCtx, chromedp.Location(&url))- title = waitForTitle(tCtx, titleWait)-- jsonResp(w, 200, map[string]any{"tabId": newTargetID, "url": url, "title": title})- return- }-- ctx, resolvedTabID, err := b.TabContext(req.TabID)- if err != nil {- jsonErr(w, 404, err)- return- }-- tCtx, tCancel := context.WithTimeout(ctx, navTimeout)- defer tCancel()- go cancelOnClientDone(r.Context(), tCancel)-- if blockPatterns != nil {- _ = setResourceBlocking(tCtx, blockPatterns)- } else if blockImages {-- _ = setResourceBlocking(tCtx, nil)- }-- if err := navigatePage(tCtx, req.URL); err != nil {- jsonErr(w, 500, fmt.Errorf("navigate: %w", err))- return- }-- b.DeleteRefCache(resolvedTabID)-- var url string- _ = chromedp.Run(tCtx, chromedp.Location(&url))- title := waitForTitle(tCtx, titleWait)-- jsonResp(w, 200, map[string]any{"url": url, "title": title})-}--func (b *Bridge) handleEvaluate(w http.ResponseWriter, r *http.Request) {- var req struct {- TabID string `json:"tabId"`- Expression string `json:"expression"`- }- if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {- jsonErr(w, 400, fmt.Errorf("decode: %w", err))- return- }- if req.Expression == "" {- jsonErr(w, 400, fmt.Errorf("expression required"))- return- }-- ctx, _, err := b.TabContext(req.TabID)- if err != nil {- jsonErr(w, 404, err)- return- }-- tCtx, tCancel := context.WithTimeout(ctx, actionTimeout)- defer tCancel()- go cancelOnClientDone(r.Context(), tCancel)-- var result any- if err := chromedp.Run(tCtx, chromedp.Evaluate(req.Expression, &result)); err != nil {- jsonErr(w, 500, fmt.Errorf("evaluate: %w", err))- return- }-- jsonResp(w, 200, map[string]any{"result": result})-}--func (b *Bridge) handleTab(w http.ResponseWriter, r *http.Request) {- var req struct {- Action string `json:"action"`- TabID string `json:"tabId"`- URL string `json:"url"`- }- if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {- jsonErr(w, 400, fmt.Errorf("decode: %w", err))- return- }-- switch req.Action {- case tabActionNew:- newTargetID, ctx, _, err := b.CreateTab(req.URL)- if err != nil {- jsonErr(w, 500, err)- return- }-- var curURL, title string- _ = chromedp.Run(ctx, chromedp.Location(&curURL), chromedp.Title(&title))- jsonResp(w, 200, map[string]any{"tabId": newTargetID, "url": curURL, "title": title})-- case tabActionClose:- if req.TabID == "" {- jsonErr(w, 400, fmt.Errorf("tabId required"))- return- }-- if err := b.CloseTab(req.TabID); err != nil {- jsonErr(w, 500, err)- return- }- jsonResp(w, 200, map[string]any{"closed": true})-- default:- jsonErr(w, 400, fmt.Errorf("action must be 'new' or 'close'"))- }-}--func (b *Bridge) handleTabLock(w http.ResponseWriter, r *http.Request) {- var req struct {- TabID string `json:"tabId"`- Owner string `json:"owner"`- TimeoutSec int `json:"timeoutSec"`- }- if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {- jsonErr(w, 400, fmt.Errorf("decode: %w", err))- return- }- if req.TabID == "" || req.Owner == "" {- jsonErr(w, 400, fmt.Errorf("tabId and owner required"))- return- }-- timeout := defaultLockTimeout- if req.TimeoutSec > 0 {- timeout = time.Duration(req.TimeoutSec) * time.Second- }-- if err := b.locks.Lock(req.TabID, req.Owner, timeout); err != nil {- jsonErr(w, 409, err)- return- }-- lock := b.locks.Get(req.TabID)- jsonResp(w, 200, map[string]any{- "locked": true,- "owner": lock.Owner,- "expiresAt": lock.ExpiresAt.Format(time.RFC3339),- })-}--func (b *Bridge) handleTabUnlock(w http.ResponseWriter, r *http.Request) {- var req struct {- TabID string `json:"tabId"`- Owner string `json:"owner"`- }- if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {- jsonErr(w, 400, fmt.Errorf("decode: %w", err))- return- }- if req.TabID == "" || req.Owner == "" {- jsonErr(w, 400, fmt.Errorf("tabId and owner required"))- return- }-- if err := b.locks.Unlock(req.TabID, req.Owner); err != nil {- jsonErr(w, 409, err)- return- }-- jsonResp(w, 200, map[string]any{"unlocked": true})-}--func (b *Bridge) handleShutdown(shutdownFn func()) func(http.ResponseWriter, *http.Request) {- return func(w http.ResponseWriter, r *http.Request) {- slog.Info("shutdown requested via API")- jsonResp(w, 200, map[string]any{"status": "shutting down"})-- go func() {- time.Sleep(100 * time.Millisecond)- shutdownFn()- }()- }-}diff --git a/integration_test.go b/integration_test.goindex f8b30f95..2196a269 100644--- a/integration_test.go+++ b/integration_test.go@@ -33,7 +33,7 @@ func testBridge(t *testing.T) (*Bridge, func()) {browserCtx, browserCancel := chromedp.NewContext(allocCtx)seed := rand.Intn(1000000000)- seededScript := fmt.Sprintf("var __pinchtab_seed = %d;\n", seed) + stealthScript+ seededScript := fmt.Sprintf("var __pinchtab_seed = %d;\nvar __pinchtab_stealth_level = %q;\n", seed, "full") + stealthScriptif err := chromedp.Run(browserCtx,chromedp.ActionFunc(func(ctx context.Context) error {_, err := page.AddScriptToEvaluateOnNewDocument(seededScript).Do(ctx)diff --git a/interfaces.go b/interfaces.goindex 9ff3d7fd..667699d0 100644--- a/interfaces.go+++ b/interfaces.go@@ -1,6 +1,4 @@-package // BridgeAPI is the interface handlers use to interact with Chrome.-// TabInfo is a simplified tab descriptor for JSON responses.-main+package mainimport ("context"diff --git a/lock.go b/lock.goindex 12eb0a06..8ba0dd00 100644--- a/lock.go+++ b/lock.go@@ -1,9 +1,4 @@-package // TabLock represents an active lock held by an agent on a tab.-// Lock acquires a lock on a tab for the given owner.-// Unlock releases a lock.-// Get returns the lock info for a tab, or nil if unlocked/expired.-// CheckAccess returns an error if the tab is locked by someone other than owner.-main+package mainimport ("fmt"diff --git a/orchestrator_handlers.go b/orchestrator_handlers.gonew file mode 100644index 00000000..16c78eee--- /dev/null+++ b/orchestrator_handlers.go@@ -0,0 +1,88 @@+package main++import (+ "encoding/json"+ "fmt"+ "net/http"+)++func (o *Orchestrator) RegisterHandlers(mux *http.ServeMux) {+ mux.HandleFunc("GET /instances", o.handleList)+ mux.HandleFunc("POST /instances/launch", o.handleLaunch)+ mux.HandleFunc("POST /instances/{id}/stop", o.handleStop)+ mux.HandleFunc("GET /instances/{id}/logs", o.handleLogs)+ mux.HandleFunc("GET /instances/tabs", o.handleAllTabs)+ mux.HandleFunc("GET /instances/{id}/proxy/screencast", o.handleProxyScreencast)+}++func (o *Orchestrator) handleList(w http.ResponseWriter, r *http.Request) {+ jsonResp(w, 200, o.List())+}++func (o *Orchestrator) handleLaunch(w http.ResponseWriter, r *http.Request) {+ var req struct {+ Name string `json:"name"`+ Port string `json:"port"`+ Headless *bool `json:"headless"`+ }+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ jsonErr(w, 400, fmt.Errorf("invalid JSON"))+ return+ }+ if req.Name == "" || req.Port == "" {+ jsonErr(w, 400, fmt.Errorf("name and port required"))+ return+ }++ headless := true+ if req.Headless != nil {+ headless = *req.Headless+ }++ inst, err := o.Launch(req.Name, req.Port, headless)+ if err != nil {+ jsonErr(w, 409, err)+ return+ }+ jsonResp(w, 201, inst)+}++func (o *Orchestrator) handleStop(w http.ResponseWriter, r *http.Request) {+ id := r.PathValue("id")+ if err := o.Stop(id); err != nil {+ jsonErr(w, 404, err)+ return+ }+ jsonResp(w, 200, map[string]string{"status": "stopped", "id": id})+}++func (o *Orchestrator) handleLogs(w http.ResponseWriter, r *http.Request) {+ id := r.PathValue("id")+ logs, err := o.Logs(id)+ if err != nil {+ jsonErr(w, 404, err)+ return+ }+ w.Header().Set("Content-Type", "text/plain")+ w.Write([]byte(logs))+}++func (o *Orchestrator) handleAllTabs(w http.ResponseWriter, r *http.Request) {+ jsonResp(w, 200, o.AllTabs())+}++func (o *Orchestrator) handleProxyScreencast(w http.ResponseWriter, r *http.Request) {+ id := r.PathValue("id")+ tabID := r.URL.Query().Get("tabId")++ o.mu.RLock()+ inst, ok := o.instances[id]+ o.mu.RUnlock()+ if !ok || inst.Status != "running" {+ http.Error(w, "instance not found or not running", 404)+ return+ }++ targetURL := fmt.Sprintf("ws://localhost:%s/screencast?tabId=%s", inst.Port, tabID)+ jsonResp(w, 200, map[string]string{"wsUrl": targetURL})+}diff --git a/orchestrator.go b/orchestrator_runtime.gosimilarity index 50%rename from orchestrator.gorename to orchestrator_runtime.goindex a5fc6cb6..71085943 100644--- a/orchestrator.go+++ b/orchestrator_runtime.go@@ -1,121 +1,18 @@-package // Launch starts a new Pinchtab instance on a named profile.-// Stop kills a running instance.-// List returns all instances with live status.-// Logs returns the log buffer for an instance.-// AllTabs aggregates tabs from all running instances.-// ProxyScreencastURL returns the WebSocket URL for a child instance's screencast.-main+package mainimport ("context""encoding/json""fmt"- "io""log/slog""net/http""os""os/exec""path/filepath"- "sync""syscall""time")-type Orchestrator struct {- instances map[string]*Instance- baseDir string- binary string- mu sync.RWMutex- client *http.Client-}--type Instance struct {- ID string `json:"id"`- Name string `json:"name"`- Profile string `json:"profile"`- Port string `json:"port"`- Headless bool `json:"headless"`- Status string `json:"status"`- PID int `json:"pid,omitempty"`- StartedAt time.Time `json:"startedAt"`- Error string `json:"error,omitempty"`- TabCount int `json:"tabCount"`- URL string `json:"url"`-- cmd *exec.Cmd- cancel context.CancelFunc- logBuf *ringBuffer-}--type ringBuffer struct {- mu sync.Mutex- data []byte- max int-}--func newRingBuffer(max int) *ringBuffer {- return &ringBuffer{max: max, data: make([]byte, 0, max)}-}--func (rb *ringBuffer) Write(p []byte) (int, error) {- rb.mu.Lock()- defer rb.mu.Unlock()- rb.data = append(rb.data, p...)- if len(rb.data) > rb.max {- rb.data = rb.data[len(rb.data)-rb.max:]- }- return len(p), nil-}--func (rb *ringBuffer) String() string {- rb.mu.Lock()- defer rb.mu.Unlock()- return string(rb.data)-}--func NewOrchestrator(baseDir string) *Orchestrator {-- binDir := filepath.Join(filepath.Dir(baseDir), "bin")- stableBin := filepath.Join(binDir, "pinchtab")-- needsBuild := true- if fi, err := os.Stat(stableBin); err == nil {-- if time.Since(fi.ModTime()) < time.Hour {- needsBuild = false- }- }-- if needsBuild {- os.MkdirAll(binDir, 0755)-- exe, _ := os.Executable()- if exe != "" {- if data, err := os.ReadFile(exe); err == nil {- if err := os.WriteFile(stableBin, data, 0755); err == nil {- slog.Info("installed pinchtab binary", "path", stableBin)- }- }- }- }-- binary := stableBin- if _, err := os.Stat(binary); err != nil {-- binary, _ = os.Executable()- if binary == "" {- binary = os.Args[0]- }- }-- return &Orchestrator{- instances: make(map[string]*Instance),- baseDir: baseDir,- binary: binary,- client: &http.Client{Timeout: 3 * time.Second},- }-}-func (o *Orchestrator) Launch(name, port string, headless bool) (*Instance, error) {o.mu.Lock()defer o.mu.Unlock()@@ -147,10 +44,8 @@ func (o *Orchestrator) Launch(name, port string, headless bool) (*Instance, erro"BRIDGE_PROFILE="+profilePath,"BRIDGE_HEADLESS="+headlessStr,"BRIDGE_NO_RESTORE=true",-"BRIDGE_NO_DASHBOARD=true",)-cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}logBuf := newRingBuffer(64 * 1024)@@ -185,7 +80,6 @@ func (o *Orchestrator) Launch(name, port string, headless bool) (*Instance, erro}func (o *Orchestrator) monitor(inst *Instance) {-healthy := falsefor i := 0; i < 30; i++ {time.Sleep(500 * time.Millisecond)@@ -236,7 +130,6 @@ func (o *Orchestrator) Stop(id string) error {resp, err := o.client.Do(req)if err == nil {resp.Body.Close()-time.Sleep(2 * time.Second)}@@ -254,18 +147,18 @@ func (o *Orchestrator) List() []Instance {result := make([]Instance, 0, len(o.instances))for _, inst := range o.instances {- copy := *inst- copy.cmd = nil- copy.cancel = nil- copy.logBuf = nil+ copyInst := *inst+ copyInst.cmd = nil+ copyInst.cancel = nil+ copyInst.logBuf = nilif inst.Status == "running" {if tabs, err := o.fetchTabs(inst.URL); err == nil {- copy.TabCount = len(tabs)+ copyInst.TabCount = len(tabs)}}- result = append(result, copy)+ result = append(result, copyInst)}return result}@@ -297,13 +190,13 @@ func (o *Orchestrator) AllTabs() []instanceTab {if err != nil {continue}- for _, t := range tabs {+ for _, tab := range tabs {all = append(all, instanceTab{InstanceID: inst.ID,InstanceName: inst.Name,InstancePort: inst.Port,- TabID: t.ID,- URL: t.URL,+ TabID: tab.ID,+ URL: tab.URL,})}}@@ -329,89 +222,12 @@ func (o *Orchestrator) fetchTabs(baseURL string) ([]remoteTab, error) {return nil, err}defer resp.Body.Close()- var tabs []remoteTab- json.NewDecoder(resp.Body).Decode(&tabs)- return tabs, nil-}--func (o *Orchestrator) RegisterHandlers(mux *http.ServeMux) {- mux.HandleFunc("GET /instances", o.handleList)- mux.HandleFunc("POST /instances/launch", o.handleLaunch)- mux.HandleFunc("POST /instances/{id}/stop", o.handleStop)- mux.HandleFunc("GET /instances/{id}/logs", o.handleLogs)- mux.HandleFunc("GET /instances/tabs", o.handleAllTabs)- mux.HandleFunc("GET /instances/{id}/proxy/screencast", o.handleProxyScreencast)-}--func (o *Orchestrator) handleList(w http.ResponseWriter, r *http.Request) {- jsonResp(w, 200, o.List())-}--func (o *Orchestrator) handleLaunch(w http.ResponseWriter, r *http.Request) {- var req struct {- Name string `json:"name"`- Port string `json:"port"`- Headless *bool `json:"headless"`- }- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {- jsonErr(w, 400, fmt.Errorf("invalid JSON"))- return- }- if req.Name == "" || req.Port == "" {- jsonErr(w, 400, fmt.Errorf("name and port required"))- return- }- headless := true- if req.Headless != nil {- headless = *req.Headless- }- inst, err := o.Launch(req.Name, req.Port, headless)- if err != nil {- jsonErr(w, 409, err)- return- }- jsonResp(w, 201, inst)-}--func (o *Orchestrator) handleStop(w http.ResponseWriter, r *http.Request) {- id := r.PathValue("id")- if err := o.Stop(id); err != nil {- jsonErr(w, 404, err)- return- }- jsonResp(w, 200, map[string]string{"status": "stopped", "id": id})-}--func (o *Orchestrator) handleLogs(w http.ResponseWriter, r *http.Request) {- id := r.PathValue("id")- logs, err := o.Logs(id)- if err != nil {- jsonErr(w, 404, err)- return- }- w.Header().Set("Content-Type", "text/plain")- w.Write([]byte(logs))-}--func (o *Orchestrator) handleAllTabs(w http.ResponseWriter, r *http.Request) {- jsonResp(w, 200, o.AllTabs())-}--func (o *Orchestrator) handleProxyScreencast(w http.ResponseWriter, r *http.Request) {- id := r.PathValue("id")- tabID := r.URL.Query().Get("tabId")-- o.mu.RLock()- inst, ok := o.instances[id]- o.mu.RUnlock()- if !ok || inst.Status != "running" {- http.Error(w, "instance not found or not running", 404)- return+ var tabs []remoteTab+ if err := json.NewDecoder(resp.Body).Decode(&tabs); err != nil {+ return nil, err}-- targetURL := fmt.Sprintf("ws://localhost:%s/screencast?tabId=%s", inst.Port, tabID)- jsonResp(w, 200, map[string]string{"wsUrl": targetURL})+ return tabs, nil}func (o *Orchestrator) ScreencastURL(instanceID, tabID string) string {@@ -439,7 +255,3 @@ func (o *Orchestrator) Shutdown() {o.Stop(id)}}--func readAll(r io.Reader, limit int64) ([]byte, error) {- return io.ReadAll(io.LimitReader(r, limit))-}diff --git a/orchestrator_types.go b/orchestrator_types.gonew file mode 100644index 00000000..ec1451d4--- /dev/null+++ b/orchestrator_types.go@@ -0,0 +1,104 @@+package main++import (+ "context"+ "log/slog"+ "net/http"+ "os"+ "os/exec"+ "path/filepath"+ "sync"+ "time"+)++type Orchestrator struct {+ instances map[string]*Instance+ baseDir string+ binary string+ mu sync.RWMutex+ client *http.Client+}++type Instance struct {+ ID string `json:"id"`+ Name string `json:"name"`+ Profile string `json:"profile"`+ Port string `json:"port"`+ Headless bool `json:"headless"`+ Status string `json:"status"`+ PID int `json:"pid,omitempty"`+ StartedAt time.Time `json:"startedAt"`+ Error string `json:"error,omitempty"`+ TabCount int `json:"tabCount"`+ URL string `json:"url"`++ cmd *exec.Cmd+ cancel context.CancelFunc+ logBuf *ringBuffer+}++type ringBuffer struct {+ mu sync.Mutex+ data []byte+ max int+}++func newRingBuffer(max int) *ringBuffer {+ return &ringBuffer{max: max, data: make([]byte, 0, max)}+}++func (rb *ringBuffer) Write(p []byte) (int, error) {+ rb.mu.Lock()+ defer rb.mu.Unlock()+ rb.data = append(rb.data, p...)+ if len(rb.data) > rb.max {+ rb.data = rb.data[len(rb.data)-rb.max:]+ }+ return len(p), nil+}++func (rb *ringBuffer) String() string {+ rb.mu.Lock()+ defer rb.mu.Unlock()+ return string(rb.data)+}++func NewOrchestrator(baseDir string) *Orchestrator {+ binDir := filepath.Join(filepath.Dir(baseDir), "bin")+ stableBin := filepath.Join(binDir, "pinchtab")++ needsBuild := true+ if fi, err := os.Stat(stableBin); err == nil {+ if time.Since(fi.ModTime()) < time.Hour {+ needsBuild = false+ }+ }++ if needsBuild {+ os.MkdirAll(binDir, 0755)++ exe, _ := os.Executable()+ if exe != "" {+ if data, err := os.ReadFile(exe); err == nil {+ if err := os.WriteFile(stableBin, data, 0755); err == nil {+ slog.Info("installed pinchtab binary", "path", stableBin)+ }+ }+ }+ }++ binary := stableBin+ if _, err := os.Stat(binary); err != nil {+ binary, _ = os.Executable()+ if binary == "" {+ binary = os.Args[0]+ }+ }++ return &Orchestrator{+ instances: make(map[string]*Instance),+ baseDir: baseDir,+ binary: binary,+ client: &http.Client{Timeout: 3 * time.Second},+ }+}diff --git a/profiles.go b/profiles.godeleted file mode 100644index 9e1825f7..00000000--- a/profiles.go+++ /dev/null@@ -1,515 +0,0 @@-package // List returns all managed profiles.-// Import copies an existing Chrome user data directory as a named profile.-// Create makes a fresh empty profile directory.-// Reset clears session data and caches but preserves bookmarks, extensions, passwords.-// Delete removes a profile entirely.-// Logs returns recent Chrome/Pinchtab logs for a profile.-// Analytics returns action patterns and optimization suggestions.-// TrackingMiddleware returns middleware that records actions per profile.-main--import (- "encoding/json"- "fmt"- "io/fs"- "log/slog"- "net/http"- "os"- "path/filepath"- "sort"- "strings"- "sync"- "time"-- "os/exec"-)--type ProfileManager struct {- baseDir string- tracker *ActionTracker- mu sync.RWMutex-}--type ProfileInfo struct {- Name string `json:"name"`- Path string `json:"path"`- CreatedAt time.Time `json:"createdAt"`- SizeMB float64 `json:"sizeMB"`- Source string `json:"source,omitempty"`-}--func NewProfileManager(baseDir string) *ProfileManager {- os.MkdirAll(baseDir, 0755)- return &ProfileManager{- baseDir: baseDir,- tracker: NewActionTracker(),- }-}--func (pm *ProfileManager) List() ([]ProfileInfo, error) {- pm.mu.RLock()- defer pm.mu.RUnlock()-- entries, err := os.ReadDir(pm.baseDir)- if err != nil {- return nil, err- }-- var profiles []ProfileInfo-- skip := map[string]bool{"bin": true, "profiles": true}- for _, e := range entries {- if !e.IsDir() || skip[e.Name()] {- continue- }- info, err := pm.profileInfo(e.Name())- if err != nil {- continue- }-- if _, err := os.Stat(filepath.Join(pm.baseDir, e.Name(), "Default")); err != nil {- continue- }- profiles = append(profiles, info)- }- sort.Slice(profiles, func(i, j int) bool { return profiles[i].Name < profiles[j].Name })- return profiles, nil-}--func (pm *ProfileManager) profileInfo(name string) (ProfileInfo, error) {- dir := filepath.Join(pm.baseDir, name)- fi, err := os.Stat(dir)- if err != nil {- return ProfileInfo{}, err- }-- size := dirSizeMB(dir)- source := "created"- if _, err := os.Stat(filepath.Join(dir, ".pinchtab-imported")); err == nil {- source = "imported"- }-- return ProfileInfo{- Name: name,- Path: dir,- CreatedAt: fi.ModTime(),- SizeMB: size,- Source: source,- }, nil-}--func (pm *ProfileManager) Import(name, sourcePath string) error {- pm.mu.Lock()- defer pm.mu.Unlock()-- dest := filepath.Join(pm.baseDir, name)- if _, err := os.Stat(dest); err == nil {- return fmt.Errorf("profile %q already exists", name)- }-- if _, err := os.Stat(filepath.Join(sourcePath, "Default")); err != nil {-- if _, err2 := os.Stat(filepath.Join(sourcePath, "Preferences")); err2 != nil {- return fmt.Errorf("source doesn't look like a Chrome user data dir (no Default/ or Preferences found)")- }- }-- slog.Info("importing profile", "name", name, "source", sourcePath)- if err := exec.Command("cp", "-a", sourcePath, dest).Run(); err != nil {- return fmt.Errorf("copy failed: %w", err)- }-- os.WriteFile(filepath.Join(dest, ".pinchtab-imported"), []byte(sourcePath), 0644)- return nil-}--func (pm *ProfileManager) Create(name string) error {- pm.mu.Lock()- defer pm.mu.Unlock()-- dest := filepath.Join(pm.baseDir, name)- if _, err := os.Stat(dest); err == nil {- return fmt.Errorf("profile %q already exists", name)- }- return os.MkdirAll(filepath.Join(dest, "Default"), 0755)-}--func (pm *ProfileManager) Reset(name string) error {- pm.mu.Lock()- defer pm.mu.Unlock()-- dir := filepath.Join(pm.baseDir, name)- if _, err := os.Stat(dir); os.IsNotExist(err) {- return fmt.Errorf("profile %q not found", name)- }-- nukeDirs := []string{- "Default/Sessions",- "Default/Session Storage",- "Default/Cache",- "Default/Code Cache",- "Default/GPUCache",- "Default/Service Worker",- "Default/blob_storage",- "ShaderCache",- "GrShaderCache",- }-- nukeFiles := []string{- "Default/Cookies",- "Default/Cookies-journal",- "Default/History",- "Default/History-journal",- "Default/Visited Links",- }-- for _, d := range nukeDirs {- p := filepath.Join(dir, d)- if err := os.RemoveAll(p); err != nil {- slog.Warn("reset: failed to remove dir", "path", p, "err", err)- }- }- for _, f := range nukeFiles {- p := filepath.Join(dir, f)- os.Remove(p)- }-- slog.Info("profile reset", "name", name)- return nil-}--func (pm *ProfileManager) Delete(name string) error {- pm.mu.Lock()- defer pm.mu.Unlock()-- dir := filepath.Join(pm.baseDir, name)- if _, err := os.Stat(dir); os.IsNotExist(err) {- return fmt.Errorf("profile %q not found", name)- }- return os.RemoveAll(dir)-}--func (pm *ProfileManager) Logs(name string, limit int) []ActionRecord {- return pm.tracker.GetLogs(name, limit)-}--func (pm *ProfileManager) Analytics(name string) AnalyticsReport {- return pm.tracker.Analyze(name)-}--type ActionTracker struct {- mu sync.Mutex- records map[string][]ActionRecord-}--type ActionRecord struct {- Timestamp time.Time `json:"timestamp"`- Method string `json:"method"`- Endpoint string `json:"endpoint"`- URL string `json:"url,omitempty"`- TabID string `json:"tabId,omitempty"`- DurationMs int64 `json:"durationMs"`- Status int `json:"status"`-}--type AnalyticsReport struct {- TotalActions int `json:"totalActions"`- Since time.Time `json:"since"`- TopEndpoints []EndpointCount `json:"topEndpoints"`- RepeatPatterns []RepeatPattern `json:"repeatPatterns"`- Suggestions []string `json:"suggestions"`-}--type EndpointCount struct {- Endpoint string `json:"endpoint"`- Count int `json:"count"`- AvgMs int64 `json:"avgMs"`-}--type RepeatPattern struct {- Pattern string `json:"pattern"`- Count int `json:"count"`- AvgGapSec float64 `json:"avgGapSec"`-}--func NewActionTracker() *ActionTracker {- return &ActionTracker{- records: make(map[string][]ActionRecord),- }-}--func (at *ActionTracker) Record(profile string, rec ActionRecord) {- at.mu.Lock()- defer at.mu.Unlock()-- recs := at.records[profile]- recs = append(recs, rec)-- if len(recs) > 10000 {- recs = recs[len(recs)-10000:]- }- at.records[profile] = recs-}--func (at *ActionTracker) GetLogs(profile string, limit int) []ActionRecord {- at.mu.Lock()- defer at.mu.Unlock()-- recs := at.records[profile]- if limit <= 0 || limit > len(recs) {- limit = len(recs)- }-- start := len(recs) - limit- result := make([]ActionRecord, limit)- copy(result, recs[start:])- return result-}--func (at *ActionTracker) Analyze(profile string) AnalyticsReport {- at.mu.Lock()- defer at.mu.Unlock()-- recs := at.records[profile]- if len(recs) == 0 {- return AnalyticsReport{Suggestions: []string{"No actions recorded yet."}}- }-- report := AnalyticsReport{- TotalActions: len(recs),- Since: recs[0].Timestamp,- }-- epCounts := map[string]struct {- count int- totalMs int64- }{}- for _, r := range recs {- v := epCounts[r.Endpoint]- v.count++- v.totalMs += r.DurationMs- epCounts[r.Endpoint] = v- }- for ep, v := range epCounts {- report.TopEndpoints = append(report.TopEndpoints, EndpointCount{- Endpoint: ep,- Count: v.count,- AvgMs: v.totalMs / int64(v.count),- })- }- sort.Slice(report.TopEndpoints, func(i, j int) bool {- return report.TopEndpoints[i].Count > report.TopEndpoints[j].Count- })- if len(report.TopEndpoints) > 10 {- report.TopEndpoints = report.TopEndpoints[:10]- }-- urlSnaps := map[string][]time.Time{}- for _, r := range recs {- if r.Endpoint == "/snapshot" && r.URL != "" {- urlSnaps[r.URL] = append(urlSnaps[r.URL], r.Timestamp)- }- }- for url, times := range urlSnaps {- if len(times) < 3 {- continue- }- var totalGap float64- for i := 1; i < len(times); i++ {- totalGap += times[i].Sub(times[i-1]).Seconds()- }- avgGap := totalGap / float64(len(times)-1)- report.RepeatPatterns = append(report.RepeatPatterns, RepeatPattern{- Pattern: fmt.Sprintf("snapshot %s", truncURL(url)),- Count: len(times),- AvgGapSec: avgGap,- })- }-- navSnap := map[string]int{}- for i := 1; i < len(recs); i++ {- if recs[i-1].Endpoint == "/navigate" && recs[i].Endpoint == "/snapshot" {- key := truncURL(recs[i-1].URL)- navSnap[key]++- }- }- for url, count := range navSnap {- if count >= 3 {- report.RepeatPatterns = append(report.RepeatPatterns, RepeatPattern{- Pattern: fmt.Sprintf("navigate→snapshot %s", url),- Count: count,- })- }- }-- for _, rp := range report.RepeatPatterns {- if strings.HasPrefix(rp.Pattern, "snapshot") && rp.AvgGapSec > 0 && rp.AvgGapSec < 10 {- report.Suggestions = append(report.Suggestions,- fmt.Sprintf("High-frequency polling detected: %s every %.0fs — consider increasing interval or using smart diff", rp.Pattern, rp.AvgGapSec))- }- if strings.HasPrefix(rp.Pattern, "navigate→snapshot") && rp.Count > 5 {- report.Suggestions = append(report.Suggestions,- fmt.Sprintf("Repeated navigate→snapshot for same URL %s (%dx) — consider caching or using /text for lighter reads", rp.Pattern, rp.Count))- }- }-- snapCount := 0- for _, r := range recs {- if r.Endpoint == "/snapshot" {- snapCount++- }- }- if snapCount > 20 {- report.Suggestions = append(report.Suggestions,- fmt.Sprintf("Heavy snapshot usage (%d calls) — use ?selector= or ?maxTokens= to reduce token cost", snapCount))- }-- if len(report.Suggestions) == 0 {- report.Suggestions = []string{"No optimization suggestions — usage looks efficient."}- }-- return report-}--func (pm *ProfileManager) RegisterHandlers(mux *http.ServeMux) {- mux.HandleFunc("GET /profiles", pm.handleList)- mux.HandleFunc("POST /profiles/import", pm.handleImport)- mux.HandleFunc("POST /profiles/create", pm.handleCreate)- mux.HandleFunc("POST /profiles/{name}/reset", pm.handleReset)- mux.HandleFunc("DELETE /profiles/{name}", pm.handleDelete)- mux.HandleFunc("GET /profiles/{name}/logs", pm.handleLogs)- mux.HandleFunc("GET /profiles/{name}/analytics", pm.handleAnalytics)-}--func (pm *ProfileManager) handleList(w http.ResponseWriter, r *http.Request) {- profiles, err := pm.List()- if err != nil {- jsonErr(w, http.StatusInternalServerError, err)- return- }- jsonResp(w, http.StatusOK, profiles)-}--func (pm *ProfileManager) handleImport(w http.ResponseWriter, r *http.Request) {- var req struct {- Name string `json:"name"`- Source string `json:"source"`- }- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {- jsonErr(w, http.StatusBadRequest, fmt.Errorf("invalid JSON"))- return- }- if req.Name == "" || req.Source == "" {- jsonErr(w, http.StatusBadRequest, fmt.Errorf("name and source required"))- return- }- if err := pm.Import(req.Name, req.Source); err != nil {- jsonErr(w, http.StatusConflict, err)- return- }- jsonResp(w, http.StatusCreated, map[string]string{"status": "imported", "name": req.Name})-}--func (pm *ProfileManager) handleCreate(w http.ResponseWriter, r *http.Request) {- var req struct {- Name string `json:"name"`- }- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {- jsonErr(w, http.StatusBadRequest, fmt.Errorf("invalid JSON"))- return- }- if req.Name == "" {- jsonErr(w, http.StatusBadRequest, fmt.Errorf("name required"))- return- }- if err := pm.Create(req.Name); err != nil {- jsonErr(w, http.StatusConflict, err)- return- }- jsonResp(w, http.StatusCreated, map[string]string{"status": "created", "name": req.Name})-}--func (pm *ProfileManager) handleReset(w http.ResponseWriter, r *http.Request) {- name := r.PathValue("name")- if err := pm.Reset(name); err != nil {- jsonErr(w, http.StatusNotFound, err)- return- }- jsonResp(w, http.StatusOK, map[string]string{"status": "reset", "name": name})-}--func (pm *ProfileManager) handleDelete(w http.ResponseWriter, r *http.Request) {- name := r.PathValue("name")- if err := pm.Delete(name); err != nil {- jsonErr(w, http.StatusNotFound, err)- return- }- jsonResp(w, http.StatusOK, map[string]string{"status": "deleted", "name": name})-}--func (pm *ProfileManager) handleLogs(w http.ResponseWriter, r *http.Request) {- name := r.PathValue("name")- limit := profileQueryInt(r, "limit", 100)- logs := pm.Logs(name, limit)- jsonResp(w, http.StatusOK, logs)-}--func (pm *ProfileManager) handleAnalytics(w http.ResponseWriter, r *http.Request) {- name := r.PathValue("name")- report := pm.Analytics(name)- jsonResp(w, http.StatusOK, report)-}--func (pm *ProfileManager) TrackingMiddleware(profileName string, next http.Handler) http.Handler {- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- start := time.Now()- sw := &statusWriter{ResponseWriter: w, code: 200}- next.ServeHTTP(sw, r)-- rec := ActionRecord{- Timestamp: start,- Method: r.Method,- Endpoint: r.URL.Path,- URL: r.URL.Query().Get("url"),- TabID: r.URL.Query().Get("tabId"),- DurationMs: time.Since(start).Milliseconds(),- Status: sw.code,- }- pm.tracker.Record(profileName, rec)- })-}--func profileQueryInt(r *http.Request, key string, def int) int {- s := r.URL.Query().Get(key)- if s == "" {- return def- }- var n int- fmt.Sscanf(s, "%d", &n)- if n <= 0 {- return def- }- return n-}--func dirSizeMB(path string) float64 {- var total int64- filepath.WalkDir(path, func(_ string, d fs.DirEntry, err error) error {- if err != nil || d.IsDir() {- return nil- }- info, err := d.Info()- if err == nil {- total += info.Size()- }- return nil- })- return float64(total) / (1024 * 1024)-}--func truncURL(u string) string {- if len(u) > 60 {- return u[:57] + "..."- }- return u-}diff --git a/profiles_handlers.go b/profiles_handlers.gonew file mode 100644index 00000000..8882fadb--- /dev/null+++ b/profiles_handlers.go@@ -0,0 +1,129 @@+package main++import (+ "encoding/json"+ "fmt"+ "net/http"+ "time"+)++func (pm *ProfileManager) RegisterHandlers(mux *http.ServeMux) {+ mux.HandleFunc("GET /profiles", pm.handleList)+ mux.HandleFunc("POST /profiles/import", pm.handleImport)+ mux.HandleFunc("POST /profiles/create", pm.handleCreate)+ mux.HandleFunc("POST /profiles/{name}/reset", pm.handleReset)+ mux.HandleFunc("DELETE /profiles/{name}", pm.handleDelete)+ mux.HandleFunc("GET /profiles/{name}/logs", pm.handleLogs)+ mux.HandleFunc("GET /profiles/{name}/analytics", pm.handleAnalytics)+}++func (pm *ProfileManager) handleList(w http.ResponseWriter, r *http.Request) {+ profiles, err := pm.List()+ if err != nil {+ jsonErr(w, http.StatusInternalServerError, err)+ return+ }+ jsonResp(w, http.StatusOK, profiles)+}++func (pm *ProfileManager) handleImport(w http.ResponseWriter, r *http.Request) {+ var req struct {+ Name string `json:"name"`+ Source string `json:"source"`+ }+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ jsonErr(w, http.StatusBadRequest, fmt.Errorf("invalid JSON"))+ return+ }+ if req.Name == "" || req.Source == "" {+ jsonErr(w, http.StatusBadRequest, fmt.Errorf("name and source required"))+ return+ }+ if err := pm.Import(req.Name, req.Source); err != nil {+ jsonErr(w, http.StatusConflict, err)+ return+ }+ jsonResp(w, http.StatusCreated, map[string]string{"status": "imported", "name": req.Name})+}++func (pm *ProfileManager) handleCreate(w http.ResponseWriter, r *http.Request) {+ var req struct {+ Name string `json:"name"`+ }+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ jsonErr(w, http.StatusBadRequest, fmt.Errorf("invalid JSON"))+ return+ }+ if req.Name == "" {+ jsonErr(w, http.StatusBadRequest, fmt.Errorf("name required"))+ return+ }+ if err := pm.Create(req.Name); err != nil {+ jsonErr(w, http.StatusConflict, err)+ return+ }+ jsonResp(w, http.StatusCreated, map[string]string{"status": "created", "name": req.Name})+}++func (pm *ProfileManager) handleReset(w http.ResponseWriter, r *http.Request) {+ name := r.PathValue("name")+ if err := pm.Reset(name); err != nil {+ jsonErr(w, http.StatusNotFound, err)+ return+ }+ jsonResp(w, http.StatusOK, map[string]string{"status": "reset", "name": name})+}++func (pm *ProfileManager) handleDelete(w http.ResponseWriter, r *http.Request) {+ name := r.PathValue("name")+ if err := pm.Delete(name); err != nil {+ jsonErr(w, http.StatusNotFound, err)+ return+ }+ jsonResp(w, http.StatusOK, map[string]string{"status": "deleted", "name": name})+}++func (pm *ProfileManager) handleLogs(w http.ResponseWriter, r *http.Request) {+ name := r.PathValue("name")+ limit := profileQueryInt(r, "limit", 100)+ logs := pm.Logs(name, limit)+ jsonResp(w, http.StatusOK, logs)+}++func (pm *ProfileManager) handleAnalytics(w http.ResponseWriter, r *http.Request) {+ name := r.PathValue("name")+ report := pm.Analytics(name)+ jsonResp(w, http.StatusOK, report)+}++func (pm *ProfileManager) TrackingMiddleware(profileName string, next http.Handler) http.Handler {+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ start := time.Now()+ sw := &statusWriter{ResponseWriter: w, code: 200}+ next.ServeHTTP(sw, r)++ rec := ActionRecord{+ Timestamp: start,+ Method: r.Method,+ Endpoint: r.URL.Path,+ URL: r.URL.Query().Get("url"),+ TabID: r.URL.Query().Get("tabId"),+ DurationMs: time.Since(start).Milliseconds(),+ Status: sw.code,+ }+ pm.tracker.Record(profileName, rec)+ })+}++func profileQueryInt(r *http.Request, key string, def int) int {+ s := r.URL.Query().Get(key)+ if s == "" {+ return def+ }+ var n int+ fmt.Sscanf(s, "%d", &n)+ if n <= 0 {+ return def+ }+ return n+}diff --git a/profiles_manager.go b/profiles_manager.gonew file mode 100644index 00000000..776c9708--- /dev/null+++ b/profiles_manager.go@@ -0,0 +1,198 @@+package main++import (+ "fmt"+ "io/fs"+ "log/slog"+ "os"+ "os/exec"+ "path/filepath"+ "sort"+ "sync"+ "time"+)++type ProfileManager struct {+ baseDir string+ tracker *ActionTracker+ mu sync.RWMutex+}++type ProfileInfo struct {+ Name string `json:"name"`+ Path string `json:"path"`+ CreatedAt time.Time `json:"createdAt"`+ SizeMB float64 `json:"sizeMB"`+ Source string `json:"source,omitempty"`+}++func NewProfileManager(baseDir string) *ProfileManager {+ os.MkdirAll(baseDir, 0755)+ return &ProfileManager{+ baseDir: baseDir,+ tracker: NewActionTracker(),+ }+}++func (pm *ProfileManager) List() ([]ProfileInfo, error) {+ pm.mu.RLock()+ defer pm.mu.RUnlock()++ entries, err := os.ReadDir(pm.baseDir)+ if err != nil {+ return nil, err+ }++ var profiles []ProfileInfo+ skip := map[string]bool{"bin": true, "profiles": true}+ for _, entry := range entries {+ if !entry.IsDir() || skip[entry.Name()] {+ continue+ }+ info, err := pm.profileInfo(entry.Name())+ if err != nil {+ continue+ }++ if _, err := os.Stat(filepath.Join(pm.baseDir, entry.Name(), "Default")); err != nil {+ continue+ }+ profiles = append(profiles, info)+ }+ sort.Slice(profiles, func(i, j int) bool { return profiles[i].Name < profiles[j].Name })+ return profiles, nil+}++func (pm *ProfileManager) profileInfo(name string) (ProfileInfo, error) {+ dir := filepath.Join(pm.baseDir, name)+ fi, err := os.Stat(dir)+ if err != nil {+ return ProfileInfo{}, err+ }++ size := dirSizeMB(dir)+ source := "created"+ if _, err := os.Stat(filepath.Join(dir, ".pinchtab-imported")); err == nil {+ source = "imported"+ }++ return ProfileInfo{+ Name: name,+ Path: dir,+ CreatedAt: fi.ModTime(),+ SizeMB: size,+ Source: source,+ }, nil+}++func (pm *ProfileManager) Import(name, sourcePath string) error {+ pm.mu.Lock()+ defer pm.mu.Unlock()++ dest := filepath.Join(pm.baseDir, name)+ if _, err := os.Stat(dest); err == nil {+ return fmt.Errorf("profile %q already exists", name)+ }++ if _, err := os.Stat(filepath.Join(sourcePath, "Default")); err != nil {+ if _, err2 := os.Stat(filepath.Join(sourcePath, "Preferences")); err2 != nil {+ return fmt.Errorf("source doesn't look like a Chrome user data dir (no Default/ or Preferences found)")+ }+ }++ slog.Info("importing profile", "name", name, "source", sourcePath)+ if err := exec.Command("cp", "-a", sourcePath, dest).Run(); err != nil {+ return fmt.Errorf("copy failed: %w", err)+ }++ os.WriteFile(filepath.Join(dest, ".pinchtab-imported"), []byte(sourcePath), 0644)+ return nil+}++func (pm *ProfileManager) Create(name string) error {+ pm.mu.Lock()+ defer pm.mu.Unlock()++ dest := filepath.Join(pm.baseDir, name)+ if _, err := os.Stat(dest); err == nil {+ return fmt.Errorf("profile %q already exists", name)+ }+ return os.MkdirAll(filepath.Join(dest, "Default"), 0755)+}++func (pm *ProfileManager) Reset(name string) error {+ pm.mu.Lock()+ defer pm.mu.Unlock()++ dir := filepath.Join(pm.baseDir, name)+ if _, err := os.Stat(dir); os.IsNotExist(err) {+ return fmt.Errorf("profile %q not found", name)+ }++ nukeDirs := []string{+ "Default/Sessions",+ "Default/Session Storage",+ "Default/Cache",+ "Default/Code Cache",+ "Default/GPUCache",+ "Default/Service Worker",+ "Default/blob_storage",+ "ShaderCache",+ "GrShaderCache",+ }++ nukeFiles := []string{+ "Default/Cookies",+ "Default/Cookies-journal",+ "Default/History",+ "Default/History-journal",+ "Default/Visited Links",+ }++ for _, d := range nukeDirs {+ path := filepath.Join(dir, d)+ if err := os.RemoveAll(path); err != nil {+ slog.Warn("reset: failed to remove dir", "path", path, "err", err)+ }+ }+ for _, f := range nukeFiles {+ os.Remove(filepath.Join(dir, f))+ }++ slog.Info("profile reset", "name", name)+ return nil+}++func (pm *ProfileManager) Delete(name string) error {+ pm.mu.Lock()+ defer pm.mu.Unlock()++ dir := filepath.Join(pm.baseDir, name)+ if _, err := os.Stat(dir); os.IsNotExist(err) {+ return fmt.Errorf("profile %q not found", name)+ }+ return os.RemoveAll(dir)+}++func (pm *ProfileManager) Logs(name string, limit int) []ActionRecord {+ return pm.tracker.GetLogs(name, limit)+}++func (pm *ProfileManager) Analytics(name string) AnalyticsReport {+ return pm.tracker.Analyze(name)+}++func dirSizeMB(path string) float64 {+ var total int64+ filepath.WalkDir(path, func(_ string, entry fs.DirEntry, err error) error {+ if err != nil || entry.IsDir() {+ return nil+ }+ info, err := entry.Info()+ if err == nil {+ total += info.Size()+ }+ return nil+ })+ return float64(total) / (1024 * 1024)+}diff --git a/profiles_tracker.go b/profiles_tracker.gonew file mode 100644index 00000000..a6cbe4a8--- /dev/null+++ b/profiles_tracker.go@@ -0,0 +1,187 @@+package main++import (+ "fmt"+ "sort"+ "strings"+ "sync"+ "time"+)++type ActionTracker struct {+ mu sync.Mutex+ records map[string][]ActionRecord+}++type ActionRecord struct {+ Timestamp time.Time `json:"timestamp"`+ Method string `json:"method"`+ Endpoint string `json:"endpoint"`+ URL string `json:"url,omitempty"`+ TabID string `json:"tabId,omitempty"`+ DurationMs int64 `json:"durationMs"`+ Status int `json:"status"`+}++type AnalyticsReport struct {+ TotalActions int `json:"totalActions"`+ Since time.Time `json:"since"`+ TopEndpoints []EndpointCount `json:"topEndpoints"`+ RepeatPatterns []RepeatPattern `json:"repeatPatterns"`+ Suggestions []string `json:"suggestions"`+}++type EndpointCount struct {+ Endpoint string `json:"endpoint"`+ Count int `json:"count"`+ AvgMs int64 `json:"avgMs"`+}++type RepeatPattern struct {+ Pattern string `json:"pattern"`+ Count int `json:"count"`+ AvgGapSec float64 `json:"avgGapSec"`+}++func NewActionTracker() *ActionTracker {+ return &ActionTracker{records: make(map[string][]ActionRecord)}+}++func (at *ActionTracker) Record(profile string, rec ActionRecord) {+ at.mu.Lock()+ defer at.mu.Unlock()++ recs := at.records[profile]+ recs = append(recs, rec)+ if len(recs) > 10000 {+ recs = recs[len(recs)-10000:]+ }+ at.records[profile] = recs+}++func (at *ActionTracker) GetLogs(profile string, limit int) []ActionRecord {+ at.mu.Lock()+ defer at.mu.Unlock()++ recs := at.records[profile]+ if limit <= 0 || limit > len(recs) {+ limit = len(recs)+ }++ start := len(recs) - limit+ result := make([]ActionRecord, limit)+ copy(result, recs[start:])+ return result+}++func (at *ActionTracker) Analyze(profile string) AnalyticsReport {+ at.mu.Lock()+ defer at.mu.Unlock()++ recs := at.records[profile]+ if len(recs) == 0 {+ return AnalyticsReport{Suggestions: []string{"No actions recorded yet."}}+ }++ report := AnalyticsReport{+ TotalActions: len(recs),+ Since: recs[0].Timestamp,+ }++ epCounts := map[string]struct {+ count int+ totalMs int64+ }{}+ for _, rec := range recs {+ entry := epCounts[rec.Endpoint]+ entry.count+++ entry.totalMs += rec.DurationMs+ epCounts[rec.Endpoint] = entry+ }+ for endpoint, entry := range epCounts {+ report.TopEndpoints = append(report.TopEndpoints, EndpointCount{+ Endpoint: endpoint,+ Count: entry.count,+ AvgMs: entry.totalMs / int64(entry.count),+ })+ }+ sort.Slice(report.TopEndpoints, func(i, j int) bool {+ return report.TopEndpoints[i].Count > report.TopEndpoints[j].Count+ })+ if len(report.TopEndpoints) > 10 {+ report.TopEndpoints = report.TopEndpoints[:10]+ }++ urlSnapshots := map[string][]time.Time{}+ for _, rec := range recs {+ if rec.Endpoint == "/snapshot" && rec.URL != "" {+ urlSnapshots[rec.URL] = append(urlSnapshots[rec.URL], rec.Timestamp)+ }+ }+ for url, times := range urlSnapshots {+ if len(times) < 3 {+ continue+ }+ var totalGap float64+ for i := 1; i < len(times); i++ {+ totalGap += times[i].Sub(times[i-1]).Seconds()+ }+ avgGap := totalGap / float64(len(times)-1)+ report.RepeatPatterns = append(report.RepeatPatterns, RepeatPattern{+ Pattern: fmt.Sprintf("snapshot %s", truncURL(url)),+ Count: len(times),+ AvgGapSec: avgGap,+ })+ }++ navPattern := map[string]int{}+ for i := 1; i < len(recs); i++ {+ if recs[i-1].Endpoint == "/navigate" && recs[i].Endpoint == "/snapshot" {+ key := truncURL(recs[i-1].URL)+ navPattern[key]+++ }+ }+ for url, count := range navPattern {+ if count >= 3 {+ report.RepeatPatterns = append(report.RepeatPatterns, RepeatPattern{+ Pattern: fmt.Sprintf("navigate→snapshot %s", url),+ Count: count,+ })+ }+ }++ for _, pattern := range report.RepeatPatterns {+ if strings.HasPrefix(pattern.Pattern, "snapshot") && pattern.AvgGapSec > 0 && pattern.AvgGapSec < 10 {+ report.Suggestions = append(report.Suggestions,+ fmt.Sprintf("High-frequency polling detected: %s every %.0fs — consider increasing interval or using smart diff", pattern.Pattern, pattern.AvgGapSec))+ }+ if strings.HasPrefix(pattern.Pattern, "navigate→snapshot") && pattern.Count > 5 {+ report.Suggestions = append(report.Suggestions,+ fmt.Sprintf("Repeated navigate→snapshot for same URL %s (%dx) — consider caching or using /text for lighter reads", pattern.Pattern, pattern.Count))+ }+ }++ snapCount := 0+ for _, rec := range recs {+ if rec.Endpoint == "/snapshot" {+ snapCount+++ }+ }+ if snapCount > 20 {+ report.Suggestions = append(report.Suggestions,+ fmt.Sprintf("Heavy snapshot usage (%d calls) — use ?selector= or ?maxTokens= to reduce token cost", snapCount))+ }++ if len(report.Suggestions) == 0 {+ report.Suggestions = []string{"No optimization suggestions — usage looks efficient."}+ }++ return report+}++func truncURL(u string) string {+ if len(u) > 60 {+ return u[:57] + "..."+ }+ return u+}diff --git a/snapshot.go b/snapshot.goindex 20aaeb49..c43915d7 100644--- a/snapshot.go+++ b/snapshot.go@@ -1,5 +1,4 @@-package // A11yNode is a flattened accessibility tree node returned by /snapshot.-main+package mainimport ("encoding/json"diff --git a/state.go b/state.goindex a89bdbc0..8edc129d 100644--- a/state.go+++ b/state.go@@ -1,8 +1,4 @@-package // TabState represents a saved tab for session persistence.-// SessionState is the on-disk format for saved sessions.-// SaveState writes all open tab URLs to sessions.-// RestoreState reopens tabs from the last saved session with concurrency limiting.-main+package mainimport ("context"diff --git a/stealth.js b/stealth.jsindex 5bad46aa..7c43ffe7 100644--- a/stealth.js+++ b/stealth.js@@ -146,6 +146,7 @@ if (window.RTCPeerConnection) {window.RTCPeerConnection.prototype = originalRTCPeerConnection.prototype;}+}const __pinchtab_origGetTimezoneOffset = Date.prototype.getTimezoneOffset;Object.defineProperty(Date.prototype, 'getTimezoneOffset', {