Skip to content

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

chore(handlers): rename test files to match source files (#88)

luigiagent7481c39b8cf5
diff --git a/internal/handlers/handler_actions_test.go b/internal/handlers/actions_test.go
similarity index 96%
rename from internal/handlers/handler_actions_test.go
rename to internal/handlers/actions_test.go
index afb114f6..f5960e7d 100644
--- a/internal/handlers/handler_actions_test.go
+++ b/internal/handlers/actions_test.go
@@ -272,3 +272,13 @@ func TestCountSuccessful(t *testing.T) {
t.Errorf("expected 3 successful, got %d", count)
}
}
+
+func TestHandleAction_InvalidJSON(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("POST", "/action", bytes.NewReader([]byte(`not json`)))
+ w := httptest.NewRecorder()
+ h.HandleAction(w, req)
+ if w.Code != 400 {
+ t.Errorf("expected 400, got %d", w.Code)
+ }
+}
diff --git a/internal/handlers/handler_cookies_test.go b/internal/handlers/cookies_test.go
similarity index 100%
rename from internal/handlers/handler_cookies_test.go
rename to internal/handlers/cookies_test.go
diff --git a/internal/handlers/handler_download_test.go b/internal/handlers/download_test.go
similarity index 100%
rename from internal/handlers/handler_download_test.go
rename to internal/handlers/download_test.go
diff --git a/internal/handlers/evaluate.go b/internal/handlers/evaluate.go
new file mode 100644
index 00000000..b688f13b
--- /dev/null
+++ b/internal/handlers/evaluate.go
@@ -0,0 +1,93 @@
+package handlers
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+
+ "github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/web"
+)
+
+// HandleEvaluate runs JavaScript in the current tab.
+//
+// @Endpoint POST /evaluate
+func (h *Handlers) HandleEvaluate(w http.ResponseWriter, r *http.Request) {
+ var req struct {
+ TabID string `json:"tabId"`
+ Expression string `json:"expression"`
+ }
+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
+ web.Error(w, 400, fmt.Errorf("decode: %w", err))
+ return
+ }
+ if req.Expression == "" {
+ web.Error(w, 400, fmt.Errorf("expression required"))
+ return
+ }
+
+ ctx, _, err := h.Bridge.TabContext(req.TabID)
+ if err != nil {
+ web.Error(w, 404, err)
+ return
+ }
+
+ tCtx, tCancel := context.WithTimeout(ctx, h.Config.ActionTimeout)
+ defer tCancel()
+ go web.CancelOnClientDone(r.Context(), tCancel)
+
+ var result any
+ if err := chromedp.Run(tCtx, chromedp.Evaluate(req.Expression, &result)); err != nil {
+ web.Error(w, 500, fmt.Errorf("evaluate: %w", err))
+ return
+ }
+
+ web.JSON(w, 200, map[string]any{"result": result})
+}
+
+// HandleTabEvaluate runs JavaScript in a tab identified by path ID.
+//
+// @Endpoint POST /tabs/{id}/evaluate
+func (h *Handlers) HandleTabEvaluate(w http.ResponseWriter, r *http.Request) {
+ tabID := r.PathValue("id")
+ if tabID == "" {
+ web.Error(w, 400, fmt.Errorf("tab id required"))
+ return
+ }
+
+ body := map[string]any{}
+ dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize))
+ if err := dec.Decode(&body); err != nil && !errors.Is(err, io.EOF) {
+ web.Error(w, 400, fmt.Errorf("decode: %w", err))
+ return
+ }
+
+ if rawTabID, ok := body["tabId"]; ok {
+ if provided, ok := rawTabID.(string); !ok || provided == "" {
+ web.Error(w, 400, fmt.Errorf("invalid tabId"))
+ return
+ } else if provided != tabID {
+ web.Error(w, 400, fmt.Errorf("tabId in body does not match path id"))
+ return
+ }
+ }
+
+ body["tabId"] = tabID
+
+ payload, err := json.Marshal(body)
+ if err != nil {
+ web.Error(w, 500, fmt.Errorf("encode: %w", err))
+ return
+ }
+
+ req := r.Clone(r.Context())
+ req.Body = io.NopCloser(bytes.NewReader(payload))
+ req.ContentLength = int64(len(payload))
+ req.Header = r.Header.Clone()
+ req.Header.Set("Content-Type", "application/json")
+ h.HandleEvaluate(w, req)
+}
diff --git a/internal/handlers/evaluate_test.go b/internal/handlers/evaluate_test.go
new file mode 100644
index 00000000..eb066365
--- /dev/null
+++ b/internal/handlers/evaluate_test.go
@@ -0,0 +1,51 @@
+package handlers
+
+import (
+ "bytes"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func TestHandleEvaluate_InvalidJSON(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("POST", "/evaluate", bytes.NewReader([]byte(`not json`)))
+ w := httptest.NewRecorder()
+ h.HandleEvaluate(w, req)
+ if w.Code != 400 {
+ t.Errorf("expected 400, got %d", w.Code)
+ }
+}
+
+func TestHandleTabEvaluate_MissingTabID(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("POST", "/tabs//evaluate", bytes.NewReader([]byte(`{"expression":"1+1"}`)))
+ w := httptest.NewRecorder()
+ h.HandleTabEvaluate(w, req)
+ if w.Code != 400 {
+ t.Errorf("expected 400, got %d", w.Code)
+ }
+}
+
+func TestHandleTabEvaluate_TabIDMismatch(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("POST", "/tabs/tab_abc/evaluate", bytes.NewReader([]byte(`{"tabId":"tab_other","expression":"1+1"}`)))
+ req.SetPathValue("id", "tab_abc")
+ w := httptest.NewRecorder()
+ h.HandleTabEvaluate(w, req)
+ if w.Code != 400 {
+ t.Errorf("expected 400, got %d", w.Code)
+ }
+}
+
+func TestHandleTabEvaluate_NoTab(t *testing.T) {
+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("POST", "/tabs/tab_abc/evaluate", bytes.NewReader([]byte(`{"expression":"1+1"}`)))
+ req.SetPathValue("id", "tab_abc")
+ w := httptest.NewRecorder()
+ h.HandleTabEvaluate(w, req)
+ if w.Code != 404 {
+ t.Errorf("expected 404, got %d", w.Code)
+ }
+}
diff --git a/internal/handlers/handler_stealth_test.go b/internal/handlers/handler_stealth_test.go
deleted file mode 100644
index 649447ca..00000000
--- a/internal/handlers/handler_stealth_test.go
+++ /dev/null
@@ -1,130 +0,0 @@
-package handlers
-
-import (
- "bytes"
- "net/http/httptest"
- "testing"
-
- "github.com/pinchtab/pinchtab/internal/config"
-)
-
-func TestHandleStealthStatus_NoTab_ReturnsStatic(t *testing.T) {
- h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
- req := httptest.NewRequest("GET", "/stealth/status", nil)
- w := httptest.NewRecorder()
-
- h.HandleStealthStatus(w, req)
-
- if w.Code != 200 {
- t.Errorf("expected 200, got %d", w.Code)
- }
-
- body := w.Body.String()
- if !searchString(body, "level") || !searchString(body, "score") {
- t.Errorf("expected level and score in response, got: %s", body)
- }
-}
-
-func TestHandleFingerprintRotate_InvalidJSON(t *testing.T) {
- h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
- req := httptest.NewRequest("POST", "/fingerprint/rotate", bytes.NewReader([]byte(`not json`)))
- w := httptest.NewRecorder()
-
- h.HandleFingerprintRotate(w, req)
-
- if w.Code != 400 {
- t.Errorf("expected 400, got %d", w.Code)
- }
-}
-
-func TestGenerateFingerprint_Windows(t *testing.T) {
- h := Handlers{Config: &config.RuntimeConfig{ChromeVersion: "120.0.0.0"}}
- fp := h.generateFingerprint(fingerprintRequest{OS: "windows"})
- if fp.Platform != "Win32" {
- t.Errorf("expected Win32, got %q", fp.Platform)
- }
- if fp.UserAgent == "" {
- t.Error("expected non-empty user agent")
- }
- if fp.ScreenWidth == 0 || fp.ScreenHeight == 0 {
- t.Error("expected non-zero screen dimensions")
- }
- if fp.Vendor != "Google Inc." {
- t.Errorf("expected Google Inc., got %q", fp.Vendor)
- }
-}
-
-func TestGenerateFingerprint_Mac(t *testing.T) {
- h := Handlers{Config: &config.RuntimeConfig{ChromeVersion: "120.0.0.0"}}
- fp := h.generateFingerprint(fingerprintRequest{OS: "mac"})
- if fp.Platform != "MacIntel" {
- t.Errorf("expected MacIntel, got %q", fp.Platform)
- }
-}
-
-func TestGenerateFingerprint_Random(t *testing.T) {
- h := Handlers{Config: &config.RuntimeConfig{ChromeVersion: "120.0.0.0"}}
- fp := h.generateFingerprint(fingerprintRequest{OS: "random"})
- validPlatforms := map[string]bool{"Win32": true, "MacIntel": true}
- if !validPlatforms[fp.Platform] {
- t.Errorf("unexpected platform %q", fp.Platform)
- }
-}
-
-func TestGenerateFingerprint_WithBrowser(t *testing.T) {
- h := Handlers{Config: &config.RuntimeConfig{ChromeVersion: "120.0.0.0"}}
- fp := h.generateFingerprint(fingerprintRequest{OS: "windows", Browser: "chrome"})
- if fp.UserAgent == "" {
- t.Error("expected non-empty user agent")
- }
-}
-
-func TestGetStealthRecommendations_AllEnabled(t *testing.T) {
- h := Handlers{}
- features := map[string]bool{
- "user_agent_override": true,
- "languages_spoofed": true,
- "webrtc_leak_prevented": true,
- "timezone_spoofed": true,
- "canvas_noise": true,
- "font_spoofing": true,
- }
- recs := h.getStealthRecommendations(features)
- if len(recs) != 1 || recs[0] != "Stealth mode is well configured" {
- t.Errorf("expected well-configured message, got %v", recs)
- }
-}
-
-func TestGetStealthRecommendations_NoneEnabled(t *testing.T) {
- h := Handlers{}
- features := map[string]bool{}
- recs := h.getStealthRecommendations(features)
- if len(recs) != 6 {
- t.Errorf("expected 6 recommendations, got %d: %v", len(recs), recs)
- }
-}
-
-func TestSendStealthResponse_HighScore(t *testing.T) {
- h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
- features := map[string]bool{
- "a": true, "b": true, "c": true, "d": true, "e": true,
- }
- w := httptest.NewRecorder()
- h.sendStealthResponse(w, features, "TestAgent/1.0")
-
- if w.Code != 200 {
- t.Errorf("expected 200, got %d", w.Code)
- }
- body := w.Body.String()
- if !searchString(body, `"level":"high"`) {
- t.Errorf("expected high level for 100%% score, got: %s", body)
- }
-}
-
-func TestStaticStealthFeatures_HasEntries(t *testing.T) {
- h := Handlers{Config: &config.RuntimeConfig{}}
- features := h.staticStealthFeatures()
- if len(features) == 0 {
- t.Error("expected non-empty stealth features map")
- }
-}
diff --git a/internal/handlers/handler_upload_test.go b/internal/handlers/handler_upload_test.go
deleted file mode 100644
index b34201ce..00000000
--- a/internal/handlers/handler_upload_test.go
+++ /dev/null
@@ -1,81 +0,0 @@
-package handlers
-
-import (
- "bytes"
- "net/http"
- "net/http/httptest"
- "testing"
-
- "github.com/pinchtab/pinchtab/internal/config"
-)
-
-func TestHandleUpload_BadJSON(t *testing.T) {
- h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
- req := httptest.NewRequest("POST", "/upload", bytes.NewReader([]byte("not json")))
- req.Header.Set("Content-Type", "application/json")
- w := httptest.NewRecorder()
- h.HandleUpload(w, req)
- if w.Code != http.StatusBadRequest {
- t.Errorf("expected 400 for bad JSON, got %d", w.Code)
- }
-}
-
-func TestHandleUpload_EmptyPaths(t *testing.T) {
- h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
- body := `{"selector": "input[type=file]"}`
- req := httptest.NewRequest("POST", "/upload", bytes.NewReader([]byte(body)))
- req.Header.Set("Content-Type", "application/json")
- w := httptest.NewRecorder()
- h.HandleUpload(w, req)
- if w.Code != http.StatusBadRequest {
- t.Errorf("expected 400 for empty paths, got %d", w.Code)
- }
-}
-
-func TestHandleUpload_NonexistentPath(t *testing.T) {
- h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
- body := `{"selector": "input[type=file]", "paths": ["/tmp/nonexistent-file-12345.jpg"]}`
- req := httptest.NewRequest("POST", "/upload", bytes.NewReader([]byte(body)))
- req.Header.Set("Content-Type", "application/json")
- w := httptest.NewRecorder()
- h.HandleUpload(w, req)
- if w.Code != http.StatusBadRequest {
- t.Errorf("expected 400 for nonexistent path, got %d", w.Code)
- }
-}
-
-func TestHandleTabUpload_MissingTabID(t *testing.T) {
- h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
- req := httptest.NewRequest("POST", "/tabs//upload", bytes.NewReader([]byte(`{"selector":"input[type=file]"}`)))
- req.Header.Set("Content-Type", "application/json")
- w := httptest.NewRecorder()
- h.HandleTabUpload(w, req)
- if w.Code != http.StatusBadRequest {
- t.Errorf("expected 400, got %d", w.Code)
- }
-}
-
-func TestHandleTabUpload_NoTab(t *testing.T) {
- h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)
- req := httptest.NewRequest("POST", "/tabs/tab_abc/upload", bytes.NewReader([]byte(`{"files":["aGVsbG8="]}`)))
- req.SetPathValue("id", "tab_abc")
- req.Header.Set("Content-Type", "application/json")
- w := httptest.NewRecorder()
- h.HandleTabUpload(w, req)
- if w.Code != http.StatusNotFound {
- t.Errorf("expected 404, got %d", w.Code)
- }
-}
-
-func TestHandleUpload_BodyTooLarge(t *testing.T) {
- h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
- // Create a body larger than 10MB
- bigBody := make([]byte, 11<<20) // 11MB
- req := httptest.NewRequest("POST", "/upload", bytes.NewReader(bigBody))
- req.Header.Set("Content-Type", "application/json")
- w := httptest.NewRecorder()
- h.HandleUpload(w, req)
- if w.Code != http.StatusBadRequest {
- t.Errorf("expected 400 for oversized body, got %d", w.Code)
- }
-}
diff --git a/internal/handlers/handlers_extra_test.go b/internal/handlers/handlers_extra_test.go
deleted file mode 100644
index fcf5e694..00000000
--- a/internal/handlers/handlers_extra_test.go
+++ /dev/null
@@ -1,187 +0,0 @@
-package handlers
-
-import (
- "bytes"
- "fmt"
- "net/http/httptest"
- "testing"
- "time"
-
- "github.com/chromedp/cdproto/target"
- "github.com/pinchtab/pinchtab/internal/config"
-)
-
-type mockBridgeDisconnected struct {
- mockBridge
-}
-
-func (m *mockBridgeDisconnected) ListTargets() ([]*target.Info, error) {
- return nil, fmt.Errorf("disconnected")
-}
-
-func TestHandleHealth_Disconnected_Returns503(t *testing.T) {
- mb := &mockBridgeDisconnected{}
- h := New(mb, &config.RuntimeConfig{}, nil, nil, nil)
- req := httptest.NewRequest("GET", "/health", nil)
- w := httptest.NewRecorder()
- h.HandleHealth(w, req)
- if w.Code != 503 {
- t.Errorf("expected 503 for disconnected browser, got %d", w.Code)
- }
-}
-
-func TestHandleHealth_Connected_Returns200(t *testing.T) {
- h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
- req := httptest.NewRequest("GET", "/health", nil)
- w := httptest.NewRecorder()
- h.HandleHealth(w, req)
- if w.Code != 200 {
- t.Errorf("expected 200 for connected browser, got %d", w.Code)
- }
-}
-
-func TestHandleHealth_Response(t *testing.T) {
- h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
- req := httptest.NewRequest("GET", "/health", nil)
- w := httptest.NewRecorder()
- h.HandleHealth(w, req)
- if w.Code != 200 {
- t.Errorf("expected 200, got %d", w.Code)
- }
- if ct := w.Header().Get("Content-Type"); ct != "application/json" {
- t.Errorf("expected application/json, got %s", ct)
- }
-}
-
-func TestHandleNavigate_InvalidJSON(t *testing.T) {
- h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
- req := httptest.NewRequest("POST", "/navigate", bytes.NewReader([]byte(`not json`)))
- w := httptest.NewRecorder()
- h.HandleNavigate(w, req)
- if w.Code != 400 {
- t.Errorf("expected 400, got %d", w.Code)
- }
-}
-
-func TestHandleTabNavigate_MissingTabID(t *testing.T) {
- h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
- req := httptest.NewRequest("POST", "/tabs//navigate", bytes.NewReader([]byte(`{"url":"https://example.com"}`)))
- w := httptest.NewRecorder()
- h.HandleTabNavigate(w, req)
- if w.Code != 400 {
- t.Errorf("expected 400, got %d", w.Code)
- }
-}
-
-func TestHandleTabNavigate_TabIDMismatch(t *testing.T) {
- h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
- req := httptest.NewRequest("POST", "/tabs/tab_abc/navigate", bytes.NewReader([]byte(`{"tabId":"tab_other","url":"https://example.com"}`)))
- req.SetPathValue("id", "tab_abc")
- w := httptest.NewRecorder()
- h.HandleTabNavigate(w, req)
- if w.Code != 400 {
- t.Errorf("expected 400, got %d", w.Code)
- }
-}
-
-func TestHandleEvaluate_InvalidJSON(t *testing.T) {
- h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
- req := httptest.NewRequest("POST", "/evaluate", bytes.NewReader([]byte(`not json`)))
- w := httptest.NewRecorder()
- h.HandleEvaluate(w, req)
- if w.Code != 400 {
- t.Errorf("expected 400, got %d", w.Code)
- }
-}
-
-func TestHandleTabEvaluate_MissingTabID(t *testing.T) {
- h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
- req := httptest.NewRequest("POST", "/tabs//evaluate", bytes.NewReader([]byte(`{"expression":"1+1"}`)))
- w := httptest.NewRecorder()
- h.HandleTabEvaluate(w, req)
- if w.Code != 400 {
- t.Errorf("expected 400, got %d", w.Code)
- }
-}
-
-func TestHandleTabEvaluate_TabIDMismatch(t *testing.T) {
- h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
- req := httptest.NewRequest("POST", "/tabs/tab_abc/evaluate", bytes.NewReader([]byte(`{"tabId":"tab_other","expression":"1+1"}`)))
- req.SetPathValue("id", "tab_abc")
- w := httptest.NewRecorder()
- h.HandleTabEvaluate(w, req)
- if w.Code != 400 {
- t.Errorf("expected 400, got %d", w.Code)
- }
-}
-
-func TestHandleTabEvaluate_NoTab(t *testing.T) {
- h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)
- req := httptest.NewRequest("POST", "/tabs/tab_abc/evaluate", bytes.NewReader([]byte(`{"expression":"1+1"}`)))
- req.SetPathValue("id", "tab_abc")
- w := httptest.NewRecorder()
- h.HandleTabEvaluate(w, req)
- if w.Code != 404 {
- t.Errorf("expected 404, got %d", w.Code)
- }
-}
-
-func TestHandleTab_InvalidJSON(t *testing.T) {
- h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
- req := httptest.NewRequest("POST", "/tab", bytes.NewReader([]byte(`not json`)))
- w := httptest.NewRecorder()
- h.HandleTab(w, req)
- if w.Code != 400 {
- t.Errorf("expected 400, got %d", w.Code)
- }
-}
-
-func TestHandleTab_InvalidAction(t *testing.T) {
- h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
- body := `{"action":"invalid"}`
- req := httptest.NewRequest("POST", "/tab", bytes.NewReader([]byte(body)))
- w := httptest.NewRecorder()
- h.HandleTab(w, req)
- if w.Code != 400 {
- t.Errorf("expected 400, got %d", w.Code)
- }
-}
-
-func TestHandleTab_CloseMissingID(t *testing.T) {
- h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
- body := `{"action":"close"}`
- req := httptest.NewRequest("POST", "/tab", bytes.NewReader([]byte(body)))
- w := httptest.NewRecorder()
- h.HandleTab(w, req)
- if w.Code != 400 {
- t.Errorf("expected 400, got %d", w.Code)
- }
-}
-
-func TestHandleAction_InvalidJSON(t *testing.T) {
- h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
- req := httptest.NewRequest("POST", "/action", bytes.NewReader([]byte(`not json`)))
- w := httptest.NewRecorder()
- h.HandleAction(w, req)
- if w.Code != 400 {
- t.Errorf("expected 400, got %d", w.Code)
- }
-}
-
-func TestHandleShutdown_CallsFunc(t *testing.T) {
- called := make(chan bool, 1)
- doShutdown := func() { called <- true }
- h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
- handler := h.HandleShutdown(doShutdown)
- req := httptest.NewRequest("POST", "/shutdown", nil)
- w := httptest.NewRecorder()
- handler(w, req)
- if w.Code != 200 {
- t.Errorf("expected 200, got %d", w.Code)
- }
- select {
- case <-called:
- case <-time.After(500 * time.Millisecond):
- t.Error("expected doShutdown to be called within 500ms")
- }
-}
diff --git a/internal/handlers/handler_test.go b/internal/handlers/handlers_test.go
similarity index 87%
rename from internal/handlers/handler_test.go
rename to internal/handlers/handlers_test.go
index dc991c22..26b0bf78 100644
--- a/internal/handlers/handler_test.go
+++ b/internal/handlers/handlers_test.go
@@ -162,3 +162,32 @@ func searchString(s, substr string) bool {
}
return false
}
+
+func TestRoutesRegistration(t *testing.T) {
+ b := &mockBridge{}
+ cfg := &config.RuntimeConfig{}
+ h := New(b, cfg, nil, nil, nil)
+
+ mux := http.NewServeMux()
+ h.RegisterRoutes(mux, func() {})
+
+ tests := []struct {
+ method string
+ path string
+ code int
+ }{
+ {"GET", "/health", 200},
+ {"GET", "/tabs", 200},
+ {"GET", "/welcome", 200},
+ {"POST", "/navigate", 400}, // missing body
+ }
+
+ for _, tt := range tests {
+ req := httptest.NewRequest(tt.method, tt.path, nil)
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+ if w.Code != tt.code {
+ t.Errorf("%s %s expected %d, got %d", tt.method, tt.path, tt.code, w.Code)
+ }
+ }
+}
diff --git a/internal/handlers/health_tabs_test.go b/internal/handlers/health_tabs_test.go
index 8992f395..bb9a06f8 100644
--- a/internal/handlers/health_tabs_test.go
+++ b/internal/handlers/health_tabs_test.go
@@ -333,3 +333,45 @@ func (m *MockBridge) EnsureChrome(cfg *config.RuntimeConfig) error {
}
return nil
}
+
+type mockBridgeDisconnected struct {
+ mockBridge
+}
+
+func (m *mockBridgeDisconnected) ListTargets() ([]*target.Info, error) {
+ return nil, fmt.Errorf("disconnected")
+}
+
+func TestHandleHealth_Disconnected_Returns503(t *testing.T) {
+ mb := &mockBridgeDisconnected{}
+ h := New(mb, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("GET", "/health", nil)
+ w := httptest.NewRecorder()
+ h.HandleHealth(w, req)
+ if w.Code != 503 {
+ t.Errorf("expected 503 for disconnected browser, got %d", w.Code)
+ }
+}
+
+func TestHandleHealth_Connected_Returns200(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("GET", "/health", nil)
+ w := httptest.NewRecorder()
+ h.HandleHealth(w, req)
+ if w.Code != 200 {
+ t.Errorf("expected 200 for connected browser, got %d", w.Code)
+ }
+}
+
+func TestHandleHealth_Response(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("GET", "/health", nil)
+ w := httptest.NewRecorder()
+ h.HandleHealth(w, req)
+ if w.Code != 200 {
+ t.Errorf("expected 200, got %d", w.Code)
+ }
+ if ct := w.Header().Get("Content-Type"); ct != "application/json" {
+ t.Errorf("expected application/json, got %s", ct)
+ }
+}
diff --git a/internal/handlers/integration_test.go b/internal/handlers/integration_test.go
deleted file mode 100644
index 491cde45..00000000
--- a/internal/handlers/integration_test.go
+++ /dev/null
@@ -1,80 +0,0 @@
-package handlers
-
-import (
- "context"
- "fmt"
- "net/http"
- "net/http/httptest"
- "testing"
-
- "github.com/chromedp/cdproto/target"
- "github.com/pinchtab/pinchtab/internal/assets"
- "github.com/pinchtab/pinchtab/internal/bridge"
- "github.com/pinchtab/pinchtab/internal/config"
-)
-
-type integrationMockBridge struct {
- bridge.BridgeAPI
- tabs map[string]context.Context
-}
-
-func (m *integrationMockBridge) TabContext(tabID string) (context.Context, string, error) {
- if tabID == "" {
- return context.Background(), "tab1", nil
- }
- ctx, ok := m.tabs[tabID]
- if !ok {
- return nil, "", fmt.Errorf("not found")
- }
- return ctx, tabID, nil
-}
-
-func (m *integrationMockBridge) ListTargets() ([]*target.Info, error) {
- return []*target.Info{{TargetID: "tab1", Type: "page"}}, nil
-}
-
-func (m *integrationMockBridge) TabLockInfo(tabID string) *bridge.LockInfo {
- return nil
-}
-
-func (m *integrationMockBridge) EnsureChrome(cfg *config.RuntimeConfig) error {
- return nil
-}
-
-func TestIntegration_RoutesRegistration(t *testing.T) {
- b := &integrationMockBridge{tabs: make(map[string]context.Context)}
- cfg := &config.RuntimeConfig{}
- h := New(b, cfg, nil, nil, nil)
-
- mux := http.NewServeMux()
- h.RegisterRoutes(mux, func() {})
-
- tests := []struct {
- method string
- path string
- code int
- }{
- {"GET", "/health", 200},
- {"GET", "/tabs", 200},
- {"GET", "/welcome", 200},
- {"POST", "/navigate", 400}, // missing body
- }
-
- for _, tt := range tests {
- req := httptest.NewRequest(tt.method, tt.path, nil)
- w := httptest.NewRecorder()
- mux.ServeHTTP(w, req)
- if w.Code != tt.code {
- t.Errorf("%s %s expected %d, got %d", tt.method, tt.path, tt.code, w.Code)
- }
- }
-}
-
-func TestIntegration_StealthInjection(t *testing.T) {
- b := bridge.New(context.Background(), context.Background(), &config.RuntimeConfig{})
- b.StealthScript = assets.StealthScript
-
- if b.StealthScript == "" {
- t.Error("expected stealth script to be populated")
- }
-}
diff --git a/internal/handlers/lock_handler_test.go b/internal/handlers/lock_shutdown_test.go
similarity index 89%
rename from internal/handlers/lock_handler_test.go
rename to internal/handlers/lock_shutdown_test.go
index 413e14a2..7f151c70 100644
--- a/internal/handlers/lock_handler_test.go
+++ b/internal/handlers/lock_shutdown_test.go
@@ -136,3 +136,21 @@ func TestHandleTabUnlockByID_Mismatch(t *testing.T) {
t.Fatalf("expected 400, got %d", w.Code)
}
}
+
+func TestHandleShutdown_CallsFunc(t *testing.T) {
+ called := make(chan bool, 1)
+ doShutdown := func() { called <- true }
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ handler := h.HandleShutdown(doShutdown)
+ req := httptest.NewRequest("POST", "/shutdown", nil)
+ w := httptest.NewRecorder()
+ handler(w, req)
+ if w.Code != 200 {
+ t.Errorf("expected 200, got %d", w.Code)
+ }
+ select {
+ case <-called:
+ case <-time.After(500 * time.Millisecond):
+ t.Error("expected doShutdown to be called within 500ms")
+ }
+}
diff --git a/internal/handlers/navigation.go b/internal/handlers/navigation.go
index 4a02e92d..b98c82fb 100644
--- a/internal/handlers/navigation.go
+++ b/internal/handlers/navigation.go
@@ -326,82 +326,6 @@ func (h *Handlers) waitForNavigationState(ctx context.Context, waitFor, waitSele
}
}
-func (h *Handlers) HandleEvaluate(w http.ResponseWriter, r *http.Request) {
- var req struct {
- TabID string `json:"tabId"`
- Expression string `json:"expression"`
- }
- if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
- web.Error(w, 400, fmt.Errorf("decode: %w", err))
- return
- }
- if req.Expression == "" {
- web.Error(w, 400, fmt.Errorf("expression required"))
- return
- }
-
- ctx, _, err := h.Bridge.TabContext(req.TabID)
- if err != nil {
- web.Error(w, 404, err)
- return
- }
-
- tCtx, tCancel := context.WithTimeout(ctx, h.Config.ActionTimeout)
- defer tCancel()
- go web.CancelOnClientDone(r.Context(), tCancel)
-
- var result any
- if err := chromedp.Run(tCtx, chromedp.Evaluate(req.Expression, &result)); err != nil {
- web.Error(w, 500, fmt.Errorf("evaluate: %w", err))
- return
- }
-
- web.JSON(w, 200, map[string]any{"result": result})
-}
-
-// HandleTabEvaluate runs JavaScript in a tab identified by path ID.
-//
-// @Endpoint POST /tabs/{id}/evaluate
-func (h *Handlers) HandleTabEvaluate(w http.ResponseWriter, r *http.Request) {
- tabID := r.PathValue("id")
- if tabID == "" {
- web.Error(w, 400, fmt.Errorf("tab id required"))
- return
- }
-
- body := map[string]any{}
- dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize))
- if err := dec.Decode(&body); err != nil && !errors.Is(err, io.EOF) {
- web.Error(w, 400, fmt.Errorf("decode: %w", err))
- return
- }
-
- if rawTabID, ok := body["tabId"]; ok {
- if provided, ok := rawTabID.(string); !ok || provided == "" {
- web.Error(w, 400, fmt.Errorf("invalid tabId"))
- return
- } else if provided != tabID {
- web.Error(w, 400, fmt.Errorf("tabId in body does not match path id"))
- return
- }
- }
-
- body["tabId"] = tabID
-
- payload, err := json.Marshal(body)
- if err != nil {
- web.Error(w, 500, fmt.Errorf("encode: %w", err))
- return
- }
-
- req := r.Clone(r.Context())
- req.Body = io.NopCloser(bytes.NewReader(payload))
- req.ContentLength = int64(len(payload))
- req.Header = r.Header.Clone()
- req.Header.Set("Content-Type", "application/json")
- h.HandleEvaluate(w, req)
-}
-
const (
tabActionNew = "new"
tabActionClose = "close"
diff --git a/internal/handlers/navigation_test.go b/internal/handlers/navigation_test.go
new file mode 100644
index 00000000..653b02f8
--- /dev/null
+++ b/internal/handlers/navigation_test.go
@@ -0,0 +1,72 @@
+package handlers
+
+import (
+ "bytes"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func TestHandleNavigate_InvalidJSON(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("POST", "/navigate", bytes.NewReader([]byte(`not json`)))
+ w := httptest.NewRecorder()
+ h.HandleNavigate(w, req)
+ if w.Code != 400 {
+ t.Errorf("expected 400, got %d", w.Code)
+ }
+}
+
+func TestHandleTabNavigate_MissingTabID(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("POST", "/tabs//navigate", bytes.NewReader([]byte(`{"url":"https://example.com"}`)))
+ w := httptest.NewRecorder()
+ h.HandleTabNavigate(w, req)
+ if w.Code != 400 {
+ t.Errorf("expected 400, got %d", w.Code)
+ }
+}
+
+func TestHandleTabNavigate_TabIDMismatch(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("POST", "/tabs/tab_abc/navigate", bytes.NewReader([]byte(`{"tabId":"tab_other","url":"https://example.com"}`)))
+ req.SetPathValue("id", "tab_abc")
+ w := httptest.NewRecorder()
+ h.HandleTabNavigate(w, req)
+ if w.Code != 400 {
+ t.Errorf("expected 400, got %d", w.Code)
+ }
+}
+
+func TestHandleTab_InvalidJSON(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("POST", "/tab", bytes.NewReader([]byte(`not json`)))
+ w := httptest.NewRecorder()
+ h.HandleTab(w, req)
+ if w.Code != 400 {
+ t.Errorf("expected 400, got %d", w.Code)
+ }
+}
+
+func TestHandleTab_InvalidAction(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ body := `{"action":"invalid"}`
+ req := httptest.NewRequest("POST", "/tab", bytes.NewReader([]byte(body)))
+ w := httptest.NewRecorder()
+ h.HandleTab(w, req)
+ if w.Code != 400 {
+ t.Errorf("expected 400, got %d", w.Code)
+ }
+}
+
+func TestHandleTab_CloseMissingID(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ body := `{"action":"close"}`
+ req := httptest.NewRequest("POST", "/tab", bytes.NewReader([]byte(body)))
+ w := httptest.NewRecorder()
+ h.HandleTab(w, req)
+ if w.Code != 400 {
+ t.Errorf("expected 400, got %d", w.Code)
+ }
+}
diff --git a/internal/handlers/media.go b/internal/handlers/pdf.go
similarity index 57%
rename from internal/handlers/media.go
rename to internal/handlers/pdf.go
index 98c00510..af3775a7 100644
--- a/internal/handlers/media.go
+++ b/internal/handlers/pdf.go
@@ -10,13 +10,10 @@ import (
"os"
"path/filepath"
"strconv"
- "strings"
"time"
"github.com/chromedp/cdproto/page"
"github.com/chromedp/chromedp"
- "github.com/pinchtab/pinchtab/internal/assets"
- "github.com/pinchtab/pinchtab/internal/bridge"
"github.com/pinchtab/pinchtab/internal/web"
)
@@ -41,113 +38,9 @@ var pdfQueryParams = map[string]struct{}{
"raw": {},
}
-func (h *Handlers) HandleScreenshot(w http.ResponseWriter, r *http.Request) {
- // Ensure Chrome is initialized
- if err := h.ensureChrome(); err != nil {
- web.Error(w, 500, fmt.Errorf("chrome initialization: %w", err))
- return
- }
-
- tabID := r.URL.Query().Get("tabId")
- output := r.URL.Query().Get("output")
- reqNoAnim := r.URL.Query().Get("noAnimations") == "true"
-
- ctx, _, err := h.Bridge.TabContext(tabID)
- if err != nil {
- web.Error(w, 404, err)
- return
- }
-
- tCtx, tCancel := context.WithTimeout(ctx, h.Config.ActionTimeout)
- defer tCancel()
- go web.CancelOnClientDone(r.Context(), tCancel)
-
- if reqNoAnim && !h.Config.NoAnimations {
- bridge.DisableAnimationsOnce(tCtx)
- }
-
- var buf []byte
- quality := 80
- if q := r.URL.Query().Get("quality"); q != "" {
- if qn, err := strconv.Atoi(q); err == nil {
- quality = qn
- }
- }
-
- if err := chromedp.Run(tCtx,
- chromedp.ActionFunc(func(ctx context.Context) error {
- var err error
- buf, err = page.CaptureScreenshot().
- WithFormat(page.CaptureScreenshotFormatJpeg).
- WithQuality(int64(quality)).
- Do(ctx)
- return err
- }),
- ); err != nil {
- web.Error(w, 500, fmt.Errorf("screenshot: %w", err))
- return
- }
-
- if output == "file" {
- screenshotDir := filepath.Join(h.Config.StateDir, "screenshots")
- if err := os.MkdirAll(screenshotDir, 0750); err != nil {
- web.Error(w, 500, fmt.Errorf("create screenshot dir: %w", err))
- return
- }
-
- timestamp := time.Now().Format("20060102-150405")
- filename := fmt.Sprintf("screenshot-%s.jpg", timestamp)
- filePath := filepath.Join(screenshotDir, filename)
-
- if err := os.WriteFile(filePath, buf, 0600); err != nil {
- web.Error(w, 500, fmt.Errorf("write screenshot: %w", err))
- return
- }
-
- web.JSON(w, 200, map[string]any{
- "path": filePath,
- "size": len(buf),
- "format": "jpeg",
- "timestamp": timestamp,
- })
- return
- }
-
- if r.URL.Query().Get("raw") == "true" {
- w.Header().Set("Content-Type", "image/jpeg")
- if _, err := w.Write(buf); err != nil {
- slog.Error("screenshot write", "err", err)
- }
- return
- }
-
- web.JSON(w, 200, map[string]any{
- "format": "jpeg",
- "base64": base64.StdEncoding.EncodeToString(buf),
- })
-}
-
-// HandleTabScreenshot returns screenshot bytes for a tab identified by path ID.
+// HandlePDF generates a PDF of the current tab.
//
-// @Endpoint GET /tabs/{id}/screenshot
-func (h *Handlers) HandleTabScreenshot(w http.ResponseWriter, r *http.Request) {
- tabID := r.PathValue("id")
- if tabID == "" {
- web.Error(w, 400, fmt.Errorf("tab id required"))
- return
- }
-
- q := r.URL.Query()
- q.Set("tabId", tabID)
-
- req := r.Clone(r.Context())
- u := *r.URL
- u.RawQuery = q.Encode()
- req.URL = &u
-
- h.HandleScreenshot(w, req)
-}
-
+// @Endpoint GET /pdf
func (h *Handlers) HandlePDF(w http.ResponseWriter, r *http.Request) {
// Ensure Chrome is initialized
if err := h.ensureChrome(); err != nil {
@@ -314,6 +207,10 @@ func (h *Handlers) HandlePDF(w http.ResponseWriter, r *http.Request) {
})
}
+// HandleTabPDF generates a PDF for a tab identified by path ID.
+//
+// @Endpoint GET /tabs/{id}/pdf
+// @Endpoint POST /tabs/{id}/pdf
func (h *Handlers) HandleTabPDF(w http.ResponseWriter, r *http.Request) {
tabID := r.PathValue("id")
if tabID == "" {
@@ -356,95 +253,3 @@ func (h *Handlers) HandleTabPDF(w http.ResponseWriter, r *http.Request) {
h.HandlePDF(w, req)
}
-
-func (h *Handlers) HandleText(w http.ResponseWriter, r *http.Request) {
- // Ensure Chrome is initialized
- if err := h.ensureChrome(); err != nil {
- web.Error(w, 500, fmt.Errorf("chrome initialization: %w", err))
- return
- }
-
- tabID := r.URL.Query().Get("tabId")
- mode := r.URL.Query().Get("mode")
- format := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("format")))
- maxChars := -1
- if v := r.URL.Query().Get("maxChars"); v != "" {
- if n, err := strconv.Atoi(v); err == nil && n > 0 {
- maxChars = n
- }
- }
-
- ctx, _, err := h.Bridge.TabContext(tabID)
- if err != nil {
- web.Error(w, 404, err)
- return
- }
-
- tCtx, tCancel := context.WithTimeout(ctx, h.Config.ActionTimeout)
- defer tCancel()
- go web.CancelOnClientDone(r.Context(), tCancel)
-
- var text string
- if mode == "raw" {
- if err := chromedp.Run(tCtx,
- chromedp.Evaluate(`document.body.innerText`, &text),
- ); err != nil {
- web.Error(w, 500, fmt.Errorf("text extract: %w", err))
- return
- }
- } else {
- if err := chromedp.Run(tCtx,
- chromedp.Evaluate(assets.ReadabilityJS, &text),
- ); err != nil {
- web.Error(w, 500, fmt.Errorf("text extract: %w", err))
- return
- }
- }
-
- truncated := false
- if maxChars > -1 && len(text) > maxChars {
- text = text[:maxChars]
- truncated = true
- }
-
- var url, title string
- _ = chromedp.Run(tCtx,
- chromedp.Location(&url),
- chromedp.Title(&title),
- )
-
- if format == "text" || format == "plain" {
- w.Header().Set("Content-Type", "text/plain; charset=utf-8")
- w.WriteHeader(200)
- _, _ = w.Write([]byte(text))
- return
- }
-
- web.JSON(w, 200, map[string]any{
- "url": url,
- "title": title,
- "text": text,
- "truncated": truncated,
- })
-}
-
-// HandleTabText extracts text for a tab identified by path ID.
-//
-// @Endpoint GET /tabs/{id}/text
-func (h *Handlers) HandleTabText(w http.ResponseWriter, r *http.Request) {
- tabID := r.PathValue("id")
- if tabID == "" {
- web.Error(w, 400, fmt.Errorf("tab id required"))
- return
- }
-
- q := r.URL.Query()
- q.Set("tabId", tabID)
-
- req := r.Clone(r.Context())
- u := *r.URL
- u.RawQuery = q.Encode()
- req.URL = &u
-
- h.HandleText(w, req)
-}
diff --git a/internal/handlers/handler_pdf_test.go b/internal/handlers/pdf_test.go
similarity index 100%
rename from internal/handlers/handler_pdf_test.go
rename to internal/handlers/pdf_test.go
diff --git a/internal/handlers/screenshot.go b/internal/handlers/screenshot.go
new file mode 100644
index 00000000..f88f7335
--- /dev/null
+++ b/internal/handlers/screenshot.go
@@ -0,0 +1,128 @@
+package handlers
+
+import (
+ "context"
+ "encoding/base64"
+ "fmt"
+ "log/slog"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strconv"
+ "time"
+
+ "github.com/chromedp/cdproto/page"
+ "github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/web"
+)
+
+// HandleScreenshot captures a screenshot of the current tab.
+//
+// @Endpoint GET /screenshot
+func (h *Handlers) HandleScreenshot(w http.ResponseWriter, r *http.Request) {
+ // Ensure Chrome is initialized
+ if err := h.ensureChrome(); err != nil {
+ web.Error(w, 500, fmt.Errorf("chrome initialization: %w", err))
+ return
+ }
+
+ tabID := r.URL.Query().Get("tabId")
+ output := r.URL.Query().Get("output")
+ reqNoAnim := r.URL.Query().Get("noAnimations") == "true"
+
+ ctx, _, err := h.Bridge.TabContext(tabID)
+ if err != nil {
+ web.Error(w, 404, err)
+ return
+ }
+
+ tCtx, tCancel := context.WithTimeout(ctx, h.Config.ActionTimeout)
+ defer tCancel()
+ go web.CancelOnClientDone(r.Context(), tCancel)
+
+ if reqNoAnim && !h.Config.NoAnimations {
+ bridge.DisableAnimationsOnce(tCtx)
+ }
+
+ var buf []byte
+ quality := 80
+ if q := r.URL.Query().Get("quality"); q != "" {
+ if qn, err := strconv.Atoi(q); err == nil {
+ quality = qn
+ }
+ }
+
+ if err := chromedp.Run(tCtx,
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ var err error
+ buf, err = page.CaptureScreenshot().
+ WithFormat(page.CaptureScreenshotFormatJpeg).
+ WithQuality(int64(quality)).
+ Do(ctx)
+ return err
+ }),
+ ); err != nil {
+ web.Error(w, 500, fmt.Errorf("screenshot: %w", err))
+ return
+ }
+
+ if output == "file" {
+ screenshotDir := filepath.Join(h.Config.StateDir, "screenshots")
+ if err := os.MkdirAll(screenshotDir, 0750); err != nil {
+ web.Error(w, 500, fmt.Errorf("create screenshot dir: %w", err))
+ return
+ }
+
+ timestamp := time.Now().Format("20060102-150405")
+ filename := fmt.Sprintf("screenshot-%s.jpg", timestamp)
+ filePath := filepath.Join(screenshotDir, filename)
+
+ if err := os.WriteFile(filePath, buf, 0600); err != nil {
+ web.Error(w, 500, fmt.Errorf("write screenshot: %w", err))
+ return
+ }
+
+ web.JSON(w, 200, map[string]any{
+ "path": filePath,
+ "size": len(buf),
+ "format": "jpeg",
+ "timestamp": timestamp,
+ })
+ return
+ }
+
+ if r.URL.Query().Get("raw") == "true" {
+ w.Header().Set("Content-Type", "image/jpeg")
+ if _, err := w.Write(buf); err != nil {
+ slog.Error("screenshot write", "err", err)
+ }
+ return
+ }
+
+ web.JSON(w, 200, map[string]any{
+ "format": "jpeg",
+ "base64": base64.StdEncoding.EncodeToString(buf),
+ })
+}
+
+// HandleTabScreenshot returns screenshot bytes for a tab identified by path ID.
+//
+// @Endpoint GET /tabs/{id}/screenshot
+func (h *Handlers) HandleTabScreenshot(w http.ResponseWriter, r *http.Request) {
+ tabID := r.PathValue("id")
+ if tabID == "" {
+ web.Error(w, 400, fmt.Errorf("tab id required"))
+ return
+ }
+
+ q := r.URL.Query()
+ q.Set("tabId", tabID)
+
+ req := r.Clone(r.Context())
+ u := *r.URL
+ u.RawQuery = q.Encode()
+ req.URL = &u
+
+ h.HandleScreenshot(w, req)
+}
diff --git a/internal/handlers/screenshot_test.go b/internal/handlers/screenshot_test.go
new file mode 100644
index 00000000..5ee29da1
--- /dev/null
+++ b/internal/handlers/screenshot_test.go
@@ -0,0 +1,51 @@
+package handlers
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func TestHandleScreenshot_NoTab(t *testing.T) {
+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("GET", "/screenshot", nil)
+ w := httptest.NewRecorder()
+ h.HandleScreenshot(w, req)
+ if w.Code != http.StatusNotFound {
+ t.Errorf("expected 404, got %d", w.Code)
+ }
+}
+
+func TestHandleScreenshot_InvalidQuality(t *testing.T) {
+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("GET", "/screenshot?quality=abc", nil)
+ w := httptest.NewRecorder()
+ h.HandleScreenshot(w, req)
+ // Should still return 404 (no tab), not crash on bad quality
+ if w.Code != http.StatusNotFound {
+ t.Errorf("expected 404, got %d", w.Code)
+ }
+}
+
+func TestHandleTabScreenshot_MissingTabID(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("GET", "/tabs//screenshot", nil)
+ w := httptest.NewRecorder()
+ h.HandleTabScreenshot(w, req)
+ if w.Code != http.StatusBadRequest {
+ t.Errorf("expected 400, got %d", w.Code)
+ }
+}
+
+func TestHandleTabScreenshot_NoTab(t *testing.T) {
+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("GET", "/tabs/tab_abc/screenshot", nil)
+ req.SetPathValue("id", "tab_abc")
+ w := httptest.NewRecorder()
+ h.HandleTabScreenshot(w, req)
+ if w.Code != http.StatusNotFound {
+ t.Errorf("expected 404, got %d", w.Code)
+ }
+}
diff --git a/internal/handlers/handler_snapshot_test.go b/internal/handlers/snapshot_test.go
similarity index 100%
rename from internal/handlers/handler_snapshot_test.go
rename to internal/handlers/snapshot_test.go
diff --git a/internal/handlers/stealth_test.go b/internal/handlers/stealth_test.go
index 56fb742d..4da91ecd 100644
--- a/internal/handlers/stealth_test.go
+++ b/internal/handlers/stealth_test.go
@@ -1,13 +1,138 @@
package handlers
import (
+ "bytes"
+ "context"
+ "net/http/httptest"
"strings"
"testing"
"github.com/pinchtab/pinchtab/internal/assets"
+ "github.com/pinchtab/pinchtab/internal/bridge"
"github.com/pinchtab/pinchtab/internal/config"
)
+func TestHandleStealthStatus_NoTab_ReturnsStatic(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("GET", "/stealth/status", nil)
+ w := httptest.NewRecorder()
+
+ h.HandleStealthStatus(w, req)
+
+ if w.Code != 200 {
+ t.Errorf("expected 200, got %d", w.Code)
+ }
+
+ body := w.Body.String()
+ if !searchString(body, "level") || !searchString(body, "score") {
+ t.Errorf("expected level and score in response, got: %s", body)
+ }
+}
+
+func TestHandleFingerprintRotate_InvalidJSON(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("POST", "/fingerprint/rotate", bytes.NewReader([]byte(`not json`)))
+ w := httptest.NewRecorder()
+
+ h.HandleFingerprintRotate(w, req)
+
+ if w.Code != 400 {
+ t.Errorf("expected 400, got %d", w.Code)
+ }
+}
+
+func TestGenerateFingerprint_Windows(t *testing.T) {
+ h := Handlers{Config: &config.RuntimeConfig{ChromeVersion: "120.0.0.0"}}
+ fp := h.generateFingerprint(fingerprintRequest{OS: "windows"})
+ if fp.Platform != "Win32" {
+ t.Errorf("expected Win32, got %q", fp.Platform)
+ }
+ if fp.UserAgent == "" {
+ t.Error("expected non-empty user agent")
+ }
+ if fp.ScreenWidth == 0 || fp.ScreenHeight == 0 {
+ t.Error("expected non-zero screen dimensions")
+ }
+ if fp.Vendor != "Google Inc." {
+ t.Errorf("expected Google Inc., got %q", fp.Vendor)
+ }
+}
+
+func TestGenerateFingerprint_Mac(t *testing.T) {
+ h := Handlers{Config: &config.RuntimeConfig{ChromeVersion: "120.0.0.0"}}
+ fp := h.generateFingerprint(fingerprintRequest{OS: "mac"})
+ if fp.Platform != "MacIntel" {
+ t.Errorf("expected MacIntel, got %q", fp.Platform)
+ }
+}
+
+func TestGenerateFingerprint_Random(t *testing.T) {
+ h := Handlers{Config: &config.RuntimeConfig{ChromeVersion: "120.0.0.0"}}
+ fp := h.generateFingerprint(fingerprintRequest{OS: "random"})
+ validPlatforms := map[string]bool{"Win32": true, "MacIntel": true}
+ if !validPlatforms[fp.Platform] {
+ t.Errorf("unexpected platform %q", fp.Platform)
+ }
+}
+
+func TestGenerateFingerprint_WithBrowser(t *testing.T) {
+ h := Handlers{Config: &config.RuntimeConfig{ChromeVersion: "120.0.0.0"}}
+ fp := h.generateFingerprint(fingerprintRequest{OS: "windows", Browser: "chrome"})
+ if fp.UserAgent == "" {
+ t.Error("expected non-empty user agent")
+ }
+}
+
+func TestGetStealthRecommendations_AllEnabled(t *testing.T) {
+ h := Handlers{}
+ features := map[string]bool{
+ "user_agent_override": true,
+ "languages_spoofed": true,
+ "webrtc_leak_prevented": true,
+ "timezone_spoofed": true,
+ "canvas_noise": true,
+ "font_spoofing": true,
+ }
+ recs := h.getStealthRecommendations(features)
+ if len(recs) != 1 || recs[0] != "Stealth mode is well configured" {
+ t.Errorf("expected well-configured message, got %v", recs)
+ }
+}
+
+func TestGetStealthRecommendations_NoneEnabled(t *testing.T) {
+ h := Handlers{}
+ features := map[string]bool{}
+ recs := h.getStealthRecommendations(features)
+ if len(recs) != 6 {
+ t.Errorf("expected 6 recommendations, got %d: %v", len(recs), recs)
+ }
+}
+
+func TestSendStealthResponse_HighScore(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ features := map[string]bool{
+ "a": true, "b": true, "c": true, "d": true, "e": true,
+ }
+ w := httptest.NewRecorder()
+ h.sendStealthResponse(w, features, "TestAgent/1.0")
+
+ if w.Code != 200 {
+ t.Errorf("expected 200, got %d", w.Code)
+ }
+ body := w.Body.String()
+ if !searchString(body, `"level":"high"`) {
+ t.Errorf("expected high level for 100%% score, got: %s", body)
+ }
+}
+
+func TestStaticStealthFeatures_HasEntries(t *testing.T) {
+ h := Handlers{Config: &config.RuntimeConfig{}}
+ features := h.staticStealthFeatures()
+ if len(features) == 0 {
+ t.Error("expected non-empty stealth features map")
+ }
+}
+
func TestStealthScript_Content(t *testing.T) {
if assets.StealthScript == "" {
t.Fatal("StealthScript is empty")
@@ -44,3 +169,12 @@ func TestGenerateFingerprint_Config(t *testing.T) {
t.Errorf("expected User-Agent to contain Chrome version 120.0.0.0, got %q", fp.UserAgent)
}
}
+
+func TestStealthScript_Populated(t *testing.T) {
+ b := bridge.New(context.Background(), context.Background(), &config.RuntimeConfig{})
+ b.StealthScript = assets.StealthScript
+
+ if b.StealthScript == "" {
+ t.Error("expected stealth script to be populated")
+ }
+}
diff --git a/internal/handlers/text.go b/internal/handlers/text.go
new file mode 100644
index 00000000..8ea04f51
--- /dev/null
+++ b/internal/handlers/text.go
@@ -0,0 +1,108 @@
+package handlers
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "strconv"
+ "strings"
+
+ "github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/assets"
+ "github.com/pinchtab/pinchtab/internal/web"
+)
+
+// HandleText extracts readable text from the current tab.
+//
+// @Endpoint GET /text
+func (h *Handlers) HandleText(w http.ResponseWriter, r *http.Request) {
+ // Ensure Chrome is initialized
+ if err := h.ensureChrome(); err != nil {
+ web.Error(w, 500, fmt.Errorf("chrome initialization: %w", err))
+ return
+ }
+
+ tabID := r.URL.Query().Get("tabId")
+ mode := r.URL.Query().Get("mode")
+ format := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("format")))
+ maxChars := -1
+ if v := r.URL.Query().Get("maxChars"); v != "" {
+ if n, err := strconv.Atoi(v); err == nil && n > 0 {
+ maxChars = n
+ }
+ }
+
+ ctx, _, err := h.Bridge.TabContext(tabID)
+ if err != nil {
+ web.Error(w, 404, err)
+ return
+ }
+
+ tCtx, tCancel := context.WithTimeout(ctx, h.Config.ActionTimeout)
+ defer tCancel()
+ go web.CancelOnClientDone(r.Context(), tCancel)
+
+ var text string
+ if mode == "raw" {
+ if err := chromedp.Run(tCtx,
+ chromedp.Evaluate(`document.body.innerText`, &text),
+ ); err != nil {
+ web.Error(w, 500, fmt.Errorf("text extract: %w", err))
+ return
+ }
+ } else {
+ if err := chromedp.Run(tCtx,
+ chromedp.Evaluate(assets.ReadabilityJS, &text),
+ ); err != nil {
+ web.Error(w, 500, fmt.Errorf("text extract: %w", err))
+ return
+ }
+ }
+
+ truncated := false
+ if maxChars > -1 && len(text) > maxChars {
+ text = text[:maxChars]
+ truncated = true
+ }
+
+ var url, title string
+ _ = chromedp.Run(tCtx,
+ chromedp.Location(&url),
+ chromedp.Title(&title),
+ )
+
+ if format == "text" || format == "plain" {
+ w.Header().Set("Content-Type", "text/plain; charset=utf-8")
+ w.WriteHeader(200)
+ _, _ = w.Write([]byte(text))
+ return
+ }
+
+ web.JSON(w, 200, map[string]any{
+ "url": url,
+ "title": title,
+ "text": text,
+ "truncated": truncated,
+ })
+}
+
+// HandleTabText extracts text for a tab identified by path ID.
+//
+// @Endpoint GET /tabs/{id}/text
+func (h *Handlers) HandleTabText(w http.ResponseWriter, r *http.Request) {
+ tabID := r.PathValue("id")
+ if tabID == "" {
+ web.Error(w, 400, fmt.Errorf("tab id required"))
+ return
+ }
+
+ q := r.URL.Query()
+ q.Set("tabId", tabID)
+
+ req := r.Clone(r.Context())
+ u := *r.URL
+ u.RawQuery = q.Encode()
+ req.URL = &u
+
+ h.HandleText(w, req)
+}
diff --git a/internal/handlers/handler_media_test.go b/internal/handlers/text_test.go
similarity index 54%
rename from internal/handlers/handler_media_test.go
rename to internal/handlers/text_test.go
index d094bb5c..90a4cc9b 100644
--- a/internal/handlers/handler_media_test.go
+++ b/internal/handlers/text_test.go
@@ -8,48 +8,6 @@ import (
"github.com/pinchtab/pinchtab/internal/config"
)
-func TestHandleScreenshot_NoTab(t *testing.T) {
- h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)
- req := httptest.NewRequest("GET", "/screenshot", nil)
- w := httptest.NewRecorder()
- h.HandleScreenshot(w, req)
- if w.Code != http.StatusNotFound {
- t.Errorf("expected 404, got %d", w.Code)
- }
-}
-
-func TestHandleScreenshot_InvalidQuality(t *testing.T) {
- h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)
- req := httptest.NewRequest("GET", "/screenshot?quality=abc", nil)
- w := httptest.NewRecorder()
- h.HandleScreenshot(w, req)
- // Should still return 404 (no tab), not crash on bad quality
- if w.Code != http.StatusNotFound {
- t.Errorf("expected 404, got %d", w.Code)
- }
-}
-
-func TestHandleTabScreenshot_MissingTabID(t *testing.T) {
- h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
- req := httptest.NewRequest("GET", "/tabs//screenshot", nil)
- w := httptest.NewRecorder()
- h.HandleTabScreenshot(w, req)
- if w.Code != http.StatusBadRequest {
- t.Errorf("expected 400, got %d", w.Code)
- }
-}
-
-func TestHandleTabScreenshot_NoTab(t *testing.T) {
- h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)
- req := httptest.NewRequest("GET", "/tabs/tab_abc/screenshot", nil)
- req.SetPathValue("id", "tab_abc")
- w := httptest.NewRecorder()
- h.HandleTabScreenshot(w, req)
- if w.Code != http.StatusNotFound {
- t.Errorf("expected 404, got %d", w.Code)
- }
-}
-
func TestHandleText_NoTab(t *testing.T) {
h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)
req := httptest.NewRequest("GET", "/text", nil)
diff --git a/internal/handlers/upload_test.go b/internal/handlers/upload_test.go
index f5155232..b1a2d387 100644
--- a/internal/handlers/upload_test.go
+++ b/internal/handlers/upload_test.go
@@ -1,9 +1,85 @@
package handlers
import (
+ "bytes"
+ "net/http"
+ "net/http/httptest"
"testing"
+
+ "github.com/pinchtab/pinchtab/internal/config"
)
+func TestHandleUpload_BadJSON(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("POST", "/upload", bytes.NewReader([]byte("not json")))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ h.HandleUpload(w, req)
+ if w.Code != http.StatusBadRequest {
+ t.Errorf("expected 400 for bad JSON, got %d", w.Code)
+ }
+}
+
+func TestHandleUpload_EmptyPaths(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ body := `{"selector": "input[type=file]"}`
+ req := httptest.NewRequest("POST", "/upload", bytes.NewReader([]byte(body)))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ h.HandleUpload(w, req)
+ if w.Code != http.StatusBadRequest {
+ t.Errorf("expected 400 for empty paths, got %d", w.Code)
+ }
+}
+
+func TestHandleUpload_NonexistentPath(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ body := `{"selector": "input[type=file]", "paths": ["/tmp/nonexistent-file-12345.jpg"]}`
+ req := httptest.NewRequest("POST", "/upload", bytes.NewReader([]byte(body)))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ h.HandleUpload(w, req)
+ if w.Code != http.StatusBadRequest {
+ t.Errorf("expected 400 for nonexistent path, got %d", w.Code)
+ }
+}
+
+func TestHandleTabUpload_MissingTabID(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("POST", "/tabs//upload", bytes.NewReader([]byte(`{"selector":"input[type=file]"}`)))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ h.HandleTabUpload(w, req)
+ if w.Code != http.StatusBadRequest {
+ t.Errorf("expected 400, got %d", w.Code)
+ }
+}
+
+func TestHandleTabUpload_NoTab(t *testing.T) {
+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("POST", "/tabs/tab_abc/upload", bytes.NewReader([]byte(`{"files":["aGVsbG8="]}`)))
+ req.SetPathValue("id", "tab_abc")
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ h.HandleTabUpload(w, req)
+ if w.Code != http.StatusNotFound {
+ t.Errorf("expected 404, got %d", w.Code)
+ }
+}
+
+func TestHandleUpload_BodyTooLarge(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ // Create a body larger than 10MB
+ bigBody := make([]byte, 11<<20) // 11MB
+ req := httptest.NewRequest("POST", "/upload", bytes.NewReader(bigBody))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ h.HandleUpload(w, req)
+ if w.Code != http.StatusBadRequest {
+ t.Errorf("expected 400 for oversized body, got %d", w.Code)
+ }
+}
+
func TestDecodeFileData_DataURL(t *testing.T) {
// 1x1 red PNG as data URL
input := "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg=="
diff --git a/internal/orchestrator/handlers.go b/internal/orchestrator/handlers.go
index 68438c0f..e012fa2d 100644
--- a/internal/orchestrator/handlers.go
+++ b/internal/orchestrator/handlers.go
@@ -1,24 +1,18 @@
package orchestrator
import (
- "bytes"
- "encoding/json"
- "fmt"
- "io"
- "net"
"net/http"
- "net/url"
- "strings"
- "time"
"github.com/pinchtab/pinchtab/internal/web"
)
func (o *Orchestrator) RegisterHandlers(mux *http.ServeMux) {
+ // Profile management
mux.HandleFunc("POST /profiles/{id}/start", o.handleStartByID)
mux.HandleFunc("POST /profiles/{id}/stop", o.handleStopByID)
mux.HandleFunc("GET /profiles/{id}/instance", o.handleProfileInstance)
+ // Instance management
mux.HandleFunc("GET /instances", o.handleList)
mux.HandleFunc("GET /instances/{id}", o.handleGetInstance)
mux.HandleFunc("GET /instances/tabs", o.handleAllTabs)
@@ -33,823 +27,36 @@ func (o *Orchestrator) RegisterHandlers(mux *http.ServeMux) {
mux.HandleFunc("POST /instances/{id}/tab", o.proxyToInstance)
mux.HandleFunc("GET /instances/{id}/screencast", o.proxyToInstance)
+ // Tab operations - custom handlers
mux.HandleFunc("POST /tabs/{id}/close", o.handleTabClose)
- mux.HandleFunc("POST /tabs/{id}/navigate", o.handleTabNavigate)
- mux.HandleFunc("GET /tabs/{id}/snapshot", o.handleTabSnapshot)
- mux.HandleFunc("GET /tabs/{id}/screenshot", o.handleTabScreenshot)
- mux.HandleFunc("POST /tabs/{id}/action", o.handleTabAction)
- mux.HandleFunc("POST /tabs/{id}/actions", o.handleTabActions)
- mux.HandleFunc("GET /tabs/{id}/text", o.handleTabText)
- mux.HandleFunc("POST /tabs/{id}/evaluate", o.handleTabEvaluate)
- mux.HandleFunc("GET /tabs/{id}/pdf", o.handleTabPDF)
- mux.HandleFunc("POST /tabs/{id}/pdf", o.handleTabPDF)
- mux.HandleFunc("GET /tabs/{id}/download", o.handleTabDownload)
- mux.HandleFunc("POST /tabs/{id}/upload", o.handleTabUpload)
- mux.HandleFunc("POST /tabs/{id}/lock", o.handleTabLock)
- mux.HandleFunc("POST /tabs/{id}/unlock", o.handleTabUnlock)
- mux.HandleFunc("GET /tabs/{id}/cookies", o.handleTabGetCookies)
- mux.HandleFunc("POST /tabs/{id}/cookies", o.handleTabSetCookies)
-}
-
-func (o *Orchestrator) handleList(w http.ResponseWriter, r *http.Request) {
- web.JSON(w, 200, o.List())
-}
-
-func (o *Orchestrator) handleGetInstance(w http.ResponseWriter, r *http.Request) {
- id := r.PathValue("id")
- o.mu.RLock()
- inst, ok := o.instances[id]
- if !ok {
- o.mu.RUnlock()
- web.Error(w, 404, fmt.Errorf("instance %q not found", id))
- return
- }
-
- copyInst := inst.Instance
- active := instanceIsActive(inst)
- o.mu.RUnlock()
-
- if active && copyInst.Status == "stopped" {
- copyInst.Status = "running"
- }
- if !active &&
- (copyInst.Status == "starting" || copyInst.Status == "running" || copyInst.Status == "stopping") {
- copyInst.Status = "stopped"
- }
-
- web.JSON(w, 200, copyInst)
-}
-
-func (o *Orchestrator) resolveProfileName(idOrName string) (string, error) {
- if o.profiles == nil {
- return "", fmt.Errorf("profile manager not configured")
- }
- if name, err := o.profiles.FindByID(idOrName); err == nil {
- return name, nil
- }
- if o.profiles.Exists(idOrName) {
- return idOrName, nil
- }
- return "", fmt.Errorf("profile %q not found", idOrName)
-}
-
-func (o *Orchestrator) handleStartByID(w http.ResponseWriter, r *http.Request) {
- id := r.PathValue("id")
- name, err := o.resolveProfileName(id)
- if err != nil {
- web.Error(w, 404, err)
- return
- }
-
- var req struct {
- Port string `json:"port,omitempty"`
- Headless bool `json:"headless"`
- }
- _ = json.NewDecoder(r.Body).Decode(&req)
-
- inst, err := o.Launch(name, req.Port, req.Headless)
- if err != nil {
- statusCode := classifyLaunchError(err)
- web.Error(w, statusCode, err)
- return
- }
- web.JSON(w, 201, inst)
-}
-
-// classifyLaunchError returns appropriate HTTP status code for launch errors.
-func classifyLaunchError(err error) int {
- msg := err.Error()
- if strings.Contains(msg, "cannot contain") || strings.Contains(msg, "cannot be empty") {
- return 400 // Bad Request - validation error
- }
- if strings.Contains(msg, "already") || strings.Contains(msg, "in use") {
- return 409 // Conflict - resource already exists
- }
- return 500 // Internal Server Error
-}
-func (o *Orchestrator) handleStopByID(w http.ResponseWriter, r *http.Request) {
- id := r.PathValue("id")
- name, err := o.resolveProfileName(id)
- if err != nil {
- web.Error(w, 404, err)
- return
+ // Tab operations - generic proxy (all route to the appropriate instance)
+ tabProxyRoutes := []string{
+ "POST /tabs/{id}/navigate",
+ "GET /tabs/{id}/snapshot",
+ "GET /tabs/{id}/screenshot",
+ "POST /tabs/{id}/action",
+ "POST /tabs/{id}/actions",
+ "GET /tabs/{id}/text",
+ "POST /tabs/{id}/evaluate",
+ "GET /tabs/{id}/pdf",
+ "POST /tabs/{id}/pdf",
+ "GET /tabs/{id}/download",
+ "POST /tabs/{id}/upload",
+ "POST /tabs/{id}/lock",
+ "POST /tabs/{id}/unlock",
+ "GET /tabs/{id}/cookies",
+ "POST /tabs/{id}/cookies",
+ }
+ for _, route := range tabProxyRoutes {
+ mux.HandleFunc(route, o.proxyTabRequest)
}
- if err := o.StopProfile(name); err != nil {
- web.Error(w, 404, err)
- return
- }
- web.JSON(w, 200, map[string]string{"status": "stopped", "id": id, "name": name})
}
-func (o *Orchestrator) handleLaunchByName(w http.ResponseWriter, r *http.Request) {
- var req struct {
- ProfileId string `json:"profileId,omitempty"`
- Name string `json:"name,omitempty"`
- Mode string `json:"mode"`
- Port string `json:"port,omitempty"`
- }
-
- if r.ContentLength > 0 {
- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
- web.Error(w, 400, fmt.Errorf("invalid JSON"))
- return
- }
- }
-
- headless := req.Mode != "headed"
-
- var name string
- if req.ProfileId != "" {
- profs, err := o.profiles.List()
- if err != nil {
- web.Error(w, 500, fmt.Errorf("failed to list profiles: %w", err))
- return
- }
- found := false
- for _, p := range profs {
- if p.ID == req.ProfileId {
- name = p.Name
- found = true
- break
- }
- }
- if !found {
- web.Error(w, 400, fmt.Errorf("profile %q not found", req.ProfileId))
- return
- }
- } else if req.Name != "" {
- name = req.Name
- } else {
- name = fmt.Sprintf("instance-%d", time.Now().UnixNano())
- }
-
- inst, err := o.Launch(name, req.Port, headless)
- if err != nil {
- statusCode := classifyLaunchError(err)
- web.Error(w, statusCode, err)
- return
- }
- web.JSON(w, 201, inst)
-}
-
-func (o *Orchestrator) handleStopByInstanceID(w http.ResponseWriter, r *http.Request) {
- id := r.PathValue("id")
- if err := o.Stop(id); err != nil {
- web.Error(w, 404, err)
- return
- }
- web.JSON(w, 200, map[string]string{"status": "stopped", "id": id})
-}
-
-func (o *Orchestrator) handleStartByInstanceID(w http.ResponseWriter, r *http.Request) {
- id := r.PathValue("id")
-
- o.mu.RLock()
- inst, ok := o.instances[id]
- if !ok {
- o.mu.RUnlock()
- web.Error(w, 404, fmt.Errorf("instance %q not found", id))
- return
- }
- active := instanceIsActive(inst)
- port := inst.Port
- profileName := inst.ProfileName
- headless := inst.Headless
- o.mu.RUnlock()
-
- if active {
- targetURL := &url.URL{
- Scheme: "http",
- Host: net.JoinHostPort("localhost", port),
- Path: "/ensure-chrome",
- }
- o.proxyToURL(w, r, targetURL)
- return
- }
-
- started, err := o.Launch(profileName, port, headless)
- if err != nil {
- statusCode := classifyLaunchError(err)
- web.Error(w, statusCode, err)
- return
- }
- web.JSON(w, 201, started)
-}
-
-func (o *Orchestrator) handleLogsByID(w http.ResponseWriter, r *http.Request) {
- id := r.PathValue("id")
- logs, err := o.Logs(id)
- if err != nil {
- web.Error(w, 404, err)
- return
- }
- w.Header().Set("Content-Type", "text/plain")
- _, _ = w.Write([]byte(logs))
-}
-
-func (o *Orchestrator) handleStartInstance(w http.ResponseWriter, r *http.Request) {
- var req struct {
- ProfileID string `json:"profileId,omitempty"`
- Mode string `json:"mode,omitempty"`
- Port string `json:"port,omitempty"`
- }
-
- if r.ContentLength > 0 {
- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
- web.Error(w, 400, fmt.Errorf("invalid JSON"))
- return
- }
- }
-
- var profileName string
- var err error
-
- if req.ProfileID != "" {
- profileName, err = o.resolveProfileName(req.ProfileID)
- if err != nil {
- web.Error(w, 404, fmt.Errorf("profile %q not found", req.ProfileID))
- return
- }
- } else {
- profileName = fmt.Sprintf("instance-%d", time.Now().UnixNano())
- }
-
- headless := req.Mode != "headed"
-
- inst, err := o.Launch(profileName, req.Port, headless)
- if err != nil {
- statusCode := classifyLaunchError(err)
- web.Error(w, statusCode, err)
- return
- }
-
- web.JSON(w, 201, inst)
+func (o *Orchestrator) handleList(w http.ResponseWriter, r *http.Request) {
+ web.JSON(w, 200, o.List())
}
func (o *Orchestrator) handleAllTabs(w http.ResponseWriter, r *http.Request) {
web.JSON(w, 200, o.AllTabs())
}
-
-func (o *Orchestrator) handleProfileInstance(w http.ResponseWriter, r *http.Request) {
- id := r.PathValue("id")
- name, err := o.resolveProfileName(id)
- if err != nil {
- web.JSON(w, 200, map[string]any{
- "name": id,
- "running": false,
- "status": "stopped",
- "port": "",
- })
- return
- }
-
- instances := o.List()
- for _, inst := range instances {
- if inst.ProfileName == name && (inst.Status == "running" || inst.Status == "starting") {
- web.JSON(w, 200, map[string]any{
- "name": name,
- "running": inst.Status == "running",
- "status": inst.Status,
- "port": inst.Port,
- "id": inst.ID,
- })
- return
- }
- }
- web.JSON(w, 200, map[string]any{
- "name": name,
- "running": false,
- "status": "stopped",
- "port": "",
- })
-}
-
-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" {
- web.Error(w, 404, fmt.Errorf("instance not found or not running"))
- return
- }
-
- targetURL := fmt.Sprintf("ws://localhost:%s/screencast?tabId=%s", inst.Port, tabID)
- web.JSON(w, 200, map[string]string{"wsUrl": targetURL})
-}
-
-func (o *Orchestrator) proxyToInstance(w http.ResponseWriter, r *http.Request) {
- id := r.PathValue("id")
-
- o.mu.RLock()
- inst, ok := o.instances[id]
- o.mu.RUnlock()
-
- if !ok {
- web.Error(w, 404, fmt.Errorf("instance %q not found", id))
- return
- }
-
- if inst.Status != "running" {
- web.Error(w, 503, fmt.Errorf("instance %q is not running (status: %s)", id, inst.Status))
- return
- }
-
- targetPath := r.URL.Path
- if len(targetPath) > len("/instances/"+id) {
- targetPath = targetPath[len("/instances/"+id):]
- } else {
- targetPath = ""
- }
-
- targetURL := &url.URL{
- Scheme: "http",
- Host: net.JoinHostPort("localhost", inst.Port),
- Path: targetPath,
- RawQuery: r.URL.RawQuery,
- }
- o.proxyToURL(w, r, targetURL)
-}
-
-func (o *Orchestrator) proxyToURL(w http.ResponseWriter, r *http.Request, targetURL *url.URL) {
- if targetURL.Hostname() != "localhost" {
- web.Error(w, 400, fmt.Errorf("invalid proxy target: only localhost allowed"))
- return
- }
-
- proxyReq, err := http.NewRequest(r.Method, targetURL.String(), r.Body)
- if err != nil {
- web.Error(w, 500, fmt.Errorf("failed to create proxy request: %w", err))
- return
- }
-
- for key, values := range r.Header {
- switch key {
- case "Host", "Connection", "Keep-Alive", "Proxy-Authenticate",
- "Proxy-Authorization", "Te", "Trailers", "Transfer-Encoding", "Upgrade":
- default:
- for _, value := range values {
- proxyReq.Header.Add(key, value)
- }
- }
- }
-
- resp, err := o.client.Do(proxyReq)
- if err != nil {
- web.Error(w, 502, fmt.Errorf("failed to proxy to instance: %w", err))
- return
- }
- defer func() { _ = resp.Body.Close() }()
-
- for key, values := range resp.Header {
- for _, value := range values {
- w.Header().Add(key, value)
- }
- }
-
- w.WriteHeader(resp.StatusCode)
- _, _ = w.Write(readResponseBody(resp))
-}
-
-func (o *Orchestrator) findRunningInstanceByTabID(tabID string) (*InstanceInternal, error) {
- o.mu.RLock()
- instances := make([]*InstanceInternal, 0, len(o.instances))
- for _, inst := range o.instances {
- if inst.Status == "running" && instanceIsActive(inst) {
- instances = append(instances, inst)
- }
- }
- o.mu.RUnlock()
-
- for _, inst := range instances {
- tabs, err := o.fetchTabs(inst.URL)
- if err != nil {
- continue
- }
- for _, tab := range tabs {
- if tab.ID == tabID || o.idMgr.TabIDFromCDPTarget(tab.ID) == tabID {
- return inst, nil
- }
- }
- }
- return nil, fmt.Errorf("tab %q not found", tabID)
-}
-
-func readResponseBody(resp *http.Response) []byte {
- if resp.Body == nil {
- return []byte{}
- }
- body := make([]byte, 0)
- buf := make([]byte, 4096)
- for {
- n, err := resp.Body.Read(buf)
- if n > 0 {
- body = append(body, buf[:n]...)
- }
- if err != nil {
- break
- }
- }
- return body
-}
-
-func (o *Orchestrator) handleTabClose(w http.ResponseWriter, r *http.Request) {
- tabID := r.PathValue("id")
- if tabID == "" {
- web.Error(w, 400, fmt.Errorf("tab id required"))
- return
- }
-
- inst, err := o.findRunningInstanceByTabID(tabID)
- if err != nil {
- web.Error(w, 404, err)
- return
- }
-
- // Construct request body for the bridge's /tab endpoint
- reqBody, _ := json.Marshal(map[string]string{
- "action": "close",
- "tabId": tabID,
- })
-
- targetURL := fmt.Sprintf("http://localhost:%s/tab", inst.Port)
- proxyReq, err := http.NewRequestWithContext(r.Context(), "POST", targetURL, bytes.NewReader(reqBody))
- if err != nil {
- web.Error(w, 500, err)
- return
- }
- proxyReq.Header.Set("Content-Type", "application/json")
-
- client := &http.Client{Timeout: 30 * time.Second}
- resp, err := client.Do(proxyReq)
- if err != nil {
- web.Error(w, 502, fmt.Errorf("instance unreachable: %w", err))
- return
- }
- defer func() { _ = resp.Body.Close() }()
-
- body, _ := io.ReadAll(resp.Body)
- w.Header().Set("Content-Type", "application/json")
- w.WriteHeader(resp.StatusCode)
- _, _ = w.Write(body)
-}
-
-func (o *Orchestrator) handleTabNavigate(w http.ResponseWriter, r *http.Request) {
- tabID := r.PathValue("id")
- if tabID == "" {
- web.Error(w, 400, fmt.Errorf("tab id required"))
- return
- }
-
- inst, err := o.findRunningInstanceByTabID(tabID)
- if err != nil {
- web.Error(w, 404, err)
- return
- }
-
- targetURL := &url.URL{
- Scheme: "http",
- Host: net.JoinHostPort("localhost", inst.Port),
- Path: "/tabs/" + tabID + "/navigate",
- RawQuery: r.URL.RawQuery,
- }
- o.proxyToURL(w, r, targetURL)
-}
-
-func (o *Orchestrator) handleTabSnapshot(w http.ResponseWriter, r *http.Request) {
- tabID := r.PathValue("id")
- if tabID == "" {
- web.Error(w, 400, fmt.Errorf("tab id required"))
- return
- }
-
- inst, err := o.findRunningInstanceByTabID(tabID)
- if err != nil {
- web.Error(w, 404, err)
- return
- }
-
- targetURL := &url.URL{
- Scheme: "http",
- Host: net.JoinHostPort("localhost", inst.Port),
- Path: "/tabs/" + tabID + "/snapshot",
- RawQuery: r.URL.RawQuery,
- }
- o.proxyToURL(w, r, targetURL)
-}
-
-func (o *Orchestrator) handleTabScreenshot(w http.ResponseWriter, r *http.Request) {
- tabID := r.PathValue("id")
- if tabID == "" {
- web.Error(w, 400, fmt.Errorf("tab id required"))
- return
- }
-
- inst, err := o.findRunningInstanceByTabID(tabID)
- if err != nil {
- web.Error(w, 404, err)
- return
- }
-
- targetURL := &url.URL{
- Scheme: "http",
- Host: net.JoinHostPort("localhost", inst.Port),
- Path: "/tabs/" + tabID + "/screenshot",
- RawQuery: r.URL.RawQuery,
- }
- o.proxyToURL(w, r, targetURL)
-}
-
-func (o *Orchestrator) handleTabAction(w http.ResponseWriter, r *http.Request) {
- tabID := r.PathValue("id")
- if tabID == "" {
- web.Error(w, 400, fmt.Errorf("tab id required"))
- return
- }
-
- inst, err := o.findRunningInstanceByTabID(tabID)
- if err != nil {
- web.Error(w, 404, err)
- return
- }
-
- targetURL := &url.URL{
- Scheme: "http",
- Host: net.JoinHostPort("localhost", inst.Port),
- Path: "/tabs/" + tabID + "/action",
- RawQuery: r.URL.RawQuery,
- }
- o.proxyToURL(w, r, targetURL)
-}
-
-func (o *Orchestrator) handleTabActions(w http.ResponseWriter, r *http.Request) {
- tabID := r.PathValue("id")
- if tabID == "" {
- web.Error(w, 400, fmt.Errorf("tab id required"))
- return
- }
-
- inst, err := o.findRunningInstanceByTabID(tabID)
- if err != nil {
- web.Error(w, 404, err)
- return
- }
-
- targetURL := &url.URL{
- Scheme: "http",
- Host: net.JoinHostPort("localhost", inst.Port),
- Path: "/tabs/" + tabID + "/actions",
- RawQuery: r.URL.RawQuery,
- }
- o.proxyToURL(w, r, targetURL)
-}
-
-func (o *Orchestrator) handleTabText(w http.ResponseWriter, r *http.Request) {
- tabID := r.PathValue("id")
- if tabID == "" {
- web.Error(w, 400, fmt.Errorf("tab id required"))
- return
- }
-
- inst, err := o.findRunningInstanceByTabID(tabID)
- if err != nil {
- web.Error(w, 404, err)
- return
- }
-
- targetURL := &url.URL{
- Scheme: "http",
- Host: net.JoinHostPort("localhost", inst.Port),
- Path: "/tabs/" + tabID + "/text",
- RawQuery: r.URL.RawQuery,
- }
- o.proxyToURL(w, r, targetURL)
-}
-
-func (o *Orchestrator) handleTabEvaluate(w http.ResponseWriter, r *http.Request) {
- tabID := r.PathValue("id")
- if tabID == "" {
- web.Error(w, 400, fmt.Errorf("tab id required"))
- return
- }
-
- inst, err := o.findRunningInstanceByTabID(tabID)
- if err != nil {
- web.Error(w, 404, err)
- return
- }
-
- targetURL := &url.URL{
- Scheme: "http",
- Host: net.JoinHostPort("localhost", inst.Port),
- Path: "/tabs/" + tabID + "/evaluate",
- RawQuery: r.URL.RawQuery,
- }
- o.proxyToURL(w, r, targetURL)
-}
-
-func (o *Orchestrator) handleTabPDF(w http.ResponseWriter, r *http.Request) {
- tabID := r.PathValue("id")
- if tabID == "" {
- web.Error(w, 400, fmt.Errorf("tab id required"))
- return
- }
-
- inst, err := o.findRunningInstanceByTabID(tabID)
- if err != nil {
- web.Error(w, 404, err)
- return
- }
-
- targetURL := &url.URL{
- Scheme: "http",
- Host: net.JoinHostPort("localhost", inst.Port),
- Path: "/tabs/" + tabID + "/pdf",
- RawQuery: r.URL.RawQuery,
- }
- o.proxyToURL(w, r, targetURL)
-}
-
-func (o *Orchestrator) handleTabDownload(w http.ResponseWriter, r *http.Request) {
- tabID := r.PathValue("id")
- if tabID == "" {
- web.Error(w, 400, fmt.Errorf("tab id required"))
- return
- }
-
- inst, err := o.findRunningInstanceByTabID(tabID)
- if err != nil {
- web.Error(w, 404, err)
- return
- }
-
- targetURL := &url.URL{
- Scheme: "http",
- Host: net.JoinHostPort("localhost", inst.Port),
- Path: "/tabs/" + tabID + "/download",
- RawQuery: r.URL.RawQuery,
- }
- o.proxyToURL(w, r, targetURL)
-}
-
-func (o *Orchestrator) handleTabUpload(w http.ResponseWriter, r *http.Request) {
- tabID := r.PathValue("id")
- if tabID == "" {
- web.Error(w, 400, fmt.Errorf("tab id required"))
- return
- }
-
- inst, err := o.findRunningInstanceByTabID(tabID)
- if err != nil {
- web.Error(w, 404, err)
- return
- }
-
- targetURL := &url.URL{
- Scheme: "http",
- Host: net.JoinHostPort("localhost", inst.Port),
- Path: "/tabs/" + tabID + "/upload",
- RawQuery: r.URL.RawQuery,
- }
- o.proxyToURL(w, r, targetURL)
-}
-
-func (o *Orchestrator) handleTabLock(w http.ResponseWriter, r *http.Request) {
- tabID := r.PathValue("id")
- if tabID == "" {
- web.Error(w, 400, fmt.Errorf("tab id required"))
- return
- }
-
- inst, err := o.findRunningInstanceByTabID(tabID)
- if err != nil {
- web.Error(w, 404, err)
- return
- }
-
- targetURL := &url.URL{
- Scheme: "http",
- Host: net.JoinHostPort("localhost", inst.Port),
- Path: "/tabs/" + tabID + "/lock",
- RawQuery: r.URL.RawQuery,
- }
- o.proxyToURL(w, r, targetURL)
-}
-
-func (o *Orchestrator) handleTabUnlock(w http.ResponseWriter, r *http.Request) {
- tabID := r.PathValue("id")
- if tabID == "" {
- web.Error(w, 400, fmt.Errorf("tab id required"))
- return
- }
-
- inst, err := o.findRunningInstanceByTabID(tabID)
- if err != nil {
- web.Error(w, 404, err)
- return
- }
-
- targetURL := &url.URL{
- Scheme: "http",
- Host: net.JoinHostPort("localhost", inst.Port),
- Path: "/tabs/" + tabID + "/unlock",
- RawQuery: r.URL.RawQuery,
- }
- o.proxyToURL(w, r, targetURL)
-}
-
-func (o *Orchestrator) handleTabGetCookies(w http.ResponseWriter, r *http.Request) {
- tabID := r.PathValue("id")
- if tabID == "" {
- web.Error(w, 400, fmt.Errorf("tab id required"))
- return
- }
-
- inst, err := o.findRunningInstanceByTabID(tabID)
- if err != nil {
- web.Error(w, 404, err)
- return
- }
-
- targetURL := &url.URL{
- Scheme: "http",
- Host: net.JoinHostPort("localhost", inst.Port),
- Path: "/tabs/" + tabID + "/cookies",
- RawQuery: r.URL.RawQuery,
- }
- o.proxyToURL(w, r, targetURL)
-}
-
-func (o *Orchestrator) handleTabSetCookies(w http.ResponseWriter, r *http.Request) {
- tabID := r.PathValue("id")
- if tabID == "" {
- web.Error(w, 400, fmt.Errorf("tab id required"))
- return
- }
-
- inst, err := o.findRunningInstanceByTabID(tabID)
- if err != nil {
- web.Error(w, 404, err)
- return
- }
-
- targetURL := &url.URL{
- Scheme: "http",
- Host: net.JoinHostPort("localhost", inst.Port),
- Path: "/tabs/" + tabID + "/cookies",
- RawQuery: r.URL.RawQuery,
- }
- o.proxyToURL(w, r, targetURL)
-}
-
-func (o *Orchestrator) handleInstanceTabOpen(w http.ResponseWriter, r *http.Request) {
- id := r.PathValue("id")
-
- o.mu.RLock()
- inst, ok := o.instances[id]
- o.mu.RUnlock()
- if !ok {
- web.Error(w, 404, fmt.Errorf("instance %q not found", id))
- return
- }
- if inst.Status != "running" {
- web.Error(w, 503, fmt.Errorf("instance %q is not running (status: %s)", id, inst.Status))
- return
- }
-
- var req struct {
- URL string `json:"url,omitempty"`
- }
- if r.ContentLength > 0 {
- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
- web.Error(w, 400, fmt.Errorf("invalid JSON"))
- return
- }
- }
-
- payload, err := json.Marshal(map[string]any{
- "action": "new",
- "url": req.URL,
- })
- if err != nil {
- web.Error(w, 500, fmt.Errorf("failed to build tab open request: %w", err))
- return
- }
-
- proxyReq := r.Clone(r.Context())
- proxyReq.Body = io.NopCloser(bytes.NewReader(payload))
- proxyReq.ContentLength = int64(len(payload))
- proxyReq.Header = r.Header.Clone()
- proxyReq.Header.Set("Content-Type", "application/json")
-
- targetURL := &url.URL{
- Scheme: "http",
- Host: net.JoinHostPort("localhost", inst.Port),
- Path: "/tab",
- RawQuery: r.URL.RawQuery,
- }
- o.proxyToURL(w, proxyReq, targetURL)
-}
diff --git a/internal/orchestrator/handlers_instances.go b/internal/orchestrator/handlers_instances.go
new file mode 100644
index 00000000..cf374e58
--- /dev/null
+++ b/internal/orchestrator/handlers_instances.go
@@ -0,0 +1,182 @@
+package orchestrator
+
+import (
+ "encoding/json"
+ "fmt"
+ "net"
+ "net/http"
+ "net/url"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/web"
+)
+
+func (o *Orchestrator) handleGetInstance(w http.ResponseWriter, r *http.Request) {
+ id := r.PathValue("id")
+ o.mu.RLock()
+ inst, ok := o.instances[id]
+ if !ok {
+ o.mu.RUnlock()
+ web.Error(w, 404, fmt.Errorf("instance %q not found", id))
+ return
+ }
+
+ copyInst := inst.Instance
+ active := instanceIsActive(inst)
+ o.mu.RUnlock()
+
+ if active && copyInst.Status == "stopped" {
+ copyInst.Status = "running"
+ }
+ if !active &&
+ (copyInst.Status == "starting" || copyInst.Status == "running" || copyInst.Status == "stopping") {
+ copyInst.Status = "stopped"
+ }
+
+ web.JSON(w, 200, copyInst)
+}
+
+func (o *Orchestrator) handleLaunchByName(w http.ResponseWriter, r *http.Request) {
+ var req struct {
+ ProfileId string `json:"profileId,omitempty"`
+ Name string `json:"name,omitempty"`
+ Mode string `json:"mode"`
+ Port string `json:"port,omitempty"`
+ }
+
+ if r.ContentLength > 0 {
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ web.Error(w, 400, fmt.Errorf("invalid JSON"))
+ return
+ }
+ }
+
+ headless := req.Mode != "headed"
+
+ var name string
+ if req.ProfileId != "" {
+ profs, err := o.profiles.List()
+ if err != nil {
+ web.Error(w, 500, fmt.Errorf("failed to list profiles: %w", err))
+ return
+ }
+ found := false
+ for _, p := range profs {
+ if p.ID == req.ProfileId {
+ name = p.Name
+ found = true
+ break
+ }
+ }
+ if !found {
+ web.Error(w, 400, fmt.Errorf("profile %q not found", req.ProfileId))
+ return
+ }
+ } else if req.Name != "" {
+ name = req.Name
+ } else {
+ name = fmt.Sprintf("instance-%d", time.Now().UnixNano())
+ }
+
+ inst, err := o.Launch(name, req.Port, headless)
+ if err != nil {
+ statusCode := classifyLaunchError(err)
+ web.Error(w, statusCode, err)
+ return
+ }
+ web.JSON(w, 201, inst)
+}
+
+func (o *Orchestrator) handleStopByInstanceID(w http.ResponseWriter, r *http.Request) {
+ id := r.PathValue("id")
+ if err := o.Stop(id); err != nil {
+ web.Error(w, 404, err)
+ return
+ }
+ web.JSON(w, 200, map[string]string{"status": "stopped", "id": id})
+}
+
+func (o *Orchestrator) handleStartByInstanceID(w http.ResponseWriter, r *http.Request) {
+ id := r.PathValue("id")
+
+ o.mu.RLock()
+ inst, ok := o.instances[id]
+ if !ok {
+ o.mu.RUnlock()
+ web.Error(w, 404, fmt.Errorf("instance %q not found", id))
+ return
+ }
+ active := instanceIsActive(inst)
+ port := inst.Port
+ profileName := inst.ProfileName
+ headless := inst.Headless
+ o.mu.RUnlock()
+
+ if active {
+ targetURL := &url.URL{
+ Scheme: "http",
+ Host: net.JoinHostPort("localhost", port),
+ Path: "/ensure-chrome",
+ }
+ o.proxyToURL(w, r, targetURL)
+ return
+ }
+
+ started, err := o.Launch(profileName, port, headless)
+ if err != nil {
+ statusCode := classifyLaunchError(err)
+ web.Error(w, statusCode, err)
+ return
+ }
+ web.JSON(w, 201, started)
+}
+
+func (o *Orchestrator) handleLogsByID(w http.ResponseWriter, r *http.Request) {
+ id := r.PathValue("id")
+ logs, err := o.Logs(id)
+ if err != nil {
+ web.Error(w, 404, err)
+ return
+ }
+ w.Header().Set("Content-Type", "text/plain")
+ _, _ = w.Write([]byte(logs))
+}
+
+func (o *Orchestrator) handleStartInstance(w http.ResponseWriter, r *http.Request) {
+ var req struct {
+ ProfileID string `json:"profileId,omitempty"`
+ Mode string `json:"mode,omitempty"`
+ Port string `json:"port,omitempty"`
+ }
+
+ if r.ContentLength > 0 {
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ web.Error(w, 400, fmt.Errorf("invalid JSON"))
+ return
+ }
+ }
+
+ var profileName string
+ var err error
+
+ if req.ProfileID != "" {
+ profileName, err = o.resolveProfileName(req.ProfileID)
+ if err != nil {
+ web.Error(w, 404, fmt.Errorf("profile %q not found", req.ProfileID))
+ return
+ }
+ } else {
+ profileName = fmt.Sprintf("instance-%d", time.Now().UnixNano())
+ }
+
+ headless := req.Mode != "headed"
+
+ inst, err := o.Launch(profileName, req.Port, headless)
+ if err != nil {
+ statusCode := classifyLaunchError(err)
+ web.Error(w, statusCode, err)
+ return
+ }
+
+ web.JSON(w, 201, inst)
+}
diff --git a/internal/orchestrator/handlers_profiles.go b/internal/orchestrator/handlers_profiles.go
new file mode 100644
index 00000000..8e3d93e6
--- /dev/null
+++ b/internal/orchestrator/handlers_profiles.go
@@ -0,0 +1,93 @@
+package orchestrator
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+
+ "github.com/pinchtab/pinchtab/internal/web"
+)
+
+func (o *Orchestrator) resolveProfileName(idOrName string) (string, error) {
+ if o.profiles == nil {
+ return "", fmt.Errorf("profile manager not configured")
+ }
+ if name, err := o.profiles.FindByID(idOrName); err == nil {
+ return name, nil
+ }
+ if o.profiles.Exists(idOrName) {
+ return idOrName, nil
+ }
+ return "", fmt.Errorf("profile %q not found", idOrName)
+}
+
+func (o *Orchestrator) handleStartByID(w http.ResponseWriter, r *http.Request) {
+ id := r.PathValue("id")
+ name, err := o.resolveProfileName(id)
+ if err != nil {
+ web.Error(w, 404, err)
+ return
+ }
+
+ var req struct {
+ Port string `json:"port,omitempty"`
+ Headless bool `json:"headless"`
+ }
+ _ = json.NewDecoder(r.Body).Decode(&req)
+
+ inst, err := o.Launch(name, req.Port, req.Headless)
+ if err != nil {
+ statusCode := classifyLaunchError(err)
+ web.Error(w, statusCode, err)
+ return
+ }
+ web.JSON(w, 201, inst)
+}
+
+func (o *Orchestrator) handleStopByID(w http.ResponseWriter, r *http.Request) {
+ id := r.PathValue("id")
+ name, err := o.resolveProfileName(id)
+ if err != nil {
+ web.Error(w, 404, err)
+ return
+ }
+ if err := o.StopProfile(name); err != nil {
+ web.Error(w, 404, err)
+ return
+ }
+ web.JSON(w, 200, map[string]string{"status": "stopped", "id": id, "name": name})
+}
+
+func (o *Orchestrator) handleProfileInstance(w http.ResponseWriter, r *http.Request) {
+ id := r.PathValue("id")
+ name, err := o.resolveProfileName(id)
+ if err != nil {
+ web.JSON(w, 200, map[string]any{
+ "name": id,
+ "running": false,
+ "status": "stopped",
+ "port": "",
+ })
+ return
+ }
+
+ instances := o.List()
+ for _, inst := range instances {
+ if inst.ProfileName == name && (inst.Status == "running" || inst.Status == "starting") {
+ web.JSON(w, 200, map[string]any{
+ "name": name,
+ "running": inst.Status == "running",
+ "status": inst.Status,
+ "port": inst.Port,
+ "id": inst.ID,
+ })
+ return
+ }
+ }
+ web.JSON(w, 200, map[string]any{
+ "name": name,
+ "running": false,
+ "status": "stopped",
+ "port": "",
+ })
+}
diff --git a/internal/orchestrator/handlers_tabs.go b/internal/orchestrator/handlers_tabs.go
new file mode 100644
index 00000000..a298506c
--- /dev/null
+++ b/internal/orchestrator/handlers_tabs.go
@@ -0,0 +1,108 @@
+package orchestrator
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/url"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/web"
+)
+
+// handleTabClose closes a tab by finding its instance and sending a close request.
+// This has custom logic (constructs a different request body) so it's not genericized.
+func (o *Orchestrator) handleTabClose(w http.ResponseWriter, r *http.Request) {
+ tabID := r.PathValue("id")
+ if tabID == "" {
+ web.Error(w, 400, fmt.Errorf("tab id required"))
+ return
+ }
+
+ inst, err := o.findRunningInstanceByTabID(tabID)
+ if err != nil {
+ web.Error(w, 404, err)
+ return
+ }
+
+ // Construct request body for the bridge's /tab endpoint
+ reqBody, _ := json.Marshal(map[string]string{
+ "action": "close",
+ "tabId": tabID,
+ })
+
+ targetURL := fmt.Sprintf("http://localhost:%s/tab", inst.Port)
+ proxyReq, err := http.NewRequestWithContext(r.Context(), "POST", targetURL, bytes.NewReader(reqBody))
+ if err != nil {
+ web.Error(w, 500, err)
+ return
+ }
+ proxyReq.Header.Set("Content-Type", "application/json")
+
+ client := &http.Client{Timeout: 30 * time.Second}
+ resp, err := client.Do(proxyReq)
+ if err != nil {
+ web.Error(w, 502, fmt.Errorf("instance unreachable: %w", err))
+ return
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ body, _ := io.ReadAll(resp.Body)
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(resp.StatusCode)
+ _, _ = w.Write(body)
+}
+
+// handleInstanceTabOpen opens a new tab in a specific instance.
+// This has custom logic so it's not genericized.
+func (o *Orchestrator) handleInstanceTabOpen(w http.ResponseWriter, r *http.Request) {
+ id := r.PathValue("id")
+
+ o.mu.RLock()
+ inst, ok := o.instances[id]
+ o.mu.RUnlock()
+ if !ok {
+ web.Error(w, 404, fmt.Errorf("instance %q not found", id))
+ return
+ }
+ if inst.Status != "running" {
+ web.Error(w, 503, fmt.Errorf("instance %q is not running (status: %s)", id, inst.Status))
+ return
+ }
+
+ var req struct {
+ URL string `json:"url,omitempty"`
+ }
+ if r.ContentLength > 0 {
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ web.Error(w, 400, fmt.Errorf("invalid JSON"))
+ return
+ }
+ }
+
+ payload, err := json.Marshal(map[string]any{
+ "action": "new",
+ "url": req.URL,
+ })
+ if err != nil {
+ web.Error(w, 500, fmt.Errorf("failed to build tab open request: %w", err))
+ return
+ }
+
+ proxyReq := r.Clone(r.Context())
+ proxyReq.Body = io.NopCloser(bytes.NewReader(payload))
+ proxyReq.ContentLength = int64(len(payload))
+ proxyReq.Header = r.Header.Clone()
+ proxyReq.Header.Set("Content-Type", "application/json")
+
+ targetURL := &url.URL{
+ Scheme: "http",
+ Host: net.JoinHostPort("localhost", inst.Port),
+ Path: "/tab",
+ RawQuery: r.URL.RawQuery,
+ }
+ o.proxyToURL(w, proxyReq, targetURL)
+}
diff --git a/internal/orchestrator/proxy.go b/internal/orchestrator/proxy.go
new file mode 100644
index 00000000..f399cc1f
--- /dev/null
+++ b/internal/orchestrator/proxy.go
@@ -0,0 +1,181 @@
+package orchestrator
+
+import (
+ "fmt"
+ "net"
+ "net/http"
+ "net/url"
+ "strings"
+
+ "github.com/pinchtab/pinchtab/internal/web"
+)
+
+// proxyTabRequest is a generic handler that proxies requests to the instance
+// that owns the tab specified in the path. Works for any /tabs/{id}/* route.
+func (o *Orchestrator) proxyTabRequest(w http.ResponseWriter, r *http.Request) {
+ tabID := r.PathValue("id")
+ if tabID == "" {
+ web.Error(w, 400, fmt.Errorf("tab id required"))
+ return
+ }
+
+ inst, err := o.findRunningInstanceByTabID(tabID)
+ if err != nil {
+ web.Error(w, 404, err)
+ return
+ }
+
+ targetURL := &url.URL{
+ Scheme: "http",
+ Host: net.JoinHostPort("localhost", inst.Port),
+ Path: r.URL.Path,
+ RawQuery: r.URL.RawQuery,
+ }
+ o.proxyToURL(w, r, targetURL)
+}
+
+// proxyToInstance proxies a request to a specific instance by ID in the path.
+func (o *Orchestrator) proxyToInstance(w http.ResponseWriter, r *http.Request) {
+ id := r.PathValue("id")
+
+ o.mu.RLock()
+ inst, ok := o.instances[id]
+ o.mu.RUnlock()
+
+ if !ok {
+ web.Error(w, 404, fmt.Errorf("instance %q not found", id))
+ return
+ }
+
+ if inst.Status != "running" {
+ web.Error(w, 503, fmt.Errorf("instance %q is not running (status: %s)", id, inst.Status))
+ return
+ }
+
+ targetPath := r.URL.Path
+ if len(targetPath) > len("/instances/"+id) {
+ targetPath = targetPath[len("/instances/"+id):]
+ } else {
+ targetPath = ""
+ }
+
+ targetURL := &url.URL{
+ Scheme: "http",
+ Host: net.JoinHostPort("localhost", inst.Port),
+ Path: targetPath,
+ RawQuery: r.URL.RawQuery,
+ }
+ o.proxyToURL(w, r, targetURL)
+}
+
+// proxyToURL proxies an HTTP request to the given target URL.
+func (o *Orchestrator) proxyToURL(w http.ResponseWriter, r *http.Request, targetURL *url.URL) {
+ if targetURL.Hostname() != "localhost" {
+ web.Error(w, 400, fmt.Errorf("invalid proxy target: only localhost allowed"))
+ return
+ }
+
+ proxyReq, err := http.NewRequest(r.Method, targetURL.String(), r.Body)
+ if err != nil {
+ web.Error(w, 500, fmt.Errorf("failed to create proxy request: %w", err))
+ return
+ }
+
+ for key, values := range r.Header {
+ switch key {
+ case "Host", "Connection", "Keep-Alive", "Proxy-Authenticate",
+ "Proxy-Authorization", "Te", "Trailers", "Transfer-Encoding", "Upgrade":
+ default:
+ for _, value := range values {
+ proxyReq.Header.Add(key, value)
+ }
+ }
+ }
+
+ resp, err := o.client.Do(proxyReq)
+ if err != nil {
+ web.Error(w, 502, fmt.Errorf("failed to proxy to instance: %w", err))
+ return
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ for key, values := range resp.Header {
+ for _, value := range values {
+ w.Header().Add(key, value)
+ }
+ }
+
+ w.WriteHeader(resp.StatusCode)
+ _, _ = w.Write(readResponseBody(resp))
+}
+
+// findRunningInstanceByTabID finds the instance that owns the given tab.
+func (o *Orchestrator) findRunningInstanceByTabID(tabID string) (*InstanceInternal, error) {
+ o.mu.RLock()
+ instances := make([]*InstanceInternal, 0, len(o.instances))
+ for _, inst := range o.instances {
+ if inst.Status == "running" && instanceIsActive(inst) {
+ instances = append(instances, inst)
+ }
+ }
+ o.mu.RUnlock()
+
+ for _, inst := range instances {
+ tabs, err := o.fetchTabs(inst.URL)
+ if err != nil {
+ continue
+ }
+ for _, tab := range tabs {
+ if tab.ID == tabID || o.idMgr.TabIDFromCDPTarget(tab.ID) == tabID {
+ return inst, nil
+ }
+ }
+ }
+ return nil, fmt.Errorf("tab %q not found", tabID)
+}
+
+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" {
+ web.Error(w, 404, fmt.Errorf("instance not found or not running"))
+ return
+ }
+
+ targetURL := fmt.Sprintf("ws://localhost:%s/screencast?tabId=%s", inst.Port, tabID)
+ web.JSON(w, 200, map[string]string{"wsUrl": targetURL})
+}
+
+func readResponseBody(resp *http.Response) []byte {
+ if resp.Body == nil {
+ return []byte{}
+ }
+ body := make([]byte, 0)
+ buf := make([]byte, 4096)
+ for {
+ n, err := resp.Body.Read(buf)
+ if n > 0 {
+ body = append(body, buf[:n]...)
+ }
+ if err != nil {
+ break
+ }
+ }
+ return body
+}
+
+// classifyLaunchError returns appropriate HTTP status code for launch errors.
+func classifyLaunchError(err error) int {
+ msg := err.Error()
+ if strings.Contains(msg, "cannot contain") || strings.Contains(msg, "cannot be empty") {
+ return 400 // Bad Request - validation error
+ }
+ if strings.Contains(msg, "already") || strings.Contains(msg, "in use") {
+ return 409 // Conflict - resource already exists
+ }
+ return 500 // Internal Server Error
+}