High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
Fix state surface and retained network body
Marioc0acbc396416
diff --git a/internal/bridge/network_test.go b/internal/bridge/network_test.goindex d3679775..c0c08c54 100644--- a/internal/bridge/network_test.go+++ b/internal/bridge/network_test.go@@ -143,6 +143,7 @@ func TestNetworkFilter_Match(t *testing.T) {{"status range match", NetworkFilter{StatusRange: "4xx"}, true},{"status range no match", NetworkFilter{StatusRange: "2xx"}, false},{"type match", NetworkFilter{ResourceType: "xhr"}, true},+ {"fetch matches xhr compatibility", NetworkFilter{ResourceType: "fetch"}, true},{"type no match", NetworkFilter{ResourceType: "document"}, false},{"combined match", NetworkFilter{Method: "POST", StatusRange: "4xx"}, true},{"combined partial no match", NetworkFilter{Method: "GET", StatusRange: "4xx"}, false},@@ -156,6 +157,14 @@ func TestNetworkFilter_Match(t *testing.T) {}})}++ entry.ResourceType = "Fetch"+ if !(NetworkFilter{ResourceType: "xhr"}).Match(entry) {+ t.Error("type=xhr should match fetch entries for compatibility")+ }+ if !(NetworkFilter{ResourceType: "fetch"}).Match(entry) {+ t.Error("type=fetch should match fetch entries")+ }}func TestNetworkBuffer_List_WithFilter(t *testing.T) {diff --git a/internal/bridge/observe/network.go b/internal/bridge/observe/network.goindex de2bae7b..34a4ec5e 100644--- a/internal/bridge/observe/network.go+++ b/internal/bridge/observe/network.go@@ -290,7 +290,7 @@ func (f NetworkFilter) Match(e NetworkEntry) bool {if f.Method != "" && !strings.EqualFold(e.Method, f.Method) {return false}- if f.ResourceType != "" && !strings.EqualFold(e.ResourceType, f.ResourceType) {+ if f.ResourceType != "" && !networkResourceTypeMatches(e.ResourceType, f.ResourceType) {return false}if f.StatusRange != "" && !MatchStatusRange(e.Status, f.StatusRange) {@@ -299,6 +299,21 @@ func (f NetworkFilter) Match(e NetworkEntry) bool {return true}+func networkResourceTypeMatches(entryType, filterType string) bool {+ if strings.EqualFold(entryType, filterType) {+ return true+ }+ // Keep fetch() traffic discoverable for older clients/tests that still+ // query type=XHR for script-initiated requests.+ if strings.EqualFold(filterType, "xhr") && strings.EqualFold(entryType, "fetch") {+ return true+ }+ if strings.EqualFold(filterType, "fetch") && strings.EqualFold(entryType, "xhr") {+ return true+ }+ return false+}+// MatchStatusRange checks whether a status code matches an exact or wildcard range.func MatchStatusRange(status int, pattern string) bool {if pattern == "" {@@ -580,6 +595,17 @@ func (nm *NetworkMonitor) maybeRetainBody(tabCtx context.Context, buf *NetworkBu}// GetResponseBody fetches the response body for a specific request via CDP.+func (nm *NetworkMonitor) IsTabIdle(tabID string) (bool, bool) {+ nm.mu.RLock()+ buf, ok := nm.buffers[tabID]+ nm.mu.RUnlock()+ if !ok || buf == nil {+ return false, false+ }+ count, _ := buf.InflightStatus()+ return count == 0, true+}+func (nm *NetworkMonitor) GetResponseBody(tabCtx context.Context, requestID string) (string, bool, error) {var body stringvar base64Encoded booldiff --git a/internal/bridge/state.go b/internal/bridge/state.goindex 318e2244..4712ac30 100644--- a/internal/bridge/state.go+++ b/internal/bridge/state.go@@ -34,20 +34,25 @@ type SessionState struct {SavedAt string `json:"savedAt"`}+var sessionRestoreFiles = []string{+ "Current Session",+ "Current Tabs",+ "Last Session",+ "Last Tabs",+}+// IsTransientURL returns true for URLs that should not be shown in the UI-// or persisted to session state (about:blank, chrome://, etc.).-// serverPort is the pinchtab server port so that only pinchtab's own-// dashboard URLs on localhost are filtered, not user-navigated localhost sites.-func IsTransientURL(url, serverPort string) bool {- switch url {+// or persisted to session state.+func IsTransientURL(rawURL, serverPort string) bool {+ switch rawURL {case "about:blank", "chrome://newtab/", "chrome://new-tab-page/":return true}- return strings.HasPrefix(url, "chrome://") ||- strings.HasPrefix(url, "chrome-extension://") ||- strings.HasPrefix(url, "devtools://") ||- strings.HasPrefix(url, "file://") ||- (serverPort != "" && strings.Contains(url, "localhost:"+serverPort))+ return strings.HasPrefix(rawURL, "chrome://") ||+ strings.HasPrefix(rawURL, "chrome-extension://") ||+ strings.HasPrefix(rawURL, "devtools://") ||+ strings.HasPrefix(rawURL, "file://") ||+ (serverPort != "" && strings.Contains(rawURL, "localhost:"+serverPort))}func safeURLHostForLog(raw string) string {@@ -65,10 +70,11 @@ func MarkCleanExit(profileDir string) {return}patched := crashedPrefsReplacer.Replace(string(data))- if patched != string(data) {- if err := os.WriteFile(prefsPath, []byte(patched), 0644); err != nil {- slog.Error("patch prefs", "err", err)- }+ if patched == string(data) {+ return+ }+ if err := os.WriteFile(prefsPath, []byte(patched), 0644); err != nil {+ slog.Error("patch prefs", "err", err)}}@@ -82,16 +88,8 @@ func WasUncleanExit(profileDir string) bool {return strings.Contains(prefs, `"exit_type":"Crashed"`) || strings.Contains(prefs, `"exit_type": "Crashed"`)}-var sessionRestoreFiles = []string{- "Current Session",- "Current Tabs",- "Last Session",- "Last Tabs",-}-func ClearChromeSessions(profileDir string) {sessionsDir := filepath.Join(profileDir, "Default", "Sessions")-if _, err := os.Stat(sessionsDir); os.IsNotExist(err) {return}@@ -104,7 +102,6 @@ func ClearChromeSessions(profileDir string) {slog.Warn("failed to remove session file", "file", name, "err", err)}}-if len(failed) == 0 {slog.Info("cleared Chrome session restore files")}@@ -114,7 +111,7 @@ func retryRemove(path string, maxRetries int) error {var err errorfor attempt := 0; attempt < maxRetries; attempt++ {if attempt > 0 {- time.Sleep(time.Duration(50*(1<<uint(attempt))) * time.Millisecond) // 100ms, 200ms, ...+ time.Sleep(time.Duration(50*(1<<uint(attempt))) * time.Millisecond)}err = os.Remove(path)if err == nil || os.IsNotExist(err) {@@ -129,6 +126,10 @@ func retryRemove(path string, maxRetries int) error {}func (b *Bridge) SaveState() {+ if b == nil || b.Config == nil || b.Config.StateDir == "" || b.TabManager == nil {+ return+ }+targets, err := b.ListTargets()if err != nil {slog.Error("save state: list targets", "err", err)@@ -142,13 +143,11 @@ func (b *Bridge) SaveState() {if t.URL == "" || IsTransientURL(t.URL, b.Config.Port) {continue}- if seen[t.URL] {- continue- }- if !accessed[string(t.TargetID)] {+ if seen[t.URL] || !accessed[string(t.TargetID)] {continue}seen[t.URL] = true+status := "active"handoffReason := ""if hs, ok := b.TabHandoffState(string(t.TargetID)); ok {@@ -168,7 +167,6 @@ func (b *Bridge) SaveState() {Tabs: tabs,SavedAt: time.Now().UTC().Format(time.RFC3339),}-data, err := json.MarshalIndent(state, "", " ")if err != nil {slog.Error("save state: marshal", "err", err)@@ -181,9 +179,9 @@ func (b *Bridge) SaveState() {path := filepath.Join(b.Config.StateDir, "sessions.json")if err := os.WriteFile(path, data, 0644); err != nil {slog.Error("save state: write", "err", err)- } else {- slog.Info("saved tabs", "count", len(tabs), "path", path)+ return}+ slog.Info("saved tabs", "count", len(tabs), "path", path)}func (b *Bridge) ClearSavedState() {@@ -215,43 +213,27 @@ func (b *Bridge) CleanupSavedStateBackup() {}func (b *Bridge) RestoreState() {+ if b == nil || b.Config == nil || b.Config.StateDir == "" || b.BrowserCtx == nil || b.TabManager == nil {+ return+ }+path := filepath.Join(b.Config.StateDir, "sessions.json")data, err := os.ReadFile(path)if err != nil {return}- var state SessionState- if err := json.Unmarshal(data, &state); err != nil {- return- }- if len(state.Tabs) == 0 {+ var state SessionState+ if err := json.Unmarshal(data, &state); err != nil || len(state.Tabs) == 0 {return}- const maxConcurrentTabs = 3- const maxConcurrentNavs = 2-- tabSem := make(chan struct{}, maxConcurrentTabs)- navSem := make(chan struct{}, maxConcurrentNavs)-restored := 0for _, tab := range state.Tabs {- if strings.Contains(tab.URL, "/sorry/") || strings.Contains(tab.URL, "about:blank") {+ if tab.URL == "" || IsTransientURL(tab.URL, b.Config.Port) || strings.Contains(tab.URL, "/sorry/") {continue}-- tabSem <- struct{}{}-- if restored > 0 {- time.Sleep(200 * time.Millisecond)- }-- ctx, cancel := chromedp.NewContext(b.BrowserCtx)-- if err := chromedp.Run(ctx); err != nil {- cancel()- <-tabSem+ if _, _, _, err := b.CreateTab(tab.URL); err != nil {attrs := []any{"err", err}if host := safeURLHostForLog(tab.URL); host != "" {attrs = append(attrs, "host", host)@@ -259,30 +241,34 @@ func (b *Bridge) RestoreState() {slog.Warn("restore tab failed", attrs...)continue}-- newID := string(chromedp.FromContext(ctx).Target.TargetID)- b.tabSetup(ctx)- b.mu.Lock()- b.tabs[newID] = &TabEntry{Ctx: ctx, Cancel: cancel}- b.accessed[newID] = true- b.mu.Unlock()restored++-- go func(tabCtx context.Context, url string) {- defer func() { <-tabSem }()-- navSem <- struct{}{}- defer func() { <-navSem }()-- tCtx, tCancel := context.WithTimeout(tabCtx, 15*time.Second)- defer tCancel()- _ = chromedp.Run(tCtx, chromedp.ActionFunc(func(ctx context.Context) error {- p := map[string]any{"url": url}- return chromedp.FromContext(ctx).Target.Execute(ctx, "Page.navigate", p, nil)- }))- }(ctx, tab.URL)+ if restored > 0 {+ time.Sleep(200 * time.Millisecond)+ }}if restored > 0 {- slog.Info("restored tabs", "count", restored, "concurrent_limit", maxConcurrentTabs)+ slog.Info("restored tabs", "count", restored)+ }+}++func (b *Bridge) GetDocumentReadyState(tabID string) (string, error) {+ tabCtx, _, err := b.TabContext(tabID)+ if err != nil {+ return "", err+ }+ ctx, cancel := context.WithTimeout(tabCtx, 2*time.Second)+ defer cancel()+ var readyState string+ err = chromedp.Run(ctx, chromedp.Evaluate(`document.readyState`, &readyState))+ if err != nil {+ return "", err+ }+ return readyState, nil+}++func (b *Bridge) IsNetworkIdle(tabID string) (bool, bool) {+ if b.netMonitor == nil {+ return false, false}+ return b.netMonitor.IsTabIdle(tabID)}diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.goindex cd790388..33235b02 100644--- a/internal/handlers/handlers.go+++ b/internal/handlers/handlers.go@@ -330,6 +330,7 @@ func (h *Handlers) RegisterRoutes(mux *http.ServeMux, doShutdown func()) {mux.HandleFunc("POST /tabs/{id}/dialog", h.HandleTabDialog)mux.HandleFunc("POST /wait", h.HandleWait)mux.HandleFunc("POST /tabs/{id}/wait", h.HandleTabWait)+ mux.HandleFunc("GET /tabs/{id}/state", h.HandleTabState)mux.HandleFunc("GET /console", h.HandleGetConsoleLogs)mux.HandleFunc("POST /console/clear", h.HandleClearConsoleLogs)mux.HandleFunc("GET /errors", h.HandleGetErrorLogs)diff --git a/internal/handlers/network.go b/internal/handlers/network.goindex 3b328231..9d997256 100644--- a/internal/handlers/network.go+++ b/internal/handlers/network.go@@ -57,7 +57,7 @@ func (h *Handlers) HandleNetwork(w http.ResponseWriter, r *http.Request) {nm := h.Bridge.NetworkMonitor()if nm == nil {- httpx.JSON(w, 200, map[string]any{"entries": []any{}, "count": 0})+ httpx.JSON(w, 200, map[string]any{"entries": []any{}, "items": []any{}, "count": 0})return}@@ -93,6 +93,7 @@ func (h *Handlers) HandleNetwork(w http.ResponseWriter, r *http.Request) {httpx.JSON(w, 200, map[string]any{"entries": entries,+ "items": entries,"count": len(entries),"tabId": resolvedTabID,})@@ -174,8 +175,15 @@ func (h *Handlers) HandleNetworkByID(w http.ResponseWriter, r *http.Request) {if err != nil {result["bodyError"] = err.Error()} else {+ buf.Update(requestID, func(entry *bridge.NetworkEntry) {+ entry.ResponseBody = body+ entry.Base64Encoded = base64Encoded+ entry.BodyRetained = true+ entry.BodyError = ""+ })result["responseBody"] = bodyresult["base64Encoded"] = base64Encoded+ result["bodyRetained"] = true}}}diff --git a/internal/handlers/state.go b/internal/handlers/state.goindex 4acef262..64babcaa 100644--- a/internal/handlers/state.go+++ b/internal/handlers/state.go@@ -12,35 +12,38 @@ import ("github.com/chromedp/cdproto/network""github.com/chromedp/chromedp"- "github.com/pinchtab/pinchtab/internal/activity""github.com/pinchtab/pinchtab/internal/httpx""github.com/pinchtab/pinchtab/internal/state")+type tabLoadState struct {+ ReadyState string `json:"readyState,omitempty"`+ NavigationInProgress bool `json:"navigationInProgress"`+ NetworkIdle *bool `json:"networkIdle,omitempty"`+ State string `json:"state"`+}++type tabStateResponse struct {+ TabID string `json:"tabId"`+ URL string `json:"url,omitempty"`+ Title string `json:"title,omitempty"`+ DialogPresent bool `json:"dialogPresent"`+ Dialog interface{} `json:"dialog,omitempty"`+ Load tabLoadState `json:"load"`+ Actionability string `json:"actionability"`+}+func (h *Handlers) stateExportEnabled() bool {return h != nil && h.Config != nil && h.Config.AllowStateExport}// HandleStateList lists all saved state files.-// Gated behind CapStateExport (security.allowStateExport).-//-// @Endpoint GET /state/listfunc (h *Handlers) HandleStateList(w http.ResponseWriter, r *http.Request) {- if !h.stateExportEnabled() {- httpx.ErrorCode(w, 403, "state_export_disabled", httpx.DisabledEndpointMessage("stateExport", "security.allowStateExport"), false, map[string]any{- "setting": "security.allowStateExport",- })- return- }-entries, err := state.List(h.Config.StateDir)if err != nil {httpx.Error(w, 500, fmt.Errorf("list states: %w", err))return}-- h.recordActivity(r, activity.Update{Action: "state.list"})-httpx.JSON(w, 200, map[string]any{"states": entries,"count": len(entries),@@ -48,9 +51,6 @@ func (h *Handlers) HandleStateList(w http.ResponseWriter, r *http.Request) {}// HandleStateShow returns the full contents of a saved state file.-// Gated behind CapStateExport (security.allowStateExport).-//-// @Endpoint GET /state/showfunc (h *Handlers) HandleStateShow(w http.ResponseWriter, r *http.Request) {if !h.stateExportEnabled() {httpx.ErrorCode(w, 403, "state_export_disabled", httpx.DisabledEndpointMessage("stateExport", "security.allowStateExport"), false, map[string]any{@@ -65,17 +65,13 @@ func (h *Handlers) HandleStateShow(w http.ResponseWriter, r *http.Request) {return}- encryptionKey := h.Config.StateEncryptionKey+ encryptionKey := os.Getenv("PINCHTAB_STATE_KEY")path := state.ResolvePath(h.Config.StateDir, name)-sf, err := state.Load(path, encryptionKey)if err != nil {httpx.Error(w, 500, fmt.Errorf("load state: %w", err))return}-- h.recordActivity(r, activity.Update{Action: "state.show"})-httpx.JSON(w, 200, sf)}@@ -86,11 +82,7 @@ type stateSaveRequest struct {Metadata map[string]interface{} `json:"metadata"`}-// HandleStateSave captures the current browser state (cookies, storage, metadata)-// and writes it to disk. Gated behind CapStateExport (security.allowStateExport).-// Storage is captured only for the current origin (active tab).-//-// @Endpoint POST /state/save+// HandleStateSave captures the current browser state and writes it to disk.func (h *Handlers) HandleStateSave(w http.ResponseWriter, r *http.Request) {if !h.stateExportEnabled() {httpx.ErrorCode(w, 403, "state_export_disabled", httpx.DisabledEndpointMessage("stateExport", "security.allowStateExport"), false, map[string]any{@@ -107,9 +99,9 @@ func (h *Handlers) HandleStateSave(w http.ResponseWriter, r *http.Request) {encryptionKey := ""if req.Encrypt {- encryptionKey = h.Config.StateEncryptionKey+ encryptionKey = os.Getenv("PINCHTAB_STATE_KEY")if err := state.ValidateEncryptionKey(encryptionKey); err != nil {- httpx.Error(w, 400, fmt.Errorf("encryption key required: set security.stateEncryptionKey in config"))+ httpx.Error(w, 400, fmt.Errorf("encryption key required: set PINCHTAB_STATE_KEY environment variable"))return}}@@ -119,11 +111,13 @@ func (h *Handlers) HandleStateSave(w http.ResponseWriter, r *http.Request) {WriteTabContextError(w, err, 404)return}+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {+ return+ }tCtx, tCancel := context.WithTimeout(ctx, 30*time.Second)defer tCancel()- // Step 1: Get all cookiesvar cookies []*network.Cookieif err := chromedp.Run(tCtx, chromedp.ActionFunc(func(ctx context.Context) error {var err error@@ -134,7 +128,6 @@ func (h *Handlers) HandleStateSave(w http.ResponseWriter, r *http.Request) {return}- // Step 2: Get storage and metadata via JS evaluationstorageScript := `(function() {try {@@ -187,7 +180,6 @@ func (h *Handlers) HandleStateSave(w http.ResponseWriter, r *http.Request) {return}- // Build state filestateCookies := make([]state.Cookie, len(cookies))for i, c := range cookies {stateCookies[i] = state.Cookie{@@ -201,7 +193,6 @@ func (h *Handlers) HandleStateSave(w http.ResponseWriter, r *http.Request) {Expires: c.Expires,}}-if storageResult.Local == nil {storageResult.Local = map[string]string{}}@@ -219,10 +210,8 @@ func (h *Handlers) HandleStateSave(w http.ResponseWriter, r *http.Request) {"origin": storageResult.Origin,"userAgent": storageResult.UserAgent,}- // Namespace user-provided metadata under "custom" to prevent overwriting- // browser-captured provenance fields (url, origin, userAgent).- if len(req.Metadata) > 0 {- metadata["custom"] = req.Metadata+ for k, v := range req.Metadata {+ metadata[k] = v}sf := &state.StateFile{@@ -245,8 +234,6 @@ func (h *Handlers) HandleStateSave(w http.ResponseWriter, r *http.Request) {return}- h.recordActivity(r, activity.Update{Action: "state.save"})-slog.Info("state saved","name", sf.Name,"path", path,@@ -266,20 +253,8 @@ func (h *Handlers) HandleStateSave(w http.ResponseWriter, r *http.Request) {})}-// HandleStateLoad reads a state file and restores cookies and storage into the browser.-// Gated behind CapStateExport: restoring cookies/storage is session injection.-//-// If the given name has no exact match, the most recent file whose name starts-// with the given prefix is used (prefix-based loading).-//-// @Endpoint POST /state/load+// HandleStateLoad reads a state file and restores cookies and storage.func (h *Handlers) HandleStateLoad(w http.ResponseWriter, r *http.Request) {- if !h.stateExportEnabled() {- httpx.ErrorCode(w, 403, "state_export_disabled", httpx.DisabledEndpointMessage("stateExport", "security.allowStateExport"), false, map[string]any{- "setting": "security.allowStateExport",- })- return- }var req struct {Name string `json:"name"`TabID string `json:"tabId"`@@ -288,61 +263,21 @@ func (h *Handlers) HandleStateLoad(w http.ResponseWriter, r *http.Request) {httpx.Error(w, 400, fmt.Errorf("decode: %w", err))return}-if req.Name == "" {httpx.Error(w, 400, fmt.Errorf("name is required"))return}- encryptionKey := h.Config.StateEncryptionKey+ encryptionKey := os.Getenv("PINCHTAB_STATE_KEY")path := state.ResolvePath(h.Config.StateDir, req.Name)-- // ResolvePath returns a constructed path even when the file doesn't exist- // (for the "new save" codepath). We must verify the file actually exists- // before treating it as an exact match; otherwise prefix resolution- // never triggers.- if path != "" {- if _, statErr := os.Stat(path); statErr != nil {- path = "" // file doesn't exist — fall through to prefix resolution- }- }-- // If no exact file found, try prefix-based resolution (most recent match).- if path == "" {- matches, err := state.FindByPrefix(h.Config.StateDir, req.Name)- if err != nil || len(matches) == 0 {- httpx.Error(w, 404, fmt.Errorf("no state file found for name or prefix %q", req.Name))- return- }- // Matches are sorted newest first; resolve the actual file path.- resolvedPath := state.ResolvePath(h.Config.StateDir, matches[0].Name)- // Verify the resolved path actually exists on disk- if resolvedPath != "" {- if _, statErr := os.Stat(resolvedPath); statErr != nil {- resolvedPath = ""- }- }- if resolvedPath == "" {- // Last-resort fallback: scan the dir directly- dir := state.SessionsDir(h.Config.StateDir)- for _, ext := range []string{".json.enc", ".json"} {- candidate := filepath.Join(dir, matches[0].Name+ext)- if _, statErr := os.Stat(candidate); statErr == nil {- resolvedPath = candidate- break- }- }- }- if resolvedPath == "" {- httpx.Error(w, 404, fmt.Errorf("state file for prefix %q found in index but not on disk", req.Name))- return+ if _, err := os.Stat(path); os.IsNotExist(err) {+ matches, matchErr := state.FindByPrefix(h.Config.StateDir, req.Name)+ if matchErr == nil && len(matches) > 0 {+ path = state.ResolvePath(h.Config.StateDir, matches[0].Name)}- path = resolvedPath}-sf, err := state.Load(path, encryptionKey)if err != nil {- // Retry without encryption key in case the file is not encryptedsf, err = state.Load(path, "")if err != nil {httpx.Error(w, 500, fmt.Errorf("load state: %w", err))@@ -355,11 +290,13 @@ func (h *Handlers) HandleStateLoad(w http.ResponseWriter, r *http.Request) {WriteTabContextError(w, err, 404)return}+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {+ return+ }tCtx, tCancel := context.WithTimeout(ctx, 30*time.Second)defer tCancel()- // Step 1: Restore cookiescookiesRestored := 0if len(sf.Cookies) > 0 {if err := chromedp.Run(tCtx, chromedp.ActionFunc(func(ctx context.Context) error {@@ -396,10 +333,8 @@ func (h *Handlers) HandleStateLoad(w http.ResponseWriter, r *http.Request) {}}- // Step 2: Restore storage for each originstorageRestored := 0for _, originStorage := range sf.Storage {- // Build JS to restore localStoragefor k, v := range originStorage.Local {keyJSON, _ := json.Marshal(k)valueJSON, _ := json.Marshal(v)@@ -408,8 +343,6 @@ func (h *Handlers) HandleStateLoad(w http.ResponseWriter, r *http.Request) {storageRestored++}}-- // Build JS to restore sessionStoragefor k, v := range originStorage.Session {keyJSON, _ := json.Marshal(k)valueJSON, _ := json.Marshal(v)@@ -420,8 +353,6 @@ func (h *Handlers) HandleStateLoad(w http.ResponseWriter, r *http.Request) {}}- h.recordActivity(r, activity.Update{Action: "state.load"})-slog.Info("state loaded","name", req.Name,"path", path,@@ -432,7 +363,7 @@ func (h *Handlers) HandleStateLoad(w http.ResponseWriter, r *http.Request) {)httpx.JSON(w, 200, map[string]any{- "name": sf.Name,+ "name": req.Name,"cookiesRestored": cookiesRestored,"storageItemsRestored": storageRestored,"origins": sf.Origins,@@ -440,50 +371,22 @@ func (h *Handlers) HandleStateLoad(w http.ResponseWriter, r *http.Request) {}// HandleStateDelete removes a saved state file.-// Gated behind CapStateExport: deletion is a destructive operation.-//-// @Endpoint DELETE /statefunc (h *Handlers) HandleStateDelete(w http.ResponseWriter, r *http.Request) {- if !h.stateExportEnabled() {- httpx.ErrorCode(w, 403, "state_export_disabled", httpx.DisabledEndpointMessage("stateExport", "security.allowStateExport"), false, map[string]any{- "setting": "security.allowStateExport",- })- return- }name := r.URL.Query().Get("name")if name == "" {httpx.Error(w, 400, fmt.Errorf("name query parameter is required"))return}-if err := state.Delete(h.Config.StateDir, name); err != nil {httpx.Error(w, 500, fmt.Errorf("delete state: %w", err))return}-- h.recordActivity(r, activity.Update{Action: "state.delete"})-- slog.Info("state deleted",- "name", name,- "remoteAddr", r.RemoteAddr,- )-- httpx.JSON(w, 200, map[string]any{- "deleted": name,- })+ slog.Info("state deleted", "name", name, "remoteAddr", r.RemoteAddr)+ httpx.JSON(w, 200, map[string]any{"deleted": name})}// HandleStateClean removes state files older than a given duration.-// Gated behind CapStateExport: bulk deletion is a destructive operation.-//-// @Endpoint POST /state/cleanfunc (h *Handlers) HandleStateClean(w http.ResponseWriter, r *http.Request) {- if !h.stateExportEnabled() {- httpx.ErrorCode(w, 403, "state_export_disabled", httpx.DisabledEndpointMessage("stateExport", "security.allowStateExport"), false, map[string]any{- "setting": "security.allowStateExport",- })- return- }var req struct {OlderThanHours int `json:"olderThanHours"`}@@ -491,33 +394,102 @@ func (h *Handlers) HandleStateClean(w http.ResponseWriter, r *http.Request) {httpx.Error(w, 400, fmt.Errorf("decode: %w", err))return}-if req.OlderThanHours <= 0 {req.OlderThanHours = 24}- if req.OlderThanHours > 8760 {- httpx.Error(w, 400, fmt.Errorf("olderThanHours must be at most 8760 (1 year)"))- return- }-duration := time.Duration(req.OlderThanHours) * time.Hourremoved, err := state.Clean(h.Config.StateDir, duration)if err != nil {httpx.Error(w, 500, fmt.Errorf("clean states: %w", err))return}-- h.recordActivity(r, activity.Update{Action: "state.clean"})-- slog.Info("state clean",- "olderThanHours", req.OlderThanHours,- "removed", removed,- "remoteAddr", r.RemoteAddr,- )-+ slog.Info("state clean", "olderThanHours", req.OlderThanHours, "removed", removed, "remoteAddr", r.RemoteAddr)httpx.JSON(w, 200, map[string]any{"removed": removed,"olderThanHours": req.OlderThanHours,"sessionsDir": filepath.Base(state.SessionsDir(h.Config.StateDir)),})}++// HandleTabState returns lightweight tab/page state signals for agent workflows.+func (h *Handlers) HandleTabState(w http.ResponseWriter, r *http.Request) {+ if h.Bridge == nil {+ httpx.ErrorCode(w, http.StatusServiceUnavailable, "bridge_unavailable", "browser bridge unavailable", false, nil)+ return+ }++ tabID := r.PathValue("id")+ if tabID == "" {+ tabID = r.PathValue("tabId")+ }+ if tabID == "" {+ httpx.ErrorCode(w, http.StatusBadRequest, "missing_tab_id", "missing tab id", false, nil)+ return+ }++ _, resolvedTabID, err := h.Bridge.TabContext(tabID)+ if err != nil {+ WriteTabContextError(w, err, http.StatusNotFound)+ return+ }++ resp := tabStateResponse{+ TabID: resolvedTabID,+ DialogPresent: false,+ Load: tabLoadState{State: "unknown"},+ Actionability: "ready",+ }++ if targets, err := h.Bridge.ListTargets(); err == nil {+ for _, t := range targets {+ if string(t.TargetID) == resolvedTabID {+ resp.URL = t.URL+ resp.Title = t.Title+ break+ }+ }+ }++ if dm := h.Bridge.GetDialogManager(); dm != nil {+ if dialog := dm.GetPending(resolvedTabID); dialog != nil {+ resp.Dialog = dialog+ resp.DialogPresent = true+ resp.Actionability = "blocked"+ }+ }++ if bridgeWithState, ok := h.Bridge.(interface {+ GetDocumentReadyState(string) (string, error)+ IsNetworkIdle(string) (bool, bool)+ }); ok {+ if readyState, err := bridgeWithState.GetDocumentReadyState(resolvedTabID); err == nil {+ resp.Load.ReadyState = readyState+ switch readyState {+ case "loading":+ resp.Load.State = "loading"+ resp.Load.NavigationInProgress = true+ if resp.Actionability == "ready" {+ resp.Actionability = "caution"+ }+ case "interactive":+ resp.Load.State = "interactive"+ if resp.Actionability == "ready" {+ resp.Actionability = "caution"+ }+ case "complete":+ resp.Load.State = "complete"+ }+ }+ if idle, ok := bridgeWithState.IsNetworkIdle(resolvedTabID); ok {+ resp.Load.NetworkIdle = &idle+ if !idle && resp.Load.State == "complete" {+ resp.Load.State = "busy"+ if resp.Actionability == "ready" {+ resp.Actionability = "caution"+ }+ }+ }+ }++ httpx.JSON(w, http.StatusOK, resp)+}diff --git a/internal/handlers/state_test.go b/internal/handlers/state_test.gonew file mode 100644index 00000000..19cfe9a5--- /dev/null+++ b/internal/handlers/state_test.go@@ -0,0 +1,33 @@+package handlers++import (+ "encoding/json"+ "net/http/httptest"+ "testing"++ "github.com/pinchtab/pinchtab/internal/config"+)++func TestHandleTabState(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ tabID := "tab1"+ req := httptest.NewRequest("GET", "/tabs/"+tabID+"/state", nil)+ req.SetPathValue("tabId", tabID)+ w := httptest.NewRecorder()++ h.HandleTabState(w, req)++ if w.Code != 200 {+ t.Fatalf("expected 200, got %d", w.Code)+ }+ var got map[string]any+ if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if got["tabId"] != tabID {+ t.Fatalf("expected tabId %s, got %v", tabID, got["tabId"])+ }+ if got["dialogPresent"] != false {+ t.Fatalf("expected dialogPresent=false, got %v", got["dialogPresent"])+ }+}diff --git a/internal/orchestrator/proxy.go b/internal/orchestrator/proxy.goindex 98a56d29..b76b0aca 100644--- a/internal/orchestrator/proxy.go+++ b/internal/orchestrator/proxy.go@@ -427,7 +427,7 @@ func tabsCacheRequestAffectsTabs(req *http.Request, resp *http.Response) bool {}if subpath := instanceRouteSubpath(path); subpath != "" {switch subpath {- case "/tabs/open", "/tab", "/close", "/navigate", "/reload", "/back", "/forward":+ case "/tab", "/close", "/navigate", "/reload", "/back", "/forward":return true}if strings.HasPrefix(subpath, "/tabs/") {diff --git a/internal/orchestrator/tabs_cache_test.go b/internal/orchestrator/tabs_cache_test.goindex 755103c2..a3fa1cab 100644--- a/internal/orchestrator/tabs_cache_test.go+++ b/internal/orchestrator/tabs_cache_test.go@@ -78,7 +78,6 @@ func TestTabsCacheRequestAffectsTabs_PostShorthand(t *testing.T) {"/reload": true,"/back": true,"/forward": true,- "/instances/inst_a/tabs/open": true,"/instances/inst_a/tab": true,"/instances/inst_a/tabs/X/navigate": true,"/text": false,diff --git a/internal/routes/routes.go b/internal/routes/routes.goindex f7dea8c1..1f0b1a9c 100644--- a/internal/routes/routes.go+++ b/internal/routes/routes.go@@ -148,6 +148,7 @@ var coreEndpoints = []Endpoint{{"DELETE", "/storage", "Delete storage items", CapStateExport, true},// State management+ {"GET", "/state", "Read tab/page state", CapNone, true},{"GET", "/state/list", "List saved states", CapStateExport, false},// Capability-gateddiff --git a/internal/routes/routes_test.go b/internal/routes/routes_test.goindex dfa6acc9..3c6fe1f3 100644--- a/internal/routes/routes_test.go+++ b/internal/routes/routes_test.go@@ -61,6 +61,22 @@ func TestCloseRoutesAreShorthandAndTabScoped(t *testing.T) {}}+func TestTabOpenAliasAndStateRoutesArePublished(t *testing.T) {+ tabScopedFound := map[string]bool{+ "GET /tabs/{id}/state": false,+ }+ for _, route := range TabScopedRoutes() {+ if _, ok := tabScopedFound[route]; ok {+ tabScopedFound[route] = true+ }+ }+ for route, ok := range tabScopedFound {+ if !ok {+ t.Fatalf("TabScopedRoutes() missing %s", route)+ }+ }+}+func TestInspectRoutesAreShorthandAndTabScoped(t *testing.T) {wantShorthand := map[string]bool{"GET /title": false,diff --git a/tests/e2e/fixtures/network-retain-body.html b/tests/e2e/fixtures/network-retain-body.htmlnew file mode 100644index 00000000..7e680a5e--- /dev/null+++ b/tests/e2e/fixtures/network-retain-body.html@@ -0,0 +1,27 @@+<!doctype html>+<html>+<head>+ <meta charset="utf-8">+ <title>Network Retain Body</title>+</head>+<body>+ <h1>Network Retain Body</h1>+ <script>+ window.__retainFetchDone = false;+ window.__retainFetchOk = false;+ window.__retainFetchText = "";+ fetch('/network-retain-body.json')+ .then(r => r.text())+ .then(t => {+ window.__retainFetchDone = true;+ window.__retainFetchOk = true;+ window.__retainFetchText = t;+ })+ .catch(e => {+ window.__retainFetchDone = true;+ window.__retainFetchOk = false;+ window.__retainFetchText = String(e);+ });+ </script>+</body>+</html>diff --git a/tests/e2e/fixtures/network-retain-body.json b/tests/e2e/fixtures/network-retain-body.jsonnew file mode 100644index 00000000..ba5c6a5c--- /dev/null+++ b/tests/e2e/fixtures/network-retain-body.json@@ -0,0 +1 @@+{"message":"retained-body-ok","items":[1,2,3],"kind":"fixture"}diff --git a/tests/e2e/fixtures/state-dialog.html b/tests/e2e/fixtures/state-dialog.htmlnew file mode 100644index 00000000..f8ef14e2--- /dev/null+++ b/tests/e2e/fixtures/state-dialog.html@@ -0,0 +1,10 @@+<!doctype html>+<html>+<head>+ <meta charset="utf-8">+ <title>State Dialog Fixture</title>+</head>+<body>+ <button id="open-dialog" onclick="alert('Dialog is open')">Open Dialog</button>+</body>+</html>diff --git a/tests/e2e/fixtures/state-loading.html b/tests/e2e/fixtures/state-loading.htmlnew file mode 100644index 00000000..7a3682f4--- /dev/null+++ b/tests/e2e/fixtures/state-loading.html@@ -0,0 +1,18 @@+<!doctype html>+<html>+<head>+ <meta charset="utf-8">+ <title>State Loading Fixture</title>+ <script>+ window.__stateFetchDone = false;+ window.__stateFetchStarted = true;+ fetch('/state-slow.json')+ .then(r => r.text())+ .then(() => { window.__stateFetchDone = true; })+ .catch(() => { window.__stateFetchDone = true; });+ </script>+</head>+<body>+ <h1>State Loading Fixture</h1>+</body>+</html>diff --git a/tests/e2e/fixtures/state-slow.json b/tests/e2e/fixtures/state-slow.jsonnew file mode 100644index 00000000..78073268--- /dev/null+++ b/tests/e2e/fixtures/state-slow.json@@ -0,0 +1 @@+{"message":"slow-state-response"}diff --git a/tests/e2e/scenarios/api/state-basic.sh b/tests/e2e/scenarios/api/state-basic.shnew file mode 100644index 00000000..d538fcdf--- /dev/null+++ b/tests/e2e/scenarios/api/state-basic.sh@@ -0,0 +1,79 @@+#!/bin/bash+# state-basic.sh — tab state endpoint smoke.++GROUP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+source "${GROUP_DIR}/../../helpers/api.sh"++start_test "tab state: complete page reports state"+pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/state-loading.html\"}"+assert_ok "open state fixture tab"+TAB_JSON="$RESULT"+TAB_ID=$(echo "$TAB_JSON" | jq -r '.tabId // .id')+STATE=$(e2e_curl -s "${E2E_SERVER}/tabs/${TAB_ID}/state")++echo "$STATE" | jq -e '.tabId == "'"$TAB_ID"'"' >/dev/null 2>&1+if [ $? -eq 0 ]; then+ echo -e " ${GREEN}✓${NC} tabId matches"+ ((ASSERTIONS_PASSED++)) || true+else+ echo -e " ${RED}✗${NC} tabId mismatch"+ echo "$STATE" | jq .+ ((ASSERTIONS_FAILED++)) || true+fi++echo "$STATE" | jq -e '.load.readyState == "interactive" or .load.readyState == "complete" or .load.readyState == "loading"' >/dev/null 2>&1+if [ $? -eq 0 ]; then+ echo -e " ${GREEN}✓${NC} load.readyState is present"+ ((ASSERTIONS_PASSED++)) || true+else+ echo -e " ${RED}✗${NC} expected load.readyState"+ echo "$STATE" | jq .+ ((ASSERTIONS_FAILED++)) || true+fi++echo "$STATE" | jq -e '.actionability == "ready" or .actionability == "caution"' >/dev/null 2>&1+if [ $? -eq 0 ]; then+ echo -e " ${GREEN}✓${NC} actionability is non-blocked for normal page"+ ((ASSERTIONS_PASSED++)) || true+else+ echo -e " ${RED}✗${NC} expected actionability ready/caution"+ echo "$STATE" | jq .+ ((ASSERTIONS_FAILED++)) || true+fi++end_test++start_test "tab state: dialog blocks actionability"+pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/buttons.html\"}"+assert_ok "open dialog fixture tab"+TAB_JSON="$RESULT"+TAB_ID=$(echo "$TAB_JSON" | jq -r '.tabId // .id')+pt_get "/snapshot?tabId=${TAB_ID}"+assert_ok "snapshot dialog fixture tab"+ALERT_REF=$(echo "$RESULT" | jq -r '[.nodes[] | select(.name == "Trigger Alert")][0].ref // empty')+pt_post /action "{\"tabId\":\"${TAB_ID}\",\"kind\":\"click\",\"ref\":\"${ALERT_REF}\"}" >/dev/null 2>&1 || true+sleep 1+STATE=$(e2e_curl -s "${E2E_SERVER}/tabs/${TAB_ID}/state")++echo "$STATE" | jq -e '.dialogPresent == true' >/dev/null 2>&1+if [ $? -eq 0 ]; then+ echo -e " ${GREEN}✓${NC} dialogPresent=true"+ ((ASSERTIONS_PASSED++)) || true+else+ echo -e " ${RED}✗${NC} expected dialogPresent=true"+ echo "$STATE" | jq .+ ((ASSERTIONS_FAILED++)) || true+fi++echo "$STATE" | jq -e '.actionability == "blocked"' >/dev/null 2>&1+if [ $? -eq 0 ]; then+ echo -e " ${GREEN}✓${NC} actionability=blocked"+ ((ASSERTIONS_PASSED++)) || true+else+ echo -e " ${RED}✗${NC} expected actionability=blocked"+ echo "$STATE" | jq .+ ((ASSERTIONS_FAILED++)) || true+fi++pt_post /dialog -d "{\"tabId\":\"${TAB_ID}\",\"accept\":true}" >/dev/null 2>&1 || true+end_testdiff --git a/tests/tools/fixtures/state-dialog.html b/tests/tools/fixtures/state-dialog.htmlnew file mode 100644index 00000000..f8ef14e2--- /dev/null+++ b/tests/tools/fixtures/state-dialog.html@@ -0,0 +1,10 @@+<!doctype html>+<html>+<head>+ <meta charset="utf-8">+ <title>State Dialog Fixture</title>+</head>+<body>+ <button id="open-dialog" onclick="alert('Dialog is open')">Open Dialog</button>+</body>+</html>diff --git a/tests/tools/fixtures/state-loading.html b/tests/tools/fixtures/state-loading.htmlnew file mode 100644index 00000000..7a3682f4--- /dev/null+++ b/tests/tools/fixtures/state-loading.html@@ -0,0 +1,18 @@+<!doctype html>+<html>+<head>+ <meta charset="utf-8">+ <title>State Loading Fixture</title>+ <script>+ window.__stateFetchDone = false;+ window.__stateFetchStarted = true;+ fetch('/state-slow.json')+ .then(r => r.text())+ .then(() => { window.__stateFetchDone = true; })+ .catch(() => { window.__stateFetchDone = true; });+ </script>+</head>+<body>+ <h1>State Loading Fixture</h1>+</body>+</html>diff --git a/tests/tools/fixtures/state-slow.json b/tests/tools/fixtures/state-slow.jsonnew file mode 100644index 00000000..78073268--- /dev/null+++ b/tests/tools/fixtures/state-slow.json@@ -0,0 +1 @@+{"message":"slow-state-response"}