High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix dashboard auth recovery and add pdev dashboard formatting
Luigi Agosti527181d150f5
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 5529b983..dc615da8 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -33,6 +33,7 @@ This significantly speeds up the merge process. Thank you! π```bash./pdev doctor # setup environment and hooks./pdev check # format, vet, build, lint+./pdev format dashboard./pdev test # unit + integration + system./pdev test unit./pdev test integration@@ -57,4 +58,9 @@ go test -tags integration ./tests/integration -v'## Hooks-`./pdev doctor` installs the git hooks. They enforce formatting and checks before commit.+`./pdev doctor` offers to install the git hooks. They enforce formatting and checks before commit.+You can also install them directly with:++```bash+./scripts/install-hooks.sh+```diff --git a/TESTING.md b/TESTING.mdindex 5d395956..7a8d3508 100644--- a/TESTING.md+++ b/TESTING.md@@ -13,7 +13,7 @@ The `pdev` developer toolkit is the easiest way to run checks and tests:./pdev check # All checks (format, vet, build, lint)./pdev check go # Go checks only./pdev check security # Gosec security scan-./pdev hooks # Install git hooks (pre-commit)+./pdev format dashboard # Run Prettier on dashboard sources./pdev doctor # Setup dev environment```diff --git a/dashboard/src/App.tsx b/dashboard/src/App.tsxindex 09dc7b5d..61262f55 100644--- a/dashboard/src/App.tsx+++ b/dashboard/src/App.tsx@@ -1,4 +1,4 @@-import { useEffect } from "react";+import { useEffect, useState } from "react";import {BrowserRouter,Routes,@@ -17,6 +17,9 @@ import {getStoredAuthToken,} from "./services/auth";+type AuthMode = "probing" | "required" | "open" | "unreachable";+const AUTH_RETRY_DELAYS_MS = [1000, 2000, 4000, 8000, 15000] as const;+function AppContent() {const {setInstances,@@ -30,15 +33,79 @@ function AppContent() {const navigate = useNavigate();const memoryMetricsEnabled = settings.monitoring?.memoryMetrics ?? false;const authToken = getStoredAuthToken();- const authenticated = authToken !== "";+ const hasStoredToken = authToken !== "";+ const [authMode, setAuthMode] = useState<AuthMode>(+ hasStoredToken ? "required" : "probing",+ );+ const [authRetryCount, setAuthRetryCount] = useState(0);+ const dashboardAccessible = hasStoredToken || authMode === "open";+ const loginRequired = !hasStoredToken && authMode === "required";useEffect(() => {document.documentElement.setAttribute("data-site-mode", "agent");}, []);+ useEffect(() => {+ if (hasStoredToken) {+ setAuthMode("required");+ setAuthRetryCount(0);+ return;+ }++ if (authMode === "open" || authMode === "unreachable") {+ return;+ }++ let cancelled = false;+ api+ .probeBackendAuth()+ .then((result) => {+ if (cancelled) {+ return;+ }+ setAuthMode(result.requiresAuth ? "required" : "open");+ setAuthRetryCount(0);+ if (result.health) {+ setServerInfo(result.health);+ }+ })+ .catch((error) => {+ if (cancelled) {+ return;+ }+ console.error("Failed to probe backend auth", error);+ setAuthMode("unreachable");+ });++ return () => {+ cancelled = true;+ };+ }, [authMode, hasStoredToken, setServerInfo]);++ useEffect(() => {+ if (+ hasStoredToken ||+ authMode !== "unreachable" ||+ authRetryCount >= AUTH_RETRY_DELAYS_MS.length+ ) {+ return;+ }++ const timer = window.setTimeout(() => {+ setAuthRetryCount((count) => count + 1);+ setAuthMode("probing");+ }, AUTH_RETRY_DELAYS_MS[authRetryCount]);++ return () => {+ window.clearTimeout(timer);+ };+ }, [authMode, authRetryCount, hasStoredToken]);+useEffect(() => {const handleAuthRequired = () => {clearStoredAuthToken();+ setAuthMode("required");+ setAuthRetryCount(0);navigate("/login", {replace: true,state: { from: location.pathname },@@ -50,17 +117,17 @@ function AppContent() {}, [location.pathname, navigate]);useEffect(() => {- if (!authenticated && location.pathname !== "/login") {+ if (loginRequired && location.pathname !== "/login") {navigate("/login", {replace: true,state: { from: location.pathname },});}- }, [authenticated, location.pathname, navigate]);+ }, [location.pathname, loginRequired, navigate]);// Initial loaduseEffect(() => {- if (!authenticated) {+ if (!dashboardAccessible) {return;}const load = async () => {@@ -78,11 +145,11 @@ function AppContent() {}};load();- }, [authenticated, setInstances, setProfiles, setServerInfo]);+ }, [dashboardAccessible, setInstances, setProfiles, setServerInfo]);// Subscribe to SSE eventsuseEffect(() => {- if (!authenticated) {+ if (!dashboardAccessible) {return;}const unsubscribe = api.subscribeToEvents(@@ -107,7 +174,7 @@ function AppContent() {return unsubscribe;}, [- authenticated,+ dashboardAccessible,applyMonitoringSnapshot,memoryMetricsEnabled,setAgents,@@ -115,7 +182,58 @@ function AppContent() {setProfiles,]);- if (!authenticated) {+ if (!hasStoredToken && authMode === "probing") {+ return (+ <div className="flex min-h-screen items-center justify-center bg-bg-app px-4">+ <div className="rounded-sm border border-border-subtle bg-black/10 px-4 py-3 text-sm text-text-muted">+ Checking server authentication...+ </div>+ </div>+ );+ }++ if (!hasStoredToken && authMode === "unreachable") {+ const nextRetryDelay =+ authRetryCount < AUTH_RETRY_DELAYS_MS.length+ ? AUTH_RETRY_DELAYS_MS[authRetryCount]+ : null;++ return (+ <div className="flex min-h-screen items-center justify-center bg-bg-app px-4">+ <div className="max-w-md space-y-3 rounded-sm border border-border-subtle bg-black/10 px-4 py-3 text-sm text-text-muted">+ <div>+ PinchTab is restarting or unreachable.+ {nextRetryDelay !== null+ ? ` Retrying in ${Math.ceil(nextRetryDelay / 1000)}s...`+ : " Automatic retries stopped."}+ </div>+ {nextRetryDelay === null && (+ <div className="flex justify-end gap-2">+ <button+ type="button"+ className="rounded-sm border border-border-subtle px-3 py-2 text-sm text-text-primary transition-all duration-150 hover:border-primary/30 hover:bg-bg-elevated"+ onClick={() => {+ setAuthRetryCount(0);+ setAuthMode("probing");+ }}+ >+ Retry now+ </button>+ <button+ type="button"+ className="rounded-sm border border-border-subtle px-3 py-2 text-sm text-text-primary transition-all duration-150 hover:border-primary/30 hover:bg-bg-elevated"+ onClick={() => window.location.reload()}+ >+ Refresh+ </button>+ </div>+ )}+ </div>+ </div>+ );+ }++ if (loginRequired) {return (<Routes><Route path="/login" element={<LoginPage />} />diff --git a/dashboard/src/components/molecules/NavBar.tsx b/dashboard/src/components/molecules/NavBar.tsxindex 244b8b54..a7bb8968 100644--- a/dashboard/src/components/molecules/NavBar.tsx+++ b/dashboard/src/components/molecules/NavBar.tsx@@ -1,6 +1,7 @@import { useCallback, useEffect, useRef, useState } from "react";import { NavLink, useLocation, useNavigate } from "react-router-dom";import { useAppStore } from "../../stores/useAppStore";+import { clearStoredAuthToken, getStoredAuthToken } from "../../services/auth";import "./NavBar.css";interface Tab {@@ -26,6 +27,7 @@ export default function NavBar({ onRefresh }: NavBarProps) {const tabsRef = useRef<HTMLElement>(null);const location = useLocation();const navigate = useNavigate();+ const hasStoredToken = getStoredAuthToken() !== "";// Close mobile menu on route changeuseEffect(() => {@@ -39,6 +41,12 @@ export default function NavBar({ onRefresh }: NavBarProps) {setTimeout(() => setRefreshing(false), 800);}, [onRefresh, refreshing]);+ const handleLogout = useCallback(() => {+ clearStoredAuthToken();+ setMobileMenuOpen(false);+ navigate("/login", { replace: true });+ }, [navigate]);+useEffect(() => {const handler = (e: KeyboardEvent) => {if (!e.metaKey && !e.ctrlKey) return;@@ -114,6 +122,15 @@ export default function NavBar({ onRefresh }: NavBarProps) {</span></div>)}+ {hasStoredToken && (+ <button+ type="button"+ className="mr-2 rounded-sm border border-transparent px-3 py-1.5 text-xs font-medium uppercase tracking-[0.08em] text-text-muted transition-all duration-150 hover:border-border-subtle hover:bg-bg-hover hover:text-text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/30"+ onClick={handleLogout}+ >+ Logout+ </button>+ )}{onRefresh && (<buttonclassName={`navbar-icon-btn flex h-8 w-8 cursor-pointer items-center justify-center rounded-sm border border-transparent bg-transparent text-base text-text-muted transition-all duration-150 hover:border-border-subtle hover:bg-bg-hover hover:text-text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/30 ${@@ -154,6 +171,15 @@ export default function NavBar({ onRefresh }: NavBarProps) {{tab.label}</NavLink>))}+ {hasStoredToken && (+ <button+ type="button"+ className="border-t border-border-subtle px-4 py-3 text-left text-sm font-medium text-text-secondary transition-colors duration-150 hover:bg-bg-elevated hover:text-text-primary"+ onClick={handleLogout}+ >+ Logout+ </button>+ )}</nav>)}</header>diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.tsindex 2e05b361..de29a23b 100644--- a/dashboard/src/services/api.ts+++ b/dashboard/src/services/api.ts@@ -152,6 +152,38 @@ export async function fetchHealth(): Promise<DashboardServerInfo> {);}+export async function probeBackendAuth(): Promise<{+ requiresAuth: boolean;+ health?: DashboardServerInfo;+}> {+ const res = await fetch(BASE + "/health");+ if (res.ok) {+ return {+ requiresAuth: false,+ health: normalizeDashboardServerInfo(+ (await res.json()) as DashboardServerInfo,+ ),+ };+ }++ const err = (await res+ .json()+ .catch(() => ({ code: "", error: res.statusText }))) as {+ code?: string;+ error?: string;+ };+ if (+ res.status === 401 &&+ (err.code === "missing_token" ||+ err.code === "bad_token" ||+ err.error === "unauthorized")+ ) {+ return { requiresAuth: true };+ }++ throw new Error(err.error || "Request failed");+}+export async function verifyBackendToken(token: string,): Promise<DashboardServerInfo> {diff --git a/docs/guides/contributing.md b/docs/guides/contributing.mdindex c67fa7e9..a3500dd3 100644--- a/docs/guides/contributing.md+++ b/docs/guides/contributing.md@@ -259,13 +259,14 @@ All dev scripts are accessible through `./pdev`:| `check dashboard` | Dashboard checks only || `check security` | Gosec security scan || `check docs` | Validate docs JSON |+| `format dashboard` | Run Prettier on dashboard sources || `test` | All tests (unit + integration + system) || `test unit` | Unit tests only || `test integration` | Integration tests only || `test system` | System tests only || `build` | Build & run (default) |+| `run` | Run the application || `doctor` | Setup dev environment |-| `hooks` | Install git hooks |For the fancy interactive picker, install [gum](https://github.com/charmbracelet/gum): `brew install gum`@@ -278,6 +279,7 @@ pdev() { if [ -x "./pdev" ]; then ./pdev "$@"; else echo "pdev not found in curr```bash./pdev check # Full non-test checks (recommended)+./pdev format dashboard # Fix dashboard formattinggofmt -w . # Format codegolangci-lint run # Lint./pdev doctor # Verify environment@@ -292,7 +294,7 @@ Git hooks are installed by `./pdev doctor` (or `./scripts/install-hooks.sh`). ThTo manually reinstall hooks:```bash-./pdev hooks+./scripts/install-hooks.sh```### Development Workflow@@ -372,7 +374,7 @@ pinchtab --version**First step:** Run doctor to verify your setup:```bash-./doctor.sh+./pdev doctor```This will tell you exactly what's missing or misconfigured.@@ -388,7 +390,7 @@ This will tell you exactly what's missing or misconfigured.- Or: `go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest`**"Git hooks not running on commit"**-- Run: `./pdev hooks`+- Run: `./scripts/install-hooks.sh`- Or: `./pdev doctor` (prompts to install)**"Chrome not found"**diff --git a/pdev b/pdevindex 17cd14f0..6a74a7f2 100755--- a/pdev+++ b/pdev@@ -17,18 +17,19 @@ NC=$'\033[0m'# ββ Commands βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# name:emoji:descriptionCOMMANDS=(- "check:π§ͺ:All checks (Go + Dashboard)"- " check go:π§ͺ:Go only"- " check dashboard:π§ͺ:Dashboard only"- " check security:π§ͺ:Gosec security scan"- " check docs:π§ͺ:Validate docs JSON"- "test:π¬:All tests (unit + integration + system)"- " test unit:π¬:Unit tests only"- " test integration:π¬:Integration tests only"- " test system:π¬:System tests only"- "build:π:Build & run (default)"+ "build:π:Build & run"+ "run:π:Run the application"+ "check:π§ͺ:All checks"+ "test:π¬:All tests"+ " unit:π¬:Unit tests only"+ " integration:π¬:Integration tests only"+ " system:π¬:System tests only""doctor:π©Ί:Setup dev environment"- "hooks:πͺ:Install git hooks"+ "check go:π§ͺ:Go only"+ "check dashboard:π§ͺ:Dashboard only"+ "check security:π§ͺ:Gosec security scan"+ "check docs:π§ͺ:Validate docs JSON"+ "format dashboard:π¨:Run Prettier on dashboard sources")# ββ Helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@@ -90,22 +91,27 @@ run_command() {echo ""exec bash scripts/check-docs-json.sh;;+ "format dashboard")+ echo " ${ACCENT}${BOLD}π¨ Dashboard formatting${NC}"+ echo ""+ exec bash -lc 'cd dashboard && if command -v bun >/dev/null 2>&1; then bun run format; else npx prettier --write '"'"'src/**/*.{ts,tsx,css}'"'"'; fi'+ ;;"test")echo " ${ACCENT}${BOLD}π¬ All tests${NC}"echo ""exec bash scripts/test.sh all;;- "test unit")+ "unit")echo " ${ACCENT}${BOLD}π¬ Unit tests${NC}"echo ""exec bash scripts/test.sh unit;;- "test integration")+ "integration")echo " ${ACCENT}${BOLD}π¬ Integration tests${NC}"echo ""exec bash scripts/test.sh integration;;- "test system")+ "system")echo " ${ACCENT}${BOLD}π¬ System tests${NC}"echo ""exec bash scripts/test.sh system@@ -205,6 +211,13 @@ if [ $# -gt 0 ]; thenrun_command "test"fi;;+ format)+ if [ $# -gt 1 ]; then+ run_command "format $2"+ else+ run_command "format"+ fi+ ;;*) run_command "$1" ;;esacfi