High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
feat: add config get subcommand and --instance CLI flag
Djain912cd3c6d92575b
diff --git a/cmd/pinchtab/cmd_cli.go b/cmd/pinchtab/cmd_cli.goindex 5aa7d381..784403d0 100644--- a/cmd/pinchtab/cmd_cli.go+++ b/cmd/pinchtab/cmd_cli.go@@ -82,6 +82,10 @@ ENVIRONMENT:BRIDGE_PORT Server port (default: 9867)BRIDGE_HEADLESS Run Chrome headless (default: true)+FLAGS (global, place before or after command):+ --instance <id> Target a specific instance by ID (e.g., pinchtab nav --instance abc123 https://...)+ -I <id> Alias for --instance+Examples:pinchtab nav https://pinchtab.compinchtab snap -i -c@@ -113,11 +117,23 @@ func isCLICommand(cmd string) bool {func runCLI(cfg *config.RuntimeConfig) {cmd := os.Args[1]- args := os.Args[2:]+ rawArgs := os.Args[2:]++ // Extract --instance/-I flag and strip it from args so sub-commands don't see it.+ var instanceID string+ args := make([]string, 0, len(rawArgs))+ for i := 0; i < len(rawArgs); i++ {+ if (rawArgs[i] == "--instance" || rawArgs[i] == "-I") && i+1 < len(rawArgs) {+ instanceID = rawArgs[i+1]+ i++ // skip the value+ } else {+ args = append(args, rawArgs[i])+ }+ }- base := fmt.Sprintf("http://%s:%s", cfg.Bind, cfg.Port)+ orchBase := fmt.Sprintf("http://%s:%s", cfg.Bind, cfg.Port)if envURL := os.Getenv("PINCHTAB_URL"); envURL != "" {- base = strings.TrimRight(envURL, "/")+ orchBase = strings.TrimRight(envURL, "/")}token := cfg.Token@@ -125,6 +141,12 @@ func runCLI(cfg *config.RuntimeConfig) {token = envToken}+ // --instance resolves the target base URL from the named instance's port.+ base := orchBase+ if instanceID != "" {+ base = resolveInstanceBase(orchBase, token, instanceID, cfg.Bind)+ }+client := &http.Client{Timeout: 30 * time.Second}// Check if server is running (except for help)@@ -217,6 +239,9 @@ Environment:PINCHTAB_URL Server URL (default: http://localhost:9867)PINCHTAB_TOKEN Auth token (sent as Bearer)+Flags (global):+ --instance <id>, -I <id> Target a specific instance (e.g., pinchtab snap --instance abc123)+Pipe with jq:pinchtab snap -i | jq '.nodes[] | select(.role=="link")'`)@@ -1285,6 +1310,24 @@ func min(a, b int) int {return b}+// resolveInstanceBase fetches the named instance from the orchestrator and returns+// a base URL pointing directly at that instance's API port.+func resolveInstanceBase(orchBase, token, instanceID, bind string) string {+ c := &http.Client{Timeout: 10 * time.Second}+ body := doGetRaw(c, orchBase, token, fmt.Sprintf("/instances/%s", instanceID), nil)++ var inst struct {+ Port string `json:"port"`+ }+ if err := json.Unmarshal(body, &inst); err != nil {+ fatal("failed to parse instance %q: %v", instanceID, err)+ }+ if inst.Port == "" {+ fatal("instance %q has no port assigned (is it still starting?)", instanceID)+ }+ return fmt.Sprintf("http://%s:%s", bind, inst.Port)+}+func fatal(format string, args ...any) {fmt.Fprintf(os.Stderr, format+"\n", args...)os.Exit(1)diff --git a/cmd/pinchtab/cmd_cli_test.go b/cmd/pinchtab/cmd_cli_test.goindex d5e06339..f910ffba 100644--- a/cmd/pinchtab/cmd_cli_test.go+++ b/cmd/pinchtab/cmd_cli_test.go@@ -651,3 +651,37 @@ func TestCheckServerAndGuide(t *testing.T) {t.Error("expected auth error message")}}++// TestResolveInstanceBase verifies that --instance resolves the correct base URL+// from the orchestrator's /instances/<id> response.+func TestResolveInstanceBase(t *testing.T) {+ // Orchestrator mock returns an instance with port 9901.+ orch := newMockServer()+ orch.response = `{"id":"abc123","port":"9901","status":"running"}`+ defer orch.close()+ client := orch.server.Client()+ _ = client // resolveInstanceBase builds its own client++ got := resolveInstanceBase(orch.base(), "", "abc123", "127.0.0.1")++ if orch.lastPath != "/instances/abc123" {+ t.Errorf("expected GET /instances/abc123, got %s", orch.lastPath)+ }+ if got != "http://127.0.0.1:9901" {+ t.Errorf("resolveInstanceBase = %q, want %q", got, "http://127.0.0.1:9901")+ }+}++// TestResolveInstanceBase_ForwardsToken verifies that the auth token is sent to the orchestrator.+func TestResolveInstanceBase_ForwardsToken(t *testing.T) {+ orch := newMockServer()+ orch.response = `{"id":"xyz","port":"9902","status":"running"}`+ defer orch.close()++ resolveInstanceBase(orch.base(), "my-token", "xyz", "localhost")++ authHeader := orch.lastHeaders.Get("Authorization")+ if authHeader != "Bearer my-token" {+ t.Errorf("Authorization header = %q, want %q", authHeader, "Bearer my-token")+ }+}diff --git a/internal/config/config.go b/internal/config/config.goindex 6286e313..2443c661 100644--- a/internal/config/config.go+++ b/internal/config/config.go@@ -748,6 +748,8 @@ func HandleConfigCommand(cfg *RuntimeConfig) {handleConfigPath()case "validate":handleConfigValidate()+ case "get":+ handleConfigGet()case "set":handleConfigSet()case "patch":@@ -767,10 +769,41 @@ func printConfigUsage() {fmt.Println(" show Show current configuration")fmt.Println(" path Show config file path")fmt.Println(" validate Validate config file")+ fmt.Println(" get <path> Get a config value (e.g., server.port)")fmt.Println(" set <path> <val> Set a config value (e.g., server.port 8080)")fmt.Println(" patch <json> Merge JSON into config")}+func handleConfigGet() {+ if len(os.Args) < 4 {+ fmt.Println("Usage: pinchtab config get <path>")+ fmt.Println()+ fmt.Println("Examples:")+ fmt.Println(" pinchtab config get server.port")+ fmt.Println(" pinchtab config get instanceDefaults.mode")+ fmt.Println(" pinchtab config get attach.allowHosts")+ fmt.Println()+ fmt.Println("Sections: server, browser, instanceDefaults, security, profiles, multiInstance, attach, timeouts")+ os.Exit(1)+ }++ path := os.Args[3]++ fc, _, err := LoadFileConfig()+ if err != nil {+ fmt.Printf("Error loading config: %v\n", err)+ os.Exit(1)+ }++ value, err := GetConfigValue(fc, path)+ if err != nil {+ fmt.Printf("Error: %v\n", err)+ os.Exit(1)+ }++ fmt.Println(value)+}+func handleConfigInit() {configPath := filepath.Join(userConfigDir(), "config.json")diff --git a/internal/config/editor.go b/internal/config/editor.goindex d44bda39..9de727f6 100644--- a/internal/config/editor.go+++ b/internal/config/editor.go@@ -229,6 +229,187 @@ func setAttachField(a *AttachConfig, field, value string) error {return nil}+// GetConfigValue reads a dotted-path field from FileConfig and returns its string representation.+// The path format matches SetConfigValue (e.g., "server.port", "attach.allowHosts").+// Pointer fields that are unset return an empty string.+// Slice fields are returned as comma-separated values.+func GetConfigValue(fc *FileConfig, path string) (string, error) {+ parts := strings.SplitN(path, ".", 2)+ if len(parts) != 2 {+ return "", fmt.Errorf("invalid path %q (expected section.field, e.g., server.port)", path)+ }++ section, field := parts[0], parts[1]++ switch section {+ case "server":+ return getServerField(&fc.Server, field)+ case "browser":+ return getBrowserField(&fc.Browser, field)+ case "instanceDefaults":+ return getInstanceDefaultsField(&fc.InstanceDefaults, field)+ case "security":+ return getSecurityField(&fc.Security, field)+ case "profiles":+ return getProfilesField(&fc.Profiles, field)+ case "multiInstance":+ return getMultiInstanceField(&fc.MultiInstance, field)+ case "attach":+ return getAttachField(&fc.Attach, field)+ case "timeouts":+ return getTimeoutsField(&fc.Timeouts, field)+ default:+ return "", fmt.Errorf("unknown section %q (valid: server, browser, instanceDefaults, security, profiles, multiInstance, attach, timeouts)", section)+ }+}++func getServerField(s *ServerConfig, field string) (string, error) {+ switch field {+ case "port":+ return s.Port, nil+ case "bind":+ return s.Bind, nil+ case "token":+ return s.Token, nil+ case "stateDir":+ return s.StateDir, nil+ default:+ return "", fmt.Errorf("unknown field server.%s", field)+ }+}++func getBrowserField(b *BrowserConfig, field string) (string, error) {+ switch field {+ case "version":+ return b.ChromeVersion, nil+ case "binary":+ return b.ChromeBinary, nil+ case "extraFlags":+ return b.ChromeExtraFlags, nil+ default:+ return "", fmt.Errorf("unknown field browser.%s", field)+ }+}++func getInstanceDefaultsField(c *InstanceDefaultsConfig, field string) (string, error) {+ switch field {+ case "mode":+ return c.Mode, nil+ case "noRestore":+ return formatBoolPtr(c.NoRestore), nil+ case "timezone":+ return c.Timezone, nil+ case "blockImages":+ return formatBoolPtr(c.BlockImages), nil+ case "blockMedia":+ return formatBoolPtr(c.BlockMedia), nil+ case "blockAds":+ return formatBoolPtr(c.BlockAds), nil+ case "maxTabs":+ return formatIntPtr(c.MaxTabs), nil+ case "maxParallelTabs":+ return formatIntPtr(c.MaxParallelTabs), nil+ case "userAgent":+ return c.UserAgent, nil+ case "noAnimations":+ return formatBoolPtr(c.NoAnimations), nil+ case "stealthLevel":+ return c.StealthLevel, nil+ case "tabEvictionPolicy":+ return c.TabEvictionPolicy, nil+ default:+ return "", fmt.Errorf("unknown field instanceDefaults.%s", field)+ }+}++func getSecurityField(s *SecurityConfig, field string) (string, error) {+ switch field {+ case "allowEvaluate":+ return formatBoolPtr(s.AllowEvaluate), nil+ case "allowMacro":+ return formatBoolPtr(s.AllowMacro), nil+ case "allowScreencast":+ return formatBoolPtr(s.AllowScreencast), nil+ case "allowDownload":+ return formatBoolPtr(s.AllowDownload), nil+ case "allowUpload":+ return formatBoolPtr(s.AllowUpload), nil+ default:+ return "", fmt.Errorf("unknown field security.%s", field)+ }+}++func getProfilesField(p *ProfilesConfig, field string) (string, error) {+ switch field {+ case "baseDir":+ return p.BaseDir, nil+ case "defaultProfile":+ return p.DefaultProfile, nil+ default:+ return "", fmt.Errorf("unknown field profiles.%s", field)+ }+}++func getMultiInstanceField(o *MultiInstanceConfig, field string) (string, error) {+ switch field {+ case "strategy":+ return o.Strategy, nil+ case "allocationPolicy":+ return o.AllocationPolicy, nil+ case "instancePortStart":+ return formatIntPtr(o.InstancePortStart), nil+ case "instancePortEnd":+ return formatIntPtr(o.InstancePortEnd), nil+ default:+ return "", fmt.Errorf("unknown field multiInstance.%s", field)+ }+}++func getAttachField(a *AttachConfig, field string) (string, error) {+ switch field {+ case "enabled":+ return formatBoolPtr(a.Enabled), nil+ case "allowHosts":+ return strings.Join(a.AllowHosts, ","), nil+ case "allowSchemes":+ return strings.Join(a.AllowSchemes, ","), nil+ default:+ return "", fmt.Errorf("unknown field attach.%s", field)+ }+}++func getTimeoutsField(t *TimeoutsConfig, field string) (string, error) {+ switch field {+ case "actionSec":+ return strconv.Itoa(t.ActionSec), nil+ case "navigateSec":+ return strconv.Itoa(t.NavigateSec), nil+ case "shutdownSec":+ return strconv.Itoa(t.ShutdownSec), nil+ case "waitNavMs":+ return strconv.Itoa(t.WaitNavMs), nil+ default:+ return "", fmt.Errorf("unknown field timeouts.%s", field)+ }+}++func formatBoolPtr(b *bool) string {+ if b == nil {+ return ""+ }+ if *b {+ return "true"+ }+ return "false"+}++func formatIntPtr(n *int) string {+ if n == nil {+ return ""+ }+ return strconv.Itoa(*n)+}+func parseBool(s string) (bool, error) {switch strings.ToLower(strings.TrimSpace(s)) {case "true", "1", "yes", "on":diff --git a/internal/config/editor_test.go b/internal/config/editor_test.goindex e30acaa2..d80da570 100644--- a/internal/config/editor_test.go+++ b/internal/config/editor_test.go@@ -349,3 +349,137 @@ func TestParseBool(t *testing.T) {})}}++// --- GetConfigValue ---++func TestGetConfigValue_RoundTrip(t *testing.T) {+ // For every path that SetConfigValue accepts, GetConfigValue must return+ // a string that parses back to the same value.+ triples := []struct {+ path string+ value string+ want string // what GetConfigValue should return+ }{+ {"server.port", "8080", "8080"},+ {"server.bind", "0.0.0.0", "0.0.0.0"},+ {"server.token", "s3cr3t", "s3cr3t"},+ {"server.stateDir", "/tmp/state", "/tmp/state"},+ {"browser.version", "120.0", "120.0"},+ {"browser.binary", "/usr/bin/chrome", "/usr/bin/chrome"},+ {"instanceDefaults.mode", "headed", "headed"},+ {"instanceDefaults.noRestore", "true", "true"},+ {"instanceDefaults.blockImages", "false", "false"},+ {"instanceDefaults.blockAds", "1", "true"}, // normalised by parseBool then formatBoolPtr+ {"instanceDefaults.maxTabs", "50", "50"},+ {"instanceDefaults.maxParallelTabs", "8", "8"},+ {"instanceDefaults.userAgent", "MyBot/1.0", "MyBot/1.0"},+ {"instanceDefaults.stealthLevel", "full", "full"},+ {"instanceDefaults.tabEvictionPolicy", "close_lru", "close_lru"},+ {"security.allowEvaluate", "true", "true"},+ {"security.allowMacro", "false", "false"},+ {"security.allowScreencast", "on", "true"},+ {"security.allowDownload", "off", "false"},+ {"security.allowUpload", "yes", "true"},+ {"profiles.baseDir", "/profiles", "/profiles"},+ {"profiles.defaultProfile", "agent", "agent"},+ {"multiInstance.strategy", "explicit", "explicit"},+ {"multiInstance.allocationPolicy", "round_robin", "round_robin"},+ {"multiInstance.instancePortStart", "9900", "9900"},+ {"multiInstance.instancePortEnd", "9950", "9950"},+ {"attach.enabled", "true", "true"},+ {"timeouts.actionSec", "60", "60"},+ {"timeouts.navigateSec", "90", "90"},+ {"timeouts.shutdownSec", "15", "15"},+ {"timeouts.waitNavMs", "3000", "3000"},+ }++ for _, tt := range triples {+ t.Run(tt.path, func(t *testing.T) {+ fc := &FileConfig{}+ if err := SetConfigValue(fc, tt.path, tt.value); err != nil {+ t.Fatalf("SetConfigValue(%q, %q) error = %v", tt.path, tt.value, err)+ }+ got, err := GetConfigValue(fc, tt.path)+ if err != nil {+ t.Fatalf("GetConfigValue(%q) error = %v", tt.path, err)+ }+ if got != tt.want {+ t.Errorf("GetConfigValue(%q) = %q, want %q", tt.path, got, tt.want)+ }+ })+ }+}++func TestGetConfigValue_NilPointerReturnsEmpty(t *testing.T) {+ fc := &FileConfig{}+ // Pointer fields that have not been set should return "".+ ptrs := []string{+ "instanceDefaults.noRestore",+ "instanceDefaults.blockImages",+ "instanceDefaults.blockMedia",+ "instanceDefaults.blockAds",+ "instanceDefaults.maxTabs",+ "instanceDefaults.maxParallelTabs",+ "instanceDefaults.noAnimations",+ "security.allowEvaluate",+ "security.allowMacro",+ "security.allowScreencast",+ "security.allowDownload",+ "security.allowUpload",+ "multiInstance.instancePortStart",+ "multiInstance.instancePortEnd",+ "attach.enabled",+ }+ for _, path := range ptrs {+ t.Run(path, func(t *testing.T) {+ got, err := GetConfigValue(fc, path)+ if err != nil {+ t.Fatalf("GetConfigValue(%q) unexpected error: %v", path, err)+ }+ if got != "" {+ t.Errorf("GetConfigValue(%q) = %q, want empty string for unset pointer", path, got)+ }+ })+ }+}++func TestGetConfigValue_AttachSlices(t *testing.T) {+ fc := &FileConfig{}+ fc.Attach.AllowHosts = []string{"127.0.0.1", "localhost"}+ fc.Attach.AllowSchemes = []string{"ws", "wss"}++ hosts, err := GetConfigValue(fc, "attach.allowHosts")+ if err != nil {+ t.Fatalf("GetConfigValue(attach.allowHosts) error = %v", err)+ }+ if hosts != "127.0.0.1,localhost" {+ t.Errorf("allowHosts = %q, want %q", hosts, "127.0.0.1,localhost")+ }++ schemes, err := GetConfigValue(fc, "attach.allowSchemes")+ if err != nil {+ t.Fatalf("GetConfigValue(attach.allowSchemes) error = %v", err)+ }+ if schemes != "ws,wss" {+ t.Errorf("allowSchemes = %q, want %q", schemes, "ws,wss")+ }+}++func TestGetConfigValue_UnknownPaths(t *testing.T) {+ fc := &FileConfig{}+ errorCases := []string{+ "port", // missing section+ "", // empty+ "unknown.field", // unknown section+ "server.ghost", // unknown field in known section+ "attach.badfield", // unknown attach field+ }+ for _, path := range errorCases {+ t.Run(path, func(t *testing.T) {+ _, err := GetConfigValue(fc, path)+ if err == nil {+ t.Errorf("GetConfigValue(%q) should have returned an error", path)+ }+ })+ }+}diff --git a/tests/integration/config_cli_test.go b/tests/integration/config_cli_test.goindex 0ffeaf93..9ab12353 100644--- a/tests/integration/config_cli_test.go+++ b/tests/integration/config_cli_test.go@@ -292,3 +292,82 @@ func filterTestEnv() []string {}return out}++// TestConfigCLI_Get tests `pinchtab config get`+func TestConfigCLI_Get(t *testing.T) {+ tmpDir := t.TempDir()+ configPath := filepath.Join(tmpDir, "config.json")++ // Initialize config, then set a known value.+ initCmd := exec.Command(server.BinaryPath, "config", "init")+ initCmd.Env = append(filterTestEnv(), "PINCHTAB_CONFIG="+configPath, "HOME="+tmpDir)+ if out, err := initCmd.CombinedOutput(); err != nil {+ t.Fatalf("config init failed: %v\nOutput: %s", err, out)+ }++ setCmd := exec.Command(server.BinaryPath, "config", "set", "server.port", "7654")+ setCmd.Env = append(filterTestEnv(), "PINCHTAB_CONFIG="+configPath)+ if out, err := setCmd.CombinedOutput(); err != nil {+ t.Fatalf("config set failed: %v\nOutput: %s", err, out)+ }++ // Get the value back.+ getCmd := exec.Command(server.BinaryPath, "config", "get", "server.port")+ getCmd.Env = append(filterTestEnv(), "PINCHTAB_CONFIG="+configPath)++ out, err := getCmd.CombinedOutput()+ if err != nil {+ t.Fatalf("config get failed: %v\nOutput: %s", err, out)+ }++ got := strings.TrimSpace(string(out))+ if got != "7654" {+ t.Errorf("config get server.port = %q, want %q", got, "7654")+ }+}++// TestConfigCLI_Get_UnknownPath tests that `pinchtab config get` exits non-zero for unknown paths.+func TestConfigCLI_Get_UnknownPath(t *testing.T) {+ tmpDir := t.TempDir()+ configPath := filepath.Join(tmpDir, "config.json")++ cmd := exec.Command(server.BinaryPath, "config", "get", "unknown.field")+ cmd.Env = append(filterTestEnv(), "PINCHTAB_CONFIG="+configPath)++ out, err := cmd.CombinedOutput()+ if err == nil {+ t.Fatalf("config get unknown.field should have failed; got: %s", out)+ }+}++// TestConfigCLI_Get_SliceField tests that slice fields (e.g., attach.allowHosts)+// are returned as comma-separated values.+func TestConfigCLI_Get_SliceField(t *testing.T) {+ tmpDir := t.TempDir()+ configPath := filepath.Join(tmpDir, "config.json")++ initCmd := exec.Command(server.BinaryPath, "config", "init")+ initCmd.Env = append(filterTestEnv(), "PINCHTAB_CONFIG="+configPath, "HOME="+tmpDir)+ if out, err := initCmd.CombinedOutput(); err != nil {+ t.Fatalf("config init failed: %v\nOutput: %s", err, out)+ }++ setCmd := exec.Command(server.BinaryPath, "config", "set", "attach.allowHosts", "127.0.0.1,localhost")+ setCmd.Env = append(filterTestEnv(), "PINCHTAB_CONFIG="+configPath)+ if out, err := setCmd.CombinedOutput(); err != nil {+ t.Fatalf("config set failed: %v\nOutput: %s", err, out)+ }++ getCmd := exec.Command(server.BinaryPath, "config", "get", "attach.allowHosts")+ getCmd.Env = append(filterTestEnv(), "PINCHTAB_CONFIG="+configPath)++ out, err := getCmd.CombinedOutput()+ if err != nil {+ t.Fatalf("config get attach.allowHosts failed: %v\nOutput: %s", err, out)+ }++ got := strings.TrimSpace(string(out))+ if got != "127.0.0.1,localhost" {+ t.Errorf("config get attach.allowHosts = %q, want %q", got, "127.0.0.1,localhost")+ }+}