Skip to content

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

Add bridge engine selection and lite action routing

zhaod216422a27236
diff --git a/cmd/pinchtab/cmd_bridge.go b/cmd/pinchtab/cmd_bridge.go
index 482ccba9..175d528a 100644
--- a/cmd/pinchtab/cmd_bridge.go
+++ b/cmd/pinchtab/cmd_bridge.go
@@ -1,21 +1,47 @@
package main
import (
+ "fmt"
+ "strings"
+
"github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/server"
"github.com/spf13/cobra"
)
+var bridgeEngine string
+
var bridgeCmd = &cobra.Command{
Use: "bridge",
Short: "Start single-instance bridge-only server",
- Run: func(cmd *cobra.Command, args []string) {
+ RunE: func(cmd *cobra.Command, args []string) error {
cfg := config.Load()
+ engineMode, err := resolveBridgeEngine(bridgeEngine, cfg.Engine)
+ if err != nil {
+ return err
+ }
+ cfg.Engine = engineMode
server.RunBridgeServer(cfg)
+ return nil
},
}
+func resolveBridgeEngine(flagValue, configValue string) (string, error) {
+ engineMode := strings.ToLower(strings.TrimSpace(configValue))
+ if strings.TrimSpace(flagValue) != "" {
+ engineMode = strings.ToLower(strings.TrimSpace(flagValue))
+ }
+ if engineMode == "" {
+ engineMode = "chrome"
+ }
+ if engineMode != "chrome" && engineMode != "lite" && engineMode != "auto" {
+ return "", fmt.Errorf("invalid --engine %q (expected chrome, lite, or auto)", engineMode)
+ }
+ return engineMode, nil
+}
+
func init() {
bridgeCmd.GroupID = "primary"
+ bridgeCmd.Flags().StringVar(&bridgeEngine, "engine", "", "Bridge engine: chrome, lite, or auto (overrides config)")
rootCmd.AddCommand(bridgeCmd)
}
diff --git a/cmd/pinchtab/cmd_bridge_test.go b/cmd/pinchtab/cmd_bridge_test.go
new file mode 100644
index 00000000..a9c789ca
--- /dev/null
+++ b/cmd/pinchtab/cmd_bridge_test.go
@@ -0,0 +1,36 @@
+package main
+
+import "testing"
+
+func TestResolveBridgeEngine(t *testing.T) {
+ tests := []struct {
+ name string
+ flagValue string
+ cfgValue string
+ want string
+ wantErr bool
+ }{
+ {name: "config default", cfgValue: "lite", want: "lite"},
+ {name: "flag overrides config", flagValue: "auto", cfgValue: "chrome", want: "auto"},
+ {name: "empty falls back to chrome", want: "chrome"},
+ {name: "invalid", flagValue: "bogus", wantErr: true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got, err := resolveBridgeEngine(tt.flagValue, tt.cfgValue)
+ if tt.wantErr {
+ if err == nil {
+ t.Fatal("expected error")
+ }
+ return
+ }
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if got != tt.want {
+ t.Fatalf("got %q want %q", got, tt.want)
+ }
+ })
+ }
+}
diff --git a/internal/config/config_load_test.go b/internal/config/config_load_test.go
index 701c77d1..f8c71611 100644
--- a/internal/config/config_load_test.go
+++ b/internal/config/config_load_test.go
@@ -174,6 +174,46 @@ func TestEnvOverridesNestedConfig(t *testing.T) {
}
}
+func TestLoadConfigEngineFromFile(t *testing.T) {
+ clearConfigEnvVars(t)
+
+ tmpDir := t.TempDir()
+ configPath := filepath.Join(tmpDir, "config.json")
+ _ = os.Setenv("PINCHTAB_CONFIG", configPath)
+ defer func() { _ = os.Unsetenv("PINCHTAB_CONFIG") }()
+
+ if err := os.WriteFile(configPath, []byte(`{"server":{"engine":"lite"}}`), 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ cfg := Load()
+ if cfg.Engine != "lite" {
+ t.Fatalf("engine = %q, want lite", cfg.Engine)
+ }
+}
+
+func TestLoadConfigEngineEnvOverridesFile(t *testing.T) {
+ clearConfigEnvVars(t)
+
+ tmpDir := t.TempDir()
+ configPath := filepath.Join(tmpDir, "config.json")
+ _ = os.Setenv("PINCHTAB_CONFIG", configPath)
+ _ = os.Setenv("PINCHTAB_ENGINE", "auto")
+ defer func() {
+ _ = os.Unsetenv("PINCHTAB_CONFIG")
+ _ = os.Unsetenv("PINCHTAB_ENGINE")
+ }()
+
+ if err := os.WriteFile(configPath, []byte(`{"server":{"engine":"lite"}}`), 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ cfg := Load()
+ if cfg.Engine != "auto" {
+ t.Fatalf("engine = %q, want auto", cfg.Engine)
+ }
+}
+
func TestApplyFileConfigToRuntimeResetsSecurityFlagsToSafeDefaults(t *testing.T) {
cfg := &RuntimeConfig{
AllowEvaluate: true,
diff --git a/internal/config/engine_test.go b/internal/config/engine_test.go
new file mode 100644
index 00000000..5cad5193
--- /dev/null
+++ b/internal/config/engine_test.go
@@ -0,0 +1,32 @@
+package config
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestLoad_EnginePrecedence(t *testing.T) {
+ t.Setenv("PINCHTAB_ENGINE", "")
+ t.Setenv("PINCHTAB_CONFIG", filepath.Join(t.TempDir(), "config.json"))
+ cfg := Load()
+ if cfg.Engine != "chrome" {
+ t.Fatalf("default engine = %q, want chrome", cfg.Engine)
+ }
+
+ configPath := filepath.Join(t.TempDir(), "config.json")
+ if err := os.WriteFile(configPath, []byte(`{"server":{"engine":"lite"}}`), 0600); err != nil {
+ t.Fatal(err)
+ }
+ t.Setenv("PINCHTAB_CONFIG", configPath)
+ cfg = Load()
+ if cfg.Engine != "lite" {
+ t.Fatalf("file engine = %q, want lite", cfg.Engine)
+ }
+
+ t.Setenv("PINCHTAB_ENGINE", "auto")
+ cfg = Load()
+ if cfg.Engine != "auto" {
+ t.Fatalf("env engine = %q, want auto", cfg.Engine)
+ }
+}
diff --git a/internal/engine/engine.go b/internal/engine/engine.go
index 7629ac33..2828f8a4 100644
--- a/internal/engine/engine.go
+++ b/internal/engine/engine.go
@@ -63,10 +63,10 @@ type SnapshotNode struct {
type Engine interface {
Name() string
Navigate(ctx context.Context, url string) (*NavigateResult, error)
- Snapshot(ctx context.Context, filter string) ([]SnapshotNode, error)
- Text(ctx context.Context) (string, error)
- Click(ctx context.Context, ref string) error
- Type(ctx context.Context, ref, text string) error
+ Snapshot(ctx context.Context, tabID, filter string) ([]SnapshotNode, error)
+ Text(ctx context.Context, tabID string) (string, error)
+ Click(ctx context.Context, tabID, ref string) error
+ Type(ctx context.Context, tabID, ref, text string) error
Capabilities() []Capability
Close() error
}
diff --git a/internal/engine/lite.go b/internal/engine/lite.go
index 6d10e5bf..093bbd6f 100644
--- a/internal/engine/lite.go
+++ b/internal/engine/lite.go
@@ -135,13 +135,13 @@ func (l *LiteEngine) Navigate(ctx context.Context, url string) (*NavigateResult,
}
// Snapshot returns the DOM tree as snapshot nodes.
-func (l *LiteEngine) Snapshot(_ context.Context, filter string) ([]SnapshotNode, error) {
+func (l *LiteEngine) Snapshot(_ context.Context, tabID, filter string) ([]SnapshotNode, error) {
l.mu.Lock()
defer l.mu.Unlock()
- tab := l.tabs[l.current]
- if tab == nil || tab.window == nil {
- return nil, errors.New("no page loaded")
+ tab, err := l.resolveTab(tabID)
+ if err != nil {
+ return nil, err
}
doc := tab.window.Document()
@@ -160,13 +160,13 @@ func (l *LiteEngine) Snapshot(_ context.Context, filter string) ([]SnapshotNode,
}
// Text returns the visible text content of the page.
-func (l *LiteEngine) Text(_ context.Context) (string, error) {
+func (l *LiteEngine) Text(_ context.Context, tabID string) (string, error) {
l.mu.Lock()
defer l.mu.Unlock()
- tab := l.tabs[l.current]
- if tab == nil || tab.window == nil {
- return "", errors.New("no page loaded")
+ tab, err := l.resolveTab(tabID)
+ if err != nil {
+ return "", err
}
doc := tab.window.Document()
@@ -184,13 +184,13 @@ func (l *LiteEngine) Text(_ context.Context) (string, error) {
}
// Click clicks an element identified by ref.
-func (l *LiteEngine) Click(ctx context.Context, ref string) (retErr error) {
+func (l *LiteEngine) Click(ctx context.Context, tabID, ref string) (retErr error) {
l.mu.Lock()
defer l.mu.Unlock()
- tab := l.tabs[l.current]
- if tab == nil {
- return errors.New("no page loaded")
+ tab, err := l.resolveTab(tabID)
+ if err != nil {
+ return err
}
el, ok := tab.refMap[ref]
@@ -214,13 +214,13 @@ func (l *LiteEngine) Click(ctx context.Context, ref string) (retErr error) {
}
// Type enters text into an element identified by ref.
-func (l *LiteEngine) Type(_ context.Context, ref, text string) error {
+func (l *LiteEngine) Type(_ context.Context, tabID, ref, text string) error {
l.mu.Lock()
defer l.mu.Unlock()
- tab := l.tabs[l.current]
- if tab == nil {
- return errors.New("no page loaded")
+ tab, err := l.resolveTab(tabID)
+ if err != nil {
+ return err
}
el, ok := tab.refMap[ref]
@@ -251,6 +251,21 @@ func (l *LiteEngine) Close() error {
return nil
}
+func (l *LiteEngine) resolveTab(tabID string) (*liteTab, error) {
+ if tabID == "" {
+ tabID = l.current
+ }
+ if tabID == "" {
+ return nil, errors.New("no page loaded")
+ }
+ tab := l.tabs[tabID]
+ if tab == nil || tab.window == nil {
+ return nil, fmt.Errorf("tab %q not found", tabID)
+ }
+ l.current = tabID
+ return tab, nil
+}
+
// ---------- helpers ----------
func (l *LiteEngine) walkDOM(tab *liteTab, node dom.Node, filter string, depth int) []SnapshotNode {
diff --git a/internal/engine/lite_test.go b/internal/engine/lite_test.go
index 7bf15863..c141cad4 100644
--- a/internal/engine/lite_test.go
+++ b/internal/engine/lite_test.go
@@ -63,7 +63,7 @@ func TestLiteEngine_Snapshot_All(t *testing.T) {
t.Fatalf("Navigate: %v", err)
}
- nodes, err := lite.Snapshot(context.Background(), "")
+ nodes, err := lite.Snapshot(context.Background(), "", "all")
if err != nil {
t.Fatalf("Snapshot: %v", err)
}
@@ -92,7 +92,7 @@ func TestLiteEngine_Snapshot_Interactive(t *testing.T) {
_, _ = lite.Navigate(context.Background(), ts.URL)
- nodes, err := lite.Snapshot(context.Background(), "interactive")
+ nodes, err := lite.Snapshot(context.Background(), "", "interactive")
if err != nil {
t.Fatalf("Snapshot interactive: %v", err)
}
@@ -117,7 +117,7 @@ func TestLiteEngine_Text(t *testing.T) {
_, _ = lite.Navigate(context.Background(), ts.URL)
- text, err := lite.Text(context.Background())
+ text, err := lite.Text(context.Background(), "")
if err != nil {
t.Fatalf("Text: %v", err)
}
@@ -138,7 +138,7 @@ func TestLiteEngine_Click(t *testing.T) {
_, _ = lite.Navigate(context.Background(), ts.URL)
- nodes, _ := lite.Snapshot(context.Background(), "interactive")
+ nodes, _ := lite.Snapshot(context.Background(), "", "interactive")
var buttonRef string
for _, n := range nodes {
if n.Role == "button" {
@@ -150,7 +150,7 @@ func TestLiteEngine_Click(t *testing.T) {
t.Fatal("no button found in snapshot")
}
- if err := lite.Click(context.Background(), buttonRef); err != nil {
+ if err := lite.Click(context.Background(), "", buttonRef); err != nil {
t.Errorf("Click: %v", err)
}
}
@@ -164,7 +164,7 @@ func TestLiteEngine_Type(t *testing.T) {
_, _ = lite.Navigate(context.Background(), ts.URL)
- nodes, _ := lite.Snapshot(context.Background(), "interactive")
+ nodes, _ := lite.Snapshot(context.Background(), "", "interactive")
var inputRef string
for _, n := range nodes {
if n.Role == "textbox" {
@@ -176,7 +176,7 @@ func TestLiteEngine_Type(t *testing.T) {
t.Fatal("no textbox found in snapshot")
}
- if err := lite.Type(context.Background(), inputRef, "hello"); err != nil {
+ if err := lite.Type(context.Background(), "", inputRef, "hello"); err != nil {
t.Errorf("Type: %v", err)
}
}
@@ -186,7 +186,7 @@ func TestLiteEngine_RefNotFound(t *testing.T) {
defer func() { _ = lite.Close() }()
// No page loaded
- _, err := lite.Snapshot(context.Background(), "")
+ _, err := lite.Snapshot(context.Background(), "", "all")
if err == nil {
t.Error("expected error for snapshot without navigate")
}
@@ -196,9 +196,9 @@ func TestLiteEngine_RefNotFound(t *testing.T) {
defer ts.Close()
_, _ = lite.Navigate(context.Background(), ts.URL)
- _, _ = lite.Snapshot(context.Background(), "")
+ _, _ = lite.Snapshot(context.Background(), "", "all")
- if err := lite.Click(context.Background(), "nonexistent"); err == nil {
+ if err := lite.Click(context.Background(), "", "nonexistent"); err == nil {
t.Error("expected error for bad ref")
}
}
@@ -219,7 +219,7 @@ func TestLiteEngine_ScriptStyleSkipped(t *testing.T) {
defer func() { _ = lite.Close() }()
_, _ = lite.Navigate(context.Background(), ts.URL)
- nodes, _ := lite.Snapshot(context.Background(), "")
+ nodes, _ := lite.Snapshot(context.Background(), "", "all")
for _, n := range nodes {
if n.Tag == "script" || n.Tag == "style" {
@@ -243,7 +243,7 @@ func TestLiteEngine_AriaAttributes(t *testing.T) {
defer func() { _ = lite.Close() }()
_, _ = lite.Navigate(context.Background(), ts.URL)
- nodes, _ := lite.Snapshot(context.Background(), "")
+ nodes, _ := lite.Snapshot(context.Background(), "", "all")
foundNav := false
foundBtn := false
@@ -283,10 +283,15 @@ func TestLiteEngine_MultiTab(t *testing.T) {
}
// Current tab is the most recent (page2)
- text, _ := lite.Text(context.Background())
+ text, _ := lite.Text(context.Background(), "")
if !strings.Contains(text, "Second") {
t.Errorf("expected page 2 text, got: %s", text)
}
+
+ text, _ = lite.Text(context.Background(), res1.TabID)
+ if !strings.Contains(text, "First") {
+ t.Errorf("expected page 1 text via tab ID, got: %s", text)
+ }
}
func TestLiteEngine_Close(t *testing.T) {
@@ -301,7 +306,7 @@ func TestLiteEngine_Close(t *testing.T) {
}
// After close, operations should fail
- _, err := lite.Snapshot(context.Background(), "")
+ _, err := lite.Snapshot(context.Background(), "", "all")
if err == nil {
t.Error("expected error after close")
}
diff --git a/internal/engine/realworld_test.go b/internal/engine/realworld_test.go
index 0fdf1d44..9ef9e22f 100644
--- a/internal/engine/realworld_test.go
+++ b/internal/engine/realworld_test.go
@@ -388,7 +388,7 @@ func runRealworldSuite(t *testing.T, tc realworldTestCase) {
func snapshotNodes(t *testing.T, lite *LiteEngine, filter string) []SnapshotNode {
t.Helper()
- nodes, err := lite.Snapshot(context.Background(), filter)
+ nodes, err := lite.Snapshot(context.Background(), "", filter)
if err != nil {
t.Fatalf("Snapshot(%q): %v", filter, err)
}
@@ -397,7 +397,7 @@ func snapshotNodes(t *testing.T, lite *LiteEngine, filter string) []SnapshotNode
func getText(t *testing.T, lite *LiteEngine) string {
t.Helper()
- text, err := lite.Text(context.Background())
+ text, err := lite.Text(context.Background(), "")
if err != nil {
t.Fatalf("Text: %v", err)
}
@@ -676,7 +676,7 @@ func TestRealworld_FormHeavy(t *testing.T) {
if firstInput == "" {
t.Fatal("no textbox found")
}
- err := lite.Type(context.Background(), firstInput, "TestUser")
+ err := lite.Type(context.Background(), "", firstInput, "TestUser")
if err != nil {
t.Errorf("Type: %v", err)
}
@@ -822,7 +822,7 @@ func TestRealworld_EmptyPage(t *testing.T) {
t.Fatalf("Navigate: %v", err)
}
- nodes, err := lite.Snapshot(context.Background(), "")
+ nodes, err := lite.Snapshot(context.Background(), "", "all")
if err != nil {
t.Fatalf("Snapshot: %v", err)
}
@@ -831,7 +831,7 @@ func TestRealworld_EmptyPage(t *testing.T) {
t.Errorf("expected <= 1 nodes for empty page, got %d", len(nodes))
}
- text, err := lite.Text(context.Background())
+ text, err := lite.Text(context.Background(), "")
if err != nil {
t.Fatalf("Text: %v", err)
}
@@ -1017,14 +1017,14 @@ func TestRealworld_ClickWorkflow(t *testing.T) {
// Click every interactive element — should not error or panic
for _, n := range nodes {
- err := lite.Click(context.Background(), n.Ref)
+ err := lite.Click(context.Background(), "", n.Ref)
if err != nil {
t.Errorf("Click(%s role=%s name=%q): %v", n.Ref, n.Role, n.Name, err)
}
}
// Engine should still be usable
- text, err := lite.Text(context.Background())
+ text, err := lite.Text(context.Background(), "")
if err != nil {
t.Fatalf("Text after clicks: %v", err)
}
@@ -1057,7 +1057,7 @@ func TestRealworld_ClickLinkRecovery(t *testing.T) {
for _, n := range nodes {
if n.Role == "link" {
- err := lite.Click(context.Background(), n.Ref)
+ err := lite.Click(context.Background(), "", n.Ref)
// Error is acceptable (recovered panic) — the key is it doesn't crash
_ = err
}
@@ -1080,7 +1080,7 @@ func TestRealworld_TypeWorkflow(t *testing.T) {
// Type into all textboxes
for _, n := range nodes {
if n.Role == "textbox" {
- err := lite.Type(context.Background(), n.Ref, "test-value")
+ err := lite.Type(context.Background(), "", n.Ref, "test-value")
if err != nil {
t.Errorf("Type(%s name=%q): %v", n.Ref, n.Name, err)
}
diff --git a/internal/engine/router_test.go b/internal/engine/router_test.go
index d433700a..090ffbca 100644
--- a/internal/engine/router_test.go
+++ b/internal/engine/router_test.go
@@ -10,12 +10,14 @@ type fakeEngine struct{ name string }
func (f *fakeEngine) Name() string { return f.name }
func (f *fakeEngine) Navigate(_ context.Context, _ string) (*NavigateResult, error) { return nil, nil }
-func (f *fakeEngine) Snapshot(_ context.Context, _ string) ([]SnapshotNode, error) { return nil, nil }
-func (f *fakeEngine) Text(_ context.Context) (string, error) { return "", nil }
-func (f *fakeEngine) Click(_ context.Context, _ string) error { return nil }
-func (f *fakeEngine) Type(_ context.Context, _, _ string) error { return nil }
-func (f *fakeEngine) Capabilities() []Capability { return nil }
-func (f *fakeEngine) Close() error { return nil }
+func (f *fakeEngine) Snapshot(_ context.Context, _, _ string) ([]SnapshotNode, error) {
+ return nil, nil
+}
+func (f *fakeEngine) Text(_ context.Context, _ string) (string, error) { return "", nil }
+func (f *fakeEngine) Click(_ context.Context, _, _ string) error { return nil }
+func (f *fakeEngine) Type(_ context.Context, _, _, _ string) error { return nil }
+func (f *fakeEngine) Capabilities() []Capability { return nil }
+func (f *fakeEngine) Close() error { return nil }
func TestRouterChromeMode(t *testing.T) {
r := NewRouter(ModeChrome, nil)
diff --git a/internal/handlers/actions.go b/internal/handlers/actions.go
index 39f4b7e9..f09eb6b3 100644
--- a/internal/handlers/actions.go
+++ b/internal/handlers/actions.go
@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
+ "errors"
"fmt"
"io"
"net/http"
@@ -13,6 +14,7 @@ import (
"github.com/chromedp/chromedp"
"github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/engine"
"github.com/pinchtab/pinchtab/internal/semantic"
"github.com/pinchtab/pinchtab/internal/web"
)
@@ -46,12 +48,6 @@ func (h *Handlers) enforceTabLease(tabID, owner string) error {
// HandleAction performs a single action on a tab (click, type, fill, etc).
func (h *Handlers) HandleAction(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
- }
-
var req bridge.ActionRequest
if r.Method == http.MethodGet {
q := r.URL.Query()
@@ -80,17 +76,19 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
web.Error(w, 400, fmt.Errorf("missing required field 'kind'"))
return
}
- if available := h.Bridge.AvailableActions(); len(available) > 0 {
- known := false
- for _, k := range available {
- if k == req.Kind {
- known = true
- break
+ if !h.shouldUseLiteAction(req.Kind) {
+ if available := h.Bridge.AvailableActions(); len(available) > 0 {
+ known := false
+ for _, k := range available {
+ if k == req.Kind {
+ known = true
+ break
+ }
+ }
+ if !known {
+ web.Error(w, 400, fmt.Errorf("unknown action kind: %s", req.Kind))
+ return
}
- }
- if !known {
- web.Error(w, 400, fmt.Errorf("unknown action kind: %s", req.Kind))
- return
}
}
@@ -125,9 +123,11 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
defer tCancel()
go web.CancelOnClientDone(r.Context(), tCancel)
+ useLiteAction := h.shouldUseLiteAction(req.Kind)
+
// Resolve ref → nodeID
refMissing := false
- if req.Ref != "" && req.NodeID == 0 && req.Selector == "" {
+ if !useLiteAction && req.Ref != "" && req.NodeID == 0 && req.Selector == "" {
cache := h.Bridge.GetRefCache(resolvedTabID)
if cache != nil {
if nid, ok := cache.Refs[req.Ref]; ok {
@@ -142,7 +142,7 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
// Cache intent before execution so recovery can reconstruct the query.
// Only cache when the ref IS in the snapshot — otherwise we'd overwrite
// the richer /find-cached entry (which has the Query) with a blank one.
- if req.Ref != "" && h.Recovery != nil && !refMissing {
+ if !useLiteAction && req.Ref != "" && h.Recovery != nil && !refMissing {
h.cacheActionIntent(resolvedTabID, req)
}
@@ -150,6 +150,7 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
// returning 404. This handles the common case where a page reload
// cleared the snapshot (DeleteRefCache) but the intent is still cached.
var result map[string]any
+ var engineName string
var actionErr error
var recoveryResult *semantic.RecoveryResult
@@ -158,7 +159,8 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
tCtx, resolvedTabID, req.Ref, req.Kind,
func(ctx context.Context, kind string, nodeID int64) (map[string]any, error) {
req.NodeID = nodeID
- return h.Bridge.ExecuteAction(ctx, kind, req)
+ res, _, err := h.executeAction(ctx, req)
+ return res, err
},
)
recoveryResult = &rr
@@ -171,14 +173,14 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
web.Error(w, 404, fmt.Errorf("ref %s not found - take a /snapshot first", req.Ref))
return
} else {
- result, actionErr = h.Bridge.ExecuteAction(tCtx, req.Kind, req)
+ result, engineName, actionErr = h.executeAction(tCtx, req)
if actionErr != nil && req.Ref != "" && shouldRetryStaleRef(actionErr) {
recordStaleRefRetry()
h.refreshRefCache(tCtx, resolvedTabID)
if cache := h.Bridge.GetRefCache(resolvedTabID); cache != nil {
if nid, ok := cache.Refs[req.Ref]; ok {
req.NodeID = nid
- result, actionErr = h.Bridge.ExecuteAction(tCtx, req.Kind, req)
+ result, engineName, actionErr = h.executeAction(tCtx, req)
}
}
}
@@ -190,7 +192,8 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
semantic.ClassifyFailure(actionErr),
func(ctx context.Context, kind string, nodeID int64) (map[string]any, error) {
req.NodeID = nodeID
- return h.Bridge.ExecuteAction(ctx, kind, req)
+ res, _, err := h.executeAction(ctx, req)
+ return res, err
},
)
recoveryResult = &rr
@@ -208,10 +211,17 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
})
return
}
+ if errors.Is(actionErr, engine.ErrLiteNotSupported) {
+ web.ErrorCode(w, http.StatusNotImplemented, "not_supported", actionErr.Error(), false, nil)
+ return
+ }
web.ErrorCode(w, 500, "action_failed", fmt.Sprintf("action %s: %v", req.Kind, actionErr), true, nil)
return
}
+ if engineName == "lite" {
+ w.Header().Set("X-Engine", "lite")
+ }
resp := map[string]any{"success": true, "result": result}
if recoveryResult != nil {
resp["recovery"] = recoveryResult
@@ -269,12 +279,6 @@ type actionResult struct {
}
func (h *Handlers) HandleActions(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
- }
-
var req actionsRequest
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
web.Error(w, 400, fmt.Errorf("decode: %w", err))
@@ -365,8 +369,9 @@ func (h *Handlers) handleActionsBatch(w http.ResponseWriter, r *http.Request, re
}
tCtx, tCancel := context.WithTimeout(ctx, h.Config.ActionTimeout)
+ useLiteAction := h.shouldUseLiteAction(action.Kind)
- if action.Ref != "" && action.NodeID == 0 && action.Selector == "" {
+ if !useLiteAction && action.Ref != "" && action.NodeID == 0 && action.Selector == "" {
cache := h.Bridge.GetRefCache(resolvedTabID)
if cache != nil {
if nid, ok := cache.Refs[action.Ref]; ok {
@@ -375,7 +380,7 @@ func (h *Handlers) handleActionsBatch(w http.ResponseWriter, r *http.Request, re
}
}
- refMissing := action.Ref != "" && action.NodeID == 0 && action.Selector == ""
+ refMissing := !useLiteAction && action.Ref != "" && action.NodeID == 0 && action.Selector == ""
if action.Kind == "" {
tCancel()
@@ -391,7 +396,7 @@ func (h *Handlers) handleActionsBatch(w http.ResponseWriter, r *http.Request, re
// Cache intent before execution so recovery can reconstruct the query.
// Only cache when the ref IS in the snapshot to avoid overwriting
// the richer /find-cached entry (which has the Query).
- if action.Ref != "" && h.Recovery != nil && !refMissing {
+ if !useLiteAction && action.Ref != "" && h.Recovery != nil && !refMissing {
h.cacheActionIntent(resolvedTabID, action)
}
@@ -405,7 +410,8 @@ func (h *Handlers) handleActionsBatch(w http.ResponseWriter, r *http.Request, re
tCtx, resolvedTabID, action.Ref, action.Kind,
func(ctx context.Context, kind string, nodeID int64) (map[string]any, error) {
action.NodeID = nodeID
- return h.Bridge.ExecuteAction(ctx, kind, action)
+ res, _, err := h.executeAction(ctx, action)
+ return res, err
},
)
_ = rr
@@ -425,14 +431,14 @@ func (h *Handlers) handleActionsBatch(w http.ResponseWriter, r *http.Request, re
}
continue
} else {
- actionRes, err = h.Bridge.ExecuteAction(tCtx, action.Kind, action)
+ actionRes, _, err = h.executeAction(tCtx, action)
if err != nil && action.Ref != "" && shouldRetryStaleRef(err) {
recordStaleRefRetry()
h.refreshRefCache(tCtx, resolvedTabID)
if cache := h.Bridge.GetRefCache(resolvedTabID); cache != nil {
if nid, ok := cache.Refs[action.Ref]; ok {
action.NodeID = nid
- actionRes, err = h.Bridge.ExecuteAction(tCtx, action.Kind, action)
+ actionRes, _, err = h.executeAction(tCtx, action)
}
}
}
@@ -443,7 +449,8 @@ func (h *Handlers) handleActionsBatch(w http.ResponseWriter, r *http.Request, re
semantic.ClassifyFailure(err),
func(ctx context.Context, kind string, nodeID int64) (map[string]any, error) {
action.NodeID = nodeID
- return h.Bridge.ExecuteAction(ctx, kind, action)
+ res, _, err := h.executeAction(ctx, action)
+ return res, err
},
)
_ = rr // recovery metadata not surfaced per-action in batch
@@ -525,9 +532,10 @@ func (h *Handlers) HandleMacro(w http.ResponseWriter, r *http.Request) {
if step.TabID == "" {
step.TabID = resolvedTabID
}
+ useLiteAction := h.shouldUseLiteAction(step.Kind)
// Resolve ref → nodeID from snapshot cache (mirrors HandleAction).
stepRefMissing := false
- if step.Ref != "" && step.NodeID == 0 && step.Selector == "" {
+ if !useLiteAction && step.Ref != "" && step.NodeID == 0 && step.Selector == "" {
cache := h.Bridge.GetRefCache(resolvedTabID)
if cache != nil {
if nid, ok := cache.Refs[step.Ref]; ok {
@@ -542,7 +550,7 @@ func (h *Handlers) HandleMacro(w http.ResponseWriter, r *http.Request) {
// Cache intent before execution so recovery can reconstruct the query.
// Only cache when the ref IS in the snapshot to avoid overwriting
// the richer /find-cached entry (which has the Query).
- if step.Ref != "" && h.Recovery != nil && !stepRefMissing {
+ if !useLiteAction && step.Ref != "" && h.Recovery != nil && !stepRefMissing {
h.cacheActionIntent(resolvedTabID, step)
}
@@ -557,7 +565,8 @@ func (h *Handlers) HandleMacro(w http.ResponseWriter, r *http.Request) {
tCtx, resolvedTabID, step.Ref, step.Kind,
func(ctx context.Context, kind string, nodeID int64) (map[string]any, error) {
step.NodeID = nodeID
- return h.Bridge.ExecuteAction(ctx, kind, step)
+ res, _, err := h.executeAction(ctx, step)
+ return res, err
},
)
_ = rr
@@ -577,14 +586,14 @@ func (h *Handlers) HandleMacro(w http.ResponseWriter, r *http.Request) {
}
continue
} else {
- res, err = h.Bridge.ExecuteAction(tCtx, step.Kind, step)
+ res, _, err = h.executeAction(tCtx, step)
if err != nil && step.Ref != "" && shouldRetryStaleRef(err) {
recordStaleRefRetry()
h.refreshRefCache(tCtx, resolvedTabID)
if cache := h.Bridge.GetRefCache(resolvedTabID); cache != nil {
if nid, ok := cache.Refs[step.Ref]; ok {
step.NodeID = nid
- res, err = h.Bridge.ExecuteAction(tCtx, step.Kind, step)
+ res, _, err = h.executeAction(tCtx, step)
}
}
}
@@ -595,7 +604,8 @@ func (h *Handlers) HandleMacro(w http.ResponseWriter, r *http.Request) {
semantic.ClassifyFailure(err),
func(ctx context.Context, kind string, nodeID int64) (map[string]any, error) {
step.NodeID = nodeID
- return h.Bridge.ExecuteAction(ctx, kind, step)
+ res, _, err := h.executeAction(ctx, step)
+ return res, err
},
)
_ = rr
@@ -665,6 +675,70 @@ func (h *Handlers) cacheActionIntent(tabID string, req bridge.ActionRequest) {
})
}
+func (h *Handlers) executeAction(ctx context.Context, req bridge.ActionRequest) (map[string]any, string, error) {
+ if h.shouldUseLiteAction(req.Kind) {
+ return h.executeLiteAction(ctx, req)
+ }
+
+ if err := h.ensureChrome(); err != nil {
+ return nil, "", fmt.Errorf("chrome initialization: %w", err)
+ }
+ result, err := h.Bridge.ExecuteAction(ctx, req.Kind, req)
+ return result, "", err
+}
+
+func (h *Handlers) shouldUseLiteAction(kind string) bool {
+ capability, ok := actionCapability(kind)
+ if !ok {
+ return h.Router != nil && h.Router.Mode() == engine.ModeLite
+ }
+ return h.useLite(capability, "")
+}
+
+func (h *Handlers) executeLiteAction(ctx context.Context, req bridge.ActionRequest) (map[string]any, string, error) {
+ if h.Router == nil || h.Router.Lite() == nil {
+ return nil, "", fmt.Errorf("lite engine unavailable")
+ }
+ switch strings.ToLower(strings.TrimSpace(req.Kind)) {
+ case bridge.ActionClick:
+ if req.Ref == "" {
+ return nil, "lite", fmt.Errorf("lite mode actions require ref from /snapshot")
+ }
+ if err := h.Router.Lite().Click(ctx, req.TabID, req.Ref); err != nil {
+ return nil, "lite", err
+ }
+ return map[string]any{"clicked": true}, "lite", nil
+ case bridge.ActionType, bridge.ActionFill:
+ if req.Ref == "" {
+ return nil, "lite", fmt.Errorf("lite mode actions require ref from /snapshot")
+ }
+ text := req.Text
+ if req.Kind == bridge.ActionFill && text == "" {
+ text = req.Value
+ }
+ if text == "" {
+ return nil, "lite", fmt.Errorf("text required for %s", req.Kind)
+ }
+ if err := h.Router.Lite().Type(ctx, req.TabID, req.Ref, text); err != nil {
+ return nil, "lite", err
+ }
+ return map[string]any{"typed": text}, "lite", nil
+ default:
+ return nil, "lite", fmt.Errorf("%w: %s", engine.ErrLiteNotSupported, req.Kind)
+ }
+}
+
+func actionCapability(kind string) (engine.Capability, bool) {
+ switch strings.ToLower(strings.TrimSpace(kind)) {
+ case bridge.ActionClick:
+ return engine.CapClick, true
+ case bridge.ActionType, bridge.ActionFill:
+ return engine.CapType, true
+ default:
+ return "", false
+ }
+}
+
func shouldRetryStaleRef(err error) bool {
if err == nil {
return false
diff --git a/internal/handlers/actions_test.go b/internal/handlers/actions_test.go
index 3cb70371..5613f6c6 100644
--- a/internal/handlers/actions_test.go
+++ b/internal/handlers/actions_test.go
@@ -5,18 +5,68 @@ import (
"context"
"encoding/json"
"fmt"
+ "io"
"net/http/httptest"
"testing"
"github.com/chromedp/cdproto/target"
"github.com/pinchtab/pinchtab/internal/bridge"
"github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/engine"
)
type failMockBridge struct {
bridge.BridgeAPI
}
+type liteActionBridge struct {
+ mockBridge
+ ensureChromeCalled bool
+}
+
+func (m *liteActionBridge) AvailableActions() []string {
+ return []string{bridge.ActionClick, bridge.ActionType, bridge.ActionPress}
+}
+
+func (m *liteActionBridge) EnsureChrome(cfg *config.RuntimeConfig) error {
+ m.ensureChromeCalled = true
+ return fmt.Errorf("ensureChrome should not be called for lite-routed actions")
+}
+
+type fakeLiteEngine struct {
+ clickRefs []string
+ typeCalls []struct {
+ ref string
+ text string
+ }
+}
+
+func (f *fakeLiteEngine) Name() string { return "lite-test" }
+func (f *fakeLiteEngine) Navigate(ctx context.Context, url string) (*engine.NavigateResult, error) {
+ return nil, fmt.Errorf("not implemented")
+}
+func (f *fakeLiteEngine) Snapshot(ctx context.Context, tabID, filter string) ([]engine.SnapshotNode, error) {
+ return nil, fmt.Errorf("not implemented")
+}
+func (f *fakeLiteEngine) Text(ctx context.Context, tabID string) (string, error) {
+ return "", fmt.Errorf("not implemented")
+}
+func (f *fakeLiteEngine) Click(ctx context.Context, tabID, ref string) error {
+ f.clickRefs = append(f.clickRefs, ref)
+ return nil
+}
+func (f *fakeLiteEngine) Type(ctx context.Context, tabID, ref, text string) error {
+ f.typeCalls = append(f.typeCalls, struct {
+ ref string
+ text string
+ }{ref: ref, text: text})
+ return nil
+}
+func (f *fakeLiteEngine) Capabilities() []engine.Capability {
+ return []engine.Capability{engine.CapClick, engine.CapType}
+}
+func (f *fakeLiteEngine) Close() error { return nil }
+
func (m *failMockBridge) TabContext(tabID string) (context.Context, string, error) {
return nil, "", fmt.Errorf("tab not found")
}
@@ -253,6 +303,94 @@ func TestHandleAction_GetMissingKind(t *testing.T) {
}
}
+func TestHandleAction_LiteClickRoutesWithoutChrome(t *testing.T) {
+ b := &liteActionBridge{}
+ lite := &fakeLiteEngine{}
+ h := New(b, &config.RuntimeConfig{}, nil, nil, nil)
+ h.Router = engine.NewRouter(engine.ModeLite, lite)
+
+ req := httptest.NewRequest("POST", "/action", bytes.NewReader([]byte(`{"kind":"click","ref":"e1"}`)))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+
+ h.HandleAction(w, req)
+
+ if w.Code != 200 {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ if got := w.Header().Get("X-Engine"); got != "lite" {
+ t.Fatalf("expected X-Engine=lite, got %q", got)
+ }
+ if b.ensureChromeCalled {
+ t.Fatal("expected lite action to skip chrome initialization")
+ }
+ if len(lite.clickRefs) != 1 || lite.clickRefs[0] != "e1" {
+ t.Fatalf("expected click ref e1, got %+v", lite.clickRefs)
+ }
+}
+
+func TestHandleAction_LiteUnsupportedReturns501(t *testing.T) {
+ b := &liteActionBridge{}
+ h := New(b, &config.RuntimeConfig{}, nil, nil, nil)
+ h.Router = engine.NewRouter(engine.ModeLite, &fakeLiteEngine{})
+
+ req := httptest.NewRequest("POST", "/action", bytes.NewReader([]byte(`{"kind":"press","ref":"e1","key":"Enter"}`)))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+
+ h.HandleAction(w, req)
+
+ if w.Code != 501 {
+ t.Fatalf("expected 501, got %d: %s", w.Code, w.Body.String())
+ }
+ if b.ensureChromeCalled {
+ t.Fatal("expected unsupported lite action to avoid chrome initialization")
+ }
+}
+
+func TestHandleActions_LiteBatchSupportsClickAndType(t *testing.T) {
+ b := &liteActionBridge{}
+ lite := &fakeLiteEngine{}
+ h := New(b, &config.RuntimeConfig{}, nil, nil, nil)
+ h.Router = engine.NewRouter(engine.ModeLite, lite)
+
+ body := `{
+ "actions": [
+ {"kind":"click","ref":"e1"},
+ {"kind":"type","ref":"e2","text":"hello"}
+ ]
+ }`
+ req := httptest.NewRequest("POST", "/actions", bytes.NewReader([]byte(body)))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+
+ h.HandleActions(w, req)
+
+ if w.Code != 200 {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ if b.ensureChromeCalled {
+ t.Fatal("expected lite batch actions to skip chrome initialization")
+ }
+
+ resp := struct {
+ Successful int `json:"successful"`
+ Failed int `json:"failed"`
+ }{}
+ if err := json.NewDecoder(bytes.NewReader(w.Body.Bytes())).Decode(&resp); err != nil && err != io.EOF {
+ t.Fatalf("decode response: %v", err)
+ }
+ if resp.Successful != 2 || resp.Failed != 0 {
+ t.Fatalf("expected 2 successful actions, got %+v", resp)
+ }
+ if len(lite.clickRefs) != 1 || lite.clickRefs[0] != "e1" {
+ t.Fatalf("unexpected click refs: %+v", lite.clickRefs)
+ }
+ if len(lite.typeCalls) != 1 || lite.typeCalls[0].ref != "e2" || lite.typeCalls[0].text != "hello" {
+ t.Fatalf("unexpected type calls: %+v", lite.typeCalls)
+ }
+}
+
func TestHandleMacro_EmptySteps(t *testing.T) {
h := New(&mockBridge{}, &config.RuntimeConfig{AllowMacro: true}, nil, nil, nil)
req := httptest.NewRequest("POST", "/macro", bytes.NewReader([]byte(`{"tabId":"tab1","steps":[]}`)))
diff --git a/internal/handlers/lite_engine_test.go b/internal/handlers/lite_engine_test.go
new file mode 100644
index 00000000..d2b319f2
--- /dev/null
+++ b/internal/handlers/lite_engine_test.go
@@ -0,0 +1,137 @@
+package handlers
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/engine"
+)
+
+func newLiteTestPage() *httptest.Server {
+ return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _, _ = w.Write([]byte(`<!doctype html><html><body><input placeholder="Name"><button>Save</button></body></html>`))
+ }))
+}
+
+func liteHandlersWithPage(t *testing.T) (*Handlers, string, string) {
+ t.Helper()
+ ts := newLiteTestPage()
+ t.Cleanup(ts.Close)
+
+ lite := engine.NewLiteEngine()
+ t.Cleanup(func() { _ = lite.Close() })
+
+ h := New(&mockBridge{}, &config.RuntimeConfig{Engine: "lite"}, nil, nil, nil)
+ h.Router = engine.NewRouter(engine.ModeLite, lite)
+
+ res, err := lite.Navigate(context.Background(), ts.URL)
+ if err != nil {
+ t.Fatalf("navigate: %v", err)
+ }
+ return h, ts.URL, res.TabID
+}
+
+func TestHandleAction_LiteTypeAndClick(t *testing.T) {
+ h, _, tabID := liteHandlersWithPage(t)
+
+ w := httptest.NewRecorder()
+ req := httptest.NewRequest("GET", "/snapshot?tabId="+tabID+"&filter=interactive", nil)
+ h.HandleSnapshot(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("snapshot status = %d body=%s", w.Code, w.Body.String())
+ }
+
+ var snap struct {
+ Nodes []struct {
+ Ref string `json:"ref"`
+ Role string `json:"role"`
+ } `json:"nodes"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &snap); err != nil {
+ t.Fatalf("unmarshal snapshot: %v", err)
+ }
+
+ var inputRef, buttonRef string
+ for _, n := range snap.Nodes {
+ switch n.Role {
+ case "textbox":
+ inputRef = n.Ref
+ case "button":
+ buttonRef = n.Ref
+ }
+ }
+ if inputRef == "" || buttonRef == "" {
+ t.Fatalf("missing refs: textbox=%q button=%q", inputRef, buttonRef)
+ }
+
+ w = httptest.NewRecorder()
+ req = httptest.NewRequest("POST", "/action", bytes.NewReader([]byte(`{"tabId":"`+tabID+`","kind":"type","ref":"`+inputRef+`","text":"hello"}`)))
+ req.Header.Set("Content-Type", "application/json")
+ h.HandleAction(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("type status = %d body=%s", w.Code, w.Body.String())
+ }
+ if got := w.Header().Get("X-Engine"); got != "lite" {
+ t.Fatalf("X-Engine = %q, want lite", got)
+ }
+
+ w = httptest.NewRecorder()
+ req = httptest.NewRequest("POST", "/action", bytes.NewReader([]byte(`{"tabId":"`+tabID+`","kind":"click","ref":"`+buttonRef+`"}`)))
+ req.Header.Set("Content-Type", "application/json")
+ h.HandleAction(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("click status = %d body=%s", w.Code, w.Body.String())
+ }
+}
+
+func TestHandleAction_LiteUnsupportedAction(t *testing.T) {
+ h, _, tabID := liteHandlersWithPage(t)
+ w := httptest.NewRecorder()
+ req := httptest.NewRequest("POST", "/action", strings.NewReader(`{"tabId":"`+tabID+`","kind":"press","key":"Enter"}`))
+ req.Header.Set("Content-Type", "application/json")
+ h.HandleAction(w, req)
+ if w.Code != http.StatusNotImplemented {
+ t.Fatalf("status = %d body=%s", w.Code, w.Body.String())
+ }
+}
+
+func TestHandleText_LiteRespectsTabID(t *testing.T) {
+ page1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _, _ = w.Write([]byte(`<html><body>first page</body></html>`))
+ }))
+ defer page1.Close()
+ page2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _, _ = w.Write([]byte(`<html><body>second page</body></html>`))
+ }))
+ defer page2.Close()
+
+ lite := engine.NewLiteEngine()
+ defer func() { _ = lite.Close() }()
+ h := New(&mockBridge{}, &config.RuntimeConfig{Engine: "lite"}, nil, nil, nil)
+ h.Router = engine.NewRouter(engine.ModeLite, lite)
+
+ res1, err := lite.Navigate(context.Background(), page1.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, err = lite.Navigate(context.Background(), page2.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ w := httptest.NewRecorder()
+ req := httptest.NewRequest("GET", "/text?tabId="+res1.TabID+"&format=text", nil)
+ h.HandleText(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d body=%s", w.Code, w.Body.String())
+ }
+ if !strings.Contains(w.Body.String(), "first page") {
+ t.Fatalf("expected first page text, got %q", w.Body.String())
+ }
+}
diff --git a/internal/handlers/snapshot.go b/internal/handlers/snapshot.go
index 78d90850..b4684b2a 100644
--- a/internal/handlers/snapshot.go
+++ b/internal/handlers/snapshot.go
@@ -63,8 +63,9 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {
filter := r.URL.Query().Get("filter")
// --- Lite engine fast path ---
+ tabID := r.URL.Query().Get("tabId")
if h.useLite(engine.CapSnapshot, "") {
- nodes, err := h.Router.Lite().Snapshot(r.Context(), filter)
+ nodes, err := h.Router.Lite().Snapshot(r.Context(), tabID, filter)
if err != nil {
web.Error(w, 500, fmt.Errorf("lite snapshot: %w", err))
return
@@ -85,8 +86,7 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {
return
}
- tabID := r.URL.Query().Get("tabId")
- // filter already parsed above for lite path
+ // filter and tabID already parsed above for lite path
doDiff := r.URL.Query().Get("diff") == "true"
format := r.URL.Query().Get("format")
output := r.URL.Query().Get("output")
diff --git a/internal/handlers/text.go b/internal/handlers/text.go
index e9b8a060..cb13f0d8 100644
--- a/internal/handlers/text.go
+++ b/internal/handlers/text.go
@@ -19,8 +19,9 @@ import (
// @Endpoint GET /text
func (h *Handlers) HandleText(w http.ResponseWriter, r *http.Request) {
// --- Lite engine fast path ---
+ tabID := r.URL.Query().Get("tabId")
if h.useLite(engine.CapText, "") {
- text, err := h.Router.Lite().Text(r.Context())
+ text, err := h.Router.Lite().Text(r.Context(), tabID)
if err != nil {
web.Error(w, 500, fmt.Errorf("lite text: %w", err))
return
@@ -37,7 +38,6 @@ func (h *Handlers) HandleText(w http.ResponseWriter, r *http.Request) {
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
diff --git a/internal/server/bridge.go b/internal/server/bridge.go
index d27f78e6..f493118c 100644
--- a/internal/server/bridge.go
+++ b/internal/server/bridge.go
@@ -32,13 +32,7 @@ func RunBridgeServer(cfg *config.RuntimeConfig) {
mux := http.NewServeMux()
h := handlers.New(bridgeInstance, cfg, nil, nil, nil)
-
- mode := engine.Mode(cfg.Engine)
- if mode == engine.ModeLite || mode == engine.ModeAuto {
- lite := engine.NewLiteEngine()
- h.Router = engine.NewRouter(mode, lite)
- slog.Info("engine router enabled", "mode", cfg.Engine, "rules", h.Router.Rules())
- }
+ configureBridgeRouter(h, cfg)
shutdownOnce := &sync.Once{}
doShutdown := func() {
@@ -87,3 +81,14 @@ func RunBridgeServer(cfg *config.RuntimeConfig) {
slog.Error("shutdown error", "err", err)
}
}
+
+func configureBridgeRouter(h *handlers.Handlers, cfg *config.RuntimeConfig) {
+ mode := engine.Mode(cfg.Engine)
+ if mode != engine.ModeLite && mode != engine.ModeAuto {
+ return
+ }
+
+ lite := engine.NewLiteEngine()
+ h.Router = engine.NewRouter(mode, lite)
+ slog.Info("engine router enabled", "mode", cfg.Engine, "rules", h.Router.Rules())
+}
diff --git a/internal/server/bridge_test.go b/internal/server/bridge_test.go
new file mode 100644
index 00000000..99a1a8a6
--- /dev/null
+++ b/internal/server/bridge_test.go
@@ -0,0 +1,33 @@
+package server
+
+import (
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/handlers"
+)
+
+func TestConfigureBridgeRouter(t *testing.T) {
+ tests := []struct {
+ name string
+ engine string
+ wantRouter bool
+ }{
+ {name: "chrome", engine: "chrome", wantRouter: false},
+ {name: "lite", engine: "lite", wantRouter: true},
+ {name: "auto", engine: "auto", wantRouter: true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ h := handlers.New(nil, &config.RuntimeConfig{Engine: tt.engine}, nil, nil, nil)
+ configureBridgeRouter(h, &config.RuntimeConfig{Engine: tt.engine})
+ if (h.Router != nil) != tt.wantRouter {
+ t.Fatalf("router presence = %v, want %v", h.Router != nil, tt.wantRouter)
+ }
+ if h.Router != nil && string(h.Router.Mode()) != tt.engine {
+ t.Fatalf("router mode = %q, want %q", h.Router.Mode(), tt.engine)
+ }
+ })
+ }
+}