High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
chore: add awaitPromise coverage and docs for /evaluate
Luigi Agosticb70c8a0ba45
diff --git a/README.md b/README.mdindex 85fa7f8f..da9b8a13 100644--- a/README.md+++ b/README.md@@ -327,12 +327,6 @@ PinchTab is a fully open-source, local-first tool. No telemetry, no analytics, aFull docs at **[pinchtab.com/docs](https://pinchtab.com/docs)**-### MCP (SMCP) integration--An **SMCP plugin** in this repo lets AI agents control PinchTab via the [Model Context Protocol](https://github.com/sanctumos/smcp) (SMCP). One plugin exposes 15 tools (e.g. `pinchtab__navigate`, `pinchtab__snapshot`, `pinchtab__action`). No extra runtime deps (stdlib only). See **[plugins/README.md](plugins/README.md)** for setup (env vars and paths).------## Examples### AI Agent Automationdiff --git a/internal/handlers/evaluate.go b/internal/handlers/evaluate.goindex 7b64bb67..168ddd9a 100644--- a/internal/handlers/evaluate.go+++ b/internal/handlers/evaluate.go@@ -70,7 +70,7 @@ func (h *Handlers) HandleEvaluate(w http.ResponseWriter, r *http.Request) {return p.WithAwaitPromise(true)})}- if err := chromedp.Run(tCtx, chromedp.Evaluate(req.Expression, &result, opts...)); err != nil {+ if err := h.evalRuntime(tCtx, req.Expression, &result, opts...); err != nil {httpx.Error(w, 500, fmt.Errorf("evaluate: %w", err))return}diff --git a/internal/handlers/evaluate_test.go b/internal/handlers/evaluate_test.goindex 6e08a3a7..9305a8b9 100644--- a/internal/handlers/evaluate_test.go+++ b/internal/handlers/evaluate_test.go@@ -2,9 +2,14 @@ package handlersimport ("bytes"+ "context"+ "encoding/json""net/http/httptest""testing"+ "time"+ "github.com/chromedp/cdproto/runtime"+ "github.com/chromedp/chromedp""github.com/pinchtab/pinchtab/internal/config")@@ -70,3 +75,114 @@ func TestHandleTabEvaluate_Disabled(t *testing.T) {t.Errorf("expected 403, got %d", w.Code)}}++func TestHandleEvaluateAwaitPromiseOption(t *testing.T) {+ tests := []struct {+ name string+ body string+ wantAwait bool+ wantResponse string+ }{+ {+ name: "default disabled",+ body: `{"expression":"Promise.resolve(\"ok\")"}`,+ wantAwait: false,+ wantResponse: `"result":"sync"`,+ },+ {+ name: "enabled when requested",+ body: `{"expression":"Promise.resolve(\"ok\")","awaitPromise":true}`,+ wantAwait: true,+ wantResponse: `"result":"awaited"`,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{+ AllowEvaluate: true,+ ActionTimeout: time.Second,+ }, nil, nil, nil)++ h.evalRuntime = func(_ context.Context, expression string, out any, opts ...chromedp.EvaluateOption) error {+ if expression != `Promise.resolve("ok")` {+ t.Fatalf("unexpected expression: %s", expression)+ }++ params := runtime.Evaluate(expression)+ for _, opt := range opts {+ params = opt(params)+ }+ if params.AwaitPromise != tt.wantAwait {+ t.Fatalf("expected awaitPromise=%v, got %v", tt.wantAwait, params.AwaitPromise)+ }++ ptr, ok := out.(*any)+ if !ok {+ t.Fatalf("expected *any output, got %T", out)+ }+ if tt.wantAwait {+ *ptr = "awaited"+ } else {+ *ptr = "sync"+ }+ return nil+ }++ req := httptest.NewRequest("POST", "/evaluate", bytes.NewReader([]byte(tt.body)))+ w := httptest.NewRecorder()+ h.HandleEvaluate(w, req)++ if w.Code != 200 {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ if !bytes.Contains(w.Body.Bytes(), []byte(tt.wantResponse)) {+ t.Fatalf("expected response to contain %s, got %s", tt.wantResponse, w.Body.String())+ }+ })+ }+}++func TestHandleTabEvaluateForwardsAwaitPromise(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{+ AllowEvaluate: true,+ ActionTimeout: time.Second,+ }, nil, nil, nil)++ h.evalRuntime = func(_ context.Context, expression string, out any, opts ...chromedp.EvaluateOption) error {+ if expression != `Promise.resolve(1)` {+ t.Fatalf("unexpected expression: %s", expression)+ }+ params := runtime.Evaluate(expression)+ for _, opt := range opts {+ params = opt(params)+ }+ if !params.AwaitPromise {+ t.Fatalf("expected awaitPromise to be forwarded for tab evaluate route")+ }++ ptr, ok := out.(*any)+ if !ok {+ t.Fatalf("expected *any output, got %T", out)+ }+ *ptr = 1+ return nil+ }++ req := httptest.NewRequest("POST", "/tabs/tab_abc/evaluate", bytes.NewReader([]byte(`{"expression":"Promise.resolve(1)","awaitPromise":true}`)))+ req.SetPathValue("id", "tab_abc")+ w := httptest.NewRecorder()+ h.HandleTabEvaluate(w, req)++ if w.Code != 200 {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }++ var payload map[string]any+ if err := json.Unmarshal(w.Body.Bytes(), &payload); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if payload["result"] != float64(1) {+ t.Fatalf("expected result 1, got %#v", payload["result"])+ }+}diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.goindex d005a470..19ff56aa 100644--- a/internal/handlers/handlers.go+++ b/internal/handlers/handlers.go@@ -36,7 +36,8 @@ type Handlers struct {clipboard clipboardStore// Optional dependency injection (for unit testing)- evalJS func(ctx context.Context, expression string, out *string) error+ evalJS func(ctx context.Context, expression string, out *string) error+ evalRuntime func(ctx context.Context, expression string, out any, opts ...chromedp.EvaluateOption) error}func New(b bridge.BridgeAPI, cfg *config.RuntimeConfig, p bridge.ProfileService, d *dashboard.Dashboard, o bridge.OrchestratorService) *Handlers {@@ -95,6 +96,9 @@ func New(b bridge.BridgeAPI, cfg *config.RuntimeConfig, p bridge.ProfileService,h.evalJS = func(ctx context.Context, expression string, out *string) error {return chromedp.Run(ctx, chromedp.Evaluate(expression, out))}+ h.evalRuntime = func(ctx context.Context, expression string, out any, opts ...chromedp.EvaluateOption) error {+ return chromedp.Run(ctx, chromedp.Evaluate(expression, out, opts...))+ }// Clean up .tmp export files orphaned by a previous crash.go CleanupStaleTmpExports(cfg.StateDir)diff --git a/internal/handlers/handlers_test.go b/internal/handlers/handlers_test.goindex 4641e74f..6fd7bbad 100644--- a/internal/handlers/handlers_test.go+++ b/internal/handlers/handlers_test.go@@ -209,6 +209,51 @@ func TestOpenAPIIncludesSensitiveEndpointStatus(t *testing.T) {}}+func TestOpenAPIIncludesEvaluateAwaitPromiseSchema(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{AllowEvaluate: true}, nil, nil, nil)++ req := httptest.NewRequest("GET", "/openapi.json", nil)+ w := httptest.NewRecorder()+ h.HandleOpenAPI(w, req)++ if w.Code != 200 {+ t.Fatalf("expected 200 from /openapi.json, got %d", w.Code)+ }++ var doc map[string]any+ if err := json.Unmarshal(w.Body.Bytes(), &doc); err != nil {+ t.Fatalf("unmarshal openapi: %v", err)+ }++ paths, ok := doc["paths"].(map[string]any)+ if !ok {+ t.Fatalf("expected paths object, got %T", doc["paths"])+ }+ evaluatePath, ok := paths["/evaluate"].(map[string]any)+ if !ok {+ t.Fatalf("expected /evaluate path, got %T", paths["/evaluate"])+ }+ post, ok := evaluatePath["post"].(map[string]any)+ if !ok {+ t.Fatalf("expected /evaluate POST operation, got %T", evaluatePath["post"])+ }+ requestBody, ok := post["requestBody"].(map[string]any)+ if !ok {+ t.Fatalf("expected requestBody, got %T", post["requestBody"])+ }+ content := requestBody["content"].(map[string]any)+ appJSON := content["application/json"].(map[string]any)+ schema := appJSON["schema"].(map[string]any)+ properties := schema["properties"].(map[string]any)+ awaitPromise, ok := properties["awaitPromise"].(map[string]any)+ if !ok {+ t.Fatalf("expected awaitPromise property, got %T", properties["awaitPromise"])+ }+ if awaitPromise["type"] != "boolean" {+ t.Fatalf("expected awaitPromise type boolean, got %#v", awaitPromise["type"])+ }+}+func TestHandleNavigate(t *testing.T) {stubNavigateHostResolution(t, func(context.Context, string, string) ([]net.IP, error) {return []net.IP{net.ParseIP("93.184.216.34")}, nildiff --git a/internal/handlers/openapi.go b/internal/handlers/openapi.goindex 36742671..c82fa4ec 100644--- a/internal/handlers/openapi.go+++ b/internal/handlers/openapi.go@@ -8,6 +8,31 @@ import (func (h *Handlers) HandleOpenAPI(w http.ResponseWriter, _ *http.Request) {security := h.endpointSecurityStates()+ evaluateRequestBody := map[string]any{+ "required": true,+ "content": map[string]any{+ "application/json": map[string]any{+ "schema": map[string]any{+ "type": "object",+ "properties": map[string]any{+ "tabId": map[string]any{+ "type": "string",+ "description": "Optional tab ID for top-level /evaluate requests",+ },+ "expression": map[string]any{+ "type": "string",+ "description": "JavaScript expression to evaluate",+ },+ "awaitPromise": map[string]any{+ "type": "boolean",+ "description": "Wait for a returned promise to resolve before returning the result",+ },+ },+ "required": []string{"expression"},+ },+ },+ },+ }httpx.JSON(w, 200, map[string]any{"openapi": "3.0.0","info": map[string]any{@@ -30,11 +55,13 @@ func (h *Handlers) HandleOpenAPI(w http.ResponseWriter, _ *http.Request) {"/evaluate": map[string]any{"post": map[string]any{"summary": "Run JavaScript in the current tab","description": security["evaluate"].Message,+ "requestBody": evaluateRequestBody,"x-pinchtab-enabled": security["evaluate"].Enabled,}},"/tabs/{id}/evaluate": map[string]any{"post": map[string]any{"summary": "Run JavaScript in a specific tab","description": security["evaluate"].Message,+ "requestBody": evaluateRequestBody,"x-pinchtab-enabled": security["evaluate"].Enabled,}},"/macro": map[string]any{"post": map[string]any{diff --git a/skills/pinchtab/references/api.md b/skills/pinchtab/references/api.mdindex 1217a7b3..f7d28090 100644--- a/skills/pinchtab/references/api.md+++ b/skills/pinchtab/references/api.md@@ -265,8 +265,14 @@ Default to read-only DOM inspection and avoid reading cookies, localStorage, or# CLI: pinchtab eval "document.title"curl -X POST /evaluate -H 'Content-Type: application/json' \-d '{"expression": "document.title"}'++# Resolve a returned promise before responding+curl -X POST /evaluate -H 'Content-Type: application/json' \+ -d '{"expression": "Promise.resolve(document.title)", "awaitPromise": true}'```+Set `awaitPromise: true` when the expression returns a promise and you want the resolved value. If omitted, behavior stays unchanged.+## Tab management```bash