Skip to content

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

fix: dashboard restart indicator, XPath security, stealth simplification, activity query limit (#307)

luigiagent6605c345d1cc
diff --git a/dashboard/src/pages/SettingsPage.tsx b/dashboard/src/pages/SettingsPage.tsx
index e35c29ec..aefae741 100644
--- a/dashboard/src/pages/SettingsPage.tsx
+++ b/dashboard/src/pages/SettingsPage.tsx
@@ -592,7 +592,6 @@ export default function SettingsPage() {
className={selectClass}
>
<option value="light">Light</option>
- <option value="medium">Medium</option>
<option value="full">Full</option>
</select>
</SettingRow>
diff --git a/dashboard/src/types/index.ts b/dashboard/src/types/index.ts
index 2f25456f..0b460017 100644
--- a/dashboard/src/types/index.ts
+++ b/dashboard/src/types/index.ts
@@ -77,7 +77,7 @@ export interface BackendInstanceDefaultsConfig {
maxParallelTabs: number;
userAgent: string;
noAnimations: boolean;
- stealthLevel: "light" | "medium" | "full";
+ stealthLevel: "light" | "full";
tabEvictionPolicy: "reject" | "close_oldest" | "close_lru";
}
diff --git a/docs/commands.md b/docs/commands.md
index 1ca1c133..6713a2d4 100644
--- a/docs/commands.md
+++ b/docs/commands.md
@@ -65,6 +65,8 @@ pinchtab press <key> # Press key (Enter, Tab, Escape...)
pinchtab hover <ref> # Hover over element
pinchtab hover --css <selector> # Hover by CSS selector
pinchtab select <ref> <value> # Select dropdown option
+pinchtab check <selector> # Check a checkbox or radio
+pinchtab uncheck <selector> # Uncheck a checkbox or radio
pinchtab scroll <ref|pixels> # Scroll to element or by pixel amount
```
diff --git a/docs/endpoints.md b/docs/endpoints.md
index b86d644d..d9ad2413 100644
--- a/docs/endpoints.md
+++ b/docs/endpoints.md
@@ -72,9 +72,9 @@ POST /tabs/{id}/action # Action on specific tab
POST /tabs/{id}/actions # Batch actions on specific tab
```
-Action kinds: `click`, `dblclick`, `type`, `fill`, `press`, `hover`, `scroll`, `select`, `focus`, `drag`
+Action kinds: `click`, `dblclick`, `type`, `fill`, `press`, `hover`, `scroll`, `select`, `focus`, `drag`, `check`, `uncheck`
-Body: `{"kind": "click", "ref": "e5"}` / `{"kind": "dblclick", "ref": "e5"}` / `{"kind": "type", "ref": "e12", "text": "hello"}`
+Body: `{"kind": "click", "ref": "e5"}` / `{"kind": "dblclick", "ref": "e5"}` / `{"kind": "type", "ref": "e12", "text": "hello"}` / `{"kind": "check", "selector": "#terms"}` / `{"kind": "uncheck", "ref": "e7"}`
## Page Analysis
diff --git a/internal/activity/activity.go b/internal/activity/activity.go
index 07537f4f..11eb085a 100644
--- a/internal/activity/activity.go
+++ b/internal/activity/activity.go
@@ -18,6 +18,7 @@ import (
const (
defaultSessionIdleTimeout = 30 * time.Minute
defaultQueryLimit = 200
+ maxQueryLimit = 1000
defaultRetentionDays = 1
)
@@ -168,10 +169,7 @@ func (s *Store) Query(filter Filter) ([]Event, error) {
return nil, nil
}
- limit := filter.Limit
- if limit <= 0 {
- limit = defaultQueryLimit
- }
+ limit := clampQueryLimit(filter.Limit)
var events []Event
for _, path := range s.queryFiles() {
@@ -211,6 +209,16 @@ func (s *Store) Query(filter Filter) ([]Event, error) {
return events, nil
}
+func clampQueryLimit(limit int) int {
+ if limit <= 0 {
+ return defaultQueryLimit
+ }
+ if limit > maxQueryLimit {
+ return maxQueryLimit
+ }
+ return limit
+}
+
func (noopRecorder) Enabled() bool {
return false
}
diff --git a/internal/activity/activity_test.go b/internal/activity/activity_test.go
index 6046e3b6..72d2456e 100644
--- a/internal/activity/activity_test.go
+++ b/internal/activity/activity_test.go
@@ -101,3 +101,15 @@ func TestNewRecorderDisabledReturnsNoop(t *testing.T) {
t.Fatal("expected disabled recorder")
}
}
+
+func TestClampQueryLimit(t *testing.T) {
+ if got := clampQueryLimit(0); got != defaultQueryLimit {
+ t.Fatalf("clampQueryLimit(0) = %d, want %d", got, defaultQueryLimit)
+ }
+ if got := clampQueryLimit(maxQueryLimit + 1); got != maxQueryLimit {
+ t.Fatalf("clampQueryLimit(max+1) = %d, want %d", got, maxQueryLimit)
+ }
+ if got := clampQueryLimit(25); got != 25 {
+ t.Fatalf("clampQueryLimit(25) = %d, want 25", got)
+ }
+}
diff --git a/internal/activity/api.go b/internal/activity/api.go
index c0f57562..704c1a45 100644
--- a/internal/activity/api.go
+++ b/internal/activity/api.go
@@ -82,7 +82,7 @@ func filterFromRequest(r *http.Request) (Filter, error) {
if err != nil || n <= 0 {
return Filter{}, errInvalidQuery("limit")
}
- filter.Limit = n
+ filter.Limit = clampQueryLimit(n)
}
if ageSec := strings.TrimSpace(q.Get("ageSec")); ageSec != "" {
n, err := strconv.Atoi(ageSec)
diff --git a/internal/activity/api_test.go b/internal/activity/api_test.go
new file mode 100644
index 00000000..ce9f2d48
--- /dev/null
+++ b/internal/activity/api_test.go
@@ -0,0 +1,27 @@
+package activity
+
+import (
+ "net/http/httptest"
+ "testing"
+)
+
+func TestFilterFromRequest_ClampsLimit(t *testing.T) {
+ req := httptest.NewRequest("GET", "/api/activity?limit=500000", nil)
+
+ filter, err := filterFromRequest(req)
+ if err != nil {
+ t.Fatalf("filterFromRequest: %v", err)
+ }
+ if filter.Limit != maxQueryLimit {
+ t.Fatalf("Limit = %d, want %d", filter.Limit, maxQueryLimit)
+ }
+}
+
+func TestFilterFromRequest_RejectsInvalidLimit(t *testing.T) {
+ req := httptest.NewRequest("GET", "/api/activity?limit=0", nil)
+
+ _, err := filterFromRequest(req)
+ if err == nil {
+ t.Fatal("expected error for invalid limit")
+ }
+}
diff --git a/internal/bridge/actions.go b/internal/bridge/actions.go
index 39f86add..975d60f9 100644
--- a/internal/bridge/actions.go
+++ b/internal/bridge/actions.go
@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"fmt"
- "strings"
"github.com/chromedp/cdproto/cdp"
"github.com/chromedp/chromedp"
@@ -542,9 +541,116 @@ func ResolveXPathToNodeID(ctx context.Context, xpath string) (int64, error) {
// ResolveTextToNodeID finds the first element whose visible text content
// contains the given string and returns its backend node ID.
func ResolveTextToNodeID(ctx context.Context, text string) (int64, error) {
- // Use XPath with contains(text(), ...) for text matching.
- xpath := fmt.Sprintf(`//*[contains(text(), %s)]`, xpathString(text))
- return ResolveXPathToNodeID(ctx, xpath)
+ var backendNodeID int64
+ err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ var docResult json.RawMessage
+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.evaluate", map[string]any{
+ "expression": "document",
+ "returnByValue": false,
+ }, &docResult); err != nil {
+ return fmt.Errorf("resolve document: %w", err)
+ }
+
+ var doc struct {
+ Result struct {
+ ObjectID string `json:"objectId"`
+ } `json:"result"`
+ }
+ if err := json.Unmarshal(docResult, &doc); err != nil {
+ return err
+ }
+ if doc.Result.ObjectID == "" {
+ return fmt.Errorf("document object not found")
+ }
+
+ const findTextFn = `function(needle) {
+ const root = this.body || this.documentElement;
+ if (!root) {
+ return null;
+ }
+ const elements = root.querySelectorAll("*");
+ for (const el of elements) {
+ const text = el.innerText || "";
+ if (!text.includes(needle)) {
+ continue;
+ }
+ let childContainsText = false;
+ for (const child of el.children) {
+ if ((child.innerText || "").includes(needle)) {
+ childContainsText = true;
+ break;
+ }
+ }
+ if (!childContainsText) {
+ return el;
+ }
+ }
+ return null;
+ }`
+
+ var callResult json.RawMessage
+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.callFunctionOn", map[string]any{
+ "functionDeclaration": findTextFn,
+ "objectId": doc.Result.ObjectID,
+ "arguments": []map[string]any{{"value": text}},
+ "returnByValue": false,
+ }, &callResult); err != nil {
+ return fmt.Errorf("find text node: %w", err)
+ }
+
+ var call struct {
+ Result struct {
+ ObjectID string `json:"objectId"`
+ Subtype string `json:"subtype"`
+ } `json:"result"`
+ }
+ if err := json.Unmarshal(callResult, &call); err != nil {
+ return err
+ }
+ if call.Result.ObjectID == "" || call.Result.Subtype == "null" {
+ return fmt.Errorf("text %q not found", text)
+ }
+
+ var nodeResult json.RawMessage
+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.requestNode", map[string]any{
+ "objectId": call.Result.ObjectID,
+ }, &nodeResult); err != nil {
+ return fmt.Errorf("request node: %w", err)
+ }
+
+ var node struct {
+ NodeID int64 `json:"nodeId"`
+ }
+ if err := json.Unmarshal(nodeResult, &node); err != nil {
+ return err
+ }
+ if node.NodeID == 0 {
+ return fmt.Errorf("text %q resolved to an invalid node", text)
+ }
+
+ var descResult json.RawMessage
+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.describeNode", map[string]any{
+ "nodeId": node.NodeID,
+ }, &descResult); err != nil {
+ return fmt.Errorf("describe node: %w", err)
+ }
+
+ var desc struct {
+ Node struct {
+ BackendNodeID int64 `json:"backendNodeId"`
+ } `json:"node"`
+ }
+ if err := json.Unmarshal(descResult, &desc); err != nil {
+ return err
+ }
+ if desc.Node.BackendNodeID == 0 {
+ return fmt.Errorf("text %q resolved to an invalid backend node", text)
+ }
+
+ backendNodeID = desc.Node.BackendNodeID
+ return nil
+ }))
+ return backendNodeID, err
}
// ResolveCSSToNodeID resolves a CSS selector to a backend node ID.
@@ -631,28 +737,3 @@ func ResolveUnifiedSelector(ctx context.Context, sel selector.Selector, refCache
return 0, fmt.Errorf("unknown selector kind: %q", sel.Kind)
}
}
-
-// xpathString returns an XPath-safe string literal using concat().
-// This safely handles all combinations of quotes and special characters.
-func xpathString(s string) string {
- // Always use concat() for safety — handles any quote combination.
- // Split on single quotes and rejoin with quoted single quote segments.
- if !strings.Contains(s, "'") {
- return "'" + s + "'"
- }
- // Use concat to handle strings with single quotes.
- // e.g., "it's" becomes concat('it', "'", 's')
- parts := strings.Split(s, "'")
- var result strings.Builder
- result.WriteString("concat(")
- for i, part := range parts {
- if i > 0 {
- result.WriteString(`, "'", `)
- }
- result.WriteString("'")
- result.WriteString(part)
- result.WriteString("'")
- }
- result.WriteString(")")
- return result.String()
-}
diff --git a/internal/bridge/actions_test.go b/internal/bridge/actions_test.go
index 456d0e39..7c9ac80a 100644
--- a/internal/bridge/actions_test.go
+++ b/internal/bridge/actions_test.go
@@ -120,27 +120,6 @@ func TestUncheckAction_WithSelector_UsesCSSPath(t *testing.T) {
}
}
-func TestXpathString(t *testing.T) {
- tests := []struct {
- input string
- expected string
- }{
- {"hello", "'hello'"},
- {"it's", "concat('it', \"'\", 's')"},
- {"say \"hi\"", "'say \"hi\"'"},
- {"it's a \"test\"", "concat('it', \"'\", 's a \"test\"')"},
- {"", "''"},
- }
- for _, tt := range tests {
- t.Run(tt.input, func(t *testing.T) {
- result := xpathString(tt.input)
- if result != tt.expected {
- t.Errorf("xpathString(%q) = %q, want %q", tt.input, result, tt.expected)
- }
- })
- }
-}
-
// ── Keyboard action tests ──────────────────────────────────────────────
func TestKeyboardTypeAction_Registered(t *testing.T) {
diff --git a/internal/config/validate.go b/internal/config/validate.go
index 1239073a..b95d89fd 100644
--- a/internal/config/validate.go
+++ b/internal/config/validate.go
@@ -84,7 +84,7 @@ func ValidateFileConfig(fc *FileConfig) []error {
if !isValidStealthLevel(fc.InstanceDefaults.StealthLevel) {
errs = append(errs, ValidationError{
Field: "instanceDefaults.stealthLevel",
- Message: fmt.Sprintf("invalid value %q (must be light, medium, or full)", fc.InstanceDefaults.StealthLevel),
+ Message: fmt.Sprintf("invalid value %q (must be light or full)", fc.InstanceDefaults.StealthLevel),
})
}
}
diff --git a/internal/dashboard/config_api.go b/internal/dashboard/config_api.go
index b0211a8b..931c4f74 100644
--- a/internal/dashboard/config_api.go
+++ b/internal/dashboard/config_api.go
@@ -68,8 +68,10 @@ func NewConfigAPI(
startedAt time.Time,
) *ConfigAPI {
boot := config.DefaultFileConfig()
- if runtime != nil {
- boot = config.FileConfigFromRuntime(runtime)
+ // Snapshot the on-disk file config at boot so restart detection compares
+ // file-at-boot against the current file, not a lossy runtime reconstruction.
+ if fc, _, err := config.LoadFileConfig(); err == nil && fc != nil {
+ boot = *fc
}
return &ConfigAPI{
runtime: runtime,
diff --git a/internal/dashboard/config_api_test.go b/internal/dashboard/config_api_test.go
new file mode 100644
index 00000000..610fbb95
--- /dev/null
+++ b/internal/dashboard/config_api_test.go
@@ -0,0 +1,65 @@
+package dashboard
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func TestNewConfigAPISnapshotsBootConfigFromFile(t *testing.T) {
+ defaults := config.DefaultFileConfig()
+ configPath := filepath.Join(t.TempDir(), "config.json")
+ t.Setenv("PINCHTAB_CONFIG", configPath)
+
+ fileConfig := map[string]any{
+ "configVersion": defaults.ConfigVersion,
+ "server": map[string]any{
+ "port": defaults.Server.Port,
+ "bind": defaults.Server.Bind,
+ "stateDir": defaults.Server.StateDir,
+ },
+ "profiles": map[string]any{
+ "baseDir": defaults.Profiles.BaseDir,
+ "defaultProfile": defaults.Profiles.DefaultProfile,
+ },
+ "multiInstance": map[string]any{
+ "strategy": defaults.MultiInstance.Strategy,
+ "restart": map[string]any{
+ "maxRestarts": nil,
+ "initBackoffSec": nil,
+ "maxBackoffSec": nil,
+ "stableAfterSec": nil,
+ },
+ },
+ }
+
+ data, err := json.Marshal(fileConfig)
+ if err != nil {
+ t.Fatalf("Marshal() error = %v", err)
+ }
+ if err := os.WriteFile(configPath, data, 0644); err != nil {
+ t.Fatalf("WriteFile() error = %v", err)
+ }
+
+ runtime := config.Load()
+ api := NewConfigAPI(runtime, nil, nil, nil, "test", time.Now())
+
+ if api.boot.MultiInstance.Restart.MaxRestarts != nil {
+ t.Fatalf("boot restart maxRestarts = %v, want nil from file snapshot", *api.boot.MultiInstance.Restart.MaxRestarts)
+ }
+
+ _, path, restartReasons, err := api.currentConfig()
+ if err != nil {
+ t.Fatalf("currentConfig() error = %v", err)
+ }
+ if path != configPath {
+ t.Fatalf("currentConfig() path = %q, want %q", path, configPath)
+ }
+ if len(restartReasons) != 0 {
+ t.Fatalf("currentConfig() restartReasons = %v, want none", restartReasons)
+ }
+}
diff --git a/tests/e2e/README.md b/tests/e2e/README.md
index 720cad7f..7ef129f0 100644
--- a/tests/e2e/README.md
+++ b/tests/e2e/README.md
@@ -63,7 +63,7 @@ The Docker stack reuses the repository root `Dockerfile` and mounts explicit con
| 02-navigate | Navigation, tab creation, tab listing |
| 03-snapshot | A11y tree extraction, text content |
| 04-tabs-api | Tab-scoped APIs (regression #207) |
-| 05-actions | Click, type, press actions |
+| 05-actions | Click, type, press, check, and uncheck actions |
| 06-screenshot-pdf | Screenshot and PDF export |
| 40-activity | Activity API capture and filtering |
| scenarios-orchestrator/01-attach-bridge | Orchestrator attaches to the dedicated `pinchtab-bridge` container and proxies tab traffic |
@@ -97,6 +97,10 @@ assert_json_length "$RESULT" '.items' 5
end_test
```
+The action scenarios already cover common interaction regressions against the bundled fixtures:
+- `tests/e2e/scenarios/05-actions.sh` covers API actions including `check` and `uncheck`
+- `tests/e2e/scenarios-cli/03-actions.sh` covers the matching CLI commands
+
## Adding Fixtures
Add HTML files to `fixtures/` for testing specific scenarios:
diff --git a/tests/e2e/scenarios-cli/03-actions.sh b/tests/e2e/scenarios-cli/03-actions.sh
index af7c3f76..ba8bda57 100755
--- a/tests/e2e/scenarios-cli/03-actions.sh
+++ b/tests/e2e/scenarios-cli/03-actions.sh
@@ -43,3 +43,22 @@ else
fi
end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "pinchtab check/uncheck <selector>"
+
+pt_ok nav "${FIXTURES_URL}/form.html"
+
+pt_ok check "#terms"
+assert_json_field ".result.checked" "true" "check marks the checkbox"
+
+pt_ok eval "document.querySelector('#terms').checked"
+assert_json_field ".result" "true" "DOM checkbox state is checked"
+
+pt_ok uncheck "#terms"
+assert_json_field ".result.checked" "false" "uncheck clears the checkbox"
+
+pt_ok eval "document.querySelector('#terms').checked"
+assert_json_field ".result" "false" "DOM checkbox state is unchecked"
+
+end_test
diff --git a/tests/e2e/scenarios/05-actions.sh b/tests/e2e/scenarios/05-actions.sh
index 81e8d86a..c0c623c4 100755
--- a/tests/e2e/scenarios/05-actions.sh
+++ b/tests/e2e/scenarios/05-actions.sh
@@ -159,3 +159,27 @@ else
fi
end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "pinchtab check/uncheck (CSS selector)"
+
+pt_post /navigate "{\"url\":\"${FIXTURES_URL}/form.html\"}"
+assert_ok "navigate"
+
+pt_post /action '{"kind":"check","selector":"#terms"}'
+assert_ok "check checkbox"
+assert_json_eq "$RESULT" '.result.checked' 'true' "check response reports checked"
+
+pt_post /evaluate '{"expression":"document.querySelector(\"#terms\").checked"}'
+assert_ok "evaluate checked state"
+assert_json_eq "$RESULT" '.result' 'true' "checkbox is checked in DOM"
+
+pt_post /action '{"kind":"uncheck","selector":"#terms"}'
+assert_ok "uncheck checkbox"
+assert_json_eq "$RESULT" '.result.checked' 'false' "uncheck response reports unchecked"
+
+pt_post /evaluate '{"expression":"document.querySelector(\"#terms\").checked"}'
+assert_ok "evaluate unchecked state"
+assert_json_eq "$RESULT" '.result' 'false' "checkbox is unchecked in DOM"
+
+end_test