Skip to content

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

fix(health): surface a server-mode browser crash — tab-not-found names the crash that destroyed the tab, /health and the instance list carry the instances' crashes block, and Monitoring shows it (PIN-293)

Luigi Agosti53e0dc8add25
diff --git a/dashboard/src/components/molecules/InstanceStats.test.tsx b/dashboard/src/components/molecules/InstanceStats.test.tsx
new file mode 100644
index 00000000..ca3c1eb1
--- /dev/null
+++ b/dashboard/src/components/molecules/InstanceStats.test.tsx
@@ -0,0 +1,53 @@
+import { render, screen } from "@testing-library/react";
+import { describe, expect, it } from "vitest";
+import type { Instance } from "../../generated/types";
+import InstanceStats from "./InstanceStats";
+
+const instance: Instance = {
+ id: "inst_1",
+ profileId: "prof_1",
+ profileName: "default",
+ port: "9868",
+ mode: "headless",
+ headless: true,
+ status: "running",
+ startTime: new Date().toISOString(),
+ attached: false,
+};
+
+describe("InstanceStats", () => {
+ it("shows the crash count and the last reason for an instance whose browser crashed", () => {
+ render(
+ <InstanceStats
+ instance={{
+ ...instance,
+ crashes: {
+ total: 2,
+ recent: [
+ {
+ time: "2026-09-03T08:48:11Z",
+ reason: "inspector.targetCrashed",
+ },
+ {
+ time: "2026-09-03T08:49:47Z",
+ reason: "unexpected context cancellation",
+ },
+ ],
+ },
+ }}
+ tabs={[]}
+ />,
+ );
+ expect(screen.getByText("Crashes")).toBeInTheDocument();
+ expect(screen.getByText("2")).toBeInTheDocument();
+ expect(
+ screen.getByText(/last: unexpected context cancellation at/),
+ ).toBeInTheDocument();
+ });
+
+ it("stays silent about crashes for an instance that never crashed", () => {
+ render(<InstanceStats instance={instance} tabs={[]} />);
+ expect(screen.getByText("running")).toBeInTheDocument();
+ expect(screen.queryByText("Crashes")).not.toBeInTheDocument();
+ });
+});
diff --git a/dashboard/src/components/molecules/InstanceStats.tsx b/dashboard/src/components/molecules/InstanceStats.tsx
index cd7f7090..fad45908 100644
--- a/dashboard/src/components/molecules/InstanceStats.tsx
+++ b/dashboard/src/components/molecules/InstanceStats.tsx
@@ -68,6 +68,12 @@ function formatUptime(startTime: string): string {
return `${days}d ${hrs % 24}h`;
}
+function formatCrashTime(time: string): string {
+ const at = new Date(time);
+ if (Number.isNaN(at.getTime())) return time;
+ return at.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
+}
+
function countUniqueDomains(tabs: InstanceTab[]): number {
const domains = new Set<string>();
for (const tab of tabs) {
@@ -91,6 +97,17 @@ export default function InstanceStats({ instance, metrics, tabs }: Props) {
<StatItem label="Status" value={instance.status} />
<StatItem label="Uptime" value={formatUptime(instance.startTime)} />
<StatItem label="Port" value={instance.port} />
+ {instance.crashes && instance.crashes.total > 0 && (
+ <StatItem
+ label="Crashes"
+ value={fmt(instance.crashes.total)}
+ sub={
+ instance.crashes.recent.length > 0
+ ? `last: ${instance.crashes.recent[instance.crashes.recent.length - 1].reason} at ${formatCrashTime(instance.crashes.recent[instance.crashes.recent.length - 1].time)} · tabs open before it were lost`
+ : "tabs open before it were lost"
+ }
+ />
+ )}
</>
)}
</StatGroup>
diff --git a/dashboard/src/generated/types.ts b/dashboard/src/generated/types.ts
index 0cf6f36b..66bb1caf 100644
--- a/dashboard/src/generated/types.ts
+++ b/dashboard/src/generated/types.ts
@@ -58,6 +58,20 @@ export interface Instance {
*/
fallbackFrom?: string;
fallbackReason?: string;
+ crashes?: CrashSummary;
+}
+export interface CrashEvent {
+ time: string;
+ targetId?: string;
+ tabId?: string;
+ url?: string;
+ reason: string;
+ lastError?: string;
+ instanceId?: string;
+}
+export interface CrashSummary {
+ total: number /* uint64 */;
+ recent: CrashEvent[];
}
export interface Agent {
id: string;
diff --git a/dashboard/src/instances/InstanceListItem.tsx b/dashboard/src/instances/InstanceListItem.tsx
index 0ba5912c..4d95940d 100644
--- a/dashboard/src/instances/InstanceListItem.tsx
+++ b/dashboard/src/instances/InstanceListItem.tsx
@@ -49,6 +49,11 @@ export default function InstanceListItem({
<div className="dashboard-mono text-xs text-text-muted">
:{instance.port} · {instance.browser || "chrome"} · {tabCount} tabs
{memoryMB !== undefined && ` · ${memoryMB.toFixed(0)}MB`}
+ {instance.crashes && instance.crashes.total > 0 && (
+ <span className="text-destructive">
+ {` · crashed ×${instance.crashes.total}`}
+ </span>
+ )}
</div>
</div>
</div>
diff --git a/docs/endpoints.md b/docs/endpoints.md
index 2afaf83e..e5734416 100644
--- a/docs/endpoints.md
+++ b/docs/endpoints.md
@@ -20,6 +20,15 @@ Notes:
- in bridge mode, `/health` reports bridge health and tab count
- in full server mode, `/health` reports dashboard health, auth state, and instance count
+- a browser crash is reported the same way in both modes: `/health` carries a `crashes`
+ block (`total`, `recent`) whenever the browser behind it has crashed. In bridge mode the
+ bridge records its own; in full server mode the front door merges every instance's
+ record and each event names its `instanceId`. `status` stays `ok` — a crashed instance is
+ relaunched and is serving again — so watch `crashes`, not `status`, for lost client
+ state. The same block appears on each entry of `GET /instances`. After a crash every
+ tab the browser held is gone, and a call to one answers `404` with code
+ `browser_crashed`, `browserCrashed: true`, `browserCrashReason` and a `hint`, rather
+ than a bare `tab <id> not found`
- `/metrics` reports the counters of the process answering it: in full server mode the front
door's own request counters (auth rejections and unrouted paths included), in bridge mode
the bridge's. Every response names its `layer`, and the layers are never summed — read one
diff --git a/docs/reference/health.md b/docs/reference/health.md
index 184f8bc0..49ca2305 100644
--- a/docs/reference/health.md
+++ b/docs/reference/health.md
@@ -67,12 +67,14 @@ curl http://localhost:9867/health
| `agents` | Connected agent count |
| `restartRequired` | `true` when file-based config changes need restart |
| `restartReasons` | Restart reason list when required |
+| `crashes` | Present once any instance's browser has crashed: `total` and `recent`, the same block bridge `/health` carries, each event naming its `instanceId` |
Notes:
- `defaultInstance` is present when at least one instance exists
- use `defaultInstance.status == "running"` when you want to confirm Chrome is ready
- strategies such as `always-on` can create an instance automatically at startup
+- `status` does not degrade on a browser crash: the instance is relaunched and is serving again. The crash is history, so it rides beside `status` as `crashes`; a crashed-then-relaunched instance differs from one that never crashed by that key alone. Every tab the dead browser held is gone, and a call to one answers `404` with code `browser_crashed` and a `hint` saying so
## Related Pages
diff --git a/internal/api/types/types.go b/internal/api/types/types.go
index 32475c58..0682c4df 100644
--- a/internal/api/types/types.go
+++ b/internal/api/types/types.go
@@ -55,6 +55,23 @@ type Instance struct {
// empty in P2.4a).
FallbackFrom string `json:"fallbackFrom,omitempty"`
FallbackReason string `json:"fallbackReason,omitempty"`
+
+ Crashes *CrashSummary `json:"crashes,omitempty"`
+}
+
+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"`
+ InstanceID string `json:"instanceId,omitempty"`
+}
+
+type CrashSummary struct {
+ Total uint64 `json:"total"`
+ Recent []CrashEvent `json:"recent"`
}
type Agent struct {
diff --git a/internal/bridge/api.go b/internal/bridge/api.go
index e0cbf6ab..066d19df 100644
--- a/internal/bridge/api.go
+++ b/internal/bridge/api.go
@@ -327,6 +327,8 @@ type Instance struct {
// Instance JSON byte-identical to pre-P2.4a output.
FallbackFrom string `json:"fallbackFrom,omitempty"`
FallbackReason string `json:"fallbackReason,omitempty"`
+
+ Crashes *CrashSummary `json:"crashes,omitempty"`
}
func (i Instance) MarshalJSON() ([]byte, error) {
diff --git a/internal/bridge/crash.go b/internal/bridge/crash.go
index 8b6c8f63..2b1e77f7 100644
--- a/internal/bridge/crash.go
+++ b/internal/bridge/crash.go
@@ -2,6 +2,7 @@ package bridge
import (
"context"
+ "fmt"
"log/slog"
"sync"
"sync/atomic"
@@ -14,6 +15,8 @@ import (
const maxRecentCrashes = 20
+const maxTabsLostToCrashes = 256
+
// 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.
@@ -24,9 +27,33 @@ type CrashEvent struct {
URL string `json:"url,omitempty"`
Reason string `json:"reason"`
LastError string `json:"lastError,omitempty"`
+ InstanceID string `json:"instanceId,omitempty"`
Generation uint64 `json:"-"`
}
+// CrashSummary is the crash block of /health and /metrics in both modes.
+type CrashSummary struct {
+ Total uint64 `json:"total"`
+ Recent []CrashEvent `json:"recent"`
+}
+
+// TabNotFoundError names the tab a lookup missed and, when the browser's death
+// is what removed it, the crash that did so.
+type TabNotFoundError struct {
+ TabID string
+ Crash *CrashEvent
+}
+
+func (e *TabNotFoundError) Error() string { return fmt.Sprintf("tab %s not found", e.TabID) }
+
+func tabNotFound(tabID string) error {
+ err := &TabNotFoundError{TabID: tabID}
+ if crash, ok := CrashThatDestroyedTab(tabID); ok {
+ err.Crash = &crash
+ }
+ return err
+}
+
// CrashHandler is called when a crash is detected
type CrashHandler func(event CrashEvent)
@@ -34,6 +61,8 @@ var (
crashMu sync.Mutex
recentCrashEvents []CrashEvent
crashEventsTotal uint64
+ tabsLostToCrashes = map[string]CrashEvent{}
+ tabsLostOrder []string
genMu sync.Mutex
generations = map[context.Context]uint64{}
@@ -112,15 +141,53 @@ func CrashForBrowserContext(ctx context.Context) (CrashEvent, bool) {
}
// CrashSnapshot returns recent crash diagnostics for /health and /metrics.
-func CrashSnapshot() map[string]any {
+func CrashSnapshot() CrashSummary {
crashMu.Lock()
recent := make([]CrashEvent, 0, len(recentCrashEvents))
recent = append(recent, recentCrashEvents...)
crashMu.Unlock()
- return map[string]any{
- "total": atomic.LoadUint64(&crashEventsTotal),
- "recent": recent,
+ return CrashSummary{
+ Total: atomic.LoadUint64(&crashEventsTotal),
+ Recent: recent,
+ }
+}
+
+// recordTabsLostToCrash remembers which tabs a browser death destroyed, so a later
+// lookup of one of them can say the crash removed it rather than blaming the id.
+// This outlives the browser generation on purpose: the tab belonged to the dead
+// browser, so its loss is attributable however many relaunches follow.
+func recordTabsLostToCrash(tabIDs []string, ev CrashEvent) {
+ crashMu.Lock()
+ defer crashMu.Unlock()
+ for _, id := range tabIDs {
+ if _, seen := tabsLostToCrashes[id]; !seen {
+ tabsLostOrder = append(tabsLostOrder, id)
+ }
+ tabsLostToCrashes[id] = ev
+ }
+ for len(tabsLostOrder) > maxTabsLostToCrashes {
+ delete(tabsLostToCrashes, tabsLostOrder[0])
+ tabsLostOrder = tabsLostOrder[1:]
+ }
+}
+
+// CrashThatDestroyedTab reports the browser death that removed tabID, if any.
+func CrashThatDestroyedTab(tabID string) (CrashEvent, bool) {
+ crashMu.Lock()
+ defer crashMu.Unlock()
+ ev, ok := tabsLostToCrashes[tabID]
+ return ev, ok
+}
+
+// recordBrowserDeath records a whole-browser crash together with every tab it
+// held, which is the fact a caller of one of those tabs needs next.
+func (b *Bridge) recordBrowserDeath(reason string) CrashEvent {
+ event := CrashEvent{Time: time.Now(), Reason: reason}
+ recordCrashEventForContext(b.BrowserCtx, event)
+ if b.TabManager != nil {
+ recordTabsLostToCrash(b.trackedTabIDs(), event)
}
+ return event
}
// HasCrashDiagnostics reports whether any crash events have been recorded.
@@ -136,6 +203,8 @@ func ResetCrashMonitoringForTests() {
atomic.StoreUint64(&crashEventsTotal, 0)
crashMu.Lock()
recentCrashEvents = nil
+ tabsLostToCrashes = map[string]CrashEvent{}
+ tabsLostOrder = nil
crashMu.Unlock()
genMu.Lock()
generations = map[context.Context]uint64{}
@@ -214,11 +283,7 @@ func (b *Bridge) MonitorCrashes(handler CrashHandler) {
if err != nil && err != context.Canceled {
reason = err.Error()
}
- event := CrashEvent{
- Time: time.Now(),
- Reason: reason,
- }
- recordCrashEventForContext(b.BrowserCtx, event)
+ event := b.recordBrowserDeath(reason)
slog.Warn("🔥 BROWSER CONTEXT ENDED UNEXPECTEDLY", "error", err)
if handler != nil {
handler(event)
diff --git a/internal/bridge/crash_lost_tabs_test.go b/internal/bridge/crash_lost_tabs_test.go
new file mode 100644
index 00000000..d8be1a28
--- /dev/null
+++ b/internal/bridge/crash_lost_tabs_test.go
@@ -0,0 +1,91 @@
+package bridge
+
+import (
+ "context"
+ "errors"
+ "testing"
+ "time"
+)
+
+func bridgeHoldingTabs(t *testing.T, ids ...string) *Bridge {
+ t.Helper()
+ ResetCrashMonitoringForTests()
+ t.Cleanup(ResetCrashMonitoringForTests)
+ ctx, cancel := context.WithCancel(context.Background())
+ t.Cleanup(cancel)
+ b := newTestBridge()
+ b.BrowserCtx = ctx
+ for _, id := range ids {
+ b.tabs[id] = &TabEntry{CreatedAt: time.Now()}
+ }
+ return b
+}
+
+// After the browser dies the relaunch starts a fresh tab manager, so every tab id
+// the caller holds misses. The miss must say the crash removed the tab, not that
+// the id was wrong, and it must keep saying so after the relaunch (a later
+// generation), because the tab belonged to the browser that died.
+func TestATabLostToABrowserDeathIsReportedAsLostWhateverBrowserAnswers(t *testing.T) {
+ b := bridgeHoldingTabs(t, "tabA", "tabB")
+ event := b.recordBrowserDeath("unexpected context cancellation")
+
+ relaunched := NewTabManager(context.Background(), nil, nil, nil, nil)
+ _, _, err := relaunched.TabContext("tabA")
+ var lost *TabNotFoundError
+ if !errors.As(err, &lost) {
+ t.Fatalf("TabContext = %v, want a TabNotFoundError", err)
+ }
+ if lost.TabID != "tabA" || err.Error() != "tab tabA not found" {
+ t.Errorf("error = %q, want the tab named as not found", err)
+ }
+ if lost.Crash == nil || lost.Crash.Reason != event.Reason {
+ t.Fatalf("crash = %+v, want the browser death %+v", lost.Crash, event)
+ }
+ if got, ok := CrashThatDestroyedTab("tabB"); !ok || got.Reason != event.Reason {
+ t.Errorf("tabB: %+v %v, want the same death", got, ok)
+ }
+}
+
+func TestAnUnknownTabIsNotBlamedOnACrash(t *testing.T) {
+ b := bridgeHoldingTabs(t, "tabA")
+ b.recordBrowserDeath("inspector.targetCrashed")
+
+ _, _, err := NewTabManager(context.Background(), nil, nil, nil, nil).TabContext("never-existed")
+ var lost *TabNotFoundError
+ if !errors.As(err, &lost) {
+ t.Fatalf("TabContext = %v, want a TabNotFoundError", err)
+ }
+ if lost.Crash != nil {
+ t.Errorf("crash = %+v on a tab the browser never held", lost.Crash)
+ }
+}
+
+func TestABrowserDeathCountsInTheCrashSummary(t *testing.T) {
+ b := bridgeHoldingTabs(t, "tabA")
+ b.recordBrowserDeath("unexpected context cancellation")
+ summary := CrashSnapshot()
+ if summary.Total != 1 || len(summary.Recent) != 1 || summary.Recent[0].Reason != "unexpected context cancellation" {
+ t.Errorf("summary = %+v, want the one death", summary)
+ }
+ if _, ok := CrashForBrowserContext(b.BrowserCtx); !ok {
+ t.Errorf("the death is not current for the browser context it happened on")
+ }
+}
+
+func TestTheLostTabRecordIsBounded(t *testing.T) {
+ ids := make([]string, maxTabsLostToCrashes+5)
+ for i := range ids {
+ ids[i] = "tab" + string(rune('A'+i%26)) + string(rune('a'+i/26))
+ }
+ b := bridgeHoldingTabs(t, ids...)
+ b.recordBrowserDeath("x")
+ kept := 0
+ for _, id := range ids {
+ if _, ok := CrashThatDestroyedTab(id); ok {
+ kept++
+ }
+ }
+ if kept != maxTabsLostToCrashes {
+ t.Errorf("kept %d lost tabs, want the bound %d", kept, maxTabsLostToCrashes)
+ }
+}
diff --git a/internal/bridge/tab_lookup.go b/internal/bridge/tab_lookup.go
index a827eca3..1f7b7136 100644
--- a/internal/bridge/tab_lookup.go
+++ b/internal/bridge/tab_lookup.go
@@ -105,7 +105,7 @@ func (tm *TabManager) TabContext(tabID string) (context.Context, string, error)
}
if !ok {
- return nil, "", fmt.Errorf("tab %s not found", tabID)
+ return nil, "", tabNotFound(tabID)
}
if entry.Ctx == nil {
diff --git a/internal/bridge/tab_manager.go b/internal/bridge/tab_manager.go
index 54dd69fd..be314a5f 100644
--- a/internal/bridge/tab_manager.go
+++ b/internal/bridge/tab_manager.go
@@ -129,6 +129,16 @@ func browserExecutorContext(ctx context.Context) (context.Context, error) {
return cdp.WithExecutor(ctx, c.Browser), nil
}
+func (tm *TabManager) trackedTabIDs() []string {
+ tm.mu.RLock()
+ defer tm.mu.RUnlock()
+ ids := make([]string, 0, len(tm.tabs))
+ for id := range tm.tabs {
+ ids = append(ids, id)
+ }
+ return ids
+}
+
func (tm *TabManager) CreateTab(url string) (string, context.Context, context.CancelFunc, error) {
return tm.createTab(url, "")
}
@@ -310,7 +320,7 @@ func (tm *TabManager) CloseTab(tabID string) error {
execCtx, execErr := browserExecutorContext(closeCtx)
if execErr != nil {
if !tracked {
- return fmt.Errorf("tab %s not found", tabID)
+ return tabNotFound(tabID)
}
slog.Debug("close target skipped", "tabId", tabID, "cdpId", cdpTargetID, "err", execErr)
tm.purgeTrackedTabState(tabID, cdpTargetID)
@@ -319,7 +329,7 @@ func (tm *TabManager) CloseTab(tabID string) error {
if err := target.CloseTarget(target.ID(cdpTargetID)).Do(execCtx); err != nil {
if !tracked {
- return fmt.Errorf("tab %s not found", tabID)
+ return tabNotFound(tabID)
}
slog.Debug("close target CDP", "tabId", tabID, "cdpId", cdpTargetID, "err", err)
}
diff --git a/internal/dashboard/config_health.go b/internal/dashboard/config_health.go
index d435fda4..b343bd87 100644
--- a/internal/dashboard/config_health.go
+++ b/internal/dashboard/config_health.go
@@ -6,6 +6,7 @@ import (
"time"
"github.com/pinchtab/pinchtab/internal/authn"
+ "github.com/pinchtab/pinchtab/internal/bridge"
"github.com/pinchtab/pinchtab/internal/cli/report"
"github.com/pinchtab/pinchtab/internal/config"
)
@@ -25,19 +26,24 @@ type healthSecurityInfo struct {
}
type healthEnvelope struct {
- Status string `json:"status"`
- Mode string `json:"mode"`
- Version string `json:"version"`
- Uptime int64 `json:"uptime"`
- AuthRequired bool `json:"authRequired"`
- Profiles int `json:"profiles"`
- QuarantinedProfiles int `json:"quarantinedProfiles"`
- Instances int `json:"instances"`
- DefaultInstance *healthInstanceInfo `json:"defaultInstance,omitempty"`
- Agents int `json:"agents"`
- RestartRequired bool `json:"restartRequired"`
- RestartReasons []string `json:"restartReasons,omitempty"`
- Security *healthSecurityInfo `json:"security,omitempty"`
+ Status string `json:"status"`
+ Mode string `json:"mode"`
+ Version string `json:"version"`
+ Uptime int64 `json:"uptime"`
+ AuthRequired bool `json:"authRequired"`
+ Profiles int `json:"profiles"`
+ QuarantinedProfiles int `json:"quarantinedProfiles"`
+ Instances int `json:"instances"`
+ DefaultInstance *healthInstanceInfo `json:"defaultInstance,omitempty"`
+ Agents int `json:"agents"`
+ RestartRequired bool `json:"restartRequired"`
+ RestartReasons []string `json:"restartReasons,omitempty"`
+ Security *healthSecurityInfo `json:"security,omitempty"`
+ Crashes *bridge.CrashSummary `json:"crashes,omitempty"`
+}
+
+type crashReporter interface {
+ CrashSummary() bridge.CrashSummary
}
func (c *ConfigAPI) healthInfo(includeSecurity bool) (healthEnvelope, error) {
@@ -95,6 +101,11 @@ func (c *ConfigAPI) healthInfo(includeSecurity bool) (healthEnvelope, error) {
security := runtimeSecurityInfo(cfg)
out.Security = &security
}
+ if reporter, ok := c.instances.(crashReporter); ok {
+ if crashes := reporter.CrashSummary(); crashes.Total > 0 {
+ out.Crashes = &crashes
+ }
+ }
return out, nil
}
diff --git a/internal/dashboard/health_crashes_test.go b/internal/dashboard/health_crashes_test.go
new file mode 100644
index 00000000..8e377494
--- /dev/null
+++ b/internal/dashboard/health_crashes_test.go
@@ -0,0 +1,74 @@
+package dashboard
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+type crashedInstances struct {
+ instances []bridge.Instance
+ crashes bridge.CrashSummary
+}
+
+func (s crashedInstances) List() []bridge.Instance { return s.instances }
+func (s crashedInstances) CrashSummary() bridge.CrashSummary { return s.crashes }
+
+type plainInstances struct{ instances []bridge.Instance }
+
+func (s plainInstances) List() []bridge.Instance { return s.instances }
+
+func healthBody(t *testing.T, instances InstanceLister) map[string]any {
+ t.Helper()
+ api := newConfigAPIForTest(config.Load(), instances, nil, nil, nil, "test", time.Now())
+ w := httptest.NewRecorder()
+ api.HandleHealth(w, httptest.NewRequest(http.MethodGet, "/health", nil))
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d: %s", w.Code, w.Body.String())
+ }
+ var body map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ return body
+}
+
+// A crashed-then-relaunched instance is running again, so status stays ok; the
+// crash is history and rides beside it under the same key bridge /health uses.
+func TestServerModeHealthCarriesTheInstancesCrashesBesideAnOkStatus(t *testing.T) {
+ running := []bridge.Instance{{ID: "inst_1", Status: "running"}}
+ body := healthBody(t, crashedInstances{instances: running, crashes: bridge.CrashSummary{
+ Total: 1,
+ Recent: []bridge.CrashEvent{{Time: time.Now(), Reason: "unexpected context cancellation", InstanceID: "inst_1"}},
+ }})
+ if body["status"] != "ok" {
+ t.Errorf("status = %v, want ok: a relaunched instance is serving", body["status"])
+ }
+ crashes, ok := body["crashes"].(map[string]any)
+ if !ok {
+ t.Fatalf("health has no crashes block: %v", body)
+ }
+ if crashes["total"] != float64(1) {
+ t.Errorf("crashes.total = %v, want 1", crashes["total"])
+ }
+ recent, _ := crashes["recent"].([]any)
+ if len(recent) != 1 {
+ t.Fatalf("crashes.recent = %v, want one event", crashes["recent"])
+ }
+ if event, _ := recent[0].(map[string]any); event["instanceId"] != "inst_1" || event["reason"] != "unexpected context cancellation" {
+ t.Errorf("event = %v, want it to name the instance and the reason", event)
+ }
+
+ clean := healthBody(t, crashedInstances{instances: running})
+ if _, present := clean["crashes"]; present {
+ t.Errorf("a never-crashed instance grew a crashes key: %v", clean["crashes"])
+ }
+ if _, present := healthBody(t, plainInstances{instances: running})["crashes"]; present {
+ t.Error("a lister that cannot report crashes produced a crashes key")
+ }
+}
diff --git a/internal/dashboard/monitoring.go b/internal/dashboard/monitoring.go
index 69a80d58..27b5eb80 100644
--- a/internal/dashboard/monitoring.go
+++ b/internal/dashboard/monitoring.go
@@ -78,6 +78,11 @@ func (d *Dashboard) monitoringSnapshot(includeMemory bool) MonitoringSnapshot {
}
if d.monitoring != nil {
+ if refresher, ok := d.monitoring.(interface {
+ RefreshCrashes() map[string]bridge.CrashSummary
+ }); ok {
+ refresher.RefreshCrashes()
+ }
snapshot.Instances = d.monitoring.List()
snapshot.Tabs = d.monitoring.AllTabs()
if includeMemory {
diff --git a/internal/handlers/crash_context_test.go b/internal/handlers/crash_context_test.go
index a72f4694..ade35958 100644
--- a/internal/handlers/crash_context_test.go
+++ b/internal/handlers/crash_context_test.go
@@ -250,3 +250,60 @@ func TestActionExecutionFailureNamesTheBrowserCrash(t *testing.T) {
t.Fatalf("details = %v, want the crash reason", body["details"])
}
}
+
+type lostTabBridge struct {
+ mockBridge
+ err error
+}
+
+func (m *lostTabBridge) TabContext(string) (*bridge.TabHandle, string, error) { return nil, "", m.err }
+
+func consoleLogsResponse(t *testing.T, b bridge.BridgeAPI) *httptest.ResponseRecorder {
+ t.Helper()
+ bridge.ResetCrashMonitoringForTests()
+ t.Cleanup(bridge.ResetCrashMonitoringForTests)
+ h := New(b, &config.RuntimeConfig{ActionTimeout: time.Second}, nil, nil, nil)
+ w := httptest.NewRecorder()
+ h.HandleGetConsoleLogs(w, httptest.NewRequest("GET", "/console?tabId=tab_dead", nil))
+ return w
+}
+
+// The dominant post-crash error: a crash deletes every tab, so what a caller sees
+// next is "tab not found", and that used to read as a bad id with no crash in it.
+func TestATabDestroyedByACrashSaysSoInsteadOfBlamingTheID(t *testing.T) {
+ crash := bridge.CrashEvent{Time: time.Now(), Reason: "unexpected context cancellation"}
+ w := consoleLogsResponse(t, &lostTabBridge{err: &bridge.TabNotFoundError{TabID: "tab_dead", Crash: &crash}})
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("status = %d, want 404: %s", w.Code, w.Body.String())
+ }
+ body := decodeErrorBody(t, w)
+ if body["code"] != "browser_crashed" {
+ t.Errorf("code = %v, want browser_crashed", body["code"])
+ }
+ message, _ := body["error"].(string)
+ if !strings.Contains(message, "tab tab_dead not found") || !strings.Contains(message, "unexpected context cancellation") {
+ t.Errorf("error = %q, want the miss and the crash reason", message)
+ }
+ details, _ := body["details"].(map[string]any)
+ if details["browserCrashed"] != true || details["browserCrashReason"] != "unexpected context cancellation" {
+ t.Errorf("details = %v, want the crash fields", details)
+ }
+ hint, _ := details["hint"].(string)
+ if !strings.Contains(hint, "browser crashed") || !strings.Contains(hint, "open a new tab") {
+ t.Errorf("hint = %q, want it to name the crash and the remedy", hint)
+ }
+}
+
+func TestATabMissWithoutACrashIsTheBareNotFound(t *testing.T) {
+ w := consoleLogsResponse(t, &lostTabBridge{err: &bridge.TabNotFoundError{TabID: "tab_dead"}})
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("status = %d, want 404", w.Code)
+ }
+ body := decodeErrorBody(t, w)
+ if body["code"] != "error" || body["error"] != "tab tab_dead not found" {
+ t.Errorf("body = %v, want the plain not-found", body)
+ }
+ if _, ok := body["details"]; ok {
+ t.Errorf("details appeared without a crash: %v", body)
+ }
+}
diff --git a/internal/handlers/empty_pointer_policy.go b/internal/handlers/empty_pointer_policy.go
index c5cac5ec..1489dc88 100644
--- a/internal/handlers/empty_pointer_policy.go
+++ b/internal/handlers/empty_pointer_policy.go
@@ -5,6 +5,7 @@ import (
"fmt"
"net/http"
+ "github.com/pinchtab/pinchtab/internal/bridge"
"github.com/pinchtab/pinchtab/internal/httpx"
)
@@ -58,5 +59,12 @@ func WriteTabContextError(w http.ResponseWriter, err error, notFoundStatus int)
if notFoundStatus == 0 {
notFoundStatus = http.StatusNotFound
}
+ var lost *bridge.TabNotFoundError
+ if errors.As(err, &lost) && lost.Crash != nil {
+ message, details := crashAnnotation(err.Error(), nil, *lost.Crash,
+ "this tab died with it, along with its logins, form state and refs; open a new tab and navigate again")
+ httpx.ErrorCode(w, notFoundStatus, "browser_crashed", message, false, details)
+ return
+ }
httpx.Error(w, notFoundStatus, err)
}
diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.go
index f64c7fbe..37190ecf 100644
--- a/internal/handlers/handlers.go
+++ b/internal/handlers/handlers.go
@@ -185,15 +185,21 @@ func (h *Handlers) annotateBrowserCrash(message string, details map[string]any)
return message, details
}
+ return crashAnnotation(message, details, crash,
+ "this error is a symptom of the dead browser, not of your selector or timeout; restart it with: pinchtab server restart")
+}
+
+// crashAnnotation is the one shape a crash takes in an error body: the reason in
+// the message, browserCrashed/browserCrashReason as discrete fields, and a hint
+// that says what the caller should do about it.
+func crashAnnotation(message string, details map[string]any, crash bridge.CrashEvent, remedy string) (string, map[string]any) {
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))
+ annotated["hint"] = fmt.Sprintf("the browser crashed (%s at %s) — %s", crash.Reason, crash.Time.Format(time.RFC3339), remedy)
return fmt.Sprintf("%s (browser crashed: %s)", message, crash.Reason), annotated
}
diff --git a/internal/orchestrator/health_transport.go b/internal/orchestrator/health_transport.go
index cd8a7c55..9ab27174 100644
--- a/internal/orchestrator/health_transport.go
+++ b/internal/orchestrator/health_transport.go
@@ -7,6 +7,7 @@ import (
"strings"
"github.com/pinchtab/pinchtab/internal/activity"
+ "github.com/pinchtab/pinchtab/internal/bridge"
"github.com/pinchtab/pinchtab/internal/sanitize"
)
@@ -22,6 +23,10 @@ type remoteMetrics struct {
Memory *memoryMetrics `json:"memory,omitempty"`
}
+type remoteHealth struct {
+ Crashes *bridge.CrashSummary `json:"crashes,omitempty"`
+}
+
type memoryMetrics struct {
MemoryMB float64 `json:"memoryMB"`
Renderers int `json:"renderers"`
@@ -87,6 +92,34 @@ func (o *Orchestrator) fetchMetrics(inst *InstanceInternal) (*memoryMetrics, err
return result.Memory, nil
}
+func (o *Orchestrator) fetchCrashes(inst *InstanceInternal) (*bridge.CrashSummary, error) {
+ target, err := o.instancePathURL(inst, "/health", "")
+ if err != nil {
+ return nil, err
+ }
+ req, err := http.NewRequest(http.MethodGet, target.String(), nil)
+ if err != nil {
+ return nil, err
+ }
+ tagOrchestratorMonitoringRequest(req)
+ o.applyInstanceAuth(req, inst)
+
+ resp, err := o.client.Do(req)
+ if err != nil {
+ return nil, err
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ if resp.StatusCode != http.StatusOK {
+ return nil, nil
+ }
+ var result remoteHealth
+ if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
+ return nil, err
+ }
+ return result.Crashes, nil
+}
+
func tagOrchestratorMonitoringRequest(req *http.Request) {
if req == nil {
return
diff --git a/internal/orchestrator/instance_crashes_test.go b/internal/orchestrator/instance_crashes_test.go
new file mode 100644
index 00000000..3e285462
--- /dev/null
+++ b/internal/orchestrator/instance_crashes_test.go
@@ -0,0 +1,66 @@
+package orchestrator
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+)
+
+func orchestratorOverInstanceHealth(t *testing.T, id, healthBody string) *Orchestrator {
+ t.Helper()
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/health" {
+ http.NotFound(w, r)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(healthBody))
+ }))
+ t.Cleanup(backend.Close)
+ o := NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})
+ o.client = backend.Client()
+ o.mu.Lock()
+ o.instances[id] = &InstanceInternal{
+ Instance: bridge.Instance{ID: id, ProfileName: "p1", Status: "running"},
+ URL: backend.URL,
+ }
+ o.mu.Unlock()
+ return o
+}
+
+// Browser crashes are recorded by the process owning the browser, which in server
+// mode is the instance; the front door has to ask. Its /health then merges every
+// instance's record, naming the instance on each event, and the instance list
+// carries the same block.
+func TestTheFrontDoorLearnsAnInstancesCrashesFromItsHealth(t *testing.T) {
+ const id = "inst_crashed"
+ o := orchestratorOverInstanceHealth(t, id, `{"status":"ok","tabs":0,"crashes":{"total":2,"recent":[
+ {"time":"2026-09-03T08:48:11Z","reason":"unexpected context cancellation"},
+ {"time":"2026-09-03T08:49:47Z","reason":"unexpected context cancellation"}]}}`)
+
+ summary := o.CrashSummary()
+ if summary.Total != 2 || len(summary.Recent) != 2 {
+ t.Fatalf("summary = %+v, want the instance's two crashes", summary)
+ }
+ for _, ev := range summary.Recent {
+ if ev.InstanceID != id {
+ t.Errorf("event %+v does not name its instance", ev)
+ }
+ }
+ instances := o.List()
+ if len(instances) != 1 || instances[0].Crashes == nil || instances[0].Crashes.Total != 2 {
+ t.Errorf("List() = %+v, want the crash block on the instance", instances)
+ }
+}
+
+func TestAnInstanceThatNeverCrashedCarriesNoCrashBlock(t *testing.T) {
+ o := orchestratorOverInstanceHealth(t, "inst_clean", `{"status":"ok","tabs":1}`)
+ if summary := o.CrashSummary(); summary.Total != 0 || len(summary.Recent) != 0 {
+ t.Errorf("summary = %+v, want empty", summary)
+ }
+ if instances := o.List(); instances[0].Crashes != nil {
+ t.Errorf("List() carries a crash block for a clean instance: %+v", instances[0].Crashes)
+ }
+}
diff --git a/internal/orchestrator/instance_query.go b/internal/orchestrator/instance_query.go
index 93be0831..6c89c620 100644
--- a/internal/orchestrator/instance_query.go
+++ b/internal/orchestrator/instance_query.go
@@ -35,11 +35,72 @@ func (o *Orchestrator) List() []bridge.Instance {
for _, inst := range o.instances {
copyInst := inst.Instance
copyInst.Status = effectiveInstanceStatus(copyInst.Status, instanceIsActive(inst))
+ if crashes, ok := o.crashes[inst.ID]; ok && crashes.Total > 0 {
+ summary := crashes
+ copyInst.Crashes = &summary
+ }
result = append(result, copyInst)
}
return result
}
+// RefreshCrashes asks every live instance for its crash record and keeps the
+// answers, so List can carry them and CrashSummary can merge them. Browser
+// crashes are recorded by the process that owns the browser, which in server
+// mode is never this one.
+func (o *Orchestrator) RefreshCrashes() map[string]bridge.CrashSummary {
+ o.mu.RLock()
+ instances := make([]*InstanceInternal, 0, len(o.instances))
+ for _, inst := range o.instances {
+ if inst.Status == "running" && instanceIsActive(inst) {
+ instances = append(instances, inst)
+ }
+ }
+ o.mu.RUnlock()
+
+ fresh := make(map[string]bridge.CrashSummary, len(instances))
+ for _, inst := range instances {
+ crashes, err := o.fetchCrashes(inst)
+ if err != nil || crashes == nil {
+ continue
+ }
+ for i := range crashes.Recent {
+ crashes.Recent[i].InstanceID = inst.ID
+ }
+ fresh[inst.ID] = *crashes
+ }
+
+ o.mu.Lock()
+ if o.crashes == nil {
+ o.crashes = map[string]bridge.CrashSummary{}
+ }
+ for id, crashes := range fresh {
+ o.crashes[id] = crashes
+ }
+ o.mu.Unlock()
+ return fresh
+}
+
+// CrashSummary merges the instances' crash records into the shape bridge /health
+// carries, each event naming its instance.
+func (o *Orchestrator) CrashSummary() bridge.CrashSummary {
+ o.RefreshCrashes()
+ o.mu.RLock()
+ defer o.mu.RUnlock()
+ var merged bridge.CrashSummary
+ for _, crashes := range o.crashes {
+ merged.Total += crashes.Total
+ merged.Recent = append(merged.Recent, crashes.Recent...)
+ }
+ sort.SliceStable(merged.Recent, func(i, j int) bool { return merged.Recent[i].Time.Before(merged.Recent[j].Time) })
+ if len(merged.Recent) > maxMergedCrashEvents {
+ merged.Recent = merged.Recent[len(merged.Recent)-maxMergedCrashEvents:]
+ }
+ return merged
+}
+
+const maxMergedCrashEvents = 20
+
func (o *Orchestrator) Logs(id string) (string, error) {
o.mu.RLock()
defer o.mu.RUnlock()
diff --git a/internal/orchestrator/orchestrator.go b/internal/orchestrator/orchestrator.go
index d68af554..520e9943 100644
--- a/internal/orchestrator/orchestrator.go
+++ b/internal/orchestrator/orchestrator.go
@@ -26,6 +26,7 @@ type EventHandler func(InstanceEvent)
type Orchestrator struct {
instances map[string]*InstanceInternal
+ crashes map[string]bridge.CrashSummary
baseDir string
binary string
profiles *profiles.ProfileManager