Skip to content

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

Unify state surface and gate full browser state

Mario2cb69c8044ee
diff --git a/cmd/pinchtab/cmd_cli_state.go b/cmd/pinchtab/cmd_cli_state.go
index de810c16..71830b79 100644
--- a/cmd/pinchtab/cmd_cli_state.go
+++ b/cmd/pinchtab/cmd_cli_state.go
@@ -7,8 +7,13 @@ import (
var stateCmd = &cobra.Command{
Use: "state",
- Short: "Manage browser session state",
- Long: "Commands for saving, loading, and managing persistent browser state (cookies, localStorage, sessionStorage).",
+ Short: "Show current browser state or manage saved state",
+ Long: "Show current browser state for the current tab, or save, load, and manage persistent browser state (cookies, localStorage, sessionStorage).",
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.StateCurrent(rt.client, rt.base, rt.token, cmd)
+ })
+ },
}
var stateListCmd = &cobra.Command{
@@ -79,6 +84,7 @@ var stateCleanCmd = &cobra.Command{
func init() {
stateCmd.AddCommand(stateListCmd, stateSaveCmd, stateLoadCmd, stateShowCmd, stateDeleteCmd, stateCleanCmd)
+ addTabFlag(stateCmd)
// save flags
stateSaveCmd.Flags().String("name", "", "Name for the saved state (auto-generated if omitted)")
diff --git a/docs/endpoints.md b/docs/endpoints.md
index 99023b36..066783fd 100644
--- a/docs/endpoints.md
+++ b/docs/endpoints.md
@@ -364,9 +364,10 @@ DELETE body fields:
- `key` — optional (if omitted, clears entire storage)
- `tabId` — optional
-## State Management
+## State
```text
+GET /state
GET /state/list
GET /state/show
POST /state/save
@@ -375,15 +376,23 @@ DELETE /state
POST /state/clean
```
-State management saves and restores browser state (cookies, localStorage, sessionStorage, metadata) to disk.
+`GET /state` returns the current full browser state for the current tab or an explicit `tabId`, including cookies, current-origin storage, metadata, and basic tab information.
+
+`/state/save|load|list|show|delete|clean` manage persisted saved browser state on disk.
+
+This is different from `GET /tabs/{id}/state`, which returns live tab/page runtime state for readiness and blocking checks.
Notes:
-- All state and storage endpoints are gated by `security.allowStateExport`: `/storage`, `/tabs/{id}/storage`, `GET /state/list`, `GET /state/show`, `POST /state/save`, `POST /state/load`, `DELETE /state`, and `POST /state/clean`
+- All state and storage endpoints are gated by `security.allowStateExport`: `/storage`, `/tabs/{id}/storage`, `GET /state`, `GET /state/list`, `GET /state/show`, `POST /state/save`, `POST /state/load`, `DELETE /state`, and `POST /state/clean`
- state files are stored in `{stateDir}/sessions/` with `0600` permissions
- optional AES-256-GCM encryption via `security.stateEncryptionKey` config setting
- storage is captured only for the current origin (active tab)
+`GET /state` query parameters:
+
+- `tabId` — optional tab identifier; when omitted, uses the current tab
+
`POST /state/save` body fields:
- `name` — state file name
@@ -404,6 +413,16 @@ Notes:
- `olderThanHours` — optional (default: 24)
+## Tab State
+
+```text
+GET /tabs/{id}/state
+```
+
+Returns lightweight live tab/page runtime state for a tab, including load state, dialog presence, and actionability.
+
+Use it as a cheap readiness probe before actions. Keep the detailed semantics in the API/skill references rather than here.
+
## Wait, Network, Dialog, Console, And Errors
```text
diff --git a/docs/reference/index.md b/docs/reference/index.md
index 173cd360..8cf3267c 100644
--- a/docs/reference/index.md
+++ b/docs/reference/index.md
@@ -30,6 +30,7 @@ Note: this index is generated and should be checked against the code when comman
- [Select](./select.md)
- [Sessions](./sessions.md)
- [Snapshot](./snapshot.md)
+- [State](./state.md)
- [Solve](./solve.md)
- [Strategies](./strategies.md)
- [Tabs](./tabs.md)
diff --git a/docs/reference/mcp-tools.md b/docs/reference/mcp-tools.md
index 8518ad55..e1b0c3af 100644
--- a/docs/reference/mcp-tools.md
+++ b/docs/reference/mcp-tools.md
@@ -124,3 +124,5 @@ Security note:
- widening IDPI allowlists or disabling strict protections increases the chance that prompt-injection text reaches downstream agent logic
For setup and client configuration, see [MCP Server](../mcp.md).
+
+Saved browser state is intentionally not exposed as MCP tools right now. Use the CLI or HTTP API for `GET /state`, `pinchtab state`, and saved-state persistence operations.
diff --git a/docs/reference/state.md b/docs/reference/state.md
new file mode 100644
index 00000000..7fd0d362
--- /dev/null
+++ b/docs/reference/state.md
@@ -0,0 +1,128 @@
+# State
+
+`pinchtab state` shows the current full browser state for a tab, and also manages saved browser state on disk.
+
+There are two related state views:
+
+- **full browser state** via `pinchtab state` or `GET /state`
+- **live tab state** via `GET /tabs/{id}/state`
+- **current-origin storage** via `pinchtab storage ...`
+
+Full browser state includes:
+
+- cookies
+- current-origin `localStorage`
+- current-origin `sessionStorage`
+- optional metadata
+
+All full/saved state operations require `security.allowStateExport=true`.
+
+## Commands
+
+```bash
+pinchtab state [--tab <id>]
+pinchtab state list
+pinchtab state save [--name <name>] [--encrypt] [--tab <id>]
+pinchtab state load --name <name-or-prefix> [--tab <id>]
+pinchtab state show --name <name>
+pinchtab state delete --name <name>
+pinchtab state clean [--older-than <hours>]
+```
+
+## Show Current Browser State
+
+```bash
+pinchtab state
+pinchtab state --tab <tabId>
+```
+
+Returns the current full browser state for the active tab or the specified tab:
+
+- cookies
+- current-origin storage
+- tab information such as `tabId`, URL, and title
+- metadata such as origin and user agent
+
+Use this when you need the richer gated state view. For the lightweight operational/readiness view, use `GET /tabs/{id}/state`.
+
+## List Saved States
+
+```bash
+pinchtab state list
+```
+
+Lists saved state files in the configured state directory.
+
+## Save Current Browser State
+
+```bash
+pinchtab state save
+pinchtab state save --name work-login
+pinchtab state save --name checkout --tab <tabId>
+pinchtab state save --name work-login --encrypt
+```
+
+Notes:
+
+- omitting `--name` lets PinchTab auto-generate one
+- `--tab <id>` captures state from a specific tab instead of the active/current one
+- `--encrypt` requires the configured state-encryption key
+
+## Load A Saved State
+
+```bash
+pinchtab state load --name work-login
+pinchtab state load --name work-log # prefix match, newest match wins
+pinchtab state load --name checkout --tab <tabId>
+```
+
+Notes:
+
+- `--name` accepts either an exact name or a prefix
+- prefix matching resolves to the most recent matching saved state
+- loading restores cookies plus current-origin storage into the target tab
+
+## Show Saved State Details
+
+```bash
+pinchtab state show --name work-login
+```
+
+Displays the full saved browser state record, including stored metadata and origin storage payloads.
+
+## Delete A Saved State
+
+```bash
+pinchtab state delete --name work-login
+```
+
+Removes the named state file from disk.
+
+## Clean Old Saved State Files
+
+```bash
+pinchtab state clean
+pinchtab state clean --older-than 72
+```
+
+Removes saved state files older than the given number of hours. Default is `24`.
+
+## HTTP API
+
+```text
+GET /state
+GET /state/list
+GET /state/show
+POST /state/save
+POST /state/load
+DELETE /state
+POST /state/clean
+```
+
+See [Endpoints](../endpoints.md) for the short route index. Use `GET /state?tabId=<id>` for the full gated browser-state view and `GET /tabs/{id}/state` for live readiness/blocking data.
+
+## Related
+
+- [Tabs](./tabs.md) for live tab work and `--tab <id>`
+- [Sessions](./sessions.md) for agent/session auth
+- [Config](./config.md) for security flags and storage directories
diff --git a/internal/cli/actions/actions_state.go b/internal/cli/actions/actions_state.go
index 94b19e85..5dda4976 100644
--- a/internal/cli/actions/actions_state.go
+++ b/internal/cli/actions/actions_state.go
@@ -11,6 +11,30 @@ import (
"github.com/spf13/cobra"
)
+// StateList lists all saved state files.
+func StateCurrent(client *http.Client, base, token string, cmd *cobra.Command) {
+ tabID, _ := cmd.Flags().GetString("tab")
+ params := url.Values{}
+ if tabID != "" {
+ params.Set("tabId", tabID)
+ }
+
+ result := apiclient.DoGetRaw(client, base, token, "/state", params)
+ if result == nil {
+ fmt.Fprintln(os.Stderr, "Failed to read current browser state")
+ os.Exit(1)
+ }
+
+ var buf map[string]any
+ if err := json.Unmarshal(result, &buf); err != nil {
+ fmt.Fprintf(os.Stderr, "Failed to parse response: %v\n", err)
+ os.Exit(1)
+ }
+
+ out, _ := json.MarshalIndent(buf, "", " ")
+ fmt.Println(string(out))
+}
+
// StateList lists all saved state files.
func StateList(client *http.Client, base, token string) {
result := apiclient.DoGetRaw(client, base, token, "/state/list", nil)
diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.go
index 2d653e70..c2830bc6 100644
--- a/internal/handlers/handlers.go
+++ b/internal/handlers/handlers.go
@@ -373,6 +373,7 @@ func (h *Handlers) RegisterRoutes(mux *http.ServeMux, doShutdown func()) {
mux.HandleFunc("DELETE /tabs/{id}/storage", h.HandleTabStorageDelete)
// State management
+ mux.HandleFunc("GET /state", h.HandleStateCurrent)
mux.HandleFunc("GET /state/list", h.HandleStateList)
mux.HandleFunc("GET /state/show", h.HandleStateShow)
mux.HandleFunc("POST /state/save", h.HandleStateSave)
diff --git a/internal/handlers/middleware_session_grants.go b/internal/handlers/middleware_session_grants.go
index 73fc4060..64b4215a 100644
--- a/internal/handlers/middleware_session_grants.go
+++ b/internal/handlers/middleware_session_grants.go
@@ -255,7 +255,7 @@ func sessionEvaluateGrantAllows(method, path string) bool {
func sessionStorageGrantAllows(method, path string) bool {
switch method {
case http.MethodGet:
- return path == "/storage" || path == "/state/list" || path == "/state/show"
+ return path == "/storage" || path == "/state" || path == "/state/list" || path == "/state/show"
case http.MethodPost:
return path == "/storage" || path == "/state/save" || path == "/state/load" || path == "/state/clean"
case http.MethodDelete:
diff --git a/internal/handlers/openapi.go b/internal/handlers/openapi.go
index 374db7b9..8e13b2c7 100644
--- a/internal/handlers/openapi.go
+++ b/internal/handlers/openapi.go
@@ -153,6 +153,15 @@ func (h *Handlers) HandleOpenAPI(w http.ResponseWriter, _ *http.Request) {
},
},
// CapStateExport-gated endpoints
+ "/state": map[string]any{"get": map[string]any{
+ "summary": "Read current browser state for a tab",
+ "description": security["stateExport"].Message,
+ "x-pinchtab-enabled": security["stateExport"].Enabled,
+ }, "delete": map[string]any{
+ "summary": "Delete a saved state file",
+ "description": security["stateExport"].Message,
+ "x-pinchtab-enabled": security["stateExport"].Enabled,
+ }},
"/state/list": map[string]any{"get": map[string]any{
"summary": "List saved state files",
"description": security["stateExport"].Message,
@@ -173,11 +182,6 @@ func (h *Handlers) HandleOpenAPI(w http.ResponseWriter, _ *http.Request) {
"description": security["stateExport"].Message,
"x-pinchtab-enabled": security["stateExport"].Enabled,
}},
- "/state": map[string]any{"delete": map[string]any{
- "summary": "Delete a saved state file",
- "description": security["stateExport"].Message,
- "x-pinchtab-enabled": security["stateExport"].Enabled,
- }},
"/state/clean": map[string]any{"post": map[string]any{
"summary": "Clean old state files",
"description": security["stateExport"].Message,
diff --git a/internal/handlers/security.go b/internal/handlers/security.go
index d16904ec..57f6f8ac 100644
--- a/internal/handlers/security.go
+++ b/internal/handlers/security.go
@@ -84,7 +84,7 @@ func (h *Handlers) endpointSecurityStates() map[string]endpointSecurityState {
Paths: []string{
"GET /storage", "POST /storage", "DELETE /storage",
"GET /tabs/{id}/storage", "POST /tabs/{id}/storage", "DELETE /tabs/{id}/storage",
- "GET /state/list", "GET /state/show", "POST /state/save",
+ "GET /state", "GET /state/list", "GET /state/show", "POST /state/save",
"POST /state/load", "DELETE /state", "POST /state/clean",
},
},
diff --git a/internal/handlers/state.go b/internal/handlers/state.go
index 64babcaa..020ab11e 100644
--- a/internal/handlers/state.go
+++ b/internal/handlers/state.go
@@ -33,12 +33,66 @@ type tabStateResponse struct {
Actionability string `json:"actionability"`
}
+type currentBrowserStateResponse struct {
+ TabID string `json:"tabId"`
+ URL string `json:"url,omitempty"`
+ Title string `json:"title,omitempty"`
+ Origins []string `json:"origins"`
+ Cookies []state.Cookie `json:"cookies"`
+ Storage map[string]state.OriginStorage `json:"storage"`
+ Metadata map[string]interface{} `json:"metadata,omitempty"`
+}
+
+type capturedBrowserState struct {
+ tabID string
+ url string
+ title string
+ file *state.StateFile
+}
+
func (h *Handlers) stateExportEnabled() bool {
return h != nil && h.Config != nil && h.Config.AllowStateExport
}
+// HandleStateCurrent returns the current gated browser state for a tab.
+func (h *Handlers) HandleStateCurrent(w http.ResponseWriter, r *http.Request) {
+ if !h.ensureStateExportEnabled(w) {
+ return
+ }
+
+ tabID := r.URL.Query().Get("tabId")
+ ctx, resolvedTabID, err := h.tabContext(r, tabID)
+ if err != nil {
+ WriteTabContextError(w, err, 404)
+ return
+ }
+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {
+ return
+ }
+
+ captured, err := h.captureBrowserState(ctx, resolvedTabID, nil)
+ if err != nil {
+ httpx.Error(w, 500, fmt.Errorf("capture state: %w", err))
+ return
+ }
+
+ httpx.JSON(w, 200, currentBrowserStateResponse{
+ TabID: captured.tabID,
+ URL: captured.url,
+ Title: captured.title,
+ Origins: captured.file.Origins,
+ Cookies: captured.file.Cookies,
+ Storage: captured.file.Storage,
+ Metadata: captured.file.Metadata,
+ })
+}
+
// HandleStateList lists all saved state files.
func (h *Handlers) HandleStateList(w http.ResponseWriter, r *http.Request) {
+ if !h.ensureStateExportEnabled(w) {
+ return
+ }
+
entries, err := state.List(h.Config.StateDir)
if err != nil {
httpx.Error(w, 500, fmt.Errorf("list states: %w", err))
@@ -52,10 +106,7 @@ func (h *Handlers) HandleStateList(w http.ResponseWriter, r *http.Request) {
// HandleStateShow returns the full contents of a saved state file.
func (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{
- "setting": "security.allowStateExport",
- })
+ if !h.ensureStateExportEnabled(w) {
return
}
@@ -84,10 +135,7 @@ type stateSaveRequest struct {
// 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{
- "setting": "security.allowStateExport",
- })
+ if !h.ensureStateExportEnabled(w) {
return
}
@@ -115,118 +163,13 @@ func (h *Handlers) HandleStateSave(w http.ResponseWriter, r *http.Request) {
return
}
- tCtx, tCancel := context.WithTimeout(ctx, 30*time.Second)
- defer tCancel()
-
- var cookies []*network.Cookie
- if err := chromedp.Run(tCtx, chromedp.ActionFunc(func(ctx context.Context) error {
- var err error
- cookies, err = network.GetCookies().Do(ctx)
- return err
- })); err != nil {
- httpx.Error(w, 500, fmt.Errorf("get cookies: %w", err))
- return
- }
-
- storageScript := `
- (function() {
- try {
- var localEntries = {};
- for (var i = 0; i < localStorage.length; i++) {
- var k = localStorage.key(i);
- localEntries[k] = localStorage.getItem(k);
- }
- var sessionEntries = {};
- for (var i = 0; i < sessionStorage.length; i++) {
- var k = sessionStorage.key(i);
- sessionEntries[k] = sessionStorage.getItem(k);
- }
- return JSON.stringify({
- local: localEntries,
- session: sessionEntries,
- url: window.location.href,
- origin: window.location.origin,
- userAgent: navigator.userAgent
- });
- } catch(e) {
- return JSON.stringify({
- error: e.message,
- local: {},
- session: {},
- url: window.location.href,
- origin: window.location.origin,
- userAgent: navigator.userAgent
- });
- }
- })()
- `
-
- var storageJSON string
- if err := chromedp.Run(tCtx, chromedp.Evaluate(storageScript, &storageJSON)); err != nil {
- httpx.Error(w, 500, fmt.Errorf("evaluate storage: %w", err))
- return
- }
-
- var storageResult struct {
- Local map[string]string `json:"local"`
- Session map[string]string `json:"session"`
- URL string `json:"url"`
- Origin string `json:"origin"`
- UserAgent string `json:"userAgent"`
- Error string `json:"error"`
- }
- if err := json.Unmarshal([]byte(storageJSON), &storageResult); err != nil {
- httpx.Error(w, 500, fmt.Errorf("parse storage result: %w", err))
+ captured, err := h.captureBrowserState(ctx, resolvedTabID, req.Metadata)
+ if err != nil {
+ httpx.Error(w, 500, fmt.Errorf("capture state: %w", err))
return
}
-
- stateCookies := make([]state.Cookie, len(cookies))
- for i, c := range cookies {
- stateCookies[i] = state.Cookie{
- Name: c.Name,
- Value: c.Value,
- Domain: c.Domain,
- Path: c.Path,
- Secure: c.Secure,
- HTTPOnly: c.HTTPOnly,
- SameSite: c.SameSite.String(),
- Expires: c.Expires,
- }
- }
- if storageResult.Local == nil {
- storageResult.Local = map[string]string{}
- }
- if storageResult.Session == nil {
- storageResult.Session = map[string]string{}
- }
-
- origins := []string{}
- if storageResult.Origin != "" {
- origins = append(origins, storageResult.Origin)
- }
-
- metadata := map[string]interface{}{
- "url": storageResult.URL,
- "origin": storageResult.Origin,
- "userAgent": storageResult.UserAgent,
- }
- for k, v := range req.Metadata {
- metadata[k] = v
- }
-
- sf := &state.StateFile{
- Name: req.Name,
- SavedAt: time.Now(),
- Origins: origins,
- Cookies: stateCookies,
- Storage: map[string]state.OriginStorage{
- storageResult.Origin: {
- Local: storageResult.Local,
- Session: storageResult.Session,
- },
- },
- Metadata: metadata,
- }
+ sf := captured.file
+ sf.Name = req.Name
path, err := state.Save(h.Config.StateDir, sf, encryptionKey)
if err != nil {
@@ -237,8 +180,8 @@ func (h *Handlers) HandleStateSave(w http.ResponseWriter, r *http.Request) {
slog.Info("state saved",
"name", sf.Name,
"path", path,
- "cookies", len(stateCookies),
- "origin", storageResult.Origin,
+ "cookies", len(sf.Cookies),
+ "origin", firstOrigin(sf.Origins),
"encrypted", req.Encrypt,
"tabId", resolvedTabID,
"remoteAddr", r.RemoteAddr,
@@ -247,14 +190,18 @@ func (h *Handlers) HandleStateSave(w http.ResponseWriter, r *http.Request) {
httpx.JSON(w, 200, map[string]any{
"name": sf.Name,
"path": path,
- "cookies": len(stateCookies),
- "origins": origins,
+ "cookies": len(sf.Cookies),
+ "origins": sf.Origins,
"encrypted": req.Encrypt,
})
}
// HandleStateLoad reads a state file and restores cookies and storage.
func (h *Handlers) HandleStateLoad(w http.ResponseWriter, r *http.Request) {
+ if !h.ensureStateExportEnabled(w) {
+ return
+ }
+
var req struct {
Name string `json:"name"`
TabID string `json:"tabId"`
@@ -370,8 +317,142 @@ func (h *Handlers) HandleStateLoad(w http.ResponseWriter, r *http.Request) {
})
}
+func (h *Handlers) captureBrowserState(ctx context.Context, resolvedTabID string, extraMetadata map[string]interface{}) (*capturedBrowserState, error) {
+ tCtx, tCancel := context.WithTimeout(ctx, 30*time.Second)
+ defer tCancel()
+
+ var cookies []*network.Cookie
+ if err := chromedp.Run(tCtx, chromedp.ActionFunc(func(ctx context.Context) error {
+ var err error
+ cookies, err = network.GetCookies().Do(ctx)
+ return err
+ })); err != nil {
+ return nil, fmt.Errorf("get cookies: %w", err)
+ }
+
+ storageScript := `
+ (function() {
+ try {
+ var localEntries = {};
+ for (var i = 0; i < localStorage.length; i++) {
+ var k = localStorage.key(i);
+ localEntries[k] = localStorage.getItem(k);
+ }
+ var sessionEntries = {};
+ for (var i = 0; i < sessionStorage.length; i++) {
+ var k = sessionStorage.key(i);
+ sessionEntries[k] = sessionStorage.getItem(k);
+ }
+ return JSON.stringify({
+ local: localEntries,
+ session: sessionEntries,
+ url: window.location.href,
+ title: document.title,
+ origin: window.location.origin,
+ userAgent: navigator.userAgent
+ });
+ } catch(e) {
+ return JSON.stringify({
+ error: e.message,
+ local: {},
+ session: {},
+ url: window.location.href,
+ title: document.title,
+ origin: window.location.origin,
+ userAgent: navigator.userAgent
+ });
+ }
+ })()
+ `
+
+ var storageJSON string
+ if err := chromedp.Run(tCtx, chromedp.Evaluate(storageScript, &storageJSON)); err != nil {
+ return nil, fmt.Errorf("evaluate storage: %w", err)
+ }
+
+ var storageResult struct {
+ Local map[string]string `json:"local"`
+ Session map[string]string `json:"session"`
+ URL string `json:"url"`
+ Title string `json:"title"`
+ Origin string `json:"origin"`
+ UserAgent string `json:"userAgent"`
+ Error string `json:"error"`
+ }
+ if err := json.Unmarshal([]byte(storageJSON), &storageResult); err != nil {
+ return nil, fmt.Errorf("parse storage result: %w", err)
+ }
+
+ stateCookies := make([]state.Cookie, len(cookies))
+ for i, c := range cookies {
+ stateCookies[i] = state.Cookie{
+ Name: c.Name,
+ Value: c.Value,
+ Domain: c.Domain,
+ Path: c.Path,
+ Secure: c.Secure,
+ HTTPOnly: c.HTTPOnly,
+ SameSite: c.SameSite.String(),
+ Expires: c.Expires,
+ }
+ }
+ if storageResult.Local == nil {
+ storageResult.Local = map[string]string{}
+ }
+ if storageResult.Session == nil {
+ storageResult.Session = map[string]string{}
+ }
+
+ origins := []string{}
+ storageMap := map[string]state.OriginStorage{}
+ if storageResult.Origin != "" {
+ origins = append(origins, storageResult.Origin)
+ storageMap[storageResult.Origin] = state.OriginStorage{
+ Local: storageResult.Local,
+ Session: storageResult.Session,
+ }
+ }
+
+ metadata := map[string]interface{}{
+ "url": storageResult.URL,
+ "title": storageResult.Title,
+ "origin": storageResult.Origin,
+ "userAgent": storageResult.UserAgent,
+ }
+ if storageResult.Error != "" {
+ metadata["storageError"] = storageResult.Error
+ }
+ for k, v := range extraMetadata {
+ metadata[k] = v
+ }
+
+ return &capturedBrowserState{
+ tabID: resolvedTabID,
+ url: storageResult.URL,
+ title: storageResult.Title,
+ file: &state.StateFile{
+ SavedAt: time.Now(),
+ Origins: origins,
+ Cookies: stateCookies,
+ Storage: storageMap,
+ Metadata: metadata,
+ },
+ }, nil
+}
+
+func firstOrigin(origins []string) string {
+ if len(origins) == 0 {
+ return ""
+ }
+ return origins[0]
+}
+
// HandleStateDelete removes a saved state file.
func (h *Handlers) HandleStateDelete(w http.ResponseWriter, r *http.Request) {
+ if !h.ensureStateExportEnabled(w) {
+ return
+ }
+
name := r.URL.Query().Get("name")
if name == "" {
httpx.Error(w, 400, fmt.Errorf("name query parameter is required"))
@@ -387,6 +468,10 @@ func (h *Handlers) HandleStateDelete(w http.ResponseWriter, r *http.Request) {
// HandleStateClean removes state files older than a given duration.
func (h *Handlers) HandleStateClean(w http.ResponseWriter, r *http.Request) {
+ if !h.ensureStateExportEnabled(w) {
+ return
+ }
+
var req struct {
OlderThanHours int `json:"olderThanHours"`
}
diff --git a/internal/routes/routes.go b/internal/routes/routes.go
index 1f0b1a9c..0d47c7fe 100644
--- a/internal/routes/routes.go
+++ b/internal/routes/routes.go
@@ -148,7 +148,7 @@ var coreEndpoints = []Endpoint{
{"DELETE", "/storage", "Delete storage items", CapStateExport, true},
// State management
- {"GET", "/state", "Read tab/page state", CapNone, true},
+ {"GET", "/state", "Read current browser state", CapStateExport, false},
{"GET", "/state/list", "List saved states", CapStateExport, false},
// Capability-gated
@@ -209,6 +209,10 @@ func TabScopedRoutes() []string {
routes = append(routes, ep.TabRoute())
}
}
+ // /state is intentionally split: GET /state is capability-gated full browser
+ // state, while GET /tabs/{id}/state is the lightweight ungated tab-runtime
+ // readiness view.
+ routes = append(routes, "GET /tabs/{id}/state")
return routes
}
diff --git a/skills/pinchtab/SKILL.md b/skills/pinchtab/SKILL.md
index 4df9dbca..3d315dca 100644
--- a/skills/pinchtab/SKILL.md
+++ b/skills/pinchtab/SKILL.md
@@ -142,6 +142,11 @@ export PINCHTAB_SESSION=$(pinchtab session create --agent-id myagent)
All subsequent commands use that session's dedicated tab automatically — no `--new-tab` or `--tab <id>` needed.
+State commands that belong with tab work:
+
+- `pinchtab state [--tab <id>]` or `GET /state` — full gated browser state for one tab: cookies, current-origin storage, metadata, and tab info.
+- `GET /tabs/{id}/state` — lightweight live tab/page runtime state for readiness, dialog blocking, and actionability checks.
+
### Observation
```bash
diff --git a/skills/pinchtab/references/api.md b/skills/pinchtab/references/api.md
index 4d2fd897..665b6815 100644
--- a/skills/pinchtab/references/api.md
+++ b/skills/pinchtab/references/api.md
@@ -170,6 +170,44 @@ curl -X POST /wait -H 'Content-Type: application/json' \
-d '{"fn":"document.readyState === \"complete\"","timeout":15000}'
```
+## Inspect tab state
+
+```bash
+# Lightweight live tab/page runtime state for a tab
+curl "/tabs/TAB_ID/state"
+```
+
+Returns:
+
+- `tabId`, `url`, `title`
+- `dialogPresent` and optional `dialog`
+- `load.readyState`, `load.navigationInProgress`, optional `load.networkIdle`, and derived `load.state`
+- `actionability` as one of:
+ - `ready` — no known blocker
+ - `caution` — page is still settling/loading
+ - `blocked` — a dialog is pending and action routes should not proceed
+
+Use this when you need a cheap health/readiness probe for a tab without pulling a full accessibility snapshot.
+
+This is live tab runtime state, not the saved browser state managed by `pinchtab state ...` and the `/state/*` endpoints.
+
+## Inspect current full browser state
+
+```bash
+# Gated full state for the current tab or an explicit tabId
+curl "/state"
+curl "/state?tabId=TAB_ID"
+```
+
+Returns:
+
+- `tabId`, `url`, `title`
+- `cookies`
+- `storage` grouped by origin with `local` and `session`
+- `metadata` such as origin and user agent
+
+This is the richer low-level browser-state view and is gated by `security.allowStateExport`.
+
## Batch actions
```bash
diff --git a/skills/pinchtab/references/mcp.md b/skills/pinchtab/references/mcp.md
index 4449898a..2cb902ad 100644
--- a/skills/pinchtab/references/mcp.md
+++ b/skills/pinchtab/references/mcp.md
@@ -44,7 +44,7 @@ For Claude Desktop (`~/Library/Application Support/Claude/claude_desktop_config.
---
-## Available Tools (34 total)
+## Available Tools
All tool names are prefixed with `pinchtab_`.
@@ -141,6 +141,8 @@ The MCP surface is intentionally scoped to browser automation. The following are
If you need these capabilities in an agent workflow, use the CLI commands alongside the MCP tools, or call the PinchTab HTTP API directly.
+Saved browser state is intentionally not exposed as MCP tools right now. Use the CLI or HTTP API for `GET /state`, `pinchtab state`, and saved-state persistence operations.
+
## Untrusted Content
For MCP specifically: