High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
feat(eval): hint --await-promise when an un-awaited eval returns a Promise instead of silently returning {} (PIN-410)
Luigi Agostidc555a587e91
diff --git a/internal/bridge/evaluate.go b/internal/bridge/evaluate.goindex 558a955c..40dd6e64 100644--- a/internal/bridge/evaluate.go+++ b/internal/bridge/evaluate.go@@ -2,6 +2,7 @@ package bridgeimport ("context"+ "encoding/json""github.com/chromedp/cdproto/runtime""github.com/chromedp/chromedp"@@ -16,3 +17,37 @@ func (b *Bridge) Evaluate(ctx context.Context, expression string, result any, op}return chromedp.Run(ctx, chromedp.Evaluate(expression, result, chromedpOpts...))}++// EvaluateSubtype runs expression like Evaluate but also reports the returned+// RemoteObject's subtype (e.g. "promise"), which chromedp.Evaluate's by-value+// decode throws away. A Promise returned without AwaitPromise serialises to an+// empty object, so the subtype is the only thing that tells it apart from a+// genuine empty object — letting the caller hint --await-promise instead of+// silently handing back {}. The value decode and exception handling mirror+// chromedp.Evaluate, so behaviour is otherwise unchanged.+func (b *Bridge) EvaluateSubtype(ctx context.Context, expression string, result any, opts EvalOpts) (string, error) {+ var subtype string+ err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {+ p := runtime.Evaluate(expression).WithReturnByValue(true)+ if opts.AwaitPromise {+ p = p.WithAwaitPromise(true)+ }+ obj, exc, err := p.Do(ctx)+ if err != nil {+ return err+ }+ if exc != nil {+ return exc+ }+ subtype = string(obj.Subtype)+ if result == nil {+ return nil+ }+ value := []byte(obj.Value)+ if len(value) == 0 {+ value = []byte("null")+ }+ return json.Unmarshal(value, result)+ }))+ return subtype, err+}diff --git a/internal/cli/actions/actions_evaluate.go b/internal/cli/actions/actions_evaluate.goindex 787e7c8d..d825655d 100644--- a/internal/cli/actions/actions_evaluate.go+++ b/internal/cli/actions/actions_evaluate.go@@ -7,6 +7,7 @@ import ("strings""github.com/pinchtab/pinchtab/internal/cli/apiclient"+ "github.com/pinchtab/pinchtab/internal/cli/output""github.com/spf13/cobra")@@ -45,4 +46,9 @@ func Evaluate(client *http.Client, base, token string, args []string, cmd *cobra}}}+ // A Promise returned without --await-promise prints {} on stdout; the hint on+ // stderr keeps stdout parseable while telling the caller why it was empty.+ if hint, ok := result["hint"].(string); ok && hint != "" {+ output.Hint(hint)+ }}diff --git a/internal/handlers/evaluate.go b/internal/handlers/evaluate.goindex 871a9521..c7bd9bda 100644--- a/internal/handlers/evaluate.go+++ b/internal/handlers/evaluate.go@@ -57,8 +57,18 @@ func (h *Handlers) HandleEvaluate(w http.ResponseWriter, r *http.Request) {)var result any+ var subtype stringopts := bridge.EvalOpts{AwaitPromise: req.AwaitPromise}- if err := h.evalRuntime(tCtx, req.Expression, &result, opts); err != nil {+ // The subtype-aware path exists only on a live bridge; a runtime without it+ // falls back to the plain eval and simply gets no Promise hint. bridgeAs looks+ // through a decorator (e.g. the ghost-chrome adapter) to the underlying bridge.+ var err error+ if se, ok := bridgeAs[subtypeEvaluator](h.Bridge); ok {+ subtype, err = se.EvaluateSubtype(tCtx, req.Expression, &result, opts)+ } else {+ err = h.evalRuntime(tCtx, req.Expression, &result, opts)+ }+ if err != nil {errMsg := err.Error()if strings.Contains(errMsg, "Cannot read properties of null") ||strings.Contains(errMsg, "Cannot read property") ||@@ -74,7 +84,24 @@ func (h *Handlers) HandleEvaluate(w http.ResponseWriter, r *http.Request) {h.recordActivity(r, activity.Update{Action: "evaluate"})- httpx.JSON(w, 200, map[string]any{"result": result})+ resp := map[string]any{"result": result}+ // A Promise returned without awaitPromise decodes to {} with no other signal;+ // name the flag rather than let the empty object read as a successful result.+ if !req.AwaitPromise && subtype == evalPromiseSubtype {+ resp["hint"] = "the expression returned a Promise; re-run with awaitPromise:true (CLI --await-promise) to resolve its value"+ }+ httpx.JSON(w, 200, resp)+}++// evalPromiseSubtype is the RemoteObject subtype a Promise carries (CDP+// runtime.Subtype "promise").+const evalPromiseSubtype = "promise"++// subtypeEvaluator is the optional bridge capability that reports a result's+// RemoteObject subtype alongside its value, so HandleEvaluate can tell a+// Promise apart from a genuine empty object. *bridge.Bridge implements it.+type subtypeEvaluator interface {+ EvaluateSubtype(ctx context.Context, expression string, result any, opts bridge.EvalOpts) (string, error)}// HandleTabEvaluate runs JavaScript in a tab identified by path ID.diff --git a/internal/handlers/evaluate_promise_test.go b/internal/handlers/evaluate_promise_test.gonew file mode 100644index 00000000..d5cc3cc0--- /dev/null+++ b/internal/handlers/evaluate_promise_test.go@@ -0,0 +1,90 @@+package handlers++import (+ "bytes"+ "context"+ "encoding/json"+ "net/http/httptest"+ "testing"+ "time"++ "github.com/pinchtab/pinchtab/internal/bridge"+ "github.com/pinchtab/pinchtab/internal/config"+)++// subtypeMockBridge implements the optional subtypeEvaluator capability so the+// handler takes its Promise-detecting path. The value/subtype are canned per+// test; the embedded mockBridge supplies the rest of the BridgeAPI surface+// (tab context, browser readiness) HandleEvaluate needs.+type subtypeMockBridge struct {+ *mockBridge+ subtype string+ value any+}++func (m *subtypeMockBridge) EvaluateSubtype(_ context.Context, _ string, result any, _ bridge.EvalOpts) (string, error) {+ if ptr, ok := result.(*any); ok {+ *ptr = m.value+ }+ return m.subtype, nil+}++func evalResponse(t *testing.T, br bridge.BridgeAPI, body string) map[string]any {+ t.Helper()+ h := New(br, &config.RuntimeConfig{AllowEvaluate: true, ActionTimeout: time.Second}, nil, nil, nil)+ req := httptest.NewRequest("POST", "/evaluate", bytes.NewReader([]byte(body)))+ w := httptest.NewRecorder()+ h.HandleEvaluate(w, req)+ if w.Code != 200 {+ t.Fatalf("status = %d, want 200: %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)+ }+ return payload+}++// A Promise returned without --await-promise still answers 200, but now carries a+// hint naming the flag instead of silently handing back {}.+func TestHandleEvaluateHintsAwaitPromiseForPromiseResult(t *testing.T) {+ br := &subtypeMockBridge{mockBridge: &mockBridge{}, subtype: "promise", value: map[string]any{}}+ payload := evalResponse(t, br, `{"expression":"Promise.resolve(42)"}`)++ hint, ok := payload["hint"].(string)+ if !ok || hint == "" {+ t.Fatalf("no hint for an un-awaited Promise result: %#v", payload)+ }+ if !bytes.Contains([]byte(hint), []byte("await-promise")) && !bytes.Contains([]byte(hint), []byte("awaitPromise")) {+ t.Errorf("hint = %q, want it to name --await-promise / awaitPromise:true", hint)+ }+}++// A genuine empty (or non-empty) object result must not trip the hint — the whole+// point is telling a Promise apart from an ordinary object.+func TestHandleEvaluateNoHintForPlainObject(t *testing.T) {+ br := &subtypeMockBridge{mockBridge: &mockBridge{}, subtype: "", value: map[string]any{"a": float64(1)}}+ payload := evalResponse(t, br, `{"expression":"({a:1})"}`)++ if _, present := payload["hint"]; present {+ t.Errorf("a plain object result carried a spurious hint: %#v", payload)+ }+ result, _ := payload["result"].(map[string]any)+ if result["a"] != float64(1) {+ t.Errorf("result = %#v, want the object value passed through", payload["result"])+ }+}++// With --await-promise the value resolves and no hint fires, even for a Promise+// subtype — the flag stays authoritative and the response is unchanged.+func TestHandleEvaluateAwaitPromiseResolvesWithoutHint(t *testing.T) {+ br := &subtypeMockBridge{mockBridge: &mockBridge{}, subtype: "promise", value: "resolved"}+ payload := evalResponse(t, br, `{"expression":"Promise.resolve(42)","awaitPromise":true}`)++ if _, present := payload["hint"]; present {+ t.Errorf("awaitPromise:true must not carry the hint: %#v", payload)+ }+ if payload["result"] != "resolved" {+ t.Errorf("result = %#v, want the resolved value", payload["result"])+ }+}