High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
feat: headed mode
Luigi Agostica415a8162ee
diff --git a/cmd_dashboard.go b/cmd_dashboard.goindex 6afcaebb..a9050e7e 100644--- a/cmd_dashboard.go+++ b/cmd_dashboard.go@@ -51,15 +51,7 @@ func runDashboard() {for _, ep := range proxyEndpoints {endpoint := epmux.HandleFunc(endpoint, func(w http.ResponseWriter, r *http.Request) {-- instances := orchestrator.List()- var target string- for _, inst := range instances {- if inst.Status == "running" {- target = inst.URL- break- }- }+ target := orchestrator.FirstRunningURL()if target == "" {jsonErr(w, 503, fmt.Errorf("no running instances — launch one from the Profiles tab"))return@@ -89,19 +81,21 @@ func runDashboard() {srv := &http.Server{Addr: ":" + dashPort, Handler: handler}- defaultProfile := os.Getenv("PINCHTAB_DEFAULT_PROFILE")- defaultPort := os.Getenv("PINCHTAB_DEFAULT_PORT")- if defaultPort == "" {- defaultPort = "9867"- }- if defaultProfile == "" {- defaultProfile = "default"- }+ autoLaunch := strings.EqualFold(os.Getenv("PINCHTAB_AUTO_LAUNCH"), "1") ||+ strings.EqualFold(os.Getenv("PINCHTAB_AUTO_LAUNCH"), "true") ||+ strings.EqualFold(os.Getenv("PINCHTAB_AUTO_LAUNCH"), "yes")+ if autoLaunch {+ defaultProfile := os.Getenv("PINCHTAB_DEFAULT_PROFILE")+ defaultPort := os.Getenv("PINCHTAB_DEFAULT_PORT")+ if defaultPort == "" {+ defaultPort = "9867"+ }+ if defaultProfile == "" {+ defaultProfile = "default"+ }- os.MkdirAll(filepath.Join(profilesDir, defaultProfile, "Default"), 0755)+ os.MkdirAll(filepath.Join(profilesDir, defaultProfile, "Default"), 0755)- autoLaunch := os.Getenv("PINCHTAB_NO_AUTO_LAUNCH") == ""- if autoLaunch {go func() {time.Sleep(500 * time.Millisecond)@@ -113,6 +107,8 @@ func runDashboard() {}slog.Info("auto-launched default instance", "id", inst.ID, "port", defaultPort, "headless", headlessDefault)}()+ } else {+ slog.Info("dashboard auto-launch disabled", "hint", "set PINCHTAB_AUTO_LAUNCH=1 to enable")}shutdownOnce := &sync.Once{}@@ -133,10 +129,14 @@ func runDashboard() {})go func() {- sig := make(chan os.Signal, 1)+ sig := make(chan os.Signal, 2)signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)<-sig- doShutdown()+ go doShutdown()+ <-sig+ slog.Warn("force shutdown requested")+ orchestrator.ForceShutdown()+ os.Exit(130)}()slog.Info("dashboard ready", "url", fmt.Sprintf("http://localhost:%s/dashboard", dashPort))diff --git a/dashboard.go b/dashboard.goindex b1b44a13..01b0d58c 100644--- a/dashboard.go+++ b/dashboard.go@@ -159,12 +159,13 @@ func (d *Dashboard) GetAgents() []AgentActivity {}func (d *Dashboard) RegisterHandlers(mux *http.ServeMux) {- mux.HandleFunc("GET /dashboard", d.handleDashboardUI)+ mux.Handle("GET /dashboard", d.withNoCache(http.HandlerFunc(d.handleDashboardUI)))mux.HandleFunc("GET /dashboard/agents", d.handleAgents)mux.HandleFunc("GET /dashboard/events", d.handleSSE)sub, _ := fs.Sub(dashboardFS, "dashboard")- mux.Handle("GET /dashboard/", http.StripPrefix("/dashboard/", http.FileServer(http.FS(sub))))+ static := http.StripPrefix("/dashboard/", http.FileServer(http.FS(sub)))+ mux.Handle("GET /dashboard/", d.withNoCache(static))}func (d *Dashboard) handleAgents(w http.ResponseWriter, r *http.Request) {@@ -212,10 +213,22 @@ func (d *Dashboard) handleSSE(w http.ResponseWriter, r *http.Request) {func (d *Dashboard) handleDashboardUI(w http.ResponseWriter, r *http.Request) {w.Header().Set("Content-Type", "text/html")+ w.Header().Set("Cache-Control", "no-store")+ w.Header().Set("Pragma", "no-cache")+ w.Header().Set("Expires", "0")data, _ := dashboardFS.ReadFile("dashboard/dashboard.html")w.Write(data)}+func (d *Dashboard) withNoCache(next http.Handler) http.Handler {+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Cache-Control", "no-store")+ w.Header().Set("Pragma", "no-cache")+ w.Header().Set("Expires", "0")+ next.ServeHTTP(w, r)+ })+}+type EventObserver func(evt AgentEvent)func extractAgentID(r *http.Request) string {diff --git a/dashboard/agents.css b/dashboard/agents.cssindex 66ac157b..bca169bc 100644--- a/dashboard/agents.css+++ b/dashboard/agents.css@@ -34,10 +34,11 @@padding: 2px 8px;border-radius: 10px;font-weight: 600;+ border: 1px solid transparent;}- .agent-status.active { background: var(--success-bg); color: var(--success); }- .agent-status.idle { background: var(--warning-bg); color: var(--warning); }- .agent-status.disconnected { background: var(--inactive-bg); color: var(--text-dim); }+ .agent-status.active { background: var(--success-bg); color: var(--success); border-color: rgba(22, 163, 74, 0.34); }+ .agent-status.idle { background: var(--idle-bg); color: var(--idle); border-color: rgba(100, 116, 139, 0.35); }+ .agent-status.disconnected { background: var(--inactive-bg); color: var(--text-dim); border-color: rgba(100, 116, 139, 0.32); }.agent-card .agent-url {font-size: 12px;color: var(--text-muted);@@ -99,7 +100,7 @@@keyframes fadeIn { from { opacity: 0; transform: translateY(-4px); } to { opacity: 1; } }.event-row .time { color: var(--text-faint); font-size: 11px; }.event-row .agent {- color: var(--primary);+ color: var(--text-bright);font-weight: 600;white-space: nowrap;overflow: hidden;diff --git a/dashboard/agents.js b/dashboard/agents.jsindex 1459aa14..a92b7f54 100644--- a/dashboard/agents.js+++ b/dashboard/agents.js@@ -80,7 +80,7 @@ function renderFeed() {}if (filtered.length === 0) {- el.innerHTML = '<div class="empty-state"><div class="crab">🦀</div>No matching events.</div>';+ el.innerHTML = '<div class="empty-state"><img src="/dashboard/pinchtab-headed-192.png" alt="" class="empty-icon">No matching events.</div>';return;}diff --git a/dashboard/app.js b/dashboard/app.jsindex 2ce4a2bc..44fe6142 100644--- a/dashboard/app.js+++ b/dashboard/app.js@@ -4,13 +4,12 @@ let profilesInterval = null;function switchView(view) {document.querySelectorAll('.view-btn').forEach(b => b.classList.remove('active'));- document.querySelector('[data-view="' + view + '"]').classList.add('active');+ const btn = document.querySelector('[data-view="' + view + '"]');+ if (btn) btn.classList.add('active');document.getElementById('feed-view').style.display = view === 'feed' ? 'flex' : 'none';document.getElementById('profiles-view').style.display = view === 'profiles' ? 'flex' : 'none';- document.getElementById('live-view').style.display = view === 'live' ? 'flex' : 'none';document.getElementById('settings-view').style.display = view === 'settings' ? 'block' : 'none';- if (view === 'live') refreshTabs();if (view === 'profiles') loadProfiles();if (view === 'settings') loadSettings();@@ -25,3 +24,4 @@ function openInstanceDirect(port) {}connect();+switchView('profiles');diff --git a/dashboard/base.css b/dashboard/base.cssindex 7c59931e..9aee01bb 100644--- a/dashboard/base.css+++ b/dashboard/base.css@@ -1,39 +1,34 @@:root {-- --primary: #f5c542;- --primary-dark: #0a0a0a;--- --bg: #0a0a0a;- --bg-raised: #111;- --bg-card: #151515;- --bg-input: #0a0a0a;- --bg-hover: #1a1a1a;- --bg-subtle: #0d0d0d;--- --border: #222;- --border-light: #333;- --border-active: #444;--- --text: #e0e0e0;- --text-muted: #888;- --text-dim: #666;- --text-faint: #555;- --text-subtle: #aaa;- --text-bright: #ccc;--- --success: #4ade80;- --success-bg: #064e3b;- --warning: #fbbf24;- --warning-bg: #422006;- --danger: #f87171;- --danger-bg: #3a1a1a;- --inactive-bg: #1c1917;--+ --primary: #16a34a;+ --primary-hover: #15803d;+ --primary-active: #166534;+ --primary-soft: rgba(22, 163, 74, 0.14);+ --primary-dark: #0b1220;+ --bg: #0b1220;+ --bg-raised: #111827;+ --bg-card: #111827;+ --bg-input: #0b1220;+ --bg-hover: #162235;+ --bg-subtle: #0f172a;+ --border: #1f2a44;+ --border-light: #2d3a5c;+ --border-active: #3c4d73;+ --text: #e2e8f0;+ --text-muted: #94a3b8;+ --text-dim: #64748b;+ --text-faint: #475569;+ --text-subtle: #cbd5e1;+ --text-bright: #f1f5f9;+ --success: #16a34a;+ --success-bg: rgba(22, 163, 74, 0.15);+ --warning: #f59e0b;+ --warning-bg: rgba(245, 158, 11, 0.18);+ --danger: #dc2626;+ --danger-hover: #b91c1c;+ --danger-bg: rgba(220, 38, 38, 0.16);+ --inactive-bg: rgba(100, 116, 139, 0.22);+ --idle: #64748b;+ --idle-bg: rgba(100, 116, 139, 0.22);--font: 'SF Mono', 'Fira Code', monospace;}@@ -46,13 +41,23 @@}header {background: var(--bg-raised);- border-bottom: 2px solid var(--primary);+ border-bottom: 1px solid var(--border);padding: 16px 24px;display: flex;align-items: center;gap: 16px;}- header h1 { font-size: 20px; color: var(--primary); }+ header h1 { font-size: 20px; color: var(--text-bright); }+ .app-brand {+ display: flex;+ align-items: center;+ gap: 10px;+ }+ .app-brand-icon {+ width: 28px;+ height: 28px;+ display: block;+ }header .status { font-size: 13px; color: var(--text-muted); }header .status .dot {display: inline-block;@@ -81,7 +86,11 @@cursor: pointer;font-family: inherit;}- .view-btn.active { border-color: var(--primary); color: var(--primary); }+ .view-btn.active {+ background: transparent;+ border-color: var(--primary);+ color: var(--text-bright);+ }.empty-state {text-align: center;@@ -90,6 +99,13 @@font-size: 14px;}.empty-state .crab { font-size: 48px; margin-bottom: 12px; }+ .empty-state .empty-icon {+ width: 52px;+ height: 52px;+ margin: 0 auto 12px;+ display: block;+ opacity: 0.92;+ }.modal-overlay {@@ -110,7 +126,10 @@width: 420px;max-width: 90vw;}- .modal h3 { color: var(--primary); margin-bottom: 16px; }+ .modal.modal-wide {+ width: min(1100px, 95vw);+ }+ .modal h3 { color: var(--text-bright); margin-bottom: 16px; }.modal input, .modal select {width: 100%;background: var(--bg);@@ -129,12 +148,20 @@border: none;padding: 8px 18px;border-radius: 6px;- font-weight: bold;+ font-weight: 600;+ font-size: 12px;+ letter-spacing: 0.06em;+ text-transform: uppercase;cursor: pointer;font-family: inherit;}+ .modal button:hover {+ background: var(--primary-hover);+ }.modal button.secondary { background: var(--border-light); color: var(--text); }+ .modal button.secondary:hover { background: var(--border-active); }.modal button.danger { background: var(--danger); color: #fff; }+ .modal button.danger:hover { background: var(--danger-hover); }.spinner {diff --git a/dashboard/dashboard.html b/dashboard/dashboard.htmlindex ab9c7b69..51b12074 100644--- a/dashboard/dashboard.html+++ b/dashboard/dashboard.html@@ -13,30 +13,23 @@</head><body><header>- <h1>🦀 Pinchtab</h1>+ <h1 class="app-brand">+ <img src="/dashboard/pinchtab-headed-192.png" alt="Pinchtab" class="app-brand-icon">+ <span>Pinchtab</span>+ </h1><div class="status"><span class="dot"></span>Live</div><div class="view-toggle">- <button class="view-btn active" data-view="feed" onclick="switchView('feed')">🤖 Agents</button>- <button class="view-btn" data-view="profiles" onclick="switchView('profiles')">📁 Profiles</button>- <button class="view-btn" data-view="live" onclick="switchView('live')">📺 Live</button>- <button class="view-btn" data-view="settings" onclick="switchView('settings')">⚙️</button>+ <button class="view-btn active" data-view="profiles" onclick="switchView('profiles')">Profiles</button>+ <button class="view-btn" data-view="feed" onclick="switchView('feed')">Agents</button>+ <button class="view-btn" data-view="settings" onclick="switchView('settings')">Settings</button></div></header>-<div id="live-view" class="live-view" style="display:none">- <div class="live-toolbar">- <button onclick="refreshTabs()" style="background:#333;color:#e0e0e0;border:1px solid #444;padding:6px 14px;border-radius:4px;cursor:pointer;font-family:inherit;font-size:12px">↻ Refresh Tabs</button>- <span id="live-tab-count" style="color:#666;font-size:12px;margin-left:12px"></span>- </div>- <div id="screencast-grid" class="screencast-grid"></div>-</div>---<div id="profiles-view" class="instances-view" style="display:none">+<div id="profiles-view" class="instances-view" style="display:flex"><div class="inst-toolbar">- <button onclick="showCreateProfileModal()" class="launch-btn">+ New Profile</button>- <button onclick="loadProfiles()" class="refresh-btn">↻ Refresh</button>+ <button onclick="showCreateProfileModal()" class="launch-btn">New Profile</button>+ <button onclick="loadProfiles()" class="refresh-btn">Refresh</button></div><div id="profiles-grid" class="instances-grid"><div class="empty-state"><div class="crab">🦀</div>No profiles yet.<br>Click <b>+ New Profile</b> to create one.</div>@@ -73,13 +66,16 @@<div class="modal-overlay" id="launch-modal"><div class="modal">- <h3>🚀 Launch Profile</h3>+ <h3>🖥️ Launch Profile</h3><input id="launch-name" type="hidden" />+ <input id="launch-profile-path" type="hidden" /><label style="color:#888;font-size:12px;display:block;margin-bottom:4px">Port</label><input id="launch-port" placeholder="e.g. 9868" />- <label style="color:#888;font-size:12px;display:flex;align-items:center;gap:8px;margin-bottom:12px">- <input type="checkbox" id="launch-headless" checked /> Headless- </label>+ <label style="color:#888;font-size:12px;display:block;margin-bottom:4px">Direct launch command (backup)</label>+ <textarea id="launch-command" class="launch-command" readonly></textarea>+ <div class="btn-row" style="justify-content:flex-start;margin-top:-2px;margin-bottom:8px">+ <button class="secondary" onclick="copyLaunchCommand()">Copy Command</button>+ </div><div class="btn-row"><button class="secondary" onclick="closeLaunchModal()">Cancel</button><button onclick="doLaunch()">Launch</button>@@ -164,18 +160,21 @@</div><div class="settings-actions">- <button onclick="applySettings()" class="launch-btn">Apply & Reconnect Live</button>+ <button onclick="applySettings()" class="launch-btn">Apply Settings</button><button onclick="loadSettings()" class="refresh-btn">Reset</button></div></div></div>-<div id="feed-view" class="container">+<div id="feed-view" class="container" style="display:none"><div class="agents-panel"><h2>Agents</h2><div id="agents-list">- <div class="empty-state"><div class="crab">🦀</div>No agents connected yet.<br>Make an API call with <code>X-Agent-Id</code> header.</div>+ <div class="empty-state">+ <img src="/dashboard/pinchtab-headed-192.png" alt="" class="empty-icon">+ No agents connected yet.<br>Make an API call with <code>X-Agent-Id</code> header.+ </div></div></div>@@ -190,13 +189,14 @@</div></div><div id="feed-list" class="feed-list">- <div class="empty-state"><div class="crab">🦀</div>Waiting for events...</div>+ <div class="empty-state">+ <img src="/dashboard/pinchtab-headed-192.png" alt="" class="empty-icon">+ Waiting for events...+ </div></div></div></div>-</div>-<div class="modal-overlay" id="modal"><div class="modal">@@ -213,4 +213,4 @@<script src="/dashboard/app.js"></script></body>-</html>\ No newline at end of file+</html>diff --git a/dashboard/pinchtab-headed-192.png b/dashboard/pinchtab-headed-192.pngnew file mode 100644index 00000000..df0c4290Binary files /dev/null and b/dashboard/pinchtab-headed-192.png differdiff --git a/dashboard/profiles.css b/dashboard/profiles.cssindex 5b45dc69..bf949575 100644--- a/dashboard/profiles.css+++ b/dashboard/profiles.css@@ -31,26 +31,33 @@gap: 8px;}.launch-btn {- background: var(--primary);- color: var(--primary-dark);- border: none;+ background: transparent;+ color: var(--primary);+ border: 1px solid var(--primary);padding: 8px 18px;border-radius: 6px;- font-weight: bold;+ font-weight: 600;cursor: pointer;font-family: inherit;- font-size: 13px;+ font-size: 12px;+ letter-spacing: 0.06em;+ text-transform: uppercase;}+ .launch-btn:hover { background: var(--primary-soft); }.refresh-btn {- background: #333;- color: var(--text);- border: 1px solid var(--border-active);+ background: #1e293b;+ color: #cbd5e1;+ border: 1px solid #334155;padding: 8px 14px;border-radius: 6px;cursor: pointer;font-family: inherit;- font-size: 13px;+ font-size: 12px;+ font-weight: 600;+ letter-spacing: 0.06em;+ text-transform: uppercase;}+ .refresh-btn:hover { background: #243244; }.instances-grid {flex: 1;display: grid;@@ -73,17 +80,19 @@align-items: center;border-bottom: 1px solid var(--bg-hover);}- .inst-card .inst-name { font-weight: bold; font-size: 16px; color: var(--primary); }+ .inst-card .inst-name { font-weight: bold; font-size: 16px; color: var(--text-bright); }.inst-card .inst-badge {font-size: 11px;padding: 3px 10px;border-radius: 10px;font-weight: 600;+ border: 1px solid transparent;}- .inst-badge.running { background: var(--success-bg); color: var(--success); }- .inst-badge.starting { background: var(--warning-bg); color: var(--warning); }- .inst-badge.stopped { background: var(--inactive-bg); color: var(--text-dim); }- .inst-badge.error { background: var(--danger-bg); color: var(--danger); }+ .inst-badge.running { background: var(--success-bg); color: var(--success); border-color: rgba(22, 163, 74, 0.34); }+ .inst-badge.starting { background: var(--warning-bg); color: var(--warning); border-color: rgba(245, 158, 11, 0.32); }+ .inst-badge.stopped { background: var(--warning-bg); color: var(--warning); border-color: rgba(245, 158, 11, 0.32); }+ .inst-badge.stopping { background: var(--idle-bg); color: var(--idle); border-color: rgba(100, 116, 139, 0.35); }+ .inst-badge.error { background: var(--danger-bg); color: var(--danger); border-color: rgba(220, 38, 38, 0.35); }.inst-card .inst-body { padding: 12px 16px; }.inst-card .inst-row {display: flex;@@ -95,7 +104,7 @@.inst-card .inst-row .value { color: var(--text-bright); }.inst-card .inst-actions {padding: 10px 16px;- border-top: 1px solid #1a1a1a;+ border-top: 1px solid var(--border);display: flex;gap: 6px;}@@ -106,9 +115,55 @@color: var(--text-subtle);padding: 6px;border-radius: 4px;- font-size: 11px;+ font-size: 12px;+ font-weight: 600;+ letter-spacing: 0.06em;+ text-transform: uppercase;cursor: pointer;font-family: inherit;}.inst-card .inst-actions button:hover { border-color: var(--primary); color: var(--primary); }- .inst-card .inst-actions button.danger:hover { border-color: var(--danger); color: var(--danger); }+ .inst-card .inst-actions button.btn-launch {+ background: var(--primary);+ border-color: var(--primary);+ color: var(--primary-dark);+ }+ .inst-card .inst-actions button.btn-launch:hover {+ background: var(--primary-hover);+ border-color: var(--primary-hover);+ color: var(--primary-dark);+ }+ .inst-card .inst-actions button.btn-feed {+ background: transparent;+ border-color: transparent;+ color: #94a3b8;+ }+ .inst-card .inst-actions button.btn-feed:hover {+ border-color: #334155;+ color: #cbd5e1;+ }+ .inst-card .inst-actions button.danger {+ background: var(--danger);+ border-color: var(--danger);+ color: #fff;+ }+ .inst-card .inst-actions button.danger:hover {+ background: var(--danger-hover);+ border-color: var(--danger-hover);+ color: #fff;+ }++ .launch-command {+ width: 100%;+ min-height: 92px;+ resize: vertical;+ background: var(--bg);+ border: 1px solid var(--border-light);+ color: var(--text-subtle);+ padding: 10px;+ border-radius: 6px;+ font-family: var(--font);+ font-size: 11px;+ line-height: 1.45;+ margin-bottom: 10px;+ }diff --git a/dashboard/profiles.js b/dashboard/profiles.jsindex cfa4af01..045de2e5 100644--- a/dashboard/profiles.js+++ b/dashboard/profiles.js@@ -1,6 +1,19 @@'use strict';let profilesLoading = false;+const profileByName = {};++async function fetchJSONOr(url, fallback) {+ try {+ const res = await fetch(url);+ if (!res.ok) return fallback;+ const contentType = res.headers.get('content-type') || '';+ if (!contentType.includes('application/json')) return fallback;+ return await res.json();+ } catch (e) {+ return fallback;+ }+}async function loadProfiles() {if (profilesLoading) return;@@ -12,19 +25,21 @@ async function loadProfiles() {}try {- const [profRes, instRes, healthRes, tabsRes] = await Promise.all([- fetch('/profiles'),- fetch('/instances'),- fetch('/health'),- fetch('/tabs')+ const [profiles, instances, health] = await Promise.all([+ fetchJSONOr('/profiles', []),+ fetchJSONOr('/instances', []),+ fetchJSONOr('/health', {})]);- const profiles = await profRes.json() || [];- const instances = await instRes.json() || [];- const health = await healthRes.json();- const tabsData = await tabsRes.json();+ let tabsData = { tabs: [] };+ if (!health.mode) {+ tabsData = await fetchJSONOr('/tabs', { tabs: [] });+ }- const running = {};- instances.forEach(inst => { if (inst.status === 'running') running[inst.name] = inst; });+ const instanceByName = {};+ instances.forEach(inst => { instanceByName[inst.name] = inst; });++ Object.keys(profileByName).forEach(k => { delete profileByName[k]; });+ profiles.forEach(p => { profileByName[p.name] = p; });const profileNames = new Set(profiles.map(p => p.name));const extraInstances = instances.filter(i => !profileNames.has(i.name));@@ -37,13 +52,21 @@ async function loadProfiles() {}profiles.forEach(p => {- cards.push(renderProfileCard(p.name, p.sizeMB, p.source, running[p.name] || null));+ cards.push(renderProfileCard(p, instanceByName[p.name] || null));});extraInstances.forEach(inst => {- cards.push(renderProfileCard(inst.name, 0, 'instance', inst.status === 'running' ? inst : null));+ cards.push(renderProfileCard({+ name: inst.name,+ sizeMB: 0,+ source: 'instance'+ }, inst));});+ if (cards.length === 0) {+ grid.innerHTML = '<div class="empty-state"><div class="crab">🦀</div>No profiles yet.<br>Click <b>+ New Profile</b> to create one.</div>';+ return;+ }grid.innerHTML = cards.join('');} catch (e) {console.error('Failed to load profiles', e);@@ -55,7 +78,7 @@ async function loadProfiles() {function renderMainCard(tabCount) {return `- <div class="inst-card" style="border-color:#f5c542">+ <div class="inst-card" style="border-color:var(--border-active)"><div class="inst-header"><span class="inst-name">🦀 Main</span><span class="inst-badge running">running :${location.port || '9867'}</span>@@ -65,19 +88,47 @@ function renderMainCard(tabCount) {<div class="inst-row"><span class="label">Port</span><span class="value">${location.port || '9867'}</span></div></div><div class="inst-actions">- <button onclick="switchView('live')">📺 Live</button>- <button onclick="resetProfile('main')">🔄 Reset</button>- <button onclick="viewAnalytics('main')">📊 Analytics</button>+ <button onclick="viewMainLive()">Live</button>+ <button class="btn-feed" onclick="viewProfileInfo('main', '')">Info</button></div></div>`;}-function renderProfileCard(name, sizeMB, source, inst) {- const isRunning = inst && inst.status === 'running';- const statusBadge = isRunning- ? '<span class="inst-badge running">running :' + inst.port + '</span>'- : '<span class="inst-badge stopped">stopped</span>';+function renderProfileCard(profile, inst) {+ const name = profile.name;+ const sizeMB = profile.sizeMB;+ const source = profile.source;+ const accountText = profile.accountEmail || profile.accountName || '';+ const accountValue = accountText || '--';+ const chromeProfileName = profile.chromeProfileName || '';+ const status = inst ? inst.status : 'stopped';+ const isRunning = status === 'running';+ const isError = status === 'error';+ const tabsValue = (isRunning && inst) ? String(inst.tabCount ?? 0) : '-';+ const pidValue = (isRunning && inst && inst.pid) ? String(inst.pid) : '-';+ let statusBadge = '<span class="inst-badge stopped">stopped</span>';+ if (status === 'running') statusBadge = '<span class="inst-badge running">running :' + inst.port + '</span>';+ else if (status === 'starting') statusBadge = '<span class="inst-badge starting">starting</span>';+ else if (status === 'stopping') statusBadge = '<span class="inst-badge stopping">stopping</span>';+ else if (status === 'error') statusBadge = '<span class="inst-badge error">error</span>';++ let actions = '';+ if (isRunning) {+ actions =+ '<button onclick="viewInstanceLive(\'' + esc(inst.id) + '\', \'' + esc(inst.port) + '\')">Live</button>'+ + '<button class="btn-feed" onclick="viewProfileInfo(\'' + esc(name) + '\', \'' + esc(inst.id) + '\')">Info</button>'+ + '<button class="danger" onclick="stopProfile(\'' + esc(name) + '\')">Stop</button>';+ } else if (inst && (status === 'starting' || status === 'stopping')) {+ actions =+ '<button class="btn-feed" onclick="viewProfileInfo(\'' + esc(name) + '\', \'' + esc(inst.id) + '\')">Info</button>'+ + '<button class="danger" onclick="stopProfile(\'' + esc(name) + '\')">Stop</button>';+ } else {+ actions =+ '<button class="btn-launch" onclick="openLaunchModal(\'' + esc(name) + '\')">Launch</button>'+ + '<button class="btn-feed" onclick="viewProfileInfo(\'' + esc(name) + '\', \'' + esc(inst ? inst.id : '') + '\')">Info</button>'+ + '<button class="danger" onclick="deleteProfile(\'' + esc(name) + '\')">Delete</button>';+ }return `<div class="inst-card">@@ -88,26 +139,14 @@ function renderProfileCard(name, sizeMB, source, inst) {<div class="inst-body"><div class="inst-row"><span class="label">Size</span><span class="value">${sizeMB ? sizeMB.toFixed(0) + ' MB' : '—'}</span></div><div class="inst-row"><span class="label">Source</span><span class="value">${esc(source)}</span></div>- ${isRunning ? '<div class="inst-row"><span class="label">Mode</span><span class="value">' + (inst.headless ? '🔲 Headless' : '🖥️ Headed') + '</span></div>' : ''}- ${isRunning ? '<div class="inst-row"><span class="label">Tabs</span><span class="value">' + inst.tabCount + '</span></div>' : ''}- ${isRunning ? '<div class="inst-row"><span class="label">PID</span><span class="value">' + inst.pid + '</span></div>' : ''}+ ${chromeProfileName ? '<div class="inst-row"><span class="label">Chrome</span><span class="value">' + esc(chromeProfileName) + '</span></div>' : ''}+ <div class="inst-row"><span class="label">Account</span><span class="value">${esc(accountValue)}</span></div>+ <div class="inst-row"><span class="label">Tabs</span><span class="value">${tabsValue}</span></div>+ <div class="inst-row"><span class="label">PID</span><span class="value">${pidValue}</span></div>+ ${isError && inst && inst.error ? '<div class="inst-row"><span class="label">Error</span><span class="value">' + esc(inst.error) + '</span></div>' : ''}</div><div class="inst-actions">- ${isRunning- ? '<button onclick="viewInstanceLive(\'' + esc(inst.id) + '\', \'' + esc(inst.port) + '\')">📺 Live</button>'- + '<button onclick="viewInstanceLogs(\'' + esc(inst.id) + '\')">📄 Logs</button>'- + '<button onclick="resetProfile(\'' + esc(name) + '\')">🔄 Reset</button>'- + '<button class="danger" onclick="stopInstance(\'' + esc(inst.id) + '\')">⏹ Stop</button>'- : (getProfileHeadless(name)- ? '<button onclick="launchProfile(\'' + esc(name) + '\')">🚀 Launch</button>'- + '<button onclick="launchHeaded(\'' + esc(name) + '\')">🖥️ Headed</button>'- : '<button onclick="launchHeaded(\'' + esc(name) + '\')">🖥️ Launch</button>'- + '<button onclick="launchProfile(\'' + esc(name) + '\')">🚀 Headless</button>'- )- + '<button onclick="resetProfile(\'' + esc(name) + '\')">🔄 Reset</button>'- + '<button onclick="viewAnalytics(\'' + esc(name) + '\')">📊 Analytics</button>'- + '<button class="danger" onclick="deleteProfile(\'' + esc(name) + '\')">🗑️ Delete</button>'- }+ ${actions}</div></div>`;@@ -152,47 +191,82 @@ async function doCreateProfile() {function getProfilePort(name) {const saved = localStorage.getItem('pinchtab-port-' + name);- if (saved) return saved;+ if (saved) {+ if (saved === String(location.port || '9867')) {+ return String(Number(saved) + 1);+ }+ return saved;+ }const cards = document.querySelectorAll('#profiles-grid .inst-card');let idx = 0;cards.forEach((c, i) => { if (c.querySelector('.inst-name')?.textContent === name) idx = i; });return String(9867 + Math.max(idx, 1));}-function saveProfilePort(name, port, headless) {+function saveProfilePort(name, port) {localStorage.setItem('pinchtab-port-' + name, port);- localStorage.setItem('pinchtab-headless-' + name, headless ? '1' : '0');-}--function getProfileHeadless(name) {- const saved = localStorage.getItem('pinchtab-headless-' + name);- if (saved !== null) return saved === '1';- return true;}-function openLaunchModal(name, headless) {+function openLaunchModal(name) {document.getElementById('launch-name').value = name;document.getElementById('launch-port').value = getProfilePort(name);- document.getElementById('launch-headless').checked = headless;+ document.getElementById('launch-profile-path').value = (profileByName[name] && profileByName[name].path) || '';+ updateLaunchCommand();document.getElementById('launch-modal').classList.add('open');document.getElementById('launch-port').focus();}-function launchProfile(name) { openLaunchModal(name, true); }-function launchHeaded(name) { openLaunchModal(name, false); }-function closeLaunchModal() {document.getElementById('launch-modal').classList.remove('open');}+function shellQuote(value) {+ return '\'' + String(value || '').replace(/'/g, "'\\''") + '\'';+}++function updateLaunchCommand() {+ const name = document.getElementById('launch-name').value.trim();+ const port = document.getElementById('launch-port').value.trim();+ const profilePathRaw = document.getElementById('launch-profile-path').value.trim();+ const profilePath = profilePathRaw || '<PROFILE_PATH>';+ const statePath = profilePath + '/.pinchtab-state';+ const prefix = profilePathRaw ? '' : '# replace <PROFILE_PATH> first\n';+ const cmd = '(test -x ./bin/pinchtab || go build -o ./bin/pinchtab .) && '+ + 'BRIDGE_PORT=' + shellQuote(port || '9868') + ' '+ + 'BRIDGE_PROFILE=' + shellQuote(profilePath) + ' '+ + 'BRIDGE_STATE_DIR=' + shellQuote(statePath) + ' '+ + 'BRIDGE_HEADLESS=false BRIDGE_NO_RESTORE=true BRIDGE_NO_DASHBOARD=true '+ + './bin/pinchtab';+ document.getElementById('launch-command').value = prefix + cmd;+}++async function copyLaunchCommand() {+ updateLaunchCommand();+ const el = document.getElementById('launch-command');+ const text = el.value;+ try {+ await navigator.clipboard.writeText(text);+ await appAlert('Command copied to clipboard.', 'Launch');+ } catch (e) {+ el.focus();+ el.select();+ document.execCommand('copy');+ await appAlert('Command copied (fallback).', 'Launch');+ }+}+async function doLaunch() {const name = document.getElementById('launch-name').value.trim();const port = document.getElementById('launch-port').value.trim();- const headless = document.getElementById('launch-headless').checked;+ const headless = false;if (!name || !port) { await appAlert('Port required'); return; }+ if (port === String(location.port || '9867')) {+ await appAlert('Choose a different port than the dashboard port (' + (location.port || '9867') + ').', 'Port in Use');+ return;+ }- saveProfilePort(name, port, headless);+ saveProfilePort(name, port);closeLaunchModal();try {@@ -218,29 +292,29 @@ async function deleteProfile(name) {loadProfiles();}-async function resetProfile(name) {- if (!await appConfirm('Reset profile "' + name + '"? This clears session data, cookies, and cache.', '🔄 Reset Profile')) return;- await fetch('/profiles/' + name + '/reset', { method: 'POST' });- closeModal();- loadProfiles();-}-function pollInstanceStatus(id) {let attempts = 0;const poll = setInterval(async () => {attempts++;- await loadProfiles();- if (attempts > 30) clearInterval(poll);+ if (attempts > 60) {+ clearInterval(poll);+ return;+ }try {const res = await fetch('/instances');const instances = await res.json();const inst = instances.find(i => i.id === id);if (inst && (inst.status === 'running' || inst.status === 'error' || inst.status === 'stopped')) {clearInterval(poll);+ if (inst.status === 'error') {+ await appAlert('Launch failed: ' + (inst.error || 'unknown error'), 'Error');+ } else if (inst.status === 'stopped') {+ await appAlert('Launch stopped before ready. Check Logs for details.', 'Launch');+ }loadProfiles();}- } catch (e) { clearInterval(poll); }+ } catch (e) {}}, 1000);}@@ -250,67 +324,88 @@ async function stopInstance(id) {setTimeout(loadProfiles, 1000);}-async function viewInstanceLogs(id) {- const res = await fetch('/instances/' + id + '/logs');- const text = await res.text();- showModal('📄 Logs: ' + id,- '<pre style="background:var(--bg);padding:12px;border-radius:6px;font-size:11px;max-height:400px;overflow:auto;color:var(--text-subtle);white-space:pre-wrap">' + esc(text) + '</pre>'- );+async function stopProfile(name) {+ if (!await appConfirm('Stop profile "' + name + '" gracefully?', '⏹ Stop Profile')) return;+ const res = await fetch('/profiles/' + encodeURIComponent(name) + '/stop', { method: 'POST' });+ if (!res.ok) {+ const data = await res.json().catch(() => ({}));+ await appAlert('Stop failed: ' + (data.error || res.statusText), 'Error');+ return;+ }+ setTimeout(loadProfiles, 700);}-async function viewAnalytics(name) {- let analytics = null;- try {- const res = await fetch('/profiles/' + name + '/analytics');- if (res.ok) analytics = await res.json();- } catch (e) {}+async function viewProfileInfo(name, instanceID) {+ const encName = encodeURIComponent(name);+ const [analytics, agents, liveTabs, state] = await Promise.all([+ fetchJSONOr('/profiles/' + encName + '/analytics', null),+ fetchJSONOr('/dashboard/agents', []),+ fetchJSONOr('/instances/tabs', []),+ fetchJSONOr('/profiles/' + encName + '/instance', null),+ ]);++ const finalInstanceID = instanceID || (state && state.id ? state.id : '');+ let logsText = '';+ if (finalInstanceID) {+ try {+ const logsRes = await fetch('/instances/' + encodeURIComponent(finalInstanceID) + '/logs');+ logsText = logsRes.ok ? await logsRes.text() : '';+ } catch (e) {+ logsText = '';+ }+ }- let tabs = [], agentList = [];- try {- const tabsRes = await fetch('/tabs');- const tabsData = await tabsRes.json();- tabs = tabsData.tabs || [];- } catch (e) {}- try {- const agentsRes = await fetch('/dashboard/agents');- agentList = await agentsRes.json() || [];- } catch (e) {}+ const tabsCount = Array.isArray(liveTabs)+ ? (name === 'main' ? liveTabs.length : liveTabs.filter(t => t.instanceName === name).length)+ : 0;+ const agentsForProfile = Array.isArray(agents)+ ? agents.filter(a => a.profile === name)+ : [];+ const status = state && state.status ? state.status : 'stopped';+ const port = state && state.port ? state.port : '-';+ const pid = state && state.pid ? state.pid : '-';let html = '';- html += '<h4 style="color:var(--text-muted);font-size:12px;margin-bottom:8px">LIVE STATUS</h4>';- html += '<div style="font-size:13px;color:var(--text-subtle);margin-bottom:4px">Tabs open: <span style="color:var(--text)">' + tabs.length + '</span></div>';- html += '<div style="font-size:13px;color:var(--text-subtle);margin-bottom:12px">Agents seen: <span style="color:var(--text)">' + agentList.length + '</span></div>';-- if (agentList.length > 0) {- html += '<h4 style="color:var(--text-muted);font-size:12px;margin-bottom:8px">AGENTS</h4>';- agentList.forEach(a => {- html += '<div style="font-size:12px;color:var(--text-subtle);padding:3px 0;display:flex;justify-content:space-between">';- html += '<span style="color:var(--primary);font-weight:600">' + esc(a.agentId) + '</span>';- html += '<span>' + a.actionCount + ' actions — ' + esc(a.lastAction || '') + '</span>';- html += '</div>';- });- html += '<div style="margin-bottom:12px"></div>';- }+ html += '<h4 style="color:var(--text-muted);font-size:12px;margin-bottom:8px">STATUS</h4>';+ html += '<div style="font-size:13px;color:var(--text-subtle);margin-bottom:4px">State: <span style="color:var(--text)">' + esc(status) + '</span></div>';+ html += '<div style="font-size:13px;color:var(--text-subtle);margin-bottom:4px">Port: <span style="color:var(--text)">' + esc(String(port)) + '</span></div>';+ html += '<div style="font-size:13px;color:var(--text-subtle);margin-bottom:12px">PID: <span style="color:var(--text)">' + esc(String(pid)) + '</span></div>';++ html += '<h4 style="color:var(--text-muted);font-size:12px;margin-bottom:8px">LIVE</h4>';+ html += '<div style="font-size:13px;color:var(--text-subtle);margin-bottom:4px">Tabs open: <span style="color:var(--text)">' + tabsCount + '</span></div>';+ html += '<div style="font-size:13px;color:var(--text-subtle);margin-bottom:12px">Agents: <span style="color:var(--text)">' + agentsForProfile.length + '</span></div>';if (analytics && analytics.totalActions > 0) {- html += '<h4 style="color:var(--text-muted);font-size:12px;margin-bottom:8px">TRACKED (' + analytics.totalActions + ' actions)</h4>';+ html += '<h4 style="color:var(--text-muted);font-size:12px;margin-bottom:8px">FEED (' + analytics.totalActions + ' actions)</h4>';if (analytics.topEndpoints) {analytics.topEndpoints.forEach(e => {- html += '<div style="font-size:12px;color:var(--text-subtle);padding:2px 0">' + esc(e.endpoint) + ' — ' + e.count + 'x, avg ' + e.avgMs + 'ms</div>';+ html += '<div style="font-size:12px;color:var(--text-subtle);padding:2px 0">' + esc(e.endpoint) + ' - ' + e.count + 'x, avg ' + e.avgMs + 'ms</div>';});}if (analytics.suggestions) {html += '<div style="margin-top:8px">';analytics.suggestions.forEach(s => {- html += '<p style="color:var(--primary);font-size:12px;margin-bottom:4px">💡 ' + esc(s) + '</p>';+ html += '<p style="color:var(--text-bright);font-size:12px;margin-bottom:4px">' + esc(s) + '</p>';});html += '</div>';}} else {- html += '<p style="color:var(--text-faint);font-size:12px">No tracked actions yet. Agents need to send <code style="color:var(--text-muted)">X-Profile</code> header to track per-profile analytics.</p>';+ html += '<p style="color:var(--text-faint);font-size:12px;margin-bottom:12px">No tracked actions yet.</p>';+ }++ html += '<h4 style="color:var(--text-muted);font-size:12px;margin-bottom:8px">LOGS</h4>';+ if (!logsText) {+ html += '<p style="color:var(--text-faint);font-size:12px">No instance logs available for this profile.</p>';+ } else {+ html += '<pre style="background:var(--bg);padding:12px;border-radius:6px;font-size:11px;max-height:45vh;overflow:auto;color:var(--text-subtle);white-space:pre-wrap">' + esc(logsText) + '</pre>';}- showModal('📊 Analytics: ' + name, html);+ showModal('INFO: ' + name, html, null, { wide: true });+}++const launchPortInput = document.getElementById('launch-port');+if (launchPortInput) {+ launchPortInput.addEventListener('input', updateLaunchCommand);}document.getElementById('modal').addEventListener('click', (e) => {diff --git a/dashboard/screencast.css b/dashboard/screencast.cssindex bec8a516..e7a0c388 100644--- a/dashboard/screencast.css+++ b/dashboard/screencast.css@@ -1,14 +1,38 @@-- .live-view { height: calc(100vh - 60px); display: flex; flex-direction: column; }- .live-toolbar { padding: 12px 24px; border-bottom: 1px solid var(--border); }+ .live-popup {+ display: flex;+ flex-direction: column;+ width: 100%;+ min-height: 380px;+ max-height: 72vh;+ }+ .live-toolbar {+ padding: 12px 0;+ border-bottom: 1px solid var(--border);+ display: flex;+ align-items: center;+ gap: 12px;+ }+ .live-count {+ color: var(--text-muted);+ font-size: 12px;+ }.screencast-grid {flex: 1;+ min-height: 320px;display: grid;- grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));+ grid-template-columns: repeat(auto-fit, minmax(360px, 1fr));gap: 12px;- padding: 16px;+ padding: 16px 0 0;overflow-y: auto;}+ .screencast-grid.empty {+ display: flex;+ align-items: center;+ justify-content: center;+ }+ .screencast-grid.empty .empty-state {+ padding: 0;+ }.screen-tile {background: var(--bg-raised);border: 1px solid var(--border);diff --git a/dashboard/screencast.js b/dashboard/screencast.jsindex d7ed9a0c..aded0c05 100644--- a/dashboard/screencast.js+++ b/dashboard/screencast.js@@ -1,31 +1,48 @@'use strict';const screencastSockets = {};+let liveModalContext = null;++function closeScreencastSockets() {+ Object.values(screencastSockets).forEach((s) => s.close());+ Object.keys(screencastSockets).forEach((k) => delete screencastSockets[k]);+}function getScreencastParams() {return '&quality=' + screencastSettings.quality + '&maxWidth=' + screencastSettings.maxWidth + '&fps=' + screencastSettings.fps;}-function connectScreencast(tabId, baseUrl) {+function makeTileKey(tabId, instancePort) {+ const portPart = String(instancePort || 'main').replace(/[^a-zA-Z0-9_-]/g, '_');+ const tabPart = String(tabId || '').replace(/[^a-zA-Z0-9_-]/g, '_');+ return portPart + '_' + tabPart;+}++function connectScreencast(stream) {+ const tabId = stream.tabId;+ const baseUrl = stream.baseUrl || null;+ const key = stream.key;const wsProto = baseUrl ? 'ws:' : (location.protocol === 'https:' ? 'wss:' : 'ws:');const wsHost = baseUrl ? baseUrl.replace(/^https?:\/\//, '') : location.host;- const wsUrl = wsProto + '//' + wsHost + '/screencast?tabId=' + tabId + getScreencastParams();+ const wsUrl = wsProto + '//' + wsHost + '/screencast?tabId=' + encodeURIComponent(tabId) + getScreencastParams();const socket = new WebSocket(wsUrl);socket.binaryType = 'arraybuffer';- screencastSockets[tabId] = socket;+ screencastSockets[key] = socket;- const canvas = document.getElementById('canvas-' + tabId);+ const canvas = document.getElementById('canvas-' + key);if (!canvas) return;const ctx2d = canvas.getContext('2d');let frameCount = 0;let lastFpsTime = Date.now();- const statusEl = document.getElementById('status-' + tabId);- const fpsEl = document.getElementById('fps-' + tabId);- const sizeEl = document.getElementById('size-' + tabId);+ const statusEl = document.getElementById('status-' + key);+ const fpsEl = document.getElementById('fps-' + key);+ const sizeEl = document.getElementById('size-' + key);- socket.onopen = () => { if (statusEl) statusEl.className = 'tile-status streaming'; };+ socket.onopen = () => {+ if (statusEl) statusEl.className = 'tile-status streaming';+ };socket.onmessage = (evt) => {const blob = new Blob([evt.data], { type: 'image/jpeg' });const url = URL.createObjectURL(blob);@@ -46,89 +63,175 @@ function connectScreencast(tabId, baseUrl) {lastFpsTime = now;}};- socket.onerror = () => { if (statusEl) statusEl.className = 'tile-status error'; };- socket.onclose = () => { if (statusEl) statusEl.className = 'tile-status error'; };+ socket.onerror = () => {+ if (statusEl) statusEl.className = 'tile-status error';+ };+ socket.onclose = () => {+ if (statusEl) statusEl.className = 'tile-status error';+ };}-function startScreencast(tabId) { connectScreencast(tabId, null); }--async function refreshTabs() {- Object.values(screencastSockets).forEach(s => s.close());- Object.keys(screencastSockets).forEach(k => delete screencastSockets[k]);-- try {- const res = await fetch('/screencast/tabs');- const tabs = await res.json();- const grid = document.getElementById('screencast-grid');- document.getElementById('live-tab-count').textContent = tabs.length + ' tab(s)';+function renderLiveEmpty(grid, messageHtml) {+ if (!grid) return;+ grid.classList.add('empty');+ grid.innerHTML = '<div class="empty-state"><img src="/dashboard/pinchtab-headed-192.png" alt="" class="empty-icon">' + messageHtml + '</div>';+}- if (tabs.length === 0) {- grid.innerHTML = '<div class="empty-state"><div class="crab">🦀</div>No tabs open.</div>';- return;- }+function renderLiveTiles(grid, html) {+ if (!grid) return;+ grid.classList.remove('empty');+ grid.innerHTML = html;+}- grid.innerHTML = tabs.map(t => `- <div class="screen-tile" id="tile-${t.id}">+function renderStreams(grid, streams) {+ renderLiveTiles(grid, streams.map((s) => `+ <div class="screen-tile" id="tile-${s.key}"><div class="tile-header"><span>- <span class="tile-id">${t.id.substring(0, 8)}</span>- <span class="tile-status connecting" id="status-${t.id}"></span>+ <span class="tile-id">${esc(s.label)}</span>+ <span class="tile-status connecting" id="status-${s.key}"></span></span>- <span class="tile-url" id="url-${t.id}">${esc(t.url || 'about:blank')}</span>+ <span class="tile-url" id="url-${s.key}">${esc(s.url || 'about:blank')}</span></div>- <canvas id="canvas-${t.id}" width="800" height="600"></canvas>+ <canvas id="canvas-${s.key}" width="800" height="600"></canvas><div class="tile-footer">- <span id="fps-${t.id}">—</span>- <span id="size-${t.id}">—</span>+ <span id="fps-${s.key}">—</span>+ <span id="size-${s.key}">—</span></div></div>- `).join('');+ `).join(''));+ streams.forEach((s) => connectScreencast(s));+}- tabs.forEach(t => startScreencast(t.id));- } catch (e) {- console.error('Failed to load tabs', e);- }+function showLiveModal(title) {+ closeScreencastSockets();+ const body = `+ <div class="live-popup">+ <div class="live-toolbar">+ <button class="refresh-btn" id="live-refresh-btn">Refresh Tabs</button>+ <span id="live-tab-count" class="live-count">Loading...</span>+ </div>+ <div id="screencast-grid" class="screencast-grid empty">+ <div class="empty-state"><span class="spinner"></span>Loading live tabs...</div>+ </div>+ </div>+ `;+ showModal(title, body, '<button class="secondary" onclick="closeModal()">Close</button>', {+ wide: true,+ onClose: () => {+ closeScreencastSockets();+ liveModalContext = null;+ }+ });+ const refreshBtn = document.getElementById('live-refresh-btn');+ if (refreshBtn) refreshBtn.onclick = () => refreshLiveModal();}-async function viewInstanceLive(id, port) {- switchView('live');+async function refreshLiveModal() {+ if (!liveModalContext) return;+ closeScreencastSockets();++ const grid = document.getElementById('screencast-grid');+ const countEl = document.getElementById('live-tab-count');+ if (!grid || !countEl) return;+try {- const res = await fetch('/instances/tabs');- const tabs = await res.json();- const instTabs = tabs.filter(t => t.instancePort === port);- const grid = document.getElementById('screencast-grid');- document.getElementById('live-tab-count').textContent = instTabs.length + ' tab(s) on ' + id;-- if (instTabs.length === 0) {- grid.innerHTML = '<div class="empty-state"><div class="crab">🦀</div>No tabs in this instance.</div>';+ const result = await liveModalContext.load();+ if (!result.ok) {+ countEl.textContent = 'Unavailable';+ renderLiveEmpty(grid, 'Live view unavailable (' + result.status + ').');+ return;+ }+ countEl.textContent = result.countLabel;+ if (!Array.isArray(result.streams) || result.streams.length === 0) {+ renderLiveEmpty(grid, result.emptyMessage || 'No tabs open.');return;}+ renderStreams(grid, result.streams);+ } catch (e) {+ countEl.textContent = 'Retrying';+ renderLiveEmpty(grid, 'Live request failed.<br>Retrying...');+ console.error('Failed to load live tabs', e);+ }+}- grid.innerHTML = instTabs.map(t => `- <div class="screen-tile" id="tile-${t.tabId}">- <div class="tile-header">- <span>- <span class="tile-id">${esc(t.instanceName)}:${t.tabId.substring(0, 6)}</span>- <span class="tile-status connecting" id="status-${t.tabId}"></span>- </span>- <span class="tile-url" id="url-${t.tabId}">${esc(t.url || 'about:blank')}</span>- </div>- <canvas id="canvas-${t.tabId}" width="800" height="600"></canvas>- <div class="tile-footer">- <span id="fps-${t.tabId}">—</span>- <span id="size-${t.tabId}">—</span>- </div>- </div>- `).join('');+async function loadMainStreams() {+ const res = await fetch('/screencast/tabs');+ if (res.status === 503) {+ return {+ ok: true,+ countLabel: 'No running instance',+ streams: [],+ emptyMessage: 'No running instance.'+ };+ }+ if (!res.ok) return { ok: false, status: res.status };+ const tabs = await res.json();+ if (!Array.isArray(tabs)) {+ return { ok: true, countLabel: '0 tab(s)', streams: [], emptyMessage: 'No tabs open.' };+ }+ return {+ ok: true,+ countLabel: tabs.length + ' tab(s)',+ streams: tabs.map((t) => ({+ key: makeTileKey(t.id, 'main'),+ tabId: t.id,+ baseUrl: null,+ label: String(t.id || '').substring(0, 8),+ url: t.url || 'about:blank',+ })),+ emptyMessage: 'No tabs open.'+ };+}- instTabs.forEach(t => {- connectScreencast(t.tabId, 'http://localhost:' + t.instancePort);- });- } catch (e) {- console.error('Failed to load instance tabs', e);+async function loadInstanceStreams(id, port) {+ const res = await fetch('/instances/tabs');+ if (res.status === 503) {+ return {+ ok: true,+ countLabel: 'No running instance',+ streams: [],+ emptyMessage: 'No running instance for this profile.'+ };}+ if (!res.ok) return { ok: false, status: res.status };++ const tabs = await res.json();+ const selectedTabs = Array.isArray(tabs)+ ? tabs.filter((t) => String(t.instancePort || '') === String(port || ''))+ : [];+ const streams = selectedTabs.map((t) => ({+ key: makeTileKey(t.tabId, t.instancePort),+ tabId: t.tabId,+ baseUrl: 'http://localhost:' + t.instancePort,+ label: (t.instanceName || 'instance') + ':' + String(t.tabId || '').substring(0, 6),+ url: t.url || 'about:blank',+ }));+ return {+ ok: true,+ countLabel: selectedTabs.length + ' tab(s) on ' + id,+ streams,+ emptyMessage: 'No tabs in this profile.'+ };+}++async function viewMainLive() {+ liveModalContext = {+ load: loadMainStreams,+ };+ showLiveModal('LIVE: Main');+ await refreshLiveModal();+}++async function viewInstanceLive(id, port) {+ liveModalContext = {+ load: () => loadInstanceStreams(id, port),+ };+ showLiveModal('LIVE: ' + id);+ await refreshLiveModal();}- window.addEventListener('beforeunload', () => {- Object.values(screencastSockets).forEach(s => s.close());+window.addEventListener('beforeunload', () => {+ liveModalContext = null;+ closeScreencastSockets();});diff --git a/dashboard/settings.js b/dashboard/settings.jsindex 358aae5c..c9d8bc4f 100644--- a/dashboard/settings.js+++ b/dashboard/settings.js@@ -56,7 +56,7 @@ async function applySettings() {Object.values(screencastSockets).forEach(s => s.close());Object.keys(screencastSockets).forEach(k => delete screencastSockets[k]);- await appAlert('Settings saved. Switch to Live view to see changes.', '⚙️ Settings');+ await appAlert('Settings saved.', '⚙️ Settings');}async function applyStealth() {diff --git a/dashboard/utils.js b/dashboard/utils.jsindex 3046c35a..5dc65129 100644--- a/dashboard/utils.js+++ b/dashboard/utils.js@@ -1,5 +1,7 @@'use strict';+let modalCloseHook = null;+function esc(s) {if (!s) return '';const d = document.createElement('div');@@ -46,11 +48,32 @@ function appAlert(message, title) {}function closeModal() {- document.getElementById('modal').classList.remove('open');+ const overlay = document.getElementById('modal');+ if (modalCloseHook) {+ const hook = modalCloseHook;+ modalCloseHook = null;+ try { hook(); } catch (e) {}+ }+ overlay.classList.remove('open');+ const dialog = overlay.querySelector('.modal');+ if (dialog) dialog.classList.remove('modal-wide');}-function showModal(title, bodyHtml, buttons) {+function showModal(title, bodyHtml, buttons, options) {+ if (modalCloseHook) {+ const hook = modalCloseHook;+ modalCloseHook = null;+ try { hook(); } catch (e) {}+ }const modal = document.getElementById('modal');+ const dialog = modal.querySelector('.modal');+ if (dialog) {+ dialog.classList.remove('modal-wide');+ if (options && options.wide) {+ dialog.classList.add('modal-wide');+ }+ }+ modalCloseHook = options && typeof options.onClose === 'function' ? options.onClose : null;document.getElementById('modal-title').textContent = title;let html = bodyHtml;if (buttons) {diff --git a/main.go b/main.goindex ca89eafd..2e2f3034 100644--- a/main.go+++ b/main.go@@ -312,10 +312,17 @@ func main() {mux.HandleFunc("POST /shutdown", bridge.handleShutdown(doShutdown))go func() {- sig := make(chan os.Signal, 1)+ sig := make(chan os.Signal, 2)signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)<-sig- doShutdown()+ go doShutdown()+ <-sig+ slog.Warn("force shutdown requested")+ orchestrator.ForceShutdown()+ cleanupCancel()+ browserCancel()+ allocCancel()+ os.Exit(130)}()slog.Info("🦀 PINCH! PINCH!", "port", port, "cdp", cdpURL, "stealth", stealthLevel)diff --git a/orchestrator_handlers.go b/orchestrator_handlers.goindex 16c78eee..0209ae9f 100644--- a/orchestrator_handlers.go+++ b/orchestrator_handlers.go@@ -3,13 +3,17 @@ package mainimport ("encoding/json""fmt"+ "log/slog""net/http"+ "strings")func (o *Orchestrator) RegisterHandlers(mux *http.ServeMux) {mux.HandleFunc("GET /instances", o.handleList)mux.HandleFunc("POST /instances/launch", o.handleLaunch)mux.HandleFunc("POST /instances/{id}/stop", o.handleStop)+ mux.HandleFunc("GET /profiles/{name}/instance", o.handleProfileInstance)+ mux.HandleFunc("POST /profiles/{name}/stop", o.handleStopProfile)mux.HandleFunc("GET /instances/{id}/logs", o.handleLogs)mux.HandleFunc("GET /instances/tabs", o.handleAllTabs)mux.HandleFunc("GET /instances/{id}/proxy/screencast", o.handleProxyScreencast)@@ -21,9 +25,8 @@ func (o *Orchestrator) handleList(w http.ResponseWriter, r *http.Request) {func (o *Orchestrator) handleLaunch(w http.ResponseWriter, r *http.Request) {var req struct {- Name string `json:"name"`- Port string `json:"port"`- Headless *bool `json:"headless"`+ Name string `json:"name"`+ Port string `json:"port"`}if err := json.NewDecoder(r.Body).Decode(&req); err != nil {jsonErr(w, 400, fmt.Errorf("invalid JSON"))@@ -34,16 +37,23 @@ func (o *Orchestrator) handleLaunch(w http.ResponseWriter, r *http.Request) {return}- headless := true- if req.Headless != nil {- headless = *req.Headless+ slog.Info("launch request", "profile", req.Name, "port", req.Port, "headed", true)+ inst, err := o.Launch(req.Name, req.Port, false)+ if isStartingConflict(err) {+ slog.Warn("launch blocked by starting instance; stopping and retrying", "profile", req.Name)+ if stopErr := o.StopProfile(req.Name); stopErr != nil {+ slog.Warn("failed to stop starting instance", "profile", req.Name, "err", stopErr)+ jsonErr(w, 409, err)+ return+ }+ inst, err = o.Launch(req.Name, req.Port, false)}-- inst, err := o.Launch(req.Name, req.Port, headless)if err != nil {+ slog.Warn("launch rejected", "profile", req.Name, "port", req.Port, "err", err)jsonErr(w, 409, err)return}+ slog.Info("launch accepted", "id", inst.ID, "profile", inst.Name, "port", inst.Port)jsonResp(w, 201, inst)}@@ -56,6 +66,46 @@ func (o *Orchestrator) handleStop(w http.ResponseWriter, r *http.Request) {jsonResp(w, 200, map[string]string{"status": "stopped", "id": id})}+func (o *Orchestrator) handleProfileInstance(w http.ResponseWriter, r *http.Request) {+ name := r.PathValue("name")+ if name == "" {+ jsonErr(w, 400, fmt.Errorf("profile name required"))+ return+ }+ inst, ok := findProfileInstance(o.List(), name)+ if !ok {+ jsonResp(w, 200, map[string]any{+ "name": name,+ "running": false,+ "status": "stopped",+ "port": "",+ })+ return+ }+ jsonResp(w, 200, map[string]any{+ "name": name,+ "running": inst.Status == "running",+ "status": inst.Status,+ "port": inst.Port,+ "id": inst.ID,+ "pid": inst.PID,+ "error": inst.Error,+ })+}++func (o *Orchestrator) handleStopProfile(w http.ResponseWriter, r *http.Request) {+ name := r.PathValue("name")+ if name == "" {+ jsonErr(w, 400, fmt.Errorf("profile name required"))+ return+ }+ if err := o.StopProfile(name); err != nil {+ jsonErr(w, 404, err)+ return+ }+ jsonResp(w, 200, map[string]string{"status": "stopped", "name": name})+}+func (o *Orchestrator) handleLogs(w http.ResponseWriter, r *http.Request) {id := r.PathValue("id")logs, err := o.Logs(id)@@ -86,3 +136,41 @@ func (o *Orchestrator) handleProxyScreencast(w http.ResponseWriter, r *http.RequtargetURL := fmt.Sprintf("ws://localhost:%s/screencast?tabId=%s", inst.Port, tabID)jsonResp(w, 200, map[string]string{"wsUrl": targetURL})}++func isStartingConflict(err error) bool {+ return err != nil && strings.Contains(err.Error(), "already has an active instance (starting)")+}++func findProfileInstance(instances []Instance, name string) (Instance, bool) {+ bestIdx := -1+ bestScore := -1+ for i := range instances {+ if instances[i].Name != name {+ continue+ }+ score := profileStatusScore(instances[i].Status)+ if bestIdx == -1 || score > bestScore || (score == bestScore && instances[i].StartedAt.After(instances[bestIdx].StartedAt)) {+ bestIdx = i+ bestScore = score+ }+ }+ if bestIdx == -1 {+ return Instance{}, false+ }+ return instances[bestIdx], true+}++func profileStatusScore(status string) int {+ switch status {+ case "running":+ return 5+ case "starting":+ return 4+ case "stopping":+ return 3+ case "error":+ return 2+ default:+ return 1+ }+}diff --git a/orchestrator_runtime.go b/orchestrator_runtime.goindex 71085943..d4fda4d1 100644--- a/orchestrator_runtime.go+++ b/orchestrator_runtime.go@@ -5,22 +5,37 @@ import ("encoding/json""fmt""log/slog"+ "net""net/http""os""os/exec""path/filepath"+ "sort"+ "strings"+ "sync""syscall""time")+const (+ instanceHealthPollInterval = 500 * time.Millisecond+ instanceStartupTimeout = 45 * time.Second+)+func (o *Orchestrator) Launch(name, port string, headless bool) (*Instance, error) {o.mu.Lock()defer o.mu.Unlock()for _, inst := range o.instances {- if inst.Port == port && inst.Status == "running" {+ if inst.Port == port && instanceIsActive(inst) {return nil, fmt.Errorf("port %s already in use by instance %q", port, inst.Name)}+ if inst.Name == name && instanceIsActive(inst) {+ return nil, fmt.Errorf("profile %q already has an active instance (%s)", name, inst.Status)+ }+ }+ if !isPortAvailable(port) {+ return nil, fmt.Errorf("port %s is already in use on this machine", port)}id := fmt.Sprintf("%s-%s", name, port)@@ -30,6 +45,8 @@ func (o *Orchestrator) Launch(name, port string, headless bool) (*Instance, erroprofilePath := filepath.Join(o.baseDir, name)os.MkdirAll(filepath.Join(profilePath, "Default"), 0755)+ instanceStateDir := filepath.Join(profilePath, ".pinchtab-state")+ os.MkdirAll(instanceStateDir, 0755)ctx, cancel := context.WithCancel(context.Background())@@ -39,13 +56,15 @@ func (o *Orchestrator) Launch(name, port string, headless bool) (*Instance, erro}cmd := exec.CommandContext(ctx, o.binary)- cmd.Env = append(os.Environ(),- "BRIDGE_PORT="+port,- "BRIDGE_PROFILE="+profilePath,- "BRIDGE_HEADLESS="+headlessStr,- "BRIDGE_NO_RESTORE=true",- "BRIDGE_NO_DASHBOARD=true",- )+ cmd.Env = mergeEnvWithOverrides(os.Environ(), map[string]string{+ "BRIDGE_PORT": port,+ "BRIDGE_PROFILE": profilePath,+ "BRIDGE_STATE_DIR": instanceStateDir,+ "BRIDGE_HEADLESS": headlessStr,+ "BRIDGE_NO_RESTORE": "true",+ "BRIDGE_NO_DASHBOARD": "true",+ })+ slog.Info("starting instance process", "id", id, "binary", o.binary, "port", port, "profile", profilePath)cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}logBuf := newRingBuffer(64 * 1024)@@ -81,35 +100,85 @@ func (o *Orchestrator) Launch(name, port string, headless bool) (*Instance, errofunc (o *Orchestrator) monitor(inst *Instance) {healthy := false- for i := 0; i < 30; i++ {- time.Sleep(500 * time.Millisecond)- resp, err := o.client.Get(inst.URL + "/health")- if err == nil {- resp.Body.Close()- if resp.StatusCode == 200 {- healthy = true- break+ exitedEarly := false+ lastProbe := "no response"+ resolvedURL := ""+ waitCh := make(chan error, 1)+ go func() {+ waitCh <- inst.cmd.Wait()+ }()+ var waitErr error+ started := time.Now()+ for time.Since(started) < instanceStartupTimeout {+ select {+ case waitErr = <-waitCh:+ exitedEarly = true+ default:+ }+ if exitedEarly {+ break+ }+ time.Sleep(instanceHealthPollInterval)++ for _, baseURL := range instanceBaseURLs(inst.Port) {+ resp, err := o.client.Get(baseURL + "/health")+ if err == nil {+ resp.Body.Close()+ lastProbe = fmt.Sprintf("%s -> HTTP %d", baseURL, resp.StatusCode)+ if isInstanceHealthyStatus(resp.StatusCode) {+ healthy = true+ resolvedURL = baseURL+ break+ }+ } else {+ lastProbe = fmt.Sprintf("%s -> %s", baseURL, err.Error())}}+ if healthy {+ break+ }}o.mu.Lock()- if healthy {- inst.Status = "running"- slog.Info("instance ready", "id", inst.ID, "port", inst.Port)- } else {- inst.Status = "error"- inst.Error = "health check timeout after 15s"- slog.Error("instance failed to start", "id", inst.ID)+ switch inst.Status {+ case "stopping", "stopped":+ default:+ if healthy {+ inst.Status = "running"+ if resolvedURL != "" {+ inst.URL = resolvedURL+ }+ slog.Info("instance ready", "id", inst.ID, "port", inst.Port)+ } else if exitedEarly {+ inst.Status = "error"+ if waitErr != nil {+ inst.Error = "process exited before health check: " + waitErr.Error()+ } else {+ inst.Error = "process exited before health check succeeded"+ }+ if tail := tailLogLine(inst.logBuf.String()); tail != "" {+ inst.Error += " | " + tail+ }+ slog.Error("instance exited before ready", "id", inst.ID)+ } else {+ inst.Status = "error"+ inst.Error = fmt.Sprintf("health check timeout after %s (%s)", instanceStartupTimeout, lastProbe)+ if tail := tailLogLine(inst.logBuf.String()); tail != "" {+ inst.Error += " | " + tail+ }+ slog.Error("instance failed to start", "id", inst.ID)+ }}o.mu.Unlock()- err := inst.cmd.Wait()+ if !exitedEarly {+ waitErr = <-waitCh+ }o.mu.Lock()- if inst.Status != "stopped" {+ if inst.Status == "running" || inst.Status == "stopping" {inst.Status = "stopped"- if err != nil {- inst.Error = err.Error()+ if waitErr != nil {+ inst.Error = waitErr.Error()}}o.mu.Unlock()@@ -123,24 +192,129 @@ func (o *Orchestrator) Stop(id string) error {o.mu.Unlock()return fmt.Errorf("instance %q not found", id)}- inst.Status = "stopped"+ if inst.Status == "stopped" && !instanceIsActive(inst) {+ o.mu.Unlock()+ return nil+ }+ inst.Status = "stopping"o.mu.Unlock()- req, _ := http.NewRequest("POST", inst.URL+"/shutdown", nil)+ if inst.cmd == nil || inst.cmd.Process == nil {+ o.markStopped(id)+ return nil+ }+ if inst.PID <= 0 {+ inst.cancel()+ o.markStopped(id)+ return nil+ }++ reqCtx, cancel := context.WithTimeout(context.Background(), 4*time.Second)+ defer cancel()+ req, _ := http.NewRequestWithContext(reqCtx, http.MethodPost, inst.URL+"/shutdown", nil)resp, err := o.client.Do(req)if err == nil {resp.Body.Close()- time.Sleep(2 * time.Second)}- if inst.cmd.ProcessState == nil || !inst.cmd.ProcessState.Exited() {- _ = syscall.Kill(-inst.cmd.Process.Pid, syscall.SIGKILL)- inst.cancel()+ if waitForProcessExit(inst.PID, 5*time.Second) {+ o.markStopped(id)+ return nil}+ if err := syscall.Kill(-inst.PID, syscall.SIGTERM); err != nil {+ slog.Warn("failed to send SIGTERM to instance", "id", id, "pid", inst.PID, "err", err)+ }+ if waitForProcessExit(inst.PID, 3*time.Second) {+ o.markStopped(id)+ return nil+ }++ if err := syscall.Kill(-inst.PID, syscall.SIGKILL); err != nil {+ slog.Warn("failed to send SIGKILL to instance", "id", id, "pid", inst.PID, "err", err)+ }+ inst.cancel()+ if waitForProcessExit(inst.PID, 2*time.Second) {+ o.markStopped(id)+ return nil+ }++ o.setStopError(id, fmt.Sprintf("failed to stop process %d; still running", inst.PID))+ return fmt.Errorf("failed to stop instance %q gracefully", id)+}++func (o *Orchestrator) StopProfile(name string) error {+ o.mu.RLock()+ ids := make([]string, 0, 1)+ for id, inst := range o.instances {+ if inst.Name == name && instanceIsActive(inst) {+ ids = append(ids, id)+ }+ }+ o.mu.RUnlock()++ if len(ids) == 0 {+ return fmt.Errorf("no active instance for profile %q", name)+ }++ var errs []string+ for _, id := range ids {+ if err := o.Stop(id); err != nil {+ errs = append(errs, err.Error())+ }+ }+ if len(errs) > 0 {+ return fmt.Errorf("failed to stop profile %q: %s", name, strings.Join(errs, "; "))+ }return nil}+func (o *Orchestrator) markStopped(id string) {+ o.mu.Lock()+ defer o.mu.Unlock()+ if inst, ok := o.instances[id]; ok {+ inst.Status = "stopped"+ }+}++func (o *Orchestrator) setStopError(id, msg string) {+ o.mu.Lock()+ defer o.mu.Unlock()+ if inst, ok := o.instances[id]; ok {+ inst.Status = "error"+ inst.Error = msg+ }+}++func instanceIsActive(inst *Instance) bool {+ if inst == nil {+ return false+ }+ if inst.PID > 0 {+ return isProcessAlive(inst.PID)+ }+ return inst.Status == "starting" || inst.Status == "running" || inst.Status == "stopping"+}++func waitForProcessExit(pid int, timeout time.Duration) bool {+ if pid <= 0 {+ return true+ }+ deadline := time.Now().Add(timeout)+ for time.Now().Before(deadline) {+ if !isProcessAlive(pid) {+ return true+ }+ time.Sleep(150 * time.Millisecond)+ }+ return !isProcessAlive(pid)+}++func isProcessAlive(pid int) bool {+ err := syscall.Kill(pid, syscall.Signal(0))+ return err == nil || err == syscall.EPERM+}+func (o *Orchestrator) List() []Instance {o.mu.RLock()defer o.mu.RUnlock()@@ -151,11 +325,12 @@ func (o *Orchestrator) List() []Instance {copyInst.cmd = nilcopyInst.cancel = nilcopyInst.logBuf = nil-- if inst.Status == "running" {- if tabs, err := o.fetchTabs(inst.URL); err == nil {- copyInst.TabCount = len(tabs)- }+ if instanceIsActive(inst) && copyInst.Status == "stopped" {+ copyInst.Status = "running"+ }+ if !instanceIsActive(inst) &&+ (copyInst.Status == "starting" || copyInst.Status == "running" || copyInst.Status == "stopping") {+ copyInst.Status = "stopped"}result = append(result, copyInst)@@ -174,11 +349,22 @@ func (o *Orchestrator) Logs(id string) (string, error) {return inst.logBuf.String(), nil}+func (o *Orchestrator) FirstRunningURL() string {+ o.mu.RLock()+ defer o.mu.RUnlock()+ for _, inst := range o.instances {+ if inst.Status == "running" && instanceIsActive(inst) {+ return inst.URL+ }+ }+ return ""+}+func (o *Orchestrator) AllTabs() []instanceTab {o.mu.RLock()instances := make([]*Instance, 0)for _, inst := range o.instances {- if inst.Status == "running" {+ if inst.Status == "running" && instanceIsActive(inst) {instances = append(instances, inst)}}@@ -244,14 +430,107 @@ func (o *Orchestrator) Shutdown() {o.mu.RLock()ids := make([]string, 0, len(o.instances))for id, inst := range o.instances {- if inst.Status == "running" {+ if instanceIsActive(inst) {ids = append(ids, id)}}o.mu.RUnlock()+ var wg sync.WaitGroupfor _, id := range ids {- slog.Info("stopping instance", "id", id)- o.Stop(id)+ wg.Add(1)+ go func(instanceID string) {+ defer wg.Done()+ slog.Info("stopping instance", "id", instanceID)+ if err := o.Stop(instanceID); err != nil {+ slog.Warn("stop instance failed", "id", instanceID, "err", err)+ }+ }(id)+ }+ wg.Wait()+}++func isPortAvailable(port string) bool {+ ln, err := net.Listen("tcp", ":"+port)+ if err != nil {+ return false+ }+ _ = ln.Close()+ return true+}++func (o *Orchestrator) ForceShutdown() {+ o.mu.RLock()+ instances := make([]*Instance, 0, len(o.instances))+ for _, inst := range o.instances {+ if instanceIsActive(inst) {+ instances = append(instances, inst)+ }+ }+ o.mu.RUnlock()++ for _, inst := range instances {+ if inst.PID > 0 {+ _ = syscall.Kill(-inst.PID, syscall.SIGKILL)+ }+ if inst.cancel != nil {+ inst.cancel()+ }+ o.markStopped(inst.ID)+ }+}++func isInstanceHealthyStatus(code int) bool {+ return code > 0 && code < http.StatusInternalServerError+}++func instanceBaseURLs(port string) []string {+ return []string{+ fmt.Sprintf("http://127.0.0.1:%s", port),+ fmt.Sprintf("http://[::1]:%s", port),+ fmt.Sprintf("http://localhost:%s", port),+ }+}++func tailLogLine(logs string) string {+ if logs == "" {+ return ""+ }+ lines := strings.Split(strings.TrimSpace(logs), "\n")+ for i := len(lines) - 1; i >= 0; i-- {+ line := strings.TrimSpace(lines[i])+ if line == "" {+ continue+ }+ const max = 220+ if len(line) > max {+ return line[len(line)-max:]+ }+ return line+ }+ return ""+}++func mergeEnvWithOverrides(base []string, overrides map[string]string) []string {+ out := make([]string, 0, len(base)+len(overrides))+ for _, kv := range base {+ key, _, ok := strings.Cut(kv, "=")+ if !ok {+ continue+ }+ if _, exists := overrides[key]; exists {+ continue+ }+ out = append(out, kv)+ }++ keys := make([]string, 0, len(overrides))+ for k := range overrides {+ keys = append(keys, k)+ }+ sort.Strings(keys)+ for _, k := range keys {+ out = append(out, k+"="+overrides[k])}+ return out}diff --git a/orchestrator_runtime_test.go b/orchestrator_runtime_test.gonew file mode 100644index 00000000..a313fd9b--- /dev/null+++ b/orchestrator_runtime_test.go@@ -0,0 +1,183 @@+package main++import (+ "fmt"+ "net/http"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"+)++func TestInstanceIsActiveStoppedButAlivePID(t *testing.T) {+ inst := &Instance{Status: "stopped", PID: os.Getpid()}+ if !instanceIsActive(inst) {+ t.Fatal("expected instance to be active when pid is alive")+ }+}++func TestLaunchRejectsStoppedButActiveInstance(t *testing.T) {+ o := &Orchestrator{+ instances: map[string]*Instance{+ "p1-9911": {+ ID: "p1-9911",+ Name: "p1",+ Port: "9911",+ Status: "stopped",+ PID: os.Getpid(),+ },+ },+ baseDir: t.TempDir(),+ binary: "pinchtab",+ client: &http.Client{Timeout: 10 * time.Millisecond},+ }++ _, err := o.Launch("p1", "9911", true)+ if err == nil {+ t.Fatal("expected launch to fail for active profile")+ }+ if !strings.Contains(err.Error(), "already has an active instance") && !strings.Contains(err.Error(), "already in use") {+ t.Fatalf("unexpected error: %v", err)+ }+}++func TestListReconcilesStoppedButAliveToRunning(t *testing.T) {+ o := &Orchestrator{+ instances: map[string]*Instance{+ "p1-9912": {+ ID: "p1-9912",+ Name: "p1",+ Port: "9912",+ Status: "stopped",+ PID: os.Getpid(),+ URL: "http://127.0.0.1:1",+ },+ },+ client: &http.Client{Timeout: 10 * time.Millisecond},+ }++ list := o.List()+ if len(list) != 1 {+ t.Fatalf("expected 1 instance, got %d", len(list))+ }+ if list[0].Status != "running" {+ t.Fatalf("expected reconciled status running, got %q", list[0].Status)+ }+}++func TestMergeEnvWithOverridesReplacesExistingValues(t *testing.T) {+ base := []string{+ "BRIDGE_PORT=9870",+ "BRIDGE_HEADLESS=true",+ "PATH=/usr/bin",+ }+ merged := mergeEnvWithOverrides(base, map[string]string{+ "BRIDGE_PORT": "9868",+ "BRIDGE_HEADLESS": "false",+ "BRIDGE_PROFILE": "/tmp/profile",+ })+ joined := strings.Join(merged, "\n")++ if strings.Contains(joined, "BRIDGE_PORT=9870") {+ t.Fatalf("expected old BRIDGE_PORT to be removed, got %v", merged)+ }+ if !strings.Contains(joined, "BRIDGE_PORT=9868") {+ t.Fatalf("expected overridden BRIDGE_PORT, got %v", merged)+ }+ if !strings.Contains(joined, "BRIDGE_HEADLESS=false") {+ t.Fatalf("expected overridden BRIDGE_HEADLESS, got %v", merged)+ }+ if !strings.Contains(joined, "BRIDGE_PROFILE=/tmp/profile") {+ t.Fatalf("expected BRIDGE_PROFILE override, got %v", merged)+ }+}++func TestIsInstanceHealthyStatus(t *testing.T) {+ tests := []struct {+ code int+ ok bool+ }{+ {code: 200, ok: true},+ {code: 401, ok: true},+ {code: 404, ok: true},+ {code: 500, ok: false},+ {code: 503, ok: false},+ }+ for _, tt := range tests {+ if got := isInstanceHealthyStatus(tt.code); got != tt.ok {+ t.Fatalf("code %d: got %v, want %v", tt.code, got, tt.ok)+ }+ }+}++func TestIsStartingConflict(t *testing.T) {+ if !isStartingConflict(fmt.Errorf(`profile "x" already has an active instance (starting)`)) {+ t.Fatal("expected starting conflict to match")+ }+ if isStartingConflict(fmt.Errorf(`profile "x" already has an active instance (running)`)) {+ t.Fatal("did not expect running conflict to match")+ }+}++func TestFindProfileInstancePrefersRunning(t *testing.T) {+ now := time.Now()+ inst, ok := findProfileInstance([]Instance{+ {Name: "alpha", Status: "error", Port: "9868", StartedAt: now.Add(-time.Minute)},+ {Name: "alpha", Status: "running", Port: "9869", StartedAt: now},+ {Name: "beta", Status: "running", Port: "9870", StartedAt: now},+ }, "alpha")+ if !ok {+ t.Fatal("expected instance for alpha")+ }+ if inst.Status != "running" || inst.Port != "9869" {+ t.Fatalf("unexpected selected instance: %+v", inst)+ }+}++func TestFindProfileInstanceMissing(t *testing.T) {+ _, ok := findProfileInstance([]Instance{{Name: "a", Status: "stopped"}}, "nope")+ if ok {+ t.Fatal("expected no instance")+ }+}++func TestInstanceBaseURLs(t *testing.T) {+ got := instanceBaseURLs("9869")+ if len(got) != 3 {+ t.Fatalf("expected 3 base URLs, got %d", len(got))+ }+ if got[0] != "http://127.0.0.1:9869" {+ t.Fatalf("unexpected IPv4 URL: %s", got[0])+ }+ if got[1] != "http://[::1]:9869" {+ t.Fatalf("unexpected IPv6 URL: %s", got[1])+ }+ if got[2] != "http://localhost:9869" {+ t.Fatalf("unexpected localhost URL: %s", got[2])+ }+}++func TestTailLogLine(t *testing.T) {+ got := tailLogLine("\nfirst\n\nsecond\n")+ if got != "second" {+ t.Fatalf("unexpected tail line: %q", got)+ }+}++func TestNewOrchestratorPrefersCurrentExecutable(t *testing.T) {+ exe, err := os.Executable()+ if err != nil || exe == "" {+ t.Skip("no executable path available")+ }++ base := filepath.Join(t.TempDir(), "profiles")+ if err := os.MkdirAll(base, 0755); err != nil {+ t.Fatalf("mkdir base: %v", err)+ }++ o := NewOrchestrator(base)+ if o.binary != exe {+ t.Fatalf("expected binary %q, got %q", exe, o.binary)+ }+}diff --git a/orchestrator_types.go b/orchestrator_types.goindex ec1451d4..fbd6147e 100644--- a/orchestrator_types.go+++ b/orchestrator_types.go@@ -66,32 +66,27 @@ func (rb *ringBuffer) String() string {func NewOrchestrator(baseDir string) *Orchestrator {binDir := filepath.Join(filepath.Dir(baseDir), "bin")stableBin := filepath.Join(binDir, "pinchtab")-- needsBuild := true- if fi, err := os.Stat(stableBin); err == nil {- if time.Since(fi.ModTime()) < time.Hour {- needsBuild = false- }+ exe, _ := os.Executable()+ binary := exe+ if binary == "" {+ binary = os.Args[0]}- if needsBuild {- os.MkdirAll(binDir, 0755)+ if err := os.MkdirAll(binDir, 0755); err != nil {+ slog.Warn("failed to create bin directory", "path", binDir, "err", err)+ }- exe, _ := os.Executable()- if exe != "" {- if data, err := os.ReadFile(exe); err == nil {- if err := os.WriteFile(stableBin, data, 0755); err == nil {- slog.Info("installed pinchtab binary", "path", stableBin)- }- }+ if exe != "" {+ if err := installStableBinary(exe, stableBin); err != nil {+ slog.Warn("failed to install pinchtab binary", "path", stableBin, "err", err)+ } else {+ slog.Info("installed pinchtab binary", "path", stableBin)}}- binary := stableBinif _, err := os.Stat(binary); err != nil {- binary, _ = os.Executable()- if binary == "" {- binary = os.Args[0]+ if _, stableErr := os.Stat(stableBin); stableErr == nil {+ binary = stableBin}}@@ -102,3 +97,11 @@ func NewOrchestrator(baseDir string) *Orchestrator {client: &http.Client{Timeout: 3 * time.Second},}}++func installStableBinary(src, dst string) error {+ data, err := os.ReadFile(src)+ if err != nil {+ return err+ }+ return os.WriteFile(dst, data, 0755)+}diff --git a/profiles_manager.go b/profiles_manager.goindex 776c9708..cbda9845 100644--- a/profiles_manager.go+++ b/profiles_manager.go@@ -1,6 +1,7 @@package mainimport (+ "encoding/json""fmt""io/fs""log/slog"@@ -19,11 +20,15 @@ type ProfileManager struct {}type ProfileInfo struct {- Name string `json:"name"`- Path string `json:"path"`- CreatedAt time.Time `json:"createdAt"`- SizeMB float64 `json:"sizeMB"`- Source string `json:"source,omitempty"`+ Name string `json:"name"`+ Path string `json:"path"`+ CreatedAt time.Time `json:"createdAt"`+ SizeMB float64 `json:"sizeMB"`+ Source string `json:"source,omitempty"`+ ChromeProfileName string `json:"chromeProfileName,omitempty"`+ AccountEmail string `json:"accountEmail,omitempty"`+ AccountName string `json:"accountName,omitempty"`+ HasAccount bool `json:"hasAccount,omitempty"`}func NewProfileManager(baseDir string) *ProfileManager {@@ -76,12 +81,18 @@ func (pm *ProfileManager) profileInfo(name string) (ProfileInfo, error) {source = "imported"}+ chromeProfileName, accountEmail, accountName, hasAccount := readChromeProfileIdentity(dir)+return ProfileInfo{- Name: name,- Path: dir,- CreatedAt: fi.ModTime(),- SizeMB: size,- Source: source,+ Name: name,+ Path: dir,+ CreatedAt: fi.ModTime(),+ SizeMB: size,+ Source: source,+ ChromeProfileName: chromeProfileName,+ AccountEmail: accountEmail,+ AccountName: accountName,+ HasAccount: hasAccount,}, nil}@@ -196,3 +207,91 @@ func dirSizeMB(path string) float64 {})return float64(total) / (1024 * 1024)}++func readChromeProfileIdentity(profileRoot string) (string, string, string, bool) {+ chromeProfileName, lsEmail, lsName, lsHas := readLocalStateIdentity(filepath.Join(profileRoot, "Local State"))+ prefsEmail, prefsName, prefsHas := readPreferencesIdentity(filepath.Join(profileRoot, "Default", "Preferences"))++ email := prefsEmail+ if email == "" {+ email = lsEmail+ }++ accountName := prefsName+ if accountName == "" {+ accountName = lsName+ }++ hasAccount := prefsHas || lsHas || email != ""+ return chromeProfileName, email, accountName, hasAccount+}++func readPreferencesIdentity(path string) (string, string, bool) {+ var prefs struct {+ AccountInfo []struct {+ Email string `json:"email"`+ FullName string `json:"full_name"`+ GaiaName string `json:"gaia_name"`+ GaiaID string `json:"gaia"`+ } `json:"account_info"`+ }+ if !readJSON(path, &prefs) {+ return "", "", false+ }++ for _, account := range prefs.AccountInfo {+ email := account.Email+ name := account.FullName+ if name == "" {+ name = account.GaiaName+ }+ if email != "" || account.GaiaID != "" || name != "" {+ return email, name, true+ }+ }++ return "", "", false+}++func readLocalStateIdentity(path string) (string, string, string, bool) {+ var state struct {+ Profile struct {+ InfoCache map[string]struct {+ Name string `json:"name"`+ UserName string `json:"user_name"`+ GaiaName string `json:"gaia_name"`+ GaiaID string `json:"gaia_id"`+ IsConsentedPrimaryAccount bool `json:"is_consented_primary_account"`+ HasConsentedPrimaryAccount bool `json:"has_consented_primary_account"`+ } `json:"info_cache"`+ } `json:"profile"`+ }+ if !readJSON(path, &state) || len(state.Profile.InfoCache) == 0 {+ return "", "", "", false+ }++ entry, ok := state.Profile.InfoCache["Default"]+ if !ok {+ for _, v := range state.Profile.InfoCache {+ entry = v+ break+ }+ }++ profileName := entry.Name+ email := entry.UserName+ accountName := entry.GaiaName+ hasAccount := email != "" || entry.GaiaID != "" || entry.IsConsentedPrimaryAccount || entry.HasConsentedPrimaryAccount+ return profileName, email, accountName, hasAccount+}++func readJSON(path string, out any) bool {+ data, err := os.ReadFile(path)+ if err != nil {+ return false+ }+ if err := json.Unmarshal(data, out); err != nil {+ return false+ }+ return true+}diff --git a/profiles_test.go b/profiles_test.goindex ae28980c..541e36e0 100644--- a/profiles_test.go+++ b/profiles_test.go@@ -76,6 +76,71 @@ func TestProfileManagerImportBadSource(t *testing.T) {}}+func TestProfileManagerListReadsAccountFromPreferences(t *testing.T) {+ dir := t.TempDir()+ pm := NewProfileManager(dir)+ if err := pm.Create("acc-pref"); err != nil {+ t.Fatal(err)+ }++ prefsPath := filepath.Join(dir, "acc-pref", "Default", "Preferences")+ prefs := `{"account_info":[{"email":"[email protected]","full_name":"Alice"}]}`+ if err := os.WriteFile(prefsPath, []byte(prefs), 0644); err != nil {+ t.Fatal(err)+ }++ profiles, err := pm.List()+ if err != nil {+ t.Fatal(err)+ }+ if len(profiles) != 1 {+ t.Fatalf("expected 1 profile, got %d", len(profiles))+ }+ if profiles[0].AccountEmail != "[email protected]" {+ t.Fatalf("expected account email [email protected], got %q", profiles[0].AccountEmail)+ }+ if profiles[0].AccountName != "Alice" {+ t.Fatalf("expected account name Alice, got %q", profiles[0].AccountName)+ }+ if !profiles[0].HasAccount {+ t.Fatal("expected hasAccount=true")+ }+}++func TestProfileManagerListReadsLocalStateIdentity(t *testing.T) {+ dir := t.TempDir()+ pm := NewProfileManager(dir)+ if err := pm.Create("acc-local"); err != nil {+ t.Fatal(err)+ }++ localStatePath := filepath.Join(dir, "acc-local", "Local State")+ localState := `{"profile":{"info_cache":{"Default":{"name":"Work","user_name":"[email protected]","gaia_name":"Bob","gaia_id":"123"}}}}`+ if err := os.WriteFile(localStatePath, []byte(localState), 0644); err != nil {+ t.Fatal(err)+ }++ profiles, err := pm.List()+ if err != nil {+ t.Fatal(err)+ }+ if len(profiles) != 1 {+ t.Fatalf("expected 1 profile, got %d", len(profiles))+ }+ if profiles[0].ChromeProfileName != "Work" {+ t.Fatalf("expected chrome profile name Work, got %q", profiles[0].ChromeProfileName)+ }+ if profiles[0].AccountEmail != "[email protected]" {+ t.Fatalf("expected account email [email protected], got %q", profiles[0].AccountEmail)+ }+ if profiles[0].AccountName != "Bob" {+ t.Fatalf("expected account name Bob, got %q", profiles[0].AccountName)+ }+ if !profiles[0].HasAccount {+ t.Fatal("expected hasAccount=true")+ }+}+func TestProfileManagerReset(t *testing.T) {dir := t.TempDir()pm := NewProfileManager(dir)diff --git a/scripts/run_pinchtab.sh b/scripts/run_pinchtab.shnew file mode 100755index 00000000..b8911be7--- /dev/null+++ b/scripts/run_pinchtab.sh@@ -0,0 +1,17 @@+#!/usr/bin/env bash+set -euo pipefail++ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"+BIN_DIR="$ROOT_DIR/bin"+BIN_PATH="$BIN_DIR/pinchtab"++mkdir -p "$BIN_DIR"+cd "$ROOT_DIR"++go build -o "$BIN_PATH" .++if [ "$#" -eq 0 ]; then+ set -- dashboard+fi++exec "$BIN_PATH" "$@"diff --git a/state.go b/state.goindex 8edc129d..681f76b8 100644--- a/state.go+++ b/state.go@@ -12,6 +12,13 @@ import ("github.com/chromedp/chromedp")+var crashedPrefsReplacer = strings.NewReplacer(+ `"exit_type":"Crashed"`, `"exit_type":"Normal"`,+ `"exit_type": "Crashed"`, `"exit_type": "Normal"`,+ `"exited_cleanly":false`, `"exited_cleanly":true`,+ `"exited_cleanly": false`, `"exited_cleanly": true`,+)+type TabState struct {ID string `json:"id"`URL string `json:"url"`@@ -29,8 +36,7 @@ func markCleanExit() {if err != nil {return}- patched := strings.ReplaceAll(string(data), `"exit_type":"Crashed"`, `"exit_type":"Normal"`)- patched = strings.ReplaceAll(patched, `"exited_cleanly":false`, `"exited_cleanly":true`)+ patched := crashedPrefsReplacer.Replace(string(data))if patched != string(data) {if err := os.WriteFile(prefsPath, []byte(patched), 0644); err != nil {slog.Error("patch prefs", "err", err)@@ -44,7 +50,8 @@ func wasUncleanExit() bool {if err != nil {return false}- return strings.Contains(string(data), `"exit_type":"Crashed"`)+ prefs := string(data)+ return strings.Contains(prefs, `"exit_type":"Crashed"`) || strings.Contains(prefs, `"exit_type": "Crashed"`)}func clearChromeSessions() {