Skip to content

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

refactor: improving live data of the dashboard

Luigi Agosti205337a6918f
diff --git a/cmd/pinchtab/cmd_dashboard.go b/cmd/pinchtab/cmd_dashboard.go
index 0cbf8fcf..81dd43c6 100644
--- a/cmd/pinchtab/cmd_dashboard.go
+++ b/cmd/pinchtab/cmd_dashboard.go
@@ -52,6 +52,15 @@ func runDashboard(cfg *config.RuntimeConfig) {
orch.ApplyRuntimeConfig(cfg)
orch.SetProfileManager(profMgr)
dash.SetInstanceLister(orch)
+ dash.SetMonitoringSource(orch)
+ dash.SetServerMetricsProvider(func() dashboard.MonitoringServerMetrics {
+ snapshot := handlers.SnapshotMetrics()
+ return dashboard.MonitoringServerMetrics{
+ GoHeapAllocMB: metricFloat(snapshot["goHeapAllocMB"]),
+ GoNumGoroutine: metricInt(snapshot["goNumGoroutine"]),
+ RateBucketHosts: metricInt(snapshot["rateBucketHosts"]),
+ }
+ })
configAPI := dashboard.NewConfigAPI(cfg, orch, profMgr, orch, version, startedAt)
// Wire up instance events to SSE broadcast
@@ -320,3 +329,35 @@ func registerDefaultProxyRoutes(mux *http.ServeMux, orch *orchestrator.Orchestra
})
}
}
+
+func metricFloat(value any) float64 {
+ switch v := value.(type) {
+ case float64:
+ return v
+ case float32:
+ return float64(v)
+ case int:
+ return float64(v)
+ case int64:
+ return float64(v)
+ case uint64:
+ return float64(v)
+ default:
+ return 0
+ }
+}
+
+func metricInt(value any) int {
+ switch v := value.(type) {
+ case int:
+ return v
+ case int64:
+ return int(v)
+ case float64:
+ return int(v)
+ case uint64:
+ return int(v)
+ default:
+ return 0
+ }
+}
diff --git a/dashboard/src/App.tsx b/dashboard/src/App.tsx
index 97f9fc2b..54b268ef 100644
--- a/dashboard/src/App.tsx
+++ b/dashboard/src/App.tsx
@@ -12,8 +12,16 @@ import { MonitoringPage, ProfilesPage, SettingsPage } from "./pages";
import * as api from "./services/api";
function AppContent() {
- const { setInstances, setProfiles, setAgents, setServerInfo } = useAppStore();
+ const {
+ setInstances,
+ setProfiles,
+ setAgents,
+ setServerInfo,
+ applyMonitoringSnapshot,
+ settings,
+ } = useAppStore();
const location = useLocation();
+ const memoryMetricsEnabled = settings.monitoring?.memoryMetrics ?? false;
useEffect(() => {
document.documentElement.setAttribute("data-site-mode", "agent");
@@ -45,30 +53,34 @@ function AppContent() {
// Subscribe to SSE events
useEffect(() => {
- const unsubscribe = api.subscribeToEvents({
- onInit: (agents) => {
- setAgents(agents);
+ const unsubscribe = api.subscribeToEvents(
+ {
+ onInit: (agents) => {
+ setAgents(agents);
+ },
+ onSystem: (event) => {
+ console.log("System event:", event);
+ },
+ onAgent: (event) => {
+ console.log("Agent event:", event);
+ },
+ onMonitoring: (snapshot) => {
+ applyMonitoringSnapshot(snapshot, memoryMetricsEnabled);
+ },
},
- onSystem: async (event) => {
- console.log("System event:", event);
- if (event.type.startsWith("instance.")) {
- try {
- const instances = await api.fetchInstances();
- setInstances(instances);
- const profiles = await api.fetchProfiles();
- setProfiles(profiles);
- } catch (e) {
- console.error("Failed to refresh after event", e);
- }
- }
+ {
+ includeMemory: memoryMetricsEnabled,
},
- onAgent: (event) => {
- console.log("Agent event:", event);
- },
- });
+ );
return unsubscribe;
- }, [setInstances, setProfiles, setAgents]);
+ }, [
+ applyMonitoringSnapshot,
+ memoryMetricsEnabled,
+ setAgents,
+ setInstances,
+ setProfiles,
+ ]);
return (
<div className="dashboard-shell flex h-screen flex-col bg-bg-app">
diff --git a/dashboard/src/pages/MonitoringPage.tsx b/dashboard/src/pages/MonitoringPage.tsx
index 3143b7a4..bc2694e6 100644
--- a/dashboard/src/pages/MonitoringPage.tsx
+++ b/dashboard/src/pages/MonitoringPage.tsx
@@ -1,155 +1,21 @@
-import { useEffect, useState, useCallback, useRef } from "react";
+import { useEffect, useState } from "react";
import { useAppStore } from "../stores/useAppStore";
import { EmptyState, Button, ErrorBoundary } from "../components/atoms";
import { TabsChart, InstanceListItem, TabItem } from "../components/molecules";
-import type { InstanceTab } from "../generated/types";
import * as api from "../services/api";
-const DEFAULT_POLL_INTERVAL = 30; // seconds
-
export default function MonitoringPage() {
const {
instances,
- setInstances,
- setInstancesLoading,
tabsChartData,
memoryChartData,
serverChartData,
currentTabs,
currentMemory,
- addChartDataPoint,
- addMemoryDataPoint,
- addServerDataPoint,
- setCurrentTabs,
- setCurrentMemory,
settings,
} = useAppStore();
const [selectedId, setSelectedId] = useState<string | null>(null);
- const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
-
- const loadInstances = async () => {
- setInstancesLoading(true);
- try {
- const data = await api.fetchInstances();
- setInstances(data);
- } catch (e) {
- console.error("Failed to load instances", e);
- } finally {
- setInstancesLoading(false);
- }
- };
-
- // Fetch tabs and optionally memory for all running instances
const memoryEnabled = settings.monitoring?.memoryMetrics ?? false;
- const pollInterval =
- (settings.monitoring?.pollInterval || DEFAULT_POLL_INTERVAL) * 1000;
-
- const fetchAllInstanceData = useCallback(async () => {
- // Guard against undefined/null instances
- if (!instances || !Array.isArray(instances)) return;
-
- // Only poll instances that have been running for at least 5 seconds
- // (Chrome needs time to initialize after status becomes "running")
- const now = Date.now();
- const runningInstances = instances.filter((i) => {
- if (i?.status !== "running") return false;
- const startTime = i.startTime ? new Date(i.startTime).getTime() : 0;
- const ageMs = now - startTime;
- return ageMs > 5000; // 5 second grace period
- });
- const timestamp = now;
-
- try {
- // Always fetch server metrics
- const serverMetrics = await api.fetchServerMetrics().catch(() => null);
- if (serverMetrics) {
- addServerDataPoint({
- timestamp,
- goHeapMB: serverMetrics.goHeapAllocMB ?? 0,
- goroutines: serverMetrics.goNumGoroutine ?? 0,
- rateBucketHosts: serverMetrics.rateBucketHosts ?? 0,
- });
- }
-
- // Skip instance data if no stable running instances
- // (this prevents calling /instances/tabs which proxies to ALL instances,
- // including fresh ones that might not be ready yet)
- if (runningInstances.length === 0) {
- // Clear stale data when no stable instances
- setCurrentTabs({});
- setCurrentMemory({});
- return;
- }
-
- // Fetch tabs and instance metrics
- const [allTabs, allMetrics] = await Promise.all([
- api.fetchAllTabs().catch(() => []),
- memoryEnabled ? api.fetchAllMetrics().catch(() => []) : [],
- ]);
-
- const tabsArray = Array.isArray(allTabs) ? allTabs : [];
- const metricsArray = Array.isArray(allMetrics) ? allMetrics : [];
-
- const tabDataPoint: Record<string, number> = { timestamp };
- const memDataPoint: Record<string, number> = { timestamp };
- const tabsByInstance: Record<string, InstanceTab[]> = {};
- const memoryByInstance: Record<string, number> = {};
-
- // Group tabs by instance
- for (const inst of runningInstances) {
- const instTabs = tabsArray.filter((t) => t.instanceId === inst.id);
- tabDataPoint[inst.id] = instTabs.length;
- tabsByInstance[inst.id] = instTabs;
-
- // Find memory for this instance (if enabled)
- if (memoryEnabled) {
- const instMem = metricsArray.find((m) => m.instanceId === inst.id);
- if (instMem) {
- memDataPoint[inst.id] = instMem.jsHeapUsedMB;
- memoryByInstance[inst.id] = instMem.jsHeapUsedMB;
- }
- }
- }
-
- addChartDataPoint(
- tabDataPoint as Parameters<typeof addChartDataPoint>[0],
- );
- if (memoryEnabled) {
- addMemoryDataPoint(
- memDataPoint as Parameters<typeof addMemoryDataPoint>[0],
- );
- }
- setCurrentTabs(tabsByInstance);
- setCurrentMemory(memoryByInstance);
- } catch (e) {
- console.error("Failed to fetch instance data:", e);
- }
- }, [
- instances,
- memoryEnabled,
- addChartDataPoint,
- addMemoryDataPoint,
- addServerDataPoint,
- setCurrentTabs,
- setCurrentMemory,
- ]);
-
- // Load once on mount if empty — intentionally omitting deps to avoid refetch loops
- useEffect(() => {
- if (instances.length === 0) {
- loadInstances();
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
-
- // Poll tabs
- useEffect(() => {
- fetchAllInstanceData();
- pollRef.current = setInterval(fetchAllInstanceData, pollInterval);
- return () => {
- if (pollRef.current) clearInterval(pollRef.current);
- };
- }, [fetchAllInstanceData, pollInterval]);
// Auto-select first running instance
useEffect(() => {
diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.ts
index fc3f67b3..fe752508 100644
--- a/dashboard/src/services/api.ts
+++ b/dashboard/src/services/api.ts
@@ -12,10 +12,13 @@ import type {
BackendConfig,
BackendConfigState,
DashboardServerInfo,
+ MonitoringServerMetrics,
+ MonitoringSnapshot,
} from "../types";
import {
normalizeBackendConfigState,
normalizeDashboardServerInfo,
+ normalizeMonitoringSnapshot,
} from "../types";
const BASE = ""; // Uses proxy in dev
@@ -106,14 +109,8 @@ export async function fetchAllMetrics(): Promise<InstanceMetrics[]> {
return request<InstanceMetrics[]>("/instances/metrics");
}
-export interface ServerMetrics {
- goHeapAllocMB: number;
- goNumGoroutine: number;
- rateBucketHosts: number;
-}
-
-export async function fetchServerMetrics(): Promise<ServerMetrics> {
- const res = await request<{ metrics: ServerMetrics }>("/metrics");
+export async function fetchServerMetrics(): Promise<MonitoringServerMetrics> {
+ const res = await request<{ metrics: MonitoringServerMetrics }>("/metrics");
return res.metrics;
}
@@ -159,10 +156,15 @@ export type EventHandler = {
onSystem?: (event: SystemEvent) => void;
onAgent?: (event: AgentEvent) => void;
onInit?: (agents: Agent[]) => void;
+ onMonitoring?: (snapshot: MonitoringSnapshot) => void;
};
-export function subscribeToEvents(handlers: EventHandler): () => void {
- const es = new EventSource("/api/events");
+export function subscribeToEvents(
+ handlers: EventHandler,
+ options?: { includeMemory?: boolean },
+): () => void {
+ const url = options?.includeMemory ? "/api/events?memory=1" : "/api/events";
+ const es = new EventSource(url);
es.addEventListener("init", (e) => {
try {
@@ -191,6 +193,17 @@ export function subscribeToEvents(handlers: EventHandler): () => void {
}
});
+ es.addEventListener("monitoring", (e) => {
+ try {
+ const snapshot = normalizeMonitoringSnapshot(
+ JSON.parse(e.data) as Partial<MonitoringSnapshot>,
+ );
+ handlers.onMonitoring?.(snapshot);
+ } catch {
+ // ignore
+ }
+ });
+
// Suppress connection errors (expected on page reload/navigation)
es.onerror = () => {
// SSE will auto-reconnect; silence console noise
diff --git a/dashboard/src/stores/useAppStore.ts b/dashboard/src/stores/useAppStore.ts
index b3908d17..027d1fe5 100644
--- a/dashboard/src/stores/useAppStore.ts
+++ b/dashboard/src/stores/useAppStore.ts
@@ -7,7 +7,7 @@ import type {
ActivityEvent,
Settings,
} from "../generated/types";
-import type { DashboardServerInfo } from "../types";
+import type { DashboardServerInfo, MonitoringSnapshot } from "../types";
export interface TabDataPoint {
timestamp: number;
@@ -50,6 +50,10 @@ interface AppState {
addServerDataPoint: (point: ServerDataPoint) => void;
setCurrentTabs: (tabs: Record<string, InstanceTab[]>) => void;
setCurrentMemory: (memory: Record<string, number>) => void;
+ applyMonitoringSnapshot: (
+ snapshot: MonitoringSnapshot,
+ includeMemory: boolean,
+ ) => void;
// Agents
agents: Agent[];
@@ -135,6 +139,57 @@ export const useAppStore = create<AppState>((set) => ({
})),
setCurrentTabs: (currentTabs) => set({ currentTabs }),
setCurrentMemory: (currentMemory) => set({ currentMemory }),
+ applyMonitoringSnapshot: (snapshot, includeMemory) =>
+ set((state) => {
+ const runningInstances = snapshot.instances.filter(
+ (instance) => instance?.status === "running",
+ );
+ const tabDataPoint: TabDataPoint = { timestamp: snapshot.timestamp };
+ const memDataPoint: MemoryDataPoint = { timestamp: snapshot.timestamp };
+ const currentTabs: Record<string, InstanceTab[]> = {};
+ const currentMemory: Record<string, number> = {};
+
+ for (const instance of runningInstances) {
+ const instanceTabs = snapshot.tabs.filter(
+ (tab) => tab.instanceId === instance.id,
+ );
+ tabDataPoint[instance.id] = instanceTabs.length;
+ currentTabs[instance.id] = instanceTabs;
+
+ if (includeMemory) {
+ const metrics = snapshot.metrics.find(
+ (entry) => entry.instanceId === instance.id,
+ );
+ if (metrics) {
+ memDataPoint[instance.id] = metrics.jsHeapUsedMB;
+ currentMemory[instance.id] = metrics.jsHeapUsedMB;
+ }
+ }
+ }
+
+ return {
+ instances: snapshot.instances,
+ currentTabs,
+ currentMemory,
+ tabsChartData:
+ runningInstances.length > 0
+ ? [...state.tabsChartData.slice(-59), tabDataPoint]
+ : state.tabsChartData,
+ memoryChartData:
+ includeMemory && runningInstances.length > 0
+ ? [...state.memoryChartData.slice(-59), memDataPoint]
+ : state.memoryChartData,
+ serverChartData: [
+ ...state.serverChartData.slice(-59),
+ {
+ timestamp: snapshot.timestamp,
+ goHeapMB: snapshot.serverMetrics.goHeapAllocMB,
+ goroutines: snapshot.serverMetrics.goNumGoroutine,
+ rateBucketHosts: snapshot.serverMetrics.rateBucketHosts,
+ },
+ ],
+ };
+ }),
// Agents
agents: [],
diff --git a/dashboard/src/types/index.ts b/dashboard/src/types/index.ts
index 08183991..6b85bd4e 100644
--- a/dashboard/src/types/index.ts
+++ b/dashboard/src/types/index.ts
@@ -4,6 +4,8 @@ import type {
BrowserSettings,
CreateProfileRequest,
Instance,
+ InstanceMetrics,
+ InstanceTab,
LaunchInstanceRequest,
Profile,
ScreencastSettings,
@@ -13,6 +15,8 @@ import type {
export type {
Profile,
Instance,
+ InstanceTab,
+ InstanceMetrics,
Agent,
ActivityEvent,
Settings,
@@ -34,6 +38,20 @@ export interface DashboardServerInfo {
restartReasons?: string[];
}
+export interface MonitoringServerMetrics {
+ goHeapAllocMB: number;
+ goNumGoroutine: number;
+ rateBucketHosts: number;
+}
+
+export interface MonitoringSnapshot {
+ timestamp: number;
+ instances: Instance[];
+ tabs: InstanceTab[];
+ metrics: InstanceMetrics[];
+ serverMetrics: MonitoringServerMetrics;
+}
+
export interface BackendServerConfig {
port: string;
bind: string;
@@ -238,6 +256,22 @@ export function normalizeDashboardServerInfo(
};
}
+export function normalizeMonitoringSnapshot(
+ input: Partial<MonitoringSnapshot>,
+): MonitoringSnapshot {
+ return {
+ timestamp: input.timestamp ?? Date.now(),
+ instances: input.instances ?? [],
+ tabs: input.tabs ?? [],
+ metrics: input.metrics ?? [],
+ serverMetrics: {
+ goHeapAllocMB: input.serverMetrics?.goHeapAllocMB ?? 0,
+ goNumGoroutine: input.serverMetrics?.goNumGoroutine ?? 0,
+ rateBucketHosts: input.serverMetrics?.rateBucketHosts ?? 0,
+ },
+ };
+}
+
export type {
Settings as LocalDashboardSettings,
ScreencastSettings as LocalScreencastSettings,
diff --git a/internal/dashboard/dashboard.go b/internal/dashboard/dashboard.go
index 6c8a1f80..7fdc7bac 100644
--- a/internal/dashboard/dashboard.go
+++ b/internal/dashboard/dashboard.go
@@ -61,6 +61,8 @@ type Dashboard struct {
sysConns map[chan SystemEvent]struct{}
cancel context.CancelFunc
instances InstanceLister
+ monitoring MonitoringSource
+ serverMetrics ServerMetricsProvider
childAuthToken string
mu sync.RWMutex
}
@@ -174,13 +176,23 @@ func (d *Dashboard) handleSSE(w http.ResponseWriter, r *http.Request) {
d.mu.Unlock()
}()
+ includeMemory := r.URL.Query().Get("memory") == "1"
+
// Send initial empty agent list
data, _ := json.Marshal([]interface{}{})
_, _ = fmt.Fprintf(w, "event: init\ndata: %s\n\n", data)
flusher.Flush()
+ if d.monitoring != nil || d.instances != nil {
+ data, _ = json.Marshal(d.monitoringSnapshot(includeMemory))
+ _, _ = fmt.Fprintf(w, "event: monitoring\ndata: %s\n\n", data)
+ flusher.Flush()
+ }
+
keepalive := time.NewTicker(30 * time.Second)
+ monitoring := time.NewTicker(5 * time.Second)
defer keepalive.Stop()
+ defer monitoring.Stop()
for {
select {
@@ -192,6 +204,17 @@ func (d *Dashboard) handleSSE(w http.ResponseWriter, r *http.Request) {
data, _ := json.Marshal(evt)
_, _ = fmt.Fprintf(w, "event: system\ndata: %s\n\n", data)
flusher.Flush()
+ if d.monitoring != nil || d.instances != nil {
+ data, _ = json.Marshal(d.monitoringSnapshot(includeMemory))
+ _, _ = fmt.Fprintf(w, "event: monitoring\ndata: %s\n\n", data)
+ flusher.Flush()
+ }
+ case <-monitoring.C:
+ if d.monitoring != nil || d.instances != nil {
+ data, _ = json.Marshal(d.monitoringSnapshot(includeMemory))
+ _, _ = fmt.Fprintf(w, "event: monitoring\ndata: %s\n\n", data)
+ flusher.Flush()
+ }
case <-keepalive.C:
_, _ = fmt.Fprintf(w, ": keepalive\n\n")
flusher.Flush()
diff --git a/internal/dashboard/monitoring.go b/internal/dashboard/monitoring.go
new file mode 100644
index 00000000..9290b75e
--- /dev/null
+++ b/internal/dashboard/monitoring.go
@@ -0,0 +1,66 @@
+package dashboard
+
+import (
+ "time"
+
+ apiTypes "github.com/pinchtab/pinchtab/internal/api/types"
+ "github.com/pinchtab/pinchtab/internal/bridge"
+)
+
+type MonitoringSource interface {
+ List() []bridge.Instance
+ AllTabs() []bridge.InstanceTab
+ AllMetrics() []apiTypes.InstanceMetrics
+}
+
+type MonitoringServerMetrics struct {
+ GoHeapAllocMB float64 `json:"goHeapAllocMB"`
+ GoNumGoroutine int `json:"goNumGoroutine"`
+ RateBucketHosts int `json:"rateBucketHosts"`
+}
+
+type MonitoringSnapshot struct {
+ Timestamp int64 `json:"timestamp"`
+ Instances []bridge.Instance `json:"instances"`
+ Tabs []bridge.InstanceTab `json:"tabs"`
+ Metrics []apiTypes.InstanceMetrics `json:"metrics"`
+ ServerMetrics MonitoringServerMetrics `json:"serverMetrics"`
+}
+
+type ServerMetricsProvider func() MonitoringServerMetrics
+
+func (d *Dashboard) SetMonitoringSource(src MonitoringSource) {
+ d.monitoring = src
+ if src != nil {
+ d.instances = src
+ }
+}
+
+func (d *Dashboard) SetServerMetricsProvider(provider ServerMetricsProvider) {
+ d.serverMetrics = provider
+}
+
+func (d *Dashboard) monitoringSnapshot(includeMemory bool) MonitoringSnapshot {
+ snapshot := MonitoringSnapshot{
+ Timestamp: time.Now().UnixMilli(),
+ Instances: []bridge.Instance{},
+ Tabs: []bridge.InstanceTab{},
+ Metrics: []apiTypes.InstanceMetrics{},
+ }
+
+ if d.monitoring != nil {
+ snapshot.Instances = d.monitoring.List()
+ snapshot.Tabs = d.monitoring.AllTabs()
+ if includeMemory {
+ snapshot.Metrics = d.monitoring.AllMetrics()
+ }
+ } else if d.instances != nil {
+ snapshot.Instances = d.instances.List()
+ }
+
+ if d.serverMetrics != nil {
+ snapshot.ServerMetrics = d.serverMetrics()
+ }
+
+ return snapshot
+}
diff --git a/internal/web/web.go b/internal/web/web.go
index 5cdf54d8..bddfee19 100644
--- a/internal/web/web.go
+++ b/internal/web/web.go
@@ -47,6 +47,10 @@ type StatusWriter struct {
Code int
}
+func (w *StatusWriter) Unwrap() http.ResponseWriter {
+ return w.ResponseWriter
+}
+
func (w *StatusWriter) WriteHeader(code int) {
w.Code = code
w.ResponseWriter.WriteHeader(code)