Skip to content

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

feat: add self-healing recovery engine with failure classification, intent caching, and semantic re-matching

Yash Jadhav299890c4ff49
diff --git a/internal/handlers/actions.go b/internal/handlers/actions.go
index 98fbc089..14f48898 100644
--- a/internal/handlers/actions.go
+++ b/internal/handlers/actions.go
@@ -13,6 +13,7 @@ import (
"github.com/chromedp/chromedp"
"github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/semantic"
"github.com/pinchtab/pinchtab/internal/web"
)
@@ -138,6 +139,11 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
}
}
+ // Cache intent before execution so recovery can reconstruct the query.
+ if req.Ref != "" && h.Recovery != nil {
+ h.cacheActionIntent(resolvedTabID, req)
+ }
+
result, err := h.Bridge.ExecuteAction(tCtx, req.Kind, req)
if err != nil && req.Ref != "" && shouldRetryStaleRef(err) {
recordStaleRefRetry()
@@ -149,6 +155,24 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
}
}
}
+ // Semantic self-healing: if stale-ref retry still failed, attempt
+ // recovery via the semantic matcher.
+ var recoveryResult *semantic.RecoveryResult
+ if err != nil && req.Ref != "" && h.Recovery != nil && h.Recovery.ShouldAttempt(err, req.Ref) {
+ rr, actionRes, recoveryErr := h.Recovery.AttemptWithClassification(
+ tCtx, resolvedTabID, req.Ref, req.Kind,
+ semantic.ClassifyFailure(err),
+ func(ctx context.Context, kind string, nodeID int64) (map[string]any, error) {
+ req.NodeID = nodeID
+ return h.Bridge.ExecuteAction(ctx, kind, req)
+ },
+ )
+ recoveryResult = &rr
+ if recoveryErr == nil {
+ result = actionRes
+ err = nil
+ }
+ }
if err != nil {
if strings.HasPrefix(err.Error(), "unknown action") {
kinds := h.Bridge.AvailableActions()
@@ -161,7 +185,11 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
return
}
- web.JSON(w, 200, map[string]any{"success": true, "result": result})
+ resp := map[string]any{"success": true, "result": result}
+ if recoveryResult != nil {
+ resp["recovery"] = recoveryResult
+ }
+ web.JSON(w, 200, resp)
}
// HandleTabAction performs a single action on a tab identified by path ID.
@@ -342,6 +370,11 @@ func (h *Handlers) handleActionsBatch(w http.ResponseWriter, r *http.Request, re
continue
}
+ // Cache intent before execution so recovery can reconstruct the query.
+ if action.Ref != "" && h.Recovery != nil {
+ h.cacheActionIntent(resolvedTabID, action)
+ }
+
actionRes, err := h.Bridge.ExecuteAction(tCtx, action.Kind, action)
if err != nil && action.Ref != "" && shouldRetryStaleRef(err) {
recordStaleRefRetry()
@@ -353,6 +386,22 @@ func (h *Handlers) handleActionsBatch(w http.ResponseWriter, r *http.Request, re
}
}
}
+ // Semantic self-healing for batched actions.
+ if err != nil && action.Ref != "" && h.Recovery != nil && h.Recovery.ShouldAttempt(err, action.Ref) {
+ rr, recRes, recErr := h.Recovery.AttemptWithClassification(
+ tCtx, resolvedTabID, action.Ref, action.Kind,
+ semantic.ClassifyFailure(err),
+ func(ctx context.Context, kind string, nodeID int64) (map[string]any, error) {
+ action.NodeID = nodeID
+ return h.Bridge.ExecuteAction(ctx, kind, action)
+ },
+ )
+ _ = rr // recovery metadata not surfaced per-action in batch
+ if recErr == nil {
+ actionRes = recRes
+ err = nil
+ }
+ }
tCancel()
if err != nil {
@@ -419,6 +468,11 @@ func (h *Handlers) HandleMacro(w http.ResponseWriter, r *http.Request) {
if step.TabID == "" {
step.TabID = resolvedTabID
}
+ // Cache intent before execution so recovery can reconstruct the query.
+ if step.Ref != "" && h.Recovery != nil {
+ h.cacheActionIntent(resolvedTabID, step)
+ }
+
tCtx, cancel := context.WithTimeout(ctx, stepTimeout)
res, err := h.Bridge.ExecuteAction(tCtx, step.Kind, step)
if err != nil && step.Ref != "" && shouldRetryStaleRef(err) {
@@ -431,6 +485,22 @@ func (h *Handlers) HandleMacro(w http.ResponseWriter, r *http.Request) {
}
}
}
+ // Semantic self-healing for macro steps.
+ if err != nil && step.Ref != "" && h.Recovery != nil && h.Recovery.ShouldAttempt(err, step.Ref) {
+ rr, recRes, recErr := h.Recovery.AttemptWithClassification(
+ tCtx, resolvedTabID, step.Ref, step.Kind,
+ semantic.ClassifyFailure(err),
+ func(ctx context.Context, kind string, nodeID int64) (map[string]any, error) {
+ step.NodeID = nodeID
+ return h.Bridge.ExecuteAction(ctx, kind, step)
+ },
+ )
+ _ = rr
+ if recErr == nil {
+ res = recRes
+ err = nil
+ }
+ }
cancel()
if err != nil {
results = append(results, actionResult{Index: i, Success: false, Error: err.Error()})
@@ -461,6 +531,31 @@ func countSuccessful(results []actionResult) int {
return count
}
+// cacheActionIntent stores the element's semantic identity in the
+// IntentCache so the recovery engine can reconstruct a query if the
+// ref becomes stale.
+func (h *Handlers) cacheActionIntent(tabID string, req bridge.ActionRequest) {
+ if h.Recovery == nil || req.Ref == "" {
+ return
+ }
+ desc := semantic.ElementDescriptor{Ref: req.Ref}
+ // Try to enrich from the current snapshot cache.
+ if cache := h.Bridge.GetRefCache(tabID); cache != nil {
+ for _, n := range cache.Nodes {
+ if n.Ref == req.Ref {
+ desc.Role = n.Role
+ desc.Name = n.Name
+ desc.Value = n.Value
+ break
+ }
+ }
+ }
+ h.Recovery.RecordIntent(tabID, req.Ref, semantic.IntentEntry{
+ Descriptor: desc,
+ CachedAt: time.Now(),
+ })
+}
+
func shouldRetryStaleRef(err error) bool {
if err == nil {
return false
diff --git a/internal/handlers/find.go b/internal/handlers/find.go
index af5aa44b..7345d8f3 100644
--- a/internal/handlers/find.go
+++ b/internal/handlers/find.go
@@ -4,6 +4,7 @@ import (
"encoding/json"
"fmt"
"net/http"
+ "strings"
"time"
"github.com/pinchtab/pinchtab/internal/bridge"
@@ -12,10 +13,13 @@ import (
)
type findRequest struct {
- Query string `json:"query"`
- TabID string `json:"tabId,omitempty"`
- Threshold float64 `json:"threshold,omitempty"`
- TopK int `json:"topK,omitempty"`
+ Query string `json:"query"`
+ TabID string `json:"tabId,omitempty"`
+ Threshold float64 `json:"threshold,omitempty"`
+ TopK int `json:"topK,omitempty"`
+ LexicalWeight float64 `json:"lexicalWeight,omitempty"`
+ EmbeddingWeight float64 `json:"embeddingWeight,omitempty"`
+ Explain bool `json:"explain,omitempty"`
}
type findResponse struct {
@@ -57,6 +61,7 @@ func (h *Handlers) HandleFind(w http.ResponseWriter, r *http.Request) {
return
}
+ req.Query = strings.TrimSpace(req.Query)
if req.Query == "" {
web.Error(w, 400, fmt.Errorf("missing required field 'query'"))
return
@@ -78,7 +83,13 @@ func (h *Handlers) HandleFind(w http.ResponseWriter, r *http.Request) {
// Try cached snapshot first; auto-fetch if not available.
nodes := h.resolveSnapshotNodes(resolvedTabID)
if len(nodes) == 0 {
- web.Error(w, 500, fmt.Errorf("no elements found in snapshot for tab %s", resolvedTabID))
+ // Auto-refresh: take a fresh snapshot via CDP.
+ ctx, _, _ := h.Bridge.TabContext(resolvedTabID)
+ h.refreshRefCache(ctx, resolvedTabID)
+ nodes = h.resolveSnapshotNodes(resolvedTabID)
+ }
+ if len(nodes) == 0 {
+ web.Error(w, 500, fmt.Errorf("no elements found in snapshot for tab %s — navigate first", resolvedTabID))
return
}
@@ -95,8 +106,11 @@ func (h *Handlers) HandleFind(w http.ResponseWriter, r *http.Request) {
start := time.Now()
result, err := h.Matcher.Find(r.Context(), req.Query, descs, semantic.FindOptions{
- Threshold: req.Threshold,
- TopK: req.TopK,
+ Threshold: req.Threshold,
+ TopK: req.TopK,
+ LexicalWeight: req.LexicalWeight,
+ EmbeddingWeight: req.EmbeddingWeight,
+ Explain: req.Explain,
})
if err != nil {
web.Error(w, 500, fmt.Errorf("matcher error: %w", err))
@@ -117,14 +131,32 @@ func (h *Handlers) HandleFind(w http.ResponseWriter, r *http.Request) {
resp.Matches = []semantic.ElementMatch{}
}
+ // Cache intent for recovery: store the query + best-match descriptor
+ // so the recovery engine can reconstruct a search if the ref goes stale.
+ if result.BestRef != "" && h.Recovery != nil {
+ var bestDesc semantic.ElementDescriptor
+ for _, d := range descs {
+ if d.Ref == result.BestRef {
+ bestDesc = d
+ break
+ }
+ }
+ h.Recovery.RecordIntent(resolvedTabID, result.BestRef, semantic.IntentEntry{
+ Query: req.Query,
+ Descriptor: bestDesc,
+ Score: result.BestScore,
+ Confidence: resp.Confidence,
+ Strategy: result.Strategy,
+ CachedAt: time.Now(),
+ })
+ }
+
web.JSON(w, 200, resp)
}
// resolveSnapshotNodes returns cached A11yNodes for the tab, or an empty
-// slice if no cache is available. The handler's auto-snapshot fetch is
-// limited to the existing RefCache — a full CDP-based auto-fetch is left
-// for future work since it requires chromedp context wiring that would
-// tightly couple this handler to CDP internals.
+// slice if no cache is available. The caller should use refreshRefCache
+// to auto-fetch a fresh snapshot via CDP when this returns nil.
func (h *Handlers) resolveSnapshotNodes(tabID string) []bridge.A11yNode {
cache := h.Bridge.GetRefCache(tabID)
if cache != nil && len(cache.Nodes) > 0 {
diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.go
index 517abef2..e678d780 100644
--- a/internal/handlers/handlers.go
+++ b/internal/handlers/handlers.go
@@ -2,7 +2,9 @@
package handlers
import (
+ "context"
"net/http"
+ "time"
"github.com/pinchtab/pinchtab/internal/assets"
"github.com/pinchtab/pinchtab/internal/bridge"
@@ -20,11 +22,15 @@ type Handlers struct {
Orchestrator bridge.OrchestratorService
IdMgr *idutil.Manager
Matcher semantic.ElementMatcher
+ IntentCache *semantic.IntentCache
+ Recovery *semantic.RecoveryEngine
}
func New(b bridge.BridgeAPI, cfg *config.RuntimeConfig, p bridge.ProfileService, d *dashboard.Dashboard, o bridge.OrchestratorService) *Handlers {
matcher := semantic.NewCombinedMatcher(semantic.NewHashingEmbedder(128))
- return &Handlers{
+ intentCache := semantic.NewIntentCache(200, 10*time.Minute)
+
+ h := &Handlers{
Bridge: b,
Config: cfg,
Profiles: p,
@@ -32,7 +38,46 @@ func New(b bridge.BridgeAPI, cfg *config.RuntimeConfig, p bridge.ProfileService,
Orchestrator: o,
IdMgr: idutil.NewManager(),
Matcher: matcher,
+ IntentCache: intentCache,
}
+
+ // Wire up the recovery engine with callbacks that delegate back to
+ // the handler's bridge without introducing circular imports.
+ h.Recovery = semantic.NewRecoveryEngine(
+ semantic.DefaultRecoveryConfig(),
+ matcher,
+ intentCache,
+ // SnapshotRefresher
+ func(ctx context.Context, tabID string) error {
+ h.refreshRefCache(ctx, tabID)
+ return nil
+ },
+ // NodeIDResolver
+ func(tabID, ref string) (int64, bool) {
+ cache := h.Bridge.GetRefCache(tabID)
+ if cache == nil {
+ return 0, false
+ }
+ nid, ok := cache.Refs[ref]
+ return nid, ok
+ },
+ // DescriptorBuilder
+ func(tabID string) []semantic.ElementDescriptor {
+ nodes := h.resolveSnapshotNodes(tabID)
+ descs := make([]semantic.ElementDescriptor, len(nodes))
+ for i, n := range nodes {
+ descs[i] = semantic.ElementDescriptor{
+ Ref: n.Ref,
+ Role: n.Role,
+ Name: n.Name,
+ Value: n.Value,
+ }
+ }
+ return descs
+ },
+ )
+
+ return h
}
// ensureChrome ensures Chrome is initialized before handling requests that need it
diff --git a/internal/semantic/combined_matcher.go b/internal/semantic/combined_matcher.go
index 89d5843f..135503ff 100644
--- a/internal/semantic/combined_matcher.go
+++ b/internal/semantic/combined_matcher.go
@@ -46,6 +46,14 @@ func (c *CombinedMatcher) Find(ctx context.Context, query string, elements []Ele
opts.TopK = 3
}
+ // Per-request weight overrides; fall back to matcher defaults.
+ lexW := c.LexicalWeight
+ embW := c.EmbeddingWeight
+ if opts.LexicalWeight > 0 || opts.EmbeddingWeight > 0 {
+ lexW = opts.LexicalWeight
+ embW = opts.EmbeddingWeight
+ }
+
// Use a lower internal threshold to capture candidates from both matchers
// that might miss the final threshold individually but pass when combined.
internalOpts := FindOptions{
@@ -107,22 +115,29 @@ func (c *CombinedMatcher) Find(ctx context.Context, query string, elements []Ele
}
type scored struct {
- ref string
- score float64
- el ElementDescriptor
+ ref string
+ score float64
+ el ElementDescriptor
+ lexScore float64
+ embScore float64
}
var candidates []scored
for ref := range allRefs {
ls := lexScores[ref]
es := embScores[ref]
- combined := c.LexicalWeight*ls + c.EmbeddingWeight*es
+ combined := lexW*ls + embW*es
if combined >= opts.Threshold {
- candidates = append(candidates, scored{
+ s := scored{
ref: ref,
score: combined,
el: refToElem[ref],
- })
+ }
+ if opts.Explain {
+ s.lexScore = ls
+ s.embScore = es
+ }
+ candidates = append(candidates, s)
}
}
@@ -141,12 +156,20 @@ func (c *CombinedMatcher) Find(ctx context.Context, query string, elements []Ele
}
for _, cand := range candidates {
- result.Matches = append(result.Matches, ElementMatch{
+ em := ElementMatch{
Ref: cand.ref,
Score: cand.score,
Role: cand.el.Role,
Name: cand.el.Name,
- })
+ }
+ if opts.Explain {
+ em.Explain = &MatchExplain{
+ LexicalScore: cand.lexScore,
+ EmbeddingScore: cand.embScore,
+ Composite: cand.el.Composite(),
+ }
+ }
+ result.Matches = append(result.Matches, em)
}
if len(result.Matches) > 0 {
diff --git a/internal/semantic/failure.go b/internal/semantic/failure.go
new file mode 100644
index 00000000..35da3cc7
--- /dev/null
+++ b/internal/semantic/failure.go
@@ -0,0 +1,168 @@
+package semantic
+
+import "strings"
+
+// FailureType classifies the cause of an action failure so the recovery
+// engine can decide whether and how to attempt self-healing.
+type FailureType int
+
+const (
+ // FailureUnknown — the error could not be classified; not recoverable.
+ FailureUnknown FailureType = iota
+
+ // FailureElementNotFound — the ref no longer maps to a DOM node.
+ // Recoverable via semantic re-match on a fresh snapshot.
+ FailureElementNotFound
+
+ // FailureElementStale — the node exists but has been detached from
+ // the live DOM (SPA re-render, modal overlay, etc.).
+ FailureElementStale
+
+ // FailureElementNotInteractable — the element is hidden, disabled,
+ // or covered by an overlay and cannot receive input.
+ FailureElementNotInteractable
+
+ // FailureNavigation — the action triggered a page navigation; the
+ // entire snapshot is invalid. Recoverable via fresh snapshot.
+ FailureNavigation
+
+ // FailureNetwork — a transport or Chrome-level error; not recoverable
+ // by the recovery engine.
+ FailureNetwork
+)
+
+// String returns a human-readable label for the failure type.
+func (f FailureType) String() string {
+ switch f {
+ case FailureElementNotFound:
+ return "element_not_found"
+ case FailureElementStale:
+ return "element_stale"
+ case FailureElementNotInteractable:
+ return "element_not_interactable"
+ case FailureNavigation:
+ return "navigation"
+ case FailureNetwork:
+ return "network"
+ default:
+ return "unknown"
+ }
+}
+
+// Recoverable reports whether the failure type is eligible for automatic
+// self-healing. Network and unknown failures are not recoverable.
+func (f FailureType) Recoverable() bool {
+ switch f {
+ case FailureElementNotFound,
+ FailureElementStale,
+ FailureElementNotInteractable,
+ FailureNavigation:
+ return true
+ default:
+ return false
+ }
+}
+
+// ClassifyFailure inspects an error string and returns the most likely
+// FailureType. The classification is intentionally broad — it matches
+// error messages produced by Chrome DevTools Protocol, chromedp, and
+// PinchTab's own bridge layer so that recovery works regardless of which
+// layer reported the failure.
+func ClassifyFailure(err error) FailureType {
+ if err == nil {
+ return FailureUnknown
+ }
+ e := strings.ToLower(err.Error())
+
+ // Element not found patterns.
+ notFoundPatterns := []string{
+ "could not find node",
+ "node with given id",
+ "no node",
+ "ref not found",
+ "node not found",
+ "backend node id",
+ "no node with given",
+ }
+ for _, p := range notFoundPatterns {
+ if strings.Contains(e, p) {
+ return FailureElementNotFound
+ }
+ }
+
+ // Stale element / detached DOM patterns.
+ // NOTE: "frame" detachment is classified as navigation, not stale.
+ stalePatterns := []string{
+ "stale",
+ "orphan",
+ "object reference",
+ "node is detached",
+ "execution context was destroyed",
+ "context was destroyed",
+ "target closed",
+ }
+ for _, p := range stalePatterns {
+ if strings.Contains(e, p) {
+ return FailureElementStale
+ }
+ }
+ // "detached" alone is stale, but "frame" + "detached" is navigation.
+ if strings.Contains(e, "detached") && !strings.Contains(e, "frame") {
+ return FailureElementStale
+ }
+
+ // Not interactable patterns.
+ interactablePatterns := []string{
+ "not interactable",
+ "not clickable",
+ "element is not visible",
+ "not visible",
+ "element is disabled",
+ "overlapped",
+ "overlapping",
+ "obscured",
+ "pointer-events: none",
+ "cannot focus",
+ "outside of the viewport",
+ "outside the viewport",
+ }
+ for _, p := range interactablePatterns {
+ if strings.Contains(e, p) {
+ return FailureElementNotInteractable
+ }
+ }
+
+ // Navigation patterns.
+ navPatterns := []string{
+ "navigat",
+ "page crashed",
+ "page was destroyed",
+ "inspected target",
+ "frame was detached",
+ "frame detached",
+ }
+ for _, p := range navPatterns {
+ if strings.Contains(e, p) {
+ return FailureNavigation
+ }
+ }
+
+ // Network patterns.
+ networkPatterns := []string{
+ "net::",
+ "connection refused",
+ "could not connect",
+ "timeout",
+ "deadline exceeded",
+ "websocket",
+ "eof",
+ "broken pipe",
+ }
+ for _, p := range networkPatterns {
+ if strings.Contains(e, p) {
+ return FailureNetwork
+ }
+ }
+
+ return FailureUnknown
+}
diff --git a/internal/semantic/intent_cache.go b/internal/semantic/intent_cache.go
new file mode 100644
index 00000000..6061f384
--- /dev/null
+++ b/internal/semantic/intent_cache.go
@@ -0,0 +1,123 @@
+package semantic
+
+import (
+ "sync"
+ "time"
+)
+
+// IntentEntry captures the semantic identity of an element at the time an
+// action was requested. When the element's ref becomes stale, the
+// recovery engine uses this cached intent to build a semantic search
+// query against the fresh snapshot.
+type IntentEntry struct {
+ // Query is the original natural-language query (if the action was
+ // preceded by /find). Otherwise empty.
+ Query string
+
+ // Descriptor holds role, name, and value of the element at
+ // action time.
+ Descriptor ElementDescriptor
+
+ // Score and Confidence from the last /find (if available).
+ Score float64
+ Confidence string
+ Strategy string
+
+ // CachedAt is the wall-clock time the entry was stored.
+ CachedAt time.Time
+}
+
+// IntentCache is a thread-safe, per-tab LRU cache of element intents.
+// Key hierarchy: tabID → ref → IntentEntry.
+type IntentCache struct {
+ mu sync.RWMutex
+ tabs map[string]map[string]IntentEntry
+ maxRefs int // max entries per tab
+ ttl time.Duration // entry expiry
+}
+
+// NewIntentCache returns an IntentCache that evicts entries older than
+// ttl and limits each tab to maxRefs entries.
+func NewIntentCache(maxRefs int, ttl time.Duration) *IntentCache {
+ if maxRefs <= 0 {
+ maxRefs = 200
+ }
+ if ttl <= 0 {
+ ttl = 10 * time.Minute
+ }
+ return &IntentCache{
+ tabs: make(map[string]map[string]IntentEntry),
+ maxRefs: maxRefs,
+ ttl: ttl,
+ }
+}
+
+// Store records (or updates) the intent for a given (tabID, ref) pair.
+func (c *IntentCache) Store(tabID, ref string, entry IntentEntry) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+
+ if entry.CachedAt.IsZero() {
+ entry.CachedAt = time.Now()
+ }
+
+ tab, ok := c.tabs[tabID]
+ if !ok {
+ tab = make(map[string]IntentEntry)
+ c.tabs[tabID] = tab
+ }
+
+ // Evict if at capacity.
+ if len(tab) >= c.maxRefs {
+ oldest := ""
+ var oldestT time.Time
+ for r, e := range tab {
+ if oldest == "" || e.CachedAt.Before(oldestT) {
+ oldest = r
+ oldestT = e.CachedAt
+ }
+ }
+ if oldest != "" {
+ delete(tab, oldest)
+ }
+ }
+
+ tab[ref] = entry
+}
+
+// Lookup returns the cached intent for the ref, or (IntentEntry{}, false).
+func (c *IntentCache) Lookup(tabID, ref string) (IntentEntry, bool) {
+ c.mu.RLock()
+ defer c.mu.RUnlock()
+
+ tab, ok := c.tabs[tabID]
+ if !ok {
+ return IntentEntry{}, false
+ }
+ entry, ok := tab[ref]
+ if !ok {
+ return IntentEntry{}, false
+ }
+ if time.Since(entry.CachedAt) > c.ttl {
+ return IntentEntry{}, false
+ }
+ return entry, true
+}
+
+// InvalidateTab removes all cached intents for a tab.
+func (c *IntentCache) InvalidateTab(tabID string) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ delete(c.tabs, tabID)
+}
+
+// Size returns the total number of cached entries across all tabs.
+func (c *IntentCache) Size() int {
+ c.mu.RLock()
+ defer c.mu.RUnlock()
+ n := 0
+ for _, tab := range c.tabs {
+ n += len(tab)
+ }
+ return n
+}
diff --git a/internal/semantic/matcher.go b/internal/semantic/matcher.go
index a2ca8110..b8bdc258 100644
--- a/internal/semantic/matcher.go
+++ b/internal/semantic/matcher.go
@@ -18,6 +18,14 @@ type ElementMatcher interface {
type FindOptions struct {
Threshold float64
TopK int
+
+ // Per-request weight overrides (optional). If both are zero the
+ // matcher's default weights are used.
+ LexicalWeight float64
+ EmbeddingWeight float64
+
+ // Explain enables verbose per-match scoring breakdown.
+ Explain bool
}
// FindResult holds the output of a Find operation.
@@ -41,4 +49,14 @@ type ElementMatch struct {
Score float64 `json:"score"`
Role string `json:"role,omitempty"`
Name string `json:"name,omitempty"`
+
+ // Explain is populated when FindOptions.Explain is true.
+ Explain *MatchExplain `json:"explain,omitempty"`
+}
+
+// MatchExplain exposes the per-strategy score breakdown for debugging.
+type MatchExplain struct {
+ LexicalScore float64 `json:"lexical_score"`
+ EmbeddingScore float64 `json:"embedding_score"`
+ Composite string `json:"composite"`
}
diff --git a/internal/semantic/recovery.go b/internal/semantic/recovery.go
new file mode 100644
index 00000000..10cdeecd
--- /dev/null
+++ b/internal/semantic/recovery.go
@@ -0,0 +1,375 @@
+package semantic
+
+import (
+ "context"
+ "fmt"
+ "time"
+)
+
+// RecoveryConfig tunes the self-healing behaviour.
+type RecoveryConfig struct {
+ // Enabled globally enables/disables recovery. Default true.
+ Enabled bool
+
+ // MaxRetries is the maximum number of recovery re-match attempts
+ // before giving up. Default 1.
+ MaxRetries int
+
+ // MinConfidence is the minimum score the semantic re-match must
+ // achieve for the recovery attempt to proceed. Default 0.4.
+ MinConfidence float64
+
+ // PreferHighConfidence when true will only auto-recover if the
+ // confidence label is "high" or "medium". Default false (will
+ // attempt recovery even at "low" confidence).
+ PreferHighConfidence bool
+}
+
+// DefaultRecoveryConfig returns a production-ready configuration.
+func DefaultRecoveryConfig() RecoveryConfig {
+ return RecoveryConfig{
+ Enabled: true,
+ MaxRetries: 1,
+ MinConfidence: 0.4,
+ PreferHighConfidence: false,
+ }
+}
+
+// RecoveryResult captures what the recovery engine did. It is embedded
+// into the action response when recovery was attempted.
+type RecoveryResult struct {
+ // Recovered is true if the action succeeded after re-matching.
+ Recovered bool `json:"recovered"`
+
+ // OriginalRef is the ref the agent originally requested.
+ OriginalRef string `json:"original_ref"`
+
+ // NewRef is the ref that the semantic re-match found.
+ NewRef string `json:"new_ref,omitempty"`
+
+ // Score is the semantic similarity score of the new match.
+ Score float64 `json:"score,omitempty"`
+
+ // Confidence is "high", "medium", or "low".
+ Confidence string `json:"confidence,omitempty"`
+
+ // Strategy is the matcher strategy that produced the new ref.
+ Strategy string `json:"strategy,omitempty"`
+
+ // FailureType classifies the original error.
+ FailureType string `json:"failure_type"`
+
+ // Attempts is how many re-match attempts were made.
+ Attempts int `json:"attempts"`
+
+ // LatencyMs is the total wall-clock time spent on recovery.
+ LatencyMs int64 `json:"latency_ms"`
+
+ // Error is non-empty when recovery was attempted but failed.
+ Error string `json:"error,omitempty"`
+}
+
+// SnapshotRefresher is a callback the handler provides so the recovery
+// engine can force a fresh CDP accessibility tree fetch without importing
+// the bridge or chromedp packages.
+type SnapshotRefresher func(ctx context.Context, tabID string) error
+
+// NodeIDResolver maps a ref string to a node ID from the current
+// snapshot cache. Returns (nodeID, true) or (0, false).
+type NodeIDResolver func(tabID, ref string) (int64, bool)
+
+// ActionExecutor runs a single action and returns the result or error.
+// This is the same signature as Bridge.ExecuteAction.
+type ActionExecutor func(ctx context.Context, kind string, nodeID int64) (map[string]any, error)
+
+// DescriptorBuilder converts raw snapshot data into ElementDescriptors.
+// The handler provides this so the recovery engine stays decoupled from
+// bridge internals.
+type DescriptorBuilder func(tabID string) []ElementDescriptor
+
+// RecoveryEngine orchestrates self-healing when an action fails because
+// the target element's ref is stale or the DOM has changed.
+//
+// Integration pattern (used in handlers/actions.go):
+//
+// result, err := bridge.ExecuteAction(...)
+// if err != nil && recovery.ShouldAttempt(err, ref) {
+// rr := recovery.Attempt(ctx, tabID, ref, kind, ...)
+// ... use rr ...
+// }
+type RecoveryEngine struct {
+ Config RecoveryConfig
+ Matcher ElementMatcher
+ IntentCache *IntentCache
+ Refresh SnapshotRefresher
+ ResolveNode NodeIDResolver
+ BuildDescs DescriptorBuilder
+}
+
+// NewRecoveryEngine creates a RecoveryEngine with the given dependencies.
+func NewRecoveryEngine(
+ cfg RecoveryConfig,
+ matcher ElementMatcher,
+ cache *IntentCache,
+ refresh SnapshotRefresher,
+ resolve NodeIDResolver,
+ buildDescs DescriptorBuilder,
+) *RecoveryEngine {
+ return &RecoveryEngine{
+ Config: cfg,
+ Matcher: matcher,
+ IntentCache: cache,
+ Refresh: refresh,
+ ResolveNode: resolve,
+ BuildDescs: buildDescs,
+ }
+}
+
+// ShouldAttempt returns true when recovery is enabled and the failure
+// type is recoverable.
+func (re *RecoveryEngine) ShouldAttempt(err error, ref string) bool {
+ if !re.Config.Enabled || ref == "" {
+ return false
+ }
+ ft := ClassifyFailure(err)
+ return ft.Recoverable()
+}
+
+// Attempt tries to semantically re-locate a stale element and re-execute
+// the action. It returns a RecoveryResult and, if successful, the action's
+// result payload.
+//
+// Flow:
+// 1. Classify the failure.
+// 2. Reconstruct a search query from the IntentCache or the ref's last
+// known descriptor.
+// 3. Force a fresh snapshot via the Refresh callback.
+// 4. Build new descriptors and run the Matcher.
+// 5. If a match exceeds MinConfidence, resolve its nodeID and call the
+// ActionExecutor.
+// 6. Return the RecoveryResult.
+func (re *RecoveryEngine) Attempt(
+ ctx context.Context,
+ tabID string,
+ ref string,
+ kind string,
+ exec ActionExecutor,
+) (RecoveryResult, map[string]any, error) {
+ start := time.Now()
+
+ ft := ClassifyFailure(fmt.Errorf("recovery trigger"))
+ // We always accept the call at this point since ShouldAttempt already
+ // gated entry. Re-classify for the result struct.
+ rr := RecoveryResult{
+ OriginalRef: ref,
+ FailureType: ft.String(),
+ }
+
+ // 1. Build the search query from cached intent.
+ query := re.reconstructQuery(tabID, ref)
+ if query == "" {
+ rr.Error = "no cached intent for ref " + ref
+ rr.LatencyMs = time.Since(start).Milliseconds()
+ return rr, nil, fmt.Errorf("recovery: %s", rr.Error)
+ }
+
+ // 2. Iterate up to MaxRetries.
+ maxRetries := re.Config.MaxRetries
+ if maxRetries <= 0 {
+ maxRetries = 1
+ }
+
+ var lastErr error
+ for attempt := 1; attempt <= maxRetries; attempt++ {
+ rr.Attempts = attempt
+
+ // 3. Force a fresh snapshot.
+ if re.Refresh != nil {
+ if err := re.Refresh(ctx, tabID); err != nil {
+ lastErr = fmt.Errorf("refresh snapshot: %w", err)
+ continue
+ }
+ }
+
+ // 4. Build descriptors from the fresh snapshot.
+ descs := re.BuildDescs(tabID)
+ if len(descs) == 0 {
+ lastErr = fmt.Errorf("empty snapshot after refresh")
+ continue
+ }
+
+ // 5. Run the semantic matcher.
+ result, err := re.Matcher.Find(ctx, query, descs, FindOptions{
+ Threshold: re.Config.MinConfidence,
+ TopK: 1,
+ })
+ if err != nil {
+ lastErr = fmt.Errorf("matcher: %w", err)
+ continue
+ }
+ if result.BestRef == "" || result.BestScore < re.Config.MinConfidence {
+ lastErr = fmt.Errorf("no match above threshold %.2f (best: %.2f)",
+ re.Config.MinConfidence, result.BestScore)
+ continue
+ }
+
+ // Confidence gate.
+ conf := CalibrateConfidence(result.BestScore)
+ if re.Config.PreferHighConfidence && conf == "low" {
+ lastErr = fmt.Errorf("match confidence too low: %s (%.2f)",
+ conf, result.BestScore)
+ continue
+ }
+
+ rr.NewRef = result.BestRef
+ rr.Score = result.BestScore
+ rr.Confidence = conf
+ rr.Strategy = result.Strategy
+
+ // 6. Resolve the new ref → nodeID.
+ nodeID, ok := re.ResolveNode(tabID, result.BestRef)
+ if !ok {
+ lastErr = fmt.Errorf("new ref %s not in cache after refresh", result.BestRef)
+ continue
+ }
+
+ // 7. Re-execute the action.
+ actionResult, execErr := exec(ctx, kind, nodeID)
+ rr.LatencyMs = time.Since(start).Milliseconds()
+ if execErr != nil {
+ lastErr = execErr
+ continue
+ }
+
+ rr.Recovered = true
+ return rr, actionResult, nil
+ }
+
+ rr.LatencyMs = time.Since(start).Milliseconds()
+ if lastErr != nil {
+ rr.Error = lastErr.Error()
+ }
+ return rr, nil, lastErr
+}
+
+// AttemptWithClassification is like Attempt but accepts the pre-classified
+// failure type so callers that already called ClassifyFailure don't
+// re-compute it.
+func (re *RecoveryEngine) AttemptWithClassification(
+ ctx context.Context,
+ tabID string,
+ ref string,
+ kind string,
+ ft FailureType,
+ exec ActionExecutor,
+) (RecoveryResult, map[string]any, error) {
+ start := time.Now()
+
+ rr := RecoveryResult{
+ OriginalRef: ref,
+ FailureType: ft.String(),
+ }
+
+ query := re.reconstructQuery(tabID, ref)
+ if query == "" {
+ rr.Error = "no cached intent for ref " + ref
+ rr.LatencyMs = time.Since(start).Milliseconds()
+ return rr, nil, fmt.Errorf("recovery: %s", rr.Error)
+ }
+
+ maxRetries := re.Config.MaxRetries
+ if maxRetries <= 0 {
+ maxRetries = 1
+ }
+
+ var lastErr error
+ for attempt := 1; attempt <= maxRetries; attempt++ {
+ rr.Attempts = attempt
+
+ if re.Refresh != nil {
+ if err := re.Refresh(ctx, tabID); err != nil {
+ lastErr = fmt.Errorf("refresh snapshot: %w", err)
+ continue
+ }
+ }
+
+ descs := re.BuildDescs(tabID)
+ if len(descs) == 0 {
+ lastErr = fmt.Errorf("empty snapshot after refresh")
+ continue
+ }
+
+ result, err := re.Matcher.Find(ctx, query, descs, FindOptions{
+ Threshold: re.Config.MinConfidence,
+ TopK: 1,
+ })
+ if err != nil {
+ lastErr = fmt.Errorf("matcher: %w", err)
+ continue
+ }
+ if result.BestRef == "" || result.BestScore < re.Config.MinConfidence {
+ lastErr = fmt.Errorf("no match above threshold %.2f (best: %.2f)",
+ re.Config.MinConfidence, result.BestScore)
+ continue
+ }
+
+ conf := CalibrateConfidence(result.BestScore)
+ if re.Config.PreferHighConfidence && conf == "low" {
+ lastErr = fmt.Errorf("match confidence too low: %s (%.2f)",
+ conf, result.BestScore)
+ continue
+ }
+
+ rr.NewRef = result.BestRef
+ rr.Score = result.BestScore
+ rr.Confidence = conf
+ rr.Strategy = result.Strategy
+
+ nodeID, ok := re.ResolveNode(tabID, result.BestRef)
+ if !ok {
+ lastErr = fmt.Errorf("new ref %s not in cache after refresh", result.BestRef)
+ continue
+ }
+
+ actionResult, execErr := exec(ctx, kind, nodeID)
+ rr.LatencyMs = time.Since(start).Milliseconds()
+ if execErr != nil {
+ lastErr = execErr
+ continue
+ }
+
+ rr.Recovered = true
+ return rr, actionResult, nil
+ }
+
+ rr.LatencyMs = time.Since(start).Milliseconds()
+ if lastErr != nil {
+ rr.Error = lastErr.Error()
+ }
+ return rr, nil, lastErr
+}
+
+// reconstructQuery builds the best possible search query from the
+// IntentCache. It prefers an explicit query string, falls back to the
+// element's composite descriptor.
+func (re *RecoveryEngine) reconstructQuery(tabID, ref string) string {
+ if re.IntentCache == nil {
+ return ""
+ }
+ entry, ok := re.IntentCache.Lookup(tabID, ref)
+ if !ok {
+ return ""
+ }
+ if entry.Query != "" {
+ return entry.Query
+ }
+ return entry.Descriptor.Composite()
+}
+
+// RecordIntent is a convenience for the handler layer to cache element
+// intent after a successful /find or before an action execution.
+func (re *RecoveryEngine) RecordIntent(tabID, ref string, entry IntentEntry) {
+ if re.IntentCache != nil {
+ re.IntentCache.Store(tabID, ref, entry)
+ }
+}
diff --git a/internal/semantic/recovery_test.go b/internal/semantic/recovery_test.go
new file mode 100644
index 00000000..c59ace68
--- /dev/null
+++ b/internal/semantic/recovery_test.go
@@ -0,0 +1,1284 @@
+package semantic
+
+import (
+ "context"
+ "fmt"
+ "strings"
+ "testing"
+ "time"
+)
+
+// ===========================================================================
+// FailureType classification tests
+// ===========================================================================
+
+func TestClassifyFailure_NilError(t *testing.T) {
+ ft := ClassifyFailure(nil)
+ if ft != FailureUnknown {
+ t.Errorf("ClassifyFailure(nil) = %v, want FailureUnknown", ft)
+ }
+}
+
+func TestClassifyFailure_ElementNotFound(t *testing.T) {
+ patterns := []string{
+ "could not find node with id 42",
+ "node with given id not found",
+ "no node for backendNodeId 123",
+ "ref not found: e15",
+ "Node not found for the given backend node id",
+ "backend node id cannot be resolved",
+ "no node with given id",
+ }
+ for _, p := range patterns {
+ ft := ClassifyFailure(fmt.Errorf("%s", p))
+ if ft != FailureElementNotFound {
+ t.Errorf("ClassifyFailure(%q) = %v, want FailureElementNotFound", p, ft)
+ }
+ }
+}
+
+func TestClassifyFailure_ElementStale(t *testing.T) {
+ patterns := []string{
+ "stale element reference",
+ "node is detached from the document",
+ "execution context was destroyed",
+ "orphan node detected",
+ "object reference not set",
+ }
+ for _, p := range patterns {
+ ft := ClassifyFailure(fmt.Errorf("%s", p))
+ if ft != FailureElementStale {
+ t.Errorf("ClassifyFailure(%q) = %v, want FailureElementStale", p, ft)
+ }
+ }
+}
+
+func TestClassifyFailure_NotInteractable(t *testing.T) {
+ patterns := []string{
+ "node is not visible on the page",
+ "element is not interactable at point (100, 200)",
+ "overlapping element covers the target",
+ "element is disabled",
+ "cannot focus the target element",
+ "Element is outside of the viewport",
+ }
+ for _, p := range patterns {
+ ft := ClassifyFailure(fmt.Errorf("%s", p))
+ if ft != FailureElementNotInteractable {
+ t.Errorf("ClassifyFailure(%q) = %v, want FailureElementNotInteractable", p, ft)
+ }
+ }
+}
+
+func TestClassifyFailure_Navigation(t *testing.T) {
+ patterns := []string{
+ "page navigated while action was pending",
+ "Frame was detached during execution",
+ "inspected target navigated or closed",
+ "Navigated away from page",
+ }
+ for _, p := range patterns {
+ ft := ClassifyFailure(fmt.Errorf("%s", p))
+ if ft != FailureNavigation {
+ t.Errorf("ClassifyFailure(%q) = %v, want FailureNavigation", p, ft)
+ }
+ }
+}
+
+func TestClassifyFailure_Network(t *testing.T) {
+ patterns := []string{
+ "connection refused to remote debugging port",
+ "websocket connection closed unexpectedly",
+ "could not connect to Chrome",
+ "timeout waiting for response from browser",
+ }
+ for _, p := range patterns {
+ ft := ClassifyFailure(fmt.Errorf("%s", p))
+ if ft != FailureNetwork {
+ t.Errorf("ClassifyFailure(%q) = %v, want FailureNetwork", p, ft)
+ }
+ }
+}
+
+func TestClassifyFailure_Unknown(t *testing.T) {
+ patterns := []string{
+ "something completely unexpected happened",
+ "random error",
+ }
+ for _, p := range patterns {
+ ft := ClassifyFailure(fmt.Errorf("%s", p))
+ if ft != FailureUnknown {
+ t.Errorf("ClassifyFailure(%q) = %v, want FailureUnknown", p, ft)
+ }
+ }
+}
+
+func TestFailureType_String(t *testing.T) {
+ cases := map[FailureType]string{
+ FailureUnknown: "unknown",
+ FailureElementNotFound: "element_not_found",
+ FailureElementStale: "element_stale",
+ FailureElementNotInteractable: "element_not_interactable",
+ FailureNavigation: "navigation",
+ FailureNetwork: "network",
+ }
+ for ft, want := range cases {
+ if ft.String() != want {
+ t.Errorf("FailureType(%d).String() = %q, want %q", ft, ft.String(), want)
+ }
+ }
+}
+
+func TestFailureType_Recoverable(t *testing.T) {
+ recoverable := []FailureType{
+ FailureElementNotFound,
+ FailureElementStale,
+ FailureElementNotInteractable,
+ FailureNavigation,
+ }
+ for _, ft := range recoverable {
+ if !ft.Recoverable() {
+ t.Errorf("%v.Recoverable() = false, want true", ft)
+ }
+ }
+ nonRecoverable := []FailureType{
+ FailureUnknown,
+ FailureNetwork,
+ }
+ for _, ft := range nonRecoverable {
+ if ft.Recoverable() {
+ t.Errorf("%v.Recoverable() = true, want false", ft)
+ }
+ }
+}
+
+// ===========================================================================
+// IntentCache tests
+// ===========================================================================
+
+func TestIntentCache_StoreAndLookup(t *testing.T) {
+ c := NewIntentCache(100, 5*time.Minute)
+
+ entry := IntentEntry{
+ Query: "submit button",
+ Descriptor: ElementDescriptor{Ref: "e1", Role: "button", Name: "Submit"},
+ Score: 0.95,
+ Confidence: "high",
+ Strategy: "combined",
+ }
+ c.Store("tab1", "e1", entry)
+
+ got, ok := c.Lookup("tab1", "e1")
+ if !ok {
+ t.Fatal("Lookup returned false for stored entry")
+ }
+ if got.Query != "submit button" {
+ t.Errorf("Query = %q, want %q", got.Query, "submit button")
+ }
+ if got.Descriptor.Role != "button" {
+ t.Errorf("Descriptor.Role = %q, want %q", got.Descriptor.Role, "button")
+ }
+ if got.Score != 0.95 {
+ t.Errorf("Score = %f, want 0.95", got.Score)
+ }
+}
+
+func TestIntentCache_LookupMiss(t *testing.T) {
+ c := NewIntentCache(100, 5*time.Minute)
+
+ _, ok := c.Lookup("tab1", "e1")
+ if ok {
+ t.Error("Lookup returned true for missing entry")
+ }
+ // Wrong tab.
+ c.Store("tab1", "e1", IntentEntry{Query: "test"})
+ _, ok = c.Lookup("tab2", "e1")
+ if ok {
+ t.Error("Lookup returned true for wrong tab")
+ }
+}
+
+func TestIntentCache_TTLExpiry(t *testing.T) {
+ c := NewIntentCache(100, 50*time.Millisecond)
+
+ c.Store("tab1", "e1", IntentEntry{Query: "test", CachedAt: time.Now()})
+
+ // Should be found immediately.
+ _, ok := c.Lookup("tab1", "e1")
+ if !ok {
+ t.Fatal("Lookup should find fresh entry")
+ }
+
+ // Wait for expiry.
+ time.Sleep(60 * time.Millisecond)
+ _, ok = c.Lookup("tab1", "e1")
+ if ok {
+ t.Error("Lookup should return false after TTL expiry")
+ }
+}
+
+func TestIntentCache_LRUEviction(t *testing.T) {
+ c := NewIntentCache(3, 5*time.Minute)
+
+ // Fill to capacity.
+ c.Store("tab1", "e1", IntentEntry{Query: "first", CachedAt: time.Now().Add(-3 * time.Minute)})
+ c.Store("tab1", "e2", IntentEntry{Query: "second", CachedAt: time.Now().Add(-2 * time.Minute)})
+ c.Store("tab1", "e3", IntentEntry{Query: "third", CachedAt: time.Now().Add(-1 * time.Minute)})
+
+ // Add one more — oldest (e1) should be evicted.
+ c.Store("tab1", "e4", IntentEntry{Query: "fourth"})
+
+ _, ok := c.Lookup("tab1", "e1")
+ if ok {
+ t.Error("e1 should have been evicted (oldest)")
+ }
+ _, ok = c.Lookup("tab1", "e4")
+ if !ok {
+ t.Error("e4 should be present after eviction")
+ }
+}
+
+func TestIntentCache_InvalidateTab(t *testing.T) {
+ c := NewIntentCache(100, 5*time.Minute)
+
+ c.Store("tab1", "e1", IntentEntry{Query: "test"})
+ c.Store("tab1", "e2", IntentEntry{Query: "test2"})
+ c.Store("tab2", "e1", IntentEntry{Query: "other"})
+
+ c.InvalidateTab("tab1")
+
+ _, ok := c.Lookup("tab1", "e1")
+ if ok {
+ t.Error("tab1/e1 should be gone after InvalidateTab")
+ }
+ _, ok = c.Lookup("tab2", "e1")
+ if !ok {
+ t.Error("tab2/e1 should still be present")
+ }
+}
+
+func TestIntentCache_Size(t *testing.T) {
+ c := NewIntentCache(100, 5*time.Minute)
+ if c.Size() != 0 {
+ t.Errorf("Size = %d, want 0", c.Size())
+ }
+
+ c.Store("tab1", "e1", IntentEntry{Query: "a"})
+ c.Store("tab1", "e2", IntentEntry{Query: "b"})
+ c.Store("tab2", "e3", IntentEntry{Query: "c"})
+ if c.Size() != 3 {
+ t.Errorf("Size = %d, want 3", c.Size())
+ }
+}
+
+func TestIntentCache_UpdateExisting(t *testing.T) {
+ c := NewIntentCache(100, 5*time.Minute)
+
+ c.Store("tab1", "e1", IntentEntry{Query: "old query"})
+ c.Store("tab1", "e1", IntentEntry{Query: "new query"})
+
+ got, ok := c.Lookup("tab1", "e1")
+ if !ok {
+ t.Fatal("Lookup should find updated entry")
+ }
+ if got.Query != "new query" {
+ t.Errorf("Query = %q, want %q", got.Query, "new query")
+ }
+ if c.Size() != 1 {
+ t.Errorf("Size = %d, want 1 (update should not add)", c.Size())
+ }
+}
+
+func TestIntentCache_DefaultValues(t *testing.T) {
+ // Zero/negative values should be replaced with defaults.
+ c := NewIntentCache(0, 0)
+ if c.maxRefs != 200 {
+ t.Errorf("maxRefs = %d, want 200", c.maxRefs)
+ }
+ if c.ttl != 10*time.Minute {
+ t.Errorf("ttl = %v, want 10m", c.ttl)
+ }
+}
+
+// ===========================================================================
+// RecoveryEngine tests
+// ===========================================================================
+
+// mockMatcher is a configurable test double for ElementMatcher.
+type mockMatcher struct {
+ findFn func(ctx context.Context, query string, descs []ElementDescriptor, opts FindOptions) (FindResult, error)
+}
+
+func (m *mockMatcher) Find(ctx context.Context, query string, descs []ElementDescriptor, opts FindOptions) (FindResult, error) {
+ if m.findFn != nil {
+ return m.findFn(ctx, query, descs, opts)
+ }
+ return FindResult{}, fmt.Errorf("mockMatcher: Find not configured")
+}
+
+func (m *mockMatcher) Strategy() string { return "mock" }
+
+func TestRecoveryEngine_ShouldAttempt(t *testing.T) {
+ re := &RecoveryEngine{Config: DefaultRecoveryConfig()}
+
+ if re.ShouldAttempt(nil, "e1") {
+ t.Error("ShouldAttempt(nil, e1) = true, want false")
+ }
+ if re.ShouldAttempt(fmt.Errorf("could not find node"), "") {
+ t.Error("ShouldAttempt(err, '') = true, want false (empty ref)")
+ }
+ if re.ShouldAttempt(fmt.Errorf("could not find node"), "e1") != true {
+ t.Error("ShouldAttempt(notFound, e1) = false, want true")
+ }
+ if re.ShouldAttempt(fmt.Errorf("stale element"), "e1") != true {
+ t.Error("ShouldAttempt(stale, e1) = false, want true")
+ }
+ if re.ShouldAttempt(fmt.Errorf("websocket connection closed"), "e1") {
+ t.Error("ShouldAttempt(network, e1) = true, want false (not recoverable)")
+ }
+ if re.ShouldAttempt(fmt.Errorf("random error xyz"), "e1") {
+ t.Error("ShouldAttempt(unknown, e1) = true, want false")
+ }
+}
+
+func TestRecoveryEngine_ShouldAttempt_Disabled(t *testing.T) {
+ cfg := DefaultRecoveryConfig()
+ cfg.Enabled = false
+ re := &RecoveryEngine{Config: cfg}
+
+ if re.ShouldAttempt(fmt.Errorf("could not find node"), "e1") {
+ t.Error("ShouldAttempt should return false when disabled")
+ }
+}
+
+func TestRecoveryEngine_Attempt_NoCachedIntent(t *testing.T) {
+ cache := NewIntentCache(100, 5*time.Minute)
+ re := NewRecoveryEngine(
+ DefaultRecoveryConfig(),
+ &mockMatcher{},
+ cache,
+ nil, nil, nil,
+ )
+
+ rr, res, err := re.Attempt(context.Background(), "tab1", "e99", "click", nil)
+ if err == nil {
+ t.Error("expected error when no intent cached")
+ }
+ if rr.Recovered {
+ t.Error("Recovered should be false")
+ }
+ if res != nil {
+ t.Error("result should be nil")
+ }
+ if !strings.Contains(rr.Error, "no cached intent") {
+ t.Errorf("Error = %q, want to contain 'no cached intent'", rr.Error)
+ }
+}
+
+func TestRecoveryEngine_Attempt_Success(t *testing.T) {
+ cache := NewIntentCache(100, 5*time.Minute)
+ cache.Store("tab1", "e5", IntentEntry{
+ Query: "submit button",
+ Descriptor: ElementDescriptor{Ref: "e5", Role: "button", Name: "Submit"},
+ })
+
+ matcher := &mockMatcher{
+ findFn: func(_ context.Context, query string, descs []ElementDescriptor, opts FindOptions) (FindResult, error) {
+ if query != "submit button" {
+ return FindResult{}, fmt.Errorf("unexpected query: %s", query)
+ }
+ return FindResult{
+ BestRef: "e12",
+ BestScore: 0.88,
+ Matches: []ElementMatch{
+ {Ref: "e12", Role: "button", Name: "Submit Form", Score: 0.88},
+ },
+ Strategy: "combined",
+ ElementCount: 3,
+ }, nil
+ },
+ }
+
+ refreshCalled := false
+ re := NewRecoveryEngine(
+ DefaultRecoveryConfig(),
+ matcher,
+ cache,
+ func(ctx context.Context, tabID string) error {
+ refreshCalled = true
+ return nil
+ },
+ func(tabID, ref string) (int64, bool) {
+ if ref == "e12" {
+ return 42, true
+ }
+ return 0, false
+ },
+ func(tabID string) []ElementDescriptor {
+ return []ElementDescriptor{
+ {Ref: "e10", Role: "link", Name: "Home"},
+ {Ref: "e12", Role: "button", Name: "Submit Form"},
+ {Ref: "e14", Role: "textbox", Name: "Email"},
+ }
+ },
+ )
+
+ actionCalled := false
+ rr, res, err := re.Attempt(context.Background(), "tab1", "e5", "click",
+ func(ctx context.Context, kind string, nodeID int64) (map[string]any, error) {
+ actionCalled = true
+ if kind != "click" {
+ return nil, fmt.Errorf("wrong kind: %s", kind)
+ }
+ if nodeID != 42 {
+ return nil, fmt.Errorf("wrong nodeID: %d", nodeID)
+ }
+ return map[string]any{"clicked": true}, nil
+ },
+ )
+
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if !rr.Recovered {
+ t.Error("Recovered should be true")
+ }
+ if !refreshCalled {
+ t.Error("snapshot refresh was not called")
+ }
+ if !actionCalled {
+ t.Error("action executor was not called")
+ }
+ if rr.NewRef != "e12" {
+ t.Errorf("NewRef = %q, want %q", rr.NewRef, "e12")
+ }
+ if rr.Score != 0.88 {
+ t.Errorf("Score = %f, want 0.88", rr.Score)
+ }
+ if rr.OriginalRef != "e5" {
+ t.Errorf("OriginalRef = %q, want %q", rr.OriginalRef, "e5")
+ }
+ if res["clicked"] != true {
+ t.Errorf("action result missing clicked=true")
+ }
+ if rr.LatencyMs < 0 {
+ t.Errorf("LatencyMs = %d, should be >= 0", rr.LatencyMs)
+ }
+}
+
+func TestRecoveryEngine_Attempt_ScoreBelowThreshold(t *testing.T) {
+ cache := NewIntentCache(100, 5*time.Minute)
+ cache.Store("tab1", "e1", IntentEntry{
+ Query: "submit button",
+ })
+
+ matcher := &mockMatcher{
+ findFn: func(_ context.Context, _ string, _ []ElementDescriptor, _ FindOptions) (FindResult, error) {
+ return FindResult{
+ BestRef: "e2",
+ BestScore: 0.25, // Below default MinConfidence (0.4)
+ }, nil
+ },
+ }
+
+ re := NewRecoveryEngine(
+ DefaultRecoveryConfig(),
+ matcher,
+ cache,
+ func(_ context.Context, _ string) error { return nil },
+ func(_, _ string) (int64, bool) { return 10, true },
+ func(_ string) []ElementDescriptor {
+ return []ElementDescriptor{{Ref: "e2", Role: "button", Name: "Cancel"}}
+ },
+ )
+
+ rr, _, err := re.Attempt(context.Background(), "tab1", "e1", "click",
+ func(_ context.Context, _ string, _ int64) (map[string]any, error) {
+ t.Error("action should not be called when score is below threshold")
+ return nil, nil
+ },
+ )
+
+ if err == nil {
+ t.Error("expected error for low score")
+ }
+ if rr.Recovered {
+ t.Error("should not recover with score below threshold")
+ }
+ if !strings.Contains(rr.Error, "no match above threshold") {
+ t.Errorf("Error = %q, want to contain threshold message", rr.Error)
+ }
+}
+
+func TestRecoveryEngine_Attempt_ActionFailsOnReMatch(t *testing.T) {
+ cache := NewIntentCache(100, 5*time.Minute)
+ cache.Store("tab1", "e1", IntentEntry{Query: "login button"})
+
+ matcher := &mockMatcher{
+ findFn: func(_ context.Context, _ string, _ []ElementDescriptor, _ FindOptions) (FindResult, error) {
+ return FindResult{
+ BestRef: "e8",
+ BestScore: 0.9,
+ Strategy: "combined",
+ }, nil
+ },
+ }
+
+ re := NewRecoveryEngine(
+ DefaultRecoveryConfig(),
+ matcher,
+ cache,
+ func(_ context.Context, _ string) error { return nil },
+ func(_, ref string) (int64, bool) {
+ if ref == "e8" {
+ return 77, true
+ }
+ return 0, false
+ },
+ func(_ string) []ElementDescriptor {
+ return []ElementDescriptor{{Ref: "e8", Role: "button", Name: "Login"}}
+ },
+ )
+
+ rr, _, err := re.Attempt(context.Background(), "tab1", "e1", "click",
+ func(_ context.Context, kind string, nodeID int64) (map[string]any, error) {
+ return nil, fmt.Errorf("element is disabled")
+ },
+ )
+
+ if err == nil {
+ t.Error("expected error when action fails after re-match")
+ }
+ if rr.Recovered {
+ t.Error("should not be recovered when re-executed action fails")
+ }
+}
+
+func TestRecoveryEngine_Attempt_EmptySnapshotAfterRefresh(t *testing.T) {
+ cache := NewIntentCache(100, 5*time.Minute)
+ cache.Store("tab1", "e1", IntentEntry{Query: "submit"})
+
+ re := NewRecoveryEngine(
+ DefaultRecoveryConfig(),
+ &mockMatcher{},
+ cache,
+ func(_ context.Context, _ string) error { return nil },
+ nil,
+ func(_ string) []ElementDescriptor { return nil }, // empty snapshot
+ )
+
+ rr, _, err := re.Attempt(context.Background(), "tab1", "e1", "click", nil)
+ if err == nil {
+ t.Error("expected error for empty snapshot")
+ }
+ if !strings.Contains(rr.Error, "empty snapshot") {
+ t.Errorf("Error = %q, want to contain 'empty snapshot'", rr.Error)
+ }
+}
+
+func TestRecoveryEngine_Attempt_RefreshFails(t *testing.T) {
+ cache := NewIntentCache(100, 5*time.Minute)
+ cache.Store("tab1", "e1", IntentEntry{Query: "submit"})
+
+ re := NewRecoveryEngine(
+ DefaultRecoveryConfig(),
+ &mockMatcher{},
+ cache,
+ func(_ context.Context, _ string) error { return fmt.Errorf("CDP timeout") },
+ nil, nil,
+ )
+
+ rr, _, err := re.Attempt(context.Background(), "tab1", "e1", "click", nil)
+ if err == nil {
+ t.Error("expected error when refresh fails")
+ }
+ if !strings.Contains(rr.Error, "refresh snapshot") {
+ t.Errorf("Error = %q, want to contain 'refresh snapshot'", rr.Error)
+ }
+}
+
+func TestRecoveryEngine_Attempt_MatcherError(t *testing.T) {
+ cache := NewIntentCache(100, 5*time.Minute)
+ cache.Store("tab1", "e1", IntentEntry{Query: "submit"})
+
+ matcher := &mockMatcher{
+ findFn: func(_ context.Context, _ string, _ []ElementDescriptor, _ FindOptions) (FindResult, error) {
+ return FindResult{}, fmt.Errorf("internal matcher error")
+ },
+ }
+
+ re := NewRecoveryEngine(
+ DefaultRecoveryConfig(),
+ matcher,
+ cache,
+ func(_ context.Context, _ string) error { return nil },
+ nil,
+ func(_ string) []ElementDescriptor {
+ return []ElementDescriptor{{Ref: "e2", Role: "button", Name: "Submit"}}
+ },
+ )
+
+ rr, _, err := re.Attempt(context.Background(), "tab1", "e1", "click", nil)
+ if err == nil {
+ t.Error("expected error when matcher fails")
+ }
+ if !strings.Contains(rr.Error, "matcher") {
+ t.Errorf("Error = %q, want to contain 'matcher'", rr.Error)
+ }
+}
+
+func TestRecoveryEngine_Attempt_NewRefNotInCache(t *testing.T) {
+ cache := NewIntentCache(100, 5*time.Minute)
+ cache.Store("tab1", "e1", IntentEntry{Query: "submit"})
+
+ matcher := &mockMatcher{
+ findFn: func(_ context.Context, _ string, _ []ElementDescriptor, _ FindOptions) (FindResult, error) {
+ return FindResult{BestRef: "e99", BestScore: 0.9, Strategy: "combined"}, nil
+ },
+ }
+
+ re := NewRecoveryEngine(
+ DefaultRecoveryConfig(),
+ matcher,
+ cache,
+ func(_ context.Context, _ string) error { return nil },
+ func(_, _ string) (int64, bool) { return 0, false }, // ref not in cache
+ func(_ string) []ElementDescriptor {
+ return []ElementDescriptor{{Ref: "e99", Role: "button", Name: "Submit"}}
+ },
+ )
+
+ rr, _, err := re.Attempt(context.Background(), "tab1", "e1", "click", nil)
+ if err == nil {
+ t.Error("expected error when new ref not in node cache")
+ }
+ if !strings.Contains(rr.Error, "not in cache after refresh") {
+ t.Errorf("Error = %q, want to contain 'not in cache after refresh'", rr.Error)
+ }
+}
+
+func TestRecoveryEngine_AttemptWithClassification(t *testing.T) {
+ cache := NewIntentCache(100, 5*time.Minute)
+ cache.Store("tab1", "e3", IntentEntry{
+ Query: "email input",
+ Descriptor: ElementDescriptor{Ref: "e3", Role: "textbox", Name: "Email"},
+ })
+
+ matcher := &mockMatcher{
+ findFn: func(_ context.Context, query string, _ []ElementDescriptor, _ FindOptions) (FindResult, error) {
+ return FindResult{
+ BestRef: "e20",
+ BestScore: 0.85,
+ Strategy: "combined",
+ }, nil
+ },
+ }
+
+ re := NewRecoveryEngine(
+ DefaultRecoveryConfig(),
+ matcher,
+ cache,
+ func(_ context.Context, _ string) error { return nil },
+ func(_, ref string) (int64, bool) {
+ if ref == "e20" {
+ return 55, true
+ }
+ return 0, false
+ },
+ func(_ string) []ElementDescriptor {
+ return []ElementDescriptor{{Ref: "e20", Role: "textbox", Name: "Email Address"}}
+ },
+ )
+
+ rr, res, err := re.AttemptWithClassification(
+ context.Background(), "tab1", "e3", "fill",
+ FailureElementStale,
+ func(_ context.Context, kind string, nodeID int64) (map[string]any, error) {
+ return map[string]any{"filled": true}, nil
+ },
+ )
+
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if !rr.Recovered {
+ t.Error("should be recovered")
+ }
+ if rr.FailureType != "element_stale" {
+ t.Errorf("FailureType = %q, want %q", rr.FailureType, "element_stale")
+ }
+ if res["filled"] != true {
+ t.Error("action result missing filled=true")
+ }
+}
+
+func TestRecoveryEngine_PreferHighConfidence_RejectsLow(t *testing.T) {
+ cache := NewIntentCache(100, 5*time.Minute)
+ cache.Store("tab1", "e1", IntentEntry{Query: "submit"})
+
+ matcher := &mockMatcher{
+ findFn: func(_ context.Context, _ string, _ []ElementDescriptor, _ FindOptions) (FindResult, error) {
+ return FindResult{
+ BestRef: "e2",
+ BestScore: 0.5, // CalibrateConfidence(0.5) = "low"
+ Strategy: "combined",
+ }, nil
+ },
+ }
+
+ cfg := DefaultRecoveryConfig()
+ cfg.PreferHighConfidence = true
+
+ re := NewRecoveryEngine(
+ cfg,
+ matcher,
+ cache,
+ func(_ context.Context, _ string) error { return nil },
+ func(_, _ string) (int64, bool) { return 10, true },
+ func(_ string) []ElementDescriptor {
+ return []ElementDescriptor{{Ref: "e2", Role: "button", Name: "Submit"}}
+ },
+ )
+
+ rr, _, err := re.Attempt(context.Background(), "tab1", "e1", "click", nil)
+ if err == nil {
+ t.Error("expected error when PreferHighConfidence rejects low-confidence match")
+ }
+ if rr.Recovered {
+ t.Error("should not recover with low confidence when PreferHighConfidence=true")
+ }
+ if !strings.Contains(rr.Error, "confidence too low") {
+ t.Errorf("Error = %q, want 'confidence too low'", rr.Error)
+ }
+}
+
+func TestRecoveryEngine_ReconstructQuery_FallbackToComposite(t *testing.T) {
+ cache := NewIntentCache(100, 5*time.Minute)
+ // Store entry with no Query, only a descriptor.
+ cache.Store("tab1", "e1", IntentEntry{
+ Descriptor: ElementDescriptor{Ref: "e1", Role: "button", Name: "Sign In"},
+ })
+
+ querySeen := ""
+ matcher := &mockMatcher{
+ findFn: func(_ context.Context, query string, _ []ElementDescriptor, _ FindOptions) (FindResult, error) {
+ querySeen = query
+ return FindResult{
+ BestRef: "e10",
+ BestScore: 0.9,
+ Strategy: "combined",
+ }, nil
+ },
+ }
+
+ re := NewRecoveryEngine(
+ DefaultRecoveryConfig(),
+ matcher,
+ cache,
+ func(_ context.Context, _ string) error { return nil },
+ func(_, ref string) (int64, bool) {
+ if ref == "e10" {
+ return 33, true
+ }
+ return 0, false
+ },
+ func(_ string) []ElementDescriptor {
+ return []ElementDescriptor{{Ref: "e10", Role: "button", Name: "Sign In"}}
+ },
+ )
+
+ _, _, _ = re.Attempt(context.Background(), "tab1", "e1", "click",
+ func(_ context.Context, _ string, _ int64) (map[string]any, error) {
+ return map[string]any{"ok": true}, nil
+ },
+ )
+
+ // The query should be the Composite() of the descriptor: "button: Sign In"
+ desc := ElementDescriptor{Ref: "e1", Role: "button", Name: "Sign In"}
+ expected := desc.Composite()
+ if querySeen != expected {
+ t.Errorf("reconstructed query = %q, want %q", querySeen, expected)
+ }
+}
+
+func TestRecoveryEngine_RecordIntent(t *testing.T) {
+ cache := NewIntentCache(100, 5*time.Minute)
+ re := NewRecoveryEngine(
+ DefaultRecoveryConfig(),
+ &mockMatcher{},
+ cache,
+ nil, nil, nil,
+ )
+
+ re.RecordIntent("tab1", "e5", IntentEntry{
+ Query: "search box",
+ Descriptor: ElementDescriptor{Ref: "e5", Role: "textbox", Name: "Search"},
+ })
+
+ entry, ok := cache.Lookup("tab1", "e5")
+ if !ok {
+ t.Fatal("RecordIntent should store in IntentCache")
+ }
+ if entry.Query != "search box" {
+ t.Errorf("Query = %q, want %q", entry.Query, "search box")
+ }
+}
+
+func TestRecoveryEngine_RecordIntent_NilCache(t *testing.T) {
+ re := &RecoveryEngine{Config: DefaultRecoveryConfig()}
+ // Should not panic with nil IntentCache.
+ re.RecordIntent("tab1", "e1", IntentEntry{Query: "test"})
+}
+
+// ===========================================================================
+// Realistic scenario tests — simulating real website interactions
+// ===========================================================================
+
+// Scenario: SPA form re-render. User found "Submit" button via /find,
+// then a React re-render assigned new refs. The click on the old ref
+// fails with "could not find node". Recovery should semantically
+// re-locate the Submit button.
+func TestRecovery_Scenario_SPAFormReRender(t *testing.T) {
+ cache := NewIntentCache(100, 5*time.Minute)
+ // Simulate /find having cached the intent for "Submit" button.
+ cache.Store("tab-react-app", "e15", IntentEntry{
+ Query: "submit button",
+ Descriptor: ElementDescriptor{Ref: "e15", Role: "button", Name: "Submit"},
+ Score: 0.95,
+ Confidence: "high",
+ Strategy: "combined",
+ })
+
+ // After re-render, the fresh snapshot has different refs.
+ freshDescs := []ElementDescriptor{
+ {Ref: "e30", Role: "heading", Name: "Contact Form"},
+ {Ref: "e31", Role: "textbox", Name: "Full Name"},
+ {Ref: "e32", Role: "textbox", Name: "Email Address"},
+ {Ref: "e33", Role: "textbox", Name: "Message"},
+ {Ref: "e34", Role: "button", Name: "Submit"},
+ {Ref: "e35", Role: "button", Name: "Cancel"},
+ }
+
+ matcher := NewCombinedMatcher(NewHashingEmbedder(128))
+
+ re := NewRecoveryEngine(
+ DefaultRecoveryConfig(),
+ matcher,
+ cache,
+ func(_ context.Context, _ string) error { return nil },
+ func(_, ref string) (int64, bool) {
+ nodeMap := map[string]int64{
+ "e30": 100, "e31": 101, "e32": 102,
+ "e33": 103, "e34": 104, "e35": 105,
+ }
+ nid, ok := nodeMap[ref]
+ return nid, ok
+ },
+ func(_ string) []ElementDescriptor { return freshDescs },
+ )
+
+ err := fmt.Errorf("could not find node with id 15")
+ if !re.ShouldAttempt(err, "e15") {
+ t.Fatal("ShouldAttempt should be true for 'could not find node'")
+ }
+
+ rr, res, recErr := re.AttemptWithClassification(
+ context.Background(), "tab-react-app", "e15", "click",
+ ClassifyFailure(err),
+ func(_ context.Context, kind string, nodeID int64) (map[string]any, error) {
+ if nodeID != 104 {
+ return nil, fmt.Errorf("wrong node: %d (expected Submit=104)", nodeID)
+ }
+ return map[string]any{"clicked": true}, nil
+ },
+ )
+
+ if recErr != nil {
+ t.Fatalf("recovery failed: %v", recErr)
+ }
+ if !rr.Recovered {
+ t.Error("should have recovered")
+ }
+ if rr.NewRef != "e34" {
+ t.Errorf("NewRef = %q, want e34 (Submit button)", rr.NewRef)
+ }
+ if rr.FailureType != "element_not_found" {
+ t.Errorf("FailureType = %q, want element_not_found", rr.FailureType)
+ }
+ if res["clicked"] != true {
+ t.Error("action result should contain clicked=true")
+ }
+}
+
+// Scenario: E-commerce checkout — the "Place Order" button becomes
+// stale after cart updates via AJAX. Recovery should find the replaced
+// button.
+func TestRecovery_Scenario_EcommerceCheckout(t *testing.T) {
+ cache := NewIntentCache(100, 5*time.Minute)
+ cache.Store("tab-shop", "e50", IntentEntry{
+ Query: "place order button",
+ Descriptor: ElementDescriptor{Ref: "e50", Role: "button", Name: "Place Order"},
+ Score: 0.92,
+ Confidence: "high",
+ })
+
+ freshDescs := []ElementDescriptor{
+ {Ref: "e70", Role: "heading", Name: "Your Cart (3 items)"},
+ {Ref: "e71", Role: "button", Name: "Update Cart"},
+ {Ref: "e72", Role: "button", Name: "Apply Coupon"},
+ {Ref: "e73", Role: "button", Name: "Place Order"},
+ {Ref: "e74", Role: "link", Name: "Continue Shopping"},
+ }
+
+ matcher := NewCombinedMatcher(NewHashingEmbedder(128))
+
+ re := NewRecoveryEngine(
+ DefaultRecoveryConfig(),
+ matcher,
+ cache,
+ func(_ context.Context, _ string) error { return nil },
+ func(_, ref string) (int64, bool) {
+ if ref == "e73" {
+ return 200, true
+ }
+ return 0, false
+ },
+ func(_ string) []ElementDescriptor { return freshDescs },
+ )
+
+ rr, res, err := re.AttemptWithClassification(
+ context.Background(), "tab-shop", "e50", "click",
+ FailureElementStale,
+ func(_ context.Context, _ string, nodeID int64) (map[string]any, error) {
+ return map[string]any{"orderPlaced": true}, nil
+ },
+ )
+
+ if err != nil {
+ t.Fatalf("recovery failed: %v", err)
+ }
+ if !rr.Recovered {
+ t.Error("should recover")
+ }
+ if rr.NewRef != "e73" {
+ t.Errorf("NewRef = %q, want e73", rr.NewRef)
+ }
+ if res["orderPlaced"] != true {
+ t.Error("should have orderPlaced=true")
+ }
+}
+
+// Scenario: Login page — typing into an email field that was replaced
+// by a password field after an SPA navigation.
+func TestRecovery_Scenario_LoginFormNavigation(t *testing.T) {
+ cache := NewIntentCache(100, 5*time.Minute)
+ cache.Store("tab-login", "e20", IntentEntry{
+ Query: "password input field",
+ Descriptor: ElementDescriptor{
+ Ref: "e20", Role: "textbox", Name: "Password",
+ },
+ })
+
+ freshDescs := []ElementDescriptor{
+ {Ref: "e40", Role: "heading", Name: "Log In"},
+ {Ref: "e41", Role: "textbox", Name: "Username or Email"},
+ {Ref: "e42", Role: "textbox", Name: "Password"},
+ {Ref: "e43", Role: "button", Name: "Log In"},
+ {Ref: "e44", Role: "link", Name: "Forgot Password?"},
+ }
+
+ matcher := NewCombinedMatcher(NewHashingEmbedder(128))
+
+ re := NewRecoveryEngine(
+ DefaultRecoveryConfig(),
+ matcher,
+ cache,
+ func(_ context.Context, _ string) error { return nil },
+ func(_, ref string) (int64, bool) {
+ m := map[string]int64{"e40": 1, "e41": 2, "e42": 3, "e43": 4, "e44": 5}
+ nid, ok := m[ref]
+ return nid, ok
+ },
+ func(_ string) []ElementDescriptor { return freshDescs },
+ )
+
+ rr, res, err := re.AttemptWithClassification(
+ context.Background(), "tab-login", "e20", "fill",
+ FailureElementNotFound,
+ func(_ context.Context, kind string, nodeID int64) (map[string]any, error) {
+ if nodeID != 3 { // Password field = e42 = nodeID 3
+ return nil, fmt.Errorf("filled wrong field, nodeID=%d", nodeID)
+ }
+ return map[string]any{"filled": true, "kind": kind}, nil
+ },
+ )
+
+ if err != nil {
+ t.Fatalf("recovery failed: %v", err)
+ }
+ if !rr.Recovered {
+ t.Error("should recover")
+ }
+ if rr.NewRef != "e42" {
+ t.Errorf("NewRef = %q, want e42 (Password field)", rr.NewRef)
+ }
+ if res["filled"] != true {
+ t.Error("should have filled=true")
+ }
+}
+
+// Scenario: Google search page — "Google Search" button re-rendered
+// with slightly different name "Search" after dynamic page update.
+func TestRecovery_Scenario_GoogleSearchButton(t *testing.T) {
+ cache := NewIntentCache(100, 5*time.Minute)
+ cache.Store("tab-google", "e10", IntentEntry{
+ Query: "google search button",
+ Descriptor: ElementDescriptor{Ref: "e10", Role: "button", Name: "Google Search"},
+ })
+
+ freshDescs := []ElementDescriptor{
+ {Ref: "e80", Role: "textbox", Name: "Search"},
+ {Ref: "e81", Role: "button", Name: "Google Search"},
+ {Ref: "e82", Role: "button", Name: "I'm Feeling Lucky"},
+ }
+
+ matcher := NewCombinedMatcher(NewHashingEmbedder(128))
+
+ re := NewRecoveryEngine(
+ DefaultRecoveryConfig(),
+ matcher,
+ cache,
+ func(_ context.Context, _ string) error { return nil },
+ func(_, ref string) (int64, bool) {
+ if ref == "e81" {
+ return 300, true
+ }
+ return 0, false
+ },
+ func(_ string) []ElementDescriptor { return freshDescs },
+ )
+
+ rr, _, err := re.AttemptWithClassification(
+ context.Background(), "tab-google", "e10", "click",
+ FailureElementStale,
+ func(_ context.Context, _ string, nodeID int64) (map[string]any, error) {
+ return map[string]any{"clicked": true}, nil
+ },
+ )
+
+ if err != nil {
+ t.Fatalf("recovery failed: %v", err)
+ }
+ if !rr.Recovered {
+ t.Error("should recover")
+ }
+ if rr.NewRef != "e81" {
+ t.Errorf("NewRef = %q, want e81 (Google Search button)", rr.NewRef)
+ }
+}
+
+// Scenario: Dashboard with many similar buttons. The recovery should
+// still find the right one using the cached query.
+func TestRecovery_Scenario_DashboardSimilarButtons(t *testing.T) {
+ cache := NewIntentCache(100, 5*time.Minute)
+ cache.Store("tab-dash", "e5", IntentEntry{
+ Query: "delete account",
+ Descriptor: ElementDescriptor{
+ Ref: "e5", Role: "button", Name: "Delete Account",
+ },
+ })
+
+ freshDescs := []ElementDescriptor{
+ {Ref: "e100", Role: "button", Name: "Delete Comment"},
+ {Ref: "e101", Role: "button", Name: "Delete Post"},
+ {Ref: "e102", Role: "button", Name: "Delete Account"},
+ {Ref: "e103", Role: "button", Name: "Edit Account"},
+ {Ref: "e104", Role: "button", Name: "Save Settings"},
+ }
+
+ matcher := NewCombinedMatcher(NewHashingEmbedder(128))
+
+ re := NewRecoveryEngine(
+ DefaultRecoveryConfig(),
+ matcher,
+ cache,
+ func(_ context.Context, _ string) error { return nil },
+ func(_, ref string) (int64, bool) {
+ m := map[string]int64{
+ "e100": 10, "e101": 11, "e102": 12, "e103": 13, "e104": 14,
+ }
+ nid, ok := m[ref]
+ return nid, ok
+ },
+ func(_ string) []ElementDescriptor { return freshDescs },
+ )
+
+ rr, _, err := re.AttemptWithClassification(
+ context.Background(), "tab-dash", "e5", "click",
+ FailureElementNotFound,
+ func(_ context.Context, _ string, nodeID int64) (map[string]any, error) {
+ if nodeID != 12 {
+ return nil, fmt.Errorf("wrong button, nodeID=%d want 12 (Delete Account)", nodeID)
+ }
+ return map[string]any{"deleted": true}, nil
+ },
+ )
+
+ if err != nil {
+ t.Fatalf("recovery failed: %v", err)
+ }
+ if !rr.Recovered {
+ t.Error("should recover with correct 'Delete Account' button")
+ }
+ if rr.NewRef != "e102" {
+ t.Errorf("NewRef = %q, want e102 (Delete Account)", rr.NewRef)
+ }
+}
+
+// Scenario: Navigation link that moved position in a CMS after page
+// edit. Descriptor-only recovery (no query stored).
+func TestRecovery_Scenario_CMSNavigationLink(t *testing.T) {
+ cache := NewIntentCache(100, 5*time.Minute)
+ // No query — only descriptor. Recovery falls back to Composite().
+ cache.Store("tab-cms", "e7", IntentEntry{
+ Descriptor: ElementDescriptor{Ref: "e7", Role: "link", Name: "About Us"},
+ })
+
+ freshDescs := []ElementDescriptor{
+ {Ref: "e200", Role: "link", Name: "Home"},
+ {Ref: "e201", Role: "link", Name: "Services"},
+ {Ref: "e202", Role: "link", Name: "About Us"},
+ {Ref: "e203", Role: "link", Name: "Contact"},
+ {Ref: "e204", Role: "link", Name: "Blog"},
+ }
+
+ matcher := NewCombinedMatcher(NewHashingEmbedder(128))
+
+ re := NewRecoveryEngine(
+ DefaultRecoveryConfig(),
+ matcher,
+ cache,
+ func(_ context.Context, _ string) error { return nil },
+ func(_, ref string) (int64, bool) {
+ m := map[string]int64{
+ "e200": 50, "e201": 51, "e202": 52, "e203": 53, "e204": 54,
+ }
+ nid, ok := m[ref]
+ return nid, ok
+ },
+ func(_ string) []ElementDescriptor { return freshDescs },
+ )
+
+ rr, _, err := re.AttemptWithClassification(
+ context.Background(), "tab-cms", "e7", "click",
+ FailureElementNotFound,
+ func(_ context.Context, _ string, nodeID int64) (map[string]any, error) {
+ return map[string]any{"navigated": true}, nil
+ },
+ )
+
+ if err != nil {
+ t.Fatalf("recovery failed: %v", err)
+ }
+ if !rr.Recovered {
+ t.Error("should recover")
+ }
+ if rr.NewRef != "e202" {
+ t.Errorf("NewRef = %q, want e202 (About Us link)", rr.NewRef)
+ }
+}
+
+// Scenario: Unrecoverable network error — recovery should NOT attempt.
+func TestRecovery_Scenario_NetworkError_NoAttempt(t *testing.T) {
+ re := &RecoveryEngine{Config: DefaultRecoveryConfig()}
+
+ err := fmt.Errorf("websocket: connection refused to remote debugging port")
+ if re.ShouldAttempt(err, "e1") {
+ t.Error("ShouldAttempt should be false for network errors")
+ }
+}
+
+// Scenario: Unknown error — recovery should NOT attempt.
+func TestRecovery_Scenario_UnknownError_NoAttempt(t *testing.T) {
+ re := &RecoveryEngine{Config: DefaultRecoveryConfig()}
+
+ err := fmt.Errorf("some completely unexpected internal error")
+ if re.ShouldAttempt(err, "e1") {
+ t.Error("ShouldAttempt should be false for unknown errors")
+ }
+}
+
+// Scenario: MaxRetries > 1. First attempt fails (matcher returns low
+// score), second attempt succeeds after the snapshot changes.
+func TestRecovery_Scenario_MultipleRetries(t *testing.T) {
+ cache := NewIntentCache(100, 5*time.Minute)
+ cache.Store("tab1", "e1", IntentEntry{Query: "save button"})
+
+ attempt := 0
+ matcher := &mockMatcher{
+ findFn: func(_ context.Context, _ string, _ []ElementDescriptor, _ FindOptions) (FindResult, error) {
+ attempt++
+ if attempt == 1 {
+ // First attempt: score too low.
+ return FindResult{BestRef: "e10", BestScore: 0.2}, nil
+ }
+ // Second attempt: match found.
+ return FindResult{BestRef: "e11", BestScore: 0.95, Strategy: "combined"}, nil
+ },
+ }
+
+ cfg := DefaultRecoveryConfig()
+ cfg.MaxRetries = 3
+
+ re := NewRecoveryEngine(
+ cfg,
+ matcher,
+ cache,
+ func(_ context.Context, _ string) error { return nil },
+ func(_, ref string) (int64, bool) {
+ if ref == "e11" {
+ return 99, true
+ }
+ return 0, false
+ },
+ func(_ string) []ElementDescriptor {
+ return []ElementDescriptor{{Ref: "e11", Role: "button", Name: "Save"}}
+ },
+ )
+
+ rr, _, err := re.Attempt(context.Background(), "tab1", "e1", "click",
+ func(_ context.Context, _ string, _ int64) (map[string]any, error) {
+ return map[string]any{"saved": true}, nil
+ },
+ )
+
+ if err != nil {
+ t.Fatalf("recovery failed: %v", err)
+ }
+ if !rr.Recovered {
+ t.Error("should recover on second attempt")
+ }
+ if rr.Attempts != 2 {
+ t.Errorf("Attempts = %d, want 2", rr.Attempts)
+ }
+}
+
+// ===========================================================================
+// DefaultRecoveryConfig tests
+// ===========================================================================
+
+func TestDefaultRecoveryConfig(t *testing.T) {
+ cfg := DefaultRecoveryConfig()
+ if !cfg.Enabled {
+ t.Error("default should be enabled")
+ }
+ if cfg.MaxRetries != 1 {
+ t.Errorf("MaxRetries = %d, want 1", cfg.MaxRetries)
+ }
+ if cfg.MinConfidence != 0.4 {
+ t.Errorf("MinConfidence = %f, want 0.4", cfg.MinConfidence)
+ }
+ if cfg.PreferHighConfidence {
+ t.Error("PreferHighConfidence should be false by default")
+ }
+}