Skip to content

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

refactor: drop dead MCP streaming path and pin selector-routing heuristic with tests

Luigi Agosti7de67e1daa44
diff --git a/internal/mcp/client.go b/internal/mcp/client.go
index cf04a0fa..c29823af 100644
--- a/internal/mcp/client.go
+++ b/internal/mcp/client.go
@@ -101,37 +101,6 @@ func (c *Client) Delete(ctx context.Context, path string, query url.Values) ([]b
return c.do(req)
}
-// PostStream performs a POST request and returns the response body as a
-// ReadCloser so the caller can stream large responses directly to disk.
-// The caller must close the returned body.
-func (c *Client) PostStream(ctx context.Context, path string, payload any) (io.ReadCloser, int, error) {
- var body io.Reader
- if payload != nil {
- b, err := json.Marshal(payload)
- if err != nil {
- return nil, 0, fmt.Errorf("marshal payload: %w", err)
- }
- body = bytes.NewReader(b)
- }
- req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.url(path), body)
- if err != nil {
- return nil, 0, err
- }
- if payload != nil {
- req.Header.Set("Content-Type", "application/json")
- }
- if c.Token != "" {
- req.Header.Set("Authorization", "Bearer "+c.Token)
- }
- req.Header.Set(activity.HeaderAgentID, "mcp")
- req.Header.Set(activity.HeaderPTSource, "mcp")
- resp, err := c.HTTPClient.Do(req)
- if err != nil {
- return nil, 0, fmt.Errorf("request %s %s: %w", req.Method, req.URL.Path, err)
- }
- return resp.Body, resp.StatusCode, nil
-}
-
// Post performs a POST request with a JSON body.
func (c *Client) Post(ctx context.Context, path string, payload any) ([]byte, int, error) {
var body io.Reader
diff --git a/internal/mcp/client_test.go b/internal/mcp/client_test.go
index 0307f649..b66eb87e 100644
--- a/internal/mcp/client_test.go
+++ b/internal/mcp/client_test.go
@@ -123,29 +123,6 @@ func TestClientPostNilPayload(t *testing.T) {
}
}
-func TestClientPostStreamReturnsReadableBody(t *testing.T) {
- payload := strings.Repeat("X", 64*1024)
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(200)
- _, _ = io.WriteString(w, payload)
- }))
- defer srv.Close()
-
- c := NewClient(srv.URL, "tok")
- body, code, err := c.PostStream(context.Background(), "/record/stop", nil)
- if err != nil {
- t.Fatal(err)
- }
- defer func() { _ = body.Close() }()
- if code != 200 {
- t.Fatalf("code = %d", code)
- }
- data, _ := io.ReadAll(body)
- if len(data) != len(payload) {
- t.Fatalf("read %d bytes, want %d", len(data), len(payload))
- }
-}
-
func TestClientAuthHeaderAbsentWhenNoToken(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if h := r.Header.Get("Authorization"); h != "" {
diff --git a/internal/mcp/handlers_helpers_test.go b/internal/mcp/handlers_helpers_test.go
new file mode 100644
index 00000000..621efe45
--- /dev/null
+++ b/internal/mcp/handlers_helpers_test.go
@@ -0,0 +1,55 @@
+package mcp
+
+import "testing"
+
+// looksLikeStructuredSelector decides whether an MCP client's free-form `query`
+// is passed through as a selector or wrapped as semantic `find:` text. Anything
+// passed through is parsed as CSS by default, so a false positive turns natural
+// language into an unmatchable selector. These cases pin the current boundary.
+func TestLooksLikeStructuredSelector(t *testing.T) {
+ tests := []struct {
+ name string
+ in string
+ want bool
+ }{
+ {"empty", "", false},
+ {"plain label", "Sign In", false},
+ {"plain sentence", "accept all cookies", false},
+ {"decimal number", "50.50", false},
+ {"id selector", "#submit", true},
+ {"class selector", ".btn-primary", true},
+ {"attribute selector", "[data-test=submit]", true},
+ {"xpath", "//button[@id='ok']", true},
+ {"parenthesised xpath", "(//a)[1]", true},
+ {"descendant combinator", "div > p", true},
+ {"tag dot class", "button.primary", true},
+
+ // Current behaviour: the punctuation test on line 92 has no
+ // whitespace guard, unlike the dot-notation branch below it, so
+ // prose containing these characters is routed to CSS.
+ {"prose with colon", "Sign up: it's free", true},
+ {"prose with equals", "name = value", true},
+ {"prose with plus", "Add + remove", true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := looksLikeStructuredSelector(tt.in); got != tt.want {
+ t.Errorf("looksLikeStructuredSelector(%q) = %v, want %v", tt.in, got, tt.want)
+ }
+ })
+ }
+}
+
+func TestHasKnownSelectorPrefixIsCaseInsensitive(t *testing.T) {
+ for _, in := range []string{"css:#a", "CSS:#a", "Find:submit", "NTH:2:div", " text:hello"} {
+ if !hasKnownSelectorPrefix(in) {
+ t.Errorf("hasKnownSelectorPrefix(%q) = false, want true", in)
+ }
+ }
+ for _, in := range []string{"submit", "unknownprefix:value"} {
+ if hasKnownSelectorPrefix(in) {
+ t.Errorf("hasKnownSelectorPrefix(%q) = true, want false", in)
+ }
+ }
+}
diff --git a/internal/mcp/handlers_record.go b/internal/mcp/handlers_record.go
index e8bbd098..3e07cd16 100644
--- a/internal/mcp/handlers_record.go
+++ b/internal/mcp/handlers_record.go
@@ -12,10 +12,6 @@ import (
"github.com/pinchtab/pinchtab/internal/readiness"
)
-// maxRecordFileBytes caps the output file written by record_stop to prevent
-// unbounded disk writes (matches the server-side maxOutputBytes).
-const maxRecordFileBytes = 256 << 20 // 256 MiB
-
func handleRecordStart(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {
file, err := r.RequireString("file")
@@ -189,29 +185,6 @@ func safeRecordPath(file string) (string, error) {
return cleaned, nil
}
-// streamToFile writes from r to path using O_CREATE|O_EXCL (no overwrite),
-// capped at maxRecordFileBytes. Returns the number of bytes written.
-func streamToFile(path string, r io.Reader) (int64, error) {
- f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
- if err != nil {
- return 0, err
- }
-
- n, copyErr := io.Copy(f, io.LimitReader(r, maxRecordFileBytes+1))
- if closeErr := f.Close(); closeErr != nil && copyErr == nil {
- copyErr = closeErr
- }
- if copyErr != nil {
- _ = os.Remove(path)
- return 0, copyErr
- }
- if n > maxRecordFileBytes {
- _ = os.Remove(path)
- return 0, fmt.Errorf("recording exceeds %d MiB limit", maxRecordFileBytes>>20)
- }
- return n, nil
-}
-
func handleRecordStatus(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {
body, code, err := c.Get(ctx, "/record/status", nil)
diff --git a/internal/mcp/handlers_record_test.go b/internal/mcp/handlers_record_test.go
index e3e3fc43..bb779b2e 100644
--- a/internal/mcp/handlers_record_test.go
+++ b/internal/mcp/handlers_record_test.go
@@ -81,38 +81,6 @@ func TestSafeRecordPath_RejectsNonDirectoryParent(t *testing.T) {
}
}
-func TestStreamToFile_WritesAndCaps(t *testing.T) {
- dir := t.TempDir()
- path := filepath.Join(dir, "out.gif")
-
- data := strings.NewReader("hello recording data")
- n, err := streamToFile(path, data)
- if err != nil {
- t.Fatalf("streamToFile() error = %v", err)
- }
- if n != 20 {
- t.Fatalf("wrote %d bytes, want 20", n)
- }
-
- got, _ := os.ReadFile(path)
- if string(got) != "hello recording data" {
- t.Fatalf("file content = %q", got)
- }
-}
-
-func TestStreamToFile_RefusesOverwrite(t *testing.T) {
- dir := t.TempDir()
- path := filepath.Join(dir, "out.gif")
- if err := os.WriteFile(path, []byte("existing"), 0600); err != nil {
- t.Fatal(err)
- }
-
- _, err := streamToFile(path, strings.NewReader("new data"))
- if err == nil {
- t.Fatal("expected error for existing file")
- }
-}
-
func TestRecordStartRejectsRelativePath(t *testing.T) {
srv := mockPinchTab()
defer srv.Close()