Skip to content

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

fix: a cookie the browser refused is reported as success to MCP and gives no reason to anyone, because /cookies answers 200 with only counts (PIN-228)

Luigi Agostid4feab3809a4
diff --git a/internal/cli/actions/actions_cookies.go b/internal/cli/actions/actions_cookies.go
index fa29e813..a1959d36 100644
--- a/internal/cli/actions/actions_cookies.go
+++ b/internal/cli/actions/actions_cookies.go
@@ -58,7 +58,7 @@ func CookiesSet(client *http.Client, base, token string, cmd *cobra.Command, nam
}
result := requireMap(apiclient.DoPost(client, base, token, "/cookies", body), 1, "Failed to set cookie")
- if set, ok := result["set"].(float64); ok && set < 1 {
+ if !cookieWriteConfirmed(result) {
fmt.Fprintf(os.Stderr, "ERROR: cookies: %q was not set (%v)\n", name, jsonLine(result))
os.Exit(2)
}
@@ -83,6 +83,15 @@ func printCookiesResult(cmd *cobra.Command, result map[string]any) {
fmt.Println("OK")
}
+// cookieWriteConfirmed reports whether a /cookies response proves the browser stored the
+// cookie. It fails CLOSED: an absent or unreadable "set" has not confirmed the write, which
+// is not the same as confirming it, so renaming the field breaks the command rather than
+// silently retiring the check. Separate from the exit path so the rule is testable.
+func cookieWriteConfirmed(result map[string]any) bool {
+ set, ok := result["set"].(float64)
+ return ok && set >= 1
+}
+
func jsonLine(v any) string {
out, err := json.Marshal(v)
if err != nil {
diff --git a/internal/cli/actions/actions_cookies_test.go b/internal/cli/actions/actions_cookies_test.go
index d277b98c..bf1e832a 100644
--- a/internal/cli/actions/actions_cookies_test.go
+++ b/internal/cli/actions/actions_cookies_test.go
@@ -150,3 +150,27 @@ func TestCookiesSetForwardsOnlyTheFlagsGiven(t *testing.T) {
t.Errorf("body pins a url the caller never gave (%v); the server defaults it to the tab's page", body["url"])
}
}
+
+// The confirmation must fail CLOSED. A response that cannot say how many cookies were
+// stored has not confirmed the write, and a check written as "if the field is readable AND
+// looks bad" silently retires itself the moment the field is renamed.
+func TestCookieWriteConfirmedFailsClosed(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ result map[string]any
+ want bool
+ }{
+ {name: "one stored", result: map[string]any{"set": float64(1), "total": float64(1)}, want: true},
+ {name: "nothing stored", result: map[string]any{"set": float64(0), "total": float64(1)}},
+ {name: "field absent", result: map[string]any{"status": "ok"}},
+ {name: "field renamed", result: map[string]any{"stored": float64(1)}},
+ {name: "field not a number", result: map[string]any{"set": "1"}},
+ {name: "empty response", result: map[string]any{}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := cookieWriteConfirmed(tc.result); got != tc.want {
+ t.Errorf("cookieWriteConfirmed(%v) = %v, want %v", tc.result, got, tc.want)
+ }
+ })
+ }
+}
diff --git a/internal/handlers/cookies.go b/internal/handlers/cookies.go
index 2fd92dc7..f25439e7 100644
--- a/internal/handlers/cookies.go
+++ b/internal/handlers/cookies.go
@@ -225,8 +225,13 @@ func (h *Handlers) HandleSetCookies(w http.ResponseWriter, r *http.Request) {
}
successCount := 0
- for _, cookie := range req.Cookies {
- if err := h.Bridge.SetCookie(tCtx, bridge.SetCookieParams{
+ // The reason each cookie was refused, not just how many were: a domain mismatch, an
+ // invalid SameSite and Secure-on-http are the same count and different remedies, and a
+ // caller that only learns the count cannot tell a malformed request from a retryable
+ // one. Reported per index so a multi-cookie request says WHICH.
+ failures := []map[string]any{}
+ for i, cookie := range req.Cookies {
+ err := h.Bridge.SetCookie(tCtx, bridge.SetCookieParams{
Name: cookie.Name,
Value: cookie.Value,
URL: req.URL,
@@ -236,18 +241,29 @@ func (h *Handlers) HandleSetCookies(w http.ResponseWriter, r *http.Request) {
HTTPOnly: cookie.HTTPOnly,
SameSite: cookie.SameSite,
Expires: cookie.Expires,
- }); err == nil {
+ })
+ if err == nil {
successCount++
+ continue
}
+ failures = append(failures, map[string]any{
+ "index": i,
+ "name": cookie.Name,
+ "error": err.Error(),
+ })
}
h.recordActivity(r, activity.Update{Action: "cookies.write"})
- httpx.JSON(w, 200, map[string]any{
+ result := map[string]any{
"set": successCount,
"failed": len(req.Cookies) - successCount,
"total": len(req.Cookies),
- })
+ }
+ if len(failures) > 0 {
+ result["failures"] = failures
+ }
+ httpx.JSON(w, 200, result)
}
// HandleTabSetCookies sets cookies for a tab identified by path ID.
diff --git a/internal/handlers/cookies_failure_reason_test.go b/internal/handlers/cookies_failure_reason_test.go
new file mode 100644
index 00000000..a14c1c62
--- /dev/null
+++ b/internal/handlers/cookies_failure_reason_test.go
@@ -0,0 +1,102 @@
+package handlers
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+// refusingCookieBridge stores nothing and says why, which is what CDP does for a domain
+// mismatch, an invalid SameSite or Secure on a plain-http URL.
+type refusingCookieBridge struct {
+ *mockBridge
+ reason string
+}
+
+func (b *refusingCookieBridge) SetCookie(context.Context, bridge.SetCookieParams) error {
+ return errCookieRefused{b.reason}
+}
+
+func (b *refusingCookieBridge) CurrentURL(context.Context) (string, error) {
+ return "https://example.com/", nil
+}
+
+type errCookieRefused struct{ reason string }
+
+func (e errCookieRefused) Error() string { return e.reason }
+
+// The counts alone are not actionable: a domain mismatch, an invalid SameSite and
+// Secure-on-http are all "failed: 1" and want three different corrections. A caller that
+// learns only the count cannot tell a malformed request from a retryable one, and both the
+// CLI and the MCP tool can only report what the endpoint says.
+func TestHandleSetCookies_ReportsWhyACookieWasRefused(t *testing.T) {
+ h := New(&refusingCookieBridge{mockBridge: &mockBridge{}, reason: "invalid sameSite value"},
+ &config.RuntimeConfig{AllowCookies: true}, nil, nil, nil)
+
+ body := `{"cookies":[{"name":"sid","value":"abc","sameSite":"Sometimes"}]}`
+ req := httptest.NewRequest("POST", "/cookies", strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+
+ h.HandleSetCookies(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200: %s", w.Code, w.Body.String())
+ }
+ var got struct {
+ Set int `json:"set"`
+ Failed int `json:"failed"`
+ Total int `json:"total"`
+ Failures []struct {
+ Index int `json:"index"`
+ Name string `json:"name"`
+ Error string `json:"error"`
+ } `json:"failures"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
+ t.Fatal(err)
+ }
+
+ if got.Set != 0 || got.Failed != 1 || got.Total != 1 {
+ t.Errorf("counts = set %d failed %d total %d, want 0/1/1", got.Set, got.Failed, got.Total)
+ }
+ if len(got.Failures) != 1 {
+ t.Fatalf("failures = %+v, want one entry naming the refused cookie", got.Failures)
+ }
+ if got.Failures[0].Name != "sid" || got.Failures[0].Index != 0 {
+ t.Errorf("failure = %+v, want index 0 and name sid so a multi-cookie request says which", got.Failures[0])
+ }
+ if !strings.Contains(got.Failures[0].Error, "invalid sameSite value") {
+ t.Errorf("failure error = %q, want the reason the browser gave", got.Failures[0].Error)
+ }
+}
+
+// A request where everything landed must not carry an empty failures array — a caller
+// checking for the key's presence would read that as a partial failure.
+func TestHandleSetCookies_OmitsFailuresWhenEveryCookieLands(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{AllowCookies: true}, nil, nil, nil)
+
+ body := `{"url":"https://example.com/","cookies":[{"name":"sid","value":"abc"}]}`
+ req := httptest.NewRequest("POST", "/cookies", strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+
+ h.HandleSetCookies(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200: %s", w.Code, w.Body.String())
+ }
+ var got map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
+ t.Fatal(err)
+ }
+ if _, present := got["failures"]; present {
+ t.Errorf("response carries a failures key with nothing wrong: %s", w.Body.String())
+ }
+}
diff --git a/internal/mcp/cookies_set_report_test.go b/internal/mcp/cookies_set_report_test.go
new file mode 100644
index 00000000..034ee086
--- /dev/null
+++ b/internal/mcp/cookies_set_report_test.go
@@ -0,0 +1,120 @@
+package mcp
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+// The WIRING, not the helper: reverting only the call site leaves the table below green, so
+// the confirmation has to be asserted through the tool. A 200 carrying set:0 must reach the
+// agent as an error result.
+func TestCookiesSetToolReportsAnUnstoredCookieAsAnError(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ respBody string
+ wantErr bool
+ }{
+ {name: "stored", respBody: `{"set":1,"failed":0,"total":1}`},
+ {
+ name: "not stored",
+ respBody: `{"set":0,"failed":1,"total":1,"failures":[{"index":0,"name":"sid","error":"invalid sameSite value"}]}`,
+ wantErr: true,
+ },
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(tc.respBody))
+ }))
+ defer srv.Close()
+
+ r := callTool(t, "pinchtab_cookies_set", map[string]any{"name": "sid", "value": "abc"}, srv)
+
+ if tc.wantErr {
+ if !r.IsError {
+ t.Fatalf("tool reported success for %s — the agent cannot tell the cookie was never stored", tc.respBody)
+ }
+ if text := resultText(t, r); !strings.Contains(text, "invalid sameSite value") {
+ t.Errorf("error text = %q, want the reason the browser gave", text)
+ }
+ return
+ }
+ if r.IsError {
+ t.Fatalf("tool reported an error for a stored cookie: %s", resultText(t, r))
+ }
+ })
+ }
+}
+
+// /cookies answers 200 whether or not the browser stored anything, and resultFromBytes only
+// treats HTTP >= 400 as an error — so without this check the tool reports a cookie that was
+// never set as a success. MCP is the surface where nothing reads the body afterwards, so the
+// confirmation has to happen in the handler.
+func TestUnsetCookieReportConfirmsTheWrite(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ body string
+ wantUnse bool
+ wantSays string
+ }{
+ {
+ name: "every cookie stored",
+ body: `{"set":1,"failed":0,"total":1}`,
+ },
+ {
+ name: "several stored",
+ body: `{"set":3,"failed":0,"total":3}`,
+ },
+ {
+ name: "nothing stored, reason given",
+ body: `{"set":0,"failed":1,"total":1,"failures":[{"index":0,"name":"sid","error":"invalid sameSite value"}]}`,
+ wantUnse: true,
+ wantSays: "invalid sameSite value",
+ },
+ {
+ name: "nothing stored, no reason",
+ body: `{"set":0,"failed":1,"total":1}`,
+ wantUnse: true,
+ wantSays: "no reason given",
+ },
+ {
+ name: "partially stored",
+ body: `{"set":1,"failed":1,"total":2}`,
+ wantUnse: true,
+ wantSays: "1 of 2",
+ },
+ {
+ // Fails CLOSED. A response that cannot say how many landed has confirmed
+ // nothing, and renaming the field must break the check rather than retire it.
+ name: "counts absent",
+ body: `{"status":"ok"}`,
+ wantUnse: true,
+ wantSays: "did not report",
+ },
+ {
+ name: "unreadable",
+ body: `not json`,
+ wantUnse: true,
+ wantSays: "unreadable",
+ },
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ got := unsetCookieReport([]byte(tc.body))
+
+ if !tc.wantUnse {
+ if got != "" {
+ t.Fatalf("reported %q for a response showing every cookie stored", got)
+ }
+ return
+ }
+ if got == "" {
+ t.Fatalf("reported success for %s — an unconfirmed write reads as a stored cookie", tc.body)
+ }
+ if !strings.Contains(got, tc.wantSays) {
+ t.Errorf("reason = %q, want it to mention %q so the agent knows what to change", got, tc.wantSays)
+ }
+ })
+ }
+}
diff --git a/internal/mcp/handlers_tabs.go b/internal/mcp/handlers_tabs.go
index c31263ab..9c6fecd9 100644
--- a/internal/mcp/handlers_tabs.go
+++ b/internal/mcp/handlers_tabs.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"net/url"
+ "strings"
"github.com/mark3labs/mcp-go/mcp"
)
@@ -102,10 +103,43 @@ func handleCookiesSet(c *Client) func(context.Context, mcp.CallToolRequest) (*mc
if err != nil {
return mcp.NewToolResultError(err.Error()), nil
}
+ // /cookies answers 200 whether or not the browser stored anything, so
+ // resultFromBytes alone would report a cookie that was never set as a success —
+ // and this is the surface where nothing reads the body afterwards.
+ if unset := unsetCookieReport(respBody); unset != "" {
+ return mcp.NewToolResultError(fmt.Sprintf("cookie %q was not set: %s", name, unset)), nil
+ }
return resultFromBytes(respBody, code)
}
}
+// unsetCookieReport returns a reason when a /cookies response shows fewer cookies stored
+// than were sent, or "" when every one landed. A response it cannot read counts as unset:
+// the point is to confirm the write, and an unparseable answer confirms nothing.
+func unsetCookieReport(respBody []byte) string {
+ var resp struct {
+ Set *int `json:"set"`
+ Total *int `json:"total"`
+ Failures []struct {
+ Name string `json:"name"`
+ Error string `json:"error"`
+ } `json:"failures"`
+ }
+ if err := json.Unmarshal(respBody, &resp); err != nil {
+ return fmt.Sprintf("unreadable response: %s", strings.TrimSpace(string(respBody)))
+ }
+ if resp.Set == nil || resp.Total == nil {
+ return fmt.Sprintf("response did not report how many cookies were set: %s", strings.TrimSpace(string(respBody)))
+ }
+ if *resp.Set >= *resp.Total {
+ return ""
+ }
+ if len(resp.Failures) > 0 {
+ return resp.Failures[0].Error
+ }
+ return fmt.Sprintf("%d of %d stored, with no reason given", *resp.Set, *resp.Total)
+}
+
func handleConnectProfile(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {
profile, err := r.RequireString("profile")