Skip to content

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

fix: after a browser target crash, action errors report selector problems PIN-025

Luigi Agosti3ba9cec93f42
diff --git a/internal/bridge/crash.go b/internal/bridge/crash.go
index 492dea5f..ebdb67a9 100644
--- a/internal/bridge/crash.go
+++ b/internal/bridge/crash.go
@@ -14,14 +14,17 @@ import (
const maxRecentCrashes = 20
-// CrashEvent contains information about a crash
+// CrashEvent contains information about a crash. Generation identifies the
+// browser context that was live when the crash was recorded; it is internal to
+// the liveness lookup and never appears in /health or /metrics output.
type CrashEvent struct {
- Time time.Time `json:"time"`
- TargetID string `json:"targetId,omitempty"`
- TabID string `json:"tabId,omitempty"`
- URL string `json:"url,omitempty"`
- Reason string `json:"reason"`
- LastError string `json:"lastError,omitempty"`
+ Time time.Time `json:"time"`
+ TargetID string `json:"targetId,omitempty"`
+ TabID string `json:"tabId,omitempty"`
+ URL string `json:"url,omitempty"`
+ Reason string `json:"reason"`
+ LastError string `json:"lastError,omitempty"`
+ Generation uint64 `json:"-"`
}
// CrashHandler is called when a crash is detected
@@ -31,8 +34,51 @@ var (
crashMu sync.Mutex
recentCrashEvents []CrashEvent
crashEventsTotal uint64
+
+ genMu sync.Mutex
+ generations = map[context.Context]uint64{}
+ generationOrder []context.Context
+ latestGeneration uint64
)
+// maxTrackedBrowserContexts bounds the generation table. The process drives few
+// browser contexts at a time (one per instance, plus replacements), and evicting
+// the oldest only ever costs an annotation, never a false one.
+const maxTrackedBrowserContexts = 16
+
+// BrowserContextGeneration numbers browser contexts: each context keeps its own
+// generation for as long as it is tracked, and a context never seen before takes
+// the next one. Crash state is process-global and shared across every instance
+// the process drives, so a crash is only current when its generation matches the
+// browser context the request is being served on — that is what keeps a replaced
+// browser, or a different instance, from answering for someone else's death.
+// Generations are keyed off the context itself rather than a counter the
+// lifecycle paths maintain, so no launch/attach/remote-CDP site can forget to
+// bump one.
+func BrowserContextGeneration(ctx context.Context) uint64 {
+ if ctx == nil {
+ return 0
+ }
+ genMu.Lock()
+ defer genMu.Unlock()
+ if generation, ok := generations[ctx]; ok {
+ return generation
+ }
+ latestGeneration++
+ generations[ctx] = latestGeneration
+ generationOrder = append(generationOrder, ctx)
+ if len(generationOrder) > maxTrackedBrowserContexts {
+ delete(generations, generationOrder[0])
+ generationOrder = generationOrder[1:]
+ }
+ return latestGeneration
+}
+
+func recordCrashEventForContext(ctx context.Context, ev CrashEvent) {
+ ev.Generation = BrowserContextGeneration(ctx)
+ recordCrashEvent(ev)
+}
+
func recordCrashEvent(ev CrashEvent) {
if ev.Time.IsZero() {
ev.Time = time.Now()
@@ -46,6 +92,25 @@ func recordCrashEvent(ev CrashEvent) {
}
}
+// CrashForBrowserContext returns the most recent crash recorded for the browser
+// context the caller is serving, if any. Crashes from a browser that has since
+// been replaced belong to an earlier generation and are not reported, so a
+// recovered browser stops answering for its predecessor's death.
+func CrashForBrowserContext(ctx context.Context) (CrashEvent, bool) {
+ if ctx == nil {
+ return CrashEvent{}, false
+ }
+ generation := BrowserContextGeneration(ctx)
+ crashMu.Lock()
+ defer crashMu.Unlock()
+ for i := len(recentCrashEvents) - 1; i >= 0; i-- {
+ if recentCrashEvents[i].Generation == generation {
+ return recentCrashEvents[i], true
+ }
+ }
+ return CrashEvent{}, false
+}
+
// CrashSnapshot returns recent crash diagnostics for /health and /metrics.
func CrashSnapshot() map[string]any {
crashMu.Lock()
@@ -71,6 +136,10 @@ func ResetCrashMonitoringForTests() {
crashMu.Lock()
recentCrashEvents = nil
crashMu.Unlock()
+ genMu.Lock()
+ generations = map[context.Context]uint64{}
+ generationOrder = nil
+ genMu.Unlock()
}
// RecordCrashForTests injects a crash event for diagnostics tests.
@@ -78,6 +147,12 @@ func RecordCrashForTests(ev CrashEvent) {
recordCrashEvent(ev)
}
+// RecordCrashForContextTests injects a crash event stamped with the generation
+// of ctx, so tests can stage crashes on a specific browser context.
+func RecordCrashForContextTests(ctx context.Context, ev CrashEvent) {
+ recordCrashEventForContext(ctx, ev)
+}
+
// MonitorCrashes listens for browser and tab crashes
func (b *Bridge) MonitorCrashes(handler CrashHandler) {
if b.BrowserCtx == nil {
@@ -92,7 +167,7 @@ func (b *Bridge) MonitorCrashes(handler CrashHandler) {
Time: time.Now(),
Reason: "inspector.targetCrashed",
}
- recordCrashEvent(event)
+ recordCrashEventForContext(b.BrowserCtx, event)
slog.Error("🔥 TARGET CRASHED",
"event", "inspector.targetCrashed",
)
@@ -106,7 +181,7 @@ func (b *Bridge) MonitorCrashes(handler CrashHandler) {
TargetID: string(e.TargetID),
Reason: e.Status,
}
- recordCrashEvent(event)
+ recordCrashEventForContext(b.BrowserCtx, event)
slog.Error("🔥 TARGET CRASHED",
"targetId", e.TargetID,
"status", e.Status,
@@ -142,7 +217,7 @@ func (b *Bridge) MonitorCrashes(handler CrashHandler) {
Time: time.Now(),
Reason: reason,
}
- recordCrashEvent(event)
+ recordCrashEventForContext(b.BrowserCtx, event)
slog.Warn("🔥 BROWSER CONTEXT ENDED UNEXPECTEDLY", "error", err)
if handler != nil {
handler(event)
diff --git a/internal/bridge/crash_generation_test.go b/internal/bridge/crash_generation_test.go
new file mode 100644
index 00000000..52ca0020
--- /dev/null
+++ b/internal/bridge/crash_generation_test.go
@@ -0,0 +1,117 @@
+package bridge
+
+import (
+ "context"
+ "encoding/json"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestBrowserContextGenerationIsStablePerContext(t *testing.T) {
+ ResetCrashMonitoringForTests()
+ t.Cleanup(ResetCrashMonitoringForTests)
+
+ first := context.Background()
+ second, cancel := context.WithCancel(context.Background())
+ defer cancel()
+
+ genFirst := BrowserContextGeneration(first)
+ if again := BrowserContextGeneration(first); again != genFirst {
+ t.Fatalf("same context produced generations %d and %d", genFirst, again)
+ }
+ genSecond := BrowserContextGeneration(second)
+ if genSecond == genFirst {
+ t.Fatalf("a new browser context reused generation %d", genSecond)
+ }
+ // A bridge with no browser context yet must not claim a generation, or a
+ // crash would attach itself to "no browser".
+ var missing context.Context
+ if BrowserContextGeneration(missing) != 0 {
+ t.Fatal("a nil context must not claim a generation")
+ }
+}
+
+// A crash belongs to the browser that was live when it happened. After that
+// browser is replaced, requests served on the new context must not be told it
+// crashed — otherwise one transient fault reports forever.
+func TestCrashForBrowserContextIgnoresEarlierGenerations(t *testing.T) {
+ ResetCrashMonitoringForTests()
+ t.Cleanup(ResetCrashMonitoringForTests)
+
+ crashed, cancelCrashed := context.WithCancel(context.Background())
+ defer cancelCrashed()
+ RecordCrashForContextTests(crashed, CrashEvent{Reason: "inspector.targetCrashed"})
+
+ got, ok := CrashForBrowserContext(crashed)
+ if !ok || got.Reason != "inspector.targetCrashed" {
+ t.Fatalf("crash on the live context = %+v (ok=%v), want the recorded crash", got, ok)
+ }
+
+ restarted, cancelRestarted := context.WithCancel(context.Background())
+ defer cancelRestarted()
+ if got, ok := CrashForBrowserContext(restarted); ok {
+ t.Fatalf("a replaced browser still reports the old crash: %+v", got)
+ }
+}
+
+// The crash buffer is process-global and shared across every instance, so a
+// crash on one must not answer for a request served on another.
+func TestCrashForBrowserContextIsPerInstance(t *testing.T) {
+ ResetCrashMonitoringForTests()
+ t.Cleanup(ResetCrashMonitoringForTests)
+
+ instanceA, cancelA := context.WithCancel(context.Background())
+ defer cancelA()
+ instanceB, cancelB := context.WithCancel(context.Background())
+ defer cancelB()
+
+ // Both contexts are seen before the crash, so this is not the "old
+ // generation" case: instance B is live and simply did not crash.
+ BrowserContextGeneration(instanceB)
+ RecordCrashForContextTests(instanceA, CrashEvent{Reason: "killed"})
+
+ if _, ok := CrashForBrowserContext(instanceB); ok {
+ t.Fatal("a crash on another instance reported against a healthy one")
+ }
+ if _, ok := CrashForBrowserContext(instanceA); !ok {
+ t.Fatal("the crashed instance stopped reporting its own crash")
+ }
+}
+
+func TestCrashForBrowserContextReturnsTheMostRecentCrash(t *testing.T) {
+ ResetCrashMonitoringForTests()
+ t.Cleanup(ResetCrashMonitoringForTests)
+
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ RecordCrashForContextTests(ctx, CrashEvent{Reason: "inspector.targetCrashed", Time: time.Unix(1, 0)})
+ RecordCrashForContextTests(ctx, CrashEvent{Reason: "unexpected context cancellation", Time: time.Unix(2, 0)})
+
+ got, ok := CrashForBrowserContext(ctx)
+ if !ok || got.Reason != "unexpected context cancellation" {
+ t.Fatalf("crash = %+v (ok=%v), want the most recent one", got, ok)
+ }
+}
+
+// The generation is bookkeeping for the liveness lookup; /health and /metrics
+// serialize CrashSnapshot directly and must not gain a field.
+func TestCrashSnapshotDoesNotExposeTheGeneration(t *testing.T) {
+ ResetCrashMonitoringForTests()
+ t.Cleanup(ResetCrashMonitoringForTests)
+
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ RecordCrashForContextTests(ctx, CrashEvent{Reason: "killed", TargetID: "T1"})
+
+ encoded, err := json.Marshal(CrashSnapshot())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := string(encoded); strings.Contains(got, "eneration") {
+ t.Fatalf("crash snapshot exposes the generation: %s", got)
+ }
+ if got := string(encoded); !strings.Contains(got, `"reason":"killed"`) || !strings.Contains(got, `"targetId":"T1"`) {
+ t.Fatalf("crash snapshot lost its existing fields: %s", got)
+ }
+}
diff --git a/internal/handlers/actions.go b/internal/handlers/actions.go
index d789af60..f262da19 100644
--- a/internal/handlers/actions.go
+++ b/internal/handlers/actions.go
@@ -357,7 +357,7 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
selectorResolution, err := h.resolveActionRequestSelector(tCtx, resolvedTabID, &req)
if err != nil {
- httpx.Error(w, selectorResolution.httpStatus(), err)
+ h.errorWithCrashContext(w, selectorResolution.httpStatus(), err)
return
}
refMissing := selectorResolution.refMissing
@@ -456,7 +456,7 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
"doNotRetry": true,
}
}
- httpx.ErrorCode(w, 500, "action_failed", fmt.Sprintf("action %s: %v", req.Kind, actionErr), retryable, details)
+ h.errorCodeWithCrashContext(w, 500, "action_failed", fmt.Sprintf("action %s: %v", req.Kind, actionErr), retryable, details)
return
}
diff --git a/internal/handlers/crash_context_test.go b/internal/handlers/crash_context_test.go
new file mode 100644
index 00000000..a72f4694
--- /dev/null
+++ b/internal/handlers/crash_context_test.go
@@ -0,0 +1,252 @@
+package handlers
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+// crashContextBridge serves requests on a browser context the test controls, so
+// a crash can be staged against that exact context (and against a replacement).
+type crashContextBridge struct {
+ mockBridge
+ browserCtx context.Context
+}
+
+func (m *crashContextBridge) BrowserContext() context.Context { return m.browserCtx }
+
+func newCrashContextBridge(t *testing.T) (*crashContextBridge, context.Context) {
+ t.Helper()
+ ctx, cancel := context.WithCancel(context.Background())
+ t.Cleanup(cancel)
+ return &crashContextBridge{browserCtx: ctx}, ctx
+}
+
+func crashHandlers(t *testing.T, b *crashContextBridge) *Handlers {
+ t.Helper()
+ bridge.ResetCrashMonitoringForTests()
+ t.Cleanup(bridge.ResetCrashMonitoringForTests)
+ return New(b, &config.RuntimeConfig{ActionTimeout: time.Second}, nil, nil, nil)
+}
+
+func decodeErrorBody(t *testing.T, w *httptest.ResponseRecorder) map[string]any {
+ t.Helper()
+ var body map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
+ t.Fatalf("decode %q: %v", w.Body.String(), err)
+ }
+ return body
+}
+
+func screenshotResponse(t *testing.T, h *Handlers) *httptest.ResponseRecorder {
+ t.Helper()
+ w := httptest.NewRecorder()
+ h.HandleScreenshot(w, httptest.NewRequest("GET", "/screenshot?selector=h1&format=png", nil))
+ return w
+}
+
+func actionResponse(t *testing.T, h *Handlers) *httptest.ResponseRecorder {
+ t.Helper()
+ w := httptest.NewRecorder()
+ h.HandleAction(w, httptest.NewRequest("GET", "/action?kind=click&selector=h1", nil))
+ return w
+}
+
+// The reported symptom: after the browser died every call blamed the caller's
+// selector, and only /health knew what had happened.
+func TestReadAndActionErrorsNameTheBrowserCrash(t *testing.T) {
+ cases := []struct {
+ name string
+ request func(*testing.T, *Handlers) *httptest.ResponseRecorder
+ }{
+ {name: "screenshot", request: screenshotResponse},
+ {name: "action", request: actionResponse},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ b, ctx := newCrashContextBridge(t)
+ h := crashHandlers(t, b)
+ bridge.RecordCrashForContextTests(ctx, bridge.CrashEvent{Reason: "inspector.targetCrashed"})
+
+ w := tc.request(t, h)
+ if w.Code < 400 {
+ t.Fatalf("status = %d, want a failure to annotate (body=%s)", w.Code, w.Body.String())
+ }
+ body := decodeErrorBody(t, w)
+
+ message, _ := body["error"].(string)
+ if !strings.Contains(message, "inspector.targetCrashed") {
+ t.Errorf("error = %q, want the crash reason in the message", message)
+ }
+
+ details, ok := body["details"].(map[string]any)
+ if !ok {
+ t.Fatalf("response has no details: %s", w.Body.String())
+ }
+ // The CLI renders details.hint, so this is what reaches the user
+ // without a separate /health call.
+ hint, _ := details["hint"].(string)
+ if !strings.Contains(hint, "browser crashed") || !strings.Contains(hint, "inspector.targetCrashed") {
+ t.Errorf("hint = %q, want it to name the crash", hint)
+ }
+ if details["browserCrashed"] != true {
+ t.Errorf("details = %v, want browserCrashed", details)
+ }
+ })
+ }
+}
+
+// Without a crash the error must be exactly what it was before this change.
+func TestErrorsAreUnchangedWithoutACrash(t *testing.T) {
+ b, _ := newCrashContextBridge(t)
+ h := crashHandlers(t, b)
+
+ shot := decodeErrorBody(t, screenshotResponse(t, h))
+ if shot["code"] != "error" {
+ t.Errorf("screenshot code = %v, want the plain error code", shot["code"])
+ }
+ if _, ok := shot["details"]; ok {
+ t.Errorf("screenshot response gained details without a crash: %v", shot)
+ }
+ if message, _ := shot["error"].(string); strings.Contains(message, "browser crashed") {
+ t.Errorf("screenshot error mentions a crash that did not happen: %q", message)
+ }
+
+ act := decodeErrorBody(t, actionResponse(t, h))
+ if message, _ := act["error"].(string); strings.Contains(message, "browser crashed") {
+ t.Errorf("action error mentions a crash that did not happen: %q", message)
+ }
+ if details, ok := act["details"].(map[string]any); ok {
+ if _, crashed := details["browserCrashed"]; crashed {
+ t.Errorf("action response claims a crash: %v", details)
+ }
+ }
+}
+
+// A crash on the browser that has since been replaced must not annotate
+// anything: the guard is generation-scoped, not a lifetime flag.
+func TestCrashFromAPreviousGenerationDoesNotAnnotate(t *testing.T) {
+ b, _ := newCrashContextBridge(t)
+ h := crashHandlers(t, b)
+
+ deadCtx, cancelDead := context.WithCancel(context.Background())
+ defer cancelDead()
+ bridge.RecordCrashForContextTests(deadCtx, bridge.CrashEvent{Reason: "killed"})
+
+ body := decodeErrorBody(t, screenshotResponse(t, h))
+ if message, _ := body["error"].(string); strings.Contains(message, "killed") {
+ t.Errorf("error = %q, want no annotation from a replaced browser", message)
+ }
+ if _, ok := body["details"]; ok {
+ t.Errorf("response annotated from a previous generation: %v", body)
+ }
+}
+
+// After the browser is replaced the same handler must stop reporting the crash,
+// which is what keeps one transient fault from failing every later request.
+func TestRestartedBrowserStopsReportingTheOldCrash(t *testing.T) {
+ b, ctx := newCrashContextBridge(t)
+ h := crashHandlers(t, b)
+ bridge.RecordCrashForContextTests(ctx, bridge.CrashEvent{Reason: "inspector.targetCrashed"})
+
+ crashed := decodeErrorBody(t, screenshotResponse(t, h))
+ if message, _ := crashed["error"].(string); !strings.Contains(message, "inspector.targetCrashed") {
+ t.Fatalf("error = %q, want the crash reported while it is current", message)
+ }
+
+ restarted, cancelRestarted := context.WithCancel(context.Background())
+ defer cancelRestarted()
+ b.browserCtx = restarted
+
+ recovered := decodeErrorBody(t, screenshotResponse(t, h))
+ if message, _ := recovered["error"].(string); strings.Contains(message, "inspector.targetCrashed") {
+ t.Errorf("error = %q, want the restarted browser to stop reporting the old crash", message)
+ }
+}
+
+// context canceled from browser death must not read like a client disconnect or
+// an action timeout, which produce the same bare string today.
+func TestCanceledContextFromBrowserDeathIsDistinguishable(t *testing.T) {
+ b, ctx := newCrashContextBridge(t)
+ h := crashHandlers(t, b)
+ bridge.RecordCrashForContextTests(ctx, bridge.CrashEvent{Reason: "unexpected context cancellation"})
+
+ w := httptest.NewRecorder()
+ h.errorWithCrashContext(w, http.StatusInternalServerError, context.Canceled)
+ body := decodeErrorBody(t, w)
+
+ message, _ := body["error"].(string)
+ if !strings.Contains(message, "context canceled") {
+ t.Errorf("error = %q, want the original cancellation text preserved", message)
+ }
+ if !strings.Contains(message, "unexpected context cancellation") {
+ t.Errorf("error = %q, want the browser death named alongside it", message)
+ }
+ if body["code"] != "browser_crashed" {
+ t.Errorf("code = %v, want browser_crashed", body["code"])
+ }
+}
+
+// Annotating must not drop what the caller already relies on: the action path
+// keeps its own code, retryable flag and details.
+func TestCrashAnnotationPreservesExistingErrorCodeAndDetails(t *testing.T) {
+ b, ctx := newCrashContextBridge(t)
+ h := crashHandlers(t, b)
+ bridge.RecordCrashForContextTests(ctx, bridge.CrashEvent{Reason: "killed"})
+
+ w := httptest.NewRecorder()
+ h.errorCodeWithCrashContext(w, 500, "action_failed", "action click: boom", true, map[string]any{"dispatch": "unconfirmed"})
+ body := decodeErrorBody(t, w)
+
+ if body["code"] != "action_failed" {
+ t.Errorf("code = %v, want the original action_failed", body["code"])
+ }
+ if body["retryable"] != true {
+ t.Errorf("retryable = %v, want it preserved", body["retryable"])
+ }
+ details, ok := body["details"].(map[string]any)
+ if !ok || details["dispatch"] != "unconfirmed" {
+ t.Fatalf("details = %v, want the original entries kept", body["details"])
+ }
+ if details["browserCrashReason"] != "killed" {
+ t.Errorf("details = %v, want the crash reason added", details)
+ }
+}
+
+// The action-execution failure path is a second, separately-reachable error
+// site: a request that resolves fine and then fails in the browser must also
+// name the crash, not just report "action click: ...".
+func TestActionExecutionFailureNamesTheBrowserCrash(t *testing.T) {
+ b, ctx := newCrashContextBridge(t)
+ b.executeActionErr = errors.New("context canceled")
+ h := crashHandlers(t, b)
+ bridge.RecordCrashForContextTests(ctx, bridge.CrashEvent{Reason: "unexpected context cancellation"})
+
+ w := httptest.NewRecorder()
+ h.HandleAction(w, httptest.NewRequest("POST", "/action", strings.NewReader(`{"kind":"click"}`)))
+
+ if w.Code != http.StatusInternalServerError {
+ t.Fatalf("status = %d, want 500 (body=%s)", w.Code, w.Body.String())
+ }
+ body := decodeErrorBody(t, w)
+ if body["code"] != "action_failed" {
+ t.Errorf("code = %v, want action_failed preserved", body["code"])
+ }
+ message, _ := body["error"].(string)
+ if !strings.Contains(message, "unexpected context cancellation") {
+ t.Errorf("error = %q, want the crash named on the execution failure path", message)
+ }
+ details, ok := body["details"].(map[string]any)
+ if !ok || details["browserCrashReason"] != "unexpected context cancellation" {
+ t.Fatalf("details = %v, want the crash reason", body["details"])
+ }
+}
diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.go
index b24c6675..b793d89c 100644
--- a/internal/handlers/handlers.go
+++ b/internal/handlers/handlers.go
@@ -163,6 +163,62 @@ func (h *Handlers) ensureBrowser(cfg *config.RuntimeConfig) error {
return h.Bridge.EnsureBrowser(cfg)
}
+// browserCrash returns the crash recorded for the browser context this request
+// is being served on, if any. The lookup is scoped to that context's generation:
+// crash state is process-global, so a crash belonging to a browser that has
+// since been replaced — or to another instance — must not answer for a healthy
+// one. HasCrashDiagnostics cannot serve here: it is a monotonic lifetime flag
+// that stays true until process exit.
+func (h *Handlers) browserCrash() (bridge.CrashEvent, bool) {
+ if h == nil || h.Bridge == nil {
+ return bridge.CrashEvent{}, false
+ }
+ return bridge.CrashForBrowserContext(h.Bridge.BrowserContext())
+}
+
+// annotateBrowserCrash rewrites a failing response's message and details to name
+// the browser crash behind it. Without a crash on the live browser context both
+// come back untouched, so uncrashed responses stay byte-identical.
+func (h *Handlers) annotateBrowserCrash(message string, details map[string]any) (string, map[string]any) {
+ crash, ok := h.browserCrash()
+ if !ok {
+ return message, details
+ }
+
+ annotated := make(map[string]any, len(details)+3)
+ for k, v := range details {
+ annotated[k] = v
+ }
+ annotated["browserCrashed"] = true
+ annotated["browserCrashReason"] = crash.Reason
+ annotated["hint"] = fmt.Sprintf(
+ "the browser crashed (%s at %s) — this error is a symptom of the dead browser, not of your selector or timeout; restart it with: pinchtab server restart",
+ crash.Reason, crash.Time.Format(time.RFC3339))
+ return fmt.Sprintf("%s (browser crashed: %s)", message, crash.Reason), annotated
+}
+
+// errorWithCrashContext is httpx.Error plus the crash annotation.
+func (h *Handlers) errorWithCrashContext(w http.ResponseWriter, status int, err error) {
+ message := ""
+ if err != nil {
+ message = err.Error()
+ }
+ annotated, details := h.annotateBrowserCrash(message, nil)
+ if len(details) == 0 {
+ httpx.Error(w, status, err)
+ return
+ }
+ httpx.ErrorCode(w, status, "browser_crashed", annotated, false, details)
+}
+
+// errorCodeWithCrashContext is httpx.ErrorCode plus the crash annotation. The
+// code is preserved so clients keying on it keep working; the crash arrives as
+// message text and details.
+func (h *Handlers) errorCodeWithCrashContext(w http.ResponseWriter, status int, code, message string, retryable bool, details map[string]any) {
+ annotated, annotatedDetails := h.annotateBrowserCrash(message, details)
+ httpx.ErrorCode(w, status, code, annotated, retryable, annotatedDetails)
+}
+
func (h *Handlers) ensureBrowserOrRespond(w http.ResponseWriter, cfg *config.RuntimeConfig) bool {
if err := h.ensureBrowser(cfg); err != nil {
if h.writeBridgeUnavailable(w, err) {
diff --git a/internal/handlers/handlers_test.go b/internal/handlers/handlers_test.go
index 70055fde..3dcdd652 100644
--- a/internal/handlers/handlers_test.go
+++ b/internal/handlers/handlers_test.go
@@ -49,6 +49,10 @@ type mockBridge struct {
createTabContexts []string
}
+// BrowserContext answers the browser-context generation lookup the error paths
+// consult; a partial mock must still be able to say which browser it is serving.
+func (m *mockBridge) BrowserContext() context.Context { return context.Background() }
+
func (m *mockBridge) TabContext(tabID string) (*bridge.TabHandle, string, error) {
if m.failTab {
return nil, "", fmt.Errorf("tab not found")
diff --git a/internal/handlers/screenshot.go b/internal/handlers/screenshot.go
index 83c5f7cd..35299555 100644
--- a/internal/handlers/screenshot.go
+++ b/internal/handlers/screenshot.go
@@ -91,7 +91,7 @@ func (h *Handlers) HandleScreenshot(w http.ResponseWriter, r *http.Request) {
clip, clipErr := h.resolveScreenshotClip(tCtx, resolvedTabID, req.selector)
if clipErr != nil {
- httpx.Error(w, clipErr.status, clipErr.err)
+ h.errorWithCrashContext(w, clipErr.status, clipErr.err)
return
}
@@ -112,7 +112,7 @@ func (h *Handlers) HandleScreenshot(w http.ResponseWriter, r *http.Request) {
DisableActivation: !h.Config.CaptureAllowActivation,
})
if captureErr != nil {
- httpx.Error(w, 500, fmt.Errorf("screenshot: %w", captureErr))
+ h.errorWithCrashContext(w, 500, fmt.Errorf("screenshot: %w", captureErr))
return
}