Skip to content

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

feat: multi-instance orchestrator

Mariof6e13846e346
diff --git a/dashboard.go b/dashboard.go
index dbe3a357..fa91e372 100644
--- a/dashboard.go
+++ b/dashboard.go
@@ -447,6 +447,97 @@ const dashboardHTML = `<!DOCTYPE html>
.profile-chip .psize { color: #555; margin-left: 8px; }
.profile-chip .psource { color: #f5c542; font-size: 10px; margin-left: 6px; }
+ /* Instances view */
+ .instances-view { height: calc(100vh - 60px); display: flex; flex-direction: column; }
+ .inst-toolbar {
+ padding: 12px 24px;
+ border-bottom: 1px solid #222;
+ display: flex;
+ gap: 8px;
+ }
+ .launch-btn {
+ background: #f5c542;
+ color: #0a0a0a;
+ border: none;
+ padding: 8px 18px;
+ border-radius: 6px;
+ font-weight: bold;
+ cursor: pointer;
+ font-family: inherit;
+ font-size: 13px;
+ }
+ .refresh-btn {
+ background: #333;
+ color: #e0e0e0;
+ border: 1px solid #444;
+ padding: 8px 14px;
+ border-radius: 6px;
+ cursor: pointer;
+ font-family: inherit;
+ font-size: 13px;
+ }
+ .instances-grid {
+ flex: 1;
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));
+ gap: 14px;
+ padding: 16px 24px;
+ overflow-y: auto;
+ align-content: start;
+ }
+ .inst-card {
+ background: #151515;
+ border: 1px solid #222;
+ border-radius: 10px;
+ overflow: hidden;
+ }
+ .inst-card .inst-header {
+ padding: 14px 16px;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ border-bottom: 1px solid #1a1a1a;
+ }
+ .inst-card .inst-name { font-weight: bold; font-size: 16px; color: #f5c542; }
+ .inst-card .inst-badge {
+ font-size: 11px;
+ padding: 3px 10px;
+ border-radius: 10px;
+ font-weight: 600;
+ }
+ .inst-badge.running { background: #064e3b; color: #4ade80; }
+ .inst-badge.starting { background: #422006; color: #fbbf24; }
+ .inst-badge.stopped { background: #1c1917; color: #666; }
+ .inst-badge.error { background: #3a1a1a; color: #f87171; }
+ .inst-card .inst-body { padding: 12px 16px; }
+ .inst-card .inst-row {
+ display: flex;
+ justify-content: space-between;
+ font-size: 13px;
+ padding: 3px 0;
+ }
+ .inst-card .inst-row .label { color: #666; }
+ .inst-card .inst-row .value { color: #ccc; }
+ .inst-card .inst-actions {
+ padding: 10px 16px;
+ border-top: 1px solid #1a1a1a;
+ display: flex;
+ gap: 6px;
+ }
+ .inst-card .inst-actions button {
+ flex: 1;
+ background: #1a1a1a;
+ border: 1px solid #333;
+ color: #aaa;
+ padding: 6px;
+ border-radius: 4px;
+ font-size: 11px;
+ cursor: pointer;
+ font-family: inherit;
+ }
+ .inst-card .inst-actions button:hover { border-color: #f5c542; color: #f5c542; }
+ .inst-card .inst-actions button.danger:hover { border-color: #f87171; color: #f87171; }
+
/* View toggle */
.view-toggle { margin-left: auto; display: flex; gap: 4px; }
.view-btn {
@@ -577,6 +668,7 @@ const dashboardHTML = `<!DOCTYPE html>
<div class="status"><span class="dot"></span>Live</div>
<div class="view-toggle">
<button class="view-btn active" data-view="feed" onclick="switchView('feed')">πŸ“‹ Feed</button>
+ <button class="view-btn" data-view="instances" onclick="switchView('instances')">πŸ–₯️ Instances</button>
<button class="view-btn" data-view="live" onclick="switchView('live')">πŸ“Ί Live</button>
</div>
</header>
@@ -590,6 +682,35 @@ const dashboardHTML = `<!DOCTYPE html>
<div id="screencast-grid" class="screencast-grid"></div>
</div>
+<!-- Instances view -->
+<div id="instances-view" class="instances-view" style="display:none">
+ <div class="inst-toolbar">
+ <button onclick="showLaunchModal()" class="launch-btn">+ Launch Instance</button>
+ <button onclick="loadInstances()" class="refresh-btn">↻ Refresh</button>
+ </div>
+ <div id="instances-grid" class="instances-grid">
+ <div class="empty-state"><div class="crab">πŸ¦€</div>No instances running.<br>Launch one to get started.</div>
+ </div>
+</div>
+
+<!-- Launch modal -->
+<div class="modal-overlay" id="launch-modal">
+ <div class="modal">
+ <h3>πŸ¦€ Launch Instance</h3>
+ <label style="color:#888;font-size:12px;display:block;margin-bottom:4px">Profile Name</label>
+ <input id="launch-name" placeholder="e.g. personal, work, scraping" />
+ <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>
+ <div class="btn-row">
+ <button class="secondary" onclick="closeLaunchModal()">Cancel</button>
+ <button onclick="doLaunch()">Launch</button>
+ </div>
+ </div>
+</div>
+
<!-- Feed view (default) -->
<div id="feed-view" class="container">
<div class="agents-panel">
@@ -839,8 +960,201 @@ function switchView(view) {
document.querySelectorAll('.view-btn').forEach(b => b.classList.remove('active'));
document.querySelector('[data-view="'+view+'"]').classList.add('active');
document.getElementById('feed-view').style.display = view === 'feed' ? 'flex' : 'none';
+ document.getElementById('instances-view').style.display = view === 'instances' ? 'flex' : 'none';
document.getElementById('live-view').style.display = view === 'live' ? 'flex' : 'none';
if (view === 'live') refreshTabs();
+ if (view === 'instances') loadInstances();
+}
+
+// ---------------------------------------------------------------------------
+// Instances
+// ---------------------------------------------------------------------------
+async function loadInstances() {
+ try {
+ const res = await fetch('/instances');
+ const instances = await res.json();
+ const grid = document.getElementById('instances-grid');
+
+ if (!instances || instances.length === 0) {
+ grid.innerHTML = '<div class="empty-state"><div class="crab">πŸ¦€</div>No instances running.<br>Click <b>+ Launch Instance</b> to start one.</div>';
+ return;
+ }
+
+ grid.innerHTML = instances.map(inst => ` + "`" + `
+ <div class="inst-card">
+ <div class="inst-header">
+ <span class="inst-name">${esc(inst.name)}</span>
+ <span class="inst-badge ${inst.status}">${inst.status}</span>
+ </div>
+ <div class="inst-body">
+ <div class="inst-row"><span class="label">Port</span><span class="value">${esc(inst.port)}</span></div>
+ <div class="inst-row"><span class="label">Mode</span><span class="value">${inst.headless ? 'πŸ”² Headless' : 'πŸ–₯️ Headed'}</span></div>
+ <div class="inst-row"><span class="label">Tabs</span><span class="value">${inst.tabCount}</span></div>
+ <div class="inst-row"><span class="label">PID</span><span class="value">${inst.pid || 'β€”'}</span></div>
+ <div class="inst-row"><span class="label">Profile</span><span class="value" style="font-size:11px;max-width:180px;overflow:hidden;text-overflow:ellipsis">${esc(inst.profile)}</span></div>
+ ${inst.error ? '<div class="inst-row"><span class="label">Error</span><span class="value" style="color:#f87171">' + esc(inst.error) + '</span></div>' : ''}
+ </div>
+ <div class="inst-actions">
+ <button onclick="viewInstanceLive('${esc(inst.id)}', '${esc(inst.port)}')">πŸ“Ί Live</button>
+ <button onclick="viewInstanceLogs('${esc(inst.id)}')">πŸ“„ Logs</button>
+ <button onclick="openInstanceDirect('${esc(inst.port)}')">πŸ”— Open</button>
+ ${inst.status === 'running' ? '<button class="danger" onclick="stopInstance(\'' + esc(inst.id) + '\')">⏹ Stop</button>' : ''}
+ </div>
+ </div>
+ ` + "`" + `).join('');
+ } catch (e) {
+ console.error('Failed to load instances', e);
+ }
+}
+
+function showLaunchModal() {
+ document.getElementById('launch-modal').classList.add('open');
+ document.getElementById('launch-name').focus();
+}
+function closeLaunchModal() {
+ document.getElementById('launch-modal').classList.remove('open');
+}
+
+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;
+
+ if (!name || !port) { alert('Name and port required'); return; }
+
+ closeLaunchModal();
+
+ try {
+ const res = await fetch('/instances/launch', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name, port, headless })
+ });
+ const data = await res.json();
+ if (!res.ok) {
+ alert('Launch failed: ' + (data.error || 'unknown'));
+ return;
+ }
+ // Poll until running
+ pollInstanceStatus(data.id);
+ } catch (e) {
+ alert('Launch error: ' + e.message);
+ }
+}
+
+function pollInstanceStatus(id) {
+ let attempts = 0;
+ const poll = setInterval(async () => {
+ attempts++;
+ await loadInstances();
+ if (attempts > 30) clearInterval(poll);
+ 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);
+ loadInstances();
+ }
+ } catch(e) { clearInterval(poll); }
+ }, 1000);
+}
+
+async function stopInstance(id) {
+ if (!confirm('Stop instance ' + id + '?')) return;
+ await fetch('/instances/' + id + '/stop', { method: 'POST' });
+ setTimeout(loadInstances, 1000);
+}
+
+async function viewInstanceLogs(id) {
+ const res = await fetch('/instances/' + id + '/logs');
+ const text = await res.text();
+ const modal = document.getElementById('modal');
+ const title = document.getElementById('modal-title');
+ const body = document.getElementById('modal-body');
+ title.textContent = 'Logs: ' + id;
+ body.innerHTML = '<pre style="background:#0a0a0a;padding:12px;border-radius:6px;font-size:11px;max-height:400px;overflow:auto;color:#aaa;white-space:pre-wrap">' + esc(text) + '</pre><div class="btn-row" style="margin-top:12px"><button class="secondary" onclick="closeModal()">Close</button></div>';
+ modal.classList.add('open');
+}
+
+async function viewInstanceLive(id, port) {
+ // Switch to live view and load tabs from that instance
+ switchView('live');
+ 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>';
+ return;
+ }
+
+ 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('');
+
+ // Connect screencast directly to child instance
+ instTabs.forEach(t => {
+ startScreencastDirect(t.tabId, t.instancePort);
+ });
+ } catch (e) {
+ console.error('Failed to load instance tabs', e);
+ }
+}
+
+function startScreencastDirect(tabId, port) {
+ const wsUrl = 'ws://localhost:' + port + '/screencast?tabId=' + tabId + '&quality=50&maxWidth=800';
+ const socket = new WebSocket(wsUrl);
+ socket.binaryType = 'arraybuffer';
+ screencastSockets[tabId] = socket;
+
+ const canvas = document.getElementById('canvas-' + tabId);
+ 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);
+
+ 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);
+ const img = new Image();
+ img.onload = () => { canvas.width = img.width; canvas.height = img.height; ctx2d.drawImage(img, 0, 0); URL.revokeObjectURL(url); };
+ img.src = url;
+ frameCount++;
+ const now = Date.now();
+ if (now - lastFpsTime >= 1000) {
+ if (fpsEl) fpsEl.textContent = frameCount + ' fps';
+ if (sizeEl) sizeEl.textContent = (evt.data.byteLength / 1024).toFixed(0) + ' KB/frame';
+ frameCount = 0; lastFpsTime = now;
+ }
+ };
+ socket.onerror = () => { if (statusEl) statusEl.className = 'tile-status error'; };
+ socket.onclose = () => { if (statusEl) statusEl.className = 'tile-status error'; };
+}
+
+function openInstanceDirect(port) {
+ window.open('http://localhost:' + port + '/dashboard', '_blank');
}
// ---------------------------------------------------------------------------
diff --git a/main.go b/main.go
index 11eeb2cd..0052df21 100644
--- a/main.go
+++ b/main.go
@@ -225,10 +225,11 @@ func main() {
bridge.initActionRegistry()
bridge.locks = newLockManager()
- // Profile manager + dashboard
+ // Profile manager + dashboard + orchestrator
profilesDir := filepath.Join(filepath.Dir(profileDir), "profiles")
profMgr := NewProfileManager(profilesDir)
dashboard := NewDashboard()
+ orchestrator := NewOrchestrator(profilesDir)
// Register the initial tab
initTargetID := chromedp.FromContext(browserCtx).Target.TargetID
@@ -278,9 +279,12 @@ func main() {
_, _ = w.Write([]byte(welcomeHTML))
})
- // Profile management + dashboard
+ // Profile management + dashboard + orchestrator
profMgr.RegisterHandlers(mux)
dashboard.RegisterHandlers(mux)
+ if os.Getenv("BRIDGE_NO_DASHBOARD") == "" {
+ orchestrator.RegisterHandlers(mux)
+ }
srv := &http.Server{Addr: ":" + port, Handler: dashboard.TrackingMiddleware(profMgr, loggingMiddleware(corsMiddleware(authMiddleware(mux))))}
@@ -289,6 +293,7 @@ func main() {
doShutdown := func() {
shutdownOnce.Do(func() {
slog.Info("shutting down, saving state...")
+ orchestrator.Shutdown()
cleanupCancel()
bridge.SaveState()
markCleanExit()
diff --git a/orchestrator.go b/orchestrator.go
new file mode 100644
index 00000000..527aad2a
--- /dev/null
+++ b/orchestrator.go
@@ -0,0 +1,436 @@
+package main
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "log/slog"
+ "net/http"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "sync"
+ "time"
+)
+
+// ---------------------------------------------------------------------------
+// Orchestrator β€” manages multiple Pinchtab instances from one dashboard
+// ---------------------------------------------------------------------------
+
+type Orchestrator struct {
+ instances map[string]*Instance
+ baseDir string // ~/.pinchtab/profiles
+ binary string // path to pinchtab binary (or "go run .")
+ mu sync.RWMutex
+ client *http.Client
+}
+
+type Instance struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Profile string `json:"profile"`
+ Port string `json:"port"`
+ Headless bool `json:"headless"`
+ Status string `json:"status"` // "starting", "running", "stopped", "error"
+ PID int `json:"pid,omitempty"`
+ StartedAt time.Time `json:"startedAt"`
+ Error string `json:"error,omitempty"`
+ TabCount int `json:"tabCount"`
+ URL string `json:"url"`
+
+ cmd *exec.Cmd
+ cancel context.CancelFunc
+ logBuf *ringBuffer
+}
+
+// ringBuffer keeps the last N bytes of output for log viewing.
+type ringBuffer struct {
+ mu sync.Mutex
+ data []byte
+ max int
+}
+
+func newRingBuffer(max int) *ringBuffer {
+ return &ringBuffer{max: max, data: make([]byte, 0, max)}
+}
+
+func (rb *ringBuffer) Write(p []byte) (int, error) {
+ rb.mu.Lock()
+ defer rb.mu.Unlock()
+ rb.data = append(rb.data, p...)
+ if len(rb.data) > rb.max {
+ rb.data = rb.data[len(rb.data)-rb.max:]
+ }
+ return len(p), nil
+}
+
+func (rb *ringBuffer) String() string {
+ rb.mu.Lock()
+ defer rb.mu.Unlock()
+ return string(rb.data)
+}
+
+func NewOrchestrator(baseDir string) *Orchestrator {
+ // Find the pinchtab binary
+ binary, _ := os.Executable()
+ if binary == "" {
+ binary = os.Args[0]
+ }
+
+ return &Orchestrator{
+ instances: make(map[string]*Instance),
+ baseDir: baseDir,
+ binary: binary,
+ client: &http.Client{Timeout: 3 * time.Second},
+ }
+}
+
+// Launch starts a new Pinchtab instance on a named profile.
+func (o *Orchestrator) Launch(name, port string, headless bool) (*Instance, error) {
+ o.mu.Lock()
+ defer o.mu.Unlock()
+
+ // Check port not already used
+ for _, inst := range o.instances {
+ if inst.Port == port && inst.Status == "running" {
+ return nil, fmt.Errorf("port %s already in use by instance %q", port, inst.Name)
+ }
+ }
+
+ id := fmt.Sprintf("%s-%s", name, port)
+ if inst, ok := o.instances[id]; ok && inst.Status == "running" {
+ return nil, fmt.Errorf("instance %q already running", id)
+ }
+
+ profilePath := filepath.Join(o.baseDir, name)
+ os.MkdirAll(filepath.Join(profilePath, "Default"), 0755)
+
+ ctx, cancel := context.WithCancel(context.Background())
+
+ headlessStr := "true"
+ if !headless {
+ headlessStr = "false"
+ }
+
+ cmd := exec.CommandContext(ctx, o.binary)
+ cmd.Env = append(os.Environ(),
+ "BRIDGE_PORT="+port,
+ "BRIDGE_PROFILE="+profilePath,
+ "BRIDGE_HEADLESS="+headlessStr,
+ "BRIDGE_NO_RESTORE=true",
+ // Don't start sub-orchestrators
+ "BRIDGE_NO_DASHBOARD=true",
+ )
+
+ logBuf := newRingBuffer(64 * 1024) // 64KB log buffer
+ cmd.Stdout = logBuf
+ cmd.Stderr = logBuf
+
+ inst := &Instance{
+ ID: id,
+ Name: name,
+ Profile: profilePath,
+ Port: port,
+ Headless: headless,
+ Status: "starting",
+ StartedAt: time.Now(),
+ URL: fmt.Sprintf("http://localhost:%s", port),
+ cmd: cmd,
+ cancel: cancel,
+ logBuf: logBuf,
+ }
+
+ if err := cmd.Start(); err != nil {
+ cancel()
+ return nil, fmt.Errorf("failed to start: %w", err)
+ }
+
+ inst.PID = cmd.Process.Pid
+ o.instances[id] = inst
+
+ // Monitor process + wait for healthy
+ go o.monitor(inst)
+
+ return inst, nil
+}
+
+func (o *Orchestrator) monitor(inst *Instance) {
+ // Wait for health check to pass
+ 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
+ }
+ }
+ }
+
+ 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)
+ }
+ o.mu.Unlock()
+
+ // Wait for process to exit
+ err := inst.cmd.Wait()
+ o.mu.Lock()
+ if inst.Status != "stopped" {
+ inst.Status = "stopped"
+ if err != nil {
+ inst.Error = err.Error()
+ }
+ }
+ o.mu.Unlock()
+ slog.Info("instance exited", "id", inst.ID)
+}
+
+// Stop kills a running instance.
+func (o *Orchestrator) Stop(id string) error {
+ o.mu.Lock()
+ inst, ok := o.instances[id]
+ if !ok {
+ o.mu.Unlock()
+ return fmt.Errorf("instance %q not found", id)
+ }
+ inst.Status = "stopped"
+ o.mu.Unlock()
+
+ // Graceful shutdown via API first
+ req, _ := http.NewRequest("POST", inst.URL+"/shutdown", nil)
+ resp, err := o.client.Do(req)
+ if err == nil {
+ resp.Body.Close()
+ // Wait a moment for graceful exit
+ time.Sleep(2 * time.Second)
+ }
+
+ // Force kill if still running
+ if inst.cmd.ProcessState == nil || !inst.cmd.ProcessState.Exited() {
+ inst.cancel()
+ }
+
+ return nil
+}
+
+// List returns all instances with live status.
+func (o *Orchestrator) List() []Instance {
+ o.mu.RLock()
+ defer o.mu.RUnlock()
+
+ result := make([]Instance, 0, len(o.instances))
+ for _, inst := range o.instances {
+ copy := *inst
+ copy.cmd = nil
+ copy.cancel = nil
+ copy.logBuf = nil
+
+ // Fetch live tab count for running instances
+ if inst.Status == "running" {
+ if tabs, err := o.fetchTabs(inst.URL); err == nil {
+ copy.TabCount = len(tabs)
+ }
+ }
+
+ result = append(result, copy)
+ }
+ return result
+}
+
+// Logs returns the log buffer for an instance.
+func (o *Orchestrator) Logs(id string) (string, error) {
+ o.mu.RLock()
+ defer o.mu.RUnlock()
+
+ inst, ok := o.instances[id]
+ if !ok {
+ return "", fmt.Errorf("instance %q not found", id)
+ }
+ return inst.logBuf.String(), nil
+}
+
+// AllTabs aggregates tabs from all running instances.
+func (o *Orchestrator) AllTabs() []instanceTab {
+ o.mu.RLock()
+ instances := make([]*Instance, 0)
+ for _, inst := range o.instances {
+ if inst.Status == "running" {
+ instances = append(instances, inst)
+ }
+ }
+ o.mu.RUnlock()
+
+ var all []instanceTab
+ for _, inst := range instances {
+ tabs, err := o.fetchTabs(inst.URL)
+ if err != nil {
+ continue
+ }
+ for _, t := range tabs {
+ all = append(all, instanceTab{
+ InstanceID: inst.ID,
+ InstanceName: inst.Name,
+ InstancePort: inst.Port,
+ TabID: t.ID,
+ URL: t.URL,
+ })
+ }
+ }
+ return all
+}
+
+type instanceTab struct {
+ InstanceID string `json:"instanceId"`
+ InstanceName string `json:"instanceName"`
+ InstancePort string `json:"instancePort"`
+ TabID string `json:"tabId"`
+ URL string `json:"url"`
+}
+
+type remoteTab struct {
+ ID string `json:"id"`
+ URL string `json:"url"`
+}
+
+func (o *Orchestrator) fetchTabs(baseURL string) ([]remoteTab, error) {
+ resp, err := o.client.Get(baseURL + "/screencast/tabs")
+ if err != nil {
+ return nil, err
+ }
+ defer resp.Body.Close()
+ var tabs []remoteTab
+ json.NewDecoder(resp.Body).Decode(&tabs)
+ return tabs, nil
+}
+
+// ---------------------------------------------------------------------------
+// HTTP Handlers
+// ---------------------------------------------------------------------------
+
+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 /instances/{id}/logs", o.handleLogs)
+ mux.HandleFunc("GET /instances/tabs", o.handleAllTabs)
+ mux.HandleFunc("GET /instances/{id}/proxy/screencast", o.handleProxyScreencast)
+}
+
+func (o *Orchestrator) handleList(w http.ResponseWriter, r *http.Request) {
+ jsonResp(w, 200, o.List())
+}
+
+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"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ jsonErr(w, 400, fmt.Errorf("invalid JSON"))
+ return
+ }
+ if req.Name == "" || req.Port == "" {
+ jsonErr(w, 400, fmt.Errorf("name and port required"))
+ return
+ }
+ headless := true
+ if req.Headless != nil {
+ headless = *req.Headless
+ }
+
+ inst, err := o.Launch(req.Name, req.Port, headless)
+ if err != nil {
+ jsonErr(w, 409, err)
+ return
+ }
+ jsonResp(w, 201, inst)
+}
+
+func (o *Orchestrator) handleStop(w http.ResponseWriter, r *http.Request) {
+ id := r.PathValue("id")
+ if err := o.Stop(id); err != nil {
+ jsonErr(w, 404, err)
+ return
+ }
+ jsonResp(w, 200, map[string]string{"status": "stopped", "id": id})
+}
+
+func (o *Orchestrator) handleLogs(w http.ResponseWriter, r *http.Request) {
+ id := r.PathValue("id")
+ logs, err := o.Logs(id)
+ if err != nil {
+ jsonErr(w, 404, err)
+ return
+ }
+ w.Header().Set("Content-Type", "text/plain")
+ w.Write([]byte(logs))
+}
+
+func (o *Orchestrator) handleAllTabs(w http.ResponseWriter, r *http.Request) {
+ jsonResp(w, 200, o.AllTabs())
+}
+
+// handleProxyScreencast proxies a WebSocket screencast from a child instance.
+func (o *Orchestrator) handleProxyScreencast(w http.ResponseWriter, r *http.Request) {
+ id := r.PathValue("id")
+ tabID := r.URL.Query().Get("tabId")
+
+ o.mu.RLock()
+ inst, ok := o.instances[id]
+ o.mu.RUnlock()
+ if !ok || inst.Status != "running" {
+ http.Error(w, "instance not found or not running", 404)
+ return
+ }
+
+ // Proxy the WebSocket connection to the child instance
+ // For now, redirect β€” the dashboard JS will connect directly
+ targetURL := fmt.Sprintf("ws://localhost:%s/screencast?tabId=%s", inst.Port, tabID)
+ jsonResp(w, 200, map[string]string{"wsUrl": targetURL})
+}
+
+// ProxyScreencastURL returns the WebSocket URL for a child instance's screencast.
+func (o *Orchestrator) ScreencastURL(instanceID, tabID string) string {
+ o.mu.RLock()
+ defer o.mu.RUnlock()
+ inst, ok := o.instances[instanceID]
+ if !ok {
+ return ""
+ }
+ return fmt.Sprintf("ws://localhost:%s/screencast?tabId=%s", inst.Port, tabID)
+}
+
+// ---------------------------------------------------------------------------
+// Cleanup β€” stop all instances on shutdown
+// ---------------------------------------------------------------------------
+
+func (o *Orchestrator) Shutdown() {
+ o.mu.RLock()
+ ids := make([]string, 0, len(o.instances))
+ for id, inst := range o.instances {
+ if inst.Status == "running" {
+ ids = append(ids, id)
+ }
+ }
+ o.mu.RUnlock()
+
+ for _, id := range ids {
+ slog.Info("stopping instance", "id", id)
+ o.Stop(id)
+ }
+}
+
+// readAll reads response body up to limit bytes
+func readAll(r io.Reader, limit int64) ([]byte, error) {
+ return io.ReadAll(io.LimitReader(r, limit))
+}