Skip to content

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

refactor(handlers): match the unknown action kind by sentinel and record batch failures once (PIN-007)

Luigi Agosti09cdecff9035
diff --git a/internal/bridge/action_request.go b/internal/bridge/action_request.go
index c5e0abb1..3a5f7d69 100644
--- a/internal/bridge/action_request.go
+++ b/internal/bridge/action_request.go
@@ -321,7 +321,7 @@ func (b *Bridge) ExecuteAction(ctx context.Context, kind string, req ActionReque
}
fn, ok := b.Actions[kind]
if !ok {
- return nil, fmt.Errorf("unknown action: %s", kind)
+ return nil, fmt.Errorf("%w: %s", ErrUnknownAction, kind)
}
urlReader := b.URLReader
if urlReader == nil {
diff --git a/internal/bridge/actions_test.go b/internal/bridge/actions_test.go
index 6b5a57c0..eb3754f8 100644
--- a/internal/bridge/actions_test.go
+++ b/internal/bridge/actions_test.go
@@ -408,8 +408,8 @@ func TestRemovedHumanActionKindsAreUnknown(t *testing.T) {
if err == nil {
t.Fatalf("expected %s to be rejected", kind)
}
- if !strings.Contains(err.Error(), "unknown action") {
- t.Fatalf("expected unknown action error for %s, got: %v", kind, err)
+ if !errors.Is(err, ErrUnknownAction) || !strings.Contains(err.Error(), kind) {
+ t.Fatalf("expected ErrUnknownAction naming %s, got: %v", kind, err)
}
})
}
diff --git a/internal/bridge/errors.go b/internal/bridge/errors.go
index 548b35e8..1eccd99f 100644
--- a/internal/bridge/errors.go
+++ b/internal/bridge/errors.go
@@ -1,6 +1,11 @@
package bridge
-import "fmt"
+import (
+ "errors"
+ "fmt"
+)
+
+var ErrUnknownAction = errors.New("unknown action")
// TabLimitError is returned when a new tab cannot be created because
// the configured limit has been reached and the eviction policy is "reject".
diff --git a/internal/handlers/action_unknown_kind_test.go b/internal/handlers/action_unknown_kind_test.go
new file mode 100644
index 00000000..566a9507
--- /dev/null
+++ b/internal/handlers/action_unknown_kind_test.go
@@ -0,0 +1,182 @@
+package handlers
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func postAction(t *testing.T, h *Handlers, body string) *httptest.ResponseRecorder {
+ t.Helper()
+ req := httptest.NewRequest(http.MethodPost, "/action", bytes.NewReader([]byte(body)))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ h.HandleAction(w, req)
+ return w
+}
+
+func TestUnknownActionKindAnswersOneCodedRefusalFromEitherPath(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ available []string
+ execErr error
+ }{
+ {"refused up front by the available list", []string{"click", "type"}, nil},
+ {"refused after dispatch by the bridge sentinel", []string{}, fmt.Errorf("%w: zap", bridge.ErrUnknownAction)},
+ {"survives a reword of the bridge message", []string{}, fmt.Errorf("no such verb %q: %w", "zap", bridge.ErrUnknownAction)},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ mb := &mockBridge{availableActions: tc.available, executeActionErr: tc.execErr}
+ h := New(mb, &config.RuntimeConfig{ActionTimeout: time.Second}, nil, nil, nil)
+ w := postAction(t, h, `{"kind":"zap","tabId":"tab1"}`)
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("status = %d, want 400: %s", w.Code, w.Body.String())
+ }
+ var body struct {
+ Code string `json:"code"`
+ Error string `json:"error"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
+ t.Fatalf("decode: %v: %s", err, w.Body.String())
+ }
+ if body.Code != "unknown_action_kind" {
+ t.Fatalf("code = %q, want unknown_action_kind: %s", body.Code, w.Body.String())
+ }
+ if !strings.Contains(body.Error, "zap") {
+ t.Fatalf("message %q does not name the kind", body.Error)
+ }
+ if valid := mb.AvailableActions(); len(valid) > 0 && !strings.Contains(body.Error, "valid values: "+strings.Join(valid, ", ")) {
+ t.Fatalf("message %q does not list the valid kinds", body.Error)
+ }
+ })
+ }
+}
+
+func TestAnUnwrappedUnknownActionMessageIsNoLongerRecoveredByPrefix(t *testing.T) {
+ mb := &mockBridge{availableActions: []string{}, executeActionErr: fmt.Errorf("unknown action: zap")}
+ h := New(mb, &config.RuntimeConfig{ActionTimeout: time.Second}, nil, nil, nil)
+ w := postAction(t, h, `{"kind":"zap","tabId":"tab1"}`)
+ if strings.Contains(w.Body.String(), "unknown_action_kind") {
+ t.Fatalf("a bridge error that merely spells the old prefix was recovered as unknown_action_kind: %s", w.Body.String())
+ }
+}
+
+func TestBatchStopOnErrorStopsAfterAPreDispatchFailure(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ stopOnError bool
+ wantResults int
+ }{
+ {"stops after the failed selector resolution", true, 1},
+ {"runs every step without stopOnError", false, 2},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{ActionTimeout: time.Second}, nil, nil, nil)
+ body := fmt.Sprintf(`{"tabId":"tab1","stopOnError":%v,"actions":[{"kind":"click","selector":"#missing"},{"kind":"click"}]}`, tc.stopOnError)
+ req := httptest.NewRequest(http.MethodPost, "/actions", bytes.NewReader([]byte(body)))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ h.HandleActions(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d: %s", w.Code, w.Body.String())
+ }
+ var envelope batchEnvelope
+ if err := json.Unmarshal(w.Body.Bytes(), &envelope); err != nil {
+ t.Fatal(err)
+ }
+ if len(envelope.Results) != tc.wantResults || envelope.Results[0].Success {
+ t.Fatalf("results = %+v, want %d with the first failed", envelope.Results, tc.wantResults)
+ }
+ if tc.wantResults == 2 && !envelope.Results[1].Success {
+ t.Fatalf("second step failed although the first failure must not stop the run: %+v", envelope.Results[1])
+ }
+ })
+ }
+}
+
+func TestEachStepTimeoutContextIsCancelledExactlyOnce(t *testing.T) {
+ f, err := parser.ParseFile(token.NewFileSet(), "actions.go", nil, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ checked := 0
+ for _, decl := range f.Decls {
+ fn, ok := decl.(*ast.FuncDecl)
+ if !ok || (fn.Name.Name != "handleActionsBatch" && fn.Name.Name != "HandleMacro" && fn.Name.Name != "runBatchStep" && fn.Name.Name != "runMultiStepActionTail") {
+ continue
+ }
+ checked++
+ cancels := map[string]int{}
+ ast.Inspect(fn.Body, func(n ast.Node) bool {
+ assign, ok := n.(*ast.AssignStmt)
+ if !ok || len(assign.Lhs) != 2 || len(assign.Rhs) != 1 {
+ return true
+ }
+ call, ok := assign.Rhs[0].(*ast.CallExpr)
+ if !ok {
+ return true
+ }
+ if sel, ok := call.Fun.(*ast.SelectorExpr); ok && sel.Sel.Name == "WithTimeout" {
+ cancels[assign.Lhs[1].(*ast.Ident).Name] = 0
+ }
+ return true
+ })
+ ast.Inspect(fn.Body, func(n ast.Node) bool {
+ call, ok := n.(*ast.CallExpr)
+ if !ok {
+ return true
+ }
+ if id, ok := call.Fun.(*ast.Ident); ok {
+ if _, tracked := cancels[id.Name]; tracked {
+ cancels[id.Name]++
+ }
+ }
+ return true
+ })
+ for name, count := range cancels {
+ if count != 1 {
+ t.Errorf("%s calls %s %d times, want exactly one cancellation path per step context", fn.Name.Name, name, count)
+ }
+ }
+ if fn.Name.Name == "runBatchStep" || fn.Name.Name == "runMultiStepActionTail" {
+ if len(cancels) != 0 {
+ t.Errorf("%s creates its own timeout context; the caller owns the step budget", fn.Name.Name)
+ }
+ }
+ }
+ if checked != 4 {
+ t.Fatalf("checked %d functions, want the two loops and the two step helpers", checked)
+ }
+}
+
+func TestNoHandlerRecoversAnUnknownActionByStringPrefix(t *testing.T) {
+ f, err := parser.ParseFile(token.NewFileSet(), "actions.go", nil, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ast.Inspect(f, func(n ast.Node) bool {
+ call, ok := n.(*ast.CallExpr)
+ if !ok {
+ return true
+ }
+ sel, ok := call.Fun.(*ast.SelectorExpr)
+ if !ok || sel.Sel.Name != "HasPrefix" || len(call.Args) != 2 {
+ return true
+ }
+ if lit, ok := call.Args[1].(*ast.BasicLit); ok && strings.Contains(lit.Value, "unknown action") {
+ t.Errorf("actions.go still recovers the unknown-action error by string prefix; match bridge.ErrUnknownAction with errors.Is")
+ }
+ return true
+ })
+}
diff --git a/internal/handlers/actions.go b/internal/handlers/actions.go
index 72113cbd..0ed53b36 100644
--- a/internal/handlers/actions.go
+++ b/internal/handlers/actions.go
@@ -481,18 +481,9 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
return
}
h.recordActionRequest(r, req)
- if available := h.Bridge.AvailableActions(); len(available) > 0 {
- known := false
- for _, k := range available {
- if k == req.Kind {
- known = true
- break
- }
- }
- if !known {
- httpx.Error(w, 400, fmt.Errorf("unknown action kind: %s", req.Kind))
- return
- }
+ if !h.actionKindKnown(req.Kind) {
+ h.writeUnknownActionKind(w, req.Kind)
+ return
}
var resolvedTabID string
@@ -642,10 +633,8 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
actionErr = nil
}
if actionErr != nil {
- if strings.HasPrefix(actionErr.Error(), "unknown action") {
- kinds := h.Bridge.AvailableActions()
- message := fmt.Sprintf("%s - valid values: %s", actionErr.Error(), strings.Join(kinds, ", "))
- httpx.JSONError(w, 400, "unknown_action_kind", message, map[string]string{"error": message})
+ if errors.Is(actionErr, bridge.ErrUnknownAction) {
+ h.writeUnknownActionKind(w, req.Kind)
return
}
if errors.Is(actionErr, bridge.ErrInvalidActionRequest) {
@@ -709,6 +698,29 @@ func (h *Handlers) HandleTabAction(w http.ResponseWriter, r *http.Request) {
h.withPathTabIDBody(w, r, h.HandleAction)
}
+func (h *Handlers) actionKindKnown(kind string) bool {
+ available := h.Bridge.AvailableActions()
+ if len(available) == 0 {
+ return true
+ }
+ for _, k := range available {
+ if k == kind {
+ return true
+ }
+ }
+ return false
+}
+
+func (h *Handlers) writeUnknownActionKind(w http.ResponseWriter, kind string) {
+ message := fmt.Sprintf("%s: %s", bridge.ErrUnknownAction, kind)
+ var details map[string]any
+ if available := h.Bridge.AvailableActions(); len(available) > 0 {
+ message += " - valid values: " + strings.Join(available, ", ")
+ details = map[string]any{"validKinds": available}
+ }
+ httpx.ErrorCode(w, http.StatusBadRequest, "unknown_action_kind", message, false, details)
+}
+
func (h *Handlers) HandleActions(w http.ResponseWriter, r *http.Request) {
var req actionsRequest
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
@@ -764,28 +776,20 @@ func (h *Handlers) handleActionsBatch(w http.ResponseWriter, r *http.Request, re
}
}
- results := make([]actionResult, 0, len(req.Actions))
- for i, action := range req.Actions {
+ run := newMultiStepRun(len(req.Actions), req.StopOnError)
+ for i := 0; i < len(req.Actions) && !run.stopped; i++ {
+ action := req.Actions[i]
if action.TabID == "" {
action.TabID = resolvedTabID
} else if action.TabID != resolvedTabID {
var err error
ctx, resolvedTabID, err = h.tabContext(r, action.TabID)
if err != nil {
- results = append(results, actionResult{
- Index: i, Success: false,
- Error: fmt.Sprintf("tab not found: %v", err),
- })
- if req.StopOnError {
- break
- }
+ run.record(actionResult{Index: i, Success: false, Error: fmt.Sprintf("tab not found: %v", err)})
continue
}
if err := h.enforceTabLease(resolvedTabID, owner); err != nil {
- results = append(results, actionResult{Index: i, Success: false, Error: err.Error()})
- if req.StopOnError {
- break
- }
+ run.record(actionResult{Index: i, Success: false, Error: err.Error()})
continue
}
}
@@ -793,90 +797,70 @@ func (h *Handlers) handleActionsBatch(w http.ResponseWriter, r *http.Request, re
return
}
if err := h.enforceTabNotPausedForHandoff(resolvedTabID); err != nil {
- results = append(results, h.handoffPausedActionResult(i, resolvedTabID, err))
- if req.StopOnError {
- break
- }
+ run.record(h.handoffPausedActionResult(i, resolvedTabID, err))
continue
}
tCtx, tCancel := context.WithTimeout(ctx, effectiveCfg.ActionTimeout)
+ var result actionResult
+ result, ctx, resolvedTabID = h.runBatchStep(ctx, tCtx, r, w, &action, effectiveCfg, resolvedTabID, i)
+ tCancel()
+ run.record(result)
+ }
- selectorResolution, resolveErr := h.resolveActionRequestSelector(tCtx, resolvedTabID, &action)
- if resolveErr != nil {
- tCancel()
- results = append(results, actionResult{
- Index: i, Success: false,
- Error: resolveErr.Error(),
- })
- if req.StopOnError {
- break
- }
- continue
- }
- refMissing := selectorResolution.refMissing
-
- if action.Kind == "" {
- tCancel()
- results = append(results, actionResult{
- Index: i, Success: false, Error: "missing required field 'kind'",
- })
- if req.StopOnError {
- break
- }
- continue
- }
+ batchRoute := routeMetadataFor(routing)
+ h.writeMultiStepActionResult(w, r, ctx, resolvedTabID, run.results, len(req.Actions), batchRoute, nil)
+}
- var stop bool
- ctx, resolvedTabID, stop = h.runMultiStepActionTail(ctx, tCtx, tCancel, r, w, &action, effectiveCfg, resolvedTabID, i, refMissing, req.StopOnError, func(err error) string {
- return fmt.Sprintf("action %s: %v", action.Kind, err)
- }, &results)
- if stop {
- break
- }
+func (h *Handlers) runBatchStep(
+ ctx, tCtx context.Context,
+ r *http.Request, w http.ResponseWriter,
+ action *bridge.ActionRequest, cfg *config.RuntimeConfig,
+ resolvedTabID string, index int,
+) (actionResult, context.Context, string) {
+ selectorResolution, resolveErr := h.resolveActionRequestSelector(tCtx, resolvedTabID, action)
+ if resolveErr != nil {
+ return actionResult{Index: index, Success: false, Error: resolveErr.Error()}, ctx, resolvedTabID
}
+ if action.Kind == "" {
+ return actionResult{Index: index, Success: false, Error: "missing required field 'kind'"}, ctx, resolvedTabID
+ }
+ return h.runMultiStepActionTail(ctx, tCtx, r, w, action, cfg, resolvedTabID, index, selectorResolution.refMissing, func(err error) string {
+ return fmt.Sprintf("action %s: %v", action.Kind, err)
+ })
+}
- batchRoute := routeMetadataFor(routing)
- h.writeMultiStepActionResult(w, r, ctx, resolvedTabID, results, len(req.Actions), batchRoute, nil)
+type multiStepRun struct {
+ results []actionResult
+ stopOnError bool
+ stopped bool
+}
+
+func newMultiStepRun(steps int, stopOnError bool) *multiStepRun {
+ return &multiStepRun{results: make([]actionResult, 0, steps), stopOnError: stopOnError}
+}
+
+func (m *multiStepRun) record(result actionResult) {
+ m.results = append(m.results, result)
+ if !result.Success && m.stopOnError {
+ m.stopped = true
+ }
}
-// runMultiStepActionTail runs the per-step work shared by the /actions batch and
-// /macro loops, once each surface's divergent pre-step work (tab switch, timeout
-// model, selector resolution, kind validation) is done and refMissing is known:
-// it caches action intent, rejects a missing ref when no recovery is configured,
-// runs the resolved action step under tCtx, and appends the result. It always
-// releases tCtx via cancel before returning. errFmt formats a step failure
-// message per-surface. It returns the (possibly auto-switch-updated) ctx +
-// resolvedTabID and whether the loop should stop (StopOnError on a failure).
func (h *Handlers) runMultiStepActionTail(
- ctx, tCtx context.Context, cancel context.CancelFunc,
+ ctx, tCtx context.Context,
r *http.Request, w http.ResponseWriter,
step *bridge.ActionRequest, cfg *config.RuntimeConfig,
- resolvedTabID string, index int, refMissing, stopOnError bool,
+ resolvedTabID string, index int, refMissing bool,
errFmt func(error) string,
- results *[]actionResult,
-) (context.Context, string, bool) {
- // Cache intent before execution so recovery can reconstruct the query.
- // Only cache when the ref IS in the snapshot to avoid overwriting the
- // richer /find-cached entry (which has the Query).
+) (actionResult, context.Context, string) {
if step.Ref != "" && h.Recovery != nil && !refMissing {
h.cacheActionIntent(resolvedTabID, *step)
}
-
if refMissing && h.Recovery == nil {
- cancel()
- *results = append(*results, actionResult{
- Index: index, Success: false,
- Error: refNotFound(step.Ref).Error(),
- })
- return ctx, resolvedTabID, stopOnError
+ return actionResult{Index: index, Success: false, Error: refNotFound(step.Ref).Error()}, ctx, resolvedTabID
}
-
- var result actionResult
- result, ctx, resolvedTabID = h.runResolvedActionStep(ctx, tCtx, r, w, step, cfg, resolvedTabID, index, refMissing, errFmt)
- cancel()
- *results = append(*results, result)
- return ctx, resolvedTabID, !result.Success && stopOnError
+ return h.runResolvedActionStep(ctx, tCtx, r, w, step, cfg, resolvedTabID, index, refMissing, errFmt)
}
// writeMultiStepActionResult finalizes a multi-step run shared by the /actions
@@ -1049,8 +1033,9 @@ func (h *Handlers) HandleMacro(w http.ResponseWriter, r *http.Request) {
}
}
- results := make([]actionResult, 0, len(req.Steps))
- for i, step := range req.Steps {
+ run := newMultiStepRun(len(req.Steps), req.StopOnError)
+ for i := 0; i < len(req.Steps) && !run.stopped; i++ {
+ step := req.Steps[i]
if step.TabID == "" {
step.TabID = resolvedTabID
}
@@ -1058,35 +1043,24 @@ func (h *Handlers) HandleMacro(w http.ResponseWriter, r *http.Request) {
return
}
if err := h.enforceTabNotPausedForHandoff(resolvedTabID); err != nil {
- results = append(results, h.handoffPausedActionResult(i, resolvedTabID, err))
- if req.StopOnError {
- break
- }
+ run.record(h.handoffPausedActionResult(i, resolvedTabID, err))
continue
}
selectorCtx, selectorCancel := context.WithTimeout(ctx, stepTimeout)
selectorResolution, resolveErr := h.resolveActionRequestSelector(selectorCtx, resolvedTabID, &step)
selectorCancel()
if resolveErr != nil {
- results = append(results, actionResult{
- Index: i, Success: false,
- Error: resolveErr.Error(),
- })
- if req.StopOnError {
- break
- }
+ run.record(actionResult{Index: i, Success: false, Error: resolveErr.Error()})
continue
}
- stepRefMissing := selectorResolution.refMissing
tCtx, cancel := context.WithTimeout(ctx, stepTimeout)
- var stop bool
- ctx, resolvedTabID, stop = h.runMultiStepActionTail(ctx, tCtx, cancel, r, w, &step, macroEffectiveCfg, resolvedTabID, i, stepRefMissing, req.StopOnError, func(err error) string {
+ var result actionResult
+ result, ctx, resolvedTabID = h.runMultiStepActionTail(ctx, tCtx, r, w, &step, macroEffectiveCfg, resolvedTabID, i, selectorResolution.refMissing, func(err error) string {
return err.Error()
- }, &results)
- if stop {
- break
- }
+ })
+ cancel()
+ run.record(result)
}
macroRoute := routeMetadataFor(browserRouting{
@@ -1096,5 +1070,5 @@ func (h *Handlers) HandleMacro(w http.ResponseWriter, r *http.Request) {
EffectiveCfg: macroEffectiveCfg,
Decision: macroHandleDecision,
})
- h.writeMultiStepActionResult(w, r, ctx, resolvedTabID, results, len(req.Steps), macroRoute, map[string]any{"kind": "macro"})
+ h.writeMultiStepActionResult(w, r, ctx, resolvedTabID, run.results, len(req.Steps), macroRoute, map[string]any{"kind": "macro"})
}