Skip to content

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

feat: cli refactoring

Luigi Agosti5e3bea605361
diff --git a/README.md b/README.md
index 0a67c452..6bb7ebd3 100644
--- a/README.md
+++ b/README.md
@@ -113,9 +113,17 @@ docker run -d \
**Terminal 1 — Start the server:**
```bash
-pinchtab
+pinchtab server
```
+**Recommended for daily local use — install the daemon once:**
+```bash
+pinchtab daemon install
+pinchtab daemon
+```
+
+That keeps PinchTab running in the background so your agent tools can reuse it without an open terminal.
+
**Terminal 2 — Control the browser:**
```bash
# Navigate
diff --git a/cmd/pinchtab/cmd_bridge.go b/cmd/pinchtab/cmd_bridge.go
index 28c22e56..482ccba9 100644
--- a/cmd/pinchtab/cmd_bridge.go
+++ b/cmd/pinchtab/cmd_bridge.go
@@ -1,86 +1,21 @@
package main
import (
- "context"
- "log/slog"
- "net/http"
- "os"
- "os/signal"
- "sync"
- "syscall"
- "time"
-
- "github.com/pinchtab/pinchtab/internal/assets"
- "github.com/pinchtab/pinchtab/internal/bridge"
"github.com/pinchtab/pinchtab/internal/config"
- "github.com/pinchtab/pinchtab/internal/engine"
- "github.com/pinchtab/pinchtab/internal/handlers"
+ "github.com/pinchtab/pinchtab/internal/server"
+ "github.com/spf13/cobra"
)
-// runBridgeServer starts a bridge without orchestrator or dashboard
-// This is used for spawned instances by the orchestrator
-func runBridgeServer(cfg *config.RuntimeConfig) {
- listenAddr := cfg.ListenAddr()
- printStartupBanner(cfg, startupBannerOptions{
- Mode: "bridge",
- ListenAddr: listenAddr,
- ProfileDir: cfg.ProfileDir,
- })
-
- // Create a bridge instance with lazy initialization
- // Chrome will be initialized on first request via ensureChrome()
- bridgeInstance := bridge.New(context.Background(), nil, cfg)
- bridgeInstance.StealthScript = assets.StealthScript
-
- mux := http.NewServeMux()
-
- // Register all bridge handlers
- h := handlers.New(bridgeInstance, cfg, nil, nil, nil)
-
- // Wire engine router if mode is "lite" or "auto".
- 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())
- }
-
- shutdownOnce := &sync.Once{}
- doShutdown := func() {
- shutdownOnce.Do(func() {
- slog.Info("shutting down bridge...")
- })
- }
- h.RegisterRoutes(mux, doShutdown)
- logSecurityWarnings(cfg)
-
- // HTTP server
- server := &http.Server{
- Addr: listenAddr,
- Handler: handlers.RequestIDMiddleware(handlers.LoggingMiddleware(handlers.AuthMiddleware(cfg, mux))),
- ReadHeaderTimeout: 10 * time.Second,
- ReadTimeout: 30 * time.Second,
- WriteTimeout: 60 * time.Second,
- IdleTimeout: 120 * time.Second,
- }
-
- go func() {
- if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
- slog.Error("server error", "err", err)
- os.Exit(1)
- }
- }()
-
- // Graceful shutdown on signal
- sigChan := make(chan os.Signal, 1)
- signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
- <-sigChan
-
- doShutdown()
+var bridgeCmd = &cobra.Command{
+ Use: "bridge",
+ Short: "Start single-instance bridge-only server",
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := config.Load()
+ server.RunBridgeServer(cfg)
+ },
+}
- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
- defer cancel()
- if err := server.Shutdown(ctx); err != nil {
- slog.Error("shutdown error", "err", err)
- }
+func init() {
+ bridgeCmd.GroupID = "primary"
+ rootCmd.AddCommand(bridgeCmd)
}
diff --git a/cmd/pinchtab/cmd_cli.go b/cmd/pinchtab/cmd_cli.go
index 4bd91329..df0146c3 100644
--- a/cmd/pinchtab/cmd_cli.go
+++ b/cmd/pinchtab/cmd_cli.go
@@ -3,23 +3,21 @@ package main
import (
"fmt"
"net/http"
- "os"
- "strings"
"time"
- "github.com/pinchtab/pinchtab/internal/browsercli"
+ browseractions "github.com/pinchtab/pinchtab/internal/cli/actions"
"github.com/pinchtab/pinchtab/internal/config"
"github.com/spf13/cobra"
)
var quickCmd = &cobra.Command{
Use: "quick <url>",
- Short: "Navigate + analyze page (beginner-friendly)",
+ Short: "Navigate + analyze page",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- browsercli.Quick(client, base, token, args)
+ browseractions.Quick(client, base, token, args)
})
},
}
@@ -31,7 +29,7 @@ var navCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- browsercli.Navigate(client, base, token, args)
+ browseractions.Navigate(client, base, token, args)
})
},
}
@@ -42,7 +40,7 @@ var snapCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- browsercli.Snapshot(client, base, token, args)
+ browseractions.Snapshot(client, base, token, args)
})
},
}
@@ -54,7 +52,7 @@ var clickCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- browsercli.Action(client, base, token, "click", args)
+ browseractions.Action(client, base, token, "click", args)
})
},
}
@@ -66,7 +64,7 @@ var typeCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- browsercli.Action(client, base, token, "type", args)
+ browseractions.Action(client, base, token, "type", args)
})
},
}
@@ -77,7 +75,7 @@ var screenshotCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- browsercli.Screenshot(client, base, token, args)
+ browseractions.Screenshot(client, base, token, args)
})
},
}
@@ -88,7 +86,7 @@ var tabsCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- browsercli.Tabs(client, base, token, args)
+ browseractions.Tabs(client, base, token, args)
})
},
}
@@ -99,7 +97,7 @@ var instancesCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- browsercli.Instances(client, base, token)
+ browseractions.Instances(client, base, token)
})
},
}
@@ -110,7 +108,7 @@ var healthCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- browsercli.Health(client, base, token)
+ browseractions.Health(client, base, token)
})
},
}
@@ -122,7 +120,7 @@ var pressCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- browsercli.Action(client, base, token, "press", args)
+ browseractions.Action(client, base, token, "press", args)
})
},
}
@@ -134,7 +132,7 @@ var fillCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- browsercli.Action(client, base, token, "fill", args)
+ browseractions.Action(client, base, token, "fill", args)
})
},
}
@@ -146,7 +144,7 @@ var hoverCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- browsercli.Action(client, base, token, "hover", args)
+ browseractions.Action(client, base, token, "hover", args)
})
},
}
@@ -158,7 +156,7 @@ var scrollCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- browsercli.Action(client, base, token, "scroll", args)
+ browseractions.Action(client, base, token, "scroll", args)
})
},
}
@@ -170,7 +168,7 @@ var evalCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- browsercli.Evaluate(client, base, token, args)
+ browseractions.Evaluate(client, base, token, args)
})
},
}
@@ -181,7 +179,7 @@ var pdfCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- browsercli.PDF(client, base, token, args)
+ browseractions.PDF(client, base, token, args)
})
},
}
@@ -192,7 +190,7 @@ var textCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- browsercli.Text(client, base, token, args)
+ browseractions.Text(client, base, token, args)
})
},
}
@@ -203,7 +201,7 @@ var profilesCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- browsercli.Profiles(client, base, token)
+ browseractions.Profiles(client, base, token)
})
},
}
@@ -214,6 +212,24 @@ var instanceCmd = &cobra.Command{
}
func init() {
+ quickCmd.GroupID = "browser"
+ navCmd.GroupID = "browser"
+ snapCmd.GroupID = "browser"
+ clickCmd.GroupID = "browser"
+ typeCmd.GroupID = "browser"
+ screenshotCmd.GroupID = "browser"
+ tabsCmd.GroupID = "browser"
+ instancesCmd.GroupID = "management"
+ healthCmd.GroupID = "management"
+ pressCmd.GroupID = "browser"
+ fillCmd.GroupID = "browser"
+ hoverCmd.GroupID = "browser"
+ scrollCmd.GroupID = "browser"
+ evalCmd.GroupID = "browser"
+ pdfCmd.GroupID = "browser"
+ textCmd.GroupID = "browser"
+ profilesCmd.GroupID = "management"
+
rootCmd.AddCommand(quickCmd)
rootCmd.AddCommand(navCmd)
rootCmd.AddCommand(snapCmd)
@@ -232,6 +248,7 @@ func init() {
rootCmd.AddCommand(textCmd)
rootCmd.AddCommand(profilesCmd)
+ instanceCmd.GroupID = "management"
instanceCmd.AddCommand(&cobra.Command{
Use: "start <name>",
Short: "Start a browser instance",
@@ -239,7 +256,7 @@ func init() {
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- browsercli.InstanceStart(client, base, token, args)
+ browseractions.InstanceStart(client, base, token, args)
})
},
})
@@ -250,7 +267,7 @@ func init() {
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- browsercli.InstanceNavigate(client, base, token, args)
+ browseractions.InstanceNavigate(client, base, token, args)
})
},
})
@@ -261,7 +278,7 @@ func init() {
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- browsercli.InstanceStop(client, base, token, args)
+ browseractions.InstanceStop(client, base, token, args)
})
},
})
@@ -272,7 +289,7 @@ func init() {
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- browsercli.InstanceLogs(client, base, token, args)
+ browseractions.InstanceLogs(client, base, token, args)
})
},
})
@@ -290,159 +307,3 @@ func runCLIWith(cfg *config.RuntimeConfig, fn func(client *http.Client, base, to
fn(client, base, token)
}
-
-func printHelp() {
- renderCLIHelp()
-}
-
-var cliCommands = map[string]bool{
- "nav": true, "navigate": true,
- "snap": true, "snapshot": true,
- "click": true, "type": true, "press": true, "fill": true,
- "hover": true, "scroll": true, "select": true, "focus": true,
- "text": true, "tabs": true, "tab": true,
- "screenshot": true, "ss": true,
- "eval": true, "evaluate": true,
- "pdf": true, "health": true,
- "help": true, "quick": true,
- "instance": true, "instances": true,
- "profiles": true,
-}
-
-func isCLICommand(cmd string) bool {
- return cliCommands[cmd]
-}
-
-func runCLI(cfg *config.RuntimeConfig) {
- cmd := os.Args[1]
- rawArgs := os.Args[2:]
-
- 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++
- } else {
- args = append(args, rawArgs[i])
- }
- }
-
- orchBase := fmt.Sprintf("http://%s:%s", cfg.Bind, cfg.Port)
- if envURL := os.Getenv("PINCHTAB_URL"); envURL != "" {
- orchBase = strings.TrimRight(envURL, "/")
- }
-
- token := cfg.Token
- if envToken := os.Getenv("PINCHTAB_TOKEN"); envToken != "" {
- token = envToken
- }
-
- base := orchBase
- if instanceID != "" {
- base = browsercli.ResolveInstanceBase(orchBase, token, instanceID, cfg.Bind)
- }
-
- client := &http.Client{Timeout: 30 * time.Second}
-
- if cmd != "help" {
- if !browsercli.CheckServerAndGuide(client, base, token) {
- return
- }
- }
-
- switch cmd {
- case "nav", "navigate":
- browsercli.Navigate(client, base, token, args)
- case "snap", "snapshot":
- browsercli.Snapshot(client, base, token, args)
- case "click", "type", "press", "fill", "hover", "scroll", "select", "focus":
- browsercli.Action(client, base, token, cmd, args)
- case "text":
- browsercli.Text(client, base, token, args)
- case "tabs", "tab":
- browsercli.Tabs(client, base, token, args)
- case "screenshot", "ss":
- browsercli.Screenshot(client, base, token, args)
- case "eval", "evaluate":
- browsercli.Evaluate(client, base, token, args)
- case "pdf":
- browsercli.PDF(client, base, token, args)
- case "health":
- browsercli.Health(client, base, token)
- case "instance":
- browsercli.Instance(client, base, token, args)
- case "instances":
- browsercli.Instances(client, base, token)
- case "profiles":
- browsercli.Profiles(client, base, token)
- case "quick":
- browsercli.Quick(client, base, token, args)
- case "help":
- cliHelp()
- }
-}
-
-func cliHelp() {
- renderCLIHelp()
- os.Exit(0)
-}
-
-func renderCLIHelp() {
- fmt.Print(`Pinchtab CLI - browser control from the command line
-
-Usage: pinchtab <command> [args] [flags]
-
-QUICK START:
- pinchtab quick <url> Navigate and show page structure (combines nav + snap)
-
-WORKFLOW:
- 1. Start server: pinchtab (or: pinchtab server)
- 2. Navigate: pinchtab nav https://pinchtab.com
- 3. See page: pinchtab snap (shows clickable refs)
- 4. Interact: pinchtab click e5 (click element)
- 5. Check result: pinchtab snap (see changes)
-
-Commands:
- quick <url> Navigate and analyze page (beginner-friendly)
-
- INSTANCE MANAGEMENT:
- instance launch Create new instance (--mode headed, --port 9999)
- instance logs <id> Get instance logs (for debugging)
- instance stop <id> Stop instance
- instances List all running instances
-
- BROWSER CONTROL:
- nav, navigate <url> Navigate to URL (--new-tab, --block-images, --block-ads)
- snap, snapshot Accessibility tree snapshot (-i, -c, -d, --max-tokens N)
- click <ref> Click element by ref
- type <ref> <text> Type text into element
- fill <ref> <text> Set input value (no key events)
- press <key> Press a key (Enter, Tab, Escape, ...)
- hover <ref> Hover over element
- scroll <direction> Scroll page (up, down, left, right)
- select <ref> <value> Select dropdown option
- focus <ref> Focus element
- text Extract page text (--raw for innerText)
- tabs List open tabs
- tabs new <url> Open new tab
- tabs close <tabId> Close tab
- ss, screenshot Take screenshot (-o file, -q quality)
- eval <expression> Evaluate JavaScript
- pdf Export page as PDF (-o file, --landscape, --scale N)
-
- OTHER:
- health Server health check
- help Show this help
-
-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")'
-`)
-}
diff --git a/cmd/pinchtab/cmd_cli_test.go b/cmd/pinchtab/cmd_cli_test.go
deleted file mode 100644
index 1a23b172..00000000
--- a/cmd/pinchtab/cmd_cli_test.go
+++ /dev/null
@@ -1,754 +0,0 @@
-package main
-
-import (
- "encoding/json"
- "io"
- "net/http"
- "net/http/httptest"
- "os"
- "strings"
- "testing"
-
- "github.com/pinchtab/pinchtab/internal/browsercli"
-)
-
-// mockServer records the last request and returns a configurable response.
-type mockServer struct {
- server *httptest.Server
- lastMethod string
- lastPath string
- lastQuery string
- lastBody string
- lastHeaders http.Header
- response string
- statusCode int
-}
-
-func newMockServer() *mockServer {
- m := &mockServer{statusCode: 200, response: `{"status":"ok"}`}
- m.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- m.lastMethod = r.Method
- m.lastPath = r.URL.Path
- m.lastQuery = r.URL.RawQuery
- m.lastHeaders = r.Header
- if r.Body != nil {
- body, _ := io.ReadAll(r.Body)
- m.lastBody = string(body)
- }
- w.WriteHeader(m.statusCode)
- _, _ = w.Write([]byte(m.response))
- }))
- return m
-}
-
-func (m *mockServer) close() { m.server.Close() }
-func (m *mockServer) base() string { return m.server.URL }
-
-// --- navigate tests ---
-
-func TestCLINavigate(t *testing.T) {
- m := newMockServer()
- defer m.close()
- client := m.server.Client()
-
- browsercli.Navigate(client, m.base(), "", []string{"https://pinchtab.com"})
- if m.lastMethod != "POST" {
- t.Errorf("expected POST, got %s", m.lastMethod)
- }
- if m.lastPath != "/navigate" {
- t.Errorf("expected /navigate, got %s", m.lastPath)
- }
- var body map[string]any
- _ = json.Unmarshal([]byte(m.lastBody), &body)
- if body["url"] != "https://pinchtab.com" {
- t.Errorf("expected url=https://pinchtab.com, got %v", body["url"])
- }
-}
-
-func TestCLINavigateWithFlags(t *testing.T) {
- m := newMockServer()
- defer m.close()
- client := m.server.Client()
-
- browsercli.Navigate(client, m.base(), "", []string{"https://pinchtab.com", "--new-tab", "--block-images"})
- var body map[string]any
- _ = json.Unmarshal([]byte(m.lastBody), &body)
- if body["newTab"] != true {
- t.Error("expected newTab=true")
- }
- if body["blockImages"] != true {
- t.Error("expected blockImages=true")
- }
-}
-
-func TestCLINavigateWithBlockAds(t *testing.T) {
- m := newMockServer()
- defer m.close()
- client := m.server.Client()
-
- browsercli.Navigate(client, m.base(), "", []string{"https://pinchtab.com", "--block-ads"})
- var body map[string]any
- _ = json.Unmarshal([]byte(m.lastBody), &body)
- if body["blockAds"] != true {
- t.Error("expected blockAds=true")
- }
-}
-
-func TestCLIInstanceNavigateUsesTabRoute(t *testing.T) {
- m := newMockServer()
- m.response = `{"tabId":"tab-abc"}`
- defer m.close()
- client := m.server.Client()
-
- browsercli.InstanceNavigate(client, m.base(), "", []string{"inst-123", "https://pinchtab.com"})
-
- if m.lastMethod != "POST" {
- t.Errorf("expected POST, got %s", m.lastMethod)
- }
- if m.lastPath != "/tabs/tab-abc/navigate" {
- t.Errorf("expected tab-scoped navigate path, got %s", m.lastPath)
- }
-
- var body map[string]any
- _ = json.Unmarshal([]byte(m.lastBody), &body)
- if body["url"] != "https://pinchtab.com" {
- t.Errorf("expected navigate URL in body, got %v", body["url"])
- }
-}
-
-// --- snapshot tests ---
-
-func TestCLISnapshot(t *testing.T) {
- m := newMockServer()
- m.response = `[{"ref":"e0","role":"button","name":"Submit"}]`
- defer m.close()
- client := m.server.Client()
-
- browsercli.Snapshot(client, m.base(), "", []string{"-i", "-c"})
- if m.lastMethod != "GET" {
- t.Errorf("expected GET, got %s", m.lastMethod)
- }
- if m.lastPath != "/snapshot" {
- t.Errorf("expected /snapshot, got %s", m.lastPath)
- }
- if !strings.Contains(m.lastQuery, "filter=interactive") {
- t.Errorf("expected filter=interactive in query, got %s", m.lastQuery)
- }
- if !strings.Contains(m.lastQuery, "format=compact") {
- t.Errorf("expected format=compact in query, got %s", m.lastQuery)
- }
-}
-
-func TestCLISnapshotDiff(t *testing.T) {
- m := newMockServer()
- defer m.close()
- client := m.server.Client()
-
- browsercli.Snapshot(client, m.base(), "", []string{"--diff", "--selector", "main", "--max-tokens", "2000", "--depth", "5"})
- if !strings.Contains(m.lastQuery, "diff=true") {
- t.Errorf("expected diff=true, got %s", m.lastQuery)
- }
- if !strings.Contains(m.lastQuery, "selector=main") {
- t.Errorf("expected selector=main, got %s", m.lastQuery)
- }
- if !strings.Contains(m.lastQuery, "maxTokens=2000") {
- t.Errorf("expected maxTokens=2000, got %s", m.lastQuery)
- }
- if !strings.Contains(m.lastQuery, "depth=5") {
- t.Errorf("expected depth=5, got %s", m.lastQuery)
- }
-}
-
-func TestCLISnapshotTabId(t *testing.T) {
- m := newMockServer()
- defer m.close()
- client := m.server.Client()
-
- browsercli.Snapshot(client, m.base(), "", []string{"--tab", "ABC123"})
- if !strings.Contains(m.lastQuery, "tabId=ABC123") {
- t.Errorf("expected tabId=ABC123, got %s", m.lastQuery)
- }
-}
-
-// --- action tests ---
-
-func TestCLIClick(t *testing.T) {
- m := newMockServer()
- defer m.close()
- client := m.server.Client()
-
- browsercli.Action(client, m.base(), "", "click", []string{"e5"})
- if m.lastPath != "/action" {
- t.Errorf("expected /action, got %s", m.lastPath)
- }
- var body map[string]any
- _ = json.Unmarshal([]byte(m.lastBody), &body)
- if body["kind"] != "click" {
- t.Errorf("expected kind=click, got %v", body["kind"])
- }
- if body["ref"] != "e5" {
- t.Errorf("expected ref=e5, got %v", body["ref"])
- }
-}
-
-func TestCLIClickWaitNav(t *testing.T) {
- m := newMockServer()
- defer m.close()
- client := m.server.Client()
-
- browsercli.Action(client, m.base(), "", "click", []string{"e5", "--wait-nav"})
- var body map[string]any
- _ = json.Unmarshal([]byte(m.lastBody), &body)
- if body["waitNav"] != true {
- t.Error("expected waitNav=true")
- }
-}
-
-func TestCLIType(t *testing.T) {
- m := newMockServer()
- defer m.close()
- client := m.server.Client()
-
- browsercli.Action(client, m.base(), "", "type", []string{"e12", "hello", "world"})
- var body map[string]any
- _ = json.Unmarshal([]byte(m.lastBody), &body)
- if body["kind"] != "type" {
- t.Errorf("expected kind=type, got %v", body["kind"])
- }
- if body["ref"] != "e12" {
- t.Errorf("expected ref=e12, got %v", body["ref"])
- }
- if body["text"] != "hello world" {
- t.Errorf("expected text='hello world', got %v", body["text"])
- }
-}
-
-func TestCLIPress(t *testing.T) {
- m := newMockServer()
- defer m.close()
- client := m.server.Client()
-
- browsercli.Action(client, m.base(), "", "press", []string{"Enter"})
- var body map[string]any
- _ = json.Unmarshal([]byte(m.lastBody), &body)
- if body["key"] != "Enter" {
- t.Errorf("expected key=Enter, got %v", body["key"])
- }
-}
-
-// TestCLIClickWithCSS verifies that --css <selector> is forwarded as the
-// "selector" field (not "ref") so that the bridge performs a CSS-based click.
-func TestCLIClickWithCSS(t *testing.T) {
- m := newMockServer()
- defer m.close()
- client := m.server.Client()
-
- browsercli.Action(client, m.base(), "", "click", []string{"--css", "button.submit"})
- var body map[string]any
- _ = json.Unmarshal([]byte(m.lastBody), &body)
- if body["selector"] != "button.submit" {
- t.Errorf("expected selector=button.submit, got %v", body["selector"])
- }
- if _, hasRef := body["ref"]; hasRef {
- t.Error("should not set ref when --css is provided")
- }
-}
-
-// TestCLIClickWithCSS_AndWaitNav verifies that --css and --wait-nav can be
-// combined in any order.
-func TestCLIClickWithCSS_AndWaitNav(t *testing.T) {
- m := newMockServer()
- defer m.close()
- client := m.server.Client()
-
- browsercli.Action(client, m.base(), "", "click", []string{"--wait-nav", "--css", "#login-btn"})
- var body map[string]any
- _ = json.Unmarshal([]byte(m.lastBody), &body)
- if body["selector"] != "#login-btn" {
- t.Errorf("expected selector=#login-btn, got %v", body["selector"])
- }
- if body["waitNav"] != true {
- t.Error("expected waitNav=true")
- }
-}
-
-// TestCLIHoverWithCSS verifies that hover accepts --css <selector>.
-func TestCLIHoverWithCSS(t *testing.T) {
- m := newMockServer()
- defer m.close()
- client := m.server.Client()
-
- browsercli.Action(client, m.base(), "", "hover", []string{"--css", ".nav-item"})
- var body map[string]any
- _ = json.Unmarshal([]byte(m.lastBody), &body)
- if body["selector"] != ".nav-item" {
- t.Errorf("expected selector=.nav-item, got %v", body["selector"])
- }
-}
-
-// TestCLIFocusWithCSS verifies that focus accepts --css <selector>.
-func TestCLIFocusWithCSS(t *testing.T) {
- m := newMockServer()
- defer m.close()
- client := m.server.Client()
-
- browsercli.Action(client, m.base(), "", "focus", []string{"--css", "input[name='email']"})
- var body map[string]any
- _ = json.Unmarshal([]byte(m.lastBody), &body)
- if body["selector"] != "input[name='email']" {
- t.Errorf("expected selector=input[name='email'], got %v", body["selector"])
- }
-}
-
-// TestCLIClickRefStillWorks verifies that positional <ref> args still work
-// when --css is not passed (backwards compatibility).
-func TestCLIClickRefStillWorks(t *testing.T) {
- m := newMockServer()
- defer m.close()
- client := m.server.Client()
-
- browsercli.Action(client, m.base(), "", "click", []string{"e42"})
- var body map[string]any
- _ = json.Unmarshal([]byte(m.lastBody), &body)
- if body["ref"] != "e42" {
- t.Errorf("expected ref=e42, got %v", body["ref"])
- }
- if _, hasSelector := body["selector"]; hasSelector {
- t.Error("should not set selector when using ref")
- }
-}
-
-func TestCLIFill(t *testing.T) {
- m := newMockServer()
- defer m.close()
- client := m.server.Client()
-
- // Fill with ref
- browsercli.Action(client, m.base(), "", "fill", []string{"e3", "test value"})
- var body map[string]any
- _ = json.Unmarshal([]byte(m.lastBody), &body)
- if body["ref"] != "e3" {
- t.Errorf("expected ref=e3, got %v", body["ref"])
- }
- if body["text"] != "test value" {
- t.Errorf("expected text='test value', got %v", body["text"])
- }
-
- // Fill with selector
- browsercli.Action(client, m.base(), "", "fill", []string{"#email", "[email protected]"})
- _ = json.Unmarshal([]byte(m.lastBody), &body)
- if body["selector"] != "#email" {
- t.Errorf("expected selector=#email, got %v", body["selector"])
- }
-}
-
-func TestCLIScroll(t *testing.T) {
- m := newMockServer()
- defer m.close()
- client := m.server.Client()
-
- // Scroll by ref
- browsercli.Action(client, m.base(), "", "scroll", []string{"e20"})
- var body map[string]any
- _ = json.Unmarshal([]byte(m.lastBody), &body)
- if body["ref"] != "e20" {
- t.Errorf("expected ref=e20, got %v", body["ref"])
- }
-
- // Scroll by pixels (now sends int, not string)
- browsercli.Action(client, m.base(), "", "scroll", []string{"800"})
- _ = json.Unmarshal([]byte(m.lastBody), &body)
- if body["scrollY"] != float64(800) { // JSON unmarshals numbers as float64
- t.Errorf("expected scrollY=800, got %v", body["scrollY"])
- }
-
- // Scroll by direction aliases.
- browsercli.Action(client, m.base(), "", "scroll", []string{"down"})
- _ = json.Unmarshal([]byte(m.lastBody), &body)
- if body["scrollY"] != float64(800) {
- t.Errorf("expected down to map to scrollY=800, got %v", body["scrollY"])
- }
-}
-
-func TestCLISelect(t *testing.T) {
- m := newMockServer()
- defer m.close()
- client := m.server.Client()
-
- browsercli.Action(client, m.base(), "", "select", []string{"e10", "option2"})
- var body map[string]any
- _ = json.Unmarshal([]byte(m.lastBody), &body)
- if body["ref"] != "e10" {
- t.Errorf("expected ref=e10, got %v", body["ref"])
- }
- if body["value"] != "option2" {
- t.Errorf("expected value=option2, got %v", body["value"])
- }
-}
-
-// --- text tests ---
-
-func TestCLIText(t *testing.T) {
- m := newMockServer()
- m.response = `{"url":"https://pinchtab.com","title":"Example","text":"Hello"}`
- defer m.close()
- client := m.server.Client()
-
- browsercli.Text(client, m.base(), "", nil)
- if m.lastPath != "/text" {
- t.Errorf("expected /text, got %s", m.lastPath)
- }
-}
-
-func TestCLITextRaw(t *testing.T) {
- m := newMockServer()
- defer m.close()
- client := m.server.Client()
-
- browsercli.Text(client, m.base(), "", []string{"--raw"})
- if !strings.Contains(m.lastQuery, "mode=raw") {
- t.Errorf("expected mode=raw, got %s", m.lastQuery)
- }
-}
-
-func TestCLITextTab(t *testing.T) {
- m := newMockServer()
- defer m.close()
- client := m.server.Client()
-
- browsercli.Text(client, m.base(), "", []string{"--tab", "TAB1"})
- if !strings.Contains(m.lastQuery, "tabId=TAB1") {
- t.Errorf("expected tabId=TAB1, got %s", m.lastQuery)
- }
-}
-
-// --- tabs tests ---
-
-func TestCLITabsList(t *testing.T) {
- m := newMockServer()
- m.response = `[{"id":"TAB1","url":"https://pinchtab.com"}]`
- defer m.close()
- client := m.server.Client()
-
- browsercli.Tabs(client, m.base(), "", nil)
- if m.lastPath != "/tabs" {
- t.Errorf("expected /tabs, got %s", m.lastPath)
- }
-}
-
-func TestCLITabsNew(t *testing.T) {
- m := newMockServer()
- defer m.close()
- client := m.server.Client()
-
- browsercli.Tabs(client, m.base(), "", []string{"new", "https://pinchtab.com"})
- if m.lastPath != "/tab" {
- t.Errorf("expected /tab, got %s", m.lastPath)
- }
- var body map[string]any
- _ = json.Unmarshal([]byte(m.lastBody), &body)
- if body["action"] != "new" {
- t.Errorf("expected action=new, got %v", body["action"])
- }
- if body["url"] != "https://pinchtab.com" {
- t.Errorf("expected url, got %v", body["url"])
- }
-}
-
-// --- evaluate tests ---
-
-func TestCLIEvaluate(t *testing.T) {
- m := newMockServer()
- m.response = `{"result":"Example Domain"}`
- defer m.close()
- client := m.server.Client()
-
- browsercli.Evaluate(client, m.base(), "", []string{"document.title"})
- if m.lastPath != "/evaluate" {
- t.Errorf("expected /evaluate, got %s", m.lastPath)
- }
- var body map[string]any
- _ = json.Unmarshal([]byte(m.lastBody), &body)
- if body["expression"] != "document.title" {
- t.Errorf("expected expression=document.title, got %v", body["expression"])
- }
-}
-
-func TestCLIEvaluateMultiWord(t *testing.T) {
- m := newMockServer()
- defer m.close()
- client := m.server.Client()
-
- browsercli.Evaluate(client, m.base(), "", []string{"1", "+", "2"})
- var body map[string]any
- _ = json.Unmarshal([]byte(m.lastBody), &body)
- if body["expression"] != "1 + 2" {
- t.Errorf("expected expression='1 + 2', got %v", body["expression"])
- }
-}
-
-// --- screenshot tests ---
-
-func TestCLIScreenshot(t *testing.T) {
- m := newMockServer()
- m.response = "FAKEJPEGDATA"
- defer m.close()
- client := m.server.Client()
-
- outFile := t.TempDir() + "/test.jpg"
- browsercli.Screenshot(client, m.base(), "", []string{"-o", outFile, "-q", "50"})
- if m.lastPath != "/screenshot" {
- t.Errorf("expected /screenshot, got %s", m.lastPath)
- }
- if !strings.Contains(m.lastQuery, "quality=50") {
- t.Errorf("expected quality=50, got %s", m.lastQuery)
- }
- data, err := os.ReadFile(outFile)
- if err != nil {
- t.Fatalf("file not written: %v", err)
- }
- if string(data) != "FAKEJPEGDATA" {
- t.Errorf("unexpected content: %s", string(data))
- }
-}
-
-// --- pdf tests ---
-
-func TestCLIPDF(t *testing.T) {
- m := newMockServer()
- m.response = "FAKEPDFDATA"
- defer m.close()
- client := m.server.Client()
-
- outFile := t.TempDir() + "/test.pdf"
- browsercli.PDF(client, m.base(), "", []string{"-o", outFile, "--tab", "tab-abc", "--landscape", "--scale", "0.8"})
- if m.lastPath != "/tabs/tab-abc/pdf" {
- t.Errorf("expected /tabs/tab-abc/pdf, got %s", m.lastPath)
- }
- if !strings.Contains(m.lastQuery, "landscape=true") {
- t.Errorf("expected landscape=true, got %s", m.lastQuery)
- }
- if !strings.Contains(m.lastQuery, "scale=0.8") {
- t.Errorf("expected scale=0.8, got %s", m.lastQuery)
- }
- data, err := os.ReadFile(outFile)
- if err != nil {
- t.Fatalf("file not written: %v", err)
- }
- if string(data) != "FAKEPDFDATA" {
- t.Errorf("unexpected content: %s", string(data))
- }
-}
-
-func TestCLIPDFAllOptions(t *testing.T) {
- m := newMockServer()
- m.response = "FAKEPDFDATA"
- defer m.close()
- client := m.server.Client()
-
- outFile := t.TempDir() + "/test.pdf"
- args := []string{
- "-o", outFile,
- "--landscape",
- "--scale", "1.5",
- "--paper-width", "11",
- "--paper-height", "8.5",
- "--margin-top", "1",
- "--margin-bottom", "1",
- "--margin-left", "0.5",
- "--margin-right", "0.5",
- "--page-ranges", "1-3,5",
- "--prefer-css-page-size",
- "--display-header-footer",
- "--header-template", "<span class='title'></span>",
- "--footer-template", "<span class='pageNumber'></span>",
- "--generate-tagged-pdf",
- "--generate-document-outline",
- "--tab", "tab-123",
- }
-
- browsercli.PDF(client, m.base(), "", args)
- if m.lastPath != "/tabs/tab-123/pdf" {
- t.Errorf("expected /tabs/tab-123/pdf, got %s", m.lastPath)
- }
-
- // Check all parameters were set correctly
- expectedParams := []string{
- "landscape=true",
- "scale=1.5",
- "paperWidth=11",
- "paperHeight=8.5",
- "marginTop=1",
- "marginBottom=1",
- "marginLeft=0.5",
- "marginRight=0.5",
- "pageRanges=1-3%2C5", // URL encoded
- "preferCSSPageSize=true",
- "displayHeaderFooter=true",
- "generateTaggedPDF=true",
- "generateDocumentOutline=true",
- "raw=true",
- }
-
- for _, expected := range expectedParams {
- if !strings.Contains(m.lastQuery, expected) {
- t.Errorf("expected %s in query, got %s", expected, m.lastQuery)
- }
- }
-
- // Check encoded HTML templates are present
- if !strings.Contains(m.lastQuery, "headerTemplate=") || !strings.Contains(m.lastQuery, "span") {
- t.Error("expected headerTemplate with HTML content")
- }
- if !strings.Contains(m.lastQuery, "footerTemplate=") || !strings.Contains(m.lastQuery, "pageNumber") {
- t.Error("expected footerTemplate with HTML content")
- }
-}
-
-// --- health tests ---
-
-func TestCLIHealth(t *testing.T) {
- m := newMockServer()
- m.response = `{"status":"ok","version":"dev"}`
- defer m.close()
- client := m.server.Client()
-
- browsercli.Health(client, m.base(), "")
- if m.lastPath != "/health" {
- t.Errorf("expected /health, got %s", m.lastPath)
- }
-}
-
-// --- auth header tests ---
-
-func TestCLIAuthHeader(t *testing.T) {
- m := newMockServer()
- defer m.close()
- client := m.server.Client()
-
- browsercli.Health(client, m.base(), "my-secret-token")
- auth := m.lastHeaders.Get("Authorization")
- if auth != "Bearer my-secret-token" {
- t.Errorf("expected 'Bearer my-secret-token', got %q", auth)
- }
-}
-
-func TestCLINoAuthHeader(t *testing.T) {
- m := newMockServer()
- defer m.close()
- client := m.server.Client()
-
- browsercli.Health(client, m.base(), "")
- auth := m.lastHeaders.Get("Authorization")
- if auth != "" {
- t.Errorf("expected no auth header, got %q", auth)
- }
-}
-
-// --- doGet/doPost helpers ---
-
-func TestDoGetPrettyPrintsJSON(t *testing.T) {
- m := newMockServer()
- m.response = `{"a":1,"b":2}`
- defer m.close()
- client := m.server.Client()
-
- // Just verify it doesn't panic with valid JSON
- browsercli.DoGet(client, m.base(), "", "/health", nil)
-}
-
-func TestDoGetNonJSON(t *testing.T) {
- m := newMockServer()
- m.response = "plain text response"
- defer m.close()
- client := m.server.Client()
-
- // Should handle non-JSON gracefully
- browsercli.DoGet(client, m.base(), "", "/text", nil)
-}
-
-func TestDoPostContentType(t *testing.T) {
- m := newMockServer()
- defer m.close()
- client := m.server.Client()
-
- _ = browsercli.DoPost(client, m.base(), "", "/action", map[string]any{"kind": "click"})
- ct := m.lastHeaders.Get("Content-Type")
- if ct != "application/json" {
- t.Errorf("expected application/json, got %q", ct)
- }
-}
-
-// --- server guidance tests ---
-
-func TestCheckServerAndGuide(t *testing.T) {
- // Test successful connection
- m := newMockServer()
- m.response = `{"status":"ok"}`
- defer m.close()
- client := m.server.Client()
-
- result := browsercli.CheckServerAndGuide(client, m.base(), "")
- if !result {
- t.Error("expected checkServerAndGuide to return true for working server")
- }
-
- // Test auth required (401)
- m2 := newMockServer()
- m2.statusCode = 401
- m2.response = `{"error":"unauthorized"}`
- defer m2.close()
- client2 := m2.server.Client()
-
- // Capture stderr
- oldStderr := os.Stderr
- r, w, _ := os.Pipe()
- os.Stderr = w
-
- result2 := browsercli.CheckServerAndGuide(client2, m2.base(), "")
-
- _ = w.Close()
- os.Stderr = oldStderr
- output, _ := io.ReadAll(r)
-
- if result2 {
- t.Error("expected checkServerAndGuide to return false for 401")
- }
- if !strings.Contains(string(output), "Authentication required") {
- 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 := browsercli.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()
-
- browsercli.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/cmd/pinchtab/cmd_config.go b/cmd/pinchtab/cmd_config.go
new file mode 100644
index 00000000..cda54d23
--- /dev/null
+++ b/cmd/pinchtab/cmd_config.go
@@ -0,0 +1,441 @@
+package main
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "strings"
+
+ "github.com/pinchtab/pinchtab/internal/cli"
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/server"
+ "github.com/spf13/cobra"
+)
+
+var clipboardExecCommand = exec.Command
+
+var configCmd = &cobra.Command{
+ Use: "config",
+ Short: "Manage configuration",
+ Run: func(cmd *cobra.Command, args []string) {
+ handleConfigOverview(loadConfig())
+ },
+}
+
+func init() {
+ configCmd.GroupID = "config"
+ configCmd.AddCommand(&cobra.Command{
+ Use: "show",
+ Short: "Display current configuration",
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := config.Load()
+ cli.HandleConfigShow(cfg)
+ },
+ })
+ configCmd.AddCommand(&cobra.Command{
+ Use: "init",
+ Short: "Initialize a new config file",
+ Run: func(cmd *cobra.Command, args []string) {
+ handleConfigInit()
+ },
+ })
+ configCmd.AddCommand(&cobra.Command{
+ Use: "path",
+ Short: "Show config file path",
+ Run: func(cmd *cobra.Command, args []string) {
+ handleConfigPath()
+ },
+ })
+ configCmd.AddCommand(&cobra.Command{
+ Use: "validate",
+ Short: "Validate config file",
+ Run: func(cmd *cobra.Command, args []string) {
+ handleConfigValidate()
+ },
+ })
+ configCmd.AddCommand(&cobra.Command{
+ Use: "get <path>",
+ Short: "Get a config value (e.g., server.port)",
+ Args: cobra.ExactArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ handleConfigGet(args[0])
+ },
+ })
+ configCmd.AddCommand(&cobra.Command{
+ Use: "set <path> <val>",
+ Short: "Set a config value (e.g., server.port 8080)",
+ Args: cobra.ExactArgs(2),
+ Run: func(cmd *cobra.Command, args []string) {
+ handleConfigSet(args[0], args[1])
+ },
+ })
+ configCmd.AddCommand(&cobra.Command{
+ Use: "patch <json>",
+ Short: "Merge JSON into config",
+ Args: cobra.ExactArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ handleConfigPatch(args[0])
+ },
+ })
+
+ rootCmd.AddCommand(configCmd)
+}
+
+func handleConfigOverview(cfg *config.RuntimeConfig) {
+ _, configPath, err := config.LoadFileConfig()
+ if err != nil {
+ fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, fmt.Sprintf("Error loading config path: %v", err)))
+ os.Exit(1)
+ }
+
+ dashPort := cfg.Port
+ if dashPort == "" {
+ dashPort = "9870"
+ }
+ dashboardURL := fmt.Sprintf("http://localhost:%s", dashPort)
+ running := server.CheckPinchTabRunning(dashPort, cfg.Token)
+
+ for {
+ fmt.Print(renderConfigOverview(cfg, configPath, dashboardURL, running))
+
+ if !isInteractiveTerminal() {
+ return
+ }
+
+ nextCfg, changed, done, err := promptConfigEdit(cfg)
+ if err != nil {
+ fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, err.Error()))
+ fmt.Println()
+ continue
+ }
+ if done {
+ return
+ }
+ if !changed {
+ fmt.Println()
+ continue
+ }
+
+ cfg = nextCfg
+ dashPort = cfg.Port
+ if dashPort == "" {
+ dashPort = "9870"
+ }
+ dashboardURL = fmt.Sprintf("http://localhost:%s", dashPort)
+ running = server.CheckPinchTabRunning(dashPort, cfg.Token)
+ fmt.Println()
+ }
+}
+
+func renderConfigOverview(cfg *config.RuntimeConfig, configPath, dashboardURL string, running bool) string {
+ out := ""
+ out += cli.StyleStdout(cli.HeadingStyle, "Config") + "\n\n"
+ out += fmt.Sprintf(" 1. %-18s %s\n", "Strategy", cli.StyleStdout(cli.ValueStyle, cfg.Strategy))
+ out += fmt.Sprintf(" 2. %-18s %s\n", "Allocation policy", cli.StyleStdout(cli.ValueStyle, cfg.AllocationPolicy))
+ out += fmt.Sprintf(" 3. %-18s %s\n", "Stealth level", cli.StyleStdout(cli.ValueStyle, cfg.StealthLevel))
+ out += fmt.Sprintf(" 4. %-18s %s\n", "Tab eviction", cli.StyleStdout(cli.ValueStyle, cfg.TabEvictionPolicy))
+ out += fmt.Sprintf(" 5. %-18s %s\n", "Copy token", cli.StyleStdout(cli.MutedStyle, "clipboard"))
+ out += "\n"
+ out += cli.StyleStdout(cli.HeadingStyle, "More") + "\n\n"
+ out += fmt.Sprintf(" %s %s\n", cli.StyleStdout(cli.MutedStyle, "File:"), cli.StyleStdout(cli.ValueStyle, configPath))
+ out += fmt.Sprintf(" %s %s\n", cli.StyleStdout(cli.MutedStyle, "Token:"), cli.StyleStdout(cli.ValueStyle, config.MaskToken(cfg.Token)))
+ if running {
+ out += fmt.Sprintf(" %s %s\n", cli.StyleStdout(cli.MutedStyle, "Dashboard:"), cli.StyleStdout(cli.ValueStyle, dashboardURL))
+ } else {
+ out += fmt.Sprintf(" %s %s\n", cli.StyleStdout(cli.MutedStyle, "Dashboard:"), cli.StyleStdout(cli.MutedStyle, "not running"))
+ }
+ if isInteractiveTerminal() {
+ out += "\n"
+ out += cli.StyleStdout(cli.MutedStyle, "Edit item (1-5, blank to exit):") + " "
+ }
+ out += "\n"
+ return out
+}
+
+func promptConfigEdit(cfg *config.RuntimeConfig) (*config.RuntimeConfig, bool, bool, error) {
+ choice, err := promptInput("", "")
+ if err != nil {
+ return nil, false, false, err
+ }
+ choice = strings.TrimSpace(choice)
+ if choice == "" {
+ return nil, false, true, nil
+ }
+
+ switch choice {
+ case "1":
+ nextCfg, changed, err := editConfigSelection("Instance strategy", "multiInstance.strategy", cfg.Strategy, config.ValidStrategies())
+ return nextCfg, changed, false, err
+ case "2":
+ nextCfg, changed, err := editConfigSelection("Allocation policy", "multiInstance.allocationPolicy", cfg.AllocationPolicy, config.ValidAllocationPolicies())
+ return nextCfg, changed, false, err
+ case "3":
+ nextCfg, changed, err := editConfigSelection("Default stealth level", "instanceDefaults.stealthLevel", cfg.StealthLevel, config.ValidStealthLevels())
+ return nextCfg, changed, false, err
+ case "4":
+ nextCfg, changed, err := editConfigSelection("Default tab eviction", "instanceDefaults.tabEvictionPolicy", cfg.TabEvictionPolicy, config.ValidEvictionPolicies())
+ return nextCfg, changed, false, err
+ case "5":
+ if err := copyConfigToken(cfg.Token); err != nil {
+ return nil, false, false, err
+ }
+ return nil, false, false, nil
+ default:
+ return nil, false, false, fmt.Errorf("invalid selection %q", choice)
+ }
+}
+
+func editConfigSelection(title, path, current string, values []string) (*config.RuntimeConfig, bool, error) {
+ options := make([]menuOption, 0, len(values)+1)
+ for _, value := range values {
+ label := value
+ if value == current {
+ label += " (current)"
+ }
+ options = append(options, menuOption{label: label, value: value})
+ }
+ options = append(options, menuOption{label: "Cancel", value: "cancel"})
+
+ picked, err := promptSelect(title, options)
+ if err != nil {
+ return nil, false, err
+ }
+ if picked == "" || picked == "cancel" {
+ return nil, false, nil
+ }
+
+ nextCfg, changed, err := updateConfigValue(path, picked)
+ if err != nil {
+ return nil, false, err
+ }
+ if changed {
+ fmt.Println(cli.StyleStdout(cli.SuccessStyle, fmt.Sprintf("Updated %s to %s", path, picked)))
+ fmt.Println(cli.StyleStdout(cli.MutedStyle, "Restart PinchTab to apply file-based changes."))
+ }
+ return nextCfg, changed, nil
+}
+
+func copyConfigToken(token string) error {
+ if strings.TrimSpace(token) == "" {
+ return fmt.Errorf("server token is empty")
+ }
+
+ if err := copyToClipboard(token); err == nil {
+ fmt.Println(cli.StyleStdout(cli.SuccessStyle, "Token copied to clipboard."))
+ return nil
+ }
+
+ fmt.Println(cli.StyleStdout(cli.WarningStyle, "Clipboard unavailable; copy the token manually:"))
+ fmt.Println(cli.StyleStdout(cli.ValueStyle, token))
+ return nil
+}
+
+func copyToClipboard(text string) error {
+ candidates := clipboardCommands()
+ var lastErr error
+
+ for _, candidate := range candidates {
+ if _, err := exec.LookPath(candidate.name); err != nil {
+ lastErr = err
+ continue
+ }
+ cmd := clipboardExecCommand(candidate.name, candidate.args...)
+ cmd.Stdin = strings.NewReader(text)
+ if output, err := cmd.CombinedOutput(); err != nil {
+ if len(strings.TrimSpace(string(output))) > 0 {
+ lastErr = fmt.Errorf("%s: %s", err, strings.TrimSpace(string(output)))
+ } else {
+ lastErr = err
+ }
+ continue
+ }
+ return nil
+ }
+
+ if lastErr == nil {
+ return fmt.Errorf("no clipboard command available")
+ }
+ return lastErr
+}
+
+type clipboardCommand struct {
+ name string
+ args []string
+}
+
+func clipboardCommands() []clipboardCommand {
+ switch runtime.GOOS {
+ case "darwin":
+ return []clipboardCommand{{name: "pbcopy"}}
+ case "windows":
+ return []clipboardCommand{{name: "clip"}}
+ default:
+ return []clipboardCommand{
+ {name: "wl-copy"},
+ {name: "xclip", args: []string{"-selection", "clipboard"}},
+ {name: "xsel", args: []string{"--clipboard", "--input"}},
+ }
+ }
+}
+
+func handleConfigInit() {
+ configPath := os.Getenv("PINCHTAB_CONFIG")
+ if configPath == "" {
+ configPath = config.DefaultConfigPath()
+ }
+
+ if _, err := os.Stat(configPath); err == nil {
+ fmt.Printf("Config file already exists at %s\n", configPath)
+ fmt.Print("Overwrite? (y/N): ")
+ var response string
+ _, _ = fmt.Scanln(&response)
+ if response != "y" && response != "Y" {
+ return
+ }
+ }
+
+ if err := os.MkdirAll(filepath.Dir(configPath), 0o755); err != nil {
+ fmt.Printf("Error creating directory: %v\n", err)
+ os.Exit(1)
+ }
+
+ fc := config.DefaultFileConfig()
+ token, err := config.GenerateAuthToken()
+ if err != nil {
+ fmt.Printf("Error generating auth token: %v\n", err)
+ os.Exit(1)
+ }
+ fc.Server.Token = token
+ data, _ := json.Marshal(fc)
+ var nested map[string]any
+ _ = json.Unmarshal(data, &nested)
+ pretty, _ := json.MarshalIndent(nested, "", " ")
+
+ if err := os.WriteFile(configPath, pretty, 0o644); err != nil {
+ fmt.Printf("Error writing config: %v\n", err)
+ os.Exit(1)
+ }
+
+ fmt.Printf("Config file created at %s\n", configPath)
+}
+
+func handleConfigPath() {
+ configPath := os.Getenv("PINCHTAB_CONFIG")
+ if configPath == "" {
+ configPath = config.DefaultConfigPath()
+ }
+ fmt.Println(configPath)
+}
+
+func handleConfigGet(path string) {
+ fc, _, err := config.LoadFileConfig()
+ if err != nil {
+ fmt.Printf("Error loading config: %v\n", err)
+ os.Exit(1)
+ }
+
+ value, err := config.GetConfigValue(fc, path)
+ if err != nil {
+ fmt.Printf("Error: %v\n", err)
+ os.Exit(1)
+ }
+
+ fmt.Println(value)
+}
+
+func handleConfigSet(path, value string) {
+ fc, configPath, err := config.LoadFileConfig()
+ if err != nil {
+ fmt.Printf("Error loading config: %v\n", err)
+ os.Exit(1)
+ }
+
+ if err := config.SetConfigValue(fc, path, value); err != nil {
+ fmt.Printf("Error: %v\n", err)
+ os.Exit(1)
+ }
+
+ if errs := config.ValidateFileConfig(fc); len(errs) > 0 {
+ fmt.Printf("Warning: new value causes validation error(s):\n")
+ for _, err := range errs {
+ fmt.Printf(" - %v\n", err)
+ }
+ fmt.Print("Save anyway? (y/N): ")
+ var response string
+ _, _ = fmt.Scanln(&response)
+ if response != "y" && response != "Y" {
+ return
+ }
+ }
+
+ if err := config.SaveFileConfig(fc, configPath); err != nil {
+ fmt.Printf("Error saving config: %v\n", err)
+ os.Exit(1)
+ }
+
+ fmt.Printf("Set %s = %s\n", path, value)
+}
+
+func handleConfigPatch(jsonPatch string) {
+ fc, configPath, err := config.LoadFileConfig()
+ if err != nil {
+ fmt.Printf("Error loading config: %v\n", err)
+ os.Exit(1)
+ }
+
+ if err := config.PatchConfigJSON(fc, jsonPatch); err != nil {
+ fmt.Printf("Error: %v\n", err)
+ os.Exit(1)
+ }
+
+ if errs := config.ValidateFileConfig(fc); len(errs) > 0 {
+ fmt.Printf("Warning: patch causes validation error(s):\n")
+ for _, err := range errs {
+ fmt.Printf(" - %v\n", err)
+ }
+ fmt.Print("Save anyway? (y/N): ")
+ var response string
+ _, _ = fmt.Scanln(&response)
+ if response != "y" && response != "Y" {
+ return
+ }
+ }
+
+ if err := config.SaveFileConfig(fc, configPath); err != nil {
+ fmt.Printf("Error saving config: %v\n", err)
+ os.Exit(1)
+ }
+
+ fmt.Println("Config patched successfully")
+}
+
+func handleConfigValidate() {
+ configPath := os.Getenv("PINCHTAB_CONFIG")
+ if configPath == "" {
+ configPath = config.DefaultConfigPath()
+ }
+ data, err := os.ReadFile(configPath)
+ if err != nil {
+ fmt.Printf("Error reading config file: %v\n", err)
+ os.Exit(1)
+ }
+
+ fc := &config.FileConfig{}
+ if err := json.Unmarshal(data, fc); err != nil {
+ fmt.Printf("Error parsing config: %v\n", err)
+ os.Exit(1)
+ }
+
+ if errs := config.ValidateFileConfig(fc); len(errs) > 0 {
+ fmt.Printf("Config file has %d error(s):\n", len(errs))
+ for _, err := range errs {
+ fmt.Printf(" - %v\n", err)
+ }
+ os.Exit(1)
+ }
+
+ fmt.Printf("Config file is valid: %s\n", configPath)
+}
diff --git a/cmd/pinchtab/cmd_config_test.go b/cmd/pinchtab/cmd_config_test.go
new file mode 100644
index 00000000..67e7ed01
--- /dev/null
+++ b/cmd/pinchtab/cmd_config_test.go
@@ -0,0 +1,50 @@
+package main
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func TestRenderConfigOverview(t *testing.T) {
+ cfg := &config.RuntimeConfig{
+ Port: "9867",
+ Strategy: "simple",
+ AllocationPolicy: "fcfs",
+ StealthLevel: "light",
+ TabEvictionPolicy: "close_lru",
+ Token: "very-long-token-secret",
+ }
+ output := renderConfigOverview(cfg, "/tmp/pinchtab/config.json", "http://localhost:9867", false)
+
+ required := []string{
+ "Config",
+ "Strategy",
+ "Allocation policy",
+ "Stealth level",
+ "Tab eviction",
+ "Copy token",
+ "More",
+ "/tmp/pinchtab/config.json",
+ "very...cret",
+ "Dashboard:",
+ }
+ for _, needle := range required {
+ if !strings.Contains(output, needle) {
+ t.Fatalf("expected config overview to contain %q\n%s", needle, output)
+ }
+ }
+}
+
+func TestClipboardCommands(t *testing.T) {
+ commands := clipboardCommands()
+ if len(commands) == 0 {
+ t.Fatal("expected clipboard commands")
+ }
+ for _, command := range commands {
+ if command.name == "" {
+ t.Fatalf("clipboard command missing name: %+v", command)
+ }
+ }
+}
diff --git a/cmd/pinchtab/cmd_connect.go b/cmd/pinchtab/cmd_connect.go
deleted file mode 100644
index 04d0e9b1..00000000
--- a/cmd/pinchtab/cmd_connect.go
+++ /dev/null
@@ -1,104 +0,0 @@
-package main
-
-import (
- "encoding/json"
- "fmt"
- "io"
- "net/http"
- "net/url"
- "os"
-
- "github.com/pinchtab/pinchtab/internal/config"
- "github.com/spf13/cobra"
-)
-
-type profileInstanceStatus struct {
- Name string `json:"name"`
- Running bool `json:"running"`
- Status string `json:"status"`
- Port string `json:"port"`
- ID string `json:"id"`
- Error string `json:"error"`
-}
-
-var connectCmd = &cobra.Command{
- Use: "connect <profile>",
- Short: "Get URL for a running profile",
- Args: cobra.ExactArgs(1),
- Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
- jsonOut, _ := cmd.Flags().GetBool("json")
- dashboardURL, _ := cmd.Flags().GetString("dashboard")
- handleConnectCommand(cfg, args[0], dashboardURL, jsonOut)
- },
-}
-
-func init() {
- connectCmd.Flags().Bool("json", false, "Output as JSON")
- connectCmd.Flags().String("dashboard", "", "Dashboard URL (e.g. http://localhost:9867)")
- rootCmd.AddCommand(connectCmd)
-}
-
-func handleConnectCommand(cfg *config.RuntimeConfig, profile, dashboardURL string, jsonOut bool) {
- if dashboardURL == "" {
- dashboardURL = os.Getenv("PINCHTAB_DASHBOARD_URL")
- }
- if dashboardURL == "" {
- dashPort := cfg.Port
- if dashPort == "" {
- dashPort = "9870"
- }
- dashboardURL = "http://localhost:" + dashPort
- }
-
- reqURL := stringsTrimRightSlash(dashboardURL) + "/profiles/" + url.PathEscape(profile) + "/instance"
- res, err := http.Get(reqURL)
- if err != nil {
- fmt.Fprintf(os.Stderr, "connect failed: %v\n", err)
- os.Exit(1)
- }
- defer func() { _ = res.Body.Close() }()
-
- if res.StatusCode != http.StatusOK {
- body, _ := io.ReadAll(io.LimitReader(res.Body, 8<<10))
- fmt.Fprintf(os.Stderr, "connect failed: dashboard returned %d: %s\n", res.StatusCode, string(body))
- os.Exit(1)
- }
-
- var st profileInstanceStatus
- if err := json.NewDecoder(res.Body).Decode(&st); err != nil {
- fmt.Fprintf(os.Stderr, "connect failed: invalid response: %v\n", err)
- os.Exit(1)
- }
- if !st.Running || st.Port == "" {
- errMsg := st.Error
- if errMsg == "" {
- errMsg = st.Status
- }
- fmt.Fprintf(os.Stderr, "profile %q not running (%s)\n", profile, errMsg)
- os.Exit(1)
- }
-
- instanceURL := "http://localhost:" + st.Port
- if jsonOut {
- enc := json.NewEncoder(os.Stdout)
- enc.SetIndent("", " ")
- _ = enc.Encode(map[string]string{
- "profile": st.Name,
- "id": st.ID,
- "status": st.Status,
- "port": st.Port,
- "url": instanceURL,
- })
- return
- }
-
- fmt.Println(instanceURL)
-}
-
-func stringsTrimRightSlash(s string) string {
- for len(s) > 0 && s[len(s)-1] == '/' {
- s = s[:len(s)-1]
- }
- return s
-}
diff --git a/cmd/pinchtab/cmd_mcp.go b/cmd/pinchtab/cmd_mcp.go
index 62c045d8..a6298000 100644
--- a/cmd/pinchtab/cmd_mcp.go
+++ b/cmd/pinchtab/cmd_mcp.go
@@ -6,8 +6,24 @@ import (
"github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/mcp"
+ "github.com/spf13/cobra"
)
+var mcpCmd = &cobra.Command{
+ Use: "mcp",
+ Short: "Start the MCP stdio server",
+ Long: "Start the Model Context Protocol stdio server and proxy browser actions to a running PinchTab instance.",
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := config.Load()
+ runMCP(cfg)
+ },
+}
+
+func init() {
+ mcpCmd.GroupID = "primary"
+ rootCmd.AddCommand(mcpCmd)
+}
+
func runMCP(cfg *config.RuntimeConfig) {
baseURL := os.Getenv("PINCHTAB_URL")
if baseURL == "" {
diff --git a/cmd/pinchtab/cmd_onboard.go b/cmd/pinchtab/cmd_onboard.go
index 353f4dd7..3db09352 100644
--- a/cmd/pinchtab/cmd_onboard.go
+++ b/cmd/pinchtab/cmd_onboard.go
@@ -1,7 +1,6 @@
package main
import (
- "bytes"
"errors"
"fmt"
"os"
@@ -11,9 +10,7 @@ import (
"runtime"
"strings"
- "github.com/charmbracelet/huh"
- "github.com/charmbracelet/lipgloss"
- "github.com/pinchtab/pinchtab/internal/cliui"
+ "github.com/pinchtab/pinchtab/internal/cli"
"github.com/pinchtab/pinchtab/internal/config"
"github.com/spf13/cobra"
)
@@ -23,18 +20,6 @@ const (
pinchtabLaunchdLabel = "com.pinchtab.pinchtab"
)
-var onboardCmd = &cobra.Command{
- Use: "onboard",
- Short: "Guided interactive setup (recommended first run)",
- Long: "Step-by-step setup to configure your profiles, security defaults, and background service.",
- Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
- force, _ := cmd.Flags().GetBool("force")
- installDaemonOpt, _ := cmd.Flags().GetBool("install-daemon")
- handleOnboardCommand(cfg, force, installDaemonOpt)
- },
-}
-
var daemonCmd = &cobra.Command{
Use: "daemon [action]",
Short: "Manage the background service",
@@ -50,57 +35,16 @@ var daemonCmd = &cobra.Command{
}
func init() {
- onboardCmd.Flags().Bool("install-daemon", false, "Install and start a user-level background service")
- onboardCmd.Flags().Bool("force", false, "Replace the existing config with fresh secure defaults")
- rootCmd.AddCommand(onboardCmd)
+ daemonCmd.GroupID = "primary"
rootCmd.AddCommand(daemonCmd)
}
-func handleOnboardCommand(_ *config.RuntimeConfig, force bool, installDaemonOpt bool) {
- configPath, effectiveCfg, configStatus, err := ensureOnboardConfig(force)
- if err != nil {
- fmt.Fprintf(os.Stderr, "onboard failed: %v\n", err)
- os.Exit(1)
- }
-
- if isInteractiveTerminal() {
- if err := runInteractiveOnboard(configPath, effectiveCfg, configStatus, installDaemonOpt); err != nil {
- fmt.Fprintf(os.Stderr, "onboard failed: %v\n", err)
- os.Exit(1)
- }
- return
- }
-
- if installDaemonOpt {
- if _, err := installDaemon(configPath); err != nil {
- fmt.Fprintf(os.Stderr, "daemon install failed: %v\n", err)
- os.Exit(1)
- }
- }
-
- fmt.Print(renderOnboardGuide(configPath, effectiveCfg, configStatus, installDaemonOpt))
-}
-
func handleDaemonCommand(_ *config.RuntimeConfig, subcommand string) {
if subcommand == "" || subcommand == "help" || subcommand == "--help" || subcommand == "-h" {
printDaemonStatusSummary()
if subcommand == "" && isInteractiveTerminal() {
- var picked string
- err := huh.NewSelect[string]().
- Title("Daemon Actions").
- Options(
- huh.NewOption("Start service", "start"),
- huh.NewOption("Stop service", "stop"),
- huh.NewOption("Restart service", "restart"),
- huh.NewOption("Install service", "install"),
- huh.NewOption("Uninstall service", "uninstall"),
- huh.NewOption("Exit", "exit"),
- ).
- Value(&picked).
- WithTheme(pinchtabOnboardTheme()).
- Run()
-
+ picked, err := promptSelect("Daemon Actions", daemonMenuOptions(cli.IsDaemonInstalled(), cli.IsDaemonRunning()))
if err != nil || picked == "exit" || picked == "" {
os.Exit(0)
}
@@ -116,7 +60,7 @@ func handleDaemonCommand(_ *config.RuntimeConfig, subcommand string) {
manager, err := currentDaemonManager()
if err != nil {
- fmt.Fprintln(os.Stderr, cliui.StyleStderr(cliui.ErrorStyle, err.Error()))
+ fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, err.Error()))
os.Exit(1)
}
@@ -124,17 +68,21 @@ func handleDaemonCommand(_ *config.RuntimeConfig, subcommand string) {
case "install":
configPath, _, _, err := ensureOnboardConfig(false)
if err != nil {
- fmt.Fprintln(os.Stderr, cliui.StyleStderr(cliui.ErrorStyle, fmt.Sprintf("daemon install failed: %v", err)))
+ fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, fmt.Sprintf("daemon install failed: %v", err)))
+ os.Exit(1)
+ }
+ if err := manager.Preflight(); err != nil {
+ fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, fmt.Sprintf("daemon install unavailable: %v", err)))
os.Exit(1)
}
message, err := manager.Install(managerEnvironment(manager).execPath, configPath)
if err != nil {
- fmt.Fprintln(os.Stderr, cliui.StyleStderr(cliui.ErrorStyle, fmt.Sprintf("daemon install failed: %v", err)))
+ fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, fmt.Sprintf("daemon install failed: %v", err)))
fmt.Println()
fmt.Println(manager.ManualInstructions())
os.Exit(1)
}
- fmt.Println(cliui.StyleStdout(cliui.SuccessStyle, " [ok] ") + message)
+ fmt.Println(cli.StyleStdout(cli.SuccessStyle, " [ok] ") + message)
printDaemonFollowUp()
case "start":
printDaemonManagerResult(manager.Start())
@@ -145,70 +93,94 @@ func handleDaemonCommand(_ *config.RuntimeConfig, subcommand string) {
case "uninstall":
message, err := manager.Uninstall()
if err != nil {
- fmt.Fprintln(os.Stderr, cliui.StyleStderr(cliui.ErrorStyle, err.Error()))
+ fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, err.Error()))
fmt.Println()
fmt.Println(manager.ManualInstructions())
os.Exit(1)
}
- fmt.Println(cliui.StyleStdout(cliui.SuccessStyle, " [ok] ") + message)
+ fmt.Println(cli.StyleStdout(cli.SuccessStyle, " [ok] ") + message)
default:
- fmt.Fprintln(os.Stderr, cliui.StyleStderr(cliui.ErrorStyle, fmt.Sprintf("unknown daemon command: %s", subcommand)))
+ fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, fmt.Sprintf("unknown daemon command: %s", subcommand)))
daemonUsage()
os.Exit(2)
}
}
func daemonUsage() {
- fmt.Println(cliui.StyleStdout(cliui.HeadingStyle, "Usage:") + " " + cliui.StyleStdout(cliui.CommandStyle, "pinchtab daemon <install|start|restart|stop|uninstall>"))
+ fmt.Println(cli.StyleStdout(cli.HeadingStyle, "Usage:") + " " + cli.StyleStdout(cli.CommandStyle, "pinchtab daemon <install|start|restart|stop|uninstall>"))
fmt.Println()
- fmt.Println(cliui.StyleStdout(cliui.MutedStyle, "Manage the PinchTab user-level background service."))
+ fmt.Println(cli.StyleStdout(cli.MutedStyle, "Manage the PinchTab user-level background service."))
fmt.Println()
}
+func daemonMenuOptions(installed, running bool) []menuOption {
+ options := make([]menuOption, 0, 4)
+ switch {
+ case !installed:
+ options = append(options, menuOption{label: "Install service", value: "install"})
+ case running:
+ options = append(options,
+ menuOption{label: "Stop service", value: "stop"},
+ menuOption{label: "Restart service", value: "restart"},
+ menuOption{label: "Uninstall service", value: "uninstall"},
+ )
+ default:
+ options = append(options,
+ menuOption{label: "Start service", value: "start"},
+ menuOption{label: "Uninstall service", value: "uninstall"},
+ )
+ }
+ options = append(options, menuOption{label: "Exit", value: "exit"})
+ return options
+}
+
func printDaemonStatusSummary() {
manager, err := currentDaemonManager()
if err != nil {
- fmt.Println(cliui.StyleStdout(cliui.ErrorStyle, " Error: ") + err.Error())
+ fmt.Println(cli.StyleStdout(cli.ErrorStyle, " Error: ") + err.Error())
return
}
- installed := IsDaemonInstalled()
- running := IsDaemonRunning()
+ installed := cli.IsDaemonInstalled()
+ running := cli.IsDaemonRunning()
- fmt.Println(cliui.StyleStdout(cliui.HeadingStyle, "Daemon status:"))
+ fmt.Println(cli.StyleStdout(cli.HeadingStyle, "Daemon status:"))
- status := cliui.StyleStdout(cliui.WarningStyle, "not installed")
+ status := cli.StyleStdout(cli.WarningStyle, "not installed")
if installed {
- status = cliui.StyleStdout(cliui.SuccessStyle, "installed")
+ status = cli.StyleStdout(cli.SuccessStyle, "installed")
}
- fmt.Printf(" %-12s %s\n", cliui.StyleStdout(cliui.MutedStyle, "Service:"), status)
+ fmt.Printf(" %-12s %s\n", cli.StyleStdout(cli.MutedStyle, "Service:"), status)
- state := cliui.StyleStdout(cliui.MutedStyle, "stopped")
+ state := cli.StyleStdout(cli.MutedStyle, "stopped")
if running {
- state = cliui.StyleStdout(cliui.SuccessStyle, "active (running)")
+ state = cli.StyleStdout(cli.SuccessStyle, "active (running)")
}
- fmt.Printf(" %-12s %s\n", cliui.StyleStdout(cliui.MutedStyle, "State:"), state)
+ fmt.Printf(" %-12s %s\n", cli.StyleStdout(cli.MutedStyle, "State:"), state)
if running {
pid, _ := manager.Pid()
if pid != "" {
- fmt.Printf(" %-12s %s\n", cliui.StyleStdout(cliui.MutedStyle, "PID:"), cliui.StyleStdout(cliui.ValueStyle, pid))
+ fmt.Printf(" %-12s %s\n", cli.StyleStdout(cli.MutedStyle, "PID:"), cli.StyleStdout(cli.ValueStyle, pid))
}
}
if installed {
- fmt.Printf(" %-12s %s\n", cliui.StyleStdout(cliui.MutedStyle, "Path:"), cliui.StyleStdout(cliui.ValueStyle, manager.ServicePath()))
+ fmt.Printf(" %-12s %s\n", cli.StyleStdout(cli.MutedStyle, "Path:"), cli.StyleStdout(cli.ValueStyle, manager.ServicePath()))
+ }
+ if err := manager.Preflight(); err != nil {
+ fmt.Printf(" %-12s %s\n", cli.StyleStdout(cli.MutedStyle, "Environment:"), cli.StyleStdout(cli.WarningStyle, err.Error()))
}
if installed {
logs, err := manager.Logs(5)
if err == nil && strings.TrimSpace(logs) != "" {
fmt.Println()
- fmt.Println(cliui.StyleStdout(cliui.HeadingStyle, "Recent logs:"))
+ fmt.Println(cli.StyleStdout(cli.HeadingStyle, "Recent logs:"))
lines := strings.Split(logs, "\n")
for _, line := range lines {
if strings.TrimSpace(line) != "" {
- fmt.Printf(" %s\n", cliui.StyleStdout(cliui.MutedStyle, line))
+ fmt.Printf(" %s\n", cli.StyleStdout(cli.MutedStyle, line))
}
}
}
@@ -218,11 +190,11 @@ func printDaemonStatusSummary() {
func printDaemonManagerResult(message string, err error) {
if err != nil {
- fmt.Fprintln(os.Stderr, cliui.StyleStderr(cliui.ErrorStyle, err.Error()))
+ fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, err.Error()))
os.Exit(1)
}
if strings.HasPrefix(message, "Installed") || strings.HasPrefix(message, "Pinchtab daemon") {
- fmt.Println(cliui.StyleStdout(cliui.SuccessStyle, " [ok] ") + message)
+ fmt.Println(cli.StyleStdout(cli.SuccessStyle, " [ok] ") + message)
} else {
// For status, it might be a block of text
fmt.Println(message)
@@ -236,7 +208,6 @@ func ensureOnboardConfig(force bool) (string, *config.RuntimeConfig, onboardConf
}
exists := fileExists(configPath)
- status := onboardConfigVerified
if !exists || force {
defaults := config.DefaultFileConfig()
token, err := config.GenerateAuthToken()
@@ -247,11 +218,21 @@ func ensureOnboardConfig(force bool) (string, *config.RuntimeConfig, onboardConf
if err := config.SaveFileConfig(&defaults, configPath); err != nil {
return "", nil, "", err
}
- if !exists {
- status = onboardConfigCreated
- } else {
+ status := onboardConfigCreated
+ if exists {
status = onboardConfigRecovered
}
+ return configPath, config.Load(), status, nil
+ }
+
+ // If file exists and not forced, check if it needs recovery to secure baseline
+ _, changed, err := cli.RestoreSecurityDefaults()
+ if err != nil {
+ return configPath, config.Load(), onboardConfigVerified, err
+ }
+ status := onboardConfigVerified
+ if changed {
+ status = onboardConfigRecovered
}
return configPath, config.Load(), status, nil
@@ -265,114 +246,6 @@ const (
onboardConfigVerified onboardConfigStatus = "verified"
)
-func runInteractiveOnboard(configPath string, cfg *config.RuntimeConfig, configStatus onboardConfigStatus, installDaemonOpt bool) error {
- totalSteps := 6
- if installDaemonOpt {
- totalSteps = 7
- }
-
- fmt.Print("\033[H\033[2J") // Clear screen
- fmt.Println(renderOnboardTitle())
- fmt.Println()
-
- // Step 1: Config
- fmt.Print(renderOnboardConfigStep(1, totalSteps, configPath, configStatus))
-
- // Step 2: API
- fmt.Print(renderOnboardAPIAccessStep(2, totalSteps, cfg))
-
- // Step 3: Capabilities
- fmt.Print(renderOnboardSensitiveStep(3, totalSteps, cfg))
-
- // Step 4: Attach
- fmt.Print(renderOnboardAttachStep(4, totalSteps, cfg))
-
- // Step 5: IDPI
- fmt.Print(renderOnboardIDPIStep(5, totalSteps, cfg))
-
- // Step 6: Daemon (optional)
- currentStep := 6
- daemonInstalled := false
- if installDaemonOpt {
- fmt.Print(cliui.StyleStdout(cliui.MutedStyle, " Installing background service..."))
- if _, err := installDaemon(configPath); err != nil {
- fmt.Printf("\r %s %v\n", cliui.StyleStdout(cliui.ErrorStyle, "!!"), err)
- } else {
- fmt.Print("\r")
- daemonInstalled = true
- fmt.Print(renderOnboardDaemonStep(6, totalSteps, true))
- }
- currentStep++
- }
-
- fmt.Print(renderOnboardNextStep(currentStep, totalSteps, daemonInstalled))
- fmt.Println()
-
- return nil
-}
-
-func installDaemon(configPath string) (string, error) {
- manager, err := currentDaemonManager()
- if err != nil {
- return "", err
- }
- return manager.Install(managerEnvironment(manager).execPath, configPath)
-}
-
-func renderOnboardGuide(configPath string, cfg *config.RuntimeConfig, configStatus onboardConfigStatus, installDaemonOpt bool) string {
- var out bytes.Buffer
- total := 6
- if installDaemonOpt {
- total = 7
- }
-
- out.WriteString(renderOnboardTitle() + "\n\n")
- out.WriteString(renderOnboardConfigStep(1, total, configPath, configStatus))
- out.WriteString(renderOnboardAPIAccessStep(2, total, cfg))
- out.WriteString(renderOnboardSensitiveStep(3, total, cfg))
- out.WriteString(renderOnboardAttachStep(4, total, cfg))
- out.WriteString(renderOnboardIDPIStep(5, total, cfg))
-
- daemonInstalled := false
- if installDaemonOpt {
- daemonInstalled = IsDaemonInstalled()
- out.WriteString(renderOnboardDaemonStep(6, total, daemonInstalled))
- out.WriteString(renderOnboardNextStep(7, total, daemonInstalled))
- } else {
- out.WriteString(renderOnboardNextStep(6, total, false))
- }
-
- return out.String()
-}
-
-func summarizeToken(token string) string {
- if len(token) <= 8 {
- return token
- }
- return token[:4] + "..." + token[len(token)-4:]
-}
-
-func formatStringSlice(ss []string) string {
- if len(ss) == 0 {
- return "(none)"
- }
- return strings.Join(ss, ", ")
-}
-
-func writeSecurityToggle(out *bytes.Buffer, key string, enabled bool, description string) {
- val := "false"
- if enabled {
- val = "true"
- }
- writeOnboardKV(out, key, val)
- writeOnboardNote(out, description)
-}
-
-type onboardOptions struct {
- installDaemon bool
- force bool
-}
-
type commandRunner interface {
CombinedOutput(name string, arg ...string) ([]byte, error)
}
@@ -392,6 +265,7 @@ type daemonEnvironment struct {
}
type daemonManager interface {
+ Preflight() error
Install(execPath, configPath string) (string, error)
ServicePath() string
Start() (string, error)
@@ -414,251 +288,13 @@ type launchdManager struct {
runner commandRunner
}
-func IsDaemonInstalled() bool {
- manager, err := currentDaemonManager()
- if err != nil {
- return false
- }
- _, err = os.Stat(manager.ServicePath())
- return err == nil
-}
-
-func IsDaemonRunning() bool {
- manager, err := currentDaemonManager()
- if err != nil {
- return false
- }
- status, err := manager.Status()
- if err != nil {
- return false
- }
- // Simple string checks for common "running" indicators
- return strings.Contains(status, "state = running") || // launchd
- strings.Contains(status, "Active: active (running)") // systemd
-}
-
-func pinchtabOnboardTheme() *huh.Theme {
- t := huh.ThemeBase()
-
- textPrimary := cliui.ColorTextPrimary
- textSecondary := lipgloss.Color("#94a3b8")
- textMuted := cliui.ColorTextMuted
- accent := cliui.ColorAccent
- accentLight := cliui.ColorAccentLight
- success := cliui.ColorSuccess
- warning := cliui.ColorWarning
- destructive := cliui.ColorDanger
-
- t.Form.Base = lipgloss.NewStyle().
- Foreground(textPrimary).
- Padding(0, 0)
-
- t.Group.Base = lipgloss.NewStyle().Foreground(textPrimary)
- t.Group.Title = lipgloss.NewStyle().
- Foreground(accent).
- Bold(true)
- t.Group.Description = lipgloss.NewStyle().
- Foreground(textMuted)
-
- t.FieldSeparator = lipgloss.NewStyle().SetString("\n")
-
- t.Focused.Base = lipgloss.NewStyle().
- BorderStyle(lipgloss.NormalBorder()).
- BorderForeground(cliui.ColorBorder).
- BorderLeft(true).
- PaddingLeft(1)
- t.Focused.Card = t.Focused.Base
- t.Focused.Title = lipgloss.NewStyle().Foreground(accent).Bold(true)
- t.Focused.NoteTitle = lipgloss.NewStyle().
- Foreground(accentLight).
- Bold(true)
- t.Focused.Description = lipgloss.NewStyle().Foreground(textPrimary)
- t.Focused.ErrorIndicator = lipgloss.NewStyle().Foreground(destructive)
- t.Focused.ErrorMessage = lipgloss.NewStyle().Foreground(destructive)
- t.Focused.SelectSelector = lipgloss.NewStyle().Foreground(accentLight).SetString("> ")
- t.Focused.Option = lipgloss.NewStyle().Foreground(textPrimary)
- t.Focused.SelectedOption = lipgloss.NewStyle().Foreground(success).Bold(true)
- t.Focused.SelectedPrefix = lipgloss.NewStyle().Foreground(success).SetString("✓ ")
- t.Focused.UnselectedOption = lipgloss.NewStyle().Foreground(textSecondary)
- t.Focused.UnselectedPrefix = lipgloss.NewStyle().Foreground(textMuted).SetString("• ")
- t.Focused.NextIndicator = lipgloss.NewStyle().Foreground(accentLight).SetString("→")
- t.Focused.PrevIndicator = lipgloss.NewStyle().Foreground(accentLight).SetString("←")
- t.Focused.FocusedButton = lipgloss.NewStyle().
- Foreground(accentLight).
- Bold(true).
- Underline(true)
- t.Focused.BlurredButton = lipgloss.NewStyle().
- Foreground(textSecondary).
- Padding(0, 0)
- t.Focused.Next = lipgloss.NewStyle().
- Foreground(accentLight).
- Bold(true).
- Underline(true)
- t.Focused.TextInput.Cursor = lipgloss.NewStyle().Foreground(accentLight)
- t.Focused.TextInput.CursorText = lipgloss.NewStyle().Foreground(textPrimary)
- t.Focused.TextInput.Placeholder = lipgloss.NewStyle().Foreground(textMuted)
- t.Focused.TextInput.Prompt = lipgloss.NewStyle().Foreground(accentLight)
- t.Focused.TextInput.Text = lipgloss.NewStyle().Foreground(textPrimary)
-
- t.Blurred = t.Focused
- t.Blurred.Base = lipgloss.NewStyle().
- BorderStyle(lipgloss.HiddenBorder()).
- PaddingLeft(1)
- t.Blurred.Card = t.Blurred.Base
- t.Blurred.Title = lipgloss.NewStyle().Foreground(textSecondary)
- t.Blurred.NoteTitle = lipgloss.NewStyle().Foreground(textSecondary).Bold(true)
- t.Blurred.Description = lipgloss.NewStyle().Foreground(textSecondary)
- t.Blurred.Option = lipgloss.NewStyle().Foreground(textSecondary)
- t.Blurred.SelectedOption = lipgloss.NewStyle().Foreground(success)
- t.Blurred.UnselectedOption = lipgloss.NewStyle().Foreground(textMuted)
- t.Blurred.NextIndicator = lipgloss.NewStyle().Foreground(warning)
- t.Blurred.PrevIndicator = lipgloss.NewStyle().Foreground(warning)
-
- return t
-}
-
-func renderOnboardConfigStep(step, total int, configPath string, configStatus onboardConfigStatus) string {
- var out bytes.Buffer
- fmt.Fprintf(&out, "%s\n", styleOnboardStep(step, total, "Config"))
- switch configStatus {
- case onboardConfigCreated:
- writeOnboardMessage(&out, true, "Wrote a default config to %s.", configPath)
- case onboardConfigRecovered:
- writeOnboardWarning(&out, "Recovered the secure baseline in %s.", configPath)
- writeOnboardNote(&out, "Existing browser, profile, port, and timeout settings were preserved.")
- default:
- writeOnboardMessage(&out, true, "Verified the existing config at %s.", configPath)
- writeOnboardNote(&out, "Recovery defaults were already in place.")
- }
- writeOnboardNote(&out, "PinchTab will read this file unless `PINCHTAB_CONFIG` overrides it.")
- out.WriteString("\n")
- return out.String()
-}
-
-func renderOnboardAPIAccessStep(step, total int, cfg *config.RuntimeConfig) string {
- var out bytes.Buffer
- fmt.Fprintf(&out, "%s\n", styleOnboardStep(step, total, "API access"))
- writeOnboardKV(&out, "server.bind", cfg.Bind)
- writeOnboardNote(&out, "Keeps the API local to this machine when set to 127.0.0.1.")
- writeOnboardKV(&out, "server.token", summarizeToken(cfg.Token))
- writeOnboardNote(&out, "A bearer token gates every API request and CLI call that reaches the server.")
- out.WriteString("\n")
- return out.String()
-}
-
-func renderOnboardSensitiveStep(step, total int, cfg *config.RuntimeConfig) string {
- var out bytes.Buffer
- fmt.Fprintf(&out, "%s\n", styleOnboardStep(step, total, "Sensitive capabilities"))
- writeSecurityToggle(&out, "security.allowEvaluate", cfg.AllowEvaluate, "JavaScript execution in the page context")
- writeSecurityToggle(&out, "security.allowMacro", cfg.AllowMacro, "higher-level macro automation routes")
- writeSecurityToggle(&out, "security.allowScreencast", cfg.AllowScreencast, "live page streaming output")
- writeSecurityToggle(&out, "security.allowDownload", cfg.AllowDownload, "server-side download endpoints")
- writeSecurityToggle(&out, "security.allowUpload", cfg.AllowUpload, "uploading local files through browser flows")
- out.WriteString("\n")
- return out.String()
-}
-
-func renderOnboardAttachStep(step, total int, cfg *config.RuntimeConfig) string {
- var out bytes.Buffer
- fmt.Fprintf(&out, "%s\n", styleOnboardStep(step, total, "Attach policy"))
- writeOnboardKV(&out, "security.attach.enabled", fmt.Sprintf("%t", cfg.AttachEnabled))
- writeOnboardNote(&out, "Leave this off unless you intentionally attach to an externally managed Chrome.")
- writeOnboardKV(&out, "security.attach.allowHosts", strings.Join(cfg.AttachAllowHosts, ", "))
- writeOnboardNote(&out, "Keeps attach targets scoped to trusted hosts.")
- writeOnboardKV(&out, "security.attach.allowSchemes", strings.Join(cfg.AttachAllowSchemes, ", "))
- writeOnboardNote(&out, "Restricts attach URLs to websocket transport.")
- out.WriteString("\n")
- return out.String()
-}
-
-func renderOnboardIDPIStep(step, total int, cfg *config.RuntimeConfig) string {
- var out bytes.Buffer
- fmt.Fprintf(&out, "%s\n", styleOnboardStep(step, total, "IDPI protections"))
- writeOnboardKV(&out, "security.idpi.enabled", fmt.Sprintf("%t", cfg.IDPI.Enabled))
- writeOnboardNote(&out, "Enables indirect prompt-injection defenses for navigation and extracted content.")
- writeOnboardKV(&out, "security.idpi.allowedDomains", formatStringSlice(cfg.IDPI.AllowedDomains))
- writeOnboardNote(&out, "Whitelists which sites are considered trusted enough for the local-default setup.")
- writeOnboardKV(&out, "security.idpi.strictMode", fmt.Sprintf("%t", cfg.IDPI.StrictMode))
- writeOnboardNote(&out, "Blocks disallowed domains or suspicious content instead of only warning.")
- writeOnboardKV(&out, "security.idpi.scanContent", fmt.Sprintf("%t", cfg.IDPI.ScanContent))
- writeOnboardNote(&out, "Scans `/text` and `/snapshot` output for prompt-injection patterns.")
- writeOnboardKV(&out, "security.idpi.wrapContent", fmt.Sprintf("%t", cfg.IDPI.WrapContent))
- writeOnboardNote(&out, "Wraps extracted content so downstream agents can treat it as untrusted data.")
- out.WriteString("\n")
- return out.String()
-}
-
-func renderOnboardDaemonStep(step, total int, installed bool) string {
- var out bytes.Buffer
- fmt.Fprintf(&out, "%s\n", styleOnboardStep(step, total, "Background service"))
- if installed {
- writeOnboardMessage(&out, true, "Installed and started a user-level daemon for PinchTab.")
- writeOnboardNote(&out, "Use `pinchtab daemon`, `start`, `restart`, `stop`, or `uninstall` to manage it.")
- out.WriteString("\n")
- return out.String()
- }
- writeOnboardWarning(&out, "This step installs a user-level background service and starts PinchTab automatically.")
- writeOnboardNote(&out, "After install you can use `pinchtab daemon`, `start`, `restart`, `stop`, and `uninstall`.")
- out.WriteString("\n")
- return out.String()
-}
-
-func renderOnboardNextStep(step, total int, installDaemon bool) string {
- var out bytes.Buffer
- if step > 0 && total > 0 {
- fmt.Fprintf(&out, "%s\n", styleOnboardStep(step, total, "Next commands"))
- } else {
- fmt.Fprintf(&out, "%s\n", cliui.ValueStyle.Render("Next commands"))
- }
- if installDaemon {
- writeOnboardCommand(&out, "pinchtab daemon")
- writeOnboardCommand(&out, "pinchtab health")
- writeOnboardCommand(&out, "pinchtab security")
- } else {
- writeOnboardCommand(&out, "pinchtab server")
- writeOnboardCommand(&out, "pinchtab health")
- writeOnboardCommand(&out, "pinchtab security")
- }
- writeOnboardCommand(&out, "pinchtab quick https://example.com")
- return out.String()
-}
-
-func renderOnboardTitle() string {
- return cliui.HeadingStyle.Render("PinchTab") + " " + cliui.CommandStyle.Render("onboarding")
-}
-
-func styleOnboardStep(step, total int, title string) string {
- prefix := cliui.StyleStdout(cliui.HeadingStyle, fmt.Sprintf("Step %d/%d", step, total))
- return prefix + " " + cliui.ValueStyle.Render(title)
-}
-
-func writeOnboardKV(out *bytes.Buffer, key, value string) {
- fmt.Fprintf(out, " %s %s\n", cliui.MutedStyle.Render(key), cliui.ValueStyle.Render(value))
-}
-
-func writeOnboardNote(out *bytes.Buffer, message string, args ...any) {
- fmt.Fprintf(out, " %s %s\n", cliui.StyleStdout(cliui.MutedStyle, ">"), cliui.StyleStdout(cliui.MutedStyle, fmt.Sprintf(message, args...)))
-}
-
-func writeOnboardMessage(out *bytes.Buffer, ok bool, message string, args ...any) {
- fmt.Fprintf(out, " [%s] %s\n", styleMarker(ok), fmt.Sprintf(message, args...))
-}
-
-func writeOnboardWarning(out *bytes.Buffer, message string, args ...any) {
- fmt.Fprintf(out, " [%s] %s\n", styleMarker(false), fmt.Sprintf(message, args...))
-}
-
-func writeOnboardCommand(out *bytes.Buffer, command string) {
- fmt.Fprintf(out, " %s %s\n", cliui.StyleStdout(cliui.MutedStyle, "$"), cliui.ValueStyle.Render(command))
-}
-
func printDaemonFollowUp() {
fmt.Println()
- fmt.Println(cliui.StyleStdout(cliui.HeadingStyle, "Follow-up commands:"))
- fmt.Printf(" %s %s\n", cliui.StyleStdout(cliui.CommandStyle, "pinchtab daemon"), cliui.StyleStdout(cliui.MutedStyle, "# Check service health and logs"))
- fmt.Printf(" %s %s\n", cliui.StyleStdout(cliui.CommandStyle, "pinchtab daemon restart"), cliui.StyleStdout(cliui.MutedStyle, "# Apply config changes"))
- fmt.Printf(" %s %s\n", cliui.StyleStdout(cliui.CommandStyle, "pinchtab daemon stop"), cliui.StyleStdout(cliui.MutedStyle, "# Stop background service"))
- fmt.Printf(" %s %s\n", cliui.StyleStdout(cliui.CommandStyle, "pinchtab daemon uninstall"), cliui.StyleStdout(cliui.MutedStyle, "# Remove service file"))
+ fmt.Println(cli.StyleStdout(cli.HeadingStyle, "Follow-up commands:"))
+ fmt.Printf(" %s %s\n", cli.StyleStdout(cli.CommandStyle, "pinchtab daemon"), cli.StyleStdout(cli.MutedStyle, "# Check service health and logs"))
+ fmt.Printf(" %s %s\n", cli.StyleStdout(cli.CommandStyle, "pinchtab daemon restart"), cli.StyleStdout(cli.MutedStyle, "# Apply config changes"))
+ fmt.Printf(" %s %s\n", cli.StyleStdout(cli.CommandStyle, "pinchtab daemon stop"), cli.StyleStdout(cli.MutedStyle, "# Stop background service"))
+ fmt.Printf(" %s %s\n", cli.StyleStdout(cli.CommandStyle, "pinchtab daemon uninstall"), cli.StyleStdout(cli.MutedStyle, "# Remove service file"))
}
func currentDaemonManager() (daemonManager, error) {
@@ -718,6 +354,13 @@ func (m *systemdUserManager) ServicePath() string {
return filepath.Join(systemdUserConfigHome(m.env), "systemd", "user", pinchtabDaemonUnitName)
}
+func (m *systemdUserManager) Preflight() error {
+ if _, err := runCommand(m.runner, "systemctl", "--user", "show-environment"); err != nil {
+ return fmt.Errorf("linux daemon install requires a working user systemd session (`systemctl --user`): %w", err)
+ }
+ return nil
+}
+
func (m *systemdUserManager) Install(execPath, configPath string) (string, error) {
if err := os.MkdirAll(filepath.Dir(m.ServicePath()), 0755); err != nil {
return "", fmt.Errorf("create systemd user directory: %w", err)
@@ -806,16 +449,16 @@ func (m *systemdUserManager) Logs(n int) (string, error) {
func (m *systemdUserManager) ManualInstructions() string {
path := m.ServicePath()
var b strings.Builder
- fmt.Fprintln(&b, cliui.StyleStdout(cliui.HeadingStyle, "Manual instructions (Linux/systemd):"))
- fmt.Fprintln(&b, cliui.StyleStdout(cliui.MutedStyle, "To install manually:"))
- fmt.Fprintf(&b, " 1. Create %s\n", cliui.StyleStdout(cliui.ValueStyle, path))
- fmt.Fprintln(&b, " 2. Run: "+cliui.StyleStdout(cliui.CommandStyle, "systemctl --user daemon-reload"))
- fmt.Fprintln(&b, " 3. Run: "+cliui.StyleStdout(cliui.CommandStyle, "systemctl --user enable --now pinchtab.service"))
+ fmt.Fprintln(&b, cli.StyleStdout(cli.HeadingStyle, "Manual instructions (Linux/systemd):"))
+ fmt.Fprintln(&b, cli.StyleStdout(cli.MutedStyle, "To install manually:"))
+ fmt.Fprintf(&b, " 1. Create %s\n", cli.StyleStdout(cli.ValueStyle, path))
+ fmt.Fprintln(&b, " 2. Run: "+cli.StyleStdout(cli.CommandStyle, "systemctl --user daemon-reload"))
+ fmt.Fprintln(&b, " 3. Run: "+cli.StyleStdout(cli.CommandStyle, "systemctl --user enable --now pinchtab.service"))
fmt.Fprintln(&b)
- fmt.Fprintln(&b, cliui.StyleStdout(cliui.MutedStyle, "To uninstall manually:"))
- fmt.Fprintln(&b, " 1. Run: "+cliui.StyleStdout(cliui.CommandStyle, "systemctl --user disable --now pinchtab.service"))
- fmt.Fprintf(&b, " 2. Remove: %s\n", cliui.StyleStdout(cliui.ValueStyle, path))
- fmt.Fprintln(&b, " 3. Run: "+cliui.StyleStdout(cliui.CommandStyle, "systemctl --user daemon-reload"))
+ fmt.Fprintln(&b, cli.StyleStdout(cli.MutedStyle, "To uninstall manually:"))
+ fmt.Fprintln(&b, " 1. Run: "+cli.StyleStdout(cli.CommandStyle, "systemctl --user disable --now pinchtab.service"))
+ fmt.Fprintf(&b, " 2. Remove: %s\n", cli.StyleStdout(cli.ValueStyle, path))
+ fmt.Fprintln(&b, " 3. Run: "+cli.StyleStdout(cli.CommandStyle, "systemctl --user daemon-reload"))
return b.String()
}
@@ -840,6 +483,16 @@ func (m *launchdManager) ServicePath() string {
return filepath.Join(m.env.homeDir, "Library", "LaunchAgents", pinchtabLaunchdLabel+".plist")
}
+func (m *launchdManager) Preflight() error {
+ if strings.TrimSpace(m.env.userID) == "" {
+ return fmt.Errorf("macOS daemon install requires a logged-in user session with a launchd GUI domain")
+ }
+ if _, err := runCommand(m.runner, "launchctl", "print", launchdDomainTarget(m.env)); err != nil {
+ return fmt.Errorf("macOS daemon install requires an active launchd GUI session: %w", err)
+ }
+ return nil
+}
+
func (m *launchdManager) Install(execPath, configPath string) (string, error) {
if err := os.MkdirAll(filepath.Dir(m.ServicePath()), 0755); err != nil {
return "", fmt.Errorf("create LaunchAgents directory: %w", err)
@@ -937,14 +590,14 @@ func (m *launchdManager) ManualInstructions() string {
path := m.ServicePath()
target := launchdDomainTarget(m.env)
var b strings.Builder
- fmt.Fprintln(&b, cliui.StyleStdout(cliui.HeadingStyle, "Manual instructions (macOS/launchd):"))
- fmt.Fprintln(&b, cliui.StyleStdout(cliui.MutedStyle, "To install manually:"))
- fmt.Fprintf(&b, " 1. Create %s\n", cliui.StyleStdout(cliui.ValueStyle, path))
- fmt.Fprintln(&b, " 2. Run: "+cliui.StyleStdout(cliui.CommandStyle, fmt.Sprintf("launchctl bootstrap %s %s", target, path)))
+ fmt.Fprintln(&b, cli.StyleStdout(cli.HeadingStyle, "Manual instructions (macOS/launchd):"))
+ fmt.Fprintln(&b, cli.StyleStdout(cli.MutedStyle, "To install manually:"))
+ fmt.Fprintf(&b, " 1. Create %s\n", cli.StyleStdout(cli.ValueStyle, path))
+ fmt.Fprintln(&b, " 2. Run: "+cli.StyleStdout(cli.CommandStyle, fmt.Sprintf("launchctl bootstrap %s %s", target, path)))
fmt.Fprintln(&b)
- fmt.Fprintln(&b, cliui.StyleStdout(cliui.MutedStyle, "To uninstall manually:"))
- fmt.Fprintln(&b, " 1. Run: "+cliui.StyleStdout(cliui.CommandStyle, fmt.Sprintf("launchctl bootout %s %s", target, path)))
- fmt.Fprintf(&b, " 2. Remove: %s\n", cliui.StyleStdout(cliui.ValueStyle, path))
+ fmt.Fprintln(&b, cli.StyleStdout(cli.MutedStyle, "To uninstall manually:"))
+ fmt.Fprintln(&b, " 1. Run: "+cli.StyleStdout(cli.CommandStyle, fmt.Sprintf("launchctl bootout %s %s", target, path)))
+ fmt.Fprintf(&b, " 2. Remove: %s\n", cli.StyleStdout(cli.ValueStyle, path))
return b.String()
}
diff --git a/cmd/pinchtab/cmd_onboard_test.go b/cmd/pinchtab/cmd_onboard_test.go
index 8b06218f..f6199a09 100644
--- a/cmd/pinchtab/cmd_onboard_test.go
+++ b/cmd/pinchtab/cmd_onboard_test.go
@@ -1,12 +1,11 @@
package main
import (
+ "errors"
"os"
"path/filepath"
"strings"
"testing"
-
- "github.com/pinchtab/pinchtab/internal/config"
)
type fakeCommandRunner struct {
@@ -107,25 +106,6 @@ func TestEnsureOnboardConfigRecoversExistingSecuritySettings(t *testing.T) {
}
}
-func TestRenderOnboardGuideIncludesSecurityValues(t *testing.T) {
- cfg := testRuntimeConfig()
- output := renderOnboardGuide("/tmp/pinchtab/config.json", cfg, onboardConfigCreated, true)
-
- required := []string{
- "Step 2/7 API access",
- "server.bind 127.0.0.1",
- "security.allowEvaluate false",
- "security.attach.enabled false",
- "security.idpi.strictMode true",
- "pinchtab daemon",
- }
- for _, needle := range required {
- if !strings.Contains(output, needle) {
- t.Fatalf("expected onboarding guide to contain %q\n%s", needle, output)
- }
- }
-}
-
func TestSystemdUserManagerInstallWritesUnitAndEnablesService(t *testing.T) {
root := t.TempDir()
runner := &fakeCommandRunner{}
@@ -214,6 +194,46 @@ func TestLaunchdManagerInstallWritesPlistAndBootstrapsAgent(t *testing.T) {
}
}
+func TestSystemdUserManagerPreflightRequiresUserSession(t *testing.T) {
+ runner := &fakeCommandRunner{
+ errors: map[string]error{
+ "systemctl --user show-environment": errors.New("exit status 1"),
+ },
+ }
+ manager := &systemdUserManager{
+ env: daemonEnvironment{osName: "linux"},
+ runner: runner,
+ }
+
+ err := manager.Preflight()
+ if err == nil {
+ t.Fatal("expected preflight error")
+ }
+ if !strings.Contains(err.Error(), "working user systemd session") {
+ t.Fatalf("unexpected error: %v", err)
+ }
+}
+
+func TestLaunchdManagerPreflightRequiresGUIDomain(t *testing.T) {
+ runner := &fakeCommandRunner{
+ errors: map[string]error{
+ "launchctl print gui/501": errors.New("exit status 113"),
+ },
+ }
+ manager := &launchdManager{
+ env: daemonEnvironment{osName: "darwin", userID: "501"},
+ runner: runner,
+ }
+
+ err := manager.Preflight()
+ if err == nil {
+ t.Fatal("expected preflight error")
+ }
+ if !strings.Contains(err.Error(), "active launchd GUI session") {
+ t.Fatalf("unexpected error: %v", err)
+ }
+}
+
func TestNewDaemonManagerRejectsUnsupportedOS(t *testing.T) {
_, err := newDaemonManager(daemonEnvironment{osName: "windows"}, &fakeCommandRunner{})
if err == nil {
@@ -221,24 +241,44 @@ func TestNewDaemonManagerRejectsUnsupportedOS(t *testing.T) {
}
}
-func testRuntimeConfig() *config.RuntimeConfig {
- return &config.RuntimeConfig{
- Bind: "127.0.0.1",
- Token: "abcd1234efgh5678",
- AllowEvaluate: false,
- AllowMacro: false,
- AllowScreencast: false,
- AllowDownload: false,
- AllowUpload: false,
- AttachEnabled: false,
- AttachAllowHosts: []string{"127.0.0.1", "localhost", "::1"},
- AttachAllowSchemes: []string{"ws", "wss"},
- IDPI: config.IDPIConfig{
- Enabled: true,
- AllowedDomains: []string{"127.0.0.1", "localhost", "::1"},
- StrictMode: true,
- ScanContent: true,
- WrapContent: true,
+func TestDaemonMenuOptions(t *testing.T) {
+ tests := []struct {
+ name string
+ installed bool
+ running bool
+ want []string
+ }{
+ {
+ name: "not installed",
+ installed: false,
+ running: false,
+ want: []string{"install", "exit"},
},
+ {
+ name: "installed stopped",
+ installed: true,
+ running: false,
+ want: []string{"start", "uninstall", "exit"},
+ },
+ {
+ name: "installed running",
+ installed: true,
+ running: true,
+ want: []string{"stop", "restart", "uninstall", "exit"},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := daemonMenuOptions(tt.installed, tt.running)
+ if len(got) != len(tt.want) {
+ t.Fatalf("len(daemonMenuOptions()) = %d, want %d", len(got), len(tt.want))
+ }
+ for i, want := range tt.want {
+ if got[i].value != want {
+ t.Fatalf("daemonMenuOptions()[%d] = %q, want %q", i, got[i].value, want)
+ }
+ }
+ })
}
}
diff --git a/cmd/pinchtab/cmd_security.go b/cmd/pinchtab/cmd_security.go
index 682e7f88..71e5989e 100644
--- a/cmd/pinchtab/cmd_security.go
+++ b/cmd/pinchtab/cmd_security.go
@@ -1,13 +1,13 @@
package main
import (
- "bufio"
+ "encoding/json"
"fmt"
"os"
- "reflect"
+ "slices"
"strings"
- "github.com/pinchtab/pinchtab/internal/cliui"
+ "github.com/pinchtab/pinchtab/internal/cli"
"github.com/pinchtab/pinchtab/internal/config"
"github.com/spf13/cobra"
)
@@ -17,80 +17,96 @@ var securityCmd = &cobra.Command{
Short: "Review runtime security posture",
Long: "Shows runtime security posture and offers to restore recommended security defaults.",
Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
+ cfg := loadConfig()
handleSecurityCommand(cfg)
},
}
func init() {
+ securityCmd.GroupID = "config"
+ securityCmd.AddCommand(&cobra.Command{
+ Use: "up",
+ Short: "Apply recommended security defaults",
+ Run: func(cmd *cobra.Command, args []string) {
+ handleSecurityUpCommand()
+ },
+ })
+ securityCmd.AddCommand(&cobra.Command{
+ Use: "down",
+ Short: "Lower guards while keeping loopback bind and API auth enabled",
+ Run: func(cmd *cobra.Command, args []string) {
+ handleSecurityDownCommand()
+ },
+ })
rootCmd.AddCommand(securityCmd)
}
func handleSecurityCommand(cfg *config.RuntimeConfig) {
- warnings := assessSecurityWarnings(cfg)
- recommended := recommendedSecurityDefaultLines(cfg)
+ interactive := isInteractiveTerminal()
- fmt.Println(cliui.StyleStdout(cliui.HeadingStyle, "Security posture"))
- fmt.Println()
- printSecuritySummary(os.Stdout, cfg, " ")
+ for {
+ posture := cli.AssessSecurityPosture(cfg)
+ warnings := cli.AssessSecurityWarnings(cfg)
+ recommended := cli.RecommendedSecurityDefaultLines(cfg)
- if len(warnings) == 0 {
- fmt.Println(cliui.StyleStdout(cliui.HeadingStyle, "Warnings"))
- fmt.Println()
- fmt.Println(" " + cliui.StyleStdout(cliui.MutedStyle, "none"))
- } else {
- fmt.Println(cliui.StyleStdout(cliui.HeadingStyle, "Warnings"))
- fmt.Println()
- for _, warning := range warnings {
- fmt.Printf(" - %s\n", cliui.StyleStdout(cliui.WarningStyle, warning.Message))
- for i := 0; i+1 < len(warning.Attrs); i += 2 {
- key, ok := warning.Attrs[i].(string)
- if !ok || key == "hint" {
- continue
+ printSecuritySummary(posture, interactive)
+
+ if len(warnings) > 0 {
+ fmt.Println()
+ fmt.Println(cli.StyleStdout(cli.HeadingStyle, "Warnings"))
+ fmt.Println()
+ for _, warning := range warnings {
+ fmt.Printf(" - %s\n", cli.StyleStdout(cli.WarningStyle, warning.Message))
+ for i := 0; i+1 < len(warning.Attrs); i += 2 {
+ key, ok := warning.Attrs[i].(string)
+ if !ok || key == "hint" {
+ continue
+ }
+ fmt.Printf(" %s: %s\n", cli.StyleStdout(cli.MutedStyle, key), cli.StyleStdout(cli.ValueStyle, formatSecurityValue(warning.Attrs[i+1])))
}
- fmt.Printf(" %s: %s\n", cliui.StyleStdout(cliui.MutedStyle, key), cliui.StyleStdout(cliui.ValueStyle, formatSecurityValue(warning.Attrs[i+1])))
- }
- for i := 0; i+1 < len(warning.Attrs); i += 2 {
- key, ok := warning.Attrs[i].(string)
- if ok && key == "hint" {
- fmt.Printf(" %s: %s\n", cliui.StyleStdout(cliui.MutedStyle, "hint"), cliui.StyleStdout(cliui.ValueStyle, formatSecurityValue(warning.Attrs[i+1])))
+ for i := 0; i+1 < len(warning.Attrs); i += 2 {
+ key, ok := warning.Attrs[i].(string)
+ if ok && key == "hint" {
+ fmt.Printf(" %s: %s\n", cli.StyleStdout(cli.MutedStyle, "hint"), cli.StyleStdout(cli.ValueStyle, formatSecurityValue(warning.Attrs[i+1])))
+ }
}
}
}
- }
-
- fmt.Println()
- fmt.Println(cliui.StyleStdout(cliui.HeadingStyle, "Recommended security defaults"))
- fmt.Println()
- if len(recommended) == 0 {
- fmt.Println(" " + cliui.StyleStdout(cliui.MutedStyle, "none"))
- } else {
- printRecommendedSecurityDefaults(recommended)
- }
- fmt.Println()
- if !isInteractiveTerminal() {
- fmt.Println(cliui.StyleStdout(cliui.MutedStyle, "Interactive restore skipped because stdin/stdout is not a terminal."))
- return
- }
+ if len(recommended) == 0 && len(warnings) == 0 {
+ fmt.Println()
+ fmt.Println(" " + cli.StyleStdout(cli.SuccessStyle, "All recommended security defaults are active."))
+ } else if len(recommended) > 0 {
+ fmt.Println()
+ fmt.Println(cli.StyleStdout(cli.HeadingStyle, "Recommended defaults"))
+ fmt.Println()
+ printRecommendedSecurityDefaults(recommended)
+ }
- if !promptRestoreDefaults() {
- fmt.Println(cliui.StyleStdout(cliui.MutedStyle, "No changes made."))
- return
- }
+ if !interactive {
+ if len(recommended) > 0 {
+ fmt.Println()
+ fmt.Println(cli.StyleStdout(cli.MutedStyle, "Interactive editing skipped because stdin/stdout is not a terminal."))
+ }
+ return
+ }
- configPath, changed, err := restoreSecurityDefaults()
- if err != nil {
- fmt.Fprintln(os.Stderr, cliui.StyleStderr(cliui.ErrorStyle, fmt.Sprintf("Error restoring defaults: %v", err)))
- os.Exit(1)
- }
- if !changed {
- fmt.Println(cliui.StyleStdout(cliui.MutedStyle, fmt.Sprintf("Security defaults already match %s", configPath)))
- return
+ nextCfg, changed, done, err := promptSecurityEdit(cfg, posture, len(recommended) > 0)
+ if err != nil {
+ fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, err.Error()))
+ os.Exit(1)
+ }
+ if done {
+ return
+ }
+ if !changed {
+ fmt.Println()
+ fmt.Println(cli.StyleStdout(cli.MutedStyle, "No changes made."))
+ return
+ }
+ cfg = nextCfg
+ fmt.Println()
}
-
- fmt.Println(cliui.StyleStdout(cliui.SuccessStyle, fmt.Sprintf("Security defaults restored in %s", configPath)))
- fmt.Println(cliui.StyleStdout(cliui.MutedStyle, "Restart PinchTab to apply file-based changes."))
}
func formatSecurityValue(value any) string {
@@ -104,128 +120,355 @@ func formatSecurityValue(value any) string {
func printRecommendedSecurityDefaults(lines []string) {
for _, line := range lines {
- fmt.Printf(" - %s\n", cliui.StyleStdout(cliui.ValueStyle, line))
- }
-}
-
-func recommendedSecurityDefaultLines(cfg *config.RuntimeConfig) []string {
- posture := assessSecurityPosture(cfg)
- ordered := []string{
- "server.bind = 127.0.0.1",
- "security.allowEvaluate = false",
- "security.allowMacro = false",
- "security.allowScreencast = false",
- "security.allowDownload = false",
- "security.allowUpload = false",
- "security.attach.enabled = false",
- "security.attach.allowHosts = 127.0.0.1,localhost,::1",
- "security.attach.allowSchemes = ws,wss",
- "security.idpi.enabled = true",
- "security.idpi.allowedDomains = 127.0.0.1,localhost,::1",
- "security.idpi.strictMode = true",
- "security.idpi.scanContent = true",
- "security.idpi.wrapContent = true",
- }
- needed := make(map[string]bool, len(ordered))
-
- for _, check := range posture.Checks {
+ fmt.Printf(" - %s\n", cli.StyleStdout(cli.ValueStyle, line))
+ }
+}
+
+func printSecuritySummary(posture cli.SecurityPosture, interactive bool) {
+ fmt.Println(cli.StyleStdout(cli.HeadingStyle, "Security"))
+ fmt.Println()
+ fmt.Printf(" %s %s\n", posture.Bar, cli.StyleStdout(cli.ValueStyle, posture.Level))
+ for i, check := range posture.Checks {
+ indicator := cli.StyleStdout(cli.WarningStyle, "!!")
if check.Passed {
+ indicator = cli.StyleStdout(cli.SuccessStyle, "ok")
+ }
+ if interactive {
+ fmt.Printf(" %d. %s %-20s %s\n", i+1, indicator, check.Label, check.Detail)
continue
}
- switch check.ID {
- case "bind_loopback":
- needed["server.bind = 127.0.0.1"] = true
- case "sensitive_endpoints_disabled":
- needed["security.allowEvaluate = false"] = true
- needed["security.allowMacro = false"] = true
- needed["security.allowScreencast = false"] = true
- needed["security.allowDownload = false"] = true
- needed["security.allowUpload = false"] = true
- case "attach_disabled":
- needed["security.attach.enabled = false"] = true
- needed["security.attach.allowHosts = 127.0.0.1,localhost,::1"] = true
- needed["security.attach.allowSchemes = ws,wss"] = true
- case "attach_local_only":
- needed["security.attach.allowHosts = 127.0.0.1,localhost,::1"] = true
- needed["security.attach.allowSchemes = ws,wss"] = true
- case "idpi_whitelist_scoped", "idpi_strict_mode", "idpi_content_protection":
- needed["security.idpi.enabled = true"] = true
- needed["security.idpi.allowedDomains = 127.0.0.1,localhost,::1"] = true
- needed["security.idpi.strictMode = true"] = true
- needed["security.idpi.scanContent = true"] = true
- needed["security.idpi.wrapContent = true"] = true
- }
- }
-
- lines := make([]string, 0, len(needed))
- for _, line := range ordered {
- if needed[line] {
- lines = append(lines, line)
- }
- }
- return lines
-}
-
-func promptRestoreDefaults() bool {
- fmt.Print(cliui.StyleStdout(cliui.HeadingStyle, "Restore recommended security defaults in config?") + " " + cliui.StyleStdout(cliui.MutedStyle, "(y/N): "))
- reader := bufio.NewReader(os.Stdin)
- response, err := reader.ReadString('\n')
- if err != nil && strings.TrimSpace(response) == "" {
- return false
- }
- switch strings.ToLower(strings.TrimSpace(response)) {
- case "y", "yes":
- return true
- default:
- return false
+ fmt.Printf(" %s %-20s %s\n", indicator, check.Label, check.Detail)
+ }
+}
+
+func promptSecurityEdit(cfg *config.RuntimeConfig, posture cli.SecurityPosture, canRestoreDefaults bool) (*config.RuntimeConfig, bool, bool, error) {
+ fmt.Println()
+ prompt := "Edit item (1-8"
+ if canRestoreDefaults {
+ prompt += ", u = security up"
+ }
+ prompt += ", d = security down, blank to exit):"
+
+ choice, err := promptInput(cli.StyleStdout(cli.HeadingStyle, prompt), "")
+ if err != nil {
+ return nil, false, false, err
+ }
+ choice = strings.ToLower(strings.TrimSpace(choice))
+ if choice == "" {
+ return nil, false, true, nil
+ }
+
+ if (choice == "u" || choice == "up") && canRestoreDefaults {
+ nextCfg, changed, err := applySecurityUp()
+ return nextCfg, changed, false, err
+ }
+
+ if choice == "d" || choice == "down" {
+ nextCfg, changed, err := applySecurityDown()
+ return nextCfg, changed, false, err
+ }
+
+ index := strings.TrimSpace(choice)
+ for i, check := range posture.Checks {
+ if index == fmt.Sprint(i+1) {
+ nextCfg, changed, err := editSecurityCheck(cfg, check)
+ return nextCfg, changed, false, err
+ }
+ }
+
+ return nil, false, false, fmt.Errorf("invalid selection %q", choice)
+}
+
+func editSecurityCheck(cfg *config.RuntimeConfig, check cli.SecurityPostureCheck) (*config.RuntimeConfig, bool, error) {
+ switch check.ID {
+ case "bind_loopback":
+ value, err := promptInput("Set server.bind:", cfg.Bind)
+ if err != nil {
+ return nil, false, err
+ }
+ return updateConfigValue("server.bind", value)
+ case "api_auth_enabled":
+ picked, err := promptSelect("API authentication", []menuOption{
+ {label: "Generate new token (Recommended)", value: "generate"},
+ {label: "Set custom token", value: "custom"},
+ {label: "Disable token", value: "disable"},
+ {label: "Cancel", value: "cancel"},
+ })
+ if err != nil || picked == "" || picked == "cancel" {
+ return cfg, false, nil
+ }
+ switch picked {
+ case "generate":
+ token, err := config.GenerateAuthToken()
+ if err != nil {
+ return nil, false, err
+ }
+ return updateConfigValue("server.token", token)
+ case "custom":
+ token, err := promptInput("Set server.token:", cfg.Token)
+ if err != nil {
+ return nil, false, err
+ }
+ return updateConfigValue("server.token", token)
+ case "disable":
+ return updateConfigValue("server.token", "")
+ }
+ case "sensitive_endpoints_disabled":
+ current := strings.Join(cfg.EnabledSensitiveEndpoints(), ",")
+ value, err := promptInput("Enable sensitive endpoints (evaluate,macro,screencast,download,upload; blank = disable all):", current)
+ if err != nil {
+ return nil, false, err
+ }
+ return updateSensitiveEndpoints(value)
+ case "attach_disabled":
+ picked, err := promptSelect("Attach endpoint", []menuOption{
+ {label: "Disable (Recommended)", value: "disable"},
+ {label: "Enable", value: "enable"},
+ {label: "Cancel", value: "cancel"},
+ })
+ if err != nil || picked == "" || picked == "cancel" {
+ return cfg, false, nil
+ }
+ return updateConfigValue("security.attach.enabled", fmt.Sprintf("%t", picked == "enable"))
+ case "attach_local_only":
+ value, err := promptInput("Set security.attach.allowHosts (comma-separated):", strings.Join(cfg.AttachAllowHosts, ","))
+ if err != nil {
+ return nil, false, err
+ }
+ return updateConfigValue("security.attach.allowHosts", value)
+ case "idpi_whitelist_scoped":
+ value, err := promptInput("Set security.idpi.allowedDomains (comma-separated):", strings.Join(cfg.IDPI.AllowedDomains, ","))
+ if err != nil {
+ return nil, false, err
+ }
+ return updateConfigValue("security.idpi.allowedDomains", value)
+ case "idpi_strict_mode":
+ picked, err := promptSelect("IDPI strict mode", []menuOption{
+ {label: "Enforce (Recommended)", value: "true"},
+ {label: "Warn only", value: "false"},
+ {label: "Cancel", value: "cancel"},
+ })
+ if err != nil || picked == "" || picked == "cancel" {
+ return cfg, false, nil
+ }
+ return updateConfigValue("security.idpi.strictMode", picked)
+ case "idpi_content_protection":
+ picked, err := promptSelect("IDPI content guard", []menuOption{
+ {label: "Active: scan + wrap (Recommended)", value: "both"},
+ {label: "Scan only", value: "scan"},
+ {label: "Wrap only", value: "wrap"},
+ {label: "Disable", value: "off"},
+ {label: "Cancel", value: "cancel"},
+ })
+ if err != nil || picked == "" || picked == "cancel" {
+ return cfg, false, nil
+ }
+ return updateContentGuard(picked)
+ }
+ return cfg, false, nil
+}
+
+func updateConfigValue(path, value string) (*config.RuntimeConfig, bool, error) {
+ fc, configPath, err := config.LoadFileConfig()
+ if err != nil {
+ return nil, false, fmt.Errorf("load config: %w", err)
+ }
+ if err := config.SetConfigValue(fc, path, value); err != nil {
+ return nil, false, fmt.Errorf("set %s: %w", path, err)
+ }
+ if errs := config.ValidateFileConfig(fc); len(errs) > 0 {
+ return nil, false, errs[0]
+ }
+ if err := config.SaveFileConfig(fc, configPath); err != nil {
+ return nil, false, fmt.Errorf("save config: %w", err)
+ }
+ return config.Load(), true, nil
+}
+
+func updateSensitiveEndpoints(value string) (*config.RuntimeConfig, bool, error) {
+ fc, configPath, err := config.LoadFileConfig()
+ if err != nil {
+ return nil, false, fmt.Errorf("load config: %w", err)
+ }
+
+ selected := map[string]bool{}
+ for _, item := range splitCommaList(value) {
+ selected[item] = true
+ }
+ for endpoint, path := range map[string]string{
+ "evaluate": "security.allowEvaluate",
+ "macro": "security.allowMacro",
+ "screencast": "security.allowScreencast",
+ "download": "security.allowDownload",
+ "upload": "security.allowUpload",
+ } {
+ enabled := selected[endpoint]
+ if err := config.SetConfigValue(fc, path, fmt.Sprintf("%t", enabled)); err != nil {
+ return nil, false, fmt.Errorf("set %s: %w", endpoint, err)
+ }
+ }
+ if errs := config.ValidateFileConfig(fc); len(errs) > 0 {
+ return nil, false, errs[0]
}
+ if err := config.SaveFileConfig(fc, configPath); err != nil {
+ return nil, false, fmt.Errorf("save config: %w", err)
+ }
+ return config.Load(), true, nil
}
-func restoreSecurityDefaults() (string, bool, error) {
+func updateContentGuard(mode string) (*config.RuntimeConfig, bool, error) {
fc, configPath, err := config.LoadFileConfig()
if err != nil {
- return "", false, err
+ return nil, false, fmt.Errorf("load config: %w", err)
+ }
+
+ scan := mode == "both" || mode == "scan"
+ wrap := mode == "both" || mode == "wrap"
+ for _, item := range []struct {
+ path string
+ value bool
+ }{
+ {path: "security.idpi.scanContent", value: scan},
+ {path: "security.idpi.wrapContent", value: wrap},
+ } {
+ if err := config.SetConfigValue(fc, item.path, fmt.Sprintf("%t", item.value)); err != nil {
+ return nil, false, fmt.Errorf("set %s: %w", item.path, err)
+ }
}
- before := securityDefaultsSnapshot(fc)
- applyRecommendedSecurityDefaults(fc)
- after := securityDefaultsSnapshot(fc)
- if reflect.DeepEqual(before, after) {
- return configPath, false, nil
+ if errs := config.ValidateFileConfig(fc); len(errs) > 0 {
+ return nil, false, errs[0]
}
if err := config.SaveFileConfig(fc, configPath); err != nil {
- return "", false, err
+ return nil, false, fmt.Errorf("save config: %w", err)
}
- return configPath, true, nil
+ return config.Load(), true, nil
}
-func applyRecommendedSecurityDefaults(fc *config.FileConfig) {
- defaults := config.DefaultFileConfig()
- if fc == nil {
- return
+func applyGuardsDownPreset() (*config.RuntimeConfig, string, bool, error) {
+ fc, configPath, err := config.LoadFileConfig()
+ if err != nil {
+ return nil, "", false, fmt.Errorf("load config: %w", err)
+ }
+ originalJSON, err := formatFileConfigJSON(fc)
+ if err != nil {
+ return nil, "", false, err
+ }
+
+ original, err := config.GetConfigValue(fc, "server.token")
+ if err != nil {
+ return nil, "", false, fmt.Errorf("read server.token: %w", err)
}
- fc.Server.Bind = defaults.Server.Bind
- if strings.TrimSpace(fc.Server.Token) == "" {
+ if strings.TrimSpace(original) == "" {
token, err := config.GenerateAuthToken()
- if err == nil {
- fc.Server.Token = token
+ if err != nil {
+ return nil, "", false, fmt.Errorf("generate token: %w", err)
+ }
+ if err := config.SetConfigValue(fc, "server.token", token); err != nil {
+ return nil, "", false, fmt.Errorf("set server.token: %w", err)
+ }
+ }
+
+ for _, item := range []struct {
+ path string
+ value string
+ }{
+ {path: "server.bind", value: "127.0.0.1"},
+ {path: "security.allowEvaluate", value: "true"},
+ {path: "security.allowMacro", value: "true"},
+ {path: "security.allowScreencast", value: "true"},
+ {path: "security.allowDownload", value: "true"},
+ {path: "security.allowUpload", value: "true"},
+ {path: "security.attach.enabled", value: "true"},
+ {path: "security.attach.allowHosts", value: "127.0.0.1,localhost,::1"},
+ {path: "security.attach.allowSchemes", value: "ws,wss"},
+ {path: "security.idpi.enabled", value: "false"},
+ {path: "security.idpi.strictMode", value: "false"},
+ {path: "security.idpi.scanContent", value: "false"},
+ {path: "security.idpi.wrapContent", value: "false"},
+ } {
+ if err := config.SetConfigValue(fc, item.path, item.value); err != nil {
+ return nil, "", false, fmt.Errorf("set %s: %w", item.path, err)
}
}
- fc.Security = defaults.Security
+
+ if errs := config.ValidateFileConfig(fc); len(errs) > 0 {
+ return nil, "", false, errs[0]
+ }
+
+ nextJSON, err := formatFileConfigJSON(fc)
+ if err != nil {
+ return nil, "", false, err
+ }
+ changed := originalJSON != nextJSON
+ if !changed {
+ return config.Load(), configPath, false, nil
+ }
+
+ if err := config.SaveFileConfig(fc, configPath); err != nil {
+ return nil, "", false, fmt.Errorf("save config: %w", err)
+ }
+ return config.Load(), configPath, true, nil
+}
+
+func applySecurityUp() (*config.RuntimeConfig, bool, error) {
+ configPath, changed, err := cli.RestoreSecurityDefaults()
+ if err != nil {
+ return nil, false, fmt.Errorf("restore defaults: %w", err)
+ }
+ if !changed {
+ fmt.Println(cli.StyleStdout(cli.MutedStyle, fmt.Sprintf("Security defaults already match %s", configPath)))
+ return config.Load(), false, nil
+ }
+ fmt.Println(cli.StyleStdout(cli.SuccessStyle, fmt.Sprintf("Security defaults restored in %s", configPath)))
+ fmt.Println(cli.StyleStdout(cli.MutedStyle, "Restart PinchTab to apply file-based changes."))
+ return config.Load(), true, nil
}
-type securityDefaultsState struct {
- Bind string
- Token string
- Security config.SecurityConfig
+func applySecurityDown() (*config.RuntimeConfig, bool, error) {
+ nextCfg, configPath, changed, err := applyGuardsDownPreset()
+ if err != nil {
+ return nil, false, fmt.Errorf("guards down: %w", err)
+ }
+ if !changed {
+ fmt.Println(cli.StyleStdout(cli.MutedStyle, fmt.Sprintf("Guards down preset already matches %s", configPath)))
+ return nextCfg, false, nil
+ }
+ fmt.Println(cli.StyleStdout(cli.WarningStyle, fmt.Sprintf("Guards down preset applied in %s", configPath)))
+ fmt.Println(cli.StyleStdout(cli.MutedStyle, "Loopback bind and API auth remain enabled; sensitive endpoints and attach are enabled, IDPI is disabled."))
+ return nextCfg, true, nil
+}
+
+func handleSecurityUpCommand() {
+ if _, _, err := applySecurityUp(); err != nil {
+ fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, err.Error()))
+ os.Exit(1)
+ }
}
-func securityDefaultsSnapshot(fc *config.FileConfig) securityDefaultsState {
- if fc == nil {
- return securityDefaultsState{}
+func handleSecurityDownCommand() {
+ if _, _, err := applySecurityDown(); err != nil {
+ fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, err.Error()))
+ os.Exit(1)
+ }
+}
+
+func formatFileConfigJSON(fc *config.FileConfig) (string, error) {
+ data, err := json.Marshal(fc)
+ if err != nil {
+ return "", fmt.Errorf("marshal config: %w", err)
}
- return securityDefaultsState{
- Bind: fc.Server.Bind,
- Token: fc.Server.Token,
- Security: fc.Security,
+ return string(data), nil
+}
+
+func splitCommaList(value string) []string {
+ parts := strings.Split(value, ",")
+ items := make([]string, 0, len(parts))
+ for _, part := range parts {
+ trimmed := strings.TrimSpace(strings.ToLower(part))
+ if trimmed != "" {
+ items = append(items, trimmed)
+ }
}
+ slices.Sort(items)
+ return slices.Compact(items)
}
diff --git a/cmd/pinchtab/cmd_security_test.go b/cmd/pinchtab/cmd_security_test.go
new file mode 100644
index 00000000..9a2fd8ea
--- /dev/null
+++ b/cmd/pinchtab/cmd_security_test.go
@@ -0,0 +1,140 @@
+package main
+
+import (
+ "io"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func TestHandleSecurityCommandDefaultConfigSkipsEmptySections(t *testing.T) {
+ cfg := testRuntimeConfig()
+
+ output := captureStdout(t, func() {
+ handleSecurityCommand(cfg)
+ })
+
+ required := []string{
+ "Security",
+ "All recommended security defaults are active.",
+ }
+ for _, needle := range required {
+ if !strings.Contains(output, needle) {
+ t.Fatalf("expected output to contain %q\n%s", needle, output)
+ }
+ }
+
+ unwanted := []string{
+ "Security posture",
+ "Warnings",
+ "Recommended security defaults",
+ "Recommended defaults",
+ "Restore recommended security defaults in config?",
+ "Interactive restore skipped because stdin/stdout is not a terminal.",
+ }
+ for _, needle := range unwanted {
+ if strings.Contains(output, needle) {
+ t.Fatalf("expected output to skip %q\n%s", needle, output)
+ }
+ }
+}
+
+func captureStdout(t *testing.T, fn func()) string {
+ t.Helper()
+
+ orig := os.Stdout
+ r, w, err := os.Pipe()
+ if err != nil {
+ t.Fatalf("os.Pipe() error = %v", err)
+ }
+ os.Stdout = w
+ defer func() {
+ os.Stdout = orig
+ }()
+
+ fn()
+
+ if err := w.Close(); err != nil {
+ t.Fatalf("close writer error = %v", err)
+ }
+ data, err := io.ReadAll(r)
+ if err != nil {
+ t.Fatalf("ReadAll() error = %v", err)
+ }
+ if err := r.Close(); err != nil {
+ t.Fatalf("close reader error = %v", err)
+ }
+ return string(data)
+}
+
+func TestApplyGuardsDownPreset(t *testing.T) {
+ configPath := filepath.Join(t.TempDir(), "pinchtab", "config.json")
+ t.Setenv("PINCHTAB_CONFIG", configPath)
+
+ fc := config.DefaultFileConfig()
+ fc.Server.Token = "guarded-token"
+ if err := os.MkdirAll(filepath.Dir(configPath), 0o755); err != nil {
+ t.Fatalf("MkdirAll() error = %v", err)
+ }
+ if err := config.SaveFileConfig(&fc, configPath); err != nil {
+ t.Fatalf("SaveFileConfig() error = %v", err)
+ }
+
+ cfg, gotPath, changed, err := applyGuardsDownPreset()
+ if err != nil {
+ t.Fatalf("applyGuardsDownPreset() error = %v", err)
+ }
+ if !changed {
+ t.Fatal("expected guards down preset to change config")
+ }
+ if gotPath != configPath {
+ t.Fatalf("config path = %q, want %q", gotPath, configPath)
+ }
+
+ if cfg.Bind != "127.0.0.1" {
+ t.Fatalf("Bind = %q, want 127.0.0.1", cfg.Bind)
+ }
+ if cfg.Token != "guarded-token" {
+ t.Fatalf("Token = %q, want existing token to remain", cfg.Token)
+ }
+ if !cfg.AllowEvaluate || !cfg.AllowMacro || !cfg.AllowScreencast || !cfg.AllowDownload || !cfg.AllowUpload {
+ t.Fatalf("expected sensitive endpoints enabled, got %+v", cfg)
+ }
+ if !cfg.AttachEnabled {
+ t.Fatal("expected attach endpoint enabled")
+ }
+ if got := strings.Join(cfg.AttachAllowHosts, ","); got != "127.0.0.1,localhost,::1" {
+ t.Fatalf("AttachAllowHosts = %q", got)
+ }
+ if got := strings.Join(cfg.AttachAllowSchemes, ","); got != "ws,wss" {
+ t.Fatalf("AttachAllowSchemes = %q", got)
+ }
+ if cfg.IDPI.Enabled || cfg.IDPI.StrictMode || cfg.IDPI.ScanContent || cfg.IDPI.WrapContent {
+ t.Fatalf("expected IDPI protections disabled, got %+v", cfg.IDPI)
+ }
+}
+
+func testRuntimeConfig() *config.RuntimeConfig {
+ return &config.RuntimeConfig{
+ Bind: "127.0.0.1",
+ Token: "abcd1234efgh5678",
+ AllowEvaluate: false,
+ AllowMacro: false,
+ AllowScreencast: false,
+ AllowDownload: false,
+ AllowUpload: false,
+ AttachEnabled: false,
+ AttachAllowHosts: []string{"127.0.0.1", "localhost", "::1"},
+ AttachAllowSchemes: []string{"ws", "wss"},
+ IDPI: config.IDPIConfig{
+ Enabled: true,
+ AllowedDomains: []string{"127.0.0.1", "localhost", "::1"},
+ StrictMode: true,
+ ScanContent: true,
+ WrapContent: true,
+ },
+ }
+}
diff --git a/cmd/pinchtab/cmd_server.go b/cmd/pinchtab/cmd_server.go
new file mode 100644
index 00000000..10a61506
--- /dev/null
+++ b/cmd/pinchtab/cmd_server.go
@@ -0,0 +1,21 @@
+package main
+
+import (
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/server"
+ "github.com/spf13/cobra"
+)
+
+var serverCmd = &cobra.Command{
+ Use: "server",
+ Short: "Start full server",
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := config.Load()
+ server.RunDashboard(cfg, version)
+ },
+}
+
+func init() {
+ serverCmd.GroupID = "primary"
+ rootCmd.AddCommand(serverCmd)
+}
diff --git a/cmd/pinchtab/config_load.go b/cmd/pinchtab/config_load.go
new file mode 100644
index 00000000..c7fb79d4
--- /dev/null
+++ b/cmd/pinchtab/config_load.go
@@ -0,0 +1,7 @@
+package main
+
+import "github.com/pinchtab/pinchtab/internal/config"
+
+func loadConfig() *config.RuntimeConfig {
+ return config.Load()
+}
diff --git a/cmd/pinchtab/prompt.go b/cmd/pinchtab/prompt.go
new file mode 100644
index 00000000..4f07d869
--- /dev/null
+++ b/cmd/pinchtab/prompt.go
@@ -0,0 +1,76 @@
+package main
+
+import (
+ "bufio"
+ "fmt"
+ "os"
+ "strconv"
+ "strings"
+
+ "github.com/pinchtab/pinchtab/internal/cli"
+)
+
+type menuOption struct {
+ label string
+ value string
+}
+
+func promptSelect(title string, options []menuOption) (string, error) {
+ if len(options) == 0 {
+ return "", nil
+ }
+
+ fmt.Println(cli.StyleStdout(cli.HeadingStyle, title))
+ for i, option := range options {
+ fmt.Printf(" %d. %s\n", i+1, option.label)
+ }
+ fmt.Print(cli.StyleStdout(cli.MutedStyle, "Select an option") + " " + cli.StyleStdout(cli.MutedStyle, "(blank to exit): "))
+
+ reader := bufio.NewReader(os.Stdin)
+ input, err := reader.ReadString('\n')
+ if err != nil && strings.TrimSpace(input) == "" {
+ return "", err
+ }
+
+ choice := strings.TrimSpace(input)
+ if choice == "" {
+ return "", nil
+ }
+
+ if idx, err := strconv.Atoi(choice); err == nil {
+ if idx >= 1 && idx <= len(options) {
+ return options[idx-1].value, nil
+ }
+ return "", fmt.Errorf("invalid selection %q", choice)
+ }
+
+ for _, option := range options {
+ if choice == option.value {
+ return option.value, nil
+ }
+ }
+
+ return "", fmt.Errorf("invalid selection %q", choice)
+}
+
+func promptInput(prompt, defaultValue string) (string, error) {
+ if prompt == "" {
+ // The caller already rendered the prompt.
+ } else if defaultValue != "" {
+ fmt.Printf("%s %s ", prompt, cli.StyleStdout(cli.MutedStyle, "["+defaultValue+"]"))
+ } else {
+ fmt.Print(prompt + " ")
+ }
+
+ reader := bufio.NewReader(os.Stdin)
+ input, err := reader.ReadString('\n')
+ if err != nil && strings.TrimSpace(input) == "" {
+ return "", err
+ }
+
+ value := strings.TrimSpace(input)
+ if value == "" {
+ return defaultValue, nil
+ }
+ return value, nil
+}
diff --git a/cmd/pinchtab/root.go b/cmd/pinchtab/root.go
index d5973625..6b4842ec 100644
--- a/cmd/pinchtab/root.go
+++ b/cmd/pinchtab/root.go
@@ -4,7 +4,9 @@ import (
"fmt"
"os"
+ "github.com/pinchtab/pinchtab/internal/cli"
"github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/server"
"github.com/spf13/cobra"
)
@@ -12,16 +14,70 @@ var version = "dev"
var rootCmd = &cobra.Command{
Use: "pinchtab",
- Short: "PinchTab - Browser for AI agents",
+ Short: "PinchTab - Browser control for AI agents",
Long: `PinchTab provides a lightweight, API-driven way for AI agents to control
browsers, manage tabs, and perform interactive tasks.`,
+ Example: ` pinchtab server
+ pinchtab nav https://pinchtab.com`,
Run: func(cmd *cobra.Command, args []string) {
- // Default action: start the server
cfg := config.Load()
- runDashboard(cfg)
+
+ if isInteractiveTerminal() {
+ cli.PrintStartupBanner(cfg, cli.StartupBannerOptions{
+ Mode: "menu",
+ ListenStatus: menuListenStatus(cfg),
+ })
+
+ picked, err := promptSelect("Main Menu", []menuOption{
+ {label: "Start server", value: "server"},
+ {label: "Daemon", value: "daemon"},
+ {label: "Start bridge", value: "bridge"},
+ {label: "Start MCP server", value: "mcp"},
+ {label: "Config", value: "config"},
+ {label: "Security", value: "security"},
+ {label: "Help", value: "help"},
+ {label: "Exit", value: "exit"},
+ })
+
+ if err != nil || picked == "exit" || picked == "" {
+ return
+ }
+
+ switch picked {
+ case "server":
+ server.RunDashboard(cfg, version)
+ case "daemon":
+ handleDaemonCommand(cfg, "")
+ case "bridge":
+ server.RunBridgeServer(cfg)
+ case "mcp":
+ runMCP(cfg)
+ case "config":
+ handleConfigOverview(cfg)
+ case "security":
+ handleSecurityCommand(cfg)
+ case "help":
+ _ = cmd.Help()
+ }
+ return
+ }
+
+ // Fallback for non-interactive: start the server
+ server.RunDashboard(cfg, version)
},
}
+func menuListenStatus(cfg *config.RuntimeConfig) string {
+ dashPort := cfg.Port
+ if dashPort == "" {
+ dashPort = "9870"
+ }
+ if server.CheckPinchTabRunning(dashPort, cfg.Token) {
+ return "running"
+ }
+ return "stopped"
+}
+
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Fprintln(os.Stderr, err)
@@ -32,5 +88,14 @@ func Execute() {
func init() {
rootCmd.Version = version
rootCmd.SetVersionTemplate("pinchtab {{.Version}}\n")
- rootCmd.AddCommand(config.ConfigCmd)
+
+ // Grouping commands
+ primaryGroup := &cobra.Group{ID: "primary", Title: "Primary Commands"}
+ browserGroup := &cobra.Group{ID: "browser", Title: "Browser Control"}
+ mgmtGroup := &cobra.Group{ID: "management", Title: "Profiles and Instances"}
+ configGroup := &cobra.Group{ID: "config", Title: "Configuration & Setup"}
+
+ rootCmd.AddGroup(primaryGroup, browserGroup, mgmtGroup, configGroup)
+
+ cli.SetupUsage(rootCmd)
}
diff --git a/cmd/pinchtab/startup_output.go b/cmd/pinchtab/startup_output.go
deleted file mode 100644
index adb141b9..00000000
--- a/cmd/pinchtab/startup_output.go
+++ /dev/null
@@ -1,165 +0,0 @@
-package main
-
-import (
- "fmt"
- "github.com/pinchtab/pinchtab/internal/cliui"
- "io"
- "os"
- "strings"
-
- "github.com/charmbracelet/lipgloss"
- "github.com/pinchtab/pinchtab/internal/config"
-)
-
-type startupBannerOptions struct {
- Mode string
- ListenAddr string
- PublicURL string
- Strategy string
- Allocation string
- ProfileDir string
-}
-
-func printStartupBanner(cfg *config.RuntimeConfig, opts startupBannerOptions) {
- writeBannerLine(renderStartupLogo(blankIfEmpty(opts.Mode, "server")))
- writeBannerf(" %s %s\n", styleLabel("listen"), styleValue(blankIfEmpty(opts.ListenAddr, cfg.ListenAddr())))
- if opts.PublicURL != "" {
- writeBannerf(" %s %s\n", styleLabel("url"), styleValue(opts.PublicURL))
- }
- strat := blankIfEmpty(opts.Strategy, "manual")
- alloc := blankIfEmpty(opts.Allocation, "none")
- writeBannerf(" %s %s\n", styleLabel("str,plc"), styleValue(fmt.Sprintf("%s,%s", strat, alloc)))
-
- daemonStatus := cliui.StyleStdout(cliui.WarningStyle, "not installed")
- if IsDaemonInstalled() {
- daemonStatus = cliui.StyleStdout(cliui.SuccessStyle, "ok")
- }
- writeBannerf(" %s %s\n", styleLabel("daemon"), daemonStatus)
-
- if opts.ProfileDir != "" {
- writeBannerf(" %s %s\n", styleLabel("profile"), styleValue(opts.ProfileDir))
- }
- printSecuritySummary(os.Stdout, cfg, " ")
- writeBannerLine("")
-}
-
-func printSecuritySummary(w io.Writer, cfg *config.RuntimeConfig, prefix string) {
- posture := assessSecurityPosture(cfg)
- writeSummaryf(w, "\n%s%s %s %s\n", prefix, styleHeading("Security posture"), styleSecurityBar(posture.Level, posture.Bar), styleSecurityLevel(posture.Level))
-
- for _, check := range posture.Checks {
- writeSummaryf(w, "%s %s %s %s\n", prefix, styleMarker(check.Passed), styleCheckLabel(check.Label), styleCheckDetail(check.Passed, check.Detail))
- }
-}
-
-func blankIfEmpty(value, fallback string) string {
- if strings.TrimSpace(value) == "" {
- return fallback
- }
- return value
-}
-
-func renderStartupLogo(mode string) string {
- return styleLogo(startupLogo) + " " + styleMode(mode)
-}
-
-func writeBannerLine(line string) {
- _, _ = fmt.Fprintln(os.Stdout, line)
-}
-
-func writeBannerf(format string, args ...any) {
- _, _ = fmt.Fprintf(os.Stdout, format, args...)
-}
-
-func writeSummaryf(w io.Writer, format string, args ...any) {
- _, _ = fmt.Fprintf(w, format, args...)
-}
-
-func styleHeading(text string) string {
- return applyStyle(text, cliui.HeadingStyle)
-}
-
-func styleCommand(text string) string {
- return applyStyle(text, cliui.CommandStyle)
-}
-
-func styleMuted(text string) string {
- return applyStyle(text, cliui.MutedStyle)
-}
-
-func styleSuccess(text string) string {
- return applyStyle(text, cliui.SuccessStyle)
-}
-
-func styleWarning(text string) string {
- return applyStyle(text, cliui.WarningStyle)
-}
-
-func styleError(text string) string {
- return applyStyle(text, cliui.ErrorStyle)
-}
-
-func styleLogo(text string) string {
- return applyStyle(text, cliui.HeadingStyle)
-}
-
-func styleMode(text string) string {
- return applyStyle(text, cliui.CommandStyle)
-}
-
-func styleLabel(text string) string {
- return applyStyle(fmt.Sprintf("%-8s", text), cliui.MutedStyle)
-}
-
-func styleValue(text string) string {
- return applyStyle(text, cliui.ValueStyle)
-}
-
-func styleCheckLabel(text string) string {
- return applyStyle(fmt.Sprintf("%-20s", text), cliui.MutedStyle)
-}
-
-func styleCheckDetail(passed bool, text string) string {
- if passed {
- return applyStyle(text, cliui.SuccessStyle)
- }
- return applyStyle(text, cliui.WarningStyle)
-}
-
-func styleMarker(passed bool) string {
- if passed {
- return applyStyle("ok", cliui.SuccessStyle)
- }
- return applyStyle("!!", cliui.ErrorStyle)
-}
-
-func styleSecurityLevel(level string) string {
- return applyStyle(level, lipgloss.NewStyle().Foreground(lipgloss.Color(securityLevelColor(level))).Bold(true))
-}
-
-func styleSecurityBar(level, bar string) string {
- return applyStyle(bar, lipgloss.NewStyle().Foreground(lipgloss.Color(securityLevelColor(level))).Bold(true))
-}
-
-func securityLevelColor(level string) string {
- switch level {
- case "LOCKED":
- return string(cliui.ColorSuccess)
- case "GUARDED":
- return string(cliui.ColorWarning)
- case "ELEVATED":
- return string(cliui.ColorDanger)
- default:
- return string(cliui.ColorDanger)
- }
-}
-
-func applyStyle(text string, style lipgloss.Style) string {
- return cliui.RenderStdout(style, text)
-}
-
-const startupLogo = ` ____ _ _ _____ _
- | _ \(_)_ __ ___| |__ |_ _|_ _| |__
- | |_) | | '_ \ / __| '_ \ | |/ _ | '_ \
- | __/| | | | | (__| | | | | | (_| | |_) |
- |_| |_|_| |_|\___|_| |_| |_|\__,_|_.__/`
diff --git a/cmd/pinchtab/startup_output_test.go b/cmd/pinchtab/startup_output_test.go
deleted file mode 100644
index f53006e3..00000000
--- a/cmd/pinchtab/startup_output_test.go
+++ /dev/null
@@ -1,25 +0,0 @@
-package main
-
-import (
- "github.com/pinchtab/pinchtab/internal/cliui"
- "testing"
-)
-
-func TestSecurityLevelColor(t *testing.T) {
- tests := []struct {
- level string
- want string
- }{
- {level: "LOCKED", want: string(cliui.ColorSuccess)},
- {level: "GUARDED", want: string(cliui.ColorWarning)},
- {level: "ELEVATED", want: string(cliui.ColorDanger)},
- {level: "EXPOSED", want: string(cliui.ColorDanger)},
- {level: "UNKNOWN", want: string(cliui.ColorDanger)},
- }
-
- for _, tt := range tests {
- if got := securityLevelColor(tt.level); got != tt.want {
- t.Fatalf("securityLevelColor(%q) = %q, want %q", tt.level, got, tt.want)
- }
- }
-}
diff --git a/docs/guides/daemon.md b/docs/guides/daemon.md
index f4d4766c..a4368fc6 100644
--- a/docs/guides/daemon.md
+++ b/docs/guides/daemon.md
@@ -6,13 +6,13 @@ PinchTab can run as a user-level background service (daemon) on both macOS (`lau
## Quick Start
-The easiest way to set up the daemon is through the interactive onboarding:
+The normal entrypoints are:
```bash
-pinchtab onboard --install-daemon
+pinchtab
```
-If you already have PinchTab configured, you can manage the service directly:
+Then choose `Daemon` from the menu, or manage the service directly:
```bash
pinchtab daemon
@@ -45,6 +45,15 @@ The `pinchtab daemon` command provides a comprehensive overview of the service:
If the automated commands fail due to permission issues or system restrictions, PinchTab provides manual instructions tailored to your OS.
+PinchTab now fails fast before install when the current session cannot manage a user service.
+
+Typical cases:
+
+- Linux shell without a working `systemctl --user` session
+- macOS shell without an active GUI `launchd` domain
+
+In those cases, use the manual steps below or run `pinchtab server` in the foreground instead.
+
### macOS (launchd)
Service file: `~/Library/LaunchAgents/com.pinchtab.pinchtab.plist`
diff --git a/docs/reference/cli.md b/docs/reference/cli.md
new file mode 100644
index 00000000..c9a5c29f
--- /dev/null
+++ b/docs/reference/cli.md
@@ -0,0 +1,161 @@
+# CLI Overview
+
+`pinchtab` has two normal usage styles:
+
+- interactive menu mode
+- direct command mode
+
+Use menu mode when you want a guided local control surface.
+Use direct commands when you want a faster shell workflow or want to script PinchTab.
+
+## Interactive Menu
+
+When you run `pinchtab` with no subcommand in an interactive terminal, it shows the startup banner and main menu.
+
+Typical flow:
+
+```text
+listen running 127.0.0.1:9867
+str,plc simple,fcfs
+daemon ok
+security [■■■■■■■■■■] LOCKED
+
+Main Menu
+ 1. Start server
+ 2. Daemon
+ 3. Start bridge
+ 4. Start MCP server
+ 5. Config
+ 6. Security
+ 7. Help
+ 8. Exit
+```
+
+What each entry does:
+
+- `Start server` starts the full PinchTab server
+- `Daemon` shows background service status and actions
+- `Start bridge` starts the single-instance bridge runtime
+- `Start MCP server` starts the stdio MCP server
+- `Config` opens the interactive config screen
+- `Security` opens the interactive security screen
+- `Help` shows the command help tree
+
+## Direct Commands
+
+You can always bypass the menu and call commands directly.
+
+Common examples:
+
+```bash
+pinchtab server
+pinchtab daemon
+pinchtab config
+pinchtab security
+pinchtab nav https://example.com
+pinchtab snap -i -c
+pinchtab click e5
+pinchtab text
+```
+
+Direct commands are the better fit when:
+
+- you are scripting PinchtTab
+- you want repeatable shell history
+- you are calling PinchtTab from another tool
+- you already know which command you want
+
+## Core Local Commands
+
+These are the main local-control commands surfaced in the menu:
+
+| Command | Purpose |
+| --- | --- |
+| `pinchtab` | Open the interactive menu in a terminal, or start the server in non-interactive use |
+| `pinchtab server` | Start the full server and dashboard |
+| `pinchtab daemon` | Show daemon status and manage the background service |
+| `pinchtab config` | Open the interactive config overview/editor |
+| `pinchtab security` | Review or change the current security posture |
+| `pinchtab bridge` | Start the single-instance bridge runtime |
+| `pinchtab mcp` | Start the stdio MCP server |
+
+## Browser Shortcuts
+
+The most common browser control shortcuts are top-level commands:
+
+| Command | Purpose |
+| --- | --- |
+| `pinchtab nav <url>` | Navigate to a URL |
+| `pinchtab quick <url>` | Navigate and analyze the page |
+| `pinchtab snap` | Get an accessibility snapshot |
+| `pinchtab click <ref>` | Click an element ref |
+| `pinchtab type <ref> <text>` | Type into an element |
+| `pinchtab fill <ref|selector> <text>` | Fill an input directly |
+| `pinchtab text` | Extract page text |
+| `pinchtab screenshot` | Capture a screenshot |
+| `pinchtab pdf` | Export the current page as PDF |
+| `pinchtab health` | Check server health |
+
+## Config From The CLI
+
+`pinchtab config` now acts as the main interactive config screen.
+
+It shows:
+
+- instance strategy
+- allocation policy
+- default stealth level
+- default tab eviction policy
+- config file path
+- dashboard URL when the server is running
+- the masked server token
+- a `Copy token` action for clipboard/manual copy
+
+For exact config commands and schema details, see [Config](./config.md).
+
+## Security From The CLI
+
+`pinchtab security` is the main interactive security screen.
+
+Use it to:
+
+- review the current posture
+- inspect warnings
+- edit individual security controls
+- apply `security up`
+- apply `security down`
+
+The direct subcommands also exist:
+
+```bash
+pinchtab security up
+pinchtab security down
+```
+
+For broader security guidance, see [Security Guide](../guides/security.md).
+
+## Daemon From The CLI
+
+`pinchtab daemon` shows status, recent logs, and available actions.
+
+The command is supported on:
+
+- macOS via `launchd`
+- Linux via user `systemd`
+
+It will fail fast when the current environment cannot manage a user service, for example:
+
+- Linux shells without a working `systemctl --user` session
+- macOS sessions without an active GUI `launchd` domain
+
+For operational details, see [Background Service (Daemon)](../guides/daemon.md).
+
+## Full Command Tree
+
+Use the built-in help for the current command tree:
+
+```bash
+pinchtab --help
+```
+
+For per-command reference pages, start at [Reference Index](./index.md).
diff --git a/docs/reference/config.md b/docs/reference/config.md
index dab47aff..4cac7d7e 100644
--- a/docs/reference/config.md
+++ b/docs/reference/config.md
@@ -8,6 +8,28 @@ For security posture, token usage, sensitive endpoint policy, and IDPI guidance,
## Commands
+### `pinchtab config`
+
+Opens the interactive config overview/editor.
+
+It currently exposes these high-signal settings directly:
+
+- `multiInstance.strategy`
+- `multiInstance.allocationPolicy`
+- `instanceDefaults.stealthLevel`
+- `instanceDefaults.tabEvictionPolicy`
+
+It also shows:
+
+- the active config file path
+- the dashboard URL when the server is running
+- the masked server token
+- a `Copy token` action for clipboard/manual copy
+
+```bash
+pinchtab config
+```
+
### `pinchtab config init`
Creates a default config file at the standard user config location.
@@ -96,6 +118,8 @@ The currently supported operational env vars are:
Everything else should be configured in `config.json`.
+For the common local workflow, prefer the interactive `pinchtab config` screen for everyday changes and use `get`, `set`, or `patch` when you need an exact scripted edit.
+
## Config File Location
Default location by OS:
diff --git a/docs/reference/index.md b/docs/reference/index.md
index 31f81d7d..5f5af9f3 100644
--- a/docs/reference/index.md
+++ b/docs/reference/index.md
@@ -4,6 +4,7 @@ Reference pages for the current PinchTab CLI and closely related command-facing
Note: this index is generated and should be checked against the code when commands change.
+- [CLI Overview](./cli.md)
- [Click](./click.md)
- [Config](./config.md)
- [Eval](./eval.md)
diff --git a/go.mod b/go.mod
index 297f8885..ee947cf4 100644
--- a/go.mod
+++ b/go.mod
@@ -3,8 +3,6 @@ module github.com/pinchtab/pinchtab
go 1.25.0
require (
- github.com/c-bata/go-prompt v0.2.6
- github.com/charmbracelet/huh v1.0.0
github.com/charmbracelet/lipgloss v1.1.0
github.com/chromedp/cdproto v0.0.0-20250803210736-d308e07a266d
github.com/chromedp/chromedp v0.14.2
@@ -18,22 +16,15 @@ require (
)
require (
- github.com/atotto/clipboard v0.1.4 // indirect
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
github.com/bahlo/generic-list-go v0.2.0 // indirect
github.com/buger/jsonparser v1.1.1 // indirect
- github.com/catppuccin/go v0.3.0 // indirect
- github.com/charmbracelet/bubbles v0.21.1-0.20250623103423-23b8fd6302d7 // indirect
- github.com/charmbracelet/bubbletea v1.3.6 // indirect
github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect
github.com/charmbracelet/x/ansi v0.9.3 // indirect
github.com/charmbracelet/x/cellbuf v0.0.13 // indirect
- github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 // indirect
github.com/charmbracelet/x/term v0.2.1 // indirect
github.com/chromedp/sysutil v1.1.0 // indirect
- github.com/dustin/go-humanize v1.0.1 // indirect
github.com/ebitengine/purego v0.10.0 // indirect
- github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2 // indirect
github.com/go-ole/go-ole v1.2.6 // indirect
github.com/gobwas/httphead v0.1.0 // indirect
@@ -45,16 +36,9 @@ require (
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect
github.com/mailru/easyjson v0.7.7 // indirect
- github.com/mattn/go-colorable v0.1.7 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
- github.com/mattn/go-localereader v0.0.1 // indirect
github.com/mattn/go-runewidth v0.0.16 // indirect
- github.com/mattn/go-tty v0.0.3 // indirect
- github.com/mitchellh/hashstructure/v2 v2.0.2 // indirect
- github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect
- github.com/muesli/cancelreader v0.2.2 // indirect
github.com/muesli/termenv v0.16.0 // indirect
- github.com/pkg/term v1.2.0-beta.2 // indirect
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/spf13/cast v1.7.1 // indirect
@@ -65,7 +49,5 @@ require (
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
- golang.org/x/sync v0.18.0 // indirect
golang.org/x/sys v0.41.0 // indirect
- golang.org/x/text v0.31.0 // indirect
)
diff --git a/go.sum b/go.sum
index 12af3a29..9bedc283 100644
--- a/go.sum
+++ b/go.sum
@@ -1,47 +1,19 @@
-github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ=
-github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE=
-github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=
-github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=
github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
-github.com/aymanbagabas/go-udiff v0.3.1 h1:LV+qyBQ2pqe0u42ZsUEtPiCaUoqgA9gYRDs3vj1nolY=
-github.com/aymanbagabas/go-udiff v0.3.1/go.mod h1:G0fsKmG+P6ylD0r6N/KgQD/nWzgfnl8ZBcNLgcbrw8E=
github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
github.com/buger/jsonparser v1.1.1 h1:2PnMjfWD7wBILjqQbt530v576A/cAbQvEW9gGIpYMUs=
github.com/buger/jsonparser v1.1.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
-github.com/c-bata/go-prompt v0.2.6 h1:POP+nrHE+DfLYx370bedwNhsqmpCUynWPxuHi0C5vZI=
-github.com/c-bata/go-prompt v0.2.6/go.mod h1:/LMAke8wD2FsNu9EXNdHxNLbd9MedkPnCdfpU9wwHfY=
-github.com/catppuccin/go v0.3.0 h1:d+0/YicIq+hSTo5oPuRi5kOpqkVA5tAsU6dNhvRu+aY=
-github.com/catppuccin/go v0.3.0/go.mod h1:8IHJuMGaUUjQM82qBrGNBv7LFq6JI3NnQCF6MOlZjpc=
-github.com/charmbracelet/bubbles v0.21.1-0.20250623103423-23b8fd6302d7 h1:JFgG/xnwFfbezlUnFMJy0nusZvytYysV4SCS2cYbvws=
-github.com/charmbracelet/bubbles v0.21.1-0.20250623103423-23b8fd6302d7/go.mod h1:ISC1gtLcVilLOf23wvTfoQuYbW2q0JevFxPfUzZ9Ybw=
-github.com/charmbracelet/bubbletea v1.3.6 h1:VkHIxPJQeDt0aFJIsVxw8BQdh/F/L2KKZGsK6et5taU=
-github.com/charmbracelet/bubbletea v1.3.6/go.mod h1:oQD9VCRQFF8KplacJLo28/jofOI2ToOfGYeFgBBxHOc=
github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs=
github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk=
-github.com/charmbracelet/huh v1.0.0 h1:wOnedH8G4qzJbmhftTqrpppyqHakl/zbbNdXIWJyIxw=
-github.com/charmbracelet/huh v1.0.0/go.mod h1:5YVc+SlZ1IhQALxRPpkGwwEKftN/+OlJlnJYlDRFqN4=
github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY=
github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30=
github.com/charmbracelet/x/ansi v0.9.3 h1:BXt5DHS/MKF+LjuK4huWrC6NCvHtexww7dMayh6GXd0=
github.com/charmbracelet/x/ansi v0.9.3/go.mod h1:3RQDQ6lDnROptfpWuUVIUG64bD2g2BgntdxH0Ya5TeE=
github.com/charmbracelet/x/cellbuf v0.0.13 h1:/KBBKHuVRbq1lYx5BzEHBAFBP8VcQzJejZ/IA3iR28k=
github.com/charmbracelet/x/cellbuf v0.0.13/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs=
-github.com/charmbracelet/x/conpty v0.1.0 h1:4zc8KaIcbiL4mghEON8D72agYtSeIgq8FSThSPQIb+U=
-github.com/charmbracelet/x/conpty v0.1.0/go.mod h1:rMFsDJoDwVmiYM10aD4bH2XiRgwI7NYJtQgl5yskjEQ=
-github.com/charmbracelet/x/errors v0.0.0-20240508181413-e8d8b6e2de86 h1:JSt3B+U9iqk37QUU2Rvb6DSBYRLtWqFqfxf8l5hOZUA=
-github.com/charmbracelet/x/errors v0.0.0-20240508181413-e8d8b6e2de86/go.mod h1:2P0UgXMEa6TsToMSuFqKFQR+fZTO9CNGUNokkPatT/0=
-github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91 h1:payRxjMjKgx2PaCWLZ4p3ro9y97+TVLZNaRZgJwSVDQ=
-github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91/go.mod h1:wDlXFlCrmJ8J+swcL/MnGUuYnqgQdW9rhSD61oNMb6U=
-github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 h1:qko3AQ4gK1MTS/de7F5hPGx6/k1u0w4TeYmBFwzYVP4=
-github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0/go.mod h1:pBhA0ybfXv6hDjQUZ7hk1lVxBiUbupdw5R31yPUViVQ=
github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ=
github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg=
-github.com/charmbracelet/x/termios v0.1.1 h1:o3Q2bT8eqzGnGPOYheoYS8eEleT5ZVNYNy8JawjaNZY=
-github.com/charmbracelet/x/termios v0.1.1/go.mod h1:rB7fnv1TgOPOyyKRJ9o+AsTU/vK5WHJ2ivHeut/Pcwo=
-github.com/charmbracelet/x/xpty v0.1.2 h1:Pqmu4TEJ8KeA9uSkISKMU3f+C1F6OGBn8ABuGlqCbtI=
-github.com/charmbracelet/x/xpty v0.1.2/go.mod h1:XK2Z0id5rtLWcpeNiMYBccNNBrP2IJnzHI0Lq13Xzq4=
github.com/chromedp/cdproto v0.0.0-20250803210736-d308e07a266d h1:ZtA1sedVbEW7EW80Iz2GR3Ye6PwbJAJXjv7D74xG6HU=
github.com/chromedp/cdproto v0.0.0-20250803210736-d308e07a266d/go.mod h1:NItd7aLkcfOA/dcMXvl8p1u+lQqioRMq/SqDp71Pb/k=
github.com/chromedp/chromedp v0.14.2 h1:r3b/WtwM50RsBZHMUm9fsNhhzRStTHrKdr2zmwbZSzM=
@@ -49,16 +21,10 @@ github.com/chromedp/chromedp v0.14.2/go.mod h1:rHzAv60xDE7VNy/MYtTUrYreSc0ujt2O1
github.com/chromedp/sysutil v1.1.0 h1:PUFNv5EcprjqXZD9nJb9b/c9ibAbxiYo4exNWZyipwM=
github.com/chromedp/sysutil v1.1.0/go.mod h1:WiThHUdltqCNKGc4gaU50XgYjwjYIhKWoHGPTUfWTJ8=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
-github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=
-github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
-github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
-github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/ebitengine/purego v0.10.0 h1:QIw4xfpWT6GWTzaW5XEKy3HXoqrJGx1ijYHzTF0/ISU=
github.com/ebitengine/purego v0.10.0/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=
-github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4=
-github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2 h1:iizUGZ9pEquQS5jTGkh4AqeeHCMbfbjeb0zMt0aEFzs=
@@ -101,36 +67,16 @@ github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0
github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
github.com/mark3labs/mcp-go v0.45.0 h1:s0S8qR/9fWaQ3pHxz7pm1uQ0DrswoSnRIxKIjbiQtkc=
github.com/mark3labs/mcp-go v0.45.0/go.mod h1:YnJfOL382MIWDx1kMY+2zsRHU/q78dBg9aFb8W6Thdw=
-github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
-github.com/mattn/go-colorable v0.1.7 h1:bQGKb3vps/j0E9GfJQ03JyhRuxsvdAanXlT9BTw3mdw=
-github.com/mattn/go-colorable v0.1.7/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
-github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
-github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84=
-github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
-github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=
-github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=
-github.com/mattn/go-runewidth v0.0.6/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
-github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
-github.com/mattn/go-tty v0.0.3 h1:5OfyWorkyO7xP52Mq7tB36ajHDG5OHrmBGIS/DtakQI=
-github.com/mattn/go-tty v0.0.3/go.mod h1:ihxohKRERHTVzN+aSVRwACLCeqIoZAWpoICkkvrWyR0=
-github.com/mitchellh/hashstructure/v2 v2.0.2 h1:vGKWl0YJqUNxE8d+h8f6NJLcCJrgbhC4NcD46KavDd4=
-github.com/mitchellh/hashstructure/v2 v2.0.2/go.mod h1:MG3aRVU/N29oo/V/IhBX8GR/zz4kQkprJgF2EVszyDE=
-github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI=
-github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo=
-github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
-github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc=
github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=
github.com/onsi/gomega v1.38.2 h1:eZCjf2xjZAqe+LeWvKb5weQ+NcPwX84kqJ0cZNxok2A=
github.com/onsi/gomega v1.38.2/go.mod h1:W2MJcYxRGV63b418Ai34Ud0hEdTVXq9NW9+Sx6uXf3k=
github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde h1:x0TT0RDC7UhAVbbWWBzr41ElhJx5tXPWkIHA2HWPRuw=
github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde/go.mod h1:nZgzbfBr3hhjoZnS66nKrHmduYNpc34ny7RK4z5/HM0=
-github.com/pkg/term v1.2.0-beta.2 h1:L3y/h2jkuBVFdWiJvNfYfKmzcCnILw7mJWm2JQuMppw=
-github.com/pkg/term v1.2.0-beta.2/go.mod h1:E25nymQcrSllhX42Ok8MRm1+hyBdHY0dCeiKZ9jpNGw=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU=
@@ -165,26 +111,15 @@ github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
-golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI=
-golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo=
+golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561 h1:MDc5xs78ZrZr3HMQugiXOAkSZtfTpbJLDr/lwfgO53E=
+golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561/go.mod h1:cyybsKvd6eL0RnXn6p/Grxp8F5bW7iYuBgsNCOHpMYE=
golang.org/x/net v0.0.0-20211216030914-fe4d6282115f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
-golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
-golang.org/x/sync v0.18.0 h1:kr88TuHDroi+UVf+0hZnirlk8o8T+4MrK6mr60WkH/I=
-golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
-golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
-golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
-golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
-golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
-golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
-golang.org/x/sys v0.0.0-20200909081042-eff7692f9009/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
-golang.org/x/sys v0.0.0-20200918174421-af09f7315aff/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
-golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
diff --git a/internal/bridge/init.go b/internal/bridge/init.go
index 40be3cde..d9e875c5 100644
--- a/internal/bridge/init.go
+++ b/internal/bridge/init.go
@@ -142,9 +142,12 @@ func setupAllocator(cfg *config.RuntimeConfig) (context.Context, context.CancelF
opts = append(opts,
chromedp.Flag("disable-automation", ""),
chromedp.Flag("disable-blink-features", "AutomationControlled"),
+ chromedp.Flag("disable-session-crashed-bubble", ""),
chromedp.Flag("disable-dev-shm-usage", ""),
+ chromedp.Flag("hide-crash-restore-bubble", ""),
chromedp.Flag("no-first-run", ""),
chromedp.Flag("no-default-browser-check", ""),
+ chromedp.Flag("noerrdialogs", ""),
)
// Extension loading
@@ -459,9 +462,11 @@ func buildChromeArgs(cfg *config.RuntimeConfig, port int) []string {
"--disable-background-timer-throttling",
"--disable-backgrounding-occluded-windows",
"--disable-breakpad",
+ "--disable-session-crashed-bubble",
"--disable-client-side-phishing-detection",
"--disable-default-apps",
"--disable-dev-shm-usage",
+ "--hide-crash-restore-bubble",
"--disable-hang-monitor",
"--disable-ipc-flooding-protection",
"--disable-popup-blocking",
@@ -472,6 +477,7 @@ func buildChromeArgs(cfg *config.RuntimeConfig, port int) []string {
"--metrics-recording-only",
"--no-first-run",
"--no-default-browser-check",
+ "--noerrdialogs",
"--safebrowsing-disable-auto-update",
"--password-store=basic",
"--use-mock-keychain",
diff --git a/internal/bridge/init_test.go b/internal/bridge/init_test.go
index 357154df..119302b6 100644
--- a/internal/bridge/init_test.go
+++ b/internal/bridge/init_test.go
@@ -1,27 +1,22 @@
package bridge
import (
- "runtime"
+ "slices"
"testing"
-)
-
-func TestFindChromeBinary_ARM64Prioritization(t *testing.T) {
- // Verifies function doesn't panic across architectures (ARM64 vs x86_64)
- // Chrome may not be installed in CI, so empty result is valid
- result := findChromeBinary()
- if result != "" {
- t.Logf("Found Chrome binary: %s (arch: %s)", result, runtime.GOARCH)
- } else {
- t.Logf("No Chrome binary found (expected in CI, arch: %s)", runtime.GOARCH)
- }
-}
+ "github.com/pinchtab/pinchtab/internal/config"
+)
-func TestFindChromeBinary_NoPathTraversal(t *testing.T) {
- // Ensures only absolute paths are returned (security check)
- result := findChromeBinary()
+func TestBuildChromeArgsSuppressesCrashDialogs(t *testing.T) {
+ args := buildChromeArgs(&config.RuntimeConfig{}, 9222)
- if result != "" && result[0] != '/' && result[1] != ':' {
- t.Errorf("findChromeBinary returned non-absolute path: %s", result)
+ for _, want := range []string{
+ "--disable-session-crashed-bubble",
+ "--hide-crash-restore-bubble",
+ "--noerrdialogs",
+ } {
+ if !slices.Contains(args, want) {
+ t.Fatalf("missing chrome arg %q in %v", want, args)
+ }
}
}
diff --git a/internal/browsercli/actions_evaluate.go b/internal/browsercli/actions_evaluate.go
deleted file mode 100644
index 443cffa9..00000000
--- a/internal/browsercli/actions_evaluate.go
+++ /dev/null
@@ -1,17 +0,0 @@
-package browsercli
-
-import (
- "github.com/pinchtab/pinchtab/internal/cliui"
- "net/http"
- "strings"
-)
-
-func Evaluate(client *http.Client, base, token string, args []string) {
- if len(args) < 1 {
- cliui.Fatal("Usage: pinchtab eval <expression>")
- }
- expr := strings.Join(args, " ")
- DoPost(client, base, token, "/evaluate", map[string]any{
- "expression": expr,
- })
-}
diff --git a/internal/browsercli/actions_quick.go b/internal/browsercli/actions_quick.go
deleted file mode 100644
index 9d0384d7..00000000
--- a/internal/browsercli/actions_quick.go
+++ /dev/null
@@ -1,49 +0,0 @@
-package browsercli
-
-import (
- "fmt"
- "github.com/pinchtab/pinchtab/internal/cliui"
- "net/http"
- "net/url"
- "time"
-)
-
-func Quick(client *http.Client, base, token string, args []string) {
- if len(args) < 1 {
- cliui.Fatal("Usage: pinchtab quick <url>")
- }
-
- fmt.Println(cliui.StyleStdout(cliui.HeadingStyle, fmt.Sprintf("Navigating to %s...", args[0])))
-
- // Navigate
- navBody := map[string]any{"url": args[0]}
- navResult := DoPost(client, base, token, "/navigate", navBody)
-
- // Small delay for page to stabilize
- time.Sleep(1 * time.Second)
-
- fmt.Println()
- fmt.Println(cliui.StyleStdout(cliui.HeadingStyle, "Page structure"))
-
- // Snapshot with interactive filter
- snapParams := url.Values{}
- snapParams.Set("filter", "interactive")
- snapParams.Set("compact", "true")
- DoGet(client, base, token, "/snapshot", snapParams)
-
- // Extract info from navigation result
- if title, ok := navResult["title"].(string); ok {
- fmt.Println()
- fmt.Printf("%s %s\n", cliui.StyleStdout(cliui.MutedStyle, "Title:"), cliui.StyleStdout(cliui.ValueStyle, title))
- }
- if urlStr, ok := navResult["url"].(string); ok {
- fmt.Printf("%s %s\n", cliui.StyleStdout(cliui.MutedStyle, "URL:"), cliui.StyleStdout(cliui.ValueStyle, urlStr))
- }
-
- fmt.Println()
- fmt.Println(cliui.StyleStdout(cliui.HeadingStyle, "Quick actions"))
- fmt.Printf(" %s %s\n", cliui.StyleStdout(cliui.CommandStyle, "pinchtab click <ref>"), cliui.StyleStdout(cliui.MutedStyle, "# Click an element (use refs from above)"))
- fmt.Printf(" %s %s\n", cliui.StyleStdout(cliui.CommandStyle, "pinchtab type <ref> <text>"), cliui.StyleStdout(cliui.MutedStyle, "# Type into input field"))
- fmt.Printf(" %s %s\n", cliui.StyleStdout(cliui.CommandStyle, "pinchtab screenshot"), cliui.StyleStdout(cliui.MutedStyle, "# Take a screenshot"))
- fmt.Printf(" %s %s\n", cliui.StyleStdout(cliui.CommandStyle, "pinchtab pdf --tab <id> -o output.pdf"), cliui.StyleStdout(cliui.MutedStyle, "# Save tab as PDF"))
-}
diff --git a/internal/browsercli/diagnostics.go b/internal/browsercli/diagnostics.go
deleted file mode 100644
index 0a4bb352..00000000
--- a/internal/browsercli/diagnostics.go
+++ /dev/null
@@ -1,130 +0,0 @@
-package browsercli
-
-import (
- "fmt"
- "github.com/pinchtab/pinchtab/internal/cliui"
- "io"
- "net/http"
- "os"
- "strings"
-)
-
-// CheckServerAndGuide checks if pinchtab server is running and provides guidance
-func CheckServerAndGuide(client *http.Client, base, token string) bool {
- req, _ := http.NewRequest("GET", base+"/health", nil)
- if token != "" {
- req.Header.Set("Authorization", "Bearer "+token)
- }
-
- resp, err := client.Do(req)
- if err != nil {
- if strings.Contains(err.Error(), "connection refused") || strings.Contains(err.Error(), "dial tcp") {
- fmt.Fprintln(os.Stderr, cliui.StyleStderr(cliui.ErrorStyle, fmt.Sprintf("Pinchtab server is not running on %s", base)))
- fmt.Fprintln(os.Stderr)
- fmt.Fprintln(os.Stderr, cliui.StyleStderr(cliui.HeadingStyle, "To start the server"))
- fmt.Fprintf(os.Stderr, " %s %s\n", cliui.StyleStderr(cliui.CommandStyle, "pinchtab"), cliui.StyleStderr(cliui.MutedStyle, "# Run in foreground (recommended for beginners)"))
- fmt.Fprintf(os.Stderr, " %s %s\n", cliui.StyleStderr(cliui.CommandStyle, "pinchtab &"), cliui.StyleStderr(cliui.MutedStyle, "# Run in background"))
- fmt.Fprintf(os.Stderr, " %s %s\n", cliui.StyleStderr(cliui.CommandStyle, "PINCHTAB_PORT=9868 pinchtab"), cliui.StyleStderr(cliui.MutedStyle, "# Use different port"))
- fmt.Fprintln(os.Stderr)
- fmt.Fprintln(os.Stderr, cliui.StyleStderr(cliui.HeadingStyle, "Then try your command again"))
- fmt.Fprintf(os.Stderr, " %s\n", cliui.StyleStderr(cliui.CommandStyle, strings.Join(os.Args, " ")))
- fmt.Fprintln(os.Stderr)
- fmt.Fprintf(os.Stderr, "%s %s\n", cliui.StyleStderr(cliui.MutedStyle, "Learn more:"), cliui.StyleStderr(cliui.CommandStyle, "https://github.com/pinchtab/pinchtab#quick-start"))
- return false
- }
- // Other connection errors
- fmt.Fprintln(os.Stderr, cliui.StyleStderr(cliui.ErrorStyle, fmt.Sprintf("Cannot connect to Pinchtab server: %v", err)))
- return false
- }
- defer func() { _ = resp.Body.Close() }()
-
- if resp.StatusCode == 401 {
- fmt.Fprintln(os.Stderr, cliui.StyleStderr(cliui.ErrorStyle, "Authentication required. Set PINCHTAB_TOKEN."))
- return false
- }
-
- if resp.StatusCode >= 400 {
- body, _ := io.ReadAll(resp.Body)
- fmt.Fprintln(os.Stderr, cliui.StyleStderr(cliui.ErrorStyle, fmt.Sprintf("Server error %d: %s", resp.StatusCode, string(body))))
- return false
- }
-
- return true
-}
-
-// SuggestNextAction provides helpful suggestions based on the current command and state
-func SuggestNextAction(cmd string, result map[string]any) {
- switch cmd {
- case "nav", "navigate":
- fmt.Fprintln(os.Stderr)
- fmt.Fprintln(os.Stderr, cliui.StyleStderr(cliui.HeadingStyle, "Next steps"))
- fmt.Fprintf(os.Stderr, " %s %s\n", cliui.StyleStderr(cliui.CommandStyle, "pinchtab snap"), cliui.StyleStderr(cliui.MutedStyle, "# See page structure"))
- fmt.Fprintf(os.Stderr, " %s %s\n", cliui.StyleStderr(cliui.CommandStyle, "pinchtab screenshot"), cliui.StyleStderr(cliui.MutedStyle, "# Capture visual"))
- fmt.Fprintf(os.Stderr, " %s %s\n", cliui.StyleStderr(cliui.CommandStyle, "pinchtab click <ref>"), cliui.StyleStderr(cliui.MutedStyle, "# Click an element"))
- fmt.Fprintf(os.Stderr, " %s %s\n", cliui.StyleStderr(cliui.CommandStyle, "pinchtab pdf --tab <id> -o output.pdf"), cliui.StyleStderr(cliui.MutedStyle, "# Save tab as PDF"))
-
- case "snap", "snapshot":
- refs := extractRefs(result)
- if len(refs) > 0 {
- fmt.Fprintln(os.Stderr)
- fmt.Fprintln(os.Stderr, cliui.StyleStderr(cliui.HeadingStyle, fmt.Sprintf("Found %d interactive elements", len(refs))))
- for i, ref := range refs[:min(3, len(refs))] {
- fmt.Fprintf(os.Stderr, " %s %s\n", cliui.StyleStderr(cliui.CommandStyle, fmt.Sprintf("pinchtab click %s", ref.id)), cliui.StyleStderr(cliui.MutedStyle, "# "+ref.desc))
- if i >= 2 {
- break
- }
- }
- if len(refs) > 3 {
- fmt.Fprintf(os.Stderr, " %s\n", cliui.StyleStderr(cliui.MutedStyle, fmt.Sprintf("... and %d more", len(refs)-3)))
- }
- }
-
- case "click", "type", "fill":
- fmt.Fprintln(os.Stderr)
- fmt.Fprintln(os.Stderr, cliui.StyleStderr(cliui.HeadingStyle, "Action completed"))
- fmt.Fprintf(os.Stderr, " %s %s\n", cliui.StyleStderr(cliui.CommandStyle, "pinchtab snap"), cliui.StyleStderr(cliui.MutedStyle, "# See updated page"))
- fmt.Fprintf(os.Stderr, " %s %s\n", cliui.StyleStderr(cliui.CommandStyle, "pinchtab screenshot"), cliui.StyleStderr(cliui.MutedStyle, "# Visual confirmation"))
- }
-}
-
-type refInfo struct {
- id string
- desc string
-}
-
-func extractRefs(data map[string]any) []refInfo {
- var refs []refInfo
-
- // Handle different snapshot formats
- if elements, ok := data["elements"].([]any); ok {
- for _, elem := range elements {
- if m, ok := elem.(map[string]any); ok {
- if ref, ok := m["ref"].(string); ok && ref != "" {
- desc := ""
- if role, ok := m["role"].(string); ok {
- desc = role
- }
- if name, ok := m["name"].(string); ok && name != "" {
- desc += ": " + name
- }
- // Only include interactive elements
- if role, ok := m["role"].(string); ok {
- if role == "button" || role == "link" || role == "textbox" ||
- role == "checkbox" || role == "radio" || role == "combobox" {
- refs = append(refs, refInfo{id: ref, desc: desc})
- }
- }
- }
- }
- }
- }
-
- return refs
-}
-
-func min(a, b int) int {
- if a < b {
- return a
- }
- return b
-}
diff --git a/internal/browsercli/actions_element.go b/internal/cli/actions/actions_element.go
similarity index 69%
rename from internal/browsercli/actions_element.go
rename to internal/cli/actions/actions_element.go
index b462a2e0..f692e717 100644
--- a/internal/browsercli/actions_element.go
+++ b/internal/cli/actions/actions_element.go
@@ -1,7 +1,8 @@
-package browsercli
+package actions
import (
- "github.com/pinchtab/pinchtab/internal/cliui"
+ "github.com/pinchtab/pinchtab/internal/cli"
+ "github.com/pinchtab/pinchtab/internal/cli/apiclient"
"net/http"
"strconv"
"strings"
@@ -34,17 +35,17 @@ func Action(client *http.Client, base, token, kind string, args []string) {
} else if refArg != "" {
body["ref"] = refArg
} else {
- cliui.Fatal("Usage: pinchtab %s <ref> [--css <selector>] [--wait-nav]", kind)
+ cli.Fatal("Usage: pinchtab %s <ref> [--css <selector>] [--wait-nav]", kind)
}
case "type":
if len(args) < 2 {
- cliui.Fatal("Usage: pinchtab type <ref> <text>")
+ cli.Fatal("Usage: pinchtab type <ref> <text>")
}
body["ref"] = args[0]
body["text"] = strings.Join(args[1:], " ")
case "fill":
if len(args) < 2 {
- cliui.Fatal("Usage: pinchtab fill <ref|selector> <text>")
+ cli.Fatal("Usage: pinchtab fill <ref|selector> <text>")
}
if strings.HasPrefix(args[0], "e") {
body["ref"] = args[0]
@@ -54,12 +55,12 @@ func Action(client *http.Client, base, token, kind string, args []string) {
body["text"] = strings.Join(args[1:], " ")
case "press":
if len(args) < 1 {
- cliui.Fatal("Usage: pinchtab press <key> (e.g. Enter, Tab, Escape)")
+ cli.Fatal("Usage: pinchtab press <key> (e.g. Enter, Tab, Escape)")
}
body["key"] = args[0]
case "scroll":
if len(args) < 1 {
- cliui.Fatal("Usage: pinchtab scroll <ref|pixels|direction> (e.g. e5, 800, or down)")
+ cli.Fatal("Usage: pinchtab scroll <ref|pixels|direction> (e.g. e5, 800, or down)")
}
if strings.HasPrefix(args[0], "e") {
body["ref"] = args[0]
@@ -76,16 +77,16 @@ func Action(client *http.Client, base, token, kind string, args []string) {
case "left":
body["scrollX"] = -800
default:
- cliui.Fatal("Usage: pinchtab scroll <ref|pixels|direction> (e.g. e5, 800, or down)")
+ cli.Fatal("Usage: pinchtab scroll <ref|pixels|direction> (e.g. e5, 800, or down)")
}
}
case "select":
if len(args) < 2 {
- cliui.Fatal("Usage: pinchtab select <ref> <value>")
+ cli.Fatal("Usage: pinchtab select <ref> <value>")
}
body["ref"] = args[0]
body["value"] = args[1]
}
- DoPost(client, base, token, "/action", body)
+ apiclient.DoPost(client, base, token, "/action", body)
}
diff --git a/internal/cli/actions/actions_element_test.go b/internal/cli/actions/actions_element_test.go
new file mode 100644
index 00000000..f410a2d7
--- /dev/null
+++ b/internal/cli/actions/actions_element_test.go
@@ -0,0 +1,212 @@
+package actions
+
+import (
+ "encoding/json"
+ "testing"
+)
+
+func TestClick(t *testing.T) {
+ m := newMockServer()
+ defer m.close()
+ client := m.server.Client()
+
+ Action(client, m.base(), "", "click", []string{"e5"})
+ if m.lastPath != "/action" {
+ t.Errorf("expected /action, got %s", m.lastPath)
+ }
+ var body map[string]any
+ _ = json.Unmarshal([]byte(m.lastBody), &body)
+ if body["kind"] != "click" {
+ t.Errorf("expected kind=click, got %v", body["kind"])
+ }
+ if body["ref"] != "e5" {
+ t.Errorf("expected ref=e5, got %v", body["ref"])
+ }
+}
+
+func TestClickWaitNav(t *testing.T) {
+ m := newMockServer()
+ defer m.close()
+ client := m.server.Client()
+
+ Action(client, m.base(), "", "click", []string{"e5", "--wait-nav"})
+ var body map[string]any
+ _ = json.Unmarshal([]byte(m.lastBody), &body)
+ if body["waitNav"] != true {
+ t.Error("expected waitNav=true")
+ }
+}
+
+func TestType(t *testing.T) {
+ m := newMockServer()
+ defer m.close()
+ client := m.server.Client()
+
+ Action(client, m.base(), "", "type", []string{"e12", "hello", "world"})
+ var body map[string]any
+ _ = json.Unmarshal([]byte(m.lastBody), &body)
+ if body["kind"] != "type" {
+ t.Errorf("expected kind=type, got %v", body["kind"])
+ }
+ if body["ref"] != "e12" {
+ t.Errorf("expected ref=e12, got %v", body["ref"])
+ }
+ if body["text"] != "hello world" {
+ t.Errorf("expected text='hello world', got %v", body["text"])
+ }
+}
+
+func TestPress(t *testing.T) {
+ m := newMockServer()
+ defer m.close()
+ client := m.server.Client()
+
+ Action(client, m.base(), "", "press", []string{"Enter"})
+ var body map[string]any
+ _ = json.Unmarshal([]byte(m.lastBody), &body)
+ if body["key"] != "Enter" {
+ t.Errorf("expected key=Enter, got %v", body["key"])
+ }
+}
+
+func TestClickWithCSS(t *testing.T) {
+ m := newMockServer()
+ defer m.close()
+ client := m.server.Client()
+
+ Action(client, m.base(), "", "click", []string{"--css", "button.submit"})
+ var body map[string]any
+ _ = json.Unmarshal([]byte(m.lastBody), &body)
+ if body["selector"] != "button.submit" {
+ t.Errorf("expected selector=button.submit, got %v", body["selector"])
+ }
+ if _, hasRef := body["ref"]; hasRef {
+ t.Error("should not set ref when --css is provided")
+ }
+}
+
+func TestClickWithCSS_AndWaitNav(t *testing.T) {
+ m := newMockServer()
+ defer m.close()
+ client := m.server.Client()
+
+ Action(client, m.base(), "", "click", []string{"--wait-nav", "--css", "#login-btn"})
+ var body map[string]any
+ _ = json.Unmarshal([]byte(m.lastBody), &body)
+ if body["selector"] != "#login-btn" {
+ t.Errorf("expected selector=#login-btn, got %v", body["selector"])
+ }
+ if body["waitNav"] != true {
+ t.Error("expected waitNav=true")
+ }
+}
+
+func TestHoverWithCSS(t *testing.T) {
+ m := newMockServer()
+ defer m.close()
+ client := m.server.Client()
+
+ Action(client, m.base(), "", "hover", []string{"--css", ".nav-item"})
+ var body map[string]any
+ _ = json.Unmarshal([]byte(m.lastBody), &body)
+ if body["selector"] != ".nav-item" {
+ t.Errorf("expected selector=.nav-item, got %v", body["selector"])
+ }
+}
+
+func TestFocusWithCSS(t *testing.T) {
+ m := newMockServer()
+ defer m.close()
+ client := m.server.Client()
+
+ Action(client, m.base(), "", "focus", []string{"--css", "input[name='email']"})
+ var body map[string]any
+ _ = json.Unmarshal([]byte(m.lastBody), &body)
+ if body["selector"] != "input[name='email']" {
+ t.Errorf("expected selector=input[name='email'], got %v", body["selector"])
+ }
+}
+
+func TestClickRefStillWorks(t *testing.T) {
+ m := newMockServer()
+ defer m.close()
+ client := m.server.Client()
+
+ Action(client, m.base(), "", "click", []string{"e42"})
+ var body map[string]any
+ _ = json.Unmarshal([]byte(m.lastBody), &body)
+ if body["ref"] != "e42" {
+ t.Errorf("expected ref=e42, got %v", body["ref"])
+ }
+ if _, hasSelector := body["selector"]; hasSelector {
+ t.Error("should not set selector when using ref")
+ }
+}
+
+func TestFill(t *testing.T) {
+ m := newMockServer()
+ defer m.close()
+ client := m.server.Client()
+
+ // Fill with ref
+ Action(client, m.base(), "", "fill", []string{"e3", "test value"})
+ var body map[string]any
+ _ = json.Unmarshal([]byte(m.lastBody), &body)
+ if body["ref"] != "e3" {
+ t.Errorf("expected ref=e3, got %v", body["ref"])
+ }
+ if body["text"] != "test value" {
+ t.Errorf("expected text='test value', got %v", body["text"])
+ }
+
+ // Fill with selector
+ Action(client, m.base(), "", "fill", []string{"#email", "[email protected]"})
+ _ = json.Unmarshal([]byte(m.lastBody), &body)
+ if body["selector"] != "#email" {
+ t.Errorf("expected selector=#email, got %v", body["selector"])
+ }
+}
+
+func TestScroll(t *testing.T) {
+ m := newMockServer()
+ defer m.close()
+ client := m.server.Client()
+
+ // Scroll by ref
+ Action(client, m.base(), "", "scroll", []string{"e20"})
+ var body map[string]any
+ _ = json.Unmarshal([]byte(m.lastBody), &body)
+ if body["ref"] != "e20" {
+ t.Errorf("expected ref=e20, got %v", body["ref"])
+ }
+
+ // Scroll by pixels
+ Action(client, m.base(), "", "scroll", []string{"800"})
+ _ = json.Unmarshal([]byte(m.lastBody), &body)
+ if body["scrollY"] != float64(800) {
+ t.Errorf("expected scrollY=800, got %v", body["scrollY"])
+ }
+
+ // Scroll by direction
+ Action(client, m.base(), "", "scroll", []string{"down"})
+ _ = json.Unmarshal([]byte(m.lastBody), &body)
+ if body["scrollY"] != float64(800) {
+ t.Errorf("expected scrollY=800 for direction=down, got %v", body["scrollY"])
+ }
+}
+
+func TestSelect(t *testing.T) {
+ m := newMockServer()
+ defer m.close()
+ client := m.server.Client()
+
+ Action(client, m.base(), "", "select", []string{"e10", "option2"})
+ var body map[string]any
+ _ = json.Unmarshal([]byte(m.lastBody), &body)
+ if body["ref"] != "e10" {
+ t.Errorf("expected ref=e10, got %v", body["ref"])
+ }
+ if body["value"] != "option2" {
+ t.Errorf("expected value=option2, got %v", body["value"])
+ }
+}
diff --git a/internal/cli/actions/actions_evaluate.go b/internal/cli/actions/actions_evaluate.go
new file mode 100644
index 00000000..387cff3e
--- /dev/null
+++ b/internal/cli/actions/actions_evaluate.go
@@ -0,0 +1,18 @@
+package actions
+
+import (
+ "github.com/pinchtab/pinchtab/internal/cli"
+ "github.com/pinchtab/pinchtab/internal/cli/apiclient"
+ "net/http"
+ "strings"
+)
+
+func Evaluate(client *http.Client, base, token string, args []string) {
+ if len(args) < 1 {
+ cli.Fatal("Usage: pinchtab eval <expression>")
+ }
+ expr := strings.Join(args, " ")
+ apiclient.DoPost(client, base, token, "/evaluate", map[string]any{
+ "expression": expr,
+ })
+}
diff --git a/internal/cli/actions/actions_evaluate_test.go b/internal/cli/actions/actions_evaluate_test.go
new file mode 100644
index 00000000..744bb4a8
--- /dev/null
+++ b/internal/cli/actions/actions_evaluate_test.go
@@ -0,0 +1,36 @@
+package actions
+
+import (
+ "encoding/json"
+ "testing"
+)
+
+func TestEvaluate(t *testing.T) {
+ m := newMockServer()
+ m.response = `{"result":"Example Domain"}`
+ defer m.close()
+ client := m.server.Client()
+
+ Evaluate(client, m.base(), "", []string{"document.title"})
+ if m.lastPath != "/evaluate" {
+ t.Errorf("expected /evaluate, got %s", m.lastPath)
+ }
+ var body map[string]any
+ _ = json.Unmarshal([]byte(m.lastBody), &body)
+ if body["expression"] != "document.title" {
+ t.Errorf("expected expression=document.title, got %v", body["expression"])
+ }
+}
+
+func TestEvaluateMultiWord(t *testing.T) {
+ m := newMockServer()
+ defer m.close()
+ client := m.server.Client()
+
+ Evaluate(client, m.base(), "", []string{"1", "+", "2"})
+ var body map[string]any
+ _ = json.Unmarshal([]byte(m.lastBody), &body)
+ if body["expression"] != "1 + 2" {
+ t.Errorf("expected expression='1 + 2', got %v", body["expression"])
+ }
+}
diff --git a/internal/browsercli/actions_instance.go b/internal/cli/actions/actions_instance.go
similarity index 61%
rename from internal/browsercli/actions_instance.go
rename to internal/cli/actions/actions_instance.go
index 5451eb65..486348c5 100644
--- a/internal/browsercli/actions_instance.go
+++ b/internal/cli/actions/actions_instance.go
@@ -1,14 +1,15 @@
-package browsercli
+package actions
import (
"fmt"
- "github.com/pinchtab/pinchtab/internal/cliui"
+ "github.com/pinchtab/pinchtab/internal/cli"
+ "github.com/pinchtab/pinchtab/internal/cli/apiclient"
"net/http"
)
func Instance(client *http.Client, base, token string, args []string) {
if len(args) < 1 {
- cliui.Fatal("Usage: pinchtab instance <subcommand> [options]\nSubcommands: start, launch (alias), navigate, logs, stop")
+ cli.Fatal("Usage: pinchtab instance <subcommand> [options]\nSubcommands: start, launch (alias), navigate, logs, stop")
}
subCmd := args[0]
@@ -24,7 +25,7 @@ func Instance(client *http.Client, base, token string, args []string) {
case "stop":
InstanceStop(client, base, token, subArgs)
default:
- cliui.Fatal("Unknown subcommand: %s", subCmd)
+ cli.Fatal("Unknown subcommand: %s", subCmd)
}
}
@@ -53,12 +54,12 @@ func InstanceStart(client *http.Client, base, token string, args []string) {
// Use new /instances/start endpoint if available, fall back to /instances/launch for backward compat
endpoint := "/instances/start"
- DoPost(client, base, token, endpoint, body)
+ apiclient.DoPost(client, base, token, endpoint, body)
}
func InstanceNavigate(client *http.Client, base, token string, args []string) {
if len(args) < 2 {
- cliui.Fatal("Usage: pinchtab instance navigate <instance-id> <url>")
+ cli.Fatal("Usage: pinchtab instance navigate <instance-id> <url>")
}
instID := args[0]
@@ -66,16 +67,16 @@ func InstanceNavigate(client *http.Client, base, token string, args []string) {
// Instance navigate now works via tab-scoped navigation:
// open a tab on the instance, then navigate that tab.
- openResp := DoPost(client, base, token, fmt.Sprintf("/instances/%s/tabs/open", instID), map[string]any{
+ openResp := apiclient.DoPost(client, base, token, fmt.Sprintf("/instances/%s/tabs/open", instID), map[string]any{
"url": "about:blank",
})
tabID, _ := openResp["tabId"].(string)
if tabID == "" {
- cliui.Fatal("failed to open tab for instance %s", instID)
+ cli.Fatal("failed to open tab for instance %s", instID)
}
- // DoPost auto-prints JSON response.
- DoPost(client, base, token, fmt.Sprintf("/tabs/%s/navigate", tabID), map[string]any{
+ // apiclient.DoPost auto-prints JSON response.
+ apiclient.DoPost(client, base, token, fmt.Sprintf("/tabs/%s/navigate", tabID), map[string]any{
"url": targetURL,
})
}
@@ -84,19 +85,19 @@ func InstanceLogs(client *http.Client, base, token string, args []string) {
var instID string
if len(args) == 0 {
- cliui.Fatal("Usage: pinchtab instance logs <instance-id> OR pinchtab instance logs --id <instance-id>")
+ cli.Fatal("Usage: pinchtab instance logs <instance-id> OR pinchtab instance logs --id <instance-id>")
}
if args[0] == "--id" {
if len(args) < 2 {
- cliui.Fatal("Usage: --id requires instance ID")
+ cli.Fatal("Usage: --id requires instance ID")
}
instID = args[1]
} else {
instID = args[0]
}
- logs := DoGetRaw(client, base, token, fmt.Sprintf("/instances/%s/logs", instID), nil)
+ logs := apiclient.DoGetRaw(client, base, token, fmt.Sprintf("/instances/%s/logs", instID), nil)
fmt.Println(string(logs))
}
@@ -104,17 +105,17 @@ func InstanceStop(client *http.Client, base, token string, args []string) {
var instID string
if len(args) == 0 {
- cliui.Fatal("Usage: pinchtab instance stop <instance-id> OR pinchtab instance stop --id <instance-id>")
+ cli.Fatal("Usage: pinchtab instance stop <instance-id> OR pinchtab instance stop --id <instance-id>")
}
if args[0] == "--id" {
if len(args) < 2 {
- cliui.Fatal("Usage: --id requires instance ID")
+ cli.Fatal("Usage: --id requires instance ID")
}
instID = args[1]
} else {
instID = args[0]
}
- DoPost(client, base, token, fmt.Sprintf("/instances/%s/stop", instID), nil)
+ apiclient.DoPost(client, base, token, fmt.Sprintf("/instances/%s/stop", instID), nil)
}
diff --git a/internal/browsercli/actions_navigate.go b/internal/cli/actions/actions_navigate.go
similarity index 53%
rename from internal/browsercli/actions_navigate.go
rename to internal/cli/actions/actions_navigate.go
index 1674b006..f506f15b 100644
--- a/internal/browsercli/actions_navigate.go
+++ b/internal/cli/actions/actions_navigate.go
@@ -1,13 +1,14 @@
-package browsercli
+package actions
import (
- "github.com/pinchtab/pinchtab/internal/cliui"
+ "github.com/pinchtab/pinchtab/internal/cli"
+ "github.com/pinchtab/pinchtab/internal/cli/apiclient"
"net/http"
)
func Navigate(client *http.Client, base, token string, args []string) {
if len(args) < 1 {
- cliui.Fatal("Usage: pinchtab nav <url> [--new-tab] [--block-images] [--block-ads]")
+ cli.Fatal("Usage: pinchtab nav <url> [--new-tab] [--block-images] [--block-ads]")
}
body := map[string]any{"url": args[0]}
for _, a := range args[1:] {
@@ -20,6 +21,6 @@ func Navigate(client *http.Client, base, token string, args []string) {
body["blockAds"] = true
}
}
- result := DoPost(client, base, token, "/navigate", body)
- SuggestNextAction("navigate", result)
+ result := apiclient.DoPost(client, base, token, "/navigate", body)
+ apiclient.SuggestNextAction("navigate", result)
}
diff --git a/internal/cli/actions/actions_navigate_test.go b/internal/cli/actions/actions_navigate_test.go
new file mode 100644
index 00000000..3276697d
--- /dev/null
+++ b/internal/cli/actions/actions_navigate_test.go
@@ -0,0 +1,54 @@
+package actions
+
+import (
+ "encoding/json"
+ "testing"
+)
+
+func TestNavigate(t *testing.T) {
+ m := newMockServer()
+ defer m.close()
+ client := m.server.Client()
+
+ Navigate(client, m.base(), "", []string{"https://pinchtab.com"})
+ if m.lastMethod != "POST" {
+ t.Errorf("expected POST, got %s", m.lastMethod)
+ }
+ if m.lastPath != "/navigate" {
+ t.Errorf("expected /navigate, got %s", m.lastPath)
+ }
+ var body map[string]any
+ _ = json.Unmarshal([]byte(m.lastBody), &body)
+ if body["url"] != "https://pinchtab.com" {
+ t.Errorf("expected url=https://pinchtab.com, got %v", body["url"])
+ }
+}
+
+func TestNavigateWithFlags(t *testing.T) {
+ m := newMockServer()
+ defer m.close()
+ client := m.server.Client()
+
+ Navigate(client, m.base(), "", []string{"https://pinchtab.com", "--new-tab", "--block-images"})
+ var body map[string]any
+ _ = json.Unmarshal([]byte(m.lastBody), &body)
+ if body["newTab"] != true {
+ t.Error("expected newTab=true")
+ }
+ if body["blockImages"] != true {
+ t.Error("expected blockImages=true")
+ }
+}
+
+func TestNavigateWithBlockAds(t *testing.T) {
+ m := newMockServer()
+ defer m.close()
+ client := m.server.Client()
+
+ Navigate(client, m.base(), "", []string{"https://pinchtab.com", "--block-ads"})
+ var body map[string]any
+ _ = json.Unmarshal([]byte(m.lastBody), &body)
+ if body["blockAds"] != true {
+ t.Error("expected blockAds=true")
+ }
+}
diff --git a/internal/browsercli/actions_pdf.go b/internal/cli/actions/actions_pdf.go
similarity index 85%
rename from internal/browsercli/actions_pdf.go
rename to internal/cli/actions/actions_pdf.go
index 51371826..2039115d 100644
--- a/internal/browsercli/actions_pdf.go
+++ b/internal/cli/actions/actions_pdf.go
@@ -1,8 +1,9 @@
-package browsercli
+package actions
import (
"fmt"
- "github.com/pinchtab/pinchtab/internal/cliui"
+ "github.com/pinchtab/pinchtab/internal/cli"
+ "github.com/pinchtab/pinchtab/internal/cli/apiclient"
"net/http"
"net/url"
"os"
@@ -111,15 +112,15 @@ func PDF(client *http.Client, base, token string, args []string) {
var data []byte
if tabID != "" {
- data = DoGetRaw(client, base, token, fmt.Sprintf("/tabs/%s/pdf", tabID), params)
+ data = apiclient.DoGetRaw(client, base, token, fmt.Sprintf("/tabs/%s/pdf", tabID), params)
} else {
- data = DoGetRaw(client, base, token, "/pdf", params)
+ data = apiclient.DoGetRaw(client, base, token, "/pdf", params)
}
if data == nil {
return
}
if err := os.WriteFile(outFile, data, 0600); err != nil {
- cliui.Fatal("Write failed: %v", err)
+ cli.Fatal("Write failed: %v", err)
}
- fmt.Println(cliui.StyleStdout(cliui.SuccessStyle, fmt.Sprintf("Saved %s (%d bytes)", outFile, len(data))))
+ fmt.Println(cli.StyleStdout(cli.SuccessStyle, fmt.Sprintf("Saved %s (%d bytes)", outFile, len(data))))
}
diff --git a/internal/cli/actions/actions_pdf_test.go b/internal/cli/actions/actions_pdf_test.go
new file mode 100644
index 00000000..0d84d329
--- /dev/null
+++ b/internal/cli/actions/actions_pdf_test.go
@@ -0,0 +1,91 @@
+package actions
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func TestPDF(t *testing.T) {
+ m := newMockServer()
+ m.response = "FAKEPDFDATA"
+ defer m.close()
+ client := m.server.Client()
+
+ outFile := filepath.Join(t.TempDir(), "test.pdf")
+ PDF(client, m.base(), "", []string{"-o", outFile, "--tab", "tab-abc", "--landscape", "--scale", "0.8"})
+ if m.lastPath != "/tabs/tab-abc/pdf" {
+ t.Errorf("expected /tabs/tab-abc/pdf, got %s", m.lastPath)
+ }
+ if !strings.Contains(m.lastQuery, "landscape=true") {
+ t.Errorf("expected landscape=true, got %s", m.lastQuery)
+ }
+ if !strings.Contains(m.lastQuery, "scale=0.8") {
+ t.Errorf("expected scale=0.8, got %s", m.lastQuery)
+ }
+ data, err := os.ReadFile(outFile)
+ if err != nil {
+ t.Fatalf("file not written: %v", err)
+ }
+ if string(data) != "FAKEPDFDATA" {
+ t.Errorf("unexpected content: %s", string(data))
+ }
+}
+
+func TestPDFAllOptions(t *testing.T) {
+ m := newMockServer()
+ m.response = "FAKEPDFDATA"
+ defer m.close()
+ client := m.server.Client()
+
+ outFile := filepath.Join(t.TempDir(), "test.pdf")
+ args := []string{
+ "-o", outFile,
+ "--landscape",
+ "--scale", "1.5",
+ "--paper-width", "11",
+ "--paper-height", "8.5",
+ "--margin-top", "1",
+ "--margin-bottom", "1",
+ "--margin-left", "0.5",
+ "--margin-right", "0.5",
+ "--page-ranges", "1-3,5",
+ "--prefer-css-page-size",
+ "--display-header-footer",
+ "--header-template", "<span class='title'></span>",
+ "--footer-template", "<span class='pageNumber'></span>",
+ "--generate-tagged-pdf",
+ "--generate-document-outline",
+ "--tab", "tab-123",
+ }
+
+ PDF(client, m.base(), "", args)
+ if m.lastPath != "/tabs/tab-123/pdf" {
+ t.Errorf("expected /tabs/tab-123/pdf, got %s", m.lastPath)
+ }
+
+ // Check all parameters were set correctly
+ expectedParams := []string{
+ "landscape=true",
+ "scale=1.5",
+ "paperWidth=11",
+ "paperHeight=8.5",
+ "marginTop=1",
+ "marginBottom=1",
+ "marginLeft=0.5",
+ "marginRight=0.5",
+ "pageRanges=1-3%2C5", // URL encoded
+ "preferCSSPageSize=true",
+ "displayHeaderFooter=true",
+ "generateTaggedPDF=true",
+ "generateDocumentOutline=true",
+ "raw=true",
+ }
+
+ for _, expected := range expectedParams {
+ if !strings.Contains(m.lastQuery, expected) {
+ t.Errorf("expected %s in query, got %s", expected, m.lastQuery)
+ }
+ }
+}
diff --git a/internal/cli/actions/actions_quick.go b/internal/cli/actions/actions_quick.go
new file mode 100644
index 00000000..a6d3d187
--- /dev/null
+++ b/internal/cli/actions/actions_quick.go
@@ -0,0 +1,50 @@
+package actions
+
+import (
+ "fmt"
+ "github.com/pinchtab/pinchtab/internal/cli"
+ "github.com/pinchtab/pinchtab/internal/cli/apiclient"
+ "net/http"
+ "net/url"
+ "time"
+)
+
+func Quick(client *http.Client, base, token string, args []string) {
+ if len(args) < 1 {
+ cli.Fatal("Usage: pinchtab quick <url>")
+ }
+
+ fmt.Println(cli.StyleStdout(cli.HeadingStyle, fmt.Sprintf("Navigating to %s...", args[0])))
+
+ // Navigate
+ navBody := map[string]any{"url": args[0]}
+ navResult := apiclient.DoPost(client, base, token, "/navigate", navBody)
+
+ // Small delay for page to stabilize
+ time.Sleep(1 * time.Second)
+
+ fmt.Println()
+ fmt.Println(cli.StyleStdout(cli.HeadingStyle, "Page structure"))
+
+ // Snapshot with interactive filter
+ snapParams := url.Values{}
+ snapParams.Set("filter", "interactive")
+ snapParams.Set("compact", "true")
+ apiclient.DoGet(client, base, token, "/snapshot", snapParams)
+
+ // Extract info from navigation result
+ if title, ok := navResult["title"].(string); ok {
+ fmt.Println()
+ fmt.Printf("%s %s\n", cli.StyleStdout(cli.MutedStyle, "Title:"), cli.StyleStdout(cli.ValueStyle, title))
+ }
+ if urlStr, ok := navResult["url"].(string); ok {
+ fmt.Printf("%s %s\n", cli.StyleStdout(cli.MutedStyle, "URL:"), cli.StyleStdout(cli.ValueStyle, urlStr))
+ }
+
+ fmt.Println()
+ fmt.Println(cli.StyleStdout(cli.HeadingStyle, "Quick actions"))
+ fmt.Printf(" %s %s\n", cli.StyleStdout(cli.CommandStyle, "pinchtab click <ref>"), cli.StyleStdout(cli.MutedStyle, "# Click an element (use refs from above)"))
+ fmt.Printf(" %s %s\n", cli.StyleStdout(cli.CommandStyle, "pinchtab type <ref> <text>"), cli.StyleStdout(cli.MutedStyle, "# Type into input field"))
+ fmt.Printf(" %s %s\n", cli.StyleStdout(cli.CommandStyle, "pinchtab screenshot"), cli.StyleStdout(cli.MutedStyle, "# Take a screenshot"))
+ fmt.Printf(" %s %s\n", cli.StyleStdout(cli.CommandStyle, "pinchtab pdf --tab <id> -o output.pdf"), cli.StyleStdout(cli.MutedStyle, "# Save tab as PDF"))
+}
diff --git a/internal/browsercli/actions_screenshot.go b/internal/cli/actions/actions_screenshot.go
similarity index 68%
rename from internal/browsercli/actions_screenshot.go
rename to internal/cli/actions/actions_screenshot.go
index 60211954..e50145c2 100644
--- a/internal/browsercli/actions_screenshot.go
+++ b/internal/cli/actions/actions_screenshot.go
@@ -1,8 +1,9 @@
-package browsercli
+package actions
import (
"fmt"
- "github.com/pinchtab/pinchtab/internal/cliui"
+ "github.com/pinchtab/pinchtab/internal/cli"
+ "github.com/pinchtab/pinchtab/internal/cli/apiclient"
"net/http"
"net/url"
"os"
@@ -37,12 +38,12 @@ func Screenshot(client *http.Client, base, token string, args []string) {
outFile = fmt.Sprintf("screenshot-%s.jpg", time.Now().Format("20060102-150405"))
}
- data := DoGetRaw(client, base, token, "/screenshot", params)
+ data := apiclient.DoGetRaw(client, base, token, "/screenshot", params)
if data == nil {
return
}
if err := os.WriteFile(outFile, data, 0600); err != nil {
- cliui.Fatal("Write failed: %v", err)
+ cli.Fatal("Write failed: %v", err)
}
- fmt.Println(cliui.StyleStdout(cliui.SuccessStyle, fmt.Sprintf("Saved %s (%d bytes)", outFile, len(data))))
+ fmt.Println(cli.StyleStdout(cli.SuccessStyle, fmt.Sprintf("Saved %s (%d bytes)", outFile, len(data))))
}
diff --git a/internal/cli/actions/actions_screenshot_test.go b/internal/cli/actions/actions_screenshot_test.go
new file mode 100644
index 00000000..0c4cd5e2
--- /dev/null
+++ b/internal/cli/actions/actions_screenshot_test.go
@@ -0,0 +1,31 @@
+package actions
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func TestScreenshot(t *testing.T) {
+ m := newMockServer()
+ m.response = "FAKEJPEGDATA"
+ defer m.close()
+ client := m.server.Client()
+
+ outFile := filepath.Join(t.TempDir(), "test.jpg")
+ Screenshot(client, m.base(), "", []string{"-o", outFile, "-q", "50"})
+ if m.lastPath != "/screenshot" {
+ t.Errorf("expected /screenshot, got %s", m.lastPath)
+ }
+ if !strings.Contains(m.lastQuery, "quality=50") {
+ t.Errorf("expected quality=50, got %s", m.lastQuery)
+ }
+ data, err := os.ReadFile(outFile)
+ if err != nil {
+ t.Fatalf("file not written: %v", err)
+ }
+ if string(data) != "FAKEJPEGDATA" {
+ t.Errorf("unexpected content: %s", string(data))
+ }
+}
diff --git a/internal/browsercli/actions_snapshot.go b/internal/cli/actions/actions_snapshot.go
similarity index 80%
rename from internal/browsercli/actions_snapshot.go
rename to internal/cli/actions/actions_snapshot.go
index f28dcccb..84c03736 100644
--- a/internal/browsercli/actions_snapshot.go
+++ b/internal/cli/actions/actions_snapshot.go
@@ -1,6 +1,7 @@
-package browsercli
+package actions
import (
+ "github.com/pinchtab/pinchtab/internal/cli/apiclient"
"net/http"
"net/url"
)
@@ -39,6 +40,6 @@ func Snapshot(client *http.Client, base, token string, args []string) {
}
}
}
- result := DoGet(client, base, token, "/snapshot", params)
- SuggestNextAction("snapshot", result)
+ result := apiclient.DoGet(client, base, token, "/snapshot", params)
+ apiclient.SuggestNextAction("snapshot", result)
}
diff --git a/internal/cli/actions/actions_snapshot_test.go b/internal/cli/actions/actions_snapshot_test.go
new file mode 100644
index 00000000..5d398892
--- /dev/null
+++ b/internal/cli/actions/actions_snapshot_test.go
@@ -0,0 +1,58 @@
+package actions
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestSnapshot(t *testing.T) {
+ m := newMockServer()
+ m.response = `[{"ref":"e0","role":"button","name":"Submit"}]`
+ defer m.close()
+ client := m.server.Client()
+
+ Snapshot(client, m.base(), "", []string{"-i", "-c"})
+ if m.lastMethod != "GET" {
+ t.Errorf("expected GET, got %s", m.lastMethod)
+ }
+ if m.lastPath != "/snapshot" {
+ t.Errorf("expected /snapshot, got %s", m.lastPath)
+ }
+ if !strings.Contains(m.lastQuery, "filter=interactive") {
+ t.Errorf("expected filter=interactive in query, got %s", m.lastQuery)
+ }
+ if !strings.Contains(m.lastQuery, "format=compact") {
+ t.Errorf("expected format=compact in query, got %s", m.lastQuery)
+ }
+}
+
+func TestSnapshotDiff(t *testing.T) {
+ m := newMockServer()
+ defer m.close()
+ client := m.server.Client()
+
+ Snapshot(client, m.base(), "", []string{"--diff", "--selector", "main", "--max-tokens", "2000", "--depth", "5"})
+ if !strings.Contains(m.lastQuery, "diff=true") {
+ t.Errorf("expected diff=true, got %s", m.lastQuery)
+ }
+ if !strings.Contains(m.lastQuery, "selector=main") {
+ t.Errorf("expected selector=main, got %s", m.lastQuery)
+ }
+ if !strings.Contains(m.lastQuery, "maxTokens=2000") {
+ t.Errorf("expected maxTokens=2000, got %s", m.lastQuery)
+ }
+ if !strings.Contains(m.lastQuery, "depth=5") {
+ t.Errorf("expected depth=5, got %s", m.lastQuery)
+ }
+}
+
+func TestSnapshotTabId(t *testing.T) {
+ m := newMockServer()
+ defer m.close()
+ client := m.server.Client()
+
+ Snapshot(client, m.base(), "", []string{"--tab", "ABC123"})
+ if !strings.Contains(m.lastQuery, "tabId=ABC123") {
+ t.Errorf("expected tabId=ABC123, got %s", m.lastQuery)
+ }
+}
diff --git a/internal/browsercli/actions_system.go b/internal/cli/actions/actions_system.go
similarity index 76%
rename from internal/browsercli/actions_system.go
rename to internal/cli/actions/actions_system.go
index b8949937..587a8b80 100644
--- a/internal/browsercli/actions_system.go
+++ b/internal/cli/actions/actions_system.go
@@ -1,25 +1,33 @@
-package browsercli
+package actions
import (
"encoding/json"
"fmt"
+ "github.com/pinchtab/pinchtab/internal/cli"
+ "github.com/pinchtab/pinchtab/internal/cli/apiclient"
"log"
"net/http"
"os"
)
func Health(client *http.Client, base, token string) {
- DoGet(client, base, token, "/health", nil)
+ apiclient.DoGet(client, base, token, "/health", nil)
}
func Instances(client *http.Client, base, token string) {
- body := DoGetRaw(client, base, token, "/instances", nil)
+ body := apiclient.DoGetRaw(client, base, token, "/instances", nil)
// Parse and format as JSON
var instances []map[string]any
if err := json.Unmarshal(body, &instances); err != nil {
- fmt.Fprintf(os.Stderr, "Failed to parse instances: %v\n", err)
- os.Exit(1)
+ var envelope struct {
+ Instances []map[string]any `json:"instances"`
+ }
+ if err := json.Unmarshal(body, &envelope); err != nil {
+ fmt.Fprintf(os.Stderr, "Failed to parse instances: %v\n", err)
+ os.Exit(1)
+ }
+ instances = envelope.Instances
}
// Transform to cleaner output format
@@ -51,7 +59,7 @@ func Instances(client *http.Client, base, token string) {
// --- profiles ---
func Profiles(client *http.Client, base, token string) {
- result := DoGet(client, base, token, "/profiles", nil)
+ result := apiclient.DoGet(client, base, token, "/profiles", nil)
// Display profiles in a friendly format
if profiles, ok := result["profiles"].([]interface{}); ok && len(profiles) > 0 {
@@ -60,7 +68,7 @@ func Profiles(client *http.Client, base, token string) {
if m, ok := prof.(map[string]any); ok {
name, _ := m["name"].(string)
- fmt.Printf("👤 %s\n", name)
+ fmt.Printf("%s %s\n", cli.StyleStdout(cli.ValueStyle, "profile:"), name)
}
}
fmt.Println()
@@ -107,5 +115,5 @@ func getInstances(client *http.Client, base, token string) []map[string]any {
// launchInstance launches a default instance
func launchInstance(client *http.Client, base, token string, profile string) {
body := map[string]any{"profile": profile}
- DoPost(client, base, token, "/instances/launch", body)
+ apiclient.DoPost(client, base, token, "/instances/launch", body)
}
diff --git a/internal/cli/actions/actions_system_test.go b/internal/cli/actions/actions_system_test.go
new file mode 100644
index 00000000..4a8549b2
--- /dev/null
+++ b/internal/cli/actions/actions_system_test.go
@@ -0,0 +1,41 @@
+package actions
+
+import (
+ "testing"
+)
+
+func TestHealth(t *testing.T) {
+ m := newMockServer()
+ m.response = `{"status":"ok","version":"dev"}`
+ defer m.close()
+ client := m.server.Client()
+
+ Health(client, m.base(), "")
+ if m.lastPath != "/health" {
+ t.Errorf("expected /health, got %s", m.lastPath)
+ }
+}
+
+func TestAuthHeader(t *testing.T) {
+ m := newMockServer()
+ defer m.close()
+ client := m.server.Client()
+
+ Health(client, m.base(), "my-secret-token")
+ auth := m.lastHeaders.Get("Authorization")
+ if auth != "Bearer my-secret-token" {
+ t.Errorf("expected 'Bearer my-secret-token', got %q", auth)
+ }
+}
+
+func TestNoAuthHeader(t *testing.T) {
+ m := newMockServer()
+ defer m.close()
+ client := m.server.Client()
+
+ Health(client, m.base(), "")
+ auth := m.lastHeaders.Get("Authorization")
+ if auth != "" {
+ t.Errorf("expected no auth header, got %q", auth)
+ }
+}
diff --git a/internal/browsercli/actions_tabs.go b/internal/cli/actions/actions_tabs.go
similarity index 64%
rename from internal/browsercli/actions_tabs.go
rename to internal/cli/actions/actions_tabs.go
index 66a609ed..6351d140 100644
--- a/internal/browsercli/actions_tabs.go
+++ b/internal/cli/actions/actions_tabs.go
@@ -1,8 +1,9 @@
-package browsercli
+package actions
import (
"fmt"
- "github.com/pinchtab/pinchtab/internal/cliui"
+ "github.com/pinchtab/pinchtab/internal/cli"
+ "github.com/pinchtab/pinchtab/internal/cli/apiclient"
"net/http"
"net/url"
"os"
@@ -14,7 +15,7 @@ import (
func Tabs(client *http.Client, base, token string, args []string) {
if len(args) == 0 {
// List all tabs
- DoGet(client, base, token, "/tabs", nil)
+ apiclient.DoGet(client, base, token, "/tabs", nil)
return
}
@@ -39,22 +40,22 @@ func Tabs(client *http.Client, base, token string, args []string) {
// Check if any instances are running
instances := getInstances(client, base, token)
if len(instances) == 0 {
- fmt.Fprintln(os.Stderr, cliui.StyleStderr(cliui.WarningStyle, "No instances running, launching default..."))
+ fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.WarningStyle, "No instances running, launching default..."))
launchInstance(client, base, token, "default")
- fmt.Fprintln(os.Stderr, cliui.StyleStderr(cliui.SuccessStyle, "Instance launched"))
+ fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.SuccessStyle, "Instance launched"))
}
body := map[string]any{"action": "new"}
if url != "" {
body["url"] = url
}
- DoPost(client, base, token, "/tab", body)
+ apiclient.DoPost(client, base, token, "/tab", body)
case "close":
if len(subArgs) < 1 {
- cliui.Fatal("Usage: pinchtab tab close <tabId>")
+ cli.Fatal("Usage: pinchtab tab close <tabId>")
}
- DoPost(client, base, token, "/tab", map[string]any{
+ apiclient.DoPost(client, base, token, "/tab", map[string]any{
"action": "close",
"tabId": subArgs[0],
})
@@ -78,7 +79,7 @@ func isTabOperation(op string) bool {
func TabOperation(client *http.Client, base, token string, op string, args []string) {
if len(args) < 1 {
- cliui.Fatal("Usage: pinchtab tab %s <tabId> [args...]", op)
+ cli.Fatal("Usage: pinchtab tab %s <tabId> [args...]", op)
}
tabID := args[0]
@@ -87,7 +88,7 @@ func TabOperation(client *http.Client, base, token string, op string, args []str
switch op {
case "navigate":
if len(restArgs) < 1 {
- cliui.Fatal("Usage: pinchtab tab navigate <tabId> <url> [--timeout N] [--block-images]")
+ cli.Fatal("Usage: pinchtab tab navigate <tabId> <url> [--timeout N] [--block-images]")
}
body := map[string]any{"url": restArgs[0]}
for i := 1; i < len(restArgs); i++ {
@@ -103,7 +104,7 @@ func TabOperation(client *http.Client, base, token string, op string, args []str
body["blockAds"] = true
}
}
- DoPost(client, base, token, fmt.Sprintf("/tabs/%s/navigate", tabID), body)
+ apiclient.DoPost(client, base, token, fmt.Sprintf("/tabs/%s/navigate", tabID), body)
case "snapshot":
params := url.Values{}
@@ -117,7 +118,7 @@ func TabOperation(client *http.Client, base, token string, op string, args []str
params.Set("diff", "true")
}
}
- DoGet(client, base, token, fmt.Sprintf("/tabs/%s/snapshot", tabID), params)
+ apiclient.DoGet(client, base, token, fmt.Sprintf("/tabs/%s/snapshot", tabID), params)
case "screenshot", "ss":
params := url.Values{}
@@ -137,47 +138,48 @@ func TabOperation(client *http.Client, base, token string, op string, args []str
}
}
params.Set("raw", "true")
- data := DoGetRaw(client, base, token, fmt.Sprintf("/tabs/%s/screenshot", tabID), params)
+ data := apiclient.DoGetRaw(client, base, token, fmt.Sprintf("/tabs/%s/screenshot", tabID), params)
if outFile == "" {
outFile = fmt.Sprintf("screenshot-%s.png", time.Now().Format("20060102-150405"))
}
if data != nil {
if err := os.WriteFile(outFile, data, 0600); err != nil {
- fmt.Println(cliui.StyleStdout(cliui.SuccessStyle, fmt.Sprintf("Saved %s (%d bytes)", outFile, len(data))))
+ cli.Fatal("Write failed: %v", err)
}
+ fmt.Println(cli.StyleStdout(cli.SuccessStyle, fmt.Sprintf("Saved %s (%d bytes)", outFile, len(data))))
}
case "click", "hover", "focus":
if len(restArgs) < 1 {
- cliui.Fatal("Usage: pinchtab tab %s <tabId> <ref>", op)
+ cli.Fatal("Usage: pinchtab tab %s <tabId> <ref>", op)
}
body := map[string]any{"kind": op, "ref": restArgs[0]}
- DoPost(client, base, token, fmt.Sprintf("/tabs/%s/action", tabID), body)
+ apiclient.DoPost(client, base, token, fmt.Sprintf("/tabs/%s/action", tabID), body)
case "type":
if len(restArgs) < 2 {
- cliui.Fatal("Usage: pinchtab tab type <tabId> <ref> <text>")
+ cli.Fatal("Usage: pinchtab tab type <tabId> <ref> <text>")
}
body := map[string]any{"kind": "type", "ref": restArgs[0], "text": strings.Join(restArgs[1:], " ")}
- DoPost(client, base, token, fmt.Sprintf("/tabs/%s/action", tabID), body)
+ apiclient.DoPost(client, base, token, fmt.Sprintf("/tabs/%s/action", tabID), body)
case "fill":
if len(restArgs) < 2 {
- cliui.Fatal("Usage: pinchtab tab fill <tabId> <ref> <text>")
+ cli.Fatal("Usage: pinchtab tab fill <tabId> <ref> <text>")
}
body := map[string]any{"kind": "fill", "ref": restArgs[0], "text": strings.Join(restArgs[1:], " ")}
- DoPost(client, base, token, fmt.Sprintf("/tabs/%s/action", tabID), body)
+ apiclient.DoPost(client, base, token, fmt.Sprintf("/tabs/%s/action", tabID), body)
case "press":
if len(restArgs) < 1 {
- cliui.Fatal("Usage: pinchtab tab press <tabId> <key>")
+ cli.Fatal("Usage: pinchtab tab press <tabId> <key>")
}
body := map[string]any{"kind": "press", "key": restArgs[0]}
- DoPost(client, base, token, fmt.Sprintf("/tabs/%s/action", tabID), body)
+ apiclient.DoPost(client, base, token, fmt.Sprintf("/tabs/%s/action", tabID), body)
case "scroll":
if len(restArgs) < 1 {
- cliui.Fatal("Usage: pinchtab tab scroll <tabId> <direction|pixels>")
+ cli.Fatal("Usage: pinchtab tab scroll <tabId> <direction|pixels>")
}
body := map[string]any{}
if v, err := strconv.Atoi(restArgs[0]); err == nil {
@@ -187,14 +189,14 @@ func TabOperation(client *http.Client, base, token string, op string, args []str
body["kind"] = "scroll"
body["direction"] = restArgs[0]
}
- DoPost(client, base, token, fmt.Sprintf("/tabs/%s/action", tabID), body)
+ apiclient.DoPost(client, base, token, fmt.Sprintf("/tabs/%s/action", tabID), body)
case "select":
if len(restArgs) < 2 {
- cliui.Fatal("Usage: pinchtab tab select <tabId> <ref> <value>")
+ cli.Fatal("Usage: pinchtab tab select <tabId> <ref> <value>")
}
body := map[string]any{"kind": "select", "ref": restArgs[0], "value": restArgs[1]}
- DoPost(client, base, token, fmt.Sprintf("/tabs/%s/action", tabID), body)
+ apiclient.DoPost(client, base, token, fmt.Sprintf("/tabs/%s/action", tabID), body)
case "text":
params := url.Values{}
@@ -203,14 +205,14 @@ func TabOperation(client *http.Client, base, token string, op string, args []str
params.Set("raw", "true")
}
}
- DoGet(client, base, token, fmt.Sprintf("/tabs/%s/text", tabID), params)
+ apiclient.DoGet(client, base, token, fmt.Sprintf("/tabs/%s/text", tabID), params)
case "eval", "evaluate":
if len(restArgs) < 1 {
- cliui.Fatal("Usage: pinchtab tab eval <tabId> <expression>")
+ cli.Fatal("Usage: pinchtab tab eval <tabId> <expression>")
}
body := map[string]any{"expression": strings.Join(restArgs, " ")}
- DoPost(client, base, token, fmt.Sprintf("/tabs/%s/evaluate", tabID), body)
+ apiclient.DoPost(client, base, token, fmt.Sprintf("/tabs/%s/evaluate", tabID), body)
case "pdf":
params := url.Values{}
@@ -232,18 +234,19 @@ func TabOperation(client *http.Client, base, token string, op string, args []str
}
}
params.Set("raw", "true")
- data := DoGetRaw(client, base, token, fmt.Sprintf("/tabs/%s/pdf", tabID), params)
+ data := apiclient.DoGetRaw(client, base, token, fmt.Sprintf("/tabs/%s/pdf", tabID), params)
if outFile == "" {
outFile = fmt.Sprintf("page-%s.pdf", time.Now().Format("20060102-150405"))
}
if data != nil {
if err := os.WriteFile(outFile, data, 0600); err != nil {
- fmt.Printf("Saved %s (%d bytes)\n", outFile, len(data))
+ cli.Fatal("Write failed: %v", err)
}
+ fmt.Println(cli.StyleStdout(cli.SuccessStyle, fmt.Sprintf("Saved %s (%d bytes)", outFile, len(data))))
}
case "cookies":
- DoGet(client, base, token, fmt.Sprintf("/tabs/%s/cookies", tabID), nil)
+ apiclient.DoGet(client, base, token, fmt.Sprintf("/tabs/%s/cookies", tabID), nil)
case "lock":
body := map[string]any{}
@@ -263,7 +266,7 @@ func TabOperation(client *http.Client, base, token string, op string, args []str
}
}
}
- DoPost(client, base, token, fmt.Sprintf("/tabs/%s/lock", tabID), body)
+ apiclient.DoPost(client, base, token, fmt.Sprintf("/tabs/%s/lock", tabID), body)
case "unlock":
body := map[string]any{}
@@ -276,15 +279,15 @@ func TabOperation(client *http.Client, base, token string, op string, args []str
}
}
}
- DoPost(client, base, token, fmt.Sprintf("/tabs/%s/unlock", tabID), body)
+ apiclient.DoPost(client, base, token, fmt.Sprintf("/tabs/%s/unlock", tabID), body)
case "locks":
- DoGet(client, base, token, fmt.Sprintf("/tabs/%s/locks", tabID), nil)
+ apiclient.DoGet(client, base, token, fmt.Sprintf("/tabs/%s/locks", tabID), nil)
case "info":
- DoGet(client, base, token, fmt.Sprintf("/tabs/%s", tabID), nil)
+ apiclient.DoGet(client, base, token, fmt.Sprintf("/tabs/%s", tabID), nil)
default:
- cliui.Fatal("Unknown tab operation: %s", op)
+ cli.Fatal("Unknown tab operation: %s", op)
}
}
diff --git a/internal/cli/actions/actions_tabs_test.go b/internal/cli/actions/actions_tabs_test.go
new file mode 100644
index 00000000..7982ef8f
--- /dev/null
+++ b/internal/cli/actions/actions_tabs_test.go
@@ -0,0 +1,37 @@
+package actions
+
+import (
+ "encoding/json"
+ "testing"
+)
+
+func TestTabsList(t *testing.T) {
+ m := newMockServer()
+ m.response = `[{"id":"TAB1","url":"https://pinchtab.com"}]`
+ defer m.close()
+ client := m.server.Client()
+
+ Tabs(client, m.base(), "", nil)
+ if m.lastPath != "/tabs" {
+ t.Errorf("expected /tabs, got %s", m.lastPath)
+ }
+}
+
+func TestTabsNew(t *testing.T) {
+ m := newMockServer()
+ defer m.close()
+ client := m.server.Client()
+
+ Tabs(client, m.base(), "", []string{"new", "https://pinchtab.com"})
+ if m.lastPath != "/tab" {
+ t.Errorf("expected /tab, got %s", m.lastPath)
+ }
+ var body map[string]any
+ _ = json.Unmarshal([]byte(m.lastBody), &body)
+ if body["action"] != "new" {
+ t.Errorf("expected action=new, got %v", body["action"])
+ }
+ if body["url"] != "https://pinchtab.com" {
+ t.Errorf("expected url, got %v", body["url"])
+ }
+}
diff --git a/internal/browsercli/actions_text.go b/internal/cli/actions/actions_text.go
similarity index 71%
rename from internal/browsercli/actions_text.go
rename to internal/cli/actions/actions_text.go
index 814075a6..c3a06fa5 100644
--- a/internal/browsercli/actions_text.go
+++ b/internal/cli/actions/actions_text.go
@@ -1,6 +1,7 @@
-package browsercli
+package actions
import (
+ "github.com/pinchtab/pinchtab/internal/cli/apiclient"
"net/http"
"net/url"
)
@@ -18,5 +19,5 @@ func Text(client *http.Client, base, token string, args []string) {
}
}
}
- DoGet(client, base, token, "/text", params)
+ apiclient.DoGet(client, base, token, "/text", params)
}
diff --git a/internal/cli/actions/actions_text_test.go b/internal/cli/actions/actions_text_test.go
new file mode 100644
index 00000000..2bbf5da7
--- /dev/null
+++ b/internal/cli/actions/actions_text_test.go
@@ -0,0 +1,40 @@
+package actions
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestText(t *testing.T) {
+ m := newMockServer()
+ m.response = `{"url":"https://pinchtab.com","title":"Example","text":"Hello"}`
+ defer m.close()
+ client := m.server.Client()
+
+ Text(client, m.base(), "", nil)
+ if m.lastPath != "/text" {
+ t.Errorf("expected /text, got %s", m.lastPath)
+ }
+}
+
+func TestTextRaw(t *testing.T) {
+ m := newMockServer()
+ defer m.close()
+ client := m.server.Client()
+
+ Text(client, m.base(), "", []string{"--raw"})
+ if !strings.Contains(m.lastQuery, "mode=raw") {
+ t.Errorf("expected mode=raw, got %s", m.lastQuery)
+ }
+}
+
+func TestTextTab(t *testing.T) {
+ m := newMockServer()
+ defer m.close()
+ client := m.server.Client()
+
+ Text(client, m.base(), "", []string{"--tab", "TAB1"})
+ if !strings.Contains(m.lastQuery, "tabId=TAB1") {
+ t.Errorf("expected tabId=TAB1, got %s", m.lastQuery)
+ }
+}
diff --git a/internal/cli/actions/mock_server_test.go b/internal/cli/actions/mock_server_test.go
new file mode 100644
index 00000000..3868c1b1
--- /dev/null
+++ b/internal/cli/actions/mock_server_test.go
@@ -0,0 +1,38 @@
+package actions
+
+import (
+ "io"
+ "net/http"
+ "net/http/httptest"
+)
+
+type mockServer struct {
+ server *httptest.Server
+ lastMethod string
+ lastPath string
+ lastQuery string
+ lastBody string
+ lastHeaders http.Header
+ response string
+ statusCode int
+}
+
+func newMockServer() *mockServer {
+ m := &mockServer{statusCode: 200, response: `{"status":"ok"}`}
+ m.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ m.lastMethod = r.Method
+ m.lastPath = r.URL.Path
+ m.lastQuery = r.URL.RawQuery
+ m.lastHeaders = r.Header
+ if r.Body != nil {
+ body, _ := io.ReadAll(r.Body)
+ m.lastBody = string(body)
+ }
+ w.WriteHeader(m.statusCode)
+ _, _ = w.Write([]byte(m.response))
+ }))
+ return m
+}
+
+func (m *mockServer) close() { m.server.Close() }
+func (m *mockServer) base() string { return m.server.URL }
diff --git a/internal/browsercli/client.go b/internal/cli/apiclient/client.go
similarity index 79%
rename from internal/browsercli/client.go
rename to internal/cli/apiclient/client.go
index 3c13bdb5..e583cd50 100644
--- a/internal/browsercli/client.go
+++ b/internal/cli/apiclient/client.go
@@ -1,10 +1,9 @@
-package browsercli
+package apiclient
import (
"bytes"
"encoding/json"
"fmt"
- "github.com/pinchtab/pinchtab/internal/cliui"
"io"
"log"
"net/http"
@@ -24,13 +23,13 @@ func DoGet(client *http.Client, base, token, path string, params url.Values) map
}
resp, err := client.Do(req)
if err != nil {
- cliui.Fatal("Request failed: %v", err)
+ fatal("Request failed: %v", err)
}
defer func() { _ = resp.Body.Close() }()
body, _ := io.ReadAll(resp.Body)
if resp.StatusCode >= 400 {
- fmt.Fprintln(os.Stderr, cliui.StyleStderr(cliui.ErrorStyle, fmt.Sprintf("Error %d: %s", resp.StatusCode, string(body))))
+ fmt.Fprintf(os.Stderr, "Error %d: %s\n", resp.StatusCode, string(body))
os.Exit(1)
}
@@ -61,13 +60,13 @@ func DoGetRaw(client *http.Client, base, token, path string, params url.Values)
}
resp, err := client.Do(req)
if err != nil {
- cliui.Fatal("Request failed: %v", err)
+ fatal("Request failed: %v", err)
return nil
}
defer func() { _ = resp.Body.Close() }()
body, _ := io.ReadAll(resp.Body)
if resp.StatusCode >= 400 {
- fmt.Fprintln(os.Stderr, cliui.StyleStderr(cliui.ErrorStyle, fmt.Sprintf("Error %d: %s", resp.StatusCode, string(body))))
+ fmt.Fprintf(os.Stderr, "Error %d: %s\n", resp.StatusCode, string(body))
os.Exit(1)
}
return body
@@ -82,13 +81,13 @@ func DoPost(client *http.Client, base, token, path string, body map[string]any)
}
resp, err := client.Do(req)
if err != nil {
- cliui.Fatal("Request failed: %v", err)
+ fatal("Request failed: %v", err)
}
defer func() { _ = resp.Body.Close() }()
respBody, _ := io.ReadAll(resp.Body)
if resp.StatusCode >= 400 {
- fmt.Fprintln(os.Stderr, cliui.StyleStderr(cliui.ErrorStyle, fmt.Sprintf("Error %d: %s", resp.StatusCode, string(respBody))))
+ fmt.Fprintf(os.Stderr, "Error %d: %s\n", resp.StatusCode, string(respBody))
os.Exit(1)
}
@@ -117,10 +116,15 @@ func ResolveInstanceBase(orchBase, token, instanceID, bind string) string {
Port string `json:"port"`
}
if err := json.Unmarshal(body, &inst); err != nil {
- cliui.Fatal("failed to parse instance %q: %v", instanceID, err)
+ fatal("failed to parse instance %q: %v", instanceID, err)
}
if inst.Port == "" {
- cliui.Fatal("instance %q has no port assigned (is it still starting?)", instanceID)
+ 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/internal/cli/apiclient/diagnostics.go b/internal/cli/apiclient/diagnostics.go
new file mode 100644
index 00000000..c94ee3a7
--- /dev/null
+++ b/internal/cli/apiclient/diagnostics.go
@@ -0,0 +1,129 @@
+package apiclient
+
+import (
+ "fmt"
+ "io"
+ "net/http"
+ "os"
+ "strings"
+)
+
+// CheckServerAndGuide checks if pinchtab server is running and provides guidance
+func CheckServerAndGuide(client *http.Client, base, token string) bool {
+ req, _ := http.NewRequest("GET", base+"/health", nil)
+ if token != "" {
+ req.Header.Set("Authorization", "Bearer "+token)
+ }
+
+ resp, err := client.Do(req)
+ if err != nil {
+ if strings.Contains(err.Error(), "connection refused") || strings.Contains(err.Error(), "dial tcp") {
+ fmt.Fprintf(os.Stderr, "Pinchtab server is not running on %s\n", base)
+ fmt.Fprintln(os.Stderr)
+ fmt.Fprintln(os.Stderr, "To start the server")
+ fmt.Fprintln(os.Stderr, " pinchtab # Run in foreground (recommended for beginners)")
+ fmt.Fprintln(os.Stderr, " pinchtab & # Run in background")
+ fmt.Fprintln(os.Stderr, " PINCHTAB_PORT=9868 pinchtab # Use different port")
+ fmt.Fprintln(os.Stderr)
+ fmt.Fprintln(os.Stderr, "Then try your command again")
+ fmt.Fprintf(os.Stderr, " %s\n", strings.Join(os.Args, " "))
+ fmt.Fprintln(os.Stderr)
+ fmt.Fprintln(os.Stderr, "Learn more: https://github.com/pinchtab/pinchtab#quick-start")
+ return false
+ }
+ // Other connection errors
+ fmt.Fprintf(os.Stderr, "Cannot connect to Pinchtab server: %v\n", err)
+ return false
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ if resp.StatusCode == 401 {
+ fmt.Fprintln(os.Stderr, "Authentication required. Set PINCHTAB_TOKEN.")
+ return false
+ }
+
+ if resp.StatusCode >= 400 {
+ body, _ := io.ReadAll(resp.Body)
+ fmt.Fprintf(os.Stderr, "Server error %d: %s\n", resp.StatusCode, string(body))
+ return false
+ }
+
+ return true
+}
+
+// SuggestNextAction provides helpful suggestions based on the current command and state
+func SuggestNextAction(cmd string, result map[string]any) {
+ switch cmd {
+ case "nav", "navigate":
+ fmt.Fprintln(os.Stderr)
+ fmt.Fprintln(os.Stderr, "Next steps")
+ fmt.Fprintln(os.Stderr, " pinchtab snap # See page structure")
+ fmt.Fprintln(os.Stderr, " pinchtab screenshot # Capture visual")
+ fmt.Fprintln(os.Stderr, " pinchtab click <ref> # Click an element")
+ fmt.Fprintln(os.Stderr, " pinchtab pdf --tab <id> -o output.pdf # Save tab as PDF")
+
+ case "snap", "snapshot":
+ refs := extractRefs(result)
+ if len(refs) > 0 {
+ fmt.Fprintln(os.Stderr)
+ fmt.Fprintf(os.Stderr, "Found %d interactive elements\n", len(refs))
+ for i, ref := range refs[:min(3, len(refs))] {
+ fmt.Fprintf(os.Stderr, " pinchtab click %s # %s\n", ref.id, ref.desc)
+ if i >= 2 {
+ break
+ }
+ }
+ if len(refs) > 3 {
+ fmt.Fprintf(os.Stderr, " ... and %d more\n", len(refs)-3)
+ }
+ }
+
+ case "click", "type", "fill":
+ fmt.Fprintln(os.Stderr)
+ fmt.Fprintln(os.Stderr, "Action completed")
+ fmt.Fprintln(os.Stderr, " pinchtab snap # See updated page")
+ fmt.Fprintln(os.Stderr, " pinchtab screenshot # Visual confirmation")
+ }
+}
+
+type refInfo struct {
+ id string
+ desc string
+}
+
+func extractRefs(data map[string]any) []refInfo {
+ var refs []refInfo
+
+ // Handle different snapshot formats
+ if elements, ok := data["elements"].([]any); ok {
+ for _, elem := range elements {
+ if m, ok := elem.(map[string]any); ok {
+ if ref, ok := m["ref"].(string); ok && ref != "" {
+ desc := ""
+ if role, ok := m["role"].(string); ok {
+ desc = role
+ }
+ if name, ok := m["name"].(string); ok && name != "" {
+ desc += ": " + name
+ }
+ // Only include interactive elements
+ if role, ok := m["role"].(string); ok {
+ if role == "button" || role == "link" || role == "textbox" ||
+ role == "checkbox" || role == "radio" || role == "combobox" {
+ refs = append(refs, refInfo{id: ref, desc: desc})
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return refs
+}
+
+func min(a, b int) int {
+ if a < b {
+ return a
+ }
+ return b
+}
diff --git a/internal/cli/apiclient_exports.go b/internal/cli/apiclient_exports.go
new file mode 100644
index 00000000..82b173a4
--- /dev/null
+++ b/internal/cli/apiclient_exports.go
@@ -0,0 +1,24 @@
+package cli
+
+import (
+ "net/http"
+ "net/url"
+
+ "github.com/pinchtab/pinchtab/internal/cli/apiclient"
+)
+
+func DoGet(client *http.Client, base, token, path string, params url.Values) map[string]any {
+ return apiclient.DoGet(client, base, token, path, params)
+}
+
+func DoPost(client *http.Client, base, token, path string, body map[string]any) map[string]any {
+ return apiclient.DoPost(client, base, token, path, body)
+}
+
+func ResolveInstanceBase(orchBase, token, instanceID, bind string) string {
+ return apiclient.ResolveInstanceBase(orchBase, token, instanceID, bind)
+}
+
+func CheckServerAndGuide(client *http.Client, base, token string) bool {
+ return apiclient.CheckServerAndGuide(client, base, token)
+}
diff --git a/internal/cli/browsercli_test.go b/internal/cli/browsercli_test.go
new file mode 100644
index 00000000..78c5f263
--- /dev/null
+++ b/internal/cli/browsercli_test.go
@@ -0,0 +1,39 @@
+package cli
+
+import (
+ "io"
+ "net/http"
+ "net/http/httptest"
+)
+
+// mockServer records the last request and returns a configurable response.
+type mockServer struct {
+ server *httptest.Server
+ lastMethod string
+ lastPath string
+ lastQuery string
+ lastBody string
+ lastHeaders http.Header
+ response string
+ statusCode int
+}
+
+func newMockServer() *mockServer {
+ m := &mockServer{statusCode: 200, response: `{"status":"ok"}`}
+ m.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ m.lastMethod = r.Method
+ m.lastPath = r.URL.Path
+ m.lastQuery = r.URL.RawQuery
+ m.lastHeaders = r.Header
+ if r.Body != nil {
+ body, _ := io.ReadAll(r.Body)
+ m.lastBody = string(body)
+ }
+ w.WriteHeader(m.statusCode)
+ _, _ = w.Write([]byte(m.response))
+ }))
+ return m
+}
+
+func (m *mockServer) close() { m.server.Close() }
+func (m *mockServer) base() string { return m.server.URL }
diff --git a/internal/cli/client_test.go b/internal/cli/client_test.go
new file mode 100644
index 00000000..b582ee98
--- /dev/null
+++ b/internal/cli/client_test.go
@@ -0,0 +1,65 @@
+package cli
+
+import (
+ "testing"
+)
+
+func TestDoGetPrettyPrintsJSON(t *testing.T) {
+ m := newMockServer()
+ m.response = `{"a":1,"b":2}`
+ defer m.close()
+ client := m.server.Client()
+
+ // Just verify it doesn't panic with valid JSON
+ DoGet(client, m.base(), "", "/health", nil)
+}
+
+func TestDoGetNonJSON(t *testing.T) {
+ m := newMockServer()
+ m.response = "plain text response"
+ defer m.close()
+ client := m.server.Client()
+
+ // Should handle non-JSON gracefully
+ DoGet(client, m.base(), "", "/text", nil)
+}
+
+func TestDoPostContentType(t *testing.T) {
+ m := newMockServer()
+ defer m.close()
+ client := m.server.Client()
+
+ _ = DoPost(client, m.base(), "", "/action", map[string]any{"kind": "click"})
+ ct := m.lastHeaders.Get("Content-Type")
+ if ct != "application/json" {
+ t.Errorf("expected application/json, got %q", ct)
+ }
+}
+
+func TestResolveInstanceBase(t *testing.T) {
+ orch := newMockServer()
+ orch.response = `{"id":"abc123","port":"9901","status":"running"}`
+ defer orch.close()
+
+ 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")
+ }
+}
+
+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/cli/diagnostics_test.go b/internal/cli/diagnostics_test.go
new file mode 100644
index 00000000..9b350b7b
--- /dev/null
+++ b/internal/cli/diagnostics_test.go
@@ -0,0 +1,46 @@
+package cli
+
+import (
+ "io"
+ "os"
+ "strings"
+ "testing"
+)
+
+func TestCheckServerAndGuide(t *testing.T) {
+ // Test successful connection
+ m := newMockServer()
+ m.response = `{"status":"ok"}`
+ defer m.close()
+ client := m.server.Client()
+
+ result := CheckServerAndGuide(client, m.base(), "")
+ if !result {
+ t.Error("expected CheckServerAndGuide to return true for working server")
+ }
+
+ // Test auth required (401)
+ m2 := newMockServer()
+ m2.statusCode = 401
+ m2.response = `{"error":"unauthorized"}`
+ defer m2.close()
+ client2 := m2.server.Client()
+
+ // Capture stderr
+ oldStderr := os.Stderr
+ r, w, _ := os.Pipe()
+ os.Stderr = w
+
+ result2 := CheckServerAndGuide(client2, m2.base(), "")
+
+ _ = w.Close()
+ os.Stderr = oldStderr
+ output, _ := io.ReadAll(r)
+
+ if result2 {
+ t.Error("expected CheckServerAndGuide to return false for 401")
+ }
+ if !strings.Contains(string(output), "Authentication required") {
+ t.Error("expected auth error message")
+ }
+}
diff --git a/internal/cli/report/config_report.go b/internal/cli/report/config_report.go
new file mode 100644
index 00000000..cfb89508
--- /dev/null
+++ b/internal/cli/report/config_report.go
@@ -0,0 +1,53 @@
+package report
+
+import (
+ "fmt"
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func HandleConfigShow(cfg *config.RuntimeConfig) {
+ fmt.Println(styleStdout(headingStyle, "Current configuration (env > file > defaults):"))
+ fmt.Println()
+ fmt.Println(styleStdout(headingStyle, "Server"))
+ fmt.Printf(" Port: %s\n", cfg.Port)
+ fmt.Printf(" Bind: %s\n", cfg.Bind)
+ fmt.Printf(" Token: %s\n", config.MaskToken(cfg.Token))
+ fmt.Printf(" State Dir: %s\n", cfg.StateDir)
+ fmt.Printf(" Instance Ports: %d-%d\n", cfg.InstancePortStart, cfg.InstancePortEnd)
+ fmt.Println()
+ fmt.Println(styleStdout(headingStyle, "Security"))
+ fmt.Printf(" Evaluate: %v\n", cfg.AllowEvaluate)
+ fmt.Printf(" Macro: %v\n", cfg.AllowMacro)
+ fmt.Printf(" Screencast: %v\n", cfg.AllowScreencast)
+ fmt.Printf(" Download: %v\n", cfg.AllowDownload)
+ fmt.Printf(" Upload: %v\n", cfg.AllowUpload)
+ fmt.Println()
+ fmt.Println(styleStdout(headingStyle, "Browser / Instance Defaults"))
+ fmt.Printf(" Headless: %v\n", cfg.Headless)
+ fmt.Printf(" No Restore: %v\n", cfg.NoRestore)
+ fmt.Printf(" Profile Dir: %s\n", cfg.ProfileDir)
+ fmt.Printf(" Profiles Dir: %s\n", cfg.ProfilesBaseDir)
+ fmt.Printf(" Default Profile: %s\n", cfg.DefaultProfile)
+ fmt.Printf(" Max Tabs: %d\n", cfg.MaxTabs)
+ fmt.Printf(" Stealth: %s\n", cfg.StealthLevel)
+ fmt.Printf(" Tab Eviction: %s\n", cfg.TabEvictionPolicy)
+ fmt.Printf(" Extensions: %v\n", cfg.ExtensionPaths)
+ fmt.Println()
+ fmt.Println(styleStdout(headingStyle, "Multi-Instance"))
+ fmt.Printf(" Strategy: %s\n", cfg.Strategy)
+ fmt.Printf(" Allocation: %s\n", cfg.AllocationPolicy)
+ fmt.Printf(" Max Restarts: %d\n", cfg.RestartMaxRestarts)
+ fmt.Printf(" Init Backoff: %v\n", cfg.RestartInitBackoff)
+ fmt.Printf(" Max Backoff: %v\n", cfg.RestartMaxBackoff)
+ fmt.Printf(" Stable After: %v\n", cfg.RestartStableAfter)
+ fmt.Println()
+ fmt.Println(styleStdout(headingStyle, "Attach"))
+ fmt.Printf(" Enabled: %v\n", cfg.AttachEnabled)
+ fmt.Printf(" Allow Hosts: %v\n", cfg.AttachAllowHosts)
+ fmt.Printf(" Allow Schemes: %v\n", cfg.AttachAllowSchemes)
+ fmt.Println()
+ fmt.Println(styleStdout(headingStyle, "Timeouts"))
+ fmt.Printf(" Action: %v\n", cfg.ActionTimeout)
+ fmt.Printf(" Navigate: %v\n", cfg.NavigateTimeout)
+ fmt.Printf(" Shutdown: %v\n", cfg.ShutdownTimeout)
+}
diff --git a/internal/cli/report/daemon_status.go b/internal/cli/report/daemon_status.go
new file mode 100644
index 00000000..3fd6a5da
--- /dev/null
+++ b/internal/cli/report/daemon_status.go
@@ -0,0 +1,102 @@
+package report
+
+import (
+ "fmt"
+ "os"
+ "os/exec"
+ "os/user"
+ "path/filepath"
+ "runtime"
+ "strings"
+)
+
+var daemonExecCommand = exec.Command
+
+func IsDaemonInstalled() bool {
+ manager, err := currentDaemonManager()
+ if err != nil {
+ return false
+ }
+ _, err = os.Stat(manager.ServicePath())
+ return err == nil
+}
+
+func IsDaemonRunning() bool {
+ manager, err := currentDaemonManager()
+ if err != nil {
+ return false
+ }
+ status, err := manager.Status()
+ if err != nil {
+ return false
+ }
+ return daemonStatusLooksRunning(status)
+}
+
+// Internal copy of simplified daemon manager discovery for status checks
+type daemonInfo struct {
+ osName string
+ userID string
+}
+
+func currentDaemonManager() (daemonService, error) {
+ u, err := user.Current()
+ if err != nil {
+ return nil, err
+ }
+ info := daemonInfo{osName: runtime.GOOS, userID: u.Uid}
+ switch info.osName {
+ case "linux":
+ return &systemdStatus{userID: u.Uid}, nil
+ case "darwin":
+ return &launchdStatus{userID: u.Uid}, nil
+ default:
+ return nil, fmt.Errorf("unsupported OS")
+ }
+}
+
+type daemonService interface {
+ ServicePath() string
+ Status() (string, error)
+}
+
+type systemdStatus struct{ userID string }
+
+func (s *systemdStatus) ServicePath() string {
+ if configHome := strings.TrimSpace(os.Getenv("XDG_CONFIG_HOME")); configHome != "" {
+ return filepath.Join(configHome, "systemd", "user", "pinchtab.service")
+ }
+ home, _ := os.UserHomeDir()
+ return filepath.Join(home, ".config", "systemd", "user", "pinchtab.service")
+}
+func (s *systemdStatus) Status() (string, error) {
+ return runDaemonCommand("systemctl", "--user", "status", "pinchtab.service", "--no-pager")
+}
+
+type launchdStatus struct{ userID string }
+
+func (s *launchdStatus) ServicePath() string {
+ home, _ := os.UserHomeDir()
+ return filepath.Join(home, "Library", "LaunchAgents", "com.pinchtab.pinchtab.plist")
+}
+func (s *launchdStatus) Status() (string, error) {
+ return runDaemonCommand("launchctl", "print", "gui/"+s.userID+"/com.pinchtab.pinchtab")
+}
+
+func runDaemonCommand(name string, args ...string) (string, error) {
+ cmd := daemonExecCommand(name, args...)
+ output, err := cmd.CombinedOutput()
+ trimmed := strings.TrimSpace(string(output))
+ if err == nil {
+ return trimmed, nil
+ }
+ if trimmed == "" {
+ return "", fmt.Errorf("%s %s: %w", name, strings.Join(args, " "), err)
+ }
+ return "", fmt.Errorf("%s %s: %w: %s", name, strings.Join(args, " "), err, trimmed)
+}
+
+func daemonStatusLooksRunning(status string) bool {
+ return strings.Contains(status, "state = running") ||
+ strings.Contains(status, "Active: active (running)")
+}
diff --git a/internal/cli/report/daemon_status_test.go b/internal/cli/report/daemon_status_test.go
new file mode 100644
index 00000000..87dafcec
--- /dev/null
+++ b/internal/cli/report/daemon_status_test.go
@@ -0,0 +1,35 @@
+package report
+
+import "testing"
+
+func TestDaemonStatusLooksRunning(t *testing.T) {
+ tests := []struct {
+ name string
+ status string
+ want bool
+ }{
+ {
+ name: "launchd running",
+ status: "state = running",
+ want: true,
+ },
+ {
+ name: "systemd running",
+ status: "Active: active (running) since Thu 2026-03-12",
+ want: true,
+ },
+ {
+ name: "stopped",
+ status: "Active: inactive (dead)",
+ want: false,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := daemonStatusLooksRunning(tt.status); got != tt.want {
+ t.Fatalf("daemonStatusLooksRunning(%q) = %v, want %v", tt.status, got, tt.want)
+ }
+ })
+ }
+}
diff --git a/cmd/pinchtab/security_warnings.go b/internal/cli/report/security.go
similarity index 85%
rename from cmd/pinchtab/security_warnings.go
rename to internal/cli/report/security.go
index 59168394..66d6aad6 100644
--- a/cmd/pinchtab/security_warnings.go
+++ b/internal/cli/report/security.go
@@ -1,4 +1,4 @@
-package main
+package report
import (
"log/slog"
@@ -7,33 +7,33 @@ import (
"github.com/pinchtab/pinchtab/internal/config"
)
-type securityWarning struct {
+type SecurityWarning struct {
ID string
Message string
Attrs []any
}
-type securityPostureCheck struct {
+type SecurityPostureCheck struct {
ID string
Label string
Passed bool
Detail string
}
-type securityPosture struct {
- Checks []securityPostureCheck
+type SecurityPosture struct {
+ Checks []SecurityPostureCheck
Passed int
Total int
Level string
Bar string
}
-func assessSecurityPosture(cfg *config.RuntimeConfig) securityPosture {
+func AssessSecurityPosture(cfg *config.RuntimeConfig) SecurityPosture {
if cfg == nil {
- return securityPosture{Level: "UNKNOWN"}
+ return SecurityPosture{Level: "UNKNOWN"}
}
- checks := []securityPostureCheck{
+ checks := []SecurityPostureCheck{
{
ID: "bind_loopback",
Label: "loopback bind",
@@ -91,7 +91,7 @@ func assessSecurityPosture(cfg *config.RuntimeConfig) securityPosture {
}
}
- return securityPosture{
+ return SecurityPosture{
Checks: checks,
Passed: passed,
Total: len(checks),
@@ -100,6 +100,10 @@ func assessSecurityPosture(cfg *config.RuntimeConfig) securityPosture {
}
}
+func assessSecurityPosture(cfg *config.RuntimeConfig) SecurityPosture {
+ return AssessSecurityPosture(cfg)
+}
+
func securityPostureBar(passed, total int) string {
if total == 0 {
return "[ ]"
@@ -114,16 +118,16 @@ func securityPostureBar(passed, total int) string {
return bar
}
-func assessSecurityWarnings(cfg *config.RuntimeConfig) []securityWarning {
+func AssessSecurityWarnings(cfg *config.RuntimeConfig) []SecurityWarning {
if cfg == nil {
return nil
}
- warnings := make([]securityWarning, 0, 8)
+ warnings := make([]SecurityWarning, 0, 8)
enabled := cfg.EnabledSensitiveEndpoints()
if len(enabled) > 0 {
- warnings = append(warnings, securityWarning{
+ warnings = append(warnings, SecurityWarning{
ID: "sensitive_endpoints_enabled",
Message: "sensitive endpoints enabled",
Attrs: []any{"endpoints", enabled, "hint", "only enable them in trusted environments"},
@@ -131,7 +135,7 @@ func assessSecurityWarnings(cfg *config.RuntimeConfig) []securityWarning {
}
if cfg.Token == "" {
- warnings = append(warnings, securityWarning{
+ warnings = append(warnings, SecurityWarning{
ID: "api_auth_disabled",
Message: "api authentication disabled",
Attrs: []any{"hint", "set PINCHTAB_TOKEN to require bearer auth for all endpoints"},
@@ -139,7 +143,7 @@ func assessSecurityWarnings(cfg *config.RuntimeConfig) []securityWarning {
}
if len(enabled) > 0 && cfg.Token == "" {
- warnings = append(warnings, securityWarning{
+ warnings = append(warnings, SecurityWarning{
ID: "sensitive_endpoints_without_auth",
Message: "high-risk configuration: sensitive endpoints enabled without API authentication",
Attrs: []any{"endpoints", enabled, "hint", "set PINCHTAB_TOKEN or disable the sensitive endpoints"},
@@ -147,7 +151,7 @@ func assessSecurityWarnings(cfg *config.RuntimeConfig) []securityWarning {
}
if !isLoopbackBind(cfg.Bind) {
- warnings = append(warnings, securityWarning{
+ warnings = append(warnings, SecurityWarning{
ID: "non_loopback_bind",
Message: "server exposed on a non-loopback bind address",
Attrs: []any{"bind", cfg.Bind, "hint", "prefer 127.0.0.1 or localhost unless remote access is intentional"},
@@ -155,20 +159,20 @@ func assessSecurityWarnings(cfg *config.RuntimeConfig) []securityWarning {
}
if !cfg.IDPI.Enabled {
- warnings = append(warnings, securityWarning{
+ warnings = append(warnings, SecurityWarning{
ID: "idpi_disabled",
Message: "IDPI disabled; website whitelist inactive",
Attrs: []any{"setting", "security.idpi.enabled", "hint", "enable IDPI and keep security.idpi.allowedDomains scoped to approved websites"},
})
} else {
if len(cfg.IDPI.AllowedDomains) == 0 {
- warnings = append(warnings, securityWarning{
+ warnings = append(warnings, SecurityWarning{
ID: "idpi_whitelist_not_set",
Message: "website whitelist is not set for IDPI",
Attrs: []any{"setting", "security.idpi.allowedDomains", "hint", "configure allowedDomains to restrict which websites navigation may reach"},
})
} else if allowsAllDomains(cfg.IDPI.AllowedDomains) {
- warnings = append(warnings, securityWarning{
+ warnings = append(warnings, SecurityWarning{
ID: "idpi_whitelist_allows_all",
Message: "website whitelist allows all domains",
Attrs: []any{"setting", "security.idpi.allowedDomains", "hint", "remove '*' and list only approved domains"},
@@ -176,7 +180,7 @@ func assessSecurityWarnings(cfg *config.RuntimeConfig) []securityWarning {
}
if !cfg.IDPI.StrictMode {
- warnings = append(warnings, securityWarning{
+ warnings = append(warnings, SecurityWarning{
ID: "idpi_warn_mode",
Message: "IDPI strict mode disabled",
Attrs: []any{"setting", "security.idpi.strictMode", "hint", "enable strict mode to block requests instead of only emitting warnings"},
@@ -184,7 +188,7 @@ func assessSecurityWarnings(cfg *config.RuntimeConfig) []securityWarning {
}
if !cfg.IDPI.ScanContent && !cfg.IDPI.WrapContent {
- warnings = append(warnings, securityWarning{
+ warnings = append(warnings, SecurityWarning{
ID: "idpi_content_protection_disabled",
Message: "IDPI content protections are disabled",
Attrs: []any{"hint", "enable security.idpi.scanContent or security.idpi.wrapContent to protect text and snapshot responses"},
@@ -193,13 +197,13 @@ func assessSecurityWarnings(cfg *config.RuntimeConfig) []securityWarning {
}
if cfg.AttachEnabled {
- warnings = append(warnings, securityWarning{
+ warnings = append(warnings, SecurityWarning{
ID: "attach_enabled",
Message: "attach endpoint enabled",
Attrs: []any{"hint", "only attach to Chrome instances you trust"},
})
if attachAllowsNonLocalHosts(cfg.AttachAllowHosts) {
- warnings = append(warnings, securityWarning{
+ warnings = append(warnings, SecurityWarning{
ID: "attach_external_hosts",
Message: "attach allowHosts includes non-local hosts",
Attrs: []any{"allowHosts", cfg.AttachAllowHosts, "hint", "keep security.attach.allowHosts limited to local addresses unless external Chrome instances are intentional"},
@@ -210,8 +214,12 @@ func assessSecurityWarnings(cfg *config.RuntimeConfig) []securityWarning {
return warnings
}
-func logSecurityWarnings(cfg *config.RuntimeConfig) {
- for _, warning := range assessSecurityWarnings(cfg) {
+func assessSecurityWarnings(cfg *config.RuntimeConfig) []SecurityWarning {
+ return AssessSecurityWarnings(cfg)
+}
+
+func LogSecurityWarnings(cfg *config.RuntimeConfig) {
+ for _, warning := range AssessSecurityWarnings(cfg) {
attrs := append([]any{"category", "security", "warningId", warning.ID}, warning.Attrs...)
slog.Warn(warning.Message, attrs...)
}
diff --git a/internal/cli/report/security_defaults.go b/internal/cli/report/security_defaults.go
new file mode 100644
index 00000000..593250a3
--- /dev/null
+++ b/internal/cli/report/security_defaults.go
@@ -0,0 +1,167 @@
+package report
+
+import (
+ "reflect"
+ "strings"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func ApplyRecommendedSecurityDefaults(fc *config.FileConfig) {
+ defaults := config.DefaultFileConfig()
+ if fc == nil {
+ return
+ }
+ fc.Server.Bind = defaults.Server.Bind
+ fc.Security = defaults.Security
+ if strings.TrimSpace(fc.Server.Token) == "" {
+ token, err := config.GenerateAuthToken()
+ if err == nil {
+ fc.Server.Token = token
+ }
+ }
+}
+
+func applyRecommendedSecurityDefaults(fc *config.FileConfig) {
+ ApplyRecommendedSecurityDefaults(fc)
+}
+
+func RestoreSecurityDefaults() (string, bool, error) {
+ fc, configPath, err := config.LoadFileConfig()
+ if err != nil {
+ return "", false, err
+ }
+ before := securityDefaultsSnapshot(fc)
+ ApplyRecommendedSecurityDefaults(fc)
+ after := securityDefaultsSnapshot(fc)
+ if reflect.DeepEqual(before, after) {
+ return configPath, false, nil
+ }
+ if err := config.SaveFileConfig(fc, configPath); err != nil {
+ return "", false, err
+ }
+ return configPath, true, nil
+}
+
+func restoreSecurityDefaults() (string, bool, error) {
+ return RestoreSecurityDefaults()
+}
+
+func RecommendedSecurityDefaultLines(cfg *config.RuntimeConfig) []string {
+ posture := AssessSecurityPosture(cfg)
+ ordered := []string{
+ "server.bind = 127.0.0.1",
+ "security.allowEvaluate = false",
+ "security.allowMacro = false",
+ "security.allowScreencast = false",
+ "security.allowDownload = false",
+ "security.allowUpload = false",
+ "security.attach.enabled = false",
+ "security.attach.allowHosts = 127.0.0.1,localhost,::1",
+ "security.attach.allowSchemes = ws,wss",
+ "security.idpi.enabled = true",
+ "security.idpi.allowedDomains = 127.0.0.1,localhost,::1",
+ "security.idpi.strictMode = true",
+ "security.idpi.scanContent = true",
+ "security.idpi.wrapContent = true",
+ }
+ needed := make(map[string]bool, len(ordered))
+
+ for _, check := range posture.Checks {
+ if check.Passed {
+ continue
+ }
+ switch check.ID {
+ case "bind_loopback":
+ needed["server.bind = 127.0.0.1"] = true
+ case "sensitive_endpoints_disabled":
+ for _, line := range []string{
+ "security.allowEvaluate = false",
+ "security.allowMacro = false",
+ "security.allowScreencast = false",
+ "security.allowDownload = false",
+ "security.allowUpload = false",
+ } {
+ needed[line] = true
+ }
+ case "attach_disabled", "attach_local_only":
+ for _, line := range []string{
+ "security.attach.enabled = false",
+ "security.attach.allowHosts = 127.0.0.1,localhost,::1",
+ "security.attach.allowSchemes = ws,wss",
+ } {
+ needed[line] = true
+ }
+ case "idpi_whitelist_scoped", "idpi_strict_mode", "idpi_content_protection":
+ for _, line := range []string{
+ "security.idpi.enabled = true",
+ "security.idpi.allowedDomains = 127.0.0.1,localhost,::1",
+ "security.idpi.strictMode = true",
+ "security.idpi.scanContent = true",
+ "security.idpi.wrapContent = true",
+ } {
+ needed[line] = true
+ }
+ }
+ }
+
+ lines := make([]string, 0, len(needed))
+ for _, line := range ordered {
+ if needed[line] {
+ lines = append(lines, line)
+ }
+ }
+ return lines
+}
+
+type securityDefaultsState struct {
+ Bind string
+ Token string
+ Security securityConfigValues
+}
+
+type securityConfigValues struct {
+ AllowEvaluate bool
+ AllowMacro bool
+ AllowScreencast bool
+ AllowDownload bool
+ AllowUpload bool
+ MaxRedirects int
+ AttachEnabled bool
+ IDPI config.IDPIConfig
+}
+
+func securityDefaultsSnapshot(fc *config.FileConfig) securityDefaultsState {
+ if fc == nil {
+ return securityDefaultsState{}
+ }
+ s := securityDefaultsState{
+ Bind: fc.Server.Bind,
+ Token: fc.Server.Token,
+ Security: securityConfigValues{
+ IDPI: fc.Security.IDPI,
+ },
+ }
+ if fc.Security.AllowEvaluate != nil {
+ s.Security.AllowEvaluate = *fc.Security.AllowEvaluate
+ }
+ if fc.Security.AllowMacro != nil {
+ s.Security.AllowMacro = *fc.Security.AllowMacro
+ }
+ if fc.Security.AllowScreencast != nil {
+ s.Security.AllowScreencast = *fc.Security.AllowScreencast
+ }
+ if fc.Security.AllowDownload != nil {
+ s.Security.AllowDownload = *fc.Security.AllowDownload
+ }
+ if fc.Security.AllowUpload != nil {
+ s.Security.AllowUpload = *fc.Security.AllowUpload
+ }
+ if fc.Security.MaxRedirects != nil {
+ s.Security.MaxRedirects = *fc.Security.MaxRedirects
+ }
+ if fc.Security.Attach.Enabled != nil {
+ s.Security.AttachEnabled = *fc.Security.Attach.Enabled
+ }
+ return s
+}
diff --git a/cmd/pinchtab/security_warnings_test.go b/internal/cli/report/security_test.go
similarity index 99%
rename from cmd/pinchtab/security_warnings_test.go
rename to internal/cli/report/security_test.go
index 14507a6d..8132617c 100644
--- a/cmd/pinchtab/security_warnings_test.go
+++ b/internal/cli/report/security_test.go
@@ -1,4 +1,4 @@
-package main
+package report
import (
"os"
diff --git a/internal/cli/report/startup.go b/internal/cli/report/startup.go
new file mode 100644
index 00000000..b704e824
--- /dev/null
+++ b/internal/cli/report/startup.go
@@ -0,0 +1,201 @@
+package report
+
+import (
+ "fmt"
+ "io"
+ "os"
+ "strings"
+ "sync"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/termstyle"
+)
+
+var menuBannerOnce sync.Once
+
+type StartupBannerOptions struct {
+ Mode string
+ ListenAddr string
+ ListenStatus string
+ PublicURL string
+ Strategy string
+ Allocation string
+ ProfileDir string
+}
+
+func PrintStartupBanner(cfg *config.RuntimeConfig, opts StartupBannerOptions) {
+ if opts.Mode == "menu" {
+ printed := false
+ menuBannerOnce.Do(func() {
+ printed = true
+ })
+ if !printed {
+ return
+ }
+ }
+
+ writeBannerLine(renderStartupLogo(blankIfEmpty(opts.Mode, "server")))
+ writeBannerf(" %s %s\n", styleLabel("listen"), formatListenValue(blankIfEmpty(opts.ListenAddr, cfg.ListenAddr()), defaultListenStatus(opts.Mode, opts.ListenStatus)))
+ if opts.PublicURL != "" {
+ writeBannerf(" %s %s\n", styleLabel("url"), styleValue(opts.PublicURL))
+ }
+ strat := blankIfEmpty(opts.Strategy, "manual")
+ alloc := blankIfEmpty(opts.Allocation, "none")
+ writeBannerf(" %s %s\n", styleLabel("str,plc"), styleValue(fmt.Sprintf("%s,%s", strat, alloc)))
+
+ daemonStatus := styleStdout(warningStyle, "not installed")
+ if IsDaemonInstalled() {
+ daemonStatus = styleStdout(successStyle, "ok")
+ }
+ writeBannerf(" %s %s\n", styleLabel("daemon"), daemonStatus)
+
+ posture := AssessSecurityPosture(cfg)
+ writeBannerf(" %s %s %s\n", styleLabel("security"), styleSecurityBar(posture.Level, posture.Bar), styleSecurityLevel(posture.Level))
+
+ if opts.ProfileDir != "" {
+ writeBannerf(" %s %s\n", styleLabel("profile"), styleValue(opts.ProfileDir))
+ }
+ writeBannerLine("")
+}
+
+func PrintSecuritySummary(w io.Writer, cfg *config.RuntimeConfig, prefix string, detailed bool) {
+ posture := AssessSecurityPosture(cfg)
+ if detailed {
+ writeSummaryf(w, "%s%s %s %s\n", prefix, styleHeading("Security"), styleSecurityBar(posture.Level, posture.Bar), styleSecurityLevel(posture.Level))
+ for _, check := range posture.Checks {
+ writeSummaryf(w, "%s %s %s %s\n", prefix, styleMarker(check.Passed), styleCheckLabel(check.Label), styleCheckDetail(check.Passed, check.Detail))
+ }
+ } else {
+ writeSummaryf(w, "%s%s %s %s\n", prefix, styleLabel("security"), styleSecurityBar(posture.Level, posture.Bar), styleSecurityLevel(posture.Level))
+ }
+}
+
+func blankIfEmpty(value, fallback string) string {
+ if strings.TrimSpace(value) == "" {
+ return fallback
+ }
+ return value
+}
+
+func renderStartupLogo(mode string) string {
+ if mode == "menu" || mode == "" {
+ return styleLogo(startupLogo)
+ }
+ return styleLogo(startupLogo) + " " + styleMode(mode)
+}
+
+func writeBannerLine(line string) {
+ _, _ = fmt.Fprintln(os.Stdout, line)
+}
+
+func writeBannerf(format string, args ...any) {
+ _, _ = fmt.Fprintf(os.Stdout, format, args...)
+}
+
+func writeSummaryf(w io.Writer, format string, args ...any) {
+ _, _ = fmt.Fprintf(w, format, args...)
+}
+
+func styleHeading(text string) string {
+ return applyStyle(text, headingStyle)
+}
+
+func styleLogo(text string) string {
+ return applyStyle(text, headingStyle)
+}
+
+func styleMode(text string) string {
+ return applyStyle(text, commandStyle)
+}
+
+func styleLabel(text string) string {
+ return applyStyle(fmt.Sprintf("%-8s", text), mutedStyle)
+}
+
+func styleValue(text string) string {
+ return applyStyle(text, valueStyle)
+}
+
+func styleListenStatus(status string) string {
+ switch status {
+ case "running":
+ return applyStyle(status, successStyle)
+ case "starting":
+ return applyStyle(status, warningStyle)
+ case "stopped":
+ return applyStyle(status, mutedStyle)
+ default:
+ return applyStyle(status, valueStyle)
+ }
+}
+
+func styleCheckLabel(text string) string {
+ return applyStyle(fmt.Sprintf("%-20s", text), mutedStyle)
+}
+
+func styleCheckDetail(passed bool, text string) string {
+ if passed {
+ return applyStyle(text, successStyle)
+ }
+ return applyStyle(text, warningStyle)
+}
+
+func styleMarker(passed bool) string {
+ if passed {
+ return applyStyle("ok", successStyle)
+ }
+ return applyStyle("!!", errorStyle)
+}
+
+func styleSecurityLevel(level string) string {
+ return applyStyle(level, termstyle.NewStyle().Foreground(termstyle.Color(SecurityLevelColor(level))).Bold(true))
+}
+
+func styleSecurityBar(level, bar string) string {
+ return applyStyle(bar, termstyle.NewStyle().Foreground(termstyle.Color(SecurityLevelColor(level))).Bold(true))
+}
+
+func SecurityLevelColor(level string) string {
+ switch level {
+ case "LOCKED":
+ return string(colorSuccess)
+ case "GUARDED":
+ return string(colorWarning)
+ case "ELEVATED":
+ return string(colorDanger)
+ default:
+ return string(colorDanger)
+ }
+}
+
+func applyStyle(text string, style termstyle.Style) string {
+ return styleStdout(style, text)
+}
+
+func formatListenValue(addr, status string) string {
+ status = strings.TrimSpace(status)
+ if status == "" {
+ return styleValue(addr)
+ }
+ return fmt.Sprintf("%-8s %s", styleListenStatus(status), styleValue(addr))
+}
+
+func defaultListenStatus(mode, explicit string) string {
+ if strings.TrimSpace(explicit) != "" {
+ return explicit
+ }
+ switch mode {
+ case "menu":
+ return "stopped"
+ case "server", "bridge", "mcp":
+ return "starting"
+ default:
+ return ""
+ }
+}
+
+const startupLogo = ` ____ _ _ _____ _
+ | _ \(_)_ __ ___| |__ |_ _|_ _| |__
+ | |_) | | '_ \ / __| '_ \ | |/ _ | '_ \
+ | __/| | | | | (__| | | | | | (_| | |_) |
+ |_| |_|_| |_|\___|_| |_| |_|\__,_|_.__/`
diff --git a/internal/cli/report/startup_test.go b/internal/cli/report/startup_test.go
new file mode 100644
index 00000000..1e30561b
--- /dev/null
+++ b/internal/cli/report/startup_test.go
@@ -0,0 +1,52 @@
+package report
+
+import (
+ "testing"
+)
+
+func TestSecurityLevelColor(t *testing.T) {
+ tests := []struct {
+ level string
+ want string
+ }{
+ {level: "LOCKED", want: string(colorSuccess)},
+ {level: "GUARDED", want: string(colorWarning)},
+ {level: "ELEVATED", want: string(colorDanger)},
+ {level: "EXPOSED", want: string(colorDanger)},
+ {level: "UNKNOWN", want: string(colorDanger)},
+ }
+
+ for _, tt := range tests {
+ if got := SecurityLevelColor(tt.level); got != tt.want {
+ t.Fatalf("SecurityLevelColor(%q) = %q, want %q", tt.level, got, tt.want)
+ }
+ }
+}
+
+func TestDefaultListenStatus(t *testing.T) {
+ tests := []struct {
+ mode string
+ explicit string
+ want string
+ }{
+ {mode: "menu", want: "stopped"},
+ {mode: "server", want: "starting"},
+ {mode: "bridge", want: "starting"},
+ {mode: "mcp", want: "starting"},
+ {mode: "server", explicit: "running", want: "running"},
+ {mode: "other", want: ""},
+ }
+
+ for _, tt := range tests {
+ if got := defaultListenStatus(tt.mode, tt.explicit); got != tt.want {
+ t.Fatalf("defaultListenStatus(%q, %q) = %q, want %q", tt.mode, tt.explicit, got, tt.want)
+ }
+ }
+}
+
+func TestFormatListenValuePlain(t *testing.T) {
+ got := formatListenValue("127.0.0.1:9867", "")
+ if got != "127.0.0.1:9867" {
+ t.Fatalf("formatListenValue() = %q, want plain address", got)
+ }
+}
diff --git a/internal/cli/report/styles.go b/internal/cli/report/styles.go
new file mode 100644
index 00000000..6e04293f
--- /dev/null
+++ b/internal/cli/report/styles.go
@@ -0,0 +1,31 @@
+package report
+
+import (
+ "os"
+
+ "github.com/pinchtab/pinchtab/internal/termstyle"
+)
+
+var (
+ colorTextPrimary = termstyle.Color("#e2e8f0")
+ colorTextMuted = termstyle.Color("#64748b")
+ colorAccent = termstyle.Color("#60a5fa")
+ colorAccentLight = termstyle.Color("#93c5fd")
+ colorSuccess = termstyle.Color("#22c55e")
+ colorWarning = termstyle.Color("#fbbf24")
+ colorDanger = termstyle.Color("#ef4444")
+)
+
+var (
+ headingStyle = termstyle.NewStyle().Foreground(colorAccent).Bold(true)
+ commandStyle = termstyle.NewStyle().Foreground(colorAccentLight)
+ mutedStyle = termstyle.NewStyle().Foreground(colorTextMuted)
+ successStyle = termstyle.NewStyle().Foreground(colorSuccess).Bold(true)
+ warningStyle = termstyle.NewStyle().Foreground(colorWarning).Bold(true)
+ errorStyle = termstyle.NewStyle().Foreground(colorDanger).Bold(true)
+ valueStyle = termstyle.NewStyle().Foreground(colorTextPrimary)
+)
+
+func styleStdout(style termstyle.Style, text string) string {
+ return termstyle.RenderToFile(os.Stdout, style, text)
+}
diff --git a/internal/cli/report_exports.go b/internal/cli/report_exports.go
new file mode 100644
index 00000000..14ea04b6
--- /dev/null
+++ b/internal/cli/report_exports.go
@@ -0,0 +1,53 @@
+package cli
+
+import (
+ "io"
+
+ "github.com/pinchtab/pinchtab/internal/cli/report"
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+type StartupBannerOptions = report.StartupBannerOptions
+type SecurityWarning = report.SecurityWarning
+type SecurityPosture = report.SecurityPosture
+type SecurityPostureCheck = report.SecurityPostureCheck
+
+func PrintStartupBanner(cfg *config.RuntimeConfig, opts StartupBannerOptions) {
+ report.PrintStartupBanner(cfg, opts)
+}
+
+func PrintSecuritySummary(w io.Writer, cfg *config.RuntimeConfig, prefix string, detailed bool) {
+ report.PrintSecuritySummary(w, cfg, prefix, detailed)
+}
+
+func HandleConfigShow(cfg *config.RuntimeConfig) {
+ report.HandleConfigShow(cfg)
+}
+
+func IsDaemonInstalled() bool {
+ return report.IsDaemonInstalled()
+}
+
+func IsDaemonRunning() bool {
+ return report.IsDaemonRunning()
+}
+
+func AssessSecurityWarnings(cfg *config.RuntimeConfig) []SecurityWarning {
+ return report.AssessSecurityWarnings(cfg)
+}
+
+func AssessSecurityPosture(cfg *config.RuntimeConfig) SecurityPosture {
+ return report.AssessSecurityPosture(cfg)
+}
+
+func RecommendedSecurityDefaultLines(cfg *config.RuntimeConfig) []string {
+ return report.RecommendedSecurityDefaultLines(cfg)
+}
+
+func RestoreSecurityDefaults() (string, bool, error) {
+ return report.RestoreSecurityDefaults()
+}
+
+func LogSecurityWarnings(cfg *config.RuntimeConfig) {
+ report.LogSecurityWarnings(cfg)
+}
diff --git a/internal/cli/styles.go b/internal/cli/styles.go
new file mode 100644
index 00000000..d2a8019b
--- /dev/null
+++ b/internal/cli/styles.go
@@ -0,0 +1,87 @@
+package cli
+
+import (
+ "fmt"
+ "os"
+
+ "github.com/pinchtab/pinchtab/internal/termstyle"
+ "github.com/spf13/cobra"
+)
+
+var (
+ ColorBorder = termstyle.Color("#2b3345")
+ ColorTextPrimary = termstyle.Color("#e2e8f0")
+ ColorTextMuted = termstyle.Color("#64748b")
+ ColorAccent = termstyle.Color("#60a5fa")
+ ColorAccentLight = termstyle.Color("#93c5fd")
+ ColorSuccess = termstyle.Color("#22c55e")
+ ColorWarning = termstyle.Color("#fbbf24")
+ ColorDanger = termstyle.Color("#ef4444")
+)
+
+var (
+ HeadingStyle = termstyle.NewStyle().Foreground(ColorAccent).Bold(true)
+ CommandStyle = termstyle.NewStyle().Foreground(ColorAccentLight)
+ MutedStyle = termstyle.NewStyle().Foreground(ColorTextMuted)
+ SuccessStyle = termstyle.NewStyle().Foreground(ColorSuccess).Bold(true)
+ WarningStyle = termstyle.NewStyle().Foreground(ColorWarning).Bold(true)
+ ErrorStyle = termstyle.NewStyle().Foreground(ColorDanger).Bold(true)
+ ValueStyle = termstyle.NewStyle().Foreground(ColorTextPrimary)
+)
+
+func RenderStdout(style termstyle.Style, text string) string {
+ return StyleStdout(style, text)
+}
+
+func RenderStderr(style termstyle.Style, text string) string {
+ return StyleStderr(style, text)
+}
+
+func StyleStdout(style termstyle.Style, text string) string {
+ return renderToWriter(os.Stdout, style, text)
+}
+
+func StyleStderr(style termstyle.Style, text string) string {
+ return renderToWriter(os.Stderr, style, text)
+}
+
+func Fatal(format string, args ...any) {
+ fmt.Fprintln(os.Stderr, StyleStderr(ErrorStyle, fmt.Sprintf(format, args...)))
+ os.Exit(1)
+}
+
+func SetupUsage(root *cobra.Command) {
+ // Custom template using the shared ANSI-ready styles.
+ headerStyle := HeadingStyle.Render
+ cmdStyle := CommandStyle.Render
+
+ root.SetUsageTemplate(fmt.Sprintf(`%s:
+{{if .HasParent}} {{.UseLine}}
+{{else}} {{.CommandPath}} [command] [flags]
+ {{.CommandPath}} server # Starts the full server
+{{end}}
+
+%s:
+{{range .Groups}}{{$group := .ID}}
+ {{.Title}}:
+{{range $.Commands}}{{if eq .GroupID $group}}{{if not .Hidden}} %s {{.Short}}
+{{end}}{{end}}{{end}}{{end}}
+{{if .HasAvailableLocalFlags}}
+%s:
+{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}
+{{end}}
+{{if .HasExample}}
+%s:
+{{.Example}}
+{{end}}
+`,
+ headerStyle("Usage"),
+ headerStyle("Commands"),
+ cmdStyle("{{rpad .Name .NamePadding}}"),
+ headerStyle("Flags"),
+ headerStyle("Examples")))
+}
+
+func renderToWriter(w *os.File, style termstyle.Style, text string) string {
+ return termstyle.RenderToFile(w, style, text)
+}
diff --git a/internal/config/config_cmd.go b/internal/config/config_cmd.go
deleted file mode 100644
index c70158c5..00000000
--- a/internal/config/config_cmd.go
+++ /dev/null
@@ -1,275 +0,0 @@
-package config
-
-import (
- "encoding/json"
- "fmt"
- "os"
- "path/filepath"
-
- "github.com/pinchtab/pinchtab/internal/cliui"
- "github.com/spf13/cobra"
-)
-
-// ConfigCmd is the root command for configuration management.
-var ConfigCmd = &cobra.Command{
- Use: "config",
- Short: "Manage configuration",
-}
-
-func init() {
- ConfigCmd.AddCommand(&cobra.Command{
- Use: "show",
- Short: "Display current configuration",
- Run: func(cmd *cobra.Command, args []string) {
- cfg := Load()
- handleConfigShow(cfg)
- },
- })
- ConfigCmd.AddCommand(&cobra.Command{
- Use: "init",
- Short: "Initialize a new config file",
- Run: func(cmd *cobra.Command, args []string) {
- handleConfigInit()
- },
- })
- ConfigCmd.AddCommand(&cobra.Command{
- Use: "path",
- Short: "Show config file path",
- Run: func(cmd *cobra.Command, args []string) {
- handleConfigPath()
- },
- })
- ConfigCmd.AddCommand(&cobra.Command{
- Use: "validate",
- Short: "Validate config file",
- Run: func(cmd *cobra.Command, args []string) {
- handleConfigValidate()
- },
- })
- ConfigCmd.AddCommand(&cobra.Command{
- Use: "get <path>",
- Short: "Get a config value (e.g., server.port)",
- Args: cobra.ExactArgs(1),
- Run: func(cmd *cobra.Command, args []string) {
- handleConfigGet(args[0])
- },
- })
- ConfigCmd.AddCommand(&cobra.Command{
- Use: "set <path> <val>",
- Short: "Set a config value (e.g., server.port 8080)",
- Args: cobra.ExactArgs(2),
- Run: func(cmd *cobra.Command, args []string) {
- handleConfigSet(args[0], args[1])
- },
- })
- ConfigCmd.AddCommand(&cobra.Command{
- Use: "patch <json>",
- Short: "Merge JSON into config",
- Args: cobra.ExactArgs(1),
- Run: func(cmd *cobra.Command, args []string) {
- handleConfigPatch(args[0])
- },
- })
-}
-
-func handleConfigShow(cfg *RuntimeConfig) {
- fmt.Println(cliui.RenderStdout(cliui.HeadingStyle, "Current configuration (env > file > defaults):"))
- fmt.Println()
- fmt.Println(cliui.RenderStdout(cliui.HeadingStyle, "Server"))
- fmt.Printf(" Port: %s\n", cfg.Port)
- fmt.Printf(" Bind: %s\n", cfg.Bind)
- fmt.Printf(" Token: %s\n", MaskToken(cfg.Token))
- fmt.Printf(" State Dir: %s\n", cfg.StateDir)
- fmt.Printf(" Instance Ports: %d-%d\n", cfg.InstancePortStart, cfg.InstancePortEnd)
- fmt.Println()
- fmt.Println(cliui.RenderStdout(cliui.HeadingStyle, "Security"))
- fmt.Printf(" Evaluate: %v\n", cfg.AllowEvaluate)
- fmt.Printf(" Macro: %v\n", cfg.AllowMacro)
- fmt.Printf(" Screencast: %v\n", cfg.AllowScreencast)
- fmt.Printf(" Download: %v\n", cfg.AllowDownload)
- fmt.Printf(" Upload: %v\n", cfg.AllowUpload)
- fmt.Println()
- fmt.Println(cliui.RenderStdout(cliui.HeadingStyle, "Browser / Instance Defaults"))
- fmt.Printf(" Headless: %v\n", cfg.Headless)
- fmt.Printf(" No Restore: %v\n", cfg.NoRestore)
- fmt.Printf(" Profile Dir: %s\n", cfg.ProfileDir)
- fmt.Printf(" Profiles Dir: %s\n", cfg.ProfilesBaseDir)
- fmt.Printf(" Default Profile: %s\n", cfg.DefaultProfile)
- fmt.Printf(" Max Tabs: %d\n", cfg.MaxTabs)
- fmt.Printf(" Stealth: %s\n", cfg.StealthLevel)
- fmt.Printf(" Tab Eviction: %s\n", cfg.TabEvictionPolicy)
- fmt.Printf(" Extensions: %v\n", cfg.ExtensionPaths)
- fmt.Println()
- fmt.Println(cliui.RenderStdout(cliui.HeadingStyle, "Multi-Instance"))
- fmt.Printf(" Strategy: %s\n", cfg.Strategy)
- fmt.Printf(" Allocation: %s\n", cfg.AllocationPolicy)
- fmt.Printf(" Max Restarts: %d\n", cfg.RestartMaxRestarts)
- fmt.Printf(" Init Backoff: %v\n", cfg.RestartInitBackoff)
- fmt.Printf(" Max Backoff: %v\n", cfg.RestartMaxBackoff)
- fmt.Printf(" Stable After: %v\n", cfg.RestartStableAfter)
- fmt.Println()
- fmt.Println(cliui.RenderStdout(cliui.HeadingStyle, "Attach"))
- fmt.Printf(" Enabled: %v\n", cfg.AttachEnabled)
- fmt.Printf(" Allow Hosts: %v\n", cfg.AttachAllowHosts)
- fmt.Printf(" Allow Schemes: %v\n", cfg.AttachAllowSchemes)
- fmt.Println()
- fmt.Println(cliui.RenderStdout(cliui.HeadingStyle, "Timeouts"))
- fmt.Printf(" Action: %v\n", cfg.ActionTimeout)
- fmt.Printf(" Navigate: %v\n", cfg.NavigateTimeout)
- fmt.Printf(" Shutdown: %v\n", cfg.ShutdownTimeout)
-}
-
-func handleConfigInit() {
- configPath := filepath.Join(userConfigDir(), "config.json")
-
- if _, err := os.Stat(configPath); err == nil {
- fmt.Printf("Config file already exists at %s\n", configPath)
- fmt.Print("Overwrite? (y/N): ")
- var response string
- _, _ = fmt.Scanln(&response)
- if response != "y" && response != "Y" {
- return
- }
- }
-
- if err := os.MkdirAll(filepath.Dir(configPath), 0755); err != nil {
- fmt.Printf("Error creating directory: %v\n", err)
- os.Exit(1)
- }
-
- fc := DefaultFileConfig()
- token, err := GenerateAuthToken()
- if err != nil {
- fmt.Printf("Error generating auth token: %v\n", err)
- os.Exit(1)
- }
- fc.Server.Token = token
- data, _ := json.MarshalIndent(fc, "", " ")
- if err := os.WriteFile(configPath, data, 0644); err != nil {
- fmt.Printf("Error writing config: %v\n", err)
- os.Exit(1)
- }
-
- fmt.Printf("Config file created at %s\n", configPath)
-}
-
-func handleConfigPath() {
- configPath := envOr("PINCHTAB_CONFIG", filepath.Join(userConfigDir(), "config.json"))
- fmt.Println(configPath)
-}
-
-func handleConfigGet(path string) {
- 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 handleConfigSet(path, value string) {
- fc, configPath, err := LoadFileConfig()
- if err != nil {
- fmt.Printf("Error loading config: %v\n", err)
- os.Exit(1)
- }
-
- if err := SetConfigValue(fc, path, value); err != nil {
- fmt.Printf("Error: %v\n", err)
- os.Exit(1)
- }
-
- if errs := ValidateFileConfig(fc); len(errs) > 0 {
- fmt.Printf("Warning: new value causes validation error(s):\n")
- for _, e := range errs {
- fmt.Printf(" - %v\n", e)
- }
- fmt.Print("Save anyway? (y/N): ")
- var response string
- _, _ = fmt.Scanln(&response)
- if response != "y" && response != "Y" {
- return
- }
- }
-
- if err := SaveFileConfig(fc, configPath); err != nil {
- fmt.Printf("Error saving config: %v\n", err)
- os.Exit(1)
- }
-
- fmt.Printf("✓ Set %s = %s\n", path, value)
-}
-
-func handleConfigPatch(jsonPatch string) {
- fc, configPath, err := LoadFileConfig()
- if err != nil {
- fmt.Printf("Error loading config: %v\n", err)
- os.Exit(1)
- }
-
- if err := PatchConfigJSON(fc, jsonPatch); err != nil {
- fmt.Printf("Error: %v\n", err)
- os.Exit(1)
- }
-
- if errs := ValidateFileConfig(fc); len(errs) > 0 {
- fmt.Printf("Warning: patch causes validation error(s):\n")
- for _, e := range errs {
- fmt.Printf(" - %v\n", e)
- }
- fmt.Print("Save anyway? (y/N): ")
- var response string
- _, _ = fmt.Scanln(&response)
- if response != "y" && response != "Y" {
- return
- }
- }
-
- if err := SaveFileConfig(fc, configPath); err != nil {
- fmt.Printf("Error saving config: %v\n", err)
- os.Exit(1)
- }
-
- fmt.Println("✓ Config patched successfully")
-}
-
-func handleConfigValidate() {
- configPath := envOr("PINCHTAB_CONFIG", filepath.Join(userConfigDir(), "config.json"))
- data, err := os.ReadFile(configPath)
- if err != nil {
- fmt.Printf("Error reading config file: %v\n", err)
- os.Exit(1)
- }
-
- var fc *FileConfig
- if isLegacyConfig(data) {
- var lc legacyFileConfig
- if err := json.Unmarshal(data, &lc); err != nil {
- fmt.Printf("Error parsing legacy config: %v\n", err)
- os.Exit(1)
- }
- fc = convertLegacyConfig(&lc)
- } else {
- fc = &FileConfig{}
- if err := json.Unmarshal(data, fc); err != nil {
- fmt.Printf("Error parsing config: %v\n", err)
- os.Exit(1)
- }
- }
-
- if errs := ValidateFileConfig(fc); len(errs) > 0 {
- fmt.Printf("✗ Config file has %d error(s):\n", len(errs))
- for _, e := range errs {
- fmt.Printf(" - %v\n", e)
- }
- os.Exit(1)
- }
- fmt.Printf("✓ Config file is valid: %s\n", configPath)
-}
diff --git a/internal/config/config_utils.go b/internal/config/config_utils.go
index 3e88cf4d..ec796ba1 100644
--- a/internal/config/config_utils.go
+++ b/internal/config/config_utils.go
@@ -39,6 +39,12 @@ func userConfigDir() string {
return newPath
}
+// DefaultConfigPath returns the default config file location used when
+// PINCHTAB_CONFIG is not explicitly set.
+func DefaultConfigPath() string {
+ return filepath.Join(userConfigDir(), "config.json")
+}
+
func dirExists(path string) bool {
info, err := os.Stat(path)
if err != nil {
diff --git a/internal/handlers/download.go b/internal/handlers/download.go
index 6d916772..932c7a17 100644
--- a/internal/handlers/download.go
+++ b/internal/handlers/download.go
@@ -22,6 +22,10 @@ import (
"github.com/pinchtab/pinchtab/internal/web"
)
+var resolveDownloadHostIPs = func(ctx context.Context, network, host string) ([]net.IP, error) {
+ return net.DefaultResolver.LookupIP(ctx, network, host)
+}
+
// validateDownloadURL blocks file://, internal hosts, private IPs, and cloud metadata.
// Only public http/https URLs are allowed.
func validateDownloadURL(rawURL string) error {
@@ -42,7 +46,7 @@ func validateDownloadURL(rawURL string) error {
ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
defer cancel()
- ips, err := net.DefaultResolver.LookupIP(ctx, "ip", host)
+ ips, err := resolveDownloadHostIPs(ctx, "ip", host)
if err != nil {
return fmt.Errorf("could not resolve host")
}
diff --git a/internal/handlers/download_test.go b/internal/handlers/download_test.go
index 0fae50d5..2477398c 100644
--- a/internal/handlers/download_test.go
+++ b/internal/handlers/download_test.go
@@ -1,6 +1,9 @@
package handlers
import (
+ "context"
+ "errors"
+ "net"
"net/http"
"net/http/httptest"
"testing"
@@ -29,6 +32,21 @@ func TestHandleDownload_EmptyURL(t *testing.T) {
}
func TestValidateDownloadURL(t *testing.T) {
+ originalResolver := resolveDownloadHostIPs
+ t.Cleanup(func() {
+ resolveDownloadHostIPs = originalResolver
+ })
+ resolveDownloadHostIPs = func(ctx context.Context, network, host string) ([]net.IP, error) {
+ switch host {
+ case "pinchtab.com":
+ return []net.IP{net.ParseIP("93.184.216.34")}, nil
+ case "localhost":
+ return []net.IP{net.ParseIP("127.0.0.1")}, nil
+ default:
+ return nil, errors.New("not found")
+ }
+ }
+
tests := []struct {
name string
url string
diff --git a/internal/semantic/improvements_test.go b/internal/semantic/improvements_test.go
index 319f276e..abd23fae 100644
--- a/internal/semantic/improvements_test.go
+++ b/internal/semantic/improvements_test.go
@@ -1197,7 +1197,7 @@ func TestMultiSiteEvaluation(t *testing.T) {
cr.total++
if pass {
cr.pass++
- t.Logf("PASS query=%q -> %s score=%.3f", tc.query, tc.wantName, result.BestScore)
+ t.Logf("query=%q -> %s score=%.3f", tc.query, tc.wantName, result.BestScore)
} else {
t.Logf("MISS query=%q wanted=%s (%s) got=%s score=%.3f",
tc.query, tc.wantRef, tc.wantName, result.BestRef, result.BestScore)
diff --git a/internal/server/bridge.go b/internal/server/bridge.go
new file mode 100644
index 00000000..eed7fb61
--- /dev/null
+++ b/internal/server/bridge.go
@@ -0,0 +1,79 @@
+package server
+
+import (
+ "context"
+ "log/slog"
+ "net/http"
+ "os"
+ "os/signal"
+ "sync"
+ "syscall"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/assets"
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/cli"
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/engine"
+ "github.com/pinchtab/pinchtab/internal/handlers"
+)
+
+func RunBridgeServer(cfg *config.RuntimeConfig) {
+ listenAddr := cfg.ListenAddr()
+ cli.PrintStartupBanner(cfg, cli.StartupBannerOptions{
+ Mode: "bridge",
+ ListenAddr: listenAddr,
+ ListenStatus: "starting",
+ ProfileDir: cfg.ProfileDir,
+ })
+
+ bridgeInstance := bridge.New(context.Background(), nil, cfg)
+ bridgeInstance.StealthScript = assets.StealthScript
+
+ 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())
+ }
+
+ shutdownOnce := &sync.Once{}
+ doShutdown := func() {
+ shutdownOnce.Do(func() {
+ slog.Info("shutting down bridge...")
+ })
+ }
+ h.RegisterRoutes(mux, doShutdown)
+ cli.LogSecurityWarnings(cfg)
+
+ server := &http.Server{
+ Addr: listenAddr,
+ Handler: handlers.RequestIDMiddleware(handlers.LoggingMiddleware(handlers.AuthMiddleware(cfg, mux))),
+ ReadHeaderTimeout: 10 * time.Second,
+ ReadTimeout: 30 * time.Second,
+ WriteTimeout: 60 * time.Second,
+ IdleTimeout: 120 * time.Second,
+ }
+
+ go func() {
+ if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
+ slog.Error("server error", "err", err)
+ os.Exit(1)
+ }
+ }()
+
+ sigChan := make(chan os.Signal, 1)
+ signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
+ <-sigChan
+
+ doShutdown()
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ if err := server.Shutdown(ctx); err != nil {
+ slog.Error("shutdown error", "err", err)
+ }
+}
diff --git a/internal/server/helpers.go b/internal/server/helpers.go
new file mode 100644
index 00000000..b8623ffb
--- /dev/null
+++ b/internal/server/helpers.go
@@ -0,0 +1,94 @@
+package server
+
+import (
+ "fmt"
+ "net/http"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/orchestrator"
+ "github.com/pinchtab/pinchtab/internal/proxy"
+ "github.com/pinchtab/pinchtab/internal/web"
+)
+
+func CheckPinchTabRunning(port, token string) bool {
+ client := &http.Client{Timeout: 500 * time.Millisecond}
+ url := fmt.Sprintf("http://localhost:%s/health", port)
+ req, _ := http.NewRequest("GET", url, nil)
+ if token != "" {
+ req.Header.Set("Authorization", "Bearer "+token)
+ }
+ resp, err := client.Do(req)
+ if err != nil {
+ return false
+ }
+ defer func() {
+ _ = resp.Body.Close()
+ }()
+ return resp.StatusCode == 200
+}
+
+func RegisterDefaultProxyRoutes(mux *http.ServeMux, orch *orchestrator.Orchestrator) {
+ mux.HandleFunc("GET /tabs", func(w http.ResponseWriter, r *http.Request) {
+ target := orch.FirstRunningURL()
+ if target == "" {
+ web.JSON(w, 200, map[string]any{"tabs": []any{}})
+ return
+ }
+ proxy.HTTP(w, r, target+"/tabs")
+ })
+
+ proxyEndpoints := []string{
+ "GET /snapshot", "GET /screenshot", "GET /text",
+ "POST /navigate", "POST /action", "POST /actions", "POST /evaluate",
+ "POST /tab", "POST /tab/lock", "POST /tab/unlock",
+ "GET /cookies", "POST /cookies",
+ "GET /download", "POST /upload",
+ "GET /stealth/status", "POST /fingerprint/rotate",
+ "GET /screencast", "GET /screencast/tabs",
+ "POST /find", "POST /macro",
+ }
+ for _, ep := range proxyEndpoints {
+ endpoint := ep
+ mux.HandleFunc(endpoint, func(w http.ResponseWriter, r *http.Request) {
+ target := orch.FirstRunningURL()
+ if target == "" {
+ web.Error(w, 503, fmt.Errorf("no running instances — launch one from the Profiles tab"))
+ return
+ }
+ path := r.URL.Path
+ proxy.HTTP(w, r, target+path)
+ })
+ }
+}
+
+func MetricFloat(value any) float64 {
+ switch v := value.(type) {
+ case float64:
+ return v
+ case float32:
+ return float64(v)
+ case int:
+ return float64(v)
+ case int64:
+ return float64(v)
+ case uint64:
+ return float64(v)
+ default:
+ return 0
+ }
+}
+
+func MetricInt(value any) int {
+ switch v := value.(type) {
+ case int:
+ return v
+ case int64:
+ return int(v)
+ case float64:
+ return int(v)
+ case uint64:
+ return int(v)
+ default:
+ return 0
+ }
+}
diff --git a/cmd/pinchtab/cmd_dashboard.go b/internal/server/server.go
similarity index 62%
rename from cmd/pinchtab/cmd_dashboard.go
rename to internal/server/server.go
index 96ab0e87..68b163e7 100644
--- a/cmd/pinchtab/cmd_dashboard.go
+++ b/internal/server/server.go
@@ -1,4 +1,4 @@
-package main
+package server
import (
"context"
@@ -13,51 +13,24 @@ import (
"syscall"
"time"
- "github.com/pinchtab/pinchtab/internal/cliui"
+ "github.com/pinchtab/pinchtab/internal/cli"
"github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/dashboard"
"github.com/pinchtab/pinchtab/internal/handlers"
"github.com/pinchtab/pinchtab/internal/orchestrator"
"github.com/pinchtab/pinchtab/internal/profiles"
- "github.com/pinchtab/pinchtab/internal/proxy"
"github.com/pinchtab/pinchtab/internal/scheduler"
"github.com/pinchtab/pinchtab/internal/strategy"
"github.com/pinchtab/pinchtab/internal/web"
- "github.com/spf13/cobra"
- // Register strategies via init().
+ // Register strategies
_ "github.com/pinchtab/pinchtab/internal/strategy/alwayson"
_ "github.com/pinchtab/pinchtab/internal/strategy/autorestart"
_ "github.com/pinchtab/pinchtab/internal/strategy/explicit"
_ "github.com/pinchtab/pinchtab/internal/strategy/simple"
)
-var serverCmd = &cobra.Command{
- Use: "server",
- Short: "Start full server explicitly",
- Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
- runDashboard(cfg)
- },
-}
-
-var bridgeCmd = &cobra.Command{
- Use: "bridge",
- Short: "Start single-instance bridge-only server",
- Run: func(cmd *cobra.Command, args []string) {
- cfg := config.Load()
- runBridgeServer(cfg)
- },
-}
-
-func init() {
- rootCmd.AddCommand(serverCmd)
- rootCmd.AddCommand(bridgeCmd)
-}
-
-// runDashboard starts a lightweight dashboard server — no Chrome, no bridge.
-// It manages PinchTab instances via the orchestrator and serves the dashboard UI.
-func runDashboard(cfg *config.RuntimeConfig) {
+func RunDashboard(cfg *config.RuntimeConfig, version string) {
dashPort := cfg.Port
if dashPort == "" {
dashPort = "9870"
@@ -80,9 +53,9 @@ func runDashboard(cfg *config.RuntimeConfig) {
dash.SetServerMetricsProvider(func() dashboard.MonitoringServerMetrics {
snapshot := handlers.SnapshotMetrics()
return dashboard.MonitoringServerMetrics{
- GoHeapAllocMB: metricFloat(snapshot["goHeapAllocMB"]),
- GoNumGoroutine: metricInt(snapshot["goNumGoroutine"]),
- RateBucketHosts: metricInt(snapshot["rateBucketHosts"]),
+ GoHeapAllocMB: MetricFloat(snapshot["goHeapAllocMB"]),
+ GoNumGoroutine: MetricInt(snapshot["goNumGoroutine"]),
+ RateBucketHosts: MetricInt(snapshot["rateBucketHosts"]),
}
})
configAPI := dashboard.NewConfigAPI(cfg, orch, profMgr, orch, version, startedAt)
@@ -101,9 +74,6 @@ func runDashboard(cfg *config.RuntimeConfig) {
configAPI.RegisterHandlers(mux)
profMgr.RegisterHandlers(mux)
- // Strategy-based routing: if a known strategy is configured, let it handle
- // instance management and shorthand route registration. Otherwise fall back
- // to the default manual route setup for backward compatibility.
var activeStrategy strategy.Strategy
stratName := "manual"
if cfg.Strategy != "" {
@@ -114,7 +84,6 @@ func runDashboard(cfg *config.RuntimeConfig) {
if runtimeAware, ok := strat.(strategy.RuntimeConfigAware); ok {
runtimeAware.SetRuntimeConfig(cfg)
}
- // Inject orchestrator dependency.
if setter, ok := strat.(strategy.OrchestratorAware); ok {
setter.SetOrchestrator(orch)
}
@@ -129,30 +98,34 @@ func runDashboard(cfg *config.RuntimeConfig) {
allocPolicy = "none"
}
- printStartupBanner(cfg, startupBannerOptions{
- Mode: "server",
- ListenAddr: cfg.Bind + ":" + dashPort,
- PublicURL: fmt.Sprintf("http://localhost:%s", dashPort),
- Strategy: stratName,
- Allocation: allocPolicy,
+ listenStatus := "starting"
+ if cli.IsDaemonRunning() && CheckPinchTabRunning(dashPort, cfg.Token) {
+ listenStatus = "running"
+ }
+
+ cli.PrintStartupBanner(cfg, cli.StartupBannerOptions{
+ Mode: "server",
+ ListenAddr: cfg.Bind + ":" + dashPort,
+ ListenStatus: listenStatus,
+ PublicURL: fmt.Sprintf("http://localhost:%s", dashPort),
+ Strategy: stratName,
+ Allocation: allocPolicy,
})
- if IsDaemonRunning() && checkPinchTabRunning(dashPort, cfg.Token) {
- fmt.Println(cliui.StyleStdout(cliui.WarningStyle, fmt.Sprintf(" pinchtab already running as a daemon on port %s", dashPort)))
- fmt.Println(cliui.StyleStdout(cliui.MutedStyle, " Stop the daemon first with `pinchtab daemon stop` to run in the foreground."))
+ if listenStatus == "running" {
+ fmt.Println(cli.StyleStdout(cli.WarningStyle, fmt.Sprintf(" pinchtab already running as a daemon on port %s", dashPort)))
+ fmt.Println(cli.StyleStdout(cli.MutedStyle, " Stop the daemon first with `pinchtab daemon stop` to run in the foreground."))
fmt.Println()
os.Exit(0)
}
slog.Info("orchestration", "strategy", stratName, "allocation", allocPolicy)
- // If no strategy handled route registration, register default routes.
if activeStrategy == nil {
orch.RegisterHandlers(mux)
- registerDefaultProxyRoutes(mux, orch)
+ RegisterDefaultProxyRoutes(mux, orch)
}
- // Scheduler: opt-in task queue for multi-agent coordination.
var sched *scheduler.Scheduler
if cfg.Scheduler.Enabled {
schedCfg := scheduler.DefaultConfig()
@@ -187,13 +160,12 @@ func runDashboard(cfg *config.RuntimeConfig) {
}
mux.HandleFunc("GET /health", configAPI.HandleHealth)
-
mux.HandleFunc("GET /metrics", func(w http.ResponseWriter, r *http.Request) {
web.JSON(w, 200, map[string]any{"metrics": handlers.SnapshotMetrics()})
})
handler := handlers.LoggingMiddleware(handlers.CorsMiddleware(handlers.AuthMiddleware(cfg, mux)))
- logSecurityWarnings(cfg)
+ cli.LogSecurityWarnings(cfg)
srv := &http.Server{
Addr: cfg.Bind + ":" + dashPort,
@@ -204,7 +176,6 @@ func runDashboard(cfg *config.RuntimeConfig) {
IdleTimeout: 120 * time.Second,
}
- // Start strategy lifecycle if active.
strategyHandlesLaunch := false
if activeStrategy != nil {
if err := activeStrategy.Start(context.Background()); err != nil {
@@ -248,8 +219,6 @@ func runDashboard(cfg *config.RuntimeConfig) {
}
slog.Info("auto-launched instance", "profile", profileToLaunch, "id", inst.ID, "port", inst.Port, "headless", headlessDefault)
}()
- } else if !strategyHandlesLaunch {
- slog.Info("dashboard auto-launch disabled", "hint", "set PINCHTAB_AUTO_LAUNCH=1 or PINCHTAB_STRATEGY=always-on to enable")
}
shutdownOnce := &sync.Once{}
@@ -296,87 +265,3 @@ func runDashboard(cfg *config.RuntimeConfig) {
os.Exit(1)
}
}
-
-func checkPinchTabRunning(port, token string) bool {
- client := &http.Client{Timeout: 500 * time.Millisecond}
- url := fmt.Sprintf("http://localhost:%s/health", port)
- req, _ := http.NewRequest("GET", url, nil)
- if token != "" {
- req.Header.Set("Authorization", "Bearer "+token)
- }
- resp, err := client.Do(req)
- if err != nil {
- return false
- }
- defer resp.Body.Close()
- return resp.StatusCode == 200
-}
-
-// registerDefaultProxyRoutes adds the default shorthand proxy routes
-// when no strategy is handling route registration.
-func registerDefaultProxyRoutes(mux *http.ServeMux, orch *orchestrator.Orchestrator) {
- // Special handler for /tabs — return empty list if no instances.
- mux.HandleFunc("GET /tabs", func(w http.ResponseWriter, r *http.Request) {
- target := orch.FirstRunningURL()
- if target == "" {
- web.JSON(w, 200, map[string]any{"tabs": []any{}})
- return
- }
- proxy.HTTP(w, r, target+"/tabs")
- })
-
- proxyEndpoints := []string{
- "GET /snapshot", "GET /screenshot", "GET /text",
- "POST /navigate", "POST /action", "POST /actions", "POST /evaluate",
- "POST /tab", "POST /tab/lock", "POST /tab/unlock",
- "GET /cookies", "POST /cookies",
- "GET /download", "POST /upload",
- "GET /stealth/status", "POST /fingerprint/rotate",
- "GET /screencast", "GET /screencast/tabs",
- "POST /find", "POST /macro",
- }
- for _, ep := range proxyEndpoints {
- endpoint := ep
- mux.HandleFunc(endpoint, func(w http.ResponseWriter, r *http.Request) {
- target := orch.FirstRunningURL()
- if target == "" {
- web.Error(w, 503, fmt.Errorf("no running instances — launch one from the Profiles tab"))
- return
- }
- path := r.URL.Path
- proxy.HTTP(w, r, target+path)
- })
- }
-}
-
-func metricFloat(value any) float64 {
- switch v := value.(type) {
- case float64:
- return v
- case float32:
- return float64(v)
- case int:
- return float64(v)
- case int64:
- return float64(v)
- case uint64:
- return float64(v)
- default:
- return 0
- }
-}
-
-func metricInt(value any) int {
- switch v := value.(type) {
- case int:
- return v
- case int64:
- return int(v)
- case float64:
- return int(v)
- case uint64:
- return int(v)
- default:
- return 0
- }
-}
diff --git a/cmd/pinchtab/main_test.go b/internal/server/timeouts_test.go
similarity index 80%
rename from cmd/pinchtab/main_test.go
rename to internal/server/timeouts_test.go
index 5a9a3253..90059d5f 100644
--- a/cmd/pinchtab/main_test.go
+++ b/internal/server/timeouts_test.go
@@ -1,4 +1,4 @@
-package main
+package server
import (
"testing"
@@ -6,8 +6,6 @@ import (
)
func TestServerTimeoutOrdering(t *testing.T) {
- // Verify the timeout values used for both bridge and dashboard servers
- // are in the correct relative order.
readHeader := 10 * time.Second
read := 30 * time.Second
write := 60 * time.Second
diff --git a/internal/termstyle/style.go b/internal/termstyle/style.go
new file mode 100644
index 00000000..76df3f21
--- /dev/null
+++ b/internal/termstyle/style.go
@@ -0,0 +1,85 @@
+package termstyle
+
+import (
+ "fmt"
+ "os"
+ "strconv"
+ "strings"
+)
+
+type Color string
+
+type Style struct {
+ foreground Color
+ bold bool
+}
+
+func NewStyle() Style {
+ return Style{}
+}
+
+func (s Style) Foreground(color Color) Style {
+ s.foreground = color
+ return s
+}
+
+func (s Style) Bold(enabled bool) Style {
+ s.bold = enabled
+ return s
+}
+
+func (s Style) Render(text string) string {
+ if !ShouldColorizeFile(os.Stdout) {
+ return text
+ }
+ var codes []string
+ if s.bold {
+ codes = append(codes, "1")
+ }
+ if r, g, b, ok := parseHexColor(string(s.foreground)); ok {
+ codes = append(codes, fmt.Sprintf("38;2;%d;%d;%d", r, g, b))
+ }
+ if len(codes) == 0 {
+ return text
+ }
+ return "\x1b[" + strings.Join(codes, ";") + "m" + text + "\x1b[0m"
+}
+
+func RenderToFile(file *os.File, style Style, text string) string {
+ if !ShouldColorizeFile(file) {
+ return text
+ }
+ return style.Render(text)
+}
+
+func ShouldColorizeFile(file *os.File) bool {
+ if file == nil {
+ return false
+ }
+ if os.Getenv("NO_COLOR") != "" {
+ return false
+ }
+ if force := os.Getenv("CLICOLOR_FORCE"); force != "" && force != "0" {
+ return true
+ }
+ if strings.EqualFold(os.Getenv("TERM"), "dumb") {
+ return false
+ }
+ info, err := file.Stat()
+ if err != nil {
+ return false
+ }
+ return (info.Mode() & os.ModeCharDevice) != 0
+}
+
+func parseHexColor(value string) (int64, int64, int64, bool) {
+ trimmed := strings.TrimPrefix(strings.TrimSpace(value), "#")
+ if len(trimmed) != 6 {
+ return 0, 0, 0, false
+ }
+ raw, err := strconv.ParseUint(trimmed, 16, 32)
+ if err != nil {
+ return 0, 0, 0, false
+ }
+ return int64((raw >> 16) & 0xff), int64((raw >> 8) & 0xff), int64(raw & 0xff), true
+}
diff --git a/pdev b/pdev
index 6df2cbe3..4d698e37 100755
--- a/pdev
+++ b/pdev
@@ -31,6 +31,8 @@ COMMANDS=(
"check dashboard:🧪:Dashboard only"
"check security:🧪:Gosec security scan"
"check docs:🧪:Validate docs JSON"
+ "binary:📦:Build release-style binary into dist/"
+ " all:📦:Build the full release binary matrix into dist/"
"format dashboard:🎨:Run Prettier on dashboard sources"
)
@@ -125,6 +127,8 @@ run_command() {
;;
"dev") exec bash scripts/dev.sh ;;
"build") exec bash scripts/build.sh ;;
+ "binary") exec bash scripts/binary.sh ;;
+ "binary all"|"all") exec bash scripts/binary.sh all ;;
"run") exec bash scripts/run.sh ;;
"doctor") exec bash scripts/doctor.sh ;;
"hooks") exec bash scripts/install-hooks.sh ;;
@@ -234,6 +238,13 @@ if [ $# -gt 0 ]; then
run_command "e2e"
fi
;;
+ binary)
+ if [ $# -gt 1 ]; then
+ run_command "binary $2"
+ else
+ run_command "binary"
+ fi
+ ;;
*) run_command "$1" ;;
esac
fi
diff --git a/scripts/README.md b/scripts/README.md
index ea6352dc..ab0d366c 100644
--- a/scripts/README.md
+++ b/scripts/README.md
@@ -20,6 +20,7 @@ Development and CI scripts for PinchTab.
| Script | Purpose |
|--------|---------|
| `build.sh` | Full build (dashboard + Go) without starting the server |
+| `binary.sh` | Release-style stripped binary build into `dist/` for the current platform, or the full matrix with `all` |
| `build-dashboard.sh` | Generate TS types (tygo) + build React dashboard + copy to Go embed |
| `dev.sh` | Full build (dashboard + Go) and run |
| `run.sh` | Run the existing `./pinchtab` binary |
diff --git a/scripts/binary.sh b/scripts/binary.sh
new file mode 100755
index 00000000..405c6f0b
--- /dev/null
+++ b/scripts/binary.sh
@@ -0,0 +1,69 @@
+#!/bin/bash
+# Build release-style PinchTab binaries into ./dist for the current or requested platform.
+set -euo pipefail
+
+cd "$(dirname "$0")/.."
+
+VERSION_VALUE="${VERSION:-dev}"
+DIST_DIR="${DIST_DIR:-dist}"
+MODE="${1:-current}"
+
+build_one() {
+ local goos_value="$1"
+ local goarch_value="$2"
+ local ext=""
+
+ if [ "$goos_value" = "windows" ]; then
+ ext=".exe"
+ fi
+
+ local output_path="$DIST_DIR/pinchtab-$goos_value-$goarch_value$ext"
+
+ echo "📦 Building release-style binary..."
+ echo " target: ${goos_value}/${goarch_value}"
+ echo " output: ${output_path}"
+
+ GOCACHE="${GOCACHE:-$PWD/.gocache}" \
+ GOOS="$goos_value" \
+ GOARCH="$goarch_value" \
+ go build \
+ -buildvcs=false \
+ -ldflags="-s -w -X main.version=${VERSION_VALUE}" \
+ -o "$output_path" \
+ ./cmd/pinchtab
+
+ if command -v stat >/dev/null 2>&1; then
+ if stat -f '%z bytes %N' "$output_path" >/dev/null 2>&1; then
+ stat -f '%z bytes %N' "$output_path"
+ else
+ stat -c '%s bytes %n' "$output_path"
+ fi
+ fi
+
+ echo "✅ Binary complete: ${output_path}"
+}
+
+mkdir -p "$DIST_DIR" .gocache
+
+./scripts/build-dashboard.sh
+
+case "$MODE" in
+ all)
+ for goos_value in linux darwin windows; do
+ for goarch_value in amd64 arm64; do
+ build_one "$goos_value" "$goarch_value"
+ done
+ done
+ ;;
+ current)
+ build_one "${GOOS:-$(go env GOOS)}" "${GOARCH:-$(go env GOARCH)}"
+ ;;
+ *)
+ echo "usage: bash scripts/binary.sh [all]"
+ exit 1
+ ;;
+esac
+
+if [ "$MODE" = "all" ]; then
+ echo "✅ All release binaries complete in ${DIST_DIR}/"
+fi
diff --git a/scripts/test.sh b/scripts/test.sh
index b2861085..e28b0b5a 100755
--- a/scripts/test.sh
+++ b/scripts/test.sh
@@ -34,7 +34,7 @@ test_summary() {
local total=0 pass=0 fail=0 skip=0
read total pass fail skip <<<"$(jq -r \
'select(.Test != null and (.Action == "pass" or .Action == "fail" or .Action == "skip"))
- | [.Package, .Test, .Action] | @tsv' "$json_file" \
+ | [.Package, (.Test | split("/")[0]), .Action] | @tsv' "$json_file" \
| awk -F'\t' 'NF == 3 { key = $1 "\t" $2; status[key] = $3 }
END {
for (k in status) {
@@ -54,6 +54,49 @@ test_summary() {
[ "$fail" -gt 0 ] && echo -e " Failed: ${ERROR}$fail${NC}"
[ "$skip" -gt 0 ] && echo -e " Skipped: ${ACCENT}$skip${NC}"
+ local failed_packages
+ failed_packages="$(
+ jq -r '
+ select(.Package != null and (.Test == null or .Test == "") and (.Action == "pass" or .Action == "fail" or .Action == "skip"))
+ | [.Package, .Action] | @tsv
+ ' "$json_file" \
+ | awk -F'\t' 'NF == 2 { status[$1] = $2 }
+ END {
+ for (pkg in status) {
+ if (status[pkg] == "fail") {
+ print pkg
+ }
+ }
+ }' \
+ | sort
+ )"
+
+ if [ -n "$failed_packages" ]; then
+ echo ""
+ echo -e " ${ERROR}Failed packages:${NC}"
+ while IFS= read -r pkg; do
+ [ -n "$pkg" ] && echo " ✗ $pkg"
+ done <<<"$failed_packages"
+
+ echo ""
+ echo -e " ${ERROR}Failure details:${NC}"
+ while IFS= read -r pkg; do
+ [ -z "$pkg" ] && continue
+ echo " $pkg"
+ jq -r --arg pkg "$pkg" '
+ select(.Package == $pkg and .Action == "output")
+ | .Output
+ ' "$json_file" \
+ | sed '/^[[:space:]]*$/d' \
+ | sed '/^=== RUN/d' \
+ | sed '/^--- PASS:/d' \
+ | sed '/^PASS$/d' \
+ | tail -n 20 \
+ | sed 's/^/ /'
+ echo ""
+ done <<<"$failed_packages"
+ fi
+
if [ "$fail" -gt 0 ]; then
echo ""
echo -e " ${ERROR}Failed tests:${NC}"
@@ -61,53 +104,151 @@ test_summary() {
fi
}
-# Live progress for integration tests
-run_integration() {
+# Live progress for go test -json streams
+run_go_test_json() {
local json_file="$1"; shift
+ local label="${1:-tests}"
+ shift
local completed=0
+ local passed=0
+ local failed=0
+ local skipped=0
local max_len=40
+ local interactive=false
+ local line_open=false
+ local current_package=""
+ local status_file="${json_file}.status"
+
+ : > "$status_file"
+
+ if [ -t 1 ]; then
+ interactive=true
+ fi
+
+ render_progress() {
+ local display="$1"
+ if $interactive; then
+ printf "\r\033[2K ${MUTED}▸${NC} ${BOLD}%-11s${NC} ${MUTED}pass:%d fail:%d skip:%d${NC} %s" \
+ "$label" "$passed" "$failed" "$skipped" "$display"
+ line_open=true
+ fi
+ }
+
+ clear_progress_line() {
+ if $interactive && $line_open; then
+ printf "\r\033[2K"
+ line_open=false
+ fi
+ }
go test -json "$@" 2>&1 | tee "$json_file" | while IFS= read -r line; do
- local action test_name elapsed
+ local action test_name package_name elapsed output_text
action=$(echo "$line" | jq -r '.Action // empty' 2>/dev/null) || continue
test_name=$(echo "$line" | jq -r '.Test // empty' 2>/dev/null) || continue
+ package_name=$(echo "$line" | jq -r '.Package // empty' 2>/dev/null) || continue
elapsed=$(echo "$line" | jq -r '.Elapsed // empty' 2>/dev/null)
+ output_text=$(echo "$line" | jq -r '.Output // empty' 2>/dev/null)
- [ -z "$test_name" ] && continue
+ if [ -z "$test_name" ]; then
+ case "$action" in
+ start)
+ if [ -n "$package_name" ]; then
+ current_package="$package_name"
+ if $interactive; then
+ render_progress "${MUTED}${package_name}${NC}"
+ else
+ printf " ${MUTED}▸${NC} ${MUTED}package${NC} %s\n" "$package_name"
+ fi
+ fi
+ ;;
+ output)
+ if [ -n "$output_text" ] && [[ "$output_text" =~ ^panic:|^FAIL[[:space:]]|^---[[:space:]]FAIL ]]; then
+ if ! $interactive; then
+ output_text=${output_text%$'\n'}
+ printf " %s\n" "$output_text"
+ fi
+ fi
+ ;;
+ pass)
+ if [ -n "$package_name" ] && $interactive; then
+ render_progress "${SUCCESS}${package_name}${NC}"
+ fi
+ ;;
+ fail)
+ if [ -n "$package_name" ]; then
+ if $interactive; then
+ render_progress "${ERROR}${package_name}${NC}"
+ else
+ if [ -n "$elapsed" ]; then
+ printf " ${ERROR}✗${NC} ${MUTED}package${NC} %s ${MUTED}%6ss${NC}\n" "$package_name" "$elapsed"
+ else
+ printf " ${ERROR}✗${NC} ${MUTED}package${NC} %s\n" "$package_name"
+ fi
+ fi
+ fi
+ ;;
+ esac
+ continue
+ fi
local display="$test_name"
+ local top_level="$test_name"
+ if [[ "$top_level" == *"/"* ]]; then
+ top_level="${top_level%%/*}"
+ fi
if [ ${#display} -gt $max_len ]; then
display="${display:0:$((max_len - 1))}…"
fi
case "$action" in
- run) printf "\r ${MUTED}▸${NC} ${MUTED}[%2d]${NC} %-${max_len}s" "$((completed + 1))" "$display" ;;
- pass) completed=$((completed + 1))
- if [ -n "$elapsed" ]; then
- printf "\r ${SUCCESS}✓${NC} ${MUTED}[%2d]${NC} %-${max_len}s ${MUTED}%6ss${NC}" "$completed" "$display" "$elapsed"
- else
- printf "\r ${SUCCESS}✓${NC} ${MUTED}[%2d]${NC} %-${max_len}s" "$completed" "$display"
+ run)
+ if $interactive; then
+ render_progress "${current_package} ${MUTED}${display}${NC}"
fi ;;
- fail) completed=$((completed + 1))
- if [ -n "$elapsed" ]; then
- printf "\r ${ERROR}✗${NC} ${MUTED}[%2d]${NC} %-${max_len}s ${MUTED}%6ss${NC}" "$completed" "$display" "$elapsed"
+ pass)
+ if ! grep -Fq "$package_name $top_level" "$status_file"; then
+ printf '%s\t%s\n' "$package_name" "$top_level" >> "$status_file"
+ completed=$((completed + 1))
+ passed=$((passed + 1))
+ fi
+ if $interactive; then
+ render_progress "${current_package} ${SUCCESS}${display}${NC}"
+ fi ;;
+ fail)
+ if ! grep -Fq "$package_name $top_level" "$status_file"; then
+ printf '%s\t%s\n' "$package_name" "$top_level" >> "$status_file"
+ completed=$((completed + 1))
+ failed=$((failed + 1))
+ fi
+ if $interactive; then
+ render_progress "${current_package} ${ERROR}${display}${NC}"
else
- printf "\r ${ERROR}✗${NC} ${MUTED}[%2d]${NC} %-${max_len}s" "$completed" "$display"
+ if [ -n "$elapsed" ]; then
+ printf " ${ERROR}✗${NC} ${MUTED}[%2d]${NC} %-${max_len}s ${MUTED}%6ss${NC}\n" "$completed" "$display" "$elapsed"
+ else
+ printf " ${ERROR}✗${NC} ${MUTED}[%2d]${NC} %-${max_len}s\n" "$completed" "$display"
+ fi
+ fi ;;
+ skip)
+ if ! grep -Fq "$package_name $top_level" "$status_file"; then
+ printf '%s\t%s\n' "$package_name" "$top_level" >> "$status_file"
+ completed=$((completed + 1))
+ skipped=$((skipped + 1))
+ fi
+ if $interactive; then
+ render_progress "${current_package} ${ACCENT}${display}${NC}"
fi ;;
- skip) completed=$((completed + 1))
- printf "\r ${ACCENT}·${NC} ${MUTED}[%2d]${NC} %-${max_len}s ${MUTED} skip${NC}" "$completed" "$display" ;;
esac
done
- return ${PIPESTATUS[0]}
+ local test_status=${PIPESTATUS[0]}
+ clear_progress_line
+ return "$test_status"
}
SCOPE="${1:-all}"
TMPDIR_TEST=$(mktemp -d)
trap 'rm -rf "$TMPDIR_TEST"' EXIT
-HAS_GOTESTSUM=false
-command -v gotestsum &>/dev/null && HAS_GOTESTSUM=true
-
# ── Unit tests ───────────────────────────────────────────────────────
if [ "$SCOPE" = "all" ] || [ "$SCOPE" = "unit" ]; then
@@ -115,18 +256,10 @@ if [ "$SCOPE" = "all" ] || [ "$SCOPE" = "unit" ]; then
UNIT_JSON="$TMPDIR_TEST/unit.json"
- if $HAS_GOTESTSUM; then
- if ! gotestsum --format dots --jsonfile "$UNIT_JSON" -- -count=1 ./...; then
- fail "Unit tests"
- test_summary "$UNIT_JSON" "Unit Test Results"
- exit 1
- fi
- else
- if ! go test -json -count=1 ./... > "$UNIT_JSON" 2>&1; then
- fail "Unit tests"
- test_summary "$UNIT_JSON" "Unit Test Results"
- exit 1
- fi
+ if ! run_go_test_json "$UNIT_JSON" "unit" -p 1 -count=1 ./...; then
+ fail "Unit tests"
+ test_summary "$UNIT_JSON" "Unit Test Results"
+ exit 1
fi
ok "Unit tests"
test_summary "$UNIT_JSON" "Unit Test Results"
@@ -139,7 +272,7 @@ if [ "$SCOPE" = "all" ] || [ "$SCOPE" = "integration" ]; then
INTEGRATION_JSON="$TMPDIR_TEST/integration.json"
- if ! run_integration "$INTEGRATION_JSON" \
+ if ! run_go_test_json "$INTEGRATION_JSON" "integration" \
-tags integration -timeout 10m -count=1 \
-run '^Test' -skip "$SYSTEM_REGEX" ./tests/integration/; then
fail "Integration tests"
@@ -156,7 +289,7 @@ if [ "$SCOPE" = "all" ] || [ "$SCOPE" = "system" ]; then
SYSTEM_JSON="$TMPDIR_TEST/system.json"
- if ! run_integration "$SYSTEM_JSON" \
+ if ! run_go_test_json "$SYSTEM_JSON" "system" \
-tags integration -timeout 12m -count=1 \
-run "$SYSTEM_REGEX" ./tests/integration/; then
fail "System tests"
diff --git a/tests/integration/config_cli_test.go b/tests/integration/config_cli_test.go
index f953ebcb..0d71808f 100644
--- a/tests/integration/config_cli_test.go
+++ b/tests/integration/config_cli_test.go
@@ -14,8 +14,7 @@ import (
// TestConfigCLI_Init tests `pinchtab config init`
func TestConfigCLI_Init(t *testing.T) {
tmpDir := t.TempDir()
- // config init writes to userConfigDir() which is $HOME/.pinchtab on macOS (legacy path)
- // or ~/Library/Application Support/pinchtab (new path). Create the legacy dir so it's used.
+ // Create the legacy dir so config.DefaultConfigPath() resolves there.
legacyDir := filepath.Join(tmpDir, ".pinchtab")
if err := os.MkdirAll(legacyDir, 0755); err != nil {
t.Fatal(err)
diff --git a/tests/integration/idpi_test.go b/tests/integration/idpi_test.go
index 062015f2..21790c85 100644
--- a/tests/integration/idpi_test.go
+++ b/tests/integration/idpi_test.go
@@ -5,9 +5,9 @@ package integration
// IDPI integration tests — indirect prompt injection defence on /find and /pdf.
//
// Each test group spins up an isolated pinchtab server configured with specific
-// IDPI settings via testutil.NewTestServer. Headed mode (Headless: false) is
-// intentional: the browser is visible so the effect of each defence can be
-// observed during development and code review.
+// IDPI settings via testutil.NewTestServer. Tests run headless by default to
+// keep CI and local runs quiet; set PINCHTAB_TEST_HEADED=1 when you explicitly
+// want a visible browser for debugging.
//
// Test naming follows the pattern:
//
@@ -44,8 +44,7 @@ func idpiCfg(enabled, scan, strict bool, custom ...string) appconfig.IDPIConfig
// newIDPIServer builds a ServerConfig for IDPI integration tests and starts a
// server using testutil.NewTestServer. Cleanup is registered automatically via
-// t.Cleanup. Headed mode is always active because the user wants to monitor
-// test runs in a visible browser.
+// t.Cleanup. Visible Chrome is opt-in via PINCHTAB_TEST_HEADED=1.
func newIDPIServer(t *testing.T, cfg appconfig.IDPIConfig) *testutil.Client {
t.Helper()
port, err := testutil.GetFreePort()
@@ -54,7 +53,7 @@ func newIDPIServer(t *testing.T, cfg appconfig.IDPIConfig) *testutil.Client {
}
sc := testutil.DefaultConfig()
sc.Port = port
- sc.Headless = false // headed mode: visible Chrome for development monitoring
+ sc.Headless = !testutil.IntegrationHeaded()
sc.IDPI = cfg
srv := testutil.NewTestServer(t, sc)
return testutil.NewClient(srv.URL)
diff --git a/tests/release/goreleaser_test.go b/tests/release/goreleaser_test.go
new file mode 100644
index 00000000..be41f70b
--- /dev/null
+++ b/tests/release/goreleaser_test.go
@@ -0,0 +1,143 @@
+package release
+
+import (
+ "os"
+ "path/filepath"
+ "slices"
+ "testing"
+
+ "gopkg.in/yaml.v3"
+)
+
+type goReleaserConfig struct {
+ Builds []struct {
+ Main string `yaml:"main"`
+ GOOS []string `yaml:"goos"`
+ GOARCH []string `yaml:"goarch"`
+ } `yaml:"builds"`
+ Archives []struct {
+ Format string `yaml:"format"`
+ NameTemplate string `yaml:"name_template"`
+ } `yaml:"archives"`
+}
+
+func TestGoReleaserBuildMatrix(t *testing.T) {
+ cfg := loadGoReleaserConfig(t)
+
+ build, ok := findPinchTabBuild(cfg)
+ if !ok {
+ t.Fatal("missing build config for ./cmd/pinchtab in .goreleaser.yml")
+ }
+
+ wantOS := []string{"darwin", "linux", "windows"}
+ wantArch := []string{"amd64", "arm64"}
+
+ gotOS := slices.Clone(build.GOOS)
+ gotArch := slices.Clone(build.GOARCH)
+ slices.Sort(gotOS)
+ slices.Sort(gotArch)
+
+ if !slices.Equal(gotOS, wantOS) {
+ t.Fatalf("unexpected goos matrix: got %v want %v", gotOS, wantOS)
+ }
+ if !slices.Equal(gotArch, wantArch) {
+ t.Fatalf("unexpected goarch matrix: got %v want %v", gotArch, wantArch)
+ }
+
+ total := len(build.GOOS) * len(build.GOARCH)
+ if total != 6 {
+ t.Fatalf("unexpected binary count: got %d want 6", total)
+ }
+}
+
+func TestGoReleaserBinaryNaming(t *testing.T) {
+ cfg := loadGoReleaserConfig(t)
+
+ build, ok := findPinchTabBuild(cfg)
+ if !ok {
+ t.Fatal("missing build config for ./cmd/pinchtab in .goreleaser.yml")
+ }
+
+ archive, ok := findBinaryArchive(cfg)
+ if !ok {
+ t.Fatal("missing binary archive config in .goreleaser.yml")
+ }
+
+ if archive.NameTemplate != "pinchtab-{{ .Os }}-{{ .Arch }}" {
+ t.Fatalf("unexpected binary name template: got %q", archive.NameTemplate)
+ }
+
+ var got []string
+ for _, goos := range build.GOOS {
+ for _, goarch := range build.GOARCH {
+ name := "pinchtab-" + goos + "-" + goarch
+ if goos == "windows" {
+ name += ".exe"
+ }
+ got = append(got, name)
+ }
+ }
+ slices.Sort(got)
+
+ want := []string{
+ "pinchtab-darwin-amd64",
+ "pinchtab-darwin-arm64",
+ "pinchtab-linux-amd64",
+ "pinchtab-linux-arm64",
+ "pinchtab-windows-amd64.exe",
+ "pinchtab-windows-arm64.exe",
+ }
+
+ if !slices.Equal(got, want) {
+ t.Fatalf("unexpected artifact names: got %v want %v", got, want)
+ }
+}
+
+func loadGoReleaserConfig(t *testing.T) goReleaserConfig {
+ t.Helper()
+
+ configPath := filepath.Join("..", "..", ".goreleaser.yml")
+ data, err := os.ReadFile(configPath)
+ if err != nil {
+ t.Fatalf("failed to read %s: %v", configPath, err)
+ }
+
+ var cfg goReleaserConfig
+ if err := yaml.Unmarshal(data, &cfg); err != nil {
+ t.Fatalf("failed to parse %s: %v", configPath, err)
+ }
+
+ return cfg
+}
+
+func findPinchTabBuild(cfg goReleaserConfig) (struct {
+ Main string "yaml:\"main\""
+ GOOS []string "yaml:\"goos\""
+ GOARCH []string "yaml:\"goarch\""
+}, bool) {
+ for _, build := range cfg.Builds {
+ if build.Main == "./cmd/pinchtab" {
+ return build, true
+ }
+ }
+ return struct {
+ Main string "yaml:\"main\""
+ GOOS []string "yaml:\"goos\""
+ GOARCH []string "yaml:\"goarch\""
+ }{}, false
+}
+
+func findBinaryArchive(cfg goReleaserConfig) (struct {
+ Format string "yaml:\"format\""
+ NameTemplate string "yaml:\"name_template\""
+}, bool) {
+ for _, archive := range cfg.Archives {
+ if archive.Format == "binary" {
+ return archive, true
+ }
+ }
+ return struct {
+ Format string "yaml:\"format\""
+ NameTemplate string "yaml:\"name_template\""
+ }{}, false
+}
diff --git a/tests/testutil/chrome_mode.go b/tests/testutil/chrome_mode.go
new file mode 100644
index 00000000..7256a59e
--- /dev/null
+++ b/tests/testutil/chrome_mode.go
@@ -0,0 +1,18 @@
+package testutil
+
+import (
+ "os"
+ "strings"
+)
+
+// IntegrationHeaded reports whether integration tests should launch visible
+// Chrome windows. Default is false to avoid desktop crash/restore dialogs
+// during automated runs. Set PINCHTAB_TEST_HEADED=1 to opt in locally.
+func IntegrationHeaded() bool {
+ switch strings.ToLower(strings.TrimSpace(os.Getenv("PINCHTAB_TEST_HEADED"))) {
+ case "1", "true", "yes", "on":
+ return true
+ default:
+ return false
+ }
+}
diff --git a/tests/testutil/chrome_mode_test.go b/tests/testutil/chrome_mode_test.go
new file mode 100644
index 00000000..90d9a1be
--- /dev/null
+++ b/tests/testutil/chrome_mode_test.go
@@ -0,0 +1,22 @@
+package testutil
+
+import "testing"
+
+func TestIntegrationHeaded(t *testing.T) {
+ t.Setenv("PINCHTAB_TEST_HEADED", "")
+ if IntegrationHeaded() {
+ t.Fatal("expected default IntegrationHeaded() to be false")
+ }
+
+ for _, value := range []string{"1", "true", "TRUE", "yes", "on"} {
+ t.Setenv("PINCHTAB_TEST_HEADED", value)
+ if !IntegrationHeaded() {
+ t.Fatalf("expected IntegrationHeaded() true for %q", value)
+ }
+ }
+
+ t.Setenv("PINCHTAB_TEST_HEADED", "0")
+ if IntegrationHeaded() {
+ t.Fatal("expected IntegrationHeaded() false for 0")
+ }
+}