Skip to content

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

refactor: rework dashboard monitoring layout and fix port configuration

Luigi Agosti671a11ef2b84
diff --git a/cmd/pinchtab/cmd_cli_runtime.go b/cmd/pinchtab/cmd_cli_runtime.go
index acf9b2af..c05889bd 100644
--- a/cmd/pinchtab/cmd_cli_runtime.go
+++ b/cmd/pinchtab/cmd_cli_runtime.go
@@ -48,12 +48,10 @@ func resolveCLIBase(cfg *config.RuntimeConfig) string {
if envURL := os.Getenv("PINCHTAB_SERVER"); envURL != "" {
return strings.TrimRight(envURL, "/")
}
- // Default to first instance port from config, falling back to 9868.
- port := cfg.InstancePortStart
- if port == 0 {
- port = 9868
- }
- return fmt.Sprintf("http://127.0.0.1:%d", port)
+ // Default to the main server port so requests go through the
+ // orchestrator. This ensures activity is recorded in the shared
+ // store and visible in the dashboard.
+ return fmt.Sprintf("http://127.0.0.1:%s", cfg.Port)
}
func resolveCLIToken(cfg *config.RuntimeConfig) string {
@@ -71,17 +69,11 @@ func resolveCLIAgentID() string {
if trimmed := strings.TrimSpace(cliAgentID); trimmed != "" {
return trimmed
}
- if trimmed := strings.TrimSpace(os.Getenv("PINCHTAB_AGENT_ID")); trimmed != "" {
- return trimmed
- }
- return "cli"
+ return strings.TrimSpace(os.Getenv("PINCHTAB_AGENT_ID"))
}
func normalizeCLIAgentID(raw string) string {
- if trimmed := strings.TrimSpace(raw); trimmed != "" {
- return trimmed
- }
- return "cli"
+ return strings.TrimSpace(raw)
}
type agentHeaderTransport struct {
@@ -97,7 +89,10 @@ func (t agentHeaderTransport) RoundTrip(req *http.Request) (*http.Response, erro
cloned := req.Clone(req.Context())
cloned.Header = req.Header.Clone()
- cloned.Header.Set(activity.HeaderAgentID, normalizeCLIAgentID(t.agentID))
+ cloned.Header.Set(activity.HeaderPTSource, "client")
+ if id := normalizeCLIAgentID(t.agentID); id != "" {
+ cloned.Header.Set(activity.HeaderAgentID, id)
+ }
return base.RoundTrip(cloned)
}
diff --git a/cmd/pinchtab/cmd_cli_runtime_test.go b/cmd/pinchtab/cmd_cli_runtime_test.go
index 609b950f..f6a0221c 100644
--- a/cmd/pinchtab/cmd_cli_runtime_test.go
+++ b/cmd/pinchtab/cmd_cli_runtime_test.go
@@ -37,8 +37,8 @@ func TestResolveCLIBase(t *testing.T) {
expected: "http://env:5678",
},
{
- name: "default fallback uses 127.0.0.1 and instancePortStart",
- expected: "http://127.0.0.1:9868",
+ name: "default fallback uses 127.0.0.1 and server port",
+ expected: "http://127.0.0.1:9867",
},
}
@@ -55,7 +55,7 @@ func TestResolveCLIBase(t *testing.T) {
t.Setenv("PINCHTAB_SERVER", "")
}
- cfg := &config.RuntimeConfig{}
+ cfg := &config.RuntimeConfig{Port: "9867"}
actual := resolveCLIBase(cfg)
if actual != tt.expected {
@@ -100,14 +100,14 @@ func TestResolveCLIAgentID(t *testing.T) {
expected: "agent-env",
},
{
- name: "blank values fall back to cli",
+ name: "blank values fall back to empty (anonymous)",
flagValue: " ",
envValue: " ",
- expected: "cli",
+ expected: "",
},
{
- name: "default fallback is cli",
- expected: "cli",
+ name: "default fallback is empty (anonymous)",
+ expected: "",
},
}
diff --git a/cmd/pinchtab/cmd_config.go b/cmd/pinchtab/cmd_config.go
index 1482695d..81f9f509 100644
--- a/cmd/pinchtab/cmd_config.go
+++ b/cmd/pinchtab/cmd_config.go
@@ -102,9 +102,6 @@ func handleConfigOverview(cfg *config.RuntimeConfig) {
}
dashPort := cfg.Port
- if dashPort == "" {
- dashPort = "9870"
- }
dashboardURL := fmt.Sprintf("http://localhost:%s", dashPort)
running := server.CheckPinchTabRunning(dashPort, cfg.Token)
@@ -131,9 +128,6 @@ func handleConfigOverview(cfg *config.RuntimeConfig) {
cfg = nextCfg
dashPort = cfg.Port
- if dashPort == "" {
- dashPort = "9870"
- }
dashboardURL = fmt.Sprintf("http://localhost:%s", dashPort)
running = server.CheckPinchTabRunning(dashPort, cfg.Token)
fmt.Println()
diff --git a/cmd/pinchtab/cmd_dashboard.go b/cmd/pinchtab/cmd_dashboard.go
index fffbfc97..72594f93 100644
--- a/cmd/pinchtab/cmd_dashboard.go
+++ b/cmd/pinchtab/cmd_dashboard.go
@@ -74,10 +74,7 @@ func runDashboardCommand(cfgPort, cfgBind, cfgToken string, noOpen bool, portOve
}
func resolvePort(cfgPort, override string) (string, error) {
- port := "9870"
- if cfgPort != "" {
- port = cfgPort
- }
+ port := cfgPort
if override != "" {
port = override
}
diff --git a/cmd/pinchtab/cmd_dashboard_test.go b/cmd/pinchtab/cmd_dashboard_test.go
index 50596de9..53c23f04 100644
--- a/cmd/pinchtab/cmd_dashboard_test.go
+++ b/cmd/pinchtab/cmd_dashboard_test.go
@@ -10,7 +10,7 @@ func TestResolvePort(t *testing.T) {
want string
wantErr bool
}{
- {"default when empty", "", "", "9870", false},
+ {"rejects empty", "", "", "", true},
{"uses config port", "8080", "", "8080", false},
{"override wins", "8080", "7777", "7777", false},
{"override wins over empty config", "", "7777", "7777", false},
diff --git a/cmd/pinchtab/root.go b/cmd/pinchtab/root.go
index 61342609..427d31e3 100644
--- a/cmd/pinchtab/root.go
+++ b/cmd/pinchtab/root.go
@@ -86,9 +86,6 @@ func maybeRunWizard() {
func menuListenStatus(cfg *config.RuntimeConfig) string {
dashPort := cfg.Port
- if dashPort == "" {
- dashPort = "9870"
- }
if server.CheckPinchTabRunning(dashPort, cfg.Token) {
return "running"
}
@@ -112,7 +109,7 @@ func init() {
rootCmd.SetVersionTemplate("pinchtab {{.Version}}\n")
// Global flags
- rootCmd.PersistentFlags().StringVar(&serverURL, "server", "", "PinchTab server URL (default: http://127.0.0.1:<instancePortStart>)")
+ rootCmd.PersistentFlags().StringVar(&serverURL, "server", "", "PinchTab server URL (default: http://127.0.0.1:<server.port>)")
rootCmd.PersistentFlags().StringVar(&cliAgentID, "agent-id", "", "Agent identifier recorded in activity logs")
// Grouping commands
diff --git a/dashboard/src/activities/ActivityExplorer.tsx b/dashboard/src/activities/ActivityExplorer.tsx
index 2b39d6fe..e8b90d18 100644
--- a/dashboard/src/activities/ActivityExplorer.tsx
+++ b/dashboard/src/activities/ActivityExplorer.tsx
@@ -149,8 +149,10 @@ export default function ActivityExplorer({
const summary = useMemo(
() =>
- `${count} events • ${stats.agents} agents • ${stats.tabs} tabs • ${stats.instances} instances`,
- [count, stats.agents, stats.instances, stats.tabs],
+ embedded
+ ? `${count} events • ${stats.agents} agents`
+ : `${count} events • ${stats.agents} agents • ${stats.tabs} tabs • ${stats.instances} instances`,
+ [count, stats.agents, stats.instances, stats.tabs, embedded],
);
const updateFilter = (key: keyof ActivityFilters, value: string) => {
@@ -229,6 +231,7 @@ export default function ActivityExplorer({
loading={loading}
error={error}
summary={summary}
+ embedded={embedded}
onFilterChange={updateFilter}
/>
</div>
diff --git a/dashboard/src/activities/ActivityTimeline.tsx b/dashboard/src/activities/ActivityTimeline.tsx
index 59be7b26..88f4ba7a 100644
--- a/dashboard/src/activities/ActivityTimeline.tsx
+++ b/dashboard/src/activities/ActivityTimeline.tsx
@@ -11,6 +11,7 @@ interface Props {
loading: boolean;
error: string;
summary: string;
+ embedded?: boolean;
onFilterChange: (key: keyof ActivityFilters, value: string) => void;
}
@@ -40,21 +41,32 @@ export default function ActivityTimeline({
loading,
error,
summary,
+ embedded = false,
onFilterChange,
}: Props) {
+ const filteredEvents = embedded
+ ? events.filter(
+ (e) => !e.source || !["dashboard", "server"].includes(e.source),
+ )
+ : events;
+
return (
- <section className="dashboard-panel flex min-h-0 flex-1 flex-col overflow-hidden">
- <div className="flex items-center justify-between border-b border-border-subtle px-4 py-3">
- <div>
- <div className="dashboard-section-label mb-1">Timeline</div>
- <h2 className="text-sm font-semibold text-text-secondary">
- Recent events
- </h2>
- </div>
- <div className="dashboard-mono text-[0.72rem] text-text-muted">
- {summary}
+ <section
+ className={`flex min-h-0 flex-1 flex-col overflow-hidden ${embedded ? "" : "dashboard-panel"}`}
+ >
+ {!embedded && (
+ <div className="flex items-center justify-between border-b border-border-subtle px-4 py-3">
+ <div>
+ <div className="dashboard-section-label mb-1">Timeline</div>
+ <h2 className="text-sm font-semibold text-text-secondary">
+ Recent events
+ </h2>
+ </div>
+ <div className="dashboard-mono text-[0.72rem] text-text-muted">
+ {summary}
+ </div>
</div>
- </div>
+ )}
{error && (
<div className="border-b border-destructive/30 bg-destructive/10 px-4 py-2 text-xs text-destructive">
@@ -63,7 +75,7 @@ export default function ActivityTimeline({
)}
<div className="min-h-0 flex-1 overflow-auto">
- {!loading && events.length === 0 ? (
+ {!loading && filteredEvents.length === 0 ? (
<EmptyState
icon="📜"
title="No matching activity"
@@ -71,7 +83,7 @@ export default function ActivityTimeline({
/>
) : (
<div className="divide-y divide-border-subtle/70">
- {events.map((event, index) => (
+ {filteredEvents.map((event, index) => (
<div
key={`${event.requestId || event.timestamp}-${index}`}
className="px-4 py-2 transition-colors hover:bg-white/2"
diff --git a/dashboard/src/activities/AgentActivityWorkspace.tsx b/dashboard/src/activities/AgentActivityWorkspace.tsx
index 11b26b37..aa5855e7 100644
--- a/dashboard/src/activities/AgentActivityWorkspace.tsx
+++ b/dashboard/src/activities/AgentActivityWorkspace.tsx
@@ -488,9 +488,6 @@ export default function AgentActivityWorkspace({
if (requireAgentIdentity && !(agent.id || "").trim()) {
return false;
}
- if (requireAgentIdentity && agent.id === "anonymous") {
- return false;
- }
return true;
})
.sort(
diff --git a/dashboard/src/components/molecules/InstanceStats.tsx b/dashboard/src/components/molecules/InstanceStats.tsx
new file mode 100644
index 00000000..bc6258d2
--- /dev/null
+++ b/dashboard/src/components/molecules/InstanceStats.tsx
@@ -0,0 +1,127 @@
+import type { Instance, InstanceMetrics, InstanceTab } from "../../generated/types";
+
+interface Props {
+ instance?: Instance | null;
+ metrics?: InstanceMetrics | null;
+ tabs: InstanceTab[];
+}
+
+function StatItem({
+ label,
+ value,
+ sub,
+}: {
+ label: string;
+ value: string;
+ sub?: string;
+}) {
+ return (
+ <div className="flex flex-col gap-0.5">
+ <span className="text-[10px] font-medium uppercase tracking-wider text-text-muted">
+ {label}
+ </span>
+ <span className="text-sm font-semibold text-text-primary">{value}</span>
+ {sub && <span className="text-[10px] text-text-muted">{sub}</span>}
+ </div>
+ );
+}
+
+function StatGroup({
+ title,
+ children,
+}: {
+ title: string;
+ children: React.ReactNode;
+}) {
+ return (
+ <div className="flex flex-col gap-3">
+ <span className="text-[10px] font-semibold uppercase tracking-[0.1em] text-text-muted/70">
+ {title}
+ </span>
+ <div className="flex gap-6">{children}</div>
+ </div>
+ );
+}
+
+function fmt(n: number, decimals = 0): string {
+ if (!Number.isFinite(n)) return "0";
+ return new Intl.NumberFormat("en-US", {
+ maximumFractionDigits: decimals,
+ }).format(n);
+}
+
+function formatUptime(startTime: string): string {
+ const ms = Date.now() - new Date(startTime).getTime();
+ if (ms < 0) return "just now";
+ const secs = Math.floor(ms / 1000);
+ if (secs < 60) return `${secs}s`;
+ const mins = Math.floor(secs / 60);
+ if (mins < 60) return `${mins}m`;
+ const hrs = Math.floor(mins / 60);
+ const remainMins = mins % 60;
+ if (hrs < 24) return `${hrs}h ${remainMins}m`;
+ const days = Math.floor(hrs / 24);
+ return `${days}d ${hrs % 24}h`;
+}
+
+function countUniqueDomains(tabs: InstanceTab[]): number {
+ const domains = new Set<string>();
+ for (const tab of tabs) {
+ try {
+ domains.add(new URL(tab.url).hostname);
+ } catch {
+ // skip invalid URLs
+ }
+ }
+ return domains.size;
+}
+
+export default function InstanceStats({ instance, metrics, tabs }: Props) {
+ const heapPct =
+ metrics && metrics.jsHeapTotalMB > 0
+ ? (metrics.jsHeapUsedMB / metrics.jsHeapTotalMB) * 100
+ : null;
+
+ const uniqueDomains = countUniqueDomains(tabs);
+
+ return (
+ <div className="grid grid-cols-2 gap-y-4 border-t border-border-subtle px-4 py-4">
+ <StatGroup title="Instance">
+ {instance && (
+ <>
+ <StatItem label="Status" value={instance.status} />
+ <StatItem label="Uptime" value={formatUptime(instance.startTime)} />
+ <StatItem label="Port" value={instance.port} />
+ </>
+ )}
+ </StatGroup>
+
+ <StatGroup title="Browsing">
+ <StatItem label="Tabs" value={fmt(tabs.length)} />
+ <StatItem label="Domains" value={fmt(uniqueDomains)} />
+ {metrics && (
+ <>
+ <StatItem label="Documents" value={fmt(metrics.documents)} />
+ <StatItem label="Frames" value={fmt(metrics.frames)} />
+ </>
+ )}
+ </StatGroup>
+
+ {metrics && (
+ <StatGroup title="Resources">
+ <StatItem
+ label="Heap"
+ value={`${fmt(metrics.jsHeapUsedMB, 1)} MB`}
+ sub={
+ heapPct !== null
+ ? `${fmt(heapPct, 0)}% of ${fmt(metrics.jsHeapTotalMB, 1)} MB`
+ : undefined
+ }
+ />
+ <StatItem label="DOM Nodes" value={fmt(metrics.nodes)} />
+ <StatItem label="Listeners" value={fmt(metrics.listeners)} />
+ </StatGroup>
+ )}
+ </div>
+ );
+}
diff --git a/dashboard/src/components/molecules/NavBar.tsx b/dashboard/src/components/molecules/NavBar.tsx
index c745a235..ec36e995 100644
--- a/dashboard/src/components/molecules/NavBar.tsx
+++ b/dashboard/src/components/molecules/NavBar.tsx
@@ -3,6 +3,7 @@ import { NavLink, useLocation, useNavigate } from "react-router-dom";
import * as api from "../../services/api";
import { dispatchAuthRequired } from "../../services/auth";
import { useAppStore } from "../../stores/useAppStore";
+import ServerStatusBadge from "./ServerStatusBadge";
import "./NavBar.css";
interface Tab {
@@ -24,13 +25,24 @@ interface NavBarProps {
}
export default function NavBar({ onRefresh, showLogout = false }: NavBarProps) {
- const { serverInfo } = useAppStore();
+ const {
+ serverInfo,
+ instances,
+ currentTabs,
+ monitoringSidebarCollapsed,
+ setMonitoringSidebarCollapsed,
+ selectedMonitoringInstanceId,
+ } = useAppStore();
const [refreshing, setRefreshing] = useState(false);
const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
const tabsRef = useRef<HTMLElement>(null);
const location = useLocation();
const navigate = useNavigate();
+ const isMonitoringPage = location.pathname.startsWith("/dashboard/monitoring");
+ const selectedInstance =
+ instances.find((i) => i.id === selectedMonitoringInstanceId) ?? null;
+
// Close mobile menu on route change
useEffect(() => {
setMobileMenuOpen(false);
@@ -73,7 +85,7 @@ export default function NavBar({ onRefresh, showLogout = false }: NavBarProps) {
return (
<header className="sticky top-0 z-50 border-b border-border-subtle bg-bg-app/95 backdrop-blur">
- <div className="flex h-[60px] items-center gap-0 px-4 sm:px-5">
+ <div className="flex h-15 items-center gap-0 px-4 sm:px-5">
<span className="min-w-32 text-sm font-semibold tracking-[0.2em] text-text-primary uppercase">
PinchTab
</span>
@@ -99,35 +111,20 @@ export default function NavBar({ onRefresh, showLogout = false }: NavBarProps) {
</nav>
<div className="ml-auto flex items-center gap-1.5">
- {serverInfo && (
- <div
- className={`mr-2 flex items-center gap-1.5 rounded-full px-2.5 py-1 ${
- serverInfo.restartRequired
- ? "border border-warning/25 bg-warning/10"
- : "border border-success/20 bg-success/10"
- }`}
- title={
- serverInfo.restartRequired
- ? serverInfo.restartReasons?.join(", ") || "Restart required"
- : "Server running"
- }
- >
- <div
- className={`h-1.5 w-1.5 rounded-full ${
- serverInfo.restartRequired
- ? "bg-warning"
- : "bg-success animate-pulse"
- }`}
- />
- <span
- className={`text-[10px] font-bold uppercase tracking-wider ${
- serverInfo.restartRequired ? "text-warning" : "text-success"
- }`}
- >
- {serverInfo.restartRequired ? "Restart Required" : "Running"}
- </span>
- </div>
- )}
+ <ServerStatusBadge
+ serverInfo={serverInfo}
+ instance={selectedInstance}
+ compact={!isMonitoringPage}
+ sidebarCollapsed={monitoringSidebarCollapsed}
+ tabCount={
+ selectedInstance
+ ? currentTabs[selectedInstance.id]?.length ?? 0
+ : 0
+ }
+ onToggleSidebar={() =>
+ setMonitoringSidebarCollapsed(!monitoringSidebarCollapsed)
+ }
+ />
{showLogout && (
<button
type="button"
diff --git a/dashboard/src/components/molecules/ServerStatusBadge.tsx b/dashboard/src/components/molecules/ServerStatusBadge.tsx
new file mode 100644
index 00000000..945e6856
--- /dev/null
+++ b/dashboard/src/components/molecules/ServerStatusBadge.tsx
@@ -0,0 +1,108 @@
+import type { Instance } from "../../generated/types";
+import type { DashboardServerInfo } from "../../types";
+
+interface Props {
+ serverInfo: DashboardServerInfo | null;
+ instance?: Instance | null;
+ compact?: boolean;
+ sidebarCollapsed?: boolean;
+ tabCount?: number;
+ onToggleSidebar?: () => void;
+}
+
+export default function ServerStatusBadge({
+ serverInfo,
+ instance,
+ compact = false,
+ sidebarCollapsed = false,
+ tabCount = 0,
+ onToggleSidebar,
+}: Props) {
+ if (instance) {
+ const statusColor =
+ instance.status === "running"
+ ? "bg-success"
+ : instance.status === "error"
+ ? "bg-destructive"
+ : "bg-text-muted";
+
+ if (compact) {
+ return (
+ <div
+ className="mr-2 flex items-center gap-1.5 px-2 py-1 text-text-muted"
+ title={`${instance.profileName} · ${instance.status} · ${instance.port}`}
+ >
+ <div className={`h-1.5 w-1.5 shrink-0 rounded-full ${statusColor}`} />
+ <span className="text-[10px] tracking-wider">
+ {instance.port}
+ </span>
+ </div>
+ );
+ }
+
+ return (
+ <button
+ type="button"
+ onClick={onToggleSidebar}
+ className="mr-2 flex items-center gap-1.5 px-2 py-1 text-text-muted transition-colors hover:text-text-primary"
+ title={sidebarCollapsed ? "Expand instance list" : "Collapse instance list"}
+ >
+ <svg
+ viewBox="0 0 24 24"
+ aria-hidden="true"
+ className={`h-3 w-3 shrink-0 transition-transform ${sidebarCollapsed ? "" : "rotate-180"}`}
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ >
+ <polyline points="6 9 12 15 18 9" />
+ </svg>
+ <div className={`h-1.5 w-1.5 shrink-0 rounded-full ${statusColor}`} />
+ <span className="hidden text-[10px] font-bold uppercase tracking-wider lg:inline">
+ {instance.profileName} ·
+ </span>
+ <span className="hidden text-[10px] tracking-wider lg:inline">
+ {instance.status} · {tabCount} tab
+ {tabCount !== 1 ? "s" : ""} ·{" "}
+ </span>
+ <span className="text-[10px] tracking-wider">
+ {instance.port}
+ </span>
+ </button>
+ );
+ }
+
+ if (!serverInfo) return null;
+
+ return (
+ <div
+ className={`mr-2 flex items-center gap-1.5 rounded-full px-2.5 py-1 ${
+ serverInfo.restartRequired
+ ? "border border-warning/25 bg-warning/10"
+ : "border border-success/20 bg-success/10"
+ }`}
+ title={
+ serverInfo.restartRequired
+ ? serverInfo.restartReasons?.join(", ") || "Restart required"
+ : "Server running"
+ }
+ >
+ <div
+ className={`h-1.5 w-1.5 rounded-full ${
+ serverInfo.restartRequired
+ ? "bg-warning"
+ : "bg-success animate-pulse"
+ }`}
+ />
+ <span
+ className={`text-[10px] font-bold uppercase tracking-wider ${
+ serverInfo.restartRequired ? "text-warning" : "text-success"
+ }`}
+ >
+ {serverInfo.restartRequired ? "Restart Required" : "Running"}
+ </span>
+ </div>
+ );
+}
diff --git a/dashboard/src/components/molecules/TabsChart.tsx b/dashboard/src/components/molecules/TabsChart.tsx
index acf7c996..00f0da11 100644
--- a/dashboard/src/components/molecules/TabsChart.tsx
+++ b/dashboard/src/components/molecules/TabsChart.tsx
@@ -173,7 +173,7 @@ function AnimatedCursor({
/* ── Loading Dots ── */
function LoadingDots({ text }: { text: string }) {
return (
- <div className="dashboard-panel flex h-56 flex-col items-center justify-center gap-3">
+ <div className="flex h-56 flex-col items-center justify-center gap-3">
<div className="flex gap-1.5">
{[0, 1, 2].map((i) => (
<span
@@ -288,7 +288,7 @@ export default function TabsChart({
const hasServer = serverData && serverData.length > 0;
return (
- <div className="dashboard-panel overflow-hidden">
+ <div className="overflow-hidden">
<div className="flex items-center justify-between border-b border-border-subtle px-4 py-3">
<div className="flex items-center gap-2.5">
<div>
diff --git a/dashboard/src/components/molecules/TabsLayout.tsx b/dashboard/src/components/molecules/TabsLayout.tsx
index 4261cbf9..089a3869 100644
--- a/dashboard/src/components/molecules/TabsLayout.tsx
+++ b/dashboard/src/components/molecules/TabsLayout.tsx
@@ -25,7 +25,7 @@ export default function TabsLayout<T extends string>({
}: Props<T>) {
return (
<div className={`flex h-full flex-col overflow-hidden ${className}`}>
- <div className="border-b border-border-subtle px-4 py-2">
+ <div className="border-b border-border-subtle px-4 py-3">
<div className="flex items-center gap-1">
{tabs.map((tab) => (
<button
diff --git a/dashboard/src/instances/InstanceListItem.tsx b/dashboard/src/instances/InstanceListItem.tsx
index 2710a7cc..a6a44487 100644
--- a/dashboard/src/instances/InstanceListItem.tsx
+++ b/dashboard/src/instances/InstanceListItem.tsx
@@ -36,10 +36,10 @@ export default function InstanceListItem({
return (
<button
onClick={onClick}
- className={`mb-2 flex w-full flex-col gap-1 px-3 py-2.5 text-left ${
+ className={`flex w-full flex-col gap-1 border-b border-border-subtle px-3 py-2.5 text-left transition-colors ${
selected
- ? "dashboard-panel dashboard-panel-selected border-primary"
- : "dashboard-panel dashboard-panel-hover"
+ ? "bg-bg-hover text-text-primary"
+ : "hover:bg-bg-hover/50"
}`}
>
<div className="flex w-full items-center gap-2">
diff --git a/dashboard/src/pages/MonitoringPage.tsx b/dashboard/src/pages/MonitoringPage.tsx
index 3b9dc6b8..d59c890c 100644
--- a/dashboard/src/pages/MonitoringPage.tsx
+++ b/dashboard/src/pages/MonitoringPage.tsx
@@ -2,7 +2,6 @@ import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { useAppStore } from "../stores/useAppStore";
import { EmptyState, ErrorBoundary } from "../components/atoms";
-import { TabsChart } from "../components/molecules";
import InstanceListItem from "../instances/InstanceListItem";
import InstanceTabsPanel from "../tabs/InstanceTabsPanel";
import * as api from "../services/api";
@@ -10,15 +9,17 @@ import * as api from "../services/api";
export default function MonitoringPage() {
const {
instances,
- tabsChartData,
- memoryChartData,
- serverChartData,
currentTabs,
currentMemory,
settings,
+ monitoringSidebarCollapsed: sidebarCollapsed,
+ setMonitoringSidebarCollapsed: setSidebarCollapsed,
+ selectedMonitoringInstanceId,
+ setSelectedMonitoringInstanceId,
} = useAppStore();
const navigate = useNavigate();
- const [selectedId, setSelectedId] = useState<string | null>(null);
+ const selectedId = selectedMonitoringInstanceId;
+ const setSelectedId = setSelectedMonitoringInstanceId;
const [strategy, setStrategy] = useState<string>("always-on");
const memoryEnabled = settings.monitoring?.memoryMetrics ?? false;
@@ -53,32 +54,10 @@ export default function MonitoringPage() {
const selectedInstance = instances?.find((i) => i.id === selectedId);
const selectedTabs = selectedId ? currentTabs?.[selectedId] || [] : [];
- const runningInstances =
- instances?.filter((i) => i?.status === "running") || [];
return (
<ErrorBoundary>
- <div className="flex h-full flex-col gap-4 overflow-hidden p-4">
- <ErrorBoundary
- fallback={
- <div className="flex h-50 items-center justify-center rounded-lg border border-destructive/50 bg-bg-surface text-sm text-destructive">
- Chart crashed - check console
- </div>
- }
- >
- <TabsChart
- data={tabsChartData || []}
- memoryData={memoryEnabled ? memoryChartData : undefined}
- serverData={serverChartData || []}
- instances={runningInstances.map((i) => ({
- id: i.id,
- profileName: i.profileName || "Unknown",
- }))}
- selectedInstanceId={selectedId}
- onSelectInstance={setSelectedId}
- />
- </ErrorBoundary>
-
+ <div className="flex h-full flex-col overflow-hidden">
{instances.length === 0 && (
<div className="flex flex-1 items-center justify-center">
<EmptyState
@@ -90,50 +69,78 @@ export default function MonitoringPage() {
)}
{instances.length > 0 && (
- <div className="flex flex-1 gap-4 overflow-hidden">
- <div className="dashboard-panel w-64 shrink-0 overflow-auto">
- <div className="p-2">
- {instances.map((inst) => (
- <InstanceListItem
- key={inst.id}
- instance={inst}
- tabCount={currentTabs[inst.id]?.length ?? 0}
- memoryMB={
- memoryEnabled ? currentMemory[inst.id] : undefined
- }
- selected={selectedId === inst.id}
- autoRestart={
- inst.profileName === "default" &&
- (strategy === "always-on" ||
- strategy === "simple-autorestart")
- }
- onClick={() => setSelectedId(inst.id)}
- onStop={() => handleStop(inst.id)}
- onOpenProfile={() =>
- navigate("/dashboard/profiles", {
- state: {
- selectedProfileKey:
- inst.profileId || inst.profileName,
- },
- })
- }
- />
- ))}
- </div>
- </div>
-
- {/* Selected instance details */}
- <div className="dashboard-panel flex flex-1 flex-col overflow-hidden">
- {selectedInstance ? (
- <InstanceTabsPanel
- tabs={selectedTabs}
- instanceId={selectedId || undefined}
- />
- ) : (
- <div className="flex flex-1 items-center justify-center text-sm text-text-muted">
- Select an instance to view details
+ <div className="dashboard-panel flex flex-1 flex-col overflow-hidden rounded-none!">
+ <div className="flex flex-1 overflow-hidden">
+ {!sidebarCollapsed && (
+ <div className="w-64 shrink-0 overflow-auto border-r border-border-subtle bg-bg-surface/50">
+ <div className="flex items-center justify-between border-b border-border-subtle px-3 py-1.5">
+ <span className="text-xs font-medium text-text-muted">
+ Instances
+ </span>
+ <button
+ type="button"
+ onClick={() => setSidebarCollapsed(true)}
+ title="Collapse sidebar"
+ className="rounded p-1 text-text-muted transition-colors hover:bg-white/10 hover:text-text-secondary"
+ >
+ <svg
+ viewBox="0 0 24 24"
+ aria-hidden="true"
+ className="h-3.5 w-3.5"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ >
+ <polyline points="15 18 9 12 15 6" />
+ </svg>
+ </button>
+ </div>
+ <div>
+ {instances.map((inst) => (
+ <InstanceListItem
+ key={inst.id}
+ instance={inst}
+ tabCount={currentTabs[inst.id]?.length ?? 0}
+ memoryMB={
+ memoryEnabled ? currentMemory[inst.id] : undefined
+ }
+ selected={selectedId === inst.id}
+ autoRestart={
+ inst.profileName === "default" &&
+ (strategy === "always-on" ||
+ strategy === "simple-autorestart")
+ }
+ onClick={() => setSelectedId(inst.id)}
+ onStop={() => handleStop(inst.id)}
+ onOpenProfile={() =>
+ navigate("/dashboard/profiles", {
+ state: {
+ selectedProfileKey:
+ inst.profileId || inst.profileName,
+ },
+ })
+ }
+ />
+ ))}
+ </div>
</div>
)}
+
+ {/* Selected instance details */}
+ <div className="flex flex-1 flex-col overflow-hidden">
+ {selectedInstance ? (
+ <InstanceTabsPanel
+ tabs={selectedTabs}
+ instanceId={selectedId || undefined}
+ />
+ ) : (
+ <div className="flex flex-1 items-center justify-center text-sm text-text-muted">
+ Select an instance to view details
+ </div>
+ )}
+ </div>
</div>
</div>
)}
diff --git a/dashboard/src/pages/ProfilesPage.tsx b/dashboard/src/pages/ProfilesPage.tsx
index d588d46b..dd6ce71b 100644
--- a/dashboard/src/pages/ProfilesPage.tsx
+++ b/dashboard/src/pages/ProfilesPage.tsx
@@ -1,7 +1,7 @@
import { useEffect, useState, useMemo } from "react";
import { useLocation } from "react-router-dom";
import { useAppStore } from "../stores/useAppStore";
-import { Toolbar, EmptyState, Button, Badge } from "../components/atoms";
+import { EmptyState, Button, Badge } from "../components/atoms";
import * as api from "../services/api";
import type { Profile } from "../generated/types";
import {
@@ -151,10 +151,6 @@ export default function ProfilesPage() {
orderedProfiles.find(
(profile) => getProfileKey(profile) === launchProfileKey,
) || null;
- const runningProfiles = instances.filter(
- (instance) => instance.status === "running",
- ).length;
-
useEffect(() => {
if (orderedProfiles.length === 0) {
setSelectedProfileKey(null);
@@ -176,19 +172,7 @@ export default function ProfilesPage() {
return (
<div className="flex h-full flex-col">
- <Toolbar
- actions={[
- { key: "refresh", label: "Refresh", onClick: loadProfiles },
- {
- key: "new",
- label: "New Profile",
- onClick: () => setShowCreate(true),
- variant: "primary",
- },
- ]}
- />
-
- <div className="flex flex-1 flex-col overflow-hidden p-4 lg:p-6">
+ <div className="flex flex-1 flex-col overflow-hidden">
<div className="h-full">
{profilesLoading && profiles.length === 0 ? (
<div className="flex items-center justify-center py-16 text-text-muted">
@@ -205,24 +189,23 @@ export default function ProfilesPage() {
}
/>
) : (
- <div className="flex h-full min-h-0 flex-col gap-4 lg:flex-row">
- <div className="dashboard-panel flex max-h-88 w-full shrink-0 flex-col overflow-hidden lg:max-h-none lg:w-80">
- <div className="border-b border-border-subtle px-4 py-3">
- <div className="dashboard-section-label mb-1">Profiles</div>
- <div className="flex items-center justify-between gap-3">
- <h3 className="text-sm font-semibold text-text-secondary">
- Profiles ({profiles.length})
- </h3>
- <Badge
- variant={runningProfiles > 0 ? "success" : "default"}
- >
- {runningProfiles} running
- </Badge>
- </div>
+ <div className="dashboard-panel flex h-full min-h-0 flex-col overflow-hidden rounded-none! lg:flex-row">
+ <div className="flex max-h-88 w-full shrink-0 flex-col overflow-hidden border-r border-border-subtle bg-bg-surface/50 lg:max-h-none lg:w-80">
+ <div className="flex items-center justify-between border-b border-border-subtle px-4 py-2.5">
+ <span className="text-xs font-medium text-text-muted">
+ Profiles
+ </span>
+ <button
+ type="button"
+ onClick={() => setShowCreate(true)}
+ className="rounded bg-primary px-2.5 py-1 text-xs font-medium text-white transition-colors hover:bg-primary/90"
+ >
+ New Profile
+ </button>
</div>
- <div className="flex-1 overflow-auto p-2">
- <div className="space-y-2">
+ <div className="flex-1 overflow-auto">
+ <div>
{orderedProfiles.map((profile) => {
const instance = instanceByProfile.get(profile.name);
const isSelected =
@@ -251,10 +234,10 @@ export default function ProfilesPage() {
onClick={() =>
setSelectedProfileKey(getProfileKey(profile))
}
- className={`w-full rounded-2xl border px-4 py-3 text-left transition ${
+ className={`w-full border-b border-border-subtle px-3 py-2.5 text-left transition-colors ${
isSelected
- ? "dashboard-panel-selected border-primary"
- : "dashboard-panel-hover border-border-subtle bg-black/10"
+ ? "bg-bg-hover text-text-primary"
+ : "hover:bg-bg-hover/50"
}`}
>
<div className="flex items-start justify-between gap-3">
diff --git a/dashboard/src/profiles/InstanceLogsPanel.tsx b/dashboard/src/profiles/InstanceLogsPanel.tsx
index 42c996e2..4780cef2 100644
--- a/dashboard/src/profiles/InstanceLogsPanel.tsx
+++ b/dashboard/src/profiles/InstanceLogsPanel.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useState } from "react";
+import { useEffect, useRef, useState } from "react";
import * as api from "../services/api";
interface Props {
@@ -12,6 +12,7 @@ export default function InstanceLogsPanel({
}: Props) {
const [logs, setLogs] = useState("");
const [loading, setLoading] = useState(false);
+ const bottomRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!instanceId) {
@@ -57,21 +58,39 @@ export default function InstanceLogsPanel({
});
}, [instanceId]);
+ useEffect(() => {
+ bottomRef.current?.scrollIntoView({ behavior: "smooth" });
+ }, [logs]);
+
+ if (loading && !logs) {
+ return (
+ <div className="flex h-full items-center justify-center text-sm text-text-muted">
+ Loading logs...
+ </div>
+ );
+ }
+
+ if (!logs) {
+ return (
+ <div className="flex h-full items-center justify-center text-sm text-text-muted">
+ {emptyMessage}
+ </div>
+ );
+ }
+
+ const lines = logs.split("\n");
+
return (
- <div className="flex h-full min-h-0 flex-col">
- {loading && !logs ? (
- <div className="flex h-full items-center justify-center border border-border-subtle bg-black/10 px-4 py-6 text-sm text-text-muted">
- Loading logs...
- </div>
- ) : logs ? (
- <pre className="h-full overflow-auto border border-border-subtle bg-black/10 p-3 font-mono text-[10px] leading-4 text-text-secondary">
- {logs}
- </pre>
- ) : (
- <div className="flex h-full items-center justify-center border border-border-subtle bg-black/10 px-4 py-6 text-sm text-text-muted">
- {emptyMessage}
+ <div className="min-h-0 flex-1 overflow-auto font-mono text-xs">
+ {lines.map((line, i) => (
+ <div
+ key={i}
+ className="border-b border-border-subtle/50 px-3 py-1.5 hover:bg-white/2"
+ >
+ <span className="break-all text-text-secondary">{line}</span>
</div>
- )}
+ ))}
+ <div ref={bottomRef} />
</div>
);
}
diff --git a/dashboard/src/profiles/ProfileDetailsPanel.tsx b/dashboard/src/profiles/ProfileDetailsPanel.tsx
index 21d3fa27..1d3a7b0b 100644
--- a/dashboard/src/profiles/ProfileDetailsPanel.tsx
+++ b/dashboard/src/profiles/ProfileDetailsPanel.tsx
@@ -3,7 +3,7 @@ import InstanceLogsPanel from "./InstanceLogsPanel";
import ProfileMetaInfoPanel from "./ProfileMetaInfoPanel";
import ProfileBasicInfoPanel from "./ProfileBasicInfoPanel";
import ProfileLiveViewPanel from "./ProfileLiveViewPanel";
-import ProfileToolbar from "./ProfileToolbar";
+import ProfileToolbarButtons from "./ProfileToolbarButtons";
import { InstanceTabsPanel } from "../tabs";
import { TabsLayout, EmptyView } from "../components/molecules";
import type { Profile, Instance, InstanceTab } from "../generated/types";
@@ -75,7 +75,7 @@ export default function ProfileDetailsPanel({
if (!profile) {
return (
- <div className="dashboard-panel h-full min-h-112">
+ <div className="h-full min-h-112">
<EmptyView message="Select a profile to inspect its instance, live tabs, and logs." />
</div>
);
@@ -86,31 +86,30 @@ export default function ProfileDetailsPanel({
formValues.useWhen !== (profile.useWhen || "");
const profileTabs: { id: TabId; label: string; badge?: string | number }[] = [
- { id: "profile", label: "Profile" },
+ { id: "profile", label: `Profile: ${profile.name}` },
{ id: "live", label: "Live" },
{ id: "tabs", label: "Tabs", badge: tabs.length },
{ id: "logs", label: "Logs" },
];
return (
- <div className="dashboard-panel flex h-full min-h-112 flex-col overflow-hidden">
- <div className="border-b border-border-subtle px-4 py-3 lg:px-5">
- <ProfileToolbar
- profile={profile}
- instance={instance}
- onLaunch={onLaunch}
- onStop={onStop || (() => {})}
- onSave={handleSave}
- onDelete={onDelete || (() => {})}
- isSaveDisabled={!formValues.name.trim() || !hasChanges}
- />
- </div>
-
+ <div className="flex h-full min-h-112 flex-col overflow-hidden">
<div className="min-h-0 flex-1 overflow-hidden">
<TabsLayout
tabs={profileTabs}
activeTab={activeTab}
onChange={(id) => setActiveTab(id)}
+ rightSlot={
+ <ProfileToolbarButtons
+ profile={profile}
+ instance={instance}
+ onLaunch={onLaunch}
+ onStop={onStop || (() => {})}
+ onSave={handleSave}
+ onDelete={onDelete || (() => {})}
+ isSaveDisabled={!formValues.name.trim() || !hasChanges}
+ />
+ }
>
{activeTab === "profile" && (
<div className="h-full overflow-auto p-4">
diff --git a/dashboard/src/profiles/ProfileToolbar.tsx b/dashboard/src/profiles/ProfileToolbar.tsx
deleted file mode 100644
index 98d99d0d..00000000
--- a/dashboard/src/profiles/ProfileToolbar.tsx
+++ /dev/null
@@ -1,89 +0,0 @@
-import { useState } from "react";
-import { Button } from "../components/atoms";
-import type { Profile, Instance } from "../generated/types";
-
-interface Props {
- profile: Profile;
- instance?: Instance;
- onLaunch: () => void;
- onStop: () => void;
- onSave: () => void;
- onDelete: () => void;
- isSaveDisabled: boolean;
-}
-
-export default function ProfileToolbar({
- profile,
- instance,
- onLaunch,
- onStop,
- onSave,
- onDelete,
- isSaveDisabled,
-}: Props) {
- const [copyFeedback, setCopyFeedback] = useState("");
- const isRunning = instance?.status === "running";
-
- const handleCopyId = async () => {
- if (!profile.id) return;
- try {
- await navigator.clipboard.writeText(profile.id);
- setCopyFeedback("Copied");
- setTimeout(() => setCopyFeedback(""), 2000);
- } catch {
- setCopyFeedback("Failed");
- setTimeout(() => setCopyFeedback(""), 2000);
- }
- };
-
- const headerMeta = [instance?.attached ? "CDP attached" : null].filter(
- Boolean,
- );
-
- return (
- <div className="flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between">
- <div className="min-w-0">
- <div className="flex flex-wrap items-center gap-3">
- <h2 className="truncate text-lg font-semibold text-text-primary">
- {profile.name}
- </h2>
- {headerMeta.length > 0 && (
- <div className="text-sm text-text-muted">
- {headerMeta.join(" · ")}
- </div>
- )}
- </div>
- {profile.useWhen?.trim() && (
- <p className="mt-1 text-sm text-text-muted">{profile.useWhen}</p>
- )}
- </div>
- <div className="flex shrink-0 flex-wrap gap-2">
- {profile.id && (
- <Button size="sm" variant="secondary" onClick={handleCopyId}>
- {copyFeedback || "Copy ID"}
- </Button>
- )}
- <Button size="sm" variant="secondary" onClick={onDelete}>
- Delete
- </Button>
- <Button
- size="sm"
- variant="primary"
- onClick={onSave}
- disabled={isSaveDisabled}
- >
- Save
- </Button>
- {isRunning ? (
- <Button size="sm" variant="danger" onClick={onStop}>
- Stop
- </Button>
- ) : (
- <Button size="sm" variant="primary" onClick={onLaunch}>
- Start
- </Button>
- )}
- </div>
- </div>
- );
-}
diff --git a/dashboard/src/profiles/ProfileToolbarButtons.tsx b/dashboard/src/profiles/ProfileToolbarButtons.tsx
new file mode 100644
index 00000000..4397e0b3
--- /dev/null
+++ b/dashboard/src/profiles/ProfileToolbarButtons.tsx
@@ -0,0 +1,68 @@
+import { useState } from "react";
+import { Button } from "../components/atoms";
+import type { Profile, Instance } from "../generated/types";
+
+interface Props {
+ profile: Profile;
+ instance?: Instance;
+ onLaunch: () => void;
+ onStop: () => void;
+ onSave: () => void;
+ onDelete: () => void;
+ isSaveDisabled: boolean;
+}
+
+export default function ProfileToolbarButtons({
+ profile,
+ instance,
+ onLaunch,
+ onStop,
+ onSave,
+ onDelete,
+ isSaveDisabled,
+}: Props) {
+ const [copyFeedback, setCopyFeedback] = useState("");
+ const isRunning = instance?.status === "running";
+
+ const handleCopyId = async () => {
+ if (!profile.id) return;
+ try {
+ await navigator.clipboard.writeText(profile.id);
+ setCopyFeedback("Copied");
+ setTimeout(() => setCopyFeedback(""), 2000);
+ } catch {
+ setCopyFeedback("Failed");
+ setTimeout(() => setCopyFeedback(""), 2000);
+ }
+ };
+
+ return (
+ <div className="flex shrink-0 items-center gap-1.5">
+ {profile.id && (
+ <Button size="sm" variant="secondary" onClick={handleCopyId}>
+ {copyFeedback || "Copy ID"}
+ </Button>
+ )}
+ <Button size="sm" variant="secondary" onClick={onDelete}>
+ Delete
+ </Button>
+ <Button
+ size="sm"
+ variant="primary"
+ onClick={onSave}
+ disabled={isSaveDisabled}
+ >
+ Save
+ </Button>
+ {isRunning ? (
+ <Button size="sm" variant="danger" onClick={onStop}>
+ Stop
+ </Button>
+ ) : (
+ <Button size="sm" variant="primary" onClick={onLaunch}>
+ Start
+ </Button>
+ )}
+ </div>
+ );
+}
diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.ts
index 847fdfab..174baddc 100644
--- a/dashboard/src/services/api.ts
+++ b/dashboard/src/services/api.ts
@@ -226,6 +226,41 @@ export async function closeTab(tabId: string): Promise<void> {
await request(`/tabs/${encodeURIComponent(tabId)}/close`, { method: "POST" });
}
+export interface ConsoleLogEntry {
+ timestamp: string;
+ level: string;
+ message: string;
+ source?: string;
+}
+
+export interface ErrorLogEntry {
+ timestamp: string;
+ message: string;
+ type?: string;
+ url?: string;
+ line?: number;
+ column?: number;
+ stack?: string;
+}
+
+export async function fetchConsoleLogs(
+ tabId: string,
+): Promise<ConsoleLogEntry[]> {
+ const res = await request<{ console: ConsoleLogEntry[] }>(
+ `/console?tabId=${encodeURIComponent(tabId)}`,
+ );
+ return res.console || [];
+}
+
+export async function fetchErrorLogs(
+ tabId: string,
+): Promise<ErrorLogEntry[]> {
+ const res = await request<{ errors: ErrorLogEntry[] }>(
+ `/errors?tabId=${encodeURIComponent(tabId)}`,
+ );
+ return res.errors || [];
+}
+
export async function navigateTab(
tabId: string,
url: string,
diff --git a/dashboard/src/stores/useAppStore.ts b/dashboard/src/stores/useAppStore.ts
index d76434ef..76711d25 100644
--- a/dashboard/src/stores/useAppStore.ts
+++ b/dashboard/src/stores/useAppStore.ts
@@ -3,6 +3,7 @@ import type {
Profile,
Instance,
InstanceTab,
+ InstanceMetrics,
Agent,
ActivityEvent,
Settings,
@@ -45,6 +46,7 @@ interface AppState {
serverChartData: ServerDataPoint[];
currentTabs: Record<string, InstanceTab[]>;
currentMemory: Record<string, number>; // instanceId -> jsHeapUsedMB
+ currentMetrics: Record<string, InstanceMetrics>; // instanceId -> full metrics
addChartDataPoint: (point: TabDataPoint) => void;
addMemoryDataPoint: (point: MemoryDataPoint) => void;
addServerDataPoint: (point: ServerDataPoint) => void;
@@ -79,6 +81,14 @@ interface AppState {
// Server info
serverInfo: DashboardServerInfo | null;
setServerInfo: (info: DashboardServerInfo | null) => void;
+
+ // Monitoring UI
+ monitoringSidebarCollapsed: boolean;
+ setMonitoringSidebarCollapsed: (collapsed: boolean) => void;
+ selectedMonitoringInstanceId: string | null;
+ setSelectedMonitoringInstanceId: (id: string | null) => void;
+ monitoringShowTelemetry: boolean;
+ setMonitoringShowTelemetry: (show: boolean) => void;
}
const defaultSettings: Settings = {
@@ -188,6 +198,7 @@ export const useAppStore = create<AppState>((set) => ({
serverChartData: [],
currentTabs: {},
currentMemory: {},
+ currentMetrics: {},
addChartDataPoint: (point) =>
set((state) => ({
tabsChartData: [...state.tabsChartData.slice(-59), point], // Keep last 60 points
@@ -211,6 +222,7 @@ export const useAppStore = create<AppState>((set) => ({
const memDataPoint: MemoryDataPoint = { timestamp: snapshot.timestamp };
const currentTabs: Record<string, InstanceTab[]> = {};
const currentMemory: Record<string, number> = {};
+ const currentMetrics: Record<string, InstanceMetrics> = {};
for (const instance of runningInstances) {
const instanceTabs = snapshot.tabs.filter(
@@ -226,6 +238,7 @@ export const useAppStore = create<AppState>((set) => ({
if (metrics) {
memDataPoint[instance.id] = metrics.jsHeapUsedMB;
currentMemory[instance.id] = metrics.jsHeapUsedMB;
+ currentMetrics[instance.id] = metrics;
}
}
}
@@ -234,6 +247,7 @@ export const useAppStore = create<AppState>((set) => ({
instances: snapshot.instances,
currentTabs,
currentMemory,
+ currentMetrics,
tabsChartData:
runningInstances.length > 0
? [...state.tabsChartData.slice(-59), tabDataPoint]
@@ -404,4 +418,15 @@ export const useAppStore = create<AppState>((set) => ({
// Server info
serverInfo: null,
setServerInfo: (serverInfo) => set({ serverInfo }),
+
+ // Monitoring UI
+ monitoringSidebarCollapsed: true,
+ setMonitoringSidebarCollapsed: (monitoringSidebarCollapsed) =>
+ set({ monitoringSidebarCollapsed }),
+ selectedMonitoringInstanceId: null,
+ setSelectedMonitoringInstanceId: (selectedMonitoringInstanceId) =>
+ set({ selectedMonitoringInstanceId }),
+ monitoringShowTelemetry: false,
+ setMonitoringShowTelemetry: (monitoringShowTelemetry) =>
+ set({ monitoringShowTelemetry }),
}));
diff --git a/dashboard/src/tabs/ConsolePanel.tsx b/dashboard/src/tabs/ConsolePanel.tsx
new file mode 100644
index 00000000..b84007c0
--- /dev/null
+++ b/dashboard/src/tabs/ConsolePanel.tsx
@@ -0,0 +1,104 @@
+import { useEffect, useState } from "react";
+import * as api from "../services/api";
+import type { ConsoleLogEntry } from "../services/api";
+
+interface Props {
+ tabId: string;
+}
+
+const LEVEL_STYLES: Record<string, string> = {
+ error: "text-destructive",
+ warn: "text-warning",
+ info: "text-info",
+ debug: "text-text-muted",
+ log: "text-text-secondary",
+};
+
+function formatTime(ts: string): string {
+ return new Date(ts).toLocaleTimeString("en-GB", {
+ hour: "2-digit",
+ minute: "2-digit",
+ second: "2-digit",
+ });
+}
+
+export default function ConsolePanel({ tabId }: Props) {
+ const [logs, setLogs] = useState<ConsoleLogEntry[]>([]);
+ const [loading, setLoading] = useState(true);
+
+ useEffect(() => {
+ let cancelled = false;
+ setLoading(true);
+
+ const fetchLogs = () => {
+ api
+ .fetchConsoleLogs(tabId)
+ .then((data) => {
+ if (!cancelled) setLogs(data);
+ })
+ .catch(() => {
+ if (!cancelled) setLogs([]);
+ })
+ .finally(() => {
+ if (!cancelled) setLoading(false);
+ });
+ };
+
+ fetchLogs();
+ const interval = setInterval(fetchLogs, 3000);
+ return () => {
+ cancelled = true;
+ clearInterval(interval);
+ };
+ }, [tabId]);
+
+ if (loading) {
+ return (
+ <div className="flex h-full flex-1 items-center justify-center text-sm text-text-muted">
+ Loading console logs...
+ </div>
+ );
+ }
+
+ if (logs.length === 0) {
+ return (
+ <div className="flex h-full flex-1 items-center justify-center text-sm text-text-muted">
+ No console logs yet
+ </div>
+ );
+ }
+
+ return (
+ <div className="min-h-0 flex-1 overflow-auto font-mono text-xs">
+ {logs.map((entry, i) => (
+ <div
+ key={`${entry.timestamp}-${i}`}
+ className={`flex gap-2 border-b border-border-subtle/50 px-3 py-1.5 hover:bg-white/2 ${
+ entry.level === "error"
+ ? "bg-destructive/5"
+ : entry.level === "warn"
+ ? "bg-warning/5"
+ : ""
+ }`}
+ >
+ <span className="shrink-0 text-text-muted">
+ {formatTime(entry.timestamp)}
+ </span>
+ <span
+ className={`w-10 shrink-0 font-semibold uppercase ${LEVEL_STYLES[entry.level] || "text-text-muted"}`}
+ >
+ {entry.level}
+ </span>
+ <span className="min-w-0 flex-1 break-all text-text-primary">
+ {entry.message}
+ </span>
+ {entry.source && (
+ <span className="shrink-0 truncate text-text-muted max-w-48">
+ {entry.source}
+ </span>
+ )}
+ </div>
+ ))}
+ </div>
+ );
+}
diff --git a/dashboard/src/tabs/ErrorsPanel.tsx b/dashboard/src/tabs/ErrorsPanel.tsx
new file mode 100644
index 00000000..aa78cb76
--- /dev/null
+++ b/dashboard/src/tabs/ErrorsPanel.tsx
@@ -0,0 +1,113 @@
+import { useEffect, useState } from "react";
+import * as api from "../services/api";
+import type { ErrorLogEntry } from "../services/api";
+
+interface Props {
+ tabId: string;
+}
+
+function formatTime(ts: string): string {
+ return new Date(ts).toLocaleTimeString("en-GB", {
+ hour: "2-digit",
+ minute: "2-digit",
+ second: "2-digit",
+ });
+}
+
+export default function ErrorsPanel({ tabId }: Props) {
+ const [errors, setErrors] = useState<ErrorLogEntry[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [expandedIndex, setExpandedIndex] = useState<number | null>(null);
+
+ useEffect(() => {
+ let cancelled = false;
+ setLoading(true);
+
+ const fetchErrors = () => {
+ api
+ .fetchErrorLogs(tabId)
+ .then((data) => {
+ if (!cancelled) setErrors(data);
+ })
+ .catch(() => {
+ if (!cancelled) setErrors([]);
+ })
+ .finally(() => {
+ if (!cancelled) setLoading(false);
+ });
+ };
+
+ fetchErrors();
+ const interval = setInterval(fetchErrors, 3000);
+ return () => {
+ cancelled = true;
+ clearInterval(interval);
+ };
+ }, [tabId]);
+
+ if (loading) {
+ return (
+ <div className="flex h-full flex-1 items-center justify-center text-sm text-text-muted">
+ Loading errors...
+ </div>
+ );
+ }
+
+ if (errors.length === 0) {
+ return (
+ <div className="flex h-full flex-1 items-center justify-center text-sm text-text-muted">
+ No errors yet
+ </div>
+ );
+ }
+
+ return (
+ <div className="min-h-0 flex-1 overflow-auto font-mono text-xs">
+ {errors.map((entry, i) => (
+ <div
+ key={`${entry.timestamp}-${i}`}
+ className="border-b border-border-subtle/50 bg-destructive/5 hover:bg-destructive/8"
+ >
+ <button
+ type="button"
+ onClick={() => setExpandedIndex(expandedIndex === i ? null : i)}
+ className="flex w-full gap-2 px-3 py-1.5 text-left"
+ >
+ <span className="shrink-0 text-text-muted">
+ {formatTime(entry.timestamp)}
+ </span>
+ {entry.type && (
+ <span className="shrink-0 font-semibold text-destructive">
+ {entry.type}
+ </span>
+ )}
+ <span className="min-w-0 flex-1 truncate text-text-primary">
+ {entry.message}
+ </span>
+ {entry.stack && (
+ <span className="shrink-0 text-text-muted">
+ {expandedIndex === i ? "▲" : "▼"}
+ </span>
+ )}
+ </button>
+ {expandedIndex === i && (
+ <div className="px-3 pb-2">
+ {entry.url && (
+ <div className="mb-1 text-text-muted">
+ {entry.url}
+ {entry.line ? `:${entry.line}` : ""}
+ {entry.column ? `:${entry.column}` : ""}
+ </div>
+ )}
+ {entry.stack && (
+ <pre className="overflow-x-auto whitespace-pre-wrap text-text-secondary">
+ {entry.stack}
+ </pre>
+ )}
+ </div>
+ )}
+ </div>
+ ))}
+ </div>
+ );
+}
diff --git a/dashboard/src/tabs/InstanceTabsPanel.tsx b/dashboard/src/tabs/InstanceTabsPanel.tsx
index 085b442b..30c1c6d2 100644
--- a/dashboard/src/tabs/InstanceTabsPanel.tsx
+++ b/dashboard/src/tabs/InstanceTabsPanel.tsx
@@ -1,5 +1,9 @@
-import { useEffect, useMemo, useState } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import type { InstanceTab } from "../generated/types";
+import { useAppStore } from "../stores/useAppStore";
+import { TabsChart } from "../components/molecules";
+import InstanceStats from "../components/molecules/InstanceStats";
+import { ErrorBoundary } from "../components/atoms";
import TabBar from "./TabBar";
import SelectedTabPanel from "./SelectedTabPanel";
@@ -16,14 +20,50 @@ export default function InstanceTabsPanel({
}: Props) {
const [selectedTabId, setSelectedTabId] = useState<string | null>(null);
const [selectionPinned, setSelectionPinned] = useState(false);
+ const manualTabsRef = useRef(false);
+
+ const {
+ instances,
+ tabsChartData,
+ memoryChartData,
+ serverChartData,
+ currentMetrics,
+ settings,
+ monitoringShowTelemetry: showTelemetry,
+ setMonitoringShowTelemetry: setShowTelemetry,
+ } = useAppStore();
+
+ const memoryEnabled = settings.monitoring?.memoryMetrics ?? false;
+
+ const selectedInstance = instances.find((i) => i.id === instanceId);
+ const chartInstances = useMemo(
+ () =>
+ selectedInstance
+ ? [
+ {
+ id: selectedInstance.id,
+ profileName: selectedInstance.profileName || "Unknown",
+ },
+ ]
+ : [],
+ [selectedInstance],
+ );
useEffect(() => {
if (tabs.length === 0) {
setSelectedTabId(null);
setSelectionPinned(false);
+ if (!manualTabsRef.current) {
+ setShowTelemetry(true);
+ }
return;
}
+ if (showTelemetry && !manualTabsRef.current) {
+ setShowTelemetry(false);
+ }
+ manualTabsRef.current = false;
+
if (selectionPinned && tabs.some((tab) => tab.id === selectedTabId)) {
return;
}
@@ -39,32 +79,24 @@ export default function InstanceTabsPanel({
setSelectionPinned(false);
}
}
- }, [selectedTabId, selectionPinned, tabs]);
+ }, [selectedTabId, selectionPinned, tabs, showTelemetry, setShowTelemetry]);
const selectedTab = useMemo(
() => tabs.find((tab) => tab.id === selectedTabId) ?? null,
[selectedTabId, tabs],
);
- if (tabs.length === 0) {
- return (
- <div className="flex min-h-0 flex-1 flex-col">
- <div className="flex flex-1 items-center justify-center py-8 text-sm text-text-muted">
- {emptyMessage}
- </div>
- </div>
- );
- }
-
return (
<div className="flex min-h-0 flex-1 flex-col">
<TabBar
tabs={tabs}
selectedTabId={selectedTabId}
pinnedTabId={selectionPinned ? selectedTabId : null}
+ telemetryActive={showTelemetry}
onSelect={(id) => {
setSelectedTabId(id);
setSelectionPinned(true);
+ setShowTelemetry(false);
}}
onTogglePinned={(id) => {
if (selectionPinned && selectedTabId === id) {
@@ -74,9 +106,45 @@ export default function InstanceTabsPanel({
}
setSelectedTabId(id);
setSelectionPinned(true);
+ setShowTelemetry(false);
+ }}
+ onSetTelemetry={(active) => {
+ manualTabsRef.current = !active;
+ setShowTelemetry(active);
}}
/>
- <SelectedTabPanel selectedTab={selectedTab} instanceId={instanceId} />
+
+ {tabs.length === 0 && !showTelemetry ? (
+ <div className="flex flex-1 items-center justify-center py-8 text-sm text-text-muted">
+ {emptyMessage}
+ </div>
+ ) : showTelemetry ? (
+ <div className="flex-1 overflow-auto">
+ <ErrorBoundary
+ fallback={
+ <div className="flex h-50 items-center justify-center rounded-lg border border-destructive/50 bg-bg-surface text-sm text-destructive">
+ Chart crashed - check console
+ </div>
+ }
+ >
+ <TabsChart
+ data={tabsChartData || []}
+ memoryData={memoryEnabled ? memoryChartData : undefined}
+ serverData={serverChartData || []}
+ instances={chartInstances}
+ selectedInstanceId={instanceId || null}
+ onSelectInstance={() => {}}
+ />
+ </ErrorBoundary>
+ <InstanceStats
+ instance={selectedInstance}
+ metrics={instanceId ? currentMetrics[instanceId] : null}
+ tabs={tabs}
+ />
+ </div>
+ ) : (
+ <SelectedTabPanel selectedTab={selectedTab} instanceId={instanceId} />
+ )}
</div>
);
}
diff --git a/dashboard/src/tabs/SelectedTabPanel.tsx b/dashboard/src/tabs/SelectedTabPanel.tsx
index 63f58e04..35c26362 100644
--- a/dashboard/src/tabs/SelectedTabPanel.tsx
+++ b/dashboard/src/tabs/SelectedTabPanel.tsx
@@ -4,6 +4,8 @@ import type { InstanceTab } from "../generated/types";
import { TabsLayout, EmptyView } from "../components/molecules";
import ScreencastTile from "../components/screencast/ScreencastTile";
import SelectedTabTitle from "./SelectedTabTitle";
+import ConsolePanel from "./ConsolePanel";
+import ErrorsPanel from "./ErrorsPanel";
interface Props {
selectedTab: InstanceTab | null;
@@ -77,10 +79,10 @@ export default function SelectedTabPanel({ selectedTab, instanceId }: Props) {
</div>
)}
{activeSubTab === "console" && (
- <EmptyView message="Console logs for this tab will appear here." />
+ <ConsolePanel tabId={selectedTab.id} />
)}
{activeSubTab === "errors" && (
- <EmptyView message="Runtime errors for this tab will appear here." />
+ <ErrorsPanel tabId={selectedTab.id} />
)}
</TabsLayout>
</div>
diff --git a/dashboard/src/tabs/TabBar.tsx b/dashboard/src/tabs/TabBar.tsx
index 14d7d0f8..7ebe2b33 100644
--- a/dashboard/src/tabs/TabBar.tsx
+++ b/dashboard/src/tabs/TabBar.tsx
@@ -5,9 +5,12 @@ interface Props {
tabs: InstanceTab[];
selectedTabId: string | null;
pinnedTabId?: string | null;
+ telemetryActive?: boolean;
onSelect: (id: string) => void;
onTogglePinned?: (id: string) => void;
onTabClosed?: () => void;
+ onToggleTelemetry?: () => void;
+ onSetTelemetry?: (active: boolean) => void;
}
function PinIcon({ pinned }: { pinned: boolean }) {
@@ -33,9 +36,12 @@ export default function TabBar({
tabs,
selectedTabId,
pinnedTabId,
+ telemetryActive,
onSelect,
onTogglePinned,
onTabClosed,
+ onToggleTelemetry,
+ onSetTelemetry,
}: Props) {
const handleClose = async (e: React.MouseEvent, tabId: string) => {
e.stopPropagation();
@@ -46,19 +52,17 @@ export default function TabBar({
console.error("Failed to close tab", err);
}
};
- if (tabs.length === 0) return null;
-
return (
- <div className="flex min-h-0 items-end gap-px overflow-x-auto border-b border-border-subtle bg-black/10 px-1 pt-1">
+ <div className="flex min-h-0 items-end gap-px overflow-x-auto border-b border-border-subtle bg-black/10">
{tabs.map((tab) => {
- const isSelected = tab.id === selectedTabId;
+ const isSelected = tab.id === selectedTabId && !telemetryActive;
const isPinned = tab.id === pinnedTabId;
const title = tab.title || "Untitled";
return (
<div
key={tab.id}
- className={`group relative flex max-w-52 min-w-0 items-center gap-1 rounded-t-md pl-3 pr-1.5 py-1.5 text-left transition-colors ${
+ className={`group relative flex max-w-52 min-w-0 items-center gap-1 pl-3 pr-1.5 py-1.5 text-left transition-colors ${
isSelected
? "bg-bg-surface text-text-primary border-x border-t border-border-subtle"
: "text-text-muted hover:bg-white/5 hover:text-text-secondary"
@@ -107,6 +111,58 @@ export default function TabBar({
</div>
);
})}
+ {(onSetTelemetry || onToggleTelemetry) && (
+ <div className="ml-auto mb-0.5 flex shrink-0 items-center gap-0.5 self-center">
+ <button
+ type="button"
+ onClick={() => (onSetTelemetry ? onSetTelemetry(false) : onToggleTelemetry?.())}
+ title="Tabs"
+ className={`shrink-0 rounded p-1.5 transition-colors ${
+ !telemetryActive
+ ? "bg-bg-hover text-text-primary"
+ : "text-text-muted hover:bg-white/10 hover:text-text-secondary"
+ }`}
+ >
+ <svg
+ viewBox="0 0 24 24"
+ aria-hidden="true"
+ className="h-4 w-4"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ >
+ <rect x="3" y="3" width="18" height="18" rx="2" />
+ <path d="M3 9h18" />
+ <path d="M9 3v6" />
+ </svg>
+ </button>
+ <button
+ type="button"
+ onClick={() => (onSetTelemetry ? onSetTelemetry(true) : onToggleTelemetry?.())}
+ title="Monitoring"
+ className={`mr-1 shrink-0 rounded p-1.5 transition-colors ${
+ telemetryActive
+ ? "bg-bg-hover text-text-primary"
+ : "text-text-muted hover:bg-white/10 hover:text-text-secondary"
+ }`}
+ >
+ <svg
+ viewBox="0 0 24 24"
+ aria-hidden="true"
+ className="h-4 w-4"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ >
+ <path d="M3 12h4l3 -9l4 18l3 -9h4" />
+ </svg>
+ </button>
+ </div>
+ )}
</div>
);
}
diff --git a/dashboard/vite.config.ts b/dashboard/vite.config.ts
index e162da7d..3c6015cd 100644
--- a/dashboard/vite.config.ts
+++ b/dashboard/vite.config.ts
@@ -16,18 +16,23 @@ export default defineConfig(() => {
ws: true,
}
- if (authHeader !== '') {
- options.headers = {
- Authorization: authHeader,
- }
- options.configure = (proxy) => {
- proxy.on('proxyReq', (proxyReq) => {
+ options.configure = (proxy) => {
+ proxy.on('proxyReq', (proxyReq) => {
+ if (authHeader !== '') {
proxyReq.setHeader('Authorization', authHeader)
- })
- proxy.on('proxyReqWs', (proxyReq) => {
+ }
+ if (!proxyReq.getHeader('X-PinchTab-Source')) {
+ proxyReq.setHeader('X-PinchTab-Source', 'dashboard')
+ }
+ })
+ proxy.on('proxyReqWs', (proxyReq) => {
+ if (authHeader !== '') {
proxyReq.setHeader('Authorization', authHeader)
- })
- }
+ }
+ if (!proxyReq.getHeader('X-PinchTab-Source')) {
+ proxyReq.setHeader('X-PinchTab-Source', 'dashboard')
+ }
+ })
}
return options
@@ -39,6 +44,7 @@ export default defineConfig(() => {
'/api', '/health', '/metrics', '/instances', '/profiles', '/tabs',
'/navigate', '/action', '/screenshot', '/evaluate', '/find', '/text',
'/snapshot', '/download', '/upload', '/cookies', '/fingerprint', '/scheduler',
+ '/console', '/errors',
]
const proxy: Record<string, ProxyOptions> = {}
for (const path of apiPaths) {
diff --git a/internal/activity/activity.go b/internal/activity/activity.go
index 4a4df918..3c555512 100644
--- a/internal/activity/activity.go
+++ b/internal/activity/activity.go
@@ -309,7 +309,7 @@ func (s *Store) queryFiles(source string) []string {
if !isActivityLogFile(name) {
continue
}
- if source == "" && !isPrimaryDailyActivityLog(name) {
+ if source != "" && !isSourceLogFile(name, source) {
continue
}
files = append(files, filepath.Join(s.dir, name))
@@ -423,6 +423,11 @@ func isPrimaryDailyActivityLog(name string) bool {
return len(middle) == len(time.DateOnly)
}
+func isSourceLogFile(name, source string) bool {
+ prefix := "events-" + source + "-"
+ return strings.HasPrefix(name, prefix)
+}
+
func activityLogDay(name string) (string, bool) {
if !isActivityLogFile(name) {
return "", false
diff --git a/internal/activity/activity_test.go b/internal/activity/activity_test.go
index b00f7f38..12627dfe 100644
--- a/internal/activity/activity_test.go
+++ b/internal/activity/activity_test.go
@@ -109,12 +109,12 @@ func TestStorePartitionsDashboardEventsOutsidePrimaryLog(t *testing.T) {
t.Fatal("dashboard activity log missing dashboard event")
}
- gotMain, err := store.Query(Filter{Limit: 10})
+ gotAll, err := store.Query(Filter{Limit: 10})
if err != nil {
- t.Fatalf("Query main: %v", err)
+ t.Fatalf("Query all: %v", err)
}
- if len(gotMain) != 1 || gotMain[0].Source != "server" {
- t.Fatalf("main query = %#v, want only external server event", gotMain)
+ if len(gotAll) != 2 {
+ t.Fatalf("unfiltered query = %d events, want 2 (server + dashboard)", len(gotAll))
}
gotDashboard, err := store.Query(Filter{Source: "dashboard", Limit: 10})
diff --git a/internal/activity/context.go b/internal/activity/context.go
index 984ee07b..c3273647 100644
--- a/internal/activity/context.go
+++ b/internal/activity/context.go
@@ -105,9 +105,13 @@ func sourceFor(r *http.Request, fallback string) string {
if source := strings.TrimSpace(r.Header.Get(HeaderPTSource)); source != "" {
return source
}
- if authn.CredentialsFromRequest(r).Method == authn.MethodCookie {
+ creds := authn.CredentialsFromRequest(r)
+ if creds.Method == authn.MethodCookie {
return "dashboard"
}
+ if creds.Method == authn.MethodHeader || creds.Method == authn.MethodSession {
+ return "client"
+ }
return fallback
}
diff --git a/internal/cli/apiclient/client.go b/internal/cli/apiclient/client.go
index 5c42557a..1d44c9cd 100644
--- a/internal/cli/apiclient/client.go
+++ b/internal/cli/apiclient/client.go
@@ -11,8 +11,6 @@ import (
"os"
"strings"
"time"
-
- "github.com/pinchtab/pinchtab/internal/activity"
)
func DoGet(client *http.Client, base, token, path string, params url.Values) map[string]any {
@@ -21,8 +19,7 @@ func DoGet(client *http.Client, base, token, path string, params url.Values) map
u += "?" + params.Encode()
}
req, _ := http.NewRequest("GET", u, nil)
- setAuthHeader(req, token)
- req.Header.Set(activity.HeaderAgentID, "cli")
+ setClientHeaders(req, token)
resp, err := client.Do(req)
if err != nil {
fatal("Request failed: %v", err)
@@ -57,8 +54,7 @@ func DoGetRaw(client *http.Client, base, token, path string, params url.Values)
u += "?" + params.Encode()
}
req, _ := http.NewRequest("GET", u, nil)
- setAuthHeader(req, token)
- req.Header.Set(activity.HeaderAgentID, "cli")
+ setClientHeaders(req, token)
resp, err := client.Do(req)
if err != nil {
fatal("Request failed: %v", err)
@@ -77,8 +73,7 @@ func DoPost(client *http.Client, base, token, path string, body map[string]any)
data, _ := json.Marshal(body)
req, _ := http.NewRequest("POST", base+path, bytes.NewReader(data))
req.Header.Set("Content-Type", "application/json")
- setAuthHeader(req, token)
- req.Header.Set(activity.HeaderAgentID, "cli")
+ setClientHeaders(req, token)
resp, err := client.Do(req)
if err != nil {
fatal("Request failed: %v", err)
@@ -113,8 +108,7 @@ func DoDelete(client *http.Client, base, token, path string, params url.Values)
u += "?" + params.Encode()
}
req, _ := http.NewRequest("DELETE", u, nil)
- setAuthHeader(req, token)
- req.Header.Set(activity.HeaderAgentID, "cli")
+ setClientHeaders(req, token)
resp, err := client.Do(req)
if err != nil {
fatal("Request failed: %v", err)
@@ -146,8 +140,7 @@ func DoDeleteJSON(client *http.Client, base, token, path string, body map[string
data, _ := json.Marshal(body)
req, _ := http.NewRequest("DELETE", base+path, bytes.NewReader(data))
req.Header.Set("Content-Type", "application/json")
- setAuthHeader(req, token)
- req.Header.Set(activity.HeaderAgentID, "cli")
+ setClientHeaders(req, token)
resp, err := client.Do(req)
if err != nil {
fatal("Request failed: %v", err)
@@ -192,7 +185,8 @@ func ResolveInstanceBase(orchBase, token, instanceID, bind string) string {
return fmt.Sprintf("http://%s:%s", bind, inst.Port)
}
-func setAuthHeader(req *http.Request, token string) {
+func setClientHeaders(req *http.Request, token string) {
+ req.Header.Set("X-PinchTab-Source", "client")
if token == "" {
return
}
diff --git a/internal/config/config_file.go b/internal/config/config_file.go
index 9c1afe83..86ad988f 100644
--- a/internal/config/config_file.go
+++ b/internal/config/config_file.go
@@ -46,7 +46,7 @@ func DefaultFileConfig() FileConfig {
return FileConfig{
ConfigVersion: CurrentConfigVersion,
Server: ServerConfig{
- Port: "9867",
+ Port: defaultPort,
Bind: "127.0.0.1",
StateDir: userConfigDir(),
},
diff --git a/internal/config/config_load.go b/internal/config/config_load.go
index c17cf541..d9e9f001 100644
--- a/internal/config/config_load.go
+++ b/internal/config/config_load.go
@@ -13,7 +13,7 @@ func Load() *RuntimeConfig {
cfg := &RuntimeConfig{
// Server defaults
Bind: "127.0.0.1",
- Port: "9867",
+ Port: defaultPort,
InstancePortStart: 9868,
InstancePortEnd: 9968,
Token: os.Getenv("PINCHTAB_TOKEN"),
@@ -170,6 +170,11 @@ func Load() *RuntimeConfig {
applyFileConfig(cfg, fc)
finalizeProfileConfig(cfg)
+ if cfg.Port == "" {
+ slog.Error("server port is not configured — set server.port in config.json")
+ os.Exit(1)
+ }
+
return cfg
}
diff --git a/internal/config/config_types.go b/internal/config/config_types.go
index 956dd274..8983a484 100644
--- a/internal/config/config_types.go
+++ b/internal/config/config_types.go
@@ -2,6 +2,9 @@ package config
import "time"
+const defaultPort = "9867"
+
+
// RuntimeConfig holds all runtime settings used throughout the application.
// This is the single source of truth for configuration at runtime.
type RuntimeConfig struct {
diff --git a/internal/handlers/health_tabs.go b/internal/handlers/health_tabs.go
index e069e672..25197941 100644
--- a/internal/handlers/health_tabs.go
+++ b/internal/handlers/health_tabs.go
@@ -167,7 +167,7 @@ func (h *Handlers) HandleTabs(w http.ResponseWriter, r *http.Request) {
tabs := make([]map[string]any, 0, len(targets))
appendTab := func(t *target.Info) {
// Skip the initial about:blank tab that Chrome creates on launch
- if bridge.IsTransientURL(t.URL) {
+ if bridge.IsTransientURL(t.URL, h.Config.Port) {
return
}
tabID := string(t.TargetID)
diff --git a/internal/orchestrator/proxy.go b/internal/orchestrator/proxy.go
index 87c3536c..a46ddb9e 100644
--- a/internal/orchestrator/proxy.go
+++ b/internal/orchestrator/proxy.go
@@ -1,6 +1,7 @@
package orchestrator
import (
+ "encoding/json"
"fmt"
"net/http"
"net/url"
@@ -133,6 +134,7 @@ func (o *Orchestrator) proxyToURL(w http.ResponseWriter, r *http.Request, target
o.applyInstanceAuth(req, inst)
}
},
+ OnResponse: enrichActivityFromResponse,
})
}
@@ -323,6 +325,29 @@ func classifyLaunchError(err error) int {
return 500 // Internal Server Error
}
+// enrichActivityFromResponse extracts tabId and url from the bridge JSON
+// response and enriches the activity event on the original request so the
+// dashboard can link the event to the correct tab.
+func enrichActivityFromResponse(origReq *http.Request, body []byte) {
+ var resp struct {
+ TabID string `json:"tabId"`
+ URL string `json:"url"`
+ }
+ if json.Unmarshal(body, &resp) != nil {
+ return
+ }
+ update := activity.Update{}
+ if resp.TabID != "" {
+ update.TabID = resp.TabID
+ }
+ if resp.URL != "" {
+ update.URL = resp.URL
+ }
+ if update.TabID != "" || update.URL != "" {
+ activity.EnrichRequest(origReq, update)
+ }
+}
+
func (o *Orchestrator) singleRunningInstance() *InstanceInternal {
o.mu.RLock()
defer o.mu.RUnlock()
diff --git a/internal/proxy/proxy.go b/internal/proxy/proxy.go
index 284a9a91..5fb4d431 100644
--- a/internal/proxy/proxy.go
+++ b/internal/proxy/proxy.go
@@ -6,6 +6,7 @@ package proxy
import (
"fmt"
+ "io"
"net/http"
"net/url"
"strings"
@@ -25,6 +26,10 @@ type Options struct {
Client *http.Client
AllowedURL func(*url.URL) bool
RewriteRequest func(*http.Request)
+ // OnResponse is called with the upstream response body for non-streaming
+ // responses (Content-Type application/json, body ≤ 64 KB). The original
+ // request is passed so callers can enrich activity context.
+ OnResponse func(origReq *http.Request, body []byte)
}
var hopByHopHeaders = map[string]struct{}{
@@ -93,6 +98,18 @@ func Forward(w http.ResponseWriter, r *http.Request, targetURL *url.URL, opts Op
defer func() { _ = resp.Body.Close() }()
copyHeaders(w.Header(), resp.Header)
+
+ // For small JSON responses, buffer to allow OnResponse to inspect the body.
+ if opts.OnResponse != nil && isSmallJSON(resp) {
+ body, readErr := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
+ w.WriteHeader(resp.StatusCode)
+ _, _ = w.Write(body)
+ if readErr == nil {
+ opts.OnResponse(r, body)
+ }
+ return
+ }
+
w.WriteHeader(resp.StatusCode)
buf := make([]byte, 32*1024)
@@ -110,6 +127,14 @@ func Forward(w http.ResponseWriter, r *http.Request, targetURL *url.URL, opts Op
}
}
+func isSmallJSON(resp *http.Response) bool {
+ ct := resp.Header.Get("Content-Type")
+ if !strings.HasPrefix(ct, "application/json") {
+ return false
+ }
+ return resp.ContentLength >= 0 && resp.ContentLength <= 64<<10
+}
+
// HTTP forwards an HTTP request to targetURL, streaming the response
// back to w. If the request is a WebSocket upgrade, it delegates to
// handlers.ProxyWebSocket instead.
diff --git a/internal/server/server.go b/internal/server/server.go
index 5f9a1dc1..e375e597 100644
--- a/internal/server/server.go
+++ b/internal/server/server.go
@@ -39,9 +39,6 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {
bridge.CleanupOrphanedChromeProcesses(cfg.ProfileDir)
dashPort := cfg.Port
- if dashPort == "" {
- dashPort = "9870"
- }
startedAt := time.Now()
profilesDir := cfg.ProfilesBaseDir